opencode-supertask 0.1.41 → 0.2.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 (97) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +66 -39
  3. package/README.zh-CN.md +66 -39
  4. package/dist/cli/chunk-3PIYMBV3.js +45 -0
  5. package/dist/cli/chunk-3PIYMBV3.js.map +1 -0
  6. package/dist/cli/chunk-4FK5KE6G.js +111 -0
  7. package/dist/cli/chunk-4FK5KE6G.js.map +1 -0
  8. package/dist/cli/chunk-5VKFECHP.js +412 -0
  9. package/dist/cli/chunk-5VKFECHP.js.map +1 -0
  10. package/dist/cli/chunk-AZM76ISG.js +143 -0
  11. package/dist/cli/chunk-AZM76ISG.js.map +1 -0
  12. package/dist/cli/chunk-CMEP6IB4.js +9379 -0
  13. package/dist/cli/chunk-CMEP6IB4.js.map +1 -0
  14. package/dist/cli/chunk-DF56RPNL.js +65 -0
  15. package/dist/cli/chunk-DF56RPNL.js.map +1 -0
  16. package/dist/cli/chunk-DIJEKFBV.js +486 -0
  17. package/dist/cli/chunk-DIJEKFBV.js.map +1 -0
  18. package/dist/cli/chunk-DYXFSX5J.js +28 -0
  19. package/dist/cli/chunk-DYXFSX5J.js.map +1 -0
  20. package/dist/cli/chunk-EQWICVCJ.js +1701 -0
  21. package/dist/cli/chunk-EQWICVCJ.js.map +1 -0
  22. package/dist/cli/chunk-GHXFMJTS.js +42 -0
  23. package/dist/cli/chunk-GHXFMJTS.js.map +1 -0
  24. package/dist/cli/chunk-IYYBJHZF.js +28 -0
  25. package/dist/cli/chunk-IYYBJHZF.js.map +1 -0
  26. package/dist/cli/chunk-J34FWHQU.js +376 -0
  27. package/dist/cli/chunk-J34FWHQU.js.map +1 -0
  28. package/dist/cli/chunk-LX5CBJLP.js +121 -0
  29. package/dist/cli/chunk-LX5CBJLP.js.map +1 -0
  30. package/dist/cli/chunk-MVQ2XONT.js +139 -0
  31. package/dist/cli/chunk-MVQ2XONT.js.map +1 -0
  32. package/dist/cli/chunk-NCT3ETTK.js +1332 -0
  33. package/dist/cli/chunk-NCT3ETTK.js.map +1 -0
  34. package/dist/cli/chunk-YB7MYTE5.js +34 -0
  35. package/dist/cli/chunk-YB7MYTE5.js.map +1 -0
  36. package/dist/cli/chunk-YGELD2E5.js +5464 -0
  37. package/dist/cli/chunk-YGELD2E5.js.map +1 -0
  38. package/dist/cli/chunk-ZBH7YWXF.js +314 -0
  39. package/dist/cli/chunk-ZBH7YWXF.js.map +1 -0
  40. package/dist/cli/config-ED56ZLHY.js +20 -0
  41. package/dist/cli/config-ED56ZLHY.js.map +1 -0
  42. package/dist/cli/database-maintenance.service-F3IZU52F.js +16 -0
  43. package/dist/cli/database-maintenance.service-F3IZU52F.js.map +1 -0
  44. package/dist/cli/database-output-GH7F6X6D.js +165 -0
  45. package/dist/cli/database-output-GH7F6X6D.js.map +1 -0
  46. package/dist/cli/db-H7GIFWS2.js +26 -0
  47. package/dist/cli/db-H7GIFWS2.js.map +1 -0
  48. package/dist/cli/doctor-smoke-QXHF7UNN.js +150 -0
  49. package/dist/cli/doctor-smoke-QXHF7UNN.js.map +1 -0
  50. package/dist/cli/duration-Q3UMLO6F.js +10 -0
  51. package/dist/cli/duration-Q3UMLO6F.js.map +1 -0
  52. package/dist/cli/gateway-BYLLK72W.js +1738 -0
  53. package/dist/cli/gateway-BYLLK72W.js.map +1 -0
  54. package/dist/cli/gateway-wake-U4HTV56Q.js +14 -0
  55. package/dist/cli/gateway-wake-U4HTV56Q.js.map +1 -0
  56. package/dist/cli/index.js +626 -26583
  57. package/dist/cli/index.js.map +1 -1
  58. package/dist/cli/job-templates-RPQJ4XXW.js +21 -0
  59. package/dist/cli/job-templates-RPQJ4XXW.js.map +1 -0
  60. package/dist/cli/logs-QD2N62KK.js +316 -0
  61. package/dist/cli/logs-QD2N62KK.js.map +1 -0
  62. package/dist/cli/output-2INTEUFQ.js +19 -0
  63. package/dist/cli/output-2INTEUFQ.js.map +1 -0
  64. package/dist/cli/pm2-WY644BUO.js +49 -0
  65. package/dist/cli/pm2-WY644BUO.js.map +1 -0
  66. package/dist/cli/task-run.service-QMDINJKG.js +15 -0
  67. package/dist/cli/task-run.service-QMDINJKG.js.map +1 -0
  68. package/dist/cli/task-template.service-SZBKGLCB.js +12 -0
  69. package/dist/cli/task-template.service-SZBKGLCB.js.map +1 -0
  70. package/dist/cli/task.service-ZVDJ6VSQ.js +19 -0
  71. package/dist/cli/task.service-ZVDJ6VSQ.js.map +1 -0
  72. package/dist/cli/update-FYD546I2.js +2058 -0
  73. package/dist/cli/update-FYD546I2.js.map +1 -0
  74. package/dist/cli/web-J3FJ23FE.js +9833 -0
  75. package/dist/cli/web-J3FJ23FE.js.map +1 -0
  76. package/dist/daemon/gateway-diagnostic-runner.js +280 -238
  77. package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
  78. package/dist/gateway/index.d.ts +82 -1
  79. package/dist/gateway/index.js +9695 -2661
  80. package/dist/gateway/index.js.map +1 -1
  81. package/dist/plugin/supertask.d.ts +157 -1
  82. package/dist/plugin/supertask.js +5056 -1550
  83. package/dist/plugin/supertask.js.map +1 -1
  84. package/dist/pm2-cli-CEDhULjk.d.ts +40 -0
  85. package/dist/web/index.d.ts +36 -34
  86. package/dist/web/index.js +10283 -3908
  87. package/dist/web/index.js.map +1 -1
  88. package/dist/worker/index.d.ts +5 -0
  89. package/dist/worker/index.js +1989 -331
  90. package/dist/worker/index.js.map +1 -1
  91. package/dist/worker/launcher.d.ts +46 -1
  92. package/dist/worker/launcher.js +218 -68
  93. package/dist/worker/launcher.js.map +1 -1
  94. package/drizzle/0009_little_weapon_omega.sql +7 -0
  95. package/drizzle/meta/0009_snapshot.json +681 -0
  96. package/drizzle/meta/_journal.json +7 -0
  97. package/package.json +4 -4
@@ -5188,7 +5188,25 @@ var tasks = sqliteTable("tasks", {
5188
5188
  index("tasks_batch_status_idx").on(table.batchId, table.status),
5189
5189
  index("tasks_template_status_idx").on(table.templateId, table.status),
5190
5190
  index("tasks_depends_on_status_idx").on(table.dependsOn, table.status),
5191
- index("tasks_cleanup_idx").on(table.finishedAt, table.id, table.status)
5191
+ index("tasks_cleanup_idx").on(table.finishedAt, table.id, table.status),
5192
+ index("tasks_dispatch_order_idx").on(
5193
+ table.status,
5194
+ sql`${table.urgency} DESC`,
5195
+ sql`${table.importance} DESC`,
5196
+ table.createdAt,
5197
+ table.id
5198
+ ),
5199
+ index("tasks_created_id_idx").on(table.createdAt, table.id),
5200
+ index("tasks_cwd_created_id_idx").on(table.cwd, table.createdAt, table.id),
5201
+ index("tasks_cwd_status_created_idx").on(
5202
+ table.cwd,
5203
+ table.status,
5204
+ table.createdAt,
5205
+ table.finishedAt,
5206
+ table.startedAt,
5207
+ table.id
5208
+ ),
5209
+ index("tasks_status_batch_idx").on(table.status, table.batchId)
5192
5210
  ]);
5193
5211
  var TASK_CATEGORIES = [
5194
5212
  "translate",
@@ -5216,7 +5234,9 @@ var taskRuns = sqliteTable("task_runs", {
5216
5234
  launchProtocol: text("launch_protocol")
5217
5235
  }, (table) => [
5218
5236
  index("task_runs_task_started_idx").on(table.taskId, table.startedAt, table.id),
5219
- index("task_runs_status_heartbeat_idx").on(table.status, table.heartbeatAt)
5237
+ index("task_runs_status_heartbeat_idx").on(table.status, table.heartbeatAt),
5238
+ index("task_runs_started_id_idx").on(table.startedAt, table.id),
5239
+ index("task_runs_status_task_idx").on(table.status, table.taskId)
5220
5240
  ]);
5221
5241
  var taskTemplates = sqliteTable("task_templates", {
5222
5242
  id: integer("id").primaryKey({ autoIncrement: true }),
@@ -5260,6 +5280,7 @@ import { join, dirname } from "path";
5260
5280
  import { fileURLToPath } from "url";
5261
5281
  var DEFAULT_DB_PATH = join(homedir(), ".local/share/opencode/tasks.db");
5262
5282
  var DB_FILE_PATH = process.env.SUPERTASK_DB_PATH || DEFAULT_DB_PATH;
5283
+ var EXPECTED_SCHEMA_USER_VERSION = 10;
5263
5284
  var _sqlite = null;
5264
5285
  var _db = null;
5265
5286
  var _migrationRan = false;
@@ -5294,7 +5315,32 @@ function ensureGatewayLock(sqliteDb) {
5294
5315
  sqliteDb.exec("ALTER TABLE gateway_lock ADD COLUMN version TEXT;");
5295
5316
  }
5296
5317
  }
5318
+ function getAppliedMigrationCount(sqliteDb) {
5319
+ const table = sqliteDb.query(
5320
+ "SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = '__drizzle_migrations'"
5321
+ ).get();
5322
+ if (!table) return null;
5323
+ const row = sqliteDb.query(
5324
+ "SELECT count(*) AS count FROM __drizzle_migrations"
5325
+ ).get();
5326
+ return row ? Number(row.count) : 0;
5327
+ }
5328
+ var REQUIRED_CORE_TABLES = ["gateway_lock", "tasks", "task_runs", "task_templates"];
5329
+ function hasRequiredCoreTables(sqliteDb) {
5330
+ const row = sqliteDb.query(
5331
+ "SELECT count(*) AS count FROM sqlite_master WHERE type = 'table' AND name IN ('gateway_lock', 'tasks', 'task_runs', 'task_templates')"
5332
+ ).get();
5333
+ return Number(row?.count ?? 0) === REQUIRED_CORE_TABLES.length;
5334
+ }
5335
+ function readSchemaUserVersion(sqliteDb) {
5336
+ const row = sqliteDb.query("PRAGMA user_version;").get();
5337
+ return Number(row?.user_version ?? 0);
5338
+ }
5297
5339
  function migrateSqliteDatabase(sqliteDb) {
5340
+ const currentUserVersion = readSchemaUserVersion(sqliteDb);
5341
+ if (currentUserVersion === EXPECTED_SCHEMA_USER_VERSION && hasRequiredCoreTables(sqliteDb)) {
5342
+ return drizzle(sqliteDb, { schema: schema_exports });
5343
+ }
5298
5344
  ensureGatewayLock(sqliteDb);
5299
5345
  const drizzleDb = drizzle(sqliteDb, { schema: schema_exports });
5300
5346
  migrate(drizzleDb, { migrationsFolder: getMigrationsFolder() });
@@ -5303,19 +5349,50 @@ function migrateSqliteDatabase(sqliteDb) {
5303
5349
  if (violations.length > 0) {
5304
5350
  throw new Error(`\u68C0\u6D4B\u5230 ${violations.length} \u6761\u5B64\u7ACB\u5173\u8054\u8BB0\u5F55\uFF0C\u8BF7\u5148\u4FEE\u590D\u6570\u636E\u518D\u542F\u52A8`);
5305
5351
  }
5352
+ const afterCount = getAppliedMigrationCount(sqliteDb);
5353
+ if (afterCount === EXPECTED_SCHEMA_USER_VERSION && hasRequiredCoreTables(sqliteDb) && currentUserVersion <= EXPECTED_SCHEMA_USER_VERSION) {
5354
+ sqliteDb.exec(`PRAGMA user_version = ${EXPECTED_SCHEMA_USER_VERSION};`);
5355
+ }
5306
5356
  return drizzleDb;
5307
5357
  }
5358
+ var CONCURRENT_MIGRATION_PATTERN = /already exists|duplicate column name/i;
5359
+ function migrateWithConcurrentOpenRetry(sqliteDb) {
5360
+ for (let attempt = 1; ; attempt += 1) {
5361
+ try {
5362
+ return migrateSqliteDatabase(sqliteDb);
5363
+ } catch (error) {
5364
+ const message = error instanceof Error ? `${error.message} ${String(error.cause ?? "")}` : String(error);
5365
+ if (attempt >= 5 || !CONCURRENT_MIGRATION_PATTERN.test(message)) throw error;
5366
+ Bun.sleepSync(50 * attempt);
5367
+ }
5368
+ }
5369
+ }
5370
+ function enableWal(sqliteDb) {
5371
+ for (let attempt = 1; ; attempt += 1) {
5372
+ try {
5373
+ sqliteDb.exec("PRAGMA journal_mode = WAL;");
5374
+ return;
5375
+ } catch (error) {
5376
+ if (attempt >= 20 || !/database is locked/i.test(error instanceof Error ? error.message : String(error))) throw error;
5377
+ Bun.sleepSync(25 * attempt);
5378
+ }
5379
+ }
5380
+ }
5308
5381
  function initDb() {
5309
5382
  const dataDir = dirname(DB_FILE_PATH);
5310
5383
  if (!existsSync(dataDir)) {
5311
5384
  mkdirSync(dataDir, { recursive: true });
5312
5385
  }
5313
5386
  _sqlite = new Database2(DB_FILE_PATH);
5314
- _sqlite.exec("PRAGMA journal_mode = WAL;");
5315
5387
  _sqlite.exec("PRAGMA busy_timeout = 5000;");
5388
+ enableWal(_sqlite);
5389
+ _sqlite.exec("PRAGMA synchronous = NORMAL;");
5390
+ _sqlite.exec("PRAGMA temp_store = MEMORY;");
5391
+ _sqlite.exec("PRAGMA cache_size = -32000;");
5392
+ _sqlite.exec("PRAGMA foreign_keys = ON;");
5316
5393
  if (!_migrationRan) {
5317
5394
  try {
5318
- _db = migrateSqliteDatabase(_sqlite);
5395
+ _db = migrateWithConcurrentOpenRetry(_sqlite);
5319
5396
  _migrationRan = true;
5320
5397
  } catch (err) {
5321
5398
  const msg = err instanceof Error ? err.message : String(err);
@@ -5423,6 +5500,26 @@ var TaskDeletionConflictError = class extends Error {
5423
5500
  this.name = "TaskDeletionConflictError";
5424
5501
  }
5425
5502
  };
5503
+ function validateIntegerField(name, value, min, max) {
5504
+ if (value === void 0 || value === null) return;
5505
+ if (!Number.isInteger(value) || value < min || value > max) {
5506
+ throw new Error(`${name} \u5FC5\u987B\u662F ${min} \u5230 ${max} \u4E4B\u95F4\u7684\u6574\u6570`);
5507
+ }
5508
+ }
5509
+ function validateCommonTaskFields(data) {
5510
+ if (!data.name.trim()) throw new Error("name \u4E0D\u80FD\u4E3A\u7A7A");
5511
+ if (!data.agent.trim()) throw new Error("agent \u4E0D\u80FD\u4E3A\u7A7A");
5512
+ if (!data.prompt.trim()) throw new Error("prompt \u4E0D\u80FD\u4E3A\u7A7A");
5513
+ validateTaskWorkingDirectory(data.cwd);
5514
+ validateIntegerField("importance", data.importance, 1, 5);
5515
+ validateIntegerField("urgency", data.urgency, 1, 5);
5516
+ validateIntegerField("maxRetries", data.maxRetries, 0, 1e3);
5517
+ validateIntegerField("retryBackoffMs", data.retryBackoffMs, 0, 864e5);
5518
+ validateIntegerField("timeoutMs", data.timeoutMs, 1e3, 6048e5);
5519
+ }
5520
+ function escapeLikePattern(value) {
5521
+ return value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
5522
+ }
5426
5523
  function hasNoExecutableDependents() {
5427
5524
  return sql`NOT EXISTS (
5428
5525
  SELECT 1 FROM tasks AS dependent_task
@@ -5468,6 +5565,289 @@ function blockedDependentsOf(prerequisiteId) {
5468
5565
  SELECT id FROM blocked_task
5469
5566
  )`;
5470
5567
  }
5568
+ function legacyCwdCondition() {
5569
+ return sql`(${tasks2.cwd} IS NULL OR trim(${tasks2.cwd}) = '')`;
5570
+ }
5571
+ var LEADING_BATCH_WHITESPACE_RANGES = [
5572
+ [" ", ""],
5573
+ // U+0009..U+000D (\t \n \v \f \r)
5574
+ [" ", "!"],
5575
+ // U+0020
5576
+ ["\xA0", "\xA1"],
5577
+ // U+00A0
5578
+ ["\u1680", "\u1681"],
5579
+ // U+1680
5580
+ ["\u2000", "\u200B"],
5581
+ // U+2000..U+200A
5582
+ ["\u2028", "\u202A"],
5583
+ // U+2028..U+2029
5584
+ ["\u202F", "\u2030"],
5585
+ // U+202F
5586
+ ["\u205F", "\u2060"],
5587
+ // U+205F
5588
+ ["\u3000", "\u3001"],
5589
+ // U+3000
5590
+ ["\uFEFF", "\uFF00"]
5591
+ // U+FEFF
5592
+ ];
5593
+ var sqliteUtf8EncodingCache = /* @__PURE__ */ new WeakMap();
5594
+ function isUtf8SqliteDatabase(sqlite2) {
5595
+ const cached = sqliteUtf8EncodingCache.get(sqlite2);
5596
+ if (cached !== void 0) return cached;
5597
+ const row = sqlite2.query("PRAGMA encoding").get();
5598
+ const isUtf8 = (row?.encoding ?? "UTF-8").toUpperCase() === "UTF-8";
5599
+ sqliteUtf8EncodingCache.set(sqlite2, isUtf8);
5600
+ return isUtf8;
5601
+ }
5602
+ function batchIdMatchCondition(normalizedBatchId) {
5603
+ if (!isUtf8SqliteDatabase(getSqlite())) {
5604
+ return sql`${tasks2.id} IN (
5605
+ SELECT batch_exact.id FROM tasks AS batch_exact
5606
+ WHERE batch_exact.batch_id = ${normalizedBatchId}
5607
+ UNION ALL
5608
+ SELECT batch_legacy.id FROM tasks AS batch_legacy
5609
+ WHERE batch_legacy.batch_id IS NOT NULL
5610
+ AND batch_legacy.batch_id <> ${normalizedBatchId}
5611
+ AND length(batch_legacy.batch_id) > length(${normalizedBatchId})
5612
+ AND trim(batch_legacy.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}
5613
+ )`;
5614
+ }
5615
+ const trailingAsciiUpper = `${normalizedBatchId}!`;
5616
+ const trailingUnicodeLower = `${normalizedBatchId}\xA0`;
5617
+ const trailingUnicodeUpper = `${normalizedBatchId}\uFF00`;
5618
+ const branches = [
5619
+ sql`SELECT batch_exact.id FROM tasks AS batch_exact WHERE batch_exact.batch_id = ${normalizedBatchId}`,
5620
+ sql`SELECT batch_trail_ascii.id FROM tasks AS batch_trail_ascii
5621
+ WHERE batch_trail_ascii.batch_id > ${normalizedBatchId}
5622
+ AND batch_trail_ascii.batch_id < ${trailingAsciiUpper}
5623
+ AND trim(batch_trail_ascii.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}`,
5624
+ sql`SELECT batch_trail_uni.id FROM tasks AS batch_trail_uni
5625
+ WHERE batch_trail_uni.batch_id >= ${trailingUnicodeLower}
5626
+ AND batch_trail_uni.batch_id < ${trailingUnicodeUpper}
5627
+ AND trim(batch_trail_uni.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}`
5628
+ ];
5629
+ for (const [lower, upper] of LEADING_BATCH_WHITESPACE_RANGES) {
5630
+ branches.push(sql`SELECT batch_lead.id FROM tasks AS batch_lead
5631
+ WHERE batch_lead.batch_id >= ${lower}
5632
+ AND batch_lead.batch_id < ${upper}
5633
+ AND trim(batch_lead.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}`);
5634
+ }
5635
+ return sql`${tasks2.id} IN (${sql.join(branches, sql` UNION ALL `)})`;
5636
+ }
5637
+ function activeExecutionCondition() {
5638
+ return sql`${tasks2.id} IN (
5639
+ SELECT active_task.id FROM tasks AS active_task
5640
+ WHERE active_task.status = 'running'
5641
+ UNION
5642
+ SELECT active_run.task_id FROM task_runs AS active_run
5643
+ WHERE active_run.status = 'running'
5644
+ )`;
5645
+ }
5646
+ function emptyDashboardStats() {
5647
+ return {
5648
+ total: 0,
5649
+ pending: 0,
5650
+ running: 0,
5651
+ activeExecution: 0,
5652
+ done: 0,
5653
+ failed: 0,
5654
+ dead_letter: 0,
5655
+ cancelled: 0
5656
+ };
5657
+ }
5658
+ function buildNextCandidateSql(hasCwdScope) {
5659
+ const cwdClause = hasCwdScope ? "AND t.cwd = ?" : "";
5660
+ return `
5661
+ WITH
5662
+ active_run_tasks(task_id) AS MATERIALIZED (
5663
+ SELECT DISTINCT task_id
5664
+ FROM task_runs
5665
+ WHERE status = 'running'
5666
+ ),
5667
+ active_batches(batch_id) AS MATERIALIZED (
5668
+ SELECT trim(batch_id, ?) AS batch_id
5669
+ FROM tasks
5670
+ WHERE status = 'running'
5671
+ AND batch_id IS NOT NULL
5672
+ AND trim(batch_id, ?) <> ''
5673
+ UNION
5674
+ SELECT trim(t.batch_id, ?) AS batch_id
5675
+ FROM tasks AS t
5676
+ INNER JOIN active_run_tasks AS art ON t.id = art.task_id
5677
+ WHERE t.batch_id IS NOT NULL
5678
+ AND trim(t.batch_id, ?) <> ''
5679
+ UNION
5680
+ SELECT value AS batch_id FROM json_each(?)
5681
+ )
5682
+ SELECT id FROM (
5683
+ SELECT id, urgency, importance, created_at FROM (
5684
+ SELECT t.id, t.urgency, t.importance, t.created_at
5685
+ FROM tasks AS t
5686
+ WHERE t.status = 'pending'
5687
+ AND COALESCE(t.retry_after, 0) <= ?
5688
+ ${cwdClause}
5689
+ AND (
5690
+ t.depends_on IS NULL
5691
+ OR EXISTS (
5692
+ SELECT 1 FROM tasks AS dep
5693
+ WHERE dep.id = t.depends_on
5694
+ AND dep.status = 'done'
5695
+ AND dep.cwd IS t.cwd
5696
+ )
5697
+ )
5698
+ AND NOT EXISTS (
5699
+ SELECT 1 FROM active_run_tasks AS art
5700
+ WHERE art.task_id = t.id
5701
+ )
5702
+ AND (
5703
+ t.batch_id IS NULL
5704
+ OR trim(t.batch_id, ?) = ''
5705
+ OR NOT EXISTS (
5706
+ SELECT 1 FROM active_batches AS ab
5707
+ WHERE ab.batch_id = trim(t.batch_id, ?)
5708
+ )
5709
+ )
5710
+ ORDER BY t.urgency DESC, t.importance DESC, t.created_at ASC, t.id ASC
5711
+ LIMIT 1
5712
+ )
5713
+ UNION ALL
5714
+ SELECT id, urgency, importance, created_at FROM (
5715
+ SELECT t.id, t.urgency, t.importance, t.created_at
5716
+ FROM tasks AS t
5717
+ WHERE t.status = 'failed'
5718
+ AND t.retry_count <= t.max_retries
5719
+ AND COALESCE(t.retry_after, 0) <= ?
5720
+ ${cwdClause}
5721
+ AND (
5722
+ t.depends_on IS NULL
5723
+ OR EXISTS (
5724
+ SELECT 1 FROM tasks AS dep
5725
+ WHERE dep.id = t.depends_on
5726
+ AND dep.status = 'done'
5727
+ AND dep.cwd IS t.cwd
5728
+ )
5729
+ )
5730
+ AND NOT EXISTS (
5731
+ SELECT 1 FROM active_run_tasks AS art
5732
+ WHERE art.task_id = t.id
5733
+ )
5734
+ AND (
5735
+ t.batch_id IS NULL
5736
+ OR trim(t.batch_id, ?) = ''
5737
+ OR NOT EXISTS (
5738
+ SELECT 1 FROM active_batches AS ab
5739
+ WHERE ab.batch_id = trim(t.batch_id, ?)
5740
+ )
5741
+ )
5742
+ ORDER BY t.urgency DESC, t.importance DESC, t.created_at ASC, t.id ASC
5743
+ LIMIT 1
5744
+ )
5745
+ )
5746
+ ORDER BY urgency DESC, importance DESC, created_at ASC, id ASC
5747
+ LIMIT 1
5748
+ `;
5749
+ }
5750
+ var COUNT_RUNNING_UNSCOPED_SQL = `
5751
+ SELECT
5752
+ (SELECT count(*) FROM tasks WHERE status = 'running')
5753
+ + (
5754
+ SELECT count(DISTINCT r.task_id)
5755
+ FROM task_runs AS r
5756
+ INNER JOIN tasks AS t ON t.id = r.task_id
5757
+ WHERE r.status = 'running' AND (t.status IS NULL OR t.status <> 'running')
5758
+ ) AS count
5759
+ `;
5760
+ var COUNT_RUNNING_BY_CWD_SQL = `
5761
+ SELECT
5762
+ (SELECT count(*) FROM tasks WHERE status = 'running' AND cwd = ?)
5763
+ + (
5764
+ SELECT count(DISTINCT r.task_id)
5765
+ FROM task_runs AS r
5766
+ INNER JOIN tasks AS t ON t.id = r.task_id
5767
+ WHERE r.status = 'running' AND (t.status IS NULL OR t.status <> 'running') AND t.cwd = ?
5768
+ ) AS count
5769
+ `;
5770
+ var COUNT_RUNNING_LEGACY_CWD_SQL = `
5771
+ SELECT
5772
+ (SELECT count(*) FROM tasks WHERE status = 'running' AND (cwd IS NULL OR trim(cwd) = ''))
5773
+ + (
5774
+ SELECT count(DISTINCT r.task_id)
5775
+ FROM task_runs AS r
5776
+ INNER JOIN tasks AS t ON t.id = r.task_id
5777
+ WHERE r.status = 'running'
5778
+ AND (t.status IS NULL OR t.status <> 'running')
5779
+ AND (t.cwd IS NULL OR trim(t.cwd) = '')
5780
+ ) AS count
5781
+ `;
5782
+ function buildCountRunningByBatchSql(cwdMode) {
5783
+ const taskCwdClause = cwdMode === "exact" ? "AND cwd = ?" : cwdMode === "legacy" ? "AND (cwd IS NULL OR trim(cwd) = '')" : "";
5784
+ const joinedCwdClause = cwdMode === "exact" ? "AND t.cwd = ?" : cwdMode === "legacy" ? "AND (t.cwd IS NULL OR trim(t.cwd) = '')" : "";
5785
+ return `
5786
+ SELECT
5787
+ (
5788
+ SELECT count(*)
5789
+ FROM tasks
5790
+ WHERE status = 'running'
5791
+ AND batch_id IS NOT NULL
5792
+ AND batch_id > ''
5793
+ AND trim(batch_id, ?) = ?
5794
+ ${taskCwdClause}
5795
+ )
5796
+ + (
5797
+ SELECT count(DISTINCT r.task_id)
5798
+ FROM task_runs AS r
5799
+ INNER JOIN tasks AS t ON t.id = r.task_id
5800
+ WHERE r.status = 'running'
5801
+ AND (t.status IS NULL OR t.status <> 'running')
5802
+ AND t.batch_id IS NOT NULL
5803
+ AND t.batch_id > ''
5804
+ AND trim(t.batch_id, ?) = ?
5805
+ ${joinedCwdClause}
5806
+ ) AS count
5807
+ `;
5808
+ }
5809
+ var COUNT_RUNNING_BY_BATCH_GLOBAL_SQL = buildCountRunningByBatchSql("none");
5810
+ var COUNT_RUNNING_BY_BATCH_CWD_SQL = buildCountRunningByBatchSql("exact");
5811
+ var COUNT_RUNNING_BY_BATCH_LEGACY_CWD_SQL = buildCountRunningByBatchSql("legacy");
5812
+ var DASHBOARD_OVERVIEW_BY_STATUS_SQL = `
5813
+ SELECT
5814
+ t.cwd AS project_cwd,
5815
+ t.status AS task_status,
5816
+ COUNT(*) AS status_count,
5817
+ MAX(t.created_at) AS last_created_at,
5818
+ MAX(t.id) AS last_task_id,
5819
+ SUM(CASE WHEN t.status = 'done' AND t.finished_at IS NOT NULL AND t.finished_at >= ? THEN 1 ELSE 0 END) AS done_7d,
5820
+ SUM(CASE WHEN t.status IN ('failed', 'dead_letter') AND t.finished_at IS NOT NULL AND t.finished_at >= ? THEN 1 ELSE 0 END) AS failed_7d,
5821
+ SUM(CASE WHEN t.status = 'done' AND t.started_at IS NOT NULL AND t.finished_at IS NOT NULL AND t.finished_at >= ? AND t.finished_at >= t.started_at THEN (t.finished_at - t.started_at) * 1000.0 ELSE 0 END) AS duration_sum_ms_7d,
5822
+ SUM(CASE WHEN t.status = 'done' AND t.started_at IS NOT NULL AND t.finished_at IS NOT NULL AND t.finished_at >= ? AND t.finished_at >= t.started_at THEN 1 ELSE 0 END) AS duration_count_7d,
5823
+ MIN(CASE WHEN t.status IN ('done', 'failed', 'dead_letter') AND t.finished_at IS NOT NULL AND t.finished_at >= ? THEN t.finished_at END) AS min_finished_7d
5824
+ FROM tasks AS t
5825
+ GROUP BY t.cwd, t.status
5826
+ `;
5827
+ var DASHBOARD_OVERVIEW_EXTRA_ACTIVE_RUNS_SQL = `
5828
+ SELECT
5829
+ t.cwd AS project_cwd,
5830
+ COUNT(DISTINCT r.task_id) AS extra_active
5831
+ FROM task_runs AS r
5832
+ INNER JOIN tasks AS t ON t.id = r.task_id
5833
+ WHERE r.status = 'running'
5834
+ AND (t.status IS NULL OR t.status <> 'running')
5835
+ GROUP BY t.cwd
5836
+ `;
5837
+ var dashboardOverviewCache = /* @__PURE__ */ new WeakMap();
5838
+ function readSqliteMutationStamp(sqlite2) {
5839
+ const dataVersionRow = sqlite2.query("PRAGMA data_version").get();
5840
+ const totalChangesRow = sqlite2.query("SELECT total_changes() AS changes").get();
5841
+ return {
5842
+ dataVersion: Number(dataVersionRow?.data_version ?? 0),
5843
+ totalChanges: Number(totalChangesRow?.changes ?? 0)
5844
+ };
5845
+ }
5846
+ function cloneDashboardStats(stats) {
5847
+ return { ...stats };
5848
+ }
5849
+ var NEXT_CANDIDATE_GLOBAL_SQL = buildNextCandidateSql(false);
5850
+ var NEXT_CANDIDATE_SCOPED_SQL = buildNextCandidateSql(true);
5471
5851
  var TaskService = class {
5472
5852
  static buildScopeWhere(scope) {
5473
5853
  const conditions = [];
@@ -5476,6 +5856,99 @@ var TaskService = class {
5476
5856
  }
5477
5857
  return conditions;
5478
5858
  }
5859
+ static cascadeDeadLetterDependents(tx, prerequisiteId, finishedAt) {
5860
+ tx.update(tasks2).set({
5861
+ status: "dead_letter",
5862
+ finishedAt,
5863
+ retryAfter: null,
5864
+ resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${prerequisiteId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5865
+ }).where(blockedDependentsOf(prerequisiteId)).run();
5866
+ }
5867
+ static findNextCandidateId(scope) {
5868
+ const sqlite2 = getSqlite();
5869
+ const nowMs = Date.now();
5870
+ const excludedBatchIds = [...new Set((scope.excludedBatchIds ?? []).map((batchId) => normalizeTaskBatchId(batchId)).filter((batchId) => Boolean(batchId)))];
5871
+ const excludedJson = JSON.stringify(excludedBatchIds);
5872
+ const trimChars = TASK_BATCH_TRIM_CHARACTERS;
5873
+ const row = scope.cwd !== void 0 ? sqlite2.query(NEXT_CANDIDATE_SCOPED_SQL).get(
5874
+ trimChars,
5875
+ trimChars,
5876
+ trimChars,
5877
+ trimChars,
5878
+ excludedJson,
5879
+ nowMs,
5880
+ scope.cwd,
5881
+ trimChars,
5882
+ trimChars,
5883
+ nowMs,
5884
+ scope.cwd,
5885
+ trimChars,
5886
+ trimChars
5887
+ ) : sqlite2.query(NEXT_CANDIDATE_GLOBAL_SQL).get(
5888
+ trimChars,
5889
+ trimChars,
5890
+ trimChars,
5891
+ trimChars,
5892
+ excludedJson,
5893
+ nowMs,
5894
+ trimChars,
5895
+ trimChars,
5896
+ nowMs,
5897
+ trimChars,
5898
+ trimChars
5899
+ );
5900
+ return row ? Number(row.id) : null;
5901
+ }
5902
+ static buildListConditions(options) {
5903
+ const conditions = [];
5904
+ if (options.activeExecution) {
5905
+ conditions.push(activeExecutionCondition());
5906
+ } else if (options.status) {
5907
+ conditions.push(eq(tasks2.status, options.status));
5908
+ }
5909
+ if (options.batchId !== void 0) {
5910
+ const batchId = normalizeTaskBatchId(options.batchId);
5911
+ conditions.push(batchId ? batchIdMatchCondition(batchId) : sql`0`);
5912
+ }
5913
+ if (options.category) {
5914
+ conditions.push(eq(tasks2.category, options.category));
5915
+ }
5916
+ if (options.agent) {
5917
+ conditions.push(eq(tasks2.agent, options.agent));
5918
+ }
5919
+ if (options.templateId !== void 0) {
5920
+ conditions.push(eq(tasks2.templateId, options.templateId));
5921
+ }
5922
+ if (options.legacyCwd) {
5923
+ conditions.push(legacyCwdCondition());
5924
+ } else if (options.cwd !== void 0) {
5925
+ conditions.push(eq(tasks2.cwd, options.cwd));
5926
+ }
5927
+ if (options.search !== void 0) {
5928
+ const trimmed = options.search.trim();
5929
+ if (trimmed.length > 0) {
5930
+ const escaped = `%${escapeLikePattern(trimmed)}%`;
5931
+ const idMatch = /^#?(\d+)$/.exec(trimmed);
5932
+ if (idMatch) {
5933
+ const numericId = Number(idMatch[1]);
5934
+ conditions.push(sql`(
5935
+ ${tasks2.id} = ${numericId}
5936
+ OR ${tasks2.name} LIKE ${escaped} ESCAPE '\\'
5937
+ OR ${tasks2.prompt} LIKE ${escaped} ESCAPE '\\'
5938
+ OR ${tasks2.batchId} LIKE ${escaped} ESCAPE '\\'
5939
+ )`);
5940
+ } else {
5941
+ conditions.push(sql`(
5942
+ ${tasks2.name} LIKE ${escaped} ESCAPE '\\'
5943
+ OR ${tasks2.prompt} LIKE ${escaped} ESCAPE '\\'
5944
+ OR ${tasks2.batchId} LIKE ${escaped} ESCAPE '\\'
5945
+ OR CAST(${tasks2.id} AS TEXT) LIKE ${escaped} ESCAPE '\\'
5946
+ )`);
5947
+ }
5948
+ }
5949
+ }
5950
+ return conditions;
5951
+ }
5479
5952
  static async add(data) {
5480
5953
  const normalizedData = {
5481
5954
  ...data,
@@ -5506,6 +5979,26 @@ var TaskService = class {
5506
5979
  return tx.insert(tasks2).values(normalizedData).returning().get();
5507
5980
  }, { behavior: "immediate" });
5508
5981
  }
5982
+ static async clone(id, overrides = {}, scope = {}) {
5983
+ const original = await this.getById(id, scope);
5984
+ if (!original) return null;
5985
+ return this.add({
5986
+ name: overrides.name ?? original.name,
5987
+ agent: overrides.agent ?? original.agent,
5988
+ model: overrides.model ?? original.model ?? "default",
5989
+ variant: overrides.variant === void 0 ? original.variant : overrides.variant,
5990
+ prompt: overrides.prompt ?? original.prompt,
5991
+ cwd: overrides.cwd === void 0 ? original.cwd : overrides.cwd,
5992
+ category: overrides.category ?? original.category ?? "general",
5993
+ importance: overrides.importance ?? original.importance ?? 3,
5994
+ urgency: overrides.urgency ?? original.urgency ?? 3,
5995
+ batchId: overrides.batchId === void 0 ? original.batchId : overrides.batchId,
5996
+ dependsOn: overrides.dependsOn === void 0 ? null : overrides.dependsOn,
5997
+ maxRetries: overrides.maxRetries ?? original.maxRetries ?? 3,
5998
+ retryBackoffMs: overrides.retryBackoffMs ?? original.retryBackoffMs ?? 3e4,
5999
+ timeoutMs: overrides.timeoutMs === void 0 ? original.timeoutMs : overrides.timeoutMs
6000
+ });
6001
+ }
5509
6002
  static async update(id, data, scope = {}) {
5510
6003
  if (Object.keys(data).length === 0) throw new Error("\u81F3\u5C11\u63D0\u4F9B\u4E00\u4E2A\u8981\u4FEE\u6539\u7684\u5B57\u6BB5");
5511
6004
  const normalizedData = {
@@ -5537,154 +6030,88 @@ var TaskService = class {
5537
6030
  dependsOn: task.dependsOn
5538
6031
  });
5539
6032
  const maxRetries = normalizedData.maxRetries ?? task.maxRetries ?? 3;
5540
- const exhausted = task.status === "failed" && (task.retryCount ?? 0) > maxRetries;
6033
+ const exhausted = (task.status === "failed" || task.status === "pending") && (task.retryCount ?? 0) > maxRetries;
6034
+ const finishedAt = exhausted ? /* @__PURE__ */ new Date() : void 0;
5541
6035
  const updated = tx.update(tasks2).set({
5542
6036
  ...normalizedData,
5543
6037
  ...exhausted ? {
5544
6038
  status: "dead_letter",
6039
+ finishedAt,
5545
6040
  retryAfter: null
5546
6041
  } : {}
5547
6042
  }).where(eq(tasks2.id, id)).returning().get() ?? null;
5548
- if (exhausted && updated) {
5549
- const finishedAt = /* @__PURE__ */ new Date();
5550
- tx.update(tasks2).set({
5551
- status: "dead_letter",
5552
- finishedAt,
5553
- retryAfter: null,
5554
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5555
- }).where(blockedDependentsOf(id)).run();
6043
+ if (exhausted && updated && finishedAt) {
6044
+ this.cascadeDeadLetterDependents(tx, id, finishedAt);
5556
6045
  }
5557
6046
  return updated;
5558
6047
  }, { behavior: "immediate" });
5559
6048
  }
5560
6049
  static validateNewTask(data) {
5561
- if (!data.name.trim()) throw new Error("name \u4E0D\u80FD\u4E3A\u7A7A");
5562
- if (!data.agent.trim()) throw new Error("agent \u4E0D\u80FD\u4E3A\u7A7A");
5563
- if (!data.prompt.trim()) throw new Error("prompt \u4E0D\u80FD\u4E3A\u7A7A");
5564
- validateTaskWorkingDirectory(data.cwd);
5565
- this.validateInteger("importance", data.importance, 1, 5);
5566
- this.validateInteger("urgency", data.urgency, 1, 5);
5567
- this.validateInteger("maxRetries", data.maxRetries, 0, 1e3);
5568
- this.validateInteger("retryBackoffMs", data.retryBackoffMs, 0, 864e5);
5569
- this.validateInteger("timeoutMs", data.timeoutMs, 1e3, 6048e5);
5570
- this.validateInteger("dependsOn", data.dependsOn, 1, Number.MAX_SAFE_INTEGER);
5571
- }
5572
- static validateInteger(name, value, min, max) {
5573
- if (value === void 0 || value === null) return;
5574
- if (!Number.isInteger(value) || value < min || value > max) {
5575
- throw new Error(`${name} \u5FC5\u987B\u662F ${min} \u5230 ${max} \u4E4B\u95F4\u7684\u6574\u6570`);
5576
- }
5577
- }
5578
- static buildRunnableTaskWhere(scope) {
5579
- const baseConditions = [...this.buildScopeWhere(scope)];
5580
- const nowMs = Date.now();
5581
- const retryAfterFilter = or(
5582
- isNull(tasks2.retryAfter),
5583
- sql`${tasks2.retryAfter} <= ${nowMs}`
5584
- );
5585
- const excludedBatchIds = [...new Set((scope.excludedBatchIds ?? []).map((batchId) => normalizeTaskBatchId(batchId)).filter((batchId) => Boolean(batchId)))];
5586
- const hasExcludedBatches = excludedBatchIds.length > 0;
5587
- let batchFilter;
5588
- if (hasExcludedBatches) {
5589
- batchFilter = or(
5590
- isNull(tasks2.batchId),
5591
- sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) = ''`,
5592
- sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) NOT IN ${excludedBatchIds}`
5593
- );
5594
- }
5595
- const statusConditions = or(
5596
- and(
5597
- eq(tasks2.status, "pending"),
5598
- retryAfterFilter
5599
- ),
5600
- and(
5601
- eq(tasks2.status, "failed"),
5602
- sql`${tasks2.retryCount} <= ${tasks2.maxRetries}`,
5603
- retryAfterFilter
5604
- )
5605
- );
5606
- const conditions = [
5607
- statusConditions,
5608
- ...baseConditions
5609
- ];
5610
- if (batchFilter) {
5611
- conditions.push(batchFilter);
5612
- }
5613
- return and(
5614
- ...conditions,
5615
- or(
5616
- isNull(tasks2.dependsOn),
5617
- sql`EXISTS (
5618
- SELECT 1 FROM tasks AS dependency_task
5619
- WHERE dependency_task.id = ${tasks2.dependsOn}
5620
- AND dependency_task.status = 'done'
5621
- AND dependency_task.cwd IS ${tasks2.cwd}
5622
- )`
5623
- ),
5624
- or(
5625
- isNull(tasks2.batchId),
5626
- sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) = ''`,
5627
- sql`NOT EXISTS (
5628
- SELECT 1 FROM tasks AS running_batch_task
5629
- WHERE trim(running_batch_task.batch_id, ${TASK_BATCH_TRIM_CHARACTERS})
5630
- = trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS})
5631
- AND (
5632
- running_batch_task.status = 'running'
5633
- OR EXISTS (
5634
- SELECT 1 FROM task_runs AS running_batch_run
5635
- WHERE running_batch_run.task_id = running_batch_task.id
5636
- AND running_batch_run.status = 'running'
5637
- )
5638
- )
5639
- )`
5640
- ),
5641
- sql`NOT EXISTS (
5642
- SELECT 1 FROM task_runs AS candidate_active_run
5643
- WHERE candidate_active_run.task_id = ${tasks2.id}
5644
- AND candidate_active_run.status = 'running'
5645
- )`
5646
- );
6050
+ validateCommonTaskFields(data);
6051
+ validateIntegerField("dependsOn", data.dependsOn, 1, Number.MAX_SAFE_INTEGER);
5647
6052
  }
5648
6053
  static async next(scope = {}) {
5649
- const result = await db.select().from(tasks2).where(this.buildRunnableTaskWhere(scope)).orderBy(
5650
- desc(tasks2.urgency),
5651
- desc(tasks2.importance),
5652
- asc(tasks2.createdAt),
5653
- asc(tasks2.id)
5654
- ).limit(1);
5655
- return result[0] ?? null;
6054
+ return db.transaction((tx) => {
6055
+ const candidateId = this.findNextCandidateId(scope);
6056
+ if (candidateId === null) return null;
6057
+ return tx.select().from(tasks2).where(eq(tasks2.id, candidateId)).get() ?? null;
6058
+ }, { behavior: "deferred" });
5656
6059
  }
5657
6060
  static async claimNext(scope = {}) {
5658
6061
  return db.transaction((tx) => {
5659
- const candidate = tx.select().from(tasks2).where(this.buildRunnableTaskWhere(scope)).orderBy(
5660
- desc(tasks2.urgency),
5661
- desc(tasks2.importance),
5662
- asc(tasks2.createdAt),
5663
- asc(tasks2.id)
5664
- ).limit(1).get();
5665
- if (!candidate) return null;
6062
+ const candidateId = this.findNextCandidateId(scope);
6063
+ if (candidateId === null) return null;
5666
6064
  return tx.update(tasks2).set({
5667
6065
  status: "running",
5668
6066
  startedAt: /* @__PURE__ */ new Date(),
5669
6067
  finishedAt: null
5670
- }).where(eq(tasks2.id, candidate.id)).returning().get() ?? null;
6068
+ }).where(eq(tasks2.id, candidateId)).returning().get() ?? null;
5671
6069
  }, { behavior: "immediate" });
5672
6070
  }
5673
6071
  static async countRunning(scope = {}) {
5674
- const scopeConditions = scope.legacyCwd ? [sql`${tasks2.cwd} IS NULL OR trim(${tasks2.cwd}) = ''`] : this.buildScopeWhere(scope);
6072
+ const sqlite2 = getSqlite();
5675
6073
  if (scope.batchId !== void 0) {
5676
6074
  const batchId = normalizeTaskBatchId(scope.batchId);
5677
- scopeConditions.push(batchId ? sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) = ${batchId}` : sql`0`);
6075
+ if (!batchId) return 0;
6076
+ const trimChars = TASK_BATCH_TRIM_CHARACTERS;
6077
+ if (scope.legacyCwd) {
6078
+ const row3 = sqlite2.query(COUNT_RUNNING_BY_BATCH_LEGACY_CWD_SQL).get(
6079
+ trimChars,
6080
+ batchId,
6081
+ trimChars,
6082
+ batchId
6083
+ );
6084
+ return Number(row3?.count ?? 0);
6085
+ }
6086
+ if (scope.cwd !== void 0) {
6087
+ const row3 = sqlite2.query(COUNT_RUNNING_BY_BATCH_CWD_SQL).get(
6088
+ trimChars,
6089
+ batchId,
6090
+ scope.cwd,
6091
+ trimChars,
6092
+ batchId,
6093
+ scope.cwd
6094
+ );
6095
+ return Number(row3?.count ?? 0);
6096
+ }
6097
+ const row2 = sqlite2.query(COUNT_RUNNING_BY_BATCH_GLOBAL_SQL).get(
6098
+ trimChars,
6099
+ batchId,
6100
+ trimChars,
6101
+ batchId
6102
+ );
6103
+ return Number(row2?.count ?? 0);
5678
6104
  }
5679
- return db.transaction((tx) => {
5680
- const runningTasks = tx.select({ count: sql`count(*)` }).from(tasks2).where(and(eq(tasks2.status, "running"), ...scopeConditions)).get();
5681
- const runsWithoutRunningTask = tx.select({ count: sql`count(DISTINCT ${taskRuns2.taskId})` }).from(taskRuns2).innerJoin(tasks2, eq(tasks2.id, taskRuns2.taskId)).where(and(
5682
- eq(taskRuns2.status, "running"),
5683
- sql`${tasks2.status} <> 'running'`,
5684
- ...scopeConditions
5685
- )).get();
5686
- return Number(runningTasks?.count ?? 0) + Number(runsWithoutRunningTask?.count ?? 0);
5687
- }, { behavior: "deferred" });
6105
+ if (scope.legacyCwd) {
6106
+ const row2 = sqlite2.query(COUNT_RUNNING_LEGACY_CWD_SQL).get();
6107
+ return Number(row2?.count ?? 0);
6108
+ }
6109
+ if (scope.cwd !== void 0) {
6110
+ const row2 = sqlite2.query(COUNT_RUNNING_BY_CWD_SQL).get(scope.cwd, scope.cwd);
6111
+ return Number(row2?.count ?? 0);
6112
+ }
6113
+ const row = sqlite2.query(COUNT_RUNNING_UNSCOPED_SQL).get();
6114
+ return Number(row?.count ?? 0);
5688
6115
  }
5689
6116
  static async start(id, scope = {}) {
5690
6117
  const conditions = [
@@ -5730,9 +6157,10 @@ var TaskService = class {
5730
6157
  const newRetryCount = (current.retryCount ?? 0) + 1;
5731
6158
  const maxRetries = current.maxRetries ?? 3;
5732
6159
  const isDeadLetter = options?.setDeadLetter ?? newRetryCount > maxRetries;
6160
+ const finishedAt = /* @__PURE__ */ new Date();
5733
6161
  const failed = tx.update(tasks2).set({
5734
6162
  status: isDeadLetter ? "dead_letter" : "failed",
5735
- finishedAt: /* @__PURE__ */ new Date(),
6163
+ finishedAt,
5736
6164
  resultLog: log,
5737
6165
  retryCount: newRetryCount,
5738
6166
  retryAfter: isDeadLetter ? null : options?.retryAfterMs ?? Date.now() + computeBackoff(
@@ -5741,12 +6169,7 @@ var TaskService = class {
5741
6169
  )
5742
6170
  }).where(and(eq(tasks2.id, id), eq(tasks2.status, "running"))).returning().get();
5743
6171
  if (failed?.status === "dead_letter") {
5744
- tx.update(tasks2).set({
5745
- status: "dead_letter",
5746
- finishedAt: /* @__PURE__ */ new Date(),
5747
- retryAfter: null,
5748
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5749
- }).where(blockedDependentsOf(id)).run();
6172
+ this.cascadeDeadLetterDependents(tx, id, finishedAt);
5750
6173
  }
5751
6174
  return failed ?? null;
5752
6175
  }, { behavior: "immediate" });
@@ -5789,24 +6212,19 @@ var TaskService = class {
5789
6212
  newRetryCount,
5790
6213
  currentTask.retryBackoffMs ?? 3e4
5791
6214
  );
5792
- const failed2 = tx.update(tasks2).set({
6215
+ const failedTask = tx.update(tasks2).set({
5793
6216
  status: isDeadLetter ? "dead_letter" : "failed",
5794
6217
  finishedAt,
5795
6218
  resultLog: log,
5796
6219
  retryCount: newRetryCount,
5797
6220
  retryAfter
5798
6221
  }).where(and(eq(tasks2.id, taskId), eq(tasks2.status, "running"))).returning().get();
5799
- if (!failed2) return null;
6222
+ if (!failedTask) return null;
5800
6223
  tx.update(taskRuns2).set({ status: "failed", finishedAt, log }).where(and(eq(taskRuns2.id, runId), eq(taskRuns2.status, "running"))).run();
5801
- if (failed2.status === "dead_letter") {
5802
- tx.update(tasks2).set({
5803
- status: "dead_letter",
5804
- finishedAt,
5805
- retryAfter: null,
5806
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${taskId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5807
- }).where(blockedDependentsOf(taskId)).run();
6224
+ if (failedTask.status === "dead_letter") {
6225
+ this.cascadeDeadLetterDependents(tx, taskId, finishedAt);
5808
6226
  }
5809
- return failed2;
6227
+ return failedTask;
5810
6228
  }, { behavior: "immediate" });
5811
6229
  return failed;
5812
6230
  }
@@ -5839,12 +6257,7 @@ var TaskService = class {
5839
6257
  resultLog: log
5840
6258
  }).where(and(eq(tasks2.id, taskId), eq(tasks2.status, "running"))).run();
5841
6259
  if (recoveryStatus === "dead_letter") {
5842
- tx.update(tasks2).set({
5843
- status: "dead_letter",
5844
- finishedAt,
5845
- retryAfter: null,
5846
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${taskId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5847
- }).where(blockedDependentsOf(taskId)).run();
6260
+ this.cascadeDeadLetterDependents(tx, taskId, finishedAt);
5848
6261
  }
5849
6262
  return {
5850
6263
  status: recoveryStatus,
@@ -5908,15 +6321,6 @@ var TaskService = class {
5908
6321
  )`).returning();
5909
6322
  return result.length;
5910
6323
  }
5911
- static async rejectBlockedDependents(prerequisiteId) {
5912
- const result = await db.update(tasks2).set({
5913
- status: "dead_letter",
5914
- finishedAt: /* @__PURE__ */ new Date(),
5915
- retryAfter: null,
5916
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${prerequisiteId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5917
- }).where(blockedDependentsOf(prerequisiteId)).returning({ id: tasks2.id });
5918
- return result.length;
5919
- }
5920
6324
  static async markPendingForRetry(id, retryAfterMs, retryCount) {
5921
6325
  const result = await db.update(tasks2).set({
5922
6326
  status: "pending",
@@ -5932,12 +6336,7 @@ var TaskService = class {
5932
6336
  const finishedAt = /* @__PURE__ */ new Date();
5933
6337
  const task = tx.update(tasks2).set({ status: "dead_letter", finishedAt, retryCount }).where(eq(tasks2.id, id)).returning().get();
5934
6338
  if (!task) return null;
5935
- tx.update(tasks2).set({
5936
- status: "dead_letter",
5937
- finishedAt,
5938
- retryAfter: null,
5939
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5940
- }).where(blockedDependentsOf(id)).run();
6339
+ this.cascadeDeadLetterDependents(tx, id, finishedAt);
5941
6340
  return task;
5942
6341
  }, { behavior: "immediate" });
5943
6342
  }
@@ -5990,15 +6389,49 @@ var TaskService = class {
5990
6389
  retryAfter: null
5991
6390
  }).where(and(...conditions)).returning().get();
5992
6391
  if (!task) return null;
5993
- tx.update(tasks2).set({
5994
- status: "dead_letter",
5995
- finishedAt,
5996
- retryAfter: null,
5997
- resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
5998
- }).where(blockedDependentsOf(id)).run();
6392
+ this.cascadeDeadLetterDependents(tx, id, finishedAt);
5999
6393
  return task;
6000
6394
  }, { behavior: "immediate" });
6001
6395
  }
6396
+ static async cancelBatch(ids, scope = {}) {
6397
+ const uniqueIds = [...new Set(ids.filter((id) => Number.isInteger(id) && id > 0))];
6398
+ if (uniqueIds.length === 0) {
6399
+ return { cancelledIds: [], skippedIds: [], cancelledCount: 0 };
6400
+ }
6401
+ return db.transaction((tx) => {
6402
+ const finishedAt = /* @__PURE__ */ new Date();
6403
+ const cancelledIds = [];
6404
+ const skippedIds = [];
6405
+ for (const id of uniqueIds) {
6406
+ const task = tx.update(tasks2).set({
6407
+ status: "cancelled",
6408
+ finishedAt,
6409
+ retryAfter: null
6410
+ }).where(and(
6411
+ eq(tasks2.id, id),
6412
+ or(
6413
+ eq(tasks2.status, "pending"),
6414
+ eq(tasks2.status, "running"),
6415
+ eq(tasks2.status, "failed")
6416
+ ),
6417
+ ...this.buildScopeWhere(scope)
6418
+ )).returning({ id: tasks2.id }).get();
6419
+ if (task) {
6420
+ cancelledIds.push(task.id);
6421
+ } else {
6422
+ skippedIds.push(id);
6423
+ }
6424
+ }
6425
+ for (const cancelledId of cancelledIds) {
6426
+ this.cascadeDeadLetterDependents(tx, cancelledId, finishedAt);
6427
+ }
6428
+ return {
6429
+ cancelledIds,
6430
+ skippedIds,
6431
+ cancelledCount: cancelledIds.length
6432
+ };
6433
+ }, { behavior: "immediate" });
6434
+ }
6002
6435
  static async retry(id, scope = {}) {
6003
6436
  const conditions = [
6004
6437
  eq(tasks2.id, id),
@@ -6013,19 +6446,82 @@ var TaskService = class {
6013
6446
  retryCount: 0
6014
6447
  }).where(and(...conditions, hasViableDependency())).returning().get() ?? null, { behavior: "immediate" });
6015
6448
  }
6449
+ static async retryIds(ids, scope = {}) {
6450
+ const uniqueIds = [...new Set(ids.filter((id) => Number.isInteger(id) && id > 0))];
6451
+ if (uniqueIds.length === 0) {
6452
+ return { retriedIds: [], skippedIds: [], retriedCount: 0 };
6453
+ }
6454
+ return db.transaction((tx) => {
6455
+ const retriedIds = [];
6456
+ let remaining = [...uniqueIds].sort((a, b) => a - b);
6457
+ while (remaining.length > 0) {
6458
+ let progressed = false;
6459
+ const nextRemaining = [];
6460
+ for (const id of remaining) {
6461
+ const retried = tx.update(tasks2).set({
6462
+ status: "pending",
6463
+ startedAt: null,
6464
+ finishedAt: null,
6465
+ retryAfter: null,
6466
+ retryCount: 0
6467
+ }).where(and(
6468
+ eq(tasks2.id, id),
6469
+ or(eq(tasks2.status, "failed"), eq(tasks2.status, "dead_letter")),
6470
+ ...this.buildScopeWhere(scope),
6471
+ hasViableDependency()
6472
+ )).returning({ id: tasks2.id }).get();
6473
+ if (retried) {
6474
+ retriedIds.push(retried.id);
6475
+ progressed = true;
6476
+ } else {
6477
+ nextRemaining.push(id);
6478
+ }
6479
+ }
6480
+ remaining = nextRemaining;
6481
+ if (!progressed) break;
6482
+ }
6483
+ return {
6484
+ retriedIds,
6485
+ skippedIds: remaining,
6486
+ retriedCount: retriedIds.length
6487
+ };
6488
+ }, { behavior: "immediate" });
6489
+ }
6016
6490
  static async retryBatch(batchId, scope = {}) {
6017
6491
  const normalizedBatchId = normalizeTaskBatchId(batchId);
6018
6492
  if (!normalizedBatchId) return 0;
6019
6493
  const sqlite2 = getSqlite();
6020
6494
  const scopeFilter = scope.cwd === void 0 ? "" : "AND candidate.cwd = ?";
6021
- const parameters = scope.cwd === void 0 ? [TASK_BATCH_TRIM_CHARACTERS, normalizedBatchId] : [TASK_BATCH_TRIM_CHARACTERS, normalizedBatchId, scope.cwd];
6495
+ const parameters = scope.cwd === void 0 ? [
6496
+ normalizedBatchId,
6497
+ normalizedBatchId,
6498
+ normalizedBatchId,
6499
+ TASK_BATCH_TRIM_CHARACTERS,
6500
+ normalizedBatchId
6501
+ ] : [
6502
+ normalizedBatchId,
6503
+ normalizedBatchId,
6504
+ normalizedBatchId,
6505
+ TASK_BATCH_TRIM_CHARACTERS,
6506
+ normalizedBatchId,
6507
+ scope.cwd
6508
+ ];
6022
6509
  return db.transaction(() => sqlite2.query(`
6023
6510
  WITH RECURSIVE
6511
+ matched_batch_ids(id) AS MATERIALIZED (
6512
+ SELECT id FROM tasks WHERE batch_id = ?
6513
+ UNION ALL
6514
+ SELECT id FROM tasks
6515
+ WHERE batch_id IS NOT NULL
6516
+ AND batch_id <> ?
6517
+ AND length(batch_id) > length(?)
6518
+ AND trim(batch_id, ?) = ?
6519
+ ),
6024
6520
  candidate(id, cwd, depends_on) AS MATERIALIZED (
6025
6521
  SELECT candidate.id, candidate.cwd, candidate.depends_on
6026
6522
  FROM tasks AS candidate
6027
- WHERE trim(candidate.batch_id, ?) = ?
6028
- AND candidate.status IN ('failed', 'dead_letter')
6523
+ INNER JOIN matched_batch_ids AS mb ON mb.id = candidate.id
6524
+ WHERE candidate.status IN ('failed', 'dead_letter')
6029
6525
  ${scopeFilter}
6030
6526
  ),
6031
6527
  retryable(id, cwd, depends_on) AS (
@@ -6076,32 +6572,33 @@ var TaskService = class {
6076
6572
  return result[0] || null;
6077
6573
  }
6078
6574
  static async list(options = {}) {
6079
- let query = db.select().from(tasks2).$dynamic();
6080
- const conditions = [];
6081
- if (options.activeExecution) {
6082
- conditions.push(or(
6083
- eq(tasks2.status, "running"),
6084
- sql`EXISTS (
6085
- SELECT 1 FROM task_runs AS active_list_run
6086
- WHERE active_list_run.task_id = ${tasks2.id}
6087
- AND active_list_run.status = 'running'
6088
- )`
6089
- ));
6090
- } else if (options.status) {
6091
- conditions.push(eq(tasks2.status, options.status));
6092
- }
6093
- if (options.batchId !== void 0) {
6094
- const batchId = normalizeTaskBatchId(options.batchId);
6095
- conditions.push(batchId ? sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) = ${batchId}` : sql`0`);
6096
- }
6097
- if (options.category) {
6098
- conditions.push(eq(tasks2.category, options.category));
6099
- }
6100
- if (options.legacyCwd) {
6101
- conditions.push(sql`${tasks2.cwd} IS NULL OR trim(${tasks2.cwd}) = ''`);
6102
- } else if (options.cwd !== void 0) {
6103
- conditions.push(eq(tasks2.cwd, options.cwd));
6104
- }
6575
+ const conditions = this.buildListConditions(options);
6576
+ let query = (options.excludeResultLog ? db.select({
6577
+ id: tasks2.id,
6578
+ name: tasks2.name,
6579
+ agent: tasks2.agent,
6580
+ model: tasks2.model,
6581
+ variant: tasks2.variant,
6582
+ prompt: tasks2.prompt,
6583
+ cwd: tasks2.cwd,
6584
+ category: tasks2.category,
6585
+ importance: tasks2.importance,
6586
+ urgency: tasks2.urgency,
6587
+ batchId: tasks2.batchId,
6588
+ dependsOn: tasks2.dependsOn,
6589
+ status: tasks2.status,
6590
+ createdAt: tasks2.createdAt,
6591
+ startedAt: tasks2.startedAt,
6592
+ finishedAt: tasks2.finishedAt,
6593
+ resultLog: sql`NULL`,
6594
+ retryCount: tasks2.retryCount,
6595
+ maxRetries: tasks2.maxRetries,
6596
+ retryBackoffMs: tasks2.retryBackoffMs,
6597
+ retryAfter: tasks2.retryAfter,
6598
+ timeoutMs: tasks2.timeoutMs,
6599
+ templateId: tasks2.templateId,
6600
+ scheduledAt: tasks2.scheduledAt
6601
+ }).from(tasks2) : db.select().from(tasks2)).$dynamic();
6105
6602
  if (conditions.length > 0) {
6106
6603
  query = query.where(and(...conditions));
6107
6604
  }
@@ -6114,14 +6611,57 @@ var TaskService = class {
6114
6611
  }
6115
6612
  return await query;
6116
6613
  }
6614
+ static async listCompact(options = {}) {
6615
+ const conditions = this.buildListConditions(options);
6616
+ let query = db.select({
6617
+ id: tasks2.id,
6618
+ name: tasks2.name,
6619
+ agent: tasks2.agent,
6620
+ model: tasks2.model,
6621
+ variant: tasks2.variant,
6622
+ prompt: tasks2.prompt,
6623
+ cwd: tasks2.cwd,
6624
+ category: tasks2.category,
6625
+ importance: tasks2.importance,
6626
+ urgency: tasks2.urgency,
6627
+ batchId: tasks2.batchId,
6628
+ dependsOn: tasks2.dependsOn,
6629
+ status: tasks2.status,
6630
+ createdAt: tasks2.createdAt,
6631
+ startedAt: tasks2.startedAt,
6632
+ finishedAt: tasks2.finishedAt,
6633
+ retryCount: tasks2.retryCount,
6634
+ maxRetries: tasks2.maxRetries,
6635
+ retryBackoffMs: tasks2.retryBackoffMs,
6636
+ retryAfter: tasks2.retryAfter,
6637
+ timeoutMs: tasks2.timeoutMs,
6638
+ templateId: tasks2.templateId,
6639
+ scheduledAt: tasks2.scheduledAt,
6640
+ hasResultLog: sql`CASE WHEN ${tasks2.resultLog} IS NOT NULL AND length(${tasks2.resultLog}) > 0 THEN 1 ELSE 0 END`,
6641
+ 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`
6642
+ }).from(tasks2).$dynamic();
6643
+ if (conditions.length > 0) {
6644
+ query = query.where(and(...conditions));
6645
+ }
6646
+ query = query.orderBy(desc(tasks2.createdAt), desc(tasks2.id));
6647
+ if (options.limit) query = query.limit(options.limit);
6648
+ if (options.offset) query = query.offset(options.offset);
6649
+ const rows = await query;
6650
+ return rows.map((row) => ({
6651
+ ...row,
6652
+ resultLog: null,
6653
+ hasResultLog: Number(row.hasResultLog) === 1,
6654
+ resultLogPreview: row.resultLogPreview
6655
+ }));
6656
+ }
6117
6657
  static async stats(options = {}) {
6118
6658
  const conditions = [];
6119
6659
  if (options.batchId !== void 0) {
6120
6660
  const batchId = normalizeTaskBatchId(options.batchId);
6121
- conditions.push(batchId ? sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) = ${batchId}` : sql`0`);
6661
+ conditions.push(batchId ? batchIdMatchCondition(batchId) : sql`0`);
6122
6662
  }
6123
6663
  if (options.legacyCwd) {
6124
- conditions.push(sql`${tasks2.cwd} IS NULL OR trim(${tasks2.cwd}) = ''`);
6664
+ conditions.push(legacyCwdCondition());
6125
6665
  } else if (options.cwd !== void 0) {
6126
6666
  conditions.push(eq(tasks2.cwd, options.cwd));
6127
6667
  }
@@ -6147,32 +6687,204 @@ var TaskService = class {
6147
6687
  }
6148
6688
  return stats;
6149
6689
  }
6690
+ static async dashboardOverview(cwdOrOptions) {
6691
+ const options = typeof cwdOrOptions === "string" ? { cwd: cwdOrOptions } : cwdOrOptions ?? {};
6692
+ const projectLimit = options.projectLimit ?? 100;
6693
+ validateIntegerField("projectLimit", projectLimit, 1, 1e3);
6694
+ const cutoff7dSec = Math.floor(Date.now() / 1e3) - 7 * 86400;
6695
+ const sqlite2 = getSqlite();
6696
+ const insideOuterTransaction = sqlite2.inTransaction;
6697
+ let cacheEntry = dashboardOverviewCache.get(sqlite2);
6698
+ if (!cacheEntry) {
6699
+ cacheEntry = { writeEpoch: 0, snapshot: null };
6700
+ dashboardOverviewCache.set(sqlite2, cacheEntry);
6701
+ }
6702
+ let snapshot = null;
6703
+ if (!insideOuterTransaction) {
6704
+ const stamp = readSqliteMutationStamp(sqlite2);
6705
+ const cached = cacheEntry.snapshot;
6706
+ const cacheHit = cached !== null && cached.dataVersion === stamp.dataVersion && cached.totalChanges === stamp.totalChanges && cached.writeEpoch === cacheEntry.writeEpoch && cutoff7dSec >= cached.computedCutoff7dSec && (cached.next7dExpirySec === null || cutoff7dSec <= cached.next7dExpirySec);
6707
+ if (cacheHit) {
6708
+ snapshot = cached;
6709
+ }
6710
+ }
6711
+ if (snapshot === null) {
6712
+ let statusRows;
6713
+ let extraActiveRows;
6714
+ let snapshotStamp = null;
6715
+ let snapshotWriteEpoch = cacheEntry.writeEpoch;
6716
+ if (!insideOuterTransaction) {
6717
+ sqlite2.exec("BEGIN DEFERRED");
6718
+ }
6719
+ try {
6720
+ statusRows = sqlite2.query(DASHBOARD_OVERVIEW_BY_STATUS_SQL).all(
6721
+ cutoff7dSec,
6722
+ cutoff7dSec,
6723
+ cutoff7dSec,
6724
+ cutoff7dSec,
6725
+ cutoff7dSec
6726
+ );
6727
+ extraActiveRows = sqlite2.query(DASHBOARD_OVERVIEW_EXTRA_ACTIVE_RUNS_SQL).all();
6728
+ if (!insideOuterTransaction) {
6729
+ snapshotStamp = readSqliteMutationStamp(sqlite2);
6730
+ snapshotWriteEpoch = cacheEntry.writeEpoch;
6731
+ sqlite2.exec("COMMIT");
6732
+ }
6733
+ } catch (error) {
6734
+ if (!insideOuterTransaction && sqlite2.inTransaction) {
6735
+ try {
6736
+ sqlite2.exec("ROLLBACK");
6737
+ } catch {
6738
+ }
6739
+ }
6740
+ throw error;
6741
+ }
6742
+ const globalStats = emptyDashboardStats();
6743
+ const legacyStats = emptyDashboardStats();
6744
+ let hasLegacyCwd = false;
6745
+ let legacyTaskCount = 0;
6746
+ let next7dExpirySec = null;
6747
+ const projectMap = /* @__PURE__ */ new Map();
6748
+ const getOrCreateProject = (cwd) => {
6749
+ let acc = projectMap.get(cwd);
6750
+ if (!acc) {
6751
+ acc = {
6752
+ cwd,
6753
+ stats: emptyDashboardStats(),
6754
+ lastCreatedAtSec: -1,
6755
+ lastTaskId: 0,
6756
+ done7d: 0,
6757
+ failed7d: 0,
6758
+ durationSumMs7d: 0,
6759
+ durationCount7d: 0
6760
+ };
6761
+ projectMap.set(cwd, acc);
6762
+ }
6763
+ return acc;
6764
+ };
6765
+ const applyStatusCount = (target, status, count) => {
6766
+ target.total += count;
6767
+ switch (status) {
6768
+ case "pending":
6769
+ target.pending += count;
6770
+ break;
6771
+ case "running":
6772
+ target.running += count;
6773
+ target.activeExecution += count;
6774
+ break;
6775
+ case "done":
6776
+ target.done += count;
6777
+ break;
6778
+ case "failed":
6779
+ target.failed += count;
6780
+ break;
6781
+ case "dead_letter":
6782
+ target.dead_letter += count;
6783
+ break;
6784
+ case "cancelled":
6785
+ target.cancelled += count;
6786
+ break;
6787
+ }
6788
+ };
6789
+ for (const row of statusRows) {
6790
+ const count = Number(row.status_count ?? 0);
6791
+ applyStatusCount(globalStats, row.task_status, count);
6792
+ if (row.min_finished_7d !== null && row.min_finished_7d !== void 0) {
6793
+ const candidate = Number(row.min_finished_7d);
6794
+ if (next7dExpirySec === null || candidate < next7dExpirySec) {
6795
+ next7dExpirySec = candidate;
6796
+ }
6797
+ }
6798
+ const isLegacy = row.project_cwd === null || row.project_cwd.trim() === "";
6799
+ if (isLegacy) {
6800
+ if (count > 0) hasLegacyCwd = true;
6801
+ legacyTaskCount += count;
6802
+ applyStatusCount(legacyStats, row.task_status, count);
6803
+ continue;
6804
+ }
6805
+ const acc = getOrCreateProject(row.project_cwd);
6806
+ applyStatusCount(acc.stats, row.task_status, count);
6807
+ const rowCreated = row.last_created_at === null ? -1 : Number(row.last_created_at);
6808
+ if (rowCreated > acc.lastCreatedAtSec) acc.lastCreatedAtSec = rowCreated;
6809
+ const rowLastId = Number(row.last_task_id ?? 0);
6810
+ if (rowLastId > acc.lastTaskId) acc.lastTaskId = rowLastId;
6811
+ acc.done7d += Number(row.done_7d ?? 0);
6812
+ acc.failed7d += Number(row.failed_7d ?? 0);
6813
+ acc.durationSumMs7d += Number(row.duration_sum_ms_7d ?? 0);
6814
+ acc.durationCount7d += Number(row.duration_count_7d ?? 0);
6815
+ }
6816
+ for (const extraRow of extraActiveRows) {
6817
+ const extra = Number(extraRow.extra_active ?? 0);
6818
+ if (extra <= 0) continue;
6819
+ globalStats.activeExecution += extra;
6820
+ const isLegacy = extraRow.project_cwd === null || extraRow.project_cwd.trim() === "";
6821
+ if (isLegacy) {
6822
+ legacyStats.activeExecution += extra;
6823
+ continue;
6824
+ }
6825
+ const acc = projectMap.get(extraRow.project_cwd);
6826
+ if (acc) {
6827
+ acc.stats.activeExecution += extra;
6828
+ }
6829
+ }
6830
+ const byCwdStats = /* @__PURE__ */ new Map();
6831
+ const sortedAccumulators = [...projectMap.values()].sort((a, b) => b.lastCreatedAtSec - a.lastCreatedAtSec || b.lastTaskId - a.lastTaskId);
6832
+ const sortedProjects = [];
6833
+ for (const acc of sortedAccumulators) {
6834
+ byCwdStats.set(acc.cwd, acc.stats);
6835
+ sortedProjects.push({
6836
+ cwd: acc.cwd,
6837
+ total: acc.stats.total,
6838
+ pending: acc.stats.pending,
6839
+ running: acc.stats.activeExecution,
6840
+ failed: acc.stats.failed + acc.stats.dead_letter,
6841
+ done: acc.stats.done,
6842
+ deadLetter: acc.stats.dead_letter,
6843
+ cancelled: acc.stats.cancelled,
6844
+ lastCreatedAt: acc.lastCreatedAtSec < 0 ? null : acc.lastCreatedAtSec * 1e3,
6845
+ done7d: acc.done7d,
6846
+ failed7d: acc.failed7d,
6847
+ avgDurationMs7d: acc.durationCount7d > 0 ? Math.round(acc.durationSumMs7d / acc.durationCount7d) : null
6848
+ });
6849
+ }
6850
+ snapshot = {
6851
+ dataVersion: snapshotStamp?.dataVersion ?? -1,
6852
+ totalChanges: snapshotStamp?.totalChanges ?? -1,
6853
+ writeEpoch: snapshotWriteEpoch,
6854
+ computedCutoff7dSec: cutoff7dSec,
6855
+ next7dExpirySec,
6856
+ global: globalStats,
6857
+ legacyStats,
6858
+ hasLegacyCwd,
6859
+ legacyTaskCount,
6860
+ byCwdStats,
6861
+ sortedProjects
6862
+ };
6863
+ if (!insideOuterTransaction && snapshotStamp !== null) {
6864
+ cacheEntry.snapshot = snapshot;
6865
+ }
6866
+ }
6867
+ const resolvedScoped = options.legacyCwd ? cloneDashboardStats(snapshot.legacyStats) : options.cwd !== void 0 ? cloneDashboardStats(snapshot.byCwdStats.get(options.cwd) ?? emptyDashboardStats()) : cloneDashboardStats(snapshot.global);
6868
+ return {
6869
+ global: cloneDashboardStats(snapshot.global),
6870
+ scoped: resolvedScoped,
6871
+ projects: snapshot.sortedProjects.slice(0, projectLimit).map((item) => ({ ...item })),
6872
+ hasLegacyCwd: snapshot.hasLegacyCwd,
6873
+ legacyTaskCount: snapshot.legacyTaskCount
6874
+ };
6875
+ }
6150
6876
  static async projectSummaries(limit = 100) {
6151
- this.validateInteger("limit", limit, 1, 1e3);
6152
- const lastCreatedAt = sql`max(${tasks2.createdAt})`;
6153
- const lastTaskId = sql`max(${tasks2.id})`;
6154
- const rows = await db.select({
6155
- cwd: tasks2.cwd,
6156
- total: sql`count(*)`,
6157
- pending: sql`sum(CASE WHEN ${tasks2.status} = 'pending' THEN 1 ELSE 0 END)`,
6158
- running: sql`sum(CASE WHEN ${tasks2.status} = 'running' OR EXISTS (
6159
- SELECT 1 FROM task_runs AS active_project_run
6160
- WHERE active_project_run.task_id = ${tasks2.id}
6161
- AND active_project_run.status = 'running'
6162
- ) THEN 1 ELSE 0 END)`,
6163
- failed: sql`sum(CASE WHEN ${tasks2.status} IN ('failed', 'dead_letter') THEN 1 ELSE 0 END)`,
6164
- done: sql`sum(CASE WHEN ${tasks2.status} = 'done' THEN 1 ELSE 0 END)`,
6165
- lastCreatedAt
6166
- }).from(tasks2).where(sql`${tasks2.cwd} IS NOT NULL AND trim(${tasks2.cwd}) <> ''`).groupBy(tasks2.cwd).orderBy(desc(lastCreatedAt), desc(lastTaskId)).limit(limit);
6167
- return rows.flatMap((row) => row.cwd === null ? [] : [{
6168
- cwd: row.cwd,
6169
- total: Number(row.total),
6170
- pending: Number(row.pending),
6171
- running: Number(row.running),
6172
- failed: Number(row.failed),
6173
- done: Number(row.done),
6174
- lastCreatedAt: row.lastCreatedAt === null ? null : Number(row.lastCreatedAt) * 1e3
6175
- }]);
6877
+ validateIntegerField("limit", limit, 1, 1e3);
6878
+ const overview = await this.dashboardOverview({ projectLimit: limit });
6879
+ return overview.projects.map((project) => ({
6880
+ cwd: project.cwd,
6881
+ total: project.total,
6882
+ pending: project.pending,
6883
+ running: project.running,
6884
+ failed: project.failed,
6885
+ done: project.done,
6886
+ lastCreatedAt: project.lastCreatedAt
6887
+ }));
6176
6888
  }
6177
6889
  static async delete(id, scope = {}) {
6178
6890
  const conditions = [
@@ -6205,6 +6917,65 @@ var TaskService = class {
6205
6917
  `\u4EFB\u52A1 #${id} \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u53D6\u6D88\u4EFB\u52A1\u5E76\u7B49\u5F85\u6267\u884C\u8FDB\u7A0B\u9000\u51FA`
6206
6918
  );
6207
6919
  }
6920
+ static async deleteBatch(ids, scope = {}) {
6921
+ const uniqueIds = [...new Set(ids.filter((id) => Number.isInteger(id) && id > 0))];
6922
+ if (uniqueIds.length === 0) {
6923
+ return { deletedIds: [], notFoundIds: [], conflicts: [], deletedCount: 0 };
6924
+ }
6925
+ return db.transaction((tx) => {
6926
+ const deletedIds = [];
6927
+ let remaining = [...uniqueIds].sort((a, b) => b - a);
6928
+ while (remaining.length > 0) {
6929
+ let progressed = false;
6930
+ const nextRemaining = [];
6931
+ for (const id of remaining) {
6932
+ const deleted = tx.delete(tasks2).where(and(
6933
+ eq(tasks2.id, id),
6934
+ sql`${tasks2.status} <> 'running'`,
6935
+ sql`NOT EXISTS (
6936
+ SELECT 1 FROM ${taskRuns2}
6937
+ WHERE ${taskRuns2.taskId} = ${tasks2.id}
6938
+ AND ${taskRuns2.status} = 'running'
6939
+ )`,
6940
+ hasNoExecutableDependents(),
6941
+ ...this.buildScopeWhere(scope)
6942
+ )).returning({ id: tasks2.id }).get();
6943
+ if (deleted) {
6944
+ tx.delete(taskRuns2).where(eq(taskRuns2.taskId, id)).run();
6945
+ deletedIds.push(id);
6946
+ progressed = true;
6947
+ } else {
6948
+ nextRemaining.push(id);
6949
+ }
6950
+ }
6951
+ remaining = nextRemaining;
6952
+ if (!progressed) break;
6953
+ }
6954
+ const notFoundIds = [];
6955
+ const conflicts = [];
6956
+ for (const id of remaining) {
6957
+ const exists2 = tx.select({ id: tasks2.id }).from(tasks2).where(and(eq(tasks2.id, id), ...this.buildScopeWhere(scope))).get();
6958
+ if (!exists2) {
6959
+ notFoundIds.push(id);
6960
+ continue;
6961
+ }
6962
+ const dependent = tx.select({ id: tasks2.id }).from(tasks2).where(and(
6963
+ eq(tasks2.dependsOn, id),
6964
+ sql`${tasks2.status} IN ('pending', 'running', 'failed', 'dead_letter')`
6965
+ )).orderBy(asc(tasks2.id)).limit(1).get();
6966
+ conflicts.push({
6967
+ id,
6968
+ reason: dependent ? `\u4EFB\u52A1 #${id} \u4ECD\u88AB\u53EF\u6267\u884C\u4EFB\u52A1 #${dependent.id} \u4F9D\u8D56\uFF0C\u8BF7\u5148\u5904\u7406\u4F9D\u8D56\u4EFB\u52A1` : `\u4EFB\u52A1 #${id} \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u53D6\u6D88\u4EFB\u52A1\u5E76\u7B49\u5F85\u6267\u884C\u8FDB\u7A0B\u9000\u51FA`
6969
+ });
6970
+ }
6971
+ return {
6972
+ deletedIds,
6973
+ notFoundIds,
6974
+ conflicts,
6975
+ deletedCount: deletedIds.length
6976
+ };
6977
+ }, { behavior: "immediate" });
6978
+ }
6208
6979
  static async deleteOlderThan(retentionDays, shouldStop = () => false) {
6209
6980
  const cutoffSec = Math.floor(Date.now() / 1e3) - retentionDays * 86400;
6210
6981
  const batchSize = 500;
@@ -6217,72 +6988,89 @@ var TaskService = class {
6217
6988
  id INTEGER NOT NULL PRIMARY KEY
6218
6989
  ) WITHOUT ROWID;
6219
6990
  `);
6991
+ const clearCandidatesStmt = sqlite2.prepare(`DELETE FROM ${candidateTable}`);
6992
+ const firstPageCandidatesStmt = sqlite2.prepare(`
6993
+ INSERT INTO ${candidateTable}(id)
6994
+ SELECT candidate.id
6995
+ FROM tasks AS candidate
6996
+ WHERE candidate.status IN ('done', 'dead_letter', 'cancelled')
6997
+ AND candidate.finished_at IS NOT NULL
6998
+ AND candidate.finished_at < ?
6999
+ AND NOT EXISTS (
7000
+ SELECT 1 FROM task_runs AS active_run
7001
+ WHERE active_run.task_id = candidate.id
7002
+ AND active_run.status = 'running'
7003
+ )
7004
+ ORDER BY candidate.id DESC
7005
+ LIMIT ?
7006
+ `);
7007
+ const nextPageCandidatesStmt = sqlite2.prepare(`
7008
+ INSERT INTO ${candidateTable}(id)
7009
+ SELECT candidate.id
7010
+ FROM tasks AS candidate
7011
+ WHERE candidate.status IN ('done', 'dead_letter', 'cancelled')
7012
+ AND candidate.finished_at IS NOT NULL
7013
+ AND candidate.finished_at < ?
7014
+ AND candidate.id < ?
7015
+ AND NOT EXISTS (
7016
+ SELECT 1 FROM task_runs AS active_run
7017
+ WHERE active_run.task_id = candidate.id
7018
+ AND active_run.status = 'running'
7019
+ )
7020
+ ORDER BY candidate.id DESC
7021
+ LIMIT ?
7022
+ `);
7023
+ const minCandidateStmt = sqlite2.prepare(`SELECT min(id) AS nextCeilingId FROM ${candidateTable}`);
7024
+ const pruneAnomalousStmt = sqlite2.prepare(`
7025
+ DELETE FROM ${candidateTable}
7026
+ WHERE EXISTS (
7027
+ SELECT 1 FROM tasks AS anomalous
7028
+ WHERE anomalous.id = ${candidateTable}.id
7029
+ AND anomalous.depends_on IS NOT NULL
7030
+ AND anomalous.depends_on >= anomalous.id
7031
+ )
7032
+ `);
7033
+ const pruneDependentStmt = sqlite2.prepare(`
7034
+ DELETE FROM ${candidateTable}
7035
+ WHERE EXISTS (
7036
+ SELECT 1 FROM tasks AS dependent_task
7037
+ WHERE dependent_task.depends_on = ${candidateTable}.id
7038
+ AND NOT EXISTS (
7039
+ SELECT 1 FROM ${candidateTable} AS selected_dependent
7040
+ WHERE selected_dependent.id = dependent_task.id
7041
+ )
7042
+ )
7043
+ `);
7044
+ const countSelectedStmt = sqlite2.prepare(`SELECT count(*) AS count FROM ${candidateTable}`);
7045
+ const deleteTasksStmt = sqlite2.prepare(`
7046
+ DELETE FROM tasks
7047
+ WHERE id IN (SELECT id FROM ${candidateTable})
7048
+ `);
7049
+ const verifyRemainingStmt = sqlite2.prepare(`
7050
+ SELECT count(*) AS count
7051
+ FROM tasks
7052
+ WHERE id IN (SELECT id FROM ${candidateTable})
7053
+ `);
6220
7054
  try {
6221
7055
  let ceilingId = null;
6222
7056
  while (true) {
6223
7057
  if (shouldStop()) return deletedTotal;
6224
7058
  const batch = db.transaction(() => {
6225
- sqlite2.query(`DELETE FROM ${candidateTable}`).run();
6226
- const ceilingPredicate = ceilingId == null ? "" : "AND candidate.id < ?";
6227
- const rawCandidateStatement = sqlite2.query(`
6228
- INSERT INTO ${candidateTable}(id)
6229
- SELECT candidate.id
6230
- FROM tasks AS candidate NOT INDEXED
6231
- WHERE candidate.status IN ('done', 'dead_letter', 'cancelled')
6232
- AND candidate.finished_at IS NOT NULL
6233
- AND candidate.finished_at < ?
6234
- ${ceilingPredicate}
6235
- AND NOT EXISTS (
6236
- SELECT 1 FROM task_runs AS active_run
6237
- WHERE active_run.task_id = candidate.id
6238
- AND active_run.status = 'running'
6239
- )
6240
- ORDER BY candidate.id DESC
6241
- LIMIT ?
6242
- `);
6243
- const rawCount = ceilingId == null ? rawCandidateStatement.run(cutoffSec, batchSize).changes : rawCandidateStatement.run(cutoffSec, ceilingId, batchSize).changes;
7059
+ clearCandidatesStmt.run();
7060
+ const rawCount = ceilingId == null ? firstPageCandidatesStmt.run(cutoffSec, batchSize).changes : nextPageCandidatesStmt.run(cutoffSec, ceilingId, batchSize).changes;
6244
7061
  if (rawCount === 0) return { deleted: 0, nextCeilingId: null };
6245
- const rawPage = sqlite2.query(`
6246
- SELECT min(id) AS nextCeilingId FROM ${candidateTable}
6247
- `).get();
6248
- sqlite2.query(`
6249
- DELETE FROM ${candidateTable}
6250
- WHERE EXISTS (
6251
- SELECT 1 FROM tasks AS anomalous
6252
- WHERE anomalous.id = ${candidateTable}.id
6253
- AND anomalous.depends_on IS NOT NULL
6254
- AND anomalous.depends_on >= anomalous.id
6255
- )
6256
- `).run();
7062
+ const rawPage = minCandidateStmt.get();
7063
+ pruneAnomalousStmt.run();
6257
7064
  while (true) {
6258
- const pruned = sqlite2.query(`
6259
- DELETE FROM ${candidateTable}
6260
- WHERE EXISTS (
6261
- SELECT 1 FROM tasks AS dependent_task
6262
- WHERE dependent_task.depends_on = ${candidateTable}.id
6263
- AND NOT EXISTS (
6264
- SELECT 1 FROM ${candidateTable} AS selected_dependent
6265
- WHERE selected_dependent.id = dependent_task.id
6266
- )
6267
- )
6268
- `).run().changes;
7065
+ const pruned = pruneDependentStmt.run().changes;
6269
7066
  if (pruned === 0) break;
6270
7067
  }
6271
- const selected = sqlite2.query(`
6272
- SELECT count(*) AS count FROM ${candidateTable}
6273
- `).get();
7068
+ const selected = countSelectedStmt.get();
6274
7069
  if (selected.count === 0) {
6275
7070
  return { deleted: 0, nextCeilingId: rawPage.nextCeilingId };
6276
7071
  }
6277
- sqlite2.query(`
6278
- DELETE FROM tasks
6279
- WHERE id IN (SELECT id FROM ${candidateTable})
6280
- `).run();
6281
- const remaining = sqlite2.query(`
6282
- SELECT count(*) AS count
6283
- FROM tasks
6284
- WHERE id IN (SELECT id FROM ${candidateTable})
6285
- `).get();
7072
+ deleteTasksStmt.run();
7073
+ const remaining = verifyRemainingStmt.get();
6286
7074
  if (remaining.count !== 0) {
6287
7075
  throw new Error("\u5386\u53F2\u6E05\u7406\u5019\u9009\u5728\u540C\u4E00\u5199\u4E8B\u52A1\u5185\u53D1\u751F\u6F02\u79FB\uFF0C\u5DF2\u56DE\u6EDA\u672C\u6279\u5220\u9664");
6288
7076
  }
@@ -6296,6 +7084,15 @@ var TaskService = class {
6296
7084
  }
6297
7085
  return deletedTotal;
6298
7086
  } finally {
7087
+ clearCandidatesStmt.finalize();
7088
+ firstPageCandidatesStmt.finalize();
7089
+ nextPageCandidatesStmt.finalize();
7090
+ minCandidateStmt.finalize();
7091
+ pruneAnomalousStmt.finalize();
7092
+ pruneDependentStmt.finalize();
7093
+ countSelectedStmt.finalize();
7094
+ deleteTasksStmt.finalize();
7095
+ verifyRemainingStmt.finalize();
6299
7096
  sqlite2.exec(`DROP TABLE IF EXISTS ${candidateTable}`);
6300
7097
  }
6301
7098
  }
@@ -6303,6 +7100,7 @@ var TaskService = class {
6303
7100
 
6304
7101
  // src/core/process-control.ts
6305
7102
  import { fileURLToPath as fileURLToPath2 } from "url";
7103
+ import { readFileSync } from "fs";
6306
7104
  import { basename, dirname as dirname2, resolve } from "path";
6307
7105
 
6308
7106
  // src/core/launch-protocol.ts
@@ -6378,7 +7176,43 @@ try {
6378
7176
  terminateGroup();
6379
7177
  }
6380
7178
  `;
7179
+ var SUPPORTS_NATIVE_SPAWN_SYNC_TIMEOUT = (() => {
7180
+ const version2 = typeof Bun !== "undefined" ? Bun.version : "";
7181
+ const match = /^(\d+)\.(\d+)/.exec(version2);
7182
+ if (!match) return false;
7183
+ const major = Number(match[1]);
7184
+ const minor = Number(match[2]);
7185
+ return major > 1 || major === 1 && minor >= 2;
7186
+ })();
6381
7187
  function runBoundedOsCommand(command, args, captureOutput = true) {
7188
+ if (SUPPORTS_NATIVE_SPAWN_SYNC_TIMEOUT) {
7189
+ try {
7190
+ const result2 = Bun.spawnSync({
7191
+ cmd: [command, ...args],
7192
+ timeout: OS_COMMAND_TIMEOUT_MS,
7193
+ maxBuffer: OS_COMMAND_MAX_OUTPUT_BYTES,
7194
+ detached: process.platform !== "win32",
7195
+ stdin: "ignore",
7196
+ stdout: captureOutput ? "pipe" : "ignore",
7197
+ stderr: "ignore"
7198
+ });
7199
+ if (process.platform !== "win32" && result2.pid > 1) {
7200
+ try {
7201
+ process.kill(-result2.pid, "SIGKILL");
7202
+ } catch {
7203
+ }
7204
+ }
7205
+ if (result2.signalCode || result2.exitCode === null) {
7206
+ return { status: null, stdout: "" };
7207
+ }
7208
+ return {
7209
+ status: result2.exitCode,
7210
+ stdout: captureOutput && result2.stdout ? new TextDecoder().decode(result2.stdout) : ""
7211
+ };
7212
+ } catch {
7213
+ return { status: null, stdout: "" };
7214
+ }
7215
+ }
6382
7216
  const result = Bun.spawnSync({
6383
7217
  cmd: [
6384
7218
  process.execPath,
@@ -6436,7 +7270,28 @@ function inspectSpawnedProcessTreePresence(pid) {
6436
7270
  return "unknown";
6437
7271
  }
6438
7272
  }
7273
+ function inspectLinuxProcProcess(pid) {
7274
+ try {
7275
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
7276
+ const closeParen = stat.lastIndexOf(")");
7277
+ if (closeParen < 0) return null;
7278
+ const fields = stat.slice(closeParen + 2).trim().split(/\s+/);
7279
+ const processGroupId = Number(fields[2]);
7280
+ if (!Number.isInteger(processGroupId) || processGroupId <= 0) return null;
7281
+ const rawCmdline = readFileSync(`/proc/${pid}/cmdline`);
7282
+ if (rawCmdline.byteLength === 0) return null;
7283
+ const command = new TextDecoder().decode(rawCmdline).replace(/\0+$/, "").replaceAll("\0", " ").trim();
7284
+ if (!command) return null;
7285
+ return { processGroupId, command };
7286
+ } catch {
7287
+ return null;
7288
+ }
7289
+ }
6439
7290
  function inspectUnixProcess(pid) {
7291
+ if (process.platform === "linux") {
7292
+ const procInfo = inspectLinuxProcProcess(pid);
7293
+ if (procInfo) return procInfo;
7294
+ }
6440
7295
  const result = runBoundedOsCommand(
6441
7296
  "ps",
6442
7297
  ["-o", "pgid=", "-o", "command=", "-p", String(pid)]
@@ -6482,20 +7337,22 @@ function guardianLauncherPath() {
6482
7337
  function commandMatches(command, expectedExecutable, launchProtocol, expectedLaunchIdentity) {
6483
7338
  const expectedName = executableName(expectedExecutable);
6484
7339
  if (!expectedName) return false;
6485
- const tokens = commandTokens(command);
6486
7340
  if (launchProtocol === TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
6487
7341
  if (!isLaunchIdentity(expectedLaunchIdentity)) return false;
6488
- const expectedLauncher = guardianLauncherPath();
6489
- const launcherIndex = tokens.findIndex((token, index2) => index2 > 0 && index2 <= 3 && token.replaceAll("\\", "/") === expectedLauncher);
6490
- if (launcherIndex < 0) return false;
7342
+ const normalized = command.trim().replaceAll("\\", "/");
7343
+ const marker = ` ${guardianLauncherPath()} ${LAUNCH_IDENTITY_ARGUMENT} ${expectedLaunchIdentity} `;
7344
+ const markerIndex = normalized.indexOf(marker);
7345
+ if (markerIndex <= 0) return false;
7346
+ const runtime = normalized.slice(0, markerIndex);
6491
7347
  const runtimeName = executableName(process.execPath);
6492
- const hasRuntime = tokens.slice(0, launcherIndex).some((token) => executableName(token) === runtimeName || executableName(token) === "bun");
6493
- const identityArgumentIndex = launcherIndex + 1;
6494
- const launchIdentityIndex = launcherIndex + 2;
6495
- const executableIndex2 = launcherIndex + 3;
6496
- return hasRuntime && tokens[identityArgumentIndex] === LAUNCH_IDENTITY_ARGUMENT && tokens[launchIdentityIndex] === expectedLaunchIdentity && executableName(tokens[executableIndex2] ?? "") === expectedName && openCodeArgsMatch(tokens.slice(executableIndex2 + 1));
7348
+ const hasRuntime = [runtime, ...runtime.split(/\s+/)].some((token) => executableName(token) === runtimeName || executableName(token) === "bun");
7349
+ const invocation = normalized.slice(markerIndex + marker.length);
7350
+ const runIndex = invocation.indexOf(" run ");
7351
+ if (runIndex <= 0) return false;
7352
+ return hasRuntime && executableName(invocation.slice(0, runIndex)) === expectedName && openCodeArgsMatch(commandTokens(invocation.slice(runIndex + 1)));
6497
7353
  }
6498
7354
  if (launchProtocol != null) return false;
7355
+ const tokens = commandTokens(command);
6499
7356
  const executableIndex = tokens.findIndex((token, index2) => index2 <= 3 && executableName(token) === expectedName);
6500
7357
  if (executableIndex < 0) return false;
6501
7358
  return openCodeArgsMatch(tokens.slice(executableIndex + 1, executableIndex + 12));
@@ -6614,6 +7471,209 @@ var TaskRunService = class {
6614
7471
  }
6615
7472
  return result;
6616
7473
  }
7474
+ static async getLatestMetaByTaskIds(taskIds, options = {}) {
7475
+ const uniqueIds = [...new Set(taskIds.filter((id) => Number.isInteger(id) && id > 0))];
7476
+ if (uniqueIds.length === 0) return /* @__PURE__ */ new Map();
7477
+ const includePreview = options.includePreview ?? true;
7478
+ const previewExpr = includePreview ? "CASE WHEN r.log IS NULL THEN NULL WHEN r.status = 'failed' THEN substr(r.log, -512) ELSE substr(r.log, 1, 512) END" : "NULL";
7479
+ const sqlite2 = getSqlite();
7480
+ const rows = sqlite2.query(`
7481
+ WITH ranked AS (
7482
+ SELECT
7483
+ r.id,
7484
+ r.task_id,
7485
+ r.session_id,
7486
+ r.model,
7487
+ r.variant,
7488
+ r.status,
7489
+ r.started_at,
7490
+ r.finished_at,
7491
+ r.locked_at,
7492
+ r.locked_by,
7493
+ r.heartbeat_at,
7494
+ r.worker_pid,
7495
+ r.child_pid,
7496
+ r.launch_protocol,
7497
+ CASE WHEN r.log IS NOT NULL AND length(r.log) > 0 THEN 1 ELSE 0 END AS has_log,
7498
+ COALESCE(length(r.log), 0) AS log_length,
7499
+ ${previewExpr} AS log_preview,
7500
+ ROW_NUMBER() OVER (PARTITION BY r.task_id ORDER BY r.started_at DESC, r.id DESC) AS rn
7501
+ FROM task_runs AS r
7502
+ WHERE r.task_id IN (SELECT value FROM json_each(?))
7503
+ )
7504
+ SELECT
7505
+ id, task_id, session_id, model, variant, status,
7506
+ started_at, finished_at, locked_at, locked_by,
7507
+ heartbeat_at, worker_pid, child_pid, launch_protocol,
7508
+ has_log, log_length, log_preview
7509
+ FROM ranked
7510
+ WHERE rn = 1
7511
+ `).all(JSON.stringify(uniqueIds));
7512
+ const result = /* @__PURE__ */ new Map();
7513
+ for (const row of rows) {
7514
+ result.set(row.task_id, {
7515
+ id: Number(row.id),
7516
+ taskId: Number(row.task_id),
7517
+ sessionId: row.session_id,
7518
+ model: row.model,
7519
+ variant: row.variant,
7520
+ status: row.status,
7521
+ startedAt: row.started_at == null ? null : new Date(Number(row.started_at) * 1e3),
7522
+ finishedAt: row.finished_at == null ? null : new Date(Number(row.finished_at) * 1e3),
7523
+ lockedAt: row.locked_at,
7524
+ lockedBy: row.locked_by,
7525
+ heartbeatAt: row.heartbeat_at,
7526
+ workerPid: row.worker_pid,
7527
+ childPid: row.child_pid,
7528
+ launchProtocol: row.launch_protocol,
7529
+ hasLog: Number(row.has_log) === 1,
7530
+ logLength: Number(row.log_length ?? 0),
7531
+ logPreview: row.log_preview
7532
+ });
7533
+ }
7534
+ return result;
7535
+ }
7536
+ static async listMeta(options = {}) {
7537
+ const limit = options.limit ?? 50;
7538
+ const offset = options.offset ?? 0;
7539
+ const includePreview = options.includePreview ?? true;
7540
+ const conditions = [];
7541
+ if (options.taskId !== void 0) {
7542
+ conditions.push(eq(taskRuns3.taskId, options.taskId));
7543
+ }
7544
+ if (options.status !== void 0) {
7545
+ conditions.push(eq(taskRuns3.status, options.status));
7546
+ }
7547
+ if (options.legacyCwd) {
7548
+ conditions.push(or(isNull(tasks3.cwd), eq(tasks3.cwd, "")));
7549
+ } else if (options.cwd !== void 0) {
7550
+ conditions.push(eq(tasks3.cwd, options.cwd));
7551
+ }
7552
+ const selection = {
7553
+ id: taskRuns3.id,
7554
+ taskId: taskRuns3.taskId,
7555
+ sessionId: taskRuns3.sessionId,
7556
+ model: taskRuns3.model,
7557
+ variant: taskRuns3.variant,
7558
+ status: taskRuns3.status,
7559
+ startedAt: taskRuns3.startedAt,
7560
+ finishedAt: taskRuns3.finishedAt,
7561
+ lockedAt: taskRuns3.lockedAt,
7562
+ lockedBy: taskRuns3.lockedBy,
7563
+ heartbeatAt: taskRuns3.heartbeatAt,
7564
+ workerPid: taskRuns3.workerPid,
7565
+ childPid: taskRuns3.childPid,
7566
+ launchProtocol: taskRuns3.launchProtocol,
7567
+ hasLog: sql`CASE WHEN ${taskRuns3.log} IS NOT NULL AND length(${taskRuns3.log}) > 0 THEN 1 ELSE 0 END`,
7568
+ logLength: sql`COALESCE(length(${taskRuns3.log}), 0)`,
7569
+ logPreview: includePreview ? sql`CASE WHEN ${taskRuns3.log} IS NULL THEN NULL WHEN ${taskRuns3.status} = 'failed' THEN substr(${taskRuns3.log}, -512) ELSE substr(${taskRuns3.log}, 1, 512) END` : sql`NULL`
7570
+ };
7571
+ const needsTaskJoin = Boolean(options.legacyCwd) || options.cwd !== void 0;
7572
+ const baseQuery = needsTaskJoin ? db.select(selection).from(taskRuns3).innerJoin(tasks3, eq(taskRuns3.taskId, tasks3.id)).$dynamic() : db.select(selection).from(taskRuns3).$dynamic();
7573
+ const filteredQuery = conditions.length > 0 ? baseQuery.where(and(...conditions)) : baseQuery;
7574
+ const rows = await filteredQuery.orderBy(desc(taskRuns3.startedAt), desc(taskRuns3.id)).limit(limit).offset(offset);
7575
+ return rows.map((row) => ({
7576
+ id: row.id,
7577
+ taskId: row.taskId,
7578
+ sessionId: row.sessionId,
7579
+ model: row.model,
7580
+ variant: row.variant,
7581
+ status: row.status,
7582
+ startedAt: row.startedAt,
7583
+ finishedAt: row.finishedAt,
7584
+ lockedAt: row.lockedAt,
7585
+ lockedBy: row.lockedBy,
7586
+ heartbeatAt: row.heartbeatAt,
7587
+ workerPid: row.workerPid,
7588
+ childPid: row.childPid,
7589
+ launchProtocol: row.launchProtocol,
7590
+ hasLog: Number(row.hasLog) === 1,
7591
+ logLength: Number(row.logLength ?? 0),
7592
+ logPreview: row.logPreview
7593
+ }));
7594
+ }
7595
+ static async getLogById(id, options = {}) {
7596
+ const selection = {
7597
+ id: taskRuns3.id,
7598
+ taskId: taskRuns3.taskId,
7599
+ status: taskRuns3.status,
7600
+ sessionId: taskRuns3.sessionId,
7601
+ log: taskRuns3.log
7602
+ };
7603
+ const row = options.cwd !== void 0 ? await db.select(selection).from(taskRuns3).innerJoin(tasks3, eq(taskRuns3.taskId, tasks3.id)).where(
7604
+ options.taskId !== void 0 ? and(
7605
+ eq(taskRuns3.id, id),
7606
+ eq(tasks3.cwd, options.cwd),
7607
+ eq(taskRuns3.taskId, options.taskId)
7608
+ ) : and(eq(taskRuns3.id, id), eq(tasks3.cwd, options.cwd))
7609
+ ).get() : await db.select(selection).from(taskRuns3).where(
7610
+ options.taskId !== void 0 ? and(eq(taskRuns3.id, id), eq(taskRuns3.taskId, options.taskId)) : eq(taskRuns3.id, id)
7611
+ ).get();
7612
+ if (!row) return null;
7613
+ const fullLog = row.log ?? "";
7614
+ const totalLength = fullLog.length;
7615
+ if (options.tailLines !== void 0 && options.tailLines >= 0) {
7616
+ if (fullLog.length === 0) {
7617
+ return {
7618
+ id: row.id,
7619
+ taskId: row.taskId,
7620
+ status: row.status,
7621
+ sessionId: row.sessionId,
7622
+ log: "",
7623
+ totalLength: 0,
7624
+ truncated: false
7625
+ };
7626
+ }
7627
+ const lines = fullLog.split("\n");
7628
+ const truncated = lines.length > options.tailLines;
7629
+ const sliced = options.tailLines === 0 ? "" : lines.slice(-options.tailLines).join("\n");
7630
+ return {
7631
+ id: row.id,
7632
+ taskId: row.taskId,
7633
+ status: row.status,
7634
+ sessionId: row.sessionId,
7635
+ log: sliced,
7636
+ totalLength,
7637
+ truncated
7638
+ };
7639
+ }
7640
+ if (options.tailChars !== void 0 && options.tailChars >= 0) {
7641
+ const truncated = totalLength > options.tailChars;
7642
+ const sliced = options.tailChars === 0 ? "" : fullLog.slice(-options.tailChars);
7643
+ return {
7644
+ id: row.id,
7645
+ taskId: row.taskId,
7646
+ status: row.status,
7647
+ sessionId: row.sessionId,
7648
+ log: sliced,
7649
+ totalLength,
7650
+ truncated
7651
+ };
7652
+ }
7653
+ if (options.offset !== void 0 || options.limit !== void 0) {
7654
+ const start = Math.max(0, options.offset ?? 0);
7655
+ const end = options.limit !== void 0 ? start + Math.max(0, options.limit) : totalLength;
7656
+ const sliced = fullLog.slice(start, end);
7657
+ return {
7658
+ id: row.id,
7659
+ taskId: row.taskId,
7660
+ status: row.status,
7661
+ sessionId: row.sessionId,
7662
+ log: sliced,
7663
+ totalLength,
7664
+ truncated: start > 0 || end < totalLength
7665
+ };
7666
+ }
7667
+ return {
7668
+ id: row.id,
7669
+ taskId: row.taskId,
7670
+ status: row.status,
7671
+ sessionId: row.sessionId,
7672
+ log: fullLog,
7673
+ totalLength,
7674
+ truncated: false
7675
+ };
7676
+ }
6617
7677
  static async getStaleRuns(heartbeatTimeoutMs) {
6618
7678
  const cutoffMs = Date.now() - heartbeatTimeoutMs;
6619
7679
  const { tasks: tasksTable } = schema_exports;
@@ -6733,7 +7793,7 @@ ${note}` : note
6733
7793
  };
6734
7794
 
6735
7795
  // src/worker/index.ts
6736
- import { spawn } from "child_process";
7796
+ import { spawn as spawn2 } from "child_process";
6737
7797
 
6738
7798
  // src/gateway/health.ts
6739
7799
  var state = null;
@@ -6758,11 +7818,441 @@ function markGatewayFailure(component, error) {
6758
7818
  };
6759
7819
  }
6760
7820
 
7821
+ // src/gateway/events.ts
7822
+ var RUN_LOG_BUFFER_MAX_BYTES = 64 * 1024;
7823
+ var RUN_LOG_BUFFER_MAX_LINES = 2e3;
7824
+ var FINISHED_BUFFER_TTL_MS = 3e4;
7825
+ var GatewayEventBus = class {
7826
+ constructor(maxBufferBytes = RUN_LOG_BUFFER_MAX_BYTES, maxBufferLines = RUN_LOG_BUFFER_MAX_LINES, finishedBufferTtlMs = FINISHED_BUFFER_TTL_MS) {
7827
+ this.maxBufferBytes = maxBufferBytes;
7828
+ this.maxBufferLines = maxBufferLines;
7829
+ this.finishedBufferTtlMs = finishedBufferTtlMs;
7830
+ }
7831
+ maxBufferBytes;
7832
+ maxBufferLines;
7833
+ finishedBufferTtlMs;
7834
+ globalSubscribers = /* @__PURE__ */ new Set();
7835
+ runSubscribers = /* @__PURE__ */ new Map();
7836
+ runBuffers = /* @__PURE__ */ new Map();
7837
+ wakeHandlers = /* @__PURE__ */ new Set();
7838
+ subscribe(listener, options = {}) {
7839
+ const subscriber = {
7840
+ listener,
7841
+ excludeRunLogs: options.excludeRunLogs ?? false,
7842
+ types: options.types ? new Set(options.types) : null
7843
+ };
7844
+ this.globalSubscribers.add(subscriber);
7845
+ return () => {
7846
+ this.globalSubscribers.delete(subscriber);
7847
+ };
7848
+ }
7849
+ emit(event) {
7850
+ for (const subscriber of [...this.globalSubscribers]) {
7851
+ if (subscriber.excludeRunLogs && event.type === "run:log") continue;
7852
+ if (subscriber.types && !subscriber.types.has(event.type)) continue;
7853
+ try {
7854
+ subscriber.listener(event);
7855
+ } catch {
7856
+ }
7857
+ }
7858
+ }
7859
+ emitTaskChanged(payload) {
7860
+ const event = {
7861
+ type: "task:changed",
7862
+ ts: Date.now(),
7863
+ ...payload
7864
+ };
7865
+ this.emit(event);
7866
+ return event;
7867
+ }
7868
+ emitTemplateChanged(payload) {
7869
+ const event = {
7870
+ type: "template:changed",
7871
+ ts: Date.now(),
7872
+ ...payload
7873
+ };
7874
+ this.emit(event);
7875
+ return event;
7876
+ }
7877
+ emitRunStarted(payload) {
7878
+ const existing = this.runBuffers.get(payload.runId);
7879
+ if (existing?.cleanupTimer) {
7880
+ clearTimeout(existing.cleanupTimer);
7881
+ }
7882
+ this.runBuffers.set(payload.runId, {
7883
+ taskId: payload.taskId,
7884
+ entries: [],
7885
+ head: 0,
7886
+ totalBytes: 0,
7887
+ nextSeq: 1,
7888
+ finished: false,
7889
+ cleanupTimer: null
7890
+ });
7891
+ const event = {
7892
+ type: "run:started",
7893
+ ts: Date.now(),
7894
+ ...payload
7895
+ };
7896
+ this.emit(event);
7897
+ return event;
7898
+ }
7899
+ emitRunLog(runId, taskId, stream, line) {
7900
+ let buffer = this.runBuffers.get(runId);
7901
+ if (!buffer) {
7902
+ buffer = {
7903
+ taskId,
7904
+ entries: [],
7905
+ head: 0,
7906
+ totalBytes: 0,
7907
+ nextSeq: 1,
7908
+ finished: false,
7909
+ cleanupTimer: null
7910
+ };
7911
+ this.runBuffers.set(runId, buffer);
7912
+ }
7913
+ const event = {
7914
+ type: "run:log",
7915
+ ts: Date.now(),
7916
+ runId,
7917
+ taskId,
7918
+ stream,
7919
+ line,
7920
+ seq: buffer.nextSeq++
7921
+ };
7922
+ this.appendToBuffer(buffer, event);
7923
+ const subscribers = this.runSubscribers.get(runId);
7924
+ if (subscribers) {
7925
+ for (const listener of [...subscribers]) {
7926
+ try {
7927
+ listener(event);
7928
+ } catch {
7929
+ }
7930
+ }
7931
+ }
7932
+ this.emit(event);
7933
+ return event;
7934
+ }
7935
+ emitRunFinished(payload) {
7936
+ const event = {
7937
+ type: "run:finished",
7938
+ ts: Date.now(),
7939
+ ...payload
7940
+ };
7941
+ const buffer = this.runBuffers.get(payload.runId);
7942
+ if (buffer) {
7943
+ buffer.finished = true;
7944
+ if (buffer.cleanupTimer) clearTimeout(buffer.cleanupTimer);
7945
+ if (this.finishedBufferTtlMs <= 0) {
7946
+ this.runBuffers.delete(payload.runId);
7947
+ } else {
7948
+ buffer.cleanupTimer = setTimeout(() => {
7949
+ if (this.runBuffers.get(payload.runId) === buffer) {
7950
+ this.runBuffers.delete(payload.runId);
7951
+ }
7952
+ }, this.finishedBufferTtlMs);
7953
+ buffer.cleanupTimer.unref?.();
7954
+ }
7955
+ }
7956
+ const subscribers = this.runSubscribers.get(payload.runId);
7957
+ if (subscribers) {
7958
+ for (const listener of [...subscribers]) {
7959
+ try {
7960
+ listener(event);
7961
+ } catch {
7962
+ }
7963
+ }
7964
+ }
7965
+ this.emit(event);
7966
+ return event;
7967
+ }
7968
+ emitHealthChanged(payload) {
7969
+ const event = {
7970
+ type: "health:changed",
7971
+ ts: Date.now(),
7972
+ ...payload
7973
+ };
7974
+ this.emit(event);
7975
+ return event;
7976
+ }
7977
+ getRunLogSnapshot(runId) {
7978
+ const buffer = this.runBuffers.get(runId);
7979
+ if (!buffer) return null;
7980
+ return {
7981
+ active: !buffer.finished,
7982
+ finished: buffer.finished,
7983
+ lines: buffer.entries.slice(buffer.head).map((entry) => entry.event)
7984
+ };
7985
+ }
7986
+ subscribeRunLog(runId, listener) {
7987
+ let subscribers = this.runSubscribers.get(runId);
7988
+ if (!subscribers) {
7989
+ subscribers = /* @__PURE__ */ new Set();
7990
+ this.runSubscribers.set(runId, subscribers);
7991
+ }
7992
+ subscribers.add(listener);
7993
+ const buffer = this.runBuffers.get(runId);
7994
+ const snapshot = buffer ? buffer.entries.slice(buffer.head).map((entry) => entry.event) : [];
7995
+ return {
7996
+ snapshot,
7997
+ active: buffer != null && !buffer.finished,
7998
+ finished: buffer?.finished ?? false,
7999
+ unsubscribe: () => {
8000
+ const current = this.runSubscribers.get(runId);
8001
+ if (!current) return;
8002
+ current.delete(listener);
8003
+ if (current.size === 0) this.runSubscribers.delete(runId);
8004
+ }
8005
+ };
8006
+ }
8007
+ registerWakeHandler(handler) {
8008
+ this.wakeHandlers.add(handler);
8009
+ return () => {
8010
+ this.wakeHandlers.delete(handler);
8011
+ };
8012
+ }
8013
+ requestWake(reason) {
8014
+ for (const handler of [...this.wakeHandlers]) {
8015
+ try {
8016
+ handler(reason);
8017
+ } catch {
8018
+ }
8019
+ }
8020
+ }
8021
+ reset() {
8022
+ for (const buffer of this.runBuffers.values()) {
8023
+ if (buffer.cleanupTimer) clearTimeout(buffer.cleanupTimer);
8024
+ }
8025
+ this.runBuffers.clear();
8026
+ this.runSubscribers.clear();
8027
+ this.globalSubscribers.clear();
8028
+ this.wakeHandlers.clear();
8029
+ }
8030
+ appendToBuffer(buffer, event) {
8031
+ const bytes = Buffer.byteLength(event.line, "utf8") + 1;
8032
+ if (bytes >= this.maxBufferBytes) {
8033
+ const truncatedLine = Buffer.from(event.line, "utf8").subarray(Math.max(0, bytes - this.maxBufferBytes)).toString("utf8");
8034
+ const trimmedEvent = { ...event, line: truncatedLine };
8035
+ buffer.entries = [{ event: trimmedEvent, bytes: Buffer.byteLength(truncatedLine, "utf8") + 1 }];
8036
+ buffer.head = 0;
8037
+ buffer.totalBytes = buffer.entries[0].bytes;
8038
+ return;
8039
+ }
8040
+ buffer.entries.push({ event, bytes });
8041
+ buffer.totalBytes += bytes;
8042
+ while ((buffer.entries.length - buffer.head > this.maxBufferLines || buffer.totalBytes > this.maxBufferBytes) && buffer.head < buffer.entries.length - 1) {
8043
+ buffer.totalBytes -= buffer.entries[buffer.head].bytes;
8044
+ buffer.entries[buffer.head] = void 0;
8045
+ buffer.head += 1;
8046
+ }
8047
+ if (buffer.head >= 512 && buffer.head * 2 >= buffer.entries.length) {
8048
+ buffer.entries = buffer.entries.slice(buffer.head);
8049
+ buffer.head = 0;
8050
+ }
8051
+ }
8052
+ };
8053
+ var gatewayEvents = new GatewayEventBus();
8054
+
6761
8055
  // src/worker/index.ts
6762
8056
  import { fileURLToPath as fileURLToPath3 } from "url";
6763
8057
  import { existsSync as existsSync2 } from "fs";
6764
8058
  import { dirname as dirname3, join as join2 } from "path";
6765
8059
  import { randomUUID } from "crypto";
8060
+
8061
+ // src/worker/run-output.ts
8062
+ var SESSION_ID_PATTERN = /^ses_[A-Za-z0-9_]+$/;
8063
+ var RunOutput = class {
8064
+ constructor(maxChars, onSessionId, onLine) {
8065
+ this.maxChars = maxChars;
8066
+ this.onSessionId = onSessionId;
8067
+ this.onLine = onLine;
8068
+ }
8069
+ maxChars;
8070
+ onSessionId;
8071
+ onLine;
8072
+ lines = [];
8073
+ head = 0;
8074
+ totalChars = 0;
8075
+ partial = { stdout: "", stderr: "" };
8076
+ sessionId = null;
8077
+ push(stream, chunk) {
8078
+ const lines = (this.partial[stream] + chunk).split("\n");
8079
+ let rest = lines.pop() ?? "";
8080
+ if (rest.length > this.maxChars) {
8081
+ lines.push(rest);
8082
+ rest = "";
8083
+ }
8084
+ this.partial[stream] = rest;
8085
+ for (const line of lines) this.appendLine(stream, line);
8086
+ }
8087
+ flush() {
8088
+ for (const stream of ["stdout", "stderr"]) {
8089
+ const rest = this.partial[stream];
8090
+ this.partial[stream] = "";
8091
+ if (rest) this.appendLine(stream, rest);
8092
+ }
8093
+ }
8094
+ text() {
8095
+ if (this.head >= this.lines.length) return "";
8096
+ return this.head === 0 ? this.lines.join("") : this.lines.slice(this.head).join("");
8097
+ }
8098
+ appendLine(stream, line) {
8099
+ const clean = line.endsWith("\r") ? line.slice(0, -1) : line;
8100
+ this.pushBoundedLine(`${clean}
8101
+ `);
8102
+ if (this.onLine) {
8103
+ try {
8104
+ this.onLine(stream, clean);
8105
+ } catch {
8106
+ }
8107
+ }
8108
+ if (stream === "stdout" && this.sessionId === null) this.detectSessionId(clean);
8109
+ }
8110
+ pushBoundedLine(entry) {
8111
+ if (this.maxChars <= 0) return;
8112
+ if (entry.length >= this.maxChars) {
8113
+ const truncated = entry.slice(-this.maxChars);
8114
+ this.lines = [truncated];
8115
+ this.head = 0;
8116
+ this.totalChars = truncated.length;
8117
+ return;
8118
+ }
8119
+ this.lines.push(entry);
8120
+ this.totalChars += entry.length;
8121
+ while (this.totalChars > this.maxChars && this.head < this.lines.length) {
8122
+ const first = this.lines[this.head];
8123
+ if (this.totalChars - first.length >= this.maxChars) {
8124
+ this.totalChars -= first.length;
8125
+ this.lines[this.head] = "";
8126
+ this.head += 1;
8127
+ } else {
8128
+ const overflow = this.totalChars - this.maxChars;
8129
+ this.lines[this.head] = first.slice(overflow);
8130
+ this.totalChars = this.maxChars;
8131
+ break;
8132
+ }
8133
+ }
8134
+ if (this.head >= 1024 && this.head * 2 >= this.lines.length) {
8135
+ this.lines = this.lines.slice(this.head);
8136
+ this.head = 0;
8137
+ }
8138
+ }
8139
+ detectSessionId(line) {
8140
+ if (!line.startsWith("{") || !line.includes("ses_")) return;
8141
+ let event;
8142
+ try {
8143
+ event = JSON.parse(line);
8144
+ } catch {
8145
+ return;
8146
+ }
8147
+ const sessionId = topLevelSessionId(event);
8148
+ if (!sessionId) return;
8149
+ this.sessionId = sessionId;
8150
+ this.onSessionId(sessionId);
8151
+ }
8152
+ };
8153
+ function topLevelSessionId(event) {
8154
+ if (event === null || typeof event !== "object" || Array.isArray(event)) return null;
8155
+ const record = event;
8156
+ const value = record.sessionID ?? record.sessionId;
8157
+ return typeof value === "string" && SESSION_ID_PATTERN.test(value) ? value : null;
8158
+ }
8159
+
8160
+ // src/core/opencode-cli.ts
8161
+ import { spawn, spawnSync } from "child_process";
8162
+ var OpenCodeInvocationError = class extends Error {
8163
+ };
8164
+ var VERSION_TIMEOUT_MS = 15e3;
8165
+ var VERSION_CACHE_MS = 5 * 6e4;
8166
+ var versionCache = /* @__PURE__ */ new Map();
8167
+ function openCodeExecutable() {
8168
+ return process.env.SUPERTASK_OPENCODE_BIN ?? "opencode";
8169
+ }
8170
+ function parseOpenCodeVersion(output) {
8171
+ const match = /(?:^|\s|v)(\d+)\.(\d+)\.(\d+)(?:[-+][0-9A-Za-z.-]+)?/.exec(output.trim());
8172
+ if (!match) return null;
8173
+ const major = Number(match[1]);
8174
+ if (major !== 1 && major !== 2) return null;
8175
+ return { version: match[0].trim().replace(/^v/, ""), major };
8176
+ }
8177
+ function detectOpenCodeVersion(executable = openCodeExecutable(), options = {}) {
8178
+ const cached = versionCache.get(executable);
8179
+ if (options.useCache !== false && cached && cached.expiresAt > Date.now()) return cached.result;
8180
+ const result = new Promise((resolve2, reject) => {
8181
+ const child = spawn(executable, ["--version"], {
8182
+ cwd: options.cwd,
8183
+ env: process.env,
8184
+ stdio: ["ignore", "pipe", "pipe"]
8185
+ });
8186
+ let output = "";
8187
+ const timer = setTimeout(() => {
8188
+ child.kill("SIGKILL");
8189
+ reject(new Error(`OpenCode --version \u8D85\u8FC7 ${VERSION_TIMEOUT_MS}ms \u672A\u5B8C\u6210`));
8190
+ }, VERSION_TIMEOUT_MS);
8191
+ child.stdout?.on("data", (chunk) => {
8192
+ output += chunk.toString();
8193
+ });
8194
+ child.stderr?.on("data", (chunk) => {
8195
+ output += chunk.toString();
8196
+ });
8197
+ child.once("error", (error) => {
8198
+ clearTimeout(timer);
8199
+ reject(new Error(`\u65E0\u6CD5\u6267\u884C OpenCode\uFF08${executable}\uFF09\uFF1A${error.message}`));
8200
+ });
8201
+ child.once("close", (code) => {
8202
+ clearTimeout(timer);
8203
+ const parsed = code === 0 ? parseOpenCodeVersion(output) : null;
8204
+ if (parsed) resolve2(parsed);
8205
+ else reject(new Error(`\u65E0\u6CD5\u8BC6\u522B OpenCode \u7248\u672C\uFF08${executable} --version \u9000\u51FA\u7801 ${code ?? "null"}\uFF09\uFF1A${output.trim().slice(0, 200)}`));
8206
+ });
8207
+ });
8208
+ if (options.useCache !== false) {
8209
+ versionCache.set(executable, { expiresAt: Date.now() + VERSION_CACHE_MS, result });
8210
+ result.catch(() => {
8211
+ if (versionCache.get(executable)?.result === result) versionCache.delete(executable);
8212
+ });
8213
+ }
8214
+ return result;
8215
+ }
8216
+ function normalizeModelVariant2(target) {
8217
+ const hashIndex = target.model?.indexOf("#") ?? -1;
8218
+ if (!target.model || hashIndex < 0) return target;
8219
+ const model = target.model.slice(0, hashIndex);
8220
+ const embedded = target.model.slice(hashIndex + 1);
8221
+ if (!model || !embedded || embedded.includes("#")) {
8222
+ throw new OpenCodeInvocationError(`\u6A21\u578B\u683C\u5F0F\u65E0\u6548\uFF1A${target.model}`);
8223
+ }
8224
+ if (target.variant && target.variant !== embedded) {
8225
+ throw new OpenCodeInvocationError(`\u6A21\u578B ${target.model} \u5185\u5D4C\u7684 variant \u4E0E\u4EFB\u52A1 variant=${target.variant} \u51B2\u7A81`);
8226
+ }
8227
+ return { ...target, model, variant: embedded };
8228
+ }
8229
+ function buildOpenCodeRunArgs(major, input) {
8230
+ const target = normalizeModelVariant2(input);
8231
+ if (major === 1) {
8232
+ const args2 = ["run", "--agent", target.agent, "--format", "json"];
8233
+ if (target.model) args2.push("-m", target.model);
8234
+ if (target.variant) args2.push("--variant", target.variant);
8235
+ args2.push(target.prompt);
8236
+ return args2;
8237
+ }
8238
+ if (target.variant && !target.model) {
8239
+ throw new OpenCodeInvocationError(
8240
+ `OpenCode 2.x \u53EA\u80FD\u901A\u8FC7 -m provider/model#variant \u6307\u5B9A variant\uFF1B\u4EFB\u52A1\u8BBE\u7F6E\u4E86 variant=${target.variant} \u4F46\u672A\u6307\u5B9A\u6A21\u578B\uFF0C\u8BF7\u4E3A\u4EFB\u52A1\u8865\u5145\u6A21\u578B\u6216\u6E05\u7A7A variant`
8241
+ );
8242
+ }
8243
+ if (target.model && !/^[^/\s]+\/\S+$/.test(target.model)) {
8244
+ throw new OpenCodeInvocationError(`OpenCode 2.x \u9700\u8981 provider/model \u683C\u5F0F\u7684\u6A21\u578B\uFF1A${target.model}`);
8245
+ }
8246
+ const args = ["run", "--standalone", "--agent", target.agent, "--format", "json"];
8247
+ if (target.model) args.push("-m", target.variant ? `${target.model}#${target.variant}` : target.model);
8248
+ const title = target.title?.replace(/\s+/g, " ").trim();
8249
+ if (title) args.push(`--title=${title}`);
8250
+ if (target.archived === true) args.push("--archived");
8251
+ args.push("--", target.prompt);
8252
+ return args;
8253
+ }
8254
+
8255
+ // src/worker/index.ts
6766
8256
  var DEFAULT_MAX_OUTPUT_CHARS = 64 * 1024;
6767
8257
  var FORBIDDEN_AGENT = "supertask-runner";
6768
8258
  function runCommandContext(executable, args, cwd) {
@@ -6784,6 +8274,9 @@ var WorkerEngine = class {
6784
8274
  activeBatchIds = /* @__PURE__ */ new Set();
6785
8275
  runningTasks = /* @__PURE__ */ new Map();
6786
8276
  stopped = false;
8277
+ wakePending = false;
8278
+ consecutiveIdlePolls = 0;
8279
+ unsubscribeWake = null;
6787
8280
  pollTimer = null;
6788
8281
  heartbeatTimer = null;
6789
8282
  pollCyclePromise = null;
@@ -6796,7 +8289,7 @@ var WorkerEngine = class {
6796
8289
  settlementRetryIntervalMs;
6797
8290
  constructor(cfg, options = {}) {
6798
8291
  this.cfg = cfg.worker;
6799
- this.opencodeBin = options.opencodeBin ?? process.env.SUPERTASK_OPENCODE_BIN ?? "opencode";
8292
+ this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
6800
8293
  this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
6801
8294
  this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
6802
8295
  this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
@@ -6804,15 +8297,38 @@ var WorkerEngine = class {
6804
8297
  start() {
6805
8298
  assertWorkerProcessIsolationSupported();
6806
8299
  this.stopped = false;
8300
+ this.wakePending = false;
8301
+ this.consecutiveIdlePolls = 0;
6807
8302
  this.shutdownDeadlineMs = null;
8303
+ this.unsubscribeWake?.();
8304
+ this.unsubscribeWake = gatewayEvents.registerWakeHandler((reason) => this.wake(reason));
6808
8305
  markGatewayActivity("worker");
6809
8306
  this.poll();
6810
8307
  this.heartbeatTimer = setInterval(() => {
6811
8308
  this.runDetached(this.updateHeartbeats(), "worker heartbeat cycle failed");
6812
8309
  }, this.cfg.heartbeatIntervalMs);
6813
8310
  }
8311
+ wake(_reason) {
8312
+ if (this.stopped) return;
8313
+ this.consecutiveIdlePolls = 0;
8314
+ if (this.pollCyclePromise) {
8315
+ this.wakePending = true;
8316
+ return;
8317
+ }
8318
+ if (this.pollTimer) {
8319
+ clearTimeout(this.pollTimer);
8320
+ this.pollTimer = null;
8321
+ }
8322
+ this.pollTimer = setTimeout(() => {
8323
+ this.pollTimer = null;
8324
+ this.poll();
8325
+ }, 0);
8326
+ }
6814
8327
  async stop(gracePeriodMs = 0) {
6815
8328
  this.stopped = true;
8329
+ this.wakePending = false;
8330
+ this.unsubscribeWake?.();
8331
+ this.unsubscribeWake = null;
6816
8332
  this.shutdownDeadlineMs = Date.now() + Math.max(0, gracePeriodMs);
6817
8333
  for (const wake of [...this.settlementRetryWakeups]) wake();
6818
8334
  if (this.pollTimer) {
@@ -6822,7 +8338,7 @@ var WorkerEngine = class {
6822
8338
  if (this.pollCyclePromise) await this.pollCyclePromise;
6823
8339
  if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
6824
8340
  const deadline = Date.now() + gracePeriodMs;
6825
- while (this.runningTasks.size > 0 && Date.now() < deadline) {
8341
+ while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
6826
8342
  await Bun.sleep(Math.min(50, deadline - Date.now()));
6827
8343
  }
6828
8344
  }
@@ -6857,31 +8373,58 @@ var WorkerEngine = class {
6857
8373
  ownsRun(taskId, runId) {
6858
8374
  return this.runningTasks.get(taskId)?.runId === runId;
6859
8375
  }
8376
+ nextPollDelayMs() {
8377
+ const base = this.cfg.pollIntervalMs;
8378
+ if (base < 500 || this.consecutiveIdlePolls <= 1 || this.runningTasks.size > 0) {
8379
+ return base;
8380
+ }
8381
+ const maxIdleMs = Math.max(base, Math.min(base * 2, 2500));
8382
+ const step = Math.min(this.consecutiveIdlePolls - 1, 3);
8383
+ return Math.max(base, Math.min(maxIdleMs, Math.round(base * (1 + step * 0.5))));
8384
+ }
6860
8385
  poll() {
6861
8386
  if (this.stopped) return;
8387
+ if (this.pollTimer) {
8388
+ clearTimeout(this.pollTimer);
8389
+ this.pollTimer = null;
8390
+ }
8391
+ this.wakePending = false;
6862
8392
  markGatewayActivity("worker");
6863
- this.pollCyclePromise = this.tryDispatch().then((healthy) => {
8393
+ this.pollCyclePromise = this.tryDispatch().then(({ healthy, dispatched }) => {
8394
+ if (dispatched > 0) this.consecutiveIdlePolls = 0;
8395
+ else this.consecutiveIdlePolls += 1;
6864
8396
  if (healthy) markGatewaySuccess("worker");
6865
8397
  }).catch((err) => {
8398
+ this.consecutiveIdlePolls = 0;
6866
8399
  markGatewayFailure("worker", err);
6867
8400
  this.logError("worker poll failed", err);
6868
8401
  }).finally(() => {
6869
8402
  this.pollCyclePromise = null;
6870
8403
  if (this.stopped) return;
6871
- this.pollTimer = setTimeout(() => this.poll(), this.cfg.pollIntervalMs);
8404
+ if (this.wakePending) {
8405
+ this.wakePending = false;
8406
+ this.pollTimer = setTimeout(() => {
8407
+ this.pollTimer = null;
8408
+ this.poll();
8409
+ }, 0);
8410
+ return;
8411
+ }
8412
+ this.pollTimer = setTimeout(() => {
8413
+ this.pollTimer = null;
8414
+ this.poll();
8415
+ }, this.nextPollDelayMs());
6872
8416
  });
6873
8417
  }
6874
8418
  async tryDispatch() {
6875
8419
  await TaskService.resetOrphanRunningToPending();
6876
8420
  await this.reconcileCancelledTasks();
6877
8421
  await this.reconcileQuarantinedTasks();
6878
- const quarantined = [...this.runningTasks.values()].filter((entry) => entry.quarantined);
6879
- if (quarantined.length > 0) {
6880
- return false;
6881
- }
8422
+ let dispatched = 0;
6882
8423
  while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
6883
8424
  const databaseRunningCount = await TaskService.countRunning();
6884
8425
  if (databaseRunningCount >= this.cfg.maxConcurrency) break;
8426
+ const openCode = await detectOpenCodeVersion(this.opencodeBin);
8427
+ if (this.stopped) break;
6885
8428
  let task;
6886
8429
  try {
6887
8430
  task = await TaskService.claimNext({ excludedBatchIds: [...this.activeBatchIds] });
@@ -6894,8 +8437,15 @@ var WorkerEngine = class {
6894
8437
  await TaskService.resetRunningToPending([task.id]);
6895
8438
  break;
6896
8439
  }
8440
+ dispatched += 1;
6897
8441
  const batchId = normalizeTaskBatchId(task.batchId);
6898
8442
  if (batchId) this.activeBatchIds.add(batchId);
8443
+ gatewayEvents.emitTaskChanged({
8444
+ taskId: task.id,
8445
+ cwd: task.cwd,
8446
+ status: "running",
8447
+ reason: "task-claimed"
8448
+ });
6899
8449
  let runId = null;
6900
8450
  try {
6901
8451
  const launchIdentity = `gateway-${process.pid}:launch:${randomUUID()}`;
@@ -6930,7 +8480,22 @@ var WorkerEngine = class {
6930
8480
  this.releaseBatch(task);
6931
8481
  continue;
6932
8482
  }
6933
- await this.spawnTask(task, run.id, launchIdentity);
8483
+ let args;
8484
+ try {
8485
+ args = buildOpenCodeRunArgs(openCode.major, {
8486
+ agent: task.agent,
8487
+ model: this.resolveModel(task.model),
8488
+ variant: this.resolveVariant(task.variant),
8489
+ prompt: task.prompt,
8490
+ title: task.name
8491
+ });
8492
+ } catch (error) {
8493
+ if (!(error instanceof OpenCodeInvocationError)) throw error;
8494
+ await TaskService.failRun(task.id, run.id, `${error.message}\uFF08OpenCode ${openCode.version}\uFF09`, { setDeadLetter: true });
8495
+ this.releaseBatch(task);
8496
+ continue;
8497
+ }
8498
+ await this.spawnTask(task, run.id, launchIdentity, args);
6934
8499
  } catch (err) {
6935
8500
  this.releaseBatch(task);
6936
8501
  const message = `Worker \u542F\u52A8\u4EFB\u52A1\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}`;
@@ -6950,7 +8515,10 @@ var WorkerEngine = class {
6950
8515
  this.logError("task dispatch failed", err, task.id);
6951
8516
  }
6952
8517
  }
6953
- return ![...this.runningTasks.values()].some((entry) => entry.quarantined);
8518
+ return {
8519
+ healthy: ![...this.runningTasks.values()].some((entry) => entry.quarantined),
8520
+ dispatched
8521
+ };
6954
8522
  }
6955
8523
  launcherEntry() {
6956
8524
  const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
@@ -6963,15 +8531,9 @@ var WorkerEngine = class {
6963
8531
  if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
6964
8532
  return entry;
6965
8533
  }
6966
- async spawnTask(task, runId, launchIdentity) {
6967
- const model = this.resolveModel(task.model);
6968
- const variant = this.resolveVariant(task.variant);
6969
- const args = ["run", "--agent", task.agent, "--format", "json"];
6970
- if (model) args.push("-m", model);
6971
- if (variant) args.push("--variant", variant);
6972
- args.push(task.prompt);
8534
+ async spawnTask(task, runId, launchIdentity, args) {
6973
8535
  const cwd = task.cwd || process.cwd();
6974
- const child = spawn(process.execPath, [
8536
+ const child = spawn2(process.execPath, [
6975
8537
  this.launcherEntry(),
6976
8538
  LAUNCH_IDENTITY_ARGUMENT,
6977
8539
  launchIdentity,
@@ -6993,8 +8555,17 @@ var WorkerEngine = class {
6993
8555
  launchIdentity,
6994
8556
  child,
6995
8557
  commandContext: runCommandContext(this.opencodeBin, args, cwd),
6996
- output: "",
6997
- sessionId: null,
8558
+ output: new RunOutput(
8559
+ this.maxOutputChars,
8560
+ (sessionId) => {
8561
+ TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
8562
+ this.logError("sessionId update failed", err, task.id);
8563
+ });
8564
+ },
8565
+ (stream, line) => {
8566
+ gatewayEvents.emitRunLog(runId, task.id, stream, line);
8567
+ }
8568
+ ),
6998
8569
  timeoutTimer: null,
6999
8570
  termination: null,
7000
8571
  terminationPromise: null,
@@ -7004,19 +8575,10 @@ var WorkerEngine = class {
7004
8575
  settled: false
7005
8576
  };
7006
8577
  this.runningTasks.set(task.id, entry);
7007
- const handleData = (data) => {
7008
- const text2 = data.toString();
7009
- entry.output = (entry.output + text2).slice(-this.maxOutputChars);
7010
- const match = entry.output.match(/"sessionID"\s*:\s*"(ses_[^"]+)"/);
7011
- if (match?.[1] && match[1] !== entry.sessionId) {
7012
- entry.sessionId = match[1];
7013
- TaskRunService.updateSessionId(runId, match[1]).catch((err) => {
7014
- this.logError("sessionId update failed", err, task.id);
7015
- });
7016
- }
7017
- };
7018
- child.stdout?.on("data", handleData);
7019
- child.stderr?.on("data", handleData);
8578
+ child.stdout?.setEncoding("utf8");
8579
+ child.stderr?.setEncoding("utf8");
8580
+ child.stdout?.on("data", (chunk) => entry.output.push("stdout", chunk));
8581
+ child.stderr?.on("data", (chunk) => entry.output.push("stderr", chunk));
7020
8582
  child.on("message", (message) => {
7021
8583
  if (isMatchingDrainProof(message, entry.launchIdentity)) {
7022
8584
  entry.guardianDrained = true;
@@ -7028,9 +8590,17 @@ var WorkerEngine = class {
7028
8590
  }
7029
8591
  });
7030
8592
  let spawnError = null;
8593
+ let started = false;
7031
8594
  const spawned = new Promise((resolve2, reject) => {
7032
- child.once("spawn", resolve2);
7033
- child.once("error", (error) => {
8595
+ child.once("spawn", () => {
8596
+ started = true;
8597
+ resolve2();
8598
+ });
8599
+ child.on("error", (error) => {
8600
+ if (started) {
8601
+ this.logError("launcher process error", error, task.id);
8602
+ return;
8603
+ }
7034
8604
  spawnError = error;
7035
8605
  reject(error);
7036
8606
  });
@@ -7072,10 +8642,25 @@ var WorkerEngine = class {
7072
8642
  await this.terminateForFailure(entry, "\u8BB0\u5F55 Worker PID \u5931\u8D25\uFF1Arun \u5DF2\u4E0D\u518D\u5904\u4E8E running \u72B6\u6001");
7073
8643
  return;
7074
8644
  }
8645
+ if (this.stopped) {
8646
+ entry.termination = { kind: "shutdown", message: "Gateway shutdown" };
8647
+ try {
8648
+ child.stdin?.end();
8649
+ } catch {
8650
+ }
8651
+ return;
8652
+ }
7075
8653
  if (!child.stdin) {
7076
8654
  await this.terminateForFailure(entry, "\u653E\u884C OpenCode \u5931\u8D25\uFF1Alauncher stdin \u4E0D\u53EF\u7528");
7077
8655
  return;
7078
8656
  }
8657
+ gatewayEvents.emitRunStarted({
8658
+ runId,
8659
+ taskId: task.id,
8660
+ cwd: task.cwd,
8661
+ model: this.resolveModel(task.model),
8662
+ variant: this.resolveVariant(task.variant)
8663
+ });
7079
8664
  try {
7080
8665
  await new Promise((resolve2, reject) => {
7081
8666
  child.stdin.end("START\n", (error) => {
@@ -7090,6 +8675,7 @@ var WorkerEngine = class {
7090
8675
  );
7091
8676
  return;
7092
8677
  }
8678
+ if (entry.settled || entry.termination) return;
7093
8679
  const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
7094
8680
  if (timeoutMs > 0) {
7095
8681
  entry.timeoutTimer = setTimeout(() => {
@@ -7099,13 +8685,14 @@ var WorkerEngine = class {
7099
8685
  entry.task.id
7100
8686
  );
7101
8687
  }, timeoutMs);
8688
+ entry.timeoutTimer.unref?.();
7102
8689
  }
7103
8690
  }
7104
8691
  handleChildClose(entry, code, signal, spawnError) {
7105
8692
  if (entry.settled || entry.termination) return;
7106
8693
  if (!entry.guardianDrained) {
7107
- const pid = entry.child.pid;
7108
- const presence = pid == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid);
8694
+ const pid2 = entry.child.pid;
8695
+ const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
7109
8696
  const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
7110
8697
  if (presence !== "not-running") {
7111
8698
  if (entry.timeoutTimer) {
@@ -7127,6 +8714,22 @@ var WorkerEngine = class {
7127
8714
  );
7128
8715
  return;
7129
8716
  }
8717
+ const pid = entry.child.pid;
8718
+ if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
8719
+ if (entry.timeoutTimer) {
8720
+ clearTimeout(entry.timeoutTimer);
8721
+ entry.timeoutTimer = null;
8722
+ }
8723
+ const message = "guardian \u9000\u51FA\u540E\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u4ECD\u5B58\u6D3B\u6216\u72B6\u6001\u4E0D\u660E";
8724
+ entry.guardianDrained = false;
8725
+ entry.termination = { kind: "failure", message };
8726
+ entry.quarantined = true;
8727
+ markGatewayFailure(
8728
+ "worker",
8729
+ new Error(`${message}\uFF1B\u4EFB\u52A1 #${entry.task.id} \u4FDD\u6301\u9694\u79BB`)
8730
+ );
8731
+ return;
8732
+ }
7130
8733
  const failure = code === 0 ? void 0 : `${spawnError ? "\u65E0\u6CD5\u542F\u52A8 opencode" : "opencode \u9000\u51FA\u7801"} ${spawnError?.message ?? code ?? "null"}${signal ? `\uFF0C\u4FE1\u53F7 ${signal}` : ""}\uFF08agent=${entry.task.agent}\uFF0Cmodel=${this.resolveModel(entry.task.model) ?? "Agent/\u9ED8\u8BA4\u914D\u7F6E"}\uFF0Cvariant=${this.resolveVariant(entry.task.variant) ?? "Agent/\u6A21\u578B\u9ED8\u8BA4\u914D\u7F6E"}\uFF0Ccwd=${entry.task.cwd ?? process.cwd()}\uFF09`;
7131
8734
  this.runDetached(
7132
8735
  this.settleEntry(entry, code, failure),
@@ -7145,6 +8748,7 @@ var WorkerEngine = class {
7145
8748
  const settlement = this.commitEntryWithRetry(entry, code, failure).finally(() => {
7146
8749
  this.runningTasks.delete(entry.task.id);
7147
8750
  this.releaseBatch(entry.task);
8751
+ if (!this.stopped) this.wake("task-settled");
7148
8752
  });
7149
8753
  entry.settlementPromise = settlement;
7150
8754
  return settlement;
@@ -7192,6 +8796,19 @@ var WorkerEngine = class {
7192
8796
  const log2 = `${termination.message}${output2 ? `
7193
8797
  ${output2}` : ""}`;
7194
8798
  await TaskRunService.fail(entry.runId, log2);
8799
+ gatewayEvents.emitRunFinished({
8800
+ runId: entry.runId,
8801
+ taskId: entry.task.id,
8802
+ status: "failed",
8803
+ taskStatus: "cancelled",
8804
+ cwd: entry.task.cwd
8805
+ });
8806
+ gatewayEvents.emitTaskChanged({
8807
+ taskId: entry.task.id,
8808
+ cwd: entry.task.cwd,
8809
+ status: "cancelled",
8810
+ reason: "run-cancelled"
8811
+ });
7195
8812
  console.log(JSON.stringify({
7196
8813
  ts: (/* @__PURE__ */ new Date()).toISOString(),
7197
8814
  level: "info",
@@ -7208,6 +8825,19 @@ ${output}` : ""}` : output;
7208
8825
  if (code === 0 && !failure) {
7209
8826
  const completed = await TaskService.completeRun(entry.task.id, entry.runId, log);
7210
8827
  if (completed) {
8828
+ gatewayEvents.emitRunFinished({
8829
+ runId: entry.runId,
8830
+ taskId: entry.task.id,
8831
+ status: "done",
8832
+ taskStatus: "done",
8833
+ cwd: entry.task.cwd
8834
+ });
8835
+ gatewayEvents.emitTaskChanged({
8836
+ taskId: entry.task.id,
8837
+ cwd: entry.task.cwd,
8838
+ status: "done",
8839
+ reason: "run-done"
8840
+ });
7211
8841
  console.log(JSON.stringify({
7212
8842
  ts: (/* @__PURE__ */ new Date()).toISOString(),
7213
8843
  level: "info",
@@ -7217,6 +8847,12 @@ ${output}` : ""}` : output;
7217
8847
  return;
7218
8848
  }
7219
8849
  await TaskRunService.fail(entry.runId, "\u4EFB\u52A1\u6216\u6267\u884C\u8BB0\u5F55\u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8");
8850
+ gatewayEvents.emitRunFinished({
8851
+ runId: entry.runId,
8852
+ taskId: entry.task.id,
8853
+ status: "failed",
8854
+ cwd: entry.task.cwd
8855
+ });
7220
8856
  return;
7221
8857
  }
7222
8858
  const failed = await TaskService.failRun(entry.task.id, entry.runId, log);
@@ -7226,7 +8862,27 @@ ${output}` : ""}` : output;
7226
8862
  `${log}${log ? "\n" : ""}\u4EFB\u52A1\u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8`
7227
8863
  );
7228
8864
  this.logError("task failure state transition rejected", failure ?? "unknown failure", entry.task.id);
8865
+ gatewayEvents.emitRunFinished({
8866
+ runId: entry.runId,
8867
+ taskId: entry.task.id,
8868
+ status: "failed",
8869
+ cwd: entry.task.cwd
8870
+ });
8871
+ return;
7229
8872
  }
8873
+ gatewayEvents.emitRunFinished({
8874
+ runId: entry.runId,
8875
+ taskId: entry.task.id,
8876
+ status: "failed",
8877
+ taskStatus: failed.status,
8878
+ cwd: entry.task.cwd
8879
+ });
8880
+ gatewayEvents.emitTaskChanged({
8881
+ taskId: entry.task.id,
8882
+ cwd: entry.task.cwd,
8883
+ status: failed.status,
8884
+ reason: "run-failed"
8885
+ });
7230
8886
  console.error(JSON.stringify({
7231
8887
  ts: (/* @__PURE__ */ new Date()).toISOString(),
7232
8888
  level: "error",
@@ -7309,15 +8965,15 @@ ${output}` : ""}` : output;
7309
8965
  }
7310
8966
  }
7311
8967
  async killEntry(entry, initialSignal = "SIGTERM") {
7312
- if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null)) return true;
7313
8968
  const pid = entry.child.pid;
8969
+ if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
7314
8970
  if (!pid) return false;
7315
8971
  const initialResult = this.signalEntry(entry, initialSignal);
7316
8972
  if (initialResult === "not-running") return true;
7317
8973
  if (initialResult !== "signalled") return false;
7318
8974
  if (await waitForSpawnedProcessTreeExit(pid, 2500)) return true;
7319
8975
  if (initialSignal === "SIGKILL") return false;
7320
- if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null)) return true;
8976
+ if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && inspectSpawnedProcessTreePresence(pid) === "not-running") return true;
7321
8977
  const forcedResult = this.signalEntry(entry, "SIGKILL");
7322
8978
  if (forcedResult === "not-running") return true;
7323
8979
  if (forcedResult !== "signalled") return false;
@@ -7339,13 +8995,15 @@ ${output}` : ""}` : output;
7339
8995
  if (batchId) this.activeBatchIds.delete(batchId);
7340
8996
  }
7341
8997
  outputWithCommand(entry) {
7342
- const output = entry.output.trim();
8998
+ entry.output.flush();
8999
+ const output = entry.output.text().trim();
7343
9000
  return `${entry.commandContext}${output ? `
7344
9001
  ${output}` : ""}`;
7345
9002
  }
7346
9003
  resolveModel(taskModel) {
7347
- if (!taskModel || taskModel === "default") return null;
7348
- return taskModel;
9004
+ const normalized = taskModel?.trim();
9005
+ if (!normalized || normalized === "default") return null;
9006
+ return normalized;
7349
9007
  }
7350
9008
  resolveVariant(taskVariant) {
7351
9009
  return taskVariant?.trim() || null;