Merge pull request '新增 Go Codex HTTP 网关和独立 worker' (#1) from codex/initial-gateway into main
Check Codex HTTP gateway / verify (push) Successful in 1m32s
Check Codex HTTP gateway / verify (push) Successful in 1m32s
Reviewed-on: #1
This commit was merged in pull request #1.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
*
|
||||
!go.mod
|
||||
!main.go
|
||||
!gateway.go
|
||||
!worker.go
|
||||
@@ -0,0 +1,34 @@
|
||||
name: Check Codex HTTP gateway
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, 'codex/**']
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
verify:
|
||||
runs-on: ces-control
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
cache: false
|
||||
- name: Format, test and vet
|
||||
run: |
|
||||
set -eu
|
||||
test -z "$(gofmt -l *.go)"
|
||||
go test -race ./...
|
||||
go vet ./...
|
||||
- name: Validate Docker Compose and build images
|
||||
run: |
|
||||
set -eu
|
||||
docker compose config -q
|
||||
build_ids=$(mktemp -d)
|
||||
trap 'rm -r "$build_ids"' EXIT
|
||||
docker build --target gateway --iidfile "$build_ids/gateway" .
|
||||
docker build --target worker --iidfile "$build_ids/worker" .
|
||||
docker run --rm --network none \
|
||||
--entrypoint /opt/codex/node_modules/.bin/codex "$(cat "$build_ids/worker")" --version \
|
||||
| grep -Fx 'codex-cli 0.172.0'
|
||||
@@ -0,0 +1,6 @@
|
||||
.env
|
||||
.env.local
|
||||
auth.json
|
||||
keys.sha256
|
||||
/state/
|
||||
/codex-gateway
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
FROM golang:1.25-bookworm AS build
|
||||
WORKDIR /src
|
||||
COPY go.mod main.go gateway.go worker.go ./
|
||||
RUN CGO_ENABLED=0 go build -trimpath -o /out/codex-gateway .
|
||||
|
||||
FROM scratch AS gateway
|
||||
COPY --from=build /out/codex-gateway /codex-gateway
|
||||
USER 10001:10001
|
||||
ENTRYPOINT ["/codex-gateway", "gateway"]
|
||||
|
||||
FROM node:24-bookworm-slim AS worker
|
||||
ARG CODEX_VERSION=0.172.0
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& npm install --prefix /opt/codex --no-audit --no-fund "@openai/codex@${CODEX_VERSION}" \
|
||||
&& groupadd --gid 10001 gateway \
|
||||
&& useradd --uid 10001 --gid 10001 --home-dir /home/gateway --create-home --shell /usr/sbin/nologin gateway \
|
||||
&& install -d -m 700 -o 10001 -g 10001 /var/lib/codex \
|
||||
&& mkdir -p /work
|
||||
COPY --from=build /out/codex-gateway /codex-gateway
|
||||
ENV CODEX_HOME=/var/lib/codex HOME=/home/gateway
|
||||
WORKDIR /work
|
||||
USER 10001:10001
|
||||
ENTRYPOINT ["/codex-gateway", "worker"]
|
||||
@@ -0,0 +1,69 @@
|
||||
# Codex HTTP Gateway
|
||||
|
||||
Go 网关提供 `POST /v1/chat/completions`。通过自签发的 Bearer key 验证后,网关经 Unix socket 把文本请求交给运行 Codex CLI 的 worker 容器。两个容器分别挂载网关 key 的哈希文件和 Codex 登录目录。
|
||||
|
||||
## HTTP 接口
|
||||
|
||||
- 客户端的 OpenAI SDK `base_url` 为 `https://<入口>/v1`,`api_key` 填网关签发的 key,模型名填 `codex`。实际模型默认由 Codex CLI 选择,部署者也可以设置 `CODEX_MODEL`。
|
||||
- 请求支持 `model`、`messages` 和可选的 `stream: false`。`messages` 支持字符串 `content` 以及 `system`、`developer`、`user`、`assistant` 四种角色,最后一条消息须来自 `user`。CLI 通过文本对话记录接收这些角色。每次请求都是独立的,多轮对话由客户端随请求重发。
|
||||
- 响应包含 `choices[0].message.content`,CLI 返回用量时也包含 `usage`。第一版支持非流式文本,流式输出、文件和工具调用参数会返回 `400`。
|
||||
- 缺少 key 或 key 无效时返回 `401`。单 worker 同时执行一条请求,忙时返回 `429`,最长执行 90 秒。
|
||||
|
||||
```sh
|
||||
curl "$GATEWAY_URL/v1/chat/completions" \
|
||||
-H "Authorization: Bearer $GATEWAY_KEY" \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"codex","messages":[{"role":"user","content":"Reply with hello."}]}'
|
||||
```
|
||||
|
||||
## 构建与部署
|
||||
|
||||
Gitea Actions 在 `ces-control` 上跑 Go 测试、检查 Compose 配置并构建两个镜像。以下部署命令在确认的远程环境中执行。在检出的项目目录运行 `docker compose build`,然后建立状态目录并登录。默认宿主机端口是 `127.0.0.1:18080`,可以通过 `GATEWAY_PORT` 修改。
|
||||
|
||||
### 建立状态目录并签发网关 key
|
||||
|
||||
在部署机的管理员 shell 执行。这里的 `GATEWAY_KEY` 是客户端凭据,与 OpenAI 或 ChatGPT 的登录凭据独立。用受控的密码管理器保存该值。服务器的网关只读取 SHA-256 哈希。
|
||||
|
||||
```sh
|
||||
install -d -m 0755 /opt/codex-http-gateway
|
||||
install -d -m 0700 -o 10001 -g 10001 \
|
||||
/opt/codex-http-gateway/run /opt/codex-http-gateway/codex-home
|
||||
umask 077
|
||||
GATEWAY_KEY="cgw_$(openssl rand -hex 32)"
|
||||
printf '%s' "$GATEWAY_KEY" | openssl dgst -sha256 -r | cut -d ' ' -f 1 \
|
||||
>> /opt/codex-http-gateway/keys.sha256
|
||||
chown 10001:10001 /opt/codex-http-gateway/keys.sha256
|
||||
chmod 0400 /opt/codex-http-gateway/keys.sha256
|
||||
```
|
||||
|
||||
文件每行对应一个已签发的 key。追加新哈希或移除被撤销的哈希后,运行 `docker compose up -d --no-build --force-recreate gateway` 重新加载文件。用完当前 shell 中的明文后运行 `unset GATEWAY_KEY`。
|
||||
|
||||
### 给 worker 登录
|
||||
|
||||
构建完镜像后,可以用设备码将 worker 绑定到你自己的 ChatGPT/Codex 账号。登录前在 ChatGPT 安全设置里启用设备码。在部署机运行以下命令,然后由你在自己的浏览器里完成授权。
|
||||
|
||||
```sh
|
||||
docker compose run --rm --no-deps \
|
||||
--entrypoint /opt/codex/node_modules/.bin/codex worker \
|
||||
-c 'cli_auth_credentials_store="file"' login --device-auth
|
||||
```
|
||||
|
||||
文件凭据保存在宿主机 `/opt/codex-http-gateway/codex-home/auth.json`,worker 在使用过程中可以更新文件。不要把凭据放进仓库、镜像或聊天。个人账号模式仅供账号持有人使用。若需要向其他人签发网关 key,请给 worker 使用专用的 OpenAI 项目 API key,并从部署机受保护文件经 stdin 登录。
|
||||
|
||||
```sh
|
||||
docker compose run --rm --no-deps -T \
|
||||
--entrypoint /opt/codex/node_modules/.bin/codex worker \
|
||||
-c 'cli_auth_credentials_store="file"' login --with-api-key \
|
||||
< /path/to/protected-openai-api-key
|
||||
docker compose up -d --no-build
|
||||
```
|
||||
|
||||
个人账号使用设备码登录后,同样运行 `docker compose up -d --no-build` 启动服务。配置参考 [Codex CLI 登录方式](https://learn.chatgpt.com/docs/auth)和 [OpenAI 使用条款](https://openai.com/policies/terms-of-use/)。
|
||||
|
||||
### 公网 HTTPS 入口
|
||||
|
||||
将宿主机现有反向代理的 `POST /v1/chat/completions` 转发到 `http://127.0.0.1:18080`,保留 `Authorization` 请求头,并将上游读取超时设为至少 105 秒。公网入口请用 HTTPS,以保护网关 key 和请求内容。
|
||||
|
||||
没有域名时,可以为固定公网 IPv4 申请短期受信证书。Certbot 5.4 或更新版本支持用 webroot 验证 IP。用现有反向代理在公网 TCP/80 提供 `/.well-known/acme-challenge/`,申请证书后在公网 TCP/443 配置 HTTPS。证书有效期约六天,启用定时续期和续签后重载代理。具体命令见 [Let's Encrypt 的 IP 地址证书指南](https://letsencrypt.org/2026/03/11/shorter-certs-certbot)。
|
||||
|
||||
公网入口上线前可用 `http://127.0.0.1:18080` 验证。无 Authorization 应返回 `401`,带有效 key 和已登录 worker 应返回 `200` 及 `chat.completion`。
|
||||
@@ -0,0 +1,59 @@
|
||||
name: codex-http-gateway
|
||||
services:
|
||||
gateway:
|
||||
build:
|
||||
context: .
|
||||
target: gateway
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
pids_limit: 64
|
||||
mem_limit: 128m
|
||||
ports:
|
||||
- "127.0.0.1:${GATEWAY_PORT:-18080}:8080"
|
||||
networks: [gateway-ingress]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${GATEWAY_KEYS_FILE:-/opt/codex-http-gateway/keys.sha256}
|
||||
target: /run/secrets/gateway-keys.sha256
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
- type: bind
|
||||
source: ${GATEWAY_RUN_DIR:-/opt/codex-http-gateway/run}
|
||||
target: /run/codex-gateway
|
||||
read_only: true
|
||||
bind:
|
||||
create_host_path: false
|
||||
worker:
|
||||
build:
|
||||
context: .
|
||||
target: worker
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
read_only: true
|
||||
cap_drop: [ALL]
|
||||
security_opt: ["no-new-privileges:true"]
|
||||
pids_limit: 128
|
||||
mem_limit: 1g
|
||||
tmpfs:
|
||||
- /tmp:rw,nosuid,nodev,noexec,mode=1777,size=64m
|
||||
environment:
|
||||
CODEX_MODEL: ${CODEX_MODEL:-}
|
||||
networks: [worker-egress]
|
||||
volumes:
|
||||
- type: bind
|
||||
source: ${GATEWAY_RUN_DIR:-/opt/codex-http-gateway/run}
|
||||
target: /run/codex-gateway
|
||||
bind:
|
||||
create_host_path: false
|
||||
- type: bind
|
||||
source: ${CODEX_AUTH_DIR:-/opt/codex-http-gateway/codex-home}
|
||||
target: /var/lib/codex
|
||||
bind:
|
||||
create_host_path: false
|
||||
networks:
|
||||
gateway-ingress:
|
||||
worker-egress:
|
||||
+226
@@ -0,0 +1,226 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const publicModel = "codex"
|
||||
|
||||
type keyHashes [][sha256.Size]byte
|
||||
|
||||
func loadKeys(path string) (keyHashes, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
var keys keyHashes
|
||||
scanner := bufio.NewScanner(file)
|
||||
scanner.Buffer(make([]byte, 256), 256)
|
||||
for scanner.Scan() {
|
||||
line := strings.TrimSpace(scanner.Text())
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
var key [sha256.Size]byte
|
||||
if len(line) != hex.EncodedLen(len(key)) || len(keys) == 256 {
|
||||
return nil, errors.New("expected at most 256 SHA-256 hex digests")
|
||||
}
|
||||
if _, err := hex.Decode(key[:], []byte(line)); err != nil {
|
||||
return nil, errors.New("invalid SHA-256 hex digest")
|
||||
}
|
||||
keys = append(keys, key)
|
||||
}
|
||||
if err := scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return nil, errors.New("at least one key hash is required")
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func (keys keyHashes) permits(r *http.Request) bool {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return false
|
||||
}
|
||||
scheme, token, ok := strings.Cut(values[0], " ")
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") {
|
||||
return false
|
||||
}
|
||||
encoded, ok := strings.CutPrefix(token, "cgw_")
|
||||
if !ok || len(encoded) != 64 {
|
||||
return false
|
||||
}
|
||||
var raw [32]byte
|
||||
if _, err := hex.Decode(raw[:], []byte(encoded)); err != nil {
|
||||
return false
|
||||
}
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
var match int
|
||||
for _, key := range keys {
|
||||
match |= subtle.ConstantTimeCompare(key[:], digest[:])
|
||||
}
|
||||
return match == 1
|
||||
}
|
||||
|
||||
type message struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
type chatRequest struct {
|
||||
Model string `json:"model"`
|
||||
Messages []message `json:"messages"`
|
||||
Stream bool `json:"stream"`
|
||||
}
|
||||
|
||||
type usage struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
TotalTokens int `json:"total_tokens"`
|
||||
}
|
||||
|
||||
type workerResult struct {
|
||||
Text string `json:"text"`
|
||||
Usage *usage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
type apiError struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
}
|
||||
|
||||
type completionChoice struct {
|
||||
Index int `json:"index"`
|
||||
Message message `json:"message"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
}
|
||||
|
||||
type completion struct {
|
||||
ID string `json:"id"`
|
||||
Object string `json:"object"`
|
||||
Created int64 `json:"created"`
|
||||
Model string `json:"model"`
|
||||
Choices []completionChoice `json:"choices"`
|
||||
Usage *usage `json:"usage,omitempty"`
|
||||
}
|
||||
|
||||
func newGateway(keys keyHashes, execute func(context.Context, string) (workerResult, int)) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.URL.Path != "/v1/chat/completions" {
|
||||
writeError(w, http.StatusNotFound, "invalid_request_error", "not_found", "Endpoint not found.")
|
||||
return
|
||||
}
|
||||
if !keys.permits(r) {
|
||||
w.Header().Set("WWW-Authenticate", "Bearer")
|
||||
writeError(w, http.StatusUnauthorized, "invalid_request_error", "invalid_api_key", "A valid gateway API key is required.")
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
writeError(w, http.StatusMethodNotAllowed, "invalid_request_error", "method_not_allowed", "Use POST for this endpoint.")
|
||||
return
|
||||
}
|
||||
var request chatRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, requestLimit))
|
||||
decoder.DisallowUnknownFields()
|
||||
err := decoder.Decode(&request)
|
||||
if err == nil {
|
||||
if trailing := decoder.Decode(new(any)); trailing != io.EOF {
|
||||
err = errors.New("expected exactly one JSON object")
|
||||
var sizeError *http.MaxBytesError
|
||||
if errors.As(trailing, &sizeError) {
|
||||
err = sizeError
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
var sizeError *http.MaxBytesError
|
||||
if errors.As(err, &sizeError) {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, "invalid_request_error", "request_too_large", "Request exceeds 128 KiB.")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusBadRequest, "invalid_request_error", "invalid_request", "Send model, text messages and optionally stream=false.")
|
||||
return
|
||||
}
|
||||
if request.Model != publicModel || request.Stream || !validMessages(request.Messages) {
|
||||
writeError(w, http.StatusBadRequest, "invalid_request_error", "unsupported_request", "Use model=codex, stream=false and text messages ending in a user message.")
|
||||
return
|
||||
}
|
||||
transcript, _ := json.Marshal(request.Messages)
|
||||
prompt := "Answer the final user message in this JSON conversation. Use earlier messages as context. Return only the text response.\n" + string(transcript)
|
||||
result, status := execute(r.Context(), prompt)
|
||||
switch status {
|
||||
case http.StatusOK:
|
||||
writeJSON(w, status, completion{
|
||||
ID: "chatcmpl-" + rand.Text(), Object: "chat.completion", Created: time.Now().Unix(), Model: publicModel,
|
||||
Choices: []completionChoice{{Index: 0, Message: message{Role: "assistant", Content: result.Text}, FinishReason: "stop"}},
|
||||
Usage: result.Usage,
|
||||
})
|
||||
case http.StatusTooManyRequests:
|
||||
w.Header().Set("Retry-After", "5")
|
||||
writeError(w, status, "rate_limit_error", "worker_busy", "Codex is already handling a request. Retry shortly.")
|
||||
case http.StatusGatewayTimeout:
|
||||
writeError(w, status, "server_error", "worker_timeout", "Codex did not finish in time.")
|
||||
case http.StatusServiceUnavailable:
|
||||
writeError(w, status, "server_error", "worker_unavailable", "Codex is unavailable.")
|
||||
default:
|
||||
writeError(w, http.StatusBadGateway, "server_error", "worker_failed", "Codex did not return a completion.")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func validMessages(messages []message) bool {
|
||||
if len(messages) == 0 || len(messages) > 128 || messages[len(messages)-1].Role != "user" {
|
||||
return false
|
||||
}
|
||||
for _, message := range messages {
|
||||
switch message.Role {
|
||||
case "system", "developer", "user", "assistant":
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(message.Content) == "" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, kind, code, description string) {
|
||||
writeJSON(w, status, map[string]apiError{"error": {Message: description, Type: kind, Code: code}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
|
||||
func decodeWorkerResponse(r io.Reader) (workerResult, error) {
|
||||
var result workerResult
|
||||
decoder := json.NewDecoder(io.LimitReader(r, 6*outputLimit+4096))
|
||||
if err := decoder.Decode(&result); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if len(result.Text) > outputLimit || result.Text == "" || decoder.Decode(new(any)) != io.EOF {
|
||||
return result, errors.New("invalid worker result")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGatewayRequiresIssuedKeyBeforeExecution(t *testing.T) {
|
||||
key := "cgw_" + strings.Repeat("a", 64)
|
||||
otherKey := "cgw_" + strings.Repeat("b", 64)
|
||||
keys := keyHashes{sha256.Sum256([]byte(otherKey)), sha256.Sum256([]byte(key))}
|
||||
var calls int
|
||||
handler := newGateway(keys, func(_ context.Context, prompt string) (workerResult, int) {
|
||||
calls++
|
||||
if !strings.Contains(prompt, `{"role":"user","content":"hello"}`) {
|
||||
t.Fatalf("missing user message in prompt: %s", prompt)
|
||||
}
|
||||
return workerResult{Text: "world", Usage: &usage{PromptTokens: 10, CompletionTokens: 1, TotalTokens: 11}}, http.StatusOK
|
||||
})
|
||||
const request = `{"model":"codex","messages":[{"role":"user","content":"hello"}]}`
|
||||
for _, lookup := range []struct {
|
||||
name string
|
||||
headers []string
|
||||
body string
|
||||
status int
|
||||
}{
|
||||
{name: "no key", body: "{", status: 401},
|
||||
{name: "unknown key", headers: []string{"Bearer cgw_" + strings.Repeat("c", 64)}, body: request, status: 401},
|
||||
{name: "duplicate credentials", headers: []string{"Bearer " + key, "Bearer " + key}, body: request, status: 401},
|
||||
{name: "unexpected tools", headers: []string{"Bearer " + key}, body: strings.TrimSuffix(request, "}") + `,"tools":[]}`, status: 400},
|
||||
{name: "streaming", headers: []string{"Bearer " + key}, body: strings.TrimSuffix(request, "}") + `,"stream":true}`, status: 400},
|
||||
{name: "oversized body", headers: []string{"Bearer " + key}, body: request + strings.Repeat(" ", requestLimit), status: 413},
|
||||
{name: "issued key", headers: []string{"bearer " + key}, body: request, status: 200},
|
||||
} {
|
||||
t.Run(lookup.name, func(t *testing.T) {
|
||||
before := calls
|
||||
req := httptest.NewRequest(http.MethodPost, "/v1/chat/completions", strings.NewReader(lookup.body))
|
||||
for _, header := range lookup.headers {
|
||||
req.Header.Add("Authorization", header)
|
||||
}
|
||||
res := httptest.NewRecorder()
|
||||
handler.ServeHTTP(res, req)
|
||||
if res.Code != lookup.status {
|
||||
t.Fatalf("status = %d, want %d: %s", res.Code, lookup.status, res.Body)
|
||||
}
|
||||
if lookup.status != http.StatusOK {
|
||||
if calls != before || !strings.Contains(res.Body.String(), `"error"`) {
|
||||
t.Fatalf("rejected request reached worker or lacked API error: %s", res.Body)
|
||||
}
|
||||
return
|
||||
}
|
||||
var got completion
|
||||
if err := json.Unmarshal(res.Body.Bytes(), &got); err != nil || calls != before+1 ||
|
||||
got.Object != "chat.completion" || got.Model != "codex" || len(got.Choices) != 1 ||
|
||||
got.Choices[0].Message.Content != "world" || got.Usage == nil || got.Usage.TotalTokens != 11 {
|
||||
t.Fatalf("unexpected completion: %s", res.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorkerReturnsOnlyFinalTextAndUsage(t *testing.T) {
|
||||
events := `{"type":"turn.started"}
|
||||
{"type":"item.completed","item":{"type":"agent_message","text":"intermediate"}}
|
||||
{"type":"item.completed","item":{"type":"reasoning","text":"internal"}}
|
||||
{"type":"item.completed","item":{"type":"agent_message","text":"final"}}
|
||||
{"type":"turn.completed","usage":{"input_tokens":5,"output_tokens":2}}`
|
||||
result, err := parseEvents([]byte(events))
|
||||
if err != nil || result.Text != "final" || result.Usage == nil || result.Usage.TotalTokens != 7 {
|
||||
t.Fatalf("unexpected result: %#v, %v", result, err)
|
||||
}
|
||||
for _, invalid := range []string{`{"type":"turn.completed"}`, `{"type":"turn.failed"}`, events + "\ntruncated"} {
|
||||
if _, err := parseEvents([]byte(invalid)); err == nil {
|
||||
t.Fatalf("invalid events accepted: %s", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module gitea.entroia.com/Zayden-Jung/codex-http-gateway
|
||||
|
||||
go 1.25.0
|
||||
@@ -0,0 +1,89 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
workerSocket = "/run/codex-gateway/worker.sock"
|
||||
requestLimit = 128 << 10
|
||||
outputLimit = 256 << 10
|
||||
jobTimeout = 90 * time.Second
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func run() error {
|
||||
if len(os.Args) != 2 {
|
||||
return errors.New("usage: codex-gateway gateway|worker")
|
||||
}
|
||||
var addr string
|
||||
var handler http.Handler
|
||||
var listener net.Listener
|
||||
var err error
|
||||
switch os.Args[1] {
|
||||
case "gateway":
|
||||
keys, err := loadKeys("/run/secrets/gateway-keys.sha256")
|
||||
if err != nil {
|
||||
return fmt.Errorf("load gateway key hashes: %w", err)
|
||||
}
|
||||
addr = ":8080"
|
||||
handler = newGateway(keys, callWorker)
|
||||
listener, err = net.Listen("tcp", addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case "worker":
|
||||
addr = workerSocket
|
||||
listener, err = listenWorker()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
handler = newWorker(os.Getenv("CODEX_MODEL"))
|
||||
default:
|
||||
return errors.New("expected gateway or worker")
|
||||
}
|
||||
defer listener.Close()
|
||||
server := &http.Server{
|
||||
Handler: handler,
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: jobTimeout + 15*time.Second,
|
||||
IdleTimeout: 30 * time.Second,
|
||||
MaxHeaderBytes: 8 << 10,
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
server.BaseContext = func(net.Listener) context.Context { return ctx }
|
||||
shutdown := make(chan struct{})
|
||||
go func() {
|
||||
defer close(shutdown)
|
||||
<-ctx.Done()
|
||||
deadline, cancel := context.WithTimeout(context.Background(), 8*time.Second)
|
||||
defer cancel()
|
||||
if server.Shutdown(deadline) != nil {
|
||||
_ = server.Close()
|
||||
}
|
||||
}()
|
||||
log.Printf("%s listening at %s", os.Args[1], addr)
|
||||
err = server.Serve(listener)
|
||||
stop()
|
||||
<-shutdown
|
||||
if errors.Is(err, http.ErrServerClosed) {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
maxPrompt = 6*requestLimit + 4096
|
||||
maxEvents = 2 << 20
|
||||
codexHome = "/var/lib/codex"
|
||||
codexCLI = "/opt/codex/node_modules/.bin/codex"
|
||||
)
|
||||
|
||||
func listenWorker() (*net.UnixListener, error) {
|
||||
syscall.Umask(0077)
|
||||
info, err := os.Lstat(workerSocket)
|
||||
if err == nil {
|
||||
if info.Mode()&os.ModeSocket == 0 {
|
||||
return nil, errors.New("worker socket path is occupied")
|
||||
}
|
||||
conn, dialErr := net.DialTimeout("unix", workerSocket, time.Second)
|
||||
if dialErr == nil {
|
||||
conn.Close()
|
||||
return nil, errors.New("worker socket already in use")
|
||||
}
|
||||
if !errors.Is(dialErr, syscall.ECONNREFUSED) {
|
||||
return nil, dialErr
|
||||
}
|
||||
if err := os.Remove(workerSocket); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
return net.ListenUnix("unix", &net.UnixAddr{Name: workerSocket, Net: "unix"})
|
||||
}
|
||||
|
||||
var workerHTTP = &http.Client{
|
||||
Timeout: jobTimeout + 5*time.Second,
|
||||
Transport: &http.Transport{
|
||||
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
|
||||
return (&net.Dialer{Timeout: time.Second}).DialContext(ctx, "unix", workerSocket)
|
||||
},
|
||||
DisableKeepAlives: true,
|
||||
},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}
|
||||
|
||||
func callWorker(ctx context.Context, prompt string) (workerResult, int) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://worker/complete", strings.NewReader(prompt))
|
||||
if err != nil {
|
||||
return workerResult{}, http.StatusBadGateway
|
||||
}
|
||||
response, err := workerHTTP.Do(request)
|
||||
if err != nil {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return workerResult{}, http.StatusGatewayTimeout
|
||||
}
|
||||
return workerResult{}, http.StatusServiceUnavailable
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return workerResult{}, response.StatusCode
|
||||
}
|
||||
result, err := decodeWorkerResponse(response.Body)
|
||||
if err != nil {
|
||||
return workerResult{}, http.StatusBadGateway
|
||||
}
|
||||
return result, http.StatusOK
|
||||
}
|
||||
|
||||
func newWorker(model string) http.Handler {
|
||||
slot := make(chan struct{}, 1)
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /complete", func(w http.ResponseWriter, r *http.Request) {
|
||||
prompt, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxPrompt))
|
||||
if err != nil || len(prompt) == 0 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
select {
|
||||
case slot <- struct{}{}:
|
||||
defer func() { <-slot }()
|
||||
default:
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), jobTimeout)
|
||||
defer cancel()
|
||||
result, status := runCodex(ctx, model, prompt)
|
||||
if status != http.StatusOK {
|
||||
w.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
writeJSON(w, status, result)
|
||||
})
|
||||
return mux
|
||||
}
|
||||
|
||||
func runCodex(ctx context.Context, model string, prompt []byte) (workerResult, int) {
|
||||
auth, err := os.Lstat(codexHome + "/auth.json")
|
||||
if err != nil || !auth.Mode().IsRegular() || auth.Size() == 0 {
|
||||
return workerResult{}, http.StatusServiceUnavailable
|
||||
}
|
||||
args := []string{
|
||||
"--ask-for-approval", "never",
|
||||
"--disable", "shell_tool",
|
||||
"--disable", "unified_exec",
|
||||
"--disable", "apps",
|
||||
"--disable", "plugins",
|
||||
"--disable", "multi_agent",
|
||||
"--disable", "multi_agent_v2",
|
||||
"--disable", "hooks",
|
||||
"--disable", "memories",
|
||||
"--disable", "image_generation",
|
||||
"--disable", "browser_use",
|
||||
"--disable", "computer_use",
|
||||
"--disable", "code_mode_host",
|
||||
"--disable", "workspace_dependencies",
|
||||
"-c", `web_search="disabled"`,
|
||||
"-c", `cli_auth_credentials_store="file"`,
|
||||
"exec", "--json", "--sandbox", "read-only", "--skip-git-repo-check", "--ephemeral", "--ignore-user-config", "--ignore-rules",
|
||||
}
|
||||
if model != "" {
|
||||
args = append(args, "--model", model)
|
||||
}
|
||||
cmd := exec.CommandContext(ctx, codexCLI, append(args, "-")...)
|
||||
cmd.Dir = "/work"
|
||||
cmd.Env = []string{
|
||||
"PATH=/usr/local/bin:/usr/bin:/bin", "HOME=/home/gateway", "CODEX_HOME=" + codexHome,
|
||||
"SSL_CERT_FILE=/etc/ssl/certs/ca-certificates.crt",
|
||||
}
|
||||
cmd.Stdin = bytes.NewReader(prompt)
|
||||
cmd.Stderr = io.Discard
|
||||
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
||||
cmd.Cancel = func() error {
|
||||
err := syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
||||
if errors.Is(err, syscall.ESRCH) {
|
||||
return os.ErrProcessDone
|
||||
}
|
||||
return err
|
||||
}
|
||||
cmd.WaitDelay = 2 * time.Second
|
||||
var output eventBuffer
|
||||
cmd.Stdout = &output
|
||||
err = cmd.Run()
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return workerResult{}, http.StatusGatewayTimeout
|
||||
}
|
||||
if err != nil || output.exceeded {
|
||||
return workerResult{}, http.StatusBadGateway
|
||||
}
|
||||
result, err := parseEvents(output.buffer.Bytes())
|
||||
if err != nil {
|
||||
return workerResult{}, http.StatusBadGateway
|
||||
}
|
||||
return result, http.StatusOK
|
||||
}
|
||||
|
||||
type eventBuffer struct {
|
||||
buffer bytes.Buffer
|
||||
exceeded bool
|
||||
}
|
||||
|
||||
func (b *eventBuffer) Write(data []byte) (int, error) {
|
||||
if len(data) > maxEvents-b.buffer.Len() {
|
||||
b.exceeded = true
|
||||
return 0, errors.New("Codex event output exceeded limit")
|
||||
}
|
||||
return b.buffer.Write(data)
|
||||
}
|
||||
|
||||
func parseEvents(output []byte) (workerResult, error) {
|
||||
var result workerResult
|
||||
var completed bool
|
||||
scanner := bufio.NewScanner(bytes.NewReader(output))
|
||||
scanner.Buffer(make([]byte, 4096), maxEvents)
|
||||
for scanner.Scan() {
|
||||
var event struct {
|
||||
Type string `json:"type"`
|
||||
Item struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
} `json:"item"`
|
||||
Usage *struct {
|
||||
Input int `json:"input_tokens"`
|
||||
Output int `json:"output_tokens"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if err := json.Unmarshal(scanner.Bytes(), &event); err != nil || event.Type == "" {
|
||||
return workerResult{}, errors.New("invalid Codex event")
|
||||
}
|
||||
switch event.Type {
|
||||
case "turn.failed", "error":
|
||||
return workerResult{}, errors.New("Codex generation failed")
|
||||
case "item.completed":
|
||||
if event.Item.Type == "agent_message" {
|
||||
result.Text = event.Item.Text
|
||||
}
|
||||
case "turn.completed":
|
||||
completed = true
|
||||
if event.Usage != nil {
|
||||
result.Usage = &usage{
|
||||
PromptTokens: event.Usage.Input, CompletionTokens: event.Usage.Output,
|
||||
TotalTokens: event.Usage.Input + event.Usage.Output,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if scanner.Err() != nil || !completed || len(result.Text) > outputLimit || strings.TrimSpace(result.Text) == "" {
|
||||
return workerResult{}, errors.New("missing or invalid Codex completion")
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
Reference in New Issue
Block a user