@lynn123411/dsh-subagent-judge-dispatch 0.6.14 → 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/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 };
@@ -483,66 +500,100 @@ function createJudgePolicy(options) {
483
500
  }
484
501
  return rules;
485
502
  }
486
- function allowedRoutes() {
503
+ async function isInCatalog(route, budget) {
487
504
  try {
488
- return options.routeValidator() === void 0 ? [] : options.allowedRoutes() ?? [];
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
+ });
489
511
  } catch {
490
- return [];
512
+ budget.check();
513
+ return false;
491
514
  }
492
515
  }
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
- };
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
+ }
499
529
  function prepare(snapshot) {
500
530
  if (!snapshot.endpointUrl || !snapshot.judgeModel) return "unconfigured";
501
531
  const rows = currentRules();
502
532
  if (rows.length === 0) return "unconfigured";
503
- const candidates = eligibleRows(rows);
504
- return candidates.length === 0 ? "no-authorized-route" : {
533
+ return {
505
534
  url: snapshot.endpointUrl,
506
535
  model: snapshot.judgeModel,
507
- rules: rows,
508
- candidates
536
+ rules: rows
509
537
  };
510
538
  }
511
539
  function planIsCurrent(plan) {
512
540
  const snapshot = settings();
513
541
  return snapshot.endpointUrl === plan.url && snapshot.judgeModel === plan.model && currentRules() === plan.rules;
514
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
+ }
515
561
  async function evaluate(plan, subject, budget, timings, checkTask = () => void 0) {
562
+ const stale = () => planIsCurrent(plan) ? checkTask() : "settings-changed";
516
563
  const judgeStarted = performance.now();
517
- let apiKey;
564
+ let outcome;
565
+ let rejectedBeforeSend;
518
566
  try {
519
- apiKey = await budget.run(() => options.resolveKey(plan.url));
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
+ );
520
592
  } catch {
593
+ return { kind: "keep", stage: "judge", reason: budget.expired() ? "timeout" : "no-authorized-route" };
594
+ } finally {
521
595
  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
596
  }
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
597
  const decision = decideRewrite(outcome);
547
598
  const metrics = outcome.metrics;
548
599
  if (outcome.kind !== "matched" || decision.kind !== "rewrite") {
@@ -551,19 +602,23 @@ function createJudgePolicy(options) {
551
602
  const match = { row: outcome.row, route: decision.rewrite };
552
603
  const preflightStarted = performance.now();
553
604
  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)) {
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)) {
558
609
  return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
559
610
  }
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";
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();
563
618
  if (changedAfterValidation !== void 0) {
564
619
  return { kind: "keep", stage: "preflight", reason: changedAfterValidation, match, metrics };
565
620
  }
566
- budget.check();
621
+ if (options.llm() !== llm) return { kind: "keep", stage: "preflight", reason: "unavailable-route", match, metrics };
567
622
  const effort = resolved?.reasoningEffort;
568
623
  return { kind: "ready", match: { ...match, resolvedEffort: typeof effort === "string" ? effort : match.route.reasoningEffort }, metrics };
569
624
  } catch {
@@ -572,11 +627,11 @@ function createJudgePolicy(options) {
572
627
  timings.preflight = Math.round(performance.now() - preflightStarted);
573
628
  }
574
629
  }
575
- return { settings, prepare, evaluate, planIsCurrent, isAllowed, previewRows: () => eligibleRows(currentRules()) };
630
+ return { settings, prepare, evaluate, planIsCurrent, checkFinalRoute, previewRows };
576
631
  }
577
632
 
578
633
  // src/server/log-store.ts
579
- import { randomUUID } from "node:crypto";
634
+ import { createHash as createHash2, randomUUID } from "node:crypto";
580
635
  import * as fs from "node:fs/promises";
581
636
  import * as path from "node:path";
582
637
 
@@ -796,6 +851,8 @@ var REASONS = [
796
851
  var STATUSES = ["skipped", "kept", "applied"];
797
852
  var STAGES = ["eligibility", "task", "judge", "preflight", "apply"];
798
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 });
799
856
  var ROUTE_MAX_BYTES = 512;
800
857
  var EFFORT_MAX_BYTES = 128;
801
858
  function record(value) {
@@ -906,11 +963,13 @@ var LogStore = class {
906
963
  loading;
907
964
  writing = Promise.resolve();
908
965
  filePath;
966
+ backupPrefix;
909
967
  constructor(filePath = dshHomePath("dsh-subagent-judge-dispatch", "judgements.json")) {
910
968
  this.filePath = filePath;
969
+ this.backupPrefix = `${filePath}.corrupt-`;
911
970
  }
912
971
  init() {
913
- this.loading ??= this.readDisk().then((entries) => {
972
+ this.loading ??= this.readRecovering().then((entries) => {
914
973
  this.entries = entries;
915
974
  }).catch(() => {
916
975
  });
@@ -940,11 +999,18 @@ var LogStore = class {
940
999
  list() {
941
1000
  return this.snapshot(this.entries);
942
1001
  }
943
- async readLatest() {
1002
+ readLatest() {
1003
+ return this.readLatestSnapshot(false).then(({ entries }) => entries);
1004
+ }
1005
+ readLatestWithRecovery() {
1006
+ return this.readLatestSnapshot(true);
1007
+ }
1008
+ async readLatestSnapshot(includeRecovery) {
944
1009
  while (true) {
945
1010
  const previous = this.entries;
946
- const disk = await this.readDisk();
947
- if (this.entries === previous) return this.snapshot(disk);
1011
+ const disk = await this.readRecovering();
1012
+ const recovered = includeRecovery && await this.hasBackup();
1013
+ if (this.entries === previous) return { entries: this.snapshot(disk), recovered };
948
1014
  }
949
1015
  }
950
1016
  snapshot(entries) {
@@ -955,23 +1021,57 @@ var LogStore = class {
955
1021
  await this.writing;
956
1022
  }
957
1023
  async readDisk() {
1024
+ let bytes;
958
1025
  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));
1026
+ bytes = await fs.readFile(this.filePath);
962
1027
  } catch (error) {
963
1028
  if (error.code === "ENOENT") return [];
964
1029
  throw error;
965
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
+ }
966
1064
  }
967
1065
  async write() {
968
1066
  if (this.pending.length === 0) return;
969
1067
  await this.loading;
970
1068
  await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 448 });
971
1069
  await withFileLock(this.filePath, async () => {
972
- const stored = await this.readDisk();
1070
+ const disk = await this.readDisk();
1071
+ const stored = Array.isArray(disk) ? disk : [];
973
1072
  const batch = this.pending.slice();
974
1073
  const retained = retainForWrite(newest([...batch, ...stored]));
1074
+ if (!Array.isArray(disk)) await this.backUp(disk);
975
1075
  await writeFileAtomic(this.filePath, retained.file, { mode: 384 });
976
1076
  const written = new Set(batch.map(({ id }) => id));
977
1077
  this.pending = this.pending.filter(({ id }) => !written.has(id));
@@ -1009,7 +1109,8 @@ function createFetchRoutes(face) {
1009
1109
  requestBody: "buffered",
1010
1110
  fetch: async () => {
1011
1111
  try {
1012
- return sendJson(200, { ok: true, entries: (await face.log()).slice(0, LOG_PAGE_LIMIT) });
1112
+ const { entries, recovered } = await face.log();
1113
+ return sendJson(200, { ok: true, entries: entries.slice(0, LOG_PAGE_LIMIT), recovered });
1013
1114
  } catch (err) {
1014
1115
  return sendJson(500, { ok: false, error: describe(err) });
1015
1116
  }
@@ -1023,7 +1124,7 @@ function createFetchRoutes(face) {
1023
1124
  try {
1024
1125
  const input = request.method === "POST" ? await readSubject(request) : void 0;
1025
1126
  if (request.method === "POST" && input === void 0) return sendJson(400, { ok: false });
1026
- return sendJson(200, { ok: true, preview: face.preview(input?.subject) });
1127
+ return sendJson(200, { ok: true, preview: await face.preview(input?.subject, request.signal) });
1027
1128
  } catch (err) {
1028
1129
  return sendJson(500, { ok: false, error: describe(err) });
1029
1130
  }
@@ -1097,11 +1198,7 @@ function apply(ctx, config) {
1097
1198
  const credentials = createJudgeCredentials(ctx.credentials, config.endpointUrl.get());
1098
1199
  const policy = createJudgePolicy({
1099
1200
  refs: config,
1100
- allowedRoutes: () => ctx.get("subagentModelSelection")?.allowedRoutes(),
1101
- routeValidator: () => {
1102
- const llm = ctx.get("llm");
1103
- return llm?.resolveCallConfig.bind(llm);
1104
- },
1201
+ llm: () => ctx.get("llm"),
1105
1202
  resolveKey: credentials.resolve
1106
1203
  });
1107
1204
  const cancelWith = (signal) => signal === void 0 ? lifetime.signal : AbortSignal.any([signal, lifetime.signal]);
@@ -1121,9 +1218,11 @@ function apply(ctx, config) {
1121
1218
  let rootId;
1122
1219
  let taskText;
1123
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);
1124
1223
  const finish = (status, reason, matched, metrics, selected) => {
1125
1224
  const now = policy.settings();
1126
- if (cancellation.aborted || !now.logEnabled || !enabledFor(now.sessionOverrides, now.enabled, rootId)) return;
1225
+ if (cancellation.aborted || !now.logEnabled || !dispatchEnabled(now)) return;
1127
1226
  log.append(buildEntry({
1128
1227
  route: selected ?? agent.model.current(),
1129
1228
  status,
@@ -1139,19 +1238,19 @@ function apply(ctx, config) {
1139
1238
  };
1140
1239
  try {
1141
1240
  let settings = policy.settings();
1142
- const hasOverrides = Object.keys(settings.sessionOverrides ?? {}).length > 0;
1143
- if (!hasOverrides && !settings.enabled) return;
1241
+ const resolveRoot2 = hasOverrides(settings);
1242
+ if (!resolveRoot2 && !settings.enabled) return;
1144
1243
  if (resumed && hasRecordedRoute(agent.session, resumed)) return;
1145
1244
  const lookup = (id) => ctx.sessions.get(id);
1146
1245
  const parentId = agent.session.header.parentSession;
1147
- if (hasOverrides && parentId) {
1246
+ if (resolveRoot2 && parentId) {
1148
1247
  rootId = await budget.run(() => resolveRootSessionId(parentId, async (id) => {
1149
1248
  budget.check();
1150
1249
  return lookup(id)?.header ?? (await ctx.get("sessionPersistence")?.stat(id))?.header;
1151
1250
  }));
1152
1251
  settings = policy.settings();
1153
1252
  }
1154
- if (judged.has(agent.id) || !enabledFor(settings.sessionOverrides, settings.enabled, rootId)) return;
1253
+ if (judged.has(agent.id) || !dispatchEnabled(settings)) return;
1155
1254
  const plan = policy.prepare(settings);
1156
1255
  timings.eligibility = budget.elapsed();
1157
1256
  if (typeof plan === "string") return finish("skipped", plan);
@@ -1162,12 +1261,10 @@ function apply(ctx, config) {
1162
1261
  if (task === void 0) {
1163
1262
  return finish("skipped", hasRecordedRoute(agent.session, resumed) ? "recorded-route" : "unidentified-task");
1164
1263
  }
1165
- if (task.explicitRoute) return finish("skipped", "explicit-route");
1166
1264
  judged.add(agent.id);
1167
1265
  taskText = task.text;
1168
1266
  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";
1267
+ if (!dispatchEnabled(policy.settings())) return "settings-changed";
1171
1268
  if (hasRecordedRoute(agent.session, resumed)) return "recorded-route";
1172
1269
  };
1173
1270
  stage = "judge";
@@ -1181,9 +1278,9 @@ function apply(ctx, config) {
1181
1278
  const { row, route } = result.match;
1182
1279
  let reason;
1183
1280
  try {
1281
+ reason = await policy.checkFinalRoute(plan, route, budget, checkTask);
1184
1282
  budget.check();
1185
- reason = policy.planIsCurrent(plan) ? checkTask() : "settings-changed";
1186
- if (reason === void 0 && !policy.isAllowed(route)) reason = "unavailable-route";
1283
+ reason ??= policy.planIsCurrent(plan) ? checkTask() : "settings-changed";
1187
1284
  if (reason === void 0) agent.model.select(route);
1188
1285
  } catch {
1189
1286
  reason = budget.expired() ? "timeout" : "unavailable-route";
@@ -1204,11 +1301,16 @@ function apply(ctx, config) {
1204
1301
  });
1205
1302
  ctx.inject(["connection"], (connectionCtx) => {
1206
1303
  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)));
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
+ }
1212
1314
  },
1213
1315
  keyConfigured: () => credentials.configured(policy.settings().endpointUrl),
1214
1316
  probe: async (signal) => {
@@ -1219,11 +1321,11 @@ function apply(ctx, config) {
1219
1321
  const apiKey = await budget.run(() => credentials.resolve(snapshot.endpointUrl));
1220
1322
  const current = policy.settings();
1221
1323
  if (current.endpointUrl !== snapshot.endpointUrl || current.judgeModel !== snapshot.judgeModel) {
1222
- return { ok: false, reason: "unconfigured", latencyMs: budget.elapsed() };
1324
+ return { ok: false, reason: "settings-changed", latencyMs: budget.elapsed() };
1223
1325
  }
1224
1326
  return await probeJudge({ url: snapshot.endpointUrl, model: snapshot.judgeModel, apiKey }, fetch, budget);
1225
1327
  } catch {
1226
- return { ok: false, reason: budget.expired() ? "timeout" : "unreachable", latencyMs: budget.elapsed() };
1328
+ return { ok: false, reason: budget.expired() ? "timeout" : "credentials-unavailable", latencyMs: budget.elapsed() };
1227
1329
  } finally {
1228
1330
  budget.dispose();
1229
1331
  }
@@ -1238,7 +1340,11 @@ function apply(ctx, config) {
1238
1340
  const budget = new JudgeBudget(cancelWith(signal));
1239
1341
  try {
1240
1342
  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 };
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
+ }
1242
1348
  return {
1243
1349
  ok: false,
1244
1350
  reason: result.reason,