# Embody + Envoy + TDXN - full text for AI agents > Open-source TouchDesigner toolkit. Envoy is an MCP server (70 tools) that lets AI > assistants build, wire, parameterize, and debug a LIVE TouchDesigner session; Embody > externalizes the network to version-control-friendly text on disk; TDXN is the diffable > YAML network format that makes both possible; Convoy relays the work to other computers > on a trusted LAN. Free, MIT, runs entirely on the user's machine. Requires > TouchDesigner 2025.33230+ (Windows/macOS). This file inlines the essential documentation in one place so an agent can read it in a single fetch. Curated index: https://embody.tools/llms.txt - For agents: https://embody.tools/for-ai Repo: https://github.com/dylanroscover/Embody - Docs: https://dylanroscover.github.io/Embody/ Sections below, in order: 1. Quickstart 2. Envoy - Setup 3. Envoy - Claude Code Integration 4. Envoy - Tools Reference (the 70 MCP tools + 24 bridge meta-tools) 5. Convoy - LAN Relay 6. TDXN - Specification 7. TDXN - Import & Export 8. AI Instructions (AGENTS.md) - critical rules for operating in a TD project ============================================================================== # Quickstart # source: docs/quickstart.md ============================================================================== # Quickstart **From nothing to your first AI-built network in about five minutes.** The fastest way to experience Embody is the AI way: install one thing, paste one line (or drag in one file), click one button, then *talk* to TouchDesigner and watch it build. You describe what you want in plain language - no coding, no scripting, and git is entirely optional. Embody itself is free, open source (MIT), and runs entirely on your own machine - no Embody account, no subscription, nothing SaaSy. You'll sign in to your AI assistant (a Claude account for Claude Code, for example), but that's the only login involved. The server Embody starts is local-only; nothing about your project leaves your computer unless you choose to share it. --- ## Step 1 - Get the two prerequisites You need two things installed before you start: - **TouchDesigner 2025.33230 or later** - Windows or macOS. [Download from Derivative](https://derivative.ca/download). - **An AI assistant that speaks [MCP](https://modelcontextprotocol.io/)** (the open standard that lets AI tools drive other apps) - [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (recommended), [OpenCode](https://opencode.ai/), [Codex](https://github.com/openai/codex), [Gemini](https://github.com/google-gemini/gemini-cli), [Cursor](https://www.cursor.com/), [Windsurf](https://windsurf.com/), or GitHub Copilot via VS Code. !!! note "Never used an AI coding tool?" Claude Code is the gentlest place to start - it runs as a desktop app, a VS Code extension, or a web app, not only in a terminal. The first time, you'll create or sign in to a Claude account and then open a folder; you won't be writing code, just describing what you want in plain language. (The five-minute estimate above assumes TouchDesigner and your AI assistant are already installed - first-time installs take a little longer.) --- ## Step 2 - Install Embody Two ways in - both end in the same place. Pick whichever suits you. === "Paste into a Textport" Open your `.toe` project (or a brand-new one), open a Textport (**Dialogs -> Textport and DATs**, or **Alt + T**), and paste this one line: ```python import requests, hashlib, tempfile, os; h = {'User-Agent': 'Embody-Install'}; mf = requests.get('https://github.com/dylanroscover/Embody/releases/latest/download/embody-release.json', headers=h, timeout=30).json(); b = requests.get('https://github.com/dylanroscover/Embody/releases/download/%s/%s' % (mf['tag'], mf['asset']), headers=h, timeout=120).content; assert hashlib.sha256(b).hexdigest() == mf['sha256'], 'checksum mismatch'; f = os.path.join(tempfile.gettempdir(), mf['asset']); open(f, 'wb').write(b); n = ui.panes.current; n = n if n.type == PaneType.NETWORKEDITOR else next(x for x in ui.panes if x.type == PaneType.NETWORKEDITOR); print('Embody', mf['version'], 'installed at', n.owner.loadTox(f).path) ``` It downloads the latest release from GitHub, verifies its sha256 against the release manifest, and drops Embody into your current network - exactly like dragging the file in. TouchDesigner pauses for a few seconds while it fetches. Works the same on macOS and Windows. === "Download the .tox" Grab the latest Embody `.tox` from **[GitHub Releases](https://github.com/dylanroscover/Embody/releases/latest)** - it's a single file - and **drag it into the network** of your open project. Either way, that's the entire install - there's nothing else to set up. Embody initializes itself automatically over the next couple of frames. The core externalization features are self-contained and need no external dependencies. --- ## Step 3 - Say yes to Envoy, the AI bridge As soon as Embody finishes initializing, its [setup wizard](embody/setup-wizard.md) opens - a few quick screens, one decision each. For the fast path, take the recommended option on every screen: **Auto** mode, **Claude Code** as the assistant, **Don't ask** for permissions - then click **Set up Embody** on the summary. Nothing changes until that final click. That single confirmation does everything for you: - Installs the MCP server's Python dependencies (~30 MB, in the background - TouchDesigner stays responsive) - Starts a local server on `127.0.0.1:9870` - Writes the AI config files into your project root - `CLAUDE.md`, `AGENTS.md`, `.mcp.json`, and a `.claude/` folder of rules and skills - so your assistant knows how to talk to TouchDesigner Clicked **Not now**, or want to change a choice later? Pulse the **Setup Wizard** parameter on the Embody component to re-run it anytime, or toggle **Envoy Enable** directly. !!! note "No git? No problem" The wizard doesn't require version control. The AI config files are generated either way - with a git repo Embody also adds its `.gitignore` / `.gitattributes` entries; without one it simply skips them. !!! info "Local and private by default" Envoy only listens on your own computer (`127.0.0.1`) - it's not reachable from the internet or your network. Every Envoy tool is pre-authorized, too, so you're not stuck clicking through permission prompts. --- ## Step 4 - Open your AI assistant and start talking **Keep TouchDesigner open** - your AI assistant talks to the live session. The easiest way in is the **Launch AI Client** button: on the Embody component's **Envoy** parameter page, set the **Launch Client** menu to your assistant, then click **Launch AI Client**. Embody opens the client (an editor as a workspace, or a CLI in a new terminal) already pointed at your project root - and if the client isn't installed yet, the terminal walks you through it: the official install command for your OS on its own line, ready to copy/paste. Prefer to open it yourself? Open your AI assistant in the **same folder as your `.toe`** and start a new chat: - **Claude Code** (the fully auto-configured path): open that folder - `File -> Open Folder` in the desktop or VS Code app, or `cd` into it and run `claude` in a terminal - then start a session. It detects the `.mcp.json` Envoy generated and connects on its own. - **Cursor or Windsurf**: open the same folder; you may need to point it at the generated `.mcp.json` yourself - see [Envoy Setup](envoy/setup.md#manual-configuration). Now just say what you want. Try this: ```text Build me a noise-driven particle system. ``` Watch the operators appear in your live session - wired up, named, annotated, and laid out. Then keep going, conversationally: ```text Now make it react to audio, slow it down, and add a bloom on the final output. ``` You're not getting a screenshot or a code snippet to paste. You're getting the **actual network**, in front of you, ready to play with. !!! tip "Big build? Start with a brief" For substantive builds, type `/brief` followed by your request (or a bare `/brief` after describing it in chat). Claude compiles your ask into a reviewable plan - the skills it will load, where it will build, verifiable success criteria, and safety gates - and gets your approval before creating a single operator. See [Task Briefs](envoy/claude-code.md#task-briefs-brief). !!! info "How long does a build take?" Small things - a parameter change, a fix, a question about your network - can land in seconds. A complete network is a real build: the AI reads your project, plans, creates, wires, and verifies its work, which typically takes **5-20 minutes** of autonomous effort, depending on your model and compute. You don't have to watch it, and you don't have to run just one: Envoy [coordinates multiple AI sessions](envoy/multi-session.md) on the same project, each scoped to its own part of the network. Less like waiting on a genie, more like directing a team. !!! tip "Confirm the connection" If your assistant doesn't seem to see TouchDesigner, ask it to *"list all operators in the project."* If that comes back empty or errors, check that **Envoy Enable** is on and that you started the AI session **after** enabling it. Still stuck? See [Envoy Troubleshooting](envoy/troubleshooting.md). --- ## What you got for free Embody's other job is making your network **version-controllable**: any COMP or DAT can be saved to disk as readable text - something you can diff, review, restore, and hand back to the AI later. No binary black box, no lock-in. Externalization is **opt-in** - nothing is written to disk until you choose. Two ways to opt in: - **Tag operators yourself**: hover one and press ++lctrl++ twice. - **Auto-externalize what the AI builds**: set the **Auto-Externalize New Ops** parameter (Embody component -> **Envoy** page) to `DATs`, `COMPs`, or `DATs and COMPs`. New operators your assistant creates through Envoy are then tagged and externalized automatically. The default is `Neither`. To keep a whole project on disk, see [Tracking a Whole Project](embody/externalization.md#tracking-a-whole-project). To save your changes, press ++ctrl+shift+u++. On the next project open, everything tagged restores from disk automatically. That's the whole loop - generate, compare, revert, branch. The lateral moves run at the speed of typing; the generating you delegate and come back to. !!! tip "Here for version control, not AI?" You can skip Envoy entirely and use Embody as a pure externalization engine - every operator diffable on disk, no AI involved. See [Getting Started](embody/getting-started.md) for that workflow. --- ## Where to go next | If you want to... | Go here | |---|---| | Understand externalization in depth | [Getting Started](embody/getting-started.md) | | See everything the AI can do | [Envoy Tools Reference](envoy/tools-reference.md) | | Configure ports, multiple instances, or permissions | [Envoy Setup](envoy/setup.md) | | Fix a connection problem | [Envoy Troubleshooting](envoy/troubleshooting.md) | | Understand why this exists | [The Manifesto](manifesto.md) | The tool keeps up with you, instead of the other way around. That's the whole idea. ============================================================================== # Envoy - Setup # source: docs/envoy/setup.md ============================================================================== # Envoy Setup ## Prerequisites You'll need: - **TouchDesigner 2025.33230** or later - An MCP-compatible client such as [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai/), [Codex](https://github.com/openai/codex), [Gemini CLI](https://github.com/google-gemini/gemini-cli), [Cursor](https://www.cursor.com/), [Windsurf](https://windsurf.com/), or GitHub Copilot via VS Code Embody automatically installs all server-side dependencies (`mcp`, `uvicorn`, etc.) when Envoy is first enabled - no manual Python setup required. This first install (and any later dependency upgrade) runs **in a background thread** so TouchDesigner stays responsive; the Embody COMP shows `Installing deps... (one-time)` while it works and switches to `Running on port ...` once MCP is ready. After that, every startup takes the fast path and skips the install entirely. Envoy validates the virtual environment on each startup and falls back to the system Python if the venv is broken (see [Broken Virtual Environment](troubleshooting.md#broken-virtual-environment)). The environment is shared with your own code too - any DAT or extension in the project can import from it, and your own packages can live in it: see [Python Environment](../embody/python-environment.md). ## Enabling Envoy 1. **Enable Envoy**: Toggle the **Envoy Enable** parameter on the Embody COMP 2. **Server starts**: Envoy runs on `127.0.0.1:9870` (configurable via **Envoy Port**) 3. **Auto-configuration**: Envoy creates `.mcp.json` and AI client config files at the root chosen by the **AI Project Root** parameter - the git repo root by default (`gitroot`), or the `.toe`'s own folder (`projectfolder`), or a custom path. When `gitroot` is selected but no git repo exists, Envoy falls back to the project folder and still writes the config. If your project is in a git repo, Envoy also generates `.gitignore` and `.gitattributes` entries. 4. **Connect your MCP client**: Start a new Claude Code session (or restart your IDE) - it picks up the `.mcp.json` automatically ## Regenerating Config Files You can regenerate Envoy's config files at any time from the TD textport or a script: ```python op.Embody.InitEnvoy() # Regenerate MCP + AI client config op.Embody.InitGit() # Init/reconnect git repo + .gitignore/.gitattributes ``` Use `InitEnvoy()` after updating Embody, changing which clients you configure for, or if config files were accidentally deleted. Use `InitGit()` after creating a git repo manually, or to refresh `.gitignore`/`.gitattributes` entries. `InitGit()` also calls `InitEnvoy()` to update paths. ## Manual Configuration If you prefer manual control, create `.mcp.json` in your project directory. You can use either the direct HTTP transport or the STDIO bridge: **HTTP transport** (simpler, requires TD to be running): ```json { "mcpServers": { "envoy": { "type": "http", "url": "http://127.0.0.1:9870/mcp" } } } ``` **STDIO bridge** (recommended - supports launching TD from Claude Code): ```json { "mcpServers": { "envoy": { "type": "stdio", "command": "python3", "args": ["-u", ".embody/envoy-bridge.py", "--port", "9870", "--config", ".embody/envoy.json"] } } } ``` The STDIO bridge provides meta-tools (`get_td_status`, `launch_td`, `restart_td`, `switch_instance`) that work even when TouchDesigner is not running. See [Claude Code Integration](claude-code.md#stdio-bridge) for details. ### Every client reads a different file `.mcp.json` is Claude Code's format, and **no other client reads it** - VS Code does not even use the same root key. So Embody writes each selected client's own MCP config as well, every one of them spawning the *same* STDIO bridge, so every client gets the bridge's resilience layer (meta-tools while TD is down, reconnection, instance-registry identity checks) rather than a bare URL. | Client | MCP config file | Root key | |---|---|---| | Claude Code | `.mcp.json` | `mcpServers` | | OpenCode | `opencode.json` | `mcp` | | Codex | `.codex/config.toml` | `[mcp_servers.envoy]` | | Gemini | `.gemini/settings.json` | `mcpServers` | | VS Code | `.vscode/mcp.json` | `servers` | | GitHub Copilot | `.vscode/mcp.json` (shared with VS Code) | `servers` | | Cursor | `.cursor/mcp.json` | `mcpServers` | | Antigravity | `.agents/mcp_config.json` | `mcpServers` | | Windsurf | `~/.codeium/windsurf/mcp_config.json` | `mcpServers` | Merging is conservative in every case: an existing file keeps all of its other servers and unrelated settings, only the `envoy` entry is written, a second deploy with an unchanged bridge command rewrites nothing, and a file Embody cannot parse (VS Code and Cursor both accept JSONC, which is not valid JSON) is left **completely untouched** with a warning rather than clobbered. Two clients need a manual step: - **Codex** reads project-level config only for projects you have trusted. Run `codex` once in the project folder and trust it, or the `.codex/config.toml` Embody writes is ignored. - **Windsurf** has no project-level MCP config at all - Cascade reads only the user-global `~/.codeium/windsurf/mcp_config.json`, shared by every project you open. Embody will **not** write a global file that points all of your projects at this one's bridge, so add the `envoy` entry there by hand once. Everything else for Windsurf (`.windsurf/rules/`) is generated normally. ### Files you already own Embody never overwrites a file you wrote. Which of two things it does depends on the file: - **`CLAUDE.md`, `AGENTS.md`, `GEMINI.md` and `.github/copilot-instructions.md` are merged into.** Your content is left exactly as it is and Embody maintains one delimited block inside the file, refreshed in place on later deploys. Uninstall removes only that block and leaves the file. The block opens with a visible heading saying which half is which, so you can tell at a glance where your own edits belong: ```markdown # My Project Always run the linter before committing. ## Embody / Envoy -- auto-generated section *Everything from this heading down to the END marker is rewritten by Embody on each deploy, so edits inside it are replaced. Put your own instructions OUTSIDE this section -- above or below, wherever you like. Embody never touches those, and Uninstall removes only this block.* ... ``` Put your own instructions anywhere outside the block. If you move the block, later deploys refresh it where you put it rather than moving it back. - **Per-rule and per-skill files are skipped.** `.claude/rules/td-python.md`, `.cursor/rules/*.mdc` and their siblings have Embody-specific names, so a file of yours at one of those paths is left completely alone -- the other rules are still written around it. A file Embody cannot read as UTF-8 is skipped with a warning rather than rewritten, and it never stops the rest of the deploy. ### Which files each client gets `AGENTS.md` (the universal standard read by all major AI tools) and `.mcp.json` are written whenever any client config is generated -- that is, unless **Configure For** is `None`. | Configure For | Also writes | |---|---| | Claude Code | `CLAUDE.md` (merged into if you already have your own), `.claude/rules/`, `.claude/skills/` | | OpenCode | `opencode.json`, and shares Claude Code's `.claude/rules/` + `.claude/skills/` | | Codex | `.codex/config.toml`, `.agents/skills/` (Codex reads `AGENTS.md` natively, so it needs no rules files of its own) | | Gemini | `GEMINI.md` (a thin `@AGENTS.md` import), `.gemini/settings.json`, `.agents/skills/` | | VS Code | `.vscode/mcp.json` | | GitHub Copilot | `.github/copilot-instructions.md`, `.github/instructions/`, and `.vscode/mcp.json` (shared with VS Code) | | Cursor | `.cursor/rules/*.mdc`, `.cursor/mcp.json`, `.agents/skills/` | | Windsurf | `.windsurf/rules/` only - its MCP config is user-global and is never written, see above | | Antigravity | `.agents/rules/`, `.agents/skills/`, `.agents/mcp_config.json` | `.agents/skills/` is one folder shared by Codex, Gemini, Cursor and Antigravity -- all four read the same `SKILL.md` contract, so the skills are written once and every selected client discovers them. Serving more than one client is normal and supported: select each in turn. Generation is additive and never removes, so an earlier client stays configured and its MCP config keeps tracking bridge and port changes. See [Local Models & Open Clients](local-models.md) for OpenCode's full setup, including local-model recommendations. ## Changing the Port Change the **Envoy Port** parameter on the Embody COMP. If the server is running, it automatically: 1. Stops the server on the old port 2. Restarts on the new port (after a 2-frame delay for clean shutdown) 3. Updates `.mcp.json` with the new port If the server is not running, changing the port simply updates the parameter value. ## Running Multiple Instances You can run multiple TouchDesigner instances with Envoy enabled in the same git repo. Each instance automatically claims a unique port from the range `[base_port, base_port + 9]` (default: 9870-9879). To switch between instances from Claude Code, use the `switch_instance` bridge meta-tool. See [Claude Code Integration](claude-code.md#working-with-multiple-instances) for usage details and [Architecture](architecture.md#multiple-instances) for how it works. ## Claude Code Integration When Envoy starts, it generates a full Claude Code configuration in your project root: - **`AGENTS.md`** - universal AI instructions, always written regardless of which clients are selected. If your repo already has its own `AGENTS.md`, Embody **merges** rather than replacing it: your content is left alone and Embody keeps a single delimited `` block inside the file, updated in place on later deploys. Uninstall removes just that block - **`CLAUDE.md`** - project context and critical rules - **`.claude/rules/`** - always-loaded conventions (TD Python, network layout, MCP safety) - **`.claude/skills/`** - on-demand workflow guides (operator creation, debugging, externalization) Pristine generated files are refreshed each time Envoy starts to stay up to date. If you edit a generated rule or skill, Embody detects the change - Embody stamps each file it generates with a hash of its own content, in the `` marker line - and keeps your version instead of overwriting it; delete the file to opt back into regeneration. The stamp is part of the file, so an edit you commit is still recognised on every other machine that clones the repo. See [Claude Code Integration](claude-code.md) for the full reference. ## MCP Tool Permissions By default, Claude Code asks for confirmation every time it wants to use an MCP tool. When you turn on the AI assistant in the [setup wizard](../embody/setup-wizard.md) (Claude Code only), a **"How should the AI ask permission?"** step lets you choose how much Embody pre-approves in `.claude/settings.local.json` - in both Auto and Advanced modes: | Choice | Effect | |---|---| | **Don't ask** (recommended) | Auto-approves **all** Envoy tools via the `mcp__envoy` wildcard - no prompts, and new tools are covered automatically. | | **Ask for some** | Auto-approves only read-only/query tools (`get_*`, `query_network`, `read_tdn`, `capture_top`, `capture_op`, ...). Anything that creates, edits, deletes, or executes still prompts. | | **Ask for all** | Pre-approves nothing - Claude Code prompts before every tool (the built-in default behavior). | | **Leave settings alone** | Embody does not create or modify `settings.local.json` at all - you manage permissions yourself. | The choice is stored on the **Tool Permissions** (`Toolpermissions`) parameter on Embody's Envoy page, so you can change it anytime without re-running the wizard. Every written posture (all but *Leave*) also whitelists your operating system's temp directory in `additionalDirectories`, so a TOP captured with `capture_top` (saved to the temp dir) can be read back without a permission prompt. Every written posture also pre-authorizes **sibling worktree folders**: Read/Edit rules for the `-wt-*` pattern beside your project root, computed at runtime from wherever your repo actually lives (any drive, any OS). The AI worktree workflow (`git worktree add ../-wt-` - see the generated `worktree-td-safety` rule) creates folders outside the workspace, which would otherwise trigger a permission prompt for every file the AI touches there. Settings written by older Embody versions gain these rules automatically the next time Envoy starts. Envoy also **mirrors the AI config into existing worktrees**: `.mcp.json` and `.claude/settings.local.json` are gitignored, so a fresh worktree checkout has neither - an AI session launched *inside* a worktree would find no Envoy MCP server and prompt for every tool. On each config deploy - and on every registry refresh (each project save) - Envoy copies both files into every sibling `-wt-*` worktree (identified by name pattern plus a `.git` entry), skipping files that are already up to date and leaving worktree-native sandboxes (a worktree with its own `.embody/envoy.json`) untouched. A worktree created mid-session picks up config at the next save; to hand it config immediately, copy the two files from the repo root. See [Git Worktrees](worktrees.md) for the full worktree workflow. **Existing files are preserved.** If a `.claude/settings.local.json` already exists, Embody updates only its Envoy tool entries and keeps everything else you have set (hooks, model, other `allow` patterns) - and it only rewrites when the posture actually changes. Choose *Leave settings alone* to keep Embody entirely hands-off. You can also edit `.claude/settings.local.json` directly at any time; the `allow` array lists tool-permission patterns. This file is gitignored. ## Fresh Clones and TD Version Matching When you clone a repo someone else built with Embody, the `.embody/envoy.json` file (which records the local TD install path) is gitignored - the path it references won't exist on your machine. On a fresh clone the bridge simply scans your standard TouchDesigner install locations (`/Applications/TouchDesigner*.app` on macOS, `C:\Program Files\Derivative\TouchDesigner.*` on Windows, `/opt/derivative/touchdesigner-*` on Linux) and launches the newest install it finds. If nothing is installed, the error response includes the Derivative download link. Once TD has run on your machine, Embody pins the build you used into the machine-local `.embody/local.json`, and later launches prefer the exact (or closest same-year) match for that pin - so your machine keeps launching the build **you** run, regardless of what your collaborators run. (Older repos may still carry a legacy `td_build` key in the committed `project.json`; it is tolerated as a fallback and removed automatically by newer Embody builds - a committed pin churned whenever collaborators ran different TD builds.) See [Architecture](architecture.md#embodylocaljson-build-pin-machine-local-and-embodyprojectjson-committed) for the full match policy. Envoy's *enablement* does travel: the committed `.embody/project.json` declares that the project uses Envoy, so a machine with no settings of its own turns it on at first open. What does not travel is `.mcp.json` itself - it hard-codes absolute venv and bridge paths, so it is written fresh when Envoy starts on your machine. If your AI client reports no Envoy server after cloning, see [A Cloned Project Has No `.mcp.json`](troubleshooting.md#a-cloned-project-has-no-mcpjson). ## Verifying the Connection After starting Envoy and your MCP client: 1. The Embody COMP should show **Envoy Enable** toggled on and a status indicator 2. Your MCP client should list the Envoy tools (e.g., `create_op`, `get_op`, `set_parameter`) 3. Try a simple command like "list all operators in the project" to verify the connection ============================================================================== # Envoy - Claude Code Integration # source: docs/envoy/claude-code.md ============================================================================== # Claude Code Integration When Envoy starts, it generates a complete Claude Code configuration in your project root. This gives Claude Code deep context about TouchDesigner development patterns, your project structure, and the MCP tools available through Envoy. ## Generated Files | File/Directory | Purpose | Regenerated on start? | |---|---|---| | `AGENTS.md` | Universal AI instructions (always written, whichever clients are selected) | Yes | | `CLAUDE.md` | Project context and critical rules | Yes -- or merged into, if the file is yours (see below) | | `.mcp.json` | MCP server connection config | Yes | | `.embody/envoy-bridge.py` | STDIO-to-HTTP bridge for MCP transport | Yes | | `.claude/settings.local.json` | Tool permissions and MCP server config | No - content follows your **Tool Permissions** choice; merges into an existing file, preserving your other keys | | `.claude/rules/` | Always-loaded conventions (see below) | Yes (unless edited) | | `.claude/skills/` | On-demand workflow guides (see below) | Yes (unless edited) | `AGENTS.md`, `CLAUDE.md`, `.claude/rules/`, and `.claude/skills/` are committed (not gitignored); the runtime files (`.mcp.json`, `.embody/`, `.claude/settings.local.json`) are automatically added to `.gitignore`. ### If you already have a `CLAUDE.md` Embody **merges** into it rather than replacing or skipping it. Your content is left exactly as written, and Embody maintains one delimited block inside the file -- opened by a visible `## Embody / Envoy -- auto-generated section` heading that says which half is which and where your own edits belong. Later deploys refresh that block in place, wherever you moved it. Uninstall removes only the block and leaves the rest of your file. Earlier versions instead wrote the guidance to a separate `ENVOY.md`. That preserved your file but delivered the instructions nowhere, because Claude Code does not auto-load `ENVOY.md`. Embody no longer writes that file; an `ENVOY.md` left over from an older version is not touched, and you can delete it once the block is present in your `CLAUDE.md`. The `Yes (unless edited)` files are refreshed from their templates on start **only while pristine**. Embody stamps each file it generates with a hash of its own content, in the `` marker line; once you edit a generated rule or skill the hash no longer matches, your version is preserved, and Embody says so in the log - delete the file to opt back into regeneration. Because the hash rides inside the file, that protection survives a clone: a teammate who pulls your edited rule keeps it too. See [How It Works](#how-it-works). ## Rules (Always-Loaded) Rules are loaded into every Claude Code conversation automatically. They provide conventions that prevent common mistakes when working with TouchDesigner. | Rule | What it covers | |------|----------------| | `network-layout.md` | Always-loaded layout invariants (200-unit grid, size+gap spacing, forward wire flow, docked-op hugging, annotation coverage); the full positioning recipe lives in `/create-operator` | | `td-python.md` | Parameter access (`.eval()` vs `.val`), operator path portability, threading, cook model | | `mcp-safety.md` | Thread boundary (never access TD from background thread), localhost binding, 30s timeout | | `parameters.md` | Custom parameter design: value access, required help text, section breaks, ordering, pages, naming, and styles | | `performance.md` | Performance gating protocol, stop conditions, and a safe-caps summary; the full crash-cause and safe-default-caps tables live in `/td-api-reference` (Heavy-Build Safety) | | `td-connectivity.md` | Session-start connectivity checks, the bridge reconciler and Envoy liveness watchdog, and manual recovery steps | | `multi-session.md` | The session-start presence check, `_peers` advisories and gate hard stops, and claiming a scope before big or destructive work | | `worktree-td-safety.md` | When to isolate multi-step edits in a git worktree instead of the live tree, and the discipline for landing that diff back | | `tdxn-economy.md` | Fewer operators, parameters and lines in every network that ends up in a `.tdxn`: measure the file by bucket, read parameters with a Parameter CHOP, share identical GLSL, let defaults carry the common case, verify a cut with a frame diff | ## Skills (On-Demand) Skills are loaded only when needed, keeping the context window lean. Claude Code loads them automatically before performing the relevant operation. | Skill | Trigger | |-------|---------| | `/create-operator` | Before creating or moving any operator (`create_op`, `copy_op`, `set_op_position`, or `execute_python` builds); carries the canonical positioning recipe | | `/create-extension` | Before creating TD extensions via `create_extension` | | `/debug-operator` | When diagnosing operator errors | | `/externalize-operator` | Before tagging or saving externalizations | | `/manage-annotations` | Before creating or modifying annotations | | `/td-api-reference` | Before writing TD Python code, and before any heavy build (its Heavy-Build Safety section holds the crash-cause and safe-caps tables) | | `/mcp-tools-reference` | Before the first MCP call in a session | | `/visual-aesthetics` | Before building or refining any rendered visual output (generative art, VJ visuals, shaders, scenes, renders) | | `/pop-networks` | Before POP networks, particle systems, or GPU point/geometry work | | `/movie-export` | Before recording or exporting any movie or image sequence | | `/parameter-design` | Before creating or designing custom parameters on a COMP | | `/td-recovery` | When Envoy/TD connectivity has not self-healed after ~15s | | `/multi-session-etiquette` | The moment a `_peers` advisory or a second AI session appears | | `/merge-divergent-tox` | When a merge or rebase conflicts on a `.tox`/`.toe`, or when comparing a component across branches, machines, or TD builds | | `/brief` | User-invoked: `/brief ` compiles a conversational ask into a task brief in `briefs/` (skills to load, anchors, success criteria, gates) that the work then executes from | | `/glsl-shaders` | Before writing GLSL or creating a `glslTOP`, `glslmultiTOP`, `glslMAT` or `glslPOP`: docked DATs, uniforms and the Colors page, TD's built-in functions, feedback and multi-pass, compile-error reading | | `/operator-gotchas` | Before wiring TOP, CHOP, MAT, DAT, light, camera or instancing operators you have not built before: abbreviated parameter names, defaults that silently misbehave, input-order rules, all verified live | | `/testing` | Before declaring a build, fix or show done, and before any soak or performance test: the verification ladder, `run_soak_test` and the observer-effect rules, iterate-by-capture, end-to-end rehearsal | | `/collab` | User-invoked: thinking-partner mode -- one small step at a time in the visible output, the next decision handed back; `/brief` returns to the autonomous default | Each skill contains step-by-step workflows, API details, and common pitfalls specific to that operation. Five skills (`td-api-reference`, `parameter-design`, `mcp-tools-reference`, `visual-aesthetics`, `merge-divergent-tox`) keep their long tables in a `references/` folder beside `SKILL.md`, seven files in all, so the skill itself stays short and loads cheaply. Envoy writes the reference files with the skill, and `get_guidance` serves one as `/` (for example `visual-aesthetics/look-recipes`). ## Task Briefs (`/brief`) For substantive, multi-step asks, Claude Code can compile your conversational request into a **task brief** before building - a short markdown contract that states, up front, everything a good build needs: - **Skills to load** - which of the skills above must be loaded before which tool call - **Anchors** - where the work happens, discovered from your live project (real container paths, never guesses) - **Success criteria** - only verifiable statements: a captured and assessed output frame, clean `get_op_errors`, fps within tolerance of the pre-build baseline - **Gates** - a performance baseline before building, multi-session claims, and flagged destructive steps that wait for your confirmation Two ways to invoke it: ```text /brief make the gallery wall react to the music ``` Everything after `/brief` is the request - as vague and conversational as you like; turning it into a precise contract is the skill's job. Or type a bare `/brief` after describing what you want in chat, and it formalizes the conversation's current ask. The compiled brief lands in `briefs/-.md` at your project root (gitignored - Embody manages the entry). Claude presents a summary for your approval, then executes **from the brief**: skills loaded at the stated moments, gates honored, every success criterion checked before "done." Because the brief is a file rather than chat history, it outlives the session - a fresh session or a sub-agent can pick it up and execute it without ever having seen the conversation. Trivial asks skip the ritual: a one-parameter change or a quick question doesn't need a brief, and the skill says so rather than taxing small requests. When a build goes wrong despite a brief, the miss is recorded in the brief's **Deviations** section and fed back into the skill - briefs get better the more you use them. `/brief` is user-invoked only: Claude won't run it on its own, though it may suggest it when a big ask arrives without one. ## STDIO Bridge Claude Code connects to Envoy through a STDIO bridge script (`.embody/envoy-bridge.py`) that translates between Claude Code's STDIO transport and Envoy's HTTP endpoint. The bridge provides four meta-tools that work even when TouchDesigner is not running: | Tool | Description | |------|-------------| | `get_td_status` | Check if TD is running, whether Envoy is reachable, crash detection, restart attempts remaining, and instance registry status | | `launch_td` | Launch TD with the project's `.toe` file and wait for Envoy to become reachable. On fresh clones (where `.embody/envoy.json`'s `td_executable` path doesn't exist locally), the bridge auto-picks a TouchDesigner install - the machine-local `.embody/local.json` build pin when present, the newest installed TD otherwise - see [Architecture](architecture.md#embodylocaljson-build-pin-machine-local-and-embodyprojectjson-committed). | | `restart_td` | Gracefully quit TD, then relaunch and wait for Envoy. Targets only this session's pinned instance's verified process (unpinned: the registry default's) - on machines running several TD projects, the others are never touched | | `switch_instance` | List all registered TD instances or switch the bridge to a different running instance | | `list_dialogs` | List the modal dialogs blocking TD (message boxes, missing-file prompts, the license box), with optional screenshots, even while TD's main thread is frozen | | `dismiss_dialog` | Dismiss a blocking dialog (close, then escape, then enter, verified gone) so the session can continue without a human at the machine | This means Claude Code can start a TD session from scratch - no need to manually open TouchDesigner first. If TD crashes, Claude can detect it and restart automatically. The bridge also handles crash-loop protection (max 3 launches in 5 minutes), automatic retry with backoff on transient connection failures, and orphan process cleanup when Claude Code exits. ### Working with Multiple Instances If you have multiple TouchDesigner instances running with Envoy enabled (e.g., your main project and a test project), the bridge connects to one at a time. Use `switch_instance` to move between them: - **List instances**: Call `switch_instance` with no arguments to see all registered instances and their reachability - **Switch**: Call `switch_instance` with the instance name (`.toe` filename without the extension) to redirect all subsequent MCP calls to that instance - **Address one call**: Pass `instance=` on any Envoy tool (every tool advertises the optional argument) to route just that call to another registered instance without switching - inspect the show file while pinned to the dev one, then carry on Each instance gets its own port automatically (ports 9870-9879). Switching is instant - no restart required. See [Architecture](architecture.md#multiple-instances) for technical details. ## How It Works Embody stores master copies of all rules and skills as template DATs inside the `templates` baseCOMP. When Envoy starts in a user project, `_extractClaudeConfig()` reads these templates and writes them to the project's `.claude/` directory. This means: - **Updates are automatic** - upgrading Embody gives you the latest rules and skills - **Templates are the source of truth for pristine files** - an unedited generated `.claude/` file is refreshed from its template on Envoy start, but Embody stamps each file it generates with a hash of its own content, in the `` marker line and will not overwrite one you've since edited (delete the file to opt back into regeneration). The stamp travels with the file, so the protection holds on a clone, a fresh checkout, or any machine that has never run Embody - **Project-specific customization** - add your own rules or skills to `.claude/` alongside the generated ones (they won't be overwritten) ## Live Build Visualization Two independent toggles on the Embody COMP's Envoy page control this, **both ON by default**: - **Envoy Follow** (`Envoyfollow`) - the camera follows the operator Envoy is working on, panning the network editor to it. - **Embot** (`Embotenable`) - the builder-bot mascot appears on each operator Envoy touches and narrates what it does. While the agent works through Envoy, with **Envoy Follow** on: - **Within the network you're viewing**, the editor smoothly **glides** to center on each operator just touched (ease-out, one step per frame). - **When the work moves to a COMP no pane is showing**, the editor **navigates** a network-editor pane into that COMP and snaps to frame the op - you can't glide across networks (different coordinate spaces), so it cuts. With **Embot** on: - A small **builder-bot** ("embot") - a figure made of minimal network-box annotations - **hops between the nodes** being worked on, hovers when idle, and throws an occasional gesture (a wave, a reach, a pump, the odd robot dance). Its color tracks "thinking time": cool cyan-green right after Envoy acts, warming toward red the longer the gap. The node Envoy just touched pulses the Envoy accent. Embot **settles rather than chases**: rebuilding him in a new network is real main-thread work, so when the agent is hopping between networks he stays where the work actually lives, keeps hopping between the operators *there*, and keeps narrating the current op from where he stands. He relocates once the work has genuinely settled somewhere new (or a queued batch proves it is about to), and if the work never settles anywhere he still moves in after a few seconds rather than standing on a stale node forever. The node-colour pulse still fires on every operator Envoy touches, in every network. With **Embot** off, **Envoy Follow** cuts to every hop exactly as before. With **Envoy Follow** off but **Embot** on, he appears only in the network you are already viewing - building nine annotations into a network the camera will never travel to costs real frame time for something nobody can see. Navigate to where the agent is working and he arrives there. It **yields the instant you pan, zoom, or navigate** the view yourself, and resumes only once you stop - it never yanks the view mid-interaction. The bot and pulse retire after a stretch of quiet. The agent never sees him either: Envoy's read tools (`get_annotations`, `get_network_layout`, `query_network`, `find_children`, `get_enclosed_ops`) filter his parts out and report how many they hid as `embot_hidden`, so nine annotations that belong to no `.tdxn` can't be mistaken for part of your network. This is purely a viewing aid: it writes only pane/view state (which TouchDesigner never externalizes), the bot is destroyed before every save, and it runs entirely on the main thread, so it adds nothing to your saved files and never affects a build. Leave it off if you'd rather your view never move on its own. ## Customization You can extend the generated configuration: - **Add project-specific rules**: Create additional `.md` files in `.claude/rules/` - Claude Code loads all rules in this directory - **Add custom commands**: Create `.md` files in `.claude/commands/` with prompt instructions - **Modify permissions**: Set the **Tool Permissions** parameter on Embody's Envoy page (or re-run the [setup wizard](../embody/setup-wizard.md)) to choose how much Embody auto-approves - all tools, read-only tools only, nothing, or leave the file untouched. See [MCP Tool Permissions](setup.md#mcp-tool-permissions). You can also hand-edit `.claude/settings.local.json` to allow or restrict specific tools. !!! tip You can edit the Envoy-generated rules and skills directly - Embody stamps each file it generates with a hash of its own content, in the `` marker line, so it won't overwrite one you've changed (it logs that it kept your edits). Commit your edited file and it stays protected everywhere: the hash is inside the file, not in a machine-local sidecar. Pristine generated files still refresh on regeneration; delete a file to discard your changes and pull the latest template. ============================================================================== # Envoy - Tools Reference # source: docs/envoy/tools-reference.md ============================================================================== # Tools Reference Envoy exposes 70 MCP tools for interacting with TouchDesigner, plus 24 bridge meta-tools: 6 TD-lifecycle tools and 18 `convoy_*` LAN work-relay tools (all listed below). All tools use the standard MCP protocol and can be called by any compatible client. Two of the 70 (`convoy_lifecycle_state`, `convoy_lifecycle_quit`) are internal Convoy host-lifecycle tools: they refuse any session other than the Convoy host app's dedicated loopback session and are not for agent use. Every mutating TD-authoring tool call is wrapped in a TouchDesigner undo block. Press Ctrl+Z in TD to revert an agent change; a `batch_operations` call is one undo step for the whole batch. Responses are compact by default; opt-in flags such as `include_defaults` and `details` return full detail when needed. ## Operator Management | Tool | Parameters | Description | |------|-----------|-------------| | `create_op` | `parent_path`, `op_type`, `name?`, `language?` | Create a new operator (e.g., `baseCOMP`, `noiseTOP`, `textDAT`, `gridPOP`). A `textDAT` is created with Content Language `python`; pass `language` (`glsl`, `json`, `yaml`, `xml`, `text`) for any other content, which also gives an auto-externalized DAT the matching file type | | `create_extension` | `parent_path`, `class_name`, `name?`, `code?`, `promote?`, `ext_name?`, `ext_index?`, `existing_comp?` | Create a TD extension: baseCOMP + text DAT + extension wiring, initialized and ready to use | | `delete_op` | `op_path`, `override?` | Delete an operator. Also purges its externalization tracking (any strategy) and the externalized file - unless the file is clone-owned or still referenced by another operator. Refused while another live session claims the scope or wrote it in the last minute; `override=True` bypasses that gate. Refuses the Embody COMP, its ancestors, `/` and Envoy's own extension DAT (`envoy.embody.host_destroy_refused`); `override=True` does not bypass that check | | `copy_op` | `source_path`, `dest_parent`, `new_name?` | Copy operator to new location | | `rename_op` | `op_path`, `new_name` | Rename an operator | | `get_op` | `op_path`, `include_defaults?` | Get operator info. Parameters are NON-DEFAULT only by default; pass `include_defaults=True` for all parameters. Parameter-heavy COMPs are expensive in full detail, so prefer `read_tdxn` for structure reads. `inputs` has one entry per input connector, `null` for an empty one - entry position IS the real connector index | | `query_network` | `parent_path?`, `recursive?`, `op_type?`, `include_utility?` | List operators in a container. Child rows are compact: `path`, `type`, `family`, `depth` (`name` is derivable from the last path segment). Set `include_utility=True` to include annotations | | `find_children` | `op_path`, `name?`, `type?`, `depth?`, `tags?`, `text?`, `comment?`, `include_utility?` | Advanced search using TD's `findChildren` - filter by name pattern, type, depth, tags, text content, or comment | | `cook_op` | `op_path`, `force?`, `recurse?` | Force-cook an operator | ## Parameter Control | Tool | Parameters | Description | |------|-----------|-------------| | `set_parameter` | `op_path`, `par_name`, `value?`, `mode?`, `expr?`, `bind_expr?` | Set a parameter's value, expression, bind expression, or mode (`constant`/`expression`/`export`/`bind`). Invalid Menu values are rejected with valid `menuNames`; sequence-block names auto-grow their sequence (`const5name` grows `numBlocks` to 6). A reload or clone pulse (`enableexternaltoxpulse`, `reinitnet`, `enablecloningpulse`) on the Embody COMP, an ancestor, `/` or Envoy's extension DAT is refused (`envoy.embody.host_destroy_refused`) | | `get_parameter` | `op_path`, `par_name?`, `search?`, `search_in?`, `depth?`, `max_results?`, `details?` | Get one parameter compactly, or search parameters by glob/substring across a subtree. Search fields: `name`, `value`, `expr`, or `any` | Search mode omits `par_name` and passes `search`. It scans the target operator and children to `depth` (default 2) using fnmatch glob semantics; patterns without `*?[` become contains searches. Results are `{root, pattern, search_in, count, results, truncated?}`, where each hit includes `op`, `par`, `value`, `mode`, and `expr` or `bindExpr` when present. `search_in='value'` evaluates every parameter it scans (expressions included), so expression side effects and cooking cost are on the caller; `search_in='any'` only evaluates constant-mode values and matches expression/bind parameters by text. Single-parameter mode returns `path`, `parameter`, `value`, `mode`, `label`, mode-specific refs (`expression`, `bindExpr`, `bindMaster`, `exportOP`), and `menuNames` for Menu parameters. Pass `details=True` to include defaults, custom/read-only/style metadata, numeric ranges, `menuLabels`, and `menuIndex`. Search mode ignores `details`. **Example** -- find expressions under `/project1` that reference absolute paths in that subtree: ```json {"op_path": "/project1", "search": "*/project1/*", "search_in": "expr", "depth": 10, "max_results": 100} ``` ## DAT Content | Tool | Parameters | Description | |------|-----------|-------------| | `get_dat_content` | `op_path`, `format?` | Get DAT text or table data (`"text"`, `"table"`, `"auto"`), or `"stats"` to reduce a table to per-column min/max/mean (numeric) or distinct counts (text) plus head/tail rows -- use it instead of dumping a large table into context | | `set_dat_content` | `op_path`, `text?`, `rows?`, `clear?`, `confirm_wipe?` | Full-replace DAT content. Wipe guardrail refuses `text=""`, `rows=[]`, or `clear=True` with no content unless `confirm_wipe=True` is passed. For partial edits to text DATs, prefer `edit_dat_content` -- it sends only the changed substring. | | `edit_dat_content` | `op_path`, `old_string`, `new_string`, `replace_all?`, `confirm_wipe?` | Surgical text edit on a DAT (mirrors Claude Code's Edit tool). Replaces `old_string` with `new_string`. By default `old_string` must appear exactly once -- pass `replace_all=True` to replace every occurrence. Token-efficient: only the changed substring crosses the wire. Text DATs only; use `set_dat_content(rows=...)` for tables. | ## CHOP / POP Data Reduced reads -- never a blind dump. A 4x600 CHOP is 2,400 raw floats; these return the shape and range instead. | Tool | Parameters | Description | |------|-----------|-------------| | `get_chop_data` | `op_path`, `channels?`, `samples?`, `compare_to?` | Per-channel `min`/`max`/`mean`/`std`/`first`/`last`, capped at 32 channels. `channels` is a name glob; `samples>0` adds head/tail raw values. `compare_to` another CHOP adds a `diff` of per-channel deltas -- the "what did this chain do to my data" read | | `get_pop_data` | `op_path`, `attributes?`, `samples?`, `max_points?` | Point/prim/vert attribute metadata (name, size, type). Metadata costs ~0.02ms at ANY point count; reading point VALUES is a GPU->CPU readback (~9.5ms at 16k points, ~69ms at 160k -- about 4 frames at 60fps), so `samples>0` is opt-in and refused above `max_points` (default 50,000) | **Why the POP guard is on point count, not sample count**: `POP.points(attr, startIndex, count)` accepts both slicing arguments and ignores them (verified on 2025.33070) -- the readback happens regardless. Asking for 4,096 points from a 160k POP measured *slower* than reading all of them. Reach for `samples` only when you actually need values, and prefer a smaller upstream POP for inspection. The reduce-don't-dump contract for CHOP and DAT reads is adapted from the `view` tool in Marius Alwan Meyer's code-mode fork of Embody ([sporqist/Embody](https://github.com/sporqist/Embody), MIT). The POP reader and its readback ceiling are Embody's own. ## Operator Flags | Tool | Parameters | Description | |------|-----------|-------------| | `get_op_flags` | `op_path` | Get all flags: bypass, lock, display, render, viewer, current, expose, selected, allowCooking | | `set_op_flags` | `op_path`, `bypass?`, `lock?`, `display?`, `render?`, `viewer?`, `current?`, `expose?`, `allowCooking?`, `selected?` | Set one or more flags on an operator | ## Positioning & Layout | Tool | Parameters | Description | |------|-----------|-------------| | `get_op_position` | `op_path` | Get operator position, size, color, and comment | | `get_network_layout` | `comp_path`, `include_annotations?` | Get compact positions of ALL operators (and annotations) in a COMP in one call. Operators include `path`, `type`, `nodeX`, `nodeY`, `nodeWidth`, `nodeHeight`; centers are derivable as `nodeX+nodeWidth/2` and `nodeY+nodeHeight/2`. Annotation text is capped at 160 chars. Returns `bounding_box` | | `set_op_position` | `op_path`, `x?`, `y?`, `width?`, `height?`, `color?`, `comment?` | Set operator position, size, color (`[r,g,b]` floats 0-1), or comment | | `layout_children` | `op_path` | Auto-layout all children in a COMP | ## Annotations | Tool | Parameters | Description | |------|-----------|-------------| | `create_annotation` | `parent_path`, `mode?`, `text?`, `title?`, `x?`, `y?`, `width?`, `height?`, `color?`, `opacity?`, `name?` | Create an annotation. Modes: `"annotate"` (default, has title bar), `"comment"`, `"networkbox"`. Created `utility=True` (matching TD UI-drawn annotations): visible to `get_annotations`, hidden from `query_network`/`find_children` unless `include_utility=True`. Every op-path tool still resolves it by path; delete with `delete_op` (durable), never a raw `.destroy()` | | `get_annotations` | `parent_path` | List all annotations in a COMP with their properties and enclosed operators | | `set_annotation` | `op_path`, `text?`, `title?`, `color?`, `opacity?`, `width?`, `height?`, `x?`, `y?` | Modify properties of an existing annotation | | `get_enclosed_ops` | `op_path` | Get operators enclosed by an annotation, or annotations enclosing an operator | ## Connections | Tool | Parameters | Description | |------|-----------|-------------| | `connect_ops` | `source_path`, `dest_path`, `source_index?`, `dest_index?`, `comp?` | Wire two operators together. Set `comp=True` for COMP connectors (top/bottom) | | `disconnect_op` | `op_path`, `input_index?`, `comp?` | Disconnect an operator's input. Set `comp=True` for COMP connectors (top/bottom) | | `get_connections` | `op_path` | Get all input/output connections (includes COMP connections for COMPs). Inputs are reported **per connector**: one entry per input connector carrying its real `index`, with `connected_to: null` for an empty connector - nothing is compacted away, so a wire on connector 2 reports as index 2. Dynamic multi-input ops (Switch, Composite) always show one trailing empty connector, the growth slot | ## Performance Monitoring | Tool | Parameters | Description | |------|-----------|-------------| | `get_op_performance` | `op_path`, `include_children?` | Get CPU/GPU cook times (milliseconds), memory usage (bytes), cook counts | | `get_project_performance` | `include_hotspots?` | Get project-level FPS, frame time, GPU/CPU memory, dropped frames, active ops, GPU temp. Optional hotspot ranking of top N COMPs by cook time | | `run_soak_test` | `duration_s?`, `interval_s?`, `fps_target?`, `label?`, `stop?`, `idempotency_key?` | Low-overhead performance soak as a background job. Samples Envoy's Perform CHOP on the frame hook -- three channel reads per frame, memory and op counts once per interval, nothing cooked, captured or created -- so the instrument does not move the needle it reads. Envoy calls that cook, capture, write or execute during the run are logged as perturbations and their 2 s neighborhood is excluded from the clean statistics. Finishes with per-metric first/last/min/max/mean/slope, exact dropped-frame counts, worst frame time, GPU headroom, hotspots at start and end, up to 600 samples, and a PASS/WARN/FAIL verdict on the performance rule's thresholds. Poll `get_job_status`; `stop=True` ends it early | ## Code Execution | Tool | Parameters | Description | |------|-----------|-------------| | `execute_python` | `code` | Execute Python in TD; set the `result` variable to return values. Auto-lints newly-created ops and emits a **LAYOUT WARNING** when they are left at (0,0) or overlapping (unlike `create_op`, raw `comp.create()` does not auto-position). Also statically lints the submitted source (as do `set_dat_content` / `edit_dat_content` for Python written to DATs) and emits a **THREADING WARNING** when a thread target calls TD's `run()` -- worker-side `run()` silently corrupts TD state and crashes later (Derivative-confirmed 2026-08-17). Refused before anything runs (`envoy.embody.host_destroy_refused`) when the code would destroy or reload the Embody COMP, an ancestor, `/` or Envoy's extension DAT in the same call -- `me` and `parent()` are the Embody COMP here; see [Troubleshooting](troubleshooting.md#touchdesigner-freezes-after-deleting-or-moving-embody) | ## Introspection & Diagnostics | Tool | Parameters | Description | |------|-----------|-------------| | `get_td_info` | _(none)_ | Get TD version, build, OS, and Envoy version | | `get_op_errors` | `op_path`, `recurse?` | Errors and warnings for an operator and its children. Covers all three surfaces TD reports red: cook errors, Python tracebacks from callbacks/DAT scripts/expressions (`OP.scriptErrors`, tagged `kind: "script"` in `errors[]`), and GLSL compile failures (separate `shaderErrors` key) | | `exec_op_method` | `op_path`, `method`, `args?`, `kwargs?` | Call a method on an operator (e.g., `appendRow`, `cook`). `destroy`, `reload`, `changeType` and `progressiveUnload` on the Embody COMP, an ancestor, `/` or Envoy's extension DAT are refused (`envoy.embody.host_destroy_refused`) | | `get_td_classes` | _(none)_ | List all Python classes/modules in the `td` module | | `get_td_class_details` | `class_name` | Get methods, properties, and docs for a TD class | | `describe_op_type` | `op_type`, `pattern?`, `page?`, `include_menus?` | Parameter names, labels, styles, creation defaults and menu values for an operator TYPE before it exists -- the look-before-you-guess read. Probes a throwaway instance in `/sys/quiet` (cooking disabled, outside the project) and caches per type for the session. `pattern` is a glob or substring over names AND labels, `page` narrows to one page. An unknown type returns `did_you_mean`; a filter that matches nothing returns a `hint` (the name guess was wrong, not the operator) | | `get_module_help` | `module_name` | Get Python help text for a module (supports dotted names like `td.tdu`) | | `get_docs` | `query`, `section?`, `source?`, `max_chars?` | Look up official TouchDesigner docs. `source` is `auto` (offline then web), `offline`, or `web`; normal responses carry `title`, `source`, `sections_available`, `content`, and optional `url`/`truncated`; ambiguous offline lookups return `source` + `matches` only | | `get_guidance` | `topic?` | Serve this project's checked-in TouchDesigner doctrine (`.claude/rules/*.md`, `.claude/skills/*/SKILL.md` and each skill's `references/*.md`) over MCP, so agents on a client with no skills folder (VS Code, Copilot, Windsurf) get the same rules Claude Code loads; Codex, Cursor, Gemini and Antigravity read `.agents/skills/`, OpenCode reads `.claude/skills/`. Bare call lists topics; `topic` returns that document, and `/` a skill's reference file. Answered worker-side (no TD round-trip) | | `get_focus` | _(none)_ | What the user is looking at: current pane network, selected operator(s), current op, and rollover. When the user says "this operator" they mean the SELECTED/current op -- rollover is incidental mouse position and must not be acted on | ## Embody Integration | Tool | Parameters | Description | |------|-----------|-------------| | `externalize_op` | `op_path`, `tag_type?` | Tag and externalize operator to disk (auto-detects type if omitted). Never shows the locked-content dialog: a TDXN export with locked TOP/CHOP/SOP/POP operators logs one WARNING (in `_logs`) naming each operator's source and the COMP to tag `tox` | | `remove_externalization_tag` | `op_path`, `delete_file?` | Remove externalization tracking (tag + row + TDXN breadcrumb); `delete_file=True` also deletes the file (best-effort). Returns `removed_tags`, `removed_rows`, `removed_anything`, `summary` -- an operator can have a tracked row but NO tag, so check `removed_anything`, not `removed_tags`, to confirm cleanup | | `get_externalizations` | _(none)_ | List all externalized operators with status | | `save_externalization` | `op_path` | Force save an externalized operator to disk. Refuses to overwrite a non-empty file with an operator-empty COMP and returns an error instead - untrack the operator or delete the file if the empty state is intended. Like `externalize_op`, it logs locked-content findings instead of showing the dialog | | `get_externalization_status` | `op_path` | Get dirty state, build number, timestamp, file path | ## TDXN Format | Tool | Parameters | Description | |------|-----------|-------------| | `read_tdxn` | `comp_path?`, `include_dat_content?`, `max_depth?`, `embed_all?` | **Preferred for reading >=3 operators.** Return the live network as a TDXN dict (in-memory, never written to disk). ~20-90x fewer tokens than a `get_op` walk thanks to default-omission, `type_defaults`, and `par_templates` compaction | | `export_network` | `root_path?`, `include_dat_content?`, `output_file?`, `max_depth?`, `embed_all?` | Write a `.tdxn` file to disk. Same payload as `read_tdxn` plus file I/O. Set `embed_all=True` to recurse into TDXN-tagged COMPs instead of skipping their children (self-contained export) | | `import_network` | `target_path`, `tdn`, `clear_first?`, `override?` | Recreate a network from a `.tdxn` file. Nested externalized-TDXN children are rebuilt from their own `.tdxn` files in the same import, recursively, so no nested COMP is left an empty shell; the result's `restored_tdn_shells` lists what was restored. With `clear_first=True`, gated against live peer sessions like `delete_op`. `clear_first` into the Embody COMP, an ancestor or `/` is refused (`envoy.embody.host_destroy_refused`) | | `diff_tdxn` | `target?`, `max_changed_ops?`, `max_bytes?` | **What is UNSAVED in TDXN networks** -- the live in-memory network vs the on-disk `.tdxn`, the view git cannot give. Omit `target` for a whole-project summary (every live TDXN COMP, which changed + counts); pass a COMP path OR a `.tdxn` file path/bare filename for one COMP in full per-field detail (`old`=disk, `new`=live). For committed/history diffs use plain `git diff`. Read-only, non-interactive | ## TOP Capture | Tool | Parameters | Description | |------|-----------|-------------| | `capture_op` | `op_path`, `format?`, `quality?`, `max_resolution?`, `inline?` | Capture any operator's current output as an image. A TOP is read natively; every other family (CHOP, SOP, POP, DAT, COMP, MAT) renders through a transient OP Viewer TOP -- what the network editor's viewer shows -- created inside the Embody COMP for the call and destroyed after (the capture waits a few frames for it to render, and the returned text says a viewer was used). Same temp-file return and Quality verdict as `capture_top`; `max_resolution` is the viewer's render width (16:9) for a non-TOP. | | `capture_top` | `op_path`, `format?`, `quality?`, `max_resolution?`, `inline?`, `sample_grid?` | Capture a TOP's output as an image (TOP only; any other family -> `capture_op`). Saves to a temp file and returns the path -- Read that path to view it. Inline base64 previews are token-heavy, so they are **off by default** (`inline=False`); pass `inline=True` to also embed a small preview. Small images (<20 KB) include the inline MCP `ImageContent` preview when requested. Default: JPEG at 80% quality, max 640px long edge. Pass `sample_grid>=2` to return a downsampled NxN RGBA grid instead of an image: row 0 is the top of the image, stats are computed over the full-resolution texture, the requested grid clamps to 2..32, the returned `grid` is further capped to the TOP's width/height and can drop below 2 on tiny textures, and image params are ignored. Channel padding: RG -> b=0/a=1, mono -> replicated/a=1, monoalpha -> replicated + real alpha; `channels` reports the raw plane count. Every capture also returns a **Quality verdict** from the raw float pixels (`is_black` / `is_flat` / `fully_transparent` / `pass` + `fail_reasons`), surfaced as a `Quality: OK\|FAIL` line so you can tell an empty/black/transparent render from a real one without reading the image (black and fully-transparent are failures; a uniform fill is advisory, `flat_frame`). | ## Multi-Session Awareness Concurrent AI sessions (multiple Claude Code windows, other MCP clients) working on the same project are tracked, warned about each other, and gated away from destroying each other's work. See [Multi-Session Coordination](multi-session.md) for the full picture. | Tool | Parameters | Description | |------|-----------|-------------| | `get_sessions` | - | List connected AI sessions: label (`repo@branch`), idle time, `recent_scopes` it modified, `claims` it holds, plus `you` (the caller's own session id). May include `worktrees`: in-flight durable worktree tasks, visible even after their session ended | | `claim_scope` | `scope`, `note?`, `ttl?` | Cooperative write lease on an op-path prefix, a `file:` path, or a `project:` scope. Peers' overlapping claims are refused while yours is live; their destructive operations on it are gated. Auto-renews on your own writes; expires on TTL or session silence | | `release_scope` | `scope` | Release a lease you hold. Polite - expiry also handles it | | `announce_task` | `title`, `scopes?`, `note?` | Announce a unit of work to the shared task ledger so parallel sessions see what is in progress and what is finished-but-uncommitted; active entries ride on `get_sessions` | | `update_task` | `task_id`, `status?`, `note?`, `commit?` | Transition a ledger task (`done_uncommitted` / `committed` with sha / `abandoned`); any session may update any task, non-owner writes record `updated_by` | | `preflight_landing` | `worktree_path` | Landing safety check for a git-worktree diff: intersects the files it would land with main-tree dirt, peer `file:` claims/touches, and unsaved live TDXN state. Run before porting any worktree diff; a `conflicts` verdict means reconcile first | !!! info "Auto-piggybacked peer advisories" A `_peers` field rides on any response whose request touches territory another session modified in the last ~10 minutes - one entry per peer: `{label, scope, tool, age_s, conflict}`. `conflict: true` means a peer *wrote* an overlapping scope within the last minute and your operation is also a write - stop and coordinate. !!! warning "Destructive-operation gate" `delete_op`, `import_network` with `clear_first=True`, `run_tests`, and batches containing them are refused with a `MULTI-SESSION GATE` error (naming the holder or recent writer) while a live peer session claims the scope or wrote it within the last minute. Pass `override=True` only when you are certain. ## Logging | Tool | Parameters | Description | |------|-----------|-------------| | `get_logs` | `level?`, `count?`, `since_id?`, `source?` | Get recent log entries from ring buffer. Filter by level, source, or use `since_id` for incremental polling | | `run_tests` | `suite_name?`, `test_name?`, `override?`, `background?`, `idempotency_key?` | Run test suites. `background=True` (recommended for full runs) returns a job id immediately and parks results in `.embody/jobs/` -- poll `get_job_status`; the synchronous mode is severed by the watchdog suites' server restart. `idempotency_key` is background only -- a retry with the same key reconciles to the original run's job handle instead of starting a second run (passing it without `background=True` is refused). Gated while a peer session holds `project:tests` | !!! info "Auto-piggybacked logs" When a tool call generates `WARNING` or `ERROR` entries since the previous call, the response carries a `_logs` field with up to the last 8 of them. `INFO`/`DEBUG`/`SUCCESS` history does not ride along - fetch it on demand with `get_logs`. Warning cursors are tracked per session, so concurrent AI sessions each receive their own copy - one session polling first no longer consumes a warning meant for everyone. !!! info "Unattended sessions" Nobody answers a dialog in an unattended session, so preset the Embody parameter that decides it: `Tdxnpalettehandling` (palette Black Box vs Full Export), `Filecleanup` (deleted-file prompt), `Tdxnlockedwarn` (`quiet`) and `Tdxndatsafety` (the save-time content report). Saves never prompt. Save through `save_project` and read the save's warnings in `get_job_status(job_id)["warnings"]`: the save reinitializes extensions, so they may never ride `_logs`. !!! info "Auto-attached recovery hints" When a tool returns an `error`, Envoy attaches a `recovery_hints` list - each entry `{code, cause, action, next_tools}`, matched to the real error string (path-not-found -> `query_network`/`find_children`, parameter-not-found -> `get_op`, wrong family, empty capture -> `get_op_performance`, thread conflict, timeout -> `get_project_performance`). Additive, never clobbers, never raises - follow the hint instead of retrying the same failing call. !!! info "Stable error codes" Every error envelope also carries `error_code`, a machine id of the form `envoy..`: `envoy.op.not_found`, `envoy.par.not_found`, `envoy.parent.not_comp`, `envoy.op.wrong_family`, `envoy.top.empty`, `envoy.capture.failed`, `envoy.thread.violation`, `envoy.op.unknown_type`, `envoy.timeout`, `envoy.session.gated`, `envoy.dat.wipe_refused`, `envoy.project.unsaved`, `envoy.embody.unavailable`, `envoy.docs.lookup_failed`, `envoy.job.error`, `envoy.embody.host_destroy_refused` (a destroy or reload of Envoy's own host, refused -- see [Troubleshooting](troubleshooting.md#touchdesigner-freezes-after-deleting-or-moving-embody)) - and `envoy.error` when no rule matches. Branch on the code, not the message: messages may be reworded, codes may not. !!! info "Write effects and shader lint" Every write tool's response may carry `_effects`: errors and warnings that appeared after your write, a meaningful fps drop, and - for DAT writes - the compile state of every GLSL operator that consumes that DAT, whether it is the DAT's dock host or references it by parameter from anywhere in the project. `shaders_checked` lists what was linted (a quiet footer means compiled clean, not unchecked), `new_shader_errors` the failures your write introduced, and `shader_errors_persist` a shader still failing after a later write, so silence never reads as fixed. ## Background Jobs Long operations that outlive the 30-second operation timeout run as disk-backed jobs: the starting tool returns a `job_...` handle immediately, results park in `.embody/jobs/` (surviving server restarts and extension reinits), and `get_job_status` polls. | Tool | Parameters | Description | |------|-----------|-------------| | `get_job_status` | `job_id?` | One job record (status `running`/`done`/`error`, result when done, `stale` when a running record stopped heartbeating), or the 16 newest records without `job_id`. A `run_soak_test` job carries `progress` (elapsed, last sample, summary and verdict so far) while running and `result` (summary, verdict, reasons, samples) when done. A finished `run_tests` job carries the summary with failures listed first; a finished `save_project` job carries `version_before`/`version_after` and `warnings` (the WARNING/ERROR lines logged during the save: errors first, then oldest first, repeats collapsed, at most 8 plus a `(+N more)` entry; INFO lines stay in `get_logs`) | | `save_project` | `idempotency_key?` | Save the project as a tracked job. **A development tool, not for shows:** a save blocks TouchDesigner's main thread for 15+ seconds and restarts the Envoy server, so never run it against a machine running a show. Refused in Embody's Perform Mode or TouchDesigner's perform window (`code: perform_mode`, no job started); Convoy relays it to remote nodes without the TD Python grant, under the same refusal. Refused while a test run is active (a mid-run save bakes test-forced parameters into the export); idempotent -- a second call while a save is in flight returns the existing handle, and the same `idempotency_key` extends that dedupe to a retry of any age, reconciling it to the original save instead of queuing a second one. The next call after a save may fail once while the bridge reconnects. The finished record lists the save's warnings (`warnings`) | | `update_embody` | `idempotency_key?` | Self-update Embody to the latest GitHub release as a tracked job -- bounded and non-interactive (sha256-pinned manifest, downgrade-refusing, TD-build-floor-gated), so it never needs the TD Python grant. Refused in Perform Mode (`code: perform_mode`) and while a test run is active. A finished record carries `version_before`/`version_after`; an up-to-date node finishes `done` with them equal. The install restarts the MCP server -- expect one reconnect blip | ## Bridge Meta-Tools These tools run locally on the STDIO bridge script, not inside TouchDesigner. They work even when TD is not running, or is frozen behind a modal dialog - this is how Claude Code can launch or restart TD without an active Envoy connection. | Tool | Parameters | Description | |------|-----------|-------------| | `get_td_status` | _(none)_ | Check if TD is running, Envoy reachable, crash detection, process liveness, restart attempts remaining. `envoy_unresponsive` / `unresponsive_since` (process alive, port accepting, Envoy silent 60s or more) and `main_thread_stalled` / `stalled_since` (Envoy answers, but TD's main thread has not run its request loop for 60s or more) flag a frozen TouchDesigner. `pin_unavailable` says this session's pinned instance left the registry, so calls have no target | | `launch_td` | `timeout?`, `project_path?` | Launch TD with this session's pinned instance's `.toe` (unpinned: the registry default's). Waits for Envoy to become reachable (default: 120s). Pass `project_path` (absolute, or relative to the git root) to open a different `.toe` | | `restart_td` | `timeout?`, `project_path?` | Gracefully quit TD and relaunch. Waits for exit before relaunching (default: 120s). Pass `project_path` to relaunch with a different `.toe`. Targets only this session's pinned instance's verified process (unpinned: the registry default's) - other running TouchDesigner instances are never touched | | `list_dialogs` | `instance?`, `screenshot?` | List the modal dialogs a TD instance shows (message boxes, missing-file and save-changes prompts, the license box, file pickers). Runs on the bridge, so it answers while TD's main thread is blocked. TouchDesigner draws its own dialogs, so their text is not readable through the OS: `screenshot=true` saves a PNG of each to the temp dir to Read. `blocked=true` when a dialog is up. macOS backend is unverified. | | `dismiss_dialog` | `instance?`, `dialog?`, `action?` | Dismiss a blocking dialog and verify it is gone. `action=auto` (default) runs close (WM_CLOSE) -> escape -> enter until the window disappears; a single rung tries only that. `dialog` picks by title substring or window id (default: the first). The main TouchDesigner window is never a target. Failure is `envoy.dialog.stuck` with what was tried. | | `switch_instance` | `instance?`, `all_sessions?` | List all registered TD instances (omit `instance`) or re-pin **this session's** bridge to a different running instance; other sessions are untouched unless `all_sessions=true`. If the pinned instance leaves the registry (closed, crashed), the session has no target: calls fail with `error_code` `envoy.instance.unavailable` and nothing is forwarded until it re-registers or you switch (a call that names another instance with `instance=` still goes there). For a single call, pass `instance=` on any Envoy tool instead: the bridge routes that one call to the named instance and leaves this session's pin alone (an unknown or unreachable name fails only that call, with `error_code` `envoy.instance.unknown` / `envoy.instance.unreachable`). See [Multiple Instances](architecture.md#multiple-instances) | ### Convoy Tools (LAN work relay) The remaining 18 meta-tools drive [Convoy](../convoy/index.md), relaying work to Convoy-enabled Embody nodes on the trusted LAN through the local per-user host app. Status and inventory calls never wake TouchDesigner. | Tool | Description | |------|-------------| | `get_convoy_status` | Is the local Convoy host app available, and what does it know. `host_status` carries the host's `advisories` (each `{kind, text}`: `realm_conflict`, `identity_reminted`, `handshake_refusals`, `peer_identity_changed`, `lan_bind`), its `lan` posture (bound address, adapter, network category, warning or refusal reason), `inbound_refusals` (refused LAN handshakes in the last 10 minutes and which admitted peers sent them), `identity_reminted` and `peers_mismatched` | | `convoy_list_nodes` | `machines`: one row per computer with its open projects, status and last-seen age. `nodes`: every project those machines know about, closed ones included, with `embody_version` and `host_app_version` per node, `offline_reason` on an offline row (`no_relay_port`: the node heartbeats but its Envoy serves no relay port; `stalled`: its TouchDesigner is alive but its frame loop stopped; `heartbeat_stale`; `no_runtime`: its TouchDesigner unregistered on exit), `compatibility` with `compatibility_reason` (protocol, shared-operation counts, the peer's host-app version), and a `capabilities` field (`td_python`, `full_shell`) on local nodes -- remote nodes carry none by design (grants are never advertised across the LAN; absent = unknown) | | `convoy_list_controllers` | Live client sessions, selected targets, leases, and active work | | `convoy_ping` | One node's liveness through its host app, without waking TouchDesigner | | `convoy_select_node` | Pin this session to one exact node so ordinary Envoy tools run there (`clear=true` to unpin) | | `convoy_call` | One-off registered operation on an explicit target, without changing the selection. Every registered node operation except `run_tests` relays to another computer; `save_project` does too, but it stalls the target's TouchDesigner 15+ seconds and is refused in Perform Mode -- development only | | `convoy_batch` | The same ordered batch on one or more explicit targets, reported per target | | `convoy_get_job` | Check durable work that outlives the original call or reconnect | | `convoy_ack_job` | Acknowledge a finished delivery so the target can release its protected result artifacts | | `convoy_cancel_job` | Request cancellation from the exact owning host | | `convoy_forget_node` | Delete a stale node row on THIS machine's host app (refuses only while a delivery has not FINISHED, naming the blocking delivery ids; a finished result never holds a row); dead and long-unseen rows are also evicted automatically | | `convoy_get_artifact` | Retrieve and verify a large result into a temporary local file by artifact reference | | `convoy_save_artifact` | Verify an artifact and save it into the current project (`overwrite=true` required to replace) | | `convoy_send_file` | Send one file from the current project to a node: its `.embody/convoy/inbox/` by default, a sibling `-wt-` worktree with `worktree`, or the live project with `live=true` (needs Allow Execute TD Python there). See [Sending files to a node](../convoy/index.md#sending-files-to-a-node) | | `convoy_start_node` | Reopen a previously registered, currently offline node | | `convoy_restart_node` | Safely replace one exact running TouchDesigner process (requires the current runtime id and an idempotency key). On TouchDesigner 2025 use `policy=save_then_restart`: the default `require_clean` always answers `project_dirty` | | `convoy_update_embody` | Self-update Embody on Convoy nodes to the latest release -- one node (`node=`) or the whole fleet (`all=true`) -- by dispatching the bounded `update_embody` operation as a durable per-node job (no TD Python grant involved). Skips offline, disabled, and Perform Mode nodes by name; poll the returned delivery handles with `convoy_get_job`. See [Fleet Updates](../convoy/fleet-updates.md) | | `convoy_owlette` | Optional read-mostly bridge to an Owlette site; fails closed without credentials | !!! info "Bridge architecture" Claude Code connects to Envoy via a STDIO bridge script (`.embody/envoy-bridge.py`). The bridge translates between Claude Code's STDIO transport and Envoy's HTTP endpoint. It handles MCP protocol handshake locally when TD is down, so these meta-tools are always available. See [Architecture](architecture.md) for details. ## Batch Operations | Tool | Parameters | Description | |------|-----------|-------------| | `batch_operations` | `operations` | Execute multiple operations in a single request. Reduces latency and token overhead | `operations` is a list of `{"tool": str, "params": dict}` objects. Each entry maps to an existing tool name and its parameters. Stops on first error. **When to use**: 3+ calls to the same tool type (positioning, connecting, parameter setting, flags). Use `execute_python` instead when you need conditionals, loops, or computed values between operations. **Example** - position 4 operators + connect them in one call: ```json {"operations": [ {"tool": "set_op_position", "params": {"op_path": "/project1/noise1", "x": 400, "y": 0}}, {"tool": "set_op_position", "params": {"op_path": "/project1/comp1", "x": 800, "y": 0}}, {"tool": "set_op_position", "params": {"op_path": "/project1/level1", "x": 1200, "y": 0}}, {"tool": "set_op_position", "params": {"op_path": "/project1/null1", "x": 1600, "y": 0}}, {"tool": "connect_ops", "params": {"source_path": "/project1/noise1", "dest_path": "/project1/comp1"}}, {"tool": "connect_ops", "params": {"source_path": "/project1/comp1", "dest_path": "/project1/level1"}}, {"tool": "connect_ops", "params": {"source_path": "/project1/level1", "dest_path": "/project1/null1"}} ]} ``` ## MCP Prompts | Prompt | Parameters | Description | |--------|-----------|-------------| | `search_op` | `op_name`, `op_type?` | Guide for searching operators by name | | `check_op_errors` | `op_path` | Guide for inspecting and resolving operator errors | | `connect_ops` | _(none)_ | Guide for wiring operators together | | `create_extension_guide` | _(none)_ | Guide for creating TD extensions with proper patterns | ============================================================================== # Convoy - LAN Relay # source: docs/convoy/index.md ============================================================================== # Convoy **Convoy** connects Embody-enabled TouchDesigner projects on the same trusted LAN. Each open project is a **node**: it can be selected as a remote target, and it can originate work for another node. There is no permanent controller, primary machine, or network leader. The everyday path, drawn with the machine boundary where it actually is: ```text YOUR COMPUTER REMOTE COMPUTER +-----------------------------+ +-------------------------------+ | VS Code / Cursor / | | TouchDesigner | | another AI client | | the selected Embody node | | | | | runs the operation | | v MCP (loopback) | | ^ | | Envoy in the local Embody | | | loopback | | | | | | | | v loopback | | | | | Convoy host app ==========+===========+==> Convoy host app | | (per-user background app) | trusted | (one per computer, serving | +-----------------------------+ LAN, | every node on it; approved | mutual | computer actions run here | TLS | even with TouchDesigner | | closed) | +-------------------------------+ ``` Only one hop crosses the network: host app to host app, over the mutually authenticated LAN transport. Everything else -- your AI client to Envoy, Envoy to its host app, the remote host app to its nodes -- stays loopback on its own computer. That is also the security shape: Envoy itself is never exposed to the LAN, on either end. Several Embody nodes can run on one computer. They share that computer's single host app and IP address but remain separately addressable. !!! warning "Development preview" Convoy is under active development. The LAN runtime and user controls are being built and tested, but production host-app packaging is not complete in every build. Windows-to-Windows acceptance testing is in progress. On macOS the enable, install, and daemon-runtime path has been validated on Apple Silicon hardware, but LAN node-to-node operation on macOS has not yet been physically validated. Do not treat this preview as a production certification. ## How membership works Convoy has two levels, and they keep separate hours: - A **machine** is a computer running the Convoy host app. TouchDesigner is how it gets set up, once. From then on the machine stays in the Convoy at every login, reachable from the others, whether or not any project is open. - A **node** is one project on a machine. Every save of a project is the same node: `e1.toe`, `e1.5.toe` and `e1.6.toe` share one identity, one address and one set of approvals, so a version-up changes nothing but the file name. `show.toe` and `rig.toe` are two nodes, and so is one file name in two folders. **Enable Convoy** is the gate for one project. There are no everyday Create, Join, invitation, role, or "Expose This Node" controls -- the one explicit Join lives inside the **Resolve Realm Conflict...** recovery dialog described in [Setup and Troubleshooting](host-app.md#recovering-from-a-realm-conflict). - If a compatible Convoy is already present, the node joins it automatically. - If none is present, enabled nodes establish one automatically, after a short randomized listen window of 8-20 seconds. Operations attempted during it report `realm_not_established` while genesis settles. The randomization is deliberate: enable two machines at the same moment and they converge on one Convoy instead of each founding its own. - Nodes discover changes and reconnect without a manual refresh. - Membership is remembered locally across ordinary restarts. Network-visible node status converges automatically, while dangerous permissions and resource limits remain local settings that peers cannot overwrite. - Every node is a sibling. A host going offline makes its own nodes unavailable, but reachable siblings continue communicating. - Once a project has joined from a machine, every saved project opened there joins by itself and is listed. Joining this way only registers the project: it turns no other setting on and builds nothing, so a project with Envoy off reads `e1.toe (Envoy off)` and takes no remote work until you turn Envoy on for it. Saying no sticks: turn **Enable Convoy** off for that project, or answer no in the Setup Wizard or the first-enable confirmation, and it stays out. Opening a project never restarts a host app you stopped. - A machine whose projects were all turned off before 6.3 stays out after updating, until you turn one on: an update does not reopen a LAN someone closed. - Turning **Enable Convoy** off stops that project sending and receiving Convoy work. The machine stays in the Convoy. To take the whole computer off the network, press **Stop Convoy App**; it stays out across logins and project opens until you press **Start Convoy App**. - Convoy remembers every project that has opened on a machine, with its approvals and launch record, until its `.toe` is deleted or you forget it. A closed project is simply not listed. The first time you enable Convoy on a machine, Embody asks once for confirmation, naming the trusted-LAN scope it grants and the background host app it will install. That consent is remembered per install: later projects mint their identity silently, and the Setup Wizard's Convoy step counts as the same answer, so you are never asked twice. The node's convoy identity and the granted scope are recorded in the committed `.embody/project.json`, which project clones inherit. A project that has never been saved cannot enable Convoy -- Embody explains why and turns the toggle back off until you save. Some fleets deliberately do **not** track `.embody/project.json` -- the same repo is mirrored onto every machine, and each box keeps its own identity. That works: if your `.gitignore` ignores the file, Envoy leaves it ignored (see [Auto-managed .gitignore](../embody/getting-started.md#auto-managed-gitignore)). A fresh machine then either gets `.embody/project.json` pre-seeded during provisioning, or simply enables Convoy and adopts the established realm during the listen window above -- a new identity only founds its own Convoy when no established one is heard on the LAN. A project whose committed binding names a *different* established Convoy -- a clone of a repo from another studio's LAN, for example -- is refused rather than merged, and its **Status** reads `Refused: local_realm_conflict`. Toggling **Enable Convoy** on arms a one-shot offer for about two minutes: when the refusal arrives inside that window, Embody opens **Rejoin Local Convoy**, naming both realms. **Keep Binding** leaves the project bound as it is and refused on this LAN; **Rejoin Local Mesh** rebinds the git-tracked `.embody/project.json` to this machine's mesh, which it adopts on the next registration. That rebind travels to every clone of the repo, so clones still on the original mesh will be refused there until they rejoin the same way. If the *machine* itself is in conflict, resolve that first -- see [Recovering from a realm conflict](host-app.md#recovering-from-a-realm-conflict). Convoy does not require an attached AI client. When **Configure For** is set to **None**, enabling Convoy keeps Envoy's loopback command server running only as Convoy's internal TouchDesigner relay; it does not generate client configuration or launch a coding tool. (The test is **Configure For**, not **Launch Client** -- those are separate settings, and leaving Launch Client set while Configure For is None is fine.) Turning Convoy off stops that otherwise-unused internal server. Convoy is intentionally convenient on a trusted production network. That also means it must not be enabled on guest Wi-Fi, public networks, or a LAN shared with people or devices you do not trust. Ordinary relayed tools can inspect and change a TouchDesigner project; the additional TD Python and Full Shell gates protect still more powerful interfaces. ## Set up a Convoy Do this once on every participating computer. Other projects on that computer then join by themselves when they open. 1. Save the TouchDesigner project. A saved `.toe` gives the node a stable project identity and a useful automatic name. 2. Choose an AI assistant if you want one. Convoy also works with **None**: Embody keeps only its internal local command service enabled and does not configure or launch an AI client. Either way, Convoy runs on Envoy: the host app runs in the Python environment Envoy builds (`.venv`), and remote work reaches TouchDesigner through Envoy's local command service. **Enable Convoy** therefore turns **Enable Envoy** on if it is off, and **Status** reads `Needs Envoy` whenever Envoy is off. 3. In the [Setup Wizard](../embody/setup-wizard.md), choose **Enable Convoy**. You can also turn on **Enable Convoy** later from the Embody COMP's **Convoy** page. 4. Approve the one-time confirmation. Enabling Convoy installs and starts the background host app automatically -- the confirmation (or the wizard's Convoy step) is the consent for the app and its login persistence. Use **Repair Convoy App** on the Convoy page only to repair a broken install or apply an update, and **Start Convoy App** after a deliberate stop. 5. Allow the Convoy host app through the operating-system firewall on the **private/trusted network profile only**. 6. Check **Status** and the **Convoy Machines** sequence. Other machines should appear automatically, whether or not they have a project open. Keep every node on the same Embody release for supported deployments. Version-skewed nodes may remain visible, but operations that cannot be proven compatible are limited or refused. See [Setup and Troubleshooting](host-app.md) for a machine-by-machine checklist and status help. ## Node names and status **Node Name** defaults to the computer hostname plus the saved `.toe` filename, for example: ```text render-01 / lobby ``` You can type a clearer display name. The name is a label only; changing it does not change the node's identity or permissions. Duplicate names are allowed, so always confirm the IP and other status details before sending consequential work. The automatic name is stored in the project file, so a `.toe` deployed to another computer arrives wearing the machine name it was saved on. That stamp heals itself: on the receiving machine the name refreshes to the local hostname and project the next time the node initializes, and until it does, the node list prefixes the row with the machine's live hostname -- for example `render-02 (render-01 / lobby)` -- so cloned projects always stay tellable-apart. A custom display name that does not look like an automatic stamp is never rewritten. The read-only **Convoy Machines** sequence shows one row per computer, so an address is never listed twice: | Column | Meaning | |---|---| | **Machine** | The computer's name and current address, for example `TEC-B4A / 192.168.88.20` | | **Open Projects** | The `.toe` files open on it right now, for example `Project.1.toe, Moonshine.toe, e1.toe`. `None open` is normal: the machine is still in the Convoy. A project that is open but cannot take work says why: `e1.toe (Envoy off)`, `e1.toe (not cooking)` | | **Status** | Reachability and age together, for example `Online / 5s ago` or `Offline / 2h ago -- peer unreachable`. A machine whose host app cannot prove every operation adds it, for example `Online / 5s ago -- limited: 12 of 19 operations shared with host app 6.0.280`. `convoy_list_nodes` carries the same as `compatibility`, `compatibility_reason` and `host_app_version` | Per-project detail lives in `convoy_list_nodes`: its `machines` list mirrors this table, and its `nodes` list has every project the machines know about, including closed ones, with `offline_reason`, approvals and versions. Convoy routes with stable identities, not names or IP addresses. Two versions of one project open at once stay two nodes. The second, `e1.6.toe` beside a running `e1.5.toe`, gets a temporary row for as long as it runs: it inherits no approvals, and it cannot be started remotely. A closed project stays known so it can still be started remotely and keeps its TD Python approval. It clears itself about half an hour after every save of it is deleted (an older save moving to another folder does not count, an unplugged or unmounted drive never counts as deleted, and a node with a delivery that has not finished is always spared). To remove something sooner, press **Forget Offline...** on the Convoy page: it names the closed projects and offline machines it would remove before anything is forgotten, or use the `convoy_forget_node` tool for a single known id. **A project is forgotten by the computer that owns it, from wherever you press**: other machines' rows are relayed to them over their live session, and only a machine that is not connected right now is left for later and named. Forgetting a machine removes this computer's record of it and its trust in that identity until it rejoins. ## Use Convoy from an AI client The MCP workflow is explicit about where work runs: 1. `get_convoy_status` checks that the local Convoy host app is available. 2. `convoy_list_nodes` lists local and reachable remote nodes; `convoy_ping` checks one node's liveness through its host app without waking TouchDesigner. 3. `convoy_select_node` pins this client session to one exact node. Ordinary Envoy tools then run there until you call `convoy_select_node` with `clear=true`. 4. `convoy_call` sends a one-off registered operation without changing the session selection. 5. `convoy_batch` runs the same ordered batch on one or more explicit targets and reports each target separately. It does not promise multi-machine rollback. 6. `convoy_get_job` checks durable work that outlives the original tool call or reconnect; `convoy_ack_job` acknowledges a finished delivery you have safely observed, letting the target release its protected result artifacts (verified artifact downloads and saves acknowledge automatically); `convoy_cancel_job` requests cancellation from the exact owning host. 7. `convoy_get_artifact` retrieves a large JSON, text, or file result from its artifact reference and verifies it into a temporary local file. Relayed screenshots are normally retrieved automatically. 8. `convoy_save_artifact` verifies an artifact and saves it into the current client's Embody project. An optional plain filename can be supplied; existing files are preserved unless `overwrite=true` is explicit. 9. `convoy_send_file` sends one file from the current project to a node (see [Sending files to a node](#sending-files-to-a-node)). 10. `convoy_list_controllers` shows live client sessions, selected targets, leases, and active work without waking TouchDesigner. 11. `convoy_start_node` can reopen a previously registered, currently offline node; `convoy_restart_node` safely replaces one exact running TouchDesigner process. ### Choosing the channel - **Reach a remote node through Convoy, not SSH.** Convoy carries the node's own permission gates, writer lease and audit trail; SSH carries none of them. Fall back to SSH only when Convoy cannot reach the node and `convoy_start_node` has failed. - **Code and project content move by git:** commit and push from one machine, then fetch and pull (or switch branches) on the other through the structured Git actions below. A pull into a node's live project changes files under its open TouchDesigner; use a worktree when the live project must not change during a show. - **A single file that is not in git** goes with `convoy_send_file`; **results come back** with `convoy_get_artifact` / `convoy_save_artifact`. You can usually ask in plain language. For example: > List my Convoy nodes, then query `/project1` on `render-02 / lobby` and report any operator errors. Do not modify anything. For a mutation, name the target and scope clearly: > On `render-03 / facade`, change only `/project1/output/level1`, then verify that operator for errors. Convoy never silently falls back to a local TouchDesigner instance when an explicit remote target cannot be reached. ## Use Convoy from TouchDesigner Python An enabled node can also originate work without an attached AI client. The API is asynchronous: it returns a local request handle immediately, and an optional callback receives progress and completion events on TouchDesigner's main thread. Convoy's extension lives on Embody's `convoy` child COMP, so TouchDesigner Python reaches it through `op.Embody.op('convoy').ext.ConvoyExt`. ```python def on_nodes(event): if event.get('event') == 'complete': debug(event.get('result')) request = op.Convoy.ext.ConvoyExt.listNodes(callback=on_nodes) ``` Use the `host_id` and `node_id` returned by that list for an exact sibling call: ```python def on_result(event): if event.get('event') == 'complete': debug(event.get('result')) request = op.Embody.op('convoy').ext.ConvoyExt.call( host_id='host-id-from-list', node_id='node-id-from-list', operation='query_network', arguments={'root': '/'}, wait=False, callback=on_result, ) ``` Keep the returned handle if you need to inspect it later with `requestResult()`. `ping()`, `batch()`, `getJob()`, and `cancelJob()` follow the same callback pattern. Disabling Convoy prevents this node from both originating and receiving sibling work. ## Controllers, edit leases, and jobs A **controller** is an active client session, such as one Cursor window or one Envoy session. It is not a membership role and does not outrank another controller. Controller counts are visible in the status sequence; the detailed controller list is intended to show who is active, which node they selected, and whether work is in progress without waking TouchDesigner. Convoy supports concurrent readers and tracks bounded **edit leases** for coordinated work: - Read and status work can proceed together. - A mutation is refused while another live controller holds an incompatible exclusive node lease. - Ordered work sent with `convoy_batch` is one target-side Envoy batch. Fanout targets remain independent and may partially succeed. - A conflict is reported with the current owner/context; Convoy does not guess, steal control, or imply distributed rollback. - Expired sessions and leases are cleaned up automatically. This is the network counterpart to Envoy's local multi-session scoping, not a permanent lock the user must manage for ordinary calls. Long-running and relayed operations are represented as **jobs**. Jobs survive a client disconnect and can be checked after the network returns. If a call times out, that does not prove it never ran: use the returned job or retry identity to reconcile before issuing a different mutation. Cancellation is best effort once work has started; always inspect the target before retrying an uncertain write. ## Perform Mode and Remote Wake **Remote Wake** is on by default. When a permitted remote TouchDesigner operation arrives while the target is in Perform Mode, Convoy temporarily makes its command service available, completes the work, and restores the previous Perform state after the idle grace period. - **Remote Wake Idle Grace** defaults to **60 seconds**. - New remote work during that window restarts the timer. - Discovery, status, ping, job polling, and controller queries do **not** wake TouchDesigner. - Turning **Remote Wake** off leaves the node discoverable but refuses work that requires waking it. - `save_project` and `update_embody` never run mid-show, and a node in Perform Mode is not woken for them. Its host app refuses the job (`refused`), or the node itself does (`failed`), including when only TouchDesigner's perform window is open; either way the job's result carries code `perform_mode` and nothing ran. Remote Wake means "temporarily leave Perform Mode." It does not launch a closed TouchDesigner process. Use the separate lifecycle tools described below when they are present in your preview build. ## Start or restart a TouchDesigner node `convoy_start_node` asks the target computer's host app to reopen a known offline node. The node must have registered successfully before, and its saved `.toe` file and TouchDesigner application must still match that local launch record. Starting an already-running node is harmless and reports that it is already online. `convoy_restart_node` addresses one exact running node and requires the runtime ID returned by `convoy_list_nodes`. This comparison prevents a delayed request from restarting a newer TouchDesigner process that happens to have taken the old node's place. Give each intended action a unique `idempotency_key`; if a response is lost, retry with the same key so Convoy can reconcile the original attempt instead of launching twice. The normal restart policies are: | Policy | Behavior | |---|---| | `require_clean` | Default. Refuses to restart if the project is dirty, unsaved, or its state cannot be verified. TouchDesigner 2025 reports project changes even right after a save, so expect `project_dirty` and use `save_then_restart`. | | `save_then_restart` | Saves first, verifies the saved state, and then restarts. A failed or uncertain save stops the restart; a dirty project on a node in Perform Mode is not saved, and the restart stops with `perform_mode`. | The public Convoy relay accepts only these two restart policies. Discard/force behavior is not exposed as a remote recovery shortcut. A restart also refuses when several Embody nodes share the same TouchDesigner process, because restarting one would silently interrupt the others. Cancellation and deadlines have an intentional safety boundary. Before the old process commits to exiting, either condition stops the restart without deliberately quitting that process. With `save_then_restart`, a response containing `save_may_have_run` means the save was handed to TouchDesigner but its final acknowledgement was uncertain; inspect the project file before retrying. After the quit commit, a response may report `cancel_deferred` or `deadline_deferred`: Convoy continues a bounded restoration attempt because abandoning the node while it is down would be less safe. The host app records that commit durably. If it restarts during the replacement window, it automatically resumes reconciliation and updates the original job instead of treating the request as new work. Query the same job, or retry with the same idempotency key, until the exact node and runtime are confirmed online. Do not issue a second restart with a new key merely because the first client wait ended. Remote lifecycle control is part of the development preview. Validate the complete quit, launch, registration, and crash-recovery path on your own machines before using it in a show-critical deployment. ## Permissions for code and computer actions Convoy's ordinary registered TouchDesigner tools are available when the node is enabled and the request is compatible. More powerful code paths have separate local gates. | Capability | Default | Approval | |---|---|---| | Registered TouchDesigner operations | Available | **Enable Convoy** on the target node | | Structured Git and GitHub CLI actions | Available where supported | No Full Shell approval required | | Arbitrary TouchDesigner Python | Off | Turn on **Allow Execute TD Python** locally on that node | | Arbitrary operating-system shell | Off | Turn on **Allow Full Shell** locally on that computer | Self-updating Embody on a node (`update_embody`, the operation behind `convoy_update_embody`) is a registered operation, not TD Python: it installs only the sha256-verified official release and refuses downgrades, so patching a fleet never requires the dangerous grant. Saving a node's project (`save_project` through `convoy_call`) needs no grant either: it runs no caller code. **It is a development action, not for shows.** A save blocks that machine's TouchDesigner main thread for 15+ seconds, so no frames render, and restarts its Envoy server. Never send it to a machine running a show; a node in Perform Mode, or with TouchDesigner's perform window open, refuses it. `run_tests` is never relayed to another computer. Structured Git and GitHub actions use named, bounded operations rather than accepting an arbitrary command line. The catalog covers repository status, remotes, branches/revision, fetch, fast-forward pull, push, branch switching, sibling worktrees, and read-only GitHub inspection; destructive Git history rewrites and force operations are not part of the default surface. Network Git is HTTPS-only. - **Pull** fast-forwards only the branch that is already checked out; naming another branch is refused (`branch_mismatch`) instead of moving the checked-out one. - **Switch branch** needs a clean tree. It switches to an existing local branch, or, when you name a `remote`, creates the branch to track `/`; it never guesses a remote. - **Worktrees** are a choice, not a requirement: `worktree_add` creates a sibling checkout named `-wt-` beside the node's project, `worktree_list` lists them, and `worktree_remove` removes one only when it holds no local, untracked or ignored files, and never when it is itself a registered node's project. Every other Git action takes an optional `worktree` name and runs there instead of in the live project, so a running TouchDesigner never sees the change. **Allow Execute TD Python** is effectively code execution as the user running TouchDesigner. TD Python can access files, the network, credentials available to TD, and process APIs. It is a separate gate from **Allow Full Shell**; leaving Full Shell off does not sandbox Python. **Allow Full Shell** permits arbitrary operating-system commands as the logged-in user. It applies to the computer's Convoy host, including its local nodes, and can only be enabled locally. Leave it off on show machines unless a specific workflow requires it. Convoy peers cannot remotely turn on either dangerous permission. Both toggles display the host app's current approval, not a stored project setting. Turning one on asks the local host app for the change: the toggle returns to its approved value and a confirmation dialog appears -- the grant takes effect (and the toggle shows On) once you confirm. If no dialog appears, the request did not reach the host app and nothing was granted. A value carried inside a saved `.toe`, a clone, or a script write is reverted automatically and never grants anything. Git, GitHub CLI, and shell actions use the tools and credentials already configured for the logged-in user. Convoy does not create a second GitHub identity. ## Screenshots, files, and Artifact Quota Screenshots, transferred files, large results, and command output are stored temporarily as **artifacts**. **Artifact Quota (MB)** limits the combined managed cache for the logged-in user on that computer across all local Convoy nodes. The default is **1024 MB**. When a relayed screenshot returns a PNG or JPEG artifact, Convoy normally downloads and verifies it automatically and presents it to the AI client as image content. Once the image is inline, Convoy removes its bridge temporary file and does not report a retained temp path. The artifact reference remains available if you want to save it explicitly. For a large JSON result, text result, or other file returned as an artifact reference, use `convoy_get_artifact`. Convoy retrieves the bytes from the owning host, verifies their size and SHA-256 digest, and returns a local temporary path. Pass the complete artifact reference and exact target information from the original result; do not substitute a displayed filename or a path reported by the remote computer. Use `convoy_save_artifact` when the file must persist. It verifies the artifact again and saves it under the current Envoy client's own `.embody/convoy/artifacts/` directory; callers cannot redirect it into another project or arbitrary folder. You may provide one plain filename. The default `overwrite=false` protects an existing project file, so set `overwrite=true` only when replacement is intended. When the quota is reached, Convoy removes the **least recently used** unpinned artifacts first. It does not remove active transfers, data required by running or not-yet-acknowledged jobs, temporary pins, or copies you explicitly saved into a project. If nothing safe can be removed, the new transfer is refused instead of deleting protected work. A quota of `0` disables operations that require managed artifact storage; it does not mean unlimited space. The managed cache is outside the project: | Platform | Managed cache | |---|---| | Windows | `%LOCALAPPDATA%\Embody\Convoy\cache\artifacts` | | macOS | `~/Library/Caches/Embody/Convoy/artifacts` | When you explicitly save or export an artifact into a project, it goes under: ```text .embody/convoy/artifacts/ ``` Those explicit copies are outside the runtime quota and are yours to retain, delete, ignore, or commit. Convoy never treats a path on another computer as though it were a local path; remote data must arrive as a verified artifact or a normal structured result. A remote `C:\...` or `/Users/...` path is descriptive target-side information only and must never be opened as a local result. ### Sending files to a node `convoy_send_file` sends one file the other way. The source must resolve inside the sending client's own project, so a file elsewhere on that computer can never be sent. The local host app uploads it as a verified artifact to the host that owns the target node, then a durable `convoy_put_file` job writes it: | Destination | How | Gate on the target | |---|---|---| | `.embody/convoy/inbox/` in the node's project (default) | `dest` is a plain file name, defaulting to the source's | none beyond **Enable Convoy** | | A path inside the node's `-wt-` worktree | `worktree=`; `dest` defaults to the file's own project-relative path | none beyond **Enable Convoy** | | A path inside the node's live project | `live=true` | **Allow Execute TD Python**, because a synced `.py` written there reloads into TouchDesigner | Destinations are relative, `/`-separated paths; `..`, drives, links, junctions, short-name aliases, Windows-reserved or invalid names, anything under `.git`, AI client config (`.mcp.json`, `.claude/`, `.codex/`, `.cursor/`, `.vscode/`, `.gemini/`) and `.embody/` are refused. A worktree that is itself a registered node's project is refused too: target that node instead. An existing file is kept unless `overwrite=true`. Only the controller that uploaded a file can have it written. ## Version and platform compatibility Use the same Embody version on all nodes. That is the supported and easiest-to-debug configuration. Keeping a fleet current is one call: `convoy_update_embody(all=true)` dispatches each node's own bounded self-update (official release, sha256-verified, downgrade-refusing) as a durable per-node job -- no per-machine visits and no **Allow Execute TD Python** grant involved. See [Fleet Updates](fleet-updates.md). Convoy checks capabilities per operation, so a minor mismatch does not have to hide a node completely. Presence and some read-only actions may continue while unsupported mutations are marked **Limited** or refused. A fundamentally incompatible version or safety contract is not bypassed for convenience. The compatibility target is: - Windows x64 to Windows x64 - Windows x64 to Apple Silicon macOS, in both directions - Apple Silicon macOS to Apple Silicon macOS TouchDesigner also runs on Intel macOS, but Convoy's first macOS target is Apple Silicon. The current preview has not completed physical macOS validation. Check the release notes before using Convoy in a show-critical deployment. ## Owlette [Owlette](https://owlette.app) is optional. Convoy on a LAN does not require an Owlette account, internet access, or an Owlette agent. The first Owlette bridge is intentionally small. `convoy_owlette` consumes only Owlette's supported public API for site and machine inventory, online detail, and command status. It is optional and fails closed when credentials or a published API primitive are unavailable. For the current preview, provide `OWLETTE_API_KEY` in the Convoy host app's process environment (or `OWLETTE_API_KEY_SECRET` to reference a key held in the operating system's secret store), then restart the host app. `OWLETTE_SITE_ID` can provide an optional default site. Ask `convoy_owlette` for `capabilities` before sending another action; inventory and status calls do not wake TouchDesigner. Owlette command submission has an additional local host opt-in: set `EMBODY_CONVOY_ALLOW_OWLETTE_COMMANDS=1` in that same host environment and restart the host app. Every submission also requires a caller-held idempotency key. Leave this setting absent or false on machines where the bridge should remain read-only. The generic `mcp_tool_call` command is refused, so Owlette cannot become an unrestricted shell or an ad hoc Convoy tunnel. Convoy and Owlette keep distinct identities, and no Owlette repository, agent, protocol, or API change is required. ## Next steps - [Setup and Troubleshooting](host-app.md) - [Fleet Updates](fleet-updates.md) - [Setup Wizard](../embody/setup-wizard.md) - [Convoy Parameter Reference](../embody/parameters.md#convoy) - [Envoy Tools Reference](../envoy/tools-reference.md) ============================================================================== # TDXN - Specification # source: docs/tdxn/specification.md ============================================================================== # TDXN Specification **Version 2.2** TDXN is the substrate that makes "create at the speed of thought" possible. It's the format your AI agent reads to understand what's on the screen, the format that lets you compare two attempts side by side, and the format a network rebuilds itself from on the next project open. Without it, AI-driven TouchDesigner work is one-directional - you generate, and you're stuck with what you got. With it, every step of the loop - generate, compare, revert, branch - runs at the speed of typing. TDXN (TouchDesigner eXternal Network) is a YAML-based file format for representing TouchDesigner operator networks as human-readable, diffable text. It stores only non-default properties, keeping files minimal. - File extension: `.tdxn` - MIME type: `application/yaml` - Encoding: UTF-8 - Schema: [`tdxn.schema.yaml`](../tdxn.schema.yaml) - validates the parsed structure. --- ## Document Structure A `.tdxn` file is a YAML document with the following top-level fields: ```yaml format: tdxn version: '2.2' build: 1 generator: Embody/6.0.4 td_build: '2025.32050' network_path: / type: containerCOMP options: include_dat_content: true include_storage: true type_defaults: { ... } par_templates: { ... } custom_pars: { ... } parameters: { ... } sequences: { ... } flags: [ ... ] color: [0.3, 0.5, 0.9] tags: [tdxn] comment: Main UI container storage: { ... } operators: [ ... ] annotations: [ ... ] ``` | Field | Type | Required | Description | |-------|------|----------|-------------| | `format` | string | Yes | `"tdxn"` as of Embody 6.1; `"tdn"` in files written by 6.0 and earlier, and by any older Embody that re-exports one. Both are permanently valid on read. | | `version` | string | Yes | Format version. Currently `2.2`. See [Back-compatibility](#back-compatibility) for how older versions are read. | | `build` | integer | No | Embody build number for the exported COMP. Incremented each time the network is saved via Embody. Useful for version tracking and git diffs. **Omitted entirely** when the COMP has no build tracking (an untracked or portable network - no externalizations-table row and no `Build` parameter). Older files may carry an explicit `build: null`; readers still accept it. Whether `build` is written also decides the provenance fields: a tracked file carries `build` and omits `source_file` / `exported_at`; an untracked one carries those two instead. | | `generator` | string | Yes | Tool that produced the file (e.g., `"Embody/6.0.4"`). | | `td_build` | string | Yes | TouchDesigner version and build number (e.g., `"2025.32050"`). | | `source_file` | string | No | Basename of the `.toe` project file the COMP was exported from (e.g., `"MyProject.toe"`). Informational provenance only; not used on import. Written only when the export has no `build`; exports of tracked COMPs no longer record it. Older files may carry it either way. | | `exported_at` | string | No | ISO 8601 UTC timestamp of export (e.g., `"2025-02-19T12:34:56Z"`). Written only when the export has no `build`; for a tracked COMP the export time lives in the `externalizations.tsv` `timestamp` column and git history. Older files may carry it either way. | | `network_path` | string | Yes | The COMP path represented by this file (e.g., `"/"` for the entire project). On paste/import as a *new* COMP, its basename names the new COMP (e.g., `"/specimen_lab/noise_terrain"` -> `noise_terrain`), sanitized via `tdu.validName`, collisions uniquified. | | `type` | string | No | TouchDesigner operator type of the target COMP (e.g., `"baseCOMP"`, `"containerCOMP"`, `"geometryCOMP"`). Added in v1.1. Makes the file self-describing for portable import into other projects. On import, a mismatch between this field and the destination COMP's type triggers a warning. | | `options` | object | Yes | Export settings used when generating this file. | | `options.include_dat_content` | boolean | Yes | Whether DAT text/table content was included in the export. | | `options.include_storage` | boolean | No | Whether operator storage entries were included in the export. Absent means `true` (included). Added in v1.2. Can be toggled per-COMP via the `embed_storage_in_tdn` storage key. | | `type_defaults` | object | No | Per-type shared properties (parameters, flags, size, color, tags). See [Type Defaults](#type-defaults). | | `par_templates` | object | No | Reusable custom parameter page definitions. See [Parameter Templates](#parameter-templates). | | `custom_pars` | object | No | Target COMP's own custom parameter definitions and values. Same format as operator-level [`custom_pars`](#custom-parameters). Only present if the target COMP has custom parameters. | | `parameters` | object | No | Target COMP's own non-default built-in parameter values. Same format as operator-level [`parameters`](#built-in-parameters). Only present if the target COMP has non-default built-in parameters. | | `sequences` | object | No | Target COMP's own built-in/custom parameter sequences with non-default block counts or values. Same format as operator-level [`sequences`](#built-in-parameter-sequences). Added in v1.3. | | `flags` | array | No | Target COMP's own non-default [flags](#flags). Same format as operator-level flags. Added in v1.1. | | `color` | `[r, g, b]` | No | Target COMP's node color, if different from default gray. RGB floats 0.0-1.0, rounded to 4 decimal places. Added in v1.1. | | `tags` | array of strings | No | Target COMP's tags, if any. Added in v1.1. | | `comment` | string | No | Target COMP's node comment, if non-empty. Added in v1.1. | | `storage` | object | No | Target COMP's persistent [storage entries](#operator-storage). Same format as operator-level storage. Added in v1.1. | | `operators` | array | Yes | Array of [operator objects](#operator-object). | | `annotations` | array | No | Array of [annotation objects](#annotations). Only present if the root COMP contains annotations. | --- ## Operator Object Each entry in the `operators` array (and in nested `children` arrays) is an operator object: ```yaml - name: noise1 type: noiseTOP position: [200, -100] size: [300, 150] color: [0.2, 0.6, 0.9] comment: Primary noise source tags: [audio, generator] parameters: { ... } custom_pars: { ... } flags: [ ... ] storage: { ... } startup_storage: { ... } inputs: [ ... ] comp_inputs: [ ... ] dat_content: ... dat_content_format: text children: [ ... ] palette_clone: true ``` ### Field Reference | Field | Type | Required | Condition for inclusion | |-------|------|----------|------------------------| | `name` | string | Yes | Always included. The operator's name. | | `type` | string | Yes | Always included. TouchDesigner operator type (e.g., `"baseCOMP"`, `"noiseTOP"`, `"textDAT"`, `"waveCHOP"`). | | `position` | `[x, y]` | No | Omitted when `[0, 0]` (default). Included only for operators not at the origin. | | `size` | `[width, height]` | No | Only if different from the default `[200, 100]`. | | `color` | `[r, g, b]` | No | Only if different from the default gray `[0.545, 0.545, 0.545]` (tolerance: 0.01 per channel). RGB values are floats from 0.0 to 1.0, rounded to 4 decimal places. | | `comment` | string | No | Only if non-empty. Annotation text on the node. | | `tags` | array of strings | No | Only if the operator has tags. | | `dock` | string | No | Only if the operator is docked to another operator. Sibling name or full path. | | `parameters` | object | No | Only if there are non-default [built-in parameters](#built-in-parameters) (after [type_defaults](#type-defaults) are factored out). | | `custom_pars` | object | No | Only if the operator has [custom parameters](#custom-parameters). Dict keyed by page name. | | `flags` | array | No | Only if any [flags](#flags) differ from their defaults. | | `storage` | object | No | Only if the operator has non-transient [storage entries](#operator-storage). Dict of key-value pairs. | | `startup_storage` | object | No | **Import-only.** Restored via `storeStartupValue()` on import; TouchDesigner exposes no read-back accessor for the startup dictionary, so the exporter never writes this field. | | `inputs` | array | No | Only if the operator has [operator-level connections](#operator-connections). | | `comp_inputs` | array | No | Only if the operator has [COMP-level connections](#comp-connections). COMPs only. | | `dat_content` | string or array | No | Only for editable DAT-family operators when `include_dat_content` is `true`, the DAT is inside an `animationCOMP`, or its content is saved nowhere else on disk; never for a DAT tagged `tdxn_exclude:dat_content`. See [DAT Content](#dat-content). | | `dat_content_format` | string | No | `"text"` or `"table"`. Present whenever `dat_content` is present. | | `dat_read_only` | boolean | No | `true` for a DAT whose content is read-only (TD auto-generates it and rejects writes on import). Written in place of `dat_content`. See [DAT Content](#dat-content). | | `children` | array | No | Only for COMPs with child operators (excluding palette clones). Contains nested operator objects. See [Children and Hierarchy](#children-and-hierarchy). | | `annotations` | array | No | Only for COMPs with [annotations](#annotations). Contains annotation objects. | | `palette_clone` | boolean | No | `true` if this COMP is cloned from the TouchDesigner palette (`/sys/`). When set, children are not exported (TD recreates them from the clone source). | | `sequences` | object | No | Only if the operator has built-in parameter sequences with non-default block counts or values. See [Built-in Parameter Sequences](#built-in-parameter-sequences). *Added in v1.3.* | | `tdn_ref` | string | No | Only for COMPs with their own TDXN externalization. Relative file path to the child's `.tdxn` file. Mutually exclusive with `children`; the entry also carries no `custom_pars`. See [COMP References](#comp-references-tdn_ref). *Added in v1.2.* | | `tox_ref` | string | No | Only for COMPs with their own TOX externalization. Relative file path to the child's `.tox` file. Mutually exclusive with `children`; the entry also carries no `custom_pars`. See [TOX References](#tox-references-tox_ref). *Added in v1.4.* | ### Compact Formatting Short numeric vectors (position, size, color - up to four elements) are written inline with YAML flow style; longer or non-numeric sequences fall to block style: ```yaml position: [200, -100] size: [300, 150] color: [0.2, 0.6, 0.9] tags: - audio - generator inputs: - noise1 ``` This keeps the most common short vectors compact while longer arrays stay readable line-by-line. --- ## Back-compatibility ### `exported_at` became optional (within 2.1) Exports of tracked COMPs stopped writing `exported_at` and `source_file`: both changed on every save and nothing read them. The schema therefore no longer requires `exported_at`; readers never required either field, so there is no format version bump. A vendored copy of `docs/tdxn.schema.yaml` from before this change rejects new tracked files -- refresh it. ### v2.2: reference entries carry no `custom_pars` A parent's `tdn_ref` and `tox_ref` entries no longer repeat the child's custom parameters or their sequences; the child's own `.tdxn` carries them at its root and a `.tox` reload replaces them (see [COMP References](#comp-references-tdn_ref) and [TOX References](#tox-references-tox_ref)). `custom_pars` was always optional, so the schema is unchanged and older files, which keep their copy, still import. The version is bumped anyway because an Embody older than v6.2.71 mis-builds such a file: it creates a nested COMP's custom parameters only at the end of that COMP's import, so an extension inside it that reads them in `__init__` fails. With the bump, such a build logs `TDXN file is v2.2, newer than this build` on open instead of failing silently (v6.2.71 builds these files correctly and logs the same line). Files written by v6.2.71 itself still say `2.1` with bare `tdn_ref` entries; an older build misreads those silently until they are next saved. Every `.tdxn` is rewritten once, on its next save, to carry the new version, and a team mixing builds rewrites the version back and forth. ### v2.1: widened definition fields v2.1 changes no structure and adds no required field. It exists to mark one thing: several custom-parameter definition fields that were always scalars can now also be a **per-component array** (see [Per-component definition fields](#per-component-definition-fields)) -- `default`, `min`, `max`, `clampMin`, `clampMax`, `normMin`, `normMax`, `readOnly`, `password`, `styleCloneImmune`, `defaultExpr`, `defaultBindExpr`, `defaultMode`, `help`, `enable` and `enableExpr`. Purely *new* keys would not have needed a version bump -- readers are required to ignore unknown fields. A widened **type** on an existing key is different: a pre-2.1 reader evaluates `readOnly: [false, true]` as a truthy value and forces the whole tuplet read-only, and drops `enable: [true, false]` entirely, both silently. Since an array is only ever written when a tuplet's components genuinely disagree, most files are unaffected -- but the bump makes an older build log `TDXN file is v2.1, newer than this build; some content may not import` rather than quietly reconstructing the wrong state. Older builds still read v2.1 files; only mixed tuplets are misread. v2.0 is the first YAML release of the format. Because YAML is a strict superset of JSON, importers read **both** new YAML files and legacy JSON `.tdn` (versions `1.x`) transparently: - Importers parse **json-first**: a document beginning with `{` or `[` is read by the JSON parser (with any leading UTF-8 BOM and whitespace stripped first), and only otherwise by the YAML parser. Correctness is therefore independent of whether a fast YAML C library is present. - Legacy `.tdn` were tab-indented JSON, which YAML forbids as indentation; the json-first path reads them losslessly. - The v1.5 array-of-lines `dat_content` and the older newline-escaped string form both still import (see [DAT Content](#dat-content)). Migration is **lazy**: an existing JSON `.tdn` is rewritten as YAML the next time Embody saves it. A v2.0 YAML file opened by a pre-2.0 Embody build (JSON-only reader) will not parse - new builds read old files, but old builds cannot read new ones. **Hand-edit caveats** (do not apply to Embody-written files, which never emit these): a hand-written YAML float needing float typing must include a decimal point (`1.0e-07`, not `1e-07`); duplicate mapping keys are silently last-wins; the loader is YAML 1.1, so an unquoted `012` is octal `10`, `0x10` is `16`, `on`/`off`/`yes`/`no` are booleans and `~` is null -- quote such strings. Round-trip through Embody after manual edits. --- ## Built-in Parameters The `parameters` object maps parameter names to their values. Only built-in (non-custom) parameters whose current value differs from their default are included. Parameters shared unanimously across all operators of a type are factored into [type_defaults](#type-defaults) instead. ### Parameter Modes Parameters can be in one of three exportable modes: **Constant** - the value is stored directly: ```yaml parameters: tx: 100 name: hello active: true ``` **Expression** - prefixed with `=`. A Python expression that TouchDesigner evaluates each frame: ```yaml parameters: tx: =absTime.frame * 0.1 resizecomp: =me ``` **Bind** - prefixed with `~`. A reference expression that binds this parameter to another: ```yaml parameters: tx: "~op('controller').par.posx" ``` !!! note A fourth mode, **Export**, exists in TouchDesigner but is not stored in TDXN. Export mode is set by the exporting operator, not the parameter itself, and cannot be meaningfully imported. ### Escaping Constant string values that literally start with `=` or `~` are escaped by doubling the prefix: | Stored value | Meaning | |-------------|---------| | `"=foo"` | Expression: `foo` | | `"==foo"` | Constant string: `"=foo"` | | `"~bar"` | Bind expression: `bar` | | `"~~bar"` | Constant string: `"~bar"` | ### Skipped Parameters The following built-in parameters are never exported, as they are internal actions or not meaningful outside a live project: **By name:** - `externaltox`, `enableexternaltox`, `reloadtox` - `reinitextensions`, `savebackup` - `savecustom`, `reloadcustom` - `pageindex` !!! info `file` and `syncfile` parameters ARE exported when non-default, so that TDXN files are self-contained for externalized DATs. This ensures file references survive import into a different project. **By style:** - `Pulse` - action buttons (fire-once, no persistent state) - `Momentary` - momentary buttons (no persistent state) - `Header` - visual section dividers (no value) **Other exclusions:** - Read-only parameters - Custom parameters (handled separately in `custom_pars`) ### Per-Parameter Omission (`tdxn_exclude:` tags) A project can exclude an individual parameter's **value** from export by tagging the operator itself with the suffixed form of the exclude tag: ``` tdxn_exclude: ``` One tag per parameter (`tdxn_exclude:file`, `tdxn_exclude:Port`). The operator, its wiring, and its other parameters export normally; the named parameter's **constant value** is left out of the document. This is the opt-out for runtime state that must not be committed - a negotiated port, a session-specific file path, a live readout. (The **bare** tag on a COMP is the whole-COMP exclusion described elsewhere; the colon-suffixed form never affects COMP visibility.) - **Constant values only.** An expression or bind on the tagged parameter still exports - a reference is authored configuration, not leaked session state. - **Custom parameters**: the definition still ships (style, range, default, help); only its `value` key is dropped. - **Visible by design**: the tag round-trips in the operator's `tags:` list, so the exported document records *why* the parameter is absent - and because the marker survives reconstruction, the next export omits it again. - **Top-level parameters only**: sequence block parameters are not omittable. - **Validation**: a tag naming a parameter the operator does not have logs a `WARNING` at export ("nothing omitted"), so a typo cannot silently no-op. - The prefix is the same `Tdxnexcludetag` parameter that governs whole-COMP exclusion (default `tdxn_exclude`); clearing it disables the whole family. The Embody UI exposes this through the tagger's **Exclude from tdxn** action on TDXN COMPs - a drop-zone panel that toggles `tdxn_exclude:` for dragged parameters (and the bare whole-COMP `tdxn_exclude` for dragged COMPs), listing every exclusion in the COMP's subtree, each removable via its **x**. ### Non-Default Comparison A constant parameter is included only if its current value differs from its default: - **Floats**: considered different if `abs(current - default) > 1e-9` - **OP-reference parameters**: `None` and `""` are treated as equivalent (both mean "no operator connected") - **All other types**: standard equality comparison (`!=`) ### OP-Reference Values A constant-mode OP-reference parameter -- a `TOP`/`CHOP`/`DAT`/`COMP`/`OP`-style built-in, a sequence block's operator slot such as a GLSL MAT sampler's `top`, or a custom `OP`-style parameter -- is written **as authored**: the typed string, normally a sibling name or a relative path, including a name that does not resolve yet and a pattern such as `constant*`. It is never the resolved operator's absolute path. (Embody 6.2.56 and earlier wrote sequence-block and custom values as `str(p.eval())` -- an absolute path, or nothing when the name did not resolve; see [issue #132](https://github.com/dylanroscover/Embody/issues/132).) **Repair of absolute values.** A sequence-block or custom OP value that is an absolute path *inside* the exported network is rewritten relative to its owner on export (`/proj/comp/tex` on `/proj/comp/glsl` becomes `tex`; from one level down, `../tex`), and such a value in an older file is remapped onto the destination COMP on import, so a copy or a clone drives its own operators. The repair is deliberately narrow: only those two parameter classes (a top-level built-in was always written as authored, so an absolute value there is the user's and is kept); only a single literal path (a pattern or a space-separated multi-operator value stays as authored); never for a whole-project document (`network_path: /`). An export does not modify the live parameter; it takes the relative form on its next reconstruction. ### Divergent Defaults and the Creation-Defaults Catalog Some TouchDesigner operators reset certain parameters during initialization, meaning the value reported by `p.default` differs from the value TouchDesigner actually assigns when the operator is created. For example: - `cameraCOMP` `tz`: `p.default` reports `0`, but TD creates cameras with `tz = 5` - `lightCOMP` `tz`: `p.default` reports `0`, but TD creates lights with `tz = 5` - `renderTOP` resolution parameters: reported defaults differ from creation values If TDXN used `p.default` directly for non-default comparison, a user-set value that happens to match `p.default` but differs from the actual creation value would be silently omitted from export. On import, TD would create the operator with the (different) creation value, and the user's intended value would be lost. Conversely, a parameter at the true creation value might be incorrectly included in the export, bloating the file with false positives. #### The Catalog System Embody solves this with a three-tier system that discovers and caches the true creation values for every operator type: **1. Background scan at startup** On project open, the `CatalogManager` extension checks whether a creation-values catalog exists for the current TD build (stored as a JSON file in the `.embody/` directory at the project root). If no catalog exists, it runs a background scan: - Iterates every creatable operator type in TouchDesigner (TOPs, CHOPs, SOPs, DATs, MATs, COMPs, POPs) - Creates a temporary instance of each type - Records `p.val` (the actual value TD assigned) for every parameter, skipping custom, read-only, and sequence parameters, a small set of known non-portable parameter names and styles, and name-dependent values (e.g. callback-DAT paths that embed the probe operator's name) The catalog stores **all** creation values, not just divergent ones. This means TDXN always has the ground-truth creation value for every parameter - `_getCreationDefault()` returns the catalog value directly, falling back to `p.default` only for parameters the catalog doesn't cover. The divergent-default problem (where `p.val` differs from `p.default`) is solved implicitly: by recording what TD actually assigns, the catalog captures both correct and divergent defaults without needing to distinguish between them. The scan processes 1-2 operator types per frame to avoid dropping frames. The resulting catalog is written to `.embody/catalog_{build}.json` (e.g., `.embody/catalog_099.2025.32280.json`) and cached for future sessions on the same TD build. **2. Export/import correction** During TDXN export, the `_getCreationDefault()` method checks the catalog before falling back to `p.default`: ```python def _getCreationDefault(self, op_type, par_name, par): divergent = self._getDivergentDefaults(op_type) if par_name in divergent: return divergent[par_name] return par.default ``` This means TDXN compares parameter values against the *actual creation value*, not the *reported default*. Parameters are included in the export if and only if the user's value truly differs from what TD would assign to a freshly created operator. **3. Cross-build patching** When a `.tdxn` file is opened on a different TD build than the one that exported it, creation defaults may have shifted between builds. The `CatalogManager` handles this automatically: 1. Reads the `td_build` field from each `.tdxn` file header 2. Loads the catalog for the source build (if available) 3. Loads the catalog for the current build 4. Finds parameters whose creation defaults changed between the two builds 5. For each affected operator, checks if the current value matches the *new* default - if so, the parameter was omitted during export (because it matched the *old* default), and TD has now assigned the wrong new default 6. Patches those parameters back to the old creation value A summary dialog is shown to the user listing every corrected parameter. #### Fallback chain The catalog is loaded in priority order: 1. **`.embody/` catalog file** - per-build JSON written by the background scan 2. **Embedded `divergent_defaults` table** - a DAT inside the Embody COMP with bootstrap data for known TD builds 3. **On-the-fly probing** - if neither source has data for the current build, a temporary operator is created at export time to discover the true creation value This ensures correct non-default comparison regardless of TD version, even on builds that Embody has never seen before. --- ## Built-in Parameter Sequences *Added in v1.3.* Many TouchDesigner operators have **resizable parameter blocks** - mathmixPOP Combine blocks, glslPOP/glslTOP uniform sequences, attributePOP attribute blocks, constantCHOP channel blocks, etc. These are called **parameter sequences** in TD's API. The `sequences` object stores per-operator sequence data. It is keyed by sequence name, where each value is an array of block objects containing only non-default parameter values using **base names** (without the sequence prefix or block index): ```yaml - name: mathmix1 type: mathmixPOP sequences: comb: - {oper: A, scopea: P, result: startPos} - {oper: A + B, scopea: vel, scopeb: direction, result: vel} - {} ``` ### Design - **Array length = `numBlocks`**: The importer sets `seq.numBlocks = len(blocks)` to create the right number of parameter slots before setting values. - **Base names**: `"oper"` rather than `"comb0oper"`. The full parameter name is `{seqName}{blockIndex}{baseName}` (e.g., `comb2oper`), but only the base name is stored. This makes the format portable and readable. - **Empty objects `{}`**: Represent blocks where all parameters are at their default values. Included to preserve correct block count and ordering. - **Omission**: The `sequences` key is omitted entirely when all sequences on the operator have their default block count and all block values are defaults. - **Default block count**: probed from a throwaway instance of the operator type (once per type per session), never assumed to be `1`. A sequence sitting *below* its type-default count therefore still exports its all-default block list, so the shrink survives reimport. - **Value shorthand**: Same as built-in parameters - `=` prefix for expressions, `~` prefix for binds, literal values for constants. ### Import Phase Sequences are expanded in two passes: - **Phase 2.5** (before Phase 3 parameter setting): sequences whose blocks carry values. This ensures the dynamically-created sequence parameters exist before Phase 3 attempts to set values on them. - **Phase 5.5** (after Phase 5 wiring): sequences whose blocks are **all empty** (`[{}, {}, ...]`). An all-empty list is purely a `numBlocks` instruction, and some sequences track the operator's wired inputs (a `mergePOP`'s `input` sequence grows one block per connection). Applying such a count before wiring declares inputs on an unwired operator and latches a `No input POP`-class error that surfaces as a reconstruction error on project open. Applied after wiring, the count already matches and the set is a no-op - while independent sequences still receive their count correctly. ### Exclusion from type_defaults Sequence data is **never included in `type_defaults`**. Sequences are inherently per-instance (different operators have different block counts), so they cannot be compressed into per-type defaults. --- ## Custom Parameters The `custom_pars` object maps page names to arrays of parameter definitions. Unlike built-in parameters, custom parameters are **always fully exported** (including their definitions, ranges, and current values) because the importer must recreate them from scratch. !!! note Only COMPs can have custom parameters in TouchDesigner. !!! note "Transient status parameters (Embody-managed COMPs)" Parameters registered as runtime status readouts on Embody-managed COMPs (registry: `EmbodyExt._TRANSIENT_STATUS_PARS`, scoped by the COMP's global OP shortcut) are exported with their declared **resting value** instead of the session value -- a status like `Running on port 9872` is machine state, not authored config, and would otherwise churn in version control on every export. Companion registry `_TDN_VALUE_OMIT_PARS` drops the `value` key of machine-written metadata stamps (`Build`, `Date`; definitions still ship). `_TRANSIENT_STATUS_PARS` also holds a few **user preferences** whose live value is restored per machine from `.embody/config.json` rather than from the file -- `Convoyenable`, `Clipboardautopaste`, `Filecleanup`, `Toxdropexpr` -- exported with their resting value (`keep`, `ask`, ...) like any other registered status par, so a receipt or a released `.tox` never carries one developer's (or the test runner's) setting into every project. The **Externalizations** table link is registered the same way (resting: its empty default) because an OP path is a location inside the authoring project, and `ExportPortableTox` additionally empties the Embody COMP's *storage* around the release save -- neither belongs in a shipped `.tox`. Expression and bind values (the `=`/`~` shorthand) are never replaced. A registered parameter **sequence** exports no block values; its block count ships only when it differs from the type default. User COMPs are never affected -- the registries key on global OP shortcuts. One page is dropped outright rather than value-stripped: an `About` page whose parameters are **only** Embody's per-COMP metadata stamp (`Build`, `Date`, `Touchbuild`) is omitted from `custom_pars` entirely, because those values are reconstructed from `externalizations.tsv` on import. The stamp is written on every externalized COMP, so most COMPs' `.tdxn` files carry no About page at all. An About page holding any additional authored parameter -- including the Embody COMP's own, larger About page -- is exported normally. ### Page-Grouped Format Custom parameters are grouped by page name. Each page contains an array of parameter definitions: ```yaml custom_pars: Controls: - name: Speed style: Float default: 1 max: 10 clampMin: true normMax: 5 value: 2.5 - name: Mode style: Menu menuNames: [linear, ease, bounce] menuLabels: [Linear, Ease In/Out, Bounce] value: 1 About: - name: Build style: Int label: Build Number readOnly: true value: 14 ``` The page name is the dict key - individual parameter definitions do not include a `"page"` field. ### Template References When a page's parameter definitions match a [parameter template](#parameter-templates), the page is stored as a template reference with value overrides: ```yaml custom_pars: About: $t: about Build: 14 Date: 2026-02-19 16:09:43 UTC Touchbuild: '2025.32050' ``` The `$t` field names the template. Other keys are parameter value overrides (parameter name -> current value). See [Parameter Templates](#parameter-templates). ### Custom Parameter Definition | Field | Type | Condition | Description | |-------|------|-----------|-------------| | `name` | string | Always | Base name of the parameter. For multi-component parameters, this is the group name without any suffix (e.g., `"Pos"` for a group of `Posx`, `Posy`, `Posz`). | | `label` | string | If different from `name` | Display label shown in the parameter dialog. Omitted when the label matches the parameter name. | | `style` | string | Always | Parameter style. See [Supported Styles](#supported-styles). | | `size` | integer | Multi-component `Float`/`Int`; suffix-style groups with non-full arity | Number of components when > 1 (e.g., `3` for a 3-component float). Also written for suffix-style groups (`RGBA`, `XYZW`, `UVW`) whose component count differs from the style's full size - TouchDesigner reports style `RGBA` for both RGB (3) and RGBA (4) groups, `XYZW` for XY/XYZ/XYZW, and `UVW` for both UV (2) and UVW (3), so `size` disambiguates (e.g. `3` for an RGB group, `2` for a UV group). When omitted on a suffix-style group, importers use the `values` length, else the style's full component count. | | `default` | any or array | If non-standard | Default value. Omitted when every component's default is a standard value (`0`, `0.0`, `""`, or `false`). Per-component: a scalar when the whole tuplet agrees, an array (one entry per component) when it does not. See [Per-component definition fields](#per-component-definition-fields). | | `min` | number or array | If != `0` | Minimum value. Per-component (see below). | | `max` | number or array | If != `1` | Maximum value. Per-component (see below). | | `clampMin` | boolean or array | If `true` | Whether the value is clamped to `min`. Per-component (see below). | | `clampMax` | boolean or array | If `true` | Whether the value is clamped to `max`. Per-component (see below). | | `normMin` | number or array | If != `0` | Normalized range minimum (for slider UI). Per-component (see below). | | `normMax` | number or array | If != `1` | Normalized range maximum (for slider UI). Per-component (see below). | | `menuNames` | array of strings | Manually defined menus | Internal names for each menu option. | | `menuLabels` | array of strings | If different from `menuNames` | Display labels for each menu option. Omitted when labels match names. | | `menuSource` | string | Dynamically populated menus | DAT path or expression that populates the menu. When present, `menuNames`/`menuLabels` are omitted. | | `startSection` | boolean | If `true` | Whether this parameter starts a new visual section. | | `readOnly` | boolean or array | If `true` | Whether the parameter is read-only. Per-component (see below). | | `password` | boolean or array | If `true` | Masks the value as asterisks in the parameter dialog. TouchDesigner allows it on custom `Str`/`Int`/`Float` parameters. Per-component. | | `styleCloneImmune` | boolean or array | If `true` | Keeps the parameter *definition* from being matched to the master on a clone sync. Per-component. | | `bindRange` | boolean | If `true` | Routes `min`/`max`/`clampMin`/`clampMax`/`normMin`/`normMax`/`normVal` to the bind master. **Tuplet-wide**, not per-component - TouchDesigner propagates it across every component of a group, so it always serializes as a scalar (verified 2026-09-04). | | `defaultExpr` | string or array | If non-empty | The parameter's default *expression*, distinct from the constant `default` and from the parameter's live `value`. Stored raw - the `=`/`~` shorthand applies to `value`/`values` only. Per-component. | | `defaultBindExpr` | string or array | If non-empty | The parameter's default bind expression. Stored raw, same as `defaultExpr`. Per-component. | | `defaultMode` | string or array | If not `CONSTANT`, or whenever `defaultExpr`/`defaultBindExpr` is set | `ParMode` name (`CONSTANT`, `EXPRESSION`, `EXPORT`, `BIND` -- all four, verified 2026-09-04) the parameter resets to. Written even when `CONSTANT` if a default expression is present: assigning `defaultExpr` auto-flips `defaultMode` to `EXPRESSION`, so a parameter authored with a default expression but forced back to `CONSTANT` would otherwise reconstruct with the wrong reset behavior (verified 2026-09-04). On import it is applied **after** the expressions, to override that side effect. Per-component. | | `enable` | boolean or array | If `false` | Static enable state (greyed out when `false`). Omitted when an `enableExpr` is set. Per-component. | | `enableExpr` | string or array | If set | Python expression that controls the enable state (conditional greying). Per-component in TDXN, though TouchDesigner documents it as shared across a ParGroup. | | `sequence` | string | Template pars of a custom sequence | Name of the custom sequence this definition belongs to. | | `help` | string or array | If non-empty | Tooltip help text shown when hovering the parameter in the dialog. Omitted when empty. Per-component. | | `value` | any | Single-component, if non-default | Current value. Can be a constant, `"=expr"` string, or `"~bind"` string. Omitted when the value equals the default; the importer then seeds the value from `default`, since TouchDesigner leaves a freshly created parameter at `0`/`""` regardless of its default. | | `values` | array | Multi-component, if any non-default | Current values for each component. Same format as `value` per element. Omitted when all values equal their defaults; the importer then seeds every component from `default` (a scalar broadcasts, a list maps per component). | #### Per-component definition fields `default`, `min`, `max`, `clampMin`, `clampMax`, `normMin`, `normMax`, `readOnly`, `password`, `styleCloneImmune`, `defaultExpr`, `defaultBindExpr`, `defaultMode`, `help`, `enable` and `enableExpr` belong to each *component* of a tuplet, not to the group: an `RGBA` parameter has four independent defaults, a `WH` two independent norm ranges, and a tuplet can be read-only in one component only. `bindRange` is the documented exception - TouchDesigner propagates it across the whole tuplet, so it always serializes as a scalar. - Written as a **scalar** when every component holds the same value (the common case, and what single-component parameters always produce). - Written as an **array**, one entry per component in group order, when the components differ. ```yaml - name: Color style: RGBA default: [0.1, 0.2, 0.3, 1] # per component - name: Size style: WH default: [500, 250] normMax: [1000, 2000] - name: Pos style: XYZ default: 2.5 # all three components agree ``` Readers broadcast a scalar across every component and map an array 1:1 (a short array leaves the remaining components untouched). Files written before Embody 6.2.11 carry only the first component's value as a scalar; reading them broadcasts that value, which is why a vector parameter's defaults can shift once on the first re-read of an old file. ### Supported Styles All 32 parameter styles recognized by TDXN: | Style | Category | Description | |-------|----------|-------------| | `Float` | Numeric | Floating-point number. Supports `size` > 1 for multi-component (suffixed `1`, `2`, `3`...). | | `Int` | Numeric | Integer number. Supports `size` > 1 for multi-component (suffixed `1`, `2`, `3`...). | | `XY` | Numeric compound | Two-component float (`x`, `y`). | | `XYZ` | Numeric compound | Three-component float (`x`, `y`, `z`). | | `XYZW` | Numeric compound | Four-component float (`x`, `y`, `z`, `w`). | | `WH` | Numeric compound | Two-component float (`w`, `h`). | | `UV` | Numeric compound | Two-component float (`u`, `v`). | | `UVW` | Numeric compound | Three-component float (`u`, `v`, `w`). | | `RGB` | Numeric compound | Three-component float (`r`, `g`, `b`). | | `RGBA` | Numeric compound | Four-component float (`r`, `g`, `b`, `a`). | | `Str` | String | Text string. | | `Menu` | Menu | Dropdown menu. Uses `menuNames`/`menuLabels` for static menus, or `menuSource` for dynamic menus. | | `StrMenu` | Menu | Editable string with dropdown suggestions. Uses `menuNames`/`menuLabels` or `menuSource`. | | `Toggle` | Boolean | On/off checkbox. | | `Pulse` | Action | Fire-once button (no persistent value). | | `Momentary` | Action | Button that is active while held. | | `Header` | Visual | Section header label (no value). | | `File` | Path | File path selector (open). | | `FileSave` | Path | File path selector (save). | | `Folder` | Path | Folder path selector. | | `Python` | Code | Python expression field. | | `OP` | Reference | Operator path reference (any type). | | `COMP` | Reference | COMP operator reference. | | `TOP` | Reference | TOP operator reference. | | `CHOP` | Reference | CHOP operator reference. | | `SOP` | Reference | SOP operator reference. | | `DAT` | Reference | DAT operator reference. | | `MAT` | Reference | MAT operator reference. | | `POP` | Reference | POP operator reference. | | `Object` | Reference | Object COMP reference. | | `PanelCOMP` | Reference | Panel COMP reference. | | `Sequence` | Sequence | Sequence block parameter. | ### Multi-Component Parameters Some parameters consist of multiple related components grouped together (called "tuplets" in TouchDesigner). **Compound styles** (XY, XYZ, XYZW, WH, UV, UVW, RGB, RGBA) have named suffixes: ```yaml - name: Pos style: XYZ values: [10.0, 20.0, 30.0] ``` This creates three parameters: `Posx`, `Posy`, `Posz`. The suffix mappings are: | Style | Suffixes | |-------|----------| | `XY` | `x`, `y` | | `XYZ` | `x`, `y`, `z` | | `XYZW` | `x`, `y`, `z`, `w` | | `WH` | `w`, `h` | | `UV` | `u`, `v` | | `UVW` | `u`, `v`, `w` | | `RGB` | `r`, `g`, `b` | | `RGBA` | `r`, `g`, `b`, `a` | **Numeric multi-component** (Float or Int with `size` > 1) use numeric suffixes: ```yaml - name: Weight style: Float size: 3 values: [0.5, 0.3, 0.2] ``` This creates three parameters: `Weight1`, `Weight2`, `Weight3`. --- ## Type Defaults The `type_defaults` section hoists properties that are shared unanimously across **all** operators of a given type into a single location, removing them from individual operators. Supported properties: `parameters`, `flags`, `size`, `color`, and `tags`. ```yaml type_defaults: containerCOMP: parameters: borderover: false reloadbuiltin: false resizecomp: =me repocomp: =me flags: - viewer size: [300, 150] textDAT: parameters: language: text flags: - viewer size: [130, 90] color: [0.67, 0.67, 0.67] tags: - source ``` ### Unanimity Rule A property enters `type_defaults` **only** if: 1. The operator type appears 2+ times in the export 2. The property is present on **every** operator of that type 3. The property has the **same value** across all operators of that type This eliminates the need for a "reset to default" marker - if a property is in `type_defaults`, every operator of that type has it. ### Import Behavior On import, `type_defaults` are merged into each operator before the relevant import phase. `parameters` use dict-level merge (operator-specific keys override individual defaults). `flags`, `size`, `color`, and `tags` use whole-value replacement (the operator either has its own value or inherits entirely from type_defaults): ``` effective_params = type_defaults[op_type].parameters | operator.parameters effective_flags = operator.flags ?? type_defaults[op_type].flags effective_size = operator.size ?? type_defaults[op_type].size effective_color = operator.color ?? type_defaults[op_type].color effective_tags = operator.tags ?? type_defaults[op_type].tags ``` ### When Type Defaults are Omitted - If no types have 2+ operators with shared properties, the `type_defaults` key is absent - Single-instance operator types never contribute to type_defaults --- ## Parameter Templates The `par_templates` section extracts custom parameter page definitions that repeat across 2+ operators into named, reusable templates. ```yaml par_templates: about: - {name: Build, style: Int, label: Build Number, readOnly: true} - {name: Date, style: Str, label: Build Date, readOnly: true} - {name: Touchbuild, style: Str, label: Touch Build, readOnly: true} ``` Templates contain parameter definitions **without values** - they define the structure (name, style, label, ranges, etc.) of a page's parameters. ### Template References Operators reference templates via `$t` in their `custom_pars`: ```yaml custom_pars: About: $t: about Build: 14 Date: 2026-02-19 16:09:43 UTC Touchbuild: '2025.32050' ``` | Field | Description | |-------|-------------| | `$t` | Template name (matches a key in `par_templates`) | | Other keys | Value overrides: parameter name -> current value | ### Import Behavior On import, `$t` references are resolved before Phase 2 (create custom parameters). Each template reference is expanded back into a full array of parameter definitions, with value overrides applied: ```yaml # Resolved from template + overrides: About: - {name: Build, style: Int, label: Build Number, readOnly: true, value: 14} - {name: Date, style: Str, label: Build Date, readOnly: true, value: 2026-02-19 16:09:43 UTC} - {name: Touchbuild, style: Str, label: Touch Build, readOnly: true, value: '2025.32050'} ``` ### Template Naming Template names are derived from the page name (lowercased, spaces replaced with underscores). Collision suffixes (`_2`, `_3`) are added if multiple distinct page definitions share the same page name. ### When Templates are Omitted - If no page definition appears on 2+ operators, the `par_templates` key is absent - Pages unique to a single operator are always stored inline --- ## Flags The `flags` array contains string names of flags whose values differ from their defaults. | Flag | Default | Description | |------|---------|-------------| | `bypass` | `false` | Operator is skipped in the processing chain. | | `lock` | `false` | Operator output is locked (frozen). See [Lock Flag Limitation](#lock-flag-limitation). | | `display` | `false` | Marks this operator as the display output (blue flag). | | `render` | `false` | Marks this operator for rendering (purple flag). | | `viewer` | `false` | Shows the operator's viewer on its node tile. | | `expose` | `true` | Whether the node is visible in the network editor. | | `allowCooking` | `true` | Whether the COMP is allowed to cook. Readable on any operator, but **only a COMP can disable it**. | | `cloneImmune` | `false` | The operator is immune to clone re-sync. Present on every operator, not COMPs only (verified 2026-09-04). | | `componentCloneImmune` | `false` | The "including children" state of the Immune flag: the COMP **and**, recursively, every node inside it are immune to clone re-sync. Paired with `cloneImmune` (which covers the node alone) as the Python half of one three-state UI flag. **COMPs only** (the attribute does not exist on other operators). | | `showCustomOnly` | `false` | The parameter dialog shows only custom pages. Present on every operator. | | `showDocked` | `true` | Docked operators are shown attached to their host. Present on every operator; being `true` by default, it serializes as `-showDocked` when turned off. | An importer ignores any flag name outside this table (it never assigns arbitrary attributes from a file), and additionally skips any flag the destination operator cannot carry - `componentCloneImmune` on a TOP, or `allowCooking` on anything that is not a COMP. !!! note "Defaults are per-type creation values" The exporter compares each flag against the **creation defaults probed for that operator type** - the same catalog-probe mechanism used for [parameter creation defaults](#divergent-defaults-and-the-creation-defaults-catalog): a temporary operator of the type is created and its actual flag values recorded. The table above is the common fallback baseline, used when probing is unavailable, not a guarantee for every operator type. For a type whose creation default differs from the listed value, an omitted flag means "this type's creation default", not the value in the table. ### Format Flags that default to `false` are listed by name when set to `true`: ```yaml flags: - viewer - display ``` Flags that default to `true` use a `-` prefix when set to `false`: ```yaml flags: - -expose ``` Combined example - viewer on, cooking disabled: ```yaml flags: - viewer - -allowCooking ``` ### Lock Flag Limitation !!! warning "Locked content is NOT preserved for TOPs, CHOPs, SOPs, or POPs" TDXN preserves the **lock flag** for all operator families, but it **cannot store frozen pixel, channel, geometry, or point data**. After a TDXN round-trip (export + import), locked non-DAT operators will be locked but **empty** - no texture, no samples, no mesh, no points. **This is by design, not a bug.** Storing binary data would defeat TDXN's purpose as a diffable, version-control-friendly format. A single locked 4K TOP could add over 100 MB to a `.tdxn` file. **When the data is lost.** In the default Export mode (`Tdxnmode` = `export`) the `.toe` keeps the frozen data. It is lost only when the COMP is rebuilt from its `.tdxn`: Roundtrip mode, `import_network` with `clear_first`, crash recovery of a missing COMP, or a checkout without the `.toe`. In Roundtrip mode (Full mode with strip on save) every save rebuilds the COMP from its `.tdxn`, so the data is lost at the next save. Embody warns you at save time if your network contains locked non-DAT operators. The warning covers only operators the export itself serializes - locked content inside a nested tox/tdn-tagged child COMP (exported separately as its own boundary) or an exclude-tagged subtree does not trigger it. The `lock` flag applies to **all** operator families - DATs, TOPs, CHOPs, SOPs, and POPs - freezing their cooked output so it no longer updates from inputs or parameters. However, TDXN only persists the frozen data for DATs. | Family | Flag persisted? | Frozen data persisted? | Notes | |--------|:-:|:-:|---| | **DAT** | Yes | Yes (via `dat_content`) | Full round-trip: both the lock state and text/table content are preserved. | | **TOP** | Yes | **No** | Pixel data is not stored. On import, the lock flag is set but no texture data exists. The operator will appear black. | | **CHOP** | Yes | **No** | Channel data is not stored. On import, the lock flag is set but no sample data exists. | | **SOP** | Yes | **No** | Geometry data is not stored. On import, the lock flag is set but no mesh data exists. | | **POP** | Yes | **No** | Point data is not stored. On import, the lock flag is set but no points exist. | #### Source labels The warning labels each locked operator with what unlocking it would do after a rebuild, traced along wires only: | Dialog label | Log token | Meaning | |---|---|---| | re-cooks if unlocked | `source: recooks` | Unlocking this operator alone produces output again. The frozen snapshot is **replaced, not restored**: unlocking never brings the locked data back. | | NO SOURCE | `source: none` | Nothing wired in survives a rebuild. Unlocking leaves it empty. | | source not traced | `source: unknown` | The source could not be traced. Treat it as no source. | A generator is a source. A filter follows its inputs. An In operator follows its COMP's input connector, and falls back to its own input when that connector is unwired; a wire into the exported COMP itself counts as a source. A locked operator upstream is a dead end, because it comes back empty too, unless it sits inside a TOX-tagged, exclude-tagged, clone, or replicant COMP whose data survives. Parameter references (Select, Object Merge, OP Viewer, Render, CHOP to, Feedback, Script callbacks), mixed sources and very large scans read **source not traced**. Expressions are not traced. Every export that writes a COMP's `.tdxn` file -- `externalize_op`, `save_externalization`, or a save that re-exports a changed COMP -- logs **one WARNING per exported COMP** with each operator's `source:` token and the exact `externalize_op(..., tag_type='tox')` call that keeps them, so MCP callers and scripted exports get the same answer as the dialog. A save that finds the COMP unchanged, autosave checkpoints, and ad-hoc snapshots of a tracked COMP skip the scan. Envoy's `externalize_op`, `save_externalization` and `export_network`, and the Autoexternalize step of `create_op`, `copy_op` and `create_extension`, never show the dialog; Python run through `execute_python` that calls Update or saveTDXN still can. **Workarounds:** - **Keep the data in a .tox.** Click **Switch to TOX** in the dialog, or run `externalize_op('', tag_type='tox')`. The narrowest COMP below the TDXN COMP that holds the locked operators is stored as a `.tox`, and the parent `.tdxn` references it with `tox_ref`; a `.tox` keeps locked TOP, CHOP, SOP, and POP data. The switch runs a few frames after the dialog closes. Operators sitting directly in a top-level TDXN COMP have no narrower COMP: move them into a child COMP first (a TDXN COMP nested in another one, the Tdxncascade shape, can itself be switched). - **Unlock** only when a fresh cook is acceptable, and only operators marked **re-cooks**. An operator marked NO SOURCE has nothing to re-cook from, so unlocking leaves it empty; one marked source not traced may have none, so treat it the same. - **Store data externally** - write pixel data to image files, channel data to CSV, etc., and reference them from your network. --- ## Connections TouchDesigner operators have two kinds of connections. TDXN stores both as string arrays where array position equals the input index. ### Operator Connections Standard wiring between operators (left/right connectors). Stored in the `inputs` array: ```yaml inputs: - noise1 ``` Multi-input example - `noise1` at index 0, nothing at index 1, `level1` at index 2: ```yaml inputs: - noise1 - null - level1 ``` A bare name always means the source's **output connector 0**. When the wire leaves a later output connector - a COMP holding several Out OPs (`out_line`, `out_params`, `out_fill`), or any multi-output operator - the entry is a mapping that names the output as well (v2.1; entries stay at their input position): ```yaml inputs: - layer # layer's output 0 -> input 0 - {source: layer, out: 2} # layer's output 2 -> input 1 ``` Readers that predate `out` wire such entries from output 0, which is exactly what happened before the key existed: every consumer of a multi-output COMP received the same stream. ### COMP Connections COMP-level wiring (top/bottom connectors). Only applicable to COMPs. Stored in the `comp_inputs` array: ```yaml comp_inputs: - container1 ``` ### Source Resolution Each string element references the source operator: - If the source operator is a **sibling** (same parent), only the operator **name** is stored (e.g., `"noise1"`). - If the source is in a **different parent**, the full **path** is stored (e.g., `"/project/other/transform1"`). - `null` means no connection at that index. On import, the source is resolved by first looking for a sibling with that name, then falling back to interpreting it as a full path. ### Array Length The array is truncated at the **last connected index** - trailing `null` entries never appear. Dynamic multi-input operators (Switch, Composite, Merge) always expose one trailing empty connector in TouchDesigner; it is never serialized, so densely wired networks produce byte-identical `inputs` arrays across exports. An exporter that emitted trailing nulls would produce a spurious diff on every multi-input operator in every file. Indices are derived from the operator's real **input connectors**, never from TouchDesigner's `OP.inputs` (a compacted list of connected sources that cannot represent a gap) - a wire on connector 2 with connectors 0-1 empty exports as `[null, null, "src"]`, and reimports onto connector 2. ### Known Limitation: Source Output Index Each element names the source operator only; there is no field for the source's **output connector index**. A multi-output source (e.g. a COMP with several Out operators) wired from output 1 or higher is re-imported from output 0. Representing it would require a format extension (the importer already tolerates dict-shaped entries for forward compatibility). --- ## Docking Operators in TouchDesigner can be visually docked to other operators. A docked operator moves with its host in the network editor and can be collapsed into the host's tile. When an operator is docked, TDXN records a `"dock"` field on it: | Field | Type | Condition | |-------|------|-----------| | `dock` | string | Only if the operator is docked to another operator. | The value is the **sibling name** of the dock host when they share a parent COMP, or the **full operator path** for cross-hierarchy docking. This follows the same reference convention as [operator connections](#connections). Docking is a purely visual/organizational relationship - it has no effect on operator behavior, data flow, or cooking. It is omitted from `type_defaults` because docking is always instance-specific. **Example:** ```yaml - name: info1 type: infoDAT dock: noise1 ``` During import, the dock target is resolved by sibling name first, then full path fallback. If the target cannot be found, a warning is logged and docking is skipped gracefully. --- ## DAT Content DAT-family operators can include their text or table data. The `include_dat_content` option controls only content a file already holds; content saved nowhere else is always included (see [Inclusion Conditions](#inclusion-conditions)). ### Text Format For text-based DATs (textDAT, etc.): ```yaml - name: script1 type: textDAT dat_content: | print('hello world') print('goodbye') dat_content_format: text ``` - `dat_content`: the DAT's text, stored in v2.0 as a **plain string**. Multi-line scripts are rendered on disk as a YAML **literal block scalar** (`|`), so the text stays human-readable and git diffs it line-by-line. Single-line content stays a compact inline string. - `dat_content_format`: `text` **Trailing-newline chomping.** YAML's literal block scalar preserves the exact number of trailing newlines through a chomping indicator chosen automatically by the writer: `|-` (strip) when the text has no trailing newline, `|` (clip) for a single trailing newline, and `|+` (keep) for two or more. The round-trip is therefore byte-exact for trailing whitespace. **Back-compatibility:** v1.5 stored a multi-line text DAT's `dat_content` as an **array of line-strings**, and v1.x earlier stored it as a single newline-escaped string. Both still import unchanged - a string is used as-is, an array is joined with `\n`. Examples of the still-valid legacy forms: ```json { "name": "script1", "type": "textDAT", "dat_content": ["print('hello world')", "print('goodbye')"], "dat_content_format": "text" } ``` ```json { "name": "script1", "type": "textDAT", "dat_content": "print('hello world')\nprint('goodbye')", "dat_content_format": "text" } ``` ### Table Format For table-based DATs (tableDAT, etc.): ```yaml - name: lookup1 type: tableDAT dat_content: - [name, value, type] - [speed, '1.5', float] - [active, '1', int] dat_content_format: table ``` - `dat_content`: array of row arrays (each row is an array of cell value strings) - `dat_content_format`: `table` ### Inclusion Conditions DAT content is only included when: 1. The operator belongs to the DAT family 2. The DAT is not tagged `tdxn_exclude:dat_content` (the exclude-tag prefix plus the reserved name `dat_content`), which drops its rows while the operator still exports 3. The `include_dat_content` option is `true`, **OR** the DAT lives inside an `animationCOMP` (its keys/channels/graph/attributes tableDATs hold all keyframe data and are always saved regardless of the option), **OR** its content is saved nowhere else on disk (no externalization tag, and no `file` parameter pointing at an existing file that is synced or holds the same text). With the option `false`, only content a file already holds is skipped; unbacked content is never dropped 4. The DAT is editable (`DAT.isEditable`); otherwise it carries `dat_read_only: true` instead (below) 5. The DAT has content (non-empty text or at least one row) **Read-only DATs.** When a DAT's content is read-only (e.g. `glsl1_info`, `popto1` - TD auto-generates their content and rejects writes on import), its text is **not** serialized. Instead the operator carries `dat_read_only: true` so the importer knows to skip content restoration for it. ### Boilerplate Omission Auto-created default docked compute DATs (the "Example Compute Shader" companion that TouchDesigner spawns alongside a `glslTOP` / `glslmultiTOP`) are **not serialized** when their text still matches TD's default template. TD recreates the exact default on import, so omitting it keeps the file smaller with no loss. A compute DAT whose shader has been edited away from the default is exported normally. --- ## Operator Storage Every TouchDesigner operator has a `.storage` dictionary for persistent Python data. TDXN exports all serializable storage entries except known transient/internal keys used by Embody's runtime. Keys are written in sorted order. A non-finite float (`nan`, `inf`) is skipped with a debug log, never aborting the export. !!! warning "Reserved keys" A two-key mapping of exactly `$type` and `$value` is the wrapper the format uses for tuples, sets and bytes (see [Value Serialization](#value-serialization)); a user dictionary of that exact shape is reconstructed as the wrapped type on import. Any other dictionary containing `$type` is a plain dictionary. ### Per-COMP Storage Toggle Storage export can be disabled per-COMP by setting the `embed_storage_in_tdn` storage key to `false` on the target COMP, or globally via Embody's `Embedstorageintdxns` parameter. When disabled, the `options.include_storage` field is `false` and operator storage entries are omitted - except for Embody control keys (`embed_dats_in_tdn`, `embed_storage_in_tdn`) which are always preserved to maintain round-trip fidelity of export preferences. ### Format ```yaml - name: my_comp type: baseCOMP storage: count: 42 label: hello items: [1, 2, 3] config: {key: value} coords: {$type: tuple, $value: [10, 20]} tags: {$type: set, $value: [a, b, c]} raw: {$type: bytes, $value: AAEC/w==} ``` ### Value Serialization Python types that map directly to JSON are stored as-is. Non-JSON types use a `$type`/`$value` wrapper: | Python Type | JSON Representation | |-------------|---------------------| | `str`, `int`, `float`, `bool` | Direct JSON value | | `None` | `null` | | `list` | JSON array (recursive) | | `dict` | JSON object (recursive, string keys only) | | `tuple` | `{"$type": "tuple", "$value": [...]}` | | `set` | `{"$type": "set", "$value": [...]}` (sorted for determinism) | | `bytes` | `{"$type": "bytes", "$value": ""}` | Values that cannot be serialized to JSON (threading objects, operator references, custom class instances) are silently skipped during export. ### Skipped Keys The following storage keys are never exported - runtime and session state managed by Embody, grouped by what each family holds: | Category | Keys | |----------|------| | Embody runtime / UI state | `_git_root`, `envoy_running`, `envoy_shutdown_event`, `claudius_running`, `expanded_paths`, `expand_order`, `git_status`, `manage_file_path`, `visible_count`, `hover`, `pressed`, `_tip_trace` | | Dirty-detection baselines | `_tdn_fingerprints` | | Strip and restore markers | `_tdn_stripped_paths`, `_tdn_rel_path`, `_pending_tox_restore`, `_pending_tdn_restore` | | Lifecycle flags | `_suppress_dialogs`, `_init_complete`, `_start_in_progress`, `_release_hook_active`, `_tdn_restore_failures` | | Test-runner bookkeeping | `_test_saved_filecleanup`, `_test_saved_toxdropexpr`, `_test_saved_status`, `_smoke_test_responses`, `test_results`, `cp_summary`, `_test_run_active`, `_test_run_owner` | | Loop generation counters | `_watchdog_gen`, `_clip_watch_gen`, `_shortcut_rec_gen`, `_convoy_gen` | Two families are worth understanding rather than just listing. The **restore markers** are per-`.toe` recovery state: a serialized `_tdn_rel_path` would make every pasted copy claim the original's file, and a serialized `_pending_tdn_restore` would be replayed by Phase 6a on every import, re-importing the child from a baked ref path forever. The **generation counters** are bumped on every extension reinit purely so a previous instance's pending `run()` tick retires itself; because they change constantly, exporting them rewrote several lines of committed `.tdxn` files on every save. ### Startup Storage TouchDesigner supports `storeStartupValue(key, value)` - values that reset to their initial state on every project open, regardless of what they were when the file was saved. TDXN supports this via an optional `startup_storage` field: ```yaml - name: my_comp type: baseCOMP storage: {runtime_count: 0} startup_storage: {version: 1, default_mode: auto} ``` On import, keys in `startup_storage` are restored via `storeStartupValue()`, while keys in `storage` use `store()`. **Export limitation:** TouchDesigner provides no API to introspect which storage keys were set with `storeStartupValue()` vs `store()`. During automatic export, all entries go into `storage`. The `startup_storage` field must be populated manually or by tools that know the intent (e.g., code generators, StorageManager-aware exporters). ### Import Behavior Storage is restored during Phase 6a (after DAT content, before positions). Keys in `storage` are restored via `op.store(key, value)`. Keys in `startup_storage` are restored via `op.storeStartupValue(key, value)`. `$type` wrappers are deserialized back to their Python types. Unknown `$type` values are treated as plain dicts with a warning logged. The [skip list](#skipped-keys) is applied on import as well: a skipped key found in a `.tdxn` is ignored rather than restored. A stale entry written by an older build therefore dies on the next round-trip instead of ratcheting forward forever. --- ## Children and Hierarchy COMPs can contain child operators. These are stored in the `children` array, which contains nested operator objects following the exact same schema: ```yaml - name: container1 type: baseCOMP children: - name: noise1 type: noiseTOP - name: null1 type: nullTOP position: [300, 0] inputs: - noise1 ``` Note that `container1` omits `position` (defaults to `[0, 0]`) and `noise1` also omits `position`. Only `null1` at `[300, 0]` includes its position. Nesting is recursive - COMPs inside COMPs can have their own `children`. The optional `max_depth` export parameter limits recursion depth (`null` means unlimited). COMPs may also contain an `annotations` array alongside `children` - see [Annotations](#annotations). ### Nested TDXN-Externalized COMPs When a parent TDXN file contains `children` for a child COMP that has its **own** TDXN externalization entry in the externalizations table, the child's `children` array is **skipped during import**. The child COMP shell is still created (its operator definition - name, type, position, parameters - is applied), but its internal network is **not** populated from the parent's snapshot. The child's own `.tdxn` file is the source of truth for its contents. This prevents a common problem: if a child COMP is updated and re-exported to its own `.tdxn` file, but the parent is not re-exported, importing the parent would silently overwrite the child with stale data. By skipping nested TDXN children, each `.tdxn` file owns exactly one level of the hierarchy. **What this means in practice:** - **Export** writes a [`tdn_ref`](#comp-references-tdn_ref) pointer in place of the child's `children`. An `embed_all` export still writes the full recursive hierarchy, for a self-contained portable snapshot. - **Import** detects child COMPs with their own TDXN entries and skips their children. A log message is emitted for each skipped child (e.g., `Skipping children of /project/parent/child - has its own TDXN externalization`). - **Reconstruction on project open** imports parents before children (sorted by path depth). Combined with the skip logic, this means each COMP's network is populated exactly once, from its own authoritative `.tdxn` file. If a child COMP is removed from the externalizations table (no longer tagged for TDXN), its `children` array in the parent TDXN will be imported normally - no special handling needed. ### COMP References (`tdn_ref`) *Added in TDXN v1.2.* When a parent COMP is exported and a child COMP has its own TDXN externalization, the parent's operator definition for that child includes a `tdn_ref` field instead of a `children` array: ```yaml - name: audio_mixer type: baseCOMP tdn_ref: Embody/project1/audio_mixer.tdxn position: [600, 0] ``` | Field | Type | Description | |---|---|---| | `tdn_ref` | `string` | Relative file path from the externalization folder to the child's `.tdxn` file. Includes the COMP name in the path for cross-validation. | **Mutually exclusive with `children`**: When `tdn_ref` is present, the operator definition does not contain a `children` array. The COMP's internal network is defined entirely in the referenced file. **Placement only**: the entry records how the COMP sits in its parent (name, type, built-in parameters and sequences, flags, position, size, color, comment, tags, storage, wires, dock) and carries **no `custom_pars`** and no custom-parameter sequences. The child's own file holds them at its root, and import [Phase 0](#import-process) creates them before the child's operators, so anything inside the COMP finds them while it builds. While the referenced file is missing from disk the entry keeps the copy, since it is the only one. A second copy in the parent was overwritten on every import and changed the parent file whenever a value changed. **Resolution**: On import, the importer creates the COMP shell (name, type, position, parameters, flags) and marks it with a `_pending_tdn_restore` storage key holding the ref path. [Phase 8.6](#import-process) then imports the referenced `.tdxn` into that shell **in the same import**, re-entering the importer so deeper nesting recurses naturally; an ancestor-chain guard refuses a true ref cycle (`A.tdxn` -> `B.tdxn` -> `A.tdxn`) while two sibling shells pointing at the same file both fill. A nested externalized COMP is therefore never left empty by an import - an empty shell reads as changed content and the next automatic export would overwrite the child's own good `.tdxn`. Two callers pass `restore_tdxn_shells=False` and skip Phase 8.6: **startup reconstruction** (`ext.Embody.reconstructTDXNComps`) and the **post-save restore**. Their own depth-sorted loops already import every tracked TDXN COMP exactly once, parents before children, so filling shells inline would import the same files twice. In that mode the markers are only cleared, never acted on. **Cross-validation**: The `tdn_ref` value is checked against two independent sources: 1. **Externalizations table**: The child COMP's path must have an entry with `strategy='tdxn'` and a matching `rel_file_path`. 2. **Disk**: The referenced `.tdxn` file must exist at the resolved absolute path. Mismatches produce warnings, not errors - the COMP shell is always created regardless. This ensures graceful degradation when files are moved or the table is out of sync. **Backward compatibility**: - Files **without** `tdn_ref` (TDXN v1.1 and earlier) continue to work. The existing `_stripNestedTDNChildren` mechanism handles them via the externalizations table. - Files **with** `tdn_ref` imported by an older Embody that doesn't recognize the field will silently ignore it. The `_stripNestedTDNChildren` path handles the nested COMP correctly as a fallback. - The `embed_all=True` export option suppresses `tdn_ref` and inlines all children, producing a fully self-contained file regardless of child externalization status. ### TOX References (`tox_ref`) *Added in TDXN v1.4.* The same ownership principle applies when a child COMP is externalized as `.tox` instead of `.tdxn`. The parent's operator definition for that child includes a `tox_ref` field instead of a `children` array: ```yaml - name: wave_speed type: sliderCOMP tags: - tox tox_ref: Embody/project1/wave_speed.tox position: [475, 425] ``` | Field | Type | Description | |---|---|---| | `tox_ref` | `string` | Relative file path from the externalization folder to the child's `.tox` file. | **Mutually exclusive with `children`**: When `tox_ref` is present, the operator definition does not contain a `children` array. The COMP's internal network is defined entirely in the referenced `.tox` file. This prevents the parent `.tdxn` from duplicating the contents of the child `.tox`, which would otherwise pollute `type_defaults` with the child's internal operator types and bloat the parent file. **Resolution**: On import, the importer creates the COMP shell (name, type, position, parameters, flags) but does not populate its children. `externaltox` is **not** present in the parent `.tdxn`'s parameter dict (it's an Embody-managed parameter, excluded from TDXN export). Instead, the importer stores the `tox_ref` path on the new shell as `_pending_tox_restore` storage, then a post-import phase (`_restoreTOXShells`) sets `externaltox` from that marker and calls `_reloadTox` to load the `.tox` content immediately. This means the `.tox` content is fully restored after import - both for runtime imports (e.g. `import_network` via MCP) and for project-open reconstruction. `ext.Embody.restoreTOXComps` (frame 45) still handles the case where the parent `.tdxn` is not re-imported and the table is the only source. **No `custom_pars`**: like a `tdn_ref` entry, a `tox_ref` entry records only placement. Reloading a `.tox` with Reload Custom Parameters on (the default, and TDXN never exports it, so a rebuilt shell always has it) replaces the COMP's custom parameters and their values with the file's own (verified on TouchDesigner 2025.33230), so a copy in the parent was overwritten. **TOX vs TDXN, when to use which**: - **TOX**: opaque binary encapsulation. The `.tox` is a single self-contained file, fast to load, but not git-diffable. Suitable for palette widgets, third-party COMPs, and anything where you don't need text-level review of internals. - **TDXN**: text/YAML snapshot of the network. Fully git-diffable. Use this when you want pull requests to show changes to the COMP's internals. Both strategies receive the same ownership treatment in parent `.tdxn` files - neither embeds children into the parent. The strategy choice is about the **child file format**, not whether the parent embeds. **Backward compatibility**: - Pre-v1.4 `.tdn` files that embedded TOX children's contents still import correctly: on import, `_stripNestedTOXChildren` consults the externalizations table and clears any embedded `children` for TOX-tagged paths. The COMP shell is created and `ext.Embody.restoreTOXComps` loads from the `.tox` file. - Files **with** `tox_ref` imported by an older Embody that doesn't recognize the field will silently ignore it. The strip path handles the nested COMP correctly as a fallback. - The `embed_all=True` export option suppresses `tox_ref` and inlines all children. ### Palette Clones COMPs that originate from the TouchDesigner palette (e.g. `abletonLink`, Widget components, anything under `Samples/Palette/`) are detected and marked with `"palette_clone": true`. Their children are **not** exported because TouchDesigner automatically recreates them from the palette source when the project loads. **Parameter handling for palette clones**: During export, parameters are compared against two baselines - the built-in default (`p.default`) and the clone source's actual value. If a parameter matches `p.default` but differs from the clone source, it is still exported. This prevents user-set values from being silently dropped when they happen to match the built-in default but not the clone source (e.g., a `buttontype` whose `p.default` is `"momentary"` but whose clone source is `"toggledown"`). The `clone` and `enablecloning` parameters are always excluded - TD auto-sets these during rebuild. #### Palette Detection Detection uses two strategies: 1. **Palette catalog** (primary): Embody ships a catalog at `embody/Embody/palette_catalog.tsv` built by scanning every `.tox` in TD's installed palette directory. The catalog records each component's `name`, `OPType`, and `min_children` count (264 entries for TD 099.2025.32280). A COMP is detected as a palette if its name matches a catalog entry, its `OPType` matches, and it has at least `min_children // 2` children (a floor that tolerates user modifications while rejecting empty user COMPs that happen to share a palette name). 2. **Clone expression heuristic** (fallback): if the `clone` parameter points to `/sys/` or references `TDBasicWidgets`, `TDResources`, or `TDTox`, the COMP is detected as a palette. Catches cases where the catalog doesn't cover the current TD build. **Exception**: paths and expressions under `/sys/TDTox/defaultCOMPs/` are explicitly excluded. That directory holds TD's native-operator templates - every freshly-created `buttonCOMP`, `panelCOMP`, etc. clones from there by default, and those are stock types, not palette components. Export them as regular COMPs. The catalog is loaded into memory by `CatalogManagerExt.EnsureCatalogs()` at startup from the shipped TSV (skipping a runtime scan) or from `.embody/catalog_.json` if already cached locally. #### Palette Handling When the export path encounters a detected palette COMP, the `Tdxnpalettehandling` parameter on Embody's TDXN page decides what to do: | Value | Behavior | |---|---| | `Ask` (default) | On first encounter of each palette COMP, prompts with four buttons: **Black Box** (this COMP), **Full Export** (this COMP), **Black Box for All** (flips the project-wide par), **Full Export for All** (flips the project-wide par). The per-COMP decision is persisted via `comp.store('_tdn_palette_handling', 'blackbox'|'fullexport')` so subsequent exports don't re-prompt. | | `Black Box` | Always emit `"palette_clone": true` with parameter overrides only. Children are re-dropped from the palette on import. Correct for stock palette COMPs; lets upstream palette updates from Derivative flow through on round-trip. | | `Full Export` | Always export all internal children as if the COMP were a regular user COMP. Use when you've heavily customized the palette internals and need that state preserved across round-trip. | Per-COMP stored decisions take precedence over the project-wide par. To reset a COMP's stored decision, call `comp.unstore('_tdn_palette_handling')`. --- ### Sibling Clones An enabled clone (`enablecloning` on, `clone` resolving) whose master is a sibling COMP in the same network exports as its parameters only: `clone`, `enablecloning`, its custom parameter values, and no `children`. On import, Phase 3 sets the clone reference and TouchDesigner refills the COMP from the master before Phase 5 wires its connectors; a final pass (Phase 8.7) pulses a re-sync. A master, a clone that is itself a clone, a clone with an immune node inside it, or a clone whose master lives elsewhere exports in full. This is the shape to reach for whenever several COMPs share the same internals: one master, clones that differ only in their custom parameter values (32 mandala layers went from 12 children each in the file to their values, 2026-09-16). ## Annotations Annotations are visual documentation elements in TouchDesigner networks (comments, network boxes, and annotate panels). They are stored in an `annotations` array at the top level (for root-level annotations) and optionally on each COMP operator (for nested annotations). ```yaml operators: [ ... ] annotations: - name: annot_core mode: annotate title: Core Tests text: Unit tests for core functionality position: [-70, -300] size: [1070, 660] color: [0.5, 0.5, 0.5] opacity: 0.8 ``` For nested COMPs, `annotations` appears alongside `children`: ```yaml - name: container1 type: baseCOMP children: [ ... ] annotations: - name: annot1 mode: comment text: Signal processing chain ``` ### Annotation Object | Field | Type | Required | Condition for inclusion | |-------|------|----------|------------------------| | `name` | string | Yes | Always included. The annotation operator's name. | | `mode` | string | Yes | Always included. One of `"annotate"`, `"comment"`, or `"networkbox"`. | | `title` | string | No | Only if non-empty. Title bar text (for `annotate` and `networkbox` modes). | | `text` | string | No | Only if non-empty. Body text content. | | `position` | `[x, y]` | No | Omitted when `[0, 0]` (default). | | `size` | `[width, height]` | Yes | Always included - annotations have no standard default size. | | `color` | `[r, g, b]` | No | Only if different from the default gray `[0.545, 0.545, 0.545]`. Background color. | | `opacity` | number | No | Only if different from `1.0`. Background opacity (0.0 to 1.0). | | `backAlpha` | number | No | Only if different from `1.0`. Background alpha; `0.0` is a value and round-trips. | | `titleHeight` | number | No | Only if different from `30`. Title bar height. | | `bodyFontSize` | number | No | Only if different from `10`. Body text size. | ### Export Behavior Annotation COMPs (`annotateCOMP`) are serialized **exclusively** to the `annotations` array - never as `operators` entries. The exporter skips any `annotateCOMP` child of a network, even a non-utility one. This matters because TD's stock annotate is a *palette clone* with an extension and ~40 custom parameters: capturing it as a regular operator would dump well over 100 lines of `custom_pars`/`par_templates` per annotation that exactly duplicate (in a far heavier form) what the compact `annotations` entry already records. The `annotations` array is the single source of truth for annotations; the round-trip rebuilds them from it (see Import Behavior). ### Import Behavior Annotations are created during Phase 7a (after operator positions, before file link restoration). Each annotation is created as an `annotateCOMP` with `utility=True` (matching TD's native behavior - annotations are utility operators hidden from `.children`). --- ## Value Serialization All parameter and content values are converted to JSON-safe types using these rules, applied in order: | Python Type | JSON Output | Rule | |-------------|-------------|------| | `None` | string | Converted to empty string `""`. | | `bool` | boolean | Stored as-is (`true`/`false`). | | `int` | number | Stored as-is. | | `float` | number (int) | If the value is a whole number (and fits in 53-bit integer range), it is converted to an integer. E.g., `1.0` becomes `1`. | | `float` | number (float) | Rounded to 10 decimal places to eliminate floating-point noise. | | `str` | string | Stored as-is (with `=`/`~` [escaping](#escaping) applied for parameter values). | | `list` / `tuple` | array | Each element is recursively serialized. | | Any other type | string | Converted via `str()`. | **Color values** (`color` field on operators) are rounded to 4 decimal places. --- ## System Exclusions The following top-level paths and all their descendants are always excluded from export. These contain TouchDesigner system internals that should not be version-controlled: | Path | Contents | |------|----------| | `/local` | Local parameters | | `/sys` | System operators (Thread Manager, TDJSON, etc.) | | `/perform` | Performance monitoring | | `/ui` | UI framework operators | An operator is excluded if its path equals one of these or starts with one followed by `/` (e.g., `/sys/TDResources` is excluded). --- ## Import Process Importing a `.tdxn` file reconstructs the network in a pre-phase plus a series of ordered phases. This ordering ensures that dependencies are satisfied - for example, operators must exist before they can be connected, and positions are set last because creating operators may shift existing nodes. When `clear_first` is set, existing children are destroyed before import - **except** COMPs carrying the exclude tag (the `Tdxnexcludetag` parameter's value, `tdxn_exclude` by default), which are preserved. Excluded COMPs are invisible to TDXN (absent from the `.tdxn`), so destroying them would be permanent data loss; the owning app manages their lifecycle instead. | Phase | Action | Details | |-------|--------|---------| | Pre | **Resolve templates and defaults** | If `par_templates` is present, `$t` references in `custom_pars` are expanded to full definitions with value overrides. If `type_defaults` is present, shared properties are merged into each operator (`parameters` via dict merge, `flags`/`size`/`color`/`tags` via whole-value injection; operator-specific values take precedence). Stale entries matching a preserved excluded COMP, and children of nested TDXN/TOX-externalized COMPs, are dropped so their own files stay authoritative. | | 0 | **Create target custom parameters** | The target COMP's own root-level `custom_pars` that it does not have yet (all of them on a bare shell created from a `tdn_ref`, new ones on a reload) are created and their values set before any child exists, so an extension or expression inside the COMP finds them mid-build. Parameters it already has are left to Phase 9, and Phase 9 does not re-create the ones Phase 0 made. A COMP nested inline in the same file still gets its parameters in Phase 2. | | 1 | **Create operators** | All operators are created depth-first. COMPs are created first so their children can be placed inside them. | | 2 | **Create custom parameters** | Custom parameter definitions are created on COMPs (pages, types, ranges, menu entries, defaults). | | 2.5 | **Expand sequences** | Built-in/custom parameter sequences (`sequences` key) have their block counts and sequence parameters created before any values are set. *Added in v1.3.* | | 3 | **Set parameter values** | Both built-in and custom parameter values are applied. `=` prefix sets expression mode, `~` prefix sets bind mode, all other values set constant mode. A custom parameter whose `value`/`values` was omitted (it equalled its default) is seeded from `default` on every component. An absolute OP-reference value inside the document's `network_path` (a sequence block or custom parameter, from an Embody 6.2.56-or-earlier export) is remapped relative to its owner in the destination -- see [OP-Reference Values](#op-reference-values). | | 4 | **Set flags** | Operator flags are applied. Array entries without `-` prefix set the flag to `true`; entries with `-` prefix set to `false`. | | 5 | **Wire connections** | Operator and COMP connections are established. Source references are resolved (sibling name first, then full path). Array position equals input index. | | 6 | **Set DAT content** | Text or table data is loaded into DAT operators. | | 6a | **Restore storage** | Storage key-value pairs are restored via `op.store()`. `$type` wrappers are deserialized to Python types (tuple, set, bytes). | | 7 | **Set positions** | Node positions, sizes, colors, and comments are applied (later phases still follow). Missing position defaults to `[0, 0]`. | | 7b | **Set docking** | Docking relationships between operators are restored. | | 7a | **Create annotations** | Annotations are created from the `annotations` array (top-level and per-COMP). Each annotation is created as an `annotateCOMP` with `utility=True`, then its mode, title, body text, position, size, color, and opacity are set. | | 8 | **Restore file links** | File/syncfile parameters are restored on externalized DATs. | | 8.5 | **Restore TOX content** | `.tox` content is loaded into `tox_ref` shells so their internals are present immediately after import. | | 8.6 | **Restore nested TDXN content** | `tdn_ref` shells are imported from their own `.tdxn` files (recursively, with an ancestor-chain cycle guard) so their internals are present immediately after import. Skipped by startup reconstruction and the post-save restore, whose own depth-sorted loops import every tracked TDXN COMP exactly once. See [COMP References](#comp-references-tdn_ref). | | 9 | **Apply target COMP properties** | The target COMP's own type, custom and built-in parameters, flags, color, tags, and comment are applied - last, so extension reinit triggered by recreating source DATs cannot overwrite them. | | 10 | **Warn about locked non-DATs** | Locked TOP/CHOP/SOP/POP operators this import created are logged with their source, after every wire (the target COMP's own external wires included) is restored. The lock is preserved but the frozen data is not (see [Lock Flag Limitation](#lock-flag-limitation)). Startup reconstruction and the post-save restore log only the count, since nested shells are not filled yet. | The importer accepts either a full `.tdxn` document (with metadata) or just the `operators` array directly. ### Extension Initialization Timing !!! danger "Extensions initialize BEFORE TDXN import" When a TDXN COMP is reconstructed (on project open or after save), the COMP shell is created first and any extensions on it initialize immediately. The TDXN import runs **after** extension initialization, calling `ImportNetwork` with `clear_first=True` - which deletes all children and recreates them from the `.tdxn` file. This means any state set up by `onInitTD` inside the COMP is **overwritten**. **Timeline on project open:** | Step | Frame | What happens | |------|-------|--------------| | 1 | Early | COMP shell created (exists but empty) | | 2 | Early | Extension `__init__` runs | | 3 | End of frame | `onInitTD` fires - network may not exist yet | | 4 | Frame 60 | `ext.Embody.reconstructTDXNComps` runs `ImportNetwork(clear_first=True)` | | 5 | Frame 60+ | All children deleted and recreated from `.tdxn` | **Timeline on save (strip/restore cycle):** | Step | What happens | |------|--------------| | 1 | Pre-save: every TDXN COMP is exported (a childless one too, unless the empty-overwrite guard refuses), then children are stripped from the COMPs that have them. A COMP is not stripped that save when a TDXN COMP inside it did not export | | 2 | `.toe` saved without TDXN children | | 3 | Post-save: `ImportNetwork` re-imports children from `.tdxn`, shallowest first; a nested TDXN COMP the strip destroyed is re-imported from its own file. A failed import rolls back to the newest backup only while the COMP is still empty | | 4 | Extensions may reinitialize during restore | **Impact:** If an extension's `onInitTD` creates operators, sets parameter values, writes to storage, or builds any state inside the COMP, that work is destroyed by the import. This affects extensions that live inside TDXN COMPs **and** extensions whose ownerComp is a TDXN-strategy COMP. **Solution:** Defer initialization using `run()` with `delayFrames`: ```python def onInitTD(self): run('args[0].postInit()', self, delayFrames=5) def postInit(self): """Runs after TDXN import completes. Safe to set up state.""" pass ``` The deferred method must be **idempotent** - it will run on every project open, after every save, and on manual reimport. Use a delay of at least 5 frames to ensure all import phases have completed. For full guidance on writing extensions that coexist with TDXN, see the [Extensions](../td-development/extensions.md#initialization-and-tdxn-import-timing) documentation. ### Version Compatibility When importing a full `.tdxn` document, the importer checks the metadata fields for compatibility: - **`version`**: Compared against the current TDXN format version. Because older files remain back-compatible, a warning is logged **only when the file's version is newer** than the running build (the genuinely risky direction, where the file may use schema this build does not understand). Equal or older versions import silently. - **`td_build`**: Compared against the running TouchDesigner version. An informational message is logged if they differ, since operator types and parameter defaults may vary between TD builds. - **`build`**: Logged for informational purposes, identifying which save iteration is being imported. These checks are non-blocking - the import always proceeds regardless of mismatches. --- ## Virtual File System (VFS) - Not Supported **TDXN does not capture a COMP's Virtual File System, and this is not planned.** Files embedded in a COMP's VFS - fonts, images, shaders, lookup tables, anything addressed as `vfs://...` - are **not exported and are lost** when the COMP is reconstructed from its `.tdxn`. Verified 2026-09-04: a COMP holding one embedded file exports with no trace of the file or its payload, and the rebuilt COMP's VFS is empty. Any parameter or script referencing `vfs://` fails to resolve after reconstruction. **Why it is excluded.** TDXN's entire purpose is a line-diffable, mergeable text representation of a network. A VFS holds arbitrary binary payloads; carrying them inline (base64 or otherwise) would destroy line-level diffability and inflate files without bound - a single embedded font would dwarf the network it belongs to, and every re-export would churn the blob. **What to do instead**, for a COMP that genuinely needs embedded files: - **Externalize it with the TOX strategy rather than TDXN.** A `.tox` is TouchDesigner's own container format and *does* preserve VFS contents (verified 2026-09-04: embedded file and payload survive a `.tox` save and re-instantiate intact). The trade is the usual one - a `.tox` is binary and does not diff. - **Or keep the assets as real files on disk** beside the project and reference them by path. Path-valued parameters round-trip through TDXN normally, so the network stays diffable and the assets stay in version control as themselves. There is no warning-free middle ground: if a COMP carries VFS files and is externalized as TDXN, those files do not come back. --- ## Round-Trip Guarantees For most networks, export -> import -> re-export produces identical `.tdxn` output. The format is designed to be stable across round-trips, with a few documented exceptions. ### Preserved - **Target COMP metadata** (v1.1+): type, flags, color, tags, comment, storage - Operator names, types, and hierarchy - Non-default parameter values (constant, expression, and bind modes) - Constant OP-reference strings as authored, including unresolved names and patterns (see [OP-Reference Values](#op-reference-values)) - Custom parameter definitions (all fields, all styles) - Flags, connections, positions, sizes, colors, comments, tags - Operator storage (serializable entries only - see [Operator Storage](#operator-storage)) - Annotations (mode, title, body text, position, size, color, opacity) - DAT text and table content (byte-for-byte when `include_dat_content` is `true`) - Float values (stable after the first export - see below) - Type defaults and parameter templates (re-computed on each export) ### Known Exceptions **Palette clones** - On first export, a palette-cloned COMP is marked `"palette_clone": true` and its children are skipped. After import, TouchDesigner materializes the children from the clone source. A subsequent re-export will include those children as regular operators. This means the second export is larger than the first. Parameters that match `p.default` but differ from the clone source are preserved (see [Palette Clones](#palette-clones)). **Color tolerance** - Colors within `0.01` per channel of the default gray `[0.545, 0.545, 0.545]` are treated as default and not exported. A color of `[0.55, 0.55, 0.55]` survives; `[0.546, 0.546, 0.546]` is dropped. **Float precision** - Values are rounded to 10 decimal places on first export. This can change the last digits of very precise values (e.g., `3.14159265358979` -> `3.1415926536`). After that first rounding, subsequent exports are stable. **Type defaults recomputation** - Type defaults and parameter templates are recomputed from scratch on each export. If operator populations change between exports (operators added/removed), different properties may qualify as "unanimous" for type_defaults, and different pages may qualify as templates. The final network state is always identical, but the YAML structure may differ. **Locked non-DAT data** - When a TOP, CHOP, SOP, or POP is locked, TDXN preserves the lock flag but not the frozen pixel, channel, geometry, or point data. After import, the operator is locked but empty. See [Lock Flag Limitation](#lock-flag-limitation). **Virtual File System** - A COMP's embedded VFS files are never exported and do not survive reconstruction. This is deliberate and permanent; see [Virtual File System (VFS) - Not Supported](#virtual-file-system-vfs-not-supported). ### Intentionally Excluded The following are never exported and are not considered a loss: - **Export-mode parameters** - set by the exporting operator, not the parameter itself - **Pulse / Momentary / Header styles** - no persistent state - **Read-only parameters** - cannot be set on import - **COMP externalization parameters** (`externaltox`, `enableexternaltox`, `reloadtox`) - COMP `.tox` externalization is managed separately by Embody - **Transient storage keys** - runtime state used by Embody (`envoy_running`, `_git_root`, etc.) - **Non-serializable storage values** - threading objects, operator references, custom class instances --- ## Error Handling TDXN import is **best-effort** - individual failures should not abort the entire operation. This section describes the expected behavior for developers working with TDXN files. ### Unknown Fields Developers should ignore unknown fields when parsing TDXN documents. This ensures forward compatibility - a file exported by a newer version of Embody can still be imported by an older version, with unrecognized fields silently skipped. ### Failure Modes | Situation | Expected behavior | |-----------|-------------------| | Unknown field in any object | Ignore it. | | Missing required field (`name`, `type`) on an operator | Skip that operator silently (no log emitted). | | Missing connection source (operator not found) | Skip that connection, log a warning. | | Unrecognized custom parameter `style` | Skip that parameter definition, log a warning. | | Unrecognized flag name | Ignore it. | | Invalid parameter value type | Attempt type coercion; if impossible, skip with a warning. | | Version mismatch (`version`, `td_build`) | Proceed with import. For `version`, log a warning only when the file is newer than the running build; older or equal versions are silent. For `td_build`, log an informational message. | | Target COMP type mismatch (`type` vs destination) | Log a warning, proceed with import. The file's `type` field is informational - import does not change the destination COMP's type. | | Unknown `$t` template reference | Log a warning, skip that page. | | Missing `type_defaults` entry for a type | No-op (operator uses its own properties). | | Non-serializable storage value on export | Skip that value, log at DEBUG level. | | Unknown `$type` in storage on import | Treat as plain dict, log a warning. | | Failed `store()` call on import | Skip that key, log a warning. | ### General Principle Log warnings for skipped items where practical (a few malformed cases, like an op-def missing `name`/`type`, are skipped silently) so the developer can inspect the result. Never abort an entire import because a single operator, parameter, or connection failed - the partial result is more useful than no result. --- ## Complete Example A realistic `.tdxn` file demonstrating all major features: ```yaml format: tdxn version: '2.2' build: 3 generator: Embody/6.0.4 td_build: '2025.32050' network_path: / type: baseCOMP options: include_dat_content: true include_storage: true type_defaults: baseCOMP: parameters: resizecomp: =me repocomp: =me par_templates: about: - {name: Build, style: Int, label: Build Number, readOnly: true} - {name: Version, style: Str, label: Version, readOnly: true} operators: - name: controller type: baseCOMP color: [0.2, 0.4, 0.8] comment: Main controller tags: [core] custom_pars: Controls: - name: Speed style: Float default: 1 max: 10 clampMin: true normMax: 5 value: 2.5 - name: Mode style: Menu menuNames: [linear, ease, bounce] menuLabels: [Linear, Ease In/Out, Bounce] value: 1 - name: Color style: RGB clampMin: true clampMax: true values: [1, 0.5, 0] About: $t: about Build: 3 Version: 1.0.0 flags: [viewer] comp_inputs: [renderer] children: - name: noise1 type: noiseTOP parameters: type: sparse amp: 0.8 period: 2 monochrome: true resolutionw: 1920 resolutionh: 1080 - name: level1 type: levelTOP position: [300, 0] parameters: opacity: =parent().par.Speed / 10 inputs: [noise1] flags: [display] - name: config type: tableDAT position: [0, -200] dat_content: - [key, value] - [resolution, 1920x1080] - [fps, '60'] dat_content_format: table flags: [lock] - name: script1 type: textDAT position: [300, -200] dat_content: | # Initialize print('Controller ready') dat_content_format: text - name: renderer type: baseCOMP position: [500, 0] size: [300, 150] custom_pars: About: $t: about Build: 1 Version: 0.9.0 ``` Key observations: - **`type_defaults`**: Both `baseCOMP`s share `resizecomp` and `repocomp` expressions, so those are hoisted out of individual operators - **`par_templates`**: The "About" page definition is shared between `controller` and `renderer`, with different values - **Expression shorthand**: `=parent().par.Speed / 10` instead of a nested `{expr: ...}` mapping - **Flags as arrays**: `[viewer]`, `[display]`, `[lock]` - **Simplified connections**: `[noise1]` instead of a list of `{index: 0, source: noise1}` mappings - **Optional position**: `noise1` at `[0, 0]` omits `position`; `controller` at `[0, 0]` also omits it - **Compact formatting**: Short numeric/string vectors like `[300, 0]`, `[0.2, 0.4, 0.8]`, `[core]` use inline YAML flow style --- ## Changelog | Version | Date | Changes | |---------|------|---------| | 1.0 | 2026-02-19 | Initial release with 8 format optimizations: expression shorthand (`=`/`~` prefixes), flags as arrays, page-grouped custom parameters, type defaults, parameter templates, optional position, simplified connections, compact formatting. | | 1.0 | 2026-02-22 | Extended `type_defaults` to support `flags`, `size`, `color`, and `tags` in addition to `parameters`. Backward-compatible: old importers ignore unknown keys, new importers handle files without the new keys. | | 1.0 | 2026-03-01 | Added annotation support (`annotations` array at top level and per-COMP). Added Phase 7a to import process. Removed `file`/`syncfile` from SKIP_PARAMS so DAT file references are preserved in TDXN exports. Pre-save now auto-exports current state before stripping TDXN COMPs. | | 1.3 | 2026-04-07 | Added built-in parameter sequence support (`sequences` key on operator objects). Operators with resizable parameter blocks (mathmixPOP, glslPOP, attributePOP, constantCHOP, etc.) now round-trip correctly. Added Phase 2.5 to import process. Sequence parameters excluded from `type_defaults` compression and `_buildParCache`. | | 1.4 | 2026-05-XX | Added `tox_ref` for COMPs with their own TOX externalization (relative path to the child's `.tox`, mutually exclusive with `children`). | | 1.5 | 2026-06-10 | A text DAT's `dat_content` may now be an **array of line-strings** (multi-line) as well as a plain string (single-line), rejoined with `\n` on import. Keeps `.tdxn` files readable and git-diffable line-by-line. Import is fully back-compatible with the v1.x string form. The version-mismatch warning now fires only when the file is newer than the running build. | | 2.0 | 2026-06-10 | The on-disk format is now **YAML** (a strict JSON superset). Multi-line `dat_content` reverts to a **plain string** rendered as a YAML literal block scalar (`|`), preserving exact trailing newlines via `\|`/`\|-`/`\|+` chomping. Importers parse json-first (BOM/whitespace-stripped), so legacy tab-indented JSON `.tdn` (v1.x/v1.5) still load losslessly with no migration gate. Auto-created default docked compute DATs are no longer serialized (TD recreates them on import). Files are roughly 17% smaller and read top-to-bottom without escaped newlines. MIME type is now `application/yaml`. | | 2.1 | 2026-09-04 | Several custom-parameter definition fields (`default`, `min`, `max`, `readOnly`, `enable`, ...) may be a per-component array when a tuplet's components disagree. No structural change. | | 2.2 | 2026-10-08 | `tdn_ref` and `tox_ref` entries no longer carry the child's `custom_pars` or their sequences: the child's own file owns them. No structural change. | ============================================================================== # TDXN - Import & Export # source: docs/tdxn/import-export.md ============================================================================== # Read, Import & Export ## Reading a Network (no disk I/O) ### MCP Tool Use the `read_tdxn` tool to return the live network as a TDXN dict **without writing anything to disk**. This is the preferred read path for LLM workflows exploring networks of more than ~3 operators - **typically 20-90x fewer tokens** than walking the same subtree with `get_op` + `query_network` because of default-omission, `type_defaults`, and `par_templates` compaction. | Parameter | Default | Description | |-----------|---------|-------------| | `comp_path` | `"/"` | Starting COMP path | | `include_dat_content` | Toggle setting | Also include file-backed DAT text/table content (content saved nowhere else is always included) | | `max_depth` | `null` (unlimited) | Cap recursion on large roots | | `embed_all` | `false` | Recurse into TDXN-tagged COMPs instead of skipping their children | Works in all three `Tdxnmode` values (Off / Export-on-Save / Roundtrip) - `read_tdxn` reads live state, not `.tdxn` files on disk. ### When NOT to use `read_tdxn` For these, reach for the runtime-state MCP tools instead: | Need | Use | |---|---| | Evaluated-expression runtime values | `get_parameter` | | Cook errors / warnings | `get_op_errors` | | DAT / CHOP / TOP output data | `get_dat_content`, `capture_top` | | Cook timing | `get_op_performance` | | Flag state after runtime mutation | `get_op_flags` | --- ## Exporting a Network ### Keyboard Shortcuts - ++ctrl+shift+e++ - Export the entire project to a single `.tdxn` file - ++ctrl+alt+e++ - Export just the current COMP to a `.tdxn` file ### MCP Tool Use the `export_network` tool with these options: | Parameter | Default | Description | |-----------|---------|-------------| | `root_path` | `"/"` | Starting COMP path | | `include_dat_content` | Toggle setting | Also include file-backed DAT text/table content (content saved nowhere else is always included) | | `output_file` | `null` | File path (use `"auto"` for automatic naming, `null` for dict-only). A path other than the COMP's tracked file writes a **snapshot**: the tracked file and its table row are left untouched. A relative path is anchored at the project folder. | | `max_depth` | `null` (unlimited) | Maximum recursion depth | | `embed_all` | `false` | Recurse into TDXN-tagged COMPs instead of writing `tdn_ref` pointers, producing a self-contained export | ### What Gets Exported - All operators under the root path (recursively) - Only non-default parameter values - Connections between operators - Custom parameter definitions - Built-in parameter sequences with non-default block counts or values (`sequences`) - Flags, positions, sizes, colors, comments, tags - Serializable operator storage entries (unless disabled per-COMP or globally) - Annotations - Optionally: DAT text/table content ### What Gets Excluded - System paths (`/local`, `/sys`, `/perform`, `/ui`) - Pulse, Momentary, and Header parameters (no persistent state) - Read-only parameters - COMP externalization parameters (`externaltox`, `enableexternaltox`, etc.) - Children of palette clones (TD recreates them from the clone source) --- ## Importing a Network Use the `import_network` MCP tool: | Parameter | Description | |-----------|-------------| | `target_path` | Destination COMP path | | `tdn` | The TDXN document, parsed object (full document or operators array) | | `clear_first` | Delete existing children before importing | ### Import Phases The import process runs in a pre-phase plus the ordered phases below. This ordering ensures dependencies are satisfied: | Phase | Action | Details | |-------|--------|---------| | Pre | **Resolve templates and defaults** | Expand `$t` references and merge `type_defaults` into operators. With `clear_first`, excluded COMPs (the `tdxn_exclude` tag) are preserved, not destroyed. | | 0 | **Create target custom parameters** | The target COMP's own custom parameters it does not have yet (all of them on a bare `tdn_ref` shell, new ones on a reload), created before any child so an extension or expression inside finds them. | | 1 | **Create operators** | Depth-first creation. COMPs first so children can be placed inside. | | 2 | **Create custom parameters** | Pages, types, ranges, menu entries, defaults. | | 2.5 | **Expand sequences** | Resizable parameter blocks (sequences on ops like `mathmixPOP`, `glslPOP`, `constantCHOP`) have their sequence parameters created before any values are set. | | 3 | **Set parameter values** | Both built-in and custom. `=` prefix -> expression, `~` prefix -> bind. Absolute OP references inside the document's `network_path` (sequence blocks and custom parameters written by Embody 6.2.56 or earlier) are remapped onto the destination -- see the specification's [OP-Reference Values](specification.md#op-reference-values). | | 4 | **Set flags** | Array entries without `-` -> `true`; with `-` -> `false`. | | 5 | **Wire connections** | Resolve sources (sibling name first, then full path). | | 6 | **Set DAT content** | Text or table data loaded into DATs. | | 6a | **Restore storage** | Storage key-value pairs restored via `op.store()`; `$type` wrappers deserialized. | | 7 | **Set positions** | Positions, sizes, colors, comments applied (later phases still follow). | | 7b | **Set docking** | Docking relationships restored between operators. | | 7a | **Create annotations** | Annotations created with `utility=True`. | | 8 | **Restore file links** | File/syncfile parameters restored on externalized DATs. | | 8.5 | **Restore TOX content** | `.tox` content loaded into `tox_ref` shells. | | 8.6 | **Restore nested TDXN content** | `tdn_ref` shells filled from their own `.tdxn` files in the same import (recursive, with an ancestor-chain cycle guard). Skipped by startup reconstruction and the post-save restore, whose own depth-sorted loops import every tracked TDXN COMP exactly once. | | 9 | **Apply target COMP properties** | The target COMP's own type, custom and built-in parameters, flags, color, tags applied last. | | 10 | **Warn about locked non-DATs** | Locked TOP/CHOP/SOP/POP operators this import created are logged with their source (lock preserved, frozen data is not), after every wire is restored. See [Lock Flag Limitation](specification.md#lock-flag-limitation). | ### Version Compatibility The importer checks metadata for compatibility: - **`version`**: Warning **only when the file's version is newer** than the running build (the risky direction - the file may use schema this build does not understand). Equal or older versions import silently. - **`td_build`**: Info message if TD version differs (parameter defaults may vary) - **`build`**: Logged for informational purposes These checks are non-blocking - import always proceeds. --- ## Diffing a Network `diff_tdxn` answers the question git cannot: **what have I changed but not saved?** It compares the **live in-memory network** against its on-disk `.tdxn` - the unsaved window, which git never sees (git only reads files on disk, not TouchDesigner's live state). | Parameter | Default | Description | |-----------|---------|-------------| | `target` | (optional) | A COMP path, or a `.tdxn` file path / bare filename (e.g. `"mixer.tdxn"`). **Omit it for a whole-project summary** across every live TDXN COMP. | | `max_changed_ops` | `200` | Cap on the total changed entries returned (added + removed + modified combined, modified filled first). The reported `counts` always reflect the true totals; entries beyond the cap are dropped from the payload and counted in `dropped`. | | `max_bytes` | `60000` | Cap on the output size. | The comparison is **semantic, not byte-level**: both sides normalize through the same `type_defaults` / `par_templates` expansion, and the volatile export header (`build`, `generator`, `td_build`, `exported_at`, `source_file`) is ignored - so a no-op re-export shows nothing. Each change is `{old, new}` (old = disk, new = live), tagged `root`, `op`, or `annotation`. ### Git diffs of `.tdxn` files `diff_tdxn` covers the *unsaved* window; `git diff` covers what you have committed. Embody keeps those diffs quiet at the source instead of filtering them: the header of any export of a tracked COMP (one with a build number) carries only fields that change for a reason -- `format` and `version` (the file format), `generator` (the Embody version), `td_build` (the TouchDesigner build) and `build` (the COMP's save count). The export time lives in the `externalizations.tsv` `timestamp` column and git history; the source `.toe` name is no longer recorded. Exports of COMPs without a build number (untracked or portable networks) still write `exported_at` and `source_file`. Files written before this change keep both fields until their next real change. Earlier versions of Embody installed a git textconv driver (`.embody/tdxn_textconv.py`, `git config diff.tdxn.textconv`) that hid the header from diffs. VS Code reads old versions through that driver, so it hid the header there too and could stage files without one. Embody retires it the next time the project opens, Envoy on or off: it unsets the key only when it points at Embody's own script, then deletes the script; a driver you pointed at your own tool is left alone. The `diff=tdxn` lines in `.gitattributes` stay -- with no driver configured, git shows a plain diff. For a header-free view on the command line, use `git diff -I'^(build|generator|td_build):'`. --- ## Crash safety and `.embody_backup` Every `.tdxn` write is **atomic** - the content goes to a temp file in the same directory, is flushed and `fsync`ed, then `os.replace()`s the target. A crash or power loss mid-write leaves either the complete old file or the complete new one, never a half-written one. Before each write, Embody also rotates two generations of the previous content into a `.embody_backup/` folder beside your `.toe`, mirroring the network file's relative path: ``` my-project/ +-- embody/ | \-- Foo/ | \-- bar.tdxn <- current \-- .embody_backup/ \-- embody/ \-- Foo/ +-- bar.tdxn.bak <- previous write \-- bar.tdxn.bak2 <- the one before that ``` A rewrite that changes only the header's `format` or `version` (a format bump re-saving an unchanged network) skips the rotation, so it never pushes an older network out of `.bak2`. After each write the file is read back and re-parsed; if that validation fails, the newest surviving backup is restored automatically and the log names the exact file it came from (a header-only rewrite puts the previous file back instead). `ext.Embody.reconstructTDXNComps` and the post-save export roll back the same way if reconstruction fails. Recovery tries `.bak` first, then `.bak2`. The folder holds backups of **both** `.tdxn` and `.tdn` files - a COMP externalized before v6.1.0 keeps writing `.tdn` forever - which is why the name carries no format token. !!! note "Renamed in v6.1.6" This folder was called `.tdn_backup/` before v6.1.6. Nothing moves or deletes an existing one: new backups are written to `.embody_backup/`, and recovery still reads `.tdn_backup/` when the newer folder has nothing for that file. Both stay git-ignored. Each COMP's legacy copies are retired automatically the first time Embody rotates a new backup for that COMP - which happens on the first save where its network actually **changed** (an unchanged COMP is skipped entirely and keeps its old copies, deliberately). Leave the old folder alone and it drains itself; there is no need to delete it by hand. **Backups are machine-local scratch and should not be committed.** They are superseded on every write and carry no history git does not already have - the `.tdxn` files themselves are the versioned record. Envoy adds both folder names to your project's auto-managed [`.gitignore`](../embody/getting-started.md#auto-managed-gitignore) on startup. If your repo predates those entries and already tracks a backup folder, untrack it once: ```bash # run for whichever folder your repo actually tracks -- git errors on a path it does not git rm -r --cached .embody_backup git rm -r --cached .tdn_backup ``` Deleting either folder at any time is safe - the current one is recreated on the next export. --- ## Error Handling TDXN import is **best-effort** - individual failures don't abort the entire operation. | Situation | Behavior | |-----------|----------| | Unknown field | Ignored (forward compatibility) | | Missing `name` or `type` | Skip operator silently (no log) | | Missing connection source | Skip connection, log warning | | Unrecognized parameter style | Skip parameter, log warning | | Unrecognized flag | Ignored | | Invalid parameter value | Attempt type coercion; skip with warning if impossible | | Version newer than build | Log warning, proceed (older/equal versions import silently) | | Unknown `$t` template reference | Log warning, skip page | !!! info "Design principle" Log warnings for anything skipped so the developer can inspect the result. Never abort an entire import because a single operator, parameter, or connection failed - the partial result is more useful than no result. ============================================================================== # AI Instructions (AGENTS.md) # source: AGENTS.md ============================================================================== # Embody + Envoy - AI Instructions This project uses **[Embody](https://github.com/dylanroscover/Embody)** (TouchDesigner externalization) and **Envoy** (MCP server for AI coding tools). - Embody externalizes TouchDesigner operators to version-controlled files (`.py`, `.tox`, `.tdxn`, `.json`, etc.) - Envoy provides MCP tools for AI assistants to inspect and modify the live TD network - Use the `Configure For` toggles on the Embody COMP's Envoy page to regenerate these files for your AI tool (more than one client can be on at once) > **Note:** For Claude Code users, a `CLAUDE.md` with modular `.claude/rules/` and `.claude/skills/` is also generated. This `AGENTS.md` is the universal fallback read by Codex, Cursor, GitHub Copilot, Windsurf, Gemini, and others. > > **Skills:** the same workflow skills ship as `SKILL.md` folders -- `.claude/skills/` (Claude Code, OpenCode) and `.agents/skills/` (Codex, Cursor, Gemini CLI, Antigravity). Read the matching skill BEFORE the action it governs: `create-operator` before creating or moving operators, `td-api-reference` before writing TD Python, `mcp-tools-reference` before the first MCP call, `manage-annotations`, `create-extension`, `externalize-operator`, `parameter-design`, `visual-aesthetics`, `pop-networks`, `movie-export`, `debug-operator`, `td-recovery`, `multi-session-etiquette`, `merge-divergent-tox`, `glsl-shaders`, `operator-gotchas`, `testing`, `brief` (user-invoked), `collab` (user-invoked). A client with no skills folder gets the identical text over MCP: `get_guidance()` lists topics, `get_guidance(topic='create-operator')` returns one. --- ## No Envoy MCP tools? (fresh clone or handed-over project) MCP config is deliberately not committed: every client's config file hard-codes absolute paths to one machine's Python venv and Envoy bridge. A clone arrives with this file and the rules/skills folders but no MCP config. Which file is missing depends on the client -- `.mcp.json` (Claude Code, and the baseline Embody always writes), `.cursor/mcp.json`, `.vscode/mcp.json` (VS Code, Copilot), `.gemini/settings.json`, `.codex/config.toml`, `.agents/mcp_config.json` (Antigravity), `opencode.json`. **A missing MCP config never means "this project has no path into TD."** It means Envoy has not run on this machine yet. Tell the user: 1. Open the project's `.toe` in TouchDesigner. 2. Envoy should start by itself -- the sender's committed `.embody/project.json` declares it, and a machine with no local settings adopts that. If the toolbar shows no port, turn on **Enable Envoy** on the Embody COMP by hand (the project may predate the declaration). 3. Restart the AI client once the Embody toolbar shows a port. If nothing is written: **Embody Mode** on `Advanced - ask first` defers config writes during project open (a log breadcrumb says so), and **Configure For** on None writes no MCP config at all. `op.Embody.InitEnvoy()` applies the deferred writes -- an extension method, not a button. **Windsurf is the exception.** Cascade reads only `~/.codeium/windsurf/mcp_config.json`, which is shared by every project the user opens, so Embody never writes it -- pointing one global file at this project's bridge would hijack all their other projects. That config is always a one-time manual paste. --- ## Critical Rules 1. **Prefer the externalized network file for reading TDXN-externalized COMPs** - these are YAML on disk with complete network structure (operators, parameters, connections, positions, flags, DAT content, annotations). Reading them directly is faster than MCP round-trips. **Never glob for an extension:** Embody writes `.tdxn`, and keeps writing `.tdn` for any COMP externalized before Embody 6.1 - both are read and round-tripped forever, so a project can hold a mix. Let `externalizations.tsv` or `get_externalizations` name the exact file instead. **The strategy column value is `tdxn`** - it read `tdn` before 6.2.30, and both are accepted on read. To edit: modify the file on disk, then call `import_network` via MCP with the COMP path, the parsed network, and `clear_first=True` to reload it in TD. Use MCP when you need live runtime state (evaluated expressions, cook errors) or for non-TDXN operators. 2. **Use Envoy MCP tools for live TD state and non-TDXN operators** - never say "I can't access that binary file." For operators not externalized as TDXN, use MCP tools to inspect and modify them. 3. **Do NOT assume network paths** - use `query_network` on `/` to discover the actual root structure. 4. **Default new COMPs to Embody's container** - `execute_python` with `result = op.Embody.parent().path` returns the same home every run. Build in `ui.panes.current.owner.path` only when you have deliberately navigated into a content network, and never treat the bare root `/` as that home. 5. **Never edit `externalizations.tsv` directly** - managed exclusively by Embody's tracking system. 6. **Always use forward slashes** in file paths. 7. **Check for errors and warnings after each group of operator creations** -- `get_op_errors` with `recurse=true` once the group is wired/positioned. 8. **Batch repetitive MCP operations** -- never make 3+ individual calls to the same tool. Use `batch_operations` for repeated positioning, connecting, parameter, or flag edits; use `execute_python` for computed or looped logic. 9. **Thread boundary**: MCP server worker thread must never import TD modules. All TD access goes through `_execute_in_td()`. --- ## TD Python Rules - **Always use `.eval()`** to get a parameter's current runtime value. `.val` only returns the constant-mode value. - **Setting `.val` silently switches mode to CONSTANT** - destroys any active expression. - **Toggle parameters** use `0`/`1` (not `"True"`/`"False"`). - **Use `opex()`** when the operator must exist - raises immediately with a clear error. `op()` returns `None` silently. - **Never call `op()`, `parent()`, or access TD objects at module level** - defer to methods. - **NEVER access TD objects from a worker thread** - all TD operations must go through main-thread hooks. - **`fetch()` searches UP the parent hierarchy** by default - pass `search=False` for local-only lookup. - **`tdu.Dependency`**: Assign to `.val` (`dep.val = 5`), NOT the object itself. Call `.modified()` after mutating contents. ## Network Layout Rules - **200-unit grid**: All positions snap to multiples of 200. Never place at arbitrary coordinates. - **200 units horizontal** between connected operators in a chain. - **Left to right** signal flow: inputs on the left, outputs on the right. - **NEVER place an operator on top of another** -- scan with `query_network` before placing, then verify the whole created/moved group with `get_network_layout`. - **Visual TOP work is output-first**: create an Out TOP `out1` and turn its display flag on BEFORE building the chain, then keep the working chain wired into it -- the user watches live in the network backdrop. - **Every logical group gets an annotation** - use `create_annotation` around each cluster of related operators. - **Annotations must enclose their operators**: `nodeX`/`nodeY` is the bottom-left corner - `nodeY` must be below (less than) the lowest operator's Y. - **TD Y-axis increases upward** - new rows go downward (decreasing Y). ## MCP Server Safety Rules - Envoy must bind to `127.0.0.1`, NEVER `0.0.0.0`. - `_execute_in_td()` times out at 30 seconds. - The MCP server runs as a `standalone=True` TDTask (long-lived, outside the worker pool). - Uses `threading.Event` + `Queue` rather than locks because TD's cook cycle is frame-based. --- ## Project Structure ``` Embody/ +-- AGENTS.md # This file - universal AI instructions +-- CLAUDE.md # Claude Code specific instructions (if using Claude) +-- dev/ | +-- embody/ | | +-- externalizations.tsv # Tracking table (NEVER edit directly) | | \-- Embody/ # Main extension source | | +-- EmbodyExt.py # Core externalization engine | | +-- EnvoyExt.py # MCP server extension | | \-- TDXNExt.py # TDXN network format export/import \-- release/ \-- Embody-v*.tox # Latest release build ``` ## Extension Referencing Three tiers. TD promotes every capitalized member, so the capital letter is the access modifier: ```python # Tier 1, public API (UpperCamelCase) - called on the COMP: op.Embody.Update() op.Embody.Refresh() op.Embody.Save('/path/to/op') # opPath is REQUIRED op.Embody.ExportPortableTox(target=some_comp, save_path='/out.tox') # Tier 2, wiring (lowerCamelCase) - through ext, from the COMP's own callback DATs: op.Embody.ext.Embody.getExternalizedOps(COMP) # Tier 3, private (_lowerCamelCase) - inside the class only. ``` `.ext.` resolves by the **Extension Name parameter**, not the class name: the extensions are named `Embody`/`Envoy`/`TDXN`/`CatalogManager` against classes `EmbodyExt`/`EnvoyExt`/`TDXNExt`/`CatalogManagerExt`, so `op.Embody.ext.Embody.x()` works and `op.Embody.ext.EmbodyExt.x()` raises. **NEVER cache extension references in variables** - always call inline. ## Third-Party Python Packages The project shares Embody's uv-managed venv (`.venv/` beside the .toe); its site-packages is importable from any DAT or extension - wired pre-cook via TD's `TDPyEnvManagerContext.yaml` (Embody authors it) so even module-level extension imports work on a cold open, with Embody's init as the fallback. To add a package, ASK THE USER FIRST (installs execute code and persist across sessions), then call `op.Embody.InstallPackages(['pkg>=1.0'])` via `execute_python` - it accepts plain name-based requirements only (never URLs, git refs, or file paths), validates against Embody's core pins and TD's bundled packages, records the request in the committed `.embody/project.json`, and installs wheels-only in the background (watch the Embody log for completion). Packages declared by OTHER machines via git do not auto-install: they surface as a warning and need the user's explicit `op.Embody.ApplyDeclaredExtras()`. Never INSTALL into `.venv` by calling pip/uv yourself - installs go through InstallPackages only (removal is the one sanctioned direct call: `uv pip uninstall --python `, and only when the user asks). Never install packages TD bundles (numpy, opencv - crash class), and treat a logged "restart TouchDesigner" notice as authoritative. External scripts run under `op.Embody.VenvPython`.