feat(core): add experimental.location_idle_timeout (#57476)

This commit is contained in:
Aiden Cline
2026-10-20 15:27:03 -05:00
committed by GitHub
Unverified
parent a13c48b90c
commit d898c048ae
12 changed files with 206 additions and 36 deletions
@@ -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
+9
View File
@@ -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))
+27 -5
View File
@@ -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<string, { readonly ref: Location.Ref; expiresAt: number }>()
const timeToLive = Duration.fromInputUnsafe(options.timeToLive ?? "60 minutes")
const entries = new Map<string, { readonly ref: Location.Ref; touchedAt: number }>()
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 = [
@@ -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()
})
+48 -2
View File
@@ -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<string, Duration.Duration | false>()
// 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,
)
}),
)
})
+16 -11
View File
@@ -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<LocationServices, FileSystem.DirectoryNotFoundError>,
{ 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 })
+11
View File
@@ -14324,6 +14324,17 @@
"type": "integer",
"minimum": 0
},
"location_idle_timeout": {
"anyOf": [
{
"type": "string"
},
{
"type": "boolean",
"enum": [false]
}
]
},
"policies": {
"type": "array",
"items": {
@@ -14,6 +14,12 @@ export class Info extends Schema.Class<Info>("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",
}),
+11
View File
@@ -14324,6 +14324,17 @@
"type": "integer",
"minimum": 0
},
"location_idle_timeout": {
"anyOf": [
{
"type": "string"
},
{
"type": "boolean",
"enum": [false]
}
]
},
"policies": {
"type": "array",
"items": {
+11
View File
@@ -14324,6 +14324,17 @@
"type": "integer",
"minimum": 0
},
"location_idle_timeout": {
"anyOf": [
{
"type": "string"
},
{
"type": "boolean",
"enum": [false]
}
]
},
"policies": {
"type": "array",
"items": {
+55 -14
View File
@@ -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
<Callout type="warning">
Experimental settings may change, break, or be removed in any release without notice. Don't rely on them for stable
workflows.
</Callout>
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`.
@@ -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
{