Skip to content

Commit e9540d3

Browse files
rekram1-nodeexe.dev user
andauthored
fix(core): stop waiting on the Console before prompts (#62397)
Co-authored-by: exe.dev user <exedev@anton.exe.xyz>
1 parent 4605a1d commit e9540d3

25 files changed

Lines changed: 260 additions & 653 deletions

‎packages/core/src/config.ts‎

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import { makeLocationNode } from "@opencode/util/effect/app-node"
44
import path from "path"
55
import { isDeepStrictEqual } from "node:util"
66
import { applyEdits, modify, type ParseError, parse } from "jsonc-parser"
7-
import { Context, Effect, FiberMap, Layer, Option, PubSub, Schema, Semaphore, Stream } from "effect"
7+
import { Context, Effect, FiberMap, Layer, Option, PubSub, Ref, Schema, Semaphore, Stream } from "effect"
88
import { Directory, Document, Info, type Patch, type Entry, Event } from "@opencode/schema/config"
99
import { Credential } from "./credential.js"
1010
import { Bus } from "./bus.js"
@@ -33,11 +33,6 @@ export function latest<K extends keyof Info>(entries: readonly Entry[], key: K):
3333
export interface Interface {
3434
/** Returns location config documents and discovery sources from lowest to highest priority. */
3535
readonly entries: () => Effect.Effect<Entry[]>
36-
/**
37-
* The entries `entries()` returns, read synchronously. Transforms read this, so a reload that runs right after a
38-
* config change, such as an integration replacing its document, sees the change before `config.updated` arrives.
39-
*/
40-
readonly snapshot: () => Entry[]
4136
/** Compatibility roots consumed by internal compatibility plugins. */
4237
readonly compatibility?: () => Effect.Effect<{
4338
readonly claude: readonly AbsolutePath[]
@@ -96,24 +91,23 @@ export const testLayer = (
9691
) =>
9792
Layer.effectContext(
9893
Effect.gen(function* () {
99-
const state = { entries: initial, integrations: new Map<string, ConfigIntegration.Document>() }
94+
const entries = yield* Ref.make(initial)
95+
const integrations = yield* Ref.make(new Map<string, ConfigIntegration.Document>())
10096
const updates = yield* PubSub.unbounded<Watcher.Update>()
101-
const snapshot = () => [...state.integrations.values(), ...state.entries]
10297
const service = Test.of({
103-
entries: () => Effect.sync(snapshot),
104-
snapshot,
98+
entries: () =>
99+
Effect.all([Ref.get(integrations), Ref.get(entries)]).pipe(
100+
Effect.map(([documents, entries]) => [...documents.values(), ...entries]),
101+
),
105102
compatibility: () => Effect.succeed(compatibility),
106103
changes: () => Stream.fromPubSub(updates),
107-
setEntries: (next) =>
108-
Effect.sync(() => {
109-
state.entries = next
110-
}),
104+
setEntries: (next) => Ref.set(entries, next),
111105
emitChange: (update) => PubSub.publish(updates, update).pipe(Effect.asVoid),
112106
integration: (integrationID, document) =>
113-
Effect.sync(() => {
114-
const next = new Map(state.integrations)
107+
Ref.update(integrations, (current) => {
108+
const next = new Map(current)
115109
next.delete(integrationID)
116-
state.integrations = document ? next.set(integrationID, document) : next
110+
return document ? next.set(integrationID, document) : next
117111
}),
118112
})
119113
return Context.empty().pipe(Context.add(Service, service), Context.add(Test, service))
@@ -495,7 +489,6 @@ export const layer = (options?: Options) =>
495489
entries: Effect.fnUntraced(function* () {
496490
return configs
497491
}),
498-
snapshot: () => configs,
499492
compatibility: () =>
500493
Effect.all({
501494
claude: Effect.filter(sources.claude, fs.isDir),

‎packages/core/src/config/plugin/entry-observer.ts‎

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,24 +7,23 @@ import { Effect, PubSub, Stream } from "effect"
77
import path from "path"
88
import { Config } from "../../config.js"
99

10-
/**
11-
* Runs `reload` on every `config.updated`. The returned `entries` always reads the current config, so a reload that
12-
* runs before the event arrives already sees the change.
13-
*/
1410
export const observe = Effect.fnUntraced(function* (
1511
config: Config.Interface,
1612
event: EventDomain,
1713
reload: Effect.Effect<void>,
1814
) {
15+
const loaded = { entries: yield* config.entries() }
16+
const refresh = config.entries().pipe(
17+
Effect.tap((entries) => Effect.sync(() => (loaded.entries = entries))),
18+
Effect.andThen(reload),
19+
)
1920
yield* event.subscribe({ types: ["config.updated"] }).pipe(
20-
Stream.runForEach(() => reload),
21+
Stream.runForEach(() => refresh),
2122
Effect.forkScoped({ startImmediately: true }),
2223
)
23-
return {
24-
get entries() {
25-
return config.snapshot()
26-
},
27-
}
24+
// Close the race between the first read and establishing the subscription.
25+
loaded.entries = yield* config.entries()
26+
return loaded
2827
})
2928

3029
/**

‎packages/core/src/config/plugin/mcp.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
export * as ConfigMcpPlugin from "./mcp.js"
22

33
import { define } from "@opencode/plugin/effect/plugin"
4-
import { Document } from "@opencode/schema/config"
4+
import { Document, type Entry } from "@opencode/schema/config"
55
import type { ServerConfig } from "@opencode/schema/mcp"
66
import { Effect, Stream } from "effect"
77
import { Config } from "../../config.js"
@@ -19,19 +19,25 @@ export const register = Effect.fn("ConfigMCPPlugin.register")(function* (
1919
) {
2020
const config = yield* Config.Service
2121
const mcp = yield* Mcp.Service
22+
const loaded = { entries: [] as Entry[] }
2223

2324
yield* events.pipe(
2425
Stream.filter((event) => event.type === "config.updated"),
2526
Stream.runForEach(() =>
26-
mcp.reload().pipe(Effect.catchCause((cause) => Effect.logError("failed to reload MCP config", { cause }))),
27+
config.entries().pipe(
28+
Effect.tap((entries) => Effect.sync(() => (loaded.entries = entries))),
29+
Effect.andThen(mcp.reload()),
30+
Effect.catchCause((cause) => Effect.logError("failed to reload MCP config", { cause })),
31+
),
2732
),
2833
Effect.ignore,
2934
Effect.forkScoped({ startImmediately: true }),
3035
)
3136

32-
// Read at reload time, so a reload right after a config change sees it before `config.updated` arrives.
37+
// Subscribe before the initial load so updates racing it trigger a rebuild.
38+
loaded.entries = yield* config.entries()
3339
yield* mcp.transform((editor) => {
34-
const documents = config.snapshot().filter((entry): entry is Document => entry.type === "document")
40+
const documents = loaded.entries.filter((entry): entry is Document => entry.type === "document")
3541
// Global timeout defaults merge in config order; each server can override them.
3642
const timeout = Object.assign(
3743
{},

‎packages/core/src/console-access.ts‎

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,7 @@
11
export * as ConsoleAccess from "./console-access.js"
22

3-
import { Context, Layer } from "effect"
4-
import { makeGlobalNode } from "@opencode/util/effect/app-node"
53
import type { Credential } from "./credential.js"
64

7-
/**
8-
* How the host keeps a connected Console's config fresh. `poll` re-checks it every minute in the background; without
9-
* it, the config refreshes only when a prompt starts, so a host that suspends between prompts stays idle.
10-
*/
11-
export const Options = Context.Reference<{ readonly poll: boolean }>("@opencode/ConsoleAccess/Options", {
12-
defaultValue: () => ({ poll: true }),
13-
})
14-
15-
export const configured = (options?: { readonly poll?: boolean }) =>
16-
makeGlobalNode({ service: Options, layer: Layer.succeed(Options, { poll: options?.poll ?? true }), deps: [] })
17-
18-
export const node = configured()
19-
205
export const defaultServer = "https://opencode.ai/console"
216

227
/** The OpenCode Console a credential signed in to. */

‎packages/core/src/mcp/index.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -523,10 +523,9 @@ export const layer = (options?: Options) =>
523523

524524
const replaceServer = Effect.fnUntraced(function* (name: ServerName, serverConfig: Mcp.ServerConfig) {
525525
const previous = entries.get(name)
526+
if (previous) yield* disposeServer(previous)
526527
const entry = makeEntry(name, serverConfig, yield* Clock.currentTimeMillis)
527-
// Readers that arrive while the previous connection closes wait for this one instead of using that one.
528528
entries.set(name, entry)
529-
if (previous) yield* disposeServer(previous)
530529
yield* Effect.gen(function* () {
531530
yield* register(name, entry)
532531
if (serverConfig.disabled) {

‎packages/core/src/plugin/internal.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,6 @@ import { Model } from "../model.js"
1515
import { Provider } from "../provider.js"
1616
import { Command } from "../command.js"
1717
import { Config } from "../config.js"
18-
import { ConsoleAccess } from "../console-access.js"
1918
import { Credential } from "../credential.js"
2019
import { llmClient } from "../effect/app-node-platform.js"
2120
import { ConfigAgentPlugin } from "../config/plugin/agent.js"
@@ -123,7 +122,6 @@ const services = [
123122
// Activation clears the ambient context, so built-ins see the configured build channel only through this.
124123
App.Metadata,
125124
FetchHttpClient.Fetch,
126-
ConsoleAccess.Options,
127125
Artifact.Service,
128126
AppProcess.Service,
129127
Provider.Service,
@@ -183,7 +181,6 @@ export type Requirements = Context.Service.Identifier<(typeof services)[number]>
183181
export const requirements = LayerNode.group([
184182
Agent.node,
185183
App.node,
186-
ConsoleAccess.node,
187184
Artifact.node,
188185
AppProcess.node,
189186
Provider.node,

‎packages/core/src/plugin/provider/opencode.ts‎

Lines changed: 21 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -193,17 +193,14 @@ export const OpencodePlugin = define<
193193
const skills = yield* Skill.Service
194194
const cache = yield* SharedCache.Service
195195
const scope = yield* Scope.Scope
196-
const settings = yield* ConsoleAccess.Options
197196
const loading = Semaphore.makeUnsafe(1)
198197
type ActiveConnection = Effect.Success<ReturnType<typeof ctx.integration.connection.active>>
199198
let snapshot: {
200199
// The Console's regular OpenCode config, merged as an integration config layer.
201200
remote: typeof ConsoleConfig.Type | undefined
202201
connection: ActiveConnection
203202
organization: string | undefined
204-
// Fingerprint of an API key, so a key replaced in place counts as a new sign-in.
205-
access: string | undefined
206-
} = { remote: undefined, connection: undefined, organization: undefined, access: undefined }
203+
} = { remote: undefined, connection: undefined, organization: undefined }
207204
let instructions: InstructionDiscovery.File[] = []
208205
// Tagged with the account and workspace they were downloaded for, so a switch hides them right away.
209206
let librarySkills: { owner: string; items: LibrarySkill[] } = { owner: "", items: [] }
@@ -216,18 +213,11 @@ export const OpencodePlugin = define<
216213
let explainers: Effect.Success<ReturnType<typeof ctx.session.hook>>[] = []
217214

218215
// Every project signed in to the same workspace shares one fetch, reused while it is younger than `maxAge`.
219-
// A failed load reports only its connection: what it falls back to depends on the snapshot, which is read under
220-
// `loading` when the outcome is applied.
221-
const load = Effect.fn("OpencodePlugin.load")(function* (
222-
maxAge: Duration.Input = Duration.minutes(1),
223-
): Effect.fn.Return<
224-
| { readonly _tag: "Loaded"; readonly next: typeof snapshot }
225-
| { readonly _tag: "Failed"; readonly connection: ActiveConnection }
226-
> {
216+
const load = Effect.fn("OpencodePlugin.load")(function* (maxAge: Duration.Input = Duration.minutes(1)) {
227217
const connection = yield* ctx.integration.connection.active("opencode")
228218
if (!connection) {
229219
reported = undefined
230-
return { _tag: "Loaded", next: { remote: undefined, connection, organization: undefined, access: undefined } }
220+
return { remote: undefined, connection, organization: undefined }
231221
}
232222
const status = (status: IntegrationConnection.Status | undefined) => {
233223
reported = status
@@ -236,7 +226,7 @@ export const OpencodePlugin = define<
236226
return yield* ctx.integration.connection.resolve(connection).pipe(
237227
Effect.flatMap((credential) => {
238228
if (!credential || credential.type === "external")
239-
return Effect.succeed({ remote: undefined, connection, organization: undefined, access: undefined })
229+
return Effect.succeed({ remote: undefined, connection, organization: undefined })
240230
return cache
241231
.get({
242232
key: `opencode-console:${workspaceKey(connection, credential)}`,
@@ -258,29 +248,25 @@ export const OpencodePlugin = define<
258248
remote,
259249
connection,
260250
organization: organizationName(credential),
261-
access: accessFingerprint(credential),
262251
})),
263252
)
264253
}),
265254
Effect.tap(() => status(undefined)),
266-
Effect.map((next) => ({ _tag: "Loaded" as const, next })),
267255
Effect.catch((cause) =>
268256
Effect.gen(function* () {
269257
// Only well-formed Console errors change the connection status; anything else may be transient.
270258
const next = connectionStatus(cause)
271259
if (next) yield* status(next)
272260
yield* Effect.logWarning("failed to load OpenCode provider config", { cause })
273-
return { _tag: "Failed" as const, connection }
261+
// A load that fails for the connection already in place keeps its last config: dropping it
262+
// would lift organization policy while personal credentials keep working.
263+
return IntegrationConnection.key(connection) === IntegrationConnection.key(snapshot.connection)
264+
? { remote: snapshot.remote, connection, organization: snapshot.organization }
265+
: { remote: undefined, connection, organization: undefined }
274266
}),
275267
),
276268
)
277269
})
278-
// A load that fails for the connection already in place keeps its last config: dropping it would lift
279-
// organization policy while personal credentials keep working.
280-
const fallback = (connection: ActiveConnection): typeof snapshot =>
281-
IntegrationConnection.key(connection) === IntegrationConnection.key(snapshot.connection)
282-
? { ...snapshot, connection }
283-
: { remote: undefined, connection, organization: undefined, access: undefined }
284270
// The Console document as config layered it. Its providers apply at this plugin's position in the provider chain,
285271
// while the rest of the document merges through config.
286272
let integrated: ConfigIntegration.Document | undefined
@@ -422,8 +408,7 @@ export const OpencodePlugin = define<
422408
editor.method.update({ integrationID: "opencode", method: { type: "key", label: "API key (service account)" } })
423409
})
424410

425-
const initial = yield* load()
426-
snapshot = initial._tag === "Loaded" ? initial.next : fallback(initial.connection)
411+
snapshot = yield* load()
427412
yield* publish(snapshot)
428413
yield* ctx.provider.transform((providers) => {
429414
if (integrated) ConfigProviderPlugin.integrate(providers, integrated)
@@ -478,27 +463,15 @@ export const OpencodePlugin = define<
478463
{ concurrency: 5, discard: true },
479464
)
480465
})
466+
const refresh = () => loading.withPermit(load().pipe(Effect.andThen(apply)))
481467
// Annotated: `apply` re-registers the hooks that call `check`, which would otherwise make inference circular.
482-
// Loads run outside `loading`, so a slow one never holds up another check. `wait` bounds the load: one still
483-
// running carries on in `SharedCache`, retries included, for the next check, while the current snapshot stays.
484-
const check = (maxAge?: Duration.Input, wait?: Duration.Input): Effect.Effect<void> =>
485-
Effect.gen(function* () {
486-
const outcome =
487-
wait === undefined
488-
? yield* load(maxAge)
489-
: Option.getOrUndefined(yield* load(maxAge).pipe(Effect.timeoutOption(wait)))
490-
if (!outcome) return
491-
yield* loading.withPermit(
492-
Effect.gen(function* () {
493-
// A switch while this load ran makes it stale; the switch's own check applies the new connection.
494-
const loaded = outcome._tag === "Loaded" ? outcome.next.connection : outcome.connection
495-
const active = yield* ctx.integration.connection.active("opencode")
496-
if (IntegrationConnection.key(loaded) !== IntegrationConnection.key(active)) return
497-
const next = outcome._tag === "Loaded" ? outcome.next : fallback(outcome.connection)
498-
if (!Equal.equals(snapshot, next)) yield* apply(next)
499-
}),
500-
)
501-
})
468+
const check = (maxAge?: Duration.Input): Effect.Effect<void> =>
469+
loading.withPermit(
470+
Effect.gen(function* () {
471+
const next = yield* load(maxAge)
472+
if (!Equal.equals(snapshot, next)) yield* apply(next)
473+
}),
474+
)
502475

503476
// Console inference rejects a missing SSO sign-in with a generic 401/403. Re-check the Console config, which
504477
// reports the reason, and replace the response with instructions when the connection needs the user.
@@ -529,24 +502,18 @@ export const OpencodePlugin = define<
529502
)
530503
})
531504
yield* guard(snapshot)
532-
// A prompt after the machine slept or the host suspended refreshes stale Console config, and the MCP gateway
533-
// tokens it carries, before the turn's tool calls run. An unreachable Console delays the prompt by at most
534-
// 3 seconds; the turn then runs on the config it has.
535-
yield* ctx.session.hook("prompt", () => check(Duration.minutes(1), Duration.seconds(3)))
536505

537506
// Console config can change independently of local credential activity, so re-fetch
538507
// periodically and only rebuild the catalog and search providers when the snapshot differs.
539-
// Only while connected: a signed-out location runs no timer and no credential lookups. Hosts that suspend
540-
// between prompts turn the timer off with the `console.poll` server option and rely on the prompt hook.
508+
// Only while connected: a signed-out location runs no timer and no credential lookups.
541509
const polling = yield* FiberHandle.make<void, never>()
542510
const poll = Effect.fnUntraced(function* () {
543-
if (!snapshot.connection || !settings.poll) return yield* FiberHandle.clear(polling)
511+
if (!snapshot.connection) return yield* FiberHandle.clear(polling)
544512
yield* FiberHandle.run(polling, Effect.sleep(Duration.minutes(1)).pipe(Effect.andThen(check()), Effect.forever), {
545513
onlyIfMissing: true,
546514
})
547515
})
548-
// A switch applies only a changed snapshot, so one a prompt already applied doesn't reload MCP servers mid-turn.
549-
yield* ProviderRefresh.onSwitch("opencode", check().pipe(Effect.andThen(poll())))
516+
yield* ProviderRefresh.onSwitch("opencode", refresh().pipe(Effect.andThen(poll())))
550517
yield* poll()
551518
}),
552519
})
@@ -581,8 +548,6 @@ function fetchConfig(http: HttpClient.HttpClient, value: Credential.Key | Creden
581548
}),
582549
),
583550
Effect.scoped,
584-
// A transient failure, which `SharedCache` retries.
585-
Effect.timeout(Duration.seconds(5)),
586551
)
587552
}
588553

@@ -620,14 +585,9 @@ function workspaceKey(
620585
ConsoleAccess.server(credential),
621586
IntegrationConnection.key(connection),
622587
credential.metadata?.orgID,
623-
accessFingerprint(credential),
624588
])
625589
}
626590

627-
function accessFingerprint(credential: Credential.Key | Credential.OAuth) {
628-
return credential.type === "key" ? SharedCache.fingerprint(credential.key) : undefined
629-
}
630-
631591
function organizationName(credential: Credential.Value) {
632592
return typeof credential.metadata?.orgName === "string" ? credential.metadata.orgName : undefined
633593
}

0 commit comments

Comments
 (0)