MCPcopy Create free account
hub / github.com/cli/cli / writeGhWrapper

Function writeGhWrapper

evals/src/core/observer.ts:92–163  ·  view source on GitHub ↗
(path: string, binary: string, socket: string)

Source from the content-addressed store, hash-verified

90}
91
92export async function writeGhWrapper(path: string, binary: string, socket: string): Promise<void> {
93 await writeFile(path, `#!${process.execPath}
94const { spawn } = require("node:child_process");
95const { connect } = require("node:net");
96const { randomUUID } = require("node:crypto");
97const { Transform } = require("node:stream");
98const { pipeline } = require("node:stream/promises");
99const { StringDecoder } = require("node:string_decoder");
100const id = "gh:" + randomUUID();
101function report(message) {
102 return new Promise((resolve, reject) => {
103 const socket = connect(${JSON.stringify(socket)});
104 socket.setTimeout(5000, () => socket.destroy(new Error("Observer timed out")));
105 socket.on("error", reject);
106 let reply = "";
107 socket.on("data", data => { reply += data; });
108 socket.on("end", () => reply === "ok\\n" ? resolve() : reject(new Error("Observer rejected command")));
109 socket.on("connect", () => socket.write(JSON.stringify({ ...message, id }) + "\\n"));
110 });
111}
112function forward(source, destination, stream) {
113 const decoder = new StringDecoder("utf8");
114 return pipeline(source, new Transform({
115 transform(chunk, _encoding, callback) {
116 const text = decoder.write(chunk);
117 (text ? report({ type: "output", stream, text }) : Promise.resolve())
118 .then(() => callback(null, chunk), callback);
119 },
120 flush(callback) {
121 const text = decoder.end();
122 (text ? report({ type: "output", stream, text }) : Promise.resolve())
123 .then(() => callback(), callback);
124 }
125 }), destination, { end: false });
126}
127(async () => {
128 const args = process.argv.slice(2);
129 const child = spawn(${JSON.stringify(binary)}, args, { stdio: ["inherit", "pipe", "pipe"], env: process.env });
130 const completion = new Promise(resolve => {
131 child.on("error", error => resolve({ error }));
132 child.on("close", (code, signal) => resolve({ code, signal }));
133 });
134 const forwards = new Map();
135 for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {
136 const forward = () => { if (child.pid) child.kill(signal); };
137 forwards.set(signal, forward);
138 process.on(signal, forward);
139 }
140 await report({ type: "start", args });
141 let forwardingError;
142 const forwarding = Promise.allSettled([
143 forward(child.stdout, process.stdout, "stdout"),
144 forward(child.stderr, process.stderr, "stderr")
145 ].map(pending => pending.catch(error => {
146 forwardingError ??= error;
147 child.kill("SIGTERM");
148 throw error;
149 })));

Callers 3

observedProcessFunction · 0.85
harness.test.tsFile · 0.85
prepareHomeFunction · 0.85

Calls 1

writeFileFunction · 0.50

Tested by 1

observedProcessFunction · 0.68