Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat: playground, CLI fingerprints, ACP support (#234, #223, #235)

diegosouzapwac89069671d3
diff --git a/open-sse/config/cliFingerprints.ts b/open-sse/config/cliFingerprints.ts
new file mode 100644
index 0000000000..3f34399ffd
--- /dev/null
+++ b/open-sse/config/cliFingerprints.ts
@@ -0,0 +1,238 @@
+/**
+ * CLI Fingerprint Definitions
+ *
+ * Defines per-provider "fingerprints" that control the exact ordering of HTTP headers
+ * and JSON body fields to match the native CLI tools exactly.
+ *
+ * When `cliCompatMode` is enabled for a provider, OmniRoute reorders outgoing requests
+ * to be indistinguishable from the real CLI binary, reducing account flagging risk.
+ *
+ * Header order and body field order were captured via mitmproxy traffic analysis.
+ */
+
+export interface CliFingerprint {
+ /** Ordered list of header names (case-sensitive). Unlisted headers are appended. */
+ headerOrder: string[];
+ /** Ordered list of top-level JSON body fields. Unlisted fields are appended. */
+ bodyFieldOrder: string[];
+ /** User-Agent string to inject (overrides default) */
+ userAgent?: string;
+ /** Extra headers to add */
+ extraHeaders?: Record<string, string>;
+}
+
+/**
+ * Fingerprint registry - keyed by provider alias (lowercase).
+ * Based on mitmproxy traffic captures from native CLI tools.
+ */
+export const CLI_FINGERPRINTS: Record<string, CliFingerprint> = {
+ codex: {
+ headerOrder: [
+ "Host",
+ "Content-Type",
+ "Authorization",
+ "Accept",
+ "User-Agent",
+ "Accept-Encoding",
+ ],
+ bodyFieldOrder: [
+ "model",
+ "messages",
+ "temperature",
+ "top_p",
+ "max_tokens",
+ "stream",
+ "tools",
+ "tool_choice",
+ "response_format",
+ "n",
+ "stop",
+ ],
+ userAgent: "codex-cli",
+ },
+ claude: {
+ headerOrder: [
+ "Host",
+ "Content-Type",
+ "x-api-key",
+ "anthropic-version",
+ "Accept",
+ "User-Agent",
+ "Accept-Encoding",
+ ],
+ bodyFieldOrder: [
+ "model",
+ "max_tokens",
+ "messages",
+ "system",
+ "temperature",
+ "top_p",
+ "top_k",
+ "stream",
+ "tools",
+ "tool_choice",
+ "metadata",
+ ],
+ userAgent: "claude-code",
+ },
+ github: {
+ headerOrder: [
+ "Host",
+ "Authorization",
+ "X-Request-Id",
+ "Vscode-Sessionid",
+ "Vscode-Machineid",
+ "Editor-Version",
+ "Editor-Plugin-Version",
+ "Copilot-Integration-Id",
+ "Openai-Organization",
+ "Openai-Intent",
+ "Content-Type",
+ "User-Agent",
+ "Accept",
+ "Accept-Encoding",
+ ],
+ bodyFieldOrder: [
+ "messages",
+ "model",
+ "temperature",
+ "top_p",
+ "max_tokens",
+ "n",
+ "stream",
+ "intent",
+ "intent_threshold",
+ "intent_content",
+ ],
+ userAgent: "GitHubCopilotChat",
+ },
+ antigravity: {
+ headerOrder: [
+ "Host",
+ "Content-Type",
+ "Authorization",
+ "User-Agent",
+ "Accept",
+ "Accept-Encoding",
+ ],
+ bodyFieldOrder: ["project", "model", "userAgent", "requestType", "requestId", "request"],
+ userAgent: "antigravity",
+ },
+};
+
+/**
+ * Reorder an object's keys according to a specified order.
+ * Keys not in the order list are appended at the end in their original order.
+ */
+export function orderFields<T extends Record<string, unknown>>(obj: T, fieldOrder: string[]): T {
+ if (!fieldOrder?.length || !obj || typeof obj !== "object") return obj;
+
+ const result: Record<string, unknown> = {};
+ const remaining = new Set(Object.keys(obj));
+
+ // First, add fields in the specified order
+ for (const key of fieldOrder) {
+ if (key in obj) {
+ result[key] = obj[key];
+ remaining.delete(key);
+ }
+ }
+
+ // Then append remaining fields in original order
+ for (const key of remaining) {
+ result[key] = obj[key];
+ }
+
+ return result as T;
+}
+
+/**
+ * Reorder HTTP headers according to a fingerprint.
+ * Returns a new object with headers in the specified order.
+ */
+export function orderHeaders(
+ headers: Record<string, string>,
+ headerOrder: string[]
+): Record<string, string> {
+ if (!headerOrder?.length || !headers) return headers;
+
+ const result: Record<string, string> = {};
+ const remaining = new Map<string, string>();
+
+ // Build case-insensitive lookup
+ const headerMap = new Map<string, [string, string]>();
+ for (const [key, value] of Object.entries(headers)) {
+ headerMap.set(key.toLowerCase(), [key, value]);
+ }
+
+ // Add ordered headers first
+ for (const orderedKey of headerOrder) {
+ const entry = headerMap.get(orderedKey.toLowerCase());
+ if (entry) {
+ result[entry[0]] = entry[1];
+ headerMap.delete(orderedKey.toLowerCase());
+ }
+ }
+
+ // Add remaining headers
+ for (const [, [key, value]] of headerMap) {
+ result[key] = value;
+ }
+
+ return result;
+}
+
+/**
+ * Apply a CLI fingerprint to headers and body.
+ * Returns { headers, bodyString } with the correct ordering.
+ */
+export function applyFingerprint(
+ provider: string,
+ headers: Record<string, string>,
+ body: unknown
+): { headers: Record<string, string>; bodyString: string } {
+ const fingerprint = CLI_FINGERPRINTS[provider?.toLowerCase()];
+
+ if (!fingerprint) {
+ return { headers, bodyString: JSON.stringify(body) };
+ }
+
+ // Apply user agent override
+ if (fingerprint.userAgent) {
+ headers["User-Agent"] = fingerprint.userAgent;
+ }
+
+ // Apply extra headers
+ if (fingerprint.extraHeaders) {
+ Object.assign(headers, fingerprint.extraHeaders);
+ }
+
+ // Reorder headers
+ const orderedHeaders = orderHeaders(headers, fingerprint.headerOrder);
+
+ // Reorder body fields
+ const orderedBody =
+ body && typeof body === "object" && !Array.isArray(body)
+ ? orderFields(body as Record<string, unknown>, fingerprint.bodyFieldOrder)
+ : body;
+
+ return {
+ headers: orderedHeaders,
+ bodyString: JSON.stringify(orderedBody),
+ };
+}
+
+/**
+ * Check if CLI compatibility mode is enabled for a provider.
+ * This reads from the settings database or environment variable.
+ */
+export function isCliCompatEnabled(provider: string): boolean {
+ // Check environment variable first: CLI_COMPAT_<PROVIDER>=1
+ const envKey = `CLI_COMPAT_${provider?.toUpperCase().replace(/[^A-Z0-9]/g, "_")}`;
+ if (process.env[envKey] === "1" || process.env[envKey] === "true") return true;
+
+ // Global enable: CLI_COMPAT_ALL=1
+ if (process.env.CLI_COMPAT_ALL === "1" || process.env.CLI_COMPAT_ALL === "true") return true;
+
+ return false;
+}
diff --git a/open-sse/executors/base.ts b/open-sse/executors/base.ts
index 00a3e9260d..83e1f95f60 100644
--- a/open-sse/executors/base.ts
+++ b/open-sse/executors/base.ts
@@ -1,4 +1,5 @@
import { HTTP_STATUS, FETCH_TIMEOUT_MS } from "../config/constants.ts";
+import { applyFingerprint, isCliCompatEnabled } from "../config/cliFingerprints.ts";
type JsonRecord = Record<string, unknown>;
@@ -192,10 +193,20 @@ export class BaseExecutor {
? mergeAbortSignals(signal, timeoutSignal)
: signal || timeoutSignal;
+ // Apply CLI fingerprint ordering if enabled for this provider
+ let finalHeaders = headers;
+ let bodyString = JSON.stringify(transformedBody);
+
+ if (isCliCompatEnabled(this.provider)) {
+ const fingerprinted = applyFingerprint(this.provider, headers, transformedBody);
+ finalHeaders = fingerprinted.headers;
+ bodyString = fingerprinted.bodyString;
+ }
+
const fetchOptions: RequestInit = {
method: "POST",
- headers,
- body: JSON.stringify(transformedBody),
+ headers: finalHeaders,
+ body: bodyString,
};
if (combinedSignal) fetchOptions.signal = combinedSignal;
diff --git a/package-lock.json b/package-lock.json
index 1433310cd3..c12779e1cb 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "omniroute",
- "version": "2.0.7",
+ "version": "2.0.8",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "omniroute",
- "version": "2.0.7",
+ "version": "2.0.8",
"hasInstallScript": true,
"license": "MIT",
"workspaces": [
diff --git a/src/app/(dashboard)/dashboard/playground/page.tsx b/src/app/(dashboard)/dashboard/playground/page.tsx
new file mode 100644
index 0000000000..a8cee7aa5f
--- /dev/null
+++ b/src/app/(dashboard)/dashboard/playground/page.tsx
@@ -0,0 +1,400 @@
+"use client";
+
+import { useState, useEffect, useCallback, useRef } from "react";
+import { Card, Button, Select, Badge } from "@/shared/components";
+import dynamic from "next/dynamic";
+
+const Editor = dynamic(() => import("@monaco-editor/react"), { ssr: false });
+
+interface ModelInfo {
+ id: string;
+ object: string;
+ owned_by: string;
+}
+
+interface ProviderOption {
+ value: string;
+ label: string;
+}
+
+const ENDPOINT_OPTIONS = [
+ { value: "chat", label: "Chat Completions" },
+ { value: "responses", label: "Responses" },
+ { value: "images", label: "Image Generation" },
+ { value: "embeddings", label: "Embeddings" },
+];
+
+const DEFAULT_BODIES: Record<string, object> = {
+ chat: {
+ model: "",
+ messages: [{ role: "user", content: "Hello! Say hi in one sentence." }],
+ max_tokens: 100,
+ stream: false,
+ },
+ responses: {
+ model: "",
+ input: "Hello! Say hi in one sentence.",
+ stream: false,
+ },
+ images: {
+ model: "",
+ prompt: "A beautiful sunset over mountains",
+ n: 1,
+ size: "1024x1024",
+ },
+ embeddings: {
+ model: "",
+ input: "Hello world",
+ encoding_format: "float",
+ },
+};
+
+const ENDPOINT_PATHS: Record<string, string> = {
+ chat: "/v1/chat/completions",
+ responses: "/v1/responses",
+ images: "/v1/images/generations",
+ embeddings: "/v1/embeddings",
+};
+
+export default function PlaygroundPage() {
+ const [models, setModels] = useState<ModelInfo[]>([]);
+ const [providers, setProviders] = useState<ProviderOption[]>([]);
+ const [selectedProvider, setSelectedProvider] = useState("");
+ const [selectedModel, setSelectedModel] = useState("");
+ const [selectedEndpoint, setSelectedEndpoint] = useState("chat");
+ const [requestBody, setRequestBody] = useState("");
+ const [responseBody, setResponseBody] = useState("");
+ const [loading, setLoading] = useState(false);
+ const [responseStatus, setResponseStatus] = useState<number | null>(null);
+ const [responseDuration, setResponseDuration] = useState<number | null>(null);
+ const abortRef = useRef<AbortController | null>(null);
+
+ // Fetch models
+ useEffect(() => {
+ fetch("/v1/models")
+ .then((res) => res.json())
+ .then((data) => {
+ const modelList = (data?.data || []) as ModelInfo[];
+ setModels(modelList);
+
+ // Extract unique providers from model ids (provider/model format)
+ const providerSet = new Set<string>();
+ modelList.forEach((m) => {
+ const parts = m.id.split("/");
+ if (parts.length >= 2) providerSet.add(parts[0]);
+ });
+ const providerOpts = Array.from(providerSet)
+ .sort()
+ .map((p) => ({ value: p, label: p }));
+ setProviders(providerOpts);
+ if (providerOpts.length > 0) setSelectedProvider(providerOpts[0].value);
+ })
+ .catch(() => {});
+ }, []);
+
+ // Filter models by selected provider
+ const filteredModels = models
+ .filter((m) => !selectedProvider || m.id.startsWith(selectedProvider + "/"))
+ .map((m) => ({ value: m.id, label: m.id }));
+
+ // Helper to generate default body for a given endpoint and model
+ const generateDefaultBody = (endpoint: string, model: string) => {
+ const template = { ...DEFAULT_BODIES[endpoint] };
+ if ("model" in template) {
+ (template as any).model = model;
+ }
+ return JSON.stringify(template, null, 2);
+ };
+
+ // When provider changes, auto-select first model and reset body
+ const handleProviderChange = (newProvider: string) => {
+ setSelectedProvider(newProvider);
+ const providerModels = models
+ .filter((m) => !newProvider || m.id.startsWith(newProvider + "/"))
+ .map((m) => m.id);
+ const firstModel = providerModels[0] || "";
+ setSelectedModel(firstModel);
+ setRequestBody(generateDefaultBody(selectedEndpoint, firstModel));
+ setResponseBody("");
+ setResponseStatus(null);
+ setResponseDuration(null);
+ };
+
+ // When model changes, update body
+ const handleModelChange = (newModel: string) => {
+ setSelectedModel(newModel);
+ setRequestBody(generateDefaultBody(selectedEndpoint, newModel));
+ setResponseBody("");
+ setResponseStatus(null);
+ setResponseDuration(null);
+ };
+
+ // When endpoint changes, update body
+ const handleEndpointChange = (newEndpoint: string) => {
+ setSelectedEndpoint(newEndpoint);
+ setRequestBody(generateDefaultBody(newEndpoint, selectedModel));
+ setResponseBody("");
+ setResponseStatus(null);
+ setResponseDuration(null);
+ };
+
+ const handleSend = useCallback(async () => {
+ if (!requestBody.trim()) return;
+ setLoading(true);
+ setResponseBody("");
+ setResponseStatus(null);
+ setResponseDuration(null);
+
+ const controller = new AbortController();
+ abortRef.current = controller;
+ const startTime = Date.now();
+
+ try {
+ const parsed = JSON.parse(requestBody);
+ const path = ENDPOINT_PATHS[selectedEndpoint];
+ const res = await fetch(path, {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify(parsed),
+ signal: controller.signal,
+ });
+
+ setResponseStatus(res.status);
+ setResponseDuration(Date.now() - startTime);
+
+ const contentType = res.headers.get("content-type") || "";
+ if (contentType.includes("text/event-stream")) {
+ // Handle streaming
+ const reader = res.body?.getReader();
+ const decoder = new TextDecoder();
+ let accumulated = "";
+ if (reader) {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ accumulated += decoder.decode(value, { stream: true });
+ setResponseBody(accumulated);
+ }
+ }
+ } else {
+ const data = await res.json();
+ setResponseBody(JSON.stringify(data, null, 2));
+ }
+ } catch (err: any) {
+ if (err.name === "AbortError") {
+ setResponseBody(JSON.stringify({ cancelled: true }, null, 2));
+ } else {
+ setResponseBody(JSON.stringify({ error: err.message }, null, 2));
+ }
+ setResponseDuration(Date.now() - startTime);
+ }
+ setLoading(false);
+ }, [requestBody, selectedEndpoint]);
+
+ const handleCancel = () => {
+ if (abortRef.current) {
+ abortRef.current.abort();
+ }
+ };
+
+ const handleCopy = async (text: string) => {
+ try {
+ await navigator.clipboard.writeText(text);
+ } catch {
+ /* silent */
+ }
+ };
+
+ return (
+ <div className="space-y-5">
+ {/* Info Banner */}
+ <div className="flex items-start gap-3 px-4 py-3 rounded-lg bg-primary/5 border border-primary/10 text-sm text-text-muted">
+ <span className="material-symbols-outlined text-primary text-[20px] mt-0.5 shrink-0">
+ science
+ </span>
+ <div>
+ <p className="font-medium text-text-main mb-0.5">Model Playground</p>
+ <p>
+ Test any model directly from the dashboard. Pick a provider, model, and endpoint type,
+ then send a request to see the raw response.
+ </p>
+ </div>
+ </div>
+
+ {/* Controls */}
+ <Card>
+ <div className="p-4 flex flex-col sm:flex-row items-end gap-4">
+ {/* Provider */}
+ <div className="flex-1 w-full">
+ <label className="block text-xs font-medium text-text-muted mb-1.5 uppercase tracking-wider">
+ Provider
+ </label>
+ <Select
+ value={selectedProvider}
+ onChange={(e: any) => handleProviderChange(e.target.value)}
+ options={providers}
+ className="w-full"
+ />
+ </div>
+
+ {/* Model */}
+ <div className="flex-1 w-full">
+ <label className="block text-xs font-medium text-text-muted mb-1.5 uppercase tracking-wider">
+ Model
+ </label>
+ <Select
+ value={selectedModel}
+ onChange={(e: any) => handleModelChange(e.target.value)}
+ options={filteredModels}
+ className="w-full"
+ />
+ </div>
+
+ {/* Endpoint */}
+ <div className="flex-1 w-full">
+ <label className="block text-xs font-medium text-text-muted mb-1.5 uppercase tracking-wider">
+ Endpoint
+ </label>
+ <Select
+ value={selectedEndpoint}
+ onChange={(e: any) => handleEndpointChange(e.target.value)}
+ options={ENDPOINT_OPTIONS}
+ className="w-full"
+ />
+ </div>
+
+ {/* Send Button */}
+ <div className="shrink-0">
+ {loading ? (
+ <Button icon="stop" variant="secondary" onClick={handleCancel}>
+ Cancel
+ </Button>
+ ) : (
+ <Button
+ icon="send"
+ onClick={handleSend}
+ disabled={!requestBody.trim() || !selectedModel}
+ >
+ Send
+ </Button>
+ )}
+ </div>
+ </div>
+ </Card>
+
+ {/* Split Editor View */}
+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
+ {/* Request Panel */}
+ <Card>
+ <div className="p-4 space-y-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="material-symbols-outlined text-[18px] text-text-muted">
+ upload
+ </span>
+ <h3 className="text-sm font-semibold text-text-main">Request</h3>
+ <Badge variant="info" size="sm">
+ POST {ENDPOINT_PATHS[selectedEndpoint]}
+ </Badge>
+ </div>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => handleCopy(requestBody)}
+ className="p-1.5 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-text-main transition-colors"
+ title="Copy"
+ >
+ <span className="material-symbols-outlined text-[16px]">content_copy</span>
+ </button>
+ <button
+ onClick={() => {
+ const template = { ...DEFAULT_BODIES[selectedEndpoint] };
+ if ("model" in template) (template as any).model = selectedModel;
+ setRequestBody(JSON.stringify(template, null, 2));
+ }}
+ className="p-1.5 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-text-main transition-colors"
+ title="Reset to default"
+ >
+ <span className="material-symbols-outlined text-[16px]">restart_alt</span>
+ </button>
+ </div>
+ </div>
+ <div className="border border-border rounded-lg overflow-hidden">
+ <Editor
+ height="400px"
+ defaultLanguage="json"
+ value={requestBody}
+ onChange={(value: string | undefined) => setRequestBody(value || "")}
+ theme="vs-dark"
+ options={{
+ minimap: { enabled: false },
+ fontSize: 12,
+ lineNumbers: "on",
+ scrollBeyondLastLine: false,
+ wordWrap: "on",
+ automaticLayout: true,
+ formatOnPaste: true,
+ }}
+ />
+ </div>
+ </div>
+ </Card>
+
+ {/* Response Panel */}
+ <Card>
+ <div className="p-4 space-y-3">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="material-symbols-outlined text-[18px] text-text-muted">
+ download
+ </span>
+ <h3 className="text-sm font-semibold text-text-main">Response</h3>
+ {responseStatus !== null && (
+ <Badge
+ variant={responseStatus >= 200 && responseStatus < 300 ? "success" : "error"}
+ size="sm"
+ >
+ {responseStatus}
+ </Badge>
+ )}
+ {responseDuration !== null && (
+ <span className="text-xs text-text-muted">{responseDuration}ms</span>
+ )}
+ {loading && (
+ <span className="material-symbols-outlined text-[14px] text-primary animate-spin">
+ progress_activity
+ </span>
+ )}
+ </div>
+ <div className="flex items-center gap-1">
+ <button
+ onClick={() => handleCopy(responseBody)}
+ className="p-1.5 rounded hover:bg-black/5 dark:hover:bg-white/5 text-text-muted hover:text-text-main transition-colors"
+ title="Copy"
+ >
+ <span className="material-symbols-outlined text-[16px]">content_copy</span>
+ </button>
+ </div>
+ </div>
+ <div className="border border-border rounded-lg overflow-hidden">
+ <Editor
+ height="400px"
+ defaultLanguage="json"
+ value={responseBody}
+ theme="vs-dark"
+ options={{
+ minimap: { enabled: false },
+ fontSize: 12,
+ lineNumbers: "on",
+ scrollBeyondLastLine: false,
+ wordWrap: "on",
+ automaticLayout: true,
+ readOnly: true,
+ }}
+ />
+ </div>
+ </div>
+ </Card>
+ </div>
+ </div>
+ );
+}
diff --git a/src/app/api/acp/agents/route.ts b/src/app/api/acp/agents/route.ts
new file mode 100644
index 0000000000..61542ed749
--- /dev/null
+++ b/src/app/api/acp/agents/route.ts
@@ -0,0 +1,35 @@
+/**
+ * API Route: /api/acp/agents
+ *
+ * Returns the list of detected CLI agents and their availability status.
+ * Used by the dashboard to show ACP transport options.
+ */
+
+import { NextResponse } from "next/server";
+import { detectInstalledAgents } from "@/lib/acp";
+
+export const dynamic = "force-dynamic";
+
+export async function GET() {
+ try {
+ const agents = detectInstalledAgents();
+ return NextResponse.json({
+ agents: agents.map((a) => ({
+ id: a.id,
+ name: a.name,
+ binary: a.binary,
+ version: a.version,
+ installed: a.installed,
+ providerAlias: a.providerAlias,
+ protocol: a.protocol,
+ })),
+ available: agents.filter((a) => a.installed).length,
+ total: agents.length,
+ });
+ } catch (error: any) {
+ return NextResponse.json(
+ { error: error.message || "Failed to detect agents" },
+ { status: 500 }
+ );
+ }
+}
diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.json
index 413cda0f9b..96f1637a54 100644
--- a/src/i18n/messages/en.json
+++ b/src/i18n/messages/en.json
@@ -72,6 +72,7 @@
"media": "Media",
"settings": "Settings",
"translator": "Translator",
+ "playground": "Playground",
"docs": "Docs",
"issues": "Issues",
"endpoints": "Endpoints",
diff --git a/src/lib/acp/index.ts b/src/lib/acp/index.ts
new file mode 100644
index 0000000000..2bc28e3a51
--- /dev/null
+++ b/src/lib/acp/index.ts
@@ -0,0 +1,11 @@
+/**
+ * ACP Module — Public API
+ *
+ * Re-exports the registry and manager for convenient imports.
+ */
+
+export { detectInstalledAgents, getAgentById, getAvailableAgents } from "./registry";
+export type { CliAgentInfo } from "./registry";
+
+export { AcpManager, acpManager } from "./manager";
+export type { AcpSession } from "./manager";
diff --git a/src/lib/acp/manager.ts b/src/lib/acp/manager.ts
new file mode 100644
index 0000000000..1ebe1cffe6
--- /dev/null
+++ b/src/lib/acp/manager.ts
@@ -0,0 +1,197 @@
+/**
+ * ACP (Agent Client Protocol) — Process Spawner & Manager
+ *
+ * Spawns CLI agents as child processes and manages their lifecycle.
+ * Communication happens via stdin/stdout (JSON-RPC style) or piped HTTP.
+ *
+ * This module provides a "CLI-as-backend" transport: instead of intercepting
+ * HTTP API calls, OmniRoute spawns the CLI directly and feeds prompts through
+ * its native interface.
+ */
+
+import { spawn, ChildProcess } from "child_process";
+import { EventEmitter } from "events";
+
+export interface AcpSession {
+ /** Unique session ID */
+ id: string;
+ /** Agent ID (e.g., "codex", "claude") */
+ agentId: string;
+ /** Child process handle */
+ process: ChildProcess;
+ /** Whether the process is alive */
+ alive: boolean;
+ /** Accumulated stdout buffer */
+ stdoutBuffer: string;
+ /** Accumulated stderr buffer */
+ stderrBuffer: string;
+ /** Created timestamp */
+ createdAt: Date;
+}
+
+/**
+ * ACP Session Manager
+ *
+ * Manages the lifecycle of CLI agent processes.
+ * Each session represents one running CLI agent instance.
+ */
+export class AcpManager extends EventEmitter {
+ private sessions: Map<string, AcpSession> = new Map();
+
+ /**
+ * Spawn a new CLI agent process.
+ */
+ spawn(
+ agentId: string,
+ binary: string,
+ args: string[] = [],
+ env: Record<string, string> = {}
+ ): AcpSession {
+ const sessionId = `acp-${agentId}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+
+ const child = spawn(binary, args, {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: { ...process.env, ...env },
+ shell: false,
+ });
+
+ const session: AcpSession = {
+ id: sessionId,
+ agentId,
+ process: child,
+ alive: true,
+ stdoutBuffer: "",
+ stderrBuffer: "",
+ createdAt: new Date(),
+ };
+
+ child.stdout?.on("data", (chunk: Buffer) => {
+ session.stdoutBuffer += chunk.toString();
+ this.emit("stdout", { sessionId, data: chunk.toString() });
+ });
+
+ child.stderr?.on("data", (chunk: Buffer) => {
+ session.stderrBuffer += chunk.toString();
+ this.emit("stderr", { sessionId, data: chunk.toString() });
+ });
+
+ child.on("exit", (code, signal) => {
+ session.alive = false;
+ this.emit("exit", { sessionId, code, signal });
+ });
+
+ child.on("error", (err) => {
+ session.alive = false;
+ this.emit("error", { sessionId, error: err });
+ });
+
+ this.sessions.set(sessionId, session);
+ return session;
+ }
+
+ /**
+ * Send input to a running session's stdin.
+ */
+ sendInput(sessionId: string, input: string): boolean {
+ const session = this.sessions.get(sessionId);
+ if (!session?.alive || !session.process.stdin?.writable) return false;
+
+ session.process.stdin.write(input);
+ return true;
+ }
+
+ /**
+ * Send a prompt to a CLI agent and collect the response.
+ * This is a higher-level method that handles the send/receive cycle.
+ */
+ async sendPrompt(sessionId: string, prompt: string, timeoutMs: number = 120000): Promise<string> {
+ const session = this.sessions.get(sessionId);
+ if (!session?.alive) throw new Error(`Session ${sessionId} is not alive`);
+
+ // Clear buffer before sending
+ session.stdoutBuffer = "";
+
+ // Send prompt
+ this.sendInput(sessionId, prompt + "\n");
+
+ // Wait for response (collect until process goes idle or timeout)
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ reject(new Error(`ACP timeout after ${timeoutMs}ms`));
+ }, timeoutMs);
+
+ let idleTimer: ReturnType<typeof setTimeout>;
+
+ const onData = ({ sessionId: sid }: { sessionId: string }) => {
+ if (sid !== sessionId) return;
+ // Reset idle timer on new data
+ clearTimeout(idleTimer);
+ idleTimer = setTimeout(() => {
+ clearTimeout(timer);
+ this.removeListener("stdout", onData);
+ this.removeListener("exit", onExit);
+ resolve(session.stdoutBuffer);
+ }, 2000); // 2s idle = response complete
+ };
+
+ const onExit = ({ sessionId: sid }: { sessionId: string }) => {
+ if (sid !== sessionId) return;
+ clearTimeout(timer);
+ clearTimeout(idleTimer);
+ this.removeListener("stdout", onData);
+ this.removeListener("exit", onExit);
+ resolve(session.stdoutBuffer);
+ };
+
+ this.on("stdout", onData);
+ this.on("exit", onExit);
+ });
+ }
+
+ /**
+ * Kill a session and clean up.
+ */
+ kill(sessionId: string): boolean {
+ const session = this.sessions.get(sessionId);
+ if (!session) return false;
+
+ if (session.alive) {
+ session.process.kill("SIGTERM");
+ // Force kill after 5s
+ setTimeout(() => {
+ if (session.alive) {
+ session.process.kill("SIGKILL");
+ }
+ }, 5000);
+ }
+
+ this.sessions.delete(sessionId);
+ return true;
+ }
+
+ /**
+ * Get all active sessions.
+ */
+ getActiveSessions(): AcpSession[] {
+ return Array.from(this.sessions.values()).filter((s) => s.alive);
+ }
+
+ /**
+ * Get a specific session.
+ */
+ getSession(sessionId: string): AcpSession | undefined {
+ return this.sessions.get(sessionId);
+ }
+
+ /**
+ * Kill all sessions.
+ */
+ killAll(): void {
+ for (const [id] of this.sessions) {
+ this.kill(id);
+ }
+ }
+}
+
+// Singleton manager instance
+export const acpManager = new AcpManager();
diff --git a/src/lib/acp/registry.ts b/src/lib/acp/registry.ts
new file mode 100644
index 0000000000..b9efad0d14
--- /dev/null
+++ b/src/lib/acp/registry.ts
@@ -0,0 +1,126 @@
+/**
+ * ACP (Agent Client Protocol) — CLI Agent Registry
+ *
+ * Discovers installed CLI tools on the system by checking standard paths
+ * and running version commands. Used to offer ACP transport as an alternative
+ * to the HTTP proxy method.
+ *
+ * Reference: https://github.com/iOfficeAI/AionUi (auto-detects CLI agents)
+ */
+
+import { execSync } from "child_process";
+
+export interface CliAgentInfo {
+ /** Agent identifier (e.g., "codex", "claude", "goose") */
+ id: string;
+ /** Display name */
+ name: string;
+ /** Binary name to spawn */
+ binary: string;
+ /** Version detection command */
+ versionCommand: string;
+ /** Detected version (null if not installed) */
+ version: string | null;
+ /** Whether the agent is installed and available */
+ installed: boolean;
+ /** Provider ID that this agent maps to in OmniRoute */
+ providerAlias: string;
+ /** Arguments to pass when spawning for ACP */
+ spawnArgs: string[];
+ /** Protocol used for communication */
+ protocol: "stdio" | "http";
+}
+
+/**
+ * Registry of known CLI agents that support ACP or similar protocols.
+ */
+const AGENT_DEFINITIONS: Omit<CliAgentInfo, "version" | "installed">[] = [
+ {
+ id: "codex",
+ name: "OpenAI Codex CLI",
+ binary: "codex",
+ versionCommand: "codex --version",
+ providerAlias: "codex",
+ spawnArgs: ["--quiet"],
+ protocol: "stdio",
+ },
+ {
+ id: "claude",
+ name: "Claude Code CLI",
+ binary: "claude",
+ versionCommand: "claude --version",
+ providerAlias: "claude",
+ spawnArgs: ["--print", "--output-format", "json"],
+ protocol: "stdio",
+ },
+ {
+ id: "goose",
+ name: "Goose CLI",
+ binary: "goose",
+ versionCommand: "goose --version",
+ providerAlias: "goose",
+ spawnArgs: [],
+ protocol: "stdio",
+ },
+ {
+ id: "gemini-cli",
+ name: "Gemini CLI",
+ binary: "gemini",
+ versionCommand: "gemini --version",
+ providerAlias: "gemini-cli",
+ spawnArgs: [],
+ protocol: "stdio",
+ },
+ {
+ id: "openclaw",
+ name: "OpenClaw",
+ binary: "openclaw",
+ versionCommand: "openclaw --version",
+ providerAlias: "openclaw",
+ spawnArgs: [],
+ protocol: "stdio",
+ },
+];
+
+/**
+ * Detect installed CLI agents on the system.
+ * Runs version commands to verify availability.
+ */
+export function detectInstalledAgents(): CliAgentInfo[] {
+ return AGENT_DEFINITIONS.map((def) => {
+ let version: string | null = null;
+ let installed = false;
+
+ try {
+ const output = execSync(def.versionCommand, {
+ timeout: 5000,
+ encoding: "utf-8",
+ stdio: ["pipe", "pipe", "pipe"],
+ }).trim();
+
+ // Extract version number from output
+ const versionMatch = output.match(/(\d+\.\d+\.\d+(?:-\w+)?)/);
+ version = versionMatch ? versionMatch[1] : output.split("\n")[0];
+ installed = true;
+ } catch {
+ // Not installed or not runnable
+ }
+
+ return { ...def, version, installed };
+ });
+}
+
+/**
+ * Get a specific agent by ID.
+ */
+export function getAgentById(id: string): CliAgentInfo | undefined {
+ const agents = detectInstalledAgents();
+ return agents.find((a) => a.id === id);
+}
+
+/**
+ * Get agents that are installed and available for ACP.
+ */
+export function getAvailableAgents(): CliAgentInfo[] {
+ return detectInstalledAgents().filter((a) => a.installed);
+}
diff --git a/src/shared/components/Sidebar.tsx b/src/shared/components/Sidebar.tsx
index eb2f0b9399..8e6cf5582d 100644
--- a/src/shared/components/Sidebar.tsx
+++ b/src/shared/components/Sidebar.tsx
@@ -27,7 +27,10 @@ const navItemDefs = [
{ href: "/dashboard/media", i18nKey: "media", icon: "auto_awesome" },
];
-const debugItemDefs = [{ href: "/dashboard/translator", i18nKey: "translator", icon: "translate" }];
+const debugItemDefs = [
+ { href: "/dashboard/translator", i18nKey: "translator", icon: "translate" },
+ { href: "/dashboard/playground", i18nKey: "playground", icon: "science" },
+];
const systemItemDefs = [{ href: "/dashboard/settings", i18nKey: "settings", icon: "settings" }];