Skip to content

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

feat(hooks): add InProcessSink for claudish -i responseEnd injections

Jack Rudenkoc9b87909bc10
diff --git a/packages/cli/src/hooks/injection/in-process-sink.test.ts b/packages/cli/src/hooks/injection/in-process-sink.test.ts
new file mode 100644
index 00000000..5c903d50
--- /dev/null
+++ b/packages/cli/src/hooks/injection/in-process-sink.test.ts
@@ -0,0 +1,142 @@
+/**
+ * The interactive launcher's sink (hook-system §2.3, last paragraph): the inbox lines a
+ * pane child appends to its file, kept in memory, and drained by the owner's rule —
+ * one `InboxReader` for both sources.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { InboxReader } from "./inbox.js";
+import {
+ HOOK_INBOX_ENV,
+ InProcessSink,
+ InboxFileSink,
+ UnavailableSink,
+ resetUnavailableSinkReportForTests,
+ setProcessSink,
+ sinkFromEnv,
+} from "./sinks.js";
+
+afterEach(() => {
+ setProcessSink(null);
+ resetUnavailableSinkReportForTests();
+});
+
+const fixed = () => new Date("2026-10-14T00:00:00.000Z");
+
+describe("InProcessSink drained by InboxReader", () => {
+ test("lines before the settle are drained at once; a request with no stop is never waited for", async () => {
+ const sink = new InProcessSink(1024 * 1024, fixed, () => {});
+ sink.stop("r1");
+ expect(sink.inject("r1", "hook:a/x", "P")).toBe("queued");
+ expect(sink.annotate("r1", "hook:a/x", "k", 1)).toBe("queued");
+ sink.end("r1", false);
+ // r2 is still streaming: an inject without a stop is taken, never waited on
+ sink.inject("r2", "hook:a/x", "Q");
+ const reader = new InboxReader(sink.inbox);
+ expect(reader.hasUnread()).toBe(true);
+ const started = Date.now();
+ const d = await reader.drain(5_000);
+ expect(Date.now() - started).toBeLessThan(200);
+ expect(d.injections.map((i) => i.text)).toEqual(["P", "Q"]);
+ expect(d.annotations).toEqual([{ req: "r1", hookId: "hook:a/x", key: "k", value: 1 }]);
+ expect(reader.hasUnread()).toBe(false);
+ });
+
+ test("a stop without its end is waited for, and the wait ends when the end arrives", async () => {
+ const sink = new InProcessSink(1024 * 1024, fixed, () => {});
+ const reader = new InboxReader(sink.inbox);
+ sink.stop("r1");
+ setTimeout(() => {
+ sink.inject("r1", "hook:a/x", "LATE");
+ sink.inject("r9", "hook:a/x", "OTHER");
+ sink.end("r1", false);
+ }, 150);
+ const started = Date.now();
+ const d = await reader.drain(5_000);
+ const took = Date.now() - started;
+ expect(took).toBeGreaterThanOrEqual(140);
+ expect(took).toBeLessThan(1_000);
+ expect(d.injections.map((i) => i.text)).toEqual(["LATE"]);
+ // another request's line arriving during the wait is carried to the next settle
+ expect(reader.hasUnread()).toBe(true);
+ const next = await reader.drain(100);
+ expect(next.injections.map((i) => i.text)).toEqual(["OTHER"]);
+ });
+
+ test("the wait is bounded and abortable", async () => {
+ const sink = new InProcessSink(1024 * 1024, fixed, () => {});
+ sink.stop("r1");
+ const bounded = Date.now();
+ const d = await new InboxReader(sink.inbox).drain(250);
+ expect(Date.now() - bounded).toBeGreaterThanOrEqual(240);
+ expect(d.timedOut).toEqual(["r1"]);
+
+ const sink2 = new InProcessSink(1024 * 1024, fixed, () => {});
+ sink2.stop("r2");
+ const ctl = new AbortController();
+ setTimeout(() => ctl.abort("exit"), 100);
+ const aborted = Date.now();
+ await new InboxReader(sink2.inbox).drain(10_000, ctl.signal);
+ expect(Date.now() - aborted).toBeLessThan(1_000);
+ });
+
+ test("the payload cap counts inject + annotate bytes only and reports once", async () => {
+ const sink = new InProcessSink(400, fixed, () => {});
+ expect(sink.inject("r1", "hook:a/x", "x".repeat(100))).toBe("queued");
+ expect(sink.inject("r1", "hook:a/x", "y".repeat(300))).toBe("inbox_cap");
+ expect(sink.inject("r1", "hook:a/x", "z")).toBe("inbox_cap");
+ for (let i = 0; i < 50; i++) {
+ sink.stop(`s${i}`);
+ sink.end(`s${i}`, false);
+ }
+ const d = await new InboxReader(sink.inbox).drain(100);
+ expect(d.capped).toBe(true);
+ expect(d.injections.map((i) => i.text.length)).toEqual([100]);
+ });
+
+ test("markUnavailable: injections are dropped `unavailable` with one stderr line, bookkeeping stops", () => {
+ const lines: string[] = [];
+ const sink = new InProcessSink(1024 * 1024, fixed, (l) => lines.push(l));
+ expect(sink.available).toBe(true);
+ sink.markUnavailable();
+ expect(sink.available).toBe(false);
+ expect(sink.inject("r1", "hook:a/x", "P")).toBe("unavailable");
+ expect(sink.inject("r2", "hook:a/x", "Q")).toBe("unavailable");
+ expect(sink.annotate("r1", "hook:a/x", "k", 1)).toBe("unavailable");
+ sink.stop("r3");
+ sink.end("r3", false);
+ expect(sink.inbox.hasNew()).toBe(false);
+ expect(lines).toHaveLength(1);
+ expect(lines[0]).toContain("hook injection dropped");
+ });
+
+ test("noteSessionId reaches every listener until it unsubscribes", () => {
+ const sink = new InProcessSink();
+ const seen: string[] = [];
+ const off = sink.onSessionId((s) => seen.push(s));
+ sink.noteSessionId("a");
+ off();
+ sink.noteSessionId("b");
+ expect(seen).toEqual(["a"]);
+ });
+});
+
+describe("sinkFromEnv with a process sink", () => {
+ test("no inbox env: the installed process sink, else unavailable", () => {
+ expect(sinkFromEnv({})).toBeInstanceOf(UnavailableSink);
+ const sink = new InProcessSink();
+ setProcessSink(sink);
+ expect(sinkFromEnv({})).toBe(sink);
+ setProcessSink(null);
+ expect(sinkFromEnv({})).toBeInstanceOf(UnavailableSink);
+ });
+
+ test("a pane owner's inbox file still wins over a process sink", () => {
+ const inProcess = new InProcessSink();
+ setProcessSink(inProcess);
+ const env = { [HOOK_INBOX_ENV]: "/tmp/never-written-inbox.jsonl" };
+ expect(sinkFromEnv({ ...env, CLAUDISH_PANE_CHILD: "1" })).toBeInstanceOf(InboxFileSink);
+ // outside a pane child the variable is not an owner's: the process sink stays
+ expect(sinkFromEnv(env)).toBe(inProcess);
+ });
+});
diff --git a/packages/cli/src/hooks/injection/sinks.ts b/packages/cli/src/hooks/injection/sinks.ts
index 664e9a8a..4311f89c 100644
--- a/packages/cli/src/hooks/injection/sinks.ts
+++ b/packages/cli/src/hooks/injection/sinks.ts
@@ -8,16 +8,20 @@
* named it in `CLAUDISH_HOOK_INBOX`; every line is one synchronous append, so
* a `stop` written before the `message_stop` chunk is enqueued is on disk
* before Claude Code can read that chunk.
+ * - `InProcessSink`: the interactive launcher, where the proxy and the
+ * session driver share one process. The same lines go to a `MemoryInbox`
+ * the driver's binding drains with the owner's rule, so `stop` before
+ * `message_stop` and the bounded wait for `end` hold exactly as in a pane.
* - `UnavailableSink`: no session driver in this process (`serve`, the MCP
* server's own proxy, a no-surface interactive launch). Injections and
* annotations are dropped `unavailable`.
- *
- * The in-process sink of the interactive launcher arrives with its driver.
*/
import { appendFileSync } from "node:fs";
import { log, logStderr } from "../../logger.js";
+import { isPaneChild } from "../../pane/child-env.js";
import type { JsonValue } from "../public.js";
+import { type InboxLine, MemoryInbox } from "./inbox.js";
/** The pane-child env var naming the owner-created inbox file. */
export const HOOK_INBOX_ENV = "CLAUDISH_HOOK_INBOX";
@@ -37,6 +41,12 @@ export interface InjectionSink {
annotate(req: string, hookId: string, key: string, value: JsonValue): SinkOutcome;
/** Every `responseEnd` hook of `req` resolved or timed out, or the stream was aborted. */
end(req: string, aborted: boolean): void;
+ /**
+ * The Claude Code session id a proxy request carried. Only the interactive
+ * launcher's sink listens: it is how its driver follows `/clear` and learns the
+ * session of a `--resume`d launch (§7.5).
+ */
+ noteSessionId?(sessionId: string): void;
}
/** A pane child's sink: one JSON object per line, appended synchronously. */
@@ -110,6 +120,16 @@ export class InboxFileSink implements InjectionSink {
let unavailableReported = false;
+/**
+ * Report, once per process, that an injection could not be delivered: there is no
+ * Claude Code session this process can type into (§4.7 rule 8).
+ */
+export function reportInjectionUnavailable(warn: (line: string) => void = logStderr): void {
+ if (unavailableReported) return;
+ unavailableReported = true;
+ warn("hook injection dropped: this claudish process has no Claude Code session to deliver it to");
+}
+
/** No session driver: injections are dropped, with one stderr line per process. */
export class UnavailableSink implements InjectionSink {
readonly available = false;
@@ -120,12 +140,7 @@ export class UnavailableSink implements InjectionSink {
end(): void {}
inject(): SinkOutcome {
- if (!unavailableReported) {
- unavailableReported = true;
- this.warn(
- "hook injection dropped: this claudish process has no Claude Code session to deliver it to"
- );
- }
+ reportInjectionUnavailable(this.warn);
return "unavailable";
}
@@ -139,16 +154,123 @@ export function resetUnavailableSinkReportForTests(): void {
unavailableReported = false;
}
+/**
+ * The interactive launcher's sink (§2.3, last paragraph). It appends the same lines a
+ * pane child writes to its inbox file, in memory, under the same payload cap; the
+ * driver's binding drains them with the same rule. `available` turns false when the
+ * driver has no pane to type into (an ambient session whose pane was not found, or a
+ * driver that stopped), and injections are then dropped `unavailable`.
+ */
+export class InProcessSink implements InjectionSink {
+ readonly inbox = new MemoryInbox();
+ private payloadBytes = 0;
+ private capped = false;
+ private open = true;
+ private sessionListeners = new Set<(sessionId: string) => void>();
+
+ constructor(
+ private readonly capBytes: number = INBOX_PAYLOAD_CAP_BYTES,
+ private readonly now: () => Date = () => new Date(),
+ private readonly warn: (line: string) => void = logStderr
+ ) {}
+
+ get available(): boolean {
+ return this.open;
+ }
+
+ /** No driver will drain this sink: later injections are dropped `unavailable`. */
+ markUnavailable(): void {
+ this.open = false;
+ }
+
+ stop(req: string): void {
+ // With no driver to drain them, bookkeeping lines would only accumulate.
+ if (this.open) this.inbox.append({ v: 1, kind: "stop", req });
+ }
+
+ inject(req: string, hookId: string, text: string): SinkOutcome {
+ if (!this.open) {
+ reportInjectionUnavailable(this.warn);
+ return "unavailable";
+ }
+ return this.payload({ v: 1, kind: "inject", req, hookId, text, at: this.now().toISOString() });
+ }
+
+ annotate(req: string, hookId: string, key: string, value: JsonValue): SinkOutcome {
+ if (!this.open) return "unavailable";
+ return this.payload({
+ v: 1,
+ kind: "annotate",
+ req,
+ hookId,
+ key,
+ value,
+ at: this.now().toISOString(),
+ });
+ }
+
+ end(req: string, aborted: boolean): void {
+ if (!this.open) return;
+ this.inbox.append(
+ aborted ? { v: 1, kind: "end", req, aborted: true } : { v: 1, kind: "end", req }
+ );
+ }
+
+ noteSessionId(sessionId: string): void {
+ for (const fn of this.sessionListeners) {
+ try {
+ fn(sessionId);
+ } catch {
+ // a listener's failure never reaches the request
+ }
+ }
+ }
+
+ /** Called with every session id a proxy request carries. Returns the unsubscribe. */
+ onSessionId(fn: (sessionId: string) => void): () => void {
+ this.sessionListeners.add(fn);
+ return () => this.sessionListeners.delete(fn);
+ }
+
+ private payload(line: InboxLine): SinkOutcome {
+ if (this.capped) return "inbox_cap";
+ const bytes = Buffer.byteLength(`${JSON.stringify(line)}\n`);
+ if (this.payloadBytes + bytes > this.capBytes) {
+ this.capped = true;
+ this.inbox.append({ v: 1, kind: "capped" });
+ return "inbox_cap";
+ }
+ this.payloadBytes += bytes;
+ this.inbox.append(line);
+ return "queued";
+ }
+}
+
+/** The interactive launcher's sink, when one is installed (`setProcessSink`). */
+let processSink: InjectionSink | null = null;
+
+/**
+ * Install the sink every proxy request of this process uses when no pane owner named an
+ * inbox. The interactive launcher installs its `InProcessSink` before Claude Code starts,
+ * so its first request already reports to the driver. `null` uninstalls.
+ */
+export function setProcessSink(sink: InjectionSink | null): void {
+ processSink = sink;
+}
+
/** One sink per inbox file, so the payload cap counts the whole file, not one request. */
const inboxSinks = new Map<string, InboxFileSink>();
/**
- * The sink for this process: the inbox a pane owner named, or none. The proxy
- * builds its per-request hooks often; every one of them shares the file's sink.
+ * The sink for this process: the inbox a pane owner named, the launcher's in-process
+ * sink, or none. The proxy builds its per-request hooks often; every one of them
+ * shares the same sink. Only a pane child has an owner-created inbox, so the variable
+ * is ignored anywhere else. Neither it nor the pane marker can come from a cwd env
+ * file: both are control variables (`launch-env.ts`), set only by the owner's spawn.
*/
export function sinkFromEnv(env: NodeJS.ProcessEnv = process.env): InjectionSink {
- const path = env[HOOK_INBOX_ENV];
- if (!path) return new UnavailableSink();
+ const path = isPaneChild(env) ? env[HOOK_INBOX_ENV] : undefined;
+ if (!path) return processSink ?? new UnavailableSink();
let sink = inboxSinks.get(path);
if (!sink) {
sink = new InboxFileSink(path);