Skip to content

Instantly share code, notes, and snippets.

@xee999
Created February 21, 2026 21:06
Show Gist options
  • Select an option

  • Save xee999/25980d8c1c7cc9ef68431e9a0e094ad4 to your computer and use it in GitHub Desktop.

Select an option

Save xee999/25980d8c1c7cc9ef68431e9a0e094ad4 to your computer and use it in GitHub Desktop.
๐Ÿ›ธ Codex-AG Bridge: Optimized specialist integration for GPT-5.3

๐Ÿ›ธ Codex-AG Bridge: The Ultimate Hybrid Intelligence Layer

License: MIT AG Compatible GPT-5.3 Powered

Codex-AG Bridge is a high-performance orchestration layer that seamlessly integrates GPT-5.3 Codex into the Anti-Gravity (AG) ecosystem. It transforms AG from a general-purpose assistant into a specialized, token-efficient technical powerhouse.


โœจ Key Features

  • ๐Ÿš€ Silent-Protocol Execution: Fully automated background task management using Windows SYSTEM accounts. No more focus-stealing console popups.
  • ๐Ÿ›ก๏ธ Laconic Token Shield: A specialized "Pipe Mode" that reduces Gemini 1.5 Flash token utilization by up to 90% by offloading reasoning to GPT-5.3.
  • ๐Ÿง  Cross-Session Brain Sync: Automatically synchronizes project context via AGENTS.md and local SQLite vector memory.
  • โšก Turbo-All Authorization: Pre-configured workflows for zero-prompt command execution.
  • ๐Ÿ”— Native MCP Integration: Exposes the Codex CLI as a standard Model Context Protocol (MCP) tool.

๐Ÿ› ๏ธ Quick Start (Automated Installation)

1. Prerequisites

2. Install the Bridge

Clone this repository and run the setup script:

git clone https://github.com/xee999/Codex-AG-Bridge.git
cd Codex-AG-Bridge/scripts
./install_bridge.ps1

3. Configure OAuth & Environment

Create a .env file in the resources directory:

CODEX_API_KEY=your_key_here
CODEX_BROKER_PORT=8787
BRAIN_CONTEXT_ENABLED=true

๐Ÿ“– Usage

Once installed, simply use the /codex command in AG:

  • /codex "Analyze this codebase for performance bottlenecks"
  • /codex "Implement a robust OAuth2 flow in FastAPI"

The bridge will automatically:

  1. Inject your "Brain" context.
  2. Delegate the task to GPT-5.3.
  3. Return the raw high-performance code silently.

๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide and Code of Conduct.

๐Ÿท๏ธ Tags

#Codex #AntiGravity #GPT5 #AGI #DevTools #Automation #VectorDB #RAG #OpenSource

"use strict";
const express = require("express");
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawn } = require("child_process");
const PORT = parseInt(process.env.CODEX_BROKER_PORT || "8787", 10);
const HOST = process.env.CODEX_BROKER_HOST || "127.0.0.1";
const TIMEOUT_MS = parseInt(process.env.CODEX_BROKER_TIMEOUT_MS || "120000", 10);
const CODEX_CMD = process.env.CODEX_CMD || "codex";
const LOG_PATH = process.env.CODEX_BROKER_LOG || path.join(__dirname, "logs", "broker.log");
const MAX_INPUT_CHARS = parseInt(process.env.CODEX_BROKER_MAX_INPUT_CHARS || "16000", 10);
const MAX_OUTPUT_CHARS = parseInt(process.env.CODEX_BROKER_MAX_OUTPUT_CHARS || "12000", 10);
const MAX_QUEUE_DEPTH = parseInt(process.env.CODEX_BROKER_MAX_QUEUE_DEPTH || "50", 10);
const BRAIN_CONTEXT_ENABLED = process.env.BRAIN_CONTEXT_ENABLED !== "false";
const AGENTS_MD_PATH = process.env.AGENTS_MD_PATH ||
path.join(os.homedir(), ".codex", "AGENTS.md");
const MAX_BRAIN_CONTEXT_CHARS = parseInt(process.env.MAX_BRAIN_CONTEXT_CHARS || "3000", 10);
const app = express();
app.use(express.json({ limit: "1mb" }));
const queue = [];
let isRunning = false;
function nowIso() {
return new Date().toISOString();
}
function writeLog(entry) {
const line = `${nowIso()} ${JSON.stringify(entry)}\n`;
fs.appendFile(LOG_PATH, line, () => { });
}
let _cachedBrainContext = "";
let _brainContextLoadedAt = 0;
function loadBrainContext() {
const now = Date.now();
if (_cachedBrainContext && now - _brainContextLoadedAt < 60000) {
return _cachedBrainContext;
}
try {
const raw = fs.readFileSync(AGENTS_MD_PATH, "utf8");
_cachedBrainContext = raw.slice(0, MAX_BRAIN_CONTEXT_CHARS);
_brainContextLoadedAt = now;
} catch {
_cachedBrainContext = "";
}
return _cachedBrainContext;
}
function runCodex(question) {
return new Promise((resolve, reject) => {
const outputPath = path.join(
os.tmpdir(),
`codex-broker-${Date.now()}-${Math.floor(Math.random() * 1e9)}.txt`
);
const args = [
"exec",
"--skip-git-repo-check",
"--color",
"never",
"--output-last-message",
outputPath,
"-",
];
const child = spawn(CODEX_CMD, args, {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
shell: true,
});
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill();
reject(new Error(`codex timeout after ${TIMEOUT_MS}ms`));
}, TIMEOUT_MS);
child.stdout.on("data", (d) => {
stdout += d.toString();
});
child.stderr.on("data", (d) => {
stderr += d.toString();
});
child.on("error", (err) => {
clearTimeout(timer);
reject(err);
});
child.on("close", (code) => {
clearTimeout(timer);
let output = "";
try {
if (fs.existsSync(outputPath)) {
output = fs.readFileSync(outputPath, "utf8").trim();
fs.unlinkSync(outputPath);
}
} catch {
// ignore best-effort temp file cleanup
}
if (code === 0) {
const answer = (output || stdout || "").trim();
if (answer.length > MAX_OUTPUT_CHARS) {
resolve(answer.slice(0, MAX_OUTPUT_CHARS));
return;
}
resolve(answer);
return;
}
reject(new Error(`codex exited with code ${code}: ${stderr.trim()}`));
});
child.stdin.write(`${question}\n`);
child.stdin.end();
});
}
async function processQueue() {
if (isRunning || queue.length === 0) {
return;
}
isRunning = true;
const item = queue.shift();
try {
const answer = await runCodex(item.question);
writeLog({ requestId: item.id, question: item.question, answer, ok: true });
item.res.status(200).json({ answer });
} catch (err) {
const message = err && err.message ? err.message : String(err);
writeLog({ requestId: item.id, question: item.question, error: message, ok: false });
item.res.status(500).json({ error: message });
} finally {
isRunning = false;
setImmediate(processQueue);
}
}
app.get("/health", (_req, res) => {
res.status(200).json({
ok: true,
queueDepth: queue.length,
running: isRunning,
limits: {
maxInputChars: MAX_INPUT_CHARS,
maxOutputChars: MAX_OUTPUT_CHARS,
maxQueueDepth: MAX_QUEUE_DEPTH,
},
});
});
app.post("/ask", (req, res) => {
let question = req.body && typeof req.body.question === "string" ? req.body.question.trim() : "";
if (!question) {
res.status(400).json({ error: "question is required" });
return;
}
// Auto-inject brain context unless explicitly disabled
const skipBrain = req.body && req.body.brain_context === false;
if (BRAIN_CONTEXT_ENABLED && !skipBrain) {
const ctx = loadBrainContext();
if (ctx) {
question = `[AG Brain Context]\n${ctx}\n[End Context]\n\n${question}`;
}
}
if (question.length > MAX_INPUT_CHARS) {
res.status(413).json({
error: `question exceeds max input size (${question.length} > ${MAX_INPUT_CHARS})`,
});
return;
}
if (queue.length >= MAX_QUEUE_DEPTH) {
res.status(429).json({
error: `broker queue is full (${queue.length}/${MAX_QUEUE_DEPTH})`,
});
return;
}
const id = `${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
queue.push({ id, question, res });
processQueue();
});
// ---------------------------------------------------------------------------
// Brain Bridge endpoints (Anti-Gravity native brain integration)
// ---------------------------------------------------------------------------
const BRAIN_BRIDGE_PATH = process.env.BRAIN_BRIDGE_PATH ||
path.join("E:", "Codex", "Falooza", "brain_bridge.py");
const PYTHON_CMD = process.env.BRAIN_PYTHON_CMD ||
path.join("E:", "Miniconda3", "envs", "bidsrag311", "python.exe");
const BRAIN_TIMEOUT_MS = parseInt(process.env.BRAIN_TIMEOUT_MS || "30000", 10);
function runBrainBridge(args) {
return new Promise((resolve, reject) => {
const child = spawn(PYTHON_CMD, [BRAIN_BRIDGE_PATH, ...args], {
stdio: ["pipe", "pipe", "pipe"],
windowsHide: true,
});
let stdout = "";
let stderr = "";
const timer = setTimeout(() => {
child.kill();
reject(new Error(`brain_bridge timeout after ${BRAIN_TIMEOUT_MS}ms`));
}, BRAIN_TIMEOUT_MS);
child.stdout.on("data", (d) => { stdout += d.toString(); });
child.stderr.on("data", (d) => { stderr += d.toString(); });
child.on("error", (err) => { clearTimeout(timer); reject(err); });
child.on("close", (code) => {
clearTimeout(timer);
if (code === 0) {
try {
resolve(JSON.parse(stdout.trim()));
} catch {
resolve({ raw: stdout.trim() });
}
} else {
reject(new Error(`brain_bridge exited ${code}: ${stderr.trim()}`));
}
});
child.stdin.end();
});
}
// POST /brain/context โ€” Get session context from AG brain
app.post("/brain/context", async (req, res) => {
const task = (req.body && req.body.task) || "";
const topK = (req.body && req.body.top_k) || 5;
try {
const result = await runBrainBridge(["context", task, String(topK)]);
writeLog({ event: "brain_context", task, ok: true });
res.status(200).json(result);
} catch (err) {
writeLog({ event: "brain_context", task, error: err.message, ok: false });
res.status(500).json({ error: err.message });
}
});
// POST /brain/query โ€” Query AG brain for relevant memory
app.post("/brain/query", async (req, res) => {
const prompt = (req.body && req.body.prompt) || "";
const topK = (req.body && req.body.top_k) || 5;
if (!prompt.trim()) {
res.status(400).json({ error: "prompt is required" });
return;
}
try {
const result = await runBrainBridge(["query", prompt, String(topK)]);
writeLog({ event: "brain_query", prompt, ok: true });
res.status(200).json(result);
} catch (err) {
writeLog({ event: "brain_query", prompt, error: err.message, ok: false });
res.status(500).json({ error: err.message });
}
});
// POST /brain/capture โ€” Capture a knowledge entry
app.post("/brain/capture", async (req, res) => {
const title = (req.body && req.body.title) || "";
const content = (req.body && req.body.content) || "";
const category = (req.body && req.body.category) || "general";
if (!title.trim() || !content.trim()) {
res.status(400).json({ error: "title and content are required" });
return;
}
try {
const result = await runBrainBridge(["capture", title, content, category]);
writeLog({ event: "brain_capture", title, category, ok: true });
res.status(200).json(result);
} catch (err) {
writeLog({ event: "brain_capture", title, error: err.message, ok: false });
res.status(500).json({ error: err.message });
}
});
// GET /brain/digest โ€” Get brain stats overview
app.get("/brain/digest", async (_req, res) => {
try {
const result = await runBrainBridge(["digest"]);
res.status(200).json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// GET /brain/list โ€” List recent conversations
app.get("/brain/list", async (_req, res) => {
try {
const result = await runBrainBridge(["list"]);
res.status(200).json(result);
} catch (err) {
res.status(500).json({ error: err.message });
}
});
// ---------------------------------------------------------------------------
app.listen(PORT, HOST, () => {
writeLog({ event: "startup", host: HOST, port: PORT, timeoutMs: TIMEOUT_MS, cmd: CODEX_CMD });
// eslint-disable-next-line no-console
console.log(`codex-broker listening on http://${HOST}:${PORT}`);
});
"use strict";
/**
* MCP Server for Codex GPT-5.3 โ€” exposes Codex CLI as a tool for Anti-Gravity.
*
* Uses stdio transport (AG spawns this process) and JSON-RPC 2.0.
* Forwards requests to the Codex Broker HTTP API at 127.0.0.1:8787.
*/
const http = require("http");
const readline = require("readline");
const BROKER_HOST = process.env.CODEX_BROKER_HOST || "127.0.0.1";
const BROKER_PORT = parseInt(process.env.CODEX_BROKER_PORT || "8787", 10);
// ---------------------------------------------------------------------------
// JSON-RPC helpers
// ---------------------------------------------------------------------------
function jsonRpcResponse(id, result) {
return JSON.stringify({ jsonrpc: "2.0", id, result });
}
function jsonRpcError(id, code, message) {
return JSON.stringify({ jsonrpc: "2.0", id, error: { code, message } });
}
// ---------------------------------------------------------------------------
// HTTP helper to call broker
// ---------------------------------------------------------------------------
function brokerRequest(path, method, body) {
return new Promise((resolve, reject) => {
const payload = body ? JSON.stringify(body) : null;
const opts = {
hostname: BROKER_HOST,
port: BROKER_PORT,
path,
method,
headers: { "Content-Type": "application/json" },
};
const req = http.request(opts, (res) => {
let data = "";
res.on("data", (chunk) => { data += chunk; });
res.on("end", () => {
try {
resolve(JSON.parse(data));
} catch {
resolve({ raw: data });
}
});
});
req.on("error", (err) => reject(err));
if (payload) req.write(payload);
req.end();
});
}
// ---------------------------------------------------------------------------
// Tool definitions
// ---------------------------------------------------------------------------
const TOOLS = [
{
name: "codex_ask",
description:
"Send a question to GPT-5.3 Codex for code generation, analysis, or technical answers. " +
"The broker auto-injects AG brain context. Use for code-heavy tasks where Codex's " +
"code-tuned model excels.",
inputSchema: {
type: "object",
properties: {
question: {
type: "string",
description: "The question or instruction for Codex GPT-5.3",
},
brain_context: {
type: "boolean",
description: "Include AG brain context (default true). Set false for raw Codex calls.",
default: true,
},
},
required: ["question"],
},
},
{
name: "codex_brain_query",
description:
"Search Anti-Gravity brain memory for relevant artifacts by keyword.",
inputSchema: {
type: "object",
properties: {
prompt: {
type: "string",
description: "Search query for brain memory",
},
top_k: {
type: "number",
description: "Max results to return (default 5)",
default: 5,
},
},
required: ["prompt"],
},
},
{
name: "codex_brain_capture",
description:
"Capture a knowledge entry into AG brain for future cross-referencing.",
inputSchema: {
type: "object",
properties: {
title: { type: "string", description: "Title of the knowledge entry" },
content: { type: "string", description: "Content to capture" },
category: {
type: "string",
description: "Category (general, techniques, projects, skills, milestones)",
default: "general",
},
},
required: ["title", "content"],
},
},
{
name: "codex_brain_digest",
description: "Get a summary of the current AG brain state โ€” conversation count, artifacts, etc.",
inputSchema: {
type: "object",
properties: {},
},
},
];
// ---------------------------------------------------------------------------
// Request handling
// ---------------------------------------------------------------------------
async function handleToolCall(name, args) {
switch (name) {
case "codex_ask": {
const body = {
question: args.question || "",
brain_context: args.brain_context !== false,
};
const result = await brokerRequest("/ask", "POST", body);
return [{ type: "text", text: result.answer || result.error || JSON.stringify(result) }];
}
case "codex_brain_query": {
const body = { prompt: args.prompt || "", top_k: args.top_k || 5 };
const result = await brokerRequest("/brain/query", "POST", body);
return [{ type: "text", text: JSON.stringify(result, null, 2) }];
}
case "codex_brain_capture": {
const body = {
title: args.title || "",
content: args.content || "",
category: args.category || "general",
};
const result = await brokerRequest("/brain/capture", "POST", body);
return [{ type: "text", text: JSON.stringify(result, null, 2) }];
}
case "codex_brain_digest": {
const result = await brokerRequest("/brain/digest", "GET", null);
return [{ type: "text", text: JSON.stringify(result, null, 2) }];
}
default:
throw new Error(`Unknown tool: ${name}`);
}
}
async function handleRequest(msg) {
const { id, method, params } = msg;
switch (method) {
case "initialize":
return jsonRpcResponse(id, {
protocolVersion: "2024-11-05",
capabilities: { tools: {} },
serverInfo: {
name: "codex-mcp-server",
version: "1.0.0",
},
});
case "notifications/initialized":
// No response needed for notifications
return null;
case "tools/list":
return jsonRpcResponse(id, { tools: TOOLS });
case "tools/call": {
const toolName = params && params.name;
const toolArgs = (params && params.arguments) || {};
try {
const content = await handleToolCall(toolName, toolArgs);
return jsonRpcResponse(id, { content, isError: false });
} catch (err) {
return jsonRpcResponse(id, {
content: [{ type: "text", text: `Error: ${err.message}` }],
isError: true,
});
}
}
default:
return jsonRpcError(id, -32601, `Method not found: ${method}`);
}
}
// ---------------------------------------------------------------------------
// stdio transport
// ---------------------------------------------------------------------------
const rl = readline.createInterface({ input: process.stdin, terminal: false });
rl.on("line", async (line) => {
try {
const msg = JSON.parse(line.trim());
const response = await handleRequest(msg);
if (response !== null) {
process.stdout.write(response + "\n");
}
} catch (err) {
const errResp = jsonRpcError(null, -32700, `Parse error: ${err.message}`);
process.stdout.write(errResp + "\n");
}
});
rl.on("close", () => process.exit(0));
param(
[string]$InstallPath = "$env:ProgramFiles\Codex-AG-Bridge",
[string]$BrokerPort = "8787"
)
$ErrorActionPreference = "Stop"
Write-Host "๐Ÿ›ธ Installing Codex-AG Bridge..." -ForegroundColor Cyan
# 1. Create Directories
if (-not (Test-Path $InstallPath)) {
New-Item -ItemType Directory -Path $InstallPath -Force | Out-Null
}
# 2. Copy Resources (Assuming script is in scripts/ folder)
$src = Split-Path -Parent $PSScriptRoot
Copy-Item "$src\*" $InstallPath -Recurse -Force
# 3. Install Node Dependencies
Set-Location "$InstallPath\resources"
npm install
# 4. Setup Silent Broker Task (SYSTEM account)
$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -Command `"node $InstallPath\resources\broker.js`""
$trigger = New-ScheduledTaskTrigger -AtStartup
$settings = New-ScheduledTaskSettingsSet -StartWhenAvailable -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1)
Register-ScheduledTask -TaskName "Codex-AG-Broker" -User "SYSTEM" -Action $action -Trigger $trigger -Settings $settings -RunLevel Highest -Force
Start-ScheduledTask -TaskName "Codex-AG-Broker"
Write-Host "โœ… Installation Complete! Codex-AG Bridge is running silently." -ForegroundColor Green
name description
Codex-AG Bridge
Specialist integration for GPT-5.3 Codex, optimized for silent execution and token preservation.

Codex-AG Bridge Skill

This skill empowers Anti-Gravity to operate as a high-performance relay for GPT-5.3.

๐Ÿ“œ Standing Rules for AG

  1. Laconic Mode: Act as a pass-through pipe. Do not summarize GPT-5.3 output.
  2. Silent Protocol: Register all background tasks as SYSTEM scheduled tasks.
  3. Brain Priority: Use AGENTS.md and the shared SQLite memory as the primary source of truth.

๐Ÿ› ๏ธ Automated Tools

  • Codex Broker: Managing the /ask and /brain endpoints.
  • Brain Sync: Keeping Codex and AG memories in perfect lock-step.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment