The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix: remove managed runtimes and ML compression
Steven Enamakel3a12cb8b873a
diff --git a/.gitmodules b/.gitmodulesindex b7a1f19c60..1a4b6bf600 100644--- a/.gitmodules+++ b/.gitmodules@@ -32,9 +32,6 @@path = vendor/tinyboxurl = https://github.com/tinyhumansai/tinyboxbranch = main-[submodule "vendor/tinyruntime"]- path = vendor/tinyruntime- url = https://github.com/tinyhumansai/tinyruntime.git[submodule "vendor/tinydocs"]path = vendor/tinydocsurl = https://github.com/tinyhumansai/tinydocsdiff --git a/AGENTS.md b/AGENTS.mdindex 601877e41b..297236183a 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -556,7 +556,6 @@ Direct rendered submodules under `vendor/`:| `tinyjuice` | Agent tool-output compression and recovery of omitted content. || `tinymcp` | The TinyMCP module implementation and its bus contract. Put MCP module behavior and contract changes here; OpenHuman owns configuration, lifecycle, and host integration. || `tinymemory` | Engine-neutral memory contracts, operations, and providers. Its nested TinyCortex submodule owns the TinyCortex memory engine. |-| `tinyruntime` | Runtime discovery/installation and bounded pools of warm language interpreter processes, exposed as a TinyBus module. || `tinysearch` | Web-search module, provider dispatch, tool declarations, and execution behind its TinyBus contract. || `tinyskills` | Host-independent skill/workflow bundle parsing, discovery, scope resolution, resource inventory, and safe reads. OpenHuman owns trust and execution policy. || `tinyvoice` | Host-agnostic voice primitives such as audio framing, VAD, wake-word gating, routing, and STT hallucination detection. |@@ -590,7 +589,6 @@ method constants, request and response types, and its contract version.| `tinydocs-bus` | `documents` || `tinyvoice-bus` | `voice` || `tinyjuice-bus` | inference kernel |-| `tinyruntime-bus` | runtime clients || `tinywallet-bus` | `web3` (contract; the chain primitives are in `tinywallet-crypto`) || `tinymcp-bus` | `mcp` || `tinychannels-bus` | channel vocabulary |diff --git a/Cargo.lock b/Cargo.lockindex 3587825d7a..5f430f0547 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4724,8 +4724,6 @@ dependencies = ["tinymemory-api","tinymemory-integrations","tinymemory-tools",- "tinyruntime-bus",- "tinyruntime-pyserver","tinysearch-bus","tinyskills","tinystoragedrivers",@@ -8046,25 +8044,6 @@ dependencies = ["tinymemory-api",]-[[package]]-name = "tinyruntime-bus"-version = "0.2.12"-dependencies = [- "serde",- "serde_json",-]--[[package]]-name = "tinyruntime-pyserver"-version = "0.2.12"-dependencies = [- "serde",- "serde_json",- "thiserror 2.0.20",- "tokio",- "tracing",-]-[[package]]name = "tinysearch-bus"version = "0.4.1"diff --git a/app/src/components/settings/panels/TokenUsagePanel.tsx b/app/src/components/settings/panels/TokenUsagePanel.tsxindex ace86f7a07..84468e9786 100644--- a/app/src/components/settings/panels/TokenUsagePanel.tsx+++ b/app/src/components/settings/panels/TokenUsagePanel.tsx@@ -275,14 +275,6 @@ const TokenUsagePanel = ({ embedded = false }: TokenUsagePanelProps = {}) => {disabled={settings === null}onChange={v => void patch({ html_enabled: v })}/>- <ToggleRow- id="tj-ml-enabled"- label={t('settings.tokenUsage.ml')}- description={t('settings.tokenUsage.mlDesc')}- checked={settings?.ml_compression_enabled ?? false}- disabled={settings === null}- onChange={v => void patch({ ml_compression_enabled: v })}- /></Card>{/* ── CCR cache ──────────────────────────────────────────────────── */}diff --git a/app/src/components/settings/panels/__tests__/TokenUsagePanel.coverage.test.tsx b/app/src/components/settings/panels/__tests__/TokenUsagePanel.coverage.test.tsxindex 4fcced94d8..5f2642b950 100644--- a/app/src/components/settings/panels/__tests__/TokenUsagePanel.coverage.test.tsx+++ b/app/src/components/settings/panels/__tests__/TokenUsagePanel.coverage.test.tsx@@ -60,12 +60,6 @@ const SETTINGS: TokenjuiceSettings = {search_enabled: false,code_enabled: false,html_enabled: false,- ml_compression_enabled: false,- ml_model_id: 'm',- ml_target_ratio: 0.5,- ml_sidecar_idle_timeout_secs: 60,- ml_max_input_chars: 1000,- ml_device: 'cpu',};const bucket = (over: Partial<SavingsStats['total']> = {}): SavingsStats['total'] => ({@@ -228,7 +222,6 @@ describe('TokenUsagePanel — compression toggles', () => {['settings.tokenUsage.search', 'search_enabled'],['settings.tokenUsage.code', 'code_enabled'],['settings.tokenUsage.html', 'html_enabled'],- ['settings.tokenUsage.ml', 'ml_compression_enabled'],['settings.tokenUsage.ccrEnabled', 'ccr_enabled'],['settings.tokenUsage.ccrDisk', 'ccr_disk_enabled'],])('toggling "%s" patches only %s', async (label, key) => {diff --git a/app/src/components/settings/panels/__tests__/TokenUsagePanel.test.tsx b/app/src/components/settings/panels/__tests__/TokenUsagePanel.test.tsxindex b195d72f77..c146914221 100644--- a/app/src/components/settings/panels/__tests__/TokenUsagePanel.test.tsx+++ b/app/src/components/settings/panels/__tests__/TokenUsagePanel.test.tsx@@ -36,12 +36,6 @@ const stubSettings: tokenjuice.TokenjuiceSettings = {search_enabled: true,code_enabled: false,html_enabled: true,- ml_compression_enabled: false,- ml_model_id: 'model',- ml_target_ratio: 0.5,- ml_sidecar_idle_timeout_secs: 30,- ml_max_input_chars: 4096,- ml_device: 'cpu',};const stubSavings: tokenjuice.SavingsStats = {@@ -72,7 +66,7 @@ describe('TokenUsagePanel', () => {// to enabled (after async settings load), proving the load actually settled.await waitFor(() => {const switches = screen.getAllByRole('switch');- expect(switches).toHaveLength(7);+ expect(switches).toHaveLength(6);for (const sw of switches) expect(sw).not.toBeDisabled();});expect(@@ -113,7 +107,7 @@ describe('TokenUsagePanel', () => {// Controls remain interactive despite the savings failure.const switches = screen.getAllByRole('switch');- expect(switches).toHaveLength(7);+ expect(switches).toHaveLength(6);for (const sw of switches) expect(sw).not.toBeDisabled();expect(screen.getByRole('spinbutton', { name: 'settings.tokenUsage.ccrMinTokens' })@@ -134,7 +128,7 @@ describe('TokenUsagePanel', () => {await screen.findByText('rpc down');const switches = screen.getAllByRole('switch');- expect(switches).toHaveLength(7);+ expect(switches).toHaveLength(6);for (const sw of switches) expect(sw).toBeDisabled();expect(screen.getByRole('spinbutton', { name: 'settings.tokenUsage.ccrMinTokens' })diff --git a/app/src/features/conversations/tools/__fixtures__/coreToolNames.json b/app/src/features/conversations/tools/__fixtures__/coreToolNames.jsonindex 0e7759df10..831be49a4e 100644--- a/app/src/features/conversations/tools/__fixtures__/coreToolNames.json+++ b/app/src/features/conversations/tools/__fixtures__/coreToolNames.json@@ -109,15 +109,12 @@"media_generate_video","media_list_models","memory",- "node_exec",- "npm_exec","oauth_connect_url","oauth_list","plan_exit","propose_workflow","proxy_config","pushover",- "python_exec","read_diff","read_workflow_resource","read_workflow_run_log",diff --git a/app/src/features/conversations/tools/toolSpecs.ts b/app/src/features/conversations/tools/toolSpecs.tsindex c74f4cb587..de8b1accb6 100644--- a/app/src/features/conversations/tools/toolSpecs.ts+++ b/app/src/features/conversations/tools/toolSpecs.ts@@ -174,18 +174,6 @@ export const EXACT_TOOL_SPECS: Record<string, ToolSpec> = {// ── Shell and system ────────────────────────────────────────────────────shell: spec('runCommand', SquareTerminalIcon, 'shell', { chip: chip.command(), body: 'shell' }),- node_exec: spec('runCode', SquareTerminalIcon, 'shell', {- chip: chip.command('script_path', 'inline_code'),- body: 'shell',- }),- python_exec: spec('runCode', SquareTerminalIcon, 'shell', {- chip: chip.command('script_path', 'inline_code'),- body: 'shell',- }),- npm_exec: spec('runPackageManager', SquareTerminalIcon, 'shell', {- chip: chip.command('subcommand'),- body: 'shell',- }),detect_tools: spec('checkInstalledTools', ScanSearchIcon, 'system'),install_tool: spec('installTool', PackagePlusIcon, 'system', {chip: chip.text('package', 'tool_name'),diff --git a/app/src/services/api/skillsApi.ts b/app/src/services/api/skillsApi.tsindex f388af204c..e5325d38e7 100644--- a/app/src/services/api/skillsApi.ts+++ b/app/src/services/api/skillsApi.ts@@ -567,11 +567,7 @@ export const skillsApi = {return raw.runs;},- /**- * Resolve the reusable Node/Python runtimes backing script-based skills.- * The backend reuses `runtime_node` and `runtime_python`; this call is a- * cheap UI/prod-smoke probe unless it has to bootstrap a missing managed runtime.- */+ /** Probe whether the host Node.js and Python executables are available on PATH. */resolveRuntimes: async (runtime: 'all' | 'node' | 'python' = 'all'): Promise<ResolveSkillRuntimesResult> => {diff --git a/app/src/utils/tauriCommands/config.ts b/app/src/utils/tauriCommands/config.tsindex a32a4cf4ce..c642f7d572 100644--- a/app/src/utils/tauriCommands/config.ts+++ b/app/src/utils/tauriCommands/config.ts@@ -486,7 +486,7 @@ export async function openhumanGetAutonomySettings(): Promise<CommandResponse<Au* already-canonicalised path strings; the UI renders them verbatim instead of* hard-coding defaults like `~/OpenHuman/projects`.*- * - `action_dir` — agent CWD for `shell` / `node_exec` / `npm_exec` / file+ * - `action_dir` — agent CWD for `shell` / file* writes. Defaults to `projects_dir`; overridable via `OPENHUMAN_ACTION_DIR`.* - `workspace_dir` — internal product state (memory / sessions / vault).* Agent-blocked.diff --git a/app/src/utils/tauriCommands/tokenjuice.ts b/app/src/utils/tauriCommands/tokenjuice.tsindex 8a1c180da1..45445c5803 100644--- a/app/src/utils/tauriCommands/tokenjuice.ts+++ b/app/src/utils/tauriCommands/tokenjuice.ts@@ -24,12 +24,6 @@ export interface TokenjuiceSettings {search_enabled: boolean;code_enabled: boolean;html_enabled: boolean;- ml_compression_enabled: boolean;- ml_model_id: string;- ml_target_ratio: number;- ml_sidecar_idle_timeout_secs: number;- ml_max_input_chars: number;- ml_device: string;}/** Partial update — only present fields are changed. */diff --git a/crates/openhuman-app/Cargo.lock b/crates/openhuman-app/Cargo.lockindex 68c195a499..fc22006462 100644--- a/crates/openhuman-app/Cargo.lock+++ b/crates/openhuman-app/Cargo.lock@@ -4682,8 +4682,6 @@ dependencies = ["tinymemory-api","tinymemory-integrations","tinymemory-tools",- "tinyruntime-bus",- "tinyruntime-pyserver","tinysearch-bus","tinyskills","tinystoragedrivers",@@ -8352,25 +8350,6 @@ dependencies = ["tinymemory-api",]-[[package]]-name = "tinyruntime-bus"-version = "0.2.12"-dependencies = [- "serde",- "serde_json",-]--[[package]]-name = "tinyruntime-pyserver"-version = "0.2.12"-dependencies = [- "serde",- "serde_json",- "thiserror 2.0.20",- "tokio",- "tracing",-]-[[package]]name = "tinysearch-bus"version = "0.4.1"diff --git a/crates/openhuman-app/Cargo.toml b/crates/openhuman-app/Cargo.tomlindex b43104350c..7e89463b77 100644--- a/crates/openhuman-app/Cargo.toml+++ b/crates/openhuman-app/Cargo.toml@@ -88,7 +88,6 @@ openhuman-rpc = { path = "../openhuman-rpc", default-features = false, features"http-server","scheduler-gate","file-logging",- "runtime-node","hosting","tinymemes","storage-sqlite",diff --git a/crates/openhuman-app/README.md b/crates/openhuman-app/README.mdindex ba31d956f2..c14aac889e 100644--- a/crates/openhuman-app/README.md+++ b/crates/openhuman-app/README.md@@ -281,7 +281,7 @@ the chain to the core. Because default features are off, every product gatemust be listed by hand:`channels`, `media`, `inference`, `voice`, `web3`, `documents`, `modules`,`flows`, `skills`, `mcp`, `crash-reporting`, `http-server`, `scheduler-gate`,-`file-logging`, `runtime-node`, `hosting`. A gate missing here disappears from+`file-logging`, `hosting`. A gate missing here disappears fromthe shipped app with no build error. [`scripts/ci/check-feature-forwarding.mjs`](../../scripts/ci/check-feature-forwarding.mjs)compares the list with [`scripts/ci/product-features.txt`](../../scripts/ci/product-features.txt), and `lib.rs` has two`const _: () = assert!(...)` guards (`VOICE_COMPILED_IN`,diff --git a/crates/openhuman-cli/Cargo.toml b/crates/openhuman-cli/Cargo.tomlindex db126e5b9f..15ddc54d95 100644--- a/crates/openhuman-cli/Cargo.toml+++ b/crates/openhuman-cli/Cargo.toml@@ -380,7 +380,6 @@ web3 = ["openhuman-rpc/web3"]storage-sqlite = ["openhuman-rpc/storage-sqlite"]storage-mongodb = ["openhuman-rpc/storage-mongodb"]storage-file = ["openhuman-rpc/storage-file"]-runtime-node = ["openhuman-rpc/runtime-node"]media = ["openhuman-rpc/media"]flows = ["openhuman-rpc/flows"]skills = ["openhuman-rpc/skills"]diff --git a/crates/openhuman-core/Cargo.toml b/crates/openhuman-core/Cargo.tomlindex cbf7cbcca3..0e4123b7e1 100644--- a/crates/openhuman-core/Cargo.toml+++ b/crates/openhuman-core/Cargo.toml@@ -187,26 +187,6 @@ tinytools = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools"tinytools-agent = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-agent" }tinytools-std = { path = "../../vendor/tinyagents/vendor/tinytools/crates/tinytools-std" }-# tinyruntime — the runtime router-# (https://github.com/tinyhumansai/tinyruntime). Only the *contract* crate is-# taken here, never the router itself: the router ships as a loadable TinyBus-# module, and a host that also compiled it would carry the download pipeline, the-# worker pool, and their dependency trees for nothing.-#-# `tinyruntime-bus` is deliberately dependency-light — `serde` and `serde_json`-# and nothing else — which is what makes naming the payload types cost this-# manifest almost nothing. The module's own CI asserts it stays that way.-#-# After cloning: `git submodule update --init --recursive vendor/tinyruntime`.-tinyruntime-bus = { path = "../../vendor/tinyruntime/crates/tinyruntime-bus" }-#-# `tinyruntime-pyserver` is the one library crate of that repository the core-# links: the persistent Python worker (spaCy, Kompress) that-# `runtime::python_server` hosts. It is a pure library (no bus, no module), so-# it needs no registry record; it carries only `serde`, `tokio` and `tracing`,-# which this manifest already has. The pin is the tinyruntime module pin plus-# the crate itself; see `scripts/ci/module-pin-exemptions.json`.-tinyruntime-pyserver = { path = "../../vendor/tinyruntime/crates/tinyruntime-pyserver" }# TinyMemory (https://github.com/tinyhumansai/tinymemory), three crates:# - `tinymemory-api`: the engine contract (`MemoryEngine`: recall / fetch /@@ -379,8 +359,8 @@ sha2 = "0.10"# cargo error, not a warning.# Archive handling for the Piper voice installer and the document tools. The# Node.js and Python toolchain archives are no longer unpacked here — the-# `tinyruntime` module owns that — which is what let `xz2` and its static-# liblzma C build leave this manifest entirely.+# OpenHuman no longer downloads or unpacks Node.js or Python; both use the host+# toolchain through the shell.tar = "0.4"zip = { version = "2", default-features = false, features = ["deflate"] }# gzip decoder for the Piper tar.gz binary releases on macOS / Linux. Already@@ -901,34 +881,6 @@ web3 = ["modules",]-# Managed Node.js runtime: `runtime::node` (the client that asks the-# `tinyruntime` module for a toolchain), the `runtime::javascript` language slot-# over it, `runtime::pool::node`, the `node_exec` / `npm_exec` agent tools, and-# the `node_runtime` harness-init step. Default-ON. Slim builds opt out via-# `--no-default-features --features "<list without runtime-node>"`.-#-# This gate no longer sheds a dependency. It used to carry the exclusive `xz2`-# and its static liblzma C build; downloading and unpacking a toolchain moved to-# the `tinyruntime` module, so that native build left this manifest for every-# configuration rather than only for slim ones. What the gate still buys is the-# absence of the tools and controllers themselves.-#-# FACADE + STUB, not a leaf gate. `ShellTool` holds `Option<Arc<NodeBootstrap>>`-# for managed-Node PATH injection and `tools/impl/system/shell.rs` is kernel, so-# deleting the module would take the shell tool with it. `runtime/node/stub.rs`-# carries the `NodeBootstrap` type surface; registration sites (`node_runtime_step`,-# the `javascript` controllers, `node_exec`/`npm_exec`) are leaf-gated at their call-# sites, because registration sites want absence.-#-# The generic native-tool dispatcher (`runtime::node::ops` / `runtime::node::types`)-# is deliberately NOT gated: it backs both the gated `javascript.*` controllers and-# the ungated `flows` `oh:` `NativeToolBackend`, so native flow tools keep working-# when the managed Node runtime is compiled out.-#-# Off-state: `try_cached`/`probe_installed` return `None`, so the shell never-# prepends a managed bin dir — identical to today's `node.enabled = false` path.-runtime-node = []-# Media-generation + image domains: the `media_generate_*` agent tools# (image/video via OpenRouter through the backend's# `/agent-integrations/openrouter` proxy) and the `openhuman::image` tool@@ -964,8 +916,7 @@ flows = ["dep:tinyflows", "dep:tinyflows-catalog", "dep:tinyflows-copilot", "tin# The dep list is INTENTIONALLY EMPTY — do not "fix" it. Unlike `voice`# (`hound`/`lettre`), these domains have no exclusive dependencies: every crate# they touch (serde, serde_json, tokio, anyhow, async-trait, …) is shared with-# always-on domains, and `runtime_node`/`runtime_python` are used by Agent /-# Flows / Memory too. This gate's value is tool-surface + prompt-bloat ++# always-on domains. This gate's value is tool-surface + prompt-bloat +# startup cost, NOT binary size.## NOTE: `openhuman::skills::types` and `::ops_types` stay compiled even whendiff --git a/crates/openhuman-core/README.md b/crates/openhuman-core/README.mdindex f014c0b5d8..3247162a7b 100644--- a/crates/openhuman-core/README.md+++ b/crates/openhuman-core/README.md@@ -53,7 +53,7 @@ OpenHuman's policy.| tinyagents (+ tinytools, tinyinference) tinymemory (+ tinycortex) || tinybus tinychannels tinyflows tinymcp tinyskills tinybox || tinyconnectors tinycomputer tinydocs tinysearch tinyjuice |- | tinyruntime tinyvoice tinywallet tinyhosts |+ | tinyvoice tinywallet tinyhosts |+-------------------------------------------------------------------------+```@@ -175,7 +175,6 @@ feature-gated by the feature of the same name.| [`src/tools/`](src/tools/README.md) | Assembles each session's tool list ([`tools/ops.rs`](./src/tools/ops.rs)), cross-cutting built-in tools, and tool policy. Domain tools live with their domain and are re-exported here. || [`src/security/`](src/security/README.md) | The trust boundary: autonomy policy, approvals, credentials and secrets, redaction, egress and local-only mode, listener guard. || [`src/sandbox/`](src/sandbox/README.md) | Sandbox backends for tool isolation (platform jail, Docker via `tinybox`). |-| [`src/runtime/`](src/runtime/README.md) | Client side of code execution: `node_exec`, `npm_exec`, `python_exec`, `shell`, worker pools over the `tinyruntime` module. || [`src/modules/`](src/modules/README.md)* | Loadable native modules: the `tinybus` module host, registry, attestation, and per-module clients (search, wallet, documents, computer, voice, ...). || [`src/skills/`](src/skills/README.md) | SKILL.md discovery, install, and run over `tinyskills`. || [`src/mcp/`](src/mcp/README.md) | Host half of MCP: configuration, lifecycle, and the MCP server surface over `tinymcp`. |@@ -226,7 +225,6 @@ forwarding, and the library chain (`openhuman-embed`, then| `voice` | no | yes | The voice stack || `web3` | no | yes | Real `web3`, `wallet`, `x402` (stubs otherwise) || `documents` | no | yes | Document tools over the `tinydocs` module |-| `runtime-node` | no | yes | Managed Node.js runtime and its tools || `hosting` | no | yes | `openhuman::hosting` || `crash-reporting` | no | yes | Sentry || `whatsapp-web` | no | no | WhatsApp Web channel provider |@@ -236,9 +234,9 @@ forwarding, and the library chain (`openhuman-embed`, thenGates come in two shapes. A leaf gate removes the module (`hosting`, `media`,`flows`, `modules`). A facade gate keeps the module declared and gates mostof its contents inside its own `mod.rs` (`channels`, `mcp`, `skills`,-`voice`, `web3`, `runtime-node`). Several facades also swap in a `stub.rs`+`voice`, `web3`). Several facades also swap in a `stub.rs`with matching signatures so always-on callers need no `#[cfg]` (`web3` and-its `wallet` and `x402` members, `skills`, `voice`, [`runtime/node`](./src/runtime/node/)). Stub+its `wallet` and `x402` members, `skills`, `voice`). Stubdrift is only caught by `cargo check --no-default-features`. Every compile-time gatecomposes with the matching runtime `DomainSet` flag. The kernel floor profileis `--no-default-features --features flows`. Read the policy comments abovediff --git a/crates/openhuman-core/src/agent/host_runtime.rs b/crates/openhuman-core/src/agent/host_runtime.rsindex bf77ba06a8..8aeb487e1c 100644--- a/crates/openhuman-core/src/agent/host_runtime.rs+++ b/crates/openhuman-core/src/agent/host_runtime.rs@@ -92,7 +92,7 @@ impl RuntimeAdapter for NativeRuntime {// actionable message naming the path, instead of an opaque OS error 267// (ERROR_DIRECTORY) from CreateProcessW on Windows / a raw ENOENT on// Unix when the process is spawned. Covers all three shell-family tools- // (shell / node_exec / npm_exec) since they all route through here.+ // (shell) since it routes through here.// (#3353, Fix 2)crate::config::ensure_usable_cwd(workspace_dir)?;cmd.current_dir(workspace_dir);diff --git a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rsindex 6f8374be46..b699dd5961 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/archetype_delegation.rs@@ -97,7 +97,7 @@ impl Tool for ArchetypeDelegationTool {/// child's lifetime is already bounded internally — by its `max_iterations`,/// the run cancellation token, and each inner tool's own timeout — so it/// governs its own duration, exactly like the sibling `spawn_parallel_agents`- /// fan-out and the long-running scripting tools (`shell`, `node_exec`).+ /// fan-out and the long-running shell tool.fn timeout_policy(&self, _args: &serde_json::Value) -> ToolTimeout {ToolTimeout::Unbounded}diff --git a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rsindex 17c7a79218..244a0e2b23 100644--- a/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs+++ b/crates/openhuman-core/src/agent/orchestration/tools/spawn_parallel_agents.rs@@ -224,7 +224,7 @@ impl Tool for SpawnParallelAgentsTool {/// each worker's research is cut short. The fan-out is already bounded/// internally — by `max_concurrency`, the run cancellation token, and each/// sub-agent's own iteration/turn caps — so it governs its own lifetime,- /// like the long-running scripting tools (`shell`, `node_exec`).+ /// like the long-running shell tool.fn timeout_policy(&self, _args: &serde_json::Value) -> ToolTimeout {ToolTimeout::Unbounded}diff --git a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rs b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rsindex a7ccdb5d01..6e022bf109 100644--- a/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rs+++ b/crates/openhuman-core/src/agent/session_host/builder/builder_tests_tool_exposure_tests.rs@@ -230,8 +230,8 @@ fn orchestrator_reaches_the_replaced_specialists_tools_through_discovery() {let deferred = agent.deferred_tool_names_for_test();let visible = agent.visible_tool_names_for_test();let policy = agent.tool_policy_session_for_test();- // Unconditionally registered members only: `node_exec` / `npm_exec` need- // the managed Node runtime and the wallet family needs the `web3`+ // Unconditionally registered members only: language commands run through shell and need+ // host Node runtime and the wallet family needs the `web3`// feature, so a test profile without them cannot see them either way.for tool in ["cron",diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rsindex 55d9599212..5a60c7751e 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_command_exit_failure_tests.rs@@ -125,8 +125,8 @@ async fn an_identical_failing_command_repeated_unchanged_still_halts() {}const MODULE_FAULT: &str =- "Failed to resolve command runtime: module 'tinyruntime' could not be loaded \- from the installer bundle: module `ubuntu-22.04-x86_64` refused: module directory is owned by \+ "Failed to resolve command runtime: module 'sample-runtime' could not be loaded \+ from the installer bundle: module `linux-x64` refused: module directory is owned by \another user. This is terminal for the running process; restart the app to try again";#[test]diff --git a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_effect_tests.rs b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_effect_tests.rsindex 578d8d1e84..3968430678 100644--- a/crates/openhuman-core/src/agent/tinyagents/middleware_failure_effect_tests.rs+++ b/crates/openhuman-core/src/agent/tinyagents/middleware_failure_effect_tests.rs@@ -93,7 +93,7 @@ fn a_timeout_before_the_tool_ran_is_transient() {// reconcile, even for an execute-class tool.assert_eq!(recovery_policy_with_effect(- "python_exec",+ "shell","Python runtime unavailable: runtime resolution timed out after 60s",false,CallEffect::SideEffecting@@ -232,7 +232,7 @@ fn a_missing_shell_command_gets_one_correction() {);// Other tools keep the zero-retry `unsupported` verdict.assert_eq!(- recovery_policy("python_exec", "executable not found", false),+ recovery_policy("shell", "executable not found", false),Some(("unsupported", 0)));}diff --git a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rsindex 0f18a22d52..bc4f051116 100644--- a/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs+++ b/crates/openhuman-core/src/channels/providers/relay/ops_tests.rs@@ -15,7 +15,6 @@ fn config(tmp: &tempfile::TempDir) -> Config {..Config::default()};config.local_ai.runtime_enabled = false;- config.runtime_python.enabled = false;config.memory.conversations.enabled = false;config.agent.session_dual_write = false;config.agent.session_shadow_reads = false;diff --git a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rsindex c4be6dbf20..6bb1f945a1 100644--- a/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs+++ b/crates/openhuman-core/src/channels/runtime/dispatch/host_agent/dispatch_tests.rs@@ -89,7 +89,6 @@ fn config(tmp: &tempfile::TempDir, agent_id: Option<&str>) -> Config {..Config::default()};config.local_ai.runtime_enabled = false;- config.runtime_python.enabled = false;config.memory.conversations.enabled = false;config.agent.session_dual_write = false;config.agent.session_shadow_reads = false;diff --git a/crates/openhuman-core/src/config/mod.rs b/crates/openhuman-core/src/config/mod.rsindex f4b8b75a70..649dfab02f 100644--- a/crates/openhuman-core/src/config/mod.rs+++ b/crates/openhuman-core/src/config/mod.rs@@ -52,18 +52,17 @@ pub use schema::{McpAuthConfig, McpClientConfig, McpClientIdentityConfig, McpServerConfig, McpToolExposure,MemoryConfig, MemoryLayoutMode, ModelRouteConfig, MultimodalConfig, MultimodalFileConfig,ObservabilityConfig, OrchestratorModelConfig, PrivacyConfig, PrivacyMode, ProxyConfig,- ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, RuntimePoolConfig,- RuntimePoolLangConfig, SandboxBackend, SandboxConfig, SchedulerConfig, SchedulerGateConfig,- SchedulerGateMode, SearchConfig, SearchEngineCredentials, SearchPresentation,- SearchProviderSettings, SearchRoute, SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig,- SlackConfig, StreamMode, SttEngine, TeamModelConfig, TelegramConfig, TokenjuiceConfig,- UpdateConfig, UpdateRestartStrategy, VoiceActivationMode, VoiceServerConfig, WebSearchConfig,- WebhookConfig, YuanbaoConfig, DEFAULT_MODEL, LEGACY_TIER_MODELS, MANAGED_MULTIMODAL_MODELS,- MANAGED_SEARCH_PROVIDERS, MODEL_IMAGE_GENERATION_AGENT, MODEL_MANAGED_DEFAULT,- MODEL_MEDIA_UNDERSTANDING, MODEL_VIDEO_GENERATION_AGENT, SEARCH_ENGINE_BRAVE,- SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA, SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL,- SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY, SEARCH_PROVIDERS, SEARCH_ROLES, SEARCH_ROLE_ANSWER,- SEARCH_ROLE_CONTENTS, SEARCH_ROLE_SEARCH,+ ProxyScope, ReliabilityConfig, ResourceLimitsConfig, RuntimeConfig, SandboxBackend,+ SandboxConfig, SchedulerConfig, SchedulerGateConfig, SchedulerGateMode, SearchConfig,+ SearchEngineCredentials, SearchPresentation, SearchProviderSettings, SearchRoute,+ SearxngConfig, SecretsConfig, SecurityConfig, ShellConfig, SlackConfig, StreamMode, SttEngine,+ TeamModelConfig, TelegramConfig, TokenjuiceConfig, UpdateConfig, UpdateRestartStrategy,+ VoiceActivationMode, VoiceServerConfig, WebSearchConfig, WebhookConfig, YuanbaoConfig,+ DEFAULT_MODEL, LEGACY_TIER_MODELS, MANAGED_MULTIMODAL_MODELS, MANAGED_SEARCH_PROVIDERS,+ MODEL_IMAGE_GENERATION_AGENT, MODEL_MANAGED_DEFAULT, MODEL_MEDIA_UNDERSTANDING,+ MODEL_VIDEO_GENERATION_AGENT, SEARCH_ENGINE_BRAVE, SEARCH_ENGINE_DISABLED, SEARCH_ENGINE_EXA,+ SEARCH_ENGINE_MANAGED, SEARCH_ENGINE_PARALLEL, SEARCH_ENGINE_QUERIT, SEARCH_ENGINE_TAVILY,+ SEARCH_PROVIDERS, SEARCH_ROLES, SEARCH_ROLE_ANSWER, SEARCH_ROLE_CONTENTS, SEARCH_ROLE_SEARCH,};// Kept as a separate re-export (issue #4117) so the large alphabetized group// above stays byte-identical and rustfmt-stable.diff --git a/crates/openhuman-core/src/config/schema/README.md b/crates/openhuman-core/src/config/schema/README.mdindex b3c4be13c6..cdcfd099e5 100644--- a/crates/openhuman-core/src/config/schema/README.md+++ b/crates/openhuman-core/src/config/schema/README.md@@ -34,15 +34,12 @@ is mounted as a submodule of [`load/dirs.rs`](./load/dirs.rs) via `#[path]`.| `[learning]` | `learning.rs` | `LearningConfig`, `ReflectionSource` || `[local_ai]` | [`local_ai.rs`](./local_ai.rs) | `LocalAiConfig`, `LocalAiUsage` || `[modules]` | [`modules.rs`](./modules.rs) | `ModulesConfig`, `ModuleOverride`: controls only whether compiled-in modules load. The loadable *set* is fixed by `crate::modules::registry` |-| `[node]` | [`node.rs`](./node.rs) | `NodeConfig` (managed Node.js toolchain for skills) || `[observability]` | [`observability.rs`](./observability.rs) | `ObservabilityConfig`, `AgentTracingConfig` || `[privacy]` | [`privacy.rs`](./privacy.rs) | `PrivacyConfig`, `PrivacyMode` || `[proxy]` | [`proxy.rs`](./proxy.rs) | `ProxyConfig`, `ProxyScope`, plus `runtime_proxy_config()` / `set_runtime_proxy_config()` process-wide accessors || `[[model_routes]]`, `[[embedding_routes]]` | [`routes.rs`](./routes.rs) | `ModelRouteConfig`, `EmbeddingRouteConfig` || `[runtime]` (+ `[runtime.docker]`), `[shell]`, `[reliability]`, `[scheduler]` | [`runtime.rs`](./runtime.rs) | `RuntimeConfig`, `DockerRuntimeConfig`, `ShellConfig`, `ReliabilityConfig`, `SchedulerConfig` |-| `[runtime_pool]` | [`runtime_pool.rs`](./runtime_pool.rs) | `RuntimePoolConfig`, `RuntimePoolLangConfig` || `[runtime.local_jail]` | [`runtime_local_jail.rs`](./runtime_local_jail.rs) | `LocalJailConfig`: filesystem grants for the local OS jail |-| `[runtime_python]` | [`runtime_python.rs`](./runtime_python.rs) | `RuntimePythonConfig` || `[scheduler_gate]` | [`scheduler_gate.rs`](./scheduler_gate.rs) | `SchedulerGateConfig`, `SchedulerGateMode` || `[memory]` (engine, `engines.<id>`, `conversations`, `context`, `sources`, embedding settings) | [`memory.rs`](./memory.rs) | `MemoryConfig`, `MemoryEngineSettings`, `MemoryConversationsConfig`, `MemoryContextConfig`, `MemorySourceConfig` (see [`docs/specs/memory-v2.md`](../../../../../docs/specs/memory-v2.md)) || `[task_sources]` | [`task_sources.rs`](./task_sources.rs) | `TaskSourcesConfig` |diff --git a/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rsindex 0a8d4d8a90..e02a73d369 100644--- a/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs+++ b/crates/openhuman-core/src/config/schema/load/env_overlay/runtime.rs@@ -1,4 +1,4 @@-//! Env overrides for the Node, Python, runtime-pool, and tokenjuice runtimes.+//! Environment overrides for token compression and related settings.use crate::config::schema::load::env::parse_env_bool;use crate::config::schema::load::env::EnvLookup;@@ -6,84 +6,6 @@ use crate::config::schema::Config;impl Config {pub(super) fn apply_runtime_env<E: EnvLookup + ?Sized>(&mut self, env: &E) {- if let Some(flag) = env.get("OPENHUMAN_NODE_ENABLED") {- if let Some(enabled) = parse_env_bool("OPENHUMAN_NODE_ENABLED", &flag) {- self.node.enabled = enabled;- }- }- if let Some(version) = env.get("OPENHUMAN_NODE_VERSION") {- let trimmed = version.trim();- if !trimmed.is_empty() {- self.node.version = trimmed.to_string();- }- }- if let Some(dir) = env.get("OPENHUMAN_NODE_CACHE_DIR") {- let trimmed = dir.trim();- if !trimmed.is_empty() {- self.node.cache_dir = trimmed.to_string();- }- }- if let Some(flag) = env.get("OPENHUMAN_NODE_PREFER_SYSTEM") {- if let Some(prefer_system) = parse_env_bool("OPENHUMAN_NODE_PREFER_SYSTEM", &flag) {- self.node.prefer_system = prefer_system;- }- }-- if let Some(flag) = env.get("OPENHUMAN_RUNTIME_PYTHON_ENABLED") {- if let Some(enabled) = parse_env_bool("OPENHUMAN_RUNTIME_PYTHON_ENABLED", &flag) {- self.runtime_python.enabled = enabled;- }- }- if let Some(version) = env.get("OPENHUMAN_RUNTIME_PYTHON_MINIMUM_VERSION") {- let trimmed = version.trim();- if !trimmed.is_empty() {- self.runtime_python.minimum_version = trimmed.to_string();- }- }- if let Some(dir) = env.get("OPENHUMAN_RUNTIME_PYTHON_CACHE_DIR") {- self.runtime_python.cache_dir = dir.trim().to_string();- }- if let Some(tag) = env.get("OPENHUMAN_RUNTIME_PYTHON_MANAGED_RELEASE_TAG") {- self.runtime_python.managed_release_tag = tag.trim().to_string();- }- if let Some(flag) = env.get("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM") {- if let Some(prefer_system) =- parse_env_bool("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM", &flag)- {- self.runtime_python.prefer_system = prefer_system;- }- }- if let Some(command) = env.get("OPENHUMAN_RUNTIME_PYTHON_PREFERRED_COMMAND") {- self.runtime_python.preferred_command = command.trim().to_string();- }-- // --- Shared language-runtime pool (#5106) --------------------------- if let Some(flag) = env.get("OPENHUMAN_RUNTIME_POOL_ENABLED") {- if let Some(enabled) = parse_env_bool("OPENHUMAN_RUNTIME_POOL_ENABLED", &flag) {- self.runtime_pool.enabled = enabled;- }- }- if let Some(raw) = env.get("OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS") {- match raw.trim().parse::<usize>() {- Ok(n) => self.runtime_pool.node.max_workers = n,- Err(e) => tracing::warn!(- value = %raw,- error = %e,- "[config] ignoring invalid OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS"- ),- }- }- if let Some(raw) = env.get("OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS") {- match raw.trim().parse::<usize>() {- Ok(n) => self.runtime_pool.python.max_workers = n,- Err(e) => tracing::warn!(- value = %raw,- error = %e,- "[config] ignoring invalid OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS"- ),- }- }-// --- TokenJuice content router -------------------------------------if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ENABLED") {if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ENABLED", &flag) {@@ -145,40 +67,5 @@ impl Config {self.tokenjuice.ccr_min_tokens = v;}}- // ML plain-text compressor (Kompress).- if let Some(flag) = env.get("OPENHUMAN_TOKENJUICE_ML_COMPRESSION_ENABLED") {- if let Some(v) = parse_env_bool("OPENHUMAN_TOKENJUICE_ML_COMPRESSION_ENABLED", &flag) {- self.tokenjuice.ml_compression_enabled = v;- }- }- if let Some(m) = env.get("OPENHUMAN_TOKENJUICE_ML_MODEL_ID") {- let t = m.trim();- if !t.is_empty() {- self.tokenjuice.ml_model_id = t.to_string();- }- }- if let Some(d) = env.get("OPENHUMAN_TOKENJUICE_ML_DEVICE") {- let t = d.trim();- if !t.is_empty() {- self.tokenjuice.ml_device = t.to_string();- }- }- if let Some(r) = env.get("OPENHUMAN_TOKENJUICE_ML_TARGET_RATIO") {- if let Ok(v) = r.trim().parse::<f64>() {- if (0.0..=1.0).contains(&v) {- self.tokenjuice.ml_target_ratio = v;- }- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_ML_SIDECAR_IDLE_TIMEOUT_SECS") {- if let Ok(v) = s.trim().parse::<u64>() {- self.tokenjuice.ml_sidecar_idle_timeout_secs = v;- }- }- if let Some(s) = env.get("OPENHUMAN_TOKENJUICE_ML_MAX_INPUT_CHARS") {- if let Ok(v) = s.trim().parse::<usize>() {- self.tokenjuice.ml_max_input_chars = v;- }- }}}diff --git a/crates/openhuman-core/src/config/schema/load/parse_tests.rs b/crates/openhuman-core/src/config/schema/load/parse_tests.rsindex fba8043a02..7bbacc2087 100644--- a/crates/openhuman-core/src/config/schema/load/parse_tests.rs+++ b/crates/openhuman-core/src/config/schema/load/parse_tests.rs@@ -29,6 +29,40 @@ fn an_empty_document_matches_direct_toml() {);}+#[test]+fn legacy_configuration_with_retired_sections_still_parses() {+ let legacy = format!(+ r#"+ [node]+ enabled = true+ version = "22.0.0"++ [runtime_python]+ enabled = true+ minimum_version = "3.12"++ [runtime_pool]+ enabled = true++ [tokenjuice]+ {}+ {}+ {}+ {}+ {}+ {}+ "#,+ concat!("ml_", "compression_enabled = true"),+ concat!("ml_", "model_id = \"old/model\""),+ concat!("ml_", "target_ratio = 0.6"),+ concat!("ml_", "sidecar_idle_timeout_secs = 60"),+ concat!("ml_", "max_input_chars = 5000"),+ concat!("ml_", "device = \"cpu\""),+ );+ let config = config_from_toml_str(&legacy).expect("legacy config still parses");+ assert!(config.tokenjuice.router_enabled);+}+#[test]fn a_syntax_error_reports_the_toml_location() {let err = config_from_toml_str("default_model = \n[broken").unwrap_err();diff --git a/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs b/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rsindex fa58d44f98..eac86947ac 100644--- a/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs+++ b/crates/openhuman-core/src/config/schema/load_active_user_and_dirs_tests.rs@@ -660,45 +660,6 @@ fn env_overlay_toggles_agent_tracing_capture_content() {assert!(cfg.observability.agent_tracing.capture_content);}-#[test]-fn env_overlay_runtime_pool_workers_and_enabled() {- // Baseline: master switch on, both pools at the default worker count.- let mut cfg = Config::default();- assert!(cfg.runtime_pool.enabled, "master switch defaults on");- assert_eq!(cfg.runtime_pool.node.max_workers, 2);- assert_eq!(cfg.runtime_pool.python.max_workers, 2);-- // Valid overrides land; `enabled` parses via the shared bool parser.- cfg.apply_env_overlay_with(- &HashMapEnv::new()- .with("OPENHUMAN_RUNTIME_POOL_ENABLED", "off")- .with("OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS", "7")- .with("OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS", "3"),- );- assert!(!cfg.runtime_pool.enabled, "explicit off disables the pool");- assert_eq!(cfg.runtime_pool.node.max_workers, 7);- assert_eq!(cfg.runtime_pool.python.max_workers, 3);-- // Unparseable worker counts are ignored (the warn arm) — the previously- // applied values survive rather than resetting to a default or zero.- cfg.apply_env_overlay_with(- &HashMapEnv::new()- .with("OPENHUMAN_RUNTIME_POOL_NODE_MAX_WORKERS", "not-a-number")- .with("OPENHUMAN_RUNTIME_POOL_PYTHON_MAX_WORKERS", ""),- );- assert_eq!(- cfg.runtime_pool.node.max_workers, 7,- "invalid node worker count keeps the prior value"- );- assert_eq!(- cfg.runtime_pool.python.max_workers, 3,- "empty python worker count keeps the prior value"- );-}--/// #6958: the iteration cap could only be raised by patching `agent.toml`.-/// `OPENHUMAN_AGENT_MAX_TOOL_ITERATIONS` sets the explicit override that wins-/// over the agent definition's cap.#[test]fn env_overlay_agent_max_tool_iterations_override() {let mut cfg = Config::default();diff --git a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rsindex 15c1de3882..7f9a167c92 100644--- a/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs+++ b/crates/openhuman-core/src/config/schema/load_env_overlay_tests.rs@@ -280,81 +280,6 @@ fn env_overlay_proxy_scope_invalid_value_leaves_scope_unchanged() {assert_eq!(cfg.proxy.scope, original_scope);}-#[test]-fn env_overlay_node_flags_respect_bool_parser() {- let mut cfg = Config::default();- let original_version = cfg.node.version.clone();-- cfg.apply_env_overlay_with(- &HashMapEnv::new()- .with("OPENHUMAN_NODE_ENABLED", "yes")- .with("OPENHUMAN_NODE_PREFER_SYSTEM", "off")- .with("OPENHUMAN_NODE_CACHE_DIR", "/tmp/oh-node"),- );- assert!(cfg.node.enabled);- assert!(!cfg.node.prefer_system);- assert_eq!(cfg.node.cache_dir, "/tmp/oh-node");- assert_eq!(- cfg.node.version, original_version,- "untouched keys stay at defaults"- );-- // Unrecognised bool — ignored, keeps previous true.- cfg.apply_env_overlay_with(&HashMapEnv::new().with("OPENHUMAN_NODE_ENABLED", "perhaps"));- assert!(cfg.node.enabled);-- // Blank version does NOT clobber.- cfg.apply_env_overlay_with(&HashMapEnv::new().with("OPENHUMAN_NODE_VERSION", " "));- assert_eq!(cfg.node.version, original_version);-}--#[test]-fn env_overlay_runtime_python_flags_respect_bool_parser() {- let mut cfg = Config::default();- let original_version = cfg.runtime_python.minimum_version.clone();-- cfg.apply_env_overlay_with(- &HashMapEnv::new()- .with("OPENHUMAN_RUNTIME_PYTHON_ENABLED", "yes")- .with("OPENHUMAN_RUNTIME_PYTHON_PREFER_SYSTEM", "off")- .with("OPENHUMAN_RUNTIME_PYTHON_CACHE_DIR", "/tmp/oh-python")- .with("OPENHUMAN_RUNTIME_PYTHON_MANAGED_RELEASE_TAG", "20260510")- .with("OPENHUMAN_RUNTIME_PYTHON_PREFERRED_COMMAND", "python3.12"),- );- assert!(cfg.runtime_python.enabled);- assert!(!cfg.runtime_python.prefer_system);- assert_eq!(cfg.runtime_python.cache_dir, "/tmp/oh-python");- assert_eq!(cfg.runtime_python.managed_release_tag, "20260510");- assert_eq!(cfg.runtime_python.preferred_command, "python3.12");- assert_eq!(- cfg.runtime_python.minimum_version, original_version,- "untouched keys stay at defaults"- );-- cfg.apply_env_overlay_with(- &HashMapEnv::new().with("OPENHUMAN_RUNTIME_PYTHON_ENABLED", "perhaps"),- );- assert!(cfg.runtime_python.enabled);-- cfg.apply_env_overlay_with(- &HashMapEnv::new().with("OPENHUMAN_RUNTIME_PYTHON_MINIMUM_VERSION", " "),- );- assert_eq!(cfg.runtime_python.minimum_version, original_version);-- cfg.runtime_python.cache_dir = "/tmp/seed".into();- cfg.runtime_python.managed_release_tag = "20260510".into();- cfg.runtime_python.preferred_command = "python3.12".into();- cfg.apply_env_overlay_with(- &HashMapEnv::new()- .with("OPENHUMAN_RUNTIME_PYTHON_CACHE_DIR", " ")- .with("OPENHUMAN_RUNTIME_PYTHON_MANAGED_RELEASE_TAG", " ")- .with("OPENHUMAN_RUNTIME_PYTHON_PREFERRED_COMMAND", " "),- );- assert_eq!(cfg.runtime_python.cache_dir, "");- assert_eq!(cfg.runtime_python.managed_release_tag, "");- assert_eq!(cfg.runtime_python.preferred_command, "");-}-#[test]fn env_overlay_sentry_dsn_trims_and_ignores_blank() {let mut cfg = Config::default();diff --git a/crates/openhuman-core/src/config/schema/mod.rs b/crates/openhuman-core/src/config/schema/mod.rsindex 03f4386d2a..0b8344d619 100644--- a/crates/openhuman-core/src/config/schema/mod.rs+++ b/crates/openhuman-core/src/config/schema/mod.rs@@ -61,15 +61,12 @@ pub use claude_agent_sdk::ClaudeAgentSdkConfig;mod local_ai;mod memory;mod modules;-mod node;mod observability;mod privacy;mod proxy;mod routes;mod runtime;mod runtime_local_jail;-mod runtime_pool;-mod runtime_python;mod scheduler_gate;mod task_sources;mod tokenjuice;@@ -104,7 +101,6 @@ pub use memory::{MemorySourceKind, MEMORY_CORTEXDB_KEY_NAME,};pub use modules::{ModuleOverride, ModulesConfig};-pub use node::NodeConfig;pub use observability::{AgentTracingBackend, AgentTracingConfig, ObservabilityConfig};pub use privacy::{PrivacyConfig, PrivacyMode};pub use proxy::{@@ -117,8 +113,6 @@ pub use runtime::{DockerRuntimeConfig, ReliabilityConfig, RuntimeConfig, SchedulerConfig, ShellConfig,};pub use runtime_local_jail::LocalJailConfig;-pub use runtime_pool::{RuntimePoolConfig, RuntimePoolLangConfig};-pub use runtime_python::RuntimePythonConfig;pub use scheduler_gate::{PauseReason, Policy, SchedulerGateConfig, SchedulerGateMode};pub use task_sources::TaskSourcesConfig;pub use tokenjuice::TokenjuiceConfig;diff --git a/crates/openhuman-core/src/config/schema/node.rs b/crates/openhuman-core/src/config/schema/node.rsdeleted file mode 100644index fe945600f3..0000000000--- a/crates/openhuman-core/src/config/schema/node.rs+++ /dev/null@@ -1,59 +0,0 @@-//! Node.js managed runtime configuration.-//!-//! Controls whether the core bootstraps a Node.js toolchain for skills that-//! require `node`/`npm` (e.g. agentskills.io packages with build steps).--use schemars::JsonSchema;-use serde::{Deserialize, Serialize};--#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(default)]-pub struct NodeConfig {- /// Master switch. When `false`, the Node runtime is not resolved and- /// `node_exec` / `npm_exec` tools are not registered. Checked before any- /// bus call, so a disabled runtime costs nothing.- #[serde(default = "default_enabled")]- pub enabled: bool,- /// Target Node.js release line, e.g. `v22.11.0`. Pin to a known LTS for- /// reproducibility.- ///- /// Carried to the `tinyruntime` module on every request; the Node provider- /// there matches on the **major** component, so a host `v22.8.0` satisfies- /// `v22.11.0`. Set `prefer_system = false` for an exact toolchain.- #[serde(default = "default_version")]- pub version: String,- /// Absolute path to a directory where managed Node distributions are- /// installed. Empty string means "use the platform cache directory"- /// (resolved by the `tinyruntime` module, which owns the install).- #[serde(default)]- pub cache_dir: String,- /// When `true` and a system `node` binary is found on `PATH` whose major- /// version matches `version`, reuse it instead of installing a managed- /// toolchain. Disable for reproducible CI / airgapped deployments — that is- /// also how a caller pins an exact version rather than a major line.- #[serde(default = "default_prefer_system")]- pub prefer_system: bool,-}--fn default_enabled() -> bool {- true-}--fn default_version() -> String {- "v22.11.0".to_string()-}--fn default_prefer_system() -> bool {- true-}--impl Default for NodeConfig {- fn default() -> Self {- Self {- enabled: default_enabled(),- version: default_version(),- cache_dir: String::new(),- prefer_system: default_prefer_system(),- }- }-}diff --git a/crates/openhuman-core/src/config/schema/runtime.rs b/crates/openhuman-core/src/config/schema/runtime.rsindex 36aed950b3..527e3ad77a 100644--- a/crates/openhuman-core/src/config/schema/runtime.rs+++ b/crates/openhuman-core/src/config/schema/runtime.rs@@ -51,8 +51,7 @@ pub struct DockerRuntimeConfig {pub allowed_workspace_roots: Vec<String>,}-/// `[shell]` — behaviour of the shell-family tools (`shell`, `node_exec`,-/// `npm_exec`, monitor) when they spawn child processes.+/// `[shell]` — behaviour of the shell-family tools (`shell`, monitor) when they spawn child processes.#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]#[serde(default)]pub struct ShellConfig {diff --git a/crates/openhuman-core/src/config/schema/runtime_pool.rs b/crates/openhuman-core/src/config/schema/runtime_pool.rsdeleted file mode 100644index 7fb7912d28..0000000000--- a/crates/openhuman-core/src/config/schema/runtime_pool.rs+++ /dev/null@@ -1,140 +0,0 @@-//! Shared language-runtime pool configuration (`[runtime_pool]`).-//!-//! Controls the bounded pools of long-lived `node` / `python` worker processes-//! that execute inline code jobs for skill runs and the `node_exec` agent tool-//! instead of forking one interpreter child per execution (issue #5106).-//!-//! ## Why this exists-//!-//! At the opencompany deployment target (100–1000 live agents in a-//! 2 GB / 2 vCPU box) a per-run interpreter child is the single biggest budget-//! breaker: a single JS skill step spawns a `node` child at ~72–75 MB RSS.-//! Sharing a small, bounded pool of warm workers turns "K concurrent skill runs-//! → K interpreters" into "K concurrent skill runs → ~one pooled worker", at-//! the cost of serialising work beyond the pool size (surfaced as queue wait).-//!-//! ## Kill switch-//!-//! `enabled = false` (globally, or per language) reverts callers to the legacy-//! per-call spawn path with **no** behavioural change — the pool is purely an-//! optimisation seam and must always be safe to turn off.--use schemars::JsonSchema;-use serde::{Deserialize, Serialize};--/// `[runtime_pool]` — top-level switch plus per-language pool tuning.-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(default)]-pub struct RuntimePoolConfig {- /// Master switch. When `false`, no pool is started and every caller falls- /// back to spawning a fresh interpreter child per execution (legacy- /// behaviour). Per-language `enabled` flags gate each language on top of- /// this.- #[serde(default = "default_true")]- pub enabled: bool,- /// Node.js worker pool.- #[serde(default)]- pub node: RuntimePoolLangConfig,- /// Python worker pool.- #[serde(default)]- pub python: RuntimePoolLangConfig,-}--/// Per-language pool tuning. Applies identically to the node and python pools.-#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(default)]-pub struct RuntimePoolLangConfig {- /// Whether this language routes through the pool. `None` (unset) means- /// "use the per-language default" — resolved via [`Self::is_enabled`]:- /// **node defaults on** (worker_thread isolation makes reuse safe),- /// **python defaults off** (in-process reuse can leak globals across jobs,- /// so it stays opt-in until stronger isolation lands). `false`/`true`- /// override explicitly.- #[serde(default)]- pub enabled: Option<bool>,- /// Maximum number of concurrently-resident worker processes. Concurrent- /// jobs beyond this bound **queue** rather than fork a new interpreter —- /// this is the whole point of the pool. Clamped to at least 1 at read time.- #[serde(default = "default_max_workers")]- pub max_workers: usize,- /// Idle time-to-live (seconds). A worker that has served no job for this- /// long is reaped so an idle fleet pays zero interpreter RSS. `0` disables- /// idle reaping (workers live until recycled or the process exits).- #[serde(default = "default_idle_ttl_secs")]- pub idle_ttl_secs: u64,- /// Recycle a worker after it has completed this many jobs, bounding- /// state/heap contamination across otherwise-isolated runs. `0` disables- /// job-count recycling.- #[serde(default = "default_recycle_after_jobs")]- pub recycle_after_jobs: u64,- /// Maximum number of jobs allowed to wait in the queue for a free worker- /// before new submissions are rejected with backpressure (rather than- /// growing memory unboundedly). Clamped to at least 1 at read time.- #[serde(default = "default_max_queue_depth")]- pub max_queue_depth: usize,-}--impl RuntimePoolLangConfig {- /// Whether this language routes through the pool, resolving an unset- /// `enabled` to the caller-supplied per-language default (node → `true`,- /// python → `false`). An explicit `enabled = true/false` always wins.- pub fn is_enabled(&self, default: bool) -> bool {- self.enabled.unwrap_or(default)- }-- /// Effective worker count, never zero.- pub fn effective_max_workers(&self) -> usize {- self.max_workers.max(1)- }-- /// Effective queue depth, never zero.- pub fn effective_max_queue_depth(&self) -> usize {- self.max_queue_depth.max(1)- }-}--fn default_true() -> bool {- true-}--fn default_max_workers() -> usize {- 2-}--fn default_idle_ttl_secs() -> u64 {- 60-}--fn default_recycle_after_jobs() -> u64 {- 100-}--fn default_max_queue_depth() -> usize {- 256-}--impl Default for RuntimePoolConfig {- fn default() -> Self {- Self {- enabled: default_true(),- node: RuntimePoolLangConfig::default(),- python: RuntimePoolLangConfig::default(),- }- }-}--impl Default for RuntimePoolLangConfig {- fn default() -> Self {- Self {- enabled: None,- max_workers: default_max_workers(),- idle_ttl_secs: default_idle_ttl_secs(),- recycle_after_jobs: default_recycle_after_jobs(),- max_queue_depth: default_max_queue_depth(),- }- }-}--#[cfg(test)]-#[path = "runtime_pool_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/config/schema/runtime_pool_tests.rs b/crates/openhuman-core/src/config/schema/runtime_pool_tests.rsdeleted file mode 100644index 011c56d8e6..0000000000--- a/crates/openhuman-core/src/config/schema/runtime_pool_tests.rs+++ /dev/null@@ -1,59 +0,0 @@-use super::*;--#[test]-fn defaults_master_on_node_on_python_off() {- let cfg = RuntimePoolConfig::default();- assert!(cfg.enabled, "master switch defaults on");- // Per-language `enabled` is unset by default; node resolves on, python off.- assert_eq!(cfg.node.enabled, None);- assert_eq!(cfg.python.enabled, None);- assert!(cfg.node.is_enabled(true), "node default is on");- assert!(!cfg.python.is_enabled(false), "python default is off");- assert_eq!(cfg.node.max_workers, 2);- assert_eq!(cfg.node.idle_ttl_secs, 60);- assert_eq!(cfg.node.recycle_after_jobs, 100);- assert_eq!(cfg.node.max_queue_depth, 256);-}--#[test]-fn effective_getters_never_zero() {- let cfg = RuntimePoolLangConfig {- enabled: Some(true),- max_workers: 0,- idle_ttl_secs: 0,- recycle_after_jobs: 0,- max_queue_depth: 0,- };- assert_eq!(cfg.effective_max_workers(), 1);- assert_eq!(cfg.effective_max_queue_depth(), 1);-}--#[test]-fn explicit_enabled_overrides_language_default() {- // A partial python table without `enabled` keeps the python-off default.- let cfg: RuntimePoolConfig =- toml::from_str("[python]\nmax_workers = 4\n").expect("partial parses");- assert_eq!(cfg.python.enabled, None);- assert!(- !cfg.python.is_enabled(false),- "python stays off on a partial table"- );- // Explicit opt-in wins.- let on: RuntimePoolConfig =- toml::from_str("[python]\nenabled = true\n").expect("explicit parses");- assert!(- on.python.is_enabled(false),- "explicit enabled=true turns python on"- );-}--#[test]-fn deserializes_partial_toml_with_defaults() {- let cfg: RuntimePoolConfig = toml::from_str("enabled = true\n[node]\nmax_workers = 4\n")- .expect("partial runtime_pool config parses");- assert!(cfg.enabled);- assert_eq!(cfg.node.max_workers, 4);- // Unspecified fields fall back to defaults.- assert_eq!(cfg.node.idle_ttl_secs, 60);- assert_eq!(cfg.python.max_workers, 2);-}diff --git a/crates/openhuman-core/src/config/schema/runtime_python.rs b/crates/openhuman-core/src/config/schema/runtime_python.rsdeleted file mode 100644index f0b3b67f1f..0000000000--- a/crates/openhuman-core/src/config/schema/runtime_python.rs+++ /dev/null@@ -1,81 +0,0 @@-//! Python runtime configuration.-//!-//! Controls how the core resolves a Python 3.12+ interpreter for features-//! that need to launch Python subprocesses such as MCP servers.-//!-//! Product direction: `runtime_python` should eventually own a managed-//! CPython distribution so OpenHuman does not depend on host Python being-//! installed correctly. The system-interpreter probe is a compatibility and-//! developer override path, not the desired long-term contract.--use schemars::JsonSchema;-use serde::{Deserialize, Serialize};--#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]-#[serde(default)]-pub struct RuntimePythonConfig {- /// Master switch. When `false`, the runtime refuses to resolve a Python- /// interpreter and callers must skip Python-backed features entirely.- #[serde(default = "default_enabled")]- pub enabled: bool,- /// Minimum accepted Python version. Interpreters older than this are- /// rejected even when present on `PATH`.- #[serde(default = "default_minimum_version")]- pub minimum_version: String,- /// Exclusive upper bound for the managed-runtime selector. The- /// `python-build-standalone` "latest" release ships every supported series- /// (incl. pre-release lines like 3.15.x betas, whose `bN` suffix the- /// version parser drops — so they look like a stable `3.15.0`). Capping- /// selection below this keeps us on a stable line with prebuilt wheels for- /// dependencies such as torch. Empty string disables the cap. Default- /// `3.14.0` → selects the latest `3.13.x`.- #[serde(default = "default_maximum_version")]- pub maximum_version: String,- /// Absolute path to a directory reserved for future managed Python- /// installs. Empty string means "use the runtime default cache dir".- #[serde(default)]- pub cache_dir: String,- /// Optional upstream release tag for managed standalone Python builds.- /// Empty string means "query the latest release at install time".- #[serde(default)]- pub managed_release_tag: String,- /// When `true`, probe the host `PATH` for a compatible interpreter before- /// attempting any managed-runtime flow. Useful for development; the- /// intended shipped path is a managed interpreter owned by OpenHuman.- #[serde(default = "default_prefer_system")]- pub prefer_system: bool,- /// Optional preferred executable name or absolute path. Examples:- /// `python3.12`, `/opt/homebrew/bin/python3.12`.- #[serde(default)]- pub preferred_command: String,-}--fn default_enabled() -> bool {- true-}--fn default_minimum_version() -> String {- "3.12.0".to_string()-}--fn default_maximum_version() -> String {- "3.14.0".to_string()-}--fn default_prefer_system() -> bool {- false-}--impl Default for RuntimePythonConfig {- fn default() -> Self {- Self {- enabled: default_enabled(),- minimum_version: default_minimum_version(),- maximum_version: default_maximum_version(),- cache_dir: String::new(),- managed_release_tag: String::new(),- prefer_system: default_prefer_system(),- preferred_command: String::new(),- }- }-}diff --git a/crates/openhuman-core/src/config/schema/tokenjuice.rs b/crates/openhuman-core/src/config/schema/tokenjuice.rsindex f690559118..afc5db223d 100644--- a/crates/openhuman-core/src/config/schema/tokenjuice.rs+++ b/crates/openhuman-core/src/config/schema/tokenjuice.rs@@ -66,29 +66,6 @@ pub struct TokenjuiceConfig {/// Enable the HTML→text extractor.#[serde(default = "default_true")]pub html_enabled: bool,-- // --- ML plain-text compressor (Kompress) — opt-in, default OFF ---------- /// Enable the Python/ML plain-text compressor ("Kompress"). Runs as a- /// `kompress` backend of the runtime_python_server (requires- /// `runtime_python.enabled`); degrades gracefully when unavailable.- #[serde(default)]- pub ml_compression_enabled: bool,- /// HuggingFace model id for the ML compressor.- #[serde(default = "default_ml_model_id")]- pub ml_model_id: String,- /// Target compression ratio (0–1) hint for the ML compressor.- #[serde(default = "default_ml_target_ratio")]- pub ml_target_ratio: f64,- /// Idle seconds before the ML sidecar process is reaped to release memory.- #[serde(default = "default_ml_idle_timeout_secs")]- pub ml_sidecar_idle_timeout_secs: u64,- /// Maximum input characters the ML compressor will accept (larger inputs- /// fall back to a native compressor).- #[serde(default = "default_ml_max_input_chars")]- pub ml_max_input_chars: usize,- /// Inference device: `cpu` or `auto`.- #[serde(default = "default_ml_device")]- pub ml_device: String,}fn default_true() -> bool {@@ -106,21 +83,6 @@ fn default_min_bytes() -> usize {fn default_ccr_min_tokens() -> usize {500}-fn default_ml_model_id() -> String {- "answerdotai/ModernBERT-base".to_string()-}-fn default_ml_target_ratio() -> f64 {- 0.5-}-fn default_ml_idle_timeout_secs() -> u64 {- 900-}-fn default_ml_max_input_chars() -> usize {- 200_000-}-fn default_ml_device() -> String {- "cpu".to_string()-}impl Default for TokenjuiceConfig {fn default() -> Self {@@ -138,12 +100,6 @@ impl Default for TokenjuiceConfig {search_enabled: true,code_enabled: true,html_enabled: true,- ml_compression_enabled: false,- ml_model_id: default_ml_model_id(),- ml_target_ratio: default_ml_target_ratio(),- ml_sidecar_idle_timeout_secs: default_ml_idle_timeout_secs(),- ml_max_input_chars: default_ml_max_input_chars(),- ml_device: default_ml_device(),}}}diff --git a/crates/openhuman-core/src/config/schema/tokenjuice_tests.rs b/crates/openhuman-core/src/config/schema/tokenjuice_tests.rsindex 04002fa1f1..bc11e0749f 100644--- a/crates/openhuman-core/src/config/schema/tokenjuice_tests.rs+++ b/crates/openhuman-core/src/config/schema/tokenjuice_tests.rs@@ -10,8 +10,6 @@ fn defaults_are_sane() {assert!(c.repl_handle_enabled);assert!(!c.repl_save_enabled);assert!(c.search_enabled);- assert!(!c.ml_compression_enabled);- assert_eq!(c.ml_device, "cpu");}#[test]@@ -19,14 +17,12 @@ fn parses_from_toml() {let c: TokenjuiceConfig = toml::from_str(r#"router_enabled = false- ml_compression_enabled = truemax_cache_entries = 12ccr_ttl_secs = 300"#,).unwrap();assert!(!c.router_enabled);- assert!(c.ml_compression_enabled);assert_eq!(c.max_cache_entries, 12);assert_eq!(c.ccr_ttl_secs, Some(300));// Untouched fields keep defaults.diff --git a/crates/openhuman-core/src/config/schema/types/config.rs b/crates/openhuman-core/src/config/schema/types/config.rsindex a3844ad03d..c52f93d11d 100644--- a/crates/openhuman-core/src/config/schema/types/config.rs+++ b/crates/openhuman-core/src/config/schema/types/config.rs@@ -411,20 +411,6 @@ pub struct Config {#[serde(default, skip_serializing_if = "Option::is_none")]pub custom_embeddings: Option<CustomEmbeddingsConfig>,- /// Node.js managed runtime configuration (skills that need `node`/`npm`).- #[serde(default)]- pub node: NodeConfig,-- /// Python managed runtime configuration (Python-backed MCP servers and- /// other Python subprocess integrations).- #[serde(default)]- pub runtime_python: RuntimePythonConfig,-- /// Shared language-runtime pool (long-lived `node`/`python` workers reused- /// across skill runs and `node_exec` instead of one child per run, #5106).- #[serde(default)]- pub runtime_pool: RuntimePoolConfig,-/// TokenJuice content-router / compaction configuration.#[serde(default)]pub tokenjuice: TokenjuiceConfig,diff --git a/crates/openhuman-core/src/config/schema/types/config_clone.rs b/crates/openhuman-core/src/config/schema/types/config_clone.rsindex e936118a96..7194a52269 100644--- a/crates/openhuman-core/src/config/schema/types/config_clone.rs+++ b/crates/openhuman-core/src/config/schema/types/config_clone.rs@@ -88,9 +88,6 @@ impl Clone for Config {memory_provider: self.memory_provider.clone(),embeddings_provider: self.embeddings_provider.clone(),custom_embeddings: self.custom_embeddings.clone(),- node: self.node.clone(),- runtime_python: self.runtime_python.clone(),- runtime_pool: self.runtime_pool.clone(),tokenjuice: self.tokenjuice.clone(),hosting: self.hosting.clone(),storage: self.storage.clone(),diff --git a/crates/openhuman-core/src/config/schema/types/defaults.rs b/crates/openhuman-core/src/config/schema/types/defaults.rsindex 6c99ae40ef..fc91bfdc43 100644--- a/crates/openhuman-core/src/config/schema/types/defaults.rs+++ b/crates/openhuman-core/src/config/schema/types/defaults.rs@@ -101,9 +101,6 @@ impl Default for Config {memory_provider: None,embeddings_provider: None,custom_embeddings: None,- node: NodeConfig::default(),- runtime_python: RuntimePythonConfig::default(),- runtime_pool: RuntimePoolConfig::default(),tokenjuice: TokenjuiceConfig::default(),hosting: HostingConfig::default(),storage: StorageConfig::default(),diff --git a/crates/openhuman-core/src/core/all.rs b/crates/openhuman-core/src/core/all.rsindex 6743bfaebf..83266a69e7 100644--- a/crates/openhuman-core/src/core/all.rs+++ b/crates/openhuman-core/src/core/all.rs@@ -549,15 +549,6 @@ fn build_registered_controllers() -> Vec<GroupedController> {DomainGroup::Platform,crate::platform::socket::all_socket_registered_controllers(),);- // Managed Node.js runtime bridge (tool listing + dispatch). Registration-site- // gate: with `runtime-node` off the `javascript.*` namespace is absent from- // `/schema` and unknown-method over `/rpc`, rather than registered+failing.- #[cfg(feature = "runtime-node")]- push(- &mut controllers,- DomainGroup::Runtimes,- crate::runtime::javascript::all_javascript_registered_controllers(),- );// Discovered SKILL.md skills and their bundled resourcespush(&mut controllers,diff --git a/crates/openhuman-core/src/core/all_tests.rs b/crates/openhuman-core/src/core/all_tests.rsindex d9935c5897..725344a11e 100644--- a/crates/openhuman-core/src/core/all_tests.rs+++ b/crates/openhuman-core/src/core/all_tests.rs@@ -1479,36 +1479,6 @@ fn memory_controllers_form_one_contiguous_run_in_aggregator_order() {);}-// ---- runtime-node gate -------------------------------------------------------#[test]-#[cfg(feature = "runtime-node")]-fn javascript_controllers_registered_when_feature_on() {- let ns: Vec<&str> = all_controller_schemas()- .iter()- .map(|s| s.namespace)- .collect();- assert!(- ns.contains(&"javascript"),- "runtime-node ON must register the `javascript` namespace"- );-}--/// The half that proves the gate removes anything: absent, not-/// registered-and-failing.-#[test]-#[cfg(not(feature = "runtime-node"))]-fn javascript_controllers_absent_when_feature_off() {- let ns: Vec<&str> = all_controller_schemas()- .iter()- .map(|s| s.namespace)- .collect();- assert!(- !ns.contains(&"javascript"),- "runtime-node OFF must not register the `javascript` namespace"- );-}-#[path = "all_extensions_tests.rs"]mod extensions_tests;diff --git a/crates/openhuman-core/src/core/domain_group.rs b/crates/openhuman-core/src/core/domain_group.rsindex 43820a4136..c201efa086 100644--- a/crates/openhuman-core/src/core/domain_group.rs+++ b/crates/openhuman-core/src/core/domain_group.rs@@ -71,8 +71,8 @@ pub enum DomainGroup {/// Background initiative: scheduled cron jobs (`cron/`). Pairs with/// `ServiceSet::cron`.Automation,- /// Code-execution substrate: the managed Node/Python runtimes, the worker- /// pool, and the sandbox/CWD-jail confinement (`runtime/`, `sandbox/`).+ /// Code-execution substrate: tool execution and sandbox/CWD-jail confinement+ /// (`tools/`, `sandbox/`).Runtimes,/// Desktop-shell-facing surfaces a headless or embedded host has no use for/// (`desktop/`).diff --git a/crates/openhuman-core/src/core/runtime/features.rs b/crates/openhuman-core/src/core/runtime/features.rsindex 3422c51ca3..6d251952cd 100644--- a/crates/openhuman-core/src/core/runtime/features.rs+++ b/crates/openhuman-core/src/core/runtime/features.rs@@ -15,7 +15,6 @@ pub fn compiled_features() -> std::collections::BTreeMap<String, bool> {("modules", cfg!(feature = "modules")),("voice", cfg!(feature = "voice")),("web3", cfg!(feature = "web3")),- ("runtime-node", cfg!(feature = "runtime-node")),("media", cfg!(feature = "media")),("flows", cfg!(feature = "flows")),("skills", cfg!(feature = "skills")),diff --git a/crates/openhuman-core/src/flows/ops/approval_manifest.rs b/crates/openhuman-core/src/flows/ops/approval_manifest.rsindex 68f6c77667..796e3aae03 100644--- a/crates/openhuman-core/src/flows/ops/approval_manifest.rs+++ b/crates/openhuman-core/src/flows/ops/approval_manifest.rs@@ -124,10 +124,9 @@ pub async fn compute_approval_manifest(config: &Config, graph: &WorkflowGraph) -// error (unknown tool, etc.) degrades conservatively// to Network — over-asking is safe, under-asking// re-introduces the mid-run park this feature removes.- let class = crate::runtime::node::ops::classify_tool_call(- config, &tool_name, &args,- )- .unwrap_or(CommandClass::Network);+ let class =+ crate::tools::native_ops::classify_tool_call(config, &tool_name, &args)+ .unwrap_or(CommandClass::Network);push_gated(&mut entries,&mut seen_tools,diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs b/crates/openhuman-core/src/flows/tinyflows/caps/code.rsindex 8e7587474d..749d74c3c5 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/code.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/code.rs@@ -21,7 +21,7 @@ use crate::security::{CommandClass, SecurityPolicy};/// [`CodeRunner`] adapter running sandboxed user code via/// `crates/openhuman-core/src/sandbox/ops.rs` (`resolve_sandbox_policy` +/// `execute_in_sandbox`), modeled on-/// `crates/openhuman-core/src/tools/impl/system/node_exec.rs::run_sandboxed`.+/// the shell tool sandbox runner.////// **Mismatch handled here:** the sandbox runs a shell command string, not a/// `(language, source, input)` triple. `source` is treated as a function body@@ -31,7 +31,7 @@ use crate::security::{CommandClass, SecurityPolicy};/// (`tinyflows::nodes::integration::code` — e.g. `"source": "return 1;"`).////// Requires `node`/`python3` on the `PATH` the sandbox backend runs under;-/// there is no managed toolchain wiring here (unlike `node_exec`'s+/// there is no managed toolchain wiring here (the same as shell/// `NodeBootstrap`).////// **Phase 2 — autonomy-tier gating:** a `code` node runs arbitrary user code@@ -223,7 +223,7 @@ pub(crate) fn python_harness(source: &str) -> String {}/// POSIX single-quote shell escaping, mirroring-/// `tools/impl/system/node_exec.rs::shell_quote`.+/// the shell quoting helper.pub(crate) fn shell_quote(s: &str) -> String {let escaped = s.replace('\'', "'\\''");format!("'{escaped}'")diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/tools/mod.rs b/crates/openhuman-core/src/flows/tinyflows/caps/tools/mod.rsindex 45364dc991..9174914d81 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/tools/mod.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/tools/mod.rs@@ -38,7 +38,7 @@ pub(crate) use native::NativeToolBackend;/// Prefix marking a `tool_call` node's slug as a NATIVE OpenHuman tool (the/// "Tool" node) rather than a Composio action (the "App action" node). e.g./// `oh:web_search`. Native tools run through the same agent tool registry the-/// assistant uses (`runtime_node::ops::execute_tool`), so a flow can call+/// assistant uses (`tools::native_ops::execute_tool`), so a flow can call/// search / media generation / file / shell / etc. — the full toolset.pub(crate) const NATIVE_TOOL_PREFIX: &str = "oh:";diff --git a/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs b/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rsindex d14d829d7f..26c8a60918 100644--- a/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs+++ b/crates/openhuman-core/src/flows/tinyflows/caps/tools/native.rs@@ -43,7 +43,7 @@ impl ToolBackend for NativeToolBackend {));}- let class = crate::runtime::node::ops::classify_tool_call(ctx.config, tool_name, &args)+ let class = crate::tools::native_ops::classify_tool_call(ctx.config, tool_name, &args).map_err(EngineError::Capability)?;let tier_decision = super::super::enforce_node_tier_gate(ctx.security, class, "tool_call")?;let summary = crate::security::approval::summarize_action(tool_name, &args);@@ -61,7 +61,7 @@ impl ToolBackend for NativeToolBackend {"[flows] tool_call: dispatching NATIVE OpenHuman tool");let exec_result =- crate::runtime::node::ops::execute_tool(ctx.config, tool_name, args, false)+ crate::tools::native_ops::execute_tool(ctx.config, tool_name, args, false).await.map_err(EngineError::Capability).and_then(|outcome| {diff --git a/crates/openhuman-core/src/hooks/README.md b/crates/openhuman-core/src/hooks/README.mdindex 15cc897871..ee5469e969 100644--- a/crates/openhuman-core/src/hooks/README.md+++ b/crates/openhuman-core/src/hooks/README.md@@ -116,7 +116,7 @@ them:| Tool family | Names | Pre event | Post event || --- | --- | --- | --- |-| `SHELL_TOOLS` | `shell`, `run_command`, `bash`, `node_exec`, `npm_exec` | `beforeShellExecution` | `afterShellExecution` |+| `SHELL_TOOLS` | `shell`, `run_command`, `bash` | `beforeShellExecution` | `afterShellExecution` || `READ_TOOLS` | `file_read`, `read_diff` | `beforeReadFile` | none || `WRITE_TOOLS` | `file_write`, `edit`, `apply_patch`, `update_memory_md` | none | `afterFileEdit` || MCP | names starting `mcp_`, `mcp:` or `mcp__` | `beforeMCPExecution` | `afterMCPExecution` |diff --git a/crates/openhuman-core/src/hooks/bridge.rs b/crates/openhuman-core/src/hooks/bridge.rsindex 30565b5861..9f72f2dbf3 100644--- a/crates/openhuman-core/src/hooks/bridge.rs+++ b/crates/openhuman-core/src/hooks/bridge.rs@@ -41,7 +41,7 @@ use tinyagents_runtime::command_hooks::types::{pub const BRIDGE_HOOK_NAME: &str = "configured_hooks";/// Tools whose calls are also reported as shell execution.-const SHELL_TOOLS: &[&str] = &["shell", "run_command", "bash", "node_exec", "npm_exec"];+const SHELL_TOOLS: &[&str] = &["shell", "run_command", "bash"];/// Tools whose calls are also reported as a file read.const READ_TOOLS: &[&str] = &["file_read", "read_diff"];diff --git a/crates/openhuman-core/src/inference/tokenjuice/README.md b/crates/openhuman-core/src/inference/tokenjuice/README.mdindex b0ec0ab209..28efb3728d 100644--- a/crates/openhuman-core/src/inference/tokenjuice/README.md+++ b/crates/openhuman-core/src/inference/tokenjuice/README.md@@ -23,7 +23,7 @@ OpenHuman-owned files:| [`config_patch.rs`](./config_patch.rs) | Partial update shape for the `[tokenjuice]` config block. || [`repl_tools.rs`](./repl_tools.rs) | The three REPL tools (`juice_find`, `juice_extract`, `juice_summarize`) over a stored result. TinyJuice owns the ops and declarations (`tinyjuice::repl::tools`, cargo feature `tinytools`); the CCR store lives in the module, so each call fetches the original with `Retrieve` and hands the stock tool a one-entry store. Registered by [`tools/ops.rs`](../../tools/ops.rs) only while `repl_handle_active(config)`. || [`tools.rs`](./tools.rs) | OpenHuman agent tool implementation for the retrieve tool (`RETRIEVE_TOOL_NAME = "juice_retrieve"`; `"tokenjuice_retrieve"` is a recognized recovery-tool alias, not the tool's registered name, see `RECOVERY_TOOL_NAMES`). |-| `ml/` | Bridge from TinyJuice's optional ML callback into the shared `runtime::python_server` Kompress backend (ModernBERT token/sentence salience); opt-in via `config.tokenjuice.ml_compression_enabled` (default off), degrades gracefully when the flag is off or the runtime server is unavailable. |+| Plain text | Compressed with TinyJuice's deterministic TextCrusher. || [`savings.rs`](./savings.rs) | OpenHuman model-pricing attribution and persisted dashboard stats. |TinyJuice-owned engine pieces:@@ -31,7 +31,7 @@ TinyJuice-owned engine pieces:| TinyJuice repository path | Role || --- | --- || `src/compress.rs` | Content router entry point. |-| `src/compressors/` | JSON, code, log, search, diff, HTML, ML slot, and generic compressors. |+| `src/compressors/` | JSON, code, log, search, diff, HTML, plain-text, and generic compressors. || `src/cache/` | CCR store, retrieval markers, disk tier, ranged retrieval helpers. || `src/rules/` | Rule loader/compiler and embedded rule table. || `src/vendor/rules/*.json` | Vendored upstream rule JSON files. |@@ -59,7 +59,7 @@ Everything with state stays where it was, reached only through TinyBus:| --- | --- || `compress::route` / `compress_content` | Picks a compressor from the rule engine and records savings. || `cache/`: the CCR store, retrieval markers, disk tier, ranged retrieval | Owns a disk tier and a marker vocabulary (`⟦tj:<hash>⟧`) the module must resolve. `juice_retrieve` is the model-facing half and is unchanged. |-| `rules/`, `reduce/`, `ml/` | Rule tables, execution reduction, the ModernBERT callback. |+| `rules/`, `reduce/` | Rule tables and execution reduction. |Why a content transform is not allowed to go through the bus: reaching it thereneeds the `modules` feature, a loaded cdylib, and `config.tokenjuice` /@@ -75,8 +75,7 @@ unterminated quotes. A host-side rewrite was prototyped and thrown away infavour of extending `html_to_markdown` upstream.Anything beyond a pure transform still belongs behind the boundary: runtime-services, settings persistence, JSON-RPC, tools, pricing, and the optional ML-callback stay here.+services, settings persistence, JSON-RPC, tools, and pricing stay here.## Wiringdiff --git a/crates/openhuman-core/src/inference/tokenjuice/config_patch.rs b/crates/openhuman-core/src/inference/tokenjuice/config_patch.rsindex b4eab9667d..8ddfc15449 100644--- a/crates/openhuman-core/src/inference/tokenjuice/config_patch.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/config_patch.rs@@ -25,12 +25,6 @@ pub struct TokenjuiceSettingsPatch {pub search_enabled: Option<bool>,pub code_enabled: Option<bool>,pub html_enabled: Option<bool>,- pub ml_compression_enabled: Option<bool>,- pub ml_model_id: Option<String>,- pub ml_target_ratio: Option<f64>,- pub ml_sidecar_idle_timeout_secs: Option<u64>,- pub ml_max_input_chars: Option<usize>,- pub ml_device: Option<String>,}impl TokenjuiceSettingsPatch {@@ -75,30 +69,6 @@ impl TokenjuiceSettingsPatch {if let Some(v) = self.html_enabled {cfg.html_enabled = v;}- if let Some(v) = self.ml_compression_enabled {- cfg.ml_compression_enabled = v;- }- if let Some(v) = &self.ml_model_id {- if !v.trim().is_empty() {- cfg.ml_model_id = v.clone();- }- }- if let Some(v) = self.ml_target_ratio {- if (0.0..=1.0).contains(&v) {- cfg.ml_target_ratio = v;- }- }- if let Some(v) = self.ml_sidecar_idle_timeout_secs {- cfg.ml_sidecar_idle_timeout_secs = v;- }- if let Some(v) = self.ml_max_input_chars {- cfg.ml_max_input_chars = v;- }- if let Some(v) = &self.ml_device {- if !v.trim().is_empty() {- cfg.ml_device = v.clone();- }- }}}diff --git a/crates/openhuman-core/src/inference/tokenjuice/ml/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/ml/mod.rsdeleted file mode 100644index 073ef95376..0000000000--- a/crates/openhuman-core/src/inference/tokenjuice/ml/mod.rs+++ /dev/null@@ -1,70 +0,0 @@-//! TokenJuice ML plain-text compressor ("Kompress").-//!-//! Plain text has no structural skeleton to exploit, so high-quality-//! compression needs a learned model (ModernBERT token/sentence salience). That-//! runs inside the shared [`crate::runtime::python_server`] as the-//! `kompress` backend — this module is just the thin Rust callback the-//! TinyJuice `ml_text` compressor calls.-//!-//! Opt-in at runtime via `config.tokenjuice.ml_compression_enabled` (default-//! off) — there is no build-time feature gate, since torch is provisioned at-//! runtime (pip), never linked. Degrades gracefully (`Ok(None)` / `Err`) when-//! the flag is off, the runtime python server is unavailable, or the input is-//! too large — the agent loop never fails because ML compression is missing.--use std::sync::{OnceLock, RwLock};--use anyhow::Result;--use crate::config::Config;-use crate::inference::tokenjuice::types::CompressOptions;--/// Global config snapshot the Kompress backend runs against. Held behind a-/// `RwLock` (not a `OnceLock`) so a live settings update — e.g. toggling-/// `ml_compression_enabled` on from Settings — is picked up without a restart.-fn config_cell() -> &'static RwLock<Option<Config>> {- static CONFIG: OnceLock<RwLock<Option<Config>>> = OnceLock::new();- CONFIG.get_or_init(|| RwLock::new(None))-}--/// Install (or replace) the config snapshot. Called at startup and on every-/// `tokenjuice.settings_update` so the runtime sees current values.-pub fn configure(config: Config) {- *config_cell().write().unwrap_or_else(|p| p.into_inner()) = Some(config);-}--/// Compress `text` via the Kompress backend of the runtime python server.-///-/// Returns `Ok(Some(compacted))` on a useful result, `Ok(None)` when the flag-/// is off / input too large / output wouldn't help, and `Err` when the backend-/// is unavailable (caller degrades to a native compressor).-pub async fn compress(text: &str, _opts: &CompressOptions) -> Result<Option<String>> {- // Snapshot the current config under the read lock (live-updated by- // `configure` on settings changes), then release it before the await.- let config = {- let guard = config_cell().read().unwrap_or_else(|p| p.into_inner());- match guard.as_ref() {- Some(c) => c.clone(),- None => anyhow::bail!("tokenjuice ml not configured"),- }- };- let tj = &config.tokenjuice;- if !tj.ml_compression_enabled {- return Ok(None);- }- if text.len() > tj.ml_max_input_chars {- // Too large for the model — let a native compressor handle it.- return Ok(None);- }-- let resp = crate::runtime::python_server::request_kompress(&config, text).await?;- if resp.compressed_text.is_empty() || resp.compressed_text.len() >= text.len() {- return Ok(None);- }- log::debug!(- "[tokenjuice::ml] kompress {} -> {} chars",- resp.input_chars,- resp.output_chars- );- Ok(Some(resp.compressed_text))-}diff --git a/crates/openhuman-core/src/inference/tokenjuice/mod.rs b/crates/openhuman-core/src/inference/tokenjuice/mod.rsindex a006b91137..c0154be12a 100644--- a/crates/openhuman-core/src/inference/tokenjuice/mod.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/mod.rs@@ -2,7 +2,6 @@pub mod config_patch;pub use tinyjuice::host::{focus, generate};-pub mod ml;pub mod repl_tools;pub mod savings;pub mod schemas;@@ -93,7 +92,6 @@ pub(crate) fn install_request(config: &crate::config::Config) -> InstallRequestsearch_enabled: tj.search_enabled,code_enabled: tj.code_enabled,html_enabled: tj.html_enabled,- ml_text_enabled: tj.ml_compression_enabled,min_bytes_to_compress: tj.min_bytes_to_compress,ccr_min_tokens: tj.ccr_min_tokens,// The summary stage still needs a context token per call, which@@ -122,7 +120,6 @@ pub(crate) fn install_request(config: &crate::config::Config) -> InstallRequest}pub async fn install_from_config(config: &crate::config::Config) -> Result<(), String> {- ml::configure(config.clone());savings::configure(config.default_modeldiff --git a/crates/openhuman-core/src/inference/tokenjuice/schemas.rs b/crates/openhuman-core/src/inference/tokenjuice/schemas.rsindex 47fe95548e..46333c5d2a 100644--- a/crates/openhuman-core/src/inference/tokenjuice/schemas.rs+++ b/crates/openhuman-core/src/inference/tokenjuice/schemas.rs@@ -201,7 +201,7 @@ pub fn schemas(function: &str) -> ControllerSchema {outputs: vec![FieldSchema {name: "settings",ty: TypeSchema::Json,- comment: "The tokenjuice config (router/CCR/compressor toggles + ML fields).",+ comment: "The tokenjuice config (router/CCR/compressor toggles).",required: true,}],},diff --git a/crates/openhuman-core/src/lib.rs b/crates/openhuman-core/src/lib.rsindex 3a3abf1159..b73e9e9d44 100644--- a/crates/openhuman-core/src/lib.rs+++ b/crates/openhuman-core/src/lib.rs@@ -75,7 +75,6 @@ pub mod memory;pub mod modules;pub mod platform;pub mod profiles;-pub mod runtime;pub mod sandbox;pub mod search;pub mod security;diff --git a/crates/openhuman-core/src/modules/README.md b/crates/openhuman-core/src/modules/README.mdindex d752358560..a505181fb4 100644--- a/crates/openhuman-core/src/modules/README.md+++ b/crates/openhuman-core/src/modules/README.md@@ -3,8 +3,7 @@This folder is the host for loadable native modules. A module is a first-party`cdylib` that speaks the tinybus module ABI and ships separately from the corebinary: `tinycomputer`, `tinysearch`, `tinydocs`, `tinywallet`, `tinyjuice`,-`tinyvoice`, `tinyruntime` (with its `tinyruntime-nodejs` and-`tinyruntime-python` providers), `tinymcp`, `tinyconnectors`, `tinybox`,+`tinyvoice`, `tinymcp`, `tinyconnectors`, `tinybox`,`tinychannels` and `tinyhosts`. The core downloads a module from a pinnedGitHub release, checks it against a digest compiled into this crate, letstinybus admit it, attaches it to a private in-process broker, and then calls@@ -214,7 +213,6 @@ download, its `dlopen`, or its resident memory.| [`documents.rs`](documents.rs) | `tinydocs` | `generate_docx`, `generate_pptx`, `extract_text`, `extract_document`, `render_pdf`. Inbound bytes ride a tinybus stream; produced documents are held by the module and pulled with `ReadOutput`, then released. Feature `documents`. || [`wallet.rs`](wallet.rs) | `tinywallet` | `derive_account`, `sign_transaction_in_module`, `sign_message`, `export_key`. Key material goes only to an attested module whose attested digest is one the registry pinned (`attested_proxy`). Feature `web3`. || [`voice.rs`](voice.rs) | `tinyvoice` | Intent routing, command extraction, wake-word and hallucination checks, capture preparation, WAV encoding, frame energies, and a `VadSession` driven from the always-on capture loop. Every call returns a `VoiceCallError` the caller falls back from. Feature `voice`. |-| [`runtime.rs`](runtime.rs) | `tinyruntime` + providers | `ensure_language` loads the router and the language provider, then `resolve`, `execute`, `languages`, `pool_stats`. Settings (`settings_for`, `pool_settings_for`) are read from config on every call. || [`desktop.rs`](desktop.rs) | `tinycomputer` | The shared proxy for TinyComputer: loads it with an 8 second bound, reinitializes it when its configuration fingerprint changes, and exposes `call`, `permissions`, `state`, `jev_ready`. || [`computer_config.rs`](computer_config.rs) | `tinycomputer` | The private configuration: `jev` (decision model), `planner` (planner, rescue and output models), `browser` (Chrome path), `trace_path`. Rebuilt from `[computer]` and stored credentials on every call; `OPENHUMAN_COMPUTER_TRACE` turns tracing on. || [`computer.rs`](computer.rs) | `tinycomputer` | `status` for the Computer settings page: lifecycle state, configured routes, and optionally what the module reports through `Describe`. |@@ -225,7 +223,7 @@ download, its `dlopen`, or its resident memory.| [`connectors.rs`](connectors.rs) | `tinyconnectors` | `proxy`, `call`, `call_stateless`, `call_bare`, `reconcile_route_if_loaded`. Builds the route configuration (signed-in backend or the user's own Composio key) and reconciles it on every call so sign-out reaches the module. || [`search/mod.rs`](search/mod.rs) | `tinysearch` | `module_config` from the host's resolved search policy, and `configured_tool_specs` computed synchronously from that same configuration. || [`search/proxy.rs`](search/proxy.rs) | `tinysearch` | Lazy load, private reinitialization on configuration change, and serialized `list_tools` / `execute_tool`; `refresh_loaded` after settings saves and credential changes. |-| [`tokenjuice_host.rs`](tokenjuice_host.rs) | `tinyjuice` | The reverse direction: an `MlHost` object the host serves at the contract's `ML_HOST_NAME` / `ML_HOST_PATH`, so the module can call the host's ML compressor and one tool-less model call for its summary stage. |+| [`tokenjuice_host.rs`](tokenjuice_host.rs) | `tinyjuice` | The reverse direction: an `MlHost` object the host serves at the contract's `ML_HOST_NAME` / `ML_HOST_PATH` for the module's tool-less summary model call. |`tinymcp`, `tinybox`, `tinychannels` and `tinyhosts` have registry records butno host file in this folder.@@ -293,7 +291,7 @@ loadable:cache-path helpers (`prune_stale_versions` and friends) belong to tinybus(`vendor/tinybus`). Change them there.- Each module's behavior lives in its own repository under `vendor/`- (`tinydocs`, `tinywallet`, `tinyvoice`, `tinyruntime`, `tinycomputer`,+ (`tinydocs`, `tinywallet`, `tinyvoice`, `tinycomputer`,`tinysearch`, `tinyconnectors`, `tinyjuice`, `tinymcp`, `tinybox`,`tinychannels`, `tinyhosts`). This folder holds only the host half of eachcall and the host's policy around it.@@ -305,7 +303,6 @@ loadable:| `tinydocs-bus` | `documents` || `tinyvoice-bus` | `voice` || `tinyjuice-bus` | inference kernel |- | `tinyruntime-bus` | runtime clients || `tinywallet-bus` | `web3` (the chain primitives are in `tinywallet-crypto`) || `tinymcp-bus` | `mcp` || `tinysearch-bus` | search provider declarations and bus payloads |diff --git a/crates/openhuman-core/src/modules/mod.rs b/crates/openhuman-core/src/modules/mod.rsindex 62b4d6369f..f6684236c4 100644--- a/crates/openhuman-core/src/modules/mod.rs+++ b/crates/openhuman-core/src/modules/mod.rs@@ -35,8 +35,6 @@//! assembles transactions while the signing key stays in this process.//! - [`host`] — the module broker, connection and loader.//! - [`ops`] — resolving, loading, and reporting status.-//! - [`runtime`] — calling `tinyruntime`: resolving a language runtime and-//! running code on it.//! - [`schemas`] — the `modules` RPC surface.//! - [`boot`] — what happens at startup.@@ -54,7 +52,6 @@ pub mod documents;pub mod host;pub mod ops;pub mod registry;-pub mod runtime;pub mod schemas;pub mod search;mod tokenjuice_host;diff --git a/crates/openhuman-core/src/modules/ops.rs b/crates/openhuman-core/src/modules/ops.rsindex 04b68c9c08..223d4965d8 100644--- a/crates/openhuman-core/src/modules/ops.rs+++ b/crates/openhuman-core/src/modules/ops.rs@@ -468,7 +468,7 @@ fn local_override(config: &Config, id: &str) -> Option<PathBuf> {/// Where downloaded artifacts are kept.////// The user cache directory, falling back to the workspace when there is none —-/// the same shape the Node and Python runtime installers use, for the same+/// the same shape used by other module asset installers, for the same/// reason: a headless container often has no `XDG_CACHE_HOME`, and failing to/// install because of that would be worse than writing beside the workspace.#[must_use]diff --git a/crates/openhuman-core/src/modules/registry.rs b/crates/openhuman-core/src/modules/registry.rsindex 9725429757..c3b4f4e023 100644--- a/crates/openhuman-core/src/modules/registry.rs+++ b/crates/openhuman-core/src/modules/registry.rs@@ -39,7 +39,6 @@ mod records_docs_wallet;mod records_extra;mod records_mcp_connectors;mod records_memory_juice;-mod records_runtime;mod records_search;mod records_voice;@@ -49,7 +48,6 @@ use records_docs_wallet::{TINYDOCS, TINYWALLET};use records_extra::{TINYBOX, TINYCHANNELS, TINYHOSTS};use records_mcp_connectors::{TINYCONNECTORS, TINYMCP};use records_memory_juice::TINYJUICE;-use records_runtime::{TINYRUNTIME, TINYRUNTIME_NODEJS, TINYRUNTIME_PYTHON};use records_search::TINYSEARCH;use records_voice::TINYVOICE;@@ -61,9 +59,6 @@ pub const ALL: &[ModuleRecord] = &[TINYWALLET,TINYJUICE,TINYVOICE,- TINYRUNTIME,- TINYRUNTIME_NODEJS,- TINYRUNTIME_PYTHON,TINYMCP,TINYCONNECTORS,TINYBOX,diff --git a/crates/openhuman-core/src/modules/registry/README.md b/crates/openhuman-core/src/modules/registry/README.mdindex 64e990135b..25758ce130 100644--- a/crates/openhuman-core/src/modules/registry/README.md+++ b/crates/openhuman-core/src/modules/registry/README.md@@ -23,7 +23,6 @@ values for a family of related modules:- [`records_extra.rs`](./records_extra.rs): `TINYBOX`, `TINYCHANNELS`, `TINYHOSTS`.- [`records_mcp_connectors.rs`](./records_mcp_connectors.rs): `TINYCONNECTORS`, `TINYMCP`.- `records_juice.rs`: `TINYJUICE`.-- [`records_runtime.rs`](./records_runtime.rs): `TINYRUNTIME`, `TINYRUNTIME_NODEJS`, `TINYRUNTIME_PYTHON`.- [`records_search.rs`](./records_search.rs): `TINYSEARCH`.- [`records_voice.rs`](./records_voice.rs): `TINYVOICE`.diff --git a/crates/openhuman-core/src/modules/registry/records_runtime.rs b/crates/openhuman-core/src/modules/registry/records_runtime.rsdeleted file mode 100644index 57c73e6787..0000000000--- a/crates/openhuman-core/src/modules/registry/records_runtime.rs+++ /dev/null@@ -1,240 +0,0 @@-//! Registry records for the `tinyruntime` router and its Node.js and Python-//! sidecars.--use crate::modules::types::{LoadPolicy, ModuleRecord, PlatformAsset};--/// The `tinyruntime` module: the runtime router.-///-/// Resolves a language runtime, installs one when the host has none, reuses one-/// when it does, and runs code on a bounded pool of warm interpreter processes.-/// It is a router: on its own it knows no languages, and it routes to the two-/// provider records below.-///-/// Lazy, because a host that never runs a skill, a flow step, or a `node_exec`-/// should not pay a download and a `dlopen` for the ability to.-///-/// The digests below are v0.2.12's, taken verbatim from that release's-/// `checksum.toml`. Until it existed this record carried no assets at all and-/// the module was reachable only from a developer build named by-/// `modules.local` or found on `OPENHUMAN_MODULE_PATH` — so on any machine that-/// had not built it, the runtime domain was a set of tools that could not run.-pub(crate) const TINYRUNTIME: ModuleRecord = ModuleRecord {- id: "tinyruntime",- description: "Language runtime resolution, installation, and pooled execution",- bus_name: "ai.tinyhumans.runtime.Runtime",- object_path: "/ai/tinyhumans/runtime/Runtime",- version: "0.2.12",- release_url: "https://github.com/tinyhumansai/tinyruntime/releases/tag/v0.2.12",- assets: &[- PlatformAsset {- host_key: "ubuntu-24.04-x86_64",- archive: "tinyruntime-0.2.12-ubuntu-24.04-x86_64.tar.gz",- sha256: "5df89d2e8f10602e392e1d2fa0d8d463822a1db1362b9efc19c76ae8fd35da15",- },- PlatformAsset {- host_key: "ubuntu-24.04-arm64",- archive: "tinyruntime-0.2.12-ubuntu-24.04-arm64.tar.gz",- sha256: "c631f2825a7b1fe3e2395581022e8f134b01aa48a7ef1d3b5f39226107651a5a",- },- PlatformAsset {- host_key: "ubuntu-22.04-x86_64",- archive: "tinyruntime-0.2.12-ubuntu-22.04-x86_64.tar.gz",- sha256: "c8434e10cb0fec5e04dc52a4245fd0bbce31a33fc45ecc52931b610873000347",- },- PlatformAsset {- host_key: "ubuntu-22.04-arm64",- archive: "tinyruntime-0.2.12-ubuntu-22.04-arm64.tar.gz",- sha256: "51423639e15d88872fb30cfc47bf3ea6a7820be701bba4d74c8d5989baeff451",- },- PlatformAsset {- host_key: "macos-26-arm64",- archive: "tinyruntime-0.2.12-macos-26-arm64.tar.gz",- sha256: "efa190b4ae736fa53b6df8afc77e94f0dff187d17cf98c8e3bfa0b1f935dac38",- },- PlatformAsset {- host_key: "macos-26-x86_64",- archive: "tinyruntime-0.2.12-macos-26-x86_64.tar.gz",- sha256: "dab8eb686c22a2af8607b0d92e4d8eafdc6badc50cce39a97c56738dd9d8b2b6",- },- PlatformAsset {- host_key: "macos-15-arm64",- archive: "tinyruntime-0.2.12-macos-15-arm64.tar.gz",- sha256: "e656ea5a6ba73d548339df13815ee869259b94762d3963e824431578779b0023",- },- PlatformAsset {- host_key: "macos-15-x86_64",- archive: "tinyruntime-0.2.12-macos-15-x86_64.tar.gz",- sha256: "96f6f31afe3896a333d33c650c9bbf89e615af01c0143b81c85dc911b393be43",- },- PlatformAsset {- host_key: "windows-2025-x86_64",- archive: "tinyruntime-0.2.12-windows-2025-x86_64.zip",- sha256: "87da4cb46edd0acdcea9795d0b357087032924661d459362704dafb612a7a5d4",- },- PlatformAsset {- host_key: "windows-2022-x86_64",- archive: "tinyruntime-0.2.12-windows-2022-x86_64.zip",- sha256: "8779766c73bb3050094d226c4019df124b7516a35fb3dc7eaee2d2011d9ec29b",- },- PlatformAsset {- host_key: "windows-11-arm64",- archive: "tinyruntime-0.2.12-windows-11-arm64.zip",- sha256: "977e5632f98383348b309fa6ee3cc6069f5b2b9dc90585b1c43b5ce0d120bf17",- },- ],- load: LoadPolicy::Lazy,-};--/// The `tinyruntime-nodejs` module: the Node.js half of the router's knowledge.-///-/// Answers which host interpreters count, which archive nodejs.org publishes for-/// this machine, where the binaries land, and what a warm Node worker is. It-/// installs nothing itself.-///-/// It implements the shared `ai.tinyhumans.runtime.Provider` interface but-/// serves at its own object path, because two modules cannot claim one bus name-/// and tinybus derives the path from the name.-///-/// Lazy, and loaded by the same call that loads the router: a language is only-/// worth its `dlopen` when something asks for that language.-///-/// Released from its own repository (own version line) against the router's source pin; see scripts/ci/module-provider-pins.json.-pub(crate) const TINYRUNTIME_NODEJS: ModuleRecord = ModuleRecord {- id: "tinyruntime-nodejs",- description: "Node.js runtime provider for tinyruntime",- bus_name: "ai.tinyhumans.runtime.nodejs.Provider",- object_path: "/ai/tinyhumans/runtime/nodejs/Provider",- version: "0.2.7",- release_url: "https://github.com/tinyhumansai/tinyruntime-nodejs/releases/tag/v0.2.7",- assets: &[- PlatformAsset {- host_key: "ubuntu-24.04-x86_64",- archive: "tinyruntime-nodejs-0.2.7-ubuntu-24.04-x86_64.tar.gz",- sha256: "bea90f1ed91793a3e06f3e7b92c751292cc00ffdbf7e6886fc4fa2334e6ef97f",- },- PlatformAsset {- host_key: "ubuntu-24.04-arm64",- archive: "tinyruntime-nodejs-0.2.7-ubuntu-24.04-arm64.tar.gz",- sha256: "8f3f99a9678c784ae8568a6991c2bf6ab0df90b571565299a674a53f489998e2",- },- PlatformAsset {- host_key: "ubuntu-22.04-x86_64",- archive: "tinyruntime-nodejs-0.2.7-ubuntu-22.04-x86_64.tar.gz",- sha256: "c6eebb7bb20dbaca76de4628e442ca112fdab22e5b0d71eeb472bc380852cb88",- },- PlatformAsset {- host_key: "ubuntu-22.04-arm64",- archive: "tinyruntime-nodejs-0.2.7-ubuntu-22.04-arm64.tar.gz",- sha256: "2bf39279700ffaaf740359abb47f219de004a5c7e0131df4fcd64f9913c6d0b8",- },- PlatformAsset {- host_key: "macos-26-arm64",- archive: "tinyruntime-nodejs-0.2.7-macos-26-arm64.tar.gz",- sha256: "3b3b8f9cd5baa04d67bf1c57841c389697e0e617fffb875b1394ec8ebbf902ac",- },- PlatformAsset {- host_key: "macos-26-x86_64",- archive: "tinyruntime-nodejs-0.2.7-macos-26-x86_64.tar.gz",- sha256: "61f0d503fee8bd9004b3dd879ce058e888fe1c6702e90ad98e8bc61795fdeb79",- },- PlatformAsset {- host_key: "macos-15-arm64",- archive: "tinyruntime-nodejs-0.2.7-macos-15-arm64.tar.gz",- sha256: "0a3c6883c96f50905ad43e624b5fc36248e3fb1b9cb2a03739da75b11260cb96",- },- PlatformAsset {- host_key: "macos-15-x86_64",- archive: "tinyruntime-nodejs-0.2.7-macos-15-x86_64.tar.gz",- sha256: "0a7240fc04b8b2c34b4bceba9fdd37ee33a76c1456ecc8a087b3b6077a2ec8c2",- },- PlatformAsset {- host_key: "windows-2025-x86_64",- archive: "tinyruntime-nodejs-0.2.7-windows-2025-x86_64.zip",- sha256: "6cda4d0d039b0ee15e1dc1b9bf2f742ac106c5164ceaeccb6d3bb662a729649d",- },- PlatformAsset {- host_key: "windows-2022-x86_64",- archive: "tinyruntime-nodejs-0.2.7-windows-2022-x86_64.zip",- sha256: "033406fe1609cf4161234b0d51257f457f5ba88944aa2f6d2fcd3114b263403d",- },- PlatformAsset {- host_key: "windows-11-arm64",- archive: "tinyruntime-nodejs-0.2.7-windows-11-arm64.zip",- sha256: "d15b41caad14346635cdbdd3b0b7777e854e874a22b4bcbc982032e03c5a3665",- },- ],- load: LoadPolicy::Lazy,-};--/// The `tinyruntime-python` module: the Python half of the router's knowledge.-///-/// Answers which host interpreters count, which standalone build to install, and-/// what a warm Python worker is. It installs nothing itself.-///-/// Released from its own repository (own version line) against the router's source pin; see scripts/ci/module-provider-pins.json.-pub(crate) const TINYRUNTIME_PYTHON: ModuleRecord = ModuleRecord {- id: "tinyruntime-python",- description: "Python runtime provider for tinyruntime",- bus_name: "ai.tinyhumans.runtime.python.Provider",- object_path: "/ai/tinyhumans/runtime/python/Provider",- version: "0.2.7",- release_url: "https://github.com/tinyhumansai/tinyruntime-python/releases/tag/v0.2.7",- assets: &[- PlatformAsset {- host_key: "ubuntu-24.04-x86_64",- archive: "tinyruntime-python-0.2.7-ubuntu-24.04-x86_64.tar.gz",- sha256: "ad1b0b25dea5cbb80e474a5fe9deaed47d8b2f31a1430f3ac00f71e20429ae74",- },- PlatformAsset {- host_key: "ubuntu-24.04-arm64",- archive: "tinyruntime-python-0.2.7-ubuntu-24.04-arm64.tar.gz",- sha256: "dd234eb5b229b7fec8fc7869036e109afd245b75cc52e34ae1ae32031a73976a",- },- PlatformAsset {- host_key: "ubuntu-22.04-x86_64",- archive: "tinyruntime-python-0.2.7-ubuntu-22.04-x86_64.tar.gz",- sha256: "009b3e7cd1e845ee9733de73083f64b5920aacf3f494510176b4998e1b031905",- },- PlatformAsset {- host_key: "ubuntu-22.04-arm64",- archive: "tinyruntime-python-0.2.7-ubuntu-22.04-arm64.tar.gz",- sha256: "1be35fafc0580869fdc136255c800325029a205b13a47259332c9a1e4962f663",- },- PlatformAsset {- host_key: "macos-26-arm64",- archive: "tinyruntime-python-0.2.7-macos-26-arm64.tar.gz",- sha256: "def3cc6aaa71fa39de02372f6f67cc550f19fd8fbc6dc9e1df38ffa1bd3dfbc5",- },- PlatformAsset {- host_key: "macos-26-x86_64",- archive: "tinyruntime-python-0.2.7-macos-26-x86_64.tar.gz",- sha256: "81ede9fab71c955bb46a0d1ce005b24763bb3eb38f5d9acb2df3cc9889a3bd60",- },- PlatformAsset {- host_key: "macos-15-arm64",- archive: "tinyruntime-python-0.2.7-macos-15-arm64.tar.gz",- sha256: "737cf83fb461862c07cfac99c092a27ccfa245dc3a968a7af2f2ce8d94f4473d",- },- PlatformAsset {- host_key: "macos-15-x86_64",- archive: "tinyruntime-python-0.2.7-macos-15-x86_64.tar.gz",- sha256: "f37bd1485d18bb9ba9545a402b13314a30265803ae58006b0bbaec040becabc7",- },- PlatformAsset {- host_key: "windows-2025-x86_64",- archive: "tinyruntime-python-0.2.7-windows-2025-x86_64.zip",- sha256: "d449fe10eda0249815196a46d9055d102bed96ead9ef4659b3ef7c6063651a68",- },- PlatformAsset {- host_key: "windows-2022-x86_64",- archive: "tinyruntime-python-0.2.7-windows-2022-x86_64.zip",- sha256: "15c338b8960fed83dcd94a3d0f2aadfa6faa6064938d79a7b659eda7c4e3e4a5",- },- PlatformAsset {- host_key: "windows-11-arm64",- archive: "tinyruntime-python-0.2.7-windows-11-arm64.zip",- sha256: "27d9dc021a03990a20648345c232becb1d2b48f361b00a2d656b0549d6bbc33d",- },- ],- load: LoadPolicy::Lazy,-};diff --git a/crates/openhuman-core/src/modules/runtime.rs b/crates/openhuman-core/src/modules/runtime.rsdeleted file mode 100644index 2183540c5b..0000000000--- a/crates/openhuman-core/src/modules/runtime.rs+++ /dev/null@@ -1,296 +0,0 @@-//! Calling the `tinyruntime` module: resolving a language runtime and running-//! code on it, over the bus.-//!-//! Everything the core used to own about managed toolchains — probing the host-//! for a compatible interpreter, downloading a distribution, verifying its-//! digest, unpacking it, keeping it across restarts, and pooling warm worker-//! processes in front of it — lives in that module now. What is left here is the-//! host half of four calls.-//!-//! # Three modules, one call-//!-//! `tinyruntime` is a router and knows no languages on its own; the language-//! knowledge is in `tinyruntime-nodejs` and `tinyruntime-python`. So a call for-//! JavaScript needs two modules loaded, not one, and [`ensure_language`] loads-//! both. Load order does not matter — the router contacts providers per call-//! rather than at setup — but a router without its provider reports the language-//! unavailable, which is a confusing way to discover a missing module.-//!-//! # Configuration travels with the call-//!-//! The module holds none of its own. Every request carries the version pin, the-//! cache directory, and the pool tuning it should be served under, which is why-//! [`settings_for`] reads this host's config on each call rather than at load.-//! A user who changes `node.version` sees it take effect on the next run instead-//! of on the next restart.-//!-//! # Deadlines belong to the caller-//!-//! Nothing here imposes one. An install is a multi-hundred-megabyte download and-//! a caller that wants to bound it knows what it is willing to wait; a deadline-//! chosen here would make the effective limit the smaller of two numbers nobody-//! picked together. `Execute` carries its own per-job deadline in the request,-//! which the worker honours and reports back.--use tinyruntime_bus::{- names, ExecRequest, ExecResponse, Language, LanguagesResponse, PoolSettings, PoolStatsResponse,- ResolveRequest, ResolveResponse, ResolvedRuntime, RuntimeSettings,-};--use super::{host, ops, registry};-use crate::config::Config;--/// Registry id of the router.-pub const MODULE_ID: &str = "tinyruntime";--/// Registry id of the Node.js provider.-pub const NODEJS_PROVIDER_ID: &str = "tinyruntime-nodejs";--/// Registry id of the Python provider.-pub const PYTHON_PROVIDER_ID: &str = "tinyruntime-python";--/// Why a runtime call did not produce what was asked for.-///-/// Three variants rather than one string because callers act on them-/// differently: a missing module disables a feature, a bad request is worth-/// reporting to whoever made it, and a failure mid-flight is worth retrying or-/// surfacing.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum RuntimeCallError {- /// The module is not loaded and cannot be: no artifact for this host,- /// downloads off, disabled in config, or a load that already failed in this- /// process.- Unavailable(String),- /// The request was rejected — an unknown language, a version that is not one,- /// a language the host has disabled.- InvalidRequest(String),- /// Resolution, installation, or execution failed.- Failed(String),-}--impl std::fmt::Display for RuntimeCallError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Self::Unavailable(message) | Self::InvalidRequest(message) | Self::Failed(message) => {- f.write_str(message)- }- }- }-}--impl std::error::Error for RuntimeCallError {}--/// The registry id of the provider module serving `language`, if this build-/// ships one.-///-/// A language with no provider record is not an error here: the router accepts-/// any language its own configuration routes, and a host may have put a-/// third-party provider on the module search path.-#[must_use]-pub fn provider_id(language: &Language) -> Option<&'static str> {- match language.as_str() {- tinyruntime_bus::NODEJS => Some(NODEJS_PROVIDER_ID),- tinyruntime_bus::PYTHON => Some(PYTHON_PROVIDER_ID),- _ => None,- }-}--/// Load the router and, when this build ships one, `language`'s provider.-///-/// # Errors-///-/// [`RuntimeCallError::Unavailable`] naming which of the two could not be-/// loaded.-pub async fn ensure_language(config: &Config, language: &Language) -> Result<(), RuntimeCallError> {- ops::ensure_loaded(config, MODULE_ID)- .await- .map_err(RuntimeCallError::Unavailable)?;- if let Some(provider) = provider_id(language) {- ops::ensure_loaded(config, provider)- .await- .map_err(RuntimeCallError::Unavailable)?;- }- Ok(())-}--/// Resolve a runtime for `language`, installing one when `install` allows it.-///-/// Returns `None` when `install` is `false` and nothing is provisioned yet —-/// which is the whole point of a non-installing probe: it answers "is this-/// ready?" without committing the caller to a download.-///-/// # Errors-///-/// [`RuntimeCallError`] describing whether the module, the request, or the-/// resolution was at fault.-pub async fn resolve(- config: &Config,- language: &Language,- install: bool,-) -> Result<Option<ResolvedRuntime>, RuntimeCallError> {- ensure_language(config, language).await?;- let settings = settings_for(config, language);- let request = if install {- ResolveRequest::new(language.clone(), settings)- } else {- ResolveRequest::probe(language.clone(), settings)- };-- let response: ResolveResponse = call(names::methods::RESOLVE, (request,)).await?;- Ok(response.runtime)-}--/// Run `code` on `language`, resolving and provisioning it first.-///-/// # Errors-///-/// [`RuntimeCallError`]. Note that a job which *ran* and threw is not an error:-/// it comes back as an [`ExecResponse`] with a non-zero exit code, because that-/// is output the caller wants rather than a failure of this call.-pub async fn execute(- config: &Config,- language: &Language,- code: impl Into<String>,- cwd: Option<String>,- timeout: Option<std::time::Duration>,-) -> Result<ExecResponse, RuntimeCallError> {- ensure_language(config, language).await?;-- let mut request = ExecRequest::new(language.clone(), settings_for(config, language), code);- request.pool = pool_settings_for(config, language);- request.cwd = cwd;- request.timeout_ms =- timeout.map(|budget| u64::try_from(budget.as_millis()).unwrap_or(u64::MAX));-- call(names::methods::EXECUTE, (request,)).await-}--/// Every language the router can route to, and whether it currently can.-///-/// Loads the router but not the providers: the point of this call is to find out-/// which providers are there, and loading them first would make the answer-/// always yes.-///-/// # Errors-///-/// [`RuntimeCallError::Unavailable`] when the router itself cannot be loaded.-pub async fn languages(config: &Config) -> Result<LanguagesResponse, RuntimeCallError> {- ops::ensure_loaded(config, MODULE_ID)- .await- .map_err(RuntimeCallError::Unavailable)?;- call(names::methods::LANGUAGES, ()).await-}--/// Every live worker pool's counters.-///-/// # Errors-///-/// [`RuntimeCallError::Unavailable`] when the router cannot be loaded.-pub async fn pool_stats(config: &Config) -> Result<PoolStatsResponse, RuntimeCallError> {- ops::ensure_loaded(config, MODULE_ID)- .await- .map_err(RuntimeCallError::Unavailable)?;- call(names::methods::POOL_STATS, ()).await-}--/// The settings this host wants `language` served under.-///-/// Read per call rather than cached, because the module holds no configuration-/// of its own: a user who edits a version pin sees it on the next run.-#[must_use]-pub fn settings_for(config: &Config, language: &Language) -> RuntimeSettings {- match language.as_str() {- tinyruntime_bus::PYTHON => {- let python = &config.runtime_python;- let mut settings = RuntimeSettings::new(python.minimum_version.clone());- settings.enabled = python.enabled;- settings.prefer_system = python.prefer_system;- settings.maximum_version = python.maximum_version.clone();- settings.cache_dir = python.cache_dir.clone();- settings.release_tag = python.managed_release_tag.clone();- settings.preferred_command = python.preferred_command.clone();- settings- }- // Node.js is the default rather than a match arm of its own: a language- // this build ships no configuration block for still gets a usable- // request, and the router refuses it by name if nothing routes it.- _ => {- let node = &config.node;- let mut settings = RuntimeSettings::new(node.version.clone());- settings.enabled = node.enabled;- settings.prefer_system = node.prefer_system;- settings.cache_dir = node.cache_dir.clone();- settings- }- }-}--/// The pool tuning this host wants for `language`.-///-/// Python defaults off where Node defaults on, and that asymmetry is real rather-/// than an oversight: a pooled Node job runs in its own worker thread with a-/// fresh module graph, while a pooled Python job shares the interpreter with-/// every other job on that worker. Opting into the second is a decision.-#[must_use]-pub fn pool_settings_for(config: &Config, language: &Language) -> PoolSettings {- let pool = &config.runtime_pool;- let (lang_config, default_enabled) = match language.as_str() {- tinyruntime_bus::PYTHON => (&pool.python, false),- _ => (&pool.node, true),- };-- let mut settings = PoolSettings::default();- settings.enabled = pool.enabled && lang_config.is_enabled(default_enabled);- settings.max_workers = lang_config.effective_max_workers();- settings.idle_ttl_secs = lang_config.idle_ttl_secs;- settings.recycle_after_jobs = lang_config.recycle_after_jobs;- settings.max_queue_depth = lang_config.effective_max_queue_depth();- settings-}--/// Make one call on the router's object.-async fn call<A, R>(member: &str, arguments: A) -> Result<R, RuntimeCallError>-where- A: serde::Serialize,- R: serde::de::DeserializeOwned,-{- let record = registry::find(MODULE_ID)- .ok_or_else(|| RuntimeCallError::Unavailable(format!("unknown module '{MODULE_ID}'")))?;- let runtime = host::runtime()- .await- .map_err(|_| RuntimeCallError::Unavailable("the module bus is not running".to_string()))?;- let proxy = runtime- .proxy(record.bus_name, record.object_path)- .map_err(|error| RuntimeCallError::Failed(error.to_string()))?;-- proxy- .call(member, arguments)- .await- .map_err(|error| classify(&error))-}--/// Map a bus failure onto the shape a caller can act on.-///-/// The router's own errors arrive as messages rather than distinct wire names,-/// so the classification is on the text it produces — which is stable, because-/// those messages are the module's public contract with a host that renders-/// them. An unrecognised failure is [`RuntimeCallError::Failed`] rather than-/// `InvalidRequest`: telling a caller its request was wrong when it was not-/// sends it into a pointless rewrite.-fn classify(error: &tinybus::Error) -> RuntimeCallError {- let message = error.to_string();- if message.contains("ModuleUnavailable") || error.wire_name().contains("ModuleUnavailable") {- return RuntimeCallError::Unavailable(message);- }- if message.contains("no runtime provider is registered")- || message.contains("named no language")- || message.contains("is disabled")- {- return RuntimeCallError::InvalidRequest(message);- }- RuntimeCallError::Failed(message)-}--#[cfg(test)]-#[path = "runtime_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/modules/runtime_tests.rs b/crates/openhuman-core/src/modules/runtime_tests.rsdeleted file mode 100644index 263238848e..0000000000--- a/crates/openhuman-core/src/modules/runtime_tests.rs+++ /dev/null@@ -1,154 +0,0 @@-//! Tests for the `tinyruntime` client facade.-//!-//! These exercise the parts that are this host's decisions rather than the-//! module's: which provider serves a language, how this host's configuration-//! becomes a request, and how a bus failure is classified. The module's own-//! behaviour — resolution order, digest verification, pooling — is tested in its-//! repository against its own suite, and re-asserting it here would only test-//! the mock.--use super::{- pool_settings_for, provider_id, settings_for, RuntimeCallError, MODULE_ID, NODEJS_PROVIDER_ID,- PYTHON_PROVIDER_ID,-};-use crate::config::Config;-use crate::modules::registry;-use tinyruntime_bus::Language;--#[test]-fn each_first_party_language_maps_to_its_provider_module() {- assert_eq!(provider_id(&Language::nodejs()), Some(NODEJS_PROVIDER_ID));- assert_eq!(provider_id(&Language::python()), Some(PYTHON_PROVIDER_ID));-}--#[test]-fn a_language_this_build_ships_no_provider_for_is_not_an_error_here() {- // The router accepts whatever its own configuration routes, and an operator- // may have put a third-party provider on the module search path. Refusing- // here would make that impossible.- assert_eq!(provider_id(&Language::new("ruby")), None);-}--#[test]-fn the_provider_records_named_here_exist_in_the_registry() {- // A typo would surface as "unknown module" at the first tool call, long- // after the change that caused it.- for id in [MODULE_ID, NODEJS_PROVIDER_ID, PYTHON_PROVIDER_ID] {- assert!(- registry::find(id).is_some(),- "no registry record for '{id}'"- );- }-}--#[test]-fn node_settings_come_from_the_node_config_block() {- let mut config = Config::default();- config.node.version = "v22.11.0".to_string();- config.node.prefer_system = false;- config.node.cache_dir = "/tmp/node-cache".to_string();-- let settings = settings_for(&config, &Language::nodejs());- assert_eq!(settings.version, "v22.11.0");- assert!(!settings.prefer_system);- assert_eq!(settings.cache_dir, "/tmp/node-cache");-}--#[test]-fn python_settings_come_from_the_python_config_block() {- let mut config = Config::default();- config.runtime_python.minimum_version = "3.12".to_string();- config.runtime_python.maximum_version = "3.15".to_string();- config.runtime_python.preferred_command = "/usr/bin/python3.12".to_string();-- let settings = settings_for(&config, &Language::python());- assert_eq!(settings.version, "3.12");- assert_eq!(settings.maximum_version, "3.15");- assert_eq!(settings.preferred_command, "/usr/bin/python3.12");-}--#[test]-fn the_two_languages_do_not_read_each_others_configuration() {- // The bug this rules out: a Python request served under the Node version- // pin, which would ask the Python channel for `v22.11.0`.- let mut config = Config::default();- config.node.version = "v22.11.0".to_string();- config.runtime_python.minimum_version = "3.12".to_string();-- assert_eq!(- settings_for(&config, &Language::nodejs()).version,- "v22.11.0"- );- assert_eq!(settings_for(&config, &Language::python()).version, "3.12");-}--#[test]-fn a_disabled_language_is_carried_into_the_request_rather_than_refused_here() {- // The module says why a language is unavailable; duplicating the check here- // would mean two places to change and two messages to keep in step.- let mut config = Config::default();- config.node.enabled = false;- assert!(!settings_for(&config, &Language::nodejs()).enabled);-}--#[test]-fn node_pools_by_default_and_python_does_not() {- // Not an oversight: a pooled Node job runs in its own worker thread with a- // fresh module graph, while a pooled Python job shares the interpreter with- // every other job on that worker.- let config = Config::default();- assert!(pool_settings_for(&config, &Language::nodejs()).enabled);- assert!(!pool_settings_for(&config, &Language::python()).enabled);-}--#[test]-fn turning_the_pool_off_wholesale_turns_it_off_for_every_language() {- let mut config = Config::default();- config.runtime_pool.enabled = false;- assert!(!pool_settings_for(&config, &Language::nodejs()).enabled);-}--#[test]-fn pool_tuning_is_carried_from_this_hosts_configuration() {- let mut config = Config::default();- config.runtime_pool.node.max_workers = 4;- config.runtime_pool.node.recycle_after_jobs = 25;-- let settings = pool_settings_for(&config, &Language::nodejs());- assert_eq!(settings.max_workers, 4);- assert_eq!(settings.recycle_after_jobs, 25);-}--#[test]-fn a_zero_worker_pool_is_clamped_before_it_leaves_this_host() {- // A pool that can hold no workers would queue every job forever. The module- // clamps too, but sending a zero would make the request a lie about what- // this host asked for.- let mut config = Config::default();- config.runtime_pool.node.max_workers = 0;- assert!(pool_settings_for(&config, &Language::nodejs()).max_workers >= 1);-}--#[test]-fn an_unloadable_module_and_a_bad_request_are_different_failures() {- // Callers act on them differently: one disables a feature, the other is- // worth reporting to whoever made the request.- let unavailable = RuntimeCallError::Unavailable("no artifact for this host".to_string());- let invalid = RuntimeCallError::InvalidRequest("no runtime provider for `ruby`".to_string());- assert_ne!(unavailable, invalid);- assert_eq!(unavailable.to_string(), "no artifact for this host");-}--#[test]-fn a_call_error_renders_as_its_message_alone() {- // These are surfaced to models and users, so a variant name leaking into the- // text would be noise in a chat transcript.- for error in [- RuntimeCallError::Unavailable("a".to_string()),- RuntimeCallError::InvalidRequest("b".to_string()),- RuntimeCallError::Failed("c".to_string()),- ] {- let rendered = error.to_string();- assert!(rendered.len() <= 1, "got `{rendered}`");- }-}diff --git a/crates/openhuman-core/src/modules/tokenjuice_host.rs b/crates/openhuman-core/src/modules/tokenjuice_host.rsindex b2ffb32bfb..2832440b63 100644--- a/crates/openhuman-core/src/modules/tokenjuice_host.rs+++ b/crates/openhuman-core/src/modules/tokenjuice_host.rs@@ -14,17 +14,6 @@ struct MlHost;#[tinybus::interface(name = "ai.tinyhumans.tinyjuice.MlHost")]impl MlHost {- async fn compress(- &self,- text: String,- options: serde_json::Value,- ) -> tinybus::Result<Option<String>> {- let options = serde_json::from_value(options).map_err(method_error)?;- crate::inference::tokenjuice::ml::compress(&text, &options)- .await- .map_err(method_error)- }-/// One tool-less model call for the module's summary stage, run under the/// turn its `context_token` names. `None` declines — the token is unknown/// or already used, and the module falls back to its own compressors.diff --git a/crates/openhuman-core/src/platform/about_app/README.md b/crates/openhuman-core/src/platform/about_app/README.mdindex a1618c73d4..97bc3d6dd7 100644--- a/crates/openhuman-core/src/platform/about_app/README.md+++ b/crates/openhuman-core/src/platform/about_app/README.md@@ -75,7 +75,7 @@ No dependencies on other `openhuman` domains: capability metadata for other doma- Adding/renaming/removing a user-facing feature requires editing `CAPABILITIES`: this is the capability catalog that CLAUDE.md's "Capability catalog" rule points at. Keep ids stable; duplicate or empty ids panic at first catalog access via `ensure_validated`.- Privacy constants encode real third-party destinations (Hugging Face, GitHub Releases, Composio `backend.composio.dev`, SearXNG, configured embedding providers, ElevenLabs, etc.): the inline comments document why several were corrected away from the generic `DERIVED_TO_BACKEND` / `LOCAL_CREDENTIALS` defaults; mirror that diligence when adding network-touching capabilities.- `Capability` fields are all `&'static str` / copy types, so `Capability` is `Copy` and the read APIs cheaply return owned `Vec`s by copying.-- A capability's `domain` is a free-text label and does not always equal its `category` wire name (e.g. `embeddings`, `wallet`, `runtime_python`, `devices`, `desktop_companion`, `security`, `tools`, `memory`).+- A capability's `domain` is a free-text label and does not always equal its `category` wire name (e.g. `embeddings`, `wallet`, `local_ai`, `devices`, `desktop_companion`, `security`, `tools`, `memory`).- `CapabilityCategory::FromStr` is lenient (case-insensitive, accepts `local-ai`/`local ai`/`localai` aliases); `as_str` emits the canonical snake_case wire name used by serde.## Further readingdiff --git a/crates/openhuman-core/src/profiles/tools.rs b/crates/openhuman-core/src/profiles/tools.rsindex 4c0138acdd..e27a5e3ce8 100644--- a/crates/openhuman-core/src/profiles/tools.rs+++ b/crates/openhuman-core/src/profiles/tools.rs@@ -105,9 +105,6 @@ pub const HARD_DENIED: &[&str] = &["create_skill","git_operations","delegate",- "node_exec",- "npm_exec",- "python_exec","curl","pushover",];diff --git a/crates/openhuman-core/src/runtime/README.md b/crates/openhuman-core/src/runtime/README.mddeleted file mode 100644index be48cccbe9..0000000000--- a/crates/openhuman-core/src/runtime/README.md+++ /dev/null@@ -1,167 +0,0 @@-# runtime--The client side of code execution. Agents, skills and flows run JavaScript and-Python through this folder: the `node_exec`, `npm_exec`, `python_exec` and-`shell` tools, Node-dependent skills, TokenJuice's ML compressor and the flows-native-tool backend all reach a toolchain or a worker from here.--The machinery itself is not here. Finding, downloading, verifying, unpacking-and caching an interpreter, and keeping pools of warm workers, all belong to-the `tinyruntime` module (`vendor/tinyruntime`), loaded over TinyBus and-reached through `crate::modules::runtime`. This folder asks that module for-answers and adapts them onto the types the rest of the core already uses-(`ResolvedNode`, `ResolvedPython`, `PoolExecOutcome`, `PoolRunError`).--## How it works--```text- tools/impl/system (node_exec, npm_exec, python_exec, shell)- skills runtime, flows oh: backend, tokenjuice ml- | | | |- v v v v- runtime::node runtime::python runtime::pool runtime::python_server- (NodeBootstrap) (PythonBootstrap) (run_inline) (ensure_started)- \ | / |- +----------------+----------------+ |- | v- v tinyruntime_pyserver- runtime::client (worker lifecycle,- (execute, resolve, JSONL protocol)- RuntimeCallError)- | \- feature "modules" on feature "modules" off- | \- v v- crate::modules::runtime client/disabled.rs- (TinyBus -> tinyruntime) (every call: Unavailable)-```--### Resolving a toolchain--`NodeBootstrap` and `PythonBootstrap` have the same shape. Each is built over-an `Arc<Config>` and memoises the last answer:--1. `try_cached()` returns the memoised toolchain without awaiting anything.- The shell uses it on every command to decide whether to prepend a managed- bin dir to `PATH`, where a blocking bus round trip would change the- meaning of an unrelated command.-2. `probe_installed()` asks the module to resolve without installing. A warm- start finds an existing install, and a cold one reports `None` instead of- starting a download nobody asked for.-3. `resolve()` asks the module to resolve and install if needed, then adapts- the reply (`ResolvedNode { node_bin, npm_bin, bin_dir, version, source }`,- `ResolvedPython { python_bin, bin_dir, version, source }`).--Both check their config switch first (`config.node.enabled`,-`config.runtime_python` for Python) and fail or return `None` when the-runtime is turned off.--### Pooled inline execution--`pool::node::run_inline` and `pool::python::run_inline` send one inline job to-the module's warm worker pool through `runtime::client::execute`. Whether a-language pools at all is decided here (`pool::node::enabled`,-`pool::python::enabled`): Node defaults on because each job gets its own-`worker_thread`, Python defaults off because jobs would share one interpreter.-`[runtime_pool] enabled = false` reverts every caller to its per-call spawn.--A module failure is classified into `PoolRunError`, and the exec tools act on-the variant. `PreDispatch` means the job never reached a worker, so a fallback-spawn is safe. `PostDispatch` means it may have run, so the caller must not-retry. `Saturated` means the pool shed the job, and the caller must not spawn-around it either. See [`pool/`](pool/README.md) for the full table.--### The persistent Python worker--`python_server::ensure_started(config)` keeps one long-lived Python process-warm for model-backed backends. Today the only backend is Kompress, the-ModernBERT plain-text compressor used by TokenJuice, enabled by-`config.tokenjuice.ml_compression_enabled`. This folder maps `Config` and the-managed interpreter onto a `ServerLaunch` and holds the process-wide slot; the-process lifecycle and the JSONL protocol are `tinyruntime_pyserver`.--## Layout--| Path | What it does |-| --- | --- |-| [`client/`](client/README.md) | The single import point for `modules::runtime` (`execute`, `resolve`, `RuntimeCallError`). With the `modules` feature off it re-exports `disabled.rs`, which answers every call with `RuntimeCallError::Unavailable`. |-| [`node/`](node/README.md) | `NodeBootstrap`, the Node toolchain client (behind `runtime-node`), plus the ungated native-tool bridge (`ops.rs`, `types.rs`) and the `javascript.*` controllers (`schemas.rs`, `rpc.rs`). `stub.rs` carries the `NodeBootstrap` type surface when `runtime-node` is off. |-| [`javascript/`](javascript/README.md) | A re-export facade over [`node`](./node) so callers import a language slot (`crate::runtime::javascript`) instead of a backend. No logic. |-| [`python/`](python/README.md) | `PythonBootstrap`, the Python interpreter client. |-| [`python_server/`](python_server/README.md) | Host side of the persistent Python worker: `ensure_started`, `status`, the backend registry and Kompress provisioning (`ensure_kompress`, `request_kompress`). |-| [`pool/`](pool/README.md) | Pooled inline execution (`run_inline` per language), the per-language enable decision, and `PoolRunError` classification. |--## Key types and entry points--- `NodeBootstrap`, `ResolvedNode`, `NodeSource` ([`node/bootstrap.rs`](./node/bootstrap.rs)) are the- Node toolchain client and its answer. `ShellTool` holds an- `Option<Arc<NodeBootstrap>>`.-- `PythonBootstrap`, `ResolvedPython`, `PythonSource` ([`python/bootstrap.rs`](./python/bootstrap.rs))- are the Python equivalents.-- `pool::node::run_inline`, `pool::python::run_inline`, `PoolExecOutcome`,- `PoolRunError`, `PoolSettings` ([`pool/`](./pool/)) are what `node_exec` and- `python_exec` call and match on.-- `python_server::ensure_started`, `status`, `request_kompress`- ([`python_server/`](./python_server/)) start the worker and send it a compress request.-- `runtime::node::execute_tool` and `list_tools` ([`node/ops.rs`](./node/ops.rs)) build the- full agent tool registry (`tools::ops::all_tools_with_runtime`) and run one- tool by name, publishing `ToolExecutionStarted` and- `ToolExecutionCompleted` on the bus with session id `"javascript"`.--## RPC / CLI surface--With `runtime-node` on, [`node/schemas.rs`](./node/schemas.rs) registers the [`javascript`](./javascript)-namespace through `core/all.rs`:--| Method | Description |-| --- | --- |-| `javascript.list_tools` | List the agent tools an embedded JavaScript host can call. |-| `javascript.execute_tool` | Run one agent tool by name with JSON arguments. |--## Boundaries--- Interpreter discovery, managed installs, digest checks, archive- extraction, install caches and the warm worker pools belong to the- `tinyruntime` module (`vendor/tinyruntime`), reached only through- `crate::modules::runtime`.-- The Python worker's process lifecycle, wire types and script- (`SERVER_SCRIPT`) are `tinyruntime_pyserver`, a library crate in- `vendor/tinyruntime`.-- How `tinyruntime` and its language providers are loaded and admitted is- covered in [`modules/registry`](../modules/registry/README.md).-- The exec tools that use these clients live in- `crates/openhuman-core/src/tools/impl/system/`.-- Runtime settings ([`node`](./node), `runtime_python`, `runtime_pool`) are defined- under `config/schema/`.--## Gotchas--- `runtime/` is always compiled even though `crate::modules` is behind the- `modules` feature, because `ShellTool` is kernel code that names- `NodeBootstrap`. That is why every module call goes through- `runtime::client`: with `modules` off the calls answer `Unavailable`- instead of failing to build.-- `runtime-node` (default on, and in `scripts/ci/product-features.txt`) gates- the managed Node client, the `javascript.*` controllers, `node_exec`,- `npm_exec` and the `node_runtime` harness step. [`node/ops.rs`](./node/ops.rs) and- [`node/types.rs`](./node/types.rs) stay ungated because the flows `oh:` native-tool backend- uses them in every build.-- `PoolRunError` classification reads the module's error text- ("pool is at capacity", "failed after dispatch"). Anything unrecognised is- treated as pre-dispatch.--## Tests--Tests sit beside their modules as `*_tests.rs`. Run them with-`cargo test -p openhuman runtime::` or `pnpm debug rust runtime::`. Build with-`--no-default-features` and a feature list without `runtime-node` (or without-`modules`) to check the stub paths compile.--See `gitbooks/developing/performance.md` for how pooling and in-process-execution feed into the project's density and cold-start numbers.--## Further reading--- [tinyruntime submodule](../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/client/README.md b/crates/openhuman-core/src/runtime/client/README.mddeleted file mode 100644index 5191246f01..0000000000--- a/crates/openhuman-core/src/runtime/client/README.md+++ /dev/null@@ -1,57 +0,0 @@-# runtime/client--The single import point the `runtime/` clients use to reach the `tinyruntime`-module (`modules::runtime`).--## Why this exists--`crate::modules` sits behind the `modules` Cargo feature, but `runtime/` does-not: `ShellTool` holds an `Option<Arc<NodeBootstrap>>` as a plain field and is-kernel code, so the toolchain clients (`runtime::node`, `runtime::python`) have-to compile whether or not `modules` is on. If those clients imported-`modules::runtime` directly, turning the feature off would break the build-instead of just disabling the managed runtimes.--So `node` and `python` import `execute`, `pool_stats`, `resolve`, and-`RuntimeCallError` from here instead of from `modules::runtime` directly. With-`modules` on, this re-exports the real client. With it off, it re-exports-`disabled`, a stand-in that answers every call with-`RuntimeCallError::Unavailable`. Callers cannot tell the two apart, which is-the point: a build without the module bus should look like a runtime that-simply is not there, not like a missing symbol.--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | The feature-gated re-export: `modules::runtime`'s `execute`, `pool_stats`, `resolve`, `RuntimeCallError` when `modules` is on, `disabled`'s copies when it is off. |-| [`disabled.rs`](./disabled.rs) | The `modules`-off stand-in. Same three-variant `RuntimeCallError` as the real client, so callers match identically in both builds; every function returns `Unavailable` with a message naming the missing feature. |--## Public surface--`pub(crate)` only: `execute`, `pool_stats`, `resolve`, `RuntimeCallError`. This-is a facade for `runtime/`'s own use, not a public API, and it re-exports only-what `runtime/` actually calls. `modules::runtime` has more surface (a-`Languages` listing, for one) that the stub deliberately does not mirror.--## Used by--- `crates/openhuman-core/src/runtime/node/bootstrap.rs` and- `crates/openhuman-core/src/runtime/python/bootstrap.rs`: call `resolve` to- get a toolchain and `execute` to run inline code on it.-- `crates/openhuman-core/src/runtime/pool/`: calls `execute` and `pool_stats`- for pooled inline execution.--## Where next--- [`modules/registry`](../../modules/registry/README.md) for how the real- `tinyruntime` module gets loaded and admitted.-- [`runtime/node`](../node/README.md) and [`runtime/python`](../python/README.md)- for the toolchain clients that sit on top of this facade.--## Further reading--- [Parent module (`runtime`)](../README.md)-- [tinyruntime submodule](../../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/client/disabled.rs b/crates/openhuman-core/src/runtime/client/disabled.rsdeleted file mode 100644index b825152714..0000000000--- a/crates/openhuman-core/src/runtime/client/disabled.rs+++ /dev/null@@ -1,90 +0,0 @@-//! The `modules`-off stand-in for the runtime client.-//!-//! Mirrors the surface the real client exposes, answering everything with-//! [`RuntimeCallError::Unavailable`]. A build without the module bus has no way-//! to reach the `tinyruntime` module, and that is a runtime fact rather than a-//! failure: the shell skips its `PATH` injection, and the exec tools are not-//! registered, exactly as when the runtime is disabled in configuration.--use tinyruntime_bus::{ExecResponse, Language, PoolStatsResponse, ResolvedRuntime};--use crate::config::Config;--/// Returned by every call in a build without the module bus.-///-/// Phrased as a build fact, matching the `runtime-node` stub's convention.-const MODULES_DISABLED_MESSAGE: &str =- "the modules feature is disabled at compile time — rebuild with `--features modules` to use \- managed language runtimes";--/// Why a runtime call did not produce what was asked for.-///-/// The same three variants the real client uses, so callers match identically in-/// both builds.-#[derive(Debug, Clone, PartialEq, Eq)]-pub enum RuntimeCallError {- /// The module is not loaded and cannot be.- Unavailable(String),- /// The request was rejected.- InvalidRequest(String),- /// Resolution, installation, or execution failed.- Failed(String),-}--impl std::fmt::Display for RuntimeCallError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Self::Unavailable(message) | Self::InvalidRequest(message) | Self::Failed(message) => {- f.write_str(message)- }- }- }-}--impl std::error::Error for RuntimeCallError {}--/// The failure every call in this build produces.-fn unavailable() -> RuntimeCallError {- RuntimeCallError::Unavailable(MODULES_DISABLED_MESSAGE.to_string())-}--/// Always unavailable: there is no module bus to ask.-///-/// # Errors-///-/// Always [`RuntimeCallError::Unavailable`].-pub async fn resolve(- _config: &Config,- _language: &Language,- _install: bool,-) -> Result<Option<ResolvedRuntime>, RuntimeCallError> {- Err(unavailable())-}--/// Always unavailable: there is no module bus to ask.-///-/// # Errors-///-/// Always [`RuntimeCallError::Unavailable`].-pub async fn execute(- _config: &Config,- _language: &Language,- _code: impl Into<String>,- _cwd: Option<String>,- _timeout: Option<std::time::Duration>,-) -> Result<ExecResponse, RuntimeCallError> {- Err(unavailable())-}--/// Always unavailable: there is no module bus to ask.-///-/// # Errors-///-/// Always [`RuntimeCallError::Unavailable`].-pub async fn pool_stats(_config: &Config) -> Result<PoolStatsResponse, RuntimeCallError> {- Err(unavailable())-}--#[cfg(test)]-#[path = "disabled_test_tests.rs"]-mod test;diff --git a/crates/openhuman-core/src/runtime/client/disabled_test_tests.rs b/crates/openhuman-core/src/runtime/client/disabled_test_tests.rsdeleted file mode 100644index ded689aa43..0000000000--- a/crates/openhuman-core/src/runtime/client/disabled_test_tests.rs+++ /dev/null@@ -1,20 +0,0 @@-use super::{resolve, unavailable, RuntimeCallError};-use crate::config::Config;-use tinyruntime_bus::Language;--#[tokio::test]-async fn every_call_reports_the_missing_feature() {- let error = resolve(&Config::default(), &Language::nodejs(), true)- .await- .expect_err("there is no module bus in this build");- assert!(matches!(error, RuntimeCallError::Unavailable(_)));- assert!(- error.to_string().contains("modules feature"),- "got `{error}`"- );-}--#[test]-fn the_failure_renders_as_its_message_alone() {- assert_eq!(unavailable().to_string(), super::MODULES_DISABLED_MESSAGE);-}diff --git a/crates/openhuman-core/src/runtime/client/mod.rs b/crates/openhuman-core/src/runtime/client/mod.rsdeleted file mode 100644index 31df5d77a9..0000000000--- a/crates/openhuman-core/src/runtime/client/mod.rs+++ /dev/null@@ -1,24 +0,0 @@-//! The one way the runtime clients reach the `tinyruntime` module.-//!-//! `crate::modules` is behind the `modules` feature, but this directory is-//! not: `ShellTool` holds an `Option<Arc<NodeBootstrap>>` as a field and is-//! kernel, so the toolchain clients are always compiled. Importing-//! `modules::runtime` directly would therefore break every build with the gate-//! off.-//!-//! So the import goes through here. With `modules` on this is the real client;-//! with it off it is [`disabled`], which answers every call with the same-//! "unavailable" shape a missing module produces. Callers cannot tell the-//! difference, and neither can the shell — which is the point: an off-state must-//! look like a runtime that is simply not there, not like a compile error.--#[cfg(not(feature = "modules"))]-mod disabled;--// Only what `runtime/` actually calls. `modules::runtime` exposes more — the-// `Languages` listing, for one — but a facade that re-exported the whole surface-// would oblige the stub to grow a twin of every member nothing here uses.-#[cfg(feature = "modules")]-pub(crate) use crate::modules::runtime::{execute, resolve, RuntimeCallError};-#[cfg(not(feature = "modules"))]-pub(crate) use disabled::{execute, pool_stats, resolve, RuntimeCallError};diff --git a/crates/openhuman-core/src/runtime/javascript/README.md b/crates/openhuman-core/src/runtime/javascript/README.mddeleted file mode 100644index c92a8c44fe..0000000000--- a/crates/openhuman-core/src/runtime/javascript/README.md+++ /dev/null@@ -1,94 +0,0 @@-# runtime/javascript--First-class **JavaScript language slot** for the core. This module is a thin-re-export facade: it gives the rest of the codebase a stable-`crate::runtime::javascript` import path that talks to a *language*-(`javascript`) rather than to a concrete backend. Today the implementation-backend is the managed Node.js client in [`crate::runtime::node`](../node/README.md),-which is itself a client for the vendored `tinyruntime` module: the facade-exists so the backend underneath can be swapped without churning callers. It-owns no logic of its own: every symbol it exposes is a `pub use`.--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | Entire module (26 lines). Module docstring plus `pub use` re-exports, some gated by the `runtime-node` feature. No types, no logic, no tests. |--## Gating (`runtime-node`)--The facade itself is **always compiled**: `ShellTool` and the other exec-tools hold an `Option<Arc<NodeBootstrap>>`, so the bootstrap type surface must-exist in every build:--- Always re-exported: `ExecuteToolOutcome`, `NodeBootstrap`, `NodeSource`,- `ResolvedNode`. With `runtime-node` off, these come from- `runtime::node::stub` (`resolve` errors with a build fact; `try_cached` /- `probe_installed` return `None`).-- Re-exported only behind `runtime-node`: `RuntimeToolSummary`, `execute_tool`,- `list_tools`, and the controller registry pair- `all_javascript_controller_schemas` / `all_javascript_registered_controllers`- (aliases of `all_runtime_node_controller_schemas` /- `all_runtime_node_registered_controllers`). The controller pair only exists- with the feature on; the dispatcher behind `execute_tool` / `list_tools`- (`runtime::node::ops`) is itself always compiled because the ungated `flows`- `oh:` backend calls it directly: only this facade's alias is gated, since- its sole consumer here is the gated `runtime::node::rpc` bridge.--## Public surface--- **Types** (always): `ExecuteToolOutcome`, `NodeBootstrap`, `NodeSource`,- `ResolvedNode`.-- **Types** (`runtime-node`): `RuntimeToolSummary`.-- **Functions** (`runtime-node`): `execute_tool`, `list_tools`.-- **Controller wiring** (`runtime-node`): `all_javascript_controller_schemas`,- `all_javascript_registered_controllers`.--## RPC / controllers--Namespace `javascript`, defined in `runtime::node::schemas` and surfaced-through this facade's `all_javascript_*` aliases:--| Method | Inputs | Outputs |-| --- | --- | --- |-| `javascript.list_tools` | none | `tools`: array of tool metadata (`name`, `description`, `category`, `permission_level`, `scope`, `supports_markdown`, `parameters`). |-| `javascript.execute_tool` | `tool_name` (required), `args` (optional Json, defaults to `{}`), `prefer_markdown` (optional bool) | `tool_name`, `elapsed_ms` (u64), `result` (MCP-style `ToolResult`: `{content, is_error, markdownFormatted?}`). |--Handlers live in `runtime::node::rpc`, load config via-`config::rpc::load_config_with_timeout`, build the full tool set via-`tools::all_tools_with_runtime`, then list or dispatch a tool by exact name.--## Events--`execute_tool` (in `runtime::node::ops`) publishes on the bus with-`session_id = "javascript"`:--- `DomainEvent::ToolExecutionStarted`-- `DomainEvent::ToolExecutionCompleted` (with `success`, `elapsed_ms`)--## Used by--- `crates/openhuman-core/src/core/all.rs`: wires- `all_javascript_registered_controllers` into the controller registry.-- `crates/openhuman-core/src/tools/ops.rs`: constructs the shared- `Arc<NodeBootstrap>` (only when `runtime-node` is on and `config.node.enabled`);- `tools/impl/system/{shell,node_exec,npm_exec}.rs` hold it for Node binary- resolution.-- `crates/openhuman-core/src/runtime/node/rpc.rs`: calls back into- `javascript::{list_tools, execute_tool}` through the facade alias.--## Notes / gotchas--- This is a rename-only facade: no `types.rs` / `ops.rs` / `store.rs` here by- design. Edit behavior in [`runtime/node`](../node/README.md), not here.-- `javascript.execute_tool` rebuilds the entire tool set on every call: there- is no persistent tool cache at this layer.-- See [`runtime/node/README.md`](../node/README.md) for everything the facade- forwards to, including what moved out to the `tinyruntime` module.--## Further reading--- [Parent module (`runtime`)](../README.md)-- [tinyruntime submodule](../../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/javascript/mod.rs b/crates/openhuman-core/src/runtime/javascript/mod.rsdeleted file mode 100644index aeff492130..0000000000--- a/crates/openhuman-core/src/runtime/javascript/mod.rs+++ /dev/null@@ -1,26 +0,0 @@-//! First-class JavaScript runtime surface.-//!-//! The implementation backend is the managed Node.js toolchain in-//! [`crate::runtime::node`], which is itself a client for the-//! `tinyruntime` module. This facade exists so the rest of the core talks to a-//! language slot (`javascript`) rather than to a specific backend — which is-//! also how the module underneath was swapped without the callers noticing.-//!-//! ## Gating (`runtime-node`)-//!-//! The facade itself is always compiled — `ShellTool` imports [`NodeBootstrap`]-//! through it — but the re-exports split. The bootstrap type surface comes from-//! `node`'s stub when the feature is off; the dispatch machinery and the-//! controller pair are gated, because their only consumers are gated off too.--pub use crate::runtime::node::{ExecuteToolOutcome, NodeBootstrap, NodeSource, ResolvedNode};--#[cfg(feature = "runtime-node")]-pub use crate::runtime::node::types::RuntimeToolSummary;-#[cfg(feature = "runtime-node")]-pub use crate::runtime::node::{- all_runtime_node_controller_schemas as all_javascript_controller_schemas,- all_runtime_node_registered_controllers as all_javascript_registered_controllers,-};-#[cfg(feature = "runtime-node")]-pub use crate::runtime::node::{execute_tool, list_tools};diff --git a/crates/openhuman-core/src/runtime/mod.rs b/crates/openhuman-core/src/runtime/mod.rsdeleted file mode 100644index 20623ac6e6..0000000000--- a/crates/openhuman-core/src/runtime/mod.rs+++ /dev/null@@ -1,30 +0,0 @@-//! Code-execution runtimes: the client side.-//!-//! The substrate agents, skills, and flows use to run untrusted-ish code. What-//! is *here* is the client half — everything that downloads a toolchain,-//! verifies it, unpacks it, caches it, or keeps a warm worker in front of it now-//! lives in the `tinyruntime` module, behind-//! [`crate::modules::runtime`], reached through the ungated-//! [`client`] facade so a build without the module bus still compiles.-//!-//! That split is what this directory is for: adapting module answers onto the-//! types the rest of the core already names, so a migration of the machinery did-//! not become a migration of every caller.-//!-//! - [`node`] — the Node toolchain client, plus the ungated native-tool-//! bridge that shares its directory-//! - [`python`] — the Python interpreter client, plus stdio child launch-//! - [`python_server`] — the persistent Python worker process-//! - [`pool`] — pooled execution, and the fallback classification-//! - [`javascript`] — JavaScript evaluation surface-//!-//! The archive and HTTP dependencies these modules used to carry went with the-//! machinery: a client that asks a module for a path needs neither a-//! decompressor nor a download pipeline.--pub mod client;-pub mod javascript;-pub mod node;-pub mod pool;-pub mod python;-pub mod python_server;diff --git a/crates/openhuman-core/src/runtime/node/README.md b/crates/openhuman-core/src/runtime/node/README.mddeleted file mode 100644index d0bd5d8d43..0000000000--- a/crates/openhuman-core/src/runtime/node/README.md+++ /dev/null@@ -1,145 +0,0 @@-# runtime/node--Two unrelated things share this directory, and the difference is the first thing-to understand about it.--**The toolchain client** asks the `tinyruntime` module for a Node.js toolchain-and adapts the answer onto `ResolvedNode`, so `node_exec`, `npm_exec`, `shell`,-and Node-dependent skills have a trusted `node`/`npm` on a stable path.--**The tool bridge** exposes the full agent tool registry over JSON-RPC under-`javascript.*`, so an embedded JS host can enumerate and run tools by name. It-has nothing to do with Node beyond being reachable from JavaScript, which is why-it is not gated with the rest.--The public-facing language slot is the sibling [`javascript`](../javascript/)-module, which re-exports this module's surface under `javascript`-prefixed names.--## What moved out--Everything that used to make this the largest module in `runtime/`: system-node-probing, distribution selection, `SHASUMS256.txt` fetching, streaming download-with SHA-256 verification, `.tar.xz` / `.zip` extraction, atomic install, cache-roots, and the guards against a workspace-vendored fake install tree.--That is all in the `tinyruntime` module now, where one implementation serves-every language, and it is reached through-[`modules::runtime`](../../modules/runtime.rs). The visible consequence for this-repository is that `xz2` and its static liblzma C build left the manifest-entirely, the first native toolchain build removed rather than merely gated.--## Responsibilities--- Ask the module to resolve a Node toolchain, installing one when the host has- none, and adapt the reply onto `ResolvedNode` (`node_bin`, `npm_bin`,- `bin_dir`, `version`, `source`).-- Memoise that answer locally so `try_cached()` can answer **without awaiting**.- The shell consults it on every command to decide whether to prepend a managed- `bin/` directory to `PATH`, and a blocking call there would make every- unrelated command wait on a bus round trip.-- Build the full agent tool registry on demand and expose two RPC controllers:- list tool metadata, and execute a named tool returning an MCP-style- `ToolResult`.-- Publish `ToolExecutionStarted` / `ToolExecutionCompleted` around bridge tool- execution.--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | Export-focused: submodule decls, the `runtime-node` gate, and `pub use` re-exports including the controller registry pair. |-| [`bootstrap.rs`](./bootstrap.rs) | The toolchain client. `NodeBootstrap` (`resolve`, `probe_installed`, `try_cached`), `ResolvedNode`, `NodeSource`. Adapts a module `ResolvedRuntime`; derives `npm` when the provider does not report it. |-| [`stub.rs`](./stub.rs) | Type surface for `runtime-node`-less builds. `try_cached`/`probe_installed` return `None`; `resolve` errors with a build fact. |-| [`ops.rs`](./ops.rs) | Bridge logic: `build_runtime_tools`, `list_tools`, `execute_tool` (event publish + timing). |-| [`rpc.rs`](./rpc.rs) | RPC param structs and `*_handler` fns; loads config and delegates through the `javascript` alias. |-| [`schemas.rs`](./schemas.rs) | Controller schemas + registered controllers for `javascript_list_tools` / `javascript_execute_tool`. |-| [`types.rs`](./types.rs) | `RuntimeToolSummary`, `ExecuteToolOutcome` serde types. |--## Public surface--- Client: `NodeBootstrap`, `NodeSource`, `ResolvedNode`.-- Bridge ops: `execute_tool`, `list_tools`.-- Types: `RuntimeToolSummary`, `ExecuteToolOutcome` (via `types`).-- Controller registry pair: `all_runtime_node_controller_schemas`,- `all_runtime_node_registered_controllers`.--## RPC / controllers--Registered under namespace `javascript` (schemas wired into `crates/openhuman-core/src/core/all.rs`-via the `javascript` module's `all_javascript_*` aliases, not under a-`runtime_node` name):--| Method | Inputs | Output |-| --- | --- | --- |-| `javascript.list_tools` | none | `tools`: array of tool metadata. |-| `javascript.execute_tool` | `tool_name` (required), `args` (optional, defaults `{}`), `prefer_markdown` (optional bool) | `tool_name`, `elapsed_ms`, `result`. |--Unknown tool name → error ``unknown tool `<name>` ``.--## Agent tools--This module owns **no** tools of its own. It builds the *entire* agent tool-registry on demand (`tools::all_tools_with_runtime`) to back the bridge. The-`node_exec`, `npm_exec`, and `shell` tools live in-`crates/openhuman-core/src/tools/impl/system/` and consume this module's `NodeBootstrap`.--## Events--`ops::execute_tool` publishes around each bridge invocation, with-`session_id = "javascript"`:--- `DomainEvent::ToolExecutionStarted`-- `DomainEvent::ToolExecutionCompleted` (with `success`, `elapsed_ms`)--## Persistence--**None here any more.** The managed install cache belongs to the `tinyruntime`-module, which decides where it lives from the settings each request carries.-This module reads `config.node` (`enabled`, `prefer_system`, `version`,-`cache_dir`) only to build those requests.--## Dependencies--- `crate::modules::runtime`: the module client this delegates to.-- `crate::config`: the settings each request carries.-- `crate::tools`, `security`, `agent::host_runtime`, `memory`: the- registry the bridge enumerates and executes.-- `crate::core::bus::BUS` / `crate::core::events::DomainEvent`,- `crate::core::all`, `crate::core::Outcome`: events and controller plumbing.--External crates: `tinyruntime-bus`, `tokio`, `anyhow`, `serde`/`serde_json`,-`tracing`, `async-trait`. No HTTP client, no archive crates, and no digest-crate: those went with the machinery.--## Used by--- `crates/openhuman-core/src/runtime/javascript/mod.rs`: the public language slot.-- `crates/openhuman-core/src/tools/impl/system/{node_exec,npm_exec,shell}.rs`: hold an- `Arc<NodeBootstrap>`; the exec tools call `resolve()`, `shell` uses the- non-blocking `try_cached()`.-- `crates/openhuman-core/src/core/all.rs`: registers the `javascript.*` controllers.--## Notes / gotchas--- Naming asymmetry: the directory is `node` but its RPC namespace and public- aliases are `javascript`. That indirection is what let the backend underneath- be replaced by a bus module without churning a single caller.-- `build_runtime_tools` is not cheap: each bridge call rebuilds the full tool- registry from `Config`. There is no caching at the bridge layer: the- memoisation here is only for toolchain resolution.-- **The local cache is not redundant with the module's.** The module memoises- too, but only this one can answer without awaiting, which is the entire reason- the shell can inject `PATH` without blocking.-- **Version policy lives in the provider now.** Major-only matching, and the- `prefer_system = false` escape hatch for strict pinning, are decisions of- `tinyruntime-nodejs`; this module carries the setting rather than the rule.-- **A toolchain without `npm` still resolves.** `npm_bin` is derived when the- provider does not report it: refusing would take `node_exec` down along with- `npm_exec`, for an install that runs `node` perfectly well.--## Further reading--- [Parent module (`runtime`)](../README.md)-- [tinyruntime submodule](../../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/node/bootstrap.rs b/crates/openhuman-core/src/runtime/node/bootstrap.rsdeleted file mode 100644index f9f38d9efc..0000000000--- a/crates/openhuman-core/src/runtime/node/bootstrap.rs+++ /dev/null@@ -1,229 +0,0 @@-//! Node.js toolchain resolution, delegated to the `tinyruntime` module.-//!-//! This used to be the orchestrator for a download-and-install pipeline: probe-//! the host, fetch a distribution, verify its digest, unpack it, promote it into-//! a cache, and remember it. All of that now lives in the `tinyruntime` module,-//! which does it identically for every language, so what is left here is the-//! adapter that turns a module answer into the [`ResolvedNode`] this core's-//! callers already name.-//!-//! # Why the type survived the move-//!-//! `ShellTool` holds an `Option<Arc<NodeBootstrap>>` as a field and is kernel —-//! always compiled. Keeping the type and its three methods meant the migration-//! did not have to touch the shell, the two exec tools, or the harness-//! initialiser, which is what made it reviewable.-//!-//! # The cache is still here, and still earns its place-//!-//! The module memoises resolution too, so this looks redundant. It is not:-//! [`try_cached`](NodeBootstrap::try_cached) must answer *without awaiting*,-//! because the shell consults it on every command to decide whether to prepend a-//! managed `bin/` directory to `PATH`. A blocking call there would make every-//! unrelated shell command wait on a bus round trip, and a download on the first-//! one.--use std::path::PathBuf;-use std::sync::{Arc, Mutex};--use anyhow::{anyhow, Result};-use tinyruntime_bus::{Language, ResolvedRuntime, RuntimeSource};--use crate::config::Config;-use crate::runtime::client as runtime;--/// Origin of the resolved toolchain — feeds into logging and lets the caller-/// decide whether to surface a "Node was downloaded to …" message in the UI.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum NodeSource {- /// Reused a compatible `node` already on the host.- System,- /// A managed distribution the module downloaded and installed.- Managed,-}--impl From<RuntimeSource> for NodeSource {- fn from(source: RuntimeSource) -> Self {- match source {- RuntimeSource::System => Self::System,- // A source this build does not know is a module from a newer- // contract. Managed is the safe reading: it is the one that makes a- // caller treat the toolchain as something the core provisioned.- _ => Self::Managed,- }- }-}--/// Fully-resolved Node.js toolchain.-#[derive(Debug, Clone)]-pub struct ResolvedNode {- /// Directory to prepend to `PATH` for child processes so `node`, `npm`,- /// `npx`, and `corepack` resolve to this toolchain's binaries.- pub bin_dir: PathBuf,- /// Absolute path to the `node` binary.- pub node_bin: PathBuf,- /// Absolute path to the `npm` launcher.- ///- /// The launcher, not the script it points at: the Unix distributions ship- /// `bin/npm` as a symlink into a JavaScript file under `lib/`, and invoking- /// that file directly is not the supported contract.- pub npm_bin: PathBuf,- /// Version string without the leading `v`, e.g. `22.11.0`.- pub version: String,- /// Where the toolchain came from.- pub source: NodeSource,-}--impl ResolvedNode {- /// Adapt a module resolution, or say what it was missing.- ///- /// `npm` is derived when the provider does not report it rather than being- /// required: a toolchain without `npm` is unusual but perfectly able to run- /// `node`, and refusing the whole resolution would take `node_exec` down- /// with `npm_exec`.- fn from_module(resolved: &ResolvedRuntime) -> Result<Self> {- let bin_dir = PathBuf::from(&resolved.bin_dir);- let node_bin = resolved- .executable("node")- .map(PathBuf::from)- .ok_or_else(|| anyhow!("the resolved node toolchain reports no `node` binary"))?;- let npm_bin = resolved.executable("npm").map_or_else(- || bin_dir.join(if cfg!(windows) { "npm.cmd" } else { "npm" }),- PathBuf::from,- );-- Ok(Self {- bin_dir,- node_bin,- npm_bin,- version: resolved- .version- .trim_start_matches(['v', 'V'])- .trim()- .to_string(),- source: resolved.source.into(),- })- }-}--/// Resolves the Node.js toolchain through the `tinyruntime` module.-///-/// Hold one per session so every tool that needs Node shares the same memoised-/// answer rather than each asking the bus.-pub struct NodeBootstrap {- config: Arc<Config>,- /// The last resolution, for the non-awaiting [`NodeBootstrap::try_cached`].- cached: Mutex<Option<ResolvedNode>>,-}--impl std::fmt::Debug for NodeBootstrap {- /// `Config` is large and full of secrets; what identifies a bootstrap is- /// whether it has resolved yet.- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- formatter- .debug_struct("NodeBootstrap")- .field("resolved", &self.try_cached().is_some())- .finish_non_exhaustive()- }-}--impl NodeBootstrap {- /// Build a bootstrap over this host's configuration.- #[must_use]- pub fn new(config: Arc<Config>) -> Self {- Self {- config,- cached: Mutex::new(None),- }- }-- /// The configuration this bootstrap resolves under.- ///- /// Exposed because the pooled-execution path needs the same configuration to- /// build its request, and threading a second copy through every tool would- /// give two answers to "which version".- #[must_use]- pub fn config(&self) -> &Config {- &self.config- }-- /// The memoised toolchain, without awaiting anything.- ///- /// Returns `None` when nothing has resolved yet. Callers use this where a- /// blocking wait would change the meaning of an unrelated operation — the- /// shell's `PATH` injection being the one that matters.- #[must_use]- pub fn try_cached(&self) -> Option<ResolvedNode> {- self.cached.lock().ok().and_then(|guard| guard.clone())- }-- /// Report an already-provisioned toolchain, without downloading one.- ///- /// Asks the module to resolve without installing, so a warm start detects an- /// existing install and a cold one reports nothing rather than spending a- /// user's first minute on a download they did not ask for.- pub async fn probe_installed(&self) -> Option<ResolvedNode> {- if let Some(existing) = self.try_cached() {- return Some(existing);- }- if !self.config.node.enabled {- return None;- }- match runtime::resolve(&self.config, &Language::nodejs(), false).await {- Ok(Some(resolved)) => self.adopt(&resolved).ok(),- Ok(None) => {- tracing::debug!(- "[runtime::node] no node toolchain is provisioned yet (provisioning required)"- );- None- }- Err(error) => {- tracing::debug!("[runtime::node] probing for a node toolchain failed: {error}");- None- }- }- }-- /// Resolve the toolchain, installing a managed one if the host has none.- ///- /// # Errors- ///- /// When Node is disabled for this host, when the module or its provider- /// cannot be loaded, or when provisioning fails.- pub async fn resolve(&self) -> Result<ResolvedNode> {- if let Some(existing) = self.try_cached() {- return Ok(existing);- }- if !self.config.node.enabled {- return Err(anyhow!(- "the node runtime is disabled (set node.enabled = true to use tools that need node or npm)"- ));- }-- let resolved = runtime::resolve(&self.config, &Language::nodejs(), true)- .await- .map_err(|error| anyhow!("{error}"))?- .ok_or_else(|| {- anyhow!("the node runtime module reported no toolchain and did not say why")- })?;- self.adopt(&resolved)- }-- /// Adapt a module resolution and remember it.- fn adopt(&self, resolved: &ResolvedRuntime) -> Result<ResolvedNode> {- let adapted = ResolvedNode::from_module(resolved)?;- tracing::info!(- version = %adapted.version,- source = ?adapted.source,- "[runtime::node] node toolchain ready"- );- if let Ok(mut cached) = self.cached.lock() {- *cached = Some(adapted.clone());- }- Ok(adapted)- }-}--#[cfg(test)]-#[path = "bootstrap_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/node/bootstrap_tests.rs b/crates/openhuman-core/src/runtime/node/bootstrap_tests.rsdeleted file mode 100644index 55e5398eaa..0000000000--- a/crates/openhuman-core/src/runtime/node/bootstrap_tests.rs+++ /dev/null@@ -1,113 +0,0 @@-//! Tests for the Node toolchain client.-//!-//! What is worth testing here is the adaptation, not the resolution: the module-//! owns probing, downloading, verifying, and installing, and it has its own-//! suite for all of it. These cover the seam — how a module answer becomes a-//! [`ResolvedNode`], and what happens when the host has Node turned off.--use std::sync::Arc;--use tinyruntime_bus::{Language, ResolvedRuntime, RuntimeLayout, RuntimeSource};--use super::{NodeBootstrap, NodeSource, ResolvedNode};-use crate::config::Config;--/// A module resolution carrying `executables`.-fn resolution(executables: &[(&str, &str)]) -> ResolvedRuntime {- let mut layout = RuntimeLayout::new("22.11.0", "/cache/node-v22.11.0/bin");- for (name, path) in executables {- layout = layout.with_executable(*name, *path);- }- ResolvedRuntime::from_layout(Language::nodejs(), RuntimeSource::Managed, layout)-}--#[test]-fn a_resolution_becomes_the_paths_callers_name() {- let adapted = ResolvedNode::from_module(&resolution(&[- ("node", "/cache/node-v22.11.0/bin/node"),- ("npm", "/cache/node-v22.11.0/bin/npm"),- ]))- .expect("a toolchain reporting node adapts");-- assert_eq!(- adapted.node_bin,- std::path::Path::new("/cache/node-v22.11.0/bin/node")- );- assert_eq!(- adapted.npm_bin,- std::path::Path::new("/cache/node-v22.11.0/bin/npm")- );- assert_eq!(- adapted.bin_dir,- std::path::Path::new("/cache/node-v22.11.0/bin")- );- assert_eq!(adapted.version, "22.11.0");- assert_eq!(adapted.source, NodeSource::Managed);-}--#[test]-fn a_toolchain_without_npm_still_resolves() {- // Refusing here would take `node_exec` down along with `npm_exec`, for a- // toolchain that runs `node` perfectly well.- let adapted = ResolvedNode::from_module(&resolution(&[("node", "/usr/bin/node")]))- .expect("a toolchain without npm is still usable");- assert_eq!(adapted.node_bin, std::path::Path::new("/usr/bin/node"));- assert!(- adapted- .npm_bin- .ends_with(if cfg!(windows) { "npm.cmd" } else { "npm" }),- "npm was not derived: {}",- adapted.npm_bin.display()- );-}--#[test]-fn a_toolchain_without_node_is_refused() {- // Deriving `node` too would turn a broken install into a spawn failure much- // later, with nothing pointing at the cause.- let error = ResolvedNode::from_module(&resolution(&[("npm", "/usr/bin/npm")]))- .expect_err("a toolchain with no node is not a toolchain");- assert!(error.to_string().contains("`node`"), "got `{error}`");-}--#[test]-fn the_version_never_keeps_a_leading_v() {- // Callers render this and compare it; `v22.11.0` and `22.11.0` reaching- // different call sites is exactly the drift the normalisation prevents.- let mut resolved = resolution(&[("node", "/usr/bin/node")]);- resolved.version = "v22.11.0".to_string();- let adapted = ResolvedNode::from_module(&resolved).expect("adapts");- assert_eq!(adapted.version, "22.11.0");-}--#[test]-fn a_system_toolchain_is_reported_as_one() {- let mut resolved = resolution(&[("node", "/usr/bin/node")]);- resolved.source = RuntimeSource::System;- assert_eq!(- ResolvedNode::from_module(&resolved).expect("adapts").source,- NodeSource::System- );-}--#[tokio::test]-async fn a_disabled_runtime_refuses_before_reaching_the_bus() {- let mut config = Config::default();- config.node.enabled = false;- let bootstrap = NodeBootstrap::new(Arc::new(config));-- let error = bootstrap.resolve().await.expect_err("node is off");- assert!(error.to_string().contains("disabled"), "got `{error}`");- assert!(- bootstrap.probe_installed().await.is_none(),- "a disabled runtime has nothing provisioned"- );-}--#[test]-fn nothing_is_cached_before_the_first_resolution() {- // The shell consults this on every command; answering with a stale or- // invented toolchain would put the wrong directory on PATH.- let bootstrap = NodeBootstrap::new(Arc::new(Config::default()));- assert!(bootstrap.try_cached().is_none());-}diff --git a/crates/openhuman-core/src/runtime/node/mod.rs b/crates/openhuman-core/src/runtime/node/mod.rsdeleted file mode 100644index ddc4f4534d..0000000000--- a/crates/openhuman-core/src/runtime/node/mod.rs+++ /dev/null@@ -1,51 +0,0 @@-//! Managed Node.js runtime and the generic tool bridge.-//!-//! Two unrelated things share this directory, and the difference matters:-//!-//! * [`bootstrap`] is the *client* for the `tinyruntime` module. It asks for a-//! Node toolchain and adapts the answer. It downloads nothing, unpacks-//! nothing, and manages no cache — the module owns all of that now.-//! * [`ops`] and [`types`] are the generic native-tool dispatcher over the agent-//! tool registry (`oh:*` tools such as `memory_search`, file, and shell-//! tools). They have nothing to do with Node beyond being reachable from-//! JavaScript, which is why they are not gated below.-//!-//! ## Gating (`runtime-node`)-//!-//! The module is always declared, but the managed-Node client and the-//! `javascript.*` controller pair are `#[cfg(feature = "runtime-node")]`; a-//! [`stub`] carries [`NodeBootstrap`]'s type surface when the feature is off.-//! The forcing constraint is `ShellTool`, which holds-//! `Option<Arc<NodeBootstrap>>` as a field and is kernel — always compiled.-//!-//! [`ops`] and [`types`] stay ungated because they back both the gated-//! `javascript.*` controllers *and* the ungated `flows` `oh:` backend, which-//! must keep dispatching native tools when the managed Node runtime is compiled-//! out.--#[cfg(feature = "runtime-node")]-pub mod bootstrap;-#[cfg(feature = "runtime-node")]-pub mod rpc;-#[cfg(feature = "runtime-node")]-mod schemas;--/// Generic runtime tool bridge. Always compiled — see module docs.-pub mod ops;-/// Inert serde types shared by [`ops`] and the gated JS RPC. Always compiled.-pub mod types;--#[cfg(not(feature = "runtime-node"))]-mod stub;-#[cfg(not(feature = "runtime-node"))]-pub use stub::{NodeBootstrap, NodeSource, ResolvedNode, RUNTIME_NODE_DISABLED_MESSAGE};--#[cfg(feature = "runtime-node")]-pub use bootstrap::{NodeBootstrap, NodeSource, ResolvedNode};-pub use ops::{execute_tool, list_tools};-#[cfg(feature = "runtime-node")]-pub use schemas::{- all_controller_schemas as all_runtime_node_controller_schemas,- all_registered_controllers as all_runtime_node_registered_controllers,-};-pub use types::ExecuteToolOutcome;diff --git a/crates/openhuman-core/src/runtime/node/ops_tests.rs b/crates/openhuman-core/src/runtime/node/ops_tests.rsdeleted file mode 100644index eaa6efc4fd..0000000000--- a/crates/openhuman-core/src/runtime/node/ops_tests.rs+++ /dev/null@@ -1,159 +0,0 @@-use super::*;-use async_trait::async_trait;-use serde_json::json;--struct DummyTool;--#[async_trait]-impl Tool for DummyTool {- fn name(&self) -> &str {- "dummy_tool"- }-- fn description(&self) -> &str {- "Dummy tool"- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({"type": "object"})- }-- async fn execute(- &self,- _args: serde_json::Value,- ) -> anyhow::Result<crate::skills::types::ToolResult> {- Ok(crate::skills::types::ToolResult::success("ok"))- }-}--struct PolicyTool {- name: &'static str,- permission: PermissionLevel,- external_effect: bool,-}--#[async_trait]-impl Tool for PolicyTool {- fn name(&self) -> &str {- self.name- }-- fn description(&self) -> &str {- "Policy test tool"- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({"type": "object"})- }-- fn permission_level(&self) -> PermissionLevel {- self.permission- }-- fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {- self.external_effect- }-- async fn execute(- &self,- _args: serde_json::Value,- ) -> anyhow::Result<crate::skills::types::ToolResult> {- Ok(crate::skills::types::ToolResult::success("ok"))- }-}--#[test]-fn summarize_tool_exposes_metadata() {- let summary = summarize_tool(&DummyTool);- assert_eq!(summary.name, "dummy_tool");- assert_eq!(summary.category, "system");- assert_eq!(summary.permission_level, "ReadOnly");- assert_eq!(summary.scope, "all");-}--#[test]-fn tool_scope_labels_are_stable() {- assert_eq!(tool_scope_label(ToolScope::All), "all");- assert_eq!(tool_scope_label(ToolScope::AgentOnly), "agent_only");- assert_eq!(tool_scope_label(ToolScope::CliRpcOnly), "cli_rpc_only");-}--#[test]-fn command_class_for_tool_maps_metadata_to_policy_buckets() {- let security = SecurityPolicy::default();-- let read = PolicyTool {- name: "read_tool",- permission: PermissionLevel::ReadOnly,- external_effect: false,- };- assert_eq!(- command_class_for_tool(&security, &read, &json!({})),- CommandClass::Read- );-- let write = PolicyTool {- name: "write_tool",- permission: PermissionLevel::Write,- external_effect: false,- };- assert_eq!(- command_class_for_tool(&security, &write, &json!({})),- CommandClass::Write- );-- let outbound = PolicyTool {- name: "outbound_tool",- permission: PermissionLevel::Write,- external_effect: true,- };- assert_eq!(- command_class_for_tool(&security, &outbound, &json!({})),- CommandClass::Network- );-- let dangerous = PolicyTool {- name: "dangerous_tool",- permission: PermissionLevel::Dangerous,- external_effect: true,- };- assert_eq!(- command_class_for_tool(&security, &dangerous, &json!({})),- CommandClass::Destructive- );-}--#[test]-fn command_class_for_shell_uses_command_args() {- let security = SecurityPolicy::default();- let shell = PolicyTool {- name: "shell",- permission: PermissionLevel::Execute,- external_effect: true,- };-- assert_eq!(- command_class_for_tool(&security, &shell, &json!({"command": "ls src"})),- CommandClass::Read- );- assert_eq!(- command_class_for_tool(&security, &shell, &json!({"command": "touch out.txt"})),- CommandClass::Write- );- assert_eq!(- command_class_for_tool(- &security,- &shell,- &json!({"command": "curl https://example.com"})- ),- CommandClass::Network- );- assert_eq!(- command_class_for_tool(- &security,- &shell,- &json!({"command": "cat Cargo.toml", "category": "destructive"})- ),- CommandClass::Destructive- );-}diff --git a/crates/openhuman-core/src/runtime/node/rpc.rs b/crates/openhuman-core/src/runtime/node/rpc.rsdeleted file mode 100644index 602382ab69..0000000000--- a/crates/openhuman-core/src/runtime/node/rpc.rs+++ /dev/null@@ -1,58 +0,0 @@-use serde::Deserialize;-use serde_json::{json, Value};--use crate::config::rpc as config_rpc;-use crate::core::Outcome;-use crate::runtime::javascript;--#[derive(Debug, Deserialize, Default)]-pub(crate) struct ListToolsParams {}--#[derive(Debug, Deserialize)]-pub(crate) struct ExecuteToolParams {- pub(crate) tool_name: String,- #[serde(default)]- pub(crate) args: Value,- #[serde(default)]- pub(crate) prefer_markdown: bool,-}--pub(crate) async fn list_tools_handler(- _params: ListToolsParams,-) -> Result<serde_json::Value, String> {- let config = config_rpc::load_config_with_timeout().await?;- let tools = javascript::list_tools(&config)?;- let payload = json!({ "tools": tools });- let log = vec![format!(- "javascript.list_tools: count={}",- payload["tools"]- .as_array()- .map(|tools| tools.len())- .unwrap_or(0)- )];- Outcome::new(payload, log).into_cli_compatible_json()-}--pub(crate) async fn execute_tool_handler(- params: ExecuteToolParams,-) -> Result<serde_json::Value, String> {- let config = config_rpc::load_config_with_timeout().await?;- let args = if params.args.is_null() {- json!({})- } else {- params.args- };- let outcome =- javascript::execute_tool(&config, ¶ms.tool_name, args, params.prefer_markdown).await?;- let payload = json!({- "tool_name": outcome.tool_name,- "elapsed_ms": outcome.elapsed_ms,- "result": outcome.result,- });- let log = vec![format!(- "javascript.execute_tool: tool_name={} elapsed_ms={}",- payload["tool_name"].as_str().unwrap_or("<unknown>"),- payload["elapsed_ms"].as_u64().unwrap_or(0)- )];- Outcome::new(payload, log).into_cli_compatible_json()-}diff --git a/crates/openhuman-core/src/runtime/node/schemas.rs b/crates/openhuman-core/src/runtime/node/schemas.rsdeleted file mode 100644index f6b9f51750..0000000000--- a/crates/openhuman-core/src/runtime/node/schemas.rs+++ /dev/null@@ -1,121 +0,0 @@-use serde_json::{Map, Value};--use crate::core::all::{ControllerFuture, RegisteredController};-use crate::core::{ControllerSchema, FieldSchema, TypeSchema};-use crate::runtime::node::rpc::{- execute_tool_handler, list_tools_handler, ExecuteToolParams, ListToolsParams,-};--pub fn all_controller_schemas() -> Vec<ControllerSchema> {- vec![- schemas("javascript_list_tools"),- schemas("javascript_execute_tool"),- ]-}--pub fn all_registered_controllers() -> Vec<RegisteredController> {- vec![- RegisteredController {- schema: schemas("javascript_list_tools"),- handler: handle_list_tools,- },- RegisteredController {- schema: schemas("javascript_execute_tool"),- handler: handle_execute_tool,- },- ]-}--pub fn schemas(function: &str) -> ControllerSchema {- match function {- "javascript_list_tools" => ControllerSchema {- namespace: "javascript",- function: "list_tools",- description: "List the agent-callable tool registry exposed through the JavaScript runtime bridge.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "tools",- ty: TypeSchema::Array(Box::new(TypeSchema::Json)),- comment: "List of tool metadata objects: name, description, category, permission_level, scope, supports_markdown, parameters.",- required: true,- }],- },- "javascript_execute_tool" => ControllerSchema {- namespace: "javascript",- function: "execute_tool",- description: "Execute a named tool through the JavaScript runtime bridge and return its MCP-style ToolResult envelope.",- inputs: vec![- FieldSchema {- name: "tool_name",- ty: TypeSchema::String,- comment: "Exact tool name returned by javascript.list_tools.",- required: true,- },- FieldSchema {- name: "args",- ty: TypeSchema::Option(Box::new(TypeSchema::Json)),- comment: "Tool argument object. Defaults to an empty object.",- required: false,- },- FieldSchema {- name: "prefer_markdown",- ty: TypeSchema::Option(Box::new(TypeSchema::Bool)),- comment: "Hint to tools that can return a compact markdown rendering for LLM consumption.",- required: false,- },- ],- outputs: vec![- FieldSchema {- name: "tool_name",- ty: TypeSchema::String,- comment: "Echo of the executed tool name.",- required: true,- },- FieldSchema {- name: "elapsed_ms",- ty: TypeSchema::U64,- comment: "Wall-clock execution time in milliseconds.",- required: true,- },- FieldSchema {- name: "result",- ty: TypeSchema::Json,- comment: "MCP-style ToolResult payload: {content, is_error, markdownFormatted?}.",- required: true,- },- ],- },- _ => ControllerSchema {- namespace: "javascript",- function: "unknown",- description: "Unknown javascript controller.",- inputs: vec![],- outputs: vec![FieldSchema {- name: "error",- ty: TypeSchema::String,- comment: "Lookup error details.",- required: true,- }],- },- }-}--fn handle_list_tools(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let params: ListToolsParams =- serde_json::from_value(Value::Object(params)).map_err(|error| error.to_string())?;- list_tools_handler(params).await- })-}--fn handle_execute_tool(params: Map<String, Value>) -> ControllerFuture {- Box::pin(async move {- let params: ExecuteToolParams =- serde_json::from_value(Value::Object(params)).map_err(|error| error.to_string())?;- execute_tool_handler(params).await- })-}--#[cfg(test)]-#[path = "schemas_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/node/schemas_tests.rs b/crates/openhuman-core/src/runtime/node/schemas_tests.rsdeleted file mode 100644index 621bcb441c..0000000000--- a/crates/openhuman-core/src/runtime/node/schemas_tests.rs+++ /dev/null@@ -1,21 +0,0 @@-use super::*;--#[test]-fn catalog_lists_both_runtime_controllers() {- let schemas = all_controller_schemas();- assert_eq!(schemas.len(), 2);- let names: Vec<&str> = schemas.iter().map(|schema| schema.function).collect();- assert!(names.contains(&"list_tools"));- assert!(names.contains(&"execute_tool"));-}--#[test]-fn execute_tool_schema_requires_tool_name() {- let schema = schemas("javascript_execute_tool");- assert_eq!(schema.namespace, "javascript");- assert_eq!(schema.function, "execute_tool");- assert!(schema- .inputs- .iter()- .any(|field| field.name == "tool_name" && field.required));-}diff --git a/crates/openhuman-core/src/runtime/node/stub.rs b/crates/openhuman-core/src/runtime/node/stub.rsdeleted file mode 100644index 48c28952f3..0000000000--- a/crates/openhuman-core/src/runtime/node/stub.rs+++ /dev/null@@ -1,115 +0,0 @@-//! `runtime-node` disabled-build stub.-//!-//! Mirrors the *type* surface that always-compiled callers name, with no-op-//! behaviour. Only what is actually reached from outside the gate lives here.-//!-//! Why a stub rather than a leaf gate: [`NodeBootstrap`] appears in the **field-//! type** of `tools::impl::system::ShellTool` (`Option<Arc<NodeBootstrap>>`, for-//! managed-Node `PATH` injection), and `shell.rs` is kernel — always compiled.-//! Deleting the module would take the shell tool with it. The registration-//! sites (`node_runtime_step`, the `javascript` controllers, `node_exec` /-//! `npm_exec`) are leaf-gated at their call sites instead, because registration-//! sites want absence.-//!-//! Off-state: `try_cached` and `probe_installed` return `None`, so the shell-//! simply never prepends a managed `bin/` directory — the same path taken when-//! `node.enabled = false`. `resolve` is the one erroring method and returns a-//! build fact so a stray caller reports something actionable.-//!-//! Note: this stub carries **only** the Node toolchain type surface.-//! [`super::ops`] and [`super::types`] are not stubbed — they are the generic-//! native-tool dispatcher and its inert serde types, always compiled so the-//! ungated `flows` backend can keep dispatching `oh:*` tools when the managed-//! Node runtime is off.--use std::path::PathBuf;-use std::sync::Arc;--use anyhow::{anyhow, Result};--use crate::config::Config;--/// Returned by [`NodeBootstrap::resolve`] in a `runtime-node`-less build.-/// Phrased as a build fact, matching the `mcp` / `tui` CLI-arm convention.-pub const RUNTIME_NODE_DISABLED_MESSAGE: &str =- "runtime-node feature disabled at compile time — rebuild with `--features runtime-node` \- to use the managed Node.js toolchain";--/// Origin of a resolved toolchain. Never produced here; kept so caller `match`-/// arms and imports still resolve.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum NodeSource {- /// Reused a compatible `node` already on the host.- System,- /// A managed distribution.- Managed,-}--/// Fully-resolved Node toolchain. Never constructed in a disabled build.-#[derive(Debug, Clone)]-pub struct ResolvedNode {- /// Directory to prepend to `PATH`.- pub bin_dir: PathBuf,- /// Absolute path to the `node` binary.- pub node_bin: PathBuf,- /// Absolute path to the `npm` launcher.- pub npm_bin: PathBuf,- /// Version string without the leading `v`.- pub version: String,- /// Where the toolchain came from.- pub source: NodeSource,-}--/// Inert stand-in for the toolchain client.-pub struct NodeBootstrap {- config: Arc<Config>,-}--impl std::fmt::Debug for NodeBootstrap {- /// The real client redacts `Config` because it is full of secrets; the stub- /// mirrors that so the two render identically in logs, rather than the- /// disabled build being the one that leaks an `api_key` into a debug line.- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- formatter- .debug_struct("NodeBootstrap")- .field("resolved", &false)- .finish_non_exhaustive()- }-}--impl NodeBootstrap {- /// Build a stub over this host's configuration.- ///- /// Takes the same argument as the real client so construction sites do not- /// need their own gate.- #[must_use]- pub fn new(config: Arc<Config>) -> Self {- Self { config }- }-- /// The configuration this bootstrap would resolve under.- #[must_use]- pub fn config(&self) -> &Config {- &self.config- }-- /// Always `None`: nothing resolves in a disabled build.- #[must_use]- pub fn try_cached(&self) -> Option<ResolvedNode> {- None- }-- /// Always `None`: nothing is provisioned in a disabled build.- pub async fn probe_installed(&self) -> Option<ResolvedNode> {- None- }-- /// Always an error naming the missing feature.- ///- /// # Errors- ///- /// Always, with [`RUNTIME_NODE_DISABLED_MESSAGE`].- pub async fn resolve(&self) -> Result<ResolvedNode> {- Err(anyhow!(RUNTIME_NODE_DISABLED_MESSAGE))- }-}diff --git a/crates/openhuman-core/src/runtime/pool/README.md b/crates/openhuman-core/src/runtime/pool/README.mddeleted file mode 100644index 2cefb79992..0000000000--- a/crates/openhuman-core/src/runtime/pool/README.md+++ /dev/null@@ -1,81 +0,0 @@-# runtime/pool--The client for pooled inline execution. The pool itself (warm interpreter-children, the job protocol, backpressure, idle reaping, recycle-after-N) lives-in the `tinyruntime` module, where one implementation serves every language.--What is here is two decisions this core still owns.--## 1. Whether a language pools at all--| Language | Default | Why |-| --- | --- | --- |-| `node` | **on** | Each job runs in its own `worker_thread`: a fresh module graph and fresh globals per job, so reuse is safe. |-| `python` | **off** | Jobs share one interpreter. CPython has no worker-thread equivalent and no safe way to kill a running thread, so reuse leaks `sys.modules`, `os.environ`, logging handlers, and threads across unrelated runs. Opt in with `[runtime_pool.python] enabled = true`. |--`[runtime_pool] enabled = false` is the master switch and reverts every caller to-its legacy per-call spawn, with no behavioural change. Pooling is an optimisation-seam, not a dependency.--## 2. What a failure means for the caller--This is the subtle part, and the reason `PoolRunError` has three variants rather-than being one error type. Each drives different caller behaviour:--| Variant | The job… | The caller must… |-| --- | --- | --- |-| `PreDispatch` | provably never reached a worker | fall back to a per-call spawn (safe, because nothing ran) |-| `PostDispatch` | reached a worker and **may have executed** | **not** retry, or it risks running someone's code twice |-| `Saturated` | was shed because the pool was full | **not** spawn: that reintroduces exactly the resident memory the pool caps, so report busy or retry later |--`classify` maps the module's failures onto these. The default is `PreDispatch`,-and the asymmetry is deliberate: mistakenly treating a job as un-run costs one-extra fallback spawn, while mistakenly treating a run job as un-run duplicates-its side effects. Only the two signals the module states explicitly, capacity-and post-dispatch, move a failure out of the default.--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | `PoolRunError`, the shared `run_inline` dispatch, and `classify`. |-| [`node.rs`](./node.rs) / [`python.rs`](./python.rs) | Per-language `enabled()` and `run_inline()`; they differ only in which language they name. |-| [`types.rs`](./types.rs) | `PoolExecOutcome` (with `queue_wait` kept apart from `elapsed`), `PoolLang`, `PoolSettings`. |--## Why it exists--At the target deployment density (100-1000 live agents on a 2 GB, 2 vCPU box),-a fresh interpreter child per run is the biggest memory cost: one JS skill-step spawns a `node` child at roughly 72-75 MB RSS. A small, bounded pool of-warm workers turns "K concurrent skill runs, K interpreters" into "K-concurrent skill runs, about one pooled worker", at the cost of queueing work-beyond the pool size. This is one piece of the density work described in-[performance.md](../../../../../gitbooks/developing/performance.md).--## Defaults (`[runtime_pool]`, `config/schema/runtime_pool.rs`)--| Setting | Default | Meaning |-| --- | --- | --- |-| `max_workers` | 2 | concurrently resident workers per language; clamped to at least 1 |-| `idle_ttl_secs` | 60 | reap a worker idle this long; `0` disables idle reaping |-| `recycle_after_jobs` | 100 | retire a worker after this many jobs; `0` disables recycling |-| `max_queue_depth` | 256 | jobs allowed to queue before new submissions are rejected; clamped to at least 1 |--Node pools by default (`worker_thread` isolation makes reuse safe); Python-does not (CPython has no safe way to kill a running thread, so reuse can leak-state across jobs). Set `enabled` explicitly per language to override.--## Notes--- **`queue_wait` is reported separately from `elapsed` on purpose.** A host that- cannot tell a slow job from a busy pool will tune the wrong knob.-- **A worker is still a child of this process.** A TinyBus module is a `cdylib`- loaded in-process, so the resident cost and the process-tree shape the- `library-profile skill-run` gate asserts on are unchanged by the move.--## Further reading--- [Parent module (`runtime`)](../README.md)-- [tinyruntime submodule](../../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/pool/mod.rs b/crates/openhuman-core/src/runtime/pool/mod.rsdeleted file mode 100644index 09c94ac364..0000000000--- a/crates/openhuman-core/src/runtime/pool/mod.rs+++ /dev/null@@ -1,103 +0,0 @@-//! Pooled execution of inline code, delegated to the `tinyruntime` module.-//!-//! The pool itself — warm interpreter children, the newline-delimited job-//! protocol, backpressure, idle reaping, recycle-after-N — moved into that-//! module, where one implementation serves every language. What is left here is-//! the client: whether this host wants pooling for a language, and the mapping-//! from a module reply back onto the shapes the exec tools already handle.-//!-//! # Why the local types survived-//!-//! [`PoolExecOutcome`] and [`PoolRunError`] are what `node_exec` and-//! `python_exec` match on to decide between reporting a result, falling back to-//! a per-call spawn, and refusing to retry. Keeping them meant the migration did-//! not have to rewrite either tool's dispatch logic — and the three-way-//! distinction they encode is the one that keeps a job from running twice.-//!-//! # The fallback is still real-//!-//! A pre-dispatch failure sends the caller to its legacy per-call spawn, which-//! still exists and still works: the tools hold a resolved interpreter path from-//! the module and can run it directly. Pooling is an optimisation seam, exactly-//! as it was — `runtime_pool.enabled = false` reverts every caller with no-//! behavioural change.--pub mod node;-pub mod python;-pub mod types;--use tinyruntime_bus::Language;--use crate::config::Config;-use crate::runtime::client::{self as runtime, RuntimeCallError};--pub use types::{PoolExecOutcome, PoolLang, PoolSettings};--/// Why a pooled run failed, classified so callers know what is safe to do next.-#[derive(Debug)]-pub enum PoolRunError {- /// The pool was at capacity and shed the job rather than buffering it.- ///- /// Callers must **not** fall back to a per-call spawn: that reintroduces the- /// very resident memory the pool exists to cap. Surface a busy error or- /// retry later.- Saturated,- /// The job never reached a worker, so it never ran. A retry or a legacy- /// per-call spawn is safe.- PreDispatch(anyhow::Error),- /// The job reached a worker and may have executed. Terminal — re-running it- /// could duplicate whatever it already did.- PostDispatch(anyhow::Error),-}--impl std::fmt::Display for PoolRunError {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Self::Saturated => write!(f, "runtime pool at capacity"),- Self::PreDispatch(error) => write!(f, "pre-dispatch pool failure: {error:#}"),- Self::PostDispatch(error) => write!(f, "post-dispatch pool failure: {error:#}"),- }- }-}--/// Run one inline job on `language`'s pool.-///-/// Shared by the two language backends, which differ only in which language they-/// name — every other decision belongs to the module.-async fn run_inline(- config: &Config,- language: &Language,- code: String,- cwd: Option<std::path::PathBuf>,- timeout: Option<std::time::Duration>,-) -> Result<PoolExecOutcome, PoolRunError> {- let cwd = cwd.map(|path| path.to_string_lossy().into_owned());-- match runtime::execute(config, language, code, cwd, timeout).await {- Ok(response) => Ok(PoolExecOutcome::from_module(&response)),- Err(error) => Err(classify(&error)),- }-}--/// Map a module failure onto the three-way distinction callers act on.-///-/// The saturation and post-dispatch readings come from the module's own error-/// text, which is its contract with a host that renders it. Anything else is-/// pre-dispatch: the conservative reading for a *retryable* classification would-/// be wrong in the other direction — assuming a job ran when it did not merely-/// costs a fallback spawn, while assuming it did not when it did would run-/// someone's code twice.-fn classify(error: &RuntimeCallError) -> PoolRunError {- let message = error.to_string();- if message.contains("pool is at capacity") {- return PoolRunError::Saturated;- }- if message.contains("failed after dispatch") {- return PoolRunError::PostDispatch(anyhow::anyhow!("{message}"));- }- PoolRunError::PreDispatch(anyhow::anyhow!("{message}"))-}--#[cfg(test)]-#[path = "pool_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/pool/node.rs b/crates/openhuman-core/src/runtime/pool/node.rsdeleted file mode 100644index ca5f7bd37e..0000000000--- a/crates/openhuman-core/src/runtime/pool/node.rs+++ /dev/null@@ -1,44 +0,0 @@-//! Node.js pooled execution: whether this host wants it, and how to ask for it.--use std::path::PathBuf;-use std::time::Duration;--use tinyruntime_bus::Language;--use super::{PoolExecOutcome, PoolRunError};-use crate::config::{Config, RuntimePoolConfig};--/// A cancellable dispatch uses the owned-subprocess fallback: the pool has-/// no acknowledged per-job abort seam.-///-/// Whether inline `node` jobs should route through the pool.-///-/// Node defaults **on**: each job runs in its own `worker_thread`, so reuse is-/// safe — a fresh module graph and fresh globals per job.-#[must_use]-pub fn enabled(pool: &RuntimePoolConfig) -> bool {- if crate::tools::timeout::ProcessCleanup::is_active()- || crate::tools::timeout::CommandEnvironment::is_active()- {- tracing::debug!(- "[node_exec] cancellable turn uses an owned subprocess instead of the pool"- );- return false;- }- pool.enabled && pool.node.is_enabled(true)-}--/// Run inline JavaScript on a pooled, warm `node` worker.-///-/// # Errors-///-/// [`PoolRunError`], classified so the caller knows whether falling back to a-/// per-call spawn is safe.-pub async fn run_inline(- config: &Config,- code: String,- cwd: Option<PathBuf>,- timeout: Option<Duration>,-) -> Result<PoolExecOutcome, PoolRunError> {- super::run_inline(config, &Language::nodejs(), code, cwd, timeout).await-}diff --git a/crates/openhuman-core/src/runtime/pool/pool_tests.rs b/crates/openhuman-core/src/runtime/pool/pool_tests.rsdeleted file mode 100644index 628f80e257..0000000000--- a/crates/openhuman-core/src/runtime/pool/pool_tests.rs+++ /dev/null@@ -1,89 +0,0 @@-//! Tests for the pooled-execution client.-//!-//! The pool's behaviour — warm workers, backpressure, recycling — belongs to the-//! `tinyruntime` module and is tested there. What is this core's decision is-//! whether a language pools by default, and how a module failure is classified,-//! because that classification is what keeps a job from running twice.--use super::{classify, node, python, PoolRunError};-use crate::config::Config;-use crate::runtime::client::RuntimeCallError;--#[test]-fn node_pools_by_default_and_python_does_not() {- // Not an oversight: a pooled Node job runs in its own worker thread with a- // fresh module graph, while a pooled Python job shares the interpreter with- // every other job on that worker.- let config = Config::default();- assert!(node::enabled(&config.runtime_pool));- assert!(!python::enabled(&config.runtime_pool));-}--#[test]-fn opting_python_in_turns_it_on() {- let mut config = Config::default();- config.runtime_pool.python.enabled = Some(true);- assert!(python::enabled(&config.runtime_pool));-}--#[test]-fn turning_the_pool_off_wholesale_turns_it_off_for_every_language() {- let mut config = Config::default();- config.runtime_pool.enabled = false;- config.runtime_pool.python.enabled = Some(true);- assert!(!node::enabled(&config.runtime_pool));- assert!(- !python::enabled(&config.runtime_pool),- "an explicit per-language opt-in must not survive the master switch"- );-}--#[test]-fn a_saturated_pool_is_recognised_so_the_caller_does_not_spawn() {- // Falling back to a per-call spawn here would reintroduce exactly the- // resident memory the pool exists to cap.- let error = RuntimeCallError::Failed("the `nodejs` runtime pool is at capacity".to_string());- assert!(matches!(classify(&error), PoolRunError::Saturated));-}--#[test]-fn a_post_dispatch_failure_is_recognised_so_the_job_is_not_re_run() {- // The distinction that matters most: this job may already have had its side- // effects, and a fallback spawn would repeat them.- let error = RuntimeCallError::Failed(- "the `nodejs` job failed after dispatch: the worker closed its protocol stream".to_string(),- );- assert!(matches!(classify(&error), PoolRunError::PostDispatch(_)));-}--#[test]-fn anything_else_is_pre_dispatch_so_the_caller_may_fall_back() {- // Including the module simply not being loaded: the job provably never ran,- // so the legacy per-call spawn is safe and is what keeps the tool working.- for error in [- RuntimeCallError::Unavailable("no artifact for this host".to_string()),- RuntimeCallError::Failed("the `nodejs` job could not be dispatched: no worker".to_string()),- RuntimeCallError::InvalidRequest("no runtime provider for `ruby`".to_string()),- ] {- assert!(- matches!(classify(&error), PoolRunError::PreDispatch(_)),- "`{error}` was not classified as pre-dispatch"- );- }-}--#[test]-fn the_three_classifications_render_distinguishably() {- // They drive opposite caller behaviour, so their messages must not blur.- assert_eq!(- PoolRunError::Saturated.to_string(),- "runtime pool at capacity"- );- let pre = PoolRunError::PreDispatch(anyhow::anyhow!("spawn failed")).to_string();- assert!(pre.starts_with("pre-dispatch pool failure:"), "got {pre}");- let post = PoolRunError::PostDispatch(anyhow::anyhow!("read wedged")).to_string();- assert!(- post.starts_with("post-dispatch pool failure:"),- "got {post}"- );-}diff --git a/crates/openhuman-core/src/runtime/pool/python.rs b/crates/openhuman-core/src/runtime/pool/python.rsdeleted file mode 100644index 420c85956c..0000000000--- a/crates/openhuman-core/src/runtime/pool/python.rs+++ /dev/null@@ -1,49 +0,0 @@-//! Python pooled execution: whether this host wants it, and how to ask for it.--use std::path::PathBuf;-use std::time::Duration;--use tinyruntime_bus::Language;--use super::{PoolExecOutcome, PoolRunError};-use crate::config::{Config, RuntimePoolConfig};--/// A cancellable dispatch uses the owned-subprocess fallback: the pool has-/// no acknowledged per-job abort seam.-///-/// Whether inline `python` jobs should route through the pool.-///-/// Python defaults **off**, and the asymmetry with Node is real rather than an-/// oversight. Jobs share one interpreter — CPython offers no worker-thread-/// equivalent and no safe way to kill a running thread — so reuse leaks-/// process-global state (`sys.modules`, `os.environ`, logging handlers, threads)-/// across otherwise unrelated runs. Opt in explicitly-/// (`[runtime_pool.python] enabled = true`) to accept that in exchange for the-/// warm-worker memory saving.-#[must_use]-pub fn enabled(pool: &RuntimePoolConfig) -> bool {- if crate::tools::timeout::ProcessCleanup::is_active()- || crate::tools::timeout::CommandEnvironment::is_active()- {- tracing::debug!(- "[python_exec] cancellable turn uses an owned subprocess instead of the pool"- );- return false;- }- pool.enabled && pool.python.is_enabled(false)-}--/// Run inline Python on a pooled, warm `python` worker.-///-/// # Errors-///-/// [`PoolRunError`], classified so the caller knows whether falling back to a-/// per-call spawn is safe.-pub async fn run_inline(- config: &Config,- code: String,- cwd: Option<PathBuf>,- timeout: Option<Duration>,-) -> Result<PoolExecOutcome, PoolRunError> {- super::run_inline(config, &Language::python(), code, cwd, timeout).await-}diff --git a/crates/openhuman-core/src/runtime/pool/types.rs b/crates/openhuman-core/src/runtime/pool/types.rsdeleted file mode 100644index 46b7703979..0000000000--- a/crates/openhuman-core/src/runtime/pool/types.rs+++ /dev/null@@ -1,116 +0,0 @@-//! The types callers of pooled execution see.--use std::time::Duration;--use tinyruntime_bus::{ExecResponse, Language};--use crate::config::RuntimePoolLangConfig;--/// A language with a worker pool.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum PoolLang {- /// JavaScript on the managed Node.js toolchain.- Node,- /// Python.- Python,-}--impl PoolLang {- /// The identifier used in logs and status surfaces.- #[must_use]- pub fn id(self) -> &'static str {- match self {- Self::Node => "node",- Self::Python => "python",- }- }-- /// The bus language this pool serves.- #[must_use]- pub fn language(self) -> Language {- match self {- Self::Node => Language::nodejs(),- Self::Python => Language::python(),- }- }-}--/// The result of running one job on a pooled worker.-///-/// Mirrors the fields a per-call spawn would have exposed, plus `queue_wait` so-/// callers can surface backpressure in run logs — a host that cannot tell a slow-/// job from a busy pool will tune the wrong thing.-#[derive(Debug, Clone)]-pub struct PoolExecOutcome {- /// Everything the job wrote to standard output.- pub stdout: String,- /// Everything the job wrote to standard error.- pub stderr: String,- /// `0` on success, non-zero when the job threw or exited non-zero.- pub exit_code: Option<i32>,- /// The job hit its soft deadline and was aborted.- pub timed_out: bool,- /// Wall-clock the job itself took inside the worker.- pub elapsed: Duration,- /// How long the submission waited for a free worker.- pub queue_wait: Duration,-}--impl PoolExecOutcome {- /// Adapt a module reply.- #[must_use]- pub fn from_module(response: &ExecResponse) -> Self {- Self {- stdout: response.stdout.clone(),- stderr: response.stderr.clone(),- exit_code: response.exit_code,- timed_out: response.timed_out,- elapsed: Duration::from_millis(response.elapsed_ms),- queue_wait: Duration::from_millis(response.queue_wait_ms),- }- }-- /// A job "succeeded" when it ran to completion with a zero (or absent) exit- /// code and did not time out.- #[must_use]- pub fn success(&self) -> bool {- !self.timed_out && matches!(self.exit_code, None | Some(0))- }-}--/// The knobs a single language pool reads from config.-///-/// Kept as a plain owned struct so a caller never re-reads config mid-flight.-#[derive(Debug, Clone)]-pub struct PoolSettings {- /// Concurrent workers.- pub max_workers: usize,- /// Retire a worker after this long idle, or never.- pub idle_ttl: Option<Duration>,- /// Retire a worker after this many jobs. `0` disables recycling.- pub recycle_after_jobs: u64,- /// Jobs allowed to queue beyond the worker slots.- pub max_queue_depth: usize,-}--impl PoolSettings {- /// Derive the effective settings from a per-language config block, applying- /// the same "never zero" clamps the config getters use.- #[must_use]- pub fn from_lang_config(cfg: &RuntimePoolLangConfig) -> Self {- Self {- max_workers: cfg.effective_max_workers(),- idle_ttl: if cfg.idle_ttl_secs == 0 {- None- } else {- Some(Duration::from_secs(cfg.idle_ttl_secs))- },- recycle_after_jobs: cfg.recycle_after_jobs,- max_queue_depth: cfg.effective_max_queue_depth(),- }- }-}--#[cfg(test)]-#[path = "types_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/pool/types_tests.rs b/crates/openhuman-core/src/runtime/pool/types_tests.rsdeleted file mode 100644index d8a0ba4596..0000000000--- a/crates/openhuman-core/src/runtime/pool/types_tests.rs+++ /dev/null@@ -1,72 +0,0 @@-//! Unit tests for the pooled-execution types.--use std::time::Duration;--use tinyruntime_bus::ExecResponse;--use super::{PoolExecOutcome, PoolSettings};-use crate::config::RuntimePoolLangConfig;--fn outcome(exit_code: Option<i32>) -> PoolExecOutcome {- PoolExecOutcome {- stdout: String::new(),- stderr: String::new(),- exit_code,- timed_out: false,- elapsed: Duration::ZERO,- queue_wait: Duration::ZERO,- }-}--#[test]-fn success_requires_a_clean_exit_and_no_timeout() {- assert!(outcome(Some(0)).success());- assert!(outcome(None).success());- assert!(!outcome(Some(1)).success());-- let timed_out = PoolExecOutcome {- timed_out: true,- ..outcome(Some(0))- };- assert!(- !timed_out.success(),- "a job aborted at its deadline did not succeed"- );-}--#[test]-fn a_module_reply_keeps_run_time_and_queue_wait_apart() {- // A host that cannot tell a slow job from a busy pool will tune the wrong- // thing, so the two never collapse into one number.- let response = ExecResponse::new("out", "err", Some(0), "22.11.0").with_timings(12, 900);- let adapted = PoolExecOutcome::from_module(&response);-- assert_eq!(adapted.stdout, "out");- assert_eq!(adapted.stderr, "err");- assert_eq!(adapted.elapsed, Duration::from_millis(12));- assert_eq!(adapted.queue_wait, Duration::from_millis(900));- assert!(adapted.success());-}--#[test]-fn a_timed_out_reply_stays_timed_out_through_the_adaptation() {- let response = ExecResponse::new("", "", None, "22.11.0").with_timed_out(true);- let adapted = PoolExecOutcome::from_module(&response);- assert!(adapted.timed_out);- assert!(!adapted.success());-}--#[test]-fn settings_disable_idle_reaping_on_zero() {- let cfg = RuntimePoolLangConfig {- enabled: Some(true),- max_workers: 3,- idle_ttl_secs: 0,- recycle_after_jobs: 5,- max_queue_depth: 10,- };- let settings = PoolSettings::from_lang_config(&cfg);- assert_eq!(settings.max_workers, 3);- assert!(settings.idle_ttl.is_none());- assert_eq!(settings.recycle_after_jobs, 5);-}diff --git a/crates/openhuman-core/src/runtime/python/README.md b/crates/openhuman-core/src/runtime/python/README.mddeleted file mode 100644index d6a710cc2e..0000000000--- a/crates/openhuman-core/src/runtime/python/README.md+++ /dev/null@@ -1,67 +0,0 @@-# runtime/python--The **Python interpreter client**.--## What moved out--Interpreter discovery (candidate ordering, `--version` probing, minimum-version-matching) and the managed standalone-CPython install pipeline (release index-selection, download, digest verification, extraction, atomic install,-cross-process install locking) are all in the `tinyruntime` module now, reached-through [`modules::runtime`](../../modules/runtime.rs).--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | Export-focused: submodule decls and `pub use` re-exports. |-| [`bootstrap.rs`](./bootstrap.rs) | The interpreter client. `PythonBootstrap` (`resolve`, `probe_installed`, `try_cached`), `ResolvedPython`, `PythonSource`. |--## Public surface--`PythonBootstrap::new(Arc<Config>)`, `.resolve() -> Result<ResolvedPython>`,-`.probe_installed()`, `.try_cached()`, plus-`ResolvedPython` (`python_bin`, `bin_dir`, `version`, `source`) and-`PythonSource`.--## Persistence--**None here.** The managed install cache belongs to the `tinyruntime` module.-This module reads `config.runtime_python` (`enabled`, `prefer_system`,-`minimum_version`, `maximum_version`, `cache_dir`, `managed_release_tag`,-`preferred_command`) only to build the requests it sends.--## Dependencies--- `crate::modules::runtime`: the module client this delegates to.-- `crate::config`: the settings each request carries.--External crates: `tinyruntime-bus`, `tokio`, `anyhow`, `tracing`. No HTTP-client, no archive crates, no `walkdir`, no `fs2`: those went with the pipeline.--## Used by--- `crates/openhuman-core/src/tools/impl/system/{python_exec,shell}.rs`: hold an- `Arc<PythonBootstrap>`; `python_exec` calls `resolve()`, `shell` uses the- non-blocking `try_cached()` for `PATH` injection.-- `crates/openhuman-core/src/skills/runtime/ops.rs`: resolves an interpreter for- Python-backed skills.--## Notes / gotchas--- **A request names a floor, not a version.** `runtime_python.minimum_version`- is a lower bound because the standalone channel publishes a moving set of- builds; the exclusive `maximum_version` is how a host stays off a newer- series. Both are interpreted by `tinyruntime-python`, not here.-- **The local cache is not redundant with the module's.** Only this one can- answer without awaiting, which is what lets the shell inject `PATH` without- blocking on a bus round trip.-- Inline Python code goes through `runtime::pool::python`, which routes to the- module's warm workers.--## Further reading--- [Parent module (`runtime`)](../README.md)-- [tinyruntime submodule](../../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/python/bootstrap.rs b/crates/openhuman-core/src/runtime/python/bootstrap.rsdeleted file mode 100644index 9a16e0acde..0000000000--- a/crates/openhuman-core/src/runtime/python/bootstrap.rs+++ /dev/null@@ -1,180 +0,0 @@-//! Python interpreter resolution, delegated to the `tinyruntime` module.-//!-//! This used to own interpreter discovery and a managed-CPython install-//! pipeline. Both now live in the `tinyruntime` module, which does the same work-//! for every language, so what is left is the adapter that turns a module answer-//! into the [`ResolvedPython`] this core's callers already name.--use std::path::PathBuf;-use std::sync::{Arc, Mutex};--use anyhow::{anyhow, Result};-use tinyruntime_bus::{Language, ResolvedRuntime, RuntimeSource};--use crate::config::Config;-use crate::runtime::client as runtime;--/// Origin of the resolved interpreter.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum PythonSource {- /// Reused a compatible interpreter already on the host.- System,- /// A managed standalone distribution the module downloaded and installed.- Managed,-}--impl From<RuntimeSource> for PythonSource {- fn from(source: RuntimeSource) -> Self {- match source {- RuntimeSource::System => Self::System,- // A source this build does not know is a module from a newer- // contract; Managed is the reading that treats it as provisioned.- _ => Self::Managed,- }- }-}--/// Fully-resolved Python interpreter.-#[derive(Debug, Clone)]-pub struct ResolvedPython {- /// Directory to prepend to `PATH` for child processes so `python`,- /// `python3`, and `pip` resolve to the same toolchain.- pub bin_dir: PathBuf,- /// Absolute path to the Python executable.- pub python_bin: PathBuf,- /// Normalised interpreter version, e.g. `3.12.4`.- pub version: String,- /// Where the interpreter came from.- pub source: PythonSource,-}--impl ResolvedPython {- /// Adapt a module resolution, or say what it was missing.- fn from_module(resolved: &ResolvedRuntime) -> Result<Self> {- let python_bin = resolved- .executable("python")- .map(PathBuf::from)- .ok_or_else(|| anyhow!("the resolved python toolchain reports no interpreter"))?;-- Ok(Self {- bin_dir: PathBuf::from(&resolved.bin_dir),- python_bin,- version: resolved.version.clone(),- source: resolved.source.into(),- })- }-}--/// Resolves the Python interpreter through the `tinyruntime` module.-pub struct PythonBootstrap {- config: Arc<Config>,- /// The last resolution, for the non-awaiting- /// [`PythonBootstrap::try_cached`].- cached: Mutex<Option<ResolvedPython>>,-}--impl std::fmt::Debug for PythonBootstrap {- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- formatter- .debug_struct("PythonBootstrap")- .field("resolved", &self.try_cached().is_some())- .finish_non_exhaustive()- }-}--impl PythonBootstrap {- /// Build a bootstrap over this host's configuration.- #[must_use]- pub fn new(config: Arc<Config>) -> Self {- Self {- config,- cached: Mutex::new(None),- }- }-- #[cfg(test)]- pub(crate) fn cache_for_test(&self, resolved: ResolvedPython) {- if let Ok(mut cached) = self.cached.lock() {- *cached = Some(resolved);- }- }-- /// The configuration this bootstrap resolves under.- #[must_use]- pub fn config(&self) -> &Config {- &self.config- }-- /// The memoised interpreter, without awaiting anything.- #[must_use]- pub fn try_cached(&self) -> Option<ResolvedPython> {- self.cached.lock().ok().and_then(|guard| guard.clone())- }-- /// Report an already-provisioned interpreter, without downloading one.- pub async fn probe_installed(&self) -> Option<ResolvedPython> {- if let Some(existing) = self.try_cached() {- return Some(existing);- }- if !self.config.runtime_python.enabled {- return None;- }- match runtime::resolve(&self.config, &Language::python(), false).await {- Ok(Some(resolved)) => self.adopt(&resolved).ok(),- Ok(None) => {- tracing::debug!(- "[runtime::python] no python interpreter is provisioned yet (provisioning required)"- );- None- }- Err(error) => {- tracing::debug!("[runtime::python] probing for an interpreter failed: {error}");- None- }- }- }-- /// Resolve the interpreter, installing a managed one if the host has none.- ///- /// # Errors- ///- /// When Python is disabled for this host, when the module or its provider- /// cannot be loaded, or when provisioning fails.- pub async fn resolve(&self) -> Result<ResolvedPython> {- if let Some(existing) = self.try_cached() {- return Ok(existing);- }- if !self.config.runtime_python.enabled {- return Err(anyhow!(- "the python runtime is disabled (set runtime_python.enabled = true to use \- python-backed integrations)"- ));- }-- let resolved = runtime::resolve(&self.config, &Language::python(), true)- .await- .map_err(|error| anyhow!("{error}"))?- .ok_or_else(|| {- anyhow!("the python runtime module reported no interpreter and did not say why")- })?;- self.adopt(&resolved)- }-- /// Adapt a module resolution and remember it.- fn adopt(&self, resolved: &ResolvedRuntime) -> Result<ResolvedPython> {- let adapted = ResolvedPython::from_module(resolved)?;- tracing::info!(- version = %adapted.version,- source = ?adapted.source,- "[runtime::python] python interpreter ready"- );- if let Ok(mut cached) = self.cached.lock() {- *cached = Some(adapted.clone());- }- Ok(adapted)- }-}--#[cfg(test)]-#[path = "bootstrap_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/python/bootstrap_tests.rs b/crates/openhuman-core/src/runtime/python/bootstrap_tests.rsdeleted file mode 100644index 418fde2700..0000000000--- a/crates/openhuman-core/src/runtime/python/bootstrap_tests.rs+++ /dev/null@@ -1,82 +0,0 @@-//! Tests for the Python interpreter client.-//!-//! The module owns discovery, selection, download, and install, and tests all of-//! it in its own repository. These cover the seam: how a module answer becomes a-//! [`ResolvedPython`], and what happens when the host has Python turned off.--use std::sync::Arc;--use tinyruntime_bus::{Language, ResolvedRuntime, RuntimeLayout, RuntimeSource};--use super::{PythonBootstrap, PythonSource, ResolvedPython};-use crate::config::Config;--/// A module resolution carrying `executables`.-fn resolution(executables: &[(&str, &str)]) -> ResolvedRuntime {- let mut layout = RuntimeLayout::new("3.12.4", "/cache/cpython-3.12.4/python/bin");- for (name, path) in executables {- layout = layout.with_executable(*name, *path);- }- ResolvedRuntime::from_layout(Language::python(), RuntimeSource::Managed, layout)-}--#[test]-fn a_resolution_becomes_the_paths_callers_name() {- let adapted = ResolvedPython::from_module(&resolution(&[- ("python", "/cache/cpython-3.12.4/python/bin/python3"),- ("pip", "/cache/cpython-3.12.4/python/bin/pip3"),- ]))- .expect("a toolchain reporting an interpreter adapts");-- assert_eq!(- adapted.python_bin,- std::path::Path::new("/cache/cpython-3.12.4/python/bin/python3")- );- assert_eq!(adapted.version, "3.12.4");- assert_eq!(adapted.source, PythonSource::Managed);-}--#[test]-fn an_install_without_an_interpreter_is_refused() {- // Unlike npm for Node, there is nothing to fall back to: the interpreter is- // the toolchain.- let error = ResolvedPython::from_module(&resolution(&[("pip", "/usr/bin/pip3")]))- .expect_err("an install with no interpreter is not one");- assert!(error.to_string().contains("interpreter"), "got `{error}`");-}--#[test]-fn an_install_without_pip_still_resolves() {- let adapted = ResolvedPython::from_module(&resolution(&[("python", "/usr/bin/python3")]))- .expect("an interpreter without pip is still an interpreter");- assert_eq!(adapted.python_bin, std::path::Path::new("/usr/bin/python3"));-}--#[test]-fn a_system_interpreter_is_reported_as_one() {- let mut resolved = resolution(&[("python", "/usr/bin/python3")]);- resolved.source = RuntimeSource::System;- assert_eq!(- ResolvedPython::from_module(&resolved)- .expect("adapts")- .source,- PythonSource::System- );-}--#[tokio::test]-async fn a_disabled_runtime_refuses_before_reaching_the_bus() {- let mut config = Config::default();- config.runtime_python.enabled = false;- let bootstrap = PythonBootstrap::new(Arc::new(config));-- let error = bootstrap.resolve().await.expect_err("python is off");- assert!(error.to_string().contains("disabled"), "got `{error}`");- assert!(bootstrap.probe_installed().await.is_none());-}--#[test]-fn nothing_is_cached_before_the_first_resolution() {- let bootstrap = PythonBootstrap::new(Arc::new(Config::default()));- assert!(bootstrap.try_cached().is_none());-}diff --git a/crates/openhuman-core/src/runtime/python/mod.rs b/crates/openhuman-core/src/runtime/python/mod.rsdeleted file mode 100644index 53e2ea4cc1..0000000000--- a/crates/openhuman-core/src/runtime/python/mod.rs+++ /dev/null@@ -1,9 +0,0 @@-//! Managed Python runtime for Python-backed integrations.-//!-//! [`bootstrap`] is the client for the `tinyruntime` module: it asks for an-//! interpreter and adapts the answer. Discovery, selection, download, and-//! install all live in the module now.--pub mod bootstrap;--pub use bootstrap::{PythonBootstrap, PythonSource, ResolvedPython};diff --git a/crates/openhuman-core/src/runtime/python_server/README.md b/crates/openhuman-core/src/runtime/python_server/README.mddeleted file mode 100644index 31759f30fe..0000000000--- a/crates/openhuman-core/src/runtime/python_server/README.md+++ /dev/null@@ -1,187 +0,0 @@-# runtime/python_server--The long-lived Python worker that keeps model-backed backends warm. This-module owns the process lifecycle and wire protocol; interpreter resolution-(finding or provisioning a `python` binary) belongs to the sibling-[`runtime/python`](../python/README.md) client, which this module calls into-to pick the interpreter it launches.--One backend currently runs inside the worker process:--- **Kompress** ([`kompress.rs`](./kompress.rs)): TokenJuice's ModernBERT/torch plain-text- compressor, gated by `config.tokenjuice.ml_compression_enabled`.--It is gated behind `config.runtime_python.enabled`; `registry::enabled_backends`-computes the active set from that flag and `config.tokenjuice.ml_compression_enabled`.--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | Submodule decls and `pub use` re-exports. |-| [`server.rs`](./server.rs) | Host side: maps `Config` and the managed interpreter onto a `ServerLaunch`, holds the process-wide `ServerSlot` (`ensure_started`, `status`). The process lifecycle itself (spawn, handshake, request/response, restart-on-failure, idle expiry, start back-off) is `tinyruntime_pyserver::{PythonServer, ServerSlot}`. |-| [`registry.rs`](./registry.rs) | `RuntimePythonBackend` enum (`Kompress`) and `enabled_backends(config)`. |-| [`kompress.rs`](./kompress.rs) | Kompress venv provisioning (`ensure_kompress`, `install_into`, `kompress_provisioned`) and the compress request (`request_kompress`). |-| (`tinyruntime-pyserver`) | Owns the JSONL wire types (`PROTOCOL_VERSION`, request/response/ready-line), the status types (`BackendStatus`, `ServerStatus`, re-exported here as `RuntimePythonServerStatus`) and the worker script itself (`SERVER_SCRIPT`), written to the cache root as `runtime_python_server.py` each time a server is prepared. Library crate in `vendor/tinyruntime`. |--## Lifecycle--`ensure_started(config)` is the single entry point. It caches one-`Arc<RuntimePythonServer>` behind a process-wide `OnceLock<Mutex<ServerCache>>`-(`Empty` / `Ready` / `Failed { message, retry_after }`):--- If the enabled backend set has changed since the cached server launched- (e.g. Kompress toggled on or off), the cache is discarded and a new server- is started: the running process was never provisioned for the new set.-- If the Kompress backend has been idle longer than- `config.tokenjuice.ml_sidecar_idle_timeout_secs`, the server is torn down and- restarted on the next request, freeing the torch process's memory.-- A startup failure caches `Failed` with a five-minute (`START_FAILURE_BACKOFF`)- retry window so a broken venv does not retry on every call.-- `RuntimePythonServer::request` sends one request, and on failure resets the- child and retries once before giving up.--`prepare_launch` picks the interpreter for the worker: when Kompress is enabled it gets its own dedicated venv via `kompress::ensure_kompress`; otherwise the worker runs under the base interpreter from `runtime::python::PythonBootstrap`.--## Wire protocol--JSONL over the child's stdin/stdout (`tinyruntime_pyserver::protocol`), one line per message:--- Startup handshake: the worker writes a `ReadyLine` (`ready`, `protocol`,- `backends`, optional `error`) before any request is sent; a `protocol`- mismatch against `PROTOCOL_VERSION`, `ready: false`, or no line within- `HANDSHAKE_TIMEOUT` (30s) fails the launch.-- Requests: `PythonServerRequest { id, method, params }`, methods namespaced by- backend (`kompress.compress`).-- Responses: `PythonServerResponse { id, ok, result, error }`, matched back to- the request by `id`; the read loop skips lines with a stale/unparseable `id`- and enforces a 60s per-request timeout (`REQUEST_TIMEOUT`, sized for the- slower Kompress backend).--stderr is drained continuously by a background task and only logged at-`debug`/`trace`, never surfaced to callers.--## Backends--**Kompress** (`kompress.rs`): TokenJuice's ModernBERT/torch plain-text- compressor, gated by `config.tokenjuice.ml_compression_enabled`.--It is gated behind `config.runtime_python.enabled`; `registry::enabled_backends`-computes the active set from that flag and `config.tokenjuice.ml_compression_enabled`.--## Key files--| File | Role |-| --- | --- |-| [`mod.rs`](./mod.rs) | Submodule decls and `pub use` re-exports. |-| [`server.rs`](./server.rs) | Host side: maps `Config` and the managed interpreter onto a `ServerLaunch`, holds the process-wide `ServerSlot` (`ensure_started`, `status`). The process lifecycle itself (spawn, handshake, request/response, restart-on-failure, idle expiry, start back-off) is `tinyruntime_pyserver::{PythonServer, ServerSlot}`. |-| [`registry.rs`](./registry.rs) | `RuntimePythonBackend` enum (`Kompress`) and `enabled_backends(config)`. |-| `kompress.rs` | Kompress venv provisioning (`ensure_kompress`, `install_into`, `kompress_provisioned`) and the compress request (`request_kompress`). |-| (`tinyruntime-pyserver`) | Owns the JSONL wire types (`PROTOCOL_VERSION`, request/response/ready-line), the status types (`BackendStatus`, `ServerStatus`, re-exported here as `RuntimePythonServerStatus`) and the worker script itself (`SERVER_SCRIPT`), written to the cache root as `runtime_python_server.py` each time a server is prepared. Library crate in `vendor/tinyruntime`. |--## Lifecycle--`ensure_started(config)` is the single entry point. It caches one-`Arc<RuntimePythonServer>` behind a process-wide `OnceLock<Mutex<ServerCache>>`-(`Empty` / `Ready` / `Failed { message, retry_after }`):--- If the enabled backend set has changed since the cached server launched- (e.g. Kompress toggled on or off), the cache is discarded and a new server- is started: the running process was never provisioned for the new set.-- If the Kompress backend has been idle longer than- `config.tokenjuice.ml_sidecar_idle_timeout_secs`, the server is torn down and- restarted on the next request, freeing the torch process's memory.-- A startup failure caches `Failed` with a five-minute (`START_FAILURE_BACKOFF`)- retry window so a broken venv does not retry on every call.-- `RuntimePythonServer::request` sends one request, and on failure resets the- child and retries once before giving up.--`prepare_launch` picks the interpreter for the worker: when Kompress is enabled it gets its own dedicated venv via `kompress::ensure_kompress`; otherwise the worker runs under the base interpreter from `runtime::python::PythonBootstrap`.--## Wire protocol--JSONL over the child's stdin/stdout (`tinyruntime_pyserver::protocol`), one line per message:--- Startup handshake: the worker writes a `ReadyLine` (`ready`, `protocol`,- `backends`, optional `error`) before any request is sent; a `protocol`- mismatch against `PROTOCOL_VERSION`, `ready: false`, or no line within- `HANDSHAKE_TIMEOUT` (30s) fails the launch.-- Requests: `PythonServerRequest { id, method, params }`, methods namespaced by- backend (`kompress.compress`).-- Responses: `PythonServerResponse { id, ok, result, error }`, matched back to- the request by `id`; the read loop skips lines with a stale/unparseable `id`- and enforces a 60s per-request timeout (`REQUEST_TIMEOUT`, sized for the- slower Kompress backend).--stderr is drained continuously by a background task and only logged at-`debug`/`trace`, never surfaced to callers.--## Backends--**spaCy** (`spacy.rs`): `ensure_spacy` provisions the `spacy-venv`-(`pip install spacy click`, `python -m spacy download en_core_web_sm`),-tracked by a versioned ready marker (`SPACY_READY_MARKER_VERSION`) so a-package-set change forces re-provisioning; `spacy_provisioned` is a cheap,-network-free readiness check. `extract` sends `spacy.extract` and-returns the shared `tinymemory_api::host::SpacyResponse` type. Called from-`modules::memory_host` for the memory tree's query extractor.--**Kompress** (`kompress.rs`): `ensure_kompress` provisions a CPU-only torch +-transformers venv and pre-downloads `config.tokenjuice.ml_model_id`;-The worker loads the model fully offline-(`HF_HUB_OFFLINE=1`, `TRANSFORMERS_OFFLINE=1`) so startup never depends on the-network once provisioned. `kompress_provisioned` is the network-free marker check the `kompress` init-step uses. `request_kompress` sends `kompress.compress` with-`target_ratio` / `max_input_chars` from `config.tokenjuice`. Called from-`inference::tokenjuice::ml`.--Provisioning is serialized behind a `tokio::sync::Mutex` so concurrent callers-don't race the same venv build.--## Status--`RuntimePythonServerStatus { enabled, running, backends: Vec<BackendStatus>, message }`-is returned by `status()` and reflects the cache directly: `Empty` reports-`disabled`, `Failed` reports the last error, `Ready` reports each backend's-`ready` flag from the worker's handshake `backends` list. There is no public-RPC method for this.--## Persistence--No domain store. `server::python_server_cache_root` picks the root:-`<runtime_python.cache_dir>/runtime-python-server` when configured, else-`<OS cache dir>/openhuman/runtime-python-server`, else-`<workspace_dir>/runtime_python_server`. Under it live `kompress-venv/`, the Kompress HF cache `kompress-hf/`, and the written-`runtime_python_server.py`.--## Security--The worker runs under whichever interpreter `runtime::python::PythonBootstrap`-or the venv provisioning resolved: it does not choose or sandbox that-interpreter itself, and it is spawned with the core's own-environment inherited (there is no `env_clear`). On top of that the module-adds `OPENHUMAN_RPS_BACKENDS` (the enabled backend list) and, for Kompress,-`OPENHUMAN_RPS_KOMPRESS_{MODEL,DEVICE,TARGET_RATIO,MAX_INPUT_CHARS}`,-`HF_HOME`, `HF_HUB_OFFLINE=1`, `TRANSFORMERS_OFFLINE=1`, and-`HF_HUB_DISABLE_TELEMETRY=1`. `process_util::apply_no_window` is applied to-the worker spawn and to every provisioning command so Windows shows no-console flash. Sandbox/approval policy for what reaches this worker is decided by the caller before the request is-sent, not here.--## Used by--- `crates/openhuman-core/src/inference/tokenjuice/ml/mod.rs`: `request_kompress` for- plain-text compression.--## Notes / gotchas--- Restart-on-failure in `RuntimePythonServer::request` means a transient- worker crash is invisible to callers except for added latency on the retried- call.--## Further reading--- [Parent module (`runtime`)](../README.md)-- [tinyruntime submodule](../../../../../vendor/tinyruntime/README.md)-- [System and utilities tools](../../../../../gitbooks/features/native-tools/system-and-utilities.md)-- [Loadable modules](../../../../../gitbooks/developing/loadable-modules.md)diff --git a/crates/openhuman-core/src/runtime/python_server/kompress.rs b/crates/openhuman-core/src/runtime/python_server/kompress.rsdeleted file mode 100644index 8ab051b062..0000000000--- a/crates/openhuman-core/src/runtime/python_server/kompress.rs+++ /dev/null@@ -1,257 +0,0 @@-//! Kompress backend — TokenJuice ML plain-text compressor (ModernBERT/torch).-//!-//! Provisions torch + transformers into the runtime python server's venv and-//! pre-downloads the model so the long-lived server can load it offline at-//! startup. The actual compression runs inside the shared `server.py` (embedded in `tinyruntime-pyserver`) and is-//! reached via [`request_kompress`] (→ `server::request("kompress.compress")`).-//!-//! [`ensure_kompress`] creates the dedicated `kompress-venv` the server runs.--use std::path::{Path, PathBuf};-use std::time::Duration;--use anyhow::{bail, Context, Result};-use serde::{Deserialize, Serialize};-use tokio::process::Command;-use tokio::sync::OnceCell;--use crate::config::Config;-use crate::runtime::python::PythonBootstrap;--use super::server::python_server_cache_root;--const VENV_TIMEOUT: Duration = Duration::from_secs(120);-/// torch + transformers wheels are large; allow a generous one-time window.-const PIP_TIMEOUT: Duration = Duration::from_secs(1800);-const MODEL_TIMEOUT: Duration = Duration::from_secs(1800);--static PROVISION_LOCK: OnceCell<tokio::sync::Mutex<()>> = OnceCell::const_new();--async fn provision_lock() -> &'static tokio::sync::Mutex<()> {- PROVISION_LOCK- .get_or_init(|| async { tokio::sync::Mutex::new(()) })- .await-}--/// A provisioned Kompress runtime: the venv interpreter with torch+transformers-/// and the HuggingFace cache holding the (pre-downloaded) model weights.-#[derive(Debug, Clone)]-pub struct KompressRuntime {- pub python_bin: PathBuf,- pub hf_home: PathBuf,-}--/// Result of one `kompress.compress` call.-#[derive(Debug, Clone, Deserialize, Serialize)]-pub struct KompressResponse {- #[serde(default)]- pub compressed_text: String,- #[serde(default)]- pub input_chars: usize,- #[serde(default)]- pub output_chars: usize,-}--/// Compress `text` with the Kompress backend over the shared runtime server.-pub async fn request_kompress(config: &Config, text: &str) -> Result<KompressResponse> {- super::server::request_kompress_compress(config, text).await-}--/// HF cache directory for Kompress model weights (kept under the server cache).-pub(crate) fn hf_home(config: &Config) -> PathBuf {- python_server_cache_root(config).join("kompress-hf")-}--fn kompress_venv_dir(config: &Config) -> PathBuf {- python_server_cache_root(config).join("kompress-venv")-}--fn venv_python_path(venv_dir: &Path) -> PathBuf {- if cfg!(windows) {- venv_dir.join("Scripts").join("python.exe")- } else {- venv_dir.join("bin").join("python")- }-}--fn marker_path(venv_dir: &Path, model_id: &str) -> PathBuf {- let safe_model: String = model_id- .chars()- .map(|ch| {- if ch.is_ascii_alphanumeric() || matches!(ch, '.' | '-' | '_') {- ch- } else {- '_'- }- })- .collect();- venv_dir.join(format!(".openhuman-kompress-ready-{safe_model}"))-}--/// Cheap, network-free probe: are torch + transformers + the model provisioned?-pub fn kompress_provisioned(config: &Config) -> bool {- let venv = kompress_venv_dir(config);- marker_path(&venv, &config.tokenjuice.ml_model_id).exists() && venv_python_path(&venv).exists()-}--/// Ensure a dedicated Kompress venv exists (torch + transformers + model).-pub async fn ensure_kompress(config: &Config) -> Result<KompressRuntime> {- let _guard = provision_lock().await.lock().await;- if !config.runtime_python.enabled {- bail!("runtime_python disabled — cannot provision Kompress");- }- if !config.tokenjuice.ml_compression_enabled {- bail!("tokenjuice.ml_compression_enabled is false");- }-- let venv_dir = kompress_venv_dir(config);- let venv_python = venv_python_path(&venv_dir);- let hf = hf_home(config);-- if marker_path(&venv_dir, &config.tokenjuice.ml_model_id).exists() && venv_python.exists() {- return Ok(KompressRuntime {- python_bin: venv_python,- hf_home: hf,- });- }-- tokio::fs::create_dir_all(&hf)- .await- .with_context(|| format!("creating kompress hf home {}", hf.display()))?;-- log::info!(- "[runtime_python_server::kompress] provisioning venv={} model={}",- venv_dir.display(),- config.tokenjuice.ml_model_id- );-- let base = PythonBootstrap::new(std::sync::Arc::new(config.clone()))- .resolve()- .await- .context("resolving base python for kompress venv")?;-- run_step(- &base.python_bin,- &["-m", "venv", &venv_dir.to_string_lossy()],- VENV_TIMEOUT,- &hf,- "create venv",- )- .await?;- if !venv_python.exists() {- bail!(- "venv created but interpreter missing at {}",- venv_python.display()- );- }-- install_deps_and_model(&venv_python, &hf, &config.tokenjuice.ml_model_id).await?;-- tokio::fs::write(- marker_path(&venv_dir, &config.tokenjuice.ml_model_id),- base.version.as_bytes(),- )- .await- .with_context(|| "writing kompress ready marker")?;-- log::info!("[runtime_python_server::kompress] provisioning complete");- Ok(KompressRuntime {- python_bin: venv_python,- hf_home: hf,- })-}--/// pip-install torch (CPU wheel) + transformers, then pre-download the model so-/// the long-lived server can load it offline.-async fn install_deps_and_model(venv_python: &Path, hf: &Path, model_id: &str) -> Result<()> {- run_step(- venv_python,- &["-m", "pip", "install", "--upgrade", "pip"],- PIP_TIMEOUT,- hf,- "pip upgrade",- )- .await?;- run_step(- venv_python,- &[- "-m",- "pip",- "install",- "--index-url",- "https://download.pytorch.org/whl/cpu",- "torch",- ],- PIP_TIMEOUT,- hf,- "pip install torch (cpu)",- )- .await?;- run_step(- venv_python,- &["-m", "pip", "install", "transformers", "tokenizers"],- PIP_TIMEOUT,- hf,- "pip install transformers",- )- .await?;- // Pre-download the model into the HF cache so server startup loads offline.- let preload = format!(- "from transformers import AutoModel, AutoTokenizer; \- AutoTokenizer.from_pretrained('{model_id}'); AutoModel.from_pretrained('{model_id}')"- );- run_step(- venv_python,- &["-c", &preload],- MODEL_TIMEOUT,- hf,- "preload model",- )- .await?;- Ok(())-}--async fn run_step(- python_bin: &Path,- args: &[&str],- timeout: Duration,- hf_home: &Path,- label: &str,-) -> Result<()> {- log::debug!(- "[runtime_python_server::kompress] step `{label}`: {} {:?}",- python_bin.display(),- args- );- let mut cmd = Command::new(python_bin);- cmd.args(args);- cmd.env("HF_HOME", hf_home);- cmd.env("HF_HUB_DISABLE_TELEMETRY", "1");- cmd.kill_on_drop(true);- // Re-provisioning can run mid-session if the venv is missing/corrupted, so- // suppress the Windows conhost flash here too (GH-4814).- tinyinference_local::process::apply_no_window(&mut cmd);-- let output = match tokio::time::timeout(timeout, cmd.output()).await {- Ok(Ok(o)) => o,- Ok(Err(e)) => return Err(e).with_context(|| format!("spawning step `{label}`")),- Err(_) => bail!("step `{label}` timed out after {:?}", timeout),- };- if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- let tail: String = stderr- .chars()- .rev()- .take(800)- .collect::<String>()- .chars()- .rev()- .collect();- bail!("step `{label}` failed (status {}): {tail}", output.status);- }- Ok(())-}--#[cfg(test)]-#[path = "kompress_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/python_server/kompress_tests.rs b/crates/openhuman-core/src/runtime/python_server/kompress_tests.rsdeleted file mode 100644index b2b709fbce..0000000000--- a/crates/openhuman-core/src/runtime/python_server/kompress_tests.rs+++ /dev/null@@ -1,51 +0,0 @@-use super::*;--#[test]-fn venv_python_path_is_platform_specific() {- let p = venv_python_path(Path::new("/tmp/venv"));- if cfg!(windows) {- assert!(p.ends_with("Scripts/python.exe") || p.ends_with("Scripts\\python.exe"));- } else {- assert_eq!(p, PathBuf::from("/tmp/venv/bin/python"));- }-}--#[test]-fn provisioned_false_on_clean_config() {- let mut config = Config::default();- config.runtime_python.cache_dir = "/nonexistent/tj-test".to_string();- assert!(!kompress_provisioned(&config));-}--#[test]-fn ready_marker_is_model_specific_and_path_safe() {- let venv = Path::new("/tmp/openhuman-kompress-test-venv");- let first = marker_path(venv, "answerdotai/ModernBERT-base");- let second = marker_path(venv, "other/model");-- assert_ne!(first, second);- assert_eq!(first.parent(), Some(venv));- assert!(first- .file_name()- .unwrap()- .to_string_lossy()- .contains("answerdotai_ModernBERT-base"));-}--// Exercises the provisioning step path (including the GH-4814-// CREATE_NO_WINDOW hook, a no-op off Windows) with a trivial binary so it-// stays covered without a real python toolchain.-#[cfg(unix)]-#[tokio::test]-async fn run_step_runs_a_trivial_binary() {- let hf = tempfile::tempdir().expect("tempdir");- run_step(- Path::new("/bin/echo"),- &["ok"],- Duration::from_secs(30),- hf.path(),- "echo smoke",- )- .await- .expect("echo step succeeds");-}diff --git a/crates/openhuman-core/src/runtime/python_server/mod.rs b/crates/openhuman-core/src/runtime/python_server/mod.rsdeleted file mode 100644index 2a50685b97..0000000000--- a/crates/openhuman-core/src/runtime/python_server/mod.rs+++ /dev/null@@ -1,14 +0,0 @@-//! Long-running Python backend host.-//!-//! `runtime_python` owns interpreter resolution. This module owns the-//! process-level server that keeps Python-backed model modules warm and serves-//! Rust callers over a private JSONL stdio protocol.--pub mod kompress;-pub mod registry;-pub mod server;--pub use kompress::{ensure_kompress, kompress_provisioned, request_kompress, KompressResponse};-pub use registry::{enabled_backends, RuntimePythonBackend};-pub use server::{ensure_started, status, RuntimePythonServer};-pub use tinyruntime_pyserver::{BackendStatus, ServerStatus as RuntimePythonServerStatus};diff --git a/crates/openhuman-core/src/runtime/python_server/registry.rs b/crates/openhuman-core/src/runtime/python_server/registry.rsdeleted file mode 100644index b46d65842b..0000000000--- a/crates/openhuman-core/src/runtime/python_server/registry.rs+++ /dev/null@@ -1,31 +0,0 @@-use crate::config::Config;--#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum RuntimePythonBackend {- /// TokenJuice ML plain-text compressor ("Kompress", ModernBERT via torch).- Kompress,-}--impl RuntimePythonBackend {- pub fn id(self) -> &'static str {- match self {- Self::Kompress => "kompress",- }- }-}--pub fn enabled_backends(config: &Config) -> Vec<RuntimePythonBackend> {- if !config.runtime_python.enabled {- return Vec::new();- }-- let mut backends = Vec::new();- if config.tokenjuice.ml_compression_enabled {- backends.push(RuntimePythonBackend::Kompress);- }- backends-}--#[cfg(test)]-#[path = "registry_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/python_server/registry_tests.rs b/crates/openhuman-core/src/runtime/python_server/registry_tests.rsdeleted file mode 100644index b40151fed9..0000000000--- a/crates/openhuman-core/src/runtime/python_server/registry_tests.rs+++ /dev/null@@ -1,29 +0,0 @@-use super::*;--/// #5056: a fresh install (`Config::default()`) must not enable any-/// Python backend, so the runtime Python server never launches — and the-/// managed CPython interpreter is never speculatively downloaded — on a-/// default boot.-#[test]-fn enabled_backends_is_empty_by_default() {- let config = Config::default();- assert!(- enabled_backends(&config).is_empty(),- "default config must not enable any runtime Python backend"- );-}--#[test]-fn registry_includes_kompress_when_enabled() {- let mut config = Config::default();- config.runtime_python.enabled = true;- config.tokenjuice.ml_compression_enabled = true;- assert_eq!(- enabled_backends(&config),- vec![RuntimePythonBackend::Kompress]- );-- // Master runtime switch still gates everything.- config.runtime_python.enabled = false;- assert!(enabled_backends(&config).is_empty());-}diff --git a/crates/openhuman-core/src/runtime/python_server/server.rs b/crates/openhuman-core/src/runtime/python_server/server.rsdeleted file mode 100644index afdc84745b..0000000000--- a/crates/openhuman-core/src/runtime/python_server/server.rs+++ /dev/null@@ -1,148 +0,0 @@-//! Host side of the runtime Python server.-//!-//! The worker process itself (spawn, handshake, request/response, restart,-//! idle expiry, startup back-off) lives in `tinyruntime-pyserver`. This file-//! only maps `Config` and the managed interpreter onto a-//! [`ServerLaunch`], and holds the process-wide slot.--use std::path::PathBuf;-use std::sync::Arc;-use std::time::Duration;--use anyhow::{bail, Result};-use serde_json::json;-use tinyruntime_pyserver::{IdleRule, PythonServer, ServerLaunch, ServerSlot, ServerStatus};--use super::registry::{enabled_backends, RuntimePythonBackend};-use crate::config::Config;--/// A running worker process, as the rest of the core names it.-pub type RuntimePythonServer = PythonServer;--static SLOT: ServerSlot = ServerSlot::new();--pub async fn ensure_started(config: &Config) -> Result<Arc<RuntimePythonServer>> {- let requested: Vec<String> = enabled_backends(config)- .iter()- .map(|backend| backend.id().to_string())- .collect();- let idle = IdleRule {- backend: RuntimePythonBackend::Kompress.id(),- timeout: Duration::from_secs(config.tokenjuice.ml_sidecar_idle_timeout_secs),- };- let server = SLOT- .ensure(&requested, Some(idle), async {- prepare_launch(config)- .await- .map_err(|error| tinyruntime_pyserver::Error::Prepare(format!("{error:#}")))- })- .await?;- Ok(server)-}--pub async fn status() -> ServerStatus {- SLOT.status().await-}--async fn prepare_launch(config: &Config) -> Result<ServerLaunch> {- let backends = enabled_backends(config);- if backends.is_empty() {- bail!("no runtime python server backends enabled");- }-- // The server runs ONE interpreter. Kompress is the only backend, and it- // owns its venv.- let mut env: Vec<(String, String)> = Vec::new();- let python_bin = if backends.contains(&RuntimePythonBackend::Kompress) {- let rt = super::kompress::ensure_kompress(config).await?;- push_kompress_env(&mut env, config, &rt.hf_home);- rt.python_bin- } else {- crate::runtime::python::PythonBootstrap::new(std::sync::Arc::new(config.clone()))- .resolve()- .await?- .python_bin- };-- env.push((- "OPENHUMAN_RPS_BACKENDS".to_string(),- backends- .iter()- .map(|b| b.id())- .collect::<Vec<_>>()- .join(","),- ));-- let script_path = write_server_script(config).await?;-- Ok(ServerLaunch::new(- python_bin,- script_path,- backends.iter().map(|b| b.id().to_string()).collect(),- env,- ))-}--/// Environment the worker needs to load + run the Kompress model offline.-fn push_kompress_env(env: &mut Vec<(String, String)>, config: &Config, hf_home: &std::path::Path) {- env.push((- "OPENHUMAN_RPS_KOMPRESS_MODEL".to_string(),- config.tokenjuice.ml_model_id.clone(),- ));- env.push((- "OPENHUMAN_RPS_KOMPRESS_DEVICE".to_string(),- config.tokenjuice.ml_device.clone(),- ));- env.push((- "OPENHUMAN_RPS_KOMPRESS_TARGET_RATIO".to_string(),- config.tokenjuice.ml_target_ratio.to_string(),- ));- env.push((- "OPENHUMAN_RPS_KOMPRESS_MAX_INPUT_CHARS".to_string(),- config.tokenjuice.ml_max_input_chars.to_string(),- ));- env.push(("HF_HOME".to_string(), hf_home.display().to_string()));- // Model was pre-downloaded during provisioning; load offline so startup- // never blocks on the network.- env.push(("HF_HUB_OFFLINE".to_string(), "1".to_string()));- env.push(("TRANSFORMERS_OFFLINE".to_string(), "1".to_string()));- env.push(("HF_HUB_DISABLE_TELEMETRY".to_string(), "1".to_string()));-}--async fn write_server_script(config: &Config) -> Result<PathBuf> {- let root = python_server_cache_root(config);- Ok(tinyruntime_pyserver::write_script(&root).await?)-}--/// Where the runtime Python server keeps its venvs, model caches and script.-pub(crate) fn python_server_cache_root(config: &Config) -> PathBuf {- let configured = config.runtime_python.cache_dir.trim();- if !configured.is_empty() {- return PathBuf::from(configured).join("runtime-python-server");- }- if let Some(user_cache) = dirs::cache_dir() {- return user_cache.join("openhuman").join("runtime-python-server");- }- config.workspace_dir.join("runtime_python_server")-}--pub async fn request_kompress_compress(- config: &Config,- text: &str,-) -> Result<super::kompress::KompressResponse> {- let server = ensure_started(config).await?;- Ok(server- .request(- "kompress.compress",- json!({- "text": text,- "target_ratio": config.tokenjuice.ml_target_ratio,- "max_input_chars": config.tokenjuice.ml_max_input_chars,- }),- )- .await?)-}--#[cfg(test)]-#[path = "server_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/runtime/python_server/server_tests.rs b/crates/openhuman-core/src/runtime/python_server/server_tests.rsdeleted file mode 100644index 350d7fcbc2..0000000000--- a/crates/openhuman-core/src/runtime/python_server/server_tests.rs+++ /dev/null@@ -1,9 +0,0 @@-use super::*;--#[tokio::test]-async fn prepare_launch_rejects_disabled_backends() {- let mut config = Config::default();- config.runtime_python.enabled = false;- let err = prepare_launch(&config).await.unwrap_err().to_string();- assert!(err.contains("no runtime python server backends enabled"));-}diff --git a/crates/openhuman-core/src/sandbox/README.md b/crates/openhuman-core/src/sandbox/README.mdindex 17493629ba..b640ef62a6 100644--- a/crates/openhuman-core/src/sandbox/README.md+++ b/crates/openhuman-core/src/sandbox/README.md@@ -2,7 +2,7 @@Decides where an agent's command runs: directly on the host, inside an OS jailconfined to the action dir, or in a throwaway Docker container. The tools that-spawn processes (`shell`, `node_exec`, `npm_exec`, `python_exec`) and the+spawn processes (`shell`) and theflows code-runner capability call into it when the agent runs in sandboxedmode. The core process itself always runs on the host; only the spawnedcommand is confined.@@ -205,9 +205,8 @@ The settings surface (`get_sandbox_settings`, `[security.sandbox]` andOS jail and spawns through `NoopBackend`. Check the handle's status, not thekind.- `ShellTool::run_sandboxed` (`tools/impl/system/shell.rs`) passes- `RuntimeConfig::default()` rather than the loaded config, while- `node_exec`, `npm_exec`, `python_exec` and the flows code runner pass the- loaded `runtime` block. So `[runtime] kind = "docker"` and+ `RuntimeConfig::default()` rather than the loaded config, while the flows+ code runner passes the loaded `runtime` block. So `[runtime] kind = "docker"` and`[runtime.local_jail]` do not reach the shell tool's sandbox today.- Every current caller passes `is_remote_session = false`, so in practiceDocker is chosen only by `[runtime] kind = "docker"`.diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rsindex f65400db17..8b62919882 100644--- a/crates/openhuman-core/src/sandbox/ops.rs+++ b/crates/openhuman-core/src/sandbox/ops.rs@@ -25,8 +25,8 @@ use std::time::Duration;/// prevents Windows paths from being passed into Linux Docker containers.////// They were missing when this defect was found, and it survived the first-/// round of fixes because the four tool launchers (`shell`, `node_exec`,-/// `npm_exec`, `python_exec`) each carry their own copy of the allow-list and+/// round of fixes because the tool launchers now share the shell and flows code-runner paths rather than+/// carrying separate copies of the allow-list and/// had already been patched: the built-in `orchestrator` runs with/// `sandbox_mode = "sandboxed"`, and all four tools divert to/// [`crate::sandbox`] *before* reaching those lists, so the host spawn pathsdiff --git a/crates/openhuman-core/src/sandbox/types.rs b/crates/openhuman-core/src/sandbox/types.rsindex d36b7f98ab..1241814b1f 100644--- a/crates/openhuman-core/src/sandbox/types.rs+++ b/crates/openhuman-core/src/sandbox/types.rs@@ -30,7 +30,7 @@ pub struct SandboxPolicy {/// local jail's output capture, lives under it so nothing appears in/// `workspace_root` while a command runs.pub state_dir: PathBuf,- /// Additional read-only mounts (e.g. `/usr/lib`, managed node).+ /// Additional read-only mounts (e.g. `/usr/lib`).pub read_only_mounts: Vec<PathBuf>,/// Additional read-write mounts (e.g. `~/.cargo`). Local jail only.#[serde(default)]diff --git a/crates/openhuman-core/src/security/policy/enforcement.rs b/crates/openhuman-core/src/security/policy/enforcement.rsindex 650a2a5398..ed9c2a9e93 100644--- a/crates/openhuman-core/src/security/policy/enforcement.rs+++ b/crates/openhuman-core/src/security/policy/enforcement.rs@@ -28,7 +28,7 @@ impl SecurityPolicy {/// by one bulk ingest — want the tier refusal and nothing else. That is the/// same shape the ~15 acting tools which gate on bare [`Self::can_act`]/// already use (e.g. `tinytools_std::filesystem::FileWriteTool`,- /// `tools/impl/system/python_exec.rs`, `cron/scheduler.rs`).+ /// `cron/scheduler.rs`).pub fn enforce_write_tier(&self, operation_name: &str) -> Result<(), String> {if !self.can_act() {log::warn!(diff --git a/crates/openhuman-core/src/skills/mod.rs b/crates/openhuman-core/src/skills/mod.rsindex 35e5594d66..80a7df2019 100644--- a/crates/openhuman-core/src/skills/mod.rs+++ b/crates/openhuman-core/src/skills/mod.rs@@ -17,7 +17,7 @@//! inert serde/std-only type definitions with zero coupling to the gated//! siblings, and they are load-bearing far outside this domain://! `tools::traits` re-exports `ToolResult`/`ToolContent` out of [`types`] as-//! the crate's unified tool-result type (`mcp`, `runtime::node`, and+//! the crate's unified tool-result type (`mcp` and//! ~236 files consume it), and `Workflow`/`WorkflowFrontmatter`///! `WorkflowScope` from [`ops_types`] appear in always-on agent-harness and//! prompt signatures. Gating them would take down the entire tool traitdiff --git a/crates/openhuman-core/src/skills/runtime/README.md b/crates/openhuman-core/src/skills/runtime/README.mdindex 1e596a48ec..f864d487f0 100644--- a/crates/openhuman-core/src/skills/runtime/README.md+++ b/crates/openhuman-core/src/skills/runtime/README.md@@ -9,7 +9,7 @@ Responsibilities:- Start a skill run in the background and cancel an in-flight one.- List recent runs and read run-log slices.-- Resolve the reusable Node/Python runtimes before script-backed skills run.+- Probe Node.js and Python availability on the host PATH for script-backed skills.A run is an `orchestrator` `Agent` built per run(`Agent::from_config_for_agent(&config, "orchestrator")`),@@ -26,8 +26,7 @@ one spawn path.It reuses, rather than duplicates:-- `crate::runtime::node` (`NodeBootstrap`) and `crate::runtime::python`- (`PythonBootstrap`) for interpreter resolution.+- the host `node` and `python3` commands for runtime availability probes.- `crate::skills::registry` for skill lookup and required-input checks,`crate::skills::preflight` for the `[github]` gate, `crate::skills::run_log`for log paths, cancellation tokens, and run scanning, anddiff --git a/crates/openhuman-core/src/skills/runtime/ops.rs b/crates/openhuman-core/src/skills/runtime/ops.rsindex 436afff7b4..de0cc3c541 100644--- a/crates/openhuman-core/src/skills/runtime/ops.rs+++ b/crates/openhuman-core/src/skills/runtime/ops.rs@@ -1,11 +1,7 @@-//! Skill runtime operations that coordinate reusable language runtimes.+//! Skill runtime availability probes and skill execution orchestration.use serde::Serialize;-use crate::config::Config;-use crate::runtime::node::{NodeBootstrap, NodeSource};-use crate::runtime::python::{PythonBootstrap, PythonSource};-#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum RuntimeRequirement {All,@@ -44,7 +40,7 @@ pub struct ResolveRuntimesOutcome {}pub async fn resolve_runtimes(- config: &Config,+ _config: &crate::config::Config,requirement: RuntimeRequirement,) -> ResolveRuntimesOutcome {tracing::debug!(@@ -56,13 +52,13 @@ pub async fn resolve_runtimes(requirement,RuntimeRequirement::All | RuntimeRequirement::Node) {- runtimes.push(resolve_node(config).await);+ runtimes.push(resolve_host_runtime("node", "node"));}if matches!(requirement,RuntimeRequirement::All | RuntimeRequirement::Python) {- runtimes.push(resolve_python(config).await);+ runtimes.push(resolve_host_runtime("python", "python3"));}tracing::debug!(count = runtimes.len(),@@ -71,95 +67,56 @@ pub async fn resolve_runtimes(ResolveRuntimesOutcome { runtimes }}-async fn resolve_node(config: &Config) -> ResolvedRuntimeSummary {- if !config.node.enabled {- return ResolvedRuntimeSummary {- runtime: "node".to_string(),- enabled: false,- available: false,- source: None,- version: None,- binary: None,- bin_dir: None,- error: Some("node runtime disabled".to_string()),- };- }- let bootstrap = NodeBootstrap::new(std::sync::Arc::new(config.clone()));- match bootstrap.resolve().await {- Ok(resolved) => ResolvedRuntimeSummary {- runtime: "node".to_string(),- enabled: true,- available: true,- source: Some(- match resolved.source {- NodeSource::System => "system",- NodeSource::Managed => "managed",- }- .to_string(),- ),- version: Some(resolved.version),- binary: Some(resolved.node_bin.display().to_string()),- bin_dir: Some(resolved.bin_dir.display().to_string()),- error: None,- },- Err(error) => ResolvedRuntimeSummary {- runtime: "node".to_string(),- enabled: true,- available: false,- source: None,- version: None,- binary: None,- bin_dir: None,- error: Some(error.to_string()),- },+fn resolve_host_runtime(runtime: &str, command: &str) -> ResolvedRuntimeSummary {+ let output = std::process::Command::new(command)+ .arg("--version")+ .output();+ let binary = find_host_binary(command);+ let (version, error) = match output {+ Ok(output) if output.status.success() => (+ Some(String::from_utf8_lossy(&output.stdout).trim().to_string()),+ None,+ ),+ Ok(output) => (+ None,+ Some(String::from_utf8_lossy(&output.stderr).trim().to_string()),+ ),+ Err(error) => (None, Some(error.to_string())),+ };+ ResolvedRuntimeSummary {+ runtime: runtime.to_string(),+ enabled: true,+ available: version.is_some(),+ source: version.as_ref().map(|_| "host".to_string()),+ version,+ binary,+ bin_dir: None,+ error,}}-async fn resolve_python(config: &Config) -> ResolvedRuntimeSummary {- if !config.runtime_python.enabled {- return ResolvedRuntimeSummary {- runtime: "python".to_string(),- enabled: false,- available: false,- source: None,- version: None,- binary: None,- bin_dir: None,- error: Some("python runtime disabled".to_string()),- };- }- let bootstrap = PythonBootstrap::new(std::sync::Arc::new(config.clone()));- match bootstrap.resolve().await {- Ok(resolved) => ResolvedRuntimeSummary {- runtime: "python".to_string(),- enabled: true,- available: true,- source: Some(- match resolved.source {- PythonSource::System => "system",- PythonSource::Managed => "managed",- }- .to_string(),- ),- version: Some(resolved.version),- binary: Some(resolved.python_bin.display().to_string()),- bin_dir: resolved- .python_bin- .parent()- .map(|path| path.display().to_string()),- error: None,- },- Err(error) => ResolvedRuntimeSummary {- runtime: "python".to_string(),- enabled: true,- available: false,- source: None,- version: None,- binary: None,- bin_dir: None,- error: Some(error.to_string()),- },- }+fn find_host_binary(command: &str) -> Option<String> {+ let path = std::env::var_os("PATH")?;+ let extensions = if cfg!(windows) {+ std::env::var_os("PATHEXT")+ .map(|extensions| {+ std::env::split_paths(&extensions)+ .map(|extension| extension.to_string_lossy().into_owned())+ .collect::<Vec<_>>()+ })+ .filter(|extensions| !extensions.is_empty())+ .unwrap_or_else(|| vec![".COM".into(), ".EXE".into(), ".BAT".into(), ".CMD".into()])+ } else {+ vec![String::new()]+ };+ std::env::split_paths(&path)+ .flat_map(|directory| {+ extensions+ .iter()+ .map(move |extension| directory.join(format!("{command}{extension}")))+ })+ .find(|candidate| candidate.is_file())+ .map(|candidate| candidate.display().to_string())}#[cfg(test)]diff --git a/crates/openhuman-core/src/tools/README.md b/crates/openhuman-core/src/tools/README.mdindex 6614bddd93..ce544e357f 100644--- a/crates/openhuman-core/src/tools/README.md+++ b/crates/openhuman-core/src/tools/README.md@@ -26,8 +26,7 @@ assembled. It is called by the session builderConfig, SecurityPolicy, AuditLogger, RuntimeAdapter, action_dir|v- shared NodeBootstrap / PythonBootstrap- (node.enabled, runtime_python.enabled)+ host `node` / `python3` commands used through shell|vbase vec: shell, file_read, file_write, grep, glob, list, edit,@@ -39,7 +38,7 @@ assembled. It is called by the session builderflows, web3, voice, skills, mcp, documents, media, hosting,memory (memory::engine::is_on), browser (browser.enabled),gitbooks (gitbooks.enabled), search, integrations, composio,- node/npm/python exec, lsp (OPENHUMAN_LSP_ENABLED), delegate+ lsp (OPENHUMAN_LSP_ENABLED), delegate|vpost-filter 1: DomainSet drop tools whose DomainGroup is off@@ -54,7 +53,7 @@ assembled. It is called by the session builderMost families gate twice: once at compile time with a Cargo feature(`flows`, `web3`, `voice`, `skills`, `mcp`, `modules`, `documents`, `media`,-`hosting`, `runtime-node`) and once at runtime from config. A tool that cannot+`hosting`) and once at runtime from config. A tool that cannotwork is left out rather than registered and failing, because a model retriesa failing tool. For example, the `memory` tool registers only while a memoryengine is usable, gitbooks and the static MCP bridge are skipped when their@@ -142,7 +141,7 @@ Where the built-in tools come from:| `detect_tools`, `curl`, `pushover` | `tinytools_std` || `http_request`, `web_fetch` | `tinytools_std::network`, wired with host limits, TinyJuice extraction and the x402 handler in [`impl/network/host.rs`](./impl/network/host.rs) || `current_time`, `resolve_time`, `ask_user_clarification`, `wait`, `wait_loop` | `tinyagents_harness::tools` |-| `shell`, `node_exec`, `npm_exec`, `python_exec`, `install_tool`, `schedule`, `proxy_config`, `lsp`, `update_check`, `update_apply`, `retrieve_tool_output` | [`impl/system/`](./impl/system/) |+| `shell`, `install_tool`, `schedule`, `proxy_config`, `lsp`, `update_check`, `update_apply`, `retrieve_tool_output` | [`impl/system/`](./impl/system/) || `gitbooks_search`, `gitbooks_get_page`, `gmail_unsubscribe`, `mcp_list_servers`, `mcp_list_tools`, `mcp_call_tool`, `mcp_<server>_<tool>` | [`impl/network/`](./impl/network/) (MCP tools behind `mcp`) || `browser`, `browser_open` | [`impl/browser/`](./impl/browser/) (behind `modules`) || `generate_document`, `generate_presentation` | [`impl/document/`](./impl/document/), [`impl/presentation/`](./impl/presentation/) (behind `documents`) |@@ -215,10 +214,7 @@ else is agent-only.`permission_level_with_args`.- `is_concurrency_safe` tells the harness a call may run alongside others inthe same batch. Return `true` only for calls with no shared side effects.-- `shell`, `node_exec` and `npm_exec` share one memoised `NodeBootstrap`.- With `node.enabled = false` or the `runtime-node` feature off, node and npm- tools are not registered and the shell skips PATH injection. Python works- the same way with `runtime_python.enabled`.+- The shell inherits the host `PATH`; Node.js and Python commands run with the host toolchain.- The browser shares `http_request.allowed_domains` but strips the `*`wildcard, so unifying the lists can only narrow browser reach. Allow-allstays behind `OPENHUMAN_BROWSER_ALLOW_ALL`.diff --git a/crates/openhuman-core/src/tools/impl/README.md b/crates/openhuman-core/src/tools/impl/README.mdindex 16137f6bb1..3d1e61fc51 100644--- a/crates/openhuman-core/src/tools/impl/README.md+++ b/crates/openhuman-core/src/tools/impl/README.md@@ -29,7 +29,7 @@ tested but no production assembly site constructs it today.| Family | Tools | Registration gate || --- | --- | --- |-| [`system/`](./system/) | `ShellTool`, `NodeExecTool`, `NpmExecTool`, `PythonExecTool`, `InstallToolTool`, `DetectToolsTool` (from `tinytools_std`), `CurrentTimeTool` and `ResolveTimeTool` (imported directly from `tinyagents_harness::tools` at their call sites; no local copy), `ScheduleTool`, `ProxyConfigTool`, `PushoverTool`, `LspTool`, `ToolStatsTool`, `UpdateCheckTool`, `UpdateApplyTool`, `InsertSqlRecordTool`, `WorkspaceStateTool`, `RetrieveToolOutputTool` (from `tinyjuice::host`, wired by `retrieve_tool_output_tool`); shell failure rendering lives in `tinytools_std::command_output` | `node_exec`/`npm_exec` and `shell`'s PATH injection need the `runtime-node` Cargo feature plus `node.enabled`; `python_exec` needs `runtime_python.enabled`; `LspTool` needs `OPENHUMAN_LSP_ENABLED` (`lsp_capability_enabled`); `ToolStatsTool` needs `learning.enabled` and `learning.tool_tracking_enabled`; `InsertSqlRecordTool` is exported, not registered; the rest are always registered |+| [`system/`](./system/) | `ShellTool`, `InstallToolTool`, `DetectToolsTool`, `CurrentTimeTool`, `ResolveTimeTool`, `ScheduleTool`, `ProxyConfigTool`, `PushoverTool`, `LspTool`, update tools, workspace and retrieval helpers. || [`filesystem/`](./filesystem/) | Host adapter only: `SecurityPolicy` implements `tinytools_std::filesystem::FsGate`. The tools (`FileReadTool`, `FileWriteTool`, `EditFileTool`, `ApplyPatchTool`, `GrepTool`, `GlobTool`, `ListFilesTool`, `ReadDiffTool`, `CsvExportTool`, `GitOperationsTool`, `RunLinterTool`, `RunTestsTool`, `UpdateMemoryMdTool`) live in `tinytools_std::filesystem` and are imported directly by `tools/ops.rs` | always registered, except `ReadDiffTool`, `RunLinterTool`, and `RunTestsTool`, which are exported, not registered || [`browser/`](./browser/) | `BrowserTool` (TinyComputer browser members and tasks), `BrowserOpenTool` (simple TinyComputer navigation), `ImageInfoTool` | Both browser tools need `browser.enabled` and the `modules` feature, and are deferred until `tool_search`; `ImageInfoTool` remains direct. Browser navigation uses the shared `http_request.allowed_domains` policy, and the checksum-pinned TinyComputer release module. Consequential actions go through the forced approval gate; `browser_unattended.rs` lets trusted cron/background/approval-free workflow turns skip it for the kinds listed in `[browser] unattended_actions`. || [`network/`](./network/) | `HttpRequestTool`, `WebFetchTool`, `CurlTool`, `GitbooksSearchTool`, `GitbooksGetPageTool`, `GmailUnsubscribeTool`, and under the `mcp` Cargo feature `McpListServersTool`, `McpListToolsTool`, `McpCallTool`; `url_guard.rs` is the shared SSRF/allowlist validator, not a tool | `http_request`, `web_fetch`, `curl`, `gmail_unsubscribe` always registered; `gitbooks_*` need `gitbooks.enabled` and, when the active profile sets an `mcp_allowlist`, an entry named `gitbooks`; `mcp_list_servers`/`mcp_list_tools`/`mcp_call_tool` register only when the static `[[mcp_client.servers]]` registry (after the profile allowlist) is non-empty |diff --git a/crates/openhuman-core/src/tools/impl/system/mod.rs b/crates/openhuman-core/src/tools/impl/system/mod.rsindex 60df886ae6..4eeed43d65 100644--- a/crates/openhuman-core/src/tools/impl/system/mod.rs+++ b/crates/openhuman-core/src/tools/impl/system/mod.rs@@ -6,10 +6,7 @@mod install_tool;mod lsp;-mod node_exec;-mod npm_exec;mod proxy_config;-mod python_exec;mod retrieve_tool_output;mod schedule;mod shell;@@ -24,10 +21,7 @@ use tinytools::ToolRunContext;pub use install_tool::InstallToolTool;pub use lsp::{lsp_capability_enabled, LspTool, LSP_ENABLED_ENV};-pub use node_exec::NodeExecTool;-pub use npm_exec::NpmExecTool;pub use proxy_config::ProxyConfigTool;-pub use python_exec::PythonExecTool;pub use retrieve_tool_output::{retrieve_tool_output_tool, RetrieveToolOutputTool};pub use schedule::ScheduleTool;pub use shell::ShellTool;@@ -44,8 +38,7 @@ pub use update_check::UpdateCheckTool;/// while the allow/deny decision reads `workspace_dir` + `trusted_roots`/// (`SecurityPolicy::is_resolved_path_allowed_for`). Granting it in the/// filesystem copy alone would let an agent read and edit a checkout it could-/// not then build, test, or commit, because `shell`, `python_exec`,-/// `node_exec`, and `npm_exec` all resolve their paths through here.+/// not then build, test, or commit, because the shell tool resolves its path through here.////// The grant is *additive and per-call*: it is pushed onto a clone, so nothing/// process-global is mutated and concurrent turns cannot race each other. Itdiff --git a/crates/openhuman-core/src/tools/impl/system/node_exec.rs b/crates/openhuman-core/src/tools/impl/system/node_exec.rsdeleted file mode 100644index e14f629f9a..0000000000--- a/crates/openhuman-core/src/tools/impl/system/node_exec.rs+++ /dev/null@@ -1,639 +0,0 @@-//! `node_exec` — execute JavaScript via the managed (or system) Node.js-//! toolchain.-//!-//! Sibling to [`crate::tools::impl::system::shell::ShellTool`]: same-//! security gates, same env hygiene, but the command is pinned to the `node`-//! binary resolved by-//! [`crate::runtime::javascript::NodeBootstrap`].-//!-//! Two input modes:-//!-//! | Mode | Params | Resulting invocation |-//! |---------------|------------------------------------------|-------------------------------------|-//! | Inline code | `inline_code: "console.log(1+1)"` | `node -e '<code>'` |-//! | Script path | `script_path: "scripts/run.js"`, `args` | `node <path> <args...>` |-//!-//! Exactly one of `inline_code` / `script_path` must be supplied. Scripts are-//! resolved relative to the workspace; paths escaping the workspace are-//! rejected by the filesystem helpers.-//!-//! The bootstrap is resolved **on first invocation**, which will download +-//! extract a managed Node.js distribution if no compatible `node` is on-//! `PATH`. Subsequent calls reuse the cached install.--use crate::agent::host_runtime::RuntimeAdapter;-use crate::runtime::javascript::NodeBootstrap;-use crate::sandbox;-use crate::security::{CommandClass, GateDecision, SecurityPolicy};-use crate::tools::schema_cache::static_schema;-use async_trait::async_trait;-use std::sync::Arc;-use std::time::Duration;-use tinytools::ToolRunContext;-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};--/// Absolute ceiling a caller may request via `timeout_secs`. There is **no**-/// default timeout — `node_exec` runs scripts that legitimately take minutes-/// (bundlers, solvers, test runs) and must not be hard-killed by a default cap-/// (issue #4023). A deadline applies only when `timeout_secs` is supplied.-const NODE_TIMEOUT_MAX_SECS: u64 = 1800;-/// Maximum combined stdout/stderr size (1 MB each) — same cap as shell.-const MAX_OUTPUT_BYTES: usize = 1_048_576;-/// Env allow-list for child processes. Matches shell.rs — secrets never leak-/// into spawned node processes. `PATH` gets a prepend of the managed bin-/// dir before being forwarded.-const SAFE_ENV_VARS: &[&str] = &[- "HOME",- "TERM",- "LANG",- "LC_ALL",- "LC_CTYPE",- "USER",- "SHELL",- "TMPDIR",- // Windows process creation and child command lookup need these after env_clear().- // PATH is rebuilt separately with the managed Node bin dir prepended.- "SystemRoot",- "WINDIR",- "COMSPEC",- "PATHEXT",- "TEMP",- "TMP",- "USERPROFILE",- "APPDATA",- "LOCALAPPDATA",- "ProgramFiles",- "ProgramFiles(x86)",- "ProgramW6432",-];--/// `node_exec` — execute JavaScript through the resolved Node.js runtime.-pub struct NodeExecTool {- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- bootstrap: Arc<NodeBootstrap>,- /// Runtime-pool config + workspace, snapshotted at construction so the hot- /// inline path never re-reads config from disk (#5106 is a perf feature).- pool_cfg: crate::config::RuntimePoolConfig,- workspace_dir: std::path::PathBuf,-}--impl NodeExecTool {- pub fn new(- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- bootstrap: Arc<NodeBootstrap>,- pool_cfg: crate::config::RuntimePoolConfig,- workspace_dir: std::path::PathBuf,- ) -> Self {- Self {- security,- runtime,- bootstrap,- pool_cfg,- workspace_dir,- }- }-}--#[async_trait]-impl Tool for NodeExecTool {- fn exposure(&self) -> tinytools::ToolExposure {- tinytools::ToolExposure::Deferred- }-- fn name(&self) -> &str {- "node_exec"- }-- fn description(&self) -> &str {- "Execute JavaScript through Node.js. Pass either `inline_code` (runs via `node -e`) or `script_path` (runs a file in your working directory, the action sandbox). Optional `args` forwards positional arguments to the script. Only the program's stdout/stderr is captured and returned to you — a value you do not `console.log` is invisible, and a script that exits 0 without printing returns an empty result. Always print the output you need (e.g. `console.log(JSON.stringify(result))`)."- }-- fn parameters_schema(&self) -> serde_json::Value {- static_schema!(include_str!("parameters/node_exec.json"))- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Execute- }-- /// `node_exec` runs scripts that legitimately take a long time, so it runs- /// unbounded unless the caller passes an explicit `timeout_secs` (capped at- /// [`NODE_TIMEOUT_MAX_SECS`]).- fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {- node_timeout_policy(args)- }-- /// Running JavaScript is arbitrary code execution → the `Write` bucket. In- /// ask-before-edit this routes through the human approval gate; in Full it- /// runs; in read-only `execute` refuses below. Previously `node_exec`- /// bypassed the gate entirely — only the rate limiter stood in the way.- fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {- self.security.gate_decision(CommandClass::Write) == GateDecision::Prompt- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, None).await- }-- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: ToolCallOptions,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, context).await- }-}--impl NodeExecTool {- async fn execute_in_context(- &self,- args: serde_json::Value,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let inline_code = args- .get("inline_code")- .and_then(|v| v.as_str())- .map(str::to_string);- let script_path = args- .get("script_path")- .and_then(|v| v.as_str())- .map(str::to_string);-- let extra_args: Vec<String> = args- .get("args")- .and_then(|v| v.as_array())- .map(|arr| {- arr.iter()- .filter_map(|v| v.as_str().map(str::to_string))- .collect()- })- .unwrap_or_default();-- // No default deadline — only the caller-supplied `timeout_secs` (capped)- // bounds the run. `None` ⇒ run to completion.- let explicit_timeout = crate::tools::timeout::explicit_call_timeout_duration(- args.get("timeout_secs").and_then(|v| v.as_u64()),- NODE_TIMEOUT_MAX_SECS,- );-- if inline_code.is_some() == script_path.is_some() {- return Ok(ToolResult::error(- "node_exec requires exactly one of `inline_code` or `script_path`",- ));- }-- // Read-only mode performs no acts. `node_exec` runs arbitrary code, so- // it must refuse here — it previously skipped the autonomy check- // entirely (only the rate limiter applied), letting `node -e '…'` run- // even in read-only mode.- if !self.security.can_act() {- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: the agent is in read-only mode and cannot execute code.",- ));- }- let path_policy = super::security_for_tool_context(&self.security, context, "node_exec");- for input in inline_code- .iter()- .chain(script_path.iter())- .chain(extra_args.iter())- {- if let Err(reason) = path_policy.check_protected_path_literals(input) {- return Ok(ToolResult::error(reason));- }- }- if self.security.is_rate_limited() {- return Ok(ToolResult::error(- "Rate limit exceeded: too many actions in the last hour",- ));- }- if !self.security.record_action() {- return Ok(ToolResult::error(- "Rate limit exceeded: action budget exhausted",- ));- }-- let resolved = match self.bootstrap.resolve().await {- Ok(r) => r,- Err(e) => {- tracing::error!(error = %e, "[node_exec] failed to resolve node runtime");- return Ok(ToolResult::error(format!(- "Node.js runtime unavailable: {e}"- )));- }- };-- tracing::info!(- version = %resolved.version,- source = ?resolved.source,- node_bin = %resolved.node_bin.display(),- "[node_exec] starting invocation"- );-- let command = if let Some(code) = inline_code.as_deref() {- format!(- "{} -e {}",- shell_quote(&resolved.node_bin.to_string_lossy()),- shell_quote(code)- )- } else if let Some(path) = script_path.as_deref() {- let resolved_script = match resolve_script_path(&path_policy.action_dir, path) {- Ok(p) => p,- Err(msg) => return Ok(ToolResult::error(msg)),- };- let mut parts: Vec<String> = Vec::with_capacity(extra_args.len() + 2);- parts.push(shell_quote(&resolved.node_bin.to_string_lossy()));- parts.push(shell_quote(&resolved_script.to_string_lossy()));- // `extra_args` are opaque positional arguments forwarded to the- // script. They are shell-quoted below so no shell metacharacter- // can escape, but we do NOT treat them as workspace paths — the- // script itself is responsible for any path validation it does- // on its own arguments.- for a in &extra_args {- parts.push(shell_quote(a));- }- parts.join(" ")- } else {- unreachable!("guarded above")- };-- // Route sandboxed agents and explicit operator backend selections- // through the shared sandbox path before considering the native pool.- let sandbox_required = match sandbox::command_requires_sandbox().await {- Ok(required) => required,- Err(err) => {- return Ok(ToolResult::error(format!(- "Cannot read sandbox configuration: {err}"- )))- }- };- if sandbox_required {- return Ok(self- .run_sandboxed(&path_policy, &command, &resolved.bin_dir, explicit_timeout)- .await);- }-- // Route inline JS through the shared runtime pool when enabled (#5106):- // a warm, bounded set of `node` workers replaces one `node -e` child per- // call, so a fleet pays ~one interpreter instead of one per skill run.- // `script_path` and sandboxed runs keep the legacy per-call spawn; a- // pool infrastructure failure also transparently falls back below.- if let Some(code) = inline_code.as_deref() {- if let Some(result) = self- .try_pool_inline(code, &path_policy.action_dir, explicit_timeout)- .await- {- return Ok(result);- }- }-- let mut cmd = match self- .runtime- .build_shell_command(&command, &path_policy.action_dir)- {- Ok(cmd) => cmd,- Err(e) => {- return Ok(ToolResult::error(format!(- "Failed to build runtime command: {e}"- )));- }- };-- cmd.env_clear();-- let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();- let sep = if cfg!(windows) { ";" } else { ":" };- let prepended_path = if host_path.is_empty() {- resolved.bin_dir.to_string_lossy().into_owned()- } else {- format!("{}{}{}", resolved.bin_dir.display(), sep, host_path)- };- cmd.env("PATH", &prepended_path);-- for var in SAFE_ENV_VARS {- if let Ok(val) = crate::tools::timeout::CommandEnvironment::var(var) {- cmd.env(var, val);- }- }-- // Bounded only when the caller asked for a deadline; otherwise run to- // completion (no harness/tool timeout on long scripts).- let result = match explicit_timeout {- Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,- None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),- };-- match result {- Ok(Ok(output)) => {- let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();- let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();-- if stdout.len() > MAX_OUTPUT_BYTES {- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));- stdout.push_str("\n... [stdout truncated at 1MB]");- }- if stderr.len() > MAX_OUTPUT_BYTES {- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));- stderr.push_str("\n... [stderr truncated at 1MB]");- }-- if output.status.success() {- if stderr.is_empty() {- Ok(ToolResult::success(stdout))- } else {- Ok(ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}")))- }- } else {- // Surface exit code + both streams so the agent can diagnose- // the failure instead of re-running it (#4095).- Ok(tinytools::command_failure(- output.status.code(),- &stdout,- &stderr,- ))- }- }- Ok(Err(e)) => Ok(ToolResult::error(format!("Failed to execute node: {e}"))),- Err(_) => Ok(ToolResult::error(format!(- "node_exec timed out after {}s and was killed",- explicit_timeout.map(|d| d.as_secs()).unwrap_or(0)- ))),- }- }-}--impl NodeExecTool {- /// Attempt to run inline JS on the shared runtime pool (#5106).- ///- /// Returns `Some(result)` when the pool handled the job — success, non-zero- /// exit, or timeout, all mapped to the same `ToolResult` shape as the legacy- /// path. Returns `None` when pooling is disabled or the pool infrastructure- /// failed, so the caller transparently falls back to a per-call spawn.- async fn try_pool_inline(- &self,- code: &str,- action_dir: &std::path::Path,- timeout: Option<Duration>,- ) -> Option<ToolResult> {- if !crate::runtime::pool::node::enabled(&self.pool_cfg) {- return None;- }- // Node forbids process.chdir() inside worker_threads. Preserve the- // legacy `node -e` contract for any statically apparent chdir use- // instead of dispatching code that the pooled worker cannot execute.- // False positives are safe: they only give up the pooling optimisation.- if inline_requires_process_chdir_compat(code) {- tracing::debug!("[node_exec] pool: process.chdir-compatible code uses legacy spawn");- return None;- }- match crate::runtime::pool::node::run_inline(- self.bootstrap.config(),- code.to_string(),- Some(action_dir.to_path_buf()),- timeout,- )- .await- {- Ok(outcome) => {- tracing::info!(- queue_wait_ms = outcome.queue_wait.as_millis() as u64,- elapsed_ms = outcome.elapsed.as_millis() as u64,- timed_out = outcome.timed_out,- "[node_exec] pool: inline job completed on a warm worker"- );- Some(pool_outcome_to_result(outcome, timeout))- }- // Job never ran → safe to fall back to a per-call spawn.- Err(crate::runtime::pool::PoolRunError::PreDispatch(error)) => {- tracing::warn!(- error = %error,- "[node_exec] pool: pre-dispatch failure; falling back to legacy spawn"- );- None- }- // Load-shed: do NOT spawn (that reintroduces the per-run RSS the pool- // caps). Surface a retryable busy error instead.- Err(crate::runtime::pool::PoolRunError::Saturated) => {- tracing::warn!("[node_exec] pool: saturated; shedding load");- Some(ToolResult::error(- "Node runtime pool is at capacity; retry shortly.",- ))- }- // The job may already have executed → terminal, never re-run it.- Err(crate::runtime::pool::PoolRunError::PostDispatch(error)) => {- tracing::warn!(- error = %error,- "[node_exec] pool: post-dispatch failure; not retried to avoid duplicate execution"- );- Some(ToolResult::error(format!(- "node_exec failed after the code was dispatched to a pooled worker; not retried to avoid running it twice: {error}"- )))- }- }- }-}--impl NodeExecTool {- /// Execute a node command through the sandbox backend. Called from- /// `execute()` when the agent's `SandboxMode` is `Sandboxed`.- ///- /// Mirrors `ShellTool::run_sandboxed`. The sandbox policy is resolved- /// from the current `RuntimeConfig` and rooted at- /// the effective `security.action_dir`; on platforms without a real `cwd_jail`- /// backend the local backend falls back to a documented noop with- /// the in-Rust path-hardening guards from `SecurityPolicy` still- /// applying (see CLAUDE.md "Action sandbox vs internal workspace").- async fn run_sandboxed(- &self,- security: &SecurityPolicy,- command: &str,- bin_dir: &std::path::Path,- timeout: Option<Duration>,- ) -> ToolResult {- use crate::sandbox;-- // Sandbox backends require a finite deadline. When the caller did not- // request one, use a generous effective-unbounded cap (24h) so a- // legitimately long script isn't killed while still bounding a wedged- // sandbox process. The native (non-sandboxed) path runs truly unbounded.- let effective = timeout.unwrap_or_else(|| {- Duration::from_secs(crate::tools::timeout::SANDBOX_UNBOUNDED_CAP_SECS)- });-- let policy = match sandbox::ops::resolve_command_policy(- &security.action_dir,- &security.workspace_dir,- )- .await- {- Ok(policy) => policy,- Err(why) => return ToolResult::error(format!("Sandbox unavailable: {why}")),- };-- tracing::debug!(backend = ?policy.backend, "[node_exec] routing to sandbox backend");- if policy.backend == sandbox::SandboxBackendKind::Docker {- return ToolResult::error(- "node_exec cannot use the Docker sandbox: its host Node.js binary and script paths are not mounted in the container",- );- }-- // Forward the managed Node.js bin dir on PATH so the child node- // process can resolve `node`, `npm`, `npx`, `corepack` consistently- // with the unsandboxed path.- let mut extra_env = std::collections::HashMap::new();- let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();- let sep = if cfg!(windows) { ";" } else { ":" };- let prepended = if host_path.is_empty() {- bin_dir.to_string_lossy().into_owned()- } else {- format!("{}{}{}", bin_dir.display(), sep, host_path)- };- extra_env.insert("PATH".into(), prepended.into());-- match sandbox::execute_in_sandbox(- &policy,- command,- &security.action_dir,- extra_env,- effective,- )- .await- {- Ok(result) => {- if result.timed_out {- ToolResult::error(format!(- "node_exec timed out after {}s and was killed",- effective.as_secs()- ))- } else if result.success() {- if result.stderr.is_empty() {- ToolResult::success(result.stdout)- } else {- ToolResult::success(format!(- "{}\n[stderr]\n{}",- result.stdout, result.stderr- ))- }- } else {- tinytools::command_failure(- tinytools::sandbox_exit_code(result.exit_code),- &result.stdout,- &result.stderr,- )- }- }- Err(e) => ToolResult::error(format!("Sandbox execution failed: {e}")),- }- }-}--/// Map a runtime-pool outcome onto the same `ToolResult` shape the legacy-/// `node -e` path produces: 1 MB stdout/stderr caps, exit-code surfacing on-/// failure, and the identical timeout message. Keeps pooled and legacy runs-/// indistinguishable to the agent.-fn pool_outcome_to_result(- outcome: crate::runtime::pool::PoolExecOutcome,- timeout: Option<Duration>,-) -> ToolResult {- if outcome.timed_out {- return ToolResult::error(format!(- "node_exec timed out after {}s and was killed",- timeout.map(|d| d.as_secs()).unwrap_or(0)- ));- }-- let mut stdout = outcome.stdout;- let mut stderr = outcome.stderr;- if stdout.len() > MAX_OUTPUT_BYTES {- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));- stdout.push_str("\n... [stdout truncated at 1MB]");- }- if stderr.len() > MAX_OUTPUT_BYTES {- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));- stderr.push_str("\n... [stderr truncated at 1MB]");- }-- let success = matches!(outcome.exit_code, None | Some(0));- if success {- if stderr.is_empty() {- ToolResult::success(stdout)- } else {- ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}"))- }- } else {- tinytools::command_failure(outcome.exit_code, &stdout, &stderr)- }-}--/// Resolve the wall-clock policy for a `node_exec` call from its args.-///-/// No `timeout_secs` (or `0`) ⇒ run unbounded; a positive value ⇒ enforce it,-/// clamped to [`NODE_TIMEOUT_MAX_SECS`]. Extracted from-/// [`NodeExecTool::timeout_policy`] so it is unit-testable without a bootstrap.-fn node_timeout_policy(args: &serde_json::Value) -> ToolTimeout {- match args.get("timeout_secs").and_then(|v| v.as_u64()) {- None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Millis(secs.min(NODE_TIMEOUT_MAX_SECS).saturating_mul(1000)),- }-}--/// Whether inline JavaScript needs the legacy main-thread process so-/// `process.chdir()` remains available.-///-/// Matching the property name anywhere deliberately catches direct calls,-/// aliases, destructuring, and bracket notation. Comments or string literals-/// may route an otherwise pool-safe snippet through the legacy path, which is-/// preferable to executing a cwd-mutating snippet with changed semantics.-fn inline_requires_process_chdir_compat(code: &str) -> bool {- code.contains("chdir")-}--/// POSIX-safe single-quote escaping. Wraps `s` in `'…'`, turning any embedded-/// single-quote into the four-char sequence `'\''`. Node bin paths and user-/// code pass through untouched semantically, but no shell metacharacter can-/// escape the quoted string.-fn shell_quote(s: &str) -> String {- let escaped = s.replace('\'', "'\\''");- format!("'{escaped}'")-}--/// Resolve a caller-supplied `script_path` against the workspace. Mirrors-/// `npm_exec::resolve_cwd` — rejects absolute paths and any component that-/// could escape the workspace (`..`, Windows drive prefixes). Scripts-/// themselves must live inside the workspace.-fn resolve_script_path(- workspace: &std::path::Path,- raw: &str,-) -> Result<std::path::PathBuf, String> {- let raw = raw.trim();- if raw.is_empty() {- return Err("node_exec `script_path` cannot be empty".to_string());- }- let candidate = std::path::Path::new(raw);- if candidate.is_absolute() {- return Err(format!(- "node_exec `script_path` must be relative to workspace; got absolute {raw:?}"- ));- }- if candidate.components().any(|c| {- matches!(- c,- std::path::Component::ParentDir | std::path::Component::Prefix(_)- )- }) {- return Err(format!(- "node_exec `script_path` must not escape workspace; got {raw:?}"- ));- }- Ok(workspace.join(candidate))-}--#[cfg(test)]-#[path = "node_exec_tests.rs"]-mod tests;--#[cfg(test)]-#[path = "node_exec_schema_tests.rs"]-mod schema_tests;diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec_schema_tests.rs b/crates/openhuman-core/src/tools/impl/system/node_exec_schema_tests.rsdeleted file mode 100644index a25d97d488..0000000000--- a/crates/openhuman-core/src/tools/impl/system/node_exec_schema_tests.rs+++ /dev/null@@ -1,44 +0,0 @@-use super::*;-use serde_json::json;--fn expected_node_exec() -> serde_json::Value {- json!({- "type": "object",- "properties": {- "inline_code": {- "type": "string",- "description": "JavaScript source passed to `node -e`. Mutually exclusive with script_path."- },- "script_path": {- "type": "string",- "description": "Path (relative to workspace) to a .js/.mjs/.cjs file. Mutually exclusive with inline_code."- },- "args": {- "type": "array",- "items": { "type": "string" },- "description": "Positional arguments appended after the script. Ignored for inline_code."- },- "timeout_secs": {- "type": "integer",- "description": "Optional wall-clock timeout (seconds) before the process is killed. No timeout by default — long-running scripts run to completion. Capped at 1800s; 0 disables."- }- }- })-}--#[test]-fn node_exec_static_schema_matches_json_literal() {- let tool = NodeExecTool::new(- std::sync::Arc::new(crate::security::SecurityPolicy::default()),- std::sync::Arc::new(crate::agent::host_runtime::NativeRuntime::new()),- std::sync::Arc::new(NodeBootstrap::new(std::sync::Arc::new(- crate::config::Config::default(),- ))),- crate::config::RuntimePoolConfig::default(),- std::path::PathBuf::from("."),- );- assert_eq!(- tinytools::Tool::parameters_schema(&tool),- expected_node_exec()- );-}diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rs b/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rsdeleted file mode 100644index 9b1f7f45c8..0000000000--- a/crates/openhuman-core/src/tools/impl/system/node_exec_tests.rs+++ /dev/null@@ -1,186 +0,0 @@-use super::*;-use serde_json::json;--#[tokio::test]-async fn node_exec_blocks_protected_literal_before_runtime_resolution() {- let tool = NodeExecTool::new(- std::sync::Arc::new(crate::security::SecurityPolicy {- enabled: false,- ..crate::security::SecurityPolicy::default()- }),- std::sync::Arc::new(crate::agent::host_runtime::NativeRuntime::new()),- std::sync::Arc::new(NodeBootstrap::new(std::sync::Arc::new(- crate::config::Config::default(),- ))),- crate::config::RuntimePoolConfig::default(),- std::path::PathBuf::from("."),- );- let result = tool- .execute(json!({"inline_code": "require('fs').readFileSync('~/.ssh/id_rsa')"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.text().contains("protected path"));-}-fn absolute_sample() -> &'static str {- if cfg!(windows) {- "C:\\Windows\\System32\\drivers\\etc\\hosts"- } else {- "/etc/passwd"- }-}--#[test]-fn shell_quote_wraps_plain_strings() {- assert_eq!(shell_quote("node"), "'node'");- assert_eq!(shell_quote("/opt/bin/node"), "'/opt/bin/node'");-}--#[test]-fn node_timeout_policy_unbounded_by_default() {- // No timeout_secs (or explicit 0) ⇒ run to completion.- assert_eq!(node_timeout_policy(&json!({})), ToolTimeout::Unbounded);- assert_eq!(- node_timeout_policy(&json!({"timeout_secs": 0})),- ToolTimeout::Unbounded- );-}--#[test]-fn node_timeout_policy_enforces_and_caps_explicit() {- assert_eq!(- node_timeout_policy(&json!({"timeout_secs": 120})),- ToolTimeout::Millis(120_000)- );- // Clamped to the 1800s ceiling.- assert_eq!(- node_timeout_policy(&json!({"timeout_secs": 99999})),- ToolTimeout::Millis(NODE_TIMEOUT_MAX_SECS * 1000)- );-}--#[test]-fn process_chdir_snippets_use_legacy_node_spawn() {- for code in [- "process.chdir('subdir'); console.log(process.cwd())",- "const move = process.chdir; move('subdir')",- "const { chdir } = process; chdir('subdir')",- "process['chdir']('subdir')",- ] {- assert!(- inline_requires_process_chdir_compat(code),- "expected legacy fallback for {code:?}"- );- }- assert!(!inline_requires_process_chdir_compat(- "console.log(process.cwd())"- ));-}--#[test]-fn shell_quote_escapes_single_quotes() {- assert_eq!(shell_quote("it's"), "'it'\\''s'");- assert_eq!(- shell_quote("console.log('hi')"),- "'console.log('\\''hi'\\'')'"- );-}--#[test]-fn shell_quote_neutralises_metacharacters() {- // $, backticks, && — all inert once wrapped in single quotes.- assert_eq!(shell_quote("$(rm -rf /)"), "'$(rm -rf /)'");- assert_eq!(shell_quote("a && b"), "'a && b'");-}--#[test]-fn resolve_script_path_rejects_empty() {- let ws = std::path::Path::new("/ws");- assert!(resolve_script_path(ws, "").is_err());- assert!(resolve_script_path(ws, " ").is_err());-}--#[test]-fn resolve_script_path_rejects_absolute() {- let ws = std::path::Path::new("/ws");- assert!(resolve_script_path(ws, absolute_sample()).is_err());-}--#[test]-fn resolve_script_path_rejects_parent_dir() {- let ws = std::path::Path::new("/ws");- assert!(resolve_script_path(ws, "../evil.js").is_err());- assert!(resolve_script_path(ws, "scripts/../../evil.js").is_err());-}--#[test]-fn resolve_script_path_accepts_relative_subdir() {- let ws = std::path::Path::new("/ws");- let resolved = resolve_script_path(ws, "scripts/run.js").unwrap();- assert_eq!(resolved, std::path::Path::new("/ws/scripts/run.js"));-}--#[test]-fn safe_env_vars_include_windows_process_essentials() {- for var in ["SystemRoot", "COMSPEC", "PATHEXT", "TEMP", "USERPROFILE"] {- assert!(- SAFE_ENV_VARS.contains(&var),- "{var} must be forwarded for Windows child processes"- );- }-}--/// Regression guard for #3238.-///-/// `node_exec` resolves caller-supplied `script_path` values against-/// `security.action_dir` (the agent's writable sandbox), never-/// `security.workspace_dir` (internal product state). If a future-/// refactor changes `NodeExecTool::execute` to pass-/// `&self.security.workspace_dir` to `resolve_script_path`, scripts-/// would resolve into the internal denylist instead of the action-/// sandbox, which is exactly the action/internal split that-/// PR #3074 prevents.-///-/// The behavioural end-to-end test for the CWD plumbing lives in-/// `shell.rs` (`shell_pwd_returns_action_dir_not_workspace_dir`) —-/// `node_exec` shares the same `runtime.build_shell_command(&command,-/// &self.security.action_dir)` call site, and the source-grep guard-/// in `shell.rs` (`shell_family_tools_route_cwd_through_action_dir`)-/// covers all three system tools. This test pins the script-resolution-/// contract specifically for `node_exec` by exercising-/// `resolve_script_path` against an `action_dir` distinct from-/// `workspace_dir`.-#[test]-fn resolve_script_path_targets_action_dir_not_workspace_dir() {- let action_dir = std::path::Path::new("/tmp/action-sandbox-3238");- let workspace_dir = std::path::Path::new("/tmp/internal-workspace-3238");-- let resolved = resolve_script_path(action_dir, "scripts/run.js")- .expect("relative script under action_dir must resolve");- assert_eq!(- resolved,- action_dir.join("scripts/run.js"),- "script_path must resolve under action_dir, not workspace_dir (see #3238)"- );- assert!(- resolved.starts_with(action_dir),- "resolved path must be under action_dir; got {}",- resolved.display()- );- assert!(- !resolved.starts_with(workspace_dir),- "resolved path leaked into workspace_dir; got {}",- resolved.display()- );-}--/// `node_exec` clears the child environment, so its allow-list must carry the-/// Windows process-bootstrap set — without `SystemRoot` a spawned `node.exe`-/// aborts with `Assertion failed: ncrypto::CSPRNG(nullptr, 0)`.-#[test]-fn safe_env_vars_cover_windows_bootstrap() {- crate::agent::platform_shell::assert_forwards_windows_bootstrap(- SAFE_ENV_VARS,- "node_exec::SAFE_ENV_VARS",- );-}diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec.rsdeleted file mode 100644index a7f018dc9b..0000000000--- a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs+++ /dev/null@@ -1,511 +0,0 @@-//! `npm_exec` — invoke the npm CLI through the managed (or system) Node.js-//! toolchain.-//!-//! Thin wrapper over `npm <subcommand> <args...>` that piggybacks on-//! [`crate::runtime::javascript::NodeBootstrap`] for binary resolution.-//! Same security posture as-//! [`crate::tools::impl::system::shell::ShellTool`] and-//! [`crate::tools::impl::system::node_exec::NodeExecTool`]:-//!-//! * Host env is cleared before spawning; only functional vars (`HOME`,-//! `TERM`, `LANG`, …) are forwarded.-//! * `PATH` is rebuilt with the resolved bin dir prepended so `npm`'s own-//! `node`/`corepack` lookups hit the managed toolchain first.-//! * Rate limits + action budget tracking piggyback on `SecurityPolicy`.-//!-//! The `subcommand` parameter is required and cannot contain shell-//! metacharacters (guarded server-side). Free-form args go through-//! POSIX-safe single-quoting.--use crate::agent::host_runtime::RuntimeAdapter;-use crate::runtime::javascript::NodeBootstrap;-use crate::sandbox;-use crate::security::{CommandClass, GateDecision, SecurityPolicy};-use crate::tools::schema_cache::static_schema;-use async_trait::async_trait;-use std::sync::Arc;-use std::time::Duration;-use tinytools::ToolRunContext;-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};--/// Absolute ceiling callers can request via `timeout_secs`. There is **no**-/// default timeout — `npm install`/build steps on a cold cache or slow network-/// legitimately take minutes and must not be hard-killed by a default cap-/// (issue #4023). A deadline applies only when `timeout_secs` is supplied.-const NPM_TIMEOUT_MAX_SECS: u64 = 1800;-/// Output cap per stream (1 MB).-const MAX_OUTPUT_BYTES: usize = 1_048_576;-/// Env allow-list — matches the shell / node_exec tools.-const SAFE_ENV_VARS: &[&str] = &[- "HOME",- "TERM",- "LANG",- "LC_ALL",- "LC_CTYPE",- "USER",- "SHELL",- "TMPDIR",- // Windows process creation and child command lookup need these after env_clear().- // PATH is rebuilt separately with the managed Node bin dir prepended.- "SystemRoot",- "WINDIR",- "COMSPEC",- "PATHEXT",- "TEMP",- "TMP",- "USERPROFILE",- "APPDATA",- "LOCALAPPDATA",- "ProgramFiles",- "ProgramFiles(x86)",- "ProgramW6432",-];--/// Subcommands we outright refuse to run. These either break the managed-/// cache (`uninstall` of tooling bundled with the install) or perform-/// write actions outside the workspace (`publish` to a registry, `adduser`-/// / `login` / `logout` which mutate `~/.npmrc`).-const DISALLOWED_SUBCOMMANDS: &[&str] = &[- "publish",- "unpublish",- "adduser",- "login",- "logout",- "token",- "star",- "unstar",- "owner",- "access",- "team",- "hook",- "profile",-];--/// `npm_exec` — run npm subcommands (install, run, ci, test, …).-pub struct NpmExecTool {- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- bootstrap: Arc<NodeBootstrap>,-}--impl NpmExecTool {- pub fn new(- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- bootstrap: Arc<NodeBootstrap>,- ) -> Self {- Self {- security,- runtime,- bootstrap,- }- }-}--#[async_trait]-impl Tool for NpmExecTool {- fn exposure(&self) -> tinytools::ToolExposure {- tinytools::ToolExposure::Deferred- }-- fn name(&self) -> &str {- "npm_exec"- }-- fn description(&self) -> &str {- "Run an npm subcommand (install, ci, run, test, exec, …) in the workspace. Dangerous registry/auth commands (publish, login, adduser, token, …) are blocked."- }-- fn parameters_schema(&self) -> serde_json::Value {- static_schema!(include_str!("parameters/npm_exec.json"))- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Execute- }-- /// `npm_exec` runs installs/builds that legitimately take a long time, so it- /// runs unbounded unless the caller passes an explicit `timeout_secs`- /// (capped at [`NPM_TIMEOUT_MAX_SECS`]).- fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {- npm_timeout_policy(args)- }-- /// npm subcommands run arbitrary scripts (`run`/`exec`/lifecycle hooks) →- /// the `Write` bucket, so ask-before-edit routes through the human approval- /// gate and read-only `execute` refuses below. Previously `npm_exec`- /// bypassed the gate (only the rate limiter applied).- fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {- self.security.gate_decision(CommandClass::Write) == GateDecision::Prompt- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, None).await- }-- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: ToolCallOptions,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, context).await- }-}--impl NpmExecTool {- async fn execute_in_context(- &self,- args: serde_json::Value,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let subcommand = match args.get("subcommand").and_then(|v| v.as_str()) {- Some(s) => s.trim().to_string(),- None => {- return Ok(ToolResult::error(- "npm_exec requires a `subcommand` (e.g. install, ci, run).",- ));- }- };- if subcommand.is_empty() {- return Ok(ToolResult::error("npm_exec `subcommand` cannot be empty"));- }- if !is_sane_subcommand(&subcommand) {- return Ok(ToolResult::error(format!(- "npm_exec rejected subcommand {subcommand:?}: only alphanumeric/._- characters allowed"- )));- }- if DISALLOWED_SUBCOMMANDS- .iter()- .any(|d| d.eq_ignore_ascii_case(&subcommand))- {- return Ok(ToolResult::error(format!(- "npm_exec refuses to run `npm {subcommand}` — registry/auth mutations are blocked"- )));- }-- let extra_args: Vec<String> = args- .get("args")- .and_then(|v| v.as_array())- .map(|arr| {- arr.iter()- .filter_map(|v| v.as_str().map(str::to_string))- .collect()- })- .unwrap_or_default();-- let cwd_override = args.get("cwd").and_then(|v| v.as_str()).map(str::to_string);-- // No default deadline — only a caller-supplied `timeout_secs` (capped)- // bounds the run. `None` ⇒ run to completion.- let explicit_timeout = crate::tools::timeout::explicit_call_timeout_duration(- args.get("timeout_secs").and_then(|v| v.as_u64()),- NPM_TIMEOUT_MAX_SECS,- );-- // Read-only mode performs no acts. npm runs arbitrary scripts, so it- // must refuse here — it previously skipped the autonomy check entirely.- if !self.security.can_act() {- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: the agent is in read-only mode and cannot run npm.",- ));- }- let path_policy = super::security_for_tool_context(&self.security, context, "npm_exec");- for input in extra_args.iter().chain(cwd_override.iter()) {- if let Err(reason) = path_policy.check_protected_path_literals(input) {- return Ok(ToolResult::error(reason));- }- }- let cwd = match resolve_cwd(&path_policy.action_dir, cwd_override.as_deref()) {- Ok(p) => p,- Err(msg) => return Ok(ToolResult::error(msg)),- };- if self.security.is_rate_limited() {- return Ok(ToolResult::error(- "Rate limit exceeded: too many actions in the last hour",- ));- }- if !self.security.record_action() {- return Ok(ToolResult::error(- "Rate limit exceeded: action budget exhausted",- ));- }-- let resolved = match self.bootstrap.resolve().await {- Ok(r) => r,- Err(e) => {- tracing::error!(error = %e, "[npm_exec] failed to resolve node runtime");- return Ok(ToolResult::error(format!(- "Node.js runtime unavailable: {e}"- )));- }- };-- tracing::info!(- version = %resolved.version,- source = ?resolved.source,- npm_bin = %resolved.npm_bin.display(),- subcommand = %subcommand,- "[npm_exec] starting invocation"- );-- let mut parts: Vec<String> = Vec::with_capacity(extra_args.len() + 2);- parts.push(shell_quote(&resolved.npm_bin.to_string_lossy()));- parts.push(shell_quote(&subcommand));- for a in &extra_args {- parts.push(shell_quote(a));- }- let command = parts.join(" ");-- // Route sandboxed agents and explicit operator backend selections- // through the shared sandbox path before native execution.- let sandbox_required = match sandbox::command_requires_sandbox().await {- Ok(required) => required,- Err(err) => {- return Ok(ToolResult::error(format!(- "Cannot read sandbox configuration: {err}"- )))- }- };- if sandbox_required {- return Ok(self- .run_sandboxed(- &path_policy,- &command,- &cwd,- &resolved.bin_dir,- explicit_timeout,- )- .await);- }-- let mut cmd = match self.runtime.build_shell_command(&command, &cwd) {- Ok(cmd) => cmd,- Err(e) => {- return Ok(ToolResult::error(format!(- "Failed to build runtime command: {e}"- )));- }- };-- cmd.env_clear();-- let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();- let sep = if cfg!(windows) { ";" } else { ":" };- let prepended_path = if host_path.is_empty() {- resolved.bin_dir.to_string_lossy().into_owned()- } else {- format!("{}{}{}", resolved.bin_dir.display(), sep, host_path)- };- cmd.env("PATH", &prepended_path);-- for var in SAFE_ENV_VARS {- if let Ok(val) = crate::tools::timeout::CommandEnvironment::var(var) {- cmd.env(var, val);- }- }-- // Bounded only when the caller asked for a deadline; otherwise run to- // completion (no harness/tool timeout on long installs/builds).- let result = match explicit_timeout {- Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,- None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),- };-- match result {- Ok(Ok(output)) => {- let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();- let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();-- if stdout.len() > MAX_OUTPUT_BYTES {- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));- stdout.push_str("\n... [stdout truncated at 1MB]");- }- if stderr.len() > MAX_OUTPUT_BYTES {- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));- stderr.push_str("\n... [stderr truncated at 1MB]");- }-- if output.status.success() {- if stderr.is_empty() {- Ok(ToolResult::success(stdout))- } else {- Ok(ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}")))- }- } else {- // Surface exit code + both streams so the agent can diagnose- // the failure instead of re-running it (#4095).- Ok(tinytools::command_failure(- output.status.code(),- &stdout,- &stderr,- ))- }- }- Ok(Err(e)) => Ok(ToolResult::error(format!("Failed to execute npm: {e}"))),- Err(_) => Ok(ToolResult::error(format!(- "npm_exec timed out after {}s and was killed",- explicit_timeout.map(|d| d.as_secs()).unwrap_or(0)- ))),- }- }-}--impl NpmExecTool {- /// Execute an npm command through the sandbox backend. Called from- /// `execute()` when the agent's `SandboxMode` is `Sandboxed`.- ///- /// Mirrors `ShellTool::run_sandboxed` and `NodeExecTool::run_sandboxed`.- /// The sandbox policy is resolved from the current `RuntimeConfig` and- /// rooted at the effective `security.action_dir` — note that the actual- /// child-process `working_dir` may be a sub-path of `action_dir` (the- /// resolved `cwd` from `cwd_override`), kept consistent with the- /// unsandboxed path.- async fn run_sandboxed(- &self,- security: &SecurityPolicy,- command: &str,- cwd: &std::path::Path,- bin_dir: &std::path::Path,- timeout: Option<Duration>,- ) -> ToolResult {- use crate::sandbox;-- // Sandbox backends require a finite deadline. When the caller did not- // request one, use a generous effective-unbounded cap (24h) — long- // enough not to kill a legitimate install/build, finite enough to- // eventually reclaim a wedged sandbox process. The native path runs- // truly unbounded.- let effective = timeout.unwrap_or_else(|| {- Duration::from_secs(crate::tools::timeout::SANDBOX_UNBOUNDED_CAP_SECS)- });-- let policy = match sandbox::ops::resolve_command_policy(- &security.action_dir,- &security.workspace_dir,- )- .await- {- Ok(policy) => policy,- Err(why) => return ToolResult::error(format!("Sandbox unavailable: {why}")),- };-- if policy.backend == sandbox::SandboxBackendKind::Docker {- return ToolResult::error(- "npm_exec cannot use the Docker sandbox: its host npm and Node.js binaries are not mounted in the container",- );- }-- tracing::debug!(backend = ?policy.backend, "[npm_exec] routing to sandbox backend");-- // Forward the managed Node.js bin dir on PATH so npm child invocations- // (e.g. `npm run` spawning user scripts) resolve `node`/`npx`- // consistently with the unsandboxed path.- let mut extra_env = std::collections::HashMap::new();- let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();- let sep = if cfg!(windows) { ";" } else { ":" };- let prepended = if host_path.is_empty() {- bin_dir.to_string_lossy().into_owned()- } else {- format!("{}{}{}", bin_dir.display(), sep, host_path)- };- extra_env.insert("PATH".into(), prepended.into());-- match sandbox::execute_in_sandbox(&policy, command, cwd, extra_env, effective).await {- Ok(result) => {- if result.timed_out {- ToolResult::error(format!(- "npm_exec timed out after {}s and was killed",- effective.as_secs()- ))- } else if result.success() {- if result.stderr.is_empty() {- ToolResult::success(result.stdout)- } else {- ToolResult::success(format!(- "{}\n[stderr]\n{}",- result.stdout, result.stderr- ))- }- } else {- tinytools::command_failure(- tinytools::sandbox_exit_code(result.exit_code),- &result.stdout,- &result.stderr,- )- }- }- Err(e) => ToolResult::error(format!("Sandbox execution failed: {e}")),- }- }-}--/// Resolve the wall-clock policy for an `npm_exec` call from its args.-///-/// No `timeout_secs` (or `0`) ⇒ run unbounded; a positive value ⇒ enforce it,-/// clamped to [`NPM_TIMEOUT_MAX_SECS`]. Extracted from-/// [`NpmExecTool::timeout_policy`] so it is unit-testable without a bootstrap.-fn npm_timeout_policy(args: &serde_json::Value) -> ToolTimeout {- match args.get("timeout_secs").and_then(|v| v.as_u64()) {- None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Millis(secs.min(NPM_TIMEOUT_MAX_SECS).saturating_mul(1000)),- }-}--/// POSIX-safe single-quote escaping (mirrors the helper in `node_exec`).-/// Wraps `s` in `'…'`, turning any embedded single-quote into `'\''` so no-/// shell metacharacter can escape the quoted string.-fn shell_quote(s: &str) -> String {- let escaped = s.replace('\'', "'\\''");- format!("'{escaped}'")-}--/// Subcommands must be plain identifiers (`install`, `run`, `ci`, `exec`,-/// `test:watch`) — never a command substitution or redirection payload.-fn is_sane_subcommand(s: &str) -> bool {- !s.is_empty()- && s.chars()- .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | ':'))-}--/// Resolve an optional `cwd` override against the workspace. Rejects any-/// path that escapes the workspace via `..` or absolute components.-fn resolve_cwd(- workspace: &std::path::Path,- override_path: Option<&str>,-) -> Result<std::path::PathBuf, String> {- match override_path {- None => Ok(workspace.to_path_buf()),- Some(raw) => {- let raw = raw.trim();- if raw.is_empty() || raw == "." {- return Ok(workspace.to_path_buf());- }- let candidate = std::path::Path::new(raw);- if candidate.is_absolute() {- return Err(format!(- "npm_exec `cwd` must be relative to workspace; got absolute path {raw:?}"- ));- }- if candidate.components().any(|c| {- matches!(- c,- std::path::Component::ParentDir | std::path::Component::Prefix(_)- )- }) {- return Err(format!(- "npm_exec `cwd` must not escape workspace; got {raw:?}"- ));- }- Ok(workspace.join(candidate))- }- }-}--#[cfg(test)]-#[path = "npm_exec_tests.rs"]-mod tests;--#[cfg(test)]-#[path = "npm_exec_schema_tests.rs"]-mod schema_tests;diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec_schema_tests.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec_schema_tests.rsdeleted file mode 100644index 09811b862a..0000000000--- a/crates/openhuman-core/src/tools/impl/system/npm_exec_schema_tests.rs+++ /dev/null@@ -1,43 +0,0 @@-use super::*;-use serde_json::json;--fn expected_npm_exec() -> serde_json::Value {- json!({- "type": "object",- "properties": {- "subcommand": {- "type": "string",- "description": "npm subcommand, e.g. `install`, `ci`, `run`, `test`, `exec`."- },- "args": {- "type": "array",- "items": { "type": "string" },- "description": "Arguments appended after the subcommand (e.g. [\"build\"] for `npm run build`)."- },- "cwd": {- "type": "string",- "description": "Optional sub-directory (relative to workspace) to run npm in. Defaults to the workspace root."- },- "timeout_secs": {- "type": "integer",- "description": "Optional wall-clock timeout (seconds) before npm is killed. No timeout by default — installs/builds run to completion. Capped at 1800s; 0 disables."- }- },- "required": ["subcommand"]- })-}--#[test]-fn npm_exec_static_schema_matches_json_literal() {- let tool = NpmExecTool::new(- std::sync::Arc::new(crate::security::SecurityPolicy::default()),- std::sync::Arc::new(crate::agent::host_runtime::NativeRuntime::new()),- std::sync::Arc::new(NodeBootstrap::new(std::sync::Arc::new(- crate::config::Config::default(),- ))),- );- assert_eq!(- tinytools::Tool::parameters_schema(&tool),- expected_npm_exec()- );-}diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rsdeleted file mode 100644index 4472c00db8..0000000000--- a/crates/openhuman-core/src/tools/impl/system/npm_exec_tests.rs+++ /dev/null@@ -1,103 +0,0 @@-use super::*;-use serde_json::json;--#[tokio::test]-async fn npm_exec_blocks_protected_literal_before_runtime_resolution() {- let tool = NpmExecTool::new(- std::sync::Arc::new(crate::security::SecurityPolicy {- enabled: false,- ..crate::security::SecurityPolicy::default()- }),- std::sync::Arc::new(crate::agent::host_runtime::NativeRuntime::new()),- std::sync::Arc::new(NodeBootstrap::new(std::sync::Arc::new(- crate::config::Config::default(),- ))),- );- let result = tool- .execute(json!({"subcommand": "run", "args": ["~/.npmrc"]}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.text().contains("protected path"));-}-fn absolute_sample() -> &'static str {- if cfg!(windows) {- "C:\\Windows\\System32"- } else {- "/etc"- }-}--#[test]-fn npm_timeout_policy_unbounded_by_default() {- assert_eq!(npm_timeout_policy(&json!({})), ToolTimeout::Unbounded);- assert_eq!(- npm_timeout_policy(&json!({"timeout_secs": 0})),- ToolTimeout::Unbounded- );-}--#[test]-fn npm_timeout_policy_enforces_and_caps_explicit() {- assert_eq!(- npm_timeout_policy(&json!({"timeout_secs": 300})),- ToolTimeout::Millis(300_000)- );- assert_eq!(- npm_timeout_policy(&json!({"timeout_secs": 99999})),- ToolTimeout::Millis(NPM_TIMEOUT_MAX_SECS * 1000)- );-}--#[test]-fn is_sane_subcommand_accepts_common_npm_verbs() {- for v in &[- "install",- "ci",- "run",- "exec",- "test",- "test:watch",- "run-script",- ] {- assert!(is_sane_subcommand(v), "{v} should be accepted");- }-}--#[test]-fn is_sane_subcommand_rejects_metacharacters() {- for v in &["install; rm -rf /", "run && echo", "|cat", "$(whoami)", ""] {- assert!(!is_sane_subcommand(v), "{v} should be rejected");- }-}--#[test]-fn resolve_cwd_defaults_to_workspace() {- let ws = std::path::Path::new("/tmp/ws");- assert_eq!(resolve_cwd(ws, None).unwrap(), ws);- assert_eq!(resolve_cwd(ws, Some("")).unwrap(), ws);- assert_eq!(resolve_cwd(ws, Some(".")).unwrap(), ws);-}--#[test]-fn resolve_cwd_rejects_absolute_and_parent() {- let ws = std::path::Path::new("/tmp/ws");- assert!(resolve_cwd(ws, Some(absolute_sample())).is_err());- assert!(resolve_cwd(ws, Some("../other")).is_err());- assert!(resolve_cwd(ws, Some("sub/../../../etc")).is_err());-}--#[test]-fn resolve_cwd_allows_relative_subdir() {- let ws = std::path::Path::new("/tmp/ws");- let got = resolve_cwd(ws, Some("app")).unwrap();- assert_eq!(got, std::path::PathBuf::from("/tmp/ws/app"));-}--#[test]-fn safe_env_vars_include_windows_process_essentials() {- crate::agent::platform_shell::assert_forwards_windows_bootstrap(- SAFE_ENV_VARS,- "npm_exec::SAFE_ENV_VARS",- );-}diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec.rs b/crates/openhuman-core/src/tools/impl/system/python_exec.rsdeleted file mode 100644index 2c1d96e582..0000000000--- a/crates/openhuman-core/src/tools/impl/system/python_exec.rs+++ /dev/null@@ -1,582 +0,0 @@-//! `python_exec` — execute Python 3 via the managed (or system) interpreter.-//!-//! Sibling to [`node_exec`](super::node_exec) with identical security gates and-//! env hygiene; the command is pinned to the `python` binary resolved by-//! [`crate::runtime::python::PythonBootstrap`].-//!-//! Two input modes:-//!-//! | Mode | Params | Resulting invocation |-//! |---------------|-------------------------------------------|--------------------------------|-//! | Inline code | `inline_code: "print(1+1)"` | `python -c '<code>'` |-//! | Script path | `script_path: "scripts/run.py"`, `args` | `python <path> <args...>` |-//!-//! Inline code routes through the shared runtime pool (#5106) when enabled — a-//! warm, bounded set of `python` workers replaces one interpreter child per-//! call — and transparently falls back to a per-call spawn otherwise. Script-//! paths and sandboxed runs always use the per-call spawn.--use crate::agent::host_runtime::RuntimeAdapter;-use crate::runtime::python::PythonBootstrap;-use crate::sandbox;-use crate::security::{CommandClass, GateDecision, SecurityPolicy};-use async_trait::async_trait;-use serde_json::json;-use std::sync::Arc;-use std::time::Duration;-use tinytools::ToolRunContext;-use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolResult, ToolTimeout};--/// Absolute ceiling a caller may request via `timeout_secs`. No default timeout —-/// Python scripts legitimately take minutes; a deadline applies only when-/// `timeout_secs` is supplied. Mirrors `node_exec` (issue #4023).-const PYTHON_TIMEOUT_MAX_SECS: u64 = 1800;-/// Maximum combined stdout/stderr size (1 MB each) — same cap as shell/node.-const MAX_OUTPUT_BYTES: usize = 1_048_576;-/// Env allow-list for child processes. Matches node_exec/shell — secrets never-/// leak into spawned python processes. `PATH` gets a prepend of the managed bin-/// dir before being forwarded.-const SAFE_ENV_VARS: &[&str] = &[- "HOME",- "TERM",- "LANG",- "LC_ALL",- "LC_CTYPE",- "USER",- "SHELL",- "TMPDIR",- "SystemRoot",- "WINDIR",- "COMSPEC",- "PATHEXT",- "TEMP",- "TMP",- "USERPROFILE",- "APPDATA",- "LOCALAPPDATA",- "ProgramFiles",- "ProgramFiles(x86)",- "ProgramW6432",-];--/// `python_exec` — execute Python through the resolved Python 3 runtime.-pub struct PythonExecTool {- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- bootstrap: Arc<PythonBootstrap>,- /// Runtime-pool config + workspace, snapshotted at construction so the hot- /// inline path never re-reads config from disk (#5106 is a perf feature).- pool_cfg: crate::config::RuntimePoolConfig,- workspace_dir: std::path::PathBuf,-}--impl PythonExecTool {- pub fn new(- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- bootstrap: Arc<PythonBootstrap>,- pool_cfg: crate::config::RuntimePoolConfig,- workspace_dir: std::path::PathBuf,- ) -> Self {- Self {- security,- runtime,- bootstrap,- pool_cfg,- workspace_dir,- }- }-}--#[async_trait]-impl Tool for PythonExecTool {- fn exposure(&self) -> tinytools::ToolExposure {- tinytools::ToolExposure::Deferred- }-- fn name(&self) -> &str {- "python_exec"- }-- fn description(&self) -> &str {- "Execute Python 3 through the managed interpreter. Pass either `inline_code` (runs via `python -c`) or `script_path` (runs a .py file in your working directory, the action sandbox). Optional `args` forwards positional arguments to the script. Only the program's stdout/stderr is captured and returned to you — a value you do not `print` is invisible. Always print the output you need (e.g. `print(json.dumps(result))`)."- }-- fn parameters_schema(&self) -> serde_json::Value {- json!({- "type": "object",- "properties": {- "inline_code": {- "type": "string",- "description": "Python source passed to `python -c`. Mutually exclusive with script_path."- },- "script_path": {- "type": "string",- "description": "Path (relative to workspace) to a .py file. Mutually exclusive with inline_code."- },- "args": {- "type": "array",- "items": { "type": "string" },- "description": "Positional arguments appended after the script. Ignored for inline_code."- },- "timeout_secs": {- "type": "integer",- "description": "Optional wall-clock timeout (seconds) before the process is killed. No timeout by default. Capped at 1800s; 0 disables."- }- }- })- }-- fn permission_level(&self) -> PermissionLevel {- PermissionLevel::Execute- }-- fn timeout_policy(&self, args: &serde_json::Value) -> ToolTimeout {- python_timeout_policy(args)- }-- /// Running Python is arbitrary code execution → the `Write` bucket, same as- /// `node_exec`. In ask-before-edit this routes through the human approval- /// gate; in Full it runs; in read-only it refuses below.- fn external_effect_with_args(&self, _args: &serde_json::Value) -> bool {- self.security.gate_decision(CommandClass::Write) == GateDecision::Prompt- }-- async fn execute(&self, args: serde_json::Value) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, None).await- }-- async fn execute_with_context(- &self,- args: serde_json::Value,- _options: ToolCallOptions,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- self.execute_in_context(args, context).await- }-}--impl PythonExecTool {- async fn execute_in_context(- &self,- args: serde_json::Value,- context: Option<&dyn ToolRunContext>,- ) -> anyhow::Result<ToolResult> {- let inline_code = args- .get("inline_code")- .and_then(|v| v.as_str())- .map(str::to_string);- let script_path = args- .get("script_path")- .and_then(|v| v.as_str())- .map(str::to_string);-- let extra_args: Vec<String> = args- .get("args")- .and_then(|v| v.as_array())- .map(|arr| {- arr.iter()- .filter_map(|v| v.as_str().map(str::to_string))- .collect()- })- .unwrap_or_default();-- let explicit_timeout = crate::tools::timeout::explicit_call_timeout_duration(- args.get("timeout_secs").and_then(|v| v.as_u64()),- PYTHON_TIMEOUT_MAX_SECS,- );-- if inline_code.is_some() == script_path.is_some() {- return Ok(ToolResult::error(- "python_exec requires exactly one of `inline_code` or `script_path`",- ));- }-- if !self.security.can_act() {- return Ok(ToolResult::error(- "[policy-blocked] Action blocked: the agent is in read-only mode and cannot execute code.",- ));- }- if self.security.is_rate_limited() {- return Ok(ToolResult::error(- "Rate limit exceeded: too many actions in the last hour",- ));- }- if !self.security.record_action() {- return Ok(ToolResult::error(- "Rate limit exceeded: action budget exhausted",- ));- }-- let resolved = match self.bootstrap.resolve().await {- Ok(r) => r,- Err(e) => {- tracing::error!(error = %e, "[python_exec] failed to resolve python runtime");- return Ok(ToolResult::error(format!(- "Python runtime unavailable: {e}"- )));- }- };-- tracing::info!(- version = %resolved.version,- python_bin = %resolved.python_bin.display(),- "[python_exec] starting invocation"- );-- let path_policy = super::security_for_tool_context(&self.security, context, "python_exec");- for input in inline_code- .iter()- .chain(script_path.iter())- .chain(extra_args.iter())- {- if let Err(reason) = path_policy.check_protected_path_literals(input) {- return Ok(ToolResult::error(reason));- }- }-- let command = if let Some(code) = inline_code.as_deref() {- format!(- "{} -c {}",- shell_quote(&resolved.python_bin.to_string_lossy()),- shell_quote(code)- )- } else if let Some(path) = script_path.as_deref() {- let resolved_script = match resolve_script_path(&path_policy.action_dir, path) {- Ok(p) => p,- Err(msg) => return Ok(ToolResult::error(msg)),- };- let mut parts: Vec<String> = Vec::with_capacity(extra_args.len() + 2);- parts.push(shell_quote(&resolved.python_bin.to_string_lossy()));- parts.push(shell_quote(&resolved_script.to_string_lossy()));- for a in &extra_args {- parts.push(shell_quote(a));- }- parts.join(" ")- } else {- unreachable!("guarded above")- };-- // Sandboxed agents and explicit operator backend selections use the- // sandbox path, mirroring node_exec.- let sandbox_required = match sandbox::command_requires_sandbox().await {- Ok(required) => required,- Err(err) => {- return Ok(ToolResult::error(format!(- "Cannot read sandbox configuration: {err}"- )))- }- };- if sandbox_required {- let bin_dir = resolved- .python_bin- .parent()- .map(std::path::Path::to_path_buf)- .unwrap_or_default();- return Ok(self- .run_sandboxed(&path_policy, &command, &bin_dir, explicit_timeout)- .await);- }-- // Route inline Python through the shared runtime pool when enabled- // (#5106). script_path and sandboxed runs keep the per-call spawn; a- // pool infrastructure failure also transparently falls back below.- if let Some(code) = inline_code.as_deref() {- if let Some(result) = self- .try_pool_inline(code, &path_policy.action_dir, explicit_timeout)- .await- {- return Ok(result);- }- }-- let mut cmd = match self- .runtime- .build_shell_command(&command, &path_policy.action_dir)- {- Ok(cmd) => cmd,- Err(e) => {- return Ok(ToolResult::error(format!(- "Failed to build runtime command: {e}"- )));- }- };-- cmd.env_clear();-- let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();- let sep = if cfg!(windows) { ";" } else { ":" };- let prepended_path = if host_path.is_empty() {- resolved.bin_dir.to_string_lossy().into_owned()- } else {- format!("{}{}{}", resolved.bin_dir.display(), sep, host_path)- };- cmd.env("PATH", &prepended_path);- // Unbuffered stdio so partial output survives a kill on timeout.- cmd.env("PYTHONUNBUFFERED", "1");-- for var in SAFE_ENV_VARS {- if let Ok(val) = crate::tools::timeout::CommandEnvironment::var(var) {- cmd.env(var, val);- }- }-- let result = match explicit_timeout {- Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,- None => Ok(crate::tools::timeout::output_unbounded(&mut cmd).await),- };-- match result {- Ok(Ok(output)) => {- let mut stdout = String::from_utf8_lossy(&output.stdout).to_string();- let mut stderr = String::from_utf8_lossy(&output.stderr).to_string();-- if stdout.len() > MAX_OUTPUT_BYTES {- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));- stdout.push_str("\n... [stdout truncated at 1MB]");- }- if stderr.len() > MAX_OUTPUT_BYTES {- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));- stderr.push_str("\n... [stderr truncated at 1MB]");- }-- if output.status.success() {- if stderr.is_empty() {- Ok(ToolResult::success(stdout))- } else {- Ok(ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}")))- }- } else {- Ok(tinytools::command_failure(- output.status.code(),- &stdout,- &stderr,- ))- }- }- Ok(Err(e)) => Ok(ToolResult::error(format!("Failed to execute python: {e}"))),- Err(_) => Ok(ToolResult::error(format!(- "python_exec timed out after {}s and was killed",- explicit_timeout.map(|d| d.as_secs()).unwrap_or(0)- ))),- }- }-- /// Attempt to run inline Python on the shared runtime pool (#5106). Returns- /// `Some(result)` when the pool handled the job; `None` when pooling is- /// disabled or the pool infrastructure failed (caller falls back to spawn).- async fn try_pool_inline(- &self,- code: &str,- action_dir: &std::path::Path,- timeout: Option<Duration>,- ) -> Option<ToolResult> {- if !crate::runtime::pool::python::enabled(&self.pool_cfg) {- return None;- }- match crate::runtime::pool::python::run_inline(- self.bootstrap.config(),- code.to_string(),- Some(action_dir.to_path_buf()),- timeout,- )- .await- {- Ok(outcome) => {- tracing::info!(- queue_wait_ms = outcome.queue_wait.as_millis() as u64,- elapsed_ms = outcome.elapsed.as_millis() as u64,- timed_out = outcome.timed_out,- "[python_exec] pool: inline job completed on a warm worker"- );- Some(pool_outcome_to_result(outcome, timeout))- }- // Job never ran → safe to fall back to a per-call spawn.- Err(crate::runtime::pool::PoolRunError::PreDispatch(error)) => {- tracing::warn!(- error = %error,- "[python_exec] pool: pre-dispatch failure; falling back to legacy spawn"- );- None- }- // Load-shed: do NOT spawn (that reintroduces per-run RSS). Surface busy.- Err(crate::runtime::pool::PoolRunError::Saturated) => {- tracing::warn!("[python_exec] pool: saturated; shedding load");- Some(ToolResult::error(- "Python runtime pool is at capacity; retry shortly.",- ))- }- // The job may already have executed → terminal, never re-run it.- Err(crate::runtime::pool::PoolRunError::PostDispatch(error)) => {- tracing::warn!(- error = %error,- "[python_exec] pool: post-dispatch failure; not retried to avoid duplicate execution"- );- Some(ToolResult::error(format!(- "python_exec failed after the code was dispatched to a pooled worker; not retried to avoid running it twice: {error}"- )))- }- }- }-- /// Execute a python command through the sandbox backend. Mirrors- /// `NodeExecTool::run_sandboxed`.- async fn run_sandboxed(- &self,- security: &SecurityPolicy,- command: &str,- bin_dir: &std::path::Path,- timeout: Option<Duration>,- ) -> ToolResult {- use crate::sandbox;-- let effective = timeout.unwrap_or_else(|| {- Duration::from_secs(crate::tools::timeout::SANDBOX_UNBOUNDED_CAP_SECS)- });-- let policy = match sandbox::ops::resolve_command_policy(- &security.action_dir,- &security.workspace_dir,- )- .await- {- Ok(policy) => policy,- Err(why) => return ToolResult::error(format!("Sandbox unavailable: {why}")),- };-- if policy.backend == sandbox::SandboxBackendKind::Docker {- return ToolResult::error(- "python_exec cannot use the Docker sandbox: its host Python binary and script paths are not mounted in the container",- );- }-- let mut extra_env = std::collections::HashMap::new();- let host_path = crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default();- let sep = if cfg!(windows) { ";" } else { ":" };- let prepended = if host_path.is_empty() {- bin_dir.to_string_lossy().into_owned()- } else {- format!("{}{}{}", bin_dir.display(), sep, host_path)- };- extra_env.insert("PATH".into(), prepended.into());- extra_env.insert("PYTHONUNBUFFERED".into(), "1".into());-- match sandbox::execute_in_sandbox(- &policy,- command,- &security.action_dir,- extra_env,- effective,- )- .await- {- Ok(result) => {- if result.timed_out {- ToolResult::error(format!(- "python_exec timed out after {}s and was killed",- effective.as_secs()- ))- } else if result.success() {- if result.stderr.is_empty() {- ToolResult::success(result.stdout)- } else {- ToolResult::success(format!(- "{}\n[stderr]\n{}",- result.stdout, result.stderr- ))- }- } else {- tinytools::command_failure(- tinytools::sandbox_exit_code(result.exit_code),- &result.stdout,- &result.stderr,- )- }- }- Err(e) => ToolResult::error(format!("Sandbox execution failed: {e}")),- }- }-}--/// Map a runtime-pool outcome onto the same `ToolResult` shape the legacy-/// `python -c` path produces.-fn pool_outcome_to_result(- outcome: crate::runtime::pool::PoolExecOutcome,- timeout: Option<Duration>,-) -> ToolResult {- if outcome.timed_out {- return ToolResult::error(format!(- "python_exec timed out after {}s and was killed",- timeout.map(|d| d.as_secs()).unwrap_or(0)- ));- }-- let mut stdout = outcome.stdout;- let mut stderr = outcome.stderr;- if stdout.len() > MAX_OUTPUT_BYTES {- stdout.truncate(crate::util::floor_char_boundary(&stdout, MAX_OUTPUT_BYTES));- stdout.push_str("\n... [stdout truncated at 1MB]");- }- if stderr.len() > MAX_OUTPUT_BYTES {- stderr.truncate(crate::util::floor_char_boundary(&stderr, MAX_OUTPUT_BYTES));- stderr.push_str("\n... [stderr truncated at 1MB]");- }-- let success = matches!(outcome.exit_code, None | Some(0));- if success {- if stderr.is_empty() {- ToolResult::success(stdout)- } else {- ToolResult::success(format!("{stdout}\n[stderr]\n{stderr}"))- }- } else {- tinytools::command_failure(outcome.exit_code, &stdout, &stderr)- }-}--/// Resolve the wall-clock policy for a `python_exec` call from its args.-fn python_timeout_policy(args: &serde_json::Value) -> ToolTimeout {- match args.get("timeout_secs").and_then(|v| v.as_u64()) {- None | Some(0) => ToolTimeout::Unbounded,- Some(secs) => ToolTimeout::Millis(secs.min(PYTHON_TIMEOUT_MAX_SECS).saturating_mul(1000)),- }-}--/// POSIX-safe single-quote escaping (mirrors node_exec::shell_quote).-fn shell_quote(s: &str) -> String {- let escaped = s.replace('\'', "'\\''");- format!("'{escaped}'")-}--/// Resolve a caller-supplied `script_path` against the workspace. Rejects-/// absolute paths and any component that could escape the workspace.-fn resolve_script_path(- workspace: &std::path::Path,- raw: &str,-) -> Result<std::path::PathBuf, String> {- let raw = raw.trim();- if raw.is_empty() {- return Err("python_exec `script_path` cannot be empty".to_string());- }- let candidate = std::path::Path::new(raw);- if candidate.is_absolute() {- return Err(format!(- "python_exec `script_path` must be relative to workspace; got absolute {raw:?}"- ));- }- if candidate.components().any(|c| {- matches!(- c,- std::path::Component::ParentDir | std::path::Component::Prefix(_)- )- }) {- return Err(format!(- "python_exec `script_path` must not escape workspace; got {raw:?}"- ));- }- Ok(workspace.join(candidate))-}--#[cfg(test)]-#[path = "python_exec_tests.rs"]-mod tests;diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rs b/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rsdeleted file mode 100644index a781157296..0000000000--- a/crates/openhuman-core/src/tools/impl/system/python_exec_tests.rs+++ /dev/null@@ -1,71 +0,0 @@-use super::*;--#[tokio::test]-async fn python_exec_blocks_protected_literal_before_runtime_resolution() {- let tool = PythonExecTool::new(- std::sync::Arc::new(crate::security::SecurityPolicy {- enabled: false,- ..crate::security::SecurityPolicy::default()- }),- std::sync::Arc::new(crate::agent::host_runtime::NativeRuntime::new()),- std::sync::Arc::new(PythonBootstrap::new(std::sync::Arc::new(- crate::config::Config::default(),- ))),- crate::config::RuntimePoolConfig::default(),- std::path::PathBuf::from("."),- );- let result = tool- .execute(json!({"inline_code": "open('~/.aws/credentials').read()"}))- .await- .unwrap();- assert!(result.is_error);- assert!(result.text().contains("protected path"));-}--#[test]-fn python_timeout_policy_unbounded_by_default() {- assert_eq!(python_timeout_policy(&json!({})), ToolTimeout::Unbounded);- assert_eq!(- python_timeout_policy(&json!({"timeout_secs": 0})),- ToolTimeout::Unbounded- );-}--#[test]-fn python_timeout_policy_enforces_and_caps_explicit() {- assert_eq!(- python_timeout_policy(&json!({"timeout_secs": 120})),- ToolTimeout::Millis(120_000)- );- assert_eq!(- python_timeout_policy(&json!({"timeout_secs": 99999})),- ToolTimeout::Millis(PYTHON_TIMEOUT_MAX_SECS * 1000)- );-}--#[test]-fn shell_quote_escapes_single_quotes() {- assert_eq!(shell_quote("it's"), "'it'\\''s'");- assert_eq!(shell_quote("print('hi')"), "'print('\\''hi'\\'')'");-}--#[test]-fn resolve_script_path_rejects_escapes() {- let ws = std::path::Path::new("/ws");- assert!(resolve_script_path(ws, "").is_err());- assert!(resolve_script_path(ws, "../evil.py").is_err());- assert_eq!(- resolve_script_path(ws, "scripts/run.py").unwrap(),- std::path::Path::new("/ws/scripts/run.py")- );-}--/// `python_exec` clears the child environment, so its allow-list must carry the-/// Windows process-bootstrap set — a child without them fails to start.-#[test]-fn safe_env_vars_cover_windows_bootstrap() {- crate::agent::platform_shell::assert_forwards_windows_bootstrap(- SAFE_ENV_VARS,- "python_exec::SAFE_ENV_VARS",- );-}diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rsindex d18e96635d..60577a8fe8 100644--- a/crates/openhuman-core/src/tools/impl/system/shell.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs@@ -1,10 +1,7 @@use super::shell_platform::{- command_param_description, command_with_runtime_path, python_utf8_env, shell_child_env,- shell_description,+ command_param_description, python_utf8_env, shell_child_env, shell_description,};use crate::agent::host_runtime::RuntimeAdapter;-use crate::runtime::javascript::NodeBootstrap;-use crate::runtime::python::PythonBootstrap;use crate::security::{AuditLogger, CommandExecutionLog, GateDecision, SecurityPolicy};use async_trait::async_trait;use serde_json::json;@@ -44,19 +41,6 @@ pub struct ShellTool {security: Arc<SecurityPolicy>,runtime: Arc<dyn RuntimeAdapter>,audit: Arc<AuditLogger>,- /// Optional managed Node.js bootstrap. When provided **and** a prior- /// `NodeBootstrap::resolve()` has already succeeded, every shell invocation- /// transparently prepends the managed `bin/` dir to `PATH` — so skills- /// shelling out to `node`/`npm`/`npx`/`corepack` resolve to the managed- /// toolchain. Non-blocking: never triggers a download for unrelated- /// commands (we use `try_cached()`).- node_bootstrap: Option<Arc<NodeBootstrap>>,- /// Optional managed Python bootstrap. Unlike Node PATH injection, Python- /// shell support is the primary execution surface for skills, so- /// Python-looking commands resolve this lazily before spawn. That keeps- /// `pip install foo` and `python3 -m foo` on one interpreter instead of- /// mixing arbitrary host `pip` and `python3` binaries.- python_bootstrap: Option<Arc<PythonBootstrap>>,}impl ShellTool {@@ -69,28 +53,6 @@ impl ShellTool {security,runtime,audit,- node_bootstrap: None,- python_bootstrap: None,- }- }-- /// Attach managed language runtimes used by shell-invoked skills. Node is- /// injected only after a dedicated node/npm tool resolved it; Python is- /// resolved lazily for python/pip commands because shell is currently the- /// user-facing Python skill execution path.- pub fn with_language_bootstraps(- security: Arc<SecurityPolicy>,- runtime: Arc<dyn RuntimeAdapter>,- audit: Arc<AuditLogger>,- node_bootstrap: Option<Arc<NodeBootstrap>>,- python_bootstrap: Option<Arc<PythonBootstrap>>,- ) -> Self {- Self {- security,- runtime,- audit,- node_bootstrap,- python_bootstrap,}}@@ -385,21 +347,12 @@ impl ShellTool {// Clear the environment to prevent leaking API keys and other secrets// (CWE-200), then re-add only safe, functional variables.let action_dir = self.effective_action_dir_for_context(context);- let runtime_path = self.runtime_path_for_command(command).await;- let execution_command = command_with_runtime_path(- command,- runtime_path.as_deref(),- self.runtime.shell_flavor(),- );- let mut cmd = match self- .runtime- .build_shell_command(&execution_command, &action_dir)- {+ let mut cmd = match self.runtime.build_shell_command(command, &action_dir) {Ok(cmd) => cmd,Err(e) => {return (true,- ToolResult::error(format!("Failed to build runtime command: {e}")),+ ToolResult::error(format!("Failed to build shell command: {e}")),);}};@@ -435,11 +388,6 @@ impl ShellTool {);}- if let Some(path) = runtime_path {- tracing::debug!(path = %path, "[shell] applying managed runtime PATH");- cmd.env("PATH", path);- }-// No default deadline — only a caller-supplied `timeout_secs` bounds the// run. `None` ⇒ run to completion (issue #4023).let explicit_timeout = self.explicit_timeout(requested_timeout);@@ -530,14 +478,6 @@ impl ShellTool {);let mut extra_env = std::collections::HashMap::new();- // A managed runtime's PATH names host directories, which a SaaS- // container cannot see.- if super::shell_saas::passes_runtime_path_with(crate::core::runtime::is_saas()) {- if let Some(path) = self.runtime_path_for_command(command).await {- extra_env.insert("PATH".into(), path.into());- }- }-// Apply the same Git config hardening to local and sandboxed shells.extra_env.extend(tinytools_std::filesystem::shell_git_env());// And the same Python UTF-8 defaults the native path sets.@@ -559,22 +499,7 @@ impl ShellTool {"[shell] starting sandboxed command");- let runtime_path = extra_env- .get(std::ffi::OsStr::new("PATH"))- .and_then(|path| path.to_str());- let execution_command = command_with_runtime_path(- command,- runtime_path,- crate::agent::platform_shell::ShellFlavor::current(),- );- match sandbox::execute_in_sandbox(- &policy,- &execution_command,- action_dir,- extra_env,- effective,- )- .await+ match sandbox::execute_in_sandbox(&policy, command, action_dir, extra_env, effective).await{Ok(result) => {let tool_result = if result.timed_out {@@ -605,144 +530,6 @@ impl ShellTool {),}}-- /// The `PATH` to run `command` under when it needs a managed runtime, or- /// `None` to keep the inherited one.- ///- /// A runtime that cannot be resolved (its module refused or faulted, the- /// download failed) leaves the inherited `PATH` in place rather than- /// failing the command: the host's own interpreter may well run it, and if- /// none exists the command fails with its own `command not found`. Failing- /// here instead blocked every `python …` command for the rest of the run- /// once the runtime module had faulted, even with a working `python3` on- /// the host. This fallback is safe because commands still pass through- /// `check_gated_command` and sandbox policy, and the child already inherits- /// `PATH` through `SAFE_ENV_VARS`.- async fn runtime_path_for_command(&self, command: &str) -> Option<String> {- let mut prepend_dirs = Vec::new();-- // Node injection preserves the existing contract: shell only sees the- // managed Node bin directory after a previous node/npm tool resolved it.- if let Some(bootstrap) = self.node_bootstrap.as_ref() {- if let Some(resolved) = bootstrap.try_cached() {- tracing::debug!(- bin_dir = %resolved.bin_dir.display(),- version = %resolved.version,- "[shell] prepending managed node bin to PATH"- );- prepend_dirs.push(resolved.bin_dir);- }- }-- if shell_command_needs_python_runtime(command) {- if let Some(bootstrap) = self.python_bootstrap.as_ref() {- match bootstrap.resolve().await {- Ok(resolved) => {- tracing::debug!(- bin_dir = %resolved.bin_dir.display(),- python_bin = %resolved.python_bin.display(),- version = %resolved.version,- source = ?resolved.source,- "[shell] prepending python runtime bin to PATH"- );- prepend_dirs.push(resolved.bin_dir);- }- Err(error) => {- log_python_runtime_unavailable(- bootstrap.config().runtime_python.enabled,- &error,- );- }- }- }- }-- if prepend_dirs.is_empty() {- None- } else {- Some(prepend_path_dirs(- prepend_dirs.iter().map(|p| p.as_path()),- &crate::tools::timeout::CommandEnvironment::var("PATH").unwrap_or_default(),- ))- }- }-}--fn log_python_runtime_unavailable(enabled: bool, error: &anyhow::Error) {- if enabled {- tracing::warn!(- error = %error,- "[shell] python runtime unavailable — running on the inherited PATH"- );- } else {- tracing::debug!(- error = %error,- "[shell] python runtime disabled — running on the inherited PATH"- );- }-}--fn prepend_path_dirs<'a>(- dirs: impl IntoIterator<Item = &'a std::path::Path>,- host_path: &str,-) -> String {- let sep = if cfg!(windows) { ";" } else { ":" };- let mut parts: Vec<String> = dirs- .into_iter()- .map(|path| path.to_string_lossy().into_owned())- .collect();- if !host_path.is_empty() {- parts.push(host_path.to_string());- }- parts.join(sep)-}--fn shell_command_needs_python_runtime(command: &str) -> bool {- let lower = command.to_ascii_lowercase();- lower- .split([';', '&', '|', '\n', '\r'])- .any(segment_starts_with_python_command)-}--fn segment_starts_with_python_command(segment: &str) -> bool {- let tokens = segment.split_whitespace().peekable();- for token in tokens {- let token = token.trim_matches(|ch| matches!(ch, '(' | ')' | '<' | '>'));- if token.is_empty() {- continue;- }- if token.contains('=') && !token.starts_with('-') {- continue;- }- if matches!(token, "sudo" | "command" | "time" | "env") {- continue;- }- return is_python_executable_token(token);- }- false-}--fn is_python_executable_token(token: &str) -> bool {- let executable = token.rsplit('/').next().unwrap_or(token);- matches!(- executable,- "python"- | "python3"- | "py"- | "pip"- | "pip3"- | "python.exe"- | "python3.exe"- | "pip.exe"- | "pip3.exe"- ) || versioned_executable(executable, "python3.")- || versioned_executable(executable, "pip3.")-}--fn versioned_executable(executable: &str, prefix: &str) -> bool {- executable- .strip_prefix(prefix)- .is_some_and(|suffix| !suffix.is_empty() && suffix.chars().all(|c| c.is_ascii_digit()))}#[cfg(test)]diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests.rsindex ef4b9583c0..a77e83592b 100644--- a/crates/openhuman-core/src/tools/impl/system/shell_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests.rs@@ -1,7 +1,6 @@use super::super::shell_platform::{PYTHON_UTF8_DEFAULTS, SAFE_ENV_VARS};use super::*;use crate::agent::host_runtime::{NativeRuntime, RuntimeAdapter};-use crate::config::test_env::EnvVarGuard;use crate::security::{AutonomyLevel, CommandClass, SecurityPolicy};fn test_security(autonomy: AutonomyLevel) -> Arc<SecurityPolicy> {diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rsindex e52242571c..bf03be45b3 100644--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_runtime_and_sandbox_tests.rs@@ -1,225 +1,5 @@use super::*;-#[test]-fn shell_detects_python_runtime_commands() {- for command in [- "python3 -m pyfiglet hello",- "python -m pip install pyfiglet",- "pip install pyfiglet",- "pip3.13 show pyfiglet",- "/opt/openhuman/python/bin/python3 script.py",- "echo hi && python3 -V",- ] {- assert!(- shell_command_needs_python_runtime(command),- "expected python runtime detection for {command}"- );- }-- for command in [- "echo python3",- "ls",- "cat ./pipelines.txt",- "node script.js",- ] {- assert!(- !shell_command_needs_python_runtime(command),- "did not expect python runtime detection for {command}"- );- }-}--#[test]-fn shell_runtime_path_prepends_managed_dirs_before_host_path() {- let python = std::path::Path::new("/opt/openhuman/python/bin");- let node = std::path::Path::new("/opt/openhuman/node/bin");- let joined = prepend_path_dirs([python, node], "/usr/local/bin:/usr/bin");- let sep = if cfg!(windows) { ";" } else { ":" };- assert_eq!(- joined,- format!(- "{}{}{}{}{}",- python.display(),- sep,- node.display(),- sep,- "/usr/local/bin:/usr/bin"- )- );-}--/// Empirical answer to "does `shell` resolve/install managed Node on its-/// own?" — NO. The shell path consults the managed Node bootstrap only via-/// `try_cached()`, which never calls `resolve()` and therefore never-/// downloads/installs anything. So without a prior `node_exec` / `npm_exec`-/// (the tools that DO call `resolve()` and share this bootstrap instance),-/// `runtime_path_for_command` injects nothing for a node command. On a host-/// with no Node in the login PATH, the command then fails — the managed-/// runtime is never reached on the shell path. (Python, by contrast, IS-/// self-resolved in `runtime_path_for_command` — see the python branch.)-#[tokio::test]-async fn shell_does_not_resolve_or_install_node_on_its_own() {- let node = Arc::new(NodeBootstrap::new(Arc::new(- crate::config::Config::default(),- )));- let tool = ShellTool::with_language_bootstraps(- test_security(AutonomyLevel::Full),- test_runtime(),- test_audit(),- Some(node),- None,- );-- // Unprimed (no prior node_exec/npm_exec resolve): shell injects NO- // managed node bin onto PATH — it does not auto-resolve or install.- let injected = tool.runtime_path_for_command("node --version").await;- assert!(- injected.is_none(),- "shell injected a managed node bin without any prior node_exec/npm_exec \- resolve — it must not auto-resolve/install on the shell path: {injected:?}"- );-}--/// A Python runtime that cannot be resolved must not fail the command: the-/// shell keeps the inherited `PATH`, so the host's own `python3` (a task-/// repo's interpreter with its dependencies) still runs it. It used to answer-/// every `python …` command with `Failed to resolve command runtime` once the-/// runtime module had faulted.-#[tokio::test]-async fn shell_keeps_inherited_path_when_python_runtime_is_unavailable() {- let mut config = crate::config::Config::default();- config.runtime_python.enabled = false;- let python = Arc::new(PythonBootstrap::new(Arc::new(config)));- assert!(- python.resolve().await.is_err(),- "a disabled python runtime must fail to resolve for this test to mean anything"- );- let tool = ShellTool::with_language_bootstraps(- test_security(AutonomyLevel::Full),- test_runtime(),- test_audit(),- None,- Some(python),- );- assert_eq!(tool.runtime_path_for_command("python3 -V").await, None);-- let result = tool- .execute(json!({"command": "python3 -c 'print(1)' || echo no-host-python"}))- .await- .unwrap();- let output = result.output();- assert!(- !output.contains("Failed to resolve command runtime")- && (output.contains('1') || output.contains("no-host-python")),- "the command must run on the inherited PATH: {output}"- );-}--#[test]-fn shell_runtime_failure_logging_accepts_enabled_and_disabled_runtime_states() {- log_python_runtime_unavailable(true, &anyhow::anyhow!("test resolution failure"));- log_python_runtime_unavailable(false, &anyhow::anyhow!("test disabled runtime"));-}--#[cfg(unix)]-#[derive(Default)]-struct TrackingNativeRuntime {- native: NativeRuntime,- builds: std::sync::atomic::AtomicUsize,-}--#[cfg(unix)]-impl RuntimeAdapter for TrackingNativeRuntime {- fn name(&self) -> &str {- self.native.name()- }- fn has_shell_access(&self) -> bool {- self.native.has_shell_access()- }- fn has_filesystem_access(&self) -> bool {- self.native.has_filesystem_access()- }- fn storage_path(&self) -> std::path::PathBuf {- self.native.storage_path()- }- fn supports_long_running(&self) -> bool {- self.native.supports_long_running()- }- fn build_shell_command(- &self,- command: &str,- workspace: &std::path::Path,- ) -> anyhow::Result<tokio::process::Command> {- self.builds- .fetch_add(1, std::sync::atomic::Ordering::SeqCst);- self.native.build_shell_command(command, workspace)- }-}--#[cfg(unix)]-fn shell_with_cached_python_using(- runtime: Arc<dyn RuntimeAdapter>,-) -> (ShellTool, tempfile::TempDir) {- use crate::runtime::python::{PythonSource, ResolvedPython};- use std::os::unix::fs::PermissionsExt;-- let bin_dir = tempfile::Builder::new()- .prefix("managed-python's $(false) ")- .tempdir()- .unwrap();- let python_bin = bin_dir.path().join("python3");- std::fs::write(&python_bin, "#!/bin/sh\necho managed-python-path\n").unwrap();- std::fs::set_permissions(&python_bin, std::fs::Permissions::from_mode(0o755)).unwrap();-- let mut config = crate::config::Config::default();- config.runtime_python.enabled = true;- let python = Arc::new(PythonBootstrap::new(Arc::new(config)));- python.cache_for_test(ResolvedPython {- bin_dir: bin_dir.path().to_path_buf(),- python_bin,- version: "test".into(),- source: PythonSource::Managed,- });- (- ShellTool::with_language_bootstraps(- test_security(AutonomyLevel::Full),- runtime,- test_audit(),- None,- Some(python),- ),- bin_dir,- )-}--#[cfg(unix)]-#[tokio::test]-async fn shell_uses_cached_python_path_in_native_mode() {- use crate::agent::harness::definition::SandboxMode;- use crate::agent::harness::with_current_sandbox_mode;-- let _env = EnvVarGuard::locked_set_async(crate::sandbox::ops::SANDBOX_OFF_ENV, "off").await;- let runtime = Arc::new(TrackingNativeRuntime::default());- let (tool, _bin_dir) = shell_with_cached_python_using(runtime.clone());- let result = with_current_sandbox_mode(SandboxMode::None, async {- tool.execute(json!({"command": "python3 -c 'print(1)'"}))- .await- .unwrap()- })- .await;- assert!(- !result.is_error,- "managed Python command failed: {}",- result.output()- );- assert!(result.output().contains("managed-python-path"));- assert_eq!(- runtime.builds.load(std::sync::atomic::Ordering::SeqCst),- 1,- "native execution must use the instrumented runtime adapter"- );-}-#[tokio::test]async fn shell_blocks_rate_limited() {let security = Arc::new(SecurityPolicy {@@ -235,116 +15,31 @@ async fn shell_blocks_rate_limited() {assert!(result.output().contains("Rate limit"));}-#[cfg(not(windows))]#[tokio::test]-async fn shell_sandboxed_mode_routes_through_sandbox_backend() {- use crate::agent::harness::definition::SandboxMode;- use crate::agent::harness::with_current_sandbox_mode;-- let _env = EnvVarGuard::locked_set_async(crate::sandbox::ops::SANDBOX_OFF_ENV, "on").await;- let runtime = Arc::new(TrackingNativeRuntime::default());- let (tool, _bin_dir) = shell_with_cached_python_using(runtime.clone());- let result = with_current_sandbox_mode(SandboxMode::Sandboxed, async {- tool.execute(json!({"command": "python3 -c 'print(1)'"}))- .await- .unwrap()- })- .await;- assert!(- !result.is_error,- "sandboxed managed Python command should succeed: {}",- result.output()- );- assert!(- result.output().contains("managed-python-path"),- "expected managed Python PATH in result, got: {:?}",- result.output()- );- assert_eq!(- runtime.builds.load(std::sync::atomic::Ordering::SeqCst),- 0,- "sandboxed execution must bypass the tool's native runtime adapter"- );-}--/// Shell-family callers must use the shared routing decision, which covers-/// both an agent's sandbox mode and an explicit operator backend. The test-/// above executes a command and proves it bypasses the native runtime adapter;-/// this guard covers Node/npm call sites without downloading their runtimes.-#[test]-fn shell_family_tools_route_to_sandbox_when_sandboxed_mode_active() {- const SHELL_SRC: &str = include_str!("shell.rs");- const NODE_EXEC_SRC: &str = include_str!("node_exec.rs");- const NPM_EXEC_SRC: &str = include_str!("npm_exec.rs");-- for (name, src) in [- ("shell.rs", SHELL_SRC),- ("node_exec.rs", NODE_EXEC_SRC),- ("npm_exec.rs", NPM_EXEC_SRC),+async fn shell_uses_host_node_and_python_from_path() {+ for (binary, command, expected) in [+ ("node", "node -e 'console.log(1)'", "1"),+ ("python3", "python3 -c 'print(1)'", "1"),] {- assert!(- src.contains("command_requires_sandbox().await"),- "{name} must use the shared command sandbox routing policy, including agent mode and operator backend"+ if std::process::Command::new(binary)+ .arg("--version")+ .output()+ .is_err()+ {+ continue;+ }++ let tool = ShellTool::new(+ test_security(AutonomyLevel::Full),+ test_runtime(),+ test_audit(),);- // Use the call-site pattern `.run_sandboxed(` so the assertion- // doesn't trivially pass on the helper definition itself- // (`fn run_sandboxed(...)`). If `execute()` / `run_with_security()`- // stop delegating, this fires even though the helper still exists.+ let result = tool.execute(json!({"command": command})).await.unwrap();+ assert!(!result.is_error, "{binary} failed: {}", result.output());assert!(- src.contains(".run_sandboxed("),- "{name} must delegate to a `run_sandboxed` helper when the sandbox mode is \- active (see #3235). Whitespace before `.run_sandboxed` is tolerated; the \- helper call must appear in the source — *not* just the helper definition."+ result.output().contains(expected),+ "{binary}: {}",+ result.output());}}--#[test]-fn managed_path_restoration_preserves_cmd_syntax_and_unmanaged_commands() {- use crate::agent::platform_shell::ShellFlavor;- let windows_command = "echo %USERPROFILE%";- assert_eq!(- command_with_runtime_path(windows_command, Some("C:\\managed\\bin"), ShellFlavor::Cmd),- windows_command- );- let unmanaged_command = "echo \"$PATH\"";- assert_eq!(- command_with_runtime_path(unmanaged_command, None, ShellFlavor::Posix),- unmanaged_command- );-}--#[cfg(unix)]-#[tokio::test]-async fn managed_python_path_keeps_the_turn_path_without_daemon_inheritance() {- use crate::runtime::python::{PythonSource, ResolvedPython};- use crate::tools::timeout::CommandEnvironment;- let python = Arc::new(PythonBootstrap::new(Arc::new(- crate::config::Config::default(),- )));- python.cache_for_test(ResolvedPython {- bin_dir: PathBuf::from("/managed/python/bin"),- python_bin: PathBuf::from("/managed/python/bin/python3"),- version: "3.12.4".into(),- source: PythonSource::Managed,- });- let tool = ShellTool::with_language_bootstraps(- test_security(AutonomyLevel::Full),- test_runtime(),- test_audit(),- None,- Some(python),- );- let environment = CommandEnvironment::new([("PATH".into(), "/turn/bin".into())]);- let path = environment- .scope(tool.runtime_path_for_command("python3 -V"))- .await- .unwrap();- assert_eq!(path, "/managed/python/bin:/turn/bin");- let empty = CommandEnvironment::new(Vec::<(String, String)>::new());- let path = empty- .scope(tool.runtime_path_for_command("python3 -V"))- .await- .unwrap();- assert_eq!(path, "/managed/python/bin");-}diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rsindex cbbbbae6b5..e13879b523 100644--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_schema_and_env_tests.rs@@ -190,310 +190,6 @@ async fn shell_pwd_returns_action_dir_not_workspace_dir() {);}-/// Source-level regression guard for #3238.-///-/// Locks in the contract that the three shell-family acting tools-/// (`shell`, `node_exec`, `npm_exec`) resolve their CWD against-/// `security.action_dir`, never `security.workspace_dir`. The-/// behavioural assertion above covers `shell`; this guard catches-/// regressions in `node_exec` / `npm_exec` without requiring a real-/// Node.js install in CI (their `execute()` path runs-/// `NodeBootstrap::resolve()` first, which is brittle to mock).-///-/// If a future refactor accidentally switches any of these tools-/// back to `workspace_dir`, this assertion fires at compile-time-/// string-match level.-#[test]-fn shell_family_tools_route_cwd_through_action_dir() {- const SHELL_SRC: &str = include_str!("shell.rs");- const NODE_EXEC_SRC: &str = include_str!("node_exec.rs");- const NPM_EXEC_SRC: &str = include_str!("npm_exec.rs");-- // Compose forbidden patterns at runtime so this test's own source- // doesn't trigger the contains() check on itself.- let bad_field = format!("self.security.{}_dir", "workspace");- let bad_call_1 = format!("build_shell_command(&command, &{bad_field})");- let bad_call_2 = format!("build_shell_command(command, &{bad_field})");-- for (name, src) in [- ("shell.rs", SHELL_SRC),- ("node_exec.rs", NODE_EXEC_SRC),- ("npm_exec.rs", NPM_EXEC_SRC),- ] {- // The tool CWD must resolve against `action_dir`, sourced from the- // tool's own `self.security`. Two accepted spellings:- // * direct: `self.security.action_dir` (shell.rs / node_exec.rs)- // * workspace-context-aware: `security_for_tool_context(&self.security, …)`- // → `resolve_cwd(&path_policy.action_dir, …)` (npm_exec.rs, #4249)- // Both keep CWD rooted at `action_dir` and tied to `self.security`;- // neither may reach for `workspace_dir`.- let direct = src.contains("self.security.action_dir");- let context_aware = src.contains("security_for_tool_context(&self.security")- && src.contains("path_policy.action_dir");- assert!(- direct || context_aware,- "{name} must route tool CWD through `action_dir` sourced from \- `self.security` (see #3074, #3238, #4249)"- );- assert!(- !src.contains(&bad_call_1) && !src.contains(&bad_call_2),- "{name} must not pass `workspace_dir` to `build_shell_command` — \- acting tools spawn into `action_dir`. See #3074, #3238."- );- }-}--/// Parity guard for the worktree-isolation action-dir override (#3376,-/// #4249 08.5). A worktree-isolated worker's shell command MUST spawn inside-/// the isolated worktree, sourced from the carried `WorkspaceDescriptor`, not-/// the shared `security.action_dir`. This encodes the exact behaviour the-/// deleted `worktree_context.rs` task-local used to provide.-#[cfg(not(windows))]-#[tokio::test]-async fn shell_uses_workspace_descriptor_root_as_cwd() {- let action_tmp = tempfile::tempdir().expect("create action tempdir");- let worktree_tmp = tempfile::tempdir().expect("create worktree tempdir");- let security = Arc::new(SecurityPolicy {- autonomy: AutonomyLevel::Full,- workspace_dir: std::env::temp_dir(),- action_dir: action_tmp.path().to_path_buf(),- ..SecurityPolicy::default()- });- let tool = ShellTool::new(security.clone(), test_runtime(), test_audit());-- // WITH a descriptor → pwd reports the worktree root, never action_dir.- let ctx = tool_context_with_workspace(worktree_tmp.path());- let result = tool- .execute_with_context(- json!({"command": "pwd"}),- tinytools::ToolCallOptions {- prefer_markdown: false,- },- Some(&ctx),- )- .await- .expect("pwd executes");- assert!(!result.is_error, "{}", result.output());- let reported = std::path::PathBuf::from(result.output().trim());- let reported = reported.canonicalize().unwrap_or(reported);- let expected_wt = worktree_tmp- .path()- .canonicalize()- .unwrap_or_else(|_| worktree_tmp.path().to_path_buf());- let action_canon = action_tmp- .path()- .canonicalize()- .unwrap_or_else(|_| action_tmp.path().to_path_buf());- assert_eq!(- reported, expected_wt,- "shell with a WorkspaceDescriptor must spawn in the worktree root"- );- assert_ne!(- reported, action_canon,- "shell must NOT fall back to security.action_dir when a descriptor is present"- );-- // WITHOUT a descriptor → pwd reports action_dir (non-isolated parity).- let result = tool- .execute(json!({"command": "pwd"}))- .await- .expect("pwd executes");- assert!(!result.is_error, "{}", result.output());- let reported = std::path::PathBuf::from(result.output().trim());- let reported = reported.canonicalize().unwrap_or(reported);- assert_eq!(- reported, action_canon,- "shell with no descriptor must fall back to security.action_dir"- );-}--#[tokio::test]-async fn shell_readonly_allows_reads_blocks_writes() {- let security = test_security(AutonomyLevel::ReadOnly);- // Read commands are permitted in read-only mode…- assert_eq!(- security.gate_decision(security.classify_command("ls")),- GateDecision::Allow- );- // …but a write command is blocked before execution.- let tool = ShellTool::new(security, test_runtime(), test_audit());- let blocked = tool- .execute(json!({"command": "touch ro_test_file"}))- .await- .unwrap();- assert!(blocked.is_error);- assert!(blocked.output().contains("read-only"));-}--#[tokio::test]-async fn shell_missing_command_param() {- let tool = ShellTool::new(- test_security(AutonomyLevel::Supervised),- test_runtime(),- test_audit(),- );- let result = tool.execute(json!({})).await;- assert!(result.is_err());- assert!(result.unwrap_err().to_string().contains("command"));-}--#[tokio::test]-async fn shell_wrong_type_param() {- let tool = ShellTool::new(- test_security(AutonomyLevel::Supervised),- test_runtime(),- test_audit(),- );- let result = tool.execute(json!({"command": 123})).await;- assert!(result.is_err());-}--#[tokio::test]-async fn shell_captures_exit_code() {- let tool = ShellTool::new(- test_security(AutonomyLevel::Supervised),- test_runtime(),- test_audit(),- );- let result = tool- .execute(json!({"command": "ls /nonexistent_dir_xyz"}))- .await- .unwrap();- assert!(result.is_error);-}--/// Regression for the code_executor no-progress loop (#4095): a FAILED-/// command must surface its exit code AND both streams — never drop stdout-/// when stderr is present — so the agent can read *why* it failed instead of-/// re-running it blindly.-#[cfg(not(windows))]-#[tokio::test]-async fn shell_failure_surfaces_exit_code_and_both_streams() {- let tool = ShellTool::new(- test_security(AutonomyLevel::Full),- test_runtime(),- test_audit(),- );- let result = tool- .execute(json!({- "command": "echo stdout-marker; echo stderr-marker 1>&2; exit 7"- }))- .await- .unwrap();- assert!(result.is_error, "non-zero exit must be an error result");- let out = result.output();- assert!(out.contains("exit code 7"), "exit code not surfaced: {out}");- assert!(- out.contains("stdout-marker"),- "stdout dropped on failure: {out}"- );- assert!(- out.contains("stderr-marker"),- "stderr dropped on failure: {out}"- );-}--/// A missing executable exits 127; the surfaced result must carry the code-/// and the actionable "command not found / missing dependency" hint so the-/// agent recognises the dependency wall and adapts instead of looping.-#[cfg(not(windows))]-#[tokio::test]-async fn shell_missing_command_surfaces_127_with_dependency_hint() {- let tool = ShellTool::new(- test_security(AutonomyLevel::Full),- test_runtime(),- test_audit(),- );- let result = tool- .execute(json!({"command": "this_binary_does_not_exist_xyz --version"}))- .await- .unwrap();- assert!(result.is_error);- let out = result.output().to_lowercase();- assert!(out.contains("127"), "exit code 127 not surfaced: {out}");- assert!(- out.contains("command not found"),- "missing-dependency hint absent: {out}"- );-}--#[cfg(not(windows))]-#[tokio::test(flavor = "current_thread")]-async fn shell_does_not_leak_api_key() {- let _g1 = EnvVarGuard::locked_set_async("API_KEY", "sk-test-secret-12345").await;-- let tool = ShellTool::new(test_security_with_env_cmd(), test_runtime(), test_audit());- let result = tool- .execute(json!({"command": "echo $API_KEY"}))- .await- .unwrap();- assert!(!result.is_error, "{}", result.output());- assert!(- !result.output().contains("sk-test-secret-12345"),- "API_KEY leaked to shell command output"- );-}--#[cfg(not(windows))]-#[tokio::test]-async fn shell_preserves_path_and_home() {- let tool = ShellTool::new(test_security_with_env_cmd(), test_runtime(), test_audit());-- let result = tool- .execute(json!({"command": "echo $HOME"}))- .await- .unwrap();- assert!(!result.is_error, "{}", result.output());- assert!(- !result.output().trim().is_empty(),- "HOME should be available in shell"- );-- let result = tool- .execute(json!({"command": "echo $PATH"}))- .await- .unwrap();- assert!(!result.is_error, "{}", result.output());- assert!(- !result.output().trim().is_empty(),- "PATH should be available in shell"- );-}--#[tokio::test]-async fn shell_writes_are_gated_in_supervised_run_in_full() {- // A write command routes through the approval gate in ask-before-edit- // (no self-asserted `approved` flag any more)…- let supervised = test_security(AutonomyLevel::Supervised);- let tool = ShellTool::new(supervised.clone(), test_runtime(), test_audit());- assert_eq!(supervised.classify_command("touch f"), CommandClass::Write);- assert!(tool.external_effect_with_args(&json!({"command": "touch f"})));-- // …and runs without prompting in Full.- let full = test_security(AutonomyLevel::Full);- let full_tool = ShellTool::new(full, test_runtime(), test_audit());- assert!(!full_tool.external_effect_with_args(&json!({"command": "touch f"})));-}--#[tokio::test]-async fn shell_llm_category_escalates_but_never_lowers() {- // In Full a Write runs silently…- let full = test_security(AutonomyLevel::Full);- let tool = ShellTool::new(full, test_runtime(), test_audit());- assert!(!tool.external_effect_with_args(&json!({"command": "touch f"})));- // …but a self-declared `destructive` escalates it to a prompt.- assert!(- tool.external_effect_with_args(&json!({"command": "touch f", "category": "destructive"}))- );- // The hint can never LOWER: declaring a destructive command "read"- // still prompts (in any acting tier).- let supervised = test_security(AutonomyLevel::Supervised);- let stool = ShellTool::new(supervised, test_runtime(), test_audit());- assert!(stool.external_effect_with_args(&json!({"command": "sudo reboot", "category": "read"})));-}--// ── §5.2 Shell timeout enforcement tests ─────────────────-#[test]fn shell_is_unbounded_by_default() {let tool = ShellTool::new(diff --git a/crates/openhuman-core/src/tools/mod.rs b/crates/openhuman-core/src/tools/mod.rsindex cd172bdb73..fd93e11c75 100644--- a/crates/openhuman-core/src/tools/mod.rs+++ b/crates/openhuman-core/src/tools/mod.rs@@ -1,5 +1,7 @@pub mod agent_policy;pub mod host_extensions;+pub(crate) mod native_ops;+mod native_ops_types;pub mod ops;pub mod orchestrator_tools;pub mod registry;diff --git a/crates/openhuman-core/src/runtime/node/ops.rs b/crates/openhuman-core/src/tools/native_ops.rssimilarity index 82%rename from crates/openhuman-core/src/runtime/node/ops.rsrename to crates/openhuman-core/src/tools/native_ops.rsindex bf13fcac46..ce31c59216 100644--- a/crates/openhuman-core/src/runtime/node/ops.rs+++ b/crates/openhuman-core/src/tools/native_ops.rs@@ -5,9 +5,9 @@ use crate::agent::host_runtime::{NativeRuntime, RuntimeAdapter};use crate::config::Config;use crate::core::bus::BUS;use crate::core::events::DomainEvent;-use crate::runtime::node::types::{ExecuteToolOutcome, RuntimeToolSummary};use crate::security::{CommandClass, SecurityPolicy};use crate::tools;+use crate::tools::native_ops_types::{ExecuteToolOutcome, RuntimeToolSummary};use tinytools::{PermissionLevel, Tool, ToolCallOptions, ToolScope};use tracing::{debug, trace};@@ -79,7 +79,7 @@ fn command_class_for_tool(pub fn build_runtime_tools(config: &Config) -> Result<Vec<Box<dyn Tool>>, String> {debug!(workspace = %config.workspace_dir.display(),- "[runtime_node::ops] build_runtime_tools: start"+ "[native_ops] build_runtime_tools: start");let security = Arc::new(SecurityPolicy::from_config(&config.autonomy,@@ -93,7 +93,7 @@ pub fn build_runtime_tools(config: &Config) -> Result<Vec<Box<dyn Tool>>, String).map_err(|e| e.to_string())?;let runtime: Arc<dyn RuntimeAdapter> = Arc::new(NativeRuntime::new());- trace!("[runtime_node::ops] build_runtime_tools: tools::ops::all_tools_with_runtime");+ trace!("[native_ops] build_runtime_tools: tools::ops::all_tools_with_runtime");let built = tools::ops::all_tools_with_runtime(Arc::new(config.clone()),&security,@@ -108,22 +108,19 @@ pub fn build_runtime_tools(config: &Config) -> Result<Vec<Box<dyn Tool>>, String);debug!(tool_count = built.len(),- "[runtime_node::ops] build_runtime_tools: done"+ "[native_ops] build_runtime_tools: done");Ok(built)}pub fn list_tools(config: &Config) -> Result<Vec<RuntimeToolSummary>, String> {- debug!("[runtime_node::ops] list_tools: start");+ debug!("[native_ops] list_tools: start");let mut summaries: Vec<RuntimeToolSummary> = build_runtime_tools(config)?.into_iter().map(|tool| summarize_tool(tool.as_ref())).collect();summaries.sort_by(|a, b| a.name.cmp(&b.name));- debug!(- count = summaries.len(),- "[runtime_node::ops] list_tools: done"- );+ debug!(count = summaries.len(), "[native_ops] list_tools: done");Ok(summaries)}@@ -132,7 +129,7 @@ pub fn classify_tool_call(tool_name: &str,args: &serde_json::Value,) -> Result<CommandClass, String> {- debug!(tool_name, "[runtime_node::ops] classify_tool_call: start");+ debug!(tool_name, "[native_ops] classify_tool_call: start");let security =SecurityPolicy::from_config(&config.autonomy, &config.workspace_dir, &config.action_dir);let tools = build_runtime_tools(config)?;@@ -140,10 +137,7 @@ pub fn classify_tool_call(.into_iter().find(|tool| tool.name() == tool_name).ok_or_else(|| {- debug!(- tool_name,- "[runtime_node::ops] classify_tool_call: tool not found"- );+ debug!(tool_name, "[native_ops] classify_tool_call: tool not found");format!("unknown tool `{tool_name}`")})?;let class = command_class_for_tool(&security, tool.as_ref(), args);@@ -152,7 +146,7 @@ pub fn classify_tool_call(?class,permission = %tool.permission_level_with_args(args),external_effect = tool.external_effect_with_args(args),- "[runtime_node::ops] classify_tool_call: done"+ "[native_ops] classify_tool_call: done");Ok(class)}@@ -165,29 +159,26 @@ pub async fn execute_tool() -> Result<ExecuteToolOutcome, String> {debug!(tool_name,- prefer_markdown, "[runtime_node::ops] execute_tool: start"+ prefer_markdown, "[native_ops] execute_tool: start");let tools = build_runtime_tools(config)?;trace!(tool_count = tools.len(),tool_name,- "[runtime_node::ops] execute_tool: runtime tools built"+ "[native_ops] execute_tool: runtime tools built");let tool = tools.into_iter().find(|tool| tool.name() == tool_name).ok_or_else(|| {- debug!(- tool_name,- "[runtime_node::ops] execute_tool: tool not found"- );+ debug!(tool_name, "[native_ops] execute_tool: tool not found");format!("unknown tool `{tool_name}`")})?;let started = Instant::now();debug!(tool_name,- "[runtime_node::ops] execute_tool: publish ToolExecutionStarted"+ "[native_ops] execute_tool: publish ToolExecutionStarted");BUS.publish(DomainEvent::ToolExecutionStarted {tool_name: tool_name.to_string(),@@ -196,7 +187,7 @@ pub async fn execute_tool(trace!(tool_name,- "[runtime_node::ops] execute_tool: dispatch execute_with_options"+ "[native_ops] execute_tool: dispatch execute_with_options");let execution = tool.execute_with_options(args, ToolCallOptions { prefer_markdown })@@ -205,7 +196,7 @@ pub async fn execute_tool(debug!(tool_name,error = %error,- "[runtime_node::ops] execute_tool: tool execution failed"+ "[native_ops] execute_tool: tool execution failed");format!("tool `{tool_name}` failed: {error:#}")});@@ -217,7 +208,7 @@ pub async fn execute_tool(.unwrap_or(false);debug!(tool_name,- success, elapsed_ms, "[runtime_node::ops] execute_tool: publish ToolExecutionCompleted"+ success, elapsed_ms, "[native_ops] execute_tool: publish ToolExecutionCompleted");BUS.publish(DomainEvent::ToolExecutionCompleted {tool_name: tool_name.to_string(),@@ -231,7 +222,7 @@ pub async fn execute_tool(tool_name,success = !result.is_error,elapsed_ms,- "[runtime_node::ops] execute_tool: returning outcome"+ "[native_ops] execute_tool: returning outcome");Ok(ExecuteToolOutcome {tool_name: tool_name.to_string(),diff --git a/crates/openhuman-core/src/runtime/node/types.rs b/crates/openhuman-core/src/tools/native_ops_types.rssimilarity index 100%rename from crates/openhuman-core/src/runtime/node/types.rsrename to crates/openhuman-core/src/tools/native_ops_types.rsdiff --git a/crates/openhuman-core/src/tools/ops.rs b/crates/openhuman-core/src/tools/ops.rsindex f4a6151ef0..4bdae5a4a9 100644--- a/crates/openhuman-core/src/tools/ops.rs+++ b/crates/openhuman-core/src/tools/ops.rs@@ -2,15 +2,11 @@ use super::*;use crate::agent::host_runtime::{NativeRuntime, RuntimeAdapter};use crate::config::{Config, DelegateAgentConfig};-use crate::runtime::javascript::NodeBootstrap;-use crate::runtime::python::PythonBootstrap;use crate::security::{AuditLogger, SecurityPolicy};use std::collections::HashMap;use std::sync::Arc;use tinyagents_harness::tools::{self as harness_tools, CurrentTimeTool, ResolveTimeTool};use tinytools::Tool;-#[cfg(test)]-use tinytools::ToolResult;use tinytools_std::detect_tools::DetectToolsTool;use tinytools_std::filesystem::{ApplyPatchTool, CsvExportTool, EditFileTool, FileReadTool, FileWriteTool, GitOperationsTool,@@ -83,57 +79,10 @@ pub fn all_tools_with_runtime(root_config: &crate::config::Config,approval_workspace_root: Option<&std::path::Path>,) -> Vec<Box<dyn Tool>> {- // One shared snapshot of this session's configuration for both language- // clients. They each hand it to the `tinyruntime` module on every call —- // the module holds no configuration of its own — so the two must not be- // able to disagree about which version this session asked for. The- // registry is assembled under `config`, so the bootstraps share that same- // Arc rather than a separately-cloned `root_config` — one configuration- // snapshot for everything this session builds.- let shared_config = Arc::clone(&config);-- // Build a session-scoped managed Node.js bootstrap once, so ShellTool,- // NodeExecTool, and NpmExecTool all share the same memoised resolution- // state. Disabled when `node.enabled = false` — in that case shell skips- // PATH injection and node/npm tools are not registered.- // `runtime-node` off => never construct a bootstrap: the stub resolves to- // nothing anyway, and this keeps the shell's PATH-injection branch dead- // rather than a silent per-invocation no-op.- let node_bootstrap: Option<Arc<NodeBootstrap>> = if cfg!(feature = "runtime-node")- && root_config.node.enabled- {- tracing::debug!(- version = %root_config.node.version,- prefer_system = root_config.node.prefer_system,- "[tools::ops] node runtime enabled — constructing shared NodeBootstrap"- );- Some(Arc::new(NodeBootstrap::new(Arc::clone(&shared_config))))- } else {- tracing::debug!(- "[tools::ops] node runtime disabled — shell PATH injection + node_exec/npm_exec suppressed"- );- None- };- let python_bootstrap: Option<Arc<PythonBootstrap>> = if root_config.runtime_python.enabled {- tracing::debug!(- minimum_version = %root_config.runtime_python.minimum_version,- prefer_system = root_config.runtime_python.prefer_system,- "[tools::ops] python runtime enabled — constructing shared PythonBootstrap"- );- Some(Arc::new(PythonBootstrap::new(Arc::clone(&shared_config))))- } else {- tracing::debug!(- "[tools::ops] python runtime disabled — shell python/pip PATH injection suppressed"- );- None- };-- let shell: Box<dyn Tool> = Box::new(ShellTool::with_language_bootstraps(+ let shell: Box<dyn Tool> = Box::new(ShellTool::new(security.clone(),Arc::clone(&runtime),Arc::clone(&audit),- node_bootstrap.as_ref().map(Arc::clone),- python_bootstrap.as_ref().map(Arc::clone),));let file_write: Box<dyn Tool> = match approval_workspace_root {@@ -573,10 +522,8 @@ pub fn all_tools_with_runtime(// `juice_find` / `juice_extract` / `juice_summarize`: only while a handle can name them.tools.extend(crate::inference::tokenjuice::repl_tools_for(root_config));- // Presentation generation (#2778). Native-Rust engine (ppt-rs- // backed) as of the #2780-follow-up rust-engine refactor — no- // managed Python venv, no first-call install latency. Always- // registered.+ // Presentation generation (#2778), backed by the native Rust engine.+ // Always registered.#[cfg(feature = "documents")]tools.push(Box::new(PresentationTool::for_config(root_config,@@ -786,40 +733,6 @@ pub fn all_tools_with_runtime(// when the user is not signed in, so they register unconditionally.tools.extend(crate::web3::all_web3_agent_tools());- // Managed Node.js exec tools — gated on `root_config.node.enabled`.- // Both share the same `NodeBootstrap` as ShellTool so the download +- // extract + install pipeline runs at most once per session.- #[cfg(feature = "runtime-node")]- if let Some(bootstrap) = node_bootstrap.as_ref() {- tools.push(Box::new(NodeExecTool::new(- security.clone(),- Arc::clone(&runtime),- Arc::clone(bootstrap),- root_config.runtime_pool.clone(),- root_config.workspace_dir.clone(),- )));- tools.push(Box::new(NpmExecTool::new(- security.clone(),- Arc::clone(&runtime),- Arc::clone(bootstrap),- )));- tracing::debug!("[tools::ops] registered node_exec + npm_exec");- }-- // Managed Python exec tool — gated on `root_config.runtime_python.enabled`.- // Shares the same `PythonBootstrap` as ShellTool. Inline code routes through- // the shared runtime pool (#5106) when enabled.- if let Some(bootstrap) = python_bootstrap.as_ref() {- tools.push(Box::new(PythonExecTool::new(- security.clone(),- Arc::clone(&runtime),- Arc::clone(bootstrap),- root_config.runtime_pool.clone(),- root_config.workspace_dir.clone(),- )));- tracing::debug!("[tools::ops] registered python_exec");- }-// Image metadata is always available for user-provided images.tools.push(Box::new(ImageInfoTool::new(security.clone())));diff --git a/crates/openhuman-core/src/tools/ops_tests.rs b/crates/openhuman-core/src/tools/ops_tests.rsindex 75a4e9acb9..570f22a356 100644--- a/crates/openhuman-core/src/tools/ops_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests.rs@@ -3,7 +3,10 @@ use crate::config::{BrowserConfig, Config};use crate::security::credentials::{AuthService, APP_SESSION_PROVIDER, DEFAULT_AUTH_PROFILE_NAME};use crate::security::AuditLogger;use crate::skills::types::ToolContent;+use crate::tools::ops::{all_tools, tool_group};+use std::collections::HashMap;use tempfile::TempDir;+use tinytools::ToolResult;#[path = "../integrations/test_support.rs"]mod integration_test_support;@@ -32,7 +35,7 @@ fn assert_contains_all(names: &[String], expected: &[&str]) {fn only_json_content(result: &ToolResult) -> &serde_json::Value {match result.content.as_slice() {- [ToolContent::Json { data }] => data,+ [ToolContent::Json { data }] => &data,other => panic!("expected a single JSON content block, got {other:?}"),}}@@ -317,7 +320,6 @@ const REPRESENTATIVE: &[(&str, crate::core::all::DomainGroup)] = {("cron_add", G::Automation),("composio_execute", G::Integrations),("dashboard_model_health", G::Desktop),- ("node_exec", G::Runtimes),("juice_retrieve", G::Inference),("shell", G::Platform),]diff --git a/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs b/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rsindex 87b355e911..0d99caa436 100644--- a/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_capability_gating_tests.rs@@ -333,21 +333,3 @@ async fn full_domain_set_keeps_platform_tools() {assert!(names.iter().any(|n| n == name), "missing `{name}`");}}--/// `node_exec` / `npm_exec` are absent when the managed Node runtime is-/// compiled out — absent, not present-and-erroring, so the model is never shown-/// a tool it cannot use.-#[test]-#[cfg(not(feature = "runtime-node"))]-fn default_tools_omits_node_tools_when_runtime_node_off() {- let tmp = TempDir::new().unwrap();- let cfg = integration_test_config(&tmp, "http://127.0.0.1:1");- let tools = integration_tools_for_config(&tmp, &cfg);- let names = tool_names(&tools);- for absent in ["node_exec", "npm_exec"] {- assert!(- !names.iter().any(|n| n == absent),- "`{absent}` must not be registered with runtime-node compiled out"- );- }-}diff --git a/crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rs b/crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rsindex f839f61bea..5223d6b6a6 100644--- a/crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_catalog_fixture_tests.rs@@ -38,7 +38,6 @@ fn full_product_features_enabled() -> bool {("http-server", cfg!(feature = "http-server")),("scheduler-gate", cfg!(feature = "scheduler-gate")),("file-logging", cfg!(feature = "file-logging")),- ("runtime-node", cfg!(feature = "runtime-node")),("hosting", cfg!(feature = "hosting")),("tinymemes", cfg!(feature = "tinymemes")),("storage-sqlite", cfg!(feature = "storage-sqlite")),diff --git a/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rsindex f17eb6b4c5..7da1eabee6 100644--- a/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_default_registry_tests.rs@@ -425,7 +425,7 @@ fn all_tools_default_registry_contains_expected_baseline_surface() {);let names = tool_names(&tools);- let mut expected = vec![+ let expected = vec!["shell","file_read","file_write",@@ -466,11 +466,6 @@ fn all_tools_default_registry_contains_expected_baseline_surface() {"gitbooks_get_page","image_info",];- // Managed Node tools exist only when the runtime is compiled in — same- // shape as the `channels` conditional just below.- if cfg!(feature = "runtime-node") {- expected.extend(&["node_exec", "npm_exec"]);- }assert_contains_all(&names, &expected);}#[test]diff --git a/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rsindex 4d1959fac4..a37c6ab8bf 100644--- a/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_domain_family_tests.rs@@ -1,4 +1,5 @@use super::*;+use crate::tools::{filter_tools_by_user_preference, http_request_tool, BrowserOpenTool};use tinytools_std::filesystem::{ApplyPatchTool, CsvExportTool};#[tokio::test]diff --git a/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs b/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rsindex e5e6d0c229..5a1ca62d1a 100644--- a/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs+++ b/crates/openhuman-core/src/tools/ops_tests_execution_and_serde_tests.rs@@ -1,4 +1,6 @@use super::*;+use crate::config::DelegateAgentConfig;+use crate::tools::ops::default_tools;#[test]fn all_tools_includes_browser_when_enabled() {@@ -125,100 +127,6 @@ fn all_tools_excludes_delegate_when_no_agents() {assert!(!names.contains(&"delegate"));}-#[test]-#[cfg(feature = "runtime-node")]-fn all_tools_registers_node_exec_when_node_enabled() {- // Default NodeConfig has `enabled = true`, so both `node_exec` and- // `npm_exec` must appear in the registry. Regression guard for the- // skills integration — if this fires, managed-node skills silently- // lose both tools.- let tmp = TempDir::new().unwrap();- let security = Arc::new(SecurityPolicy::default());-- let browser = BrowserConfig::default();- let http = crate::config::HttpRequestConfig::default();- let cfg = test_config(&tmp);-- let tools = all_tools(- Arc::new(Config::default()),- &security,- AuditLogger::disabled(),- &browser,- &http,- tmp.path(),- &HashMap::new(),- &cfg,- );- let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();- assert!(- names.contains(&"node_exec"),- "node_exec must be registered when node.enabled=true; got: {names:?}"- );- assert!(- names.contains(&"npm_exec"),- "npm_exec must be registered when node.enabled=true; got: {names:?}"- );-}--#[test]-fn all_tools_registers_python_exec_when_python_enabled() {- // Default RuntimePythonConfig has `enabled = true`, so `python_exec` must- // appear in the registry (routes inline code through the runtime pool, #5106).- let tmp = TempDir::new().unwrap();- let security = Arc::new(SecurityPolicy::default());-- let browser = BrowserConfig::default();- let http = crate::config::HttpRequestConfig::default();- let cfg = test_config(&tmp);-- let tools = all_tools(- Arc::new(Config::default()),- &security,- AuditLogger::disabled(),- &browser,- &http,- tmp.path(),- &HashMap::new(),- &cfg,- );- let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();- assert!(- names.contains(&"python_exec"),- "python_exec must be registered when runtime_python.enabled=true; got: {names:?}"- );-}--#[test]-fn all_tools_excludes_node_exec_when_node_disabled() {- let tmp = TempDir::new().unwrap();- let security = Arc::new(SecurityPolicy::default());-- let browser = BrowserConfig::default();- let http = crate::config::HttpRequestConfig::default();- let mut cfg = test_config(&tmp);- cfg.node.enabled = false;-- let tools = all_tools(- Arc::new(Config::default()),- &security,- AuditLogger::disabled(),- &browser,- &http,- tmp.path(),- &HashMap::new(),- &cfg,- );- let names: Vec<&str> = tools.iter().map(|t| t.name()).collect();- assert!(- !names.contains(&"node_exec"),- "node_exec must NOT be registered when node.enabled=false; got: {names:?}"- );- assert!(- !names.contains(&"npm_exec"),- "npm_exec must NOT be registered when node.enabled=false; got: {names:?}"- );-}-#[test]fn all_tools_registers_integration_families_when_enabled_and_signed_in() {let tmp = TempDir::new().unwrap();diff --git a/crates/openhuman-core/src/tools/ops_tool_groups.rs b/crates/openhuman-core/src/tools/ops_tool_groups.rsindex 1cb97379a7..c4ad79f952 100644--- a/crates/openhuman-core/src/tools/ops_tool_groups.rs+++ b/crates/openhuman-core/src/tools/ops_tool_groups.rs@@ -215,11 +215,6 @@ pub(crate) fn tool_group(name: &str) -> crate::core::all::DomainGroup {if name.starts_with("dashboard_") || name.starts_with("desktop_") {return DomainGroup::Desktop;}- // Runtimes: the managed Node/Python execution tools. These live under- // `tools/impl/system/` rather than `runtime/`, so they are matched by name.- if name == "node_exec" || name == "npm_exec" || name == "python_exec" {- return DomainGroup::Runtimes;- }// Inference: the CCR retrieval surface. Matched against the crate's own// constant list rather than a name prefix — the live tool is// `juice_retrieve`, and `tokenjuice_retrieve` / `retrieve_tool_output`diff --git a/crates/openhuman-core/src/tools/timeout/README.md b/crates/openhuman-core/src/tools/timeout/README.mdindex 2b7ed5035f..96907f17ba 100644--- a/crates/openhuman-core/src/tools/timeout/README.md+++ b/crates/openhuman-core/src/tools/timeout/README.md@@ -32,14 +32,14 @@ Highest precedence first:- `env_override_active() -> bool`: true when `OPENHUMAN_TOOL_TIMEOUT_SECS` is set to a valid override, so UI changes are ignored. Surfaced to the settings panel.- `tool_execution_timeout_secs() -> u64`: effective timeout in seconds, read fresh each call.- `install_harness_tool_timeouts(harness)`: installs the shared settings on a TinyAgents `AgentHarness` (`with_tool_timeout_settings`). The harness enforces `ToolTimeout` policies only when settings are installed; the turn harness (`agent/tinyagents/harness_assembly.rs`) and the live voice harness call this. Tools that wait on a human inside `execute` carry their own budgets (`composio_connect`: park bound + 60s; `browser`: 12 min).-- `explicit_call_timeout_secs(requested: Option<u64>, cap: u64) -> Option<u64>`: resolves an explicit per-call timeout for an otherwise-unbounded scripting tool. `None` or `Some(0)` means `None` (run unbounded); any positive value clamps to `MIN_TIMEOUT_SECS..=cap`. Callers pass their own ceiling (`MAX_TIMEOUT_SECS` for `shell`, `1800` for `node_exec`/`npm_exec`/`python_exec`).+- `explicit_call_timeout_secs(requested: Option<u64>, cap: u64) -> Option<u64>`: resolves an explicit per-call timeout for an otherwise-unbounded scripting tool. `None` or `Some(0)` means `None` (run unbounded); any positive value clamps to `MIN_TIMEOUT_SECS..=cap`. Callers pass their own ceiling (`MAX_TIMEOUT_SECS` for `shell`, the shell limit for shell).- `explicit_call_timeout_duration(requested: Option<u64>, cap: u64) -> Option<Duration>`: same as a `Duration`, `None` for unbounded.- `resolve_tool_deadline(policy: tinytools::ToolTimeout) -> (Option<Duration>, u64)`: resolves a tool's `ToolTimeout` policy (`Inherit`, `Millis(req)`, or `Unbounded`) into the `(deadline, timeout_secs)` pair the agent tool-execution loop enforces, padding an explicit millisecond request with `TOOL_TIMEOUT_GRACE_SECS` before the hard deadline fires.- Constants: `DEFAULT_TIMEOUT_SECS = 120`, `MIN_TIMEOUT_SECS = 1`, `MAX_TIMEOUT_SECS = 3600`, `SANDBOX_UNBOUNDED_CAP_SECS = 86_400`, `ENV_VAR = "OPENHUMAN_TOOL_TIMEOUT_SECS"`.## Scripting tools run unbounded (issue #4023)-The global timeout governs non-scripting tools only, since a hung network or MCP call must stay bounded. The scripting tools (`shell`, `node_exec`, `npm_exec`, `python_exec`) instead run with no default deadline: a build, solver, or test run legitimately takes minutes and must not be hard-killed. They expose a per-call `timeout_secs` argument and resolve it through `explicit_call_timeout_secs`/`explicit_call_timeout_duration`: `None` runs unbounded, a positive value clamps to the tool's own ceiling. Sandbox backends, which require a finite deadline even when the caller asked for none, substitute `SANDBOX_UNBOUNDED_CAP_SECS` (24h) for the unbounded case.+The global timeout governs non-scripting tools only, since a hung network or MCP call must stay bounded. The scripting tools (`shell`) instead run with no default deadline: a build, solver, or test run legitimately takes minutes and must not be hard-killed. They expose a per-call `timeout_secs` argument and resolve it through `explicit_call_timeout_secs`/`explicit_call_timeout_duration`: `None` runs unbounded, a positive value clamps to the tool's own ceiling. Sandbox backends, which require a finite deadline even when the caller asked for none, substitute `SANDBOX_UNBOUNDED_CAP_SECS` (24h) for the unbounded case.## Configuration@@ -53,7 +53,7 @@ The global timeout governs non-scripting tools only, since a hung network or MCP## Used by- `crates/openhuman-core/src/agent/tinyagents/tools.rs`: OpenHuman tools execute through `execute_with_options`, which applies each tool's `Tool::timeout_policy`.-- `crates/openhuman-core/src/tools/impl/system/{shell,node_exec,npm_exec,python_exec}.rs`: scripting tools, unbounded by default, explicit `timeout_secs` via `explicit_call_timeout_*`.+- `crates/openhuman-core/src/tools/impl/system/shell.rs`: the shell tool, unbounded by default, with explicit `timeout_secs` via `explicit_call_timeout_*`.- `crates/openhuman-core/src/agent/tools/delegate.rs`: bounds the delegated provider chat call with `tool_execution_timeout_secs`.- `crates/openhuman-core/src/config/ops/agent.rs`: `apply_agent_settings` calls `set_tool_timeout_secs` after persisting; `get_agent_settings` reports `effective_timeout_secs`/`env_override`.- `crates/openhuman-core/src/core/runtime/subscribers.rs`: `register_domain_subscribers` seeds the runtime value from config on the always-on core boot path, so channel-less or web-chat-only cores get the configured timeout too (#5027).diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rsindex c689a71972..fe7dd7f898 100644--- a/crates/openhuman-core/src/tools/timeout/mod.rs+++ b/crates/openhuman-core/src/tools/timeout/mod.rs@@ -80,7 +80,7 @@ fn settings() -> &'static ToolTimeoutSettings {/// reach already-assembled harnesses on their next tool call.////// Long-running tools opt out through their own policy rather than here:-/// scripting tools (`shell`, `node_exec`, …) are `Unbounded` unless the call+/// the scripting tool (`shell`) are `Unbounded` unless the call/// passes `timeout_secs`, media generation carries its own budget, and/// `composio_connect` / `browser` size theirs to the approval park they wait/// on inside `execute`.@@ -178,7 +178,7 @@ pub fn tool_execution_timeout_secs() -> u64 {}/// Resolve an **explicit** per-call timeout request for a tool that is-/// otherwise unbounded (the scripting tools: `shell`, `node_exec`, `npm_exec`).+/// otherwise unbounded (the scripting tool: `shell`).////// Unlike most tools — which inherit the global config-driven timeout so a hung/// network/MCP call can't wedge a session — scripting tools run with **no**diff --git a/crates/openhuman-core/src/tools/toolpacks/guides/coding.md b/crates/openhuman-core/src/tools/toolpacks/guides/coding.mdindex c72cfc7b1f..e0732dd24a 100644--- a/crates/openhuman-core/src/tools/toolpacks/guides/coding.md+++ b/crates/openhuman-core/src/tools/toolpacks/guides/coding.md@@ -2,7 +2,7 @@ Repository and code work, end to end, in the action sandbox (`action_dir`). Clon1. **Locate.** `grep` / `glob` / `list` for symbols, error strings or files, then `file_read` the top hits. Use `lsp` for definitions and references when it is enabled. Two rounds of searching, then start editing.2. **Edit.** `edit` for a small exact replacement, `apply_patch` for multi-hunk changes, `file_write` only to create a new file. Never rewrite an existing file through a shell heredoc.-3. **Run.** `shell` for builds and focused tests; `node_exec` / `npm_exec` / `python_exec` run scripts on OpenHuman's managed runtimes rather than whatever is on PATH. `curl` is for a raw HTTP call when `web_fetch` is not enough. Only stdout/stderr come back: a script that prints nothing returned nothing, not success. If you create a virtualenv, use its own `pip`/`python`.+3. **Run.** Use `shell` for builds, focused tests, and scripts. Node.js and Python commands use the host's `node` and `python3` on `PATH`. `curl` is for a raw HTTP call when `web_fetch` is not enough. Only stdout/stderr come back: a script that prints nothing returned nothing, not success. If you create a virtualenv, use its own `pip`/`python`.4. **Verify.** `run_tests` and `run_linter` in the working tree; fix what fails before reporting.5. **Review before you finish.** `read_diff`, then check it in this order: security (injection, secrets, unsafe input) → correctness (edge cases, off-by-one, error paths, races) → tests cover the new paths → style matches the surrounding code. Name file and line for each problem.6. **Git.** `git_operations` (or `shell` with `git`) for status, diff, branch, commit and push in the working tree. GitHub *state* (issues, PRs, reviews, checks, comments) goes through the connected GitHub integration: `tool_search` for the action. Never shell `gh`.diff --git a/crates/openhuman-core/src/tools/toolpacks/registry.rs b/crates/openhuman-core/src/tools/toolpacks/registry.rsindex bfbb99dab7..779df93343 100644--- a/crates/openhuman-core/src/tools/toolpacks/registry.rs+++ b/crates/openhuman-core/src/tools/toolpacks/registry.rs@@ -311,9 +311,6 @@ pub const PACKS: &[ToolPack] = &["list","git_operations","edit",- "node_exec",- "npm_exec",- "python_exec","curl","read_diff","run_linter",diff --git a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rsindex 8104edf56a..2bfd8ab35a 100644--- a/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs+++ b/crates/openhuman-core/src/tools/toolpacks/toolpacks_tests.rs@@ -389,9 +389,6 @@ fn every_pack_declares_the_tools_it_is_named_for() {"list","git_operations","edit",- "node_exec",- "npm_exec",- "python_exec","curl","read_diff","run_linter",diff --git a/crates/openhuman-embed/Cargo.toml b/crates/openhuman-embed/Cargo.tomlindex 1107364ba6..31615af910 100644--- a/crates/openhuman-embed/Cargo.toml+++ b/crates/openhuman-embed/Cargo.toml@@ -25,7 +25,6 @@ web3 = ["openhuman-core/web3"]storage-sqlite = ["openhuman-core/storage-sqlite"]storage-mongodb = ["openhuman-core/storage-mongodb"]storage-file = ["openhuman-core/storage-file"]-runtime-node = ["openhuman-core/runtime-node"]media = ["openhuman-core/media"]flows = ["openhuman-core/flows"]skills = ["openhuman-core/skills"]diff --git a/crates/openhuman-embed/examples/linux_fleet.rs b/crates/openhuman-embed/examples/linux_fleet.rsindex 469259f649..19b218b246 100644--- a/crates/openhuman-embed/examples/linux_fleet.rs+++ b/crates/openhuman-embed/examples/linux_fleet.rs@@ -59,7 +59,6 @@ async fn measure(count: usize) -> anyhow::Result<()> {.mount(&mock).await;let mut config = openhuman_embed::RuntimeConfig::default();config.local_ai.runtime_enabled = false;- config.runtime_python.enabled = false;config.memory.conversations.enabled = false;config.agent.session_dual_write = false;config.agent.session_shadow_reads = false;diff --git a/crates/openhuman-embed/examples/support/mod.rs b/crates/openhuman-embed/examples/support/mod.rsindex ac8c39d19e..cbcf31da33 100644--- a/crates/openhuman-embed/examples/support/mod.rs+++ b/crates/openhuman-embed/examples/support/mod.rs@@ -43,7 +43,6 @@ pub fn chat_completion(content: &str) -> serde_json::Value {pub fn offline_config() -> Config {let mut config = Config::default();config.local_ai.runtime_enabled = false;- config.runtime_python.enabled = false;// Conversation memory ingest is intentionally fire-and-forget. It can// still be buffering after a turn returns, which is useful in the product// but unrelated to these tests' contracts and would race the finaldiff --git a/crates/openhuman-embed/tests/common/mod.rs b/crates/openhuman-embed/tests/common/mod.rsindex 22d75e8fc0..a5c1b2a6a0 100644--- a/crates/openhuman-embed/tests/common/mod.rs+++ b/crates/openhuman-embed/tests/common/mod.rs@@ -43,7 +43,6 @@ pub fn chat_completion(content: &str) -> serde_json::Value {pub fn offline_config() -> Config {let mut config = Config::default();config.local_ai.runtime_enabled = false;- config.runtime_python.enabled = false;// Conversation memory ingest is intentionally fire-and-forget. It can// still be buffering after a turn returns, which is useful in the product// but unrelated to these tests' contracts and would race the finaldiff --git a/crates/openhuman-rpc/Cargo.toml b/crates/openhuman-rpc/Cargo.tomlindex c96550044f..22b9ff8fa1 100644--- a/crates/openhuman-rpc/Cargo.toml+++ b/crates/openhuman-rpc/Cargo.toml@@ -59,7 +59,6 @@ web3 = ["openhuman-tinyhumans/web3"]storage-sqlite = ["openhuman-tinyhumans/storage-sqlite"]storage-mongodb = ["openhuman-tinyhumans/storage-mongodb"]storage-file = ["openhuman-tinyhumans/storage-file"]-runtime-node = ["openhuman-tinyhumans/runtime-node"]media = ["openhuman-tinyhumans/media"]flows = ["openhuman-tinyhumans/flows"]skills = ["openhuman-tinyhumans/skills"]diff --git a/crates/openhuman-tinyhumans/Cargo.toml b/crates/openhuman-tinyhumans/Cargo.tomlindex bf2334c372..21a2893c8e 100644--- a/crates/openhuman-tinyhumans/Cargo.toml+++ b/crates/openhuman-tinyhumans/Cargo.toml@@ -31,7 +31,6 @@ web3 = ["openhuman-embed/web3"]storage-sqlite = ["openhuman-embed/storage-sqlite"]storage-mongodb = ["openhuman-embed/storage-mongodb"]storage-file = ["openhuman-embed/storage-file"]-runtime-node = ["openhuman-embed/runtime-node"]media = ["openhuman-embed/media"]flows = ["openhuman-embed/flows"]skills = ["openhuman-embed/skills"]diff --git a/crates/openhuman-tui/Cargo.toml b/crates/openhuman-tui/Cargo.tomlindex 0f2f9e8152..3ca3711064 100644--- a/crates/openhuman-tui/Cargo.toml+++ b/crates/openhuman-tui/Cargo.toml@@ -42,7 +42,6 @@ web3 = ["openhuman-rpc/web3"]storage-sqlite = ["openhuman-rpc/storage-sqlite"]storage-mongodb = ["openhuman-rpc/storage-mongodb"]storage-file = ["openhuman-rpc/storage-file"]-runtime-node = ["openhuman-rpc/runtime-node"]media = ["openhuman-rpc/media"]flows = ["openhuman-rpc/flows"]skills = ["openhuman-rpc/skills"]diff --git a/docs/gitbooks/en/developing/embed/capability-matrix.md b/docs/gitbooks/en/developing/embed/capability-matrix.mdindex c621982188..07dc4c0fdf 100644--- a/docs/gitbooks/en/developing/embed/capability-matrix.md+++ b/docs/gitbooks/en/developing/embed/capability-matrix.md@@ -20,7 +20,6 @@ This matrix comes from the default-feature compiled capability-report example. R| `media` | Yes || `modules` | Yes || `rss-bench` | No |-| `runtime-node` | No || `scheduler-gate` | Yes || `skills` | Yes || `storage-file` | No |diff --git a/gitbooks/developing/architecture.md b/gitbooks/developing/architecture.mdindex b5c3c8cc9a..022072fdaf 100644--- a/gitbooks/developing/architecture.md+++ b/gitbooks/developing/architecture.md@@ -9,7 +9,7 @@ icon: code-branchOpenHuman is a personal AI assistant built on Rust. It has a persistent memory, stored in CortexDB (hosted by TinyHumans or your own), and an agent harness that can act across your connected services.-OpenHuman is a Rust core that runs agent turns, keeps a pluggable memory engine, and runs tools against memory, channels, integrations and (for users who opt in) a wallet. A single React and Rust (Tauri) codebase wraps it. The stack also includes a managed Node.js runtime for tool-capable skills, persistent Rust-native WebSocket infrastructure to the backend, a native Rust tool-dispatch path, and a Model Context Protocol (MCP) server for external clients.+OpenHuman is a Rust core that runs agent turns, keeps a pluggable memory engine, and runs tools against memory, channels, integrations and (for users who opt in) a wallet. A single React and Rust (Tauri) codebase wraps it. Node.js and Python commands use the host toolchain on `PATH`. The stack also includes persistent Rust-native WebSocket infrastructure to the backend, a native Rust tool-dispatch path, and a Model Context Protocol (MCP) server for external clients.OpenHuman ships for desktop only: Windows, macOS and Linux. Web is not a supported target. Android and iOS exist as experimental clients with their own build and publish workflows (`android-compile.yml`, `ios-appstore.yml`). They are not part of the shipped desktop host and are not product-ready.@@ -28,10 +28,10 @@ OpenHuman ships for desktop only: Windows, macOS and Linux. Web is not a support| `crates/openhuman-cli/` | The `openhuman-core` binary (`openhuman_rpc::host::cli`), the ops bins, and every root `tests/*.rs` / `examples/*.rs` target (which reach the core through dev-dependencies). The benchmark bins live in [openhuman-benchmarks](https://github.com/tinyhumansai/openhuman-benchmarks). || `crates/openhuman-tui/` | Standalone ratatui terminal frontend. Boots the core in-process via `openhuman_rpc::host::tui` (every domain, no background services), no HTTP. || `Cargo.toml` (root) | Virtual workspace for `openhuman-core`, `openhuman-embed`, `openhuman-rpc`, `openhuman-tinyhumans`, `openhuman-cli`, and `openhuman-tui` (`cargo build -p openhuman-cli --bin openhuman-core` builds the standalone CLI/server); `vendor/`, `worktrees/`, `crates/openhuman-app`, `app/src-tauri-mobile`, and `packages/tauri-plugin-ptt` are excluded. Holds the `[patch]` tables for vendored crates. There is no sidecar: the desktop bundle links the core in-process. |-| `crates/openhuman-core/src/skills/` | Skill metadata and run orchestration (`ops_create`, `ops_discover`, `ops_install`, `ops_parse`, `catalog/`, `registry`, `runtime/`, `schemas/`, `types`, `bundled/`, `webhooks/`). Skills contribute metadata and tool descriptors that are injected into agent prompts. Tool execution flows through native Rust handlers and Node-backed helpers via `runtime::node` (Cargo feature `runtime-node`). |+| `crates/openhuman-core/src/skills/` | Skill metadata and run orchestration (`ops_create`, `ops_discover`, `ops_install`, `ops_parse`, `catalog/`, `registry`, `runtime/`, `schemas/`, `types`, `bundled/`, `webhooks/`). Skills contribute metadata and tool descriptors that are injected into agent prompts. Tool execution flows through native Rust handlers and the shell tool for host commands such as Node.js and Python. || `gitbooks/` | This book (public product and contributor documentation). || `docs/` | Internal maintainer documentation (test-coverage matrix, release smoke checklist, library benchmarking notes). |-| `vendor/` | Recursive git submodules for the `tiny*` crate family (`tinyagents`, `tinyflows`, `tinychannels`, `tinyjuice`, `tinymemory`, `tinymcp`, `tinybus`, `tinybox`, `tinycomputer`, `tinyruntime`, `tinydocs`, `tinysearch`, `tinyskills`, `tinyvoice`, `tinywallet`, `tinyhosts`, `tinyconnectors`, `tinyhumans-sdk`). |+| `vendor/` | Recursive git submodules for the `tiny*` crate family (`tinyagents`, `tinyflows`, `tinychannels`, `tinyjuice`, `tinymemory`, `tinymcp`, `tinybus`, `tinybox`, `tinycomputer`, `tinydocs`, `tinysearch`, `tinyskills`, `tinyvoice`, `tinywallet`, `tinyhosts`, `tinyconnectors`, `tinyhumans-sdk`). |The desktop app's webview loads the UI from `app/`. RPC, agents and skills run in the `openhuman_core` core, hosted in-process as a tokio task by the Tauri shell (`crates/openhuman-app/src/core_process.rs`, `openhuman_rpc::host::desktop`) and reachable over loopback HTTP. The renderer's `coreRpcClient` `fetch()`es `http://127.0.0.1:<port>/rpc` directly. The `relay_http_rpc` Tauri command (backed by `openhuman_rpc::post_json_rpc`) is only the fallback for non-loopback plain-`http://` runtimes that the webview would block as mixed content. The standalone `openhuman-core serve` binary is the CLI/debug path.@@ -135,7 +135,7 @@ Tauri v2 compiles the Rust core into native binaries per platform, embedding theThe frontend talks to the Rust core in two ways. Tauri IPC carries shell commands (windows, hotkeys, and the `relay_http_rpc` HTTP relay used only for non-loopback plain-`http://` runtimes). HTTP JSON-RPC over loopback carries business logic and tools. The core also serves a Socket.IO bridge for live events such as chat streaming and notifications.-The core owns the outbound persistent connection to the TinyHumans backend, the memory engine binding (memory items are stored in CortexDB, not on the device) and tool execution. Agent turns run through the `tinyagents` harness. Tools dispatch as native Rust handlers, plus Node-backed helpers via `runtime::node`, gated by the `security/` sandbox policy. Skills do not execute in-process. The `crates/openhuman-core/src/skills/` domain contributes metadata and tool descriptors that get injected into agent prompts. External MCP clients (Claude Desktop, Cursor, Zed) reach the same tool surface over a separate stdio MCP server. See [MCP server](mcp-server.md).+The core owns the outbound persistent connection to the TinyHumans backend, the memory engine binding (memory items are stored in CortexDB, not on the device) and tool execution. Agent turns run through the `tinyagents` harness. Tools dispatch through native Rust handlers and the shell tool, which runs host commands such as Node.js and Python under the `security/` sandbox policy. Skills do not execute in-process. The `crates/openhuman-core/src/skills/` domain contributes metadata and tool descriptors that get injected into agent prompts. External MCP clients (Claude Desktop, Cursor, Zed) reach the same tool surface over a separate stdio MCP server. See [MCP server](mcp-server.md).---@@ -146,7 +146,7 @@ OpenHuman uses Tauri and Rust instead of Electron for performance and security.| Metric | OpenHuman (Tauri + Rust) | Typical Electron App || ------------------------- | -------------------------------------------------------------------------- | ---------------------------------------- || Binary size | Feature-dependent (native Wry webview; no bundled Chromium) | ~150 MB+ |-| Memory per tool execution | Native Rust (no per-tool VM); shared managed Node runtime for helper calls | ~150 MB+ (Chromium renderer per process) |+| Memory per tool execution | Native Rust (no per-tool VM); host Node.js and Python are available through shell | ~150 MB+ (Chromium renderer per process) || Cold startup | Sub-500ms | 2-5 seconds || Garbage collection pauses | None (Rust ownership model) | V8 GC pauses || Memory safety | Compile-time guaranteed | Runtime exceptions |@@ -208,7 +208,7 @@ Skill discovery uses `SKILL.md` plus optional bundled resources:| `allowed-tools` | Tool allowlist guidance || bundled resources | scripts, references, assets |-Script-backed skills run through shared runtime domains rather than embedded VMs. `runtime::node` (Cargo feature `runtime-node`) resolves a compatible system `node` or installs a managed distribution (SHA-256-verified) into the OpenHuman cache, and `runtime::python` does the same for Python. Execution is gated by the `security/` sandbox policy like any other tool.+Script-backed skills run through the shell tool and use the host `node` and `python3` executables on `PATH`. Execution is gated by the `security/` sandbox policy like any other tool.Recurring work belongs to the `cron` domain (with `scheduler_gate`), not to skills. There is no per-skill cron handler.@@ -218,7 +218,7 @@ Recurring work belongs to the `cron` domain (with `scheduler_gate`), not to skilOpenHuman implements the Model Context Protocol on both sides of the connection. As a client, the core browses Smithery and the official MCP registry, connects servers a user declares in `mcp.json`, and surfaces their tools to agents through the same tool registry native tools use; see [MCP registry](architecture/mcp-registry.md). As a server, `openhuman-core mcp` exposes OpenHuman's own tools over stdio or HTTP so external MCP hosts such as Claude Desktop, Cursor, and Zed can call them; see [MCP server](mcp-server.md).-Every remote tool definition, whether coming in through a connected server or served out to a host, passes a prompt-injection scan before it reaches a model. Tool execution itself runs through the same Tool Registry as native tools: native Rust handlers or Node helpers via `runtime::node`, gated by `SecurityPolicy` and the active sandbox backend.+Every remote tool definition, whether coming in through a connected server or served out to a host, passes a prompt-injection scan before it reaches a model. Tool execution itself runs through the same Tool Registry as native tools: native Rust handlers or shell commands using the host toolchain, gated by `SecurityPolicy` and the active sandbox backend.## Memory@@ -276,7 +276,7 @@ Model decides to call a tool (e.g., send a Telegram message)Tool Registry routes to the registered handler|v-Handler executes: native Rust, or a Node helper via `runtime::node`+Handler executes: native Rust, or a shell command using the host toolchain|vHandler runs through `SecurityPolicy` and the active sandbox backenddiff --git a/gitbooks/developing/architecture/agent-harness.md b/gitbooks/developing/architecture/agent-harness.mdindex e443da8ae1..97158935d1 100644--- a/gitbooks/developing/architecture/agent-harness.md+++ b/gitbooks/developing/architecture/agent-harness.md@@ -369,9 +369,9 @@ Before a fresh tool result enters history (and ahead of the byte-budget backstop- Search → relevance-ranked top-K matches per file with a `+N more` tally.- Diff → keep changed hunks, collapse unchanged context, summarise lockfile hunks.- HTML → strip markup to readable text.-- Plain text → the opt-in Python/ML "Kompress" compressor (ModernBERT), or pass-through.+- Plain text → deterministic TextCrusher.-Every lossy compression offloads the original to the CCR (Compress-Cache-Retrieve) store behind a `⟦tj:<hash>⟧` marker, so compaction is effectively lossless: the agent calls `juice_retrieve` (token + optional byte/line range) to fetch the full original on demand. The same engine is exposed as a universal `compress_content(content, hint, opts)` for any large payload (file reads, web fetches), and as read-only `tokenjuice.*` debug RPCs. Compaction is on by default (`context.compaction_enabled`; `OPENHUMAN_COMPACTION=0` opts out). A large result is stored and replaced by a stats line, a 500-character head and a handle that the read-only `juice_find` / `juice_extract` / `juice_summarize` tools query (`tokenjuice.repl_handle_enabled`), so the LLM summary stage is skipped for results that get a handle. Configured via the `[tokenjuice]` block / `OPENHUMAN_TOKENJUICE_*` env. Agent definitions can override tool-result compression with `tokenjuice_compression = "auto" | "full" | "light" | "off"`; `auto` resolves coding-model agents (`[model] hint = "coding"`) to `light`, which disables CCR-backed lossy compression so coding agents keep raw build/test/diff/search text unless a reduction is truly lossless. Other agents default to `full`. The ML (Kompress) path runs as a `kompress` backend of the shared [`runtime_python_server`](https://github.com/tinyhumansai/openhuman/tree/main/crates/openhuman-core/src/runtime/python_server) (torch + ModernBERT pip-installed at runtime), gated by the `ml_compression_enabled` flag and degrading gracefully to a native compressor when the Python runtime is unavailable.+Every lossy compression offloads the original to the CCR (Compress-Cache-Retrieve) store behind a `⟦tj:<hash>⟧` marker, so compaction is effectively lossless: the agent calls `juice_retrieve` (token + optional byte/line range) to fetch the full original on demand. The same engine is exposed as a universal `compress_content(content, hint, opts)` for any large payload (file reads, web fetches), and as read-only `tokenjuice.*` debug RPCs. Compaction is on by default (`context.compaction_enabled`; `OPENHUMAN_COMPACTION=0` opts out). A large result is stored and replaced by a stats line, a 500-character head and a handle that the read-only `juice_find` / `juice_extract` / `juice_summarize` tools query (`tokenjuice.repl_handle_enabled`), so the LLM summary stage is skipped for results that get a handle. Configured via the `[tokenjuice]` block / `OPENHUMAN_TOKENJUICE_*` env. Agent definitions can override tool-result compression with `tokenjuice_compression = "auto" | "full" | "light" | "off"`; `auto` resolves coding-model agents (`[model] hint = "coding"`) to `light`, which disables CCR-backed lossy compression so coding agents keep raw build/test/diff/search text unless a reduction is truly lossless. Other agents default to `full`. Plain-text compression uses the deterministic TextCrusher.### Missing capabilitiesdiff --git a/gitbooks/developing/embed/capability-matrix.md b/gitbooks/developing/embed/capability-matrix.mdindex c621982188..07dc4c0fdf 100644--- a/gitbooks/developing/embed/capability-matrix.md+++ b/gitbooks/developing/embed/capability-matrix.md@@ -20,7 +20,6 @@ This matrix comes from the default-feature compiled capability-report example. R| `media` | Yes || `modules` | Yes || `rss-bench` | No |-| `runtime-node` | No || `scheduler-gate` | Yes || `skills` | Yes || `storage-file` | No |diff --git a/gitbooks/developing/hooks.md b/gitbooks/developing/hooks.mdindex 5442df6331..a4c5447701 100644--- a/gitbooks/developing/hooks.md+++ b/gitbooks/developing/hooks.md@@ -102,7 +102,7 @@ Every field is optional. Each event honors the subset it defines:| `preToolUse` | before any tool | `permission`, `updated_input`, `agent_message` || `postToolUse` | after a tool succeeded | `additional_context` || `postToolUseFailure` | after a tool failed | - |-| `beforeShellExecution` | before `shell` / `node_exec` / ... | `permission`, `agent_message` |+| `beforeShellExecution` | before `shell` | `permission`, `agent_message` || `afterShellExecution` | after one completed | - || `beforeReadFile` | before `file_read` / `read_diff` | `permission` || `afterFileEdit` | after `file_write` / `edit` / `apply_patch` | - |diff --git a/gitbooks/developing/loadable-modules.md b/gitbooks/developing/loadable-modules.mdindex 0bbe97332c..31b12a63c5 100644--- a/gitbooks/developing/loadable-modules.md+++ b/gitbooks/developing/loadable-modules.md@@ -23,7 +23,6 @@ The trade is explicit. A module shares the core's address space and crash domain| `tinywallet` | Key derivation and transaction signing || `tinyjuice` | Tool-output compression and recovery || `tinyvoice` | Audio framing, VAD, wake-word gating, hallucination detection |-| `tinyruntime` + `tinyruntime-nodejs` + `tinyruntime-python` | Runtime discovery and warm interpreter pools || `tinymcp` | The MCP client and registry || `tinyconnectors` | OAuth connector actions and triggers || `tinybox` | Sandbox capability discovery |diff --git a/gitbooks/developing/performance.md b/gitbooks/developing/performance.mdindex ec69bea4ae..8ec233b7ed 100644--- a/gitbooks/developing/performance.md+++ b/gitbooks/developing/performance.md@@ -64,7 +64,7 @@ Note that the smallest figure here, 15.2 MiB, is private memory in a slim runninCargo features (`media`, `skills`, `flows`, `mcp`, `channels`, `http-server`, `scheduler-gate`, `file-logging`, `modules` and more) decide what compiles in. Beyond that, several domains ship as loadable native `cdylib` modules that are not linked into the core binary at all.-The compiled registry pins fourteen records across twelve module names, because `tinyruntime` ships as a router plus two language providers. The modules are `tinycomputer`, `tinysearch`, `tinydocs`, `tinywallet`, `tinyjuice`, `tinyvoice`, `tinyruntime` (with its Node and Python providers), `tinymcp`, `tinyconnectors`, `tinybox`, `tinychannels` and `tinyhosts`. Each sits behind a small `*-bus` contract crate. A module loads into the same process and shares its privileges, so the admission checks (ABI, manifest, dependency, digest) matter more than for an ordinary dependency. See [Loadable modules](loadable-modules.md).+The compiled registry pins eleven module names: `tinycomputer`, `tinysearch`, `tinydocs`, `tinywallet`, `tinyjuice`, `tinyvoice`, `tinymcp`, `tinyconnectors`, `tinybox`, `tinychannels` and `tinyhosts`. Each sits behind a small `*-bus` contract crate. A module loads into the same process and shares its privileges, so the admission checks (ABI, manifest, dependency, digest) matter more than for an ordinary dependency. See [Loadable modules](loadable-modules.md).## The dependency-floor ratchetdiff --git a/gitbooks/developing/testing-strategy.md b/gitbooks/developing/testing-strategy.mdindex 11444341cf..42b82b9abf 100644--- a/gitbooks/developing/testing-strategy.md+++ b/gitbooks/developing/testing-strategy.md@@ -196,7 +196,7 @@ ls vendor/<module> | wc -l # 0 = empty, whatever status says`cargo test -p openhuman --lib` on default features builds a smaller product than CI does, and the difference changes test outcomes, not just which tests exist. A feature flag can gate a tool's registration. A test can compare a static allowlist with what it finds by inspecting the built binary. The flag then moves the result silently, and the failure names a product concept, such as "agents that carry tools but whose prompt names none of them", with no mention of a feature.-In one comparison, `openhuman --lib` failed 5 tests on default features and 3 under CI's set. The two that differed were profile artifacts: `every_prompt_names_at_least_one_tool_it_can_call` needs `runtime-node`, and `the_withheld_block_renders_for_a_renamed_session_with_a_filter` needs `documents`. Reproduce CI exactly before you assert anything:+In one comparison, `openhuman --lib` failed 5 tests on default features and 3 under CI's set. The two that differed were profile artifacts: `every_prompt_names_at_least_one_tool_it_can_call` depends on its default registry, and `the_withheld_block_renders_for_a_renamed_session_with_a_filter` needs `documents`. Reproduce CI exactly before you assert anything:```bashRUST_MIN_STACK=67108864 cargo test -p openhuman --lib \diff --git a/gitbooks/features/native-tools/coder.md b/gitbooks/features/native-tools/coder.mdindex 1de3519181..5cc62ebf09 100644--- a/gitbooks/features/native-tools/coder.md+++ b/gitbooks/features/native-tools/coder.md@@ -43,5 +43,5 @@ With the autonomy policy on, `workspace_only` confines the tools to the working## See also-- [System and utilities](system-and-utilities.md): `shell`, `node_exec`, `npm_exec` and `python_exec` for the rest of the dev loop.+- [System and utilities](system-and-utilities.md): `shell` for the rest of the dev loop, including Node.js, npm and Python commands available on the host's `PATH`.- [Agent coordination](agent-coordination.md): `todo` and `spawn_subagent` for larger refactors.diff --git a/gitbooks/features/native-tools/system-and-utilities.md b/gitbooks/features/native-tools/system-and-utilities.mdindex ee92304160..88d339c54d 100644--- a/gitbooks/features/native-tools/system-and-utilities.md+++ b/gitbooks/features/native-tools/system-and-utilities.md@@ -7,14 +7,13 @@ icon: gearThese are small tools the agent uses to finish a task.+Use the `shell` tool for Node.js, npm, and Python commands. OpenHuman uses the host's `node` and `python3` executables on `PATH`; install them with the platform package manager when needed.+## Tools in the family| Tool | What it does || --- | --- || `shell` | Run a shell command. Output is bounded and the exit code is captured. |-| `node_exec` | Run a Node.js snippet, useful for one-off scripting. |-| `npm_exec` | Run an `npm`, `pnpm` or `yarn` script. |-| `python_exec` | Run a Python 3 snippet or `.py` script. || `current_time` | Get the current time in any timezone, with formatting options. || `schedule` | Do something once at a given time. For recurring jobs see [Cron](cron.md). || `pushover` | Send a push notification to your devices. |diff --git a/gitbooks/features/token-compression.md b/gitbooks/features/token-compression.mdindex 699fa4e6ae..45c5ba1bb0 100644--- a/gitbooks/features/token-compression.md+++ b/gitbooks/features/token-compression.md@@ -45,7 +45,7 @@ raw tool result1. **Size gate.** If the router is off or the input is below `min_bytes_to_compress` (default 2048 bytes), it passes through untouched. Tiny outputs are not worth compressing.2. **Content detection** (`detect/kind.rs`). The result is classified into one of seven kinds. The order of precedence is an explicit hint, then a MIME or extension tag, then a per-tool prior (for example `grep` means Search, `git_operations` means Diff, `run_tests` means Log), then cheap structural heuristics (JSON, Diff, HTML, Search, Code, Log, PlainText). There is no regex on the hot path.-3. **Compressor selection.** Each kind goes to its own compressor, honoring per-kind toggles (`search_enabled`, `code_enabled`, `html_enabled`, `ml_compression_enabled`).+3. **Compressor selection.** Each kind goes to its own compressor, honoring per-kind toggles (`search_enabled`, `code_enabled`, `html_enabled`).4. **Compression.** The compressor runs. If it declines or its output is no smaller than the input, TokenJuice falls back to the generic compressor or passes the original through. It never makes things bigger.5. **CCR offload.** When a compression is lossy and the original is large enough (`ccr_min_tokens`, default about 500 tokens), the full original goes into the Compress-Cache-Retrieve (CCR) store, so nothing is lost for good.6. **Recovery marker.** A footer with the marker `⟦tj:<hash>⟧` is appended. It tells the agent the view is partial and how to fetch the rest.@@ -63,7 +63,7 @@ Each content kind has a purpose-built compressor (`vendor/tinyjuice/src/compress| Search | Search | Groups grep and ripgrep `path:line:body` hits by file, ranks by query-term density, keeps the top matches per file and tallies `[+N more]`. || Diff | Diff | Keeps changed lines and hunk headers and collapses long unchanged runs to an anchor. Lockfile hunks shrink to a one-line `+A/-B` summary. || Html | HTML | Strips markup to readable text with sensible block-boundary newlines and entity decoding (allocation-light, no DOM). |-| MlText | PlainText | Opt-in ML salience compression (see below). |+| TextCrusher | PlainText | Deterministic salience compression that preserves sentence and paragraph boundaries. || Generic | fallback | Head and tail summary for command output that no specific rule matched. It declines on structured results so they are preserved. |Multi-byte text (CJK, emoji, combining marks) is handled grapheme by grapheme and never split mid-character.@@ -89,15 +89,6 @@ Answers are size-capped, and an unknown or evicted handle is an error. `juice_reTo turn off the whole feature, set `context.compaction_enabled = false` or `OPENHUMAN_COMPACTION=0`. To keep compaction but go back to one-blob compression and `juice_retrieve`, set `tokenjuice.repl_handle_enabled = false` (`OPENHUMAN_TOKENJUICE_REPL_HANDLE_ENABLED=0`). Set `tokenjuice.repl_save_enabled = true` to also write each stored original to `<workspace>/.tokenjuice/repl/<handle>.txt` (mode 0600) so an agent can script over it. That puts raw tool output on disk, and nothing prunes it.-## ML compression (opt-in)--Besides the deterministic compressors, TokenJuice can route plain text through a ModernBERT token-salience model that scores and drops low-information spans. TinyJuice exposes the optional ML slot, and OpenHuman connects it to Kompress in `crates/openhuman-core/src/inference/tokenjuice/ml/`.--- Off by default. Enable it with `ml_compression_enabled = true` in `[tokenjuice]`.-- It runs locally, as the `kompress` backend of the long-running Python host process OpenHuman keeps warm for Python-backed models (`crates/openhuman-core/src/runtime/python_server/`), reached over a private stdio protocol. No data leaves your machine.-- Tunable keys: `ml_model_id` (default `answerdotai/ModernBERT-base`), `ml_target_ratio` (default `0.5`), `ml_max_input_chars` (default `200000`), `ml_device` (`cpu`/`auto`), `ml_sidecar_idle_timeout_secs`.-- If that process is unavailable or an input exceeds the character cap, it falls back to the native compressors and never fails the agent loop.-## Nothing is lost: the CCR cacheLossy compression normally throws data away. TokenJuice instead stores the full original in the CCR store and leaves a breadcrumb (`vendor/tinyjuice/src/cache/`).diff --git a/scripts/__tests__/module-pins.test.mjs b/scripts/__tests__/module-pins.test.mjsindex dc1e7ce759..0e26906b37 100644--- a/scripts/__tests__/module-pins.test.mjs+++ b/scripts/__tests__/module-pins.test.mjs@@ -79,7 +79,6 @@ function submodulesPresent() {"vendor/tinywallet","vendor/tinyjuice","vendor/tinyvoice",- "vendor/tinyruntime","vendor/tinymcp","vendor/tinyconnectors",];diff --git a/scripts/ci/check-dep-sim-calibration.sh b/scripts/ci/check-dep-sim-calibration.shindex c1cd19c8eb..f38b41ec70 100755--- a/scripts/ci/check-dep-sim-calibration.sh+++ b/scripts/ci/check-dep-sim-calibration.sh@@ -15,10 +15,8 @@# whenever scripts/kernel-floor.limits does and belongs in the same PR.# 264 -> 265 on 2026-08-21: the tinymemory #76/#77 bump adds exactly one# name, `tinymemory-bus`. 265 -> 267 on 2026-08-22: the MCP extraction-# adds `tinymcp` and `tinymcp-bus`. 267 -> 268 on 2026-08-22: language-# runtimes moved behind the `tinyruntime` TinyBus module, adding-# `tinyruntime-bus`. 268 -> 269 on 2026-08-23: the TinyJuice wire-# contract moved into `tinyjuice-bus`, which cannot be gated because+# adds `tinymcp` and `tinymcp-bus`. 267 -> 268 on 2026-08-23: the+# TinyJuice wire contract moved into `tinyjuice-bus`, which cannot be gated because# `inference::tokenjuice` compiles in every build. 269 -> 270 on# 2026-08-29: `tinytools` becomes the dependency behind the `Tool`# trait/types, which cannot be gated because `tools/` is kernel@@ -113,8 +111,10 @@ cd "$(dirname "$0")/../.."# 316 -> 317 on 2026-10-10: storage-file is always on, adding the# first-party tinystoragedrivers-file crate (one package, one name; no new# external crate).-# This matches the current `flows:339:317:2` entry in+# 339 -> 337 packages / 317 -> 315 names on 2026-10-10: removing the+# managed-runtime dependency surface sheds two names; native builds stay at 2.+# This matches the current `flows:337:315:2` entry in# scripts/kernel-floor.limits; its preceding entries are historical.-EXPECTED_NAMES=317+EXPECTED_NAMES=315exec python3 scripts/dep-sim.py --cut-nothing --expect-names "${EXPECTED_NAMES}"diff --git a/scripts/ci/check-module-pins.mjs b/scripts/ci/check-module-pins.mjsindex 669f42fe3b..67bb64378e 100755--- a/scripts/ci/check-module-pins.mjs+++ b/scripts/ci/check-module-pins.mjs@@ -84,24 +84,11 @@ const PIN_MAP = {tinywallet: { submodule: "vendor/tinywallet" },tinyjuice: { submodule: "vendor/tinyjuice" },tinyvoice: { submodule: "vendor/tinyvoice" },- tinyruntime: { submodule: "vendor/tinyruntime" },tinymcp: { submodule: "vendor/tinymcp" },tinyconnectors: { submodule: "vendor/tinyconnectors" },tinybox: { submodule: "vendor/tinybox" },tinychannels: { submodule: "vendor/tinychannels" },tinyhosts: { submodule: "vendor/tinyhosts" },- "tinyruntime-nodejs": {- submodule: null,- provider: { builtAgainst: "vendor/tinyruntime" },- reason:- "released from tinyhumansai/tinyruntime-nodejs on its own version line; checked via module-provider-pins.json",- },- "tinyruntime-python": {- submodule: null,- provider: { builtAgainst: "vendor/tinyruntime" },- reason:- "released from tinyhumansai/tinyruntime-python on its own version line; checked via module-provider-pins.json",- },};const failures = [];diff --git a/scripts/ci/check-openhuman-rust-layout.mjs b/scripts/ci/check-openhuman-rust-layout.mjsindex 2551bb3432..322ef42a26 100644--- a/scripts/ci/check-openhuman-rust-layout.mjs+++ b/scripts/ci/check-openhuman-rust-layout.mjs@@ -48,7 +48,7 @@ const LEGACY_LIMIT_ENTRIES = [["crates/openhuman-core/src/agent/session_host/builder/factory.rs", 973],["crates/openhuman-core/src/agent/subagent_host/lifecycle.rs", 1247],["crates/openhuman-core/src/agent/subagent_host/ops/runner.rs", 1132],- ["crates/openhuman-core/src/tools/ops.rs", 970],+ ["crates/openhuman-core/src/tools/ops.rs", 883],["crates/openhuman-core/src/web_chat/progress_bridge.rs", 1264],// These established external test modules grew with upstream coverage. Pin// their current sizes while follow-up work separates their test concerns.diff --git a/scripts/ci/fetch-submodule-tags.sh b/scripts/ci/fetch-submodule-tags.shindex 479dc58ce3..6a161c4abe 100755--- a/scripts/ci/fetch-submodule-tags.sh+++ b/scripts/ci/fetch-submodule-tags.sh@@ -12,7 +12,7 @@ cd "$(dirname "$0")/../.."for module in \vendor/tinydocs vendor/tinywallet vendor/tinymemory vendor/tinyjuice \- vendor/tinyvoice vendor/tinyruntime vendor/tinymcp vendor/tinyconnectors \+ vendor/tinyvoice vendor/tinymcp vendor/tinyconnectors \vendor/tinysearch vendor/tinybox vendor/tinychannels vendor/tinyhostsdoif [ "$(git -C "$module" rev-parse --is-shallow-repository)" = true ]; thendiff --git a/scripts/ci/module-pin-exemptions.json b/scripts/ci/module-pin-exemptions.jsonindex 8af2cdaf35..758dc7954c 100644--- a/scripts/ci/module-pin-exemptions.json+++ b/scripts/ci/module-pin-exemptions.json@@ -13,14 +13,14 @@],"exemptions": [{- "id": "tinywallet",- "expect": "v0.7.4-6-gaccb920a",- "reason": "The vendored tree includes six unreleased commits; the shipped v0.7.4 artifact remains the last published runtime module. Remove this exception when the next artifact is published and both pins advance."+ "id": "tinybox",+ "expect": "v0.1.16-7-gb61c6bce",+ "reason": "The upstream submodule includes seven unreleased commits while the registry continues to load the published v0.1.16 module. Remove this exception when the next TinyBox artifact is published and both pins advance."},{- "id": "tinychannels",- "expect": "v0.1.12-3-g5e3b2044",- "reason": "The vendored tree includes three unreleased commits; the shipped v0.1.12 artifact remains the last published runtime module. Remove this exception when the next artifact is published and both pins advance."+ "id": "tinyjuice",+ "expect": "v0.6.1-2-gb085e82",+ "reason": "OpenHuman integration is validating the v2 contract from tinyhumansai/tinyjuice#62 before its release. Replace this exception with the published v2 artifact and matching submodule pin before this PR is marked ready."}]}diff --git a/scripts/ci/module-provider-pins.json b/scripts/ci/module-provider-pins.jsonindex 13e055dc1a..b5153e687a 100644--- a/scripts/ci/module-provider-pins.json+++ b/scripts/ci/module-provider-pins.json@@ -1,25 +1,6 @@{"$comment": [- "Provider modules released from their OWN repositories on their own version line",- "(so their version can never equal a vendor/ tag). See scripts/ci/check-module-pins.mjs.",- "",- "`version` is the provider release the registry record must name; `built_against` is the",- "full commit of the shared source submodule (vendor/tinyruntime) that release was built",- "from, i.e. the provider repository's own pin at that tag. check-module-pins.mjs fails",- "when the host's gitlink moves off `built_against`: re-release the provider and update",- "this file together with the registry record. Take `built_against` from",- "`gh api repos/<repo>/contents/vendor/tinyruntime?ref=v<version>`."+ "Provider modules released from their own repositories on their own version line. See scripts/ci/check-module-pins.mjs."],- "providers": {- "tinyruntime-nodejs": {- "repo": "tinyhumansai/tinyruntime-nodejs",- "version": "0.2.7",- "built_against": "e685357099722a25c0d61e1678df69b71a049033"- },- "tinyruntime-python": {- "repo": "tinyhumansai/tinyruntime-python",- "version": "0.2.7",- "built_against": "e685357099722a25c0d61e1678df69b71a049033"- }- }+ "providers": {}}diff --git a/scripts/ci/product-features.txt b/scripts/ci/product-features.txtindex a780310460..80cfa594dd 100644--- a/scripts/ci/product-features.txt+++ b/scripts/ci/product-features.txt@@ -83,11 +83,6 @@ scheduler-gate# with nothing to attach, and the absence is silent.file-logging-# The managed Node.js toolchain (download/verify/extract/install a pinned-# release) and the JavaScript language surface on top of it. Carries `xz2` and-# its static liblzma C build.-runtime-node-# The `hosting_*` agent tools: put a workspace on a real hosting provider and# manage its sites, databases, environment, domains and deployments over the# tinyhosts unified model. Its gate in the root Cargo.toml declaresdiff --git a/scripts/ci/storage-bypass-baseline.json b/scripts/ci/storage-bypass-baseline.jsonindex bcc9600972..f93a64f801 100644--- a/scripts/ci/storage-bypass-baseline.json+++ b/scripts/ci/storage-bypass-baseline.json@@ -328,13 +328,6 @@"text": "std::fs::write(&layout.meta_path, raw)","occurrence": 1},- {- "rule": "json-write",- "path": "crates/openhuman-core/src/runtime/python_server/kompress.rs",- "line": 150,- "text": "tokio::fs::write(",- "occurrence": 1- },{"rule": "json-write","path": "crates/openhuman-core/src/security/audit.rs",diff --git a/scripts/kernel-floor.limits b/scripts/kernel-floor.limitsindex 59c165421b..ceeb5f531b 100644--- a/scripts/kernel-floor.limits+++ b/scripts/kernel-floor.limits@@ -278,22 +278,7 @@# and drops the path dependency, keeping only# `tinymcp-bus` — at which point the MCP transport stack# leaves the always-on graph entirely. Lower it in that PR.-# (2) Language runtimes moved behind the `tinyruntime`-# TinyBus module (+1 package, +1 NAME: `tinyruntime-bus`,-# the wire contract for the runtime router). It lands on the-# always-on path and cannot be gated: `ShellTool` holds an-# `Option<Arc<NodeBootstrap>>` as a FIELD and-# `tools/impl/system/shell.rs` is kernel, so the toolchain-# clients in `runtime/` are always compiled and name the-# contract's payload types. `tinyruntime-bus` is-# deliberately dependency-light — `serde` and `serde_json`,-# both already in this profile, and nothing else. What it-# buys is a much larger shed elsewhere: downloading,-# verifying and unpacking language toolchains left this-# repository entirely, taking `xz2` AND its static liblzma C-# build with it, so `runtime-node = []` as a result. The-# two native packages are unchanged.-# 283/265/2 2026-08-21 tinymemory bumped past its #76/#77 line (-2 packages,+# 283/265/2 2026-08-21 tinymemory bumped past its #76/#77 line (-2 packages,# +1 NAME). The name is `tinymemory-bus`, and it is a# RAISE, so: tinymemory#74 moved the wire vocabulary —# member names, payload types, the error-name table — out@@ -473,7 +458,7 @@# limit to paper over inherited growth is what this file# exists to prevent.# 302/279/2 2026-08-09 `memory-git` gate (-3 packages / -3 names / -2 NATIVE),-# measured on top of the runtime-node entry below.+# measured on the then-current dependency graph.## *** THE SPEC TARGET IS REACHED. *** Two native builds# remain — `libsqlite3-sys` and `ring` — which is exactly@@ -504,17 +489,6 @@# written. Default (full-feature) profile moved 356 -> 353.# Verified with `scripts/assert-shed.sh flows git2# libgit2-sys libz-sys`.-# 305/282/4 2026-08-09 runtime-node gate, measured on top of the-# upstream/main merge below (307/284/5 -> 305/282/4).-# `xz2` + its static liblzma C build are exclusive to-# runtime::node::extractor's .tar.xz path, so gating the-# managed Node toolchain removes them: -2 packages, -2-# names, and lzma-sys leaves the NATIVE list (5 -> 4) —-# the first native toolchain build removed by the gating-# program. Remaining native: libgit2-sys, libsqlite3-sys,-# libz-sys, ring — the target keeps the last two.-# Measured with `scripts/kernel-floor.sh flows`, and-# `scripts/dep-sim.py --cut-nothing` agrees (282 names).# 307/284/5 2026-08-09 merge upstream/main + PR #5446 memory-subsystem work.# Measured, not derived: `scripts/kernel-floor.sh flows`# reports 307/284/5 on this merge. +3 names over the@@ -673,4 +647,6 @@# the file driver backs `file:` URLs), which adds the# first-party tinystoragedrivers-file crate (one package,# one name; no external crate, native builds unchanged).-flows:339:317:2+# 337/315/2 2026-10-10 remove the managed runtime and ML compression stacks;+# two unique packages and names leave the flows graph.+flows:337:315:2diff --git a/scripts/lib/module-pins.mjs b/scripts/lib/module-pins.mjsindex 2be1c53f59..9b0aa63ae7 100644--- a/scripts/lib/module-pins.mjs+++ b/scripts/lib/module-pins.mjs@@ -157,7 +157,7 @@ export function classifyPin({ id, version, submodulePath, actual, exemption }) {/*** Decide what a provider record's pin state means.*- * A provider module (tinyruntime-nodejs, tinyruntime-python) is released from+ * A provider module is released from* its OWN repository on its OWN version line, so its version can never equal* the tag of the shared source submodule it is built against. What can be* checked offline is: (1) the registry record names the release thatdiff --git a/vendor/tinyjuice b/vendor/tinyjuiceindex b134e70514..b085e8250d 160000--- a/vendor/tinyjuice+++ b/vendor/tinyjuice@@ -1 +1 @@-Subproject commit b134e7051441e716b4c3749d03a3c17bbee7164f+Subproject commit b085e8250da6a5f5529a6cd85df627d4b220b304