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.
Files changed (99) hide show
  1. package/CHANGELOG.md +95 -1
  2. package/LICENSE +21 -0
  3. package/README.md +73 -39
  4. package/README.zh-CN.md +73 -39
  5. package/dist/cli/chunk-3PIYMBV3.js +45 -0
  6. package/dist/cli/chunk-3PIYMBV3.js.map +1 -0
  7. package/dist/cli/chunk-4FK5KE6G.js +111 -0
  8. package/dist/cli/chunk-4FK5KE6G.js.map +1 -0
  9. package/dist/cli/chunk-5VKFECHP.js +412 -0
  10. package/dist/cli/chunk-5VKFECHP.js.map +1 -0
  11. package/dist/cli/chunk-AZM76ISG.js +143 -0
  12. package/dist/cli/chunk-AZM76ISG.js.map +1 -0
  13. package/dist/cli/chunk-CMEP6IB4.js +9379 -0
  14. package/dist/cli/chunk-CMEP6IB4.js.map +1 -0
  15. package/dist/cli/chunk-DF56RPNL.js +65 -0
  16. package/dist/cli/chunk-DF56RPNL.js.map +1 -0
  17. package/dist/cli/chunk-DIJEKFBV.js +486 -0
  18. package/dist/cli/chunk-DIJEKFBV.js.map +1 -0
  19. package/dist/cli/chunk-DYXFSX5J.js +28 -0
  20. package/dist/cli/chunk-DYXFSX5J.js.map +1 -0
  21. package/dist/cli/chunk-EQWICVCJ.js +1701 -0
  22. package/dist/cli/chunk-EQWICVCJ.js.map +1 -0
  23. package/dist/cli/chunk-GHXFMJTS.js +42 -0
  24. package/dist/cli/chunk-GHXFMJTS.js.map +1 -0
  25. package/dist/cli/chunk-IYYBJHZF.js +28 -0
  26. package/dist/cli/chunk-IYYBJHZF.js.map +1 -0
  27. package/dist/cli/chunk-J34FWHQU.js +376 -0
  28. package/dist/cli/chunk-J34FWHQU.js.map +1 -0
  29. package/dist/cli/chunk-LX5CBJLP.js +121 -0
  30. package/dist/cli/chunk-LX5CBJLP.js.map +1 -0
  31. package/dist/cli/chunk-MVQ2XONT.js +139 -0
  32. package/dist/cli/chunk-MVQ2XONT.js.map +1 -0
  33. package/dist/cli/chunk-NCT3ETTK.js +1332 -0
  34. package/dist/cli/chunk-NCT3ETTK.js.map +1 -0
  35. package/dist/cli/chunk-YB7MYTE5.js +34 -0
  36. package/dist/cli/chunk-YB7MYTE5.js.map +1 -0
  37. package/dist/cli/chunk-YGELD2E5.js +5464 -0
  38. package/dist/cli/chunk-YGELD2E5.js.map +1 -0
  39. package/dist/cli/chunk-ZBH7YWXF.js +314 -0
  40. package/dist/cli/chunk-ZBH7YWXF.js.map +1 -0
  41. package/dist/cli/config-ED56ZLHY.js +20 -0
  42. package/dist/cli/config-ED56ZLHY.js.map +1 -0
  43. package/dist/cli/database-maintenance.service-F3IZU52F.js +16 -0
  44. package/dist/cli/database-maintenance.service-F3IZU52F.js.map +1 -0
  45. package/dist/cli/database-output-GH7F6X6D.js +165 -0
  46. package/dist/cli/database-output-GH7F6X6D.js.map +1 -0
  47. package/dist/cli/db-H7GIFWS2.js +26 -0
  48. package/dist/cli/db-H7GIFWS2.js.map +1 -0
  49. package/dist/cli/doctor-smoke-QXHF7UNN.js +150 -0
  50. package/dist/cli/doctor-smoke-QXHF7UNN.js.map +1 -0
  51. package/dist/cli/duration-Q3UMLO6F.js +10 -0
  52. package/dist/cli/duration-Q3UMLO6F.js.map +1 -0
  53. package/dist/cli/gateway-HNMX5ZTO.js +1738 -0
  54. package/dist/cli/gateway-HNMX5ZTO.js.map +1 -0
  55. package/dist/cli/gateway-wake-U4HTV56Q.js +14 -0
  56. package/dist/cli/gateway-wake-U4HTV56Q.js.map +1 -0
  57. package/dist/cli/index.js +626 -26342
  58. package/dist/cli/index.js.map +1 -1
  59. package/dist/cli/job-templates-RPQJ4XXW.js +21 -0
  60. package/dist/cli/job-templates-RPQJ4XXW.js.map +1 -0
  61. package/dist/cli/logs-QD2N62KK.js +316 -0
  62. package/dist/cli/logs-QD2N62KK.js.map +1 -0
  63. package/dist/cli/output-2INTEUFQ.js +19 -0
  64. package/dist/cli/output-2INTEUFQ.js.map +1 -0
  65. package/dist/cli/pm2-WY644BUO.js +49 -0
  66. package/dist/cli/pm2-WY644BUO.js.map +1 -0
  67. package/dist/cli/task-run.service-QMDINJKG.js +15 -0
  68. package/dist/cli/task-run.service-QMDINJKG.js.map +1 -0
  69. package/dist/cli/task-template.service-SZBKGLCB.js +12 -0
  70. package/dist/cli/task-template.service-SZBKGLCB.js.map +1 -0
  71. package/dist/cli/task.service-ZVDJ6VSQ.js +19 -0
  72. package/dist/cli/task.service-ZVDJ6VSQ.js.map +1 -0
  73. package/dist/cli/update-FYD546I2.js +2058 -0
  74. package/dist/cli/update-FYD546I2.js.map +1 -0
  75. package/dist/cli/web-2S7DW7XA.js +9403 -0
  76. package/dist/cli/web-2S7DW7XA.js.map +1 -0
  77. package/dist/daemon/gateway-diagnostic-runner.d.ts +2 -0
  78. package/dist/daemon/gateway-diagnostic-runner.js +503 -0
  79. package/dist/daemon/gateway-diagnostic-runner.js.map +1 -0
  80. package/dist/gateway/index.d.ts +82 -1
  81. package/dist/gateway/index.js +9301 -2948
  82. package/dist/gateway/index.js.map +1 -1
  83. package/dist/plugin/supertask.d.ts +157 -1
  84. package/dist/plugin/supertask.js +5066 -1531
  85. package/dist/plugin/supertask.js.map +1 -1
  86. package/dist/pm2-cli-CEDhULjk.d.ts +40 -0
  87. package/dist/web/index.d.ts +36 -34
  88. package/dist/web/index.js +10030 -4341
  89. package/dist/web/index.js.map +1 -1
  90. package/dist/worker/index.d.ts +13 -0
  91. package/dist/worker/index.js +2147 -364
  92. package/dist/worker/index.js.map +1 -1
  93. package/dist/worker/launcher.d.ts +46 -1
  94. package/dist/worker/launcher.js +218 -68
  95. package/dist/worker/launcher.js.map +1 -1
  96. package/drizzle/0009_little_weapon_omega.sql +7 -0
  97. package/drizzle/meta/0009_snapshot.json +681 -0
  98. package/drizzle/meta/_journal.json +7 -0
  99. package/package.json +15 -6
@@ -0,0 +1,45 @@
1
+ #!/usr/bin/env bun
2
+
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
10
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
11
+ }) : x)(function(x) {
12
+ if (typeof require !== "undefined") return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __commonJS = (cb, mod) => function __require2() {
16
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
17
+ };
18
+ var __export = (target, all) => {
19
+ for (var name in all)
20
+ __defProp(target, name, { get: all[name], enumerable: true });
21
+ };
22
+ var __copyProps = (to, from, except, desc) => {
23
+ if (from && typeof from === "object" || typeof from === "function") {
24
+ for (let key of __getOwnPropNames(from))
25
+ if (!__hasOwnProp.call(to, key) && key !== except)
26
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
27
+ }
28
+ return to;
29
+ };
30
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
31
+ // If the importer is in node compatibility mode or this is not an ESM
32
+ // file that has been converted to a CommonJS file using a Babel-
33
+ // compatible transform (i.e. "__esModule" has not been set), then set
34
+ // "default" to the CommonJS "module.exports" for node compatibility.
35
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
36
+ mod
37
+ ));
38
+
39
+ export {
40
+ __require,
41
+ __commonJS,
42
+ __export,
43
+ __toESM
44
+ };
45
+ //# sourceMappingURL=chunk-3PIYMBV3.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -0,0 +1,111 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import {
4
+ cliText
5
+ } from "./chunk-IYYBJHZF.js";
6
+
7
+ // src/cli/output.ts
8
+ function shouldUseJson(options = {}) {
9
+ const isTTY = options.isTTY ?? process.stdout.isTTY === true;
10
+ return options.json === true || !isTTY;
11
+ }
12
+ function padCell(value, width) {
13
+ return value.length >= width ? value : value + " ".repeat(width - value.length);
14
+ }
15
+ function truncateLine(value, maxChars) {
16
+ const singleLine = value.replace(/\s+/g, " ").trim();
17
+ if (singleLine.length <= maxChars) return singleLine;
18
+ return `${singleLine.slice(0, Math.max(0, maxChars - 1))}\u2026`;
19
+ }
20
+ function formatDateValue(value) {
21
+ if (value == null) return "-";
22
+ const date = value instanceof Date ? value : new Date(value);
23
+ if (Number.isNaN(date.getTime())) return "-";
24
+ return date.toISOString().replace("T", " ").slice(0, 19);
25
+ }
26
+ function renderTaskStatus(stats, options = {}) {
27
+ if (shouldUseJson(options)) return JSON.stringify(stats, null, 2);
28
+ const locale = options.locale ?? "zh-CN";
29
+ const header = options.batchId ? cliText(locale, `\u4EFB\u52A1\u7EDF\u8BA1\uFF08\u6279\u6B21\uFF1A${options.batchId}\uFF09`, `Task Status (batch: ${options.batchId})`) : cliText(locale, "\u4EFB\u52A1\u7EDF\u8BA1", "Task Status");
30
+ const rows = [
31
+ [cliText(locale, "\u603B\u8BA1", "total"), stats.total ?? 0],
32
+ [cliText(locale, "\u6392\u961F", "pending"), stats.pending ?? 0],
33
+ [cliText(locale, "\u8FD0\u884C\u4E2D", "running"), stats.running ?? 0],
34
+ [cliText(locale, "\u5DF2\u5B8C\u6210", "done"), stats.done ?? 0],
35
+ [cliText(locale, "\u5931\u8D25\u5F85\u91CD\u8BD5", "failed"), stats.failed ?? 0],
36
+ [cliText(locale, "\u6B7B\u4FE1", "dead_letter"), stats.dead_letter ?? 0],
37
+ [cliText(locale, "\u5DF2\u53D6\u6D88", "cancelled"), stats.cancelled ?? 0]
38
+ ];
39
+ const summary = rows.map(([label, count]) => `${label} ${count}`).join(" \xB7 ");
40
+ return `${header}
41
+ ${summary}`;
42
+ }
43
+ function renderTaskList(tasks, options = {}) {
44
+ if (shouldUseJson(options)) return JSON.stringify(tasks, null, 2);
45
+ const locale = options.locale ?? "zh-CN";
46
+ if (tasks.length === 0) {
47
+ return cliText(locale, "\u6682\u65E0\u5339\u914D\u7684\u4EFB\u52A1\u3002", "No matching tasks.");
48
+ }
49
+ const headers = locale === "en" ? ["ID", "STATUS", "PRI", "AGENT", "BATCH", "NAME"] : ["ID", "\u72B6\u6001", "\u4F18\u5148\u7EA7", "Agent", "\u6279\u6B21", "\u540D\u79F0"];
50
+ const rows = tasks.map((task) => [
51
+ `#${task.id}`,
52
+ task.status ?? "pending",
53
+ `U${task.urgency ?? 3}/I${task.importance ?? 3}`,
54
+ truncateLine(task.agent, 18),
55
+ task.batchId ? truncateLine(task.batchId, 18) : "-",
56
+ truncateLine(task.name, 48)
57
+ ]);
58
+ const widths = headers.map((header, columnIndex) => Math.max(
59
+ header.length,
60
+ ...rows.map((row) => row[columnIndex].length)
61
+ ));
62
+ const formatRow = (columns) => columns.map((value, columnIndex) => columnIndex === columns.length - 1 ? value : padCell(value, widths[columnIndex])).join(" ");
63
+ return [formatRow(headers), ...rows.map(formatRow)].join("\n");
64
+ }
65
+ function renderTaskDetail(task, options = {}) {
66
+ if (shouldUseJson(options)) return JSON.stringify(task, null, 2);
67
+ const locale = options.locale ?? "zh-CN";
68
+ const model = task.model && task.model !== "default" ? task.variant ? `${task.model}#${task.variant}` : task.model : task.variant ? `default#${task.variant}` : "default";
69
+ const lines = [
70
+ `#${task.id} ${task.name} [${task.status ?? "pending"}]`,
71
+ `${cliText(locale, "Agent / \u6A21\u578B", "Agent / Model")}: ${task.agent} / ${model}`,
72
+ `${cliText(locale, "\u76EE\u5F55", "Directory")}: ${task.cwd ?? "-"}`,
73
+ `${cliText(locale, "\u4F18\u5148\u7EA7 / \u91CD\u8BD5", "Priority / Retries")}: U${task.urgency ?? 3}/I${task.importance ?? 3} \xB7 ${task.retryCount ?? 0}/${task.maxRetries ?? 3}`,
74
+ `${cliText(locale, "\u6279\u6B21 / \u4F9D\u8D56", "Batch / Depends")}: ${task.batchId ?? "-"} / ${task.dependsOn != null ? `#${task.dependsOn}` : "-"}`,
75
+ `${cliText(locale, "\u65F6\u95F4", "Timing")}: ${cliText(locale, "\u521B\u5EFA", "created")} ${formatDateValue(task.createdAt)} \xB7 ${cliText(locale, "\u5F00\u59CB", "started")} ${formatDateValue(task.startedAt)} \xB7 ${cliText(locale, "\u7ED3\u675F", "finished")} ${formatDateValue(task.finishedAt)}`,
76
+ `${cliText(locale, "\u63D0\u793A\u8BCD", "Prompt")}: ${truncateLine(task.prompt, 240)}`
77
+ ];
78
+ if (task.resultLog) {
79
+ const preview = task.resultLog.length > 600 ? `\u2026${task.resultLog.slice(-600)}` : task.resultLog;
80
+ lines.push(`${cliText(locale, "\u7ED3\u679C\u65E5\u5FD7\u5C3E\u90E8", "Result log tail")}:
81
+ ${preview}`);
82
+ }
83
+ return lines.join("\n");
84
+ }
85
+ function renderTaskLogs(payload, options = {}) {
86
+ if (shouldUseJson(options)) return JSON.stringify(payload, null, 2);
87
+ const locale = options.locale ?? "zh-CN";
88
+ const headerParts = [
89
+ `task #${payload.taskId}`,
90
+ payload.runId != null ? `run #${payload.runId}` : cliText(locale, "\u65E0\u6267\u884C\u8BB0\u5F55", "no run"),
91
+ payload.status ?? "unknown"
92
+ ];
93
+ if (payload.sessionId) headerParts.push(`session ${payload.sessionId}`);
94
+ if (payload.truncated) headerParts.push(cliText(locale, "\u5DF2\u622A\u65AD", "truncated"));
95
+ const header = `=== ${headerParts.join(" \xB7 ")} ===`;
96
+ if (!payload.log) {
97
+ return `${header}
98
+ ${cliText(locale, "\uFF08\u6682\u65E0\u65E5\u5FD7\u8F93\u51FA\uFF09", "(no log output yet)")}`;
99
+ }
100
+ return `${header}
101
+ ${payload.log}`;
102
+ }
103
+
104
+ export {
105
+ shouldUseJson,
106
+ renderTaskStatus,
107
+ renderTaskList,
108
+ renderTaskDetail,
109
+ renderTaskLogs
110
+ };
111
+ //# sourceMappingURL=chunk-4FK5KE6G.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/cli/output.ts"],"sourcesContent":["import type { Task } from '@core/db/schema';\nimport { cliText, type CliLocale } from './i18n';\n\nexport interface OutputRenderOptions {\n json?: boolean;\n isTTY?: boolean;\n locale?: CliLocale;\n batchId?: string;\n}\n\nexport interface TaskLogsPayload {\n taskId: number;\n runId: number | null;\n status: string | null;\n sessionId: string | null;\n totalLength: number;\n truncated: boolean;\n log: string;\n}\n\nexport function shouldUseJson(options: { json?: boolean; isTTY?: boolean } = {}): boolean {\n const isTTY = options.isTTY ?? process.stdout.isTTY === true;\n return options.json === true || !isTTY;\n}\n\nfunction padCell(value: string, width: number): string {\n return value.length >= width ? value : value + ' '.repeat(width - value.length);\n}\n\nfunction truncateLine(value: string, maxChars: number): string {\n const singleLine = value.replace(/\\s+/g, ' ').trim();\n if (singleLine.length <= maxChars) return singleLine;\n return `${singleLine.slice(0, Math.max(0, maxChars - 1))}…`;\n}\n\nfunction formatDateValue(value: Date | number | string | null | undefined): string {\n if (value == null) return '-';\n const date = value instanceof Date ? value : new Date(value);\n if (Number.isNaN(date.getTime())) return '-';\n return date.toISOString().replace('T', ' ').slice(0, 19);\n}\n\nexport function renderTaskStatus(\n stats: Record<string, number>,\n options: OutputRenderOptions = {},\n): string {\n if (shouldUseJson(options)) return JSON.stringify(stats, null, 2);\n\n const locale = options.locale ?? 'zh-CN';\n const header = options.batchId\n ? cliText(locale, `任务统计(批次:${options.batchId})`, `Task Status (batch: ${options.batchId})`)\n : cliText(locale, '任务统计', 'Task Status');\n\n const rows: Array<[string, number]> = [\n [cliText(locale, '总计', 'total'), stats.total ?? 0],\n [cliText(locale, '排队', 'pending'), stats.pending ?? 0],\n [cliText(locale, '运行中', 'running'), stats.running ?? 0],\n [cliText(locale, '已完成', 'done'), stats.done ?? 0],\n [cliText(locale, '失败待重试', 'failed'), stats.failed ?? 0],\n [cliText(locale, '死信', 'dead_letter'), stats.dead_letter ?? 0],\n [cliText(locale, '已取消', 'cancelled'), stats.cancelled ?? 0],\n ];\n\n const summary = rows.map(([label, count]) => `${label} ${count}`).join(' · ');\n return `${header}\\n${summary}`;\n}\n\nexport function renderTaskList(\n tasks: Task[],\n options: OutputRenderOptions = {},\n): string {\n if (shouldUseJson(options)) return JSON.stringify(tasks, null, 2);\n\n const locale = options.locale ?? 'zh-CN';\n if (tasks.length === 0) {\n return cliText(locale, '暂无匹配的任务。', 'No matching tasks.');\n }\n\n const headers = locale === 'en'\n ? ['ID', 'STATUS', 'PRI', 'AGENT', 'BATCH', 'NAME']\n : ['ID', '状态', '优先级', 'Agent', '批次', '名称'];\n\n const rows = tasks.map((task) => [\n `#${task.id}`,\n task.status ?? 'pending',\n `U${task.urgency ?? 3}/I${task.importance ?? 3}`,\n truncateLine(task.agent, 18),\n task.batchId ? truncateLine(task.batchId, 18) : '-',\n truncateLine(task.name, 48),\n ]);\n\n const widths = headers.map((header, columnIndex) => Math.max(\n header.length,\n ...rows.map((row) => row[columnIndex].length),\n ));\n\n const formatRow = (columns: string[]) => columns\n .map((value, columnIndex) => (columnIndex === columns.length - 1 ? value : padCell(value, widths[columnIndex])))\n .join(' ');\n\n return [formatRow(headers), ...rows.map(formatRow)].join('\\n');\n}\n\nexport function renderTaskDetail(\n task: Task,\n options: OutputRenderOptions = {},\n): string {\n if (shouldUseJson(options)) return JSON.stringify(task, null, 2);\n\n const locale = options.locale ?? 'zh-CN';\n const model = task.model && task.model !== 'default'\n ? (task.variant ? `${task.model}#${task.variant}` : task.model)\n : (task.variant ? `default#${task.variant}` : 'default');\n const lines = [\n `#${task.id} ${task.name} [${task.status ?? 'pending'}]`,\n `${cliText(locale, 'Agent / 模型', 'Agent / Model')}: ${task.agent} / ${model}`,\n `${cliText(locale, '目录', 'Directory')}: ${task.cwd ?? '-'}`,\n `${cliText(locale, '优先级 / 重试', 'Priority / Retries')}: U${task.urgency ?? 3}/I${task.importance ?? 3} · ${task.retryCount ?? 0}/${task.maxRetries ?? 3}`,\n `${cliText(locale, '批次 / 依赖', 'Batch / Depends')}: ${task.batchId ?? '-'} / ${task.dependsOn != null ? `#${task.dependsOn}` : '-'}`,\n `${cliText(locale, '时间', 'Timing')}: ${cliText(locale, '创建', 'created')} ${formatDateValue(task.createdAt)} · ${cliText(locale, '开始', 'started')} ${formatDateValue(task.startedAt)} · ${cliText(locale, '结束', 'finished')} ${formatDateValue(task.finishedAt)}`,\n `${cliText(locale, '提示词', 'Prompt')}: ${truncateLine(task.prompt, 240)}`,\n ];\n\n if (task.resultLog) {\n const preview = task.resultLog.length > 600\n ? `…${task.resultLog.slice(-600)}`\n : task.resultLog;\n lines.push(`${cliText(locale, '结果日志尾部', 'Result log tail')}:\\n${preview}`);\n }\n\n return lines.join('\\n');\n}\n\nexport function renderTaskLogs(\n payload: TaskLogsPayload,\n options: OutputRenderOptions = {},\n): string {\n if (shouldUseJson(options)) return JSON.stringify(payload, null, 2);\n\n const locale = options.locale ?? 'zh-CN';\n const headerParts = [\n `task #${payload.taskId}`,\n payload.runId != null ? `run #${payload.runId}` : cliText(locale, '无执行记录', 'no run'),\n payload.status ?? 'unknown',\n ];\n if (payload.sessionId) headerParts.push(`session ${payload.sessionId}`);\n if (payload.truncated) headerParts.push(cliText(locale, '已截断', 'truncated'));\n\n const header = `=== ${headerParts.join(' · ')} ===`;\n if (!payload.log) {\n return `${header}\\n${cliText(locale, '(暂无日志输出)', '(no log output yet)')}`;\n }\n return `${header}\\n${payload.log}`;\n}\n"],"mappings":";;;;;;;AAoBO,SAAS,cAAc,UAA+C,CAAC,GAAY;AACtF,QAAM,QAAQ,QAAQ,SAAS,QAAQ,OAAO,UAAU;AACxD,SAAO,QAAQ,SAAS,QAAQ,CAAC;AACrC;AAEA,SAAS,QAAQ,OAAe,OAA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";
18
+
19
+ // src/core/services/task-run.service.ts
20
+ var { tasks, taskRuns } = schema_exports;
21
+ var LegacyRunAbandonConflictError = class extends Error {
22
+ constructor(message) {
23
+ super(message);
24
+ this.name = "LegacyRunAbandonConflictError";
25
+ }
26
+ };
27
+ var TaskRunService = class {
28
+ static async create(data) {
29
+ const result = await db.insert(taskRuns).values(data).returning();
30
+ return result[0];
31
+ }
32
+ static async updateSessionId(id, sessionId) {
33
+ const result = await db.update(taskRuns).set({ sessionId }).where(and(eq(taskRuns.id, id), eq(taskRuns.status, "running"))).returning();
34
+ return result[0] || null;
35
+ }
36
+ static async done(id, log) {
37
+ const result = await db.update(taskRuns).set({
38
+ status: "done",
39
+ finishedAt: /* @__PURE__ */ new Date(),
40
+ log
41
+ }).where(and(eq(taskRuns.id, id), eq(taskRuns.status, "running"))).returning();
42
+ return result[0] || null;
43
+ }
44
+ static async fail(id, log) {
45
+ const result = await db.update(taskRuns).set({
46
+ status: "failed",
47
+ finishedAt: /* @__PURE__ */ new Date(),
48
+ log
49
+ }).where(and(eq(taskRuns.id, id), eq(taskRuns.status, "running"))).returning();
50
+ return result[0] || null;
51
+ }
52
+ static async heartbeat(id) {
53
+ const result = await db.update(taskRuns).set({ heartbeatAt: Date.now() }).where(and(eq(taskRuns.id, id), eq(taskRuns.status, "running"))).returning();
54
+ return result[0] || null;
55
+ }
56
+ static async updatePid(id, workerPid, childPid, lockedBy = `gateway-${process.pid}`) {
57
+ const result = await db.update(taskRuns).set({
58
+ workerPid,
59
+ childPid,
60
+ lockedAt: Date.now(),
61
+ lockedBy
62
+ }).where(and(eq(taskRuns.id, id), eq(taskRuns.status, "running"))).returning();
63
+ return result[0] || null;
64
+ }
65
+ static async getById(id) {
66
+ const result = await db.select().from(taskRuns).where(eq(taskRuns.id, id));
67
+ return result[0] || null;
68
+ }
69
+ static async listByTaskId(taskId) {
70
+ return await db.select().from(taskRuns).where(eq(taskRuns.taskId, taskId)).orderBy(desc(taskRuns.startedAt), desc(taskRuns.id));
71
+ }
72
+ static async getLatestByTaskId(taskId) {
73
+ const result = await db.select().from(taskRuns).where(eq(taskRuns.taskId, taskId)).orderBy(desc(taskRuns.startedAt), desc(taskRuns.id)).limit(1);
74
+ return result[0] || null;
75
+ }
76
+ static async getLatestByTaskIds(taskIds) {
77
+ if (taskIds.length === 0) return /* @__PURE__ */ new Map();
78
+ const latestRuns = await db.select().from(taskRuns).where(inArray(taskRuns.taskId, taskIds)).orderBy(desc(taskRuns.startedAt), desc(taskRuns.id));
79
+ const result = /* @__PURE__ */ new Map();
80
+ for (const run of latestRuns) {
81
+ if (!result.has(run.taskId)) {
82
+ result.set(run.taskId, run);
83
+ }
84
+ }
85
+ return result;
86
+ }
87
+ static async getLatestMetaByTaskIds(taskIds, options = {}) {
88
+ const uniqueIds = [...new Set(taskIds.filter((id) => Number.isInteger(id) && id > 0))];
89
+ if (uniqueIds.length === 0) return /* @__PURE__ */ new Map();
90
+ const includePreview = options.includePreview ?? true;
91
+ 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";
92
+ const sqlite = getSqlite();
93
+ const rows = sqlite.query(`
94
+ WITH ranked AS (
95
+ SELECT
96
+ r.id,
97
+ r.task_id,
98
+ r.session_id,
99
+ r.model,
100
+ r.variant,
101
+ r.status,
102
+ r.started_at,
103
+ r.finished_at,
104
+ r.locked_at,
105
+ r.locked_by,
106
+ r.heartbeat_at,
107
+ r.worker_pid,
108
+ r.child_pid,
109
+ r.launch_protocol,
110
+ CASE WHEN r.log IS NOT NULL AND length(r.log) > 0 THEN 1 ELSE 0 END AS has_log,
111
+ COALESCE(length(r.log), 0) AS log_length,
112
+ ${previewExpr} AS log_preview,
113
+ ROW_NUMBER() OVER (PARTITION BY r.task_id ORDER BY r.started_at DESC, r.id DESC) AS rn
114
+ FROM task_runs AS r
115
+ WHERE r.task_id IN (SELECT value FROM json_each(?))
116
+ )
117
+ SELECT
118
+ id, task_id, session_id, model, variant, status,
119
+ started_at, finished_at, locked_at, locked_by,
120
+ heartbeat_at, worker_pid, child_pid, launch_protocol,
121
+ has_log, log_length, log_preview
122
+ FROM ranked
123
+ WHERE rn = 1
124
+ `).all(JSON.stringify(uniqueIds));
125
+ const result = /* @__PURE__ */ new Map();
126
+ for (const row of rows) {
127
+ result.set(row.task_id, {
128
+ id: Number(row.id),
129
+ taskId: Number(row.task_id),
130
+ sessionId: row.session_id,
131
+ model: row.model,
132
+ variant: row.variant,
133
+ status: row.status,
134
+ startedAt: row.started_at == null ? null : new Date(Number(row.started_at) * 1e3),
135
+ finishedAt: row.finished_at == null ? null : new Date(Number(row.finished_at) * 1e3),
136
+ lockedAt: row.locked_at,
137
+ lockedBy: row.locked_by,
138
+ heartbeatAt: row.heartbeat_at,
139
+ workerPid: row.worker_pid,
140
+ childPid: row.child_pid,
141
+ launchProtocol: row.launch_protocol,
142
+ hasLog: Number(row.has_log) === 1,
143
+ logLength: Number(row.log_length ?? 0),
144
+ logPreview: row.log_preview
145
+ });
146
+ }
147
+ return result;
148
+ }
149
+ static async listMeta(options = {}) {
150
+ const limit = options.limit ?? 50;
151
+ const offset = options.offset ?? 0;
152
+ const includePreview = options.includePreview ?? true;
153
+ const conditions = [];
154
+ if (options.taskId !== void 0) {
155
+ conditions.push(eq(taskRuns.taskId, options.taskId));
156
+ }
157
+ if (options.status !== void 0) {
158
+ conditions.push(eq(taskRuns.status, options.status));
159
+ }
160
+ if (options.legacyCwd) {
161
+ conditions.push(or(isNull(tasks.cwd), eq(tasks.cwd, "")));
162
+ } else if (options.cwd !== void 0) {
163
+ conditions.push(eq(tasks.cwd, options.cwd));
164
+ }
165
+ const selection = {
166
+ id: taskRuns.id,
167
+ taskId: taskRuns.taskId,
168
+ sessionId: taskRuns.sessionId,
169
+ model: taskRuns.model,
170
+ variant: taskRuns.variant,
171
+ status: taskRuns.status,
172
+ startedAt: taskRuns.startedAt,
173
+ finishedAt: taskRuns.finishedAt,
174
+ lockedAt: taskRuns.lockedAt,
175
+ lockedBy: taskRuns.lockedBy,
176
+ heartbeatAt: taskRuns.heartbeatAt,
177
+ workerPid: taskRuns.workerPid,
178
+ childPid: taskRuns.childPid,
179
+ launchProtocol: taskRuns.launchProtocol,
180
+ hasLog: sql`CASE WHEN ${taskRuns.log} IS NOT NULL AND length(${taskRuns.log}) > 0 THEN 1 ELSE 0 END`,
181
+ logLength: sql`COALESCE(length(${taskRuns.log}), 0)`,
182
+ logPreview: includePreview ? sql`CASE WHEN ${taskRuns.log} IS NULL THEN NULL WHEN ${taskRuns.status} = 'failed' THEN substr(${taskRuns.log}, -512) ELSE substr(${taskRuns.log}, 1, 512) END` : sql`NULL`
183
+ };
184
+ const needsTaskJoin = Boolean(options.legacyCwd) || options.cwd !== void 0;
185
+ const baseQuery = needsTaskJoin ? db.select(selection).from(taskRuns).innerJoin(tasks, eq(taskRuns.taskId, tasks.id)).$dynamic() : db.select(selection).from(taskRuns).$dynamic();
186
+ const filteredQuery = conditions.length > 0 ? baseQuery.where(and(...conditions)) : baseQuery;
187
+ const rows = await filteredQuery.orderBy(desc(taskRuns.startedAt), desc(taskRuns.id)).limit(limit).offset(offset);
188
+ return rows.map((row) => ({
189
+ id: row.id,
190
+ taskId: row.taskId,
191
+ sessionId: row.sessionId,
192
+ model: row.model,
193
+ variant: row.variant,
194
+ status: row.status,
195
+ startedAt: row.startedAt,
196
+ finishedAt: row.finishedAt,
197
+ lockedAt: row.lockedAt,
198
+ lockedBy: row.lockedBy,
199
+ heartbeatAt: row.heartbeatAt,
200
+ workerPid: row.workerPid,
201
+ childPid: row.childPid,
202
+ launchProtocol: row.launchProtocol,
203
+ hasLog: Number(row.hasLog) === 1,
204
+ logLength: Number(row.logLength ?? 0),
205
+ logPreview: row.logPreview
206
+ }));
207
+ }
208
+ static async getLogById(id, options = {}) {
209
+ const selection = {
210
+ id: taskRuns.id,
211
+ taskId: taskRuns.taskId,
212
+ status: taskRuns.status,
213
+ sessionId: taskRuns.sessionId,
214
+ log: taskRuns.log
215
+ };
216
+ const row = options.cwd !== void 0 ? await db.select(selection).from(taskRuns).innerJoin(tasks, eq(taskRuns.taskId, tasks.id)).where(
217
+ options.taskId !== void 0 ? and(
218
+ eq(taskRuns.id, id),
219
+ eq(tasks.cwd, options.cwd),
220
+ eq(taskRuns.taskId, options.taskId)
221
+ ) : and(eq(taskRuns.id, id), eq(tasks.cwd, options.cwd))
222
+ ).get() : await db.select(selection).from(taskRuns).where(
223
+ options.taskId !== void 0 ? and(eq(taskRuns.id, id), eq(taskRuns.taskId, options.taskId)) : eq(taskRuns.id, id)
224
+ ).get();
225
+ if (!row) return null;
226
+ const fullLog = row.log ?? "";
227
+ const totalLength = fullLog.length;
228
+ if (options.tailLines !== void 0 && options.tailLines >= 0) {
229
+ if (fullLog.length === 0) {
230
+ return {
231
+ id: row.id,
232
+ taskId: row.taskId,
233
+ status: row.status,
234
+ sessionId: row.sessionId,
235
+ log: "",
236
+ totalLength: 0,
237
+ truncated: false
238
+ };
239
+ }
240
+ const lines = fullLog.split("\n");
241
+ const truncated = lines.length > options.tailLines;
242
+ const sliced = options.tailLines === 0 ? "" : lines.slice(-options.tailLines).join("\n");
243
+ return {
244
+ id: row.id,
245
+ taskId: row.taskId,
246
+ status: row.status,
247
+ sessionId: row.sessionId,
248
+ log: sliced,
249
+ totalLength,
250
+ truncated
251
+ };
252
+ }
253
+ if (options.tailChars !== void 0 && options.tailChars >= 0) {
254
+ const truncated = totalLength > options.tailChars;
255
+ const sliced = options.tailChars === 0 ? "" : fullLog.slice(-options.tailChars);
256
+ return {
257
+ id: row.id,
258
+ taskId: row.taskId,
259
+ status: row.status,
260
+ sessionId: row.sessionId,
261
+ log: sliced,
262
+ totalLength,
263
+ truncated
264
+ };
265
+ }
266
+ if (options.offset !== void 0 || options.limit !== void 0) {
267
+ const start = Math.max(0, options.offset ?? 0);
268
+ const end = options.limit !== void 0 ? start + Math.max(0, options.limit) : totalLength;
269
+ const sliced = fullLog.slice(start, end);
270
+ return {
271
+ id: row.id,
272
+ taskId: row.taskId,
273
+ status: row.status,
274
+ sessionId: row.sessionId,
275
+ log: sliced,
276
+ totalLength,
277
+ truncated: start > 0 || end < totalLength
278
+ };
279
+ }
280
+ return {
281
+ id: row.id,
282
+ taskId: row.taskId,
283
+ status: row.status,
284
+ sessionId: row.sessionId,
285
+ log: fullLog,
286
+ totalLength,
287
+ truncated: false
288
+ };
289
+ }
290
+ static async getStaleRuns(heartbeatTimeoutMs) {
291
+ const cutoffMs = Date.now() - heartbeatTimeoutMs;
292
+ const { tasks: tasksTable } = schema_exports;
293
+ const result = await db.select({
294
+ runId: taskRuns.id,
295
+ taskId: taskRuns.taskId,
296
+ childPid: taskRuns.childPid,
297
+ workerPid: taskRuns.workerPid,
298
+ launchProtocol: taskRuns.launchProtocol,
299
+ lockedBy: taskRuns.lockedBy,
300
+ startedAt: taskRuns.startedAt,
301
+ heartbeatAt: taskRuns.heartbeatAt,
302
+ taskRetryCount: tasksTable.retryCount,
303
+ taskMaxRetries: tasksTable.maxRetries,
304
+ taskRetryBackoffMs: tasksTable.retryBackoffMs,
305
+ taskStatus: tasksTable.status,
306
+ taskCwd: tasksTable.cwd
307
+ }).from(taskRuns).innerJoin(tasksTable, eq(taskRuns.taskId, tasksTable.id)).where(eq(taskRuns.status, "running"));
308
+ return result.filter((row) => {
309
+ const heartbeatExpired = row.heartbeatAt == null ? row.startedAt == null || row.startedAt.getTime() < cutoffMs : row.heartbeatAt < cutoffMs;
310
+ const ownerExited = row.workerPid != null && row.workerPid > 0 && !isProcessAlive(row.workerPid);
311
+ return heartbeatExpired || ownerExited;
312
+ }).map((row) => ({
313
+ runId: row.runId,
314
+ taskId: row.taskId,
315
+ childPid: row.childPid,
316
+ workerPid: row.workerPid,
317
+ launchProtocol: row.launchProtocol,
318
+ lockedBy: row.lockedBy,
319
+ taskRetryCount: row.taskRetryCount ?? 0,
320
+ taskMaxRetries: row.taskMaxRetries ?? 3,
321
+ taskRetryBackoffMs: row.taskRetryBackoffMs ?? 3e4,
322
+ taskStatus: row.taskStatus,
323
+ taskCwd: row.taskCwd,
324
+ ownerAlive: row.workerPid != null && row.workerPid > 0 && isProcessAlive(row.workerPid)
325
+ }));
326
+ }
327
+ static async listLegacyQuarantinedRuns(heartbeatTimeoutMs = 0) {
328
+ const staleRuns = await this.getStaleRuns(heartbeatTimeoutMs);
329
+ return staleRuns.filter(
330
+ (row) => row.launchProtocol == null && row.childPid == null
331
+ ).map((row) => ({
332
+ runId: row.runId,
333
+ taskId: row.taskId,
334
+ taskStatus: row.taskStatus,
335
+ taskCwd: row.taskCwd,
336
+ workerPid: row.workerPid,
337
+ ownerAlive: row.ownerAlive
338
+ }));
339
+ }
340
+ static async abandonLegacyRun(runId) {
341
+ return db.transaction((tx) => {
342
+ const current = tx.select({
343
+ runId: taskRuns.id,
344
+ taskId: taskRuns.taskId,
345
+ runStatus: taskRuns.status,
346
+ taskStatus: tasks.status,
347
+ workerPid: taskRuns.workerPid,
348
+ childPid: taskRuns.childPid,
349
+ launchProtocol: taskRuns.launchProtocol,
350
+ log: taskRuns.log
351
+ }).from(taskRuns).innerJoin(tasks, eq(taskRuns.taskId, tasks.id)).where(eq(taskRuns.id, runId)).get();
352
+ if (!current) return null;
353
+ if (current.runStatus !== "running") {
354
+ throw new LegacyRunAbandonConflictError(`run #${runId} \u5DF2\u4E0D\u662F running \u72B6\u6001`);
355
+ }
356
+ if (current.launchProtocol != null) {
357
+ throw new LegacyRunAbandonConflictError(
358
+ `run #${runId} \u4F7F\u7528\u672A\u77E5\u6216\u53D7\u7BA1\u534F\u8BAE ${current.launchProtocol}\uFF0C\u7981\u6B62\u4EBA\u5DE5 abandon`
359
+ );
360
+ }
361
+ if (current.childPid != null) {
362
+ throw new LegacyRunAbandonConflictError(
363
+ `run #${runId} \u5DF2\u8BB0\u5F55 child PID ${current.childPid}\uFF0C\u5FC5\u987B\u7531 Worker/Watchdog \u786E\u8BA4\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A`
364
+ );
365
+ }
366
+ if (current.workerPid != null && isProcessAlive(current.workerPid)) {
367
+ throw new LegacyRunAbandonConflictError(
368
+ `run #${runId} \u7684 owner PID ${current.workerPid} \u4ECD\u5B58\u6D3B`
369
+ );
370
+ }
371
+ if (current.taskStatus !== "cancelled") {
372
+ throw new LegacyRunAbandonConflictError(
373
+ `\u4EFB\u52A1 #${current.taskId} \u5FC5\u987B\u5148\u53D6\u6D88\u5E76\u4FDD\u6301 cancelled \u72B6\u6001`
374
+ );
375
+ }
376
+ const note = "\u64CD\u4F5C\u5458\u5DF2\u786E\u8BA4\u65E7\u7248\u65E0 PID \u6267\u884C\u4E0D\u5B58\u5728\uFF0C\u5E76\u901A\u8FC7 run abandon \u5173\u95ED\u9694\u79BB\u8BB0\u5F55";
377
+ const updated = tx.update(taskRuns).set({
378
+ status: "failed",
379
+ finishedAt: /* @__PURE__ */ new Date(),
380
+ log: current.log ? `${current.log}
381
+ ${note}` : note
382
+ }).where(and(eq(taskRuns.id, runId), eq(taskRuns.status, "running"))).returning({ id: taskRuns.id }).get();
383
+ if (!updated) {
384
+ throw new LegacyRunAbandonConflictError(`run #${runId} \u72B6\u6001\u5DF2\u88AB\u5176\u4ED6\u64CD\u4F5C\u6539\u53D8`);
385
+ }
386
+ return {
387
+ runId,
388
+ taskId: current.taskId,
389
+ runStatus: "failed",
390
+ taskStatus: "cancelled"
391
+ };
392
+ }, { behavior: "immediate" });
393
+ }
394
+ static async getRunningRunByTaskId(taskId) {
395
+ const result = await db.select().from(taskRuns).where(and(eq(taskRuns.taskId, taskId), eq(taskRuns.status, "running"))).orderBy(desc(taskRuns.startedAt), desc(taskRuns.id)).limit(1);
396
+ return result[0] || null;
397
+ }
398
+ static async deleteByTaskIds(taskIds) {
399
+ if (taskIds.length === 0) return 0;
400
+ const result = await db.delete(taskRuns).where(inArray(taskRuns.taskId, taskIds)).returning();
401
+ return result.length;
402
+ }
403
+ static async getAllRunningRuns() {
404
+ return await db.select().from(taskRuns).where(eq(taskRuns.status, "running"));
405
+ }
406
+ };
407
+
408
+ export {
409
+ LegacyRunAbandonConflictError,
410
+ TaskRunService
411
+ };
412
+ //# sourceMappingURL=chunk-5VKFECHP.js.map