@staix/agent-hub 0.35.0 → 0.36.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.
- package/CHANGELOG.md +26 -0
- package/README.md +21 -4
- package/docs/agent-notes/README.md +60 -0
- package/docs/agent-notes/adapters.md +5 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +5 -4
- package/docs/agent-notes/models.md +4 -3
- package/docs/agent-notes/tasks.md +8 -1
- package/docs/agent-notes/tests.md +1 -0
- package/docs/design/adapters.md +72 -0
- package/docs/design/agent-hub-architecture.md +1 -1
- package/docs/design/bus.md +8 -0
- package/docs/design/execution-reference.md +171 -11
- package/docs/design/guidance-experiments.md +438 -0
- package/docs/design/model-routes.md +628 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +111 -0
- package/docs/dogfood.md +15 -4
- package/docs/operations.md +291 -22
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +106 -1
- package/docs/research.md +4 -2
- package/docs/sdlc.md +108 -4
- package/docs/security.md +67 -5
- package/docs/specs/2026-09-19-agent-hub-design.md +5 -4
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +46 -0
- package/docs/verification/2026-11-10-0.36.0.md +59 -0
- package/docs/verification/2026-11-10-claude-implementer-2.1.322.md +59 -0
- package/docs/verification/2026-11-10-qwen-0270-dual-output.md +367 -0
- package/docs/verification/2026-11-10-qwen-0271-dual-output.md +101 -0
- package/docs/verification/claude-shell-wrapper-native.py +1 -1
- package/docs/verified.json +27 -27
- package/package.json +1 -1
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +1201 -368
- package/plugins/agent-hub/server.js +1682 -431
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/compat.ts +10 -10
- package/src/adapters/local-worker.ts +1 -1
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +10 -3
- package/src/cli/identity.ts +10 -3
- package/src/cli/init-prompt.ts +15 -2
- package/src/cli/init-required-checks.ts +122 -0
- package/src/cli/init-settings.ts +10 -4
- package/src/cli/init.ts +39 -3
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +111 -10
- package/src/cli/setup-research.ts +10 -0
- package/src/hub/autonomy-defaults.ts +20 -9
- package/src/hub/board.ts +346 -4
- package/src/hub/build-entry.ts +11 -0
- package/src/hub/bus.ts +12 -0
- package/src/hub/ci-watch.ts +4 -4
- package/src/hub/config-apply.ts +2 -1
- package/src/hub/config-trust.ts +1 -0
- package/src/hub/control-client.ts +1 -1
- package/src/hub/daemon.ts +342 -20
- package/src/hub/delivery-hints.ts +4 -2
- package/src/hub/delivery-journal.ts +50 -2
- package/src/hub/delivery-public.ts +51 -0
- package/src/hub/dogfood-profile.ts +8 -4
- package/src/hub/execution-lineage-owner.ts +272 -0
- package/src/hub/execution-lineage.ts +52 -8
- package/src/hub/execution-links.ts +85 -0
- package/src/hub/guidance-variants.ts +398 -0
- package/src/hub/handoff.ts +1 -0
- package/src/hub/hub-tools.ts +43 -2
- package/src/hub/manager.ts +44 -2
- package/src/hub/memory-policy.ts +2 -2
- package/src/hub/peers.ts +1 -1
- package/src/hub/planning.ts +1 -1
- package/src/hub/progress.ts +24 -7
- package/src/hub/restart.ts +13 -0
- package/src/hub/roles.ts +26 -0
- package/src/hub/routing.ts +4 -1
- package/src/hub/sdlc-merge.ts +39 -1
- package/src/hub/sdlc-release.ts +1 -1
- package/src/hub/sdlc.ts +62 -11
- package/src/hub/settings.ts +2 -0
- package/src/hub/supervision-proposals.ts +405 -0
- package/src/hub/supervision-rules.ts +388 -0
- package/src/hub/supervision.ts +2 -0
- package/src/hub/task-approval.ts +2 -2
- package/src/hub/task-repository.ts +5 -0
- package/src/hub/tasks.ts +603 -50
- package/src/memory/capture.ts +2 -2
- package/src/models/relay.ts +9 -2
- package/src/models/route/config.ts +27 -0
- package/src/models/route/decision.ts +87 -15
- package/src/models/route/relay-selector.ts +8 -7
- package/src/models/route/runtime.ts +22 -16
- package/src/models/route/stage-diagnostics.ts +22 -0
- package/src/models/route/stage-evidence.ts +55 -0
- package/src/models/route/stage-fallback.ts +58 -0
- package/src/models/route/stage-input.ts +155 -0
- package/src/models/route/stage.ts +5 -147
- package/src/ui/guidance-panel.ts +156 -0
- package/src/ui/guidance-view.ts +43 -0
- package/src/ui/lineage-view.ts +34 -0
- package/src/ui/plugin.ts +71 -7
package/src/memory/capture.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { reviewCaptureExcluded } from "../hub/memory-policy.ts";
|
|
2
2
|
import { isAbsolute, relative, resolve, sep } from "node:path";
|
|
3
3
|
import { defaultCapturePeer } from "../adapters/definitions/native-identity-defaults.ts";
|
|
4
|
-
import { BOUNDED_TASK_TOOLS, CAPABILITY_TOOLS, HANDOFF_TOOLS, QUESTION_TOOLS, STUDY_TOOLS } from "../hub/hub-tools.ts";
|
|
4
|
+
import { BOUNDED_TASK_TOOLS, LINEAGE_TOOL_NAMES, GUIDANCE_TOOL_NAMES, CAPABILITY_TOOLS, HANDOFF_TOOLS, QUESTION_TOOLS, STUDY_TOOLS } from "../hub/hub-tools.ts";
|
|
5
5
|
import { MEMORY_READ_TOOLS } from "../hub/read-tools.ts";
|
|
6
6
|
import { isDenied } from "../local/deny.ts";
|
|
7
7
|
import type { MemoryClient } from "./client.ts";
|
|
@@ -40,7 +40,7 @@ export class Capture {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
observe(call: { tool: string; args: string; output: string; id: string; paths: string[]; sourceId?: string }): void {
|
|
43
|
-
if (!this.sessionId || reviewCaptureExcluded(call.tool, call.args) || ((MEMORY_READ_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || BOUNDED_TASK_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || CAPABILITY_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || STUDY_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || HANDOFF_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, ""))) || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_memory_correct") || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_source_read" || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_set_title" || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_evidence_record" || this.opts.skip?.includes(call.tool)) return;
|
|
43
|
+
if (!this.sessionId || GUIDANCE_TOOL_NAMES.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || LINEAGE_TOOL_NAMES.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || reviewCaptureExcluded(call.tool, call.args) || ((MEMORY_READ_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || BOUNDED_TASK_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || CAPABILITY_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || STUDY_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, "")) || HANDOFF_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, ""))) || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_memory_correct") || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_source_read" || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_set_title" || call.tool.replace(/^mcp__[^ ]+__/, "") === "hub_evidence_record" || this.opts.skip?.includes(call.tool)) return;
|
|
44
44
|
// #1053: a question and its answer are the person's and the peer's words: never memory evidence, whatever the call's paths say.
|
|
45
45
|
if (QUESTION_TOOLS.has(call.tool.replace(/^mcp__[^ ]+__/, ""))) return;
|
|
46
46
|
// Anything that names a denylisted path is kept out of memory entirely, input and output alike.
|
package/src/models/relay.ts
CHANGED
|
@@ -3,7 +3,8 @@ import { isIP } from "node:net";
|
|
|
3
3
|
import type { OmniRoute, ChatMessage } from "../omniroute/client.ts";
|
|
4
4
|
import { ensureMlx, MlxBusyError, type MlxHandle, type MlxOptions, type MlxStatus } from "./mlx.ts";
|
|
5
5
|
import { AutoRouteSelector, type AutoChoice, type RelayRouteEvent } from "./route/relay-selector.ts";
|
|
6
|
-
import { estimateInputTokens,
|
|
6
|
+
import { estimateInputTokens, estimateStageInputTokens } from "./route/stage-input.ts";
|
|
7
|
+
import type { StaySwitchPolicy } from "./route/stage-fallback.ts";
|
|
7
8
|
|
|
8
9
|
export type ModelBackend = { kind: "mlx"; alias?: string } | { kind: "dgx"; alias: string };
|
|
9
10
|
|
|
@@ -649,7 +650,13 @@ export async function startModelRelay(options: ModelRelayOptions): Promise<Model
|
|
|
649
650
|
const own = backend;
|
|
650
651
|
// A refused request still records the decision, unmoved; a dispatched one records it after the ordering step.
|
|
651
652
|
const emitRoute = () => { if (auto) try { options.onRoute?.(auto.route); } catch { /* observation cannot fail routing */ } };
|
|
652
|
-
const inputTokens =
|
|
653
|
+
const inputTokens = estimateStageInputTokens(body.messages, body.tools);
|
|
654
|
+
if (inputTokens === undefined) {
|
|
655
|
+
emitRoute();
|
|
656
|
+
record.cleanup();
|
|
657
|
+
activeRequests.delete(record);
|
|
658
|
+
return Response.json({ error: "model input size is unavailable; provide bounded JSON messages and tool schemas" }, { status: 400 });
|
|
659
|
+
}
|
|
653
660
|
const inputBudget = own.kind === "mlx" ? (options.mlx?.maxInputTokens ?? (options.mlx?.provider === "ollama" ? 6000 : 16_000)) : dgxMaxInputTokens;
|
|
654
661
|
const ollama = own.kind === "mlx" && options.mlx?.provider === "ollama";
|
|
655
662
|
const contextWindow = ollama ? (options.mlx?.contextWindow ?? 8192) : undefined;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { isAdecRouteEndpoint } from "./adec.ts";
|
|
2
|
+
import { AMBIGUOUS_BAND_DEFAULT, AMBIGUOUS_BAND_MAX } from "./stage-fallback.ts";
|
|
2
3
|
|
|
3
4
|
/** In-process hub model-route policy. */
|
|
4
5
|
export interface HubRoute {
|
|
@@ -9,6 +10,8 @@ export interface HubRoute {
|
|
|
9
10
|
policy_id?: string;
|
|
10
11
|
candidates?: { alias: string; efforts: string[] }[];
|
|
11
12
|
decision_timeout_ms?: number;
|
|
13
|
+
classifier?: "decision";
|
|
14
|
+
ambiguous_band?: number;
|
|
12
15
|
efficient?: string;
|
|
13
16
|
capable?: string;
|
|
14
17
|
judge?: string;
|
|
@@ -45,11 +48,35 @@ export function parseHubRoutes(input: unknown): Record<string, HubRoute> {
|
|
|
45
48
|
if (typeof r.pattern === "string") new RegExp(r.pattern, "u");
|
|
46
49
|
if (r.type === "decision") {
|
|
47
50
|
out[id] = parseDecisionConfig(id, r);
|
|
51
|
+
} else if (r.type === "stage") {
|
|
52
|
+
out[id] = parseStageConfig(id, r);
|
|
48
53
|
} else out[id] = r as unknown as HubRoute;
|
|
49
54
|
}
|
|
50
55
|
return out;
|
|
51
56
|
}
|
|
52
57
|
|
|
58
|
+
/** A stage route keeps the deterministic picker; the optional classifier only decides whether adec is asked. */
|
|
59
|
+
function parseStageConfig(id: string, r: Record<string, unknown>): HubRoute {
|
|
60
|
+
if (r.classifier === undefined) {
|
|
61
|
+
if (r.ambiguous_band !== undefined) throw new Error(`routing.toml: invalid ${id}.ambiguous_band; set classifier = "decision" first`);
|
|
62
|
+
return r as unknown as HubRoute;
|
|
63
|
+
}
|
|
64
|
+
const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
|
|
65
|
+
if (r.classifier !== "decision") problem("classifier", 'use "decision"');
|
|
66
|
+
// ponytail: these four service validators repeat parseDecisionConfig because a stage route names two tiers instead of alias/effort pairs; fold both into one adec-service parser if a third route type needs it.
|
|
67
|
+
if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
|
|
68
|
+
if (r.decision_mode === "enforce") throw new Error("decision_mode enforce is not available yet; use shadow; tracked in #554");
|
|
69
|
+
if (r.decision_mode !== undefined && !["off", "shadow"].includes(String(r.decision_mode))) problem("decision_mode", 'use "off" or "shadow"');
|
|
70
|
+
if (typeof r.policy_id !== "string" || !/^[a-z0-9][a-z0-9._-]{0,49}$/.test(r.policy_id)) problem("policy_id", "name a configured adec policy with 1 to 50 lowercase identifier characters");
|
|
71
|
+
const endpoint = r.adec_endpoint ?? "http://127.0.0.1:8740/v1/route";
|
|
72
|
+
if (!isAdecRouteEndpoint(endpoint)) problem("adec_endpoint", "use an HTTP numeric loopback /v1/route URL without credentials, query or fragment");
|
|
73
|
+
if (r.decision_timeout_ms !== undefined && (!Number.isSafeInteger(r.decision_timeout_ms) || Number(r.decision_timeout_ms) < 1 || Number(r.decision_timeout_ms) > 30_000)) problem("decision_timeout_ms", "use 1 to 30000 milliseconds");
|
|
74
|
+
for (const tier of ["efficient", "capable"] as const) if (typeof r[tier] !== "string" || !(r[tier] as string).trim()) problem(tier, 'name the model alias this tier executes when classifier = "decision"');
|
|
75
|
+
const band = r.ambiguous_band ?? AMBIGUOUS_BAND_DEFAULT;
|
|
76
|
+
if (typeof band !== "number" || !Number.isFinite(band) || band < 0 || band > AMBIGUOUS_BAND_MAX) problem("ambiguous_band", `use a number from 0 to ${AMBIGUOUS_BAND_MAX}`);
|
|
77
|
+
return { ...r, decision_backend: "adec", decision_mode: r.decision_mode ?? "off", adec_endpoint: endpoint, ambiguous_band: band } as unknown as HubRoute;
|
|
78
|
+
}
|
|
79
|
+
|
|
53
80
|
function parseDecisionConfig(id: string, r: Record<string, unknown>): HubRoute {
|
|
54
81
|
const problem = (field: string, step: string): never => { throw new Error(`routing.toml: invalid ${id}.${field}; ${step}`); };
|
|
55
82
|
if (r.decision_backend !== "adec") problem("decision_backend", 'set decision_backend = "adec" for a loopback policy service');
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import { requestAdecRoute, type AdecResult, type AdecFailure, type AdecReason } from "./adec.ts";
|
|
2
|
+
import { requestAdecRoute, type AdecPair, type AdecResult, type AdecFailure, type AdecReason } from "./adec.ts";
|
|
3
3
|
import { buildDecisionEvidence } from "./decision-evidence.ts";
|
|
4
4
|
import type { HubRoute } from "./config.ts";
|
|
5
5
|
import type { ChatMessage } from "../../omniroute/client.ts";
|
|
6
6
|
import type { RouteLabelTracker } from "./labels.ts";
|
|
7
|
-
import { estimateInputTokens
|
|
7
|
+
import { estimateInputTokens } from "./stage-input.ts";
|
|
8
|
+
import { sensitiveStageEvidence, type CodingAgentDimensions, type StageEvidence } from "./stage-evidence.ts";
|
|
9
|
+
import type { StageTier } from "./stage-fallback.ts";
|
|
8
10
|
import { SessionState } from "./state.ts";
|
|
9
11
|
|
|
10
12
|
export interface DecisionHost {
|
|
@@ -24,15 +26,30 @@ export interface DecisionTrace {
|
|
|
24
26
|
interface Context {
|
|
25
27
|
route: string; scope: string; turn: ReturnType<RouteLabelTracker["captureTurn"]>;
|
|
26
28
|
current(): boolean; messages: ChatMessage[]; dimensions: CodingAgentDimensions; pii: boolean; signal: AbortSignal;
|
|
29
|
+
stageEvidence?: StageEvidence;
|
|
27
30
|
}
|
|
31
|
+
/** What one stage classification needs: bounded evidence instead of a conversation projection. */
|
|
32
|
+
export interface StageClassifyContext {
|
|
33
|
+
route: string; scope: string; turn: ReturnType<RouteLabelTracker["captureTurn"]>;
|
|
34
|
+
current(): boolean; messages: ChatMessage[]; evidence: StageEvidence; pii: boolean; signal: AbortSignal; tier: StageTier;
|
|
35
|
+
}
|
|
36
|
+
/** A purpose scopes the per-turn memo so one route type cannot read another's held answer. */
|
|
37
|
+
export type DecisionPurpose = "stage" | "decision";
|
|
38
|
+
interface Options { pairs: AdecPair[]; candidates: string[]; current?: AdecPair }
|
|
28
39
|
interface Privacy { pii: boolean; private: boolean; excluded: boolean }
|
|
29
40
|
interface Selection { trace?: DecisionTrace; check?(): void }
|
|
30
41
|
type Attempt = { result: AdecResult; privacy: Privacy } | { skipped: string };
|
|
31
42
|
export class DecisionPolicyChangedError extends Error {
|
|
32
43
|
constructor() { super("decision routing privacy or observer policy changed or is unavailable during preparation; run ahub status, inspect current task policy and retry"); }
|
|
33
44
|
}
|
|
34
|
-
interface State { fingerprint: string; failure?: { turn: string; result: AdecResult } }
|
|
45
|
+
interface State { fingerprint: string; failure?: { turn: string; result: AdecResult }; held?: { turn: string; trace: Partial<DecisionTrace>; privacy: Privacy } }
|
|
35
46
|
const ended = () => new Error("model route turn ended before execution; retry in the current turn");
|
|
47
|
+
/** R1's stage packet: numeric and categorical fields only, never a conversation fragment. */
|
|
48
|
+
function stagePacket(context: Context, sensitive: boolean): string {
|
|
49
|
+
const evidence = context.stageEvidence;
|
|
50
|
+
if (!evidence) throw new Error("stage routing needs R1's stage evidence; inspect the route call before retrying");
|
|
51
|
+
return JSON.stringify(sensitive ? sensitiveStageEvidence(evidence) : evidence);
|
|
52
|
+
}
|
|
36
53
|
|
|
37
54
|
/** Optional decision work never changes the baseline on failure; valid pins/rules remain owned by adec. */
|
|
38
55
|
export class DecisionRouteController {
|
|
@@ -52,7 +69,7 @@ export class DecisionRouteController {
|
|
|
52
69
|
this.fence(context, privacy);
|
|
53
70
|
return { ...selection, check: () => { this.fence(context, privacy); selection.check?.(); } };
|
|
54
71
|
};
|
|
55
|
-
try { return checked(await this.select(config, context)); }
|
|
72
|
+
try { return checked(await this.select(config, context, "decision", this.decisionOptions(config))); }
|
|
56
73
|
catch (error) {
|
|
57
74
|
if (context.signal.aborted || context.turn?.closed) throw ended();
|
|
58
75
|
this.fence(context, privacy); // a rejected await is still an authority boundary
|
|
@@ -60,6 +77,58 @@ export class DecisionRouteController {
|
|
|
60
77
|
return checked(this.skip(config, "unavailable"));
|
|
61
78
|
}
|
|
62
79
|
}
|
|
80
|
+
/** Shadow only: the answer is recorded as a route event, and no tier is returned, so it cannot change routing. */
|
|
81
|
+
async shadowClassify(config: HubRoute, context: StageClassifyContext): Promise<Partial<DecisionTrace>> {
|
|
82
|
+
if (config.type !== "stage" || config.classifier !== "decision" || (config.decision_mode ?? "off") === "off") { this.issues.delete(context.route); return {}; }
|
|
83
|
+
const options = this.stageOptions(config, context.tier);
|
|
84
|
+
if (!options) return {};
|
|
85
|
+
const inner: Context = { route: context.route, scope: context.scope, turn: context.turn, current: context.current,
|
|
86
|
+
messages: context.messages, dimensions: context.evidence.dimensions, stageEvidence: context.evidence, pii: context.pii, signal: context.signal };
|
|
87
|
+
// An optional stage question never refuses a turn: the heuristic tier already stands, so a refusal records nothing to apply.
|
|
88
|
+
if (inner.signal.aborted || inner.turn?.closed) return {};
|
|
89
|
+
const state = this.state(config, inner, "stage"), key = this.turnKey("stage", inner);
|
|
90
|
+
// One question per user turn, kept through the tool loop, exactly like the #197 pin rule. The held answer was
|
|
91
|
+
// computed under the privacy and observer facts recorded with it, so a turn whose facts moved on drops it instead of
|
|
92
|
+
// publishing a classification the current authority never approved; an unreadable authority read keeps propagating.
|
|
93
|
+
const held = state.held;
|
|
94
|
+
if (held?.turn === key) {
|
|
95
|
+
const now = this.privacy(inner.pii);
|
|
96
|
+
if (!inner.current() || !this.same(held.privacy, now)) { state.held = undefined; return {}; }
|
|
97
|
+
return held.trace;
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
const trace = (await this.select(config, inner, "stage", options)).trace ?? {};
|
|
101
|
+
this.hold(state, key, trace, inner);
|
|
102
|
+
return trace;
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
// Changed or unavailable authority is not a service failure: it keeps refusing the stale turn, exactly as on a
|
|
106
|
+
// decision route, instead of becoming a model fallback around that refusal. A closed turn only moots the question.
|
|
107
|
+
if (error instanceof DecisionPolicyChangedError || error && typeof error === "object" && "budgetStop" in error) throw error;
|
|
108
|
+
if (inner.signal.aborted || inner.turn?.closed) return {};
|
|
109
|
+
const trace = this.skip(config, "unavailable").trace ?? {};
|
|
110
|
+
this.hold(state, key, trace, inner);
|
|
111
|
+
return trace;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** The memo keeps the facts an answer was computed under; an unreadable binding stores no publishable record. */
|
|
115
|
+
private hold(state: State, key: string, trace: Partial<DecisionTrace>, context: Context): void {
|
|
116
|
+
try { state.held = { turn: key, trace, privacy: this.privacy(context.pii) }; } catch { state.held = undefined; }
|
|
117
|
+
}
|
|
118
|
+
private turnKey(purpose: DecisionPurpose, context: Context): string {
|
|
119
|
+
return createHash("sha256").update(JSON.stringify([purpose, context.route, context.scope, context.turn?.context.turn])).digest("hex");
|
|
120
|
+
}
|
|
121
|
+
private decisionOptions(config: HubRoute): Options {
|
|
122
|
+
const pairs = config.candidates?.flatMap(candidate => candidate.efforts.map(effort => ({ alias: candidate.alias, effort }))) ?? [];
|
|
123
|
+
return { pairs, candidates: [...new Set(pairs.map(pair => pair.alias))] };
|
|
124
|
+
}
|
|
125
|
+
/** A tier carries no effort, so both offerings use "none" and the answer maps back by alias equality. */
|
|
126
|
+
private stageOptions(config: HubRoute, tier: StageTier): Options | undefined {
|
|
127
|
+
const efficient = config.efficient, capable = config.capable;
|
|
128
|
+
if (!efficient || !capable || efficient === capable) return undefined;
|
|
129
|
+
const efficientPair: AdecPair = { alias: efficient, effort: "none" }, capablePair: AdecPair = { alias: capable, effort: "none" };
|
|
130
|
+
return { pairs: [efficientPair, capablePair], candidates: [efficient, capable], current: tier === "capable" ? capablePair : efficientPair };
|
|
131
|
+
}
|
|
63
132
|
private issue(config: HubRoute, context: Context, reason: AdecFailure | AdecReason | null): void {
|
|
64
133
|
const fingerprint = JSON.stringify(config), previous = this.issues.get(context.route);
|
|
65
134
|
if (previous?.fingerprint === fingerprint && previous.reason === reason) return;
|
|
@@ -69,8 +138,8 @@ export class DecisionRouteController {
|
|
|
69
138
|
private skip(config: HubRoute, reason: string): Selection {
|
|
70
139
|
return { trace: { decisionMode: config.decision_mode ?? "off", chosenAlias: null, chosenEffort: null, decisionReason: reason } };
|
|
71
140
|
}
|
|
72
|
-
private state(config: HubRoute, context: Context): State {
|
|
73
|
-
const key = JSON.stringify([context.route, context.scope]), fingerprint = JSON.stringify(config);
|
|
141
|
+
private state(config: HubRoute, context: Context, purpose: DecisionPurpose): State {
|
|
142
|
+
const key = JSON.stringify([purpose, context.route, context.scope]), fingerprint = JSON.stringify(config);
|
|
74
143
|
const prior = this.states.get(key);
|
|
75
144
|
if (prior?.fingerprint === fingerprint) return prior;
|
|
76
145
|
const state: State = { fingerprint }; this.states.set(key, state); return state;
|
|
@@ -92,16 +161,16 @@ export class DecisionRouteController {
|
|
|
92
161
|
try { if (this.same(privacy, this.privacy(context.pii))) return; } catch { /* unavailable current facts refuse the handoff */ }
|
|
93
162
|
throw new DecisionPolicyChangedError();
|
|
94
163
|
}
|
|
95
|
-
private async select(config: HubRoute, context: Context): Promise<Selection> {
|
|
164
|
+
private async select(config: HubRoute, context: Context, purpose: DecisionPurpose, options: Options): Promise<Selection> {
|
|
96
165
|
const { turn } = context;
|
|
97
166
|
if (!turn) return this.skip(config, "turn_unavailable");
|
|
98
167
|
const privacy = this.privacy(context.pii);
|
|
99
168
|
if (privacy.excluded) return this.skip(config, "observer_excluded");
|
|
100
169
|
// A newly private board context is not permission to reuse a public delivery's text.
|
|
101
170
|
if ((privacy.pii || privacy.private) && !context.pii) throw new DecisionPolicyChangedError();
|
|
102
|
-
const state = this.state(config, context), key =
|
|
171
|
+
const state = this.state(config, context, purpose), key = this.turnKey(purpose, context);
|
|
103
172
|
const began = performance.now();
|
|
104
|
-
const attempt: Attempt = state.failure?.turn === key ? { result: state.failure.result, privacy } : await this.request(config, context, privacy, state, key);
|
|
173
|
+
const attempt: Attempt = state.failure?.turn === key ? { result: state.failure.result, privacy } : await this.request(config, context, privacy, state, key, options, purpose);
|
|
105
174
|
if (!context.current()) throw ended();
|
|
106
175
|
if ("skipped" in attempt) return this.skip(config, attempt.skipped);
|
|
107
176
|
this.fence(context, attempt.privacy);
|
|
@@ -118,7 +187,7 @@ export class DecisionRouteController {
|
|
|
118
187
|
decisionLatencyMs: Math.max(0, performance.now() - began), decisionReason: d.reason, fallbackApplied: d.fallbackApplied,
|
|
119
188
|
...(decider === undefined ? {} : { decider }) } };
|
|
120
189
|
}
|
|
121
|
-
private async request(config: HubRoute, context: Context, initial: Privacy, state: State, key: string): Promise<Attempt> {
|
|
190
|
+
private async request(config: HubRoute, context: Context, initial: Privacy, state: State, key: string, options: Options, purpose: DecisionPurpose): Promise<Attempt> {
|
|
122
191
|
await this.host.admitDecision?.();
|
|
123
192
|
if (!context.current()) throw ended();
|
|
124
193
|
const privacy = this.privacy(context.pii);
|
|
@@ -127,14 +196,17 @@ export class DecisionRouteController {
|
|
|
127
196
|
this.fence(context, privacy);
|
|
128
197
|
if (!campus) return { skipped: "off_campus" };
|
|
129
198
|
const sensitive = privacy.pii || privacy.private;
|
|
130
|
-
|
|
131
|
-
|
|
199
|
+
// The stage question carries R1's own closed numeric/categorical evidence. The generic v1 projection quotes
|
|
200
|
+
// conversation fragments, which that contract never allows; a sensitive turn keeps only the dimensions view.
|
|
201
|
+
const evidence = purpose === "stage" ? stagePacket(context, sensitive)
|
|
202
|
+
: buildDecisionEvidence(sensitive ? [] : context.messages, context.dimensions, text => this.host.publicDecisionText?.(text) === true);
|
|
132
203
|
this.fence(context, privacy);
|
|
133
204
|
const result = await requestAdecRoute(config.adec_endpoint ?? "http://127.0.0.1:8740/v1/route", {
|
|
134
205
|
policyId: config.policy_id ?? "", turnId: `ahub:${key}`, evidence,
|
|
135
|
-
constraints: { contextTokens: sensitive ? 0 : estimateInputTokens(context.messages), pii: privacy.pii, private: privacy.private
|
|
136
|
-
|
|
137
|
-
|
|
206
|
+
constraints: { contextTokens: sensitive ? 0 : estimateInputTokens(context.messages), pii: privacy.pii, private: privacy.private,
|
|
207
|
+
...(options.current === undefined ? {} : { current: options.current }) },
|
|
208
|
+
candidates: options.candidates,
|
|
209
|
+
}, options.pairs, context.signal, config.decision_timeout_ms ?? this.timeoutMs);
|
|
138
210
|
this.fence(context, privacy);
|
|
139
211
|
// Only failed transports are held locally, never a valid pin: the service rechecks current hard rules.
|
|
140
212
|
if (!result.ok) state.failure = { turn: key, result };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import type { ModelBackend, ModelRelayOptions, RelayRequest } from "../relay.ts";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { captureStageInput } from "./stage-input.ts";
|
|
3
|
+
import { buildStageEvidence } from "./stage-evidence.ts";
|
|
4
|
+
import { selectFallbackStage, planStageSwitch, type FallbackStageState as StageState, type StageSwitchTrace as SwitchTrace, type StageTier as Tier } from "./stage-fallback.ts";
|
|
5
5
|
import { SessionState } from "./state.ts";
|
|
6
6
|
|
|
7
7
|
type RelaySelectorOptions = Pick<ModelRelayOptions, "mlx" | "selectBackend" | "routeSessionKey" | "allowedDGXmodels" | "staySwitch"> & { dgxMaxInputTokens: number };
|
|
@@ -44,11 +44,12 @@ export class AutoRouteSelector {
|
|
|
44
44
|
let movable = true;
|
|
45
45
|
let prefer: string | undefined;
|
|
46
46
|
try {
|
|
47
|
-
const
|
|
48
|
-
|
|
47
|
+
const input = captureStageInput(body);
|
|
48
|
+
if (!input) throw new Error("stage input is unavailable");
|
|
49
|
+
const decision = selectFallbackStage(buildStageEvidence(input), { confidenceThreshold: 0.5, holdTurns: 2 }, prior?.stage);
|
|
49
50
|
const inputTokens = this.estimateInputTokens(body.messages, body.tools);
|
|
50
51
|
const fits = (candidate: Tier) => { const staged = this.stageBackend(candidate, body, inputTokens); return !!staged && (staged.kind === "mlx" || inputTokens <= this.options.dgxMaxInputTokens); };
|
|
51
|
-
const staged =
|
|
52
|
+
const staged = planStageSwitch(this.options.staySwitch?.(), prior?.pin?.tier, decision, input.turn, { inputTokens, fits });
|
|
52
53
|
next = { stage: decision.state, ...(staged.pin ? { pin: { tier: staged.pin, alias: "" } } : {}) };
|
|
53
54
|
trace = staged.trace;
|
|
54
55
|
score = decision.score;
|
|
@@ -106,7 +107,7 @@ export class AutoRouteSelector {
|
|
|
106
107
|
}
|
|
107
108
|
|
|
108
109
|
private sourceOf(source: string): RouteSource {
|
|
109
|
-
if (source === "
|
|
110
|
+
if (source === "hold") return "hold";
|
|
110
111
|
if (source === "override" || source === "dimensions") return source;
|
|
111
112
|
if (source === "llm-classifier") return "classifier";
|
|
112
113
|
return "default";
|
|
@@ -4,9 +4,11 @@ import { AdvisorGate, buildAdvisorJudgeRequest, redoFeedback } from "./advisor.t
|
|
|
4
4
|
import type { HubRoute } from "./config.ts";
|
|
5
5
|
import { buildEscalationJudgeRequest, parseEscalationVerdict } from "./escalation.ts";
|
|
6
6
|
import { normalizeConversation } from "./normalize.ts";
|
|
7
|
-
import { extractToolSignals
|
|
7
|
+
import { extractToolSignals } from "./signals.ts";
|
|
8
8
|
import { RouteLabelTracker, type RouteLabelEvent, type RouteTurnContext, type RouteTurnOutcome } from "./labels.ts";
|
|
9
|
-
import {
|
|
9
|
+
import { captureStageInput, estimateStageInputTokens } from "./stage-input.ts";
|
|
10
|
+
import { buildStageEvidence, type CodingAgentDimensions } from "./stage-evidence.ts";
|
|
11
|
+
import { selectFallbackStage, planStageSwitch, ambiguousStage, type FallbackStageState, type StaySwitchPolicy, type StageSwitchTrace as SwitchTrace, type StageTier as Tier } from "./stage-fallback.ts";
|
|
10
12
|
import { EscalationState, SessionState } from "./state.ts";
|
|
11
13
|
import { parseAdvisorVerdict } from "./text.ts";
|
|
12
14
|
import { planExecutePhase, type PlanExecuteState } from "./plan-execute.ts";
|
|
@@ -16,7 +18,7 @@ export interface RouteEvent extends Partial<SwitchTrace>, Partial<DecisionTrace>
|
|
|
16
18
|
decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number;
|
|
17
19
|
}
|
|
18
20
|
export interface AdvisorEvent { route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }
|
|
19
|
-
interface RouteState { fingerprint: string; stage:
|
|
21
|
+
interface RouteState { fingerprint: string; stage: FallbackStageState; pin?: Tier; plan: PlanExecuteState; escalation: EscalationState; advisor: AdvisorGate }
|
|
20
22
|
export interface RouteHost extends DecisionHost {
|
|
21
23
|
execute: (model: string, messages: ChatMessage[], judge: boolean, signal: AbortSignal, maxTokens?: number) => Promise<ChatResult>;
|
|
22
24
|
/** Read on every stage call (#197); absent is the shadow default. */
|
|
@@ -51,7 +53,7 @@ export class HubRouteRuntime {
|
|
|
51
53
|
const key = `${scope}:${route}`, fingerprint = JSON.stringify(config);
|
|
52
54
|
const prior = this.states.get(key);
|
|
53
55
|
if (prior?.fingerprint === fingerprint) return prior;
|
|
54
|
-
const value: RouteState = { fingerprint, stage: {
|
|
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 }) };
|
|
55
57
|
this.states.set(key, value); return value;
|
|
56
58
|
}
|
|
57
59
|
|
|
@@ -60,27 +62,31 @@ export class HubRouteRuntime {
|
|
|
60
62
|
const labelTurn = this.labels.captureTurn();
|
|
61
63
|
this.decisions.checkEntry(config, pii);
|
|
62
64
|
const started = performance.now(), state = this.state(route, config, scope);
|
|
63
|
-
const
|
|
64
|
-
const
|
|
65
|
+
const input = captureStageInput(messages) ?? { turn: "other" as const, incomplete: true, assistantTurns: 0, results: [] };
|
|
66
|
+
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));
|
|
65
69
|
const efficient = config.efficient ?? "fast", capable = config.capable ?? "coding";
|
|
66
70
|
let model = efficient, source: RouteEvent["source"] = "default", score = 0;
|
|
67
71
|
let sent = messages, trace: Partial<SwitchTrace> = {};
|
|
68
72
|
if (config.type === "stage" || config.type === "decision") {
|
|
69
|
-
const decision =
|
|
73
|
+
const decision = selectFallbackStage(evidence, { confidenceThreshold: config.confidence_threshold, holdTurns: config.hold_turns }, state.stage);
|
|
70
74
|
state.stage = decision.state;
|
|
71
|
-
//
|
|
72
|
-
|
|
73
|
-
// something about its text, as a private envelope's does: the planner never sees it (no prefill bound, so no
|
|
74
|
-
// plan or reason can depend on it) and the event leaves it out.
|
|
75
|
-
const staged = stayOrSwitch(this.host.staySwitch?.(), state.pin, decision, turnKind(conversation), { inputTokens: pii ? 0 : estimateInputTokens(messages), fits: () => true });
|
|
75
|
+
// Public planner sizing is separate from local full-context admission. Sensitive size is omitted.
|
|
76
|
+
const staged = planStageSwitch(this.host.staySwitch?.(), state.pin, decision, input.turn, { inputTokens: pii ? undefined : estimateStageInputTokens(messages), fits: () => true });
|
|
76
77
|
state.pin = staged.pin;
|
|
77
78
|
const { prefillTokens, ...shape } = staged.trace;
|
|
78
79
|
trace = pii ? shape : staged.trace;
|
|
79
80
|
model = staged.tier === "capable" ? capable : efficient;
|
|
80
81
|
score = decision.score;
|
|
81
|
-
source = decision.source
|
|
82
|
+
source = decision.source;
|
|
83
|
+
if (config.type === "stage" && config.classifier === "decision" && ambiguousStage(decision, { confidenceThreshold: config.confidence_threshold, ambiguousBand: config.ambiguous_band })) {
|
|
84
|
+
// The band decides only whether adec is asked; the tier and model above stay exactly as the heuristic chose them.
|
|
85
|
+
trace = { ...trace, ...await this.decisions.shadowClassify(config, { route, scope, turn: labelTurn, messages, evidence, pii, signal, tier: staged.tier,
|
|
86
|
+
current: () => !signal.aborted && !labelTurn?.closed && this.labels.captureTurn() === labelTurn }) };
|
|
87
|
+
}
|
|
82
88
|
} else if (config.type === "plan_execute") {
|
|
83
|
-
const decision = planExecutePhase(signals
|
|
89
|
+
const decision = planExecutePhase(signals!, scope, state.plan);
|
|
84
90
|
model = decision.tier === "capable" ? capable : efficient;
|
|
85
91
|
state.plan = decision.state;
|
|
86
92
|
if (decision.planningPrompt) sent = [{ role: "system", content: decision.planningPrompt }, ...messages];
|
|
@@ -92,7 +98,7 @@ export class HubRouteRuntime {
|
|
|
92
98
|
let decisionId = this.emitRoute({ route, tier: model, source, score, ms: performance.now() - started, ...trace, ...picked?.trace }, labelTurn, dimensions, pii, messages);
|
|
93
99
|
const result = await this.host.execute(model, sent, false, signal);
|
|
94
100
|
if (config.type !== "escalation" || state.escalation.snapshot().latched) return this.withDecision(result, decisionId);
|
|
95
|
-
const request = buildEscalationJudgeRequest(normalizeConversation([...messages, result.message]), signals
|
|
101
|
+
const request = buildEscalationJudgeRequest(normalizeConversation([...messages, result.message]), signals!.assistantTurnCount + 1);
|
|
96
102
|
const answer = await this.judge(config.judge ?? capable, [{ role: "system", content: request.systemPrompt }, ...request.messages], pii, signal, request.maxOutputTokens);
|
|
97
103
|
const verdict = answer ? parseEscalationVerdict(answer) : undefined;
|
|
98
104
|
if (answer && !verdict) this.judgeOffUntil = Date.now() + 5 * 60_000;
|
|
@@ -124,7 +130,7 @@ export class HubRouteRuntime {
|
|
|
124
130
|
return decisionId ? { ...result, routeDecision: decisionId } : result;
|
|
125
131
|
}
|
|
126
132
|
|
|
127
|
-
private emitRoute(event: RouteEvent, turn: ReturnType<RouteLabelTracker["captureTurn"]>, dimensions:
|
|
133
|
+
private emitRoute(event: RouteEvent, turn: ReturnType<RouteLabelTracker["captureTurn"]>, dimensions: CodingAgentDimensions, pii: boolean, priorMessages: ChatMessage[]): string | undefined {
|
|
128
134
|
if (turn && turn.closed) return undefined;
|
|
129
135
|
let decision: string | undefined;
|
|
130
136
|
try {
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { StageResultInput } from "./stage-input.ts";
|
|
2
|
+
export type FaultClass = "none" | "reported" | "exception" | "critical";
|
|
3
|
+
export interface StageDiagnostic { fault: FaultClass; test: "none" | "pass" | "fail" | "unknown"; fingerprint?: string }
|
|
4
|
+
/** Diagnostics are local evidence, never instructions or public fragments. */
|
|
5
|
+
export function diagnoseStageResult(result: StageResultInput): StageDiagnostic {
|
|
6
|
+
const value = result.text.toLowerCase();
|
|
7
|
+
// Remove counted zero-failure summaries before matching uncounted "tests failed" wording.
|
|
8
|
+
const diagnosticText = value.replace(/\b0\s+(?:tests?\s+)?(?:fail|failed|failures)\b/g, "");
|
|
9
|
+
const failedTest = /\b(?:[1-9]\d*\s+(?:tests?\s+)?(?:fail|failed)|tests?\s+failed|assertion(?:error| failed))\b/.test(diagnosticText);
|
|
10
|
+
const positivePass = /\b[1-9]\d*\s+(?:tests?\s+)?(?:pass|passed)\b/.test(value);
|
|
11
|
+
const zeroPass = /\b0\s+(?:tests?\s+)?(?:pass|passed)\b/.test(value);
|
|
12
|
+
const affirmativePass = /^[ \t]*(?:all[ \t]+tests?[ \t]+pass(?:ed)?|tests?[ \t]+passed)[.!]?[ \t\r]*$/m.test(value);
|
|
13
|
+
const passedTest = !failedTest && (positivePass || !zeroPass && affirmativePass);
|
|
14
|
+
const critical = /\b(?:fatal|panic|segmentation fault|out of memory|memoryerror)\b/.test(value);
|
|
15
|
+
const explicit = result.error || failedTest || (critical || /\b(?:error|failed|failure|exception|fatal|panic|memoryerror)\b/.test(diagnosticText) || /\b\w*(?:exception|error):/.test(diagnosticText)) && result.family !== "read";
|
|
16
|
+
if (!explicit) return { fault: "none", test: passedTest ? "pass" : zeroPass ? "unknown" : "none" };
|
|
17
|
+
const fault: FaultClass = critical ? "critical"
|
|
18
|
+
: !/\bassertionerror:/.test(value) && /\b\w*(?:exception|error):/.test(value) ? "exception" : "reported";
|
|
19
|
+
// Bounded source capture makes this local comparison bounded too; no fingerprint enters StageEvidence.
|
|
20
|
+
const fingerprint = value.replace(/\b\d+\b/g, "#").replace(/\s+/g, " ").trim();
|
|
21
|
+
return { fault, test: failedTest ? "fail" : "none", fingerprint: `${failedTest ? "test" : "other"}:${fingerprint}` };
|
|
22
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { diagnoseStageResult, type FaultClass } from "./stage-diagnostics.ts";
|
|
2
|
+
import type { StageInput, StageTurn } from "./stage-input.ts";
|
|
3
|
+
export interface CodingAgentDimensions { severity: number; spinning: number; exploring: number; productionIntensity: number }
|
|
4
|
+
export interface StageEvidence {
|
|
5
|
+
schemaVersion: 1; kind: "stage-route-evidence"; turn: StageTurn; incomplete: boolean;
|
|
6
|
+
signals: { results: number; failures: number; repeatedFailures: number; reads: number; mutations: number; assistantTurns: number; tests: "none" | "pass" | "fail" | "unknown"; fault: FaultClass };
|
|
7
|
+
dimensions: CodingAgentDimensions;
|
|
8
|
+
scores: { efficient: number; capable: number };
|
|
9
|
+
}
|
|
10
|
+
// Published by the owned #637 no-progress corpus rule. These are fallback calibration, not transport bounds.
|
|
11
|
+
const EXECUTION_STREAK = 8, EXECUTION_AMBIGUITY = 0.46;
|
|
12
|
+
const SEVERITY = { none: 0, reported: 0.3, exception: 0.7, critical: 1 } as const;
|
|
13
|
+
/** Numeric/categorical projection only. Generic routing-decision-evidence v1 is a different contract. */
|
|
14
|
+
export function buildStageEvidence(input: StageInput): StageEvidence {
|
|
15
|
+
const failures: { fault: FaultClass; test: boolean; fingerprint: string }[] = [];
|
|
16
|
+
let reads = 0, mutations = 0, tests: StageEvidence["signals"]["tests"] = "none";
|
|
17
|
+
let latestFault: FaultClass = "none", successfulExecutions = 0;
|
|
18
|
+
const executionFrames = new Set<number>();
|
|
19
|
+
for (const result of input.results) {
|
|
20
|
+
if (result.family === "read") reads++;
|
|
21
|
+
if (result.family === "mutation") mutations++;
|
|
22
|
+
const diagnostic = diagnoseStageResult(result);
|
|
23
|
+
tests = diagnostic.test;
|
|
24
|
+
latestFault = diagnostic.fault;
|
|
25
|
+
if (result.family === "execution" && result.associated && result.assistantTurn !== undefined && diagnostic.fault === "none" && diagnostic.test !== "pass") {
|
|
26
|
+
successfulExecutions++;
|
|
27
|
+
executionFrames.add(result.assistantTurn);
|
|
28
|
+
} else {
|
|
29
|
+
successfulExecutions = 0;
|
|
30
|
+
executionFrames.clear();
|
|
31
|
+
}
|
|
32
|
+
if (diagnostic.test === "pass") {
|
|
33
|
+
for (let index = failures.length - 1; index >= 0; index--) if (failures[index]!.test) failures.splice(index, 1);
|
|
34
|
+
}
|
|
35
|
+
if (diagnostic.fault !== "none") failures.push({ fault: diagnostic.fault, test: diagnostic.test === "fail", fingerprint: diagnostic.fingerprint! });
|
|
36
|
+
}
|
|
37
|
+
const fault = failures.reduce<FaultClass>((prior, failure) => SEVERITY[failure.fault] > SEVERITY[prior] ? failure.fault : prior, "none");
|
|
38
|
+
const groups = new Map<string, number>();
|
|
39
|
+
for (const failure of failures) groups.set(failure.fingerprint, (groups.get(failure.fingerprint) ?? 0) + 1);
|
|
40
|
+
const repeatedFailures = Math.max(0, ...groups.values());
|
|
41
|
+
const currentCompletion = input.turn === "tool_result";
|
|
42
|
+
const currentFailure = currentCompletion && latestFault !== "none";
|
|
43
|
+
const noProgress = currentCompletion && successfulExecutions >= EXECUTION_STREAK && executionFrames.size >= EXECUTION_STREAK && input.assistantTurns >= EXECUTION_STREAK;
|
|
44
|
+
const dimensions = { severity: currentCompletion ? SEVERITY[latestFault] : 0,
|
|
45
|
+
spinning: currentFailure && repeatedFailures >= 2 ? Math.min(1, repeatedFailures / Math.max(1, failures.length)) : noProgress ? EXECUTION_AMBIGUITY : 0,
|
|
46
|
+
exploring: reads / Math.max(1, input.results.length), productionIntensity: mutations / Math.max(1, input.results.length) };
|
|
47
|
+
const risk = Math.max(dimensions.severity, dimensions.spinning);
|
|
48
|
+
return { schemaVersion: 1, kind: "stage-route-evidence", turn: input.turn, incomplete: input.incomplete,
|
|
49
|
+
signals: { results: input.results.length, failures: failures.length, repeatedFailures, reads, mutations, assistantTurns: input.assistantTurns, tests, fault },
|
|
50
|
+
dimensions, scores: { efficient: 1 - risk, capable: risk } };
|
|
51
|
+
}
|
|
52
|
+
/** A sensitive future service projection must not expose history shape. No transport is introduced here. */
|
|
53
|
+
export function sensitiveStageEvidence(evidence: StageEvidence): Pick<StageEvidence, "schemaVersion" | "kind" | "dimensions"> {
|
|
54
|
+
return { schemaVersion: evidence.schemaVersion, kind: evidence.kind, dimensions: { ...evidence.dimensions } };
|
|
55
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import type { StageEvidence } from "./stage-evidence.ts";
|
|
2
|
+
import type { StageTurn } from "./stage-input.ts";
|
|
3
|
+
export type StageTier = "efficient" | "capable";
|
|
4
|
+
export interface FallbackStagePolicy { confidenceThreshold?: number; holdTurns?: number; ambiguousBand?: number }
|
|
5
|
+
export interface FallbackStageState { recoveryHoldRemaining: number }
|
|
6
|
+
export interface FallbackStageResult { tier: StageTier; source: "default" | "dimensions" | "override" | "hold"; score: number; state: FallbackStageState }
|
|
7
|
+
export function selectFallbackStage(evidence: StageEvidence, policy: FallbackStagePolicy = {}, prior?: FallbackStageState): FallbackStageResult {
|
|
8
|
+
const threshold = policy.confidenceThreshold ?? 0.5, hold = policy.holdTurns ?? 2;
|
|
9
|
+
if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1 || !Number.isSafeInteger(hold) || hold < 0 || hold > 200_000) throw new Error("invalid stage fallback policy");
|
|
10
|
+
const score = evidence.scores.capable;
|
|
11
|
+
const currentFailure = evidence.turn === "tool_result" && evidence.dimensions.severity > 0;
|
|
12
|
+
const recovery = evidence.turn === "compaction" || currentFailure && (evidence.dimensions.severity === 1 || evidence.signals.repeatedFailures >= 2);
|
|
13
|
+
const cleanPass = evidence.turn === "tool_result" && evidence.signals.tests === "pass" && evidence.dimensions.severity === 0;
|
|
14
|
+
const remaining = cleanPass ? 0 : prior?.recoveryHoldRemaining ?? 0;
|
|
15
|
+
if (recovery) return { tier: "capable", source: "override", score, state: { recoveryHoldRemaining: hold } };
|
|
16
|
+
if (remaining > 0) return { tier: "capable", source: "hold", score, state: { recoveryHoldRemaining: remaining - 1 } };
|
|
17
|
+
return { tier: score > threshold ? "capable" : "efficient", source: score > threshold ? "dimensions" : "default", score, state: { recoveryHoldRemaining: 0 } };
|
|
18
|
+
}
|
|
19
|
+
/** The band decides only whether a decider is asked; membership never changes the tier. */
|
|
20
|
+
export const AMBIGUOUS_BAND_DEFAULT = 0.05, AMBIGUOUS_BAND_MAX = 0.5;
|
|
21
|
+
export function ambiguousStage(result: FallbackStageResult, policy: FallbackStagePolicy = {}): boolean {
|
|
22
|
+
const threshold = policy.confidenceThreshold ?? 0.5, band = policy.ambiguousBand ?? AMBIGUOUS_BAND_DEFAULT;
|
|
23
|
+
// Zero is the documented way to switch the question off, so it cannot fire on an exact tie with the threshold; a
|
|
24
|
+
// band outside its own range is not ambiguous either, and the fallback tier stands with no service asked.
|
|
25
|
+
if (!Number.isFinite(threshold) || !Number.isFinite(band) || band <= 0 || band > AMBIGUOUS_BAND_MAX) return false;
|
|
26
|
+
return Math.abs(result.score - threshold) <= band;
|
|
27
|
+
}
|
|
28
|
+
export type StaySwitchMode = "off" | "shadow" | "enforce";
|
|
29
|
+
export interface StaySwitchPolicy { stay_switch: StaySwitchMode; max_switch_prefill_tokens: number }
|
|
30
|
+
export const DEFAULT_STAY_SWITCH: StaySwitchPolicy = { stay_switch: "shadow", max_switch_prefill_tokens: 32_000 };
|
|
31
|
+
export type StageSwitchReason = "new_pin" | "compaction" | "context_fit" | "same_tier" | "override" | "tool_loop" | "prefill_bound" | "user_turn";
|
|
32
|
+
export interface StageSwitchTrace { turnType?: Exclude<StageTurn, "other">; prefillTokens?: number; staySwitch?: "shadow" | "enforce"; plan?: "stay" | "switch"; reason?: StageSwitchReason }
|
|
33
|
+
export interface StageSwitchResult { tier: StageTier; pin: StageTier | undefined; trace: StageSwitchTrace }
|
|
34
|
+
/** A switch proposal cannot bypass host fit or authorize a model call. */
|
|
35
|
+
export function planStageSwitch(policy: StaySwitchPolicy | undefined, pin: StageTier | undefined, fallback: FallbackStageResult, turn: StageTurn,
|
|
36
|
+
host: { inputTokens?: number; fits: (tier: StageTier) => boolean }): StageSwitchResult {
|
|
37
|
+
const actual = policy ?? DEFAULT_STAY_SWITCH;
|
|
38
|
+
const trace: StageSwitchTrace = { ...(turn === "other" ? {} : { turnType: turn }), ...(host.inputTokens === undefined ? {} : { prefillTokens: host.inputTokens }) };
|
|
39
|
+
if (turn === "other") return { tier: fallback.tier, pin, trace };
|
|
40
|
+
if (actual.stay_switch === "off") return { tier: fallback.tier, pin: undefined, trace };
|
|
41
|
+
let proposal = fallback.tier, reason: StageSwitchReason;
|
|
42
|
+
if (!pin) reason = "new_pin";
|
|
43
|
+
else if (!host.fits(pin)) reason = "context_fit";
|
|
44
|
+
else if (turn === "compaction") reason = "compaction";
|
|
45
|
+
else if (pin === fallback.tier) reason = "same_tier";
|
|
46
|
+
else if (fallback.source === "override") reason = "override";
|
|
47
|
+
else if (turn === "tool_result") { proposal = pin; reason = "tool_loop"; }
|
|
48
|
+
else if (fallback.tier === "efficient" && host.inputTokens !== undefined && host.inputTokens > actual.max_switch_prefill_tokens) { proposal = pin; reason = "prefill_bound"; }
|
|
49
|
+
else reason = "user_turn";
|
|
50
|
+
if (!host.fits(proposal)) {
|
|
51
|
+
const other = proposal === "capable" ? "efficient" : "capable";
|
|
52
|
+
if (!host.fits(other)) throw new Error("no stage backend fits the model input");
|
|
53
|
+
proposal = other; reason = "context_fit";
|
|
54
|
+
}
|
|
55
|
+
trace.staySwitch = actual.stay_switch; trace.plan = !pin || pin === proposal ? "stay" : "switch"; trace.reason = reason;
|
|
56
|
+
const tier = actual.stay_switch === "enforce" ? proposal : fallback.tier;
|
|
57
|
+
return { tier, pin: tier, trace };
|
|
58
|
+
}
|