@staix/agent-hub 0.35.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 (165) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +25 -4
  3. package/THIRD_PARTY_NOTICES.md +0 -18
  4. package/docs/agent-notes/README.md +71 -1
  5. package/docs/agent-notes/adapters.md +5 -2
  6. package/docs/agent-notes/bus.md +1 -0
  7. package/docs/agent-notes/daemon.md +7 -6
  8. package/docs/agent-notes/local-worker.md +1 -0
  9. package/docs/agent-notes/models.md +5 -3
  10. package/docs/agent-notes/tasks.md +9 -2
  11. package/docs/agent-notes/tests.md +1 -1
  12. package/docs/contracts/companion-cli-v1.json +70 -0
  13. package/docs/design/adapters.md +115 -2
  14. package/docs/design/agent-hub-architecture.md +10 -2
  15. package/docs/design/bus.md +8 -0
  16. package/docs/design/execution-reference.md +171 -11
  17. package/docs/design/guidance-experiments.md +438 -0
  18. package/docs/design/guidance-probes.md +802 -0
  19. package/docs/design/model-routes.md +1053 -0
  20. package/docs/design/supervision.md +121 -0
  21. package/docs/design/task-board.md +111 -0
  22. package/docs/dogfood.md +24 -15
  23. package/docs/events.md +20 -1
  24. package/docs/memory.md +3 -3
  25. package/docs/operations.md +366 -133
  26. package/docs/profiles.md +2 -2
  27. package/docs/quickstart.md +114 -3
  28. package/docs/research.md +5 -3
  29. package/docs/sdlc.md +113 -7
  30. package/docs/security.md +88 -6
  31. package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
  32. package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
  33. package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
  34. package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
  35. package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
  36. package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -0
  37. package/docs/verification/2026-11-10-0.36.0.md +59 -0
  38. package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
  39. package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
  40. package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
  41. package/docs/verification/2026-11-11-0.37.0.md +40 -0
  42. package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
  43. package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
  44. package/docs/verification/claude-shell-wrapper-native.py +1 -1
  45. package/docs/verified.json +27 -27
  46. package/package.json +3 -4
  47. package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
  48. package/plugins/agent-hub/kimi-hook.js +3570 -1800
  49. package/plugins/agent-hub/server.js +4112 -1913
  50. package/src/adapters/channel-peer.ts +7 -1
  51. package/src/adapters/claude-channel.ts +7 -4
  52. package/src/adapters/compat.ts +10 -10
  53. package/src/adapters/local-probe.ts +174 -0
  54. package/src/adapters/local-worker.ts +233 -22
  55. package/src/adapters/qwen-dual.ts +324 -44
  56. package/src/cli/console-state.ts +25 -6
  57. package/src/cli/console-versions.ts +99 -0
  58. package/src/cli/console.ts +13 -1
  59. package/src/cli/guidance.ts +67 -0
  60. package/src/cli/help.ts +12 -4
  61. package/src/cli/identity.ts +10 -3
  62. package/src/cli/init-prompt.ts +15 -2
  63. package/src/cli/init-required-checks.ts +122 -0
  64. package/src/cli/init-settings.ts +10 -4
  65. package/src/cli/init.ts +39 -3
  66. package/src/cli/install-paths.ts +7 -2
  67. package/src/cli/lineage.ts +78 -0
  68. package/src/cli/main.ts +171 -14
  69. package/src/cli/runtime-version-warning.ts +2 -2
  70. package/src/cli/sdlc-output.ts +9 -5
  71. package/src/cli/setup-research.ts +10 -0
  72. package/src/hub/autonomy-defaults.ts +20 -9
  73. package/src/hub/board.ts +346 -4
  74. package/src/hub/build-entry.ts +11 -0
  75. package/src/hub/bus.ts +12 -0
  76. package/src/hub/ci-watch.ts +4 -4
  77. package/src/hub/config-apply.ts +6 -3
  78. package/src/hub/config-trust.ts +7 -1
  79. package/src/hub/control-client.ts +5 -2
  80. package/src/hub/daemon.ts +508 -26
  81. package/src/hub/delivery-hints.ts +4 -2
  82. package/src/hub/delivery-journal.ts +50 -2
  83. package/src/hub/delivery-public.ts +51 -0
  84. package/src/hub/dogfood-profile.ts +8 -4
  85. package/src/hub/events.ts +3 -2
  86. package/src/hub/execution-lineage-owner.ts +272 -0
  87. package/src/hub/execution-lineage.ts +52 -8
  88. package/src/hub/execution-links.ts +85 -0
  89. package/src/hub/guidance-probe-store.ts +713 -0
  90. package/src/hub/guidance-probes.ts +358 -0
  91. package/src/hub/guidance-variants.ts +398 -0
  92. package/src/hub/handoff.ts +1 -0
  93. package/src/hub/hub-tools.ts +43 -2
  94. package/src/hub/inference.ts +18 -5
  95. package/src/hub/manager.ts +44 -2
  96. package/src/hub/memory-policy.ts +2 -2
  97. package/src/hub/operational-authority.ts +13 -1
  98. package/src/hub/peers.ts +6 -1
  99. package/src/hub/planning.ts +1 -1
  100. package/src/hub/ports.ts +1 -1
  101. package/src/hub/progress.ts +47 -23
  102. package/src/hub/report.ts +2 -0
  103. package/src/hub/research.ts +1 -0
  104. package/src/hub/restart.ts +20 -0
  105. package/src/hub/roles.ts +26 -0
  106. package/src/hub/routing.ts +4 -1
  107. package/src/hub/sdlc-merge.ts +39 -1
  108. package/src/hub/sdlc-release-authorization.ts +139 -17
  109. package/src/hub/sdlc-release-policy.ts +100 -0
  110. package/src/hub/sdlc-release.ts +60 -8
  111. package/src/hub/sdlc.ts +62 -11
  112. package/src/hub/settings.ts +2 -0
  113. package/src/hub/supervision-proposals.ts +405 -0
  114. package/src/hub/supervision-rules.ts +388 -0
  115. package/src/hub/supervision.ts +2 -0
  116. package/src/hub/task-approval.ts +2 -2
  117. package/src/hub/task-repository.ts +5 -0
  118. package/src/hub/tasks.ts +917 -53
  119. package/src/local/probe-errors.ts +28 -0
  120. package/src/local/probe-sandbox.ts +224 -0
  121. package/src/local/probe-types.ts +108 -0
  122. package/src/local/probe-workspace.ts +237 -0
  123. package/src/local/sandbox.ts +71 -2
  124. package/src/local/tools.ts +135 -9
  125. package/src/memory/capture.ts +2 -2
  126. package/src/models/relay.ts +9 -2
  127. package/src/models/route/advisor-trigger.ts +88 -0
  128. package/src/models/route/config.ts +39 -8
  129. package/src/models/route/conversation-view.ts +179 -0
  130. package/src/models/route/decision-evidence.ts +1 -1
  131. package/src/models/route/decision.ts +193 -26
  132. package/src/models/route/escalation-control.ts +30 -0
  133. package/src/models/route/hub-prompts.ts +97 -0
  134. package/src/models/route/judge-choice.ts +155 -0
  135. package/src/models/route/judge-replies.ts +102 -0
  136. package/src/models/route/labels.ts +14 -70
  137. package/src/models/route/observation-signals.ts +250 -0
  138. package/src/models/route/plan-execute-choice.ts +27 -0
  139. package/src/models/route/relay-selector.ts +10 -9
  140. package/src/models/route/runtime.ts +129 -60
  141. package/src/models/route/stage-diagnostics.ts +22 -0
  142. package/src/models/route/stage-evidence.ts +55 -0
  143. package/src/models/route/stage-fallback.ts +58 -0
  144. package/src/models/route/stage-input.ts +155 -0
  145. package/src/models/route/stage.ts +5 -147
  146. package/src/models/route/turn-state.ts +77 -0
  147. package/src/omniroute/client.ts +3 -0
  148. package/src/ui/guidance-panel.ts +156 -0
  149. package/src/ui/guidance-view.ts +43 -0
  150. package/src/ui/lineage-view.ts +34 -0
  151. package/src/ui/plugin.ts +141 -27
  152. package/src/version.ts +4 -0
  153. package/templates/adec/README.md +32 -0
  154. package/templates/adec/ahub.plan-execute.json +23 -0
  155. package/templates/adec/ahub.stage.json +23 -0
  156. package/LICENSES/Apache-2.0.txt +0 -204
  157. package/src/models/route/advisor.ts +0 -102
  158. package/src/models/route/escalation.ts +0 -82
  159. package/src/models/route/judge.ts +0 -23
  160. package/src/models/route/normalize.ts +0 -103
  161. package/src/models/route/plan-execute.ts +0 -52
  162. package/src/models/route/prompts.ts +0 -8
  163. package/src/models/route/signals.ts +0 -247
  164. package/src/models/route/state.ts +0 -54
  165. package/src/models/route/text.ts +0 -61
@@ -1,147 +1,5 @@
1
- // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2
- // SPDX-License-Identifier: Apache-2.0
3
- // Ported to TypeScript from NVIDIA NeMo Switchyard crates/libsy/src/algorithms/util/stage.rs at c8848511, modified.
4
-
5
- import type { ToolSignals, TurnKind } from './signals.ts';
6
-
7
- export type Tier = 'capable' | 'efficient';
8
- export type PickerMode = 'capable_first' | 'efficient_first';
9
- export type DecisionSource = 'override' | 'capable_hold' | 'dimensions' | 'ambiguous' | 'llm-classifier' | 'fall_open';
10
- export interface CodingAgentDimensions { severity:number; spinning:number; exploring:number; productionIntensity:number }
11
- export interface ScoreResult { score:number; confidence:number }
12
- export type PickOutcome =
13
- | {kind:'resolved';tier:Tier;source:DecisionSource;probability:number;confidence:number|null}
14
- | {kind:'consult_classifier';probability:number;confidence:number;defaultTier:Tier};
15
- export interface StageState { capableHoldTurnsRemaining:number }
16
- export interface HandoffNoteConfig {
17
- escalationNote: string;
18
- deescalationNote?: string;
19
- onlyOnWrongSignalEscalation?: boolean;
20
- }
21
- export interface StageOptions { mode?:PickerMode; confidenceThreshold?:number; capableHoldTurns?:number; handoffNotes?:HandoffNoteConfig }
22
- /** `hardOverride` (#197, not ported): pickTier's override predicate holds, even when a capable hold answered first. */
23
- export interface StageDecision { tier:Tier|undefined; defaultTier:Tier; source:DecisionSource; probability:number; confidence:number; score:number; dimensions:CodingAgentDimensions; note?:string; state:StageState; hardOverride:boolean }
24
-
25
- const STALL_MIN_TURN_DEPTH=8;
26
- const SCORE_GAIN=5;
27
- const HARD_SEVERITY=0.7;
28
- const SIGNAL_UNIT=0.1;
29
- const SEVERITY_CRITICAL=1;
30
-
31
- export function dimensionsFromSignal(signal:ToolSignals):CodingAgentDimensions {
32
- const recentOps=signal.recentWriteCount+signal.recentEditCount+signal.recentReadCount+signal.recentTodowriteCount;
33
- const deep=signal.turnDepth>=STALL_MIN_TURN_DEPTH;
34
- const noProduction=signal.recentWriteCount===0&&signal.recentEditCount===0;
35
- const investigating=signal.recentReadCount>=1||signal.recentTodowriteCount>=1;
36
- const newActivity=signal.recentNewCount>=1;
37
- const spinning=deep&&noProduction&&!investigating&&!newActivity;
38
- const exploring=deep&&noProduction&&investigating&&!newActivity;
39
- const production=recentOps===0?0:(signal.recentWriteCount+signal.recentEditCount)/recentOps;
40
- return {severity:signal.severity,spinning:spinning?1:0,exploring:exploring?1:0,productionIntensity:production};
41
- }
42
-
43
- export function scoreSignal(signal:ToolSignals):ScoreResult {
44
- const d=dimensionsFromSignal(signal);
45
- const raw=SIGNAL_UNIT*(d.severity/HARD_SEVERITY+d.spinning+d.exploring-d.productionIntensity);
46
- const score=Math.tanh(SCORE_GAIN*raw);
47
- return {score,confidence:Math.abs(score)};
48
- }
49
-
50
- /** Compaction, critical severity or a repeated failure: capable whatever the scores say. */
51
- export function hardOverride(signal:ToolSignals):boolean {
52
- return signal.compacted||signal.severity>=SEVERITY_CRITICAL||signal.repeatedFailure;
53
- }
54
-
55
- export function pickTier(signal:ToolSignals, mode:PickerMode='efficient_first', confidenceThreshold=0.5):PickOutcome {
56
- const defaultTier:Tier=mode==='capable_first'?'capable':'efficient';
57
- if(hardOverride(signal))
58
- return {kind:'resolved',tier:'capable',source:'override',probability:0.5,confidence:1};
59
- const scored=scoreSignal(signal); const probability=(scored.score+1)/2; const half=confidenceThreshold/2;
60
- if(probability>0.5+half||probability<0.5-half)
61
- return {kind:'resolved',tier:probability>0.5?'capable':'efficient',source:'dimensions',probability,confidence:scored.confidence};
62
- return {kind:'consult_classifier',probability,confidence:scored.confidence,defaultTier};
63
- }
64
-
65
- export function handoffNoteFor(tier:Tier, source:DecisionSource, config:HandoffNoteConfig):string|undefined {
66
- if(tier==='capable') {
67
- const signalDriven=source==='override'||source==='dimensions';
68
- return (config.onlyOnWrongSignalEscalation??true)&&!signalDriven ? undefined : config.escalationNote;
69
- }
70
- return config.deescalationNote;
71
- }
72
-
73
- /** Apply stage hard rules, dimension scoring, and the capable recovery hold. */
74
- export function selectStage(signal:ToolSignals, options:StageOptions={}, state:StageState={capableHoldTurnsRemaining:0}):StageDecision {
75
- const mode=options.mode??'efficient_first'; const defaultTier:Tier=mode==='capable_first'?'capable':'efficient';
76
- const holdTurns=Math.max(0,Math.trunc(options.capableHoldTurns??2));
77
- let remaining=Math.max(0,Math.trunc(state.capableHoldTurnsRemaining));
78
- const cleanTestPass=signal.testsPassed&&signal.noErrorStreak>0;
79
- if(cleanTestPass)remaining=0;
80
- let outcome:PickOutcome;
81
- if(!cleanTestPass&&remaining>0){remaining--;outcome={kind:'resolved',tier:'capable',source:'capable_hold',probability:0.5,confidence:1};}
82
- else outcome=pickTier(signal,mode,options.confidenceThreshold??0.5);
83
- if(outcome.kind==='resolved'&&outcome.tier==='capable'&&(outcome.source==='override'||outcome.source==='dimensions'))remaining=holdTurns;
84
- const dimensions=dimensionsFromSignal(signal); const score=scoreSignal(signal).score;
85
- const note = outcome.kind === 'resolved' && options.handoffNotes
86
- ? handoffNoteFor(outcome.tier, outcome.source, options.handoffNotes)
87
- : undefined;
88
- return {
89
- tier: outcome.kind === 'resolved' ? outcome.tier : undefined,
90
- defaultTier,
91
- source: outcome.kind === 'consult_classifier' ? 'ambiguous' : outcome.source,
92
- probability: outcome.probability,
93
- confidence: outcome.confidence ?? 0,
94
- score,
95
- dimensions,
96
- ...(note === undefined ? {} : { note }),
97
- state: { capableHoldTurnsRemaining: remaining },
98
- hardOverride: hardOverride(signal),
99
- };
100
- }
101
-
102
- // Session-aware stay/switch (#197): not ported from Switchyard; the rules follow Weave Router's planner, without its
103
- // history summary on a switch.
104
- export type StaySwitchMode = 'off' | 'shadow' | 'enforce';
105
- /** The routing.toml keys the planner reads. */
106
- export interface StaySwitchPolicy { stay_switch: StaySwitchMode; max_switch_prefill_tokens: number }
107
- // ponytail: an unmeasured prefill bound; #197 AC6 measures prefill before enforce becomes the default.
108
- export const DEFAULT_STAY_SWITCH: StaySwitchPolicy = { stay_switch: 'shadow', max_switch_prefill_tokens: 32_000 };
109
- export type SwitchReason = 'new_pin' | 'compaction' | 'context_fit' | 'same_tier' | 'override' | 'tool_loop' | 'prefill_bound' | 'user_turn';
110
- export interface SwitchCost { inputTokens: number; maxSwitchPrefillTokens: number; fits: (tier: Tier) => boolean }
111
- /** Input tokens a backend would prefill for a conversation, 4 characters each; the relay and local routes share it. */
112
- export function estimateInputTokens(messages: unknown, tools?: unknown[]): number {
113
- return Math.ceil(JSON.stringify({ messages, tools }).length / 4);
114
- }
115
- export interface SwitchPlan { plan: 'stay' | 'switch'; tier: Tier; reason: SwitchReason }
116
- /** What a route event records about the planner; never prompt text. */
117
- export interface SwitchTrace { turnType: TurnKind; prefillTokens: number; staySwitch?: 'shadow' | 'enforce'; plan?: 'stay' | 'switch'; reason?: SwitchReason }
118
-
119
- /**
120
- * Stay on the session's pinned tier or switch to this call's stage decision. A new session or a compaction starts a fresh
121
- * pin, a hard override escalates on any turn, a tool loop keeps its tier, and other changes wait for a user turn; a
122
- * de-escalation that makes the efficient backend prefill more than the bound stays. A tier whose backend cannot hold the
123
- * conversation is never chosen: nothing here summarizes or trims the history to make a switch fit.
124
- */
125
- export function planSwitch(pin: Tier | undefined, fresh: Pick<StageDecision, 'tier' | 'defaultTier' | 'source'> & { hardOverride?: boolean }, turn: TurnKind, cost: SwitchCost): SwitchPlan {
126
- const wanted = fresh.tier ?? fresh.defaultTier, other: Tier = wanted === 'capable' ? 'efficient' : 'capable';
127
- const want = cost.fits(wanted) || !cost.fits(other) ? wanted : other;
128
- const plan = (tier: Tier, reason: SwitchReason): SwitchPlan => ({ plan: pin === undefined || pin === tier ? 'stay' : 'switch', tier, reason });
129
- if (pin === undefined) return plan(want, 'new_pin');
130
- if (turn === 'compaction') return plan(want, 'compaction');
131
- if (want !== wanted || !cost.fits(pin)) return plan(want, 'context_fit');
132
- if (want === pin) return plan(pin, 'same_tier');
133
- // A hold answers before pickTier's overrides, so the override is read on its own: it escalates even during a hold.
134
- if (fresh.source === 'override' || fresh.hardOverride) return plan(want, 'override');
135
- if (turn === 'tool_result') return plan(pin, 'tool_loop');
136
- if (want === 'efficient' && cost.inputTokens > cost.maxSwitchPrefillTokens) return plan(pin, 'prefill_bound');
137
- return plan(want, 'user_turn');
138
- }
139
-
140
- /** The one place hub/auto and local stage routes apply the mode, so both record the same trace. `shadow` and `off` keep the stage tier. */
141
- export function stayOrSwitch(policy: StaySwitchPolicy | undefined, pin: Tier | undefined, fresh: StageDecision, turn: TurnKind, cost: Omit<SwitchCost, 'maxSwitchPrefillTokens'>): { tier: Tier; pin?: Tier; trace: SwitchTrace } {
142
- const { stay_switch: mode, max_switch_prefill_tokens: maxSwitchPrefillTokens } = policy ?? DEFAULT_STAY_SWITCH;
143
- const tier = fresh.tier ?? fresh.defaultTier, trace: SwitchTrace = { turnType: turn, prefillTokens: cost.inputTokens };
144
- if (mode === 'off') return { tier, trace };
145
- const planned = planSwitch(pin, fresh, turn, { ...cost, maxSwitchPrefillTokens });
146
- return { tier: mode === 'enforce' ? planned.tier : tier, pin: planned.tier, trace: { ...trace, staySwitch: mode, plan: planned.plan, reason: planned.reason } };
147
- }
1
+ /** Compatibility path for existing consumers; implementation is authored in stage-only units. */
2
+ export { estimateInputTokens } from "./stage-input.ts";
3
+ export type { CodingAgentDimensions } from "./stage-evidence.ts";
4
+ export { AMBIGUOUS_BAND_DEFAULT, AMBIGUOUS_BAND_MAX, DEFAULT_STAY_SWITCH, ambiguousStage } from "./stage-fallback.ts";
5
+ export type { StageTier as Tier, FallbackStageState as StageState, StaySwitchMode, StaySwitchPolicy, StageSwitchTrace as SwitchTrace } from "./stage-fallback.ts";
@@ -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
  }
@@ -0,0 +1,156 @@
1
+ /** The producer console owns transport and authority. This module owns only its scoped public read view. */
2
+ export function guidancePanelAssets(): { js: string; css: string } {
3
+ const js = String.raw`
4
+ export default (host) => {
5
+ const doc = host.mount.ownerDocument;
6
+ const node = (tag, text, className) => {
7
+ const element = doc.createElement(tag);
8
+ if (text !== undefined) element.textContent = text;
9
+ if (className) element.className = className;
10
+ return element;
11
+ };
12
+ const root = node('div', undefined, 'ahub-guidance');
13
+ root.hidden = true;
14
+ const title = node('h2', 'Guidance');
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
+ const instructions = node('p', 'Create or withdraw with the authorized ahub guidance CLI or MCP tools. This panel only reads declarations.');
17
+ const scopeForm = node('form', undefined, 'ahub-guidance-scope');
18
+ const field = (label, control) => {
19
+ const wrapper = node('label');
20
+ wrapper.append(node('span', label), control);
21
+ scopeForm.append(wrapper);
22
+ return control;
23
+ };
24
+ const project = field('Project', node('select'));
25
+ project.append(node('option', 'Select a running project'));
26
+ project.options[0].value = '';
27
+ const task = field('Task ID', node('input'));
28
+ const epoch = field('Task creation epoch', node('input'));
29
+ for (const input of [task, epoch]) {
30
+ input.type = 'text'; input.inputMode = 'numeric'; input.required = true;
31
+ input.autocomplete = 'off'; input.pattern = '[0-9]+';
32
+ }
33
+ const listButton = node('button', 'List declarations'); listButton.type = 'submit';
34
+ const projectsButton = node('button', 'Refresh projects'); projectsButton.type = 'button';
35
+ scopeForm.append(listButton, projectsButton);
36
+ const notice = node('p', 'Select a project, task ID and task creation epoch.');
37
+ notice.setAttribute('role', 'status'); notice.setAttribute('aria-live', 'polite');
38
+ const recordList = node('div', undefined, 'ahub-guidance-records');
39
+ const next = node('button', 'Next page'); next.type = 'button'; next.hidden = true;
40
+ const output = node('pre', undefined, 'ahub-guidance-output');
41
+ output.tabIndex = 0; output.setAttribute('aria-label', 'Guidance public details');
42
+ root.append(title, introduction, instructions, scopeForm, notice, recordList, next, output);
43
+ host.mount.append(root);
44
+ let generation = 0, disposed = false, visible = false, projects = [], cursor, busy = false;
45
+ const state = (message) => { notice.textContent = message; };
46
+ const update = () => {
47
+ listButton.disabled = busy;
48
+ projectsButton.disabled = busy;
49
+ next.disabled = busy;
50
+ for (const button of recordList.querySelectorAll('button')) button.disabled = busy;
51
+ root.setAttribute('aria-busy', busy ? 'true' : 'false');
52
+ };
53
+ const invalidate = () => {
54
+ generation++; busy = false; cursor = undefined;
55
+ recordList.replaceChildren(); output.textContent = ''; next.hidden = true;
56
+ update();
57
+ };
58
+ const scope = () => {
59
+ const selected = projects.find(row => row.id === project.value);
60
+ if (!selected || typeof selected.instanceId !== 'string' || !selected.instanceId
61
+ || !/^[0-9]+$/.test(task.value) || !/^[0-9]+$/.test(epoch.value)) return;
62
+ const taskId = Number(task.value), taskCreated = Number(epoch.value);
63
+ if (!Number.isSafeInteger(taskId) || taskId < 1 || !Number.isSafeInteger(taskCreated) || taskCreated < 0) return;
64
+ return { projectId: selected.id, instanceId: selected.instanceId, taskId, taskCreated };
65
+ };
66
+ const active = (token) => !disposed && visible && token === generation;
67
+ const failure = () => state('Guidance unavailable. Refresh the selected task scope or check access and guidance_views support.');
68
+ const track = (work) => { void work.catch(() => {}); };
69
+ async function refreshProjects(wanted) {
70
+ invalidate();
71
+ const token = generation;
72
+ busy = true; update(); state('Reading running projects...');
73
+ try {
74
+ const result = await host.snapshot({ panel: 'board', after: 0 });
75
+ if (!active(token)) return;
76
+ if (!result || result.ok === false || !Array.isArray(result.projects)) { failure(); return; }
77
+ const previous = typeof wanted === 'string' ? wanted : project.value;
78
+ projects = result.projects.filter(row => row && typeof row.id === 'string' && row.state === 'running'
79
+ && typeof row.instanceId === 'string' && row.instanceId);
80
+ const empty = node('option', 'Select a running project'); empty.value = '';
81
+ project.replaceChildren(empty);
82
+ for (const row of projects) { const option = node('option', row.id); option.value = row.id; project.append(option); }
83
+ project.value = projects.some(row => row.id === previous) ? previous : '';
84
+ state(projects.length ? 'Select an explicit task ID and creation epoch, then list declarations.' : 'No running projects are available.');
85
+ } catch { if (active(token)) failure(); }
86
+ finally { if (active(token)) { busy = false; update(); } }
87
+ }
88
+ async function read(op, id, after) {
89
+ const selected = scope();
90
+ if (!selected) { state('Select a running project and enter a valid task ID and creation epoch.'); return; }
91
+ const token = ++generation;
92
+ busy = true; next.hidden = true; update();
93
+ state(op === 'show' ? 'Reading declaration diff...' : 'Reading declarations...');
94
+ recordList.replaceChildren(); output.textContent = ''; cursor = undefined;
95
+ try {
96
+ const result = await host.snapshot({ panel: 'guidance', op, ...selected,
97
+ ...(id === undefined ? {} : { id }), ...(after === undefined ? {} : { cursor: after }) });
98
+ if (!active(token)) return;
99
+ if (!result || result.ok !== true || !result.guidance || result.guidance.state !== 'available') { failure(); return; }
100
+ const value = result.guidance;
101
+ if (value.current?.taskId !== selected.taskId || value.current?.taskCreated !== selected.taskCreated) { failure(); return; }
102
+ if (op === 'show' && value.record?.id !== id || op === 'list' && !Array.isArray(value.records)) { failure(); return; }
103
+ if (!Array.isArray(result.lines) || result.lines.some(line => typeof line !== 'string')) { failure(); return; }
104
+ output.textContent = result.lines.join('\n');
105
+ if (op === 'list') {
106
+ for (const record of value.records) {
107
+ const row = node('div', undefined, 'ahub-guidance-record');
108
+ const identity = node('code', record.id);
109
+ const status = node('span', record.status + '; applicable: ' + (record.applicable ? 'yes' : 'no'));
110
+ const show = node('button', 'Show diff'); show.type = 'button';
111
+ show.addEventListener('click', () => track(read('show', record.id)));
112
+ row.append(identity, status, show); recordList.append(row);
113
+ }
114
+ if (value.truncated && typeof value.cursor === 'string' && value.cursor) {
115
+ cursor = value.cursor; next.hidden = false;
116
+ }
117
+ }
118
+ state(op === 'show' ? 'Public editable-section diff. Protected section bodies remain private.'
119
+ : value.truncated ? 'Page read. Use Next page to read more, or list again to refresh.' : 'Page complete.');
120
+ } catch { if (active(token)) failure(); }
121
+ finally { if (active(token)) { busy = false; update(); } }
122
+ }
123
+ scopeForm.addEventListener('submit', event => { event.preventDefault(); track(read('list')); });
124
+ projectsButton.addEventListener('click', () => track(refreshProjects()));
125
+ next.addEventListener('click', () => { if (cursor) track(read('list', undefined, cursor)); });
126
+ for (const input of [project, task, epoch]) input.addEventListener('input', () => {
127
+ invalidate(); state('Task scope changed. List declarations to read the selected scope.');
128
+ });
129
+ return {
130
+ show(_panel, params) {
131
+ if (disposed) return;
132
+ visible = true; root.hidden = false;
133
+ if (typeof params?.taskId === 'string') task.value = params.taskId;
134
+ if (typeof params?.taskCreated === 'string') epoch.value = params.taskCreated;
135
+ track(refreshProjects(typeof params?.project === 'string' ? params.project : undefined));
136
+ },
137
+ hide() { visible = false; invalidate(); root.hidden = true; },
138
+ destroy() { disposed = true; visible = false; invalidate(); root.remove(); },
139
+ };
140
+ };
141
+ `;
142
+ const css = `.ahub-guidance{color:inherit;font:inherit;padding:20px;max-width:1100px;-webkit-font-smoothing:antialiased}
143
+ .ahub-guidance h2{margin:0 0 8px;text-wrap:balance}.ahub-guidance p{max-width:85ch;line-height:1.5;text-wrap:pretty}
144
+ .ahub-guidance-scope{display:flex;flex-wrap:wrap;gap:12px;align-items:end;margin:20px 0}
145
+ .ahub-guidance label{display:grid;gap:6px;min-width:160px}.ahub-guidance label span{font-size:.875em}
146
+ .ahub-guidance input,.ahub-guidance select,.ahub-guidance button{font:inherit;color:inherit;background:transparent;border:1px solid currentColor;border-radius:6px;min-height:40px;padding:8px 12px}
147
+ .ahub-guidance input{width:18ch;max-width:100%;box-sizing:border-box;font-variant-numeric:tabular-nums}
148
+ .ahub-guidance button{cursor:pointer}.ahub-guidance button:disabled{opacity:.5;cursor:default}
149
+ .ahub-guidance :is(button,input,select,pre):focus-visible{outline:2px solid currentColor;outline-offset:3px}
150
+ .ahub-guidance-records{display:grid;gap:8px;margin:12px 0}.ahub-guidance-record{display:flex;flex-wrap:wrap;gap:12px;align-items:center;padding:12px;border:1px solid currentColor;border-radius:10px}
151
+ .ahub-guidance-record code{overflow-wrap:anywhere;flex:1 1 30ch}.ahub-guidance-record span{font-size:.875em}
152
+ .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
+ .ahub-guidance-output:empty{display:none}.ahub-guidance [hidden]{display:none!important}
154
+ @media(max-width:600px){.ahub-guidance{padding:12px}.ahub-guidance-scope>label{width:100%}.ahub-guidance input{width:100%}}`;
155
+ return { js, css };
156
+ }
@@ -0,0 +1,43 @@
1
+ import type { GuidanceDiffResult, GuidancePageResult, GuidanceWriteReceipt } from "../hub/guidance-variants.ts";
2
+ import { sanitize } from "../hub/envelope.ts";
3
+
4
+ /** Shared public projection only. These lines neither reconstruct private role bytes nor attest to a handoff. */
5
+ export function guidanceLines(value: GuidancePageResult | GuidanceDiffResult): string[] {
6
+ const text = (raw: string): string => sanitize(raw).replace(/[\p{Cc}\p{Cf}]/gu, character => character === "\n" ? character : "");
7
+ const field = (label: string, raw: string): string[] => [label + " (untrusted advisory text):", ...text(raw).split("\n").map(line => `> ${line}`)];
8
+ if (value.state !== "available") return ["Guidance unavailable. Refresh the selected task scope or check access and guidance_views support."];
9
+ const current = value.current;
10
+ const lines = ["Guidance declarations (advisory)", `Current task #${current.taskId}; epoch ${current.taskCreated}; flow ${current.flowRevision}.`,
11
+ "Source evidence is declared or unavailable. Actual handoff, testing and model consumption are unknown."];
12
+ const records = "record" in value ? [value.record] : value.records;
13
+ if (!records.length) lines.push("No guidance declarations in this page.");
14
+ for (const record of records) {
15
+ lines.push(`Variant ${record.id}`, `Task #${record.taskId}; epoch ${record.taskCreated}; declaration flow ${record.flowRevision}.`,
16
+ `Status: ${record.status}; currently applicable: ${record.applicable ? "yes" : "no"}.`,
17
+ `Role: ${record.roleId} (${record.layer}); author: ${record.author}.`,
18
+ `Baseline SHA-256: ${record.baselineSha256}`, `Candidate SHA-256: ${record.candidateSha256}`,
19
+ `Bytes: baseline ${record.bytes.baseline}; candidate ${record.bytes.candidate}; record ${record.bytes.record}.`,
20
+ `Changed sections: ${record.changedSections.join(", ") || "none"}.`,
21
+ ...field("Experiment label", record.experimentId),
22
+ ...field("Problem hypothesis", record.rationale.problemHypothesis),
23
+ ...field("Expected observable difference", record.rationale.expectedObservableDifference));
24
+ for (const evidence of record.evidence) lines.push(`Evidence digest ${evidence.key}: ${evidence.status} (declaration only).`);
25
+ if (!record.evidence.length) lines.push("No source evidence declarations.");
26
+ }
27
+ if ("sections" in value) {
28
+ for (const section of value.sections) lines.push(`${section.section} diff`, ...field("Before", section.before), ...field("After", section.after));
29
+ lines.push(`Protected sections unchanged by construction: ${value.protectedSections.join(", ")}.`,
30
+ "Diff text is a screened public presentation, not the exact private bytes for a new record.");
31
+ } else {
32
+ lines.push(value.truncated ? "More declarations are available. Request the next page explicitly." : "Page complete.");
33
+ }
34
+ return lines;
35
+ }
36
+
37
+ /** A receipt confirms only its recorded declaration status, never execution or model use. */
38
+ export function guidanceReceiptLines(receipt: GuidanceWriteReceipt): string[] {
39
+ const experiment = sanitize(receipt.experimentId).replace(/[\p{Cc}\p{Cf}]/gu, "");
40
+ return [`Guidance ${receipt.status}${receipt.already ? " (already recorded)" : ""}.`, `Variant ${receipt.id}; task #${receipt.taskId}.`,
41
+ "Experiment label (untrusted advisory text):", `> ${experiment}`,
42
+ "Actual handoff, testing and model consumption are unknown."];
43
+ }
@@ -0,0 +1,34 @@
1
+ import type { ExecutionReferenceV1 } from "../hub/execution-reference.ts";
2
+ import type { LineageResult } from "../hub/execution-lineage.ts";
3
+
4
+ /**
5
+ * The one lineage view, shared by `ahub lineage show` and the acon provider (#1220 T3), so both
6
+ * surfaces show the same admitted page. Pure: no IO, clocks, probes or imports of a CLI module.
7
+ * Every string rendered here comes from a result that passed `parseLineageResult` and
8
+ * `parseExecutionReference`, which reject `\p{Cc}`; a terminal surface still strips at its own
9
+ * boundary (`renderExecutionLineage` in src/cli/lineage.ts).
10
+ */
11
+ export const executionLineageAddress = (ref: ExecutionReferenceV1): string =>
12
+ `${ref.tool}:${ref.kind} ${ref.id} (project ${ref.projectKey}${ref.revision === undefined ? "" : `, revision ${ref.revision}`}${ref.sha256 === undefined ? "" : `, sha256 ${ref.sha256}`})`;
13
+
14
+ type Unavailable = Extract<LineageResult, { state: "unavailable" }>;
15
+ const REPAIR: Record<NonNullable<Unavailable["reason"]>, string> = {
16
+ corrupt: "trusted source state could not be read; inspect ahub recovery status and the trusted source state before retrying ahub lineage show",
17
+ cursor_invalid: "the cursor is stale or does not match this source snapshot; refresh the same root and bounds without --cursor",
18
+ invalid: "the execution reference or page bounds are invalid; run ahub help lineage, correct the reference or bounds and retry",
19
+ withheld: "source metadata is withheld by policy; ask an authorized person to check the policy and select a public task scope before retrying ahub lineage show",
20
+ missing: "the root is not recorded in this admitted source; check the task or attempt identity and task scope, then retry ahub lineage show",
21
+ unsupported: "this source cannot project the requested root or scope within its supported bounds; select a supported root or smaller task scope, or upgrade the source before retrying ahub lineage show",
22
+ };
23
+
24
+ export function executionLineageLines(result: LineageResult): string[] {
25
+ if (result.state === "unavailable") {
26
+ // An unavailable source is never an empty successful graph: the reason is shown only when the
27
+ // source admitted diagnostics, and its absence keeps the unqualified refusal.
28
+ if (result.reason === undefined) return ["Lineage unavailable; check the root reference and your source-read access, then retry ahub lineage show."];
29
+ return [`Lineage unavailable (${result.reason}): ${REPAIR[result.reason]}.`];
30
+ }
31
+ return ["Execution lineage (metadata only)", ...result.nodes.map(node => `${executionLineageAddress(node.ref)}: ${node.state}, ${node.strength}`),
32
+ ...result.edges.map(edge => `${executionLineageAddress(edge.from)} -> ${executionLineageAddress(edge.to)}: ${edge.relation}, ${edge.strength}`),
33
+ ...(result.truncated ? [`Page truncated; retry the same root and bounds with --cursor ${result.cursor}.`] : ["Page complete."])];
34
+ }