@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,127 @@
|
|
|
1
|
+
import {
|
|
2
|
+
jsonByteSize
|
|
3
|
+
} from "./chunk-A7RQFPRO.js";
|
|
4
|
+
|
|
5
|
+
// src/tools/compose.ts
|
|
6
|
+
function composeToolInterceptors(tools, interceptors, getContext) {
|
|
7
|
+
if (interceptors.length === 0) {
|
|
8
|
+
return tools;
|
|
9
|
+
}
|
|
10
|
+
const wrapped = {};
|
|
11
|
+
for (const [name, t] of Object.entries(tools)) {
|
|
12
|
+
const orig = t;
|
|
13
|
+
if (typeof orig.execute !== "function") {
|
|
14
|
+
wrapped[name] = t;
|
|
15
|
+
continue;
|
|
16
|
+
}
|
|
17
|
+
const origExecute = orig.execute.bind(t);
|
|
18
|
+
wrapped[name] = {
|
|
19
|
+
...t,
|
|
20
|
+
execute: async (args, callOpts) => {
|
|
21
|
+
const extraCtx = getContext ? getContext(name) : {};
|
|
22
|
+
const ctx = {
|
|
23
|
+
toolName: name,
|
|
24
|
+
...extraCtx
|
|
25
|
+
};
|
|
26
|
+
let index = -1;
|
|
27
|
+
const dispatch = async (i, currentArgs) => {
|
|
28
|
+
if (i <= index) {
|
|
29
|
+
throw new Error("next() called multiple times in tool interceptor");
|
|
30
|
+
}
|
|
31
|
+
index = i;
|
|
32
|
+
if (i === interceptors.length) {
|
|
33
|
+
return origExecute(currentArgs, callOpts);
|
|
34
|
+
}
|
|
35
|
+
const interceptor = interceptors[i];
|
|
36
|
+
return interceptor(
|
|
37
|
+
currentArgs,
|
|
38
|
+
ctx,
|
|
39
|
+
(nextArgs) => dispatch(i + 1, nextArgs !== void 0 ? nextArgs : currentArgs)
|
|
40
|
+
);
|
|
41
|
+
};
|
|
42
|
+
return dispatch(0, args);
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
return wrapped;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// src/tools/telemetryAspect.ts
|
|
50
|
+
function createTelemetryInterceptor(opts) {
|
|
51
|
+
return async (args, ctx, next) => {
|
|
52
|
+
const t0 = Date.now();
|
|
53
|
+
const runId = ctx.runId ?? opts.runId;
|
|
54
|
+
const sessionId = ctx.sessionId ?? opts.sessionId;
|
|
55
|
+
const sourceId = ctx.sourceId ?? opts.sourceId;
|
|
56
|
+
try {
|
|
57
|
+
const result = await next(args);
|
|
58
|
+
const isErrorObj = result && typeof result === "object" && result.isError === true;
|
|
59
|
+
if (runId) {
|
|
60
|
+
opts.telemetry.emit({
|
|
61
|
+
type: "tool_result",
|
|
62
|
+
runId,
|
|
63
|
+
sessionId,
|
|
64
|
+
tool: ctx.toolName,
|
|
65
|
+
sourceId,
|
|
66
|
+
ok: !isErrorObj,
|
|
67
|
+
bytes: jsonByteSize(result),
|
|
68
|
+
durationMs: Date.now() - t0
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
} catch (err) {
|
|
73
|
+
if (runId) {
|
|
74
|
+
opts.telemetry.emit({
|
|
75
|
+
type: "tool_result",
|
|
76
|
+
runId,
|
|
77
|
+
sessionId,
|
|
78
|
+
tool: ctx.toolName,
|
|
79
|
+
sourceId,
|
|
80
|
+
ok: false,
|
|
81
|
+
bytes: -1,
|
|
82
|
+
durationMs: Date.now() - t0
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
throw err;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// src/tools/timeoutAspect.ts
|
|
91
|
+
var ToolTimeoutError = class extends Error {
|
|
92
|
+
constructor(toolName, timeoutMs) {
|
|
93
|
+
super(`Tool "${toolName}" timed out after ${timeoutMs}ms`);
|
|
94
|
+
this.toolName = toolName;
|
|
95
|
+
this.timeoutMs = timeoutMs;
|
|
96
|
+
this.name = "ToolTimeoutError";
|
|
97
|
+
}
|
|
98
|
+
toolName;
|
|
99
|
+
timeoutMs;
|
|
100
|
+
};
|
|
101
|
+
function createTimeoutInterceptor(timeoutMs) {
|
|
102
|
+
if (timeoutMs <= 0) {
|
|
103
|
+
return async (args, _ctx, next) => next(args);
|
|
104
|
+
}
|
|
105
|
+
return async (args, ctx, next) => {
|
|
106
|
+
let timer;
|
|
107
|
+
const timeoutPromise = new Promise((_, reject) => {
|
|
108
|
+
timer = setTimeout(() => {
|
|
109
|
+
reject(new ToolTimeoutError(ctx.toolName, timeoutMs));
|
|
110
|
+
}, timeoutMs);
|
|
111
|
+
});
|
|
112
|
+
try {
|
|
113
|
+
return await Promise.race([next(args), timeoutPromise]);
|
|
114
|
+
} finally {
|
|
115
|
+
if (timer) {
|
|
116
|
+
clearTimeout(timer);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export {
|
|
123
|
+
composeToolInterceptors,
|
|
124
|
+
createTelemetryInterceptor,
|
|
125
|
+
ToolTimeoutError,
|
|
126
|
+
createTimeoutInterceptor
|
|
127
|
+
};
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import {
|
|
2
|
+
importRedisConstructor
|
|
3
|
+
} from "./chunk-HYD33JX5.js";
|
|
4
|
+
|
|
5
|
+
// src/finops/costLedger.ts
|
|
6
|
+
import fs from "fs";
|
|
7
|
+
import path from "path";
|
|
8
|
+
var DEFAULT_QUOTA_WINDOW_MS = 864e5;
|
|
9
|
+
var PRICING_PATH_DEFAULT = path.join(process.cwd(), "config", "model-pricing.json");
|
|
10
|
+
var ModelPricingTable = class {
|
|
11
|
+
#configPath;
|
|
12
|
+
#staticTable;
|
|
13
|
+
#cache = null;
|
|
14
|
+
#mtimeMs = -1;
|
|
15
|
+
constructor(configOrPath = PRICING_PATH_DEFAULT) {
|
|
16
|
+
if (typeof configOrPath === "string") {
|
|
17
|
+
this.#configPath = configOrPath;
|
|
18
|
+
} else {
|
|
19
|
+
this.#staticTable = { ...configOrPath };
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** 文件 mtime 变化时重载(改 config 无需重启进程);读失败静默清空缓存 */
|
|
23
|
+
reloadIfChanged() {
|
|
24
|
+
if (this.#staticTable) return;
|
|
25
|
+
if (!this.#configPath) return;
|
|
26
|
+
try {
|
|
27
|
+
const stat = fs.statSync(this.#configPath);
|
|
28
|
+
if (stat.mtimeMs === this.#mtimeMs) return;
|
|
29
|
+
this.#mtimeMs = stat.mtimeMs;
|
|
30
|
+
const parsed = JSON.parse(fs.readFileSync(this.#configPath, "utf-8"));
|
|
31
|
+
if (!parsed || typeof parsed !== "object") {
|
|
32
|
+
this.#cache = null;
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const entries = {};
|
|
36
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
37
|
+
if (value && typeof value === "object" && typeof value.input === "number" && typeof value.output === "number") {
|
|
38
|
+
entries[key] = value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
this.#cache = entries;
|
|
42
|
+
} catch {
|
|
43
|
+
this.#cache = null;
|
|
44
|
+
this.#mtimeMs = -1;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** 最长前缀匹配;未命中返回 undefined */
|
|
48
|
+
priceFor(model) {
|
|
49
|
+
if (this.#staticTable) {
|
|
50
|
+
const lower2 = model.toLowerCase();
|
|
51
|
+
let best2;
|
|
52
|
+
for (const key of Object.keys(this.#staticTable)) {
|
|
53
|
+
if (lower2.startsWith(key.toLowerCase()) && (best2 === void 0 || key.length > best2.length)) {
|
|
54
|
+
best2 = key;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return best2 === void 0 ? void 0 : this.#staticTable[best2];
|
|
58
|
+
}
|
|
59
|
+
this.reloadIfChanged();
|
|
60
|
+
const table = this.#cache;
|
|
61
|
+
if (!table) return void 0;
|
|
62
|
+
const lower = model.toLowerCase();
|
|
63
|
+
let best;
|
|
64
|
+
for (const key of Object.keys(table)) {
|
|
65
|
+
if (lower.startsWith(key.toLowerCase()) && (best === void 0 || key.length > best.length)) {
|
|
66
|
+
best = key;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return best === void 0 ? void 0 : table[best];
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
function computeCostUsd(pricing, promptTokens, completionTokens, options) {
|
|
73
|
+
const cachedTokens = Math.min(promptTokens, Math.max(0, options?.cachedPromptTokens ?? 0));
|
|
74
|
+
const regularPromptTokens = Math.max(0, promptTokens - cachedTokens);
|
|
75
|
+
const cacheRate = pricing.cacheRead ?? pricing.input * 0.5;
|
|
76
|
+
const reasoningTokens = Math.min(completionTokens, Math.max(0, options?.reasoningTokens ?? 0));
|
|
77
|
+
const regularOutputTokens = Math.max(0, completionTokens - reasoningTokens);
|
|
78
|
+
const reasoningRate = pricing.reasoning ?? pricing.output;
|
|
79
|
+
const usd = regularPromptTokens / 1e6 * pricing.input + cachedTokens / 1e6 * cacheRate + regularOutputTokens / 1e6 * pricing.output + reasoningTokens / 1e6 * reasoningRate;
|
|
80
|
+
return Number(usd.toFixed(6));
|
|
81
|
+
}
|
|
82
|
+
var InMemoryCostLedger = class {
|
|
83
|
+
#records = [];
|
|
84
|
+
async record(entry) {
|
|
85
|
+
this.#records.push({ ...entry });
|
|
86
|
+
}
|
|
87
|
+
async sumUsage(tenantId, windowMs) {
|
|
88
|
+
const since = Date.now() - windowMs;
|
|
89
|
+
let tokens = 0;
|
|
90
|
+
let costUsd = 0;
|
|
91
|
+
for (const r of this.#records) {
|
|
92
|
+
if (r.tenantId !== tenantId || r.finishedAt < since) continue;
|
|
93
|
+
tokens += r.promptTokens + r.completionTokens;
|
|
94
|
+
costUsd += r.costUsd ?? 0;
|
|
95
|
+
}
|
|
96
|
+
return { tokens, costUsd: Number(costUsd.toFixed(6)) };
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
var NdjsonCostLedger = class {
|
|
100
|
+
#filePath;
|
|
101
|
+
#records = null;
|
|
102
|
+
constructor(opts = {}) {
|
|
103
|
+
this.#filePath = opts.filePath ?? path.join(process.cwd(), "data", "cost-ledger.ndjson");
|
|
104
|
+
}
|
|
105
|
+
/** 首次使用懒加载回放(重启后重建索引);坏行跳过不阻塞 */
|
|
106
|
+
#ensureLoaded() {
|
|
107
|
+
if (this.#records) return this.#records;
|
|
108
|
+
const records = [];
|
|
109
|
+
try {
|
|
110
|
+
const raw = fs.readFileSync(this.#filePath, "utf-8");
|
|
111
|
+
for (const line of raw.split("\n")) {
|
|
112
|
+
if (!line.trim()) continue;
|
|
113
|
+
try {
|
|
114
|
+
const parsed = JSON.parse(line);
|
|
115
|
+
if (parsed && typeof parsed.runId === "string" && typeof parsed.tenantId === "string" && typeof parsed.finishedAt === "number") {
|
|
116
|
+
records.push(parsed);
|
|
117
|
+
}
|
|
118
|
+
} catch {
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
} catch {
|
|
122
|
+
}
|
|
123
|
+
this.#records = records;
|
|
124
|
+
return records;
|
|
125
|
+
}
|
|
126
|
+
async record(entry) {
|
|
127
|
+
const records = this.#ensureLoaded();
|
|
128
|
+
records.push({ ...entry });
|
|
129
|
+
fs.mkdirSync(path.dirname(this.#filePath), { recursive: true });
|
|
130
|
+
fs.appendFileSync(this.#filePath, `${JSON.stringify(entry)}
|
|
131
|
+
`, "utf-8");
|
|
132
|
+
}
|
|
133
|
+
async sumUsage(tenantId, windowMs) {
|
|
134
|
+
const since = Date.now() - windowMs;
|
|
135
|
+
let tokens = 0;
|
|
136
|
+
let costUsd = 0;
|
|
137
|
+
for (const r of this.#ensureLoaded()) {
|
|
138
|
+
if (r.tenantId !== tenantId || r.finishedAt < since) continue;
|
|
139
|
+
tokens += r.promptTokens + r.completionTokens;
|
|
140
|
+
costUsd += r.costUsd ?? 0;
|
|
141
|
+
}
|
|
142
|
+
return { tokens, costUsd: Number(costUsd.toFixed(6)) };
|
|
143
|
+
}
|
|
144
|
+
};
|
|
145
|
+
var LEDGER_KEY = (tenantId) => `harness:ledger:${tenantId}`;
|
|
146
|
+
var RedisCostLedger = class {
|
|
147
|
+
#client;
|
|
148
|
+
ready;
|
|
149
|
+
constructor(opts = {}) {
|
|
150
|
+
this.ready = this.init(opts);
|
|
151
|
+
}
|
|
152
|
+
async init(opts) {
|
|
153
|
+
if (opts.client) {
|
|
154
|
+
this.#client = opts.client;
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
if (!opts.url) {
|
|
158
|
+
throw new Error("RedisCostLedger \u9700\u8981 url \u6216\u6CE8\u5165 client");
|
|
159
|
+
}
|
|
160
|
+
const createClient = await importRedisConstructor();
|
|
161
|
+
this.#client = new createClient(opts.url);
|
|
162
|
+
}
|
|
163
|
+
async client() {
|
|
164
|
+
await this.ready;
|
|
165
|
+
return this.#client;
|
|
166
|
+
}
|
|
167
|
+
async record(entry) {
|
|
168
|
+
const c = await this.client();
|
|
169
|
+
await c.zadd(LEDGER_KEY(entry.tenantId), entry.finishedAt, JSON.stringify(entry));
|
|
170
|
+
}
|
|
171
|
+
async sumUsage(tenantId, windowMs) {
|
|
172
|
+
const c = await this.client();
|
|
173
|
+
const since = String(Date.now() - windowMs);
|
|
174
|
+
const members = await c.zrangebyscore(LEDGER_KEY(tenantId), since, "+inf");
|
|
175
|
+
let tokens = 0;
|
|
176
|
+
let costUsd = 0;
|
|
177
|
+
for (const member of members) {
|
|
178
|
+
try {
|
|
179
|
+
const r = JSON.parse(member);
|
|
180
|
+
tokens += r.promptTokens + r.completionTokens;
|
|
181
|
+
costUsd += r.costUsd ?? 0;
|
|
182
|
+
} catch {
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return { tokens, costUsd: Number(costUsd.toFixed(6)) };
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
export {
|
|
190
|
+
DEFAULT_QUOTA_WINDOW_MS,
|
|
191
|
+
ModelPricingTable,
|
|
192
|
+
computeCostUsd,
|
|
193
|
+
InMemoryCostLedger,
|
|
194
|
+
NdjsonCostLedger,
|
|
195
|
+
RedisCostLedger
|
|
196
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// src/tools/zodTool.ts
|
|
2
|
+
import { tool, jsonSchema } from "ai";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
function zodTool(def) {
|
|
5
|
+
let modelSchema;
|
|
6
|
+
try {
|
|
7
|
+
modelSchema = z.toJSONSchema(def.parameters, {
|
|
8
|
+
target: "draft-7",
|
|
9
|
+
io: "input"
|
|
10
|
+
});
|
|
11
|
+
} catch {
|
|
12
|
+
modelSchema = { type: "object" };
|
|
13
|
+
}
|
|
14
|
+
return tool({
|
|
15
|
+
description: def.description,
|
|
16
|
+
// jsonSchema() 不带 validate = 模型侧宽松入口:类型小错的参数直达 execute,
|
|
17
|
+
// 由下方 zod 校验反馈(而非 parseToolCall 处抛 InvalidToolArgumentsError)
|
|
18
|
+
parameters: jsonSchema(modelSchema),
|
|
19
|
+
execute: async (raw) => {
|
|
20
|
+
const parsed = def.parameters.safeParse(raw);
|
|
21
|
+
if (!parsed.success) {
|
|
22
|
+
return {
|
|
23
|
+
error: `\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${JSON.stringify(
|
|
24
|
+
parsed.error.issues
|
|
25
|
+
)}\u3002\u8BF7\u6309\u5DE5\u5177\u53C2\u6570\u5B9A\u4E49\u4FEE\u6B63\u5FC5\u586B\u9879\u4E0E\u7C7B\u578B\u540E\u91CD\u65B0\u8C03\u7528\u3002`,
|
|
26
|
+
isError: true
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
return def.execute(parsed.data);
|
|
30
|
+
}
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export {
|
|
35
|
+
zodTool
|
|
36
|
+
};
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
// src/graph/checkpointer.ts
|
|
2
|
+
var InMemoryCheckpointer = class {
|
|
3
|
+
checkpoints = /* @__PURE__ */ new Map();
|
|
4
|
+
async save(checkpoint) {
|
|
5
|
+
this.checkpoints.set(checkpoint.id, {
|
|
6
|
+
...checkpoint,
|
|
7
|
+
state: JSON.parse(JSON.stringify(checkpoint.state))
|
|
8
|
+
});
|
|
9
|
+
}
|
|
10
|
+
async load(checkpointId) {
|
|
11
|
+
const cp = this.checkpoints.get(checkpointId);
|
|
12
|
+
return cp ? JSON.parse(JSON.stringify(cp)) : void 0;
|
|
13
|
+
}
|
|
14
|
+
async loadLatest(sessionId) {
|
|
15
|
+
const list = await this.list(sessionId);
|
|
16
|
+
return list[list.length - 1];
|
|
17
|
+
}
|
|
18
|
+
async list(sessionId) {
|
|
19
|
+
const matched = [];
|
|
20
|
+
for (const cp of this.checkpoints.values()) {
|
|
21
|
+
if (cp.sessionId === sessionId) {
|
|
22
|
+
matched.push(JSON.parse(JSON.stringify(cp)));
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return matched.sort((a, b) => a.createdAt - b.createdAt);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
// src/graph/stateGraph.ts
|
|
30
|
+
import { randomUUID } from "crypto";
|
|
31
|
+
var START = "__start__";
|
|
32
|
+
var END = "__end__";
|
|
33
|
+
var StateGraph = class {
|
|
34
|
+
nodes = /* @__PURE__ */ new Map();
|
|
35
|
+
edges = /* @__PURE__ */ new Map();
|
|
36
|
+
conditionalEdges = /* @__PURE__ */ new Map();
|
|
37
|
+
breakpoints = /* @__PURE__ */ new Map();
|
|
38
|
+
/**
|
|
39
|
+
* 注册图节点
|
|
40
|
+
*/
|
|
41
|
+
addNode(name, action) {
|
|
42
|
+
if (name === START || name === END) {
|
|
43
|
+
throw new Error(`Reserved node name cannot be used: ${name}`);
|
|
44
|
+
}
|
|
45
|
+
this.nodes.set(name, action);
|
|
46
|
+
return this;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* 注册普通静态边
|
|
50
|
+
*/
|
|
51
|
+
addEdge(from, to) {
|
|
52
|
+
if (from !== START && !this.nodes.has(from)) {
|
|
53
|
+
throw new Error(`Source node does not exist: ${from}`);
|
|
54
|
+
}
|
|
55
|
+
if (to !== END && !this.nodes.has(to)) {
|
|
56
|
+
throw new Error(`Target node does not exist: ${to}`);
|
|
57
|
+
}
|
|
58
|
+
this.edges.set(from, to);
|
|
59
|
+
return this;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* 注册条件路由边
|
|
63
|
+
*/
|
|
64
|
+
addConditionalEdge(from, router) {
|
|
65
|
+
if (from !== START && !this.nodes.has(from)) {
|
|
66
|
+
throw new Error(`Source node does not exist: ${from}`);
|
|
67
|
+
}
|
|
68
|
+
this.conditionalEdges.set(from, router);
|
|
69
|
+
return this;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* 在特定节点设置人机交互断点 (Human-in-the-Loop)
|
|
73
|
+
*/
|
|
74
|
+
addBreakpoint(node, options) {
|
|
75
|
+
if (!this.nodes.has(node)) {
|
|
76
|
+
throw new Error(`Cannot set breakpoint on nonexistent node: ${node}`);
|
|
77
|
+
}
|
|
78
|
+
if (typeof options === "string") {
|
|
79
|
+
this.breakpoints.set(node, {
|
|
80
|
+
when: "before",
|
|
81
|
+
defaultReason: options
|
|
82
|
+
});
|
|
83
|
+
} else {
|
|
84
|
+
this.breakpoints.set(node, {
|
|
85
|
+
when: options?.when ?? "before",
|
|
86
|
+
defaultReason: options?.reason ?? "Breakpoint encountered",
|
|
87
|
+
condition: options?.condition
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* 编译为可执行的状态图实例
|
|
94
|
+
*/
|
|
95
|
+
compile(options) {
|
|
96
|
+
return new CompiledStateGraph(
|
|
97
|
+
new Map(this.nodes),
|
|
98
|
+
new Map(this.edges),
|
|
99
|
+
new Map(this.conditionalEdges),
|
|
100
|
+
new Map(this.breakpoints),
|
|
101
|
+
options?.checkpointer ?? new InMemoryCheckpointer()
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
var CompiledStateGraph = class {
|
|
106
|
+
constructor(nodes, edges, conditionalEdges, breakpoints, checkpointer) {
|
|
107
|
+
this.nodes = nodes;
|
|
108
|
+
this.edges = edges;
|
|
109
|
+
this.conditionalEdges = conditionalEdges;
|
|
110
|
+
this.breakpoints = breakpoints;
|
|
111
|
+
this.checkpointer = checkpointer;
|
|
112
|
+
}
|
|
113
|
+
nodes;
|
|
114
|
+
edges;
|
|
115
|
+
conditionalEdges;
|
|
116
|
+
breakpoints;
|
|
117
|
+
checkpointer;
|
|
118
|
+
/**
|
|
119
|
+
* 从头开始调用执行图
|
|
120
|
+
*/
|
|
121
|
+
async invoke(initialState, options) {
|
|
122
|
+
const runId = options?.runId ?? `run-${randomUUID()}`;
|
|
123
|
+
const sessionId = options?.sessionId ?? `sess-${randomUUID()}`;
|
|
124
|
+
const startNode = this.edges.get(START);
|
|
125
|
+
if (!startNode) {
|
|
126
|
+
throw new Error("No START edge configured in graph. Call addEdge(START, 'firstNode') first.");
|
|
127
|
+
}
|
|
128
|
+
return this.runFrom(startNode, initialState, runId, sessionId, false, options);
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* 从指定检查点唤醒并恢复执行 (Human-in-the-Loop Resume)
|
|
132
|
+
*/
|
|
133
|
+
async resume(checkpointId, statePatch, options) {
|
|
134
|
+
const checkpoint = await this.checkpointer.load(checkpointId);
|
|
135
|
+
if (!checkpoint) {
|
|
136
|
+
throw new Error(`Checkpoint not found: ${checkpointId}`);
|
|
137
|
+
}
|
|
138
|
+
const mergedState = {
|
|
139
|
+
...checkpoint.state,
|
|
140
|
+
...statePatch ?? {}
|
|
141
|
+
};
|
|
142
|
+
const bp = this.breakpoints.get(checkpoint.node);
|
|
143
|
+
const resumeMode = bp?.when === "after" ? "skipToNext" : "resumeAction";
|
|
144
|
+
if (resumeMode === "skipToNext") {
|
|
145
|
+
const nextNode = await this.getNextNode(checkpoint.node, mergedState);
|
|
146
|
+
if (!nextNode || nextNode === END) {
|
|
147
|
+
return {
|
|
148
|
+
state: mergedState,
|
|
149
|
+
status: "completed",
|
|
150
|
+
checkpointId
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
return this.runFrom(
|
|
154
|
+
nextNode,
|
|
155
|
+
mergedState,
|
|
156
|
+
options?.runId ?? checkpoint.runId,
|
|
157
|
+
options?.sessionId ?? checkpoint.sessionId,
|
|
158
|
+
false,
|
|
159
|
+
options
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
return this.runFrom(
|
|
163
|
+
checkpoint.node,
|
|
164
|
+
mergedState,
|
|
165
|
+
options?.runId ?? checkpoint.runId,
|
|
166
|
+
options?.sessionId ?? checkpoint.sessionId,
|
|
167
|
+
true,
|
|
168
|
+
// skipBeforeBreakpoint
|
|
169
|
+
options
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* 执行循环
|
|
174
|
+
*/
|
|
175
|
+
async runFrom(currentNode, initialState, runId, sessionId, skipBeforeBreakpoint, options) {
|
|
176
|
+
let state = { ...initialState };
|
|
177
|
+
let nodeName = currentNode;
|
|
178
|
+
let steps = 0;
|
|
179
|
+
const maxSteps = options?.maxSteps ?? 50;
|
|
180
|
+
let bypassNextBeforeBp = skipBeforeBreakpoint;
|
|
181
|
+
while (nodeName && nodeName !== END) {
|
|
182
|
+
if (options?.signal?.aborted) {
|
|
183
|
+
return {
|
|
184
|
+
state,
|
|
185
|
+
status: "aborted"
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
if (++steps > maxSteps) {
|
|
189
|
+
throw new Error(
|
|
190
|
+
`Graph execution exceeded maximum step limit of ${maxSteps}. Check for cyclic dependencies.`
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
const bp = this.breakpoints.get(nodeName);
|
|
194
|
+
if (bp && bp.when === "before" && !bypassNextBeforeBp) {
|
|
195
|
+
const hit = this.checkBreakpoint(bp, state);
|
|
196
|
+
if (hit.interrupt) {
|
|
197
|
+
const cp = {
|
|
198
|
+
id: `cp-${randomUUID()}`,
|
|
199
|
+
runId,
|
|
200
|
+
sessionId,
|
|
201
|
+
node: nodeName,
|
|
202
|
+
state,
|
|
203
|
+
createdAt: Date.now(),
|
|
204
|
+
interrupt: {
|
|
205
|
+
reason: hit.reason,
|
|
206
|
+
payload: hit.payload
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
await this.checkpointer.save(cp);
|
|
210
|
+
return {
|
|
211
|
+
state,
|
|
212
|
+
status: "suspended",
|
|
213
|
+
checkpointId: cp.id,
|
|
214
|
+
interrupt: {
|
|
215
|
+
node: nodeName,
|
|
216
|
+
reason: hit.reason,
|
|
217
|
+
payload: hit.payload
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
bypassNextBeforeBp = false;
|
|
223
|
+
const action = this.nodes.get(nodeName);
|
|
224
|
+
if (!action) {
|
|
225
|
+
throw new Error(`Node action not found for: ${nodeName}`);
|
|
226
|
+
}
|
|
227
|
+
const patch = await action(state, options?.signal);
|
|
228
|
+
state = { ...state, ...patch ?? {} };
|
|
229
|
+
if (bp && bp.when === "after") {
|
|
230
|
+
const hit = this.checkBreakpoint(bp, state);
|
|
231
|
+
if (hit.interrupt) {
|
|
232
|
+
const cp = {
|
|
233
|
+
id: `cp-${randomUUID()}`,
|
|
234
|
+
runId,
|
|
235
|
+
sessionId,
|
|
236
|
+
node: nodeName,
|
|
237
|
+
state,
|
|
238
|
+
createdAt: Date.now(),
|
|
239
|
+
interrupt: {
|
|
240
|
+
reason: hit.reason,
|
|
241
|
+
payload: hit.payload
|
|
242
|
+
}
|
|
243
|
+
};
|
|
244
|
+
await this.checkpointer.save(cp);
|
|
245
|
+
return {
|
|
246
|
+
state,
|
|
247
|
+
status: "suspended",
|
|
248
|
+
checkpointId: cp.id,
|
|
249
|
+
interrupt: {
|
|
250
|
+
node: nodeName,
|
|
251
|
+
reason: hit.reason,
|
|
252
|
+
payload: hit.payload
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
nodeName = await this.getNextNode(nodeName, state);
|
|
258
|
+
}
|
|
259
|
+
const finalCp = {
|
|
260
|
+
id: `cp-${randomUUID()}`,
|
|
261
|
+
runId,
|
|
262
|
+
sessionId,
|
|
263
|
+
node: END,
|
|
264
|
+
state,
|
|
265
|
+
createdAt: Date.now()
|
|
266
|
+
};
|
|
267
|
+
await this.checkpointer.save(finalCp);
|
|
268
|
+
return {
|
|
269
|
+
state,
|
|
270
|
+
status: "completed",
|
|
271
|
+
checkpointId: finalCp.id
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
async getNextNode(currentNode, state) {
|
|
275
|
+
if (this.conditionalEdges.has(currentNode)) {
|
|
276
|
+
const router = this.conditionalEdges.get(currentNode);
|
|
277
|
+
return router(state);
|
|
278
|
+
}
|
|
279
|
+
return this.edges.get(currentNode);
|
|
280
|
+
}
|
|
281
|
+
checkBreakpoint(bp, state) {
|
|
282
|
+
if (!bp.condition) {
|
|
283
|
+
return { interrupt: true, reason: bp.defaultReason ?? "Breakpoint hit" };
|
|
284
|
+
}
|
|
285
|
+
const res = bp.condition(state);
|
|
286
|
+
if (typeof res === "boolean") {
|
|
287
|
+
return {
|
|
288
|
+
interrupt: res,
|
|
289
|
+
reason: bp.defaultReason ?? "Breakpoint condition satisfied"
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
return {
|
|
293
|
+
interrupt: res.interrupt,
|
|
294
|
+
reason: res.reason ?? bp.defaultReason ?? "Breakpoint condition satisfied",
|
|
295
|
+
payload: res.payload
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
export {
|
|
301
|
+
InMemoryCheckpointer,
|
|
302
|
+
START,
|
|
303
|
+
END,
|
|
304
|
+
StateGraph,
|
|
305
|
+
CompiledStateGraph
|
|
306
|
+
};
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/tokenizer/heuristic.ts
|
|
2
|
+
var CJK_RE = /[一-鿿㐀-䶿䶿豈--ヿ가-]/g;
|
|
3
|
+
function estimateTextTokensHeuristic(text) {
|
|
4
|
+
if (!text) return 0;
|
|
5
|
+
const cjk = (text.match(CJK_RE) ?? []).length;
|
|
6
|
+
return Math.ceil((cjk / 1.5 + (text.length - cjk) / 4) * 1.1);
|
|
7
|
+
}
|
|
8
|
+
var HeuristicTokenizer = class {
|
|
9
|
+
encode(text) {
|
|
10
|
+
return estimateTextTokensHeuristic(text);
|
|
11
|
+
}
|
|
12
|
+
};
|
|
13
|
+
|
|
14
|
+
export {
|
|
15
|
+
estimateTextTokensHeuristic,
|
|
16
|
+
HeuristicTokenizer
|
|
17
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// src/providers/registry.ts
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_MODEL_WINDOW_MAP,
|
|
4
|
+
CONTEXT_WINDOW_MIN,
|
|
5
|
+
CONTEXT_WINDOW_MAX,
|
|
6
|
+
DEFAULT_CONTEXT_WINDOW,
|
|
7
|
+
isReasoningModel,
|
|
8
|
+
ModelCatalogRegistry,
|
|
9
|
+
defaultModelCatalog,
|
|
10
|
+
resolveContextWindow
|
|
11
|
+
} from "@ginkgolab/models";
|
|
12
|
+
|
|
13
|
+
export {
|
|
14
|
+
DEFAULT_MODEL_WINDOW_MAP,
|
|
15
|
+
CONTEXT_WINDOW_MIN,
|
|
16
|
+
CONTEXT_WINDOW_MAX,
|
|
17
|
+
DEFAULT_CONTEXT_WINDOW,
|
|
18
|
+
isReasoningModel,
|
|
19
|
+
ModelCatalogRegistry,
|
|
20
|
+
defaultModelCatalog,
|
|
21
|
+
resolveContextWindow
|
|
22
|
+
};
|