diff --git a/docs-site/src/content/docs/es/reference/cli/messaging.md b/docs-site/src/content/docs/es/reference/cli/messaging.md index a185fd0a750..de15ffbc2bf 100644 --- a/docs-site/src/content/docs/es/reference/cli/messaging.md +++ b/docs-site/src/content/docs/es/reference/cli/messaging.md @@ -116,6 +116,36 @@ respuestas guardadas de Codex. Para una prueba de ida y vuelta: y vuelta. Si la espera vence, vuelve a comprobar el mismo recibo o revisa la conversación de Codex. Un tiempo de espera agotado no justifica otro envío. + + +## Listar sesiones locales de Claude Code + +En macOS o Linux, indica la ruta absoluta a un ejecutable de confianza de +Claude Code. Debe admitir [`claude agents --json`](https://code.claude.com/docs/en/agent-view#list-sessions-as-json). + +```bash +ocx message claude-sessions --claude /absolute/path/to/claude --json +``` + +El resultado `ocx-claude-sessions/1` incluye el UUID de cada sesión (`id`), +su tipo (`kind`, con valor `interactive` o `background`) y el estado de +actividad que informa Claude Code (`busy`, `waiting` o `idle`). Se omiten +las filas cuyo identificador de sesión o PID sea nulo o esté ausente. Si +ambos campos están presentes, un UUID de sesión abreviado o inválido, o +un PID inválido, provoca un fallo en toda la consulta. Si se define +`CLAUDE_CONFIG_DIR`, esta variable selecciona la configuración local de +Claude. El resultado omite los nombres, las rutas, los PID y el historial. +El comando ejecuta la CLI de Claude una vez con un plazo de cinco segundos, +un límite de salida de 256 KiB y un máximo de 256 filas. Respeta +`CLAUDE_CODE_DISABLE_AGENT_VIEW` y desactiva el tráfico no esencial de la CLI +de Claude durante la consulta. Claude Code puede inicializar su propia +configuración en el primer uso. Si la consulta falla, el comando devuelve +un error sin datos sensibles y sin resultados parciales. + +La lista solo refleja las sesiones locales observadas. El comando no +comprueba si pueden recibir mensajes, no envía mensajes y no usa los pares +SSH registrados. + ## Descubrir y enviar diff --git a/docs-site/src/content/docs/reference/cli/messaging.md b/docs-site/src/content/docs/reference/cli/messaging.md index 2d52efc5fdc..8d19f8fee16 100644 --- a/docs-site/src/content/docs/reference/cli/messaging.md +++ b/docs-site/src/content/docs/reference/cli/messaging.md @@ -214,6 +214,31 @@ text with the client. For a round trip: the round trip. If the wait expires, check the same receipt again or inspect the Codex conversation. A wait timeout does not justify another send. +## List local Claude Code sessions + +On macOS or Linux, pass the absolute path to your trusted native Claude Code +executable. It must support [`claude agents --json`](https://code.claude.com/docs/en/agent-view#list-sessions-as-json). + +```bash +ocx message claude-sessions --claude /absolute/path/to/claude --json +``` + +The `ocx-claude-sessions/1` result lists session UUIDs (`id`), `kind` +(`interactive` or `background`) and the activity reported by Claude Code +(`busy`, `waiting` or `idle`). Rows with a missing or null session ID or PID +are skipped. When both fields are present, a shortened or otherwise invalid +session UUID or an invalid PID causes the entire lookup to fail. +`CLAUDE_CONFIG_DIR`, if set, selects the local Claude configuration. Names, +paths, PIDs and history are omitted from the result. The command invokes the +Claude CLI once with a five-second deadline, 256 KiB output limit and 256-row +limit. It respects the `CLAUDE_CODE_DISABLE_AGENT_VIEW` opt-out and disables +nonessential Claude CLI traffic for the lookup. Claude Code can initialize +its own configuration on first use. On failure the command returns a +sanitized error and no partial list. + +A listed session is an observed local session. This command does not test +inbox reachability, send messages, or use enrolled SSH peers. + ## Discover and send ```bash diff --git a/docs-site/src/content/docs/tr/reference/cli/messaging.md b/docs-site/src/content/docs/tr/reference/cli/messaging.md index 1377182d678..983645ddd8c 100644 --- a/docs-site/src/content/docs/tr/reference/cli/messaging.md +++ b/docs-site/src/content/docs/tr/reference/cli/messaging.md @@ -31,6 +31,10 @@ yardımcı kapatma bunu geçersiz kılmaz, son tarihten sonra tamamlanan okumala kullanılmaz. Mesaj gönderme ve yanıt bekleme ayrı çağrılardır. [Ayrıntılar ve sınırlar](/reference/cli/messaging/#opt-in-stored-turn-replies). +Yerel Claude Code oturumlarını listelemek için +[`ocx message claude-sessions`](/reference/cli/messaging/#list-local-claude-code-sessions) +komutunu kullanın. Liste, bir oturumun mesaj alabileceğini doğrulamaz. + ## Keşfetme ve gönderme ```bash diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 7b6470b3737..b22c4097c28 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -28,7 +28,7 @@ These answer in the CLI head and never reach the proxy, so they work with nothin | [lifecycle](01_surface_lifecycle.md) | 14 | | [providers-models](01_surface_providers-models.md) | 54 | | [accounts](01_surface_accounts.md) | 44 | -| [agents-routing](01_surface_agents-routing.md) | 71 | +| [agents-routing](01_surface_agents-routing.md) | 72 | | [integrations](01_surface_integrations.md) | 41 | | [observe-system](01_surface_observe-system.md) | 105 | | [access-remote](01_surface_access-remote.md) | 55 | @@ -711,6 +711,10 @@ Original invocation order. These headings preserve links to the previous single- [State-changing task](01_surface_agents-routing.md#ocx-message-mcp) +### `ocx message claude-sessions` + +[Read-oriented task](01_surface_agents-routing.md#ocx-message-claude-sessions) + ### `ocx advisor` [State-changing task](01_surface_agents-routing.md#ocx-advisor) @@ -1669,6 +1673,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 405 +- declared capabilities: 406 - of those, state-changing: 254 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_agents-routing.md b/skills/ocx/references/01_surface_agents-routing.md index 05d206617a9..566e1a4a8b3 100644 --- a/skills/ocx/references/01_surface_agents-routing.md +++ b/skills/ocx/references/01_surface_agents-routing.md @@ -8,7 +8,7 @@ Use these declarations to choose a task, then check its flags and authority before execution. Non-mutating probes may still contact providers, consume quota or refresh caches. -Declared capabilities: 71. +Declared capabilities: 72. ### `ocx agent subagents force` @@ -202,6 +202,23 @@ Drives no management route. - macOS/Linux only. Default queue/read tools need no proxy/control socket; resume uses the explicitly configured existing Unix socket. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged. - Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. --allow-reply-read exposes bounded same-turn final text, not exclusive reply ownership or goal completion. No daemon start, steer, automatic replies or registration. Resume preflight is separate opt-in through a same-home existing Unix server; managed requirements and unavailable profiles refuse. The checked native API cannot enforce unloaded-only resume atomically, so execution is blocked with resume_atomicity_unsupported; no thread/resume is sent. +### `ocx message claude-sessions` + +Usage: `ocx message claude-sessions --claude [--json]` + +List local Claude Code session IDs and their reported activity. + +State-changing: no. JSON mode: `envelope`. + +Drives no management route. + +| Flag | Value | Meaning | +|---|---|---| +| `--claude` | string | Absolute path to a trusted Claude Code CLI with agents --json support. | +| `--json` | boolean | Emit a versioned Claude Code session directory. | + +- macOS/Linux only. Invokes the selected local CLI once. Returns only UUID, interactive/background kind and busy/waiting/idle status. Does not test reachability or send a message. + ### `ocx advisor` Inspect and configure the advisor sidecar (expert consultation for routed workers). diff --git a/src/cli/capabilities-agents-routing.ts b/src/cli/capabilities-agents-routing.ts index 2cd4abed478..f1c96299c45 100644 --- a/src/cli/capabilities-agents-routing.ts +++ b/src/cli/capabilities-agents-routing.ts @@ -39,6 +39,15 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [ details: ["macOS/Linux only. Default queue/read tools need no proxy/control socket; resume uses the explicitly configured existing Unix socket. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged.", "Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. --allow-reply-read exposes bounded same-turn final text, not exclusive reply ownership or goal completion. No daemon start, steer, automatic replies or registration. Resume preflight is separate opt-in through a same-home existing Unix server; managed requirements and unavailable profiles refuse. The checked native API cannot enforce unloaded-only resume atomically, so execution is blocked with resume_atomicity_unsupported; no thread/resume is sent."], }, + { + command: ["message", "claude-sessions"], + usage: "ocx message claude-sessions --claude [--json]", + summary: "List local Claude Code session IDs and their reported activity.", + routes: [], mutates: false, json: "envelope", + flags: [{ name: "--claude", value: "string", required: true, summary: "Absolute path to a trusted Claude Code CLI with agents --json support." }, + { name: "--json", value: "boolean", summary: "Emit a versioned Claude Code session directory." }], + details: ["macOS/Linux only. Invokes the selected local CLI once. Returns only UUID, interactive/background kind and busy/waiting/idle status. Does not test reachability or send a message."], + }, { command: ["advisor"], summary: "Inspect and configure the advisor sidecar (expert consultation for routed workers).", diff --git a/src/cli/message-claude-command.ts b/src/cli/message-claude-command.ts new file mode 100644 index 00000000000..2595bba7a99 --- /dev/null +++ b/src/cli/message-claude-command.ts @@ -0,0 +1,40 @@ +import { isAbsolute } from "node:path"; +import { discoverClaudeSessions } from "../messaging/claude-discovery"; +import { LocalMessagingError } from "../messaging/types"; + +export async function runMessageClaudeCommand(argv: readonly string[], env: NodeJS.ProcessEnv): Promise { + let claude: string | undefined; + let json = false; + for (let index = 0; index < argv.length; index++) { + const flag = argv[index]; + if (flag === "--json" && !json) json = true; + else if (flag === "--claude" && claude === undefined) claude = argv[++index]; + else { claude = undefined; break; } + } + if (!claude || !isAbsolute(claude) || /[\x00-\x1f]/.test(claude)) { + console.error("Usage: ocx message claude-sessions --claude [--json]"); + return 64; + } + const controller = new AbortController(); + const cancel = () => controller.abort(); + process.once("SIGINT", cancel); + process.once("SIGTERM", cancel); + try { + if (process.platform !== "linux" && process.platform !== "darwin") { + throw new LocalMessagingError("unsupported_platform", "Claude Code session discovery currently supports macOS and Linux only."); + } + const sessions = await discoverClaudeSessions(claude, env, controller.signal); + if (json) console.log(JSON.stringify({ schema: "ocx-claude-sessions/1", sessions })); + else for (const session of sessions) console.log(`${session.id}\t${session.kind}\t${session.status}`); + return 0; + } catch (cause) { + const error = cause instanceof LocalMessagingError ? { code: cause.code, message: cause.message } + : { code: "claude_directory_unavailable", message: "Local Claude Code session discovery failed." }; + if (json) console.log(JSON.stringify({ schema: "ocx-message-error/1", error })); + else console.error(error.message); + return 1; + } finally { + process.removeListener("SIGINT", cancel); + process.removeListener("SIGTERM", cancel); + } +} diff --git a/src/cli/message-command.ts b/src/cli/message-command.ts index e0d11a34427..464d5e53cc9 100644 --- a/src/cli/message-command.ts +++ b/src/cli/message-command.ts @@ -8,11 +8,12 @@ import { terminalSafeText } from "./runtime-api"; /** Run one local messaging operation after pure syntax validation, then release owned resources. */ export async function runMessageCommand(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): Promise { if (argv[0] === "mcp") return (await import("./message-mcp-command")).runMessageMcpCommand(argv.slice(1)); + if (argv[0] === "claude-sessions") return (await import("./message-claude-command")).runMessageClaudeCommand(argv.slice(1), env); const remote = parseRemoteMessageArgs(argv); if (remote) return (await import("./message-remote-command")).runRemoteMessageCommand(remote, env); const args = parseMessageArgs(argv); if (!args) { - console.error("Usage: ocx message sessions [--host ] [--json] | send (--thread | --name ) --stdin [--host ] [--kind request|response|notification] [--in-reply-to ] [--json] | mcp --codex --codex-home [--allow-reply-read] [--allow-resume --resume-socket --resume-permissions ] | enable [--port ] | disable | status | hosts | serve [--host ]..."); + console.error("Usage: ocx message sessions [--host ] [--json] | send (--thread | --name ) --stdin [--host ] [--kind request|response|notification] [--in-reply-to ] [--json] | mcp --codex --codex-home [--allow-reply-read] [--allow-resume --resume-socket --resume-permissions ] | claude-sessions --claude [--json] | enable [--port ] | disable | status | hosts | serve [--host ]..."); return 64; } const controller = new AbortController(); diff --git a/src/cli/registry.ts b/src/cli/registry.ts index 1c56d0875ad..f84b0da4fb9 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -18,8 +18,8 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ }, { name: "message", - usage: "ocx message [options]", - summary: "Discover loaded Codex sessions and queue messages locally or through explicit SSH peers.", + usage: "ocx message [options]", + summary: "Discover local Codex or Claude Code sessions and queue Codex messages locally or through explicit SSH peers.", details: ["Remote listeners/tunnels require explicit foreground serve; no daemon start. queued is submission, not processing; never replay an unknown send."], }, { diff --git a/src/messaging/claude-discovery.ts b/src/messaging/claude-discovery.ts new file mode 100644 index 00000000000..d491ce72cd5 --- /dev/null +++ b/src/messaging/claude-discovery.ts @@ -0,0 +1,62 @@ +import { readBoundedResponseBytes } from "../lib/bounded-body"; +import { isRecord, isThreadId, LocalMessagingError } from "./types"; + +interface ClaudeSession { + id: string; + kind: "interactive" | "background"; + status: "busy" | "waiting" | "idle"; +} + +const invalidDirectory = () => new LocalMessagingError("invalid_claude_directory", "Claude Code returned an invalid or oversized session directory."); + +/** Use the documented agent directory. Its entries are metadata, not delivery routes. */ +export async function discoverClaudeSessions(claude: string, env: NodeJS.ProcessEnv, signal: AbortSignal): Promise { + if (/^(?:1|true|yes|on)$/i.test(env.CLAUDE_CODE_DISABLE_AGENT_VIEW?.trim() ?? "")) { + throw new LocalMessagingError("claude_agent_view_disabled", "Claude Code agent view is disabled."); + } + const deadline = AbortSignal.any([signal, AbortSignal.timeout(5000)]); + const unavailable = () => new LocalMessagingError("claude_directory_unavailable", "Claude Code could not list local sessions. Check that the selected CLI supports agents --json."); + const childEnv = Object.fromEntries(["HOME", "PATH", "TMPDIR", "LANG", "LC_ALL", "CLAUDE_CONFIG_DIR", "CLAUDE_CODE_DISABLE_AGENT_VIEW"] + .flatMap(key => env[key] === undefined ? [] : [[key, env[key]!] as const])); + let child; + try { + deadline.throwIfAborted(); + child = Bun.spawn([claude, "agents", "--json"], { + env: { ...childEnv, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, + stdin: "ignore", stdout: "pipe", stderr: "ignore", signal: deadline, killSignal: "SIGKILL", + }); + } catch { throw unavailable(); } + let bytes: Uint8Array; + try { + const capture = await readBoundedResponseBytes(new Response(child.stdout), { maxBytes: 256 * 1024, signal: deadline }); + if (capture.oversized) throw invalidDirectory(); + if (await child.exited !== 0 || deadline.aborted) throw unavailable(); + bytes = capture.bytes; + } catch (error) { + if (error instanceof LocalMessagingError) throw error; + throw unavailable(); + } finally { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + await child.exited; + } + + let rows: unknown; + try { rows = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } + catch { throw invalidDirectory(); } + if (!Array.isArray(rows) || rows.length > 256) throw invalidDirectory(); + const sessions: ClaudeSession[] = []; + const seen = new Set(); + for (const row of rows) { + if (!isRecord(row)) throw invalidDirectory(); + if (row.sessionId == null || row.pid == null) continue; + const { sessionId, pid, kind, status } = row; + if (!isThreadId(sessionId) || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 + || (kind !== "interactive" && kind !== "background") + || (status !== "busy" && status !== "waiting" && status !== "idle")) throw invalidDirectory(); + const id = sessionId.toLowerCase(); + if (seen.has(id)) throw invalidDirectory(); + seen.add(id); + sessions.push({ id, kind, status }); + } + return sessions; +} diff --git a/structure/local-messaging.md b/structure/local-messaging.md index 2b3698125af..618c56db71c 100644 --- a/structure/local-messaging.md +++ b/structure/local-messaging.md @@ -72,7 +72,7 @@ no recipient, daemon or proxy is stopped. > Decision record: [ADR-6479](decisions/ADR-6479-local-messaging-command.md) `src/cli/dispatch.ts` dynamically imports the command runner for the message verb. -`src/cli/message-args.ts` rejects malformed, duplicate and remote/Claude options +`src/cli/message-args.ts` rejects malformed, duplicate and remote options on the Codex path before any command resource or home selection. `src/cli/codex-shim-autorestore.ts` skips repair for the whole namespace. Registry, capability and help declarations describe sessions/send; no management route is claimed. The separate pure remote @@ -80,7 +80,7 @@ parser selects a dynamic remote-command import only for explicit remote operatio local operations do not read peer state or start an owner. `src/cli/message-runtime.ts` reuses effective Codex-home resolution without -persistence. Messaging needs no selected CLI binary or version pin. The existing +persistence. The local Codex path needs no selected CLI binary or version pin. The existing Codex daemon must support experimental `thread/queue/add`; there is no installation, repair, daemon start or runtime fallback when it rejects the method. @@ -89,6 +89,25 @@ rejecting invalid bytes, empty text and NUL. The final envelope is bounded at 32 KiB. Message text travels only in the existing Unix RPC connection, never in spawned process arguments. No request-body logging is added. +## Local Claude Code session directory + +`src/cli/message-claude-command.ts` validates the explicit `claude-sessions` +invocation before `src/messaging/claude-discovery.ts` spawns one user-selected +absolute Claude executable with fixed `agents --json` arguments. The subprocess +receives no stdin or inherited credentials, disables Claude's nonessential +traffic, and has a five-second deadline and 256 KiB output limit. An enabled +`CLAUDE_CODE_DISABLE_AGENT_VIEW` refuses before spawn; other values pass to +the native CLI. The executable can initialize its own local configuration. +Cancellation stops only the directly owned executable; raw diagnostics are discarded. + +The snapshot has at most 256 source rows. Rows with a missing or null session +ID or process ID are skipped. Invalid rows with both IDs present, including +shortened session UUIDs, and duplicate session UUIDs fail the snapshot. +Results expose only UUID, session kind and activity status; they give no +inbox address or permission to send and do not prove reachability. +No history, working directory, session title or process ID is returned. Neither +the Codex transport nor the remote-peer mode uses this directory. + ## Envelope and receipt semantics `src/messaging/envelope.ts` assembles the caller-generated UUID, kind, response diff --git a/tests/codex-integration/messaging-local-cli.test.ts b/tests/codex-integration/messaging-local-cli.test.ts index 12efb8c7ffe..484cf764486 100644 --- a/tests/codex-integration/messaging-local-cli.test.ts +++ b/tests/codex-integration/messaging-local-cli.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; -import { existsSync } from "node:fs"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { messageCodexHome } from "../../src/cli/message-runtime"; import { skipsCodexShimAutoRestore } from "../../src/cli/codex-shim-autorestore"; @@ -13,8 +14,12 @@ test("local commands stay registered and skip global repair even on malformed us expect(caps.map(cap => cap.command[1])).toContain("sessions"); expect(caps.map(cap => cap.command[1])).toContain("send"); expect(caps.every(cap => cap.routes.length === 0)).toBe(true); - expect(caps[1]!.mutates).toBe(true); - expect(caps[1]!.flags.map(flag => flag.name)).toContain("--host"); + const send = caps.find(cap => cap.command[1] === "send"); + expect(send?.mutates).toBe(true); + expect(send?.flags.map(flag => flag.name)).toContain("--host"); + const claude = caps.find(cap => cap.command[1] === "claude-sessions"); + expect(claude?.mutates).toBe(false); + expect(claude?.flags.map(flag => flag.name)).toContain("--claude"); }); test("invalid usage allocates no timer, socket, helper or runtime-selection work", async () => { @@ -22,7 +27,20 @@ test("invalid usage allocates no timer, socket, helper or runtime-selection work const { runMessageCommand } = await import(${JSON.stringify(repoPath("src/cli/message-command.ts"))}); const fail = () => { throw new Error('Unexpected resource allocation'); }; globalThis.setTimeout = fail; Bun.spawn = fail; globalThis.WebSocket = class { constructor() { fail(); } }; - process.exitCode = await runMessageCommand(['send', '--host', 'remote', '--stdin'], { CODEX_HOME: '/must-not-read' }); + globalThis.AbortController = class { constructor() { fail(); } }; + for (const args of [ + ['send', '--host', 'remote', '--stdin'], + ['claude-sessions'], + ['claude-sessions', '--claude', 'relative'], + ['claude-sessions', '--claude', '/must-not-run', '--json', '--json'], + ['claude-sessions', '--claude', '/must-not-run', '--claude', '/must-not-run'], + ['claude-sessions', '--claude', '/must-not-run', '--host', 'remote'], + ]) { + if (await runMessageCommand(args, { CODEX_HOME: '/must-not-read' }) !== 64) { + throw new Error('Expected invalid usage exit code'); + } + } + process.exitCode = 64; `; const child = Bun.spawn([process.execPath, "-e", script], { stdout: "pipe", stderr: "pipe" }); const [code, output, errors] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); @@ -77,3 +95,110 @@ test.skipIf(process.platform === "win32")("full CLI uses the daemon directly, em } finally { await fixture.close(); } } }, 30_000); + +test.skipIf(process.platform === "win32")("Claude discovery projects live sessions and sanitizes failed lookups", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-claude-sessions-")); + const executable = join(root, "fake claude"); + const responsePath = join(root, "response.json"); + const failPath = join(root, "fail"); + const hangPath = join(root, "hang"); + const env = { + PATH: process.env.PATH, HOME: root, CODEX_HOME: join(root, "codex"), + OPENCODEX_HOME: join(root, "ocx"), OCX_TEST_HOME_GUARD: "1", + ANTHROPIC_API_KEY: "fixture-private-env", + }; + const cli = [process.execPath, repoPath("src/cli/index.ts"), "message", "claude-sessions"]; + const run = async (args: string[], extraEnv: Record = {}) => { + const child = Bun.spawn([...cli, ...args], { + env: { ...env, ...extraEnv }, stdin: new Blob(["fixture-private-stdin\n"]), stdout: "pipe", stderr: "pipe", + }); + const timer = setTimeout(() => child.kill(), 10_000); + try { + const [exitCode, stdout, stderr] = await Promise.all([ + child.exited, new Response(child.stdout).text(), new Response(child.stderr).text(), + ]); + return { exitCode, stdout, stderr }; + } finally { clearTimeout(timer); } + }; + try { + writeFileSync(executable, `#!/bin/sh +[ "$#" -eq 2 ] && [ "$1" = agents ] && [ "$2" = --json ] || exit 40 +if IFS= read -r line; then exit 41; fi +[ -z "$ANTHROPIC_API_KEY" ] || exit 44 +[ "$CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" = 1 ] || exit 45 +printf '%s\\n' fixture-private-stderr >&2 +/bin/cat "\${0%/*}/response.json" || exit 42 +if [ -f "\${0%/*}/fail" ]; then exit 43; fi +if [ -f "\${0%/*}/hang" ]; then exec /bin/sleep 30; fi +`, { mode: 0o700 }); + const records = [ + { sessionId: "1111111A-1111-4111-8111-111111111111", pid: 123, kind: "interactive", status: "busy", cwd: "/fixture-private-cwd" }, + { sessionId: "22222222-2222-4222-8222-222222222222", pid: 456, kind: "background", status: "idle", name: "fixture-private-name" }, + { sessionId: "33333333-3333-4333-8333-333333333333", pid: 789, kind: "interactive", status: "waiting", summary: "fixture-private-summary" }, + ]; + writeFileSync(responsePath, JSON.stringify([ + ...records, + { sessionId: LOCAL_TARGET, summary: "fixture-private-stopped" }, + { pid: 987, status: "busy" }, + { ...records[0], sessionId: null }, + ])); + const args = ["--claude", executable]; + for (const value of ["1", "true", " Yes ", "ON"]) { + const disabled = await run(["--claude", join(root, "missing executable"), "--json"], { CLAUDE_CODE_DISABLE_AGENT_VIEW: value }); + expect(disabled.exitCode).toBe(1); + expect(JSON.parse(disabled.stdout).error.code).toBe("claude_agent_view_disabled"); + } + const json = await run([...args, "--json"]); + expect(json.exitCode).toBe(0); + expect(json.stderr).toBe(""); + expect(JSON.parse(json.stdout)).toEqual({ + schema: "ocx-claude-sessions/1", + sessions: records.map(({ sessionId, kind, status }) => ({ id: sessionId.toLowerCase(), kind, status })), + }); + const human = await run(args); + expect(human.exitCode).toBe(0); + expect(human.stderr).toBe(""); + expect(human.stdout).not.toContain("fixture-private"); + for (const { sessionId, kind, status } of records) { + expect(human.stdout).toContain(`${sessionId.toLowerCase()}\t${kind}\t${status}\n`); + } + + const expectFailure = async (path = executable) => { + const result = await run(["--claude", path, "--json"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toBe(""); + expect(result.stdout).not.toContain("fixture-private"); + expect(result.stdout).not.toContain(root); + expect(JSON.parse(result.stdout)).toMatchObject({ + schema: "ocx-message-error/1", error: { message: expect.any(String) }, + }); + }; + writeFileSync(responsePath, "[]"); + const empty = await run([...args, "--json"]); + expect(empty.exitCode).toBe(0); + expect(JSON.parse(empty.stdout)).toEqual({ schema: "ocx-claude-sessions/1", sessions: [] }); + const first = records[0]!; + for (const response of [ + "fixture-private-invalid-json", + JSON.stringify({ sessions: records }), + JSON.stringify([records[0], { ...records[1], pid: 0 }]), + JSON.stringify([records[0], { ...records[1], sessionId: "fixture-private-invalid-id" }]), + JSON.stringify([records[0], { ...records[1], sessionId: "12345678" }]), + JSON.stringify([records[0], { ...records[1], kind: "fixture-private-invalid-kind" }]), + JSON.stringify([records[0], { ...records[1], status: "fixture-private-invalid-status" }]), + JSON.stringify([first, { ...first, sessionId: first.sessionId.toLowerCase() }]), + JSON.stringify(Array.from({ length: 257 }, () => ({}))), + " ".repeat(256 * 1024) + "[]", + ]) { + writeFileSync(responsePath, response); + await expectFailure(); + } + writeFileSync(responsePath, "[]"); + writeFileSync(failPath, ""); + await expectFailure(); + await expectFailure(join(root, "missing executable")); + rmSync(failPath); + writeFileSync(hangPath, ""); + await expectFailure(); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 30_000); diff --git a/tests/codex-integration/messaging-local-lifecycle.test.ts b/tests/codex-integration/messaging-local-lifecycle.test.ts index c0988317eb6..d1d6a5afa93 100644 --- a/tests/codex-integration/messaging-local-lifecycle.test.ts +++ b/tests/codex-integration/messaging-local-lifecycle.test.ts @@ -19,7 +19,7 @@ test("transport rejects remote URLs and unsupported platforms without opening a }); test("importing the unactivated subsystem allocates no listener, timer, child or socket", async () => { - const modules = ["types", "budget", "socket", "rpc", "discovery", "envelope", "input", "send", "mcp-queue-rpc", "mcp-queue-tools", "mcp-queue-server", "mcp-reply-tools", "mcp-reply-cursor", "mcp-reply-wait", "mcp-resume-tools", "resume-permissions"].map(name => repoPath("src", "messaging", `${name}.ts`)); + const modules = ["types", "budget", "socket", "rpc", "discovery", "claude-discovery", "envelope", "input", "send", "mcp-queue-rpc", "mcp-queue-tools", "mcp-queue-server", "mcp-reply-tools", "mcp-reply-cursor", "mcp-reply-wait", "mcp-resume-tools", "resume-permissions"].map(name => repoPath("src", "messaging", `${name}.ts`)); const script = ` const forbidden = () => { throw new Error("unexpected messaging resource allocation"); }; globalThis.setTimeout = forbidden; @@ -35,7 +35,7 @@ test("importing the unactivated subsystem allocates no listener, timer, child or test("messaging activation is command-local, never on an ordinary proxy startup path", async () => { // Native parser inventory, not graph completeness: catches static/dynamic literal imports. - const allowed = new Set(["src/cli/message-args.ts", "src/cli/message-command.ts", "src/cli/message-remote-args.ts", "src/cli/message-remote-command.ts", "src/cli/message-mcp-command.ts"]); + const allowed = new Set(["src/cli/message-args.ts", "src/cli/message-command.ts", "src/cli/message-remote-args.ts", "src/cli/message-remote-command.ts", "src/cli/message-mcp-command.ts", "src/cli/message-claude-command.ts"]); const transpiler = new Bun.Transpiler({ loader: "ts" }); for await (const scanned of new Bun.Glob("src/**/*.{ts,mts}").scan({ cwd: repoPath() })) { const path = scanned.replaceAll("\\", "/"); // Bun.Glob yields native separators on Windows. @@ -43,6 +43,10 @@ test("messaging activation is command-local, never on an ordinary proxy startup const imports = transpiler.scanImports(readFileSync(repoPath(path), "utf8").replace(/^#![^\n]*\n/, "")); const incoming = imports.filter(entry => /(?:^|\/)messaging(?:\/|$)/.test(entry.path)); if (!allowed.has(path)) expect(incoming, path).toEqual([]); + for (const entry of imports.filter(entry => entry.path.endsWith("/message-claude-command"))) { + expect(path).toBe("src/cli/message-command.ts"); + expect(entry.kind).toBe("dynamic-import"); + } for (const entry of imports.filter(entry => /(?:^|\/)message-(?:command|args|runtime)$/.test(entry.path))) { expect(["src/cli/dispatch.ts", "src/cli/message-command.ts", "src/cli/message-remote-command.ts", "src/cli/message-remote-args.ts"], path).toContain(path); if (path === "src/cli/dispatch.ts") {