@staix/agent-hub 0.36.0 → 0.38.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 (121) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +6 -2
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +13 -3
  5. package/docs/agent-notes/daemon.md +4 -4
  6. package/docs/agent-notes/local-worker.md +1 -0
  7. package/docs/agent-notes/models.md +2 -1
  8. package/docs/agent-notes/tasks.md +1 -1
  9. package/docs/agent-notes/tests.md +1 -2
  10. package/docs/contracts/companion-cli-v1.json +70 -0
  11. package/docs/design/adapters.md +43 -2
  12. package/docs/design/agent-hub-architecture.md +9 -1
  13. package/docs/design/guidance-probes.md +1167 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +12 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +123 -151
  19. package/docs/profiles.md +1 -1
  20. package/docs/quickstart.md +15 -3
  21. package/docs/research.md +1 -1
  22. package/docs/sdlc.md +5 -3
  23. package/docs/security.md +25 -1
  24. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  25. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  26. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  27. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  28. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  29. package/docs/verification/2026-11-11-0.38.0.md +41 -0
  30. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  31. package/docs/verification/2026-11-11-guidance-probe-t3-1226.md +85 -0
  32. package/docs/verification/2026-11-11-guidance-probe-t4-1226.md +65 -0
  33. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  34. package/docs/verified.json +25 -25
  35. package/package.json +3 -4
  36. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  37. package/plugins/agent-hub/kimi-hook.js +2403 -1444
  38. package/plugins/agent-hub/server.js +2480 -1509
  39. package/src/adapters/channel-peer.ts +7 -1
  40. package/src/adapters/claude-channel.ts +2 -1
  41. package/src/adapters/compat.ts +1 -1
  42. package/src/adapters/local-probe.ts +233 -0
  43. package/src/adapters/local-worker.ts +232 -21
  44. package/src/cli/console-state.ts +25 -6
  45. package/src/cli/console-versions.ts +99 -0
  46. package/src/cli/console.ts +13 -1
  47. package/src/cli/help.ts +2 -1
  48. package/src/cli/init.ts +3 -1
  49. package/src/cli/install-paths.ts +7 -2
  50. package/src/cli/main.ts +78 -7
  51. package/src/cli/output.ts +8 -4
  52. package/src/cli/runtime-version-warning.ts +2 -2
  53. package/src/cli/sdlc-output.ts +9 -5
  54. package/src/cli/upgrade-runtime.ts +1 -1
  55. package/src/hub/bus.ts +2 -2
  56. package/src/hub/config-apply.ts +4 -2
  57. package/src/hub/config-trust.ts +6 -1
  58. package/src/hub/control-client.ts +5 -2
  59. package/src/hub/daemon.ts +195 -13
  60. package/src/hub/envelope.ts +6 -1
  61. package/src/hub/events.ts +3 -2
  62. package/src/hub/guidance-probe-store.ts +1044 -0
  63. package/src/hub/guidance-probes.ts +692 -0
  64. package/src/hub/inference.ts +18 -5
  65. package/src/hub/manager.ts +24 -1
  66. package/src/hub/operational-authority.ts +14 -1
  67. package/src/hub/peers.ts +5 -0
  68. package/src/hub/person-command.ts +25 -0
  69. package/src/hub/ports.ts +1 -1
  70. package/src/hub/progress.ts +23 -16
  71. package/src/hub/report.ts +2 -0
  72. package/src/hub/research.ts +1 -0
  73. package/src/hub/restart.ts +7 -0
  74. package/src/hub/sdlc-release-authorization.ts +139 -17
  75. package/src/hub/sdlc-release-policy.ts +100 -0
  76. package/src/hub/sdlc-release.ts +59 -7
  77. package/src/hub/supervision.ts +3 -2
  78. package/src/hub/tasks.ts +363 -7
  79. package/src/local/probe-errors.ts +28 -0
  80. package/src/local/probe-sandbox.ts +224 -0
  81. package/src/local/probe-types.ts +110 -0
  82. package/src/local/probe-workspace.ts +426 -0
  83. package/src/local/sandbox.ts +71 -2
  84. package/src/local/tools.ts +135 -9
  85. package/src/models/route/advisor-trigger.ts +88 -0
  86. package/src/models/route/config.ts +21 -17
  87. package/src/models/route/conversation-view.ts +179 -0
  88. package/src/models/route/decision-evidence.ts +1 -1
  89. package/src/models/route/decision.ts +114 -19
  90. package/src/models/route/escalation-control.ts +30 -0
  91. package/src/models/route/hub-prompts.ts +97 -0
  92. package/src/models/route/judge-choice.ts +155 -0
  93. package/src/models/route/judge-replies.ts +102 -0
  94. package/src/models/route/labels.ts +14 -70
  95. package/src/models/route/observation-signals.ts +250 -0
  96. package/src/models/route/plan-execute-choice.ts +27 -0
  97. package/src/models/route/relay-selector.ts +2 -2
  98. package/src/models/route/runtime.ts +115 -52
  99. package/src/models/route/turn-state.ts +77 -0
  100. package/src/omniroute/client.ts +3 -0
  101. package/src/ui/guidance-panel.ts +34 -2
  102. package/src/ui/guidance-view.ts +33 -0
  103. package/src/ui/plugin.ts +80 -23
  104. package/src/version.ts +4 -0
  105. package/templates/AGENTS.block.md +14 -14
  106. package/templates/adec/README.md +32 -0
  107. package/templates/adec/ahub.plan-execute.json +23 -0
  108. package/templates/adec/ahub.stage.json +23 -0
  109. package/templates/profiles/general.json +1 -1
  110. package/templates/profiles/research.json +1 -1
  111. package/templates/profiles/writing.json +1 -1
  112. package/LICENSES/Apache-2.0.txt +0 -204
  113. package/src/models/route/advisor.ts +0 -102
  114. package/src/models/route/escalation.ts +0 -82
  115. package/src/models/route/judge.ts +0 -23
  116. package/src/models/route/normalize.ts +0 -103
  117. package/src/models/route/plan-execute.ts +0 -52
  118. package/src/models/route/prompts.ts +0 -8
  119. package/src/models/route/signals.ts +0 -247
  120. package/src/models/route/state.ts +0 -54
  121. package/src/models/route/text.ts +0 -61
@@ -1,24 +1,26 @@
1
- import { DecisionRouteController, type DecisionHost, type DecisionTrace } from "./decision.ts";
1
+ import { DecisionRouteController, type DecisionHost, type DecisionTrace, type DecisionSelection, DecisionPolicyChangedError } from "./decision.ts";
2
2
  import type { ChatMessage, ChatResult } from "../../omniroute/client.ts";
3
- import { AdvisorGate, buildAdvisorJudgeRequest, redoFeedback } from "./advisor.ts";
3
+ import { AdvisorTrigger } from "./advisor-trigger.ts";
4
+ import { buildAdvisorRequest, buildEscalationRequest, planningInstruction, redoFeedback } from "./hub-prompts.ts";
5
+ import { captureJudgeConversation, captureRouteView } from "./conversation-view.ts";
6
+ import { parseAdvisorReply, parseEscalationReply } from "./judge-replies.ts";
7
+ import { runHostJudge, type HostChoicePurpose } from "./judge-choice.ts";
4
8
  import type { HubRoute } from "./config.ts";
5
- import { buildEscalationJudgeRequest, parseEscalationVerdict } from "./escalation.ts";
6
- import { normalizeConversation } from "./normalize.ts";
7
- import { extractToolSignals } from "./signals.ts";
8
9
  import { RouteLabelTracker, type RouteLabelEvent, type RouteTurnContext, type RouteTurnOutcome } from "./labels.ts";
9
10
  import { captureStageInput, estimateStageInputTokens } from "./stage-input.ts";
10
- import { buildStageEvidence, type CodingAgentDimensions } from "./stage-evidence.ts";
11
+ import { buildStageEvidence, type CodingAgentDimensions, type StageEvidence } from "./stage-evidence.ts";
11
12
  import { selectFallbackStage, planStageSwitch, ambiguousStage, type FallbackStageState, type StaySwitchPolicy, type StageSwitchTrace as SwitchTrace, type StageTier as Tier } from "./stage-fallback.ts";
12
- import { EscalationState, SessionState } from "./state.ts";
13
- import { parseAdvisorVerdict } from "./text.ts";
14
- import { planExecutePhase, type PlanExecuteState } from "./plan-execute.ts";
13
+ import { EscalationControl } from "./escalation-control.ts";
14
+ import { ScopeStore } from "./turn-state.ts";
15
+ import { PlanPhase } from "./plan-execute-choice.ts";
15
16
 
16
17
  export interface RouteEvent extends Partial<SwitchTrace>, Partial<DecisionTrace> {
18
+ decisionTarget?: "judge";
17
19
  route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "decision"; score: number; ms: number;
18
20
  decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number;
19
21
  }
20
22
  export interface AdvisorEvent { route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }
21
- interface RouteState { fingerprint: string; stage: FallbackStageState; pin?: Tier; plan: PlanExecuteState; escalation: EscalationState; advisor: AdvisorGate }
23
+ interface RouteState { fingerprint: string; stage: FallbackStageState; pin?: Tier; plan: PlanPhase; escalation: EscalationControl; advisor: AdvisorTrigger }
22
24
  export interface RouteHost extends DecisionHost {
23
25
  execute: (model: string, messages: ChatMessage[], judge: boolean, signal: AbortSignal, maxTokens?: number) => Promise<ChatResult>;
24
26
  /** Read on every stage call (#197); absent is the shadow default. */
@@ -27,14 +29,16 @@ export interface RouteHost extends DecisionHost {
27
29
  onRouteOutcome?: (event: RouteLabelEvent) => void;
28
30
  onAdvisor?: (event: AdvisorEvent) => void;
29
31
  }
32
+ /** Internal model-free proof only; no choice data or authority is exposed. */
33
+ export interface RouteProofPorts { choicePrepared?(ready: Promise<void>): void }
30
34
 
31
35
  /** Transport stays in the host. Optional judge work has one deadline and five-minute failure backoff. */
32
36
  export class HubRouteRuntime {
33
- private readonly states = new SessionState<RouteState>();
37
+ private readonly states = new ScopeStore<RouteState>();
34
38
  private readonly labels: RouteLabelTracker;
35
39
  private readonly decisions: DecisionRouteController;
36
40
  private judgeOffUntil = 0;
37
- constructor(private readonly host: RouteHost, private readonly judgeTimeoutMs = 8000) {
41
+ constructor(private readonly host: RouteHost, private readonly judgeTimeoutMs = 8000, private readonly proof?: RouteProofPorts) {
38
42
  this.decisions = new DecisionRouteController(host, judgeTimeoutMs);
39
43
  this.labels = new RouteLabelTracker(event => this.host.onRouteOutcome?.(event));
40
44
  }
@@ -53,7 +57,7 @@ export class HubRouteRuntime {
53
57
  const key = `${scope}:${route}`, fingerprint = JSON.stringify(config);
54
58
  const prior = this.states.get(key);
55
59
  if (prior?.fingerprint === fingerprint) return prior;
56
- const value: RouteState = { fingerprint, stage: { recoveryHoldRemaining: 0 }, plan: { executingSessions: [] }, escalation: new EscalationState(), advisor: new AdvisorGate({ trigger: config.trigger, pattern: config.pattern, maxReviews: config.max_reviews, gateStallTurns: config.gate_stall_turns, gateMinToolResults: config.gate_min_tool_results, transcriptMaxChars: config.transcript_max_chars }) };
60
+ const value: RouteState = { fingerprint, stage: { recoveryHoldRemaining: 0 }, plan: new PlanPhase(), escalation: new EscalationControl(), advisor: new AdvisorTrigger({ trigger: config.trigger, pattern: config.pattern, maxReviews: config.max_reviews, gateStallTurns: config.gate_stall_turns, gateMinToolResults: config.gate_min_tool_results }) };
57
61
  this.states.set(key, value); return value;
58
62
  }
59
63
 
@@ -64,11 +68,10 @@ export class HubRouteRuntime {
64
68
  const started = performance.now(), state = this.state(route, config, scope);
65
69
  const input = captureStageInput(messages) ?? { turn: "other" as const, incomplete: true, assistantTurns: 0, results: [] };
66
70
  const evidence = buildStageEvidence(input), dimensions = evidence.dimensions;
67
- // The remaining legacy consumers belong to R2; stage does not traverse their normalized history.
68
- const signals = config.type === "stage" || config.type === "decision" ? undefined : extractToolSignals(normalizeConversation(messages));
69
71
  const efficient = config.efficient ?? "fast", capable = config.capable ?? "coding";
70
72
  let model = efficient, source: RouteEvent["source"] = "default", score = 0;
71
73
  let sent = messages, trace: Partial<SwitchTrace> = {};
74
+ let phase: "planning" | "executing" | undefined;
72
75
  if (config.type === "stage" || config.type === "decision") {
73
76
  const decision = selectFallbackStage(evidence, { confidenceThreshold: config.confidence_threshold, holdTurns: config.hold_turns }, state.stage);
74
77
  state.stage = decision.state;
@@ -86,21 +89,40 @@ export class HubRouteRuntime {
86
89
  current: () => !signal.aborted && !labelTurn?.closed && this.labels.captureTurn() === labelTurn }) };
87
90
  }
88
91
  } else if (config.type === "plan_execute") {
89
- const decision = planExecutePhase(signals!, scope, state.plan);
90
- model = decision.tier === "capable" ? capable : efficient;
91
- state.plan = decision.state;
92
- if (decision.planningPrompt) sent = [{ role: "system", content: decision.planningPrompt }, ...messages];
92
+ const decision = state.plan.observe(captureRouteView(messages), scope);
93
+ phase = decision.phase;
94
+ model = decision.fallbackTier === "capable" ? capable : efficient;
95
+ if (decision.addPlanningInstruction) sent = [{ role: "system", content: planningInstruction }, ...messages];
93
96
  } else if (config.type === "escalation" && state.escalation.snapshot().latched) model = capable;
94
- const proposed: Awaited<ReturnType<DecisionRouteController["pick"]>> = config.type === "decision" ? await this.decisions.pick(config, { route, scope, turn: labelTurn, messages, dimensions, pii, signal,
95
- current: () => !signal.aborted && !labelTurn?.closed && this.labels.captureTurn() === labelTurn }) : {};
97
+ const current = () => !signal.aborted && !labelTurn?.closed && this.labels.captureTurn() === labelTurn;
98
+ let phaseGuard: ReturnType<DecisionRouteController["captureGuard"]> | undefined;
99
+ let proposed: DecisionSelection = {};
100
+ if (config.type === "decision") proposed = await this.decisions.pick(config, { route, scope, turn: labelTurn, messages, dimensions, pii, signal, current });
101
+ else if (config.type === "plan_execute" && config.decision_backend === "adec" && (config.decision_mode ?? "off") === "shadow") {
102
+ phaseGuard = this.decisions.captureGuard(pii, current);
103
+ const timeout = config.decision_timeout_ms ?? this.judgeTimeoutMs;
104
+ const window = this.decisions.openHostChoice(config, { route, scope, turn: labelTurn, messages, evidence, pii, signal, current,
105
+ purpose: "plan_execute_model", phase, deadline: performance.now() + timeout });
106
+ let timer: ReturnType<typeof setTimeout> | undefined;
107
+ try {
108
+ if (window) {
109
+ timer = setTimeout(() => { void window.close().catch(() => {}); }, timeout);
110
+ proposed = await window.result ?? {};
111
+ }
112
+ } finally { clearTimeout(timer); await window?.close(); }
113
+ phaseGuard();
114
+ }
96
115
  const picked = this.decisions.confirm(proposed);
97
116
  source = picked.trace ? "decision" : source;
98
117
  let decisionId = this.emitRoute({ route, tier: model, source, score, ms: performance.now() - started, ...trace, ...picked?.trace }, labelTurn, dimensions, pii, messages);
99
118
  const result = await this.host.execute(model, sent, false, signal);
119
+ phaseGuard?.("executor reply");
100
120
  if (config.type !== "escalation" || state.escalation.snapshot().latched) return this.withDecision(result, decisionId);
101
- const request = buildEscalationJudgeRequest(normalizeConversation([...messages, result.message]), signals!.assistantTurnCount + 1);
102
- const answer = await this.judge(config.judge ?? capable, [{ role: "system", content: request.systemPrompt }, ...request.messages], pii, signal, request.maxOutputTokens);
103
- const verdict = answer ? parseEscalationVerdict(answer) : undefined;
121
+ const conversation = captureJudgeConversation([...messages, result.message]);
122
+ const request = buildEscalationRequest(conversation, conversation?.assistantTurns ?? 0);
123
+ const answer = request ? await this.judge(config.judge ?? capable, [{ role: "system", content: request.systemPrompt }, ...request.messages], pii, signal, request.maxOutputTokens,
124
+ { route, config, scope, turn: labelTurn, messages, evidence, purpose: "escalation_judge_model", current }) : undefined;
125
+ const verdict = answer ? parseEscalationReply(answer) : undefined;
104
126
  if (answer && !verdict) this.judgeOffUntil = Date.now() + 5 * 60_000;
105
127
  const snapshot = state.escalation.apply(verdict, config.confirmations ?? 2);
106
128
  if (snapshot.latched) { try { this.labels.setLatched(labelTurn, true); } catch { /* optional labels */ } }
@@ -113,17 +135,27 @@ export class HubRouteRuntime {
113
135
  /** Reviews held no-tool responses. A redo is fed into the same local turn and bounded by its normal step cap. */
114
136
  async review(route: string, config: HubRoute, messages: ChatMessage[], scope: string, pii: boolean, signal: AbortSignal, decisionId?: string): Promise<string | undefined> {
115
137
  if (config.type !== "advisor") return undefined;
116
- const state = this.state(route, config, scope), conversation = normalizeConversation(messages);
117
- const latest = messages.at(-1);
118
- if (!state.advisor.shouldReview(conversation, { hasToolUse: !!latest?.tool_calls?.length, visibleText: latest?.content ?? "" }, scope) || !state.advisor.reserve(scope)) return undefined;
119
- const request = buildAdvisorJudgeRequest(conversation, latest?.content ?? undefined, config.transcript_max_chars);
120
- const answer = await this.judge(config.judge ?? config.capable ?? "coding", [{ role: "system", content: request.systemPrompt }, ...request.messages], pii, signal, request.maxOutputTokens);
121
- const verdict = answer ? parseAdvisorVerdict(answer) : undefined;
122
- state.advisor.settle(scope, verdict ? "success" : "failure");
123
- try { this.labels.observeAdvisor(decisionId, verdict?.kind ?? "failed"); } catch { /* optional labels */ }
124
- if (answer && !verdict) this.judgeOffUntil = Date.now() + 5 * 60_000;
125
- try { this.host.onAdvisor?.({ route, trigger: config.trigger ?? "no_tool_call", verdict: verdict?.kind ?? "failed", discardedChars: Math.max(0, [...JSON.stringify(conversation.messages)].length - (config.transcript_max_chars ?? 200_000)) }); } catch { /* optional telemetry */ }
126
- return verdict?.kind === "redo" ? redoFeedback(verdict, latest?.content ?? "").user : undefined;
138
+ const turn = this.labels.captureTurn(), current = () => !signal.aborted && !turn?.closed && this.labels.captureTurn() === turn;
139
+ const guard = this.decisions.captureGuard(pii, current);
140
+ const state = this.state(route, config, scope), conversation = captureJudgeConversation(messages), latest = messages.at(-1);
141
+ if (!state.advisor.eligible(conversation, { hasToolUse: !!latest?.tool_calls?.length, visibleText: latest?.content ?? "" }, scope) || !state.advisor.reserve(scope)) return undefined;
142
+ let settled = false;
143
+ try {
144
+ const request = buildAdvisorRequest(conversation, latest?.content ?? undefined, config.transcript_max_chars);
145
+ const input = captureStageInput(messages) ?? { turn: "other" as const, incomplete: true, assistantTurns: 0, results: [] };
146
+ const answer = request ? await this.judge(config.judge ?? config.capable ?? "coding", [{ role: "system", content: request.systemPrompt }, ...request.messages], pii, signal, request.maxOutputTokens,
147
+ { route, config, scope, turn, messages, evidence: buildStageEvidence(input), purpose: "advisor_judge_model", current }) : undefined;
148
+ guard("advisor reply");
149
+ const verdict = answer ? parseAdvisorReply(answer) : undefined;
150
+ state.advisor.settle(scope, verdict ? "success" : "failure"); settled = true;
151
+ try { this.labels.observeAdvisor(decisionId, verdict?.kind ?? "failed"); } catch { /* optional telemetry */ }
152
+ if (answer && !verdict) this.judgeOffUntil = Date.now() + 5 * 60_000;
153
+ guard("advisor publication");
154
+ try { this.host.onAdvisor?.({ route, trigger: config.trigger ?? "no_tool_call", verdict: verdict?.kind ?? "failed", discardedChars: request?.discardedChars ?? 0 }); }
155
+ catch (error) { if (error instanceof DecisionPolicyChangedError) throw error; }
156
+ guard("advisor publication");
157
+ return verdict?.kind === "redo" ? redoFeedback(verdict, latest?.content ?? "").user : undefined;
158
+ } finally { if (!settled) state.advisor.settle(scope, "failure"); }
127
159
  }
128
160
 
129
161
  private withDecision(result: ChatResult, decisionId: string | undefined): ChatResult {
@@ -156,24 +188,55 @@ export class HubRouteRuntime {
156
188
  return decision;
157
189
  }
158
190
 
159
- private async judge(model: string, messages: ChatMessage[], pii: boolean, parent: AbortSignal, maxTokens = 2048): Promise<string | undefined> {
191
+ private async judge(model: string, messages: ChatMessage[], pii: boolean, parent: AbortSignal, maxTokens = 2048,
192
+ choice?: { route: string; config: HubRoute; scope: string; turn: ReturnType<RouteLabelTracker["captureTurn"]>; messages: ChatMessage[]; evidence: StageEvidence; purpose: HostChoicePurpose; current(): boolean }): Promise<string | undefined> {
160
193
  if (parent.aborted || Date.now() < this.judgeOffUntil) return undefined;
161
- const controller = new AbortController();
162
- const abort = () => controller.abort();
163
- parent.addEventListener("abort", abort, { once: true });
164
- let timer: ReturnType<typeof setTimeout> | undefined;
165
- const work = async (): Promise<string | undefined> => {
166
- if (pii && !(await this.host.onCampus())) return undefined;
167
- if (controller.signal.aborted) return undefined;
168
- const result = await this.host.execute(model, messages, true, controller.signal, maxTokens);
169
- return result.message.content?.trim() || undefined;
170
- };
194
+ const current = choice?.current ?? (() => !parent.aborted), guard = this.decisions.captureGuard(pii, current);
195
+ const began = performance.now(), deadline = began + this.judgeTimeoutMs;
171
196
  try {
172
- const timeout = new Promise<undefined>(resolve => { timer = setTimeout(() => { controller.abort(); resolve(undefined); }, this.judgeTimeoutMs); });
173
- const result = await Promise.race([work(), timeout]);
174
- if (!result && !parent.aborted) this.judgeOffUntil = Date.now() + 5 * 60_000;
175
- return result;
176
- } catch { if (!parent.aborted) this.judgeOffUntil = Date.now() + 5 * 60_000; return undefined; }
177
- finally { clearTimeout(timer); parent.removeEventListener("abort", abort); }
197
+ const result = await runHostJudge<string, DecisionSelection>({
198
+ parent, timeoutMs: this.judgeTimeoutMs, current: guard,
199
+ common: async signal => {
200
+ const campus = pii ? await this.host.onCampus() === true : true;
201
+ if (signal.aborted) return false;
202
+ guard(); return campus;
203
+ },
204
+ fallback: async signal => {
205
+ guard();
206
+ const result = await this.host.execute(model, messages, true, signal, maxTokens);
207
+ return result.message.content?.trim() || undefined;
208
+ },
209
+ observe: signal => {
210
+ const window = choice ? this.decisions.openHostChoice(choice.config, { route: choice.route, scope: choice.scope,
211
+ turn: choice.turn, current: choice.current, messages: choice.messages, evidence: choice.evidence, pii, signal,
212
+ purpose: choice.purpose, deadline }) : undefined;
213
+ try {
214
+ const notify = this.proof?.choicePrepared;
215
+ if (window && notify) {
216
+ const ready = window.result.then(() => undefined);
217
+ void ready.catch(() => {});
218
+ notify.call(this.proof, ready);
219
+ }
220
+ } catch { /* proof sinks have no authority; the original result is still awaited below */ }
221
+ return window;
222
+ },
223
+ });
224
+ guard("judge result");
225
+ const observed = this.decisions.confirm(result.observation ?? {});
226
+ if (observed.trace && choice) {
227
+ guard("observation publication");
228
+ // Metadata only: never enter emitRoute/addDecision, label, progress or usage paths.
229
+ try { this.host.onRoute?.({ route: choice.route, tier: model, source: "default", score: 0,
230
+ ms: Math.max(0, performance.now() - began), ...observed.trace, decisionTarget: "judge" }); }
231
+ catch (error) { if (error instanceof DecisionPolicyChangedError) throw error; }
232
+ guard("observation publication");
233
+ }
234
+ if (!result.value && !parent.aborted) this.judgeOffUntil = Date.now() + 5 * 60_000;
235
+ return result.value;
236
+ } catch (error) {
237
+ if (error instanceof DecisionPolicyChangedError || error && typeof error === "object" && "budgetStop" in error) throw error;
238
+ if (!parent.aborted) this.judgeOffUntil = Date.now() + 5 * 60_000;
239
+ return undefined;
240
+ }
178
241
  }
179
242
  }
@@ -0,0 +1,77 @@
1
+ /** Local route state. It carries no cross-scope authority or transcript. */
2
+ const SCOPE_ENTRIES = 512;
3
+ const SCOPE_TTL_MS = 60 * 60_000;
4
+ const SCOPE_KEY_BYTES = 4096;
5
+
6
+ export interface ScopeStoreOptions {
7
+ maxEntries?: number;
8
+ ttlMs?: number;
9
+ now?: () => number;
10
+ }
11
+
12
+ interface Entry<T> { value: T; lastAccessAt: number }
13
+
14
+ /** Bounded LRU order; expiry is an idle TTL renewed by each successful get or set. */
15
+ export class ScopeStore<T> {
16
+ private readonly entries = new Map<string, Entry<T>>();
17
+ private readonly maxEntries: number;
18
+ private readonly ttlMs: number;
19
+ private readonly now: () => number;
20
+ private lastTime: number | undefined;
21
+
22
+ constructor(options: ScopeStoreOptions = {}) {
23
+ this.maxEntries = options.maxEntries ?? SCOPE_ENTRIES;
24
+ this.ttlMs = options.ttlMs ?? SCOPE_TTL_MS;
25
+ this.now = options.now ?? Date.now;
26
+ if (!Number.isSafeInteger(this.maxEntries) || this.maxEntries < 1 || this.maxEntries > SCOPE_ENTRIES
27
+ || !Number.isSafeInteger(this.ttlMs) || this.ttlMs < 1 || this.ttlMs > SCOPE_TTL_MS) {
28
+ throw new RangeError("invalid route scope bounds");
29
+ }
30
+ }
31
+
32
+ get(scope: string): T | undefined {
33
+ this.key(scope);
34
+ const time = this.time();
35
+ const entry = this.entries.get(scope);
36
+ if (!entry) return undefined;
37
+ if (time < entry.lastAccessAt || time - entry.lastAccessAt >= this.ttlMs) {
38
+ this.entries.delete(scope);
39
+ return undefined;
40
+ }
41
+ entry.lastAccessAt = time;
42
+ this.entries.delete(scope);
43
+ this.entries.set(scope, entry);
44
+ return entry.value;
45
+ }
46
+
47
+ set(scope: string, value: T): void {
48
+ this.key(scope);
49
+ if (value === undefined) throw new TypeError("route scope values must be defined");
50
+ const time = this.time();
51
+ for (const [key, entry] of this.entries) {
52
+ if (time < entry.lastAccessAt || time - entry.lastAccessAt >= this.ttlMs) this.entries.delete(key);
53
+ }
54
+ this.entries.delete(scope);
55
+ this.entries.set(scope, { value, lastAccessAt: time });
56
+ while (this.entries.size > this.maxEntries) {
57
+ const oldest = this.entries.keys().next().value;
58
+ if (oldest === undefined) break;
59
+ this.entries.delete(oldest);
60
+ }
61
+ }
62
+
63
+ delete(scope: string): void { this.key(scope); this.entries.delete(scope); }
64
+
65
+ private key(scope: string): void {
66
+ if (typeof scope !== "string" || scope.length === 0 || scope.length > SCOPE_KEY_BYTES
67
+ || Buffer.byteLength(scope, "utf8") > SCOPE_KEY_BYTES) throw new RangeError("invalid route scope key");
68
+ }
69
+
70
+ private time(): number {
71
+ const time = this.now();
72
+ if (!Number.isFinite(time) || time < 0) throw new RangeError("route clock unavailable");
73
+ if (this.lastTime !== undefined && time < this.lastTime) this.entries.clear();
74
+ this.lastTime = time;
75
+ return time;
76
+ }
77
+ }
@@ -35,6 +35,8 @@ export interface ChatResult {
35
35
  usage?: NormalizedUsage;
36
36
  /** Model named by the completed response, when the gateway reports it. */
37
37
  servedModel?: string;
38
+ /** Positive metadata only when the raw response identity required no normalization. */
39
+ servedModelExact?: true;
38
40
  /** `x-omniroute-provider` (direct path) */
39
41
  provider?: string;
40
42
  }
@@ -187,6 +189,7 @@ export class OmniRoute {
187
189
  ...(usage ? { usage } : {}),
188
190
  ...(safeProvider ? { provider: safeProvider } : {}),
189
191
  ...(servedModel ? { servedModel } : {}),
192
+ ...(servedModel && json.model === servedModel ? { servedModelExact: true as const } : {}),
190
193
  };
191
194
  }
192
195
  }
@@ -14,6 +14,15 @@ export default (host) => {
14
14
  const title = node('h2', 'Guidance');
15
15
  const introduction = node('p', 'Inspect task-bound declarations and editable-section diffs. Source evidence is a declaration; actual handoff, testing and model consumption are unknown.');
16
16
  const instructions = node('p', 'Create or withdraw with the authorized ahub guidance CLI or MCP tools. This panel only reads declarations.');
17
+ const probeForm = node('form', undefined, 'ahub-guidance-probe');
18
+ const probeId = node('input'); probeId.type = 'text'; probeId.autocomplete = 'off'; probeId.required = true;
19
+ probeId.pattern = '[a-f0-9]{64}'; probeId.maxLength = 64; probeId.spellcheck = false;
20
+ const probeLabel = node('label'); probeLabel.append(node('span', 'Probe ID (64 hex)'), probeId);
21
+ const probeButton = node('button', 'Read probe status'); probeButton.type = 'submit';
22
+ probeForm.append(probeLabel, probeButton);
23
+ const probeNote = node('p', 'Probe status is fixture evidence only: it reads the sealed receipts and the outcome denominator and claims no live model or worker trial.');
24
+ const probeOutput = node('pre', undefined, 'ahub-guidance-output');
25
+ probeOutput.tabIndex = 0; probeOutput.setAttribute('aria-label', 'Guidance probe status');
17
26
  const scopeForm = node('form', undefined, 'ahub-guidance-scope');
18
27
  const field = (label, control) => {
19
28
  const wrapper = node('label');
@@ -39,20 +48,21 @@ export default (host) => {
39
48
  const next = node('button', 'Next page'); next.type = 'button'; next.hidden = true;
40
49
  const output = node('pre', undefined, 'ahub-guidance-output');
41
50
  output.tabIndex = 0; output.setAttribute('aria-label', 'Guidance public details');
42
- root.append(title, introduction, instructions, scopeForm, notice, recordList, next, output);
51
+ root.append(title, introduction, instructions, scopeForm, notice, recordList, next, output, probeForm, probeNote, probeOutput);
43
52
  host.mount.append(root);
44
53
  let generation = 0, disposed = false, visible = false, projects = [], cursor, busy = false;
45
54
  const state = (message) => { notice.textContent = message; };
46
55
  const update = () => {
47
56
  listButton.disabled = busy;
48
57
  projectsButton.disabled = busy;
58
+ probeButton.disabled = busy;
49
59
  next.disabled = busy;
50
60
  for (const button of recordList.querySelectorAll('button')) button.disabled = busy;
51
61
  root.setAttribute('aria-busy', busy ? 'true' : 'false');
52
62
  };
53
63
  const invalidate = () => {
54
64
  generation++; busy = false; cursor = undefined;
55
- recordList.replaceChildren(); output.textContent = ''; next.hidden = true;
65
+ recordList.replaceChildren(); output.textContent = ''; probeOutput.textContent = ''; next.hidden = true;
56
66
  update();
57
67
  };
58
68
  const scope = () => {
@@ -120,12 +130,33 @@ export default (host) => {
120
130
  } catch { if (active(token)) failure(); }
121
131
  finally { if (active(token)) { busy = false; update(); } }
122
132
  }
133
+ async function readProbe() {
134
+ const selected = projects.find(row => row.id === project.value);
135
+ if (!selected || typeof selected.instanceId !== 'string' || !selected.instanceId || !/^[a-f0-9]{64}$/.test(probeId.value)) {
136
+ state('Select a running project and enter the exact 64-character probe id.'); return;
137
+ }
138
+ const id = probeId.value, token = ++generation;
139
+ busy = true; probeOutput.textContent = ''; update(); state('Reading probe status...');
140
+ try {
141
+ const result = await host.snapshot({ panel: 'guidance', op: 'probe', projectId: selected.id, instanceId: selected.instanceId, id });
142
+ if (!active(token)) return;
143
+ // The text shown is the provider's own lines for exactly the probe that was asked for; anything else is a refusal, never partial text.
144
+ if (!result || result.ok !== true || result.probe?.status?.id !== id || !Array.isArray(result.lines) || result.lines.some(line => typeof line !== 'string')) {
145
+ state(typeof result?.error === 'string' && result.ok === false ? result.error : 'Probe status unavailable. Refresh the probe id or check access and guidance_probe_receipts support.'); return;
146
+ }
147
+ probeOutput.textContent = result.lines.join('\n');
148
+ state('Probe status read. Fixture evidence only; every unknown stays unknown.');
149
+ } catch { if (active(token)) state('Probe status unavailable. Refresh the probe id or check access and guidance_probe_receipts support.'); }
150
+ finally { if (active(token)) { busy = false; update(); } }
151
+ }
123
152
  scopeForm.addEventListener('submit', event => { event.preventDefault(); track(read('list')); });
153
+ probeForm.addEventListener('submit', event => { event.preventDefault(); track(readProbe()); });
124
154
  projectsButton.addEventListener('click', () => track(refreshProjects()));
125
155
  next.addEventListener('click', () => { if (cursor) track(read('list', undefined, cursor)); });
126
156
  for (const input of [project, task, epoch]) input.addEventListener('input', () => {
127
157
  invalidate(); state('Task scope changed. List declarations to read the selected scope.');
128
158
  });
159
+ probeId.addEventListener('input', () => { generation++; busy = false; probeOutput.textContent = ''; update(); state('Probe id changed. Read probe status to refresh.'); });
129
160
  return {
130
161
  show(_panel, params) {
131
162
  if (disposed) return;
@@ -151,6 +182,7 @@ export default (host) => {
151
182
  .ahub-guidance-record code{overflow-wrap:anywhere;flex:1 1 30ch}.ahub-guidance-record span{font-size:.875em}
152
183
  .ahub-guidance-output{white-space:pre-wrap;overflow-wrap:anywhere;font-size:.875em;line-height:1.55;font-variant-numeric:tabular-nums;padding:16px;border:1px solid currentColor;border-radius:10px;max-height:65vh;overflow:auto}
153
184
  .ahub-guidance-output:empty{display:none}.ahub-guidance [hidden]{display:none!important}
185
+ .ahub-guidance-probe{display:flex;flex-wrap:wrap;gap:12px;align-items:end;margin:20px 0}.ahub-guidance-probe input{width:68ch;max-width:100%;font-family:ui-monospace,monospace}
154
186
  @media(max-width:600px){.ahub-guidance{padding:12px}.ahub-guidance-scope>label{width:100%}.ahub-guidance input{width:100%}}`;
155
187
  return { js, css };
156
188
  }
@@ -1,4 +1,5 @@
1
1
  import type { GuidanceDiffResult, GuidancePageResult, GuidanceWriteReceipt } from "../hub/guidance-variants.ts";
2
+ import type { ProbeReceiptExport } from "../hub/guidance-probes.ts";
2
3
  import { sanitize } from "../hub/envelope.ts";
3
4
 
4
5
  /** Shared public projection only. These lines neither reconstruct private role bytes nor attest to a handoff. */
@@ -41,3 +42,35 @@ export function guidanceReceiptLines(receipt: GuidanceWriteReceipt): string[] {
41
42
  "Experiment label (untrusted advisory text):", `> ${experiment}`,
42
43
  "Actual handoff, testing and model consumption are unknown."];
43
44
  }
45
+
46
+ /** Wire text is advisory and untrusted: no control or format character survives, and a model-written name is never shown raw. */
47
+ const plain = (raw: string): string => sanitize(raw).replace(/[\p{Cc}\p{Cf}]/gu, "");
48
+ const known = (value: number | null): string => value === null ? "unknown" : String(value);
49
+ /**
50
+ * T4 (#1226): the producer's probe status, one text for the plugin panel and the CLI. It states what the host observed and nothing more: a fixture run says
51
+ * `fixture`, a missing measurement says `unknown` and never zero, and every state that is not a success stays visible, so a failed, cancelled or unavailable
52
+ * arm cannot disappear from the denominator. A live trial is never claimed here: no production runner exists, and evidence is at most `fixture`.
53
+ */
54
+ export function guidanceProbeStatusLines(exported: ProbeReceiptExport): string[] {
55
+ const status = exported.status, counts = exported.counts;
56
+ const lines = [`Guidance probe ${status.id}`, `Task #${status.taskId}; revision ${status.revision}; state ${status.state}; evidence ${status.evidence}.`,
57
+ `Experiment label (untrusted advisory text): ${plain(status.experimentId)}`,
58
+ `Comparable: ${exported.comparable ? "yes" : "no"}${exported.reasons.length ? ` (${exported.reasons.join(", ")})` : ""}.`,
59
+ `Outcomes (every reserved slot counts): ${counts.succeeded} succeeded, ${counts.failed} failed, ${counts.cancelled} cancelled, ${counts.timed_out} timed out, ${counts.unavailable} unavailable, ${counts.unknown} unknown; not started ${counts.planned}; not needed ${counts.not_needed}.`,
60
+ `Attempts: ${status.counters.workerAttempts} worker, ${status.counters.editorAttempts} editor; model calls ${status.counters.modelCalls}; tool calls ${status.counters.toolCalls}.`,
61
+ `Token usage: ${status.counters.usageUnknown || status.counters.modelCalls === 0 ? "unknown" : status.counters.tokensObservedKnown}.`,
62
+ `Cancel requested: ${status.cancelRequested ? "yes" : "no"}.`,
63
+ "Fixture evidence only: no live model or worker trial, sampling control, provider behaviour or model quality is claimed."];
64
+ for (const slot of exported.slots) {
65
+ const receipt = slot.receipt;
66
+ lines.push(`Slot ${plain(slot.slotId)}: ${slot.stage}/${slot.role}/${slot.arm}; session ${slot.state}; retained output ${slot.retention}.`);
67
+ if (receipt) {
68
+ lines.push(` Receipt ${receipt.state}; requested ${plain(receipt.requestedModel)}; served ${receipt.servedModel === null ? "unobserved" : plain(receipt.servedModel)}.`,
69
+ ` Elapsed ${receipt.elapsedMs} ms; model calls ${receipt.usage.modelCalls} (${receipt.usage.modelUsageKnown} with known usage); tool calls ${receipt.usage.toolCalls}; tokens ${known(receipt.usage.tokensObserved)}.`,
70
+ ` Output: ${receipt.output.entries.length} file${receipt.output.entries.length === 1 ? "" : "s"}, ${receipt.output.totalBytes} bytes; ${receipt.output.excluded.length} excluded.`,
71
+ ` Limits: ${receipt.limits.join(", ") || "none"}.`, ` Receipt digest ${receipt.digest}`);
72
+ } else if (slot.withheld) lines.push(` Receipt withheld by the privacy screen; digest ${slot.receiptDigest}.`);
73
+ else lines.push(" No receipt: this slot has no sealed observation, so its outcome is unknown or not started.");
74
+ }
75
+ return lines;
76
+ }