mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
fix(core): list the browser on the step that follows a restart or an idle unload
A step lists the browser tools only if its session holds the desktop's grant when the step selects its tools. After the server restarts or unloads a location, the desktop attaches again only once it sees the session run, about 100 ms after that step selected its tools, so the step ran without the browser and the model was told it was gone. - core: the experimental.step.before session hook runs before a step selects its agent, tools and instructions, as the MCP startup grace does for servers that are still connecting. - plugin-browser: a session whose attachment ended is expected. Its next step waits for the desktop, 2 s at most and once; a step also waits for an attach that is in flight.
This commit is contained in:
parent
f555dfefad
commit
08623d032b
12 changed files with 485 additions and 60 deletions
|
|
@ -232,6 +232,8 @@ const layer = Layer.effect(
|
|||
const prepareContext = Effect.fn("SessionRunner.prepareContext")(function* (sessionID: SessionSchema.ID) {
|
||||
// Plugins can reload mid-turn; each step and retry must read the settled agents, models and skills.
|
||||
yield* plugins.awaitActivation
|
||||
// A plugin may settle Session state the selection reads, such as permissions a client is about to grant.
|
||||
yield* hooks.trigger("session", "experimental.step.before", { sessionID })
|
||||
const selected = yield* context.select(sessionID)
|
||||
// A blocked initial instruction baseline must leave admitted input pending.
|
||||
yield* InstructionState.prepare(db, bus, selected.instructions, sessionID)
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { Job } from "@opencode/core/job"
|
|||
import { LocationActivity } from "@opencode/core/location-activity"
|
||||
import { LocationServiceMap } from "@opencode/core/location-services"
|
||||
import { Plugin } from "@opencode/core/plugin"
|
||||
import { PluginHooks } from "@opencode/core/plugin/hooks"
|
||||
import { Rpc } from "@opencode/core/rpc"
|
||||
import { AbsolutePath } from "@opencode/core/schema"
|
||||
import { Session } from "@opencode/core/session"
|
||||
|
|
@ -38,6 +39,10 @@ const activityClock: Clock.Clock = {
|
|||
sleep: (duration) => live.sleep(duration),
|
||||
}
|
||||
|
||||
// A step's wait for its session's desktop runs on this clock, which never ends a sleep: such a step goes on only once
|
||||
// the desktop is attached, however slow the machine is.
|
||||
const unending: Clock.Clock = { ...live, sleep: () => Effect.never }
|
||||
|
||||
const it = testEffect(
|
||||
AppNodeBuilder.build(
|
||||
LayerNode.group([Database.node, Bus.node, Session.node, LocationServiceMap.node, LocationActivity.node]),
|
||||
|
|
@ -58,7 +63,7 @@ const it = testEffect(
|
|||
)
|
||||
|
||||
it.live(
|
||||
"idle eviction ends the browser attachment and permits a fresh attachment",
|
||||
"idle eviction ends the browser attachment, and the session's next step waits for a fresh one",
|
||||
() =>
|
||||
Effect.gen(function* () {
|
||||
const dir = yield* tmpdirScoped()
|
||||
|
|
@ -91,8 +96,20 @@ it.live(
|
|||
|
||||
const replacement = yield* locations.contextEffect(ref)
|
||||
yield* Plugin.awaitActivation.pipe(Effect.provideContext(replacement))
|
||||
// The desktop attaches again once it sees the session run. The step that starts that run selects its tools
|
||||
// only after it did, so the step lists the browser.
|
||||
const step = yield* Context.get(replacement, PluginHooks.Service)
|
||||
.trigger("session", "experimental.step.before", { sessionID: session.id })
|
||||
.pipe(Effect.provideService(Clock.Clock, unending), Effect.forkScoped({ startImmediately: true }))
|
||||
expect(step.pollUnsafe()).toBeUndefined()
|
||||
const fresh = Context.get(replacement, Rpc.Service).client(Browser.Definition)
|
||||
const resumed = yield* fresh.attach({ ...attachment, version: 4 }).pipe(Effect.forkScoped)
|
||||
yield* Fiber.join(step)
|
||||
expect((yield* sessions.get(session.id)).permissions).toContainEqual({
|
||||
action: "browser",
|
||||
resource: "*",
|
||||
effect: "allow",
|
||||
})
|
||||
yield* fresh.state(state).pipe(
|
||||
Effect.retry({
|
||||
while: (error) => "type" in error && error.type === "unavailable",
|
||||
|
|
|
|||
|
|
@ -1304,6 +1304,31 @@ describe("SessionRunnerLLM", () => {
|
|||
expect(idles).toEqual([2])
|
||||
})
|
||||
|
||||
scenario("selects each step's tools by the session permissions its step hook settled first", function* (s) {
|
||||
const hooks = yield* PluginHooks.Service
|
||||
const before: number[] = []
|
||||
yield* hooks.register("session", "experimental.step.before", (event) =>
|
||||
Effect.gen(function* () {
|
||||
before.push(s.requests.length)
|
||||
// The first step's hook withdraws a tool, as a client that lets go of it would; the next one gives it back.
|
||||
yield* s.session
|
||||
.setPermissions({
|
||||
sessionID: event.sessionID,
|
||||
permissions: before.length === 1 ? [{ action: "defect", resource: "*", effect: "deny" }] : [],
|
||||
})
|
||||
.pipe(Effect.orDie)
|
||||
}),
|
||||
)
|
||||
yield* s.admit("Start")
|
||||
yield* s.llm.push(TestLLM.toolCall("call-echo", "echo", { text: "hello" }), TestLLM.text("Done", "text-done"))
|
||||
|
||||
yield* s.resume
|
||||
|
||||
expect(before).toEqual([0, 1])
|
||||
expect(s.requests[0]?.tools.map((tool) => tool.name)).toEqual(["echo", "storefail"])
|
||||
expect(s.requests[1]?.tools.map((tool) => tool.name)).toEqual(["defect", "echo", "storefail"])
|
||||
})
|
||||
|
||||
scenario("passes background work of the session and its descendants to the idle hook", function* (s) {
|
||||
const jobs = yield* Job.Service
|
||||
const hooks = yield* PluginHooks.Service
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import { Location } from "@opencode/schema/location"
|
|||
import type { Permission } from "@opencode/schema/permission"
|
||||
import { Session } from "@opencode/schema/session"
|
||||
import { Tool } from "@opencode/schema/tool"
|
||||
import { Cause, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect"
|
||||
import { Cause, Clock, Deferred, Duration, Effect, Exit, Option, Schema, Scope, Semaphore, Stream } from "effect"
|
||||
import { BrowserMachine } from "./machine.js"
|
||||
import { Browser } from "./rpc.js"
|
||||
import { BrowserTunnel } from "./tunnel.js"
|
||||
|
|
@ -27,40 +27,87 @@ const GrantOwner = Schema.Struct({ host: Schema.String, pid: Schema.Number, loca
|
|||
const GRANT_PREFIX = "grant:"
|
||||
|
||||
/**
|
||||
* A crash or SIGKILL skips the revokes, so a session keeps its grant with no attachment behind it. Revokes the grants
|
||||
* this location's servers recorded, except those of a process that still runs: several servers can share one
|
||||
* database, and another one's attachment may be live. Runs before the RPC registers, so no attach here can race it.
|
||||
* A session a desktop was attached to and that has not run since, stored as `expect:<sessionID>` when that attachment
|
||||
* ended, until the session runs, a desktop attaches or `EXPECTATION_TTL_MS` passes.
|
||||
*/
|
||||
export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleGrants")(function* (ctx: {
|
||||
const Expectation = Schema.Struct({ location: Location.Ref, at: Schema.Finite })
|
||||
|
||||
const EXPECT_PREFIX = "expect:"
|
||||
|
||||
type Stored = {
|
||||
readonly session: Pick<Context["session"], "get" | "update">
|
||||
readonly storage: Pick<Context["storage"], "scan" | "remove">
|
||||
readonly storage: Pick<Context["storage"], "scan" | "set" | "remove">
|
||||
readonly location: Pick<Context["location"], "directory" | "workspaceID">
|
||||
}) {
|
||||
const revoke = (entry: { readonly key: string; readonly value: Schema.Json }) => {
|
||||
const owner = Schema.decodeUnknownOption(GrantOwner)(entry.value)
|
||||
if (
|
||||
Option.isNone(owner) ||
|
||||
owner.value.location.directory !== ctx.location.directory ||
|
||||
owner.value.location.workspaceID !== ctx.location.workspaceID ||
|
||||
running(owner.value)
|
||||
)
|
||||
return Effect.void
|
||||
return writePermissions(ctx, Session.ID.make(entry.key.slice(GRANT_PREFIX.length)), false).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(ctx.storage.remove(entry.key)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** This plugin's location, as its stored records name it. */
|
||||
const locationOf = (ctx: Pick<Stored, "location">): typeof Location.Ref.Encoded => ({
|
||||
directory: ctx.location.directory,
|
||||
...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }),
|
||||
})
|
||||
|
||||
const here = (ctx: Pick<Stored, "location">, location: Location.Ref) =>
|
||||
location.directory === ctx.location.directory && location.workspaceID === ctx.location.workspaceID
|
||||
|
||||
/** Runs `each` on every stored entry under `prefix`, a page at a time. */
|
||||
const scan = (
|
||||
ctx: Pick<Stored, "storage">,
|
||||
prefix: string,
|
||||
each: (entry: { readonly key: string; readonly value: Schema.Json }) => Effect.Effect<void>,
|
||||
) => {
|
||||
const page = (after?: string): Effect.Effect<void> =>
|
||||
ctx.storage
|
||||
.scan({ prefix: GRANT_PREFIX, after })
|
||||
.scan({ prefix, after })
|
||||
.pipe(
|
||||
Effect.flatMap((result) =>
|
||||
Effect.forEach(result.entries, revoke, { discard: true }).pipe(
|
||||
Effect.forEach(result.entries, each, { discard: true }).pipe(
|
||||
Effect.andThen(result.next === undefined ? Effect.void : page(result.next)),
|
||||
),
|
||||
),
|
||||
)
|
||||
yield* page()
|
||||
return page()
|
||||
}
|
||||
|
||||
const expect = (ctx: Pick<Stored, "storage" | "location">, sessionID: Session.ID) =>
|
||||
Clock.currentTimeMillis.pipe(
|
||||
Effect.flatMap((at) => ctx.storage.set(EXPECT_PREFIX + sessionID, { location: locationOf(ctx), at })),
|
||||
)
|
||||
|
||||
/**
|
||||
* A crash or SIGKILL skips the revokes, so a session keeps its grant with no attachment behind it. Revokes the grants
|
||||
* this location's servers recorded, except those of a process that still runs: several servers can share one
|
||||
* database, and another one's attachment may be live. Such a session's desktop was attached when its server died, so
|
||||
* the session is expected. Runs before the RPC registers, so no attach here can race it.
|
||||
*/
|
||||
export const reconcileStaleGrants = Effect.fn("BrowserConnection.reconcileStaleGrants")(function* (ctx: Stored) {
|
||||
yield* scan(ctx, GRANT_PREFIX, (entry) => {
|
||||
const owner = Schema.decodeUnknownOption(GrantOwner)(entry.value)
|
||||
if (Option.isNone(owner) || !here(ctx, owner.value.location) || running(owner.value)) return Effect.void
|
||||
const sessionID = Session.ID.make(entry.key.slice(GRANT_PREFIX.length))
|
||||
return writePermissions(ctx, sessionID, false).pipe(
|
||||
Effect.ignore,
|
||||
Effect.andThen(ctx.storage.remove(entry.key)),
|
||||
Effect.andThen(expect(ctx, sessionID)),
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
* The sessions this location's earlier plugin instances left expected. One that has not run for `EXPECTATION_TTL_MS`
|
||||
* is forgotten instead, so the records of sessions that never run again do not pile up.
|
||||
*/
|
||||
export const loadExpectations = Effect.fn("BrowserConnection.loadExpectations")(function* (
|
||||
ctx: Pick<Stored, "storage" | "location">,
|
||||
) {
|
||||
const now = yield* Clock.currentTimeMillis
|
||||
const expected: Session.ID[] = []
|
||||
yield* scan(ctx, EXPECT_PREFIX, (entry) => {
|
||||
const record = Schema.decodeUnknownOption(Expectation)(entry.value)
|
||||
if (Option.isNone(record) || !here(ctx, record.value.location)) return Effect.void
|
||||
if (record.value.at + BrowserMachine.EXPECTATION_TTL_MS <= now) return ctx.storage.remove(entry.key)
|
||||
return Effect.sync(() => void expected.push(Session.ID.make(entry.key.slice(EXPECT_PREFIX.length))))
|
||||
})
|
||||
return expected
|
||||
})
|
||||
|
||||
export const make = Effect.fn("BrowserConnection.make")(function* (
|
||||
|
|
@ -112,9 +159,12 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
|
|||
// Permission syncs run here. Registered first, so it closes last: after disposal has drained the revokes.
|
||||
const work = yield* Scope.make()
|
||||
yield* Effect.addFinalizer((exit) => Scope.close(work, exit))
|
||||
const machine = { state: BrowserMachine.createConnectionState() }
|
||||
yield* reconcileStaleGrants(ctx)
|
||||
const machine = { state: BrowserMachine.createConnectionState(yield* loadExpectations(ctx)) }
|
||||
const attachments = new Map<number, Attachment>()
|
||||
const requests = new Map<string, Deferred.Deferred<Browser.Result, Tool.Error>>()
|
||||
// Steps that wait for their session's attachment, each until `notify-settled` or its grace runs out.
|
||||
const waiting = new Map<Session.ID, Deferred.Deferred<void>>()
|
||||
const drained = Deferred.makeUnsafe<void>()
|
||||
// One event at a time, effects included, so controls reach the bus in transition order: `attached` before any
|
||||
// `command` of that attachment.
|
||||
|
|
@ -163,16 +213,18 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
|
|||
).pipe(Effect.asVoid)
|
||||
})
|
||||
if (effect.type === "warn") return Effect.logWarning(effect.message, effect.error)
|
||||
if (effect.type === "record-expectation") return expect(ctx, effect.sessionID)
|
||||
if (effect.type === "forget-expectation") return ctx.storage.remove(EXPECT_PREFIX + effect.sessionID)
|
||||
if (effect.type === "notify-settled")
|
||||
return Effect.suspend(() => {
|
||||
const settled = waiting.get(effect.sessionID)
|
||||
if (!settled) return Effect.void
|
||||
waiting.delete(effect.sessionID)
|
||||
return Deferred.done(settled, Exit.void).pipe(Effect.asVoid)
|
||||
})
|
||||
return Deferred.done(drained, Exit.void).pipe(Effect.asVoid)
|
||||
}
|
||||
const owner: typeof GrantOwner.Encoded = {
|
||||
host: hostname(),
|
||||
pid: process.pid,
|
||||
location: {
|
||||
directory: ctx.location.directory,
|
||||
...(ctx.location.workspaceID === undefined ? {} : { workspaceID: ctx.location.workspaceID }),
|
||||
},
|
||||
}
|
||||
const owner: typeof GrantOwner.Encoded = { host: hostname(), pid: process.pid, location: locationOf(ctx) }
|
||||
const syncPermissions = (effect: Extract<BrowserMachine.ConnectionEffect, { readonly type: "sync-permissions" }>) =>
|
||||
// The owner is recorded before the grant and forgotten after the revoke, so a stored grant always has one.
|
||||
(effect.allow
|
||||
|
|
@ -210,7 +262,6 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
|
|||
? Effect.succeed(attachment.tunnels)
|
||||
: Effect.fail(new Error("Browser attachment is unavailable; its network connections were closed."))
|
||||
}
|
||||
yield* reconcileStaleGrants(ctx)
|
||||
const rpc: RpcRegistration<typeof Browser.Definition> = yield* ctx.rpc
|
||||
.register(Browser.Definition, {
|
||||
attach: (input, call) =>
|
||||
|
|
@ -333,6 +384,23 @@ export const make = Effect.fn("BrowserConnection.make")(function* (
|
|||
Effect.catchCause((cause) => Effect.logWarning("Browser permission revoke failed", cause)),
|
||||
),
|
||||
)
|
||||
// A step lists the browser tools only if its session holds the grant when the step selects its tools. A step that
|
||||
// would start just ahead of it waits here: for a desktop that is attaching, and once for one that is expected to
|
||||
// attach again, as after the server restarted or unloaded the session's location. The grace that runs out ends the
|
||||
// expectation, so no later step waits for a desktop that is gone.
|
||||
yield* ctx.session.hook("experimental.step.before", (event) =>
|
||||
Effect.suspend(() => {
|
||||
if (!BrowserMachine.isAwaited(machine.state, event.sessionID)) return Effect.void
|
||||
const settled = waiting.get(event.sessionID) ?? Deferred.makeUnsafe<void>()
|
||||
waiting.set(event.sessionID, settled)
|
||||
return Deferred.await(settled).pipe(
|
||||
Effect.timeoutOrElse({
|
||||
duration: Duration.millis(BrowserMachine.ATTACH_GRACE_MS),
|
||||
orElse: () => dispatch({ type: "step.timed-out", sessionID: event.sessionID }),
|
||||
}),
|
||||
)
|
||||
}),
|
||||
)
|
||||
// Registered last, so it runs first: attachments close and revokes drain while the RPC and `work` are still open.
|
||||
yield* Effect.addFinalizer(() => dispatch({ type: "disposed" }).pipe(Effect.andThen(Deferred.await(drained))))
|
||||
|
||||
|
|
|
|||
|
|
@ -13,6 +13,15 @@ export const PERMISSION_SYNC_TIMEOUT_MS = 10_000
|
|||
/** How long a dispatched browser command may run before it times out and is cancelled on the desktop. */
|
||||
export const REQUEST_TIMEOUT_MS = 60_000
|
||||
|
||||
/**
|
||||
* How long a step may wait, before it selects its tools, for a desktop that is attaching to its session or is expected
|
||||
* to attach again. Core gives an MCP server that is still connecting the same grace.
|
||||
*/
|
||||
export const ATTACH_GRACE_MS = 2_000
|
||||
|
||||
/** How long a session stays `expected` while it does not run. A desktop that has not come back by then is not waited for. */
|
||||
export const EXPECTATION_TTL_MS = 7 * 24 * 60 * 60 * 1_000
|
||||
|
||||
/** The browser tools and their skill, which an attachment allows together. */
|
||||
export const ACCESS = [
|
||||
{ action: "browser", resource: "*" },
|
||||
|
|
@ -28,7 +37,12 @@ export type PermissionSync = { readonly attempt: number; readonly allow: boolean
|
|||
* - `attaching`: the desktop called `attach` as `attempt`. Its grant runs after any revoke in flight (`sync`); until it
|
||||
* succeeds, no `attached` handshake is sent and no command is dispatched.
|
||||
* - `attached`: the session allows the browser and the desktop received `attached`; commands run.
|
||||
* - `revoking`: no attachment; `sync` settles, then a revoke follows unless the session was `deleted`.
|
||||
* - `revoking`: no attachment; `sync` settles, then a revoke follows unless the session was `deleted`. With `expect`,
|
||||
* the session is `expected` once that revoke settles.
|
||||
* - `expected`: no attachment and no sync in flight. A desktop was attached and the session has not run since, so that
|
||||
* desktop may attach again once it does: one the server cut off, as when it unloads the session's location or
|
||||
* restarts, attaches again when it sees the session run. The session's next step waits for that, `ATTACH_GRACE_MS`
|
||||
* at most, and the entry ends with that step or with the attachment.
|
||||
*/
|
||||
export type SessionState =
|
||||
| {
|
||||
|
|
@ -44,10 +58,13 @@ export type SessionState =
|
|||
readonly browserState: Browser.State
|
||||
readonly pending: ReadonlyMap<string, Browser.Command>
|
||||
}
|
||||
| { readonly status: "revoking"; readonly sync: PermissionSync; readonly deleted: boolean }
|
||||
| { readonly status: "revoking"; readonly sync: PermissionSync; readonly deleted: boolean; readonly expect: boolean }
|
||||
| { readonly status: "expected" }
|
||||
|
||||
export type RevokingSession = Extract<SessionState, { readonly status: "revoking" }>
|
||||
|
||||
type ExpectedSession = Extract<SessionState, { readonly status: "expected" }>
|
||||
|
||||
type AttachingSession = Extract<SessionState, { readonly status: "attaching" }>
|
||||
|
||||
type AttachedSession = Extract<SessionState, { readonly status: "attached" }>
|
||||
|
|
@ -132,6 +149,8 @@ export type ConnectionEvent =
|
|||
}
|
||||
| { readonly type: "session.moved"; readonly sessionID: Session.ID }
|
||||
| { readonly type: "session.deleted"; readonly sessionID: Session.ID }
|
||||
/** A step waited `ATTACH_GRACE_MS` for the session's attachment before it selected its tools, and went on without. */
|
||||
| { readonly type: "step.timed-out"; readonly sessionID: Session.ID }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type ConnectionEffect =
|
||||
|
|
@ -153,6 +172,11 @@ export type ConnectionEffect =
|
|||
}
|
||||
| { readonly type: "settle-request"; readonly requestID: string; readonly settlement: RequestSettlement }
|
||||
| { readonly type: "warn"; readonly message: string; readonly error: unknown }
|
||||
/** Stores that the session is `expected`, for the plugin's next instance in this location. */
|
||||
| { readonly type: "record-expectation"; readonly sessionID: Session.ID }
|
||||
| { readonly type: "forget-expectation"; readonly sessionID: Session.ID }
|
||||
/** No step waits for the session any more (`isAwaited`): a desktop attached, or none is expected. */
|
||||
| { readonly type: "notify-settled"; readonly sessionID: Session.ID }
|
||||
/** The disposed plugin has no revoke left in flight. */
|
||||
| { readonly type: "notify-drained" }
|
||||
|
||||
|
|
@ -166,8 +190,13 @@ type Step<S extends SessionState> = {
|
|||
readonly effects: readonly ConnectionEffect[]
|
||||
}
|
||||
|
||||
export function createConnectionState(): ConnectionState {
|
||||
return { status: "active", nextAttempt: 1, sessions: new Map() }
|
||||
/** `expected` are the sessions the plugin's earlier instances in this location left `expected`. */
|
||||
export function createConnectionState(expected: Iterable<Session.ID> = []): ConnectionState {
|
||||
return {
|
||||
status: "active",
|
||||
nextAttempt: 1,
|
||||
sessions: new Map(Array.from(expected, (sessionID) => [sessionID, { status: "expected" }])),
|
||||
}
|
||||
}
|
||||
|
||||
export function transitionConnection(state: ConnectionState, event: ConnectionEvent): ConnectionTransition {
|
||||
|
|
@ -195,9 +224,10 @@ export function transitionConnection(state: ConnectionState, event: ConnectionEv
|
|||
if (!step) return { state, effects: [] }
|
||||
const sessions = new Map(state.sessions)
|
||||
|
||||
if (step.entry) sessions.set(event.sessionID, step.entry)
|
||||
// A disposed plugin keeps only its revokes: an expectation waits in storage for the next instance.
|
||||
if (step.entry?.status === "revoking") sessions.set(event.sessionID, step.entry)
|
||||
|
||||
if (!step.entry) sessions.delete(event.sessionID)
|
||||
if (step.entry?.status !== "revoking") sessions.delete(event.sessionID)
|
||||
|
||||
return {
|
||||
state: { status: "disposed", nextAttempt: step.nextAttempt, sessions },
|
||||
|
|
@ -213,8 +243,12 @@ export function transitionConnection(state: ConnectionState, event: ConnectionEv
|
|||
if (step.entry) sessions.set(event.sessionID, step.entry)
|
||||
|
||||
if (!step.entry) sessions.delete(event.sessionID)
|
||||
const settled = awaited(entry) && !awaited(step.entry)
|
||||
|
||||
return { state: { status: "active", nextAttempt: step.nextAttempt, sessions }, effects: step.effects }
|
||||
return {
|
||||
state: { status: "active", nextAttempt: step.nextAttempt, sessions },
|
||||
effects: settled ? [...step.effects, { type: "notify-settled", sessionID: event.sessionID }] : step.effects,
|
||||
}
|
||||
}
|
||||
|
||||
function transitionSession(
|
||||
|
|
@ -226,6 +260,8 @@ function transitionSession(
|
|||
|
||||
if (!entry) return undefined
|
||||
|
||||
if (entry.status === "expected") return transitionExpected(event, nextAttempt)
|
||||
|
||||
if (entry.status === "revoking") return transitionRevoking(entry, event, nextAttempt)
|
||||
|
||||
if (entry.status === "attaching") return transitionAttaching(entry, event, nextAttempt)
|
||||
|
|
@ -259,7 +295,9 @@ function attach(
|
|||
const effects: ConnectionEffect[] =
|
||||
entry?.status === "attached"
|
||||
? [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "replaced" }]
|
||||
: []
|
||||
: entry?.status === "expected"
|
||||
? [{ type: "forget-expectation", sessionID: event.sessionID }]
|
||||
: []
|
||||
|
||||
return {
|
||||
entry: attaching(sync),
|
||||
|
|
@ -310,7 +348,7 @@ function transitionAttaching(
|
|||
const sync = { attempt: nextAttempt, allow: false }
|
||||
|
||||
return {
|
||||
entry: { status: "revoking", sync, deleted: false },
|
||||
entry: { status: "revoking", sync, deleted: false, expect: false },
|
||||
nextAttempt: nextAttempt + 1,
|
||||
effects: [
|
||||
...warning,
|
||||
|
|
@ -326,7 +364,7 @@ function transitionAttaching(
|
|||
event.type === "session.deleted"
|
||||
)
|
||||
return {
|
||||
entry: { status: "revoking", sync: entry.sync, deleted: event.type === "session.deleted" },
|
||||
entry: { status: "revoking", sync: entry.sync, deleted: event.type === "session.deleted", expect: false },
|
||||
nextAttempt,
|
||||
effects: [{ type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
|
||||
}
|
||||
|
|
@ -380,20 +418,32 @@ function transitionAttached(
|
|||
effects: [...failPending(entry), { type: "close-attachment", attempt: entry.attempt, outcome: "closed" }],
|
||||
}
|
||||
|
||||
// A session that moved runs in another location, so no step here waits for its desktop.
|
||||
if ((event.type === "attach.closed" && event.attempt === entry.attempt) || event.type === "session.moved")
|
||||
return revokeAttached(entry, event.sessionID, nextAttempt)
|
||||
return revokeAttached(entry, event.sessionID, nextAttempt, event.type === "attach.closed")
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
function transitionExpected(event: SessionEvent, nextAttempt: number): Step<SessionState> | undefined {
|
||||
// The step that waited was the desktop's one chance; a deleted session has no step, and a moved one none here.
|
||||
if (event.type !== "step.timed-out" && event.type !== "session.moved" && event.type !== "session.deleted")
|
||||
return undefined
|
||||
|
||||
return { entry: undefined, nextAttempt, effects: [{ type: "forget-expectation", sessionID: event.sessionID }] }
|
||||
}
|
||||
|
||||
function transitionRevoking(
|
||||
entry: RevokingSession,
|
||||
event: SessionEvent,
|
||||
nextAttempt: number,
|
||||
): Step<RevokingSession> | undefined {
|
||||
): Step<RevokingSession | ExpectedSession> | undefined {
|
||||
if (event.type === "session.deleted")
|
||||
return entry.deleted ? undefined : { entry: { ...entry, deleted: true }, nextAttempt, effects: [] }
|
||||
|
||||
if (event.type === "step.timed-out" || event.type === "session.moved")
|
||||
return entry.expect ? { entry: { ...entry, expect: false }, nextAttempt, effects: [] } : undefined
|
||||
|
||||
if (
|
||||
event.type !== "permissions.synced" &&
|
||||
event.type !== "permissions.failed" &&
|
||||
|
|
@ -409,12 +459,19 @@ function transitionRevoking(
|
|||
const sync = { attempt: nextAttempt, allow: false }
|
||||
|
||||
return {
|
||||
entry: { status: "revoking", sync, deleted: false },
|
||||
entry: { status: "revoking", sync, deleted: false, expect: entry.expect },
|
||||
nextAttempt: nextAttempt + 1,
|
||||
effects: [...warning, { type: "sync-permissions", sessionID: event.sessionID, ...sync }],
|
||||
}
|
||||
}
|
||||
|
||||
if (entry.expect && !entry.deleted)
|
||||
return {
|
||||
entry: { status: "expected" },
|
||||
nextAttempt,
|
||||
effects: [...warning, { type: "record-expectation", sessionID: event.sessionID }],
|
||||
}
|
||||
|
||||
return { entry: undefined, nextAttempt, effects: warning }
|
||||
}
|
||||
|
||||
|
|
@ -423,6 +480,12 @@ function dispose(state: ConnectionState): ConnectionTransition {
|
|||
const effects: ConnectionEffect[] = []
|
||||
const sessions = new Map<Session.ID, RevokingSession>()
|
||||
const nextAttempt = Array.from(state.sessions).reduce((attempt, [sessionID, entry]) => {
|
||||
// A step that waits for the session's attachment goes on: this instance takes none.
|
||||
if (awaited(entry)) effects.push({ type: "notify-settled", sessionID })
|
||||
|
||||
// Its record stays in storage for the next instance.
|
||||
if (entry.status === "expected") return attempt
|
||||
|
||||
if (entry.status === "revoking") {
|
||||
sessions.set(sessionID, entry)
|
||||
|
||||
|
|
@ -430,12 +493,12 @@ function dispose(state: ConnectionState): ConnectionTransition {
|
|||
}
|
||||
|
||||
if (entry.status === "attaching") {
|
||||
sessions.set(sessionID, { status: "revoking", sync: entry.sync, deleted: false })
|
||||
sessions.set(sessionID, { status: "revoking", sync: entry.sync, deleted: false, expect: false })
|
||||
effects.push({ type: "close-attachment", attempt: entry.attempt, outcome: "closed" })
|
||||
|
||||
return attempt
|
||||
}
|
||||
const step = revokeAttached(entry, sessionID, attempt)
|
||||
const step = revokeAttached(entry, sessionID, attempt, true)
|
||||
|
||||
if (step.entry) sessions.set(sessionID, step.entry)
|
||||
effects.push(...step.effects)
|
||||
|
|
@ -448,11 +511,16 @@ function dispose(state: ConnectionState): ConnectionTransition {
|
|||
return { state: { status: "disposed", nextAttempt, sessions }, effects }
|
||||
}
|
||||
|
||||
function revokeAttached(entry: AttachedSession, sessionID: Session.ID, nextAttempt: number): Step<RevokingSession> {
|
||||
function revokeAttached(
|
||||
entry: AttachedSession,
|
||||
sessionID: Session.ID,
|
||||
nextAttempt: number,
|
||||
expect: boolean,
|
||||
): Step<RevokingSession> {
|
||||
const sync = { attempt: nextAttempt, allow: false }
|
||||
|
||||
return {
|
||||
entry: { status: "revoking", sync, deleted: false },
|
||||
entry: { status: "revoking", sync, deleted: false, expect },
|
||||
nextAttempt: nextAttempt + 1,
|
||||
effects: [
|
||||
...failPending(entry),
|
||||
|
|
@ -595,7 +663,23 @@ export function isConnectionDisposed(state: ConnectionState) {
|
|||
|
||||
/** Whether the session has an attachment or a permission sync in flight, either of which owns its browser rules. */
|
||||
export function hasSession(state: ConnectionState, sessionID: Session.ID) {
|
||||
return state.sessions.has(sessionID)
|
||||
const entry = state.sessions.get(sessionID)
|
||||
|
||||
return entry !== undefined && entry.status !== "expected"
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a step waits before it selects its tools: a desktop is attaching to the session, or one is expected to
|
||||
* attach again. The step lists the browser tools only if the session holds the grant by then.
|
||||
*/
|
||||
export function isAwaited(state: ConnectionState, sessionID: Session.ID) {
|
||||
return state.status === "active" && awaited(state.sessions.get(sessionID))
|
||||
}
|
||||
|
||||
function awaited(entry: SessionState | undefined) {
|
||||
return (
|
||||
entry?.status === "attaching" || entry?.status === "expected" || (entry?.status === "revoking" && entry.expect)
|
||||
)
|
||||
}
|
||||
|
||||
/** The attempt the next `attach` gets; the driver keys its handle by it before dispatching `attach.started`. */
|
||||
|
|
@ -608,7 +692,8 @@ export function selectAttachment(state: ConnectionState, sessionID: Session.ID,
|
|||
if (state.status === "disposed") return undefined
|
||||
const entry = state.sessions.get(sessionID)
|
||||
|
||||
if (entry?.status === "revoking" || entry?.connectionID !== connectionID) return undefined
|
||||
if (entry?.status === "revoking" || entry?.status === "expected" || entry?.connectionID !== connectionID)
|
||||
return undefined
|
||||
|
||||
return entry.attempt
|
||||
}
|
||||
|
|
@ -646,7 +731,7 @@ export function selectConnection(
|
|||
| { readonly ok: false; readonly error: Tool.Error } {
|
||||
const entry = state.status === "active" ? state.sessions.get(sessionID) : undefined
|
||||
|
||||
if (!entry || entry.status === "revoking")
|
||||
if (!entry || entry.status === "revoking" || entry.status === "expected")
|
||||
return {
|
||||
ok: false,
|
||||
error: new Tool.Error({
|
||||
|
|
|
|||
|
|
@ -6,7 +6,9 @@ import type { PermissionEvaluation } from "@opencode/plugin/effect/permission"
|
|||
import type { Permission } from "@opencode/schema/permission"
|
||||
import { Tool } from "@opencode/schema/tool"
|
||||
import { Effect, Fiber, Schedule, Stream } from "effect"
|
||||
import { TestClock } from "effect/testing"
|
||||
import { BrowserConnection } from "../src/connection.js"
|
||||
import { BrowserMachine } from "../src/machine.js"
|
||||
import { Browser } from "../src/rpc.js"
|
||||
import { BrowserTools } from "../src/tools.js"
|
||||
|
||||
|
|
@ -41,6 +43,7 @@ function plugin(input: {
|
|||
const storage = new Map(Object.entries(input.storage ?? {}))
|
||||
const hooks: ((event: PermissionEvaluation) => Effect.Effect<void>)[] = []
|
||||
const prompts: ((event: { sessionID: string }) => Effect.Effect<void>)[] = []
|
||||
const steps: ((event: { sessionID: string }) => Effect.Effect<void>)[] = []
|
||||
const tools: ToolDefinition[] = []
|
||||
const asserts: AssertCall[] = []
|
||||
const controls: Control[] = []
|
||||
|
|
@ -72,7 +75,8 @@ function plugin(input: {
|
|||
|
||||
if (row) row.permissions = request.permissions
|
||||
}),
|
||||
hook: (_name: "prompt", hook: (event: { sessionID: string }) => Effect.Effect<void>) => Effect.sync(() => void prompts.push(hook)),
|
||||
hook: (name: "prompt" | "experimental.step.before", hook: (event: { sessionID: string }) => Effect.Effect<void>) =>
|
||||
Effect.sync(() => void (name === "prompt" ? prompts : steps).push(hook)),
|
||||
},
|
||||
storage: {
|
||||
scan: (request: { prefix: string }) =>
|
||||
|
|
@ -124,6 +128,11 @@ function plugin(input: {
|
|||
commands: () => controls.filter((control) => control.type === "command").length,
|
||||
evaluate: (event: PermissionEvaluation) => Effect.forEach(hooks, (hook) => hook(event), { discard: true }).pipe(Effect.as(event)),
|
||||
prompt: (sessionID: string) => Effect.forEach(prompts, (hook) => hook({ sessionID }), { discard: true }),
|
||||
/** What core runs before a step of `sessionID` selects its tools. */
|
||||
step: (sessionID: string) => Effect.forEach(steps, (hook) => hook({ sessionID }), { discard: true }),
|
||||
/** A desktop's `attach` call for `sessionID`, without waiting for its handshake. */
|
||||
connect: (sessionID: string) =>
|
||||
Effect.forkChild(rpc.handlers!.attach({ sessionID, connectionID: crypto.randomUUID(), version: 4 }, call), { startImmediately: true }),
|
||||
/** Attaches a desktop to `sessionID` and reports one open tab; interrupting the fiber detaches it. */
|
||||
attach: (sessionID: string) =>
|
||||
Effect.gen(function* () {
|
||||
|
|
@ -365,7 +374,8 @@ describe("grants", () => {
|
|||
|
||||
expect([...fake.sessions.values()].map((row) => [row.id, row.permissions?.length])).toEqual([["ses_dead", 1], ["ses_live", 3], ["ses_remote", 3], ["ses_elsewhere", 3]])
|
||||
expect(fake.sessions.get("ses_dead")?.permissions).toEqual([rule("*", "deny", "bash")])
|
||||
expect([...fake.storage.keys()]).toEqual(["grant:ses_live", "grant:ses_remote", "grant:ses_elsewhere"])
|
||||
// Its desktop was attached when its server died, so the session is expected.
|
||||
expect([...fake.storage.keys()]).toEqual(["grant:ses_live", "grant:ses_remote", "grant:ses_elsewhere", "expect:ses_dead"])
|
||||
})
|
||||
|
||||
test("attaching grants the session, and detaching revokes it and forgets its owner", async () => {
|
||||
|
|
@ -408,3 +418,70 @@ describe("grants", () => {
|
|||
)
|
||||
})
|
||||
})
|
||||
|
||||
// The server restarts, or unloads a location that went idle, with a desktop attached. That desktop attaches again once
|
||||
// it sees the session run, a moment after the step that starts the run has selected its tools: without the grant, so
|
||||
// without the browser. The step waits for the desktop the session expects instead, for a bounded time and once.
|
||||
describe("a step and the desktop its session expects", () => {
|
||||
const expected = (directory = "/workspace", at = Date.now()) => ({ location: { directory }, at })
|
||||
|
||||
// On the test clock: only the test moves time, so a step that goes on did so because the desktop attached.
|
||||
test("the step waits until the desktop holds the grant again", async () => {
|
||||
const fake = plugin({ directory: "/workspace", sessions: [session("ses_a", "/workspace")], storage: { "expect:ses_a": expected() } })
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* BrowserConnection.make(fake.context)
|
||||
const step = yield* Effect.forkChild(fake.step("ses_a"), { startImmediately: true })
|
||||
expect(step.pollUnsafe()).toBeUndefined()
|
||||
|
||||
yield* fake.connect("ses_a")
|
||||
yield* Fiber.join(step)
|
||||
expect(fake.sessions.get("ses_a")?.permissions).toEqual(grant)
|
||||
expect(fake.storage.has("expect:ses_a")).toBe(false)
|
||||
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
|
||||
)
|
||||
})
|
||||
|
||||
test("a desktop that does not come back costs the next step its grace, and no step after it", async () => {
|
||||
const fake = plugin({ directory: "/workspace", sessions: [session("ses_a", "/workspace")], storage: { "expect:ses_a": expected() } })
|
||||
|
||||
await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* BrowserConnection.make(fake.context)
|
||||
const first = yield* Effect.forkChild(fake.step("ses_a"), { startImmediately: true })
|
||||
yield* TestClock.adjust(BrowserMachine.ATTACH_GRACE_MS - 1)
|
||||
expect(first.pollUnsafe()).toBeUndefined()
|
||||
yield* TestClock.adjust(1)
|
||||
yield* Fiber.join(first)
|
||||
expect(fake.storage.has("expect:ses_a")).toBe(false)
|
||||
|
||||
// Time stands still here: a second wait would never end.
|
||||
yield* fake.step("ses_a")
|
||||
}).pipe(Effect.scoped, Effect.provide(TestClock.layer())),
|
||||
)
|
||||
})
|
||||
|
||||
test("an attachment that ends leaves its session expected for the plugin's next instance", async () => {
|
||||
const fake = plugin({
|
||||
directory: "/workspace",
|
||||
sessions: [session("ses_a", "/workspace")],
|
||||
storage: { "expect:ses_old": expected("/workspace", 0), "expect:ses_elsewhere": expected("/other") },
|
||||
})
|
||||
|
||||
const loaded = await Effect.runPromise(
|
||||
Effect.gen(function* () {
|
||||
yield* BrowserConnection.make(fake.context)
|
||||
yield* Fiber.interrupt(yield* fake.attach("ses_a"))
|
||||
yield* until(() => fake.storage.has("expect:ses_a"))
|
||||
expect(fake.sessions.get("ses_a")?.permissions).toEqual([])
|
||||
|
||||
return yield* BrowserConnection.loadExpectations(fake.context)
|
||||
}).pipe(Effect.scoped),
|
||||
)
|
||||
|
||||
// One that did not run for the whole TTL was forgotten when the plugin started; another location's is not ours.
|
||||
expect<string[]>(loaded).toEqual(["ses_a"])
|
||||
expect([...fake.storage.keys()].toSorted()).toEqual(["expect:ses_a", "expect:ses_elsewhere"])
|
||||
})
|
||||
})
|
||||
|
|
|
|||
|
|
@ -175,7 +175,11 @@ describe("handshake", () => {
|
|||
const first = run(initial, attach(initial, "conn_1"))
|
||||
const grant = lastSync(first.effects)
|
||||
const closed = run(first.state, type === "attach.closed" ? { type, sessionID, attempt: 1 } : { type, sessionID })
|
||||
expect(closed.effects).toEqual([{ type: "close-attachment", attempt: 1, outcome: "closed" }])
|
||||
// A step that waited for the attach goes on without it.
|
||||
expect(closed.effects).toEqual([
|
||||
{ type: "close-attachment", attempt: 1, outcome: "closed" },
|
||||
{ type: "notify-settled", sessionID },
|
||||
])
|
||||
|
||||
const settled = run(closed.state, synced(grant.attempt))
|
||||
expect(controls(settled.effects)).toEqual([])
|
||||
|
|
@ -468,6 +472,83 @@ describe("session lifecycle", () => {
|
|||
})
|
||||
})
|
||||
|
||||
// A step lists the browser tools only if its session holds the grant when the step selects its tools. After the server
|
||||
// restarted or unloaded a location, the desktop attaches again only once it sees the session run, which is just too
|
||||
// late for that step: so a session whose attachment ended is expected, and its next step waits for the desktop, once.
|
||||
describe("expected desktop", () => {
|
||||
/** The session after its desktop's attachment ended and the revoke settled. */
|
||||
function ended() {
|
||||
const closed = run(attached(), { type: "attach.closed", sessionID, attempt: 1 })
|
||||
return { closed, revoked: run(closed.state, synced(lastSync(closed.effects).attempt)) }
|
||||
}
|
||||
|
||||
test("a session whose attachment ended is expected, and a step waits until its desktop holds the grant again", () => {
|
||||
const { closed, revoked } = ended()
|
||||
expect(BrowserMachine.isAwaited(closed.state, sessionID)).toBe(true)
|
||||
expect(entry(revoked.state)).toEqual({ status: "expected" })
|
||||
expect(revoked.effects).toEqual([{ type: "record-expectation", sessionID }])
|
||||
// No attachment owns the session's rules meanwhile, and no tool call reaches a desktop.
|
||||
expect(BrowserMachine.hasSession(revoked.state, sessionID)).toBe(false)
|
||||
expect(BrowserMachine.selectConnection(revoked.state, sessionID).ok).toBe(false)
|
||||
|
||||
const back = run(revoked.state, attach(revoked.state, "conn_2"))
|
||||
expect(back.effects).toContainEqual({ type: "forget-expectation", sessionID })
|
||||
expect(BrowserMachine.isAwaited(back.state, sessionID)).toBe(true)
|
||||
|
||||
const granted = run(back.state, synced(lastSync(back.effects).attempt))
|
||||
expect(granted.effects).toContainEqual({ type: "notify-settled", sessionID })
|
||||
expect(BrowserMachine.isAwaited(granted.state, sessionID)).toBe(false)
|
||||
})
|
||||
|
||||
test("the step that waits in vain ends the expectation, also while the revoke is still in flight", () => {
|
||||
const { closed, revoked } = ended()
|
||||
const waited = run(revoked.state, { type: "step.timed-out", sessionID })
|
||||
expect(entry(waited.state)).toBeUndefined()
|
||||
expect(waited.effects).toEqual([
|
||||
{ type: "forget-expectation", sessionID },
|
||||
{ type: "notify-settled", sessionID },
|
||||
])
|
||||
|
||||
const early = run(closed.state, { type: "step.timed-out", sessionID })
|
||||
expect(early.effects).toEqual([{ type: "notify-settled", sessionID }])
|
||||
const done = run(early.state, synced(lastSync(closed.effects).attempt))
|
||||
expect(entry(done.state)).toBeUndefined()
|
||||
expect(done.effects).toEqual([])
|
||||
})
|
||||
|
||||
test.each(["session.moved", "session.deleted"] as const)("%s ends the expectation: no step here waits", (type) => {
|
||||
const gone = run(ended().revoked.state, { type, sessionID })
|
||||
expect(entry(gone.state)).toBeUndefined()
|
||||
expect(gone.effects).toContainEqual({ type: "forget-expectation", sessionID })
|
||||
})
|
||||
|
||||
test("a session that moved while attached is not expected here", () => {
|
||||
const moved = run(attached(), { type: "session.moved", sessionID })
|
||||
expect(BrowserMachine.isAwaited(moved.state, sessionID)).toBe(false)
|
||||
const done = run(moved.state, synced(lastSync(moved.effects).attempt))
|
||||
expect(entry(done.state)).toBeUndefined()
|
||||
expect(done.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("a step waits for an attach in flight only: its grace running out changes nothing", () => {
|
||||
const initial = BrowserMachine.createConnectionState()
|
||||
const attaching = run(initial, attach(initial, "conn_1"))
|
||||
expect(BrowserMachine.isAwaited(attaching.state, sessionID)).toBe(true)
|
||||
const waited = BrowserMachine.transitionConnection(attaching.state, { type: "step.timed-out", sessionID })
|
||||
expect(waited.state).toBe(attaching.state)
|
||||
expect(waited.effects).toEqual([])
|
||||
})
|
||||
|
||||
test("the sessions an earlier instance left expected start expected, and stay stored when this one goes away", () => {
|
||||
const initial = BrowserMachine.createConnectionState([sessionID])
|
||||
expect(BrowserMachine.isAwaited(initial, sessionID)).toBe(true)
|
||||
expect(BrowserMachine.isAwaited(initial, other)).toBe(false)
|
||||
|
||||
const disposed = run(initial, { type: "disposed" })
|
||||
expect(disposed.effects).toEqual([{ type: "notify-settled", sessionID }, { type: "notify-drained" }])
|
||||
})
|
||||
})
|
||||
|
||||
describe("disposal", () => {
|
||||
test("an idle plugin drains at once", () => {
|
||||
const next = run(BrowserMachine.createConnectionState(), { type: "disposed" })
|
||||
|
|
@ -486,9 +567,10 @@ describe("disposal", () => {
|
|||
expect(BrowserMachine.selectTarget(disposed.state, sessionID, { type: "tabs.list" }).ok).toBe(false)
|
||||
expect(BrowserMachine.selectAttachment(disposed.state, sessionID, "conn_1")).toBeUndefined()
|
||||
|
||||
// The desktop was attached when the plugin went away, so the next instance expects it for the session.
|
||||
const revoke = lastSync(disposed.effects)
|
||||
const firstDone = run(disposed.state, synced(revoke.attempt))
|
||||
expect(firstDone.effects).toEqual([])
|
||||
expect(firstDone.effects).toEqual([{ type: "record-expectation", sessionID }])
|
||||
|
||||
// The other session's grant was still in flight; it is revoked before the plugin drains.
|
||||
const otherSettled = run(firstDone.state, synced(otherGrant.attempt, other))
|
||||
|
|
|
|||
|
|
@ -146,6 +146,18 @@ restart recovery and the hook keeps running. Persist your own state if the loop
|
|||
fails, fails the execution like any other session hook, so handle errors from slow or remote work such as a judge model
|
||||
call.
|
||||
|
||||
Before a Session selects the agent, tools and instructions of a step, the `experimental.step.before` hook runs, and
|
||||
again before each retry of that step. It is experimental: its name and shape may still change. State the hook settles
|
||||
first decides what the step lists, such as Session permissions a client is about to grant. The step waits for the hook,
|
||||
so bound any wait on something outside the server, and return at once when there is nothing to wait for:
|
||||
|
||||
```ts
|
||||
await ctx.session.hook("experimental.step.before", async (event) => {
|
||||
// `attached` is your own promise for a client that is connecting to this Session.
|
||||
await Promise.race([attached(event.sessionID), new Promise((resolve) => setTimeout(resolve, 2_000))])
|
||||
})
|
||||
```
|
||||
|
||||
Promise tools use complete executable tool values with async executors:
|
||||
|
||||
```ts
|
||||
|
|
|
|||
|
|
@ -152,6 +152,19 @@ restart recovery and the hook keeps running. Persist your own state if the loop
|
|||
fails, fails the execution like any other session hook, so handle errors from slow or remote work such as a judge model
|
||||
call.
|
||||
|
||||
Before a Session selects the agent, tools and instructions of a step, the `experimental.step.before` hook runs, and
|
||||
again before each retry of that step. It is experimental: its name and shape may still change. State the hook settles
|
||||
first decides what the step lists, such as Session permissions a client is about to grant. The step waits for the hook,
|
||||
so bound any wait on something outside the server, and return at once when there is nothing to wait for:
|
||||
|
||||
```ts
|
||||
yield *
|
||||
ctx.session.hook("experimental.step.before", (event) =>
|
||||
// `attached` is your own effect for a client that is connecting to this Session.
|
||||
attached(event.sessionID).pipe(Effect.timeoutOption("2 seconds"), Effect.asVoid),
|
||||
)
|
||||
```
|
||||
|
||||
## Reloading A Domain
|
||||
|
||||
When data captured by a transform changes, reload the affected domain:
|
||||
|
|
|
|||
|
|
@ -204,6 +204,15 @@ export interface SessionIdle {
|
|||
readonly background: ReadonlyArray<SessionIdleBackground>
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs before a Session selects the agent, tools and instructions of a step, and again before each retry of that step.
|
||||
* State the hook settles first, such as Session permissions a client is about to grant, decides what the step lists.
|
||||
* The step waits for the hook, so a hook that waits on anything outside the server must bound that wait. Experimental.
|
||||
*/
|
||||
export interface SessionStepBefore {
|
||||
readonly sessionID: Session.ID
|
||||
}
|
||||
|
||||
export interface SessionHooks {
|
||||
readonly fork: { readonly sessionID: Session.ID }
|
||||
readonly prompt: SessionPrompt
|
||||
|
|
@ -220,6 +229,7 @@ export interface SessionHooks {
|
|||
readonly "experimental.ws.receive": SessionWebSocketReceive
|
||||
readonly retry: SessionRetry
|
||||
readonly "experimental.idle": SessionIdle
|
||||
readonly "experimental.step.before": SessionStepBefore
|
||||
}
|
||||
|
||||
export type SessionDomain = Pick<
|
||||
|
|
|
|||
|
|
@ -204,6 +204,15 @@ export interface SessionIdle {
|
|||
readonly background: ReadonlyArray<SessionIdleBackground>
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs before a Session selects the agent, tools and instructions of a step, and again before each retry of that step.
|
||||
* State the hook settles first, such as Session permissions a client is about to grant, decides what the step lists.
|
||||
* The step waits for the hook, so a hook that waits on anything outside the server must bound that wait. Experimental.
|
||||
*/
|
||||
export interface SessionStepBefore {
|
||||
readonly sessionID: Session.ID
|
||||
}
|
||||
|
||||
export interface SessionHooks {
|
||||
readonly fork: { readonly sessionID: Session.ID }
|
||||
readonly prompt: SessionPrompt
|
||||
|
|
@ -220,6 +229,7 @@ export interface SessionHooks {
|
|||
readonly "experimental.ws.receive": SessionWebSocketReceive
|
||||
readonly retry: SessionRetry
|
||||
readonly "experimental.idle": SessionIdle
|
||||
readonly "experimental.step.before": SessionStepBefore
|
||||
}
|
||||
|
||||
export type SessionDomain = Pick<
|
||||
|
|
|
|||
|
|
@ -1379,7 +1379,7 @@ so later hooks see changes made by earlier hooks.
|
|||
|
||||
### Sessions
|
||||
|
||||
Session hooks intercept prompt admission, model calls, native HTTP, and retries.
|
||||
Session hooks intercept prompt admission, step selection, model calls, native HTTP, and retries.
|
||||
|
||||
#### Forks
|
||||
|
||||
|
|
@ -1431,6 +1431,25 @@ Keep prompt hooks retry-safe. They are not an exactly-once side-effect boundary:
|
|||
- Concurrent submissions can run hooks more than once, but only the first successful admission wins.
|
||||
- Prompt hooks transform input and do not expose a typed rejection API.
|
||||
|
||||
#### Before a step
|
||||
|
||||
Experimental. Runs before a session selects the agent, tools, and instructions of a step, and again before each retry
|
||||
of that step. State the hook settles first decides what the step lists, such as session permissions a client is about
|
||||
to grant.
|
||||
|
||||
```ts
|
||||
await ctx.session.hook("experimental.step.before", async ({ sessionID }) => {
|
||||
// `attached` is your own promise for a client that is connecting to this session.
|
||||
await Promise.race([attached(sessionID), new Promise((resolve) => setTimeout(resolve, 2_000))])
|
||||
})
|
||||
```
|
||||
|
||||
The step waits for the hook, so follow these rules:
|
||||
|
||||
- Bound every wait on something outside the server, as the example does.
|
||||
- Return at once when there is nothing to wait for. The hook runs for every step of every session.
|
||||
- The hook cannot add tools or edit the request. Use `context` for that.
|
||||
|
||||
#### Model requests
|
||||
|
||||
Modify assembled system instructions, messages, tools, or request options immediately before model dispatch. Each
|
||||
|
|
@ -1651,6 +1670,11 @@ interface SessionHooks {
|
|||
"experimental.ws.send": SessionWebSocketSendHook
|
||||
"experimental.ws.receive": SessionWebSocketReceiveHook
|
||||
retry: SessionRetryHook
|
||||
"experimental.step.before": SessionStepBeforeHook
|
||||
}
|
||||
|
||||
interface SessionStepBeforeHook {
|
||||
readonly sessionID: string
|
||||
}
|
||||
|
||||
interface SessionModelResolveHook {
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue