@getengram/cli 0.6.0 → 0.7.0
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/LICENSE +112 -0
- package/README.md +1 -1
- package/dist/commands/auth.d.ts.map +1 -1
- package/dist/commands/auth.js +38 -11
- package/dist/commands/auth.js.map +1 -1
- package/dist/commands/conversations.d.ts.map +1 -1
- package/dist/commands/conversations.js +8 -2
- package/dist/commands/conversations.js.map +1 -1
- package/dist/commands/exclude.d.ts.map +1 -1
- package/dist/commands/exclude.js +73 -21
- package/dist/commands/exclude.js.map +1 -1
- package/dist/commands/import.d.ts +30 -3
- package/dist/commands/import.d.ts.map +1 -1
- package/dist/commands/import.js +374 -45
- package/dist/commands/import.js.map +1 -1
- package/dist/commands/login.d.ts.map +1 -1
- package/dist/commands/login.js +144 -29
- package/dist/commands/login.js.map +1 -1
- package/dist/commands/search.js +2 -2
- package/dist/commands/search.js.map +1 -1
- package/dist/commands/status.d.ts +16 -0
- package/dist/commands/status.d.ts.map +1 -0
- package/dist/commands/status.js +51 -0
- package/dist/commands/status.js.map +1 -0
- package/dist/commands/store.d.ts.map +1 -1
- package/dist/commands/store.js +19 -3
- package/dist/commands/store.js.map +1 -1
- package/dist/commands/upgrade.d.ts +24 -0
- package/dist/commands/upgrade.d.ts.map +1 -1
- package/dist/commands/upgrade.js +64 -15
- package/dist/commands/upgrade.js.map +1 -1
- package/dist/commands/usage.d.ts +44 -0
- package/dist/commands/usage.d.ts.map +1 -1
- package/dist/commands/usage.js +79 -19
- package/dist/commands/usage.js.map +1 -1
- package/dist/commands/vault.d.ts +11 -2
- package/dist/commands/vault.d.ts.map +1 -1
- package/dist/commands/vault.js +372 -53
- package/dist/commands/vault.js.map +1 -1
- package/dist/config-file.d.ts +74 -0
- package/dist/config-file.d.ts.map +1 -0
- package/dist/config-file.js +152 -0
- package/dist/config-file.js.map +1 -0
- package/dist/config-guard.d.ts +96 -0
- package/dist/config-guard.d.ts.map +1 -0
- package/dist/config-guard.js +184 -0
- package/dist/config-guard.js.map +1 -0
- package/dist/config.d.ts +48 -4
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +101 -12
- package/dist/config.js.map +1 -1
- package/dist/daemon/as-root.d.ts +46 -0
- package/dist/daemon/as-root.d.ts.map +1 -0
- package/dist/daemon/as-root.js +64 -0
- package/dist/daemon/as-root.js.map +1 -0
- package/dist/daemon/backoff.d.ts +26 -0
- package/dist/daemon/backoff.d.ts.map +1 -0
- package/dist/daemon/backoff.js +37 -0
- package/dist/daemon/backoff.js.map +1 -0
- package/dist/daemon/codex-parser.d.ts +38 -4
- package/dist/daemon/codex-parser.d.ts.map +1 -1
- package/dist/daemon/codex-parser.js +111 -23
- package/dist/daemon/codex-parser.js.map +1 -1
- package/dist/daemon/command-path.d.ts +13 -0
- package/dist/daemon/command-path.d.ts.map +1 -0
- package/dist/daemon/command-path.js +35 -0
- package/dist/daemon/command-path.js.map +1 -0
- package/dist/daemon/commands.d.ts +153 -3
- package/dist/daemon/commands.d.ts.map +1 -1
- package/dist/daemon/commands.js +2775 -235
- package/dist/daemon/commands.js.map +1 -1
- package/dist/daemon/db.d.ts +255 -27
- package/dist/daemon/db.d.ts.map +1 -1
- package/dist/daemon/db.js +749 -53
- package/dist/daemon/db.js.map +1 -1
- package/dist/daemon/exclusions.d.ts +23 -3
- package/dist/daemon/exclusions.d.ts.map +1 -1
- package/dist/daemon/exclusions.js +91 -21
- package/dist/daemon/exclusions.js.map +1 -1
- package/dist/daemon/homebrew.d.ts +26 -0
- package/dist/daemon/homebrew.d.ts.map +1 -0
- package/dist/daemon/homebrew.js +43 -0
- package/dist/daemon/homebrew.js.map +1 -0
- package/dist/daemon/instance.d.ts +427 -0
- package/dist/daemon/instance.d.ts.map +1 -0
- package/dist/daemon/instance.js +1201 -0
- package/dist/daemon/instance.js.map +1 -0
- package/dist/daemon/key-source.d.ts +41 -0
- package/dist/daemon/key-source.d.ts.map +1 -0
- package/dist/daemon/key-source.js +89 -0
- package/dist/daemon/key-source.js.map +1 -0
- package/dist/daemon/launch.d.ts +56 -0
- package/dist/daemon/launch.d.ts.map +1 -0
- package/dist/daemon/launch.js +153 -0
- package/dist/daemon/launch.js.map +1 -0
- package/dist/daemon/launchd.d.ts +215 -0
- package/dist/daemon/launchd.d.ts.map +1 -0
- package/dist/daemon/launchd.js +527 -0
- package/dist/daemon/launchd.js.map +1 -0
- package/dist/daemon/login-start.d.ts +2 -0
- package/dist/daemon/login-start.d.ts.map +1 -0
- package/dist/daemon/login-start.js +25 -0
- package/dist/daemon/login-start.js.map +1 -0
- package/dist/daemon/ownership.d.ts +123 -0
- package/dist/daemon/ownership.d.ts.map +1 -0
- package/dist/daemon/ownership.js +245 -0
- package/dist/daemon/ownership.js.map +1 -0
- package/dist/daemon/package-runner.d.ts +28 -0
- package/dist/daemon/package-runner.d.ts.map +1 -0
- package/dist/daemon/package-runner.js +113 -0
- package/dist/daemon/package-runner.js.map +1 -0
- package/dist/daemon/parser.d.ts +50 -5
- package/dist/daemon/parser.d.ts.map +1 -1
- package/dist/daemon/parser.js +224 -47
- package/dist/daemon/parser.js.map +1 -1
- package/dist/daemon/powershell.d.ts +25 -0
- package/dist/daemon/powershell.d.ts.map +1 -0
- package/dist/daemon/powershell.js +30 -0
- package/dist/daemon/powershell.js.map +1 -0
- package/dist/daemon/preflight.d.ts +0 -17
- package/dist/daemon/preflight.d.ts.map +1 -1
- package/dist/daemon/preflight.js +32 -6
- package/dist/daemon/preflight.js.map +1 -1
- package/dist/daemon/prune.d.ts +101 -0
- package/dist/daemon/prune.d.ts.map +1 -0
- package/dist/daemon/prune.js +287 -0
- package/dist/daemon/prune.js.map +1 -0
- package/dist/daemon/queue-error.d.ts +47 -0
- package/dist/daemon/queue-error.d.ts.map +1 -0
- package/dist/daemon/queue-error.js +59 -0
- package/dist/daemon/queue-error.js.map +1 -0
- package/dist/daemon/root-daemon.d.ts +60 -0
- package/dist/daemon/root-daemon.d.ts.map +1 -0
- package/dist/daemon/root-daemon.js +86 -0
- package/dist/daemon/root-daemon.js.map +1 -0
- package/dist/daemon/scoop.d.ts +52 -0
- package/dist/daemon/scoop.d.ts.map +1 -0
- package/dist/daemon/scoop.js +84 -0
- package/dist/daemon/scoop.js.map +1 -0
- package/dist/daemon/scrubber.d.ts +456 -0
- package/dist/daemon/scrubber.d.ts.map +1 -0
- package/dist/daemon/scrubber.js +994 -0
- package/dist/daemon/scrubber.js.map +1 -0
- package/dist/daemon/status.d.ts +306 -11
- package/dist/daemon/status.d.ts.map +1 -1
- package/dist/daemon/status.js +568 -43
- package/dist/daemon/status.js.map +1 -1
- package/dist/daemon/supervise.d.ts +78 -0
- package/dist/daemon/supervise.d.ts.map +1 -0
- package/dist/daemon/supervise.js +121 -0
- package/dist/daemon/supervise.js.map +1 -0
- package/dist/daemon/supervisor.d.ts +18 -0
- package/dist/daemon/supervisor.d.ts.map +1 -0
- package/dist/daemon/supervisor.js +56 -0
- package/dist/daemon/supervisor.js.map +1 -0
- package/dist/daemon/syncer.d.ts +382 -21
- package/dist/daemon/syncer.d.ts.map +1 -1
- package/dist/daemon/syncer.js +1448 -178
- package/dist/daemon/syncer.js.map +1 -1
- package/dist/daemon/systemd.d.ts +109 -0
- package/dist/daemon/systemd.d.ts.map +1 -0
- package/dist/daemon/systemd.js +363 -0
- package/dist/daemon/systemd.js.map +1 -0
- package/dist/daemon/types.d.ts +58 -6
- package/dist/daemon/types.d.ts.map +1 -1
- package/dist/daemon/vault-changed.d.ts +29 -0
- package/dist/daemon/vault-changed.d.ts.map +1 -0
- package/dist/daemon/vault-changed.js +47 -0
- package/dist/daemon/vault-changed.js.map +1 -0
- package/dist/daemon/vault-key-missing.d.ts +70 -0
- package/dist/daemon/vault-key-missing.d.ts.map +1 -0
- package/dist/daemon/vault-key-missing.js +125 -0
- package/dist/daemon/vault-key-missing.js.map +1 -0
- package/dist/daemon/watcher.d.ts +87 -4
- package/dist/daemon/watcher.d.ts.map +1 -1
- package/dist/daemon/watcher.js +286 -36
- package/dist/daemon/watcher.js.map +1 -1
- package/dist/daemon/worker-main.js +363 -51
- package/dist/daemon/worker-main.js.map +1 -1
- package/dist/daemon/worker.js +19 -1
- package/dist/daemon/worker.js.map +1 -1
- package/dist/import-resume.d.ts +163 -0
- package/dist/import-resume.d.ts.map +1 -0
- package/dist/import-resume.js +267 -0
- package/dist/import-resume.js.map +1 -0
- package/dist/index.js +242 -33
- package/dist/index.js.map +1 -1
- package/dist/message-bounds.d.ts +52 -0
- package/dist/message-bounds.d.ts.map +1 -0
- package/dist/message-bounds.js +157 -0
- package/dist/message-bounds.js.map +1 -0
- package/dist/output.d.ts +14 -0
- package/dist/output.d.ts.map +1 -1
- package/dist/output.js +33 -5
- package/dist/output.js.map +1 -1
- package/dist/private-files.d.ts +126 -0
- package/dist/private-files.d.ts.map +1 -0
- package/dist/private-files.js +372 -0
- package/dist/private-files.js.map +1 -0
- package/dist/server-url.d.ts +31 -0
- package/dist/server-url.d.ts.map +1 -0
- package/dist/server-url.js +47 -0
- package/dist/server-url.js.map +1 -0
- package/dist/vault-key.d.ts +122 -0
- package/dist/vault-key.d.ts.map +1 -0
- package/dist/vault-key.js +273 -0
- package/dist/vault-key.js.map +1 -0
- package/package.json +11 -12
package/dist/daemon/commands.js
CHANGED
|
@@ -1,335 +1,2875 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { readFileSync,
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
|
-
import { join,
|
|
5
|
-
import { bold, dim, red } from "../output.js";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { readFileSync, existsSync, mkdtempSync, realpathSync, rmSync, statSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { dirname, join, win32 } from "node:path";
|
|
5
|
+
import { bold, dim, plural, red } from "../output.js";
|
|
6
|
+
import { loadConfigStrict, saveConfig, saveFailure } from "../config.js";
|
|
7
|
+
import { ConfigUnreadable } from "../config-file.js";
|
|
8
|
+
import { inspectConfig, lockedConfigDir, printEmptyConfigNote } from "../config-guard.js";
|
|
9
|
+
import { writePrivateFileSync } from "../private-files.js";
|
|
10
|
+
import { readStatus, syncErrorSummary, captureErrorSummary, configProblemSummary, deleteRefusedSummary, } from "./status.js";
|
|
11
|
+
import { formatWait } from "./backoff.js";
|
|
8
12
|
import { ALL_ADAPTERS } from "./adapters.js";
|
|
9
|
-
|
|
10
|
-
|
|
13
|
+
import { asRootRefusal, rootForAnotherUser } from "./as-root.js";
|
|
14
|
+
import { commandFailure } from "./command-path.js";
|
|
15
|
+
import { throughOptLink } from "./homebrew.js";
|
|
16
|
+
import { scoopVersionOf, throughScoopCurrent } from "./scoop.js";
|
|
17
|
+
import { INSTALL_CLI, engramCommand, runnerCacheOf, runnerCacheOfThisCli } from "./package-runner.js";
|
|
18
|
+
import { foreignFiles, foreignFilesFix, foreignFilesProblem, lockedDir, lockedDirFix, lockedDirProblem, lockedDirReason, OWNERSHIP_FIX, } from "./ownership.js";
|
|
19
|
+
import { envVaultKeySaved, envVaultKeyState, vaultKeyFileState, vaultKeyFix, VaultKeyUnreadable } from "../vault-key.js";
|
|
20
|
+
import { ENGRAM_DIR, LOG_FILE, START_WAIT_MS, logProblem, loginStartPath, prepareLogSync, spawnSupervisor, spawnWorker, workerPath, } from "./launch.js";
|
|
21
|
+
import { STOPPING_WAIT_MS, STOP_FILE, VERSION, alive, identifyProcess, pidInFile, probeDaemon, removePidFileIf, } from "./instance.js";
|
|
22
|
+
import { UNIT_VERSION, generateUnit, installUnit, readUnit, removeUnit, rewriteUnit, startUnit, systemctlPath, systemdReachable, unitPath, unitPid, } from "./systemd.js";
|
|
23
|
+
import { findRootDaemon, rootDaemonLines, systemJobLeft, untiedRootLine, untiedRootWorkers, } from "./root-daemon.js";
|
|
24
|
+
import { LAUNCH_AGENTS_FIX, PLIST_VERSION, agentDisabled, agentLoaded, agentPid, enableAgent, generatePlist, kickstartAgent, launchAgentsNotYours, loadAgent, plistPath, readPlist, reloadAgent, systemJob, unloadAgent, writePlistFile, } from "./launchd.js";
|
|
25
|
+
/** Render the per-host capture status (engram#261). `paused`: why nothing
|
|
26
|
+
* is captured, e.g. the daemon runs without a key (engram#594). */
|
|
27
|
+
function printHostStatus(paused) {
|
|
11
28
|
console.log(`${dim("Hosts:")}`);
|
|
12
29
|
for (const a of ALL_ADAPTERS) {
|
|
13
30
|
const on = a.available();
|
|
14
31
|
const mark = on ? "✓" : "·";
|
|
15
|
-
const state = on ? "capturing" : "not installed";
|
|
32
|
+
const state = on ? (paused ? `paused (${paused})` : "capturing") : "not installed";
|
|
16
33
|
console.log(` ${mark} ${a.label.padEnd(14)} ${dim(state)}`);
|
|
17
34
|
}
|
|
18
35
|
}
|
|
19
|
-
const ENGRAM_DIR = join(homedir(), ".engram");
|
|
20
|
-
const PID_FILE = join(ENGRAM_DIR, "daemon.pid");
|
|
21
36
|
const DB_FILE = join(ENGRAM_DIR, "daemon.db");
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
37
|
+
function sleep(ms) {
|
|
38
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
39
|
+
}
|
|
40
|
+
function fromAnswer(probe) {
|
|
41
|
+
if (probe.state !== "answered")
|
|
42
|
+
return null;
|
|
43
|
+
const { info } = probe;
|
|
44
|
+
if (info.stopping)
|
|
45
|
+
return { state: "stopping", pid: info.pid };
|
|
46
|
+
return {
|
|
47
|
+
state: "running",
|
|
48
|
+
pid: info.pid,
|
|
49
|
+
version: info.version,
|
|
50
|
+
ready: info.ready,
|
|
51
|
+
older: false,
|
|
52
|
+
id: info.id,
|
|
53
|
+
stopFile: info.stopFile,
|
|
54
|
+
output: info.output,
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Find the daemon. It answers on ~/.engram/daemon.sock (a named pipe on
|
|
59
|
+
* Windows) with its PID. The PID file alone is never trusted: one left by a
|
|
60
|
+
* daemon that didn't exit cleanly can name a PID that has since gone to
|
|
61
|
+
* another program, which this used to report as the daemon and `engram stop`
|
|
62
|
+
* signalled.
|
|
63
|
+
*/
|
|
64
|
+
async function findDaemon(timeoutMs) {
|
|
65
|
+
const probe = await probeDaemon({ timeoutMs });
|
|
66
|
+
const answered = fromAnswer(probe);
|
|
67
|
+
if (answered)
|
|
68
|
+
return answered;
|
|
69
|
+
if (probe.state === "silent") {
|
|
70
|
+
// The PID file is left as it is: a daemon busy starting wrote it.
|
|
71
|
+
return { state: "unresponsive", pid: readLaunchdPid() ?? usersOwn(pidFileDaemon(false)) };
|
|
72
|
+
}
|
|
73
|
+
// Nothing answers. A daemon from before engram#612 has no socket, but
|
|
74
|
+
// launchd, or its PID file confirmed, still finds it. (A daemon since
|
|
75
|
+
// listens before it writes the PID file.) Where no socket can be used
|
|
76
|
+
// (probe "unavailable"), that is how every daemon is found.
|
|
77
|
+
const launchd = readLaunchdPid();
|
|
78
|
+
const inFile = launchd === null ? pidFileDaemon(true) : null;
|
|
79
|
+
const pid = launchd ?? usersOwn(inFile);
|
|
80
|
+
if (pid !== null)
|
|
81
|
+
return { state: "running", pid, ready: true, older: probe.state === "none" };
|
|
82
|
+
// One running as root for them (engram#680), named in the PID file or run
|
|
83
|
+
// by a job in launchd's system domain. Its socket, if it has one, is
|
|
84
|
+
// root's: the probe can't use it.
|
|
85
|
+
const root = findRootDaemon(inFile);
|
|
86
|
+
return root === null ? { state: "stopped" } : { state: "root", ...root };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The daemon the PID file names, when that process is confirmed to be it
|
|
90
|
+
* (see identifyProcess). `root`: it runs as root for this user (engram#680);
|
|
91
|
+
* its file is kept, as it is still running. `tidy`: remove a file that
|
|
92
|
+
* names a process that has exited, or another program.
|
|
93
|
+
*/
|
|
94
|
+
function pidFileDaemon(tidy) {
|
|
95
|
+
const pid = pidInFile();
|
|
96
|
+
if (pid === null || pid === process.pid)
|
|
97
|
+
return null;
|
|
98
|
+
if (!alive(pid)) {
|
|
99
|
+
if (tidy)
|
|
100
|
+
removePidFileIf(pid);
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
const what = identifyProcess(pid);
|
|
104
|
+
if (what === "other" && tidy)
|
|
105
|
+
removePidFileIf(pid);
|
|
106
|
+
return what === "daemon" || what === "root" ? { pid, root: what === "root" } : null;
|
|
107
|
+
}
|
|
108
|
+
/** Its PID, when it runs as the user. */
|
|
109
|
+
function usersOwn(found) {
|
|
110
|
+
return found !== null && !found.root ? found.pid : null;
|
|
111
|
+
}
|
|
112
|
+
/** "Daemon already running", for a start that finds one. */
|
|
113
|
+
function printAlreadyRunning(found) {
|
|
114
|
+
const pid = found.pid === null ? "" : ` (pid ${found.pid})`;
|
|
115
|
+
if (found.state === "unresponsive") {
|
|
116
|
+
console.log(`Daemon already running${pid}, but it isn't answering right now`);
|
|
117
|
+
console.log(dim(` It may be busy, or still starting.${itsLog()}`));
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
console.log(`Daemon already running${pid}`);
|
|
121
|
+
printVersionHint(found);
|
|
122
|
+
// Its log can be written, and it doesn't write there (engram#720): a
|
|
123
|
+
// start after fixing the log finds it running.
|
|
124
|
+
if (found.output !== undefined && found.output !== "log" && logProblem() === null) {
|
|
125
|
+
printLog(true, found.pid, undefined, found.output);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** When the running daemon isn't this CLI's version, how to switch to it. */
|
|
129
|
+
function printVersionHint(found) {
|
|
130
|
+
if (found.older) {
|
|
131
|
+
console.log(dim(` It's from an older version of Engram: run '${engramCommand("stop")}' and then '${engramCommand("start")}' to update it.`));
|
|
132
|
+
}
|
|
133
|
+
else if (found.version && VERSION !== "unknown" && found.version !== VERSION) {
|
|
134
|
+
console.log(dim(` It runs version ${found.version}, and this CLI is ${VERSION}: run '${engramCommand("stop")}' and then '${engramCommand("start")}' to switch.`));
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Wait, up to STOPPING_WAIT_MS, for a daemon that is stopping to exit, and
|
|
139
|
+
* then look again. Its exit, not its socket: it lets the socket go a moment
|
|
140
|
+
* before it exits, and in that moment launchd still names it.
|
|
141
|
+
*/
|
|
142
|
+
async function whileStopping(found) {
|
|
143
|
+
if (found.state !== "stopping")
|
|
144
|
+
return found;
|
|
145
|
+
console.log(dim(`Waiting for the daemon that is stopping (pid ${found.pid}) to finish...`));
|
|
146
|
+
return (await exited(found.pid)) ? findDaemon() : found;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Wait, up to STOPPING_WAIT_MS, for `pid` to exit; true once it has.
|
|
150
|
+
* `slow`: said once, when it takes more than two seconds.
|
|
151
|
+
*/
|
|
152
|
+
async function exited(pid, slow) {
|
|
153
|
+
const start = Date.now();
|
|
154
|
+
while (alive(pid)) {
|
|
155
|
+
const waited = Date.now() - start;
|
|
156
|
+
if (waited >= STOPPING_WAIT_MS)
|
|
157
|
+
return false;
|
|
158
|
+
if (slow && waited >= 2_000) {
|
|
159
|
+
slow();
|
|
160
|
+
slow = undefined;
|
|
161
|
+
}
|
|
162
|
+
await sleep(100);
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
function readLaunchdPid() {
|
|
167
|
+
return isLaunchdInstalled() ? agentPid() : null;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* `sudo engram start` or `sudo engram install` would set capture up for
|
|
171
|
+
* root, not for the user (engram#653), and `sudo engram stop` or
|
|
172
|
+
* `uninstall` would save the setting as root's (engram#682): say so, and
|
|
173
|
+
* change nothing. The CLI's entry refuses them first; this is for any
|
|
174
|
+
* other caller.
|
|
175
|
+
*/
|
|
176
|
+
function refusedAsRoot(command) {
|
|
177
|
+
if (!rootForAnotherUser())
|
|
178
|
+
return false;
|
|
179
|
+
const { problem, fix } = asRootRefusal(command);
|
|
180
|
+
console.error(red(problem));
|
|
181
|
+
console.error(dim(fix));
|
|
182
|
+
process.exitCode = 1;
|
|
183
|
+
return true;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Say that start at login can't be turned on or repaired from this CLI,
|
|
187
|
+
* which runs from a package runner's cache (`where`, engram#665), and how
|
|
188
|
+
* to install the CLI. `again`: the command to run then.
|
|
189
|
+
*/
|
|
190
|
+
function printRunnerRefusal(where, what, again) {
|
|
191
|
+
console.error(red(`Can't ${what} start at login: this Engram runs from ${where}, which can be cleared at any time.`));
|
|
192
|
+
console.error(dim(` Install the CLI with: ${INSTALL_CLI}`));
|
|
193
|
+
console.error(dim(` Then run: ${again}`));
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* `engram install` and `engram start --install` from a CLI that a package
|
|
197
|
+
* runner runs from its cache (engram#665): start at login would name the
|
|
198
|
+
* files there, and once the cache was cleared the daemon no longer started
|
|
199
|
+
* at login, without a word. Say so, and how to install the CLI, and change
|
|
200
|
+
* nothing: no start now either, as the command asked for both.
|
|
201
|
+
*/
|
|
202
|
+
function refusedFromRunnerCache(again) {
|
|
203
|
+
const where = runnerCacheOfThisCli();
|
|
204
|
+
if (where === null)
|
|
205
|
+
return false;
|
|
206
|
+
printRunnerRefusal(where, "turn on", again);
|
|
207
|
+
process.exitCode = 1;
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
export async function daemonStart(_args, flags) {
|
|
211
|
+
if (refusedAsRoot("start"))
|
|
212
|
+
return;
|
|
213
|
+
if ("install" in flags && refusedFromRunnerCache("engram start --install"))
|
|
214
|
+
return;
|
|
215
|
+
await recordCaptureIntent("on", "start");
|
|
216
|
+
// `engram stop` and then `engram start`: the last daemon may still be
|
|
217
|
+
// finishing a send. A worker started now would only wait for it too.
|
|
218
|
+
const found = await whileStopping(await findDaemon());
|
|
219
|
+
if (found.state === "stopping") {
|
|
220
|
+
console.error(red(`The daemon is still stopping (pid ${found.pid}). Run '${engramCommand("start")}' again in a moment.`));
|
|
221
|
+
process.exitCode = 1;
|
|
222
|
+
return;
|
|
223
|
+
}
|
|
224
|
+
// Files in ~/.engram that are another user's (engram#659), and a
|
|
225
|
+
// ~/.engram whose own permissions keep the user out of it (engram#723).
|
|
226
|
+
const foreign = foreignFiles();
|
|
227
|
+
const locked = lockedDir();
|
|
228
|
+
const again = "install" in flags ? engramCommand("start --install") : engramCommand("start");
|
|
229
|
+
if (found.state === "root") {
|
|
230
|
+
// A daemon started beside it would exit at once (engram#680), and with
|
|
231
|
+
// --install, so would the one start at login starts.
|
|
232
|
+
printRootDaemon(found, "No daemon of yours starts while it runs.", { foreign, again });
|
|
233
|
+
process.exitCode = 1;
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
if (found.state === "running" || found.state === "unresponsive") {
|
|
237
|
+
printAlreadyRunning(found);
|
|
238
|
+
// It runs, so they haven't stopped it: only said.
|
|
239
|
+
if (foreign)
|
|
240
|
+
printForeignFiles(foreign, "running");
|
|
241
|
+
if (locked) {
|
|
242
|
+
// It goes on with what it opened as it started (engram#723). Start at
|
|
243
|
+
// login isn't turned on: the daemon launchd or systemd would start,
|
|
244
|
+
// now and at each login, would stop at once.
|
|
245
|
+
const install = "install" in flags;
|
|
246
|
+
printLockedDir(locked, "running", install ? again : undefined);
|
|
247
|
+
// One that can't open the files in its folder captures nothing now.
|
|
248
|
+
if (install || locked.search)
|
|
249
|
+
process.exitCode = 1;
|
|
250
|
+
if (install)
|
|
251
|
+
return;
|
|
252
|
+
}
|
|
253
|
+
// --install still asks for start at login (engram#602). On macOS,
|
|
254
|
+
// loading the launchd agent starts a worker there and then, which finds
|
|
255
|
+
// this daemon and exits (engram#612).
|
|
256
|
+
if ("install" in flags)
|
|
257
|
+
await enableStartAtLogin(true, engramCommand("start --install"));
|
|
258
|
+
printOutsideManager(found);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (foreign || locked) {
|
|
262
|
+
// A daemon started now would stop at once: none is started. Not in the
|
|
263
|
+
// foreground either: the fix is the same, and takes a moment. A log
|
|
264
|
+
// that is another user's only costs the log (engram#679). One in a
|
|
265
|
+
// ~/.engram that keeps them out would stop too (engram#723): said
|
|
266
|
+
// last, with the command to run again once both are fixed.
|
|
267
|
+
const stops = stopsCapture(foreign) || locked !== null;
|
|
268
|
+
if (foreign)
|
|
269
|
+
printForeignFiles(foreign, "stopped", stops && !locked ? "start" : undefined);
|
|
270
|
+
if (locked)
|
|
271
|
+
printLockedDir(locked, "stopped", again);
|
|
272
|
+
if (stops) {
|
|
273
|
+
process.exitCode = 1;
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
// A daemon running as root that nothing ties to this user (engram#680):
|
|
278
|
+
// said, as theirs would run beside it.
|
|
279
|
+
printUntiedRootWorkers([], foreign);
|
|
280
|
+
const foreground = "foreground" in flags || "f" in flags;
|
|
281
|
+
if (foreground) {
|
|
282
|
+
console.log("Starting daemon in foreground...");
|
|
283
|
+
// Import and run worker directly
|
|
284
|
+
await import("./worker.js");
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
// A stale plist survives every CLI upgrade, so check it here rather than
|
|
288
|
+
// only at install time (engram#469), and a broken one too (engram#616).
|
|
289
|
+
// The Windows entry and the systemd unit likewise. With --install, start
|
|
290
|
+
// at login is turned on below, which says what stops it (engram#715).
|
|
291
|
+
// From a package runner's cache, a broken one stays broken: said, as the
|
|
292
|
+
// daemon then starts only when they start it (engram#665).
|
|
293
|
+
const repairs = [
|
|
294
|
+
repairLaunchdIfStale(undefined, { quiet: "install" in flags }),
|
|
295
|
+
repairRunEntryIfStale(),
|
|
296
|
+
repairSystemdUnitIfStale(),
|
|
297
|
+
];
|
|
298
|
+
const runner = repairs.includes("runner") ? runnerCacheOfThisCli() : null;
|
|
299
|
+
if (runner !== null)
|
|
300
|
+
printRunnerRefusal(runner, "repair", "engram install");
|
|
301
|
+
// Start at login first where the service manager starts the daemon then:
|
|
302
|
+
// on macOS, loading the agent has launchd start it (engram#641); on Linux,
|
|
303
|
+
// with the unit enabled, systemd is asked to (engram#689). Then it is
|
|
304
|
+
// theirs, and they start it again after a crash. Not with settings in this
|
|
305
|
+
// environment that their daemon wouldn't have: the daemon is started here
|
|
306
|
+
// then, as before. Nor without a systemd user session: that start at login
|
|
307
|
+
// isn't available is said after the start, as before.
|
|
308
|
+
const platform = process.platform;
|
|
309
|
+
const managerFirst = "install" in flags && !daemonEnvOverrides() && (platform === "darwin" || (platform === "linux" && systemdSession()));
|
|
310
|
+
if (managerFirst && platform === "darwin")
|
|
311
|
+
await enableLaunchdStartAtLogin(false, engramCommand("start --install"));
|
|
312
|
+
if (managerFirst && platform === "linux")
|
|
313
|
+
await enableSystemdStartAtLogin(true, false);
|
|
314
|
+
const started = await startInBackground();
|
|
315
|
+
if (!reportStart(started)) {
|
|
316
|
+
process.exit(1);
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
printLog(true, started.state === "failed" ? null : started.pid);
|
|
320
|
+
console.log(`${dim("DB:")} ${DB_FILE}`);
|
|
321
|
+
if ("install" in flags && !managerFirst) {
|
|
322
|
+
await enableStartAtLogin(true, engramCommand("start --install"));
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Said when the daemon runs, and launchd or systemd isn't running it though
|
|
327
|
+
* it could (engram#641, engram#689): it doesn't start that one again after
|
|
328
|
+
* a crash. A daemon `engram start` spawned before this version, or with a
|
|
329
|
+
* key, a server or the vault key set that their daemon wouldn't have, or
|
|
330
|
+
* one theirs found running as it started. A stop and a start hand it to
|
|
331
|
+
* them. Not when the version hint says to do that anyway. `engram start`
|
|
332
|
+
* and `engram install` say it when they find the daemon running, and
|
|
333
|
+
* `engram status` under its Auto-start line (engram#692).
|
|
334
|
+
*
|
|
335
|
+
* `switchedOn`: the caller asked launchctl already, and launchd hasn't the
|
|
336
|
+
* job switched off.
|
|
337
|
+
*/
|
|
338
|
+
function printOutsideManager(found, switchedOn = false) {
|
|
339
|
+
if (found.state !== "running" || found.older)
|
|
340
|
+
return;
|
|
341
|
+
if (found.version && VERSION !== "unknown" && found.version !== VERSION)
|
|
342
|
+
return;
|
|
343
|
+
const manager = outsideLaunchd(found.pid, switchedOn) ? "launchd" : outsideSystemd(found.pid) ? "systemd" : null;
|
|
344
|
+
if (manager === null)
|
|
345
|
+
return;
|
|
346
|
+
console.log(dim(` The running daemon (pid ${found.pid}) wasn't started by ${manager}, so ${manager} won't restart it after a crash: run '${engramCommand("stop")}' and then '${engramCommand("start")}' to fix that.`));
|
|
347
|
+
}
|
|
348
|
+
/** launchd could run this CLI's daemon, and doesn't run `pid`. */
|
|
349
|
+
function outsideLaunchd(pid, switchedOn) {
|
|
350
|
+
if (!launchdRunsThisCli())
|
|
351
|
+
return false;
|
|
352
|
+
const agent = agentPid();
|
|
353
|
+
if (agent === pid)
|
|
354
|
+
return false;
|
|
355
|
+
if (agent === null && !agentLoaded())
|
|
356
|
+
return false;
|
|
357
|
+
return switchedOn || agentDisabled() !== true;
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* systemd could run this CLI's daemon, and doesn't run `pid`: the unit's
|
|
361
|
+
* MainPID is another, or 0 when it runs none. Not when no service manager
|
|
362
|
+
* answers, which could start it.
|
|
363
|
+
*/
|
|
364
|
+
function outsideSystemd(pid) {
|
|
365
|
+
const unit = systemdMainPid();
|
|
366
|
+
return unit !== null && unit !== pid;
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* The PID of the daemon Engram's unit runs, 0 when it runs none, or null
|
|
370
|
+
* when systemd couldn't run this CLI's daemon, or doesn't answer.
|
|
371
|
+
*/
|
|
372
|
+
function systemdMainPid() {
|
|
373
|
+
if (!systemdRunsThisCli())
|
|
374
|
+
return null;
|
|
375
|
+
const file = systemctlPath();
|
|
376
|
+
return file === null ? null : unitPid(file, "MainPID");
|
|
377
|
+
}
|
|
378
|
+
/**
|
|
379
|
+
* Say what in ~/.engram is another user's, and how to make it the user's
|
|
380
|
+
* (engram#659). `daemon`: whether it runs. `again`: the command they
|
|
381
|
+
* stopped, to run again then. `engram start` and `engram install` say it
|
|
382
|
+
* themselves: the banner before a command isn't shown for them.
|
|
383
|
+
*/
|
|
384
|
+
function printForeignFiles(foreign, daemon, again) {
|
|
385
|
+
console.error(red(foreignFilesProblem(foreign, daemon)));
|
|
386
|
+
console.error(dim(` ${foreignFilesFix(foreign)}`));
|
|
387
|
+
if (again)
|
|
388
|
+
console.error(dim(` Then run '${engramCommand(again)}' again.`));
|
|
389
|
+
}
|
|
390
|
+
/**
|
|
391
|
+
* Say that ~/.engram's own permissions keep the user out of it, what that
|
|
392
|
+
* stops, and what fixes it (engram#723). `daemon`: whether it runs.
|
|
393
|
+
* `again`: the command that did nothing because of it, to run again then.
|
|
394
|
+
* `engram start` and `engram install` say it themselves, as for
|
|
395
|
+
* printForeignFiles.
|
|
396
|
+
*/
|
|
397
|
+
function printLockedDir(locked, daemon, again) {
|
|
398
|
+
console.error(red(lockedDirProblem(locked, daemon)));
|
|
399
|
+
console.error(dim(` ${lockedDirFix(locked)}`));
|
|
400
|
+
if (again)
|
|
401
|
+
console.error(dim(` Then run '${again}' again.`));
|
|
402
|
+
}
|
|
403
|
+
/** Whether they stop the daemon. */
|
|
404
|
+
function stopsCapture(foreign) {
|
|
405
|
+
return foreign !== null && foreign.stopsDaemon;
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Why a running daemon doesn't write to its log, by where its output goes
|
|
409
|
+
* (engram#720).
|
|
410
|
+
*/
|
|
411
|
+
const NOT_THE_LOG = {
|
|
412
|
+
none: "it started without it",
|
|
413
|
+
deleted: "the log it writes to has been deleted or replaced",
|
|
414
|
+
file: "it writes to another file",
|
|
415
|
+
terminal: "it writes to the terminal it was started in",
|
|
416
|
+
};
|
|
417
|
+
const IN_JOURNAL = " systemd keeps its output in the journal: journalctl --user -u engram";
|
|
418
|
+
/**
|
|
419
|
+
* The Log line of `engram start` and `engram status`: where the daemon's
|
|
420
|
+
* log is, or that it can't be written, so the daemon runs without it
|
|
421
|
+
* (engram#679), and what fixes that. `running`: whether a daemon runs,
|
|
422
|
+
* and `pid`, its PID where that is known: systemd keeps what one it
|
|
423
|
+
* started writes in the journal. `said`: a fix said above it, for
|
|
424
|
+
* ~/.engram (engram#723), which isn't said again. `output`: where the
|
|
425
|
+
* running daemon's output goes, when it says (engram#720), given only for
|
|
426
|
+
* one that runs. One that runs keeps the output it was started with,
|
|
427
|
+
* whatever is done to the log since, until it is started again.
|
|
428
|
+
*/
|
|
429
|
+
function printLog(running, pid = null, said, output) {
|
|
430
|
+
const problem = logProblem();
|
|
431
|
+
// Asked only when it would be said: it runs systemctl.
|
|
432
|
+
const journal = () => pid !== null && systemdMainPid() === pid;
|
|
433
|
+
if (problem === null) {
|
|
434
|
+
if (output === undefined || output === "log") {
|
|
435
|
+
console.log(`${dim("Log:")} ${LOG_FILE}`);
|
|
436
|
+
return;
|
|
437
|
+
}
|
|
438
|
+
console.log(`${dim("Log:")} ${LOG_FILE}, but the daemon doesn't write to it: ${NOT_THE_LOG[output]}.`);
|
|
439
|
+
if (output === "none" && journal())
|
|
440
|
+
console.log(dim(IN_JOURNAL));
|
|
441
|
+
// Not one in the foreground, which was started to write there.
|
|
442
|
+
if (output !== "terminal")
|
|
443
|
+
console.log(dim(` '${engramCommand("stop")}' and then '${engramCommand("start")}' have the daemon write to it.`));
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
const fix = logFix(problem);
|
|
447
|
+
const fixLine = fix !== null && fix !== said ? dim(` To fix it, run: ${fix}`) : null;
|
|
448
|
+
if (output === "log") {
|
|
449
|
+
// It opened the log as it started, and goes on writing to it. Started
|
|
450
|
+
// again before the log is fixed, it would run without it: no stop and
|
|
451
|
+
// start is suggested.
|
|
452
|
+
console.log(`${dim("Log:")} ${LOG_FILE}. The daemon writes to it, but it can't be opened for writing now (${problem}), so a daemon started again would run without it.`);
|
|
453
|
+
if (fixLine)
|
|
454
|
+
console.log(fixLine);
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
console.log(`${dim("Log:")} ${LOG_FILE} can't be written (${problem}), so the daemon ${running ? "runs" : "will run"} without it.`);
|
|
458
|
+
if ((output === undefined || output === "none") && journal())
|
|
459
|
+
console.log(dim(IN_JOURNAL));
|
|
460
|
+
if (fixLine)
|
|
461
|
+
console.log(fixLine);
|
|
462
|
+
if (running && output !== "terminal") {
|
|
463
|
+
console.log(dim(` Once it can be written, '${engramCommand("stop")}' and then '${engramCommand("start")}' have the daemon write to it again.`));
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
/** " Its log: …", after a sentence; nothing while it can't be written (engram#679). */
|
|
467
|
+
function itsLog() {
|
|
468
|
+
return logProblem() === null ? ` Its log: ${LOG_FILE}` : "";
|
|
469
|
+
}
|
|
470
|
+
/**
|
|
471
|
+
* `chmod u+w` for the log, or for ~/.engram when the log isn't there, when
|
|
472
|
+
* the user's own lacks its write permission and that is all that's wrong.
|
|
473
|
+
* Null otherwise: another user's is said with the rest that is theirs
|
|
474
|
+
* (engram#659), with its chown.
|
|
475
|
+
*/
|
|
476
|
+
function logFix(problem) {
|
|
477
|
+
if (problem !== "EACCES" || process.platform === "win32")
|
|
478
|
+
return null;
|
|
479
|
+
for (const [path, shown] of [
|
|
480
|
+
[LOG_FILE, "~/.engram/daemon.log"],
|
|
481
|
+
[ENGRAM_DIR, "~/.engram"],
|
|
482
|
+
]) {
|
|
483
|
+
let st;
|
|
484
|
+
try {
|
|
485
|
+
st = statSync(path);
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
continue; // not there: the folder it is made in is what matters
|
|
489
|
+
}
|
|
490
|
+
if (st.uid !== process.geteuid?.())
|
|
491
|
+
return null;
|
|
492
|
+
return (st.mode & 0o200) === 0 ? `chmod u+w ${shown}` : null;
|
|
493
|
+
}
|
|
494
|
+
return null;
|
|
495
|
+
}
|
|
496
|
+
/**
|
|
497
|
+
* engram#680, for `engram start`, `stop` and `install`, which do nothing
|
|
498
|
+
* while a daemon runs as root for the user. `why`: what that means for the
|
|
499
|
+
* command. Then what stops it, and what makes capture theirs again: the
|
|
500
|
+
* files it made (`foreign`), made theirs, and `again`, the command to run
|
|
501
|
+
* again, if any.
|
|
502
|
+
*/
|
|
503
|
+
function printRootDaemon(root, why, { foreign, again }) {
|
|
504
|
+
const { problem, fixes } = rootDaemonLines(root);
|
|
505
|
+
console.error(red(`${problem} ${why}`));
|
|
506
|
+
for (const fix of fixes)
|
|
507
|
+
console.error(dim(` ${fix}`));
|
|
508
|
+
if (foreign) {
|
|
509
|
+
console.error(red(foreignFilesProblem(foreign)));
|
|
510
|
+
console.error(dim(` ${foreignFilesFix(foreign, true)}`));
|
|
511
|
+
}
|
|
512
|
+
if (again)
|
|
513
|
+
console.error(dim(` Then run '${again}' again.`));
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Daemons running as root that nothing ties to this user, besides `known`
|
|
517
|
+
* (engram#680): only said. Most likely theirs, from `sudo engram start`
|
|
518
|
+
* with a CLI that then removed its PID file, but that can't be told.
|
|
519
|
+
*/
|
|
520
|
+
function printUntiedRootWorkers(known, foreign) {
|
|
521
|
+
const untied = untiedRootWorkers(known, foreign);
|
|
522
|
+
if (untied.length > 0)
|
|
523
|
+
console.error(red(untiedRootLine(untied)));
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* How long before `engram start` gives up waiting on the Windows
|
|
527
|
+
* supervisor's first worker the supervisor stops reporting that it couldn't
|
|
528
|
+
* start (engram#613), so that a failure it reports is always seen here. It
|
|
529
|
+
* starts one that fails after that again.
|
|
530
|
+
*/
|
|
531
|
+
const REPORT_MARGIN_MS = 2_000;
|
|
532
|
+
/**
|
|
533
|
+
* Start the daemon in the background, and wait for it to be ready (see
|
|
534
|
+
* waitForWorker). On Windows through the supervisor, which starts it again
|
|
535
|
+
* after an error (engram#613). On macOS through launchd, which does that
|
|
536
|
+
* too, when its agent is loaded (engram#641), and on Linux through systemd,
|
|
537
|
+
* when its unit is enabled (engram#689).
|
|
538
|
+
*/
|
|
539
|
+
function startInBackground() {
|
|
540
|
+
if (process.platform === "win32") {
|
|
541
|
+
const reportUntil = Date.now() + START_WAIT_MS - REPORT_MARGIN_MS;
|
|
542
|
+
return waitForWorker(spawnSupervisor(reportUntil), START_WAIT_MS, { supervisor: true });
|
|
543
|
+
}
|
|
544
|
+
const manager = serviceManager();
|
|
545
|
+
if (manager)
|
|
546
|
+
return startThroughManager(manager);
|
|
547
|
+
return waitForWorker(spawnWorker());
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Settings in this command's environment that a daemon spawned from it
|
|
551
|
+
* inherits, and one the service manager starts doesn't have: launchd gives
|
|
552
|
+
* its job only the plist's environment (engram#641), and systemd its unit
|
|
553
|
+
* only the unit's and its own (engram#689). A key or a server set here, or
|
|
554
|
+
* the vault key, which the daemon scrubs vault values with, unless
|
|
555
|
+
* ~/.engram/vault-key holds it, which their daemon reads (engram#690). With
|
|
556
|
+
* one of them set, the daemon is spawned, as before.
|
|
557
|
+
*/
|
|
558
|
+
function daemonEnvOverrides() {
|
|
559
|
+
return Boolean(process.env.ENGRAM_API_KEY ||
|
|
560
|
+
process.env.ENGRAM_BASE_URL?.trim() ||
|
|
561
|
+
(process.env.ENGRAM_VAULT_KEY && !envVaultKeySaved()));
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* This command's environment without the settings in it a daemon spawned
|
|
565
|
+
* from it would take over ~/.engram's (daemonEnvOverrides): the key, the
|
|
566
|
+
* server and the vault key. For one that takes over from the daemon
|
|
567
|
+
* launchd ran, which read them from ~/.engram (engram#667): the account it
|
|
568
|
+
* captures for, and how it scrubs vault values, stay as they were.
|
|
569
|
+
*/
|
|
570
|
+
function withoutEnvOverrides() {
|
|
571
|
+
const env = { ...process.env };
|
|
572
|
+
delete env.ENGRAM_API_KEY;
|
|
573
|
+
delete env.ENGRAM_BASE_URL;
|
|
574
|
+
delete env.ENGRAM_VAULT_KEY;
|
|
575
|
+
return env;
|
|
576
|
+
}
|
|
577
|
+
/**
|
|
578
|
+
* The agent is ours and current, for this CLI (plistForThisCli), and the
|
|
579
|
+
* daemon launchd starts from it has everything this command's environment
|
|
580
|
+
* would give one (daemonEnvOverrides). No launchctl call.
|
|
581
|
+
*/
|
|
582
|
+
function launchdRunsThisCli() {
|
|
583
|
+
if (process.platform !== "darwin" || daemonEnvOverrides() || !isLaunchdInstalled())
|
|
584
|
+
return false;
|
|
585
|
+
const made = plistForThisCli();
|
|
586
|
+
return "text" in made && installedPlistText() === made.text;
|
|
587
|
+
}
|
|
588
|
+
/**
|
|
589
|
+
* launchd can start this CLI's daemon (engram#641): launchdRunsThisCli,
|
|
590
|
+
* and the agent is loaded and not switched off. A plist of another CLI's,
|
|
591
|
+
* or one not loaded, is left as it is, and the daemon is spawned.
|
|
592
|
+
*/
|
|
593
|
+
function launchdCanStart() {
|
|
594
|
+
return launchdRunsThisCli() && agentLoaded() && agentDisabled() !== true;
|
|
595
|
+
}
|
|
596
|
+
/**
|
|
597
|
+
* The service manager that can start this CLI's daemon now: launchd, when
|
|
598
|
+
* its agent is loaded and not switched off (launchdCanStart, engram#641), or
|
|
599
|
+
* systemd, when its unit is ours, enabled and current, and the user's
|
|
600
|
+
* service manager answers (engram#689). Null when neither can: the daemon is
|
|
601
|
+
* spawned then, as before, and nothing more is said.
|
|
602
|
+
*/
|
|
603
|
+
function serviceManager() {
|
|
604
|
+
if (launchdCanStart())
|
|
605
|
+
return { name: "launchd", tool: "launchctl", start: kickstartAgent, pid: agentPid };
|
|
606
|
+
if (!systemdRunsThisCli())
|
|
607
|
+
return null;
|
|
608
|
+
const file = systemctlPath();
|
|
609
|
+
if (file === null || !systemdReachable(file))
|
|
610
|
+
return null;
|
|
611
|
+
return {
|
|
612
|
+
name: "systemd",
|
|
613
|
+
tool: "systemctl",
|
|
614
|
+
start: () => startUnit(file),
|
|
615
|
+
// The last process systemd started for the unit, which it names until
|
|
616
|
+
// the next: one that exits as it starts is still seen to have started.
|
|
617
|
+
// 0 before it has started any.
|
|
618
|
+
pid: () => unitPid(file, "ExecMainPID") || null,
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Have the service manager start the daemon, and wait for it to be ready
|
|
623
|
+
* (engram#641, engram#689). It starts the daemon it runs again after a
|
|
624
|
+
* crash; one spawned, it doesn't. The daemon is spawned, as before, when it
|
|
625
|
+
* won't start it, or hasn't within MANAGER_SPAWN_WAIT_MS: said, since that
|
|
626
|
+
* one isn't restarted.
|
|
627
|
+
*/
|
|
628
|
+
async function startThroughManager(manager) {
|
|
629
|
+
const refused = manager.start();
|
|
630
|
+
if (refused === null) {
|
|
631
|
+
const started = await waitForAgent(START_WAIT_MS, MANAGER_SPAWN_WAIT_MS, manager.pid);
|
|
632
|
+
if (started !== null)
|
|
633
|
+
return started;
|
|
634
|
+
}
|
|
635
|
+
const why = refused === null ? "didn't start the daemon in time" : `couldn't start the daemon (${manager.tool}: ${refused})`;
|
|
636
|
+
console.log(dim(` ${manager.name} ${why}, so it is started directly, and won't be restarted after a crash.`));
|
|
637
|
+
return waitForWorker(spawnWorker());
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* How long `engram start` waits for launchd or systemd to start the daemon
|
|
641
|
+
* it asked for before spawning one itself. They start it at once, as a rule.
|
|
642
|
+
*/
|
|
643
|
+
const MANAGER_SPAWN_WAIT_MS = 3_000;
|
|
644
|
+
/**
|
|
645
|
+
* Wait for the daemon the service manager was asked to start (kickstartAgent,
|
|
646
|
+
* startUnit) to answer on its socket as ready, as waitForWorker waits for
|
|
647
|
+
* one spawned. Its PID is the service manager's (`pidOf`: agentPid by
|
|
648
|
+
* default), asked for at once: launchd names the process as it starts it,
|
|
649
|
+
* and systemd keeps naming the last one it started, so one that exits as it
|
|
650
|
+
* starts is still seen to have started. Gives up as soon as that process
|
|
651
|
+
* has exited with nothing holding the socket: it couldn't start. A daemon
|
|
652
|
+
* that answers, ready, is the one running: the service manager's, or one
|
|
653
|
+
* started beside it, which the service manager's leaves the capture to
|
|
654
|
+
* (engram#612).
|
|
655
|
+
*
|
|
656
|
+
* Null when the service manager hasn't started a process within
|
|
657
|
+
* `spawnWaitMs`: the caller spawns the daemon then. Exported for tests.
|
|
658
|
+
*/
|
|
659
|
+
export async function waitForAgent(timeoutMs = START_WAIT_MS, spawnWaitMs = MANAGER_SPAWN_WAIT_MS, pidOf = agentPid) {
|
|
660
|
+
const start = Date.now();
|
|
661
|
+
const deadline = start + timeoutMs;
|
|
662
|
+
let pid = pidOf();
|
|
663
|
+
while (Date.now() < deadline) {
|
|
664
|
+
await sleep(100);
|
|
665
|
+
const probe = await probeDaemon({ timeoutMs: 1_000 });
|
|
666
|
+
if (probe.state === "answered" && probe.info.ready && !probe.info.stopping) {
|
|
667
|
+
return { state: "running", pid: probe.info.pid };
|
|
668
|
+
}
|
|
669
|
+
pid ??= pidOf();
|
|
670
|
+
// A daemon holds the socket, and is still loading.
|
|
671
|
+
if (probe.state === "answered" || probe.state === "silent")
|
|
672
|
+
continue;
|
|
673
|
+
if (pid === null) {
|
|
674
|
+
if (Date.now() - start >= spawnWaitMs)
|
|
675
|
+
return null;
|
|
676
|
+
continue;
|
|
677
|
+
}
|
|
678
|
+
// No socket on this machine (see daemonEndpoint): the PID file is all there is.
|
|
679
|
+
if (probe.state === "unavailable" && pidInFile() === pid)
|
|
680
|
+
return { state: "running", pid };
|
|
681
|
+
if (!alive(pid))
|
|
682
|
+
return { state: "failed" };
|
|
683
|
+
}
|
|
684
|
+
return { state: "starting", pid };
|
|
685
|
+
}
|
|
686
|
+
/** Say how a worker just spawned got on; false when it didn't start. */
|
|
687
|
+
function reportStart(started) {
|
|
688
|
+
if (started.state === "failed") {
|
|
689
|
+
printStartFailed("Daemon failed to start");
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
if (started.state === "running") {
|
|
693
|
+
console.log(`${bold("Engram daemon started")} (pid ${started.pid})`);
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
// Still loading: most often the preflight rebuilding better-sqlite3 for
|
|
697
|
+
// a Node it wasn't built for, which takes a minute or two.
|
|
698
|
+
const pid = started.pid === null ? "" : ` (pid ${started.pid})`;
|
|
699
|
+
console.log(`${bold("Engram daemon is starting")}${pid} — this one is taking a while`);
|
|
700
|
+
console.log(dim(` Check on it with '${engramCommand("status")}' in a minute.`));
|
|
701
|
+
}
|
|
702
|
+
return true;
|
|
703
|
+
}
|
|
704
|
+
/** Say that a worker just spawned didn't start, `what` first, and where to see why. */
|
|
705
|
+
function printStartFailed(what) {
|
|
706
|
+
const problem = logProblem();
|
|
707
|
+
if (problem === null) {
|
|
708
|
+
console.error(`${what}. Check the log:`);
|
|
709
|
+
console.error(` ${process.platform === "win32" ? "type" : "cat"} "${LOG_FILE}"`);
|
|
710
|
+
}
|
|
711
|
+
else {
|
|
712
|
+
// It ran without one (engram#679), so what it said is gone.
|
|
713
|
+
console.error(`${what}, and its log can't be written (${problem}). To see why, run it here:`);
|
|
714
|
+
console.error(` ${engramCommand("start --foreground")}`);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
/**
|
|
718
|
+
* Wait for a worker just spawned to answer on the daemon's socket as ready:
|
|
719
|
+
* past the preflight, capture set up. A fixed half-second pause was too
|
|
720
|
+
* short on Windows, where Node loads slowly the first time while antivirus
|
|
721
|
+
* scans each file: `engram start` reported a failure, exited 1 and skipped
|
|
722
|
+
* --install, and the daemon came up a moment later (engram#602). Gives up as
|
|
723
|
+
* soon as the worker exits with an error.
|
|
724
|
+
*
|
|
725
|
+
* `supervisor`: `child` is the Windows supervisor (engram#613), which starts
|
|
726
|
+
* the worker, so the worker's PID is the one that answers. While this
|
|
727
|
+
* waits, the supervisor exits only when its first worker does: with
|
|
728
|
+
* START_FAILED_EXIT when that one couldn't start, and 0 when it found
|
|
729
|
+
* another daemon running. After any other error it starts the worker again.
|
|
730
|
+
*/
|
|
731
|
+
export async function waitForWorker(child, timeoutMs = START_WAIT_MS, options = {}) {
|
|
732
|
+
// In an object: TypeScript doesn't see the callbacks assign plain locals.
|
|
733
|
+
const ended = {};
|
|
734
|
+
child.once("exit", (code) => {
|
|
735
|
+
ended.code = code;
|
|
736
|
+
});
|
|
737
|
+
child.once("error", () => {
|
|
738
|
+
ended.error = true;
|
|
739
|
+
});
|
|
740
|
+
const ready = async (pid) => {
|
|
741
|
+
if (options.supervisor)
|
|
742
|
+
return supervisedReady();
|
|
743
|
+
return (await answersReady(pid)) ? pid : null;
|
|
744
|
+
};
|
|
745
|
+
const deadline = Date.now() + timeoutMs;
|
|
746
|
+
while (Date.now() < deadline) {
|
|
747
|
+
await sleep(100);
|
|
748
|
+
if (ended.error || child.pid === undefined)
|
|
749
|
+
return { state: "failed" };
|
|
750
|
+
if (ended.code !== undefined)
|
|
751
|
+
return ended.code === 0 ? waitForOther(deadline) : { state: "failed" };
|
|
752
|
+
const pid = await ready(child.pid);
|
|
753
|
+
if (pid !== null)
|
|
754
|
+
return { state: "running", pid };
|
|
755
|
+
}
|
|
756
|
+
if (ended.error || child.pid === undefined)
|
|
757
|
+
return { state: "failed" };
|
|
758
|
+
if (ended.code !== undefined)
|
|
759
|
+
return ended.code === 0 ? waitForOther(0) : { state: "failed" };
|
|
760
|
+
return { state: "starting", pid: options.supervisor ? null : child.pid };
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* The PID of the daemon that answers, ready and not stopping: the
|
|
764
|
+
* supervisor's worker, or one started beside it, which that worker then
|
|
765
|
+
* leaves the capture to. Only on Windows, where the named pipe can always
|
|
766
|
+
* be used.
|
|
767
|
+
*/
|
|
768
|
+
async function supervisedReady() {
|
|
769
|
+
const probe = await probeDaemon({ timeoutMs: 1_000 });
|
|
770
|
+
return probe.state === "answered" && probe.info.ready && !probe.info.stopping ? probe.info.pid : null;
|
|
771
|
+
}
|
|
772
|
+
/** Whether `pid` answers on the daemon's socket, ready; where there is no socket, whether the PID file names it. */
|
|
773
|
+
async function answersReady(pid) {
|
|
774
|
+
const probe = await probeDaemon({ timeoutMs: 1_000 });
|
|
775
|
+
if (probe.state === "answered")
|
|
776
|
+
return probe.info.pid === pid && probe.info.ready;
|
|
777
|
+
// No socket on this machine (see daemonEndpoint): the PID file is all there is.
|
|
778
|
+
return probe.state === "unavailable" && pidInFile() === pid;
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* The worker exited 0 as soon as it started: another daemon was running, or
|
|
782
|
+
* started at that moment, and it left the capture to that one (engram#612).
|
|
783
|
+
* launchd starts one beside `engram start` when it loads an updated plist.
|
|
784
|
+
* Waits, until `deadline`, for that daemon to be ready.
|
|
785
|
+
*/
|
|
786
|
+
async function waitForOther(deadline) {
|
|
787
|
+
for (;;) {
|
|
788
|
+
const found = await findDaemon(1_000);
|
|
789
|
+
if (found.state === "unresponsive")
|
|
790
|
+
return { state: "starting", pid: found.pid };
|
|
791
|
+
if (found.state !== "running")
|
|
792
|
+
return { state: "failed" };
|
|
793
|
+
if (found.ready)
|
|
794
|
+
return { state: "running", pid: found.pid };
|
|
795
|
+
if (Date.now() >= deadline)
|
|
796
|
+
return { state: "starting", pid: found.pid };
|
|
797
|
+
await sleep(100);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
/**
|
|
801
|
+
* Record whether capture is on, for the capture check after other commands
|
|
802
|
+
* (autoEnableCapture). `command`: the one that was run.
|
|
803
|
+
*
|
|
804
|
+
* A config.json that can't be read isn't saved over (engram#673): it holds
|
|
805
|
+
* the API key and the folders excluded from capture. Read leniently, as it
|
|
806
|
+
* was, `engram stop` replaced it with only `autocapture`. Nothing is lost
|
|
807
|
+
* by not recording "on": nothing turns capture off meanwhile, and the
|
|
808
|
+
* banner before the command said what is wrong with the file.
|
|
809
|
+
*
|
|
810
|
+
* A save that fails never stops the command: the daemon is stopped or
|
|
811
|
+
* started all the same. But it is said, with what fixes it (engram#681).
|
|
812
|
+
* Not recording "off" means the next command starts the daemon again, so
|
|
813
|
+
* the exit says that too. Not recording "on" over an "off" means no other
|
|
814
|
+
* command starts it again after it stops; over anything else, nothing
|
|
815
|
+
* changes, so nothing is said.
|
|
816
|
+
*/
|
|
817
|
+
async function recordCaptureIntent(v, command) {
|
|
818
|
+
let config;
|
|
34
819
|
try {
|
|
35
|
-
|
|
36
|
-
|
|
820
|
+
config = await loadConfigStrict();
|
|
821
|
+
}
|
|
822
|
+
catch (err) {
|
|
823
|
+
if (err instanceof ConfigUnreadable && err.empty) {
|
|
824
|
+
printEmptyConfigNote();
|
|
825
|
+
config = {};
|
|
826
|
+
}
|
|
827
|
+
else {
|
|
828
|
+
if (v === "off") {
|
|
829
|
+
// The daemon still stops, but capture comes back on with the next
|
|
830
|
+
// command once the file is fixed: not all that was asked, so the
|
|
831
|
+
// exit says so to a script that runs `engram stop`. In a ~/.engram
|
|
832
|
+
// that can't be searched, it is the folder that needs the fix, not
|
|
833
|
+
// the file (engram#723).
|
|
834
|
+
process.exitCode = 1;
|
|
835
|
+
const locked = err instanceof ConfigUnreadable ? lockedConfigDir(err) : null;
|
|
836
|
+
const why = locked
|
|
837
|
+
? lockedDirReason("opening config.json")
|
|
838
|
+
: err instanceof ConfigUnreadable
|
|
839
|
+
? err.message
|
|
840
|
+
: "~/.engram/config.json can't be read";
|
|
841
|
+
console.error(red(`Couldn't record that capture is off: ${why}.`));
|
|
842
|
+
const again = `run '${engramCommand(command)}' again, or the next engram command turns capture back on.`;
|
|
843
|
+
if (locked) {
|
|
844
|
+
console.error(dim(` ${lockedDirFix(locked)}`));
|
|
845
|
+
console.error(dim(` Then ${again}`));
|
|
846
|
+
}
|
|
847
|
+
else {
|
|
848
|
+
console.error(dim(` Once it's fixed, ${again}`));
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
return;
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
const was = config.autocapture;
|
|
855
|
+
try {
|
|
856
|
+
config.autocapture = v;
|
|
857
|
+
await saveConfig(config);
|
|
858
|
+
}
|
|
859
|
+
catch (err) {
|
|
860
|
+
const { problem, fix } = saveFailure(err);
|
|
861
|
+
if (v === "off") {
|
|
862
|
+
process.exitCode = 1;
|
|
863
|
+
console.error(red(`Couldn't record that capture is off: ${problem}.`));
|
|
864
|
+
const again = `run '${engramCommand(command)}' again, or the next engram command turns capture back on.`;
|
|
865
|
+
if (fix) {
|
|
866
|
+
console.error(dim(` To fix it, run: ${fix}`));
|
|
867
|
+
console.error(dim(` Then ${again}`));
|
|
868
|
+
}
|
|
869
|
+
else {
|
|
870
|
+
console.error(dim(` Once it's fixed, ${again}`));
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
else if (was === "off" && !lockedDir()) {
|
|
874
|
+
// In a ~/.engram that keeps them out (engram#723), `engram start` and
|
|
875
|
+
// `engram install` start nothing, and say so with the fix.
|
|
876
|
+
console.error(dim(`Note: couldn't record that capture is on: ${problem}.`));
|
|
877
|
+
console.error(dim(" Until it is, other engram commands won't start the daemon again if it stops."));
|
|
878
|
+
if (fix) {
|
|
879
|
+
console.error(dim(` To fix it, run: ${fix}`));
|
|
880
|
+
console.error(dim(` Then run '${engramCommand(command)}' again.`));
|
|
881
|
+
}
|
|
882
|
+
else {
|
|
883
|
+
console.error(dim(` Once it's fixed, run '${engramCommand(command)}' again.`));
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
}
|
|
888
|
+
/**
|
|
889
|
+
* How long `engram stop` waits on Windows for the daemon to take its request
|
|
890
|
+
* to stop (engram#613). The daemon looks for one every second.
|
|
891
|
+
*/
|
|
892
|
+
export const STOP_PICKUP_MS = 10_000;
|
|
893
|
+
/**
|
|
894
|
+
* Stop the daemon: only a process confirmed to be it is signalled
|
|
895
|
+
* (engram#612), and this waits for it to finish a send in progress and exit,
|
|
896
|
+
* so an `engram start` straight after starts a new one.
|
|
897
|
+
*
|
|
898
|
+
* On Windows a signal can't be caught there: process.kill ends the process
|
|
899
|
+
* wherever it is (TerminateProcess), in the middle of a send or of writing
|
|
900
|
+
* its queue. So there `engram stop` asks the daemon to stop through
|
|
901
|
+
* STOP_FILE, and it stops as it does for SIGTERM elsewhere (engram#613).
|
|
902
|
+
* Only a daemon from before that, or one that doesn't take the request in
|
|
903
|
+
* STOP_PICKUP_MS, is ended outright. Nothing queued is lost either way: what
|
|
904
|
+
* it was sending is sent again when it next starts. One that holds its pipe
|
|
905
|
+
* and doesn't answer is left running there: that is most often a daemon
|
|
906
|
+
* rebuilding better-sqlite3, which ending it would cut off half done
|
|
907
|
+
* (engram#640).
|
|
908
|
+
*/
|
|
909
|
+
export async function daemonStop() {
|
|
910
|
+
// Run as root, it would save the setting as root's (engram#682).
|
|
911
|
+
if (refusedAsRoot("stop"))
|
|
912
|
+
return;
|
|
913
|
+
await recordCaptureIntent("off", "stop");
|
|
914
|
+
const found = await findDaemon();
|
|
915
|
+
if (found.state === "stopped") {
|
|
916
|
+
// A supervisor waiting to start the daemon again after an error finds
|
|
917
|
+
// this, and doesn't (engram#613).
|
|
918
|
+
if (process.platform === "win32")
|
|
919
|
+
writeStopRequest({ pid: null });
|
|
920
|
+
if (lockedDir()?.search) {
|
|
921
|
+
// What finds one can't be looked at (engram#723). The fix was said
|
|
922
|
+
// with capture off, which couldn't be recorded either.
|
|
923
|
+
console.error(red("No daemon was found, but one may still be running: ~/.engram's permissions keep you from opening its socket and PID file."));
|
|
924
|
+
process.exitCode = 1;
|
|
925
|
+
}
|
|
926
|
+
else {
|
|
927
|
+
console.log("Daemon is not running.");
|
|
928
|
+
}
|
|
929
|
+
printUntiedRootWorkers([], foreignFiles());
|
|
930
|
+
return;
|
|
931
|
+
}
|
|
932
|
+
if (found.state === "root") {
|
|
933
|
+
// It can't be signalled, and launchd may run it (engram#680).
|
|
934
|
+
printRootDaemon(found, `'${engramCommand("stop")}' can't stop it.`, { foreign: foreignFiles() });
|
|
935
|
+
process.exitCode = 1;
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
if (found.pid === null) {
|
|
939
|
+
console.error(red("The daemon isn't answering, and no process could be confirmed as it, so nothing was stopped."));
|
|
940
|
+
console.error(dim(` It may be busy, or still starting: try again in a minute.${itsLog()}`));
|
|
941
|
+
process.exitCode = 1;
|
|
942
|
+
return;
|
|
943
|
+
}
|
|
944
|
+
const pid = found.pid;
|
|
945
|
+
// One that answers as stopping is on its way out already, and is only
|
|
946
|
+
// waited for.
|
|
947
|
+
if (found.state !== "stopping") {
|
|
948
|
+
// A named pipe's name is one namespace for the whole machine, so on
|
|
949
|
+
// Windows the PID file, which only this user can write, must name the
|
|
950
|
+
// process the pipe's answer gives.
|
|
951
|
+
if (process.platform === "win32" && pidInFile() !== pid) {
|
|
952
|
+
console.error(red(`The daemon's pipe gives pid ${pid}, and ~/.engram/daemon.pid doesn't name it, so nothing was stopped.`));
|
|
953
|
+
process.exitCode = 1;
|
|
954
|
+
return;
|
|
955
|
+
}
|
|
956
|
+
if (process.platform === "win32" && found.state === "unresponsive") {
|
|
957
|
+
console.error(red(`The daemon (pid ${pid}) isn't answering right now, so it wasn't stopped.`));
|
|
958
|
+
console.error(dim(` It may be busy, or still starting: try again in a minute.${itsLog()}`));
|
|
959
|
+
process.exitCode = 1;
|
|
960
|
+
return;
|
|
961
|
+
}
|
|
962
|
+
const asked = process.platform === "win32" && found.state === "running" && found.stopFile && found.id
|
|
963
|
+
? await askToStop(pid, found.id)
|
|
964
|
+
: "unasked";
|
|
965
|
+
if (asked !== "taken") {
|
|
37
966
|
try {
|
|
38
|
-
process.kill(pid,
|
|
39
|
-
return pid;
|
|
967
|
+
process.kill(pid, "SIGTERM");
|
|
40
968
|
}
|
|
41
|
-
catch {
|
|
42
|
-
|
|
43
|
-
|
|
969
|
+
catch (err) {
|
|
970
|
+
if (err.code === "ESRCH") {
|
|
971
|
+
removePidFileIf(pid);
|
|
972
|
+
console.log("Daemon is not running.");
|
|
973
|
+
return;
|
|
974
|
+
}
|
|
975
|
+
console.error(red(`Failed to stop daemon (pid ${pid})`));
|
|
976
|
+
// Root's, as a rule: `sudo engram start`, which a CLI from before
|
|
977
|
+
// engram#653 ran as root (engram#659).
|
|
978
|
+
if (process.platform !== "win32" && err.code === "EPERM") {
|
|
979
|
+
console.error(dim(` It runs as another user (root, if it was started with sudo). Stop it with: sudo kill ${pid}`));
|
|
44
980
|
}
|
|
45
|
-
|
|
981
|
+
process.exitCode = 1;
|
|
982
|
+
return;
|
|
983
|
+
}
|
|
984
|
+
if (asked === "ignored") {
|
|
985
|
+
console.log(dim(` It didn't take the request to stop within ${STOP_PICKUP_MS / 1000}s, so it was ended.`));
|
|
986
|
+
console.log(dim(" Nothing queued is lost: what it hadn't sent goes when it next starts."));
|
|
987
|
+
}
|
|
988
|
+
else if (asked === "unwritten") {
|
|
989
|
+
// Its supervisor finds no request, so it takes this for a crash.
|
|
990
|
+
console.log(dim(` Couldn't write ${STOP_FILE}, so it was ended outright, and may start again in a few seconds.`));
|
|
991
|
+
console.log(dim(` If '${engramCommand("status")}' shows it running again, run '${engramCommand("stop")}' again.`));
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
const gone = await exited(pid, () => console.log(dim(" Waiting for it to finish what it was sending...")));
|
|
996
|
+
if (!gone) {
|
|
997
|
+
console.log(`Asked the daemon to stop (pid ${pid}); it is still finishing.`);
|
|
998
|
+
return;
|
|
999
|
+
}
|
|
1000
|
+
// Its own exit removes the PID file; one killed outright can't.
|
|
1001
|
+
removePidFileIf(pid);
|
|
1002
|
+
console.log(`Daemon stopped (pid ${pid})`);
|
|
1003
|
+
// One running as root beside it still captures (engram#680): capture
|
|
1004
|
+
// hasn't stopped.
|
|
1005
|
+
const root = findRootDaemon();
|
|
1006
|
+
const foreign = foreignFiles();
|
|
1007
|
+
if (root !== null) {
|
|
1008
|
+
printRootDaemon(root, `'${engramCommand("stop")}' can't stop it.`, { foreign });
|
|
1009
|
+
process.exitCode = 1;
|
|
1010
|
+
}
|
|
1011
|
+
printUntiedRootWorkers([pid, root?.pid ?? null, root?.job?.pid ?? null], foreign);
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Write a stop request to STOP_FILE (engram#613); false when it couldn't be
|
|
1015
|
+
* written. Through a temp file, so the daemon never reads half of one.
|
|
1016
|
+
*/
|
|
1017
|
+
function writeStopRequest(request) {
|
|
1018
|
+
try {
|
|
1019
|
+
writePrivateFileSync(STOP_FILE, `${JSON.stringify(request)}\n`, { durable: false });
|
|
1020
|
+
return true;
|
|
1021
|
+
}
|
|
1022
|
+
catch {
|
|
1023
|
+
return false;
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
/**
|
|
1027
|
+
* Ask the daemon `pid`, whose answer gave `id`, to stop, and wait up to
|
|
1028
|
+
* STOP_PICKUP_MS for it to take the request: it then answers as stopping,
|
|
1029
|
+
* or has let its pipe go. "taken": it did, or it is gone. "ignored": it
|
|
1030
|
+
* didn't, and is still the daemon, by its answer or by the PID file. The
|
|
1031
|
+
* request is left in place then, so the supervisor doesn't start it again
|
|
1032
|
+
* once it is ended. "unwritten": the request couldn't be written.
|
|
1033
|
+
*/
|
|
1034
|
+
async function askToStop(pid, id) {
|
|
1035
|
+
if (!writeStopRequest({ pid, id }))
|
|
1036
|
+
return "unwritten";
|
|
1037
|
+
const deadline = Date.now() + STOP_PICKUP_MS;
|
|
1038
|
+
for (;;) {
|
|
1039
|
+
await sleep(250);
|
|
1040
|
+
if (!alive(pid))
|
|
1041
|
+
return "taken";
|
|
1042
|
+
const probe = await probeDaemon({ timeoutMs: 1_000 });
|
|
1043
|
+
if (probe.state === "none")
|
|
1044
|
+
return "taken";
|
|
1045
|
+
if (probe.state === "answered" && (probe.info.pid !== pid || probe.info.stopping))
|
|
1046
|
+
return "taken";
|
|
1047
|
+
if (Date.now() >= deadline) {
|
|
1048
|
+
return probe.state === "answered" || pidInFile() === pid ? "ignored" : "taken";
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
/**
|
|
1053
|
+
* Print local capture stats; never let a broken native module crash status.
|
|
1054
|
+
*
|
|
1055
|
+
* Read-only: daemon.db belongs to the daemon, which may be an older version
|
|
1056
|
+
* than this CLI. Opening it read-write here used to bring its schema up to
|
|
1057
|
+
* this CLI's version under a daemon that doesn't know that schema.
|
|
1058
|
+
*
|
|
1059
|
+
* "Pending" counts what the configured key will send. What another
|
|
1060
|
+
* account's key queued is "held" (engram#594): it stays on this machine
|
|
1061
|
+
* and is sent only when that account signs in again. What was queued for a
|
|
1062
|
+
* conversation Engram no longer has is "not sent" (engram#593): it stays on
|
|
1063
|
+
* this machine, and the conversation isn't created again.
|
|
1064
|
+
*/
|
|
1065
|
+
async function printDbStats(foreign, config) {
|
|
1066
|
+
if (!existsSync(DB_FILE))
|
|
1067
|
+
return;
|
|
1068
|
+
try {
|
|
1069
|
+
const { DaemonDb } = await import("./db.js");
|
|
1070
|
+
const { accountFingerprint, keyFingerprint } = await import("./syncer.js");
|
|
1071
|
+
const { resolveBaseUrl } = await import("../server-url.js");
|
|
1072
|
+
const key = process.env.ENGRAM_API_KEY || config?.apiKey;
|
|
1073
|
+
// The account the daemon sends for, its key and server read together
|
|
1074
|
+
// (engram#685). With config.json unreadable and no ENGRAM_BASE_URL,
|
|
1075
|
+
// which server is unknown, and the daemon sends nothing.
|
|
1076
|
+
const server = config !== null || process.env.ENGRAM_BASE_URL?.trim() ? resolveBaseUrl(config ?? {}) : undefined;
|
|
1077
|
+
const mine = key && server ? accountFingerprint({ key, server }) : null;
|
|
1078
|
+
const db = new DaemonDb(DB_FILE, { readonly: true });
|
|
1079
|
+
let stats;
|
|
1080
|
+
try {
|
|
1081
|
+
// What the key queued before its server was recorded is sent too,
|
|
1082
|
+
// once the server confirms the key (see ownershipCandidates).
|
|
1083
|
+
stats = db.getStats(mine, key ? keyFingerprint(key) : undefined);
|
|
1084
|
+
}
|
|
1085
|
+
finally {
|
|
1086
|
+
db.close();
|
|
1087
|
+
}
|
|
1088
|
+
console.log(`${dim("Sessions captured:")} ${stats.sessionsMapped}`);
|
|
1089
|
+
console.log(`${dim("Pending sync:")} ${plural(stats.pendingMessages, "message")}`);
|
|
1090
|
+
if (stats.heldMessages > 0) {
|
|
1091
|
+
console.log(`${dim("Held:")} ${plural(stats.heldMessages, "message")} ` +
|
|
1092
|
+
dim(mine ? "(another account's — sent when it signs in again)" : "(sent when their account signs in)"));
|
|
1093
|
+
}
|
|
1094
|
+
// engram#593: Engram doesn't have their conversation any more.
|
|
1095
|
+
if (stats.notSentMessages > 0) {
|
|
1096
|
+
console.log(`${dim("Not sent:")} ${plural(stats.notSentMessages, "message")} ` +
|
|
1097
|
+
dim("(their conversation is no longer on Engram — kept on this machine; nothing to do if you deleted it)"));
|
|
1098
|
+
}
|
|
1099
|
+
console.log(`${dim("Files tracked:")} ${stats.trackedFiles}`);
|
|
1100
|
+
}
|
|
1101
|
+
catch {
|
|
1102
|
+
if (foreign?.files.some((name) => name.startsWith("daemon.db"))) {
|
|
1103
|
+
// engram#659: not the native module, and no start repairs it.
|
|
1104
|
+
console.log(dim("Local capture DB unreadable: it isn't yours, see below."));
|
|
1105
|
+
}
|
|
1106
|
+
else if (lockedDir()) {
|
|
1107
|
+
// engram#723: nor the native module. To read the database, SQLite
|
|
1108
|
+
// needs its -wal and -shm files beside it, and makes them when they
|
|
1109
|
+
// aren't there, as a stopped daemon leaves it.
|
|
1110
|
+
console.log(dim("Local capture DB unreadable: ~/.engram's own permissions get in the way."));
|
|
1111
|
+
}
|
|
1112
|
+
else {
|
|
1113
|
+
console.log(dim("Local capture DB unreadable (native module mismatch?) — the daemon rebuilds it on start."));
|
|
1114
|
+
}
|
|
1115
|
+
}
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* engram#659, in `engram status`. `stopped`: the daemon isn't running, so
|
|
1119
|
+
* once they are the user's, it has to be started. `thenStart`: false when
|
|
1120
|
+
* that is said after the next warning instead, as ~/.engram keeps them out
|
|
1121
|
+
* too (engram#723), and it can't be started until both are fixed.
|
|
1122
|
+
*/
|
|
1123
|
+
function printForeignFilesWarning(foreign, stopped, blankBefore = true, thenStart = true) {
|
|
1124
|
+
if (blankBefore)
|
|
1125
|
+
console.log("");
|
|
1126
|
+
console.log(red(` ${foreignFilesProblem(foreign, stopped ? "stopped" : "running")}`));
|
|
1127
|
+
console.log(dim(` ${foreignFilesFix(foreign)}`));
|
|
1128
|
+
if (thenStart && stopped && stopsCapture(foreign))
|
|
1129
|
+
console.log(dim(` Then run: ${engramCommand("start")}`));
|
|
1130
|
+
console.log("");
|
|
1131
|
+
}
|
|
1132
|
+
/**
|
|
1133
|
+
* engram#723, in `engram status`. `stopped`: the daemon isn't running, or
|
|
1134
|
+
* can't be told to be, so once ~/.engram lets them in, it has to be started.
|
|
1135
|
+
*/
|
|
1136
|
+
function printLockedDirWarning(locked, stopped, blankBefore = true) {
|
|
1137
|
+
if (blankBefore)
|
|
1138
|
+
console.log("");
|
|
1139
|
+
console.log(red(` ${lockedDirProblem(locked, stopped ? "stopped" : "running")}`));
|
|
1140
|
+
console.log(dim(` ${lockedDirFix(locked)}`));
|
|
1141
|
+
if (stopped)
|
|
1142
|
+
console.log(dim(` Then run: ${engramCommand("start")}`));
|
|
1143
|
+
console.log("");
|
|
1144
|
+
}
|
|
1145
|
+
/**
|
|
1146
|
+
* engram#680, in `engram status`: the daemon running as root for the user
|
|
1147
|
+
* that it found, or one besides theirs, from `sudo engram start` or `sudo
|
|
1148
|
+
* engram install` before engram#653; any other daemon running as root; and
|
|
1149
|
+
* Engram's job left in launchd's system domain. True when it said any.
|
|
1150
|
+
*/
|
|
1151
|
+
function printRootWarnings(found, foreign) {
|
|
1152
|
+
const job = found.state === "root" ? found.job : systemJob();
|
|
1153
|
+
const root = found.state === "root" ? found : findRootDaemon(undefined, job);
|
|
1154
|
+
const own = found.state === "stopped" || found.state === "root" ? null : found.pid;
|
|
1155
|
+
// The job's daemon is said with the job.
|
|
1156
|
+
const untied = untiedRootWorkers([own, root?.pid ?? null, job?.pid ?? null], foreign);
|
|
1157
|
+
if (root === null && untied.length === 0 && job === null)
|
|
1158
|
+
return false;
|
|
1159
|
+
console.log("");
|
|
1160
|
+
if (root !== null) {
|
|
1161
|
+
const { problem, fixes } = rootDaemonLines(root);
|
|
1162
|
+
const why = found.state === "root"
|
|
1163
|
+
? `'${engramCommand("stop")}' can't stop it, and no daemon of yours starts while it runs.`
|
|
1164
|
+
: "It runs beside yours, and only one should.";
|
|
1165
|
+
console.log(red(` ${problem} ${why}`));
|
|
1166
|
+
for (const fix of fixes)
|
|
1167
|
+
console.log(dim(` ${fix}`));
|
|
1168
|
+
if (found.state === "root") {
|
|
1169
|
+
if (foreign) {
|
|
1170
|
+
console.log(red(` ${foreignFilesProblem(foreign)}`));
|
|
1171
|
+
console.log(dim(` ${foreignFilesFix(foreign, true)}`));
|
|
46
1172
|
}
|
|
1173
|
+
console.log(dim(` Then run: ${engramCommand("start")}`));
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
else if (job !== null) {
|
|
1177
|
+
console.log(dim(` ${systemJobLeft()}`));
|
|
1178
|
+
}
|
|
1179
|
+
if (untied.length > 0)
|
|
1180
|
+
console.log(red(` ${untiedRootLine(untied)}`));
|
|
1181
|
+
console.log("");
|
|
1182
|
+
return true;
|
|
1183
|
+
}
|
|
1184
|
+
export async function daemonStatus() {
|
|
1185
|
+
const found = await findDaemon();
|
|
1186
|
+
// Files in ~/.engram that are another user's (engram#659).
|
|
1187
|
+
const foreign = foreignFiles();
|
|
1188
|
+
// A ~/.engram whose own permissions keep the user out of it (engram#723).
|
|
1189
|
+
// One that can't be searched hides everything in it: that is said, not
|
|
1190
|
+
// what can't be read in it, which is every file. Nor can it be told
|
|
1191
|
+
// whether a daemon runs, unless launchd runs it: the exit says so.
|
|
1192
|
+
const locked = lockedDir();
|
|
1193
|
+
if (locked?.search)
|
|
1194
|
+
process.exitCode = 1;
|
|
1195
|
+
// A config.json that can't be read (engram#673): capture waits on it.
|
|
1196
|
+
const { config, problem: unread } = await inspectConfig();
|
|
1197
|
+
const problem = locked?.search ? null : unread;
|
|
1198
|
+
// A vault key that can't be read (engram#677): sends wait on it.
|
|
1199
|
+
const key = await keyFile(foreign, locked);
|
|
1200
|
+
if (found.state === "stopped") {
|
|
1201
|
+
// Its socket and PID file are how a daemon is found.
|
|
1202
|
+
console.log(locked?.search
|
|
1203
|
+
? `${bold("Status:")} unknown — ~/.engram's permissions keep you from opening the files that say whether the daemon runs`
|
|
1204
|
+
: `${bold("Status:")} stopped`);
|
|
1205
|
+
// Still show DB stats if available
|
|
1206
|
+
await printDbStats(foreign, config);
|
|
1207
|
+
const saidRoot = printRootWarnings(found, foreign);
|
|
1208
|
+
if (foreign)
|
|
1209
|
+
printForeignFilesWarning(foreign, true, !saidRoot, !locked);
|
|
1210
|
+
if (locked)
|
|
1211
|
+
printLockedDirWarning(locked, true, !saidRoot && !foreign);
|
|
1212
|
+
if (problem)
|
|
1213
|
+
printConfigWarning(problem);
|
|
1214
|
+
if (key instanceof VaultKeyUnreadable)
|
|
1215
|
+
printVaultKeyWarning(key, null);
|
|
1216
|
+
// A broken start-at-login entry is often why it's stopped. Files that
|
|
1217
|
+
// aren't the user's, said above, are why, when they stop it, and so is
|
|
1218
|
+
// a ~/.engram that keeps them out. With config.json unreadable, whether
|
|
1219
|
+
// 'engram stop' recorded capture off can't be told.
|
|
1220
|
+
const startsAtLogin = printAutoStart();
|
|
1221
|
+
if (startsAtLogin && !stopsCapture(foreign) && !locked && config !== null && config.autocapture !== "off") {
|
|
1222
|
+
// Not stopped by 'engram stop', which records autocapture "off", and
|
|
1223
|
+
// started at sign-in, so it stopped by itself (engram#613).
|
|
1224
|
+
console.log(dim(" It should be running: start at login is on. It may have stopped after an error."));
|
|
1225
|
+
// Without its log (engram#679), what it said is in the journal on
|
|
1226
|
+
// Linux, and gone on macOS.
|
|
1227
|
+
const linux = process.platform === "linux";
|
|
1228
|
+
console.log(dim(logProblem() === null
|
|
1229
|
+
? ` The end of its log says why: ${LOG_FILE}`
|
|
1230
|
+
: linux
|
|
1231
|
+
? " The end of its output says why: journalctl --user -u engram"
|
|
1232
|
+
: ` Its log can't be written: '${engramCommand("start --foreground")}' shows why it stops.`));
|
|
1233
|
+
console.log(dim(` Run '${engramCommand("start")}' to start it again.`));
|
|
1234
|
+
}
|
|
1235
|
+
if (startsAtLogin)
|
|
1236
|
+
await printLoginVaultKeyWarning();
|
|
1237
|
+
// Not "will run without it": in a ~/.engram that keeps them out, it
|
|
1238
|
+
// doesn't run at all, which is said above.
|
|
1239
|
+
if (logProblem() !== null && !locked)
|
|
1240
|
+
printLog(false);
|
|
1241
|
+
return;
|
|
1242
|
+
}
|
|
1243
|
+
if (found.state === "stopping") {
|
|
1244
|
+
console.log(`${bold("Status:")} stopping (pid ${found.pid})`);
|
|
1245
|
+
}
|
|
1246
|
+
else if (found.state === "root") {
|
|
1247
|
+
console.log(`${bold("Status:")} running as root (pid ${found.pid}), started with sudo`);
|
|
1248
|
+
}
|
|
1249
|
+
else if (found.state === "unresponsive") {
|
|
1250
|
+
const held = process.platform === "win32" ? "the daemon's named pipe" : "~/.engram/daemon.sock";
|
|
1251
|
+
console.log(found.pid === null
|
|
1252
|
+
? `${bold("Status:")} not answering — ${held} is held, but nothing replies`
|
|
1253
|
+
: `${bold("Status:")} running (pid ${found.pid}) — not answering right now`);
|
|
1254
|
+
console.log(dim(" Busy, or still starting: the first start after an update can take a minute or two."));
|
|
1255
|
+
}
|
|
1256
|
+
else {
|
|
1257
|
+
console.log(`${bold("Status:")} running (pid ${found.pid})`);
|
|
1258
|
+
if (!found.ready)
|
|
1259
|
+
console.log(dim(" Still starting up."));
|
|
1260
|
+
printVersionHint(found);
|
|
1261
|
+
}
|
|
1262
|
+
await printDbStats(foreign, config);
|
|
1263
|
+
// With one running as root, what it made is said with it.
|
|
1264
|
+
const saidRoot = printRootWarnings(found, foreign);
|
|
1265
|
+
const ownDaemon = found.state !== "root";
|
|
1266
|
+
if (foreign && ownDaemon)
|
|
1267
|
+
printForeignFilesWarning(foreign, false, !saidRoot);
|
|
1268
|
+
if (locked && ownDaemon)
|
|
1269
|
+
printLockedDirWarning(locked, false, !saidRoot && !foreign);
|
|
1270
|
+
// status.json can't be read either in a ~/.engram that can't be
|
|
1271
|
+
// searched: what it says is the same as with none.
|
|
1272
|
+
const syncStatus = readStatus();
|
|
1273
|
+
printHostStatus(locked?.search && ownDaemon
|
|
1274
|
+
? "~/.engram, see above"
|
|
1275
|
+
: problem
|
|
1276
|
+
? "config.json, see below"
|
|
1277
|
+
: syncStatus.signed_out_at
|
|
1278
|
+
? "signed out"
|
|
1279
|
+
: undefined);
|
|
1280
|
+
// The daemon has no vault key, and the vault holds secrets (engram#698):
|
|
1281
|
+
// said with what to do, which is what the warning below would say.
|
|
1282
|
+
const keyMissing = await vaultKeyMissing(syncStatus, key);
|
|
1283
|
+
// Show sync health warnings
|
|
1284
|
+
printSyncWarnings(syncStatus, problem, key, keyMissing);
|
|
1285
|
+
// One running as root can write to it, and does. One running in a
|
|
1286
|
+
// ~/.engram that can't be searched opened it as it started, and goes on
|
|
1287
|
+
// writing to it: no one else can open it then (engram#723).
|
|
1288
|
+
if (found.state === "root" || locked?.search)
|
|
1289
|
+
console.log(`${dim("Log:")} ${LOG_FILE}`);
|
|
1290
|
+
else
|
|
1291
|
+
printLog(true, found.pid, ownDaemon ? locked?.command : undefined, found.state === "running" ? found.output : undefined);
|
|
1292
|
+
if (printAutoStart(found) && !keyMissing)
|
|
1293
|
+
await printLoginVaultKeyWarning();
|
|
1294
|
+
}
|
|
1295
|
+
/**
|
|
1296
|
+
* Print how the daemon starts at login; true when it is set to and should
|
|
1297
|
+
* work. What it says to run works whether the daemon runs or not: `engram
|
|
1298
|
+
* start` finds a running daemon and repairs nothing, and status is mostly
|
|
1299
|
+
* read while it runs (engram#651).
|
|
1300
|
+
*
|
|
1301
|
+
* `found`: the daemon that runs. Under the line, when start at login is on
|
|
1302
|
+
* and launchd or systemd doesn't run that daemon, though it could: it won't
|
|
1303
|
+
* be started again after a crash (engram#692, engram#689).
|
|
1304
|
+
*/
|
|
1305
|
+
function printAutoStart(found) {
|
|
1306
|
+
const { on, line, after = [] } = autoStart();
|
|
1307
|
+
if (line !== null)
|
|
1308
|
+
console.log(line);
|
|
1309
|
+
for (const more of after)
|
|
1310
|
+
console.log(more);
|
|
1311
|
+
// On: launchd hasn't the job switched off, as autoStart asked, or the
|
|
1312
|
+
// systemd unit is enabled.
|
|
1313
|
+
if (on && found)
|
|
1314
|
+
printOutsideManager(found, true);
|
|
1315
|
+
return on;
|
|
1316
|
+
}
|
|
1317
|
+
function autoStart() {
|
|
1318
|
+
if (process.platform === "darwin")
|
|
1319
|
+
return launchdAutoStart(readPlist());
|
|
1320
|
+
if (process.platform === "linux")
|
|
1321
|
+
return systemdAutoStart(readUnit());
|
|
1322
|
+
const entry = readRunEntry();
|
|
1323
|
+
if (entry === null)
|
|
1324
|
+
return { on: false, line: null };
|
|
1325
|
+
// Said before broken, as on macOS and Linux: one switched off doesn't
|
|
1326
|
+
// start at sign-in either way, and 'engram install' switches it back on.
|
|
1327
|
+
if (switchedOffInStartupApps()) {
|
|
1328
|
+
return {
|
|
1329
|
+
on: false,
|
|
1330
|
+
line: `${dim("Auto-start:")} off — switched off in Windows Startup apps` +
|
|
1331
|
+
dim(` ('${engramCommand("install")}' turns it back on)`),
|
|
1332
|
+
};
|
|
1333
|
+
}
|
|
1334
|
+
if (runEntryBroken(entry)) {
|
|
1335
|
+
return {
|
|
1336
|
+
on: false,
|
|
1337
|
+
line: `${dim("Auto-start:")} enabled (Windows sign-in)` + red(` — broken, run '${engramCommand("install")}' to repair`),
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
return {
|
|
1341
|
+
on: true,
|
|
1342
|
+
line: `${dim("Auto-start:")} enabled (Windows sign-in)` +
|
|
1343
|
+
(runEntryOutdated(entry) ? red(` — outdated config, run '${engramCommand("install")}' to update`) : ""),
|
|
1344
|
+
};
|
|
1345
|
+
}
|
|
1346
|
+
/** autoStart for the launchd agent: nothing when there is none. */
|
|
1347
|
+
function launchdAutoStart(plist) {
|
|
1348
|
+
if (plist.kind === "none")
|
|
1349
|
+
return { on: false, line: null };
|
|
1350
|
+
// A plist in a folder that isn't the user's can't be rewritten or removed
|
|
1351
|
+
// (engram#715): said whatever its state, as it is what 'engram install'
|
|
1352
|
+
// and 'engram uninstall' would stop at.
|
|
1353
|
+
const notYours = launchAgentsNotYours();
|
|
1354
|
+
const after = notYours === null
|
|
1355
|
+
? []
|
|
1356
|
+
: [
|
|
1357
|
+
red(` ${launchAgentsWhose(notYours)}, so Engram can't update or remove its launchd agent.`),
|
|
1358
|
+
dim(` Make it yours with: ${LAUNCH_AGENTS_FIX}`),
|
|
1359
|
+
];
|
|
1360
|
+
// Said before broken or outdated: 'engram start' won't repair a job the
|
|
1361
|
+
// user switched off (engram#654).
|
|
1362
|
+
if (agentDisabled() === true) {
|
|
1363
|
+
return {
|
|
1364
|
+
on: false,
|
|
1365
|
+
line: `${dim("Auto-start:")} off — disabled in launchd` + dim(` ('${engramCommand("install")}' turns it back on)`),
|
|
1366
|
+
after,
|
|
1367
|
+
};
|
|
1368
|
+
}
|
|
1369
|
+
if (plist.broken) {
|
|
1370
|
+
return {
|
|
1371
|
+
on: false,
|
|
1372
|
+
line: `${dim("Auto-start:")} enabled (launchd)` + red(` — broken, run '${engramCommand("install")}' to repair`),
|
|
1373
|
+
after,
|
|
1374
|
+
};
|
|
1375
|
+
}
|
|
1376
|
+
return {
|
|
1377
|
+
on: true,
|
|
1378
|
+
line: `${dim("Auto-start:")} enabled (launchd)` +
|
|
1379
|
+
(plist.outdated ? red(` — outdated config, run '${engramCommand("install")}' to update`) : ""),
|
|
1380
|
+
after,
|
|
1381
|
+
};
|
|
1382
|
+
}
|
|
1383
|
+
/** autoStart for the systemd unit: nothing when there is none of ours. */
|
|
1384
|
+
function systemdAutoStart(unit) {
|
|
1385
|
+
if (unit.kind !== "ours")
|
|
1386
|
+
return { on: false, line: null };
|
|
1387
|
+
if (!unit.enabled) {
|
|
1388
|
+
return {
|
|
1389
|
+
on: false,
|
|
1390
|
+
line: `${dim("Auto-start:")} off — disabled with systemctl` + dim(` ('${engramCommand("install")}' turns it back on)`),
|
|
1391
|
+
};
|
|
1392
|
+
}
|
|
1393
|
+
if (unit.broken) {
|
|
1394
|
+
return {
|
|
1395
|
+
on: false,
|
|
1396
|
+
line: `${dim("Auto-start:")} enabled (systemd)` + red(` — broken, run '${engramCommand("install")}' to repair`),
|
|
1397
|
+
};
|
|
1398
|
+
}
|
|
1399
|
+
return {
|
|
1400
|
+
on: true,
|
|
1401
|
+
line: `${dim("Auto-start:")} enabled (systemd)` +
|
|
1402
|
+
(unit.outdated ? red(` — outdated config, run '${engramCommand("install")}' to update`) : ""),
|
|
1403
|
+
};
|
|
1404
|
+
}
|
|
1405
|
+
/**
|
|
1406
|
+
* engram#673, in `engram status`: config.json can't be read, so capture
|
|
1407
|
+
* waits on it, and commands that save settings won't save over it.
|
|
1408
|
+
*/
|
|
1409
|
+
function printConfigWarning(problem) {
|
|
1410
|
+
console.log("");
|
|
1411
|
+
console.log(red(` WARNING: ${configProblemSummary(problem.message)}`));
|
|
1412
|
+
if (problem.empty) {
|
|
1413
|
+
console.log(dim(` Add back any folders you had excluded ('${engramCommand("exclude add <path>")}'),`));
|
|
1414
|
+
console.log(dim(` then sign in again ('${engramCommand("login")}').`));
|
|
1415
|
+
}
|
|
1416
|
+
else {
|
|
1417
|
+
console.log(dim(" Fix the file: it holds your API key and the folders you excluded, so Engram"));
|
|
1418
|
+
console.log(dim(` won't save over it. To start over instead: run '${engramCommand("stop")}', remove it, add`));
|
|
1419
|
+
console.log(dim(` back the folders you excluded ('${engramCommand("exclude add <path>")}'), then '${engramCommand("login")}'.`));
|
|
1420
|
+
}
|
|
1421
|
+
console.log("");
|
|
1422
|
+
}
|
|
1423
|
+
async function keyFile(foreign, locked) {
|
|
1424
|
+
const state = await vaultKeyFileState();
|
|
1425
|
+
if (!(state instanceof VaultKeyUnreadable))
|
|
1426
|
+
return state;
|
|
1427
|
+
if (locked?.search)
|
|
1428
|
+
return "locked";
|
|
1429
|
+
return foreign?.files.includes("vault-key") ? "foreign" : state;
|
|
1430
|
+
}
|
|
1431
|
+
/**
|
|
1432
|
+
* engram#677, in `engram status`: no key can be read from ~/.engram/vault-key.
|
|
1433
|
+
* `held`: the daemon's status, while it holds sends for the key.
|
|
1434
|
+
*/
|
|
1435
|
+
function printVaultKeyWarning(problem, held) {
|
|
1436
|
+
console.log("");
|
|
1437
|
+
console.log(red(` WARNING: ${problem.message}.`));
|
|
1438
|
+
// A sentence to a line: the one for a key that is gone is long.
|
|
1439
|
+
for (const line of vaultKeyFix(problem).split(/(?<=\.) /))
|
|
1440
|
+
console.log(dim(` ${line}`));
|
|
1441
|
+
// ENGRAM_VAULT_KEY wins over the file for commands run in this shell, not
|
|
1442
|
+
// for the daemon, which launchd and systemd start without it. A file that
|
|
1443
|
+
// is gone is no key to commands: they run without one.
|
|
1444
|
+
const envKey = Boolean(process.env.ENGRAM_VAULT_KEY) && problem.kind !== "gone";
|
|
1445
|
+
const refused = !envKey && problem.kind !== "gone";
|
|
1446
|
+
if (held) {
|
|
1447
|
+
console.log(dim(" Meanwhile, messages wait here rather than be sent with your vault's secrets"));
|
|
1448
|
+
console.log(dim(` in them${refused ? ", and commands that need the key won't run" : ""}. Nothing is lost.`));
|
|
1449
|
+
if (held.pending_messages > 0) {
|
|
1450
|
+
console.log(red(` ${plural(held.pending_messages, "message")} waiting to sync`));
|
|
1451
|
+
}
|
|
1452
|
+
if (held.last_error_at)
|
|
1453
|
+
console.log(dim(` Last error: ${held.last_error_at}`));
|
|
1454
|
+
}
|
|
1455
|
+
else if (refused) {
|
|
1456
|
+
console.log(dim(" Meanwhile, commands that need the key won't run."));
|
|
1457
|
+
}
|
|
1458
|
+
if (envKey)
|
|
1459
|
+
console.log(dim(" Commands run here use ENGRAM_VAULT_KEY instead, which wins over the file."));
|
|
1460
|
+
console.log("");
|
|
1461
|
+
}
|
|
1462
|
+
/**
|
|
1463
|
+
* engram#690: ENGRAM_VAULT_KEY is set here, and ~/.engram/vault-key doesn't
|
|
1464
|
+
* hold its key. A daemon started at login reads the file: launchd never
|
|
1465
|
+
* gives it a shell's variables, and systemd and Windows may not. Without
|
|
1466
|
+
* the key, it captures without the vault's values removed (scrubber.ts);
|
|
1467
|
+
* with another key, without those encrypted with this one. Nothing said for
|
|
1468
|
+
* a variable that holds no key, or a file that can't be read, which
|
|
1469
|
+
* printVaultKeyWarning says (engram#677). `startsAtLogin`: whether the
|
|
1470
|
+
* daemon starts at login, asked only when there is something to say, as on
|
|
1471
|
+
* macOS that asks launchd.
|
|
1472
|
+
*/
|
|
1473
|
+
async function printLoginVaultKeyWarning(startsAtLogin = () => true) {
|
|
1474
|
+
const state = await envVaultKeyState();
|
|
1475
|
+
if (state !== "none" && state !== "different")
|
|
1476
|
+
return;
|
|
1477
|
+
if (!startsAtLogin())
|
|
1478
|
+
return;
|
|
1479
|
+
console.log("");
|
|
1480
|
+
if (state === "none") {
|
|
1481
|
+
console.log(red(" WARNING: ENGRAM_VAULT_KEY is set here, but ~/.engram/vault-key isn't there."));
|
|
1482
|
+
console.log(dim(" A daemon started at login may not get this shell's variables. Then it has no"));
|
|
1483
|
+
console.log(dim(" vault key, and your vault's secrets aren't removed from what it captures."));
|
|
1484
|
+
console.log(dim(` To save the key there, readable only by you: ${engramCommand("vault save-key")}`));
|
|
1485
|
+
}
|
|
1486
|
+
else {
|
|
1487
|
+
console.log(red(" WARNING: ~/.engram/vault-key holds a different vault key from ENGRAM_VAULT_KEY."));
|
|
1488
|
+
console.log(dim(" A daemon started at login may not get this shell's variables. Then it uses the"));
|
|
1489
|
+
console.log(dim(" file's key, and secrets encrypted with ENGRAM_VAULT_KEY's aren't removed from"));
|
|
1490
|
+
console.log(dim(" what it captures. If ENGRAM_VAULT_KEY's key is the right one:"));
|
|
1491
|
+
console.log(dim(` ${engramCommand("vault save-key --force")} (the file's key is backed up first).`));
|
|
1492
|
+
console.log(dim(" If the file's is, unset ENGRAM_VAULT_KEY."));
|
|
1493
|
+
}
|
|
1494
|
+
console.log("");
|
|
1495
|
+
}
|
|
1496
|
+
async function vaultKeyMissing(status, key) {
|
|
1497
|
+
const secrets = status.vault_key_missing?.secrets;
|
|
1498
|
+
if (typeof secrets !== "number" || !Number.isSafeInteger(secrets) || secrets <= 0)
|
|
1499
|
+
return null;
|
|
1500
|
+
const keyHeld = status.error_type === "vault_key" && status.health !== "healthy";
|
|
1501
|
+
if (status.vault_key !== null || key !== "none" || keyHeld || status.signed_out_at)
|
|
1502
|
+
return null;
|
|
1503
|
+
return { secrets, envKey: (await envVaultKeyState()) === "none" };
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* engram#698, in `engram status`. A key saved now is read before the next
|
|
1507
|
+
* send: no restart.
|
|
1508
|
+
*/
|
|
1509
|
+
function printVaultKeyMissingWarning({ secrets, envKey }) {
|
|
1510
|
+
const one = secrets === 1;
|
|
1511
|
+
console.log("");
|
|
1512
|
+
console.log(red(` WARNING: The daemon has no vault key, and your vault has ${plural(secrets, "secret")}.`));
|
|
1513
|
+
console.log(dim(` Without the key, it can't remove ${one ? "its value" : "their values"} from what it captures before`));
|
|
1514
|
+
console.log(dim(" sending it."));
|
|
1515
|
+
if (envKey) {
|
|
1516
|
+
console.log(dim(` To save ENGRAM_VAULT_KEY's key for it: ${engramCommand("vault save-key")}`));
|
|
1517
|
+
}
|
|
1518
|
+
else {
|
|
1519
|
+
console.log(dim(` Put your vault key in ~/.engram/vault-key, or run '${engramCommand("vault save-key")}'`));
|
|
1520
|
+
console.log(dim(" from a shell where ENGRAM_VAULT_KEY holds it."));
|
|
1521
|
+
}
|
|
1522
|
+
console.log(dim(" The daemon reads it before its next send: no restart needed."));
|
|
1523
|
+
console.log("");
|
|
1524
|
+
}
|
|
1525
|
+
/**
|
|
1526
|
+
* engram#694, in `engram status`: the daemon holds sends for secrets its
|
|
1527
|
+
* vault key doesn't decrypt, until each decrypts, or is gone. It decrypts
|
|
1528
|
+
* none of the vault's secrets, or did when the hold began and some now:
|
|
1529
|
+
* saved again one at a time, they hold until the last. Then the key they
|
|
1530
|
+
* were saved with isn't the fix: the others don't decrypt with it. Its key
|
|
1531
|
+
* is the file's, or ENGRAM_VAULT_KEY's, which it read when it started:
|
|
1532
|
+
* then setting the variable again takes a restart.
|
|
1533
|
+
*/
|
|
1534
|
+
function printVaultMismatchWarning(status) {
|
|
1535
|
+
const secrets = status.vault_undecryptable?.secrets ?? 0;
|
|
1536
|
+
const decrypted = status.vault_undecryptable?.decrypted ?? 0;
|
|
1537
|
+
const one = secrets === 1;
|
|
1538
|
+
const they = one ? "it was" : "they were";
|
|
1539
|
+
console.log("");
|
|
1540
|
+
console.log(red(decrypted > 0
|
|
1541
|
+
? ` WARNING: ${secrets} of your vault's ${secrets + decrypted} secrets ${one ? "doesn't" : "don't"} decrypt with your vault key.`
|
|
1542
|
+
: one
|
|
1543
|
+
? " WARNING: Your vault key doesn't decrypt your vault's secret."
|
|
1544
|
+
: ` WARNING: Your vault key doesn't decrypt any of your vault's ${secrets > 1 ? `${secrets} ` : ""}secrets.`));
|
|
1545
|
+
console.log(dim(` ${one ? "It was" : "They were"} saved with another key, so the daemon can't remove ${one ? "it" : "them"} from`));
|
|
1546
|
+
console.log(dim(" what it captures. Meanwhile, messages wait here rather than be sent with your"));
|
|
1547
|
+
console.log(dim(" vault's secrets in them. Nothing is lost. To send what waits, do one of these:"));
|
|
1548
|
+
if (decrypted > 0) {
|
|
1549
|
+
// The others decrypt with this key, and wouldn't with that one.
|
|
1550
|
+
}
|
|
1551
|
+
else if (status.vault_key === "env") {
|
|
1552
|
+
console.log(dim(` Set ENGRAM_VAULT_KEY to the key ${they} saved with, then run`));
|
|
1553
|
+
console.log(dim(` '${engramCommand("stop")}' and '${engramCommand("start")}' from that shell.`));
|
|
1554
|
+
}
|
|
1555
|
+
else {
|
|
1556
|
+
console.log(dim(` Put the key ${they} saved with in ~/.engram/vault-key.`));
|
|
1557
|
+
}
|
|
1558
|
+
console.log(dim(` Save ${one ? "it" : "each"} again with this key: ${engramCommand("vault set <NAME>")}`));
|
|
1559
|
+
// Not "whose key is lost": one still in use, deleted, is no longer
|
|
1560
|
+
// removed from what the daemon captures. Saved again, it is.
|
|
1561
|
+
console.log(dim(` Delete ${one ? "it, if you no longer use it" : "each you no longer use"}: ${engramCommand("vault delete <NAME>")}`));
|
|
1562
|
+
if (decrypted > 0) {
|
|
1563
|
+
console.log(dim(` '${engramCommand("vault list --check")}' shows which. Then the daemon sends what it held`));
|
|
1564
|
+
console.log(dim(" within 5 minutes."));
|
|
1565
|
+
}
|
|
1566
|
+
else {
|
|
1567
|
+
console.log(dim(` '${engramCommand("vault list")}' lists ${one ? "it" : "them"}. Then the daemon sends what it held within`));
|
|
1568
|
+
console.log(dim(" 5 minutes."));
|
|
1569
|
+
}
|
|
1570
|
+
if (status.pending_messages > 0) {
|
|
1571
|
+
console.log(red(` ${plural(status.pending_messages, "message")} waiting to sync`));
|
|
1572
|
+
}
|
|
1573
|
+
// Held with nothing waiting yet, the last error is another's.
|
|
1574
|
+
if (status.last_error_at && status.health !== "healthy") {
|
|
1575
|
+
console.log(dim(` Last error: ${status.last_error_at}`));
|
|
1576
|
+
}
|
|
1577
|
+
console.log("");
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* engram#694, in `engram status`: some of the vault's secrets don't decrypt
|
|
1581
|
+
* with the daemon's vault key, and the others do. Sends go on: the key
|
|
1582
|
+
* these were saved with would leave the others out instead. Those it read
|
|
1583
|
+
* before, with a key it had then, it still removes, until it restarts.
|
|
1584
|
+
* Putting that key back isn't the fix: the others don't decrypt with it.
|
|
1585
|
+
*/
|
|
1586
|
+
function printVaultUndecryptableWarning(found) {
|
|
1587
|
+
const { secrets, unscrubbed } = found;
|
|
1588
|
+
const one = secrets === 1;
|
|
1589
|
+
console.log("");
|
|
1590
|
+
console.log(red(` WARNING: ${plural(secrets, "secret")} in your vault ${one ? "doesn't" : "don't"} decrypt with your vault key.`));
|
|
1591
|
+
if (unscrubbed >= secrets) {
|
|
1592
|
+
console.log(dim(` ${one ? "It was" : "They were"} saved with another key, so the daemon can't remove ${one ? "it" : "them"} from`));
|
|
1593
|
+
console.log(dim(" what it captures before sending it."));
|
|
1594
|
+
}
|
|
1595
|
+
else if (unscrubbed === 0) {
|
|
1596
|
+
console.log(dim(` ${one ? "It was" : "They were"} saved with another key. The daemon still removes ${one ? "it" : "them"} from what`));
|
|
1597
|
+
console.log(dim(` it captures, with what it read before, but can't once it restarts.`));
|
|
1598
|
+
}
|
|
1599
|
+
else {
|
|
1600
|
+
console.log(dim(` They were saved with another key. The daemon can't remove ${unscrubbed} of them from`));
|
|
1601
|
+
console.log(dim(" what it captures before sending it, and the others only until it restarts."));
|
|
1602
|
+
}
|
|
1603
|
+
console.log(dim(` Save ${one ? "it" : "each"} again with this key (${engramCommand("vault set <NAME>")}), or delete ${one ? "it if you" : "each you"}`));
|
|
1604
|
+
console.log(dim(` no longer use${one ? " it" : ""} (${engramCommand("vault delete <NAME>")}). '${engramCommand("vault list --check")}'`));
|
|
1605
|
+
console.log(dim(" shows which don't decrypt."));
|
|
1606
|
+
console.log("");
|
|
1607
|
+
}
|
|
1608
|
+
/**
|
|
1609
|
+
* `problem`: config.json can't be read (engram#673), said above. `key`:
|
|
1610
|
+
* what ~/.engram/vault-key holds now (engram#677). `keyMissing`: the daemon
|
|
1611
|
+
* has no vault key for the vault's secrets (engram#698).
|
|
1612
|
+
*/
|
|
1613
|
+
function printSyncWarnings(status, problem, key, keyMissing = null) {
|
|
1614
|
+
if (problem)
|
|
1615
|
+
printConfigWarning(problem);
|
|
1616
|
+
// Sends wait while the daemon can't read the vault key, and go on waiting
|
|
1617
|
+
// once the file is gone (scrubber.ts). Nothing is sent while signed out.
|
|
1618
|
+
const keyHeld = status.error_type === "vault_key" && status.health !== "healthy" && !status.signed_out_at;
|
|
1619
|
+
const keyProblem = key instanceof VaultKeyUnreadable
|
|
1620
|
+
? key
|
|
1621
|
+
: keyHeld && key === "none"
|
|
1622
|
+
? new VaultKeyUnreadable("isn't there any more", "gone")
|
|
1623
|
+
: null;
|
|
1624
|
+
if (keyProblem)
|
|
1625
|
+
printVaultKeyWarning(keyProblem, keyHeld ? status : null);
|
|
1626
|
+
// The file is gone, and the daemon had read a key from it (engram#693): it
|
|
1627
|
+
// goes on with that key, and the secrets read with it, until it restarts.
|
|
1628
|
+
if (status.vault_key === "file" && key === "none" && !keyHeld) {
|
|
1629
|
+
console.log("");
|
|
1630
|
+
console.log(red(" WARNING: ~/.engram/vault-key isn't there any more."));
|
|
1631
|
+
console.log(dim(" The daemon still removes your vault's secrets from what it captures, with the"));
|
|
1632
|
+
console.log(dim(" key it read before. When it restarts, it starts without one: put the key back"));
|
|
1633
|
+
console.log(dim(" if you still use the vault."));
|
|
1634
|
+
console.log("");
|
|
1635
|
+
}
|
|
1636
|
+
// No key saved (engram#594): the daemon runs, but captures and sends
|
|
1637
|
+
// nothing until one is. Nothing queued is lost meanwhile.
|
|
1638
|
+
if (status.signed_out_at) {
|
|
1639
|
+
// With config.json unreadable, whether a key is saved can't be told,
|
|
1640
|
+
// and signing in has to wait for the fix: said above, instead.
|
|
1641
|
+
if (!problem) {
|
|
1642
|
+
console.log("");
|
|
1643
|
+
console.log(red(" Signed out — capture is paused and nothing is sent."));
|
|
1644
|
+
console.log(dim(` Run '${engramCommand("auth login")}' to resume. Queued messages stay on this machine.`));
|
|
1645
|
+
console.log(dim(` Since: ${status.signed_out_at}`));
|
|
1646
|
+
console.log("");
|
|
1647
|
+
}
|
|
1648
|
+
return;
|
|
1649
|
+
}
|
|
1650
|
+
// Capture comes before sending: what can't be queued here can't be sent
|
|
1651
|
+
// either, however healthy syncing is (engram#584). Waiting on a
|
|
1652
|
+
// config.json that can't be read is said above.
|
|
1653
|
+
if (status.capture_error && !(problem && status.capture_error.kind === "config")) {
|
|
1654
|
+
console.log("");
|
|
1655
|
+
if (status.capture_error.kind === "config") {
|
|
1656
|
+
// The daemon tries again on its own: 5 minutes apart at most.
|
|
1657
|
+
console.log(red(" Capture is waiting on ~/.engram/config.json, which reads fine now."));
|
|
1658
|
+
console.log(dim(" It picks up where it stopped within 5 minutes: nothing is skipped."));
|
|
1659
|
+
}
|
|
1660
|
+
else {
|
|
1661
|
+
console.log(red(` WARNING: ${captureErrorSummary(status.capture_error)}`));
|
|
1662
|
+
}
|
|
1663
|
+
console.log(dim(` Since: ${status.capture_error.since}`));
|
|
1664
|
+
console.log("");
|
|
1665
|
+
}
|
|
1666
|
+
// Opt-outs the key in use may not delete (engram#597). Sending goes on
|
|
1667
|
+
// regardless, so this doesn't wait for a sync error.
|
|
1668
|
+
if (status.delete_refused) {
|
|
1669
|
+
console.log("");
|
|
1670
|
+
console.log(red(` WARNING: ${deleteRefusedSummary(status.delete_refused)}`));
|
|
1671
|
+
console.log(dim(" Kept on this machine; not tried again with this key."));
|
|
1672
|
+
console.log(dim(` Since: ${status.delete_refused.since}`));
|
|
1673
|
+
console.log("");
|
|
1674
|
+
}
|
|
1675
|
+
if (keyMissing)
|
|
1676
|
+
printVaultKeyMissingWarning(keyMissing);
|
|
1677
|
+
// Sends wait for secrets the daemon's vault key doesn't decrypt: said
|
|
1678
|
+
// below, or here while nothing waits yet. Some of them, with no hold:
|
|
1679
|
+
// sending goes on, said here (engram#694).
|
|
1680
|
+
const mismatchHeld = status.error_type === "vault_mismatch" && status.health !== "healthy";
|
|
1681
|
+
const held = status.vault_undecryptable?.held === true;
|
|
1682
|
+
if (status.vault_undecryptable && !mismatchHeld && !held) {
|
|
1683
|
+
printVaultUndecryptableWarning(status.vault_undecryptable);
|
|
1684
|
+
}
|
|
1685
|
+
if (status.health === "healthy") {
|
|
1686
|
+
if (held)
|
|
1687
|
+
printVaultMismatchWarning(status);
|
|
1688
|
+
if (status.last_sync_at) {
|
|
1689
|
+
console.log(`${dim("Last sync:")} ${status.last_sync_at}`);
|
|
1690
|
+
}
|
|
1691
|
+
return;
|
|
1692
|
+
}
|
|
1693
|
+
// Waiting on the vault key: said above when it can't be read now. One
|
|
1694
|
+
// that is another user's is said with them, and gets the words below.
|
|
1695
|
+
if (status.error_type === "vault_key" && keyProblem)
|
|
1696
|
+
return;
|
|
1697
|
+
if (status.error_type === "vault_key" && key === "key") {
|
|
1698
|
+
console.log("");
|
|
1699
|
+
console.log(red(" Sending is waiting on ~/.engram/vault-key, which reads fine now."));
|
|
1700
|
+
console.log(dim(" The daemon reads it again within a minute, then sends what it held."));
|
|
1701
|
+
if (status.pending_messages > 0) {
|
|
1702
|
+
console.log(dim(` ${plural(status.pending_messages, "message")} waiting to sync`));
|
|
47
1703
|
}
|
|
1704
|
+
console.log("");
|
|
1705
|
+
return;
|
|
48
1706
|
}
|
|
49
|
-
|
|
50
|
-
|
|
1707
|
+
if (mismatchHeld) {
|
|
1708
|
+
printVaultMismatchWarning(status);
|
|
1709
|
+
return;
|
|
1710
|
+
}
|
|
1711
|
+
// The same words as the daemon's log line and desktop notification. This
|
|
1712
|
+
// kept a copy of its own, which had no storage_full entry: a full account
|
|
1713
|
+
// showed the raw server error instead of what to do about it.
|
|
1714
|
+
const msg = syncErrorSummary(status.error_type, status.storage);
|
|
1715
|
+
console.log("");
|
|
1716
|
+
console.log(red(` WARNING: ${msg}`));
|
|
1717
|
+
if (status.pending_messages > 0) {
|
|
1718
|
+
console.log(red(` ${plural(status.pending_messages, "message")} waiting to sync`));
|
|
1719
|
+
}
|
|
1720
|
+
// The latest failure: last_error_at moves with each one.
|
|
1721
|
+
if (status.last_error_at) {
|
|
1722
|
+
console.log(dim(` Last error: ${status.last_error_at}`));
|
|
1723
|
+
}
|
|
1724
|
+
// When the daemon tries again (engram#596). A time already past means a
|
|
1725
|
+
// try is due at the next flush, seconds away, so it says nothing.
|
|
1726
|
+
const next = status.next_retry_at ? Date.parse(status.next_retry_at) : NaN;
|
|
1727
|
+
const wait = next - Date.now();
|
|
1728
|
+
if (wait > 0) {
|
|
1729
|
+
console.log(dim(` Next try: in ${formatWait(wait)} (${status.next_retry_at})`));
|
|
51
1730
|
}
|
|
52
|
-
|
|
53
|
-
return readLaunchdPid();
|
|
1731
|
+
console.log("");
|
|
54
1732
|
}
|
|
55
|
-
|
|
56
|
-
|
|
1733
|
+
// ── macOS: a launchd agent ──
|
|
1734
|
+
//
|
|
1735
|
+
// ~/Library/LaunchAgents/app.getengram.daemon.plist: launchd loads it when
|
|
1736
|
+
// the user logs in and starts the daemon, and starts it again after a crash.
|
|
1737
|
+
// See launchd.ts.
|
|
1738
|
+
/**
|
|
1739
|
+
* The plist for this CLI: this Node, this build's worker, this home. Or why
|
|
1740
|
+
* there can't be one: a path with a control character in it, which a plist
|
|
1741
|
+
* can't hold. The reason has the path JSON-escaped, so it is safe to print.
|
|
1742
|
+
*/
|
|
1743
|
+
function plistForThisCli() {
|
|
1744
|
+
const node = nodePathForEntry();
|
|
1745
|
+
try {
|
|
1746
|
+
return {
|
|
1747
|
+
text: generatePlist({
|
|
1748
|
+
node,
|
|
1749
|
+
// A CLI installed with brew runs from a versioned keg too (engram#652).
|
|
1750
|
+
worker: throughOptLink(workerPath()),
|
|
1751
|
+
// None while it can't be written: launchd would never start the
|
|
1752
|
+
// daemon (engram#679).
|
|
1753
|
+
log: logProblem() === null ? LOG_FILE : null,
|
|
1754
|
+
home: homedir(),
|
|
1755
|
+
// launchd hands a job a bare PATH (/usr/bin:/bin:/usr/sbin:/sbin) —
|
|
1756
|
+
// npm is not on it. The ABI self-heal in preflight.ts shells out to
|
|
1757
|
+
// `npm rebuild better-sqlite3`, so without this it fails with
|
|
1758
|
+
// command-not-found at the exact moment it is needed. npm ships
|
|
1759
|
+
// beside the node binary, so node's own directory goes first.
|
|
1760
|
+
path: `${dirname(node)}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`,
|
|
1761
|
+
}),
|
|
1762
|
+
};
|
|
1763
|
+
}
|
|
1764
|
+
catch (err) {
|
|
1765
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
/** The plist's text as it is now; null when there is none to read. */
|
|
1769
|
+
function installedPlistText() {
|
|
1770
|
+
try {
|
|
1771
|
+
return readFileSync(plistPath(), "utf-8");
|
|
1772
|
+
}
|
|
1773
|
+
catch {
|
|
57
1774
|
return null;
|
|
1775
|
+
}
|
|
1776
|
+
}
|
|
1777
|
+
/**
|
|
1778
|
+
* launchd opens the log for the job, and creates a missing one with the
|
|
1779
|
+
* default 0644 (engram#627), so it is made first, 0600. Best effort: the
|
|
1780
|
+
* worker sets every file in ~/.engram to 0600 when it starts anyway.
|
|
1781
|
+
*/
|
|
1782
|
+
function prepareLaunchdLog() {
|
|
58
1783
|
try {
|
|
59
|
-
|
|
60
|
-
encoding: "utf-8",
|
|
61
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
62
|
-
});
|
|
63
|
-
const match = output.match(/"PID"\s*=\s*(\d+)/);
|
|
64
|
-
if (match)
|
|
65
|
-
return parseInt(match[1], 10);
|
|
66
|
-
// Also check the tabular format: PID\tStatus\tLabel
|
|
67
|
-
const lines = output.trim().split("\n");
|
|
68
|
-
for (const line of lines) {
|
|
69
|
-
const parts = line.split("\t");
|
|
70
|
-
if (parts.length >= 1) {
|
|
71
|
-
const pid = parseInt(parts[0], 10);
|
|
72
|
-
if (!isNaN(pid) && pid > 0)
|
|
73
|
-
return pid;
|
|
74
|
-
}
|
|
75
|
-
}
|
|
1784
|
+
prepareLogSync();
|
|
76
1785
|
}
|
|
77
1786
|
catch {
|
|
78
|
-
//
|
|
1787
|
+
// the worker's start covers it
|
|
79
1788
|
}
|
|
80
|
-
return null;
|
|
81
1789
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
1790
|
+
/** "~/Library/LaunchAgents belongs to root, not to you" (engram#678). */
|
|
1791
|
+
function launchAgentsWhose({ root }) {
|
|
1792
|
+
return `~/Library/LaunchAgents belongs to ${root ? "root" : "another user"}, not to you`;
|
|
1793
|
+
}
|
|
1794
|
+
/**
|
|
1795
|
+
* Writing the plist failed because ~/Library/LaunchAgents isn't the user's
|
|
1796
|
+
* (engram#678): whether it is root's. Null when it failed for another
|
|
1797
|
+
* reason.
|
|
1798
|
+
*/
|
|
1799
|
+
function launchAgentsRefused(err) {
|
|
1800
|
+
const code = err?.code;
|
|
1801
|
+
if (code !== "EACCES" && code !== "EPERM")
|
|
1802
|
+
return null;
|
|
1803
|
+
return launchAgentsNotYours();
|
|
1804
|
+
}
|
|
1805
|
+
/**
|
|
1806
|
+
* Rewrite and reload a plist of ours that an older CLI wrote (engram#469),
|
|
1807
|
+
* or that can't start the daemon (engram#616): one launchd can't read, or
|
|
1808
|
+
* one naming a Node or a CLI that has since moved. Or one naming them in a
|
|
1809
|
+
* Homebrew version that the next upgrade removes (engram#652).
|
|
1810
|
+
*
|
|
1811
|
+
* Without this, a plist defect is permanent: `brew upgrade` / `npm i -g`
|
|
1812
|
+
* replaces the code but leaves the plist, so the machine keeps launching the
|
|
1813
|
+
* old entry point forever. That is how a self-heal shipped in 0.4.2 was still
|
|
1814
|
+
* inert on a 0.6.0 install. Runs on any daemon start; silent when current.
|
|
1815
|
+
*
|
|
1816
|
+
* One the user switched off in launchd is left as it is, as on Linux: only
|
|
1817
|
+
* `engram install` switches it back on (engram#654).
|
|
1818
|
+
*
|
|
1819
|
+
* In a ~/Library/LaunchAgents that isn't the user's, it can't be rewritten:
|
|
1820
|
+
* that is said, unless `quiet` (engram#715). It used to be left broken
|
|
1821
|
+
* without a word, while `engram status` said to run `engram install`,
|
|
1822
|
+
* which failed on it too. Auto-capture says it with the rest, and `engram
|
|
1823
|
+
* start --install` as it turns start at login on.
|
|
1824
|
+
*
|
|
1825
|
+
* From a CLI that a package runner runs from its cache, it is left as it
|
|
1826
|
+
* is (engram#665): the cache can be cleared at any time. "runner" when it
|
|
1827
|
+
* is broken, and not switched off, for the caller to say.
|
|
1828
|
+
*/
|
|
1829
|
+
export function repairLaunchdIfStale(plist, { quiet = false } = {}) {
|
|
1830
|
+
if (process.platform !== "darwin")
|
|
1831
|
+
return "unchanged";
|
|
1832
|
+
const state = plist ?? readPlist();
|
|
1833
|
+
if (state.kind !== "ours")
|
|
1834
|
+
return "unchanged";
|
|
1835
|
+
if (!state.broken && !state.outdated)
|
|
1836
|
+
return "unchanged";
|
|
1837
|
+
if (runnerCacheOfThisCli() !== null)
|
|
1838
|
+
return state.broken && agentDisabled() !== true ? "runner" : "unchanged";
|
|
1839
|
+
// Only a source checkout run through tsx has no worker.js: the build ships it.
|
|
1840
|
+
if (!existsSync(workerPath()))
|
|
1841
|
+
return "unchanged";
|
|
1842
|
+
// Never fails the command it runs in: a plist that can't be made or
|
|
1843
|
+
// written is left as it is, and `engram install` says why.
|
|
1844
|
+
const made = plistForThisCli();
|
|
1845
|
+
if ("error" in made)
|
|
1846
|
+
return "unchanged";
|
|
1847
|
+
// One the user switched off is left as it is too: reloading it would stop
|
|
1848
|
+
// the daemon launchd still runs, if it runs one, and launchd wouldn't load
|
|
1849
|
+
// it again.
|
|
1850
|
+
if (agentDisabled() === true)
|
|
1851
|
+
return "unchanged";
|
|
1852
|
+
try {
|
|
1853
|
+
writePlistFile(made.text);
|
|
1854
|
+
}
|
|
1855
|
+
catch (err) {
|
|
1856
|
+
const notYours = launchAgentsRefused(err);
|
|
1857
|
+
if (notYours === null)
|
|
1858
|
+
return "unchanged";
|
|
1859
|
+
if (!quiet) {
|
|
1860
|
+
console.error(red(`Couldn't update start at login: ${launchAgentsWhose(notYours)}.`));
|
|
1861
|
+
console.error(dim(` Make it yours with: ${LAUNCH_AGENTS_FIX}`));
|
|
1862
|
+
console.error(dim(` Then run: ${engramCommand("install")}`));
|
|
1863
|
+
}
|
|
1864
|
+
return "refused";
|
|
1865
|
+
}
|
|
1866
|
+
prepareLaunchdLog();
|
|
1867
|
+
// launchd keeps running the job it loaded until it is unloaded. One it
|
|
1868
|
+
// can't load now loads from the file at the next login.
|
|
1869
|
+
reloadAgent();
|
|
1870
|
+
console.log(`${bold("Updated auto-start configuration")} ${dim(`(plist v${PLIST_VERSION})`)}`);
|
|
1871
|
+
return "repaired";
|
|
1872
|
+
}
|
|
1873
|
+
function isLaunchdInstalled() {
|
|
1874
|
+
// Darwin only: CLIs before engram#602 wrote this plist on every platform,
|
|
1875
|
+
// and a stray copy must not read as "auto-start enabled" or send status
|
|
1876
|
+
// shelling out to launchctl on Windows.
|
|
1877
|
+
return process.platform === "darwin" && existsSync(plistPath());
|
|
1878
|
+
}
|
|
1879
|
+
/** A path as one word of a command line for the user to run. */
|
|
1880
|
+
function shellWord(path) {
|
|
1881
|
+
return /^[\w@%+=:,./-]+$/.test(path) ? path : `'${path.replace(/'/g, "'\\''")}'`;
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Start at login on macOS, for `engram install` and `engram start
|
|
1885
|
+
* --install`: write the plist, switch the job on in launchd, and have
|
|
1886
|
+
* launchd load it, which starts the daemon (RunAtLoad). A job launchd has
|
|
1887
|
+
* loaded already isn't loaded again, so it starts no daemon: with `start`
|
|
1888
|
+
* (no daemon runs), launchd is asked to start one then (engram#691).
|
|
1889
|
+
* `again`: the command to run again, once the plist can be written.
|
|
1890
|
+
*/
|
|
1891
|
+
async function enableLaunchdStartAtLogin(start = false, again = engramCommand("install")) {
|
|
1892
|
+
if (!existsSync(workerPath())) {
|
|
1893
|
+
// Only a source checkout run through tsx gets here: the build ships it.
|
|
1894
|
+
console.error(red(`Can't turn on start at login: ${workerPath()} is missing.`));
|
|
1895
|
+
process.exitCode = 1;
|
|
87
1896
|
return;
|
|
88
1897
|
}
|
|
89
|
-
const
|
|
90
|
-
if (
|
|
91
|
-
console.
|
|
92
|
-
|
|
93
|
-
|
|
1898
|
+
const made = plistForThisCli();
|
|
1899
|
+
if ("error" in made) {
|
|
1900
|
+
console.error(red("Can't turn on start at login: a launchd job can't hold one of the paths it needs."));
|
|
1901
|
+
console.error(dim(` ${made.error}`));
|
|
1902
|
+
process.exitCode = 1;
|
|
94
1903
|
return;
|
|
95
1904
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
1905
|
+
const unchanged = installedPlistText() === made.text;
|
|
1906
|
+
if (!unchanged) {
|
|
1907
|
+
try {
|
|
1908
|
+
writePlistFile(made.text);
|
|
1909
|
+
}
|
|
1910
|
+
catch (err) {
|
|
1911
|
+
// engram#678: the error alone names a temporary file in the folder,
|
|
1912
|
+
// and not why.
|
|
1913
|
+
const notYours = launchAgentsRefused(err);
|
|
1914
|
+
if (notYours) {
|
|
1915
|
+
console.error(red(`Couldn't turn on start at login: ${launchAgentsWhose(notYours)}.`));
|
|
1916
|
+
console.error(dim(` Make it yours with: ${LAUNCH_AGENTS_FIX}`));
|
|
1917
|
+
console.error(dim(` Then run '${again}' again.`));
|
|
1918
|
+
}
|
|
1919
|
+
else {
|
|
1920
|
+
console.error(red("Couldn't turn on start at login."));
|
|
1921
|
+
console.error(dim(` ${err instanceof Error ? err.message : String(err)}`));
|
|
1922
|
+
}
|
|
1923
|
+
process.exitCode = 1;
|
|
1924
|
+
return;
|
|
116
1925
|
}
|
|
117
1926
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
1927
|
+
prepareLaunchdLog();
|
|
1928
|
+
// Install is the user asking for start at login, so it switches the job
|
|
1929
|
+
// back on where they switched it off (engram#654). Where launchd won't take
|
|
1930
|
+
// that, the load below does it, with load -w.
|
|
1931
|
+
const switchedOn = agentDisabled() === false || enableAgent();
|
|
1932
|
+
// Loading the job starts the daemon (a second one finds the first and
|
|
1933
|
+
// exits, engram#612). One launchd has loaded already is loaded again only
|
|
1934
|
+
// when the plist changed: unloading it stops the daemon launchd runs.
|
|
1935
|
+
const loadedAlready = unchanged && switchedOn && agentLoaded();
|
|
1936
|
+
const failed = loadedAlready ? null : reloadAgent({ turnOn: true });
|
|
1937
|
+
if (failed !== null) {
|
|
1938
|
+
console.log(`Plist written to ${plistPath()}`);
|
|
1939
|
+
console.log(dim(` launchctl: ${failed}`));
|
|
1940
|
+
console.log(`Run manually: launchctl load -w ${shellWord(plistPath())}`);
|
|
1941
|
+
return;
|
|
122
1942
|
}
|
|
1943
|
+
console.log(`${bold("Auto-start enabled")} — daemon will start on login`);
|
|
1944
|
+
console.log(`${dim("Plist:")} ${plistPath()}`);
|
|
1945
|
+
await printLoginVaultKeyWarning();
|
|
1946
|
+
// A job launchd had loaded already starts no daemon now: after `engram
|
|
1947
|
+
// stop`, its daemon exited 0, which KeepAlive doesn't start again
|
|
1948
|
+
// (engram#691). It is started as `engram start` starts it: through
|
|
1949
|
+
// launchd, which starts it again after a crash. Windows and Linux start
|
|
1950
|
+
// one here too.
|
|
1951
|
+
if (start && loadedAlready && !reportStart(await startInBackground()))
|
|
1952
|
+
process.exitCode = 1;
|
|
123
1953
|
}
|
|
124
|
-
|
|
1954
|
+
/**
|
|
1955
|
+
* Start at login when auto-capture turns capture on: add the agent when
|
|
1956
|
+
* there is none, and repair one of ours that is broken or outdated. Unlike
|
|
1957
|
+
* `engram install`, it leaves a job the user switched off in launchd off
|
|
1958
|
+
* (engram#654), as on Windows and Linux. Never fails the command it runs
|
|
1959
|
+
* after.
|
|
1960
|
+
*
|
|
1961
|
+
* "changed": it added or repaired the agent, and said so. "failed": it
|
|
1962
|
+
* couldn't add one, which autoEnableCapture says along with the rest.
|
|
1963
|
+
* "runner": there is none that works, and this CLI runs from a package
|
|
1964
|
+
* runner's cache, which nothing is pointed at (engram#665).
|
|
1965
|
+
*/
|
|
1966
|
+
function autoEnableLaunchdStartAtLogin() {
|
|
1967
|
+
const plist = readPlist();
|
|
1968
|
+
if (plist.kind === "ours") {
|
|
1969
|
+
const repair = repairLaunchdIfStale(plist, { quiet: true });
|
|
1970
|
+
return repair === "repaired" ? "changed" : repair === "refused" ? "failed" : repair;
|
|
1971
|
+
}
|
|
1972
|
+
// Only a source checkout run through tsx has no worker.js: the build ships it.
|
|
1973
|
+
if (!existsSync(workerPath()))
|
|
1974
|
+
return "unchanged";
|
|
1975
|
+
if (runnerCacheOfThisCli() !== null)
|
|
1976
|
+
return "runner";
|
|
1977
|
+
const made = plistForThisCli();
|
|
1978
|
+
if ("error" in made)
|
|
1979
|
+
return "failed";
|
|
125
1980
|
try {
|
|
126
|
-
|
|
127
|
-
config.autocapture = v;
|
|
128
|
-
await saveConfig(config);
|
|
1981
|
+
writePlistFile(made.text);
|
|
129
1982
|
}
|
|
130
1983
|
catch {
|
|
131
|
-
|
|
1984
|
+
return "failed";
|
|
1985
|
+
}
|
|
1986
|
+
prepareLaunchdLog();
|
|
1987
|
+
// launchd remembers a job switched off after its plist is gone. Said once:
|
|
1988
|
+
// from now on the plist is there, and current.
|
|
1989
|
+
if (agentDisabled() === true) {
|
|
1990
|
+
console.log(`${bold("Start at login is switched off")} in launchd`);
|
|
1991
|
+
console.log(dim(` Run '${engramCommand("install")}' to start the daemon when you log in.`));
|
|
1992
|
+
return "changed";
|
|
132
1993
|
}
|
|
1994
|
+
loadAgent(); // one launchd can't load now loads at the next login
|
|
1995
|
+
console.log(`${bold("Auto-start enabled")} — daemon will start on login`);
|
|
1996
|
+
return "changed";
|
|
133
1997
|
}
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
1998
|
+
/**
|
|
1999
|
+
* Turn start at login off: unload the agent and remove its plist.
|
|
2000
|
+
* Unloading it stops the daemon launchd runs for it, where on Linux and
|
|
2001
|
+
* Windows the daemon keeps running until `engram stop` or sign-out
|
|
2002
|
+
* (engram#667): that one is started again, outside launchd. One launchd
|
|
2003
|
+
* won't unload runs on under launchd until sign-out, and the plist it
|
|
2004
|
+
* would load at the next login is gone all the same.
|
|
2005
|
+
*/
|
|
2006
|
+
async function uninstallLaunchd() {
|
|
2007
|
+
if (!isLaunchdInstalled()) {
|
|
2008
|
+
console.log("Auto-start isn't on.");
|
|
2009
|
+
await printKeepsRunning();
|
|
139
2010
|
return;
|
|
140
2011
|
}
|
|
2012
|
+
// The plist can't be removed from a folder that isn't the user's
|
|
2013
|
+
// (engram#715), and launchd would load it again at the next login:
|
|
2014
|
+
// launchd, and the daemon it runs, are left as they are.
|
|
2015
|
+
const notYours = launchAgentsNotYours();
|
|
2016
|
+
if (notYours) {
|
|
2017
|
+
console.error(red(`Couldn't turn off start at login: ${launchAgentsWhose(notYours)}.`));
|
|
2018
|
+
console.error(dim(` Make it yours with: ${LAUNCH_AGENTS_FIX}`));
|
|
2019
|
+
console.error(dim(` Then run '${engramCommand("uninstall")}' again.`));
|
|
2020
|
+
process.exitCode = 1;
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
const pid = agentPid();
|
|
2024
|
+
const ran = pid !== null && alive(pid) ? pid : null;
|
|
2025
|
+
const unloaded = unloadAgent();
|
|
141
2026
|
try {
|
|
142
|
-
|
|
143
|
-
console.log(
|
|
2027
|
+
rmSync(plistPath(), { force: true });
|
|
2028
|
+
console.log(`${bold("Auto-start disabled")} — launchd agent removed`);
|
|
144
2029
|
}
|
|
145
2030
|
catch {
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
2031
|
+
// Unloaded all the same, and loaded again at the next login: the
|
|
2032
|
+
// daemon is started again all the same.
|
|
2033
|
+
console.error(red("Couldn't remove the launchd agent."));
|
|
2034
|
+
console.error(dim(` Remove ${plistPath()} to turn start at login off.`));
|
|
2035
|
+
process.exitCode = 1;
|
|
151
2036
|
}
|
|
152
|
-
|
|
2037
|
+
if (ran === null)
|
|
2038
|
+
await printKeepsRunning();
|
|
2039
|
+
else
|
|
2040
|
+
await keepRunning(ran, unloaded);
|
|
153
2041
|
}
|
|
154
|
-
/**
|
|
155
|
-
|
|
156
|
-
|
|
2042
|
+
/**
|
|
2043
|
+
* Start the daemon again, as `engram start` would, once the one launchd
|
|
2044
|
+
* ran for the agent just unloaded has exited (engram#667), and say it
|
|
2045
|
+
* keeps running. Not before: a worker started while that one still
|
|
2046
|
+
* answers takes it for the daemon, and leaves the capture to it. From
|
|
2047
|
+
* ~/.engram's key, server and vault key, as launchd's read them, not ones
|
|
2048
|
+
* set in this command's environment (withoutEnvOverrides). When it can't
|
|
2049
|
+
* be, that is said, and the command fails. `unloaded`: whether launchctl
|
|
2050
|
+
* took the unload (unloadAgent).
|
|
2051
|
+
*/
|
|
2052
|
+
async function keepRunning(ran, unloaded) {
|
|
2053
|
+
// launchctl took neither the bootout nor the unload. A daemon launchd
|
|
2054
|
+
// still runs, refusing them, answers as running, not stopping; one
|
|
2055
|
+
// bootout gave up waiting for answers as stopping, and is waited for.
|
|
2056
|
+
if (!unloaded && (await runsOn()))
|
|
2057
|
+
return;
|
|
2058
|
+
const slow = () => console.log(dim(" Waiting for the daemon launchd ran to finish what it was sending..."));
|
|
2059
|
+
if (!(await exited(ran, slow))) {
|
|
2060
|
+
// Never stopped after all: it answers as running.
|
|
2061
|
+
if (await runsOn())
|
|
2062
|
+
return;
|
|
2063
|
+
console.error(red(`The daemon launchd ran (pid ${ran}) is stopping with its agent, and hasn't finished, so it wasn't started again.`));
|
|
2064
|
+
console.error(dim(` Run '${engramCommand("start")}' in a moment to start it again.`));
|
|
2065
|
+
process.exitCode = 1;
|
|
157
2066
|
return;
|
|
158
|
-
try {
|
|
159
|
-
const { DaemonDb } = await import("./db.js");
|
|
160
|
-
const db = new DaemonDb(DB_FILE);
|
|
161
|
-
const stats = db.getStats();
|
|
162
|
-
db.close();
|
|
163
|
-
console.log(`${dim("Sessions captured:")} ${stats.sessionsMapped}`);
|
|
164
|
-
console.log(`${dim("Pending sync:")} ${stats.pendingMessages} messages`);
|
|
165
|
-
console.log(`${dim("Files tracked:")} ${stats.trackedFiles}`);
|
|
166
2067
|
}
|
|
167
|
-
|
|
168
|
-
|
|
2068
|
+
// Another, started meanwhile, or one running as root for them (engram#680).
|
|
2069
|
+
const found = await findDaemon();
|
|
2070
|
+
if (found.state !== "stopped") {
|
|
2071
|
+
await printKeepsRunning(found);
|
|
2072
|
+
return;
|
|
169
2073
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
console.
|
|
175
|
-
|
|
176
|
-
await printDbStats();
|
|
2074
|
+
// One started now would stop at once (engram#659, engram#723). The banner
|
|
2075
|
+
// before the command said what is wrong, and how to fix it.
|
|
2076
|
+
if (stopsCapture(foreignFiles()) || lockedDir() !== null) {
|
|
2077
|
+
console.error(red("The daemon launchd ran stopped with its agent, and wasn't started again: one started now would stop at once."));
|
|
2078
|
+
console.error(dim(` Once that's fixed, run '${engramCommand("start")}' to start it.`));
|
|
2079
|
+
process.exitCode = 1;
|
|
177
2080
|
return;
|
|
178
2081
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
console.log(`${dim("Log:")} ${LOG_FILE}`);
|
|
186
|
-
if (isLaunchdInstalled()) {
|
|
187
|
-
console.log(`${dim("Auto-start:")} enabled (launchd)`);
|
|
2082
|
+
const started = await waitForWorker(spawnWorker(withoutEnvOverrides()));
|
|
2083
|
+
if (started.state === "failed") {
|
|
2084
|
+
printStartFailed("The daemon launchd ran stopped with its agent, and couldn't be started again");
|
|
2085
|
+
console.error(dim(` Run '${engramCommand("start")}' to start it.`));
|
|
2086
|
+
process.exitCode = 1;
|
|
2087
|
+
return;
|
|
188
2088
|
}
|
|
2089
|
+
console.log(dim(keepsRunning()));
|
|
2090
|
+
if (started.state === "starting")
|
|
2091
|
+
console.log(dim(` It is still starting: check on it with '${engramCommand("status")}' in a minute.`));
|
|
189
2092
|
}
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
2093
|
+
/**
|
|
2094
|
+
* Whether the daemon answers as running, not stopping, as one launchd
|
|
2095
|
+
* didn't stop with its agent does: then that it keeps running is said.
|
|
2096
|
+
*/
|
|
2097
|
+
async function runsOn() {
|
|
2098
|
+
const found = await findDaemon();
|
|
2099
|
+
if (found.state !== "running")
|
|
2100
|
+
return false;
|
|
2101
|
+
await printKeepsRunning(found);
|
|
2102
|
+
return true;
|
|
2103
|
+
}
|
|
2104
|
+
// ── Windows: a per-user Run entry ──
|
|
2105
|
+
//
|
|
2106
|
+
// HKCU\…\Run is per-user sign-in startup: it needs no admin rights, it is
|
|
2107
|
+
// what apps' "open at login" settings use, and Windows lists it under Startup
|
|
2108
|
+
// apps, where it can be switched off. (A Task Scheduler logon task would work
|
|
2109
|
+
// too, but creating one with schtasks can take admin rights.)
|
|
2110
|
+
const RUN_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run";
|
|
2111
|
+
const RUN_VALUE = "Engram";
|
|
2112
|
+
// Switching an entry off under Startup apps (Settings, Task Manager) leaves
|
|
2113
|
+
// it in the Run key and writes a value of the same name here instead: its
|
|
2114
|
+
// first byte is 3 for off, 2 or 6 for on, and no value at all is on. The
|
|
2115
|
+
// format is undocumented; "an odd first byte is off" is the observed rule.
|
|
2116
|
+
// Without reading it, status said "enabled" for an entry Windows skips.
|
|
2117
|
+
const APPROVED_KEY = "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run";
|
|
2118
|
+
/**
|
|
2119
|
+
* reg.exe by absolute path: a bare name is looked up in the current
|
|
2120
|
+
* directory before PATH on Windows.
|
|
2121
|
+
*/
|
|
2122
|
+
function regExe() {
|
|
2123
|
+
return win32.join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
|
|
2124
|
+
}
|
|
2125
|
+
/** The command line Windows runs at sign-in. Exported for tests. */
|
|
2126
|
+
export function runEntryCommand(nodePath, entryPath) {
|
|
2127
|
+
return `"${nodePath}" "${entryPath}"`;
|
|
2128
|
+
}
|
|
2129
|
+
/**
|
|
2130
|
+
* Node's own path, through any links. A version manager can start Node
|
|
2131
|
+
* through a link made for one shell session (fnm's multishell directories),
|
|
2132
|
+
* which may be gone by the next sign-in; the program it links to stays.
|
|
2133
|
+
* Homebrew's Node goes by its opt link, which outlasts the version the next
|
|
2134
|
+
* `brew upgrade` removes (engram#652); on Windows, Scoop's by its `current`
|
|
2135
|
+
* junction, which outlasts the version `scoop cleanup` removes (engram#664).
|
|
2136
|
+
*/
|
|
2137
|
+
function nodePathForEntry() {
|
|
2138
|
+
try {
|
|
2139
|
+
const real = realpathSync.native(process.execPath);
|
|
2140
|
+
return process.platform === "win32" ? throughScoopCurrent(real) : throughOptLink(real);
|
|
2141
|
+
}
|
|
2142
|
+
catch {
|
|
2143
|
+
return process.execPath;
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Our value's data in a `reg export` of the Run key: null when it isn't
|
|
2148
|
+
* there, "" when it is but isn't a plain string. Exported for tests.
|
|
2149
|
+
*
|
|
2150
|
+
* The export, not `reg query`: reg prints in the console's code page, so a
|
|
2151
|
+
* path with a letter outside it (the "í" of "C:\Users\Ana María\…") came
|
|
2152
|
+
* back mangled and a working entry read as broken. The export is UTF-16.
|
|
2153
|
+
*/
|
|
2154
|
+
export function parseRunExport(exported) {
|
|
2155
|
+
const data = exportedData(exported);
|
|
2156
|
+
if (data === null)
|
|
2157
|
+
return null;
|
|
2158
|
+
const quoted = data.match(/^"((?:[^"\\]|\\.)*)"$/);
|
|
2159
|
+
return quoted ? quoted[1].replace(/\\(.)/g, "$1") : "";
|
|
2160
|
+
}
|
|
2161
|
+
/**
|
|
2162
|
+
* Whether a `reg export` of the StartupApproved key has our entry switched
|
|
2163
|
+
* off (see APPROVED_KEY). Exported for tests.
|
|
2164
|
+
*/
|
|
2165
|
+
export function parseApprovedExport(exported) {
|
|
2166
|
+
const first = exportedData(exported)?.match(/^hex:([0-9a-f]{2})/i);
|
|
2167
|
+
return !!first && parseInt(first[1], 16) % 2 === 1;
|
|
2168
|
+
}
|
|
2169
|
+
/** What follows `"Engram"=` in an exported key, or null when it isn't there. */
|
|
2170
|
+
function exportedData(exported) {
|
|
2171
|
+
const name = `"${RUN_VALUE.toLowerCase()}"=`;
|
|
2172
|
+
let inKey = false;
|
|
2173
|
+
for (const line of exported.split(/\r?\n/)) {
|
|
2174
|
+
if (line.startsWith("[")) {
|
|
2175
|
+
// The key's own values come first; any subkeys follow.
|
|
2176
|
+
if (inKey)
|
|
2177
|
+
break;
|
|
2178
|
+
inKey = true;
|
|
2179
|
+
}
|
|
2180
|
+
else if (inKey && line.toLowerCase().startsWith(name)) {
|
|
2181
|
+
return line.slice(name.length);
|
|
194
2182
|
}
|
|
195
|
-
return;
|
|
196
2183
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
2184
|
+
return null;
|
|
2185
|
+
}
|
|
2186
|
+
/**
|
|
2187
|
+
* How long a reg.exe call may take. Auto-capture reads the Run entry after
|
|
2188
|
+
* interactive commands (engram#614), so a reg.exe that hung would otherwise
|
|
2189
|
+
* hang each of them; one that times out counts as one that failed.
|
|
2190
|
+
*/
|
|
2191
|
+
const REG_TIMEOUT_MS = 15_000;
|
|
2192
|
+
function runReg(args) {
|
|
2193
|
+
return execFileSync(regExe(), args, {
|
|
2194
|
+
encoding: "utf-8",
|
|
2195
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
2196
|
+
windowsHide: true,
|
|
2197
|
+
timeout: REG_TIMEOUT_MS,
|
|
2198
|
+
});
|
|
2199
|
+
}
|
|
2200
|
+
/** A registry key as `reg export` writes it; null when reg can't (no such key). */
|
|
2201
|
+
function exportKey(key) {
|
|
2202
|
+
let dir;
|
|
2203
|
+
try {
|
|
2204
|
+
dir = mkdtempSync(join(tmpdir(), "engram-"));
|
|
2205
|
+
const file = join(dir, "key.reg");
|
|
2206
|
+
runReg(["export", key, file, "/y"]);
|
|
2207
|
+
const bytes = readFileSync(file);
|
|
2208
|
+
const utf16 = bytes[0] === 0xff && bytes[1] === 0xfe;
|
|
2209
|
+
return bytes.toString(utf16 ? "utf16le" : "utf-8");
|
|
209
2210
|
}
|
|
210
|
-
|
|
211
|
-
|
|
2211
|
+
catch {
|
|
2212
|
+
return null;
|
|
2213
|
+
}
|
|
2214
|
+
finally {
|
|
2215
|
+
if (dir)
|
|
2216
|
+
rmSync(dir, { recursive: true, force: true });
|
|
212
2217
|
}
|
|
213
|
-
console.log("");
|
|
214
2218
|
}
|
|
215
|
-
|
|
216
|
-
function
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
<plist version="1.0">
|
|
222
|
-
<dict>
|
|
223
|
-
<key>Label</key>
|
|
224
|
-
<string>${PLIST_NAME}</string>
|
|
225
|
-
<key>ProgramArguments</key>
|
|
226
|
-
<array>
|
|
227
|
-
<string>${nodePath}</string>
|
|
228
|
-
<string>${workerPath}</string>
|
|
229
|
-
</array>
|
|
230
|
-
<key>RunAtLoad</key>
|
|
231
|
-
<true/>
|
|
232
|
-
<key>KeepAlive</key>
|
|
233
|
-
<dict>
|
|
234
|
-
<key>SuccessfulExit</key>
|
|
235
|
-
<false/>
|
|
236
|
-
</dict>
|
|
237
|
-
<key>StandardOutPath</key>
|
|
238
|
-
<string>${LOG_FILE}</string>
|
|
239
|
-
<key>StandardErrorPath</key>
|
|
240
|
-
<string>${LOG_FILE}</string>
|
|
241
|
-
<key>ThrottleInterval</key>
|
|
242
|
-
<integer>10</integer>
|
|
243
|
-
<key>EnvironmentVariables</key>
|
|
244
|
-
<dict>
|
|
245
|
-
<key>HOME</key>
|
|
246
|
-
<string>${homedir()}</string>
|
|
247
|
-
</dict>
|
|
248
|
-
</dict>
|
|
249
|
-
</plist>`;
|
|
2219
|
+
/** The installed entry's command line; null when there is none, or off Windows. */
|
|
2220
|
+
function readRunEntry() {
|
|
2221
|
+
if (process.platform !== "win32")
|
|
2222
|
+
return null;
|
|
2223
|
+
const exported = exportKey(RUN_KEY);
|
|
2224
|
+
return exported === null ? null : parseRunExport(exported);
|
|
250
2225
|
}
|
|
251
|
-
|
|
252
|
-
|
|
2226
|
+
/** The user switched our entry off under Startup apps. */
|
|
2227
|
+
function switchedOffInStartupApps() {
|
|
2228
|
+
if (process.platform !== "win32")
|
|
2229
|
+
return false;
|
|
2230
|
+
const exported = exportKey(APPROVED_KEY);
|
|
2231
|
+
return exported !== null && parseApprovedExport(exported);
|
|
253
2232
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
2233
|
+
/**
|
|
2234
|
+
* Forget a Startup apps switch-off: no value there means on. For install and
|
|
2235
|
+
* uninstall only, which are the user asking for it on or gone; `engram
|
|
2236
|
+
* start` repairs a broken entry but leaves the switch where the user put it.
|
|
2237
|
+
*/
|
|
2238
|
+
function clearStartupSwitch() {
|
|
257
2239
|
try {
|
|
258
|
-
|
|
259
|
-
console.log(`${bold("Auto-start enabled")} — daemon will start on login`);
|
|
260
|
-
console.log(`${dim("Plist:")} ${PLIST_PATH}`);
|
|
2240
|
+
runReg(["delete", APPROVED_KEY, "/v", RUN_VALUE, "/f"]);
|
|
261
2241
|
}
|
|
262
2242
|
catch {
|
|
263
|
-
|
|
264
|
-
console.log("Run manually: launchctl load -w " + PLIST_PATH);
|
|
2243
|
+
// never switched
|
|
265
2244
|
}
|
|
266
2245
|
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
2246
|
+
/** The command line runEntryCommand writes: Node, then the sign-in entry. */
|
|
2247
|
+
const RUN_ENTRY = /^"([^"]+)"\s+"([^"]+)"$/;
|
|
2248
|
+
/** Either program the entry names is gone (Node moved, CLI uninstalled). */
|
|
2249
|
+
function runEntryBroken(entry) {
|
|
2250
|
+
const m = entry.match(RUN_ENTRY);
|
|
2251
|
+
return !m || !existsSync(m[1]) || !existsSync(m[2]);
|
|
2252
|
+
}
|
|
2253
|
+
/**
|
|
2254
|
+
* The entry starts the CLI from a package runner's cache, which can be
|
|
2255
|
+
* cleared at any time (engram#665): a CLI run that way wrote it, before
|
|
2256
|
+
* none did. Or it names Node by a version of the Scoop app this CLI's Node
|
|
2257
|
+
* goes by the `current` of, which the next update and cleanup remove
|
|
2258
|
+
* (engram#664): never the Node nodePathForEntry names, so a CLI never
|
|
2259
|
+
* rewrites the entry it just wrote.
|
|
2260
|
+
*/
|
|
2261
|
+
function runEntryOutdated(entry) {
|
|
2262
|
+
const m = entry.match(RUN_ENTRY);
|
|
2263
|
+
return m !== null && (runnerCacheOf(m[2]) !== null || scoopVersionOf(m[1], nodePathForEntry()));
|
|
2264
|
+
}
|
|
2265
|
+
/** Add the entry, or point it at this CLI. Null when reg did; else what reg said, to print. */
|
|
2266
|
+
function writeRunEntry() {
|
|
2267
|
+
try {
|
|
2268
|
+
runReg([
|
|
2269
|
+
"add", RUN_KEY, "/v", RUN_VALUE, "/t", "REG_SZ",
|
|
2270
|
+
"/d", runEntryCommand(nodePathForEntry(), loginStartPath()), "/f",
|
|
2271
|
+
]);
|
|
2272
|
+
return null;
|
|
2273
|
+
}
|
|
2274
|
+
catch (err) {
|
|
2275
|
+
return commandFailure(err);
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
/** Remove the entry. Null when reg did; else what reg said, to print. */
|
|
2279
|
+
function deleteRunEntry() {
|
|
2280
|
+
try {
|
|
2281
|
+
runReg(["delete", RUN_KEY, "/v", RUN_VALUE, "/f"]);
|
|
2282
|
+
return null;
|
|
2283
|
+
}
|
|
2284
|
+
catch (err) {
|
|
2285
|
+
return commandFailure(err);
|
|
271
2286
|
}
|
|
2287
|
+
}
|
|
2288
|
+
/**
|
|
2289
|
+
* Point a broken entry at this CLI, the counterpart of repairLaunchdIfStale:
|
|
2290
|
+
* an entry naming a Node or a CLI that has since moved fails at every
|
|
2291
|
+
* sign-in without a word. And one naming a package runner's cache, which
|
|
2292
|
+
* can be cleared at any time (engram#665), or Node by a Scoop version the
|
|
2293
|
+
* next update and cleanup remove (engram#664). A working entry is left as
|
|
2294
|
+
* it is. So is any, from a CLI that runs from such a cache: "runner" when
|
|
2295
|
+
* it is broken, and not switched off in Startup apps, for the caller to say.
|
|
2296
|
+
*/
|
|
2297
|
+
export function repairRunEntryIfStale(entry = readRunEntry()) {
|
|
2298
|
+
if (entry === null)
|
|
2299
|
+
return "unchanged";
|
|
2300
|
+
const broken = runEntryBroken(entry);
|
|
2301
|
+
if (!broken && !runEntryOutdated(entry))
|
|
2302
|
+
return "unchanged";
|
|
2303
|
+
if (runnerCacheOfThisCli() !== null)
|
|
2304
|
+
return broken && !switchedOffInStartupApps() ? "runner" : "unchanged";
|
|
2305
|
+
if (!existsSync(loginStartPath()) || writeRunEntry() !== null)
|
|
2306
|
+
return "unchanged";
|
|
2307
|
+
console.log(bold("Updated the start-at-login entry"));
|
|
2308
|
+
return "repaired";
|
|
2309
|
+
}
|
|
2310
|
+
/** The plist CLIs before engram#602 wrote off macOS too. */
|
|
2311
|
+
function removeStrayPlist() {
|
|
272
2312
|
try {
|
|
273
|
-
|
|
2313
|
+
rmSync(plistPath(), { force: true });
|
|
274
2314
|
}
|
|
275
2315
|
catch {
|
|
276
|
-
//
|
|
2316
|
+
// nothing reads it on this OS
|
|
2317
|
+
}
|
|
2318
|
+
}
|
|
2319
|
+
// ── Linux: a systemd user unit (engram#615) ──
|
|
2320
|
+
//
|
|
2321
|
+
// ~/.config/systemd/user/engram.service, linked into default.target by
|
|
2322
|
+
// `systemctl --user enable`: the user's service manager starts the daemon at
|
|
2323
|
+
// login and again after a crash. See systemd.ts.
|
|
2324
|
+
/**
|
|
2325
|
+
* The unit for this CLI: this Node, this build's worker, this home. Or why
|
|
2326
|
+
* there can't be one: a path with a control character in it, which a unit
|
|
2327
|
+
* can't hold. The reason has the path JSON-escaped, so it is safe to print.
|
|
2328
|
+
*/
|
|
2329
|
+
function unitForThisCli() {
|
|
2330
|
+
const node = nodePathForEntry();
|
|
2331
|
+
try {
|
|
2332
|
+
return {
|
|
2333
|
+
text: generateUnit({
|
|
2334
|
+
node,
|
|
2335
|
+
worker: throughOptLink(workerPath()),
|
|
2336
|
+
log: LOG_FILE,
|
|
2337
|
+
engramDir: ENGRAM_DIR,
|
|
2338
|
+
home: homedir(),
|
|
2339
|
+
path: `${dirname(node)}:/usr/local/bin:/usr/bin:/bin`,
|
|
2340
|
+
}),
|
|
2341
|
+
};
|
|
2342
|
+
}
|
|
2343
|
+
catch (err) {
|
|
2344
|
+
return { error: err instanceof Error ? err.message : String(err) };
|
|
277
2345
|
}
|
|
2346
|
+
}
|
|
2347
|
+
/** The unit's text as it is now; null when there is none to read. */
|
|
2348
|
+
function installedUnitText() {
|
|
278
2349
|
try {
|
|
279
|
-
|
|
2350
|
+
return readFileSync(unitPath(), "utf-8");
|
|
280
2351
|
}
|
|
281
2352
|
catch {
|
|
282
|
-
|
|
2353
|
+
return null;
|
|
2354
|
+
}
|
|
2355
|
+
}
|
|
2356
|
+
/**
|
|
2357
|
+
* The unit is ours, enabled and current, for this CLI (unitForThisCli), and
|
|
2358
|
+
* the daemon systemd starts from it has everything this command's
|
|
2359
|
+
* environment would give one (daemonEnvOverrides): systemd can run this
|
|
2360
|
+
* CLI's daemon (engram#689). No systemctl call. One the user disabled is
|
|
2361
|
+
* left to them: the daemon is spawned then, as before.
|
|
2362
|
+
*/
|
|
2363
|
+
function systemdRunsThisCli() {
|
|
2364
|
+
if (process.platform !== "linux" || daemonEnvOverrides())
|
|
2365
|
+
return false;
|
|
2366
|
+
const unit = readUnit();
|
|
2367
|
+
if (unit.kind !== "ours" || !unit.enabled)
|
|
2368
|
+
return false;
|
|
2369
|
+
const made = unitForThisCli();
|
|
2370
|
+
return "text" in made && installedUnitText() === made.text;
|
|
2371
|
+
}
|
|
2372
|
+
/**
|
|
2373
|
+
* Rewrite an enabled unit of ours that names a Node or a CLI that has since
|
|
2374
|
+
* moved, or that an older CLI wrote, or that names them in a Homebrew version
|
|
2375
|
+
* (engram#652) or a package runner's cache (engram#665): the counterpart of
|
|
2376
|
+
* repairLaunchdIfStale and repairRunEntryIfStale. One the user disabled is
|
|
2377
|
+
* left as it is. So is any, from a CLI that runs from such a cache:
|
|
2378
|
+
* "runner" when it is broken, for the caller to say.
|
|
2379
|
+
*/
|
|
2380
|
+
export function repairSystemdUnitIfStale(unit = readUnit()) {
|
|
2381
|
+
if (process.platform !== "linux")
|
|
2382
|
+
return "unchanged";
|
|
2383
|
+
if (unit.kind !== "ours" || !unit.enabled)
|
|
2384
|
+
return "unchanged";
|
|
2385
|
+
if (!unit.broken && !unit.outdated)
|
|
2386
|
+
return "unchanged";
|
|
2387
|
+
if (runnerCacheOfThisCli() !== null)
|
|
2388
|
+
return unit.broken ? "runner" : "unchanged";
|
|
2389
|
+
// Only a source checkout run through tsx has no worker.js: the build ships it.
|
|
2390
|
+
if (!existsSync(workerPath()))
|
|
2391
|
+
return "unchanged";
|
|
2392
|
+
// Never fails the command it runs in: a unit that can't be made or written
|
|
2393
|
+
// is left as it is, and `engram install` says why.
|
|
2394
|
+
const made = unitForThisCli();
|
|
2395
|
+
if ("error" in made || !rewriteUnit(made.text))
|
|
2396
|
+
return "unchanged";
|
|
2397
|
+
console.log(`${bold("Updated auto-start configuration")} ${dim(`(systemd unit v${UNIT_VERSION})`)}`);
|
|
2398
|
+
return "repaired";
|
|
2399
|
+
}
|
|
2400
|
+
/** A systemd user session: there is a user service manager, and it answers. */
|
|
2401
|
+
function systemdSession() {
|
|
2402
|
+
const file = systemctlPath();
|
|
2403
|
+
return file !== null && systemdReachable(file);
|
|
2404
|
+
}
|
|
2405
|
+
/**
|
|
2406
|
+
* Start at login on Linux, for `engram install` and `engram start
|
|
2407
|
+
* --install`: write the unit, and enable it. `running`: a daemon runs, or
|
|
2408
|
+
* the caller starts one next, for what is said where there is no start at
|
|
2409
|
+
* login. `start`: start the daemon too, as `engram start` does: through
|
|
2410
|
+
* systemd, once the unit is enabled (engram#689).
|
|
2411
|
+
*/
|
|
2412
|
+
async function enableSystemdStartAtLogin(running, start = !running) {
|
|
2413
|
+
removeStrayPlist();
|
|
2414
|
+
if (readUnit().kind === "foreign") {
|
|
2415
|
+
console.error(red(`Can't turn on start at login: ${unitPath()} is there already, and Engram didn't write it.`));
|
|
2416
|
+
console.error(dim(` Rename or remove it, then run '${engramCommand("install")}' again.`));
|
|
2417
|
+
process.exitCode = 1;
|
|
2418
|
+
return;
|
|
2419
|
+
}
|
|
2420
|
+
const systemctl = systemctlPath();
|
|
2421
|
+
if (systemctl === null || !systemdReachable(systemctl)) {
|
|
2422
|
+
console.log(bold("Start at login isn't available here: it needs a systemd user session ('systemctl --user')."));
|
|
2423
|
+
console.log(dim(running ? runsUntilRestart() : startAfterRestart()));
|
|
2424
|
+
return;
|
|
2425
|
+
}
|
|
2426
|
+
if (!existsSync(workerPath())) {
|
|
2427
|
+
// Only a source checkout run through tsx gets here: the build ships it.
|
|
2428
|
+
console.error(red(`Can't turn on start at login: ${workerPath()} is missing.`));
|
|
2429
|
+
process.exitCode = 1;
|
|
2430
|
+
return;
|
|
2431
|
+
}
|
|
2432
|
+
const made = unitForThisCli();
|
|
2433
|
+
if ("error" in made) {
|
|
2434
|
+
console.error(red("Can't turn on start at login: a systemd unit can't hold one of the paths it needs."));
|
|
2435
|
+
console.error(dim(` ${made.error}`));
|
|
2436
|
+
process.exitCode = 1;
|
|
2437
|
+
return;
|
|
2438
|
+
}
|
|
2439
|
+
const failed = installUnit(systemctl, made.text);
|
|
2440
|
+
if (failed !== null) {
|
|
2441
|
+
console.error(red("Couldn't turn on start at login."));
|
|
2442
|
+
console.error(dim(` systemctl: ${failed}`));
|
|
2443
|
+
process.exitCode = 1;
|
|
2444
|
+
return;
|
|
2445
|
+
}
|
|
2446
|
+
console.log(`${bold("Auto-start enabled")} — daemon will start when you log in (systemd)`);
|
|
2447
|
+
console.log(`${dim("Unit:")} ${unitPath()}`);
|
|
2448
|
+
await printLoginVaultKeyWarning();
|
|
2449
|
+
// Enabled, not started: systemd starts it from the next login on. The
|
|
2450
|
+
// daemon now is started as 'engram start' starts it: by systemd, unless
|
|
2451
|
+
// this shell's environment has settings systemd's daemon wouldn't
|
|
2452
|
+
// (engram#689); never beside a running one.
|
|
2453
|
+
if (start && !reportStart(await startInBackground())) {
|
|
2454
|
+
process.exitCode = 1;
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
/**
|
|
2458
|
+
* Start at login when auto-capture turns capture on, as on macOS and
|
|
2459
|
+
* Windows: add the unit when there is none, and repair one of ours that is
|
|
2460
|
+
* broken or outdated. One the user disabled with systemctl stays disabled,
|
|
2461
|
+
* and one Engram didn't write is never touched. Never fails the command it
|
|
2462
|
+
* runs after.
|
|
2463
|
+
*
|
|
2464
|
+
* "changed": it added or repaired the unit, and said so. "failed": it
|
|
2465
|
+
* couldn't add one. "unavailable": there is no systemd user session to add
|
|
2466
|
+
* one to. "runner": there is none that works, and this CLI runs from a
|
|
2467
|
+
* package runner's cache, which nothing is pointed at (engram#665).
|
|
2468
|
+
* autoEnableCapture says any of them along with the rest.
|
|
2469
|
+
*/
|
|
2470
|
+
function autoEnableSystemdStartAtLogin() {
|
|
2471
|
+
const unit = readUnit();
|
|
2472
|
+
if (unit.kind === "foreign")
|
|
2473
|
+
return "unchanged";
|
|
2474
|
+
if (unit.kind === "ours") {
|
|
2475
|
+
const repair = repairSystemdUnitIfStale(unit);
|
|
2476
|
+
return repair === "repaired" ? "changed" : repair;
|
|
2477
|
+
}
|
|
2478
|
+
if (!existsSync(workerPath()))
|
|
2479
|
+
return "unchanged";
|
|
2480
|
+
const systemctl = systemctlPath();
|
|
2481
|
+
if (systemctl === null || !systemdReachable(systemctl))
|
|
2482
|
+
return "unavailable";
|
|
2483
|
+
if (runnerCacheOfThisCli() !== null)
|
|
2484
|
+
return "runner";
|
|
2485
|
+
const made = unitForThisCli();
|
|
2486
|
+
if ("error" in made || installUnit(systemctl, made.text) !== null)
|
|
2487
|
+
return "failed";
|
|
2488
|
+
console.log(`${bold("Auto-start enabled")} — daemon will start when you log in (systemd)`);
|
|
2489
|
+
return "changed";
|
|
2490
|
+
}
|
|
2491
|
+
// ── Start at login, per platform ──
|
|
2492
|
+
/** "Windows", "Linux", … for the messages below. */
|
|
2493
|
+
function platformLabel(platform = process.platform) {
|
|
2494
|
+
switch (platform) {
|
|
2495
|
+
case "darwin":
|
|
2496
|
+
return "macOS";
|
|
2497
|
+
case "win32":
|
|
2498
|
+
return "Windows";
|
|
2499
|
+
case "linux":
|
|
2500
|
+
return "Linux";
|
|
2501
|
+
default:
|
|
2502
|
+
return platform;
|
|
2503
|
+
}
|
|
2504
|
+
}
|
|
2505
|
+
function runsUntilRestart() {
|
|
2506
|
+
return ` The daemon keeps running until you sign out or restart. Run '${engramCommand("start")}' again after that.`;
|
|
2507
|
+
}
|
|
2508
|
+
function startAfterRestart() {
|
|
2509
|
+
return ` Run '${engramCommand("start")}' to capture now, and again after you sign out or restart.`;
|
|
2510
|
+
}
|
|
2511
|
+
/**
|
|
2512
|
+
* Start at login: a launchd agent on macOS, a Run entry on Windows
|
|
2513
|
+
* (engram#602), a systemd user unit on Linux (engram#615). Elsewhere, this
|
|
2514
|
+
* used to write a macOS plist into ~/Library/LaunchAgents and run a
|
|
2515
|
+
* launchctl that isn't there; now it says what actually happens. `running`:
|
|
2516
|
+
* whether a daemon is up right now. `again`: the command that asked, to
|
|
2517
|
+
* run again where something stops it.
|
|
2518
|
+
*/
|
|
2519
|
+
async function enableStartAtLogin(running, again = engramCommand("install")) {
|
|
2520
|
+
if (process.platform === "darwin") {
|
|
2521
|
+
await enableLaunchdStartAtLogin(!running, again);
|
|
2522
|
+
return;
|
|
2523
|
+
}
|
|
2524
|
+
if (process.platform === "win32") {
|
|
2525
|
+
await enableWindowsStartAtLogin(running);
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
if (process.platform === "linux") {
|
|
2529
|
+
await enableSystemdStartAtLogin(running);
|
|
2530
|
+
return;
|
|
2531
|
+
}
|
|
2532
|
+
console.log(bold(`Start at login isn't available on ${platformLabel()} yet.`));
|
|
2533
|
+
console.log(dim(running ? runsUntilRestart() : startAfterRestart()));
|
|
2534
|
+
}
|
|
2535
|
+
async function enableWindowsStartAtLogin(running) {
|
|
2536
|
+
removeStrayPlist();
|
|
2537
|
+
const entryPath = loginStartPath();
|
|
2538
|
+
if (!existsSync(entryPath)) {
|
|
2539
|
+
// Only a source checkout run through tsx gets here: the build ships it.
|
|
2540
|
+
console.error(red(`Can't turn on start at login: ${entryPath} is missing.`));
|
|
2541
|
+
process.exitCode = 1;
|
|
2542
|
+
return;
|
|
2543
|
+
}
|
|
2544
|
+
// Said here, as on macOS and Linux: status sends people to 'engram install'
|
|
2545
|
+
// to repair start at login, so this is where they learn why it can't be
|
|
2546
|
+
// (engram#651).
|
|
2547
|
+
const failed = writeRunEntry();
|
|
2548
|
+
if (failed !== null) {
|
|
2549
|
+
console.error(red("Couldn't add the Windows startup entry."));
|
|
2550
|
+
console.error(dim(` reg: ${failed}`));
|
|
2551
|
+
console.error(dim(` It goes in ${RUN_KEY} as "${RUN_VALUE}". Run '${engramCommand("install")}' to try again.`));
|
|
2552
|
+
process.exitCode = 1;
|
|
2553
|
+
return;
|
|
2554
|
+
}
|
|
2555
|
+
clearStartupSwitch();
|
|
2556
|
+
console.log(`${bold("Auto-start enabled")} — daemon will start when you sign in to Windows`);
|
|
2557
|
+
console.log(dim(" A console window flashes briefly at sign-in while it starts."));
|
|
2558
|
+
console.log(`${dim("Startup entry:")} ${RUN_KEY}\\${RUN_VALUE}`);
|
|
2559
|
+
await printLoginVaultKeyWarning();
|
|
2560
|
+
// launchctl load starts the agent right away on macOS; match that, but
|
|
2561
|
+
// never start a second worker beside a running one. Through the
|
|
2562
|
+
// supervisor, as at sign-in, so it is started again after an error too.
|
|
2563
|
+
if (!running && !reportStart(await startInBackground())) {
|
|
2564
|
+
process.exitCode = 1;
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
/**
|
|
2568
|
+
* Start at login when auto-capture turns capture on (engram#614), the
|
|
2569
|
+
* Windows counterpart of the launchd agent it installs on macOS: add the
|
|
2570
|
+
* entry when there is none, and point a broken one at this CLI. Unlike
|
|
2571
|
+
* `engram install`, it leaves the Startup apps switch where the user put it,
|
|
2572
|
+
* as macOS leaves a login item switched off under Login Items, and it never
|
|
2573
|
+
* fails the command it runs after.
|
|
2574
|
+
*
|
|
2575
|
+
* "changed": it added or repaired the entry, and said so. "failed": it
|
|
2576
|
+
* couldn't add one, which autoEnableCapture says along with the rest.
|
|
2577
|
+
* "runner": there is none that works, and this CLI runs from a package
|
|
2578
|
+
* runner's cache, which nothing is pointed at (engram#665).
|
|
2579
|
+
*/
|
|
2580
|
+
function autoEnableWindowsStartAtLogin() {
|
|
2581
|
+
const entry = readRunEntry();
|
|
2582
|
+
if (entry !== null) {
|
|
2583
|
+
const repair = repairRunEntryIfStale(entry);
|
|
2584
|
+
return repair === "repaired" ? "changed" : repair;
|
|
2585
|
+
}
|
|
2586
|
+
// Only a source checkout run through tsx has no login-start.js: the build ships it.
|
|
2587
|
+
if (!existsSync(loginStartPath()))
|
|
2588
|
+
return "unchanged";
|
|
2589
|
+
if (runnerCacheOfThisCli() !== null)
|
|
2590
|
+
return "runner";
|
|
2591
|
+
if (writeRunEntry() !== null)
|
|
2592
|
+
return "failed";
|
|
2593
|
+
if (switchedOffInStartupApps()) {
|
|
2594
|
+
console.log(`${bold("Start at login is switched off")} in Windows Startup apps`);
|
|
2595
|
+
console.log(dim(` Switch Engram on there, or run '${engramCommand("install")}', to start the daemon when you sign in.`));
|
|
2596
|
+
return "changed";
|
|
2597
|
+
}
|
|
2598
|
+
console.log(`${bold("Auto-start enabled")} — daemon will start when you sign in to Windows`);
|
|
2599
|
+
console.log(dim(" A console window flashes briefly at sign-in while it starts."));
|
|
2600
|
+
return "changed";
|
|
2601
|
+
}
|
|
2602
|
+
function keepsRunning() {
|
|
2603
|
+
return ` The daemon keeps running until '${engramCommand("stop")}' or sign-out.`;
|
|
2604
|
+
}
|
|
2605
|
+
/**
|
|
2606
|
+
* Say that the daemon keeps running, after start at login is turned off,
|
|
2607
|
+
* when one of the user's runs: `found`, or the one found now. Not one
|
|
2608
|
+
* running as root, which `engram stop` can't stop (engram#680), nor one
|
|
2609
|
+
* that is stopping.
|
|
2610
|
+
*/
|
|
2611
|
+
async function printKeepsRunning(found) {
|
|
2612
|
+
const { state } = found ?? (await findDaemon());
|
|
2613
|
+
if (state === "running" || state === "unresponsive")
|
|
2614
|
+
console.log(dim(keepsRunning()));
|
|
2615
|
+
}
|
|
2616
|
+
async function disableStartAtLogin() {
|
|
2617
|
+
if (process.platform === "darwin") {
|
|
2618
|
+
await uninstallLaunchd();
|
|
2619
|
+
return;
|
|
2620
|
+
}
|
|
2621
|
+
removeStrayPlist();
|
|
2622
|
+
if (process.platform === "win32") {
|
|
2623
|
+
if (readRunEntry() === null) {
|
|
2624
|
+
console.log("Auto-start isn't on.");
|
|
2625
|
+
}
|
|
2626
|
+
else {
|
|
2627
|
+
const failed = deleteRunEntry();
|
|
2628
|
+
if (failed !== null) {
|
|
2629
|
+
console.error(red("Couldn't remove the Windows startup entry."));
|
|
2630
|
+
console.error(dim(` reg: ${failed}`));
|
|
2631
|
+
console.error(dim(` Remove "${RUN_VALUE}" from ${RUN_KEY}, or switch it off under Startup apps.`));
|
|
2632
|
+
process.exitCode = 1;
|
|
2633
|
+
return;
|
|
2634
|
+
}
|
|
2635
|
+
clearStartupSwitch();
|
|
2636
|
+
console.log(`${bold("Auto-start disabled")} — the Windows startup entry is removed`);
|
|
2637
|
+
}
|
|
2638
|
+
await printKeepsRunning();
|
|
2639
|
+
return;
|
|
2640
|
+
}
|
|
2641
|
+
if (process.platform === "linux") {
|
|
2642
|
+
const unit = readUnit();
|
|
2643
|
+
if (unit.kind === "none") {
|
|
2644
|
+
console.log("Auto-start isn't on.");
|
|
2645
|
+
}
|
|
2646
|
+
else if (unit.kind === "foreign") {
|
|
2647
|
+
console.log("Auto-start isn't on.");
|
|
2648
|
+
console.log(dim(` ${unitPath()} isn't one Engram wrote, so it was left as it is.`));
|
|
2649
|
+
}
|
|
2650
|
+
else {
|
|
2651
|
+
try {
|
|
2652
|
+
removeUnit();
|
|
2653
|
+
}
|
|
2654
|
+
catch {
|
|
2655
|
+
console.error(red("Couldn't remove the systemd unit."));
|
|
2656
|
+
console.error(dim(` Remove ${unitPath()} to turn start at login off.`));
|
|
2657
|
+
process.exitCode = 1;
|
|
2658
|
+
return;
|
|
2659
|
+
}
|
|
2660
|
+
console.log(`${bold("Auto-start disabled")} — the systemd unit is removed`);
|
|
2661
|
+
}
|
|
2662
|
+
await printKeepsRunning();
|
|
2663
|
+
return;
|
|
283
2664
|
}
|
|
284
|
-
console.log(
|
|
2665
|
+
console.log(`Start at login isn't set up on ${platformLabel()}, so there is nothing to remove.`);
|
|
285
2666
|
}
|
|
286
2667
|
export async function daemonInstall() {
|
|
287
|
-
|
|
288
|
-
|
|
2668
|
+
if (refusedAsRoot("install"))
|
|
2669
|
+
return;
|
|
2670
|
+
if (refusedFromRunnerCache("engram install"))
|
|
2671
|
+
return;
|
|
2672
|
+
await recordCaptureIntent("on", "install");
|
|
2673
|
+
// A daemon that is stopping isn't counted: on Windows a new worker is
|
|
2674
|
+
// started, which takes over once that one has gone. On macOS and Linux
|
|
2675
|
+
// install waits for it to exit first, as `engram start` does: launchd or
|
|
2676
|
+
// systemd takes one it runs for its daemon, still running, and would start
|
|
2677
|
+
// none in its place (engram#691, engram#689).
|
|
2678
|
+
const platform = process.platform;
|
|
2679
|
+
const managed = platform === "darwin" || platform === "linux";
|
|
2680
|
+
let found = await findDaemon();
|
|
2681
|
+
if (managed)
|
|
2682
|
+
found = await whileStopping(found);
|
|
2683
|
+
const running = found.state === "running" || found.state === "unresponsive";
|
|
2684
|
+
// Files in ~/.engram that are another user's (engram#659). Unless one
|
|
2685
|
+
// runs already, start at login would start a daemon that stops at once:
|
|
2686
|
+
// it isn't turned on. Nor, whether one runs or not, in a ~/.engram whose
|
|
2687
|
+
// own permissions keep the user out of it (engram#723): the daemon
|
|
2688
|
+
// launchd or systemd would start, now and at each login, would stop at
|
|
2689
|
+
// once.
|
|
2690
|
+
const foreign = foreignFiles();
|
|
2691
|
+
const locked = lockedDir();
|
|
2692
|
+
if (found.state === "root") {
|
|
2693
|
+
// The daemon start at login started would exit at once (engram#680).
|
|
2694
|
+
printRootDaemon(found, "Start at login wasn't turned on: no daemon of yours starts while it runs.", {
|
|
2695
|
+
foreign,
|
|
2696
|
+
again: engramCommand("install"),
|
|
2697
|
+
});
|
|
2698
|
+
process.exitCode = 1;
|
|
2699
|
+
return;
|
|
2700
|
+
}
|
|
2701
|
+
if (foreign || locked) {
|
|
2702
|
+
const stops = (!running && stopsCapture(foreign)) || locked !== null;
|
|
2703
|
+
if (foreign)
|
|
2704
|
+
printForeignFiles(foreign, running ? "running" : "stopped", stops && !locked ? "install" : undefined);
|
|
2705
|
+
if (locked)
|
|
2706
|
+
printLockedDir(locked, running ? "running" : "stopped", engramCommand("install"));
|
|
2707
|
+
if (stops) {
|
|
2708
|
+
process.exitCode = 1;
|
|
2709
|
+
return;
|
|
2710
|
+
}
|
|
2711
|
+
}
|
|
2712
|
+
if (found.state === "stopping" && managed) {
|
|
2713
|
+
// Start at login all the same, but no start now: launchd or systemd
|
|
2714
|
+
// would take the one stopping for theirs if they run it. (A job loaded
|
|
2715
|
+
// now starts one, which waits for that one to go, engram#612.)
|
|
2716
|
+
if (platform === "darwin")
|
|
2717
|
+
await enableLaunchdStartAtLogin();
|
|
2718
|
+
else
|
|
2719
|
+
await enableSystemdStartAtLogin(false, false);
|
|
2720
|
+
console.error(red(`The daemon is still stopping (pid ${found.pid}). Run '${engramCommand("start")}' in a moment.`));
|
|
2721
|
+
process.exitCode = 1;
|
|
2722
|
+
return;
|
|
2723
|
+
}
|
|
2724
|
+
await enableStartAtLogin(running);
|
|
2725
|
+
// A daemon that runs stays the one that runs: one launchd starts as the
|
|
2726
|
+
// agent loads finds it and exits (engram#612). Said when launchd or
|
|
2727
|
+
// systemd doesn't run it, as `engram start --install` says it (engram#692).
|
|
2728
|
+
printOutsideManager(found);
|
|
289
2729
|
}
|
|
290
2730
|
/**
|
|
291
2731
|
* Auto-capture is the product default: a successful interactive login
|
|
292
2732
|
* turns the capture daemon on and enables start-at-login, loudly, with a
|
|
293
2733
|
* one-line off switch. Never fatal — login must succeed even if the
|
|
294
|
-
* daemon can't start. Skipped for scripted logins (no TTY)
|
|
295
|
-
* ENGRAM_NO_AUTOCAPTURE is set
|
|
2734
|
+
* daemon can't start. Skipped for scripted logins (no TTY), when
|
|
2735
|
+
* ENGRAM_NO_AUTOCAPTURE is set, and for root run for someone else, which
|
|
2736
|
+
* would set capture up for root (engram#653).
|
|
2737
|
+
*
|
|
2738
|
+
* After any other command it makes sure capture is still on, and says so
|
|
2739
|
+
* only when it had to do something: start the daemon, or turn on or repair
|
|
2740
|
+
* start at login (engram#644). A reminder after every search pushes the
|
|
2741
|
+
* command's own output up, and teaches people to skip what follows a
|
|
2742
|
+
* command, which is where a real warning would be.
|
|
296
2743
|
*/
|
|
297
|
-
export async function autoEnableCapture() {
|
|
2744
|
+
export async function autoEnableCapture({ after }) {
|
|
298
2745
|
if (process.env.ENGRAM_NO_AUTOCAPTURE)
|
|
299
2746
|
return;
|
|
300
2747
|
if (!process.stdin.isTTY)
|
|
301
2748
|
return;
|
|
302
|
-
|
|
2749
|
+
const platform = process.platform;
|
|
2750
|
+
if (platform !== "darwin" && platform !== "linux" && platform !== "win32")
|
|
2751
|
+
return;
|
|
2752
|
+
// It would start the daemon and start at login for root (engram#653).
|
|
2753
|
+
if (rootForAnotherUser()) {
|
|
2754
|
+
if (after === "login") {
|
|
2755
|
+
console.log(dim(" Auto-capture runs as you, not as root, so it wasn't turned on: sign in again without sudo."));
|
|
2756
|
+
}
|
|
303
2757
|
return;
|
|
2758
|
+
}
|
|
304
2759
|
try {
|
|
305
|
-
|
|
2760
|
+
// Files in ~/.engram that are another user's (engram#659): a daemon
|
|
2761
|
+
// started now would stop at once, after every command. The banner
|
|
2762
|
+
// before the command said why.
|
|
2763
|
+
if (stopsCapture(foreignFiles())) {
|
|
2764
|
+
if (after === "login") {
|
|
2765
|
+
console.log(dim(` Auto-capture wasn't turned on: files in ~/.engram aren't yours. Make them yours with: ${OWNERSHIP_FIX}`));
|
|
2766
|
+
}
|
|
2767
|
+
return;
|
|
2768
|
+
}
|
|
2769
|
+
// A ~/.engram whose own permissions keep the user out of it
|
|
2770
|
+
// (engram#723): likewise, and the daemon would say so in a desktop
|
|
2771
|
+
// notification as it stops, after every command.
|
|
2772
|
+
const locked = lockedDir();
|
|
2773
|
+
if (locked) {
|
|
2774
|
+
if (after === "login") {
|
|
2775
|
+
console.log(dim(` Auto-capture wasn't turned on: ${lockedDirProblem(locked)} ${lockedDirFix(locked)}`));
|
|
2776
|
+
}
|
|
2777
|
+
return;
|
|
2778
|
+
}
|
|
2779
|
+
// Strict (engram#673): one that can't be read may say capture is off.
|
|
2780
|
+
// A daemon started now would only wait on it; the banner said why.
|
|
2781
|
+
const config = await loadConfigStrict();
|
|
306
2782
|
if (config.autocapture === "off")
|
|
307
2783
|
return; // user said stop; respect it
|
|
308
2784
|
if (!(process.env.ENGRAM_API_KEY ?? config.apiKey))
|
|
309
2785
|
return; // nothing to capture into
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
2786
|
+
let changed = false;
|
|
2787
|
+
const found = await findDaemon(500);
|
|
2788
|
+
// One runs as root for them (engram#680): none of theirs would start
|
|
2789
|
+
// beside it, and start at login is left as it is. After other commands,
|
|
2790
|
+
// `engram status` says so.
|
|
2791
|
+
if (found.state === "root") {
|
|
2792
|
+
if (after === "login") {
|
|
2793
|
+
const { problem, fixes } = rootDaemonLines(found);
|
|
2794
|
+
console.log(dim(` Auto-capture wasn't turned on. ${problem}`));
|
|
2795
|
+
for (const fix of fixes)
|
|
2796
|
+
console.log(dim(` ${fix}`));
|
|
2797
|
+
console.log(dim(` Then run: ${engramCommand("start")}`));
|
|
2798
|
+
}
|
|
2799
|
+
return;
|
|
2800
|
+
}
|
|
2801
|
+
// When launchd's start at login couldn't be set up because
|
|
2802
|
+
// ~/Library/LaunchAgents isn't the user's (engram#678): whose it is.
|
|
2803
|
+
let launchAgents = null;
|
|
2804
|
+
const autoEnableStartAtLogin = () => {
|
|
2805
|
+
if (platform === "win32")
|
|
2806
|
+
return autoEnableWindowsStartAtLogin();
|
|
2807
|
+
if (platform !== "darwin")
|
|
2808
|
+
return autoEnableSystemdStartAtLogin();
|
|
2809
|
+
const result = autoEnableLaunchdStartAtLogin();
|
|
2810
|
+
if (result === "failed")
|
|
2811
|
+
launchAgents = launchAgentsNotYours();
|
|
2812
|
+
return result;
|
|
2813
|
+
};
|
|
2814
|
+
// On macOS and Linux, with no daemon at all, start at login first: then
|
|
2815
|
+
// launchd or systemd starts the daemon, and starts it again after a crash
|
|
2816
|
+
// (engram#641, engram#689). Not with settings in this environment that
|
|
2817
|
+
// their daemon wouldn't have: the daemon is spawned then, as before.
|
|
2818
|
+
const managerFirst = platform !== "win32" && found.state === "stopped" && !daemonEnvOverrides();
|
|
2819
|
+
let startAtLogin = managerFirst ? autoEnableStartAtLogin() : undefined;
|
|
2820
|
+
if (found.state === "stopped" || found.state === "stopping") {
|
|
2821
|
+
// On Windows through the supervisor, as at sign-in, so a worker that
|
|
2822
|
+
// exits with an error is started again (engram#613). Nothing waits on
|
|
2823
|
+
// it here, so it is never asked to report a failed start.
|
|
2824
|
+
if (platform === "win32")
|
|
2825
|
+
spawnSupervisor();
|
|
2826
|
+
else if (!(managerFirst && serviceManager()?.start() === null))
|
|
2827
|
+
spawnWorker();
|
|
2828
|
+
changed = true;
|
|
2829
|
+
await sleep(500);
|
|
2830
|
+
}
|
|
2831
|
+
startAtLogin ??= autoEnableStartAtLogin();
|
|
2832
|
+
if (startAtLogin === "changed")
|
|
2833
|
+
changed = true;
|
|
2834
|
+
const startAtLoginFailed = startAtLogin === "failed";
|
|
2835
|
+
const startAtLoginUnavailable = startAtLogin === "unavailable";
|
|
2836
|
+
// A CLI a package runner runs from its cache sets none up (engram#665).
|
|
2837
|
+
const runner = startAtLogin === "runner" ? runnerCacheOfThisCli() : null;
|
|
2838
|
+
if (after === "command" && !changed)
|
|
2839
|
+
return;
|
|
2840
|
+
// Said with the rest, not after every command while it keeps failing:
|
|
2841
|
+
// after a command, that is when the daemon had to be started, which is
|
|
2842
|
+
// what start at login would have done.
|
|
2843
|
+
if (startAtLoginFailed) {
|
|
2844
|
+
// A ~/Library/LaunchAgents that isn't the user's (engram#678): what
|
|
2845
|
+
// makes it theirs. Start at login is set up once it is, after the
|
|
2846
|
+
// next command.
|
|
2847
|
+
console.log(dim(launchAgents
|
|
2848
|
+
? ` Couldn't set up start at login: ${launchAgentsWhose(launchAgents)}. Make it yours with: ${LAUNCH_AGENTS_FIX}`
|
|
2849
|
+
: ` Couldn't turn on start at login. Run '${engramCommand("install")}' to try again.`));
|
|
323
2850
|
}
|
|
324
2851
|
console.log(`${bold("Auto-capture is on")} — conversations from supported agents on this machine save to your Engram.`);
|
|
325
|
-
|
|
2852
|
+
if (startAtLoginUnavailable) {
|
|
2853
|
+
console.log(dim(` Start at login isn't available here (no systemd user session): run '${engramCommand("start")}' after a restart.`));
|
|
2854
|
+
}
|
|
2855
|
+
if (runner !== null) {
|
|
2856
|
+
console.log(dim(` The daemon won't start at login: this Engram runs from ${runner}, which can be cleared at any time.`));
|
|
2857
|
+
console.log(dim(` To start it at login, install the CLI: ${INSTALL_CLI} && engram install`));
|
|
2858
|
+
}
|
|
2859
|
+
console.log(dim(` Turn off anytime: ${engramCommand("stop")} && ${engramCommand("uninstall")}`));
|
|
2860
|
+
// When start at login is on: the daemon it starts reads the file
|
|
2861
|
+
// (engram#690). Not one the user switched off, or never there.
|
|
2862
|
+
await printLoginVaultKeyWarning(() => autoStart().on);
|
|
326
2863
|
}
|
|
327
2864
|
catch {
|
|
328
2865
|
// Non-fatal by design: capture is a convenience, login is the job.
|
|
329
2866
|
}
|
|
330
2867
|
}
|
|
331
2868
|
export async function daemonUninstall() {
|
|
332
|
-
|
|
333
|
-
|
|
2869
|
+
// Run as root, it would save the setting as root's (engram#682).
|
|
2870
|
+
if (refusedAsRoot("uninstall"))
|
|
2871
|
+
return;
|
|
2872
|
+
await recordCaptureIntent("off", "uninstall");
|
|
2873
|
+
await disableStartAtLogin();
|
|
334
2874
|
}
|
|
335
2875
|
//# sourceMappingURL=commands.js.map
|