@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/dist/pipeline.js CHANGED
@@ -1,351 +1,15 @@
1
- // src/pipeline/pipeline.ts
2
- var HarnessPipeline = class {
3
- middlewares = [];
4
- /**
5
- * 注册中间件
6
- */
7
- use(middleware) {
8
- if (typeof middleware === "function") {
9
- this.middlewares.push(middleware);
10
- } else if (typeof middleware?.execute === "function") {
11
- this.middlewares.push(middleware.execute.bind(middleware));
12
- }
13
- return this;
14
- }
15
- /**
16
- * 按序执行洋葱模型流水线
17
- */
18
- async run(ctx) {
19
- let index = -1;
20
- const dispatch = async (i) => {
21
- if (i <= index) {
22
- throw new Error("next() called multiple times in middleware");
23
- }
24
- index = i;
25
- const fn = this.middlewares[i];
26
- if (!fn) return;
27
- await fn(ctx, () => dispatch(i + 1));
28
- };
29
- await dispatch(0);
30
- }
31
- };
32
-
33
- // src/pipeline/middlewares/credentialGuard.ts
34
- function createCredentialGuardMiddleware(options) {
35
- return async (ctx, next) => {
36
- const { clientKey, clientBaseURL, resiliencePolicy } = options;
37
- if (clientBaseURL && !clientKey) {
38
- ctx.telemetry.emit({
39
- type: "warn",
40
- runId: ctx.runId,
41
- sessionId: ctx.sessionId,
42
- code: "CRED_GUARD_REJECTED",
43
- detail: "\u81EA\u5B9A\u4E49 baseURL \u65F6\u672A\u63D0\u4F9B apiKey\uFF0C\u62D2\u7EDD\u4EE5\u73AF\u5883\u51ED\u8BC1\u8BF7\u6C42\u4EFB\u610F URL"
44
- });
45
- ctx.response = Response.json(
46
- { 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" },
47
- { status: 400 }
48
- );
49
- return;
50
- }
51
- if (resiliencePolicy?.fallbacks && resiliencePolicy.fallbacks.length > 0) {
52
- const primaryBase = (ctx.modelSpec.baseURL ?? "https://api.openai.com/v1").replace(
53
- /\/+$/,
54
- ""
55
- );
56
- for (const fb of resiliencePolicy.fallbacks) {
57
- const effectiveBase = (fb.baseURL ?? ctx.modelSpec.baseURL ?? "").replace(
58
- /\/+$/,
59
- ""
60
- );
61
- if (effectiveBase && effectiveBase !== primaryBase && !fb.apiKey) {
62
- ctx.telemetry.emit({
63
- type: "warn",
64
- runId: ctx.runId,
65
- sessionId: ctx.sessionId,
66
- code: "CRED_GUARD_REJECTED",
67
- 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`
68
- });
69
- ctx.response = Response.json(
70
- { 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" },
71
- { status: 400 }
72
- );
73
- return;
74
- }
75
- }
76
- }
77
- await next();
78
- };
79
- }
80
-
81
- // src/pipeline/middlewares/concurrencyGate.ts
82
- function createConcurrencyGateMiddleware(options) {
83
- return async (ctx, next) => {
84
- const { streamHub, maxConcurrentTasks, isReconnect } = options;
85
- if (!isReconnect && ctx.sessionId) {
86
- const running = await streamHub.runningCount();
87
- if (running >= maxConcurrentTasks) {
88
- ctx.telemetry.emit({
89
- type: "warn",
90
- runId: ctx.runId,
91
- sessionId: ctx.sessionId,
92
- code: "CONCURRENCY_REJECTED",
93
- detail: `running \u4EFB\u52A1\u6570\u5DF2\u8FBE\u4E0A\u9650 ${maxConcurrentTasks},\u62D2\u7EDD\u65B0\u4EFB\u52A1`
94
- });
95
- ctx.response = Response.json(
96
- { error: "\u670D\u52A1\u7AEF\u5206\u6790\u4EFB\u52A1\u5E76\u53D1\u5DF2\u8FBE\u4E0A\u9650\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" },
97
- { status: 429 }
98
- );
99
- return;
100
- }
101
- }
102
- await next();
103
- };
104
- }
105
-
106
- // src/finops/costLedger.ts
107
- import fs from "fs";
108
- import path from "path";
109
- var DEFAULT_QUOTA_WINDOW_MS = 864e5;
110
- var PRICING_PATH_DEFAULT = path.join(process.cwd(), "config", "model-pricing.json");
111
-
112
- // src/pipeline/middlewares/tenantQuota.ts
113
- function createTenantQuotaMiddleware(options) {
114
- return async (ctx, next) => {
115
- const { costLedger, quota, isReconnect } = options;
116
- if (quota?.tenantTokenLimit && costLedger && !isReconnect) {
117
- const windowMs = quota.windowMs ?? DEFAULT_QUOTA_WINDOW_MS;
118
- const windowUsage = await costLedger.sumUsage(ctx.tenantId, windowMs);
119
- if (windowUsage.tokens >= quota.tenantTokenLimit) {
120
- ctx.telemetry.emit({
121
- type: "warn",
122
- runId: ctx.runId,
123
- sessionId: ctx.sessionId,
124
- code: "QUOTA_EXCEEDED",
125
- detail: `\u79DF\u6237 ${ctx.tenantId} \u6EDA\u52A8\u7A97\u7D2F\u8BA1 ${windowUsage.tokens} tokens \u5DF2\u8FBE\u4E0A\u9650 ${quota.tenantTokenLimit},\u62D2\u7EDD\u65B0\u4EFB\u52A1`
126
- });
127
- ctx.response = Response.json(
128
- { error: "\u79DF\u6237\u989D\u5EA6\u5DF2\u7528\u5C3D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5" },
129
- { status: 429 }
130
- );
131
- return;
132
- }
133
- }
134
- await next();
135
- };
136
- }
137
-
138
- // src/guardrails/autoHealing.ts
139
- var AutoHealingGuardrail = class {
140
- maxRounds;
141
- telemetry;
142
- runId;
143
- sessionId;
144
- constructor(options = {}) {
145
- this.maxRounds = options.maxRounds ?? 1;
146
- this.telemetry = options.telemetry;
147
- this.runId = options.runId;
148
- this.sessionId = options.sessionId;
149
- }
150
- /**
151
- * 执行自愈防护:
152
- * 1. 优先校验当前文本;
153
- * 2. 若合法直接返回(零额外开销);
154
- * 3. 若有语法错误,向 healer 申请定向修复,并在轮数内迭代确认。
155
- */
156
- async enforce(initialText, validator, healer) {
157
- let currentText = initialText;
158
- let round = 0;
159
- while (round <= this.maxRounds) {
160
- const check = validator.validate(currentText);
161
- if (check.ok) {
162
- return {
163
- text: currentText,
164
- healed: round > 0,
165
- finalValid: true
166
- };
167
- }
168
- if (round >= this.maxRounds) {
169
- this.telemetry?.emit({
170
- type: "warn",
171
- runId: this.runId ?? "auto-healing",
172
- sessionId: this.sessionId,
173
- code: "AUTO_HEALING_EXHAUSTED",
174
- detail: `[${validator.name}] \u81EA\u6108\u5C1D\u8BD5 ${this.maxRounds} \u8F6E\u540E\u4ECD\u5B58\u5728\u8BED\u6CD5\u9519\u8BEF: ${check.errors.join("; ")}`
175
- });
176
- return {
177
- text: currentText,
178
- healed: round > 0,
179
- finalValid: false
180
- };
181
- }
182
- round++;
183
- this.telemetry?.emit({
184
- type: "warn",
185
- runId: this.runId ?? "auto-healing",
186
- sessionId: this.sessionId,
187
- code: "AUTO_HEALING_TRIGGERED",
188
- detail: `[${validator.name}] \u68C0\u6D4B\u5230\u8BED\u6CD5\u7F3A\u9677\uFF0C\u89E6\u53D1\u7B2C ${round} \u8F6E\u5B9A\u5411\u81EA\u6108: ${check.errors.join("; ")}`
189
- });
190
- const fixPrompt = validator.buildFixPrompt(currentText, check.errors);
191
- try {
192
- currentText = await healer(fixPrompt);
193
- } catch (err) {
194
- this.telemetry?.emit({
195
- type: "warn",
196
- runId: this.runId ?? "auto-healing",
197
- sessionId: this.sessionId,
198
- code: "AUTO_HEALING_FAILED",
199
- detail: `[${validator.name}] \u81EA\u6108\u5FAE\u5FAA\u73AF\u8BF7\u6C42\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`
200
- });
201
- return {
202
- text: currentText,
203
- healed: false,
204
- finalValid: false
205
- };
206
- }
207
- }
208
- return {
209
- text: currentText,
210
- healed: false,
211
- finalValid: false
212
- };
213
- }
214
- };
215
-
216
- // src/pipeline/middlewares/autoHealingGuardrail.ts
217
- function createAutoHealingMiddleware(options) {
218
- return async (ctx, next) => {
219
- await next();
220
- const rawText = ctx.state.finalText;
221
- if (typeof rawText !== "string" || !rawText) {
222
- return;
223
- }
224
- const guardrail = new AutoHealingGuardrail({
225
- maxRounds: options.maxRounds ?? 1,
226
- telemetry: ctx.telemetry,
227
- runId: ctx.runId,
228
- sessionId: ctx.sessionId
229
- });
230
- const result = await guardrail.enforce(rawText, options.validator, options.healer);
231
- if (result.healed) {
232
- ctx.state.finalText = result.text;
233
- }
234
- };
235
- }
236
-
237
- // src/pipeline/budgetController.ts
238
- var ExecutionBudgetExceededError = class extends Error {
239
- constructor(reason) {
240
- super(`Execution budget exceeded: ${reason}`);
241
- this.reason = reason;
242
- this.name = "ExecutionBudgetExceededError";
243
- }
244
- reason;
245
- };
246
- var ExecutionBudgetController = class {
247
- constructor(config = {}) {
248
- this.config = config;
249
- this.maxSteps = Math.min(Math.max(Math.round(config.maxSteps ?? 25), 1), 100);
250
- this.tokenBudget = Math.min(
251
- Math.max(Math.round(config.tokenBudget ?? 2e5), 1e4),
252
- 5e6
253
- );
254
- this.timeoutMs = config.timeoutMs;
255
- this._startTime = Date.now();
256
- this._abortController = new AbortController();
257
- if (this.timeoutMs && this.timeoutMs > 0) {
258
- this._timer = setTimeout(() => {
259
- this.triggerExceeded(`\u4EFB\u52A1\u6267\u884C\u8017\u65F6\u8D85\u8FC7\u4E0A\u9650 ${this.timeoutMs}ms`);
260
- }, this.timeoutMs);
261
- }
262
- }
263
- config;
264
- maxSteps;
265
- tokenBudget;
266
- timeoutMs;
267
- _steps = 0;
268
- _tokens = 0;
269
- _startTime;
270
- _isExceeded = false;
271
- _exceededReason;
272
- _abortController;
273
- _timer;
274
- get steps() {
275
- return this._steps;
276
- }
277
- get tokens() {
278
- return this._tokens;
279
- }
280
- get durationMs() {
281
- return Date.now() - this._startTime;
282
- }
283
- get isExceeded() {
284
- return this._isExceeded;
285
- }
286
- get exceededReason() {
287
- return this._exceededReason;
288
- }
289
- get signal() {
290
- return this._abortController.signal;
291
- }
292
- /**
293
- * 记录新执行的一步,若步数超出 maxSteps 则触发熔断
294
- */
295
- recordStep() {
296
- this._steps++;
297
- if (!this._isExceeded && this._steps > this.maxSteps) {
298
- this.triggerExceeded(`\u6267\u884C\u6B65\u6570\u8FBE\u5230\u4E0A\u9650 ${this.maxSteps} \u6B65`);
299
- }
300
- return {
301
- exceeded: this._isExceeded,
302
- reason: this._exceededReason
303
- };
304
- }
305
- /**
306
- * 记录消耗的 Token,若累计超出 tokenBudget 则触发熔断
307
- */
308
- recordUsage(usage) {
309
- const delta = typeof usage === "number" ? usage : (usage.promptTokens ?? 0) + (usage.completionTokens ?? 0);
310
- this._tokens += Math.max(0, delta);
311
- if (!this._isExceeded && this._tokens > this.tokenBudget) {
312
- this.triggerExceeded(
313
- `\u7D2F\u8BA1\u6D88\u8017 ${this._tokens} tokens \u8D85\u51FA\u9884\u7B97\u4E0A\u9650 ${this.tokenBudget}`
314
- );
315
- }
316
- return {
317
- exceeded: this._isExceeded,
318
- reason: this._exceededReason
319
- };
320
- }
321
- /**
322
- * 外部显式中止或由超时触发
323
- */
324
- triggerExceeded(reason) {
325
- if (this._isExceeded) return;
326
- this._isExceeded = true;
327
- this._exceededReason = reason;
328
- if (this._timer) {
329
- clearTimeout(this._timer);
330
- this._timer = void 0;
331
- }
332
- this.config.onExceeded?.(reason, {
333
- steps: this._steps,
334
- tokens: this._tokens,
335
- durationMs: this.durationMs
336
- });
337
- this._abortController.abort(new ExecutionBudgetExceededError(reason));
338
- }
339
- /**
340
- * 任务完成时释放计时器
341
- */
342
- dispose() {
343
- if (this._timer) {
344
- clearTimeout(this._timer);
345
- this._timer = void 0;
346
- }
347
- }
348
- };
1
+ import {
2
+ ExecutionBudgetController,
3
+ ExecutionBudgetExceededError,
4
+ HarnessPipeline,
5
+ createAutoHealingMiddleware,
6
+ createConcurrencyGateMiddleware,
7
+ createCredentialGuardMiddleware,
8
+ createTenantQuotaMiddleware
9
+ } from "./chunk-OEJYZ6IB.js";
10
+ import "./chunk-RYIWJPIR.js";
11
+ import "./chunk-HYD33JX5.js";
12
+ import "./chunk-6OYMWYZS.js";
349
13
  export {
350
14
  ExecutionBudgetController,
351
15
  ExecutionBudgetExceededError,
package/dist/registry.js CHANGED
@@ -1,14 +1,14 @@
1
- // src/providers/registry.ts
2
1
  import {
3
- DEFAULT_MODEL_WINDOW_MAP,
4
- CONTEXT_WINDOW_MIN,
5
2
  CONTEXT_WINDOW_MAX,
3
+ CONTEXT_WINDOW_MIN,
6
4
  DEFAULT_CONTEXT_WINDOW,
7
- isReasoningModel,
5
+ DEFAULT_MODEL_WINDOW_MAP,
8
6
  ModelCatalogRegistry,
9
7
  defaultModelCatalog,
8
+ isReasoningModel,
10
9
  resolveContextWindow
11
- } from "@ginkgolab/models";
10
+ } from "./chunk-ZO2UWHNE.js";
11
+ import "./chunk-6OYMWYZS.js";
12
12
  export {
13
13
  CONTEXT_WINDOW_MAX,
14
14
  CONTEXT_WINDOW_MIN,