Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

feat(channel): record the calling Claude Code session in spawn.json

Jack Rudenko011fffb0441a
diff --git a/ai-docs/architecture/mcp-channel.md b/ai-docs/architecture/mcp-channel.md
index 4d888195..36ae2c0b 100644
--- a/ai-docs/architecture/mcp-channel.md
+++ b/ai-docs/architecture/mcp-channel.md
@@ -165,6 +165,58 @@ file that exists only during the wait cannot give it that. `finalize` settles be
`appendFileSync` of < 200 bytes per line; a write failure goes to stderr and loses only that
line; the file stops at 1 MB. A one-shot session never writes one.
+### `spawn.json` — the start-time record, and who started the run
+
+`createSession` writes `<sessionDir>/spawn.json` after `prompt.md` and BEFORE `spawn()`,
+atomically (`spawn.json.tmp` + rename), one key per line, and NOT inside a `try`: a session
+that cannot be recorded fails the tool call rather than run unrecorded. It exists before
+every runtime file (`output.log`, `events.jsonl`, `tokens.json`, `waits.jsonl`, `meta.json`)
+and is never removed.
+
+```jsonc
+{
+ "schema": 1, // versions spawn.json only
+ "kind": "session", // "session" | "team"
+ "sessionId": "1a2b3c4d",
+ "parentClaudeSessionId": "<uuid>", // OPTIONAL — present only when proven
+ "hostPid": 12345, // the Claude Code process that launched this server
+ "launcherPid": 12398, // OPTIONAL — present only on the npm launcher path
+ "mcpPid": 12399, // this process: the one that writes meta.json
+ "startedAt": "2026-10-02T10:00:00.000Z",
+ "model": "<as the caller asked for it>",
+ "timeoutSeconds": 600, // effective: min(requested ?? 600, 3600)
+ "claudeSessionId": "<the child's uuid>"
+}
+```
+
+It exists for observers OUTSIDE this process — the magus `claudish` plugin monitor polls the
+sessions directory and reports progress to the Claude Code window that started a run.
+
+**`hostPid` is structural, computed once at startup** (`hostPidFrom`, `channel/parent-proof.ts`).
+A compiled binary or `bun src/index.ts` is the direct child of Claude Code, so `hostPid` is
+`process.ppid`. An npm/bun global install runs Claude Code → `node bin/claudish.cjs` → `bun
+dist/index.js`, so the launcher puts `CLAUDISH_LAUNCHER_PID` (itself) and
+`CLAUDISH_LAUNCHER_PPID` (its parent) in the child's env, and the child believes the pair only
+when `CLAUDISH_LAUNCHER_PID` is its real `ppid` — a pair leaked into a nested claudish is
+inert. `launcherPid` is recorded exactly when that branch ran. No `ps`, no tree walk.
+
+**`parentClaudeSessionId` is proven per call, or absent** (`proveCallingConversation`). The
+environment's `CLAUDE_CODE_SESSION_ID` goes stale on `/clear`, on a resume, and whenever two
+windows share a conversation, so it is never stored as such. Claude Code puts the calling
+tool-use id in the request `_meta["claudecode/toolUseId"]` (the dispatcher passes it as
+`ctx.toolUseId`), and the tool_use block is on disk in the caller's transcript before the tool
+runs. For at most two candidates — the env id (only when `CLAUDE_CODE_CHILD_SESSION` is empty)
+and the `sessionId` of the host's live record `<configDir>/sessions/<hostPid>.json` (only when
+its `pid` matches) — the proof finds the candidate's project directory (fast path: the host
+record's `cwd` with every non-alphanumeric character replaced by `-`; else one listing of
+`projects/`, cached per candidate), then searches the last 256 KB of `<C>.jsonl` and up to 32
+subagent transcripts modified in the last 10 minutes for the quoted id. No hit → wait 250 ms
+once, look again, then absent. A tool-use id is unique and lives only in the transcript of the
+conversation that issued it, so a hit is proof and every failure degrades to "absent". It is
+`await`ed with `fs/promises` before `createSession`, so the server keeps pumping live sessions
+while it looks. `meta.json` (`SessionInfo.parentClaudeSessionId`) carries the same key with the
+same value exactly when `spawn.json` does.
+
### Diagnostics are captured unconditionally, and reachable from the API
Two sessions once ran 900 s of genuine billed work — 241 assistant messages, ~94 k output
diff --git a/docs/usage/mcp-server.md b/docs/usage/mcp-server.md
index cda51ae9..ebeea464 100644
--- a/docs/usage/mcp-server.md
+++ b/docs/usage/mcp-server.md
@@ -309,8 +309,9 @@ contract.
| File | Written | Contents |
|------|---------|----------|
+| `spawn.json` | once, before the session's process starts; atomic | `schema`, `kind: "session"`, `sessionId`, `hostPid` (the Claude Code process running this MCP server), `mcpPid`, `startedAt`, `model`, `timeoutSeconds`, `claudeSessionId`; `launcherPid` when claudish runs through the npm launcher; `parentClaudeSessionId` only when claudish proved which Claude Code conversation made the call |
| `waits.jsonl` | one line each time the session starts and stops waiting for `send_input` | `{"wait":"open","since":…,"turns":…}` then `{"wait":"closed","since":…,"at":…,"to":…}`. Interactive sessions only; append-only, so a wait that opened and closed between two reads still shows. Stops at 1 MB |
-| `meta.json` | once, when the session ends | the final `SessionInfo`: status, exit code, turns, tokens, cost |
+| `meta.json` | once, when the session ends | the final `SessionInfo`: status, exit code, turns, tokens, cost, and `parentClaudeSessionId` exactly when `spawn.json` has it |
---
diff --git a/packages/cli/bin/claudish.cjs b/packages/cli/bin/claudish.cjs
index ff8c3199..d4212b6b 100755
--- a/packages/cli/bin/claudish.cjs
+++ b/packages/cli/bin/claudish.cjs
@@ -111,7 +111,16 @@ Learn more: https://bun.sh`);
try {
child = spawn(bun, [entry, ...process.argv.slice(2)], {
stdio: "inherit",
- env: process.env,
+ // The pid pair tells the Bun child who launched it: this launcher, and the
+ // launcher's own parent (Claude Code, for an MCP server). The child
+ // believes the pair only when CLAUDISH_LAUNCHER_PID is its real parent
+ // (channel/parent-proof.ts `hostPidFrom`), so a value leaked into a
+ // nested claudish is inert.
+ env: {
+ ...process.env,
+ CLAUDISH_LAUNCHER_PID: String(process.pid),
+ CLAUDISH_LAUNCHER_PPID: String(process.ppid),
+ },
});
} catch (err) {
console.error("Failed to start claudish:", err.message);
diff --git a/packages/cli/src/channel/parent-proof.ts b/packages/cli/src/channel/parent-proof.ts
new file mode 100644
index 00000000..9ffef005
--- /dev/null
+++ b/packages/cli/src/channel/parent-proof.ts
@@ -0,0 +1,447 @@
+// ─── Host pid and the parent proof ───────────────────────────────────────────
+//
+// Two facts a session or team record carries so an observer outside this
+// process — the magus `claudish` plugin monitor — can tell which Claude Code
+// window started a run:
+//
+// * `hostPid`: the Claude Code process that launched this MCP server. A
+// structural fact, read once at startup from the process tree we were given
+// (our parent, or our launcher's parent). Never searched for.
+// * `parentClaudeSessionId`: the Claude Code CONVERSATION that issued the
+// tool call. Recorded only when PROVEN per call: the calling tool-use id is
+// found in that conversation's transcript. Otherwise absent — never the id
+// the server happened to start with, which goes stale on /clear, on a
+// resume, and whenever two windows share one conversation.
+//
+// Why a hit is proof: a tool-use id is unique and is written only into the
+// transcript of the conversation (or of a subagent of it) that issued the call.
+// Every source below is used to CONFIRM, and every failure — no `_meta`, an
+// unreadable record, a transcript layout a future Claude Code changed —
+// degrades to "absent", never to a wrong answer.
+
+import * as fsPromises from "node:fs/promises";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+/** What a Claude Code session id or tool-use id may look like. Also the path-safety gate. */
+export const CLAUDE_ID_RE = /^[A-Za-z0-9_-]{8,128}$/;
+
+/** `_meta` key Claude Code puts the calling tool-use id under. */
+export const TOOL_USE_ID_META_KEY = "claudecode/toolUseId";
+
+/** Bytes of a main transcript searched for the tool-use id, from its end. */
+export const TRANSCRIPT_TAIL_BYTES = 256 * 1024;
+
+/** Subagent transcripts are searched only when modified this recently. */
+export const SUBAGENT_WINDOW_MS = 10 * 60_000;
+
+/** At most this many subagent transcripts are searched, newest first. */
+export const MAX_SUBAGENT_FILES = 32;
+
+/** The single wait before the second look: the transcript append may be in flight. */
+export const PROOF_RETRY_DELAY_MS = 250;
+
+// ─── hostPid ─────────────────────────────────────────────────────────────────
+
+export interface HostPids {
+ /** The Claude Code process that launched this MCP server. */
+ hostPid: number;
+ /**
+ * The npm `node` launcher (`bin/claudish.cjs`) between Claude Code and this
+ * process, when there is one. Present exactly when `hostPid` came from the
+ * launcher branch, so every record says which branch produced it.
+ */
+ launcherPid?: number;
+}
+
+function positiveInt(value: string | undefined): number | undefined {
+ if (value === undefined || !/^[1-9][0-9]*$/.test(value)) return undefined;
+ const n = Number(value);
+ return Number.isSafeInteger(n) ? n : undefined;
+}
+
+/**
+ * The host pid, from the environment and our own parent pid. Pure.
+ *
+ * - npm / bun global install: Claude Code → `node` launcher → `bun` (us). The
+ * launcher sets `CLAUDISH_LAUNCHER_PID` (itself) and `CLAUDISH_LAUNCHER_PPID`
+ * (its parent). When `CLAUDISH_LAUNCHER_PID` is OUR parent, the host is the
+ * launcher's parent.
+ * - compiled binary, or `bun src/index.ts`: our parent is the host.
+ *
+ * The pair check makes a leaked pair inert: a nested claudish that inherits an
+ * outer launcher's variables sees `CLAUDISH_LAUNCHER_PID` ≠ its own parent and
+ * ignores them. No `ps`, no walk.
+ */
+export function hostPidFrom(env: Record<string, string | undefined>, ppid: number): HostPids {
+ const launcherPpid = positiveInt(env.CLAUDISH_LAUNCHER_PPID);
+ if (
+ env.CLAUDISH_LAUNCHER_PID === String(ppid) &&
+ launcherPpid !== undefined &&
+ launcherPpid !== ppid
+ ) {
+ return { hostPid: launcherPpid, launcherPid: ppid };
+ }
+ return { hostPid: ppid };
+}
+
+// ─── Candidates ──────────────────────────────────────────────────────────────
+
+/**
+ * The conversation id this server was started with, when it can be a
+ * candidate at all.
+ *
+ * `CLAUDE_CODE_SESSION_ID` when it is well formed and `CLAUDE_CODE_CHILD_SESSION`
+ * is empty. Claude Code sets the latter for Bash-tool children and monitors and
+ * strips it from the stdio MCP servers it launches, so its presence means this
+ * server was not started by Claude Code directly. A candidate only: it is
+ * believed when the proof finds the tool-use id in its transcript.
+ */
+export function parentSessionIdFrom(env: Record<string, string | undefined>): string | undefined {
+ const id = env.CLAUDE_CODE_SESSION_ID;
+ if (id === undefined || !CLAUDE_ID_RE.test(id)) return undefined;
+ if (env.CLAUDE_CODE_CHILD_SESSION) return undefined;
+ return id;
+}
+
+/** `CLAUDE_CONFIG_DIR`, else `~/.claude`. */
+export function claudeConfigDir(env: Record<string, string | undefined>): string {
+ const fromEnv = env.CLAUDE_CONFIG_DIR;
+ return fromEnv && fromEnv.length > 0 ? fromEnv : join(homedir(), ".claude");
+}
+
+/** The subset of `node:fs/promises` the proof uses. Injectable for tests. */
+export interface ProofFs {
+ readFile: (path: string, encoding: "utf-8") => Promise<string>;
+ readdir: (path: string) => Promise<string[]>;
+ stat: (path: string) => Promise<{ mtimeMs: number; size: number; isDirectory(): boolean }>;
+ open: (
+ path: string,
+ flags: "r"
+ ) => Promise<{
+ read: (
+ buffer: Uint8Array,
+ offset: number,
+ length: number,
+ position: number
+ ) => Promise<{ bytesRead: number }>;
+ close: () => Promise<void>;
+ }>;
+}
+
+const defaultFs: ProofFs = {
+ readFile: (path, encoding) => fsPromises.readFile(path, encoding),
+ readdir: (path) => fsPromises.readdir(path),
+ stat: (path) => fsPromises.stat(path),
+ open: (path, flags) => fsPromises.open(path, flags),
+};
+
+/** The host's live session record, as far as the proof trusts it. */
+export interface HostSessionRecord {
+ sessionId: string;
+ /** The host's working directory, when the record names one. Feeds the fast path. */
+ cwd?: string;
+}
+
+/**
+ * `<configDir>/sessions/<hostPid>.json`, the record Claude Code writes at
+ * startup and rewrites on every session switch (so it is current after
+ * `/clear`). Used only when it parses, its `pid === hostPid`, and its
+ * `sessionId` is well formed; anything else is `undefined`. Never throws.
+ */
+export async function readHostSessionRecord(opts: {
+ configDir: string;
+ hostPid: number;
+ fs?: ProofFs;
+}): Promise<HostSessionRecord | undefined> {
+ const fs = opts.fs ?? defaultFs;
+ try {
+ const raw = await fs.readFile(
+ join(opts.configDir, "sessions", `${opts.hostPid}.json`),
+ "utf-8"
+ );
+ const parsed: unknown = JSON.parse(raw);
+ if (!parsed || typeof parsed !== "object") return undefined;
+ const rec = parsed as { pid?: unknown; sessionId?: unknown; cwd?: unknown };
+ if (rec.pid !== opts.hostPid) return undefined;
+ if (typeof rec.sessionId !== "string" || !CLAUDE_ID_RE.test(rec.sessionId)) return undefined;
+ return {
+ sessionId: rec.sessionId,
+ ...(typeof rec.cwd === "string" && rec.cwd.length > 0 ? { cwd: rec.cwd } : {}),
+ };
+ } catch {
+ return undefined;
+ }
+}
+
+/** One conversation the proof may confirm. */
+export interface ProofCandidate {
+ sessionId: string;
+ /** Working directory whose project directory is tried first (the fast path). */
+ cwd?: string;
+}
+
+/**
+ * The candidates for one call, deduplicated, at most two: the environment's
+ * session id, then the host session record's. The host record's `cwd` is
+ * attached to both, since it names the project the host runs in.
+ */
+export async function gatherProofCandidates(opts: {
+ env: Record<string, string | undefined>;
+ hostPid: number;
+ configDir: string;
+ fs?: ProofFs;
+}): Promise<ProofCandidate[]> {
+ const record = await readHostSessionRecord({
+ configDir: opts.configDir,
+ hostPid: opts.hostPid,
+ fs: opts.fs,
+ });
+ const cwd = record?.cwd;
+ const ids = [parentSessionIdFrom(opts.env), record?.sessionId].filter(
+ (id): id is string => id !== undefined
+ );
+ return [...new Set(ids)].map((sessionId) => ({ sessionId, ...(cwd ? { cwd } : {}) }));
+}
+
+// ─── The proof ───────────────────────────────────────────────────────────────
+
+/**
+ * Claude Code's project directory name for a cwd: every character outside
+ * `[A-Za-z0-9]` becomes `-` (so `/.claude/` becomes `--claude-`). Observed
+ * naming, used ONLY as the fast path: a future rule change degrades to the
+ * directory listing, never to a wrong answer.
+ */
+export function projectDirNameFor(cwd: string): string {
+ return cwd.replace(/[^A-Za-z0-9]/g, "-");
+}
+
+/**
+ * `<configDir>\0<candidate>` → the project directory holding `<candidate>.jsonl`.
+ * A hit is kept for the server's life, so the listing fallback runs at most
+ * once per candidate.
+ */
+export type ProjectDirCache = Map<string, string>;
+
+const serverProjectDirCache: ProjectDirCache = new Map();
+
+async function exists(fs: ProofFs, path: string): Promise<boolean> {
+ try {
+ await fs.stat(path);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+async function findProjectDir(
+ fs: ProofFs,
+ configDir: string,
+ candidate: ProofCandidate,
+ cache: ProjectDirCache
+): Promise<string | undefined> {
+ const cacheKey = `${configDir}\0${candidate.sessionId}`;
+ const cached = cache.get(cacheKey);
+ if (cached !== undefined) return cached;
+
+ const projectsDir = join(configDir, "projects");
+ const fileName = `${candidate.sessionId}.jsonl`;
+
+ if (candidate.cwd) {
+ const fast = join(projectsDir, projectDirNameFor(candidate.cwd));
+ if (await exists(fs, join(fast, fileName))) {
+ cache.set(cacheKey, fast);
+ return fast;
+ }
+ }
+
+ let names: string[];
+ try {
+ names = await fs.readdir(projectsDir);
+ } catch {
+ return undefined;
+ }
+ for (const name of names) {
+ const dir = join(projectsDir, name);
+ if (await exists(fs, join(dir, fileName))) {
+ cache.set(cacheKey, dir);
+ return dir;
+ }
+ }
+ return undefined;
+}
+
+/** Whether the last `TRANSCRIPT_TAIL_BYTES` of `path` contain `needle`. */
+async function tailContains(fs: ProofFs, path: string, needle: Buffer): Promise<boolean> {
+ let handle: Awaited<ReturnType<ProofFs["open"]>> | undefined;
+ try {
+ const { size } = await fs.stat(path);
+ const length = Math.min(size, TRANSCRIPT_TAIL_BYTES);
+ if (length < needle.length) return false;
+ const buffer = Buffer.alloc(length);
+ handle = await fs.open(path, "r");
+ const { bytesRead } = await handle.read(buffer, 0, length, size - length);
+ return buffer.subarray(0, bytesRead).includes(needle);
+ } catch {
+ return false;
+ } finally {
+ await handle?.close().catch(() => {});
+ }
+}
+
+/** `<project>/<candidate>/subagents/*.jsonl` modified in the window, newest first, capped. */
+async function recentSubagentTranscripts(
+ fs: ProofFs,
+ projectDir: string,
+ candidateId: string,
+ nowMs: number
+): Promise<string[]> {
+ const dir = join(projectDir, candidateId, "subagents");
+ let names: string[];
+ try {
+ names = await fs.readdir(dir);
+ } catch {
+ return [];
+ }
+ const recent: { path: string; mtimeMs: number }[] = [];
+ for (const name of names) {
+ if (!name.endsWith(".jsonl")) continue;
+ const path = join(dir, name);
+ try {
+ const { mtimeMs } = await fs.stat(path);
+ if (nowMs - mtimeMs <= SUBAGENT_WINDOW_MS) recent.push({ path, mtimeMs });
+ } catch {
+ /* gone between readdir and stat */
+ }
+ }
+ recent.sort((a, b) => b.mtimeMs - a.mtimeMs);
+ return recent.slice(0, MAX_SUBAGENT_FILES).map((f) => f.path);
+}
+
+async function candidateHolds(
+ fs: ProofFs,
+ configDir: string,
+ candidate: ProofCandidate,
+ needle: Buffer,
+ nowMs: number,
+ cache: ProjectDirCache
+): Promise<boolean> {
+ const projectDir = await findProjectDir(fs, configDir, candidate, cache);
+ if (projectDir === undefined) return false;
+ if (await tailContains(fs, join(projectDir, `${candidate.sessionId}.jsonl`), needle)) {
+ return true;
+ }
+ for (const path of await recentSubagentTranscripts(fs, projectDir, candidate.sessionId, nowMs)) {
+ if (await tailContains(fs, path, needle)) return true;
+ }
+ return false;
+}
+
+export interface ProveCallingConversationOptions {
+ /** The calling tool-use id, from the request `_meta`. Anything malformed → `undefined`, no read. */
+ toolUseId: unknown;
+ /** At most two are used, after deduplication. A bare string is a candidate with no `cwd`. */
+ candidates: readonly (ProofCandidate | string)[];
+ /** Claude Code's config directory (`claudeConfigDir(env)`). */
+ configDir: string;
+ /** Clock for the subagent recency window. Default `Date.now`. */
+ now?: () => number;
+ /** Injected filesystem. Default `node:fs/promises`. */
+ fs?: ProofFs;
+ /** The single 250 ms wait. Default a real timer. */
+ sleep?: (ms: number) => Promise<void>;
+ /** Project-directory hits. Default: one cache for the server's life. */
+ cache?: ProjectDirCache;
+}
+
+/**
+ * The conversation whose transcript holds the calling tool-use id, or
+ * `undefined`. Asynchronous throughout, so the MCP process keeps pumping every
+ * live session while one call proves. Never throws.
+ *
+ * For each candidate: find its project directory (fast path from `cwd`, else
+ * one listing), then search the last 256 KB of `<C>.jsonl`, then up to 32
+ * subagent transcripts modified in the last 10 minutes, newest first, for the
+ * exact quoted substring `"<toolUseId>"`. The first hit decides. With no hit,
+ * wait 250 ms once and look again; then `undefined`.
+ */
+export async function proveCallingConversation(
+ opts: ProveCallingConversationOptions
+): Promise<string | undefined> {
+ const { toolUseId } = opts;
+ if (typeof toolUseId !== "string" || !CLAUDE_ID_RE.test(toolUseId)) return undefined;
+ const candidates = normaliseCandidates(opts.candidates);
+ if (candidates.length === 0) return undefined;
+
+ const fs = opts.fs ?? defaultFs;
+ const now = opts.now ?? Date.now;
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ const cache = opts.cache ?? serverProjectDirCache;
+ const needle = Buffer.from(`"${toolUseId}"`, "utf-8");
+
+ const look = async (): Promise<string | undefined> => {
+ for (const candidate of candidates) {
+ if (await candidateHolds(fs, opts.configDir, candidate, needle, now(), cache)) {
+ return candidate.sessionId;
+ }
+ }
+ return undefined;
+ };
+
+ try {
+ const first = await look();
+ if (first !== undefined) return first;
+ await sleep(PROOF_RETRY_DELAY_MS);
+ return await look();
+ } catch {
+ // Every failure is "not proven".
+ return undefined;
+ }
+}
+
+/**
+ * Well-formed, deduplicated, at most two. The id becomes a path segment, and
+ * the pattern is what keeps it one.
+ */
+function normaliseCandidates(raw: readonly (ProofCandidate | string)[]): ProofCandidate[] {
+ const out: ProofCandidate[] = [];
+ for (const entry of raw) {
+ const candidate = typeof entry === "string" ? { sessionId: entry } : entry;
+ if (!CLAUDE_ID_RE.test(candidate.sessionId)) continue;
+ if (out.some((c) => c.sessionId === candidate.sessionId)) continue;
+ out.push(candidate);
+ if (out.length === 2) break;
+ }
+ return out;
+}
+
+/**
+ * The whole per-call proof as the MCP handlers run it: gather the candidates
+ * for this host, then prove. `undefined` whenever nothing is proven.
+ */
+export async function proveParentForCall(opts: {
+ toolUseId: unknown;
+ hostPid: number;
+ env?: Record<string, string | undefined>;
+ fs?: ProofFs;
+}): Promise<string | undefined> {
+ if (typeof opts.toolUseId !== "string" || !CLAUDE_ID_RE.test(opts.toolUseId)) return undefined;
+ const env = opts.env ?? process.env;
+ const configDir = claudeConfigDir(env);
+ try {
+ const candidates = await gatherProofCandidates({
+ env,
+ hostPid: opts.hostPid,
+ configDir,
+ fs: opts.fs,
+ });
+ return await proveCallingConversation({
+ toolUseId: opts.toolUseId,
+ candidates,
+ configDir,
+ fs: opts.fs,
+ });
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/cli/src/channel/session-manager.ts b/packages/cli/src/channel/session-manager.ts
index fff85543..bbc60eee 100644
--- a/packages/cli/src/channel/session-manager.ts
+++ b/packages/cli/src/channel/session-manager.ts
@@ -32,6 +32,7 @@ import {
openSync,
readFileSync,
readSync,
+ renameSync,
statSync,
writeFileSync,
} from "node:fs";
@@ -48,6 +49,7 @@ import { resolveClaudishSpawn } from "../spawn-claudish.js";
import { decodeChunk } from "../stdio-decode.js";
import { STDOUT_TAIL_LIMIT, classifyRunOutput, meaningfulStderr } from "../team-orchestrator.js";
import { readTokenStatsAt } from "../team-stats.js";
+import { hostPidFrom } from "./parent-proof.js";
import { ScrollbackBuffer } from "./scrollback-buffer.js";
import {
type ResultSummary,
@@ -300,6 +302,22 @@ const DEFAULT_EVENT_LIMIT = 40;
*/
const UPSTREAM_ERROR_TAIL_BYTES = 64 * 1024;
+/**
+ * `spawn.json`'s `schema`. Bumped only on a breaking change to `spawn.json`; it
+ * versions that file alone, not `waits.jsonl` or a team record's `meta.json`.
+ */
+const SPAWN_RECORD_SCHEMA = 1;
+
+/**
+ * Write JSON so a reader never sees half of it: `<path>.tmp`, then rename over
+ * `<path>`. Throws on failure; callers that must not throw catch it themselves.
+ */
+function writeJsonAtomic(path: string, value: unknown): void {
+ const tmp = `${path}.tmp`;
+ writeFileSync(tmp, JSON.stringify(value, null, 2), "utf-8");
+ renameSync(tmp, path);
+}
+
/** Marker `recordStderr` leaves where it dropped the middle of the buffer. */
const STDERR_TRUNCATION_MARKER = "[claudish] … stderr truncated to";
@@ -634,6 +652,10 @@ function readJsonObject(path: string, maxBytes: number): Record<string, unknown>
const metaString = (v: unknown): string | null =>
typeof v === "string" && v.length > 0 ? v : null;
+/** `{ parentClaudeSessionId }` when there is one, else nothing — never the key with no value. */
+const optionalParent = (id: string | null | undefined): { parentClaudeSessionId?: string } =>
+ id ? { parentClaudeSessionId: id } : {};
+
/** A field of a `meta.json` that must be a finite number, or null. */
const metaNumber = (v: unknown): number | null =>
typeof v === "number" && Number.isFinite(v) ? v : null;
@@ -747,8 +769,18 @@ export class SessionManager {
private terminalRetentionMs: number;
private onStateChange?: (sessionId: string, event: ChannelEvent) => void;
private sigintHandler: (() => void) | null = null;
+ private readonly _hostPid: number;
+ private readonly _launcherPid: number | undefined;
constructor(options?: SessionManagerOptions) {
+ // Computed once: the Claude Code process that launched this MCP server
+ // does not change for the life of the process. See parent-proof.ts.
+ const host =
+ options?.hostPid !== undefined
+ ? { hostPid: options.hostPid }
+ : hostPidFrom(process.env, process.ppid);
+ this._hostPid = host.hostPid;
+ this._launcherPid = host.launcherPid;
this.maxSessions = options?.maxSessions ?? DEFAULT_MAX_SESSIONS;
this.scrollbackCapacity = options?.scrollbackCapacity ?? DEFAULT_SCROLLBACK;
this.terminalRetentionMs = options?.terminalRetentionMs ?? TERMINAL_RETENTION_MS;
@@ -760,6 +792,55 @@ export class SessionManager {
this.onStateChange = options?.onStateChange;
}
+ /** The Claude Code process that launched this MCP server (`spawn.json` `hostPid`). */
+ get hostPid(): number {
+ return this._hostPid;
+ }
+
+ /** The npm `node` launcher between Claude Code and this process, when there is one. */
+ get launcherPid(): number | undefined {
+ return this._launcherPid;
+ }
+
+ /**
+ * Write `<dir>/spawn.json`, the start-time record, atomically (tmp + rename),
+ * one key per line.
+ *
+ * Deliberately NOT wrapped in a `try`: a run that cannot be recorded must not
+ * run unrecorded, so a failure here fails the tool call before any child
+ * exists. `hostPid`, `launcherPid` (only when the launcher branch produced
+ * `hostPid`) and `mcpPid` — this process, the one that writes `meta.json` —
+ * are filled in here; the caller supplies the rest.
+ */
+ private writeSpawnRecord(
+ dir: string,
+ record: {
+ kind: "session" | "team";
+ sessionId: string;
+ parentClaudeSessionId?: string;
+ startedAt: string;
+ model?: string;
+ timeoutSeconds?: number;
+ claudeSessionId?: string;
+ teamPath?: string;
+ slots?: number;
+ }
+ ): void {
+ const { kind, sessionId, parentClaudeSessionId, startedAt, ...rest } = record;
+ const body = {
+ schema: SPAWN_RECORD_SCHEMA,
+ kind,
+ sessionId,
+ ...(parentClaudeSessionId ? { parentClaudeSessionId } : {}),
+ hostPid: this._hostPid,
+ ...(this._launcherPid !== undefined ? { launcherPid: this._launcherPid } : {}),
+ mcpPid: process.pid,
+ startedAt,
+ ...rest,
+ };
+ writeJsonAtomic(join(dir, "spawn.json"), body);
+ }
+
/** Create and start a new session. Returns the session ID. */
createSession(opts: SessionCreateOptions): string {
if (this.activeSessions >= this.maxSessions) {
@@ -787,6 +868,20 @@ export class SessionManager {
writeFileSync(join(sessionDir, "prompt.md"), opts.prompt, "utf-8");
}
+ // The start-time record, BEFORE spawn and before every runtime file, so a
+ // session never runs unrecorded and an observer of the sessions directory
+ // can attribute it from its first moment (`hostPid`, and the calling
+ // conversation when the caller proved it). Throws rather than continue.
+ this.writeSpawnRecord(sessionDir, {
+ kind: "session",
+ sessionId,
+ parentClaudeSessionId: opts.parentClaudeSessionId,
+ startedAt,
+ model: opts.model,
+ timeoutSeconds: timeout,
+ claudeSessionId,
+ });
+
// `spawnModel` is the parent-resolved explicit "provider@model" spec when
// routing was pinned; absent means spawn the caller's string. `info.model`
// below deliberately keeps `opts.model` — the pin is argv-only.
@@ -865,6 +960,9 @@ export class SessionManager {
toolCallCount: 0,
terminalReason: null,
claudeSessionId,
+ // Present only when proven, so `meta.json` carries the key exactly when
+ // `spawn.json` does, with the same value.
+ ...optionalParent(opts.parentClaudeSessionId),
// Derived from the spawn cwd now, and re-derived from the child's own
// `system:init.cwd` if that turns out to differ. See refreshTranscriptPath.
transcriptPath: transcriptPathFor(cwd, claudeSessionId),
@@ -1401,7 +1499,15 @@ export class SessionManager {
return null;
}
+ // A team run's record lives in the same directory (`team-<8 hex>/`, written
+ // for the plugin monitor) and its id passes SESSION_ID_RE, but it is not a
+ // session: read as one it would come back a confident `model: "unknown"`
+ // record. `spawn.json` exists from creation, so it is checked first; an
+ // id-addressed tool then answers a team id exactly like an unknown id.
+ const spawnRecord = readJsonObject(join(sessionDir, "spawn.json"), META_READ_LIMIT);
+ if (spawnRecord?.kind === "team") return null;
const meta = readJsonObject(join(sessionDir, "meta.json"), META_READ_LIMIT);
+ if (meta?.kind === "team") return null;
const partial = meta === null;
const measured = diskAccounting(sessionDir);
@@ -1449,6 +1555,8 @@ export class SessionManager {
// plus this marker say "ended without a record", not "ended in error".
terminalReason: metaString(meta?.terminalReason) ?? (partial ? NO_TERMINAL_RECORD : null),
claudeSessionId: metaString(meta?.claudeSessionId),
+ // Absent unless the file carries a non-empty value: `""` is "not proven".
+ ...optionalParent(metaString(meta?.parentClaudeSessionId)),
transcriptPath: metaString(meta?.transcriptPath),
},
};
diff --git a/packages/cli/src/channel/types.ts b/packages/cli/src/channel/types.ts
index 07e8d7ad..d39cdc92 100644
--- a/packages/cli/src/channel/types.ts
+++ b/packages/cli/src/channel/types.ts
@@ -88,6 +88,13 @@ export interface SessionInfo {
* consumer can find the full record without guessing by mtime.
*/
claudeSessionId: string | null;
+ /**
+ * The Claude Code conversation that called create_session, PROVEN at call
+ * time: the calling tool-use id was found in that conversation's transcript
+ * (channel/parent-proof.ts). Absent when not proven — never a guess, never
+ * the id the MCP server happened to start with.
+ */
+ parentClaudeSessionId?: string;
/**
* Absolute path to the child's authoritative JSONL transcript, or null before
* `claudeSessionId` is known.
@@ -167,6 +174,12 @@ export interface SessionCreateOptions {
* consumers differ.
*/
keepUnrecognizedJson?: boolean;
+ /**
+ * The calling conversation, when the caller PROVED it (see
+ * `proveCallingConversation`). Recorded verbatim in `spawn.json` and
+ * `SessionInfo`; absent means not proven. Never pass an unproven id.
+ */
+ parentClaudeSessionId?: string;
}
export interface ChannelEvent {
@@ -231,4 +244,10 @@ export interface SessionManagerOptions {
* unaffected by eviction.
*/
terminalRetentionMs?: number;
+ /**
+ * Test override for the host pid recorded in `spawn.json`. Default:
+ * `hostPidFrom(process.env, process.ppid)` (channel/parent-proof.ts). An
+ * override records no `launcherPid`.
+ */
+ hostPid?: number;
}
diff --git a/packages/cli/src/mcp-server.ts b/packages/cli/src/mcp-server.ts
index 60f6023e..acab036c 100644
--- a/packages/cli/src/mcp-server.ts
+++ b/packages/cli/src/mcp-server.ts
@@ -24,6 +24,7 @@ import { assertAgentAvailable } from "./agent-availability.js";
import { prehydrateCredentialsForSpawn } from "./auth/credentials/prehydrate.js";
import { installWireTap, watchNotificationResult, wrapStateChange } from "./channel/diagnostics.js";
import { SessionManager } from "./channel/index.js";
+import { TOOL_USE_ID_META_KEY, proveParentForCall } from "./channel/parent-proof.js";
import { isSubscriptionProvider } from "./handlers/shared/remote-provider-types.js";
import {
type HeartbeatHandle,
@@ -147,6 +148,13 @@ interface ToolCallContext {
* heartbeat has been stopped. Never throws.
*/
reportProgress: (message?: string) => void;
+ /**
+ * The calling tool-use id, from the request `_meta["claudecode/toolUseId"]`
+ * Claude Code attaches to every MCP tool call. Undefined when the client sent
+ * none. Untrusted input: `proveCallingConversation` validates it before any
+ * use, and it is only ever used to PROVE which conversation called.
+ */
+ toolUseId?: string;
}
interface ToolDefinition {
@@ -1714,7 +1722,7 @@ function defineTools(
required: ["model"],
},
group: "channel",
- handler: async (args) => {
+ handler: async (args, ctx) => {
try {
const claudishFlags = buildChildClaudeFlags(args.agent, args.claude_flags);
@@ -1741,6 +1749,14 @@ function defineTools(
pin: workDir === undefined || resolve(workDir) === process.cwd(),
});
+ // Which conversation called, PROVEN from its transcript or left absent.
+ // Asynchronous throughout (fs/promises, one 250 ms timer at most), so
+ // this process keeps pumping every live session while it looks.
+ const parentClaudeSessionId = await proveParentForCall({
+ toolUseId: ctx.toolUseId,
+ hostPid: sessionManager.hostPid,
+ });
+
const sessionId = sessionManager.createSession({
model: requestedModel,
spawnModel: plan.pinned.get(requestedModel),
@@ -1748,6 +1764,7 @@ function defineTools(
timeoutSeconds: args.timeout_seconds as number | undefined,
claudishFlags,
cwd: workDir,
+ parentClaudeSessionId,
});
return {
@@ -2153,7 +2170,11 @@ async function main() {
extra.sendNotification({ method: "notifications/progress", params: frame }),
})
: NOOP_HEARTBEAT;
- const ctx: ToolCallContext = { reportProgress: (message) => heartbeat.tick(message) };
+ const rawToolUseId = extra._meta?.[TOOL_USE_ID_META_KEY];
+ const ctx: ToolCallContext = {
+ reportProgress: (message) => heartbeat.tick(message),
+ ...(typeof rawToolUseId === "string" ? { toolUseId: rawToolUseId } : {}),
+ };
try {
return await tool.handler(args ?? {}, ctx);