Skip to content

Commit 9964772

Browse files
authored
chore(core): revert niche fixes from the daily review job (#66140)
1 parent 66d53a8 commit 9964772

21 files changed

Lines changed: 56 additions & 850 deletions

File tree

‎packages/core/src/automation.ts‎

Lines changed: 3 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -254,25 +254,14 @@ const layer = Layer.effect(
254254
const doorbell = yield* Latch.make()
255255
const watches = yield* FiberMap.make<ID>()
256256

257-
/**
258-
* Runs `effect` with `owner`'s Session capabilities. A plugin provides its instance's selector, which can serve the
259-
* instance while it is still booting.
260-
*/
261-
const inSession =
262-
(owner: SessionSchema.Info) =>
263-
<A, E, R>(effect: Effect.Effect<A, E, R>) =>
264-
Effect.flatMap(Effect.serviceOption(Instance.Service), (selector) =>
265-
Option.getOrElse(selector, () => instances).provide(owner)(effect),
266-
)
267-
268257
/**
269258
* The agent a run's child Session starts with, if `owner` could start it with the subagent tool: not hidden, not
270259
* primary-only, within the depth limit and already allowed in the owner's current Location. The code/tools
271260
* authorized when the automation was created do not grant permission to start a child.
272261
*/
273262
const subagent = (owner: SessionSchema.Info, id: Agent.ID, invocation?: Invocation) =>
274263
Effect.gen(function* () {
275-
yield* AutomationCode.awaitPlugins.pipe(Effect.mapError((reason) => new InvalidError({ reason })))
264+
yield* Plugin.awaitActivation
276265
const location = yield* Location.Service
277266
if (location.project.id !== owner.projectID)
278267
return yield* new InvalidError({ reason: "The creating session's location is no longer in its project" })
@@ -307,7 +296,7 @@ const layer = Layer.effect(
307296
),
308297
)
309298
return agent
310-
}).pipe(inSession(owner))
299+
}).pipe(instances.provide(owner))
311300

312301
/** Runs `effect` in the Location of `directory`; fails with DirectoryNotFoundError when the folder is gone. */
313302
const inDirectory =
@@ -1107,7 +1096,7 @@ const layer = Layer.effect(
11071096
if (action.type === "shell") {
11081097
if (!owner) return yield* new InvalidError({ reason: "A shell action needs a session" })
11091098
yield* AutomationShell.authorize(owner, input.name, trigger, action, invocation).pipe(
1110-
inSession(owner),
1099+
instances.provide(owner),
11111100
Effect.mapError((error) => (typeof error === "string" ? new InvalidError({ reason: error }) : error)),
11121101
)
11131102
return action

‎packages/core/src/automation/code.ts‎

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ export * as AutomationCode from "./code.js"
22

33
import { CodeMode } from "@opencode/codemode"
44
import { Automation } from "@opencode/schema/automation"
5-
import { Array, Context, Effect, Option, Result, Schema } from "effect"
5+
import { Array, Effect, Option, Result, Schema } from "effect"
66
import { Agent } from "../agent.js"
77
import { CodeModeTool } from "../codemode/tool.js"
88
import { Permission } from "../permission.js"
@@ -83,24 +83,6 @@ function scanProgram(code: string): Result.Result<ProgramScan, string> {
8383
return Result.succeed({ tools: scanned.success.tools, actions: extensionActions(scanned.success) })
8484
}
8585

86-
/** The calling plugin's registry. SDK instances and the host can have separate registries at the same Location. */
87-
export const FromPlugin = Context.Reference<Plugin.Interface | undefined>("@opencode/AutomationCode/FromPlugin", {
88-
defaultValue: () => undefined,
89-
})
90-
91-
/**
92-
* Waits for this registry's plugins. A create from a plugin in this same registry is refused instead while it activates:
93-
* its activation may be waiting on that plugin's setup, and configured permissions are applied by plugins that load later.
94-
*/
95-
export const awaitPlugins = Effect.gen(function* () {
96-
const plugins = yield* Plugin.Service
97-
if ((yield* FromPlugin) !== plugins) return yield* plugins.awaitActivation
98-
if (yield* plugins.activated) return
99-
return yield* Effect.fail(
100-
"Plugins in this location are still loading, so configured permissions are not applied yet. Create this automation after plugin setup, for example from an event handler.",
101-
)
102-
})
103-
10486
/**
10587
* Runs in the creating Session's Location while the user is present: asks once for tool and extension permissions (and for
10688
* `execute` if none of those needed approval), without saving, so every run can be allowed unattended.
@@ -113,7 +95,7 @@ export const authorize = Effect.fnUntraced(function* (
11395
invocation?: Invocation,
11496
) {
11597
const scanned = yield* Effect.fromResult(scan(action.code))
116-
yield* awaitPlugins
98+
yield* Plugin.awaitActivation
11799
const permission = yield* Permission.Service
118100
const agents = yield* Agent.Service
119101
const agent = yield* agents.select(session.agent)

‎packages/core/src/automation/shell.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import { Shell } from "../shell.js"
1212
import { ShellPermissions } from "../shell/permissions.js"
1313
import { ShellSelect } from "../shell/select.js"
1414
import { type Invocation, matchesAuthor } from "./author.js"
15-
import { AutomationCode } from "./code.js"
1615

1716
export const authorize = Effect.fnUntraced(function* (
1817
owner: SessionSchema.Info,
@@ -21,7 +20,7 @@ export const authorize = Effect.fnUntraced(function* (
2120
action: Automation.ShellAction,
2221
invocation?: Invocation,
2322
) {
24-
if (invocation || (yield* AutomationCode.FromPlugin)) yield* AutomationCode.awaitPlugins
23+
if (invocation) yield* Plugin.awaitActivation
2524
const agents = yield* Agent.Service
2625
const agent = yield* agents.select(owner.agent)
2726
if (invocation && !matchesAuthor(owner, agent.info, invocation))

‎packages/core/src/model-lookup.ts‎

Lines changed: 0 additions & 23 deletions
This file was deleted.

‎packages/core/src/model.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { State } from "./state.js"
88
import { Location } from "./location.js"
99
import { freeze } from "immer"
1010
import { AISDKNative } from "./aisdk-native.js"
11-
import { lookupModel } from "./model-lookup.js"
1211

1312
export const ID = Model.ID
1413
export type ID = typeof ID.Type
@@ -294,12 +293,7 @@ const layer = Layer.effect(
294293
transform: (update) => prepare.pipe(Effect.andThen(state.transform(update))),
295294
reload,
296295
get: Effect.fn("Model.get")((providerID, modelID) =>
297-
read().pipe(
298-
Effect.map((value) => {
299-
const models = value.byProvider.get(providerID)
300-
return lookupModel(providerID, modelID, (id) => models?.get(id))
301-
}),
302-
),
296+
read().pipe(Effect.map((value) => value.byProvider.get(providerID)?.get(modelID))),
303297
),
304298
all: Effect.fn("Model.all")(() => read().pipe(Effect.map((value) => value.all))),
305299
available: Effect.fn("Model.available")((types?: readonly Model.Type[]) =>

‎packages/core/src/models-dev.ts‎

Lines changed: 14 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -290,23 +290,16 @@ const normalize = Effect.fnUntraced(function* (
290290
return [
291291
{ ...base, variants },
292292
...tiers.flatMap((tier) => {
293-
const mode = modes.find(([key, options]) => (options.service_tier ?? key) === tier)
294-
// A mode for the tier keeps its ID, so a saved session asks for the same tier, unless another model already
295-
// has that ID. Otherwise "priority" is the tier people know as fast.
296-
const name =
297-
mode && !ids.has(Model.ID.make(`${source.model.id}-${mode[0]}`))
298-
? mode[0]
299-
: tier === "priority" && !tiers.includes("fast")
300-
? "fast"
301-
: tier
293+
// "priority" is the tier people know as fast.
294+
const name = tier === "priority" && !tiers.includes("fast") ? "fast" : tier
302295
const speedID = Model.ID.make(`${source.model.id}-${name}`)
303-
// A mode's ID stays with the tier it asks for, even when another tier has that name.
304-
if (ids.has(speedID) || (!mode && modes.some(([key]) => key === name))) return []
296+
if (ids.has(speedID)) return []
297+
// Until every tier has a multiplier, a mode for the tier may still carry its price.
298+
const mode = modes.find(([key, options]) => (options.service_tier ?? key) === tier)?.[1]
305299
return [
306300
modelInfo(providerID, { packageName, baseURL }, speedID, source, {
307301
...speed(name, tier),
308-
// Until every tier has a multiplier, a mode for the tier may still carry its price.
309-
cost: modeCost(source.model, baseCost, tier, { cost: mode?.[1].cost }),
302+
cost: modeCost(source.model, baseCost, tier, { cost: mode?.cost }),
310303
request: tierRequest(source.route.protocol, tier),
311304
}),
312305
]
@@ -502,7 +495,7 @@ function modeCost(model: SourceModel, base: Model.Info["cost"], name: string, mo
502495
if (mode.cost) return [cost(mode.cost)[0], ...baseTiers]
503496
const tier = mode.service_tier ?? name
504497
// A tier's multiplier may only hold for some dates (an introductory price); the one for today is used.
505-
const today = utcDay()
498+
const today = new Date().toISOString().slice(0, 10)
506499
const factor = model.cost?.multipliers?.find((multiplier) => {
507500
if (!Object.keys(multiplier.when).every((key) => key === "service_tier" || key === "date")) return false
508501
if (Option.getOrUndefined(decodeServiceTier(multiplier.when.service_tier))?.equals !== tier) return false
@@ -557,11 +550,6 @@ function tierPrices(source: SourceCost | undefined, base: Model.Info["cost"][num
557550
}
558551
}
559552

560-
// Prices are dated by the UTC day, so normalized models are only good until it changes.
561-
function utcDay() {
562-
return new Date().toISOString().slice(0, 10)
563-
}
564-
565553
const decodeServiceTier = Schema.decodeUnknownOption(Schema.Struct({ equals: Schema.optional(Schema.String) }))
566554
// ISO dates (YYYY-MM-DD), which compare as strings.
567555
const decodeDate = Schema.decodeUnknownOption(
@@ -701,19 +689,18 @@ export const decodeSnapshot = (text: string, recommended = false, speeds = false
701689
// packages/core/src/models-dev/snapshot.txt and refreshed via
702690
// `bun run script/update-models-snapshot.ts`. Release builds bundle the live
703691
// catalog in its place when it can be fetched. Decoded and normalized once per
704-
// flag value per isolate and day: the snapshot is a multi-MB module-level constant and one isolate can
692+
// flag value per isolate: the snapshot is a multi-MB module-level constant and one isolate can
705693
// host many runtimes (Cloudflare colocates Durable Object instances), so
706694
// per-runtime decoding would multiply the cost.
707-
const bundledCache = new Map<string, { readonly day: string; readonly snapshot: readonly Snapshot[] }>()
695+
const bundledCache = new Map<string, readonly Snapshot[]>()
708696
const bundledSnapshot = (recommended: boolean, speeds: boolean) =>
709697
Effect.suspend(() => {
710698
const key = `${recommended}:${speeds}`
711-
const day = utcDay()
712699
const cached = bundledCache.get(key)
713-
return cached?.day === day
714-
? Effect.succeed(cached.snapshot)
700+
return cached
701+
? Effect.succeed(cached)
715702
: decodeSnapshot(snapshotText, recommended, speeds).pipe(
716-
Effect.tap((snapshot) => Effect.sync(() => bundledCache.set(key, { day, snapshot }))),
703+
Effect.tap((snapshot) => Effect.sync(() => bundledCache.set(key, snapshot))),
717704
)
718705
})
719706

@@ -859,13 +846,6 @@ export const layer = (options?: Options) =>
859846
([recommended, speeds]) => Effect.cachedInvalidateWithTTL(populate(recommended, speeds), Duration.infinity),
860847
)
861848
const get = (recommended = false, speeds = false) => caches[Number(recommended) * 2 + Number(speeds)][0]
862-
// The UTC day the cached models were priced for.
863-
const priced = { day: utcDay() }
864-
const invalidate = Effect.gen(function* () {
865-
priced.day = utcDay()
866-
yield* Effect.forEach(caches, ([, invalidate]) => invalidate, { discard: true })
867-
yield* bus.publish(ModelsDev.Event.Refreshed, {}, { global: true })
868-
})
869849

870850
const refresh = Effect.fn("ModelsDev.refresh")(function* (force = false) {
871851
yield* lock
@@ -887,15 +867,14 @@ export const layer = (options?: Options) =>
887867
if (!response) return
888868
yield* decodeCatalog(response.text)
889869
yield* writeCache(response.text, response.etag, digest)
890-
yield* invalidate
870+
yield* Effect.forEach(caches, ([, invalidate]) => invalidate, { discard: true })
871+
yield* bus.publish(ModelsDev.Event.Refreshed, {}, { global: true })
891872
}),
892873
)
893874
.pipe(
894875
Effect.tapCause((cause) => Effect.logError("Failed to fetch models.dev", { cause: cause })),
895876
Effect.ignore,
896877
)
897-
// An unchanged or unreachable catalog can still hold a price that started or ended today.
898-
if (priced.day !== utcDay()) yield* invalidate
899878
})
900879

901880
if (fetch && !process.argv.includes("--get-yargs-completions")) {

‎packages/core/src/plugin.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ const layer = Layer.effect(
7676
release: holdUnsafe(),
7777
})
7878
})
79-
const host = yield* PluginHost.make(service, plugin.id).pipe(Effect.provideContext(hostContext))
79+
const host = yield* PluginHost.make({ list }, plugin.id).pipe(Effect.provideContext(hostContext))
8080
const exit = yield* Effect.suspend(() => plugin.effect(host)).pipe(
8181
grouped,
8282
inherit,
@@ -265,16 +265,14 @@ const layer = Layer.effect(
265265
)
266266
yield* Effect.addFinalizer(close)
267267

268-
const service = Service.of({
268+
return Service.of({
269269
activate,
270270
close,
271271
awaitActivation: ready.await,
272-
activated: Effect.sync(() => pending.size === 0),
273272
hold,
274273
list,
275274
gui,
276275
})
277-
return service
278276
}),
279277
)
280278

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

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import { Agent } from "../agent.js"
1111
import { Artifact } from "../artifact.js"
1212
import { AISDK } from "../aisdk.js"
1313
import { Automation } from "../automation.js"
14-
import { AutomationCode } from "../automation/code.js"
1514
import { Command } from "../command.js"
1615
import { Credential } from "../credential.js"
1716
import { Environment } from "../environment/index.js"
@@ -38,10 +37,9 @@ import { WebSearch } from "../websearch.js"
3837
import { Worktree } from "../worktree.js"
3938
import { WorktreeStrategies } from "../worktree/strategies.js"
4039
import { Generate } from "../generate.js"
41-
import { Instance } from "../instance/service.js"
4240
import { Permission } from "../permission.js"
4341
import { PluginHooks } from "./hooks.js"
44-
import type { Interface } from "./service.js"
42+
import type { Interface } from "../plugin.js"
4543
import { LayerNode } from "@opencode/util/effect/layer-node"
4644

4745
const mutable = <T>(value: T) => value as DeepMutable<T>
@@ -54,12 +52,11 @@ const isRpcType = (type: string): type is RpcEvent["type"] => type.startsWith("r
5452
const isRpcEvent = (event: Event.Payload): event is RpcEvent => isRpcType(event.type)
5553
const isPublicEvent = (event: Event.Payload): event is EventManifest.ServerEvent | RpcEvent =>
5654
EventManifest.isServer(event) || isRpcEvent(event)
57-
export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, pluginID: string) {
55+
export const make = Effect.fn("PluginHost.make")(function* (plugin: Pick<Interface, "list">, pluginID: string) {
5856
const app = yield* App.Service
5957
const agents = yield* Agent.Service
6058
const artifacts = yield* Artifact.Service
6159
const automations = yield* Automation.Service
62-
const instances = yield* Instance.Service
6360
const aisdk = yield* AISDK.Service
6461
const providers = yield* Provider.Service
6562
const models = yield* Model.Service
@@ -327,16 +324,11 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
327324
automation: {
328325
// A plugin has no UI listener to answer an interactive ask, so asks settle unattended, as they do over HTTP.
329326
// A JavaScript plugin can pass any shape, so validate it against the type-side schema before storing it.
330-
// Its own registry may be waiting on this setup, so creates that need permissions are refused there until it
331-
// finishes activating. The instance's selector can serve its own Sessions while booting. Other registries still
332-
// have to finish activating.
333327
create: (input) =>
334328
Schema.decodeUnknownEffect(Schema.toType(Automation.CreateInput))(input).pipe(
335329
Effect.mapError((error) => new Automation.InvalidError({ reason: error.message })),
336330
Effect.flatMap((decoded) => automations.create(decoded)),
337331
Effect.provideService(Permission.Unattended, []),
338-
Effect.provideService(AutomationCode.FromPlugin, plugin),
339-
Effect.provideService(Instance.Service, instances),
340332
),
341333
list: (input) => automations.list(input),
342334
delete: (input) => automations.remove(input.automationID),
@@ -660,7 +652,6 @@ export const requirements = LayerNode.group([
660652
Artifact.node,
661653
AISDK.node,
662654
Automation.node,
663-
Instance.node,
664655
Provider.node,
665656
Model.node,
666657
Command.node,

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

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,6 @@ export interface Interface {
1414
readonly close: (exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>
1515
/** Wait for announced updates and activation to settle; failures remain in the inventory. */
1616
readonly awaitActivation: Effect.Effect<void>
17-
/** Whether activation has settled, without waiting for it. */
18-
readonly activated: Effect.Effect<boolean>
1917
/** Keep readiness pending while preparing an update. Run the returned Effect to release it. */
2018
readonly hold: () => Effect.Effect<Effect.Effect<void>>
2119
}

‎packages/core/src/session/runner/model.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import { Context, Effect, Layer, Schema } from "effect"
88
import type { SessionRequestKind } from "@opencode/plugin/effect/session"
99
import { Agent } from "../../agent.js"
1010
import { ModelResolver } from "../../model-resolver.js"
11-
import { findModelByID } from "../../model-lookup.js"
1211
import { PluginHooks } from "../../plugin/hooks.js"
1312
import { SessionSchema } from "../schema.js"
1413

@@ -91,7 +90,9 @@ const layer = Layer.effect(
9190
available: () => Effect.Effect<ReadonlyArray<Model.Info>>,
9291
) {
9392
const find = (ref: Model.Ref) =>
94-
available().pipe(Effect.map((models) => findModelByID(models, ref.providerID, ref.id)))
93+
available().pipe(
94+
Effect.map((models) => models.find((model) => model.providerID === ref.providerID && model.id === ref.id)),
95+
)
9596
if (session.model) {
9697
const info = yield* find(session.model)
9798
if (info) return { info, variant: session.model.variant }

0 commit comments

Comments
 (0)