Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions FORK-DELTA.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Working ledgers (per case, with commands and evidence) were kept outside the rep
- **Observability**: the gated usage line (`8ca6f61ec5`) and the privacy-bounded refusal-shape log (`fae0ae4736`). Analytics `physicalBreakdown` and `redAlerts` plus the physical-attempt accounting used by summaries, health, the lab and route explainability. `p<hex6>` Anthropic account labels (`326bdfd7f7`), `comboTargetAdvanced`, cache TTL attribution, the `codex-account-retry` kind, and request-incompatible route traces.
- **Providers and state**: the `xai-apikey` identity (`de6381aa3b`), lower-only response-store environment bounds (`db4cf5cbef`), credit-journal expiry (`326e1a77b7`, co-authored by Gauge), Kimi `usages` precedence (`aa80674b33`), quota explanation (`af51f855b4`), the 20-minute Antigravity paste window (`d6d040ed32`), a 60-second API-key 429 cap, `.27` plan vocabulary for hosted `?quota=1`, and `--code` as an alias of `--headless`.
- **Claude ingress**: hosted exact `count_tokens` (pin-respecting; the `.27` bug that counted on an unpinned pool account is fixed). `prompt_cache_key` on session and parent session. The 5-minute cache default in hosted mode. Image 413 shrink on the native lane. Native-only client tools are refused before send.
- **Unix-socket-only serving** (AGE-6145): with `OPENCODEX_UNIX_SOCKET=<absolute path, at most 104 bytes>`, `ocx start` serves only on that socket (mode 0600, a stale socket is replaced, a non-socket at the path is refused) and opens no TCP listener: no Claude intercept (requested port 0), no hub link listener, no liveness fence, port choice or TCP bind probes. It refuses to start beside `unauthenticatedLoopbackListener`, `hub.managementIngress` or a fixed `claudeCode.intercept.port`. Why: several companies' OCX processes share one loopback inside a Fargate task, and OCX asks no key on loopback, so a TCP port would let one company call another's. Unset, behaviour is unchanged. No routing, account, retry or cache-key code is touched. In this mode the socket is created 0600 under umask 0177 inside a private (0700, own-uid, non-symlink) parent directory, runtime Claude intercept starts are refused (`unix_socket_only`), and OCX's own calls to its API (`selfFetch`, `directLocalHttpFetch`) go over the socket instead of the shared loopback port.

## Replaced by upstream (do not reapply)

Expand Down
4 changes: 3 additions & 1 deletion src/advisor/consult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
*/
import type { OcxConfig } from "../types";
import { localInferenceDestination, selfFetchAdmissionToken, type LocalInferenceDestination } from "../lib/local-destinations";
import { selfFetch } from "../server/index/unix-socket-only";

import { cancelBodyOnAbort } from "../lib/abort";
import { advisorBackoffMs } from "./failure-backoff";
import { sidecarEnter } from "../lib/sidecar-tracker";
Expand Down Expand Up @@ -299,7 +301,7 @@ export async function consultAdvisor(
try {
policyRegistration = registerAdvisorAdmissionPolicy(admissionPolicy ?? captureAdmissionPolicy(config, undefined, admissionScope), linkedSignal.signal);
headers[ADVISOR_ADMISSION_POLICY_HEADER] = policyRegistration.token;
const res = await fetch(`${baseUrlOverride ?? advisorBaseUrl(config)}/v1/chat/completions`, {
const res = await selfFetch(`${baseUrlOverride ?? advisorBaseUrl(config)}/v1/chat/completions`, {
method: "POST",
headers,
body: JSON.stringify(requestBody),
Expand Down
3 changes: 2 additions & 1 deletion src/claude/gateway-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { mkdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { join } from "node:path";
import { localAdmissionToken, localInferenceDestination } from "../lib/local-destinations";
import { selfFetch } from "../server/index/unix-socket-only";
import { assertNotRealClaudeConfigUnderTest } from "../lib/test-home-guard";
import type { OcxConfig } from "../types";

Expand Down Expand Up @@ -117,7 +118,7 @@ export async function fetchGatewayModels(

// ?ids=cli pins the readable claude-ocx id family deterministically (audit 051
// #5): the cache prewrite must not depend on UA sniffing.
const res = await (options.fetchImpl ?? fetch)(`${baseUrl}/v1/models?limit=1000&ids=cli`, {
const res = await (options.fetchImpl ?? (typeof portOrTarget === "number" ? selfFetch : fetch))(`${baseUrl}/v1/models?limit=1000&ids=cli`, {
headers,
signal: AbortSignal.timeout(options.timeoutMs ?? 3_000),
});
Expand Down
2 changes: 1 addition & 1 deletion src/claude/intercept/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ const PICKER_AUTHORITY_ERROR_CODES = new Set([

export { CLAUDE_INTERCEPT_PORT_OFFSET, claudeInterceptEnabled, claudeInterceptProxyPort, claudePickerProxyPort } from "./port-policy";

export type ClaudeInterceptOutcome = { ok: true; state: ClaudeInterceptState } | { ok: false; reason: "disabled" | "client_role" | "ephemeral_port" | "port_in_use" | "stopped" | "failed"; port?: number; message?: string };
export type ClaudeInterceptOutcome = { ok: true; state: ClaudeInterceptState } | { ok: false; reason: "disabled" | "client_role" | "unix_socket_only" | "ephemeral_port" | "port_in_use" | "stopped" | "failed"; port?: number; message?: string };

export interface ClaudeInterceptState {
pickerReason?: "port_in_use" | "failed" | null;
Expand Down
3 changes: 2 additions & 1 deletion src/cli/account-api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { selfFetch } from "../server/index/unix-socket-only";
import { configuredAnthropicInstance, isAnthropicOAuthInstance } from "../providers/anthropic-instance";
import { parseQuotaFailureCode, parseQuotaUnknownReason, type QuotaFailureCode, type QuotaUnknownReason, type ProviderQuota, type AccountQuotaMode } from "../providers/quota-types";
import { parseWeeklyWindowConflicts, type WeeklyWindowConflict } from "../codex/quota-window-conflict";
Expand Down Expand Up @@ -155,7 +156,7 @@ export async function apiJson(
options: { signal?: AbortSignal; redirect?: RequestRedirect } = {},
): Promise<ApiResult> {
if (baseUrl === LINK_HOME_BASE) return linkHomeApiJson(deps, method, path);
const fetchImpl = deps.fetchImpl ?? fetch;
const fetchImpl = deps.fetchImpl ?? selfFetch; // AGE-6145: admin token goes over the unix socket in unix-socket-only mode
try {
const res = await fetchImpl(`${baseUrl}${path}`, {
method,
Expand Down
4 changes: 3 additions & 1 deletion src/cli/claude.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import { isProxyAdmissionSecret } from "../server/auth-cors";
import { findLiveProxy } from "../server/proxy-liveness";
import type { OcxConfig } from "../types";
import { configuredAdminToken } from "../lib/admin-secrets";
import { selfFetch } from "../server/index/unix-socket-only";

import { localAdmissionToken, localInferenceDestination, localLoopbackInferencePorts, localManagementOrigin } from "../lib/local-destinations";
import { PROXY_MARKER, ownAdmissionTokens, defaultAuthDetectDeps, detectClaudeAuth, resolveClaudeKeychainPresence, type AuthDetectDeps } from "../claude/auth-detect";
import { resolveClaudeAuthMode } from "../claude/auth-mode";
Expand Down Expand Up @@ -465,7 +467,7 @@ export async function fetchClaudeCodeState(config: OcxConfig, port: number, time
const headers = new Headers();
const token = configuredAdminToken();
if (token) headers.set("x-opencodex-api-key", token);
const res = await fetch(`${localManagementOrigin(config, port)}/api/claude-code?view=launch`, {
const res = await selfFetch(`${localManagementOrigin(config, port)}/api/claude-code?view=launch`, { // AGE-6145: over the unix socket in unix-socket-only mode
headers,
signal: AbortSignal.timeout(timeoutMs),
});
Expand Down
13 changes: 7 additions & 6 deletions src/cli/debug.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { selfFetch } from "../server/index/unix-socket-only";
import { findLiveProxy, probeHostname } from "../server/proxy-liveness";
import { DEBUG_ENV, type DebugSettingsView } from "../lib/debug-settings";
import { runningProxyUpdateHeaders } from "../oauth/login-cli";
Expand All @@ -24,7 +25,7 @@ async function requireLiveProxy() {
async function fetchDebugSettings(): Promise<DebugSettingsView> {
const live = await requireLiveProxy();
try {
const res = await fetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, {
const res = await selfFetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, {
headers: runningProxyUpdateHeaders(),
});
if (!res.ok) {
Expand All @@ -40,7 +41,7 @@ async function fetchDebugSettings(): Promise<DebugSettingsView> {

async function putDebugSettings(body: Record<string, unknown>): Promise<DebugSettingsView> {
const live = await requireLiveProxy();
const res = await fetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, {
const res = await selfFetch(`http://${probeHostname(live.hostname)}:${live.port}/api/debug`, {
method: "PUT",
headers: runningProxyUpdateHeaders(),
body: JSON.stringify(body),
Expand Down Expand Up @@ -84,7 +85,7 @@ async function printProviderLogs(follow: boolean): Promise<void> {

let after = 0;
try {
const res = await fetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() });
const res = await selfFetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() });
if (!res.ok) {
console.error(`Failed to read debug logs (${res.status})`);
process.exit(1);
Expand All @@ -102,7 +103,7 @@ async function printProviderLogs(follow: boolean): Promise<void> {
while (true) {
await new Promise(resolve => setTimeout(resolve, 1000));
try {
const res = await fetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() });
const res = await selfFetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() });
if (!res.ok) continue;
const entries = await res.json() as { seq: number; line: string }[];
for (const entry of entries) console.log(entry.line);
Expand All @@ -119,7 +120,7 @@ async function printUsageLogs(follow: boolean): Promise<void> {

let after = 0;
try {
const res = await fetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() });
const res = await selfFetch(`${base}?limit=500`, { headers: runningProxyUpdateHeaders() });
if (!res.ok) {
console.error(`Failed to read usage debug logs (${res.status})`);
process.exit(1);
Expand All @@ -138,7 +139,7 @@ async function printUsageLogs(follow: boolean): Promise<void> {
while (true) {
await new Promise(resolve => setTimeout(resolve, 1000));
try {
const res = await fetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() });
const res = await selfFetch(`${base}?after=${after}&limit=500`, { headers: runningProxyUpdateHeaders() });
if (!res.ok) continue;
const entries = await res.json() as { seq: number; line: string }[];
for (const entry of entries) console.log(entry.line);
Expand Down
9 changes: 5 additions & 4 deletions src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ import { redactUrlForLog } from "../lib/redact";
import { dispatchCommand, decideBusyPreferredPort, decideStartExitTeardown, decideStartWithLiveOwner, startupLeftCodexNativeLine } from "./dispatch";
import { probeOwnerPastRestartParent, takeRestartHandoffMarkers } from "./restart-handoff";
import { AuxiliaryListenerBindError, findAvailablePort, isAddrInUse, PortUnavailableError, shouldPersistSelectedPort, waitForPortAvailable } from "../server/ports";
import { unixSocketOnlyActive, unixSocketOnlyPath } from "../server/index/unix-socket-only";
import {
findLiveProxy,
proveLiveProxyOwnedByHome,
Expand Down Expand Up @@ -529,7 +530,7 @@ async function handleStart(options: { block?: boolean } = {}) {
}
// Recovery rechecked liveness under its lease. This fence owns the bind decision: an
// updater may have stopped the old runtime and acquired this lease for replacement.
const fencedLive = await findLiveProxy(START_OWNERSHIP_LIVENESS);
const unixSocketPath = unixSocketOnlyPath(), fencedLive = unixSocketPath !== undefined ? null : await findLiveProxy(START_OWNERSHIP_LIVENESS); // AGE-6145: unix-only mode opens and probes no TCP port
if (fencedLive) {
const decision = decideStartWithLiveOwner({
livePort: fencedLive.port,
Expand All @@ -552,7 +553,7 @@ async function handleStart(options: { block?: boolean } = {}) {

// Port selection is check-then-bind. The lease prevents every cooperating start or
// updater from turning that check into a different ownership decision.
let port = await chooseListenPort(requestedPort, { sibling: siblingStart });
let port = unixSocketPath !== undefined ? requestedPort ?? loadConfig().port ?? 10100 : await chooseListenPort(requestedPort, { sibling: siblingStart }); // unix mode: the port is only a label
raiseWindowsProxyPriority();
const serverModule = await import("../server");
const readinessGate = createReadinessGate();
Expand Down Expand Up @@ -583,7 +584,7 @@ async function handleStart(options: { block?: boolean } = {}) {
console.error(`❌ ${err.message}`);
throw new StartCommandExit(1);
}
if (err instanceof AuxiliaryListenerBindError || !isAddrInUse(err) || attempt >= 2) throw err;
if (unixSocketPath !== undefined || err instanceof AuxiliaryListenerBindError || !isAddrInUse(err) || attempt >= 2) throw err;
if (requestedPort !== undefined) {
console.log(`⚠️ Port ${port} was taken while starting; waiting to retry the same port...`);
const hostname = config.hostname ?? "127.0.0.1";
Expand Down Expand Up @@ -760,7 +761,7 @@ async function handleStart(options: { block?: boolean } = {}) {
// #7423: routing an update kept in place for this proxy is ours once the startup sync published.
if (!siblingStart && startupSync.published) completeUpdateTeardownHandover(pid => isProcessAlive(pid) && isLikelyOcxProcess(pid));
await refreshOwnedRaycastCatalog(config, port);
if (!cleaned && !shuttingDown) healthSentinel = startServiceHealthSentinel(config); // after startup reconciliation; never mid-boot or mid-drain
if (!cleaned && !shuttingDown && !unixSocketOnlyActive()) healthSentinel = startServiceHealthSentinel(config); // AGE-6145: it probes /healthz over TCP; after startup reconciliation; never mid-boot or mid-drain
// #1046: one warning per startup, after BOTH writes. The server's cache
// invalidation happens first and the catalog sync second, so the mtime is only
// final here — and neither write site warns on its own, or a boot that hits
Expand Down
3 changes: 2 additions & 1 deletion src/cli/observe-stream.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
/** Bounded, serial observation of fixed management read surfaces. */
import { selfFetch } from "../server/index/unix-socket-only";
import { readBoundedResponseBytes } from "../lib/bounded-body";
import { runningProxyUpdateHeaders } from "../oauth/login-cli";
import { findLiveProxy, type LiveProxy } from "../server/proxy-liveness";
Expand Down Expand Up @@ -112,7 +113,7 @@ export async function withObserveStream(
const timer = setTimeout(abort, timeoutMs);
try {
signal.throwIfAborted();
const responsePromise = (deps.fetchImpl ?? fetch)(`${origin}${path}?${query}`, {
const responsePromise = (deps.fetchImpl ?? selfFetch)(`${origin}${path}?${query}`, {
method: "GET", headers: runningProxyUpdateHeaders(), credentials: "omit", redirect: "error", signal: request.signal,
});
// A test transport or late fetch may settle after abort. Release its body too.
Expand Down
3 changes: 2 additions & 1 deletion src/cli/runtime-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
* - 다른 대안 대신 이 방식을 선택한 이유: GUI/CLI의 검증 규칙이 갈라지지 않고 fallback port도 안전하게 찾는다.
* - 장점, 단점 및 영향: 동작 일관성이 높아지는 대신 live 관리 명령은 실행 중인 proxy가 필요하다.
*/
import { selfFetch } from "../server/index/unix-socket-only";
import { findLiveProxy, probeHostname, type LivenessIo, type LiveProxy } from "../server/proxy-liveness";
import { runningProxyUpdateHeaders } from "../oauth/login-cli";
import { terminalSafeText } from "../lib/terminal-safe-text";
Expand Down Expand Up @@ -213,7 +214,7 @@ export async function runtimeRequest<T = unknown>(
}
const headers = runningProxyUpdateHeaders();
for (const [key, value] of new Headers(init.headers).entries()) headers.set(key, value);
const fetchImpl = deps.fetchImpl ?? fetch;
const fetchImpl = deps.fetchImpl ?? selfFetch; // AGE-6145: admin token goes over the unix socket in unix-socket-only mode
let response: Response;
try {
response = await fetchImpl(`${baseUrl}${path.startsWith("/") ? path : `/${path}`}`, { ...init, headers });
Expand Down
3 changes: 2 additions & 1 deletion src/cli/sync-link-status.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { selfFetch } from "../server/index/unix-socket-only";
import { runningProxyUpdateHeaders } from "../oauth/login-cli";
import { runtimeBaseUrl, RuntimeApiError } from "./runtime-api";
import { validateStatus, type LinkStatusPayload } from "./link";
Expand Down Expand Up @@ -28,7 +29,7 @@ export async function readHomeLinkStatus(deadlineMs = 5000, deps: {
if (!base) throw new LinkStatusError("home-runtime-not-running");
let response: Response;
// wp2: children=1 adds each row's child block (activity, active job); an older Home ignores the query.
try { response = await (deps.fetchImpl ?? fetch)(`${base}/api/link/status?children=1`, { headers: (deps.headers ?? runningProxyUpdateHeaders)(), signal: controller.signal }); }
try { response = await (deps.fetchImpl ?? selfFetch)(`${base}/api/link/status?children=1`, { headers: (deps.headers ?? runningProxyUpdateHeaders)(), signal: controller.signal }); }
catch (cause) { throw new LinkStatusError("home-link-status-unavailable", { cause }); }
if (response.status === 401 || response.status === 403) throw new LinkStatusError("home-link-status-unauthorized");
if (!response.ok) throw new LinkStatusError("home-link-status-unavailable");
Expand Down
4 changes: 3 additions & 1 deletion src/lib/local-chat-completion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import { sidecarEnter } from "./sidecar-tracker";
import { internalCallCapability } from "./local-internal-call-capability";
import { registerAdvisorAdmissionPolicy, SIDECAR_ADMISSION_POLICY_HEADER, SIDECAR_INTERNAL_CAPABILITY_HEADER } from "../server/advisor-admission-scope";
import { configuredPort } from "../server/auth-cors";
import { selfFetch } from "../server/index/unix-socket-only";

import type { CapturedAdmissionPolicy } from "../types/admission-policy";

export type LocalChatConfig = Pick<OcxConfig, "port" | "hostname" | "apiKeys" | "unauthenticatedLoopbackListener">;
Expand Down Expand Up @@ -90,7 +92,7 @@ export async function postLocalChatCompletion(request: LocalChatCompletionReques
registration = registerAdvisorAdmissionPolicy(request.admissionPolicy, linkedSignal.signal);
headers[SIDECAR_ADMISSION_POLICY_HEADER] = registration.token;
headers[SIDECAR_INTERNAL_CAPABILITY_HEADER] = internalCallCapability();
const res = await fetch(`${request.baseUrlOverride ?? localChatCompletionBaseUrl(config)}/v1/chat/completions`, {
const res = await selfFetch(`${request.baseUrlOverride ?? localChatCompletionBaseUrl(config)}/v1/chat/completions`, {
method: "POST",
headers,
body: JSON.stringify({ ...request.body, stream: false }),
Expand Down
12 changes: 11 additions & 1 deletion src/server/direct-local-http.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import net, { type Socket } from "node:net";
import { unixSocketOnlyPath } from "./index/unix-socket-only";

const DIRECT_LOCAL_HTTP_MAX_BYTES = 8 * 1024 * 1024;
const DIRECT_LOCAL_HTTP_TIMEOUT_MS = 10_000;
Expand Down Expand Up @@ -241,6 +242,13 @@ function parseResponse(bytes: Buffer): Response {
});
}

/** A socket path nothing has bound reports ENOENT; as "nothing is listening" it must read as a refusal, like a free TCP port. */
function connectUnixSocket(path: string): Socket {
const socket = net.createConnection({ path });
socket.once("error", error => { if ((error as NodeJS.ErrnoException).code === "ENOENT") (error as NodeJS.ErrnoException).code = "ECONNREFUSED"; });
return socket;
}

/**
* Fetch one bodyless local HTTP GET or POST over a direct TCP connection.
*
Expand Down Expand Up @@ -346,7 +354,9 @@ export async function directLocalHttpFetch(
settleAfterClose(error);
};

socket = (io.connect ?? ((host, selectedPort) => net.createConnection({
// AGE-6145: in unix-socket-only mode a local request goes over the socket, never to a shared loopback TCP port.
const unixPath = io.connect ? undefined : unixSocketOnlyPath();
socket = (io.connect ?? ((host, selectedPort) => unixPath !== undefined ? connectUnixSocket(unixPath) : net.createConnection({
host,
port: selectedPort,
autoSelectFamily: true,
Expand Down
Loading