diff --git a/packages/client/src/promise/generated/types.ts b/packages/client/src/promise/generated/types.ts index be9351b6cca..7671045c4b5 100644 --- a/packages/client/src/promise/generated/types.ts +++ b/packages/client/src/promise/generated/types.ts @@ -2331,6 +2331,7 @@ export type ConfigEntry = portable_shell_scanner?: boolean todo?: boolean subagent_depth?: number + location_idle_timeout?: string | false policies?: Array<{ action: "provider.use" | "tool.use" | "integration.use" resource: string diff --git a/packages/core/src/config/normalize.ts b/packages/core/src/config/normalize.ts index 35d702a051f..4ef02b96e5e 100644 --- a/packages/core/src/config/normalize.ts +++ b/packages/core/src/config/normalize.ts @@ -485,6 +485,15 @@ function normalizeExperimental( ) if (value !== undefined) result.subagent_depth = value } + if (own(experimental, "location_idle_timeout")) { + const value = decodeEncoded( + ConfigExperimental.Info.fields.location_idle_timeout, + experimental.location_idle_timeout, + ["experimental", "location_idle_timeout"], + diagnostics, + ) + if (value !== undefined) result.location_idle_timeout = value + } } } if (Object.keys(result).length || (isRecord(input.experimental) && !Object.keys(input.experimental).length)) diff --git a/packages/core/src/location-activity.ts b/packages/core/src/location-activity.ts index 9745f82a60d..c98319027a2 100644 --- a/packages/core/src/location-activity.ts +++ b/packages/core/src/location-activity.ts @@ -1,7 +1,9 @@ export * as LocationActivity from "./location-activity.js" -import { Clock, Context, Duration, Effect, Layer, RcMap, Schema } from "effect" +import { Clock, Context, Duration, Effect, Layer, Option, RcMap, Schema } from "effect" +import type { Document } from "@opencode/schema/config" import { Bus } from "./bus.js" +import { Config } from "./config.js" import { Job } from "./job.js" import { Location } from "./location.js" import { LocationServiceMap } from "./location-service-map.js" @@ -24,14 +26,30 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly const execution = yield* SessionExecution.Service const jobs = yield* Job.Service const sessions = yield* SessionStore.Service - const timeToLive = Duration.toMillis(options.timeToLive ?? "60 minutes") - const entries = new Map() + const timeToLive = Duration.fromInputUnsafe(options.timeToLive ?? "60 minutes") + const entries = new Map() const key = (ref: Location.Ref) => `${LocationServiceMap.canonical(ref).directory}\0${ref.workspaceID ?? ""}` const touch = (ref: Location.Ref) => Effect.sync(() => { - entries.set(key(ref), { ref, expiresAt: clock.currentTimeMillisUnsafe() + timeToLive }) + entries.set(key(ref), { ref, touchedAt: clock.currentTimeMillisUnsafe() }) }) + // Read per location so project config can override the global value. + const idleTimeout = (ref: Location.Ref) => + Effect.gen(function* () { + const context = yield* locations.contextEffectOption(ref) + if (Option.isNone(context)) return timeToLive + const entries = yield* Context.get(context.value, Config.Service).entries() + const configured = entries.findLast( + (entry): entry is Document => + entry.type === "document" && entry.info.experimental?.location_idle_timeout !== undefined, + ) + return configured?.info.experimental?.location_idle_timeout ?? timeToLive + }).pipe( + Effect.scoped, + Effect.orElseSucceed(() => timeToLive), + ) + const unsubscribe = yield* bus.listen((event) => { if (!isSessionEvent(event)) return Effect.void const location = event.location @@ -50,7 +68,11 @@ export function layer(options: { readonly timeToLive?: Duration.Input; readonly if (!cached.has(id)) entries.delete(id) } const now = clock.currentTimeMillisUnsafe() - const expired = Array.from(entries.values()).filter((entry) => entry.expiresAt <= now) + const expired = yield* Effect.filter(Array.from(entries.values()), (entry) => + idleTimeout(entry.ref).pipe( + Effect.map((timeout) => timeout !== false && entry.touchedAt + Duration.toMillis(timeout) <= now), + ), + ) if (expired.length === 0) return // Waiting on a question, a long tool call, or a background job emits no durable activity. const owners = [ diff --git a/packages/core/test/config/normalization.test.ts b/packages/core/test/config/normalization.test.ts index 09b8cfb93cd..7725b7ff43e 100644 --- a/packages/core/test/config/normalization.test.ts +++ b/packages/core/test/config/normalization.test.ts @@ -526,11 +526,17 @@ describe("ConfigNormalize", () => { portable_shell_scanner: true, todo: true, subagent_depth: 0, + location_idle_timeout: "2 hours", policies: [{ action: "provider.use", resource: "custom", effect: "allow" }], }, }).encoded, ).toMatchObject({ - experimental: { portable_shell_scanner: true, todo: true, subagent_depth: 0 }, + experimental: { + portable_shell_scanner: true, + todo: true, + subagent_depth: 0, + location_idle_timeout: "7200000 millis", + }, policies: [ { action: "provider.use", resource: "*", effect: "deny" }, { action: "provider.use", resource: "anthropic", effect: "allow" }, @@ -701,7 +707,7 @@ describe("ConfigNormalize", () => { agents: {}, providers: {}, instructions: [], - experimental: { subagent_depth: 0 }, + experimental: { subagent_depth: 0, location_idle_timeout: false }, }) expect(result.encoded).toMatchObject({ snapshots: false, @@ -710,7 +716,7 @@ describe("ConfigNormalize", () => { agents: {}, providers: {}, instructions: [], - experimental: { subagent_depth: 0 }, + experimental: { subagent_depth: 0, location_idle_timeout: false }, }) expect(result.encoded.share).toBeUndefined() }) diff --git a/packages/core/test/location-activity.test.ts b/packages/core/test/location-activity.test.ts index 256f169198e..e7a10ed1517 100644 --- a/packages/core/test/location-activity.test.ts +++ b/packages/core/test/location-activity.test.ts @@ -6,6 +6,7 @@ import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder" import { LayerNode } from "@opencode/util/effect/layer-node" import { makeGlobalNode } from "@opencode/util/effect/app-node" import { Bus } from "@opencode/core/bus" +import { Config } from "@opencode/core/config" import { Database } from "@opencode/core/database/database" import { Form } from "@opencode/core/form" import { Job } from "@opencode/core/job" @@ -22,8 +23,13 @@ import { SessionRunner } from "@opencode/core/session/runner/index" import { SessionTable } from "@opencode/core/session/sql" import { SessionStore } from "@opencode/core/session/store" import { Workspace } from "@opencode/core/workspace" +import { Document, Info } from "@opencode/schema/config" +import { ConfigExperimental } from "@opencode/schema/config/experimental" import { testEffect } from "./lib/effect" +// Per-workspace experimental.location_idle_timeout, read by each location's Config. +const idleTimeouts = new Map() + // Keep real execution ownership, location caching, forms, and eviction. The fixture // runner waits on a form instead of making a model request before asking a question. const locations = Layer.effect( @@ -32,9 +38,23 @@ const locations = Layer.effect( const bus = yield* Bus.Service const map = yield* LayerMap.make( (ref: Location.Ref) => - // The fixture only exercises these three Location services. + // The fixture only exercises these four Location services. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion - Layer.merge( + Layer.mergeAll( + Config.testLayer( + idleTimeouts.has(ref.workspaceID ?? "") + ? [ + new Document({ + type: "document", + info: new Info({ + experimental: new ConfigExperimental.Info({ + location_idle_timeout: idleTimeouts.get(ref.workspaceID ?? ""), + }), + }), + }), + ] + : [], + ), Layer.succeed( Location.Service, Location.Service.of({ @@ -240,4 +260,30 @@ describe("LocationActivity eviction", () => { expect(Array.from(yield* RcMap.keys(map.rcMap))).toEqual([]) }), ) + + for (const [timeout, after, evicted] of [ + ["10 minutes", "11 minutes", true], + [false, "3 hours", false], + ] as const) + it.effect(`honors experimental.location_idle_timeout = ${JSON.stringify(timeout)}`, () => + Effect.gen(function* () { + const map = yield* LocationServiceMap.Service + const workspaceID = Workspace.ID.make(`wrk_timeout_${String(timeout).replace(" ", "_")}`) + idleTimeouts.set(workspaceID, timeout === false ? false : Duration.fromInputUnsafe(timeout)) + yield* Effect.addFinalizer(() => Effect.sync(() => idleTimeouts.delete(workspaceID))) + const configured = Location.Ref.make({ directory: AbsolutePath.make("/project"), workspaceID }) + const fallback = Location.Ref.make({ directory: AbsolutePath.make("/project") }) + yield* Location.Service.pipe(Effect.provide(map.get(configured)), Effect.scoped) + yield* Location.Service.pipe(Effect.provide(map.get(fallback)), Effect.scoped) + + yield* TestClock.adjust("1 minute") + yield* TestClock.adjust(after) + const cached = Array.from(yield* RcMap.keys(map.rcMap)) + expect(cached.some((ref) => ref.workspaceID === workspaceID)).toBe(!evicted) + // Locations without the setting keep the 60 minute default. + expect(cached.some((ref) => ref.workspaceID === undefined)).toBe( + Duration.toMinutes(Duration.fromInputUnsafe(after)) < 60, + ) + }), + ) }) diff --git a/packages/core/test/location-layer.test.ts b/packages/core/test/location-layer.test.ts index 1987338e0f2..06550852305 100644 --- a/packages/core/test/location-layer.test.ts +++ b/packages/core/test/location-layer.test.ts @@ -2,7 +2,7 @@ import type { FileSystem } from "@opencode/core/filesystem" import fs from "fs/promises" import path from "path" import { describe, expect } from "bun:test" -import { Config } from "@opencode/schema/config" +import { Event } from "@opencode/schema/config" import { Money } from "@opencode/schema/money" import { DateTime, @@ -29,6 +29,7 @@ import { Global } from "@opencode/util/global" import { LocationServiceMap, type LocationServices } from "@opencode/core/location-services" import { LocationActivity } from "@opencode/core/location-activity" import { Location } from "@opencode/core/location" +import { Config } from "@opencode/core/config" import { LocationWatcher } from "@opencode/core/filesystem/location-watcher" import { Plugin } from "@opencode/core/plugin" import { Model } from "@opencode/core/model" @@ -59,14 +60,18 @@ const activityLocations = Layer.effect( LocationServiceMap.Service, LayerMap.make( (ref) => + // LocationActivity reads each location's config during its sweep. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion - Layer.succeed( - Location.Service, - Location.Service.of({ - directory: ref.directory, - workspaceID: ref.workspaceID, - project: { id: Project.ID.global, directory: ref.directory, canonical: ref.directory }, - }), + Layer.merge( + Layer.succeed( + Location.Service, + Location.Service.of({ + directory: ref.directory, + workspaceID: ref.workspaceID, + project: { id: Project.ID.global, directory: ref.directory, canonical: ref.directory }, + }), + ), + Config.testLayer(), ) as unknown as Layer.Layer, { idleTimeToLive: Duration.infinity }, ), @@ -338,19 +343,19 @@ describe("LocationServiceMap", () => { const firstContext = yield* locations.contextEffect(firstRef) const secondContext = yield* locations.contextEffect(secondRef) const received = { first: 0, second: 0 } - yield* bus.subscribe(Config.Event.Updated).pipe( + yield* bus.subscribe(Event.Updated).pipe( Stream.runForEach(() => Effect.sync(() => received.first++)), Effect.provideContext(firstContext), Effect.forkScoped({ startImmediately: true }), ) - yield* bus.subscribe(Config.Event.Updated).pipe( + yield* bus.subscribe(Event.Updated).pipe( Stream.runForEach(() => Effect.sync(() => received.second++)), Effect.provideContext(secondContext), Effect.forkScoped({ startImmediately: true }), ) yield* Effect.sleep("10 millis") - yield* bus.publish(Config.Event.Updated, {}, { location: firstRef }) + yield* bus.publish(Event.Updated, {}, { location: firstRef }) yield* Effect.sleep("10 millis") expect(received).toEqual({ first: 1, second: 0 }) diff --git a/packages/protocol/openapi.json b/packages/protocol/openapi.json index 829c7e20c1f..89a23a1d439 100644 --- a/packages/protocol/openapi.json +++ b/packages/protocol/openapi.json @@ -14324,6 +14324,17 @@ "type": "integer", "minimum": 0 }, + "location_idle_timeout": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "boolean", + "enum": [false] + } + ] + }, "policies": { "type": "array", "items": { diff --git a/packages/schema/src/config/experimental.ts b/packages/schema/src/config/experimental.ts index 515cc77db07..4b378aeb1a6 100644 --- a/packages/schema/src/config/experimental.ts +++ b/packages/schema/src/config/experimental.ts @@ -14,6 +14,12 @@ export class Info extends Schema.Class("ConfigExperimental.Info")({ subagent_depth: NonNegativeInt.pipe(optional).annotate({ description: "Maximum subagent nesting depth. Defaults to 1.", }), + location_idle_timeout: Schema.Union([Schema.DurationFromString, Schema.Literal(false)]) + .pipe(optional) + .annotate({ + description: + 'How long a location can go without session activity before its services are unloaded. Running sessions and background jobs keep a location loaded. Set to false to never unload (default: "60 minutes")', + }), policies: ConfigPolicy.Info.pipe(Schema.Array, optional).annotate({ description: "Deprecated: use top-level policies. Ordered policies controlling access to configured resources", }), diff --git a/services/www/openapi.json b/services/www/openapi.json index 829c7e20c1f..89a23a1d439 100644 --- a/services/www/openapi.json +++ b/services/www/openapi.json @@ -14324,6 +14324,17 @@ "type": "integer", "minimum": 0 }, + "location_idle_timeout": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "boolean", + "enum": [false] + } + ] + }, "policies": { "type": "array", "items": { diff --git a/services/www/public/openapi.json b/services/www/public/openapi.json index 829c7e20c1f..89a23a1d439 100644 --- a/services/www/public/openapi.json +++ b/services/www/public/openapi.json @@ -14324,6 +14324,17 @@ "type": "integer", "minimum": 0 }, + "location_idle_timeout": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "boolean", + "enum": [false] + } + ] + }, "policies": { "type": "array", "items": { diff --git a/services/www/src/docs/content/config.mdx b/services/www/src/docs/content/config.mdx index 314088d13b8..b89d3ea1626 100644 --- a/services/www/src/docs/content/config.mdx +++ b/services/www/src/docs/content/config.mdx @@ -410,20 +410,6 @@ interval and 30-minute active window. See the [warming guide](/warming) for request behavior, customization, and cost considerations. -### Experimental - -Experimental features may change or be removed in a future release. - -Set `todo` to `true` to give agents a `todowrite` tool for tracking multi-step work. - -```jsonc -{ - "experimental": { - "todo": true, - }, -} -``` - ### Skills Add directories or URLs that OpenCode should search for agent skills. @@ -623,3 +609,58 @@ These are useful for: - Keeping sensitive data like API keys in separate files. - Sharing common configuration snippets across multiple config files. + +## Experimental + + + Experimental settings may change, break, or be removed in any release without notice. Don't rely on them for stable + workflows. + + +All experimental settings live under the `experimental` key: + +```jsonc title="opencode.jsonc" +{ + "$schema": "https://opencode.ai/config.json", + "experimental": { + "todo": true, + "subagent_depth": 2, + "portable_shell_scanner": true, + "location_idle_timeout": "4 hours", + }, +} +``` + +### Todos + +Set `todo` to `true` to give agents a `todowrite` tool for tracking multi-step work. Defaults to `false`. + +### Subagent depth + +`subagent_depth` sets how deeply subagents can start their own subagents. Defaults to `1`, so a subagent cannot +start another subagent. + +### Portable shell scanner + +Set `portable_shell_scanner` to `true` to replace the default tree-sitter shell scanner used by permission checks. +Defaults to `false`. See [Permissions](/permissions#scanner) for how it behaves. + +### Location idle timeout + +`location_idle_timeout` controls how long a project location can go without session activity before OpenCode unloads +its services. It takes a duration such as `"2 hours"` and defaults to `"60 minutes"`. Running sessions and background +jobs keep a location loaded. Set it to `false` to never unload idle locations. Project config can override the global +value. + +```jsonc +{ + "experimental": { + "location_idle_timeout": false, + }, +} +``` + +### Deprecated policies + +`experimental.policies` is deprecated. Use top-level [`policies`](/policies) instead. The old key still works and +merges into `policies`. diff --git a/services/www/src/docs/content/permissions.mdx b/services/www/src/docs/content/permissions.mdx index e9c997253a1..31d26e6dcf0 100644 --- a/services/www/src/docs/content/permissions.mdx +++ b/services/www/src/docs/content/permissions.mdx @@ -190,7 +190,8 @@ so authorize only trusted directory boundaries. ## Scanner -Enable the experimental portable shell scanner with: +Enable the experimental portable shell scanner with the following setting. Like all +[experimental settings](/config#experimental), it may change or be removed in a future release. ```jsonc {