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
5 changes: 5 additions & 0 deletions .changeset/fix-reply-to-local-lineage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"sessionpipe": patch
---

Fix control daemon `reply_to` lineage leak when `reply_to` is not placed on this machine (#331): only set `SESSIONPIPE_ASKED_BY` (`delegated_by`) and `SESSIONPIPE_ASK_CHAIN` in child processes when the daemon actually placed `reply_to` locally (`handoffs`), matching `spec/CONTROL.md` §6 ("no handoff at all").
25 changes: 15 additions & 10 deletions packages/cli/src/control/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3620,7 +3620,7 @@ export class ControlDaemon {
target,
o,
recorded,
this.childEnv(r, cmd),
this.childEnv(r, id),
drv.live && {
refused: (res) => (drv.live as NonNullable<Driver["live"]>).refused(res, target),
instead: () => this.queueLive(r, id, cmd, drv, ready.bin, target, sent),
Expand Down Expand Up @@ -3982,7 +3982,7 @@ export class ControlDaemon {
CLAUDE_CODE_RESUME_SOURCE_ALIVE: `${target}|${new Date(this.deps.now()).toISOString()}|${target}`,
}
: {}),
...this.childEnv(r, cmd),
...this.childEnv(r, id),
},
timeoutMs: JOB_TIMEOUT_MS,
...(claude.caps.stream
Expand Down Expand Up @@ -4449,7 +4449,7 @@ export class ControlDaemon {
// A session the daemon will hold: from here a Stop is that session's interrupt.
this.letGo(run);
const sdk = this.deps.sdk;
const extra = this.childEnv(r, cmd);
const extra = this.childEnv(r, id);
const out = await this.slot(async () => {
const s = sdk.start({
session: ref.id,
Expand Down Expand Up @@ -4488,7 +4488,7 @@ export class ControlDaemon {
this.picturesSaid(id, got.pictures.length, 0, "claude -p takes none; Claude Code opens them");
const res = await this.ownRun(run, c.bin, args, {
cwd,
env: { ...claudeEnv(undefined, this.deps.env), ...this.childEnv(r, cmd) },
env: { ...claudeEnv(undefined, this.deps.env), ...this.childEnv(r, id) },
timeoutMs: JOB_TIMEOUT_MS,
...(c.caps.stream ? { onLine: (l: string) => stream.feed(l) } : {}),
});
Expand Down Expand Up @@ -4570,7 +4570,7 @@ export class ControlDaemon {
});
this.deps.log(`${id.slice(-8)}: ${drv.cmd} new session for ${known(ref.id)} (${o.permission}) in ${cwd}`);
const both = this.withPictures(id, drv, got.pictures, args);
await this.drive(r, id, ref, drv, ready.bin, both, cwd, sent, null, o, o, this.childEnv(r, cmd));
await this.drive(r, id, ref, drv, ready.bin, both, cwd, sent, null, o, o, this.childEnv(r, id));
});
}

Expand Down Expand Up @@ -4602,7 +4602,7 @@ export class ControlDaemon {
const stream = this.answerStream(r, id);
const out = await this.slot(async () => {
const run: HeldRun = { mode: this.cfg.mode, modeEnv: found.modeEnv };
const opened = await this.openAcp(id, found, cwd, label, stream, { env: this.childEnv(r, cmd) });
const opened = await this.openAcp(id, found, cwd, label, stream, { env: this.childEnv(r, id) });
if ("failed" in opened) return { reply: "", error: opened.failed };
/* v8 ignore next -- unsupported only comes of a session/load, which a start never asks for */
if ("unsupported" in opened) return { reply: "", error: opened.unsupported };
Expand Down Expand Up @@ -4641,7 +4641,7 @@ export class ControlDaemon {
const run: HeldRun = { mode: this.cfg.mode, modeEnv: found.modeEnv };
const opened = await this.openAcp(id, found, place.folder, label, stream, {
load: target,
env: this.childEnv(r, cmd),
env: this.childEnv(r, id),
});
if ("unsupported" in opened) return { reply: "", unsupported: opened.unsupported };
if ("failed" in opened) return { reply: "", error: opened.failed };
Expand Down Expand Up @@ -4754,10 +4754,15 @@ export class ControlDaemon {

/** What a child run gets in its environment beyond the job's: its lineage, for its
* hooks to stamp `delegated_by` (§13). An ask's sink says who asked; a receiver's
* command with `reply_to` was asked, as far as the child knows, by that session (§6). */
private childEnv(r: Caller, cmd: ControlCommand): Record<string, string> {
* command with a `reply_to` this machine placed (`handoffs`) was asked, as far as the
* child knows, by that session (§6). A `reply_to` the machine could not place is no
* handoff at all, so the child carries no lineage. */
private childEnv(r: Caller, id: string): Record<string, string> {
if (isSink(r)) return r.env ?? {};
return cmd.reply_to ? { [DELEGATED_BY_ENV]: cmd.reply_to, SESSIONPIPE_ASK_CHAIN: cmd.reply_to } : {};
const h = this.handoffs.get(id);
if (!h) return {};
const by = `${h.to.harness}:${h.to.id}`;
return { [DELEGATED_BY_ENV]: by, SESSIONPIPE_ASK_CHAIN: by };
}

/** An ask's `permission` on a prompt (CONTROL.md §13; an ask always names one, safe
Expand Down
216 changes: 216 additions & 0 deletions packages/cli/test/control-ask.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -651,6 +651,8 @@ describe.runIf(unix)("a handoff (CONTROL.md §6 reply_to)", () => {
/reply_to claude-code:7b\S+ isn't a session this machine can place \(that session's folder isn't one this machine allows\); the command runs, nothing is relayed/,
);
expect(runs().map((r) => r.bin)).toEqual(["codex"]);
// No handoff at all: the child gets neither SESSIONPIPE_ASKED_BY nor SESSIONPIPE_ASK_CHAIN.
expect(runs()[0]).toMatchObject({ bin: "codex", asked_by: null, chain: null });
expect(existsSync(path.join(tmp, "state", "outbox"))).toBe(false);
// Allowed when the command arrives, not any more when the reply is ready: the started
// event went out, and ended says unsupported, as for a session no mode fits.
Expand All @@ -665,6 +667,11 @@ describe.runIf(unix)("a handoff (CONTROL.md §6 reply_to)", () => {
await until(() => events("claude-code", OTHER).length === 1);
d?.reload(cfg({ receivers: true }));
expect(await rx.waitAck(q2.id)).toMatchObject({ outcome: "delivered" });
expect(runs()[1]).toMatchObject({
bin: "codex",
asked_by: `claude-code:${OTHER}`,
chain: `claude-code:${OTHER}`,
});
const ev = await until(() => (events("claude-code", OTHER).length === 2 ? events("claude-code", OTHER) : null));
expect(ev[1]?.data).toMatchObject({ ok: true, relayed: "unsupported", error: expect.stringContaining("folder") });
});
Expand Down Expand Up @@ -1101,12 +1108,150 @@ describe.runIf(unix)("a handoff (CONTROL.md §6 reply_to): the other modes and e
expect(await rx.waitAck(q.id)).toMatchObject({ outcome: "delivered" });
expect(log.find((l) => l.includes("isn't a session this machine can place"))).toMatch(/no Claude Code session/);
expect(runs().map((r) => r.bin)).toEqual(["codex"]);
// Cross-machine or nonexistent reply_to: no handoff at all — never leak delegated_by / ask chain (#331).
expect(runs()[0]).toMatchObject({ bin: "codex", asked_by: null, chain: null });
expect(existsSync(path.join(tmp, "state", "outbox"))).toBe(false);
expect(existsSync(path.join(tmp, "state", "facts"))).toBe(false);
// Exactly one final ack, as ever: the relay's fate is never a second one.
expect(rx.acks.filter((a) => a.id === q.id && a.outcome !== "taken" && a.outcome !== "progress")).toHaveLength(1);
});

it("Claude Code start (headless and SDK) and prompt: lineage env is set only when reply_to is placed locally (#331)", {
timeout: 20_000,
}, async () => {
const REMOTE = SID.replace(/^8c/, "6a");
const NEW_UNPLACED = SID.replace(/^8c/, "1a");
const NEW_PLACED = SID.replace(/^8c/, "2b");
const TARGET = SID.replace(/^8c/, "3c");
transcript(TARGET, project);
await startDaemon({ receivers: true });

// 1. Headless Claude Code start with remote (unplaced) reply_to: no lineage, no relay.
const q1 = await rx.send({
kind: "start",
session: `claude-code:${NEW_UNPLACED}`,
cwd: project,
text: "remote start",
reply_to: `claude-code:${REMOTE}`,
});
expect(await rx.waitAck(q1.id)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(runs()[0]).toMatchObject({ bin: "claude", asked_by: null, chain: null });
expect(runs()).toHaveLength(1);
expect(existsSync(path.join(tmp, "state", "outbox"))).toBe(false);

// 2. Headless Claude Code start with placed reply_to: lineage set and answer relayed.
const q2 = await rx.send({
kind: "start",
session: `claude-code:${NEW_PLACED}`,
cwd: project,
text: "local start",
reply_to: ASKER,
});
expect(await rx.waitAck(q2.id)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(runs()[1]).toMatchObject({ bin: "claude", asked_by: ASKER, chain: ASKER });
await until(() => events("claude-code", SID).length === 2);
expect(runs()[2]).toMatchObject({ bin: "claude", asked_by: null, chain: null });

// 3. Headless prompt (resume) with remote (unplaced) reply_to: no lineage, no relay.
const before = runs().length;
const q3 = await rx.send({
session: `claude-code:${TARGET}`,
text: "remote prompt",
reply_to: `claude-code:${REMOTE}`,
});
expect(await rx.waitAck(q3.id)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(runs()[before]).toMatchObject({ bin: "claude", asked_by: null, chain: null });
expect(runs()).toHaveLength(before + 1);

// 4. Headless prompt (resume) with placed reply_to: lineage set and answer relayed.
const before2 = runs().length;
const q4 = await rx.send({
session: `claude-code:${TARGET}`,
text: "local prompt",
reply_to: ASKER,
});
expect(await rx.waitAck(q4.id)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(runs()[before2]).toMatchObject({ bin: "claude", asked_by: ASKER, chain: ASKER });
await until(() => events("claude-code", SID).length === 4);
});

it("SDK start with unplaced vs placed reply_to: env is omitted when unplaced, set when placed (#331)", {
timeout: 20_000,
}, async () => {
const REMOTE = SID.replace(/^8c/, "6a");
const SDK_UNPLACED = SID.replace(/^8c/, "4d");
const SDK_PLACED = SID.replace(/^8c/, "5e");
const seenEnv: Array<Record<string, string> | undefined> = [];
const sdk: SdkHost = {
start(o) {
seenEnv.push(o.env);
return {
busy: false,
lastUsed: Date.now(),
async send(text) {
return { reply: `sdk: ${text.split("\n")[0]}` };
},
async interrupt() {},
close() {},
};
},
};
await startDaemon({ receivers: true, extra: { sdk } });

const q1 = await rx.send({
kind: "start",
session: `claude-code:${SDK_UNPLACED}`,
cwd: project,
text: "sdk remote",
reply_to: `claude-code:${REMOTE}`,
});
expect(await rx.waitAck(q1.id)).toMatchObject({ outcome: "delivered", mode: "sdk" });
expect(seenEnv[0]).toBeUndefined();
expect(existsSync(path.join(tmp, "state", "outbox"))).toBe(false);

const q2 = await rx.send({
kind: "start",
session: `claude-code:${SDK_PLACED}`,
cwd: project,
text: "sdk local",
reply_to: ASKER,
});
expect(await rx.waitAck(q2.id)).toMatchObject({ outcome: "delivered", mode: "sdk" });
expect(seenEnv[1]).toEqual({ SESSIONPIPE_ASKED_BY: ASKER, SESSIONPIPE_ASK_CHAIN: ASKER });
await until(() => events("claude-code", SID).length === 2);
});

it("ambiguous Claude Code home for reply_to: unplaced, so no lineage env and no handoff (#331)", {
timeout: 20_000,
}, async () => {
const secondDir = path.join(tmp, "claude-config-2");
const AMBIG = SID.replace(/^8c/, "9f");
for (const dir of [configDir, secondDir]) {
const p = path.join(dir, "projects", project.replace(/[^a-zA-Z0-9]/g, "-"));
mkdirSync(p, { recursive: true });
const f = path.join(p, `${AMBIG}.jsonl`);
writeFileSync(f, `${JSON.stringify({ type: "user", cwd: project, message: { content: "hi" } })}\n`);
utimesSync(f, new Date(Date.now() - 600_000), new Date(Date.now() - 600_000));
}
const log: string[] = [];
await startDaemon({
receivers: true,
extra: { claudeDirs: () => [configDir, secondDir], log: (l) => log.push(l) },
});
const q = await rx.send({
kind: "start",
session: `codex:${RECV}`,
cwd: project,
text: "go",
reply_to: `claude-code:${AMBIG}`,
});
expect(await rx.waitAck(q.id)).toMatchObject({ outcome: "delivered" });
expect(log.find((l) => l.includes("isn't a session this machine can place"))).toMatch(/more than one Claude Code/);
expect(runs()).toHaveLength(1);
expect(runs()[0]).toMatchObject({ bin: "codex", asked_by: null, chain: null });
expect(existsSync(path.join(tmp, "state", "outbox"))).toBe(false);
});

it("a relay whose run throws: relayed failed, in its words", { timeout: 20_000 }, async () => {
await startDaemon({
receivers: true,
Expand Down Expand Up @@ -1163,6 +1308,77 @@ describe.runIf(unix)("ask coverage: the level a child runs at, and depth from a
});
});

describe("reply_to across machines (CONTROL.md §6, #331)", () => {
it("sets SESSIONPIPE_ASKED_BY and SESSIONPIPE_ASK_CHAIN only when reply_to is placed locally", async () => {
const xSock = process.platform === "win32" ? `\\\\.\\pipe\\sp-reply-to-${process.pid}-${Date.now()}` : sock;
const seen: Array<{ bin: string; env: NodeJS.ProcessEnv | undefined }> = [];
d = new ControlDaemon(cfg({ receivers: true }), path.join(tmp, "state", "control"), xSock, {
now: Date.now,
fetch,
log: () => {},
claudeDirs: () => [configDir],
claude: () => ({
bin: "claude",
caps: { hasMode: true, modes: ["default", "dontAsk"], promptsNone: false, fork: true },
}),
codex: () => "codex",
run: async (bin, args, o) => {
seen.push({ bin, env: o.env });
if (bin === "codex") {
const out =
`${JSON.stringify({ type: "thread.started", thread_id: THREAD })}\n` +
`${JSON.stringify({ type: "item.completed", item: { id: "i1", type: "agent_message", text: "ok" } })}\n`;
return { code: 0, stdout: out, stderr: "", timedOut: false };
}
const i = args.indexOf("--resume");
const j = args.indexOf("--session-id");
const sid = i >= 0 ? args[i + 1] : j >= 0 ? args[j + 1] : SID;
return {
code: 0,
stdout: JSON.stringify({ type: "result", result: "ok", session_id: sid, is_error: false }),
stderr: "",
timedOut: false,
};
},
env,
answerWaitMs: 5000,
});
await d.start();

const REMOTE = SID.replace(/^8c/, "6a");
// Unplaced reply_to (session on another computer): no lineage env, no handoff, no events.
const qRemote = await rx.send({
kind: "start",
session: `codex:${RECV}`,
cwd: project,
text: "from another machine",
reply_to: `claude-code:${REMOTE}`,
});
expect(await rx.waitAck(qRemote.id)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(seen).toHaveLength(1);
expect(seen[0]?.env?.SESSIONPIPE_ASKED_BY).toBeUndefined();
expect(seen[0]?.env?.SESSIONPIPE_ASK_CHAIN).toBeUndefined();
expect(existsSync(path.join(tmp, "state", "outbox"))).toBe(false);

// Placed reply_to (session on this machine): lineage env set, answer relayed, events emitted.
const qLocal = await rx.send({
kind: "start",
session: `codex:${SID.replace(/^8c/, "2b")}`,
cwd: project,
text: "from this machine",
reply_to: ASKER,
});
expect(await rx.waitAck(qLocal.id)).toMatchObject({ outcome: "delivered", mode: "resume" });
expect(seen[1]?.env?.SESSIONPIPE_ASKED_BY).toBe(ASKER);
expect(seen[1]?.env?.SESSIONPIPE_ASK_CHAIN).toBe(ASKER);
await until(() => events("claude-code", SID).length === 2);
// Relay child itself carries no lineage env.
expect(seen[2]?.bin).toBe("claude");
expect(seen[2]?.env?.SESSIONPIPE_ASKED_BY).toBeUndefined();
expect(seen[2]?.env?.SESSIONPIPE_ASK_CHAIN).toBeUndefined();
});
});

function parseUuid(session: string): boolean {
return UUID.test(session.slice(session.indexOf(":") + 1));
}
Loading