mirror of
https://github.com/binaricat/Netcatty.git
synced 2026-11-26 10:53:56 +00:00
feat(ai): make tool call output truncation limit configurable in AI settings
This commit is contained in:
1 parent
2ddb6f2bee
commit
8ef6734445
38 files changed
+811
-19
No files matched your search
@@ -722,6 +722,9 @@ export const enAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'sec',
|
||||
'ai.safety.maxIterations': 'Max Iterations',
|
||||
'ai.safety.maxIterations.description': 'Maximum number of AI tool-use loops to prevent runaway execution. External agents may have their own internal iteration limits that take precedence.',
|
||||
'ai.safety.toolOutputMaxChars': 'Built-in AI Tool Output Limit',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Maximum characters kept inline per built-in AI tool result (such as terminal commands or SFTP reads) before truncating and spilling the full output to a saved handle (2,000–200,000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'chars',
|
||||
'ai.safety.blocklist': 'Command Blocklist',
|
||||
'ai.safety.blocklist.description': 'Regex patterns to block dangerous commands executed through Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Regex pattern...',
|
||||
|
||||
@@ -722,6 +722,9 @@ export const esAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'seg',
|
||||
'ai.safety.maxIterations': 'Máximo de iteraciones',
|
||||
'ai.safety.maxIterations.description': 'Máximo de bucles de uso de herramientas de IA para evitar una ejecución descontrolada. Los agentes externos pueden tener sus propios límites de iteración internos que tienen prioridad.',
|
||||
'ai.safety.toolOutputMaxChars': 'Límite de salida de herramientas de IA integrada',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Máximo de caracteres que se mantienen en línea por resultado de herramienta de la IA integrada (como comandos de terminal o lecturas SFTP) antes de truncar y guardar la salida completa en un identificador (2,000–200,000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'car.',
|
||||
'ai.safety.blocklist': 'Lista de bloqueo de comandos',
|
||||
'ai.safety.blocklist.description': 'Patrones regex para bloquear comandos peligrosos ejecutados mediante Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Patrón regex...',
|
||||
|
||||
@@ -210,3 +210,21 @@ test("managed group delete warning mentions SSH config backup in every locale",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("AI tool output limit settings copy is localized across all five locales", () => {
|
||||
const keys = [
|
||||
"ai.safety.toolOutputMaxChars",
|
||||
"ai.safety.toolOutputMaxChars.description",
|
||||
"ai.safety.toolOutputMaxChars.unit",
|
||||
] as const;
|
||||
for (const [locale, messages] of Object.entries(ALL_LOCALES)) {
|
||||
for (const key of keys) {
|
||||
assert.ok(messages[key]?.trim(), `${locale}: missing ${key}`);
|
||||
if (locale !== "en") {
|
||||
assert.notEqual(messages[key], en[key], `${locale}: ${key} should be translated`);
|
||||
}
|
||||
}
|
||||
}
|
||||
assert.match(zhTW["ai.safety.toolOutputMaxChars.description"], /傳回/);
|
||||
assert.equal(zhTW["ai.safety.toolOutputMaxChars.description"].includes("返回"), false);
|
||||
});
|
||||
@@ -661,6 +661,9 @@ export const ruAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': 'с',
|
||||
'ai.safety.maxIterations': 'Макс. число итераций',
|
||||
'ai.safety.maxIterations.description': 'Максимальное число циклов использования инструментов AI, чтобы предотвратить бесконтрольное выполнение. У внешних агентов могут быть собственные внутренние лимиты итераций, имеющие приоритет.',
|
||||
'ai.safety.toolOutputMaxChars': 'Лимит вывода инструментов встроенного ИИ',
|
||||
'ai.safety.toolOutputMaxChars.description': 'Максимум символов, оставляемых напрямую в результате инструмента встроенного ИИ (например, вывода команд терминала или чтения SFTP) до обрезки и сохранения полного вывода в дескриптор (2 000–200 000).',
|
||||
'ai.safety.toolOutputMaxChars.unit': 'симв.',
|
||||
'ai.safety.blocklist': 'Чёрный список команд',
|
||||
'ai.safety.blocklist.description': 'Regex-шаблоны для блокировки опасных команд. Применяется как к встроенным, так и к внешним агентам через механизм выполнения Netcatty.',
|
||||
'ai.safety.blocklist.placeholder': 'Regex-шаблон...',
|
||||
|
||||
@@ -722,6 +722,9 @@ export const zhCNAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': '秒',
|
||||
'ai.safety.maxIterations': '最大迭代次数',
|
||||
'ai.safety.maxIterations.description': '防止 AI 失控执行的最大工具调用循环次数。外部 Agent 可能有自己的内部迭代限制,以其为准。',
|
||||
'ai.safety.toolOutputMaxChars': '内置 AI 工具输出限制',
|
||||
'ai.safety.toolOutputMaxChars.description': '内置 AI 单次工具调用(如终端命令或 SFTP 读取)直接返回的最大字符数,超出后会截断并将完整结果保存为可读取的句柄(2,000–200,000)。',
|
||||
'ai.safety.toolOutputMaxChars.unit': '字符',
|
||||
'ai.safety.blocklist': '命令黑名单',
|
||||
'ai.safety.blocklist.description': '用于拦截通过 Netcatty 执行的危险命令的正则表达式。',
|
||||
'ai.safety.blocklist.placeholder': '正则表达式...',
|
||||
|
||||
@@ -721,6 +721,9 @@ export const zhTWAiMessages: Messages = {
|
||||
'ai.safety.responseIdleTimeout.unit': '秒',
|
||||
'ai.safety.maxIterations': '最大迭代次數',
|
||||
'ai.safety.maxIterations.description': '防止 AI 失控執行的最大工具呼叫迴圈次數。外部 Agent 可能有自己的內部迭代限制,以其為準。',
|
||||
'ai.safety.toolOutputMaxChars': '內建 AI 工具輸出上限',
|
||||
'ai.safety.toolOutputMaxChars.description': '內建 AI 單次工具呼叫(例如終端機指令或 SFTP 讀取)直接傳回的最大字元數,超出時會截斷並將完整輸出儲存為可讀取的控制碼(2,000–200,000)。',
|
||||
'ai.safety.toolOutputMaxChars.unit': '字元',
|
||||
'ai.safety.blocklist': '指令黑名單',
|
||||
'ai.safety.blocklist.description': '用於攔截透過 Netcatty 執行的危險指令的正規表示式。',
|
||||
'ai.safety.blocklist.placeholder': '正規表示式...',
|
||||
|
||||
@@ -116,6 +116,7 @@ export interface SendToCattyContext {
|
||||
commandBlocklist?: string[];
|
||||
commandTimeout?: number;
|
||||
responseIdleTimeout?: number;
|
||||
toolOutputMaxChars?: number;
|
||||
terminalSessions: TerminalSessionInfo[];
|
||||
webSearchConfig?: WebSearchConfig | null;
|
||||
getExecutorContext?: () => ExecutorContext;
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
STORAGE_KEY_AI_SESSION_MESSAGE_CAP,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
@@ -39,6 +40,10 @@ import {
|
||||
DEFAULT_AI_SESSION_MESSAGE_CAP,
|
||||
normalizeAiSessionMessageCap,
|
||||
} from '../../domain/aiSessionMessageCap';
|
||||
import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import { AI_STATE_CHANGED_EVENT, emitAIStateChanged } from './aiStateEvents';
|
||||
import { getAIBridge } from './aiStateSnapshots';
|
||||
import { useStoredBoolean } from './useStoredBoolean';
|
||||
@@ -92,6 +97,12 @@ export function useAISettingsState() {
|
||||
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
|
||||
);
|
||||
const [toolOutputMaxChars, setToolOutputMaxCharsRaw] = useState<number>(() =>
|
||||
normalizeAiToolOutputMaxChars(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
)
|
||||
);
|
||||
const [aiSessionMessageCap, setAiSessionMessageCapRaw] = useState<number>(() =>
|
||||
normalizeAiSessionMessageCap(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_SESSION_MESSAGE_CAP)
|
||||
@@ -208,6 +219,12 @@ export function useAISettingsState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(value);
|
||||
}, []);
|
||||
|
||||
const setToolOutputMaxChars = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiToolOutputMaxChars(value);
|
||||
setToolOutputMaxCharsRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS, normalizedValue);
|
||||
}, []);
|
||||
|
||||
const setAiSessionMessageCap = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiSessionMessageCap(value);
|
||||
setAiSessionMessageCapRaw(normalizedValue);
|
||||
@@ -294,6 +311,13 @@ export function useAISettingsState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS: {
|
||||
const limit = localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS;
|
||||
if (!Number.isFinite(limit)) break;
|
||||
setToolOutputMaxCharsRaw(normalizeAiToolOutputMaxChars(limit));
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_SESSION_MESSAGE_CAP:
|
||||
setAiSessionMessageCapRaw(
|
||||
normalizeAiSessionMessageCap(
|
||||
@@ -365,6 +389,8 @@ export function useAISettingsState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
webSearchConfig,
|
||||
@@ -400,6 +426,8 @@ export function useAISettingsState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
webSearchConfig,
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
STORAGE_KEY_AI_SESSIONS,
|
||||
STORAGE_KEY_AI_SESSIONS_OVERFLOW,
|
||||
STORAGE_KEY_AI_SESSIONS_DISK_OVERFLOW,
|
||||
@@ -45,6 +46,10 @@ import {
|
||||
normalizeCommandTimeoutSeconds,
|
||||
normalizeResponseIdleTimeoutSeconds,
|
||||
} from '../../infrastructure/ai/types';
|
||||
import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from '../../domain/aiToolOutputLimit';
|
||||
import {
|
||||
activateDraftView,
|
||||
clearScopeDraftState,
|
||||
@@ -200,6 +205,12 @@ export function useAIState() {
|
||||
const [maxIterations, setMaxIterationsRaw] = useState<number>(() =>
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS) ?? 20
|
||||
);
|
||||
const [toolOutputMaxChars, setToolOutputMaxCharsRaw] = useState<number>(() =>
|
||||
normalizeAiToolOutputMaxChars(
|
||||
localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
)
|
||||
);
|
||||
|
||||
// ── Sessions ──
|
||||
// Memory-only initial state: the primary store is IndexedDB and loads
|
||||
@@ -695,6 +706,12 @@ export function useAIState() {
|
||||
bridge?.aiMcpSetMaxIterations?.(value);
|
||||
}, []);
|
||||
|
||||
const setToolOutputMaxChars = useCallback((value: number) => {
|
||||
const normalizedValue = normalizeAiToolOutputMaxChars(value);
|
||||
setToolOutputMaxCharsRaw(normalizedValue);
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS, normalizedValue);
|
||||
}, []);
|
||||
|
||||
// ── Cross-window sync via storage events ──
|
||||
// When the settings window updates localStorage, the main window picks up changes.
|
||||
useEffect(() => {
|
||||
@@ -783,6 +800,16 @@ export function useAIState() {
|
||||
getAIBridge()?.aiMcpSetMaxIterations?.(iters);
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS: {
|
||||
const limit = localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS)
|
||||
?? DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS;
|
||||
if (!Number.isFinite(limit)) {
|
||||
console.warn('[useAIState] Cross-window sync: AI_TOOL_OUTPUT_MAX_CHARS is not a finite number, skipping');
|
||||
break;
|
||||
}
|
||||
setToolOutputMaxCharsRaw(normalizeAiToolOutputMaxChars(limit));
|
||||
break;
|
||||
}
|
||||
case STORAGE_KEY_AI_HOST_PERMISSIONS: {
|
||||
const perms = localStorageAdapter.read<HostAIPermission[]>(STORAGE_KEY_AI_HOST_PERMISSIONS);
|
||||
if (perms != null && !Array.isArray(perms)) {
|
||||
@@ -1749,6 +1776,8 @@ export function useAIState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
agentModelMap,
|
||||
setAgentModel,
|
||||
agentProviderMap,
|
||||
@@ -1816,6 +1845,8 @@ export function useAIState() {
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
agentModelMap,
|
||||
setAgentModel,
|
||||
agentProviderMap,
|
||||
|
||||
@@ -371,6 +371,7 @@ test("buildSyncPayload includes AI configuration settings", () => {
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_COMMAND_TIMEOUT, "120");
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT, "600");
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_MAX_ITERATIONS, "10");
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS, "64000");
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_AGENT_MODEL_MAP, JSON.stringify({ codex: "gpt-test" }));
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_AGENT_PROVIDER_MAP, JSON.stringify({ catty: "openai-main" }));
|
||||
localStorage.setItem(storageKeys.STORAGE_KEY_AI_AGENT_THINKING_MAP, JSON.stringify({ catty: "high" }));
|
||||
@@ -393,6 +394,7 @@ test("buildSyncPayload includes AI configuration settings", () => {
|
||||
commandTimeout: 120,
|
||||
responseIdleTimeout: 600,
|
||||
maxIterations: 10,
|
||||
toolOutputMaxChars: 64_000,
|
||||
agentModelMap: { codex: "gpt-test" },
|
||||
agentProviderMap: { catty: "openai-main" },
|
||||
agentThinkingMap: { catty: "high" },
|
||||
@@ -417,6 +419,14 @@ test("AI response wait time is syncable for auto-sync detection", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("AI tool output limit is syncable for auto-sync detection", () => {
|
||||
assert.ok(
|
||||
(SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(
|
||||
storageKeys.STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test("terminal side panel auto-open settings are syncable for auto-sync detection", () => {
|
||||
assert.ok(
|
||||
(SYNCABLE_SETTING_STORAGE_KEYS as readonly string[]).includes(
|
||||
@@ -773,6 +783,7 @@ test("applySyncPayload restores AI configuration settings", async () => {
|
||||
commandTimeout: 30,
|
||||
responseIdleTimeout: 900,
|
||||
maxIterations: 5,
|
||||
toolOutputMaxChars: 80_000,
|
||||
agentModelMap: { claude: "claude-test" },
|
||||
agentProviderMap: { catty: "anthropic-main" },
|
||||
webSearchConfig: webSearch,
|
||||
@@ -794,6 +805,7 @@ test("applySyncPayload restores AI configuration settings", async () => {
|
||||
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_AI_COMMAND_TIMEOUT), "30");
|
||||
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT), "900");
|
||||
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_AI_MAX_ITERATIONS), "5");
|
||||
assert.equal(localStorage.getItem(storageKeys.STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS), "80000");
|
||||
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_AGENT_MODEL_MAP)!), { claude: "claude-test" });
|
||||
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_AGENT_PROVIDER_MAP)!), { catty: "anthropic-main" });
|
||||
assert.deepEqual(JSON.parse(localStorage.getItem(storageKeys.STORAGE_KEY_AI_WEB_SEARCH)!), webSearch);
|
||||
|
||||
@@ -131,6 +131,7 @@ import {
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AGENT_THINKING_MAP,
|
||||
@@ -146,6 +147,7 @@ import {
|
||||
} from '../infrastructure/config/storageKeys';
|
||||
import { mergeAiSessionLists, mergeSyncPayloads, stripAiSessionDeviceState, stripAiSessionPayloadForSync } from '../domain/syncMerge';
|
||||
import { isTerminalSidePanelAutoOpenTab } from '../domain/terminalSidePanelAutoOpen';
|
||||
import { normalizeAiToolOutputMaxChars } from '../domain/aiToolOutputLimit';
|
||||
import { prepareRestoredPayloadConvergentWrites } from './convergentSyncReplica';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -361,6 +363,7 @@ export const SYNCABLE_SETTING_STORAGE_KEYS = [
|
||||
STORAGE_KEY_AI_COMMAND_TIMEOUT,
|
||||
STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT,
|
||||
STORAGE_KEY_AI_MAX_ITERATIONS,
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
STORAGE_KEY_AI_AGENT_MODEL_MAP,
|
||||
STORAGE_KEY_AI_AGENT_PROVIDER_MAP,
|
||||
STORAGE_KEY_AI_AGENT_THINKING_MAP,
|
||||
@@ -638,6 +641,10 @@ export function collectSyncableSettings(): SyncPayload['settings'] {
|
||||
}
|
||||
const maxIterations = localStorageAdapter.readNumber(STORAGE_KEY_AI_MAX_ITERATIONS);
|
||||
if (maxIterations != null && Number.isFinite(maxIterations)) ai.maxIterations = maxIterations;
|
||||
const toolOutputMaxChars = localStorageAdapter.readNumber(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
if (toolOutputMaxChars != null && Number.isFinite(toolOutputMaxChars)) {
|
||||
ai.toolOutputMaxChars = normalizeAiToolOutputMaxChars(toolOutputMaxChars);
|
||||
}
|
||||
const agentModelMap = readRecordSetting<Record<string, string>>(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
||||
if (agentModelMap) ai.agentModelMap = agentModelMap;
|
||||
const agentProviderMap = readRecordSetting<Record<string, string>>(STORAGE_KEY_AI_AGENT_PROVIDER_MAP);
|
||||
@@ -946,6 +953,12 @@ async function applySyncableSettings(
|
||||
localStorageAdapter.writeNumber(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT, ai.responseIdleTimeout);
|
||||
}
|
||||
if (ai.maxIterations != null) localStorageAdapter.writeNumber(STORAGE_KEY_AI_MAX_ITERATIONS, ai.maxIterations);
|
||||
if (ai.toolOutputMaxChars != null) {
|
||||
localStorageAdapter.writeNumber(
|
||||
STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars(ai.toolOutputMaxChars),
|
||||
);
|
||||
}
|
||||
if (ai.agentModelMap != null) localStorageAdapter.write(STORAGE_KEY_AI_AGENT_MODEL_MAP, ai.agentModelMap);
|
||||
if (ai.agentProviderMap != null) localStorageAdapter.write(STORAGE_KEY_AI_AGENT_PROVIDER_MAP, ai.agentProviderMap);
|
||||
if (ai.agentThinkingMap != null) localStorageAdapter.write(STORAGE_KEY_AI_AGENT_THINKING_MAP, ai.agentThinkingMap);
|
||||
@@ -1000,6 +1013,7 @@ function notifyAIStateAfterSync(ai: NonNullable<SyncPayload['settings']>['ai']):
|
||||
if (ai.commandTimeout != null) touched.push(STORAGE_KEY_AI_COMMAND_TIMEOUT);
|
||||
if (ai.responseIdleTimeout != null) touched.push(STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT);
|
||||
if (ai.maxIterations != null) touched.push(STORAGE_KEY_AI_MAX_ITERATIONS);
|
||||
if (ai.toolOutputMaxChars != null) touched.push(STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
if (ai.agentModelMap != null) touched.push(STORAGE_KEY_AI_AGENT_MODEL_MAP);
|
||||
if (ai.agentThinkingMap != null) touched.push(STORAGE_KEY_AI_AGENT_THINKING_MAP);
|
||||
// agentProviderMap is *always* potentially mutated because the reconcile
|
||||
|
||||
@@ -305,6 +305,18 @@ test('AI side panel re-renders when response wait time changes', () => {
|
||||
), false);
|
||||
});
|
||||
|
||||
test('AI side panel re-renders when tool output limit changes', () => {
|
||||
const props = baseProps({
|
||||
isVisible: true,
|
||||
toolOutputMaxChars: 24_000,
|
||||
});
|
||||
|
||||
assert.equal(aiChatSidePanelPropsAreEqual(
|
||||
props,
|
||||
{ ...props, toolOutputMaxChars: 64_000 },
|
||||
), false);
|
||||
});
|
||||
|
||||
test('AI side panel skips re-render when only a sibling scope session object changes', () => {
|
||||
const own = session({ id: 'session-1', scope: { type: 'terminal', targetId: 'terminal-1' } });
|
||||
const siblingA = session({ id: 'session-2', scope: { type: 'terminal', targetId: 'terminal-2' } });
|
||||
|
||||
@@ -320,6 +320,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
commandTimeout,
|
||||
responseIdleTimeout,
|
||||
maxIterations = 20,
|
||||
toolOutputMaxChars,
|
||||
webSearchConfig,
|
||||
quickMessages = [],
|
||||
scopeType,
|
||||
@@ -1922,6 +1923,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
commandBlocklist,
|
||||
commandTimeout,
|
||||
responseIdleTimeout,
|
||||
toolOutputMaxChars,
|
||||
terminalSessions,
|
||||
webSearchConfig,
|
||||
getExecutorContext: () => buildExecutorContextForScope(toolScope),
|
||||
@@ -1945,7 +1947,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
setStreamingForScope,
|
||||
sendToExternalAgent, sendToCattyAgent, reportStreamError, autoTitleSession, t,
|
||||
abortControllersRef, terminalSessions, defaultTargetSession, providers, selectedAgentModel, updateSessionExternalSessionId,
|
||||
scopeType, scopeTargetId, scopeHostIds, scopeLabel, commandBlocklist, commandTimeout, responseIdleTimeout, webSearchConfig, buildExecutorContextForScope,
|
||||
scopeType, scopeTargetId, scopeHostIds, scopeLabel, commandBlocklist, commandTimeout, responseIdleTimeout, toolOutputMaxChars, webSearchConfig, buildExecutorContextForScope,
|
||||
toolIntegrationMode,
|
||||
clearScopeDraft, showScopeSessionView, setActiveSessionId,
|
||||
flushDraftText, currentAgentConfig, buildExternalAgentRuntimeModelTarget,
|
||||
@@ -1989,6 +1991,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
commandBlocklist,
|
||||
commandTimeout,
|
||||
responseIdleTimeout,
|
||||
toolOutputMaxChars,
|
||||
terminalSessions,
|
||||
webSearchConfig,
|
||||
getExecutorContext: () => buildExecutorContextForScope({
|
||||
@@ -2014,6 +2017,7 @@ const AIChatSidePanelActive: React.FC<AIChatSidePanelProps> = ({
|
||||
commandBlocklist,
|
||||
commandTimeout,
|
||||
responseIdleTimeout,
|
||||
toolOutputMaxChars,
|
||||
currentAgentId,
|
||||
effectiveActiveModelId,
|
||||
effectiveActiveProvider,
|
||||
@@ -2551,6 +2555,7 @@ const AI_CHAT_SIDE_PANEL_AI_STATE_KEYS = [
|
||||
'commandTimeout',
|
||||
'responseIdleTimeout',
|
||||
'maxIterations',
|
||||
'toolOutputMaxChars',
|
||||
'webSearchConfig',
|
||||
'quickMessages',
|
||||
] as const satisfies readonly (keyof AIChatSidePanelProps)[];
|
||||
|
||||
@@ -95,6 +95,7 @@ export interface AIChatSidePanelProps {
|
||||
commandTimeout?: number;
|
||||
responseIdleTimeout?: number;
|
||||
maxIterations?: number;
|
||||
toolOutputMaxChars?: number;
|
||||
|
||||
// Web search
|
||||
webSearchConfig?: WebSearchConfig | null;
|
||||
|
||||
@@ -247,6 +247,8 @@ const SettingsAITabContainer: React.FC = () => {
|
||||
setResponseIdleTimeout={aiState.setResponseIdleTimeout}
|
||||
maxIterations={aiState.maxIterations}
|
||||
setMaxIterations={aiState.setMaxIterations}
|
||||
toolOutputMaxChars={aiState.toolOutputMaxChars}
|
||||
setToolOutputMaxChars={aiState.setToolOutputMaxChars}
|
||||
aiSessionMessageCap={aiState.aiSessionMessageCap}
|
||||
setAiSessionMessageCap={aiState.setAiSessionMessageCap}
|
||||
webSearchConfig={aiState.webSearchConfig}
|
||||
|
||||
@@ -165,6 +165,8 @@ interface SettingsAITabProps {
|
||||
setResponseIdleTimeout: (value: number) => void;
|
||||
maxIterations: number;
|
||||
setMaxIterations: (value: number) => void;
|
||||
toolOutputMaxChars: number;
|
||||
setToolOutputMaxChars: (value: number) => void;
|
||||
aiSessionMessageCap: number;
|
||||
setAiSessionMessageCap: (value: number) => void;
|
||||
webSearchConfig: WebSearchConfig | null;
|
||||
@@ -204,6 +206,8 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
aiSessionMessageCap,
|
||||
setAiSessionMessageCap,
|
||||
webSearchConfig,
|
||||
@@ -1489,6 +1493,8 @@ const SettingsAITab: React.FC<SettingsAITabProps> = ({
|
||||
setResponseIdleTimeout={setResponseIdleTimeout}
|
||||
maxIterations={maxIterations}
|
||||
setMaxIterations={setMaxIterations}
|
||||
toolOutputMaxChars={toolOutputMaxChars}
|
||||
setToolOutputMaxChars={setToolOutputMaxChars}
|
||||
/>
|
||||
<PermissionGrantsSettings
|
||||
grants={permissionGrants}
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import React, { act, useState } from 'react';
|
||||
import { JSDOM } from 'jsdom';
|
||||
import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
MAX_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
MIN_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
} from '../../../../domain/aiToolOutputLimit';
|
||||
|
||||
const dom = new JSDOM('<div id="root"></div>', { url: 'http://localhost/#/settings' });
|
||||
for (const key of [
|
||||
'window',
|
||||
'document',
|
||||
'DocumentFragment',
|
||||
'navigator',
|
||||
'HTMLElement',
|
||||
'HTMLInputElement',
|
||||
'Element',
|
||||
'Node',
|
||||
'NodeFilter',
|
||||
'MutationObserver',
|
||||
'CustomEvent',
|
||||
'Event',
|
||||
'KeyboardEvent',
|
||||
'MouseEvent',
|
||||
'FocusEvent',
|
||||
'getComputedStyle',
|
||||
'localStorage',
|
||||
] as const) {
|
||||
Object.defineProperty(globalThis, key, { value: dom.window[key], configurable: true });
|
||||
}
|
||||
Object.assign(globalThis, {
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
requestAnimationFrame: (fn: () => void) => setTimeout(fn, 0),
|
||||
cancelAnimationFrame: clearTimeout,
|
||||
});
|
||||
|
||||
const { createRoot } = await import('react-dom/client');
|
||||
const { I18nProvider } = await import('../../../../application/i18n/I18nProvider');
|
||||
const { SafetySettings } = await import('./SafetySettings');
|
||||
|
||||
function Harness({
|
||||
initialLimit = DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
onLimitChange,
|
||||
}: {
|
||||
initialLimit?: number;
|
||||
onLimitChange: (value: number) => void;
|
||||
}) {
|
||||
const [limit, setLimit] = useState(initialLimit);
|
||||
return (
|
||||
<I18nProvider locale="en">
|
||||
<SafetySettings
|
||||
globalPermissionMode="confirm"
|
||||
setGlobalPermissionMode={() => {}}
|
||||
commandBlocklist={[]}
|
||||
setCommandBlocklist={() => {}}
|
||||
commandTimeout={60}
|
||||
setCommandTimeout={() => {}}
|
||||
responseIdleTimeout={120}
|
||||
setResponseIdleTimeout={() => {}}
|
||||
maxIterations={20}
|
||||
setMaxIterations={() => {}}
|
||||
toolOutputMaxChars={limit}
|
||||
setToolOutputMaxChars={(next) => {
|
||||
setLimit(next);
|
||||
onLimitChange(next);
|
||||
}}
|
||||
/>
|
||||
</I18nProvider>
|
||||
);
|
||||
}
|
||||
|
||||
async function setInputValue(el: HTMLInputElement, value: string) {
|
||||
await act(async () => {
|
||||
Object.getOwnPropertyDescriptor(dom.window.HTMLInputElement.prototype, 'value')!.set!.call(el, value);
|
||||
el.dispatchEvent(new dom.window.Event('input', { bubbles: true }));
|
||||
});
|
||||
}
|
||||
|
||||
test('SafetySettings tool output limit input supports multi-digit typing, clamping on blur, and empty revert', async () => {
|
||||
const updates: number[] = [];
|
||||
const root = createRoot(document.getElementById('root')!);
|
||||
await act(async () => root.render(<Harness onLimitChange={(value) => updates.push(value)} />));
|
||||
try {
|
||||
const input = document.querySelector<HTMLInputElement>('input[aria-label="Built-in AI Tool Output Limit"]')!;
|
||||
assert.ok(input);
|
||||
assert.equal(input.value, String(DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS));
|
||||
|
||||
// Typing a partial number below min does not prematurely jump to min.
|
||||
await setInputValue(input, '5');
|
||||
assert.equal(input.value, '5');
|
||||
assert.deepEqual(updates, []);
|
||||
|
||||
// Completing an in-range number updates immediately.
|
||||
await setInputValue(input, '50000');
|
||||
assert.equal(input.value, '50000');
|
||||
assert.deepEqual(updates, [50_000]);
|
||||
|
||||
// Typing above max clamps cleanly on blur.
|
||||
await act(async () => {
|
||||
input.focus();
|
||||
});
|
||||
await setInputValue(input, '999999');
|
||||
assert.equal(input.value, '999999');
|
||||
await act(async () => {
|
||||
input.blur();
|
||||
});
|
||||
assert.equal(input.value, String(MAX_AI_TOOL_OUTPUT_MAX_CHARS));
|
||||
assert.equal(updates.at(-1), MAX_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
|
||||
// Typing below min clamps cleanly on blur.
|
||||
await act(async () => {
|
||||
input.focus();
|
||||
});
|
||||
await setInputValue(input, '100');
|
||||
await act(async () => {
|
||||
input.blur();
|
||||
});
|
||||
assert.equal(input.value, String(MIN_AI_TOOL_OUTPUT_MAX_CHARS));
|
||||
assert.equal(updates.at(-1), MIN_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
|
||||
// Clearing the field and blurring restores the current valid value.
|
||||
await act(async () => {
|
||||
input.focus();
|
||||
});
|
||||
await setInputValue(input, '');
|
||||
await act(async () => {
|
||||
input.blur();
|
||||
});
|
||||
assert.equal(input.value, String(MIN_AI_TOOL_OUTPUT_MAX_CHARS));
|
||||
} finally {
|
||||
await act(async () => root.unmount());
|
||||
}
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { useCallback, useState } from "react";
|
||||
import React, { useCallback, useEffect, useState } from "react";
|
||||
import { Plus, X } from "lucide-react";
|
||||
import type { AIPermissionMode } from "../../../../infrastructure/ai/types";
|
||||
import {
|
||||
@@ -6,6 +6,11 @@ import {
|
||||
MAX_COMMAND_TIMEOUT_SECONDS,
|
||||
MAX_RESPONSE_IDLE_TIMEOUT_SECONDS,
|
||||
} from "../../../../infrastructure/ai/types";
|
||||
import {
|
||||
MAX_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
MIN_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
} from "../../../../domain/aiToolOutputLimit";
|
||||
import { useI18n } from "../../../../application/i18n/I18nProvider";
|
||||
import { Button } from "../../../ui/button";
|
||||
import { Select, SettingCard, SettingRow, SettingsAnchor, SettingsSection } from "../../settings-ui";
|
||||
@@ -21,6 +26,8 @@ export const SafetySettings: React.FC<{
|
||||
setResponseIdleTimeout: (value: number) => void;
|
||||
maxIterations: number;
|
||||
setMaxIterations: (value: number) => void;
|
||||
toolOutputMaxChars: number;
|
||||
setToolOutputMaxChars: (value: number) => void;
|
||||
}> = ({
|
||||
globalPermissionMode,
|
||||
setGlobalPermissionMode,
|
||||
@@ -32,9 +39,32 @@ export const SafetySettings: React.FC<{
|
||||
setResponseIdleTimeout,
|
||||
maxIterations,
|
||||
setMaxIterations,
|
||||
toolOutputMaxChars,
|
||||
setToolOutputMaxChars,
|
||||
}) => {
|
||||
const { t } = useI18n();
|
||||
const [regexErrors, setRegexErrors] = useState<Record<number, string>>({});
|
||||
const [toolOutputDraft, setToolOutputDraft] = useState<string>(() => String(toolOutputMaxChars));
|
||||
|
||||
useEffect(() => {
|
||||
setToolOutputDraft(String(toolOutputMaxChars));
|
||||
}, [toolOutputMaxChars]);
|
||||
|
||||
const commitToolOutputDraft = useCallback(() => {
|
||||
const trimmed = toolOutputDraft.trim();
|
||||
if (!trimmed) {
|
||||
setToolOutputDraft(String(toolOutputMaxChars));
|
||||
return;
|
||||
}
|
||||
const parsed = Number(trimmed);
|
||||
if (!Number.isFinite(parsed)) {
|
||||
setToolOutputDraft(String(toolOutputMaxChars));
|
||||
return;
|
||||
}
|
||||
const normalized = normalizeAiToolOutputMaxChars(parsed);
|
||||
setToolOutputMaxChars(normalized);
|
||||
setToolOutputDraft(String(normalized));
|
||||
}, [setToolOutputMaxChars, toolOutputDraft, toolOutputMaxChars]);
|
||||
|
||||
const validatePattern = useCallback((pattern: string, idx: number): boolean => {
|
||||
if (!pattern) {
|
||||
@@ -152,6 +182,43 @@ export const SafetySettings: React.FC<{
|
||||
className="w-20 h-9 rounded-md border border-input bg-background px-3 text-sm text-right focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
/>
|
||||
</SettingRow>
|
||||
|
||||
<SettingRow
|
||||
anchorId="ai-safety-tool-output-max-chars"
|
||||
label={t('ai.safety.toolOutputMaxChars')}
|
||||
description={t('ai.safety.toolOutputMaxChars.description')}
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<input
|
||||
type="number"
|
||||
aria-label={t('ai.safety.toolOutputMaxChars')}
|
||||
value={toolOutputDraft}
|
||||
onChange={(e) => {
|
||||
const raw = e.target.value;
|
||||
setToolOutputDraft(raw);
|
||||
const val = parseInt(raw, 10);
|
||||
if (
|
||||
!isNaN(val)
|
||||
&& val >= MIN_AI_TOOL_OUTPUT_MAX_CHARS
|
||||
&& val <= MAX_AI_TOOL_OUTPUT_MAX_CHARS
|
||||
) {
|
||||
setToolOutputMaxChars(val);
|
||||
}
|
||||
}}
|
||||
onBlur={commitToolOutputDraft}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
commitToolOutputDraft();
|
||||
}
|
||||
}}
|
||||
min={MIN_AI_TOOL_OUTPUT_MAX_CHARS}
|
||||
max={MAX_AI_TOOL_OUTPUT_MAX_CHARS}
|
||||
step={1000}
|
||||
className="w-24 h-9 rounded-md border border-input bg-background px-3 text-sm text-right focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground">{t('ai.safety.toolOutputMaxChars.unit')}</span>
|
||||
</div>
|
||||
</SettingRow>
|
||||
</SettingCard>
|
||||
|
||||
{/* Command Blocklist */}
|
||||
|
||||
@@ -676,6 +676,7 @@ const AIChatPanelsHostInner: React.FC<AIChatPanelsHostProps> = ({
|
||||
commandTimeout={aiConfig.commandTimeout}
|
||||
responseIdleTimeout={aiConfig.responseIdleTimeout}
|
||||
maxIterations={aiConfig.maxIterations}
|
||||
toolOutputMaxChars={aiConfig.toolOutputMaxChars}
|
||||
webSearchConfig={aiConfig.webSearchConfig}
|
||||
quickMessages={aiConfig.quickMessages}
|
||||
scopeType={context.scopeType}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
MAX_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
MIN_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
normalizeAiToolOutputMaxChars,
|
||||
resolveTerminalStderrMaxChars,
|
||||
} from './aiToolOutputLimit';
|
||||
|
||||
test('normalizeAiToolOutputMaxChars falls back to default for missing or non-finite inputs', () => {
|
||||
assert.equal(normalizeAiToolOutputMaxChars(undefined), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(null), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(''), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(false), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(true), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(Number.NaN), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(Number.POSITIVE_INFINITY), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(Number.NEGATIVE_INFINITY), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars('not-a-number'), DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
});
|
||||
|
||||
test('normalizeAiToolOutputMaxChars clamps values to safe min/max bounds and rounds decimals', () => {
|
||||
assert.equal(normalizeAiToolOutputMaxChars(-500), MIN_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(0), MIN_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(MIN_AI_TOOL_OUTPUT_MAX_CHARS - 1), MIN_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(MIN_AI_TOOL_OUTPUT_MAX_CHARS), MIN_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(64_000), 64_000);
|
||||
assert.equal(normalizeAiToolOutputMaxChars('48000'), 48_000);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(32_000.6), 32_001);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(MAX_AI_TOOL_OUTPUT_MAX_CHARS), MAX_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(MAX_AI_TOOL_OUTPUT_MAX_CHARS + 1), MAX_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(normalizeAiToolOutputMaxChars(10_000_000), MAX_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
});
|
||||
|
||||
test('resolveTerminalStderrMaxChars matches legacy 12,000 default and scales cleanly with custom limits', () => {
|
||||
assert.equal(resolveTerminalStderrMaxChars(DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS), 12_000);
|
||||
assert.equal(resolveTerminalStderrMaxChars(MIN_AI_TOOL_OUTPUT_MAX_CHARS), MIN_AI_TOOL_OUTPUT_MAX_CHARS);
|
||||
assert.equal(resolveTerminalStderrMaxChars(100_000), 50_000);
|
||||
assert.equal(resolveTerminalStderrMaxChars(MAX_AI_TOOL_OUTPUT_MAX_CHARS), 100_000);
|
||||
assert.equal(resolveTerminalStderrMaxChars(Number.NaN), 12_000);
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* User-configurable inline character limit for built-in AI (Catty) tool results.
|
||||
*
|
||||
* Outputs up to this limit are returned inline to the model; larger outputs
|
||||
* spill to `ToolOutputStore` behind a `tool_output_read` handle. Keeping the
|
||||
* setting bounded protects renderer memory, IPC serialization, and request
|
||||
* budgets from runaway outputs while letting users with large-context models
|
||||
* inspect complete command and file results without excessive pagination.
|
||||
*/
|
||||
|
||||
export const DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS = 24_000;
|
||||
export const MIN_AI_TOOL_OUTPUT_MAX_CHARS = 2_000;
|
||||
export const MAX_AI_TOOL_OUTPUT_MAX_CHARS = 200_000;
|
||||
|
||||
export function normalizeAiToolOutputMaxChars(value: unknown): number {
|
||||
if (typeof value === 'boolean' || value === null || value === undefined || value === '') {
|
||||
return DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS;
|
||||
}
|
||||
const numeric = typeof value === 'number' ? value : Number(value);
|
||||
if (!Number.isFinite(numeric)) return DEFAULT_AI_TOOL_OUTPUT_MAX_CHARS;
|
||||
return Math.min(
|
||||
MAX_AI_TOOL_OUTPUT_MAX_CHARS,
|
||||
Math.max(MIN_AI_TOOL_OUTPUT_MAX_CHARS, Math.round(numeric)),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the inline stderr budget from the configured tool output limit.
|
||||
* Keeps parity with the legacy 12,000-char default when the limit is 24,000,
|
||||
* and scales proportionally up or down within `[MIN, limit]`.
|
||||
*/
|
||||
export function resolveTerminalStderrMaxChars(maxOutputChars: number): number {
|
||||
const normalized = normalizeAiToolOutputMaxChars(maxOutputChars);
|
||||
return Math.min(
|
||||
normalized,
|
||||
Math.max(MIN_AI_TOOL_OUTPUT_MAX_CHARS, Math.floor(normalized / 2)),
|
||||
);
|
||||
}
|
||||
@@ -248,6 +248,7 @@ test("later-added settings retain their tab and sub-tab destinations", () => {
|
||||
["ai-chat-history-message-cap", "ai", "tools", "ai.chatHistory.messageCap"],
|
||||
["ai-web-search-max-results", "ai", "search", "ai.webSearch.maxResults"],
|
||||
["ai-safety-max-iterations", "ai", "safety", "ai.safety.maxIterations"],
|
||||
["ai-safety-tool-output-max-chars", "ai", "safety", "ai.safety.toolOutputMaxChars"],
|
||||
["sync-ai-sessions", "sync", "status", "cloudSync.aiSessions.title"],
|
||||
["system-network-proxy-url", "system", undefined, "settings.system.networkProxy.url"],
|
||||
] as const) {
|
||||
|
||||
@@ -1265,6 +1265,15 @@ export const SETTINGS_SEARCH_CATALOG: readonly SettingsSearchEntry[] = [
|
||||
descriptionKey: "ai.safety.maxIterations.description",
|
||||
sectionKey: "ai.safety.title",
|
||||
},
|
||||
{
|
||||
id: "ai-safety-tool-output-max-chars",
|
||||
tab: "ai",
|
||||
aiSubTab: "safety",
|
||||
labelKey: "ai.safety.toolOutputMaxChars",
|
||||
descriptionKey: "ai.safety.toolOutputMaxChars.description",
|
||||
sectionKey: "ai.safety.title",
|
||||
keywords: ["tool", "output", "truncate", "limit", "chars", "工具", "返回", "输出", "截断", "限制", "傳回", "輸出"],
|
||||
},
|
||||
{
|
||||
id: "ai-safety-blocklist",
|
||||
tab: "ai",
|
||||
|
||||
@@ -388,6 +388,7 @@ export interface SyncPayload {
|
||||
commandTimeout?: number;
|
||||
responseIdleTimeout?: number;
|
||||
maxIterations?: number;
|
||||
toolOutputMaxChars?: number;
|
||||
agentModelMap?: Record<string, string>;
|
||||
agentProviderMap?: Record<string, string>;
|
||||
agentThinkingMap?: Record<string, string>;
|
||||
|
||||
@@ -641,3 +641,109 @@ describe('capabilityTools terminal polling', () => {
|
||||
assert.equal(result.output, 'first new line');
|
||||
});
|
||||
});
|
||||
|
||||
describe('capabilityTools configurable toolOutputMaxChars', () => {
|
||||
it('keeps larger terminal_execute stdout inline up to custom limit and spills above it', async () => {
|
||||
const store = new ToolOutputStore();
|
||||
const mediumStdout = Array.from({ length: 1_000 }, (_, i) => `line-${String(i).padStart(4, '0')}-${'a'.repeat(28)}`).join('\n');
|
||||
const hugeStdout = `${Array.from({ length: 1_800 }, (_, i) => `row-${String(i).padStart(4, '0')}-${'b'.repeat(32)}`).join('\n')}\nUNIQUE_END_MARKER_4147`;
|
||||
assert.ok(mediumStdout.length > 35_000 && mediumStdout.length < 60_000);
|
||||
assert.ok(hugeStdout.length > 70_000);
|
||||
|
||||
let nextOutput = mediumStdout;
|
||||
const { tools, toolsContext } = createCattyToolsFromCatalog(
|
||||
{
|
||||
aiExec: async () => ({
|
||||
ok: true,
|
||||
stdout: nextOutput,
|
||||
stderr: '',
|
||||
exitCode: 0,
|
||||
}),
|
||||
},
|
||||
{
|
||||
sessions: [{
|
||||
sessionId: 'session-1',
|
||||
hostId: 'host-1',
|
||||
hostname: 'prod.internal',
|
||||
label: 'prod',
|
||||
protocol: 'ssh',
|
||||
connected: true,
|
||||
}],
|
||||
},
|
||||
[],
|
||||
'auto',
|
||||
undefined,
|
||||
'chat-custom-limit',
|
||||
store,
|
||||
undefined,
|
||||
{ toolOutputMaxChars: 60_000 },
|
||||
);
|
||||
|
||||
const exec = withCattyToolContext(tools.terminal_execute, toolsContext.terminal_execute);
|
||||
const mediumResult = await exec.execute({ sessionId: 'session-1', command: 'cat medium.log' }) as { stdout: string };
|
||||
assert.equal(mediumResult.stdout, mediumStdout);
|
||||
assert.doesNotMatch(mediumResult.stdout, /output handle/);
|
||||
|
||||
nextOutput = hugeStdout;
|
||||
const hugeResult = await exec.execute({ sessionId: 'session-1', command: 'cat huge.log' }) as { stdout: string };
|
||||
assert.notEqual(hugeResult.stdout, hugeStdout);
|
||||
assert.ok(hugeResult.stdout.length > 50_000, 'truncated output should utilize the configured limit rather than collapsing to 4.8k');
|
||||
assert.match(hugeResult.stdout, /output handle/);
|
||||
const handleId = hugeResult.stdout.match(/handleId=(tool-output-[^\]\s]+)/)?.[1];
|
||||
assert.ok(handleId);
|
||||
assert.match(
|
||||
store.read({ handleId, mode: 'tail', maxChars: 1_000 }, 'chat-custom-limit') ?? '',
|
||||
/UNIQUE_END_MARKER_4147/,
|
||||
);
|
||||
});
|
||||
|
||||
it('honors custom toolOutputMaxChars for sftp_read_file with and without dedup', async () => {
|
||||
const mediumFile = Array.from({ length: 1_000 }, (_, i) => `config_${i}=${'v'.repeat(30)}`).join('\n');
|
||||
const hugeFile = `${Array.from({ length: 1_800 }, (_, i) => `entry_${i}=${'w'.repeat(34)}`).join('\n')}\nSFTP_TAIL_4147`;
|
||||
assert.ok(mediumFile.length > 35_000 && mediumFile.length < 60_000);
|
||||
assert.ok(hugeFile.length > 70_000);
|
||||
|
||||
for (const withDedup of [true, false]) {
|
||||
const store = new ToolOutputStore();
|
||||
const dedup = withDedup ? new ToolResultDedup() : undefined;
|
||||
dedup?.beginTurn();
|
||||
const { tools, toolsContext } = createCattyToolsFromCatalog(
|
||||
{
|
||||
aiCapability: async (_method: string, params: Record<string, unknown>) => ({
|
||||
ok: true,
|
||||
path: params.path,
|
||||
content: params.path === '/etc/medium.conf' ? mediumFile : hugeFile,
|
||||
}),
|
||||
},
|
||||
{ sessions: [] },
|
||||
[],
|
||||
'auto',
|
||||
undefined,
|
||||
`chat-sftp-${withDedup ? 'dedup' : 'plain'}`,
|
||||
store,
|
||||
dedup,
|
||||
{ toolOutputMaxChars: 60_000 },
|
||||
);
|
||||
|
||||
const readFile = withCattyToolContext(tools.sftp_read_file, toolsContext.sftp_read_file);
|
||||
const mediumResult = await readFile.execute({ sessionId: 'session-1', path: '/etc/medium.conf' }) as {
|
||||
content?: string;
|
||||
handleId?: string;
|
||||
};
|
||||
assert.equal(mediumResult.content, mediumFile);
|
||||
assert.equal(mediumResult.handleId, undefined);
|
||||
|
||||
const hugeResult = await readFile.execute({ sessionId: 'session-1', path: '/etc/huge.conf' }) as {
|
||||
content?: string;
|
||||
handleId?: string;
|
||||
};
|
||||
const handleId = hugeResult.handleId ?? hugeResult.content?.match(/handleId=(tool-output-[^\]\s]+)/)?.[1];
|
||||
assert.ok(handleId, `expected handleId for oversized SFTP file (withDedup=${withDedup})`);
|
||||
const recovered = store.readChunk(
|
||||
{ handleId, mode: 'search', query: 'SFTP_TAIL_4147' },
|
||||
`chat-sftp-${withDedup ? 'dedup' : 'plain'}`,
|
||||
);
|
||||
assert.match(recovered?.content ?? '', /SFTP_TAIL_4147/);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import { z } from 'zod';
|
||||
import { SHELL_READINESS_UNKNOWN_CODE } from '../aiChatStreamingSupport';
|
||||
import type { ExecutorContext, NetcattyBridge } from '../cattyAgent/executor';
|
||||
import type { TerminalContextReadRange } from '../../../domain/terminalContextRead';
|
||||
import { normalizeAiToolOutputMaxChars } from '../../../domain/aiToolOutputLimit';
|
||||
import type { AIPermissionMode } from '../types';
|
||||
import type { WebSearchConfig } from '../types';
|
||||
import { isWebSearchReady } from '../types';
|
||||
@@ -134,6 +135,8 @@ function applyToolDedup(
|
||||
return result;
|
||||
}
|
||||
|
||||
const MAX_LIVE_SFTP_READ_CHARS = 24_000;
|
||||
|
||||
function fitCapabilityResultForModel(
|
||||
result: unknown,
|
||||
spec: CattyToolSpec,
|
||||
@@ -141,6 +144,7 @@ function fitCapabilityResultForModel(
|
||||
toolOutputStore?: ToolOutputStore,
|
||||
args?: Record<string, unknown>,
|
||||
toolResultDedup?: ToolResultDedup,
|
||||
maxStringChars?: number,
|
||||
): unknown {
|
||||
if (spec.capabilityId === 'harness.tool_output.read') {
|
||||
return result;
|
||||
@@ -164,6 +168,7 @@ function fitCapabilityResultForModel(
|
||||
chatSessionId,
|
||||
toolOutputStore,
|
||||
terminalSessionId,
|
||||
maxStringChars,
|
||||
normalizeStrings: spec.capabilityId.startsWith('terminal.')
|
||||
|| spec.capabilityId === 'harness.terminal.read_context',
|
||||
});
|
||||
@@ -398,7 +403,10 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
execute: async (args, { toolCallId: _toolCallId, abortSignal, context }) => {
|
||||
const toolContext = context as CattyToolContext;
|
||||
const deps = toolDepsFromContext(toolContext);
|
||||
const { toolOutputStore, toolResultDedup } = toolContext;
|
||||
const { toolOutputStore, toolResultDedup, toolOutputMaxChars } = toolContext;
|
||||
const effectiveToolOutputMaxChars = toolOutputMaxChars != null
|
||||
? normalizeAiToolOutputMaxChars(toolOutputMaxChars)
|
||||
: undefined;
|
||||
|
||||
const queueKey = resolveSessionQueueKey(
|
||||
spec,
|
||||
@@ -479,6 +487,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
chatSessionId: deps.chatSessionId,
|
||||
toolOutputStore,
|
||||
terminalSessionId: sid,
|
||||
maxStringChars: effectiveToolOutputMaxChars,
|
||||
normalizeStrings: true,
|
||||
}),
|
||||
...fitTerminalExecuteResultForModel({
|
||||
@@ -488,6 +497,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
}, {
|
||||
chatSessionId: deps.chatSessionId,
|
||||
toolOutputStore,
|
||||
maxOutputChars: effectiveToolOutputMaxChars,
|
||||
}),
|
||||
};
|
||||
if (writeFingerprint) toolResultDedup?.rememberCompletedWrite(writeFingerprint, fittedFailure);
|
||||
@@ -500,6 +510,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
}, {
|
||||
chatSessionId: deps.chatSessionId,
|
||||
toolOutputStore,
|
||||
maxOutputChars: effectiveToolOutputMaxChars,
|
||||
});
|
||||
if (writeFingerprint) toolResultDedup?.rememberCompletedWrite(writeFingerprint, fitted);
|
||||
return fitted;
|
||||
@@ -524,6 +535,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
toolOutputStore,
|
||||
args as Record<string, unknown>,
|
||||
toolResultDedup,
|
||||
effectiveToolOutputMaxChars,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -638,6 +650,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
toolOutputStore,
|
||||
args as Record<string, unknown>,
|
||||
toolResultDedup,
|
||||
effectiveToolOutputMaxChars,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -656,12 +669,14 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
toolOutputStore,
|
||||
args as Record<string, unknown>,
|
||||
toolResultDedup,
|
||||
effectiveToolOutputMaxChars,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (spec.capabilityId.includes('sftp') && spec.capabilityId.includes('read')) {
|
||||
const { sessionId: sid, path } = args as { sessionId?: string; path?: string };
|
||||
const sftpMaxChars = effectiveToolOutputMaxChars ?? MAX_LIVE_SFTP_READ_CHARS;
|
||||
const fingerprint = toolResultDedup?.fingerprintFor(
|
||||
spec.toolName,
|
||||
hashScopeKey([sid, path]),
|
||||
@@ -674,6 +689,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
toolOutputStore,
|
||||
args as Record<string, unknown>,
|
||||
toolResultDedup,
|
||||
sftpMaxChars,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -685,8 +701,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
&& deps.chatSessionId
|
||||
) {
|
||||
const content = String((raw as { content?: string }).content ?? '');
|
||||
const MAX_LIVE_SFTP_READ_CHARS = 24_000;
|
||||
if (content.length > MAX_LIVE_SFTP_READ_CHARS) {
|
||||
if (content.length > sftpMaxChars) {
|
||||
const handle = toolOutputStore.store({
|
||||
chatSessionId: deps.chatSessionId,
|
||||
capabilityId: spec.capabilityId,
|
||||
@@ -703,6 +718,16 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return fitCapabilityResultForModel(
|
||||
raw,
|
||||
spec,
|
||||
deps.chatSessionId,
|
||||
toolOutputStore,
|
||||
args as Record<string, unknown>,
|
||||
toolResultDedup,
|
||||
sftpMaxChars,
|
||||
);
|
||||
}
|
||||
|
||||
const fittedRaw = fitCapabilityResultForModel(
|
||||
@@ -712,6 +737,7 @@ function createCatalogTool(spec: CattyToolSpec) {
|
||||
toolOutputStore,
|
||||
args as Record<string, unknown>,
|
||||
toolResultDedup,
|
||||
effectiveToolOutputMaxChars,
|
||||
);
|
||||
if (
|
||||
terminalStartFingerprint
|
||||
@@ -744,6 +770,7 @@ export function buildCattyToolContext(input: {
|
||||
chatSessionId?: string;
|
||||
toolOutputStore?: ToolOutputStore;
|
||||
toolResultDedup?: ToolResultDedup;
|
||||
toolOutputMaxChars?: number;
|
||||
}): CattyToolContext {
|
||||
return {
|
||||
bridge: input.bridge,
|
||||
@@ -756,6 +783,7 @@ export function buildCattyToolContext(input: {
|
||||
: () => input.context as ExecutorContext,
|
||||
toolOutputStore: input.toolOutputStore,
|
||||
toolResultDedup: input.toolResultDedup,
|
||||
toolOutputMaxChars: input.toolOutputMaxChars,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -768,7 +796,11 @@ export function createCattyToolsFromCatalog(
|
||||
chatSessionId?: string,
|
||||
toolOutputStore?: ToolOutputStore,
|
||||
toolResultDedup?: ToolResultDedup,
|
||||
selection?: { agentKind?: import('../agentKinds').AgentKind; allowedCapabilityIds?: readonly string[] },
|
||||
selection?: {
|
||||
agentKind?: import('../agentKinds').AgentKind;
|
||||
allowedCapabilityIds?: readonly string[];
|
||||
toolOutputMaxChars?: number;
|
||||
},
|
||||
): CattyToolsBundle {
|
||||
const sharedContext = buildCattyToolContext({
|
||||
bridge,
|
||||
@@ -779,6 +811,7 @@ export function createCattyToolsFromCatalog(
|
||||
chatSessionId,
|
||||
toolOutputStore,
|
||||
toolResultDedup,
|
||||
toolOutputMaxChars: selection?.toolOutputMaxChars,
|
||||
});
|
||||
|
||||
const catalogTools: Record<string, ReturnType<typeof tool>> = {};
|
||||
|
||||
@@ -21,7 +21,13 @@ interface WireRequest {
|
||||
|
||||
type Reply = { tool: 'terminal_execute' | 'sftp_read_file' } | { text: string };
|
||||
|
||||
function fixture(t: test.TestContext, replies: Reply[], style: 'openai' | 'anthropic' = 'openai', terminalOutput = 'small output') {
|
||||
function fixture(
|
||||
t: test.TestContext,
|
||||
replies: Reply[],
|
||||
style: 'openai' | 'anthropic' = 'openai',
|
||||
terminalOutput = 'small output',
|
||||
toolOutputMaxChars?: number,
|
||||
) {
|
||||
const originalWindow = globalThis.window;
|
||||
const originalRaf = globalThis.requestAnimationFrame;
|
||||
const originalCancelRaf = globalThis.cancelAnimationFrame;
|
||||
@@ -129,6 +135,7 @@ function fixture(t: test.TestContext, replies: Reply[], style: 'openai' | 'anthr
|
||||
context: {
|
||||
activeProvider: provider, activeModelId: provider.defaultModel!, scopeType: 'terminal', scopeLabel: 'Fixture',
|
||||
globalPermissionMode: 'auto', commandBlocklist: [], autoTitleSession: () => undefined,
|
||||
toolOutputMaxChars,
|
||||
terminalSessions: [{ sessionId: 'terminal-1', hostname: 'fixture.example.test', label: 'Fixture', connected: true }],
|
||||
},
|
||||
ui: {
|
||||
@@ -249,3 +256,23 @@ for (const providerId of ['openrouter', 'ollama'] as const) {
|
||||
assert.equal(f.messages.at(-1)?.content, 'OK');
|
||||
});
|
||||
}
|
||||
|
||||
test('Catty delivers larger terminal output inline end-to-end when toolOutputMaxChars is raised', async t => {
|
||||
const mediumOutput = `${Array.from({ length: 1_200 }, (_, i) => `record-${String(i).padStart(4, '0')}-${'z'.repeat(24)}`).join('\n')}\nEND_MARKER_4147`;
|
||||
assert.ok(mediumOutput.length > 40_000 && mediumOutput.length < 60_000);
|
||||
const f = fixture(
|
||||
t,
|
||||
[{ tool: 'terminal_execute' }, { text: 'OK' }, { text: 'Follow-up OK' }],
|
||||
'openai',
|
||||
mediumOutput,
|
||||
80_000,
|
||||
);
|
||||
await f.turn(2);
|
||||
await f.turn(1);
|
||||
assert.equal(f.requests.length, 3);
|
||||
const wireAfterTool = JSON.stringify(f.requests[1]);
|
||||
assert.match(wireAfterTool, /END_MARKER_4147/);
|
||||
assert.doesNotMatch(wireAfterTool, /output handle:/);
|
||||
assert.doesNotMatch(wireAfterTool, /output truncated for request size/);
|
||||
assertRequestPrefix(f.requests[1], f.requests[2]);
|
||||
});
|
||||
@@ -41,6 +41,7 @@ export interface CompactCattyMessagesInput {
|
||||
/** Override protect-recent window (default: DEFAULT_PROTECT_RECENT_MESSAGES). */
|
||||
protectRecentMessages?: number;
|
||||
maxOutputTokens?: number;
|
||||
maxToolResultChars?: number;
|
||||
onCompactionStart?: (trigger: 'pre-turn' | '413-retry' | 'force') => void;
|
||||
onCompaction?: (trace: CompactionTrace) => void;
|
||||
toolOutputStore?: ToolOutputStore;
|
||||
@@ -212,6 +213,7 @@ export async function compactCattyMessages(
|
||||
trigger,
|
||||
force: input.force,
|
||||
compressForRequestTooLargeRetry: input.compressForRequestTooLargeRetry,
|
||||
maxToolResultChars: input.maxToolResultChars,
|
||||
protectRecentMessages: input.protectRecentMessages ?? DEFAULT_PROTECT_RECENT_MESSAGES,
|
||||
summarize,
|
||||
sessionId: input.sessionId,
|
||||
|
||||
@@ -22,6 +22,7 @@ export const cattyRuntimeContextSchema = z.object({
|
||||
lastCompaction: z.custom<CompactionTrace>().optional(),
|
||||
lastStepAdjusted: z.boolean().optional(),
|
||||
promptContext: z.custom<PromptContextSnapshot>().optional(),
|
||||
toolOutputMaxChars: z.number().optional(),
|
||||
});
|
||||
|
||||
export type CattyRuntimeContext = z.infer<typeof cattyRuntimeContextSchema>;
|
||||
@@ -35,6 +36,7 @@ export const cattyToolContextSchema = z.object({
|
||||
getExecutorContext: z.custom<() => ExecutorContext>(),
|
||||
toolOutputStore: z.custom<ToolOutputStore>().optional(),
|
||||
toolResultDedup: z.custom<ToolResultDedup>().optional(),
|
||||
toolOutputMaxChars: z.number().optional(),
|
||||
});
|
||||
|
||||
export type CattyToolContext = z.infer<typeof cattyToolContextSchema>;
|
||||
@@ -51,6 +53,7 @@ export function createInitialCattyRuntimeContext(input: {
|
||||
delegated?: boolean;
|
||||
scopeLabel?: string;
|
||||
promptContext?: PromptContextSnapshot;
|
||||
toolOutputMaxChars?: number;
|
||||
}): CattyRuntimeContext {
|
||||
return {
|
||||
chatSessionId: input.chatSessionId,
|
||||
@@ -64,6 +67,7 @@ export function createInitialCattyRuntimeContext(input: {
|
||||
scopeType: input.scopeType,
|
||||
scopeLabel: input.scopeLabel,
|
||||
promptContext: input.promptContext,
|
||||
toolOutputMaxChars: input.toolOutputMaxChars,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -416,3 +416,60 @@ test('413 retry still trades attachments for a text placeholder', async () => {
|
||||
|
||||
assert.match(JSON.stringify(prepared.messages), /attachment omitted to keep the AI request small/);
|
||||
});
|
||||
|
||||
test('prepareStepContext and prepareTurnContext preserve live tool results up to configured toolOutputMaxChars', async () => {
|
||||
const payload = Array.from({ length: 1_000 }, (_, i) => `item_${i}=${'k'.repeat(30)}`).join('\n');
|
||||
assert.ok(payload.length > 35_000 && payload.length < 60_000);
|
||||
const messages: ModelMessage[] = [
|
||||
{ role: 'user', content: 'read /etc/app.conf' },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [{ type: 'tool-call', toolCallId: 'call-1', toolName: 'sftp_read_file', input: { sessionId: 's1', path: '/etc/app.conf' } }],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: [{
|
||||
type: 'tool-result',
|
||||
toolCallId: 'call-1',
|
||||
toolName: 'sftp_read_file',
|
||||
output: { type: 'json', value: { ok: true, path: '/etc/app.conf', content: payload } },
|
||||
}],
|
||||
},
|
||||
];
|
||||
const runtimeContext = createInitialCattyRuntimeContext({
|
||||
chatSessionId: 'chat-limit',
|
||||
turnId: 'turn-1',
|
||||
permissionMode: 'auto',
|
||||
scopeType: 'terminal',
|
||||
toolOutputMaxChars: 60_000,
|
||||
});
|
||||
|
||||
const step = await prepareStepContext({
|
||||
messages,
|
||||
stepNumber: 1,
|
||||
sessionId: 'chat-limit',
|
||||
chatSessionId: 'chat-limit',
|
||||
contextWindow: 1_000_000,
|
||||
toolOutputMaxChars: 60_000,
|
||||
runtimeContext,
|
||||
});
|
||||
assert.deepEqual(step.messages, messages);
|
||||
|
||||
const turn = await prepareTurnContext({
|
||||
messages,
|
||||
backend: 'catty',
|
||||
contextWindow: 1_000_000,
|
||||
trigger: 'pre-turn',
|
||||
maxToolResultChars: 60_000,
|
||||
});
|
||||
assert.deepEqual(turn.messages, messages);
|
||||
|
||||
const retry = await prepareTurnContext({
|
||||
messages,
|
||||
backend: 'catty',
|
||||
contextWindow: 1_000_000,
|
||||
trigger: '413-retry',
|
||||
compressForRequestTooLargeRetry: true,
|
||||
});
|
||||
assert.ok(JSON.stringify(retry.messages).length < 6_000);
|
||||
});
|
||||
@@ -40,6 +40,7 @@ export interface PrepareTurnContextInput {
|
||||
protectRecentMessages?: number;
|
||||
force?: boolean;
|
||||
compressForRequestTooLargeRetry?: boolean;
|
||||
maxToolResultChars?: number;
|
||||
summarize?: (messagesToSummarize: ModelMessage[]) => Promise<string>;
|
||||
onEvent?: AgentEventListener;
|
||||
sessionId?: string;
|
||||
@@ -233,7 +234,10 @@ export async function prepareTurnContext(
|
||||
} else {
|
||||
// Routine pre-turn pass: keep the user's attachment parts. Only the explicit
|
||||
// 413 retry above may trade them for text placeholders.
|
||||
const typed = applyTypedMessageCompression(working, { preserveAttachments: true });
|
||||
const typed = applyTypedMessageCompression(working, {
|
||||
preserveAttachments: true,
|
||||
maxToolResultChars: input.maxToolResultChars,
|
||||
});
|
||||
if (typed.didAdjust) {
|
||||
working = typed.messages;
|
||||
didTypedCompression = true;
|
||||
@@ -417,7 +421,11 @@ export async function prepareStepContext(
|
||||
|
||||
// Step-level typed compression runs before every model call, so it must keep
|
||||
// multimodal parts: the user's image would otherwise never reach the model.
|
||||
const typed = compressMessagesForRequestTooLargeRetry(working, { preserveAttachments: true });
|
||||
const maxToolResultChars = input.toolOutputMaxChars ?? input.runtimeContext?.toolOutputMaxChars;
|
||||
const typed = compressMessagesForRequestTooLargeRetry(working, {
|
||||
preserveAttachments: true,
|
||||
maxToolResultChars,
|
||||
});
|
||||
working = typed.messages;
|
||||
|
||||
const budgetGuard = applyStepBudgetGuard(working, {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { compressVerboseText, truncateTextWithHeadAndTail } from '../requestPayloadCompression';
|
||||
import type { ToolOutputStore } from './toolOutputStore';
|
||||
import { redactSecretsForModel } from './modelSecretRedaction';
|
||||
import {
|
||||
normalizeAiToolOutputMaxChars,
|
||||
resolveTerminalStderrMaxChars,
|
||||
} from '../../../domain/aiToolOutputLimit';
|
||||
|
||||
export const MAX_LIVE_TERMINAL_STDOUT_CHARS = 24_000;
|
||||
export const MAX_LIVE_TERMINAL_STDERR_CHARS = 12_000;
|
||||
@@ -26,19 +30,31 @@ export interface TerminalOutputHandle {
|
||||
export interface FitTerminalExecuteResultOptions {
|
||||
chatSessionId?: string;
|
||||
toolOutputStore?: ToolOutputStore;
|
||||
maxOutputChars?: number;
|
||||
maxStdoutChars?: number;
|
||||
maxStderrChars?: number;
|
||||
}
|
||||
|
||||
export function fitTerminalExecuteResultForModel(
|
||||
result: TerminalExecuteResult,
|
||||
options?: FitTerminalExecuteResultOptions,
|
||||
): TerminalExecuteResult {
|
||||
const maxStdoutChars = options?.maxStdoutChars
|
||||
?? (options?.maxOutputChars != null
|
||||
? normalizeAiToolOutputMaxChars(options.maxOutputChars)
|
||||
: MAX_LIVE_TERMINAL_STDOUT_CHARS);
|
||||
const maxStderrChars = options?.maxStderrChars
|
||||
?? (options?.maxOutputChars != null
|
||||
? resolveTerminalStderrMaxChars(options.maxOutputChars)
|
||||
: MAX_LIVE_TERMINAL_STDERR_CHARS);
|
||||
|
||||
const stdout = truncateTextWithHeadAndTail(
|
||||
redactSecretsForModel(compressVerboseText(result.stdout), options?.chatSessionId),
|
||||
MAX_LIVE_TERMINAL_STDOUT_CHARS,
|
||||
maxStdoutChars,
|
||||
);
|
||||
const stderr = truncateTextWithHeadAndTail(
|
||||
redactSecretsForModel(compressVerboseText(result.stderr), options?.chatSessionId),
|
||||
MAX_LIVE_TERMINAL_STDERR_CHARS,
|
||||
maxStderrChars,
|
||||
);
|
||||
|
||||
const fitted: TerminalExecuteResult = {
|
||||
|
||||
@@ -48,6 +48,7 @@ import type { CattyTurnInput, TurnDriver, TurnDriverContext } from './types';
|
||||
import { fitLargeUserInputForModel } from '../largeUserInput';
|
||||
import { buildPromptContextSnapshot } from '../promptContextSnapshot';
|
||||
import { initializeModelPrivacy, protectModel, redactOpenAIChatAssistantFields, type ModelPrivacyBridge } from '../modelPrivacy';
|
||||
import { normalizeAiToolOutputMaxChars } from '../../../../domain/aiToolOutputLimit';
|
||||
|
||||
export class CattyTurnDriver implements TurnDriver {
|
||||
readonly backend = 'catty' as const;
|
||||
@@ -163,6 +164,7 @@ async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Prom
|
||||
workspaceId: context.scopeType === 'workspace' ? context.scopeTargetId : undefined,
|
||||
workspaceName: context.scopeType === 'workspace' ? context.scopeLabel : undefined,
|
||||
}));
|
||||
const toolOutputMaxChars = normalizeAiToolOutputMaxChars(context.toolOutputMaxChars);
|
||||
const toolsBundle = createCattyToolsFromCatalog(
|
||||
netcattyBridge,
|
||||
getExecutorContext,
|
||||
@@ -172,7 +174,11 @@ async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Prom
|
||||
sessionId,
|
||||
ctx.toolOutputStore,
|
||||
ctx.toolResultDedup,
|
||||
{ agentKind: context.agentKind, allowedCapabilityIds: context.allowedCapabilityIds },
|
||||
{
|
||||
agentKind: context.agentKind,
|
||||
allowedCapabilityIds: context.allowedCapabilityIds,
|
||||
toolOutputMaxChars,
|
||||
},
|
||||
);
|
||||
const { tools } = toolsBundle;
|
||||
|
||||
@@ -358,6 +364,7 @@ async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Prom
|
||||
trigger: options.force ? 'force' : options.compressForRequestTooLargeRetry ? '413-retry' : 'pre-turn',
|
||||
force: options.force,
|
||||
compressForRequestTooLargeRetry: options.compressForRequestTooLargeRetry,
|
||||
maxToolResultChars: options.compressForRequestTooLargeRetry ? undefined : toolOutputMaxChars,
|
||||
protectRecentMessages: options.protectRecentMessages,
|
||||
onCompactionStart: (trigger) => {
|
||||
ctx.emit({
|
||||
@@ -464,6 +471,7 @@ async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Prom
|
||||
scopeLabel: context.scopeLabel,
|
||||
userGoal: extractLatestUserGoal(messagesForStream),
|
||||
promptContext,
|
||||
toolOutputMaxChars,
|
||||
});
|
||||
const commandTimeoutSeconds =
|
||||
Number.isFinite(context.commandTimeout) && context.commandTimeout > 0
|
||||
@@ -505,6 +513,7 @@ async function runCattyTurn(input: CattyTurnInput, ctx: TurnDriverContext): Prom
|
||||
reservedTokens: getRequestReserveTokens(),
|
||||
maxOutputTokens: compactionMaxOutputTokens,
|
||||
toolOutputStore: ctx.toolOutputStore,
|
||||
toolOutputMaxChars,
|
||||
runtimeContext: stepRuntimeContext,
|
||||
onEvent: (event) => ctx.emit(event),
|
||||
});
|
||||
|
||||
@@ -69,6 +69,7 @@ export interface CattyTurnContext {
|
||||
commandBlocklist?: string[];
|
||||
commandTimeout?: number;
|
||||
responseIdleTimeout?: number;
|
||||
toolOutputMaxChars?: number;
|
||||
terminalSessions: TerminalSessionInfo[];
|
||||
webSearchConfig?: WebSearchConfig | null;
|
||||
getExecutorContext?: () => ExecutorContext;
|
||||
@@ -191,6 +192,7 @@ export interface PrepareStepContextInput {
|
||||
maxOutputTokens?: number;
|
||||
protectRecentMessages?: number;
|
||||
toolOutputStore?: ToolOutputStore;
|
||||
toolOutputMaxChars?: number;
|
||||
runtimeContext: import('../cattyRuntimeContext').CattyRuntimeContext;
|
||||
onEvent?: AgentEventListener;
|
||||
}
|
||||
@@ -164,3 +164,40 @@ test("compressMessagesForRequestTooLargeRetry still placeholders text/plain file
|
||||
text: `[file attachment omitted to keep the AI request small: filename=note.txt, mediaType=text/plain, ${text.length} chars]`,
|
||||
});
|
||||
});
|
||||
|
||||
test("truncateTextWithHeadAndTail scales head and tail to use larger maxChars budgets", () => {
|
||||
const value = `${"H".repeat(20_000)}${"M".repeat(40_000)}${"T".repeat(20_000)}`;
|
||||
const truncated = truncateTextWithHeadAndTail(value, 50_000);
|
||||
assert.ok(truncated.startsWith("HHH"));
|
||||
assert.ok(truncated.endsWith("TTT"));
|
||||
assert.ok(truncated.includes("[... output truncated for request size ...]"));
|
||||
assert.ok(truncated.length <= 50_000);
|
||||
assert.ok(truncated.length >= 49_000);
|
||||
});
|
||||
|
||||
test("compressMessagesForRequestTooLargeRetry honors custom maxToolResultChars for live and replayed results", () => {
|
||||
const mediumPayload = Array.from({ length: 800 }, (_, i) => `row-${i}-${"x".repeat(30)}`).join("\n");
|
||||
const jsonPart = {
|
||||
type: "tool-result" as const,
|
||||
toolCallId: "call-1",
|
||||
toolName: "sftp_read_file",
|
||||
output: { type: "json" as const, value: { ok: true, content: mediumPayload } },
|
||||
};
|
||||
const replayedPart = {
|
||||
type: "tool-result" as const,
|
||||
toolCallId: "call-1",
|
||||
toolName: "sftp_read_file",
|
||||
output: { type: "text" as const, value: JSON.stringify({ ok: true, content: mediumPayload }) },
|
||||
};
|
||||
const messages: ModelMessage[] = [
|
||||
{ role: "tool", content: [jsonPart] },
|
||||
{ role: "tool", content: [replayedPart] },
|
||||
];
|
||||
|
||||
const preserved = compressMessagesForRequestTooLargeRetry(messages, {
|
||||
preserveAttachments: true,
|
||||
maxToolResultChars: 50_000,
|
||||
});
|
||||
assert.equal(preserved.didAdjust, false);
|
||||
assert.deepEqual(preserved.messages, messages);
|
||||
});
|
||||
@@ -27,6 +27,12 @@ export interface CompressMessagesForRequestTooLargeRetryOptions {
|
||||
* Only the 413 retry drops images as well.
|
||||
*/
|
||||
preserveAttachments?: boolean;
|
||||
/**
|
||||
* Inline character limit for tool results during routine turn/step passes.
|
||||
* When omitted (e.g., HTTP 413 retries or budget-pressure head compression),
|
||||
* falls back to the tight emergency cap (`RETRY_MAX_TOOL_RESULT_CHARS`).
|
||||
*/
|
||||
maxToolResultChars?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -89,8 +95,8 @@ export function truncateTextWithHeadAndTail(
|
||||
value: string,
|
||||
maxChars: number,
|
||||
{
|
||||
headChars = HEAD_CHARS,
|
||||
tailChars = TAIL_CHARS,
|
||||
headChars,
|
||||
tailChars,
|
||||
marker = TRUNCATION_MARKER,
|
||||
}: {
|
||||
headChars?: number;
|
||||
@@ -104,8 +110,18 @@ export function truncateTextWithHeadAndTail(
|
||||
}
|
||||
|
||||
const budget = maxChars - marker.length;
|
||||
const head = Math.min(headChars, budget);
|
||||
let tail = Math.min(tailChars, Math.max(0, budget - head));
|
||||
let resolvedHeadChars: number;
|
||||
let resolvedTailChars: number;
|
||||
if (headChars === undefined && tailChars === undefined && budget > HEAD_CHARS + TAIL_CHARS) {
|
||||
resolvedHeadChars = Math.max(HEAD_CHARS, Math.floor(budget * 0.2));
|
||||
resolvedTailChars = Math.max(0, budget - resolvedHeadChars);
|
||||
} else {
|
||||
resolvedHeadChars = headChars ?? HEAD_CHARS;
|
||||
resolvedTailChars = tailChars ?? TAIL_CHARS;
|
||||
}
|
||||
|
||||
const head = Math.min(resolvedHeadChars, budget);
|
||||
let tail = Math.min(resolvedTailChars, Math.max(0, budget - head));
|
||||
if (head + tail > budget) {
|
||||
tail = Math.max(0, budget - head);
|
||||
}
|
||||
@@ -124,9 +140,14 @@ export function compressMessagesForRequestTooLargeRetry(
|
||||
options: CompressMessagesForRequestTooLargeRetryOptions = {},
|
||||
): CompressMessagesForRequestTooLargeRetryResult {
|
||||
const preserveAttachments = options.preserveAttachments === true;
|
||||
const maxToolResultChars = options.maxToolResultChars;
|
||||
let didAdjust = false;
|
||||
const compressedMessages = messages.map((message) => {
|
||||
const compressed = compressModelMessageForRequestRetry(message, preserveAttachments);
|
||||
const compressed = compressModelMessageForRequestRetry(
|
||||
message,
|
||||
preserveAttachments,
|
||||
maxToolResultChars,
|
||||
);
|
||||
if (compressed !== message) didAdjust = true;
|
||||
return compressed;
|
||||
});
|
||||
@@ -140,6 +161,7 @@ export function compressMessagesForRequestTooLargeRetry(
|
||||
function compressModelMessageForRequestRetry(
|
||||
message: ModelMessage,
|
||||
preserveAttachments: boolean,
|
||||
maxToolResultChars?: number,
|
||||
): ModelMessage {
|
||||
if (typeof message.content === "string") {
|
||||
// User text is an instruction or exact input, not terminal output. Lossy
|
||||
@@ -154,7 +176,11 @@ function compressModelMessageForRequestRetry(
|
||||
let didAdjust = false;
|
||||
const content = message.content.map((part) => {
|
||||
if (message.role === "user" && part.type === "text") return part;
|
||||
const compressed = compressContentPartForRequestRetry(part, preserveAttachments);
|
||||
const compressed = compressContentPartForRequestRetry(
|
||||
part,
|
||||
preserveAttachments,
|
||||
maxToolResultChars,
|
||||
);
|
||||
if (compressed !== part) didAdjust = true;
|
||||
return compressed;
|
||||
});
|
||||
@@ -162,7 +188,11 @@ function compressModelMessageForRequestRetry(
|
||||
return didAdjust ? ({ ...message, content } as ModelMessage) : message;
|
||||
}
|
||||
|
||||
function compressContentPartForRequestRetry(part: unknown, preserveAttachments: boolean): unknown {
|
||||
function compressContentPartForRequestRetry(
|
||||
part: unknown,
|
||||
preserveAttachments: boolean,
|
||||
maxToolResultChars?: number,
|
||||
): unknown {
|
||||
if (!part || typeof part !== "object") return part;
|
||||
const record = part as Record<string, unknown>;
|
||||
const type = record.type;
|
||||
@@ -180,6 +210,26 @@ function compressContentPartForRequestRetry(part: unknown, preserveAttachments:
|
||||
? outputRecord.value
|
||||
: outputRecord.type === "json" ? JSON.stringify(outputRecord.value) : undefined;
|
||||
if (text !== undefined) {
|
||||
if (maxToolResultChars != null && Number.isFinite(maxToolResultChars) && maxToolResultChars > 0) {
|
||||
const routineLimit = Math.floor(maxToolResultChars);
|
||||
// Live SDK tool results arrive as `json`, while persisted history
|
||||
// replays their exact `JSON.stringify` payload as `text`. Use the same
|
||||
// envelope allowance for both so live and replayed tool results stay
|
||||
// byte-for-byte identical (preserving prompt-cache prefixes) and a
|
||||
// result already fitted by capabilityTools is not chopped mid-flight.
|
||||
const effectiveLimit = routineLimit + Math.max(2_048, Math.floor(routineLimit * 0.5));
|
||||
if (text.length <= effectiveLimit) return part;
|
||||
const value = truncateTextWithHeadAndTail(text, effectiveLimit);
|
||||
if (value === text) return part;
|
||||
return {
|
||||
...record,
|
||||
output: {
|
||||
...outputRecord,
|
||||
type: "text",
|
||||
value,
|
||||
},
|
||||
};
|
||||
}
|
||||
// Live SDK tool results are JSON, while persisted results replay as
|
||||
// text. Apply the same reduction before their first model request.
|
||||
const value = compressAndTruncateText(text, RETRY_MAX_TOOL_RESULT_CHARS);
|
||||
|
||||
@@ -437,6 +437,7 @@ export interface AISettings {
|
||||
commandTimeout: number; // seconds, default 60
|
||||
responseIdleTimeout: number; // seconds without response data, default 120
|
||||
maxIterations: number; // doom loop prevention, default 20
|
||||
toolOutputMaxChars?: number; // inline tool result character cap for built-in AI, default 24000
|
||||
webSearchConfig?: WebSearchConfig;
|
||||
}
|
||||
|
||||
|
||||
@@ -214,6 +214,7 @@ export const STORAGE_KEY_AI_COMMAND_BLOCKLIST = 'netcatty_ai_command_blocklist_v
|
||||
export const STORAGE_KEY_AI_COMMAND_TIMEOUT = 'netcatty_ai_command_timeout_v1';
|
||||
export const STORAGE_KEY_AI_RESPONSE_IDLE_TIMEOUT = 'netcatty_ai_response_idle_timeout_v1';
|
||||
export const STORAGE_KEY_AI_MAX_ITERATIONS = 'netcatty_ai_max_iterations_v1';
|
||||
export const STORAGE_KEY_AI_TOOL_OUTPUT_MAX_CHARS = 'netcatty_ai_tool_output_max_chars_v1';
|
||||
export const STORAGE_KEY_AI_SESSION_MESSAGE_CAP = 'netcatty_ai_session_message_cap_v1';
|
||||
export const STORAGE_KEY_AI_SESSIONS = 'netcatty_ai_sessions_v1';
|
||||
/** Byte-budget overflow JSON; further chunks use suffixes _2, _3, etc. */
|
||||
|
||||
Reference in new issue
Block a user