@gaunt-sloth/core 2.0.0-alpha.9 → 2.0.0-beta.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/.gsloth.review.md +2 -0
- package/README.md +71 -20
- package/dist/config/colour.d.ts +38 -0
- package/dist/config/colour.js +36 -0
- package/dist/config/colour.js.map +1 -0
- package/dist/config/configDiscovery.d.ts +79 -0
- package/dist/config/configDiscovery.js +80 -0
- package/dist/config/configDiscovery.js.map +1 -0
- package/dist/config/defaults.d.ts +20 -20
- package/dist/config/defaults.js +10 -8
- package/dist/config/defaults.js.map +1 -1
- package/dist/config/filesystem-tools.d.ts +41 -0
- package/dist/config/filesystem-tools.js +56 -0
- package/dist/config/filesystem-tools.js.map +1 -0
- package/dist/config/loader.d.ts +171 -19
- package/dist/config/loader.js +1054 -144
- package/dist/config/loader.js.map +1 -1
- package/dist/config/mouse.d.ts +50 -0
- package/dist/config/mouse.js +44 -0
- package/dist/config/mouse.js.map +1 -0
- package/dist/config/profiles.d.ts +68 -0
- package/dist/config/profiles.js +93 -0
- package/dist/config/profiles.js.map +1 -0
- package/dist/config/providerKeys.d.ts +69 -0
- package/dist/config/providerKeys.js +69 -0
- package/dist/config/providerKeys.js.map +1 -0
- package/dist/config/schema.d.ts +2671 -138
- package/dist/config/schema.js +1361 -85
- package/dist/config/schema.js.map +1 -1
- package/dist/config/shell-policy.d.ts +899 -111
- package/dist/config/shell-policy.js +800 -70
- package/dist/config/shell-policy.js.map +1 -1
- package/dist/config/tool-descriptions.d.ts +211 -0
- package/dist/config/tool-descriptions.js +272 -0
- package/dist/config/tool-descriptions.js.map +1 -0
- package/dist/config/types.d.ts +352 -41
- package/dist/config/types.js +1 -0
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +35 -1
- package/dist/config.js +16 -1
- package/dist/config.js.map +1 -1
- package/dist/constants.d.ts +28 -1
- package/dist/constants.js +28 -1
- package/dist/constants.js.map +1 -1
- package/dist/core/GthAbstractAgent.d.ts +166 -11
- package/dist/core/GthAbstractAgent.js +484 -45
- package/dist/core/GthAbstractAgent.js.map +1 -1
- package/dist/core/GthAgentRunner.d.ts +543 -57
- package/dist/core/GthAgentRunner.js +1494 -140
- package/dist/core/GthAgentRunner.js.map +1 -1
- package/dist/core/GthLangChainAgent.d.ts +117 -2
- package/dist/core/GthLangChainAgent.js +602 -29
- package/dist/core/GthLangChainAgent.js.map +1 -1
- package/dist/core/approvals/annotations.d.ts +122 -0
- package/dist/core/approvals/annotations.js +137 -0
- package/dist/core/approvals/annotations.js.map +1 -0
- package/dist/core/approvals/grants.d.ts +216 -0
- package/dist/core/approvals/grants.js +469 -0
- package/dist/core/approvals/grants.js.map +1 -0
- package/dist/core/approvals/matcher.d.ts +202 -0
- package/dist/core/approvals/matcher.js +267 -0
- package/dist/core/approvals/matcher.js.map +1 -0
- package/dist/core/approvals/mcpSubjects.d.ts +40 -0
- package/dist/core/approvals/mcpSubjects.js +99 -0
- package/dist/core/approvals/mcpSubjects.js.map +1 -0
- package/dist/core/approvals/promptHeader.d.ts +28 -0
- package/dist/core/approvals/promptHeader.js +62 -0
- package/dist/core/approvals/promptHeader.js.map +1 -0
- package/dist/core/approvals/toolAnnotationSources.d.ts +105 -0
- package/dist/core/approvals/toolAnnotationSources.js +277 -0
- package/dist/core/approvals/toolAnnotationSources.js.map +1 -0
- package/dist/core/approvals/toolHost.d.ts +46 -0
- package/dist/core/approvals/toolHost.js +108 -0
- package/dist/core/approvals/toolHost.js.map +1 -0
- package/dist/core/debugCapture.d.ts +74 -0
- package/dist/core/debugCapture.js +100 -0
- package/dist/core/debugCapture.js.map +1 -0
- package/dist/core/gthLeanAgentFactory.d.ts +4 -4
- package/dist/core/gthLeanAgentFactory.js +4 -4
- package/dist/core/launchBanner.d.ts +127 -0
- package/dist/core/launchBanner.js +414 -0
- package/dist/core/launchBanner.js.map +1 -0
- package/dist/core/modelLabel.d.ts +19 -0
- package/dist/core/modelLabel.js +26 -0
- package/dist/core/modelLabel.js.map +1 -0
- package/dist/core/plainToolIndication.d.ts +15 -0
- package/dist/core/plainToolIndication.js +174 -0
- package/dist/core/plainToolIndication.js.map +1 -0
- package/dist/core/reasoningBlocks.d.ts +65 -0
- package/dist/core/reasoningBlocks.js +103 -0
- package/dist/core/reasoningBlocks.js.map +1 -0
- package/dist/core/refusal.d.ts +53 -0
- package/dist/core/refusal.js +133 -0
- package/dist/core/refusal.js.map +1 -0
- package/dist/core/runHeader.d.ts +38 -0
- package/dist/core/runHeader.js +42 -0
- package/dist/core/runHeader.js.map +1 -0
- package/dist/core/runStats.d.ts +14 -3
- package/dist/core/runStats.js +48 -3
- package/dist/core/runStats.js.map +1 -1
- package/dist/core/shell/ShellCommandFailedError.d.ts +3 -4
- package/dist/core/shell/ShellCommandFailedError.js +3 -4
- package/dist/core/shell/ShellCommandFailedError.js.map +1 -1
- package/dist/core/shell/abstention.d.ts +88 -0
- package/dist/core/shell/abstention.js +184 -0
- package/dist/core/shell/abstention.js.map +1 -0
- package/dist/core/shell/approvalCapture.d.ts +271 -0
- package/dist/core/shell/approvalCapture.js +108 -0
- package/dist/core/shell/approvalCapture.js.map +1 -0
- package/dist/core/shell/approvalStop.d.ts +123 -0
- package/dist/core/shell/approvalStop.js +269 -0
- package/dist/core/shell/approvalStop.js.map +1 -0
- package/dist/core/shell/arity.d.ts +6 -0
- package/dist/core/shell/arity.js +20 -6
- package/dist/core/shell/arity.js.map +1 -1
- package/dist/core/shell/denylist.d.ts +11 -0
- package/dist/core/shell/denylist.js +37 -0
- package/dist/core/shell/denylist.js.map +1 -0
- package/dist/core/shell/escalationSeverity.d.ts +141 -0
- package/dist/core/shell/escalationSeverity.js +89 -0
- package/dist/core/shell/escalationSeverity.js.map +1 -0
- package/dist/core/shell/framing.d.ts +190 -0
- package/dist/core/shell/framing.js +633 -0
- package/dist/core/shell/framing.js.map +1 -0
- package/dist/core/shell/hardline.d.ts +103 -0
- package/dist/core/shell/hardline.js +780 -0
- package/dist/core/shell/hardline.js.map +1 -0
- package/dist/core/shell/negotiation.d.ts +328 -0
- package/dist/core/shell/negotiation.js +488 -0
- package/dist/core/shell/negotiation.js.map +1 -0
- package/dist/core/shell/normalize.d.ts +44 -4
- package/dist/core/shell/normalize.js +61 -7
- package/dist/core/shell/normalize.js.map +1 -1
- package/dist/core/shell/openWorld.d.ts +263 -0
- package/dist/core/shell/openWorld.js +1188 -0
- package/dist/core/shell/openWorld.js.map +1 -0
- package/dist/core/shell/rater.d.ts +873 -0
- package/dist/core/shell/rater.js +1454 -0
- package/dist/core/shell/rater.js.map +1 -0
- package/dist/core/shell/raterModel.d.ts +41 -0
- package/dist/core/shell/raterModel.js +51 -0
- package/dist/core/shell/raterModel.js.map +1 -0
- package/dist/core/shell/raterVocabulary.d.ts +121 -0
- package/dist/core/shell/raterVocabulary.js +116 -0
- package/dist/core/shell/raterVocabulary.js.map +1 -0
- package/dist/core/shell/rejection.d.ts +69 -0
- package/dist/core/shell/rejection.js +38 -0
- package/dist/core/shell/rejection.js.map +1 -0
- package/dist/core/toolCallRepair/grammar.d.ts +41 -0
- package/dist/core/toolCallRepair/grammar.js +116 -0
- package/dist/core/toolCallRepair/grammar.js.map +1 -0
- package/dist/core/toolCallRepair/index.d.ts +2 -0
- package/dist/core/toolCallRepair/index.js +7 -0
- package/dist/core/toolCallRepair/index.js.map +1 -0
- package/dist/core/toolCallRepair/payload.d.ts +36 -0
- package/dist/core/toolCallRepair/payload.js +341 -0
- package/dist/core/toolCallRepair/payload.js.map +1 -0
- package/dist/core/toolCallRepair/promote.d.ts +45 -0
- package/dist/core/toolCallRepair/promote.js +90 -0
- package/dist/core/toolCallRepair/promote.js.map +1 -0
- package/dist/core/toolDisplay.d.ts +123 -0
- package/dist/core/toolDisplay.js +451 -0
- package/dist/core/toolDisplay.js.map +1 -0
- package/dist/core/toolOutputChannel.d.ts +95 -0
- package/dist/core/toolOutputChannel.js +165 -0
- package/dist/core/toolOutputChannel.js.map +1 -0
- package/dist/core/types.d.ts +349 -16
- package/dist/core/types.js.map +1 -1
- package/dist/history/historyFormat.d.ts +12 -3
- package/dist/history/historyFormat.js +50 -8
- package/dist/history/historyFormat.js.map +1 -1
- package/dist/history/historyStore.d.ts +77 -0
- package/dist/history/historyStore.js +173 -6
- package/dist/history/historyStore.js.map +1 -1
- package/dist/history/recordSession.d.ts +10 -1
- package/dist/history/recordSession.js +27 -0
- package/dist/history/recordSession.js.map +1 -1
- package/dist/providers/anthropic.js +12 -0
- package/dist/providers/anthropic.js.map +1 -1
- package/dist/providers/configurationPassthrough.d.ts +107 -0
- package/dist/providers/configurationPassthrough.js +148 -0
- package/dist/providers/configurationPassthrough.js.map +1 -0
- package/dist/providers/geminiSchemaSanitizer.d.ts +55 -0
- package/dist/providers/geminiSchemaSanitizer.js +347 -0
- package/dist/providers/geminiSchemaSanitizer.js.map +1 -0
- package/dist/providers/geminiThinking.d.ts +60 -0
- package/dist/providers/geminiThinking.js +92 -0
- package/dist/providers/geminiThinking.js.map +1 -0
- package/dist/providers/google-genai.js +18 -1
- package/dist/providers/google-genai.js.map +1 -1
- package/dist/providers/groq.js +12 -0
- package/dist/providers/groq.js.map +1 -1
- package/dist/providers/huggingface.d.ts +25 -0
- package/dist/providers/huggingface.js +69 -0
- package/dist/providers/huggingface.js.map +1 -0
- package/dist/providers/modelCatalog.d.ts +109 -0
- package/dist/providers/modelCatalog.js +245 -0
- package/dist/providers/modelCatalog.js.map +1 -0
- package/dist/providers/modelDiscovery.d.ts +99 -5
- package/dist/providers/modelDiscovery.js +191 -35
- package/dist/providers/modelDiscovery.js.map +1 -1
- package/dist/providers/ollama.d.ts +18 -4
- package/dist/providers/ollama.js +67 -37
- package/dist/providers/ollama.js.map +1 -1
- package/dist/providers/openai.js +34 -0
- package/dist/providers/openai.js.map +1 -1
- package/dist/providers/openrouter.d.ts +26 -4
- package/dist/providers/openrouter.js +83 -26
- package/dist/providers/openrouter.js.map +1 -1
- package/dist/providers/vertexai.js +19 -1
- package/dist/providers/vertexai.js.map +1 -1
- package/dist/providers/xai.js +20 -0
- package/dist/providers/xai.js.map +1 -1
- package/dist/runtime/askStructured.d.ts +105 -0
- package/dist/runtime/askStructured.js +120 -0
- package/dist/runtime/askStructured.js.map +1 -0
- package/dist/runtime/conversation.d.ts +64 -0
- package/dist/runtime/conversation.js +171 -0
- package/dist/runtime/conversation.js.map +1 -0
- package/dist/runtime/singleShot.d.ts +37 -6
- package/dist/runtime/singleShot.js +113 -67
- package/dist/runtime/singleShot.js.map +1 -1
- package/dist/runtime/structuredOutput.d.ts +104 -0
- package/dist/runtime/structuredOutput.js +393 -0
- package/dist/runtime/structuredOutput.js.map +1 -0
- package/dist/utils/ProgressIndicator.d.ts +21 -0
- package/dist/utils/ProgressIndicator.js +30 -3
- package/dist/utils/ProgressIndicator.js.map +1 -1
- package/dist/utils/aiignoreUtils.js.map +1 -1
- package/dist/utils/binaryOutputUtils.js.map +1 -1
- package/dist/utils/consoleUtils.d.ts +95 -0
- package/dist/utils/consoleUtils.js +112 -2
- package/dist/utils/consoleUtils.js.map +1 -1
- package/dist/utils/crashHandler.d.ts +87 -0
- package/dist/utils/crashHandler.js +128 -0
- package/dist/utils/crashHandler.js.map +1 -0
- package/dist/utils/debugDump.d.ts +134 -0
- package/dist/utils/debugDump.js +381 -0
- package/dist/utils/debugDump.js.map +1 -0
- package/dist/utils/debugUtils.d.ts +13 -4
- package/dist/utils/debugUtils.js +36 -13
- package/dist/utils/debugUtils.js.map +1 -1
- package/dist/utils/displayWidth.d.ts +53 -0
- package/dist/utils/displayWidth.js +195 -0
- package/dist/utils/displayWidth.js.map +1 -0
- package/dist/utils/fileUtils.js.map +1 -1
- package/dist/utils/globalConfigUtils.d.ts +14 -2
- package/dist/utils/globalConfigUtils.js +22 -4
- package/dist/utils/globalConfigUtils.js.map +1 -1
- package/dist/utils/llmUtils.d.ts +39 -8
- package/dist/utils/llmUtils.js +76 -8
- package/dist/utils/llmUtils.js.map +1 -1
- package/dist/utils/redactSecrets.d.ts +63 -0
- package/dist/utils/redactSecrets.js +286 -0
- package/dist/utils/redactSecrets.js.map +1 -0
- package/dist/utils/systemPromptNotes.d.ts +222 -0
- package/dist/utils/systemPromptNotes.js +338 -0
- package/dist/utils/systemPromptNotes.js.map +1 -0
- package/dist/utils/systemUtils.d.ts +18 -1
- package/dist/utils/systemUtils.js +38 -3
- package/dist/utils/systemUtils.js.map +1 -1
- package/dist/utils/toolMatching.d.ts +30 -0
- package/dist/utils/toolMatching.js +44 -0
- package/dist/utils/toolMatching.js.map +1 -0
- package/dist/utils/untrustedText.d.ts +86 -0
- package/dist/utils/untrustedText.js +101 -0
- package/dist/utils/untrustedText.js.map +1 -0
- package/package.json +21 -7
- package/schema/gsloth-config.schema.json +1921 -326
- package/dist/core/shell/allowlist.d.ts +0 -75
- package/dist/core/shell/allowlist.js +0 -187
- package/dist/core/shell/allowlist.js.map +0 -1
- package/dist/core/shell/judge.d.ts +0 -161
- package/dist/core/shell/judge.js +0 -261
- package/dist/core/shell/judge.js.map +0 -1
|
@@ -1,19 +1,296 @@
|
|
|
1
|
+
import { SHELL_TOOL_NAME, commandAnswersApprovals, resolveApprovals, resolveGatedToolNames, resolveInterruptToolNames, resolveShellApprovalGate, } from '#src/config.js';
|
|
1
2
|
import { StatusLevel } from '#src/core/types.js';
|
|
2
3
|
import { GthAbstractAgent } from '#src/core/GthAbstractAgent.js';
|
|
3
4
|
import { debugLog, debugLogObject } from '#src/utils/debugUtils.js';
|
|
4
|
-
import { buildSystemMessages, formatToolCalls,
|
|
5
|
+
import { buildSystemMessages, formatToolCalls, readModePrompt } from '#src/utils/llmUtils.js';
|
|
5
6
|
import { getCurrentWorkDir } from '#src/utils/systemUtils.js';
|
|
7
|
+
import { isToolAllowed } from '#src/utils/toolMatching.js';
|
|
8
|
+
import { appendOsShellNote, appendCwdNote, appendCommitCoAuthorNote, appendModelContextNote, appendMcpServerInstructionsNote, resolveModelIdentity, } from '#src/utils/systemPromptNotes.js';
|
|
6
9
|
import { isShellCommandFailedError } from '#src/core/shell/ShellCommandFailedError.js';
|
|
10
|
+
import { extractDebugRequestExtras } from '#src/core/debugCapture.js';
|
|
11
|
+
import { promoteTextEmittedToolCallMessage } from '#src/core/toolCallRepair/index.js';
|
|
7
12
|
import { AIMessage, ToolMessage } from '@langchain/core/messages';
|
|
8
|
-
import { createAgent, createMiddleware } from 'langchain';
|
|
13
|
+
import { createAgent, createMiddleware, humanInTheLoopMiddleware, } from 'langchain';
|
|
14
|
+
/**
|
|
15
|
+
* GS2-36 — default cap for the tool-error retry budget: how many status:'error' tool results may
|
|
16
|
+
* accrue back-to-back (no successful tool result in between) before the run is ended gracefully.
|
|
17
|
+
* Small on purpose: it still lets the model try a couple of genuine recovery variants (the whole
|
|
18
|
+
* point of feeding errors back — GS2-32 showed the model routes around a surfaced error in 1–2
|
|
19
|
+
* tries) while stopping a runaway self-inflicted loop long before createAgent's coarse
|
|
20
|
+
* recursionLimit backstop would.
|
|
21
|
+
*/
|
|
22
|
+
export const MAX_CONSECUTIVE_TOOL_ERRORS = 5;
|
|
23
|
+
/**
|
|
24
|
+
* GS2-36 — the tool-error retry budget as a standalone, testable middleware factory (exported so the
|
|
25
|
+
* real thing can be unit-tested and exercised in a real `createAgent` graph, mirroring
|
|
26
|
+
* `createPathNamespaceCorrectionMiddleware`).
|
|
27
|
+
*
|
|
28
|
+
* Runs in `beforeModel` (like langchain's own `modelCallLimitMiddleware`): after the tools node has
|
|
29
|
+
* appended its result(s) and before the next model call is spent, it walks the trailing messages and
|
|
30
|
+
* counts CONSECUTIVE errored tool results — a `ToolMessage` with `status: 'error'` (the shape the
|
|
31
|
+
* shell/MCP softeners produce; GthAbstractAgent maps `status==='error' → isError`). The walk skips
|
|
32
|
+
* the assistant tool-call requests between rounds, and RESETS on the first successful tool result
|
|
33
|
+
* (progress / diagnosis) or a Human/System message (a fresh user turn). Once the count reaches the
|
|
34
|
+
* cap it returns `{ jumpTo: 'end', messages: [<action-oriented notice>] }`, ending the run without
|
|
35
|
+
* spending another model call.
|
|
36
|
+
*
|
|
37
|
+
* Scope: counts `status: 'error'` results only. The recoverable fs error STRINGS
|
|
38
|
+
* (`write_file`/`edit_file`/…) are `status: 'success'` by the write_file precedent, so a pure fs
|
|
39
|
+
* error loop is deliberately NOT capped here — it stays bounded by the coarse `recursionLimit` and is
|
|
40
|
+
* the remit of the loop-DETECTION node (EXT-36). Counting `status: 'error'` overall (not per-tool)
|
|
41
|
+
* catches both same-tool and alternating-tool error loops with one robust rule.
|
|
42
|
+
*/
|
|
43
|
+
export function createToolErrorBudgetMiddleware(maxConsecutiveErrors = MAX_CONSECUTIVE_TOOL_ERRORS) {
|
|
44
|
+
return createMiddleware({
|
|
45
|
+
name: 'GthLeanToolErrorBudget',
|
|
46
|
+
beforeModel: {
|
|
47
|
+
canJumpTo: ['end'],
|
|
48
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
49
|
+
hook: (state) => {
|
|
50
|
+
const messages = Array.isArray(state?.messages) ? state.messages : [];
|
|
51
|
+
let consecutive = 0;
|
|
52
|
+
let lastErrorContent = '';
|
|
53
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
54
|
+
const msg = messages[i];
|
|
55
|
+
if (ToolMessage.isInstance(msg)) {
|
|
56
|
+
if (msg.status === 'error') {
|
|
57
|
+
consecutive++;
|
|
58
|
+
if (!lastErrorContent) {
|
|
59
|
+
lastErrorContent = typeof msg.content === 'string' ? msg.content : '';
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
else {
|
|
63
|
+
// A successful tool result — the model is making progress / diagnosing, so the
|
|
64
|
+
// unrecovered-error streak is broken. Stop the walk (reset).
|
|
65
|
+
break;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else if (AIMessage.isInstance(msg)) {
|
|
69
|
+
// The assistant tool-call request that produced the error above; skip and keep counting.
|
|
70
|
+
// GS2-72: this `continue` INTENTIONALLY also skips the budget's OWN injected terminal
|
|
71
|
+
// notice (itself an AIMessage). If the run re-enters beforeModel on the same thread after
|
|
72
|
+
// a jumpTo:'end' (a re-invoke on the same thread — e.g. the no-checkpointer degrade of
|
|
73
|
+
// the string path's empty-stream fallback, or a later turn that keeps erroring), skipping
|
|
74
|
+
// the notice lets the walk still reach the errored results and re-trip deterministically.
|
|
75
|
+
// Do NOT special-case the notice to reset/break here — treating it as a fresh-turn
|
|
76
|
+
// boundary would let the capped loop resume.
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
else {
|
|
80
|
+
// A Human/System message: a fresh user-turn boundary — earlier errors don't count.
|
|
81
|
+
break;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (consecutive >= maxConsecutiveErrors) {
|
|
85
|
+
const firstLine = (lastErrorContent.split('\n')[0] ?? '').slice(0, 300);
|
|
86
|
+
const notice = `Stopped after ${consecutive} consecutive failed tool calls to avoid a retry loop that ` +
|
|
87
|
+
'keeps spending tokens without making progress' +
|
|
88
|
+
(firstLine ? ` (last error: ${firstLine})` : '') +
|
|
89
|
+
'. Do not repeat the same call: inspect the error, then change your approach — different ' +
|
|
90
|
+
'arguments, a narrower path, or a different tool — or report the blocker to the user.';
|
|
91
|
+
return { jumpTo: 'end', messages: [new AIMessage(notice)] };
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* EXT-36 — default number of consecutive identical `(tool, args)` calls before the tool-loop guard
|
|
100
|
+
* fires. Small on purpose: it must catch a genuine no-progress loop (a model re-issuing the SAME
|
|
101
|
+
* call verbatim) while never tripping a legitimate one-off retry (2x). Kept below GS2-36's coarser
|
|
102
|
+
* error cap (5) because a same-signature repeat is a stronger, more specific loop signal than "an
|
|
103
|
+
* error happened again".
|
|
104
|
+
*/
|
|
105
|
+
export const DEFAULT_TOOL_LOOP_THRESHOLD = 3;
|
|
106
|
+
/**
|
|
107
|
+
* EXT-36 — normalise the `toolLoopGuard` config union (`false | true | { warn?, halt?, threshold? }`)
|
|
108
|
+
* into concrete {@link ToolLoopGuardOptions}, applying the WARN-ON-by-default policy at the read site
|
|
109
|
+
* (mirrors how `debugDump.redact` defaults with `!== false`, NOT in DEFAULT_CONFIG, so the
|
|
110
|
+
* effective-config snapshot never churns).
|
|
111
|
+
* - `false` → both modes off (a no-op guard);
|
|
112
|
+
* - `true` / absent → warn on, halt off, default threshold;
|
|
113
|
+
* - object → per-field, with warn defaulting ON and halt defaulting OFF.
|
|
114
|
+
*/
|
|
115
|
+
export function resolveToolLoopGuardOptions(setting) {
|
|
116
|
+
if (setting === false)
|
|
117
|
+
return { warn: false, halt: false };
|
|
118
|
+
if (setting === true || setting === undefined || setting === null)
|
|
119
|
+
return {};
|
|
120
|
+
return { warn: setting.warn, halt: setting.halt, threshold: setting.threshold };
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* EXT-36 — a deterministic, key-sorted stringify so `(tool, args)` signatures are stable regardless
|
|
124
|
+
* of object key order. No-args (`{}`) collapses to `"{}"`, so identical no-arg repeats collide BY
|
|
125
|
+
* DESIGN — that is exactly the loop signal. Known limitation: args carrying a volatile value (a
|
|
126
|
+
* timestamp / uuid) make every call look distinct, so the guard cannot see that loop; volatile-key
|
|
127
|
+
* stripping is deliberately NOT attempted (over-engineering for a rare, model-authored case).
|
|
128
|
+
*/
|
|
129
|
+
function stableStringify(value) {
|
|
130
|
+
if (value === null || typeof value !== 'object')
|
|
131
|
+
return JSON.stringify(value) ?? 'null';
|
|
132
|
+
if (Array.isArray(value))
|
|
133
|
+
return `[${value.map(stableStringify).join(',')}]`;
|
|
134
|
+
const record = value;
|
|
135
|
+
const keys = Object.keys(record).sort();
|
|
136
|
+
return `{${keys.map((k) => `${JSON.stringify(k)}:${stableStringify(record[k])}`).join(',')}}`;
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* The delimiter between a tool name and its serialised arguments in a call signature. U+0000 is
|
|
140
|
+
* chosen because a tool name cannot contain a control character, so no `(name, args)` pair can be
|
|
141
|
+
* spelled two ways and no pair of distinct calls can collide on one signature.
|
|
142
|
+
*
|
|
143
|
+
* It MUST stay written as this escape. A raw NUL byte in the source makes the whole file binary to
|
|
144
|
+
* ripgrep and ugrep, which then skip it in silence — every symbol in this file becomes invisible to
|
|
145
|
+
* a repo-wide search, and an empty result reads as proof of absence. `noRawControlBytes.spec.ts` guards
|
|
146
|
+
* the repo against the raw form returning.
|
|
147
|
+
*/
|
|
148
|
+
export const TOOL_CALL_SIGNATURE_DELIMITER = '\u0000';
|
|
149
|
+
/**
|
|
150
|
+
* EXT-36 — the `(tool, args)` identity a repeat-detection streak is counted over. Exported so the
|
|
151
|
+
* delimiter invariant above is asserted directly rather than inferred from loop behaviour.
|
|
152
|
+
*/
|
|
153
|
+
export function toolCallSignature(name, args) {
|
|
154
|
+
return `${name}${TOOL_CALL_SIGNATURE_DELIMITER}${stableStringify(args ?? {})}`;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* EXT-36 — the tool-loop guardrail as a standalone, testable middleware factory. The ORTHOGONAL
|
|
158
|
+
* sibling of {@link createToolErrorBudgetMiddleware}: GS2-36 caps a consecutive-tool-ERROR streak;
|
|
159
|
+
* this catches a **repeated identical `(tool, args)` / no-progress loop** — the same call re-issued
|
|
160
|
+
* verbatim, whether it keeps erroring OR keeps "succeeding" with the same result (the fs-error-string
|
|
161
|
+
* loop GS2-36's comment explicitly leaves to EXT-36).
|
|
162
|
+
*
|
|
163
|
+
* STATELESS (the critical trap): the factory runs ONCE per session, so a closure-held counter would
|
|
164
|
+
* bleed across every turn. Like GS2-36 it holds NO state — each `beforeModel` recomputes the streak
|
|
165
|
+
* from the message tail.
|
|
166
|
+
*
|
|
167
|
+
* Detection. A signature is `(tool_name, args_hash)`. Name + args live on `AIMessage.tool_calls[]`,
|
|
168
|
+
* NOT on the `ToolMessage` (softener ToolMessages carry only content+tool_call_id+status), so each
|
|
169
|
+
* `ToolMessage` is paired to its call by `tool_call_id === AIMessage.tool_calls[].id` to recover the
|
|
170
|
+
* signature. The backward walk counts CONSECUTIVE ToolMessages with the SAME signature; a DIFFERENT
|
|
171
|
+
* signature breaks the streak (the model tried something else = progress), and a Human/System message
|
|
172
|
+
* is a fresh-turn boundary. Assistant messages (the tool-call requests) are skipped. Known no-op
|
|
173
|
+
* (safe, never a false trip): a single AIMessage issuing PARALLEL tool calls yields back-to-back
|
|
174
|
+
* differing signatures, which the walk reads as progress and resets.
|
|
175
|
+
*
|
|
176
|
+
* Two modes (composable):
|
|
177
|
+
* - WARN (default ON, provably harmless): the default path must NOT change what the model sees.
|
|
178
|
+
* Appending ANY message then re-invoking the model mutates its input — a *steer*, not a *warn* —
|
|
179
|
+
* and is provider-unsafe by default (Gemini expects a trailing user turn → crash risk; Anthropic
|
|
180
|
+
* treats a trailing assistant as PREFILL → the note silently becomes the opening of the model's own
|
|
181
|
+
* next reply, corrupt with no error; a HumanMessage after a ToolMessage is two consecutive user
|
|
182
|
+
* turns for Anthropic/Gemini). So WARN instead SURFACES a user-visible notice via {@link onWarn}
|
|
183
|
+
* and returns `undefined` — zero `state.messages` mutation, zero control-flow. Fired statelessly
|
|
184
|
+
* ONCE per streak at the exact crossing (`streak === threshold`): a still-looping streak on later
|
|
185
|
+
* turns (`streak > threshold`) does not re-surface, while an interrupted-then-resumed loop
|
|
186
|
+
* re-reaches `threshold` and surfaces again — no marker/`additional_kwargs` machinery needed.
|
|
187
|
+
* - HALT (opt-in only, active loop-breaking): at/over threshold, return
|
|
188
|
+
* `{ jumpTo: 'end', messages: [new AIMessage(reason)] }` — a TERMINAL notice (the model is never
|
|
189
|
+
* re-invoked after it, so the prefill/role hazard cannot arise; the GS2-72-proven clean-stream
|
|
190
|
+
* path). NEVER throws. A validated behaviour change lives behind this opt-in.
|
|
191
|
+
*
|
|
192
|
+
* @param onWarn TUI-safe user-notice sink for WARN, wired at the read site to
|
|
193
|
+
* `statusUpdate(StatusLevel.WARNING, …)` (routed through the agent's status callback the renderer
|
|
194
|
+
* consumes, never raw stdout, so it can't leak over the Ink frame). Omitted → WARN still runs but
|
|
195
|
+
* surfaces nothing (still zero model-input mutation).
|
|
196
|
+
*/
|
|
197
|
+
export function createToolLoopGuardMiddleware(options = {}, onWarn) {
|
|
198
|
+
const warn = options.warn ?? true;
|
|
199
|
+
const halt = options.halt ?? false;
|
|
200
|
+
const threshold = options.threshold ?? DEFAULT_TOOL_LOOP_THRESHOLD;
|
|
201
|
+
return createMiddleware({
|
|
202
|
+
name: 'GthLeanToolLoopGuard',
|
|
203
|
+
beforeModel: {
|
|
204
|
+
canJumpTo: ['end'],
|
|
205
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
206
|
+
hook: (state) => {
|
|
207
|
+
// `false` config resolves to warn:false + halt:false — a genuine no-op (fast bail).
|
|
208
|
+
if (!warn && !halt)
|
|
209
|
+
return undefined;
|
|
210
|
+
const messages = Array.isArray(state?.messages) ? state.messages : [];
|
|
211
|
+
// Recover each tool call's signature by id — name + args are on the AIMessage, not the
|
|
212
|
+
// ToolMessage. One pass over all AIMessages builds the id → {sig, name} lookup.
|
|
213
|
+
const callById = new Map();
|
|
214
|
+
for (const msg of messages) {
|
|
215
|
+
if (AIMessage.isInstance(msg) && Array.isArray(msg.tool_calls)) {
|
|
216
|
+
for (const tc of msg.tool_calls) {
|
|
217
|
+
const id = tc?.id;
|
|
218
|
+
if (typeof id === 'string') {
|
|
219
|
+
const name = typeof tc.name === 'string' ? tc.name : '';
|
|
220
|
+
// Signature identity + its delimiter: see toolCallSignature.
|
|
221
|
+
callById.set(id, { sig: toolCallSignature(name, tc.args), name });
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
// Walk the tail backward, counting consecutive identical signatures since the last boundary.
|
|
227
|
+
let streak = 0;
|
|
228
|
+
let currentSig;
|
|
229
|
+
let currentName = '';
|
|
230
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
231
|
+
const msg = messages[i];
|
|
232
|
+
if (ToolMessage.isInstance(msg)) {
|
|
233
|
+
const call = callById.get(msg.tool_call_id);
|
|
234
|
+
// No paired call → cannot prove a repeat; treat as a boundary (never a false trip).
|
|
235
|
+
if (!call)
|
|
236
|
+
break;
|
|
237
|
+
if (currentSig === undefined) {
|
|
238
|
+
currentSig = call.sig;
|
|
239
|
+
currentName = call.name;
|
|
240
|
+
streak = 1;
|
|
241
|
+
}
|
|
242
|
+
else if (call.sig === currentSig) {
|
|
243
|
+
streak++;
|
|
244
|
+
}
|
|
245
|
+
else {
|
|
246
|
+
break; // different signature = the model tried something else = progress
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else if (AIMessage.isInstance(msg)) {
|
|
250
|
+
continue; // the tool-call request — skip and keep counting the streak
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
break; // Human/System message: a fresh user turn resets everything.
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
if (currentSig === undefined || streak < threshold)
|
|
257
|
+
return undefined;
|
|
258
|
+
// HALT (opt-in): end the run cleanly — never a throw. Terminal, so the model is never
|
|
259
|
+
// re-invoked after this AIMessage (no prefill/role hazard). Takes precedence over WARN.
|
|
260
|
+
if (halt) {
|
|
261
|
+
const notice = `Stopped after ${streak} identical calls to the \`${currentName}\` tool with the same ` +
|
|
262
|
+
'arguments to avoid a loop that keeps spending tokens without making progress. ' +
|
|
263
|
+
'The same call cannot yield a different result: change your approach — different ' +
|
|
264
|
+
'arguments, a narrower step, or a different tool — or report the blocker to the user.';
|
|
265
|
+
return { jumpTo: 'end', messages: [new AIMessage(notice)] };
|
|
266
|
+
}
|
|
267
|
+
// WARN (default): SURFACE a user-visible notice and DO NOT touch state.messages (return
|
|
268
|
+
// undefined → the model's input is byte-for-byte unchanged, so no prefill/role hazard on any
|
|
269
|
+
// provider). Fire once per streak at the exact crossing: `streak === threshold` is a
|
|
270
|
+
// stateless "fire once" — a still-looping streak (streak > threshold) stays quiet, while an
|
|
271
|
+
// interrupted-then-resumed loop re-reaches threshold and surfaces again.
|
|
272
|
+
if (warn && streak === threshold) {
|
|
273
|
+
onWarn?.(`Tool-loop guard: the agent has called \`${currentName}\` with the same arguments ` +
|
|
274
|
+
`${streak} times without new progress. It may be stuck — consider interrupting and ` +
|
|
275
|
+
'refining the request.');
|
|
276
|
+
}
|
|
277
|
+
return undefined;
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
});
|
|
281
|
+
}
|
|
9
282
|
/**
|
|
10
283
|
* Lean agent: builds a standard `createAgent` (ReAct) graph. All run/stream/event
|
|
11
284
|
* plumbing lives in {@link GthAbstractAgent}; this class only knows how to construct
|
|
12
285
|
* the graph in {@link init}.
|
|
13
286
|
*/
|
|
14
287
|
export class GthLangChainAgent extends GthAbstractAgent {
|
|
15
|
-
async init(command, configIn, checkpointer) {
|
|
288
|
+
async init(command, configIn, checkpointer, options) {
|
|
16
289
|
this.command = command;
|
|
290
|
+
// GS2-95 — the header's name for this run, when the command supplied one. Read by
|
|
291
|
+
// `compactHeaderStatus` and by nothing else; it deliberately does NOT feed `this.command`,
|
|
292
|
+
// which selects the mode prompt.
|
|
293
|
+
this.displayCommand = options?.displayCommand;
|
|
17
294
|
debugLog(`GthLangChainAgent.init called with command: ${command || 'default'}`);
|
|
18
295
|
// Merge command-specific filesystem config if provided
|
|
19
296
|
this.config = this.getEffectiveConfig(configIn, command);
|
|
@@ -23,16 +300,20 @@ export class GthLangChainAgent extends GthAbstractAgent {
|
|
|
23
300
|
streamOutput: this.config.streamOutput,
|
|
24
301
|
debugLog: this.config.debugLog,
|
|
25
302
|
});
|
|
26
|
-
|
|
303
|
+
// GS2-93: the run header opens here. Exactly one of these two speaks, decided by the rung —
|
|
304
|
+
// `compact` emits the attribution line and nothing else, every `headerStatus` below is the
|
|
305
|
+
// `debug` rung's preamble, and `none` silences both.
|
|
306
|
+
this.compactHeaderStatus();
|
|
307
|
+
this.headerStatus(`Workdir: ${getCurrentWorkDir()}`);
|
|
27
308
|
if (this.config.modelDisplayName) {
|
|
28
|
-
this.
|
|
309
|
+
this.headerStatus(`Model: ${this.config.modelDisplayName}`);
|
|
29
310
|
}
|
|
30
311
|
// An empty allowedTools allow-list disables every tool. Skip resolution entirely so we
|
|
31
312
|
// don't contact MCP servers (and trigger OAuth) just to discard the result.
|
|
32
313
|
const allowedTools = this.config.allowedTools;
|
|
33
314
|
const toolsDisabled = Array.isArray(allowedTools) && allowedTools.length === 0;
|
|
34
315
|
if (toolsDisabled) {
|
|
35
|
-
this.
|
|
316
|
+
this.headerStatus('Tool loading disabled by allowedTools: []; MCP/A2A servers will not be contacted. Omit allowedTools for no filtering.');
|
|
36
317
|
}
|
|
37
318
|
// Resolve tools via resolver or fall back to config tools only
|
|
38
319
|
debugLog('Resolving tools...');
|
|
@@ -48,19 +329,20 @@ export class GthLangChainAgent extends GthAbstractAgent {
|
|
|
48
329
|
// Combine all tools, then apply the allowedTools name allow-list when configured.
|
|
49
330
|
let tools = [...resolvedTools, ...flattenedConfigTools];
|
|
50
331
|
if (Array.isArray(allowedTools)) {
|
|
51
|
-
|
|
52
|
-
//
|
|
53
|
-
// as Anthropic web search) may have no `name`, so
|
|
54
|
-
// allow-list - drop-by-default would silently remove
|
|
55
|
-
// nameless tools instead; the allow-list is a name-based
|
|
56
|
-
|
|
332
|
+
// Filter named tools by the allow-list. Entries match by exact name, or glob-style when
|
|
333
|
+
// they contain `*` (e.g. `mcp__unimarket__*`) — see isToolAllowed. ServerTools
|
|
334
|
+
// (provider-native "magic objects" such as Anthropic web search) may have no `name`, so
|
|
335
|
+
// they can never be referenced in the allow-list - drop-by-default would silently remove
|
|
336
|
+
// them with no recourse. Retain such nameless tools instead; the allow-list is a name-based
|
|
337
|
+
// filter and cannot target them.
|
|
338
|
+
tools = tools.filter((tool) => !tool.name || isToolAllowed(tool.name, allowedTools));
|
|
57
339
|
}
|
|
58
340
|
if (tools.length > 0) {
|
|
59
341
|
const toolNames = tools
|
|
60
342
|
.map((tool) => tool.name)
|
|
61
343
|
.filter((name) => name)
|
|
62
344
|
.join(', ');
|
|
63
|
-
this.
|
|
345
|
+
this.headerStatus(`Loaded tools: ${toolNames}`);
|
|
64
346
|
debugLog(`Total tools available: ${tools.length}`);
|
|
65
347
|
debugLogObject('All Tools', toolNames.split(', '));
|
|
66
348
|
}
|
|
@@ -88,8 +370,39 @@ export class GthLangChainAgent extends GthAbstractAgent {
|
|
|
88
370
|
return state;
|
|
89
371
|
},
|
|
90
372
|
});
|
|
91
|
-
// EXT-
|
|
92
|
-
//
|
|
373
|
+
// EXT-35: promote a text-emitted tool call to a native tool_call so the loop doesn't stall.
|
|
374
|
+
// Small/local models (Gemma, lmstudio, gpt-oss) often serialise a tool call as assistant TEXT
|
|
375
|
+
// instead of a native `tool_call`; the ReAct router then sees no tool_calls on the last message
|
|
376
|
+
// and ENDS the turn ("no tool calls = done"). This afterModel hook runs ONLY when the last
|
|
377
|
+
// AIMessage carries no native tool_calls (the native happy path is byte-for-byte untouched):
|
|
378
|
+
// it parses a STANDALONE text-emitted call (bracket / <function=…> / Harmony), gated HARD by the
|
|
379
|
+
// bound-tool allow-list + a payload-size cap + standalone-only, and — when it promotes — returns
|
|
380
|
+
// the rewritten message. Preserving the original message id is load-bearing: LangGraph's
|
|
381
|
+
// message-state reducer merges by id, so a same-id message REPLACES the model's text message in
|
|
382
|
+
// graph state; the router then sees the native tool_calls and routes to the tools node, so the
|
|
383
|
+
// loop continues instead of concluding done. Ported from the openclaw tool-call-repair reference.
|
|
384
|
+
// Bound-tool names are the allow-list; an empty toolset promotes nothing (prose-safe default).
|
|
385
|
+
const repairToolNames = new Set(tools.map((t) => t.name).filter((name) => Boolean(name)));
|
|
386
|
+
const toolCallRepairMiddleware = createMiddleware({
|
|
387
|
+
name: 'GthMiddlewareToolCallRepair',
|
|
388
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
389
|
+
afterModel: (state) => {
|
|
390
|
+
const lastMessage = state.messages[state.messages.length - 1];
|
|
391
|
+
if (!AIMessage.isInstance(lastMessage))
|
|
392
|
+
return state;
|
|
393
|
+
if (lastMessage.tool_calls && lastMessage.tool_calls.length > 0)
|
|
394
|
+
return state;
|
|
395
|
+
const promoted = promoteTextEmittedToolCallMessage(lastMessage, {
|
|
396
|
+
allowedToolNames: repairToolNames,
|
|
397
|
+
});
|
|
398
|
+
if (!promoted)
|
|
399
|
+
return state;
|
|
400
|
+
debugLog(`Repaired a text-emitted tool call into a native tool_call: ${formatToolCalls(promoted.tool_calls ?? [])}`);
|
|
401
|
+
// Replace-by-id (same id) so the reducer swaps the text message rather than appending.
|
|
402
|
+
return { messages: [promoted] };
|
|
403
|
+
},
|
|
404
|
+
});
|
|
405
|
+
// EXT-21: `exec` / `ask --write` route through this `createAgent` graph, whose run_* shell/dev
|
|
93
406
|
// tools (GthDevToolkit.executeCommand) THROW a ShellCommandFailedError on a non-zero exit or a
|
|
94
407
|
// timeout-kill. langchain's default ToolNode would catch that throw into a ToolMessage but leave
|
|
95
408
|
// it status:'success' (✓) — misreporting a failed command. Catch it here at the tool-wrap layer
|
|
@@ -121,26 +434,286 @@ export class GthLangChainAgent extends GthAbstractAgent {
|
|
|
121
434
|
}
|
|
122
435
|
},
|
|
123
436
|
});
|
|
437
|
+
// MCP tool-execution errors are spec-compliant RESULTS, not fatal faults. Per the MCP spec
|
|
438
|
+
// (2025-11-25 & draft, "Server › Tools › Error Handling"), a tool that hits an API failure, an
|
|
439
|
+
// input-validation problem, or a business-logic error (e.g. a disabled capability) returns a
|
|
440
|
+
// normal tools/call result with `isError: true`, and the CLIENT *SHOULD* hand that error to the
|
|
441
|
+
// model so it can self-correct. `@langchain/mcp-adapters` instead surfaces such a result by
|
|
442
|
+
// THROWING a ToolException at call time (its `_convertCallToolResult`). Because we install a
|
|
443
|
+
// wrapToolCall middleware, langchain's ToolNode treats any error a middleware rethrows as a fatal
|
|
444
|
+
// "middleware error" (`errorFromMiddleware && handleToolErrors !== true` → throw) and aborts the
|
|
445
|
+
// whole turn instead of relaying the error to the model — the opposite of the spec's client
|
|
446
|
+
// SHOULD. This middleware closes that gap: it catches a thrown ToolException and RETURNS it as a
|
|
447
|
+
// status:'error' ToolMessage (→ isError → ✗), so the model observes the error and can retry or
|
|
448
|
+
// explain (matching the non-stream invoke path's ToolException handling). Scope & safety: matched
|
|
449
|
+
// by name === 'ToolException' (the adapter's marker), so GraphInterrupt and every non-MCP throw
|
|
450
|
+
// fall through the final rethrow untouched. The adapter ALSO wraps a call-time AbortError into a
|
|
451
|
+
// ToolException (its `_callTool` catch-all), so we RETHROW when the run's abort signal is set —
|
|
452
|
+
// otherwise softening here would swallow user cancellation that ToolNode's own `signal?.aborted`
|
|
453
|
+
// guard normally enforces (bypassed once we handle the error in middleware). MCP connect/auth
|
|
454
|
+
// (401/403) and load failures are handled at CONNECT time (resolvers.ts throwOnLoadError +
|
|
455
|
+
// onConnectionError), not here, so they stay fatal as intended.
|
|
456
|
+
const mcpToolErrorSoftening = createMiddleware({
|
|
457
|
+
name: 'GthMcpToolErrorSoftening',
|
|
458
|
+
wrapToolCall: async (request, handler) => {
|
|
459
|
+
try {
|
|
460
|
+
return await handler(request);
|
|
461
|
+
}
|
|
462
|
+
catch (e) {
|
|
463
|
+
if (e instanceof Error &&
|
|
464
|
+
e.name === 'ToolException' &&
|
|
465
|
+
!request.runtime?.signal?.aborted) {
|
|
466
|
+
debugLog(`Softened MCP tool error into an error ToolMessage: ${e.message}`);
|
|
467
|
+
return new ToolMessage({
|
|
468
|
+
content: e.message,
|
|
469
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
470
|
+
tool_call_id: request.toolCall?.id ?? '',
|
|
471
|
+
status: 'error',
|
|
472
|
+
});
|
|
473
|
+
}
|
|
474
|
+
throw e;
|
|
475
|
+
}
|
|
476
|
+
},
|
|
477
|
+
});
|
|
478
|
+
// Debug-capture middleware (TUI `/debug` panel); the contract lives in core's debugCapture.
|
|
479
|
+
// Always installed but lazy: it reads `this.debugCapture` per call, so until the TUI attaches a
|
|
480
|
+
// sink it is a transparent pass-through (one extra await around the handler — the normal path
|
|
481
|
+
// pays nothing). `request.messages` is the real history at call time; `handler(request)`
|
|
482
|
+
// resolves to the AIMessage response. Without this, the TUI's System-prompt/Tools/Chat-history
|
|
483
|
+
// tabs stay empty on the (now default) lean backend.
|
|
484
|
+
const getDebugCapture = () => this.debugCapture;
|
|
485
|
+
const debugCaptureMiddleware = createMiddleware({
|
|
486
|
+
name: 'GthMiddlewareDebugCapture',
|
|
487
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
488
|
+
wrapModelCall: async (request, handler) => {
|
|
489
|
+
// GS2-56: stash the always-on last-model-request snapshot (extras + as-sent messages)
|
|
490
|
+
// UNCONDITIONALLY — before the `capture` short-circuit — so `/debug-dump` has the full
|
|
491
|
+
// model input even when no TUI `/debug` sink is attached (a non-TUI surface, or `/debug`
|
|
492
|
+
// never opened). Guarded: snapshotting must never break the run. The computed extras are
|
|
493
|
+
// reused for the sink below so extraction runs once.
|
|
494
|
+
let extras;
|
|
495
|
+
try {
|
|
496
|
+
extras = extractDebugRequestExtras(request);
|
|
497
|
+
this.setLastModelRequest(request.messages, extras);
|
|
498
|
+
}
|
|
499
|
+
catch {
|
|
500
|
+
/* the always-on snapshot must never break the run */
|
|
501
|
+
}
|
|
502
|
+
const capture = getDebugCapture();
|
|
503
|
+
if (!capture)
|
|
504
|
+
return handler(request);
|
|
505
|
+
try {
|
|
506
|
+
capture.onRequest?.(request.messages, extras);
|
|
507
|
+
}
|
|
508
|
+
catch {
|
|
509
|
+
/* a debug sink must never break the run */
|
|
510
|
+
}
|
|
511
|
+
const response = await handler(request);
|
|
512
|
+
try {
|
|
513
|
+
capture.onResponse?.(response);
|
|
514
|
+
}
|
|
515
|
+
catch {
|
|
516
|
+
/* a debug sink must never break the run */
|
|
517
|
+
}
|
|
518
|
+
return response;
|
|
519
|
+
},
|
|
520
|
+
});
|
|
124
521
|
// shellExitSoftening FIRST so it is the outermost wrapToolCall — it must see the raw
|
|
125
522
|
// ShellCommandFailedError throw before any user-configured middleware could transform it.
|
|
126
|
-
|
|
127
|
-
|
|
523
|
+
// mcpToolErrorSoftening sits right after it, still outboard of any user-configured middleware so
|
|
524
|
+
// it sees the raw ToolException before a user wrapToolCall could transform it. Order between the
|
|
525
|
+
// two softeners is not load-bearing: they catch DISJOINT conditions (a ShellCommandFailedError
|
|
526
|
+
// vs a name==='ToolException') and each rethrows what it doesn't recognize, so neither can
|
|
527
|
+
// swallow the other.
|
|
528
|
+
// EXT-35: toolCallRepairMiddleware sits AFTER toolCallStatusMiddleware in the array. afterModel
|
|
529
|
+
// nodes execute in reverse array order (the later one runs first), so repair runs BEFORE the
|
|
530
|
+
// status middleware — a promoted call is therefore reported by the "Requested tools:" line too.
|
|
531
|
+
// Correctness (routing) is order-independent: the router reads final graph state after all
|
|
532
|
+
// afterModel nodes, and repair replaces-by-id, so the promoted tool_calls are present regardless.
|
|
533
|
+
// GS2-36: cap a self-inflicted tool-error loop. The shell/MCP softeners above turn a failed
|
|
534
|
+
// run_*/MCP call into a status:'error' ToolMessage the model observes; a model that keeps
|
|
535
|
+
// re-issuing the same failing call would drain tokens turn after turn. This beforeModel guard
|
|
536
|
+
// ends the run gracefully once MAX_CONSECUTIVE_TOOL_ERRORS such results accrue with no successful
|
|
537
|
+
// tool result in between — a tighter, error-specific complement to createAgent's coarse
|
|
538
|
+
// recursionLimit (loop DETECTION proper is the separate EXT-36). Placed after the softeners and
|
|
539
|
+
// before user middleware so it can't be bypassed. Lean backend only (per GS2-36 scope); the deep
|
|
540
|
+
// backend keeps its own recursionLimit backstop.
|
|
541
|
+
const toolErrorBudget = createToolErrorBudgetMiddleware();
|
|
542
|
+
// EXT-36: the ORTHOGONAL loop guard — repeated identical (tool, args) / no-progress detection,
|
|
543
|
+
// the sibling of GS2-36's error budget above. It catches the case GS2-36 explicitly leaves open:
|
|
544
|
+
// a model re-issuing the SAME call verbatim, whether it keeps erroring or keeps "succeeding" with
|
|
545
|
+
// the same result. Placed at index 3, immediately AFTER toolErrorBudget (index 2) and BEFORE user
|
|
546
|
+
// middleware: beforeModel hooks run in forward order with jumpTo short-circuiting, so on a
|
|
547
|
+
// simultaneous trip GS2-36's coarse error cap wins first and EXT-36 fires on its own
|
|
548
|
+
// signature-repeat threshold otherwise; keeping it outboard of user middleware means it can't be
|
|
549
|
+
// bypassed. WARN is on by default and SURFACES a user notice WITHOUT touching state.messages (the
|
|
550
|
+
// default path must never mutate the model's input — appending a message + re-invoking is a
|
|
551
|
+
// provider-unsafe steer, not a warn); HALT (opt-in) actively breaks the loop via a terminal
|
|
552
|
+
// jumpTo:'end'. Default WARN-ON is applied here at the read site (resolveToolLoopGuardOptions),
|
|
553
|
+
// NOT in DEFAULT_CONFIG, so the
|
|
554
|
+
// effective-config snapshot never churns.
|
|
555
|
+
// `toolLoopGuard: false` resolves to a no-op guard (still installed at index 3 so the
|
|
556
|
+
// placement is stable).
|
|
557
|
+
const toolLoopGuard = createToolLoopGuardMiddleware(resolveToolLoopGuardOptions(this.config.toolLoopGuard),
|
|
558
|
+
// WARN surfaces through the same TUI-safe status channel every other agent notice uses
|
|
559
|
+
// (renderer-consumed, never raw stdout) so it can't leak over the Ink frame (TUI-C31).
|
|
560
|
+
(message) => statusUpdate(StatusLevel.WARNING, message));
|
|
561
|
+
// EXT-52: gate the opt-in run_shell_command tool behind the per-command approval interrupt —
|
|
562
|
+
// langchain's `humanInTheLoopMiddleware`. Without it,
|
|
563
|
+
// no interrupt ever fires, so the runner's whole approval stack
|
|
564
|
+
// (`GthAgentRunner.decideToolApproval`: sessionYolo → allow-list → judge → human callback,
|
|
565
|
+
// fail-closed reject) was DEAD CODE on lean and shell commands ran unprompted. A matching tool
|
|
566
|
+
// call now suspends the graph with a HITLRequest interrupt; the runner drains it via
|
|
567
|
+
// getPendingToolInterrupts/streamResume (both backend-agnostic in GthAbstractAgent), so ONE
|
|
568
|
+
// gating code path drives both backends and the existing TUI + readline approval prompts fire
|
|
569
|
+
// identically on lean.
|
|
570
|
+
//
|
|
571
|
+
// The gate condition and its user-facing notices are the SHARED policy
|
|
572
|
+
// (`resolveShellApprovalGate`, EXT-12 semantics documented there); the interrupt itself is
|
|
573
|
+
// installed directly as middleware here.
|
|
574
|
+
const { gateShell, notice: shellGateNotice } = resolveShellApprovalGate(this.config ?? undefined, this.command);
|
|
575
|
+
//
|
|
576
|
+
// EXT-80: the shell is not the whole story. At `manual` and `write` every bound tool the
|
|
577
|
+
// rung's access class does not auto-grant — the write built-ins, MCP tools, custom tools — must
|
|
578
|
+
// reach the human, because those two rungs promise the user that anything beyond reading
|
|
579
|
+
// (respectively, beyond reading and writing files here) comes to them.
|
|
580
|
+
//
|
|
581
|
+
// **The interrupt is wired rung-INDEPENDENTLY, over every tool any rung could gate.** It is
|
|
582
|
+
// installed once, here, while `/approvals <rung>` moves the rung for the rest of the session
|
|
583
|
+
// without rebuilding this graph; a set that carried the rung would be frozen at the rung the
|
|
584
|
+
// session started on, and since the default is `assisted`, typing `/approvals manual` would
|
|
585
|
+
// leave exactly the write tools ungated. `GthAgentRunner.decideToolApproval` decides on the rung
|
|
586
|
+
// in force instead, which is where the rung has always been read — so wiring wider does not gate
|
|
587
|
+
// wider: at a rated rung a non-shell call is approved there with no rating call and no prompt.
|
|
588
|
+
//
|
|
589
|
+
// Both sets come from core's shared policy, which the runner also calls, so
|
|
590
|
+
// the two cannot disagree; and both read the FINAL tool array below rather than any
|
|
591
|
+
// static list, because a hand-written list cannot contain an MCP or custom tool, which is
|
|
592
|
+
// exactly what has to escalate.
|
|
593
|
+
const rung = resolveApprovals(this.config ?? undefined, this.command).rung;
|
|
594
|
+
const boundToolNames = tools
|
|
595
|
+
.map((tool) => tool?.name)
|
|
596
|
+
.filter((name) => typeof name === 'string' && name.length > 0);
|
|
597
|
+
// **What a surface that answers no approval gets — for BOTH sets below.** An interrupt nobody
|
|
598
|
+
// can answer suspends the graph forever: the tool never runs and the client is never asked. So
|
|
599
|
+
// such a surface is wired with exactly what the shell gate itself requires and nothing more,
|
|
600
|
+
// and is not TOLD it will be asked either. Neither the live set nor the interrupt set is a safe
|
|
601
|
+
// fallback here — both are non-empty at `manual` and `write`, which is precisely where an
|
|
602
|
+
// AG-UI server's writes and MCP calls would vanish, or be announced as approvable when nothing
|
|
603
|
+
// will ever approve them.
|
|
604
|
+
const answersApprovals = commandAnswersApprovals(this.command);
|
|
605
|
+
const noDrainTools = gateShell ? [SHELL_TOOL_NAME] : [];
|
|
606
|
+
// The LIVE gated set — what THIS rung gates — for the §4.5 tool descriptions below. Narrower
|
|
607
|
+
// than the interrupt set at the rated rungs, and it must stay so: a description promising an
|
|
608
|
+
// approval the runner will not ask for is the drift §4.5 calls worse than no description.
|
|
609
|
+
const gatedTools = answersApprovals
|
|
610
|
+
? resolveGatedToolNames({ rung, gateShell, boundToolNames })
|
|
611
|
+
: noDrainTools;
|
|
612
|
+
// Rung-independent ONLY where something answers the interrupt.
|
|
613
|
+
const interruptTools = answersApprovals
|
|
614
|
+
? resolveInterruptToolNames({ gateShell, boundToolNames })
|
|
615
|
+
: noDrainTools;
|
|
616
|
+
// Installed on the interrupt SET, not on `gateShell`: at a deterministic rung there is a gate to
|
|
617
|
+
// install even when the shell tool is disabled or the command emits no dev tools (a plain
|
|
618
|
+
// `chat` session with MCP servers). Keying the install off `gateShell` there would leave every
|
|
619
|
+
// one of those tools ungated while the rung's description promised otherwise.
|
|
620
|
+
const approvalMiddleware = interruptTools.length > 0
|
|
621
|
+
? [
|
|
622
|
+
humanInTheLoopMiddleware({
|
|
623
|
+
interruptOn: Object.fromEntries(interruptTools.map((name) => [
|
|
624
|
+
name,
|
|
625
|
+
{ allowedDecisions: ['approve', 'reject'] },
|
|
626
|
+
])),
|
|
627
|
+
}),
|
|
628
|
+
]
|
|
629
|
+
: [];
|
|
630
|
+
if (shellGateNotice) {
|
|
631
|
+
this.statusUpdate(shellGateNotice.level, shellGateNotice.message);
|
|
632
|
+
}
|
|
633
|
+
// EXT-58 (spec §4.5) — state the approvals posture where the model reads it: on the tool
|
|
634
|
+
// descriptions themselves. Every tool NOT auto-approved at the resolved rung gets the rung's
|
|
635
|
+
// sentence appended; every granted tool keeps its description exactly as written, because the
|
|
636
|
+
// ABSENCE of the sentence is what marks it free. `gatedTools` is the LIVE set for the rung in
|
|
637
|
+
// force — narrower than the interrupt set above, which covers every rung so the rung can still
|
|
638
|
+
// move — so a description can never promise an approval this rung will not ask for. Applied
|
|
639
|
+
// after the allowedTools filter and before createAgent, so the model only ever sees the final,
|
|
640
|
+
// suffixed set.
|
|
641
|
+
this.registerApprovalsAwareTools(tools, { rung, gatedTools });
|
|
642
|
+
// EXT-52 placement note: the HITL gate sits EARLY in the array — before user-configured
|
|
643
|
+
// middleware and, crucially, before toolCallRepairMiddleware — because afterModel hooks run in
|
|
644
|
+
// REVERSE array order (the EXT-35 rule above). The gate's afterModel therefore executes LAST,
|
|
645
|
+
// after EXT-35's repair has promoted a text-emitted `run_shell_command` into a native
|
|
646
|
+
// tool_call, so a small local model that serialises the call as text is gated too (were the
|
|
647
|
+
// gate appended last it would run FIRST and a promoted shell call would bypass approval
|
|
648
|
+
// entirely).
|
|
649
|
+
const middleware = [
|
|
650
|
+
shellExitSoftening,
|
|
651
|
+
mcpToolErrorSoftening,
|
|
652
|
+
toolErrorBudget,
|
|
653
|
+
toolLoopGuard,
|
|
654
|
+
...approvalMiddleware,
|
|
655
|
+
...configuredMiddleware,
|
|
656
|
+
toolCallStatusMiddleware,
|
|
657
|
+
toolCallRepairMiddleware,
|
|
658
|
+
debugCaptureMiddleware,
|
|
659
|
+
];
|
|
660
|
+
this.headerStatus(`Loaded middleware: ${middleware.map((m) => m.name).join(', ')}`);
|
|
128
661
|
// GS2-21: compose gsloth's system prompt (backstory + guidelines + per-command mode prompt +
|
|
129
|
-
// system prompt)
|
|
130
|
-
// honored on the lean backend too. Previously the lean agent gave the model NO system prompt
|
|
131
|
-
// (only the deep agent composed one), so `system-prompt.md` / projectGuidelines never reached
|
|
132
|
-
// the model — the robot (agent.backend: lean) behaved as if it never got its guidelines.
|
|
662
|
+
// system prompt), so identity profiles and `.gsloth.*.md` reach the model.
|
|
133
663
|
// This is passed to createAgent as `systemPrompt`, which langchain applies as the agent's
|
|
134
664
|
// static system message on every turn — NOT injected as a separate mid-conversation
|
|
135
|
-
// SystemMessage (a non-first system message that Anthropic rejects).
|
|
136
|
-
//
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
: readChatPrompt(this.config);
|
|
665
|
+
// SystemMessage (a non-first system message that Anthropic rejects). GS2-79: which mode prompt
|
|
666
|
+
// a command gets is decided ONCE, in core's `readModePrompt` — 'code' the code-mode prompt,
|
|
667
|
+
// 'exec' the exec-mode prompt, 'review'/'pr' the REVIEW INSTRUCTIONS, chat/api/others the chat
|
|
668
|
+
// prompt — so a command left out of the selection can no longer be served the chat prompt by
|
|
669
|
+
// silent default.
|
|
670
|
+
const modePrompt = readModePrompt(this.command, this.config);
|
|
142
671
|
const systemMessages = buildSystemMessages(this.config, modePrompt);
|
|
143
|
-
const
|
|
672
|
+
const baseSystemPrompt = typeof systemMessages[0]?.content === 'string' ? systemMessages[0].content : undefined;
|
|
673
|
+
// GS2-27: in `code` mode append the SHARED code-mode notes — the real-cwd / path-model note
|
|
674
|
+
// (EXT-13) and the OS + shell-dialect note (EXT-26). They are backend-agnostic (they describe
|
|
675
|
+
// the opt-in `run_shell_command` tool and the real-fs cwd), which is why they are composed from
|
|
676
|
+
// core's `systemPromptNotes` rather than inline here. Order: cwd note first, OS/shell note
|
|
677
|
+
// last. `getCurrentWorkDir()` is already read above for the status line, so the value is free.
|
|
678
|
+
// GS2-34/EXT-83: resolve the active model identity ONCE, honouring the `injectModelContext`
|
|
679
|
+
// opt-out (default ON) at this single read site. Both consumers below take this same value, so
|
|
680
|
+
// the commit trailer and the model-context note can never disagree about which model is serving
|
|
681
|
+
// the session — and the opt-out means "my model identity stays out of the prompt", which covers
|
|
682
|
+
// the trailer as much as the identity line.
|
|
683
|
+
const modelIdentity = this.config.injectModelContext !== false ? resolveModelIdentity(this.config) : undefined;
|
|
684
|
+
// GS2-35: also append the commit co-authoring rule so the agent credits Gaunt Sloth (config
|
|
685
|
+
// `commit.coAuthor`, defaulting to the Gaunt Sloth account) in the `Co-Authored-By` trailer, and
|
|
686
|
+
// the EXT-83 commit-message rules (plain English, and passed by file — never inline, where the
|
|
687
|
+
// shell would expand the message before git runs). Same code-mode gate as the shell/cwd notes —
|
|
688
|
+
// the git-commit capability rides on `run_shell_command`, which is a code-mode tool.
|
|
689
|
+
// EXT-84: the effective `filesystem` is threaded in so the note names the writing tool only
|
|
690
|
+
// where that tool is registered. `this.config` is the command-merged value (getEffectiveConfig,
|
|
691
|
+
// above) — the SAME value handed to the tool resolver, so the note and the registered toolset
|
|
692
|
+
// cannot disagree.
|
|
693
|
+
const codeNotesPrompt = this.command === 'code'
|
|
694
|
+
? appendCommitCoAuthorNote(appendOsShellNote(appendCwdNote(baseSystemPrompt, getCurrentWorkDir())), this.config.commit?.coAuthor, modelIdentity, this.config.filesystem)
|
|
695
|
+
: baseSystemPrompt;
|
|
696
|
+
// GS2-34: inject the resolved provider:model identity so the agent knows which model is serving
|
|
697
|
+
// it (to answer "what model are you?" and reason about its own capabilities/limits). Composed
|
|
698
|
+
// OUTSIDE the code-mode gate above — unlike the cwd/os-shell/commit notes, that question can
|
|
699
|
+
// arise in ANY mode (chat/ask/code/exec), so the identity must be visible everywhere. The
|
|
700
|
+
// `injectModelContext` opt-out is applied at the single read site above; when it is off — or
|
|
701
|
+
// when no model resolves — `modelIdentity` is undefined, nothing is appended, and the prompt is
|
|
702
|
+
// exactly as before. GS2-6's capability note is a deferred follow-up (bare provider:model
|
|
703
|
+
// identity only for now).
|
|
704
|
+
const modelContextPrompt = appendModelContextNote(codeNotesPrompt, modelIdentity);
|
|
705
|
+
// EXT-32: inject each connected MCP server's discovery `instructions` (captured during tool
|
|
706
|
+
// resolution) into the prompt — fenced + per-server-labelled as untrusted server-provided
|
|
707
|
+
// context. Mode-independent: MCP tools load in every mode, so their usage guidance applies in
|
|
708
|
+
// every mode (not just `code`). Empty/absent capture (or a resolver without the accessor) adds
|
|
709
|
+
// nothing. Composed through the shared path in core so any backend reaches it alike.
|
|
710
|
+
// When tools are disabled, resolveTools is skipped entirely (no MCP contact), so a REUSED
|
|
711
|
+
// resolver could still hold a prior run's capture — gate on toolsDisabled so no stale
|
|
712
|
+
// instructions leak into a tools-disabled session.
|
|
713
|
+
const mcpInstructions = toolsDisabled
|
|
714
|
+
? []
|
|
715
|
+
: (this.resolvers?.getMcpServerInstructions?.() ?? []);
|
|
716
|
+
const systemPrompt = appendMcpServerInstructionsNote(modelContextPrompt, mcpInstructions);
|
|
144
717
|
// Create agent with configured middleware. Only pass systemPrompt when non-empty so we never
|
|
145
718
|
// hand createAgent an empty system message.
|
|
146
719
|
this.agent = createAgent({
|