Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(agents): der Hermes-Zweig waehlt Werkzeuge aus wie der native

Claudef9b2f0f87778
diff --git a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
index 00d82a5d..9bf39949 100644
--- a/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
+++ b/src/api/mcp/__tests__/tool-catalog-tokens.test.ts
@@ -74,11 +74,45 @@ const fullWire = () => JSON.stringify(wireTools(codingCatalog()))
*
* The ceilings carry ~4 percent of headroom for a wording fix; a new paragraph
* blows through them.
+ *
+ * ── 2.6.8: die Hintergrundagenten ──────────────────────────────────────────
+ * Zwei neue Werkzeuge (check_tasks, message_agent) haben BEIDE Deckel
+ * gerissen, und das Ergebnis war unterschiedlich, weil die Frage
+ * unterschiedlich ist:
+ *
+ * codierender Zug 8.444 -> wieder 7.418 Zeichen, Deckel BLEIBT 7.600
+ * voller Katalog 18.099 -> 17.711 Zeichen, Deckel STEIGT auf 17.750
+ *
+ * Der codierende Zug hat sich nicht durch Kuerzen erholt, sondern durch eine
+ * Korrektur: die beiden Werkzeuge sprechen UEBER eine Delegation, und
+ * delegate_task selbst faehrt auf einem gewoehnlichen Refactor laengst nicht
+ * mit (siehe den Test darueber). Sie stehen jetzt hinter demselben Tor
+ * (GATE_KEYWORDS in lib/tool-selection.ts), also kostet ein Zug ohne
+ * Delegation wieder genau so viel wie vorher. Dieser Deckel hat einen
+ * Entwurfsfehler gefunden, nicht nur eine Zahl.
+ *
+ * Der volle Katalog steigt wirklich: zwei Werkzeuge sind zwei Werkzeuge, und
+ * kein Tor der Welt macht sie im vollstaendigen Katalog unsichtbar. 388
+ * Zeichen davon sind durch Kuerzen der Beschreibungen zurueckgeholt; die
+ * uebrigen 711 sind der ehrliche Preis. Der Deckel steht auf dem GEMESSENEN
+ * Wert plus zwei Promille, nicht auf einem Wunsch.
+ *
+ * ── 2.6.8, zweiter Zug: delegate_task bekommt `model` ─────────────────────
+ * „glm 5.3 aktiv und der prompt sagt nutze 5 glm 5.2 agenten" — dafuer braucht
+ * das Werkzeug einen Modellparameter, den es nie hatte. Ein Schemafeld mit
+ * Beschreibung kostet:
+ *
+ * voller Katalog 17.711 -> 17.843 Zeichen (+132, nach Kuerzung der
+ * Beschreibung von 151 auf 93 Zeichen)
+ * codierender Zug unveraendert — delegate_task faehrt dort nicht mit
+ *
+ * Der codierende Zug ist der, den jeder Refactor bezahlt, und er bleibt
+ * gleich. Das ist der Grund, warum das Tor existiert.
*/
const CODING_CHAR_CEILING = 7600
const CODING_TOKEN_CEILING = 1730
-const FULL_CHAR_CEILING = 17000
-const FULL_TOKEN_CEILING = 3880
+const FULL_CHAR_CEILING = 17880
+const FULL_TOKEN_CEILING = 4090
describe('the coding step carries a catalog the diet actually shrank', () => {
it('the gate really is what a plain coding turn gets', () => {
diff --git a/src/hooks/__tests__/codex-create-tool-gate.test.ts b/src/hooks/__tests__/codex-create-tool-gate.test.ts
index 25f83d65..20e4ae51 100644
--- a/src/hooks/__tests__/codex-create-tool-gate.test.ts
+++ b/src/hooks/__tests__/codex-create-tool-gate.test.ts
@@ -65,9 +65,15 @@ describe('a plain coding turn does not carry the generators', () => {
// A6 widened the gate from the three generators to five: pr_resume and
// delegate_task shipped a schema on every step of every run that never
// mentions a PR or a fan-out.
+ //
+ // 2.6.8 macht sieben daraus: check_tasks und message_agent sprechen UEBER
+ // eine Delegation und gehoeren deshalb hinter dasselbe Tor wie sie. Ohne
+ // das kostete ein gewoehnlicher Refactor-Zug 844 Zeichen Katalogtext fuer
+ // zwei Werkzeuge, die auf ihm nichts zu tun haben — gefunden vom Deckel in
+ // tool-catalog-tokens.test.ts, nicht von einem Menschen.
const before = names(codingCatalog())
const after = names(gateCreateTools(codingCatalog(), 'fix the failing test in parser.ts'))
- expect(before.length - after.length).toBe(5)
+ expect(before.length - after.length).toBe(7)
expect(before.filter((n) => !after.includes(n)).sort()).toEqual([...GATE_OPENING_TOOLS].sort())
})
@@ -82,6 +88,17 @@ describe('a plain coding turn does not carry the generators', () => {
expect(out).not.toContain('image_generate')
})
+ it('ein Fan-out bringt die zwei Begleiter MIT, sonst waeren sie unerreichbar', () => {
+ // Die Kehrseite der Torentscheidung, und sie muss festgenagelt sein:
+ // haengt man check_tasks hinter ein Tor und vergisst, es zusammen mit
+ // delegate_task zu oeffnen, kann ein Agent zwar delegieren, aber nie
+ // nachsehen. Das waere schlimmer als der Katalogtext, den das Tor spart.
+ const out = names(gateCreateTools(codingCatalog(), 'delegate this and fan out'))
+ expect(out).toContain('delegate_task')
+ expect(out).toContain('check_tasks')
+ expect(out).toContain('message_agent')
+ })
+
it('a PR ask brings pr_resume back and nothing else', () => {
const out = names(gateCreateTools(codingCatalog(), 'continue the pull request from yesterday'))
expect(out).toContain('pr_resume')
@@ -230,12 +247,17 @@ describe('a run that discovers halfway through that it needs a picture', () => {
)
})
- it('isGatedTool names exactly the gated five, and nothing that always ships', () => {
- for (const n of [...CREATE_TOOLS, 'pr_resume', 'delegate_task']) expect(isGatedTool(n), n).toBe(true)
+ it('isGatedTool nennt genau die sieben Torwerkzeuge und nichts, was immer faehrt', () => {
+ // Seit 2.6.8 sieben: die drei Erzeuger, pr_resume, delegate_task und
+ // dessen zwei Begleiter. Die Liste steht hier ausgeschrieben und wird
+ // NICHT aus GATE_KEYWORDS abgeleitet — sonst pruefte sie eine Karte gegen
+ // sich selbst und waere fuer jeden kuenftigen Eintrag automatisch gruen.
+ const TOR = [...CREATE_TOOLS, 'pr_resume', 'delegate_task', 'check_tasks', 'message_agent']
+ for (const n of TOR) expect(isGatedTool(n), n).toBe(true)
for (const n of ['file_read', 'file_edit', 'shell_execute', 'todo_write', 'web_search']) {
expect(isGatedTool(n), n).toBe(false)
}
- expect([...GATE_OPENING_TOOLS].sort()).toEqual([...CREATE_TOOLS, 'pr_resume', 'delegate_task'].sort())
+ expect([...GATE_OPENING_TOOLS].sort()).toEqual([...TOR].sort())
})
it('a closed gate still tells the model the hatch is there', () => {
diff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.ts
index 56e0102b..f7431552 100644
--- a/src/hooks/useAgentChat.ts
+++ b/src/hooks/useAgentChat.ts
@@ -53,13 +53,24 @@ import { extractMemoriesFromPair } from './useMemory'
import { useAgentWorkflowStore } from '../stores/agentWorkflowStore'
import { WorkflowEngine } from '../lib/workflow-engine'
import type { AgentBlock, AgentToolCall } from '../types/agent-mode'
-import { selectRelevantToolsAsync, ALWAYS_INCLUDE, SMALL_MODEL_MAX_TOOLS } from '../lib/tool-selection'
+import { selectRelevantToolsAsync, toolSelectionOpts, ALWAYS_INCLUDE } from '../lib/tool-selection'
import { renderToolRoster, renderToolNames } from '../lib/tool-roster'
import { MUTATING_TOOLS, allowedInReadOnlyTurn } from '../lib/mutating-tools'
+import {
+ parseFanoutRequest,
+ resolveRequestedModel,
+ fanoutDirective,
+ unresolvedModelNote,
+} from '../lib/agent-fanout'
+import { setExplicitFanout } from '../api/agents/sub-agent'
+import { appendTaskReport } from '../lib/agent-task-report'
+import { useAgentTaskStore } from '../stores/agentTaskStore'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
import { beginRun, isRunStopped, stopRun } from '../lib/run-stop'
import { buildLoopRecheck, loopPassSaysDone } from '../lib/agent-commands'
+import { applyStoredCompaction } from '../lib/compact-summary'
+import { newestCompaction, maybeAutoCompact } from '../lib/run-compact-command'
import { generateEmbeddings } from '../api/rag'
import { truncateToolResult } from '../lib/truncate-tool-result'
import { toolCallCapMs, raceWithToolTimeout, SHELL_EXECUTE_DEFAULT_TIMEOUT_MS } from '../lib/tool-timeout'
@@ -217,6 +228,17 @@ export function useAgentChat() {
// router passes the task kind + the prior generation's exact args so a weak
// model that can't emit the call still gets the SAME media synthesized.
mediaHint?: { kind: 'image' | 'video'; args?: Record<string, unknown> }
+ /**
+ * Die Nutzernachricht dieses Zuges reist versteckt.
+ *
+ * Fuer den Weckzug eines fertigen Hintergrundagenten: ein Zug braucht
+ * eine Nutzernachricht, aber im Verlauf stuende sonst ein Satz, den der
+ * Mensch nie geschrieben hat. Der Nutzlastbau filtert `role:'system'`
+ * und NICHT `hidden` — die Zeile erreicht also das Modell und nicht das
+ * Auge. Denselben Weg nimmt schon die Werkzeugkette, die useCodex nach
+ * einem Lauf zurueckschreibt.
+ */
+ hiddenUser?: boolean
},
) => {
const { activeModel } = useModelStore.getState()
@@ -402,6 +424,7 @@ export function useAgentChat() {
content: userContent,
// Slash command: show "/commit" to the user, keep the expansion in content.
...(opts?.displayContent ? { displayContent: opts.displayContent } : {}),
+ ...(opts?.hiddenUser ? { hidden: true } : {}),
images: userImages,
timestamp: Date.now(),
}
@@ -491,12 +514,48 @@ export function useAgentChat() {
const toolMatchesCurated = (name: string) =>
(!curated || curated.includes(name)) && !(opts?.readOnly && !allowedInReadOnlyTurn(name))
- // Build agent system prompt FIRST, then append caveman style as a modifier
- const hermesToolDefs = toolRegistry.toHermesToolDefs(permissions)
- .filter((t) => toolMatchesCurated(t.name))
+ // ── Die Werkzeugliste fuer den Rueckfallweg ─────────────────────────────
+ //
+ // Hier stand `toolRegistry.toHermesToolDefs(permissions)` — also der ganze
+ // Katalog, nur nach Berechtigungen gefiltert. Der native Zweig weiter
+ // unten laesst dieselbe Menge durch `selectRelevantToolsAsync` laufen und
+ // deckelt unter Small-Model-Mode auf SMALL_MODEL_MAX_TOOLS; dieser Zweig
+ // tat beides nicht.
+ //
+ // Das war genau herum falsch. `hermes_xml` ist kein Weg, den man waehlt,
+ // sondern der RUECKFALL fuer Modelle, deren Template kein natives
+ // Werkzeug-Feld kann (agent-strategy.ts, applyLiveCapabilities). Die
+ // schwaechsten Modelle bekamen also die LAENGSTE Liste — und weil Hermes
+ // die Schemata nicht als `tools`-Feld auf die Leitung legen kann, sondern
+ // als Text in den Systemprompt schreibt, bezahlt jeder Zug sie voll.
+ //
+ // Gemessen am 02.09.2026: 17 Werkzeuge = 19.459 Zeichen ≈ 4.866 Token.
+ // smollm2:135m/360m melden Ollama kein `tools`, landen also hier, haben
+ // 8k Fenster und damit unter Small-Model-Mode ein Sendefenster von 4.096
+ // Token. Die Werkzeugliste ALLEIN war 119 % davon — die Anfrage konnte
+ // gar nicht passen, bevor eine Frage darin stand.
+ //
+ // Nur im hermes_xml-Fall berechnet: sonst zahlte jeder native Zug eine
+ // Einbettungsabfrage fuer eine Liste, die er nie benutzt.
+ const hermesToolDefs = strategy === 'hermes_xml'
+ ? await selectRelevantToolsAsync(
+ userContent,
+ toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),
+ permissions,
+ toolSelectionOpts(!!settings.smallModelMode, (texts) => generateEmbeddings(texts)),
+ )
+ : []
// Small-Model Mode (Knob 2): swap the ~3000-char agent prompt for a lean
- // ~750-char one on the native path. The Hermes-XML branch already uses a
- // tight tool prompt (buildHermesToolPrompt), so it stays as-is.
+ // ~750-char one on the native path. Der Hermes-Zweig behaelt seine eigene
+ // Anweisung — nicht weil sie kuerzer waere (sie ist es nicht: 1.112
+ // Zeichen wie ausgeliefert gegen ~750), sondern weil sie der PROTOKOLL-
+ // VERTRAG ist. In ihr steht, dass ein Aufruf als <tool_call>-Block kommt,
+ // und genau danach sucht parseHermesToolCalls. Tauscht man sie gegen die
+ // schlanke, ruft das Modell weiter Werkzeuge — nur erkennt sie niemand.
+ //
+ // Was diesen Zweig frueher gesprengt hat, war ohnehin nie die Huelle,
+ // sondern die LISTE darin: 18.347 der 19.459 Zeichen, also 94 %. Die zieht
+ // jetzt oben durch dieselbe Vorauswahl wie der native Zweig.
// Chat-Tools mode uses a conversational prompt (NOT the autonomous-agent
// one) so plain chat keeps its normal voice and only reaches for a tool
// when the user actually needs it.
@@ -559,11 +618,28 @@ export function useAgentChat() {
agentSystemPrompt += ragSuffix
agentSystemPrompt += `\n\n${hostClockLine()}`
+ // 2.6.8 auto-compact, once per user turn — deliberately outside the
+ // iteration loop below. Inside it, every step would re-ask and a long run
+ // would summarise itself again and again; the cooldown in
+ // shouldAutoCompact would catch it, but relying on a guard to undo a
+ // wrong call site is not the same as calling it in the right place.
+ if (useSettingsStore.getState().settings.autoCompactThreshold) {
+ await maybeAutoCompact({ conversationId: convId, activeModel })
+ }
+ const convForPayload =
+ useChatStore.getState().conversations.find((c) => c.id === convId) ?? conv
+
// Build messages array
let agentMessages: ChatMessage[] = [
...(agentSystemPrompt ? [{ role: 'system' as const, content: agentSystemPrompt }] : []),
- ...conv.messages
- .filter((m) => m.role !== 'system' && m.content.trim() !== '')
+ // 2.6.8: a recorded compaction stands in for everything up to its
+ // anchor. On the stored messages, before the wire map — the record's
+ // anchor is a message id, and the wire shape has none. See
+ // lib/run-compact-command.ts.
+ ...applyStoredCompaction(
+ convForPayload.messages.filter((m) => m.role !== 'system' && m.content.trim() !== ''),
+ newestCompaction(convForPayload.compactions),
+ ).messages
.map((m) => ({
role: m.role as 'user' | 'assistant' | 'tool',
content: m.role === 'user' && cavemanReminder
@@ -665,6 +741,40 @@ export function useAgentChat() {
agentMessages.push({ role: 'user', content: resume.text })
}
}
+ // ── „nutze 5 glm 5.2 agenten" ────────────────────────────────────────
+ //
+ // Ausdrueckliche Anweisung des Nutzers, deterministisch aus dem Text
+ // gelesen statt dem Modell ueberlassen. Der Grund steht in
+ // lib/agent-fanout.ts und ist gemessen: ein 4B-Modell antwortete auf
+ // „call delegate_task with background true" mit PROSA („Task ID: t12345")
+ // und rief nie ein Werkzeug. Eine genannte Zahl darf daran nicht
+ // scheitern.
+ //
+ // Als NUTZER-Material, wie jede andere Notiz in diesem Verlauf: eine
+ // System-Nachricht an anderer Stelle als Index 0 weisen strenge
+ // Jinja-Vorlagen ab, eine Werkzeugantwort braeuchte eine echte
+ // tool_call_id.
+ {
+ const wunsch = parseFanoutRequest(userContent)
+ if (wunsch) {
+ const modelle = useModelStore.getState().models
+ const treffer = wunsch.modelPhrase
+ ? resolveRequestedModel(wunsch.modelPhrase, modelle)
+ : null
+ const note = wunsch.modelPhrase && !treffer
+ ? unresolvedModelNote(wunsch.modelPhrase, modelle.map((m) => m.name))
+ : undefined
+ // Die Schranke folgt der Ansage. SUB_AGENT_MAX_PARALLEL (4) bremst
+ // eine Fan-out-Schleife des MODELLS; sagt der NUTZER „nutze 5", ist
+ // sie keine Sicherheitsgrenze mehr, sondern Bevormundung.
+ setExplicitFanout(convId, wunsch.count)
+ agentMessages.push({
+ role: 'user',
+ content: fanoutDirective(wunsch, treffer ? treffer.name : null, note),
+ })
+ }
+ }
+
// Seed the media intent from the router's continuation hint too (David
// 2026-06-20): "ok generiere jetzt" carries no noun, so detecting wants from
// the last message alone left wantsVideo=false and the synth fallback never
@@ -749,6 +859,16 @@ export function useAgentChat() {
// ── Agent Loop ──────────────────────────────────────────
while (runningRef.current && !abort.signal.aborted) {
stepNo++
+ // Fertige Hintergrundagenten melden sich hier, oben in der Iteration:
+ // vor dem Modellaufruf und nach den Werkzeugantworten der vorigen
+ // Runde. Als NUTZER-Material — die Begruendung steht in
+ // lib/agent-task-report.ts und ist dieselbe Regel, an der schon die
+ // Verdichtungsnotiz haengt.
+ appendTaskReport(
+ agentMessages,
+ () => useAgentTaskStore.getState().takeUnreported(convId),
+ Date.now(),
+ )
budget.addIteration()
const exceed = budget.exceeded()
if (exceed.kind !== 'none') {
@@ -925,13 +1045,15 @@ export function useAgentChat() {
// embedding router even on a modest catalog (threshold 6) so a 3B-8B
// model sees ≤6 semantically-ranked tools. Default mode keeps the
// permissive selection unchanged for big models.
+ // Die Zahlen dahinter stehen in `toolSelectionOpts`, nicht hier.
+ // Als sie hier standen, gab es sie nur an DIESER Stelle — der
+ // hermes_xml-Zweig oben nahm stattdessen den ganzen Katalog, und
+ // niemandem fiel es auf, weil nichts brach.
const relevantDefs = await selectRelevantToolsAsync(
lastUserMsg,
toolRegistry.getAll().filter((t) => toolMatchesCurated(t.name)),
permissions,
- settings.smallModelMode
- ? { embed: (texts) => generateEmbeddings(texts), topN: 5, embeddingThreshold: 6, maxTools: SMALL_MODEL_MAX_TOOLS }
- : { embed: (texts) => generateEmbeddings(texts) }
+ toolSelectionOpts(!!settings.smallModelMode, (texts) => generateEmbeddings(texts)),
)
const tools: ToolDefinition[] = relevantDefs.map(t => ({
type: 'function' as const,
diff --git a/src/hooks/useChat.ts b/src/hooks/useChat.ts
index f3658752..500913de 100644
--- a/src/hooks/useChat.ts
+++ b/src/hooks/useChat.ts
@@ -17,6 +17,8 @@ import { requestGenerationCancel } from "../api/vram-handoff"
import { effectiveContextWindow } from "../lib/context-window"
import { useAgentChat } from "./useAgentChat"
import { parseAgentCommand, parseLoopSpec } from '../lib/agent-commands'
+import { runCompactForConversation, compactOutcomeMessage, newestCompaction, maybeAutoCompact } from '../lib/run-compact-command'
+import { applyStoredCompaction } from '../lib/compact-summary'
import { planResend } from '../lib/resend-plan'
import { isOrphanRun } from '../lib/orphan-run'
import { applyGoalCommand } from '../lib/goal-command'
@@ -40,6 +42,7 @@ import { log } from "../lib/logger"
import { CREDITS_EXHAUSTED_MESSAGE } from '../lib/credits-exhausted'
import { shouldDowngradeThinking } from './codex/thinking-downgrade'
import { ProviderError } from '../api/providers/types'
+import { useBackgroundAgentWake } from './useBackgroundAgentWake'
/**
* Pull the most recent media generation (image/video) out of an assistant
@@ -89,8 +92,12 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
// the most multiplied surface in the app: one round sends the whole shared
// history to two to four models, so an uncapped group chat bills history
// level times N every time the user says anything. The budget is resolved per
- // model because the line-up can mix a 262k cloud model with a local one, and
- // a local one is not billed and stays exactly as it was.
+ // model because the line-up can mix a 262k cloud model with a local one: the
+ // paid member is held to the cost ceiling, the local one to 0.8 of its own
+ // window (2.6.8, Compact-Schritt 2). Neither is skipped any more — a local
+ // member with a small window was the one most likely to be silently
+ // truncated in a group round, because it carries the same shared history as
+ // the 262k model beside it.
const messages = applyChatSendBudget(
capMessageCount([
{ role: 'system' as const, content: groupSystemPrompt(model, allModels, personaPrompt) },
@@ -98,9 +105,10 @@ async function runGroupTurn(convId: string, model: string, allModels: string[],
]),
{
providerId,
- // Only asked where the answer can change something: resolving the window
- // is an /api/show round trip, and a local member of the line-up is not
- // capped at all.
+ // Only asked where the answer can change something — which, since the
+ // notaus is now the only thing that closes the gate, means: unless the
+ // user switched capping off. The lookup is cached per model, so a group
+ // round does not pay an /api/show per member per turn.
modelWindow: chatBudgetApplies(providerId, settings.contextDecay)
? await getModelMaxTokens(model)
: 0,
@@ -278,11 +286,24 @@ export function useChat() {
const { sendAgentMessage } = agentChat
const { extractAndSave } = useMemory()
+
// G29: a run outlives this hook instance when the chat view unmounts on a
// view switch, so the conversation's own flag is the only honest source for
// "is something still in flight here". Without it the composer showed Send
// next to a running clock and the user had no way to end the run.
const activeConversationId = useChatStore((s) => s.activeConversationId)
+
+ // Ein fertiger Hintergrundagent holt den Hauptagenten zurueck. Hier montiert
+ // und nicht in useAgentChat: `sendAgentMessage` entsteht dort, aber der Hook
+ // bekommt den Sendeweg von aussen, damit derselbe Hook auch den Codex-Weg
+ // bedienen kann. Er kostet nichts, solange es keine Hintergrundaufgaben
+ // gibt — `shouldWakeParent` faellt auf der ersten Bedingung heraus.
+ //
+ // NACH `activeConversationId`, weil der Hook die REAKTIVE Kennung braucht:
+ // ein `getState()` im Render liefert eine Momentaufnahme, und nach einem
+ // Gespraechswechsel weckte der Hook still das falsche Gespraech.
+ useBackgroundAgentWake(activeConversationId, sendAgentMessage)
+
const storeGenerating = useGenerationStore((s) => !!s.generating[activeConversationId ?? ''])
const orphanRun = isOrphanRun(storeGenerating, isGenerating, agentChat.isAgentRunning)
@@ -347,6 +368,59 @@ export function useChat() {
return
}
+ // /compact — BEFORE the agent delegation, because this one command is not
+ // an agent task. It belongs to the conversation, and both surfaces this
+ // hook serves (plain chat and agent mode) have one. Putting it after the
+ // delegation would have meant a second, identical branch inside
+ // useAgentChat for no reason; putting it before means the scope decides.
+ //
+ // The scope also does the refusing: in plain chat parseAgentCommand only
+ // recognises commands marked for it, so "/fix the login" stays literal
+ // text there instead of quietly becoming an agent instruction on a
+ // surface with no tools to carry it out.
+ {
+ const convId = store.activeConversationId
+ const agentOn = convId ? useAgentModeStore.getState().isActive(convId) : false
+ const cmd = parseAgentCommand(content, agentOn ? 'agent' : 'chat')
+ if (cmd?.command.name === 'compact') {
+ if (!convId) return
+ // BEIDE Zeilen sind App-Hinweise, keine Modell-Turns.
+ //
+ // Bis 2.6.8 standen sie als `role:'user'` und `role:'assistant'` im
+ // Verlauf — und die Nutzlast filtert nur `role:'system'`. Also fuhr
+ // ein erfundener Assistentenzug („Summarised 12 earlier messages …")
+ // in JEDE spaetere Anfrage mit, sass im geschuetzten Schwanz der
+ // letzten sechs Nachrichten und wurde bei der naechsten Verdichtung
+ // als Protokoll mitzusammengefasst. Das Modell las sich selbst dabei
+ // zu, wie es angeblich zusammengefasst hatte.
+ //
+ // In der Claude-Code-Desktop-App sind Schraegstrich-Befehle und ihre
+ // Ausgabe rein oertlich und erreichen das Modell nie. Der Mechanismus
+ // dafuer gibt es hier schon: `notice` auf einer System-Nachricht, von
+ // der Nutzlast verworfen, von der Ansicht als schlichte Zeile
+ // gezeigt. Er wurde nur nie benutzt.
+ store.addMessage(convId, {
+ id: uuid(), role: 'system', notice: 'info', content, timestamp: Date.now(),
+ })
+ // A placeholder first: writing the summary is a real round trip, and a
+ // composer that just goes quiet for ten seconds reads as a hang. The
+ // same reason the send path shows a streaming placeholder.
+ const noticeId = uuid()
+ store.addMessage(convId, {
+ id: noticeId, role: 'system', notice: 'info',
+ content: 'Summarising the earlier turns…', timestamp: Date.now(),
+ })
+ const outcome = await runCompactForConversation({
+ conversationId: convId,
+ activeModel,
+ trigger: 'manual',
+ focus: cmd.args || undefined,
+ })
+ useChatStore.getState().updateMessageContent(convId, noticeId, compactOutcomeMessage(outcome))
+ return
+ }
+ }
+
// Agent mode delegation: if active for this conversation, use agent chat.
//
// 2.5.9: slash commands work here too. They were Code-only, which meant the
@@ -585,12 +659,46 @@ export function useChat() {
// token budget while the count climbs past the LU Cloud proxy's
// 400-message gate — after which EVERY send 400s and the chat is a
// permanent dead end (yaserrieh, 2026-08-21).
- // Token budget (plan A4), on top of the count cap and only where a token
- // sent is a token billed. Plain chat rebuilt the ENTIRE history on every
- // send, so turn 60 of a long chat paid for turns 1 to 59 again just to ask
- // "and shorter please", and every attachment ever made rode along with it,
- // invisible to the token estimator the whole way. Local backends and the
- // contextDecay notaus get the untouched array, byte for byte.
+ // Token budget (plan A4), on top of the count cap. Plain chat rebuilt the
+ // ENTIRE history on every send, so turn 60 of a long chat paid for turns 1
+ // to 59 again just to ask "and shorter please", and every attachment ever
+ // made rode along with it, invisible to the token estimator the whole way.
+ //
+ // Since 2.6.8 this holds on a local backend too, at 0.8 of its own window
+ // instead of a cost ceiling — a local chat that outgrew its window used to
+ // be truncated by the model itself, from the front, without a word. Below
+ // 92% of the window (the A3 hysteresis on top of that 0.8) the payload is
+ // byte-identical to 2.6.7. The contextDecay notaus still returns every
+ // surface to the untouched array.
+ //
+ // The window is already resolved above for the memory budget, so this
+ // costs nothing extra on this path.
+ // 2.6.8 auto-compact, immediately before the payload is assembled.
+ //
+ // HERE and not earlier: the fill number this reads is "what the NEXT
+ // request will carry", and the user's message plus the assistant
+ // placeholder are already in the store by now, so it is measuring the
+ // request that is actually about to go out. Earlier would measure the
+ // previous turn; later would be after the budget already trimmed.
+ //
+ // Costs nothing when the opt-in was never taken — maybeAutoCompact reads
+ // the threshold first and returns on the cheap path.
+ if (settings.autoCompactThreshold) {
+ await maybeAutoCompact({
+ conversationId: convId,
+ activeModel,
+ window: modelWindowTokens,
+ // Plain chat resolves the window through getModelMaxTokens, which is
+ // the model's real trained context on Ollama and the catalogue value
+ // on cloud — not a fallback guess. Zero means the lookup failed, and
+ // shouldAutoCompact refuses a zero window outright.
+ windowIsTrue: modelWindowTokens > 0,
+ })
+ }
+ // Re-read: a compaction just wrote a record, and the payload below has to
+ // see it. The binding above was taken before the turn started.
+ const convNow = useChatStore.getState().conversations.find((c) => c.id === convId) ?? conv
+
const messages = applyChatSendBudget(
capMessageCount([
...(systemPrompt ? [{ role: "system" as const, content: systemPrompt }] : []),
@@ -602,8 +710,17 @@ export function useChat() {
// whatever index it happened to sit at, and a strict Jinja template
// answers a mid-conversation system message with "System message must
// be at the beginning" instead of a reply.
- ...conv.messages
- .filter((m) => m.role !== 'system' && m.content.trim() !== '')
+ // 2.6.8: a recorded compaction stands in for everything up to its
+ // anchor. Applied HERE — on the stored messages, before the wire map —
+ // for two reasons: the record's anchor is a message id and the wire
+ // shape does not carry one, and the filter above has to have run first
+ // so the anchor is looked up in the same array the payload is built
+ // from. A record whose anchor is gone applies nothing and the full
+ // history goes out, which is the honest answer to a stale record.
+ ...applyStoredCompaction(
+ convNow.messages.filter((m) => m.role !== 'system' && m.content.trim() !== ''),
+ newestCompaction(convNow.compactions),
+ ).messages
.map((m) => ({
role: m.role as 'user' | 'assistant' | 'tool',
content: m.role === 'user' && cavemanReminder
diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.ts
index 26b406eb..e6aa85cd 100644
--- a/src/hooks/useCodex.ts
+++ b/src/hooks/useCodex.ts
@@ -2,6 +2,8 @@ import { useRef, useState, useCallback } from 'react'
import { v4 as uuid } from 'uuid'
import { useCodexStore } from '../stores/codexStore'
import { useModelStore } from '../stores/modelStore'
+import { runCompactForConversation, compactOutcomeMessage, newestCompaction, maybeAutoCompact } from '../lib/run-compact-command'
+import { applyStoredCompaction } from '../lib/compact-summary'
import { useSettingsStore } from '../stores/settingsStore'
import { useChatStore, flushChatPersist } from '../stores/chatStore'
import { endTurnDurably } from '../stores/durability'
@@ -12,6 +14,15 @@ import { usePermissionStore } from '../stores/permissionStore'
import { toolStrategyFor } from '../lib/tool-support'
import { allowedInReadOnlyTurn } from '../lib/mutating-tools'
import { applyGoalCommand } from '../lib/goal-command'
+import {
+ parseFanoutRequest,
+ resolveRequestedModel,
+ fanoutDirective,
+ unresolvedModelNote,
+} from '../lib/agent-fanout'
+import { setExplicitFanout } from '../api/agents/sub-agent'
+import { appendTaskReport } from '../lib/agent-task-report'
+import { useAgentTaskStore } from '../stores/agentTaskStore'
import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'
import { useAgentLoopStore } from '../stores/agentLoopStore'
import { beginRun, isRunStopped, stopRun } from '../lib/run-stop'
@@ -249,6 +260,13 @@ export function useCodex() {
displayContent?: string
/** Set by the /loop driver when this run is pass 2 or later. */
loop?: { pass: number; intervalMs: number; task: string; startedAt: number }
+ /**
+ * Die Nutzernachricht dieses Zuges reist versteckt — siehe die
+ * gleichnamige Option in useAgentChat. Fuer den Weckzug eines fertigen
+ * Hintergrundagenten: der Zug braucht eine Nutzernachricht, aber im
+ * Verlauf stuende sonst ein Satz, den der Mensch nie geschrieben hat.
+ */
+ hiddenUser?: boolean
},
) => {
const { activeModel } = useModelStore.getState()
@@ -357,6 +375,35 @@ export function useCodex() {
// `/goal` is bookkeeping, not a prompt. Handle it here and show the result;
// every LATER turn picks the goal up from the system prompt below.
+ // /compact — a round trip, unlike /goal, but the same kind of branch: the
+ // hook does the work and nothing is sent to the model as an instruction.
+ // See lib/run-compact-command.ts for why it is a record and not an edit.
+ if (slash?.command.handledLocally && slash.command.name === 'compact') {
+ // BEIDE Zeilen sind App-Hinweise, keine Modell-Turns. Bis 2.6.8 standen
+ // sie als user/assistant im Verlauf, und die Nutzlast filtert nur
+ // `role:'system'` — also fuhr ein erfundener Assistentenzug
+ // („Summarised 12 earlier messages …") in jede spaetere Anfrage mit und
+ // wurde bei der naechsten Verdichtung als Protokoll mitzusammengefasst.
+ // In der Claude-Code-Desktop-App erreichen Schraegstrich-Befehle das
+ // Modell nie. Der Mechanismus dafuer gab es hier schon: `notice`.
+ useChatStore.getState().addMessage(convId, {
+ id: uuid(), role: 'system', notice: 'info', content: rawInstruction, timestamp: Date.now(),
+ })
+ const noticeId = uuid()
+ useChatStore.getState().addMessage(convId, {
+ id: noticeId, role: 'system', notice: 'info',
+ content: 'Summarising the earlier turns…', timestamp: Date.now(),
+ })
+ const outcome = await runCompactForConversation({
+ conversationId: convId,
+ activeModel: activeModel || '',
+ trigger: 'manual',
+ focus: slash.args || undefined,
+ })
+ useChatStore.getState().updateMessageContent(convId, noticeId, compactOutcomeMessage(outcome))
+ return
+ }
+
if (slash?.command.handledLocally && slash.command.name === 'goal') {
const res = applyGoalCommand(convId, slash.args)
useChatStore.getState().addMessage(convId, {
@@ -415,6 +462,7 @@ export function useCodex() {
useChatStore.getState().addMessage(convId, {
id: uuid(), role: 'user', content: instruction, timestamp: Date.now(),
...(displayInstruction ? { displayContent: displayInstruction } : {}),
+ ...(opts?.hiddenUser ? { hidden: true } : {}),
})
// Add empty assistant message. For a slash command, tag it so CodexView
@@ -640,11 +688,26 @@ export function useCodex() {
// comes back at exactly those bytes (decayRestoredToolResult is a pure
// function of the stored text), so a restore never re-cuts with a second
// budget and never moves the prefix.
+ // 2.6.8 auto-compact, once per user turn — outside the iteration loop for
+ // the same reason as in useAgentChat.
+ if (settings.autoCompactThreshold) {
+ await maybeAutoCompact({ conversationId: convId, activeModel })
+ }
+ const convForPayload =
+ useChatStore.getState().conversations.find(c => c.id === convId) ?? conv
+
const decayRestored = settings.contextDecay !== false
let messages: ChatMessage[] = [
{ role: 'system', content: systemPrompt },
- ...conv.messages
- .filter(m => m.role !== 'system' && (m.content.trim() || m.hidden))
+ // 2.6.8: a recorded compaction stands in for everything up to its
+ // anchor. Note the filter here keeps `hidden` turns (the agent's own
+ // tool chain) that the other two paths drop, so the anchor is looked up
+ // in exactly the array this payload is built from — which is the reason
+ // this call sits inside each builder rather than in a shared wrapper.
+ ...applyStoredCompaction(
+ convForPayload.messages.filter(m => m.role !== 'system' && (m.content.trim() || m.hidden)),
+ newestCompaction(convForPayload.compactions),
+ ).messages
.map(m => {
const msg: ChatMessage = {
role: m.role as 'user' | 'assistant' | 'tool',
@@ -685,6 +748,40 @@ export function useCodex() {
messages.push({ role: 'user', content: resume.text })
}
}
+ // ── „nutze 5 glm 5.2 agenten" ────────────────────────────────────────
+ //
+ // Ausdrueckliche Anweisung des Nutzers, deterministisch aus dem Text
+ // gelesen statt dem Modell ueberlassen. Der Grund steht in
+ // lib/agent-fanout.ts und ist gemessen: ein 4B-Modell antwortete auf
+ // „call delegate_task with background true" mit PROSA („Task ID: t12345")
+ // und rief nie ein Werkzeug. Eine genannte Zahl darf daran nicht
+ // scheitern.
+ //
+ // Als NUTZER-Material, wie jede andere Notiz in diesem Verlauf: eine
+ // System-Nachricht an anderer Stelle als Index 0 weisen strenge
+ // Jinja-Vorlagen ab, eine Werkzeugantwort braeuchte eine echte
+ // tool_call_id.
+ {
+ const wunsch = parseFanoutRequest(instruction)
+ if (wunsch) {
+ const modelle = useModelStore.getState().models
+ const treffer = wunsch.modelPhrase
+ ? resolveRequestedModel(wunsch.modelPhrase, modelle)
+ : null
+ const note = wunsch.modelPhrase && !treffer
+ ? unresolvedModelNote(wunsch.modelPhrase, modelle.map((m) => m.name))
+ : undefined
+ // Die Schranke folgt der Ansage. SUB_AGENT_MAX_PARALLEL (4) bremst
+ // eine Fan-out-Schleife des MODELLS; sagt der NUTZER „nutze 5", ist
+ // sie keine Sicherheitsgrenze mehr, sondern Bevormundung.
+ setExplicitFanout(convId, wunsch.count)
+ messages.push({
+ role: 'user',
+ content: fanoutDirective(wunsch, treffer ? treffer.name : null, note),
+ })
+ }
+ }
+
const messagesStartLen = messages.length
// Setup
@@ -900,6 +997,16 @@ export function useCodex() {
// backstop. Floor of 1 so a stray 0 setting can't zero the loop.
const MAX_CODEX_ITERATIONS = Math.max(settings.agentMaxIterations ?? 200, 1)
for (let i = 0; i < MAX_CODEX_ITERATIONS && runningRef.current && !abort.signal.aborted; i++) {
+ // Fertige Hintergrundagenten melden sich hier, oben in der Iteration:
+ // vor dem Modellaufruf und nach den Werkzeugantworten der vorigen
+ // Runde. Als NUTZER-Material — die Begruendung steht in
+ // lib/agent-task-report.ts und ist dieselbe Regel, an der schon die
+ // Verdichtungsnotiz haengt.
+ appendTaskReport(
+ messages,
+ () => useAgentTaskStore.getState().takeUnreported(convId!),
+ Date.now(),
+ )
budget.addIteration()
const bx = budget.exceeded()
if (bx.kind !== 'none') {
diff --git a/src/lib/__tests__/hermes-werkzeugauswahl.test.ts b/src/lib/__tests__/hermes-werkzeugauswahl.test.ts
new file mode 100644
index 00000000..e1a83d0b
--- /dev/null
+++ b/src/lib/__tests__/hermes-werkzeugauswahl.test.ts
@@ -0,0 +1,221 @@
+/**
+ * Der Hermes-Pfad wählt Werkzeuge wie der native — nicht anders.
+ *
+ * ── WORUM ES GEHT ──────────────────────────────────────────────────────────
+ *
+ * Es gibt zwei Wege, einem Modell zu sagen, welche Werkzeuge es hat:
+ *
+ * native Die Liste reist als eigenes Feld `tools` auf der Leitung.
+ * hermes_xml Das Modell kann dieses Feld nicht, also werden die JSON-
+ * Schemata als TEXT in den Systemprompt geschrieben.
+ *
+ * Der native Zweig sortiert vorher aus: `selectRelevantToolsAsync` nimmt, was
+ * zur Frage passt, und deckelt unter Small-Model-Mode auf
+ * SMALL_MODEL_MAX_TOOLS. Der Hermes-Zweig tat das bis 2026-09-02 NICHT — er
+ * nahm alles, was die Berechtigungen durchliessen.
+ *
+ * ── WARUM DAS GENAU HERUM FALSCH WAR ───────────────────────────────────────
+ *
+ * `hermes_xml` ist kein Weg, den man waehlt, sondern der RUECKFALL fuer
+ * Modelle, deren Template kein natives Werkzeug-Feld kann
+ * (agent-strategy.ts: `applyLiveCapabilities`). Das ist strukturell die
+ * SCHWAECHSTE Population — und die bekam die LAENGSTE Liste, waehrend die
+ * starken Modelle die kurze bekamen.
+ *
+ * Am 02.09.2026 auf der Entwicklermaschine nachgemessen:
+ *
+ * Katalog nach dem 2.6.6-Schnitt 17 Werkzeuge
+ * Hermes-Prompt daraus 19.459 Zeichen ≈ 4.866 Token
+ * davon die Werkzeugliste (<tools>) 18.347 Zeichen ← 94,3 %
+ * davon die Huelle (Anweisungstext) 1.112 Zeichen ← 5,7 %
+ *
+ * smollm2:135m / 360m melden Ollama nur `completion`, kein `tools`
+ * → hermes_xml. Trainiertes Fenster 8192, Sendefenster unter
+ * Small-Model-Mode min(8192 × 0,5, 6000) = 4.096 Token.
+ *
+ * 4.866 von 4.096 = 119 %. Die Werkzeugliste ALLEIN passte nicht ins
+ * Sendefenster, bevor ein einziges Wort Gespraech dazukam.
+ *
+ * ── WAS DIE FORSCHUNG DAZU SAGT ────────────────────────────────────────────
+ *
+ * Bei 4B–14B-Modellen bricht die Werkzeugtreffsicherheit oberhalb von etwa 15
+ * in den Prompt geschriebenen Schemata auf 0–49 % ein; retrieval-gestuetzte
+ * Vorauswahl hob sie in einer Messung von 13,6 % auf 43 %. Wir standen bei 17.
+ *
+ * ── DIE SORGE, DIE HIER MITGEPRUEFT WIRD ───────────────────────────────────
+ *
+ * Ein Deckel nimmt dem Modell Werkzeuge weg — kommt es dann nicht mehr ans
+ * siebte? Zwei Antworten, beide unten als Zusicherung:
+ *
+ * 1. Der native Zweig routet in JEDER Iteration auf dasselbe `userContent`
+ * (useAgentChat.ts:1007, ein nie neu belegter Funktionsparameter). Es
+ * gibt dort also gar keine "zweite Runde", in der nachjustiert wuerde.
+ * Der Deckel auf Hermes stellt Gleichstand her, statt etwas zu nehmen.
+ * 2. Wer ein Werkzeug woertlich beim Namen nennt, schiebt es am Deckel
+ * vorbei (`mentionedToolNames` → `pinned` in applyMaxTools).
+ *
+ * Lauf: npx vitest run src/lib/__tests__/hermes-werkzeugauswahl.test.ts
+ */
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve, dirname } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { toolRegistry, DEFAULT_PERMISSIONS, registerBuiltinTools } from '../../api/mcp'
+import { buildHermesToolPrompt } from '../../api/hermes-tool-calling'
+import {
+ selectRelevantToolsAsync,
+ toolSelectionOpts,
+ SMALL_MODEL_MAX_TOOLS,
+} from '../tool-selection'
+import { effectiveSendWindow } from '../send-window'
+import { estimateTokens } from '../context-compaction'
+
+const here = dirname(fileURLToPath(import.meta.url))
+const lies = (p: string) => readFileSync(resolve(here, '../..', p), 'utf8')
+
+/** Das kleinste Fenster, das ein Hermes-Modell hier real bekommt: smollm2, 8k. */
+const KLEINSTES_MODELLFENSTER = 8192
+
+const kleinstesSendefenster = () =>
+ effectiveSendWindow({
+ providerId: 'ollama',
+ modelWindow: KLEINSTES_MODELLFENSTER,
+ capEnabled: true,
+ smallModelMode: true,
+ })
+
+function katalog() {
+ registerBuiltinTools(toolRegistry)
+ return toolRegistry.getAll()
+}
+
+const FRAGE = 'count the ts files under src'
+
+describe('Der ungefilterte Katalog passt nicht — der Grund fuer diese Datei', () => {
+ it('die volle Liste sprengt das kleinste Hermes-Sendefenster', () => {
+ katalog()
+ // Diese Zusicherung behauptet NICHT, dass der Code das tut. Sie haelt die
+ // MESSUNG fest, aus der die Aenderung folgt: wer den Deckel spaeter wieder
+ // entfernt, kommt genau hier heraus und liest, warum es ihn gibt.
+ const voll = toolRegistry.toHermesToolDefs(DEFAULT_PERMISSIONS)
+ const prompt = buildHermesToolPrompt(voll)
+ const fenster = kleinstesSendefenster()
+
+ expect(voll.length).toBeGreaterThan(SMALL_MODEL_MAX_TOOLS)
+ expect(estimateTokens(prompt)).toBeGreaterThan(fenster)
+ })
+
+ it('die Huelle ist NICHT das Problem — sie ist ein Zwanzigstel', () => {
+ katalog()
+ // Der Kommentar, der die Auslassung bis 2026-09-02 begruendete, sagte:
+ // "The Hermes-XML branch already uses a tight tool prompt". Das stimmt und
+ // beantwortet die falsche Frage: eng ist die Anweisung drumherum, nicht
+ // die Liste darin.
+ //
+ // Gemessen wird die Huelle WIE AUSGELIEFERT — nicht `buildHermesToolPrompt([])`.
+ // Die leere Huelle sind 543 Zeichen, aber drei Absaetze darin haengen an
+ // `has(name)` (todo_write, web_search+web_fetch, file_edit) und entstehen
+ // erst mit den Werkzeugen. Wer die LEERE Huelle abzieht, schlaegt diese 569
+ // Zeichen der Liste zu und macht den Befund groesser, als er ist: 97,2 %
+ // statt der wahren 94,3 %. Der Befund traegt auch ohne diese Aufrundung.
+ const voll = toolRegistry.toHermesToolDefs(DEFAULT_PERMISSIONS)
+ const ganz = buildHermesToolPrompt(voll)
+ const anfang = ganz.indexOf('\n<tools>\n') + '\n<tools>\n'.length
+ // `lastIndexOf` fuer das Ende: die ERSTE Zeile des Prompts nennt
+ // "<tools></tools>" selbst, ein vorwaerts suchendes indexOf faende dort ein
+ // leeres Paar und maesse die Huelle als 100 %.
+ const liste = ganz.slice(anfang, ganz.lastIndexOf('\n</tools>\n'))
+ expect(liste.length).toBeGreaterThan(0)
+ expect((ganz.length - liste.length) / ganz.length).toBeLessThan(0.1)
+ })
+})
+
+describe('Nach der Auswahl passt es', () => {
+ it('die ausgewaehlte Liste passt ins kleinste Sendefenster', async () => {
+ const gewaehlt = await selectRelevantToolsAsync(
+ FRAGE, katalog(), DEFAULT_PERMISSIONS, toolSelectionOpts(true),
+ )
+ const prompt = buildHermesToolPrompt(gewaehlt)
+ // Mit Luft: die Liste darf hoechstens die HAELFTE des Sendefensters
+ // belegen, sonst bleibt fuer Systemprompt, Verlauf und die Frage selbst
+ // nichts uebrig. Sie war vorher bei 119 %.
+ expect(estimateTokens(prompt)).toBeLessThan(kleinstesSendefenster() / 2)
+ })
+
+ it('haelt den Deckel des nativen Zweigs ein', async () => {
+ const gewaehlt = await selectRelevantToolsAsync(
+ FRAGE, katalog(), DEFAULT_PERMISSIONS, toolSelectionOpts(true),
+ )
+ expect(gewaehlt.length).toBeLessThanOrEqual(SMALL_MODEL_MAX_TOOLS)
+ })
+
+ it('ein woertlich genanntes Werkzeug kommt am Deckel vorbei', async () => {
+ // Die Notausfahrt, ohne die der Deckel wirklich etwas wegnaehme. Sie
+ // steckt in applyMaxTools (`pinned`) und gilt fuer beide Zweige.
+ const gewaehlt = await selectRelevantToolsAsync(
+ 'use web_fetch to read https://example.com',
+ katalog(), DEFAULT_PERMISSIONS, toolSelectionOpts(true),
+ )
+ expect(gewaehlt.map((t) => t.name)).toContain('web_fetch')
+ })
+
+ it('ohne Small-Model-Mode wird gefiltert, aber nicht gedeckelt', async () => {
+ // Die Vorauswahl gilt auf BEIDEN Stufen — der Deckel nur unten. Ein
+ // grosses Modell auf dem Rueckfallweg (kaputtes Template, viel Fenster)
+ // soll seine Auswahl behalten, aber trotzdem keine 17 Schemata lesen
+ // muessen, von denen 11 nichts mit der Frage zu tun haben.
+ const gross = await selectRelevantToolsAsync(
+ FRAGE, katalog(), DEFAULT_PERMISSIONS, toolSelectionOpts(false),
+ )
+ expect(gross.length).toBeGreaterThan(SMALL_MODEL_MAX_TOOLS)
+ expect(gross.length).toBeLessThanOrEqual(katalog().length)
+ })
+})
+
+describe('Beide Zweige benutzen dieselben Stellschrauben', () => {
+ const quelle = () => lies('hooks/useAgentChat.ts')
+
+ it('der Hermes-Zweig waehlt aus, statt den Katalog zu nehmen', () => {
+ const t = quelle()
+ // Die eigentliche Zusicherung: die Zuweisung an `hermesToolDefs` geht
+ // durch die Auswahl. Auf `selectRelevantToolsAsync` allein zu pruefen
+ // waere zahnlos — die Zeile steht ja auch im nativen Zweig.
+ expect(t).toMatch(/hermesToolDefs\s*=\s*[\s\S]{0,200}selectRelevantToolsAsync\(/)
+ expect(t).not.toMatch(/hermesToolDefs\s*=\s*toolRegistry\s*\n?\s*\.toHermesToolDefs\(/)
+ })
+
+ it('keiner der beiden Zweige buchstabiert die Stellschrauben selbst aus', () => {
+ // Der Grund, warum es `toolSelectionOpts` gibt und nicht zwei Objektliterale:
+ // die Abweichung, die diese Datei behebt, ist genau so entstanden. Ein
+ // zweites Literal irgendwo laesst die Zweige beim naechsten Umbau wieder
+ // auseinanderlaufen, ohne dass etwas bricht.
+ const t = quelle()
+ expect(t).not.toContain('embeddingThreshold:')
+ expect(t).not.toContain('maxTools: SMALL_MODEL_MAX_TOOLS')
+ // Beide Aufrufe holen sie aus der einen Quelle.
+ const treffer = t.match(/toolSelectionOpts\(/g) ?? []
+ expect(treffer.length).toBeGreaterThanOrEqual(2)
+ })
+
+ it('die Vorauswahl bekommt dieselbe Werkzeugmenge wie nativ', () => {
+ // `toolRegistry.getAll()` plus derselbe curated/readOnly-Filter. Wer hier
+ // `getAvailableTools` einsetzte, veraenderte nichts an den Rechten
+ // (selectRelevantToolsAsync filtert `blocked` selbst), wohl aber die
+ // Vergleichbarkeit der beiden Zweige.
+ const t = quelle()
+ // Fenster fester Laenge hinter jedem Aufruf statt einer Klammer-Regex:
+ // ein nicht-gieriges `\)` haelt schon beim ersten `getAll()` an und der
+ // Waechter prueft dann nur den Anfang des Aufrufs.
+ const stellen: number[] = []
+ for (let i = t.indexOf('selectRelevantToolsAsync('); i !== -1; i = t.indexOf('selectRelevantToolsAsync(', i + 1)) {
+ stellen.push(i)
+ }
+ expect(stellen).toHaveLength(2)
+ for (const i of stellen) {
+ const fenster = t.slice(i, i + 400)
+ expect(fenster).toContain('toolRegistry.getAll()')
+ expect(fenster).toContain('toolMatchesCurated')
+ expect(fenster).toContain('toolSelectionOpts(')
+ }
+ })
+})
diff --git a/src/lib/tool-selection.ts b/src/lib/tool-selection.ts
index f8202762..af675a8c 100644
--- a/src/lib/tool-selection.ts
+++ b/src/lib/tool-selection.ts
@@ -49,9 +49,30 @@ const PR_KEYWORDS = [
'pull request', 'pull-request', 'open a pr', 'create a pr', 'the pr', 'this pr',
'github', 'gh pr', '/resume', 'pick up review', '/pull/',
]
+/**
+ * Die Woerter, die `delegate_task` und seine zwei Begleiter ins Werkzeugregal
+ * holen.
+ *
+ * ZWEI Befunde vom 02.09.2026 stecken in dieser Liste, beide von einem
+ * Fable-Urteil gegen die Claude-Code-Desktop-App gefunden:
+ *
+ * 1. Sie war rein ENGLISCH. Der Nutzer schreibt Deutsch — „nutze 5 glm 5.2
+ * agenten" haette das Tor nicht geoeffnet, und das Werkzeug waere dem
+ * Modell nie angeboten worden. MEDIA_KEYWORDS hat aus genau diesem Grund
+ * am 14.08.2026 'bild', 'foto', 'zeichne' bekommen; hier ist es
+ * nachgeholt.
+ * 2. Das blosse Wort „agent" fehlte. Wer „starte 3 agenten" sagt, sagt
+ * nicht „delegate" und nicht „fan out". Es ist das nachliegendste Wort
+ * ueberhaupt und war das einzige, das nicht drinstand.
+ */
const DELEGATE_KEYWORDS = [
+ // Englisch
'delegate', 'sub-agent', 'subagent', 'sub agent', 'fan out', 'fan-out',
- 'in parallel', 'parallelize', 'parallelise', 'split the work',
+ 'in parallel', 'parallel', 'parallelize', 'parallelise', 'split the work',
+ 'agents', 'agent',
+ // Deutsch
+ 'agenten', 'unteragent', 'aufteilen', 'aufteilung', 'nebenlaeufig',
+ 'nebenläufig', 'gleichzeitig', 'im hintergrund', 'hintergrundaufgabe',
]
/**
@@ -74,6 +95,21 @@ const GATE_KEYWORDS: Record<string, readonly string[]> = {
run_workflow: WORKFLOW_KEYWORDS,
pr_resume: PR_KEYWORDS,
delegate_task: DELEGATE_KEYWORDS,
+ // Dieselben Woerter wie delegate_task, und das ist keine Sparsamkeit,
+ // sondern die Bedeutung: beide Werkzeuge sprechen UEBER eine Delegation.
+ // Ohne eine gibt es nichts nachzusehen und niemanden anzureden.
+ //
+ // Der Deckel in tool-catalog-tokens.test.ts hat das erzwungen: die zwei
+ // Werkzeuge kosteten einen gewoehnlichen Refactor-Zug 844 Zeichen extra
+ // (+11 %), obwohl auf demselben Zug delegate_task laengst nicht mitfaehrt.
+ // Eine Sperre, die ein Budget haelt, hat hier einen Entwurfsfehler
+ // gefunden, nicht nur eine Zahl.
+ //
+ // Der Selbstheilungspfad traegt mit: ruft ein Lauf im sechsten Schritt doch
+ // delegate_task, oeffnet GATE_OPENING_TOOLS das Tor fuer den Rest des
+ // Laufs — und dann kommen diese beiden mit, genau wenn sie gebraucht werden.
+ check_tasks: DELEGATE_KEYWORDS,
+ message_agent: DELEGATE_KEYWORDS,
}
/**
@@ -140,8 +176,14 @@ const TOOL_GROUPS: ToolGroup[] = [
tools: ['pr_resume', 'shell_execute'],
},
{
- keywords: ['delegate', 'sub-agent', 'subagent', 'fan out', 'in parallel', 'parallelize', 'split the work'],
- tools: ['delegate_task'],
+ // EINE Liste, nicht zwei. Hier stand bis 2.6.8 eine abgeschriebene Kopie,
+ // und sie war schon auseinandergelaufen: 'sub agent', 'fan-out' und
+ // 'parallelise' fehlten, obwohl der Kommentar bei DELEGATE_KEYWORDS
+ // ausdruecklich verspricht, dass beide Wege „identisch antworten". Genau
+ // so entsteht der Fehler, den niemand sieht — der lokale Pfad oeffnet das
+ // Tor, der Cloud-Pfad nicht, und es haengt am Wort.
+ keywords: DELEGATE_KEYWORDS,
+ tools: ['delegate_task', 'check_tasks', 'message_agent'],
},
{
// system_info / process_list retired (2.6.6): the environment block in
@@ -376,6 +418,54 @@ export function applyMaxTools(
* is absent, throws, or fails, silently falls back to the keyword-only
* path.
*/
+/**
+ * Wie eng ein Small-Model-Zug die Werkzeugliste zieht.
+ *
+ * `topN` ist, wie viele der semantische Router hoechstens vorschlaegt;
+ * `embeddingThreshold` ist die Katalogroesse, ab der ueberhaupt semantisch
+ * geroutet statt nur nach Stichworten gefiltert wird. Beide standen bis
+ * 2026-09-02 als nackte Zahlen im Aufruf in useAgentChat.ts — 5 und 6, ohne
+ * Namen, ohne Begruendung, an genau einer von zwei Stellen, die sie brauchen.
+ */
+const SMALL_MODEL_TOP_N = 5
+const SMALL_MODEL_EMBEDDING_THRESHOLD = 6
+
+/**
+ * Die Stellschrauben der Werkzeug-Vorauswahl, an EINER Stelle.
+ *
+ * ── WARUM DAS EINE FUNKTION IST UND KEIN OBJEKTLITERAL AM AUFRUF ───────────
+ *
+ * Weil die Abweichung, die sie behebt, genau so entstanden ist. Bis
+ * 2026-09-02 stand dieses Objekt ausgeschrieben im NATIVEN Zweig von
+ * useAgentChat.ts — und nur dort. Der hermes_xml-Zweig derselben Datei nahm
+ * stattdessen `toolRegistry.toHermesToolDefs(permissions)`, also den ganzen
+ * Katalog, ohne Vorauswahl und ohne Deckel.
+ *
+ * Nichts an dieser Auslassung war sichtbar: kein Fehler, kein Test, keine
+ * Warnung. Sie fiel erst auf, als jemand nachrechnete. Gemessen an dem Tag:
+ * 17 Werkzeuge ergaben einen Hermes-Prompt von 19.459 Zeichen (≈ 4.866 Token),
+ * bei einem Sendefenster von 4.096 Token fuer die Modelle, die auf diesem
+ * Rueckfallweg ueberhaupt landen — die Liste allein war 119 % des Fensters.
+ *
+ * Zwei Objektliterale koennen wieder auseinanderlaufen. Eine Funktion, die
+ * beide Zweige rufen, kann es nicht. Eine Sperrklinke in
+ * lib/__tests__/hermes-werkzeugauswahl.test.ts haelt fest, dass keiner der
+ * beiden Zweige die Zahlen wieder selbst ausbuchstabiert.
+ */
+export function toolSelectionOpts(
+ smallModelMode: boolean,
+ embed?: EmbeddingFn,
+): { embed?: EmbeddingFn; embeddingThreshold?: number; topN?: number; maxTools?: number } {
+ return smallModelMode
+ ? {
+ embed,
+ topN: SMALL_MODEL_TOP_N,
+ embeddingThreshold: SMALL_MODEL_EMBEDDING_THRESHOLD,
+ maxTools: SMALL_MODEL_MAX_TOOLS,
+ }
+ : { embed }
+}
+
export async function selectRelevantToolsAsync(
userMessage: string,
allTools: MCPToolDefinition[],