@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,254 @@
|
|
|
1
|
+
import {
|
|
2
|
+
estimateTextTokensHeuristic
|
|
3
|
+
} from "./chunk-VNSZH3H7.js";
|
|
4
|
+
import {
|
|
5
|
+
defaultModelCatalog
|
|
6
|
+
} from "./chunk-ZO2UWHNE.js";
|
|
7
|
+
|
|
8
|
+
// src/context/budget.ts
|
|
9
|
+
function resolveContextWindow(model, clientHint, catalog = defaultModelCatalog) {
|
|
10
|
+
return catalog.resolveContextWindow(model, clientHint);
|
|
11
|
+
}
|
|
12
|
+
function computeContextBudget(window, maxOutputTokens = 4096, reserveRatio = 0.25) {
|
|
13
|
+
const triggerAt = Math.min(
|
|
14
|
+
Math.floor(window * 0.7),
|
|
15
|
+
window - maxOutputTokens - 8192
|
|
16
|
+
);
|
|
17
|
+
return {
|
|
18
|
+
window,
|
|
19
|
+
triggerAt: Math.max(triggerAt, 1024),
|
|
20
|
+
retainTokens: Math.floor(window * Math.max(0.1, Math.min(reserveRatio, 0.5)))
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// src/context/estimator.ts
|
|
25
|
+
function safeSerialize(value) {
|
|
26
|
+
try {
|
|
27
|
+
return JSON.stringify(value) ?? "";
|
|
28
|
+
} catch {
|
|
29
|
+
return "";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
function estimateMessageTokens(message, countText = estimateTextTokensHeuristic) {
|
|
33
|
+
const m = message;
|
|
34
|
+
if (!m || typeof m !== "object") return 0;
|
|
35
|
+
let tokens = 8;
|
|
36
|
+
const rest = m;
|
|
37
|
+
if (Array.isArray(rest.parts) && rest.parts.length > 0) {
|
|
38
|
+
tokens += countText(safeSerialize(rest.parts));
|
|
39
|
+
} else {
|
|
40
|
+
if (typeof m.content === "string") {
|
|
41
|
+
tokens += countText(m.content);
|
|
42
|
+
} else if (m.content !== void 0 && m.content !== null) {
|
|
43
|
+
tokens += countText(safeSerialize(m.content));
|
|
44
|
+
}
|
|
45
|
+
if (rest.toolInvocations !== void 0) {
|
|
46
|
+
tokens += countText(safeSerialize(rest.toolInvocations));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (rest.annotations !== void 0) {
|
|
50
|
+
tokens += countText(safeSerialize(rest.annotations));
|
|
51
|
+
}
|
|
52
|
+
return tokens;
|
|
53
|
+
}
|
|
54
|
+
function estimateMessagesTokens(messages, countText = estimateTextTokensHeuristic) {
|
|
55
|
+
let total = 0;
|
|
56
|
+
for (const m of messages) {
|
|
57
|
+
total += estimateMessageTokens(m, countText);
|
|
58
|
+
}
|
|
59
|
+
return total;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// src/context/pruning.ts
|
|
63
|
+
var DEFAULT_PRUNED_PLACEHOLDER = (toolName) => `[\u5DF2\u88C1\u526A: ${toolName}]`;
|
|
64
|
+
function roleOf(m) {
|
|
65
|
+
return m?.role ?? "";
|
|
66
|
+
}
|
|
67
|
+
function toolNamesOf(m) {
|
|
68
|
+
const content = m?.content;
|
|
69
|
+
if (!Array.isArray(content)) return [];
|
|
70
|
+
return content.filter(
|
|
71
|
+
(p) => p !== null && typeof p === "object"
|
|
72
|
+
).filter((p) => p.type === "tool-result").map((p) => typeof p.toolName === "string" ? p.toolName : "tool");
|
|
73
|
+
}
|
|
74
|
+
function projectMessagesWithPruning(opts) {
|
|
75
|
+
const { messages, budget } = opts;
|
|
76
|
+
const overhead = opts.systemTokens ?? 0;
|
|
77
|
+
const countText = opts.tokenizer ? opts.tokenizer.encode.bind(opts.tokenizer) : estimateTextTokensHeuristic;
|
|
78
|
+
const heuristic = estimateMessagesTokens(messages, countText);
|
|
79
|
+
const estimated = Math.max(heuristic, opts.anchorTokens ?? 0) + overhead;
|
|
80
|
+
if (estimated <= budget.triggerAt) {
|
|
81
|
+
return {
|
|
82
|
+
messages,
|
|
83
|
+
pruned: false,
|
|
84
|
+
prunedCount: 0,
|
|
85
|
+
estimatedPromptTokens: estimated,
|
|
86
|
+
summarizeUpToIndex: -1
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
let acc = 0;
|
|
90
|
+
let retainFrom = messages.length;
|
|
91
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
92
|
+
const t = estimateMessageTokens(messages[i], countText);
|
|
93
|
+
if (acc + t > budget.retainTokens && retainFrom < messages.length) {
|
|
94
|
+
retainFrom = i + 1;
|
|
95
|
+
break;
|
|
96
|
+
}
|
|
97
|
+
acc += t;
|
|
98
|
+
retainFrom = i;
|
|
99
|
+
}
|
|
100
|
+
if (retainFrom <= 0) {
|
|
101
|
+
return {
|
|
102
|
+
messages,
|
|
103
|
+
pruned: false,
|
|
104
|
+
prunedCount: 0,
|
|
105
|
+
estimatedPromptTokens: estimated,
|
|
106
|
+
summarizeUpToIndex: -1
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const formatPlaceholder = opts.placeholderFormatter ?? DEFAULT_PRUNED_PLACEHOLDER;
|
|
110
|
+
let prunedCount = 0;
|
|
111
|
+
const projected = messages.map((m, i) => {
|
|
112
|
+
if (i >= retainFrom) return m;
|
|
113
|
+
if (roleOf(m) !== "tool") return m;
|
|
114
|
+
if (opts.isProtectedMessage?.(m, i, messages.length)) {
|
|
115
|
+
return m;
|
|
116
|
+
}
|
|
117
|
+
const content = m.content;
|
|
118
|
+
if (!Array.isArray(content)) return m;
|
|
119
|
+
const names = toolNamesOf(m);
|
|
120
|
+
prunedCount += names.length;
|
|
121
|
+
return {
|
|
122
|
+
...m,
|
|
123
|
+
content: content.map(
|
|
124
|
+
(p) => p !== null && typeof p === "object" && p.type === "tool-result" ? {
|
|
125
|
+
...p,
|
|
126
|
+
result: formatPlaceholder(
|
|
127
|
+
typeof p.toolName === "string" ? p.toolName : "tool"
|
|
128
|
+
)
|
|
129
|
+
} : p
|
|
130
|
+
)
|
|
131
|
+
};
|
|
132
|
+
});
|
|
133
|
+
const afterPrune = estimateMessagesTokens(projected, countText) + overhead;
|
|
134
|
+
const needSummary = afterPrune > budget.triggerAt;
|
|
135
|
+
return {
|
|
136
|
+
messages: projected,
|
|
137
|
+
pruned: prunedCount > 0,
|
|
138
|
+
prunedCount,
|
|
139
|
+
estimatedPromptTokens: afterPrune,
|
|
140
|
+
summarizeUpToIndex: needSummary ? retainFrom - 1 : -1
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// src/context/sanitizer.ts
|
|
145
|
+
function roleOf2(m) {
|
|
146
|
+
return m?.role ?? "";
|
|
147
|
+
}
|
|
148
|
+
function trimOrphanToolMessages(messages, fallbackUserPrompt = "\uFF08\u4EE5\u4E0A\u662F\u6B64\u524D\u4F1A\u8BDD\u7684\u6458\u8981\uFF0C\u8BF7\u57FA\u4E8E\u6B64\u7EE7\u7EED\u5F53\u524D\u4EFB\u52A1\u3002\uFF09") {
|
|
149
|
+
let start = 0;
|
|
150
|
+
while (start < messages.length && roleOf2(messages[start]) === "tool") {
|
|
151
|
+
start++;
|
|
152
|
+
}
|
|
153
|
+
const trimmed = messages.slice(start);
|
|
154
|
+
if (trimmed.length === 0 || roleOf2(trimmed[0]) !== "user") {
|
|
155
|
+
return [
|
|
156
|
+
{
|
|
157
|
+
role: "user",
|
|
158
|
+
content: fallbackUserPrompt
|
|
159
|
+
},
|
|
160
|
+
...trimmed
|
|
161
|
+
];
|
|
162
|
+
}
|
|
163
|
+
return trimmed;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// src/context/summary.ts
|
|
167
|
+
function roleOf3(m) {
|
|
168
|
+
return m?.role ?? "";
|
|
169
|
+
}
|
|
170
|
+
function textOf(m) {
|
|
171
|
+
const content = m?.content;
|
|
172
|
+
if (typeof content === "string") return content;
|
|
173
|
+
if (Array.isArray(content)) {
|
|
174
|
+
return content.map(
|
|
175
|
+
(p) => p && typeof p === "object" && typeof p.text === "string" ? p.text : ""
|
|
176
|
+
).join("");
|
|
177
|
+
}
|
|
178
|
+
return "";
|
|
179
|
+
}
|
|
180
|
+
function serializeMessagesForSummary(messages, maxCharsPerMessage = 4e3) {
|
|
181
|
+
return messages.map((m) => {
|
|
182
|
+
const text = textOf(m);
|
|
183
|
+
const clipped = text.length > maxCharsPerMessage ? `${text.slice(0, maxCharsPerMessage)}\u2026` : text;
|
|
184
|
+
return `[${roleOf3(m)}] ${clipped}`;
|
|
185
|
+
}).join("\n\n");
|
|
186
|
+
}
|
|
187
|
+
var DEFAULT_SUMMARY_MAX_TOKENS = 2048;
|
|
188
|
+
function buildGenericSummaryPrompt(opts) {
|
|
189
|
+
const { covered, previousSummary, domainGuidelines, maxWords = 1200 } = opts;
|
|
190
|
+
const guidelinesBlock = domainGuidelines && domainGuidelines.length > 0 ? `
|
|
191
|
+
\u7279\u522B\u5173\u6CE8\u5E76\u5FC5\u987B\u4FDD\u7559\uFF1A
|
|
192
|
+
${domainGuidelines.map((g, i) => `${i + 1}. ${g}`).join("\n")}
|
|
193
|
+
` : "";
|
|
194
|
+
return `\u4F60\u662F\u4E00\u4E2A\u4F1A\u8BDD\u5386\u53F2\u538B\u7F29\u5668\u3002\u628A\u4E0B\u9762\u7684\u4F1A\u8BDD\u5386\u53F2\u538B\u7F29\u6210\u4E00\u4EFD\u8FDE\u8D2F\u7D27\u51D1\u7684\u4E2D\u6587\u6458\u8981\uFF08\u4E0D\u8D85\u8FC7 ${maxWords} \u5B57\uFF09\uFF0C\u4F9B\u540E\u7EED\u5BF9\u8BDD\u4F5C\u4E3A\u4E0A\u4E0B\u6587\u80CC\u666F\u4F7F\u7528\u3002
|
|
195
|
+
${guidelinesBlock}
|
|
196
|
+
\u5FC5\u987B\u4E22\u5F03\uFF1A\u5197\u4F59\u5DE5\u5177\u8C03\u7528\u7EC6\u8282\u3001\u5E95\u5C42\u4EE3\u7801/\u6570\u636E\u539F\u6587\u5B57\u8282\u3001\u91CD\u590D\u5BD2\u6684\u4E0E\u65E0\u610F\u4E49\u8FC7\u6E21\u3002
|
|
197
|
+
${previousSummary ? `
|
|
198
|
+
\u6B64\u524D\u7684\u5386\u53F2\u6458\u8981\uFF08\u8BF7\u5728\u5176\u57FA\u7840\u4E0A\u589E\u91CF\u5408\u5E76\u66F4\u65B0\uFF0C\u907F\u514D\u9057\u6F0F\u5173\u952E\u7ED3\u8BBA\uFF09\uFF1A
|
|
199
|
+
${previousSummary}
|
|
200
|
+
` : ""}
|
|
201
|
+
\u9700\u8981\u538B\u7F29\u7684\u4F1A\u8BDD\u7247\u6BB5\uFF1A
|
|
202
|
+
${serializeMessagesForSummary(covered)}`;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// src/context/engine.ts
|
|
206
|
+
var ContextEngine = class {
|
|
207
|
+
constructor(options = {}) {
|
|
208
|
+
this.options = options;
|
|
209
|
+
}
|
|
210
|
+
options;
|
|
211
|
+
/**
|
|
212
|
+
* 解析指定模型上下文窗口大小
|
|
213
|
+
*/
|
|
214
|
+
resolveWindow(model, clientHint) {
|
|
215
|
+
return resolveContextWindow(model, clientHint, this.options.catalog);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* 计算指定窗口的保留水位预算
|
|
219
|
+
*/
|
|
220
|
+
computeBudget(window, maxOutputTokens = 4096, reserveRatio = 0.25) {
|
|
221
|
+
return computeContextBudget(window, maxOutputTokens, reserveRatio);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* 执行消息投影与第一道 Pruning
|
|
225
|
+
*/
|
|
226
|
+
project(opts) {
|
|
227
|
+
return projectMessagesWithPruning({
|
|
228
|
+
...opts,
|
|
229
|
+
tokenizer: this.options.tokenizer,
|
|
230
|
+
isProtectedMessage: this.options.isProtectedMessage,
|
|
231
|
+
placeholderFormatter: this.options.placeholderFormatter
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* 净化摘要/截断后的消息边界,移除孤儿工具结果并确保首条为 user
|
|
236
|
+
*/
|
|
237
|
+
trimBoundary(messages, fallbackUserPrompt) {
|
|
238
|
+
return trimOrphanToolMessages(messages, fallbackUserPrompt);
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
|
|
242
|
+
export {
|
|
243
|
+
resolveContextWindow,
|
|
244
|
+
computeContextBudget,
|
|
245
|
+
estimateMessageTokens,
|
|
246
|
+
estimateMessagesTokens,
|
|
247
|
+
DEFAULT_PRUNED_PLACEHOLDER,
|
|
248
|
+
projectMessagesWithPruning,
|
|
249
|
+
trimOrphanToolMessages,
|
|
250
|
+
serializeMessagesForSummary,
|
|
251
|
+
DEFAULT_SUMMARY_MAX_TOKENS,
|
|
252
|
+
buildGenericSummaryPrompt,
|
|
253
|
+
ContextEngine
|
|
254
|
+
};
|
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
import {
|
|
2
|
+
DEFAULT_QUOTA_WINDOW_MS
|
|
3
|
+
} from "./chunk-RYIWJPIR.js";
|
|
4
|
+
|
|
5
|
+
// src/pipeline/pipeline.ts
|
|
6
|
+
var HarnessPipeline = class {
|
|
7
|
+
middlewares = [];
|
|
8
|
+
/**
|
|
9
|
+
* 注册中间件
|
|
10
|
+
*/
|
|
11
|
+
use(middleware) {
|
|
12
|
+
if (typeof middleware === "function") {
|
|
13
|
+
this.middlewares.push(middleware);
|
|
14
|
+
} else if (typeof middleware?.execute === "function") {
|
|
15
|
+
this.middlewares.push(middleware.execute.bind(middleware));
|
|
16
|
+
}
|
|
17
|
+
return this;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* 按序执行洋葱模型流水线
|
|
21
|
+
*/
|
|
22
|
+
async run(ctx) {
|
|
23
|
+
let index = -1;
|
|
24
|
+
const dispatch = async (i) => {
|
|
25
|
+
if (i <= index) {
|
|
26
|
+
throw new Error("next() called multiple times in middleware");
|
|
27
|
+
}
|
|
28
|
+
index = i;
|
|
29
|
+
const fn = this.middlewares[i];
|
|
30
|
+
if (!fn) return;
|
|
31
|
+
await fn(ctx, () => dispatch(i + 1));
|
|
32
|
+
};
|
|
33
|
+
await dispatch(0);
|
|
34
|
+
}
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// src/pipeline/middlewares/credentialGuard.ts
|
|
38
|
+
function createCredentialGuardMiddleware(options) {
|
|
39
|
+
return async (ctx, next) => {
|
|
40
|
+
const { clientKey, clientBaseURL, resiliencePolicy } = options;
|
|
41
|
+
if (clientBaseURL && !clientKey) {
|
|
42
|
+
ctx.telemetry.emit({
|
|
43
|
+
type: "warn",
|
|
44
|
+
runId: ctx.runId,
|
|
45
|
+
sessionId: ctx.sessionId,
|
|
46
|
+
code: "CRED_GUARD_REJECTED",
|
|
47
|
+
detail: "\u81EA\u5B9A\u4E49 baseURL \u65F6\u672A\u63D0\u4F9B apiKey\uFF0C\u62D2\u7EDD\u4EE5\u73AF\u5883\u51ED\u8BC1\u8BF7\u6C42\u4EFB\u610F URL"
|
|
48
|
+
});
|
|
49
|
+
ctx.response = Response.json(
|
|
50
|
+
{ error: "\u81EA\u5B9A\u4E49 baseURL \u65F6\u5FC5\u987B\u540C\u65F6\u63D0\u4F9B apiKey\uFF08\u4E0D\u5141\u8BB8\u4E0E\u670D\u52A1\u7AEF\u73AF\u5883\u51ED\u8BC1\u6DF7\u7528\uFF09" },
|
|
51
|
+
{ status: 400 }
|
|
52
|
+
);
|
|
53
|
+
return;
|
|
54
|
+
}
|
|
55
|
+
if (resiliencePolicy?.fallbacks && resiliencePolicy.fallbacks.length > 0) {
|
|
56
|
+
const primaryBase = (ctx.modelSpec.baseURL ?? "https://api.openai.com/v1").replace(
|
|
57
|
+
/\/+$/,
|
|
58
|
+
""
|
|
59
|
+
);
|
|
60
|
+
for (const fb of resiliencePolicy.fallbacks) {
|
|
61
|
+
const effectiveBase = (fb.baseURL ?? ctx.modelSpec.baseURL ?? "").replace(
|
|
62
|
+
/\/+$/,
|
|
63
|
+
""
|
|
64
|
+
);
|
|
65
|
+
if (effectiveBase && effectiveBase !== primaryBase && !fb.apiKey) {
|
|
66
|
+
ctx.telemetry.emit({
|
|
67
|
+
type: "warn",
|
|
68
|
+
runId: ctx.runId,
|
|
69
|
+
sessionId: ctx.sessionId,
|
|
70
|
+
code: "CRED_GUARD_REJECTED",
|
|
71
|
+
detail: `fallback \u6A21\u578B ${fb.model} \u6307\u5411\u65B0 baseURL \u4F46\u672A\u63D0\u4F9B apiKey\uFF0C\u62D2\u7EDD\u4EE5\u4E3B\u8BF7\u6C42\u51ED\u8BC1\u8BF7\u6C42`
|
|
72
|
+
});
|
|
73
|
+
ctx.response = Response.json(
|
|
74
|
+
{ error: "fallback \u6A21\u578B\u6307\u5411\u65B0 baseURL \u65F6\u5FC5\u987B\u81EA\u5E26 apiKey\uFF08\u4E0D\u5141\u8BB8\u4E0E\u670D\u52A1\u7AEF\u73AF\u5883\u51ED\u8BC1\u6DF7\u7528\uFF09" },
|
|
75
|
+
{ status: 400 }
|
|
76
|
+
);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
await next();
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// src/pipeline/middlewares/concurrencyGate.ts
|
|
86
|
+
function createConcurrencyGateMiddleware(options) {
|
|
87
|
+
return async (ctx, next) => {
|
|
88
|
+
const { streamHub, maxConcurrentTasks, isReconnect } = options;
|
|
89
|
+
if (!isReconnect && ctx.sessionId) {
|
|
90
|
+
const running = await streamHub.runningCount();
|
|
91
|
+
if (running >= maxConcurrentTasks) {
|
|
92
|
+
ctx.telemetry.emit({
|
|
93
|
+
type: "warn",
|
|
94
|
+
runId: ctx.runId,
|
|
95
|
+
sessionId: ctx.sessionId,
|
|
96
|
+
code: "CONCURRENCY_REJECTED",
|
|
97
|
+
detail: `running \u4EFB\u52A1\u6570\u5DF2\u8FBE\u4E0A\u9650 ${maxConcurrentTasks},\u62D2\u7EDD\u65B0\u4EFB\u52A1`
|
|
98
|
+
});
|
|
99
|
+
ctx.response = Response.json(
|
|
100
|
+
{ error: "\u670D\u52A1\u7AEF\u5206\u6790\u4EFB\u52A1\u5E76\u53D1\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" },
|
|
101
|
+
{ status: 429 }
|
|
102
|
+
);
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
await next();
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// src/pipeline/middlewares/tenantQuota.ts
|
|
111
|
+
function createTenantQuotaMiddleware(options) {
|
|
112
|
+
return async (ctx, next) => {
|
|
113
|
+
const { costLedger, quota, isReconnect } = options;
|
|
114
|
+
if (quota?.tenantTokenLimit && costLedger && !isReconnect) {
|
|
115
|
+
const windowMs = quota.windowMs ?? DEFAULT_QUOTA_WINDOW_MS;
|
|
116
|
+
const windowUsage = await costLedger.sumUsage(ctx.tenantId, windowMs);
|
|
117
|
+
if (windowUsage.tokens >= quota.tenantTokenLimit) {
|
|
118
|
+
ctx.telemetry.emit({
|
|
119
|
+
type: "warn",
|
|
120
|
+
runId: ctx.runId,
|
|
121
|
+
sessionId: ctx.sessionId,
|
|
122
|
+
code: "QUOTA_EXCEEDED",
|
|
123
|
+
detail: `\u79DF\u6237 ${ctx.tenantId} \u6EDA\u52A8\u7A97\u7D2F\u8BA1 ${windowUsage.tokens} tokens \u5DF2\u8FBE\u4E0A\u9650 ${quota.tenantTokenLimit},\u62D2\u7EDD\u65B0\u4EFB\u52A1`
|
|
124
|
+
});
|
|
125
|
+
ctx.response = Response.json(
|
|
126
|
+
{ error: "\u79DF\u6237\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" },
|
|
127
|
+
{ status: 429 }
|
|
128
|
+
);
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
await next();
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/guardrails/autoHealing.ts
|
|
137
|
+
var AutoHealingGuardrail = class {
|
|
138
|
+
maxRounds;
|
|
139
|
+
telemetry;
|
|
140
|
+
runId;
|
|
141
|
+
sessionId;
|
|
142
|
+
constructor(options = {}) {
|
|
143
|
+
this.maxRounds = options.maxRounds ?? 1;
|
|
144
|
+
this.telemetry = options.telemetry;
|
|
145
|
+
this.runId = options.runId;
|
|
146
|
+
this.sessionId = options.sessionId;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* 执行自愈防护:
|
|
150
|
+
* 1. 优先校验当前文本;
|
|
151
|
+
* 2. 若合法直接返回(零额外开销);
|
|
152
|
+
* 3. 若有语法错误,向 healer 申请定向修复,并在轮数内迭代确认。
|
|
153
|
+
*/
|
|
154
|
+
async enforce(initialText, validator, healer) {
|
|
155
|
+
let currentText = initialText;
|
|
156
|
+
let round = 0;
|
|
157
|
+
while (round <= this.maxRounds) {
|
|
158
|
+
const check = validator.validate(currentText);
|
|
159
|
+
if (check.ok) {
|
|
160
|
+
return {
|
|
161
|
+
text: currentText,
|
|
162
|
+
healed: round > 0,
|
|
163
|
+
finalValid: true
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
if (round >= this.maxRounds) {
|
|
167
|
+
this.telemetry?.emit({
|
|
168
|
+
type: "warn",
|
|
169
|
+
runId: this.runId ?? "auto-healing",
|
|
170
|
+
sessionId: this.sessionId,
|
|
171
|
+
code: "AUTO_HEALING_EXHAUSTED",
|
|
172
|
+
detail: `[${validator.name}] \u81EA\u6108\u5C1D\u8BD5 ${this.maxRounds} \u8F6E\u540E\u4ECD\u5B58\u5728\u8BED\u6CD5\u9519\u8BEF: ${check.errors.join("; ")}`
|
|
173
|
+
});
|
|
174
|
+
return {
|
|
175
|
+
text: currentText,
|
|
176
|
+
healed: round > 0,
|
|
177
|
+
finalValid: false
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
round++;
|
|
181
|
+
this.telemetry?.emit({
|
|
182
|
+
type: "warn",
|
|
183
|
+
runId: this.runId ?? "auto-healing",
|
|
184
|
+
sessionId: this.sessionId,
|
|
185
|
+
code: "AUTO_HEALING_TRIGGERED",
|
|
186
|
+
detail: `[${validator.name}] \u68C0\u6D4B\u5230\u8BED\u6CD5\u7F3A\u9677\uFF0C\u89E6\u53D1\u7B2C ${round} \u8F6E\u5B9A\u5411\u81EA\u6108: ${check.errors.join("; ")}`
|
|
187
|
+
});
|
|
188
|
+
const fixPrompt = validator.buildFixPrompt(currentText, check.errors);
|
|
189
|
+
try {
|
|
190
|
+
currentText = await healer(fixPrompt);
|
|
191
|
+
} catch (err) {
|
|
192
|
+
this.telemetry?.emit({
|
|
193
|
+
type: "warn",
|
|
194
|
+
runId: this.runId ?? "auto-healing",
|
|
195
|
+
sessionId: this.sessionId,
|
|
196
|
+
code: "AUTO_HEALING_FAILED",
|
|
197
|
+
detail: `[${validator.name}] \u81EA\u6108\u5FAE\u5FAA\u73AF\u8BF7\u6C42\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`
|
|
198
|
+
});
|
|
199
|
+
return {
|
|
200
|
+
text: currentText,
|
|
201
|
+
healed: false,
|
|
202
|
+
finalValid: false
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
text: currentText,
|
|
208
|
+
healed: false,
|
|
209
|
+
finalValid: false
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
// src/pipeline/middlewares/autoHealingGuardrail.ts
|
|
215
|
+
function createAutoHealingMiddleware(options) {
|
|
216
|
+
return async (ctx, next) => {
|
|
217
|
+
await next();
|
|
218
|
+
const rawText = ctx.state.finalText;
|
|
219
|
+
if (typeof rawText !== "string" || !rawText) {
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
const guardrail = new AutoHealingGuardrail({
|
|
223
|
+
maxRounds: options.maxRounds ?? 1,
|
|
224
|
+
telemetry: ctx.telemetry,
|
|
225
|
+
runId: ctx.runId,
|
|
226
|
+
sessionId: ctx.sessionId
|
|
227
|
+
});
|
|
228
|
+
const result = await guardrail.enforce(rawText, options.validator, options.healer);
|
|
229
|
+
if (result.healed) {
|
|
230
|
+
ctx.state.finalText = result.text;
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// src/pipeline/budgetController.ts
|
|
236
|
+
var ExecutionBudgetExceededError = class extends Error {
|
|
237
|
+
constructor(reason) {
|
|
238
|
+
super(`Execution budget exceeded: ${reason}`);
|
|
239
|
+
this.reason = reason;
|
|
240
|
+
this.name = "ExecutionBudgetExceededError";
|
|
241
|
+
}
|
|
242
|
+
reason;
|
|
243
|
+
};
|
|
244
|
+
var ExecutionBudgetController = class {
|
|
245
|
+
constructor(config = {}) {
|
|
246
|
+
this.config = config;
|
|
247
|
+
this.maxSteps = Math.min(Math.max(Math.round(config.maxSteps ?? 25), 1), 100);
|
|
248
|
+
this.tokenBudget = Math.min(
|
|
249
|
+
Math.max(Math.round(config.tokenBudget ?? 2e5), 1e4),
|
|
250
|
+
5e6
|
|
251
|
+
);
|
|
252
|
+
this.timeoutMs = config.timeoutMs;
|
|
253
|
+
this._startTime = Date.now();
|
|
254
|
+
this._abortController = new AbortController();
|
|
255
|
+
if (this.timeoutMs && this.timeoutMs > 0) {
|
|
256
|
+
this._timer = setTimeout(() => {
|
|
257
|
+
this.triggerExceeded(`\u4EFB\u52A1\u6267\u884C\u8017\u65F6\u8D85\u8FC7\u4E0A\u9650 ${this.timeoutMs}ms`);
|
|
258
|
+
}, this.timeoutMs);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
config;
|
|
262
|
+
maxSteps;
|
|
263
|
+
tokenBudget;
|
|
264
|
+
timeoutMs;
|
|
265
|
+
_steps = 0;
|
|
266
|
+
_tokens = 0;
|
|
267
|
+
_startTime;
|
|
268
|
+
_isExceeded = false;
|
|
269
|
+
_exceededReason;
|
|
270
|
+
_abortController;
|
|
271
|
+
_timer;
|
|
272
|
+
get steps() {
|
|
273
|
+
return this._steps;
|
|
274
|
+
}
|
|
275
|
+
get tokens() {
|
|
276
|
+
return this._tokens;
|
|
277
|
+
}
|
|
278
|
+
get durationMs() {
|
|
279
|
+
return Date.now() - this._startTime;
|
|
280
|
+
}
|
|
281
|
+
get isExceeded() {
|
|
282
|
+
return this._isExceeded;
|
|
283
|
+
}
|
|
284
|
+
get exceededReason() {
|
|
285
|
+
return this._exceededReason;
|
|
286
|
+
}
|
|
287
|
+
get signal() {
|
|
288
|
+
return this._abortController.signal;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* 记录新执行的一步,若步数超出 maxSteps 则触发熔断
|
|
292
|
+
*/
|
|
293
|
+
recordStep() {
|
|
294
|
+
this._steps++;
|
|
295
|
+
if (!this._isExceeded && this._steps > this.maxSteps) {
|
|
296
|
+
this.triggerExceeded(`\u6267\u884C\u6B65\u6570\u8FBE\u5230\u4E0A\u9650 ${this.maxSteps} \u6B65`);
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
exceeded: this._isExceeded,
|
|
300
|
+
reason: this._exceededReason
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* 记录消耗的 Token,若累计超出 tokenBudget 则触发熔断
|
|
305
|
+
*/
|
|
306
|
+
recordUsage(usage) {
|
|
307
|
+
const delta = typeof usage === "number" ? usage : (usage.promptTokens ?? 0) + (usage.completionTokens ?? 0);
|
|
308
|
+
this._tokens += Math.max(0, delta);
|
|
309
|
+
if (!this._isExceeded && this._tokens > this.tokenBudget) {
|
|
310
|
+
this.triggerExceeded(
|
|
311
|
+
`\u7D2F\u8BA1\u6D88\u8017 ${this._tokens} tokens \u8D85\u51FA\u9884\u7B97\u4E0A\u9650 ${this.tokenBudget}`
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
return {
|
|
315
|
+
exceeded: this._isExceeded,
|
|
316
|
+
reason: this._exceededReason
|
|
317
|
+
};
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* 外部显式中止或由超时触发
|
|
321
|
+
*/
|
|
322
|
+
triggerExceeded(reason) {
|
|
323
|
+
if (this._isExceeded) return;
|
|
324
|
+
this._isExceeded = true;
|
|
325
|
+
this._exceededReason = reason;
|
|
326
|
+
if (this._timer) {
|
|
327
|
+
clearTimeout(this._timer);
|
|
328
|
+
this._timer = void 0;
|
|
329
|
+
}
|
|
330
|
+
this.config.onExceeded?.(reason, {
|
|
331
|
+
steps: this._steps,
|
|
332
|
+
tokens: this._tokens,
|
|
333
|
+
durationMs: this.durationMs
|
|
334
|
+
});
|
|
335
|
+
this._abortController.abort(new ExecutionBudgetExceededError(reason));
|
|
336
|
+
}
|
|
337
|
+
/**
|
|
338
|
+
* 任务完成时释放计时器
|
|
339
|
+
*/
|
|
340
|
+
dispose() {
|
|
341
|
+
if (this._timer) {
|
|
342
|
+
clearTimeout(this._timer);
|
|
343
|
+
this._timer = void 0;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
|
|
348
|
+
export {
|
|
349
|
+
HarnessPipeline,
|
|
350
|
+
createCredentialGuardMiddleware,
|
|
351
|
+
createConcurrencyGateMiddleware,
|
|
352
|
+
createTenantQuotaMiddleware,
|
|
353
|
+
AutoHealingGuardrail,
|
|
354
|
+
createAutoHealingMiddleware,
|
|
355
|
+
ExecutionBudgetExceededError,
|
|
356
|
+
ExecutionBudgetController
|
|
357
|
+
};
|