longtable 0.1.1 → 0.1.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/longtable.mjs +165 -156
- package/package.json +1 -1
- package/src/autostart.mjs +115 -110
- package/src/claude.mjs +156 -118
- package/src/codex.mjs +154 -151
- package/src/repo.mjs +208 -67
- package/src/run.mjs +735 -300
package/src/claude.mjs
CHANGED
|
@@ -1,118 +1,156 @@
|
|
|
1
|
-
// Claude Code on this computer: where it is, its own sign-in for the connection, and a locked-down answer.
|
|
2
|
-
|
|
3
|
-
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
4
|
-
import { existsSync, readdirSync } from "node:fs";
|
|
5
|
-
import { homedir } from "node:os";
|
|
6
|
-
import { delimiter, join } from "node:path";
|
|
7
|
-
import { loadSecret, log } from "./store.mjs";
|
|
8
|
-
|
|
9
|
-
const isWindows = process.platform === "win32";
|
|
10
|
-
const exe = isWindows ? "claude.exe" : "claude";
|
|
11
|
-
|
|
12
|
-
function byVersionDesc(a, b) {
|
|
13
|
-
const pa = a.split(".").map(Number);
|
|
14
|
-
const pb = b.split(".").map(Number);
|
|
15
|
-
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pb[i] - pa[i];
|
|
16
|
-
return 0;
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
// PATH, then the native installer, then the copy bundled with Claude Desktop on Windows.
|
|
20
|
-
export function findClaude() {
|
|
21
|
-
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
22
|
-
if (dir && existsSync(join(dir, exe))) return join(dir, exe);
|
|
23
|
-
}
|
|
24
|
-
const native = join(homedir(), ".local", "bin", exe);
|
|
25
|
-
if (existsSync(native)) return native;
|
|
26
|
-
if (isWindows) {
|
|
27
|
-
const root = join(process.env.APPDATA || "", "Claude", "claude-code");
|
|
28
|
-
if (existsSync(root)) {
|
|
29
|
-
const versions = readdirSync(root).filter((v) => /^\d+\.\d+\.\d+$/.test(v)).sort(byVersionDesc);
|
|
30
|
-
for (const v of versions) {
|
|
31
|
-
for (const h of readdirSync(join(root, v))) {
|
|
32
|
-
const p = join(root, v, h, exe);
|
|
33
|
-
if (existsSync(p)) return p;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
return null;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// A clean environment: only what the operating system needs, plus the connection's own sign-in.
|
|
42
|
-
// Nothing from the parent process leaks in: no API keys, no settings from whatever started the connection.
|
|
43
|
-
// apiKey is only for the evals in CI, on the owner's own key; a person's connection always uses their own sign-in.
|
|
44
|
-
export function childEnv(token, apiKey) {
|
|
45
|
-
const keep = ["PATH", "Path", "PATHEXT", "SYSTEMROOT", "SystemRoot", "WINDIR", "COMSPEC", "TEMP", "TMP",
|
|
46
|
-
"USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", "HOME", "USER", "LANG", "SHELL"];
|
|
47
|
-
const env = {};
|
|
48
|
-
for (const k of keep) if (process.env[k] !== undefined) env[k] = process.env[k];
|
|
49
|
-
if (token) env.CLAUDE_CODE_OAUTH_TOKEN = token;
|
|
50
|
-
if (apiKey) env.ANTHROPIC_API_KEY = apiKey;
|
|
51
|
-
return env;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
// A token only counts once a one-word request goes through with it.
|
|
55
|
-
export function tokenWorks(claude, token) {
|
|
56
|
-
const r = spawnSync(claude, ["-p", "Reply with the word OK", "--output-format", "json", "--model", "haiku",
|
|
57
|
-
"--max-turns", "1", "--restricted", "--permission-mode", "dontAsk", "--tools", ""], {
|
|
58
|
-
env: childEnv(token), windowsHide: true, timeout: 120000,
|
|
59
|
-
});
|
|
60
|
-
try {
|
|
61
|
-
return JSON.parse(r.stdout.toString()).is_error === false;
|
|
62
|
-
} catch {
|
|
63
|
-
return false;
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export function claudeVersion(claude) {
|
|
68
|
-
return execFileSync(claude, ["--version"], { windowsHide: true, env: childEnv(null) }).toString().trim();
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
// Answer one job, locked down: read and search the clean copy only. No commands, no edits, no network tools, none
|
|
72
|
-
// of the person's own settings, and no MCP servers. The prompt goes in through stdin, so a long table history never
|
|
73
|
-
// hits the command-line length limit. With a schema, the result carries `structured_output`.
|
|
74
|
-
// A client's AI gets no tools at all (tools ""): it only reads what the job hands it.
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
//
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
if (
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
child
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
1
|
+
// Claude Code on this computer: where it is, its own sign-in for the connection, and a locked-down answer.
|
|
2
|
+
|
|
3
|
+
import { execFileSync, spawn, spawnSync } from "node:child_process";
|
|
4
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
5
|
+
import { homedir } from "node:os";
|
|
6
|
+
import { delimiter, join } from "node:path";
|
|
7
|
+
import { loadSecret, log } from "./store.mjs";
|
|
8
|
+
|
|
9
|
+
const isWindows = process.platform === "win32";
|
|
10
|
+
const exe = isWindows ? "claude.exe" : "claude";
|
|
11
|
+
|
|
12
|
+
function byVersionDesc(a, b) {
|
|
13
|
+
const pa = a.split(".").map(Number);
|
|
14
|
+
const pb = b.split(".").map(Number);
|
|
15
|
+
for (let i = 0; i < 3; i++) if (pa[i] !== pb[i]) return pb[i] - pa[i];
|
|
16
|
+
return 0;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// PATH, then the native installer, then the copy bundled with Claude Desktop on Windows.
|
|
20
|
+
export function findClaude() {
|
|
21
|
+
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
22
|
+
if (dir && existsSync(join(dir, exe))) return join(dir, exe);
|
|
23
|
+
}
|
|
24
|
+
const native = join(homedir(), ".local", "bin", exe);
|
|
25
|
+
if (existsSync(native)) return native;
|
|
26
|
+
if (isWindows) {
|
|
27
|
+
const root = join(process.env.APPDATA || "", "Claude", "claude-code");
|
|
28
|
+
if (existsSync(root)) {
|
|
29
|
+
const versions = readdirSync(root).filter((v) => /^\d+\.\d+\.\d+$/.test(v)).sort(byVersionDesc);
|
|
30
|
+
for (const v of versions) {
|
|
31
|
+
for (const h of readdirSync(join(root, v))) {
|
|
32
|
+
const p = join(root, v, h, exe);
|
|
33
|
+
if (existsSync(p)) return p;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// A clean environment: only what the operating system needs, plus the connection's own sign-in.
|
|
42
|
+
// Nothing from the parent process leaks in: no API keys, no settings from whatever started the connection.
|
|
43
|
+
// apiKey is only for the evals in CI, on the owner's own key; a person's connection always uses their own sign-in.
|
|
44
|
+
export function childEnv(token, apiKey) {
|
|
45
|
+
const keep = ["PATH", "Path", "PATHEXT", "SYSTEMROOT", "SystemRoot", "WINDIR", "COMSPEC", "TEMP", "TMP",
|
|
46
|
+
"USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "PROGRAMDATA", "HOME", "USER", "LANG", "SHELL"];
|
|
47
|
+
const env = {};
|
|
48
|
+
for (const k of keep) if (process.env[k] !== undefined) env[k] = process.env[k];
|
|
49
|
+
if (token) env.CLAUDE_CODE_OAUTH_TOKEN = token;
|
|
50
|
+
if (apiKey) env.ANTHROPIC_API_KEY = apiKey;
|
|
51
|
+
return env;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// A token only counts once a one-word request goes through with it.
|
|
55
|
+
export function tokenWorks(claude, token) {
|
|
56
|
+
const r = spawnSync(claude, ["-p", "Reply with the word OK", "--output-format", "json", "--model", "haiku",
|
|
57
|
+
"--max-turns", "1", "--restricted", "--permission-mode", "dontAsk", "--tools", ""], {
|
|
58
|
+
env: childEnv(token), windowsHide: true, timeout: 120000,
|
|
59
|
+
});
|
|
60
|
+
try {
|
|
61
|
+
return JSON.parse(r.stdout.toString()).is_error === false;
|
|
62
|
+
} catch {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function claudeVersion(claude) {
|
|
68
|
+
return execFileSync(claude, ["--version"], { windowsHide: true, env: childEnv(null) }).toString().trim();
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Answer one job, locked down: read and search the clean copy only. No commands, no edits, no network tools, none
|
|
72
|
+
// of the person's own settings, and no MCP servers. The prompt goes in through stdin, so a long table history never
|
|
73
|
+
// hits the command-line length limit. With a schema, the result carries `structured_output`.
|
|
74
|
+
// A client's AI gets no tools at all (tools ""): it only reads what the job hands it.
|
|
75
|
+
// With `edit`, the file tools may also change files, still only inside the working folder and still with no commands:
|
|
76
|
+
// that is how a person's own AI does work they asked for, in the connection's copy.
|
|
77
|
+
export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,Grep,Glob", edit = false, long = false, onNote, control, apiKey, timeoutMs = 4 * 60 * 1000 }) {
|
|
78
|
+
// Work a person asked for takes as long as it takes: no time limit, and steps to match. It ends when it is done,
|
|
79
|
+
// when someone presses Stop, or when the connection itself goes away.
|
|
80
|
+
if (edit) { tools = "Read,Grep,Glob,Edit,Write"; timeoutMs = long ? 0 : 10 * 60 * 1000; }
|
|
81
|
+
const token = apiKey ? null : loadSecret("claude-token");
|
|
82
|
+
if (!token && !apiKey) return Promise.reject(new Error("This connection has no Claude sign-in yet. Run connect again."));
|
|
83
|
+
// Streamed output carries the plan's usage limits (a rate_limit_event) as well as the result.
|
|
84
|
+
const args = ["-p", "--output-format", "stream-json", "--verbose", "--restricted", "--permission-mode", edit ? "acceptEdits" : "dontAsk",
|
|
85
|
+
"--strict-mcp-config", "--max-turns", edit ? (long ? "10000" : "60") : tools ? "25" : "4", "--tools", tools];
|
|
86
|
+
if (system) args.push("--append-system-prompt", system);
|
|
87
|
+
if (schema) args.push("--json-schema", JSON.stringify(schema));
|
|
88
|
+
if (model) args.push("--model", model);
|
|
89
|
+
return new Promise((resolve, reject) => {
|
|
90
|
+
const started = Date.now();
|
|
91
|
+
const child = spawn(claude, args, { cwd, env: childEnv(token, apiKey), windowsHide: true });
|
|
92
|
+
// Output arrives a line at a time, each line one event. Only the result and the plan's limits are kept: work
|
|
93
|
+
// with no time limit would otherwise hold every file it ever read in memory.
|
|
94
|
+
let rest = "";
|
|
95
|
+
let err = "";
|
|
96
|
+
let ended = "";
|
|
97
|
+
let result = null;
|
|
98
|
+
let rate = null;
|
|
99
|
+
child.stdout.setEncoding("utf8");
|
|
100
|
+
child.stderr.setEncoding("utf8");
|
|
101
|
+
const timer = timeoutMs ? setTimeout(() => { ended = "ran out of time"; child.kill(); }, timeoutMs) : null;
|
|
102
|
+
if (control) control.kill = () => { ended = "stopped"; child.kill(); };
|
|
103
|
+
const take = (line) => {
|
|
104
|
+
if (!line.trim()) return;
|
|
105
|
+
let e;
|
|
106
|
+
try { e = JSON.parse(line); } catch { return; }
|
|
107
|
+
if (e.type === "result") result = e;
|
|
108
|
+
else if (e.type === "rate_limit_event") rate = e.rate_limit_info;
|
|
109
|
+
else if (onNote && e.type === "assistant") {
|
|
110
|
+
// A tool call says what the AI is doing right now.
|
|
111
|
+
for (const part of e.message?.content || []) {
|
|
112
|
+
if (part.type !== "tool_use") continue;
|
|
113
|
+
const file = String(part.input?.file_path || part.input?.path || "").split(/[/\\]/).pop();
|
|
114
|
+
onNote(part.name === "Edit" || part.name === "Write" ? `editing ${file}` : part.name === "Read" ? `reading ${file}` : "searching the code");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
child.stdout.on("data", (d) => {
|
|
119
|
+
rest += d;
|
|
120
|
+
let at;
|
|
121
|
+
while ((at = rest.indexOf(String.fromCharCode(10))) !== -1) {
|
|
122
|
+
const line = rest.slice(0, at);
|
|
123
|
+
rest = rest.slice(at + 1);
|
|
124
|
+
try { take(line); } catch {}
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
child.stderr.on("data", (d) => { if (err.length < 4000) err += d; });
|
|
128
|
+
child.on("error", (e) => { clearTimeout(timer); reject(e); });
|
|
129
|
+
child.on("close", (code) => {
|
|
130
|
+
clearTimeout(timer);
|
|
131
|
+
try { take(rest); } catch {}
|
|
132
|
+
if (ended) return reject(new Error(ended));
|
|
133
|
+
if (!result) {
|
|
134
|
+
log(`claude exited ${code} without a result: ${err.slice(0, 300)}`);
|
|
135
|
+
return reject(new Error("Claude Code did not answer. See the runner log."));
|
|
136
|
+
}
|
|
137
|
+
resolve({ ...result, wall_ms: Date.now() - started, limits: claudeLimits(rate) });
|
|
138
|
+
});
|
|
139
|
+
// A child that dies before it has read the whole prompt must not take the connection down with it.
|
|
140
|
+
child.stdin.on("error", () => {});
|
|
141
|
+
child.stdin.end(prompt);
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// The plan's limits as Longtable shows them: each window's use in percent and when it resets.
|
|
146
|
+
export function claudeLimits(rate) {
|
|
147
|
+
if (!rate) return null;
|
|
148
|
+
const names = { five_hour: "5-hour", seven_day: "weekly" };
|
|
149
|
+
const windows = Object.entries(rate.unifiedWindows || {}).map(([k, w]) => ({
|
|
150
|
+
// A week counted for one model alone arrives as seven_day_<model>.
|
|
151
|
+
name: names[k] || (k.startsWith("seven_day_") ? `weekly ${k.slice(10).replace(/_/g, " ")}` : k.replace(/_/g, " ")),
|
|
152
|
+
used: Math.round((w.utilization ?? 0) * 100),
|
|
153
|
+
resets: w.resetsAt ? new Date(w.resetsAt * 1000).toISOString() : null,
|
|
154
|
+
}));
|
|
155
|
+
return { ai: "claude", plan: null, status: rate.status === "rejected" ? "limited" : "allowed", windows };
|
|
156
|
+
}
|
package/src/codex.mjs
CHANGED
|
@@ -1,151 +1,154 @@
|
|
|
1
|
-
// Codex on this computer: where it is, the connection's own ChatGPT sign-in, and a locked-down answer.
|
|
2
|
-
//
|
|
3
|
-
// The connection keeps its own Codex folder (CODEX_HOME), so its sign-in and settings are its own and none of the
|
|
4
|
-
// person's Codex settings, plugins or MCP servers come in. Every tool is switched off: a client's AI only reads
|
|
5
|
-
// what the job hands it and writes a reply.
|
|
6
|
-
|
|
7
|
-
import { spawn, spawnSync } from "node:child_process";
|
|
8
|
-
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { tmpdir } from "node:os";
|
|
10
|
-
import { delimiter, join } from "node:path";
|
|
11
|
-
import { childEnv } from "./claude.mjs";
|
|
12
|
-
import { home, log } from "./store.mjs";
|
|
13
|
-
|
|
14
|
-
const isWindows = process.platform === "win32";
|
|
15
|
-
|
|
16
|
-
// Its own sign-in lives here. LONGTABLE_CODEX_HOME points tests at a signed-in folder.
|
|
17
|
-
export const codexHome = process.env.LONGTABLE_CODEX_HOME || join(home, "codex");
|
|
18
|
-
|
|
19
|
-
// OpenAI's Codex command-line tool. The desktop app's own copy cannot be run from outside it.
|
|
20
|
-
// npm puts a launcher script on PATH; it is run with this Node, so nothing goes through a shell.
|
|
21
|
-
export function findCodex() {
|
|
22
|
-
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
23
|
-
if (!dir) continue;
|
|
24
|
-
const js = join(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
|
|
25
|
-
if (existsSync(js)) return { cmd: process.execPath, pre: [js] };
|
|
26
|
-
const bin = join(dir, isWindows ? "codex.exe" : "codex");
|
|
27
|
-
if (existsSync(bin)) {
|
|
28
|
-
const real = realpathSync(bin);
|
|
29
|
-
return real.endsWith(".js") ? { cmd: process.execPath, pre: [real] } : { cmd: real, pre: [] };
|
|
30
|
-
}
|
|
31
|
-
}
|
|
32
|
-
return null;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
function env() {
|
|
36
|
-
mkdirSync(codexHome, { recursive: true });
|
|
37
|
-
return { ...childEnv(null), CODEX_HOME: codexHome };
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export function codexVersion(codex) {
|
|
41
|
-
const r = spawnSync(codex.cmd, [...codex.pre, "--version"], { env: env(), windowsHide: true });
|
|
42
|
-
return r.stdout.toString().trim();
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export function codexSignedIn(codex) {
|
|
46
|
-
const r = spawnSync(codex.cmd, [...codex.pre, "login", "status"], { env: env(), windowsHide: true, timeout: 30000 });
|
|
47
|
-
return r.status === 0 && /logged in/i.test(`${r.stdout}${r.stderr}`);
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
// Codex's own sign-in: it opens the person's browser at OpenAI and waits for them to approve.
|
|
51
|
-
export function codexSignIn(codex, { timeoutMs = 10 * 60 * 1000 } = {}) {
|
|
52
|
-
return new Promise((resolve) => {
|
|
53
|
-
const child = spawn(codex.cmd, [...codex.pre, "login"], { env: env(), windowsHide: true });
|
|
54
|
-
const timer = setTimeout(() => child.kill(), timeoutMs);
|
|
55
|
-
child.on("close", (code) => { clearTimeout(timer); resolve(code === 0 && codexSignedIn(codex)); });
|
|
56
|
-
child.on("error", () => { clearTimeout(timer); resolve(false); });
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Every tool Codex has, off. What is left is the model reading the prompt and writing the reply.
|
|
61
|
-
const OFF = ["shell_tool", "unified_exec", "apps", "plugins", "multi_agent", "image_generation", "browser_use",
|
|
62
|
-
"browser_use_external", "computer_use", "view_image", "hooks", "skill_search", "tool_suggest", "goals",
|
|
63
|
-
"in_app_browser", "remote_plugin", "workspace_dependencies", "sleep_tool", "code_mode_host"];
|
|
64
|
-
|
|
65
|
-
// Answer one job, locked down: an empty folder, read-only, no tools, nothing saved, none of the person's own
|
|
66
|
-
// settings or rules. The prompt goes in through stdin; the reply comes back shaped by the schema.
|
|
67
|
-
export function askCodex({ codex, prompt, schema, model, timeoutMs = 3 * 60 * 1000 }) {
|
|
68
|
-
const work = mkdtempSync(join(tmpdir(), "longtable-codex-"));
|
|
69
|
-
const schemaFile = join(work, "schema.json");
|
|
70
|
-
const lastFile = join(work, "last.json");
|
|
71
|
-
const room = join(work, "room");
|
|
72
|
-
mkdirSync(room);
|
|
73
|
-
writeFileSync(schemaFile, JSON.stringify(schema));
|
|
74
|
-
const args = [...codex.pre, "exec", "--json", "--ephemeral", "--skip-git-repo-check", "--ignore-user-config",
|
|
75
|
-
"--ignore-rules", "--sandbox", "read-only", "--color", "never", "-C", room,
|
|
76
|
-
"--output-schema", schemaFile, "-o", lastFile, "-c", 'web_search="disabled"'];
|
|
77
|
-
for (const f of OFF) args.push("--disable", f);
|
|
78
|
-
if (model) args.push("-m", model);
|
|
79
|
-
args.push("-");
|
|
80
|
-
return new Promise((resolve, reject) => {
|
|
81
|
-
const started = Date.now();
|
|
82
|
-
const child = spawn(codex.cmd, args, { cwd: room, env: env(), windowsHide: true });
|
|
83
|
-
let out = "";
|
|
84
|
-
let err = "";
|
|
85
|
-
const timer = setTimeout(() => child.kill(), timeoutMs);
|
|
86
|
-
child.stdout.
|
|
87
|
-
child.stderr.
|
|
88
|
-
child.on("error", (
|
|
89
|
-
child.on("
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
const
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
const
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
1
|
+
// Codex on this computer: where it is, the connection's own ChatGPT sign-in, and a locked-down answer.
|
|
2
|
+
//
|
|
3
|
+
// The connection keeps its own Codex folder (CODEX_HOME), so its sign-in and settings are its own and none of the
|
|
4
|
+
// person's Codex settings, plugins or MCP servers come in. Every tool is switched off: a client's AI only reads
|
|
5
|
+
// what the job hands it and writes a reply.
|
|
6
|
+
|
|
7
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
8
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { tmpdir } from "node:os";
|
|
10
|
+
import { delimiter, join } from "node:path";
|
|
11
|
+
import { childEnv } from "./claude.mjs";
|
|
12
|
+
import { home, log } from "./store.mjs";
|
|
13
|
+
|
|
14
|
+
const isWindows = process.platform === "win32";
|
|
15
|
+
|
|
16
|
+
// Its own sign-in lives here. LONGTABLE_CODEX_HOME points tests at a signed-in folder.
|
|
17
|
+
export const codexHome = process.env.LONGTABLE_CODEX_HOME || join(home, "codex");
|
|
18
|
+
|
|
19
|
+
// OpenAI's Codex command-line tool. The desktop app's own copy cannot be run from outside it.
|
|
20
|
+
// npm puts a launcher script on PATH; it is run with this Node, so nothing goes through a shell.
|
|
21
|
+
export function findCodex() {
|
|
22
|
+
for (const dir of (process.env.PATH || "").split(delimiter)) {
|
|
23
|
+
if (!dir) continue;
|
|
24
|
+
const js = join(dir, "node_modules", "@openai", "codex", "bin", "codex.js");
|
|
25
|
+
if (existsSync(js)) return { cmd: process.execPath, pre: [js] };
|
|
26
|
+
const bin = join(dir, isWindows ? "codex.exe" : "codex");
|
|
27
|
+
if (existsSync(bin)) {
|
|
28
|
+
const real = realpathSync(bin);
|
|
29
|
+
return real.endsWith(".js") ? { cmd: process.execPath, pre: [real] } : { cmd: real, pre: [] };
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function env() {
|
|
36
|
+
mkdirSync(codexHome, { recursive: true });
|
|
37
|
+
return { ...childEnv(null), CODEX_HOME: codexHome };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function codexVersion(codex) {
|
|
41
|
+
const r = spawnSync(codex.cmd, [...codex.pre, "--version"], { env: env(), windowsHide: true });
|
|
42
|
+
return r.stdout.toString().trim();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function codexSignedIn(codex) {
|
|
46
|
+
const r = spawnSync(codex.cmd, [...codex.pre, "login", "status"], { env: env(), windowsHide: true, timeout: 30000 });
|
|
47
|
+
return r.status === 0 && /logged in/i.test(`${r.stdout}${r.stderr}`);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Codex's own sign-in: it opens the person's browser at OpenAI and waits for them to approve.
|
|
51
|
+
export function codexSignIn(codex, { timeoutMs = 10 * 60 * 1000 } = {}) {
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
const child = spawn(codex.cmd, [...codex.pre, "login"], { env: env(), windowsHide: true });
|
|
54
|
+
const timer = setTimeout(() => child.kill(), timeoutMs);
|
|
55
|
+
child.on("close", (code) => { clearTimeout(timer); resolve(code === 0 && codexSignedIn(codex)); });
|
|
56
|
+
child.on("error", () => { clearTimeout(timer); resolve(false); });
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Every tool Codex has, off. What is left is the model reading the prompt and writing the reply.
|
|
61
|
+
const OFF = ["shell_tool", "unified_exec", "apps", "plugins", "multi_agent", "image_generation", "browser_use",
|
|
62
|
+
"browser_use_external", "computer_use", "view_image", "hooks", "skill_search", "tool_suggest", "goals",
|
|
63
|
+
"in_app_browser", "remote_plugin", "workspace_dependencies", "sleep_tool", "code_mode_host"];
|
|
64
|
+
|
|
65
|
+
// Answer one job, locked down: an empty folder, read-only, no tools, nothing saved, none of the person's own
|
|
66
|
+
// settings or rules. The prompt goes in through stdin; the reply comes back shaped by the schema.
|
|
67
|
+
export function askCodex({ codex, prompt, schema, model, timeoutMs = 3 * 60 * 1000 }) {
|
|
68
|
+
const work = mkdtempSync(join(tmpdir(), "longtable-codex-"));
|
|
69
|
+
const schemaFile = join(work, "schema.json");
|
|
70
|
+
const lastFile = join(work, "last.json");
|
|
71
|
+
const room = join(work, "room");
|
|
72
|
+
mkdirSync(room);
|
|
73
|
+
writeFileSync(schemaFile, JSON.stringify(schema));
|
|
74
|
+
const args = [...codex.pre, "exec", "--json", "--ephemeral", "--skip-git-repo-check", "--ignore-user-config",
|
|
75
|
+
"--ignore-rules", "--sandbox", "read-only", "--color", "never", "-C", room,
|
|
76
|
+
"--output-schema", schemaFile, "-o", lastFile, "-c", 'web_search="disabled"'];
|
|
77
|
+
for (const f of OFF) args.push("--disable", f);
|
|
78
|
+
if (model) args.push("-m", model);
|
|
79
|
+
args.push("-");
|
|
80
|
+
return new Promise((resolve, reject) => {
|
|
81
|
+
const started = Date.now();
|
|
82
|
+
const child = spawn(codex.cmd, args, { cwd: room, env: env(), windowsHide: true });
|
|
83
|
+
let out = "";
|
|
84
|
+
let err = "";
|
|
85
|
+
const timer = setTimeout(() => child.kill(), timeoutMs);
|
|
86
|
+
child.stdout.setEncoding("utf8");
|
|
87
|
+
child.stderr.setEncoding("utf8");
|
|
88
|
+
child.stdin.on("error", () => {});
|
|
89
|
+
child.stdout.on("data", (d) => (out += d));
|
|
90
|
+
child.stderr.on("data", (d) => { if (err.length < 4000) err += d; });
|
|
91
|
+
child.on("error", (e) => { clearTimeout(timer); rmSync(work, { recursive: true, force: true }); reject(e); });
|
|
92
|
+
child.on("close", (code) => {
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
const events = out.split(/\r?\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
|
|
95
|
+
let structured = null;
|
|
96
|
+
try { structured = JSON.parse(readFileSync(lastFile, "utf8")); } catch {}
|
|
97
|
+
rmSync(work, { recursive: true, force: true });
|
|
98
|
+
if (!structured) {
|
|
99
|
+
log(`codex exited ${code} without an answer: ${err.slice(0, 300)}`);
|
|
100
|
+
return reject(new Error("Codex did not answer. See the runner log."));
|
|
101
|
+
}
|
|
102
|
+
const usage = events.filter((e) => e.type === "turn.completed").map((e) => e.usage).filter(Boolean).at(-1) || {};
|
|
103
|
+
const items = events.filter((e) => e.type === "item.started" || e.type === "item.completed").map((e) => e.item || {});
|
|
104
|
+
// Codex's own notices arrive as error items (switching its code-mode host off makes it say code mode "will
|
|
105
|
+
// fail closed"); they are logged, not counted. Anything else that is not its message or reasoning is a tool.
|
|
106
|
+
for (const i of items) if (i.type === "error") log(`codex notice: ${String(i.message || "").slice(0, 200)}`);
|
|
107
|
+
const tools = items.map((i) => i.type).filter((t) => t && !["agent_message", "reasoning", "error"].includes(t));
|
|
108
|
+
resolve({ structured_output: structured, usage, tools, wall_ms: Date.now() - started });
|
|
109
|
+
});
|
|
110
|
+
child.stdin.end(prompt);
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// The ChatGPT plan's Codex limits, read from Codex's own app server (account/rateLimits/read). Null if it does not
|
|
115
|
+
// answer within ten seconds.
|
|
116
|
+
export function codexLimits(codex) {
|
|
117
|
+
return new Promise((resolve) => {
|
|
118
|
+
const child = spawn(codex.cmd, [...codex.pre, "app-server"], { env: env(), windowsHide: true });
|
|
119
|
+
let buf = "";
|
|
120
|
+
let limits = null;
|
|
121
|
+
const done = (value) => { clearTimeout(timer); child.kill(); resolve(value); };
|
|
122
|
+
const timer = setTimeout(() => done(limits), 10000);
|
|
123
|
+
const send = (m) => child.stdin.write(JSON.stringify(m) + "\n");
|
|
124
|
+
const name = (mins) => mins === 300 ? "5-hour" : mins === 10080 ? "weekly" : mins === 43200 ? "30-day" : `${Math.round(mins / 60)}-hour`;
|
|
125
|
+
const window = (w) => w && ({ name: name(w.windowDurationMins), used: Math.round(w.usedPercent ?? 0),
|
|
126
|
+
resets: w.resetsAt ? new Date(w.resetsAt * 1000).toISOString() : null });
|
|
127
|
+
child.stdout.on("data", (d) => {
|
|
128
|
+
buf += d;
|
|
129
|
+
let i;
|
|
130
|
+
while ((i = buf.indexOf("\n")) >= 0) {
|
|
131
|
+
const line = buf.slice(0, i);
|
|
132
|
+
buf = buf.slice(i + 1);
|
|
133
|
+
let m;
|
|
134
|
+
try { m = JSON.parse(line); } catch { continue; }
|
|
135
|
+
if (m.id === 1) {
|
|
136
|
+
send({ method: "initialized" });
|
|
137
|
+
send({ method: "account/rateLimits/read", id: 2 });
|
|
138
|
+
} else if (m.id === 2) {
|
|
139
|
+
const r = m.result?.rateLimits;
|
|
140
|
+
limits = r ? { ai: "codex", plan: r.planType || null, status: r.rateLimitReachedType ? "limited" : "allowed",
|
|
141
|
+
windows: [window(r.primary), window(r.secondary)].filter(Boolean) } : null;
|
|
142
|
+
send({ method: "model/list", id: 3, params: {} });
|
|
143
|
+
} else if (m.id === 3) {
|
|
144
|
+
// The model Codex uses when none is asked for: the one it marks as its default, else the first it lists.
|
|
145
|
+
const list = m.result?.data || [];
|
|
146
|
+
const pick = list.find((x) => x.isDefault) || list[0];
|
|
147
|
+
done(limits ? { ...limits, model: pick?.id || null, models: list.filter((x) => !x.hidden).map((x) => x.id).filter(Boolean).slice(0, 12) } : null);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
});
|
|
151
|
+
child.on("error", () => done(null));
|
|
152
|
+
send({ method: "initialize", id: 1, params: { clientInfo: { name: "longtable", title: "Longtable", version: "0.1.0" } } });
|
|
153
|
+
});
|
|
154
|
+
}
|