@lynn123411/dsh-subagent-judge-dispatch 0.6.13 → 0.6.15
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 +13 -9
- package/cordis.patch.yml +0 -8
- package/lib/client.js +148 -202
- package/lib/client.js.map +3 -3
- package/lib/index.js +213 -119
- package/lib/index.js.map +3 -3
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -74,8 +74,7 @@ function matchingCall(data, label) {
|
|
|
74
74
|
if (typeof call?.description !== "string" || call.description.trim() !== label || typeof call.prompt !== "string" || call.prompt.trim() === "") return void 0;
|
|
75
75
|
return {
|
|
76
76
|
label,
|
|
77
|
-
text: call.prompt.trim()
|
|
78
|
-
explicitRoute: call.provider !== void 0 || call.model !== void 0 || call.reasoning_effort !== void 0
|
|
77
|
+
text: call.prompt.trim()
|
|
79
78
|
};
|
|
80
79
|
}
|
|
81
80
|
function outstandingDelegation(events, label, resumedChildId) {
|
|
@@ -138,13 +137,14 @@ async function resolveRootSessionId(startId, lookup) {
|
|
|
138
137
|
let current = startId;
|
|
139
138
|
for (let hop = 0; hop < 32; hop += 1) {
|
|
140
139
|
const header = await lookup(current);
|
|
141
|
-
if (header
|
|
140
|
+
if (header?.id !== current) return void 0;
|
|
141
|
+
if (header.origin !== "subagent" && (header.delegationDepth ?? 0) < 1) return current;
|
|
142
142
|
const parent = header.parentSession;
|
|
143
|
-
if (typeof parent !== "string" || parent === "" || seen.has(parent)) return
|
|
143
|
+
if (typeof parent !== "string" || parent === "" || seen.has(parent)) return void 0;
|
|
144
144
|
seen.add(parent);
|
|
145
145
|
current = parent;
|
|
146
146
|
}
|
|
147
|
-
return
|
|
147
|
+
return void 0;
|
|
148
148
|
}
|
|
149
149
|
|
|
150
150
|
// src/server/judge-budget.ts
|
|
@@ -168,7 +168,6 @@ var JudgeBudget = class {
|
|
|
168
168
|
this.expired();
|
|
169
169
|
this.signal.throwIfAborted();
|
|
170
170
|
}
|
|
171
|
-
/** Stop waiting at the deadline even if the operation ignores its signal. */
|
|
172
171
|
async run(operation) {
|
|
173
172
|
this.check();
|
|
174
173
|
let onAbort;
|
|
@@ -284,27 +283,33 @@ function readChoice(payload) {
|
|
|
284
283
|
const answers = body.answers;
|
|
285
284
|
const fromAnswers = typeof answers === "object" && answers !== null ? answers[QUESTION_KEY] : void 0;
|
|
286
285
|
const candidate = fromAnswers ?? body[QUESTION_KEY];
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
if (typeof choice === "number" && Number.isFinite(choice)) return String(choice);
|
|
291
|
-
return void 0;
|
|
292
|
-
}
|
|
293
|
-
if (typeof candidate === "string" && candidate.trim() !== "") return candidate.trim();
|
|
294
|
-
if (typeof candidate === "number" && Number.isFinite(candidate)) return String(candidate);
|
|
286
|
+
const choice = typeof candidate === "object" && candidate !== null ? candidate.choice : candidate;
|
|
287
|
+
if (typeof choice === "string" && choice.trim() !== "") return choice;
|
|
288
|
+
if (typeof choice === "number" && Number.isFinite(choice)) return String(choice);
|
|
295
289
|
return void 0;
|
|
296
290
|
}
|
|
297
291
|
function readJudgeAnswer(payload, rows) {
|
|
298
292
|
const choice = readChoice(payload);
|
|
299
293
|
if (choice === void 0) return { kind: "empty" };
|
|
300
294
|
if (choice === NONE_OPTION_ID) return { kind: "none" };
|
|
301
|
-
const
|
|
302
|
-
if (!Number.isFinite(wanted)) return { kind: "unmatched" };
|
|
303
|
-
const row = rows.find((candidate) => candidate.id === wanted && isOfferedRow(candidate));
|
|
295
|
+
const row = rows.find((candidate) => String(candidate.id) === choice && isOfferedRow(candidate));
|
|
304
296
|
return row === void 0 ? { kind: "unmatched" } : { kind: "row", row };
|
|
305
297
|
}
|
|
306
298
|
|
|
307
299
|
// src/server/judge-client.ts
|
|
300
|
+
var JudgeHttpError = class extends Error {
|
|
301
|
+
status;
|
|
302
|
+
constructor(status) {
|
|
303
|
+
super(`Judge endpoint returned HTTP ${status}`);
|
|
304
|
+
this.status = status;
|
|
305
|
+
}
|
|
306
|
+
};
|
|
307
|
+
function probeHttpReason(status) {
|
|
308
|
+
if (status === 401 || status === 403) return "authentication";
|
|
309
|
+
if (status === 429) return "rate-limited";
|
|
310
|
+
if (status >= 500) return "server-error";
|
|
311
|
+
return "http-error";
|
|
312
|
+
}
|
|
308
313
|
async function requestJudge(budget, endpoint, body, fetchImpl) {
|
|
309
314
|
return budget.run(async (signal) => {
|
|
310
315
|
const response = await fetchImpl(endpoint.url.trim(), {
|
|
@@ -318,8 +323,16 @@ async function requestJudge(budget, endpoint, body, fetchImpl) {
|
|
|
318
323
|
signal
|
|
319
324
|
});
|
|
320
325
|
signal.throwIfAborted();
|
|
321
|
-
if (!response.ok)
|
|
322
|
-
|
|
326
|
+
if (!response.ok) {
|
|
327
|
+
void response.body?.cancel().catch(() => {
|
|
328
|
+
});
|
|
329
|
+
throw new JudgeHttpError(response.status);
|
|
330
|
+
}
|
|
331
|
+
const payload = await response.json().catch((error) => {
|
|
332
|
+
if (error instanceof SyntaxError) return void 0;
|
|
333
|
+
throw error;
|
|
334
|
+
});
|
|
335
|
+
return { payload, status: response.status };
|
|
323
336
|
});
|
|
324
337
|
}
|
|
325
338
|
async function probeJudge(endpoint, fetchImpl = fetch, sharedBudget) {
|
|
@@ -328,9 +341,12 @@ async function probeJudge(endpoint, fetchImpl = fetch, sharedBudget) {
|
|
|
328
341
|
}
|
|
329
342
|
const budget = sharedBudget ?? new JudgeBudget();
|
|
330
343
|
try {
|
|
331
|
-
const payload = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);
|
|
332
|
-
return
|
|
333
|
-
} catch {
|
|
344
|
+
const { payload, status } = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);
|
|
345
|
+
return readChoice(payload) === PROBE_OPTION_ID ? { ok: true, latencyMs: budget.elapsed() } : { ok: false, latencyMs: budget.elapsed(), reason: "unmatched", httpStatus: status };
|
|
346
|
+
} catch (error) {
|
|
347
|
+
if (error instanceof JudgeHttpError && !budget.expired()) {
|
|
348
|
+
return { ok: false, latencyMs: budget.elapsed(), reason: probeHttpReason(error.status), httpStatus: error.status };
|
|
349
|
+
}
|
|
334
350
|
return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? "timeout" : "unreachable" };
|
|
335
351
|
} finally {
|
|
336
352
|
if (sharedBudget === void 0) budget.dispose();
|
|
@@ -347,7 +363,7 @@ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch, sharedB
|
|
|
347
363
|
}
|
|
348
364
|
budget.check();
|
|
349
365
|
metrics = { judgeModel: model, optionCount: offered.length, subjectLength: subject.length };
|
|
350
|
-
const payload = await requestJudge(budget, endpoint, buildJudgeRequest(offered, model, subject), fetchImpl);
|
|
366
|
+
const { payload } = await requestJudge(budget, endpoint, buildJudgeRequest(offered, model, subject), fetchImpl);
|
|
351
367
|
const decision = readJudgeAnswer(payload, offered);
|
|
352
368
|
const latencyMs = budget.elapsed();
|
|
353
369
|
if (decision.kind === "row") return { kind: "matched", row: decision.row, latencyMs, metrics };
|
|
@@ -407,32 +423,20 @@ function resolveEndpointUrl(input) {
|
|
|
407
423
|
// src/server/config.ts
|
|
408
424
|
var TypeRowSchema = z.object({
|
|
409
425
|
stableId: z.string().default(""),
|
|
410
|
-
/** Whether this type takes part in judgements; a row written before the switch existed counts as on. */
|
|
411
426
|
enabled: z.boolean().default(true),
|
|
412
|
-
/** Criterion text the judge reads for this type. */
|
|
413
427
|
description: z.string().default(""),
|
|
414
|
-
/** Provider route of the model this type runs on. */
|
|
415
428
|
provider: z.string().default(""),
|
|
416
|
-
/** Model id interpreted by that provider. */
|
|
417
429
|
model: z.string().default(""),
|
|
418
|
-
/** Reasoning effort id this type runs at. */
|
|
419
430
|
effort: z.string().default(""),
|
|
420
|
-
/** An explicit choice to let the Host supply the model's default. */
|
|
421
431
|
useDefaultEffort: z.const(true)
|
|
422
432
|
});
|
|
423
433
|
var Config = z.object({
|
|
424
|
-
/** Default for conversations without their own choice. */
|
|
425
434
|
enabled: z.boolean().default(DEFAULT_ENABLED).volatile(),
|
|
426
435
|
sessionOverrides: z.dict(z.boolean()).default({}).volatile(),
|
|
427
|
-
/** Whether judgements are written to the plugin's own log. */
|
|
428
436
|
logEnabled: z.boolean().default(true).volatile(),
|
|
429
|
-
/** Whether new log entries may retain bounded copies of task text and type descriptions. */
|
|
430
437
|
logDetails: z.boolean().default(true).volatile(),
|
|
431
|
-
/** Judge service address, as the reader typed it; the path is appended when a call is made. */
|
|
432
438
|
endpointUrl: z.string().default("").volatile(),
|
|
433
|
-
/** Judge model id. */
|
|
434
439
|
judgeModel: z.string().default("").volatile(),
|
|
435
|
-
/** The task-type list, in page order. */
|
|
436
440
|
rows: z.array(TypeRowSchema).default([]).volatile()
|
|
437
441
|
});
|
|
438
442
|
function readConfigRows(stored) {
|
|
@@ -496,66 +500,100 @@ function createJudgePolicy(options) {
|
|
|
496
500
|
}
|
|
497
501
|
return rules;
|
|
498
502
|
}
|
|
499
|
-
function
|
|
503
|
+
async function isInCatalog(route, budget) {
|
|
500
504
|
try {
|
|
501
|
-
return
|
|
505
|
+
return await budget.run(async () => {
|
|
506
|
+
const llm = options.llm();
|
|
507
|
+
if (llm === void 0) return false;
|
|
508
|
+
const listed = await llm.isModelInCatalog(route.provider, route.model);
|
|
509
|
+
return listed === true && options.llm() === llm;
|
|
510
|
+
});
|
|
502
511
|
} catch {
|
|
503
|
-
|
|
512
|
+
budget.check();
|
|
513
|
+
return false;
|
|
504
514
|
}
|
|
505
515
|
}
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
516
|
+
async function eligibleRows(rows, budget) {
|
|
517
|
+
const lookups = /* @__PURE__ */ new Map();
|
|
518
|
+
const available = await Promise.all(rows.map((row) => {
|
|
519
|
+
const route = { provider: row.provider.trim(), model: row.model.trim() };
|
|
520
|
+
const key = JSON.stringify([route.provider, route.model]);
|
|
521
|
+
const existing = lookups.get(key);
|
|
522
|
+
if (existing !== void 0) return existing;
|
|
523
|
+
const lookup = isInCatalog(route, budget);
|
|
524
|
+
lookups.set(key, lookup);
|
|
525
|
+
return lookup;
|
|
526
|
+
}));
|
|
527
|
+
return rows.filter((_row, index) => available[index]);
|
|
528
|
+
}
|
|
512
529
|
function prepare(snapshot) {
|
|
513
530
|
if (!snapshot.endpointUrl || !snapshot.judgeModel) return "unconfigured";
|
|
514
531
|
const rows = currentRules();
|
|
515
532
|
if (rows.length === 0) return "unconfigured";
|
|
516
|
-
|
|
517
|
-
return candidates.length === 0 ? "no-authorized-route" : {
|
|
533
|
+
return {
|
|
518
534
|
url: snapshot.endpointUrl,
|
|
519
535
|
model: snapshot.judgeModel,
|
|
520
|
-
rules: rows
|
|
521
|
-
candidates
|
|
536
|
+
rules: rows
|
|
522
537
|
};
|
|
523
538
|
}
|
|
524
539
|
function planIsCurrent(plan) {
|
|
525
540
|
const snapshot = settings();
|
|
526
541
|
return snapshot.endpointUrl === plan.url && snapshot.judgeModel === plan.model && currentRules() === plan.rules;
|
|
527
542
|
}
|
|
543
|
+
async function previewRows(snapshot, budget) {
|
|
544
|
+
const plan = { url: snapshot.endpointUrl, model: snapshot.judgeModel, rules: currentRules() };
|
|
545
|
+
const rows = await eligibleRows(plan.rules, budget);
|
|
546
|
+
budget.check();
|
|
547
|
+
if (!planIsCurrent(plan)) throw new Error("Judgement settings changed while preparing the preview");
|
|
548
|
+
return rows;
|
|
549
|
+
}
|
|
550
|
+
async function checkFinalRoute(plan, route, budget, checkTask = () => void 0) {
|
|
551
|
+
const stale = () => planIsCurrent(plan) ? checkTask() : "settings-changed";
|
|
552
|
+
try {
|
|
553
|
+
const changed = stale();
|
|
554
|
+
if (changed !== void 0) return changed;
|
|
555
|
+
const listed = await isInCatalog(route, budget);
|
|
556
|
+
return stale() ?? (listed ? void 0 : "unavailable-route");
|
|
557
|
+
} catch {
|
|
558
|
+
return budget.expired() ? "timeout" : "unavailable-route";
|
|
559
|
+
}
|
|
560
|
+
}
|
|
528
561
|
async function evaluate(plan, subject, budget, timings, checkTask = () => void 0) {
|
|
562
|
+
const stale = () => planIsCurrent(plan) ? checkTask() : "settings-changed";
|
|
529
563
|
const judgeStarted = performance.now();
|
|
530
|
-
let
|
|
564
|
+
let outcome;
|
|
565
|
+
let rejectedBeforeSend;
|
|
531
566
|
try {
|
|
532
|
-
apiKey
|
|
567
|
+
let apiKey;
|
|
568
|
+
try {
|
|
569
|
+
apiKey = await budget.run(() => options.resolveKey(plan.url));
|
|
570
|
+
} catch {
|
|
571
|
+
return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "credentials-unavailable" };
|
|
572
|
+
}
|
|
573
|
+
const changed = stale();
|
|
574
|
+
if (changed !== void 0) return { kind: "keep", stage: "judge", reason: changed };
|
|
575
|
+
const candidates = await eligibleRows(plan.rules, budget);
|
|
576
|
+
const changedAfterLookup = stale();
|
|
577
|
+
if (changedAfterLookup !== void 0 || candidates.length === 0) {
|
|
578
|
+
return { kind: "keep", stage: "judge", reason: changedAfterLookup ?? "no-authorized-route" };
|
|
579
|
+
}
|
|
580
|
+
outcome = await judgeTaskType(
|
|
581
|
+
{ url: plan.url, model: plan.model, apiKey },
|
|
582
|
+
candidates,
|
|
583
|
+
composeJudgeSubject(subject.label, subject.text),
|
|
584
|
+
(url, init) => {
|
|
585
|
+
rejectedBeforeSend = stale();
|
|
586
|
+
if (rejectedBeforeSend !== void 0) throw new Error("Judgement changed before sending");
|
|
587
|
+
budget.check();
|
|
588
|
+
return fetch(url, init);
|
|
589
|
+
},
|
|
590
|
+
budget
|
|
591
|
+
);
|
|
533
592
|
} catch {
|
|
593
|
+
return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "no-authorized-route" };
|
|
594
|
+
} finally {
|
|
534
595
|
timings.judge = Math.round(performance.now() - judgeStarted);
|
|
535
|
-
return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "credentials-unavailable" };
|
|
536
|
-
}
|
|
537
|
-
const changed = planIsCurrent(plan) ? checkTask() : "settings-changed";
|
|
538
|
-
const candidates = changed === void 0 ? eligibleRows(plan.candidates) : [];
|
|
539
|
-
if (candidates.length === 0) {
|
|
540
|
-
timings.judge = Math.round(performance.now() - judgeStarted);
|
|
541
|
-
return { kind: "keep", stage: "judge", reason: changed ?? "no-authorized-route" };
|
|
542
596
|
}
|
|
543
|
-
let rejectedBeforeSend;
|
|
544
|
-
const outcome = await judgeTaskType(
|
|
545
|
-
{ url: plan.url, model: plan.model, apiKey },
|
|
546
|
-
candidates,
|
|
547
|
-
composeJudgeSubject(subject.label, subject.text),
|
|
548
|
-
(url, init) => {
|
|
549
|
-
rejectedBeforeSend = planIsCurrent(plan) ? checkTask() : "settings-changed";
|
|
550
|
-
if (rejectedBeforeSend === void 0 && eligibleRows(candidates).length !== candidates.length) {
|
|
551
|
-
rejectedBeforeSend = "no-authorized-route";
|
|
552
|
-
}
|
|
553
|
-
if (rejectedBeforeSend !== void 0) throw new Error("Judgement changed before sending");
|
|
554
|
-
return fetch(url, init);
|
|
555
|
-
},
|
|
556
|
-
budget
|
|
557
|
-
);
|
|
558
|
-
timings.judge = Math.round(performance.now() - judgeStarted);
|
|
559
597
|
const decision = decideRewrite(outcome);
|
|
560
598
|
const metrics = outcome.metrics;
|
|
561
599
|
if (outcome.kind !== "matched" || decision.kind !== "rewrite") {
|
|
@@ -564,19 +602,23 @@ function createJudgePolicy(options) {
|
|
|
564
602
|
const match = { row: outcome.row, route: decision.rewrite };
|
|
565
603
|
const preflightStarted = performance.now();
|
|
566
604
|
try {
|
|
567
|
-
const
|
|
568
|
-
if (
|
|
569
|
-
const
|
|
570
|
-
if (
|
|
605
|
+
const changed = stale();
|
|
606
|
+
if (changed !== void 0) return { kind: "keep", stage: "preflight", reason: changed, match, metrics };
|
|
607
|
+
const llm = options.llm();
|
|
608
|
+
if (llm === void 0 || !await isInCatalog(match.route, budget)) {
|
|
571
609
|
return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
|
|
572
610
|
}
|
|
573
|
-
const
|
|
574
|
-
if (
|
|
575
|
-
|
|
611
|
+
const changedAfterLookup = stale();
|
|
612
|
+
if (changedAfterLookup !== void 0) {
|
|
613
|
+
return { kind: "keep", stage: "preflight", reason: changedAfterLookup, match, metrics };
|
|
614
|
+
}
|
|
615
|
+
if (options.llm() !== llm) return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
|
|
616
|
+
const resolved = await budget.run((signal) => llm.resolveCallConfig(match.route, signal));
|
|
617
|
+
const changedAfterValidation = stale();
|
|
576
618
|
if (changedAfterValidation !== void 0) {
|
|
577
619
|
return { kind: "keep", stage: "preflight", reason: changedAfterValidation, match, metrics };
|
|
578
620
|
}
|
|
579
|
-
|
|
621
|
+
if (options.llm() !== llm) return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
|
|
580
622
|
const effort = resolved?.reasoningEffort;
|
|
581
623
|
return { kind: "ready", match: { ...match, resolvedEffort: typeof effort === "string" ? effort : match.route.reasoningEffort }, metrics };
|
|
582
624
|
} catch {
|
|
@@ -585,11 +627,11 @@ function createJudgePolicy(options) {
|
|
|
585
627
|
timings.preflight = Math.round(performance.now() - preflightStarted);
|
|
586
628
|
}
|
|
587
629
|
}
|
|
588
|
-
return { settings, prepare, evaluate, planIsCurrent,
|
|
630
|
+
return { settings, prepare, evaluate, planIsCurrent, checkFinalRoute, previewRows };
|
|
589
631
|
}
|
|
590
632
|
|
|
591
633
|
// src/server/log-store.ts
|
|
592
|
-
import { randomUUID } from "node:crypto";
|
|
634
|
+
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
593
635
|
import * as fs from "node:fs/promises";
|
|
594
636
|
import * as path from "node:path";
|
|
595
637
|
|
|
@@ -809,6 +851,8 @@ var REASONS = [
|
|
|
809
851
|
var STATUSES = ["skipped", "kept", "applied"];
|
|
810
852
|
var STAGES = ["eligibility", "task", "judge", "preflight", "apply"];
|
|
811
853
|
var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
854
|
+
var BACKUP_HASH = /^[0-9a-f]{64}$/;
|
|
855
|
+
var LOG_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
|
|
812
856
|
var ROUTE_MAX_BYTES = 512;
|
|
813
857
|
var EFFORT_MAX_BYTES = 128;
|
|
814
858
|
function record(value) {
|
|
@@ -919,11 +963,13 @@ var LogStore = class {
|
|
|
919
963
|
loading;
|
|
920
964
|
writing = Promise.resolve();
|
|
921
965
|
filePath;
|
|
966
|
+
backupPrefix;
|
|
922
967
|
constructor(filePath = dshHomePath("dsh-subagent-judge-dispatch", "judgements.json")) {
|
|
923
968
|
this.filePath = filePath;
|
|
969
|
+
this.backupPrefix = `${filePath}.corrupt-`;
|
|
924
970
|
}
|
|
925
971
|
init() {
|
|
926
|
-
this.loading ??= this.
|
|
972
|
+
this.loading ??= this.readRecovering().then((entries) => {
|
|
927
973
|
this.entries = entries;
|
|
928
974
|
}).catch(() => {
|
|
929
975
|
});
|
|
@@ -953,10 +999,19 @@ var LogStore = class {
|
|
|
953
999
|
list() {
|
|
954
1000
|
return this.snapshot(this.entries);
|
|
955
1001
|
}
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
1002
|
+
readLatest() {
|
|
1003
|
+
return this.readLatestSnapshot(false).then(({ entries }) => entries);
|
|
1004
|
+
}
|
|
1005
|
+
readLatestWithRecovery() {
|
|
1006
|
+
return this.readLatestSnapshot(true);
|
|
1007
|
+
}
|
|
1008
|
+
async readLatestSnapshot(includeRecovery) {
|
|
1009
|
+
while (true) {
|
|
1010
|
+
const previous = this.entries;
|
|
1011
|
+
const disk = await this.readRecovering();
|
|
1012
|
+
const recovered = includeRecovery && await this.hasBackup();
|
|
1013
|
+
if (this.entries === previous) return { entries: this.snapshot(disk), recovered };
|
|
1014
|
+
}
|
|
960
1015
|
}
|
|
961
1016
|
snapshot(entries) {
|
|
962
1017
|
return newest([...this.pending, ...entries]).map((entry) => structuredClone(entry));
|
|
@@ -966,23 +1021,57 @@ var LogStore = class {
|
|
|
966
1021
|
await this.writing;
|
|
967
1022
|
}
|
|
968
1023
|
async readDisk() {
|
|
1024
|
+
let bytes;
|
|
969
1025
|
try {
|
|
970
|
-
|
|
971
|
-
if (!Array.isArray(parsed)) throw new Error("Invalid log format");
|
|
972
|
-
return newest(parsed.map(readEntry).filter((entry) => entry !== void 0));
|
|
1026
|
+
bytes = await fs.readFile(this.filePath);
|
|
973
1027
|
} catch (error) {
|
|
974
1028
|
if (error.code === "ENOENT") return [];
|
|
975
1029
|
throw error;
|
|
976
1030
|
}
|
|
1031
|
+
let parsed;
|
|
1032
|
+
try {
|
|
1033
|
+
parsed = JSON.parse(LOG_DECODER.decode(bytes));
|
|
1034
|
+
} catch {
|
|
1035
|
+
return bytes;
|
|
1036
|
+
}
|
|
1037
|
+
if (!Array.isArray(parsed)) return bytes;
|
|
1038
|
+
return newest(parsed.map(readEntry).filter((entry) => entry !== void 0));
|
|
1039
|
+
}
|
|
1040
|
+
async readRecovering() {
|
|
1041
|
+
const stored = await this.readDisk();
|
|
1042
|
+
if (Array.isArray(stored)) return stored;
|
|
1043
|
+
return withFileLock(this.filePath, async () => {
|
|
1044
|
+
const latest = await this.readDisk();
|
|
1045
|
+
if (Array.isArray(latest)) return latest;
|
|
1046
|
+
await this.backUp(latest);
|
|
1047
|
+
await writeFileAtomic(this.filePath, "[]", { mode: 384 });
|
|
1048
|
+
return [];
|
|
1049
|
+
});
|
|
1050
|
+
}
|
|
1051
|
+
async backUp(bytes) {
|
|
1052
|
+
const hash = createHash2("sha256").update(bytes).digest("hex");
|
|
1053
|
+
await writeFileAtomic(`${this.backupPrefix}${hash}`, bytes, { mode: 384 });
|
|
1054
|
+
}
|
|
1055
|
+
async hasBackup() {
|
|
1056
|
+
const prefix = path.basename(this.backupPrefix);
|
|
1057
|
+
try {
|
|
1058
|
+
const files = await fs.readdir(path.dirname(this.filePath), { withFileTypes: true });
|
|
1059
|
+
return files.some((file) => file.name.startsWith(prefix) && BACKUP_HASH.test(file.name.slice(prefix.length)) && file.isFile());
|
|
1060
|
+
} catch (error) {
|
|
1061
|
+
if (error.code === "ENOENT") return false;
|
|
1062
|
+
throw error;
|
|
1063
|
+
}
|
|
977
1064
|
}
|
|
978
1065
|
async write() {
|
|
979
1066
|
if (this.pending.length === 0) return;
|
|
980
1067
|
await this.loading;
|
|
981
1068
|
await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 448 });
|
|
982
1069
|
await withFileLock(this.filePath, async () => {
|
|
983
|
-
const
|
|
1070
|
+
const disk = await this.readDisk();
|
|
1071
|
+
const stored = Array.isArray(disk) ? disk : [];
|
|
984
1072
|
const batch = this.pending.slice();
|
|
985
1073
|
const retained = retainForWrite(newest([...batch, ...stored]));
|
|
1074
|
+
if (!Array.isArray(disk)) await this.backUp(disk);
|
|
986
1075
|
await writeFileAtomic(this.filePath, retained.file, { mode: 384 });
|
|
987
1076
|
const written = new Set(batch.map(({ id }) => id));
|
|
988
1077
|
this.pending = this.pending.filter(({ id }) => !written.has(id));
|
|
@@ -1020,7 +1109,8 @@ function createFetchRoutes(face) {
|
|
|
1020
1109
|
requestBody: "buffered",
|
|
1021
1110
|
fetch: async () => {
|
|
1022
1111
|
try {
|
|
1023
|
-
|
|
1112
|
+
const { entries, recovered } = await face.log();
|
|
1113
|
+
return sendJson(200, { ok: true, entries: entries.slice(0, LOG_PAGE_LIMIT), recovered });
|
|
1024
1114
|
} catch (err) {
|
|
1025
1115
|
return sendJson(500, { ok: false, error: describe(err) });
|
|
1026
1116
|
}
|
|
@@ -1034,7 +1124,7 @@ function createFetchRoutes(face) {
|
|
|
1034
1124
|
try {
|
|
1035
1125
|
const input = request.method === "POST" ? await readSubject(request) : void 0;
|
|
1036
1126
|
if (request.method === "POST" && input === void 0) return sendJson(400, { ok: false });
|
|
1037
|
-
return sendJson(200, { ok: true, preview: face.preview(input?.subject) });
|
|
1127
|
+
return sendJson(200, { ok: true, preview: await face.preview(input?.subject, request.signal) });
|
|
1038
1128
|
} catch (err) {
|
|
1039
1129
|
return sendJson(500, { ok: false, error: describe(err) });
|
|
1040
1130
|
}
|
|
@@ -1090,14 +1180,12 @@ var inject = ["credentials", "sessions"];
|
|
|
1090
1180
|
var JUDGED_LIMIT = 500;
|
|
1091
1181
|
var JudgedChildren = class {
|
|
1092
1182
|
seen = /* @__PURE__ */ new Set();
|
|
1093
|
-
/** Record a child as judged, forgetting the oldest entry past the cap. */
|
|
1094
1183
|
add(id) {
|
|
1095
1184
|
this.seen.add(id);
|
|
1096
1185
|
if (this.seen.size <= JUDGED_LIMIT) return;
|
|
1097
1186
|
const oldest = this.seen.values().next();
|
|
1098
1187
|
if (!oldest.done) this.seen.delete(oldest.value);
|
|
1099
1188
|
}
|
|
1100
|
-
/** Whether this child has already been judged. */
|
|
1101
1189
|
has(id) {
|
|
1102
1190
|
return this.seen.has(id);
|
|
1103
1191
|
}
|
|
@@ -1110,11 +1198,7 @@ function apply(ctx, config) {
|
|
|
1110
1198
|
const credentials = createJudgeCredentials(ctx.credentials, config.endpointUrl.get());
|
|
1111
1199
|
const policy = createJudgePolicy({
|
|
1112
1200
|
refs: config,
|
|
1113
|
-
|
|
1114
|
-
routeValidator: () => {
|
|
1115
|
-
const llm = ctx.get("llm");
|
|
1116
|
-
return llm?.resolveCallConfig.bind(llm);
|
|
1117
|
-
},
|
|
1201
|
+
llm: () => ctx.get("llm"),
|
|
1118
1202
|
resolveKey: credentials.resolve
|
|
1119
1203
|
});
|
|
1120
1204
|
const cancelWith = (signal) => signal === void 0 ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);
|
|
@@ -1134,9 +1218,11 @@ function apply(ctx, config) {
|
|
|
1134
1218
|
let rootId;
|
|
1135
1219
|
let taskText;
|
|
1136
1220
|
let stage = "eligibility";
|
|
1221
|
+
const hasOverrides = (settings) => Object.keys(settings.sessionOverrides ?? {}).length > 0;
|
|
1222
|
+
const dispatchEnabled = (settings) => (rootId !== void 0 || !hasOverrides(settings)) && enabledFor(settings.sessionOverrides, settings.enabled, rootId);
|
|
1137
1223
|
const finish = (status, reason, matched, metrics, selected) => {
|
|
1138
1224
|
const now = policy.settings();
|
|
1139
|
-
if (cancellation.aborted || !now.logEnabled || !
|
|
1225
|
+
if (cancellation.aborted || !now.logEnabled || !dispatchEnabled(now)) return;
|
|
1140
1226
|
log.append(buildEntry({
|
|
1141
1227
|
route: selected ?? agent.model.current(),
|
|
1142
1228
|
status,
|
|
@@ -1152,18 +1238,19 @@ function apply(ctx, config) {
|
|
|
1152
1238
|
};
|
|
1153
1239
|
try {
|
|
1154
1240
|
let settings = policy.settings();
|
|
1155
|
-
const
|
|
1156
|
-
if (!
|
|
1241
|
+
const resolveRoot2 = hasOverrides(settings);
|
|
1242
|
+
if (!resolveRoot2 && !settings.enabled) return;
|
|
1243
|
+
if (resumed && hasRecordedRoute(agent.session, resumed)) return;
|
|
1157
1244
|
const lookup = (id) => ctx.sessions.get(id);
|
|
1158
1245
|
const parentId = agent.session.header.parentSession;
|
|
1159
|
-
if (
|
|
1246
|
+
if (resolveRoot2 && parentId) {
|
|
1160
1247
|
rootId = await budget.run(() => resolveRootSessionId(parentId, async (id) => {
|
|
1161
1248
|
budget.check();
|
|
1162
1249
|
return lookup(id)?.header ?? (await ctx.get("sessionPersistence")?.stat(id))?.header;
|
|
1163
1250
|
}));
|
|
1164
1251
|
settings = policy.settings();
|
|
1165
1252
|
}
|
|
1166
|
-
if (judged.has(agent.id) || !
|
|
1253
|
+
if (judged.has(agent.id) || !dispatchEnabled(settings)) return;
|
|
1167
1254
|
const plan = policy.prepare(settings);
|
|
1168
1255
|
timings.eligibility = budget.elapsed();
|
|
1169
1256
|
if (typeof plan === "string") return finish("skipped", plan);
|
|
@@ -1174,12 +1261,10 @@ function apply(ctx, config) {
|
|
|
1174
1261
|
if (task === void 0) {
|
|
1175
1262
|
return finish("skipped", hasRecordedRoute(agent.session, resumed) ? "recorded-route" : "unidentified-task");
|
|
1176
1263
|
}
|
|
1177
|
-
if (task.explicitRoute) return finish("skipped", "explicit-route");
|
|
1178
1264
|
judged.add(agent.id);
|
|
1179
1265
|
taskText = task.text;
|
|
1180
1266
|
const checkTask = () => {
|
|
1181
|
-
|
|
1182
|
-
if (rootId === void 0 && !hasOverrides && Object.keys(current.sessionOverrides ?? {}).length > 0 || !enabledFor(current.sessionOverrides, current.enabled, rootId)) return "settings-changed";
|
|
1267
|
+
if (!dispatchEnabled(policy.settings())) return "settings-changed";
|
|
1183
1268
|
if (hasRecordedRoute(agent.session, resumed)) return "recorded-route";
|
|
1184
1269
|
};
|
|
1185
1270
|
stage = "judge";
|
|
@@ -1193,9 +1278,9 @@ function apply(ctx, config) {
|
|
|
1193
1278
|
const { row, route } = result.match;
|
|
1194
1279
|
let reason;
|
|
1195
1280
|
try {
|
|
1281
|
+
reason = await policy.checkFinalRoute(plan, route, budget, checkTask);
|
|
1196
1282
|
budget.check();
|
|
1197
|
-
reason
|
|
1198
|
-
if (reason === void 0 && !policy.isAllowed(route)) reason = "unavailable-route";
|
|
1283
|
+
reason ??= policy.planIsCurrent(plan) ? checkTask() : "settings-changed";
|
|
1199
1284
|
if (reason === void 0) agent.model.select(route);
|
|
1200
1285
|
} catch {
|
|
1201
1286
|
reason = budget.expired() ? "timeout" : "unavailable-route";
|
|
@@ -1216,11 +1301,16 @@ function apply(ctx, config) {
|
|
|
1216
1301
|
});
|
|
1217
1302
|
ctx.inject(["connection"], (connectionCtx) => {
|
|
1218
1303
|
const routes = createFetchRoutes({
|
|
1219
|
-
log: () => log.
|
|
1220
|
-
preview: (subject) => {
|
|
1221
|
-
const
|
|
1222
|
-
const
|
|
1223
|
-
|
|
1304
|
+
log: () => log.readLatestWithRecovery(),
|
|
1305
|
+
preview: async (subject, signal) => {
|
|
1306
|
+
const snapshot = policy.settings();
|
|
1307
|
+
const budget = new JudgeBudget(cancelWith(signal));
|
|
1308
|
+
try {
|
|
1309
|
+
const rows = await policy.previewRows(snapshot, budget);
|
|
1310
|
+
return subject === void 0 ? buildPreview(rows, snapshot.judgeModel) : formatJudgeRequest(buildJudgeRequest(rows, snapshot.judgeModel, composeJudgeSubject(subject.label, subject.text)));
|
|
1311
|
+
} finally {
|
|
1312
|
+
budget.dispose();
|
|
1313
|
+
}
|
|
1224
1314
|
},
|
|
1225
1315
|
keyConfigured: () => credentials.configured(policy.settings().endpointUrl),
|
|
1226
1316
|
probe: async (signal) => {
|
|
@@ -1231,11 +1321,11 @@ function apply(ctx, config) {
|
|
|
1231
1321
|
const apiKey = await budget.run(() => credentials.resolve(snapshot.endpointUrl));
|
|
1232
1322
|
const current = policy.settings();
|
|
1233
1323
|
if (current.endpointUrl !== snapshot.endpointUrl || current.judgeModel !== snapshot.judgeModel) {
|
|
1234
|
-
return { ok: false, reason: "
|
|
1324
|
+
return { ok: false, reason: "settings-changed", latencyMs: budget.elapsed() };
|
|
1235
1325
|
}
|
|
1236
1326
|
return await probeJudge({ url: snapshot.endpointUrl, model: snapshot.judgeModel, apiKey }, fetch, budget);
|
|
1237
1327
|
} catch {
|
|
1238
|
-
return { ok: false, reason: budget.expired() ? "timeout" : "
|
|
1328
|
+
return { ok: false, reason: budget.expired() ? "timeout" : "credentials-unavailable", latencyMs: budget.elapsed() };
|
|
1239
1329
|
} finally {
|
|
1240
1330
|
budget.dispose();
|
|
1241
1331
|
}
|
|
@@ -1250,7 +1340,11 @@ function apply(ctx, config) {
|
|
|
1250
1340
|
const budget = new JudgeBudget(cancelWith(signal));
|
|
1251
1341
|
try {
|
|
1252
1342
|
const result = await policy.evaluate(plan, task, budget, {});
|
|
1253
|
-
if (result.kind === "ready")
|
|
1343
|
+
if (result.kind === "ready") {
|
|
1344
|
+
const { row, route } = result.match;
|
|
1345
|
+
const reason = await policy.checkFinalRoute(plan, route, budget) ?? (policy.planIsCurrent(plan) ? void 0 : "settings-changed");
|
|
1346
|
+
return reason === void 0 ? { ok: true, typeId: row.id, route, valid: true } : { ok: false, reason, typeId: row.id, route, valid: false };
|
|
1347
|
+
}
|
|
1254
1348
|
return {
|
|
1255
1349
|
ok: false,
|
|
1256
1350
|
reason: result.reason,
|