mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-17 05:26:47 +03:00
feat(core): add session-aware instance selection (#46442)
This commit is contained in:
committed by
GitHub
Unverified
parent
36ac35a7c8
commit
3e9b009642
@@ -55,6 +55,7 @@ import { ToolOutput } from "./tool-output.js"
|
||||
import { Vcs } from "./vcs.js"
|
||||
|
||||
export * as Instance from "./instance.js"
|
||||
export { Service, byLocationNode, type Interface } from "./instance/service.js"
|
||||
|
||||
const nodes = [
|
||||
Location.node,
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
export * as Instance from "./service.js"
|
||||
export type { Services } from "../instance.js"
|
||||
|
||||
import { Context, Effect, Layer, Option, Scope } from "effect"
|
||||
import type { Session } from "@opencode-ai/schema/session"
|
||||
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
|
||||
import type { Services } from "../instance.js"
|
||||
import { LocationServiceMap } from "../location-service-map.js"
|
||||
|
||||
/** Selects Session capabilities; implementations own caching and lifetime. */
|
||||
export interface Interface {
|
||||
readonly provide: (
|
||||
session: Session.Info,
|
||||
) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, Exclude<R, Services>>
|
||||
/** Borrow a cached instance without initializing one when it is absent. */
|
||||
readonly provideIfLoaded: (
|
||||
session: Session.Info,
|
||||
) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<Option.Option<A>, E, Exclude<R, Services>>
|
||||
}
|
||||
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/Instance") {}
|
||||
|
||||
const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
return Service.of({
|
||||
provide: (session) => Effect.provide(locations.get(session.location)),
|
||||
provideIfLoaded: (session) => (effect) =>
|
||||
// Scope the borrowed reference without replacing the caller's Scope.
|
||||
Effect.scopedWith((scope) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* locations.contextEffectOption(session.location).pipe(Scope.provide(scope))
|
||||
if (Option.isNone(context)) return Option.none()
|
||||
return Option.some(yield* effect.pipe(Effect.provide(context.value)))
|
||||
}),
|
||||
),
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
export const byLocationNode = makeGlobalNode({ service: Service, layer, deps: [LocationServiceMap.node] })
|
||||
@@ -80,7 +80,8 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
|
||||
const response = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
effect.pipe(Effect.map((data) => ({ location: locationInfo(), data })))
|
||||
|
||||
return {
|
||||
// Keep the instance graph's inferred types independent of Session handles.
|
||||
const context: Plugin.Context = {
|
||||
app,
|
||||
location: locationInfo(),
|
||||
options: {},
|
||||
@@ -206,7 +207,8 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
|
||||
.subscribe()
|
||||
.pipe(
|
||||
Stream.filter(
|
||||
(event): event is EventManifest.ServerEvent | RpcEvent => EventManifest.isServer(event) || isRpcEvent(event),
|
||||
(event): event is EventManifest.ServerEvent | RpcEvent =>
|
||||
EventManifest.isServer(event) || isRpcEvent(event),
|
||||
),
|
||||
),
|
||||
},
|
||||
@@ -449,7 +451,8 @@ export const make = Effect.fn("PluginHost.make")(function* (plugin: Interface, p
|
||||
wait: (input) => runtime.session.wait(input.sessionID),
|
||||
context: (input) => runtime.session.context(input.sessionID),
|
||||
},
|
||||
} satisfies Plugin.Context
|
||||
}
|
||||
return context
|
||||
})
|
||||
|
||||
export function storage(kv: KV.Interface, pluginID: string): Plugin.Context["storage"] {
|
||||
|
||||
@@ -62,7 +62,7 @@ const require = <A, E, R>(cell: Cell, f: (runtime: Interface) => Effect.Effect<A
|
||||
|
||||
const defaultCell = makeCell()
|
||||
|
||||
export const layerWithCell = (cell: Cell) =>
|
||||
export const layerWithCell = (cell: Cell): Layer.Layer<Service> =>
|
||||
Layer.succeed(
|
||||
Service,
|
||||
Service.of({
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export * as Session from "./session.js"
|
||||
export * from "./session/schema.js"
|
||||
|
||||
import { Cause, Effect, Layer, Schema, Context, RcMap, Stream } from "effect"
|
||||
import { Cause, Effect, Layer, Schema, Context, Stream } from "effect"
|
||||
import { ListAnchor } from "@opencode-ai/schema/session"
|
||||
import { and, desc, eq } from "drizzle-orm"
|
||||
import { Project } from "./project.js"
|
||||
@@ -10,6 +10,7 @@ import { Location } from "./location.js"
|
||||
import { SessionMessage } from "./session/message.js"
|
||||
import { PromptInput } from "@opencode-ai/schema/prompt-input"
|
||||
import { Bus } from "./bus.js"
|
||||
import { Instance } from "./instance/service.js"
|
||||
import { Database } from "./database/database.js"
|
||||
import { SessionProjector } from "./session/projector.js"
|
||||
import { SessionMessageTable } from "./session/sql.js"
|
||||
@@ -238,20 +239,16 @@ const layer = Layer.effect(
|
||||
const global = yield* Global.Service
|
||||
const execution = yield* SessionExecution.Service
|
||||
const store = yield* SessionStore.Service
|
||||
const instances = yield* Instance.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const fs = yield* FSUtil.Service
|
||||
const jobs = yield* Job.Service
|
||||
const environments = yield* SessionEnvironment.Service
|
||||
const sessions = yield* Session.make((ref) => locations.get(ref))
|
||||
const sessions = yield* Session.make()
|
||||
const admission = yield* SessionInbox.Service
|
||||
const closeTransport = Effect.fn("Session.closeTransport")(function* (session: SessionSchema.Info) {
|
||||
const location = Location.Ref.make({
|
||||
directory: session.location.directory,
|
||||
workspaceID: session.location.workspaceID,
|
||||
})
|
||||
if (!(yield* RcMap.has(locations.rcMap, location))) return
|
||||
yield* SessionModelTransport.Service.use((transport) => transport.close(session.id)).pipe(
|
||||
Effect.provide(locations.get(location)),
|
||||
instances.provideIfLoaded(session),
|
||||
)
|
||||
})
|
||||
const isDurableSessionEvent = Schema.is(SessionEvent.Durable)
|
||||
@@ -403,7 +400,7 @@ const layer = Layer.effect(
|
||||
prompt: (input) => sessions.forSession(input.sessionID).prompt(input),
|
||||
generate: Effect.fn("Session.generate")(function* (input) {
|
||||
const session = yield* result.get(input.sessionID)
|
||||
const generate = yield* SessionGenerate.Service.pipe(Effect.provide(locations.get(session.location)))
|
||||
const generate = yield* SessionGenerate.Service.pipe(instances.provide(session))
|
||||
return yield* generate.generate(input)
|
||||
}),
|
||||
command: Effect.fn("Session.command")(function* (input) {
|
||||
@@ -412,7 +409,7 @@ const layer = Layer.effect(
|
||||
const plugins = yield* PluginSupervisor.Service
|
||||
yield* plugins.flush
|
||||
return yield* Command.Service
|
||||
}).pipe(Effect.provide(locations.get(session.location)))
|
||||
}).pipe(instances.provide(session))
|
||||
const delivery = input.delivery ?? "steer"
|
||||
yield* commands.execute({
|
||||
name: input.command,
|
||||
@@ -535,6 +532,7 @@ export const node = makeGlobalNode({
|
||||
Project.node,
|
||||
SessionExecution.node,
|
||||
SessionStore.node,
|
||||
Instance.byLocationNode,
|
||||
SessionInbox.node,
|
||||
LocationServiceMap.node,
|
||||
SessionProjector.node,
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Cause, Context, Effect, Exit, Layer } from "effect"
|
||||
import { Bus } from "../bus.js"
|
||||
import { Database } from "../database/database.js"
|
||||
import { Job } from "../job.js"
|
||||
import { LocationServiceMap } from "../location-service-map.js"
|
||||
import { Instance } from "../instance/service.js"
|
||||
import { makeGlobalNode } from "@opencode-ai/util/effect/app-node"
|
||||
import { SessionEvent } from "./event.js"
|
||||
import { SessionRunCoordinator } from "./run-coordinator.js"
|
||||
@@ -35,7 +35,7 @@ export interface Interface {
|
||||
readonly awaitIdle: (sessionID: SessionSchema.ID) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
/** Routes execution from a Session ID to the runner owned by that Session's Location. */
|
||||
/** Routes execution from a Session ID to its selected instance's runner. */
|
||||
export class Service extends Context.Service<Service, Interface>()("@opencode/SessionExecution") {}
|
||||
|
||||
type InterruptReason = "user" | "shutdown"
|
||||
@@ -48,12 +48,12 @@ export function terminal(exit: Exit.Exit<void, SessionRunner.RunError>, reason?:
|
||||
return { type: "failed" as const, error: toSessionError(failure) }
|
||||
}
|
||||
|
||||
/** Process-local execution: drains run in this process, routed through the Session's Location graph. */
|
||||
/** Process-local execution: drains run in this process using the selected instance. */
|
||||
export const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const store = yield* SessionStore.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const instances = yield* Instance.Service
|
||||
const bus = yield* Bus.Service
|
||||
const jobs = yield* Job.Service
|
||||
const db = (yield* Database.Service).db
|
||||
@@ -90,7 +90,7 @@ export const layer = Layer.effect(
|
||||
const result = yield* SessionRunner.Service.use((runner) =>
|
||||
runner.drain({ sessionID, force, continuation, promotable }),
|
||||
).pipe(
|
||||
Effect.provide(locations.get(session.location)),
|
||||
instances.provide(session),
|
||||
Effect.tapCause((cause) =>
|
||||
Cause.hasInterruptsOnly(cause)
|
||||
? Effect.void
|
||||
@@ -173,7 +173,7 @@ export const layer = Layer.effect(
|
||||
export const node = makeGlobalNode({
|
||||
service: Service,
|
||||
layer,
|
||||
deps: [SessionStore.node, LocationServiceMap.node, Bus.node, Database.node, Job.node],
|
||||
deps: [SessionStore.node, Instance.byLocationNode, Bus.node, Database.node, Job.node],
|
||||
})
|
||||
|
||||
/** Low-level compatibility layer for callers that only need durable Session recording. */
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
export * as Session from "./session.js"
|
||||
|
||||
import { DateTime, Effect, Fiber, Layer, Schema, Scope } from "effect"
|
||||
import { DateTime, Effect, Fiber, Schema, Scope } from "effect"
|
||||
import type { Agent } from "@opencode-ai/schema/agent"
|
||||
import type { Model } from "@opencode-ai/schema/model"
|
||||
import { Event } from "@opencode-ai/schema/event"
|
||||
import { Bus } from "../bus.js"
|
||||
import { Location } from "../location.js"
|
||||
import { Instance } from "../instance/service.js"
|
||||
import { PluginSupervisor } from "../plugin/supervisor-service.js"
|
||||
import { Shell } from "../shell.js"
|
||||
import { ShellResult } from "../shell/result.js"
|
||||
@@ -33,26 +33,19 @@ import { SessionRevert } from "./revert.js"
|
||||
import { SessionSchema } from "./schema.js"
|
||||
import { SessionStore } from "./store.js"
|
||||
|
||||
export type Services =
|
||||
| PluginSupervisor.Service
|
||||
| Reference.Service
|
||||
| SessionPrompt.Service
|
||||
| SessionRevert.Service
|
||||
| Shell.Service
|
||||
| Skill.Service
|
||||
|
||||
type PromptRequest = SessionPrompt.Input & {
|
||||
id?: SessionMessage.ID
|
||||
resume?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Build once in the host Scope: `const sessions = yield* Session.make(servicesFor)`.
|
||||
* Build once in the host Scope: `const sessions = yield* Session.make()`.
|
||||
* Use `sessions.forSession(id)` for handles that share host services and reload current state.
|
||||
*/
|
||||
export const make = Effect.fn("Session.make")(function* (servicesFor: (ref: Location.Ref) => Layer.Layer<Services>) {
|
||||
export const make = Effect.fn("Session.make")(function* () {
|
||||
const bus = yield* Bus.Service
|
||||
const store = yield* SessionStore.Service
|
||||
const instances = yield* Instance.Service
|
||||
const execution = yield* SessionExecution.Service
|
||||
const admission = yield* SessionInbox.Service
|
||||
const scope = yield* Scope.Scope
|
||||
@@ -174,7 +167,7 @@ export const make = Effect.fn("Session.make")(function* (servicesFor: (ref: Loca
|
||||
const preparation = yield* SessionPrompt.Service
|
||||
const references = yield* Reference.Service
|
||||
return { item: yield* preparation.prepare({ sessionID, messageID, input }), references }
|
||||
}).pipe(Effect.provide(servicesFor(session.location))),
|
||||
}).pipe(instances.provide(session)),
|
||||
)
|
||||
// Commit a staged revert only after preparation succeeds, before admitting new work.
|
||||
if (session.revert) yield* SessionRevert.commit(bus, session)
|
||||
@@ -205,7 +198,7 @@ export const make = Effect.fn("Session.make")(function* (servicesFor: (ref: Loca
|
||||
const plugins = yield* PluginSupervisor.Service
|
||||
yield* plugins.flush
|
||||
return yield* Shell.Service
|
||||
}).pipe(Effect.provide(servicesFor(session.location)))
|
||||
}).pipe(instances.provide(session))
|
||||
const started = yield* shell
|
||||
.create({
|
||||
command: input.command,
|
||||
@@ -256,7 +249,7 @@ export const make = Effect.fn("Session.make")(function* (servicesFor: (ref: Loca
|
||||
input: { id?: SessionMessage.ID; skill: Skill.ID; resume?: boolean },
|
||||
) {
|
||||
const session = yield* get(sessionID)
|
||||
const skills = yield* Skill.Service.pipe(Effect.provide(servicesFor(session.location)))
|
||||
const skills = yield* Skill.Service.pipe(instances.provide(session))
|
||||
const skill = yield* skills.get(input.skill)
|
||||
if (!skill) return yield* new SkillNotFoundError({ skill: input.skill })
|
||||
yield* bus.publish(
|
||||
@@ -355,14 +348,12 @@ export const make = Effect.fn("Session.make")(function* (servicesFor: (ref: Loca
|
||||
if (yield* execution.isActive(sessionID)) return yield* new BusyError({ sessionID })
|
||||
return yield* SessionRevert.Service.use((revert) =>
|
||||
revert.stage({ session, messageID: input.messageID, files: input.files }),
|
||||
).pipe(Effect.provide(servicesFor(session.location)))
|
||||
).pipe(instances.provide(session))
|
||||
})
|
||||
const clear = Effect.fn("Session.revert.clear")(function* (sessionID: SessionSchema.ID) {
|
||||
const session = yield* get(sessionID)
|
||||
if (yield* execution.isActive(sessionID)) return yield* new BusyError({ sessionID })
|
||||
yield* SessionRevert.Service.use((revert) => revert.clear(session)).pipe(
|
||||
Effect.provide(servicesFor(session.location)),
|
||||
)
|
||||
yield* SessionRevert.Service.use((revert) => revert.clear(session)).pipe(instances.provide(session))
|
||||
return yield* execution.wake(sessionID)
|
||||
})
|
||||
const commit = Effect.fn("Session.revert.commit")(function* (sessionID: SessionSchema.ID) {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Database } from "@opencode-ai/core/database/database"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { Job } from "@opencode-ai/core/job"
|
||||
import { KV } from "@opencode-ai/core/kv"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
|
||||
@@ -1371,7 +1372,10 @@ function buildExecution(
|
||||
Layer.provide(Layer.succeed(Bus.Service, bus)),
|
||||
Layer.provide(Layer.succeed(SessionStore.Service, store)),
|
||||
Layer.provide(Layer.succeed(Job.Service, jobs)),
|
||||
Layer.provide(locations),
|
||||
// Do not reuse the outer harness's selector with its already-captured Location map.
|
||||
Layer.provide(
|
||||
LayerNode.compile(Instance.byLocationNode, [[LocationServiceMap.node, locations]]).pipe(Layer.fresh),
|
||||
),
|
||||
),
|
||||
scope,
|
||||
)
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Bus } from "../src/bus.js"
|
||||
import { Database } from "../src/database/database.js"
|
||||
import { EventTable } from "../src/event/sql.js"
|
||||
import { Image } from "../src/image.js"
|
||||
import { Instance } from "../src/instance/service.js"
|
||||
import { Location } from "../src/location.js"
|
||||
import { PluginHooks } from "../src/plugin/hooks.js"
|
||||
import { PluginSupervisor } from "../src/plugin/supervisor-service.js"
|
||||
@@ -129,7 +130,7 @@ const setup = Effect.fnUntraced(function* (options?: {
|
||||
Layer.mock(Image.Service, {}),
|
||||
options?.shell ?? Layer.mock(Shell.Service, {}),
|
||||
)
|
||||
const servicesFor = (ref: Location.Ref): Layer.Layer<Session.Services> => {
|
||||
const servicesFor = (ref: Location.Ref) => {
|
||||
locations.push(ref)
|
||||
return Layer.merge(SessionRevert.layer, SessionPrompt.layer).pipe(
|
||||
Layer.provideMerge(
|
||||
@@ -158,10 +159,20 @@ const setup = Effect.fnUntraced(function* (options?: {
|
||||
Layer.fresh,
|
||||
)
|
||||
}
|
||||
const sessions = yield* Session.make(servicesFor).pipe(
|
||||
const sessions = yield* Session.make().pipe(
|
||||
Effect.satisfiesServicesType<
|
||||
Bus.Service | SessionStore.Service | SessionExecution.Service | SessionInbox.Service | Scope.Scope
|
||||
| Bus.Service
|
||||
| SessionStore.Service
|
||||
| Instance.Service
|
||||
| SessionExecution.Service
|
||||
| SessionInbox.Service
|
||||
| Scope.Scope
|
||||
>(),
|
||||
Effect.provideService(Instance.Service, {
|
||||
// This fixture supplies only the instance services exercised by Session.
|
||||
provide: (session) => Effect.provide(servicesFor(session.location) as Layer.Layer<Instance.Services>),
|
||||
provideIfLoaded: () => () => Effect.die("Unexpected loaded-only instance lookup"),
|
||||
}),
|
||||
Effect.provideService(SessionExecution.Service, options?.execution ?? execution),
|
||||
)
|
||||
return { sessions, hooks, locations, flushes, resumes, wakes, db: database.db, bus, store }
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { describe, expect } from "bun:test"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { Effect, Layer, Option, RcMap, Scope } from "effect"
|
||||
import { AppNodeBuilder } from "@opencode-ai/core/effect/app-node-builder"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { Project } from "@opencode-ai/core/project"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
@@ -19,12 +20,18 @@ import { globalProjectNode } from "./lib/project"
|
||||
import { tmpdirScoped } from "./fixture/tmpdir"
|
||||
|
||||
const closed: Session.ID[] = []
|
||||
const transport = Layer.succeed(
|
||||
const transportScopes = new Set<Scope.Scope>()
|
||||
const transport = Layer.effect(
|
||||
SessionModelTransport.Service,
|
||||
SessionModelTransport.Service.of({
|
||||
bind: () => ({ execute: () => Effect.die("Unexpected WebSocket execution") }),
|
||||
close: (sessionID) => Effect.sync(() => closed.push(sessionID)),
|
||||
closeAll: Effect.void,
|
||||
Effect.gen(function* () {
|
||||
const scope = yield* Scope.Scope
|
||||
transportScopes.add(scope)
|
||||
yield* Effect.addFinalizer(() => Effect.sync(() => transportScopes.delete(scope)))
|
||||
return SessionModelTransport.Service.of({
|
||||
bind: () => ({ execute: () => Effect.die("Unexpected WebSocket execution") }),
|
||||
close: (sessionID) => Effect.sync(() => closed.push(sessionID)),
|
||||
closeAll: Effect.void,
|
||||
})
|
||||
}),
|
||||
)
|
||||
const it = testEffect(
|
||||
@@ -36,6 +43,7 @@ const it = testEffect(
|
||||
SessionStore.node,
|
||||
SessionEnvironment.node,
|
||||
Session.node,
|
||||
Instance.byLocationNode,
|
||||
LocationServiceMap.node,
|
||||
]),
|
||||
[
|
||||
@@ -72,6 +80,27 @@ describe("Session.remove", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("removes unloaded sessions and children without initializing an instance", () =>
|
||||
Effect.gen(function* () {
|
||||
const temporary = yield* tmpdirScoped()
|
||||
const sessions = yield* Session.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const parent = yield* sessions.create({
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make(temporary.path) }),
|
||||
})
|
||||
yield* sessions.create({ parentID: parent.id })
|
||||
closed.length = 0
|
||||
expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
|
||||
|
||||
yield* sessions.remove(parent.id)
|
||||
|
||||
expect(closed).toEqual([])
|
||||
expect(transportScopes.size).toBe(0)
|
||||
expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
|
||||
expect((yield* sessions.list()).data).toEqual([])
|
||||
}),
|
||||
)
|
||||
|
||||
it.effect("fails when the session does not exist", () =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* Session.Service
|
||||
@@ -84,3 +113,40 @@ describe("Session.remove", () => {
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
describe("Instance.provideIfLoaded", () => {
|
||||
it.live("skips absent instances and scopes loaded borrows without replacing the caller's Scope", () =>
|
||||
Effect.gen(function* () {
|
||||
const temporary = yield* tmpdirScoped()
|
||||
const sessions = yield* Session.Service
|
||||
const instances = yield* Instance.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const scope = yield* Scope.Scope
|
||||
const session = yield* sessions.create({
|
||||
location: Location.Ref.make({ directory: AbsolutePath.make(temporary.path) }),
|
||||
})
|
||||
const absent = Effect.die("An unloaded instance must not run the effect").pipe(instances.provideIfLoaded(session))
|
||||
|
||||
expect(yield* absent).toEqual(Option.none())
|
||||
expect(transportScopes.size).toBe(0)
|
||||
yield* Location.Service.pipe(instances.provide(session))
|
||||
expect(transportScopes.size).toBe(1)
|
||||
expect(yield* Effect.void.pipe(instances.provideIfLoaded(session))).toEqual(Option.some(undefined))
|
||||
const failure = new Error("Borrowed operation failed")
|
||||
expect(yield* Effect.fail(failure).pipe(instances.provideIfLoaded(session), Effect.flip)).toBe(failure)
|
||||
|
||||
const borrowed = yield* Effect.gen(function* () {
|
||||
const location = yield* Location.Service
|
||||
const callerScope = yield* Scope.Scope
|
||||
expect(callerScope).toBe(scope)
|
||||
yield* locations.invalidate(session.location)
|
||||
expect(transportScopes.size).toBe(1)
|
||||
return location.directory
|
||||
}).pipe(instances.provideIfLoaded(session), Effect.satisfiesServicesType<Scope.Scope>())
|
||||
|
||||
expect(borrowed).toEqual(Option.some(session.location.directory))
|
||||
expect(transportScopes.size).toBe(0)
|
||||
expect(yield* absent).toEqual(Option.none())
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { Form } from "@opencode-ai/core/form"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-services"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import {
|
||||
ConflictError,
|
||||
FormAlreadySettledError,
|
||||
@@ -11,7 +12,7 @@ import {
|
||||
import { Effect, Option } from "effect"
|
||||
import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi"
|
||||
import { Api } from "../api"
|
||||
import { requestRef, response, sessionRef, withLoadedLocationServices } from "../location"
|
||||
import { requestRef, response, sessionInfo, withLoadedLocationServices } from "../location"
|
||||
|
||||
function missingForm(id: Form.ID) {
|
||||
return new FormNotFoundError({ id, message: `Form not found: ${id}` })
|
||||
@@ -20,7 +21,8 @@ function missingForm(id: Form.ID) {
|
||||
export const FormHandler = HttpApiBuilder.group(Api, "server.form", (handlers) =>
|
||||
Effect.gen(function* () {
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const database = yield* Database.Service
|
||||
const instances = yield* Instance.Service
|
||||
const sessions = yield* Session.Service
|
||||
const requireOwnedForm = Effect.fnUntraced(function* (sessionID: Form.Info["sessionID"], formID: Form.ID) {
|
||||
const form = yield* Form.Service
|
||||
const info = yield* form.get(formID).pipe(Effect.catchTag("Form.NotFoundError", () => missingForm(formID)))
|
||||
@@ -39,15 +41,12 @@ export const FormHandler = HttpApiBuilder.group(Api, "server.form", (handlers) =
|
||||
.handle(
|
||||
"session.form.list",
|
||||
Effect.fn(function* (ctx) {
|
||||
const ref =
|
||||
ctx.params.sessionID === "global"
|
||||
? requestRef(ctx.request)
|
||||
: yield* sessionRef(database, ctx.params.sessionID)
|
||||
const forms = yield* withLoadedLocationServices(
|
||||
locations,
|
||||
ref,
|
||||
Form.Service.use((form) => form.list({ sessionID: ctx.params.sessionID })),
|
||||
)
|
||||
const session =
|
||||
ctx.params.sessionID === "global" ? undefined : yield* sessionInfo(sessions, ctx.params.sessionID)
|
||||
const read = Form.Service.use((form) => form.list({ sessionID: ctx.params.sessionID }))
|
||||
const forms = yield* session
|
||||
? read.pipe(instances.provideIfLoaded(session))
|
||||
: withLoadedLocationServices(locations, requestRef(ctx.request), read)
|
||||
return { data: Option.getOrElse(forms, () => []) }
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-services"
|
||||
import { Permission } from "@opencode-ai/core/permission"
|
||||
import { PermissionSaved } from "@opencode-ai/core/permission/saved"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Effect, Option } from "effect"
|
||||
import { HttpApiBuilder, HttpApiSchema } from "effect/unstable/httpapi"
|
||||
import { Api } from "../api"
|
||||
import { PermissionNotFoundError, SessionNotFoundError } from "@opencode-ai/protocol/errors"
|
||||
import { response, sessionRef, withLoadedLocationServices } from "../location"
|
||||
import { PermissionNotFoundError } from "@opencode-ai/protocol/errors"
|
||||
import { response, sessionInfo } from "../location"
|
||||
import { missingSession } from "./session-error"
|
||||
|
||||
function missingRequest(id: Permission.ID) {
|
||||
return new PermissionNotFoundError({ requestID: id, message: `Permission request not found: ${id}` })
|
||||
@@ -15,8 +16,8 @@ function missingRequest(id: Permission.ID) {
|
||||
|
||||
export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission", (handlers) =>
|
||||
Effect.gen(function* () {
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const database = yield* Database.Service
|
||||
const instances = yield* Instance.Service
|
||||
const sessions = yield* Session.Service
|
||||
const requireOwnedRequest = Effect.fnUntraced(function* (
|
||||
sessionID: Permission.Request["sessionID"],
|
||||
requestID: Permission.ID,
|
||||
@@ -51,28 +52,17 @@ export const PermissionHandler = HttpApiBuilder.group(Api, "server.permission",
|
||||
source: ctx.payload.source,
|
||||
agent: ctx.payload.agent,
|
||||
})
|
||||
.pipe(
|
||||
Effect.catchTag(
|
||||
"Session.NotFoundError",
|
||||
(error) =>
|
||||
new SessionNotFoundError({
|
||||
sessionID: error.sessionID,
|
||||
message: `Session not found: ${error.sessionID}`,
|
||||
}),
|
||||
),
|
||||
),
|
||||
.pipe(Effect.catchTag("Session.NotFoundError", missingSession)),
|
||||
}
|
||||
}),
|
||||
)
|
||||
.handle(
|
||||
"session.permission.list",
|
||||
Effect.fn(function* (ctx) {
|
||||
const ref = yield* sessionRef(database, ctx.params.sessionID)
|
||||
const requests = yield* withLoadedLocationServices(
|
||||
locations,
|
||||
ref,
|
||||
Permission.Service.use((permission) => permission.forSession(ctx.params.sessionID)),
|
||||
)
|
||||
const session = yield* sessionInfo(sessions, ctx.params.sessionID)
|
||||
const requests = yield* Permission.Service.use((permission) =>
|
||||
permission.forSession(ctx.params.sessionID),
|
||||
).pipe(instances.provideIfLoaded(session))
|
||||
return { data: Option.getOrElse(requests, () => []) }
|
||||
}),
|
||||
)
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { Location } from "@opencode-ai/core/location"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-services"
|
||||
import { AbsolutePath } from "@opencode-ai/core/schema"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { SessionTable } from "@opencode-ai/core/session/sql"
|
||||
import { Workspace } from "@opencode-ai/core/workspace"
|
||||
import { InvalidRequestError, SessionNotFoundError } from "@opencode-ai/protocol/errors"
|
||||
import { eq } from "drizzle-orm"
|
||||
import { InvalidRequestError } from "@opencode-ai/protocol/errors"
|
||||
import { Context, Effect, Layer, Option, Schema } from "effect"
|
||||
import { HttpServerRequest } from "effect/unstable/http"
|
||||
import { HttpApiMiddleware } from "effect/unstable/httpapi"
|
||||
import { missingSession } from "./handlers/session-error"
|
||||
|
||||
export type LocationServices = Layer.Success<ReturnType<(typeof LocationServiceMap.Service)["get"]>>
|
||||
|
||||
@@ -33,24 +31,12 @@ export function response<A, E, R>(data: Effect.Effect<A, E, R>) {
|
||||
|
||||
const decodeSessionID = Schema.decodeUnknownEffect(Session.ID)
|
||||
|
||||
export function sessionRef(database: Context.Service.Shape<typeof Database.Service>, sessionID: unknown) {
|
||||
return Effect.gen(function* () {
|
||||
const id = yield* decodeSessionID(sessionID).pipe(
|
||||
Effect.mapError(() => new InvalidRequestError({ message: "Invalid session ID", field: "sessionID" })),
|
||||
)
|
||||
const row = yield* database.db
|
||||
.select({ directory: SessionTable.directory, workspaceID: SessionTable.workspace_id })
|
||||
.from(SessionTable)
|
||||
.where(eq(SessionTable.id, id))
|
||||
.get()
|
||||
.pipe(Effect.orDie)
|
||||
if (!row) return yield* new SessionNotFoundError({ sessionID: id, message: `Session not found: ${id}` })
|
||||
return Location.Ref.make({
|
||||
directory: AbsolutePath.make(row.directory),
|
||||
workspaceID: row.workspaceID ? Workspace.ID.make(row.workspaceID) : undefined,
|
||||
})
|
||||
})
|
||||
}
|
||||
export const sessionInfo = Effect.fnUntraced(function* (sessions: Session.Interface, sessionID: unknown) {
|
||||
const id = yield* decodeSessionID(sessionID).pipe(
|
||||
Effect.mapError(() => new InvalidRequestError({ message: "Invalid session ID", field: "sessionID" })),
|
||||
)
|
||||
return yield* sessions.get(id).pipe(Effect.catchTag("Session.NotFoundError", missingSession))
|
||||
})
|
||||
|
||||
export function withLoadedLocationServices<A, E>(
|
||||
locations: Context.Service.Shape<typeof LocationServiceMap.Service>,
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-services"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { InvalidRequestError, SessionNotFoundError } from "@opencode-ai/protocol/errors"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { HttpRouter, HttpServerRequest } from "effect/unstable/http"
|
||||
import { HttpApiMiddleware } from "effect/unstable/httpapi"
|
||||
import { requestRef, sessionRef, type LocationServices } from "../location"
|
||||
import { requestRef, sessionInfo, type LocationServices } from "../location"
|
||||
|
||||
export class FormLocationMiddleware extends HttpApiMiddleware.Service<
|
||||
FormLocationMiddleware,
|
||||
@@ -16,7 +17,8 @@ export class FormLocationMiddleware extends HttpApiMiddleware.Service<
|
||||
export const formLocationLayer = Layer.effect(
|
||||
FormLocationMiddleware,
|
||||
Effect.gen(function* () {
|
||||
const database = yield* Database.Service
|
||||
const sessions = yield* Session.Service
|
||||
const instances = yield* Instance.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
|
||||
return FormLocationMiddleware.of((effect) =>
|
||||
@@ -30,8 +32,8 @@ export const formLocationLayer = Layer.effect(
|
||||
return yield* effect.pipe(Effect.provide(locations.get(requestRef(request))))
|
||||
}
|
||||
|
||||
const ref = yield* sessionRef(database, route.params.sessionID)
|
||||
return yield* effect.pipe(Effect.provide(locations.get(ref)))
|
||||
const session = yield* sessionInfo(sessions, route.params.sessionID)
|
||||
return yield* effect.pipe(instances.provide(session))
|
||||
}),
|
||||
)
|
||||
}),
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-services"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Effect, Layer } from "effect"
|
||||
import { HttpRouter } from "effect/unstable/http"
|
||||
import { HttpApiMiddleware } from "effect/unstable/httpapi"
|
||||
import { InvalidRequestError, SessionNotFoundError } from "@opencode-ai/protocol/errors"
|
||||
import { sessionRef, type LocationServices } from "../location"
|
||||
import { sessionInfo, type LocationServices } from "../location"
|
||||
|
||||
export class SessionLocationMiddleware extends HttpApiMiddleware.Service<
|
||||
SessionLocationMiddleware,
|
||||
@@ -16,14 +16,14 @@ export class SessionLocationMiddleware extends HttpApiMiddleware.Service<
|
||||
export const sessionLocationLayer = Layer.effect(
|
||||
SessionLocationMiddleware,
|
||||
Effect.gen(function* () {
|
||||
const database = yield* Database.Service
|
||||
const locations = yield* LocationServiceMap.Service
|
||||
const sessions = yield* Session.Service
|
||||
const instances = yield* Instance.Service
|
||||
|
||||
return SessionLocationMiddleware.of((effect) =>
|
||||
Effect.gen(function* () {
|
||||
const route = yield* HttpRouter.RouteContext
|
||||
const ref = yield* sessionRef(database, route.params.sessionID)
|
||||
return yield* effect.pipe(Effect.provide(locations.get(ref)))
|
||||
const session = yield* sessionInfo(sessions, route.params.sessionID)
|
||||
return yield* effect.pipe(instances.provide(session))
|
||||
}),
|
||||
)
|
||||
}),
|
||||
|
||||
@@ -14,6 +14,7 @@ import { PtyTicket } from "@opencode-ai/core/pty/ticket"
|
||||
import { PersistentPty } from "@opencode-ai/core/persistent-pty"
|
||||
import { Project } from "@opencode-ai/core/project"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { Instance } from "@opencode-ai/core/instance/service"
|
||||
import { SessionTransfer } from "@opencode-ai/core/session/transfer"
|
||||
import { ShellSelect } from "@opencode-ai/core/shell/select"
|
||||
import { Job } from "@opencode-ai/core/job"
|
||||
@@ -56,6 +57,7 @@ const applicationServiceNodes = [
|
||||
Project.node,
|
||||
Worktree.node,
|
||||
Session.node,
|
||||
Instance.byLocationNode,
|
||||
SessionTransfer.node,
|
||||
PluginRuntime.providerNode,
|
||||
SdkPlugins.node,
|
||||
|
||||
@@ -340,7 +340,7 @@ it.live("serves the session view operation and missing-session error", () =>
|
||||
}),
|
||||
)
|
||||
|
||||
it.live("does not load a location when reading pending session requests", () =>
|
||||
it.live("routes pending requests by Session without loading an instance", () =>
|
||||
Effect.gen(function* () {
|
||||
const config = yield* Effect.acquireDisposable(Effect.promise(() => tmpdir("opencode-pending-read-")))
|
||||
const handler = yield* ServerFetch.make({
|
||||
@@ -368,16 +368,18 @@ it.live("does not load a location when reading pending session requests", () =>
|
||||
),
|
||||
)
|
||||
|
||||
// Session routing must ignore the caller's unrelated Location.
|
||||
const headers = { "x-opencode-directory": encodeURIComponent(config.path) }
|
||||
expect(yield* loaded()).toEqual([])
|
||||
for (const resource of ["permission", "form"]) {
|
||||
const response = yield* Effect.promise(() =>
|
||||
handler(new Request(`http://opencode.local/api/session/${created.data.id}/${resource}`)),
|
||||
handler(new Request(`http://opencode.local/api/session/${created.data.id}/${resource}`, { headers })),
|
||||
)
|
||||
expect(response.status).toBe(200)
|
||||
expect(yield* Effect.promise(() => response.json())).toEqual({ data: [] })
|
||||
|
||||
const missing = yield* Effect.promise(() =>
|
||||
handler(new Request(`http://opencode.local/api/session/ses_missing_pending/${resource}`)),
|
||||
handler(new Request(`http://opencode.local/api/session/ses_missing_pending/${resource}`, { headers })),
|
||||
)
|
||||
expect(missing.status).toBe(404)
|
||||
}
|
||||
@@ -396,7 +398,7 @@ it.live("does not load a location when reading pending session requests", () =>
|
||||
handler(
|
||||
new Request(`http://opencode.local/api/session/${created.data.id}/form`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
body: JSON.stringify({ title: "Test form", fields: [{ key: "answer", type: "string" }] }),
|
||||
}),
|
||||
),
|
||||
@@ -404,7 +406,7 @@ it.live("does not load a location when reading pending session requests", () =>
|
||||
expect(createdForm.status).toBe(200)
|
||||
|
||||
const forms = yield* Effect.promise(() =>
|
||||
handler(new Request(`http://opencode.local/api/session/${created.data.id}/form`)),
|
||||
handler(new Request(`http://opencode.local/api/session/${created.data.id}/form`, { headers })),
|
||||
)
|
||||
expect(forms.status).toBe(200)
|
||||
expect(yield* Effect.promise(() => forms.json())).toMatchObject({
|
||||
@@ -442,7 +444,7 @@ it.live("does not load a location when reading pending session requests", () =>
|
||||
handler(
|
||||
new Request(`http://opencode.local/api/session/${created.data.id}/permission`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
headers: { "content-type": "application/json", ...headers },
|
||||
body: JSON.stringify({ id: "per_pending_read", action: "shell", resources: ["pwd"] }),
|
||||
}),
|
||||
),
|
||||
@@ -453,7 +455,7 @@ it.live("does not load a location when reading pending session requests", () =>
|
||||
})
|
||||
|
||||
const permissions = yield* Effect.promise(() =>
|
||||
handler(new Request(`http://opencode.local/api/session/${created.data.id}/permission`)),
|
||||
handler(new Request(`http://opencode.local/api/session/${created.data.id}/permission`, { headers })),
|
||||
)
|
||||
expect(permissions.status).toBe(200)
|
||||
expect(yield* Effect.promise(() => permissions.json())).toMatchObject({
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
import { expect } from "bun:test"
|
||||
import { App } from "@opencode-ai/core/app"
|
||||
import { Bus } from "@opencode-ai/core/bus"
|
||||
import { Database } from "@opencode-ai/core/database/database"
|
||||
import { llmClient } from "@opencode-ai/core/effect/app-node-platform"
|
||||
import { Watcher } from "@opencode-ai/core/filesystem/watcher"
|
||||
import { Form } from "@opencode-ai/core/form"
|
||||
import { Instance } from "@opencode-ai/core/instance"
|
||||
import { LocationServiceMap } from "@opencode-ai/core/location-service-map"
|
||||
import { ModelsDev } from "@opencode-ai/core/models-dev"
|
||||
import { Permission } from "@opencode-ai/core/permission"
|
||||
import { PluginRuntime } from "@opencode-ai/core/plugin/runtime"
|
||||
import { Session } from "@opencode-ai/core/session"
|
||||
import { SessionRunnerModel } from "@opencode-ai/core/session/runner/model"
|
||||
import { Plugin } from "@opencode-ai/plugin/effect"
|
||||
import { Agent } from "@opencode-ai/schema/agent"
|
||||
import { Location } from "@opencode-ai/schema/location"
|
||||
import { AbsolutePath } from "@opencode-ai/schema/schema"
|
||||
import { LayerNode } from "@opencode-ai/util/effect/layer-node"
|
||||
import { Global } from "@opencode-ai/util/global"
|
||||
import { Context, Duration, Effect, Layer, LayerMap, Option, RcMap, Schema, Scope } from "effect"
|
||||
import { HttpEffect, HttpRouter, HttpServer } from "effect/unstable/http"
|
||||
import { LanguageModel, LLMClient } from "../../ai/src"
|
||||
import { OpenAIChat } from "../../ai/src/protocols/openai-chat"
|
||||
import { TestLLM } from "../../ai/src/testing"
|
||||
import { tempGlobalLayer } from "../../core/test/fixture/global"
|
||||
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
|
||||
import { it } from "../../core/test/lib/effect"
|
||||
import { createEmbeddedRoutes } from "../src/routes"
|
||||
|
||||
it.live(
|
||||
"isolates same-directory Session tools, hooks, commands, and HTTP requests through one selector",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const directory = yield* tmpdirScoped()
|
||||
const location = Location.Ref.make({ directory: AbsolutePath.make(directory.path) })
|
||||
const first = { id: Session.ID.make("ses_instance_first"), tool: "instance_first", temperature: 0.1 }
|
||||
const second = { id: Session.ID.make("ses_instance_second"), tool: "instance_second", temperature: 0.2 }
|
||||
const configs = [first, second]
|
||||
const boots: Session.ID[] = []
|
||||
const executed: Session.ID[] = []
|
||||
const commands: Session.ID[] = []
|
||||
const llm = yield* TestLLM.Test.pipe(Effect.provide(TestLLM.testLayer()))
|
||||
const model = SessionRunnerModel.resolved(
|
||||
LanguageModel.make({ id: "instance-model", provider: "test", route: OpenAIChat.route }),
|
||||
{
|
||||
capabilities: { tools: true, input: ["text"], output: ["text"] },
|
||||
cost: [],
|
||||
limit: { context: 200_000, output: 8_192 },
|
||||
},
|
||||
)
|
||||
const cell = PluginRuntime.makeCell()
|
||||
// Host and private instances must reuse the same global layer identities.
|
||||
const replacements: LayerNode.Replacements = [
|
||||
[Global.node, tempGlobalLayer],
|
||||
[Database.node, Database.node],
|
||||
[Bus.node, Bus.node],
|
||||
[App.node, App.node],
|
||||
[ModelsDev.node, ModelsDev.configured({ fetch: false })],
|
||||
[Watcher.node, Watcher.configured({ enabled: false })],
|
||||
[PluginRuntime.node, PluginRuntime.layerWithCell(cell)],
|
||||
[PluginRuntime.providerNode, PluginRuntime.providerNodeWithCell(cell)],
|
||||
[llmClient, Layer.succeed(LLMClient.Service, llm)],
|
||||
[SessionRunnerModel.node, Layer.succeed(SessionRunnerModel.Service, { resolve: () => Effect.succeed(model) })],
|
||||
[
|
||||
Instance.byLocationNode,
|
||||
Layer.effect(
|
||||
Instance.Service,
|
||||
Effect.gen(function* () {
|
||||
const instances = yield* LayerMap.make(
|
||||
(id: Session.ID) => {
|
||||
const config = configs.find((config) => config.id === id)
|
||||
if (!config) throw new Error(`No instance configuration for ${id}`)
|
||||
return Instance.layer(location, {
|
||||
discovery: false,
|
||||
replacements,
|
||||
plugins: [
|
||||
Plugin.define({
|
||||
id: "session-instance",
|
||||
effect: Effect.fnUntraced(function* (ctx) {
|
||||
boots.push(config.id)
|
||||
yield* ctx.agent.transform((draft) =>
|
||||
draft.update("build", (agent) => {
|
||||
agent.permissions = [{ action: "*", resource: "*", effect: "allow" }]
|
||||
}),
|
||||
)
|
||||
yield* ctx.session.hook("prompt", (event) =>
|
||||
Effect.sync(() => {
|
||||
event.prompt.text += ` [${config.tool}]`
|
||||
}),
|
||||
)
|
||||
yield* ctx.session.hook("context", (event) =>
|
||||
Effect.sync(() => {
|
||||
event.generation.temperature = config.temperature
|
||||
}),
|
||||
)
|
||||
yield* ctx.permission.hook("evaluate", (event) =>
|
||||
Effect.sync(() => {
|
||||
event.effect = event.action === "instance-test" ? "ask" : "allow"
|
||||
if (event.action === "instance-test") event.message = config.tool
|
||||
}),
|
||||
)
|
||||
yield* ctx.tool.transform((draft) =>
|
||||
draft.add({
|
||||
name: config.tool,
|
||||
description: `Tool for ${config.id}`,
|
||||
input: Schema.Struct({}),
|
||||
output: Schema.String,
|
||||
options: { codemode: false },
|
||||
execute: () =>
|
||||
Effect.sync(() => {
|
||||
executed.push(config.id)
|
||||
return { output: config.id, content: config.id }
|
||||
}),
|
||||
}),
|
||||
)
|
||||
yield* ctx.command.transform((draft) =>
|
||||
draft.add({
|
||||
name: "instance-check",
|
||||
execute: (input) =>
|
||||
ctx.session
|
||||
.prompt({
|
||||
sessionID: input.sessionID,
|
||||
text: `command ${config.tool}`,
|
||||
delivery: input.delivery,
|
||||
resume: false,
|
||||
})
|
||||
.pipe(
|
||||
Effect.tap(() => Effect.sync(() => commands.push(config.id))),
|
||||
Effect.asVoid,
|
||||
),
|
||||
}),
|
||||
)
|
||||
}),
|
||||
}),
|
||||
],
|
||||
})
|
||||
},
|
||||
{ idleTimeToLive: Duration.infinity },
|
||||
)
|
||||
return Instance.Service.of({
|
||||
provide: (session) => Effect.provide(instances.get(session.id)),
|
||||
provideIfLoaded: (session) => (effect) =>
|
||||
Effect.scopedWith((scope) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* instances.contextEffectOption(session.id).pipe(Scope.provide(scope))
|
||||
if (Option.isNone(context)) return Option.none()
|
||||
return Option.some(yield* effect.pipe(Effect.provide(context.value)))
|
||||
}),
|
||||
),
|
||||
})
|
||||
}),
|
||||
),
|
||||
],
|
||||
]
|
||||
const context = yield* Layer.build(
|
||||
createEmbeddedRoutes({}, replacements).pipe(Layer.provide(HttpServer.layerServices)),
|
||||
)
|
||||
const sessions = Context.get(context, Session.Service)
|
||||
const instances = Context.get(context, Instance.Service)
|
||||
const locations = Context.get(context, LocationServiceMap.Service)
|
||||
const handler = Context.get(context, HttpRouter.HttpRouter)
|
||||
.asHttpEffect()
|
||||
.pipe(HttpEffect.toWebHandlerWith(context))
|
||||
const request = (route: string, body?: unknown) =>
|
||||
Effect.promise(() =>
|
||||
handler(
|
||||
new Request(
|
||||
`http://opencode.local${route}`,
|
||||
body === undefined
|
||||
? undefined
|
||||
: { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) },
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
yield* Effect.forEach(configs, (config) =>
|
||||
sessions.create({
|
||||
id: config.id,
|
||||
title: config.tool,
|
||||
agent: Agent.ID.make("build"),
|
||||
model: model.ref,
|
||||
location,
|
||||
}),
|
||||
)
|
||||
expect((yield* sessions.list()).data.map((session) => session.location)).toEqual([location, location])
|
||||
expect(yield* sessions.messages({ sessionID: first.id })).toEqual([])
|
||||
yield* sessions.get(second.id)
|
||||
for (const config of configs) {
|
||||
for (const resource of ["permission", "form"]) {
|
||||
const response = yield* request(`/api/session/${config.id}/${resource}`)
|
||||
expect(response.status).toBe(200)
|
||||
expect(yield* Effect.promise<unknown>(() => response.json())).toEqual({ data: [] })
|
||||
}
|
||||
}
|
||||
expect(boots).toEqual([])
|
||||
|
||||
for (const config of configs) {
|
||||
const admitted = yield* sessions.prompt({ sessionID: config.id, text: "run", resume: false })
|
||||
expect(admitted.payload.text).toBe(`run [${config.tool}]`)
|
||||
}
|
||||
expect(boots).toEqual([first.id, second.id])
|
||||
|
||||
for (const config of configs) {
|
||||
yield* llm.push(TestLLM.tool(`call_${config.tool}`, config.tool, {}), TestLLM.text(config.id, config.tool))
|
||||
yield* sessions.resume(config.id)
|
||||
}
|
||||
expect(executed).toEqual([first.id, second.id])
|
||||
|
||||
for (const config of configs) {
|
||||
yield* llm.push(TestLLM.text(`generated ${config.id}`, config.tool))
|
||||
expect(yield* sessions.generate({ sessionID: config.id, prompt: "summarize" })).toBe(`generated ${config.id}`)
|
||||
yield* sessions.command({ sessionID: config.id, command: "instance-check", text: "" })
|
||||
expect(yield* sessions.inbox(config.id)).toMatchObject([
|
||||
{ type: "user", payload: { text: `command ${config.tool} [${config.tool}]` } },
|
||||
])
|
||||
}
|
||||
expect(commands).toEqual([first.id, second.id])
|
||||
expect(
|
||||
(yield* llm.requests()).map((request) => ({
|
||||
temperature: request.generation?.temperature,
|
||||
tools: request.tools?.filter((tool) => tool.name.startsWith("instance_")).map((tool) => tool.name),
|
||||
})),
|
||||
).toEqual(
|
||||
[first, first, second, second, first, second].map((config) => ({
|
||||
temperature: config.temperature,
|
||||
tools: [config.tool],
|
||||
})),
|
||||
)
|
||||
|
||||
// Seed through Core, then use HTTP to reach those exact private instances.
|
||||
const pending = yield* Effect.forEach(configs, (config) =>
|
||||
Effect.gen(function* () {
|
||||
const session = yield* sessions.get(config.id)
|
||||
return yield* Effect.gen(function* () {
|
||||
const forms = yield* Form.Service
|
||||
const permissions = yield* Permission.Service
|
||||
const form = yield* forms.create({
|
||||
sessionID: config.id,
|
||||
title: config.tool,
|
||||
fields: [{ key: "answer", type: "string" }],
|
||||
})
|
||||
const permission = {
|
||||
id: Permission.ID.create(),
|
||||
sessionID: config.id,
|
||||
action: "instance-test",
|
||||
resources: [config.tool],
|
||||
}
|
||||
expect(yield* permissions.ask(permission)).toEqual({ id: permission.id, effect: "ask" })
|
||||
const foreignID = config.id === first.id ? second.id : first.id
|
||||
const foreignForm = yield* forms.create({
|
||||
sessionID: foreignID,
|
||||
title: "Foreign form",
|
||||
fields: [{ key: "answer", type: "string" }],
|
||||
})
|
||||
const foreignPermission = yield* permissions.ask({
|
||||
...permission,
|
||||
id: Permission.ID.create(),
|
||||
sessionID: foreignID,
|
||||
})
|
||||
return {
|
||||
session,
|
||||
form,
|
||||
permission: { ...permission, message: config.tool },
|
||||
foreignForm,
|
||||
foreignPermission,
|
||||
}
|
||||
}).pipe(instances.provide(session))
|
||||
}),
|
||||
)
|
||||
for (const entry of pending) {
|
||||
const forms = yield* request(`/api/session/${entry.session.id}/form`)
|
||||
expect(forms.status).toBe(200)
|
||||
expect(yield* Effect.promise<unknown>(() => forms.json())).toEqual({ data: [entry.form] })
|
||||
const permissions = yield* request(`/api/session/${entry.session.id}/permission`)
|
||||
expect(permissions.status).toBe(200)
|
||||
expect(yield* Effect.promise<unknown>(() => permissions.json())).toEqual({ data: [entry.permission] })
|
||||
|
||||
// These IDs exist in the selected instance, but belong to the other Session.
|
||||
expect((yield* request(`/api/session/${entry.session.id}/form/${entry.foreignForm.id}`)).status).toBe(404)
|
||||
expect(
|
||||
(yield* request(`/api/session/${entry.session.id}/permission/${entry.foreignPermission.id}`)).status,
|
||||
).toBe(404)
|
||||
expect(
|
||||
(yield* request(`/api/session/${entry.session.id}/form/${entry.foreignForm.id}/reply`, {
|
||||
answer: { answer: "wrong" },
|
||||
})).status,
|
||||
).toBe(404)
|
||||
expect(
|
||||
(yield* request(`/api/session/${entry.session.id}/permission/${entry.foreignPermission.id}/reply`, {
|
||||
reply: "once",
|
||||
})).status,
|
||||
).toBe(404)
|
||||
yield* Effect.gen(function* () {
|
||||
const forms = yield* Form.Service
|
||||
const permissions = yield* Permission.Service
|
||||
expect(yield* forms.state(entry.foreignForm.id)).toEqual({ status: "pending" })
|
||||
expect(yield* permissions.get(entry.foreignPermission.id)).toMatchObject({
|
||||
sessionID: entry.foreignForm.sessionID,
|
||||
})
|
||||
}).pipe(instances.provide(entry.session))
|
||||
}
|
||||
for (const entry of pending) {
|
||||
expect(
|
||||
(yield* request(`/api/session/${entry.session.id}/form/${entry.form.id}/reply`, {
|
||||
answer: { answer: entry.session.id },
|
||||
})).status,
|
||||
).toBe(204)
|
||||
expect(
|
||||
(yield* request(`/api/session/${entry.session.id}/permission/${entry.permission.id}/reply`, {
|
||||
reply: "once",
|
||||
})).status,
|
||||
).toBe(204)
|
||||
yield* Effect.gen(function* () {
|
||||
const forms = yield* Form.Service
|
||||
const permissions = yield* Permission.Service
|
||||
expect(yield* forms.state(entry.form.id)).toEqual({
|
||||
status: "answered",
|
||||
answer: { answer: entry.session.id },
|
||||
})
|
||||
expect(yield* permissions.get(entry.permission.id)).toBeUndefined()
|
||||
}).pipe(instances.provide(entry.session))
|
||||
}
|
||||
expect(boots).toEqual([first.id, second.id])
|
||||
expect(Array.from(yield* RcMap.keys(locations.rcMap))).toEqual([])
|
||||
}),
|
||||
15_000,
|
||||
)
|
||||
Reference in New Issue
Block a user