@staix/agent-hub 0.36.0 → 0.37.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 (102) hide show
  1. package/CHANGELOG.md +17 -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 +802 -0
  14. package/docs/design/model-routes.md +437 -12
  15. package/docs/dogfood.md +11 -13
  16. package/docs/events.md +20 -1
  17. package/docs/memory.md +3 -3
  18. package/docs/operations.md +112 -148
  19. package/docs/quickstart.md +9 -3
  20. package/docs/research.md +1 -1
  21. package/docs/sdlc.md +5 -3
  22. package/docs/security.md +21 -1
  23. package/docs/specs/2026-09-19-agent-hub-design.md +9 -7
  24. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  25. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  26. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +21 -6
  27. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  28. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  29. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  30. package/docs/verified.json +24 -24
  31. package/package.json +3 -4
  32. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  33. package/plugins/agent-hub/kimi-hook.js +2373 -1436
  34. package/plugins/agent-hub/server.js +2445 -1497
  35. package/src/adapters/channel-peer.ts +7 -1
  36. package/src/adapters/compat.ts +1 -1
  37. package/src/adapters/local-probe.ts +174 -0
  38. package/src/adapters/local-worker.ts +232 -21
  39. package/src/cli/console-state.ts +25 -6
  40. package/src/cli/console-versions.ts +99 -0
  41. package/src/cli/console.ts +13 -1
  42. package/src/cli/help.ts +2 -1
  43. package/src/cli/install-paths.ts +7 -2
  44. package/src/cli/main.ts +60 -4
  45. package/src/cli/runtime-version-warning.ts +2 -2
  46. package/src/cli/sdlc-output.ts +9 -5
  47. package/src/hub/config-apply.ts +4 -2
  48. package/src/hub/config-trust.ts +6 -1
  49. package/src/hub/control-client.ts +5 -2
  50. package/src/hub/daemon.ts +169 -9
  51. package/src/hub/events.ts +3 -2
  52. package/src/hub/guidance-probe-store.ts +713 -0
  53. package/src/hub/guidance-probes.ts +358 -0
  54. package/src/hub/inference.ts +18 -5
  55. package/src/hub/operational-authority.ts +13 -1
  56. package/src/hub/peers.ts +5 -0
  57. package/src/hub/ports.ts +1 -1
  58. package/src/hub/progress.ts +23 -16
  59. package/src/hub/report.ts +2 -0
  60. package/src/hub/research.ts +1 -0
  61. package/src/hub/restart.ts +7 -0
  62. package/src/hub/sdlc-release-authorization.ts +139 -17
  63. package/src/hub/sdlc-release-policy.ts +100 -0
  64. package/src/hub/sdlc-release.ts +59 -7
  65. package/src/hub/tasks.ts +317 -6
  66. package/src/local/probe-errors.ts +28 -0
  67. package/src/local/probe-sandbox.ts +224 -0
  68. package/src/local/probe-types.ts +108 -0
  69. package/src/local/probe-workspace.ts +237 -0
  70. package/src/local/sandbox.ts +71 -2
  71. package/src/local/tools.ts +135 -9
  72. package/src/models/route/advisor-trigger.ts +88 -0
  73. package/src/models/route/config.ts +21 -17
  74. package/src/models/route/conversation-view.ts +179 -0
  75. package/src/models/route/decision-evidence.ts +1 -1
  76. package/src/models/route/decision.ts +114 -19
  77. package/src/models/route/escalation-control.ts +30 -0
  78. package/src/models/route/hub-prompts.ts +97 -0
  79. package/src/models/route/judge-choice.ts +155 -0
  80. package/src/models/route/judge-replies.ts +102 -0
  81. package/src/models/route/labels.ts +14 -70
  82. package/src/models/route/observation-signals.ts +250 -0
  83. package/src/models/route/plan-execute-choice.ts +27 -0
  84. package/src/models/route/relay-selector.ts +2 -2
  85. package/src/models/route/runtime.ts +115 -52
  86. package/src/models/route/turn-state.ts +77 -0
  87. package/src/omniroute/client.ts +3 -0
  88. package/src/ui/plugin.ts +70 -20
  89. package/src/version.ts +4 -0
  90. package/templates/adec/README.md +32 -0
  91. package/templates/adec/ahub.plan-execute.json +23 -0
  92. package/templates/adec/ahub.stage.json +23 -0
  93. package/LICENSES/Apache-2.0.txt +0 -204
  94. package/src/models/route/advisor.ts +0 -102
  95. package/src/models/route/escalation.ts +0 -82
  96. package/src/models/route/judge.ts +0 -23
  97. package/src/models/route/normalize.ts +0 -103
  98. package/src/models/route/plan-execute.ts +0 -52
  99. package/src/models/route/prompts.ts +0 -8
  100. package/src/models/route/signals.ts +0 -247
  101. package/src/models/route/state.ts +0 -54
  102. package/src/models/route/text.ts +0 -61
@@ -2,7 +2,7 @@ import type { ModelBackend, ModelRelayOptions, RelayRequest } from "../relay.ts"
2
2
  import { captureStageInput } from "./stage-input.ts";
3
3
  import { buildStageEvidence } from "./stage-evidence.ts";
4
4
  import { selectFallbackStage, planStageSwitch, type FallbackStageState as StageState, type StageSwitchTrace as SwitchTrace, type StageTier as Tier } from "./stage-fallback.ts";
5
- import { SessionState } from "./state.ts";
5
+ import { ScopeStore } from "./turn-state.ts";
6
6
 
7
7
  type RelaySelectorOptions = Pick<ModelRelayOptions, "mlx" | "selectBackend" | "routeSessionKey" | "allowedDGXmodels" | "staySwitch"> & { dgxMaxInputTokens: number };
8
8
  type RouteSource = "override" | "dimensions" | "hold" | "classifier" | "default" | "load" | "cooldown" | "pin";
@@ -18,7 +18,7 @@ export interface AutoChoice { backend: ModelBackend; route: RelayRouteEvent; mov
18
18
 
19
19
  /** Stage selection for the relay's virtual `hub/auto` model. */
20
20
  export class AutoRouteSelector {
21
- private readonly states = new SessionState<AutoState>(512, 60 * 60_000);
21
+ private readonly states = new ScopeStore<AutoState>({ maxEntries: 512, ttlMs: 60 * 60_000 });
22
22
 
23
23
  constructor(
24
24
  private readonly options: RelaySelectorOptions,
@@ -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
  }
package/src/ui/plugin.ts CHANGED
@@ -177,7 +177,7 @@ function lazyLifecycle(): Lifecycle {
177
177
  }
178
178
 
179
179
  /** Build the provider over an injectable registry and lifecycle (tests use a temp home and fakes). */
180
- export function createProvider(options: { visualPolicy?: (cwd: string) => Promise<DeliverablePorts>; visualRead?: typeof import("../hub/visual-assets.ts").readVisualAsset; home: string; registry?: Registry; lifecycle?: Lifecycle; log?: (line: string) => void; spaceBudgetMs?: number; features?: readonly string[]; forwardTimeoutMs?: ManagerOptions["forwardTimeoutMs"]; inboxFreshMs?: number; inboxStaleMs?: number; inboxProjectBudgetMs?: number }): ConsoleProvider {
180
+ export function createProvider(options: { visualPolicy?: (cwd: string) => Promise<DeliverablePorts>; visualRead?: typeof import("../hub/visual-assets.ts").readVisualAsset; home: string; registry?: Registry; lifecycle?: Lifecycle; log?: (line: string) => void; spaceBudgetMs?: number; runningFreshMs?: number; features?: readonly string[]; forwardTimeoutMs?: ManagerOptions["forwardTimeoutMs"]; inboxFreshMs?: number; inboxStaleMs?: number; inboxProjectBudgetMs?: number }): ConsoleProvider {
181
181
  const registry = options.registry ?? new Registry(join(options.home, "registry.db"));
182
182
  const owned = !options.registry;
183
183
  const lifecycle = options.lifecycle ?? lazyLifecycle();
@@ -203,14 +203,23 @@ export function createProvider(options: { visualPolicy?: (cwd: string) => Promis
203
203
  * One listing is in flight at a time and both callers join it, so a listing that hangs is asked once, not once per poll. A listing that finishes after its budget still becomes the fallback.
204
204
  */
205
205
  let lastRunning: ProjectRow[] = [];
206
- let listingFlight: Promise<ProjectRow[]> | undefined;
207
- function runningWithin(ms: number): Promise<ProjectRow[]> {
208
- if (!listingFlight) {
209
- const flight: Promise<ProjectRow[]> = running().then((rows) => { lastRunning = rows; return rows; }, () => lastRunning)
210
- .finally(() => { if (listingFlight === flight) listingFlight = undefined; });
211
- listingFlight = flight;
206
+ const RUNNING_FRESH_MS = options.runningFreshMs ?? 10_000;
207
+ let runningCache: { generation: number; at: number } | undefined;
208
+ let listingFlight: { generation: number; promise: Promise<ProjectRow[]> } | undefined;
209
+ function runningWithin(ms: number, cached = false): Promise<ProjectRow[]> {
210
+ const generation = inboxGeneration;
211
+ const reusable = runningCache?.generation === generation;
212
+ if (cached && reusable && Date.now() - runningCache!.at < RUNNING_FRESH_MS) return Promise.resolve(lastRunning);
213
+ if (!listingFlight || listingFlight.generation !== generation) {
214
+ const promise: Promise<ProjectRow[]> = running().then((rows) => {
215
+ if (generation === inboxGeneration) { lastRunning = rows; runningCache = { generation, at: Date.now() }; }
216
+ return rows;
217
+ }, () => lastRunning).finally(() => { if (listingFlight?.promise === promise) listingFlight = undefined; });
218
+ listingFlight = { generation, promise };
212
219
  }
213
- return within(listingFlight, ms).then((rows) => rows ?? lastRunning);
220
+ // Space reuses an expired listing while its one refresh runs; the inbox keeps its existing bounded refresh path.
221
+ if (cached && reusable) return Promise.resolve(lastRunning);
222
+ return within(listingFlight.promise, ms).then((rows) => rows ?? lastRunning);
214
223
  }
215
224
  /**
216
225
  * #727: one project's items from its last answer, reused for a project that did not answer in time, so a slow daemon neither blanks its rows nor restarts their `at`.
@@ -357,7 +366,9 @@ export function createProvider(options: { visualPolicy?: (cwd: string) => Promis
357
366
  * `previous`, as the dashboard keeps it, so desk slots and message arcs persist across polls. A restarted daemon
358
367
  * (new instanceId) restarts its event sequence at zero, so its previous model is dropped.
359
368
  */
360
- const offices = new Map<string, { instanceId: string | null; model: OfficeScene }>();
369
+ const offices = new Map<string, { instanceId: string | null; cursor: number; model: OfficeScene }>();
370
+ const officeFlights = new Map<string, { instanceId: string | null; generation: number; promise: Promise<Record<string, unknown> | null> }>();
371
+ let spaceFlight: { generation: number; promise: Promise<{ scene: ReturnType<typeof mergeSpaces>; cursor: number }> } | undefined;
361
372
  /**
362
373
  * acon wants a snapshot within 5 s. The project listing asks every daemon for its status, so it gets its own budget and
363
374
  * falls back to the last listing; projects are then read concurrently, and one that has not answered is left out of this poll.
@@ -368,22 +379,61 @@ export function createProvider(options: { visualPolicy?: (cwd: string) => Promis
368
379
  const late = new Promise<null>((resolve) => { timer = setTimeout(() => resolve(null), ms); });
369
380
  try { return await Promise.race([work, late]); } catch { return null; } finally { clearTimeout(timer); }
370
381
  };
371
- async function space() {
372
- const projects = await runningWithin(Math.round(SPACE_BUDGET_MS / 2));
373
- for (const id of offices.keys()) if (!projects.some((p) => p.id === id)) offices.delete(id);
382
+ function officeSnapshot(project: ProjectRow, after: number, generation: number) {
383
+ let flight = officeFlights.get(project.id);
384
+ if (!flight || flight.instanceId !== project.instanceId || flight.generation !== generation) {
385
+ const promise: Promise<Record<string, unknown> | null> = Promise.resolve(act({ action: "snapshot", after, projectId: project.id, instanceId: project.instanceId, view: "office" }) as Promise<Record<string, unknown>>)
386
+ .then(value => value, () => null)
387
+ .finally(() => { if (officeFlights.get(project.id)?.promise === promise) officeFlights.delete(project.id); });
388
+ flight = { instanceId: project.instanceId, generation, promise };
389
+ officeFlights.set(project.id, flight);
390
+ }
391
+ return within(flight.promise, SPACE_BUDGET_MS);
392
+ }
393
+ async function spaceComputation(generation: number) {
394
+ const projects = await runningWithin(Math.round(SPACE_BUDGET_MS / 2), true);
395
+ const previous = new Map(offices);
374
396
  const scenes = [];
375
- const snaps = await Promise.all(projects.map((project) =>
376
- within(act({ action: "snapshot", after: 0, projectId: project.id, instanceId: project.instanceId, view: "office" }) as Promise<Record<string, unknown>>, SPACE_BUDGET_MS)));
397
+ const cursors: (string | number | null)[][] = [];
398
+ const next = new Map<string, { instanceId: string | null; cursor: number; model: OfficeScene }>();
399
+ const snaps = await Promise.all(projects.map(project => officeSnapshot(project,
400
+ previous.get(project.id)?.instanceId === project.instanceId ? previous.get(project.id)!.cursor : 0, generation)));
377
401
  for (const [i, project] of projects.entries()) {
378
402
  const snap = snaps[i];
379
- if (!snap || snap.ok === false) continue;
380
- const cached = offices.get(project.id);
381
- const model = officeModel(snap as never, cached?.instanceId === project.instanceId ? cached.model : null, { cols: 4, now: Date.now() });
382
- offices.set(project.id, { instanceId: project.instanceId, model });
403
+ const cached = previous.get(project.id);
404
+ const sameInstance = cached?.instanceId === project.instanceId;
405
+ // A timeout omits this project's outward scene, but retains its baseline for the next valid reply.
406
+ // A known refusal or a restarted instance gets no such fallback.
407
+ if (!snap) { if (sameInstance) next.set(project.id, cached!); continue; }
408
+ if (snap.ok === false) continue;
409
+ // Event cursors do not cover every public status/privacy field on older daemons. Only an explicit
410
+ // unchanged reply permits model reuse; a full reply is always screened by the unchanged #264 mapper.
411
+ if (snap.changed === false && !sameInstance) continue;
412
+ const model = snap.changed === false ? cached!.model
413
+ : officeModel(snap as never, sameInstance ? cached!.model : null, { cols: 4, now: Date.now() });
414
+ const cursor = Number.isSafeInteger(snap.cursor) && Number(snap.cursor) >= 0 ? Number(snap.cursor) : 0;
415
+ next.set(project.id, { instanceId: project.instanceId, cursor, model });
416
+ cursors.push([project.id, project.instanceId, cursor]);
383
417
  const label = projects.length > 1 ? (project.root.split("/").filter(Boolean).pop() ?? project.id) : undefined;
418
+ // Keep the wall clock here even when the model is reused: message arcs expire without a daemon event.
384
419
  scenes.push(officeSpace(model, { id: project.id, ...(label ? { label } : {}) }, Date.now()));
385
420
  }
386
- return mergeSpaces(scenes);
421
+ const scene = mergeSpaces(scenes);
422
+ if (generation !== inboxGeneration) return { scene, cursor: 0 };
423
+ const fingerprint = createHash("sha256").update(JSON.stringify([projects.map(p => [p.id, p.instanceId, p.root]), cursors, scene])).digest("hex");
424
+ // Thirteen hex digits fit exactly in a safe integer; provider reopen cannot alias a local counter's first value.
425
+ const cursor = Number.parseInt(fingerprint.slice(0, 13), 16) || 1;
426
+ offices.clear(); for (const [id, entry] of next) offices.set(id, entry);
427
+ return { scene, cursor };
428
+ }
429
+ async function space(after: number) {
430
+ if (!spaceFlight || spaceFlight.generation !== inboxGeneration) {
431
+ const generation = inboxGeneration;
432
+ const promise = spaceComputation(generation).finally(() => { if (spaceFlight?.promise === promise) spaceFlight = undefined; });
433
+ spaceFlight = { generation, promise };
434
+ }
435
+ const value = await spaceFlight.promise;
436
+ return after > 0 && after === value.cursor ? { changed: false, cursor: value.cursor } : value;
387
437
  }
388
438
 
389
439
  /**
@@ -460,7 +510,7 @@ export function createProvider(options: { visualPolicy?: (cwd: string) => Promis
460
510
  return await consoleControl({ projectId, instanceId }, input.panel, payload);
461
511
  }
462
512
  if (input.panel === "inbox") return { ...await inboxSnapshot() };
463
- if (input.panel === "space") return { scene: await space() };
513
+ if (input.panel === "space") return await space(input.after);
464
514
  // #1220 T3: the execution-lineage read (AC5). A provider port, not a panel id: the shell's own panels are
465
515
  // DASHBOARD_VIEWS and neither that list nor the dashboard's action list grows. Reading executes nothing, and
466
516
  // an unavailable or unsupported source stays a refusal here rather than an empty successful graph.
package/src/version.ts CHANGED
@@ -2,3 +2,7 @@ import pkg from "../package.json";
2
2
 
3
3
  /** The one version. `scripts/build.mjs` stamps it into the plugin manifest and the bundle, and `--check` fails when they differ. */
4
4
  export const VERSION: string = pkg.version;
5
+
6
+ const SEMVER = /^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?(?:\+[0-9A-Za-z]+(?:[.-][0-9A-Za-z]+)*)?$/;
7
+ /** A version another process reported, kept only when it is a plain semver of at most 64 characters; anything else is unknown, never shown. Display only (#1385). */
8
+ export const displayVersion = (value: unknown): string | undefined => typeof value === "string" && value.length <= 64 && SEMVER.exec(value)?.[0] === value ? value : undefined;
@@ -0,0 +1,32 @@
1
+ # ADEc policy examples
2
+
3
+ These are editable examples for the separately operated `adec` service. They
4
+ follow the public policy schema at [agent-decide commit 008548c5](https://github.com/STAIxBWLB/agent-decide/blob/008548c57d3b0983719826aae36288dc5e3bad31/src/policy.ts): `policyId`, `provider`, `instructions`, `candidates`, `default`, `contextLimit`, and `minMargin`.
5
+
6
+ Before a person copies a file into their ADEc policy directory, replace the
7
+ provider and every `replace-me-*` alias or effort with values that exist in
8
+ their own ADEc configuration and match the hub route's allowed candidate
9
+ pairs. Keep `default` equal to one candidate pair. `ahub.stage` uses `none`
10
+ effort for both options, matching the stage route contract. The plan/execute
11
+ `edit-effort` token is only a syntactically valid placeholder.
12
+
13
+ Every candidate sets `onPrem` explicitly to `false`. A person must verify a
14
+ model's actual serving location before changing this to `true`; a loopback hub
15
+ endpoint alone does not establish that the model itself is on-prem. Until then,
16
+ these examples are not suitable for sensitive routes that require an on-prem
17
+ candidate.
18
+
19
+ The `contextLimit` value `20000` and `minMargin` value `0.05` are example
20
+ settings, not measured or calibrated defaults. ADEc's `minMargin` is independent
21
+ of the hub's `ambiguous_band`.
22
+
23
+ Both policies are for model/effort selection only. They do not authorize or
24
+ apply a selection. The host keeps its existing route, phase transition, review
25
+ and escalation rules, and executes its existing fallback in `shadow` mode.
26
+ Decision mode remains off unless a person explicitly configures `shadow`.
27
+ `enforce` is refused. The hub does not access the ADEc home; the person owns
28
+ local policy placement and service configuration.
29
+
30
+ No provider, alias, effort, latency gain, live model behavior, or production
31
+ readiness is established by these examples. The manual model-routing receipt
32
+ and live benchmark remain unrun.
@@ -0,0 +1,23 @@
1
+ {
2
+ "policyId": "ahub.plan-execute",
3
+ "provider": "replace-me-provider",
4
+ "instructions": "Choose one model/effort pair from the supplied options for the already-determined planning or execution phase, using only the bounded host-route evidence. This is a shadow recommendation: the hub owns phase transitions, execution authority, and the actual fallback model. Do not decide whether planning is complete, authorize work, infer privacy authority, select a peer, or add options.",
5
+ "candidates": [
6
+ {
7
+ "alias": "replace-me-efficient",
8
+ "efforts": ["edit-effort"],
9
+ "onPrem": false
10
+ },
11
+ {
12
+ "alias": "replace-me-capable",
13
+ "efforts": ["edit-effort"],
14
+ "onPrem": false
15
+ }
16
+ ],
17
+ "default": {
18
+ "alias": "replace-me-efficient",
19
+ "effort": "edit-effort"
20
+ },
21
+ "contextLimit": 20000,
22
+ "minMargin": 0.05
23
+ }
@@ -0,0 +1,23 @@
1
+ {
2
+ "policyId": "ahub.stage",
3
+ "provider": "replace-me-provider",
4
+ "instructions": "Choose one model/effort pair from the supplied options using only the bounded stage evidence. This is a shadow recommendation: the hub keeps its deterministic tier and may ignore the choice. Do not infer task actions, phase transitions, approvals, escalation, peer assignment, privacy authority, or new options.",
5
+ "candidates": [
6
+ {
7
+ "alias": "replace-me-efficient",
8
+ "efforts": ["none"],
9
+ "onPrem": false
10
+ },
11
+ {
12
+ "alias": "replace-me-capable",
13
+ "efforts": ["none"],
14
+ "onPrem": false
15
+ }
16
+ ],
17
+ "default": {
18
+ "alias": "replace-me-efficient",
19
+ "effort": "none"
20
+ },
21
+ "contextLimit": 20000,
22
+ "minMargin": 0.05
23
+ }