opencode-supertask 0.2.1 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +34 -0
- package/README.md +10 -0
- package/README.zh-CN.md +10 -0
- package/dist/cli/{chunk-NCT3ETTK.js → chunk-7BATA4DM.js} +20 -1
- package/dist/cli/chunk-7BATA4DM.js.map +1 -0
- package/dist/cli/{chunk-J34FWHQU.js → chunk-ETLJ4YXW.js} +3 -2
- package/dist/cli/chunk-ETLJ4YXW.js.map +1 -0
- package/dist/cli/{chunk-AZM76ISG.js → chunk-INW2NH3O.js} +6 -5
- package/dist/cli/chunk-INW2NH3O.js.map +1 -0
- package/dist/cli/{chunk-CMEP6IB4.js → chunk-K6UTYKN5.js} +19 -5
- package/dist/cli/{chunk-CMEP6IB4.js.map → chunk-K6UTYKN5.js.map} +1 -1
- package/dist/cli/{chunk-ZBH7YWXF.js → chunk-KC34M3F3.js} +2 -2
- package/dist/cli/{chunk-DF56RPNL.js → chunk-MZLIVCEU.js} +10 -2
- package/dist/cli/{chunk-DF56RPNL.js.map → chunk-MZLIVCEU.js.map} +1 -1
- package/dist/cli/{chunk-5VKFECHP.js → chunk-OJLDJVHB.js} +3 -3
- package/dist/cli/{chunk-LX5CBJLP.js → chunk-WHGCKWMR.js} +26 -3
- package/dist/cli/chunk-WHGCKWMR.js.map +1 -0
- package/dist/cli/{chunk-EQWICVCJ.js → chunk-XUCZLWCB.js} +48 -6
- package/dist/cli/chunk-XUCZLWCB.js.map +1 -0
- package/dist/cli/{chunk-YB7MYTE5.js → chunk-XWTKMNNI.js} +3 -1
- package/dist/cli/chunk-XWTKMNNI.js.map +1 -0
- package/dist/cli/{chunk-DIJEKFBV.js → chunk-YADLWDYK.js} +4 -4
- package/dist/cli/{chunk-YGELD2E5.js → chunk-ZIR7RA5B.js} +7 -4
- package/dist/cli/{chunk-YGELD2E5.js.map → chunk-ZIR7RA5B.js.map} +1 -1
- package/dist/cli/database-maintenance.service-NQBZ5VJT.js +16 -0
- package/dist/cli/{db-H7GIFWS2.js → db-KWSXP22E.js} +2 -2
- package/dist/cli/{doctor-smoke-QXHF7UNN.js → doctor-smoke-6VU2KCRK.js} +7 -7
- package/dist/cli/{gateway-BYLLK72W.js → gateway-I2SQOXWB.js} +686 -24
- package/dist/cli/gateway-I2SQOXWB.js.map +1 -0
- package/dist/cli/{gateway-wake-U4HTV56Q.js → gateway-wake-M5EXAIGD.js} +2 -2
- package/dist/cli/index.js +38 -38
- package/dist/cli/{job-templates-RPQJ4XXW.js → job-templates-FH7SGS34.js} +5 -5
- package/dist/cli/{logs-QD2N62KK.js → logs-HB5RV7HD.js} +7 -7
- package/dist/cli/{pm2-WY644BUO.js → pm2-YSCAIIBU.js} +2 -2
- package/dist/cli/task-run.service-R45W2VID.js +15 -0
- package/dist/cli/task-template.service-VA4WBJA4.js +12 -0
- package/dist/cli/{task.service-ZVDJ6VSQ.js → task.service-RB6RKV7T.js} +3 -3
- package/dist/cli/{update-FYD546I2.js → update-FMCBRTHT.js} +4 -4
- package/dist/cli/{web-J3FJ23FE.js → web-4QWJ4Z5K.js} +157 -17
- package/dist/cli/{web-J3FJ23FE.js.map → web-4QWJ4Z5K.js.map} +1 -1
- package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
- package/dist/gateway/index.d.ts +1 -0
- package/dist/gateway/index.js +929 -31
- package/dist/gateway/index.js.map +1 -1
- package/dist/plugin/supertask.js +106 -11
- package/dist/plugin/supertask.js.map +1 -1
- package/dist/web/index.js +235 -16
- package/dist/web/index.js.map +1 -1
- package/dist/worker/index.d.ts +492 -1
- package/dist/worker/index.js +728 -20
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/launcher.js.map +1 -1
- package/drizzle/0010_task_metadata.sql +2 -0
- package/drizzle/meta/0010_snapshot.json +695 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +1 -1
- package/dist/cli/chunk-AZM76ISG.js.map +0 -1
- package/dist/cli/chunk-EQWICVCJ.js.map +0 -1
- package/dist/cli/chunk-J34FWHQU.js.map +0 -1
- package/dist/cli/chunk-LX5CBJLP.js.map +0 -1
- package/dist/cli/chunk-NCT3ETTK.js.map +0 -1
- package/dist/cli/chunk-YB7MYTE5.js.map +0 -1
- package/dist/cli/database-maintenance.service-F3IZU52F.js +0 -16
- package/dist/cli/gateway-BYLLK72W.js.map +0 -1
- package/dist/cli/task-run.service-QMDINJKG.js +0 -15
- package/dist/cli/task-template.service-SZBKGLCB.js +0 -12
- /package/dist/cli/{chunk-ZBH7YWXF.js.map → chunk-KC34M3F3.js.map} +0 -0
- /package/dist/cli/{chunk-5VKFECHP.js.map → chunk-OJLDJVHB.js.map} +0 -0
- /package/dist/cli/{chunk-DIJEKFBV.js.map → chunk-YADLWDYK.js.map} +0 -0
- /package/dist/cli/{database-maintenance.service-F3IZU52F.js.map → database-maintenance.service-NQBZ5VJT.js.map} +0 -0
- /package/dist/cli/{db-H7GIFWS2.js.map → db-KWSXP22E.js.map} +0 -0
- /package/dist/cli/{doctor-smoke-QXHF7UNN.js.map → doctor-smoke-6VU2KCRK.js.map} +0 -0
- /package/dist/cli/{gateway-wake-U4HTV56Q.js.map → gateway-wake-M5EXAIGD.js.map} +0 -0
- /package/dist/cli/{job-templates-RPQJ4XXW.js.map → job-templates-FH7SGS34.js.map} +0 -0
- /package/dist/cli/{logs-QD2N62KK.js.map → logs-HB5RV7HD.js.map} +0 -0
- /package/dist/cli/{pm2-WY644BUO.js.map → pm2-YSCAIIBU.js.map} +0 -0
- /package/dist/cli/{task-run.service-QMDINJKG.js.map → task-run.service-R45W2VID.js.map} +0 -0
- /package/dist/cli/{task-template.service-SZBKGLCB.js.map → task-template.service-VA4WBJA4.js.map} +0 -0
- /package/dist/cli/{task.service-ZVDJ6VSQ.js.map → task.service-RB6RKV7T.js.map} +0 -0
- /package/dist/cli/{update-FYD546I2.js.map → update-FMCBRTHT.js.map} +0 -0
package/dist/worker/index.js
CHANGED
|
@@ -5182,7 +5182,9 @@ var tasks = sqliteTable("tasks", {
|
|
|
5182
5182
|
retryAfter: integer("retry_after"),
|
|
5183
5183
|
timeoutMs: integer("timeout_ms"),
|
|
5184
5184
|
templateId: integer("template_id"),
|
|
5185
|
-
scheduledAt: integer("scheduled_at")
|
|
5185
|
+
scheduledAt: integer("scheduled_at"),
|
|
5186
|
+
// 调用方不透明元数据(JSON 对象字符串,供上层平台存储归属/应用标识等)
|
|
5187
|
+
metadata: text("metadata")
|
|
5186
5188
|
}, (table) => [
|
|
5187
5189
|
index("tasks_queue_idx").on(table.status, table.retryAfter, table.urgency, table.importance, table.createdAt, table.id),
|
|
5188
5190
|
index("tasks_batch_status_idx").on(table.batchId, table.status),
|
|
@@ -5262,7 +5264,8 @@ var taskTemplates = sqliteTable("task_templates", {
|
|
|
5262
5264
|
nextRunAt: integer("next_run_at"),
|
|
5263
5265
|
enabled: integer("enabled", { mode: "boolean" }).default(true),
|
|
5264
5266
|
createdAt: integer("created_at").default(0),
|
|
5265
|
-
updatedAt: integer("updated_at").default(0)
|
|
5267
|
+
updatedAt: integer("updated_at").default(0),
|
|
5268
|
+
metadata: text("metadata")
|
|
5266
5269
|
}, (table) => [
|
|
5267
5270
|
index("task_templates_due_idx").on(table.enabled, table.nextRunAt, table.id),
|
|
5268
5271
|
index("task_templates_retention_idx").on(
|
|
@@ -5280,7 +5283,7 @@ import { join, dirname } from "path";
|
|
|
5280
5283
|
import { fileURLToPath } from "url";
|
|
5281
5284
|
var DEFAULT_DB_PATH = join(homedir(), ".local/share/opencode/tasks.db");
|
|
5282
5285
|
var DB_FILE_PATH = process.env.SUPERTASK_DB_PATH || DEFAULT_DB_PATH;
|
|
5283
|
-
var EXPECTED_SCHEMA_USER_VERSION =
|
|
5286
|
+
var EXPECTED_SCHEMA_USER_VERSION = 11;
|
|
5284
5287
|
var _sqlite = null;
|
|
5285
5288
|
var _db = null;
|
|
5286
5289
|
var _migrationRan = false;
|
|
@@ -5491,6 +5494,41 @@ function normalizeModelVariant(value) {
|
|
|
5491
5494
|
return normalized;
|
|
5492
5495
|
}
|
|
5493
5496
|
|
|
5497
|
+
// src/core/metadata.ts
|
|
5498
|
+
var MAX_METADATA_BYTES = 16 * 1024;
|
|
5499
|
+
function normalizeTaskMetadata(input) {
|
|
5500
|
+
if (input === void 0) return void 0;
|
|
5501
|
+
if (input === null || input === "") return null;
|
|
5502
|
+
let parsed = input;
|
|
5503
|
+
if (typeof input === "string") {
|
|
5504
|
+
const trimmed = input.trim();
|
|
5505
|
+
if (!trimmed) return null;
|
|
5506
|
+
try {
|
|
5507
|
+
parsed = JSON.parse(trimmed);
|
|
5508
|
+
} catch {
|
|
5509
|
+
throw new Error("metadata \u5FC5\u987B\u662F\u5408\u6CD5\u7684 JSON \u5BF9\u8C61");
|
|
5510
|
+
}
|
|
5511
|
+
}
|
|
5512
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
5513
|
+
throw new Error("metadata \u5FC5\u987B\u662F JSON \u5BF9\u8C61");
|
|
5514
|
+
}
|
|
5515
|
+
const serialized = JSON.stringify(parsed);
|
|
5516
|
+
if (Buffer.byteLength(serialized, "utf8") > MAX_METADATA_BYTES) {
|
|
5517
|
+
throw new Error(`metadata \u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC7 ${MAX_METADATA_BYTES} \u5B57\u8282`);
|
|
5518
|
+
}
|
|
5519
|
+
return serialized;
|
|
5520
|
+
}
|
|
5521
|
+
function parseTaskMetadata(raw) {
|
|
5522
|
+
if (!raw || typeof raw !== "string") return null;
|
|
5523
|
+
try {
|
|
5524
|
+
const parsed = JSON.parse(raw);
|
|
5525
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
|
|
5526
|
+
return parsed;
|
|
5527
|
+
} catch {
|
|
5528
|
+
return null;
|
|
5529
|
+
}
|
|
5530
|
+
}
|
|
5531
|
+
|
|
5494
5532
|
// src/core/services/task.service.ts
|
|
5495
5533
|
var { tasks: tasks2, taskRuns: taskRuns2 } = schema_exports;
|
|
5496
5534
|
var cleanupInvocation = 0;
|
|
@@ -5953,7 +5991,8 @@ var TaskService = class {
|
|
|
5953
5991
|
const normalizedData = {
|
|
5954
5992
|
...data,
|
|
5955
5993
|
batchId: normalizeTaskBatchId(data.batchId),
|
|
5956
|
-
variant: normalizeModelVariant(data.variant)
|
|
5994
|
+
variant: normalizeModelVariant(data.variant),
|
|
5995
|
+
metadata: normalizeTaskMetadata(data.metadata) ?? null
|
|
5957
5996
|
};
|
|
5958
5997
|
this.validateNewTask(normalizedData);
|
|
5959
5998
|
return db.transaction((tx) => {
|
|
@@ -5996,7 +6035,8 @@ var TaskService = class {
|
|
|
5996
6035
|
dependsOn: overrides.dependsOn === void 0 ? null : overrides.dependsOn,
|
|
5997
6036
|
maxRetries: overrides.maxRetries ?? original.maxRetries ?? 3,
|
|
5998
6037
|
retryBackoffMs: overrides.retryBackoffMs ?? original.retryBackoffMs ?? 3e4,
|
|
5999
|
-
timeoutMs: overrides.timeoutMs === void 0 ? original.timeoutMs : overrides.timeoutMs
|
|
6038
|
+
timeoutMs: overrides.timeoutMs === void 0 ? original.timeoutMs : overrides.timeoutMs,
|
|
6039
|
+
metadata: overrides.metadata === void 0 ? original.metadata : overrides.metadata
|
|
6000
6040
|
});
|
|
6001
6041
|
}
|
|
6002
6042
|
static async update(id, data, scope = {}) {
|
|
@@ -6004,7 +6044,8 @@ var TaskService = class {
|
|
|
6004
6044
|
const normalizedData = {
|
|
6005
6045
|
...data,
|
|
6006
6046
|
...data.batchId === void 0 ? {} : { batchId: normalizeTaskBatchId(data.batchId) ?? null },
|
|
6007
|
-
...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null }
|
|
6047
|
+
...data.variant === void 0 ? {} : { variant: normalizeModelVariant(data.variant) ?? null },
|
|
6048
|
+
...data.metadata === void 0 ? {} : { metadata: normalizeTaskMetadata(data.metadata) ?? null }
|
|
6008
6049
|
};
|
|
6009
6050
|
return db.transaction((tx) => {
|
|
6010
6051
|
const task = tx.select().from(tasks2).where(and(
|
|
@@ -6597,7 +6638,8 @@ var TaskService = class {
|
|
|
6597
6638
|
retryAfter: tasks2.retryAfter,
|
|
6598
6639
|
timeoutMs: tasks2.timeoutMs,
|
|
6599
6640
|
templateId: tasks2.templateId,
|
|
6600
|
-
scheduledAt: tasks2.scheduledAt
|
|
6641
|
+
scheduledAt: tasks2.scheduledAt,
|
|
6642
|
+
metadata: tasks2.metadata
|
|
6601
6643
|
}).from(tasks2) : db.select().from(tasks2)).$dynamic();
|
|
6602
6644
|
if (conditions.length > 0) {
|
|
6603
6645
|
query = query.where(and(...conditions));
|
|
@@ -6637,6 +6679,7 @@ var TaskService = class {
|
|
|
6637
6679
|
timeoutMs: tasks2.timeoutMs,
|
|
6638
6680
|
templateId: tasks2.templateId,
|
|
6639
6681
|
scheduledAt: tasks2.scheduledAt,
|
|
6682
|
+
metadata: tasks2.metadata,
|
|
6640
6683
|
hasResultLog: sql`CASE WHEN ${tasks2.resultLog} IS NOT NULL AND length(${tasks2.resultLog}) > 0 THEN 1 ELSE 0 END`,
|
|
6641
6684
|
resultLogPreview: sql`CASE WHEN ${tasks2.resultLog} IS NULL THEN NULL WHEN ${tasks2.status} IN ('failed', 'dead_letter') THEN substr(${tasks2.resultLog}, -512) ELSE substr(${tasks2.resultLog}, 1, 512) END`
|
|
6642
6685
|
}).from(tasks2).$dynamic();
|
|
@@ -8052,6 +8095,504 @@ var GatewayEventBus = class {
|
|
|
8052
8095
|
};
|
|
8053
8096
|
var gatewayEvents = new GatewayEventBus();
|
|
8054
8097
|
|
|
8098
|
+
// src/gateway/webhook.ts
|
|
8099
|
+
import { createHmac } from "crypto";
|
|
8100
|
+
var DEFAULT_TIMEOUT_MS = 5e3;
|
|
8101
|
+
var DEFAULT_MAX_ATTEMPTS = 2;
|
|
8102
|
+
var MAX_SUMMARY_CHARS = 2e3;
|
|
8103
|
+
var pendingWebhooks = /* @__PURE__ */ new Set();
|
|
8104
|
+
function signWebhookPayload(secret, timestamp, body) {
|
|
8105
|
+
const digest = createHmac("sha256", secret).update(`${timestamp}.${body}`).digest("hex");
|
|
8106
|
+
return `sha256=${digest}`;
|
|
8107
|
+
}
|
|
8108
|
+
function extractOutputSummary(rawLog, maxChars = MAX_SUMMARY_CHARS) {
|
|
8109
|
+
if (!rawLog) return "";
|
|
8110
|
+
const texts = [];
|
|
8111
|
+
let framed = false;
|
|
8112
|
+
for (const line of rawLog.split("\n")) {
|
|
8113
|
+
const trimmed = line.trim();
|
|
8114
|
+
if (!trimmed) continue;
|
|
8115
|
+
try {
|
|
8116
|
+
const event = JSON.parse(trimmed);
|
|
8117
|
+
if (event.type) framed = true;
|
|
8118
|
+
if (event.type === "text" && typeof event.part?.text === "string" && event.part.text.trim()) {
|
|
8119
|
+
texts.push(event.part.text.trim());
|
|
8120
|
+
} else if (event.type === "error") {
|
|
8121
|
+
const msg = event.error?.data?.message || event.error?.message;
|
|
8122
|
+
if (typeof msg === "string" && msg.trim()) texts.push(msg.trim());
|
|
8123
|
+
} else if (event.type === "tool_use" && event.part?.state?.status === "error" && typeof event.part.state.error === "string" && event.part.state.error.trim()) {
|
|
8124
|
+
texts.push(event.part.state.error.trim());
|
|
8125
|
+
}
|
|
8126
|
+
} catch {
|
|
8127
|
+
if (!framed) texts.push(trimmed);
|
|
8128
|
+
}
|
|
8129
|
+
}
|
|
8130
|
+
const combined = texts.join("\n").trim();
|
|
8131
|
+
if (combined.length <= maxChars) return combined;
|
|
8132
|
+
return `${combined.slice(0, Math.max(0, maxChars - 1))}\u2026`;
|
|
8133
|
+
}
|
|
8134
|
+
function toMs(value) {
|
|
8135
|
+
if (value == null) return null;
|
|
8136
|
+
if (value instanceof Date) return value.getTime();
|
|
8137
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
8138
|
+
return null;
|
|
8139
|
+
}
|
|
8140
|
+
function buildTaskWebhookPayload(event, task, run, outputOverride) {
|
|
8141
|
+
const startedAt = toMs(task.startedAt);
|
|
8142
|
+
const finishedAt = toMs(task.finishedAt) ?? Date.now();
|
|
8143
|
+
const durationMs = startedAt != null && finishedAt > startedAt ? finishedAt - startedAt : 0;
|
|
8144
|
+
return {
|
|
8145
|
+
event,
|
|
8146
|
+
timestamp: Date.now(),
|
|
8147
|
+
task: {
|
|
8148
|
+
id: task.id,
|
|
8149
|
+
name: task.name,
|
|
8150
|
+
agent: task.agent,
|
|
8151
|
+
model: task.model ?? null,
|
|
8152
|
+
variant: task.variant ?? null,
|
|
8153
|
+
cwd: task.cwd ?? null,
|
|
8154
|
+
templateId: task.templateId ?? null,
|
|
8155
|
+
status: task.status ?? event.slice("task.".length),
|
|
8156
|
+
metadata: parseTaskMetadata(task.metadata),
|
|
8157
|
+
startedAt,
|
|
8158
|
+
finishedAt,
|
|
8159
|
+
durationMs
|
|
8160
|
+
},
|
|
8161
|
+
run,
|
|
8162
|
+
outputSummary: extractOutputSummary(outputOverride ?? task.resultLog)
|
|
8163
|
+
};
|
|
8164
|
+
}
|
|
8165
|
+
function dispatchTaskWebhook(payload, options = {}) {
|
|
8166
|
+
const task = deliverTaskWebhook(payload, options);
|
|
8167
|
+
pendingWebhooks.add(task);
|
|
8168
|
+
void task.finally(() => {
|
|
8169
|
+
pendingWebhooks.delete(task);
|
|
8170
|
+
});
|
|
8171
|
+
return task;
|
|
8172
|
+
}
|
|
8173
|
+
async function deliverTaskWebhook(payload, options = {}) {
|
|
8174
|
+
const url = (options.url ?? process.env.SUPERTASK_WEBHOOK_URL ?? "").trim();
|
|
8175
|
+
if (!url) return false;
|
|
8176
|
+
try {
|
|
8177
|
+
const parsed = new URL(url);
|
|
8178
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
|
|
8179
|
+
} catch {
|
|
8180
|
+
return false;
|
|
8181
|
+
}
|
|
8182
|
+
const secret = (options.secret ?? process.env.SUPERTASK_WEBHOOK_SECRET ?? "").trim();
|
|
8183
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
8184
|
+
const maxAttempts = Math.max(1, options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS);
|
|
8185
|
+
const fetchFn = options.fetchImpl ?? fetch;
|
|
8186
|
+
const body = JSON.stringify(payload);
|
|
8187
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
8188
|
+
const ts = Date.now();
|
|
8189
|
+
const headers = {
|
|
8190
|
+
"content-type": "application/json",
|
|
8191
|
+
"x-supertask-event": payload.event,
|
|
8192
|
+
"x-supertask-timestamp": String(ts)
|
|
8193
|
+
};
|
|
8194
|
+
if (secret) {
|
|
8195
|
+
headers["x-supertask-signature"] = signWebhookPayload(secret, ts, body);
|
|
8196
|
+
}
|
|
8197
|
+
try {
|
|
8198
|
+
const resp = await fetchFn(url, {
|
|
8199
|
+
method: "POST",
|
|
8200
|
+
headers,
|
|
8201
|
+
body,
|
|
8202
|
+
redirect: "error",
|
|
8203
|
+
signal: AbortSignal.timeout(timeoutMs)
|
|
8204
|
+
});
|
|
8205
|
+
if (resp.ok) return true;
|
|
8206
|
+
if (resp.status >= 400 && resp.status < 500 && resp.status !== 429) {
|
|
8207
|
+
console.warn(JSON.stringify({
|
|
8208
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8209
|
+
level: "warn",
|
|
8210
|
+
msg: "task webhook rejected",
|
|
8211
|
+
event: payload.event,
|
|
8212
|
+
taskId: payload.task.id,
|
|
8213
|
+
status: resp.status
|
|
8214
|
+
}));
|
|
8215
|
+
return false;
|
|
8216
|
+
}
|
|
8217
|
+
if (attempt >= maxAttempts) {
|
|
8218
|
+
console.warn(JSON.stringify({
|
|
8219
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8220
|
+
level: "warn",
|
|
8221
|
+
msg: "task webhook delivery exhausted",
|
|
8222
|
+
event: payload.event,
|
|
8223
|
+
taskId: payload.task.id,
|
|
8224
|
+
status: resp.status,
|
|
8225
|
+
attempts: maxAttempts
|
|
8226
|
+
}));
|
|
8227
|
+
return false;
|
|
8228
|
+
}
|
|
8229
|
+
} catch (err) {
|
|
8230
|
+
if (attempt >= maxAttempts) {
|
|
8231
|
+
console.warn(JSON.stringify({
|
|
8232
|
+
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8233
|
+
level: "warn",
|
|
8234
|
+
msg: "task webhook delivery failed",
|
|
8235
|
+
event: payload.event,
|
|
8236
|
+
taskId: payload.task.id,
|
|
8237
|
+
error: err instanceof Error ? err.message : String(err)
|
|
8238
|
+
}));
|
|
8239
|
+
return false;
|
|
8240
|
+
}
|
|
8241
|
+
}
|
|
8242
|
+
if (attempt < maxAttempts) {
|
|
8243
|
+
await new Promise((resolve2) => setTimeout(resolve2, 300 * attempt));
|
|
8244
|
+
}
|
|
8245
|
+
}
|
|
8246
|
+
return false;
|
|
8247
|
+
}
|
|
8248
|
+
|
|
8249
|
+
// src/worker/runners/opencode-server.ts
|
|
8250
|
+
var MAX_SSE_BUFFER_CHARS = 2 * 1024 * 1024;
|
|
8251
|
+
function isLoopbackHost(hostname) {
|
|
8252
|
+
const h = hostname.toLowerCase();
|
|
8253
|
+
return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]";
|
|
8254
|
+
}
|
|
8255
|
+
function sanitizeErrorDetail(raw, maxLen = 240) {
|
|
8256
|
+
if (!raw) return "";
|
|
8257
|
+
return raw.replace(/(authorization\s*[:=]\s*)(basic|bearer)\s+[^\s,;'"`]+/gi, "$1$2 [REDACTED]").replace(/(basic|bearer)\s+[A-Za-z0-9+/_=-]{12,}/gi, "$1 [REDACTED]").replace(/((?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?)[^\s"',;{}]+/gi, "$1[REDACTED]").replace(/\bsk-[A-Za-z0-9_-]{12,}\b/g, "sk-[REDACTED]").replace(/\s+/g, " ").trim().slice(0, maxLen);
|
|
8258
|
+
}
|
|
8259
|
+
function parseModelSpec(rawModel, explicitVariant) {
|
|
8260
|
+
if (!rawModel || rawModel === "default") return null;
|
|
8261
|
+
let modelStr = rawModel.trim();
|
|
8262
|
+
let variant = explicitVariant?.trim() || void 0;
|
|
8263
|
+
const hashIdx = modelStr.indexOf("#");
|
|
8264
|
+
if (hashIdx > 0) {
|
|
8265
|
+
const embedded = modelStr.slice(hashIdx + 1).trim();
|
|
8266
|
+
modelStr = modelStr.slice(0, hashIdx).trim();
|
|
8267
|
+
if (!variant && embedded) variant = embedded;
|
|
8268
|
+
}
|
|
8269
|
+
const slashIdx = modelStr.indexOf("/");
|
|
8270
|
+
if (slashIdx <= 0 || slashIdx === modelStr.length - 1) return null;
|
|
8271
|
+
return {
|
|
8272
|
+
providerID: modelStr.slice(0, slashIdx),
|
|
8273
|
+
id: modelStr.slice(slashIdx + 1),
|
|
8274
|
+
...variant ? { variant } : {}
|
|
8275
|
+
};
|
|
8276
|
+
}
|
|
8277
|
+
var OpenCodeServerRunner = class {
|
|
8278
|
+
name = "opencode-server";
|
|
8279
|
+
baseUrl;
|
|
8280
|
+
password;
|
|
8281
|
+
defaultModel;
|
|
8282
|
+
allowInsecureHttp;
|
|
8283
|
+
fetchFn;
|
|
8284
|
+
constructor(options = {}) {
|
|
8285
|
+
const rawUrl = (options.baseUrl ?? process.env.OPENCODE_URL ?? "").trim();
|
|
8286
|
+
this.baseUrl = rawUrl.replace(/\/+$/, "");
|
|
8287
|
+
this.password = (options.password ?? process.env.OPENCODE_PASSWORD ?? "").trim();
|
|
8288
|
+
this.defaultModel = (options.defaultModel ?? process.env.SUPERTASK_DEFAULT_MODEL ?? process.env.DEFAULT_MODEL ?? "").trim();
|
|
8289
|
+
this.allowInsecureHttp = options.allowInsecureHttp ?? process.env.SUPERTASK_ALLOW_INSECURE_HTTP === "1";
|
|
8290
|
+
this.fetchFn = options.fetchImpl ?? fetch;
|
|
8291
|
+
}
|
|
8292
|
+
authHeaders(extra = {}) {
|
|
8293
|
+
const headers = { ...extra };
|
|
8294
|
+
if (this.password) {
|
|
8295
|
+
headers.authorization = `Basic ${Buffer.from(`opencode:${this.password}`).toString("base64")}`;
|
|
8296
|
+
}
|
|
8297
|
+
return headers;
|
|
8298
|
+
}
|
|
8299
|
+
async interruptSession(sessionId) {
|
|
8300
|
+
try {
|
|
8301
|
+
const resp = await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/interrupt`, {
|
|
8302
|
+
method: "POST",
|
|
8303
|
+
headers: this.authHeaders(),
|
|
8304
|
+
signal: AbortSignal.timeout(3e3)
|
|
8305
|
+
});
|
|
8306
|
+
return resp.ok;
|
|
8307
|
+
} catch {
|
|
8308
|
+
return false;
|
|
8309
|
+
}
|
|
8310
|
+
}
|
|
8311
|
+
async execute(ctx) {
|
|
8312
|
+
if (!this.baseUrl) {
|
|
8313
|
+
return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_URL \u914D\u7F6E" };
|
|
8314
|
+
}
|
|
8315
|
+
if (!this.password) {
|
|
8316
|
+
return { ok: false, sessionId: null, errorMessage: "opencode-server Runner \u7F3A\u5C11 OPENCODE_PASSWORD \u914D\u7F6E" };
|
|
8317
|
+
}
|
|
8318
|
+
let parsedBaseUrl;
|
|
8319
|
+
try {
|
|
8320
|
+
parsedBaseUrl = new URL(this.baseUrl);
|
|
8321
|
+
} catch {
|
|
8322
|
+
return { ok: false, sessionId: null, errorMessage: "OPENCODE_URL \u4E0D\u662F\u6709\u6548\u7684 HTTP(S) \u5730\u5740" };
|
|
8323
|
+
}
|
|
8324
|
+
if (parsedBaseUrl.protocol !== "https:" && !(parsedBaseUrl.protocol === "http:" && (isLoopbackHost(parsedBaseUrl.hostname) || this.allowInsecureHttp))) {
|
|
8325
|
+
return {
|
|
8326
|
+
ok: false,
|
|
8327
|
+
sessionId: null,
|
|
8328
|
+
errorMessage: "\u5B89\u5168\u9650\u5236\uFF1A\u975E\u672C\u673A\u5730\u5740\u7981\u6B62\u901A\u8FC7\u660E\u6587 HTTP \u4F20\u8F93 OpenCode \u53E3\u4EE4\uFF08\u8BF7\u4F7F\u7528 HTTPS \u6216\u8BBE\u7F6E SUPERTASK_ALLOW_INSECURE_HTTP=1\uFF09"
|
|
8329
|
+
};
|
|
8330
|
+
}
|
|
8331
|
+
const explicitModel = ctx.model && ctx.model !== "default" ? ctx.model.trim() : null;
|
|
8332
|
+
const explicitVariant = ctx.variant && ctx.variant !== "default" ? ctx.variant.trim() : null;
|
|
8333
|
+
if (explicitModel && !parseModelSpec(explicitModel, explicitVariant)) {
|
|
8334
|
+
return { ok: false, sessionId: null, errorMessage: `\u65E0\u6548\u7684\u6A21\u578B\u683C\u5F0F\uFF08\u9700\u8981 provider/model\uFF09\uFF1A${explicitModel}` };
|
|
8335
|
+
}
|
|
8336
|
+
let sessionId = null;
|
|
8337
|
+
let interruptedRemote = false;
|
|
8338
|
+
const ensureInterrupt = async (targetIds) => {
|
|
8339
|
+
if (interruptedRemote && !targetIds) return;
|
|
8340
|
+
const ids = /* @__PURE__ */ new Set();
|
|
8341
|
+
if (targetIds) {
|
|
8342
|
+
for (const id of targetIds) if (id) ids.add(id);
|
|
8343
|
+
}
|
|
8344
|
+
if (sessionId) ids.add(sessionId);
|
|
8345
|
+
if (ids.size === 0) return;
|
|
8346
|
+
interruptedRemote = true;
|
|
8347
|
+
await Promise.all([...ids].map((id) => this.interruptSession(id)));
|
|
8348
|
+
};
|
|
8349
|
+
const sseController = new AbortController();
|
|
8350
|
+
const onOuterAbort = () => {
|
|
8351
|
+
sseController.abort();
|
|
8352
|
+
};
|
|
8353
|
+
if (ctx.signal.aborted) {
|
|
8354
|
+
return { ok: false, sessionId: null, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
8355
|
+
}
|
|
8356
|
+
ctx.signal.addEventListener("abort", onOuterAbort, { once: true });
|
|
8357
|
+
try {
|
|
8358
|
+
const agentUrl = new URL(`${this.baseUrl}/api/agent`);
|
|
8359
|
+
agentUrl.searchParams.set("location[directory]", ctx.cwd);
|
|
8360
|
+
let agentDef;
|
|
8361
|
+
for (let attempt = 0; attempt < 4; attempt += 1) {
|
|
8362
|
+
const agentResp = await this.fetchFn(agentUrl.toString(), {
|
|
8363
|
+
headers: this.authHeaders(),
|
|
8364
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
|
|
8365
|
+
});
|
|
8366
|
+
if (!agentResp.ok) {
|
|
8367
|
+
return { ok: false, sessionId: null, errorMessage: `\u65E0\u6CD5\u8BFB\u53D6 OpenCode Agent \u6E05\u5355\uFF1AHTTP ${agentResp.status}` };
|
|
8368
|
+
}
|
|
8369
|
+
const payload = await agentResp.json();
|
|
8370
|
+
agentDef = Array.isArray(payload.data) ? payload.data.find((a) => a.id === ctx.agent) : void 0;
|
|
8371
|
+
if (agentDef) break;
|
|
8372
|
+
if (attempt < 3) await new Promise((r) => setTimeout(r, 250));
|
|
8373
|
+
}
|
|
8374
|
+
if (!agentDef || agentDef.hidden || agentDef.disabled || agentDef.mode === "subagent") {
|
|
8375
|
+
return { ok: false, sessionId: null, errorMessage: `\u4EFB\u52A1\u7684 Agent \u5DF2\u4E0D\u5B58\u5728\u6216\u4E0D\u53EF\u7528\uFF08${ctx.agent}\uFF09` };
|
|
8376
|
+
}
|
|
8377
|
+
const createResp = await this.fetchFn(`${this.baseUrl}/api/session`, {
|
|
8378
|
+
method: "POST",
|
|
8379
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
8380
|
+
body: JSON.stringify({
|
|
8381
|
+
agent: ctx.agent,
|
|
8382
|
+
location: { directory: ctx.cwd },
|
|
8383
|
+
metadata: {
|
|
8384
|
+
...ctx.metadata ?? {},
|
|
8385
|
+
supertaskTaskId: ctx.task.id,
|
|
8386
|
+
supertaskRunId: ctx.runId
|
|
8387
|
+
}
|
|
8388
|
+
}),
|
|
8389
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
|
|
8390
|
+
});
|
|
8391
|
+
if (!createResp.ok) {
|
|
8392
|
+
return { ok: false, sessionId: null, errorMessage: `\u521B\u5EFA OpenCode \u4F1A\u8BDD\u5931\u8D25\uFF1AHTTP ${createResp.status}` };
|
|
8393
|
+
}
|
|
8394
|
+
const created = await createResp.json();
|
|
8395
|
+
sessionId = created.data?.id ?? created.id ?? null;
|
|
8396
|
+
if (!sessionId) {
|
|
8397
|
+
return { ok: false, sessionId: null, errorMessage: "OpenCode \u672A\u8FD4\u56DE\u6709\u6548\u7684\u4F1A\u8BDD ID" };
|
|
8398
|
+
}
|
|
8399
|
+
ctx.onSessionId(sessionId);
|
|
8400
|
+
const cleanTitle = ctx.title.replace(/\s+/g, " ").trim().slice(0, 200);
|
|
8401
|
+
if (cleanTitle) {
|
|
8402
|
+
await this.fetchFn(`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}`, {
|
|
8403
|
+
method: "PATCH",
|
|
8404
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
8405
|
+
body: JSON.stringify({ title: cleanTitle }),
|
|
8406
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(5e3)])
|
|
8407
|
+
}).catch(() => void 0);
|
|
8408
|
+
}
|
|
8409
|
+
let modelSpec = explicitModel ? parseModelSpec(explicitModel, explicitVariant) : null;
|
|
8410
|
+
if (!modelSpec && agentDef.model?.providerID && agentDef.model?.id) {
|
|
8411
|
+
const resolvedVariant = explicitVariant ?? (agentDef.model.variant && agentDef.model.variant !== "default" ? agentDef.model.variant : void 0);
|
|
8412
|
+
modelSpec = {
|
|
8413
|
+
providerID: agentDef.model.providerID,
|
|
8414
|
+
id: agentDef.model.id,
|
|
8415
|
+
...resolvedVariant ? { variant: resolvedVariant } : {}
|
|
8416
|
+
};
|
|
8417
|
+
}
|
|
8418
|
+
if (!modelSpec && this.defaultModel) {
|
|
8419
|
+
modelSpec = parseModelSpec(this.defaultModel, explicitVariant);
|
|
8420
|
+
}
|
|
8421
|
+
if (explicitVariant && !modelSpec) {
|
|
8422
|
+
return { ok: false, sessionId, errorMessage: "\u6307\u5B9A\u4E86 variant \u4F46\u672A\u914D\u7F6E\u53EF\u7528\u6A21\u578B" };
|
|
8423
|
+
}
|
|
8424
|
+
if (modelSpec) {
|
|
8425
|
+
const switchResp = await this.fetchFn(
|
|
8426
|
+
`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/model`,
|
|
8427
|
+
{
|
|
8428
|
+
method: "POST",
|
|
8429
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
8430
|
+
body: JSON.stringify({ model: modelSpec }),
|
|
8431
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(1e4)])
|
|
8432
|
+
}
|
|
8433
|
+
);
|
|
8434
|
+
if (!switchResp.ok) {
|
|
8435
|
+
return { ok: false, sessionId, errorMessage: `\u5207\u6362 OpenCode \u6A21\u578B\u5931\u8D25\uFF1AHTTP ${switchResp.status}` };
|
|
8436
|
+
}
|
|
8437
|
+
}
|
|
8438
|
+
const sseResp = await this.fetchFn(`${this.baseUrl}/api/event`, {
|
|
8439
|
+
headers: this.authHeaders({ accept: "text/event-stream" }),
|
|
8440
|
+
signal: sseController.signal
|
|
8441
|
+
});
|
|
8442
|
+
const contentType = sseResp.headers.get("content-type") || "";
|
|
8443
|
+
if (!sseResp.ok || !sseResp.body || !contentType.toLowerCase().includes("text/event-stream")) {
|
|
8444
|
+
sseController.abort();
|
|
8445
|
+
return {
|
|
8446
|
+
ok: false,
|
|
8447
|
+
sessionId,
|
|
8448
|
+
errorMessage: `\u65E0\u6CD5\u8BA2\u9605 OpenCode \u4E8B\u4EF6\u6D41\uFF1AHTTP ${sseResp.status}${contentType ? ` (${contentType})` : ""}`
|
|
8449
|
+
};
|
|
8450
|
+
}
|
|
8451
|
+
const promptResp = await this.fetchFn(
|
|
8452
|
+
`${this.baseUrl}/api/session/${encodeURIComponent(sessionId)}/prompt`,
|
|
8453
|
+
{
|
|
8454
|
+
method: "POST",
|
|
8455
|
+
headers: this.authHeaders({ "content-type": "application/json" }),
|
|
8456
|
+
body: JSON.stringify({ text: ctx.prompt }),
|
|
8457
|
+
signal: AbortSignal.any([ctx.signal, AbortSignal.timeout(15e3)])
|
|
8458
|
+
}
|
|
8459
|
+
);
|
|
8460
|
+
if (!promptResp.ok) {
|
|
8461
|
+
sseController.abort();
|
|
8462
|
+
const detail = sanitizeErrorDetail(await promptResp.text().catch(() => ""));
|
|
8463
|
+
return {
|
|
8464
|
+
ok: false,
|
|
8465
|
+
sessionId,
|
|
8466
|
+
errorMessage: `OpenCode \u63D0\u4EA4\u4EFB\u52A1\u5931\u8D25\uFF1AHTTP ${promptResp.status}${detail ? ` ${detail}` : ""}`
|
|
8467
|
+
};
|
|
8468
|
+
}
|
|
8469
|
+
const trackedSessionIds = /* @__PURE__ */ new Set([sessionId]);
|
|
8470
|
+
const reader = sseResp.body.getReader();
|
|
8471
|
+
const decoder = new TextDecoder();
|
|
8472
|
+
let buffer = "";
|
|
8473
|
+
let pendingText = "";
|
|
8474
|
+
const flushText = () => {
|
|
8475
|
+
if (!pendingText) return;
|
|
8476
|
+
ctx.onOutputChunk(`${JSON.stringify({ type: "text", sessionID: sessionId, part: { text: pendingText } })}
|
|
8477
|
+
`);
|
|
8478
|
+
pendingText = "";
|
|
8479
|
+
};
|
|
8480
|
+
const processEventPayload = async (rawData) => {
|
|
8481
|
+
let evt;
|
|
8482
|
+
try {
|
|
8483
|
+
evt = JSON.parse(rawData);
|
|
8484
|
+
} catch {
|
|
8485
|
+
return null;
|
|
8486
|
+
}
|
|
8487
|
+
const evtType = evt.type || "";
|
|
8488
|
+
if (evtType === "session.created") {
|
|
8489
|
+
const childId = evt.data?.id ?? evt.data?.session?.id ?? "";
|
|
8490
|
+
const parentId = evt.data?.parentID ?? evt.data?.session?.parentID ?? "";
|
|
8491
|
+
if (childId && parentId && trackedSessionIds.has(parentId)) {
|
|
8492
|
+
trackedSessionIds.add(childId);
|
|
8493
|
+
}
|
|
8494
|
+
return null;
|
|
8495
|
+
}
|
|
8496
|
+
const evtSessionId = evt.data?.sessionID ?? evt.data?.form?.sessionID ?? "";
|
|
8497
|
+
if (!evtSessionId || !trackedSessionIds.has(evtSessionId)) return null;
|
|
8498
|
+
if (evtType === "permission.asked" || evtType === "form.created") {
|
|
8499
|
+
flushText();
|
|
8500
|
+
const message = evtType === "permission.asked" ? "\u4EFB\u52A1\u9700\u8981\u4EBA\u5DE5\u6279\u51C6\uFF0C\u540E\u53F0\u6267\u884C\u5DF2\u505C\u6B62\u3002\u8BF7\u5728\u4EA4\u4E92\u5BF9\u8BDD\u4E2D\u5904\u7406\uFF0C\u6216\u660E\u786E\u8C03\u6574\u8BE5Agent\u7684\u64CD\u4F5C\u6743\u9650\u540E\u91CD\u8BD5\u3002" : "\u4EFB\u52A1\u9700\u8981\u4F60\u56DE\u7B54\u95EE\u9898\uFF0C\u540E\u53F0\u6267\u884C\u5DF2\u505C\u6B62\u3002\u8BF7\u8865\u5168\u4EFB\u52A1\u8BF4\u660E\u540E\u91CD\u8BD5\uFF0C\u6216\u5728\u4EA4\u4E92\u5BF9\u8BDD\u4E2D\u5904\u7406\u3002";
|
|
8501
|
+
ctx.onOutputChunk(`${JSON.stringify({
|
|
8502
|
+
type: "error",
|
|
8503
|
+
sessionID: sessionId,
|
|
8504
|
+
error: { name: "InteractionRequired", data: { message } }
|
|
8505
|
+
})}
|
|
8506
|
+
`);
|
|
8507
|
+
await ensureInterrupt(trackedSessionIds);
|
|
8508
|
+
return { ok: false, sessionId, errorMessage: message };
|
|
8509
|
+
}
|
|
8510
|
+
if (evtSessionId !== sessionId) return null;
|
|
8511
|
+
if (evtType === "session.text.delta") {
|
|
8512
|
+
const delta = typeof evt.data?.delta === "string" ? evt.data.delta : typeof evt.data?.text === "string" ? evt.data.text : "";
|
|
8513
|
+
if (delta) {
|
|
8514
|
+
pendingText += delta;
|
|
8515
|
+
if (pendingText.includes("\n") || pendingText.length >= 256) flushText();
|
|
8516
|
+
}
|
|
8517
|
+
return null;
|
|
8518
|
+
}
|
|
8519
|
+
if (evtType === "session.step.ended") {
|
|
8520
|
+
flushText();
|
|
8521
|
+
return null;
|
|
8522
|
+
}
|
|
8523
|
+
if (evtType === "session.execution.succeeded") {
|
|
8524
|
+
flushText();
|
|
8525
|
+
return { ok: true, sessionId };
|
|
8526
|
+
}
|
|
8527
|
+
if (evtType === "session.execution.failed") {
|
|
8528
|
+
flushText();
|
|
8529
|
+
const rawErr = evt.data?.error?.data?.message || evt.data?.error?.message || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
|
|
8530
|
+
const errMsg = sanitizeErrorDetail(rawErr, 400) || "\u4EFB\u52A1\u6267\u884C\u5931\u8D25";
|
|
8531
|
+
ctx.onOutputChunk(`${JSON.stringify({
|
|
8532
|
+
type: "error",
|
|
8533
|
+
sessionID: sessionId,
|
|
8534
|
+
error: { name: evt.data?.error?.name || "ExecutionError", data: { message: errMsg } }
|
|
8535
|
+
})}
|
|
8536
|
+
`);
|
|
8537
|
+
return { ok: false, sessionId, errorMessage: errMsg };
|
|
8538
|
+
}
|
|
8539
|
+
if (evtType === "session.execution.interrupted") {
|
|
8540
|
+
flushText();
|
|
8541
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u6267\u884C\u5DF2\u4E2D\u65AD" };
|
|
8542
|
+
}
|
|
8543
|
+
return null;
|
|
8544
|
+
};
|
|
8545
|
+
try {
|
|
8546
|
+
while (true) {
|
|
8547
|
+
const { done, value } = await reader.read();
|
|
8548
|
+
if (done) break;
|
|
8549
|
+
buffer += decoder.decode(value, { stream: true }).replace(/\r\n/g, "\n").replace(/\r/g, "\n");
|
|
8550
|
+
if (buffer.length > MAX_SSE_BUFFER_CHARS) {
|
|
8551
|
+
buffer = buffer.slice(-MAX_SSE_BUFFER_CHARS);
|
|
8552
|
+
}
|
|
8553
|
+
let sepIdx = buffer.indexOf("\n\n");
|
|
8554
|
+
while (sepIdx >= 0) {
|
|
8555
|
+
const frame = buffer.slice(0, sepIdx);
|
|
8556
|
+
buffer = buffer.slice(sepIdx + 2);
|
|
8557
|
+
const dataLines = [];
|
|
8558
|
+
for (const line of frame.split("\n")) {
|
|
8559
|
+
if (line.startsWith("data:")) dataLines.push(line.slice(5).trimStart());
|
|
8560
|
+
}
|
|
8561
|
+
if (dataLines.length > 0) {
|
|
8562
|
+
const terminal = await processEventPayload(dataLines.join("\n"));
|
|
8563
|
+
if (terminal) {
|
|
8564
|
+
sseController.abort();
|
|
8565
|
+
return terminal;
|
|
8566
|
+
}
|
|
8567
|
+
}
|
|
8568
|
+
sepIdx = buffer.indexOf("\n\n");
|
|
8569
|
+
}
|
|
8570
|
+
}
|
|
8571
|
+
} finally {
|
|
8572
|
+
reader.releaseLock();
|
|
8573
|
+
}
|
|
8574
|
+
flushText();
|
|
8575
|
+
if (ctx.signal.aborted) {
|
|
8576
|
+
await ensureInterrupt(trackedSessionIds);
|
|
8577
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
8578
|
+
}
|
|
8579
|
+
await ensureInterrupt(trackedSessionIds);
|
|
8580
|
+
return { ok: false, sessionId, errorMessage: "OpenCode \u4E8B\u4EF6\u6D41\u63D0\u524D\u65AD\u5F00\uFF0C\u5DF2\u4E2D\u6B62\u8FDC\u7AEF\u4F1A\u8BDD" };
|
|
8581
|
+
} catch (error) {
|
|
8582
|
+
if (ctx.signal.aborted) {
|
|
8583
|
+
await ensureInterrupt();
|
|
8584
|
+
return { ok: false, sessionId, errorMessage: "\u4EFB\u52A1\u5DF2\u53D6\u6D88" };
|
|
8585
|
+
}
|
|
8586
|
+
if (sessionId) await ensureInterrupt();
|
|
8587
|
+
const msg = sanitizeErrorDetail(error instanceof Error ? error.message : String(error), 300) || "Runner \u6267\u884C\u5F02\u5E38";
|
|
8588
|
+
return { ok: false, sessionId, errorMessage: msg };
|
|
8589
|
+
} finally {
|
|
8590
|
+
sseController.abort();
|
|
8591
|
+
ctx.signal.removeEventListener("abort", onOuterAbort);
|
|
8592
|
+
}
|
|
8593
|
+
}
|
|
8594
|
+
};
|
|
8595
|
+
|
|
8055
8596
|
// src/worker/index.ts
|
|
8056
8597
|
import { fileURLToPath as fileURLToPath3 } from "url";
|
|
8057
8598
|
import { existsSync as existsSync2 } from "fs";
|
|
@@ -8159,6 +8700,28 @@ function topLevelSessionId(event) {
|
|
|
8159
8700
|
|
|
8160
8701
|
// src/core/opencode-cli.ts
|
|
8161
8702
|
import { spawn, spawnSync } from "child_process";
|
|
8703
|
+
|
|
8704
|
+
// src/core/env-sanitize.ts
|
|
8705
|
+
var GATEWAY_SECRET_ENV_KEYS = [
|
|
8706
|
+
"SUPERTASK_API_TOKEN",
|
|
8707
|
+
"SUPERTASK_WEBHOOK_SECRET",
|
|
8708
|
+
"SUPERTASK_WEBHOOK_URL",
|
|
8709
|
+
"OPENCODE_PASSWORD",
|
|
8710
|
+
"OPENCODE_SERVER_PASSWORD"
|
|
8711
|
+
];
|
|
8712
|
+
function sanitizedChildEnv(baseEnv = process.env, overrides = {}) {
|
|
8713
|
+
const env = { ...baseEnv };
|
|
8714
|
+
for (const key of GATEWAY_SECRET_ENV_KEYS) {
|
|
8715
|
+
delete env[key];
|
|
8716
|
+
}
|
|
8717
|
+
for (const [key, value] of Object.entries(overrides)) {
|
|
8718
|
+
if (value === void 0) delete env[key];
|
|
8719
|
+
else env[key] = value;
|
|
8720
|
+
}
|
|
8721
|
+
return env;
|
|
8722
|
+
}
|
|
8723
|
+
|
|
8724
|
+
// src/core/opencode-cli.ts
|
|
8162
8725
|
var OpenCodeInvocationError = class extends Error {
|
|
8163
8726
|
};
|
|
8164
8727
|
var VERSION_TIMEOUT_MS = 15e3;
|
|
@@ -8180,7 +8743,7 @@ function detectOpenCodeVersion(executable = openCodeExecutable(), options = {})
|
|
|
8180
8743
|
const result = new Promise((resolve2, reject) => {
|
|
8181
8744
|
const child = spawn(executable, ["--version"], {
|
|
8182
8745
|
cwd: options.cwd,
|
|
8183
|
-
env: process.env,
|
|
8746
|
+
env: sanitizedChildEnv(process.env),
|
|
8184
8747
|
stdio: ["ignore", "pipe", "pipe"]
|
|
8185
8748
|
});
|
|
8186
8749
|
let output = "";
|
|
@@ -8284,12 +8847,14 @@ var WorkerEngine = class {
|
|
|
8284
8847
|
settlementRetryWakeups = /* @__PURE__ */ new Set();
|
|
8285
8848
|
cfg;
|
|
8286
8849
|
opencodeBin;
|
|
8850
|
+
runner;
|
|
8287
8851
|
maxOutputChars;
|
|
8288
8852
|
settlementRetryDelaysMs;
|
|
8289
8853
|
settlementRetryIntervalMs;
|
|
8290
8854
|
constructor(cfg, options = {}) {
|
|
8291
8855
|
this.cfg = cfg.worker;
|
|
8292
8856
|
this.opencodeBin = options.opencodeBin ?? openCodeExecutable();
|
|
8857
|
+
this.runner = options.runner ?? (process.env.SUPERTASK_RUNNER?.trim() === "opencode-server" ? new OpenCodeServerRunner() : null);
|
|
8293
8858
|
this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;
|
|
8294
8859
|
this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1e3, 4e3];
|
|
8295
8860
|
this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5e3;
|
|
@@ -8338,7 +8903,7 @@ var WorkerEngine = class {
|
|
|
8338
8903
|
if (this.pollCyclePromise) await this.pollCyclePromise;
|
|
8339
8904
|
if (gracePeriodMs > 0 && this.runningTasks.size > 0) {
|
|
8340
8905
|
const deadline = Date.now() + gracePeriodMs;
|
|
8341
|
-
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
8906
|
+
while ([...this.runningTasks.values()].some((entry) => !(entry.termination?.kind === "shutdown" && (!entry.child || entry.child.exitCode !== null || entry.child.signalCode !== null))) && Date.now() < deadline) {
|
|
8342
8907
|
await Bun.sleep(Math.min(50, deadline - Date.now()));
|
|
8343
8908
|
}
|
|
8344
8909
|
}
|
|
@@ -8423,7 +8988,7 @@ var WorkerEngine = class {
|
|
|
8423
8988
|
while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {
|
|
8424
8989
|
const databaseRunningCount = await TaskService.countRunning();
|
|
8425
8990
|
if (databaseRunningCount >= this.cfg.maxConcurrency) break;
|
|
8426
|
-
const openCode = await detectOpenCodeVersion(this.opencodeBin);
|
|
8991
|
+
const openCode = this.runner ? null : await detectOpenCodeVersion(this.opencodeBin);
|
|
8427
8992
|
if (this.stopped) break;
|
|
8428
8993
|
let task;
|
|
8429
8994
|
try {
|
|
@@ -8457,7 +9022,7 @@ var WorkerEngine = class {
|
|
|
8457
9022
|
workerPid: process.pid,
|
|
8458
9023
|
lockedAt: Date.now(),
|
|
8459
9024
|
lockedBy: launchIdentity,
|
|
8460
|
-
launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
9025
|
+
launchProtocol: this.runner ? `runner:${this.runner.name}` : TOKEN_GUARDIAN_LAUNCH_PROTOCOL
|
|
8461
9026
|
});
|
|
8462
9027
|
runId = run.id;
|
|
8463
9028
|
if (this.stopped) {
|
|
@@ -8477,9 +9042,19 @@ var WorkerEngine = class {
|
|
|
8477
9042
|
} catch (error) {
|
|
8478
9043
|
const message = error instanceof Error ? error.message : String(error);
|
|
8479
9044
|
await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
|
|
9045
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
9046
|
+
"task.dead_letter",
|
|
9047
|
+
{ ...task, status: "dead_letter", finishedAt: /* @__PURE__ */ new Date(), resultLog: message },
|
|
9048
|
+
{ id: run.id, sessionId: null, status: "failed" },
|
|
9049
|
+
message
|
|
9050
|
+
));
|
|
8480
9051
|
this.releaseBatch(task);
|
|
8481
9052
|
continue;
|
|
8482
9053
|
}
|
|
9054
|
+
if (this.runner) {
|
|
9055
|
+
this.executeViaRunner(task, run.id, launchIdentity, this.runner);
|
|
9056
|
+
continue;
|
|
9057
|
+
}
|
|
8483
9058
|
let args;
|
|
8484
9059
|
try {
|
|
8485
9060
|
args = buildOpenCodeRunArgs(openCode.major, {
|
|
@@ -8491,7 +9066,14 @@ var WorkerEngine = class {
|
|
|
8491
9066
|
});
|
|
8492
9067
|
} catch (error) {
|
|
8493
9068
|
if (!(error instanceof OpenCodeInvocationError)) throw error;
|
|
8494
|
-
|
|
9069
|
+
const message = `${error.message}\uFF08OpenCode ${openCode.version}\uFF09`;
|
|
9070
|
+
await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });
|
|
9071
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
9072
|
+
"task.dead_letter",
|
|
9073
|
+
{ ...task, status: "dead_letter", finishedAt: /* @__PURE__ */ new Date(), resultLog: message },
|
|
9074
|
+
{ id: run.id, sessionId: null, status: "failed" },
|
|
9075
|
+
message
|
|
9076
|
+
));
|
|
8495
9077
|
this.releaseBatch(task);
|
|
8496
9078
|
continue;
|
|
8497
9079
|
}
|
|
@@ -8531,8 +9113,106 @@ var WorkerEngine = class {
|
|
|
8531
9113
|
if (!entry) throw new Error(`Worker launcher \u4E0D\u5B58\u5728\uFF1A${candidates.join(", ")}`);
|
|
8532
9114
|
return entry;
|
|
8533
9115
|
}
|
|
9116
|
+
executeViaRunner(task, runId, launchIdentity, runner) {
|
|
9117
|
+
const cwd = task.cwd || process.cwd();
|
|
9118
|
+
const abortController = new AbortController();
|
|
9119
|
+
const model = this.resolveModel(task.model);
|
|
9120
|
+
const variant = this.resolveVariant(task.variant);
|
|
9121
|
+
const entry = {
|
|
9122
|
+
task,
|
|
9123
|
+
runId,
|
|
9124
|
+
sessionId: null,
|
|
9125
|
+
launchIdentity,
|
|
9126
|
+
child: null,
|
|
9127
|
+
runnerAbort: abortController,
|
|
9128
|
+
commandContext: runCommandContext(`runner:${runner.name}`, [task.agent], cwd),
|
|
9129
|
+
output: new RunOutput(
|
|
9130
|
+
this.maxOutputChars,
|
|
9131
|
+
(sessionId) => {
|
|
9132
|
+
entry.sessionId = sessionId;
|
|
9133
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
9134
|
+
this.logError("sessionId update failed", err, task.id);
|
|
9135
|
+
});
|
|
9136
|
+
},
|
|
9137
|
+
(stream, line) => {
|
|
9138
|
+
gatewayEvents.emitRunLog(runId, task.id, stream, line);
|
|
9139
|
+
}
|
|
9140
|
+
),
|
|
9141
|
+
timeoutTimer: null,
|
|
9142
|
+
termination: null,
|
|
9143
|
+
terminationPromise: null,
|
|
9144
|
+
settlementPromise: null,
|
|
9145
|
+
guardianDrained: true,
|
|
9146
|
+
quarantined: false,
|
|
9147
|
+
settled: false
|
|
9148
|
+
};
|
|
9149
|
+
this.runningTasks.set(task.id, entry);
|
|
9150
|
+
gatewayEvents.emitRunStarted({
|
|
9151
|
+
runId,
|
|
9152
|
+
taskId: task.id,
|
|
9153
|
+
cwd: task.cwd,
|
|
9154
|
+
model,
|
|
9155
|
+
variant
|
|
9156
|
+
});
|
|
9157
|
+
const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;
|
|
9158
|
+
if (timeoutMs > 0) {
|
|
9159
|
+
entry.timeoutTimer = setTimeout(() => {
|
|
9160
|
+
this.runDetached(
|
|
9161
|
+
this.terminateForFailure(entry, `\u4EFB\u52A1\u8D85\u65F6\uFF08${timeoutMs}ms\uFF09`, "SIGKILL"),
|
|
9162
|
+
"runner timeout termination failed",
|
|
9163
|
+
entry.task.id
|
|
9164
|
+
);
|
|
9165
|
+
}, timeoutMs);
|
|
9166
|
+
entry.timeoutTimer.unref?.();
|
|
9167
|
+
}
|
|
9168
|
+
const runnerPromise = runner.execute({
|
|
9169
|
+
task,
|
|
9170
|
+
runId,
|
|
9171
|
+
cwd,
|
|
9172
|
+
agent: task.agent,
|
|
9173
|
+
model,
|
|
9174
|
+
variant,
|
|
9175
|
+
prompt: task.prompt,
|
|
9176
|
+
title: task.name,
|
|
9177
|
+
metadata: parseTaskMetadata(task.metadata),
|
|
9178
|
+
signal: abortController.signal,
|
|
9179
|
+
onSessionId: (sessionId) => {
|
|
9180
|
+
entry.sessionId = sessionId;
|
|
9181
|
+
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
9182
|
+
this.logError("sessionId update failed", err, task.id);
|
|
9183
|
+
});
|
|
9184
|
+
},
|
|
9185
|
+
onOutputChunk: (chunk) => {
|
|
9186
|
+
entry.output.push("stdout", chunk);
|
|
9187
|
+
}
|
|
9188
|
+
}).then((result) => {
|
|
9189
|
+
if (entry.settled || entry.termination) return;
|
|
9190
|
+
this.runDetached(
|
|
9191
|
+
this.settleEntry(entry, result.ok ? 0 : 1, result.ok ? void 0 : result.errorMessage || "Runner \u6267\u884C\u5931\u8D25"),
|
|
9192
|
+
"runner settlement failed",
|
|
9193
|
+
entry.task.id
|
|
9194
|
+
);
|
|
9195
|
+
}).catch((error) => {
|
|
9196
|
+
if (entry.settled || entry.termination) return;
|
|
9197
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
9198
|
+
this.runDetached(
|
|
9199
|
+
this.settleEntry(entry, 1, `Runner \u6267\u884C\u5F02\u5E38\uFF1A${msg}`),
|
|
9200
|
+
"runner error settlement failed",
|
|
9201
|
+
entry.task.id
|
|
9202
|
+
);
|
|
9203
|
+
});
|
|
9204
|
+
entry.runnerDone = runnerPromise;
|
|
9205
|
+
}
|
|
8534
9206
|
async spawnTask(task, runId, launchIdentity, args) {
|
|
8535
9207
|
const cwd = task.cwd || process.cwd();
|
|
9208
|
+
const childEnv = {
|
|
9209
|
+
...process.env,
|
|
9210
|
+
PWD: cwd,
|
|
9211
|
+
[MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
|
|
9212
|
+
};
|
|
9213
|
+
delete childEnv.SUPERTASK_API_TOKEN;
|
|
9214
|
+
delete childEnv.SUPERTASK_WEBHOOK_SECRET;
|
|
9215
|
+
delete childEnv.SUPERTASK_WEBHOOK_URL;
|
|
8536
9216
|
const child = spawn2(process.execPath, [
|
|
8537
9217
|
this.launcherEntry(),
|
|
8538
9218
|
LAUNCH_IDENTITY_ARGUMENT,
|
|
@@ -8541,23 +9221,21 @@ var WorkerEngine = class {
|
|
|
8541
9221
|
...args
|
|
8542
9222
|
], {
|
|
8543
9223
|
cwd,
|
|
8544
|
-
env:
|
|
8545
|
-
...process.env,
|
|
8546
|
-
PWD: cwd,
|
|
8547
|
-
[MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE
|
|
8548
|
-
},
|
|
9224
|
+
env: childEnv,
|
|
8549
9225
|
stdio: ["pipe", "pipe", "pipe", "ipc"],
|
|
8550
9226
|
detached: process.platform !== "win32"
|
|
8551
9227
|
});
|
|
8552
9228
|
const entry = {
|
|
8553
9229
|
task,
|
|
8554
9230
|
runId,
|
|
9231
|
+
sessionId: null,
|
|
8555
9232
|
launchIdentity,
|
|
8556
9233
|
child,
|
|
8557
9234
|
commandContext: runCommandContext(this.opencodeBin, args, cwd),
|
|
8558
9235
|
output: new RunOutput(
|
|
8559
9236
|
this.maxOutputChars,
|
|
8560
9237
|
(sessionId) => {
|
|
9238
|
+
entry.sessionId = sessionId;
|
|
8561
9239
|
TaskRunService.updateSessionId(runId, sessionId).catch((err) => {
|
|
8562
9240
|
this.logError("sessionId update failed", err, task.id);
|
|
8563
9241
|
});
|
|
@@ -8691,7 +9369,7 @@ var WorkerEngine = class {
|
|
|
8691
9369
|
handleChildClose(entry, code, signal, spawnError) {
|
|
8692
9370
|
if (entry.settled || entry.termination) return;
|
|
8693
9371
|
if (!entry.guardianDrained) {
|
|
8694
|
-
const pid2 = entry.child
|
|
9372
|
+
const pid2 = entry.child?.pid;
|
|
8695
9373
|
const presence = pid2 == null ? spawnError == null ? "unknown" : "not-running" : inspectSpawnedProcessTreePresence(pid2);
|
|
8696
9374
|
const message = "guardian \u672A\u63D0\u4F9B\u53D7\u7BA1\u8FDB\u7A0B\u7EC4\u6392\u7A7A\u8BC1\u660E";
|
|
8697
9375
|
if (presence !== "not-running") {
|
|
@@ -8714,7 +9392,7 @@ var WorkerEngine = class {
|
|
|
8714
9392
|
);
|
|
8715
9393
|
return;
|
|
8716
9394
|
}
|
|
8717
|
-
const pid = entry.child
|
|
9395
|
+
const pid = entry.child?.pid;
|
|
8718
9396
|
if (pid != null && inspectSpawnedProcessTreePresence(pid) !== "not-running") {
|
|
8719
9397
|
if (entry.timeoutTimer) {
|
|
8720
9398
|
clearTimeout(entry.timeoutTimer);
|
|
@@ -8809,6 +9487,12 @@ ${output2}` : ""}`;
|
|
|
8809
9487
|
status: "cancelled",
|
|
8810
9488
|
reason: "run-cancelled"
|
|
8811
9489
|
});
|
|
9490
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
9491
|
+
"task.cancelled",
|
|
9492
|
+
{ ...entry.task, status: "cancelled", finishedAt: /* @__PURE__ */ new Date(), resultLog: log2 },
|
|
9493
|
+
{ id: entry.runId, sessionId: entry.sessionId, status: "failed" },
|
|
9494
|
+
log2
|
|
9495
|
+
));
|
|
8812
9496
|
console.log(JSON.stringify({
|
|
8813
9497
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8814
9498
|
level: "info",
|
|
@@ -8838,6 +9522,12 @@ ${output}` : ""}` : output;
|
|
|
8838
9522
|
status: "done",
|
|
8839
9523
|
reason: "run-done"
|
|
8840
9524
|
});
|
|
9525
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
9526
|
+
"task.done",
|
|
9527
|
+
{ ...entry.task, status: "done", finishedAt: /* @__PURE__ */ new Date(), resultLog: log },
|
|
9528
|
+
{ id: entry.runId, sessionId: entry.sessionId, status: "done" },
|
|
9529
|
+
log
|
|
9530
|
+
));
|
|
8841
9531
|
console.log(JSON.stringify({
|
|
8842
9532
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8843
9533
|
level: "info",
|
|
@@ -8883,6 +9573,13 @@ ${output}` : ""}` : output;
|
|
|
8883
9573
|
status: failed.status,
|
|
8884
9574
|
reason: "run-failed"
|
|
8885
9575
|
});
|
|
9576
|
+
const webhookEvent = failed.status === "dead_letter" ? "task.dead_letter" : "task.failed";
|
|
9577
|
+
void dispatchTaskWebhook(buildTaskWebhookPayload(
|
|
9578
|
+
webhookEvent,
|
|
9579
|
+
{ ...entry.task, status: failed.status, finishedAt: /* @__PURE__ */ new Date(), resultLog: log },
|
|
9580
|
+
{ id: entry.runId, sessionId: entry.sessionId, status: "failed" },
|
|
9581
|
+
log
|
|
9582
|
+
));
|
|
8886
9583
|
console.error(JSON.stringify({
|
|
8887
9584
|
ts: (/* @__PURE__ */ new Date()).toISOString(),
|
|
8888
9585
|
level: "error",
|
|
@@ -8965,6 +9662,17 @@ ${output}` : ""}` : output;
|
|
|
8965
9662
|
}
|
|
8966
9663
|
}
|
|
8967
9664
|
async killEntry(entry, initialSignal = "SIGTERM") {
|
|
9665
|
+
if (entry.runnerAbort) {
|
|
9666
|
+
entry.runnerAbort.abort();
|
|
9667
|
+
if (entry.runnerDone) {
|
|
9668
|
+
await Promise.race([
|
|
9669
|
+
entry.runnerDone.catch(() => void 0),
|
|
9670
|
+
new Promise((resolve2) => setTimeout(resolve2, 5e3))
|
|
9671
|
+
]);
|
|
9672
|
+
}
|
|
9673
|
+
return true;
|
|
9674
|
+
}
|
|
9675
|
+
if (!entry.child) return true;
|
|
8968
9676
|
const pid = entry.child.pid;
|
|
8969
9677
|
if (entry.guardianDrained && (entry.child.exitCode !== null || entry.child.signalCode !== null) && (!pid || inspectSpawnedProcessTreePresence(pid) === "not-running")) return true;
|
|
8970
9678
|
if (!pid) return false;
|
|
@@ -8980,7 +9688,7 @@ ${output}` : ""}` : output;
|
|
|
8980
9688
|
return waitForSpawnedProcessTreeExit(pid, 2500);
|
|
8981
9689
|
}
|
|
8982
9690
|
signalEntry(entry, signal) {
|
|
8983
|
-
const pid = entry.child
|
|
9691
|
+
const pid = entry.child?.pid;
|
|
8984
9692
|
if (!pid) return "not-running";
|
|
8985
9693
|
return signalRecordedProcessTreeWithResult(
|
|
8986
9694
|
pid,
|