@ginkgolab/harness-core 0.1.0 → 0.1.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/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,66 @@
|
|
|
1
|
+
// src/tokenizer/types.ts
|
|
2
|
+
var DEFAULT_TIKTOKEN_ENCODING = "cl100k_base";
|
|
3
|
+
|
|
4
|
+
// src/tokenizer/tiktoken.ts
|
|
5
|
+
var warnedMissing = false;
|
|
6
|
+
var encoderCache = /* @__PURE__ */ new Map();
|
|
7
|
+
async function createTiktokenEstimator(encoding = DEFAULT_TIKTOKEN_ENCODING, options) {
|
|
8
|
+
try {
|
|
9
|
+
const pkgName = "js-tiktoken";
|
|
10
|
+
const mod = await import(
|
|
11
|
+
/* @vite-ignore */
|
|
12
|
+
pkgName
|
|
13
|
+
);
|
|
14
|
+
if (typeof mod.getEncoding !== "function") {
|
|
15
|
+
throw new Error("js-tiktoken \u683C\u5F0F\u4E0D\u5339\u914D\uFF08\u7F3A\u5C11 getEncoding \u65B9\u6CD5\uFF09");
|
|
16
|
+
}
|
|
17
|
+
let encoder = encoderCache.get(encoding);
|
|
18
|
+
if (!encoder) {
|
|
19
|
+
encoder = mod.getEncoding(encoding);
|
|
20
|
+
encoderCache.set(encoding, encoder);
|
|
21
|
+
}
|
|
22
|
+
return {
|
|
23
|
+
encode: (text) => encoder.encode(text).length
|
|
24
|
+
};
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (!warnedMissing) {
|
|
27
|
+
warnedMissing = true;
|
|
28
|
+
if (options?.onWarnMissing) {
|
|
29
|
+
options.onWarnMissing(error);
|
|
30
|
+
} else {
|
|
31
|
+
console.warn(
|
|
32
|
+
`[tokenizer] Optional peer dependency "js-tiktoken" is not available (${error instanceof Error ? error.message : String(error)}). Falling back to heuristic estimation.`
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return void 0;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/tokenizer/encodingResolver.ts
|
|
41
|
+
function resolveEncodingForModel(model, mappingOrPath) {
|
|
42
|
+
let table;
|
|
43
|
+
if (typeof mappingOrPath === "object" && mappingOrPath !== null) {
|
|
44
|
+
table = mappingOrPath;
|
|
45
|
+
}
|
|
46
|
+
if (!table) {
|
|
47
|
+
return DEFAULT_TIKTOKEN_ENCODING;
|
|
48
|
+
}
|
|
49
|
+
const lower = model.toLowerCase();
|
|
50
|
+
let bestKey;
|
|
51
|
+
for (const key of Object.keys(table)) {
|
|
52
|
+
if (lower.startsWith(key.toLowerCase()) && (bestKey === void 0 || key.length > bestKey.length)) {
|
|
53
|
+
bestKey = key;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (bestKey !== void 0 && typeof table[bestKey] === "string") {
|
|
57
|
+
return table[bestKey];
|
|
58
|
+
}
|
|
59
|
+
return DEFAULT_TIKTOKEN_ENCODING;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export {
|
|
63
|
+
DEFAULT_TIKTOKEN_ENCODING,
|
|
64
|
+
createTiktokenEstimator,
|
|
65
|
+
resolveEncodingForModel
|
|
66
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
2
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
3
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
4
|
+
}) : x)(function(x) {
|
|
5
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
6
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
7
|
+
});
|
|
8
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
9
|
+
try {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
} catch (e) {
|
|
12
|
+
throw mod = 0, e;
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
export {
|
|
17
|
+
__require,
|
|
18
|
+
__commonJS
|
|
19
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// src/telemetry/telemetry.ts
|
|
2
|
+
function createConsoleSink() {
|
|
3
|
+
return {
|
|
4
|
+
emit(event) {
|
|
5
|
+
const line = JSON.stringify(event);
|
|
6
|
+
if (event.type === "error") {
|
|
7
|
+
console.error(line);
|
|
8
|
+
} else {
|
|
9
|
+
console.log(line);
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function compositeSink(...sinks) {
|
|
15
|
+
return {
|
|
16
|
+
emit(event) {
|
|
17
|
+
for (const s of sinks) {
|
|
18
|
+
try {
|
|
19
|
+
s.emit(event);
|
|
20
|
+
} catch {
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function newRunId() {
|
|
27
|
+
return globalThis.crypto.randomUUID();
|
|
28
|
+
}
|
|
29
|
+
function jsonByteSize(value) {
|
|
30
|
+
try {
|
|
31
|
+
return Buffer.byteLength(JSON.stringify(value) ?? "", "utf-8");
|
|
32
|
+
} catch {
|
|
33
|
+
return -1;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export {
|
|
38
|
+
createConsoleSink,
|
|
39
|
+
compositeSink,
|
|
40
|
+
newRunId,
|
|
41
|
+
jsonByteSize
|
|
42
|
+
};
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import {
|
|
2
|
+
zodTool
|
|
3
|
+
} from "./chunk-SCHUPQP4.js";
|
|
4
|
+
|
|
5
|
+
// src/lifecycle/terminationTool.ts
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
var terminationSchema = z.object({
|
|
8
|
+
status: z.enum(["completed", "insufficient_data", "blocked"]).describe(
|
|
9
|
+
"\u4EFB\u52A1\u7EC8\u6001\uFF1Acompleted(\u5DF2\u5B8C\u6210\u5E76\u4EA4\u4ED8\u5B9E\u8D28\u4EA7\u51FA)\u3001insufficient_data(\u7F3A\u5C11\u5173\u952E\u6570\u636E\u6216\u9700\u6F84\u6E05)\u3001blocked(\u5916\u90E8\u963B\u788D\u4E0D\u53EF\u6297\u529B)"
|
|
10
|
+
),
|
|
11
|
+
deliverableSummary: z.string().optional().describe("completed \u72B6\u6001\u4E0B\u5BF9\u6700\u7EC8\u4EA4\u4ED8\u4EA7\u7269\u7684\u603B\u7ED3"),
|
|
12
|
+
summary: z.string().optional().describe("\u7B80\u8981\u7EC8\u6001\u603B\u7ED3\uFF08\u4E0E deliverableSummary \u7B49\u6548\uFF09"),
|
|
13
|
+
missingInformation: z.array(z.string()).optional().describe("insufficient_data \u72B6\u6001\u4E0B\u7F3A\u5931\u7684\u5173\u952E\u4FE1\u606F"),
|
|
14
|
+
blockerReason: z.string().optional().describe("blocked \u72B6\u6001\u4E0B\u7684\u963B\u585E\u539F\u56E0")
|
|
15
|
+
});
|
|
16
|
+
function createTerminationTool(options = {}) {
|
|
17
|
+
const desc = options.description ?? "\u663E\u5F0F\u58F0\u660E\u5F53\u524D\u4EFB\u52A1\u8FBE\u5230\u7EC8\u6001\u3002\u5FC5\u987B\u5728\u5DF2\u5B8C\u6210\u5206\u6790\u5E76\u4EA7\u51FA\u5B9E\u8D28\u5185\u5BB9\uFF0C\u6216\u786E\u8BA4\u6570\u636E\u4E0D\u8DB3\u9700\u6F84\u6E05\u65F6\u8C03\u7528\u3002";
|
|
18
|
+
return zodTool({
|
|
19
|
+
description: desc,
|
|
20
|
+
parameters: terminationSchema,
|
|
21
|
+
execute: async (args) => {
|
|
22
|
+
const summaryText = args.summary ?? args.deliverableSummary;
|
|
23
|
+
const signal = {
|
|
24
|
+
status: args.status,
|
|
25
|
+
deliverableSummary: summaryText,
|
|
26
|
+
missingInformation: args.missingInformation,
|
|
27
|
+
blockerReason: args.blockerReason
|
|
28
|
+
};
|
|
29
|
+
const extraCtx = options.getAssertionContext ? options.getAssertionContext() : {};
|
|
30
|
+
const assertionCtx = {
|
|
31
|
+
status: signal.status,
|
|
32
|
+
signal,
|
|
33
|
+
stepCount: extraCtx.stepCount ?? 0,
|
|
34
|
+
executedTools: extraCtx.executedTools ?? [],
|
|
35
|
+
evidence: extraCtx.evidence
|
|
36
|
+
};
|
|
37
|
+
if (signal.status === "completed" && options.assertion) {
|
|
38
|
+
const checkResult = options.assertion(assertionCtx);
|
|
39
|
+
const check = checkResult instanceof Promise ? await checkResult : checkResult;
|
|
40
|
+
if (!check.passed) {
|
|
41
|
+
const rejectReason = check.rejectReason ?? "\u65E0\u6CD5\u4EE5 completed \u7EC8\u6001\u7ED3\u675F\uFF1A\u672A\u68C0\u6D4B\u5230\u6709\u6548\u5B9E\u8D28\u4EA7\u51FA\uFF0C\u8BF7\u5B8C\u6210\u5206\u6790\u4EA7\u51FA\u6216\u4F7F\u7528 insufficient_data \u72B6\u6001\u3002";
|
|
42
|
+
options.onSignalRejected?.(signal, rejectReason);
|
|
43
|
+
return {
|
|
44
|
+
isError: true,
|
|
45
|
+
accepted: false,
|
|
46
|
+
terminated: false,
|
|
47
|
+
status: "rejected",
|
|
48
|
+
summary: summaryText ?? "",
|
|
49
|
+
message: rejectReason
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
options.onSignalAccepted?.(signal);
|
|
54
|
+
const message = options.resolveMessage ? options.resolveMessage(assertionCtx) : `\u4EFB\u52A1\u7EC8\u6001\u58F0\u660E\u5DF2\u786E\u8BA4: ${signal.status}`;
|
|
55
|
+
return {
|
|
56
|
+
isError: false,
|
|
57
|
+
accepted: true,
|
|
58
|
+
terminated: true,
|
|
59
|
+
status: signal.status,
|
|
60
|
+
summary: summaryText ?? "",
|
|
61
|
+
message
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/lifecycle/machine.ts
|
|
68
|
+
var TaskLifecycleMachine = class {
|
|
69
|
+
constructor(options = {}) {
|
|
70
|
+
this.options = options;
|
|
71
|
+
}
|
|
72
|
+
options;
|
|
73
|
+
_stepCount = 0;
|
|
74
|
+
_executedTools = [];
|
|
75
|
+
_explicitSignal;
|
|
76
|
+
get stepCount() {
|
|
77
|
+
return this._stepCount;
|
|
78
|
+
}
|
|
79
|
+
get executedTools() {
|
|
80
|
+
return this._executedTools;
|
|
81
|
+
}
|
|
82
|
+
get explicitSignal() {
|
|
83
|
+
return this._explicitSignal;
|
|
84
|
+
}
|
|
85
|
+
recordStep() {
|
|
86
|
+
this._stepCount++;
|
|
87
|
+
return this._stepCount;
|
|
88
|
+
}
|
|
89
|
+
recordToolExecution(toolName) {
|
|
90
|
+
this._executedTools.push(toolName);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* 创建绑定的终态声明工具(如 finish_task)
|
|
94
|
+
*/
|
|
95
|
+
createTool() {
|
|
96
|
+
return createTerminationTool({
|
|
97
|
+
toolName: this.options.toolName,
|
|
98
|
+
assertion: this.options.assertion,
|
|
99
|
+
getAssertionContext: () => ({
|
|
100
|
+
stepCount: this._stepCount,
|
|
101
|
+
executedTools: [...this._executedTools],
|
|
102
|
+
evidence: this.options.getEvidence?.()
|
|
103
|
+
}),
|
|
104
|
+
onSignalAccepted: (sig) => {
|
|
105
|
+
this._explicitSignal = sig;
|
|
106
|
+
this.options.onSignalAccepted?.(sig);
|
|
107
|
+
},
|
|
108
|
+
onSignalRejected: (sig, reason) => {
|
|
109
|
+
this.options.onSignalRejected?.(sig, reason);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/**
|
|
114
|
+
* 综合显式信号与执行结果,裁定最终终态决议
|
|
115
|
+
*/
|
|
116
|
+
resolve(fallbackType, reason) {
|
|
117
|
+
if (this._explicitSignal) {
|
|
118
|
+
return {
|
|
119
|
+
terminated: true,
|
|
120
|
+
type: "explicit_tool",
|
|
121
|
+
status: this._explicitSignal.status,
|
|
122
|
+
reason: this._explicitSignal.deliverableSummary ?? reason,
|
|
123
|
+
signal: this._explicitSignal
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
const type = fallbackType ?? "natural_stop";
|
|
127
|
+
return {
|
|
128
|
+
terminated: type === "natural_stop" || type === "explicit_tool",
|
|
129
|
+
type,
|
|
130
|
+
status: type === "natural_stop" ? "completed" : "incomplete",
|
|
131
|
+
reason
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
export {
|
|
137
|
+
createTerminationTool,
|
|
138
|
+
TaskLifecycleMachine
|
|
139
|
+
};
|
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// src/stream/redisTaskStore.ts
|
|
2
|
+
var TASK_KEY = (sessionKey) => `harness:task:${sessionKey}`;
|
|
3
|
+
var CHUNKS_KEY = (sessionKey) => `harness:task:${sessionKey}:chunks`;
|
|
4
|
+
var CHUNKS_CHAN_PREFIX = "harness:chan:";
|
|
5
|
+
var CHUNKS_CHAN = (sessionKey) => `${CHUNKS_CHAN_PREFIX}${sessionKey}`;
|
|
6
|
+
var CONTROL_CHAN = "harness:control";
|
|
7
|
+
var LEASE_KEY = (sessionKey) => `harness:lease:${sessionKey}`;
|
|
8
|
+
var RUNNING_SET = "harness:running";
|
|
9
|
+
var RUNNING_TTL_SECONDS = 600;
|
|
10
|
+
var TERMINAL_RETENTION_SECONDS = 30;
|
|
11
|
+
var OWNER_LOST_ERROR_MESSAGE = "owner_lost";
|
|
12
|
+
async function importRedisConstructor() {
|
|
13
|
+
try {
|
|
14
|
+
const mod = await import("./built-JAK7YFRG.js");
|
|
15
|
+
return mod.default ?? mod;
|
|
16
|
+
} catch (error) {
|
|
17
|
+
if (error?.code === "ERR_MODULE_NOT_FOUND") {
|
|
18
|
+
throw new Error(
|
|
19
|
+
"\u9700\u8981 ioredis\uFF0C\u4F46\u5F53\u524D\u8FDB\u7A0B\u672A\u5B89\u88C5\uFF1A\u591A\u526F\u672C\u90E8\u7F72\u8BF7\u6267\u884C `pnpm add ioredis` \u540E\u91CD\u542F\uFF1B\u5355\u8FDB\u7A0B\u90E8\u7F72\u8BF7\u6539\u7528 LLM_TASK_STORE=memory \u6216 file\u3002"
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function encodeChunkMessage(seq, base64) {
|
|
26
|
+
return JSON.stringify({ t: "c", s: seq, d: base64 });
|
|
27
|
+
}
|
|
28
|
+
function encodeCloseMessage(status, errorMessage) {
|
|
29
|
+
return JSON.stringify({ t: "e", st: status, ...errorMessage !== void 0 ? { m: errorMessage } : {} });
|
|
30
|
+
}
|
|
31
|
+
var RedisTaskStore = class {
|
|
32
|
+
/** 多副本语义声明:hub 据此启动孤儿清扫器(单机后端不声明) */
|
|
33
|
+
multiReplica = true;
|
|
34
|
+
#client;
|
|
35
|
+
#subscriber;
|
|
36
|
+
/** 连接(或依赖加载)完成即 resolve;ioredis 缺失时 reject 且携带安装指引 */
|
|
37
|
+
ready;
|
|
38
|
+
#controlHandlers = /* @__PURE__ */ new Set();
|
|
39
|
+
#chunkHandlers = /* @__PURE__ */ new Map();
|
|
40
|
+
#controlSubscribed = false;
|
|
41
|
+
constructor(opts = {}) {
|
|
42
|
+
this.ready = this.init(opts);
|
|
43
|
+
}
|
|
44
|
+
async init(opts) {
|
|
45
|
+
if (opts.client) {
|
|
46
|
+
this.#client = opts.client;
|
|
47
|
+
this.#subscriber = opts.subscriber ?? opts.client.duplicate();
|
|
48
|
+
} else {
|
|
49
|
+
if (!opts.url) {
|
|
50
|
+
throw new Error("RedisTaskStore \u9700\u8981 url \u6216\u6CE8\u5165 client");
|
|
51
|
+
}
|
|
52
|
+
const createClient = await importRedisConstructor();
|
|
53
|
+
this.#client = new createClient(opts.url);
|
|
54
|
+
this.#subscriber = opts.subscriber ?? this.#client.duplicate();
|
|
55
|
+
}
|
|
56
|
+
this.#subscriber.on("message", (channel, message) => this.dispatch(channel, message));
|
|
57
|
+
}
|
|
58
|
+
async client() {
|
|
59
|
+
await this.ready;
|
|
60
|
+
return this.#client;
|
|
61
|
+
}
|
|
62
|
+
async subscriber() {
|
|
63
|
+
await this.ready;
|
|
64
|
+
return this.#subscriber;
|
|
65
|
+
}
|
|
66
|
+
async create(snapshot) {
|
|
67
|
+
const c = await this.client();
|
|
68
|
+
await c.del(CHUNKS_KEY(snapshot.sessionKey));
|
|
69
|
+
await c.hset(TASK_KEY(snapshot.sessionKey), this.encodeSnapshot(snapshot));
|
|
70
|
+
if (snapshot.status === "running") {
|
|
71
|
+
await c.expire(TASK_KEY(snapshot.sessionKey), RUNNING_TTL_SECONDS);
|
|
72
|
+
await c.sadd(RUNNING_SET, snapshot.sessionKey);
|
|
73
|
+
} else {
|
|
74
|
+
await c.expire(TASK_KEY(snapshot.sessionKey), TERMINAL_RETENTION_SECONDS);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
async appendChunk(sessionKey, chunk) {
|
|
78
|
+
const c = await this.client();
|
|
79
|
+
const base64 = Buffer.from(chunk).toString("base64");
|
|
80
|
+
const seq = await c.rpush(CHUNKS_KEY(sessionKey), base64);
|
|
81
|
+
await c.expire(CHUNKS_KEY(sessionKey), RUNNING_TTL_SECONDS);
|
|
82
|
+
await c.publish(CHUNKS_CHAN(sessionKey), encodeChunkMessage(seq, base64));
|
|
83
|
+
}
|
|
84
|
+
async setStatus(sessionKey, status, errorMessage) {
|
|
85
|
+
const c = await this.client();
|
|
86
|
+
const key = TASK_KEY(sessionKey);
|
|
87
|
+
if (await c.hget(key, "status") === null) return;
|
|
88
|
+
await c.hset(key, {
|
|
89
|
+
status,
|
|
90
|
+
updatedAt: String(Date.now()),
|
|
91
|
+
...errorMessage === void 0 ? {} : { errorMessage }
|
|
92
|
+
});
|
|
93
|
+
if (status === "running") return;
|
|
94
|
+
await c.srem(RUNNING_SET, sessionKey);
|
|
95
|
+
await c.expire(key, TERMINAL_RETENTION_SECONDS);
|
|
96
|
+
await c.expire(CHUNKS_KEY(sessionKey), TERMINAL_RETENTION_SECONDS);
|
|
97
|
+
await c.publish(CHUNKS_CHAN(sessionKey), encodeCloseMessage(status, errorMessage));
|
|
98
|
+
}
|
|
99
|
+
async get(sessionKey) {
|
|
100
|
+
const c = await this.client();
|
|
101
|
+
return this.decodeSnapshot(await c.hgetall(TASK_KEY(sessionKey)));
|
|
102
|
+
}
|
|
103
|
+
async getChunks(sessionKey) {
|
|
104
|
+
const c = await this.client();
|
|
105
|
+
const raw = await c.lrange(CHUNKS_KEY(sessionKey), 0, -1);
|
|
106
|
+
return raw.map((line) => new Uint8Array(Buffer.from(line, "base64")));
|
|
107
|
+
}
|
|
108
|
+
async delete(sessionKey) {
|
|
109
|
+
const c = await this.client();
|
|
110
|
+
await c.del(TASK_KEY(sessionKey), CHUNKS_KEY(sessionKey), LEASE_KEY(sessionKey));
|
|
111
|
+
await c.srem(RUNNING_SET, sessionKey);
|
|
112
|
+
}
|
|
113
|
+
async runningCount() {
|
|
114
|
+
const c = await this.client();
|
|
115
|
+
return c.scard(RUNNING_SET);
|
|
116
|
+
}
|
|
117
|
+
subscribeChunks(sessionKey, onChunk, onClose) {
|
|
118
|
+
const handlers = this.#chunkHandlers.get(sessionKey) ?? /* @__PURE__ */ new Set();
|
|
119
|
+
const handler = { onChunk, onClose };
|
|
120
|
+
handlers.add(handler);
|
|
121
|
+
this.#chunkHandlers.set(sessionKey, handlers);
|
|
122
|
+
void this.ensureChanSubscribed(sessionKey);
|
|
123
|
+
return () => {
|
|
124
|
+
handlers.delete(handler);
|
|
125
|
+
if (handlers.size > 0) return;
|
|
126
|
+
this.#chunkHandlers.delete(sessionKey);
|
|
127
|
+
void this.subscriber().then((s) => s.unsubscribe(CHUNKS_CHAN(sessionKey))).catch(() => {
|
|
128
|
+
});
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
async publishAbort(sessionKey, reason) {
|
|
132
|
+
const c = await this.client();
|
|
133
|
+
await c.publish(CONTROL_CHAN, JSON.stringify({ k: sessionKey, r: reason }));
|
|
134
|
+
}
|
|
135
|
+
subscribeAbort(onAbort) {
|
|
136
|
+
this.#controlHandlers.add(onAbort);
|
|
137
|
+
if (!this.#controlSubscribed) {
|
|
138
|
+
this.#controlSubscribed = true;
|
|
139
|
+
void this.subscriber().then((s) => s.subscribe(CONTROL_CHAN)).catch(() => {
|
|
140
|
+
this.#controlSubscribed = false;
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
return () => {
|
|
144
|
+
this.#controlHandlers.delete(onAbort);
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
async refreshLease(sessionKey, ownerInstanceId, ttlMs) {
|
|
148
|
+
const c = await this.client();
|
|
149
|
+
if (await c.hget(TASK_KEY(sessionKey), "status") !== "running") return;
|
|
150
|
+
await c.set(
|
|
151
|
+
LEASE_KEY(sessionKey),
|
|
152
|
+
ownerInstanceId,
|
|
153
|
+
"EX",
|
|
154
|
+
Math.max(1, Math.ceil(ttlMs / 1e3))
|
|
155
|
+
);
|
|
156
|
+
await c.expire(TASK_KEY(sessionKey), RUNNING_TTL_SECONDS);
|
|
157
|
+
await c.expire(CHUNKS_KEY(sessionKey), RUNNING_TTL_SECONDS);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* 清扫器:回收租约失踪的 running 任务。多实例同时扫是幂等的
|
|
161
|
+
* (重复 setStatus 同值 / SREM 幂等 / 关闭广播的订阅方收尾幂等)。
|
|
162
|
+
* 返回本次回收的 sessionKey 列表。
|
|
163
|
+
*/
|
|
164
|
+
async sweepOrphans(isAlive) {
|
|
165
|
+
const c = await this.client();
|
|
166
|
+
const members = await c.smembers(RUNNING_SET);
|
|
167
|
+
const reclaimed = [];
|
|
168
|
+
for (const sessionKey of members) {
|
|
169
|
+
const snapshot = this.decodeSnapshot(await c.hgetall(TASK_KEY(sessionKey)));
|
|
170
|
+
if (!snapshot || snapshot.status !== "running") {
|
|
171
|
+
await c.srem(RUNNING_SET, sessionKey);
|
|
172
|
+
continue;
|
|
173
|
+
}
|
|
174
|
+
if (await c.get(LEASE_KEY(sessionKey)) !== null) continue;
|
|
175
|
+
if (await isAlive(snapshot.ownerInstanceId, sessionKey)) continue;
|
|
176
|
+
await this.setStatus(sessionKey, "error", OWNER_LOST_ERROR_MESSAGE);
|
|
177
|
+
reclaimed.push(sessionKey);
|
|
178
|
+
}
|
|
179
|
+
return reclaimed;
|
|
180
|
+
}
|
|
181
|
+
async ensureChanSubscribed(sessionKey) {
|
|
182
|
+
try {
|
|
183
|
+
const s = await this.subscriber();
|
|
184
|
+
await s.subscribe(CHUNKS_CHAN(sessionKey));
|
|
185
|
+
} catch {
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
dispatch(channel, message) {
|
|
189
|
+
if (channel === CONTROL_CHAN) {
|
|
190
|
+
let parsed2;
|
|
191
|
+
try {
|
|
192
|
+
parsed2 = JSON.parse(message);
|
|
193
|
+
} catch {
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
if (typeof parsed2.k !== "string" || typeof parsed2.r !== "string") return;
|
|
197
|
+
for (const handler of [...this.#controlHandlers]) {
|
|
198
|
+
try {
|
|
199
|
+
handler(parsed2.k, parsed2.r);
|
|
200
|
+
} catch {
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
if (!channel.startsWith(CHUNKS_CHAN_PREFIX)) return;
|
|
206
|
+
const sessionKey = channel.slice(CHUNKS_CHAN_PREFIX.length);
|
|
207
|
+
const handlers = this.#chunkHandlers.get(sessionKey);
|
|
208
|
+
if (!handlers || handlers.size === 0) return;
|
|
209
|
+
let parsed;
|
|
210
|
+
try {
|
|
211
|
+
parsed = JSON.parse(message);
|
|
212
|
+
} catch {
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
if (parsed.t === "c" && typeof parsed.s === "number" && typeof parsed.d === "string") {
|
|
216
|
+
const chunk = new Uint8Array(Buffer.from(parsed.d, "base64"));
|
|
217
|
+
for (const handler of [...handlers]) {
|
|
218
|
+
try {
|
|
219
|
+
handler.onChunk(chunk, parsed.s);
|
|
220
|
+
} catch {
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
} else if (parsed.t === "e" && (parsed.st === "completed" || parsed.st === "error")) {
|
|
224
|
+
for (const handler of [...handlers]) {
|
|
225
|
+
try {
|
|
226
|
+
handler.onClose?.(parsed.st, typeof parsed.m === "string" ? parsed.m : void 0);
|
|
227
|
+
} catch {
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
encodeSnapshot(snapshot) {
|
|
233
|
+
return {
|
|
234
|
+
sessionKey: snapshot.sessionKey,
|
|
235
|
+
...snapshot.runId === void 0 ? {} : { runId: snapshot.runId },
|
|
236
|
+
ownerInstanceId: snapshot.ownerInstanceId,
|
|
237
|
+
status: snapshot.status,
|
|
238
|
+
...snapshot.errorMessage === void 0 ? {} : { errorMessage: snapshot.errorMessage },
|
|
239
|
+
createdAt: String(snapshot.createdAt),
|
|
240
|
+
updatedAt: String(snapshot.updatedAt)
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
decodeSnapshot(raw) {
|
|
244
|
+
if (!raw.sessionKey || !raw.status) return void 0;
|
|
245
|
+
if (raw.status !== "running" && raw.status !== "completed" && raw.status !== "error") {
|
|
246
|
+
return void 0;
|
|
247
|
+
}
|
|
248
|
+
return {
|
|
249
|
+
sessionKey: raw.sessionKey,
|
|
250
|
+
runId: raw.runId || void 0,
|
|
251
|
+
ownerInstanceId: raw.ownerInstanceId ?? "",
|
|
252
|
+
status: raw.status,
|
|
253
|
+
errorMessage: raw.errorMessage || void 0,
|
|
254
|
+
createdAt: Number(raw.createdAt) || 0,
|
|
255
|
+
updatedAt: Number(raw.updatedAt) || 0
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
export {
|
|
261
|
+
OWNER_LOST_ERROR_MESSAGE,
|
|
262
|
+
importRedisConstructor,
|
|
263
|
+
RedisTaskStore
|
|
264
|
+
};
|