@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.
- package/CHANGELOG.md +43 -0
- package/README.md +25 -4
- package/THIRD_PARTY_NOTICES.md +0 -18
- package/docs/agent-notes/README.md +71 -1
- package/docs/agent-notes/adapters.md +5 -2
- package/docs/agent-notes/bus.md +1 -0
- package/docs/agent-notes/daemon.md +7 -6
- package/docs/agent-notes/local-worker.md +1 -0
- package/docs/agent-notes/models.md +5 -3
- package/docs/agent-notes/tasks.md +9 -2
- package/docs/agent-notes/tests.md +1 -1
- package/docs/contracts/companion-cli-v1.json +70 -0
- package/docs/design/adapters.md +115 -2
- package/docs/design/agent-hub-architecture.md +10 -2
- 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/guidance-probes.md +802 -0
- package/docs/design/model-routes.md +1053 -0
- package/docs/design/supervision.md +121 -0
- package/docs/design/task-board.md +111 -0
- package/docs/dogfood.md +24 -15
- package/docs/events.md +20 -1
- package/docs/memory.md +3 -3
- package/docs/operations.md +366 -133
- package/docs/profiles.md +2 -2
- package/docs/quickstart.md +114 -3
- package/docs/research.md +5 -3
- package/docs/sdlc.md +113 -7
- package/docs/security.md +88 -6
- package/docs/specs/2026-09-19-agent-hub-design.md +14 -11
- package/docs/specs/2026-10-04-switchyard-source-port-design.md +3 -1
- package/docs/verification/2026-10-25-qwen-dual-output-t0.md +22 -0
- package/docs/verification/2026-11-08-qwen-0269-model-setter-1317.md +25 -11
- package/docs/verification/2026-11-09-qwen-0270-acp.md +181 -0
- package/docs/verification/2026-11-09-qwen-0270-model-setter-1317.md +61 -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/2026-11-11-0.37.0.md +40 -0
- package/docs/verification/2026-11-11-guidance-probe-t2-1226.md +153 -0
- package/docs/verification/2026-11-11-qwen-setter-suggestions-off.md +167 -0
- package/docs/verification/claude-shell-wrapper-native.py +1 -1
- package/docs/verified.json +27 -27
- package/package.json +3 -4
- package/plugins/agent-hub/.claude-plugin/plugin.json +1 -1
- package/plugins/agent-hub/kimi-hook.js +3570 -1800
- package/plugins/agent-hub/server.js +4112 -1913
- package/src/adapters/channel-peer.ts +7 -1
- package/src/adapters/claude-channel.ts +7 -4
- package/src/adapters/compat.ts +10 -10
- package/src/adapters/local-probe.ts +174 -0
- package/src/adapters/local-worker.ts +233 -22
- package/src/adapters/qwen-dual.ts +324 -44
- package/src/cli/console-state.ts +25 -6
- package/src/cli/console-versions.ts +99 -0
- package/src/cli/console.ts +13 -1
- package/src/cli/guidance.ts +67 -0
- package/src/cli/help.ts +12 -4
- 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/install-paths.ts +7 -2
- package/src/cli/lineage.ts +78 -0
- package/src/cli/main.ts +171 -14
- package/src/cli/runtime-version-warning.ts +2 -2
- package/src/cli/sdlc-output.ts +9 -5
- 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 +6 -3
- package/src/hub/config-trust.ts +7 -1
- package/src/hub/control-client.ts +5 -2
- package/src/hub/daemon.ts +508 -26
- 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/events.ts +3 -2
- 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-probe-store.ts +713 -0
- package/src/hub/guidance-probes.ts +358 -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/inference.ts +18 -5
- package/src/hub/manager.ts +44 -2
- package/src/hub/memory-policy.ts +2 -2
- package/src/hub/operational-authority.ts +13 -1
- package/src/hub/peers.ts +6 -1
- package/src/hub/planning.ts +1 -1
- package/src/hub/ports.ts +1 -1
- package/src/hub/progress.ts +47 -23
- package/src/hub/report.ts +2 -0
- package/src/hub/research.ts +1 -0
- package/src/hub/restart.ts +20 -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-authorization.ts +139 -17
- package/src/hub/sdlc-release-policy.ts +100 -0
- package/src/hub/sdlc-release.ts +60 -8
- 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 +917 -53
- package/src/local/probe-errors.ts +28 -0
- package/src/local/probe-sandbox.ts +224 -0
- package/src/local/probe-types.ts +108 -0
- package/src/local/probe-workspace.ts +237 -0
- package/src/local/sandbox.ts +71 -2
- package/src/local/tools.ts +135 -9
- package/src/memory/capture.ts +2 -2
- package/src/models/relay.ts +9 -2
- package/src/models/route/advisor-trigger.ts +88 -0
- package/src/models/route/config.ts +39 -8
- package/src/models/route/conversation-view.ts +179 -0
- package/src/models/route/decision-evidence.ts +1 -1
- package/src/models/route/decision.ts +193 -26
- package/src/models/route/escalation-control.ts +30 -0
- package/src/models/route/hub-prompts.ts +97 -0
- package/src/models/route/judge-choice.ts +155 -0
- package/src/models/route/judge-replies.ts +102 -0
- package/src/models/route/labels.ts +14 -70
- package/src/models/route/observation-signals.ts +250 -0
- package/src/models/route/plan-execute-choice.ts +27 -0
- package/src/models/route/relay-selector.ts +10 -9
- package/src/models/route/runtime.ts +129 -60
- 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/models/route/turn-state.ts +77 -0
- package/src/omniroute/client.ts +3 -0
- 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 +141 -27
- package/src/version.ts +4 -0
- package/templates/adec/README.md +32 -0
- package/templates/adec/ahub.plan-execute.json +23 -0
- package/templates/adec/ahub.stage.json +23 -0
- package/LICENSES/Apache-2.0.txt +0 -204
- package/src/models/route/advisor.ts +0 -102
- package/src/models/route/escalation.ts +0 -82
- package/src/models/route/judge.ts +0 -23
- package/src/models/route/normalize.ts +0 -103
- package/src/models/route/plan-execute.ts +0 -52
- package/src/models/route/prompts.ts +0 -8
- package/src/models/route/signals.ts +0 -247
- package/src/models/route/state.ts +0 -54
- package/src/models/route/text.ts +0 -61
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import type { ModelBackend, ModelRelayOptions, RelayRequest } from "../relay.ts";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
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
|
+
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
|
|
21
|
+
private readonly states = new ScopeStore<AutoState>({ maxEntries: 512, ttlMs: 60 * 60_000 });
|
|
22
22
|
|
|
23
23
|
constructor(
|
|
24
24
|
private readonly options: RelaySelectorOptions,
|
|
@@ -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";
|
|
@@ -1,22 +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 {
|
|
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, turnKind } from "./signals.ts";
|
|
8
9
|
import { RouteLabelTracker, type RouteLabelEvent, type RouteTurnContext, type RouteTurnOutcome } from "./labels.ts";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
10
|
+
import { captureStageInput, estimateStageInputTokens } from "./stage-input.ts";
|
|
11
|
+
import { buildStageEvidence, type CodingAgentDimensions, type StageEvidence } from "./stage-evidence.ts";
|
|
12
|
+
import { selectFallbackStage, planStageSwitch, ambiguousStage, type FallbackStageState, type StaySwitchPolicy, type StageSwitchTrace as SwitchTrace, type StageTier as Tier } from "./stage-fallback.ts";
|
|
13
|
+
import { EscalationControl } from "./escalation-control.ts";
|
|
14
|
+
import { ScopeStore } from "./turn-state.ts";
|
|
15
|
+
import { PlanPhase } from "./plan-execute-choice.ts";
|
|
13
16
|
|
|
14
17
|
export interface RouteEvent extends Partial<SwitchTrace>, Partial<DecisionTrace> {
|
|
18
|
+
decisionTarget?: "judge";
|
|
15
19
|
route: string; tier: string; source: "override" | "dimensions" | "hold" | "classifier" | "default" | "decision"; score: number; ms: number;
|
|
16
20
|
decision?: string; turn?: string; task?: number; pii?: boolean; severity?: number; spinning?: number; exploring?: number; production?: number;
|
|
17
21
|
}
|
|
18
22
|
export interface AdvisorEvent { route: string; trigger: string; verdict: "approve" | "redo" | "failed"; discardedChars: number }
|
|
19
|
-
interface RouteState { fingerprint: string; stage:
|
|
23
|
+
interface RouteState { fingerprint: string; stage: FallbackStageState; pin?: Tier; plan: PlanPhase; escalation: EscalationControl; advisor: AdvisorTrigger }
|
|
20
24
|
export interface RouteHost extends DecisionHost {
|
|
21
25
|
execute: (model: string, messages: ChatMessage[], judge: boolean, signal: AbortSignal, maxTokens?: number) => Promise<ChatResult>;
|
|
22
26
|
/** Read on every stage call (#197); absent is the shadow default. */
|
|
@@ -25,14 +29,16 @@ export interface RouteHost extends DecisionHost {
|
|
|
25
29
|
onRouteOutcome?: (event: RouteLabelEvent) => void;
|
|
26
30
|
onAdvisor?: (event: AdvisorEvent) => void;
|
|
27
31
|
}
|
|
32
|
+
/** Internal model-free proof only; no choice data or authority is exposed. */
|
|
33
|
+
export interface RouteProofPorts { choicePrepared?(ready: Promise<void>): void }
|
|
28
34
|
|
|
29
35
|
/** Transport stays in the host. Optional judge work has one deadline and five-minute failure backoff. */
|
|
30
36
|
export class HubRouteRuntime {
|
|
31
|
-
private readonly states = new
|
|
37
|
+
private readonly states = new ScopeStore<RouteState>();
|
|
32
38
|
private readonly labels: RouteLabelTracker;
|
|
33
39
|
private readonly decisions: DecisionRouteController;
|
|
34
40
|
private judgeOffUntil = 0;
|
|
35
|
-
constructor(private readonly host: RouteHost, private readonly judgeTimeoutMs = 8000) {
|
|
41
|
+
constructor(private readonly host: RouteHost, private readonly judgeTimeoutMs = 8000, private readonly proof?: RouteProofPorts) {
|
|
36
42
|
this.decisions = new DecisionRouteController(host, judgeTimeoutMs);
|
|
37
43
|
this.labels = new RouteLabelTracker(event => this.host.onRouteOutcome?.(event));
|
|
38
44
|
}
|
|
@@ -51,7 +57,7 @@ export class HubRouteRuntime {
|
|
|
51
57
|
const key = `${scope}:${route}`, fingerprint = JSON.stringify(config);
|
|
52
58
|
const prior = this.states.get(key);
|
|
53
59
|
if (prior?.fingerprint === fingerprint) return prior;
|
|
54
|
-
const value: RouteState = { fingerprint, stage: {
|
|
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 }) };
|
|
55
61
|
this.states.set(key, value); return value;
|
|
56
62
|
}
|
|
57
63
|
|
|
@@ -60,41 +66,63 @@ export class HubRouteRuntime {
|
|
|
60
66
|
const labelTurn = this.labels.captureTurn();
|
|
61
67
|
this.decisions.checkEntry(config, pii);
|
|
62
68
|
const started = performance.now(), state = this.state(route, config, scope);
|
|
63
|
-
const
|
|
64
|
-
const
|
|
69
|
+
const input = captureStageInput(messages) ?? { turn: "other" as const, incomplete: true, assistantTurns: 0, results: [] };
|
|
70
|
+
const evidence = buildStageEvidence(input), dimensions = evidence.dimensions;
|
|
65
71
|
const efficient = config.efficient ?? "fast", capable = config.capable ?? "coding";
|
|
66
72
|
let model = efficient, source: RouteEvent["source"] = "default", score = 0;
|
|
67
73
|
let sent = messages, trace: Partial<SwitchTrace> = {};
|
|
74
|
+
let phase: "planning" | "executing" | undefined;
|
|
68
75
|
if (config.type === "stage" || config.type === "decision") {
|
|
69
|
-
const decision =
|
|
76
|
+
const decision = selectFallbackStage(evidence, { confidenceThreshold: config.confidence_threshold, holdTurns: config.hold_turns }, state.stage);
|
|
70
77
|
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 });
|
|
78
|
+
// Public planner sizing is separate from local full-context admission. Sensitive size is omitted.
|
|
79
|
+
const staged = planStageSwitch(this.host.staySwitch?.(), state.pin, decision, input.turn, { inputTokens: pii ? undefined : estimateStageInputTokens(messages), fits: () => true });
|
|
76
80
|
state.pin = staged.pin;
|
|
77
81
|
const { prefillTokens, ...shape } = staged.trace;
|
|
78
82
|
trace = pii ? shape : staged.trace;
|
|
79
83
|
model = staged.tier === "capable" ? capable : efficient;
|
|
80
84
|
score = decision.score;
|
|
81
|
-
source = decision.source
|
|
85
|
+
source = decision.source;
|
|
86
|
+
if (config.type === "stage" && config.classifier === "decision" && ambiguousStage(decision, { confidenceThreshold: config.confidence_threshold, ambiguousBand: config.ambiguous_band })) {
|
|
87
|
+
// The band decides only whether adec is asked; the tier and model above stay exactly as the heuristic chose them.
|
|
88
|
+
trace = { ...trace, ...await this.decisions.shadowClassify(config, { route, scope, turn: labelTurn, messages, evidence, pii, signal, tier: staged.tier,
|
|
89
|
+
current: () => !signal.aborted && !labelTurn?.closed && this.labels.captureTurn() === labelTurn }) };
|
|
90
|
+
}
|
|
82
91
|
} else if (config.type === "plan_execute") {
|
|
83
|
-
const decision =
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
if (decision.
|
|
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];
|
|
87
96
|
} else if (config.type === "escalation" && state.escalation.snapshot().latched) model = capable;
|
|
88
|
-
const
|
|
89
|
-
|
|
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
|
+
}
|
|
90
115
|
const picked = this.decisions.confirm(proposed);
|
|
91
116
|
source = picked.trace ? "decision" : source;
|
|
92
117
|
let decisionId = this.emitRoute({ route, tier: model, source, score, ms: performance.now() - started, ...trace, ...picked?.trace }, labelTurn, dimensions, pii, messages);
|
|
93
118
|
const result = await this.host.execute(model, sent, false, signal);
|
|
119
|
+
phaseGuard?.("executor reply");
|
|
94
120
|
if (config.type !== "escalation" || state.escalation.snapshot().latched) return this.withDecision(result, decisionId);
|
|
95
|
-
const
|
|
96
|
-
const
|
|
97
|
-
const
|
|
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;
|
|
98
126
|
if (answer && !verdict) this.judgeOffUntil = Date.now() + 5 * 60_000;
|
|
99
127
|
const snapshot = state.escalation.apply(verdict, config.confirmations ?? 2);
|
|
100
128
|
if (snapshot.latched) { try { this.labels.setLatched(labelTurn, true); } catch { /* optional labels */ } }
|
|
@@ -107,24 +135,34 @@ export class HubRouteRuntime {
|
|
|
107
135
|
/** Reviews held no-tool responses. A redo is fed into the same local turn and bounded by its normal step cap. */
|
|
108
136
|
async review(route: string, config: HubRoute, messages: ChatMessage[], scope: string, pii: boolean, signal: AbortSignal, decisionId?: string): Promise<string | undefined> {
|
|
109
137
|
if (config.type !== "advisor") return undefined;
|
|
110
|
-
const
|
|
111
|
-
const
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
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"); }
|
|
121
159
|
}
|
|
122
160
|
|
|
123
161
|
private withDecision(result: ChatResult, decisionId: string | undefined): ChatResult {
|
|
124
162
|
return decisionId ? { ...result, routeDecision: decisionId } : result;
|
|
125
163
|
}
|
|
126
164
|
|
|
127
|
-
private emitRoute(event: RouteEvent, turn: ReturnType<RouteLabelTracker["captureTurn"]>, dimensions:
|
|
165
|
+
private emitRoute(event: RouteEvent, turn: ReturnType<RouteLabelTracker["captureTurn"]>, dimensions: CodingAgentDimensions, pii: boolean, priorMessages: ChatMessage[]): string | undefined {
|
|
128
166
|
if (turn && turn.closed) return undefined;
|
|
129
167
|
let decision: string | undefined;
|
|
130
168
|
try {
|
|
@@ -150,24 +188,55 @@ export class HubRouteRuntime {
|
|
|
150
188
|
return decision;
|
|
151
189
|
}
|
|
152
190
|
|
|
153
|
-
private async judge(model: string, messages: ChatMessage[], pii: boolean, parent: AbortSignal, maxTokens = 2048
|
|
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> {
|
|
154
193
|
if (parent.aborted || Date.now() < this.judgeOffUntil) return undefined;
|
|
155
|
-
const
|
|
156
|
-
const
|
|
157
|
-
parent.addEventListener("abort", abort, { once: true });
|
|
158
|
-
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
159
|
-
const work = async (): Promise<string | undefined> => {
|
|
160
|
-
if (pii && !(await this.host.onCampus())) return undefined;
|
|
161
|
-
if (controller.signal.aborted) return undefined;
|
|
162
|
-
const result = await this.host.execute(model, messages, true, controller.signal, maxTokens);
|
|
163
|
-
return result.message.content?.trim() || undefined;
|
|
164
|
-
};
|
|
194
|
+
const current = choice?.current ?? (() => !parent.aborted), guard = this.decisions.captureGuard(pii, current);
|
|
195
|
+
const began = performance.now(), deadline = began + this.judgeTimeoutMs;
|
|
165
196
|
try {
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
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
|
+
}
|
|
172
241
|
}
|
|
173
242
|
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/** Local bounded observation, deliberately separate from the whole forwarded wire. */
|
|
2
|
+
export type StageTurn = "user" | "tool_result" | "compaction" | "other";
|
|
3
|
+
export interface StageResultInput { text: string; error: boolean; family: "read" | "mutation" | "execution" | "other"; associated: boolean; assistantTurn?: number }
|
|
4
|
+
export interface StageInput { turn: StageTurn; incomplete: boolean; assistantTurns: number; results: StageResultInput[] }
|
|
5
|
+
const MESSAGE_LIMIT = 64, RESULT_LIMIT = 16, CALL_LIMIT = 32, PART_LIMIT = 32;
|
|
6
|
+
const TEXT_BYTES = 64 * 1024, ID_BYTES = 128, NAME_BYTES = 64;
|
|
7
|
+
|
|
8
|
+
/** Accessors are not part of a transport record; capture never invokes them. */
|
|
9
|
+
function field(value: unknown, key: string): unknown {
|
|
10
|
+
if (!value || typeof value !== "object") return undefined;
|
|
11
|
+
return Object.getOwnPropertyDescriptor(value, key)?.value;
|
|
12
|
+
}
|
|
13
|
+
function boundedString(value: unknown, bytes: number): string | undefined {
|
|
14
|
+
return typeof value === "string" && value.length <= bytes && Buffer.byteLength(value) <= bytes ? value : undefined;
|
|
15
|
+
}
|
|
16
|
+
function family(name: string | undefined): StageResultInput["family"] {
|
|
17
|
+
if (!name) return "other";
|
|
18
|
+
if (/^(bash|exec_command)$/i.test(name)) return "execution";
|
|
19
|
+
if (/^(read|read_file|readfile|glob|grep|search|list|ls|lookup)(_|$)/i.test(name)) return "read";
|
|
20
|
+
if (/^(write|write_file|edit|apply_patch|patch|delete|create|replace)(_|$)/i.test(name)) return "mutation";
|
|
21
|
+
return "other";
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function captureStageInput(source: unknown): StageInput | undefined {
|
|
25
|
+
try {
|
|
26
|
+
const messages = Array.isArray(source) ? source : field(source, "messages");
|
|
27
|
+
if (!Array.isArray(messages)) return undefined;
|
|
28
|
+
let incomplete = messages.length > MESSAGE_LIMIT, bytes = 0, parts = 0, inspectedCalls = 0;
|
|
29
|
+
const text = (value: unknown): string => {
|
|
30
|
+
if (typeof value === "string") {
|
|
31
|
+
if (value.length > TEXT_BYTES || bytes + Buffer.byteLength(value) > TEXT_BYTES) { incomplete = true; return ""; }
|
|
32
|
+
bytes += Buffer.byteLength(value); return value;
|
|
33
|
+
}
|
|
34
|
+
if (!Array.isArray(value)) return "";
|
|
35
|
+
const kept: string[] = [];
|
|
36
|
+
const available = PART_LIMIT - parts;
|
|
37
|
+
for (let index = 0; index < value.length && parts < PART_LIMIT; index++, parts++) {
|
|
38
|
+
const part = field(value, String(index));
|
|
39
|
+
if (field(part, "type") === "text" && typeof field(part, "text") === "string") kept.push(text(field(part, "text")));
|
|
40
|
+
}
|
|
41
|
+
if (value.length > available) incomplete = true;
|
|
42
|
+
return kept.join("\n");
|
|
43
|
+
};
|
|
44
|
+
const calls = new Map<string, { name?: string; index: number } | null>();
|
|
45
|
+
const observations: { id?: string; text: string; error: boolean; index: number }[] = [];
|
|
46
|
+
let turn: StageTurn = "other", assistantTurns = 0, turnCaptured = false;
|
|
47
|
+
for (let index = messages.length - 1; index >= Math.max(0, messages.length - MESSAGE_LIMIT); index--) {
|
|
48
|
+
const message = field(messages, String(index)), role = field(message, "role");
|
|
49
|
+
if (role === "system" || role === "developer") continue;
|
|
50
|
+
if (role !== "user" && role !== "assistant" && role !== "tool") {
|
|
51
|
+
incomplete = true;
|
|
52
|
+
if (!turnCaptured) { turnCaptured = true; turn = "other"; }
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
if (!turnCaptured) {
|
|
56
|
+
turnCaptured = true;
|
|
57
|
+
turn = role === "tool" ? "tool_result" : role === "user" ? "user" : "other";
|
|
58
|
+
if (role === "user") {
|
|
59
|
+
const latest = text(field(message, "content"));
|
|
60
|
+
if (/\b(compact(?:ed|ion)?|context summary|conversation summary)\b|continued[\s\S]*(?:previous conversation|ran out of context)/i.test(latest)) turn = "compaction";
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (role === "assistant") {
|
|
64
|
+
assistantTurns++;
|
|
65
|
+
const entries = field(message, "tool_calls");
|
|
66
|
+
if (Array.isArray(entries)) {
|
|
67
|
+
const availableCalls = CALL_LIMIT - inspectedCalls;
|
|
68
|
+
for (let at = entries.length - 1; at >= 0 && inspectedCalls < CALL_LIMIT; at--, inspectedCalls++) {
|
|
69
|
+
const call = field(entries, String(at));
|
|
70
|
+
const id = boundedString(field(call, "id"), ID_BYTES);
|
|
71
|
+
const name = boundedString(field(field(call, "function"), "name"), NAME_BYTES);
|
|
72
|
+
if (id) calls.set(id, calls.has(id) ? null : { name, index });
|
|
73
|
+
else incomplete = true;
|
|
74
|
+
}
|
|
75
|
+
if (entries.length > availableCalls) incomplete = true;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
if (role === "tool") {
|
|
79
|
+
if (observations.length === RESULT_LIMIT) { incomplete = true; continue; }
|
|
80
|
+
const id = boundedString(field(message, "tool_call_id"), ID_BYTES);
|
|
81
|
+
observations.push({ id, index, text: text(field(message, "content")), error: field(message, "is_error") === true || field(message, "isError") === true });
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
const resultIds = new Set<string>(), duplicates = new Set<string>();
|
|
85
|
+
for (const result of observations) if (result.id) { if (resultIds.has(result.id)) duplicates.add(result.id); resultIds.add(result.id); }
|
|
86
|
+
const results = observations.reverse().map(result => {
|
|
87
|
+
const call = result.id && !duplicates.has(result.id) ? calls.get(result.id) : undefined;
|
|
88
|
+
const associated = !!call && call.index < result.index;
|
|
89
|
+
return { text: result.text, error: result.error, family: associated ? family(call!.name) : "other" as const, associated, ...(associated ? { assistantTurn: call!.index } : {}) };
|
|
90
|
+
});
|
|
91
|
+
return { turn, incomplete, assistantTurns, results };
|
|
92
|
+
} catch { return undefined; }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Closed failure for numeric compatibility callers; never convert an unavailable size to zero. */
|
|
96
|
+
export class StageSizingUnavailableError extends Error {
|
|
97
|
+
constructor() { super("model input size is unavailable; provide bounded JSON messages and tool schemas"); }
|
|
98
|
+
}
|
|
99
|
+
const WIRE_BYTES = 2_000_000;
|
|
100
|
+
/** Whole-wire UTF-8 estimate. This is not the bounded stage evidence capture. */
|
|
101
|
+
export function estimateStageInputTokens(messages: readonly unknown[], tools?: readonly unknown[]): number | undefined {
|
|
102
|
+
try {
|
|
103
|
+
if (!Array.isArray(messages) || tools !== undefined && !Array.isArray(tools)) return undefined;
|
|
104
|
+
const envelope = { messages, ...(tools === undefined ? {} : { tools }) };
|
|
105
|
+
const active = new Set<object>();
|
|
106
|
+
let bytes = 0, inspected = 0;
|
|
107
|
+
const append = (part: string): void => {
|
|
108
|
+
bytes += Buffer.byteLength(part);
|
|
109
|
+
if (bytes > WIRE_BYTES) throw new StageSizingUnavailableError();
|
|
110
|
+
};
|
|
111
|
+
const encode = (value: unknown, depth: number): void => {
|
|
112
|
+
if (++inspected > WIRE_BYTES || depth > 128) throw new StageSizingUnavailableError();
|
|
113
|
+
if (value === null || typeof value === "boolean") { append(String(value)); return; }
|
|
114
|
+
if (typeof value === "string") {
|
|
115
|
+
if (value.length > WIRE_BYTES) throw new StageSizingUnavailableError();
|
|
116
|
+
append(JSON.stringify(value)); return;
|
|
117
|
+
}
|
|
118
|
+
if (typeof value === "number" && Number.isFinite(value)) { append(JSON.stringify(value)); return; }
|
|
119
|
+
if (!value || typeof value !== "object" || active.has(value)) throw new StageSizingUnavailableError();
|
|
120
|
+
const array = Array.isArray(value);
|
|
121
|
+
if (!array && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) throw new StageSizingUnavailableError();
|
|
122
|
+
if (Object.getOwnPropertyDescriptor(value, "toJSON")) throw new StageSizingUnavailableError();
|
|
123
|
+
active.add(value);
|
|
124
|
+
try {
|
|
125
|
+
append(array ? "[" : "{");
|
|
126
|
+
let count = 0;
|
|
127
|
+
const keys = array ? undefined : Object.keys(value);
|
|
128
|
+
const length = Array.isArray(value) ? value.length : keys!.length;
|
|
129
|
+
if (length > WIRE_BYTES) throw new StageSizingUnavailableError();
|
|
130
|
+
for (let index = 0; index < length; index++) {
|
|
131
|
+
const key = array ? String(index) : keys![index]!;
|
|
132
|
+
const descriptor = Object.getOwnPropertyDescriptor(value, key);
|
|
133
|
+
if (descriptor && !("value" in descriptor)) throw new StageSizingUnavailableError();
|
|
134
|
+
const item: unknown = descriptor?.value;
|
|
135
|
+
if (!array && item === undefined) continue;
|
|
136
|
+
if (count++) append(",");
|
|
137
|
+
if (!array) {
|
|
138
|
+
if (key.length > WIRE_BYTES) throw new StageSizingUnavailableError();
|
|
139
|
+
append(JSON.stringify(key)); append(":");
|
|
140
|
+
}
|
|
141
|
+
encode(item === undefined ? null : item, depth + 1);
|
|
142
|
+
}
|
|
143
|
+
append(array ? "]" : "}");
|
|
144
|
+
} finally { active.delete(value); }
|
|
145
|
+
};
|
|
146
|
+
encode(envelope, 0);
|
|
147
|
+
const estimate = Math.ceil(bytes / 4);
|
|
148
|
+
return Number.isSafeInteger(estimate) ? estimate : undefined;
|
|
149
|
+
} catch { return undefined; }
|
|
150
|
+
}
|
|
151
|
+
export function estimateInputTokens(messages: readonly unknown[], tools?: readonly unknown[]): number {
|
|
152
|
+
const estimate = estimateStageInputTokens(messages, tools);
|
|
153
|
+
if (estimate === undefined) throw new StageSizingUnavailableError();
|
|
154
|
+
return estimate;
|
|
155
|
+
}
|