opencode-supertask 0.1.40 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +95 -1
- package/LICENSE +21 -0
- package/README.md +73 -39
- package/README.zh-CN.md +73 -39
- package/dist/cli/chunk-3PIYMBV3.js +45 -0
- package/dist/cli/chunk-3PIYMBV3.js.map +1 -0
- package/dist/cli/chunk-4FK5KE6G.js +111 -0
- package/dist/cli/chunk-4FK5KE6G.js.map +1 -0
- package/dist/cli/chunk-5VKFECHP.js +412 -0
- package/dist/cli/chunk-5VKFECHP.js.map +1 -0
- package/dist/cli/chunk-AZM76ISG.js +143 -0
- package/dist/cli/chunk-AZM76ISG.js.map +1 -0
- package/dist/cli/chunk-CMEP6IB4.js +9379 -0
- package/dist/cli/chunk-CMEP6IB4.js.map +1 -0
- package/dist/cli/chunk-DF56RPNL.js +65 -0
- package/dist/cli/chunk-DF56RPNL.js.map +1 -0
- package/dist/cli/chunk-DIJEKFBV.js +486 -0
- package/dist/cli/chunk-DIJEKFBV.js.map +1 -0
- package/dist/cli/chunk-DYXFSX5J.js +28 -0
- package/dist/cli/chunk-DYXFSX5J.js.map +1 -0
- package/dist/cli/chunk-EQWICVCJ.js +1701 -0
- package/dist/cli/chunk-EQWICVCJ.js.map +1 -0
- package/dist/cli/chunk-GHXFMJTS.js +42 -0
- package/dist/cli/chunk-GHXFMJTS.js.map +1 -0
- package/dist/cli/chunk-IYYBJHZF.js +28 -0
- package/dist/cli/chunk-IYYBJHZF.js.map +1 -0
- package/dist/cli/chunk-J34FWHQU.js +376 -0
- package/dist/cli/chunk-J34FWHQU.js.map +1 -0
- package/dist/cli/chunk-LX5CBJLP.js +121 -0
- package/dist/cli/chunk-LX5CBJLP.js.map +1 -0
- package/dist/cli/chunk-MVQ2XONT.js +139 -0
- package/dist/cli/chunk-MVQ2XONT.js.map +1 -0
- package/dist/cli/chunk-NCT3ETTK.js +1332 -0
- package/dist/cli/chunk-NCT3ETTK.js.map +1 -0
- package/dist/cli/chunk-YB7MYTE5.js +34 -0
- package/dist/cli/chunk-YB7MYTE5.js.map +1 -0
- package/dist/cli/chunk-YGELD2E5.js +5464 -0
- package/dist/cli/chunk-YGELD2E5.js.map +1 -0
- package/dist/cli/chunk-ZBH7YWXF.js +314 -0
- package/dist/cli/chunk-ZBH7YWXF.js.map +1 -0
- package/dist/cli/config-ED56ZLHY.js +20 -0
- package/dist/cli/config-ED56ZLHY.js.map +1 -0
- package/dist/cli/database-maintenance.service-F3IZU52F.js +16 -0
- package/dist/cli/database-maintenance.service-F3IZU52F.js.map +1 -0
- package/dist/cli/database-output-GH7F6X6D.js +165 -0
- package/dist/cli/database-output-GH7F6X6D.js.map +1 -0
- package/dist/cli/db-H7GIFWS2.js +26 -0
- package/dist/cli/db-H7GIFWS2.js.map +1 -0
- package/dist/cli/doctor-smoke-QXHF7UNN.js +150 -0
- package/dist/cli/doctor-smoke-QXHF7UNN.js.map +1 -0
- package/dist/cli/duration-Q3UMLO6F.js +10 -0
- package/dist/cli/duration-Q3UMLO6F.js.map +1 -0
- package/dist/cli/gateway-HNMX5ZTO.js +1738 -0
- package/dist/cli/gateway-HNMX5ZTO.js.map +1 -0
- package/dist/cli/gateway-wake-U4HTV56Q.js +14 -0
- package/dist/cli/gateway-wake-U4HTV56Q.js.map +1 -0
- package/dist/cli/index.js +626 -26342
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/job-templates-RPQJ4XXW.js +21 -0
- package/dist/cli/job-templates-RPQJ4XXW.js.map +1 -0
- package/dist/cli/logs-QD2N62KK.js +316 -0
- package/dist/cli/logs-QD2N62KK.js.map +1 -0
- package/dist/cli/output-2INTEUFQ.js +19 -0
- package/dist/cli/output-2INTEUFQ.js.map +1 -0
- package/dist/cli/pm2-WY644BUO.js +49 -0
- package/dist/cli/pm2-WY644BUO.js.map +1 -0
- package/dist/cli/task-run.service-QMDINJKG.js +15 -0
- package/dist/cli/task-run.service-QMDINJKG.js.map +1 -0
- package/dist/cli/task-template.service-SZBKGLCB.js +12 -0
- package/dist/cli/task-template.service-SZBKGLCB.js.map +1 -0
- package/dist/cli/task.service-ZVDJ6VSQ.js +19 -0
- package/dist/cli/task.service-ZVDJ6VSQ.js.map +1 -0
- package/dist/cli/update-FYD546I2.js +2058 -0
- package/dist/cli/update-FYD546I2.js.map +1 -0
- package/dist/cli/web-2S7DW7XA.js +9403 -0
- package/dist/cli/web-2S7DW7XA.js.map +1 -0
- package/dist/daemon/gateway-diagnostic-runner.d.ts +2 -0
- package/dist/daemon/gateway-diagnostic-runner.js +503 -0
- package/dist/daemon/gateway-diagnostic-runner.js.map +1 -0
- package/dist/gateway/index.d.ts +82 -1
- package/dist/gateway/index.js +9301 -2948
- package/dist/gateway/index.js.map +1 -1
- package/dist/plugin/supertask.d.ts +157 -1
- package/dist/plugin/supertask.js +5066 -1531
- package/dist/plugin/supertask.js.map +1 -1
- package/dist/pm2-cli-CEDhULjk.d.ts +40 -0
- package/dist/web/index.d.ts +36 -34
- package/dist/web/index.js +10030 -4341
- package/dist/web/index.js.map +1 -1
- package/dist/worker/index.d.ts +13 -0
- package/dist/worker/index.js +2147 -364
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/launcher.d.ts +46 -1
- package/dist/worker/launcher.js +218 -68
- package/dist/worker/launcher.js.map +1 -1
- package/drizzle/0009_little_weapon_omega.sql +7 -0
- package/drizzle/meta/0009_snapshot.json +681 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +15 -6
package/dist/worker/index.js
CHANGED
|
@@ -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 =
|
|
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,125 +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;
|
|
5541
|
-
|
|
6033
|
+
const exhausted = (task.status === "failed" || task.status === "pending") && (task.retryCount ?? 0) > maxRetries;
|
|
6034
|
+
const finishedAt = exhausted ? /* @__PURE__ */ new Date() : void 0;
|
|
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;
|
|
6043
|
+
if (exhausted && updated && finishedAt) {
|
|
6044
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
6045
|
+
}
|
|
6046
|
+
return updated;
|
|
5548
6047
|
}, { behavior: "immediate" });
|
|
5549
6048
|
}
|
|
5550
6049
|
static validateNewTask(data) {
|
|
5551
|
-
|
|
5552
|
-
|
|
5553
|
-
if (!data.prompt.trim()) throw new Error("prompt \u4E0D\u80FD\u4E3A\u7A7A");
|
|
5554
|
-
validateTaskWorkingDirectory(data.cwd);
|
|
5555
|
-
this.validateInteger("importance", data.importance, 1, 5);
|
|
5556
|
-
this.validateInteger("urgency", data.urgency, 1, 5);
|
|
5557
|
-
this.validateInteger("maxRetries", data.maxRetries, 0, 1e3);
|
|
5558
|
-
this.validateInteger("retryBackoffMs", data.retryBackoffMs, 0, 864e5);
|
|
5559
|
-
this.validateInteger("timeoutMs", data.timeoutMs, 1e3, 6048e5);
|
|
5560
|
-
this.validateInteger("dependsOn", data.dependsOn, 1, Number.MAX_SAFE_INTEGER);
|
|
5561
|
-
}
|
|
5562
|
-
static validateInteger(name, value, min, max) {
|
|
5563
|
-
if (value === void 0 || value === null) return;
|
|
5564
|
-
if (!Number.isInteger(value) || value < min || value > max) {
|
|
5565
|
-
throw new Error(`${name} \u5FC5\u987B\u662F ${min} \u5230 ${max} \u4E4B\u95F4\u7684\u6574\u6570`);
|
|
5566
|
-
}
|
|
6050
|
+
validateCommonTaskFields(data);
|
|
6051
|
+
validateIntegerField("dependsOn", data.dependsOn, 1, Number.MAX_SAFE_INTEGER);
|
|
5567
6052
|
}
|
|
5568
6053
|
static async next(scope = {}) {
|
|
5569
|
-
|
|
5570
|
-
|
|
5571
|
-
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
5577
|
-
|
|
5578
|
-
|
|
5579
|
-
|
|
5580
|
-
|
|
5581
|
-
|
|
5582
|
-
|
|
5583
|
-
);
|
|
5584
|
-
}
|
|
5585
|
-
const statusConditions = or(
|
|
5586
|
-
and(
|
|
5587
|
-
eq(tasks2.status, "pending"),
|
|
5588
|
-
retryAfterFilter
|
|
5589
|
-
),
|
|
5590
|
-
and(
|
|
5591
|
-
eq(tasks2.status, "failed"),
|
|
5592
|
-
sql`${tasks2.retryCount} <= ${tasks2.maxRetries}`,
|
|
5593
|
-
retryAfterFilter
|
|
5594
|
-
)
|
|
5595
|
-
);
|
|
5596
|
-
const conditions = [
|
|
5597
|
-
statusConditions,
|
|
5598
|
-
...baseConditions
|
|
5599
|
-
];
|
|
5600
|
-
if (batchFilter) {
|
|
5601
|
-
conditions.push(batchFilter);
|
|
5602
|
-
}
|
|
5603
|
-
const result = await db.select().from(tasks2).where(and(
|
|
5604
|
-
...conditions,
|
|
5605
|
-
or(
|
|
5606
|
-
isNull(tasks2.dependsOn),
|
|
5607
|
-
sql`EXISTS (
|
|
5608
|
-
SELECT 1 FROM tasks AS dependency_task
|
|
5609
|
-
WHERE dependency_task.id = ${tasks2.dependsOn}
|
|
5610
|
-
AND dependency_task.status = 'done'
|
|
5611
|
-
AND dependency_task.cwd IS ${tasks2.cwd}
|
|
5612
|
-
)`
|
|
5613
|
-
),
|
|
5614
|
-
or(
|
|
5615
|
-
isNull(tasks2.batchId),
|
|
5616
|
-
sql`trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS}) = ''`,
|
|
5617
|
-
sql`NOT EXISTS (
|
|
5618
|
-
SELECT 1 FROM tasks AS running_batch_task
|
|
5619
|
-
WHERE trim(running_batch_task.batch_id, ${TASK_BATCH_TRIM_CHARACTERS})
|
|
5620
|
-
= trim(${tasks2.batchId}, ${TASK_BATCH_TRIM_CHARACTERS})
|
|
5621
|
-
AND (
|
|
5622
|
-
running_batch_task.status = 'running'
|
|
5623
|
-
OR EXISTS (
|
|
5624
|
-
SELECT 1 FROM task_runs AS running_batch_run
|
|
5625
|
-
WHERE running_batch_run.task_id = running_batch_task.id
|
|
5626
|
-
AND running_batch_run.status = 'running'
|
|
5627
|
-
)
|
|
5628
|
-
)
|
|
5629
|
-
)`
|
|
5630
|
-
),
|
|
5631
|
-
sql`NOT EXISTS (
|
|
5632
|
-
SELECT 1 FROM task_runs AS candidate_active_run
|
|
5633
|
-
WHERE candidate_active_run.task_id = ${tasks2.id}
|
|
5634
|
-
AND candidate_active_run.status = 'running'
|
|
5635
|
-
)`
|
|
5636
|
-
)).orderBy(
|
|
5637
|
-
desc(tasks2.urgency),
|
|
5638
|
-
desc(tasks2.importance),
|
|
5639
|
-
asc(tasks2.createdAt),
|
|
5640
|
-
asc(tasks2.id)
|
|
5641
|
-
).limit(1);
|
|
5642
|
-
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" });
|
|
6059
|
+
}
|
|
6060
|
+
static async claimNext(scope = {}) {
|
|
6061
|
+
return db.transaction((tx) => {
|
|
6062
|
+
const candidateId = this.findNextCandidateId(scope);
|
|
6063
|
+
if (candidateId === null) return null;
|
|
6064
|
+
return tx.update(tasks2).set({
|
|
6065
|
+
status: "running",
|
|
6066
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
6067
|
+
finishedAt: null
|
|
6068
|
+
}).where(eq(tasks2.id, candidateId)).returning().get() ?? null;
|
|
6069
|
+
}, { behavior: "immediate" });
|
|
5643
6070
|
}
|
|
5644
6071
|
static async countRunning(scope = {}) {
|
|
5645
|
-
const
|
|
6072
|
+
const sqlite2 = getSqlite();
|
|
5646
6073
|
if (scope.batchId !== void 0) {
|
|
5647
6074
|
const batchId = normalizeTaskBatchId(scope.batchId);
|
|
5648
|
-
|
|
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);
|
|
5649
6104
|
}
|
|
5650
|
-
|
|
5651
|
-
const
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5655
|
-
|
|
5656
|
-
|
|
5657
|
-
|
|
5658
|
-
|
|
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);
|
|
5659
6115
|
}
|
|
5660
6116
|
static async start(id, scope = {}) {
|
|
5661
6117
|
const conditions = [
|
|
@@ -5701,9 +6157,10 @@ var TaskService = class {
|
|
|
5701
6157
|
const newRetryCount = (current.retryCount ?? 0) + 1;
|
|
5702
6158
|
const maxRetries = current.maxRetries ?? 3;
|
|
5703
6159
|
const isDeadLetter = options?.setDeadLetter ?? newRetryCount > maxRetries;
|
|
6160
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
5704
6161
|
const failed = tx.update(tasks2).set({
|
|
5705
6162
|
status: isDeadLetter ? "dead_letter" : "failed",
|
|
5706
|
-
finishedAt
|
|
6163
|
+
finishedAt,
|
|
5707
6164
|
resultLog: log,
|
|
5708
6165
|
retryCount: newRetryCount,
|
|
5709
6166
|
retryAfter: isDeadLetter ? null : options?.retryAfterMs ?? Date.now() + computeBackoff(
|
|
@@ -5712,12 +6169,7 @@ var TaskService = class {
|
|
|
5712
6169
|
)
|
|
5713
6170
|
}).where(and(eq(tasks2.id, id), eq(tasks2.status, "running"))).returning().get();
|
|
5714
6171
|
if (failed?.status === "dead_letter") {
|
|
5715
|
-
|
|
5716
|
-
status: "dead_letter",
|
|
5717
|
-
finishedAt: /* @__PURE__ */ new Date(),
|
|
5718
|
-
retryAfter: null,
|
|
5719
|
-
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
5720
|
-
}).where(blockedDependentsOf(id)).run();
|
|
6172
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
5721
6173
|
}
|
|
5722
6174
|
return failed ?? null;
|
|
5723
6175
|
}, { behavior: "immediate" });
|
|
@@ -5760,24 +6212,19 @@ var TaskService = class {
|
|
|
5760
6212
|
newRetryCount,
|
|
5761
6213
|
currentTask.retryBackoffMs ?? 3e4
|
|
5762
6214
|
);
|
|
5763
|
-
const
|
|
6215
|
+
const failedTask = tx.update(tasks2).set({
|
|
5764
6216
|
status: isDeadLetter ? "dead_letter" : "failed",
|
|
5765
6217
|
finishedAt,
|
|
5766
6218
|
resultLog: log,
|
|
5767
6219
|
retryCount: newRetryCount,
|
|
5768
6220
|
retryAfter
|
|
5769
6221
|
}).where(and(eq(tasks2.id, taskId), eq(tasks2.status, "running"))).returning().get();
|
|
5770
|
-
if (!
|
|
6222
|
+
if (!failedTask) return null;
|
|
5771
6223
|
tx.update(taskRuns2).set({ status: "failed", finishedAt, log }).where(and(eq(taskRuns2.id, runId), eq(taskRuns2.status, "running"))).run();
|
|
5772
|
-
if (
|
|
5773
|
-
|
|
5774
|
-
status: "dead_letter",
|
|
5775
|
-
finishedAt,
|
|
5776
|
-
retryAfter: null,
|
|
5777
|
-
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${taskId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
5778
|
-
}).where(blockedDependentsOf(taskId)).run();
|
|
6224
|
+
if (failedTask.status === "dead_letter") {
|
|
6225
|
+
this.cascadeDeadLetterDependents(tx, taskId, finishedAt);
|
|
5779
6226
|
}
|
|
5780
|
-
return
|
|
6227
|
+
return failedTask;
|
|
5781
6228
|
}, { behavior: "immediate" });
|
|
5782
6229
|
return failed;
|
|
5783
6230
|
}
|
|
@@ -5810,12 +6257,7 @@ var TaskService = class {
|
|
|
5810
6257
|
resultLog: log
|
|
5811
6258
|
}).where(and(eq(tasks2.id, taskId), eq(tasks2.status, "running"))).run();
|
|
5812
6259
|
if (recoveryStatus === "dead_letter") {
|
|
5813
|
-
|
|
5814
|
-
status: "dead_letter",
|
|
5815
|
-
finishedAt,
|
|
5816
|
-
retryAfter: null,
|
|
5817
|
-
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${taskId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
5818
|
-
}).where(blockedDependentsOf(taskId)).run();
|
|
6260
|
+
this.cascadeDeadLetterDependents(tx, taskId, finishedAt);
|
|
5819
6261
|
}
|
|
5820
6262
|
return {
|
|
5821
6263
|
status: recoveryStatus,
|
|
@@ -5879,15 +6321,6 @@ var TaskService = class {
|
|
|
5879
6321
|
)`).returning();
|
|
5880
6322
|
return result.length;
|
|
5881
6323
|
}
|
|
5882
|
-
static async rejectBlockedDependents(prerequisiteId) {
|
|
5883
|
-
const result = await db.update(tasks2).set({
|
|
5884
|
-
status: "dead_letter",
|
|
5885
|
-
finishedAt: /* @__PURE__ */ new Date(),
|
|
5886
|
-
retryAfter: null,
|
|
5887
|
-
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${prerequisiteId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
5888
|
-
}).where(blockedDependentsOf(prerequisiteId)).returning({ id: tasks2.id });
|
|
5889
|
-
return result.length;
|
|
5890
|
-
}
|
|
5891
6324
|
static async markPendingForRetry(id, retryAfterMs, retryCount) {
|
|
5892
6325
|
const result = await db.update(tasks2).set({
|
|
5893
6326
|
status: "pending",
|
|
@@ -5903,12 +6336,7 @@ var TaskService = class {
|
|
|
5903
6336
|
const finishedAt = /* @__PURE__ */ new Date();
|
|
5904
6337
|
const task = tx.update(tasks2).set({ status: "dead_letter", finishedAt, retryCount }).where(eq(tasks2.id, id)).returning().get();
|
|
5905
6338
|
if (!task) return null;
|
|
5906
|
-
|
|
5907
|
-
status: "dead_letter",
|
|
5908
|
-
finishedAt,
|
|
5909
|
-
retryAfter: null,
|
|
5910
|
-
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
5911
|
-
}).where(blockedDependentsOf(id)).run();
|
|
6339
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
5912
6340
|
return task;
|
|
5913
6341
|
}, { behavior: "immediate" });
|
|
5914
6342
|
}
|
|
@@ -5961,15 +6389,49 @@ var TaskService = class {
|
|
|
5961
6389
|
retryAfter: null
|
|
5962
6390
|
}).where(and(...conditions)).returning().get();
|
|
5963
6391
|
if (!task) return null;
|
|
5964
|
-
|
|
5965
|
-
status: "dead_letter",
|
|
5966
|
-
finishedAt,
|
|
5967
|
-
retryAfter: null,
|
|
5968
|
-
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${id} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
5969
|
-
}).where(blockedDependentsOf(id)).run();
|
|
6392
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
5970
6393
|
return task;
|
|
5971
6394
|
}, { behavior: "immediate" });
|
|
5972
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
|
+
}
|
|
5973
6435
|
static async retry(id, scope = {}) {
|
|
5974
6436
|
const conditions = [
|
|
5975
6437
|
eq(tasks2.id, id),
|
|
@@ -5984,19 +6446,82 @@ var TaskService = class {
|
|
|
5984
6446
|
retryCount: 0
|
|
5985
6447
|
}).where(and(...conditions, hasViableDependency())).returning().get() ?? null, { behavior: "immediate" });
|
|
5986
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
|
+
}
|
|
5987
6490
|
static async retryBatch(batchId, scope = {}) {
|
|
5988
6491
|
const normalizedBatchId = normalizeTaskBatchId(batchId);
|
|
5989
6492
|
if (!normalizedBatchId) return 0;
|
|
5990
6493
|
const sqlite2 = getSqlite();
|
|
5991
6494
|
const scopeFilter = scope.cwd === void 0 ? "" : "AND candidate.cwd = ?";
|
|
5992
|
-
const parameters = scope.cwd === void 0 ? [
|
|
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
|
+
];
|
|
5993
6509
|
return db.transaction(() => sqlite2.query(`
|
|
5994
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
|
+
),
|
|
5995
6520
|
candidate(id, cwd, depends_on) AS MATERIALIZED (
|
|
5996
6521
|
SELECT candidate.id, candidate.cwd, candidate.depends_on
|
|
5997
6522
|
FROM tasks AS candidate
|
|
5998
|
-
|
|
5999
|
-
|
|
6523
|
+
INNER JOIN matched_batch_ids AS mb ON mb.id = candidate.id
|
|
6524
|
+
WHERE candidate.status IN ('failed', 'dead_letter')
|
|
6000
6525
|
${scopeFilter}
|
|
6001
6526
|
),
|
|
6002
6527
|
retryable(id, cwd, depends_on) AS (
|
|
@@ -6047,32 +6572,33 @@ var TaskService = class {
|
|
|
6047
6572
|
return result[0] || null;
|
|
6048
6573
|
}
|
|
6049
6574
|
static async list(options = {}) {
|
|
6050
|
-
|
|
6051
|
-
|
|
6052
|
-
|
|
6053
|
-
|
|
6054
|
-
|
|
6055
|
-
|
|
6056
|
-
|
|
6057
|
-
|
|
6058
|
-
|
|
6059
|
-
|
|
6060
|
-
|
|
6061
|
-
|
|
6062
|
-
|
|
6063
|
-
|
|
6064
|
-
|
|
6065
|
-
|
|
6066
|
-
|
|
6067
|
-
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
|
|
6071
|
-
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
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();
|
|
6076
6602
|
if (conditions.length > 0) {
|
|
6077
6603
|
query = query.where(and(...conditions));
|
|
6078
6604
|
}
|
|
@@ -6085,14 +6611,57 @@ var TaskService = class {
|
|
|
6085
6611
|
}
|
|
6086
6612
|
return await query;
|
|
6087
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
|
+
}
|
|
6088
6657
|
static async stats(options = {}) {
|
|
6089
6658
|
const conditions = [];
|
|
6090
6659
|
if (options.batchId !== void 0) {
|
|
6091
6660
|
const batchId = normalizeTaskBatchId(options.batchId);
|
|
6092
|
-
conditions.push(batchId ?
|
|
6661
|
+
conditions.push(batchId ? batchIdMatchCondition(batchId) : sql`0`);
|
|
6093
6662
|
}
|
|
6094
6663
|
if (options.legacyCwd) {
|
|
6095
|
-
conditions.push(
|
|
6664
|
+
conditions.push(legacyCwdCondition());
|
|
6096
6665
|
} else if (options.cwd !== void 0) {
|
|
6097
6666
|
conditions.push(eq(tasks2.cwd, options.cwd));
|
|
6098
6667
|
}
|
|
@@ -6118,32 +6687,204 @@ var TaskService = class {
|
|
|
6118
6687
|
}
|
|
6119
6688
|
return stats;
|
|
6120
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
|
+
}
|
|
6121
6876
|
static async projectSummaries(limit = 100) {
|
|
6122
|
-
|
|
6123
|
-
const
|
|
6124
|
-
|
|
6125
|
-
|
|
6126
|
-
|
|
6127
|
-
|
|
6128
|
-
|
|
6129
|
-
|
|
6130
|
-
|
|
6131
|
-
|
|
6132
|
-
|
|
6133
|
-
) THEN 1 ELSE 0 END)`,
|
|
6134
|
-
failed: sql`sum(CASE WHEN ${tasks2.status} IN ('failed', 'dead_letter') THEN 1 ELSE 0 END)`,
|
|
6135
|
-
done: sql`sum(CASE WHEN ${tasks2.status} = 'done' THEN 1 ELSE 0 END)`,
|
|
6136
|
-
lastCreatedAt
|
|
6137
|
-
}).from(tasks2).where(sql`${tasks2.cwd} IS NOT NULL AND trim(${tasks2.cwd}) <> ''`).groupBy(tasks2.cwd).orderBy(desc(lastCreatedAt), desc(lastTaskId)).limit(limit);
|
|
6138
|
-
return rows.flatMap((row) => row.cwd === null ? [] : [{
|
|
6139
|
-
cwd: row.cwd,
|
|
6140
|
-
total: Number(row.total),
|
|
6141
|
-
pending: Number(row.pending),
|
|
6142
|
-
running: Number(row.running),
|
|
6143
|
-
failed: Number(row.failed),
|
|
6144
|
-
done: Number(row.done),
|
|
6145
|
-
lastCreatedAt: row.lastCreatedAt === null ? null : Number(row.lastCreatedAt) * 1e3
|
|
6146
|
-
}]);
|
|
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
|
+
}));
|
|
6147
6888
|
}
|
|
6148
6889
|
static async delete(id, scope = {}) {
|
|
6149
6890
|
const conditions = [
|
|
@@ -6176,84 +6917,160 @@ var TaskService = class {
|
|
|
6176
6917
|
`\u4EFB\u52A1 #${id} \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u53D6\u6D88\u4EFB\u52A1\u5E76\u7B49\u5F85\u6267\u884C\u8FDB\u7A0B\u9000\u51FA`
|
|
6177
6918
|
);
|
|
6178
6919
|
}
|
|
6179
|
-
static async
|
|
6180
|
-
const
|
|
6181
|
-
|
|
6182
|
-
|
|
6183
|
-
|
|
6184
|
-
|
|
6185
|
-
|
|
6186
|
-
|
|
6187
|
-
|
|
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
|
+
}
|
|
6979
|
+
static async deleteOlderThan(retentionDays, shouldStop = () => false) {
|
|
6980
|
+
const cutoffSec = Math.floor(Date.now() / 1e3) - retentionDays * 86400;
|
|
6981
|
+
const batchSize = 500;
|
|
6982
|
+
const sqlite2 = getSqlite();
|
|
6983
|
+
cleanupInvocation += 1;
|
|
6984
|
+
const candidateTable = `cleanup_candidates_${process.pid}_${cleanupInvocation}`;
|
|
6985
|
+
let deletedTotal = 0;
|
|
6986
|
+
sqlite2.exec(`
|
|
6987
|
+
CREATE TEMP TABLE ${candidateTable} (
|
|
6188
6988
|
id INTEGER NOT NULL PRIMARY KEY
|
|
6189
6989
|
) WITHOUT ROWID;
|
|
6190
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
|
+
`);
|
|
6191
7054
|
try {
|
|
6192
7055
|
let ceilingId = null;
|
|
6193
7056
|
while (true) {
|
|
6194
7057
|
if (shouldStop()) return deletedTotal;
|
|
6195
7058
|
const batch = db.transaction(() => {
|
|
6196
|
-
|
|
6197
|
-
const
|
|
6198
|
-
const rawCandidateStatement = sqlite2.query(`
|
|
6199
|
-
INSERT INTO ${candidateTable}(id)
|
|
6200
|
-
SELECT candidate.id
|
|
6201
|
-
FROM tasks AS candidate NOT INDEXED
|
|
6202
|
-
WHERE candidate.status IN ('done', 'dead_letter', 'cancelled')
|
|
6203
|
-
AND candidate.finished_at IS NOT NULL
|
|
6204
|
-
AND candidate.finished_at < ?
|
|
6205
|
-
${ceilingPredicate}
|
|
6206
|
-
AND NOT EXISTS (
|
|
6207
|
-
SELECT 1 FROM task_runs AS active_run
|
|
6208
|
-
WHERE active_run.task_id = candidate.id
|
|
6209
|
-
AND active_run.status = 'running'
|
|
6210
|
-
)
|
|
6211
|
-
ORDER BY candidate.id DESC
|
|
6212
|
-
LIMIT ?
|
|
6213
|
-
`);
|
|
6214
|
-
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;
|
|
6215
7061
|
if (rawCount === 0) return { deleted: 0, nextCeilingId: null };
|
|
6216
|
-
const rawPage =
|
|
6217
|
-
|
|
6218
|
-
`).get();
|
|
6219
|
-
sqlite2.query(`
|
|
6220
|
-
DELETE FROM ${candidateTable}
|
|
6221
|
-
WHERE EXISTS (
|
|
6222
|
-
SELECT 1 FROM tasks AS anomalous
|
|
6223
|
-
WHERE anomalous.id = ${candidateTable}.id
|
|
6224
|
-
AND anomalous.depends_on IS NOT NULL
|
|
6225
|
-
AND anomalous.depends_on >= anomalous.id
|
|
6226
|
-
)
|
|
6227
|
-
`).run();
|
|
7062
|
+
const rawPage = minCandidateStmt.get();
|
|
7063
|
+
pruneAnomalousStmt.run();
|
|
6228
7064
|
while (true) {
|
|
6229
|
-
const pruned =
|
|
6230
|
-
DELETE FROM ${candidateTable}
|
|
6231
|
-
WHERE EXISTS (
|
|
6232
|
-
SELECT 1 FROM tasks AS dependent_task
|
|
6233
|
-
WHERE dependent_task.depends_on = ${candidateTable}.id
|
|
6234
|
-
AND NOT EXISTS (
|
|
6235
|
-
SELECT 1 FROM ${candidateTable} AS selected_dependent
|
|
6236
|
-
WHERE selected_dependent.id = dependent_task.id
|
|
6237
|
-
)
|
|
6238
|
-
)
|
|
6239
|
-
`).run().changes;
|
|
7065
|
+
const pruned = pruneDependentStmt.run().changes;
|
|
6240
7066
|
if (pruned === 0) break;
|
|
6241
7067
|
}
|
|
6242
|
-
const selected =
|
|
6243
|
-
SELECT count(*) AS count FROM ${candidateTable}
|
|
6244
|
-
`).get();
|
|
7068
|
+
const selected = countSelectedStmt.get();
|
|
6245
7069
|
if (selected.count === 0) {
|
|
6246
7070
|
return { deleted: 0, nextCeilingId: rawPage.nextCeilingId };
|
|
6247
7071
|
}
|
|
6248
|
-
|
|
6249
|
-
|
|
6250
|
-
WHERE id IN (SELECT id FROM ${candidateTable})
|
|
6251
|
-
`).run();
|
|
6252
|
-
const remaining = sqlite2.query(`
|
|
6253
|
-
SELECT count(*) AS count
|
|
6254
|
-
FROM tasks
|
|
6255
|
-
WHERE id IN (SELECT id FROM ${candidateTable})
|
|
6256
|
-
`).get();
|
|
7072
|
+
deleteTasksStmt.run();
|
|
7073
|
+
const remaining = verifyRemainingStmt.get();
|
|
6257
7074
|
if (remaining.count !== 0) {
|
|
6258
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");
|
|
6259
7076
|
}
|
|
@@ -6267,14 +7084,23 @@ var TaskService = class {
|
|
|
6267
7084
|
}
|
|
6268
7085
|
return deletedTotal;
|
|
6269
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();
|
|
6270
7096
|
sqlite2.exec(`DROP TABLE IF EXISTS ${candidateTable}`);
|
|
6271
7097
|
}
|
|
6272
7098
|
}
|
|
6273
7099
|
};
|
|
6274
7100
|
|
|
6275
7101
|
// src/core/process-control.ts
|
|
6276
|
-
import { spawnSync } from "child_process";
|
|
6277
7102
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
7103
|
+
import { readFileSync } from "fs";
|
|
6278
7104
|
import { basename, dirname as dirname2, resolve } from "path";
|
|
6279
7105
|
|
|
6280
7106
|
// src/core/launch-protocol.ts
|
|
@@ -6298,6 +7124,120 @@ function isMatchingDrainProof(message, launchIdentity) {
|
|
|
6298
7124
|
|
|
6299
7125
|
// src/core/process-control.ts
|
|
6300
7126
|
var OS_COMMAND_TIMEOUT_MS = 2e3;
|
|
7127
|
+
var OS_COMMAND_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
7128
|
+
var OS_COMMAND_RESULT_MARKER = "\n\0supertask-os-command-result:";
|
|
7129
|
+
var BOUNDED_OS_COMMAND_RUNNER = `
|
|
7130
|
+
const { writeSync } = await import('fs');
|
|
7131
|
+
let child;
|
|
7132
|
+
try {
|
|
7133
|
+
child = Bun.spawn(process.argv.slice(2), {
|
|
7134
|
+
stdin: 'ignore',
|
|
7135
|
+
stdout: 'pipe',
|
|
7136
|
+
stderr: 'ignore',
|
|
7137
|
+
});
|
|
7138
|
+
} catch {
|
|
7139
|
+
process.exit(127);
|
|
7140
|
+
}
|
|
7141
|
+
const terminateGroup = () => {
|
|
7142
|
+
if (process.platform !== 'win32') {
|
|
7143
|
+
try {
|
|
7144
|
+
process.kill(-process.pid, 'SIGKILL');
|
|
7145
|
+
} catch {
|
|
7146
|
+
}
|
|
7147
|
+
}
|
|
7148
|
+
try {
|
|
7149
|
+
child.kill('SIGKILL');
|
|
7150
|
+
} catch {
|
|
7151
|
+
}
|
|
7152
|
+
process.exit(1);
|
|
7153
|
+
};
|
|
7154
|
+
const timer = setTimeout(terminateGroup, ${OS_COMMAND_TIMEOUT_MS});
|
|
7155
|
+
try {
|
|
7156
|
+
const chunks = [];
|
|
7157
|
+
let outputBytes = 0;
|
|
7158
|
+
const readOutput = async () => {
|
|
7159
|
+
const reader = child.stdout.getReader();
|
|
7160
|
+
while (true) {
|
|
7161
|
+
const { done, value } = await reader.read();
|
|
7162
|
+
if (done) return;
|
|
7163
|
+
outputBytes += value.byteLength;
|
|
7164
|
+
if (outputBytes > ${OS_COMMAND_MAX_OUTPUT_BYTES}) terminateGroup();
|
|
7165
|
+
chunks.push(value);
|
|
7166
|
+
}
|
|
7167
|
+
};
|
|
7168
|
+
const [exitCode] = await Promise.all([child.exited, readOutput()]);
|
|
7169
|
+
clearTimeout(timer);
|
|
7170
|
+
for (const chunk of chunks) writeSync(1, chunk);
|
|
7171
|
+
writeSync(1, ${JSON.stringify(OS_COMMAND_RESULT_MARKER)} + String(exitCode));
|
|
7172
|
+
if (process.platform !== 'win32') terminateGroup();
|
|
7173
|
+
process.exit(0);
|
|
7174
|
+
} catch {
|
|
7175
|
+
clearTimeout(timer);
|
|
7176
|
+
terminateGroup();
|
|
7177
|
+
}
|
|
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
|
+
})();
|
|
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
|
+
}
|
|
7216
|
+
const result = Bun.spawnSync({
|
|
7217
|
+
cmd: [
|
|
7218
|
+
process.execPath,
|
|
7219
|
+
"-e",
|
|
7220
|
+
BOUNDED_OS_COMMAND_RUNNER,
|
|
7221
|
+
"supertask-os-command",
|
|
7222
|
+
command,
|
|
7223
|
+
...args
|
|
7224
|
+
],
|
|
7225
|
+
detached: process.platform !== "win32",
|
|
7226
|
+
maxBuffer: OS_COMMAND_MAX_OUTPUT_BYTES + 1024,
|
|
7227
|
+
stdin: "ignore",
|
|
7228
|
+
stdout: "pipe",
|
|
7229
|
+
stderr: "ignore"
|
|
7230
|
+
});
|
|
7231
|
+
const output = new TextDecoder().decode(result.stdout);
|
|
7232
|
+
const markerIndex = output.lastIndexOf(OS_COMMAND_RESULT_MARKER);
|
|
7233
|
+
if (markerIndex < 0) return { status: null, stdout: "" };
|
|
7234
|
+
const statusText = output.slice(markerIndex + OS_COMMAND_RESULT_MARKER.length);
|
|
7235
|
+
if (!/^\d+$/.test(statusText)) return { status: null, stdout: "" };
|
|
7236
|
+
return {
|
|
7237
|
+
status: Number(statusText),
|
|
7238
|
+
stdout: captureOutput ? output.slice(0, markerIndex) : ""
|
|
7239
|
+
};
|
|
7240
|
+
}
|
|
6301
7241
|
function isSafePid(pid) {
|
|
6302
7242
|
return Number.isInteger(pid) && pid > 1 && pid !== process.pid;
|
|
6303
7243
|
}
|
|
@@ -6330,13 +7270,32 @@ function inspectSpawnedProcessTreePresence(pid) {
|
|
|
6330
7270
|
return "unknown";
|
|
6331
7271
|
}
|
|
6332
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
|
+
}
|
|
6333
7290
|
function inspectUnixProcess(pid) {
|
|
6334
|
-
|
|
6335
|
-
|
|
6336
|
-
|
|
6337
|
-
|
|
6338
|
-
|
|
6339
|
-
|
|
7291
|
+
if (process.platform === "linux") {
|
|
7292
|
+
const procInfo = inspectLinuxProcProcess(pid);
|
|
7293
|
+
if (procInfo) return procInfo;
|
|
7294
|
+
}
|
|
7295
|
+
const result = runBoundedOsCommand(
|
|
7296
|
+
"ps",
|
|
7297
|
+
["-o", "pgid=", "-o", "command=", "-p", String(pid)]
|
|
7298
|
+
);
|
|
6340
7299
|
if (result.status !== 0) return null;
|
|
6341
7300
|
const match = result.stdout.trim().match(/^(\d+)\s+(.+)$/s);
|
|
6342
7301
|
if (!match) return null;
|
|
@@ -6344,30 +7303,18 @@ function inspectUnixProcess(pid) {
|
|
|
6344
7303
|
}
|
|
6345
7304
|
function inspectWindowsCommand(pid) {
|
|
6346
7305
|
const script = `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`;
|
|
6347
|
-
const result =
|
|
7306
|
+
const result = runBoundedOsCommand(
|
|
6348
7307
|
"powershell.exe",
|
|
6349
|
-
["-NoProfile", "-NonInteractive", "-Command", script]
|
|
6350
|
-
{
|
|
6351
|
-
encoding: "utf8",
|
|
6352
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
6353
|
-
timeout: OS_COMMAND_TIMEOUT_MS,
|
|
6354
|
-
killSignal: "SIGKILL"
|
|
6355
|
-
}
|
|
7308
|
+
["-NoProfile", "-NonInteractive", "-Command", script]
|
|
6356
7309
|
);
|
|
6357
7310
|
if (result.status !== 0) return null;
|
|
6358
7311
|
return result.stdout.trim() || null;
|
|
6359
7312
|
}
|
|
6360
7313
|
function inspectWindowsProcessTree(rootPid) {
|
|
6361
7314
|
const script = `$root=${rootPid}; $all=@(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId); $ids=New-Object 'System.Collections.Generic.HashSet[int]'; [void]$ids.Add($root); do { $added=$false; foreach($p in $all) { if($ids.Contains([int]$p.ParentProcessId) -and $ids.Add([int]$p.ProcessId)) { $added=$true } } } while($added); $all | Where-Object { $ids.Contains([int]$_.ProcessId) } | Select-Object -ExpandProperty ProcessId`;
|
|
6362
|
-
const result =
|
|
7315
|
+
const result = runBoundedOsCommand(
|
|
6363
7316
|
"powershell.exe",
|
|
6364
|
-
["-NoProfile", "-NonInteractive", "-Command", script]
|
|
6365
|
-
{
|
|
6366
|
-
encoding: "utf8",
|
|
6367
|
-
stdio: ["ignore", "pipe", "ignore"],
|
|
6368
|
-
timeout: OS_COMMAND_TIMEOUT_MS,
|
|
6369
|
-
killSignal: "SIGKILL"
|
|
6370
|
-
}
|
|
7317
|
+
["-NoProfile", "-NonInteractive", "-Command", script]
|
|
6371
7318
|
);
|
|
6372
7319
|
if (result.status !== 0) return null;
|
|
6373
7320
|
return result.stdout.split(/\s+/).filter(Boolean).map(Number).filter((pid) => Number.isInteger(pid) && pid > 0);
|
|
@@ -6390,20 +7337,22 @@ function guardianLauncherPath() {
|
|
|
6390
7337
|
function commandMatches(command, expectedExecutable, launchProtocol, expectedLaunchIdentity) {
|
|
6391
7338
|
const expectedName = executableName(expectedExecutable);
|
|
6392
7339
|
if (!expectedName) return false;
|
|
6393
|
-
const tokens = commandTokens(command);
|
|
6394
7340
|
if (launchProtocol === TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
6395
7341
|
if (!isLaunchIdentity(expectedLaunchIdentity)) return false;
|
|
6396
|
-
const
|
|
6397
|
-
const
|
|
6398
|
-
|
|
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);
|
|
6399
7347
|
const runtimeName = executableName(process.execPath);
|
|
6400
|
-
const hasRuntime =
|
|
6401
|
-
const
|
|
6402
|
-
const
|
|
6403
|
-
|
|
6404
|
-
return hasRuntime &&
|
|
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)));
|
|
6405
7353
|
}
|
|
6406
7354
|
if (launchProtocol != null) return false;
|
|
7355
|
+
const tokens = commandTokens(command);
|
|
6407
7356
|
const executableIndex = tokens.findIndex((token, index2) => index2 <= 3 && executableName(token) === expectedName);
|
|
6408
7357
|
if (executableIndex < 0) return false;
|
|
6409
7358
|
return openCodeArgsMatch(tokens.slice(executableIndex + 1, executableIndex + 12));
|
|
@@ -6424,11 +7373,7 @@ function signalRecordedProcessTreeWithResult(pid, signal, expectedExecutable, la
|
|
|
6424
7373
|
}
|
|
6425
7374
|
const args = ["/PID", String(pid), "/T"];
|
|
6426
7375
|
if (signal === "SIGKILL") args.push("/F");
|
|
6427
|
-
const status =
|
|
6428
|
-
stdio: "ignore",
|
|
6429
|
-
timeout: OS_COMMAND_TIMEOUT_MS,
|
|
6430
|
-
killSignal: "SIGKILL"
|
|
6431
|
-
}).status;
|
|
7376
|
+
const status = runBoundedOsCommand("taskkill", args, false).status;
|
|
6432
7377
|
if (status === 0) return "signalled";
|
|
6433
7378
|
return isProcessAlive(pid) ? "signal-failed" : absentLeaderResult(pid);
|
|
6434
7379
|
}
|
|
@@ -6526,6 +7471,209 @@ var TaskRunService = class {
|
|
|
6526
7471
|
}
|
|
6527
7472
|
return result;
|
|
6528
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
|
+
}
|
|
6529
7677
|
static async getStaleRuns(heartbeatTimeoutMs) {
|
|
6530
7678
|
const cutoffMs = Date.now() - heartbeatTimeoutMs;
|
|
6531
7679
|
const { tasks: tasksTable } = schema_exports;
|
|
@@ -6599,7 +7747,7 @@ var TaskRunService = class {
|
|
|
6599
7747
|
}
|
|
6600
7748
|
if (current.childPid != null) {
|
|
6601
7749
|
throw new LegacyRunAbandonConflictError(
|
|
6602
|
-
`run #${runId} \u5DF2\u8BB0\u5F55 child PID ${current.childPid}\uFF0C\u5FC5\u987B\u7531 Worker/Watchdog \u786E\u8BA4\u8FDB\u7A0B\
|
|
7750
|
+
`run #${runId} \u5DF2\u8BB0\u5F55 child PID ${current.childPid}\uFF0C\u5FC5\u987B\u7531 Worker/Watchdog \u786E\u8BA4\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A`
|
|
6603
7751
|
);
|
|
6604
7752
|
}
|
|
6605
7753
|
if (current.workerPid != null && isProcessAlive(current.workerPid)) {
|
|
@@ -6645,7 +7793,7 @@ ${note}` : note
|
|
|
6645
7793
|
};
|
|
6646
7794
|
|
|
6647
7795
|
// src/worker/index.ts
|
|
6648
|
-
import { spawn } from "child_process";
|
|
7796
|
+
import { spawn as spawn2 } from "child_process";
|
|
6649
7797
|
|
|
6650
7798
|
// src/gateway/health.ts
|
|
6651
7799
|
var state = null;
|
|
@@ -6670,11 +7818,441 @@ function markGatewayFailure(component, error) {
|
|
|
6670
7818
|
};
|
|
6671
7819
|
}
|
|
6672
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
|
+
|
|
6673
8055
|
// src/worker/index.ts
|
|
6674
8056
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
6675
8057
|
import { existsSync as existsSync2 } from "fs";
|
|
6676
8058
|
import { dirname as dirname3, join as join2 } from "path";
|
|
6677
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
|
|
6678
8256
|
var DEFAULT_MAX_OUTPUT_CHARS = 64 * 1024;
|
|
6679
8257
|
var FORBIDDEN_AGENT = "supertask-runner";
|
|
6680
8258
|
function runCommandContext(executable, args, cwd) {
|
|
@@ -6688,7 +8266,7 @@ function runCommandContext(executable, args, cwd) {
|
|
|
6688
8266
|
function assertWorkerProcessIsolationSupported(platform = process.platform) {
|
|
6689
8267
|
if (platform === "win32") {
|
|
6690
8268
|
throw new Error(
|
|
6691
|
-
"Windows Worker \u5DF2\u5B89\u5168\u7981\u7528\uFF1A\u5F53\u524D\u8FD0\u884C\u65F6\u65E0\u6CD5\u7528 Job Object \
|
|
8269
|
+
"Windows Worker \u5DF2\u5B89\u5168\u7981\u7528\uFF1A\u5F53\u524D\u8FD0\u884C\u65F6\u65E0\u6CD5\u7528 Job Object \u63D0\u4F9B\u7B49\u4EF7\u7684\u53D7\u7BA1\u8FDB\u7A0B\u9694\u79BB\u4E0E\u6392\u7A7A\u8BC1\u660E"
|
|
6692
8270
|
);
|
|
6693
8271
|
}
|
|
6694
8272
|
}
|
|
@@ -6696,28 +8274,63 @@ var WorkerEngine = class {
|
|
|
6696
8274
|
activeBatchIds = /* @__PURE__ */ new Set();
|
|
6697
8275
|
runningTasks = /* @__PURE__ */ new Map();
|
|
6698
8276
|
stopped = false;
|
|
8277
|
+
wakePending = false;
|
|
8278
|
+
consecutiveIdlePolls = 0;
|
|
8279
|
+
unsubscribeWake = null;
|
|
6699
8280
|
pollTimer = null;
|
|
6700
8281
|
heartbeatTimer = null;
|
|
6701
8282
|
pollCyclePromise = null;
|
|
8283
|
+
shutdownDeadlineMs = null;
|
|
8284
|
+
settlementRetryWakeups = /* @__PURE__ */ new Set();
|
|
6702
8285
|
cfg;
|
|
6703
8286
|
opencodeBin;
|
|
6704
8287
|
maxOutputChars;
|
|
8288
|
+
settlementRetryDelaysMs;
|
|
8289
|
+
settlementRetryIntervalMs;
|
|
6705
8290
|
constructor(cfg, options = {}) {
|
|
6706
8291
|
this.cfg = cfg.worker;
|
|
6707
|
-
this.opencodeBin = options.opencodeBin ??
|
|
8292
|
+
this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
|
|
6708
8293
|
this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
|
|
8294
|
+
this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
|
|
8295
|
+
this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
|
|
6709
8296
|
}
|
|
6710
8297
|
start() {
|
|
6711
8298
|
assertWorkerProcessIsolationSupported();
|
|
6712
8299
|
this.stopped = false;
|
|
8300
|
+
this.wakePending = false;
|
|
8301
|
+
this.consecutiveIdlePolls = 0;
|
|
8302
|
+
this.shutdownDeadlineMs = null;
|
|
8303
|
+
this.unsubscribeWake?.();
|
|
8304
|
+
this.unsubscribeWake = gatewayEvents.registerWakeHandler((reason) => this.wake(reason));
|
|
6713
8305
|
markGatewayActivity("worker");
|
|
6714
8306
|
this.poll();
|
|
6715
8307
|
this.heartbeatTimer = setInterval(() => {
|
|
6716
8308
|
this.runDetached(this.updateHeartbeats(), "worker heartbeat cycle failed");
|
|
6717
8309
|
}, this.cfg.heartbeatIntervalMs);
|
|
6718
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
|
+
}
|
|
6719
8327
|
async stop(gracePeriodMs = 0) {
|
|
6720
8328
|
this.stopped = true;
|
|
8329
|
+
this.wakePending = false;
|
|
8330
|
+
this.unsubscribeWake?.();
|
|
8331
|
+
this.unsubscribeWake = null;
|
|
8332
|
+
this.shutdownDeadlineMs = Date.now() + Math.max(0, gracePeriodMs);
|
|
8333
|
+
for (const wake of [...this.settlementRetryWakeups]) wake();
|
|
6721
8334
|
if (this.pollTimer) {
|
|
6722
8335
|
clearTimeout(this.pollTimer);
|
|
6723
8336
|
this.pollTimer = null;
|
|
@@ -6725,7 +8338,7 @@ var WorkerEngine = class {
|
|
|
6725
8338
|
if (this.pollCyclePromise) await this.pollCyclePromise;
|
|
6726
8339
|
if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
|
|
6727
8340
|
const deadline = Date.now() + gracePeriodMs;
|
|
6728
|
-
while (this.runningTasks.
|
|
8341
|
+
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
6729
8342
|
await Bun.sleep(Math.min(50, deadline - Date.now()));
|
|
6730
8343
|
}
|
|
6731
8344
|
}
|
|
@@ -6760,48 +8373,79 @@ var WorkerEngine = class {
|
|
|
6760
8373
|
ownsRun(taskId, runId) {
|
|
6761
8374
|
return this.runningTasks.get(taskId)?.runId === runId;
|
|
6762
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
|
+
}
|
|
6763
8385
|
poll() {
|
|
6764
8386
|
if (this.stopped) return;
|
|
8387
|
+
if (this.pollTimer) {
|
|
8388
|
+
clearTimeout(this.pollTimer);
|
|
8389
|
+
this.pollTimer = null;
|
|
8390
|
+
}
|
|
8391
|
+
this.wakePending = false;
|
|
6765
8392
|
markGatewayActivity("worker");
|
|
6766
|
-
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;
|
|
6767
8396
|
if (healthy) markGatewaySuccess("worker");
|
|
6768
8397
|
}).catch((err) => {
|
|
8398
|
+
this.consecutiveIdlePolls = 0;
|
|
6769
8399
|
markGatewayFailure("worker", err);
|
|
6770
8400
|
this.logError("worker poll failed", err);
|
|
6771
8401
|
}).finally(() => {
|
|
6772
8402
|
this.pollCyclePromise = null;
|
|
6773
8403
|
if (this.stopped) return;
|
|
6774
|
-
|
|
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());
|
|
6775
8416
|
});
|
|
6776
8417
|
}
|
|
6777
8418
|
async tryDispatch() {
|
|
6778
8419
|
await TaskService.resetOrphanRunningToPending();
|
|
6779
8420
|
await this.reconcileCancelledTasks();
|
|
6780
8421
|
await this.reconcileQuarantinedTasks();
|
|
6781
|
-
|
|
6782
|
-
if (quarantined.length > 0) {
|
|
6783
|
-
return false;
|
|
6784
|
-
}
|
|
8422
|
+
let dispatched = 0;
|
|
6785
8423
|
while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
|
|
6786
8424
|
const databaseRunningCount = await TaskService.countRunning();
|
|
6787
8425
|
if (databaseRunningCount >= this.cfg.maxConcurrency) break;
|
|
8426
|
+
const openCode = await detectOpenCodeVersion(this.opencodeBin);
|
|
8427
|
+
if (this.stopped) break;
|
|
6788
8428
|
let task;
|
|
6789
8429
|
try {
|
|
6790
|
-
task = await TaskService.
|
|
8430
|
+
task = await TaskService.claimNext({ excludedBatchIds: [...this.activeBatchIds] });
|
|
6791
8431
|
} catch (err) {
|
|
6792
8432
|
this.logError("task claim failed", err);
|
|
6793
8433
|
throw err;
|
|
6794
8434
|
}
|
|
6795
8435
|
if (!task) break;
|
|
6796
|
-
if (this.stopped) break;
|
|
6797
|
-
if (!await TaskService.start(task.id)) continue;
|
|
6798
|
-
const batchId = normalizeTaskBatchId(task.batchId);
|
|
6799
|
-
if (batchId) this.activeBatchIds.add(batchId);
|
|
6800
8436
|
if (this.stopped) {
|
|
6801
8437
|
await TaskService.resetRunningToPending([task.id]);
|
|
6802
|
-
this.releaseBatch(task);
|
|
6803
8438
|
break;
|
|
6804
8439
|
}
|
|
8440
|
+
dispatched += 1;
|
|
8441
|
+
const batchId = normalizeTaskBatchId(task.batchId);
|
|
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
|
+
});
|
|
6805
8449
|
let runId = null;
|
|
6806
8450
|
try {
|
|
6807
8451
|
const launchIdentity = `gateway-${process.pid}:launch:${randomUUID()}`;
|
|
@@ -6836,7 +8480,22 @@ var WorkerEngine = class {
|
|
|
6836
8480
|
this.releaseBatch(task);
|
|
6837
8481
|
continue;
|
|
6838
8482
|
}
|
|
6839
|
-
|
|
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);
|
|
6840
8499
|
} catch (err) {
|
|
6841
8500
|
this.releaseBatch(task);
|
|
6842
8501
|
const message = `Worker \u542F\u52A8\u4EFB\u52A1\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}`;
|
|
@@ -6856,7 +8515,10 @@ var WorkerEngine = class {
|
|
|
6856
8515
|
this.logError("task dispatch failed", err, task.id);
|
|
6857
8516
|
}
|
|
6858
8517
|
}
|
|
6859
|
-
return
|
|
8518
|
+
return {
|
|
8519
|
+
healthy: ![...this.runningTasks.values()].some((entry) => entry.quarantined),
|
|
8520
|
+
dispatched
|
|
8521
|
+
};
|
|
6860
8522
|
}
|
|
6861
8523
|
launcherEntry() {
|
|
6862
8524
|
const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
|
|
@@ -6869,15 +8531,9 @@ var WorkerEngine = class {
|
|
|
6869
8531
|
if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
|
|
6870
8532
|
return entry;
|
|
6871
8533
|
}
|
|
6872
|
-
async spawnTask(task, runId, launchIdentity) {
|
|
6873
|
-
const model = this.resolveModel(task.model);
|
|
6874
|
-
const variant = this.resolveVariant(task.variant);
|
|
6875
|
-
const args = ["run", "--agent", task.agent, "--format", "json"];
|
|
6876
|
-
if (model) args.push("-m", model);
|
|
6877
|
-
if (variant) args.push("--variant", variant);
|
|
6878
|
-
args.push(task.prompt);
|
|
8534
|
+
async spawnTask(task, runId, launchIdentity, args) {
|
|
6879
8535
|
const cwd = task.cwd || process.cwd();
|
|
6880
|
-
const child =
|
|
8536
|
+
const child = spawn2(process.execPath, [
|
|
6881
8537
|
this.launcherEntry(),
|
|
6882
8538
|
LAUNCH_IDENTITY_ARGUMENT,
|
|
6883
8539
|
launchIdentity,
|
|
@@ -6899,8 +8555,17 @@ var WorkerEngine = class {
|
|
|
6899
8555
|
launchIdentity,
|
|
6900
8556
|
child,
|
|
6901
8557
|
commandContext: runCommandContext(this.opencodeBin, args, cwd),
|
|
6902
|
-
output:
|
|
6903
|
-
|
|
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
|
+
),
|
|
6904
8569
|
timeoutTimer: null,
|
|
6905
8570
|
termination: null,
|
|
6906
8571
|
terminationPromise: null,
|
|
@@ -6910,19 +8575,10 @@ var WorkerEngine = class {
|
|
|
6910
8575
|
settled: false
|
|
6911
8576
|
};
|
|
6912
8577
|
this.runningTasks.set(task.id, entry);
|
|
6913
|
-
|
|
6914
|
-
|
|
6915
|
-
|
|
6916
|
-
|
|
6917
|
-
if (match?.[1] && match[1] !== entry.sessionId) {
|
|
6918
|
-
entry.sessionId = match[1];
|
|
6919
|
-
TaskRunService.updateSessionId(runId, match[1]).catch((err) => {
|
|
6920
|
-
this.logError("sessionId update failed", err, task.id);
|
|
6921
|
-
});
|
|
6922
|
-
}
|
|
6923
|
-
};
|
|
6924
|
-
child.stdout?.on("data", handleData);
|
|
6925
|
-
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));
|
|
6926
8582
|
child.on("message", (message) => {
|
|
6927
8583
|
if (isMatchingDrainProof(message, entry.launchIdentity)) {
|
|
6928
8584
|
entry.guardianDrained = true;
|
|
@@ -6934,9 +8590,17 @@ var WorkerEngine = class {
|
|
|
6934
8590
|
}
|
|
6935
8591
|
});
|
|
6936
8592
|
let spawnError = null;
|
|
8593
|
+
let started = false;
|
|
6937
8594
|
const spawned = new Promise((resolve2, reject) => {
|
|
6938
|
-
child.once("spawn",
|
|
6939
|
-
|
|
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
|
+
}
|
|
6940
8604
|
spawnError = error;
|
|
6941
8605
|
reject(error);
|
|
6942
8606
|
});
|
|
@@ -6978,10 +8642,25 @@ var WorkerEngine = class {
|
|
|
6978
8642
|
await this.terminateForFailure(entry, "\u8BB0\u5F55 Worker PID \u5931\u8D25\uFF1Arun \u5DF2\u4E0D\u518D\u5904\u4E8E running \u72B6\u6001");
|
|
6979
8643
|
return;
|
|
6980
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
|
+
}
|
|
6981
8653
|
if (!child.stdin) {
|
|
6982
8654
|
await this.terminateForFailure(entry, "\u653E\u884C OpenCode \u5931\u8D25\uFF1Alauncher stdin \u4E0D\u53EF\u7528");
|
|
6983
8655
|
return;
|
|
6984
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
|
+
});
|
|
6985
8664
|
try {
|
|
6986
8665
|
await new Promise((resolve2, reject) => {
|
|
6987
8666
|
child.stdin.end("START\n", (error) => {
|
|
@@ -6996,6 +8675,7 @@ var WorkerEngine = class {
|
|
|
6996
8675
|
);
|
|
6997
8676
|
return;
|
|
6998
8677
|
}
|
|
8678
|
+
if (entry.settled || entry.termination) return;
|
|
6999
8679
|
const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
|
|
7000
8680
|
if (timeoutMs > 0) {
|
|
7001
8681
|
entry.timeoutTimer = setTimeout(() => {
|
|
@@ -7005,14 +8685,15 @@ var WorkerEngine = class {
|
|
|
7005
8685
|
entry.task.id
|
|
7006
8686
|
);
|
|
7007
8687
|
}, timeoutMs);
|
|
8688
|
+
entry.timeoutTimer.unref?.();
|
|
7008
8689
|
}
|
|
7009
8690
|
}
|
|
7010
8691
|
handleChildClose(entry, code, signal, spawnError) {
|
|
7011
8692
|
if (entry.settled || entry.termination) return;
|
|
7012
8693
|
if (!entry.guardianDrained) {
|
|
7013
|
-
const
|
|
7014
|
-
const presence =
|
|
7015
|
-
const message = "guardian \u672A\u63D0\u4F9B\u8FDB\u7A0B\
|
|
8694
|
+
const pid2 = entry.child.pid;
|
|
8695
|
+
const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
|
|
8696
|
+
const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
|
|
7016
8697
|
if (presence !== "not-running") {
|
|
7017
8698
|
if (entry.timeoutTimer) {
|
|
7018
8699
|
clearTimeout(entry.timeoutTimer);
|
|
@@ -7033,6 +8714,22 @@ var WorkerEngine = class {
|
|
|
7033
8714
|
);
|
|
7034
8715
|
return;
|
|
7035
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
|
+
}
|
|
7036
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`;
|
|
7037
8734
|
this.runDetached(
|
|
7038
8735
|
this.settleEntry(entry, code, failure),
|
|
@@ -7048,17 +8745,49 @@ var WorkerEngine = class {
|
|
|
7048
8745
|
clearTimeout(entry.timeoutTimer);
|
|
7049
8746
|
entry.timeoutTimer = null;
|
|
7050
8747
|
}
|
|
7051
|
-
const settlement = this.
|
|
7052
|
-
markGatewayFailure("worker", error);
|
|
7053
|
-
this.logError("task settlement failed", error, entry.task.id);
|
|
7054
|
-
return false;
|
|
7055
|
-
}).finally(() => {
|
|
8748
|
+
const settlement = this.commitEntryWithRetry(entry, code, failure).finally(() => {
|
|
7056
8749
|
this.runningTasks.delete(entry.task.id);
|
|
7057
8750
|
this.releaseBatch(entry.task);
|
|
8751
|
+
if (!this.stopped) this.wake("task-settled");
|
|
7058
8752
|
});
|
|
7059
8753
|
entry.settlementPromise = settlement;
|
|
7060
8754
|
return settlement;
|
|
7061
8755
|
}
|
|
8756
|
+
async commitEntryWithRetry(entry, code, failure) {
|
|
8757
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
8758
|
+
try {
|
|
8759
|
+
await this.commitEntry(entry, code, failure);
|
|
8760
|
+
return true;
|
|
8761
|
+
} catch (error) {
|
|
8762
|
+
markGatewayFailure("worker", error);
|
|
8763
|
+
const shortRetryDelayMs = this.settlementRetryDelaysMs[attempt];
|
|
8764
|
+
let retryDelayMs = shortRetryDelayMs ?? this.settlementRetryIntervalMs;
|
|
8765
|
+
if (this.stopped) {
|
|
8766
|
+
const remainingMs = Math.max(0, (this.shutdownDeadlineMs ?? 0) - Date.now());
|
|
8767
|
+
if (remainingMs === 0) return false;
|
|
8768
|
+
retryDelayMs = Math.min(retryDelayMs, remainingMs);
|
|
8769
|
+
}
|
|
8770
|
+
this.logError(
|
|
8771
|
+
`task settlement failed; retrying in ${retryDelayMs}ms`,
|
|
8772
|
+
error,
|
|
8773
|
+
entry.task.id
|
|
8774
|
+
);
|
|
8775
|
+
await this.waitForSettlementRetry(retryDelayMs);
|
|
8776
|
+
}
|
|
8777
|
+
}
|
|
8778
|
+
}
|
|
8779
|
+
waitForSettlementRetry(delayMs) {
|
|
8780
|
+
return new Promise((resolve2) => {
|
|
8781
|
+
let timer;
|
|
8782
|
+
const finish = () => {
|
|
8783
|
+
clearTimeout(timer);
|
|
8784
|
+
this.settlementRetryWakeups.delete(finish);
|
|
8785
|
+
resolve2();
|
|
8786
|
+
};
|
|
8787
|
+
timer = setTimeout(finish, delayMs);
|
|
8788
|
+
this.settlementRetryWakeups.add(finish);
|
|
8789
|
+
});
|
|
8790
|
+
}
|
|
7062
8791
|
async commitEntry(entry, code, failure) {
|
|
7063
8792
|
const termination = entry.termination;
|
|
7064
8793
|
if (termination?.kind === "shutdown") return;
|
|
@@ -7067,6 +8796,19 @@ var WorkerEngine = class {
|
|
|
7067
8796
|
const log2 = `${termination.message}${output2 ? `
|
|
7068
8797
|
${output2}` : ""}`;
|
|
7069
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
|
+
});
|
|
7070
8812
|
console.log(JSON.stringify({
|
|
7071
8813
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7072
8814
|
level: "info",
|
|
@@ -7083,6 +8825,19 @@ ${output}` : ""}` : output;
|
|
|
7083
8825
|
if (code === 0 && !failure) {
|
|
7084
8826
|
const completed = await TaskService.completeRun(entry.task.id, entry.runId, log);
|
|
7085
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
|
+
});
|
|
7086
8841
|
console.log(JSON.stringify({
|
|
7087
8842
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7088
8843
|
level: "info",
|
|
@@ -7092,6 +8847,12 @@ ${output}` : ""}` : output;
|
|
|
7092
8847
|
return;
|
|
7093
8848
|
}
|
|
7094
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
|
+
});
|
|
7095
8856
|
return;
|
|
7096
8857
|
}
|
|
7097
8858
|
const failed = await TaskService.failRun(entry.task.id, entry.runId, log);
|
|
@@ -7101,7 +8862,27 @@ ${output}` : ""}` : output;
|
|
|
7101
8862
|
`${log}${log ? "\n" : ""}\u4EFB\u52A1\u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8`
|
|
7102
8863
|
);
|
|
7103
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;
|
|
7104
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
|
+
});
|
|
7105
8886
|
console.error(JSON.stringify({
|
|
7106
8887
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
7107
8888
|
level: "error",
|
|
@@ -7184,15 +8965,15 @@ ${output}` : ""}` : output;
|
|
|
7184
8965
|
}
|
|
7185
8966
|
}
|
|
7186
8967
|
async killEntry(entry, initialSignal = "SIGTERM") {
|
|
7187
|
-
if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null)) return true;
|
|
7188
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;
|
|
7189
8970
|
if (!pid) return false;
|
|
7190
8971
|
const initialResult = this.signalEntry(entry, initialSignal);
|
|
7191
8972
|
if (initialResult === "not-running") return true;
|
|
7192
8973
|
if (initialResult !== "signalled") return false;
|
|
7193
8974
|
if (await waitForSpawnedProcessTreeExit(pid, 2500)) return true;
|
|
7194
8975
|
if (initialSignal === "SIGKILL") return false;
|
|
7195
|
-
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;
|
|
7196
8977
|
const forcedResult = this.signalEntry(entry, "SIGKILL");
|
|
7197
8978
|
if (forcedResult === "not-running") return true;
|
|
7198
8979
|
if (forcedResult !== "signalled") return false;
|
|
@@ -7214,13 +8995,15 @@ ${output}` : ""}` : output;
|
|
|
7214
8995
|
if (batchId) this.activeBatchIds.delete(batchId);
|
|
7215
8996
|
}
|
|
7216
8997
|
outputWithCommand(entry) {
|
|
7217
|
-
|
|
8998
|
+
entry.output.flush();
|
|
8999
|
+
const output = entry.output.text().trim();
|
|
7218
9000
|
return `${entry.commandContext}${output ? `
|
|
7219
9001
|
${output}` : ""}`;
|
|
7220
9002
|
}
|
|
7221
9003
|
resolveModel(taskModel) {
|
|
7222
|
-
|
|
7223
|
-
return
|
|
9004
|
+
const normalized = taskModel?.trim();
|
|
9005
|
+
if (!normalized || normalized === "default") return null;
|
|
9006
|
+
return normalized;
|
|
7224
9007
|
}
|
|
7225
9008
|
resolveVariant(taskVariant) {
|
|
7226
9009
|
return taskVariant?.trim() || null;
|