@lynn123411/dsh-subagent-judge-dispatch 0.6.14 → 0.6.16

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/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 === void 0 || header.origin !== "subagent" && (header.delegationDepth ?? 0) < 1) return current;
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 current;
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 current;
147
+ return void 0;
148
148
  }
149
149
 
150
150
  // src/server/judge-budget.ts
@@ -283,27 +283,33 @@ function readChoice(payload) {
283
283
  const answers = body.answers;
284
284
  const fromAnswers = typeof answers === "object" && answers !== null ? answers[QUESTION_KEY] : void 0;
285
285
  const candidate = fromAnswers ?? body[QUESTION_KEY];
286
- if (typeof candidate === "object" && candidate !== null) {
287
- const choice = candidate.choice;
288
- if (typeof choice === "string" && choice.trim() !== "") return choice.trim();
289
- if (typeof choice === "number" && Number.isFinite(choice)) return String(choice);
290
- return void 0;
291
- }
292
- if (typeof candidate === "string" && candidate.trim() !== "") return candidate.trim();
293
- 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);
294
289
  return void 0;
295
290
  }
296
291
  function readJudgeAnswer(payload, rows) {
297
292
  const choice = readChoice(payload);
298
293
  if (choice === void 0) return { kind: "empty" };
299
294
  if (choice === NONE_OPTION_ID) return { kind: "none" };
300
- const wanted = Number(choice);
301
- if (!Number.isFinite(wanted)) return { kind: "unmatched" };
302
- const row = rows.find((candidate) => candidate.id === wanted && isOfferedRow(candidate));
295
+ const row = rows.find((candidate) => String(candidate.id) === choice && isOfferedRow(candidate));
303
296
  return row === void 0 ? { kind: "unmatched" } : { kind: "row", row };
304
297
  }
305
298
 
306
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
+ }
307
313
  async function requestJudge(budget, endpoint, body, fetchImpl) {
308
314
  return budget.run(async (signal) => {
309
315
  const response = await fetchImpl(endpoint.url.trim(), {
@@ -317,8 +323,16 @@ async function requestJudge(budget, endpoint, body, fetchImpl) {
317
323
  signal
318
324
  });
319
325
  signal.throwIfAborted();
320
- if (!response.ok) throw new Error("Judge endpoint failed");
321
- return response.json();
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 };
322
336
  });
323
337
  }
324
338
  async function probeJudge(endpoint, fetchImpl = fetch, sharedBudget) {
@@ -327,9 +341,12 @@ async function probeJudge(endpoint, fetchImpl = fetch, sharedBudget) {
327
341
  }
328
342
  const budget = sharedBudget ?? new JudgeBudget();
329
343
  try {
330
- const payload = await requestJudge(budget, endpoint, buildProbeRequest(endpoint.model.trim()), fetchImpl);
331
- return Number(readChoice(payload)) === Number(PROBE_OPTION_ID) ? { ok: true, latencyMs: budget.elapsed() } : { ok: false, latencyMs: budget.elapsed(), reason: "unmatched" };
332
- } 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
+ }
333
350
  return { ok: false, latencyMs: budget.elapsed(), reason: budget.expired() ? "timeout" : "unreachable" };
334
351
  } finally {
335
352
  if (sharedBudget === void 0) budget.dispose();
@@ -346,7 +363,7 @@ async function judgeTaskType(endpoint, rows, subject, fetchImpl = fetch, sharedB
346
363
  }
347
364
  budget.check();
348
365
  metrics = { judgeModel: model, optionCount: offered.length, subjectLength: subject.length };
349
- const payload = await requestJudge(budget, endpoint, buildJudgeRequest(offered, model, subject), fetchImpl);
366
+ const { payload } = await requestJudge(budget, endpoint, buildJudgeRequest(offered, model, subject), fetchImpl);
350
367
  const decision = readJudgeAnswer(payload, offered);
351
368
  const latencyMs = budget.elapsed();
352
369
  if (decision.kind === "row") return { kind: "matched", row: decision.row, latencyMs, metrics };
@@ -389,6 +406,9 @@ function createJudgeCredentials(service, initialEndpoint) {
389
406
  };
390
407
  }
391
408
 
409
+ // src/server/judge-policy.ts
410
+ import { symbols } from "@deepseek-ai/cordis";
411
+
392
412
  // src/server/config.ts
393
413
  import z from "@deepseek-ai/schemastery";
394
414
 
@@ -466,11 +486,15 @@ function outcomeReason(outcome, decision) {
466
486
  }
467
487
 
468
488
  // src/server/judge-policy.ts
489
+ function serviceIdentity(llm) {
490
+ return llm?.[symbols.original] ?? llm;
491
+ }
469
492
  function createJudgePolicy(options) {
470
493
  let previousRows;
471
494
  let previousSignature = "";
472
495
  let rules = [];
473
496
  const settings = () => readConfigState(options.refs);
497
+ const isCurrentLlm = (llm) => serviceIdentity(options.llm()) === serviceIdentity(llm);
474
498
  function currentRules() {
475
499
  const stored = options.refs.rows.get();
476
500
  if (stored !== previousRows) {
@@ -483,66 +507,106 @@ function createJudgePolicy(options) {
483
507
  }
484
508
  return rules;
485
509
  }
486
- function allowedRoutes() {
510
+ async function readCatalog(provider, llm, budget) {
511
+ if (llm === void 0) return void 0;
487
512
  try {
488
- return options.routeValidator() === void 0 ? [] : options.allowedRoutes() ?? [];
489
- } catch {
490
- return [];
513
+ const models = await budget.run(() => llm.listModels(provider));
514
+ return new Set(models.map(({ id }) => id));
515
+ } catch (error) {
516
+ budget.check();
517
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "NO_ADAPTER") {
518
+ return /* @__PURE__ */ new Set();
519
+ }
520
+ return void 0;
491
521
  }
492
522
  }
493
- const matches = (left, right) => left.provider === right.provider && left.model === right.model;
494
- const isAllowed = (route) => allowedRoutes().some((pair) => matches(pair, route));
495
- const eligibleRows = (rows) => {
496
- const allowed = allowedRoutes();
497
- return rows.filter((row) => allowed.some((pair) => pair.provider === row.provider.trim() && pair.model === row.model.trim()));
498
- };
523
+ async function eligibleRows(rows, budget) {
524
+ const llm = options.llm();
525
+ const providers = new Set(rows.map((row) => row.provider.trim()));
526
+ const catalogs = new Map(await Promise.all(Array.from(
527
+ providers,
528
+ async (provider) => [provider, await readCatalog(provider, llm, budget)]
529
+ )));
530
+ if (llm === void 0 || !isCurrentLlm(llm)) return { rows: [], failed: providers.size > 0 };
531
+ return {
532
+ rows: rows.filter((row) => catalogs.get(row.provider.trim())?.has(row.model.trim())),
533
+ failed: Array.from(catalogs.values()).some((catalog) => catalog === void 0)
534
+ };
535
+ }
536
+ async function checkCatalog(route, llm, budget) {
537
+ const catalog = await readCatalog(route.provider, llm, budget);
538
+ if (llm === void 0 || catalog === void 0 || !isCurrentLlm(llm)) return "catalog-unavailable";
539
+ return catalog.has(route.model) ? void 0 : "unavailable-route";
540
+ }
499
541
  function prepare(snapshot) {
500
542
  if (!snapshot.endpointUrl || !snapshot.judgeModel) return "unconfigured";
501
543
  const rows = currentRules();
502
544
  if (rows.length === 0) return "unconfigured";
503
- const candidates = eligibleRows(rows);
504
- return candidates.length === 0 ? "no-authorized-route" : {
545
+ return {
505
546
  url: snapshot.endpointUrl,
506
547
  model: snapshot.judgeModel,
507
- rules: rows,
508
- candidates
548
+ rules: rows
509
549
  };
510
550
  }
511
551
  function planIsCurrent(plan) {
512
552
  const snapshot = settings();
513
553
  return snapshot.endpointUrl === plan.url && snapshot.judgeModel === plan.model && currentRules() === plan.rules;
514
554
  }
555
+ async function previewRows(snapshot, budget) {
556
+ const plan = { url: snapshot.endpointUrl, model: snapshot.judgeModel, rules: currentRules() };
557
+ const candidates = await eligibleRows(plan.rules, budget);
558
+ budget.check();
559
+ if (!planIsCurrent(plan)) throw new Error("Judgement settings changed while preparing the preview");
560
+ if (candidates.failed && candidates.rows.length === 0) throw new Error("Could not read the DSH model catalog");
561
+ return candidates.rows;
562
+ }
563
+ async function checkFinalRoute(plan, route, budget, checkTask = () => void 0) {
564
+ const stale = () => planIsCurrent(plan) ? checkTask() : "settings-changed";
565
+ try {
566
+ const changed = stale();
567
+ if (changed !== void 0) return changed;
568
+ const reason = await checkCatalog(route, options.llm(), budget);
569
+ return stale() ?? reason;
570
+ } catch {
571
+ return budget.expired() ? "timeout" : "unavailable-route";
572
+ }
573
+ }
515
574
  async function evaluate(plan, subject, budget, timings, checkTask = () => void 0) {
575
+ const stale = () => planIsCurrent(plan) ? checkTask() : "settings-changed";
516
576
  const judgeStarted = performance.now();
517
- let apiKey;
577
+ let outcome;
578
+ let rejectedBeforeSend;
518
579
  try {
519
- apiKey = await budget.run(() => options.resolveKey(plan.url));
580
+ let apiKey;
581
+ try {
582
+ apiKey = await budget.run(() => options.resolveKey(plan.url));
583
+ } catch {
584
+ return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "credentials-unavailable" };
585
+ }
586
+ const changed = stale();
587
+ if (changed !== void 0) return { kind: "keep", stage: "judge", reason: changed };
588
+ const candidates = await eligibleRows(plan.rules, budget);
589
+ const changedAfterLookup = stale();
590
+ if (changedAfterLookup !== void 0 || candidates.rows.length === 0) {
591
+ return { kind: "keep", stage: "judge", reason: changedAfterLookup ?? (candidates.failed ? "catalog-unavailable" : "no-authorized-route") };
592
+ }
593
+ outcome = await judgeTaskType(
594
+ { url: plan.url, model: plan.model, apiKey },
595
+ candidates.rows,
596
+ composeJudgeSubject(subject.label, subject.text),
597
+ (url, init) => {
598
+ rejectedBeforeSend = stale();
599
+ if (rejectedBeforeSend !== void 0) throw new Error("Judgement changed before sending");
600
+ budget.check();
601
+ return fetch(url, init);
602
+ },
603
+ budget
604
+ );
520
605
  } catch {
606
+ return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "catalog-unavailable" };
607
+ } finally {
521
608
  timings.judge = Math.round(performance.now() - judgeStarted);
522
- return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "credentials-unavailable" };
523
- }
524
- const changed = planIsCurrent(plan) ? checkTask() : "settings-changed";
525
- const candidates = changed === void 0 ? eligibleRows(plan.candidates) : [];
526
- if (candidates.length === 0) {
527
- timings.judge = Math.round(performance.now() - judgeStarted);
528
- return { kind: "keep", stage: "judge", reason: changed ?? "no-authorized-route" };
529
609
  }
530
- let rejectedBeforeSend;
531
- const outcome = await judgeTaskType(
532
- { url: plan.url, model: plan.model, apiKey },
533
- candidates,
534
- composeJudgeSubject(subject.label, subject.text),
535
- (url, init) => {
536
- rejectedBeforeSend = planIsCurrent(plan) ? checkTask() : "settings-changed";
537
- if (rejectedBeforeSend === void 0 && eligibleRows(candidates).length !== candidates.length) {
538
- rejectedBeforeSend = "no-authorized-route";
539
- }
540
- if (rejectedBeforeSend !== void 0) throw new Error("Judgement changed before sending");
541
- return fetch(url, init);
542
- },
543
- budget
544
- );
545
- timings.judge = Math.round(performance.now() - judgeStarted);
546
610
  const decision = decideRewrite(outcome);
547
611
  const metrics = outcome.metrics;
548
612
  if (outcome.kind !== "matched" || decision.kind !== "rewrite") {
@@ -551,19 +615,25 @@ function createJudgePolicy(options) {
551
615
  const match = { row: outcome.row, route: decision.rewrite };
552
616
  const preflightStarted = performance.now();
553
617
  try {
554
- const changed2 = planIsCurrent(plan) ? checkTask() : "settings-changed";
555
- if (changed2 !== void 0) return { kind: "keep", stage: "preflight", reason: changed2, match, metrics };
556
- const validate = options.routeValidator();
557
- if (validate === void 0 || !isAllowed(match.route)) {
558
- return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
618
+ const changed = stale();
619
+ if (changed !== void 0) return { kind: "keep", stage: "preflight", reason: changed, match, metrics };
620
+ const llm = options.llm();
621
+ if (llm === void 0) return { kind: "keep", stage: "preflight", reason: "catalog-unavailable", match, metrics };
622
+ const catalogReason = await checkCatalog(match.route, llm, budget);
623
+ if (catalogReason !== void 0) {
624
+ return { kind: "keep", stage: "preflight", reason: catalogReason, match, metrics };
559
625
  }
560
- const resolved = await budget.run((signal) => validate(match.route, signal));
561
- if (!isAllowed(match.route)) return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
562
- const changedAfterValidation = planIsCurrent(plan) ? checkTask() : "settings-changed";
626
+ const changedAfterLookup = stale();
627
+ if (changedAfterLookup !== void 0) {
628
+ return { kind: "keep", stage: "preflight", reason: changedAfterLookup, match, metrics };
629
+ }
630
+ if (!isCurrentLlm(llm)) return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
631
+ const resolved = await budget.run((signal) => llm.resolveCallConfig(match.route, signal));
632
+ const changedAfterValidation = stale();
563
633
  if (changedAfterValidation !== void 0) {
564
634
  return { kind: "keep", stage: "preflight", reason: changedAfterValidation, match, metrics };
565
635
  }
566
- budget.check();
636
+ if (!isCurrentLlm(llm)) return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
567
637
  const effort = resolved?.reasoningEffort;
568
638
  return { kind: "ready", match: { ...match, resolvedEffort: typeof effort === "string" ? effort : match.route.reasoningEffort }, metrics };
569
639
  } catch {
@@ -572,11 +642,11 @@ function createJudgePolicy(options) {
572
642
  timings.preflight = Math.round(performance.now() - preflightStarted);
573
643
  }
574
644
  }
575
- return { settings, prepare, evaluate, planIsCurrent, isAllowed, previewRows: () => eligibleRows(currentRules()) };
645
+ return { settings, prepare, evaluate, planIsCurrent, checkFinalRoute, previewRows };
576
646
  }
577
647
 
578
648
  // src/server/log-store.ts
579
- import { randomUUID } from "node:crypto";
649
+ import { createHash as createHash2, randomUUID } from "node:crypto";
580
650
  import * as fs from "node:fs/promises";
581
651
  import * as path from "node:path";
582
652
 
@@ -787,6 +857,7 @@ var REASONS = [
787
857
  "unavailable-route",
788
858
  "unconfigured",
789
859
  "no-authorized-route",
860
+ "catalog-unavailable",
790
861
  "unidentified-task",
791
862
  "explicit-route",
792
863
  "recorded-route",
@@ -796,6 +867,8 @@ var REASONS = [
796
867
  var STATUSES = ["skipped", "kept", "applied"];
797
868
  var STAGES = ["eligibility", "task", "judge", "preflight", "apply"];
798
869
  var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
870
+ var BACKUP_HASH = /^[0-9a-f]{64}$/;
871
+ var LOG_DECODER = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
799
872
  var ROUTE_MAX_BYTES = 512;
800
873
  var EFFORT_MAX_BYTES = 128;
801
874
  function record(value) {
@@ -906,11 +979,13 @@ var LogStore = class {
906
979
  loading;
907
980
  writing = Promise.resolve();
908
981
  filePath;
982
+ backupPrefix;
909
983
  constructor(filePath = dshHomePath("dsh-subagent-judge-dispatch", "judgements.json")) {
910
984
  this.filePath = filePath;
985
+ this.backupPrefix = `${filePath}.corrupt-`;
911
986
  }
912
987
  init() {
913
- this.loading ??= this.readDisk().then((entries) => {
988
+ this.loading ??= this.readRecovering().then((entries) => {
914
989
  this.entries = entries;
915
990
  }).catch(() => {
916
991
  });
@@ -940,11 +1015,18 @@ var LogStore = class {
940
1015
  list() {
941
1016
  return this.snapshot(this.entries);
942
1017
  }
943
- async readLatest() {
1018
+ readLatest() {
1019
+ return this.readLatestSnapshot(false).then(({ entries }) => entries);
1020
+ }
1021
+ readLatestWithRecovery() {
1022
+ return this.readLatestSnapshot(true);
1023
+ }
1024
+ async readLatestSnapshot(includeRecovery) {
944
1025
  while (true) {
945
1026
  const previous = this.entries;
946
- const disk = await this.readDisk();
947
- if (this.entries === previous) return this.snapshot(disk);
1027
+ const disk = await this.readRecovering();
1028
+ const recovered = includeRecovery && await this.hasBackup();
1029
+ if (this.entries === previous) return { entries: this.snapshot(disk), recovered };
948
1030
  }
949
1031
  }
950
1032
  snapshot(entries) {
@@ -955,23 +1037,57 @@ var LogStore = class {
955
1037
  await this.writing;
956
1038
  }
957
1039
  async readDisk() {
1040
+ let bytes;
958
1041
  try {
959
- const parsed = JSON.parse(await fs.readFile(this.filePath, "utf8"));
960
- if (!Array.isArray(parsed)) throw new Error("Invalid log format");
961
- return newest(parsed.map(readEntry).filter((entry) => entry !== void 0));
1042
+ bytes = await fs.readFile(this.filePath);
962
1043
  } catch (error) {
963
1044
  if (error.code === "ENOENT") return [];
964
1045
  throw error;
965
1046
  }
1047
+ let parsed;
1048
+ try {
1049
+ parsed = JSON.parse(LOG_DECODER.decode(bytes));
1050
+ } catch {
1051
+ return bytes;
1052
+ }
1053
+ if (!Array.isArray(parsed)) return bytes;
1054
+ return newest(parsed.map(readEntry).filter((entry) => entry !== void 0));
1055
+ }
1056
+ async readRecovering() {
1057
+ const stored = await this.readDisk();
1058
+ if (Array.isArray(stored)) return stored;
1059
+ return withFileLock(this.filePath, async () => {
1060
+ const latest = await this.readDisk();
1061
+ if (Array.isArray(latest)) return latest;
1062
+ await this.backUp(latest);
1063
+ await writeFileAtomic(this.filePath, "[]", { mode: 384 });
1064
+ return [];
1065
+ });
1066
+ }
1067
+ async backUp(bytes) {
1068
+ const hash = createHash2("sha256").update(bytes).digest("hex");
1069
+ await writeFileAtomic(`${this.backupPrefix}${hash}`, bytes, { mode: 384 });
1070
+ }
1071
+ async hasBackup() {
1072
+ const prefix = path.basename(this.backupPrefix);
1073
+ try {
1074
+ const files = await fs.readdir(path.dirname(this.filePath), { withFileTypes: true });
1075
+ return files.some((file) => file.name.startsWith(prefix) && BACKUP_HASH.test(file.name.slice(prefix.length)) && file.isFile());
1076
+ } catch (error) {
1077
+ if (error.code === "ENOENT") return false;
1078
+ throw error;
1079
+ }
966
1080
  }
967
1081
  async write() {
968
1082
  if (this.pending.length === 0) return;
969
1083
  await this.loading;
970
1084
  await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 448 });
971
1085
  await withFileLock(this.filePath, async () => {
972
- const stored = await this.readDisk();
1086
+ const disk = await this.readDisk();
1087
+ const stored = Array.isArray(disk) ? disk : [];
973
1088
  const batch = this.pending.slice();
974
1089
  const retained = retainForWrite(newest([...batch, ...stored]));
1090
+ if (!Array.isArray(disk)) await this.backUp(disk);
975
1091
  await writeFileAtomic(this.filePath, retained.file, { mode: 384 });
976
1092
  const written = new Set(batch.map(({ id }) => id));
977
1093
  this.pending = this.pending.filter(({ id }) => !written.has(id));
@@ -1009,7 +1125,8 @@ function createFetchRoutes(face) {
1009
1125
  requestBody: "buffered",
1010
1126
  fetch: async () => {
1011
1127
  try {
1012
- return sendJson(200, { ok: true, entries: (await face.log()).slice(0, LOG_PAGE_LIMIT) });
1128
+ const { entries, recovered } = await face.log();
1129
+ return sendJson(200, { ok: true, entries: entries.slice(0, LOG_PAGE_LIMIT), recovered });
1013
1130
  } catch (err) {
1014
1131
  return sendJson(500, { ok: false, error: describe(err) });
1015
1132
  }
@@ -1023,7 +1140,7 @@ function createFetchRoutes(face) {
1023
1140
  try {
1024
1141
  const input = request.method === "POST" ? await readSubject(request) : void 0;
1025
1142
  if (request.method === "POST" && input === void 0) return sendJson(400, { ok: false });
1026
- return sendJson(200, { ok: true, preview: face.preview(input?.subject) });
1143
+ return sendJson(200, { ok: true, preview: await face.preview(input?.subject, request.signal) });
1027
1144
  } catch (err) {
1028
1145
  return sendJson(500, { ok: false, error: describe(err) });
1029
1146
  }
@@ -1097,11 +1214,7 @@ function apply(ctx, config) {
1097
1214
  const credentials = createJudgeCredentials(ctx.credentials, config.endpointUrl.get());
1098
1215
  const policy = createJudgePolicy({
1099
1216
  refs: config,
1100
- allowedRoutes: () => ctx.get("subagentModelSelection")?.allowedRoutes(),
1101
- routeValidator: () => {
1102
- const llm = ctx.get("llm");
1103
- return llm?.resolveCallConfig.bind(llm);
1104
- },
1217
+ llm: () => ctx.get("llm"),
1105
1218
  resolveKey: credentials.resolve
1106
1219
  });
1107
1220
  const cancelWith = (signal) => signal === void 0 ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);
@@ -1121,9 +1234,11 @@ function apply(ctx, config) {
1121
1234
  let rootId;
1122
1235
  let taskText;
1123
1236
  let stage = "eligibility";
1237
+ const hasOverrides = (settings) => Object.keys(settings.sessionOverrides ?? {}).length > 0;
1238
+ const dispatchEnabled = (settings) => (rootId !== void 0 || !hasOverrides(settings)) && enabledFor(settings.sessionOverrides, settings.enabled, rootId);
1124
1239
  const finish = (status, reason, matched, metrics, selected) => {
1125
1240
  const now = policy.settings();
1126
- if (cancellation.aborted || !now.logEnabled || !enabledFor(now.sessionOverrides, now.enabled, rootId)) return;
1241
+ if (cancellation.aborted || !now.logEnabled || !dispatchEnabled(now)) return;
1127
1242
  log.append(buildEntry({
1128
1243
  route: selected ?? agent.model.current(),
1129
1244
  status,
@@ -1139,19 +1254,19 @@ function apply(ctx, config) {
1139
1254
  };
1140
1255
  try {
1141
1256
  let settings = policy.settings();
1142
- const hasOverrides = Object.keys(settings.sessionOverrides ?? {}).length > 0;
1143
- if (!hasOverrides && !settings.enabled) return;
1257
+ const resolveRoot2 = hasOverrides(settings);
1258
+ if (!resolveRoot2 && !settings.enabled) return;
1144
1259
  if (resumed && hasRecordedRoute(agent.session, resumed)) return;
1145
1260
  const lookup = (id) => ctx.sessions.get(id);
1146
1261
  const parentId = agent.session.header.parentSession;
1147
- if (hasOverrides && parentId) {
1262
+ if (resolveRoot2 && parentId) {
1148
1263
  rootId = await budget.run(() => resolveRootSessionId(parentId, async (id) => {
1149
1264
  budget.check();
1150
1265
  return lookup(id)?.header ?? (await ctx.get("sessionPersistence")?.stat(id))?.header;
1151
1266
  }));
1152
1267
  settings = policy.settings();
1153
1268
  }
1154
- if (judged.has(agent.id) || !enabledFor(settings.sessionOverrides, settings.enabled, rootId)) return;
1269
+ if (judged.has(agent.id) || !dispatchEnabled(settings)) return;
1155
1270
  const plan = policy.prepare(settings);
1156
1271
  timings.eligibility = budget.elapsed();
1157
1272
  if (typeof plan === "string") return finish("skipped", plan);
@@ -1162,12 +1277,10 @@ function apply(ctx, config) {
1162
1277
  if (task === void 0) {
1163
1278
  return finish("skipped", hasRecordedRoute(agent.session, resumed) ? "recorded-route" : "unidentified-task");
1164
1279
  }
1165
- if (task.explicitRoute) return finish("skipped", "explicit-route");
1166
1280
  judged.add(agent.id);
1167
1281
  taskText = task.text;
1168
1282
  const checkTask = () => {
1169
- const current = policy.settings();
1170
- if (rootId === void 0 && !hasOverrides && Object.keys(current.sessionOverrides ?? {}).length > 0 || !enabledFor(current.sessionOverrides, current.enabled, rootId)) return "settings-changed";
1283
+ if (!dispatchEnabled(policy.settings())) return "settings-changed";
1171
1284
  if (hasRecordedRoute(agent.session, resumed)) return "recorded-route";
1172
1285
  };
1173
1286
  stage = "judge";
@@ -1181,9 +1294,9 @@ function apply(ctx, config) {
1181
1294
  const { row, route } = result.match;
1182
1295
  let reason;
1183
1296
  try {
1297
+ reason = await policy.checkFinalRoute(plan, route, budget, checkTask);
1184
1298
  budget.check();
1185
- reason = policy.planIsCurrent(plan) ? checkTask() : "settings-changed";
1186
- if (reason === void 0 && !policy.isAllowed(route)) reason = "unavailable-route";
1299
+ reason ??= policy.planIsCurrent(plan) ? checkTask() : "settings-changed";
1187
1300
  if (reason === void 0) agent.model.select(route);
1188
1301
  } catch {
1189
1302
  reason = budget.expired() ? "timeout" : "unavailable-route";
@@ -1204,11 +1317,16 @@ function apply(ctx, config) {
1204
1317
  });
1205
1318
  ctx.inject(["connection"], (connectionCtx) => {
1206
1319
  const routes = createFetchRoutes({
1207
- log: () => log.readLatest(),
1208
- preview: (subject) => {
1209
- const rows = policy.previewRows();
1210
- const model = policy.settings().judgeModel;
1211
- return subject === void 0 ? buildPreview(rows, model) : formatJudgeRequest(buildJudgeRequest(rows, model, composeJudgeSubject(subject.label, subject.text)));
1320
+ log: () => log.readLatestWithRecovery(),
1321
+ preview: async (subject, signal) => {
1322
+ const snapshot = policy.settings();
1323
+ const budget = new JudgeBudget(cancelWith(signal));
1324
+ try {
1325
+ const rows = await policy.previewRows(snapshot, budget);
1326
+ return subject === void 0 ? buildPreview(rows, snapshot.judgeModel) : formatJudgeRequest(buildJudgeRequest(rows, snapshot.judgeModel, composeJudgeSubject(subject.label, subject.text)));
1327
+ } finally {
1328
+ budget.dispose();
1329
+ }
1212
1330
  },
1213
1331
  keyConfigured: () => credentials.configured(policy.settings().endpointUrl),
1214
1332
  probe: async (signal) => {
@@ -1219,11 +1337,11 @@ function apply(ctx, config) {
1219
1337
  const apiKey = await budget.run(() => credentials.resolve(snapshot.endpointUrl));
1220
1338
  const current = policy.settings();
1221
1339
  if (current.endpointUrl !== snapshot.endpointUrl || current.judgeModel !== snapshot.judgeModel) {
1222
- return { ok: false, reason: "unconfigured", latencyMs: budget.elapsed() };
1340
+ return { ok: false, reason: "settings-changed", latencyMs: budget.elapsed() };
1223
1341
  }
1224
1342
  return await probeJudge({ url: snapshot.endpointUrl, model: snapshot.judgeModel, apiKey }, fetch, budget);
1225
1343
  } catch {
1226
- return { ok: false, reason: budget.expired() ? "timeout" : "unreachable", latencyMs: budget.elapsed() };
1344
+ return { ok: false, reason: budget.expired() ? "timeout" : "credentials-unavailable", latencyMs: budget.elapsed() };
1227
1345
  } finally {
1228
1346
  budget.dispose();
1229
1347
  }
@@ -1238,7 +1356,11 @@ function apply(ctx, config) {
1238
1356
  const budget = new JudgeBudget(cancelWith(signal));
1239
1357
  try {
1240
1358
  const result = await policy.evaluate(plan, task, budget, {});
1241
- if (result.kind === "ready") return { ok: true, typeId: result.match.row.id, route: result.match.route, valid: true };
1359
+ if (result.kind === "ready") {
1360
+ const { row, route } = result.match;
1361
+ const reason = await policy.checkFinalRoute(plan, route, budget) ?? (policy.planIsCurrent(plan) ? void 0 : "settings-changed");
1362
+ return reason === void 0 ? { ok: true, typeId: row.id, route, valid: true } : { ok: false, reason, typeId: row.id, route, valid: false };
1363
+ }
1242
1364
  return {
1243
1365
  ok: false,
1244
1366
  reason: result.reason,