|
| 1 | +import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; |
| 2 | +import os from "node:os"; |
| 3 | +import path from "node:path"; |
| 4 | +import type { |
| 5 | + CliBackendExecuteContext, |
| 6 | + CliBackendLiveSessionHandle, |
| 7 | + CliBackendPreparedExecution, |
| 8 | +} from "openclaw/plugin-sdk/cli-backend"; |
| 9 | +import { formatErrorMessageForDisplay } from "openclaw/plugin-sdk/error-runtime"; |
| 10 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 11 | +import type { ClaudeAgentSdkSecretInput } from "./agent-sdk-process.js"; |
| 12 | +import { executeClaudeAgentSdk } from "./agent-sdk.runtime.js"; |
| 13 | +import { buildAnthropicCliBackend } from "./cli-backend.js"; |
| 14 | + |
| 15 | +const roots: string[] = []; |
| 16 | +const sessions = new Set<CliBackendLiveSessionHandle>(); |
| 17 | + |
| 18 | +const PROTOCOL_CHILD = ` |
| 19 | + import { createInterface } from "node:readline"; |
| 20 | + import { readFileSync, writeSync } from "node:fs"; |
| 21 | + const credential = process.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR |
| 22 | + ? readFileSync(3, "utf8") : ""; |
| 23 | + const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); |
| 24 | + let delayedDiagnostic = ""; |
| 25 | + createInterface({ input: process.stdin }).on("line", (line) => { |
| 26 | + const message = JSON.parse(line); |
| 27 | + if (message.type === "control_request") { |
| 28 | + send({ type: "control_response", response: { |
| 29 | + subtype: "success", request_id: message.request_id, response: {}, |
| 30 | + } }); |
| 31 | + } else if (message.type === "user") { |
| 32 | + const text = message.message.content; |
| 33 | + if (delayedDiagnostic) { |
| 34 | + writeSync(2, delayedDiagnostic); |
| 35 | + delayedDiagnostic = ""; |
| 36 | + } |
| 37 | + if (text === "fail silently") process.exit(1); |
| 38 | + if (text === "fail noisily" || text === "exit without result") { |
| 39 | + writeSync(2, "PermissionError: current turn failed " + credential + "\\n"); |
| 40 | + writeSync(2, "process environment: " + process.env.OPENCLAW_MCP_TOKEN + "\\n"); |
| 41 | + process.exit(text === "exit without result" ? 0 : 1); |
| 42 | + } |
| 43 | + if (text === "success with stderr") writeSync(2, "previous turn diagnostic\\n"); |
| 44 | + if (text === "success with delayed stderr") { |
| 45 | + delayedDiagnostic = "previous turn diagnostic " + credential + "\\n"; |
| 46 | + } |
| 47 | + send({ type: "result", subtype: "success", is_error: false, result: "ok", |
| 48 | + session_id: "synthetic-session", duration_ms: 1, duration_api_ms: 1, |
| 49 | + num_turns: 1, total_cost_usd: 0, usage: {}, modelUsage: {}, permission_denials: [], |
| 50 | + }); |
| 51 | + } |
| 52 | + }); |
| 53 | +`; |
| 54 | + |
| 55 | +afterEach(async () => { |
| 56 | + for (const session of sessions) { |
| 57 | + session.close("restart"); |
| 58 | + await session.waitForExit(); |
| 59 | + } |
| 60 | + sessions.clear(); |
| 61 | + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); |
| 62 | + vi.restoreAllMocks(); |
| 63 | +}); |
| 64 | + |
| 65 | +async function contextForChild(source: string): Promise<CliBackendExecuteContext> { |
| 66 | + const root = await mkdtemp(path.join(os.tmpdir(), "openclaw-claude-stderr-")); |
| 67 | + roots.push(root); |
| 68 | + const command = path.join(root, "claude.mjs"); |
| 69 | + await writeFile(command, source); |
| 70 | + return { |
| 71 | + command, |
| 72 | + args: [], |
| 73 | + cwd: root, |
| 74 | + env: { PATH: process.env.PATH ?? "", HOME: root, CLAUDE_CONFIG_DIR: root }, |
| 75 | + prompt: "Synthetic subprocess diagnostic probe.", |
| 76 | + systemPrompt: "Synthetic subprocess diagnostic probe.", |
| 77 | + modelId: "claude-sonnet-4-6", |
| 78 | + useResume: false, |
| 79 | + timeoutMs: 10_000, |
| 80 | + abortSignal: AbortSignal.timeout(10_000), |
| 81 | + requestToolPermission: async () => ({ behavior: "deny", message: "No tools in this probe." }), |
| 82 | + requestUserInput: async () => ({ status: "cancelled", message: "No input in this probe." }), |
| 83 | + }; |
| 84 | +} |
| 85 | + |
| 86 | +async function collect( |
| 87 | + context: CliBackendExecuteContext, |
| 88 | + secretInput?: Parameters<typeof executeClaudeAgentSdk>[1], |
| 89 | + execute = executeClaudeAgentSdk, |
| 90 | +) { |
| 91 | + const events: Record<string, unknown>[] = []; |
| 92 | + for await (const event of execute(context, secretInput)) { |
| 93 | + events.push(event); |
| 94 | + } |
| 95 | + return events; |
| 96 | +} |
| 97 | + |
| 98 | +function attachLiveSession(context: CliBackendExecuteContext) { |
| 99 | + let current: CliBackendLiveSessionHandle | undefined; |
| 100 | + context.liveSession = { |
| 101 | + fingerprint: "synthetic-process-policy", |
| 102 | + current: () => current, |
| 103 | + register: (handle) => { |
| 104 | + current = handle; |
| 105 | + sessions.add(handle); |
| 106 | + }, |
| 107 | + activate: () => {}, |
| 108 | + remove: (handle) => { |
| 109 | + if (current === handle) { |
| 110 | + current = undefined; |
| 111 | + } |
| 112 | + }, |
| 113 | + }; |
| 114 | + return () => current; |
| 115 | +} |
| 116 | + |
| 117 | +describe("Claude subprocess diagnostics through the real Agent SDK", () => { |
| 118 | + it("drains pipe-sized stderr and reports a bounded redacted fatal diagnostic", async () => { |
| 119 | + const secret = "sk-ant-api03-synthetic-diagnostic-credential-123456789"; |
| 120 | + const context = await contextForChild(` |
| 121 | + import { writeSync } from "node:fs"; |
| 122 | + writeSync(2, "discarded noise".repeat(100_000) + "\\n"); |
| 123 | + writeSync(2, "Authorization: Bear"); |
| 124 | + writeSync(2, "er ${secret}\\n"); |
| 125 | + writeSync(2, "PermissionError: [Errno 1] Operation not permitted: '/bin/ps' 🦞"); |
| 126 | + process.exit(1); |
| 127 | + `); |
| 128 | + const error = await collect(context).catch((failure: unknown) => failure); |
| 129 | + expect(error).toBeInstanceOf(Error); |
| 130 | + expect((error as Error).message).toBe("Claude Code process exited with code 1"); |
| 131 | + expect(formatErrorMessageForDisplay(error)).toContain("exited with code 1"); |
| 132 | + expect(formatErrorMessageForDisplay(error)).toContain("PermissionError: [Errno 1]"); |
| 133 | + expect(formatErrorMessageForDisplay(error)).toContain("'/bin/ps' 🦞"); |
| 134 | + expect(formatErrorMessageForDisplay(error)).not.toContain(secret); |
| 135 | + expect(formatErrorMessageForDisplay(error)).not.toContain("discarded noise"); |
| 136 | + expect(formatErrorMessageForDisplay(error).length).toBeLessThan(2_200); |
| 137 | + }); |
| 138 | + |
| 139 | + it("preserves a silent child's exit error without inventing stderr", async () => { |
| 140 | + const context = await contextForChild("process.exit(1);"); |
| 141 | + await expect(collect(context)).rejects.toThrow(/^Claude Code process exited with code 1$/); |
| 142 | + }); |
| 143 | + |
| 144 | + it("masks opaque descriptor and environment credentials without copying native stdout", async () => { |
| 145 | + const context = await contextForChild(` |
| 146 | + import { readFileSync, writeSync } from "node:fs"; |
| 147 | + writeSync(1, "native stdout must stay private\\n"); |
| 148 | + writeSync(2, "credential: " + readFileSync(3, "utf8") + "\\n"); |
| 149 | + writeSync(2, "environment: " + process.env.OPENCLAW_MCP_TOKEN + "\\n"); |
| 150 | + writeSync(2, "PermissionError: denied resource 3\\n"); |
| 151 | + process.exit(1); |
| 152 | + `); |
| 153 | + const credential = "opaque-descriptor-fixture-value"; |
| 154 | + const grant = "opaque-mcp-fixture-value"; |
| 155 | + context.env.OPENCLAW_MCP_TOKEN = grant; |
| 156 | + context.env.CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR = "3"; |
| 157 | + const buffers: Buffer[] = []; |
| 158 | + const running = collect(context, { |
| 159 | + fd: 3, |
| 160 | + createData: () => { |
| 161 | + const bytes = Buffer.from(credential); |
| 162 | + buffers.push(bytes); |
| 163 | + return bytes; |
| 164 | + }, |
| 165 | + }); |
| 166 | + const error = await running.catch((failure: unknown) => failure); |
| 167 | + expect(formatErrorMessageForDisplay(error)).toContain("PermissionError: denied resource 3"); |
| 168 | + expect(formatErrorMessageForDisplay(error)).toContain("[REDACTED]"); |
| 169 | + for (const privateText of [ |
| 170 | + credential, |
| 171 | + grant, |
| 172 | + "native stdout must stay private", |
| 173 | + context.prompt, |
| 174 | + ]) { |
| 175 | + expect(formatErrorMessageForDisplay(error)).not.toContain(privateText); |
| 176 | + } |
| 177 | + expect(buffers.length).toBeGreaterThan(0); |
| 178 | + expect(buffers.every((bytes) => bytes.every((byte) => byte === 0))).toBe(true); |
| 179 | + }); |
| 180 | + |
| 181 | + it("reports failure while a descendant still holds stderr open", async () => { |
| 182 | + const context = await contextForChild(` |
| 183 | + import { spawn } from "node:child_process"; |
| 184 | + import { writeFileSync, writeSync } from "node:fs"; |
| 185 | + const descendant = spawn(process.execPath, ["-e", "setTimeout(() => {}, 10000)"], |
| 186 | + { stdio: ["ignore", "ignore", 2] }); |
| 187 | + writeFileSync("descendant.pid", String(descendant.pid)); |
| 188 | + writeSync(2, "PermissionError: parent exited\\n"); |
| 189 | + process.exit(1); |
| 190 | + `); |
| 191 | + try { |
| 192 | + const error = await collect(context).catch((failure: unknown) => failure); |
| 193 | + expect(formatErrorMessageForDisplay(error)).toContain("PermissionError: parent exited"); |
| 194 | + const pid = Number(await readFile(path.join(context.cwd, "descendant.pid"), "utf8")); |
| 195 | + expect(() => process.kill(pid, 0)).not.toThrow(); |
| 196 | + } finally { |
| 197 | + const pid = Number(await readFile(path.join(context.cwd, "descendant.pid"), "utf8")); |
| 198 | + try { |
| 199 | + process.kill(pid, "SIGKILL"); |
| 200 | + } catch {} |
| 201 | + } |
| 202 | + }); |
| 203 | + |
| 204 | + it.each(["success", "success with stderr"])("keeps %s quiet", async (prompt) => { |
| 205 | + const context = await contextForChild(PROTOCOL_CHILD); |
| 206 | + const stderr = vi.spyOn(process.stderr, "write"); |
| 207 | + const events = await collect({ ...context, prompt }); |
| 208 | + expect(events).toContainEqual(expect.objectContaining({ type: "result", result: "ok" })); |
| 209 | + expect(stderr).not.toHaveBeenCalled(); |
| 210 | + }); |
| 211 | + |
| 212 | + it("keeps diagnostics isolated between live processes", async () => { |
| 213 | + const warm = await contextForChild(PROTOCOL_CHILD); |
| 214 | + attachLiveSession(warm); |
| 215 | + await collect({ ...warm, prompt: "success with stderr" }); |
| 216 | + const other = await contextForChild("process.exit(1);"); |
| 217 | + attachLiveSession(other); |
| 218 | + await expect(collect(other)).rejects.toThrow(/^Claude Code process exited with code 1$/); |
| 219 | + const error = await collect({ ...warm, prompt: "fail silently" }).catch( |
| 220 | + (failure: unknown) => failure, |
| 221 | + ); |
| 222 | + expect(formatErrorMessageForDisplay(error)).toContain( |
| 223 | + "stderr (process-wide; may include earlier turns): previous turn diagnostic", |
| 224 | + ); |
| 225 | + }); |
| 226 | + |
| 227 | + it.each([ |
| 228 | + { firstPrompt: "success with stderr", prompt: "fail silently" }, |
| 229 | + { firstPrompt: "success with stderr", prompt: "fail noisily" }, |
| 230 | + { firstPrompt: "success with stderr", prompt: "close idle" }, |
| 231 | + { firstPrompt: "success with delayed stderr", prompt: "fail silently" }, |
| 232 | + { firstPrompt: "success with stderr", prompt: "exit without result" }, |
| 233 | + ])( |
| 234 | + "retains process diagnostics after credential cleanup: $firstPrompt then $prompt", |
| 235 | + async ({ firstPrompt, prompt }) => { |
| 236 | + const context = await contextForChild(PROTOCOL_CHILD); |
| 237 | + const credential = "opaque-warm-credential-fixture"; |
| 238 | + const processGrant = "opaque-first-process-grant-fixture"; |
| 239 | + const backend = buildAnthropicCliBackend(); |
| 240 | + const prepare = async () => { |
| 241 | + // The descriptor is a provider-private field, outside the public SDK result type. |
| 242 | + const prepared = (await backend.prepareExecution?.({ |
| 243 | + workspaceDir: context.cwd, |
| 244 | + provider: "claude-cli", |
| 245 | + modelId: context.modelId, |
| 246 | + executionMode: "agent", |
| 247 | + authCredential: { type: "token", token: credential }, |
| 248 | + } as Parameters<NonNullable<typeof backend.prepareExecution>>[0])) as |
| 249 | + | (CliBackendPreparedExecution & { secretInput?: ClaudeAgentSdkSecretInput }) |
| 250 | + | undefined; |
| 251 | + if (!prepared?.execute || !prepared.secretInput || !prepared.cleanup) { |
| 252 | + throw new Error("Expected a managed Claude SDK execution."); |
| 253 | + } |
| 254 | + return { |
| 255 | + ...prepared, |
| 256 | + execute: prepared.execute, |
| 257 | + secretInput: prepared.secretInput, |
| 258 | + cleanup: prepared.cleanup, |
| 259 | + }; |
| 260 | + }; |
| 261 | + const current = attachLiveSession(context); |
| 262 | + const stderr = vi.spyOn(process.stderr, "write"); |
| 263 | + const first = await prepare(); |
| 264 | + const buffers: Buffer[] = []; |
| 265 | + const createData = first.secretInput.createData; |
| 266 | + vi.spyOn(first.secretInput, "createData").mockImplementation(() => { |
| 267 | + const bytes = createData(); |
| 268 | + buffers.push(bytes); |
| 269 | + return bytes; |
| 270 | + }); |
| 271 | + await expect( |
| 272 | + collect( |
| 273 | + { |
| 274 | + ...context, |
| 275 | + env: { ...context.env, ...first.env, OPENCLAW_MCP_TOKEN: processGrant }, |
| 276 | + prompt: firstPrompt, |
| 277 | + }, |
| 278 | + undefined, |
| 279 | + first.execute, |
| 280 | + ), |
| 281 | + ).resolves.toContainEqual(expect.objectContaining({ result: "ok" })); |
| 282 | + await first.cleanup(); |
| 283 | + expect(() => first.secretInput.createData()).toThrow("no longer available"); |
| 284 | + expect(current()?.isIdle()).toBe(true); |
| 285 | + if (prompt === "close idle") { |
| 286 | + const closing = current(); |
| 287 | + closing?.close("idle"); |
| 288 | + await closing?.waitForExit(); |
| 289 | + } else { |
| 290 | + const second = await prepare(); |
| 291 | + const error = await collect( |
| 292 | + { |
| 293 | + ...context, |
| 294 | + env: { ...context.env, ...second.env, OPENCLAW_MCP_TOKEN: "opaque-next-grant-fixture" }, |
| 295 | + prompt, |
| 296 | + useResume: true, |
| 297 | + }, |
| 298 | + undefined, |
| 299 | + second.execute, |
| 300 | + ).catch((failure: unknown) => failure); |
| 301 | + await second.cleanup(); |
| 302 | + expect(formatErrorMessageForDisplay(error)).toContain( |
| 303 | + prompt === "exit without result" |
| 304 | + ? "live session exited unexpectedly" |
| 305 | + : "exited with code 1", |
| 306 | + ); |
| 307 | + expect(formatErrorMessageForDisplay(error)).toContain( |
| 308 | + "stderr (process-wide; may include earlier turns):", |
| 309 | + ); |
| 310 | + expect(formatErrorMessageForDisplay(error)).toContain("previous turn diagnostic"); |
| 311 | + expect(formatErrorMessageForDisplay(error)).not.toContain(credential); |
| 312 | + expect(formatErrorMessageForDisplay(error)).not.toContain(processGrant); |
| 313 | + expect( |
| 314 | + formatErrorMessageForDisplay(error).includes("PermissionError: current turn failed"), |
| 315 | + ).toBe(prompt === "fail noisily" || prompt === "exit without result"); |
| 316 | + } |
| 317 | + expect(buffers.length).toBeGreaterThan(0); |
| 318 | + expect(buffers.every((bytes) => bytes.every((byte) => byte === 0))).toBe(true); |
| 319 | + expect(stderr).not.toHaveBeenCalled(); |
| 320 | + }, |
| 321 | + ); |
| 322 | +}); |
0 commit comments