PHP Harness: Unified Orchestration for AI Coding Agents (Claude, Codex, Copilot, OpenCode)

This article introduces Tinywan/harness, a PHP 8.4+ library that provides a unified headless interface to orchestrate four major AI coding CLIs—Claude Code, OpenAI Codex, GitHub Copilot, and OpenCode—standardizing their disparate command parameters, output formats, rule files, and token billing for seamless integration into CI/CD pipelines, background jobs, and internal platforms.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
PHP Harness: Unified Orchestration for AI Coding Agents (Claude, Codex, Copilot, OpenCode)

Problem: Fragmented AI Coding CLIs

By 2026, AI coding tools have moved from autocomplete to autonomous agents. Anthropic's Claude Code , OpenAI's Codex CLI , GitHub's Copilot CLI , and the open-source OpenCode can each analyze code, run commands, read/write files, execute tests, and even complete a full PR workflow from a terminal. However, integrating them into automated backend systems (CI/CD pipelines, job queues, internal platforms, Docker sandboxes) is painful because each CLI differs in:

Launch parameters – e.g.,

claude -p --output-format stream-json --permission-mode bypassPermissions "prompt"

vs codex exec --json --sandbox danger-full-access -- "prompt" vs

copilot -p --output-format json --autopilot --allow-all "prompt"

vs opencode run --format json --auto "prompt".

Rule/instruction files – Claude reads CLAUDE.md, Codex and OpenCode read AGENTS.md, Copilot reads .github/copilot-instructions.md.

Skills directories – .claude/skills/, skills/, .github/skills/, .opencode/skill/.

Output formats – each emits a different JSONL structure with distinct field names, nesting, and event types.

Token billing – Claude returns output tokens + total USD cost; Codex returns tokens but no cost; Copilot returns nano-AIU credits requiring manual conversion.

Manually adapting to each CLI is impractical.

Solution: Tinywan/harness

Harness is a PHP 8.4+ library designed as an AI programming agent orchestration engine . Its core capability is driving the four major AI CLIs in headless mode through a single unified API. In one sentence: your PHP backend can drive any AI agent like a normal method call.

Core Features

1. Unified Interface, One-Line Backend Switch

Regardless of the underlying CLI (Claude, Codex, Copilot, OpenCode), the PHP code remains identical. Example:

use Harness\Harness;
use Harness\Job;
use Harness\Runner;
use Harness\Event;

// Select backend: 'claude', 'codex', 'copilot', or 'opencode'
$backend = Harness::byName('codex');

// Define task
$job = new Job([
    'workspace' => '/path/to/project',
    'srcDir' => '.',
    'prompt' => 'Implement a CSV parser function with full unit tests.',
    'model' => 'deepseek-v4-pro',
    'maxTurns' => 20,
]);

// Run and receive real-time events
Runner::run($backend, $job, function (Event $event): void {
    echo $event->format() . "
";
});

Switching to Claude Code only requires changing 'codex' to 'claude'; the rest of the code stays untouched.

2. Standardized Streaming Events

Harness parses each CLI's raw stdout into clean domain event objects in real time:

Thinking – AI's chain-of-thought / deep reasoning.

Tool – Bash commands, file reads/writes, code searches.

Text – Model's regular text replies.

Result – Final settlement: total cost, turns, token breakdown.

Session – Session ID (usable for checkpoint recovery).

RateLimit – Throttling status and reset time.

Error – Error details.

Frontends can consume these standard events to build live thinking animations, command execution progress, and cost panels.

3. Precise Token Cost Accounting

Built-in price dictionaries for Anthropic, OpenAI, and Copilot models automatically convert:

Token counts → USD cost.

Copilot nano-AIU credits → USD cost.

Enterprises can accurately allocate per-invocation costs for departmental chargebacks or customer billing.

4. Agent Skills Specification Support

Following the Agent Skills Specification , developers write a single SKILL.md file. Harness parses its YAML metadata, validates parameter constraints, and stages the skill into the correct discovery directory for the target CLI:

$skill = SkillParser::parse('/path/to/security-audit/SKILL.md');
SkillDelivery::stage($backend, $job, $skill);

5. Checkpoint Recovery & Security Sandbox

Checkpoint recovery – Every run captures a Session ID. Subsequent jobs can resume from the interruption point by providing resumeSessionID and a resumePrompt.

Security sandbox – One-call egress allowlist writing prevents agents from sending network requests to unauthorized domains:

use Harness\Egress\Sandbox;
Sandbox::writeSandboxSettings($workspace, $backend->getEgressHosts());

6. Intelligent Error Detection

Harness automatically identifies provider-specific errors:

429 rate limits → extracts exact reset timestamp.

Quota exhaustion → marks as non-recoverable.

Account permission failures → throws AccountError exception.

Upstream schedulers can decide whether to wait-and-retry or failover to another backend.

Real-World Run Example

In the author's local dnmp-php84 Docker container, running php examples/run_codex.php produced the following fully unattended flow:

Running Codex CLI via Harness ...
[session] 01a0626c-a72b-7820-99e9-8da96b506775
I'll first examine the workspace structure and language, then decide how to implement and write tests.
[command] Get-ChildItem -Force | Select-Object Mode, Length, Name
[command] python --version
Workspace is empty, no language specified. I'll implement in Python 3...
[file_change] csv_parser.py, test_csv_parser.py
[command] python -m unittest -v
Completed, added two files:
- csv_parser.py: supports quotes, escapes, embedded newlines, UTF-8 BOM, custom delimiters
- test_csv_parser.py: 12 test cases all passed (Ran 12 tests in 0.117s OK)
[result] cost=$0.0000 turns=1

From prompt to autonomous environment analysis, code writing, test creation, test execution, and result return – zero human intervention.

Typical Enterprise Use Cases

CI/CD Automated Code Review – PR submit → Webhook → PHP Worker → Harness drives Claude Code → AI reviews code → outputs JSON report → auto-comments on PR.

Automated Bug-Fix Agent – User ticket → background worker spins Docker sandbox → Harness drives Codex → AI analyzes, locates defect, modifies code, runs tests, passes → auto-submits PR.

Multi-Model Evaluation (Arena) – Same task set → Harness concurrently schedules all four backends → compare code quality, pass rate, latency, token cost → generate benchmark report.

Enterprise AI Programming Platform – In Laravel/Webman/Symfony, wrap AI coding as internal API: Frontend → AI request → Backend API → Harness schedules → WebSocket pushes event stream → Frontend shows thinking, commands, final result.

Engineering Practices

The project itself demonstrates modern PHP engineering:

Runtime : PHP 8.4 (strict types, constructor property promotion, enums).

Testing : Pest 3.0 (40 tests, 168 assertions, 100% pass).

Formatting & Static Analysis : Mago (Rust-based high-performance PHP toolchain).

CI/CD : GitHub Actions (Pest auto-test + Mago quality gate).

Local Development : Docker container dnmp-php84.

Package Management : Composer, PSR-4 autoloading.

Installation & Project Structure

Requires PHP ≥ 8.4 + Composer: composer require tinywan/harness Open-source repository: https://github.com/Tinywan/harness Key directories: src/Backends/ – Four CLI adapters ( ClaudeHarness.php, CodexHarness.php, CopilotHarness.php, OpencodeHarness.php). src/Skills/ – Agent Skills parsing and delivery ( Skill.php, SkillParser.php, SkillDelivery.php, SkillFilter.php, SkillWalker.php). src/Egress/Sandbox.php – Security sandbox configuration. src/Exceptions/AccountError.php – Account error exception. src/Harness.php – Unified facade. src/HarnessInterface.php – Backend contract interface. src/Runner.php – Subprocess driver. src/Job.php – Task entity. src/Event.php – Streaming event model. src/EventKind.php – Event type enum. src/Pricing.php – Token pricing and cost calculation. src/Usage.php – Token consumption metering. tests/ – Pest 3.0 unit tests. examples/ – Four runnable example scripts. mago.toml – Mago formatting and linting config. composer.json – Package definition. .github/workflows/ci.yml – GitHub Actions CI pipeline.

Closing Thoughts

In the AI Agent era, conversational coding is just the starting point. True productivity gains come from embedding AI programming agents into your existing engineering systems – your CI/CD, your task queues, your internal platforms. Harness aims to be the bridge that lets PHP developers integrate AI coding agent capabilities into their systems at minimal cost.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

CI/CDAI agentsPHPGitHub CopilotorchestrationOpenAI CodexClaude CodeOpenCode
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.