diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts index 37350b4925cf9..d841c6d61c752 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts @@ -314,6 +314,7 @@ const resumed = ( readonly resolveExtractedTextPath?: (path: string) => Effect.Effect; readonly fileSystem?: FileSystem.FileSystem; readonly onPrompt?: (input: unknown) => void; + readonly autoCompactThreshold?: string; }, ) => Effect.gen(function* () { @@ -344,6 +345,9 @@ const resumed = ( ...(options?.resolveExtractedTextPath === undefined ? {} : { resolveExtractedTextPath: options.resolveExtractedTextPath }), + ...(options?.autoCompactThreshold === undefined + ? {} + : { autoCompactThreshold: options.autoCompactThreshold }), }, ); const thread = yield* runtime.resumeThread({ @@ -3188,6 +3192,47 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => { }).pipe(Effect.scoped), ); + it.effect.each([ + { threshold: "150000", expected: 150_000 }, + // At or above the model window the threshold never applies, like Claude's. + { threshold: "160000", expected: undefined }, + { threshold: "200000", expected: undefined }, + ])( + "reports the configured auto-compact threshold $threshold as $expected", + ({ threshold, expected }) => + Effect.gen(function* () { + const { runtime, thread } = yield* resumed( + [ + out("session.prompt", { sessionID: SESSION, text: "" }), + promptAccepted, + event("session.step.ended", { + sessionID: SESSION, + assistantMessageID: "msg_0eb735d5b001oAFVeY5jz3WD4Z", + finish: "stop", + cost: 0, + tokens: { input: 1200, output: 40, reasoning: 0, cache: { read: 0, write: 0 } }, + }), + event("session.execution.succeeded", { sessionID: SESSION }), + ], + { autoCompactThreshold: threshold }, + ); + const settled = yield* runtime.events.pipe( + Stream.filter( + (event) => + event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null, + ), + Stream.runHead, + Effect.forkScoped, + ); + yield* runtime.startTurn(turnInput(thread)); + const turn = Option.getOrUndefined(yield* Fiber.join(settled)); + const tokenUsage = + turn?.type === "provider_turn.updated" ? turn.providerTurn.tokenUsage : undefined; + assert.equal(tokenUsage?.maxTokens, 160000); + assert.equal(tokenUsage?.autoCompactThreshold, expected); + }).pipe(Effect.scoped), + ); + it.effect("clears a staged revert whose commit failed, before the next prompt too", () => Effect.gen(function* () { const kept = "msg_t3_turn_run-attempt:kept:1"; diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts index 9a5f0332f9cc1..2a2530ef406e2 100644 --- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.testkit.ts @@ -241,13 +241,17 @@ const makeReplayAdapter = ( readonly onPrompt?: (input: unknown) => void; readonly replayGate?: ProviderReplayGate; readonly borrowers?: { current: number }; + readonly autoCompactThreshold?: string; }, ) => Effect.gen(function* () { const server = yield* replayServer(transcript, options); - return yield* OpenCode2Adapter.make(ProviderInstanceId.make("opencode")).pipe( - Effect.provideService(OpenCode2Server.OpenCode2Server, server), - ); + return yield* OpenCode2Adapter.make( + ProviderInstanceId.make("opencode"), + options?.autoCompactThreshold === undefined + ? undefined + : { autoCompactThreshold: options.autoCompactThreshold }, + ).pipe(Effect.provideService(OpenCode2Server.OpenCode2Server, server)); }); const layerReplayHost = TestProviderHost.layer().pipe(Layer.provide(NodeServices.layer)); @@ -291,6 +295,7 @@ export const openCode2ReplayRuntime = ( readonly attachmentsDir?: string; readonly resolveExtractedTextPath?: (path: string) => Effect.Effect; readonly fileSystem?: FileSystem.FileSystem; + readonly autoCompactThreshold?: string; }, ) => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/IdleCompaction.test.ts b/apps/server/src/orchestration-v2/IdleCompaction.test.ts index 73b9a8b54caf5..55aacec54b94c 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.test.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.test.ts @@ -5,14 +5,21 @@ import { ProjectId, ProviderDriverKind, ProviderInstanceId, + ProviderSessionId, ProviderThreadId, ProviderTurnId, RunId, + RuntimeRequestId, ThreadId, } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; -import { idleCompactionWindow, type IdleCompactionRecords } from "./IdleCompaction.ts"; +import { + idleCompactionWindow, + openCodeAutoCompactThreshold, + thresholdCompactionDue, + type IdleCompactionRecords, +} from "./IdleCompaction.ts"; const NOW_MS = Date.parse("2026-10-19T12:00:00.000Z"); const MINUTE_MS = 60_000; @@ -154,3 +161,138 @@ describe("idleCompactionWindow", () => { expect(idleCompactionWindow(archived, NOW_MS)).toBeNull(); }); }); + +const openCodeInstanceId = ProviderInstanceId.make("opencode"); + +function openCodeRecords( + usage: { readonly usedTokens?: number; readonly autoCompactThreshold?: number } = {}, +): { -readonly [Key in keyof IdleCompactionRecords]: IdleCompactionRecords[Key] } { + const base = records(usage.usedTokens === undefined ? {} : { usedTokens: usage.usedTokens }); + return { + ...base, + thread: { + ...base.thread, + providerInstanceId: openCodeInstanceId, + modelSelection: { instanceId: openCodeInstanceId, model: "opencode/big-pickle" }, + }, + runs: [ + { + ...base.runs[0]!, + providerInstanceId: openCodeInstanceId, + modelSelection: { instanceId: openCodeInstanceId, model: "opencode/big-pickle" }, + }, + ], + providerThreads: [ + { + ...base.providerThreads[0]!, + driver: ProviderDriverKind.make("opencode"), + providerInstanceId: openCodeInstanceId, + }, + ], + providerTurns: [ + { + ...base.providerTurns[0]!, + tokenUsage: { + usedTokens: usage.usedTokens ?? 250_000, + maxTokens: 1_000_000, + ...(usage.autoCompactThreshold === undefined + ? {} + : { autoCompactThreshold: usage.autoCompactThreshold }), + updatedAt: DateTime.formatIso(at()), + }, + }, + ], + }; +} + +describe("thresholdCompactionDue", () => { + it("fires at and above the threshold, and skips below it", () => { + expect(thresholdCompactionDue(openCodeRecords({ usedTokens: 199_999 }), 200_000)).toBeNull(); + expect(thresholdCompactionDue(openCodeRecords({ usedTokens: 200_000 }), 200_000)).toEqual({ + runId, + }); + expect(thresholdCompactionDue(openCodeRecords({ usedTokens: 400_000 }), 200_000)).toEqual({ + runId, + }); + }); + + it("prefers the threshold the provider reported over the configured one", () => { + // A tighter provider-reported threshold fires even when the configured one is higher. + expect( + thresholdCompactionDue( + openCodeRecords({ usedTokens: 150_000, autoCompactThreshold: 100_000 }), + 200_000, + ), + ).toEqual({ runId }); + // A looser provider-reported threshold holds back a crossed configured one. + expect( + thresholdCompactionDue( + openCodeRecords({ usedTokens: 150_000, autoCompactThreshold: 300_000 }), + 100_000, + ), + ).toBeNull(); + }); + + it("skips unset thresholds, other drivers, and compactions", () => { + expect(thresholdCompactionDue(openCodeRecords(), 0)).toBeNull(); + expect(thresholdCompactionDue(openCodeRecords(), Number.NaN)).toBeNull(); + const claude = records({ usedTokens: 400_000 }); + expect(thresholdCompactionDue(claude, 200_000)).toBeNull(); + const compacted = openCodeRecords({ usedTokens: 400_000 }); + compacted.messages = [{ ...compacted.messages[0]!, text: "/compact" }]; + expect(thresholdCompactionDue(compacted, 200_000)).toBeNull(); + const running = openCodeRecords({ usedTokens: 400_000 }); + running.runs = [{ ...running.runs[0]!, status: "running", completedAt: null }]; + expect(thresholdCompactionDue(running, 200_000)).toBeNull(); + const pending = openCodeRecords({ usedTokens: 400_000 }); + pending.runtimeRequests = [ + { + id: RuntimeRequestId.make("request-1"), + nodeId: NodeId.make("root-node"), + providerTurnId: null, + nativeRequestRef: null, + kind: "permission", + status: "pending", + responseCapability: { + type: "live", + providerSessionId: ProviderSessionId.make("provider-session-1"), + }, + createdAt: at(), + resolvedAt: null, + }, + ]; + expect(thresholdCompactionDue(pending, 200_000)).toBeNull(); + }); +}); + +describe("openCodeAutoCompactThreshold", () => { + const settingsFor = (config: unknown) => ({ + providerInstances: { + [openCodeInstanceId]: { driver: ProviderDriverKind.make("opencode"), config }, + }, + }); + it("reads the instance threshold and rejects empty or invalid values", () => { + expect( + openCodeAutoCompactThreshold( + settingsFor({ autoCompactThreshold: "200000" }), + openCodeInstanceId, + ), + ).toBe(200_000); + expect(openCodeAutoCompactThreshold(settingsFor({}), openCodeInstanceId)).toBeNull(); + expect( + openCodeAutoCompactThreshold(settingsFor({ autoCompactThreshold: "" }), openCodeInstanceId), + ).toBeNull(); + expect( + openCodeAutoCompactThreshold( + settingsFor({ autoCompactThreshold: "lots" }), + openCodeInstanceId, + ), + ).toBeNull(); + expect( + openCodeAutoCompactThreshold( + settingsFor({ autoCompactThreshold: "200000" }), + ProviderInstanceId.make("codex"), + ), + ).toBeNull(); + }); +}); diff --git a/apps/server/src/orchestration-v2/IdleCompaction.ts b/apps/server/src/orchestration-v2/IdleCompaction.ts index b142dd4efb19d..0f7fd65595f44 100644 --- a/apps/server/src/orchestration-v2/IdleCompaction.ts +++ b/apps/server/src/orchestration-v2/IdleCompaction.ts @@ -1,7 +1,14 @@ -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import type { + OrchestrationV2ThreadProjection, + ProviderInstanceId, + ServerSettings as ContractsServerSettings, +} from "@t3tools/contracts"; +import { OpenCodeSettings } from "@t3tools/provider-opencode/settings"; import { COMPACTION_SUGGESTION_MIN_TOKENS } from "@t3tools/shared/claudeCompaction"; import { derivePendingBackgroundWork } from "@t3tools/shared/orchestrationV2PendingBackgroundWork"; import * as DateTime from "effect/DateTime"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; // Claude Code's idleCompaction defaults to 200K and won't go below 100K. Below // that a cold re-read is cheap, so compacting mostly loses context for little @@ -101,3 +108,94 @@ export function idleCompactionWindow( if (!Number.isFinite(endMs) || nowMs >= endMs) return null; return { runId: latestRun.id, startMs: endMs - LEAD_MS, endMs }; } + +const decodeOpenCodeSettings = Schema.decodeUnknownOption(OpenCodeSettings); + +/** + * The instance's configured OpenCode auto-compact threshold in tokens, or + * null when unset or unparsable. An empty value disables threshold compaction. + */ +export const openCodeAutoCompactThreshold = ( + settings: Pick, + instanceId: ProviderInstanceId, +): number | null => { + const config = Object.hasOwn(settings.providerInstances, instanceId) + ? settings.providerInstances[instanceId]?.config + : undefined; + const raw = decodeOpenCodeSettings(config ?? {}).pipe( + Option.getOrUndefined, + (value) => value?.autoCompactThreshold, + ); + const threshold = raw === undefined || raw === "" ? Number.NaN : Number(raw); + return Number.isFinite(threshold) && threshold > 0 ? threshold : null; +}; + +/** + * Whether an OpenCode thread just crossed its configured auto-compact + * threshold. Guards mirror idleCompactionWindow, but there is no cache-expiry + * timing: OpenCode reports no prompt-cache TTL, so the check runs once when + * the completed run's usage is known. + */ +export function thresholdCompactionDue( + { + thread, + runs, + messages, + providerThreads, + providerTurns, + runtimeRequests, + turnItems, + contextTransfers, + }: IdleCompactionRecords, + autoCompactThreshold: number, +): { readonly runId: (typeof runs)[number]["id"] } | null { + if (!Number.isFinite(autoCompactThreshold) || autoCompactThreshold <= 0) return null; + if (thread.deletedAt !== null || thread.archivedAt !== null) return null; + if (thread.settledAt !== null || thread.settledOverride === "settled") return null; + if (thread.lineage.relationshipToParent === "subagent") return null; + const latestRun = runs.reduce<(typeof runs)[number] | null>( + (latest, run) => (latest === null || run.ordinal > latest.ordinal ? run : latest), + null, + ); + if (latestRun?.status !== "completed" || latestRun.completedAt === null) return null; + const message = messages.find((candidate) => candidate.id === latestRun.userMessageId); + // Never compact a compaction, so one completed run compacts at most once. + if (message === undefined || message.text.trim().toLowerCase() === "/compact") return null; + if ( + runtimeRequests.some((request) => request.status === "pending") || + contextTransfers.some( + (transfer) => + transfer.type === "merge_back" && + transfer.targetThreadId === thread.id && + transfer.status === "pending", + ) || + derivePendingBackgroundWork({ + latestRun, + runs, + providerThreads, + turnItems, + activeProviderThreadId: thread.activeProviderThreadId, + }).length > 0 + ) + return null; + const providerThread = providerThreads.find( + (candidate) => candidate.id === thread.activeProviderThreadId, + ); + if ( + providerThread?.driver !== "opencode" || + providerThread.id !== latestRun.providerThreadId || + providerThread.providerInstanceId !== thread.providerInstanceId || + latestRun.providerInstanceId !== thread.providerInstanceId + ) + return null; + const usages = providerTurns + .filter((turn) => turn.providerThreadId === providerThread.id && turn.tokenUsage !== undefined) + .map((turn) => turn.tokenUsage!) + .toSorted((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt)); + const usedTokens = usages[0]?.usedTokens ?? 0; + const reportedThreshold = usages[0]?.autoCompactThreshold ?? null; + const threshold = + reportedThreshold !== null && reportedThreshold > 0 ? reportedThreshold : autoCompactThreshold; + if (usedTokens < threshold) return null; + return { runId: latestRun.id }; +} diff --git a/apps/server/src/orchestration-v2/IdleCompactionService.ts b/apps/server/src/orchestration-v2/IdleCompactionService.ts index 2b16cb8c1d73d..aade80535b383 100644 --- a/apps/server/src/orchestration-v2/IdleCompactionService.ts +++ b/apps/server/src/orchestration-v2/IdleCompactionService.ts @@ -15,7 +15,11 @@ import * as Stream from "effect/Stream"; import { forkParked } from "../serverActivation.ts"; import * as ServerSettings from "../serverSettings.ts"; -import { idleCompactionWindow } from "./IdleCompaction.ts"; +import { + idleCompactionWindow, + openCodeAutoCompactThreshold, + thresholdCompactionDue, +} from "./IdleCompaction.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; @@ -49,8 +53,6 @@ export const make = Effect.gen(function* () { { messageRunIds: [runId], turnItemStatuses: ["pending", "running", "waiting"] }, ); if ( - resolveIdleCompaction(current, records.thread.providerInstanceId) !== - "beforeCacheExpires" || !resolveProjectProviderInstanceEnabled( current, records.thread.projectId, @@ -58,6 +60,29 @@ export const make = Effect.gen(function* () { ) ) return; + // Usage-fraction trigger for OpenCode threads: no cache timing, so a + // crossed threshold compacts on the completed run without waiting. + const threshold = openCodeAutoCompactThreshold(current, records.thread.providerInstanceId); + if (threshold !== null && thresholdCompactionDue(records, threshold)?.runId === runId) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + // One compaction per completed run, even across duplicate events. + commandId: CommandId.make(`server:threshold-compact:${threadId}:${runId}`), + messageId: MessageId.make(`threshold-compact:${threadId}:${runId}`), + threadId, + text: IDLE_COMPACTION_TEXT, + attachments: [], + createdBy: "agent", + creationSource: "server", + idleCompaction: "threshold", + dispatchMode: { type: "start_immediately" }, + }); + return; + } + if ( + resolveIdleCompaction(current, records.thread.providerInstanceId) !== "beforeCacheExpires" + ) + return; const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const window = idleCompactionWindow(records, nowMs); if (window?.runId !== runId) return; diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts index 2fae89baadcf8..2c5406149d37e 100644 --- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts +++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts @@ -541,7 +541,9 @@ describe("deriveMessagesTimelineRows", () => { const [history0, history1, history2, liveUser, , liveAssistant] = fixture.visibleTurnItems; if (liveUser?.item.type !== "user_message" || liveAssistant?.item.type !== "assistant_message") throw new Error("Expected live fixture items"); - const compactPrompt = (idleCompaction: "beforeCacheExpires" | "onReturn" | undefined) => ({ + const compactPrompt = ( + idleCompaction: "beforeCacheExpires" | "onReturn" | "threshold" | undefined, + ) => ({ ...liveUser, item: { ...liveUser.item, text: "/compact", idleCompaction }, }); @@ -590,6 +592,15 @@ describe("deriveMessagesTimelineRows", () => { { kind: "working", compacting: "Compacting after being idle…" }, "Context compacted after being idle", ], + [ + "threshold", + { + kind: "context-compaction", + active: true, + label: "Compacting past the threshold…", + }, + "Context automatically compacted past the threshold", + ], [undefined, { kind: "context-compaction", active: true }, undefined], ] as const) { const prompt = compactPrompt(reason); diff --git a/docs/user/providers-opencode.md b/docs/user/providers-opencode.md index 9ecee2a0439c2..9c3e4a0952d4d 100644 --- a/docs/user/providers-opencode.md +++ b/docs/user/providers-opencode.md @@ -22,6 +22,18 @@ started on 1.x continue on 2.x. Plan mode uses OpenCode's `plan` agent. +## Compact long conversations + +Set **Auto-compact after** in the OpenCode provider settings to an integer +between `1000` and `10000000`. For example, `200000` compacts the thread once +its context reaches about 200,000 tokens. Leave it empty to compact only when +the model's context window is nearly full. The compaction appears in the thread +as a `/compact` turn sent by T3 Code. Automatic threshold compaction needs +OpenCode 2, which reports context usage; on 1.x only manual compaction applies. + +You can also send `/compact` in an existing conversation. Web and desktop offer +**Compact context** from the context meter. + ## Local or external server Leave **Server URL** empty to let T3 Code start OpenCode locally. A password in diff --git a/packages/client-runtime/src/userMessage.ts b/packages/client-runtime/src/userMessage.ts index 8f5eb2e2ffec3..9da39cd5d584a 100644 --- a/packages/client-runtime/src/userMessage.ts +++ b/packages/client-runtime/src/userMessage.ts @@ -10,12 +10,14 @@ import { export const IDLE_COMPACTING_LABELS = { beforeCacheExpires: "Compacting before the cache expires…", onReturn: "Compacting after being idle…", + threshold: "Compacting past the threshold…", } satisfies Record; /** Leads the finished compaction's token counts, in place of "Context compacted". */ export const IDLE_COMPACTION_TITLES = { beforeCacheExpires: "Context automatically compacted before cache expiry", onReturn: "Context compacted after being idle", + threshold: "Context automatically compacted past the threshold", } satisfies Record; const LEGACY_AUTOMATION_PREFIX = /^\[Triggered by schedule task: [^\r\n]+\]\r?\n\r?\n/; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index b3a85fa3700d8..da33809d0dcf9 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1157,7 +1157,11 @@ export const OrchestrationV2Notification = Schema.Struct({ export type OrchestrationV2Notification = typeof OrchestrationV2Notification.Type; /** Why T3 Code compacted a thread on its own, on the `/compact` it sent. */ -export const OrchestrationV2IdleCompaction = Schema.Literals(["beforeCacheExpires", "onReturn"]); +export const OrchestrationV2IdleCompaction = Schema.Literals([ + "beforeCacheExpires", + "onReturn", + "threshold", +]); export type OrchestrationV2IdleCompaction = typeof OrchestrationV2IdleCompaction.Type; export const OrchestrationV2ConversationMessage = Schema.Struct({ diff --git a/packages/provider-opencode/src/server/driver.ts b/packages/provider-opencode/src/server/driver.ts index 713bc3f05ad27..d598c0b55617c 100644 --- a/packages/provider-opencode/src/server/driver.ts +++ b/packages/provider-opencode/src/server/driver.ts @@ -279,9 +279,9 @@ export const OpenCodeDriver: ProviderDriver< const orchestrationAdapter = selectOpenCodeRuntimeAdapter({ probe: runtimeProbe, v1: openCodeV1Adapter, - v2: yield* OpenCode2AdapterV2.make(instanceId).pipe( - Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server), - ), + v2: yield* OpenCode2AdapterV2.make(instanceId, { + autoCompactThreshold: effectiveConfig.autoCompactThreshold, + }).pipe(Effect.provideService(OpenCode2Server.OpenCode2Server, openCode2Server)), }); const loadOpenCode2Models = yield* makeOpenCode2ModelLoader( openCode2Server.withConnection(({ client }) => loadOpenCode2Catalog(client, host.paths.cwd)), diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.ts index 229dc38e66b94..36bdb7667d96d 100644 --- a/packages/provider-opencode/src/server/v2/adapter.ts +++ b/packages/provider-opencode/src/server/v2/adapter.ts @@ -646,7 +646,19 @@ const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["s hasSubagents: turn.usedSubagents, }; -export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: ProviderInstanceId) { +// The configured threshold applies to the turn too, so the context meter and +// handoff budget read the same value before the thread snapshot lands. +const openCodeAutoCompactThreshold = (autoCompactThreshold: string, maxTokens: number | null) => { + const threshold = Number(autoCompactThreshold); + return threshold > 0 && (maxTokens === null || threshold < maxTokens) + ? { autoCompactThreshold: threshold } + : {}; +}; + +export const make = Effect.fn("OpenCode2Adapter.make")(function* ( + instanceId: ProviderInstanceId, + options?: { readonly autoCompactThreshold?: string | undefined }, +) { const server = yield* OpenCode2Server.OpenCode2Server; const idAllocator = yield* IdAllocator.IdAllocatorV2; const host = yield* ProviderHost.ProviderHost; @@ -655,6 +667,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr const continuationRequests = yield* ProviderContinuationRequests.ProviderContinuationRequests; const crypto = yield* Crypto.Crypto; const driver = OPENCODE_PROVIDER; + const autoCompactThreshold = options?.autoCompactThreshold ?? ""; const mcpServerNameFor = (threadId: string) => t3McpServerName(threadId).pipe(Effect.provideService(Crypto.Crypto, crypto)); @@ -1590,6 +1603,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Pr cachedInputTokens: lastStep.cache.read, outputTokens: lastStep.output, reasoningOutputTokens: lastStep.reasoning, + ...openCodeAutoCompactThreshold(autoCompactThreshold, window ?? null), updatedAt: DateTime.formatIso(completedAt), }, }), diff --git a/packages/provider-opencode/src/settings.ts b/packages/provider-opencode/src/settings.ts index e6a21e99691b9..e15fc153c1d52 100644 --- a/packages/provider-opencode/src/settings.ts +++ b/packages/provider-opencode/src/settings.ts @@ -9,6 +9,10 @@ import { import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; +// OpenCode reports no cache TTL, so idle compaction is usage-only. An empty +// value disables automatic threshold compaction for the instance. +const OPENCODE_AUTO_COMPACT_THRESHOLD_PATTERN = /^(?:|[1-9]\d{3,}|10000000)$/; + export const OpenCodeSettings = makeProviderSettingsSchema( { enabled: Schema.Boolean.pipe( @@ -25,6 +29,20 @@ export const OpenCodeSettings = makeProviderSettingsSchema( }, }), ), + autoCompactThreshold: TrimmedString.check( + Schema.isPattern(OPENCODE_AUTO_COMPACT_THRESHOLD_PATTERN), + ).pipe( + Schema.withDecodingDefault(Effect.succeed("")), + Schema.annotateKey({ + title: "Auto-compact after", + description: + "Compact after 1,000 to 10,000,000 tokens. Leave empty to disable automatic compaction.", + providerSettingsForm: { + placeholder: "e.g. 200000", + clearWhenEmpty: "omit", + }, + }), + ), serverUrl: TrimmedString.pipe( Schema.withDecodingDefault(Effect.succeed("")), Schema.annotateKey({ @@ -55,7 +73,7 @@ export const OpenCodeSettings = makeProviderSettingsSchema( ), }, { - order: ["binaryPath", "serverUrl", "serverPassword"], + order: ["binaryPath", "autoCompactThreshold", "serverUrl", "serverPassword"], }, ); export type OpenCodeSettings = typeof OpenCodeSettings.Type;