Repository navigation
Expand file tree
/
Copy pathplugin.ts
More file actions
320 lines (304 loc) · 13.1 KB
/
Copy pathplugin.ts
File metadata and controls
320 lines (304 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
export * as Plugin from "./plugin.js"
export { Event, GuiBundle, ID, Info, Source, State } from "@opencode/schema/plugin"
import { readFile } from "node:fs/promises"
import { fileURLToPath } from "node:url"
import { Plugin } from "@opencode/schema/plugin"
import { Node } from "@opencode/util/effect/app-node"
import { LayerNode } from "@opencode/util/effect/layer-node"
import type { PersistentPty } from "./persistent-pty.js"
import { Cause, Context, Effect, Exit, Latch, Layer, Logger, Queue, References, Scope, Semaphore } from "effect"
import { Bus } from "./bus.js"
import { PluginHost } from "./plugin/host.js"
import { type Failure, type Generation, Service } from "./plugin/service.js"
import { State } from "./state.js"
export { awaitActivation, type Failure, type Generation, type Interface, Service } from "./plugin/service.js"
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const bus = yield* Bus.Service
const scope = yield* Scope.make()
// One slot per requested definition in activation order, including ones whose setup failed, so
// the prefix diff below stays index-aligned and a failed revision is not retried until it changes.
const active = new Map<Plugin.ID, Slot>()
const lock = Semaphore.makeUnsafe(1)
const ready = yield* Latch.make(true)
const pending = new Set<object>()
let closed = false
const holdUnsafe = () => {
if (closed) return Effect.void
const token = {}
pending.add(token)
ready.closeUnsafe()
return Effect.sync(() => {
if (pending.delete(token) && pending.size === 0) ready.openUnsafe()
})
}
const hold = () => Effect.sync(holdUnsafe)
const pendingFailures = yield* Queue.unbounded<PendingFailure>()
let discovered: readonly Failure[] = []
let inventory: Plugin.Info[] = []
const snapshot = () => [...Array.from(active.values()).map(slotInfo), ...discovered]
// A changed `./gui-experimental` bundle alone restarts nothing; its revision is part of what changes, so the event
// tells the app to reload it.
const publish = State.changes(
(items: readonly Plugin.Info[]) => [items, Array.from(active.values(), (entry) => entry.plugin.gui?.revision)],
() => bus.publish(Plugin.Event.Updated, {}).pipe(Effect.asVoid),
)
const list = Effect.fn("Plugin.list")(function* () {
return inventory
})
const gui = Effect.fn("Plugin.gui")(function* (id: Plugin.ID) {
const gui = active.get(id)?.plugin.gui
if (!gui) return undefined
// A plugin that resolved a `./gui-experimental` file but cannot read it now is a server fault, not a missing
// bundle.
const code = yield* Effect.promise(() => readFile(fileURLToPath(gui.file), "utf8"))
return { code, revision: gui.revision, options: gui.options } satisfies Plugin.GuiBundle
})
const hostContext = yield* Effect.context<Effect.Services<ReturnType<typeof PluginHost.make>>>()
const load = Effect.fnUntraced(function* (plugin: Generation) {
const activation: Activation = { plugin, scope: yield* Scope.fork(scope) }
const inherit = yield* State.inherit()
const grouped = State.group((failure, refresh) => {
activation.failure = {
error: `Plugin disabled after ${failure.state}.transform failed. Check server logs for details.`,
ref: `err_${crypto.randomUUID().slice(0, 8)}`,
}
Queue.offerUnsafe(pendingFailures, {
plugin,
scope: activation.scope,
failure,
refresh,
ref: activation.failure.ref,
release: holdUnsafe(),
})
})
const host = yield* PluginHost.make({ list }, plugin.id).pipe(Effect.provideContext(hostContext))
const exit = yield* Effect.suspend(() => plugin.effect(host)).pipe(
grouped,
inherit,
Effect.updateContext((context: Context.Context<never>) =>
Context.make(Scope.Scope, activation.scope).pipe(
Context.add(Logger.CurrentLoggers, Context.get(context, Logger.CurrentLoggers)),
Context.add(References.MinimumLogLevel, Context.get(context, References.MinimumLogLevel)),
),
),
Effect.withSpan("Plugin.load", { attributes: { "plugin.id": plugin.id } }),
Effect.onExit((exit) =>
Exit.isFailure(exit) && !activation.failure ? Scope.close(activation.scope, exit) : Effect.void,
),
Effect.exit,
)
if (activation.failure || Exit.isSuccess(exit)) return { activation } as const
yield* Effect.logWarning("failed to load plugin", {
"plugin.id": plugin.id,
cause: exit.cause,
})
return { error: Cause.pretty(exit.cause) } as const
})
const activate = Effect.fn("Plugin.activate")(function* (
plugins: readonly Generation[],
failures: readonly Failure[] = [],
) {
const definitions = plugins.map((plugin) => ({ ...plugin, id: Plugin.ID.make(plugin.id) }))
const ids = new Set<Plugin.ID>()
for (const definition of definitions) {
if (ids.has(definition.id)) yield* Effect.die(new Error(`Duplicate plugin ID: ${definition.id}`))
ids.add(definition.id)
}
yield* Effect.acquireUseRelease(
hold(),
() =>
lock.withPermit(
Effect.gen(function* () {
if (closed) return
discovered = failures
const current = Array.from(active.values())
const changed = definitions.findIndex((definition, index) => {
const entry = current[index]
return entry?.plugin.id !== definition.id || entry.plugin.revision !== definition.revision
})
const prefix = changed === -1 ? definitions.length : changed
for (const definition of definitions.slice(0, prefix)) {
const entry = active.get(definition.id)
if (entry) active.set(definition.id, { ...entry, plugin: definition })
}
if (prefix === definitions.length && active.size === definitions.length) {
inventory = snapshot()
yield* publish(inventory)
return
}
yield* State.batch(
Effect.gen(function* () {
// Registrations are ordered by setup, so only the unchanged prefix can stay alive.
const previous = new Map(Array.from(active.entries()).slice(prefix))
yield* Effect.forEach(
Array.from(previous.entries()).toReversed(),
([id, slot]) =>
Effect.gen(function* () {
active.delete(id)
if (!slot.activation || slot.activation.failure) return
// Later plugins, including the config agents and commands, are already closed. A failing
// finalizer must not abort the swap, or they stay unregistered until the next reload.
yield* Scope.close(slot.activation.scope, Exit.void).pipe(
Effect.catchCause((cause) =>
Effect.logError("failed to clean up plugin", { "plugin.id": id, cause }),
),
)
}),
{ discard: true },
)
for (const definition of definitions.slice(prefix)) {
const slot = previous.get(definition.id)
// Reordering healthy registrations does not authorize retrying a failed revision.
if (slot?.activation?.failure && slot.plugin.revision === definition.revision) {
active.set(definition.id, { ...slot, plugin: definition })
continue
}
const result = yield* load(definition)
if (result.activation !== undefined) {
active.set(definition.id, {
plugin: definition,
activation: result.activation,
})
continue
}
active.set(definition.id, { plugin: definition, error: result.error })
const fallback = slot?.activation
if (!fallback || fallback.failure) continue
const restored = yield* load(fallback.plugin)
if (restored.activation !== undefined) {
active.set(definition.id, {
plugin: definition,
activation: restored.activation,
error: result.error,
})
continue
}
yield* Effect.logError("failed to restore plugin; deactivating", {
"plugin.id": definition.id,
})
}
inventory = snapshot()
}),
)
yield* publish(inventory)
}),
),
(release) => release,
)
})
yield* Queue.take(pendingFailures).pipe(
Effect.flatMap((item) =>
Effect.gen(function* () {
yield* Effect.logWarning("disabled plugin after transform failure", {
"plugin.id": item.plugin.id,
state: item.failure.state,
ref: item.ref,
cause: Cause.die(item.failure.cause),
})
yield* lock.withPermit(
Effect.gen(function* () {
if (closed) return
// Failure is already recorded on its exact activation, so an old queued item
// cannot disable a replacement and teardown need not wait for this worker.
inventory = snapshot()
const refreshed = yield* State.batch(item.refresh).pipe(Effect.exit)
yield* publish(inventory)
if (Exit.isFailure(refreshed))
yield* Effect.logWarning("failed to refresh state after disabling plugin", {
"plugin.id": item.plugin.id,
ref: item.ref,
cause: refreshed.cause,
})
}),
)
}).pipe(
// Cleanup must also be scheduled if an inventory observer fails. User finalizers
// may await readiness, so never join them under the activation lock or readiness hold.
Effect.ensuring(
Scope.close(item.scope, Exit.void).pipe(
Effect.catchCause((cause) =>
Effect.logWarning("failed to clean up disabled plugin", {
"plugin.id": item.plugin.id,
ref: item.ref,
cause,
}),
),
Effect.forkScoped({ startImmediately: true }),
),
),
Effect.catchCauseIf(
(cause) => !Cause.hasInterrupts(cause),
(cause) =>
Effect.logError("failed to report disabled plugin", {
"plugin.id": item.plugin.id,
ref: item.ref,
cause,
}),
),
Effect.ensuring(item.release),
),
),
Effect.forever,
Effect.forkScoped,
)
const close = (exit: Exit.Exit<unknown, unknown>) =>
lock.withPermit(
Effect.gen(function* () {
closed = true
pending.clear()
ready.openUnsafe()
active.clear()
yield* State.shutdown(Scope.close(scope, exit))
}),
)
yield* Effect.addFinalizer(close)
return Service.of({
activate,
close,
awaitActivation: ready.await,
hold,
list,
gui,
})
}),
)
// `plugin` is the requested definition; `activation` is its last activation, which may have
// failed or be an older fallback while the requested revision keeps failing setup.
type Slot = {
readonly plugin: Generation & { readonly id: Plugin.ID }
readonly activation?: Activation
readonly error?: string
}
// Share the activation across slot snapshots so teardown sees failures synchronously,
// including failures discovered after activate() has captured its previous slots.
type Activation = {
readonly plugin: Generation
readonly scope: Scope.Closeable
failure?: { readonly error: string; readonly ref: string }
}
type PendingFailure = {
readonly plugin: Generation
readonly scope: Scope.Closeable
readonly failure: State.Failure
readonly refresh: Effect.Effect<void>
readonly ref: string
readonly release: Effect.Effect<void>
}
function slotInfo(slot: Slot): Plugin.Info {
const failure = slot.activation?.failure ?? (slot.error === undefined ? undefined : { error: slot.error })
return {
id: slot.plugin.id,
source: slot.plugin.source ?? { type: "builtin" },
state: failure === undefined ? { status: "active" } : { status: "failed", ...failure },
// Built-in and SDK plugins are server parts; a package lists its own parts.
features: slot.plugin.features ?? { server: true },
}
}
export const node: LayerNode.Provider<Service, PersistentPty.UnavailableError, typeof Node.tags.values.location> =
Node.makeLocationNode({
service: Service,
layer,
deps: [PluginHost.requirements],
})