import { chmod, mkdtemp, readFile, writeFile } from 'node:fs/promises'; import { spawn } from 'node:child_process'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; function waitForExit(child, timeoutMs = 1500) { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { child.kill('SIGKILL'); reject(new Error(`wrapper did not exit within ${timeoutMs}ms`)); }, timeoutMs); child.on('error', (error) => { clearTimeout(timeout); reject(error); }); child.on('close', (code) => { clearTimeout(timeout); resolve(code ?? 0); }); }); } async function runWrapperWithFakePi(requestedModel) { const dir = await mkdtemp(join(tmpdir(), 'pi-subagents-wrapper-')); const metaPath = join(dir, 'meta.json'); const resultPath = join(dir, 'result.json'); const capturePath = join(dir, 'capture.json'); const piPath = join(dir, 'pi'); const resolved = requestedModel; await writeFile( piPath, [ `#!${process.execPath}`, "const fs = require('fs');", `const capturePath = ${JSON.stringify(capturePath)};`, "const obj = {", " PI_SUBAGENTS_GITHUB_COPILOT_INITIATOR: process.env.PI_SUBAGENTS_GITHUB_COPILOT_INITIATOR || '',", " PI_SUBAGENTS_CHILD: process.env.PI_SUBAGENTS_CHILD || '',", " argv: process.argv.slice(2)", "};", "fs.writeFileSync(capturePath, JSON.stringify(obj), 'utf8');", "console.log(JSON.stringify({type:'message_end',message:{role:'assistant',content:[{type:'text',text:'done'}],model:'github-copilot/gpt-4o',stopReason:'stop'}}));", ].join('\n'), 'utf8', ); await chmod(piPath, 0o755); await writeFile( metaPath, JSON.stringify( { runId: 'run-1', mode: 'single', task: 'inspect auth', cwd: dir, requestedModel, resolvedModel: resolved, startedAt: '2026-04-09T00:00:00.000Z', sessionPath: join(dir, 'child-session.jsonl'), eventsPath: join(dir, 'events.jsonl'), resultPath, stdoutPath: join(dir, 'stdout.log'), stderrPath: join(dir, 'stderr.log'), transcriptPath: join(dir, 'transcript.log'), tools: ['read', 'grep'], systemPromptPath: join(dir, 'system-prompt.md'), }, null, 2, ), 'utf8', ); const wrapperPath = join(dirname(fileURLToPath(import.meta.url)), 'src/wrapper/cli.mjs'); const child = spawn(process.execPath, [wrapperPath, metaPath], { env: { ...process.env, PATH: dir, }, stdio: ['ignore', 'pipe', 'pipe'], }); const exitCode = await waitForExit(child); console.log('exitCode', exitCode); const captureJson = JSON.parse(await readFile(capturePath, 'utf8')); return { flags: captureJson }; } (async () => { try { const captured = await runWrapperWithFakePi('github-copilot/gpt-4o'); console.log('captured', captured); } catch (err) { console.error('error', err); process.exit(1); } })();