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
|
@@ -0,0 +1,1701 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
and,
|
|
5
|
+
asc,
|
|
6
|
+
db,
|
|
7
|
+
desc,
|
|
8
|
+
eq,
|
|
9
|
+
getSqlite,
|
|
10
|
+
isNull,
|
|
11
|
+
or,
|
|
12
|
+
schema_exports,
|
|
13
|
+
sql
|
|
14
|
+
} from "./chunk-YGELD2E5.js";
|
|
15
|
+
|
|
16
|
+
// src/core/backoff.ts
|
|
17
|
+
var MAX_BACKOFF_MS = 30 * 60 * 1e3;
|
|
18
|
+
function computeBackoff(retryCount, baseMs = 3e4, maxMs = MAX_BACKOFF_MS) {
|
|
19
|
+
return Math.min(baseMs * Math.pow(2, retryCount - 1), maxMs);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/core/task-working-directory.ts
|
|
23
|
+
import { statSync } from "fs";
|
|
24
|
+
import { isAbsolute } from "path";
|
|
25
|
+
var InvalidTaskWorkingDirectoryError = class extends Error {
|
|
26
|
+
constructor(message) {
|
|
27
|
+
super(message);
|
|
28
|
+
this.name = "InvalidTaskWorkingDirectoryError";
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
function validateTaskWorkingDirectory(cwd) {
|
|
32
|
+
if (cwd == null) return;
|
|
33
|
+
if (!cwd.trim()) {
|
|
34
|
+
throw new InvalidTaskWorkingDirectoryError("\u4EFB\u52A1\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A");
|
|
35
|
+
}
|
|
36
|
+
if (!isAbsolute(cwd)) {
|
|
37
|
+
throw new InvalidTaskWorkingDirectoryError(`\u4EFB\u52A1\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF1A${cwd}`);
|
|
38
|
+
}
|
|
39
|
+
let stat;
|
|
40
|
+
try {
|
|
41
|
+
stat = statSync(cwd);
|
|
42
|
+
} catch (error) {
|
|
43
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
44
|
+
throw new InvalidTaskWorkingDirectoryError(`\u4EFB\u52A1\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\u6216\u65E0\u6CD5\u8BBF\u95EE\uFF1A${cwd}\uFF08${detail}\uFF09`);
|
|
45
|
+
}
|
|
46
|
+
if (!stat.isDirectory()) {
|
|
47
|
+
throw new InvalidTaskWorkingDirectoryError(`\u4EFB\u52A1\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u76EE\u5F55\uFF1A${cwd}`);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// src/core/task-batch.ts
|
|
52
|
+
var TASK_BATCH_TRIM_CHARACTERS = " \n\v\f\r\xA0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u2028\u2029\u202F\u205F\u3000\uFEFF";
|
|
53
|
+
function normalizeTaskBatchId(batchId) {
|
|
54
|
+
if (batchId == null) return batchId;
|
|
55
|
+
return batchId.trim() || null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/core/model-variant.ts
|
|
59
|
+
var MAX_MODEL_VARIANT_LENGTH = 128;
|
|
60
|
+
var CONTROL_CHARACTER_PATTERN = /[\u0000-\u001F\u007F]/;
|
|
61
|
+
function normalizeModelVariant(value) {
|
|
62
|
+
if (value === void 0 || value === null) return value;
|
|
63
|
+
const normalized = value.trim();
|
|
64
|
+
if (!normalized) return null;
|
|
65
|
+
if (normalized.length > MAX_MODEL_VARIANT_LENGTH) {
|
|
66
|
+
throw new Error(`variant \u957F\u5EA6\u4E0D\u80FD\u8D85\u8FC7 ${MAX_MODEL_VARIANT_LENGTH} \u4E2A\u5B57\u7B26`);
|
|
67
|
+
}
|
|
68
|
+
if (CONTROL_CHARACTER_PATTERN.test(normalized)) {
|
|
69
|
+
throw new Error("variant \u4E0D\u80FD\u5305\u542B\u63A7\u5236\u5B57\u7B26");
|
|
70
|
+
}
|
|
71
|
+
return normalized;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/core/services/task.service.ts
|
|
75
|
+
var { tasks, taskRuns } = schema_exports;
|
|
76
|
+
var cleanupInvocation = 0;
|
|
77
|
+
var TaskDeletionConflictError = class extends Error {
|
|
78
|
+
constructor(message) {
|
|
79
|
+
super(message);
|
|
80
|
+
this.name = "TaskDeletionConflictError";
|
|
81
|
+
}
|
|
82
|
+
};
|
|
83
|
+
function validateIntegerField(name, value, min, max) {
|
|
84
|
+
if (value === void 0 || value === null) return;
|
|
85
|
+
if (!Number.isInteger(value) || value < min || value > max) {
|
|
86
|
+
throw new Error(`${name} \u5FC5\u987B\u662F ${min} \u5230 ${max} \u4E4B\u95F4\u7684\u6574\u6570`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function validateCommonTaskFields(data) {
|
|
90
|
+
if (!data.name.trim()) throw new Error("name \u4E0D\u80FD\u4E3A\u7A7A");
|
|
91
|
+
if (!data.agent.trim()) throw new Error("agent \u4E0D\u80FD\u4E3A\u7A7A");
|
|
92
|
+
if (!data.prompt.trim()) throw new Error("prompt \u4E0D\u80FD\u4E3A\u7A7A");
|
|
93
|
+
validateTaskWorkingDirectory(data.cwd);
|
|
94
|
+
validateIntegerField("importance", data.importance, 1, 5);
|
|
95
|
+
validateIntegerField("urgency", data.urgency, 1, 5);
|
|
96
|
+
validateIntegerField("maxRetries", data.maxRetries, 0, 1e3);
|
|
97
|
+
validateIntegerField("retryBackoffMs", data.retryBackoffMs, 0, 864e5);
|
|
98
|
+
validateIntegerField("timeoutMs", data.timeoutMs, 1e3, 6048e5);
|
|
99
|
+
}
|
|
100
|
+
function escapeLikePattern(value) {
|
|
101
|
+
return value.replaceAll("\\", "\\\\").replaceAll("%", "\\%").replaceAll("_", "\\_");
|
|
102
|
+
}
|
|
103
|
+
function hasNoExecutableDependents() {
|
|
104
|
+
return sql`NOT EXISTS (
|
|
105
|
+
SELECT 1 FROM tasks AS dependent_task
|
|
106
|
+
WHERE dependent_task.depends_on = ${tasks.id}
|
|
107
|
+
AND dependent_task.status IN ('pending', 'running', 'failed', 'dead_letter')
|
|
108
|
+
)`;
|
|
109
|
+
}
|
|
110
|
+
function hasViableDependency() {
|
|
111
|
+
return or(
|
|
112
|
+
isNull(tasks.dependsOn),
|
|
113
|
+
sql`EXISTS (
|
|
114
|
+
SELECT 1 FROM tasks AS dependency_task
|
|
115
|
+
WHERE dependency_task.id = ${tasks.dependsOn}
|
|
116
|
+
AND dependency_task.cwd IS ${tasks.cwd}
|
|
117
|
+
AND (
|
|
118
|
+
dependency_task.status IN ('pending', 'running', 'done')
|
|
119
|
+
OR (
|
|
120
|
+
dependency_task.status = 'failed'
|
|
121
|
+
AND dependency_task.retry_count <= dependency_task.max_retries
|
|
122
|
+
)
|
|
123
|
+
)
|
|
124
|
+
)`
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
function blockedDependentsOf(prerequisiteId) {
|
|
128
|
+
return sql`${tasks.id} IN (
|
|
129
|
+
WITH RECURSIVE blocked_task(id) AS (
|
|
130
|
+
SELECT direct_dependent.id
|
|
131
|
+
FROM tasks AS direct_dependent
|
|
132
|
+
WHERE direct_dependent.depends_on = ${prerequisiteId}
|
|
133
|
+
AND direct_dependent.status IN ('pending', 'failed')
|
|
134
|
+
AND EXISTS (
|
|
135
|
+
SELECT 1 FROM tasks AS prerequisite
|
|
136
|
+
WHERE prerequisite.id = ${prerequisiteId}
|
|
137
|
+
AND prerequisite.status IN ('dead_letter', 'cancelled')
|
|
138
|
+
)
|
|
139
|
+
UNION
|
|
140
|
+
SELECT descendant.id
|
|
141
|
+
FROM tasks AS descendant
|
|
142
|
+
INNER JOIN blocked_task ON descendant.depends_on = blocked_task.id
|
|
143
|
+
WHERE descendant.status IN ('pending', 'failed')
|
|
144
|
+
)
|
|
145
|
+
SELECT id FROM blocked_task
|
|
146
|
+
)`;
|
|
147
|
+
}
|
|
148
|
+
function legacyCwdCondition() {
|
|
149
|
+
return sql`(${tasks.cwd} IS NULL OR trim(${tasks.cwd}) = '')`;
|
|
150
|
+
}
|
|
151
|
+
var LEADING_BATCH_WHITESPACE_RANGES = [
|
|
152
|
+
[" ", ""],
|
|
153
|
+
// U+0009..U+000D (\t \n \v \f \r)
|
|
154
|
+
[" ", "!"],
|
|
155
|
+
// U+0020
|
|
156
|
+
["\xA0", "\xA1"],
|
|
157
|
+
// U+00A0
|
|
158
|
+
["\u1680", "\u1681"],
|
|
159
|
+
// U+1680
|
|
160
|
+
["\u2000", "\u200B"],
|
|
161
|
+
// U+2000..U+200A
|
|
162
|
+
["\u2028", "\u202A"],
|
|
163
|
+
// U+2028..U+2029
|
|
164
|
+
["\u202F", "\u2030"],
|
|
165
|
+
// U+202F
|
|
166
|
+
["\u205F", "\u2060"],
|
|
167
|
+
// U+205F
|
|
168
|
+
["\u3000", "\u3001"],
|
|
169
|
+
// U+3000
|
|
170
|
+
["\uFEFF", "\uFF00"]
|
|
171
|
+
// U+FEFF
|
|
172
|
+
];
|
|
173
|
+
var sqliteUtf8EncodingCache = /* @__PURE__ */ new WeakMap();
|
|
174
|
+
function isUtf8SqliteDatabase(sqlite) {
|
|
175
|
+
const cached = sqliteUtf8EncodingCache.get(sqlite);
|
|
176
|
+
if (cached !== void 0) return cached;
|
|
177
|
+
const row = sqlite.query("PRAGMA encoding").get();
|
|
178
|
+
const isUtf8 = (row?.encoding ?? "UTF-8").toUpperCase() === "UTF-8";
|
|
179
|
+
sqliteUtf8EncodingCache.set(sqlite, isUtf8);
|
|
180
|
+
return isUtf8;
|
|
181
|
+
}
|
|
182
|
+
function batchIdMatchCondition(normalizedBatchId) {
|
|
183
|
+
if (!isUtf8SqliteDatabase(getSqlite())) {
|
|
184
|
+
return sql`${tasks.id} IN (
|
|
185
|
+
SELECT batch_exact.id FROM tasks AS batch_exact
|
|
186
|
+
WHERE batch_exact.batch_id = ${normalizedBatchId}
|
|
187
|
+
UNION ALL
|
|
188
|
+
SELECT batch_legacy.id FROM tasks AS batch_legacy
|
|
189
|
+
WHERE batch_legacy.batch_id IS NOT NULL
|
|
190
|
+
AND batch_legacy.batch_id <> ${normalizedBatchId}
|
|
191
|
+
AND length(batch_legacy.batch_id) > length(${normalizedBatchId})
|
|
192
|
+
AND trim(batch_legacy.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}
|
|
193
|
+
)`;
|
|
194
|
+
}
|
|
195
|
+
const trailingAsciiUpper = `${normalizedBatchId}!`;
|
|
196
|
+
const trailingUnicodeLower = `${normalizedBatchId}\xA0`;
|
|
197
|
+
const trailingUnicodeUpper = `${normalizedBatchId}\uFF00`;
|
|
198
|
+
const branches = [
|
|
199
|
+
sql`SELECT batch_exact.id FROM tasks AS batch_exact WHERE batch_exact.batch_id = ${normalizedBatchId}`,
|
|
200
|
+
sql`SELECT batch_trail_ascii.id FROM tasks AS batch_trail_ascii
|
|
201
|
+
WHERE batch_trail_ascii.batch_id > ${normalizedBatchId}
|
|
202
|
+
AND batch_trail_ascii.batch_id < ${trailingAsciiUpper}
|
|
203
|
+
AND trim(batch_trail_ascii.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}`,
|
|
204
|
+
sql`SELECT batch_trail_uni.id FROM tasks AS batch_trail_uni
|
|
205
|
+
WHERE batch_trail_uni.batch_id >= ${trailingUnicodeLower}
|
|
206
|
+
AND batch_trail_uni.batch_id < ${trailingUnicodeUpper}
|
|
207
|
+
AND trim(batch_trail_uni.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}`
|
|
208
|
+
];
|
|
209
|
+
for (const [lower, upper] of LEADING_BATCH_WHITESPACE_RANGES) {
|
|
210
|
+
branches.push(sql`SELECT batch_lead.id FROM tasks AS batch_lead
|
|
211
|
+
WHERE batch_lead.batch_id >= ${lower}
|
|
212
|
+
AND batch_lead.batch_id < ${upper}
|
|
213
|
+
AND trim(batch_lead.batch_id, ${TASK_BATCH_TRIM_CHARACTERS}) = ${normalizedBatchId}`);
|
|
214
|
+
}
|
|
215
|
+
return sql`${tasks.id} IN (${sql.join(branches, sql` UNION ALL `)})`;
|
|
216
|
+
}
|
|
217
|
+
function activeExecutionCondition() {
|
|
218
|
+
return sql`${tasks.id} IN (
|
|
219
|
+
SELECT active_task.id FROM tasks AS active_task
|
|
220
|
+
WHERE active_task.status = 'running'
|
|
221
|
+
UNION
|
|
222
|
+
SELECT active_run.task_id FROM task_runs AS active_run
|
|
223
|
+
WHERE active_run.status = 'running'
|
|
224
|
+
)`;
|
|
225
|
+
}
|
|
226
|
+
function emptyDashboardStats() {
|
|
227
|
+
return {
|
|
228
|
+
total: 0,
|
|
229
|
+
pending: 0,
|
|
230
|
+
running: 0,
|
|
231
|
+
activeExecution: 0,
|
|
232
|
+
done: 0,
|
|
233
|
+
failed: 0,
|
|
234
|
+
dead_letter: 0,
|
|
235
|
+
cancelled: 0
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
function buildNextCandidateSql(hasCwdScope) {
|
|
239
|
+
const cwdClause = hasCwdScope ? "AND t.cwd = ?" : "";
|
|
240
|
+
return `
|
|
241
|
+
WITH
|
|
242
|
+
active_run_tasks(task_id) AS MATERIALIZED (
|
|
243
|
+
SELECT DISTINCT task_id
|
|
244
|
+
FROM task_runs
|
|
245
|
+
WHERE status = 'running'
|
|
246
|
+
),
|
|
247
|
+
active_batches(batch_id) AS MATERIALIZED (
|
|
248
|
+
SELECT trim(batch_id, ?) AS batch_id
|
|
249
|
+
FROM tasks
|
|
250
|
+
WHERE status = 'running'
|
|
251
|
+
AND batch_id IS NOT NULL
|
|
252
|
+
AND trim(batch_id, ?) <> ''
|
|
253
|
+
UNION
|
|
254
|
+
SELECT trim(t.batch_id, ?) AS batch_id
|
|
255
|
+
FROM tasks AS t
|
|
256
|
+
INNER JOIN active_run_tasks AS art ON t.id = art.task_id
|
|
257
|
+
WHERE t.batch_id IS NOT NULL
|
|
258
|
+
AND trim(t.batch_id, ?) <> ''
|
|
259
|
+
UNION
|
|
260
|
+
SELECT value AS batch_id FROM json_each(?)
|
|
261
|
+
)
|
|
262
|
+
SELECT id FROM (
|
|
263
|
+
SELECT id, urgency, importance, created_at FROM (
|
|
264
|
+
SELECT t.id, t.urgency, t.importance, t.created_at
|
|
265
|
+
FROM tasks AS t
|
|
266
|
+
WHERE t.status = 'pending'
|
|
267
|
+
AND COALESCE(t.retry_after, 0) <= ?
|
|
268
|
+
${cwdClause}
|
|
269
|
+
AND (
|
|
270
|
+
t.depends_on IS NULL
|
|
271
|
+
OR EXISTS (
|
|
272
|
+
SELECT 1 FROM tasks AS dep
|
|
273
|
+
WHERE dep.id = t.depends_on
|
|
274
|
+
AND dep.status = 'done'
|
|
275
|
+
AND dep.cwd IS t.cwd
|
|
276
|
+
)
|
|
277
|
+
)
|
|
278
|
+
AND NOT EXISTS (
|
|
279
|
+
SELECT 1 FROM active_run_tasks AS art
|
|
280
|
+
WHERE art.task_id = t.id
|
|
281
|
+
)
|
|
282
|
+
AND (
|
|
283
|
+
t.batch_id IS NULL
|
|
284
|
+
OR trim(t.batch_id, ?) = ''
|
|
285
|
+
OR NOT EXISTS (
|
|
286
|
+
SELECT 1 FROM active_batches AS ab
|
|
287
|
+
WHERE ab.batch_id = trim(t.batch_id, ?)
|
|
288
|
+
)
|
|
289
|
+
)
|
|
290
|
+
ORDER BY t.urgency DESC, t.importance DESC, t.created_at ASC, t.id ASC
|
|
291
|
+
LIMIT 1
|
|
292
|
+
)
|
|
293
|
+
UNION ALL
|
|
294
|
+
SELECT id, urgency, importance, created_at FROM (
|
|
295
|
+
SELECT t.id, t.urgency, t.importance, t.created_at
|
|
296
|
+
FROM tasks AS t
|
|
297
|
+
WHERE t.status = 'failed'
|
|
298
|
+
AND t.retry_count <= t.max_retries
|
|
299
|
+
AND COALESCE(t.retry_after, 0) <= ?
|
|
300
|
+
${cwdClause}
|
|
301
|
+
AND (
|
|
302
|
+
t.depends_on IS NULL
|
|
303
|
+
OR EXISTS (
|
|
304
|
+
SELECT 1 FROM tasks AS dep
|
|
305
|
+
WHERE dep.id = t.depends_on
|
|
306
|
+
AND dep.status = 'done'
|
|
307
|
+
AND dep.cwd IS t.cwd
|
|
308
|
+
)
|
|
309
|
+
)
|
|
310
|
+
AND NOT EXISTS (
|
|
311
|
+
SELECT 1 FROM active_run_tasks AS art
|
|
312
|
+
WHERE art.task_id = t.id
|
|
313
|
+
)
|
|
314
|
+
AND (
|
|
315
|
+
t.batch_id IS NULL
|
|
316
|
+
OR trim(t.batch_id, ?) = ''
|
|
317
|
+
OR NOT EXISTS (
|
|
318
|
+
SELECT 1 FROM active_batches AS ab
|
|
319
|
+
WHERE ab.batch_id = trim(t.batch_id, ?)
|
|
320
|
+
)
|
|
321
|
+
)
|
|
322
|
+
ORDER BY t.urgency DESC, t.importance DESC, t.created_at ASC, t.id ASC
|
|
323
|
+
LIMIT 1
|
|
324
|
+
)
|
|
325
|
+
)
|
|
326
|
+
ORDER BY urgency DESC, importance DESC, created_at ASC, id ASC
|
|
327
|
+
LIMIT 1
|
|
328
|
+
`;
|
|
329
|
+
}
|
|
330
|
+
var COUNT_RUNNING_UNSCOPED_SQL = `
|
|
331
|
+
SELECT
|
|
332
|
+
(SELECT count(*) FROM tasks WHERE status = 'running')
|
|
333
|
+
+ (
|
|
334
|
+
SELECT count(DISTINCT r.task_id)
|
|
335
|
+
FROM task_runs AS r
|
|
336
|
+
INNER JOIN tasks AS t ON t.id = r.task_id
|
|
337
|
+
WHERE r.status = 'running' AND (t.status IS NULL OR t.status <> 'running')
|
|
338
|
+
) AS count
|
|
339
|
+
`;
|
|
340
|
+
var COUNT_RUNNING_BY_CWD_SQL = `
|
|
341
|
+
SELECT
|
|
342
|
+
(SELECT count(*) FROM tasks WHERE status = 'running' AND cwd = ?)
|
|
343
|
+
+ (
|
|
344
|
+
SELECT count(DISTINCT r.task_id)
|
|
345
|
+
FROM task_runs AS r
|
|
346
|
+
INNER JOIN tasks AS t ON t.id = r.task_id
|
|
347
|
+
WHERE r.status = 'running' AND (t.status IS NULL OR t.status <> 'running') AND t.cwd = ?
|
|
348
|
+
) AS count
|
|
349
|
+
`;
|
|
350
|
+
var COUNT_RUNNING_LEGACY_CWD_SQL = `
|
|
351
|
+
SELECT
|
|
352
|
+
(SELECT count(*) FROM tasks WHERE status = 'running' AND (cwd IS NULL OR trim(cwd) = ''))
|
|
353
|
+
+ (
|
|
354
|
+
SELECT count(DISTINCT r.task_id)
|
|
355
|
+
FROM task_runs AS r
|
|
356
|
+
INNER JOIN tasks AS t ON t.id = r.task_id
|
|
357
|
+
WHERE r.status = 'running'
|
|
358
|
+
AND (t.status IS NULL OR t.status <> 'running')
|
|
359
|
+
AND (t.cwd IS NULL OR trim(t.cwd) = '')
|
|
360
|
+
) AS count
|
|
361
|
+
`;
|
|
362
|
+
function buildCountRunningByBatchSql(cwdMode) {
|
|
363
|
+
const taskCwdClause = cwdMode === "exact" ? "AND cwd = ?" : cwdMode === "legacy" ? "AND (cwd IS NULL OR trim(cwd) = '')" : "";
|
|
364
|
+
const joinedCwdClause = cwdMode === "exact" ? "AND t.cwd = ?" : cwdMode === "legacy" ? "AND (t.cwd IS NULL OR trim(t.cwd) = '')" : "";
|
|
365
|
+
return `
|
|
366
|
+
SELECT
|
|
367
|
+
(
|
|
368
|
+
SELECT count(*)
|
|
369
|
+
FROM tasks
|
|
370
|
+
WHERE status = 'running'
|
|
371
|
+
AND batch_id IS NOT NULL
|
|
372
|
+
AND batch_id > ''
|
|
373
|
+
AND trim(batch_id, ?) = ?
|
|
374
|
+
${taskCwdClause}
|
|
375
|
+
)
|
|
376
|
+
+ (
|
|
377
|
+
SELECT count(DISTINCT r.task_id)
|
|
378
|
+
FROM task_runs AS r
|
|
379
|
+
INNER JOIN tasks AS t ON t.id = r.task_id
|
|
380
|
+
WHERE r.status = 'running'
|
|
381
|
+
AND (t.status IS NULL OR t.status <> 'running')
|
|
382
|
+
AND t.batch_id IS NOT NULL
|
|
383
|
+
AND t.batch_id > ''
|
|
384
|
+
AND trim(t.batch_id, ?) = ?
|
|
385
|
+
${joinedCwdClause}
|
|
386
|
+
) AS count
|
|
387
|
+
`;
|
|
388
|
+
}
|
|
389
|
+
var COUNT_RUNNING_BY_BATCH_GLOBAL_SQL = buildCountRunningByBatchSql("none");
|
|
390
|
+
var COUNT_RUNNING_BY_BATCH_CWD_SQL = buildCountRunningByBatchSql("exact");
|
|
391
|
+
var COUNT_RUNNING_BY_BATCH_LEGACY_CWD_SQL = buildCountRunningByBatchSql("legacy");
|
|
392
|
+
var DASHBOARD_OVERVIEW_BY_STATUS_SQL = `
|
|
393
|
+
SELECT
|
|
394
|
+
t.cwd AS project_cwd,
|
|
395
|
+
t.status AS task_status,
|
|
396
|
+
COUNT(*) AS status_count,
|
|
397
|
+
MAX(t.created_at) AS last_created_at,
|
|
398
|
+
MAX(t.id) AS last_task_id,
|
|
399
|
+
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,
|
|
400
|
+
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,
|
|
401
|
+
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,
|
|
402
|
+
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,
|
|
403
|
+
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
|
|
404
|
+
FROM tasks AS t
|
|
405
|
+
GROUP BY t.cwd, t.status
|
|
406
|
+
`;
|
|
407
|
+
var DASHBOARD_OVERVIEW_EXTRA_ACTIVE_RUNS_SQL = `
|
|
408
|
+
SELECT
|
|
409
|
+
t.cwd AS project_cwd,
|
|
410
|
+
COUNT(DISTINCT r.task_id) AS extra_active
|
|
411
|
+
FROM task_runs AS r
|
|
412
|
+
INNER JOIN tasks AS t ON t.id = r.task_id
|
|
413
|
+
WHERE r.status = 'running'
|
|
414
|
+
AND (t.status IS NULL OR t.status <> 'running')
|
|
415
|
+
GROUP BY t.cwd
|
|
416
|
+
`;
|
|
417
|
+
var dashboardOverviewCache = /* @__PURE__ */ new WeakMap();
|
|
418
|
+
function invalidateDashboardOverviewCache(sqlite) {
|
|
419
|
+
const entry = dashboardOverviewCache.get(sqlite);
|
|
420
|
+
if (entry) {
|
|
421
|
+
entry.writeEpoch += 1;
|
|
422
|
+
entry.snapshot = null;
|
|
423
|
+
} else {
|
|
424
|
+
dashboardOverviewCache.set(sqlite, { writeEpoch: 1, snapshot: null });
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
function readSqliteMutationStamp(sqlite) {
|
|
428
|
+
const dataVersionRow = sqlite.query("PRAGMA data_version").get();
|
|
429
|
+
const totalChangesRow = sqlite.query("SELECT total_changes() AS changes").get();
|
|
430
|
+
return {
|
|
431
|
+
dataVersion: Number(dataVersionRow?.data_version ?? 0),
|
|
432
|
+
totalChanges: Number(totalChangesRow?.changes ?? 0)
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
function cloneDashboardStats(stats) {
|
|
436
|
+
return { ...stats };
|
|
437
|
+
}
|
|
438
|
+
var NEXT_CANDIDATE_GLOBAL_SQL = buildNextCandidateSql(false);
|
|
439
|
+
var NEXT_CANDIDATE_SCOPED_SQL = buildNextCandidateSql(true);
|
|
440
|
+
var TaskService = class {
|
|
441
|
+
static buildScopeWhere(scope) {
|
|
442
|
+
const conditions = [];
|
|
443
|
+
if (scope?.cwd !== void 0) {
|
|
444
|
+
conditions.push(eq(tasks.cwd, scope.cwd));
|
|
445
|
+
}
|
|
446
|
+
return conditions;
|
|
447
|
+
}
|
|
448
|
+
static cascadeDeadLetterDependents(tx, prerequisiteId, finishedAt) {
|
|
449
|
+
tx.update(tasks).set({
|
|
450
|
+
status: "dead_letter",
|
|
451
|
+
finishedAt,
|
|
452
|
+
retryAfter: null,
|
|
453
|
+
resultLog: `\u4F9D\u8D56\u4EFB\u52A1 #${prerequisiteId} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`
|
|
454
|
+
}).where(blockedDependentsOf(prerequisiteId)).run();
|
|
455
|
+
}
|
|
456
|
+
static findNextCandidateId(scope) {
|
|
457
|
+
const sqlite = getSqlite();
|
|
458
|
+
const nowMs = Date.now();
|
|
459
|
+
const excludedBatchIds = [...new Set((scope.excludedBatchIds ?? []).map((batchId) => normalizeTaskBatchId(batchId)).filter((batchId) => Boolean(batchId)))];
|
|
460
|
+
const excludedJson = JSON.stringify(excludedBatchIds);
|
|
461
|
+
const trimChars = TASK_BATCH_TRIM_CHARACTERS;
|
|
462
|
+
const row = scope.cwd !== void 0 ? sqlite.query(NEXT_CANDIDATE_SCOPED_SQL).get(
|
|
463
|
+
trimChars,
|
|
464
|
+
trimChars,
|
|
465
|
+
trimChars,
|
|
466
|
+
trimChars,
|
|
467
|
+
excludedJson,
|
|
468
|
+
nowMs,
|
|
469
|
+
scope.cwd,
|
|
470
|
+
trimChars,
|
|
471
|
+
trimChars,
|
|
472
|
+
nowMs,
|
|
473
|
+
scope.cwd,
|
|
474
|
+
trimChars,
|
|
475
|
+
trimChars
|
|
476
|
+
) : sqlite.query(NEXT_CANDIDATE_GLOBAL_SQL).get(
|
|
477
|
+
trimChars,
|
|
478
|
+
trimChars,
|
|
479
|
+
trimChars,
|
|
480
|
+
trimChars,
|
|
481
|
+
excludedJson,
|
|
482
|
+
nowMs,
|
|
483
|
+
trimChars,
|
|
484
|
+
trimChars,
|
|
485
|
+
nowMs,
|
|
486
|
+
trimChars,
|
|
487
|
+
trimChars
|
|
488
|
+
);
|
|
489
|
+
return row ? Number(row.id) : null;
|
|
490
|
+
}
|
|
491
|
+
static buildListConditions(options) {
|
|
492
|
+
const conditions = [];
|
|
493
|
+
if (options.activeExecution) {
|
|
494
|
+
conditions.push(activeExecutionCondition());
|
|
495
|
+
} else if (options.status) {
|
|
496
|
+
conditions.push(eq(tasks.status, options.status));
|
|
497
|
+
}
|
|
498
|
+
if (options.batchId !== void 0) {
|
|
499
|
+
const batchId = normalizeTaskBatchId(options.batchId);
|
|
500
|
+
conditions.push(batchId ? batchIdMatchCondition(batchId) : sql`0`);
|
|
501
|
+
}
|
|
502
|
+
if (options.category) {
|
|
503
|
+
conditions.push(eq(tasks.category, options.category));
|
|
504
|
+
}
|
|
505
|
+
if (options.agent) {
|
|
506
|
+
conditions.push(eq(tasks.agent, options.agent));
|
|
507
|
+
}
|
|
508
|
+
if (options.templateId !== void 0) {
|
|
509
|
+
conditions.push(eq(tasks.templateId, options.templateId));
|
|
510
|
+
}
|
|
511
|
+
if (options.legacyCwd) {
|
|
512
|
+
conditions.push(legacyCwdCondition());
|
|
513
|
+
} else if (options.cwd !== void 0) {
|
|
514
|
+
conditions.push(eq(tasks.cwd, options.cwd));
|
|
515
|
+
}
|
|
516
|
+
if (options.search !== void 0) {
|
|
517
|
+
const trimmed = options.search.trim();
|
|
518
|
+
if (trimmed.length > 0) {
|
|
519
|
+
const escaped = `%${escapeLikePattern(trimmed)}%`;
|
|
520
|
+
const idMatch = /^#?(\d+)$/.exec(trimmed);
|
|
521
|
+
if (idMatch) {
|
|
522
|
+
const numericId = Number(idMatch[1]);
|
|
523
|
+
conditions.push(sql`(
|
|
524
|
+
${tasks.id} = ${numericId}
|
|
525
|
+
OR ${tasks.name} LIKE ${escaped} ESCAPE '\\'
|
|
526
|
+
OR ${tasks.prompt} LIKE ${escaped} ESCAPE '\\'
|
|
527
|
+
OR ${tasks.batchId} LIKE ${escaped} ESCAPE '\\'
|
|
528
|
+
)`);
|
|
529
|
+
} else {
|
|
530
|
+
conditions.push(sql`(
|
|
531
|
+
${tasks.name} LIKE ${escaped} ESCAPE '\\'
|
|
532
|
+
OR ${tasks.prompt} LIKE ${escaped} ESCAPE '\\'
|
|
533
|
+
OR ${tasks.batchId} LIKE ${escaped} ESCAPE '\\'
|
|
534
|
+
OR CAST(${tasks.id} AS TEXT) LIKE ${escaped} ESCAPE '\\'
|
|
535
|
+
)`);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return conditions;
|
|
540
|
+
}
|
|
541
|
+
static async add(data) {
|
|
542
|
+
const normalizedData = {
|
|
543
|
+
...data,
|
|
544
|
+
batchId: normalizeTaskBatchId(data.batchId),
|
|
545
|
+
variant: normalizeModelVariant(data.variant)
|
|
546
|
+
};
|
|
547
|
+
this.validateNewTask(normalizedData);
|
|
548
|
+
return db.transaction((tx) => {
|
|
549
|
+
if (normalizedData.dependsOn != null) {
|
|
550
|
+
const dependency = tx.select({
|
|
551
|
+
id: tasks.id,
|
|
552
|
+
cwd: tasks.cwd,
|
|
553
|
+
status: tasks.status,
|
|
554
|
+
retryCount: tasks.retryCount,
|
|
555
|
+
maxRetries: tasks.maxRetries
|
|
556
|
+
}).from(tasks).where(eq(tasks.id, normalizedData.dependsOn)).get();
|
|
557
|
+
if (!dependency) {
|
|
558
|
+
throw new Error(`dependsOn \u6307\u5411\u7684\u4EFB\u52A1 #${normalizedData.dependsOn} \u4E0D\u5B58\u5728`);
|
|
559
|
+
}
|
|
560
|
+
if ((dependency.cwd ?? null) !== (normalizedData.cwd ?? null)) {
|
|
561
|
+
throw new Error("dependsOn \u5FC5\u987B\u6307\u5411\u540C\u4E00 cwd \u7684\u4EFB\u52A1");
|
|
562
|
+
}
|
|
563
|
+
const dependencyIsRecoverable = dependency.status === "pending" || dependency.status === "running" || dependency.status === "done" || dependency.status === "failed" && (dependency.retryCount ?? 0) <= (dependency.maxRetries ?? 3);
|
|
564
|
+
if (!dependencyIsRecoverable) {
|
|
565
|
+
throw new Error(`dependsOn \u6307\u5411\u7684\u4EFB\u52A1 #${normalizedData.dependsOn} \u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001`);
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
return tx.insert(tasks).values(normalizedData).returning().get();
|
|
569
|
+
}, { behavior: "immediate" });
|
|
570
|
+
}
|
|
571
|
+
static async clone(id, overrides = {}, scope = {}) {
|
|
572
|
+
const original = await this.getById(id, scope);
|
|
573
|
+
if (!original) return null;
|
|
574
|
+
return this.add({
|
|
575
|
+
name: overrides.name ?? original.name,
|
|
576
|
+
agent: overrides.agent ?? original.agent,
|
|
577
|
+
model: overrides.model ?? original.model ?? "default",
|
|
578
|
+
variant: overrides.variant === void 0 ? original.variant : overrides.variant,
|
|
579
|
+
prompt: overrides.prompt ?? original.prompt,
|
|
580
|
+
cwd: overrides.cwd === void 0 ? original.cwd : overrides.cwd,
|
|
581
|
+
category: overrides.category ?? original.category ?? "general",
|
|
582
|
+
importance: overrides.importance ?? original.importance ?? 3,
|
|
583
|
+
urgency: overrides.urgency ?? original.urgency ?? 3,
|
|
584
|
+
batchId: overrides.batchId === void 0 ? original.batchId : overrides.batchId,
|
|
585
|
+
dependsOn: overrides.dependsOn === void 0 ? null : overrides.dependsOn,
|
|
586
|
+
maxRetries: overrides.maxRetries ?? original.maxRetries ?? 3,
|
|
587
|
+
retryBackoffMs: overrides.retryBackoffMs ?? original.retryBackoffMs ?? 3e4,
|
|
588
|
+
timeoutMs: overrides.timeoutMs === void 0 ? original.timeoutMs : overrides.timeoutMs
|
|
589
|
+
});
|
|
590
|
+
}
|
|
591
|
+
static async update(id, data, scope = {}) {
|
|
592
|
+
if (Object.keys(data).length === 0) throw new Error("\u81F3\u5C11\u63D0\u4F9B\u4E00\u4E2A\u8981\u4FEE\u6539\u7684\u5B57\u6BB5");
|
|
593
|
+
const normalizedData = {
|
|
594
|
+
...data,
|
|
595
|
+
...data.batchId === void 0 ? {} : { batchId: normalizeTaskBatchId(data.batchId) ?? null },
|
|
596
|
+
...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null }
|
|
597
|
+
};
|
|
598
|
+
return db.transaction((tx) => {
|
|
599
|
+
const task = tx.select().from(tasks).where(and(
|
|
600
|
+
eq(tasks.id, id),
|
|
601
|
+
sql`${tasks.status} IN ('pending', 'failed', 'dead_letter')`,
|
|
602
|
+
...this.buildScopeWhere(scope)
|
|
603
|
+
)).get();
|
|
604
|
+
if (!task) return null;
|
|
605
|
+
this.validateNewTask({
|
|
606
|
+
name: normalizedData.name ?? task.name,
|
|
607
|
+
agent: normalizedData.agent ?? task.agent,
|
|
608
|
+
model: normalizedData.model ?? task.model,
|
|
609
|
+
variant: normalizedData.variant === void 0 ? task.variant : normalizedData.variant,
|
|
610
|
+
prompt: normalizedData.prompt ?? task.prompt,
|
|
611
|
+
cwd: task.cwd,
|
|
612
|
+
category: normalizedData.category ?? task.category,
|
|
613
|
+
importance: normalizedData.importance ?? task.importance,
|
|
614
|
+
urgency: normalizedData.urgency ?? task.urgency,
|
|
615
|
+
batchId: normalizedData.batchId === void 0 ? task.batchId : normalizedData.batchId,
|
|
616
|
+
maxRetries: normalizedData.maxRetries ?? task.maxRetries,
|
|
617
|
+
retryBackoffMs: normalizedData.retryBackoffMs ?? task.retryBackoffMs,
|
|
618
|
+
timeoutMs: normalizedData.timeoutMs === void 0 ? task.timeoutMs : normalizedData.timeoutMs,
|
|
619
|
+
dependsOn: task.dependsOn
|
|
620
|
+
});
|
|
621
|
+
const maxRetries = normalizedData.maxRetries ?? task.maxRetries ?? 3;
|
|
622
|
+
const exhausted = (task.status === "failed" || task.status === "pending") && (task.retryCount ?? 0) > maxRetries;
|
|
623
|
+
const finishedAt = exhausted ? /* @__PURE__ */ new Date() : void 0;
|
|
624
|
+
const updated = tx.update(tasks).set({
|
|
625
|
+
...normalizedData,
|
|
626
|
+
...exhausted ? {
|
|
627
|
+
status: "dead_letter",
|
|
628
|
+
finishedAt,
|
|
629
|
+
retryAfter: null
|
|
630
|
+
} : {}
|
|
631
|
+
}).where(eq(tasks.id, id)).returning().get() ?? null;
|
|
632
|
+
if (exhausted && updated && finishedAt) {
|
|
633
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
634
|
+
}
|
|
635
|
+
return updated;
|
|
636
|
+
}, { behavior: "immediate" });
|
|
637
|
+
}
|
|
638
|
+
static validateNewTask(data) {
|
|
639
|
+
validateCommonTaskFields(data);
|
|
640
|
+
validateIntegerField("dependsOn", data.dependsOn, 1, Number.MAX_SAFE_INTEGER);
|
|
641
|
+
}
|
|
642
|
+
static async next(scope = {}) {
|
|
643
|
+
return db.transaction((tx) => {
|
|
644
|
+
const candidateId = this.findNextCandidateId(scope);
|
|
645
|
+
if (candidateId === null) return null;
|
|
646
|
+
return tx.select().from(tasks).where(eq(tasks.id, candidateId)).get() ?? null;
|
|
647
|
+
}, { behavior: "deferred" });
|
|
648
|
+
}
|
|
649
|
+
static async claimNext(scope = {}) {
|
|
650
|
+
return db.transaction((tx) => {
|
|
651
|
+
const candidateId = this.findNextCandidateId(scope);
|
|
652
|
+
if (candidateId === null) return null;
|
|
653
|
+
return tx.update(tasks).set({
|
|
654
|
+
status: "running",
|
|
655
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
656
|
+
finishedAt: null
|
|
657
|
+
}).where(eq(tasks.id, candidateId)).returning().get() ?? null;
|
|
658
|
+
}, { behavior: "immediate" });
|
|
659
|
+
}
|
|
660
|
+
static async countRunning(scope = {}) {
|
|
661
|
+
const sqlite = getSqlite();
|
|
662
|
+
if (scope.batchId !== void 0) {
|
|
663
|
+
const batchId = normalizeTaskBatchId(scope.batchId);
|
|
664
|
+
if (!batchId) return 0;
|
|
665
|
+
const trimChars = TASK_BATCH_TRIM_CHARACTERS;
|
|
666
|
+
if (scope.legacyCwd) {
|
|
667
|
+
const row3 = sqlite.query(COUNT_RUNNING_BY_BATCH_LEGACY_CWD_SQL).get(
|
|
668
|
+
trimChars,
|
|
669
|
+
batchId,
|
|
670
|
+
trimChars,
|
|
671
|
+
batchId
|
|
672
|
+
);
|
|
673
|
+
return Number(row3?.count ?? 0);
|
|
674
|
+
}
|
|
675
|
+
if (scope.cwd !== void 0) {
|
|
676
|
+
const row3 = sqlite.query(COUNT_RUNNING_BY_BATCH_CWD_SQL).get(
|
|
677
|
+
trimChars,
|
|
678
|
+
batchId,
|
|
679
|
+
scope.cwd,
|
|
680
|
+
trimChars,
|
|
681
|
+
batchId,
|
|
682
|
+
scope.cwd
|
|
683
|
+
);
|
|
684
|
+
return Number(row3?.count ?? 0);
|
|
685
|
+
}
|
|
686
|
+
const row2 = sqlite.query(COUNT_RUNNING_BY_BATCH_GLOBAL_SQL).get(
|
|
687
|
+
trimChars,
|
|
688
|
+
batchId,
|
|
689
|
+
trimChars,
|
|
690
|
+
batchId
|
|
691
|
+
);
|
|
692
|
+
return Number(row2?.count ?? 0);
|
|
693
|
+
}
|
|
694
|
+
if (scope.legacyCwd) {
|
|
695
|
+
const row2 = sqlite.query(COUNT_RUNNING_LEGACY_CWD_SQL).get();
|
|
696
|
+
return Number(row2?.count ?? 0);
|
|
697
|
+
}
|
|
698
|
+
if (scope.cwd !== void 0) {
|
|
699
|
+
const row2 = sqlite.query(COUNT_RUNNING_BY_CWD_SQL).get(scope.cwd, scope.cwd);
|
|
700
|
+
return Number(row2?.count ?? 0);
|
|
701
|
+
}
|
|
702
|
+
const row = sqlite.query(COUNT_RUNNING_UNSCOPED_SQL).get();
|
|
703
|
+
return Number(row?.count ?? 0);
|
|
704
|
+
}
|
|
705
|
+
static async start(id, scope = {}) {
|
|
706
|
+
const conditions = [
|
|
707
|
+
eq(tasks.id, id),
|
|
708
|
+
or(
|
|
709
|
+
eq(tasks.status, "pending"),
|
|
710
|
+
and(
|
|
711
|
+
eq(tasks.status, "failed"),
|
|
712
|
+
sql`${tasks.retryCount} <= ${tasks.maxRetries}`
|
|
713
|
+
)
|
|
714
|
+
),
|
|
715
|
+
...this.buildScopeWhere(scope)
|
|
716
|
+
];
|
|
717
|
+
const result = await db.update(tasks).set({
|
|
718
|
+
status: "running",
|
|
719
|
+
startedAt: /* @__PURE__ */ new Date(),
|
|
720
|
+
finishedAt: null
|
|
721
|
+
}).where(and(...conditions)).returning();
|
|
722
|
+
return result[0] || null;
|
|
723
|
+
}
|
|
724
|
+
static async done(id, log, scope = {}) {
|
|
725
|
+
const conditions = [
|
|
726
|
+
eq(tasks.id, id),
|
|
727
|
+
eq(tasks.status, "running"),
|
|
728
|
+
...this.buildScopeWhere(scope)
|
|
729
|
+
];
|
|
730
|
+
const result = await db.update(tasks).set({
|
|
731
|
+
status: "done",
|
|
732
|
+
finishedAt: /* @__PURE__ */ new Date(),
|
|
733
|
+
resultLog: log,
|
|
734
|
+
retryAfter: null
|
|
735
|
+
}).where(and(...conditions)).returning();
|
|
736
|
+
return result[0] || null;
|
|
737
|
+
}
|
|
738
|
+
static async fail(id, log, scope = {}, options) {
|
|
739
|
+
return db.transaction((tx) => {
|
|
740
|
+
const current = tx.select().from(tasks).where(and(
|
|
741
|
+
eq(tasks.id, id),
|
|
742
|
+
eq(tasks.status, "running"),
|
|
743
|
+
...this.buildScopeWhere(scope)
|
|
744
|
+
)).get();
|
|
745
|
+
if (!current) return null;
|
|
746
|
+
const newRetryCount = (current.retryCount ?? 0) + 1;
|
|
747
|
+
const maxRetries = current.maxRetries ?? 3;
|
|
748
|
+
const isDeadLetter = options?.setDeadLetter ?? newRetryCount > maxRetries;
|
|
749
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
750
|
+
const failed = tx.update(tasks).set({
|
|
751
|
+
status: isDeadLetter ? "dead_letter" : "failed",
|
|
752
|
+
finishedAt,
|
|
753
|
+
resultLog: log,
|
|
754
|
+
retryCount: newRetryCount,
|
|
755
|
+
retryAfter: isDeadLetter ? null : options?.retryAfterMs ?? Date.now() + computeBackoff(
|
|
756
|
+
newRetryCount,
|
|
757
|
+
current.retryBackoffMs ?? 3e4
|
|
758
|
+
)
|
|
759
|
+
}).where(and(eq(tasks.id, id), eq(tasks.status, "running"))).returning().get();
|
|
760
|
+
if (failed?.status === "dead_letter") {
|
|
761
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
762
|
+
}
|
|
763
|
+
return failed ?? null;
|
|
764
|
+
}, { behavior: "immediate" });
|
|
765
|
+
}
|
|
766
|
+
static async completeRun(taskId, runId, log) {
|
|
767
|
+
return db.transaction((tx) => {
|
|
768
|
+
const currentTask = tx.select().from(tasks).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).get();
|
|
769
|
+
const currentRun = tx.select({ id: taskRuns.id }).from(taskRuns).where(and(
|
|
770
|
+
eq(taskRuns.id, runId),
|
|
771
|
+
eq(taskRuns.taskId, taskId),
|
|
772
|
+
eq(taskRuns.status, "running")
|
|
773
|
+
)).get();
|
|
774
|
+
if (!currentTask || !currentRun) return null;
|
|
775
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
776
|
+
const completed = tx.update(tasks).set({
|
|
777
|
+
status: "done",
|
|
778
|
+
finishedAt,
|
|
779
|
+
resultLog: log,
|
|
780
|
+
retryAfter: null
|
|
781
|
+
}).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).returning().get();
|
|
782
|
+
if (!completed) return null;
|
|
783
|
+
tx.update(taskRuns).set({ status: "done", finishedAt, log }).where(and(eq(taskRuns.id, runId), eq(taskRuns.status, "running"))).run();
|
|
784
|
+
return completed;
|
|
785
|
+
}, { behavior: "immediate" });
|
|
786
|
+
}
|
|
787
|
+
static async failRun(taskId, runId, log, options) {
|
|
788
|
+
const failed = db.transaction((tx) => {
|
|
789
|
+
const currentTask = tx.select().from(tasks).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).get();
|
|
790
|
+
const currentRun = tx.select({ id: taskRuns.id }).from(taskRuns).where(and(
|
|
791
|
+
eq(taskRuns.id, runId),
|
|
792
|
+
eq(taskRuns.taskId, taskId),
|
|
793
|
+
eq(taskRuns.status, "running")
|
|
794
|
+
)).get();
|
|
795
|
+
if (!currentTask || !currentRun) return null;
|
|
796
|
+
const newRetryCount = (currentTask.retryCount ?? 0) + 1;
|
|
797
|
+
const maxRetries = currentTask.maxRetries ?? 3;
|
|
798
|
+
const isDeadLetter = options?.setDeadLetter ?? newRetryCount > maxRetries;
|
|
799
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
800
|
+
const retryAfter = isDeadLetter ? null : options?.retryAfterMs ?? Date.now() + computeBackoff(
|
|
801
|
+
newRetryCount,
|
|
802
|
+
currentTask.retryBackoffMs ?? 3e4
|
|
803
|
+
);
|
|
804
|
+
const failedTask = tx.update(tasks).set({
|
|
805
|
+
status: isDeadLetter ? "dead_letter" : "failed",
|
|
806
|
+
finishedAt,
|
|
807
|
+
resultLog: log,
|
|
808
|
+
retryCount: newRetryCount,
|
|
809
|
+
retryAfter
|
|
810
|
+
}).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).returning().get();
|
|
811
|
+
if (!failedTask) return null;
|
|
812
|
+
tx.update(taskRuns).set({ status: "failed", finishedAt, log }).where(and(eq(taskRuns.id, runId), eq(taskRuns.status, "running"))).run();
|
|
813
|
+
if (failedTask.status === "dead_letter") {
|
|
814
|
+
this.cascadeDeadLetterDependents(tx, taskId, finishedAt);
|
|
815
|
+
}
|
|
816
|
+
return failedTask;
|
|
817
|
+
}, { behavior: "immediate" });
|
|
818
|
+
return failed;
|
|
819
|
+
}
|
|
820
|
+
static async recoverRun(taskId, runId, log) {
|
|
821
|
+
const recovery = db.transaction((tx) => {
|
|
822
|
+
const currentTask = tx.select().from(tasks).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).get();
|
|
823
|
+
const currentRun = tx.select({ id: taskRuns.id }).from(taskRuns).where(and(
|
|
824
|
+
eq(taskRuns.id, runId),
|
|
825
|
+
eq(taskRuns.taskId, taskId),
|
|
826
|
+
eq(taskRuns.status, "running")
|
|
827
|
+
)).get();
|
|
828
|
+
if (!currentRun) return null;
|
|
829
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
830
|
+
tx.update(taskRuns).set({ status: "failed", finishedAt, log }).where(and(eq(taskRuns.id, runId), eq(taskRuns.status, "running"))).run();
|
|
831
|
+
if (!currentTask) return null;
|
|
832
|
+
const retryCount = (currentTask.retryCount ?? 0) + 1;
|
|
833
|
+
const maxRetries = currentTask.maxRetries ?? 3;
|
|
834
|
+
const isDeadLetter = retryCount > maxRetries;
|
|
835
|
+
const recoveryStatus = isDeadLetter ? "dead_letter" : "pending";
|
|
836
|
+
const retryAfterMs = isDeadLetter ? null : Date.now() + computeBackoff(
|
|
837
|
+
retryCount,
|
|
838
|
+
currentTask.retryBackoffMs ?? 3e4
|
|
839
|
+
);
|
|
840
|
+
tx.update(tasks).set({
|
|
841
|
+
status: recoveryStatus,
|
|
842
|
+
startedAt: null,
|
|
843
|
+
finishedAt: isDeadLetter ? finishedAt : null,
|
|
844
|
+
retryCount,
|
|
845
|
+
retryAfter: retryAfterMs,
|
|
846
|
+
resultLog: log
|
|
847
|
+
}).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).run();
|
|
848
|
+
if (recoveryStatus === "dead_letter") {
|
|
849
|
+
this.cascadeDeadLetterDependents(tx, taskId, finishedAt);
|
|
850
|
+
}
|
|
851
|
+
return {
|
|
852
|
+
status: recoveryStatus,
|
|
853
|
+
retryCount,
|
|
854
|
+
retryAfterMs
|
|
855
|
+
};
|
|
856
|
+
}, { behavior: "immediate" });
|
|
857
|
+
return recovery;
|
|
858
|
+
}
|
|
859
|
+
static async interruptRun(taskId, runId, log) {
|
|
860
|
+
return db.transaction((tx) => {
|
|
861
|
+
const currentRun = tx.select({ id: taskRuns.id }).from(taskRuns).where(and(
|
|
862
|
+
eq(taskRuns.id, runId),
|
|
863
|
+
eq(taskRuns.taskId, taskId),
|
|
864
|
+
eq(taskRuns.status, "running")
|
|
865
|
+
)).get();
|
|
866
|
+
if (!currentRun) return false;
|
|
867
|
+
const updatedRun = tx.update(taskRuns).set({ status: "failed", finishedAt: /* @__PURE__ */ new Date(), log }).where(and(eq(taskRuns.id, runId), eq(taskRuns.status, "running"))).returning({ id: taskRuns.id }).get();
|
|
868
|
+
tx.update(tasks).set({
|
|
869
|
+
status: "pending",
|
|
870
|
+
startedAt: null,
|
|
871
|
+
finishedAt: null,
|
|
872
|
+
retryAfter: null,
|
|
873
|
+
resultLog: log
|
|
874
|
+
}).where(and(eq(tasks.id, taskId), eq(tasks.status, "running"))).run();
|
|
875
|
+
return updatedRun != null;
|
|
876
|
+
}, { behavior: "immediate" });
|
|
877
|
+
}
|
|
878
|
+
static async resolveBlockedDependencies() {
|
|
879
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
880
|
+
const result = await db.update(tasks).set({
|
|
881
|
+
status: "dead_letter",
|
|
882
|
+
finishedAt,
|
|
883
|
+
retryAfter: null,
|
|
884
|
+
resultLog: "\u4F9D\u8D56\u4EFB\u52A1\u4E0D\u5B58\u5728\u3001\u8DE8\u9879\u76EE\u6216\u5DF2\u8FDB\u5165\u4E0D\u53EF\u6062\u590D\u7EC8\u6001"
|
|
885
|
+
}).where(sql`${tasks.id} IN (
|
|
886
|
+
WITH RECURSIVE blocked_task(id) AS (
|
|
887
|
+
SELECT candidate.id
|
|
888
|
+
FROM tasks AS candidate
|
|
889
|
+
WHERE candidate.status IN ('pending', 'failed')
|
|
890
|
+
AND candidate.depends_on IS NOT NULL
|
|
891
|
+
AND NOT EXISTS (
|
|
892
|
+
SELECT 1 FROM tasks AS viable_dependency
|
|
893
|
+
WHERE viable_dependency.id = candidate.depends_on
|
|
894
|
+
AND viable_dependency.cwd IS candidate.cwd
|
|
895
|
+
AND (
|
|
896
|
+
viable_dependency.status IN ('pending', 'running', 'done')
|
|
897
|
+
OR (
|
|
898
|
+
viable_dependency.status = 'failed'
|
|
899
|
+
AND viable_dependency.retry_count <= viable_dependency.max_retries
|
|
900
|
+
)
|
|
901
|
+
)
|
|
902
|
+
)
|
|
903
|
+
UNION
|
|
904
|
+
SELECT descendant.id
|
|
905
|
+
FROM tasks AS descendant
|
|
906
|
+
INNER JOIN blocked_task ON descendant.depends_on = blocked_task.id
|
|
907
|
+
WHERE descendant.status IN ('pending', 'failed')
|
|
908
|
+
)
|
|
909
|
+
SELECT id FROM blocked_task
|
|
910
|
+
)`).returning();
|
|
911
|
+
return result.length;
|
|
912
|
+
}
|
|
913
|
+
static async markPendingForRetry(id, retryAfterMs, retryCount) {
|
|
914
|
+
const result = await db.update(tasks).set({
|
|
915
|
+
status: "pending",
|
|
916
|
+
startedAt: null,
|
|
917
|
+
finishedAt: null,
|
|
918
|
+
retryAfter: retryAfterMs,
|
|
919
|
+
retryCount
|
|
920
|
+
}).where(eq(tasks.id, id)).returning();
|
|
921
|
+
return result[0] || null;
|
|
922
|
+
}
|
|
923
|
+
static async markDeadLetter(id, retryCount) {
|
|
924
|
+
return db.transaction((tx) => {
|
|
925
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
926
|
+
const task = tx.update(tasks).set({ status: "dead_letter", finishedAt, retryCount }).where(eq(tasks.id, id)).returning().get();
|
|
927
|
+
if (!task) return null;
|
|
928
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
929
|
+
return task;
|
|
930
|
+
}, { behavior: "immediate" });
|
|
931
|
+
}
|
|
932
|
+
static async resetRunningToPending(ids) {
|
|
933
|
+
if (ids.length === 0) return 0;
|
|
934
|
+
const result = await db.update(tasks).set({
|
|
935
|
+
status: "pending",
|
|
936
|
+
startedAt: null,
|
|
937
|
+
finishedAt: null
|
|
938
|
+
}).where(
|
|
939
|
+
and(
|
|
940
|
+
sql`${tasks.id} IN ${ids}`,
|
|
941
|
+
eq(tasks.status, "running")
|
|
942
|
+
)
|
|
943
|
+
).returning();
|
|
944
|
+
return result.length;
|
|
945
|
+
}
|
|
946
|
+
static async resetOrphanRunningToPending() {
|
|
947
|
+
const result = await db.update(tasks).set({
|
|
948
|
+
status: "pending",
|
|
949
|
+
startedAt: null,
|
|
950
|
+
finishedAt: null
|
|
951
|
+
}).where(
|
|
952
|
+
and(
|
|
953
|
+
eq(tasks.status, "running"),
|
|
954
|
+
sql`NOT EXISTS (
|
|
955
|
+
SELECT 1 FROM ${taskRuns}
|
|
956
|
+
WHERE ${taskRuns.taskId} = ${tasks.id}
|
|
957
|
+
AND ${taskRuns.status} = 'running'
|
|
958
|
+
)`
|
|
959
|
+
)
|
|
960
|
+
).returning();
|
|
961
|
+
return result.length;
|
|
962
|
+
}
|
|
963
|
+
static async cancel(id, scope = {}) {
|
|
964
|
+
const conditions = [
|
|
965
|
+
eq(tasks.id, id),
|
|
966
|
+
or(
|
|
967
|
+
eq(tasks.status, "pending"),
|
|
968
|
+
eq(tasks.status, "running"),
|
|
969
|
+
eq(tasks.status, "failed")
|
|
970
|
+
),
|
|
971
|
+
...this.buildScopeWhere(scope)
|
|
972
|
+
];
|
|
973
|
+
return db.transaction((tx) => {
|
|
974
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
975
|
+
const task = tx.update(tasks).set({
|
|
976
|
+
status: "cancelled",
|
|
977
|
+
finishedAt,
|
|
978
|
+
retryAfter: null
|
|
979
|
+
}).where(and(...conditions)).returning().get();
|
|
980
|
+
if (!task) return null;
|
|
981
|
+
this.cascadeDeadLetterDependents(tx, id, finishedAt);
|
|
982
|
+
return task;
|
|
983
|
+
}, { behavior: "immediate" });
|
|
984
|
+
}
|
|
985
|
+
static async cancelBatch(ids, scope = {}) {
|
|
986
|
+
const uniqueIds = [...new Set(ids.filter((id) => Number.isInteger(id) && id > 0))];
|
|
987
|
+
if (uniqueIds.length === 0) {
|
|
988
|
+
return { cancelledIds: [], skippedIds: [], cancelledCount: 0 };
|
|
989
|
+
}
|
|
990
|
+
return db.transaction((tx) => {
|
|
991
|
+
const finishedAt = /* @__PURE__ */ new Date();
|
|
992
|
+
const cancelledIds = [];
|
|
993
|
+
const skippedIds = [];
|
|
994
|
+
for (const id of uniqueIds) {
|
|
995
|
+
const task = tx.update(tasks).set({
|
|
996
|
+
status: "cancelled",
|
|
997
|
+
finishedAt,
|
|
998
|
+
retryAfter: null
|
|
999
|
+
}).where(and(
|
|
1000
|
+
eq(tasks.id, id),
|
|
1001
|
+
or(
|
|
1002
|
+
eq(tasks.status, "pending"),
|
|
1003
|
+
eq(tasks.status, "running"),
|
|
1004
|
+
eq(tasks.status, "failed")
|
|
1005
|
+
),
|
|
1006
|
+
...this.buildScopeWhere(scope)
|
|
1007
|
+
)).returning({ id: tasks.id }).get();
|
|
1008
|
+
if (task) {
|
|
1009
|
+
cancelledIds.push(task.id);
|
|
1010
|
+
} else {
|
|
1011
|
+
skippedIds.push(id);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
for (const cancelledId of cancelledIds) {
|
|
1015
|
+
this.cascadeDeadLetterDependents(tx, cancelledId, finishedAt);
|
|
1016
|
+
}
|
|
1017
|
+
return {
|
|
1018
|
+
cancelledIds,
|
|
1019
|
+
skippedIds,
|
|
1020
|
+
cancelledCount: cancelledIds.length
|
|
1021
|
+
};
|
|
1022
|
+
}, { behavior: "immediate" });
|
|
1023
|
+
}
|
|
1024
|
+
static async retry(id, scope = {}) {
|
|
1025
|
+
const conditions = [
|
|
1026
|
+
eq(tasks.id, id),
|
|
1027
|
+
or(eq(tasks.status, "failed"), eq(tasks.status, "dead_letter")),
|
|
1028
|
+
...this.buildScopeWhere(scope)
|
|
1029
|
+
];
|
|
1030
|
+
return db.transaction((tx) => tx.update(tasks).set({
|
|
1031
|
+
status: "pending",
|
|
1032
|
+
startedAt: null,
|
|
1033
|
+
finishedAt: null,
|
|
1034
|
+
retryAfter: null,
|
|
1035
|
+
retryCount: 0
|
|
1036
|
+
}).where(and(...conditions, hasViableDependency())).returning().get() ?? null, { behavior: "immediate" });
|
|
1037
|
+
}
|
|
1038
|
+
static async retryIds(ids, scope = {}) {
|
|
1039
|
+
const uniqueIds = [...new Set(ids.filter((id) => Number.isInteger(id) && id > 0))];
|
|
1040
|
+
if (uniqueIds.length === 0) {
|
|
1041
|
+
return { retriedIds: [], skippedIds: [], retriedCount: 0 };
|
|
1042
|
+
}
|
|
1043
|
+
return db.transaction((tx) => {
|
|
1044
|
+
const retriedIds = [];
|
|
1045
|
+
let remaining = [...uniqueIds].sort((a, b) => a - b);
|
|
1046
|
+
while (remaining.length > 0) {
|
|
1047
|
+
let progressed = false;
|
|
1048
|
+
const nextRemaining = [];
|
|
1049
|
+
for (const id of remaining) {
|
|
1050
|
+
const retried = tx.update(tasks).set({
|
|
1051
|
+
status: "pending",
|
|
1052
|
+
startedAt: null,
|
|
1053
|
+
finishedAt: null,
|
|
1054
|
+
retryAfter: null,
|
|
1055
|
+
retryCount: 0
|
|
1056
|
+
}).where(and(
|
|
1057
|
+
eq(tasks.id, id),
|
|
1058
|
+
or(eq(tasks.status, "failed"), eq(tasks.status, "dead_letter")),
|
|
1059
|
+
...this.buildScopeWhere(scope),
|
|
1060
|
+
hasViableDependency()
|
|
1061
|
+
)).returning({ id: tasks.id }).get();
|
|
1062
|
+
if (retried) {
|
|
1063
|
+
retriedIds.push(retried.id);
|
|
1064
|
+
progressed = true;
|
|
1065
|
+
} else {
|
|
1066
|
+
nextRemaining.push(id);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
remaining = nextRemaining;
|
|
1070
|
+
if (!progressed) break;
|
|
1071
|
+
}
|
|
1072
|
+
return {
|
|
1073
|
+
retriedIds,
|
|
1074
|
+
skippedIds: remaining,
|
|
1075
|
+
retriedCount: retriedIds.length
|
|
1076
|
+
};
|
|
1077
|
+
}, { behavior: "immediate" });
|
|
1078
|
+
}
|
|
1079
|
+
static async retryBatch(batchId, scope = {}) {
|
|
1080
|
+
const normalizedBatchId = normalizeTaskBatchId(batchId);
|
|
1081
|
+
if (!normalizedBatchId) return 0;
|
|
1082
|
+
const sqlite = getSqlite();
|
|
1083
|
+
const scopeFilter = scope.cwd === void 0 ? "" : "AND candidate.cwd = ?";
|
|
1084
|
+
const parameters = scope.cwd === void 0 ? [
|
|
1085
|
+
normalizedBatchId,
|
|
1086
|
+
normalizedBatchId,
|
|
1087
|
+
normalizedBatchId,
|
|
1088
|
+
TASK_BATCH_TRIM_CHARACTERS,
|
|
1089
|
+
normalizedBatchId
|
|
1090
|
+
] : [
|
|
1091
|
+
normalizedBatchId,
|
|
1092
|
+
normalizedBatchId,
|
|
1093
|
+
normalizedBatchId,
|
|
1094
|
+
TASK_BATCH_TRIM_CHARACTERS,
|
|
1095
|
+
normalizedBatchId,
|
|
1096
|
+
scope.cwd
|
|
1097
|
+
];
|
|
1098
|
+
return db.transaction(() => sqlite.query(`
|
|
1099
|
+
WITH RECURSIVE
|
|
1100
|
+
matched_batch_ids(id) AS MATERIALIZED (
|
|
1101
|
+
SELECT id FROM tasks WHERE batch_id = ?
|
|
1102
|
+
UNION ALL
|
|
1103
|
+
SELECT id FROM tasks
|
|
1104
|
+
WHERE batch_id IS NOT NULL
|
|
1105
|
+
AND batch_id <> ?
|
|
1106
|
+
AND length(batch_id) > length(?)
|
|
1107
|
+
AND trim(batch_id, ?) = ?
|
|
1108
|
+
),
|
|
1109
|
+
candidate(id, cwd, depends_on) AS MATERIALIZED (
|
|
1110
|
+
SELECT candidate.id, candidate.cwd, candidate.depends_on
|
|
1111
|
+
FROM tasks AS candidate
|
|
1112
|
+
INNER JOIN matched_batch_ids AS mb ON mb.id = candidate.id
|
|
1113
|
+
WHERE candidate.status IN ('failed', 'dead_letter')
|
|
1114
|
+
${scopeFilter}
|
|
1115
|
+
),
|
|
1116
|
+
retryable(id, cwd, depends_on) AS (
|
|
1117
|
+
SELECT candidate.id,
|
|
1118
|
+
candidate.cwd,
|
|
1119
|
+
candidate.depends_on
|
|
1120
|
+
FROM candidate
|
|
1121
|
+
WHERE candidate.depends_on IS NULL
|
|
1122
|
+
OR (
|
|
1123
|
+
NOT EXISTS (
|
|
1124
|
+
SELECT 1 FROM candidate AS internal_parent
|
|
1125
|
+
WHERE internal_parent.id = candidate.depends_on
|
|
1126
|
+
)
|
|
1127
|
+
AND EXISTS (
|
|
1128
|
+
SELECT 1 FROM tasks AS external_parent
|
|
1129
|
+
WHERE external_parent.id = candidate.depends_on
|
|
1130
|
+
AND external_parent.cwd IS candidate.cwd
|
|
1131
|
+
AND (
|
|
1132
|
+
external_parent.status IN ('pending', 'running', 'done')
|
|
1133
|
+
OR (
|
|
1134
|
+
external_parent.status = 'failed'
|
|
1135
|
+
AND external_parent.retry_count <= external_parent.max_retries
|
|
1136
|
+
)
|
|
1137
|
+
)
|
|
1138
|
+
)
|
|
1139
|
+
)
|
|
1140
|
+
UNION
|
|
1141
|
+
SELECT child.id,
|
|
1142
|
+
child.cwd,
|
|
1143
|
+
child.depends_on
|
|
1144
|
+
FROM candidate AS child
|
|
1145
|
+
INNER JOIN retryable AS parent
|
|
1146
|
+
ON child.depends_on = parent.id
|
|
1147
|
+
AND child.cwd IS parent.cwd
|
|
1148
|
+
)
|
|
1149
|
+
UPDATE tasks
|
|
1150
|
+
SET status = 'pending',
|
|
1151
|
+
started_at = NULL,
|
|
1152
|
+
finished_at = NULL,
|
|
1153
|
+
retry_after = NULL,
|
|
1154
|
+
retry_count = 0
|
|
1155
|
+
WHERE id IN (SELECT id FROM retryable)
|
|
1156
|
+
`).run(...parameters).changes, { behavior: "immediate" });
|
|
1157
|
+
}
|
|
1158
|
+
static async getById(id, scope = {}) {
|
|
1159
|
+
const conditions = [eq(tasks.id, id), ...this.buildScopeWhere(scope)];
|
|
1160
|
+
const result = await db.select().from(tasks).where(and(...conditions));
|
|
1161
|
+
return result[0] || null;
|
|
1162
|
+
}
|
|
1163
|
+
static async list(options = {}) {
|
|
1164
|
+
const conditions = this.buildListConditions(options);
|
|
1165
|
+
let query = (options.excludeResultLog ? db.select({
|
|
1166
|
+
id: tasks.id,
|
|
1167
|
+
name: tasks.name,
|
|
1168
|
+
agent: tasks.agent,
|
|
1169
|
+
model: tasks.model,
|
|
1170
|
+
variant: tasks.variant,
|
|
1171
|
+
prompt: tasks.prompt,
|
|
1172
|
+
cwd: tasks.cwd,
|
|
1173
|
+
category: tasks.category,
|
|
1174
|
+
importance: tasks.importance,
|
|
1175
|
+
urgency: tasks.urgency,
|
|
1176
|
+
batchId: tasks.batchId,
|
|
1177
|
+
dependsOn: tasks.dependsOn,
|
|
1178
|
+
status: tasks.status,
|
|
1179
|
+
createdAt: tasks.createdAt,
|
|
1180
|
+
startedAt: tasks.startedAt,
|
|
1181
|
+
finishedAt: tasks.finishedAt,
|
|
1182
|
+
resultLog: sql`NULL`,
|
|
1183
|
+
retryCount: tasks.retryCount,
|
|
1184
|
+
maxRetries: tasks.maxRetries,
|
|
1185
|
+
retryBackoffMs: tasks.retryBackoffMs,
|
|
1186
|
+
retryAfter: tasks.retryAfter,
|
|
1187
|
+
timeoutMs: tasks.timeoutMs,
|
|
1188
|
+
templateId: tasks.templateId,
|
|
1189
|
+
scheduledAt: tasks.scheduledAt
|
|
1190
|
+
}).from(tasks) : db.select().from(tasks)).$dynamic();
|
|
1191
|
+
if (conditions.length > 0) {
|
|
1192
|
+
query = query.where(and(...conditions));
|
|
1193
|
+
}
|
|
1194
|
+
query = query.orderBy(desc(tasks.createdAt), desc(tasks.id));
|
|
1195
|
+
if (options.limit) {
|
|
1196
|
+
query = query.limit(options.limit);
|
|
1197
|
+
}
|
|
1198
|
+
if (options.offset) {
|
|
1199
|
+
query = query.offset(options.offset);
|
|
1200
|
+
}
|
|
1201
|
+
return await query;
|
|
1202
|
+
}
|
|
1203
|
+
static async listCompact(options = {}) {
|
|
1204
|
+
const conditions = this.buildListConditions(options);
|
|
1205
|
+
let query = db.select({
|
|
1206
|
+
id: tasks.id,
|
|
1207
|
+
name: tasks.name,
|
|
1208
|
+
agent: tasks.agent,
|
|
1209
|
+
model: tasks.model,
|
|
1210
|
+
variant: tasks.variant,
|
|
1211
|
+
prompt: tasks.prompt,
|
|
1212
|
+
cwd: tasks.cwd,
|
|
1213
|
+
category: tasks.category,
|
|
1214
|
+
importance: tasks.importance,
|
|
1215
|
+
urgency: tasks.urgency,
|
|
1216
|
+
batchId: tasks.batchId,
|
|
1217
|
+
dependsOn: tasks.dependsOn,
|
|
1218
|
+
status: tasks.status,
|
|
1219
|
+
createdAt: tasks.createdAt,
|
|
1220
|
+
startedAt: tasks.startedAt,
|
|
1221
|
+
finishedAt: tasks.finishedAt,
|
|
1222
|
+
retryCount: tasks.retryCount,
|
|
1223
|
+
maxRetries: tasks.maxRetries,
|
|
1224
|
+
retryBackoffMs: tasks.retryBackoffMs,
|
|
1225
|
+
retryAfter: tasks.retryAfter,
|
|
1226
|
+
timeoutMs: tasks.timeoutMs,
|
|
1227
|
+
templateId: tasks.templateId,
|
|
1228
|
+
scheduledAt: tasks.scheduledAt,
|
|
1229
|
+
hasResultLog: sql`CASE WHEN ${tasks.resultLog} IS NOT NULL AND length(${tasks.resultLog}) > 0 THEN 1 ELSE 0 END`,
|
|
1230
|
+
resultLogPreview: sql`CASE WHEN ${tasks.resultLog} IS NULL THEN NULL WHEN ${tasks.status} IN ('failed', 'dead_letter') THEN substr(${tasks.resultLog}, -512) ELSE substr(${tasks.resultLog}, 1, 512) END`
|
|
1231
|
+
}).from(tasks).$dynamic();
|
|
1232
|
+
if (conditions.length > 0) {
|
|
1233
|
+
query = query.where(and(...conditions));
|
|
1234
|
+
}
|
|
1235
|
+
query = query.orderBy(desc(tasks.createdAt), desc(tasks.id));
|
|
1236
|
+
if (options.limit) query = query.limit(options.limit);
|
|
1237
|
+
if (options.offset) query = query.offset(options.offset);
|
|
1238
|
+
const rows = await query;
|
|
1239
|
+
return rows.map((row) => ({
|
|
1240
|
+
...row,
|
|
1241
|
+
resultLog: null,
|
|
1242
|
+
hasResultLog: Number(row.hasResultLog) === 1,
|
|
1243
|
+
resultLogPreview: row.resultLogPreview
|
|
1244
|
+
}));
|
|
1245
|
+
}
|
|
1246
|
+
static async stats(options = {}) {
|
|
1247
|
+
const conditions = [];
|
|
1248
|
+
if (options.batchId !== void 0) {
|
|
1249
|
+
const batchId = normalizeTaskBatchId(options.batchId);
|
|
1250
|
+
conditions.push(batchId ? batchIdMatchCondition(batchId) : sql`0`);
|
|
1251
|
+
}
|
|
1252
|
+
if (options.legacyCwd) {
|
|
1253
|
+
conditions.push(legacyCwdCondition());
|
|
1254
|
+
} else if (options.cwd !== void 0) {
|
|
1255
|
+
conditions.push(eq(tasks.cwd, options.cwd));
|
|
1256
|
+
}
|
|
1257
|
+
const whereCondition = conditions.length > 0 ? and(...conditions) : void 0;
|
|
1258
|
+
const result = await db.select({
|
|
1259
|
+
status: tasks.status,
|
|
1260
|
+
count: sql`count(*)`
|
|
1261
|
+
}).from(tasks).where(whereCondition).groupBy(tasks.status);
|
|
1262
|
+
const stats = {
|
|
1263
|
+
total: 0,
|
|
1264
|
+
pending: 0,
|
|
1265
|
+
running: 0,
|
|
1266
|
+
done: 0,
|
|
1267
|
+
failed: 0,
|
|
1268
|
+
dead_letter: 0,
|
|
1269
|
+
cancelled: 0
|
|
1270
|
+
};
|
|
1271
|
+
for (const row of result) {
|
|
1272
|
+
if (row.status) {
|
|
1273
|
+
stats[row.status] = Number(row.count);
|
|
1274
|
+
stats.total += Number(row.count);
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
return stats;
|
|
1278
|
+
}
|
|
1279
|
+
static async dashboardOverview(cwdOrOptions) {
|
|
1280
|
+
const options = typeof cwdOrOptions === "string" ? { cwd: cwdOrOptions } : cwdOrOptions ?? {};
|
|
1281
|
+
const projectLimit = options.projectLimit ?? 100;
|
|
1282
|
+
validateIntegerField("projectLimit", projectLimit, 1, 1e3);
|
|
1283
|
+
const cutoff7dSec = Math.floor(Date.now() / 1e3) - 7 * 86400;
|
|
1284
|
+
const sqlite = getSqlite();
|
|
1285
|
+
const insideOuterTransaction = sqlite.inTransaction;
|
|
1286
|
+
let cacheEntry = dashboardOverviewCache.get(sqlite);
|
|
1287
|
+
if (!cacheEntry) {
|
|
1288
|
+
cacheEntry = { writeEpoch: 0, snapshot: null };
|
|
1289
|
+
dashboardOverviewCache.set(sqlite, cacheEntry);
|
|
1290
|
+
}
|
|
1291
|
+
let snapshot = null;
|
|
1292
|
+
if (!insideOuterTransaction) {
|
|
1293
|
+
const stamp = readSqliteMutationStamp(sqlite);
|
|
1294
|
+
const cached = cacheEntry.snapshot;
|
|
1295
|
+
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);
|
|
1296
|
+
if (cacheHit) {
|
|
1297
|
+
snapshot = cached;
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
if (snapshot === null) {
|
|
1301
|
+
let statusRows;
|
|
1302
|
+
let extraActiveRows;
|
|
1303
|
+
let snapshotStamp = null;
|
|
1304
|
+
let snapshotWriteEpoch = cacheEntry.writeEpoch;
|
|
1305
|
+
if (!insideOuterTransaction) {
|
|
1306
|
+
sqlite.exec("BEGIN DEFERRED");
|
|
1307
|
+
}
|
|
1308
|
+
try {
|
|
1309
|
+
statusRows = sqlite.query(DASHBOARD_OVERVIEW_BY_STATUS_SQL).all(
|
|
1310
|
+
cutoff7dSec,
|
|
1311
|
+
cutoff7dSec,
|
|
1312
|
+
cutoff7dSec,
|
|
1313
|
+
cutoff7dSec,
|
|
1314
|
+
cutoff7dSec
|
|
1315
|
+
);
|
|
1316
|
+
extraActiveRows = sqlite.query(DASHBOARD_OVERVIEW_EXTRA_ACTIVE_RUNS_SQL).all();
|
|
1317
|
+
if (!insideOuterTransaction) {
|
|
1318
|
+
snapshotStamp = readSqliteMutationStamp(sqlite);
|
|
1319
|
+
snapshotWriteEpoch = cacheEntry.writeEpoch;
|
|
1320
|
+
sqlite.exec("COMMIT");
|
|
1321
|
+
}
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
if (!insideOuterTransaction && sqlite.inTransaction) {
|
|
1324
|
+
try {
|
|
1325
|
+
sqlite.exec("ROLLBACK");
|
|
1326
|
+
} catch {
|
|
1327
|
+
}
|
|
1328
|
+
}
|
|
1329
|
+
throw error;
|
|
1330
|
+
}
|
|
1331
|
+
const globalStats = emptyDashboardStats();
|
|
1332
|
+
const legacyStats = emptyDashboardStats();
|
|
1333
|
+
let hasLegacyCwd = false;
|
|
1334
|
+
let legacyTaskCount = 0;
|
|
1335
|
+
let next7dExpirySec = null;
|
|
1336
|
+
const projectMap = /* @__PURE__ */ new Map();
|
|
1337
|
+
const getOrCreateProject = (cwd) => {
|
|
1338
|
+
let acc = projectMap.get(cwd);
|
|
1339
|
+
if (!acc) {
|
|
1340
|
+
acc = {
|
|
1341
|
+
cwd,
|
|
1342
|
+
stats: emptyDashboardStats(),
|
|
1343
|
+
lastCreatedAtSec: -1,
|
|
1344
|
+
lastTaskId: 0,
|
|
1345
|
+
done7d: 0,
|
|
1346
|
+
failed7d: 0,
|
|
1347
|
+
durationSumMs7d: 0,
|
|
1348
|
+
durationCount7d: 0
|
|
1349
|
+
};
|
|
1350
|
+
projectMap.set(cwd, acc);
|
|
1351
|
+
}
|
|
1352
|
+
return acc;
|
|
1353
|
+
};
|
|
1354
|
+
const applyStatusCount = (target, status, count) => {
|
|
1355
|
+
target.total += count;
|
|
1356
|
+
switch (status) {
|
|
1357
|
+
case "pending":
|
|
1358
|
+
target.pending += count;
|
|
1359
|
+
break;
|
|
1360
|
+
case "running":
|
|
1361
|
+
target.running += count;
|
|
1362
|
+
target.activeExecution += count;
|
|
1363
|
+
break;
|
|
1364
|
+
case "done":
|
|
1365
|
+
target.done += count;
|
|
1366
|
+
break;
|
|
1367
|
+
case "failed":
|
|
1368
|
+
target.failed += count;
|
|
1369
|
+
break;
|
|
1370
|
+
case "dead_letter":
|
|
1371
|
+
target.dead_letter += count;
|
|
1372
|
+
break;
|
|
1373
|
+
case "cancelled":
|
|
1374
|
+
target.cancelled += count;
|
|
1375
|
+
break;
|
|
1376
|
+
}
|
|
1377
|
+
};
|
|
1378
|
+
for (const row of statusRows) {
|
|
1379
|
+
const count = Number(row.status_count ?? 0);
|
|
1380
|
+
applyStatusCount(globalStats, row.task_status, count);
|
|
1381
|
+
if (row.min_finished_7d !== null && row.min_finished_7d !== void 0) {
|
|
1382
|
+
const candidate = Number(row.min_finished_7d);
|
|
1383
|
+
if (next7dExpirySec === null || candidate < next7dExpirySec) {
|
|
1384
|
+
next7dExpirySec = candidate;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
const isLegacy = row.project_cwd === null || row.project_cwd.trim() === "";
|
|
1388
|
+
if (isLegacy) {
|
|
1389
|
+
if (count > 0) hasLegacyCwd = true;
|
|
1390
|
+
legacyTaskCount += count;
|
|
1391
|
+
applyStatusCount(legacyStats, row.task_status, count);
|
|
1392
|
+
continue;
|
|
1393
|
+
}
|
|
1394
|
+
const acc = getOrCreateProject(row.project_cwd);
|
|
1395
|
+
applyStatusCount(acc.stats, row.task_status, count);
|
|
1396
|
+
const rowCreated = row.last_created_at === null ? -1 : Number(row.last_created_at);
|
|
1397
|
+
if (rowCreated > acc.lastCreatedAtSec) acc.lastCreatedAtSec = rowCreated;
|
|
1398
|
+
const rowLastId = Number(row.last_task_id ?? 0);
|
|
1399
|
+
if (rowLastId > acc.lastTaskId) acc.lastTaskId = rowLastId;
|
|
1400
|
+
acc.done7d += Number(row.done_7d ?? 0);
|
|
1401
|
+
acc.failed7d += Number(row.failed_7d ?? 0);
|
|
1402
|
+
acc.durationSumMs7d += Number(row.duration_sum_ms_7d ?? 0);
|
|
1403
|
+
acc.durationCount7d += Number(row.duration_count_7d ?? 0);
|
|
1404
|
+
}
|
|
1405
|
+
for (const extraRow of extraActiveRows) {
|
|
1406
|
+
const extra = Number(extraRow.extra_active ?? 0);
|
|
1407
|
+
if (extra <= 0) continue;
|
|
1408
|
+
globalStats.activeExecution += extra;
|
|
1409
|
+
const isLegacy = extraRow.project_cwd === null || extraRow.project_cwd.trim() === "";
|
|
1410
|
+
if (isLegacy) {
|
|
1411
|
+
legacyStats.activeExecution += extra;
|
|
1412
|
+
continue;
|
|
1413
|
+
}
|
|
1414
|
+
const acc = projectMap.get(extraRow.project_cwd);
|
|
1415
|
+
if (acc) {
|
|
1416
|
+
acc.stats.activeExecution += extra;
|
|
1417
|
+
}
|
|
1418
|
+
}
|
|
1419
|
+
const byCwdStats = /* @__PURE__ */ new Map();
|
|
1420
|
+
const sortedAccumulators = [...projectMap.values()].sort((a, b) => b.lastCreatedAtSec - a.lastCreatedAtSec || b.lastTaskId - a.lastTaskId);
|
|
1421
|
+
const sortedProjects = [];
|
|
1422
|
+
for (const acc of sortedAccumulators) {
|
|
1423
|
+
byCwdStats.set(acc.cwd, acc.stats);
|
|
1424
|
+
sortedProjects.push({
|
|
1425
|
+
cwd: acc.cwd,
|
|
1426
|
+
total: acc.stats.total,
|
|
1427
|
+
pending: acc.stats.pending,
|
|
1428
|
+
running: acc.stats.activeExecution,
|
|
1429
|
+
failed: acc.stats.failed + acc.stats.dead_letter,
|
|
1430
|
+
done: acc.stats.done,
|
|
1431
|
+
deadLetter: acc.stats.dead_letter,
|
|
1432
|
+
cancelled: acc.stats.cancelled,
|
|
1433
|
+
lastCreatedAt: acc.lastCreatedAtSec < 0 ? null : acc.lastCreatedAtSec * 1e3,
|
|
1434
|
+
done7d: acc.done7d,
|
|
1435
|
+
failed7d: acc.failed7d,
|
|
1436
|
+
avgDurationMs7d: acc.durationCount7d > 0 ? Math.round(acc.durationSumMs7d / acc.durationCount7d) : null
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
snapshot = {
|
|
1440
|
+
dataVersion: snapshotStamp?.dataVersion ?? -1,
|
|
1441
|
+
totalChanges: snapshotStamp?.totalChanges ?? -1,
|
|
1442
|
+
writeEpoch: snapshotWriteEpoch,
|
|
1443
|
+
computedCutoff7dSec: cutoff7dSec,
|
|
1444
|
+
next7dExpirySec,
|
|
1445
|
+
global: globalStats,
|
|
1446
|
+
legacyStats,
|
|
1447
|
+
hasLegacyCwd,
|
|
1448
|
+
legacyTaskCount,
|
|
1449
|
+
byCwdStats,
|
|
1450
|
+
sortedProjects
|
|
1451
|
+
};
|
|
1452
|
+
if (!insideOuterTransaction && snapshotStamp !== null) {
|
|
1453
|
+
cacheEntry.snapshot = snapshot;
|
|
1454
|
+
}
|
|
1455
|
+
}
|
|
1456
|
+
const resolvedScoped = options.legacyCwd ? cloneDashboardStats(snapshot.legacyStats) : options.cwd !== void 0 ? cloneDashboardStats(snapshot.byCwdStats.get(options.cwd) ?? emptyDashboardStats()) : cloneDashboardStats(snapshot.global);
|
|
1457
|
+
return {
|
|
1458
|
+
global: cloneDashboardStats(snapshot.global),
|
|
1459
|
+
scoped: resolvedScoped,
|
|
1460
|
+
projects: snapshot.sortedProjects.slice(0, projectLimit).map((item) => ({ ...item })),
|
|
1461
|
+
hasLegacyCwd: snapshot.hasLegacyCwd,
|
|
1462
|
+
legacyTaskCount: snapshot.legacyTaskCount
|
|
1463
|
+
};
|
|
1464
|
+
}
|
|
1465
|
+
static async projectSummaries(limit = 100) {
|
|
1466
|
+
validateIntegerField("limit", limit, 1, 1e3);
|
|
1467
|
+
const overview = await this.dashboardOverview({ projectLimit: limit });
|
|
1468
|
+
return overview.projects.map((project) => ({
|
|
1469
|
+
cwd: project.cwd,
|
|
1470
|
+
total: project.total,
|
|
1471
|
+
pending: project.pending,
|
|
1472
|
+
running: project.running,
|
|
1473
|
+
failed: project.failed,
|
|
1474
|
+
done: project.done,
|
|
1475
|
+
lastCreatedAt: project.lastCreatedAt
|
|
1476
|
+
}));
|
|
1477
|
+
}
|
|
1478
|
+
static async delete(id, scope = {}) {
|
|
1479
|
+
const conditions = [
|
|
1480
|
+
eq(tasks.id, id),
|
|
1481
|
+
sql`${tasks.status} <> 'running'`,
|
|
1482
|
+
sql`NOT EXISTS (
|
|
1483
|
+
SELECT 1 FROM ${taskRuns}
|
|
1484
|
+
WHERE ${taskRuns.taskId} = ${tasks.id}
|
|
1485
|
+
AND ${taskRuns.status} = 'running'
|
|
1486
|
+
)`,
|
|
1487
|
+
hasNoExecutableDependents(),
|
|
1488
|
+
...this.buildScopeWhere(scope)
|
|
1489
|
+
];
|
|
1490
|
+
const result = await db.delete(tasks).where(and(...conditions)).returning();
|
|
1491
|
+
if (result.length > 0) {
|
|
1492
|
+
await db.delete(taskRuns).where(eq(taskRuns.taskId, id));
|
|
1493
|
+
return true;
|
|
1494
|
+
}
|
|
1495
|
+
if (!await this.getById(id, scope)) return false;
|
|
1496
|
+
const dependent = await db.select({ id: tasks.id }).from(tasks).where(and(
|
|
1497
|
+
eq(tasks.dependsOn, id),
|
|
1498
|
+
sql`${tasks.status} IN ('pending', 'running', 'failed', 'dead_letter')`
|
|
1499
|
+
)).orderBy(asc(tasks.id)).limit(1);
|
|
1500
|
+
if (dependent[0]) {
|
|
1501
|
+
throw new TaskDeletionConflictError(
|
|
1502
|
+
`\u4EFB\u52A1 #${id} \u4ECD\u88AB\u53EF\u6267\u884C\u4EFB\u52A1 #${dependent[0].id} \u4F9D\u8D56\uFF0C\u8BF7\u5148\u5904\u7406\u4F9D\u8D56\u4EFB\u52A1`
|
|
1503
|
+
);
|
|
1504
|
+
}
|
|
1505
|
+
throw new TaskDeletionConflictError(
|
|
1506
|
+
`\u4EFB\u52A1 #${id} \u6B63\u5728\u8FD0\u884C\uFF0C\u8BF7\u5148\u53D6\u6D88\u4EFB\u52A1\u5E76\u7B49\u5F85\u6267\u884C\u8FDB\u7A0B\u9000\u51FA`
|
|
1507
|
+
);
|
|
1508
|
+
}
|
|
1509
|
+
static async deleteBatch(ids, scope = {}) {
|
|
1510
|
+
const uniqueIds = [...new Set(ids.filter((id) => Number.isInteger(id) && id > 0))];
|
|
1511
|
+
if (uniqueIds.length === 0) {
|
|
1512
|
+
return { deletedIds: [], notFoundIds: [], conflicts: [], deletedCount: 0 };
|
|
1513
|
+
}
|
|
1514
|
+
return db.transaction((tx) => {
|
|
1515
|
+
const deletedIds = [];
|
|
1516
|
+
let remaining = [...uniqueIds].sort((a, b) => b - a);
|
|
1517
|
+
while (remaining.length > 0) {
|
|
1518
|
+
let progressed = false;
|
|
1519
|
+
const nextRemaining = [];
|
|
1520
|
+
for (const id of remaining) {
|
|
1521
|
+
const deleted = tx.delete(tasks).where(and(
|
|
1522
|
+
eq(tasks.id, id),
|
|
1523
|
+
sql`${tasks.status} <> 'running'`,
|
|
1524
|
+
sql`NOT EXISTS (
|
|
1525
|
+
SELECT 1 FROM ${taskRuns}
|
|
1526
|
+
WHERE ${taskRuns.taskId} = ${tasks.id}
|
|
1527
|
+
AND ${taskRuns.status} = 'running'
|
|
1528
|
+
)`,
|
|
1529
|
+
hasNoExecutableDependents(),
|
|
1530
|
+
...this.buildScopeWhere(scope)
|
|
1531
|
+
)).returning({ id: tasks.id }).get();
|
|
1532
|
+
if (deleted) {
|
|
1533
|
+
tx.delete(taskRuns).where(eq(taskRuns.taskId, id)).run();
|
|
1534
|
+
deletedIds.push(id);
|
|
1535
|
+
progressed = true;
|
|
1536
|
+
} else {
|
|
1537
|
+
nextRemaining.push(id);
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
remaining = nextRemaining;
|
|
1541
|
+
if (!progressed) break;
|
|
1542
|
+
}
|
|
1543
|
+
const notFoundIds = [];
|
|
1544
|
+
const conflicts = [];
|
|
1545
|
+
for (const id of remaining) {
|
|
1546
|
+
const exists = tx.select({ id: tasks.id }).from(tasks).where(and(eq(tasks.id, id), ...this.buildScopeWhere(scope))).get();
|
|
1547
|
+
if (!exists) {
|
|
1548
|
+
notFoundIds.push(id);
|
|
1549
|
+
continue;
|
|
1550
|
+
}
|
|
1551
|
+
const dependent = tx.select({ id: tasks.id }).from(tasks).where(and(
|
|
1552
|
+
eq(tasks.dependsOn, id),
|
|
1553
|
+
sql`${tasks.status} IN ('pending', 'running', 'failed', 'dead_letter')`
|
|
1554
|
+
)).orderBy(asc(tasks.id)).limit(1).get();
|
|
1555
|
+
conflicts.push({
|
|
1556
|
+
id,
|
|
1557
|
+
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`
|
|
1558
|
+
});
|
|
1559
|
+
}
|
|
1560
|
+
return {
|
|
1561
|
+
deletedIds,
|
|
1562
|
+
notFoundIds,
|
|
1563
|
+
conflicts,
|
|
1564
|
+
deletedCount: deletedIds.length
|
|
1565
|
+
};
|
|
1566
|
+
}, { behavior: "immediate" });
|
|
1567
|
+
}
|
|
1568
|
+
static async deleteOlderThan(retentionDays, shouldStop = () => false) {
|
|
1569
|
+
const cutoffSec = Math.floor(Date.now() / 1e3) - retentionDays * 86400;
|
|
1570
|
+
const batchSize = 500;
|
|
1571
|
+
const sqlite = getSqlite();
|
|
1572
|
+
cleanupInvocation += 1;
|
|
1573
|
+
const candidateTable = `cleanup_candidates_${process.pid}_${cleanupInvocation}`;
|
|
1574
|
+
let deletedTotal = 0;
|
|
1575
|
+
sqlite.exec(`
|
|
1576
|
+
CREATE TEMP TABLE ${candidateTable} (
|
|
1577
|
+
id INTEGER NOT NULL PRIMARY KEY
|
|
1578
|
+
) WITHOUT ROWID;
|
|
1579
|
+
`);
|
|
1580
|
+
const clearCandidatesStmt = sqlite.prepare(`DELETE FROM ${candidateTable}`);
|
|
1581
|
+
const firstPageCandidatesStmt = sqlite.prepare(`
|
|
1582
|
+
INSERT INTO ${candidateTable}(id)
|
|
1583
|
+
SELECT candidate.id
|
|
1584
|
+
FROM tasks AS candidate
|
|
1585
|
+
WHERE candidate.status IN ('done', 'dead_letter', 'cancelled')
|
|
1586
|
+
AND candidate.finished_at IS NOT NULL
|
|
1587
|
+
AND candidate.finished_at < ?
|
|
1588
|
+
AND NOT EXISTS (
|
|
1589
|
+
SELECT 1 FROM task_runs AS active_run
|
|
1590
|
+
WHERE active_run.task_id = candidate.id
|
|
1591
|
+
AND active_run.status = 'running'
|
|
1592
|
+
)
|
|
1593
|
+
ORDER BY candidate.id DESC
|
|
1594
|
+
LIMIT ?
|
|
1595
|
+
`);
|
|
1596
|
+
const nextPageCandidatesStmt = sqlite.prepare(`
|
|
1597
|
+
INSERT INTO ${candidateTable}(id)
|
|
1598
|
+
SELECT candidate.id
|
|
1599
|
+
FROM tasks AS candidate
|
|
1600
|
+
WHERE candidate.status IN ('done', 'dead_letter', 'cancelled')
|
|
1601
|
+
AND candidate.finished_at IS NOT NULL
|
|
1602
|
+
AND candidate.finished_at < ?
|
|
1603
|
+
AND candidate.id < ?
|
|
1604
|
+
AND NOT EXISTS (
|
|
1605
|
+
SELECT 1 FROM task_runs AS active_run
|
|
1606
|
+
WHERE active_run.task_id = candidate.id
|
|
1607
|
+
AND active_run.status = 'running'
|
|
1608
|
+
)
|
|
1609
|
+
ORDER BY candidate.id DESC
|
|
1610
|
+
LIMIT ?
|
|
1611
|
+
`);
|
|
1612
|
+
const minCandidateStmt = sqlite.prepare(`SELECT min(id) AS nextCeilingId FROM ${candidateTable}`);
|
|
1613
|
+
const pruneAnomalousStmt = sqlite.prepare(`
|
|
1614
|
+
DELETE FROM ${candidateTable}
|
|
1615
|
+
WHERE EXISTS (
|
|
1616
|
+
SELECT 1 FROM tasks AS anomalous
|
|
1617
|
+
WHERE anomalous.id = ${candidateTable}.id
|
|
1618
|
+
AND anomalous.depends_on IS NOT NULL
|
|
1619
|
+
AND anomalous.depends_on >= anomalous.id
|
|
1620
|
+
)
|
|
1621
|
+
`);
|
|
1622
|
+
const pruneDependentStmt = sqlite.prepare(`
|
|
1623
|
+
DELETE FROM ${candidateTable}
|
|
1624
|
+
WHERE EXISTS (
|
|
1625
|
+
SELECT 1 FROM tasks AS dependent_task
|
|
1626
|
+
WHERE dependent_task.depends_on = ${candidateTable}.id
|
|
1627
|
+
AND NOT EXISTS (
|
|
1628
|
+
SELECT 1 FROM ${candidateTable} AS selected_dependent
|
|
1629
|
+
WHERE selected_dependent.id = dependent_task.id
|
|
1630
|
+
)
|
|
1631
|
+
)
|
|
1632
|
+
`);
|
|
1633
|
+
const countSelectedStmt = sqlite.prepare(`SELECT count(*) AS count FROM ${candidateTable}`);
|
|
1634
|
+
const deleteTasksStmt = sqlite.prepare(`
|
|
1635
|
+
DELETE FROM tasks
|
|
1636
|
+
WHERE id IN (SELECT id FROM ${candidateTable})
|
|
1637
|
+
`);
|
|
1638
|
+
const verifyRemainingStmt = sqlite.prepare(`
|
|
1639
|
+
SELECT count(*) AS count
|
|
1640
|
+
FROM tasks
|
|
1641
|
+
WHERE id IN (SELECT id FROM ${candidateTable})
|
|
1642
|
+
`);
|
|
1643
|
+
try {
|
|
1644
|
+
let ceilingId = null;
|
|
1645
|
+
while (true) {
|
|
1646
|
+
if (shouldStop()) return deletedTotal;
|
|
1647
|
+
const batch = db.transaction(() => {
|
|
1648
|
+
clearCandidatesStmt.run();
|
|
1649
|
+
const rawCount = ceilingId == null ? firstPageCandidatesStmt.run(cutoffSec, batchSize).changes : nextPageCandidatesStmt.run(cutoffSec, ceilingId, batchSize).changes;
|
|
1650
|
+
if (rawCount === 0) return { deleted: 0, nextCeilingId: null };
|
|
1651
|
+
const rawPage = minCandidateStmt.get();
|
|
1652
|
+
pruneAnomalousStmt.run();
|
|
1653
|
+
while (true) {
|
|
1654
|
+
const pruned = pruneDependentStmt.run().changes;
|
|
1655
|
+
if (pruned === 0) break;
|
|
1656
|
+
}
|
|
1657
|
+
const selected = countSelectedStmt.get();
|
|
1658
|
+
if (selected.count === 0) {
|
|
1659
|
+
return { deleted: 0, nextCeilingId: rawPage.nextCeilingId };
|
|
1660
|
+
}
|
|
1661
|
+
deleteTasksStmt.run();
|
|
1662
|
+
const remaining = verifyRemainingStmt.get();
|
|
1663
|
+
if (remaining.count !== 0) {
|
|
1664
|
+
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");
|
|
1665
|
+
}
|
|
1666
|
+
return { deleted: selected.count, nextCeilingId: rawPage.nextCeilingId };
|
|
1667
|
+
}, { behavior: "immediate" });
|
|
1668
|
+
if (batch.nextCeilingId == null) break;
|
|
1669
|
+
ceilingId = batch.nextCeilingId;
|
|
1670
|
+
deletedTotal += batch.deleted;
|
|
1671
|
+
await Bun.sleep(0);
|
|
1672
|
+
if (shouldStop()) return deletedTotal;
|
|
1673
|
+
}
|
|
1674
|
+
return deletedTotal;
|
|
1675
|
+
} finally {
|
|
1676
|
+
clearCandidatesStmt.finalize();
|
|
1677
|
+
firstPageCandidatesStmt.finalize();
|
|
1678
|
+
nextPageCandidatesStmt.finalize();
|
|
1679
|
+
minCandidateStmt.finalize();
|
|
1680
|
+
pruneAnomalousStmt.finalize();
|
|
1681
|
+
pruneDependentStmt.finalize();
|
|
1682
|
+
countSelectedStmt.finalize();
|
|
1683
|
+
deleteTasksStmt.finalize();
|
|
1684
|
+
verifyRemainingStmt.finalize();
|
|
1685
|
+
sqlite.exec(`DROP TABLE IF EXISTS ${candidateTable}`);
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
};
|
|
1689
|
+
|
|
1690
|
+
export {
|
|
1691
|
+
validateTaskWorkingDirectory,
|
|
1692
|
+
TASK_BATCH_TRIM_CHARACTERS,
|
|
1693
|
+
normalizeTaskBatchId,
|
|
1694
|
+
normalizeModelVariant,
|
|
1695
|
+
TaskDeletionConflictError,
|
|
1696
|
+
validateIntegerField,
|
|
1697
|
+
validateCommonTaskFields,
|
|
1698
|
+
invalidateDashboardOverviewCache,
|
|
1699
|
+
TaskService
|
|
1700
|
+
};
|
|
1701
|
+
//# sourceMappingURL=chunk-EQWICVCJ.js.map
|