aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-11 11:06:46 +01:00
parent df99318392
commit 86e7c72e5f
10383 changed files with 749164 additions and 749170 deletions

1
akode-cli/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/vendor/

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

@@ -0,0 +1,115 @@
#!/bin/bash
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/akode/allowed_domains.txt"
if [ -f "$ALLOWED_DOMAINS_FILE" ]; then
ALLOWED_DOMAINS=()
while IFS= read -r domain; do
ALLOWED_DOMAINS+=("$domain")
done < "$ALLOWED_DOMAINS_FILE"
echo "Using domains from file: ${ALLOWED_DOMAINS[*]}"
else
# Fallback to default domains
ALLOWED_DOMAINS=("api.openai.com")
echo "Domains file not found, using default: ${ALLOWED_DOMAINS[*]}"
fi
# Ensure we have at least one domain
if [ ${#ALLOWED_DOMAINS[@]} -eq 0 ]; then
echo "ERROR: No allowed domains specified"
exit 1
fi
# Flush existing rules and delete existing ipsets
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
ipset destroy allowed-domains 2>/dev/null || true
# First allow DNS and localhost before any restrictions
# Allow outbound DNS
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
# Allow inbound DNS responses
iptables -A INPUT -p udp --sport 53 -j ACCEPT
# Allow localhost
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Create ipset with CIDR support
ipset create allowed-domains hash:net
# Resolve and add other allowed domains
for domain in "${ALLOWED_DOMAINS[@]}"; do
echo "Resolving $domain..."
ips=$(dig +short A "$domain")
if [ -z "$ips" ]; then
echo "ERROR: Failed to resolve $domain"
exit 1
fi
while read -r ip; do
if [[ ! "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
echo "ERROR: Invalid IP from DNS for $domain: $ip"
exit 1
fi
echo "Adding $ip for $domain"
ipset add allowed-domains "$ip"
done < <(echo "$ips")
done
# Get host IP from default route
HOST_IP=$(ip route | grep default | cut -d" " -f3)
if [ -z "$HOST_IP" ]; then
echo "ERROR: Failed to detect host IP"
exit 1
fi
HOST_NETWORK=$(echo "$HOST_IP" | sed "s/\.[0-9]*$/.0\/24/")
echo "Host network detected as: $HOST_NETWORK"
# Set up remaining iptables rules
iptables -A INPUT -s "$HOST_NETWORK" -j ACCEPT
iptables -A OUTPUT -d "$HOST_NETWORK" -j ACCEPT
# Set default policies to DROP first
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
# First allow established connections for already approved traffic
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Then allow only specific outbound traffic to allowed domains
iptables -A OUTPUT -m set --match-set allowed-domains dst -j ACCEPT
# Append final REJECT rules for immediate error responses
# For TCP traffic, send a TCP reset; for UDP, send ICMP port unreachable.
iptables -A INPUT -p tcp -j REJECT --reject-with tcp-reset
iptables -A INPUT -p udp -j REJECT --reject-with icmp-port-unreachable
iptables -A OUTPUT -p tcp -j REJECT --reject-with tcp-reset
iptables -A OUTPUT -p udp -j REJECT --reject-with icmp-port-unreachable
iptables -A FORWARD -p tcp -j REJECT --reject-with tcp-reset
iptables -A FORWARD -p udp -j REJECT --reject-with icmp-port-unreachable
echo "Firewall configuration complete"
echo "Verifying firewall rules..."
if curl --connect-timeout 5 https://example.com >/dev/null 2>&1; then
echo "ERROR: Firewall verification failed - was able to reach https://example.com"
exit 1
else
echo "Firewall verification passed - unable to reach https://example.com as expected"
fi
# Always verify OpenAI API access is working
if ! curl --connect-timeout 5 https://api.openai.com >/dev/null 2>&1; then
echo "ERROR: Firewall verification failed - unable to reach https://api.openai.com"
exit 1
else
echo "Firewall verification passed - able to reach https://api.openai.com as expected"
fi

View File

@@ -0,0 +1,95 @@
#!/bin/bash
set -e
# Usage:
# ./run_in_container.sh [--work_dir directory] "COMMAND"
#
# Examples:
# ./run_in_container.sh --work_dir project/code "ls -la"
# ./run_in_container.sh "echo Hello, world!"
# Default the work directory to WORKSPACE_ROOT_DIR if not provided.
WORK_DIR="${WORKSPACE_ROOT_DIR:-$(pwd)}"
# Default allowed domains - can be overridden with OPENAI_ALLOWED_DOMAINS env var
OPENAI_ALLOWED_DOMAINS="${OPENAI_ALLOWED_DOMAINS:-api.openai.com}"
# Parse optional flag.
if [ "$1" = "--work_dir" ]; then
if [ -z "$2" ]; then
echo "Error: --work_dir flag provided but no directory specified."
exit 1
fi
WORK_DIR="$2"
shift 2
fi
WORK_DIR=$(realpath "$WORK_DIR")
# Generate a unique container name based on the normalized work directory
CONTAINER_NAME="codex_$(echo "$WORK_DIR" | sed 's/\//_/g' | sed 's/[^a-zA-Z0-9_-]//g')"
# Define cleanup to remove the container on script exit, ensuring no leftover containers
cleanup() {
docker rm -f "$CONTAINER_NAME" >/dev/null 2>&1 || true
}
# Trap EXIT to invoke cleanup regardless of how the script terminates
trap cleanup EXIT
# Ensure a command is provided.
if [ "$#" -eq 0 ]; then
echo "Usage: $0 [--work_dir directory] \"COMMAND\""
exit 1
fi
# Check if WORK_DIR is set.
if [ -z "$WORK_DIR" ]; then
echo "Error: No work directory provided and WORKSPACE_ROOT_DIR is not set."
exit 1
fi
# Verify that OPENAI_ALLOWED_DOMAINS is not empty
if [ -z "$OPENAI_ALLOWED_DOMAINS" ]; then
echo "Error: OPENAI_ALLOWED_DOMAINS is empty."
exit 1
fi
# Kill any existing container for the working directory using cleanup(), centralizing removal logic.
cleanup
# Run the container with the specified directory mounted at the same path inside the container.
docker run --name "$CONTAINER_NAME" -d \
-e OPENAI_API_KEY \
--cap-add=NET_ADMIN \
--cap-add=NET_RAW \
-v "$WORK_DIR:/app$WORK_DIR" \
akode \
sleep infinity
# Write the allowed domains to a file in the container
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/akode/allowed_domains.txt"
done
# Set proper permissions on the domains file
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"
# Remove the firewall script after running it
docker exec --user root "$CONTAINER_NAME" bash -c "rm -f /usr/local/bin/init_firewall.sh"
# Execute the provided command in the container, ensuring it runs in the work directory.
# We use a parameterized bash command to safely handle the command and directory.
quoted_args=""
for arg in "$@"; do
quoted_args+=" $(printf '%q' "$arg")"
done
docker exec -it "$CONTAINER_NAME" bash -c "cd \"/app$WORK_DIR\" && akode --sandbox workspace-write --ask-for-approval on-request ${quoted_args}"

View File

@@ -0,0 +1,121 @@
// 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";
import {
copyFile,
mkdir,
mkdtemp,
rm,
symlink,
writeFile,
} from "node:fs/promises";
import { constants, tmpdir } from "node:os";
import path from "node:path";
import { createInterface } from "node:readline";
import test from "node:test";
test(
"the npm wrapper preserves numeric exits and child signals",
{
skip: process.platform === "win32",
},
async () => {
assert.ok(
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;
let killTimer;
try {
const arch = process.arch === "arm64" ? "aarch64" : "x86_64";
const target = `${arch}-${process.platform === "darwin" ? "apple-darwin" : "unknown-linux-musl"}`;
const bin = path.join(directory, "vendor", target, "bin");
const home = path.join(directory, "home");
await mkdir(bin, { recursive: true });
await mkdir(home);
await mkdir(path.join(directory, "bin"));
await writeFile(
path.join(directory, "package.json"),
'{"type":"module"}',
);
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.AKODE_TEST_BINARY),
path.join(bin, "codex"),
);
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(
process.execPath,
[wrapper, "--invalid-codex-option"],
{ env, timeout: 30_000, killSignal: "SIGKILL" },
);
assert.equal(invalid.error, undefined);
assert.deepEqual([invalid.status, invalid.signal], [2, null]);
for (const signal of ["SIGHUP", "SIGXFSZ"]) {
// Wait for the real migration prompt before terminating a process.
child = spawn(process.execPath, [wrapper, "migrate-nfs-db"], {
env,
detached: true,
});
const processGroup = child.pid;
killTimer = setTimeout(() => {
try {
process.kill(-processGroup, "SIGKILL");
} catch (error) {
if (error.code !== "ESRCH") throw error;
}
}, 30_000);
const exited = once(child, "exit");
const lines = createInterface({ input: child.stderr });
let prompted = false;
for await (const line of lines) {
if (line.endsWith("[y/N]:")) {
prompted = true;
break;
}
}
assert.ok(prompted, "migration must reach its confirmation prompt");
const processes = execFileSync("ps", ["-axo", "pid=,ppid="], {
encoding: "utf8",
});
const children = processes
.trim()
.split("\n")
.map((line) => line.trim().split(/\s+/).map(Number))
.filter(([, parent]) => parent === child.pid);
const usesExecve = typeof process.execve === "function";
assert.equal(
children.length,
usesExecve ? 0 : 1,
"execve must replace the wrapper; spawn must create one native child",
);
if (usesExecve || signal === "SIGHUP") {
// Signal the native process directly, or let the wrapper forward it.
child.kill(signal);
assert.deepEqual(await exited, [null, signal]);
} else {
// A native child can die from a signal that Node ignores by default.
process.kill(children[0][0], signal);
assert.deepEqual(await exited, [
128 + constants.signals[signal],
null,
]);
}
clearTimeout(killTimer);
}
} finally {
clearTimeout(killTimer);
if (child && child.exitCode === null && child.signalCode === null) {
process.kill(-child.pid, "SIGKILL");
await once(child, "exit");
}
await rm(directory, { recursive: true, force: true });
}
},
);