Skip to Content
Bear documentation

Bear execution environment

createBearSession binds a Bear-configured code loader and domain environment to the same Playground. It runs inside the realm where models are compiled. This environment has no renderer, drawing jig or branch selector.

import { createBearSession } from "bear/runtime/session";

const task = createBearSession({
  playground: taskPlayground,
  capabilities: {},
  types: { module: "bear/runtime/environment", export: "BearEnvironment" },
});

await task.run({ entryPoint: "analysis.ts", input: {} });
await task.evaluate(`
  const model = await env.bear.model({ entryPoint: "model.tsx", exportName: "default", props: {} });
  model.tree.fqn
`);
await task.close();

The environment is BearEnvironment<Capabilities, Files>: playground, the supplied capabilities, and bear.model(selection). Hosts with capabilities export a concrete alias of that type and name it in types, so snippets see the same contract their handlers and factory use. The generic session's declarations are supplied to the host's language service alongside those types.

Files defaults to the full writable Playground, and the factory infers it from the supplied object. Compilation needs only PlaygroundReader (open, resolve, and a directory listing), so a captured Playground preserves its read-only type in env.playground.

model resolves the selected entrypoint through that Playground's loader. The model store keys by the loader's module URL, export selection and detached data props. The module URL incorporates project imports, so a changed dependency causes a new build. Concurrent requests for the same key share the pending materialization; failed entries are removed so a later call can retry.

Several models coexist. Calling model does not replace a current model or change what an earlier result means. Models and keyed loaded shapes are kept until session close. This initial policy favors sharing; it is not a bounded cache for an indefinitely open editor. An eviction policy can later release unreferenced revisions without changing the operation API.

Model results expose ModelView, the engine's consumer contract. The store keeps the owning Model and its disposal operation. Queries, drawings, checks, scenes and compiled snapshots accept the view. Model data and native solids are borrowed for computation, not transferred out of the runtime. Return a detached snapshot or other portable result across a sandbox boundary. Closing the session invalidates its native geometry; detached snapshots remain usable.

Each operation gets a bound bear.model function. Calls through a saved environment after the operation ends fail. Session shutdown drains operations before disposing their models. Operations must await the work they start.

The loader/runtime/asset view is the cache's scope. Code URLs alone do not pin arbitrary network responses or mutable external assets. Hosts supplying those must version them or start a new environment when that view changes. Automatic filesystem capture remains an explicit host operation.

Drawings use ordinary jig-owned handlers receiving BearEnvironment, obtain a model, and invoke their own drawing functions. No drawing operation is registered in this environment or in Playground.

Captured main and task inputs

Playground's existing snapshotTree captures a project's root and linked directory heads. openSnapshotPlayground opens that descriptor as a SnapshotPlayground: the loader's extension/index fallback, file reads and directory listings all refer to the captured tree. Imported modules are read on demand. No file list is passed to Bear and no checkpoint is published.

import { snapshotTree } from "playground/history/snapshot";
import { openSnapshotPlayground, type SnapshotPlayground } from "playground/history/playground";
import { diffModels } from "bear/engine/diff";
import { snapshotModel } from "bear/engine/snapshot";
import type { BearEnvironment } from "bear/runtime/environment";

// Export this concrete alias from the host's environment module; use that
// module's name in `types` for both sessions.
export type ReviewEnvironment = BearEnvironment<{}, SnapshotPlayground>;

const revision = await snapshotTree(repo, mainRoot, "/");
const mainPlayground = await openSnapshotPlayground(context, revision);
const main = createBearSession({
  playground: mainPlayground,
  capabilities: {},
  types: { module: "my-product/environment", export: "ReviewEnvironment" },
});
// Construct task the same way from the task root or a saved TreeSnapshot.

async function capture(_input: undefined, env: ReviewEnvironment) {
  const selection = { entryPoint: "model.tsx", exportName: "default", props: {} };
  return snapshotModel(await env.bear.model(selection), {
    files: env.playground.revision,
    selection,
  });
}

try {
  const [before, after] = await Promise.all([
    main.invoke(capture, undefined),
    task.invoke(capture, undefined),
  ]);
  const changes = diffModels(before, after);
  // changes.before.files.root.heads retains its captured type and values.
} finally {
  await Promise.all([main.close(), task.close()]);
}

The descriptor uses Playground's stored, repo-encoded Automerge heads for each document. One Heads array cannot identify an entire linked project. Opening copies the descriptor before its first await, so changing the input or editing either live workspace cannot change subsequent reads. Captured files expose read operations only, and returned listings are detached. A missing captured version fails through the existing history reader instead of falling back to live bytes.

This is source pinning. The host still owns the runtime/importmap and external asset versions; include their identifiers in revision metadata when comparing across runtimes. Published mounts are immutable by URI in production; local development deliberately serves their current contents. Neither arbitrary network reads nor ambient process state becomes pinned by opening a snapshot.

Tests compile main and a real task branch after both live workspaces change, check that unchanged FQNs keep their mesh IDs, and distinguish a data-only edit from a geometry edit. This remains full materialization per changed model; compilation reuse and incremental rendering are later slices.

Studio and executor

createBearExecution({ playground, modules }) is the host adapter both the studio iframe and executor use. It shares one model store between env.bear, the displayed model and pictures. Building another model changes the host's current-model pointer without invalidating a borrowed model or rendering it. The existing workbench remains available to standalone build consumers.

The shared contract is ExecutionEnvironment from bear/runtime/contract:

import type { ExecutionEnvironment } from "bear/runtime/contract";
import { q } from "bear/engine/query";

export default async function (input: { name: string }, env: ExecutionEnvironment) {
  const model = await env.bear.model({ entryPoint: "model.tsx", exportName: "default", props: {} });
  return q(model).named(input.name).all().map((node) => node.fqn);
}

The executor's eval({ filePath, args }) loads this as an ordinary module, including relative imports from that file's directory. Its default export must be a handler. The entry initializes each run; its imports stay cached. Inline snippets keep their existing persistent console semantics. The iframe accepts the same handler request through runSandboxHandler. Saved modules import the environment type explicitly; env is a snippet binding, not a project-wide global. The session exposes its declaration for a future snippet editor (the studio console currently uses a textarea).

env.capabilities.agent contains the calling agent's tools, or is undefined for a human console or a host-only operation. Inline agent snippets also get the existing read, write, edit, bash and tools aliases. Each call gets a fresh file-version ledger. Saved tool functions reject after that invocation ends; a module helper receives env explicitly instead of depending on globals.

The adapters retain models until session close (or iframe destruction). This also applies to editor rebuilds; bounded retention needs an explicit ownership policy before old borrowed models can be evicted. Hosts can now open captured sessions as above; wiring those into studio review panes and partial recompilation remain separate work.

Shared model tools

Every executor binds the contract in tool-contract.ts under tools.bear (and env.tools.bear in a saved handler). tool-catalog.ts references that contract for discovery; tools.ts supplies the implementation. Adding an operation must satisfy both the typed catalog and the implementation.

materialize(element) returns a session-owned model. Every other operation requires that model explicitly: query(model), show(model), view(model, options?), print(model, options?) and diagnostics(model). There is no current-model state or implicit materialization. query keeps the full fluent query and component identity. show presents through the host, view returns PNG content, and print returns a tree or constraint report. For custom geometry, define a small part and materialize it before inspection. Project operations and jig namespaces continue through the same tools proxy.

Loading a file with env.bear.model requires all source fields: { entryPoint: "model/index.tsx", exportName: "default", props: {} }. The loader never infers the file, export or arguments from a previous model.

The host supplies presentation and image rendering. A headless microVM uses Darkroom for pictures and has no direct interactive presentation capability; the project's existing top-level browser tools still handle those calls. The Claude widget and Studio iframe present models locally. Models created from elements and loaded modules share session ownership and survive later materializations. Only tool bindings expire at the end of each invocation.

A test file is an ordinary handler. Import assertions and runTests from bear/test, pass the model to runTests(model), and return the report through execute({ filePath, exportName?, args? }). Inline code uses execute({ code }).

On this page