# Pi Training Harness

This repository provides Pi-based focused harness profiles without replacing Pi's runtime. See [Profiles](#profiles) for the complete list.

The custom profiles share Pi's model runtime, TUI, headless modes, compaction, resume, and native JSONL sessions. Their system prompts and tool contracts remain isolated from the `pi` harness.

## Install

Requires Node.js 22.19 or newer.

```bash
npm install --global @qwen-code/qwen-harness@dev
qwen-harness --help
```

For repository development, install dependencies with `npm install --ignore-scripts`.

Pi runtime dependencies are pinned to 1.5.0. The explicit `@earendil-works/pi-server`
dependency supplies the server runtime used by Pi.

## Development

Use one development command for every harness. Omitting `--harness` runs the `pi` profile:

```bash
npm run dev
npm run dev -- --harness bash-apply-patch -p "Fix the failing tests"
```

## Run

```bash
qwen-harness
qwen-harness --harness bash-apply-patch -p "Fix the failing tests"
```

Pass any name from the [Profiles](#profiles) table to `--harness`. The `scaling` profile also consumes its `--scaling-*` options; the remaining arguments are passed to Pi.

To use the same command from a checkout, run `npm run build && npm link` once. Re-run
`npm run build` after source changes; `qwen-harness` will continue to point at this checkout.

The compiled entrypoint calls Pi's public `main()` function. The `pi` harness adds no
system prompt or new tool names; it keeps Pi's four built-in tools and applies the bounded
`bash` capability. `pi-ptc` preserves Pi's normal prompt
but activates the packaged programmatic-tool-calling capability: the model sees only
`run_code`, while Pi's four default tools are callable from its JavaScript runtime.
`self-compact` preserves Pi's normal prompt and built-in tool names while adding context
compaction and applying the same bounded `bash` capability; external extension and
skill discovery are disabled for these harnesses.
The Arena profiles load only their explicit tool extensions. Long Horizon
loads only its declared `pi-subagents` dependency by its resolved package path and restricts
the Supervisor to its three orchestration tools. Extension discovery, built-in tools, and
unrelated resource catalogs remain disabled by each profile's own contract.
The tool-comparison profiles keep Pi's built-in implementations except for the bounded
`bash` capability, apply an explicit
model-visible tool allowlist, and load only the selected custom editor when one is required.

## Harness Scaling: Components × Design

The `scaling` profile assembles one design from each of six components. It includes the
survey's 18 pairwise-orthogonal configurations (`H01`–`H18`): each design appears six
times, and each of the 135 cross-component pairs appears twice. These are the first
evaluation batch: evaluate all 18, identify weak configurations, add targeted SFT/RL,
and reevaluate. The full six-axis space contains 729 configurations.

All 18 presets use the complete S v2 policies: S1 is a concise maintainer with
dense rules, S2 an implementation partner with conditional workflow stages, and
S3 a contract-oriented engineer with layered constraints. Each policy covers the
same core responsibilities while differing in clarification, regression tests,
comments, and delivery defaults. Runtime context supplies the actual workspace,
platform, command shell, date, and interaction mode. Print/JSON runs and delegated
children are non-interactive; the bound host determines dialog support.
The TS/TC/O/C/W composition and tool interfaces remain independent of S.

```bash
# Show the 18 configurations without calling a model.
npm run dev -- --harness scaling --scaling-list

# Inspect the selected prompt, tool entry points, and limits.
npm run dev -- --harness scaling --scaling-preset H02 --scaling-describe

# Run through Pi's normal model/provider, output, and session options.
npm run dev -- --harness scaling --scaling-preset H02 -p "Fix the failing tests"
npm run dev -- --harness scaling --scaling-config ./experiment.json -p "Fix the failing tests"
```

`experiment.json` specifies exactly six choices, for example:

```json
{"S":"S2","TS":"TS3","TC":"TC3","O":"O3","C":"C2","W":"W3"}
```

The composer records model calls, tool calls, tokens, cost, and subagent usage.
It imposes no task-wide token, call-count, or elapsed-time ceiling, and no subagent
count or per-child call ceiling. Experiment runtime limits belong to the evaluation
runner and should be held constant across configurations. `--scaling-describe`
reports the component parameters for output handling and context management.

| Component | Design 1 | Design 2 | Design 3 | Mechanism reference |
| --- | --- | --- | --- | --- |
| S: system prompt | Minimal guidance | Eight explicit engineering rules | The same rules plus steps, failure branches, and two examples | Pi's concise core; Codex engineering rules and Qwen Code mandates/workflows |
| TS: task tools | 70 standard snake_case tools | Baseline 20 with fixed new names | The same 70 with fixed new names | Existing capabilities, Pi MCP, and Harness Corpus tool contracts |
| TC: invocation | Core direct tools plus on-demand discovery | `run_code`, fresh JavaScript scope per call | `exec`, persistent JavaScript variables and functions | Pi's native discovery/codemode; [Fibona](https://github.com/FibonaAI/fibona-agent) native REPL pattern |
| O: observations | Direct text within the feedback limit | Fixed head/tail preview, no saved-output path | Same preview plus a complete output file, read through the selected task tools | Qwen Code / OpenCode / Pi / Kimi Code saved-output paths |
| C: context | Host-generated summary at pressure threshold | Model-authored Notes and explicit window handoff | Segment summaries, older summary rollups, and source index | Pi compaction; local Qwen Code Notes; [Headlong](https://github.com/laude-institute/headlong) tiered recap |
| W: workflow | Autonomous loop | Investigate, submit a plan, automatically execute next turn | Optional one-level `subagent` delegation | Codex Plan mode; independent returning subagent sessions |

TS, C, and W first contribute their tools to one registry. TC then determines
how the model reaches **all** of them. TC2/TC3 register the underlying tools as
callable-only and expose one entry point. Every nested call goes through Pi's
`executeTool`, preserving validation, hooks, planning gates, observation policy,
and usage records. Pi's registration allowlist includes both visible and callable
tools; the active loadout controls visibility.

The baseline 20 are `read_file`, `apply_patch`, `list_directory`, `glob`, `grep`,
`bash`, `list_processes`, `read_process_output`, `write_stdin`, `stop_process`,
`web_search`, `http_request`, `skill`, `notebook_edit`, `memory_search`,
`memory_write`, `enter_worktree`, `exit_worktree`, `list_mcp_resources`, and
`read_mcp_resource`. The additional 50 cover LSP and batch edits, scheduling and
monitoring, skills, media, workflows, goals, tasks, MCP, session archives,
communications, artifacts, plugins, connections, intents, secrets, and local portals.
There are no browser tools. C/W tools and TC entry points are counted separately.

Each tool lives in `src/capabilities/tools/<category>/`; shared state and clients
live in `src/utils/`. The two capability builders assemble 20 or 70 definitions;
scaling adds policy guards and then applies the versioned name mapping. TS2 and TS3
share the same aliases for the baseline 20. Aliases use synonymous functional names,
such as `read_file` → `inspect_file`, `bash` → `run_shell`, and
`http_request` → `request_url`. Schemas and execution remain the same. TC programs can call
every exact name with `tools["name"](args)`. The JavaScript bridges also support
normalized identifier aliases; Pi's native QuickJS tool catalog lists those identifiers.

Optional services are supplied with `--scaling-tool-config ./tool-services.json`:

```json
{
  "mcpServers": {
    "project": { "command": "node", "args": ["./mcp-server.js"] },
    "remote": {
      "url": "https://example.com/mcp",
      "headers": { "Authorization": "Bearer ${MCP_TOKEN}" }
    }
  },
  "skillPaths": ["./skills"],
  "lspServers": {
    "typescript": {
      "command": "typescript-language-server",
      "args": ["--stdio"],
      "extensions": [".ts", ".tsx"],
      "language_id": "typescript"
    }
  },
  "sessionDirectory": "/path/to/authorized/session-archives"
}
```

Commands and paths are resolved from the project working directory. Environment
references in MCP headers/environment, LSP environment, and gateway tokens expand
as `${NAME}`; missing values are errors. Configuration never evaluates shell
substitutions. `gateway` accepts an OpenClaw `url`, `token`, and `session_key` for
the external conversation tools. `transcriptProviders` maps names to stdout capture
commands. Media generation and search reuse the existing capability provider settings.
Missing external providers return a configuration error when their tools are called.
Interactive secret entry and clarification require Pi's UI; headless calls report
their unavailability. Secret references can be used in HTTP/MCP headers, MCP
environment, and gateway tokens; children can resolve inherited references without
copying plaintext into tool results.

State defaults to `scaling-tools/<exact-session-id>/` under Pi's session directory.
`stateRoot` can change the parent directory. Memory, task records, schedules, goals,
and configured connections survive resume; runtime processes and handles are stopped
on shutdown. Interrupted execution records are marked cancelled on restart; missed
wakeups are recorded rather than replayed. Timers and monitors run only while the
hosting session is alive. Resuming requires the same six-axis configuration, limits,
tool catalog, naming version, and state root. Sessions from the former TS design
require a new run. Background notifications pass through the selected O policy;
workflow tools use the same guarded execution path. Explicit goal budgets use the
shared parent/child/summary accounting; no goal budget is added automatically.

The concrete adaptations are:

- **S:** all three designs share the same identity, workspace description, and selected
  component mechanisms. S1 follows Pi's concise guidance style. S2 combines Codex and
  Qwen Code engineering guidance into eight rules covering evidence, project conventions,
  scope, existing work, dependencies, verification, failures, and completion. S3 includes
  all of S2 and adds an iterative task workflow, failure and missing-information branches,
  and two worked examples adapted from Qwen Code's workflow style. The templates are
  rewritten for this experiment. Tool names and calling protocols come from TS/TC;
  planning, delegation, and context tools remain controlled by W/C.
- **TC1:** exposes `bash`, `read_file`, `apply_patch` (create and edit), and `tool_search`
  on the first request. W3 parents also expose `subagent`. Pi's ToolSearch ranks deferred
  task, context, and planning tools by name and description. Matches are callable on the
  next request and stay loaded on the same session branch. TS2/TS3 apply their aliases
  to both the search entry point and the tool definitions it returns.
- **TC2:** uses `@earendil-works/pi-codemode` 1.5.0 for the QuickJS sandbox, tool
  declarations, bridge, cancellation, and execution deadline. Registered nested calls
  still pass through Pi's `executeTool` and the selected O/C/W policies. Each call has
  fresh variables and functions; `store/load` writes are not retained between calls.
  Native `text`, `console`, `image`, `exit`, and return values are supported; timers
  and direct Node/filesystem/network APIs are unavailable. Its native five-minute
  default deadline is disabled so TC2 does not cut off a nested tool or subagent;
  explicit `timeout_ms` and caller cancellation still use Pi's native cancellation.
  The adapter adds no VM heap ceiling. Native
  output limits fail explicitly; successful output reaches O before display truncation,
  so O3 can save the complete emitted text. Tool search and additional model APIs are
  not added by this adapter. The standalone `pi-ptc` profile retains its existing runtime.
- **C1:** uses Pi's built-in compaction end to end: native threshold detection, history
  selection, summary prompts, and context restoration, including manual and overflow
  compaction. The composer records summary requests/usage and clears TC3 execution
  state after successful compaction. C1 continues from the summary and recent messages;
  it registers no Notes, history lookup, or context-capacity tools.
  Pi's effective `compaction.reserveTokens` and `compaction.keepRecentTokens`, including
  model overrides, are recorded in the session and inherited by C1 subagents. Automatic
  compaction must be enabled. The composer's `contextTriggerRatio` and `summaryTokens`
  do not override C1's native policy.
- **TC3:** follows Fibona's native REPL mechanism (`f3a007f`), using the same JavaScript
  language, `tools.<name>` API, and registered Pi execution path as TC2. A separate
  process exposes no Node, filesystem, or network APIs. It uses Node's default heap
  sizing and has no implicit wall-clock timeout while a nested tool or timer is active.
  Explicit `timeout_ms`, caller cancellation, and the synchronous/no-progress guard
  still apply. REPL state survives cells;
  compaction, Notes handoff, session replacement/resume, cancellation, and execution
  errors reset it. Unawaited work is cancelled when a cell ends.
  Emitted images use Pi codemode's Base64 and format-signature checks; the actual
  image signature determines the MIME type. Invalid output returns a tool error
  so the model can correct it before another request.
- **C2:** follows the local Qwen Code branch
  `dragon/local-notes-compaction@7ee219f032`: `session_notes` saves a versioned
  checkpoint, `new_context` stages a switch using that revision, and
  `session_history` recovers old observations. Saving and switching require separate
  tool-only model turns. The safe turn boundary retains Notes and user task anchors
  without a summary call. The JSONL log is authoritative; a `.notes.md` projection
  beside it is available for inspection. A stale checkpoint or pending user input
  prevents a handoff. When estimated remaining capacity is at most 6,144 tokens,
  C2 records one instruction for that context window. Pi maps its internal `system`
  role to the provider's supported `developer`/`system` instructions (Anthropic uses
  the top-level `system` field). The same historical reminder is retained without
  duplication across requests, retries, and resume; only a committed context switch
  allows another reminder. `get_context_remaining` remains available for current
  estimates. Its context tools follow TC.
- **C3:** follows Headlong's implemented tiered recap (`2e39a3f`). A segment becomes
  a leaf summary; three adjacent summaries of one level form the next level. The
  live context contains older coarse summaries plus newer fine summaries and recent
  raw messages. `memory_lookup` expands children and source references;
  `session_history` reads those sources, adapting Headlong's `traj show` / `traj search`
  access to preserved steps. The tree and original observations survive resume.
  C3 uses a 75% host-managed pressure threshold; C1 uses Pi's effective settings.
  Neither exposes a capacity query tool or per-request capacity reminder. C2 prompts the model to manage
  its window and uses an explicitly recorded emergency summary at 90% pressure.
  C2 emergency summaries and C3 segment/rollup summaries use the selected model's
  native output allowance and the parent's thinking level. `summaryTokens` is a
  prompt target, not an API generation cap. Summary calls use Pi's retry policy;
  every attempt is recorded, and incomplete responses never replace original history.
- **W2:** adapts Codex's investigation-to-execution phase boundary (`5b1d656018`) to automatic
  evaluation. Before `submit_plan`, write/edit tools are blocked. Shell investigation
  accepts literal read-only commands and pipelines (`pwd`, `ls`, `cat`, `head`,
  `tail`, `wc`, `grep`, `rg`, selected Git queries, and numeric `sed -n ...p`).
  It rejects command substitution, redirection, interpreters, and mutation commands.
  Scaling profiles use Pi's default Shell setup and omit user-configured command prefixes.
  Execution opens in the next model turn, including when the plan was submitted
  through TC2 or TC3.
- **W3:** `subagent` starts a child and returns its `agent_id` immediately. `list_agents`
  lists child status, `wait_agents` collects results (a wait timeout leaves the child
  running), and `send_message` submits additional facts or constraints through Pi's
  steering queue. Submission is distinct from child completion. At most one child runs
  at a time; the parent can continue independent work. Each child starts with the supplied
  task description, uses the parent's model route and S/TS/TC/O/C, shares the project
  directory, and has none of the four collaboration tools. It inherits the parent's Pi settings, including retries and cache warming;
  C2/C3 retain their selected context policy. Child sessions are retained under the
  parent's session directory. Parent, child, and summarization usage are recorded
  in one ledger, with no extra call or child-count ceiling. Creation, waits and message
  submission are recorded as `scaling-agent-operation` entries. If the parent tries to
  finish before collecting child results, the host waits, delivers the results through O,
  and requests integration. Parent cancellation or shutdown stops live children. Completed
  records survive session resume; interrupted children are recorded as cancelled.

All configurations use an 8,000-character observation preview and a 64,000-character
ceiling for an individual feedback text payload. O applies only immediately before model
delivery: to the direct tool result in TC1, or the completed program output in TC2/TC3.
Internal `tools.xxx` calls keep their native content, structured output, error details,
limits and spool paths. Only explicitly emitted output enters the model's observation/history.
Typed image blocks are never text-cropped. Each delivered image is actually decoded;
an invalid image is replaced by error text without discarding other valid content.
Valid images, including 1×1 images, are not enlarged or subjected to provider minimum-size rules.
O3 saves the complete delivered text or native TC1 Bash spool to a session-associated
file before applying the preview budget. The 64,000-character feedback ceiling does not
truncate that file. Large native spools are copied in full and previewed with bounded reads;
program output is also preserved before the requested display limit is applied.

O3 returns the file path and a reading hint: use `read_file` with line offset/limit or
`grep`, or use `bash` to select byte ranges. TS2/TS3 hints use the mapped names. A long single-line result
needs a byte-range read or a query of the saved data. These are the existing task tools,
reached directly in TC1 or through `run_code`/`exec` in TC2/TC3. Every retrieval still
passes through O at the model delivery boundary and is included in usage accounting. Output files live under
`scaling-outputs/<session-id>/` in the session directory and remain available after resume.

O3 output files are individual tool artifacts, so C1 can read them through its task
tools while retaining no conversation-history query. C2/C3 history lookup returns
delivered observations, including to nested programs, and cannot recover text discarded
by O2.

The common defaults are 200 model requests, 1,000 tool calls, two million reported
tokens, and one hour per task. The token limit is checked between requests: a final
in-flight response can cross it, after which further calls stop. The ledger includes
summary calls and child usage. API callers can pass shared `limits` to
`createScalingRuntime`; configuration and limits are pinned in the session and must
match on resume.

The local tests use Pi sessions against a deterministic local provider to exercise
all 18 loadouts and the cross-component mechanics. Model quality and real benchmark
performance remain the next evaluation step.

## Pi settings

Pi and the harness tools use the same global file:

```text
~/.pi/agent/settings.json
```

Long Horizon does not use project or global extension discovery. It resolves `pi-subagents`
from the harness runtime's own installed package dependencies, so other installed extensions
do not run in the Supervisor session. The process working directory remains the writable
task workspace, so container workspaces such as `/app` do not need to contain the harness's
`node_modules` directory.

Pi's native fields configure the main agent. The `harnesses` field configures models and services used inside tools:

```json
{
  "defaultProvider": "openai",
  "defaultModel": "qwen3.5-plus",
  "defaultThinkingLevel": "high",
  "compaction": {
    "enabled": true,
    "reserveTokens": 16384,
    "keepRecentTokens": 20000
  },
  "retry": {
    "enabled": true,
    "maxRetries": 5,
    "baseDelayMs": 2000,
    "provider": {
      "maxRetries": 2,
      "maxRetryDelayMs": 60000
    }
  },
  "shellPath": "/bin/bash",
  "npmCommand": ["node", "/path/to/npm-cli.js"],
  "harnesses": {
    "toolServices": {
      "routify": {
        "apiKey": "routify-key",
        "webSearchUrl": "https://routify-pub.alibaba-inc.com/protocol/compatible-mode/res/v1/llm/context",
        "imageSearchUrl": "https://routify-pub.alibaba-inc.com/protocol/brave/res/v1/images/search",
        "webFetchUrl": "https://routify-pub.alibaba-inc.com/protocol/search/tools"
      },
      "dashScope": {
        "apiKey": "dashscope-key",
        "apiBase": "https://dashscope.aliyuncs.com/api/v1"
      },
      "pexels": {
        "apiKey": "pexels-key",
        "cacheTtlMs": 86400000,
        "cacheDir": "/tmp/pi-harness-pexels-cache"
      }
    },
    "tools": {
      "webSearch": {
        "model": "brave.llm-context"
      },
      "generateImage": {
        "model": "qwen-image-2.0-pro",
        "size": "2048*2048",
        "taskTimeoutMs": 300000,
        "taskPollIntervalMs": 1000
      },
      "generateSpeech": {
        "model": "qwen-audio-3.0-tts-flash",
        "voice": "longanhuan_v3.6"
      },
      "imageCaption": {
        "provider": "openai",
        "model": "qwen-vl-max",
        "systemPrompt": "Return an accurate image caption.",
        "prompt": "Describe this image in detail for another model."
      },
      "code": {
        "bashTimeoutSeconds": 300,
        "fullStackBuildTimeoutMs": 300000,
        "previewPort": 3000,
        "previewUrl": "http://127.0.0.1:3000"
      },
      "documents": {
        "sofficePath": "/path/to/soffice"
      }
    }
  }
}
```

Only configure fields required by the tools you enable. Defaults are applied when optional fields are absent. Unknown `harnesses` fields fail at startup instead of being silently ignored. A missing service credential produces a tool error only when that service-backed tool is called.

Execution capabilities reuse Pi's native settings instead of defining harness-specific
duplicates: `npmCommand` controls npm invocation, `shellPath` selects the command shell,
and Pi resolves that shell with its normal cross-platform fallback behavior. Routify,
DashScope, and Pexels HTTP requests use `retry.provider.maxRetries` and
`retry.provider.maxRetryDelayMs`; the top-level retry count remains Pi's agent-turn
policy. The `harnesses` namespace contains only capability-specific settings that Pi
does not own.

The optional `bash` capability wraps Pi's built-in `bash` definition and
changes only its omitted timeout to 120 seconds; explicit timeouts are preserved. Profiles
must compose the capability to install it. Every profile that already exposed `bash` now
uses it: `pi`, `self-compact`, Agent Arena, Code Arena Full Stack, and all four tool-
comparison profiles. `pi-ptc` reuses the same `bash` definition for its nested tool.
Profiles that did not expose `bash` do not gain it.

Tool service and model configuration does not read the legacy `ARENA_*`, `CODE_HARNESS_*`, `DASHSCOPE_*`, `ROUTIFY_*`, or `PEXELS_*` variables. Subprocess tools still inherit the normal process environment so builds and user programs can access their own environment variables; the runtime also injects workspace-path variables for command compatibility.

The settings file can contain plaintext service credentials. Restrict it to the current user:

```bash
chmod 600 ~/.pi/agent/settings.json
```

### Main model versus tool models

- `defaultProvider`, `defaultModel`, model selection CLI flags, thinking level, retry, and compaction are handled by Pi.
- `npmCommand` and the shell resolved from `shellPath` are consumed by execution capabilities. External HTTP clients use `retry.provider.maxRetries` and `retry.provider.maxRetryDelayMs`.
- `harnesses.tools.webSearch`, `generateImage`, and `generateSpeech` configure the corresponding external tool calls.
- `harnesses.tools.imageCaption` is optional. When the active Pi model cannot read images, `read_file` sends the image to this Pi-registered side model and returns its caption. The side model uses Pi's model registry and credentials; `provider` and `model` must resolve through the same Pi installation.

## Profiles

| Profile | Distinct behavior |
| --- | --- |
| `pi` | Pi's default prompt and tool names, with the bounded `bash` capability |
| `pi-ptc` | Pi's default prompt with only `run_code` model-visible; JavaScript can call nested `read`, `bash`, `edit`, and `write` |
| `scaling` | Six-component composition with the 18 survey presets and explicit configuration files |
| `self-compact` | Isolated Pi plus the bounded `bash`, SelfCompact-style context status, rubric, and the `compact_context` tool |
| `agent-arena` | General workspace agent tools, multimodal file reading, search, image and speech generation, and interactive `ask_user` |
| `code-arena-html` | Single-file HTML tools with a smaller edit/search/media tool set |
| `code-arena-react` | React/Vite file tools, package installation, build validation, research, media search, and image generation |
| `code-arena-full-stack` | Next.js/PostgreSQL tools, bash, managed build/start validation, research, media search, and image generation |
| `long-horizon-mea` | A supervisor session coordinating fresh Manager, Executor, and Auditor child Pi sessions through `pi-subagents` |
| `bash-only` | Pi's default prompt and runtime with only the bounded `bash` active |
| `bash-apply-patch` | `bash` plus the Codex-style `apply_patch` capability |
| `bash-str-replace-editor` | `bash` plus the DSH-style `str_replace_editor` capability |
| `bash-file-search` | Pi's built-in `read`, `edit`, `write`, and `grep`, the bounded `bash`, plus `glob` backed by Pi's native file finder |

### Tool-interface comparison

The profiles under `src/harnesses/tool-comparison/` form a controlled tool-interface matrix.
They all retain Pi's native prompt, model runtime, settings, sessions, and workspace behavior while
disabling external resource discovery. Their model-visible tool sets are:

| Experiment | Run with `--harness` | Active tools |
| --- | --- | --- |
| Bash only | `bash-only` | `bash` |
| Codex editing | `bash-apply-patch` | `bash`, `apply_patch` |
| Pi editing baseline | `pi` | `read`, `bash`, `edit`, `write` |
| Programmatic tool calling | `pi-ptc` | `run_code` (nests Pi's four default tools) |
| DSH editing | `bash-str-replace-editor` | `bash`, `str_replace_editor` |
| File search and editing | `bash-file-search` | `read`, `bash`, `edit`, `write`, `grep`, `glob` |

Pi calls its native glob-based search tool `find`; the final experiment exposes that same
implementation under the conventional `glob` name without changing its execution or result format.

### Programmatic tool calling / code mode

`createProgrammaticToolCallingCapability(cwd, options?)` (also exported as
`createCodeModeCapability`) registers one model-visible function tool:

```text
run_code(code, timeout_ms?, max_output_chars?)
```

The `pi-ptc` profile disables direct built-in-tool exposure and nests Pi's default `read`,
`bash`, `edit`, and `write` definitions under the JavaScript `tools` object.
Scripts emit selected results with `text()` or forward either an image block or a nested
tool result with `image()`. Each call runs in a fresh child Node process with an empty
environment, a memory limit, and Node's permission model denying direct filesystem,
child-process, and worker access. The runtime stops synchronous JavaScript loops and scripts
that make no progress, but it does not impose a default wall-clock deadline while a nested
tool or a bounded `setTimeout()` is active. Configure duration on the nested tool doing the
work (for example, `tools.bash({ command, timeout: 300 })`). Use top-level `timeout_ms` only
when the entire orchestration needs an additional independent hard deadline. When embedding
shell parameter expansion in a JavaScript template literal, escape its dollar sign (for
example, `\${name}`). No runtime dependency or copied Codex source is added.

Pi's public extension API can enumerate another extension's tool metadata, but it does not
provide an execution handle for those tools. Consequently, this capability cannot safely
auto-capture arbitrary peer-extension tools. A future profile that needs custom nested tools
must pass their `ToolDefinition` objects explicitly through `options.nestedTools` (and,
when cwd-bound, `options.resolveNestedTools`). The current `pi-ptc` profile needs no such bridge
because its nested set consists of Pi's four public default tool definitions.

### Reusable editing capabilities

Two standalone editing capabilities are available for profile composition. The comparison profiles
activate them independently so their effects can be evaluated without changing another profile:

- `createApplyPatchCapability(cwd)` registers `apply_patch`, which accepts a Codex patch envelope
  in `{ "patch": "*** Begin Patch\n...\n*** End Patch" }` and supports add, update, delete,
  and move hunks.
- `createStrReplaceEditorCapability(cwd, options?)` registers DSH-style
  `str_replace_editor` with `view`, `create`, `str_replace`, and `insert` commands. Its public
  paths are absolute and confined to `cwd`.

Both factories return the normal `HarnessCapability` contract, so another profile can pass them to
`runComposedHarness` or merge them with `composeHarnessCapabilities` without copying their tools.

### SelfCompact context compaction

The `self-compact` harness loads the reusable capability implemented under
`context-management/self-compact`, inspired by
[Self-Compacting Language Model Agents](https://arxiv.org/abs/2606.23525).
Before every model call, the capability injects an ephemeral `<context_status>` block with
estimated tokens, context-window size, used percentage, and remaining tokens. It registers
one model tool:

```text
compact_context(reason, preserve?)
```

Before calling the tool, the model applies the paper-inspired rubric: the current work unit
must be closed, the continuation state must be safely summarizable, concrete progress must
exist since the last compaction, and the agent must not be stuck. Token pressure alone is
not enough. The tool finishes its own tool turn,
runs Pi's native compactor, and automatically starts a continuation turn from the compacted
state. The capability cancels only threshold-triggered automatic compaction. Pi's overflow
recovery and user-initiated `/compact` remain enabled. Keep Pi's native
`compaction.enabled` setting set to `true`; the capability suppresses the threshold through
the compaction lifecycle hook rather than disabling Pi's safety path.

### Long-horizon orchestration

The `long-horizon-mea` profile activates a reusable orchestration capability. The capability
gives the parent session `ask_user` and the explicitly loaded `pi-subagents` tools, then
runs three namespaced package-owned agents in order:

```text
long-horizon.manager → long-horizon.executor → long-horizon.auditor
```

Each role starts with fresh context. Manager has no workspace tools. Executor receives
Pi's built-in `read`, `edit`, `write`, `grep`, `find`, and `ls` plus the bounded `bash`;
Auditor receives the built-in read-only tools plus the same `bash`. Their packaged child
runtime applies the shared capability; no role-specific child
tool extension is loaded. The parent repeats the cycle until an Auditor independently reports
complete, clean, contract-aligned evidence.

Role definitions ship under `.pi/agents/long-horizon/`. At startup, the capability resolves
that catalog relative to the installed `@qwen-code/qwen-harness` package, independently of the
task workspace. Future harnesses can add their own subdirectory and unique `package`
namespace under `.pi/agents/`. The Long Horizon Supervisor also registers an
`allowedAgents` capability ceiling, so it cannot launch roles belonging to another harness
even though Pi discovers the shared packaged agent catalog. Parent and child sessions
remain separate so Harbor can capture them as related trajectories instead of flattening
distinct tool contracts into one conversation.

The source tree keeps every atomic capability under one `capabilities/` boundary,
grouped by how it participates in the harness:

```text
.pi/
  agents/
    long-horizon/   namespaced Manager, Executor, and Auditor definitions
src/
  capabilities/
    types.ts          common contract for composable harness capabilities
    settings.ts       loads Pi-owned settings and composes capability-owned settings
    global/
      session_affinity.ts  capability enabled for every harness
    orchestration/
      mea/            prompt, Supervisor lifecycle, round tracking, and role contract
    context-management/
      self-compact/   model-visible status, compaction rubric, and continuation lifecycle
    tools/
      settings.ts     composes tool-owned settings
      ask-user/       Pi tool adapter for the question workflow
      context-management/  model-visible context management tools
      execution/      tools, the bash capability, and their local settings parser
      filesystem/     model-visible workspace file tools
      media/          media tools and their local settings parser
      programmatic-tool-calling/  run_code adapter and isolated JavaScript child runtime
      web/            web tools and their local settings parser
  utils/
    capability_settings.ts  composes settings consumed by reusable utilities
    ask-user/         interactive question workflow, independent of tool schemas
    filesystem/       document extraction and its settings parser
    image-caption/    side-model perception and its settings parser
    settings.ts       shared parsing primitives
    workspace.ts      workspace confinement and common result formatting
    clients/
      settings.ts     composes external-client settings
      media/          DashScope and Pexels clients plus their settings parser
      retry.ts        provider-style HTTP retry shared by external clients
      web/            Routify clients and settings parser
  runtime/
    harness-capabilities.ts  merges peer capability contributions
    harness-main.ts          starts isolated and composed harnesses
  harnesses/          thin profile composition and Pi startup
  entrypoint.ts       selects and starts one harness
```

Capability directories follow seven harness dimensions by primary responsibility:

- **E — Execution environment:** runtimes, sandboxes, microVMs, browser or computer-use environments, and OS permission boundaries.
- **T — Tool interface and protocol:** tool description, discovery, selection, invocation protocols, tool-augmented training, and session interfaces. The current `tools/` directory belongs here.
- **C — Context and memory management:** short-term context, session state, persistent memory, long-horizon context, and context-drift mitigation.
- **L — Lifecycle and orchestration:** agent loops, multi-agent control flow, state transitions, and end-to-end task pipelines. The current `orchestration/` directory belongs here.
- **O — Observability and operations:** traces, costs, failures, reliability signals, and operational control planes.
- **V — Verification and evaluation:** benchmarks, controlled execution, judgement, failure attribution, regression feedback, and deployment-time evaluation.
- **G — Governance and security:** permissions, lifecycle hooks, component hardening, constitutions, audit, and organizational policy.

New capabilities should live under the dimension that owns their primary behavior.
Reusable implementation belongs under `utils/`, and provider-specific network access
belongs under `utils/clients/`, instead of being presented as independently activatable
capabilities. Dimension directories are added when they gain a concrete capability rather
than being created empty in advance.

`capabilities/tools/` contains the Pi-specific exposure layer: tool names, TypeBox
parameter schemas, descriptions, and result contracts. `utils/clients/` owns
vendor-specific transport and retry behavior. The rest of `utils/` contains reusable
implementations that are not independently exposed to the model. For example, the
`ask_user` tool delegates to the reusable interactive-question workflow, while
`read_file` composes document extraction, image captioning, and workspace confinement.
Plain-text reads and filesystem search delegate their result limits, truncation, and
continuation notices to Pi instead of defining harness-specific caps.
Each capability-owned settings parser lives beside that capability; the root
`capabilities/settings.ts` only loads Pi settings and composes the three category-level
settings objects. Adding a capability changes its local parser and category composition,
not the root loader.

Dependencies point inward: harnesses select `capabilities/tools`, tools may compose
`utils` and `utils/clients`, and those lower layers do not import tool adapters. Both
`fetch_page` and `web_fetch` use Routify; `fetch_page` adds its own 8,000-character
chunking and cache.

Harness capabilities are peer contributions. They may append system-prompt sections,
declare tools and extension paths, register inline extensions, and prepare packaged
resources. A harness may still provide one base system prompt; normal capability prompts
append after it, and orchestration prompts append last. Long Horizon uses this final phase
so an existing harness prompt remains available as task and domain requirements while the
Supervisor protocol controls how those requirements are delegated. The standalone
`long-horizon-mea` harness is only a thin preset around `createLongHorizonCapability()`; another
harness can compose that capability with its own peer capabilities without copying the
Manager, Executor, Auditor, prompt, or runtime setup.

## Sessions and resume

Sessions use Pi's native storage under `~/.pi/agent/sessions/`, organized by working directory. Pi writes its append-only JSONL containing messages, tool calls/results, usage, model changes, and compaction entries.

```bash
npm run agent-arena -- --resume
npm run code-arena-react -- --continue
npm run code-arena-html -- --session /absolute/path/to/session.jsonl
npm run long-horizon-mea -- --resume
```

Headless modes use the same session behavior:

```bash
npm run agent-arena -- -p "First turn"
npm run agent-arena -- --continue -p "Continue"
npm run code-arena-full-stack -- --mode json "Build the application"
```

## Validate

```bash
npm run check
npm test
```
