Files
command-code-openai-bridge/AGENTS.md
T
2026-08-05 16:43:18 +08:00

9.2 KiB
Raw Blame History

Command Code OpenAI Bridge

Command Code OpenAI Bridge 是一个仅在本机运行的 OpenAI Chat Completions 兼容服务。它把 OpenAI 客户端发送的文本对话转交给 Command Code CLI 执行,并将最终 assistant 回复以标准 Chat Completions 格式返回。

默认 API 地址:http://127.0.0.1:18000/v1

工作方式

每个请求都会启动一个独立的 Command Code headless agent

  1. 接收并校验 OpenAI Chat Completions 请求。
  2. 保留消息的角色、顺序和完整文本,将全部会话历史序列化后通过 stdin 传给 Command Code。
  3. 在启动服务的终端中显示模型状态、turn、工具调用、工具结果、stderr、最终回答和耗时。
  4. 从 Command Code 的 NDJSON 结构化结果中提取 finalText
  5. 只把最终回复和可用的 token usage 返回给 API 客户端。

服务不保存跨请求会话。每次调用都使用 --no-session,对话历史由客户端维护并在请求中完整提供。

主要能力

  • 提供 GET /healthGET /v1/modelsPOST /v1/chat/completions
  • 支持字符串形式的 content 和 OpenAI 文本 part 数组。
  • 接受 stream: true,但 Command Code 调用仍为非流式;完整结果生成后再一次性封装为 SSE 事件返回。
  • 支持中文、Unicode、Markdown、代码块和较长文本。
  • 模型名称通过 YAML 配置映射到实际 Command Code 模型。
  • 请求内容通过 stdin 传输,不受命令行参数长度限制。
  • 同时只运行一个 Command Code 请求;忙碌时返回 HTTP 429。
  • 客户端断开、请求取消、总超时和 Ctrl+C 会终止当前子进程组。
  • 单次 Command Code 失败后,HTTP 服务可继续处理后续请求。
  • Authorization 请求头会被忽略,服务强制绑定 127.0.0.1

当前只支持文本 Chat Completions。stream: true 是客户端兼容层,不会实时输出 Command Code 的生成过程。图片、音频、function calling、Responses API 和服务端会话均未实现。

技术实现

  • Node.js 22+
  • TypeScript
  • Fastify
  • Zod
  • YAML
  • Command Code CLI 官方 headless 模式:-p --output-format json

项目使用普通子进程读取 Command Code 的 NDJSON 事件。终端输出由本项目渲染,可显示主要运行事件,但不包含 Command Code 原始 Ink TUI、动画和键盘交互。启用 dangerously_skip_permissions 时会向 CLI 传入 --yolo,只应在可信工作目录中使用。

项目结构

src/
├── index.ts         # 程序入口、服务启动和信号处理
├── server.ts        # HTTP 路由、单请求状态和错误处理
├── openai.ts        # 请求校验、消息转换和响应生成
├── command-code.ts  # CLI 检查、子进程管理和最终结果提取
├── renderer.ts      # Command Code 事件的终端显示
└── config.ts        # YAML 配置读取与校验

scripts/
├── install.sh       # 安装依赖并构建项目
└── start.sh         # 启动服务

examples/
├── python_client.py # OpenAI Python SDK 示例
└── node_client.mjs  # OpenAI Node.js SDK 示例

快速开始

./scripts/install.sh
command-code login
command-code status --json
./scripts/start.sh

默认配置位于 config.yaml,配置示例位于 config.example.yaml。常用配置包括监听端口、Command Code 可执行文件、工作目录、总超时、请求体上限、最大 turn 数、权限模式和模型映射。

调用示例:

curl http://127.0.0.1:18000/v1/chat/completions \
  -H 'Content-Type: application/json' \
  -d '{
    "model": "command-default",
    "messages": [{"role": "user", "content": "用一句话解释递归。"}],
    "stream": false
  }'

更完整的安装、配置、接口说明、运行行为、检查结果和已知限制见 README.md

GitNexus — Code Intelligence

This project is indexed by GitNexus as command-code-openai-bridge (106 symbols, 201 relationships, 9 execution flows). Use the GitNexus MCP tools to understand code, assess impact, and navigate safely.

If any GitNexus tool warns the index is stale, run npx gitnexus analyze in terminal first.

Always Do

  • MUST run impact analysis before editing any symbol. Before modifying a function, class, or method, run gitnexus_impact({target: "symbolName", direction: "upstream"}) and report the blast radius (direct callers, affected processes, risk level) to the user.
  • MUST run gitnexus_detect_changes() before committing to verify your changes only affect expected symbols and execution flows.
  • MUST warn the user if impact analysis returns HIGH or CRITICAL risk before proceeding with edits.
  • When exploring unfamiliar code, use gitnexus_query({query: "concept"}) to find execution flows instead of grepping. It returns process-grouped results ranked by relevance.
  • When you need full context on a specific symbol — callers, callees, which execution flows it participates in — use gitnexus_context({name: "symbolName"}).

When Debugging

  1. gitnexus_query({query: "<error or symptom>"}) — find execution flows related to the issue
  2. gitnexus_context({name: "<suspect function>"}) — see all callers, callees, and process participation
  3. READ gitnexus://repo/command-code-openai-bridge/process/{processName} — trace the full execution flow step by step
  4. For regressions: gitnexus_detect_changes({scope: "compare", base_ref: "main"}) — see what your branch changed

When Refactoring

  • Renaming: MUST use gitnexus_rename({symbol_name: "old", new_name: "new", dry_run: true}) first. Review the preview — graph edits are safe, text_search edits need manual review. Then run with dry_run: false.
  • Extracting/Splitting: MUST run gitnexus_context({name: "target"}) to see all incoming/outgoing refs, then gitnexus_impact({target: "target", direction: "upstream"}) to find all external callers before moving code.
  • After any refactor: run gitnexus_detect_changes({scope: "all"}) to verify only expected files changed.

Never Do

  • NEVER edit a function, class, or method without first running gitnexus_impact on it.
  • NEVER ignore HIGH or CRITICAL risk warnings from impact analysis.
  • NEVER rename symbols with find-and-replace — use gitnexus_rename which understands the call graph.
  • NEVER commit changes without running gitnexus_detect_changes() to check affected scope.

Tools Quick Reference

Tool When to use Command
query Find code by concept gitnexus_query({query: "auth validation"})
context 360-degree view of one symbol gitnexus_context({name: "validateUser"})
impact Blast radius before editing gitnexus_impact({target: "X", direction: "upstream"})
detect_changes Pre-commit scope check gitnexus_detect_changes({scope: "staged"})
rename Safe multi-file rename gitnexus_rename({symbol_name: "old", new_name: "new", dry_run: true})
cypher Custom graph queries gitnexus_cypher({query: "MATCH ..."})

Impact Risk Levels

Depth Meaning Action
d=1 WILL BREAK — direct callers/importers MUST update these
d=2 LIKELY AFFECTED — indirect deps Should test
d=3 MAY NEED TESTING — transitive Test if critical path

Resources

Resource Use for
gitnexus://repo/command-code-openai-bridge/context Codebase overview, check index freshness
gitnexus://repo/command-code-openai-bridge/clusters All functional areas
gitnexus://repo/command-code-openai-bridge/processes All execution flows
gitnexus://repo/command-code-openai-bridge/process/{name} Step-by-step execution trace

Self-Check Before Finishing

Before completing any code modification task, verify:

  1. gitnexus_impact was run for all modified symbols
  2. No HIGH/CRITICAL risk warnings were ignored
  3. gitnexus_detect_changes() confirms changes match expected scope
  4. All d=1 (WILL BREAK) dependents were updated

Keeping the Index Fresh

After committing code changes, the GitNexus index becomes stale. Re-run analyze to update it:

npx gitnexus analyze

If the index previously included embeddings, preserve them by adding --embeddings:

npx gitnexus analyze --embeddings

To check whether embeddings exist, inspect .gitnexus/meta.json — the stats.embeddings field shows the count (0 means no embeddings). Running analyze without --embeddings will delete any previously generated embeddings.

Claude Code users: A PostToolUse hook handles this automatically after git commit and git merge.

CLI

Task Read this skill file
Understand architecture / "How does X work?" .claude/skills/gitnexus/gitnexus-exploring/SKILL.md
Blast radius / "What breaks if I change X?" .claude/skills/gitnexus/gitnexus-impact-analysis/SKILL.md
Trace bugs / "Why is X failing?" .claude/skills/gitnexus/gitnexus-debugging/SKILL.md
Rename / extract / split / refactor .claude/skills/gitnexus/gitnexus-refactoring/SKILL.md
Tools, resources, schema reference .claude/skills/gitnexus/gitnexus-guide/SKILL.md
Index, status, clean, wiki CLI commands .claude/skills/gitnexus/gitnexus-cli/SKILL.md