agentcompass 0.2.0: route on AgentCompass v0.6.0 (#1083)

agentcompass routes on the AgentCompass v0.6.0 engine: four capability
categories, quota-economy seat ordering and data gates. With no caller
profile, a request keeps the model the client asked for. External
scoring stays off unless allowExternalScorer and a scorer base URL are
both set. The reference ships in the package. This supersedes #791.

Run at 52a98632, merged onto main, on WSL (Ubuntu 24.04) with
HOME=$(mktemp -d):
- npm test in packages/agentcompass: 140 pass, 0 fail
- bun scripts/check.mjs agentcompass: ok
- Read the diff for new I/O: src/ has no fetch outside the opt-in
  scorer, and no spawn, env read or disk access.
- The docs' scorer example was checked against scorerOptionsOf and
  resolveClassifier.

Not tried: a real Magpie gateway routing live traffic through it.

Co-authored-by: akiiwa-games <akiiwa-games@users.noreply.github.com>
This commit is contained in:
Akiiwa
2026-11-13 17:14:25 +08:00
committed by GitHub
co-authored by akiiwa-games
parent 319b0a6459
commit c4e9c1099e
36 changed files with 18944 additions and 7260 deletions
+141 -160
View File
@@ -11,14 +11,29 @@
*/
import {
DEFAULT_MODELS,
DEFAULT_SCORING_POLICY,
DISPATCH_EFFORTS,
FAMILIES,
MODEL_ALIASES,
SCORING_POLICY as DEFAULT_SCORING_POLICY,
canonicalModel,
resolveModelSpec,
healthKey,
modelSpec,
resolveModel,
} from "./catalog.js";
import { defaultScoredModels } from "./axis-scores.js";
import { dispatchAllowedEfforts } from "./candidate-eval.js";
import { isModelQuotaExhausted } from "./quota.js";
/** The scored models a call reads (the host's own `options.models` when it gives some). */
const modelsOf = (options) => (options && options.models) || defaultScoredModels();
const aliasesOf = (options) => (options && options.aliases) || MODEL_ALIASES;
/** The row of a model a session runs on: its context window and whether the public data says it takes images. */
const specOf = (model, options) => modelSpec(model, modelsOf(options), aliasesOf(options), FAMILIES);
/** Whether the public data cites image input for this model (unknown is not yes: a turn that needs images routes again). */
const takesImages = (spec) => (((spec || {}).five_axis || {}).image_input || {}).status === "yes";
export const CACHE_WORTH_TOKENS = 1024;
export const CACHE_COLD_MS = 5 * 60 * 1000;
export const CHATGPT_CODEX_COLD_MS = 60 * 60 * 1000;
@@ -233,48 +248,6 @@ export function userSaidFromText(rawText) {
return stripAgentNoise(rawText);
}
/**
* Detect whether a user turn is a short conversational follow-up / continuation nudge
* (e.g. "继续", "好的", "按这个改", "continue", "ok go ahead", "lgtm", "do it").
*/
export function isShortFollowupMessage(text) {
if (!text || typeof text !== "string" || text.length > MAX_NOISE_STRIP_CHARS) return false;
const cleaned = stripAgentNoise(text).trim();
if (!cleaned || cleaned.length > 96) return false;
if (cleaned.includes("```") || cleaned.includes("\n\n")) return false;
const compact = cleaned
.toLowerCase()
.replace(/^[.!?,;:,。!?、;:'"`~()[\]{}\s-]+|[.!?,;:,。!?、;:'"`~()[\]{}\s-]+$/g, "")
.trim();
if (!compact) return false;
const exactPatterns = /^(继续|接着|接着写|接着做|往下|往下写|好的|好|行|可以|没问题|对|是的|没错|照做|按这个来|按这个改|按你说的做|就这么改|开始吧|动手吧|改吧|修吧|试一下|再试一次|确认|同意|再来|ok|okay|k|yes|yep|yeah|sure|continue|go on|keep going|proceed|do it|go ahead|sounds good|looks good|lgtm|ship it|fix it|apply it|try again|next|please continue|yes please|go for it|run it)$/i;
if (exactPatterns.test(compact)) return true;
const prefixPatterns = /^(继续|好的|好,|行,|可以,|没问题,|按这个|照这个|就按|ok[, ]|okay[, ]|yes[, ]|sure[, ]|please continue|go ahead and|continue with)/i;
const wordCount = compact.split(/\s+/).filter(Boolean).length;
if (prefixPatterns.test(compact) && compact.length <= 48 && wordCount <= 10) {
return true;
}
return false;
}
/**
* Detect whether the request is a context compaction / summarization turn (`/compact`).
*/
export function isCompactionText(text) {
if (!text || typeof text !== "string") return false;
const sample = text.length > MAX_USER_TURN_CHARS ? capTextSlice(text, MAX_USER_TURN_CHARS) : text;
return (
/(?:^|\s)\/compact(?:\s|$)/i.test(sample) ||
/<compact_instruction\b/i.test(sample) ||
/Provide a detailed summary of the conversation so far/i.test(sample) ||
/Summarize the conversation so far/i.test(sample) ||
/Your task is to create a detailed summary of the conversation/i.test(sample)
);
}
function extractPartText(part) {
if (!part) return "";
if (typeof part === "string") return part;
@@ -564,6 +537,44 @@ export function firstWords(body) {
return "";
}
/**
* The latest genuine user turns of the conversation the client resent, newest first:
* `{ index, stamp }`. `index` is the item's position, so the body cut after it is the
* request that turn began with; `stamp` names the turn (`<index>:<hash>`) and stays the same as
* the conversation grows, since history is only appended to. Scans back from the end and stops
* after `max` turns, so a long conversation costs no more than its last few turns.
*/
export function recentUserTurns(body, max = 6) {
const items = getNormalizedItems(body);
const turns = [];
for (let i = items.length - 1; i >= 0 && turns.length < max; i--) {
const item = items[i];
if (!item || typeof item !== "object" || String(item.role || "").toLowerCase() !== "user") {
continue;
}
const info = inspectMessageItem(item, { needFullText: true, needAssistantText: false });
if (!info.userSaid) continue;
turns.push({
index: i,
stamp: `${i}:${sha256Hex(info.userSaid.slice(0, MAX_FIRST_WORDS_HASH_CHARS)).slice(0, 16)}`,
});
}
return turns;
}
/**
* `body` as it was when the item at `index` was its last: the request that began that turn,
* for the router to decide again what that request was given.
*/
export function bodyUpTo(body, index) {
const cut = { ...body };
delete cut.estimated_input_tokens;
if (Array.isArray(body.messages)) cut.messages = body.messages.slice(0, index + 1);
else if (Array.isArray(body.input)) cut.input = body.input.slice(0, index + 1);
else if (Array.isArray(body.contents)) cut.contents = body.contents.slice(0, index + 1);
return cut;
}
function getHeaderCaseInsensitive(headers, name) {
if (!headers || typeof headers !== "object") return "";
const target = name.toLowerCase();
@@ -732,13 +743,6 @@ export function analyzeTurnState(body = {}, ctx = {}) {
within = true;
}
const isShortFollowup =
!within &&
Boolean(lastUserText) &&
(turn > 1 || Boolean(previousAssistantText) || Boolean(body?.previous_response_id)) &&
isShortFollowupMessage(lastUserText);
const isCompacting = isCompactionText(lastUserText);
const fw = firstUserSaid
? sha256Hex(firstUserSaid.slice(0, MAX_FIRST_WORDS_HASH_CHARS)).slice(0, 24)
: "";
@@ -755,8 +759,6 @@ export function analyzeTurnState(body = {}, ctx = {}) {
previousAssistantText,
hasAnyVisual,
hasCurrentTurnVisual,
isShortFollowup,
isCompacting,
firstWords: fw,
sessionKey: computeSessionKey(body, ctx, fw),
};
@@ -843,7 +845,6 @@ export function keepsEffort(
const prevTokens = Number(sessionState.tokens || 0);
const prevReqTokens = Number(sessionState.requestTokens || 0);
const compacted =
Boolean(options?.isCompacting) ||
(options?.hasExplicitEstimatedTokens &&
prevTokens >= CACHE_WORTH_TOKENS &&
currentTokens > 0 &&
@@ -853,39 +854,19 @@ export function keepsEffort(
currentTokens < prevReqTokens * COMPACTION_DROP_RATIO);
const isWarm =
!compacted &&
sessionState.ageKnown !== false &&
ageMs <= ttlMs &&
(sessionState.cached === true ||
prevTokens >= CACHE_WORTH_TOKENS ||
currentTokens >= CACHE_WORTH_TOKENS ||
options?.isShortFollowup === true);
currentTokens >= CACHE_WORTH_TOKENS);
if (!isWarm) {
return wantedEffort || "medium";
}
const { spec } = resolveModelSpec(sessionState.model, options.models, options.aliases);
return ratchetEffort(sessionState.effort, wantedEffort, spec?.efforts);
}
/**
* Detect whether a new user message clearly outgrows a lightweight tier model (`tier < 3.5`,
* e.g. `claude-haiku-5-5`, `gpt-6-luna`, `gemini-3.8-flash-high`, `deepseek-v4.1-flash-free`, `grok-4.7`)
* by requesting deep multi-module architecture, cross-runtime refactoring, or frontier debugging.
*/
export function detectTierEscalationOutgrowth(text, currentSpec) {
if (!text || !currentSpec || (currentSpec.tier ?? 3.5) >= 3.5) {
return false;
}
const cleaned = stripAgentNoise(text);
if (!cleaned || isShortFollowupMessage(cleaned)) {
return false;
}
const hasHighRiskSignals =
/architecture|trade-?off|consensus|distributed|cap theorem|zero-downtime|migration|root cause|deadlock|race condition|memory corruption|heisenbug|formal verification|security audit|cryptograph|multi-runtime|cross-module|重构|架构|死锁|并发|根因|全链路|跨模块|分布式/i.test(
cleaned
);
const isLongComplexPrompt = cleaned.length >= 260 && (cleaned.match(/\n/g) || []).length >= 3;
return hasHighRiskSignals || isLongComplexPrompt;
const fleet = { models: modelsOf(options), aliases: aliasesOf(options), families: FAMILIES, dispatch_efforts: DISPATCH_EFFORTS };
const allowed = dispatchAllowedEfforts({ provider: sessionState.provider || "", model: sessionState.model }, fleet, sessionState.model);
return ratchetEffort(sessionState.effort, wantedEffort, allowed || undefined);
}
/**
@@ -894,7 +875,6 @@ export function detectTierEscalationOutgrowth(text, currentSpec) {
*
* Hold reasons (`shouldHold: true`):
* - `"turn"`: mid-turn tool call / tool result loop (`within === true`)
* - `"followup"`: short user continuation nudge while session is active
* - `"cache"`: KV cache is worth holding (`>= 1024` tokens or `cached: true`) and still warm
* - `"session"`: `affinityMode === "session"` and model is healthy & within limits
* - `"strict"`: `affinityMode === "strict"` and model is healthy
@@ -905,12 +885,31 @@ export function detectTierEscalationOutgrowth(text, currentSpec) {
* - `"gone"`: current model is no longer in the candidate pool
* - `"worn"`: cumulative session tokens (`compactedTokens + tokens`) >= 2,000,000
* - `"outgrown"`: current token count exceeds 95% of the model's `context_window`
* - `"capability_outgrown"`: new turn requires visual/GUI/frontier capability the current model lacks
* - `"capability_outgrown"`: new turn needs image input (a screenshot, or computer use) the current model is not cited for
* - `"compacted"`: conversation was `/compact`-ed (token count dropped > 50%)
* - `"cold"`: KV cache TTL expired (`now - updatedAt > coldAfterMs`) or cache < 1024 tokens
* - `"cold"`: KV cache TTL expired (`now - updatedAt > coldAfterMs`) or cache < 1024 tokens, or the state has no
* age (`ageKnown: false`, decided again from the history), so no TTL-gated hold applies
* - `"turn_mode"`: `affinityMode === "turn"` and request is a new user turn (`within === false`)
* - `"off"`: `affinityMode === "off"`
*/
/**
* Whether the user now names something other than what the session runs (contract R3). A hold would hide that.
*/
function pinOverridesSession(sessionState, pins, options) {
if (!pins) return false;
if (pins.pinnedBundle && pins.pinnedBundle !== sessionState.pinnedBundle) return true;
let effort = pins.constraintEffort ? String(pins.constraintEffort).trim().toLowerCase() : null;
if (pins.constraintModel) {
const models = modelsOf(options);
const aliases = aliasesOf(options);
// Each row is its own model (contract R1): a session on a family row is not on the flagship it folds to, nor the other way round.
const running = healthKey(sessionState.target || sessionState.model, models, aliases);
if (healthKey(String(pins.constraintModel), models, aliases) !== running) return true;
effort = effort || resolveModel(String(pins.constraintModel), models, aliases).effort;
}
return Boolean(effort && effort !== sessionState.effort);
}
export function evaluateProviderContinuation(facts = {}, sessionState = null, options = {}) {
const now = Number.isFinite(options.now) ? Number(options.now) : Date.now();
const affinityMode = String(options.affinityMode || "cache").toLowerCase();
@@ -933,12 +932,8 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
};
}
const currentModel = canonicalModel(sessionState.model, options.aliases || MODEL_ALIASES);
const { spec } = resolveModelSpec(
currentModel,
options.models || DEFAULT_MODELS,
options.aliases || MODEL_ALIASES
);
const currentModel = canonicalModel(sessionState.model, aliasesOf(options), modelsOf(options));
const spec = specOf(currentModel, options);
// 1. Check 24h session retention expiry
const ageMs = Math.max(0, now - (sessionState.updatedAt || 0));
@@ -954,6 +949,17 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
};
}
if (pinOverridesSession(sessionState, options.pins, options)) {
return {
shouldHold: false,
why: "user_pin_override",
previousModel: currentModel,
previousEffort: sessionState.effort,
within: Boolean(facts.within),
turn: facts.turn || 1,
};
}
// 2. Check candidate pool membership (if candidate list is explicitly provided)
const candidateList = Array.isArray(options.availableModels)
? options.availableModels
@@ -961,10 +967,11 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
? facts.candidateModels
: [];
if (candidateList.length > 0) {
const canonicalCandidates = candidateList.map((m) =>
canonicalModel(typeof m === "string" ? m : m?.model || m?.id || "", options.aliases)
const running = healthKey(sessionState.target || sessionState.model, options.models, options.aliases);
const candidateKeys = candidateList.map((m) =>
healthKey(typeof m === "string" ? m : m?.model || m?.id || "", options.models, options.aliases)
);
if (!canonicalCandidates.includes(currentModel)) {
if (!candidateKeys.includes(running)) {
return {
shouldHold: false,
why: "gone",
@@ -977,21 +984,24 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
}
// 3. Check provider/model health
const runningName = sessionState.target || sessionState.model;
const failedModel = healthKey(runningName, options.models, options.aliases);
const unhealthySet = new Set(
(options.unhealthyModels || []).map((m) => canonicalModel(m, options.aliases))
(options.unhealthyModels || []).map((m) => healthKey(m, options.models, options.aliases))
);
const storeHealthy =
options.store && typeof options.store.isModelHealthy === "function"
? options.store.isModelHealthy(currentModel, now)
? options.store.isModelHealthy(runningName, now)
: true;
if (
sessionState.healthy === false ||
!storeHealthy ||
unhealthySet.has(currentModel)
unhealthySet.has(failedModel)
) {
return {
shouldHold: false,
why: "provider_unhealthy",
failedModel,
previousModel: currentModel,
previousEffort: sessionState.effort,
within: Boolean(facts.within),
@@ -1061,8 +1071,7 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
// 6. Check visual modality outgrowth (even mid-turn if a tool returned a screenshot to a blind model)
const needsVisual = Boolean(facts.hasCurrentTurnVisual || facts.hasVisual);
const modelHasVisual =
spec?.visual !== false && Number(spec?.capabilities?.visual ?? spec?.visual ?? 0) > 0;
const modelHasVisual = takesImages(spec);
if (affinityMode !== "strict" && needsVisual && !modelHasVisual) {
return {
shouldHold: false,
@@ -1103,11 +1112,7 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
}
// GUI / computer-use capability outgrowth on a new user turn
if (
affinityMode !== "strict" &&
facts.hasComputerUse &&
Number(spec?.capabilities?.gui ?? 0) < 0.5
) {
if (affinityMode !== "strict" && facts.hasComputerUse && !modelHasVisual) {
return {
shouldHold: false,
why: "capability_outgrown",
@@ -1119,25 +1124,7 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
};
}
// Tier escalation outgrowth: lightweight model (`tier < 3.5`) hit with a frontier/coupled task
if (
affinityMode !== "strict" &&
affinityMode !== "session" &&
(facts.demandsFrontierEscalation ||
detectTierEscalationOutgrowth(facts.turnText || facts.lastUserText || "", spec))
) {
return {
shouldHold: false,
why: "capability_outgrown",
reasonDetail: "tier_escalation_required",
previousModel: currentModel,
previousEffort: sessionState.effort,
within: false,
turn: facts.turn || 1,
};
}
// Check context compaction (`/compact` or request token drop > 50% from warm state)
// Check context compaction (request token drop > 50% from warm state)
const prevReqTokens = Number(sessionState.requestTokens || 0);
const tokenDroppedByHalf =
(facts.hasExplicitEstimatedTokens &&
@@ -1150,7 +1137,7 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
if (
affinityMode !== "strict" &&
affinityMode !== "session" &&
(facts.isCompacting || tokenDroppedByHalf)
tokenDroppedByHalf
) {
return {
shouldHold: false,
@@ -1180,22 +1167,9 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
...sessionState,
...options,
});
const withinCacheTtl = ageMs <= ttlMs;
// Short follow-up nudge ("继续", "ok go ahead", "lgtm") while session is still within TTL
if (facts.isShortFollowup && withinCacheTtl) {
return {
shouldHold: true,
why: "followup",
model: currentModel,
effort: sessionState.effort || "high",
provider: sessionState.provider || "",
previousModel: currentModel,
previousEffort: sessionState.effort || "high",
within: false,
turn: facts.turn || sessionState.turn || 1,
};
}
// A state decided again from the history (`ageKnown: false`) has no age, so it is never within a TTL
const ageKnown = sessionState.ageKnown !== false;
const withinCacheTtl = ageKnown && ageMs <= ttlMs;
// Warm KV cache hold (`tokens >= 1024` or `cached === true` within TTL)
const cacheWorthHolding =
@@ -1222,7 +1196,7 @@ export function evaluateProviderContinuation(facts = {}, sessionState = null, op
why: "cold",
previousModel: currentModel,
previousEffort: sessionState.effort,
ageMs,
ageMs: ageKnown ? ageMs : null,
ttlMs,
within: false,
turn: facts.turn || 1,
@@ -1252,7 +1226,7 @@ export class SessionContinuityStore {
}
}
get(sessionKey, now = Date.now()) {
get(sessionKey, now = Date.now(), { keepExpired = false } = {}) {
if (!sessionKey) return null;
let resolvedKey = sessionKey;
let state = this.sessions.get(resolvedKey);
@@ -1267,7 +1241,7 @@ export class SessionContinuityStore {
if (!state) return null;
if (state.updatedAt && now - state.updatedAt > STICK_KEEP_MS) {
this.sessions.delete(resolvedKey);
return null;
return keepExpired ? state : null;
}
return state;
}
@@ -1316,7 +1290,6 @@ export class SessionContinuityStore {
const prevReqTokens = Number(existing?.requestTokens || 0);
const dropped =
Boolean(facts.isCompacting) ||
(facts.hasExplicitEstimatedTokens &&
prevTokens >= CACHE_WORTH_TOKENS &&
estTokens > 0 &&
@@ -1348,6 +1321,8 @@ export class SessionContinuityStore {
sessionKey,
{
model: decision.model || existing?.model || "",
// `target` keeps the model as routed (`upstream/claude-opus-5-5`); `set` stores `model` canonical
target: decision.model || existing?.target || "",
effort: decision.effort || existing?.effort || "medium",
provider: decision.provider ?? existing?.provider ?? "",
workKind: decision.workKind || existing?.workKind || "general_implementation",
@@ -1358,8 +1333,12 @@ export class SessionContinuityStore {
cached,
healthy: true,
turn: facts.turn || existing?.turn || 1,
anchor: decision.anchor ?? existing?.anchor ?? "",
lastWhy: decision.why || "first",
lastHeld: Boolean(decision.held),
// What a later provider route of a held turn profiles with, and which pin the session is on.
profile: decision.profile ?? existing?.profile ?? null,
pinnedBundle: decision.pinnedBundle ?? existing?.pinnedBundle ?? null,
},
now
);
@@ -1383,11 +1362,12 @@ export class SessionContinuityStore {
const targetModel = canonicalModel(
ctx?.model || existing?.model || reply?.model || ""
);
const ranModel = healthKey(ctx?.model || existing?.target || existing?.model || reply?.model || "");
if (isError) {
if (targetModel) {
if (ranModel) {
this.markModelUnhealthy(
targetModel,
ranModel,
ctx?.error || reply?.error?.message || `http_${status || "error"}`,
now
);
@@ -1434,8 +1414,8 @@ export class SessionContinuityStore {
);
const totalContext = inputTokens + cacheReadTokens + cacheWriteTokens + outputTokens;
if (targetModel) {
this.markModelHealthy(targetModel);
if (ranModel) {
this.markModelHealthy(ranModel);
}
if (!key) return null;
@@ -1470,22 +1450,23 @@ export class SessionContinuityStore {
row.conversation_id ||
this.lastActiveSessionKey;
const targetModel = canonicalModel(row.model || row.request_model || "");
const ranModel = healthKey(row.model || row.request_model || "");
const isRejected =
row.rejected === true ||
Boolean(row.error) ||
(Number(row.status) >= 400 && Number(row.status) < 600);
if (isRejected) {
if (targetModel) {
if (ranModel) {
this.markModelUnhealthy(
targetModel,
ranModel,
row.error || row.reject_reason || `status_${row.status || "rejected"}`,
now
);
}
if (key && this.sessions.has(key)) {
const existing = this.sessions.get(key);
if (!targetModel || existing.model === targetModel) {
if (!ranModel || healthKey(existing.target || existing.model) === ranModel) {
this.set(key, { ...existing, healthy: false }, now);
}
}
@@ -1525,34 +1506,34 @@ export class SessionContinuityStore {
}
markModelUnhealthy(model, reason = "unhealthy", now = Date.now(), cooldownMs = UNHEALTHY_COOLDOWN_MS) {
const canonical = canonicalModel(model);
if (!canonical) return;
this.modelHealth.set(canonical, {
const key = healthKey(model);
if (!key) return;
this.modelHealth.set(key, {
healthy: false,
reason: String(reason || "unhealthy"),
failedAt: now,
until: now + cooldownMs,
});
for (const [k, state] of this.sessions.entries()) {
if (state.model === canonical) {
if (healthKey(state.target || state.model) === key) {
this.sessions.set(k, { ...state, healthy: false });
}
}
}
markModelHealthy(model) {
const canonical = canonicalModel(model);
if (!canonical) return;
this.modelHealth.delete(canonical);
const key = healthKey(model);
if (!key) return;
this.modelHealth.delete(key);
}
isModelHealthy(model, now = Date.now()) {
const canonical = canonicalModel(model);
if (!canonical) return true;
const entry = this.modelHealth.get(canonical);
const key = healthKey(model);
if (!key) return true;
const entry = this.modelHealth.get(key);
if (!entry) return true;
if (entry.until && now > entry.until) {
this.modelHealth.delete(canonical);
this.modelHealth.delete(key);
return true;
}
return entry.healthy !== false;