Skip to content

Latest commit

 

History

History
168 lines (125 loc) · 68.8 KB

README.md

File metadata and controls

168 lines (125 loc) · 68.8 KB

OpenCode for Blender

@neuralnomads/opencode-blender lets OpenCode read and change the scene open in Blender 5.3 or later. It is a native integration: the OpenCode Link add-on runs an authenticated host inside Blender, and the plugin sends it typed, revision-checked batches, fixed inspection and render programs, and (asking each time) Python code. No Blender documentation is bundled: the plugin asks the running Blender what it exposes and links the official documentation of its version.

Status: preview (draft 0.2, spec: 0, RPC contract 1). Not published to npm yet.

Installation

Any OpenCode client

  1. Add the plugin to the plugins list of your global OpenCode configuration (~/.config/opencode/opencode.json). Native integrations are installed in the global configuration only.

    {
      "plugins": ["@neuralnomads/opencode-blender@^0.4"]
    }

    With options (all optional, see Options):

    {
      "plugins": [{ "package": "@neuralnomads/opencode-blender@^0.4", "options": { "hostInspectionDir": "/path/to/extensions/user_default" } }]
    }
  2. Install the add-on: ask OpenCode to run blender_install_host (it asks for permission), or install host/blender/opencode_link-<version>.zip from the package with Blender's Preferences ▸ Get Extensions ▸ Install from Disk. The add-on is installed on the computer that runs OpenCode, in the user extensions folder of the newest Blender 5.3 or later started there.

  3. In Blender, enable OpenCode Link (Preferences ▸ Add-ons). While it is enabled, the session is offered to OpenCode, at every start included; disabling it withdraws the offer.

  4. In OpenCode, use any Blender tool: with one Blender open and attached to no other conversation, the first call attaches it to this conversation. With several, blender_hosts lists them and blender_hosts with attach attaches one (it asks for permission).

In CodeNomad

The Plugins section lists OpenCode for Blender as an integration: its version, whether the add-on is installed and up to date, and whether the conversation is attached; its menu installs or updates the add-on after a confirmation and detaches the conversation. Plugins ▸ Add also accepts the package name.

Chat in Blender (prototype)

With OpenCode running and OpenCode Link enabled, open a Python Console (Shift–F4) and choose Console → Languages → Opencode. It connects on its own, even for an unsaved scene, and keeps the current conversation when you open another file in the same folder. Use the conversation menu in the header, or /list then /open <n>, to switch. New conversation (/new) stays empty until you send a message. /stop interrupts or clears queued messages; /status and /help are always available. The console uses OpenCode’s executable; Node.js 22+ (NEURALNOMADS_BLENDER_NODE or PATH) is only a fallback. The add-on preferences can target a named OpenCode service.

The Console wraps lines and keeps its own Up-arrow history. An unfinished line appears when the stream finishes or the next newline arrives. Copy as Script copies this area's scrollback as plain text, not executable Python. Earlier messages stay in OpenCode when you reconnect; they are not replayed into Blender. /allow approves a single pending OpenCode permission once; /reject declines it. Use OpenCode to handle questions or multiple pending approvals.

CodeNomad can stay attached separately. Blender cannot repaint or accept console input while a main-thread Python operation or bake is running. Output queues and appears once the main thread is free; /stop does not preempt Python already running in Blender.

How it works

  • Discovery and consent. While OpenCode Link is enabled, the add-on listens on 127.0.0.1 on a random port with a random 256-bit token kept in memory, and offers the session to every OpenCode service registered for your user (or to one: the add-on setting OpenCode service). Offers last 15 seconds and are renewed every 5 seconds.
  • Attachment. A conversation acts on the Blender attached to it. The only offered Blender, compatible and attached to no conversation, attaches itself at the conversation's first Blender call, without asking; otherwise blender_hosts with attach asks the blender_attach permission. Opening another file in Blender replaces the offer: the conversation attaches again the same way.
  • Which Blender. blender_hosts and blender_context name the Blender this conversation acts on (attached_to: offer and label). Other conversations attaching or detaching other Blenders, or Blenders appearing, never make this conversation's ownership unverifiable; a permission prompt is refused only when this conversation's own Blender changed meanwhile.
  • Across an OpenCode restart. The plugin keeps each conversation's attachment in its storage (the Blender's offer key only as a SHA-256 digest, with the label; never a token, port or script handle). When the same Blender offers itself again after a restart, the conversation is attached back without asking, once its ownership is verified at its Location; never inside a read. A kept attachment lasts while its Blender is offered and two minutes after it stops; detaching removes it at once. A Blender restarted itself is a new offer: the conversation attaches again as above.
  • Upgrading without restarting OpenCode. A daemon that loads a newer version of the plugin without restarting can keep the older one in memory. Each version keeps its own list of offered Blenders, named after the add-on versions it accepts, so a Blender is always judged by the version that lists it; it offers itself again within 5 seconds.
  • The working method. When a conversation attaches a Blender, a short method joins it (an instructions entry, about 250 tokens): read the Blender version first, inspect the exact element before coding it, read an error's hint and inspect again instead of guessing, turn each requirement of the task into a check, run every check on the saved file (blender_verify with saved: true: the file is what is delivered), and report each requirement with its measured value, saying what failed or was not checked.
  • Session binding. Clients read bindingRead({ sessionID }) at the session's current OpenCode Location: attached identifies its live offer and safe label, none confirms a verified session without a binding, and unknown keeps the state unverified. status_changed {} invalidates the read; detachHost({ sessionID }) detaches. See the draft 0.2 RPC contract.

Tools

Tool What it does
blender_hosts The offered Blenders (label, document, Blender version, whether this conversation or another one is attached to each) and the add-on's install state; attach attaches one (asks permission), detach releases this conversation's.
blender_install_host Installs or updates OpenCode Link in the newest Blender 5.3 or later (asks permission).
blender_context A compact read of the scene: revision, scene settings, collections, markers, a page of objects with their transforms; ref gives one object in detail (world bounds, pose bones); include: ["parts"] lists a mesh's loose parts (world box, material, dominant vertex group), region keeps those in a world box.
blender_apply Up to 50 typed operations as one undo step, checked whole before anything changes; a failure part-way restores every changed field. See Typed operations.
blender_execute_code Python in Blender; every run asks the blender_execute_code permission. See Code execution.
blender_lab One of Blender Lab's tools (object and file summaries, screenshots, views, thumbnails), run by the add-on; images come back as attachments.
blender_inspect What this Blender really exposes: search (words found in its types, properties, functions and operators, with their paths and the properties that lead to a type), a type (properties, functions; a node type's real sockets, made in the tree named), an operator (parameters, the element type of its collections, its poll here with Blender's reason) or live data; entries beyond limit are named, match takes a glob or words. With the links to the API docs, manual and release notes of its version.
blender_verify criteria: the agent's checks (a read-only expression or a bpy.data path, a comparison, a value, frames), each measured on the evaluated scene and passed or failed with the value; visible: whether an object shows in the render at a frame, otherwise every reason found (out of frame, hidden in render, collection excluded, view layer not rendered, holdout, transparent or zero-density material, no geometry, hidden behind another object). Without them, or with render or view: a low-resolution render of the scene's final output, or from a free viewpoint (view: location, target, lens), with facts: black or transparent, brightness, the camera used and why, strips, instances. frames returns several frames as one contact sheet; scene chooses the scene (the facts name the one read, and warn when it is a shot of a montage). geometry says what is wrong with the meshes in view (closed meshes with inward normals, open or non-manifold edges, zero-area faces, faces of two objects on one plane toward the camera), and a render names its near-black areas with the object a camera ray meets there; caches names the simulation caches the checked frames read without a current bake (not baked, outdated, frames outside it) (Blender marks a rigid body bake outdated whenever its file is opened, and says so in note); unsaved, what the saved file lacks; saved reads the file as written on disk instead (a background Blender opens it: same criteria, visible and render; read names the file). Settings, cameras and frame are restored; the revision stays.
blender_render A render in a separate background Blender to an exact output (an image, a frame pattern or an H.264 video, with the montage's sound when it has any; the result lists the streams written), followed as a task (task, wait_s up to an hour, cancel). It renders the saved file (unsaved).
blender_save Saves the file, under a path, or a copy, and says what it wrote (bytes; wrote_steps, the OpenCode steps now in the file, an empty list when none was pending) and, after a copy, what the open file still lacks (unsaved), with check, the blender_verify call that reads the file back (a code run that saved the open file says it too); a save that failed because another process held the file a moment is retried once and says so (retried).
blender_import BlenderKit and Sketchfab searches, and imports from them or from a file (glTF, FBX, OBJ, USD; a path or an https URL), followed as a task (task, wait_s, cancel). BlenderKit and Sketchfab need their add-ons.

blender_inspect, blender_verify, blender_render and blender_save send fixed programs of the package (programs/*.py) through the host's code execution, read only, with their parameters as JSON data; they ask no permission because they run no code from the model. Without if_revision and command_id, blender_apply applies to the document as it is now under a new command_id; with them it is refused when the scene changed, and a replayed command_id applies nothing.

Typed operations

The fields, kinds and rules come from the add-on's validator (host/ops.json, generated with python integrations/blender/host/ops_json.py); the plugin checks the same fields and the add-on checks them again against the document. Names created or copied earlier in a batch are $alias (their as); a rename or a delete is visible to the later operations; a field given null counts as absent.

Operation Arguments (* required, = default) Description and rules
set_transform ref* ref
location vec3
rotation rotation
scale scale
delta bool =false
Location, rotation (written in the object's own rotation mode) and scale; delta adds the location. Rule: give location, rotation or scale.
fit_height ref* ref
height number
ground bool =true
ground_z number =0.0
children bool =true
scale_axes z|uniform ="z"
frame whole_frame
key bool =false
Scale to a height in metres (Z only by default; scale_axes uniform keeps the proportions) and/or put the lowest point at ground_z, measured on the evaluated geometry (armature pose and modifiers included) at frame (default: the current frame, which stays current); key keys the location (and scale) there, so a falling body touches the ground at each of its key frames. Without height nothing is scaled. Rule: give height or ground true. Rule: height above 0.
pose_bone ref* ref
bone* name
location vec3
rotation rotation
scale scale
A pose bone's location, rotation (in the bone's rotation mode) and scale. Rule: give location, rotation or scale.
aim_bone ref* ref
bone* name
target* target
axis Y|-Y|X|-X|Z|-Z ="Y"
tolerance_deg number
Rotate a pose bone about its head so its axis points at a point, an object (or one of its bones) or along a world direction; reports error_deg and refuses a miss above tolerance_deg.
reach ref* ref
chain* bones
target* goal
pole target
frame whole_frame
key bool
tolerance positive
Two-bone IK solved once and written as a pose: chain is [upper, lower] or [upper, lower, end] (an arm, and its hand), each the parent of the next. The lower bone's tail reaches target (a point, an object or one of its bones), the elbow bends toward pole (a point, an object, a bone or a world direction; default: the side it bends to now), and end takes the target's world orientation (an object or bone target, or target.rotation). At frame (which stays current) it keys the chain's rotations (key, default true with frame). Reports error (metres), end_error_deg and the elbow; refuses a miss above tolerance (default 1 mm), such as a target out of reach. Rule: each bone of chain is the parent of the next. Rule: target is point or object (with bone), rotation optional. Rule: key needs frame.
insert_key ref* ref
bone name
paths paths
path data_path
index index
owner object|data|shape_keys ="object"
value value
frame* frame
interpolation CONSTANT|LINEAR|BEZIER
Key at a frame the current location, rotation and/or scale (paths) of an object or pose bone, or any animatable property by its RNA path (path), such as constraints["Grab"].influence, key_blocks["Blink"].value with owner shape_keys, lens with owner data, or ["prop"]; with bone the path is the pose bone's. value sets the property first; index keys one element of an array. Rule: give paths or path (one of them). Rule: value and index go with path. Rule: owner other than object goes with path, without bone.
delete_keys ref* ref
bone name
paths paths
path data_path
index index
owner object|data|shape_keys ="object"
frames frames
Delete the keys of paths (location, rotation, scale) or of one RNA path (each array element unless index) in frames [first, last] (all without frames); an F-curve left without keys is removed. Rule: give paths or path (one of them). Rule: index goes with path. Rule: owner other than object goes with path, without bone. Rule: frames is [first, last] with first at most last.
create_object kind* empty|camera|light|mesh|text
name* name
as alias
primitive cube|plane|uv_sphere|cylinder|cone
size positive
depth positive
light_type POINT|SUN|SPOT|AREA
energy number
lens number
body text
extrude nonnegative
align_x LEFT|CENTER|RIGHT|JUSTIFY|FLUSH
align_y TOP|TOP_BASELINE|CENTER|BOTTOM_BASELINE|BOTTOM
location vec3
rotation rotation
collection name
parent ref
A new empty, camera, light, mesh primitive or text; as names it $alias for later operations. Mesh size (default 1 m): a cube's edge, a plane's side, a uv_sphere's diameter, a cylinder's diameter and height, a cone's base diameter and height; depth sets a cylinder's or cone's height apart (a barrel 0.6 wide and 0.9 high: size 0.6, depth 0.9). Text: body, size (font size in metres, default 1), extrude (depth), align_x, align_y. Rule: primitive and size apply to a mesh; depth to a cylinder or cone; light_type and energy to a light; lens to a camera; body, size, extrude, align_x and align_y to a text. Rule: a text needs body.
rename ref* ref
name* name
Rename an object.
delete refs refs
collections names
Delete objects (refs) and empty collections (collections): their names are free for the batch's later operations at once (and an object's data's when only it used it); they leave the document when the batch succeeds. Rule: give refs or collections. Rule: a collection is deleted empty: its objects and child collections are deleted by the same batch or moved first.
duplicate ref* ref
as alias
name name
suffix name
offset vec3
linked bool =false
children bool =true
Copy an object with its whole hierarchy (children false: alone) into the same collections, moved by offset in world space. linked shares the data (Blender's Alt+D), otherwise each copy gets its own (Shift+D); materials and actions stay shared. name names the copy of ref, suffix is added to every copy's original name (Blender's .001 otherwise); as names the copy of ref $alias. Rule: name, suffix and as apply to the copy of ref (suffix to every copy).
set_material ref* ref
material* name
color rgb
roughness nonnegative
metallic nonnegative
slot index
Assign a material to an object's slot, creating it (Principled BSDF) when no material has that name; color (linear RGB, also the viewport colour), roughness and metallic set its Principled BSDF, also on an existing material. Without slot: its only slot (added when it has none); slot equal to the number of slots adds one. Rule: color, roughness and metallic are optional: without them an existing material is only assigned.
material_nodes material* name
nodes nodes
links links
ref ref
slot index
Build or edit a material's shader graph: nodes adds a node per entry ({name, type, location, label, inputs: {socket: value}, props: {attribute: value}, ramp: [[position, [r, g, b, a]], ...]}) or updates the node of that name (Principled BSDF and Material Output in a new material); links connects {from: [node, output], to: [node, input]}, replacing what fed that input. Procedural textures (ShaderNodeTexNoise, TexVoronoi, TexWave...), mixes, color ramps and bumps included. A material of that name is made when there is none; ref assigns it like set_material. Rule: give nodes, links or ref. Rule: a new node needs type. Rule: slot goes with ref.
scene_settings frame_start whole_frame
frame_end whole_frame
frame_current whole_frame
fps positive
The scene's frame range, current frame (animation evaluated there) and frames per second (a fractional rate such as 23.976 sets fps and fps_base). Rule: give at least one field. Rule: frame_start at most frame_end when both are given; one alone may not cross the scene's other end (refused, never pushed).
shift_keys ref* ref
bone name
paths paths
frames frames
offset number
delete bool =false
Move the keys of an object (or one pose bone) in frames [first, last] (all without frames) by offset frames, handles included, or delete them; paths narrows them to location, rotation and/or scale. The keys of its action's slot (Blender 5 layered actions). Rule: give offset (not 0) or delete true, not both. Rule: frames is [first, last] with first at most last. Rule: a key may not land on a key that does not move (refused).
link ref* ref
collection* name
Link an object into a collection.
unlink ref* ref
collection* name
Unlink an object from a collection (never from its last one: use delete).
create_collection name* name
parent name
A new collection, in parent or the scene's.
set_parent ref* ref
parent ref
bone name
keep_transform bool =true
Parent an object (to a bone with bone), or clear its parent without parent; keeps its world transform. Rule: bone needs parent.
add_marker name* name
frame* frame
camera ref
A timeline marker, optionally bound to a camera.
set_camera ref* ref Make a camera the scene's active camera.
add_constraint ref* ref
type* TRACK_TO|DAMPED_TRACK|COPY_LOCATION|COPY_ROTATION|COPY_TRANSFORMS|CHILD_OF
target* ref
subtarget name
name name
influence nonnegative
An object constraint targeting an object (subtarget: one of its bones), with its influence (0 to 1). Rule: influence from 0 to 1.
switch_parent ref* ref
parent ref
bone name
frame* whole_frame
From frame on, the object follows parent (one of its bones with bone; the world without parent) without a jump: an anchor empty is made under parent where the object is at that frame, and a Copy Transforms constraint to it takes over at that frame (influences keyed CONSTANT: this switch's 1, earlier switches' 0). Before frame nothing changes. A revolver goes holster, hand, ground in three operations. Rule: bone needs parent. Rule: parent is not the object or one of its children.

Behaviour to know:

  • Primitive size (default 1 m) is a cube's edge, a plane's side, a uv_sphere's diameter, a cylinder's diameter and height, a cone's base diameter and height; depth gives a cylinder's or cone's height apart. A text's size is its font size.
  • fit_height scales Z only by default (scale_axes: "uniform" keeps the proportions, and says that X and Y were scaled too); it refuses a tilted object in Z mode; without height it scales nothing. The result names the axes and the factor. With frame it measures the deformed pose at that frame and key keys the result there.
  • Rotations are written in the holder's own mode: Euler angles in its order as given (360° stays 360°, so a full turn can be keyed); another order or a quaternion becomes the equivalent nearest the current angles. A quaternion or axis-angle holder keeps an orientation only and says so for 180° or more. A linear full turn: insert_key with interpolation: "LINEAR" on both keys.
  • reach solves a two-bone chain once and writes the pose (no IK constraint is left): the lower bone's tail on the target, the elbow toward pole (by default the side it bends to now), the end bone turned like an object or bone target; at frame it keys the chain's rotations. A target out of reach is refused and undone, with the chain's length.
  • switch_parent keeps one anchor empty and one Copy Transforms constraint per switch, named OC parent f<frame> <parent>; its own keys no longer move the object after a switch.
  • insert_key and delete_keys take an RNA path on the object, its data or its shape keys (owner); delete_keys removes keys by position from the last and an F-curve left empty.
  • set_parent with keep_transform evaluates the scene first, so objects created or moved earlier in the batch keep their world transform, and keeps the object's own values (Blender's Parent, Keep Transform).
  • delete frees the names at its place in the batch: a later create_object, duplicate or rename gets that exact name, and the new mesh the deleted mesh's name when only the deleted object used it. The deleted objects leave the document when the batch succeeds, with the data only they used.
  • duplicate copies a hierarchy into the originals' collections, keeps each child's parenting, points constraints at the copies and shares materials and actions; linked also shares the data. A name or suffix another object holds is refused before anything runs.
  • set_material creates a Principled material when no material has that name, or sets the values of an existing one; a value Blender would clamp fails the batch, which is restored.
  • scene_settings never lets Blender push the other end of the frame range: one end crossing the other is refused. fps 23.976 sets fps 24 and its base.
  • shift_keys moves keys with both handles (or deletes them) in the action slot the object uses (Blender 5 layered actions); a key landing on one that does not move is refused.

Options

Option Environment variable Default
hostInspectionDir NEURALNOMADS_BLENDER_HOST_INSPECTION_DIR The user extensions folder of the newest Blender 5.3 or later
requestTimeoutMs NEURALNOMADS_BLENDER_REQUEST_TIMEOUT_MS 120000 (1 s to 10 min); a verification render waits 10 min

Add-on settings (Preferences ▸ Add-ons ▸ OpenCode Link): OpenCode service (offer to one service only), OpenCode configuration folder (only for a service started with OPENCODE_CONFIG_DIR), and Reset OpenCode Link after a failed restoration.

Permissions

Permission Asked when
blender_attach blender_hosts attaches a Blender (never for the automatic attachment)
blender_install_host blender_install_host installs or updates the add-on
blender_execute_code every blender_execute_code run
blender_import blender_import imports an asset or a file (never for a search)

Code execution

blender_execute_code runs Python in Blender with your rights: it can read and write files, start processes and reach the network. The add-on lists it while it is enabled, and every run asks the blender_execute_code permission ("ask" unless you allow it in OpenCode's permission settings); a refused run executes nothing. A run that changes the scene is one undo step; a failing one is undone. Blender keeps linked data outside its undo (a linked library, the brush a sculpt or paint mode links): it is named in restoration.kept_linked, unused and not saved. When an undo cannot be proven, OpenCode Link is quarantined: reads, blender_verify, blender_inspect and read_only code still run, changes wait; blender_context shows quarantine.may_have_changed, and once you checked it, blender_context with release_quarantine (that read's revision) lifts it, as does Reset in the add-on's panel. A long script can be a file (path): it is read as written, with no escaping through a JSON or JavaScript string, and its tracebacks name the file. See SECURITY.md.

When the open document differs from its file, the results of blender_context, blender_apply, blender_execute_code and blender_verify carry unsaved: the file's name (never_saved for a new document) and the OpenCode steps since its last save or load (changes made by hand are not listed); saving a copy leaves it, a run that saves the open file and changes nothing after clears it, and a run that opens a file pushes no step into it.

A run that fails on Blender's API carries a hint read from that Blender before the run is undone: for an unknown attribute, the closest names and the type's properties; for an operator's arguments, its real signature (with the element type of its collections) and the closest names; for an invalid enumeration value, the closest items; for a missing key, the collection's keys (a node's sockets included); for an unknown node type, the closest types the tree creates, with their sockets; for a failed poll, Blender's reason, the context the code had, the operators of its group whose poll passes, and the context members (with their path) or editor area that make it pass, found by trying poll() only. While a run executes, OpenCode Link prepares two calls Blender 5.3 closes on from a script, as Blender's interactive path prepares them, and says so in warnings: a mask stroke (sculpt.brush_stroke with the Mask brush or brush_toggle='MASK') on a multiresolution object gets its mask layer first, and in a Blender without interface a sculpt-mode operator gets a first undo step when none was pushed yet. If the attached Blender crashes, the call running then stops waiting within two seconds and says so with the crash report Blender wrote (<file name>.crash.txt in its temporary folder; only the report named after its own document counts, since every Blender of a user writes there); on Windows its process stays open behind Blender's crash window. A Blender closed without a report (closed, or ended by another program), one whose offer stopped while its process runs, and a call that outlasts its wait while Blender still runs it (the add-on's status answers off Blender's main thread, with the request running and for how long) are said as such; after its Blender crashed or closed, a conversation never attaches another Blender by itself.

Blender limits

  • Blender 5.3 or later; edits run in Object mode only.
  • Two conversations may attach the same Blender: each batch is checked against the document's revision, and the attach that makes it shared says so (shared).
  • Blender 5.3 closes when a script sets use_disk_cache on the rigid body world's point cache of a saved file (a Blender defect, outside OpenCode Link).
  • The code-change fingerprint that keeps the revision current does not read mesh vertices, modifier and node values or settings below one nested level. A read_only run is judged by its content instead (poses, mesh vertices, shape key values, constraint influences, material node values): one that puts everything back is no change.

Earlier installation

A blender plugin file in the global configuration, or a listener answering the earlier bridge's ping on port 9876, is reported as legacy_install in status. Remove it: both would compete with this plugin.

Development

npm run build --workspace @neuralnomads/opencode-blender        # dist/ (checks the host artifacts)
npm run build:host --workspace @neuralnomads/opencode-blender   # the add-on payload and the marker's digest
python integrations/blender/host/ops_json.py                    # host/ops.json and the table above
node --test integrations/blender/test/*.test.ts                 # BLENDER_TEST_BIN=<Blender 5.3> for the host tests

What 0.4.0 keeps, replaces and retires from 0.2.0, and how to reintroduce a retired part: METHODS.md.

Licence

MIT for the plugin; GPL-3.0-or-later for the add-on, the Blender Lab tool code it contains and the programs run in Blender (see NOTICE.md).