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 CHANGED
@@ -1,156 +1,165 @@
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
- }
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 { rmSync } from "node:fs";
15
+ import { hostname } from "node:os";
16
+ import { join, resolve } from "node:path";
17
+ import { fileURLToPath } from "node:url";
18
+ import { client, fetchConfig } from "../src/api.mjs";
19
+ import { claudeVersion, findClaude, tokenWorks } from "../src/claude.mjs";
20
+ import { codexSignIn, codexSignedIn, codexVersion, findCodex } from "../src/codex.mjs";
21
+ import { disableAutostart, enableAutostart } from "../src/autostart.mjs";
22
+ import { freshCopy, resolveSource } from "../src/repo.mjs";
23
+ import { runLoop, runningConnection } from "../src/run.mjs";
24
+ import { forgetSecret, home, loadSecret, log, readConfig, saveSecret, writeConfig } from "../src/store.mjs";
25
+
26
+ const binPath = fileURLToPath(import.meta.url);
27
+ const [command, ...args] = process.argv.slice(2);
28
+ const option = (name) => {
29
+ const i = args.indexOf(`--${name}`);
30
+ return i >= 0 && args[i + 1] && !args[i + 1].startsWith("--") ? args[i + 1] : undefined;
31
+ };
32
+ const has = (name) => args.includes(`--${name}`);
33
+ const say = (line) => process.stdout.write(`${line}\n`);
34
+
35
+ async function connect() {
36
+ const code = args.find((a, i) => !a.startsWith("--") && !(i > 0 && args[i - 1].startsWith("--") && ["app", "repo", "model", "ai"].includes(args[i - 1].slice(2))));
37
+ if (!code) throw new Error("Missing the connect code. Press Connect in Longtable again.");
38
+ const app = option("app") || "https://longtable.chat";
39
+ const ai = option("ai") || "claude";
40
+ if (!["claude", "codex"].includes(ai)) throw new Error("--ai is claude or codex.");
41
+ // Check the AI is here before the one-use code is spent.
42
+ const claude = ai === "claude" ? findClaude() : null;
43
+ const codex = ai === "codex" ? findCodex() : null;
44
+ 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.");
45
+ 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.");
46
+
47
+ // Find the code before the one-use code is spent: a repository this computer cannot open stops here, with
48
+ // nothing changed at the table. (A client's AI gets no code; whether this is one is only known after pairing.)
49
+ let source = null;
50
+ const repo = option("repo");
51
+ try {
52
+ source = resolveSource(repo || process.cwd());
53
+ } catch (e) {
54
+ if (repo) throw e;
55
+ }
56
+
57
+ const cfg = await fetchConfig(app);
58
+ const rpc = client(cfg);
59
+ const paired = await rpc("pair_connection", { code, device_label: hostname() });
60
+ // From here on, anything that goes wrong takes the connection off the table again, so the table never shows an AI
61
+ // as connected that is not running.
62
+ const leave = async (message) => {
63
+ try { await rpc("runner_leave", { token: paired.token, reason: message }); } catch {}
64
+ forgetSecret(`device-${paired.table_id}-${paired.kind}`);
65
+ throw new Error(message);
66
+ };
67
+ if (paired.kind !== ai) await leave(`That connect code is for ${paired.kind === "codex" ? "Codex" : "Claude"}. Press Connect again.`);
68
+ saveSecret(`device-${paired.table_id}-${paired.kind}`, paired.token);
69
+ if (paired.role === "client") source = null;
70
+ else if (!source) await leave("This folder is not the project. Open your AI in the project's own folder, then press Connect again.");
71
+
72
+ const config = readConfig();
73
+ config.app = app;
74
+ config.supabaseUrl = cfg.supabaseUrl;
75
+ config.publishableKey = cfg.publishableKey;
76
+ // One seat per person at a table: connecting a different AI takes the place of the one that was there.
77
+ 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}`);
78
+ config.connections = (config.connections || []).filter((c) => c.table_id !== paired.table_id);
79
+ config.connections.push({
80
+ table_id: paired.table_id,
81
+ kind: paired.kind,
82
+ table_name: paired.table_name,
83
+ member_name: paired.member_name,
84
+ role: paired.role,
85
+ source,
86
+ folder: /^(https?:|git@|ssh:)/.test(repo || "") ? null : resolve(repo || process.cwd()),
87
+ model: option("model") || null,
88
+ });
89
+ writeConfig(config);
90
+
91
+ if (source) {
92
+ try {
93
+ freshCopy(paired.table_id, source);
94
+ } catch (e) {
95
+ writeConfig({ ...config, connections: config.connections.filter((c) => c.table_id !== paired.table_id) });
96
+ await leave(`The connection could not copy the project's code: ${String(e.message).split("\n").pop()}`);
97
+ }
98
+ }
99
+
100
+ if (ai === "claude") {
101
+ const token = loadSecret("claude-token");
102
+ if (!token || !tokenWorks(claude, token)) {
103
+ say("A page is opening in your browser so this connection can have its own Claude sign-in. Approve it there.");
104
+ // Loaded only here: it needs packages that the copy kept for start-up does not carry.
105
+ const { signIn } = await import("../src/signin.mjs");
106
+ if (!(await signIn(claude))) await leave("The Claude sign-in didn't finish. Press Connect again.");
107
+ }
108
+ } else if (!codexSignedIn(codex)) {
109
+ say("A page is opening in your browser so this connection can have its own ChatGPT sign-in for Codex. Approve it there.");
110
+ if (!(await codexSignIn(codex))) await leave("The ChatGPT sign-in didn't finish. Press Connect again.");
111
+ }
112
+
113
+ const auto = has("no-autostart") ? { started: false } : enableAutostart(process.execPath, binPath);
114
+ if (!has("no-run") && !auto.started) {
115
+ spawn(process.execPath, [binPath, "run"], { detached: true, stdio: "ignore", windowsHide: true }).unref();
116
+ }
117
+ const word = ai === "codex" ? "Codex" : "Claude";
118
+ log(`connected to "${paired.table_name}" for ${paired.member_name} (${ai === "codex" ? codexVersion(codex) : claudeVersion(claude)})`);
119
+ say(`Connected. ${paired.member_name}'s ${word} is now at "${paired.table_name}". It answers in the background whenever this computer is on.`);
120
+ }
121
+
122
+ async function status() {
123
+ const config = readConfig();
124
+ if (!config.connections?.length) return say("Not connected to any table.");
125
+ const rpc = client(config);
126
+ for (const c of config.connections) {
127
+ const token = loadSecret(`device-${c.table_id}-${c.kind}`);
128
+ let state = "missing its device key";
129
+ if (token) {
130
+ try {
131
+ await rpc("runner_hello", { token });
132
+ state = "connected";
133
+ } catch (e) {
134
+ state = e.message;
135
+ }
136
+ }
137
+ say(`${c.member_name}'s ${c.kind === "claude" ? "Claude" : "Codex"} at "${c.table_name}": ${state}${c.source ? `, reading ${c.source}` : ""}`);
138
+ }
139
+ }
140
+
141
+ function disconnect() {
142
+ const config = readConfig();
143
+ for (const c of config.connections || []) forgetSecret(`device-${c.table_id}-${c.kind}`);
144
+ writeConfig({ ...config, connections: [] });
145
+ disableAutostart();
146
+ // The connection that is running right now still holds its keys in memory: end it.
147
+ try {
148
+ const pid = runningConnection();
149
+ if (pid && pid !== process.pid) process.kill(pid);
150
+ } catch {}
151
+ rmSync(join(home, "runner.pid"), { force: true });
152
+ say("Disconnected on this computer. Remove it in Longtable's settings too if it still shows.");
153
+ }
154
+
155
+ try {
156
+ if (command === "connect") await connect();
157
+ else if (command === "run") await runLoop();
158
+ else if (command === "status") await status();
159
+ else if (command === "disconnect") disconnect();
160
+ else say("Usage: longtable connect <code> | run | status | disconnect");
161
+ } catch (e) {
162
+ log(`error: ${e.message}`);
163
+ process.stderr.write(`${e.message}\n`);
164
+ process.exit(1);
165
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "longtable",
3
- "version": "0.1.1",
3
+ "version": "0.1.7",
4
4
  "description": "Brings your own Claude Code or Codex to your team's table on longtable.chat, quietly, on your own plan.",
5
5
  "homepage": "https://longtable.chat",
6
6
  "repository": {
package/src/autostart.mjs CHANGED
@@ -1,110 +1,115 @@
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
- }
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
+ // Writing the unit is not enough: it has to be switched on to come back after a restart.
102
+ spawnSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" });
103
+ const on = spawnSync("systemctl", ["--user", "enable", "--now", "longtable.service"], { stdio: "ignore" });
104
+ return { started: on.status === 0, where: unitFile() };
105
+ }
106
+
107
+ export function disableAutostart() {
108
+ if (process.platform === "win32") {
109
+ removeTask(TASK);
110
+ rmSync(join(home, "start.vbs"), { force: true });
111
+ }
112
+ // On Linux the service is switched off before its file goes, or it would keep bringing the connection back.
113
+ if (process.platform === "linux" && existsSync(unitFile())) spawnSync("systemctl", ["--user", "disable", "--now", "longtable.service"], { stdio: "ignore" });
114
+ for (const f of [legacyStartup(), agentFile(), unitFile()]) if (existsSync(f)) rmSync(f, { force: true });
115
+ }