@ginkgolab/harness-core 0.1.0 → 0.1.2
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/README.md +11 -0
- package/dist/built-JAK7YFRG.js +10825 -0
- package/dist/chunk-2N25X2GE.js +66 -0
- package/dist/chunk-6OYMWYZS.js +19 -0
- package/dist/chunk-A7RQFPRO.js +42 -0
- package/dist/chunk-DIWHNBPO.js +139 -0
- package/dist/chunk-HYD33JX5.js +264 -0
- package/dist/chunk-JLMNLT6T.js +345 -0
- package/dist/chunk-JYNDOV22.js +790 -0
- package/dist/chunk-K2XRWRKF.js +274 -0
- package/dist/chunk-LASGGBG6.js +371 -0
- package/dist/chunk-MWOHX4WC.js +254 -0
- package/dist/chunk-OEJYZ6IB.js +357 -0
- package/dist/chunk-PPR3G4HX.js +127 -0
- package/dist/chunk-RYIWJPIR.js +196 -0
- package/dist/chunk-SCHUPQP4.js +36 -0
- package/dist/chunk-VIREJDUO.js +306 -0
- package/dist/chunk-VNSZH3H7.js +17 -0
- package/dist/chunk-ZO2UWHNE.js +22 -0
- package/dist/config.js +15 -356
- package/dist/context.js +21 -252
- package/dist/finops.js +10 -11057
- package/dist/graph.js +8 -298
- package/dist/index.js +131 -14348
- package/dist/lifecycle.js +6 -165
- package/dist/mcp.js +7 -338
- package/dist/pipeline.js +12 -348
- package/dist/registry.js +5 -5
- package/dist/stream.js +16 -11908
- package/dist/telemetry.js +11 -305
- package/dist/tokenizer.js +10 -73
- package/dist/tools.js +11 -158
- package/package.json +2 -2
|
@@ -0,0 +1,790 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createConsoleSink
|
|
3
|
+
} from "./chunk-A7RQFPRO.js";
|
|
4
|
+
|
|
5
|
+
// src/stream/taskStore.ts
|
|
6
|
+
import { EventEmitter } from "events";
|
|
7
|
+
var InMemoryTaskStore = class {
|
|
8
|
+
tasks = /* @__PURE__ */ new Map();
|
|
9
|
+
events = new EventEmitter();
|
|
10
|
+
constructor() {
|
|
11
|
+
this.events.setMaxListeners(0);
|
|
12
|
+
}
|
|
13
|
+
async create(snapshot) {
|
|
14
|
+
this.tasks.set(snapshot.sessionKey, {
|
|
15
|
+
snapshot: { ...snapshot },
|
|
16
|
+
chunks: []
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
async appendChunk(sessionKey, chunk) {
|
|
20
|
+
const record = this.tasks.get(sessionKey);
|
|
21
|
+
if (!record) return;
|
|
22
|
+
record.chunks.push(chunk);
|
|
23
|
+
this.events.emit(this.chunkEvent(sessionKey), chunk, record.chunks.length);
|
|
24
|
+
}
|
|
25
|
+
async setStatus(sessionKey, status, errorMessage) {
|
|
26
|
+
const record = this.tasks.get(sessionKey);
|
|
27
|
+
if (!record) return;
|
|
28
|
+
const previous = record.snapshot.status;
|
|
29
|
+
record.snapshot = {
|
|
30
|
+
...record.snapshot,
|
|
31
|
+
status,
|
|
32
|
+
updatedAt: Date.now(),
|
|
33
|
+
...errorMessage === void 0 ? {} : { errorMessage }
|
|
34
|
+
};
|
|
35
|
+
if (status !== "running" && previous === "running") {
|
|
36
|
+
this.events.emit(this.closeEvent(sessionKey), status, errorMessage);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
async get(sessionKey) {
|
|
40
|
+
const snapshot = this.tasks.get(sessionKey)?.snapshot;
|
|
41
|
+
return snapshot ? { ...snapshot } : void 0;
|
|
42
|
+
}
|
|
43
|
+
async getChunks(sessionKey) {
|
|
44
|
+
return [...this.tasks.get(sessionKey)?.chunks ?? []];
|
|
45
|
+
}
|
|
46
|
+
async delete(sessionKey) {
|
|
47
|
+
this.tasks.delete(sessionKey);
|
|
48
|
+
}
|
|
49
|
+
async runningCount() {
|
|
50
|
+
let count = 0;
|
|
51
|
+
for (const record of this.tasks.values()) {
|
|
52
|
+
if (record.snapshot.status === "running") count++;
|
|
53
|
+
}
|
|
54
|
+
return count;
|
|
55
|
+
}
|
|
56
|
+
subscribeChunks(sessionKey, onChunk, onClose) {
|
|
57
|
+
const event = this.chunkEvent(sessionKey);
|
|
58
|
+
this.events.on(event, onChunk);
|
|
59
|
+
let unsubscribeClose;
|
|
60
|
+
if (onClose) {
|
|
61
|
+
const closeEvent = this.closeEvent(sessionKey);
|
|
62
|
+
const closeListener = (status, errorMessage) => onClose(status, errorMessage);
|
|
63
|
+
this.events.on(closeEvent, closeListener);
|
|
64
|
+
unsubscribeClose = () => this.events.off(closeEvent, closeListener);
|
|
65
|
+
}
|
|
66
|
+
return () => {
|
|
67
|
+
this.events.off(event, onChunk);
|
|
68
|
+
unsubscribeClose?.();
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
async publishAbort(sessionKey, reason) {
|
|
72
|
+
this.events.emit("abort", sessionKey, reason);
|
|
73
|
+
}
|
|
74
|
+
subscribeAbort(onAbort) {
|
|
75
|
+
this.events.on("abort", onAbort);
|
|
76
|
+
return () => this.events.off("abort", onAbort);
|
|
77
|
+
}
|
|
78
|
+
/** 单进程不存在跨实例租约,保留完整接口供多副本后端实现。 */
|
|
79
|
+
// 无参实现即可满足可选接口方法签名(TS 兼容少参方法);单机无租约语义
|
|
80
|
+
async refreshLease() {
|
|
81
|
+
}
|
|
82
|
+
/** 单进程 owner 与任务同生命周期,无跨副本孤儿可扫。 */
|
|
83
|
+
async sweepOrphans() {
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
chunkEvent(sessionKey) {
|
|
87
|
+
return `chunk:${sessionKey}`;
|
|
88
|
+
}
|
|
89
|
+
closeEvent(sessionKey) {
|
|
90
|
+
return `close:${sessionKey}`;
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// src/stream/fileTaskStore.ts
|
|
95
|
+
import { EventEmitter as EventEmitter2 } from "events";
|
|
96
|
+
import { randomUUID } from "crypto";
|
|
97
|
+
import fs from "fs/promises";
|
|
98
|
+
import path from "path";
|
|
99
|
+
var TERMINAL_RETENTION_MS = 3e4;
|
|
100
|
+
var PROCESS_RESTART_ERROR_MESSAGE = "process_restart";
|
|
101
|
+
var FileTaskStore = class {
|
|
102
|
+
dir;
|
|
103
|
+
tasks = /* @__PURE__ */ new Map();
|
|
104
|
+
cleanupTimers = /* @__PURE__ */ new Map();
|
|
105
|
+
/** 同 key 的文件写入排队尾部:append 与元数据 rename 不得交错 */
|
|
106
|
+
writeQueues = /* @__PURE__ */ new Map();
|
|
107
|
+
events = new EventEmitter2();
|
|
108
|
+
loading;
|
|
109
|
+
constructor(opts) {
|
|
110
|
+
this.dir = path.resolve(opts.dir);
|
|
111
|
+
this.events.setMaxListeners(0);
|
|
112
|
+
}
|
|
113
|
+
async create(snapshot) {
|
|
114
|
+
await this.ensureLoaded();
|
|
115
|
+
this.clearCleanup(snapshot.sessionKey);
|
|
116
|
+
const record = { snapshot: { ...snapshot }, chunks: [] };
|
|
117
|
+
this.tasks.set(snapshot.sessionKey, record);
|
|
118
|
+
await fs.mkdir(this.dir, { recursive: true });
|
|
119
|
+
await this.enqueueWrite(snapshot.sessionKey, () => this.persist(record));
|
|
120
|
+
}
|
|
121
|
+
async appendChunk(sessionKey, chunk) {
|
|
122
|
+
await this.ensureLoaded();
|
|
123
|
+
const record = this.tasks.get(sessionKey);
|
|
124
|
+
if (!record) return;
|
|
125
|
+
await fs.mkdir(this.dir, { recursive: true });
|
|
126
|
+
await this.enqueueWrite(sessionKey, async () => {
|
|
127
|
+
if (this.tasks.get(sessionKey) !== record) return;
|
|
128
|
+
await fs.appendFile(this.filePath(sessionKey), `${Buffer.from(chunk).toString("base64")}
|
|
129
|
+
`);
|
|
130
|
+
record.chunks.push(chunk);
|
|
131
|
+
this.events.emit(this.chunkEvent(sessionKey), chunk, record.chunks.length);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
async setStatus(sessionKey, status, errorMessage) {
|
|
135
|
+
await this.ensureLoaded();
|
|
136
|
+
const record = this.tasks.get(sessionKey);
|
|
137
|
+
if (!record) return;
|
|
138
|
+
const previous = record.snapshot.status;
|
|
139
|
+
record.snapshot = {
|
|
140
|
+
...record.snapshot,
|
|
141
|
+
status,
|
|
142
|
+
updatedAt: Date.now(),
|
|
143
|
+
...errorMessage === void 0 ? {} : { errorMessage }
|
|
144
|
+
};
|
|
145
|
+
await this.enqueueWrite(sessionKey, async () => {
|
|
146
|
+
if (this.tasks.get(sessionKey) !== record) return;
|
|
147
|
+
await this.persist(record);
|
|
148
|
+
});
|
|
149
|
+
if (status !== "running" && previous === "running") {
|
|
150
|
+
this.events.emit(this.closeEvent(sessionKey), status, errorMessage);
|
|
151
|
+
}
|
|
152
|
+
if (status !== "running") this.scheduleCleanup(sessionKey);
|
|
153
|
+
}
|
|
154
|
+
async get(sessionKey) {
|
|
155
|
+
await this.ensureLoaded();
|
|
156
|
+
const snapshot = this.tasks.get(sessionKey)?.snapshot;
|
|
157
|
+
return snapshot ? { ...snapshot } : void 0;
|
|
158
|
+
}
|
|
159
|
+
async getChunks(sessionKey) {
|
|
160
|
+
await this.ensureLoaded();
|
|
161
|
+
return [...this.tasks.get(sessionKey)?.chunks ?? []];
|
|
162
|
+
}
|
|
163
|
+
async delete(sessionKey) {
|
|
164
|
+
await this.ensureLoaded();
|
|
165
|
+
this.clearCleanup(sessionKey);
|
|
166
|
+
this.tasks.delete(sessionKey);
|
|
167
|
+
await this.enqueueWrite(sessionKey, () => fs.rm(this.filePath(sessionKey), { force: true }));
|
|
168
|
+
}
|
|
169
|
+
async runningCount() {
|
|
170
|
+
await this.ensureLoaded();
|
|
171
|
+
let count = 0;
|
|
172
|
+
for (const record of this.tasks.values()) {
|
|
173
|
+
if (record.snapshot.status === "running") count++;
|
|
174
|
+
}
|
|
175
|
+
return count;
|
|
176
|
+
}
|
|
177
|
+
subscribeChunks(sessionKey, onChunk, onClose) {
|
|
178
|
+
const event = this.chunkEvent(sessionKey);
|
|
179
|
+
this.events.on(event, onChunk);
|
|
180
|
+
let unsubscribeClose;
|
|
181
|
+
if (onClose) {
|
|
182
|
+
const closeEvent = this.closeEvent(sessionKey);
|
|
183
|
+
const closeListener = (status, errorMessage) => onClose(status, errorMessage);
|
|
184
|
+
this.events.on(closeEvent, closeListener);
|
|
185
|
+
unsubscribeClose = () => this.events.off(closeEvent, closeListener);
|
|
186
|
+
}
|
|
187
|
+
return () => {
|
|
188
|
+
this.events.off(event, onChunk);
|
|
189
|
+
unsubscribeClose?.();
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
async publishAbort(sessionKey, reason) {
|
|
193
|
+
this.events.emit("abort", sessionKey, reason);
|
|
194
|
+
}
|
|
195
|
+
subscribeAbort(onAbort) {
|
|
196
|
+
this.events.on("abort", onAbort);
|
|
197
|
+
return () => this.events.off("abort", onAbort);
|
|
198
|
+
}
|
|
199
|
+
/** 单进程文件后端不需要分布式租约。 */
|
|
200
|
+
// 无参实现即可满足可选接口方法签名(TS 兼容少参方法);单机无租约语义
|
|
201
|
+
async refreshLease() {
|
|
202
|
+
}
|
|
203
|
+
/** 文件后端不跨副本,running 恢复已在加载时转为 process_restart。 */
|
|
204
|
+
async sweepOrphans() {
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
ensureLoaded() {
|
|
208
|
+
this.loading ??= this.restore();
|
|
209
|
+
return this.loading;
|
|
210
|
+
}
|
|
211
|
+
/** 同 key 的文件写入排队执行:旧任务的 append 不会与新任务的 rename/rm 交错。 */
|
|
212
|
+
enqueueWrite(sessionKey, write) {
|
|
213
|
+
const previous = this.writeQueues.get(sessionKey) ?? Promise.resolve();
|
|
214
|
+
const run = previous.then(write, write);
|
|
215
|
+
const tail = run.then(
|
|
216
|
+
() => void 0,
|
|
217
|
+
() => void 0
|
|
218
|
+
);
|
|
219
|
+
this.writeQueues.set(sessionKey, tail);
|
|
220
|
+
void tail.then(() => {
|
|
221
|
+
if (this.writeQueues.get(sessionKey) === tail) this.writeQueues.delete(sessionKey);
|
|
222
|
+
});
|
|
223
|
+
return run;
|
|
224
|
+
}
|
|
225
|
+
/** 懒恢复:completed/error 可重放;异常退出遗留的 running 不得伪装为仍在运行。 */
|
|
226
|
+
async restore() {
|
|
227
|
+
let files;
|
|
228
|
+
try {
|
|
229
|
+
files = await fs.readdir(this.dir);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (error.code === "ENOENT") return;
|
|
232
|
+
throw error;
|
|
233
|
+
}
|
|
234
|
+
for (const file of files) {
|
|
235
|
+
if (!file.endsWith(".ndjson")) continue;
|
|
236
|
+
const filePath = path.join(this.dir, file);
|
|
237
|
+
try {
|
|
238
|
+
const content = await fs.readFile(filePath, "utf8");
|
|
239
|
+
const terminated = content.endsWith("\n") ? content : content.slice(0, content.lastIndexOf("\n") + 1);
|
|
240
|
+
const lines = terminated.split("\n");
|
|
241
|
+
const snapshot = JSON.parse(lines[0]);
|
|
242
|
+
if (!snapshot.sessionKey || snapshot.ownerInstanceId === void 0) continue;
|
|
243
|
+
const record = {
|
|
244
|
+
snapshot,
|
|
245
|
+
chunks: lines.slice(1).flatMap((line) => {
|
|
246
|
+
if (line.length === 0) return [];
|
|
247
|
+
const decoded = Buffer.from(line, "base64");
|
|
248
|
+
return decoded.toString("base64") === line ? [new Uint8Array(decoded)] : [];
|
|
249
|
+
})
|
|
250
|
+
};
|
|
251
|
+
if (snapshot.status === "running") {
|
|
252
|
+
record.snapshot = {
|
|
253
|
+
...snapshot,
|
|
254
|
+
status: "error",
|
|
255
|
+
errorMessage: PROCESS_RESTART_ERROR_MESSAGE,
|
|
256
|
+
updatedAt: Date.now()
|
|
257
|
+
};
|
|
258
|
+
await this.persist(record);
|
|
259
|
+
}
|
|
260
|
+
this.tasks.set(snapshot.sessionKey, record);
|
|
261
|
+
if (record.snapshot.status !== "running") {
|
|
262
|
+
this.scheduleCleanup(snapshot.sessionKey);
|
|
263
|
+
}
|
|
264
|
+
} catch {
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
/** 原子重写元数据与既有分块,避免状态更新崩溃留下半行首行。 */
|
|
269
|
+
async persist(record) {
|
|
270
|
+
const filePath = this.filePath(record.snapshot.sessionKey);
|
|
271
|
+
const tempPath = `${filePath}.${randomUUID()}.tmp`;
|
|
272
|
+
const lines = [
|
|
273
|
+
JSON.stringify(record.snapshot),
|
|
274
|
+
...record.chunks.map((chunk) => Buffer.from(chunk).toString("base64"))
|
|
275
|
+
];
|
|
276
|
+
await fs.writeFile(tempPath, `${lines.join("\n")}
|
|
277
|
+
`, "utf8");
|
|
278
|
+
await fs.rename(tempPath, filePath);
|
|
279
|
+
}
|
|
280
|
+
scheduleCleanup(sessionKey) {
|
|
281
|
+
this.clearCleanup(sessionKey);
|
|
282
|
+
const snapshot = this.tasks.get(sessionKey)?.snapshot;
|
|
283
|
+
if (!snapshot) return;
|
|
284
|
+
const remaining = Math.max(
|
|
285
|
+
0,
|
|
286
|
+
TERMINAL_RETENTION_MS - (Date.now() - snapshot.updatedAt)
|
|
287
|
+
);
|
|
288
|
+
const timer = setTimeout(
|
|
289
|
+
() => this.delete(sessionKey).catch(() => {
|
|
290
|
+
}),
|
|
291
|
+
remaining
|
|
292
|
+
);
|
|
293
|
+
this.cleanupTimers.set(sessionKey, timer);
|
|
294
|
+
const unref = timer;
|
|
295
|
+
if (typeof unref === "object" && unref !== null && typeof unref.unref === "function") {
|
|
296
|
+
unref.unref();
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
clearCleanup(sessionKey) {
|
|
300
|
+
const timer = this.cleanupTimers.get(sessionKey);
|
|
301
|
+
if (timer) clearTimeout(timer);
|
|
302
|
+
this.cleanupTimers.delete(sessionKey);
|
|
303
|
+
}
|
|
304
|
+
filePath(sessionKey) {
|
|
305
|
+
return path.join(this.dir, `${encodeURIComponent(sessionKey)}.ndjson`);
|
|
306
|
+
}
|
|
307
|
+
chunkEvent(sessionKey) {
|
|
308
|
+
return `chunk:${sessionKey}`;
|
|
309
|
+
}
|
|
310
|
+
closeEvent(sessionKey) {
|
|
311
|
+
return `close:${sessionKey}`;
|
|
312
|
+
}
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
// src/stream/streamHub.ts
|
|
316
|
+
import { hostname } from "os";
|
|
317
|
+
var DEFAULT_TENANT_ID = "anon";
|
|
318
|
+
function sessionStorageKey(sessionId, tenantId) {
|
|
319
|
+
return `${tenantId ?? DEFAULT_TENANT_ID}:${sessionId}`;
|
|
320
|
+
}
|
|
321
|
+
var TASK_TIMEOUT_MIN_MS = 3e4;
|
|
322
|
+
var TASK_TIMEOUT_MAX_MS = 36e5;
|
|
323
|
+
var TASK_TIMEOUT_DEFAULT_MS = 6e5;
|
|
324
|
+
var TERMINAL_RETENTION_MS2 = 3e4;
|
|
325
|
+
var LEASE_TTL_DEFAULT_MS = 15e3;
|
|
326
|
+
var SWEEP_INTERVAL_DEFAULT_MS = 3e4;
|
|
327
|
+
var SessionStreamHub = class {
|
|
328
|
+
/** 仅 owner 侧进程内运行时对象;任务状态与 chunks 不在此镜像。 */
|
|
329
|
+
tasks = /* @__PURE__ */ new Map();
|
|
330
|
+
/** 同 sessionKey 关键区操作(注册/中止)的串行队列尾部 */
|
|
331
|
+
keyOperations = /* @__PURE__ */ new Map();
|
|
332
|
+
taskTimeoutMs;
|
|
333
|
+
sink;
|
|
334
|
+
store;
|
|
335
|
+
instanceId;
|
|
336
|
+
leaseTtlMs;
|
|
337
|
+
leaseRefreshIntervalMs;
|
|
338
|
+
sweepIntervalMs;
|
|
339
|
+
/** 孤儿清扫器的永续定时器(带抖动递归,unref 不阻塞退出) */
|
|
340
|
+
sweepTimer;
|
|
341
|
+
constructor(opts = {}) {
|
|
342
|
+
this.sink = opts.sink ?? createConsoleSink();
|
|
343
|
+
this.store = opts.store ?? new InMemoryTaskStore();
|
|
344
|
+
this.instanceId = opts.instanceId ?? `${hostname()}:${process.pid}`;
|
|
345
|
+
const envMs = Number(process.env.LLM_TASK_TIMEOUT_MS);
|
|
346
|
+
const envValid = Number.isFinite(envMs) && envMs > 0;
|
|
347
|
+
this.taskTimeoutMs = Math.min(
|
|
348
|
+
Math.max(
|
|
349
|
+
opts.taskTimeoutMs ?? (envValid ? envMs : TASK_TIMEOUT_DEFAULT_MS),
|
|
350
|
+
TASK_TIMEOUT_MIN_MS
|
|
351
|
+
),
|
|
352
|
+
TASK_TIMEOUT_MAX_MS
|
|
353
|
+
);
|
|
354
|
+
this.leaseTtlMs = Math.max(1e3, opts.leaseTtlMs ?? LEASE_TTL_DEFAULT_MS);
|
|
355
|
+
this.leaseRefreshIntervalMs = Math.max(1e3, Math.floor(this.leaseTtlMs / 3));
|
|
356
|
+
this.sweepIntervalMs = Math.max(1e3, opts.sweepIntervalMs ?? SWEEP_INTERVAL_DEFAULT_MS);
|
|
357
|
+
if (this.store.sweepOrphans && this.store.multiReplica) {
|
|
358
|
+
this.scheduleSweep();
|
|
359
|
+
}
|
|
360
|
+
this.store.subscribeAbort((sessionKey, reason) => {
|
|
361
|
+
const task = this.tasks.get(sessionKey);
|
|
362
|
+
if (!task) return;
|
|
363
|
+
void this.runKeyOperation(sessionKey, () => this.abortOwnedTask(task, reason)).catch(() => {
|
|
364
|
+
});
|
|
365
|
+
});
|
|
366
|
+
}
|
|
367
|
+
/** 清扫周期带 ±20% 抖动:多实例错峰,避免同步扫描风暴。 */
|
|
368
|
+
scheduleSweep() {
|
|
369
|
+
const jitter = this.sweepIntervalMs * 0.2 * (Math.random() * 2 - 1);
|
|
370
|
+
this.sweepTimer = setTimeout(() => {
|
|
371
|
+
void this.runSweep();
|
|
372
|
+
}, Math.max(1e3, this.sweepIntervalMs + jitter));
|
|
373
|
+
this.unrefTimer(this.sweepTimer);
|
|
374
|
+
}
|
|
375
|
+
/**
|
|
376
|
+
* 执行一轮孤儿回收(供测试与运维调用;定时清扫器亦复用此路径)。
|
|
377
|
+
* 返回本次回收的 sessionKey 列表。
|
|
378
|
+
*/
|
|
379
|
+
async sweepOnce() {
|
|
380
|
+
try {
|
|
381
|
+
const reclaimed = await this.store.sweepOrphans?.(async (ownerInstanceId, sessionKey) => {
|
|
382
|
+
if (ownerInstanceId === this.instanceId) return this.tasks.has(sessionKey);
|
|
383
|
+
return false;
|
|
384
|
+
}) ?? [];
|
|
385
|
+
for (const sessionKey of reclaimed) {
|
|
386
|
+
this.sink.emit({ type: "abort", sessionId: sessionKey, reason: "timeout" });
|
|
387
|
+
}
|
|
388
|
+
return reclaimed;
|
|
389
|
+
} catch {
|
|
390
|
+
return [];
|
|
391
|
+
} finally {
|
|
392
|
+
this.scheduleSweep();
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
async runSweep() {
|
|
396
|
+
await this.sweepOnce();
|
|
397
|
+
}
|
|
398
|
+
async hasRunningTask(sessionId, tenantId) {
|
|
399
|
+
const snapshot = await this.store.get(sessionStorageKey(sessionId, tenantId));
|
|
400
|
+
return snapshot?.status === "running";
|
|
401
|
+
}
|
|
402
|
+
async hasTask(sessionId, tenantId) {
|
|
403
|
+
return await this.store.get(sessionStorageKey(sessionId, tenantId)) !== void 0;
|
|
404
|
+
}
|
|
405
|
+
async getTask(sessionId, tenantId) {
|
|
406
|
+
const sessionKey = sessionStorageKey(sessionId, tenantId);
|
|
407
|
+
const snapshot = await this.store.get(sessionKey);
|
|
408
|
+
if (!snapshot) return void 0;
|
|
409
|
+
return {
|
|
410
|
+
...snapshot,
|
|
411
|
+
sessionId,
|
|
412
|
+
chunks: await this.store.getChunks(sessionKey)
|
|
413
|
+
};
|
|
414
|
+
}
|
|
415
|
+
/** 当前 running 状态的任务数(并发准入的计数来源,多副本后端可给全局值) */
|
|
416
|
+
async runningCount() {
|
|
417
|
+
return this.store.runningCount();
|
|
418
|
+
}
|
|
419
|
+
async abortTask(sessionId, reason = "user", tenantId) {
|
|
420
|
+
const sessionKey = sessionStorageKey(sessionId, tenantId);
|
|
421
|
+
return this.runKeyOperation(sessionKey, async () => {
|
|
422
|
+
const snapshot = await this.store.get(sessionKey);
|
|
423
|
+
if (!snapshot) return false;
|
|
424
|
+
const task = this.tasks.get(sessionKey);
|
|
425
|
+
if (task) {
|
|
426
|
+
await this.abortOwnedTask(task, reason);
|
|
427
|
+
await task.readerDone;
|
|
428
|
+
}
|
|
429
|
+
await this.store.publishAbort(sessionKey, reason);
|
|
430
|
+
return true;
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
/** 为当前任务创建 HTTP 响应流:重放历史分块,running 任务再续接 live 分块。 */
|
|
434
|
+
async createResponse(sessionId, tenantId) {
|
|
435
|
+
const sessionKey = sessionStorageKey(sessionId, tenantId);
|
|
436
|
+
const snapshot = await this.store.get(sessionKey);
|
|
437
|
+
if (!snapshot) return null;
|
|
438
|
+
const ownedTask = this.tasks.get(sessionKey);
|
|
439
|
+
const recoveredFromRestart = snapshot.status === "error" && snapshot.errorMessage === PROCESS_RESTART_ERROR_MESSAGE;
|
|
440
|
+
let subscriber = null;
|
|
441
|
+
let unsubscribeChunks;
|
|
442
|
+
let errorReplayIndex = 0;
|
|
443
|
+
let chunks = [];
|
|
444
|
+
let replayLength = 0;
|
|
445
|
+
let liveStarted = false;
|
|
446
|
+
let pendingClose;
|
|
447
|
+
const liveBuffer = [];
|
|
448
|
+
let controllerRef = null;
|
|
449
|
+
const enqueueLive = (chunk) => {
|
|
450
|
+
if (!controllerRef) return;
|
|
451
|
+
try {
|
|
452
|
+
controllerRef.enqueue(chunk);
|
|
453
|
+
} catch {
|
|
454
|
+
unsubscribeChunks?.();
|
|
455
|
+
unsubscribeChunks = void 0;
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
const applyClose = () => {
|
|
459
|
+
const close = pendingClose;
|
|
460
|
+
pendingClose = void 0;
|
|
461
|
+
if (!close || !controllerRef) return;
|
|
462
|
+
unsubscribeChunks?.();
|
|
463
|
+
unsubscribeChunks = void 0;
|
|
464
|
+
try {
|
|
465
|
+
if (close.status === "completed") controllerRef.close();
|
|
466
|
+
else controllerRef.error(new Error(close.errorMessage ?? "Stream error"));
|
|
467
|
+
} catch {
|
|
468
|
+
}
|
|
469
|
+
};
|
|
470
|
+
if (snapshot.status === "running" && !ownedTask) {
|
|
471
|
+
unsubscribeChunks = this.store.subscribeChunks(
|
|
472
|
+
sessionKey,
|
|
473
|
+
(chunk, seq) => {
|
|
474
|
+
if (!liveStarted) {
|
|
475
|
+
liveBuffer.push({ chunk, seq });
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
enqueueLive(chunk);
|
|
479
|
+
},
|
|
480
|
+
(status, errorMessage) => {
|
|
481
|
+
pendingClose = { status, errorMessage };
|
|
482
|
+
if (liveStarted) applyClose();
|
|
483
|
+
}
|
|
484
|
+
);
|
|
485
|
+
chunks = await this.store.getChunks(sessionKey);
|
|
486
|
+
replayLength = chunks.length;
|
|
487
|
+
} else {
|
|
488
|
+
chunks = await this.store.getChunks(sessionKey);
|
|
489
|
+
}
|
|
490
|
+
const stream = new ReadableStream({
|
|
491
|
+
start: (controller) => {
|
|
492
|
+
if (snapshot.status === "error" && !recoveredFromRestart) {
|
|
493
|
+
for (const chunk of chunks) controller.enqueue(chunk);
|
|
494
|
+
controller.error(new Error(snapshot.errorMessage ?? "Stream terminated"));
|
|
495
|
+
return;
|
|
496
|
+
}
|
|
497
|
+
if (recoveredFromRestart) {
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
for (const chunk of chunks) controller.enqueue(chunk);
|
|
501
|
+
if (snapshot.status === "completed") {
|
|
502
|
+
controller.close();
|
|
503
|
+
return;
|
|
504
|
+
}
|
|
505
|
+
if (ownedTask) {
|
|
506
|
+
subscriber = { controller };
|
|
507
|
+
ownedTask.subscribers.add(subscriber);
|
|
508
|
+
} else {
|
|
509
|
+
controllerRef = controller;
|
|
510
|
+
liveStarted = true;
|
|
511
|
+
for (const buffered of liveBuffer.splice(0)) {
|
|
512
|
+
if (buffered.seq <= replayLength) continue;
|
|
513
|
+
enqueueLive(buffered.chunk);
|
|
514
|
+
}
|
|
515
|
+
if (pendingClose) {
|
|
516
|
+
applyClose();
|
|
517
|
+
} else {
|
|
518
|
+
void this.store.get(sessionKey).then((fresh) => {
|
|
519
|
+
if (fresh && fresh.status !== "running" && controllerRef) {
|
|
520
|
+
pendingClose = { status: fresh.status, errorMessage: fresh.errorMessage };
|
|
521
|
+
applyClose();
|
|
522
|
+
}
|
|
523
|
+
}).catch(() => {
|
|
524
|
+
});
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
},
|
|
528
|
+
pull: (controller) => {
|
|
529
|
+
if (!recoveredFromRestart) return;
|
|
530
|
+
if (errorReplayIndex < chunks.length) {
|
|
531
|
+
controller.enqueue(chunks[errorReplayIndex++]);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
controller.error(new Error(snapshot.errorMessage ?? "Stream terminated"));
|
|
535
|
+
},
|
|
536
|
+
cancel: () => {
|
|
537
|
+
if (subscriber && ownedTask) ownedTask.subscribers.delete(subscriber);
|
|
538
|
+
unsubscribeChunks?.();
|
|
539
|
+
}
|
|
540
|
+
});
|
|
541
|
+
return new Response(stream, {
|
|
542
|
+
status: 200,
|
|
543
|
+
headers: {
|
|
544
|
+
"Content-Type": "text/plain; charset=utf-8",
|
|
545
|
+
"x-vercel-ai-data-stream": "v1"
|
|
546
|
+
}
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* 注册原始流并启动 owner 侧后台 Reader。meta.abortController 与 handler 的 streamText
|
|
551
|
+
* 共用,使用户停止/看门狗超时可真正取消 provider 生成。
|
|
552
|
+
*/
|
|
553
|
+
async registerAndConsume(sessionId, rawResponse, meta) {
|
|
554
|
+
const tenantId = meta?.tenantId ?? DEFAULT_TENANT_ID;
|
|
555
|
+
const sessionKey = sessionStorageKey(sessionId, tenantId);
|
|
556
|
+
return this.runKeyOperation(sessionKey, async () => {
|
|
557
|
+
const previous = this.tasks.get(sessionKey);
|
|
558
|
+
const snapshot = await this.store.get(sessionKey);
|
|
559
|
+
if (snapshot?.status === "running") {
|
|
560
|
+
if (previous) {
|
|
561
|
+
await this.abortOwnedTask(previous, "new_task");
|
|
562
|
+
await previous.readerDone;
|
|
563
|
+
}
|
|
564
|
+
await this.store.publishAbort(sessionKey, "new_task");
|
|
565
|
+
}
|
|
566
|
+
const now = Date.now();
|
|
567
|
+
await this.store.create({
|
|
568
|
+
sessionKey,
|
|
569
|
+
runId: meta?.runId,
|
|
570
|
+
ownerInstanceId: this.instanceId,
|
|
571
|
+
status: "running",
|
|
572
|
+
createdAt: now,
|
|
573
|
+
updatedAt: now
|
|
574
|
+
});
|
|
575
|
+
const task = {
|
|
576
|
+
sessionKey,
|
|
577
|
+
sessionId,
|
|
578
|
+
runId: meta?.runId,
|
|
579
|
+
subscribers: /* @__PURE__ */ new Set(),
|
|
580
|
+
abortController: meta?.abortController ?? new AbortController()
|
|
581
|
+
};
|
|
582
|
+
this.tasks.set(sessionKey, task);
|
|
583
|
+
task.deadlineTimer = setTimeout(() => {
|
|
584
|
+
void this.abortTask(sessionId, "timeout", tenantId).catch(() => {
|
|
585
|
+
});
|
|
586
|
+
}, this.taskTimeoutMs);
|
|
587
|
+
this.unrefTimer(task.deadlineTimer);
|
|
588
|
+
if (this.store.refreshLease) {
|
|
589
|
+
void this.store.refreshLease(sessionKey, this.instanceId, this.leaseTtlMs).catch(() => {
|
|
590
|
+
});
|
|
591
|
+
task.leaseTimer = setInterval(() => {
|
|
592
|
+
void this.store.refreshLease?.(sessionKey, this.instanceId, this.leaseTtlMs).catch(() => {
|
|
593
|
+
});
|
|
594
|
+
}, this.leaseRefreshIntervalMs);
|
|
595
|
+
this.unrefTimer(task.leaseTimer);
|
|
596
|
+
}
|
|
597
|
+
const response = await this.createResponse(sessionId, tenantId);
|
|
598
|
+
task.readerDone = this.consumeUpstream(rawResponse, task);
|
|
599
|
+
return response;
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* 同 sessionKey 的关键区操作(注册/中止)串行执行,防止并发 create/abort 交错覆盖。
|
|
604
|
+
*/
|
|
605
|
+
runKeyOperation(sessionKey, operation) {
|
|
606
|
+
const previous = this.keyOperations.get(sessionKey) ?? Promise.resolve();
|
|
607
|
+
const run = previous.then(operation, operation);
|
|
608
|
+
const tail = run.then(
|
|
609
|
+
() => void 0,
|
|
610
|
+
() => void 0
|
|
611
|
+
);
|
|
612
|
+
this.keyOperations.set(sessionKey, tail);
|
|
613
|
+
void tail.then(() => {
|
|
614
|
+
if (this.keyOperations.get(sessionKey) === tail) this.keyOperations.delete(sessionKey);
|
|
615
|
+
});
|
|
616
|
+
return run;
|
|
617
|
+
}
|
|
618
|
+
/**
|
|
619
|
+
* owner 侧后台消费循环:读取上游、先持久化再广播给订阅者。
|
|
620
|
+
* 返回的 Promise 永不 reject:既作为替换/中止前等待收尾的句柄,
|
|
621
|
+
* 也兜底任何残余异常,保证不产生 unhandled rejection。
|
|
622
|
+
*/
|
|
623
|
+
consumeUpstream(rawResponse, task) {
|
|
624
|
+
const { sessionKey, sessionId } = task;
|
|
625
|
+
const consumption = (async () => {
|
|
626
|
+
const reader = rawResponse.body?.getReader();
|
|
627
|
+
if (!reader) {
|
|
628
|
+
const error = new Error("Upstream response has no body");
|
|
629
|
+
await this.setStatusBestEffort(task, "error", error.message);
|
|
630
|
+
this.sink.emit({
|
|
631
|
+
type: "error",
|
|
632
|
+
runId: task.runId,
|
|
633
|
+
sessionId,
|
|
634
|
+
code: "STREAM_BODY_UNREADABLE",
|
|
635
|
+
detail: "rawResponse.body is not readable; terminating task"
|
|
636
|
+
});
|
|
637
|
+
this.clearTimers(task);
|
|
638
|
+
this.closeSubscribers(task, "error", error);
|
|
639
|
+
this.scheduleCleanup(task);
|
|
640
|
+
return;
|
|
641
|
+
}
|
|
642
|
+
task.cancelUpstream = async () => {
|
|
643
|
+
await reader.cancel().catch(() => {
|
|
644
|
+
});
|
|
645
|
+
};
|
|
646
|
+
let terminalStatus = "running";
|
|
647
|
+
let terminalError;
|
|
648
|
+
try {
|
|
649
|
+
while (true) {
|
|
650
|
+
if (task.abortController.signal.aborted) {
|
|
651
|
+
await task.cancelUpstream();
|
|
652
|
+
terminalStatus = "error";
|
|
653
|
+
const abortError = new Error("Stream aborted");
|
|
654
|
+
terminalError = abortError;
|
|
655
|
+
await this.setStatusBestEffort(task, "error", abortError.message);
|
|
656
|
+
break;
|
|
657
|
+
}
|
|
658
|
+
const { done, value } = await reader.read();
|
|
659
|
+
if (task.abortController.signal.aborted) {
|
|
660
|
+
terminalStatus = "error";
|
|
661
|
+
const abortError = new Error("Stream aborted");
|
|
662
|
+
terminalError = abortError;
|
|
663
|
+
await this.setStatusBestEffort(task, "error", abortError.message);
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
if (done) {
|
|
667
|
+
terminalStatus = "completed";
|
|
668
|
+
await this.setStatusBestEffort(task, "completed");
|
|
669
|
+
break;
|
|
670
|
+
}
|
|
671
|
+
if (value) {
|
|
672
|
+
await this.store.appendChunk(sessionKey, value);
|
|
673
|
+
for (const subscriber of [...task.subscribers]) {
|
|
674
|
+
try {
|
|
675
|
+
subscriber.controller.enqueue(value);
|
|
676
|
+
} catch {
|
|
677
|
+
task.subscribers.delete(subscriber);
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
} catch (error) {
|
|
683
|
+
terminalStatus = "error";
|
|
684
|
+
terminalError = error;
|
|
685
|
+
await this.setStatusBestEffort(
|
|
686
|
+
task,
|
|
687
|
+
"error",
|
|
688
|
+
error instanceof Error ? error.message : String(error)
|
|
689
|
+
);
|
|
690
|
+
this.sink.emit({
|
|
691
|
+
type: "error",
|
|
692
|
+
runId: task.runId,
|
|
693
|
+
sessionId,
|
|
694
|
+
code: "READER_ERROR",
|
|
695
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
696
|
+
});
|
|
697
|
+
} finally {
|
|
698
|
+
this.clearTimers(task);
|
|
699
|
+
this.closeSubscribers(task, terminalStatus, terminalError);
|
|
700
|
+
this.scheduleCleanup(task);
|
|
701
|
+
}
|
|
702
|
+
})();
|
|
703
|
+
return consumption.then(
|
|
704
|
+
() => void 0,
|
|
705
|
+
() => void 0
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
/** 终态持久化 best-effort:写入失败只记遥测,不得阻断定时器/订阅者/错误遥测的收尾。 */
|
|
709
|
+
async setStatusBestEffort(task, status, errorMessage) {
|
|
710
|
+
try {
|
|
711
|
+
await this.store.setStatus(task.sessionKey, status, errorMessage);
|
|
712
|
+
} catch (error) {
|
|
713
|
+
this.sink.emit({
|
|
714
|
+
type: "error",
|
|
715
|
+
runId: task.runId,
|
|
716
|
+
sessionId: task.sessionId,
|
|
717
|
+
code: "TASK_STATUS_PERSIST_FAILED",
|
|
718
|
+
detail: error instanceof Error ? error.message : String(error)
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
async abortOwnedTask(task, reason) {
|
|
723
|
+
if (task.abortController.signal.aborted) return;
|
|
724
|
+
this.clearTimers(task);
|
|
725
|
+
this.sink.emit({
|
|
726
|
+
type: "abort",
|
|
727
|
+
runId: task.runId,
|
|
728
|
+
sessionId: task.sessionId,
|
|
729
|
+
reason
|
|
730
|
+
});
|
|
731
|
+
task.abortController.abort();
|
|
732
|
+
void task.cancelUpstream?.().catch(() => {
|
|
733
|
+
});
|
|
734
|
+
const error = new Error("Stream error");
|
|
735
|
+
this.closeSubscribers(task, "error", error);
|
|
736
|
+
this.tasks.delete(task.sessionKey);
|
|
737
|
+
await this.store.setStatus(task.sessionKey, "error", reason);
|
|
738
|
+
await this.store.delete(task.sessionKey);
|
|
739
|
+
}
|
|
740
|
+
clearTimers(task) {
|
|
741
|
+
if (task.deadlineTimer) {
|
|
742
|
+
clearTimeout(task.deadlineTimer);
|
|
743
|
+
task.deadlineTimer = void 0;
|
|
744
|
+
}
|
|
745
|
+
if (task.leaseTimer) {
|
|
746
|
+
clearInterval(task.leaseTimer);
|
|
747
|
+
task.leaseTimer = void 0;
|
|
748
|
+
}
|
|
749
|
+
}
|
|
750
|
+
/** owner 运行时对象与共享记录均在终态保留 30 秒,供刷新页面做最后重放。 */
|
|
751
|
+
scheduleCleanup(task) {
|
|
752
|
+
const timer = setTimeout(() => {
|
|
753
|
+
if (this.tasks.get(task.sessionKey) !== task) return;
|
|
754
|
+
this.tasks.delete(task.sessionKey);
|
|
755
|
+
void this.store.delete(task.sessionKey).catch(() => {
|
|
756
|
+
});
|
|
757
|
+
}, TERMINAL_RETENTION_MS2);
|
|
758
|
+
this.unrefTimer(timer);
|
|
759
|
+
}
|
|
760
|
+
closeSubscribers(task, status, error) {
|
|
761
|
+
for (const subscriber of task.subscribers) {
|
|
762
|
+
try {
|
|
763
|
+
if (status === "completed") {
|
|
764
|
+
subscriber.controller.close();
|
|
765
|
+
} else if (status === "error") {
|
|
766
|
+
subscriber.controller.error(error ?? new Error("Stream error"));
|
|
767
|
+
}
|
|
768
|
+
} catch {
|
|
769
|
+
}
|
|
770
|
+
}
|
|
771
|
+
task.subscribers.clear();
|
|
772
|
+
}
|
|
773
|
+
unrefTimer(timer) {
|
|
774
|
+
const candidate = timer;
|
|
775
|
+
if (typeof candidate === "object" && candidate !== null && typeof candidate.unref === "function") {
|
|
776
|
+
candidate.unref();
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
};
|
|
780
|
+
var defaultStreamHub = new SessionStreamHub();
|
|
781
|
+
|
|
782
|
+
export {
|
|
783
|
+
InMemoryTaskStore,
|
|
784
|
+
PROCESS_RESTART_ERROR_MESSAGE,
|
|
785
|
+
FileTaskStore,
|
|
786
|
+
DEFAULT_TENANT_ID,
|
|
787
|
+
sessionStorageKey,
|
|
788
|
+
SessionStreamHub,
|
|
789
|
+
defaultStreamHub
|
|
790
|
+
};
|