-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathCodexJsonRpcConnection.ts
More file actions
57 lines (46 loc) · 1.84 KB
/
Copy pathCodexJsonRpcConnection.ts
File metadata and controls
57 lines (46 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as rpc from "vscode-jsonrpc/node";
import type {MessageConnection} from "vscode-jsonrpc/node";
import type {ChildProcessWithoutNullStreams} from "node:child_process";
import {spawn} from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import {createJSONRPCReader, createJSONRPCWriter} from "./StdUtils";
export interface CodexConnection {
readonly connection: MessageConnection
readonly process: ChildProcessWithoutNullStreams;
}
export function startCodexConnection(codexPath: string, logPath?: string): CodexConnection {
const codex: ChildProcessWithoutNullStreams = process.platform === 'win32'
? spawn(`"${codexPath}" app-server`, { shell: true })
: spawn(codexPath, ['app-server']);
if (logPath) {
attachLogs(codex, logPath);
}
const reader = createJSONRPCReader(codex.stdout);
const writer = createJSONRPCWriter(codex.stdin);
let connection = rpc.createMessageConnection(reader, writer);
connection.listen();
// Terminate all current activities on process termination
codex.on("exit", _ => {
connection.dispose();
});
return {connection: connection, process: codex};
}
function attachLogs(proc: ChildProcessWithoutNullStreams, logPath: string) {
function log(message: string) {
const logDir = path.join(logPath);
if (!fs.existsSync(logDir)) fs.mkdirSync(logDir);
const logFile = path.join(logPath, "app-server.log");
const timestamp = new Date().toISOString();
fs.appendFileSync(logFile, `[${timestamp}] ${message}\n`);
}
proc.stderr.on("data", (data) => {
log("[STDERR] " + data.toString());
});
proc.stdout.on("data", (data: Buffer) => {
log("[STDOUT] " + data.toString());
});
proc.on("exit", (code) => {
log("[EXIT] " + code?.toString());
});
}