Skip to content
Merged
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
30 changes: 30 additions & 0 deletions docs-site/src/content/docs/es/reference/cli/messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

<a id="list-local-claude-code-sessions"></a>

## 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.

<a id="discover-and-send"></a>

## Descubrir y enviar
Expand Down
25 changes: 25 additions & 0 deletions docs-site/src/content/docs/reference/cli/messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docs-site/src/content/docs/tr/reference/cli/messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 6 additions & 2 deletions skills/ocx/references/01_management_surface.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
19 changes: 18 additions & 1 deletion skills/ocx/references/01_surface_agents-routing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down Expand Up @@ -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 <absolute-cli-path> [--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).
Expand Down
9 changes: 9 additions & 0 deletions src/cli/capabilities-agents-routing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 <absolute-cli-path> [--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).",
Expand Down
40 changes: 40 additions & 0 deletions src/cli/message-claude-command.ts
Original file line number Diff line number Diff line change
@@ -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<number> {
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 <absolute-cli-path> [--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);
}
}
3 changes: 2 additions & 1 deletion src/cli/message-command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<number> {
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 <peer>] [--json] | send (--thread <uuid> | --name <exact-name>) --stdin [--host <peer>] [--kind request|response|notification] [--in-reply-to <uuid>] [--json] | mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home> [--allow-reply-read] [--allow-resume --resume-socket <absolute-existing-unix-socket> --resume-permissions <profile-id>] | enable [--port <port>] | disable | status | hosts <probe|add|list|remove|abandon|allow-inbound|deny-inbound> | serve [--host <peer>]...");
console.error("Usage: ocx message sessions [--host <peer>] [--json] | send (--thread <uuid> | --name <exact-name>) --stdin [--host <peer>] [--kind request|response|notification] [--in-reply-to <uuid>] [--json] | mcp --codex <absolute-cli-path> --codex-home <absolute-existing-home> [--allow-reply-read] [--allow-resume --resume-socket <absolute-existing-unix-socket> --resume-permissions <profile-id>] | claude-sessions --claude <absolute-cli-path> [--json] | enable [--port <port>] | disable | status | hosts <probe|add|list|remove|abandon|allow-inbound|deny-inbound> | serve [--host <peer>]...");
return 64;
}
const controller = new AbortController();
Expand Down
4 changes: 2 additions & 2 deletions src/cli/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export const CLI_COMMANDS: CliCommandEntry[] = [
},
{
name: "message",
usage: "ocx message <sessions|send|mcp|enable|disable|status|hosts|serve> [options]",
summary: "Discover loaded Codex sessions and queue messages locally or through explicit SSH peers.",
usage: "ocx message <sessions|send|mcp|claude-sessions|enable|disable|status|hosts|serve> [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."],
},
{
Expand Down
62 changes: 62 additions & 0 deletions src/messaging/claude-discovery.ts
Original file line number Diff line number Diff line change
@@ -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<ClaudeSession[]> {
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<string>();
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;
}
23 changes: 21 additions & 2 deletions structure/local-messaging.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,15 +72,15 @@ 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
parser selects a dynamic remote-command import only for explicit remote operations;
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.

Expand All @@ -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
Expand Down
Loading
Loading