xonecas.io
64875
Mc

mini-coder / commit 5be0bb0

feat: improve context sanitization and SDK usage

xonecas2026-03-11 5be0bb08b239eac3f7467e13b011eb760d99cf60 parent 29c124b

7 files changed

src/agent/agent.ts+21−0
@@ -3,15 +3,18 @@ import { type AgentConfig, loadAgents } from "../cli/agents.ts";
33 import type { CommandContext } from "../cli/commands.ts";
44 import { tildePath } from "../cli/output.ts";
55 import { getContextWindow, type ThinkingEffort } from "../llm-api/providers.ts";
6+import type { ContextPruningMode } from "../llm-api/turn.ts";
67 import type { ToolDef } from "../llm-api/types.ts";
78 import { connectMcpServer } from "../mcp/client.ts";
89 import {
910 getPreferredActiveAgent,
1011 listMcpServers,
1112 setPreferredActiveAgent,
13+ setPreferredContextPruningMode,
1214 setPreferredModel,
1315 setPreferredShowReasoning,
1416 setPreferredThinkingEffort,
17+ setPreferredToolResultPayloadCapBytes,
1518 } from "../session/db/index.ts";
1619 import type { SubagentSummary } from "../tools/subagent.ts";
1720 import { getGitBranch } from "./agent-helpers.ts";
@@ -27,6 +30,8 @@ interface AgentOptions {
2730 cwd: string;
2831 initialThinkingEffort: ThinkingEffort | null;
2932 initialShowReasoning: boolean;
33+ initialPruningMode: ContextPruningMode;
34+ initialToolResultPayloadCapBytes: number;
3035 sessionId?: string;
3136 initialPrompt?: string;
3237 reporter: AgentReporter;
@@ -99,6 +104,8 @@ export async function runAgent(
99104 initialModel: currentModel,
100105 initialThinkingEffort: opts.initialThinkingEffort,
101106 initialShowReasoning: opts.initialShowReasoning,
107+ initialPruningMode: opts.initialPruningMode,
108+ initialToolResultPayloadCapBytes: opts.initialToolResultPayloadCapBytes,
102109 sessionId: opts.sessionId,
103110 extraSystemPrompt: opts.agentSystemPrompt,
104111 isSubagent: opts.headless,
@@ -143,6 +150,20 @@ export async function runAgent(
143150 runner.showReasoning = show;
144151 setPreferredShowReasoning(show);
145152 },
153+ get pruningMode() {
154+ return runner.pruningMode;
155+ },
156+ setPruningMode: (mode) => {
157+ runner.pruningMode = mode;
158+ setPreferredContextPruningMode(mode);
159+ },
160+ get toolResultPayloadCapBytes() {
161+ return runner.toolResultPayloadCapBytes;
162+ },
163+ setToolResultPayloadCapBytes: (bytes) => {
164+ runner.toolResultPayloadCapBytes = Math.max(0, bytes);
165+ setPreferredToolResultPayloadCapBytes(runner.toolResultPayloadCapBytes);
166+ },
146167 get planMode() {
147168 return runner.planMode;
148169 },
src/agent/session-runner.ts+9−1
@@ -3,7 +3,7 @@ import type { ImageAttachment } from "../cli/image-types.ts";
33 import { watchForCancel } from "../cli/input.ts";
44 import type { ThinkingEffort } from "../llm-api/providers.ts";
55 import { resolveModel } from "../llm-api/providers.ts";
6-import type { CoreMessage } from "../llm-api/turn.ts";
6+import type { ContextPruningMode, CoreMessage } from "../llm-api/turn.ts";
77 import { runTurn } from "../llm-api/turn.ts";
88 import type { ToolDef } from "../llm-api/types.ts";
99 import {
@@ -35,6 +35,8 @@ interface SessionRunnerOptions {
3535 initialModel: string;
3636 initialThinkingEffort: ThinkingEffort | null;
3737 initialShowReasoning: boolean;
38+ initialPruningMode: ContextPruningMode;
39+ initialToolResultPayloadCapBytes: number;
3840 sessionId?: string | undefined;
3941 extraSystemPrompt?: string | undefined;
4042 isSubagent?: boolean | undefined;
@@ -49,6 +51,8 @@ export class SessionRunner {
4951 public currentModel: string;
5052 public currentThinkingEffort: ThinkingEffort | null;
5153 public showReasoning: boolean;
54+ public pruningMode: ContextPruningMode;
55+ public toolResultPayloadCapBytes: number;
5256
5357 public session!: ActiveSession;
5458 public coreHistory!: CoreMessage[];
@@ -73,6 +77,8 @@ export class SessionRunner {
7377 this.currentModel = opts.initialModel;
7478 this.currentThinkingEffort = opts.initialThinkingEffort;
7579 this.showReasoning = opts.initialShowReasoning;
80+ this.pruningMode = opts.initialPruningMode;
81+ this.toolResultPayloadCapBytes = opts.initialToolResultPayloadCapBytes;
7682 this.extraSystemPrompt = opts.extraSystemPrompt;
7783 this.isSubagent = opts.isSubagent;
7884 this.killSubprocesses = opts.killSubprocesses;
@@ -177,6 +183,8 @@ export class SessionRunner {
177183 : this.tools,
178184 systemPrompt,
179185 signal: abortController.signal,
186+ pruningMode: this.pruningMode,
187+ toolResultPayloadCapBytes: this.toolResultPayloadCapBytes,
180188 ...(this.currentThinkingEffort
181189 ? { thinkingEffort: this.currentThinkingEffort }
182190 : {}),
src/cli/commands.ts+67−0
@@ -1,6 +1,7 @@
11 import * as c from "yoctocolors";
22 import type { ThinkingEffort } from "../llm-api/providers.ts";
33 import { fetchAvailableModels } from "../llm-api/providers.ts";
4+import type { ContextPruningMode } from "../llm-api/turn.ts";
45 import {
56 deleteMcpServer,
67 listMcpServers,
@@ -30,6 +31,10 @@ export interface CommandContext {
3031 setThinkingEffort: (effort: ThinkingEffort | null) => void;
3132 showReasoning: boolean;
3233 setShowReasoning: (show: boolean) => void;
34+ pruningMode: ContextPruningMode;
35+ setPruningMode: (mode: ContextPruningMode) => void;
36+ toolResultPayloadCapBytes: number;
37+ setToolResultPayloadCapBytes: (bytes: number) => void;
3338 planMode: boolean;
3439 setPlanMode: (enabled: boolean) => void;
3540 ralphMode: boolean;
@@ -219,6 +224,63 @@ function handleReasoning(ctx: CommandContext, args: string): void {
219224 writeln(`${PREFIX.error} usage: /reasoning <on|off>`);
220225 }
221226
227+function handleContext(ctx: CommandContext, args: string): void {
228+ const [sub, value] = args.trim().split(/\s+/, 2);
229+ if (!sub) {
230+ const capText =
231+ ctx.toolResultPayloadCapBytes <= 0
232+ ? "off"
233+ : `${Math.round(ctx.toolResultPayloadCapBytes / 1024)}KB (${ctx.toolResultPayloadCapBytes} bytes)`;
234+ writeln(
235+ `${PREFIX.info} pruning=${c.cyan(ctx.pruningMode)} tool-result-cap=${c.cyan(capText)}`,
236+ );
237+ writeln(c.dim(" usage: /context prune <off|balanced|aggressive>"));
238+ writeln(c.dim(" /context cap <off|bytes|kb>"));
239+ return;
240+ }
241+
242+ if (sub === "prune") {
243+ if (value === "off" || value === "balanced" || value === "aggressive") {
244+ ctx.setPruningMode(value);
245+ writeln(`${PREFIX.success} context pruning → ${c.cyan(value)}`);
246+ return;
247+ }
248+ writeln(`${PREFIX.error} usage: /context prune <off|balanced|aggressive>`);
249+ return;
250+ }
251+
252+ if (sub === "cap") {
253+ if (!value) {
254+ writeln(`${PREFIX.error} usage: /context cap <off|bytes|kb>`);
255+ return;
256+ }
257+ if (value === "off") {
258+ ctx.setToolResultPayloadCapBytes(0);
259+ writeln(`${PREFIX.success} tool-result payload cap disabled`);
260+ return;
261+ }
262+ const capMatch = value.match(/^(\d+)(kb)?$/i);
263+ if (!capMatch) {
264+ writeln(`${PREFIX.error} invalid cap: ${c.cyan(value)}`);
265+ return;
266+ }
267+ const base = Number.parseInt(capMatch[1] ?? "", 10);
268+ const capBytes =
269+ (capMatch[2] ?? "").toLowerCase() === "kb" ? base * 1024 : base;
270+ if (!Number.isFinite(capBytes) || capBytes < 0) {
271+ writeln(`${PREFIX.error} invalid cap: ${c.cyan(value)}`);
272+ return;
273+ }
274+ ctx.setToolResultPayloadCapBytes(capBytes);
275+ writeln(
276+ `${PREFIX.success} tool-result payload cap → ${c.cyan(`${capBytes} bytes`)}`,
277+ );
278+ return;
279+ }
280+
281+ writeln(`${PREFIX.error} usage: /context <prune|cap> ...`);
282+}
283+
222284 function handlePlan(ctx: CommandContext): void {
223285 ctx.setPlanMode(!ctx.planMode);
224286 if (ctx.planMode) {
@@ -478,6 +540,7 @@ function handleHelp(
478540 ["/model [id]", "list or switch models (fetches live list)"],
479541 ["/undo", "remove the last turn from conversation history"],
480542 ["/reasoning [on|off]", "toggle display of model reasoning output"],
543+ ["/context [prune|cap]", "configure context pruning and tool-result caps"],
481544 ["/plan", "toggle plan mode (read-only tools + MCP)"],
482545 [
483546 "/ralph",
@@ -586,6 +649,10 @@ export async function handleCommand(
586649 handleReasoning(ctx, args);
587650 return { type: "handled" };
588651
652+ case "context":
653+ handleContext(ctx, args);
654+ return { type: "handled" };
655+
589656 case "plan":
590657 handlePlan(ctx);
591658 return { type: "handled" };
src/index.ts+7−0
@@ -23,9 +23,11 @@ import {
2323 import { autoDiscoverModel } from "./llm-api/providers.ts";
2424
2525 import {
26+ getPreferredContextPruningMode,
2627 getPreferredModel,
2728 getPreferredShowReasoning,
2829 getPreferredThinkingEffort,
30+ getPreferredToolResultPayloadCapBytes,
2931 } from "./session/db/index.ts";
3032 import { getMostRecentSession, printSessionList } from "./session/manager.ts";
3133 import {
@@ -299,6 +301,9 @@ async function main(): Promise<void> {
299301 cwd: runCwd,
300302 initialThinkingEffort: getPreferredThinkingEffort(),
301303 initialShowReasoning: getPreferredShowReasoning(),
304+ initialPruningMode: getPreferredContextPruningMode(),
305+ initialToolResultPayloadCapBytes:
306+ getPreferredToolResultPayloadCapBytes(),
302307 reporter: new HeadlessReporter(),
303308 initialPrompt: args.prompt ?? "",
304309 headless: true,
@@ -336,6 +341,8 @@ async function main(): Promise<void> {
336341 cwd: args.cwd,
337342 initialThinkingEffort: getPreferredThinkingEffort(),
338343 initialShowReasoning: getPreferredShowReasoning(),
344+ initialPruningMode: getPreferredContextPruningMode(),
345+ initialToolResultPayloadCapBytes: getPreferredToolResultPayloadCapBytes(),
339346 reporter: new CliReporter(),
340347 };
341348 if (sessionId) agentOpts.sessionId = sessionId;
src/llm-api/turn.test.ts+90−0
@@ -1,6 +1,9 @@
11 import { describe, expect, test } from "bun:test";
22 import type { CoreMessage } from "./turn.ts";
33 import {
4+ applyContextPruning,
5+ compactToolResultPayloads,
6+ getMessageDiagnostics,
47 getReasoningDeltaFromStreamChunk,
58 isOpenAIGPT,
69 sanitizeGeminiToolMessages,
@@ -222,3 +225,90 @@ describe("sanitizeGeminiToolMessages", () => {
222225 );
223226 });
224227 });
228+
229+describe("applyContextPruning", () => {
230+ test("balanced mode prunes stale tool history", () => {
231+ const messages: CoreMessage[] = [
232+ { role: "user", content: "u1" },
233+ {
234+ role: "assistant",
235+ content: [
236+ { type: "tool-call", toolCallId: "a", toolName: "read", input: {} },
237+ ],
238+ } as unknown as CoreMessage,
239+ {
240+ role: "tool",
241+ content: [
242+ {
243+ type: "tool-result",
244+ toolCallId: "a",
245+ toolName: "read",
246+ output: { text: "payload" },
247+ },
248+ ],
249+ } as unknown as CoreMessage,
250+ { role: "user", content: "u2" },
251+ { role: "assistant", content: "a2" },
252+ { role: "user", content: "u3" },
253+ { role: "assistant", content: "a3" },
254+ { role: "user", content: "u4" },
255+ ];
256+
257+ const pruned = applyContextPruning(messages, "balanced");
258+ expect(pruned.length).toBeLessThan(messages.length);
259+ expect(pruned[pruned.length - 1]?.role).toBe("user");
260+ });
261+});
262+
263+describe("getMessageDiagnostics", () => {
264+ test("aggregates role and tool-result byte stats", () => {
265+ const messages: CoreMessage[] = [
266+ { role: "user", content: "hello" },
267+ {
268+ role: "tool",
269+ content: [
270+ {
271+ type: "tool-result",
272+ toolCallId: "1",
273+ toolName: "read",
274+ output: { value: "abc" },
275+ },
276+ ],
277+ } as unknown as CoreMessage,
278+ ];
279+
280+ const diagnostics = getMessageDiagnostics(messages);
281+ expect(diagnostics.messageCount).toBe(2);
282+ expect(diagnostics.totalBytes).toBeGreaterThan(0);
283+ expect(diagnostics.roleBreakdown.user?.count).toBe(1);
284+ expect(diagnostics.toolResults.count).toBe(1);
285+ expect(diagnostics.toolResults.topContributors[0]?.toolName).toBe("read");
286+ });
287+});
288+
289+describe("compactToolResultPayloads", () => {
290+ test("compacts oversized tool payloads with truncation metadata", () => {
291+ const largePayload = "x".repeat(10_000);
292+ const messages: CoreMessage[] = [
293+ {
294+ role: "tool",
295+ content: [
296+ {
297+ type: "tool-result",
298+ toolCallId: "1",
299+ toolName: "read",
300+ output: { blob: largePayload },
301+ },
302+ ],
303+ } as unknown as CoreMessage,
304+ ];
305+
306+ const compacted = compactToolResultPayloads(messages, 1024);
307+ const part = (compacted[0] as { content: Array<Record<string, unknown>> })
308+ .content[0];
309+ expect(part?.output).toMatchObject({
310+ truncated: true,
311+ strategy: "head-tail",
312+ });
313+ });
314+});
src/llm-api/turn.ts+251−4
@@ -1,5 +1,11 @@
11 import type { FlexibleSchema, StepResult } from "ai";
2-import { dynamicTool, jsonSchema, stepCountIs, streamText } from "ai";
2+import {
3+ dynamicTool,
4+ jsonSchema,
5+ pruneMessages,
6+ stepCountIs,
7+ streamText,
8+} from "ai";
39 import { logApiEvent } from "./api-log.ts";
410 import {
511 getThinkingProviderOptions,
@@ -16,6 +22,217 @@ type ToolSet = NonNullable<StreamTextOptions["tools"]>;
1622 type ToolEntry = ToolSet extends Record<string, infer T> ? T : never;
1723 type StreamChunk = { type?: string; [key: string]: unknown };
1824
25+export type ContextPruningMode = "off" | "balanced" | "aggressive";
26+
27+interface ToolContributorStats {
28+ toolName: string;
29+ count: number;
30+ bytes: number;
31+}
32+
33+interface RoleStats {
34+ count: number;
35+ bytes: number;
36+}
37+
38+interface MessageDiagnostics {
39+ messageCount: number;
40+ totalBytes: number;
41+ roleBreakdown: Record<string, RoleStats>;
42+ toolResults: {
43+ count: number;
44+ bytes: number;
45+ topContributors: ToolContributorStats[];
46+ };
47+}
48+
49+const DEFAULT_TOOL_RESULT_PAYLOAD_CAP_BYTES = 16 * 1024;
50+
51+function getByteLength(value: string): number {
52+ return Buffer.byteLength(value, "utf8");
53+}
54+
55+function safeStringify(value: unknown): string {
56+ try {
57+ return JSON.stringify(value) ?? "null";
58+ } catch {
59+ return JSON.stringify(String(value));
60+ }
61+}
62+
63+export function getMessageDiagnostics(
64+ messages: CoreMessage[],
65+): MessageDiagnostics {
66+ const roleBreakdown: Record<string, RoleStats> = {};
67+ const toolContributorMap = new Map<
68+ string,
69+ { count: number; bytes: number }
70+ >();
71+ let totalBytes = 0;
72+ let toolResultBytes = 0;
73+ let toolResultCount = 0;
74+
75+ for (const message of messages) {
76+ const serializedMessage = safeStringify(message);
77+ const messageBytes = getByteLength(serializedMessage);
78+ totalBytes += messageBytes;
79+
80+ const role = message.role;
81+ const roleStats = roleBreakdown[role] ?? { count: 0, bytes: 0 };
82+ roleStats.count += 1;
83+ roleStats.bytes += messageBytes;
84+ roleBreakdown[role] = roleStats;
85+
86+ if (!Array.isArray(message.content)) continue;
87+ for (const part of message.content) {
88+ if (!isRecord(part)) continue;
89+ const partType = (part as { type?: unknown }).type;
90+ if (partType !== "tool-result") continue;
91+ toolResultCount += 1;
92+
93+ const partRecord = part as Record<string, unknown>;
94+ const rawToolName = partRecord.toolName;
95+ const toolName =
96+ typeof rawToolName === "string" && rawToolName.length > 0
97+ ? rawToolName
98+ : "unknown";
99+ const payload =
100+ "output" in partRecord
101+ ? partRecord.output
102+ : "result" in partRecord
103+ ? partRecord.result
104+ : null;
105+ const payloadBytes = getByteLength(safeStringify(payload));
106+ toolResultBytes += payloadBytes;
107+
108+ const existing = toolContributorMap.get(toolName) ?? {
109+ count: 0,
110+ bytes: 0,
111+ };
112+ existing.count += 1;
113+ existing.bytes += payloadBytes;
114+ toolContributorMap.set(toolName, existing);
115+ }
116+ }
117+
118+ const topContributors = [...toolContributorMap.entries()]
119+ .map(([toolName, stats]) => ({
120+ toolName,
121+ count: stats.count,
122+ bytes: stats.bytes,
123+ }))
124+ .sort((a, b) =>
125+ b.bytes === a.bytes
126+ ? a.toolName.localeCompare(b.toolName)
127+ : b.bytes - a.bytes,
128+ )
129+ .slice(0, 5);
130+
131+ return {
132+ messageCount: messages.length,
133+ totalBytes,
134+ roleBreakdown,
135+ toolResults: {
136+ count: toolResultCount,
137+ bytes: toolResultBytes,
138+ topContributors,
139+ },
140+ };
141+}
142+
143+export function applyContextPruning(
144+ messages: CoreMessage[],
145+ mode: ContextPruningMode,
146+): CoreMessage[] {
147+ if (mode === "off") return messages;
148+ if (mode === "aggressive") {
149+ return pruneMessages({
150+ messages,
151+ reasoning: "before-last-message",
152+ toolCalls: "before-last-2-messages",
153+ emptyMessages: "remove",
154+ }) as CoreMessage[];
155+ }
156+
157+ return pruneMessages({
158+ messages,
159+ reasoning: "before-last-message",
160+ toolCalls: "before-last-3-messages",
161+ emptyMessages: "remove",
162+ }) as CoreMessage[];
163+}
164+
165+function compactHeadTail(
166+ serialized: string,
167+ maxChars = 4096,
168+): { head: string; tail: string } {
169+ const chars = Math.max(512, maxChars);
170+ const headLength = Math.floor(chars / 2);
171+ const tailLength = chars - headLength;
172+ return {
173+ head: serialized.slice(0, headLength),
174+ tail: serialized.slice(-tailLength),
175+ };
176+}
177+
178+export function compactToolResultPayloads(
179+ messages: CoreMessage[],
180+ capBytes = DEFAULT_TOOL_RESULT_PAYLOAD_CAP_BYTES,
181+): CoreMessage[] {
182+ if (!Number.isFinite(capBytes) || capBytes <= 0) return messages;
183+
184+ let mutated = false;
185+ const compacted = messages.map((message) => {
186+ if (message.role !== "tool" || !Array.isArray(message.content)) {
187+ return message;
188+ }
189+
190+ let contentMutated = false;
191+ const nextContent = message.content.map((part) => {
192+ if (!isRecord(part)) return part;
193+ const partType = (part as { type?: unknown }).type;
194+ if (partType !== "tool-result") return part;
195+
196+ const payload =
197+ "output" in part ? part.output : "result" in part ? part.result : null;
198+ const serializedPayload = safeStringify(payload);
199+ const originalBytes = getByteLength(serializedPayload);
200+ if (originalBytes <= capBytes) return part;
201+
202+ const { head, tail } = compactHeadTail(
203+ serializedPayload,
204+ Math.floor(capBytes / 2),
205+ );
206+ const compactedPayload = {
207+ truncated: true,
208+ originalBytes,
209+ strategy: "head-tail",
210+ head,
211+ tail,
212+ };
213+
214+ contentMutated = true;
215+ const partRecord = part as Record<string, unknown>;
216+ if ("output" in partRecord) {
217+ return { ...partRecord, output: compactedPayload };
218+ }
219+ if ("result" in partRecord) {
220+ return { ...partRecord, result: compactedPayload };
221+ }
222+ return { ...partRecord, output: compactedPayload };
223+ });
224+
225+ if (!contentMutated) return message;
226+ mutated = true;
227+ return {
228+ ...message,
229+ content: nextContent as CoreMessage["content"],
230+ } as CoreMessage;
231+ });
232+
233+ return mutated ? compacted : messages;
234+}
235+
19236 export function getReasoningDeltaFromStreamChunk(
20237 chunk: StreamChunk,
21238 ): string | null {
@@ -187,6 +404,8 @@ export async function* runTurn(options: {
187404 systemPrompt?: string;
188405 signal?: AbortSignal;
189406 thinkingEffort?: ThinkingEffort;
407+ pruningMode?: ContextPruningMode;
408+ toolResultPayloadCapBytes?: number;
190409 }): AsyncGenerator<TurnEvent> {
191410 const {
192411 model,
@@ -196,6 +415,8 @@ export async function* runTurn(options: {
196415 systemPrompt,
197416 signal,
198417 thinkingEffort,
418+ pruningMode = "balanced",
419+ toolResultPayloadCapBytes = DEFAULT_TOOL_RESULT_PAYLOAD_CAP_BYTES,
199420 } = options;
200421
201422 let stepCount = 0;
@@ -233,18 +454,44 @@ export async function* runTurn(options: {
233454 modelString,
234455 messageCount: messages.length,
235456 reasoningSummaryRequested,
457+ pruningMode,
458+ toolResultPayloadCapBytes,
236459 });
237460
238- const turnMessages = sanitizeGeminiToolMessages(
461+ const geminiSanitizedMessages = sanitizeGeminiToolMessages(
239462 messages,
240463 modelString,
241464 toolCount > 0,
242465 );
243- if (turnMessages.length !== messages.length) {
466+ if (geminiSanitizedMessages.length !== messages.length) {
244467 logApiEvent("gemini tool history truncated", {
245468 modelString,
246469 originalMessages: messages.length,
247- sanitizedMessages: turnMessages.length,
470+ sanitizedMessages: geminiSanitizedMessages.length,
471+ });
472+ }
473+
474+ logApiEvent(
475+ "turn context pre-prune",
476+ getMessageDiagnostics(geminiSanitizedMessages),
477+ );
478+ const prunedMessages = applyContextPruning(
479+ geminiSanitizedMessages,
480+ pruningMode,
481+ );
482+ logApiEvent(
483+ "turn context post-prune",
484+ getMessageDiagnostics(prunedMessages),
485+ );
486+
487+ const turnMessages = compactToolResultPayloads(
488+ prunedMessages,
489+ toolResultPayloadCapBytes,
490+ );
491+ if (turnMessages !== prunedMessages) {
492+ logApiEvent("turn context post-compaction", {
493+ capBytes: toolResultPayloadCapBytes,
494+ diagnostics: getMessageDiagnostics(turnMessages),
248495 });
249496 }
250497
src/session/db/settings-repo.ts+27−2
@@ -1,3 +1,5 @@
1+import type { ThinkingEffort } from "../../llm-api/providers.ts";
2+import type { ContextPruningMode } from "../../llm-api/turn.ts";
13 import { getDb } from "./connection.ts";
24
35 function getSetting(key: string): string | null {
@@ -25,8 +27,6 @@ export function setPreferredModel(model: string): void {
2527 setSetting("preferred_model", model);
2628 }
2729
28-import type { ThinkingEffort } from "../../llm-api/providers.ts";
29-
3030 export function getPreferredThinkingEffort(): ThinkingEffort | null {
3131 const v = getSetting("preferred_thinking_effort");
3232 if (v === "low" || v === "medium" || v === "high" || v === "xhigh") return v;
@@ -53,6 +53,31 @@ export function setPreferredShowReasoning(show: boolean): void {
5353 setSetting("preferred_show_reasoning", show ? "true" : "false");
5454 }
5555
56+export function getPreferredContextPruningMode(): ContextPruningMode {
57+ const v = getSetting("preferred_context_pruning_mode");
58+ if (v === "off" || v === "balanced" || v === "aggressive") return v;
59+ return "balanced";
60+}
61+
62+export function setPreferredContextPruningMode(mode: ContextPruningMode): void {
63+ setSetting("preferred_context_pruning_mode", mode);
64+}
65+
66+export function getPreferredToolResultPayloadCapBytes(): number {
67+ const v = getSetting("preferred_tool_result_payload_cap_bytes");
68+ if (v === null) return 16 * 1024;
69+ const parsed = Number.parseInt(v, 10);
70+ if (!Number.isFinite(parsed) || parsed < 0) return 16 * 1024;
71+ return parsed;
72+}
73+
74+export function setPreferredToolResultPayloadCapBytes(bytes: number): void {
75+ setSetting(
76+ "preferred_tool_result_payload_cap_bytes",
77+ String(Math.max(0, bytes)),
78+ );
79+}
80+
5681 export function getPreferredActiveAgent(): string | null {
5782 return getSetting("preferred_active_agent");
5883 }