@staix/agent-hub 0.53.0 → 0.54.0

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.
Files changed (88) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.md +4 -3
  3. package/docs/agent-notes/README.md +1 -1
  4. package/docs/agent-notes/adapters.md +4 -3
  5. package/docs/agent-notes/budget.md +2 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +1 -1
  8. package/docs/agent-notes/models.md +1 -1
  9. package/docs/agent-notes/tests.md +4 -4
  10. package/docs/contracts/companion-cli-v3.json +348 -0
  11. package/docs/design/adapters.md +1 -1
  12. package/docs/design/agent-hub-architecture.md +8 -5
  13. package/docs/design/bus.md +1 -1
  14. package/docs/design/cli-output-inventory.md +2 -2
  15. package/docs/design/model-routes.md +20 -5
  16. package/docs/dogfood.md +7 -3
  17. package/docs/events.md +1 -1
  18. package/docs/memory.md +2 -2
  19. package/docs/operations.md +122 -45
  20. package/docs/quickstart.md +8 -2
  21. package/docs/security.md +11 -7
  22. package/docs/specs/2026-09-19-agent-hub-design.md +5 -3
  23. package/docs/specs/2026-09-19-multi-project-design.md +1 -1
  24. package/docs/specs/2026-12-04-arev-adoption-design.md +3 -3
  25. package/docs/specs/mcp-endpoint.md +1 -1
  26. package/docs/specs/relay-contract.md +38 -0
  27. package/docs/verification/2026-12-06-0.54.0.md +76 -0
  28. package/docs/verification/2026-12-06-codex-0174-reviewer-isolation.md +43 -0
  29. package/docs/verification/2026-12-06-codex-0174-reviewer-tool-call.md +34 -0
  30. package/docs/verification/2026-12-06-compat-codex-capabilities-0.174.0.md +25 -0
  31. package/docs/verification/2026-12-06-compat-pi-1.8.0.md +23 -0
  32. package/docs/verified.json +27 -28
  33. package/package.json +5 -4
  34. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  35. package/plugins/agent-hub/.mcp.json +1 -1
  36. package/plugins/agent-hub/compat.json +5 -3
  37. package/plugins/agent-hub/kimi-hook.js +5 -4
  38. package/plugins/agent-hub/relay-launcher.js +24 -0
  39. package/plugins/agent-hub/server.js +5112 -4737
  40. package/src/adapters/acp.ts +5 -4
  41. package/src/adapters/compat.ts +22 -12
  42. package/src/adapters/definitions/native-cli-preview-pi.ts +2 -1
  43. package/src/adapters/definitions/native-config-defaults.ts +1 -1
  44. package/src/adapters/definitions/native-factories.ts +4 -1
  45. package/src/adapters/local-worker.ts +3 -3
  46. package/src/adapters/pi.ts +26 -7
  47. package/src/adapters/relay-launcher.ts +27 -0
  48. package/src/cli/agents.ts +20 -8
  49. package/src/cli/commands/agents.ts +18 -1
  50. package/src/cli/commands/doctor.ts +18 -4
  51. package/src/cli/commands/launch-line.ts +13 -5
  52. package/src/cli/help.ts +4 -2
  53. package/src/cli/launch-line-plan.ts +82 -0
  54. package/src/cli/pi-steps-warning.ts +14 -0
  55. package/src/hub/accounts.ts +8 -4
  56. package/src/hub/adec-triage.ts +105 -0
  57. package/src/hub/bus.ts +39 -6
  58. package/src/hub/config-apply.ts +1 -1
  59. package/src/hub/config.ts +2 -2
  60. package/src/hub/control/dashboard-messages.ts +221 -0
  61. package/src/hub/control/delivery-messages.ts +356 -0
  62. package/src/hub/control/dispatch.ts +114 -0
  63. package/src/hub/control/operations-messages.ts +269 -0
  64. package/src/hub/control/peer-messages.ts +126 -0
  65. package/src/hub/control/scope.ts +79 -2
  66. package/src/hub/daemon.ts +111 -918
  67. package/src/hub/delivery-hints.ts +2 -0
  68. package/src/hub/delivery-journal.ts +17 -6
  69. package/src/hub/events.ts +2 -1
  70. package/src/hub/host.ts +41 -9
  71. package/src/hub/lifecycle.ts +3 -2
  72. package/src/hub/peers.ts +2 -0
  73. package/src/hub/pi-exit-policy.ts +27 -0
  74. package/src/hub/protocol-window.ts +1 -1
  75. package/src/hub/routing.ts +9 -0
  76. package/src/hub/supervision.ts +33 -6
  77. package/src/hub/tasks-types.ts +4 -1
  78. package/src/hub/tasks.ts +35 -1
  79. package/src/models/route/config.ts +4 -4
  80. package/src/models/route/decision.ts +18 -10
  81. package/src/models/route/runtime.ts +8 -5
  82. package/src/npm-artifact.ts +76 -0
  83. package/src/omniroute/client.ts +6 -0
  84. package/src/pi/extension.ts +5 -2
  85. package/src/pi/install.ts +77 -0
  86. package/src/pi/pin.ts +49 -0
  87. package/templates/adec/README.md +10 -6
  88. package/templates/config.json +1 -1
@@ -1,5 +1,7 @@
1
1
  import { KINDS, sanitize, type Kind } from "./envelope.ts";
2
2
 
3
+ /** #1946: the reason an ACP session stop leaves on a row (src/adapters/acp.ts). It is the one needs_review reason that holds only its own row; the producer and the bus both use this constant. */
4
+ export const ACP_STOPPED_BEFORE_SETTLEMENT = "ACP session stopped before settlement";
3
5
  export const HELD_DELIVERY_PAGE = 32;
4
6
  export const MAX_HELD_HINT_ROWS = 32;
5
7
  export const DELIVERY_RETRY_WARNING = sanitize("Hub redelivery warning: An earlier attempt of this delivery is uncertain; check for its effects before acting.");
@@ -55,6 +55,8 @@ export interface JournalDelivery {
55
55
  out: Envelope[];
56
56
  reason?: string;
57
57
  failureCause?: DeliveryFailureCause;
58
+ /** #1946: a host-owned mark (only the ACP adapter's own unrequested stop sets it): this needs_review row holds only itself. Never derived from reason text. */
59
+ holdsSelf?: true;
58
60
  attempt?: number;
59
61
  previousId?: string;
60
62
  }
@@ -320,6 +322,7 @@ function validateDelivery(value: unknown, name = "delivery"): JournalDelivery {
320
322
  );
321
323
  if (d.reason !== undefined) text(d.reason, `${name}.reason`, 1_000_000);
322
324
  const failureCause = checkedFailureCause(d.failureCause);
325
+ if (d.holdsSelf !== undefined && d.holdsSelf !== true) fail(`${name}.holdsSelf is invalid`);
323
326
  if (d.attempt !== undefined) integer(d.attempt, `${name}.attempt`, 0, 100);
324
327
  if (d.previousId !== undefined) text(d.previousId, `${name}.previousId`, 256);
325
328
  return {
@@ -333,6 +336,7 @@ function validateDelivery(value: unknown, name = "delivery"): JournalDelivery {
333
336
  out,
334
337
  ...(d.reason === undefined ? {} : { reason: d.reason as string }),
335
338
  ...(failureCause === undefined ? {} : { failureCause }),
339
+ ...(d.holdsSelf === true ? { holdsSelf: true as const } : {}),
336
340
  ...(d.attempt === undefined ? {} : { attempt: d.attempt as number }),
337
341
  ...(d.previousId === undefined
338
342
  ? {}
@@ -497,6 +501,7 @@ export class DeliveryJournal {
497
501
  );
498
502
  const deliveryColumns = this.db.query("PRAGMA table_info(deliveries)").all() as { name: string }[];
499
503
  if (!deliveryColumns.some(column => column.name === "failure_cause")) this.db.run("ALTER TABLE deliveries ADD COLUMN failure_cause TEXT");
504
+ if (!deliveryColumns.some(column => column.name === "holds_self")) this.db.run("ALTER TABLE deliveries ADD COLUMN holds_self INTEGER");
500
505
  this.db.run("CREATE TABLE IF NOT EXISTS review_input_sessions (project_id TEXT NOT NULL, peer TEXT NOT NULL, session_hash TEXT NOT NULL, input_hash TEXT, PRIMARY KEY(project_id,peer,session_hash))");
501
506
  this.db.run("CREATE TABLE IF NOT EXISTS review_input_incomplete_peers (project_id TEXT NOT NULL, peer TEXT NOT NULL, PRIMARY KEY(project_id,peer))");
502
507
  this.db.run("CREATE TABLE IF NOT EXISTS review_input_incomplete_sessions (project_id TEXT NOT NULL, peer TEXT NOT NULL, session_hash TEXT NOT NULL, PRIMARY KEY(project_id,peer,session_hash))");
@@ -1249,7 +1254,7 @@ export class DeliveryJournal {
1249
1254
  for (const d of deliveries)
1250
1255
  this.db
1251
1256
  .query(
1252
- "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1257
+ "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause, holds_self) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1253
1258
  )
1254
1259
  .run(
1255
1260
  d.id,
@@ -1265,6 +1270,7 @@ export class DeliveryJournal {
1265
1270
  d.attempt ?? null,
1266
1271
  d.previousId ?? null,
1267
1272
  checkedFailureCause(d.failureCause) ?? null,
1273
+ d.holdsSelf === true ? 1 : null,
1268
1274
  );
1269
1275
  this.refreshReviewInputCoverage(true);
1270
1276
  this.harden();
@@ -1316,7 +1322,7 @@ export class DeliveryJournal {
1316
1322
  this.writeQueueMetadata(bus, revision, trackQueuePressure);
1317
1323
  this.db
1318
1324
  .query(
1319
- "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1325
+ "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause, holds_self) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1320
1326
  )
1321
1327
  .run(
1322
1328
  delivery.id,
@@ -1332,6 +1338,7 @@ export class DeliveryJournal {
1332
1338
  delivery.attempt ?? null,
1333
1339
  delivery.previousId ?? null,
1334
1340
  checkedFailureCause(delivery.failureCause) ?? null,
1341
+ delivery.holdsSelf === true ? 1 : null,
1335
1342
  );
1336
1343
  this.harden();
1337
1344
  return { ...delivery, revision, updatedAt: now };
@@ -1354,7 +1361,7 @@ export class DeliveryJournal {
1354
1361
  const updatedAt = input.updatedAt ?? Date.now();
1355
1362
  this.db
1356
1363
  .query(
1357
- "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1364
+ "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause, holds_self) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1358
1365
  )
1359
1366
  .run(
1360
1367
  input.id,
@@ -1370,6 +1377,7 @@ export class DeliveryJournal {
1370
1377
  input.attempt ?? null,
1371
1378
  input.previousId ?? null,
1372
1379
  checkedFailureCause(input.failureCause) ?? null,
1380
+ input.holdsSelf === true ? 1 : null,
1373
1381
  );
1374
1382
  this.pruneTerminal(input.state, input.id);
1375
1383
  return { ...input, revision, updatedAt };
@@ -1442,6 +1450,7 @@ export class DeliveryJournal {
1442
1450
  reason?: string,
1443
1451
  expectedRevision?: number,
1444
1452
  failureCause?: DeliveryFailureCause,
1453
+ holdsSelf?: boolean,
1445
1454
  ): JournalDelivery {
1446
1455
  this.ensureOpen();
1447
1456
  if (!STATES.has(state)) throw new Error("invalid delivery state");
@@ -1456,9 +1465,9 @@ export class DeliveryJournal {
1456
1465
  const revision = this.bump();
1457
1466
  this.db
1458
1467
  .query(
1459
- "UPDATE deliveries SET state = ?, revision = ?, updated_at = ?, reason = ?, failure_cause = ? WHERE id = ? AND project_id = ?",
1468
+ "UPDATE deliveries SET state = ?, revision = ?, updated_at = ?, reason = ?, failure_cause = ?, holds_self = ? WHERE id = ? AND project_id = ?",
1460
1469
  )
1461
- .run(state, revision, Date.now(), reason ?? null, failureCause ?? old.failureCause ?? null, id, this.projectId);
1470
+ .run(state, revision, Date.now(), reason ?? null, failureCause ?? old.failureCause ?? null, holdsSelf === undefined ? (old.holdsSelf ? 1 : null) : holdsSelf ? 1 : null, id, this.projectId);
1462
1471
  this.refreshReviewInputCoverage(true);
1463
1472
  this.pruneTerminal(state, id);
1464
1473
  return this.get(id)!;
@@ -1859,7 +1868,7 @@ export class DeliveryJournal {
1859
1868
  for (const row of snapshot.deliveries)
1860
1869
  this.db
1861
1870
  .query(
1862
- "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1871
+ "INSERT INTO deliveries (id, project_id, peer, state, revision, created_at, updated_at, originals, out_json, reason, attempt, previous_id, failure_cause, holds_self) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
1863
1872
  )
1864
1873
  .run(
1865
1874
  row.id,
@@ -1875,6 +1884,7 @@ export class DeliveryJournal {
1875
1884
  row.attempt ?? null,
1876
1885
  row.previousId ?? null,
1877
1886
  checkedFailureCause(row.failureCause) ?? null,
1887
+ row.holdsSelf === true ? 1 : null,
1878
1888
  );
1879
1889
  for (const raw of reviewInputProvenance.holds) {
1880
1890
  const hold = reviewInputHold(raw, "snapshot review input");
@@ -1917,6 +1927,7 @@ function parseDelivery(row: Record<string, unknown>): JournalDelivery {
1917
1927
  out: JSON.parse(String(row.out_json)),
1918
1928
  ...(row.reason == null ? {} : { reason: String(row.reason) }),
1919
1929
  ...(row.failure_cause == null ? {} : { failureCause: row.failure_cause }),
1930
+ ...(row.holds_self === 1 ? { holdsSelf: true } : {}),
1920
1931
  ...(row.attempt == null ? {} : { attempt: Number(row.attempt) }),
1921
1932
  ...(row.previous_id == null ? {} : { previousId: String(row.previous_id) }),
1922
1933
  });
package/src/hub/events.ts CHANGED
@@ -2,6 +2,7 @@ import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSyn
2
2
  import type { TaskAttribution } from "./attribution.ts";
3
3
  import { segmentsOf, streamEnd } from "./log-rotation.ts";
4
4
  import type { PeerId } from "./envelope.ts";
5
+ import type { DecisionTrace } from "../models/route/decision.ts";
5
6
  import type { StageSwitchTrace as SwitchTrace } from "../models/route/stage-fallback.ts";
6
7
  import type { ScreenRecord } from "./inference.ts";
7
8
  import { safeModelLabel } from "../omniroute/usage.ts";
@@ -76,7 +77,7 @@ export type HubEvent =
76
77
  | { type: "quiet"; id: string; from: string; peers: string[] }
77
78
  | { type: "fact"; peer: string; id: string; files: number; plans: number; unknown: number; named: number; bytes: number; via: "hook" | "steer" | "done"; ms?: number; hookMs?: number; rttMs?: number; accepted?: boolean; unanswered?: boolean; probe?: boolean; coverage?: boolean }
78
79
  | { type: "fact_ack"; peer: string; id: string; via: string; ms: number }
79
- | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionTarget?: "judge"; decisionMode?: "off" | "shadow"; chosenAlias?: string | null; chosenEffort?: string | null; margin?: number; decisionLatencyMs?: number; decisionReason?: string; fallbackApplied?: boolean; decider?: { provider: string; model: string; version?: string; latencyMs: number } | null; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial<SwitchTrace>)
80
+ | ({ type: "route"; peer: string; route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin" | "decision"; score: number; ms: number; decisionTarget?: "judge"; stateless?: boolean; decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number } & Partial<SwitchTrace> & Partial<DecisionTrace>)
80
81
  | { type: "cooldown"; peer: string; alias: string; event: "start" | "end"; failures: number; ms?: number }
81
82
  | { type: "route_outcome"; peer: string; decision: string; turnId: string; turn: "completed" | "failed"; task?: number; pii: boolean; latched: boolean; next?: { severity: number; tests: "pass" | "fail" | "none"; repeat: boolean }; advisor?: "approve" | "redo" | "failed" }
82
83
  | { type: "advisor"; peer: string; route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }
package/src/hub/host.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { WebSocketHandler } from "bun";
1
2
  import { AsyncLocalStorage } from "node:async_hooks";
2
3
  import { createHash, randomUUID } from "node:crypto";
3
4
  import { chmodSync, existsSync, mkdirSync, rmSync } from "node:fs";
@@ -12,7 +13,21 @@ import { processSignature } from "../pi/process-signature.ts";
12
13
  /** What a launched project gives the host: the daemon's stop and its end, and the registry claim to give back. */
13
14
  export interface HostedDaemon { stop(): Promise<void>; stopped: Promise<unknown> }
14
15
  export interface Launched { daemon: HostedDaemon; release(): void }
15
- export type Launch = (project: Project, options: { unattended: boolean; hostId: string }) => Promise<Launched>;
16
+ export interface HostLaunchOptions {
17
+ unattended: boolean;
18
+ hostId: string;
19
+ runControlWebSocket(callback: () => void): void;
20
+ }
21
+ export type Launch = (project: Project, options: HostLaunchOptions) => Promise<Launched>;
22
+
23
+ export function hostedControlWebSocket<T>(handler: WebSocketHandler<T>, run?: HostLaunchOptions["runControlWebSocket"]): WebSocketHandler<T> {
24
+ if (!run) return handler;
25
+ return {
26
+ ...handler,
27
+ message(socket, data) { run(() => handler.message(socket, data)); },
28
+ close(socket, code, reason) { run(() => handler.close?.(socket, code, reason)); },
29
+ };
30
+ }
16
31
 
17
32
  export interface HostOptions {
18
33
  launch: Launch;
@@ -59,7 +74,23 @@ export class Host {
59
74
  if (this.projects.has(project.id) || this.pending.has(project.id)) throw new Error("project already runs in this host");
60
75
  this.pending.add(project.id); // reserve the id across the await
61
76
  let launched: Launched;
62
- try { launched = await this.within(project.id, () => this.options.launch(project, { unattended, hostId: this.id })); }
77
+ let controlFailure: { error: unknown } | undefined;
78
+ const stopForControlFailure = (error: unknown) => {
79
+ const running = this.projects.get(project.id);
80
+ if (running && running.launched === launched) {
81
+ void this.stopFailedProject(project.id, error, "uncaught exception").catch(() => {});
82
+ }
83
+ };
84
+ const runControlWebSocket = (callback: () => void) => this.within(project.id, () => {
85
+ try { callback(); }
86
+ catch (error) {
87
+ if (controlFailure) return;
88
+ // Bun may lose the async context when a WebSocket throw escapes into the process hook.
89
+ controlFailure = { error };
90
+ stopForControlFailure(error);
91
+ }
92
+ });
93
+ try { launched = await this.within(project.id, () => this.options.launch(project, { unattended, hostId: this.id, runControlWebSocket })); }
63
94
  catch (error) { this.pending.delete(project.id); this.maybeFinish(); throw error; }
64
95
  finally { this.pending.delete(project.id); }
65
96
  this.everAdded = true;
@@ -69,6 +100,7 @@ export class Host {
69
100
  this.maybeFinish();
70
101
  });
71
102
  this.projects.set(project.id, { project, launched, ended });
103
+ if (controlFailure) stopForControlFailure(controlFailure.error);
72
104
  }
73
105
 
74
106
  /** Stop one project, leaving the others serving. Removes its listener, timers and children through the daemon's own stop. */
@@ -106,16 +138,16 @@ export class Host {
106
138
  if (this.everAdded && this.projects.size === 0 && this.pending.size === 0 && !this.closing) { this.uninstall(); this.finish(); }
107
139
  }
108
140
 
141
+ private async stopFailedProject(id: string, error: unknown, kind: string): Promise<void> {
142
+ this.log(`${kind} in project ${id}; stopping that project only: ${error instanceof Error ? error.message : String(error)}`);
143
+ await this.stopProject(id);
144
+ }
145
+
109
146
  /** An uncaught error: stops the project it belongs to, or, with no attribution, the host. */
110
147
  async handleUncaught(error: unknown, kind = "uncaught exception"): Promise<void> {
111
- const text = error instanceof Error ? error.message : String(error);
112
148
  const id = this.currentProject();
113
- if (id !== undefined && this.projects.has(id)) {
114
- this.log(`${kind} in project ${id}; stopping that project only: ${text}`);
115
- await this.stopProject(id);
116
- return;
117
- }
118
- this.log(`${kind} outside any project; stopping the host: ${text}`);
149
+ if (id !== undefined && this.projects.has(id)) return this.stopFailedProject(id, error, kind);
150
+ this.log(`${kind} outside any project; stopping the host: ${error instanceof Error ? error.message : String(error)}`);
119
151
  await this.stopAll();
120
152
  }
121
153
 
@@ -1,3 +1,4 @@
1
+ import type { HostLaunchOptions } from "./host.ts";
1
2
  import { waitForStartupReadiness, type StartupOwner } from "./startup-readiness.ts";
2
3
  import { rotateTextLogAtStart } from "./log-rotation.ts";
3
4
  import { resolveProjectRuntime, recordProjectRuntime, confirmProjectRuntime, readProjectRuntimeForCaller, projectRuntimeRefusal, type ProjectRuntimeSelection } from "./project-runtime.ts";
@@ -182,7 +183,7 @@ export async function runProjectDaemon(project: Project, unattended = false): Pr
182
183
  * #1779 T3a: the daemon half of `runProjectDaemon`, for a host process that owns the signals and the forced exit.
183
184
  * ponytail: it mirrors `runProjectDaemon`'s claim, runtime check and port loop so the default one-process path stays byte-identical; fold the two once shared mode is the default (T5).
184
185
  */
185
- export async function launchHostedProject(project: Project, opts: { unattended: boolean; hostId: string; env: NodeJS.ProcessEnv }): Promise<{ daemon: Awaited<ReturnType<typeof import("./daemon.ts").startDaemon>>; release(): void }> {
186
+ export async function launchHostedProject(project: Project, opts: HostLaunchOptions & { env: NodeJS.ProcessEnv }): Promise<{ daemon: Awaited<ReturnType<typeof import("./daemon.ts").startDaemon>>; release(): void }> {
186
187
  assertLifecycleAvailable(project.root);
187
188
  assertHubDbCompatible(join(project.stateDir, "hub.db"));
188
189
  const registry = new Registry();
@@ -210,7 +211,7 @@ export async function launchHostedProject(project: Project, opts: { unattended:
210
211
  for (let attempt = 0; attempt < 100; attempt++) {
211
212
  if (await available(base)) {
212
213
  try {
213
- daemon = await startDaemon({ cwd: project.root, stateDir: project.stateDir, projectId: project.id, instanceId, mcpHome: hubHome(), mcpServe: true, context, hostId: opts.hostId,
214
+ daemon = await startDaemon({ cwd: project.root, stateDir: project.stateDir, projectId: project.id, instanceId, mcpHome: hubHome(), mcpServe: true, context, hostId: opts.hostId, runControlWebSocket: opts.runControlWebSocket,
214
215
  controlPort: base + CONTROL, codexAppPort: base + CODEX_APP, codexProxyPort: base + CODEX_PROXY,
215
216
  unattended: opts.unattended, agentDrift: true,
216
217
  terminal: (template) => terminalOpener({ template, cwd: project.root, stateDir: project.stateDir }) });
package/src/hub/peers.ts CHANGED
@@ -13,6 +13,8 @@ export interface DeliveryReceipt {
13
13
  reason?: string;
14
14
  /** Public-safe transport cause only, never native error text. */
15
15
  failureCause?: DeliveryFailureCause;
16
+ /** #1946: only the in-process ACP adapter's own unrequested stop sets this; the control receipt path never copies it from a caller. */
17
+ holdsSelf?: true;
16
18
  /** A provider refused before acceptance for quota; requeue without spending poison retries while paused. */
17
19
  quota?: true;
18
20
  }
@@ -0,0 +1,27 @@
1
+ import type { PiExit } from "../adapters/pi.ts";
2
+
3
+ /** #1967 T1: one label per unexpected Pi exit, so the log and the restart rule name the same cause. Never carries task text. */
4
+ export function piExitReason(exit: Pick<PiExit, "cause" | "code" | "signal" | "modelProvider">): string {
5
+ if (exit.signal) return `signal:${exit.signal}`;
6
+ if (exit.cause === "session_shutdown" && exit.modelProvider) return `model_select:${exit.modelProvider}`;
7
+ if (exit.cause === "session_shutdown" && exit.code === null) return "session_shutdown";
8
+ if (exit.code !== null) return `code:${exit.code}`;
9
+ return exit.cause;
10
+ }
11
+
12
+ /** A killed or self-shutdown owner has no clean exit code to explain it; the owner may restart once (#1967). A plain exit code keeps the earlier inspect-first rule. */
13
+ export const piRestartableReason = (reason: string): boolean => reason.startsWith("signal:") || reason === "session_shutdown" || reason.startsWith("model_select:");
14
+
15
+ const PI_SAME_CAUSE_WINDOW_MS = 10 * 60_000;
16
+
17
+ /** Per peer: an owner restarts once after an unexpected exit, and not again while the same cause repeats inside the window. */
18
+ export class PiRestartLedger {
19
+ // Keyed by peer and cause, so a different cause never erases the window of an earlier one.
20
+ private readonly last = new Map<string, number>();
21
+ private key(peer: string, reason: string): string { return JSON.stringify([peer, reason]); }
22
+ allow(peer: string, reason: string, now: number): boolean {
23
+ const previous = this.last.get(this.key(peer, reason));
24
+ return !(previous !== undefined && now - previous < PI_SAME_CAUSE_WINDOW_MS);
25
+ }
26
+ record(peer: string, reason: string, now: number): void { this.last.set(this.key(peer, reason), now); }
27
+ }
@@ -43,7 +43,7 @@ export const BRIDGE_PROTOCOL_RELEASES = [
43
43
  [14, "v0.12.16", "2026-10-09", "v0.12.16", "2026-10-09"],
44
44
  [15, "v0.12.17", "2026-10-09", "v0.12.19", "2026-10-09"],
45
45
  [16, "v0.12.20", "2026-10-09", "v0.25.0", "2026-11-01"],
46
- [17, "v0.26.0", "2026-11-01", "v0.53.0", "2026-12-05"],
46
+ [17, "v0.26.0", "2026-11-01", "v0.54.0", "2026-12-06"],
47
47
  ] as const;
48
48
 
49
49
  export function bridgeWindowSettings(raw: unknown): BridgeWindowSettings {
@@ -1,4 +1,5 @@
1
1
  import { contextHeadroom, type ContextAdmission } from "./context-window.ts";
2
+ import { DEFAULT_TRIAGE_ENDPOINT, isTriageEndpoint } from "./adec-triage.ts";
2
3
  import { queueBackpressure, type QueueBackpressureCode, type QueueBackpressurePolicy, type QueuePressure } from "./queue-backpressure.ts";
3
4
  import { selectReviewerPool, type ReviewerPoolSelection } from "./reviewer-pool.ts";
4
5
  import type { ReviewBudgetSnapshot } from "./review-budget.ts";
@@ -37,6 +38,8 @@ export interface Routing {
37
38
  local: { route?: string; fixed_model: string };
38
39
  /** Loader-owned diagnostics for ignored legacy routing tables. */
39
40
  retired?: string[];
41
+ /** #1936: the person's switch for adec triage, read from routing.toml only (the overlay cannot set it). */
42
+ inference: { triage_adec: "off" | "shadow" | "enforce"; triage_adec_endpoint: string };
40
43
  hub_routes?: Record<string, HubRoute>;
41
44
  /** Session-aware stay/switch for `hub/auto` and hub stage routes (#197). */
42
45
  stay_switch: StaySwitchMode;
@@ -251,8 +254,14 @@ export function parseRouting(text: string, overlay?: RoutingOverlay): Routing {
251
254
  if (nested) throw new Error(`routing.toml: ${nested} is inside a table; stay_switch and max_switch_prefill_tokens are top-level keys, before any table`);
252
255
  if (!["off", "shadow", "enforce"].includes(stay_switch)) throw new Error('routing.toml: stay_switch must be "off", "shadow" or "enforce" (a top-level key, before any table)');
253
256
  if (!(Number.isSafeInteger(max_switch_prefill_tokens) && max_switch_prefill_tokens > 0)) throw new Error("routing.toml: max_switch_prefill_tokens must be a positive integer");
257
+ const rawInference = ((raw as Record<string, unknown>).inference ?? {}) as Record<string, unknown>;
258
+ for (const name of Object.keys(rawInference)) if (name !== "triage_adec" && name !== "triage_adec_endpoint") throw new Error(`routing.toml: [inference] ${name} is not a key; use triage_adec or triage_adec_endpoint`);
259
+ const triageAdec = rawInference.triage_adec ?? "off", triageEndpoint = rawInference.triage_adec_endpoint ?? DEFAULT_TRIAGE_ENDPOINT;
260
+ if (triageAdec !== "off" && triageAdec !== "shadow" && triageAdec !== "enforce") throw new Error('routing.toml: [inference] triage_adec must be "off", "shadow" or "enforce"');
261
+ if (!isTriageEndpoint(triageEndpoint)) throw new Error("routing.toml: [inference] triage_adec_endpoint must be an HTTP numeric loopback /v1/systemone URL without credentials, query or fragment");
254
262
  return {
255
263
  local: raw.local,
264
+ inference: { triage_adec: triageAdec, triage_adec_endpoint: triageEndpoint },
256
265
  ...(retired.length ? { retired } : {}),
257
266
  hub_routes: parseHubRoutes(raw.hub_routes),
258
267
  stay_switch,
@@ -44,9 +44,14 @@ export interface SupervisionDeps {
44
44
  }
45
45
 
46
46
  /** Deterministic milestone producer. The Bus alone owns batching, retry and native turns. */
47
+ /** #1946: the delivery id a hold notice key names, for the first notice and its one `:repeat`; undefined for any other key. */
48
+ export const holdNoticeDelivery = (key: string): string | undefined => key.match(/:hold:[^:]+:([^:]+?)(?::repeat)?$/)?.[1];
49
+
47
50
  export class SupervisionFeed {
48
51
  private readonly approvals = new Set<string>();
49
52
  private readonly holds = new Set<string>();
53
+ private readonly holdSentAt = new Map<string, number>();
54
+ private readonly holdRepeated = new Set<string>();
50
55
  private readonly rounds = new Map<string, string>();
51
56
  /** #1738: the key of the last round check that sent nothing; never set after a refused send, which must stay retryable. */
52
57
  private quietRound: string | undefined;
@@ -59,7 +64,7 @@ export class SupervisionFeed {
59
64
  /** Pending notices may have been withdrawn on role/off change; live requests can notify again on regrant. */
60
65
  resetPending(peer: string): void {
61
66
  for (const key of this.approvals) if (key.startsWith(`${peer}:`)) this.approvals.delete(key);
62
- for (const key of this.holds) if (key.startsWith(`${peer}:`)) this.holds.delete(key);
67
+ for (const key of this.holds) if (key.startsWith(`${peer}:`)) { this.holds.delete(key); this.holdSentAt.delete(key); this.holdRepeated.delete(key); }
63
68
  }
64
69
 
65
70
  private recipient(): string | undefined {
@@ -157,13 +162,35 @@ export class SupervisionFeed {
157
162
  return sent;
158
163
  }
159
164
 
160
- needsReview(peer: string, deliveryId: string, command: string | (() => string) = () => queueResolveCommand({ id: deliveryId, peer })): boolean { // a thunk is built only when the notice is sent, not on every tick
165
+ /**
166
+ * The hold notice for a needs_review row. #1946: the conductor may run `ahub queue resolve` for a plain row, so the notice says so; an invocation row stays person-only.
167
+ * It repeats once after `afterMs` while the row is still held, then stops. A thunk is built only when a notice is sent, not on every tick.
168
+ */
169
+ needsReview(peer: string, deliveryId: string, command: string | (() => string) = () => queueResolveCommand({ id: deliveryId, peer }), opts?: { personOnly?: boolean; afterMs: number }): boolean {
161
170
  const conductor = this.recipient();
162
171
  const key = `${conductor}:${peer}:${deliveryId}`;
163
- if (!conductor || this.holds.has(key)) return false;
164
- const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; give the person this command exactly as printed: ${typeof command === "string" ? command : command()}`, "important");
165
- if (sent) this.holds.add(key);
166
- return sent;
172
+ if (!conductor) return false;
173
+ if (!opts) { // a row that holds the peer wide keeps the notice it always had
174
+ if (this.holds.has(key)) return false;
175
+ const sent = this.send(`hold:${peer}:${deliveryId}`, `${peer}: needs_review hold; delivery ${deliveryId}; give the person this command exactly as printed: ${typeof command === "string" ? command : command()}`, "important");
176
+ if (sent) this.holds.add(key);
177
+ return sent;
178
+ }
179
+ const text = (prefix: string) => `${peer}: needs_review hold; delivery ${deliveryId}; ${prefix}${opts.personOnly
180
+ ? "an invocation row is person-only: give the person this command exactly as printed"
181
+ : "you, the conductor, may run this command exactly as printed (the person may too)"}: ${typeof command === "string" ? command : command()}`;
182
+ if (!this.holds.has(key)) {
183
+ const sent = this.send(`hold:${peer}:${deliveryId}`, text(""), "important");
184
+ if (sent) { this.holds.add(key); this.holdSentAt.set(key, this.d.now?.() ?? Date.now()); }
185
+ return sent;
186
+ }
187
+ const at = this.holdSentAt.get(key);
188
+ if (opts.afterMs > 0 && at !== undefined && !this.holdRepeated.has(key) && (this.d.now?.() ?? Date.now()) - at >= opts.afterMs) {
189
+ const sent = this.send(`hold:${peer}:${deliveryId}:repeat`, text("still unresolved; "), "important");
190
+ if (sent) this.holdRepeated.add(key);
191
+ return sent;
192
+ }
193
+ return false;
167
194
  }
168
195
 
169
196
  checkRound(): boolean {
@@ -1,4 +1,5 @@
1
1
  // The type and interface declarations of the task flow (#1830 S4e-1): moved unchanged out of tasks.ts, which re-exports every name it exported before.
2
+ import type { TriageAdec } from "./adec-triage.ts";
2
3
  import type { RoadmapConfig } from "./roadmap.ts";
3
4
  import type { GuidanceProbeStore } from "./guidance-probe-store.ts";
4
5
  import type { ProbeStoredState, ProbeSlot, GuidanceProbeFakePorts, ProbeWorkerFramePreparer } from "./guidance-probes.ts";
@@ -252,7 +253,9 @@ export interface TasksDeps {
252
253
  /** Roles from `.agenthub/config.json` (issue #92): peers with the reviewer role join the reviewer candidates. */
253
254
  roles?: Record<string, string[]>;
254
255
  /** Optional: name a class for a task proposed without one. `onCampus` says whether the model call stays on campus. */
255
- triage?: { classify: (title: string, detail: string) => Promise<TaskClass | undefined>; onCampus: () => Promise<boolean> };
256
+ triage?: { classify: (title: string, detail: string) => Promise<TaskClass | undefined>; onCampus: () => Promise<boolean>;
257
+ /** #1936: adec's triage question and the outcome label; absent or `off` changes nothing. */
258
+ adec?: Pick<TriageAdec, "mode" | "ask" | "settled"> };
256
259
  /** #334: natural-language intake. `split` is the hub model's one call, `partsSchema` the profile's `hub_backlog_split` parts schema, `sourceKnown` the source registry. */
257
260
  intake?: { split: (system: string, user: string, opts: { campusOnly: boolean }) => Promise<string | undefined>; partsSchema: () => unknown; sourceKnown: (id: string) => boolean };
258
261
  /** The PII screen (issue #198): a closed verdict from a model on this machine or on campus, `unknown` on any failure. */
package/src/hub/tasks.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { REMEMBERED } from "./adec-triage.ts";
1
2
  import { ESCALATE_AFTER } from "./operational-settings.ts";
2
3
  import { conductorPeer, requireConductor } from "./conductor.ts";
3
4
  import { managedTaskPullRequest } from "./task-pr.ts";
@@ -589,6 +590,8 @@ export class Tasks {
589
590
  catch { throw new PreEffectToolRefusal("comment resolution requires the task owner and sent comment ids; refresh the task review before hub_task_done"); }
590
591
  }
591
592
  private readonly planReviewRequests = new Map<number, string>();
593
+ /** #1936: tasks whose class adec named under enforce, so approval does not post that class back as adec's outcome. */
594
+ private readonly adecNamed = new Map<number, TaskClass>();
592
595
  private readonly repositories: TaskRepositories;
593
596
  private get incomingBacklog() { return this.backlog.incomingBacklog; }
594
597
  private get knownPlanners() { return this.backlog.knownPlanners; }
@@ -2651,6 +2654,8 @@ export class Tasks {
2651
2654
  let cls = baseGiven;
2652
2655
  let triaged = false;
2653
2656
  let fenced = false; // a PII task off campus: triage is not asked
2657
+ let adecClass = false;
2658
+ let adecShadow: { title: string; detail: string; current: TaskClass | undefined; pii: boolean } | undefined;
2654
2659
  if (!cls && this.d.triage) {
2655
2660
  // Signals first: a PII task's text may only go to a model that is reached without leaving the campus network.
2656
2661
  const pii = this.isPii({ signals });
@@ -2659,6 +2664,17 @@ export class Tasks {
2659
2664
  if (reached) cls = await this.d.triage.classify(text.title, text.detail).catch(() => undefined);
2660
2665
  else fenced = true;
2661
2666
  requestCheck();
2667
+ // #1936: adec is asked only where the hub's own model was reachable (a PII task off campus asks neither). It never
2668
+ // fails the proposal: shadow records its answer, and only a person's enforce switch lets a non-abstaining answer replace the class.
2669
+ const adec = reached ? this.d.triage.adec : undefined;
2670
+ if (adec && adec.mode !== "off") {
2671
+ // Shadow adds no latency: it is asked after the board write below. Only enforce waits, because its answer is the class.
2672
+ if (adec.mode === "enforce") {
2673
+ const answer = await adec.ask({ title: text.title, detail: text.detail, current: cls, pii }).catch(() => ({} as { cls?: TaskClass }));
2674
+ requestCheck();
2675
+ if (answer.cls) { cls = answer.cls; adecClass = true; }
2676
+ } else adecShadow = { title: text.title, detail: text.detail, current: cls, pii };
2677
+ }
2662
2678
  triaged = !!cls;
2663
2679
  }
2664
2680
  // A claim is work the caller will do itself: without a class and a model to name one, it is implementation (#6).
@@ -2682,7 +2698,20 @@ export class Tasks {
2682
2698
  if (screening) task = this.screenedTask(task, screened);
2683
2699
  task = this.linkOnWrite(task); // #723
2684
2700
  if (goal) this.linkNative(task, goal, by);
2685
- if (triaged) task = this.d.board.update(task.id, "hub", "triaged", {}, `class ${cls} named by the hub's model`);
2701
+ if (triaged) task = this.d.board.update(task.id, "hub", "triaged", {}, adecClass ? `class ${cls} named by adec (inference.triage_adec = enforce)` : `class ${cls} named by the hub's model`);
2702
+ if (adecClass) {
2703
+ this.adecNamed.set(task.id, cls as TaskClass);
2704
+ // Bounded like TriageAdec.ids: a cancelled task never reaches approval, so the oldest entry goes first.
2705
+ while (this.adecNamed.size > REMEMBERED) this.adecNamed.delete(this.adecNamed.keys().next().value as number);
2706
+ }
2707
+ if (adecShadow && this.d.triage?.adec) {
2708
+ // The class adec named, or `abstain`, beside the hub's own; never the text. A failure records nothing.
2709
+ const shadowTask = task.id, own = cls;
2710
+ void this.d.triage.adec.ask(adecShadow).then(answer => {
2711
+ if (!answer.cls && !answer.abstain) return; // a down, slow or malformed adec is not an abstention
2712
+ this.d.board.update(shadowTask, "hub", "adec shadow", {}, `adec ${answer.cls ?? "abstain"} beside ${own ?? "no class"} (inference.triage_adec = shadow)`);
2713
+ }).catch(() => {});
2714
+ }
2686
2715
  if (defaulted) task = this.d.board.update(task.id, "hub", "class defaulted", {}, "class implement for a claim without one");
2687
2716
  if (backlog) {
2688
2717
  this.incomingBacklog.add(task.id);
@@ -7335,6 +7364,11 @@ export class Tasks {
7335
7364
  notifyAcceptedReopens();
7336
7365
  this.recordConsideredAfter(next, parsed.filter(finding => finding.disposition === "false_positive"), "review", findingHead ?? reviewedHead);
7337
7366
  this.recordInLedger(next, by, "approved", findingHead ?? reviewedHead, parsed, items, coverage, withheld || evidenceObserverExcluded || reviewObserverTurn);
7367
+ // #1936: the settled class is the outcome label of adec's triage decision; a down adec never blocks the approval.
7368
+ // Under enforce the class adec itself named is not an outcome: it would label its own answer.
7369
+ const adecNamedClass = this.adecNamed.get(next.id);
7370
+ this.adecNamed.delete(next.id);
7371
+ if (adecNamedClass !== next.class) void this.d.triage?.adec?.settled(next.title, next.detail, next.class).catch(() => {});
7338
7372
  this.writePlannerNotices(next, capacity, next.state === "approved");
7339
7373
  if (next.owner) {
7340
7374
  this.d.board.recordOutcome(next.owner, next.class, true);
@@ -5,7 +5,7 @@ import { AMBIGUOUS_BAND_DEFAULT, AMBIGUOUS_BAND_MAX } from "./stage-fallback.ts"
5
5
  export interface HubRoute {
6
6
  type: "stage" | "plan_execute" | "advisor" | "escalation" | "decision";
7
7
  decision_backend?: "adec";
8
- decision_mode?: "off" | "shadow";
8
+ decision_mode?: "off" | "shadow" | "enforce";
9
9
  adec_endpoint?: string;
10
10
  policy_id?: string;
11
11
  candidates?: { alias: string; efforts: string[] }[];
@@ -96,11 +96,11 @@ const SERVICE_FIELDS = ["decision_backend", "decision_mode", "policy_id", "adec_
96
96
  function parseServiceConfig(id: string, r: Record<string, unknown>): Pick<HubRoute, "decision_backend" | "decision_mode" | "adec_endpoint"> {
97
97
  const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
98
98
  if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
99
- if (r.decision_mode === "enforce") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
100
- if (r.decision_mode !== undefined && !["off", "shadow"].includes(String(r.decision_mode))) problem("decision_mode", 'use "off" or "shadow"');
99
+ if (r.decision_mode === "enforce" && r.type !== "decision") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
100
+ if (r.decision_mode !== undefined && (typeof r.decision_mode !== "string" || !["off", "shadow", "enforce"].includes(r.decision_mode))) problem("decision_mode", 'use "off", "shadow", or "enforce" on a decision route');
101
101
  if (typeof r.policy_id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,49}$/.test(r.policy_id)) problem("policy_id", "name a configured adec policy with 1 to 50 lowercase identifier characters");
102
102
  const endpoint = r.adec_endpoint ?? "http://127.0.0.1:8740/v1/route";
103
103
  if (!isAdecRouteEndpoint(endpoint)) return problem("adec_endpoint", "use an HTTP numeric loopback /v1/route URL without credentials, query or fragment");
104
104
  if (r.decision_timeout_ms !== undefined && (!Number.isSafeInteger(r.decision_timeout_ms) || Number(r.decision_timeout_ms) < 1 || Number(r.decision_timeout_ms) > 30_000)) problem("decision_timeout_ms", "use 1 to 30000 milliseconds");
105
- return { decision_backend: "adec", decision_mode: (r.decision_mode ?? "off") as "off" | "shadow", adec_endpoint: endpoint };
105
+ return { decision_backend: "adec", decision_mode: (r.decision_mode ?? "off") as HubRoute["decision_mode"], adec_endpoint: endpoint };
106
106
  }
@@ -19,7 +19,7 @@ export interface DecisionHost {
19
19
  onDecisionIssue?: (reason: AdecFailure | AdecReason) => void;
20
20
  }
21
21
  export interface DecisionTrace {
22
- decisionMode: "off" | "shadow";
22
+ decisionMode: NonNullable<HubRoute["decision_mode"]>;
23
23
  chosenAlias: string | null; chosenEffort: string | null; margin?: number; decisionLatencyMs?: number;
24
24
  decisionReason?: string; fallbackApplied?: boolean;
25
25
  decider?: { provider: string; model: string; version?: string; latencyMs: number } | null;
@@ -31,6 +31,8 @@ interface Context {
31
31
  hostChoice?: { purpose: HostChoicePurpose; phase?: HostPhase };
32
32
  deadline?: number;
33
33
  closed?(): boolean;
34
+ /** #1936: the alias the heuristic picked for this call, sent as adec's `current`. */
35
+ heuristic?: string;
34
36
  }
35
37
  /** What one stage classification needs: bounded evidence instead of a conversation projection. */
36
38
  export interface StageClassifyContext {
@@ -42,11 +44,11 @@ export type DecisionPurpose = "stage" | "decision" | "phase" | "judge";
42
44
  export interface HostChoiceContext {
43
45
  route: string; scope: string; turn: ReturnType<RouteLabelTracker["captureTurn"]>;
44
46
  current(): boolean; messages: ChatMessage[]; evidence: StageEvidence; pii: boolean; signal: AbortSignal;
45
- purpose: HostChoicePurpose; phase?: HostPhase; deadline?: number;
47
+ purpose: HostChoicePurpose; phase?: HostPhase; deadline?: number; heuristic?: string;
46
48
  }
47
49
  interface Options { pairs: AdecPair[]; candidates: string[]; current?: AdecPair }
48
50
  interface Privacy { pii: boolean; private: boolean; excluded: boolean }
49
- export interface DecisionSelection { trace?: DecisionTrace; check?(): void }
51
+ export interface DecisionSelection { trace?: DecisionTrace; apply?: AdecPair; check?(): void }
50
52
  type Selection = DecisionSelection;
51
53
  type Attempt = { result: AdecResult; privacy: Privacy } | { skipped: string };
52
54
  type PreparedRequest = { privacy: Privacy; input: AdecRouteRequest; options: Options; timeoutMs: number } | { skipped: string };
@@ -79,11 +81,13 @@ export class DecisionRouteController {
79
81
  if (config.type !== "decision" || (config.decision_mode ?? "off") === "off") { this.issues.delete(context.route); return {}; }
80
82
  if (context.signal.aborted || context.turn?.closed) throw ended();
81
83
  const privacy = this.privacy(context.pii);
84
+ const options = this.decisionOptions(config, context.heuristic);
82
85
  const checked = (selection: Selection): Selection => {
83
86
  this.fence(context, privacy);
84
- return { ...selection, check: () => { this.fence(context, privacy); selection.check?.(); } };
87
+ const apply = config.decision_mode === "enforce" ? selection.apply ?? options.current : undefined;
88
+ return { ...selection, ...(apply ? { apply } : {}), check: () => { this.fence(context, privacy); selection.check?.(); } };
85
89
  };
86
- try { return checked(await this.select(config, context, "decision", this.decisionOptions(config))); }
90
+ try { return checked(await this.select(config, context, "decision", options)); }
87
91
  catch (error) {
88
92
  if (context.signal.aborted || context.turn?.closed) throw ended();
89
93
  this.fence(context, privacy); // a rejected await is still an authority boundary
@@ -132,9 +136,11 @@ export class DecisionRouteController {
132
136
  private turnKey(purpose: DecisionPurpose, context: Context): string {
133
137
  return createHash("sha256").update(JSON.stringify([purpose, context.route, context.scope, context.turn?.context.turn])).digest("hex");
134
138
  }
135
- private decisionOptions(config: HubRoute): Options {
139
+ private decisionOptions(config: HubRoute, heuristic?: string): Options {
136
140
  const pairs = config.candidates?.flatMap(candidate => candidate.efforts.map(effort => ({ alias: candidate.alias, effort }))) ?? [];
137
- return { pairs, candidates: [...new Set(pairs.map(pair => pair.alias))] };
141
+ // #1936: the pair the route would use without adec (the alias the heuristic picked, else the efficient alias, else the first offered), so the shadow rows carry what adec is compared with.
142
+ const current = pairs.find(pair => pair.alias === (heuristic ?? config.efficient)) ?? pairs.find(pair => pair.alias === config.efficient) ?? pairs[0];
143
+ return { pairs, candidates: [...new Set(pairs.map(pair => pair.alias))], ...(current ? { current } : {}) };
138
144
  }
139
145
  /** A tier carries no effort, so both offerings use "none" and the answer maps back by alias equality. */
140
146
  private stageOptions(config: HubRoute, tier: StageTier): Options | undefined {
@@ -161,11 +167,11 @@ export class DecisionRouteController {
161
167
  const purpose: DecisionPurpose = context.purpose === "plan_execute_model" ? "phase" : "judge";
162
168
  const inner: Context = { route: context.route, scope: context.scope, turn: context.turn, current: context.current,
163
169
  messages: context.messages, dimensions: context.evidence.dimensions, stageEvidence: context.evidence,
164
- hostChoice: { purpose: context.purpose, ...(context.phase ? { phase: context.phase } : {}) },
170
+ hostChoice: { purpose: context.purpose, ...(context.phase ? { phase: context.phase } : {}) }, ...(context.heuristic ? { heuristic: context.heuristic } : {}),
165
171
  pii: context.pii, signal: context.signal, ...(context.deadline === undefined ? {} : { deadline: context.deadline }) };
166
172
  const initial = this.privacy(context.pii);
167
173
  let state: State | undefined, key: string | undefined;
168
- const began = performance.now(), options = this.decisionOptions(config);
174
+ const began = performance.now(), options = this.decisionOptions(config, context.heuristic);
169
175
  type Prepared = PreparedRequest | { cached: AdecResult; privacy: Privacy };
170
176
  return startChoiceWindow<Prepared, Selection>({
171
177
  signal: context.signal,
@@ -264,7 +270,9 @@ export class DecisionRouteController {
264
270
  if (d.decider === null) decider = null;
265
271
  else if (this.host.publicDecisionText?.(JSON.stringify(d.decider)) === true) decider = { provider: d.decider.provider, model: d.decider.model, latencyMs: d.decider.latencyMs, ...(d.decider.version === undefined ? {} : { version: d.decider.version }) };
266
272
  this.fence(context, attempt.privacy);
267
- return { check: () => this.publicationFence(context, attempt.privacy),
273
+ const apply = config.type === "decision" && config.decision_mode === "enforce" && !d.abstain && d.alias !== null && d.effort !== null
274
+ ? { alias: d.alias, effort: d.effort } : undefined;
275
+ return { ...(apply ? { apply } : {}), check: () => this.publicationFence(context, attempt.privacy),
268
276
  trace: { decisionMode: config.decision_mode ?? "off", chosenAlias: d.alias, chosenEffort: d.effort, margin: d.margin,
269
277
  decisionLatencyMs: Math.max(0, performance.now() - began), decisionReason: d.reason, fallbackApplied: d.fallbackApplied,
270
278
  ...(decider === undefined ? {} : { decider }) } };