mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-29 03:24:54 +00:00
refactor: break the app current-server and codemode VM import cycles
App: current.tsx no longer imports runtime.tsx. The Server context takes the server's health as a prop, and ServerProvider, which reads useGlobal, moves to runtime.tsx. Codemode: Mode, Frame, CustomIter and VmInternalFn move to frame.ts so the VM's helper modules import only the Vm type. Snapshots no longer run through Vm: captureVm and restoreVm are called directly, and the Interpreter and AsyncFromSyncIterator codec specs move from the generic codec to snapshot.ts. generators.ts makes its promise capability through the scheduler instead of importing runtime/promises.ts.
This commit is contained in:
parent
1cb0633c8b
commit
fb87e6dd78
26 changed files with 178 additions and 176 deletions
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<Show
|
||||
when={global.serverCtx(key)}
|
||||
keyed
|
||||
fallback={<Show when={global.serverSignedOut(key)}>{props.signedOut}</Show>}
|
||||
>
|
||||
{(ctx) => (
|
||||
<context.provider conn={props.conn} ctx={ctx}>
|
||||
{props.children}
|
||||
</context.provider>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
export const ServerContextProvider = context.provider
|
||||
|
||||
export const useData = () => {
|
||||
const server = useServer()
|
||||
|
|
|
|||
|
|
@ -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<ServerConnection.Any | undefined>)
|
|||
}
|
||||
}
|
||||
|
||||
// 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 (
|
||||
<Show
|
||||
when={global.serverCtx(key)}
|
||||
keyed
|
||||
fallback={<Show when={global.serverSignedOut(key)}>{props.signedOut}</Show>}
|
||||
>
|
||||
{(ctx) => (
|
||||
<ServerContextProvider conn={props.conn} ctx={ctx} health={global.servers.health[key]}>
|
||||
{props.children}
|
||||
</ServerContextProvider>
|
||||
)}
|
||||
</Show>
|
||||
)
|
||||
}
|
||||
|
||||
export type ServerCtx = ReturnType<typeof createServerController>
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
||||
|
|
|
|||
|
|
@ -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 }>) {
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
59
packages/codemode/src/frame.ts
Normal file
59
packages/codemode/src/frame.ts
Normal file
|
|
@ -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<Cell> = EMPTY_CELLS
|
||||
code: Code
|
||||
pc = 0
|
||||
sp = 0
|
||||
regs: Array<unknown>
|
||||
thisValue: Value = undefined
|
||||
args: Array<Value> | undefined = undefined
|
||||
mode: FrameMode = Mode.CALLER
|
||||
target: unknown = undefined
|
||||
answer: unknown = undefined
|
||||
origin: AstNode | undefined = undefined
|
||||
counted = false
|
||||
|
||||
constructor(code: Code, regs: Array<unknown>) {
|
||||
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<Value>,
|
||||
) {}
|
||||
}
|
||||
|
|
@ -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<unkno
|
|||
const kind = slots[1] as GeneratorRequestKind
|
||||
const args = slots[2] as Array<Value>
|
||||
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") {
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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`,
|
||||
|
|
|
|||
|
|
@ -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 = <R>(
|
|||
const restoredSources = new Map<string, Source>()
|
||||
|
||||
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<R> {
|
|||
}
|
||||
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<R> {
|
|||
}
|
||||
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
|
||||
|
|
|
|||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -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.
|
||||
|
|
|
|||
|
|
@ -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<ClassSpec> | 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<ClassSpec> =>
|
||||
(specs ??= [
|
||||
{
|
||||
|
|
@ -99,6 +101,20 @@ const vmSpecs = (): ReadonlyArray<ClassSpec> =>
|
|||
{ 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<string> } => {
|
||||
vm.ensureIntrinsics()
|
||||
vm.compact()
|
||||
const ctx = vm.ctx
|
||||
const lost: Array<string> = []
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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<string>
|
||||
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<ClassSpec> | 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<ClassSpec> => [
|
||||
{ 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<ClassSpec> => [
|
|||
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<ClassSpec> => [
|
|||
{ 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<Function, ClassSpec>; readonly byName: Map<string, ClassSpec> } | undefined
|
||||
|
|
|
|||
|
|
@ -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 = <T>(): Array<T> => {
|
||||
const a: Array<unknown> = [""]
|
||||
|
|
@ -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<Cell> = EMPTY_CELLS
|
||||
code: Code
|
||||
pc = 0
|
||||
sp = 0
|
||||
regs: Array<unknown>
|
||||
thisValue: Value = undefined
|
||||
args: Array<Value> | undefined = undefined
|
||||
mode: FrameMode = Mode.CALLER
|
||||
target: unknown = undefined
|
||||
answer: unknown = undefined
|
||||
origin: AstNode | undefined = undefined
|
||||
counted = false
|
||||
|
||||
constructor(code: Code, regs: Array<unknown>) {
|
||||
this.code = code
|
||||
this.regs = regs
|
||||
}
|
||||
}
|
||||
|
||||
const EXEC_DONE = 0
|
||||
const EXEC_FUEL = 1
|
||||
|
||||
|
|
@ -207,19 +163,11 @@ const allocRegs = (size: number): Array<unknown> => {
|
|||
return regs
|
||||
}
|
||||
|
||||
/** Internal closure wrapper that does not touch `builtins.Function` or `nativeRule.sealed`. */
|
||||
export class VmInternalFn {
|
||||
constructor(
|
||||
readonly code: Code,
|
||||
readonly boundArgs?: ReadonlyArray<Value>,
|
||||
) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
|
||||
|
|
|
|||
|
|
@ -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({
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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<typeof sliced>) => {
|
|||
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<Show when={ctx()} keyed>
|
||||
{(resolved) => (
|
||||
<ServerContext.Provider
|
||||
value={{
|
||||
conn,
|
||||
key,
|
||||
isLocal: ServerConnection.local(conn),
|
||||
ctx: resolved,
|
||||
get health() {
|
||||
return global.servers.health[key]
|
||||
},
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</ServerContext.Provider>
|
||||
)}
|
||||
</Show>
|
||||
<ServerContext.Provider
|
||||
value={{
|
||||
conn,
|
||||
key,
|
||||
isLocal: ServerConnection.local(conn),
|
||||
ctx: props.ctx,
|
||||
get health() {
|
||||
return props.health
|
||||
},
|
||||
}}
|
||||
>
|
||||
{props.children}
|
||||
</ServerContext.Provider>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue