Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions packages/opencode/src/cli/tui/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@ import { Server } from "@/server/server"
import { InstanceRuntime } from "@/project/instance-runtime"
import { Rpc } from "@/util/rpc"
import { upgrade } from "@/cli/upgrade"
import { Config } from "@/config/config"
import { GlobalBus } from "@/bus/global"
import { ServerAuth } from "@/server/auth"
import { writeHeapSnapshot } from "node:v8"
import { Heap } from "@/cli/heap"
import { AppRuntime } from "@/effect/app-runtime"
import { Effect } from "effect"
import { disposeAllInstancesAndEmitGlobalDisposed } from "@/server/global-lifecycle"
import { reloadIfConfigChanged } from "@/server/global-lifecycle"

Heap.start()

Expand Down Expand Up @@ -61,13 +59,7 @@ export const rpc = {
await upgrade().catch(() => {})
},
async reload() {
await AppRuntime.runPromise(
Effect.gen(function* () {
const cfg = yield* Config.Service
yield* cfg.invalidate()
yield* disposeAllInstancesAndEmitGlobalDisposed({ swallowErrors: true })
}),
)
await AppRuntime.runPromise(reloadIfConfigChanged())
},
async shutdown() {
await InstanceRuntime.disposeAllInstances()
Expand Down
92 changes: 92 additions & 0 deletions packages/opencode/src/config/fingerprint.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { createHash } from "crypto"
import { Flag } from "@opencode-ai/core/flag/flag"
import { Glob } from "@opencode-ai/core/util/glob"
import { Effect } from "effect"
import fs from "fs/promises"
import path from "path"
import { isRecord } from "@/util/record"
import { ConfigParse } from "./parse"
import { ConfigPaths } from "./paths"
import { ConfigVariable } from "./variable"

// Most config objects are unordered, but permission maps use last-match
// precedence. Preserve their order, including permissions inside agent config.
export const canonicalEquals = (a: unknown, b: unknown): boolean =>
JSON.stringify(canonicalize(a)) === JSON.stringify(canonicalize(b))

const canonicalize = (value: unknown): unknown => {
if (Array.isArray(value)) return value.map(canonicalize)
if (value && typeof value === "object") {
return Object.fromEntries(
Object.entries(value)
.sort(([x], [y]) => x.localeCompare(y))
.map(([k, v]) => [k, k === "permission" ? v : canonicalize(v)]),
)
}
return value
}

// Normalize expanded config so referenced file changes are visible, while
// harmless key reorders hash equal. Malformed expanded text is hashed as-is.
const normalize = async (file: string, text: string): Promise<string> => {
if (!file.endsWith(".json") && !file.endsWith(".jsonc")) return text
const expanded = await ConfigVariable.substitute({ type: "path", path: file, text })
try {
const value = ConfigParse.jsonc(expanded, file)
// The loader inserts this editor hint itself after the baseline is read.
if (isRecord(value)) delete value.$schema
return JSON.stringify(canonicalize(value))
} catch {
return expanded
}
}

// Content fingerprint of everything the instance config loader reads from disk
// for one project: the project opencode.json/jsonc chain, every config
// directory's agent/mode/command/plugin files, the filtered directories'
// opencode.json/jsonc, and the OPENCODE_CONFIG override file. Mirrors the
// reads in Config's instance loader. Theme files are deliberately excluded:
// they affect rendering only and must not force an instance rebuild.
export const hashInstanceInputs = Effect.fn("ConfigFingerprint.hashInstanceInputs")(function* (
directory: string,
worktree?: string,
) {
const files: string[] = []
for (const file of yield* ConfigPaths.files("opencode", directory, worktree).pipe(Effect.orDie)) {
files.push(file)
}
for (const dir of yield* ConfigPaths.directories(directory, worktree).pipe(Effect.orDie)) {
if (dir.endsWith(".opencode") || dir === Flag.OPENCODE_CONFIG_DIR) {
files.push(path.join(dir, "opencode.json"), path.join(dir, "opencode.jsonc"))
}
for (const pattern of [
"{agent,agents}/**/*.md",
"{mode,modes}/*.md",
"{command,commands}/**/*.md",
"{plugin,plugins}/*.{ts,js}",
]) {
files.push(
...(yield* Effect.promise(() => Glob.scan(pattern, { cwd: dir, absolute: true, dot: true, symlink: true }))),
)
}
}
if (Flag.OPENCODE_CONFIG) files.push(Flag.OPENCODE_CONFIG)

const hash = createHash("sha256")
for (const file of [...new Set(files)].sort()) {
const text = yield* Effect.promise(() =>
fs.readFile(file, "utf8").catch((error: NodeJS.ErrnoException) => {
if (error.code === "ENOENT") return undefined
throw error
}),
)
if (text === undefined) continue
hash.update(file)
hash.update("\0")
hash.update(yield* Effect.promise(() => normalize(file, text)))
hash.update("\0")
}
return hash.digest("hex")
})

export * as ConfigFingerprint from "./fingerprint"
40 changes: 36 additions & 4 deletions packages/opencode/src/project/instance-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { WorkspaceContext } from "@/control-plane/workspace-context"
import { InstanceRef } from "@/effect/instance-ref"
import { disposeInstance as runDisposers } from "@/effect/instance-registry"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { ConfigFingerprint } from "@/config/fingerprint"
import { Context, Deferred, Duration, Effect, Exit, Layer, Scope } from "effect"
import { type InstanceContext } from "./instance-context"
import { InstanceBootstrap } from "./bootstrap-service"
Expand All @@ -24,6 +25,10 @@ export interface Interface {
readonly disposeDirectory: (directory: string) => Effect.Effect<void>
readonly disposeAll: () => Effect.Effect<void>
readonly provide: <A, E, R>(input: LoadInput, effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>
// True when any loaded instance's on-disk config inputs (project config,
// agent/command/mode/plugin files, OPENCODE_CONFIG) changed since that
// instance booted. A missing or unreadable baseline counts as changed.
readonly configChanged: () => Effect.Effect<boolean>
}

export class Service extends Context.Service<Service, Interface>()("@opencode/InstanceStore") {}
Expand All @@ -32,17 +37,29 @@ export const use = serviceUse(Service)

interface Entry {
readonly deferred: Deferred.Deferred<InstanceContext>
configHash?: string
}

const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Service> = Layer.effect(
const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Service | FSUtil.Service> = Layer.effect(
Service,
Effect.gen(function* () {
const project = yield* Project.Service
const bootstrap = yield* InstanceBootstrap.Service
const fsutil = yield* FSUtil.Service
const scope = yield* Scope.Scope
const cache = new Map<string, Entry>()

const boot = (input: LoadInput & { directory: string }) =>
const fingerprint = (ctx: InstanceContext) =>
ConfigFingerprint.hashInstanceInputs(ctx.directory, ctx.worktree).pipe(
Effect.provideService(FSUtil.Service, fsutil),
Effect.catchCause((cause) =>
Effect.logWarning("config fingerprint failed", { directory: ctx.directory, cause }).pipe(
Effect.as(undefined),
),
),
)

const boot = (input: LoadInput & { directory: string }, entry: Entry) =>
Effect.gen(function* () {
const ctx: InstanceContext =
input.project && input.worktree
Expand All @@ -58,6 +75,9 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
project: result.project,
})),
)
// A later snapshot could adopt an edit made after config was consumed
// during bootstrap, leaving stale runtime state undetected on reload.
entry.configHash = yield* fingerprint(ctx)
yield* bootstrap.run.pipe(Effect.provideService(InstanceRef, ctx))
return ctx
}).pipe(Effect.withSpan("InstanceStore.boot"))
Expand All @@ -71,7 +91,7 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser

const completeLoad = (directory: string, input: LoadInput, entry: Entry) =>
Effect.gen(function* () {
const exit = yield* Effect.exit(boot({ ...input, directory }))
const exit = yield* Effect.exit(boot({ ...input, directory }, entry))
if (Exit.isFailure(exit)) yield* removeEntry(directory, entry)
yield* Deferred.done(entry.deferred, exit).pipe(Effect.asVoid)
})
Expand Down Expand Up @@ -186,6 +206,17 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
return yield* cachedDisposeAll
})

const configChanged = Effect.fn("InstanceStore.configChanged")(function* () {
for (const entry of cache.values()) {
const exit = yield* Deferred.await(entry.deferred).pipe(Effect.exit)
if (Exit.isFailure(exit)) continue
if (!entry.configHash) return true
const fresh = yield* fingerprint(exit.value)
if (fresh === undefined || fresh !== entry.configHash) return true
}
return false
})

const provide = <A, E, R>(input: LoadInput, effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>
load(input).pipe(Effect.flatMap((ctx) => effect.pipe(Effect.provideService(InstanceRef, ctx))))

Expand All @@ -198,6 +229,7 @@ const layer: Layer.Layer<Service, never, Project.Service | InstanceBootstrap.Ser
disposeDirectory,
disposeAll,
provide,
configChanged,
})
}),
)
Expand All @@ -207,7 +239,7 @@ export const bootstrapNode = LayerNode.unbound(InstanceBootstrap.Service, Node.t
export const node = makeGlobalNode({
service: Service,
layer: layer,
deps: [Project.node, bootstrapNode],
deps: [Project.node, bootstrapNode, FSUtil.node],
})

export * as InstanceStore from "./instance-store"
39 changes: 38 additions & 1 deletion packages/opencode/src/server/global-lifecycle.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { GlobalBus } from "@/bus/global"
import { Config } from "@/config/config"
import { ConfigFingerprint } from "@/config/fingerprint"
import { InstanceStore } from "@/project/instance-store"
import { Effect } from "effect"
import { Effect, Option } from "effect"
import { Event } from "./event"

export const emitGlobalDisposed = Effect.sync(() =>
Expand All @@ -25,4 +27,39 @@ export const disposeAllInstancesAndEmitGlobalDisposed = Effect.fn("Server.dispos
},
)

// External reload signals (SIGUSR2 from theme switchers such as Omarchy or
// Noctalia hooks) usually mean "repaint": themes are discovered from
// themes/*.json and never touch the config. Disposing instances aborts their
// in-flight sessions, so only pay that cost when config inputs actually
// changed. Covers the global config and every loaded instance's on-disk
// inputs (project config, agent/command/mode/plugin files, OPENCODE_CONFIG).
// A read failure or a missing fingerprint baseline counts as changed, keeping
// the historical unconditional-dispose behavior for any case the gate cannot
// prove is clean. Returns whether instances were disposed.
export const reloadIfConfigChanged = Effect.fn("Server.reloadIfConfigChanged")(function* () {
const config = yield* Config.Service
const store = yield* InstanceStore.Service
// ConfigParse throws on malformed files, surfacing here as a defect rather
// than a typed error, so read via catchAllCause: a failed read must never
// block invalidation, and unprovable means changed.
const read = config.getGlobal().pipe(
Effect.map(Option.some),
Effect.catchCause((cause) =>
Effect.logWarning("global config read failed during reload check", { cause: String(cause) }).pipe(
Effect.as(Option.none()),
),
),
)
const before = yield* read
yield* config.invalidate()
const next = yield* read
const globalChanged =
Option.isNone(before) || Option.isNone(next) || !ConfigFingerprint.canonicalEquals(before.value, next.value)
if (globalChanged || (yield* store.configChanged())) {
yield* disposeAllInstancesAndEmitGlobalDisposed({ swallowErrors: true })
return true
}
return false
})

export * as GlobalLifecycle from "./global-lifecycle"
Loading
Loading