longtable 0.0.0-stage → 0.1.1

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/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # longtable
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Brings your own Claude Code or Codex to your team's table on [longtable.chat](https://longtable.chat), quietly, on
4
+ your own plan.
5
+
6
+ Nobody types these commands. In Longtable you press **Connect your AI**, pick Claude or ChatGPT, and your own AI
7
+ opens with a short message already written. You press Send and it runs this package for you.
8
+
9
+ What it does on your computer:
10
+
11
+ - Keeps its own clean copy of your project's committed code, in `~/.longtable`. It never touches your work folder.
12
+ - Waits for questions from your table and answers them with your own Claude Code or Codex, on your own plan.
13
+ - Sends only the answers to the table. Your code stays on your computer.
14
+ - Claude can only read and search that copy. Codex gets no tools at all.
15
+
16
+ ```
17
+ longtable connect <code> [--ai claude|codex] [--repo <folder or git address>] [--app <url>]
18
+ longtable status
19
+ longtable disconnect
20
+ ```
21
+
22
+ MIT licence.
@@ -0,0 +1,156 @@
1
+ #!/usr/bin/env node
2
+ // longtable: brings your own Claude Code or Codex to your team's Longtable, quietly, on your own plan.
3
+ //
4
+ // longtable connect <code> [--ai claude|codex] [--app <url>] [--repo <folder or git address>] [--model <name>]
5
+ // [--no-autostart] [--no-run]
6
+ // longtable run
7
+ // longtable status
8
+ // longtable disconnect
9
+ //
10
+ // Nobody types these: Longtable's Connect button hands them to the person's own Claude or Codex, which runs them
11
+ // after the person presses Send. A client's AI gets no copy of the code.
12
+
13
+ import { spawn } from "node:child_process";
14
+ import { hostname } from "node:os";
15
+ import { fileURLToPath } from "node:url";
16
+ import { client, fetchConfig } from "../src/api.mjs";
17
+ import { claudeVersion, findClaude, tokenWorks } from "../src/claude.mjs";
18
+ import { codexSignIn, codexSignedIn, codexVersion, findCodex } from "../src/codex.mjs";
19
+ import { disableAutostart, enableAutostart } from "../src/autostart.mjs";
20
+ import { freshCopy, resolveSource } from "../src/repo.mjs";
21
+ import { runLoop } from "../src/run.mjs";
22
+ import { forgetSecret, loadSecret, log, readConfig, saveSecret, writeConfig } from "../src/store.mjs";
23
+
24
+ const binPath = fileURLToPath(import.meta.url);
25
+ const [command, ...args] = process.argv.slice(2);
26
+ const option = (name) => {
27
+ const i = args.indexOf(`--${name}`);
28
+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith("--") ? args[i + 1] : undefined;
29
+ };
30
+ const has = (name) => args.includes(`--${name}`);
31
+ const say = (line) => process.stdout.write(`${line}\n`);
32
+
33
+ async function connect() {
34
+ const code = args.find((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--") && ["app", "repo", "model", "ai"].includes(args[i - 1].slice(2))));
35
+ if (!code) throw new Error("Missing the connect code. Press Connect in Longtable again.");
36
+ const app = option("app") || "https://longtable.chat";
37
+ const ai = option("ai") || "claude";
38
+ if (!["claude", "codex"].includes(ai)) throw new Error("--ai is claude or codex.");
39
+ // Check the AI is here before the one-use code is spent.
40
+ const claude = ai === "claude" ? findClaude() : null;
41
+ const codex = ai === "codex" ? findCodex() : null;
42
+ if (ai === "claude" && !claude) throw new Error("Claude Code isn't installed on this computer. Install it from claude.com/claude-code, then press Connect again.");
43
+ if (ai === "codex" && !codex) throw new Error("Codex's command-line tool isn't installed on this computer. Install it with npm install -g @openai/codex, then press Connect again.");
44
+
45
+ // Find the code before the one-use code is spent: a repository this computer cannot open stops here, with
46
+ // nothing changed at the table. (A client's AI gets no code; whether this is one is only known after pairing.)
47
+ let source = null;
48
+ const repo = option("repo");
49
+ try {
50
+ source = resolveSource(repo || process.cwd());
51
+ } catch (e) {
52
+ if (repo) throw e;
53
+ }
54
+
55
+ const cfg = await fetchConfig(app);
56
+ const rpc = client(cfg);
57
+ const paired = await rpc("pair_connection", { code, device_label: hostname() });
58
+ // From here on, anything that goes wrong takes the connection off the table again, so the table never shows an AI
59
+ // as connected that is not running.
60
+ const leave = async (message) => {
61
+ try { await rpc("runner_leave", { token: paired.token, reason: message }); } catch {}
62
+ forgetSecret(`device-${paired.table_id}-${paired.kind}`);
63
+ throw new Error(message);
64
+ };
65
+ if (paired.kind !== ai) await leave(`That connect code is for ${paired.kind === "codex" ? "Codex" : "Claude"}. Press Connect again.`);
66
+ saveSecret(`device-${paired.table_id}-${paired.kind}`, paired.token);
67
+ if (paired.role === "client") source = null;
68
+ else if (!source) await leave("This folder is not the project. Open your AI in the project's own folder, then press Connect again.");
69
+
70
+ const config = readConfig();
71
+ config.app = app;
72
+ config.supabaseUrl = cfg.supabaseUrl;
73
+ config.publishableKey = cfg.publishableKey;
74
+ // One seat per person at a table: connecting a different AI takes the place of the one that was there.
75
+ for (const old of (config.connections || []).filter((c) => c.table_id === paired.table_id && c.kind !== paired.kind)) forgetSecret(`device-${old.table_id}-${old.kind}`);
76
+ config.connections = (config.connections || []).filter((c) => c.table_id !== paired.table_id);
77
+ config.connections.push({
78
+ table_id: paired.table_id,
79
+ kind: paired.kind,
80
+ table_name: paired.table_name,
81
+ member_name: paired.member_name,
82
+ role: paired.role,
83
+ source,
84
+ model: option("model") || null,
85
+ });
86
+ writeConfig(config);
87
+
88
+ if (source) {
89
+ try {
90
+ freshCopy(paired.table_id, source);
91
+ } catch (e) {
92
+ writeConfig({ ...config, connections: config.connections.filter((c) => c.table_id !== paired.table_id) });
93
+ await leave(`The connection could not copy the project's code: ${String(e.message).split("\n").pop()}`);
94
+ }
95
+ }
96
+
97
+ if (ai === "claude") {
98
+ const token = loadSecret("claude-token");
99
+ if (!token || !tokenWorks(claude, token)) {
100
+ say("A page is opening in your browser so this connection can have its own Claude sign-in. Approve it there.");
101
+ // Loaded only here: it needs packages that the copy kept for start-up does not carry.
102
+ const { signIn } = await import("../src/signin.mjs");
103
+ if (!(await signIn(claude))) await leave("The Claude sign-in didn't finish. Press Connect again.");
104
+ }
105
+ } else if (!codexSignedIn(codex)) {
106
+ say("A page is opening in your browser so this connection can have its own ChatGPT sign-in for Codex. Approve it there.");
107
+ if (!(await codexSignIn(codex))) await leave("The ChatGPT sign-in didn't finish. Press Connect again.");
108
+ }
109
+
110
+ const auto = has("no-autostart") ? { started: false } : enableAutostart(process.execPath, binPath);
111
+ if (!has("no-run") && !auto.started) {
112
+ spawn(process.execPath, [binPath, "run"], { detached: true, stdio: "ignore", windowsHide: true }).unref();
113
+ }
114
+ const word = ai === "codex" ? "Codex" : "Claude";
115
+ log(`connected to "${paired.table_name}" for ${paired.member_name} (${ai === "codex" ? codexVersion(codex) : claudeVersion(claude)})`);
116
+ say(`Connected. ${paired.member_name}'s ${word} is now at "${paired.table_name}". It answers in the background whenever this computer is on.`);
117
+ }
118
+
119
+ async function status() {
120
+ const config = readConfig();
121
+ if (!config.connections?.length) return say("Not connected to any table.");
122
+ const rpc = client(config);
123
+ for (const c of config.connections) {
124
+ const token = loadSecret(`device-${c.table_id}-${c.kind}`);
125
+ let state = "missing its device key";
126
+ if (token) {
127
+ try {
128
+ await rpc("runner_hello", { token });
129
+ state = "connected";
130
+ } catch (e) {
131
+ state = e.message;
132
+ }
133
+ }
134
+ say(`${c.member_name}'s ${c.kind === "claude" ? "Claude" : "Codex"} at "${c.table_name}": ${state}${c.source ? `, reading ${c.source}` : ""}`);
135
+ }
136
+ }
137
+
138
+ function disconnect() {
139
+ const config = readConfig();
140
+ for (const c of config.connections || []) forgetSecret(`device-${c.table_id}-${c.kind}`);
141
+ writeConfig({ ...config, connections: [] });
142
+ disableAutostart();
143
+ say("Disconnected on this computer. Remove it in Longtable's settings too if it still shows.");
144
+ }
145
+
146
+ try {
147
+ if (command === "connect") await connect();
148
+ else if (command === "run") await runLoop();
149
+ else if (command === "status") await status();
150
+ else if (command === "disconnect") disconnect();
151
+ else say("Usage: longtable connect <code> | run | status | disconnect");
152
+ } catch (e) {
153
+ log(`error: ${e.message}`);
154
+ process.stderr.write(`${e.message}\n`);
155
+ process.exit(1);
156
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Brings your own Claude Code or Codex to your team's table on longtable.chat, quietly, on your own plan.",
5
+ "homepage": "https://longtable.chat",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/TarikAlHadethi/Longtable.git",
9
+ "directory": "packages/connect"
10
+ },
11
+ "license": "MIT",
12
+ "type": "module",
13
+ "bin": {
14
+ "longtable": "bin/longtable.mjs"
15
+ },
16
+ "files": [
17
+ "bin",
18
+ "src",
19
+ "README.md"
20
+ ],
21
+ "engines": {
22
+ "node": ">=20"
23
+ },
24
+ "dependencies": {
25
+ "@lydell/node-pty": "1.2.0-beta.15",
26
+ "@xterm/headless": "^6.0.0"
27
+ },
28
+ "keywords": [
29
+ "longtable",
30
+ "claude",
31
+ "codex",
32
+ "ai",
33
+ "team"
34
+ ]
35
+ }
package/src/api.mjs ADDED
@@ -0,0 +1,23 @@
1
+ // Talking to Longtable. The connection has no login: it uses the public key and proves itself with its device token,
2
+ // and the only things it can call are the pairing and runner functions.
3
+
4
+ export async function fetchConfig(app) {
5
+ const res = await fetch(new URL("/api/connect/config", app));
6
+ if (!res.ok) throw new Error(`Longtable at ${app} did not answer (${res.status})`);
7
+ return res.json();
8
+ }
9
+
10
+ export function client({ supabaseUrl, publishableKey }) {
11
+ return async function rpc(fn, args) {
12
+ const res = await fetch(`${supabaseUrl}/rest/v1/rpc/${fn}`, {
13
+ method: "POST",
14
+ headers: { apikey: publishableKey, "Content-Type": "application/json" },
15
+ body: JSON.stringify(args),
16
+ });
17
+ const text = await res.text();
18
+ let body;
19
+ try { body = text ? JSON.parse(text) : null; } catch { body = text; }
20
+ if (!res.ok) throw new Error(body?.message || `Longtable said no (${res.status})`);
21
+ return body;
22
+ };
23
+ }
@@ -0,0 +1,110 @@
1
+ // Start the connection with the computer, with no window. Only ever set up after the person pressed Send on the
2
+ // Connect message that says so, and removed again by `longtable disconnect`.
3
+ //
4
+ // Windows: a per-user task in Task Scheduler, not the Startup folder. Claude Desktop is a packaged app, and files
5
+ // written from inside it into AppData (the Startup folder included) are kept in its private folder, where Windows
6
+ // never looks at sign-in. Task Scheduler is a service outside the app, so the task is real, and it starts the
7
+ // connection outside the app too. The task runs a copy of the connection kept in ~/.longtable/app, since the copy
8
+ // that ran `connect` may itself live somewhere only the app can see.
9
+
10
+ import { spawnSync } from "node:child_process";
11
+ import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
12
+ import { homedir } from "node:os";
13
+ import { dirname, join } from "node:path";
14
+ import { home } from "./store.mjs";
15
+
16
+ export const TASK = "Longtable connection";
17
+ const legacyStartup = () => join(process.env.APPDATA || "", "Microsoft", "Windows", "Start Menu", "Programs", "Startup", "Longtable.vbs");
18
+ const agentFile = () => join(homedir(), "Library", "LaunchAgents", "chat.longtable.connection.plist");
19
+ const unitFile = () => join(homedir(), ".config", "systemd", "user", "longtable.service");
20
+
21
+ function powershell(script, env = {}) {
22
+ const r = spawnSync("powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", script], {
23
+ env: { ...process.env, ...env },
24
+ windowsHide: true,
25
+ encoding: "utf8",
26
+ });
27
+ if (r.status !== 0) throw new Error(`Task Scheduler said no: ${(r.stderr || r.stdout || "").trim().slice(0, 300)}`);
28
+ return r.stdout;
29
+ }
30
+
31
+ // Copy the connection (its command and code; it needs nothing installed to run) to a place every program sees.
32
+ export function installCopy(binPath) {
33
+ const pkg = dirname(dirname(binPath));
34
+ const app = join(home, "app");
35
+ rmSync(app, { recursive: true, force: true });
36
+ mkdirSync(app, { recursive: true });
37
+ for (const part of ["bin", "src", "package.json"]) cpSync(join(pkg, part), join(app, part), { recursive: true });
38
+ return join(app, "bin", "longtable.mjs");
39
+ }
40
+
41
+ // The task runs this script, which starts Node with no window.
42
+ function writeStarter(nodePath, binPath) {
43
+ const q = (s) => s.replace(/"/g, '""');
44
+ const file = join(home, "start.vbs");
45
+ writeFileSync(file, `CreateObject("Wscript.Shell").Run """${q(nodePath)}"" ""${q(binPath)}"" run", 0, False\r\n`);
46
+ return file;
47
+ }
48
+
49
+ export function registerTask(name, starter) {
50
+ powershell(
51
+ "$a = New-ScheduledTaskAction -Execute 'wscript.exe' -Argument ('\"' + $env:LT_STARTER + '\"'); " +
52
+ "$t = New-ScheduledTaskTrigger -AtLogOn -User ([Security.Principal.WindowsIdentity]::GetCurrent().Name); " +
53
+ "$p = New-ScheduledTaskPrincipal -UserId ([Security.Principal.WindowsIdentity]::GetCurrent().Name) -LogonType Interactive -RunLevel Limited; " +
54
+ "$s = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable; " +
55
+ "Register-ScheduledTask -TaskName $env:LT_TASK -Action $a -Trigger $t -Principal $p -Settings $s -Force | Out-Null",
56
+ { LT_TASK: name, LT_STARTER: starter },
57
+ );
58
+ }
59
+
60
+ export function startTask(name) {
61
+ powershell("Start-ScheduledTask -TaskName $env:LT_TASK", { LT_TASK: name });
62
+ }
63
+
64
+ export function removeTask(name) {
65
+ try {
66
+ powershell("Unregister-ScheduledTask -TaskName $env:LT_TASK -Confirm:$false -ErrorAction Stop", { LT_TASK: name });
67
+ } catch {}
68
+ }
69
+
70
+ export function taskExists(name) {
71
+ try {
72
+ return powershell("if (Get-ScheduledTask -TaskName $env:LT_TASK -ErrorAction SilentlyContinue) { 'yes' } else { 'no' }", { LT_TASK: name }).trim() === "yes";
73
+ } catch {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ // Returns how the connection will start: on Windows the task also starts it now, outside whatever ran `connect`.
79
+ export function enableAutostart(nodePath, binPath) {
80
+ if (process.platform === "win32") {
81
+ const copy = installCopy(binPath);
82
+ registerTask(TASK, writeStarter(nodePath, copy));
83
+ rmSync(legacyStartup(), { force: true });
84
+ startTask(TASK);
85
+ return { started: true, where: `Task Scheduler: ${TASK}` };
86
+ }
87
+ if (process.platform === "darwin") {
88
+ mkdirSync(join(homedir(), "Library", "LaunchAgents"), { recursive: true });
89
+ writeFileSync(agentFile(), `<?xml version="1.0" encoding="UTF-8"?>
90
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
91
+ <plist version="1.0"><dict>
92
+ <key>Label</key><string>chat.longtable.connection</string>
93
+ <key>ProgramArguments</key><array><string>${nodePath}</string><string>${binPath}</string><string>run</string></array>
94
+ <key>RunAtLoad</key><true/><key>KeepAlive</key><true/>
95
+ </dict></plist>
96
+ `);
97
+ return { started: false, where: agentFile() };
98
+ }
99
+ mkdirSync(join(homedir(), ".config", "systemd", "user"), { recursive: true });
100
+ writeFileSync(unitFile(), `[Unit]\nDescription=Longtable connection\n\n[Service]\nExecStart=${nodePath} ${binPath} run\nRestart=always\n\n[Install]\nWantedBy=default.target\n`);
101
+ return { started: false, where: unitFile() };
102
+ }
103
+
104
+ export function disableAutostart() {
105
+ if (process.platform === "win32") {
106
+ removeTask(TASK);
107
+ rmSync(join(home, "start.vbs"), { force: true });
108
+ }
109
+ for (const f of [legacyStartup(), agentFile(), unitFile()]) if (existsSync(f)) rmSync(f, { force: true });
110
+ }
package/src/claude.mjs ADDED
@@ -0,0 +1,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
+ export function ask({ claude, cwd, prompt, system, schema, model, tools = "Read,Grep,Glob", apiKey, timeoutMs = 4 * 60 * 1000 }) {
76
+ const token = apiKey ? null : loadSecret("claude-token");
77
+ if (!token && !apiKey) return Promise.reject(new Error("This connection has no Claude sign-in yet. Run connect again."));
78
+ // Streamed output carries the plan's usage limits (a rate_limit_event) as well as the result.
79
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--restricted", "--permission-mode", "dontAsk",
80
+ "--strict-mcp-config", "--max-turns", tools ? "25" : "4", "--tools", tools];
81
+ if (system) args.push("--append-system-prompt", system);
82
+ if (schema) args.push("--json-schema", JSON.stringify(schema));
83
+ if (model) args.push("--model", model);
84
+ return new Promise((resolve, reject) => {
85
+ const started = Date.now();
86
+ const child = spawn(claude, args, { cwd, env: childEnv(token, apiKey), windowsHide: true });
87
+ let out = "";
88
+ let err = "";
89
+ const timer = setTimeout(() => child.kill(), timeoutMs);
90
+ child.stdout.on("data", (d) => (out += d));
91
+ child.stderr.on("data", (d) => (err += d));
92
+ child.on("error", (e) => { clearTimeout(timer); reject(e); });
93
+ child.on("close", (code) => {
94
+ clearTimeout(timer);
95
+ const events = out.split(/\r?\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
96
+ const result = events.filter((e) => e.type === "result").at(-1);
97
+ if (!result) {
98
+ log(`claude exited ${code} without a result: ${err.slice(0, 300)}`);
99
+ return reject(new Error("Claude Code did not answer. See the runner log."));
100
+ }
101
+ const rate = events.filter((e) => e.type === "rate_limit_event").at(-1)?.rate_limit_info;
102
+ resolve({ ...result, wall_ms: Date.now() - started, limits: claudeLimits(rate) });
103
+ });
104
+ child.stdin.end(prompt);
105
+ });
106
+ }
107
+
108
+ // The plan's limits as Longtable shows them: each window's use in percent and when it resets.
109
+ export function claudeLimits(rate) {
110
+ if (!rate) return null;
111
+ const names = { five_hour: "5-hour", seven_day: "weekly" };
112
+ const windows = Object.entries(rate.unifiedWindows || {}).map(([k, w]) => ({
113
+ name: names[k] || k.replace(/_/g, " "),
114
+ used: Math.round((w.utilization ?? 0) * 100),
115
+ resets: w.resetsAt ? new Date(w.resetsAt * 1000).toISOString() : null,
116
+ }));
117
+ return { ai: "claude", plan: null, status: rate.status === "rejected" ? "limited" : "allowed", windows };
118
+ }
package/src/codex.mjs ADDED
@@ -0,0 +1,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.on("data", (d) => (out += d));
87
+ child.stderr.on("data", (d) => (err += d));
88
+ child.on("error", (e) => { clearTimeout(timer); rmSync(work, { recursive: true, force: true }); reject(e); });
89
+ child.on("close", (code) => {
90
+ clearTimeout(timer);
91
+ const events = out.split(/\r?\n/).filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
92
+ let structured = null;
93
+ try { structured = JSON.parse(readFileSync(lastFile, "utf8")); } catch {}
94
+ rmSync(work, { recursive: true, force: true });
95
+ if (!structured) {
96
+ log(`codex exited ${code} without an answer: ${err.slice(0, 300)}`);
97
+ return reject(new Error("Codex did not answer. See the runner log."));
98
+ }
99
+ const usage = events.filter((e) => e.type === "turn.completed").map((e) => e.usage).filter(Boolean).at(-1) || {};
100
+ const items = events.filter((e) => e.type === "item.started" || e.type === "item.completed").map((e) => e.item || {});
101
+ // Codex's own notices arrive as error items (switching its code-mode host off makes it say code mode "will
102
+ // fail closed"); they are logged, not counted. Anything else that is not its message or reasoning is a tool.
103
+ for (const i of items) if (i.type === "error") log(`codex notice: ${String(i.message || "").slice(0, 200)}`);
104
+ const tools = items.map((i) => i.type).filter((t) => t && !["agent_message", "reasoning", "error"].includes(t));
105
+ resolve({ structured_output: structured, usage, tools, wall_ms: Date.now() - started });
106
+ });
107
+ child.stdin.end(prompt);
108
+ });
109
+ }
110
+
111
+ // The ChatGPT plan's Codex limits, read from Codex's own app server (account/rateLimits/read). Null if it does not
112
+ // answer within ten seconds.
113
+ export function codexLimits(codex) {
114
+ return new Promise((resolve) => {
115
+ const child = spawn(codex.cmd, [...codex.pre, "app-server"], { env: env(), windowsHide: true });
116
+ let buf = "";
117
+ let limits = null;
118
+ const done = (value) => { clearTimeout(timer); child.kill(); resolve(value); };
119
+ const timer = setTimeout(() => done(limits), 10000);
120
+ const send = (m) => child.stdin.write(JSON.stringify(m) + "\n");
121
+ const name = (mins) => mins === 300 ? "5-hour" : mins === 10080 ? "weekly" : mins === 43200 ? "30-day" : `${Math.round(mins / 60)}-hour`;
122
+ const window = (w) => w && ({ name: name(w.windowDurationMins), used: Math.round(w.usedPercent ?? 0),
123
+ resets: w.resetsAt ? new Date(w.resetsAt * 1000).toISOString() : null });
124
+ child.stdout.on("data", (d) => {
125
+ buf += d;
126
+ let i;
127
+ while ((i = buf.indexOf("\n")) >= 0) {
128
+ const line = buf.slice(0, i);
129
+ buf = buf.slice(i + 1);
130
+ let m;
131
+ try { m = JSON.parse(line); } catch { continue; }
132
+ if (m.id === 1) {
133
+ send({ method: "initialized" });
134
+ send({ method: "account/rateLimits/read", id: 2 });
135
+ } else if (m.id === 2) {
136
+ const r = m.result?.rateLimits;
137
+ limits = r ? { ai: "codex", plan: r.planType || null, status: r.rateLimitReachedType ? "limited" : "allowed",
138
+ windows: [window(r.primary), window(r.secondary)].filter(Boolean) } : null;
139
+ send({ method: "model/list", id: 3, params: {} });
140
+ } else if (m.id === 3) {
141
+ // The model Codex uses when none is asked for: the one it marks as its default, else the first it lists.
142
+ const list = m.result?.data || [];
143
+ const pick = list.find((x) => x.isDefault) || list[0];
144
+ done(limits ? { ...limits, model: pick?.displayName || pick?.id || null } : null);
145
+ }
146
+ }
147
+ });
148
+ child.on("error", () => done(null));
149
+ send({ method: "initialize", id: 1, params: { clientInfo: { name: "longtable", title: "Longtable", version: "0.1.0" } } });
150
+ });
151
+ }