diff --git a/packages/app/src/components-lab/dialog-story-runtime.tsx b/packages/app/src/components-lab/dialog-story-runtime.tsx index 23b0a41d06e..e4e4c887234 100644 --- a/packages/app/src/components-lab/dialog-story-runtime.tsx +++ b/packages/app/src/components-lab/dialog-story-runtime.tsx @@ -5,8 +5,7 @@ import { LocalProvider } from "@/providers/models/selection" import { ModelsProvider } from "@/providers/models/models" import { PlatformProvider, type Platform } from "@/runtime/platform/platform" import { PluginRoot } from "@/runtime/plugin/root" -import { ServerProvider } from "@/runtime/server/current" -import { GlobalProvider } from "@/runtime/server/runtime" +import { ServerProvider, GlobalProvider } from "@/runtime/server/runtime" import { ServerConnection, ServersProvider } from "@/runtime/server/registry" import { SettingsProvider } from "@/settings/model" import { CommandProvider } from "@/shell/commands/command" diff --git a/packages/app/src/components-lab/lab.tsx b/packages/app/src/components-lab/lab.tsx index 811acb7d937..46ac00843e5 100644 --- a/packages/app/src/components-lab/lab.tsx +++ b/packages/app/src/components-lab/lab.tsx @@ -4,10 +4,10 @@ import { CommentsProvider } from "@/composer/comments" import { ComposerPersistenceProvider } from "@/composer/persistence" import { ModelsProvider } from "@/providers/models/models" import { Contribution } from "@/runtime/plugin/render" -import { ServerProvider, useServer } from "@/runtime/server/current" +import { useServer } from "@/runtime/server/current" +import { ServerProvider, useGlobal } from "@/runtime/server/runtime" import { ServerConnection, useServers } from "@/runtime/server/registry" import { isServerHealthy } from "@/runtime/server/health-machine" -import { useGlobal } from "@/runtime/server/runtime" import { SessionUIProvider } from "@/shell/routes/session-ui-provider" import { FileProvider } from "@/workspaces/files/model" import { LocationProvider } from "@/workspaces/location" diff --git a/packages/app/src/new-session/route.tsx b/packages/app/src/new-session/route.tsx index 3f49c80c1da..9475cd91680 100644 --- a/packages/app/src/new-session/route.tsx +++ b/packages/app/src/new-session/route.tsx @@ -2,11 +2,11 @@ import { Navigate, useSearchParams } from "@solidjs/router" import { createMemo, ErrorBoundary, Show, type ParentProps } from "solid-js" import { CommentsProvider } from "@/composer/comments" import { FileProvider } from "@/workspaces/files/model" -import { useGlobal } from "@/runtime/server/runtime" +import { useGlobal, ServerProvider } from "@/runtime/server/runtime" import { LocationProvider } from "@/workspaces/location" import { ModelsProvider } from "@/providers/models/models" import { ComposerPersistenceProvider } from "@/composer/persistence" -import { ServerProvider, useServer } from "@/runtime/server/current" +import { useServer } from "@/runtime/server/current" import { ServerConnection } from "@/runtime/server/registry" import { isServerIncompatible } from "@/runtime/server/health-machine" import { useTabs, type DraftTab } from "@/shell/tabs/tabs" diff --git a/packages/app/src/runtime/server/current.tsx b/packages/app/src/runtime/server/current.tsx index 2abfbffa387..dd47b711cf6 100644 --- a/packages/app/src/runtime/server/current.tsx +++ b/packages/app/src/runtime/server/current.tsx @@ -1,16 +1,16 @@ -import { Show, type JSX, type ParentProps } from "solid-js" import { createSimpleContext } from "@opencode/ui/context" import { ServerConnection } from "./registry" -import { useGlobal, type ServerCtx } from "./runtime" +import type { ServerHealth } from "./health-machine" +import type { ServerCtx } from "./runtime" +// Takes the server's health as a prop rather than reading `useGlobal`, so this module doesn't import `./runtime`, +// which imports modules that call `useServer`. `ServerProvider` in `./runtime` provides it. const context = createSimpleContext({ name: "Server", - init: (props: { conn: ServerConnection.Any; ctx: ServerCtx }) => { + init: (props: { conn: ServerConnection.Any; ctx: ServerCtx; health: ServerHealth | undefined }) => { const conn = props.conn const key = ServerConnection.key(conn) - const global = useGlobal() - return { conn, key, @@ -19,7 +19,7 @@ const context = createSimpleContext({ }, ctx: props.ctx, get health() { - return global.servers.health[key] + return props.health }, } }, @@ -27,26 +27,7 @@ const context = createSimpleContext({ export const useServer = context.use -// Keyed by controller: while the server rejects our credentials the children unmount and `signedOut` shows instead, -// and they mount again with the controller its new credentials start. -export function ServerProvider(props: ParentProps<{ conn: ServerConnection.Any; signedOut?: JSX.Element }>) { - const global = useGlobal() - const key = ServerConnection.key(props.conn) - - return ( - {props.signedOut}} - > - {(ctx) => ( - - {props.children} - - )} - - ) -} +export const ServerContextProvider = context.provider export const useData = () => { const server = useServer() diff --git a/packages/app/src/runtime/server/runtime.tsx b/packages/app/src/runtime/server/runtime.tsx index 832a67739b5..ef578ed9f75 100644 --- a/packages/app/src/runtime/server/runtime.tsx +++ b/packages/app/src/runtime/server/runtime.tsx @@ -11,6 +11,9 @@ import { getOwner, onCleanup, untrack, + Show, + type JSX, + type ParentProps, } from "solid-js" import { createServerProjects, ServerConnection, useServers } from "./registry" import { @@ -25,6 +28,7 @@ import { pathKey } from "@/workspaces/path-key" import { useServerHealth } from "@/runtime/server/health" import { selectServerHostname } from "@/runtime/server/health-machine" import { createServerSdkContext } from "./client" +import { ServerContextProvider } from "./current" import { createServerSyncContext } from "./sync" import { createData, createSessionRetention } from "@opencode/client/solid" import type { ServerScope } from "@/runtime/server/scope" @@ -393,4 +397,25 @@ export function useServerCtx(server: Accessor) } } +// Keyed by controller: while the server rejects our credentials the children unmount and `signedOut` shows instead, +// and they mount again with the controller its new credentials start. +export function ServerProvider(props: ParentProps<{ conn: ServerConnection.Any; signedOut?: JSX.Element }>) { + const global = useGlobal() + const key = ServerConnection.key(props.conn) + + return ( + {props.signedOut}} + > + {(ctx) => ( + + {props.children} + + )} + + ) +} + export type ServerCtx = ReturnType diff --git a/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx b/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx index fa2210efa29..846ccd62123 100644 --- a/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx +++ b/packages/app/src/session/server-unavailable-panel.standalone.stories.tsx @@ -1,7 +1,7 @@ import { Button } from "@opencode/ui/button" import { createSignal, Show } from "solid-js" import { DialogStoryRuntime, STORY_LOCKED_SERVER, STORY_SERVER } from "@/components-lab/dialog-story-runtime" -import { ServerProvider } from "@/runtime/server/current" +import { ServerProvider } from "@/runtime/server/runtime" import type { ServerConnection } from "@/runtime/server/registry" import { ServerSignedOutPanel, ServerUnavailablePanel } from "./server-unavailable-panel" diff --git a/packages/app/src/settings/server-scope.tsx b/packages/app/src/settings/server-scope.tsx index 1db9c94ed6f..24a58ab62e2 100644 --- a/packages/app/src/settings/server-scope.tsx +++ b/packages/app/src/settings/server-scope.tsx @@ -1,6 +1,6 @@ import { type ParentProps } from "solid-js" import { ModelsProvider } from "@/providers/models/models" -import { ServerProvider } from "@/runtime/server/current" +import { ServerProvider } from "@/runtime/server/runtime" import { ServerConnection } from "@/runtime/server/registry" export function SettingsServerDataScope(props: ParentProps<{ server: ServerConnection.Any; directory?: string }>) { diff --git a/packages/app/src/shell/routes/routes.tsx b/packages/app/src/shell/routes/routes.tsx index 7303f5d26e5..ed71293481b 100644 --- a/packages/app/src/shell/routes/routes.tsx +++ b/packages/app/src/shell/routes/routes.tsx @@ -1,8 +1,7 @@ import { Route, useParams } from "@solidjs/router" import { createMemo, lazy, Show, Suspense, type ParentProps } from "solid-js" import { Home } from "@/home/route" -import { ServerProvider } from "@/runtime/server/current" -import { useGlobal } from "@/runtime/server/runtime" +import { ServerProvider, useGlobal } from "@/runtime/server/runtime" import { ServerConnection, useServers } from "@/runtime/server/registry" import { isServerUnauthorized } from "@/runtime/server/health-machine" import { SessionPanelFrame, SessionRouteFrame } from "@/session/session-frame" diff --git a/packages/app/src/workspaces/selection/picker.tsx b/packages/app/src/workspaces/selection/picker.tsx index 19683259c68..8715d9debf5 100644 --- a/packages/app/src/workspaces/selection/picker.tsx +++ b/packages/app/src/workspaces/selection/picker.tsx @@ -1,7 +1,7 @@ import { useDialog } from "@opencode/ui/context/dialog" import { uuid } from "@opencode/util/uuid" import { ServerConnection, useServers } from "@/runtime/server/registry" -import { ServerProvider } from "@/runtime/server/current" +import { ServerProvider } from "@/runtime/server/runtime" import { useGlobal } from "@/runtime/server/runtime" import { usePlatform } from "@/runtime/platform/platform" import { createEffect, lazy, Suspense } from "solid-js" diff --git a/packages/codemode/src/async.ts b/packages/codemode/src/async.ts index 3eae192d5be..08eb8763b8a 100644 --- a/packages/codemode/src/async.ts +++ b/packages/codemode/src/async.ts @@ -22,7 +22,8 @@ import { abrupt, type Completion, Interruption, Invoke, MAX_CALL_DEPTH, normal } import { type Combination, type Job, type Reaction, Resolving } from "./scheduler.js" import { internalCode, VmIntrinsic } from "./internal-prelude.js" import { CodeFlags } from "./opcodes.js" -import { type Frame, type FrameMode, Mode, type Vm } from "./vm.js" +import { type Frame, type FrameMode, Mode } from "./frame.js" +import type { Vm } from "./vm.js" export type SettlingTarget = { resolve(value: Value): void diff --git a/packages/codemode/src/frame.ts b/packages/codemode/src/frame.ts new file mode 100644 index 00000000000..bf0025043e7 --- /dev/null +++ b/packages/codemode/src/frame.ts @@ -0,0 +1,59 @@ +import type { Code } from "./code.js" +import { type Cell, EMPTY_CELLS } from "./opcodes.js" +import type { AstNode } from "./runtime/model.js" +import type { Fn, Obj, Value } from "./runtime/objects.js" + +// The VM's activation records and the small classes its helper modules share, apart from `vm.ts` so `async.ts`, +// `generators.ts`, `host.ts`, `internal-prelude.ts` and `snapshot.ts` can use them without importing the VM. + +export const Mode = { + CALLER: 0, + ASYNC: 1, + GENERATOR: 2, + SETTLE: 3, + REJECT_ONLY: 4, + PROGRAM: 5, + BOUNDARY_OUT: 6, +} as const + +export type FrameMode = (typeof Mode)[keyof typeof Mode] + +/** Custom synchronous/async iterator state stored in a frame's hidden `%it` slot. */ +export class CustomIter { + done = false + rawGen = false + constructor( + readonly iterator: Obj, + readonly next: Value, + ) {} +} + +/** Single uniform activation record for the bytecode VM. */ +export class Frame { + fn: Fn | null = null + cells: ReadonlyArray = EMPTY_CELLS + code: Code + pc = 0 + sp = 0 + regs: Array + thisValue: Value = undefined + args: Array | undefined = undefined + mode: FrameMode = Mode.CALLER + target: unknown = undefined + answer: unknown = undefined + origin: AstNode | undefined = undefined + counted = false + + constructor(code: Code, regs: Array) { + this.code = code + this.regs = regs + } +} + +/** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */ +export class VmInternalFn { + constructor( + readonly code: Code, + readonly boundArgs?: ReadonlyArray, + ) {} +} diff --git a/packages/codemode/src/generators.ts b/packages/codemode/src/generators.ts index cfb49e430f7..9e4d5a48e1d 100644 --- a/packages/codemode/src/generators.ts +++ b/packages/codemode/src/generators.ts @@ -12,12 +12,12 @@ import { type Value, } from "./runtime/objects.js" import { readProperty, requireIteratorMethod, requireIteratorObject } from "./runtime/operations.js" -import { capability } from "./runtime/promises.js" import { abrupt, type Completion, type GeneratorRequest, Interruption, normal, Resume } from "./runtime/signals.js" import type { Reaction, Resolving } from "./scheduler.js" import { internalCode, VmIntrinsic } from "./internal-prelude.js" import { CodeFlags, Op } from "./opcodes.js" -import { CustomIter, type Frame, Mode, type Vm } from "./vm.js" +import { CustomIter, type Frame, Mode } from "./frame.js" +import type { Vm } from "./vm.js" /** * CreateAsyncFromSyncIterator's object: an async iterator over a synchronous one, for `for await` and an async @@ -413,7 +413,7 @@ export const handleAdapterPush = (vm: Vm, callerFrame: Frame, slots: Array const site = adapter.site - const made = capability(vm.ctx, site) + const made = vm.scheduler.resolving(vm.scheduler.newPromise(), site) const sync = adapter.sync if (sync instanceof Position) { if (kind === "next") { diff --git a/packages/codemode/src/host.ts b/packages/codemode/src/host.ts index 7ddad97120a..a237db25166 100644 --- a/packages/codemode/src/host.ts +++ b/packages/codemode/src/host.ts @@ -10,7 +10,8 @@ import { type ExtensionRequest, HostCall, type HostRequest, Resolving } from "./ import type { ExtensionInvocation } from "./tool-runtime.js" import type { Code } from "./code.js" import { internalCode, tryFastBoundaryOrJson, VmIntrinsic } from "./internal-prelude.js" -import { type FrameMode, Mode, type Vm } from "./vm.js" +import { type FrameMode, Mode } from "./frame.js" +import type { Vm } from "./vm.js" // The VM's side of host work (plan §4.10): tool calls, `search`, and extension calls, the host calls they queue, and // the blocking call a job may wait on. diff --git a/packages/codemode/src/internal-prelude.ts b/packages/codemode/src/internal-prelude.ts index 305fc669d95..96e94d96838 100644 --- a/packages/codemode/src/internal-prelude.ts +++ b/packages/codemode/src/internal-prelude.ts @@ -28,7 +28,8 @@ import { Convert } from "./runtime/signals.js" import type { Code } from "./code.js" import { builtinCodes } from "./prelude/bytecode.js" import { UnaryOp } from "./opcodes.js" -import { type Vm, VmInternalFn } from "./vm.js" +import { VmInternalFn } from "./frame.js" +import type { Vm } from "./vm.js" /** * Lightweight internal callable for VM-only `$` intrinsics. Does not extend `Obj` or `Native`, diff --git a/packages/codemode/src/runtime/execute.ts b/packages/codemode/src/runtime/execute.ts index 20bb53d9262..a2d3011528d 100644 --- a/packages/codemode/src/runtime/execute.ts +++ b/packages/codemode/src/runtime/execute.ts @@ -2,6 +2,7 @@ import { parse, type Program } from "acorn" import { Cause, Deferred, Effect, Option, Schema } from "effect" import type { DataValue, Diagnostic, Outcome, ResolvedExecutionLimits, Result, Suspended } from "../codemode.js" import { fromBytes, header, type Snapshot, SnapshotError, toBytes } from "../snapshot/snapshot.js" +import { captureVm, restoreVm } from "../snapshot.js" import { ToolRuntime } from "../tool-runtime.js" import { normalizeError } from "./errors.js" import { createBuiltins } from "./intrinsics.js" @@ -106,7 +107,7 @@ export const resumeProgram = ( const restoredSources = new Map() const restoreInto = (saved: unknown, vm: Vm): Snapshot => - vm.restore(saved, { + restoreVm(vm, saved, { parse: (code) => { const known = restoredSources.get(code) if (known !== undefined) return known @@ -311,7 +312,7 @@ export class Running { } const limits = this.setup.limits const saved = attempt(() => - vm.capture({ + captureVm(vm, { limits: { timeoutMs: limits.timeoutMs ?? null, maxToolCalls: limits.maxToolCalls ?? null, @@ -358,7 +359,7 @@ export class Running { } if (driver.holdsHostValues) return this.trips++ - const attempted = attempt(() => this.ctx.vm.capture({ strict: !this.setup.lossy })) + const attempted = attempt(() => captureVm(this.ctx.vm, { strict: !this.setup.lossy })) // An extension's `snapshot` hooks may refuse to save a value, which fails a suspend, not the run. if (!attempted.ok) { const error = attempted.error diff --git a/packages/codemode/src/runtime/objects.ts b/packages/codemode/src/runtime/objects.ts index ad09b37256b..7901c02b94c 100644 --- a/packages/codemode/src/runtime/objects.ts +++ b/packages/codemode/src/runtime/objects.ts @@ -14,7 +14,7 @@ import { type Convert, type GeneratorRequest, Invoke, type Push, type Resume } f import type { Code } from "../code.js" import { type Cell, CodeFlags } from "../opcodes.js" import type { Reaction, Resolving } from "../scheduler.js" -import type { Frame } from "../vm.js" +import type { Frame } from "../frame.js" import { OrderedTable, type TableCursor } from "./table.js" /** Property attributes, as in a JS property descriptor. */ diff --git a/packages/codemode/src/scheduler.ts b/packages/codemode/src/scheduler.ts index 3d372013db8..bdec7ac08e8 100644 --- a/packages/codemode/src/scheduler.ts +++ b/packages/codemode/src/scheduler.ts @@ -4,7 +4,7 @@ import { locate } from "./runtime/errors.js" import type { AstNode } from "./runtime/model.js" import type { Callable, Cursor, GeneratorObj, Obj, PromiseObj, Value } from "./runtime/objects.js" import type { Completion } from "./runtime/signals.js" -import type { Frame } from "./vm.js" +import type { Frame } from "./frame.js" // The scheduler's records: jobs, reactions, resolvers, and host calls. All of them are data the VM keeps, so a run's // queue and the work it waits on can be read (and saved) between `run()`s. diff --git a/packages/codemode/src/snapshot.ts b/packages/codemode/src/snapshot.ts index cc8c5b7835e..841b38b96fb 100644 --- a/packages/codemode/src/snapshot.ts +++ b/packages/codemode/src/snapshot.ts @@ -12,7 +12,10 @@ import { HostCalls } from "./host.js" import { getInternalPrelude } from "./internal-prelude.js" import { compiledPrelude } from "./prelude/prelude.js" import { Cell, CodeFlags, EMPTY_CELLS, HOLE, Op } from "./opcodes.js" -import { CustomIter, Frame, Mode, Vm, VmInternalFn } from "./vm.js" +import { CustomIter, Frame, Mode, VmInternalFn } from "./frame.js" +import { AsyncFromSyncIterator } from "./generators.js" +import { Interpreter } from "./runtime/interpreter.js" +import { Vm } from "./vm.js" // Snapshots of the bytecode VM (plan §6): the generic graph codec, plus records for the VM's own classes. // @@ -40,7 +43,6 @@ export type RestoreOptions = { let specs: ReadonlyArray | undefined -// Built on first use: this module and vm.ts import each other, so the classes aren't there at load time. const vmSpecs = (): ReadonlyArray => (specs ??= [ { @@ -99,6 +101,20 @@ const vmSpecs = (): ReadonlyArray => { name: "AsyncFromSyncCloseTarget", ctor: AsyncFromSyncCloseTarget, fields: ["made", "reason"] }, { name: "Cell", ctor: Cell, fields: ["v"] }, { name: "CustomIter", ctor: CustomIter, fields: ["done", "rawGen", "iterator", "next"] }, + { + name: "AsyncFromSyncIterator", + ctor: AsyncFromSyncIterator, + fields: ["sync", "site"], + obj: true, + constants: { tag: "AsyncFromSyncIterator" }, + }, + { + name: "Interpreter", + ctor: Interpreter, + anchor: "ctx", + fields: ["logs", "globalScope", "modules", "namespaces"], + skip: ["tools", "builtins", "vm", "intrinsics", "extensionWork", "hosts", "sources", "prelude"], + }, ]) let build: string | undefined @@ -127,6 +143,7 @@ export const captureVm = ( vm: Vm, options: CaptureOptions, ): { readonly snapshot: Snapshot; readonly lost: ReadonlyArray } => { + vm.ensureIntrinsics() vm.compact() const ctx = vm.ctx const lost: Array = [] @@ -183,6 +200,7 @@ export const captureVm = ( * after checking the snapshot belongs to this build, these host globals, its own sources and their bytecode. */ export const restoreVm = (vm: Vm, saved: unknown, options: RestoreOptions): Snapshot => { + vm.ensureIntrinsics() const snapshot = validate(saved) const header = snapshot.header const ctx = vm.ctx diff --git a/packages/codemode/src/snapshot/codec.ts b/packages/codemode/src/snapshot/codec.ts index 1af62f67aa9..c3090af834b 100644 --- a/packages/codemode/src/snapshot/codec.ts +++ b/packages/codemode/src/snapshot/codec.ts @@ -1,4 +1,3 @@ -import { Interpreter } from "../runtime/interpreter.js" import { type AstNode, AsyncIteratorSymbol, @@ -36,7 +35,6 @@ import { } from "../runtime/objects.js" import { Convert, Interruption, Invoke } from "../runtime/signals.js" import { deleted, OrderedTable } from "../runtime/table.js" -import { AsyncFromSyncIterator } from "../generators.js" import { HostCall, Resolving } from "../scheduler.js" import { BufferObj } from "../stdlib/buffer.js" import { TextDecoderObj } from "../stdlib/bytes.js" @@ -111,7 +109,7 @@ export type EncodeEnv = { readonly lost: Array readonly strict: boolean readonly hosts?: HostBridge | undefined - /** More classes to save (the VM's frames and closures), after the built-in ones. */ + /** More classes to save (the VM's own state, its frames and closures, the interpreter), after the built-in ones. */ readonly specs?: ReadonlyArray | undefined /** The data the VM names an object or symbol by, saved as `["x", data]`, instead of copying it. */ readonly external?: ((value: object | symbol) => Json | undefined) | undefined @@ -163,7 +161,6 @@ export type ClassSpec = { const objFields = ["props", "extensible", "proto", "intrinsic"] const callable = { tag: "Function" } -// Built on first use: the VM's modules and this one import each other, so the classes aren't there at load time. const builtinSpecs = (): ReadonlyArray => [ { name: "Obj", ctor: Obj, fields: [], obj: true, constants: { tag: "Object" } }, { name: "Arr", ctor: Arr, fields: ["items", "elements"], obj: true, constants: { tag: "Array" } }, @@ -234,13 +231,6 @@ const builtinSpecs = (): ReadonlyArray => [ obj: true, constants: { tag: "Object" }, }, - { - name: "AsyncFromSyncIterator", - ctor: AsyncFromSyncIterator, - fields: ["sync", "site"], - obj: true, - constants: { tag: "AsyncFromSyncIterator" }, - }, { name: "Position", ctor: Position, fields: ["index", "done", "source", "kind", "arrays"] }, { name: "OrderedTable", @@ -267,13 +257,6 @@ const builtinSpecs = (): ReadonlyArray => [ { name: "Invoke", ctor: Invoke, fields: ["callable", "thisValue", "args", "site"] }, { name: "ToolReference", ctor: ToolReference, fields: ["path"] }, { name: "Lost", ctor: Lost, fields: ["description"] }, - { - name: "Interpreter", - ctor: Interpreter, - anchor: "ctx", - fields: ["logs", "globalScope", "modules", "namespaces"], - skip: ["tools", "builtins", "vm", "intrinsics", "extensionWork", "hosts", "sources", "prelude"], - }, ] let builtins: { readonly byCtor: Map; readonly byName: Map } | undefined diff --git a/packages/codemode/src/vm.ts b/packages/codemode/src/vm.ts index fc6003ed8d1..36636195e22 100644 --- a/packages/codemode/src/vm.ts +++ b/packages/codemode/src/vm.ts @@ -84,7 +84,6 @@ import { enumerableSource } from "./stdlib/object.js" import { ToolReference } from "./tool-runtime.js" import { registerAsyncIntrinsics, type SettlingTarget, VmScheduler } from "./async.js" import type { Code } from "./code.js" -import { type CaptureOptions, captureVm, type RestoreOptions, restoreVm } from "./snapshot.js" import { compileSource } from "./compiler/compile.js" import { AsyncFromSyncIterator, @@ -139,6 +138,7 @@ import { UnaryOp, } from "./opcodes.js" import { hidden } from "./runtime/objects.js" +import { CustomIter, Frame, type FrameMode, Mode, VmInternalFn } from "./frame.js" const contiguous = (): Array => { const a: Array = [""] @@ -154,50 +154,6 @@ const INITIAL_FUEL = 10_000 const NATIVE_FUEL = 50 const SLICE_MS = 1 -export const Mode = { - CALLER: 0, - ASYNC: 1, - GENERATOR: 2, - SETTLE: 3, - REJECT_ONLY: 4, - PROGRAM: 5, - BOUNDARY_OUT: 6, -} as const - -export type FrameMode = (typeof Mode)[keyof typeof Mode] - -/** Custom synchronous/async iterator state stored in a frame's hidden `%it` slot. */ -export class CustomIter { - done = false - rawGen = false - constructor( - readonly iterator: Obj, - readonly next: Value, - ) {} -} - -/** Single uniform activation record for the bytecode VM. */ -export class Frame { - fn: Fn | null = null - cells: ReadonlyArray = EMPTY_CELLS - code: Code - pc = 0 - sp = 0 - regs: Array - thisValue: Value = undefined - args: Array | undefined = undefined - mode: FrameMode = Mode.CALLER - target: unknown = undefined - answer: unknown = undefined - origin: AstNode | undefined = undefined - counted = false - - constructor(code: Code, regs: Array) { - this.code = code - this.regs = regs - } -} - const EXEC_DONE = 0 const EXEC_FUEL = 1 @@ -207,19 +163,11 @@ const allocRegs = (size: number): Array => { return regs } -/** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */ -export class VmInternalFn { - constructor( - readonly code: Code, - readonly boundArgs?: ReadonlyArray, - ) {} -} - /** * Runs a runtime's program code: the job stack, the job queue, promises, and host calls. `execute.ts` and the driver * use only its host surface: * - * - **Starting.** Exactly one of `start(source)` (a new run) or `restore(saved, …)` (a saved one), once. Host call + * - **Starting.** Exactly one of `start(source)` (a new run) or `restoreVm(vm, saved, …)` (a saved one, `snapshot.ts`), once. Host call * ids count up in program order. * - **Running.** `run()` is synchronous, runs no host work, and returns a `Stop`: * - `host(calls)`: start these queued calls now (they are `queued`; the driver marks them `running`), @@ -233,7 +181,7 @@ export class VmInternalFn { * blocking call's outcome continues the job that made it; a concurrent call's waits in the inbox and settles its * promise in a later job, in completion order. Unknown or completed ids are ignored. `call(id)`/`calls()` list the * calls handed over and not completed, in the order they were made. - * - **Snapshots.** `capture` and `restore` run only between `run()`s, synchronously. A capture changes nothing a + * - **Snapshots.** `captureVm` and `restoreVm` (`snapshot.ts`) run only between `run()`s, synchronously. A capture changes nothing a * later `run()` sees; it fails (throws) only on a codec gap. A state holding live host values (`calls()` with an * extension call, or `activeExtension`) can't be restored faithfully. */ @@ -271,7 +219,9 @@ export class Vm { } } - private initIntrinsics(): void { + /** Registers the VM's internal callables, once: running, capturing and restoring all need them. */ + ensureIntrinsics(): void { + if (this.intrinsics.size > 0) return registerVmIntrinsics(this.intrinsics, this) registerAsyncIntrinsics(this.intrinsics, this) registerGeneratorIntrinsics(this.intrinsics, this) @@ -281,7 +231,7 @@ export class Vm { private getIntrinsic(name: string): unknown { const p = this.ctx.prelude.scope.get(name) if (p !== undefined) return p - if (this.intrinsics.size === 0) this.initIntrinsics() + this.ensureIntrinsics() return this.intrinsics.get(name) } @@ -434,18 +384,6 @@ export class Vm { return this.hosts.extension } - /** Saves the run's state as it is now. */ - capture(options: CaptureOptions) { - if (this.intrinsics.size === 0) this.initIntrinsics() - return captureVm(this, options) - } - - /** Restores a saved state into this fresh VM, after checking it belongs to this build and runtime. */ - restore(saved: unknown, options: RestoreOptions) { - if (this.intrinsics.size === 0) this.initIntrinsics() - return restoreVm(this, saved, options) - } - deliverAnswer(frame: Frame): void { if (frame.answer !== undefined) { const answer = frame.answer as Value diff --git a/packages/codemode/test/bytecode-limits.test.ts b/packages/codemode/test/bytecode-limits.test.ts index 7834457af05..5b6b15aa9a3 100644 --- a/packages/codemode/test/bytecode-limits.test.ts +++ b/packages/codemode/test/bytecode-limits.test.ts @@ -5,7 +5,7 @@ import type { ToolRuntime } from "../src/tool-runtime.js" import { CodeBuilder, CodeSizeOverflow, hashOf } from "../src/code.js" import { compileSource } from "../src/compiler/compile.js" import { CodeFlags, EMPTY_CELLS, Op, packWord, PutKind } from "../src/opcodes.js" -import { Mode } from "../src/vm.js" +import { Mode } from "../src/frame.js" import { parseVmSource, type RunOptions, runProgram } from "./run-program.js" import { verifyAll, verifyCode } from "./verify-bytecode.js" diff --git a/packages/codemode/test/fixtures/prelude-roundtrip.ts b/packages/codemode/test/fixtures/prelude-roundtrip.ts index e3f52f35f73..3310ab400b0 100644 --- a/packages/codemode/test/fixtures/prelude-roundtrip.ts +++ b/packages/codemode/test/fixtures/prelude-roundtrip.ts @@ -9,10 +9,11 @@ import { Vm } from "../../src/vm.js" setRoundTrip(true) let saved = 0 -const capture = Vm.prototype.capture -Vm.prototype.capture = function (this: Vm, options) { +// `captureVm` compacts the VM first, and nothing else does: counting compactions counts saves. +const compact = Vm.prototype.compact +Vm.prototype.compact = function (this: Vm) { if (this.frames.some((frame) => (frame.code.flags & CodeFlags.INTERNAL) !== 0)) saved++ - return capture.call(this, options) + return compact.call(this) } const result = await Effect.runPromise( CodeMode.execute({ diff --git a/packages/codemode/test/run-program.ts b/packages/codemode/test/run-program.ts index 6277b8d88ca..ff4ab5736d5 100644 --- a/packages/codemode/test/run-program.ts +++ b/packages/codemode/test/run-program.ts @@ -12,6 +12,7 @@ import { Interruption } from "../src/runtime/signals.js" import type { Source } from "../src/runtime/source.js" import type { ToolRuntime } from "../src/tool-runtime.js" import type { Snapshot } from "../src/snapshot/snapshot.js" +import { captureVm, restoreVm } from "../src/snapshot.js" /** A quoted `file:` URL for a module relative to `test`, to import from a script run with `bun -e` on any platform. */ export const moduleUrl = (relative: string) => @@ -79,11 +80,11 @@ export const runProgram = (code: string, options?: RunOptions): Result => { const stop = vm.run() if (stop.kind === "slice") { if (roundTrip !== undefined && vm.tripEvery > 0) { - const { snapshot } = vm.capture({ strict: true }) + const { snapshot } = captureVm(vm, { strict: true }) options?.onTrip?.(snapshot) ctx = runtime(undefined) vm = ctx.vm - vm.restore(JSON.parse(JSON.stringify(snapshot)), { + restoreVm(vm, JSON.parse(JSON.stringify(snapshot)), { parse: (code) => { const again = parseVmSource(code) if (!again.ok) throw new Error(again.error.message) diff --git a/packages/codemode/test/snapshot.test.ts b/packages/codemode/test/snapshot.test.ts index 40cc6f4ee2d..c0eb2ffc8b6 100644 --- a/packages/codemode/test/snapshot.test.ts +++ b/packages/codemode/test/snapshot.test.ts @@ -8,7 +8,7 @@ import { ToolRuntime } from "../src/tool-runtime.js" import { hashOf } from "../src/code.js" import { compileSource } from "../src/compiler/compile.js" import { moduleUrl, parseVmSource, runProgram } from "./run-program.js" -import { buildId } from "../src/snapshot.js" +import { buildId, captureVm, restoreVm } from "../src/snapshot.js" // The VM's snapshots: a run saved and restored into a fresh runtime anywhere it slices goes on as if it never stopped. @@ -153,7 +153,7 @@ const sliced = (code = `let n = 0\nfor (let i = 0; i < 10; i++) { try { n += i } vm.start(parse(code)) vm.tripEvery = 3 expect(vm.run().kind).toBe("slice") - const { snapshot, lost } = vm.capture({ strict: true }) + const { snapshot, lost } = captureVm(vm, { strict: true }) expect(lost).toEqual([]) return JSON.parse(JSON.stringify(snapshot)) as Saved } @@ -168,7 +168,7 @@ const regsOf = (snapshot: ReturnType) => { const refusal = (snapshot: unknown) => { try { - runtime().vm.restore(snapshot, restoreOptions) + restoreVm(runtime().vm, snapshot, restoreOptions) } catch (error) { expect(error).toBeInstanceOf(SnapshotError) return (error as Error).message @@ -190,7 +190,7 @@ describe("snapshots", () => { test("a restored VM runs to the same result", () => { const vm = runtime().vm - vm.restore(sliced(), restoreOptions) + restoreVm(vm, sliced(), restoreOptions) const stop = vm.run() expect(stop).toEqual({ kind: "done", completion: { ok: true, value: 45 } }) }) @@ -204,7 +204,7 @@ describe("snapshots", () => { expect(stop).toEqual({ kind: "done", completion: { ok: true, value: 45 } }) break } - vm.capture({ strict: true }) + captureVm(vm, { strict: true }) } }) @@ -241,7 +241,7 @@ describe("snapshots", () => { ) vm.tripEvery = 1 expect(vm.run().kind).toBe("slice") - const snapshot = JSON.parse(JSON.stringify(vm.capture({ strict: true }).snapshot)) + const snapshot = JSON.parse(JSON.stringify(captureVm(vm, { strict: true }).snapshot)) const regs = regsOf(snapshot) const code = compileSource(parse(snapshot.header.sources[0].code))[0]! expect(regs.length).toBeGreaterThan(code.locals) diff --git a/packages/codemode/test/state.test.ts b/packages/codemode/test/state.test.ts index a085113421b..564afb3e6db 100644 --- a/packages/codemode/test/state.test.ts +++ b/packages/codemode/test/state.test.ts @@ -14,7 +14,8 @@ import { AsyncFromSyncIterator } from "../src/generators.js" import { VmIntrinsic } from "../src/internal-prelude.js" import { Cell, CodeFlags } from "../src/opcodes.js" import type { Stop } from "../src/scheduler.js" -import { CustomIter, Frame, Mode, Vm } from "../src/vm.js" +import { CustomIter, Frame, Mode } from "../src/frame.js" +import { Vm } from "../src/vm.js" // The VM (`src/vm.ts`) runs programs as bytecode frames, and keeps the jobs, promises, and host calls they wait on as // data: a frame is its code, pc, and registers, and every suspension point is one. The Effect driver only does what diff --git a/packages/stories/mocks/app/context/server-current.tsx b/packages/stories/mocks/app/context/server-current.tsx index b28c409c662..7821d8d6663 100644 --- a/packages/stories/mocks/app/context/server-current.tsx +++ b/packages/stories/mocks/app/context/server-current.tsx @@ -1,6 +1,6 @@ -import { createContext, Show, useContext, type ParentProps } from "solid-js" +import { createContext, useContext, type ParentProps } from "solid-js" import { ServerConnection } from "@/runtime/server/registry" -import { useGlobal, type ServerCtx } from "@/runtime/server/runtime" +import type { ServerCtx, useGlobal } from "@/runtime/server/runtime" // Stories render without a connected server by default: no location has synced integrations or usage limits yet. const fallbackData = { @@ -77,33 +77,26 @@ export function useData() { return useServer().ctx.data } -export function ServerProvider(props: ParentProps<{ conn?: ServerConnection.Any }>) { - if (!props.conn) return props.children +// The real `ServerProvider` in `@/runtime/server/runtime` resolves the controller and provides it through this. +export function ServerContextProvider( + props: ParentProps<{ conn: ServerConnection.Any; ctx: ServerCtx; health: ActiveServerValue["health"] }>, +) { const conn = props.conn - - const global = useGlobal() - const key = ServerConnection.key(conn) - const ctx = () => global.serverCtx(key) - return ( - - {(resolved) => ( - - {props.children} - - )} - + + {props.children} + ) }