Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -1,4 +1,4 @@
# Without this, Bazel will consider BUILD.bazel files in
# .git/sl/origbackups (which can be populated by Sapling SCM).
.git
codex-rs/target
akode-rs/target

View File

@@ -24,7 +24,7 @@ build --host_features=static_link_msvcrt
build --workspace_status_command=./scripts/workspace-status.sh
build:windows --workspace_status_command=./scripts/workspace-status.cmd
# Runfiles strategy rationale: codex-rs/utils/cargo-bin/README.md
# Runfiles strategy rationale: akode-rs/utils/cargo-bin/README.md
common --noenable_runfiles
common --enable_platform_specific_config
@@ -127,8 +127,8 @@ common:ci-bazel --build_metadata=TAG_workflow=bazel
# Shared config for Bazel-backed Rust linting.
build:clippy --aspects=@rules_rust//rust:defs.bzl%rust_clippy_aspect
build:clippy --output_groups=+clippy_checks
build:clippy --@rules_rust//rust/settings:clippy.toml=//codex-rs:clippy.toml
# Keep this deny-list in sync with `codex-rs/Cargo.toml` `[workspace.lints.clippy]`.
build:clippy --@rules_rust//rust/settings:clippy.toml=//akode-rs:clippy.toml
# Keep this deny-list in sync with `akode-rs/Cargo.toml` `[workspace.lints.clippy]`.
# Cargo applies those lint levels to member crates that opt into `[lints] workspace = true`
# in their own `Cargo.toml`, but `rules_rust` Bazel clippy does not read Cargo lint levels.
# `clippy.toml` can configure lint behavior, but it cannot set allow/warn/deny/forbid levels.
@@ -181,7 +181,7 @@ common:ci-windows --build_metadata=TAG_os=windows
common:ci-windows --repo_contents_cache=D:/a/.cache/bazel-repo-contents-cache
# The hidden dynamic-tool callback currently times out on Windows, and ConPTY
# cannot reliably interrupt foreground processes on Windows Bazel runners.
common:ci-windows --test_env=CODEX_BAZEL_TEST_SKIP_FILTERS=suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child
common:ci-windows --test_env=AKODE_BAZEL_TEST_SKIP_FILTERS=suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child
# We prefer to run the build actions entirely remotely so we can dial up the concurrency.
# We have platform-specific tests, so we want to execute the tests on all platforms using the strongest sandboxing available on each platform.
@@ -212,7 +212,7 @@ common:ci-windows-cross --test_env=RUST_TEST_THREADS=1
# Native Windows CI still covers the PowerShell parser-process tests. The
# cross-built gnullvm binaries currently hang in those tests when run on the
# Windows runner. This replaces the Windows skip list, so retain its exclusions.
common:ci-windows-cross --test_env=CODEX_BAZEL_TEST_SKIP_FILTERS=command_safety::powershell_parser::tests::,suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child
common:ci-windows-cross --test_env=AKODE_BAZEL_TEST_SKIP_FILTERS=command_safety::powershell_parser::tests::,suite::code_mode::code_mode_can_call_hidden_dynamic_tools,tests::windows_tests::conpty_ctrl_c_interrupts_powershell_foreground_child
common:ci-windows-cross --platforms=//:windows_x86_64_gnullvm
common:ci-windows-cross --extra_execution_platforms=//:rbe,//:windows_x86_64_msvc
common:ci-windows-cross --extra_toolchains=//:windows_gnullvm_tests_on_msvc_host_toolchain
@@ -245,7 +245,7 @@ build:ci-windows-msvc --host_action_env=WindowsSdkDir
build:ci-windows-msvc --action_env=VCINSTALLDIR
build:ci-windows-msvc --host_action_env=VCINSTALLDIR
# Release profile settings are also defined in codex-rs/Cargo.toml.
# Release profile settings are also defined in akode-rs/Cargo.toml.
# runtime_package.bzl applies this profile to archive dependencies automatically.
# Packaging extracts symbols before stripping; the Rust toolchains retain
# line tables and use split-debuginfo=off. opt mode selects Rust opt-level=3,

4
.gitattributes vendored
View File

@@ -1,4 +1,4 @@
codex-rs/app-server-protocol/schema/** linguist-generated
codex-rs/hooks/schema/generated/** linguist-generated
akode-rs/app-server-protocol/schema/** linguist-generated
akode-rs/hooks/schema/generated/** linguist-generated
third_party/voice/sources.json text eol=lf
patches/v8_array_sort_elements_kind.patch text eol=lf

2
.gitignore vendored
View File

@@ -16,7 +16,7 @@ out/
storybook-static/
# ignore README for publishing
codex-cli/README.md
akode-cli/README.md
# ignore Nix derivation results
result

View File

@@ -347,8 +347,8 @@ register_toolchains("//bazel/toolchains/prost:toolchain")
crate = use_extension("@rules_rs//rs:extensions.bzl", "crate")
crate.from_cargo(
cargo_lock = "//codex-rs:Cargo.lock",
cargo_toml = "//codex-rs:Cargo.toml",
cargo_lock = "//akode-rs:Cargo.lock",
cargo_toml = "//akode-rs:Cargo.toml",
platform_triples = [
"aarch64-unknown-linux-gnu",
"aarch64-unknown-linux-musl",
@@ -386,7 +386,7 @@ crate.from_cargo(
bazel_dep(name = "zstd", version = "1.5.7.bcr.2")
crate.annotation(
# Keep Windows proxy authentication aligned with codex-rs/.cargo/config.toml.
# Keep Windows proxy authentication aligned with akode-rs/.cargo/config.toml.
build_script_env = {"CFLAGS": "-DCURL_ENABLE_NTLM"},
crate = "curl-sys",
)
@@ -660,7 +660,7 @@ crate.annotation(
"CMAKE": "$${pwd}/$(CMAKE)",
"CMAKE_GENERATOR": "Ninja",
"CMAKE_TOOLCHAIN_FILE": "$(execpath @@//third_party/voice:opus-toolchain.cmake)",
"CODEX_VOICE_NINJA": "$${pwd}/$(NINJA)",
"AKODE_VOICE_NINJA": "$${pwd}/$(NINJA)",
},
build_script_toolchains = [
"@rules_foreign_cc//toolchains:current_cmake_toolchain",

View File

@@ -1,81 +1,25 @@
<p align="center"><strong>Codex CLI</strong> is a coding agent from OpenAI that runs locally on your computer.
<p align="center">
<img src="https://github.com/openai/codex/blob/main/.github/codex-cli-splash.png" alt="Codex CLI splash" width="80%" />
</p>
</br>
If you want Codex in your code editor (VS Code, Cursor, Windsurf), <a href="https://developers.openai.com/codex/ide">install in your IDE.</a>
</br>If you want the desktop app experience, run <code>codex app</code> or visit <a href="https://chatgpt.com/codex?app-landing-page=true">the Codex App page</a>.
</br>If you are looking for the <em>cloud-based agent</em> from OpenAI, <strong>Codex Web</strong>, go to <a href="https://chatgpt.com/codex">chatgpt.com/codex</a>.</p>
# aKode (ramo `pulito`, sperimentale)
---
aKode e' un fork privato di [Codex CLI](https://github.com/openai/codex) (Apache-2.0, vedi `LICENSE` e `NOTICE`).
## Quickstart
Questo ramo riporta aKode allo stato di Codex originale, con soltanto:
### Installing and running Codex CLI
- **A** il nome: crate `akode-*`, cartelle `akode-rs/` e `akode-cli/`, binario `akode`, `~/.akode` (`AKODE_HOME`), variabili `AKODE_*`, testi per l'utente;
- **B** nessun contatto con OpenAI/ChatGPT e nessuna telemetria (login ChatGPT, provider OpenAI/Bedrock/GCP integrati, analytics, aggiornamenti verso terzi rimossi);
- **C** compatibilita' minima con un server locale: timeout dello stream a 30 minuti per i provider locali, nessun TCP keepalive, provider personalizzato (`[model_providers.<id>]`, chiave da `env_key`).
Run the following on Mac or Linux to install Codex CLI:
Non c'e' nessun provider predefinito: va dichiarato in `config.toml`. Esempio:
```shell
curl -fsSL https://chatgpt.com/codex/install.sh | sh
```toml
model_provider = "locale"
model = "<id del modello>"
[model_providers.locale]
name = "Server locale"
base_url = "http://192.168.40.25:8080/v1" # deve offrire POST /responses
env_key = "AKODE_LOCALE_API_KEY" # variabile d'ambiente con la chiave Bearer
```
Run the following on Windows to install Codex CLI:
Build: `cd akode-rs && cargo build --release -p akode-cli`.
```shell
powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"
```
The standalone installers download from `https://releases.openai.com/codex` by default and fall back to GitHub Releases if a metadata or asset download is unavailable. To force GitHub Releases, set `CODEX_INSTALLER_USE_RELEASES_OPENAI_COM` to `false` (`0` and `no` are also accepted):
```shell
curl -fsSL https://chatgpt.com/codex/install.sh | CODEX_INSTALLER_USE_RELEASES_OPENAI_COM=false sh
```
```powershell
$env:CODEX_INSTALLER_USE_RELEASES_OPENAI_COM='false'; irm https://chatgpt.com/codex/install.ps1 | iex
```
Codex CLI can also be installed via the following package managers:
```shell
# Install using npm
npm install -g @openai/codex
```
```shell
# Install using Homebrew
brew install --cask codex
```
Then simply run `codex` to get started.
<details>
<summary>You can also go to the <a href="https://github.com/openai/codex/releases/latest">latest GitHub Release</a> and download the appropriate binary for your platform.</summary>
Each GitHub Release contains many executables, but in practice, you likely want one of these:
- macOS
- Apple Silicon/arm64: `codex-aarch64-apple-darwin.tar.gz`
- x86_64 (older Mac hardware): `codex-x86_64-apple-darwin.tar.gz`
- Linux
- x86_64: `codex-x86_64-unknown-linux-musl.tar.gz`
- arm64: `codex-aarch64-unknown-linux-musl.tar.gz`
Each archive contains a single entry with the platform baked into the name (e.g., `codex-x86_64-unknown-linux-musl`), so you likely want to rename it to `codex` after extracting it.
</details>
### Using Codex with your ChatGPT plan
Run `codex` and select **Sign in with ChatGPT**. We recommend signing into your ChatGPT account to use Codex as part of your Plus, Pro, Business, Edu, or Enterprise plan. [Learn more about what's included in your ChatGPT plan](https://help.openai.com/en/articles/11369540-codex-in-chatgpt).
You can also use Codex with an API key, but this requires [additional setup](https://developers.openai.com/codex/auth#sign-in-with-an-api-key).
## Docs
- [**Codex Documentation**](https://developers.openai.com/codex)
- [**Contributing**](./docs/contributing.md)
- [**Installing & building**](./docs/install.md)
- [**Open source fund**](./docs/open-source-fund.md)
This repository is licensed under the [Apache-2.0 License](LICENSE).
La versione completa di aKode (v0.9.2) resta nel ramo `main` e nel tag `v0.9.2`.

302
akode-cli/bin/akode.js Executable file
View File

@@ -0,0 +1,302 @@
#!/usr/bin/env node
// Unified entry point for the Codex CLI.
import { spawn } from "node:child_process";
import { existsSync, readFileSync, realpathSync } from "fs";
import { createRequire } from "node:module";
import { constants } from "node:os";
import path from "path";
import { fileURLToPath } from "url";
// __dirname equivalent in ESM
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const require = createRequire(import.meta.url);
const codexPackageRoot = realpathSync(path.join(__dirname, ".."));
const PLATFORM_PACKAGE_BY_TARGET = {
"x86_64-unknown-linux-musl": "@openai/codex-linux-x64",
"aarch64-unknown-linux-musl": "@openai/codex-linux-arm64",
"x86_64-apple-darwin": "@openai/codex-darwin-x64",
"aarch64-apple-darwin": "@openai/codex-darwin-arm64",
"x86_64-pc-windows-msvc": "@openai/codex-win32-x64",
"aarch64-pc-windows-msvc": "@openai/codex-win32-arm64",
};
const { platform, arch } = process;
let targetTriple = null;
switch (platform) {
case "linux":
case "android":
switch (arch) {
case "x64":
targetTriple = "x86_64-unknown-linux-musl";
break;
case "arm64":
targetTriple = "aarch64-unknown-linux-musl";
break;
default:
break;
}
break;
case "darwin":
switch (arch) {
case "x64":
targetTriple = "x86_64-apple-darwin";
break;
case "arm64":
targetTriple = "aarch64-apple-darwin";
break;
default:
break;
}
break;
case "win32":
switch (arch) {
case "x64":
targetTriple = "x86_64-pc-windows-msvc";
break;
case "arm64":
targetTriple = "aarch64-pc-windows-msvc";
break;
default:
break;
}
break;
default:
break;
}
if (!targetTriple) {
throw new Error(`Unsupported platform: ${platform} (${arch})`);
}
const platformPackage = PLATFORM_PACKAGE_BY_TARGET[targetTriple];
if (!platformPackage) {
throw new Error(`Unsupported target triple: ${targetTriple}`);
}
function findCodexExecutable() {
let vendorRoot;
try {
const packageJsonPath = require.resolve(`${platformPackage}/package.json`);
vendorRoot = path.join(path.dirname(packageJsonPath), "vendor");
} catch {
vendorRoot = path.join(__dirname, "..", "vendor");
}
const codexExecutable = path.join(
vendorRoot,
targetTriple,
"bin",
process.platform === "win32" ? "akode.exe" : "akode",
);
if (existsSync(codexExecutable)) {
return codexExecutable;
}
const packageManager = detectPackageManager();
const updateCommand =
packageManager === "bun"
? "bun install -g @openai/codex@latest"
: packageManager === "pnpm"
? "pnpm add -g @openai/codex@latest"
: packageManager === "vite-plus"
? "vp install -g @openai/codex@latest"
: "npm install -g @openai/codex@latest";
throw new Error(
`Missing optional dependency ${platformPackage}. Reinstall Codex: ${updateCommand}`,
);
}
const binaryPath = findCodexExecutable();
function isPnpmOwnedCodexInstall(nodeModulesDir) {
if (!existsSync(path.join(nodeModulesDir, ".modules.yaml"))) {
return false;
}
try {
return (
realpathSync(path.join(nodeModulesDir, "@openai", "codex")) ===
codexPackageRoot
);
} catch {
return false;
}
}
function isVitePlusOwnedCodexInstall(packagesDir) {
if (path.basename(packagesDir) !== "packages") {
return false;
}
try {
const metadata = JSON.parse(
readFileSync(path.join(packagesDir, "@openai", "codex.json"), "utf8"),
);
if (metadata.name !== "@openai/codex") {
return false;
}
// Vite+ records the active global installation in packages/@openai/codex.json.
// Older installs have no ID or append a #-prefixed ID to the package name;
// newer installs put the ID in a subdirectory of the package prefix.
const installId = metadata.installId || "";
const installDir = installId.startsWith("#")
? path.join(packagesDir, `@openai/codex${installId}`)
: path.join(packagesDir, "@openai/codex", installId);
for (const nodeModulesDir of [
path.join(installDir, "lib", "node_modules"),
path.join(installDir, "node_modules"),
]) {
const packageRoot = path.join(nodeModulesDir, "@openai", "codex");
if (
existsSync(packageRoot) &&
realpathSync(packageRoot) === codexPackageRoot
) {
return true;
}
}
} catch {
// Missing or unreadable ownership metadata must not prevent Codex starting.
}
return false;
}
/**
* Use heuristics to detect the package manager that was used to install Codex
* in order to give the user a hint about how to update it.
*/
function detectPackageManager() {
// Package-manager ownership metadata can be several parents above the package.
// Search ancestors of both the canonical package root and lexical entrypoint
// because the package manager may link either path.
const entrypointDir = path.dirname(path.resolve(process.argv[1]));
for (const startDir of new Set([codexPackageRoot, entrypointDir])) {
const filesystemRoot = path.parse(startDir).root;
for (
let currentDir = startDir;
currentDir !== filesystemRoot;
currentDir = path.dirname(currentDir)
) {
if (isVitePlusOwnedCodexInstall(currentDir)) {
return "vite-plus";
}
if (isPnpmOwnedCodexInstall(path.join(currentDir, "node_modules"))) {
return "pnpm";
}
}
if (isPnpmOwnedCodexInstall(path.join(filesystemRoot, "node_modules"))) {
return "pnpm";
}
}
const userAgent = process.env.npm_config_user_agent || "";
if (/\bbun\//.test(userAgent)) {
return "bun";
}
const execPath = process.env.npm_execpath || "";
if (execPath.includes("bun")) {
return "bun";
}
if (
__dirname.includes(".bun/install/global") ||
__dirname.includes(".bun\\install\\global")
) {
return "bun";
}
return userAgent ? "npm" : null;
}
const packageManager = detectPackageManager();
const packageManagerEnvVar =
packageManager === "bun"
? "AKODE_MANAGED_BY_BUN"
: packageManager === "pnpm"
? "AKODE_MANAGED_BY_PNPM"
: packageManager === "vite-plus"
? "AKODE_MANAGED_BY_VITE_PLUS"
: "AKODE_MANAGED_BY_NPM";
const env = {
...process.env,
AKODE_MANAGED_PACKAGE_ROOT: codexPackageRoot,
};
delete env.AKODE_MANAGED_BY_NPM;
delete env.AKODE_MANAGED_BY_BUN;
delete env.AKODE_MANAGED_BY_PNPM;
delete env.AKODE_MANAGED_BY_VITE_PLUS;
env[packageManagerEnvVar] = "1";
// Replace Node so the native binary receives signals and exits directly.
// Node exposes execve on Windows too, but calling it there is unsupported.
if (process.platform !== "win32" && typeof process.execve === "function") {
// Node ignores SIGXFSZ, and ignored signals survive execve. Installing a
// handler lets execve restore the default disposition in the native binary.
process.on("SIGXFSZ", () => {});
process.execve(binaryPath, [binaryPath, ...process.argv.slice(2)], env);
}
// Older Node versions and Windows need a child process. Spawn asynchronously
// so Node can forward signals while the native binary is executing.
const child = spawn(binaryPath, process.argv.slice(2), {
stdio: "inherit",
env,
});
child.on("error", (err) => {
// Typically triggered when the binary is missing or not executable.
// Re-throwing here will terminate the parent with a non-zero exit code
// while still printing a helpful stack trace.
// eslint-disable-next-line no-console
console.error(err);
process.exit(1);
});
// Forward common termination signals to the child so that it shuts down
// gracefully. In the handler we temporarily disable the default behavior of
// exiting immediately; once the child has been signaled we simply wait for
// its exit event which will in turn terminate the parent (see below).
const forwardSignal = (signal) => {
if (child.killed) {
return;
}
try {
child.kill(signal);
} catch {
/* ignore */
}
};
["SIGINT", "SIGTERM", "SIGHUP"].forEach((sig) => {
process.on(sig, () => forwardSignal(sig));
});
// When the child exits, mirror its termination reason in the parent so that
// shell scripts and other tooling observe the correct exit status.
// Wrap the lifetime of the child process in a Promise so that we can await
// its termination in a structured way. The Promise resolves with an object
// describing how the child exited: either via exit code or due to a signal.
const childResult = await new Promise((resolve) => {
child.on("exit", (code, signal) => {
if (signal) {
resolve({ type: "signal", signal });
} else {
resolve({ type: "code", exitCode: code ?? 1 });
}
});
});
if (childResult.type === "signal") {
// Preserve a failure exit code even if Node ignores the re-emitted signal.
process.exitCode = 128 + constants.signals[childResult.signal];
process.removeAllListeners(childResult.signal);
process.kill(process.pid, childResult.signal);
} else {
process.exit(childResult.exitCode);
}

23
akode-cli/package.json Normal file
View File

@@ -0,0 +1,23 @@
{
"name": "akode",
"private": true,
"version": "0.0.0-dev",
"description": "aKode: local coding agent (derived from OpenAI Codex CLI).",
"license": "Apache-2.0",
"bin": {
"akode": "bin/akode.js"
},
"type": "module",
"engines": {
"node": ">=16"
},
"files": [
"bin/akode.js"
],
"repository": {
"type": "git",
"url": "git+https://github.com/openai/codex.git",
"directory": "akode-cli"
},
"packageManager": "pnpm@10.34.5+sha512.a4ee05f2f73658255bd6a89859c065a45c28a57daefae2c893a168ee2b73168c37b91e83e57ea67654ad03f03031746430e8bce38e362e042605fb8abc80192e"
}

View File

@@ -0,0 +1,29 @@
# npm releases
Use the staging helper in the repo root to generate npm tarballs for a release. For
example, to stage the CLI, responses proxy, and SDK packages for version `0.6.0`:
```bash
./scripts/stage_npm_packages.py \
--release-version 0.6.0 \
--package codex \
--package codex-responses-api-proxy \
--package codex-sdk
```
This downloads the required native package archive artifacts, hydrates `vendor/` for
each package, and writes tarballs to `dist/npm/`.
When `--package codex` is provided, the staging helper builds the lightweight
`@openai/codex` meta package plus all platform-native `@openai/codex` variants
that are later published under platform-specific dist-tags.
The npm variants omit the standalone `akode-exec-server` executable and its
`execServer` manifest entry to keep uploads within npm's package size limit.
They retain `codex exec-server` through the CLI, the code-mode host, and the
platform sandbox helpers. Canonical release archives retain the standalone
executor; npm staging changes only the package copy.
Direct `build_npm_package.py` invocations are still useful for package-specific
debugging, but native packages expect `--vendor-src` to point at a prehydrated
`vendor/` tree. Release packaging should use `scripts/stage_npm_packages.py`

View File

@@ -3,7 +3,7 @@ set -euo pipefail # Exit on error, undefined vars, and pipeline failures
IFS=$'\n\t' # Stricter word splitting
# Read allowed domains from file
ALLOWED_DOMAINS_FILE="/etc/codex/allowed_domains.txt"
ALLOWED_DOMAINS_FILE="/etc/akode/allowed_domains.txt"
if [ -f "$ALLOWED_DOMAINS_FILE" ]; then
ALLOWED_DOMAINS=()
while IFS= read -r domain; do

View File

@@ -62,22 +62,22 @@ docker run --name "$CONTAINER_NAME" -d \
--cap-add=NET_ADMIN \
--cap-add=NET_RAW \
-v "$WORK_DIR:/app$WORK_DIR" \
codex \
akode \
sleep infinity
# Write the allowed domains to a file in the container
docker exec --user root "$CONTAINER_NAME" bash -c "mkdir -p /etc/codex"
docker exec --user root "$CONTAINER_NAME" bash -c "mkdir -p /etc/akode"
for domain in $OPENAI_ALLOWED_DOMAINS; do
# Validate domain format to prevent injection
if [[ ! "$domain" =~ ^[a-zA-Z0-9][a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]; then
echo "Error: Invalid domain format: $domain"
exit 1
fi
echo "$domain" | docker exec --user root -i "$CONTAINER_NAME" bash -c "cat >> /etc/codex/allowed_domains.txt"
echo "$domain" | docker exec --user root -i "$CONTAINER_NAME" bash -c "cat >> /etc/akode/allowed_domains.txt"
done
# Set proper permissions on the domains file
docker exec --user root "$CONTAINER_NAME" bash -c "chmod 444 /etc/codex/allowed_domains.txt && chown root:root /etc/codex/allowed_domains.txt"
docker exec --user root "$CONTAINER_NAME" bash -c "chmod 444 /etc/akode/allowed_domains.txt && chown root:root /etc/akode/allowed_domains.txt"
# Initialize the firewall inside the container as root user
docker exec --user root "$CONTAINER_NAME" bash -c "/usr/local/bin/init_firewall.sh"
@@ -92,4 +92,4 @@ quoted_args=""
for arg in "$@"; do
quoted_args+=" $(printf '%q' "$arg")"
done
docker exec -it "$CONTAINER_NAME" bash -c "cd \"/app$WORK_DIR\" && codex --sandbox workspace-write --ask-for-approval on-request ${quoted_args}"
docker exec -it "$CONTAINER_NAME" bash -c "cd \"/app$WORK_DIR\" && akode --sandbox workspace-write --ask-for-approval on-request ${quoted_args}"

View File

@@ -1,4 +1,4 @@
// Run with CODEX_TEST_BINARY=/absolute/path/to/codex node --test codex-cli/tests/exit-status.test.mjs.
// Run with AKODE_TEST_BINARY=/absolute/path/to/codex node --test akode-cli/tests/exit-status.test.mjs.
import assert from "node:assert/strict";
import { execFileSync, spawn, spawnSync } from "node:child_process";
import { once } from "node:events";
@@ -22,8 +22,8 @@ test(
},
async () => {
assert.ok(
process.env.CODEX_TEST_BINARY,
"Set CODEX_TEST_BINARY to a built Codex binary",
process.env.AKODE_TEST_BINARY,
"Set AKODE_TEST_BINARY to a built Codex binary",
);
const directory = await mkdtemp(path.join(tmpdir(), "codex-npm-exit-"));
let child;
@@ -43,10 +43,10 @@ test(
const wrapper = path.join(directory, "bin", "codex.js");
await copyFile(new URL("../bin/codex.js", import.meta.url), wrapper);
await symlink(
path.resolve(process.env.CODEX_TEST_BINARY),
path.resolve(process.env.AKODE_TEST_BINARY),
path.join(bin, "codex"),
);
const env = { ...process.env, CODEX_HOME: home, CODEX_SQLITE_HOME: home };
const env = { ...process.env, AKODE_HOME: home, AKODE_SQLITE_HOME: home };
// A normal CLI argument error must retain its numeric exit status.
const invalid = spawnSync(

View File

@@ -16,7 +16,7 @@ ignore = [
"RUSTSEC-2026-0371", # zbus_names 3.0.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
"RUSTSEC-2026-0372", # zvariant_derive 4.2.0 via zbus 4.4.0 in Linux TUI and keyring/secret-service; remove when those paths migrate off the retired standalone crates
# Reviewed 2026-10-20.
"RUSTSEC-2026-0374", # basic-toml 0.1.10 via i18n-config/i18n-embed-fl under age 0.12.1 in codex-secrets; no patched release; remove when age's localization dependencies migrate off basic-toml
"RUSTSEC-2026-0374", # basic-toml 0.1.10 via i18n-config/i18n-embed-fl under age 0.12.1 in akode-secrets; no patched release; remove when age's localization dependencies migrate off basic-toml
"RUSTSEC-2026-0387", # crypto-bigint 0.5.5 via elliptic-curve 0.13.8 is used by age, AWS login, user verification, and WebRTC; timing leakage can affect private-key or session-secret operations; remove when these dependency paths use crypto-bigint >=0.7.6
# Reviewed 2026-10-26.
"RUSTSEC-2026-0391", # Codex, tonic and zip use zstd 0.13.3 without reusing borrowed contexts across streams. Remove when all paths use zstd >=0.14.3.
@@ -24,7 +24,7 @@ ignore = [
"RUSTSEC-2026-0403", # zstd 0.13.3 pulls in zstd-safe 7.2.4. Codex, tonic and zip use read decoders or initialized output buffers and discard output on error. Remove when all paths use zstd-safe >=8.2.0.
"RUSTSEC-2026-0410", # zstd-safe 7.2.4 pulls in zstd-sys 2.0.16. Its allocator bug only affects wasm32, and Codex ships native binaries. Remove when the lockfile uses zstd-sys >=2.1.2.
# Reviewed 2026-10-29.
"RUSTSEC-2026-0418", # libz-sys 1.1.29 via curl-sys/curl in codex-http-client is Windows-only and skips the affected probe; cc is locked to 1.2.55 (<1.6.0). Remove when libz-sys >=1.1.31; reassess if used on Unix with cc >=1.6.0.
"RUSTSEC-2026-0418", # libz-sys 1.1.29 via curl-sys/curl in akode-http-client is Windows-only and skips the affected probe; cc is locked to 1.2.55 (<1.6.0). Remove when libz-sys >=1.1.31; reassess if used on Unix with cc >=1.6.0.
# Reviewed 2026-11-05.
"RUSTSEC-2026-0441", # pin-utils 0.1.0 via AWS Smithy and loom under tokio-graceful; unmaintained with no patched release; remove when these paths drop pin-utils
]

View File

@@ -7,18 +7,18 @@ retries = 1
[[profile.default.overrides]]
# These cases cold-start a daemon before confirming a second launch with new settings.
filter = 'package(codex-cli) & binary(daemon_startup) & test(requires_confirmation_to_disable_)'
filter = 'package(akode-cli) & binary(daemon_startup) & test(requires_confirmation_to_disable_)'
slow-timeout = { period = "1m", terminate-after = 2 }
[[profile.default.overrides]]
# This case validates and copies both the initial and replacement debug package.
filter = 'package(codex-cli) & binary(=app_server_daemon_package) & test(=packaged_daemon_start_and_explicit_replacement)'
filter = 'package(akode-cli) & binary(=app_server_daemon_package) & test(=packaged_daemon_start_and_explicit_replacement)'
slow-timeout = { period = "1m", terminate-after = 3 }
threads-required = "num-test-threads"
[[profile.default.overrides]]
# These copies must not compete with other tests on the same runner.
filter = 'package(codex-cli) & binary(=app_server_daemon_package)'
filter = 'package(akode-cli) & binary(=app_server_daemon_package)'
slow-timeout = { period = "1m", terminate-after = 2 }
threads-required = "num-test-threads"
@@ -58,7 +58,7 @@ slow-timeout = { period = "1m", terminate-after = 4 }
[[profile.default.overrides]]
# This end-to-end case launches several CLI subprocesses and checks cloud policy.
filter = 'package(codex-exec) & test(worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume)'
filter = 'package(akode-exec) & test(worktree_start_and_fork_use_host_pool_and_preserve_legacy_resume)'
slow-timeout = { period = "30s", terminate-after = 4 }
[[profile.default.overrides]]
@@ -66,25 +66,25 @@ filter = 'test(approval_matrix_covers_all_modes)'
slow-timeout = { period = "30s", terminate-after = 2 }
[[profile.default.overrides]]
filter = 'package(codex-app-server-protocol) & (test(typescript_schema_fixtures_match_generated) | test(json_schema_fixtures_match_generated) | test(generate_ts_with_experimental_api_retains_experimental_entries) | test(generated_ts_optional_nullable_fields_only_in_params) | test(generate_json_filters_experimental_fields_and_methods))'
filter = 'package(akode-app-server-protocol) & (test(typescript_schema_fixtures_match_generated) | test(json_schema_fixtures_match_generated) | test(generate_ts_with_experimental_api_retains_experimental_entries) | test(generated_ts_optional_nullable_fields_only_in_params) | test(generate_json_filters_experimental_fields_and_methods))'
test-group = 'app_server_protocol_codegen'
[[profile.default.overrides]]
# These integration tests spawn a fresh app-server subprocess per case.
# Keep the library unit tests parallel.
filter = 'package(codex-app-server) & kind(test)'
filter = 'package(akode-app-server) & kind(test)'
test-group = 'app_server_integration'
[[profile.local.overrides]]
# Use up to four app-server subprocesses locally. The global nextest pool still
# limits this to the machine's logical CPU count.
filter = 'package(codex-app-server) & kind(test)'
filter = 'package(akode-app-server) & kind(test)'
test-group = 'app_server_integration_local'
[[profile.default.overrides]]
# These tests exercise full Codex turns and apply_patch execution, and they are
# sensitive to Windows runner process-startup stalls when many cases launch at once.
filter = 'package(codex-core) & kind(test) & test(apply_patch_cli)'
filter = 'package(akode-core) & kind(test) & test(apply_patch_cli)'
test-group = 'core_apply_patch_cli_integration'
[[profile.default.overrides]]
@@ -92,16 +92,16 @@ test-group = 'core_apply_patch_cli_integration'
# starting their timeout; their file lock still coordinates other test processes.
platform = 'cfg(windows)'
filter = '''
(package(codex-core) & binary(windows_sandbox)) |
(package(codex-exec-server) & test(file_system_elevated_relative_read_denial_uses_policy_cwd)) |
(package(codex-windows-sandbox) & test(elevated_non_tty_cmd_forwards_env_output_and_exit))
(package(akode-core) & binary(windows_sandbox)) |
(package(akode-exec-server) & test(file_system_elevated_relative_read_denial_uses_policy_cwd)) |
(package(akode-windows-sandbox) & test(elevated_non_tty_cmd_forwards_env_output_and_exit))
'''
test-group = 'windows_sandbox_accounts'
[[profile.default.overrides]]
# These tests create restricted-token Windows child processes and private desktops.
# Serialize them to avoid exhausting Windows session/global desktop resources in CI.
filter = 'package(codex-windows-sandbox) & test(legacy_)'
filter = 'package(akode-windows-sandbox) & test(legacy_)'
test-group = 'windows_sandbox_legacy_sessions'
[[profile.default.overrides]]

107
akode-rs/BUILD.bazel Normal file
View File

@@ -0,0 +1,107 @@
load("@bazel_skylib//rules:common_settings.bzl", "string_flag")
load("//bazel/rules:runtime_package.bzl", "runtime_archive")
exports_files([
"clippy.toml",
])
filegroup(
name = "workspace-files",
srcs = glob(
[
"*",
".cargo/**",
],
exclude = [
"BUILD.bazel",
],
),
visibility = ["//visibility:public"],
)
test_suite(
name = "e2e-benchmarks",
tags = ["manual"],
tests = [
"//akode-rs/cli:codex-help-bench",
],
visibility = ["//visibility:public"],
)
string_flag(
name = "runtime_package_build_mode",
build_setting_default = "release",
values = [
"release",
"debug",
],
visibility = ["//visibility:public"],
)
alias(
name = "runtime_package",
actual = ":runtime_package_combined",
tags = ["manual"],
visibility = ["//visibility:public"],
)
# These targets produce flat staging archives for the existing signing and
# packaging steps. Release builds retain their binaries and debug symbols.
runtime_archive(
name = "runtime_package_combined",
srcs = [
"//akode-rs/app-server:release_files",
"//akode-rs/cli:release_files",
"//akode-rs/code-mode-host:release_files",
"//akode-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//akode-rs/bwrap:release_files"],
"@platforms//os:windows": [
"//akode-rs/windows-sandbox-rs:command-runner-release_files",
"//akode-rs/windows-sandbox-rs:sandbox-setup-release_files",
],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_primary",
srcs = [
"//akode-rs/cli:release_files",
"//akode-rs/code-mode-host:release_files",
"//akode-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//akode-rs/bwrap:release_files"],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_app-server",
srcs = [
"//akode-rs/app-server:release_files",
"//akode-rs/code-mode-host:release_files",
"//akode-rs/exec-server-cli:release_files",
] + select({
"@platforms//os:linux": ["//akode-rs/bwrap:release_files"],
"//conditions:default": [],
}),
tags = ["manual"],
visibility = ["//visibility:public"],
)
runtime_archive(
name = "runtime_package_helpers",
srcs = [
"//akode-rs/windows-sandbox-rs:command-runner-release_files",
"//akode-rs/windows-sandbox-rs:sandbox-setup-release_files",
"//akode-rs/windows-sandbox-service:release_files",
],
tags = ["manual"],
target_compatible_with = ["@platforms//os:windows"],
visibility = ["//visibility:public"],
)

File diff suppressed because it is too large Load Diff

656
akode-rs/Cargo.toml Normal file
View File

@@ -0,0 +1,656 @@
[workspace]
members = [
"aws-auth",
"agent-graph-store",
"agent-message-board-client",
"agent-message-board-host",
"agent-roles",
"bwrap",
"build-info",
"ansi-escape",
"attachment-store",
"async-utils",
"app-server",
"app-server-transport",
"app-server-daemon",
"app-server-client",
"app-server-protocol",
"app-server-protocol-noop-macros",
"app-server-test-client",
"apply-patch",
"arg0",
"feedback",
"features",
"install-context",
"code-mode",
"code-mode-host",
"code-mode-protocol",
"code-mode-runtime",
"plugin-host",
"akode-home",
"cli",
"collaboration-mode-templates",
"config",
"config-schema",
"context-fragments",
"shell-command",
"skills",
"core",
"core-api",
"core-plugin-common",
"core-plugins",
"diagnostics",
"direct-tool-timing",
"guardian-context",
"hooks",
"history",
"http-client",
"secrets",
"exec",
"file-system",
"exec-server-protocol",
"exec-server",
"exec-server-cli",
"exec-server/tests/support",
"execpolicy",
"ext/agent",
"ext/agent-message-board",
"ext/extension-api",
"ext/multi-env-copy-file",
"ext/goal",
"ext/git-attribution",
"ext/guardian-reviewer",
"ext/guardian-v2",
"ext/guardian-v3",
"ext/items",
"ext/memories",
"ext/mcp",
"ext/queue",
"ext/skills",
"ext/web-search",
"external-agent-migration",
"keyring-store",
"file-search",
"file-watcher",
"linux-sandbox",
"lmstudio",
"login",
"akode-mcp",
"memories/read",
"memories/write",
"mermaid",
"message-board",
"message-board-mcp",
"model-provider-info",
"mxc-sandbox",
"models-manager",
"network-proxy",
"ollama",
"process-hardening",
"realtime-webrtc",
"voice-host",
"protocol",
"protocol/tests/support",
"prompts",
"rollout",
"rollout-trace",
"rmcp-client",
"response-debug-context",
"sandboxing",
"stdio-to-uds",
"otel",
"tcp-tunnel",
"tui",
"user-verification",
"tools",
"v8-poc",
"websocket-auth",
"websocket-client",
"windows-sandbox-rs/tests/support",
"windows-sandbox-service",
"worktree",
"utils/absolute-path",
"utils/audio",
"utils/path-uri",
"utils/cargo-bin",
"git-utils",
"utils/cache",
"utils/critical-path",
"utils/git-discovery",
"utils/head-tail-buffer",
"utils/image",
"utils/json-to-toml",
"utils/home-dir",
"utils/process",
"utils/pty",
"utils/readiness",
"utils/redacted-string",
"utils/rustls-provider",
"utils/string",
"utils/cli",
"utils/elapsed",
"utils/sandbox-summary",
"utils/model-facing-id",
"utils/sleep-inhibitor",
"utils/approval-presets",
"utils/oss",
"utils/output-truncation",
"utils/path-utils",
"utils/plugins",
"utils/fuzzy-match",
"utils/stream-parser",
"utils/template",
"akode-client",
"akode-api",
"state",
"terminal-detection",
"test-binary-support",
"thread-manager-sample",
"thread-store",
"uds",
"akode-experimental-api-macros",
"plugin",
"model-provider",
]
resolver = "2"
[workspace.package]
version = "0.0.0"
# Track the edition for all workspace crates in one place. Individual
# crates can still override this value, but keeping it here means new
# crates created with `cargo new -w ...` automatically inherit the 2024
# edition.
edition = "2024"
license = "Apache-2.0"
[workspace.dependencies]
# Internal
akode-realtime-webrtc = { path = "realtime-webrtc" }
app_test_support = { path = "app-server/tests/common" }
akode-agent-graph-store = { path = "agent-graph-store" }
akode-agent-roles = { path = "agent-roles" }
akode-ansi-escape = { path = "ansi-escape" }
akode-api = { path = "akode-api" }
akode-attachment-store = { path = "attachment-store" }
akode-aws-auth = { path = "aws-auth" }
akode-app-server = { path = "app-server" }
akode-app-server-transport = { path = "app-server-transport" }
akode-app-server-daemon = { path = "app-server-daemon" }
akode-app-server-client = { path = "app-server-client" }
akode-app-server-protocol = { path = "app-server-protocol" }
akode-app-server-protocol-noop-macros = { path = "app-server-protocol-noop-macros" }
akode-app-server-test-client = { path = "app-server-test-client" }
akode-apply-patch = { path = "apply-patch" }
akode-arg0 = { path = "arg0" }
akode-async-utils = { path = "async-utils" }
akode-build-info = { path = "build-info" }
akode-client = { path = "akode-client" }
akode-collaboration-mode-templates = { path = "collaboration-mode-templates" }
akode-code-mode = { path = "code-mode" }
akode-code-mode-protocol = { path = "code-mode-protocol" }
akode-code-mode-runtime = { path = "code-mode-runtime" }
akode-plugin-host = { path = "plugin-host" }
akode-home = { path = "akode-home" }
akode-http-client = { path = "http-client" }
akode-websocket-auth = { path = "websocket-auth" }
akode-websocket-client = { path = "websocket-client" }
akode-config = { path = "config" }
akode-agent-message-board-client = { path = "agent-message-board-client" }
akode-agent-message-board-extension = { path = "ext/agent-message-board" }
akode-agent-message-board-host = { path = "agent-message-board-host" }
akode-message-board = { path = "message-board" }
akode-message-board-mcp = { path = "message-board-mcp" }
akode-context-fragments = { path = "context-fragments" }
akode-core = { path = "core" }
akode-core-api = { path = "core-api" }
akode-core-plugin-common = { path = "core-plugin-common" }
akode-core-plugins = { path = "core-plugins" }
akode-diagnostics = { path = "diagnostics" }
akode-direct-tool-timing = { path = "direct-tool-timing" }
akode-exec = { path = "exec" }
akode-file-system = { path = "file-system" }
akode-exec-server-protocol = { path = "exec-server-protocol" }
akode-exec-server = { path = "exec-server" }
akode-exec-server-cli = { path = "exec-server-cli" }
akode-exec-server-test-support = { path = "exec-server/tests/support" }
akode-execpolicy = { path = "execpolicy" }
akode-extension-api = { path = "ext/extension-api" }
akode-extension-items = { path = "ext/items" }
akode-multi-env-copy-file = { path = "ext/multi-env-copy-file" }
akode-goal-extension = { path = "ext/goal" }
akode-git-attribution = { path = "ext/git-attribution" }
akode-guardian-reviewer = { path = "ext/guardian-reviewer" }
akode-guardian-v2 = { path = "ext/guardian-v2" }
akode-guardian-v3 = { path = "ext/guardian-v3" }
akode-external-agent-migration = { path = "external-agent-migration" }
akode-experimental-api-macros = { path = "akode-experimental-api-macros" }
akode-features = { path = "features" }
akode-feedback = { path = "feedback" }
akode-install-context = { path = "install-context" }
akode-file-search = { path = "file-search" }
akode-file-watcher = { path = "file-watcher" }
akode-git-utils = { path = "git-utils" }
akode-guardian-context = { path = "guardian-context" }
akode-hooks = { path = "hooks" }
akode-history = { path = "history" }
akode-keyring-store = { path = "keyring-store" }
akode-linux-sandbox = { path = "linux-sandbox" }
akode-lmstudio = { path = "lmstudio" }
akode-login = { path = "login" }
akode-mermaid = { path = "mermaid" }
akode-message-history = { path = "message-history" }
akode-memories-extension = { path = "ext/memories" }
akode-web-search-extension = { path = "ext/web-search" }
akode-memories-read = { path = "memories/read" }
akode-memories-write = { path = "memories/write" }
akode-mcp = { path = "akode-mcp" }
akode-mcp-extension = { path = "ext/mcp" }
akode-model-provider-info = { path = "model-provider-info" }
akode-models-manager = { path = "models-manager" }
akode-mxc-sandbox = { path = "mxc-sandbox" }
akode-network-proxy = { path = "network-proxy" }
akode-ollama = { path = "ollama" }
akode-otel = { path = "otel" }
akode-plugin = { path = "plugin" }
akode-model-provider = { path = "model-provider" }
akode-process-hardening = { path = "process-hardening" }
akode-protocol = { path = "protocol" }
akode-protocol-test-support = { path = "protocol/tests/support" }
akode-prompts = { path = "prompts" }
akode-queue-extension = { path = "ext/queue" }
akode-response-debug-context = { path = "response-debug-context" }
akode-rmcp-client = { path = "rmcp-client" }
akode-rollout = { path = "rollout" }
akode-rollout-trace = { path = "rollout-trace" }
akode-sandboxing = { path = "sandboxing" }
akode-secrets = { path = "secrets" }
akode-shell-command = { path = "shell-command" }
akode-skills-extension = { path = "ext/skills" }
akode-skills = { path = "skills" }
akode-state = { path = "state" }
akode-stdio-to-uds = { path = "stdio-to-uds" }
akode-terminal-detection = { path = "terminal-detection" }
akode-test-binary-support = { path = "test-binary-support" }
akode-thread-store = { path = "thread-store" }
akode-tools = { path = "tools" }
akode-tcp-tunnel = { path = "tcp-tunnel" }
akode-tui = { path = "tui" }
akode-uds = { path = "uds" }
akode-utils-absolute-path = { path = "utils/absolute-path" }
akode-utils-approval-presets = { path = "utils/approval-presets" }
akode-utils-audio = { path = "utils/audio" }
akode-utils-cache = { path = "utils/cache" }
akode-utils-cargo-bin = { path = "utils/cargo-bin" }
akode-utils-cli = { path = "utils/cli" }
akode-utils-critical-path = { path = "utils/critical-path" }
akode-utils-elapsed = { path = "utils/elapsed" }
akode-utils-fuzzy-match = { path = "utils/fuzzy-match" }
akode-utils-git-discovery = { path = "utils/git-discovery" }
akode-utils-head-tail-buffer = { path = "utils/head-tail-buffer" }
akode-utils-home-dir = { path = "utils/home-dir" }
akode-utils-image = { path = "utils/image" }
akode-utils-json-to-toml = { path = "utils/json-to-toml" }
akode-utils-oss = { path = "utils/oss" }
akode-utils-output-truncation = { path = "utils/output-truncation" }
akode-utils-path = { path = "utils/path-utils" }
akode-utils-path-uri = { path = "utils/path-uri" }
akode-utils-plugins = { path = "utils/plugins" }
akode-utils-process = { path = "utils/process" }
akode-utils-pty = { path = "utils/pty" }
akode-utils-redacted-string = { path = "utils/redacted-string" }
akode-utils-rustls-provider = { path = "utils/rustls-provider" }
akode-utils-sandbox-summary = { path = "utils/sandbox-summary" }
akode-worktree = { path = "worktree" }
akode-utils-sleep-inhibitor = { path = "utils/sleep-inhibitor" }
akode-utils-stream-parser = { path = "utils/stream-parser" }
akode-utils-string = { path = "utils/string" }
akode-utils-template = { path = "utils/template" }
akode-user-verification = { path = "user-verification" }
akode-v8-poc = { path = "v8-poc" }
akode-windows-sandbox = { path = "windows-sandbox-rs" }
akode-windows-sandbox-test-support = { path = "windows-sandbox-rs/tests/support" }
core_test_support = { path = "core/tests/common" }
# External
age = "0.12.1"
ansi-to-tui = "8.0.1"
anyhow = "1"
arboard = { version = "3", features = ["wayland-data-control"] }
arc-swap = "1.9.0"
assert_cmd = "2"
assert_matches = "1.5.0"
async-channel = "2.3.1"
async-io = "2.6.0"
async-stream = "0.3.6"
aws-config = "1"
aws-credential-types = "1"
aws-sigv4 = "1"
aws-smithy-runtime-api = { version = "1", features = ["client", "http-1x"] }
aws-smithy-types = { version = "1", features = ["http-body-1-x"] }
aws-types = "1"
axum = { version = "0.8", default-features = false }
base64 = "0.22.1"
bitflags = "2.13.1"
blake3 = "1.8.2"
bm25 = "2.3.2"
bytes = "1.10.1"
caseless = "0.2.2"
chardetng = "0.1.17"
chrono = "0.4.43"
clap = "4"
clap_complete = "4"
clatter = { version = "2.2.0", default-features = false, features = [
"alloc",
"getrandom",
"use-25519",
"use-aes-gcm",
"use-rust-crypto-ml-kem",
"use-sha",
] }
color-eyre = "0.6.3"
constant_time_eq = "0.3.1"
crossbeam-channel = "0.5.15"
crypto_box = { version = "0.9.1", features = ["seal"] }
crossterm = "0.29.0"
ctor = "0.6.3"
deno_core_icudata = "0.78.0"
derive_more = "2"
diffy = "0.4.2"
dirs = "6"
divan = "0.1.21"
dns-lookup = "3.0.1"
dotenvy = "0.15.7"
dunce = "1.0.4"
ed25519-dalek = { version = "2.2.0", features = ["pkcs8"] }
encoding_rs = "0.8.35"
eventsource-stream = "0.2.3"
file-id = "0.2.3"
flatbuffers = "25"
flate2 = "1.1.8"
futures = { version = "0.3", default-features = false }
gethostname = "1.1.0"
gix = { version = "0.89.0", default-features = false, features = ["sha1"] }
gix-url = "0.40.0"
glob = "0.3"
globset = "0.4"
hmac = "0.12.1"
http = "1.3.1"
httpdate = "1.0.3"
hyper-util = { version = "0.1.20", features = ["tokio"] }
iana-time-zone = "0.1.64"
icu_decimal = "2.1"
icu_locale_core = "2.1"
icu_provider = { version = "2.1", features = ["sync"] }
ignore = "0.4.30"
image = { version = "^0.25.9", default-features = false }
include_dir = "0.7.4"
indexmap = "2.12.0"
insta = "1.46.3"
inventory = "0.3.19"
itertools = "0.14.0"
jsonptr = { version = "0.7.1", default-features = false }
jsonwebtoken = "9.3.1"
keyring = { version = "3.6", default-features = false }
landlock = "0.4.4"
lazy_static = "1"
libc = "0.2.182"
# Keep SQLx's bundled SQLite on a version containing the WAL-reset corruption fix:
# https://www.sqlite.org/wal.html#the_wal_reset_bug
libsqlite3-sys = { version = "0.37", default-features = false }
linkify = "0.11"
log = "0.4"
lru = "0.18.2"
maplit = "1.0.2"
memchr = "2.7.6"
mime_guess = "2.0.5"
multimap = "0.10.0"
mxc-sdk = { git = "https://github.com/microsoft/mxc", rev = "b21120168d70befe12356411423266bfef168446" }
notify = "8.2.0"
nucleo = { git = "https://github.com/helix-editor/nucleo.git", rev = "4253de9faabb4e5c6d81d946a5e35a90f87347ee" }
once_cell = "1.20.2"
openssl-sys = "*"
opentelemetry = "0.31.0"
opentelemetry-semantic-conventions = "0.31.0"
opentelemetry_sdk = "0.31.0"
os_info = "3.12.0"
owo-colors = "4.3.0"
pathdiff = "0.2"
portable-pty = "0.9.0"
predicates = "3"
pretty_assertions = "1.4.1"
pulldown-cmark = { version = "0.10", default-features = false }
quick-xml = "0.41.0"
rand = "0.9"
rand_regex = "0.18.1"
ratatui = { version = "0.30.2", default-features = false, features = [
"crossterm",
"layout-cache",
"underline-color",
] }
ratatui-macros = "0.7.2"
rcgen = { version = "0.14.7", default-features = false, features = [
"aws_lc_rs",
"pem",
] }
regex = "1.12.3"
regex-automata = { version = "0.4.13", default-features = false, features = ["std", "syntax", "unicode", "nfa-pikevm"] }
regex-lite = "0.1.8"
regex-syntax = "0.8.8"
reqwest = { version = "0.12", features = ["cookies"] }
rmcp = { git = "https://github.com/modelcontextprotocol/rust-sdk", rev = "98a54789b80110ad210495c4ad845c89e1980471", version = "=3.5.1", default-features = false }
runfiles = { git = "https://github.com/dzbarsky/rules_rust", rev = "b56cbaa8465e74127f1ea216f813cd377295ad81" }
rustix = { version = "1.1.4", features = ["net"] }
rustls = { version = "0.23.46", default-features = false, features = [
"aws_lc_rs",
"std",
] }
rustls-native-certs = "0.8.3"
rustls-pki-types = "1.14.0"
schemars = "0.8.22"
seccompiler = "0.5.0"
semver = "1.0"
serde = { version = "1", features = ["rc"] }
serde_ignored = "0.1.14"
serde_json = "1"
serde_path_to_error = "0.1.20"
serde_with = "3.17"
serde_yaml = "0.9"
serial_test = "3.2.0"
sha1 = "0.10.6"
scopeguard = "1.2.0"
sha2 = "0.10"
shlex = "1.3.0"
signal-hook = "0.3.18"
similar = "2.7.0"
symphonia = { version = "0.6.0", default-features = false, features = [
"isomp4",
"mkv",
"mp3",
"ogg",
"wav",
] }
# Keep SQLx versions in sync; when bumping, audit the SQLite constructor deny list in clippy.toml.
sqlx = { version = "=0.9.0", default-features = false, features = [
"chrono",
"json",
"migrate",
"runtime-tokio",
"tls-rustls",
"sqlite-bundled",
"time",
"uuid",
] }
# Derives and migration embedding do not need query macros or a host SQLite driver.
sqlx-macros = { version = "=0.9.0", default-features = false, features = ["derive", "migrate"] }
# Preserve the target driver's query-description support without building it on the host.
sqlx-sqlite = { version = "=0.9.0", default-features = false, features = ["offline"] }
starlark = { version = "0.14.2", default-features = false }
strum = "0.27.2"
strum_macros = "0.28.0"
supports-color = "3.0.2"
syntect = "5"
sys-locale = "0.3.2"
system-configuration = "0.7"
tar = { version = "=0.4.45", default-features = false }
tempfile = "3.23.0"
test-log = "0.2.19"
textwrap = "0.16.2"
thiserror = "2.0.17"
tikv-jemallocator = "=0.7.0"
time = "0.3.47"
tiny_http = "0.12"
tokio = "1"
tokio-rustls = "0.26.4"
tokio-stream = "0.1.18"
tokio-test = "0.4"
tokio-tungstenite = { version = "0.28.0", features = [
"proxy",
"rustls-tls-native-roots",
] }
tokio-util = "0.7.18"
toml = "0.9.5"
toml_edit = "0.24.0"
tracing = "0.1.44"
tracing-appender = "0.2.3"
tracing-opentelemetry = "0.32.0"
tracing-subscriber = "0.3.22"
tracing-test = "0.2.5"
tonic = { version = "0.14.3", default-features = false, features = ["channel", "codegen"] }
tonic-prost = "0.14.3"
tree-sitter = "0.25.10"
tree-sitter-bash = "0.25"
tree-sitter-powershell = "=0.26.4"
ts-rs = "11"
tungstenite = { version = "0.27.0", features = ["deflate", "proxy"] }
uds_windows = "1.1.0"
unicode-linebreak = "0.1.5"
unicode-normalization = "0.1.25"
unicode-segmentation = "1.12.0"
unicode-width = "0.2"
url = "2"
urlencoding = "2.1"
uuid = "1"
v8 = "=152.2.0"
vt100 = "0.16.2"
vtparse = "0.6.2"
walkdir = "2.5.0"
webbrowser = "1.2.2"
which = "8"
whoami = "1.6.1"
wildmatch = "2.6.1"
winapi-util = "0.1.11"
windows-sys = "0.61.2"
winreg = "0.55.0"
# Keep the zip 2.x feature set. In zip 9, `bzip2-rs` selects the bzip2-sys
# backend we already build; the default selects libbz2-rs-sys instead.
zip = { version = "9.0.0", default-features = false, features = [
"aes-crypto",
"bzip2-rs",
"deflate",
"deflate64",
"lzma",
"time",
"xz",
"zstd",
] }
zstd = "0.13"
wiremock = "0.6"
zeroize = "1.8.2"
[workspace.lints]
rust = {}
[workspace.lints.clippy]
await_holding_invalid_type = "deny"
await_holding_lock = "deny"
disallowed_methods = "deny"
expect_used = "deny"
identity_op = "deny"
manual_clamp = "deny"
manual_filter = "deny"
manual_find = "deny"
manual_flatten = "deny"
manual_map = "deny"
manual_memcpy = "deny"
manual_non_exhaustive = "deny"
manual_ok_or = "deny"
manual_range_contains = "deny"
manual_retain = "deny"
manual_strip = "deny"
manual_try_fold = "deny"
manual_unwrap_or = "deny"
needless_borrow = "deny"
needless_borrowed_reference = "deny"
needless_collect = "deny"
needless_late_init = "deny"
needless_option_as_deref = "deny"
needless_question_mark = "deny"
needless_update = "deny"
redundant_clone = "deny"
redundant_closure = "deny"
redundant_closure_for_method_calls = "deny"
redundant_static_lifetimes = "deny"
trivially_copy_pass_by_ref = "deny"
uninlined_format_args = "deny"
unnecessary_filter_map = "deny"
unnecessary_lazy_evaluations = "deny"
unnecessary_sort_by = "deny"
unnecessary_to_owned = "deny"
unwrap_used = "deny"
# cargo-shear cannot see the platform-specific openssl-sys usage, so we
# silence the false positive here instead of deleting a real dependency.
[workspace.metadata.cargo-shear]
ignored = [
"icu_provider",
"openssl-sys",
"akode-v8-poc",
]
[profile.dev]
# The test profile inherits dev. Keep source locations in ordinary builds;
# use CARGO_PROFILE_DEV_DEBUG=full (or CARGO_PROFILE_TEST_DEBUG=full) for locals.
debug = "line-tables-only"
[profile.dev-small]
inherits = "dev"
opt-level = 0
debug = "none"
strip = "symbols"
[profile.release]
lto = "thin"
debug = "line-tables-only"
split-debuginfo = "off"
# Keep release binaries symbolicateable until packaging has archived the
# sidecar symbols and stripped the binaries.
strip = false
# Balance parallel release code generation against binary size.
codegen-units = 4
[profile.profiling]
inherits = "release"
debug = "full"
lto = false
strip = false
[profile.ci-test]
# Reduce binary size to reduce disk pressure.
inherits = "test"
opt-level = 0
[patch.crates-io]
# Uncomment to debug local changes.
# ratatui = { path = "../../ratatui" }
crossterm = { git = "https://github.com/openai-oss-forks/crossterm", rev = "ed1cdab335221515706178d68495bba2aed1924f" }
tokio-tungstenite = { git = "https://github.com/openai-oss-forks/tokio-tungstenite", rev = "02cb49fa827411e9279e3688d19ab9e82661b0e8" }
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "db4be399bc1b8b5de2edb46c7187834edabf7e30" }
v8 = { git = "https://github.com/openai-oss-forks/rusty_v8.git", rev = "90a65f887a0c0f048f3784afbcb320b373c8a2e0" }
# Uncomment to debug local changes.
# rmcp = { path = "../../rust-sdk/crates/rmcp" }
[patch."ssh://git@github.com/openai-oss-forks/tungstenite-rs.git"]
tungstenite = { git = "https://github.com/openai-oss-forks/tungstenite-rs", rev = "db4be399bc1b8b5de2edb46c7187834edabf7e30" }

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-graph-store",
crate_name = "akode_agent_graph_store",
)

View File

@@ -0,0 +1,26 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-agent-graph-store"
version.workspace = true
[lib]
name = "akode_agent_graph_store"
path = "src/lib.rs"
doctest = false
[lints]
workspace = true
[dependencies]
akode-protocol = { workspace = true }
akode-state = { workspace = true }
serde = { workspace = true, features = ["derive"] }
thiserror = { workspace = true }
[dev-dependencies]
akode-utils-absolute-path = { workspace = true }
pretty_assertions = { workspace = true }
serde_json = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread", "sync"] }

View File

@@ -0,0 +1,344 @@
use akode_protocol::ThreadId;
use akode_state::StateRuntime;
use std::sync::Arc;
use crate::AgentGraphStore;
use crate::AgentGraphStoreError;
use crate::AgentGraphStoreFuture;
use crate::ThreadSpawnEdgeStatus;
/// SQLite-backed implementation of [`AgentGraphStore`] using an existing state runtime.
#[derive(Clone)]
pub struct LocalAgentGraphStore {
state_db: Arc<StateRuntime>,
}
impl std::fmt::Debug for LocalAgentGraphStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LocalAgentGraphStore")
.field("sqlite", self.state_db.sqlite())
.finish_non_exhaustive()
}
}
impl LocalAgentGraphStore {
/// Create a local graph store from an already-initialized state runtime.
pub fn new(state_db: Arc<StateRuntime>) -> Self {
Self { state_db }
}
}
impl AgentGraphStore for LocalAgentGraphStore {
fn upsert_thread_spawn_edge(
&self,
parent_thread_id: ThreadId,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
self.state_db
.upsert_thread_spawn_edge(
parent_thread_id,
child_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error)
})
}
fn set_thread_spawn_edge_status(
&self,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()> {
Box::pin(async move {
self.state_db
.set_thread_spawn_edge_status(child_thread_id, to_state_status(status))
.await
.map_err(internal_error)
})
}
fn list_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
Box::pin(async move {
if let Some(status) = status_filter {
return self
.state_db
.list_thread_spawn_children_with_status(
parent_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error);
}
self.state_db
.list_thread_spawn_children(parent_thread_id)
.await
.map_err(internal_error)
})
}
fn list_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>> {
Box::pin(async move {
match status_filter {
Some(status) => self
.state_db
.list_thread_spawn_descendants_with_status(
root_thread_id,
to_state_status(status),
)
.await
.map_err(internal_error),
None => self
.state_db
.list_thread_spawn_descendants(root_thread_id)
.await
.map_err(internal_error),
}
})
}
}
fn to_state_status(status: ThreadSpawnEdgeStatus) -> akode_state::DirectionalThreadSpawnEdgeStatus {
match status {
ThreadSpawnEdgeStatus::Open => akode_state::DirectionalThreadSpawnEdgeStatus::Open,
ThreadSpawnEdgeStatus::Closed => akode_state::DirectionalThreadSpawnEdgeStatus::Closed,
}
}
fn internal_error(err: impl std::fmt::Display) -> AgentGraphStoreError {
AgentGraphStoreError::Internal {
message: err.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use akode_state::DirectionalThreadSpawnEdgeStatus;
use akode_utils_absolute_path::test_support::PathExt;
use pretty_assertions::assert_eq;
use tempfile::TempDir;
struct TestRuntime {
state_db: Arc<StateRuntime>,
_codex_home: TempDir,
}
fn thread_id(suffix: u128) -> ThreadId {
ThreadId::from_string(&format!("00000000-0000-0000-0000-{suffix:012}"))
.expect("valid thread id")
}
async fn state_runtime() -> TestRuntime {
let codex_home = TempDir::new().expect("tempdir should be created");
let state_db = StateRuntime::init(
akode_state::SqliteConfig::new_for_testing(codex_home.path().abs()),
"test-provider".to_string(),
)
.await
.expect("state db should initialize");
TestRuntime {
state_db,
_codex_home: codex_home,
}
}
#[tokio::test]
async fn local_store_upserts_and_lists_direct_children_with_status_filters() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db.clone());
let parent_thread_id = thread_id(/*suffix*/ 1);
let first_child_thread_id = thread_id(/*suffix*/ 2);
let second_child_thread_id = thread_id(/*suffix*/ 3);
store
.upsert_thread_spawn_edge(
parent_thread_id,
second_child_thread_id,
ThreadSpawnEdgeStatus::Closed,
)
.await
.expect("closed child edge should insert");
store
.upsert_thread_spawn_edge(
parent_thread_id,
first_child_thread_id,
ThreadSpawnEdgeStatus::Open,
)
.await
.expect("open child edge should insert");
let all_children = store
.list_thread_spawn_children(parent_thread_id, /*status_filter*/ None)
.await
.expect("all children should load");
assert_eq!(
all_children,
vec![first_child_thread_id, second_child_thread_id]
);
let open_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open children should load");
let state_open_children = state_db
.list_thread_spawn_children_with_status(
parent_thread_id,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("state open children should load");
assert_eq!(open_children, state_open_children);
assert_eq!(open_children, vec![first_child_thread_id]);
let closed_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed children should load");
assert_eq!(closed_children, vec![second_child_thread_id]);
}
#[tokio::test]
async fn local_store_updates_edge_status() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db);
let parent_thread_id = thread_id(/*suffix*/ 10);
let child_thread_id = thread_id(/*suffix*/ 11);
store
.upsert_thread_spawn_edge(
parent_thread_id,
child_thread_id,
ThreadSpawnEdgeStatus::Open,
)
.await
.expect("child edge should insert");
store
.set_thread_spawn_edge_status(child_thread_id, ThreadSpawnEdgeStatus::Closed)
.await
.expect("child edge should close");
let open_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open children should load");
assert_eq!(open_children, Vec::<ThreadId>::new());
let closed_children = store
.list_thread_spawn_children(parent_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed children should load");
assert_eq!(closed_children, vec![child_thread_id]);
}
#[tokio::test]
async fn local_store_lists_descendants_breadth_first_with_status_filters() {
let fixture = state_runtime().await;
let state_db = fixture.state_db;
let store = LocalAgentGraphStore::new(state_db.clone());
let root_thread_id = thread_id(/*suffix*/ 20);
let later_child_thread_id = thread_id(/*suffix*/ 22);
let earlier_child_thread_id = thread_id(/*suffix*/ 21);
let closed_grandchild_thread_id = thread_id(/*suffix*/ 23);
let open_grandchild_thread_id = thread_id(/*suffix*/ 24);
let closed_child_thread_id = thread_id(/*suffix*/ 25);
let closed_great_grandchild_thread_id = thread_id(/*suffix*/ 26);
for (parent_thread_id, child_thread_id, status) in [
(
root_thread_id,
later_child_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
root_thread_id,
earlier_child_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
earlier_child_thread_id,
open_grandchild_thread_id,
ThreadSpawnEdgeStatus::Open,
),
(
later_child_thread_id,
closed_grandchild_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
(
root_thread_id,
closed_child_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
(
closed_child_thread_id,
closed_great_grandchild_thread_id,
ThreadSpawnEdgeStatus::Closed,
),
] {
store
.upsert_thread_spawn_edge(parent_thread_id, child_thread_id, status)
.await
.expect("edge should insert");
}
let all_descendants = store
.list_thread_spawn_descendants(root_thread_id, /*status_filter*/ None)
.await
.expect("all descendants should load");
assert_eq!(
all_descendants,
vec![
earlier_child_thread_id,
later_child_thread_id,
closed_child_thread_id,
closed_grandchild_thread_id,
open_grandchild_thread_id,
closed_great_grandchild_thread_id,
]
);
let open_descendants = store
.list_thread_spawn_descendants(root_thread_id, Some(ThreadSpawnEdgeStatus::Open))
.await
.expect("open descendants should load");
let state_open_descendants = state_db
.list_thread_spawn_descendants_with_status(
root_thread_id,
DirectionalThreadSpawnEdgeStatus::Open,
)
.await
.expect("state open descendants should load");
assert_eq!(open_descendants, state_open_descendants);
assert_eq!(
open_descendants,
vec![
earlier_child_thread_id,
later_child_thread_id,
open_grandchild_thread_id,
]
);
let closed_descendants = store
.list_thread_spawn_descendants(root_thread_id, Some(ThreadSpawnEdgeStatus::Closed))
.await
.expect("closed descendants should load");
assert_eq!(
closed_descendants,
vec![closed_child_thread_id, closed_great_grandchild_thread_id]
);
}
}

View File

@@ -0,0 +1,62 @@
use std::future::Future;
use std::pin::Pin;
use akode_protocol::ThreadId;
use crate::AgentGraphStoreResult;
use crate::ThreadSpawnEdgeStatus;
/// Future returned by [`AgentGraphStore`] operations.
pub type AgentGraphStoreFuture<'a, T> =
Pin<Box<dyn Future<Output = AgentGraphStoreResult<T>> + Send + 'a>>;
/// Storage-neutral boundary for persisted thread-spawn parent/child topology.
///
/// Implementations are expected to return stable ordering for list methods so callers can merge
/// persisted graph state with live in-memory state without introducing nondeterministic output.
pub trait AgentGraphStore: Send + Sync {
/// Insert or replace the directional parent/child edge for a spawned thread.
///
/// `child_thread_id` has at most one persisted parent. Re-inserting the same child should
/// update both the parent and status to match the supplied values.
/// The edge may be published before the child's metadata or history exists. A successful
/// write must make the child discoverable through the list methods.
fn upsert_thread_spawn_edge(
&self,
parent_thread_id: ThreadId,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()>;
/// Update the persisted lifecycle status of a spawned thread's incoming edge.
///
/// Implementations should treat missing children as a successful no-op.
fn set_thread_spawn_edge_status(
&self,
child_thread_id: ThreadId,
status: ThreadSpawnEdgeStatus,
) -> AgentGraphStoreFuture<'_, ()>;
/// List direct spawned children of a parent thread.
///
/// When `status_filter` is `Some`, only child edges with that exact status are returned. When
/// it is `None`, all direct child edges are returned regardless of status, including statuses
/// that may be added by a future store implementation.
fn list_thread_spawn_children(
&self,
parent_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>>;
/// List spawned descendants breadth-first by depth, then by thread id.
///
/// `status_filter` is applied to every traversed edge, not just to the returned descendants.
/// For example, `Some(Open)` walks only open edges, so descendants under a closed edge are not
/// included even if their own incoming edge is open. `None` walks and returns every persisted
/// edge regardless of status.
fn list_thread_spawn_descendants(
&self,
root_thread_id: ThreadId,
status_filter: Option<ThreadSpawnEdgeStatus>,
) -> AgentGraphStoreFuture<'_, Vec<ThreadId>>;
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-client",
crate_name = "akode_agent_message_board_client",
)

View File

@@ -0,0 +1,34 @@
[package]
name = "akode-agent-message-board-client"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
anyhow = { workspace = true }
chrono = { workspace = true, features = ["serde"] }
akode-message-board = { workspace = true }
akode-extension-api = { workspace = true }
akode-http-client = { workspace = true }
akode-protocol = { workspace = true }
eventsource-stream = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["rt", "time"] }
tokio-util = { workspace = true }
tracing = { workspace = true }
url = { workspace = true }
[dev-dependencies]
pretty_assertions = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
wiremock = { workspace = true }

View File

@@ -0,0 +1,437 @@
//! Typed remote implementation of the board contract. HTTP policy is supplied
//! by the caller; reads and writes never fall back to a private local board.
//! Live notification frames are bounded before SSE parsing.
use crate::protocol::AccessToken;
use crate::protocol::BoardNotification;
use crate::protocol::Call;
use crate::protocol::Failure;
use crate::protocol::MAX_BODY;
use crate::protocol::MAX_RESPONSE;
use crate::protocol::Operation;
use crate::protocol::PermissionDeniedDetails;
use crate::protocol::Registration;
use crate::protocol::Watch;
use anyhow::Context;
use chrono::DateTime;
use chrono::Utc;
use akode_http_client::HttpClient;
use akode_http_client::HttpResponse;
use akode_message_board::AgentMessageBoard;
use akode_message_board::AppendRequest;
use akode_message_board::ChannelPage;
use akode_message_board::ChannelQuery;
use akode_message_board::ChannelSummary;
use akode_message_board::CreateChannelRequest;
use akode_message_board::Page;
use akode_message_board::PermissionDenied;
use akode_message_board::PostContent;
use akode_message_board::PostMetadata;
use akode_message_board::PostPreview;
use akode_message_board::PostQuery;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::ReadThreadRequest;
use akode_message_board::SubscriptionRequest;
use akode_message_board::SubscriptionState;
use akode_message_board::ThreadPage;
use akode_message_board::ThreadQuery;
use akode_message_board::ThreadSummary;
use akode_message_board::UpsertChannelRequest;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::Result;
use eventsource_stream::Eventsource;
use futures::StreamExt;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use serde::de::DeserializeOwned;
use std::collections::HashMap;
use std::error::Error;
use std::sync::Arc;
use std::task::Poll;
use std::time::Duration;
use url::Url;
/// A client for one session's board. Use the shared HTTP client's configured
/// proxy and CA policy.
#[derive(Clone)]
pub struct RemoteAgentMessageBoard {
http: HttpClient,
board_url: Url,
board: SessionId,
token: AccessToken,
clock: Arc<dyn Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync>,
}
impl RemoteAgentMessageBoard {
/// Validate the HTTP(S) endpoint and append the board path to its optional path prefix.
pub fn new(
http: HttpClient,
endpoint: &str,
board: SessionId,
token: AccessToken,
) -> anyhow::Result<Self> {
let mut board_url = Url::parse(endpoint).context("invalid message-board endpoint")?;
anyhow::ensure!(
matches!(board_url.scheme(), "http" | "https") && board_url.host_str().is_some(),
"message-board endpoint must be an HTTP(S) URL"
);
anyhow::ensure!(
board_url.query().is_none() && board_url.fragment().is_none(),
"message-board endpoint must not contain a query or fragment"
);
board_url.set_path(&format!(
"{}/v1/boards/{board}",
board_url.path().trim_end_matches('/')
));
Ok(Self {
http,
board_url,
board,
token,
clock: Arc::new(|_| Box::pin(async { Ok(Utc::now()) })),
})
}
/// Supply the runtime's configured clock for research's simulated time.
pub fn with_clock(
mut self,
clock: impl Fn(ThreadId) -> BoxFuture<'static, Result<DateTime<Utc>>> + Send + Sync + 'static,
) -> Self {
self.clock = Arc::new(clock);
self
}
pub async fn create_board(&self) -> Result<SessionId> {
let response = self
.http
.request(http::Method::PUT, self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
pub async fn delete_board(&self) -> Result<()> {
let response = self
.http
.delete(self.url(""))
.bearer_auth(&self.token.0)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
if response.status().is_success() {
Ok(())
} else {
decode(response).await
}
}
/// Register the session's agents. The returned session token is stable on retry.
pub async fn register_members(
&self,
members: HashMap<ThreadId, AgentPath>,
) -> Result<AccessToken> {
let response = self
.http
.post(self.url("/members"))
.bearer_auth(&self.token.0)
.json(&Registration { members })
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
/// Opens a live receiver and waits until the service has registered it.
/// Setup, including readiness or an error body, has a 30-second deadline.
/// Drop it when the turn ends. Reopening does not replay earlier previews.
pub async fn notifications(
&self,
caller: ThreadId,
turn_id: String,
) -> Result<BoardNotifications> {
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 30);
let response = tokio::time::timeout_at(
deadline,
self.http
.post(self.url("/notifications"))
.bearer_auth(&self.token.0)
.json(&Watch {
caller,
turn_id: turn_id.clone(),
})
.send(),
)
.await
.map_err(transport_error)?
.map_err(transport_error)?;
if !response.status().is_success() {
tracing::warn!(
%caller, %turn_id,
http_status = response.status().as_u16(),
"Remote board notification request rejected"
);
tokio::time::timeout_at(deadline, decode::<()>(response))
.await
.map_err(transport_error)??;
return Err(transport_error("unexpected notification response"));
}
// Count wire bytes before the parser buffers them, resetting at blank lines.
// Defer CR handling so CRLF counts as one line ending even across chunks.
let mut frame_bytes = 0;
let mut line_empty = true;
let mut previous_cr = false;
// Validate before the SSE decoder can retain malformed UTF-8 indefinitely.
// Only an incomplete code point (at most three bytes) carries across chunks.
let mut utf8 = [0; 4];
let mut utf8_len = 0;
let mut chunks = Some(response.bytes_stream());
let mut events = futures::stream::poll_fn(move |cx| {
let Some(source) = chunks.as_mut() else {
return Poll::Ready(None);
};
let Some(chunk) = std::task::ready!(source.poll_next_unpin(cx)) else {
chunks = None;
return Poll::Ready(None);
};
let result = chunk.map_err(transport_error).and_then(|chunk| {
for &byte in chunk.iter() {
if !byte.is_ascii() || utf8_len > 0 {
utf8[utf8_len] = byte;
utf8_len += 1;
match std::str::from_utf8(&utf8[..utf8_len]) {
Ok(_) => utf8_len = 0,
Err(error) if error.error_len().is_some() => {
return Err(transport_error(error));
}
Err(_) => {}
}
}
if previous_cr && byte != b'\n' {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
frame_bytes += 1;
if frame_bytes > MAX_BODY {
return Err(transport_error("board SSE frame exceeds the service limit"));
}
match byte {
b'\n' => {
if line_empty {
frame_bytes = 0;
}
line_empty = true;
}
b'\r' => {}
_ => line_empty = false,
}
previous_cr = byte == b'\r';
}
Ok(chunk)
});
if result.is_err() {
chunks = None;
}
Poll::Ready(Some(result))
})
.eventsource();
let ready = tokio::time::timeout_at(deadline, events.next())
.await
.map_err(transport_error)?
.ok_or_else(|| transport_error("notification stream closed before readiness"))?
.map_err(transport_error)?;
if ready.event != "ready" {
return Err(transport_error(
"notification stream did not acknowledge readiness",
));
}
let stream = events.map(|event| event.map_err(transport_error)).boxed();
Ok(BoardNotifications {
caller,
turn_id,
stream,
})
}
fn url(&self, suffix: &str) -> Url {
let mut url = self.board_url.clone();
url.set_path(&format!("{}{suffix}", url.path()));
url
}
async fn call<T: DeserializeOwned>(&self, caller: ThreadId, operation: Operation) -> Result<T> {
let timestamp = match &operation {
Operation::CreateChannel(_) => Some((self.clock)(caller).await?),
// The service can replay a committed post without a fresh timestamp.
// A new post still requires one; never substitute wall-clock time.
Operation::Post(_) => (self.clock)(caller).await.ok(),
Operation::ListChannels(_)
| Operation::ListThreads(_)
| Operation::SearchPosts(_)
| Operation::ReadThread(_)
| Operation::ReadPost(_)
| Operation::SetSubscription(_) => None,
};
let call = Call {
caller,
timestamp,
operation,
};
let body = serde_json::to_vec(&call)?;
if body.len() > MAX_BODY {
return Err(CodexErr::InvalidRequest(
"board request exceeds the service limit".into(),
));
}
let response = self
.http
.post(self.url("/call"))
.bearer_auth(&self.token.0)
.header("content-type", "application/json")
.body(body)
.timeout(Duration::from_secs(/*secs*/ 30))
.send()
.await
.map_err(transport_error)?;
decode(response).await
}
}
macro_rules! operation {
($method:ident, $variant:ident, $input:ty, $output:ty) => {
fn $method(&self, caller: ThreadId, request: $input) -> BoxFuture<'_, Result<$output>> {
Box::pin(self.call(caller, Operation::$variant(request)))
}
};
}
impl AgentMessageBoard for RemoteAgentMessageBoard {
fn identity(&self) -> SessionId {
self.board
}
operation!(
create_channel,
CreateChannel,
CreateChannelRequest,
ChannelSummary
);
operation!(list_channels, ListChannels, ChannelQuery, ChannelPage);
fn upsert_channel(
&self,
_caller: ThreadId,
_request: UpsertChannelRequest,
) -> BoxFuture<'_, Result<()>> {
// The service has no description-update operation; creation has different semantics.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support channel upsert".into(),
))
})
}
operation!(post, Post, PostRequest, PostMetadata);
fn append(
&self,
_caller: ThreadId,
_request: AppendRequest,
) -> BoxFuture<'_, Result<PostMetadata>> {
// The remote protocol has no silent write operation. Posting is not equivalent.
Box::pin(async {
Err(CodexErr::InvalidRequest(
"remote message boards do not support silent append".into(),
))
})
}
operation!(list_threads, ListThreads, ThreadQuery, Page<ThreadSummary>);
operation!(search_posts, SearchPosts, PostQuery, Page<PostPreview>);
operation!(read_thread, ReadThread, ReadThreadRequest, ThreadPage);
operation!(read_post, ReadPost, ReadPostRequest, PostContent);
operation!(
set_subscription,
SetSubscription,
SubscriptionRequest,
SubscriptionState
);
}
/// One active turn's live receiver. Frames are checked against this receiver's
/// identity before accepted notices enter the host's ordinary message delivery.
pub struct BoardNotifications {
caller: ThreadId,
turn_id: String,
stream: BoxStream<'static, Result<eventsource_stream::Event>>,
}
impl BoardNotifications {
/// Skips invalid individual notices. Transport and framing failures remain errors.
pub async fn next(&mut self) -> Result<Option<BoardNotification>> {
while let Some(event) = self.stream.next().await.transpose()? {
let error_kind = if event.event != "notification" {
"unexpected_event"
} else {
match serde_json::from_str::<BoardNotification>(&event.data) {
Ok(notice) => {
if notice.recipient != self.caller || notice.turn_id != self.turn_id {
"wrong_recipient_or_turn"
} else if notice.post.text_preview.chars().count() > 150 {
"oversized_preview"
} else {
return Ok(Some(notice));
}
}
Err(_) => "invalid_json",
}
};
tracing::warn!(
caller = %self.caller, turn_id = %self.turn_id, error_kind,
"Skipping invalid remote board notification"
);
}
Ok(None)
}
}
async fn decode<T: DeserializeOwned>(mut response: HttpResponse) -> Result<T> {
let status = response.status();
let mut body = Vec::new();
while let Some(chunk) = response.chunk().await.map_err(transport_error)? {
if body.len().saturating_add(chunk.len()) > MAX_RESPONSE {
return Err(transport_error("board response exceeds the service limit"));
}
body.extend_from_slice(&chunk);
}
if !status.is_success() {
let failure: Failure = serde_json::from_slice(&body)
.with_context(|| format!("invalid board error response (HTTP {status})"))
.map_err(transport_error)?;
if status == http::StatusCode::FORBIDDEN && failure.code == "permission_denied" {
let details: PermissionDeniedDetails = serde_json::from_slice(&body)?;
return Err(PermissionDenied {
message: failure.message,
action: details.action,
resource: details.resource,
}
.into());
}
let message = format!("{}: {}", failure.code, failure.message);
return Err(if status.is_server_error() {
transport_error(message)
} else {
CodexErr::InvalidRequest(message)
});
}
serde_json::from_slice(&body).map_err(CodexErr::from)
}
fn transport_error(error: impl Into<Box<dyn Error + Send + Sync>>) -> CodexErr {
CodexErr::Io(std::io::Error::other(error))
}

View File

@@ -0,0 +1,122 @@
//! Receives live board previews for an active turn using the extension's turn hooks.
//! Provisioning and durable board ownership belong to the research host.
use crate::RemoteAgentMessageBoard;
use akode_extension_api::ExtensionData;
use akode_extension_api::ExtensionFuture;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::TurnAbortInput;
use akode_extension_api::TurnErrorInput;
use akode_extension_api::TurnLifecycleContributor;
use akode_extension_api::TurnStartInput;
use akode_extension_api::TurnStartPhase;
use akode_extension_api::TurnStopInput;
use akode_message_board::MessageBoardHost;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErrKind;
use futures::channel::oneshot;
use std::sync::Arc;
use std::time::Duration;
use tokio_util::task::AbortOnDropHandle;
type Binding = (Arc<RemoteAgentMessageBoard>, Arc<dyn MessageBoardHost>);
type ResolveBinding = dyn Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync;
struct Notifications(Box<ResolveBinding>);
struct Receiver {
_task: AbortOnDropHandle<()>,
}
impl TurnLifecycleContributor for Notifications {
fn turn_start_phase(&self, _thread_store: &ExtensionData) -> TurnStartPhase {
TurnStartPhase::RegularTaskStart
}
fn on_turn_start<'a>(&'a self, input: TurnStartInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
let Some((board, host)) = (self.0)(&input) else {
return;
};
let Ok(caller) = ThreadId::from_string(input.thread_store.level_id()) else {
return;
};
let turn_id = input.turn_id.to_owned();
let (first_attempt_tx, first_attempt_rx) = oneshot::channel();
input.turn_store.insert(Receiver {
_task: AbortOnDropHandle::new(tokio::spawn(async move {
let mut first_attempt_tx = Some(first_attempt_tx);
loop {
let connection = board.notifications(caller, turn_id.clone()).await;
if let Some(first_attempt_tx) = first_attempt_tx.take() {
let _ = first_attempt_tx.send(());
}
match connection {
Ok(mut stream) => loop {
match stream.next().await {
Ok(Some(notice)) => {
if let Err(error) = host.notify(caller, notice.post).await {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification delivery failed"
);
}
}
Ok(None) => break,
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification stream failed"
);
break;
}
}
},
Err(error) => {
tracing::warn!(
%caller, %turn_id,
error_kind = ?CodexErrKind::from(&error),
"Remote board notification connection failed"
);
}
}
// Reopen for future previews; the service does not replay missed ones.
tokio::time::sleep(Duration::from_secs(/*secs*/ 1)).await;
}
})),
});
// A healthy service is listening before inference. A failed first attempt
// releases startup while the same turn-owned receiver keeps retrying.
let _ = first_attempt_rx.await;
})
}
fn on_turn_stop<'a>(&'a self, input: TurnStopInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_abort<'a>(&'a self, input: TurnAbortInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
fn on_turn_error<'a>(&'a self, input: TurnErrorInput<'a>) -> ExtensionFuture<'a, ()> {
Box::pin(async move {
input.turn_store.remove::<Receiver>();
})
}
}
/// Installs live notification delivery. The host resolves the existing remote
/// client and delivery host. Accepted notices use the host's ordinary message policy.
/// The turn store owns the receiver and cancels it when the turn ends.
pub fn install_notifications<C: Sync>(
registry: &mut ExtensionRegistryBuilder<C>,
resolve: impl Fn(&TurnStartInput<'_>) -> Option<Binding> + Send + Sync + 'static,
) {
registry.turn_lifecycle_contributor(Arc::new(Notifications(Box::new(resolve))));
}

View File

@@ -0,0 +1,107 @@
//! Versioned service requests reuse board operations; only host identity travels separately.
use chrono::DateTime;
use chrono::Utc;
use akode_message_board::ChannelQuery;
use akode_message_board::CreateChannelRequest;
use akode_message_board::PostPreview;
use akode_message_board::PostQuery;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::ReadThreadRequest;
use akode_message_board::SubscriptionRequest;
use akode_message_board::ThreadQuery;
use akode_protocol::AgentPath;
use akode_protocol::ThreadId;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use std::collections::HashMap;
use std::fmt;
pub(crate) const MAX_BODY: usize = 512 * 1024;
pub(crate) const MAX_RESPONSE: usize = 1024 * 1024;
/// A host credential. Debug output must never reveal its contents.
#[derive(Clone, Serialize)]
#[serde(transparent)]
pub struct AccessToken(pub(crate) String);
impl AccessToken {
pub fn new(value: String) -> anyhow::Result<Self> {
anyhow::ensure!(
(32..=4096).contains(&value.len()),
"credentials must contain 32–4096 bytes"
);
anyhow::ensure!(
value.bytes().all(|b| b.is_ascii_graphic()),
"credential must be ASCII without whitespace"
);
Ok(Self(value))
}
}
impl<'de> Deserialize<'de> for AccessToken {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
impl fmt::Debug for AccessToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AccessToken([REDACTED])")
}
}
#[derive(Serialize)]
pub(crate) struct Registration {
pub(crate) members: HashMap<ThreadId, AgentPath>,
}
#[derive(Serialize)]
pub(crate) struct Call {
pub(crate) caller: ThreadId,
pub(crate) timestamp: Option<DateTime<Utc>>,
#[serde(flatten)]
pub(crate) operation: Operation,
}
#[derive(Serialize)]
#[serde(tag = "method", content = "params", rename_all = "snake_case")]
pub(crate) enum Operation {
CreateChannel(CreateChannelRequest),
ListChannels(ChannelQuery),
Post(PostRequest),
ListThreads(ThreadQuery),
SearchPosts(PostQuery),
ReadThread(ReadThreadRequest),
ReadPost(ReadPostRequest),
SetSubscription(SubscriptionRequest),
}
#[derive(Serialize)]
pub(crate) struct Watch {
pub(crate) caller: ThreadId,
pub(crate) turn_id: String,
}
/// A best-effort preview bound to the receiving turn. Hosts must atomically check
/// `turn_id` when admitting it; a received preview must never start a new turn.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct BoardNotification {
pub recipient: ThreadId,
pub turn_id: String,
pub post: PostPreview,
}
#[derive(Deserialize)]
pub(crate) struct Failure {
pub(crate) code: String,
pub(crate) message: String,
}
#[derive(Deserialize)]
pub(crate) struct PermissionDeniedDetails {
pub(crate) action: Option<String>,
pub(crate) resource: Option<String>,
}

View File

@@ -2,24 +2,24 @@
use chrono::DateTime;
use chrono::Utc;
use codex_agent_message_board_client::AccessToken;
use codex_agent_message_board_client::BoardNotification;
use codex_agent_message_board_client::RemoteAgentMessageBoard;
use codex_http_client::HttpClientBuilder;
use codex_message_board::AgentMessageBoard;
use codex_message_board::AppendRequest;
use codex_message_board::PostContent;
use codex_message_board::PostDestination;
use codex_message_board::PostMetadata;
use codex_message_board::PostPreview;
use codex_message_board::PostRequest;
use codex_message_board::ReadPostRequest;
use codex_message_board::UpsertChannelRequest;
use codex_protocol::AgentPath;
use codex_protocol::SessionId;
use codex_protocol::ThreadId;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use akode_agent_message_board_client::AccessToken;
use akode_agent_message_board_client::BoardNotification;
use akode_agent_message_board_client::RemoteAgentMessageBoard;
use akode_http_client::HttpClientBuilder;
use akode_message_board::AgentMessageBoard;
use akode_message_board::AppendRequest;
use akode_message_board::PostContent;
use akode_message_board::PostDestination;
use akode_message_board::PostMetadata;
use akode_message_board::PostPreview;
use akode_message_board::PostRequest;
use akode_message_board::ReadPostRequest;
use akode_message_board::UpsertChannelRequest;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::collections::HashMap;

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-message-board-host",
crate_name = "akode_agent_message_board_host",
)

View File

@@ -0,0 +1,25 @@
[package]
name = "akode-agent-message-board-host"
version.workspace = true
edition.workspace = true
license.workspace = true
[lib]
test = false
doctest = false
[lints]
workspace = true
[dependencies]
chrono = { workspace = true }
akode-agent-message-board-client = { workspace = true }
akode-agent-message-board-extension = { workspace = true }
akode-core = { workspace = true }
akode-extension-api = { workspace = true }
akode-features = { workspace = true }
akode-message-board = { workspace = true }
akode-protocol = { workspace = true }
akode-state = { workspace = true }
akode-thread-store = { workspace = true }
futures = { workspace = true }

View File

@@ -0,0 +1,261 @@
//! Supplies board host capabilities through the public Core runtime interfaces.
//!
//! The extension owns backend construction, storage and tool registration. This adapter
//! selects configuration and supplies host capabilities. It never starts or restores
//! recipients during lookup. Notifications use ordinary agent-message scheduling.
//! Permanent board deletion uses the thread store's existing host cleanup callback.
#![deny(clippy::print_stdout, clippy::print_stderr)]
use chrono::DateTime;
use chrono::Utc;
use akode_agent_message_board_client::RemoteAgentMessageBoard;
use akode_agent_message_board_extension::BoardBackend;
use akode_agent_message_board_extension::local_board_options;
use akode_core::CodexThread;
use akode_core::MULTI_AGENT_V2_NAMESPACE_DESCRIPTION;
use akode_core::ThreadManager;
use akode_core::config::Config;
use akode_extension_api::ExtensionRegistryBuilder;
use akode_extension_api::ThreadStartInput;
use akode_features::Feature;
use akode_message_board::LocalAgentMessageBoard;
use akode_message_board::LocalBoardConnection;
use akode_message_board::MessageBoardHost;
use akode_message_board::NotificationDelivery;
use akode_message_board::PostPreview;
use akode_protocol::AgentPath;
use akode_protocol::SessionId;
use akode_protocol::ThreadId;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::Result;
use akode_protocol::protocol::InterAgentCommunication;
use akode_protocol::protocol::Op;
use akode_state::SqliteConfig;
use akode_thread_store::ThreadStoreError;
use akode_thread_store::ThreadStoreResult;
use futures::future::BoxFuture;
use std::sync::Arc;
use std::sync::Weak;
/// Registers the configured board for opted-in MAv2 runtimes.
/// Training can share an in-memory board per tree, including ephemeral sessions.
pub fn install_agent_message_board(
registry: &mut ExtensionRegistryBuilder<Config>,
manager: Weak<ThreadManager>,
) {
akode_agent_message_board_client::install_notifications(registry, |input| {
let board = input.thread_store.get::<RemoteAgentMessageBoard>()?;
let host = input.thread_store.get::<LocalBoardHost>()?;
Some((
board,
Arc::new(LocalBoardHost {
remote_notifications: true,
..host.as_ref().clone()
}),
))
});
akode_agent_message_board_extension::install(
registry,
MULTI_AGENT_V2_NAMESPACE_DESCRIPTION,
|config: &Config| config.multi_agent_v2.tool_namespace.clone(),
move |input: &ThreadStartInput<'_, Config>, tree, caller| {
let config = input.config;
let connection = input.thread_store.get::<LocalBoardConnection>();
let in_memory = config.multi_agent_v2.message_board_in_memory;
let mcp =
config.features.enabled(Feature::AgentMessageBoardMcp) && connection.is_none();
// Automatic boards need MAv2. In-memory boards and explicit host
// connections also work for isolated, ephemeral runtimes.
if connection.is_none()
&& ((!config.features.enabled(Feature::AgentMessageBoard) && !mcp)
|| !config.features.enabled(Feature::MultiAgentV2)
|| (config.ephemeral
&& !mcp
&& !in_memory
&& config.multi_agent_v2.message_board_remote.is_none()))
{
return None;
}
let backend = if mcp {
BoardBackend::Mcp
} else if let Some(connection) = &connection {
BoardBackend::Connected(connection.clone())
} else if let Some(remote) = config.multi_agent_v2.message_board_remote.clone() {
BoardBackend::Remote {
config: remote,
http: config.http_client_factory(),
}
} else if in_memory {
BoardBackend::InMemory
} else {
BoardBackend::Local(config.sqlite_config().clone())
};
Some((
backend,
LocalBoardHost {
manager: manager.clone(),
tree,
caller,
remote_notifications: false,
connection,
},
))
},
);
}
/// Removes persisted agent-board data through the thread store's deletion callback.
/// Cleanup also applies when the board feature is currently disabled.
pub async fn delete_agent_message_boards(
sqlite: &SqliteConfig,
thread_ids: &[ThreadId],
) -> ThreadStoreResult<()> {
let boards = thread_ids
.iter()
.copied()
.map(Into::into)
.collect::<Vec<_>>();
LocalAgentMessageBoard::delete_boards(sqlite, &local_board_options(), &boards)
.await
.map_err(|err| ThreadStoreError::Internal {
message: format!("failed to delete agent message boards: {err}"),
})
}
#[derive(Clone)]
struct LocalBoardHost {
manager: Weak<ThreadManager>,
tree: SessionId,
caller: ThreadId,
remote_notifications: bool,
connection: Option<Arc<LocalBoardConnection>>,
}
impl LocalBoardHost {
async fn actor(&self, caller: ThreadId) -> Result<Arc<CodexThread>> {
let manager = self
.manager
.upgrade()
.ok_or_else(|| CodexErr::ThreadNotFound(caller))?;
if let Some(connection) = &self.connection {
return manager
.get_thread_with_extension::<LocalBoardConnection>(caller, |other| {
connection.same_board(other)
})
.await;
}
let actor = manager.get_thread(caller).await?;
if actor.startup_metadata().session_id != self.tree
|| actor
.thread_extension_data()
.get::<LocalBoardConnection>()
.is_some()
{
return Err(CodexErr::InvalidRequest(
"agent belongs to another message board".into(),
));
}
Ok(actor)
}
async fn registered_path(&self, actor: &CodexThread) -> Result<AgentPath> {
let caller = actor.startup_metadata().thread_id;
if let Some(connection) = &self.connection {
return connection.caller_path(caller);
}
let path = actor
.session_source()
.get_agent_path()
.or_else(|| (caller == ThreadId::from(self.tree)).then(AgentPath::root))
.ok_or_else(|| CodexErr::InvalidRequest("agent has no tree path".into()))?;
let resolved = actor.resolve_agent_reference(path.as_str()).await?;
if resolved != caller {
return Err(CodexErr::InvalidRequest(
"agent does not own its tree path".into(),
));
}
Ok(path)
}
}
impl MessageBoardHost for LocalBoardHost {
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
Box::pin(async move {
let actor = self.actor(caller).await?;
self.registered_path(&actor).await
})
}
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
Box::pin(async move {
if self.connection.is_some() {
let caller = path
.as_str()
.strip_prefix("/root/")
.and_then(|id| ThreadId::from_string(id).ok())
.ok_or_else(|| {
CodexErr::InvalidRequest("invalid connected board agent path".into())
})?;
return self
.actor(caller)
.await
.map(|actor| actor.startup_metadata().thread_id);
}
let actor = self.actor(self.caller).await?;
actor.resolve_agent_reference(path.as_str()).await
})
}
fn current_time(&self, caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
Box::pin(async move {
let actor = self.actor(caller).await?;
self.registered_path(&actor).await?;
actor.current_time().await
})
}
fn notify(
&self,
recipient_id: ThreadId,
post: PostPreview,
) -> BoxFuture<'_, Result<NotificationDelivery>> {
Box::pin(async move {
let recipient = match self.actor(recipient_id).await {
Ok(thread) => thread,
Err(error) if matches!(error.details(), CodexErrorDetails::ThreadNotFound(_)) => {
return Ok(NotificationDelivery::SkippedInactive);
}
Err(error) => return Err(error),
};
let recipient_path = self.registered_path(&recipient).await?;
let communication = InterAgentCommunication::new(
post.metadata.author.clone(),
recipient_path,
Vec::new(),
post.notification_text(),
/*trigger_turn*/ false,
);
// Remote metadata is untrusted. Skip an oversized notice without closing
// the receiver; the post remains available through the board tools.
if self.remote_notifications
&& communication.content.len()
+ communication.author.as_str().len()
+ communication.recipient.as_str().len()
> 1024
{
return Err(CodexErr::InvalidRequest(
"remote board notice exceeds the context budget".into(),
));
}
recipient
.submit(Op::InterAgentCommunication {
communication,
start_options: Default::default(),
})
.await?;
Ok(NotificationDelivery::Accepted)
})
}
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "agent-roles",
crate_name = "akode_agent_roles",
)

View File

@@ -0,0 +1,23 @@
[package]
edition.workspace = true
license.workspace = true
name = "akode-agent-roles"
version.workspace = true
[lib]
doctest = false
name = "akode_agent_roles"
path = "src/lib.rs"
test = false
[lints]
workspace = true
[dependencies]
akode-config = { workspace = true }
akode-file-system = { workspace = true }
akode-utils-absolute-path = { workspace = true }
akode-utils-path-uri = { workspace = true }
serde = { workspace = true, features = ["derive"] }
toml = { workspace = true, features = ["preserve_order"] }
tracing = { workspace = true }

View File

@@ -1,5 +1,5 @@
use codex_config::config_toml::ConfigToml;
use codex_utils_absolute_path::AbsolutePathBufGuard;
use akode_config::config_toml::ConfigToml;
use akode_utils_absolute_path::AbsolutePathBufGuard;
use serde::Deserialize;
use std::collections::BTreeSet;
use std::path::Path;

View File

@@ -0,0 +1,40 @@
use akode_file_system::ExecutorFileSystem;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_path_uri::PathUri;
use std::io;
use std::io::ErrorKind;
pub(crate) async fn collect_agent_role_files(
fs: &dyn ExecutorFileSystem,
dir: &AbsolutePathBuf,
) -> io::Result<Vec<AbsolutePathBuf>> {
let mut files = Vec::new();
let mut dirs = vec![dir.clone()];
while let Some(dir) = dirs.pop() {
let dir_uri = PathUri::from_abs_path(&dir);
let entries = match fs.read_directory(&dir_uri, /*sandbox*/ None).await {
Ok(entries) => entries,
Err(err) if err.kind() == ErrorKind::NotFound => continue,
Err(err) => return Err(err),
};
for entry in entries {
let path = dir.join(entry.file_name);
if entry.is_directory {
dirs.push(path);
continue;
}
if entry.is_file
&& path
.as_path()
.extension()
.is_some_and(|extension| extension == "toml")
{
files.push(path);
}
}
}
files.sort();
Ok(files)
}

View File

@@ -0,0 +1,335 @@
use crate::AgentRoleConfig;
use crate::ResolvedAgentRoleFile;
use crate::agent_role_config::normalize_agent_role_description;
use crate::agent_role_config::normalize_agent_role_nickname_candidates;
use crate::discovery::collect_agent_role_files;
use crate::parse_agent_role_file_contents;
use akode_config::ConfigLayerStack;
use akode_config::config_toml::AgentRoleToml;
use akode_config::config_toml::AgentsToml;
use akode_config::config_toml::ConfigToml;
use akode_file_system::ExecutorFileSystem;
use akode_file_system::GetMetadataOptions;
use akode_file_system::ReadFileOptions;
use akode_utils_absolute_path::AbsolutePathBuf;
use akode_utils_absolute_path::AbsolutePathBufGuard;
use akode_utils_path_uri::PathUri;
use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::path::Path;
use std::path::PathBuf;
use toml::Value as TomlValue;
pub async fn load_agent_roles(
fs: &dyn ExecutorFileSystem,
cfg: &ConfigToml,
config_layer_stack: &ConfigLayerStack,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut layers = config_layer_stack.layers_low_to_high().peekable();
if layers.peek().is_none() {
return load_agent_roles_without_layers(fs, cfg).await;
}
let mut roles: BTreeMap<String, AgentRoleConfig> = BTreeMap::new();
for layer in layers {
let mut layer_roles: BTreeMap<String, AgentRoleConfig> = BTreeMap::new();
let mut declared_role_files = BTreeSet::new();
let config_folder = layer.config_folder();
let agents_toml = match agents_toml_from_layer(&layer.config, config_folder.as_deref()) {
Ok(agents_toml) => agents_toml,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
None
}
};
if let Some(agents_toml) = agents_toml {
for (declared_role_name, role_toml) in &agents_toml.roles {
let (role_name, role) =
match read_declared_role(fs, declared_role_name, role_toml).await {
Ok(role) => role,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
continue;
}
};
if let Some(config_file) = role.config_file.clone() {
declared_role_files.insert(config_file);
}
if layer_roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` declared in the same config layer"
),
),
);
continue;
}
layer_roles.insert(role_name, role);
}
}
if let Some(config_folder) = layer.config_folder() {
for (role_name, role) in discover_agent_roles_in_dir(
fs,
&config_folder.join("agents"),
&declared_role_files,
startup_warnings,
)
.await?
{
if layer_roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` declared in the same config layer"
),
),
);
continue;
}
layer_roles.insert(role_name, role);
}
}
for (role_name, role) in layer_roles {
let mut merged_role = role;
if let Some(existing_role) = roles.get(&role_name) {
merge_missing_role_fields(&mut merged_role, existing_role);
}
if let Err(err) = validate_required_agent_role_description(
&role_name,
merged_role.description.as_deref(),
) {
push_agent_role_warning(startup_warnings, err);
continue;
}
roles.insert(role_name, merged_role);
}
}
Ok(roles)
}
fn push_agent_role_warning(startup_warnings: &mut Vec<String>, err: std::io::Error) {
let message = format!("Ignoring malformed agent role definition: {err}");
tracing::warn!("{message}");
startup_warnings.push(message);
}
async fn load_agent_roles_without_layers(
fs: &dyn ExecutorFileSystem,
cfg: &ConfigToml,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut roles = BTreeMap::new();
if let Some(agents_toml) = cfg.agents.as_ref() {
for (declared_role_name, role_toml) in &agents_toml.roles {
let (role_name, role) = read_declared_role(fs, declared_role_name, role_toml).await?;
validate_required_agent_role_description(&role_name, role.description.as_deref())?;
if roles.insert(role_name.clone(), role).is_some() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("duplicate agent role name `{role_name}` declared in config"),
));
}
}
}
Ok(roles)
}
async fn read_declared_role(
fs: &dyn ExecutorFileSystem,
declared_role_name: &str,
role_toml: &AgentRoleToml,
) -> std::io::Result<(String, AgentRoleConfig)> {
let mut role = agent_role_config_from_toml(fs, declared_role_name, role_toml).await?;
let mut role_name = declared_role_name.to_string();
if let Some(config_file) = role.config_file.as_deref() {
let config_file = AbsolutePathBuf::from_absolute_path(config_file)?;
let parsed_file =
read_resolved_agent_role_file(fs, &config_file, Some(declared_role_name)).await?;
role_name = parsed_file.role_name;
role.description = parsed_file.description.or(role.description);
role.nickname_candidates = parsed_file.nickname_candidates.or(role.nickname_candidates);
}
Ok((role_name, role))
}
fn merge_missing_role_fields(role: &mut AgentRoleConfig, fallback: &AgentRoleConfig) {
role.description = role.description.clone().or(fallback.description.clone());
role.config_file = role.config_file.clone().or(fallback.config_file.clone());
role.nickname_candidates = role
.nickname_candidates
.clone()
.or(fallback.nickname_candidates.clone());
}
fn agents_toml_from_layer(
layer_toml: &TomlValue,
config_base_dir: Option<&Path>,
) -> std::io::Result<Option<AgentsToml>> {
let Some(agents_toml) = layer_toml.get("agents") else {
return Ok(None);
};
// AbsolutePathBufGuard resolves relative paths while it remains in scope.
let _guard = config_base_dir.map(AbsolutePathBufGuard::new);
agents_toml
.clone()
.try_into()
.map(Some)
.map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))
}
async fn agent_role_config_from_toml(
fs: &dyn ExecutorFileSystem,
role_name: &str,
role: &AgentRoleToml,
) -> std::io::Result<AgentRoleConfig> {
let config_file = role
.config_file
.as_ref()
.map(AbsolutePathBuf::from_absolute_path)
.transpose()?;
validate_agent_role_config_file(fs, role_name, config_file.as_ref()).await?;
let description = normalize_agent_role_description(
&format!("agents.{role_name}.description"),
role.description.as_deref(),
)?;
let nickname_candidates = normalize_agent_role_nickname_candidates(
&format!("agents.{role_name}.nickname_candidates"),
role.nickname_candidates.as_deref(),
)?;
Ok(AgentRoleConfig {
description,
config_file: config_file.map(AbsolutePathBuf::into_path_buf),
nickname_candidates,
})
}
async fn read_resolved_agent_role_file(
fs: &dyn ExecutorFileSystem,
path: &AbsolutePathBuf,
role_name_hint: Option<&str>,
) -> std::io::Result<ResolvedAgentRoleFile> {
let path_uri = PathUri::from_abs_path(path);
let contents = fs
.read_file_text(&path_uri, ReadFileOptions::default(), /*sandbox*/ None)
.await?;
let config_base_dir = path.parent().unwrap_or_else(|| path.clone());
parse_agent_role_file_contents(
&contents,
path.as_path(),
config_base_dir.as_path(),
role_name_hint,
)
}
fn validate_required_agent_role_description(
role_name: &str,
description: Option<&str>,
) -> std::io::Result<()> {
if description.is_some() {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!("agent role `{role_name}` must define a description"),
))
}
}
async fn validate_agent_role_config_file(
fs: &dyn ExecutorFileSystem,
role_name: &str,
config_file: Option<&AbsolutePathBuf>,
) -> std::io::Result<()> {
let Some(config_file) = config_file else {
return Ok(());
};
let config_file_uri = PathUri::from_abs_path(config_file);
let metadata = fs
.get_metadata(
&config_file_uri,
GetMetadataOptions::default(),
/*sandbox*/ None,
)
.await
.map_err(|e| {
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agents.{role_name}.config_file must point to an existing file at {}: {e}",
config_file.as_path().display()
),
)
})?;
if metadata.is_file {
Ok(())
} else {
Err(std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"agents.{role_name}.config_file must point to a file: {}",
config_file.as_path().display()
),
))
}
}
async fn discover_agent_roles_in_dir(
fs: &dyn ExecutorFileSystem,
agents_dir: &AbsolutePathBuf,
declared_role_files: &BTreeSet<PathBuf>,
startup_warnings: &mut Vec<String>,
) -> std::io::Result<BTreeMap<String, AgentRoleConfig>> {
let mut roles = BTreeMap::new();
for agent_file in collect_agent_role_files(fs, agents_dir).await? {
if declared_role_files.contains(agent_file.as_path()) {
continue;
}
let parsed_file =
match read_resolved_agent_role_file(fs, &agent_file, /*role_name_hint*/ None).await {
Ok(parsed_file) => parsed_file,
Err(err) => {
push_agent_role_warning(startup_warnings, err);
continue;
}
};
let role_name = parsed_file.role_name;
if roles.contains_key(&role_name) {
push_agent_role_warning(
startup_warnings,
std::io::Error::new(
std::io::ErrorKind::InvalidInput,
format!(
"duplicate agent role name `{role_name}` discovered in {}",
agents_dir.as_path().display()
),
),
);
continue;
}
roles.insert(
role_name,
AgentRoleConfig {
description: parsed_file.description,
config_file: Some(agent_file.to_path_buf()),
nickname_candidates: parsed_file.nickname_candidates,
},
);
}
Ok(roles)
}

View File

@@ -0,0 +1,6 @@
load("//:defs.bzl", "codex_rust_crate")
codex_rust_crate(
name = "akode-api",
crate_name = "akode_api",
)

View File

@@ -0,0 +1,48 @@
[package]
name = "akode-api"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
async-channel = { workspace = true }
base64 = { workspace = true }
bytes = { workspace = true }
chrono = { workspace = true }
akode-client = { workspace = true }
akode-http-client = { workspace = true }
akode-protocol = { workspace = true }
akode-utils-rustls-provider = { workspace = true }
akode-websocket-client = { workspace = true }
futures = { workspace = true }
http = { workspace = true }
rustls = { workspace = true }
schemars = { workspace = true }
serde = { workspace = true, features = ["derive"] }
serde_json = { workspace = true, features = ["raw_value"] }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["fs", "macros", "net", "rt", "sync", "time"] }
tokio-tungstenite = { workspace = true }
tungstenite = { workspace = true }
tracing = { workspace = true }
eventsource-stream = { workspace = true }
regex-lite = { workspace = true }
tokio-util = { workspace = true, features = ["codec", "io"] }
url = { workspace = true }
uuid = { workspace = true }
[dev-dependencies]
anyhow = { workspace = true }
assert_matches = { workspace = true }
pretty_assertions = { workspace = true }
rcgen = { workspace = true }
tempfile = { workspace = true }
tokio = { workspace = true, features = ["test-util"] }
tokio-test = { workspace = true }
wiremock = { workspace = true }
[lints]
workspace = true
[lib]
doctest = false

View File

@@ -0,0 +1,30 @@
# akode-api
Typed clients for Codex/OpenAI APIs built on top of the generic transport in `akode-client`.
- Hosts the request/response models and request builders for Responses and related Codex APIs.
- Owns provider configuration (base URLs, headers, query params), auth header injection, retry tuning, and stream idle settings.
- Parses SSE streams into `ResponseEvent`/`ResponseStream`, including rate-limit snapshots and API-specific error mapping.
- Serves as the wire-level layer consumed by `akode-core`; higher layers handle auth refresh and business logic.
## Core interface
The public interface of this crate is intentionally small and uniform:
- **Responses endpoint**
- Input:
- `ResponsesApiRequest` for the request body (`model`, `input`, `tools`, `parallel_tool_calls`, reasoning/text controls).
- `ResponsesOptions` for transport/header concerns (`conversation_id`, `session_source`, `extra_headers`, `compression`, `turn_state`).
- Output: a `ResponseStream` of `ResponseEvent` (both re-exported from `common`).
- **Memory summarize endpoint**
- Input: `MemorySummarizeInput` (re-exported as `akode_api::MemorySummarizeInput`):
- `model: String`.
- `raw_memories: Vec<RawMemory>` (serialized as `traces` for wire compatibility).
- `RawMemory` includes `id`, `metadata.source_path`, and normalized `items`.
- `reasoning: Option<Reasoning>`.
- Output: `Vec<MemorySummarizeOutput>`.
- `MemoriesClient::summarize_input(&MemorySummarizeInput, extra_headers)` wraps JSON encoding and retry/telemetry wiring.
All HTTP details (URLs, headers, retry/backoff policies, SSE framing) are encapsulated in `akode-api` and `akode-client`. Callers construct prompts/inputs using protocol types and work with typed streams of `ResponseEvent` or other endpoint-specific response values.

View File

@@ -7,14 +7,14 @@ use crate::rate_limits::parse_rate_limit_reached_type;
use base64::Engine;
use chrono::DateTime;
use chrono::Utc;
use codex_protocol::auth::PlanType;
use codex_protocol::error::CodexErr;
use codex_protocol::error::CodexErrorDetails;
use codex_protocol::error::ConnectionFailedError;
use codex_protocol::error::RetryLimitReachedError;
use codex_protocol::error::UnexpectedResponseError;
use codex_protocol::error::UsageLimitReachedError;
use codex_protocol::protocol::MisalignmentErrorDetails;
use akode_protocol::auth::PlanType;
use akode_protocol::error::CodexErr;
use akode_protocol::error::CodexErrorDetails;
use akode_protocol::error::ConnectionFailedError;
use akode_protocol::error::RetryLimitReachedError;
use akode_protocol::error::UnexpectedResponseError;
use akode_protocol::error::UsageLimitReachedError;
use akode_protocol::protocol::MisalignmentErrorDetails;
use http::HeaderMap;
use serde::Deserialize;
use serde_json::Value;

View File

@@ -1,8 +1,8 @@
use super::*;
use base64::Engine;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::CodexErrorInfo;
use codex_protocol::protocol::RateLimitReachedType;
use akode_http_client::RetryAfter;
use akode_protocol::protocol::CodexErrorInfo;
use akode_protocol::protocol::RateLimitReachedType;
use pretty_assertions::assert_eq;
#[test]
@@ -479,7 +479,7 @@ fn map_api_error_preserves_misalignment_details_from_403_body() {
error_type: Some("unauthorized_data_transfer".to_string()),
review_target: Some(" RB/opaque== ".to_string()),
detailed_explanation: Some("The agent attempted an external transfer.".to_string()),
steer: Some(codex_protocol::protocol::MisalignmentSteer {
steer: Some(akode_protocol::protocol::MisalignmentSteer {
message: "Do not transfer the user's files.".to_string(),
}),
})
@@ -529,7 +529,7 @@ fn map_api_error_preserves_misalignment_details_from_wrapped_websocket_error() {
error_type: Some("future_safety_category".to_string()),
review_target: Some(" RB/opaque== ".to_string()),
detailed_explanation: Some("The agent attempted an external transfer.".to_string()),
steer: Some(codex_protocol::protocol::MisalignmentSteer {
steer: Some(akode_protocol::protocol::MisalignmentSteer {
message: "Do not transfer the user's files.".to_string(),
}),
})

View File

@@ -0,0 +1,121 @@
use akode_client::Request;
use akode_client::TransportError;
use akode_http_client::NetworkPolicyDenied;
use http::HeaderMap;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
/// Error returned while applying authentication to an outbound request.
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
#[error(transparent)]
Policy(#[from] NetworkPolicyDenied),
#[error("request auth build error: {0}")]
Build(String),
#[error("transient auth error: {0}")]
Transient(String),
}
impl From<AuthError> for TransportError {
fn from(error: AuthError) -> Self {
match error {
AuthError::Policy(denied) => TransportError::Policy(denied),
AuthError::Build(message) => TransportError::Build(message),
AuthError::Transient(message) => TransportError::Network(message),
}
}
}
/// Applies authentication to API requests.
///
/// Header-only providers can implement `add_auth_headers`; providers that sign
/// complete requests can override `apply_auth`.
pub trait AuthProvider: Send + Sync {
/// Adds any auth headers that are available without request body access.
///
/// Implementations should be cheap and non-blocking. This method is also
/// used by telemetry and non-HTTP request paths. Providers that require async
/// work must return an error here and override `apply_auth_headers`.
/// Callers must not send the request if this returns an error.
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError>;
/// Returns any auth headers that are available without request body access.
fn to_auth_headers(&self) -> Result<HeaderMap, AuthError> {
let mut headers = HeaderMap::new();
self.add_auth_headers(&mut headers)?;
Ok(headers)
}
/// Describes headers expected on a successful request without refreshing or registering auth.
/// Async providers should override this rather than resolving credentials for telemetry.
fn auth_header_telemetry(&self) -> Result<AuthHeaderTelemetry, AuthError> {
let headers = self.to_auth_headers()?;
let name = headers
.contains_key(http::header::AUTHORIZATION)
.then_some("authorization");
Ok(AuthHeaderTelemetry {
attached: name.is_some(),
name,
})
}
/// Refreshes credentials after an explicit HTTP 401. Returns whether the caller
/// may retry with new credentials. Callers must bound retries and pass the headers
/// of the rejected request so concurrent failures can reuse an earlier refresh.
fn refresh_after_unauthorized(&self, _rejected_headers: HeaderMap) -> AuthRefreshFuture<'_> {
Box::pin(async { false })
}
/// Authenticates a header-only request, including removing credentials it supersedes.
///
/// Implementations may refresh credentials asynchronously. Providers with static credentials
/// can rely on the default implementation.
/// Callers must use the returned map rather than overlaying resolved headers.
fn apply_auth_headers(&self, mut headers: HeaderMap) -> AuthHeadersFuture<'_> {
Box::pin(async move {
headers.extend(self.to_auth_headers()?);
Ok(headers)
})
}
/// Applies auth to a complete outbound request and returns the request to send.
///
/// The input `request` is moved into this method. Implementations may mutate
/// the owned request, or replace it entirely, before returning.
///
/// Header-only auth providers can rely on the default implementation.
/// Request-signing providers can override this to inspect the final URL,
/// headers, and body bytes before the transport sends the request.
///
/// Callers must always use the returned request as authoritative.
/// If this returns [`AuthError`], the request should not be sent.
fn apply_auth(&self, request: Request) -> AuthProviderFuture<'_> {
Box::pin(async move {
let mut request = request;
request.headers = self.apply_auth_headers(request.headers).await?;
Ok(request)
})
}
}
pub type AuthProviderFuture<'a> =
Pin<Box<dyn Future<Output = Result<Request, AuthError>> + Send + 'a>>;
pub type AuthHeadersFuture<'a> =
Pin<Box<dyn Future<Output = Result<HeaderMap, AuthError>> + Send + 'a>>;
pub type AuthRefreshFuture<'a> = Pin<Box<dyn Future<Output = bool> + Send + 'a>>;
/// Shared auth handle passed through API clients.
pub type SharedAuthProvider = Arc<dyn AuthProvider>;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct AuthHeaderTelemetry {
pub attached: bool,
pub name: Option<&'static str>,
}
pub fn auth_header_telemetry(auth: &dyn AuthProvider) -> Result<AuthHeaderTelemetry, AuthError> {
auth.auth_header_telemetry()
}

View File

@@ -0,0 +1,423 @@
use crate::error::ApiError;
use akode_protocol::ResponseUsageMetadata;
use akode_protocol::config_types::ReasoningSummary as ReasoningSummaryConfig;
use akode_protocol::config_types::Verbosity as VerbosityConfig;
use akode_protocol::models::ResponseItem;
use akode_protocol::openai_models::ReasoningEffort as ReasoningEffortConfig;
use akode_protocol::protocol::RateLimitSnapshot;
use akode_protocol::protocol::TokenUsage;
use akode_protocol::protocol::TurnModerationMetadataEvent;
use akode_protocol::protocol::W3cTraceContext;
use akode_protocol::turn_input::PromptCacheTtl;
use futures::Stream;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value;
use serde_json::value::RawValue;
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;
use std::task::Context;
use std::task::Poll;
use tokio::sync::mpsc;
use tokio::sync::oneshot;
pub const WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY: &str = "ws_request_header_traceparent";
pub const WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY: &str = "ws_request_header_tracestate";
/// Canonical input payload for the memory summarize endpoint.
#[derive(Debug, Clone, Serialize)]
pub struct MemorySummarizeInput {
pub model: String,
#[serde(rename = "traces")]
pub raw_memories: Vec<RawMemory>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<Reasoning>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RawMemory {
pub id: String,
pub metadata: RawMemoryMetadata,
pub items: Vec<Value>,
}
#[derive(Debug, Clone, Serialize)]
pub struct RawMemoryMetadata {
pub source_path: String,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct MemorySummarizeOutput {
#[serde(rename = "trace_summary", alias = "raw_memory")]
pub raw_memory: String,
pub memory_summary: String,
}
/// The latest server response ID received in this turn, shared with tool-review extensions.
#[derive(Clone, Debug)]
pub struct ResponseId(pub String);
#[derive(Debug)]
pub enum ResponseEvent {
Created {
/// Existing server response ID, when supplied by the stream.
response_id: Option<String>,
},
SafetyBuffering(SafetyBuffering),
OutputItemDone(ResponseItem),
OutputItemAdded(ResponseItem),
/// Emitted when the server includes `OpenAI-Model` on the stream response.
/// This can differ from the requested model when backend safety routing applies.
ServerModel(String),
/// Emitted when the server includes moderation metadata for first-party turn presentation.
TurnModerationMetadata(TurnModerationMetadataEvent),
/// Action-bound Guardian evidence for request-scoped consumers, not model history.
GuardianAssessment(crate::guardian_assessment::GuardianAssessment),
/// Emitted when `X-Reasoning-Included: true` is present on the response,
/// meaning the server already accounted for past reasoning tokens and the
/// client should not re-estimate them.
ServerReasoningIncluded(bool),
Completed {
response_id: String,
token_usage: Option<TokenUsage>,
usage_metadata: Option<ResponseUsageMetadata>,
/// Did the model affirmatively end its turn? Some providers do not set this,
/// so we rely on fallback logic when this is `None`.
end_turn: Option<bool>,
},
OutputTextDelta(String),
ToolCallInputDelta {
item_id: String,
call_id: Option<String>,
delta: String,
},
ReasoningSummaryDelta {
delta: String,
summary_index: i64,
},
ReasoningSummaryDone {
item_id: String,
text: String,
summary_index: i64,
},
ReasoningContentDelta {
delta: String,
content_index: i64,
},
ReasoningSummaryPartAdded {
summary_index: i64,
},
RateLimits(RateLimitSnapshot),
ModelsEtag(String),
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct SafetyBuffering {
pub use_cases: Vec<String>,
pub reasons: Vec<String>,
#[serde(skip)]
pub show_buffering_ui: bool,
#[serde(rename = "retry_model")]
pub faster_model: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct SafetyBufferingTreatment {
pub faster_model: Option<String>,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningContext {
Auto,
CurrentTurn,
AllTurns,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct Reasoning {
#[serde(
skip_serializing_if = "Option::is_none",
serialize_with = "serialize_reasoning_effort"
)]
pub effort: Option<ReasoningEffortConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub summary: Option<ReasoningSummaryConfig>,
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<ReasoningContext>,
}
fn serialize_reasoning_effort<S>(
effort: &Option<ReasoningEffortConfig>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
if let Some(ReasoningEffortConfig::Custom(value)) = effort
&& let Ok(value) = value.parse::<u64>()
{
return serializer.serialize_u64(value);
}
effort.serialize(serializer)
}
#[derive(Debug, Serialize, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum ReasoningSummaryDelivery {
SequentialCutoff,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct StreamOptions {
pub reasoning_summary_delivery: ReasoningSummaryDelivery,
}
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum TextFormatType {
#[default]
JsonSchema,
}
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
pub struct TextFormat {
/// Format type used by the OpenAI text controls.
pub r#type: TextFormatType,
/// When true, the server is expected to strictly validate responses.
pub strict: bool,
/// JSON schema for the desired output.
pub schema: Value,
/// Friendly name for the format, used in telemetry/debugging.
pub name: String,
}
/// Controls the `text` field for the Responses API, combining verbosity and
/// optional JSON schema output formatting.
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
pub struct TextControls {
#[serde(skip_serializing_if = "Option::is_none")]
pub verbosity: Option<OpenAiVerbosity>,
#[serde(skip_serializing_if = "Option::is_none")]
pub format: Option<TextFormat>,
}
#[derive(Debug, Serialize, Default, Clone, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OpenAiVerbosity {
Low,
#[default]
Medium,
High,
}
impl From<VerbosityConfig> for OpenAiVerbosity {
fn from(v: VerbosityConfig) -> Self {
match v {
VerbosityConfig::Low => OpenAiVerbosity::Low,
VerbosityConfig::Medium => OpenAiVerbosity::Medium,
VerbosityConfig::High => OpenAiVerbosity::High,
}
}
}
/// Serialized tool definitions for Responses API requests.
///
/// Keeping the tool list as raw JSON avoids rebuilding a generic JSON value
/// tree, while the shared allocation keeps request clones cheap.
#[derive(Debug, Clone)]
pub struct ResponsesApiTools(Arc<RawValue>);
impl ResponsesApiTools {
pub(crate) fn as_raw_value(&self) -> &RawValue {
&self.0
}
}
impl From<Arc<RawValue>> for ResponsesApiTools {
fn from(value: Arc<RawValue>) -> Self {
Self(value)
}
}
impl PartialEq for ResponsesApiTools {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0) || self.0.get() == other.0.get()
}
}
impl Serialize for ResponsesApiTools {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct PromptCacheOptions {
pub ttl: PromptCacheTtl,
}
#[derive(Debug, Serialize, Clone, PartialEq)]
pub struct ResponsesApiRequest {
// Keep routing fields first: serde serializes struct fields in declaration order, and
// gateways may inspect request bodies incrementally before potentially multi-megabyte input.
pub model: String,
pub stream: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_tier: Option<String>,
pub input: Vec<ResponseItem>,
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<ResponsesApiTools>,
pub tool_choice: String,
pub parallel_tool_calls: bool,
pub reasoning: Option<Reasoning>,
pub store: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub stream_options: Option<StreamOptions>,
pub include: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_options: Option<PromptCacheOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<TextControls>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_metadata: Option<HashMap<String, String>>,
}
impl<'a> From<&'a ResponsesApiRequest> for ResponseCreateWsRequest<'a> {
fn from(request: &'a ResponsesApiRequest) -> Self {
Self {
model: &request.model,
previous_response_id: None,
input: &request.input,
tools: request.tools.as_ref().map(ResponsesApiTools::as_raw_value),
tool_choice: &request.tool_choice,
parallel_tool_calls: request.parallel_tool_calls,
reasoning: request.reasoning.as_ref(),
store: request.store,
stream: request.stream,
stream_options: request.stream_options.as_ref(),
include: &request.include,
service_tier: request.service_tier.as_deref(),
prompt_cache_key: request.prompt_cache_key.as_deref(),
prompt_cache_options: request.prompt_cache_options,
text: request.text.as_ref(),
generate: None,
client_metadata: request.client_metadata.clone(),
}
}
}
#[derive(Debug, Serialize)]
pub struct ResponseCreateWsRequest<'a> {
// Keep routing fields first: serde serializes struct fields in declaration order, and
// gateways may inspect request bodies incrementally before potentially multi-megabyte input.
pub model: &'a str,
pub stream: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub service_tier: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub previous_response_id: Option<String>,
pub input: &'a [ResponseItem],
#[serde(skip_serializing_if = "Option::is_none")]
pub tools: Option<&'a RawValue>,
pub tool_choice: &'a str,
pub parallel_tool_calls: bool,
pub reasoning: Option<&'a Reasoning>,
pub store: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub stream_options: Option<&'a StreamOptions>,
pub include: &'a [String],
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_key: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub prompt_cache_options: Option<PromptCacheOptions>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text: Option<&'a TextControls>,
#[serde(skip_serializing_if = "Option::is_none")]
pub generate: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub client_metadata: Option<HashMap<String, String>>,
}
pub fn response_create_client_metadata(
client_metadata: Option<HashMap<String, String>>,
trace: Option<&W3cTraceContext>,
) -> Option<HashMap<String, String>> {
let mut client_metadata = client_metadata.unwrap_or_default();
if let Some(traceparent) = trace.and_then(|trace| trace.traceparent.as_deref()) {
client_metadata.insert(
WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY.to_string(),
traceparent.to_string(),
);
}
if let Some(tracestate) = trace.and_then(|trace| trace.tracestate.as_deref()) {
client_metadata.insert(
WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY.to_string(),
tracestate.to_string(),
);
}
(!client_metadata.is_empty()).then_some(client_metadata)
}
#[derive(Debug, Serialize)]
#[serde(tag = "type")]
#[allow(clippy::large_enum_variant)]
pub enum ResponsesWsRequest<'a> {
#[serde(rename = "response.create")]
ResponseCreate(ResponseCreateWsRequest<'a>),
}
pub fn create_text_param_for_request(
verbosity: Option<VerbosityConfig>,
output_schema: &Option<Value>,
output_schema_strict: bool,
) -> Option<TextControls> {
if verbosity.is_none() && output_schema.is_none() {
return None;
}
Some(TextControls {
verbosity: verbosity.map(std::convert::Into::into),
format: output_schema.as_ref().map(|schema| TextFormat {
r#type: TextFormatType::JsonSchema,
strict: output_schema_strict,
schema: schema.clone(),
name: "codex_output_schema".to_string(),
}),
})
}
/// Distinguishes draining a live response from abandoning obsolete work.
#[derive(Clone, Copy)]
pub enum ResponseInterrupt {
/// Drain normally, without validating or waiting for interruption acknowledgements.
Drain,
/// Skip undispatched work or retire its transport at the cleanup deadline.
/// Undispatched work ends without a completion event and leaves the socket reusable.
Cancel { deadline: tokio::time::Instant },
}
pub struct ResponseStream {
pub rx_event: mpsc::Receiver<Result<ResponseEvent, ApiError>>,
/// Server-assigned `x-request-id` response header, when present.
pub upstream_request_id: Option<String>,
/// Requests a graceful interrupt. Keep consuming events through completion.
/// Only `Cancel` validates and waits for an interruption acknowledgement.
pub interrupt: Option<oneshot::Sender<ResponseInterrupt>>,
}
impl Stream for ResponseStream {
type Item = Result<ResponseEvent, ApiError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rx_event.poll_recv(cx)
}
}

View File

@@ -0,0 +1,227 @@
use crate::auth::SharedAuthProvider;
use crate::common::MemorySummarizeInput;
use crate::common::MemorySummarizeOutput;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use akode_client::HttpTransport;
use akode_client::RequestTelemetry;
use http::HeaderMap;
use http::Method;
use serde::Deserialize;
use serde_json::to_value;
use std::sync::Arc;
pub struct MemoriesClient<T: HttpTransport> {
session: EndpointSession<T>,
}
impl<T: HttpTransport> MemoriesClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
}
}
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
Self {
session: self.session.with_request_telemetry(request),
}
}
fn path() -> &'static str {
"memories/trace_summarize"
}
pub async fn summarize(
&self,
body: serde_json::Value,
extra_headers: HeaderMap,
) -> Result<Vec<MemorySummarizeOutput>, ApiError> {
let resp = self
.session
.execute(Method::POST, Self::path(), extra_headers, Some(body))
.await?;
let parsed: SummarizeResponse =
serde_json::from_slice(&resp.body).map_err(|e| ApiError::Stream(e.to_string()))?;
Ok(parsed.output)
}
pub async fn summarize_input(
&self,
input: &MemorySummarizeInput,
extra_headers: HeaderMap,
) -> Result<Vec<MemorySummarizeOutput>, ApiError> {
let body = to_value(input).map_err(|e| {
ApiError::Stream(format!("failed to encode memory summarize input: {e}"))
})?;
self.summarize(body, extra_headers).await
}
}
#[derive(Debug, Deserialize)]
struct SummarizeResponse {
output: Vec<MemorySummarizeOutput>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::AuthProvider;
use crate::common::RawMemory;
use crate::common::RawMemoryMetadata;
use crate::provider::RetryConfig;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use http::HeaderMap;
use http::Method;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
#[derive(Clone, Default)]
struct DummyTransport;
impl HttpTransport for DummyTransport {
async fn execute(&self, _req: Request) -> Result<Response, TransportError> {
Err(TransportError::Build("execute should not run".to_string()))
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
#[derive(Clone, Default)]
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
Ok(())
}
}
#[derive(Clone)]
struct CapturingTransport {
last_request: Arc<Mutex<Option<Request>>>,
response_body: Arc<Vec<u8>>,
}
impl CapturingTransport {
fn new(response_body: Vec<u8>) -> Self {
Self {
last_request: Arc::new(Mutex::new(None)),
response_body: Arc::new(response_body),
}
}
}
impl HttpTransport for CapturingTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
*self.last_request.lock().expect("lock request store") = Some(req);
Ok(Response {
status: StatusCode::OK,
headers: HeaderMap::new(),
body: self.response_body.as_ref().clone().into(),
})
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
fn provider(base_url: &str) -> Provider {
Provider {
name: "test".to_string(),
base_url: base_url.to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(1),
}
}
#[test]
fn path_is_memories_trace_summarize_for_wire_compatibility() {
assert_eq!(
MemoriesClient::<DummyTransport>::path(),
"memories/trace_summarize"
);
}
#[tokio::test]
async fn summarize_input_posts_expected_payload_and_parses_output() {
let transport = CapturingTransport::new(
serde_json::to_vec(&json!({
"output": [
{
"trace_summary": "raw summary",
"memory_summary": "memory summary"
}
]
}))
.expect("serialize response"),
);
let client = MemoriesClient::new(
transport.clone(),
provider("https://example.com/api/codex"),
Arc::new(DummyAuth),
);
let input = MemorySummarizeInput {
model: "gpt-test".to_string(),
raw_memories: vec![RawMemory {
id: "trace-1".to_string(),
metadata: RawMemoryMetadata {
source_path: "/tmp/trace.json".to_string(),
},
items: vec![json!({"type": "message", "role": "user", "content": []})],
}],
reasoning: None,
};
let output = client
.summarize_input(&input, HeaderMap::new())
.await
.expect("summarize input request should succeed");
assert_eq!(output.len(), 1);
assert_eq!(output[0].raw_memory, "raw summary");
assert_eq!(output[0].memory_summary, "memory summary");
let request = transport
.last_request
.lock()
.expect("lock request store")
.clone()
.expect("request should be captured");
assert_eq!(request.method, Method::POST);
assert_eq!(
request.url,
"https://example.com/api/codex/memories/trace_summarize"
);
let body = request
.body
.as_ref()
.and_then(RequestBody::json)
.expect("request body should be JSON");
assert_eq!(body["model"], "gpt-test");
assert_eq!(body["traces"][0]["id"], "trace-1");
assert_eq!(
body["traces"][0]["metadata"]["source_path"],
"/tmp/trace.json"
);
}
}

View File

@@ -0,0 +1,434 @@
use crate::auth::SharedAuthProvider;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use bytes::Bytes;
use akode_client::HttpTransport;
use akode_client::RequestTelemetry;
use akode_protocol::openai_models::ModelInfo;
use akode_protocol::openai_models::ModelsResponse;
use http::HeaderMap;
use http::Method;
use http::header::ETAG;
use std::sync::Arc;
use url::Url;
pub struct ModelsClient<T: HttpTransport> {
session: EndpointSession<T>,
}
impl<T: HttpTransport> ModelsClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
}
}
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
Self {
session: self.session.with_request_telemetry(request),
}
}
fn path() -> &'static str {
"models"
}
fn append_client_version_query(req: &mut akode_client::Request, client_version: &str) {
let separator = if req.url.contains('?') { '&' } else { '?' };
req.url = format!("{}{}client_version={client_version}", req.url, separator);
}
pub fn request_url(provider: &Provider, client_version: &str) -> String {
let mut request = provider.build_request(Method::GET, Self::path());
Self::append_client_version_query(&mut request, client_version);
request.url
}
/// Builds a full catalog URL, preserving provider routing parameters and client version.
pub fn catalog_request_url(
provider: &Provider,
catalog_url: &str,
client_version: &str,
) -> Result<String, ApiError> {
let invalid = |message: &str| ApiError::InvalidRequest {
message: message.to_string(),
};
let mut url = Url::parse(catalog_url)
.map_err(|_| invalid("model_catalog_url must be an absolute URL"))?;
{
let mut query = url.query_pairs_mut();
if let Some(params) = &provider.query_params {
query.extend_pairs(params);
}
query.append_pair("client_version", client_version);
}
Ok(url.into())
}
/// Fetches and decodes a catalog, optionally bounding response bytes before decoding.
pub async fn list_models(
&self,
request_url: String,
extra_headers: HeaderMap,
response_body_limit_bytes: Option<usize>,
) -> Result<(Vec<ModelInfo>, Option<String>), ApiError> {
let (body, header_etag) = self
.list_models_raw(request_url, extra_headers, response_body_limit_bytes)
.await?;
let ModelsResponse { models } =
serde_json::from_slice::<ModelsResponse>(&body).map_err(|e| {
ApiError::Stream(format!(
"failed to decode models response: {:?} at line {} column {} (body: {} bytes)",
e.classify(),
e.line(),
e.column(),
body.len()
))
})?;
Ok((models, header_etag))
}
/// Fetches a catalog using the provider's auth and retry policy without decoding it.
///
/// Callers accepting provider-controlled catalogs must validate the native response
/// without including raw values in diagnostics.
pub async fn list_models_raw(
&self,
request_url: String,
extra_headers: HeaderMap,
response_body_limit_bytes: Option<usize>,
) -> Result<(Bytes, Option<String>), ApiError> {
let resp = self
.session
.execute_with(
Method::GET,
Self::path(),
extra_headers,
/*body*/ None,
move |req| {
req.url.clone_from(&request_url);
req.response_body_limit_bytes = response_body_limit_bytes;
},
)
.await?;
let header_etag = resp
.headers
.get(ETAG)
.and_then(|value| value.to_str().ok())
.map(ToString::to_string);
Ok((resp.body, header_etag))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::AuthError;
use crate::auth::AuthProvider;
use crate::auth::AuthProviderFuture;
use crate::provider::RetryConfig;
use akode_client::Request;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use http::HeaderMap;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;
#[derive(Clone)]
struct CapturingTransport {
last_request: Arc<Mutex<Option<Request>>>,
body: Arc<ModelsResponse>,
etag: Option<String>,
}
impl Default for CapturingTransport {
fn default() -> Self {
Self {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(ModelsResponse { models: Vec::new() }),
etag: None,
}
}
}
impl HttpTransport for CapturingTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
*self.last_request.lock().unwrap() = Some(req);
let body = serde_json::to_vec(&*self.body).unwrap();
let mut headers = HeaderMap::new();
if let Some(etag) = &self.etag {
headers.insert(ETAG, etag.parse().unwrap());
}
Ok(Response {
status: StatusCode::OK,
headers,
body: body.into(),
})
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
#[derive(Clone, Default)]
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
Ok(())
}
}
#[derive(Default)]
struct RetryAuth {
request_limits: Mutex<Vec<Option<usize>>>,
}
impl AuthProvider for RetryAuth {
fn add_auth_headers(&self, headers: &mut HeaderMap) -> Result<(), AuthError> {
headers.insert(http::header::AUTHORIZATION, "Bearer test".parse().unwrap());
Ok(())
}
fn apply_auth(&self, mut request: Request) -> AuthProviderFuture<'_> {
Box::pin(async move {
let mut limits = self.request_limits.lock().unwrap();
limits.push(request.response_body_limit_bytes);
if limits.len() == 1 {
return Err(AuthError::Transient("retry authentication".to_string()));
}
self.add_auth_headers(&mut request.headers)?;
Ok(request)
})
}
}
fn provider(base_url: &str) -> Provider {
Provider {
name: "test".to_string(),
base_url: base_url.to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(1),
}
}
#[test]
fn catalog_request_url_preserves_routing_and_encodes_queries() {
let mut provider = provider("https://gateway.example/v1");
provider.query_params = Some(std::collections::HashMap::from([(
"api-version".to_string(),
"2026 09".to_string(),
)]));
let url = ModelsClient::<CapturingTransport>::catalog_request_url(
&provider,
"https://catalog.example/codex/models?deployment=one",
"1.2.3",
)
.unwrap();
assert_eq!(
url,
"https://catalog.example/codex/models?deployment=one&api-version=2026+09&client_version=1.2.3"
);
}
#[test]
fn catalog_request_url_rejects_relative_urls() {
let provider = provider("https://gateway.example/v1");
for catalog_url in ["/codex/models", "codex/models"] {
let error = ModelsClient::<CapturingTransport>::catalog_request_url(
&provider,
catalog_url,
"1.2.3",
)
.unwrap_err();
assert!(matches!(error, ApiError::InvalidRequest { .. }));
}
}
#[tokio::test]
async fn response_body_limit_survives_auth_retry_without_limiting_other_models_requests() {
let transport = CapturingTransport::default();
let auth = Arc::new(RetryAuth::default());
let mut provider = provider("https://example.com/api/codex");
provider.retry.max_attempts = 2;
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport.clone(), provider, auth.clone());
client
.list_models(
request_url.clone(),
HeaderMap::new(),
/*response_body_limit_bytes*/ Some(64),
)
.await
.expect("limited request should succeed after auth retry");
{
let request = transport.last_request.lock().unwrap();
let request = request.as_ref().unwrap();
assert_eq!(request.response_body_limit_bytes, Some(64));
assert_eq!(request.url, request_url);
assert_eq!(request.headers[http::header::AUTHORIZATION], "Bearer test");
}
let (models, _) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("ordinary request on the same client should remain unbounded");
assert!(models.is_empty());
assert_eq!(
transport
.last_request
.lock()
.unwrap()
.as_ref()
.unwrap()
.response_body_limit_bytes,
None
);
assert_eq!(
*auth.request_limits.lock().unwrap(),
vec![Some(64), Some(64), None]
);
}
#[tokio::test]
async fn appends_client_version_query() {
let response = ModelsResponse { models: Vec::new() };
let transport = CapturingTransport {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(response),
etag: None,
};
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport.clone(), provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("request should succeed");
assert_eq!(models.len(), 0);
let url = transport
.last_request
.lock()
.unwrap()
.as_ref()
.unwrap()
.url
.clone();
assert_eq!(
url,
"https://example.com/api/codex/models?client_version=0.99.0"
);
}
#[tokio::test]
async fn parses_models_response() {
let response = ModelsResponse {
models: vec![
serde_json::from_value(json!({
"slug": "gpt-test",
"display_name": "gpt-test",
"description": "desc",
"default_reasoning_level": "medium",
"supported_reasoning_levels": [{"effort": "low", "description": "low"}, {"effort": "medium", "description": "medium"}, {"effort": "high", "description": "high"}],
"shell_type": "shell_command",
"visibility": "list",
"minimal_client_version": [0, 99, 0],
"supported_in_api": true,
"priority": 1,
"upgrade": null,
"support_verbosity": false,
"default_verbosity": null,
"apply_patch_tool_type": null,
"truncation_policy": {"mode": "bytes", "limit": 10_000},
"supports_image_detail_original": false,
"context_window": 272_000,
"experimental_supported_tools": [],
}))
.unwrap(),
],
};
let transport = CapturingTransport {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(response),
etag: None,
};
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.99.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, _) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("request should succeed");
assert_eq!(models.len(), 1);
assert_eq!(models[0].slug, "gpt-test");
assert_eq!(models[0].supported_in_api, true);
assert_eq!(models[0].priority, 1);
}
#[tokio::test]
async fn list_models_includes_etag() {
let response = ModelsResponse { models: Vec::new() };
let transport = CapturingTransport {
last_request: Arc::new(Mutex::new(None)),
body: Arc::new(response),
etag: Some("\"abc\"".to_string()),
};
let provider = provider("https://example.com/api/codex");
let request_url = ModelsClient::<CapturingTransport>::request_url(&provider, "0.1.0");
let client = ModelsClient::new(transport, provider, Arc::new(DummyAuth));
let (models, etag) = client
.list_models(
request_url,
HeaderMap::new(),
/*response_body_limit_bytes*/ None,
)
.await
.expect("request should succeed");
assert_eq!(models.len(), 0);
assert_eq!(etag, Some("\"abc\"".to_string()));
}
}

View File

@@ -6,10 +6,10 @@ use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use bytes::Bytes;
use codex_client::HttpTransport;
use codex_client::Request;
use codex_client::RequestBody;
use codex_client::RequestTelemetry;
use akode_client::HttpTransport;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::RequestTelemetry;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
@@ -116,7 +116,7 @@ impl<T: HttpTransport> RealtimeCallClient<T> {
session_config: RealtimeSessionConfig,
extra_headers: HeaderMap,
) -> Result<RealtimeCallResponse, ApiError> {
trace!(target: "codex_api::realtime_websocket::wire", "realtime call request SDP: {sdp}");
trace!(target: "akode_api::realtime_websocket::wire", "realtime call request SDP: {sdp}");
// WebRTC can begin inference as soon as the peer connection comes up, so the initial
// session payload is sent with call creation. Legacy sidebands still send session.update
// after joining; Frameless sidebands attach to the session that is already running.
@@ -253,11 +253,11 @@ mod tests {
use crate::endpoint::realtime_websocket::RealtimeOutputModality;
use crate::endpoint::realtime_websocket::RealtimeSessionMode;
use crate::provider::RetryConfig;
use codex_client::Request;
use codex_client::Response;
use codex_client::StreamResponse;
use codex_client::TransportError;
use codex_protocol::protocol::RealtimeVoice;
use akode_client::Request;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_protocol::protocol::RealtimeVoice;
use http::StatusCode;
use pretty_assertions::assert_eq;
use std::sync::Mutex;

View File

@@ -21,17 +21,17 @@ use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::parse_realtime_event;
use crate::error::ApiError;
use crate::provider::Provider;
use codex_client::backoff;
use codex_http_client::HttpClientFactory;
use codex_http_client::NetworkPolicyDenied;
use codex_http_client::maybe_build_rustls_client_config_with_custom_ca;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole;
use codex_protocol::protocol::RealtimeTranscriptDelta;
use codex_utils_rustls_provider::ensure_rustls_crypto_provider;
use codex_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector;
use codex_websocket_client::WebSocketTlsMode;
use akode_client::backoff;
use akode_http_client::HttpClientFactory;
use akode_http_client::NetworkPolicyDenied;
use akode_http_client::maybe_build_rustls_client_config_with_custom_ca;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_utils_rustls_provider::ensure_rustls_crypto_provider;
use akode_websocket_client::WebSocketConnection;
use akode_websocket_client::WebSocketConnector;
use akode_websocket_client::WebSocketTlsMode;
use futures::SinkExt;
use futures::StreamExt;
use http::HeaderMap;
@@ -62,7 +62,7 @@ use tungstenite::protocol::WebSocketConfig;
use tungstenite::protocol::frame::coding::CloseCode;
use url::Url;
const REALTIME_WIRE_LOG_TARGET: &str = "codex_api::realtime_websocket::wire";
const REALTIME_WIRE_LOG_TARGET: &str = "akode_api::realtime_websocket::wire";
mod sideband;
struct WsStream {
@@ -94,7 +94,7 @@ impl WsStream {
let transport_task = tokio::spawn(async move {
let mut inner = inner;
let report_write_policy_error = |error: &WsError| {
if let Some(denied) = codex_websocket_client::network_policy_denial(error) {
if let Some(denied) = akode_websocket_client::network_policy_denial(error) {
terminal_policy_tx.send_replace(Some(denied));
let _ = tx_message.try_send(Err(Self::policy_error(denied)));
}
@@ -140,7 +140,7 @@ impl WsStream {
trace!(payload_len = payload.len(), "realtime websocket received ping");
if let Err(err) = inner.send(Message::Pong(payload)).await {
error!("realtime websocket failed to send pong: {err}");
terminal_policy_tx.send_replace(codex_websocket_client::network_policy_denial(&err));
terminal_policy_tx.send_replace(akode_websocket_client::network_policy_denial(&err));
let _ = tx_message.send(Err(err)).await;
break;
}
@@ -178,7 +178,7 @@ impl WsStream {
}
Err(err) => {
error!("realtime websocket receive failed: {err}");
terminal_policy_tx.send_replace(codex_websocket_client::network_policy_denial(&err));
terminal_policy_tx.send_replace(akode_websocket_client::network_policy_denial(&err));
let _ = tx_message.send(Err(err)).await;
break;
}
@@ -1020,7 +1020,7 @@ impl RealtimeWebsocketClient {
.await;
match result {
Ok(connection) => return Ok(connection),
Err(err @ ApiError::Transport(codex_http_client::TransportError::Policy(_))) => {
Err(err @ ApiError::Transport(akode_http_client::TransportError::Policy(_))) => {
return Err(err);
}
Err(err) if webrtc_sideband_session_ended(&err) => return Err(err),
@@ -1118,7 +1118,7 @@ impl RealtimeWebsocketClient {
let tls_config = match tls_config {
Some(tls_config) => Some(tls_config),
None => Some(
codex_http_client::build_windows_platform_tls_config().map_err(|err| {
akode_http_client::build_windows_platform_tls_config().map_err(|err| {
ApiError::Stream(format!("failed to configure websocket TLS: {err}"))
})?,
),
@@ -1190,8 +1190,8 @@ fn webrtc_sideband_session_ended(err: &ApiError) -> bool {
}
fn map_realtime_websocket_connect_error(err: WsError) -> ApiError {
if let Some(denied) = codex_websocket_client::network_policy_denial(&err) {
return ApiError::Transport(codex_http_client::TransportError::Policy(denied));
if let Some(denied) = akode_websocket_client::network_policy_denial(&err) {
return ApiError::Transport(akode_http_client::TransportError::Policy(denied));
}
match err {
WsError::Http(response) => ApiError::Api {
@@ -1373,16 +1373,16 @@ mod tests {
use super::*;
use crate::endpoint::realtime_websocket::protocol::RealtimeTranscriptEntry;
use crate::provider::RetryConfig;
use codex_http_client::OutboundProxyPolicy::ReqwestDefault;
use codex_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeInputAudioSpeechStarted;
use codex_protocol::protocol::RealtimeNoopRequested;
use codex_protocol::protocol::RealtimeResponseCancelled;
use codex_protocol::protocol::RealtimeResponseCreated;
use codex_protocol::protocol::RealtimeResponseDone;
use codex_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone;
use codex_protocol::protocol::RealtimeVoice;
use akode_http_client::OutboundProxyPolicy::ReqwestDefault;
use akode_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
use akode_protocol::protocol::RealtimeNoopRequested;
use akode_protocol::protocol::RealtimeResponseCancelled;
use akode_protocol::protocol::RealtimeResponseCreated;
use akode_protocol::protocol::RealtimeResponseDone;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_protocol::protocol::RealtimeTranscriptDone;
use akode_protocol::protocol::RealtimeVoice;
use http::HeaderValue;
use http::StatusCode;
use pretty_assertions::assert_eq;
@@ -1628,11 +1628,11 @@ mod tests {
#[tokio::test]
async fn writer_policy_failure_reaches_realtime_events() {
use codex_http_client::DestinationPolicy::Unrestricted;
use codex_http_client::NetworkPolicyController;
use codex_http_client::NetworkPolicyDenied::Revoked;
use codex_http_client::TransportError::Policy;
use codex_websocket_client::network_policy_denial;
use akode_http_client::DestinationPolicy::Unrestricted;
use akode_http_client::NetworkPolicyController;
use akode_http_client::NetworkPolicyDenied::Revoked;
use akode_http_client::TransportError::Policy;
use akode_websocket_client::network_policy_denial;
use tokio::time::timeout;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();

View File

@@ -0,0 +1,158 @@
//! Adapts caller-owned, bounded JSON channels to the existing realtime parser and writer.
//!
//! ```text
//! Caller -- incoming JSON --> read loop -- Message::Text --> Core event parser
//! Caller <-- outgoing JSON -- write loop <-- WsCommand ----- Core writer
//! ```
//!
//! Each channel item carries one JSON message of up to 1 MiB. The loops run
//! independently so Core can still receive events while a command waits for
//! space in the caller's queue. Shutdown seals incoming messages and drains accepted
//! input before closing both directions, including a frame awaiting parser capacity.
use super::*;
use akode_protocol::protocol::RealtimeSidebandTransport;
const MAX_MESSAGE_BYTES: usize = 1024 * 1024;
impl RealtimeWebsocketConnection {
/// Uses an already authenticated, caller-owned stream without opening or reconnecting a socket.
pub fn from_sideband(
transport: RealtimeSidebandTransport,
event_parser: RealtimeEventParser,
) -> Self {
let RealtimeSidebandTransport {
mut incoming,
outgoing,
} = transport;
let (tx_command, mut rx_command) = mpsc::channel::<WsCommand>(32);
let (tx_message, rx_message) = async_channel::bounded(32);
let (_, terminal_policy_error) = tokio::sync::watch::channel(None);
let (input_stop, mut input_stopped) = tokio::sync::watch::channel(false);
let transport_input_stop = input_stop.clone();
let transport_task = tokio::spawn(async move {
let read = async {
let mut is_draining = false;
loop {
let text = if is_draining {
// A reserved but unsent permit must not hold shutdown open.
// try_recv() will drain messages already queued and exit when emptied.
incoming.try_recv().ok()
} else {
tokio::select! {
biased;
// Core requested shutdown, or the transport's write loop ended.
_ = input_stopped.changed() => {
incoming.close();
is_draining = true;
continue;
}
// The caller dropped its receiver for Core commands.
// Detect this even when the writer is idle, then drain accepted input.
_ = outgoing.closed() => {
incoming.close();
is_draining = true;
continue;
}
text = incoming.recv() => text,
}
};
let Some(text) = text else {
break;
};
if text.len() > MAX_MESSAGE_BYTES {
break;
}
if tx_message
.send(Ok(Message::Text(text.into())))
.await
.is_err()
{
break;
}
}
};
let write = async {
while let Some(command) = rx_command.recv().await {
// These commands are still called WsCommand for legacy reasons.
match command {
WsCommand::Send {
message: Message::Text(text),
tx_result,
} => {
let result = if text.len() > MAX_MESSAGE_BYTES {
Err(WsError::Io(std::io::Error::other(
"sideband message too large",
)))
} else {
outgoing
.send(text.to_string())
.await
.map_err(|_| WsError::ConnectionClosed)
};
let failed = result.is_err();
// Tell Core's writer whether the caller's channel accepted the command.
let _ = tx_result.send(result);
if failed {
break;
}
}
WsCommand::Close {
frame: _,
tx_result,
} => {
let _ = tx_result.send(Ok(()));
break;
}
WsCommand::Send { tx_result, .. } => {
let _ = tx_result.send(Err(WsError::Io(std::io::Error::other(
"sideband requires JSON text",
))));
break;
}
}
}
};
tokio::pin!(read);
tokio::select! {
_ = &mut read => {},
_ = write => {
transport_input_stop.send_replace(true);
// Preserve the read future: it may already own a frame that
// has not yet fit into the parser queue.
read.await;
},
}
});
Self::new(
WsStream {
tx_command,
transport_task,
sideband_input_stop: Some(input_stop),
terminal_policy_error,
},
rx_message,
event_parser,
RealtimeTranscriptState::default(),
)
}
}
impl RealtimeWebsocketWriter {
/// Seal caller-owned input so its accepted events can drain without waiting for producers.
/// Socket-backed connections are unaffected.
pub fn close_sideband_input(&self) {
if let Some(input_stop) = &self.stream.sideband_input_stop {
input_stop.send_replace(true);
}
}
}
#[cfg(test)]
#[path = "sideband_tests.rs"]
mod tests;

View File

@@ -145,8 +145,8 @@ async fn queued_transcript_survives_peer_hangup() {
.unwrap()
.unwrap(),
Some(
codex_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
codex_protocol::protocol::RealtimeTranscriptDelta {
akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
akode_protocol::protocol::RealtimeTranscriptDelta {
delta: "last words".into()
}
)
@@ -154,7 +154,7 @@ async fn queued_transcript_survives_peer_hangup() {
);
assert_eq!(
connection.events().take_transcript_tail().await,
vec![codex_protocol::protocol::RealtimeTranscriptEntry {
vec![akode_protocol::protocol::RealtimeTranscriptEntry {
role: "user".into(),
text: "last words".into()
}]
@@ -192,8 +192,8 @@ async fn input_stop_drains_backpressure_without_waiting_for_reserved_permit() {
.unwrap()
.unwrap(),
Some(
codex_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
codex_protocol::protocol::RealtimeTranscriptDelta {
akode_protocol::protocol::RealtimeEvent::InputTranscriptDelta(
akode_protocol::protocol::RealtimeTranscriptDelta {
delta: "tail".into()
}
)

View File

@@ -53,8 +53,8 @@ fn client(base_url: String) -> RealtimeWebsocketClient {
},
stream_idle_timeout: Duration::from_secs(5),
},
codex_http_client::HttpClientFactory::new(
codex_http_client::OutboundProxyPolicy::ReqwestDefault,
akode_http_client::HttpClientFactory::new(
akode_http_client::OutboundProxyPolicy::ReqwestDefault,
),
)
.with_webrtc_sideband_base_url(base_url)

View File

@@ -17,8 +17,8 @@ use crate::endpoint::realtime_websocket::protocol::RealtimeSessionConfig;
use crate::endpoint::realtime_websocket::protocol::RealtimeSessionMode;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use crate::endpoint::realtime_websocket::protocol::RealtimeWireAdapter;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use serde_json::Result as JsonResult;
use serde_json::Value;
use serde_json::to_value;

View File

@@ -3,8 +3,8 @@ use crate::endpoint::realtime_websocket::protocol::FramelessInputTextContent;
use crate::endpoint::realtime_websocket::protocol::RealtimeContextAppendChannel;
use crate::endpoint::realtime_websocket::protocol::RealtimeOutboundMessage;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use serde_json::Value;
use serde_json::json;

View File

@@ -2,8 +2,8 @@ use super::CONTEXT_APPEND_MAX_BYTES;
use super::context_append_chunks;
use super::session_json;
use crate::endpoint::realtime_websocket::protocol::RealtimeVoice;
use codex_protocol::protocol::ConversationTextParams;
use codex_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
use pretty_assertions::assert_eq;
use serde_json::json;

View File

@@ -13,7 +13,7 @@ use crate::endpoint::realtime_websocket::protocol::SessionAudioInput;
use crate::endpoint::realtime_websocket::protocol::SessionAudioOutput;
use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use codex_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::ConversationTextRole;
pub(super) fn conversation_item_create_message(
text: String,

View File

@@ -24,7 +24,7 @@ use crate::endpoint::realtime_websocket::protocol::SessionTurnDetection;
use crate::endpoint::realtime_websocket::protocol::SessionType;
use crate::endpoint::realtime_websocket::protocol::SessionUpdateSession;
use crate::endpoint::realtime_websocket::protocol::TurnDetectionType;
use codex_protocol::protocol::ConversationTextRole;
use akode_protocol::protocol::ConversationTextRole;
use serde_json::json;
const REALTIME_V2_OUTPUT_MODALITY_AUDIO: &str = "audio";

View File

@@ -0,0 +1,272 @@
use crate::endpoint::realtime_websocket::protocol_frameless_bidi::parse_frameless_bidi_event;
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
use crate::endpoint::realtime_websocket::protocol_v2::parse_realtime_event_v2;
use akode_protocol::protocol::ConversationTextParams;
use akode_protocol::protocol::ConversationTextRole;
pub use akode_protocol::protocol::RealtimeAudioFrame;
pub use akode_protocol::protocol::RealtimeEvent;
pub use akode_protocol::protocol::RealtimeOutputModality;
pub use akode_protocol::protocol::RealtimeTranscriptEntry;
pub use akode_protocol::protocol::RealtimeVoice;
use serde::Serialize;
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RealtimeEventParser {
V1,
FramelessBidi,
RealtimeV2,
}
pub type RealtimeWireAdapter = RealtimeEventParser;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RealtimeSessionMode {
Conversational,
Transcription,
}
/// Selects the semantic stream used for Frameless Bidi context appends.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RealtimeContextAppendChannel {
Speakable,
Commentary,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RealtimeSessionConfig {
pub instructions: String,
pub initial_items: Vec<ConversationTextParams>,
pub delegation_ack_filler: Option<bool>,
pub model: Option<String>,
pub session_id: Option<String>,
pub event_parser: RealtimeEventParser,
pub session_mode: RealtimeSessionMode,
pub output_modality: RealtimeOutputModality,
pub voice: RealtimeVoice,
}
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type")]
pub(super) enum RealtimeOutboundMessage {
#[serde(rename = "input_audio_buffer.append")]
InputAudioBufferAppend { audio: String },
#[serde(rename = "conversation.handoff.append")]
ConversationHandoffAppend {
handoff_id: String,
output_text: String,
},
#[serde(rename = "input_audio.append")]
InputAudioAppend { audio: String },
#[serde(rename = "delegation.context.append")]
DelegationContextAppend {
delegation_item_id: String,
#[serde(skip_serializing_if = "Option::is_none")]
channel: Option<RealtimeContextAppendChannel>,
content: Vec<FramelessInputTextContent>,
},
#[serde(rename = "session.context.append")]
SessionContextAppend {
#[serde(skip_serializing_if = "Option::is_none")]
channel: Option<RealtimeContextAppendChannel>,
content: Vec<FramelessInputTextContent>,
},
#[serde(rename = "session.close")]
SessionClose,
#[serde(rename = "response.create")]
ResponseCreate,
#[serde(rename = "session.update")]
SessionUpdate { session: SessionUpdateSession },
#[serde(rename = "session.update")]
FramelessSessionUpdate { session: Value },
#[serde(rename = "conversation.item.create")]
ConversationItemCreate { item: ConversationItemPayload },
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct FramelessInputTextContent {
#[serde(rename = "type")]
pub(super) r#type: FramelessContentType,
pub(super) text: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum FramelessContentType {
InputText,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionUpdateSession {
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) id: Option<String>,
#[serde(rename = "type")]
pub(super) r#type: SessionType,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) model: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) instructions: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) output_modalities: Option<Vec<String>>,
pub(super) audio: SessionAudio,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) tools: Option<Vec<SessionFunctionTool>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) tool_choice: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SessionType {
Quicksilver,
Realtime,
Transcription,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudio {
pub(super) input: SessionAudioInput,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) output: Option<SessionAudioOutput>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioInput {
pub(super) format: SessionAudioFormat,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) noise_reduction: Option<SessionNoiseReduction>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) transcription: Option<SessionInputAudioTranscription>,
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) turn_detection: Option<SessionTurnDetection>,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionInputAudioTranscription {
pub(super) model: String,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioFormat {
#[serde(rename = "type")]
pub(super) r#type: AudioFormatType,
pub(super) rate: u32,
}
#[derive(Debug, Clone, Copy, Serialize)]
pub(super) enum AudioFormatType {
#[serde(rename = "audio/pcm")]
AudioPcm,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioOutput {
#[serde(skip_serializing_if = "Option::is_none")]
pub(super) format: Option<SessionAudioOutputFormat>,
pub(super) voice: RealtimeVoice,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionNoiseReduction {
#[serde(rename = "type")]
pub(super) r#type: NoiseReductionType,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum NoiseReductionType {
NearField,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionTurnDetection {
#[serde(rename = "type")]
pub(super) r#type: TurnDetectionType,
pub(super) interrupt_response: bool,
pub(super) create_response: bool,
pub(super) silence_duration_ms: u32,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum TurnDetectionType {
ServerVad,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionAudioOutputFormat {
#[serde(rename = "type")]
pub(super) r#type: AudioFormatType,
pub(super) rate: u32,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationMessageItem {
#[serde(rename = "type")]
pub(super) r#type: ConversationItemType,
pub(super) role: ConversationTextRole,
pub(super) content: Vec<ConversationItemContent>,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum ConversationItemType {
Message,
FunctionCallOutput,
}
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub(super) enum ConversationItemPayload {
Message(ConversationMessageItem),
FunctionCallOutput(ConversationFunctionCallOutputItem),
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationFunctionCallOutputItem {
#[serde(rename = "type")]
pub(super) r#type: ConversationItemType,
pub(super) call_id: String,
pub(super) output: String,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct ConversationItemContent {
#[serde(rename = "type")]
pub(super) r#type: ConversationContentType,
pub(super) text: String,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum ConversationContentType {
InputText,
OutputText,
}
#[derive(Debug, Clone, Serialize)]
pub(super) struct SessionFunctionTool {
#[serde(rename = "type")]
pub(super) r#type: SessionToolType,
pub(super) name: String,
pub(super) description: String,
pub(super) parameters: Value,
}
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum SessionToolType {
Function,
}
pub(super) fn parse_realtime_event(
payload: &str,
event_parser: RealtimeEventParser,
) -> Option<RealtimeEvent> {
match event_parser {
RealtimeEventParser::V1 => parse_realtime_event_v1(payload),
RealtimeEventParser::FramelessBidi => parse_frameless_bidi_event(payload),
RealtimeEventParser::RealtimeV2 => parse_realtime_event_v2(payload),
}
}

View File

@@ -1,6 +1,6 @@
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_protocol::protocol::RealtimeTranscriptDone;
use serde_json::Value;
use tracing::debug;

View File

@@ -1,11 +1,11 @@
use crate::endpoint::realtime_websocket::protocol_common::parse_error_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload;
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use codex_protocol::protocol::RealtimeAudioFrame;
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone;
use akode_protocol::protocol::RealtimeAudioFrame;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_protocol::protocol::RealtimeTranscriptDone;
use serde_json::Value;
use tracing::debug;

View File

@@ -1,7 +1,7 @@
use super::parse_frameless_bidi_event;
use crate::endpoint::realtime_websocket::protocol_v1::parse_realtime_event_v1;
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
#[test]
fn legacy_and_frameless_delegations_decode_to_the_same_handoff() {

View File

@@ -3,9 +3,9 @@ use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
use codex_protocol::protocol::RealtimeAudioFrame;
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeAudioFrame;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
use serde_json::Value;
use tracing::debug;

View File

@@ -3,14 +3,14 @@ use crate::endpoint::realtime_websocket::protocol_common::parse_realtime_payload
use crate::endpoint::realtime_websocket::protocol_common::parse_session_updated_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_delta_event;
use crate::endpoint::realtime_websocket::protocol_common::parse_transcript_done_event;
use codex_protocol::protocol::RealtimeAudioFrame;
use codex_protocol::protocol::RealtimeEvent;
use codex_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeInputAudioSpeechStarted;
use codex_protocol::protocol::RealtimeNoopRequested;
use codex_protocol::protocol::RealtimeResponseCancelled;
use codex_protocol::protocol::RealtimeResponseCreated;
use codex_protocol::protocol::RealtimeResponseDone;
use akode_protocol::protocol::RealtimeAudioFrame;
use akode_protocol::protocol::RealtimeEvent;
use akode_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeInputAudioSpeechStarted;
use akode_protocol::protocol::RealtimeNoopRequested;
use akode_protocol::protocol::RealtimeResponseCancelled;
use akode_protocol::protocol::RealtimeResponseCreated;
use akode_protocol::protocol::RealtimeResponseDone;
use serde_json::Map as JsonMap;
use serde_json::Value;
use tracing::debug;

View File

@@ -0,0 +1,131 @@
//! V3 transcript reconciliation across interleaved speakers, reconnects, and turn boundaries.
use super::*;
use akode_protocol::protocol::RealtimeTranscriptDone;
use pretty_assertions::assert_eq;
fn events(transcript_state: RealtimeTranscriptState) -> RealtimeWebsocketEvents {
let (_, rx_message) = async_channel::unbounded();
RealtimeWebsocketEvents {
rx_message,
pending_events: Arc::new(Mutex::new(VecDeque::new())),
transcript_state,
event_parser: RealtimeEventParser::FramelessBidi,
is_closed: Arc::new(AtomicBool::new(false)),
}
}
fn entry(role: &str, text: &str) -> RealtimeTranscriptEntry {
RealtimeTranscriptEntry {
role: role.to_string(),
text: text.to_string(),
}
}
async fn observe(events: &RealtimeWebsocketEvents, mut event: RealtimeEvent) {
let original = event.clone();
events.update_active_transcript(&mut event).await;
assert_eq!(
event, original,
"live transcript events must pass through unchanged"
);
}
#[tokio::test]
async fn interleaved_transcripts_reconcile_across_reconnect_in_either_completion_order() {
for assistant_finishes_first in [false, true] {
let state = RealtimeTranscriptState::default();
let first = events(state.clone());
for event in [
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
delta: "What can ".into(),
}),
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
delta: "A bunch ".into(),
}),
RealtimeEvent::InputTranscriptDelta(RealtimeTranscriptDelta {
delta: "you do?".into(),
}),
RealtimeEvent::OutputTranscriptDelta(RealtimeTranscriptDelta {
delta: "of stuff".into(),
}),
] {
observe(&first, event).await;
}
let reconnected = events(state);
let user = RealtimeEvent::InputTranscriptDone(RealtimeTranscriptDone {
text: "What can you do?".into(),
});
let assistant = RealtimeEvent::OutputTranscriptDone(RealtimeTranscriptDone {
text: "A bunch of stuff, including coding.".into(),
});
let finals = if assistant_finishes_first {
[assistant, user]
} else {
[user, assistant]
};
for event in finals {
observe(&reconnected, event).await;
}
assert_eq!(
reconnected.take_transcript_tail().await,
vec![
entry("user", "What can you do?"),
entry("assistant", "A bunch of stuff, including coding."),
]
);
assert_eq!(reconnected.take_transcript_tail().await, vec![]);
}
}
#[tokio::test]
async fn completed_utterances_keep_repeated_speech_and_final_only_turns_distinct() {
let events = events(RealtimeTranscriptState::default());
for role in ["user", "assistant"] {
for with_delta in [true, true, false] {
if with_delta {
let delta = RealtimeTranscriptDelta {
delta: "Again".into(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDelta(delta)
} else {
RealtimeEvent::OutputTranscriptDelta(delta)
},
)
.await;
}
let done = RealtimeTranscriptDone {
text: "Again.".into(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDone(done)
} else {
RealtimeEvent::OutputTranscriptDone(done)
},
)
.await;
// An empty delta must not reopen the utterance we just completed.
let empty = RealtimeTranscriptDelta {
delta: String::new(),
};
observe(
&events,
if role == "user" {
RealtimeEvent::InputTranscriptDelta(empty)
} else {
RealtimeEvent::OutputTranscriptDelta(empty)
},
)
.await;
}
assert_eq!(
events.take_transcript_tail().await,
vec![entry(role, "Again."); 3]
);
}
}

View File

@@ -0,0 +1,159 @@
use crate::auth::SharedAuthProvider;
use crate::common::ResponseStream;
use crate::common::ResponsesApiRequest;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use crate::requests::Compression;
use crate::requests::headers::build_session_headers;
use crate::requests::headers::insert_header;
use crate::requests::headers::subagent_header;
use crate::sse::spawn_response_stream;
use crate::telemetry::SseTelemetry;
use akode_client::EncodedJsonBody;
use akode_client::HttpTransport;
use akode_client::RequestCompression;
use akode_client::RequestTelemetry;
use akode_protocol::protocol::SessionSource;
use http::HeaderMap;
use http::HeaderValue;
use http::Method;
use serde_json::Value;
use std::sync::Arc;
use std::sync::OnceLock;
use tracing::instrument;
pub struct ResponsesClient<T: HttpTransport> {
session: EndpointSession<T>,
sse_telemetry: Option<Arc<dyn SseTelemetry>>,
}
#[derive(Default)]
pub struct ResponsesOptions {
pub session_id: Option<String>,
pub thread_id: Option<String>,
pub session_source: Option<SessionSource>,
pub extra_headers: HeaderMap,
pub compression: Compression,
pub turn_state: Option<Arc<OnceLock<String>>>,
}
impl<T: HttpTransport> ResponsesClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
sse_telemetry: None,
}
}
pub fn with_telemetry(
self,
request: Option<Arc<dyn RequestTelemetry>>,
sse: Option<Arc<dyn SseTelemetry>>,
) -> Self {
Self {
session: self.session.with_request_telemetry(request),
sse_telemetry: sse,
}
}
#[instrument(
name = "responses.stream_request",
level = "info",
skip_all,
fields(
transport = "responses_http",
http.method = "POST",
api.path = "/responses"
)
)]
pub async fn stream_request(
&self,
request: ResponsesApiRequest,
options: ResponsesOptions,
) -> Result<ResponseStream, ApiError> {
let ResponsesOptions {
session_id,
thread_id,
session_source,
extra_headers,
compression,
turn_state,
} = options;
let body = EncodedJsonBody::encode(&request)
.map_err(|e| ApiError::Stream(format!("failed to encode responses request: {e}")))?;
let mut headers = extra_headers;
if let Some(ref thread_id) = thread_id {
insert_header(&mut headers, "x-client-request-id", thread_id);
}
headers.extend(build_session_headers(session_id, thread_id));
if let Some(subagent) = subagent_header(&session_source) {
insert_header(&mut headers, "x-openai-subagent", &subagent);
}
self.stream_encoded(body, headers, compression, turn_state)
.await
}
#[instrument(
name = "responses.stream",
level = "info",
skip_all,
fields(
transport = "responses_http",
http.method = "POST",
api.path = "/responses",
turn.has_state = turn_state.is_some()
)
)]
pub async fn stream(
&self,
body: Value,
extra_headers: HeaderMap,
compression: Compression,
turn_state: Option<Arc<OnceLock<String>>>,
) -> Result<ResponseStream, ApiError> {
let body = EncodedJsonBody::encode(&body)
.map_err(|e| ApiError::Stream(format!("failed to encode responses request: {e}")))?;
self.stream_encoded(body, extra_headers, compression, turn_state)
.await
}
async fn stream_encoded(
&self,
body: EncodedJsonBody,
extra_headers: HeaderMap,
compression: Compression,
turn_state: Option<Arc<OnceLock<String>>>,
) -> Result<ResponseStream, ApiError> {
let request_compression = match compression {
Compression::None => RequestCompression::None,
Compression::Zstd => RequestCompression::Zstd,
};
let stream_response = self
.session
.stream_encoded_json_with(
Method::POST,
"/responses",
extra_headers,
Some(body),
|req| {
req.headers.insert(
http::header::ACCEPT,
HeaderValue::from_static("text/event-stream"),
);
req.compression = request_compression;
},
)
.await?;
Ok(spawn_response_stream(
stream_response,
self.session.provider().stream_idle_timeout,
self.sse_telemetry.clone(),
turn_state,
))
}
}

View File

@@ -18,11 +18,11 @@ use crate::safety_buffering::treatment_from_headers;
use crate::sse::ResponsesStreamEvent;
use crate::sse::process_responses_event;
use crate::telemetry::WebsocketTelemetry;
use codex_client::TransportError;
use codex_http_client::HttpClientFactory;
use codex_http_client::RetryAfter;
use codex_websocket_client::WebSocketConnection;
use codex_websocket_client::WebSocketConnector;
use akode_client::TransportError;
use akode_http_client::HttpClientFactory;
use akode_http_client::RetryAfter;
use akode_websocket_client::WebSocketConnection;
use akode_websocket_client::WebSocketConnector;
use futures::FutureExt;
use futures::SinkExt;
use futures::StreamExt;
@@ -175,7 +175,7 @@ const PREVIOUS_RESPONSE_NOT_FOUND_CODE: &str = "previous_response_not_found";
const PREVIOUS_RESPONSE_NOT_FOUND_MESSAGE: &str =
"Previous response was not found. Retrying the full request.";
const RESPONSES_WEBSOCKET_TIMING_KIND: &str = "responsesapi.websocket_timing";
const RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET: &str = "codex_api::responses_websocket_timing";
const RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET: &str = "akode_api::responses_websocket_timing";
const SESSION_ID_CLIENT_METADATA_KEY: &str = "session_id";
const THREAD_ID_CLIENT_METADATA_KEY: &str = "thread_id";
const TURN_ID_CLIENT_METADATA_KEY: &str = "turn_id";
@@ -639,14 +639,14 @@ fn websocket_config() -> WebSocketConfig {
}
fn map_ws_stream_error(error: WsError) -> ApiError {
match codex_websocket_client::network_policy_denial(&error) {
match akode_websocket_client::network_policy_denial(&error) {
Some(denied) => ApiError::Transport(TransportError::Policy(denied)),
None => ApiError::Stream(error.to_string()),
}
}
fn map_ws_error(err: WsError, url: &Url) -> ApiError {
if let Some(denied) = codex_websocket_client::network_policy_denial(&err) {
if let Some(denied) = akode_websocket_client::network_policy_denial(&err) {
return ApiError::Transport(TransportError::Policy(denied));
}
match err {
@@ -1015,7 +1015,7 @@ fn emit_responses_websocket_timing_event(
}
// This full payload is excluded from always-on sinks. Opt in with
// `RUST_LOG='codex_api::responses_websocket_timing=trace'`.
// `RUST_LOG='akode_api::responses_websocket_timing=trace'`.
tracing::event!(
name: RESPONSES_WEBSOCKET_TIMING_KIND,
target: RESPONSES_WEBSOCKET_TIMING_EVENT_TARGET,
@@ -1086,9 +1086,9 @@ mod tests {
use super::*;
use crate::common::ResponseCreateWsRequest;
use crate::common::ResponsesApiRequest;
use codex_protocol::ResponseItemId;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use http::HeaderValue;
use pretty_assertions::assert_eq;
use serde_json::json;
@@ -1133,7 +1133,7 @@ mod tests {
service_tier: Some("priority".to_string()),
prompt_cache_key: Some("cache-key".to_string()),
prompt_cache_options: Some(crate::PromptCacheOptions {
ttl: codex_protocol::turn_input::PromptCacheTtl::TwelveHours,
ttl: akode_protocol::turn_input::PromptCacheTtl::TwelveHours,
}),
text: None,
client_metadata: Some(HashMap::from([(
@@ -1268,7 +1268,7 @@ mod tests {
let wrapped = parse_wrapped_websocket_error_event(&payload).expect("websocket error");
let api_error = map_wrapped_websocket_error_event(wrapped, payload).expect("API error");
let err = crate::api_bridge::map_api_error(api_error);
let codex_protocol::error::CodexErrorDetails::UsageLimitReached(usage_limit) =
let akode_protocol::error::CodexErrorDetails::UsageLimitReached(usage_limit) =
err.details()
else {
panic!("expected usage-limit error, got {err:?}");

View File

@@ -8,7 +8,7 @@ use super::merge_request_headers;
use crate::ApiError;
use crate::RESPONSES_PATH;
use crate::WebsocketTelemetry;
use codex_websocket_client::WebSocketConnector;
use akode_websocket_client::WebSocketConnector;
use http::HeaderMap;
use std::sync::Arc;
use std::sync::OnceLock;

View File

@@ -0,0 +1,324 @@
use crate::auth::SharedAuthProvider;
use crate::endpoint::session::EndpointSession;
use crate::error::ApiError;
use crate::provider::Provider;
use crate::search::SearchRequest;
use crate::search::SearchResponse;
use akode_client::HttpTransport;
use akode_client::RequestTelemetry;
use http::HeaderMap;
use http::Method;
use serde_json::to_value;
use std::sync::Arc;
/// The provider-relative endpoint for standalone web search.
const SEARCH_ENDPOINT: &str = "alpha/search";
pub struct SearchClient<T: HttpTransport> {
session: EndpointSession<T>,
}
impl<T: HttpTransport> SearchClient<T> {
pub fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
session: EndpointSession::new(transport, provider, auth),
}
}
pub fn with_telemetry(self, request: Option<Arc<dyn RequestTelemetry>>) -> Self {
Self {
session: self.session.with_request_telemetry(request),
}
}
pub async fn search(
&self,
request: &SearchRequest,
extra_headers: HeaderMap,
) -> Result<SearchResponse, ApiError> {
let body = to_value(request)
.map_err(|e| ApiError::Stream(format!("failed to encode search request: {e}")))?;
let resp = self
.session
.execute(Method::POST, SEARCH_ENDPOINT, extra_headers, Some(body))
.await?;
serde_json::from_slice(&resp.body)
.map_err(|e| ApiError::Stream(format!("failed to decode search response: {e}")))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::auth::AuthProvider;
use crate::provider::RetryConfig;
use crate::search::AllowedCaller;
use crate::search::ApproximateLocation;
use crate::search::ExternalWebAccess;
use crate::search::LocationType;
use crate::search::OpenOperation;
use crate::search::SearchCommands;
use crate::search::SearchContextSize;
use crate::search::SearchFilters;
use crate::search::SearchImageSettings;
use crate::search::SearchInput;
use crate::search::SearchQuery;
use crate::search::SearchSettings;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ImageReference;
use akode_protocol::models::ResponseItem;
use http::StatusCode;
use pretty_assertions::assert_eq;
use serde_json::json;
use std::sync::Mutex;
use std::time::Duration;
#[derive(Clone, Default)]
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), crate::AuthError> {
Ok(())
}
}
#[derive(Clone)]
struct CapturingTransport {
last_request: Arc<Mutex<Option<Request>>>,
response_body: Arc<Vec<u8>>,
}
impl CapturingTransport {
fn new(response_body: Vec<u8>) -> Self {
Self {
last_request: Arc::new(Mutex::new(None)),
response_body: Arc::new(response_body),
}
}
}
impl HttpTransport for CapturingTransport {
async fn execute(&self, req: Request) -> Result<Response, TransportError> {
*self.last_request.lock().expect("lock request store") = Some(req);
Ok(Response {
status: StatusCode::OK,
headers: HeaderMap::new(),
body: self.response_body.as_ref().clone().into(),
})
}
async fn stream(&self, _req: Request) -> Result<StreamResponse, TransportError> {
Err(TransportError::Build("stream should not run".to_string()))
}
}
fn provider() -> Provider {
Provider {
name: "test".to_string(),
base_url: "https://example.com/v1".to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
retry_5xx: true,
retry_transport: true,
},
stream_idle_timeout: Duration::from_secs(1),
}
}
#[tokio::test]
async fn search_posts_typed_request_and_parses_output() {
let transport = CapturingTransport::new(
serde_json::to_vec(&json!({
"encrypted_output": "ciphertext",
"output": "search result",
"results": [{
"type": "text_result",
"ref_id": "turn0search0",
"url": "https://example.com/result",
"future_field": {"preserved": true},
}],
}))
.expect("serialize response"),
);
let client = SearchClient::new(transport.clone(), provider(), Arc::new(DummyAuth));
let response = client
.search(
&SearchRequest {
id: "search-session".to_string(),
model: "gpt-test".to_string(),
reasoning: None,
input: Some(SearchInput::Items(vec![ResponseItem::Message {
status: None,
encrypted_content: None,
id: Some(ResponseItemId::with_suffix("msg", "search")),
role: "user".to_string(),
content: vec![
ContentItem::InputText {
text: "find this".to_string(),
},
ContentItem::InputImage {
image: ImageReference::Inline {
image_url: "https://example.com/image.png".to_string(),
},
detail: None,
},
],
phase: None,
internal_chat_message_metadata_passthrough: None,
}])),
commands: Some(SearchCommands {
search_query: Some(vec![SearchQuery {
q: "OpenAI news".to_string(),
recency: Some(7),
domains: Some(vec!["openai.com".to_string()]),
}]),
open: Some(vec![OpenOperation {
ref_id: "https://openai.com".to_string(),
lineno: Some(12),
}]),
..Default::default()
}),
settings: Some(SearchSettings {
user_location: Some(ApproximateLocation {
r#type: LocationType::Approximate,
country: Some("US".to_string()),
region: None,
city: Some("San Francisco".to_string()),
timezone: None,
}),
search_context_size: Some(SearchContextSize::Low),
filters: Some(SearchFilters {
allowed_domains: Some(vec!["openai.com".to_string()]),
blocked_domains: Some(vec!["example.com".to_string()]),
}),
image_settings: Some(SearchImageSettings {
max_results: Some(4),
caption: Some(true),
}),
allowed_callers: Some(vec![AllowedCaller::Direct]),
external_web_access: Some(ExternalWebAccess::Boolean(true)),
}),
max_output_tokens: Some(2500),
},
HeaderMap::new(),
)
.await
.expect("search request should succeed");
assert_eq!(
response,
SearchResponse {
encrypted_output: Some("ciphertext".to_string()),
output: "search result".to_string(),
results: Some(vec![json!({
"type": "text_result",
"ref_id": "turn0search0",
"url": "https://example.com/result",
"future_field": {"preserved": true},
})]),
}
);
let request = transport
.last_request
.lock()
.expect("lock request store")
.clone()
.expect("request should be captured");
let body = request
.body
.as_ref()
.and_then(RequestBody::json)
.expect("request body should be JSON");
assert_eq!(
body,
&json!({
"id": "search-session",
"model": "gpt-test",
"input": [{
"type": "message",
"id": "msg_search",
"role": "user",
"content": [
{"type": "input_text", "text": "find this"},
{
"type": "input_image",
"image_url": "https://example.com/image.png"
}
]
}],
"commands": {
"search_query": [{
"q": "OpenAI news",
"recency": 7,
"domains": ["openai.com"]
}],
"open": [{"ref_id": "https://openai.com", "lineno": 12}]
},
"settings": {
"user_location": {
"type": "approximate",
"country": "US",
"city": "San Francisco"
},
"search_context_size": "low",
"filters": {
"allowed_domains": ["openai.com"],
"blocked_domains": ["example.com"]
},
"image_settings": {"max_results": 4, "caption": true},
"allowed_callers": ["direct"],
"external_web_access": true
},
"max_output_tokens": 2500
})
);
}
#[test]
fn search_response_defaults_missing_results_for_older_endpoints() {
let response: SearchResponse = serde_json::from_value(json!({
"encrypted_output": null,
"output": "search result",
}))
.expect("response without results should deserialize");
assert_eq!(
response,
SearchResponse {
encrypted_output: None,
output: "search result".to_string(),
results: None,
}
);
}
#[test]
fn search_response_preserves_supported_empty_results() {
let response: SearchResponse = serde_json::from_value(json!({
"encrypted_output": null,
"output": "search result",
"results": [],
}))
.expect("response with empty results should deserialize");
assert_eq!(
response,
SearchResponse {
encrypted_output: None,
output: "search result".to_string(),
results: Some(Vec::new()),
}
);
}
}

View File

@@ -0,0 +1,156 @@
use crate::auth::SharedAuthProvider;
use crate::error::ApiError;
use crate::provider::Provider;
use crate::telemetry::run_with_request_telemetry;
use akode_client::EncodedJsonBody;
use akode_client::HttpTransport;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::RequestTelemetry;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use http::HeaderMap;
use http::Method;
use serde_json::Value;
use std::sync::Arc;
use tracing::instrument;
pub(crate) struct EndpointSession<T: HttpTransport> {
transport: T,
provider: Provider,
auth: SharedAuthProvider,
request_telemetry: Option<Arc<dyn RequestTelemetry>>,
}
impl<T: HttpTransport> EndpointSession<T> {
pub(crate) fn new(transport: T, provider: Provider, auth: SharedAuthProvider) -> Self {
Self {
transport,
provider,
auth,
request_telemetry: None,
}
}
pub(crate) fn with_request_telemetry(
mut self,
request: Option<Arc<dyn RequestTelemetry>>,
) -> Self {
self.request_telemetry = request;
self
}
pub(crate) fn provider(&self) -> &Provider {
&self.provider
}
fn make_request(
&self,
method: &Method,
path: &str,
extra_headers: &HeaderMap,
body: Option<&RequestBody>,
) -> Request {
let mut req = self.provider.build_request(method.clone(), path);
req.headers.extend(extra_headers.clone());
if let Some(body) = body {
req.body = Some(body.clone());
}
req
}
pub(crate) async fn execute(
&self,
method: Method,
path: &str,
extra_headers: HeaderMap,
body: Option<Value>,
) -> Result<Response, ApiError> {
self.execute_with(method, path, extra_headers, body, |_| {})
.await
}
#[instrument(
name = "endpoint_session.execute_with",
level = "info",
skip_all,
fields(http.method = %method, api.path = path)
)]
pub(crate) async fn execute_with<C>(
&self,
method: Method,
path: &str,
extra_headers: HeaderMap,
body: Option<Value>,
configure: C,
) -> Result<Response, ApiError>
where
C: Fn(&mut Request),
{
let body = body.map(RequestBody::Json);
let make_request = || {
let mut req = self.make_request(&method, path, &extra_headers, body.as_ref());
configure(&mut req);
req
};
let response = run_with_request_telemetry(
self.provider.retry.to_policy(),
self.request_telemetry.clone(),
make_request,
|req| {
let auth = self.auth.clone();
let transport = &self.transport;
async move {
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
transport.execute(req).await
}
},
)
.await?;
Ok(response)
}
#[instrument(
name = "endpoint_session.stream_encoded_json_with",
level = "info",
skip_all,
fields(http.method = %method, api.path = path)
)]
pub(crate) async fn stream_encoded_json_with<C>(
&self,
method: Method,
path: &str,
extra_headers: HeaderMap,
body: Option<EncodedJsonBody>,
configure: C,
) -> Result<StreamResponse, ApiError>
where
C: Fn(&mut Request),
{
let body = body.map(RequestBody::EncodedJson);
let mut request = self.make_request(&method, path, &extra_headers, body.as_ref());
configure(&mut request);
let request = request.into_prepared().map_err(TransportError::Build)?;
let make_request = || request.clone();
let stream = run_with_request_telemetry(
self.provider.retry.to_policy(),
self.request_telemetry.clone(),
make_request,
|req| {
let auth = self.auth.clone();
let transport = &self.transport;
async move {
let req = auth.apply_auth(req).await.map_err(TransportError::from)?;
transport.stream(req).await
}
},
)
.await?;
Ok(stream)
}
}

View File

@@ -0,0 +1,131 @@
use crate::rate_limits::RateLimitError;
use akode_client::TransportError;
use akode_http_client::RetryAfter;
use akode_protocol::error::ResponseIncompleteError;
use akode_protocol::protocol::MisalignmentErrorDetails;
use http::StatusCode;
use serde_json::Value;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ApiError {
#[error(transparent)]
Transport(#[from] TransportError),
#[error("api error {status}: {message}")]
Api { status: StatusCode, message: String },
#[error("stream error: {0}")]
Stream(String),
#[error("stream error: Incomplete response returned, reason: content_filter")]
ContentFilter,
#[error(transparent)]
ResponseIncomplete(Box<ResponseIncompleteError>),
#[error("context window exceeded")]
ContextWindowExceeded,
#[error("quota exceeded")]
QuotaExceeded,
#[error("usage not included")]
UsageNotIncluded,
#[error("session budget exceeded")]
SessionBudgetExceeded,
#[error("retryable error: {message}")]
Retryable {
message: String,
retry_after: Option<RetryAfter>,
},
#[error("rate limit exceeded: {message}")]
RateLimitExceeded {
message: String,
retry_after: Option<RetryAfter>,
},
#[error("rate limit: {0}")]
RateLimit(String),
#[error("invalid request: {message}")]
InvalidRequest { message: String },
#[error("{message}")]
InvalidAudioInput {
message: String,
/// True when the provider rejected an individual clip, independent of request size.
per_recording: bool,
},
#[error("{message}")]
ModelNotFound {
message: String,
status: Option<StatusCode>,
},
#[error("invalid prompt: {message}")]
InvalidPrompt { message: String },
#[error("cyber policy: {message}")]
CyberPolicy { message: String },
#[error("bio policy: {message}")]
BioPolicy { message: String },
#[error("misalignment policy violation: {message}")]
MisalignmentPolicyViolation {
message: String,
misalignment: Option<MisalignmentErrorDetails>,
},
#[error("Flex capacity unavailable.")]
FlexUnavailable,
/// Server-confirmed capacity failure on a policy-restricted route.
#[error("policy-restricted capacity unavailable")]
PolicyCapacityUnavailable { retry_after: Option<RetryAfter> },
#[error("server overloaded")]
ServerOverloaded { retry_after: Option<RetryAfter> },
}
impl From<RateLimitError> for ApiError {
fn from(err: RateLimitError) -> Self {
Self::RateLimit(err.to_string())
}
}
pub(crate) fn parse_terminal_provider_error(
error: Option<&Value>,
status: Option<StatusCode>,
) -> Option<ApiError> {
let error = error?;
let code = error.get("code")?.as_str()?;
match (code, status) {
("budget_reached", None | Some(StatusCode::BAD_REQUEST)) => {
Some(ApiError::SessionBudgetExceeded)
}
(
"audio_too_large"
| "audio_too_short"
| "invalid_audio"
| "invalid_audio_data"
| "invalid_audio_format"
| "missing_audio_sample_rate",
None | Some(StatusCode::BAD_REQUEST),
) => Some(ApiError::InvalidAudioInput {
per_recording: code != "audio_too_large",
message: error
.get("message")
.and_then(Value::as_str)
.filter(|message| !message.trim().is_empty())
.unwrap_or("Invalid audio input.")
.to_owned(),
}),
("flex_unavailable", None | Some(StatusCode::TOO_MANY_REQUESTS)) => {
Some(ApiError::FlexUnavailable)
}
(
"model_not_found",
None | Some(StatusCode::BAD_REQUEST | StatusCode::FORBIDDEN | StatusCode::NOT_FOUND),
) => Some(ApiError::ModelNotFound {
message: error
.get("message")
.and_then(Value::as_str)
.filter(|message| !message.trim().is_empty())
.unwrap_or(code)
.to_owned(),
status,
}),
_ => None,
}
}
impl From<crate::AuthError> for ApiError {
fn from(error: crate::AuthError) -> Self {
Self::Transport(error.into())
}
}

View File

@@ -0,0 +1,116 @@
pub(crate) mod api_bridge;
pub(crate) mod auth;
pub(crate) mod common;
pub(crate) mod endpoint;
pub(crate) mod error;
mod guardian_assessment;
pub(crate) mod provider;
pub(crate) mod rate_limits;
pub(crate) mod requests;
mod responses_headers;
pub(crate) mod safety_buffering;
pub(crate) mod search;
pub(crate) mod sse;
pub(crate) mod telemetry;
/// Path of the Responses endpoint, relative to a provider's base URL.
pub const RESPONSES_PATH: &str = "/responses";
pub use crate::requests::headers::build_session_headers;
pub use akode_client::RequestTelemetry;
pub use akode_client::ReqwestTransport;
pub use akode_client::TransportError;
pub use crate::api_bridge::map_api_error;
pub use crate::auth::AuthError;
pub use crate::auth::AuthHeaderTelemetry;
pub use crate::auth::AuthHeadersFuture;
pub use crate::auth::AuthProvider;
pub use crate::auth::AuthProviderFuture;
pub use crate::auth::AuthRefreshFuture;
pub use crate::auth::SharedAuthProvider;
pub use crate::auth::auth_header_telemetry;
pub use crate::common::MemorySummarizeInput;
pub use crate::common::MemorySummarizeOutput;
pub use crate::common::OpenAiVerbosity;
pub use crate::common::PromptCacheOptions;
pub use crate::common::RawMemory;
pub use crate::common::RawMemoryMetadata;
pub use crate::common::Reasoning;
pub use crate::common::ReasoningContext;
pub use crate::common::ReasoningSummaryDelivery;
pub use crate::common::ResponseCreateWsRequest;
pub use crate::common::ResponseEvent;
pub use crate::common::ResponseId;
pub use crate::common::ResponseInterrupt;
pub use crate::common::ResponseStream;
pub use crate::common::ResponsesApiRequest;
pub use crate::common::ResponsesApiTools;
pub use crate::common::ResponsesWsRequest;
pub use crate::common::StreamOptions;
pub use crate::common::TextControls;
pub use crate::common::WS_REQUEST_HEADER_TRACEPARENT_CLIENT_METADATA_KEY;
pub use crate::common::WS_REQUEST_HEADER_TRACESTATE_CLIENT_METADATA_KEY;
pub use crate::common::create_text_param_for_request;
pub use crate::common::response_create_client_metadata;
pub use crate::endpoint::MemoriesClient;
pub use crate::endpoint::ModelsClient;
pub use crate::endpoint::RealtimeCallClient;
pub use crate::endpoint::RealtimeCallResponse;
pub use crate::endpoint::RealtimeContextAppendChannel;
pub use crate::endpoint::RealtimeEventParser;
pub use crate::endpoint::RealtimeOutputModality;
pub use crate::endpoint::RealtimeSessionConfig;
pub use crate::endpoint::RealtimeSessionMode;
pub use crate::endpoint::RealtimeTranscriptState;
pub use crate::endpoint::RealtimeWebsocketClient;
pub use crate::endpoint::RealtimeWebsocketConnection;
pub use crate::endpoint::RealtimeWebsocketEvents;
pub use crate::endpoint::RealtimeWebsocketWriter;
pub use crate::endpoint::ResponsesClient;
pub use crate::endpoint::ResponsesOptions;
pub use crate::endpoint::ResponsesWebsocketClient;
pub use crate::endpoint::ResponsesWebsocketClose;
pub use crate::endpoint::ResponsesWebsocketConnection;
pub use crate::endpoint::ResponsesWebsocketProbe;
pub use crate::endpoint::ResponsesWebsocketProbeError;
pub use crate::endpoint::ResponsesWebsocketProbeFailureStage;
pub use crate::endpoint::SearchClient;
pub use crate::endpoint::session_update_session_json;
pub use crate::error::ApiError;
pub use crate::guardian_assessment::GuardianAssessment;
pub use crate::provider::Provider;
pub use crate::provider::RetryConfig;
pub use crate::provider::is_azure_responses_provider;
pub use crate::requests::Compression;
pub use crate::search::AllowedCaller;
pub use crate::search::ApproximateLocation;
pub use crate::search::ClickOperation;
pub use crate::search::ExternalWebAccess;
pub use crate::search::ExternalWebAccessMode;
pub use crate::search::FinanceAssetType;
pub use crate::search::FinanceOperation;
pub use crate::search::FindOperation;
pub use crate::search::LocationType;
pub use crate::search::OpenOperation;
pub use crate::search::ScreenshotOperation;
pub use crate::search::SearchCommands;
pub use crate::search::SearchContextSize;
pub use crate::search::SearchFilters;
pub use crate::search::SearchImageSettings;
pub use crate::search::SearchInput;
pub use crate::search::SearchQuery;
pub use crate::search::SearchRequest;
pub use crate::search::SearchResponse;
pub use crate::search::SearchResponseLength;
pub use crate::search::SearchSettings;
pub use crate::search::SportsFunction;
pub use crate::search::SportsLeague;
pub use crate::search::SportsOperation;
pub use crate::search::SportsToolName;
pub use crate::search::TimeOperation;
pub use crate::search::WeatherOperation;
pub use crate::telemetry::SseTelemetry;
pub use crate::telemetry::WebsocketTelemetry;
pub use akode_protocol::protocol::RealtimeAudioFrame;
pub use akode_protocol::protocol::RealtimeEvent;

View File

@@ -0,0 +1,67 @@
pub use akode_client::Provider;
pub use akode_client::RetryConfig;
pub fn is_azure_responses_provider(name: &str, base_url: Option<&str>) -> bool {
if name.eq_ignore_ascii_case("azure") {
true
} else if let Some(base_url) = base_url {
matches_azure_responses_base_url(base_url)
} else {
false
}
}
fn matches_azure_responses_base_url(base_url: &str) -> bool {
let base_url = base_url.to_ascii_lowercase();
const AZURE_MARKERS: [&str; 6] = [
"openai.azure.",
"cognitiveservices.azure.",
"aoai.azure.",
"azure-api.",
"azurefd.",
"windows.net/openai",
];
AZURE_MARKERS.iter().any(|marker| base_url.contains(marker))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn detects_azure_responses_base_urls() {
let positive_cases = [
"https://foo.openai.azure.com/openai",
"https://foo.openai.azure.us/openai/deployments/bar",
"https://foo.cognitiveservices.azure.cn/openai",
"https://foo.aoai.azure.com/openai",
"https://foo.openai.azure-api.net/openai",
"https://foo.z01.azurefd.net/",
];
for base_url in positive_cases {
assert!(
is_azure_responses_provider("test", Some(base_url)),
"expected {base_url} to be detected as Azure"
);
}
assert!(is_azure_responses_provider(
"Azure",
Some("https://example.com")
));
let negative_cases = [
"https://api.openai.com/v1",
"https://example.com/openai",
"https://myproxy.azurewebsites.net/openai",
];
for base_url in negative_cases {
assert!(
!is_azure_responses_provider("test", Some(base_url)),
"expected {base_url} not to be detected as Azure"
);
}
}
}

View File

@@ -0,0 +1,382 @@
use akode_protocol::account::PlanType;
use akode_protocol::protocol::CreditsSnapshot;
use akode_protocol::protocol::RateLimitReachedType;
use akode_protocol::protocol::RateLimitSnapshot;
use akode_protocol::protocol::RateLimitWindow;
use http::HeaderMap;
use serde::Deserialize;
use std::collections::BTreeSet;
use std::fmt::Display;
#[derive(Debug)]
pub struct RateLimitError {
pub message: String,
}
impl Display for RateLimitError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
/// Parses the default Codex rate-limit header family into a `RateLimitSnapshot`.
pub fn parse_default_rate_limit(headers: &HeaderMap) -> Option<RateLimitSnapshot> {
parse_rate_limit_for_limit(headers, /*limit_id*/ None)
}
/// Parses all known rate-limit header families into update records keyed by limit id.
pub fn parse_all_rate_limits(headers: &HeaderMap) -> Vec<RateLimitSnapshot> {
let mut snapshots = Vec::new();
if let Some(snapshot) = parse_default_rate_limit(headers) {
snapshots.push(snapshot);
}
let mut limit_ids: BTreeSet<String> = BTreeSet::new();
for name in headers.keys() {
let header_name = name.as_str().to_ascii_lowercase();
if let Some(limit_id) = header_name_to_limit_id(&header_name)
&& limit_id != "codex"
{
limit_ids.insert(limit_id);
}
}
snapshots.extend(limit_ids.into_iter().filter_map(|limit_id| {
let snapshot = parse_rate_limit_for_limit(headers, Some(limit_id.as_str()))?;
has_rate_limit_data(&snapshot).then_some(snapshot)
}));
snapshots
}
/// Parses rate-limit headers for the provided limit id.
///
/// `limit_id` should match the server-provided metered limit id (e.g. `codex`,
/// `codex_other`). When omitted, this defaults to the legacy `codex` header family.
pub fn parse_rate_limit_for_limit(
headers: &HeaderMap,
limit_id: Option<&str>,
) -> Option<RateLimitSnapshot> {
let normalized_limit = limit_id
.map(str::trim)
.filter(|name| !name.is_empty())
.unwrap_or("codex")
.to_ascii_lowercase()
.replace('_', "-");
let prefix = format!("x-{normalized_limit}");
let primary = parse_rate_limit_window(
headers,
&format!("{prefix}-primary-used-percent"),
&format!("{prefix}-primary-window-minutes"),
&format!("{prefix}-primary-reset-at"),
);
let secondary = parse_rate_limit_window(
headers,
&format!("{prefix}-secondary-used-percent"),
&format!("{prefix}-secondary-window-minutes"),
&format!("{prefix}-secondary-reset-at"),
);
let normalized_limit_id = normalize_limit_id(normalized_limit);
let credits = parse_credits_snapshot(headers);
let limit_name_header = format!("{prefix}-limit-name");
let parsed_limit_name = parse_header_str(headers, &limit_name_header)
.map(str::trim)
.filter(|name| !name.is_empty())
.map(std::string::ToString::to_string);
Some(RateLimitSnapshot {
limit_id: Some(normalized_limit_id),
limit_name: parsed_limit_name,
normal_model_slug: None,
primary,
secondary,
credits,
individual_limit: None,
spend_control_reached: None,
plan_type: None,
rate_limit_reached_type: None,
})
}
#[derive(Debug, Deserialize)]
struct RateLimitEventWindow {
used_percent: f64,
window_minutes: Option<i64>,
reset_at: Option<i64>,
}
#[derive(Debug, Deserialize)]
struct RateLimitEventDetails {
primary: Option<RateLimitEventWindow>,
secondary: Option<RateLimitEventWindow>,
}
#[derive(Debug, Deserialize)]
struct RateLimitEventCredits {
has_credits: bool,
unlimited: bool,
balance: Option<String>,
}
#[derive(Debug, Deserialize)]
struct RateLimitEvent {
#[serde(rename = "type")]
kind: String,
plan_type: Option<PlanType>,
rate_limits: Option<RateLimitEventDetails>,
credits: Option<RateLimitEventCredits>,
metered_limit_name: Option<String>,
limit_name: Option<String>,
}
pub fn parse_rate_limit_event(payload: &str) -> Option<RateLimitSnapshot> {
let event: RateLimitEvent = serde_json::from_str(payload).ok()?;
if event.kind != "codex.rate_limits" {
return None;
}
let (primary, secondary) = if let Some(details) = event.rate_limits.as_ref() {
(
map_event_window(details.primary.as_ref()),
map_event_window(details.secondary.as_ref()),
)
} else {
(None, None)
};
let credits = event.credits.map(|credits| CreditsSnapshot {
has_credits: credits.has_credits,
unlimited: credits.unlimited,
balance: credits.balance,
});
let limit_id = event
.metered_limit_name
.or(event.limit_name)
.map(normalize_limit_id);
Some(RateLimitSnapshot {
limit_id: Some(limit_id.unwrap_or_else(|| "codex".to_string())),
limit_name: None,
normal_model_slug: None,
primary,
secondary,
credits,
individual_limit: None,
spend_control_reached: None,
plan_type: event.plan_type,
rate_limit_reached_type: None,
})
}
fn map_event_window(window: Option<&RateLimitEventWindow>) -> Option<RateLimitWindow> {
let window = window?;
Some(RateLimitWindow {
used_percent: window.used_percent,
window_minutes: window.window_minutes,
resets_at: window.reset_at,
})
}
/// Parses the bespoke Codex rate-limit headers into a `RateLimitSnapshot`.
pub fn parse_promo_message(headers: &HeaderMap) -> Option<String> {
parse_header_str(headers, "x-codex-promo-message")
.map(str::trim)
.filter(|value| !value.is_empty())
.map(std::string::ToString::to_string)
}
pub(crate) fn parse_rate_limit_reached_type(headers: &HeaderMap) -> Option<RateLimitReachedType> {
parse_header_str(headers, "x-codex-rate-limit-reached-type")?
.trim()
.parse()
.ok()
}
fn parse_rate_limit_window(
headers: &HeaderMap,
used_percent_header: &str,
window_minutes_header: &str,
resets_at_header: &str,
) -> Option<RateLimitWindow> {
let used_percent: Option<f64> = parse_header_f64(headers, used_percent_header);
used_percent.and_then(|used_percent| {
let window_minutes = parse_header_i64(headers, window_minutes_header);
let resets_at = parse_header_i64(headers, resets_at_header);
let has_data = used_percent != 0.0
|| window_minutes.is_some_and(|minutes| minutes != 0)
|| resets_at.is_some();
has_data.then_some(RateLimitWindow {
used_percent,
window_minutes,
resets_at,
})
})
}
fn parse_credits_snapshot(headers: &HeaderMap) -> Option<CreditsSnapshot> {
let has_credits = parse_header_bool(headers, "x-codex-credits-has-credits")?;
let unlimited = parse_header_bool(headers, "x-codex-credits-unlimited")?;
let balance = parse_header_str(headers, "x-codex-credits-balance")
.map(str::trim)
.filter(|value| !value.is_empty())
.map(std::string::ToString::to_string);
Some(CreditsSnapshot {
has_credits,
unlimited,
balance,
})
}
fn parse_header_f64(headers: &HeaderMap, name: &str) -> Option<f64> {
parse_header_str(headers, name)?
.parse::<f64>()
.ok()
.filter(|v| v.is_finite())
}
fn parse_header_i64(headers: &HeaderMap, name: &str) -> Option<i64> {
parse_header_str(headers, name)?.parse::<i64>().ok()
}
fn parse_header_bool(headers: &HeaderMap, name: &str) -> Option<bool> {
let raw = parse_header_str(headers, name)?;
if raw.eq_ignore_ascii_case("true") || raw == "1" {
Some(true)
} else if raw.eq_ignore_ascii_case("false") || raw == "0" {
Some(false)
} else {
None
}
}
fn parse_header_str<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
headers.get(name)?.to_str().ok()
}
fn has_rate_limit_data(snapshot: &RateLimitSnapshot) -> bool {
snapshot.primary.is_some() || snapshot.secondary.is_some() || snapshot.credits.is_some()
}
fn header_name_to_limit_id(header_name: &str) -> Option<String> {
let suffix = "-primary-used-percent";
let prefix = header_name.strip_suffix(suffix)?;
let limit = prefix.strip_prefix("x-")?;
Some(normalize_limit_id(limit.to_string()))
}
fn normalize_limit_id(name: impl Into<String>) -> String {
name.into().trim().to_ascii_lowercase().replace('-', "_")
}
#[cfg(test)]
mod tests {
use super::*;
use http::HeaderValue;
use pretty_assertions::assert_eq;
#[test]
fn parse_rate_limit_for_limit_defaults_to_codex_headers() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-primary-used-percent",
HeaderValue::from_static("12.5"),
);
headers.insert(
"x-codex-primary-window-minutes",
HeaderValue::from_static("60"),
);
headers.insert(
"x-codex-primary-reset-at",
HeaderValue::from_static("1704069000"),
);
let snapshot = parse_rate_limit_for_limit(&headers, /*limit_id*/ None).expect("snapshot");
assert_eq!(snapshot.limit_id.as_deref(), Some("codex"));
assert_eq!(snapshot.limit_name, None);
let primary = snapshot.primary.expect("primary");
assert_eq!(primary.used_percent, 12.5);
assert_eq!(primary.window_minutes, Some(60));
assert_eq!(primary.resets_at, Some(1704069000));
}
#[test]
fn parse_rate_limit_for_limit_reads_secondary_headers() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-secondary-primary-used-percent",
HeaderValue::from_static("80"),
);
headers.insert(
"x-codex-secondary-primary-window-minutes",
HeaderValue::from_static("1440"),
);
headers.insert(
"x-codex-secondary-primary-reset-at",
HeaderValue::from_static("1704074400"),
);
let snapshot =
parse_rate_limit_for_limit(&headers, Some("codex_secondary")).expect("snapshot");
assert_eq!(snapshot.limit_id.as_deref(), Some("codex_secondary"));
assert_eq!(snapshot.limit_name, None);
let primary = snapshot.primary.expect("primary");
assert_eq!(primary.used_percent, 80.0);
assert_eq!(primary.window_minutes, Some(1440));
assert_eq!(primary.resets_at, Some(1704074400));
assert_eq!(snapshot.secondary, None);
}
#[test]
fn parse_rate_limit_for_limit_prefers_limit_name_header() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-bengalfox-primary-used-percent",
HeaderValue::from_static("80"),
);
headers.insert(
"x-codex-bengalfox-limit-name",
HeaderValue::from_static("gpt-5.2-codex-sonic"),
);
let snapshot =
parse_rate_limit_for_limit(&headers, Some("codex_bengalfox")).expect("snapshot");
assert_eq!(snapshot.limit_id.as_deref(), Some("codex_bengalfox"));
assert_eq!(snapshot.limit_name.as_deref(), Some("gpt-5.2-codex-sonic"));
}
#[test]
fn parse_all_rate_limits_reads_all_limit_families() {
let mut headers = HeaderMap::new();
headers.insert(
"x-codex-primary-used-percent",
HeaderValue::from_static("12.5"),
);
headers.insert(
"x-codex-secondary-primary-used-percent",
HeaderValue::from_static("80"),
);
let updates = parse_all_rate_limits(&headers);
assert_eq!(updates.len(), 2);
assert_eq!(updates[0].limit_id.as_deref(), Some("codex"));
assert_eq!(updates[1].limit_id.as_deref(), Some("codex_secondary"));
assert_eq!(updates[0].limit_name, None);
assert_eq!(updates[1].limit_name, None);
}
#[test]
fn parse_all_rate_limits_includes_default_codex_snapshot() {
let headers = HeaderMap::new();
let updates = parse_all_rate_limits(&headers);
assert_eq!(updates.len(), 1);
assert_eq!(updates[0].limit_id.as_deref(), Some("codex"));
assert_eq!(updates[0].limit_name, None);
assert_eq!(updates[0].primary, None);
assert_eq!(updates[0].secondary, None);
assert_eq!(updates[0].credits, None);
}
}

View File

@@ -0,0 +1,40 @@
use akode_protocol::protocol::SessionSource;
use http::HeaderMap;
use http::HeaderValue;
pub fn build_session_headers(session_id: Option<String>, thread_id: Option<String>) -> HeaderMap {
let mut headers = HeaderMap::new();
if let Some(id) = session_id {
insert_header(&mut headers, "session-id", &id);
}
if let Some(id) = thread_id {
insert_header(&mut headers, "thread-id", &id);
}
headers
}
pub(crate) fn subagent_header(source: &Option<SessionSource>) -> Option<String> {
let SessionSource::SubAgent(sub) = source.as_ref()? else {
return None;
};
match sub {
akode_protocol::protocol::SubAgentSource::Review => Some("review".to_string()),
akode_protocol::protocol::SubAgentSource::Compact => Some("compact".to_string()),
akode_protocol::protocol::SubAgentSource::MemoryConsolidation => {
Some("memory_consolidation".to_string())
}
akode_protocol::protocol::SubAgentSource::ThreadSpawn { .. } => {
Some("collab_spawn".to_string())
}
akode_protocol::protocol::SubAgentSource::Other(label) => Some(label.clone()),
}
}
pub(crate) fn insert_header(headers: &mut HeaderMap, name: &str, value: &str) {
if let (Ok(header_name), Ok(header_value)) = (
name.parse::<http::HeaderName>(),
HeaderValue::from_str(value),
) {
headers.insert(header_name, header_value);
}
}

View File

@@ -0,0 +1,308 @@
use crate::common::Reasoning;
use akode_protocol::models::ResponseItem;
use schemars::JsonSchema;
use serde::Deserialize;
use serde::Serialize;
use serde_json::Value as JsonValue;
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct SearchRequest {
pub id: String,
pub model: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reasoning: Option<Reasoning>,
#[serde(skip_serializing_if = "Option::is_none")]
pub input: Option<SearchInput>,
#[serde(skip_serializing_if = "Option::is_none")]
pub commands: Option<SearchCommands>,
#[serde(skip_serializing_if = "Option::is_none")]
pub settings: Option<SearchSettings>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u64>,
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(untagged)]
pub enum SearchInput {
Text(String),
Items(Vec<ResponseItem>),
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, JsonSchema)]
pub struct SearchCommands {
/// Query the internet search engine for a given list of queries.
#[serde(skip_serializing_if = "Option::is_none")]
pub search_query: Option<Vec<SearchQuery>>,
/// Search for scientific papers. Open relevant papers and cite the primary sources you use.
#[serde(skip_serializing_if = "Option::is_none")]
pub literature_search_query: Option<Vec<SearchQuery>>,
/// Query the image search engine for a given list of queries.
#[serde(skip_serializing_if = "Option::is_none")]
pub image_query: Option<Vec<SearchQuery>>,
/// Open pages by reference id or URL.
#[serde(skip_serializing_if = "Option::is_none")]
pub open: Option<Vec<OpenOperation>>,
/// Open links from previously opened pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub click: Option<Vec<ClickOperation>>,
/// Find text patterns in pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub find: Option<Vec<FindOperation>>,
/// Take screenshots of PDF pages.
#[serde(skip_serializing_if = "Option::is_none")]
pub screenshot: Option<Vec<ScreenshotOperation>>,
/// Look up prices for the given stock symbols.
#[serde(skip_serializing_if = "Option::is_none")]
pub finance: Option<Vec<FinanceOperation>>,
/// Look up weather forecasts.
#[serde(skip_serializing_if = "Option::is_none")]
pub weather: Option<Vec<WeatherOperation>>,
/// Look up sports schedules and standings.
#[serde(skip_serializing_if = "Option::is_none")]
pub sports: Option<Vec<SportsOperation>>,
/// Get time for the given UTC offsets.
#[serde(skip_serializing_if = "Option::is_none")]
pub time: Option<Vec<TimeOperation>>,
/// Set the length of the response to be returned.
#[serde(skip_serializing_if = "Option::is_none")]
pub response_length: Option<SearchResponseLength>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct SearchQuery {
/// Search query.
pub q: String,
/// Whether to filter by recency, as a number of recent days.
#[serde(skip_serializing_if = "Option::is_none")]
pub recency: Option<u64>,
/// Whether to filter by a specific list of domains.
#[serde(skip_serializing_if = "Option::is_none")]
pub domains: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct OpenOperation {
/// Reference id or URL to open.
pub ref_id: String,
/// Line number to position the page at.
#[serde(skip_serializing_if = "Option::is_none")]
pub lineno: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct ClickOperation {
/// Reference id containing the numbered link.
pub ref_id: String,
/// Numbered link id to open.
pub id: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct FindOperation {
/// Reference id or URL to search within.
pub ref_id: String,
/// Text pattern to find.
pub pattern: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct ScreenshotOperation {
/// Reference id or URL to screenshot.
pub ref_id: String,
/// Zero-indexed PDF page number.
pub pageno: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct FinanceOperation {
/// Ticker symbol to look up.
pub ticker: String,
/// Asset type to look up.
pub r#type: FinanceAssetType,
/// ISO 3166-1 alpha-3 country code, "OTC", or "" for cryptocurrency.
#[serde(skip_serializing_if = "Option::is_none")]
pub market: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FinanceAssetType {
Equity,
Fund,
Crypto,
Index,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct WeatherOperation {
/// Location in "Country, Area, City" format.
pub location: String,
/// Start date in YYYY-MM-DD format. Defaults to today.
#[serde(skip_serializing_if = "Option::is_none")]
pub start: Option<String>,
/// Number of days to return. Defaults to 7.
#[serde(skip_serializing_if = "Option::is_none")]
pub duration: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, JsonSchema)]
pub struct SportsOperation {
/// Tool name for sports requests.
#[serde(skip_serializing_if = "Option::is_none")]
pub tool: Option<SportsToolName>,
/// Sports function to call.
pub r#fn: SportsFunction,
/// League to look up.
pub league: SportsLeague,
/// Team to look up, using the common 3 or 4 letter alias used in broadcasts.
#[serde(skip_serializing_if = "Option::is_none")]
pub team: Option<String>,
/// Opponent to use with `team` when narrowing the lookup.
#[serde(skip_serializing_if = "Option::is_none")]
pub opponent: Option<String>,
/// Start date in YYYY-MM-DD format.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_from: Option<String>,
/// End date in YYYY-MM-DD format.
#[serde(skip_serializing_if = "Option::is_none")]
pub date_to: Option<String>,
/// Number of games to return.
#[serde(skip_serializing_if = "Option::is_none")]
pub num_games: Option<u64>,
/// Locale for the lookup.
#[serde(skip_serializing_if = "Option::is_none")]
pub locale: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SportsToolName {
Sports,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SportsFunction {
Schedule,
Standings,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SportsLeague {
Nba,
Wnba,
Nfl,
Nhl,
Mlb,
Epl,
Ncaamb,
Ncaawb,
Ipl,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
pub struct TimeOperation {
/// UTC offset formatted like "+03:00".
pub utc_offset: String,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum SearchResponseLength {
Short,
Medium,
Long,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(rename_all = "snake_case")]
pub enum ExternalWebAccessMode {
Cached,
Indexed,
Live,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
#[serde(untagged)]
pub enum ExternalWebAccess {
Boolean(bool),
Mode(ExternalWebAccessMode),
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct SearchSettings {
#[serde(skip_serializing_if = "Option::is_none")]
pub user_location: Option<ApproximateLocation>,
#[serde(skip_serializing_if = "Option::is_none")]
pub search_context_size: Option<SearchContextSize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub filters: Option<SearchFilters>,
#[serde(skip_serializing_if = "Option::is_none")]
pub image_settings: Option<SearchImageSettings>,
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_callers: Option<Vec<AllowedCaller>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_web_access: Option<ExternalWebAccess>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ApproximateLocation {
pub r#type: LocationType,
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub region: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub city: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub timezone: Option<String>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LocationType {
Approximate,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SearchContextSize {
Low,
Medium,
High,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct SearchFilters {
#[serde(skip_serializing_if = "Option::is_none")]
pub allowed_domains: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub blocked_domains: Option<Vec<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
pub struct SearchImageSettings {
#[serde(skip_serializing_if = "Option::is_none")]
pub max_results: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
pub caption: Option<bool>,
}
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum AllowedCaller {
Direct,
Shell,
CodeInterpreter,
}
#[derive(Debug, Clone, Deserialize, PartialEq, Eq)]
pub struct SearchResponse {
pub encrypted_output: Option<String>,
pub output: String,
/// Structured result DTOs are passed to clients out-of-band from `output`.
/// Keep them opaque here so newer result variants remain forward-compatible.
#[serde(default)]
pub results: Option<Vec<JsonValue>>,
}

File diff suppressed because it is too large Load Diff

View File

@@ -4,8 +4,8 @@
use crate::error::ApiError;
use crate::error::parse_terminal_provider_error;
use crate::responses_headers::json_headers_to_http_headers;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::MisalignmentErrorDetails;
use akode_http_client::RetryAfter;
use akode_protocol::protocol::MisalignmentErrorDetails;
use serde::Deserialize;
use serde_json::Value;
use std::time::Duration;

View File

@@ -5,9 +5,9 @@ use super::spawn_response_stream;
use crate::api_bridge::map_api_error;
use crate::common::ResponseEvent;
use bytes::Bytes;
use codex_client::StreamResponse;
use codex_http_client::RetryAfter;
use codex_protocol::protocol::CodexErrorInfo;
use akode_client::StreamResponse;
use akode_http_client::RetryAfter;
use akode_protocol::protocol::CodexErrorInfo;
use futures::StreamExt;
use futures::stream;
use http::HeaderMap;
@@ -50,7 +50,7 @@ fn audio_validation_codes_map_to_non_retryable_audio_input_errors_on_all_transpo
assert_eq!(error.retry_delay(/*retry_count*/ 1), None);
assert!(matches!(
error.details(),
codex_protocol::error::CodexErrorDetails::InvalidAudioInput { .. }
akode_protocol::error::CodexErrorDetails::InvalidAudioInput { .. }
));
assert_eq!(error.to_string(), "Invalid recording.");
}

View File

@@ -0,0 +1,98 @@
use crate::error::ApiError;
use akode_client::Request;
use akode_client::RequestTelemetry;
use akode_client::Response;
use akode_client::RetryPolicy;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_client::run_with_retry;
use http::StatusCode;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::Instant;
/// Generic telemetry.
pub trait SseTelemetry: Send + Sync {
fn on_sse_poll(
&self,
result: &Result<
Option<
Result<
eventsource_stream::Event,
eventsource_stream::EventStreamError<TransportError>,
>,
>,
tokio::time::error::Elapsed,
>,
duration: Duration,
);
}
/// Telemetry for Responses WebSocket transport.
pub trait WebsocketTelemetry: Send + Sync {
/// Reports how long it took to send the request and whether the send failed.
fn on_ws_request(&self, duration: Duration, error: Option<&ApiError>, connection_reused: bool);
/// Reports the poll duration for timeouts, stream errors, end of stream,
/// and binary, close, or raw frames.
fn on_ws_receive_failure(&self, duration: Duration);
/// Reports each text frame and its poll duration. `kind` is `None` if decoding the stream event failed.
fn on_ws_text_event(&self, text: &str, kind: Option<&str>, duration: Duration);
}
pub(crate) trait WithStatus {
fn status(&self) -> StatusCode;
}
fn http_status(err: &TransportError) -> Option<StatusCode> {
match err {
TransportError::Http { status, .. } => Some(*status),
_ => None,
}
}
impl WithStatus for Response {
fn status(&self) -> StatusCode {
self.status
}
}
impl WithStatus for StreamResponse {
fn status(&self) -> StatusCode {
self.status
}
}
pub(crate) async fn run_with_request_telemetry<T, F, Fut>(
policy: RetryPolicy,
telemetry: Option<Arc<dyn RequestTelemetry>>,
make_request: impl FnMut() -> Request,
send: F,
) -> Result<T, TransportError>
where
T: WithStatus,
F: Clone + Fn(Request) -> Fut,
Fut: Future<Output = Result<T, TransportError>>,
{
// Wraps `run_with_retry` to attach per-attempt request telemetry for both
// unary and streaming HTTP calls.
run_with_retry(policy, make_request, move |req, attempt| {
let telemetry = telemetry.clone();
let send = send.clone();
async move {
let start = Instant::now();
let result = send(req).await;
if let Some(t) = telemetry.as_ref() {
let (status, err) = match &result {
Ok(resp) => (Some(resp.status()), None),
Err(err) => (http_status(err), Some(err)),
};
t.on_request(attempt, status, err, start.elapsed());
}
result
}
})
.await
}

View File

@@ -5,25 +5,25 @@ use std::time::Duration;
use anyhow::Result;
use bytes::Bytes;
use codex_api::ApiError;
use codex_api::AuthError;
use codex_api::AuthProvider;
use codex_api::Compression;
use codex_api::Provider;
use codex_api::ResponsesApiRequest;
use codex_api::ResponsesClient;
use codex_api::ResponsesOptions;
use codex_client::HttpTransport;
use codex_client::Request;
use codex_client::RequestBody;
use codex_client::Response;
use codex_client::StreamResponse;
use codex_client::TransportError;
use codex_protocol::ResponseItemId;
use codex_protocol::models::ContentItem;
use codex_protocol::models::ResponseItem;
use codex_protocol::protocol::SessionSource;
use codex_protocol::protocol::SubAgentSource;
use akode_api::ApiError;
use akode_api::AuthError;
use akode_api::AuthProvider;
use akode_api::Compression;
use akode_api::Provider;
use akode_api::ResponsesApiRequest;
use akode_api::ResponsesClient;
use akode_api::ResponsesOptions;
use akode_client::HttpTransport;
use akode_client::Request;
use akode_client::RequestBody;
use akode_client::Response;
use akode_client::StreamResponse;
use akode_client::TransportError;
use akode_protocol::ResponseItemId;
use akode_protocol::models::ContentItem;
use akode_protocol::models::ResponseItem;
use akode_protocol::protocol::SessionSource;
use akode_protocol::protocol::SubAgentSource;
use http::HeaderMap;
use http::HeaderValue;
use http::StatusCode;
@@ -144,7 +144,7 @@ fn provider(name: &str) -> Provider {
base_url: "https://example.com/v1".to_string(),
query_params: None,
headers: HeaderMap::new(),
retry: codex_api::RetryConfig {
retry: akode_api::RetryConfig {
max_attempts: 1,
base_delay: Duration::from_millis(1),
retry_429: false,
@@ -158,7 +158,7 @@ fn provider(name: &str) -> Provider {
#[derive(Debug, Default)]
struct FlakyTransportState {
attempts: i64,
requests: Vec<(RequestBody, HeaderMap, codex_client::RequestCompression)>,
requests: Vec<(RequestBody, HeaderMap, akode_client::RequestCompression)>,
}
#[derive(Clone)]
@@ -186,7 +186,7 @@ impl FlakyTransport {
.attempts
}
fn requests(&self) -> Vec<(RequestBody, HeaderMap, codex_client::RequestCompression)> {
fn requests(&self) -> Vec<(RequestBody, HeaderMap, akode_client::RequestCompression)> {
self.state
.lock()
.expect("flaky transport state mutex should not be poisoned")
@@ -240,7 +240,7 @@ impl AuthProvider for FailsOnceAuth {
Ok(())
}
fn apply_auth(&self, request: Request) -> codex_api::AuthProviderFuture<'_> {
fn apply_auth(&self, request: Request) -> akode_api::AuthProviderFuture<'_> {
Box::pin(FailsOnceAuth::apply_auth(self, request))
}
}
@@ -534,7 +534,7 @@ async fn streaming_client_retries_on_transport_error() -> Result<()> {
requests[0].1.get(http::header::CONTENT_ENCODING),
Some(&HeaderValue::from_static("zstd"))
);
assert_eq!(requests[0].2, codex_client::RequestCompression::None);
assert_eq!(requests[0].2, akode_client::RequestCompression::None);
Ok(())
}
@@ -567,7 +567,7 @@ async fn streaming_client_retries_on_transient_auth_error() -> Result<()> {
async fn streaming_client_does_not_retry_terminal_auth_errors() {
for error in [
AuthError::Build("invalid auth configuration".into()),
AuthError::Policy(codex_http_client::NetworkPolicyDenied::Revoked),
AuthError::Policy(akode_http_client::NetworkPolicyDenied::Revoked),
] {
let state = RecordingState::default();
let transport = RecordingTransport::new(state.clone());
@@ -728,13 +728,13 @@ async fn header_auth_error_prevents_sending_partial_authentication() {
struct AsyncHeaderAuth;
impl AuthProvider for AsyncHeaderAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
Err(codex_api::AuthError::Build(
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), akode_api::AuthError> {
Err(akode_api::AuthError::Build(
"authentication requires async header resolution".to_string(),
))
}
fn apply_auth_headers(&self, mut headers: HeaderMap) -> codex_api::AuthHeadersFuture<'_> {
fn apply_auth_headers(&self, mut headers: HeaderMap) -> akode_api::AuthHeadersFuture<'_> {
Box::pin(async move {
headers.insert(
http::header::AUTHORIZATION,

View File

@@ -1,18 +1,18 @@
use codex_api::AuthProvider;
use codex_api::ModelsClient;
use codex_api::Provider;
use codex_api::RetryConfig;
use codex_client::ReqwestTransport;
use codex_http_client::HttpClientBuilder;
use codex_protocol::config_types::ReasoningSummary;
use codex_protocol::openai_models::ConfigShellToolType;
use codex_protocol::openai_models::ModelInfo;
use codex_protocol::openai_models::ModelVisibility;
use codex_protocol::openai_models::ModelsResponse;
use codex_protocol::openai_models::ReasoningEffort;
use codex_protocol::openai_models::ReasoningEffortPreset;
use codex_protocol::openai_models::TruncationPolicyConfig;
use codex_protocol::openai_models::default_input_modalities;
use akode_api::AuthProvider;
use akode_api::ModelsClient;
use akode_api::Provider;
use akode_api::RetryConfig;
use akode_client::ReqwestTransport;
use akode_http_client::HttpClientBuilder;
use akode_protocol::config_types::ReasoningSummary;
use akode_protocol::openai_models::ConfigShellToolType;
use akode_protocol::openai_models::ModelInfo;
use akode_protocol::openai_models::ModelVisibility;
use akode_protocol::openai_models::ModelsResponse;
use akode_protocol::openai_models::ReasoningEffort;
use akode_protocol::openai_models::ReasoningEffortPreset;
use akode_protocol::openai_models::TruncationPolicyConfig;
use akode_protocol::openai_models::default_input_modalities;
use http::HeaderMap;
use http::Method;
use pretty_assertions::assert_eq;
@@ -28,7 +28,7 @@ use wiremock::matchers::path;
struct DummyAuth;
impl AuthProvider for DummyAuth {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), codex_api::AuthError> {
fn add_auth_headers(&self, _headers: &mut HeaderMap) -> Result<(), akode_api::AuthError> {
Ok(())
}
}

View File

@@ -3,24 +3,24 @@ use std::collections::HashMap;
use std::future::Future;
use std::time::Duration;
use codex_api::ApiError;
use codex_api::Provider;
use codex_api::RealtimeAudioFrame;
use codex_api::RealtimeEvent;
use codex_api::RealtimeEventParser;
use codex_api::RealtimeOutputModality;
use codex_api::RealtimeSessionConfig;
use codex_api::RealtimeSessionMode;
use codex_api::RealtimeTranscriptState;
use codex_api::RealtimeWebsocketClient;
use codex_api::RetryConfig;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy::ReqwestDefault;
use codex_protocol::protocol::RealtimeHandoffRequested;
use codex_protocol::protocol::RealtimeTranscriptDelta;
use codex_protocol::protocol::RealtimeTranscriptDone;
use codex_protocol::protocol::RealtimeTranscriptEntry;
use codex_protocol::protocol::RealtimeVoice;
use akode_api::ApiError;
use akode_api::Provider;
use akode_api::RealtimeAudioFrame;
use akode_api::RealtimeEvent;
use akode_api::RealtimeEventParser;
use akode_api::RealtimeOutputModality;
use akode_api::RealtimeSessionConfig;
use akode_api::RealtimeSessionMode;
use akode_api::RealtimeTranscriptState;
use akode_api::RealtimeWebsocketClient;
use akode_api::RetryConfig;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy::ReqwestDefault;
use akode_protocol::protocol::RealtimeHandoffRequested;
use akode_protocol::protocol::RealtimeTranscriptDelta;
use akode_protocol::protocol::RealtimeTranscriptDone;
use akode_protocol::protocol::RealtimeTranscriptEntry;
use akode_protocol::protocol::RealtimeVoice;
use futures::SinkExt;
use futures::StreamExt;
use http::HeaderMap;

View File

@@ -8,21 +8,21 @@ use std::sync::Arc;
use std::time::Duration;
use std::time::Instant;
use codex_api::Provider;
use codex_api::RealtimeEventParser;
use codex_api::RealtimeOutputModality;
use codex_api::RealtimeSessionConfig;
use codex_api::RealtimeSessionMode;
use codex_api::RealtimeWebsocketClient;
use codex_api::RetryConfig;
use codex_http_client::HttpClientFactory;
use codex_http_client::OutboundProxyPolicy;
use codex_protocol::protocol::RealtimeVoice;
use akode_api::Provider;
use akode_api::RealtimeEventParser;
use akode_api::RealtimeOutputModality;
use akode_api::RealtimeSessionConfig;
use akode_api::RealtimeSessionMode;
use akode_api::RealtimeWebsocketClient;
use akode_api::RetryConfig;
use akode_http_client::HttpClientFactory;
use akode_http_client::OutboundProxyPolicy;
use akode_protocol::protocol::RealtimeVoice;
use http::HeaderMap;
use pretty_assertions::assert_eq;
const ADDRESS_ENV: &str = "CODEX_TEST_REALTIME_TLS_ADDRESS";
const TRUST_ENV: &str = "CODEX_TEST_REALTIME_TLS_TRUST";
const ADDRESS_ENV: &str = "AKODE_TEST_REALTIME_TLS_ADDRESS";
const TRUST_ENV: &str = "AKODE_TEST_REALTIME_TLS_TRUST";
#[test]
fn realtime_tls_selects_system_and_custom_trust() {
@@ -35,7 +35,7 @@ fn realtime_tls_selects_system_and_custom_trust() {
return;
}
codex_utils_rustls_provider::ensure_rustls_crypto_provider();
akode_utils_rustls_provider::ensure_rustls_crypto_provider();
let certificate = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]).unwrap();
let temp = tempfile::TempDir::new().unwrap();
let ca = temp.path().join("ca.pem");
@@ -96,10 +96,10 @@ fn realtime_tls_selects_system_and_custom_trust() {
])
.env(ADDRESS_ENV, format!("localhost:{}", address.port()))
.env(TRUST_ENV, trust)
.env_remove("CODEX_CA_CERTIFICATE")
.env_remove("AKODE_CA_CERTIFICATE")
.env_remove("SSL_CERT_FILE");
if trust == "custom" {
child.env("CODEX_CA_CERTIFICATE", &ca).env(
child.env("AKODE_CA_CERTIFICATE", &ca).env(
"SSL_CERT_FILE",
temp.path().join("missing-lower-priority-ca.pem"),
);

Some files were not shown because too many files have changed in this diff Show More