openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

Add harness_script/python_runner for LLM-authored orchestration flows

Open senamakel opened this issue 5 months ago • 1 comments

Summary

Add a first-class harness_script/python_runner layer that lets an LLM author expressive Python orchestration scripts over OpenHuman's existing harness primitives.

The goal is RLM / Claude-workflow style expressiveness without turning arbitrary Python into the authority for local side effects. Python should coordinate approved agent/workflow primitives; existing OpenHuman agents and tools should continue to own filesystem, shell, network, approval, sandboxing, memory, model routing, and policy.

Motivation

OpenHuman already has the hard execution pieces:

  • runtime_python resolves, installs, and launches a managed Python interpreter.
  • runtime_python_server keeps trusted Python backends warm for fixed methods like spaCy and Kompress.
  • agent::harness owns the shared LLM tool loop, prompt construction, compaction, cost/budget checks, and sub-agent execution.
  • agent_orchestration owns parent/child lineage, lifecycle state, wait/close/follow-up semantics, and progress events.
  • workflow_runs supports durable declarative phase DAGs.
  • run_workflow / await_workflow already let an agent compose reusable workflows by id.

What is missing is an LLM-writable control-flow layer. Current durable workflows are intentionally static phase graphs, not arbitrary scripts. That is safer, but it makes ad hoc decomposition, fanout/reduce, retries, branching, loops, and intermediate state awkward for an LLM to define.

External reference points / attribution

This issue is inspired by two public systems:

  1. Recursive Language Models (RLM) by Alex Zhang et al.

    • Repo: https://github.com/alexzhang13/rlm
    • Paper/blog linked from the repo.
    • Core idea: replace llm.completion(prompt) with rlm.completion(prompt), where the model writes CodeAct-style Python into a REPL. The prompt/context live as variables, and recursive calls such as llm_query(...), rlm_query(...), and batched variants are ordinary Python functions.
    • Relevant design lesson for OpenHuman: model-authored code is a natural way to express loops, maps/reduces, recursion, intermediate state, and sub-call composition.
  2. Claude Code workflows

    • Docs: https://code.claude.com/docs/en/workflows
    • Core idea: Claude can author and run background JavaScript workflow scripts. The script stores intermediate state in variables and controls agent fanout, branching, waiting, retries, and synthesis.
    • Relevant design lesson for OpenHuman: keep the script as the orchestration authority, while agents remain the execution workers. Claude's docs explicitly distinguish workflows from subagents/skills/teams: subagents are turn-by-turn model decisions; workflows are script-controlled execution plans.

This proposal is not to copy either system wholesale. It is to adapt the useful abstraction to OpenHuman's stricter policy/sandbox/runtime architecture.

Current local anchors

Existing code that should be reused instead of duplicated:

  • src/openhuman/runtime_python/README.md
    • runtime_python owns managed interpreter discovery, download/install, and stdio process launch.
  • src/openhuman/runtime_python_server/server.py
    • Current long-lived Python server is a fixed-method backend host (spacy.extract, kompress.compress). Do not turn this shared server into an arbitrary-code REPL.
  • src/openhuman/agent_orchestration/README.md
    • High-level parent/child lifecycle model.
  • src/openhuman/agent_orchestration/workflow_runs/types.rs
    • Declarative workflow definition model. It explicitly avoids arbitrary scripts.
  • src/openhuman/agent/tools/run_workflow.rs
    • Existing workflow composition guardrails: spawn backstop, active await cap, re-entrancy lock.
  • src/openhuman/agent/harness/definition.rs
    • Data-driven agent definitions, tool scopes, runtime limits, and spawn hierarchy.
  • src/openhuman/agent/harness/engine/core.rs
    • Shared agent turn engine to keep child execution semantics consistent.

Proposed design

Add a new module family:

src/openhuman/harness_script/
  mod.rs
  python_runner.rs
  schemas.rs
  types.rs
  store.rs            # optional, if not folded into existing run ledger
  protocol.rs
  README.md

The runner should launch a fresh Python subprocess per workflow/script run using runtime_python::PythonBootstrap. The subprocess speaks a compact JSONL stdio protocol to Rust.

Do not use the existing runtime_python_server process for this. That process is a trusted shared backend host for NLP/ML services; arbitrary LLM-authored code needs per-run isolation and clean state.

Python programming model

The script should be ordinary Python, but with a deliberately tiny injected API:

# Example target user experience for an LLM-authored harness script.
areas = ["security", "correctness", "performance"]

findings = parallel([
    agent("researcher").run({
        "task": f"Audit {area} risks in the target code. Return concrete file refs."
    })
    for area in areas
], concurrency=3)

verified = parallel([
    agent("critic").run({
        "task": "Try to refute this finding against the actual code.",
        "finding": finding.output,
    })
    for finding in findings
], concurrency=3)

checkpoint("raw_findings", findings)
checkpoint("verified_findings", verified)

return_result({
    "summary": synthesize(findings, verified),
    "findings": findings,
    "verification": verified,
})

Potential injected primitives:

agent(id).run(input: dict, *, wait: bool = True, timeout: int | None = None) -> AgentResult
agent(id).start(input: dict) -> RunHandle
wait(handle_or_handles, *, timeout: int | None = None) -> AgentResult | list[AgentResult]
parallel(tasks, *, concurrency: int = 4) -> list
workflow(id).run(inputs: dict, *, wait_seconds: int = 90) -> WorkflowResult
checkpoint(name: str, value: Any) -> None
artifact(name: str, value: Any) -> None
return_result(value: Any) -> Never
sleep(seconds: float) -> None
budget() -> BudgetSnapshot

Key rule: the Python script coordinates. It should not get direct shell, filesystem, network, or arbitrary host APIs by default. Leaf agents use OpenHuman tools under existing policy.

Reference protocol sketch

Python subprocess emits requests to Rust:

{"id":"1","method":"agent.run","params":{"agent_id":"researcher","input":{"task":"..."},"timeout_secs":600}}
{"id":"2","method":"checkpoint.put","params":{"name":"raw_findings","value":[...]}}
{"id":"3","method":"workflow.run","params":{"workflow_id":"pr-review-shepherd","inputs":{"pr":123},"wait_seconds":0}}

Rust replies:

{"id":"1","ok":true,"result":{"run_id":"...","status":"completed","output":"...","cost":0.12}}
{"id":"2","ok":true,"result":{}}
{"id":"3","ok":true,"result":{"run_id":"...","status":"running"}}

The Python helper library can hide the JSON protocol so LLMs write normal Python rather than JSON plumbing.

Safety model

Initial version should be conservative:

  • Fresh Python subprocess per script run.
  • No direct filesystem, network, shell, import of arbitrary installed packages, or env access in the default runner.
  • Only stdlib features needed for orchestration: lists/dicts/functions/classes/control flow/json/math/time-ish helpers.
  • All side-effectful work must happen through agent(...).run(...) or workflow(...).run(...) so existing tool policy, approvals, sandboxing, and model routing remain authoritative.
  • Hard caps:
    • max script wall time
    • max agent runs per script
    • max concurrent child agents
    • max nested workflow awaits
    • max checkpoint/artifact bytes
    • max stdout/stderr bytes
  • Reuse or adapt guardrails from run_workflow.rs: spawn backstop, active await cap, re-entrancy lock.
  • Add explicit safety_tier metadata for scripts, similar to workflow definitions.
  • Require user approval before running LLM-authored scripts that can trigger edit-capable agents.

Why Python first

Python is a pragmatic first language because:

  • LLMs write it well.
  • It naturally expresses loops, branching, recursion, fanout/reduce, retry logic, and temporary data structures.
  • OpenHuman already has runtime_python, so interpreter distribution is solved.
  • It maps closely to the RLM programming model while still allowing us to enforce OpenHuman-specific policy at the Rust boundary.

JavaScript/TypeScript can be added later using runtime_node, but Python is enough to validate the product abstraction.

Implementation plan

Phase 1: Runner skeleton

  • Add src/openhuman/harness_script/ module.
  • Add a minimal PythonHarnessScriptRunner that resolves Python through PythonBootstrap and launches a subprocess with piped stdio.
  • Add a tiny Python bootstrap script embedded or written to cache dir at startup.
  • Implement handshake, request/response framing, timeout, cancellation, stdout/stderr capture, and child cleanup.
  • Unit-test process lifecycle and protocol errors.

Phase 2: Orchestration bridge

  • Implement Rust-side handlers for:
    • agent.run
    • agent.start
    • agent.wait
    • workflow.run
    • checkpoint.put
    • artifact.put
    • budget.get
  • Route agent execution through existing agent_orchestration / agent::harness paths, not a new child-agent runner.
  • Persist child run ids and checkpoints in the existing run ledger or a new script-run table.

Phase 3: Tool surface

  • Add an orchestrator-visible tool, e.g. run_harness_script.
  • Inputs:
    • language: "python"
    • script
    • inputs
    • safety_tier
    • wait_seconds
  • Return either terminal output or a detachable run id.
  • Add await_harness_script for re-attaching to long runs.

Phase 4: Validation and approvals

  • Add static validation for disallowed syntax/imports/calls in the Python AST.
  • Enforce runtime caps independent of static validation.
  • Gate edit-capable scripts behind explicit approval.
  • Emit clear validation errors that an LLM can repair.

Phase 5: Observability/UI

  • Add event stream entries for:
    • script started/completed/failed/cancelled
    • child agent started/completed
    • checkpoint written
    • artifact written
  • Surface runs in the existing workflow/agent run UI where possible.
  • Emit backend observability events for the script execution graph so we can detect and debug graph-level failures: invalid edges, stuck waits, fanout backpressure, child-run failures, retry loops, cancellation propagation bugs, checkpoint serialization errors, and budget/guardrail trips.
  • Send only privacy-safe telemetry to the backend: stable run ids, node ids, agent ids, workflow ids, phase names, statuses, timings, cost/token counters, error classes, guardrail names, and hashed/redacted argument fingerprints. Do not upload raw prompts, tool outputs, script source, checkpoint payloads, artifacts, file contents, user messages, environment variables, or other PII.
  • Reuse the backend's PII stripping/redaction path before any graph telemetry leaves the client, and add tests that prove sensitive fields are removed while graph topology and error diagnostics remain usable.
  • Store local script source + inputs + outputs for replay/debugging; backend telemetry should reference local run ids rather than carrying sensitive payloads.

Phase 6: Docs and examples

  • Add docs explaining when to use:
    • direct tool call
    • subagent
    • static workflow DAG
    • harness script
  • Include example harness scripts:
    • deep research fanout + critic verification
    • PR review shepherd
    • audit finder -> verifier -> synthesizer
    • retrying flaky integration work

Acceptance criteria

  • An LLM can submit a Python harness script that fans out to multiple existing agent definitions, waits for results, checkpoints intermediate state, and returns a synthesized result.
  • Script execution uses runtime_python; no new Python distribution mechanism is introduced.
  • The shared runtime_python_server remains fixed-method and is not used for arbitrary script execution.
  • Child work flows through existing agent/workflow runners and inherits existing policy, sandbox, approval, model routing, and telemetry behavior.
  • A script run is durable enough to inspect after completion: source, inputs, child run ids, checkpoints/artifacts, final output, error if any.
  • Backend graph observability captures privacy-safe topology, status, timing, cost, guardrail, and error-class events for script runs, with PII stripping tests covering prompts, outputs, script source, checkpoint payloads, artifacts, env vars, and user messages.
  • Hard caps prevent runaway fanout/recursion/await loops.
  • Tests cover protocol lifecycle, validation rejection, successful fanout, cancellation, and guardrail trips.

Open questions

  • Should script runs reuse workflow_runs storage or get a distinct harness_script_runs ledger?
  • Should the first version allow persistent per-run Python state across turns, or only one-shot scripts?
  • Should static workflow DAGs compile to harness scripts eventually, or remain separate primitives?
  • Should Python imports be completely disabled initially, or allow a curated stdlib allowlist?
  • How should script-authored artifacts appear in the UI relative to agent artifacts?

senamakel avatar Jun 29 '26 00:06 senamakel

Closing in favor of the hosted medulla orchestration direction.

The core need here — RLM / Claude-workflow style expressiveness for multi-step, fan-out/reduce, branching orchestration — is now served by the medulla v3 orchestration surface rather than a new on-device LLM-authored script layer:

  • Backend /orchestration/v1/run + /run/continue (tinyhumansai/backend#1085) provide a caller-driven tool loop with server-side reasoning, prompt/config/limit overrides, and paid-gated billing.
  • OpenHuman integrates against it in #4807 (openhuman.orchestration_run), executing tool calls on-device through the existing agent/tool policy + trust gate while the reasoning runs in the hosted brain.
  • That surface already exposes an ORCHESTRATE_RLM_SYSTEM prompt — the recursive-language-model orchestration this issue cited RLM as inspiration for is delivered server-side.

This also aligns with the architectural pivot to a hosted-only brain (#4738, which retired the client-side local orchestration engine). Introducing a new local orchestration-authority layer that executes arbitrary LLM-authored Python on-device (with its own AST validation, subprocess sandbox, approval gates, and PII-stripped observability) runs counter to that direction and largely duplicates what medulla now provides.

The underlying capability gap noted here — that static workflow_runs DAGs can't express dynamic, LLM-authored control flow — remains valid. If a need for local (offline / non-paid-gated) script-driven orchestration resurfaces that medulla can't cover, we'll reopen with a design reconciled against the medulla surface. For now, medulla is the path.

YellowSnnowmann avatar Jul 13 '26 09:07 YellowSnnowmann