@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.
Files changed (208) hide show
  1. package/LICENSE +112 -0
  2. package/README.md +1 -1
  3. package/dist/commands/auth.d.ts.map +1 -1
  4. package/dist/commands/auth.js +38 -11
  5. package/dist/commands/auth.js.map +1 -1
  6. package/dist/commands/conversations.d.ts.map +1 -1
  7. package/dist/commands/conversations.js +8 -2
  8. package/dist/commands/conversations.js.map +1 -1
  9. package/dist/commands/exclude.d.ts.map +1 -1
  10. package/dist/commands/exclude.js +73 -21
  11. package/dist/commands/exclude.js.map +1 -1
  12. package/dist/commands/import.d.ts +30 -3
  13. package/dist/commands/import.d.ts.map +1 -1
  14. package/dist/commands/import.js +374 -45
  15. package/dist/commands/import.js.map +1 -1
  16. package/dist/commands/login.d.ts.map +1 -1
  17. package/dist/commands/login.js +144 -29
  18. package/dist/commands/login.js.map +1 -1
  19. package/dist/commands/search.js +2 -2
  20. package/dist/commands/search.js.map +1 -1
  21. package/dist/commands/status.d.ts +16 -0
  22. package/dist/commands/status.d.ts.map +1 -0
  23. package/dist/commands/status.js +51 -0
  24. package/dist/commands/status.js.map +1 -0
  25. package/dist/commands/store.d.ts.map +1 -1
  26. package/dist/commands/store.js +19 -3
  27. package/dist/commands/store.js.map +1 -1
  28. package/dist/commands/upgrade.d.ts +24 -0
  29. package/dist/commands/upgrade.d.ts.map +1 -1
  30. package/dist/commands/upgrade.js +64 -15
  31. package/dist/commands/upgrade.js.map +1 -1
  32. package/dist/commands/usage.d.ts +44 -0
  33. package/dist/commands/usage.d.ts.map +1 -1
  34. package/dist/commands/usage.js +79 -19
  35. package/dist/commands/usage.js.map +1 -1
  36. package/dist/commands/vault.d.ts +11 -2
  37. package/dist/commands/vault.d.ts.map +1 -1
  38. package/dist/commands/vault.js +372 -53
  39. package/dist/commands/vault.js.map +1 -1
  40. package/dist/config-file.d.ts +74 -0
  41. package/dist/config-file.d.ts.map +1 -0
  42. package/dist/config-file.js +152 -0
  43. package/dist/config-file.js.map +1 -0
  44. package/dist/config-guard.d.ts +96 -0
  45. package/dist/config-guard.d.ts.map +1 -0
  46. package/dist/config-guard.js +184 -0
  47. package/dist/config-guard.js.map +1 -0
  48. package/dist/config.d.ts +48 -4
  49. package/dist/config.d.ts.map +1 -1
  50. package/dist/config.js +101 -12
  51. package/dist/config.js.map +1 -1
  52. package/dist/daemon/as-root.d.ts +46 -0
  53. package/dist/daemon/as-root.d.ts.map +1 -0
  54. package/dist/daemon/as-root.js +64 -0
  55. package/dist/daemon/as-root.js.map +1 -0
  56. package/dist/daemon/backoff.d.ts +26 -0
  57. package/dist/daemon/backoff.d.ts.map +1 -0
  58. package/dist/daemon/backoff.js +37 -0
  59. package/dist/daemon/backoff.js.map +1 -0
  60. package/dist/daemon/codex-parser.d.ts +38 -4
  61. package/dist/daemon/codex-parser.d.ts.map +1 -1
  62. package/dist/daemon/codex-parser.js +111 -23
  63. package/dist/daemon/codex-parser.js.map +1 -1
  64. package/dist/daemon/command-path.d.ts +13 -0
  65. package/dist/daemon/command-path.d.ts.map +1 -0
  66. package/dist/daemon/command-path.js +35 -0
  67. package/dist/daemon/command-path.js.map +1 -0
  68. package/dist/daemon/commands.d.ts +153 -3
  69. package/dist/daemon/commands.d.ts.map +1 -1
  70. package/dist/daemon/commands.js +2775 -235
  71. package/dist/daemon/commands.js.map +1 -1
  72. package/dist/daemon/db.d.ts +255 -27
  73. package/dist/daemon/db.d.ts.map +1 -1
  74. package/dist/daemon/db.js +749 -53
  75. package/dist/daemon/db.js.map +1 -1
  76. package/dist/daemon/exclusions.d.ts +23 -3
  77. package/dist/daemon/exclusions.d.ts.map +1 -1
  78. package/dist/daemon/exclusions.js +91 -21
  79. package/dist/daemon/exclusions.js.map +1 -1
  80. package/dist/daemon/homebrew.d.ts +26 -0
  81. package/dist/daemon/homebrew.d.ts.map +1 -0
  82. package/dist/daemon/homebrew.js +43 -0
  83. package/dist/daemon/homebrew.js.map +1 -0
  84. package/dist/daemon/instance.d.ts +427 -0
  85. package/dist/daemon/instance.d.ts.map +1 -0
  86. package/dist/daemon/instance.js +1201 -0
  87. package/dist/daemon/instance.js.map +1 -0
  88. package/dist/daemon/key-source.d.ts +41 -0
  89. package/dist/daemon/key-source.d.ts.map +1 -0
  90. package/dist/daemon/key-source.js +89 -0
  91. package/dist/daemon/key-source.js.map +1 -0
  92. package/dist/daemon/launch.d.ts +56 -0
  93. package/dist/daemon/launch.d.ts.map +1 -0
  94. package/dist/daemon/launch.js +153 -0
  95. package/dist/daemon/launch.js.map +1 -0
  96. package/dist/daemon/launchd.d.ts +215 -0
  97. package/dist/daemon/launchd.d.ts.map +1 -0
  98. package/dist/daemon/launchd.js +527 -0
  99. package/dist/daemon/launchd.js.map +1 -0
  100. package/dist/daemon/login-start.d.ts +2 -0
  101. package/dist/daemon/login-start.d.ts.map +1 -0
  102. package/dist/daemon/login-start.js +25 -0
  103. package/dist/daemon/login-start.js.map +1 -0
  104. package/dist/daemon/ownership.d.ts +123 -0
  105. package/dist/daemon/ownership.d.ts.map +1 -0
  106. package/dist/daemon/ownership.js +245 -0
  107. package/dist/daemon/ownership.js.map +1 -0
  108. package/dist/daemon/package-runner.d.ts +28 -0
  109. package/dist/daemon/package-runner.d.ts.map +1 -0
  110. package/dist/daemon/package-runner.js +113 -0
  111. package/dist/daemon/package-runner.js.map +1 -0
  112. package/dist/daemon/parser.d.ts +50 -5
  113. package/dist/daemon/parser.d.ts.map +1 -1
  114. package/dist/daemon/parser.js +224 -47
  115. package/dist/daemon/parser.js.map +1 -1
  116. package/dist/daemon/powershell.d.ts +25 -0
  117. package/dist/daemon/powershell.d.ts.map +1 -0
  118. package/dist/daemon/powershell.js +30 -0
  119. package/dist/daemon/powershell.js.map +1 -0
  120. package/dist/daemon/preflight.d.ts +0 -17
  121. package/dist/daemon/preflight.d.ts.map +1 -1
  122. package/dist/daemon/preflight.js +32 -6
  123. package/dist/daemon/preflight.js.map +1 -1
  124. package/dist/daemon/prune.d.ts +101 -0
  125. package/dist/daemon/prune.d.ts.map +1 -0
  126. package/dist/daemon/prune.js +287 -0
  127. package/dist/daemon/prune.js.map +1 -0
  128. package/dist/daemon/queue-error.d.ts +47 -0
  129. package/dist/daemon/queue-error.d.ts.map +1 -0
  130. package/dist/daemon/queue-error.js +59 -0
  131. package/dist/daemon/queue-error.js.map +1 -0
  132. package/dist/daemon/root-daemon.d.ts +60 -0
  133. package/dist/daemon/root-daemon.d.ts.map +1 -0
  134. package/dist/daemon/root-daemon.js +86 -0
  135. package/dist/daemon/root-daemon.js.map +1 -0
  136. package/dist/daemon/scoop.d.ts +52 -0
  137. package/dist/daemon/scoop.d.ts.map +1 -0
  138. package/dist/daemon/scoop.js +84 -0
  139. package/dist/daemon/scoop.js.map +1 -0
  140. package/dist/daemon/scrubber.d.ts +456 -0
  141. package/dist/daemon/scrubber.d.ts.map +1 -0
  142. package/dist/daemon/scrubber.js +994 -0
  143. package/dist/daemon/scrubber.js.map +1 -0
  144. package/dist/daemon/status.d.ts +306 -11
  145. package/dist/daemon/status.d.ts.map +1 -1
  146. package/dist/daemon/status.js +568 -43
  147. package/dist/daemon/status.js.map +1 -1
  148. package/dist/daemon/supervise.d.ts +78 -0
  149. package/dist/daemon/supervise.d.ts.map +1 -0
  150. package/dist/daemon/supervise.js +121 -0
  151. package/dist/daemon/supervise.js.map +1 -0
  152. package/dist/daemon/supervisor.d.ts +18 -0
  153. package/dist/daemon/supervisor.d.ts.map +1 -0
  154. package/dist/daemon/supervisor.js +56 -0
  155. package/dist/daemon/supervisor.js.map +1 -0
  156. package/dist/daemon/syncer.d.ts +382 -21
  157. package/dist/daemon/syncer.d.ts.map +1 -1
  158. package/dist/daemon/syncer.js +1448 -178
  159. package/dist/daemon/syncer.js.map +1 -1
  160. package/dist/daemon/systemd.d.ts +109 -0
  161. package/dist/daemon/systemd.d.ts.map +1 -0
  162. package/dist/daemon/systemd.js +363 -0
  163. package/dist/daemon/systemd.js.map +1 -0
  164. package/dist/daemon/types.d.ts +58 -6
  165. package/dist/daemon/types.d.ts.map +1 -1
  166. package/dist/daemon/vault-changed.d.ts +29 -0
  167. package/dist/daemon/vault-changed.d.ts.map +1 -0
  168. package/dist/daemon/vault-changed.js +47 -0
  169. package/dist/daemon/vault-changed.js.map +1 -0
  170. package/dist/daemon/vault-key-missing.d.ts +70 -0
  171. package/dist/daemon/vault-key-missing.d.ts.map +1 -0
  172. package/dist/daemon/vault-key-missing.js +125 -0
  173. package/dist/daemon/vault-key-missing.js.map +1 -0
  174. package/dist/daemon/watcher.d.ts +87 -4
  175. package/dist/daemon/watcher.d.ts.map +1 -1
  176. package/dist/daemon/watcher.js +286 -36
  177. package/dist/daemon/watcher.js.map +1 -1
  178. package/dist/daemon/worker-main.js +363 -51
  179. package/dist/daemon/worker-main.js.map +1 -1
  180. package/dist/daemon/worker.js +19 -1
  181. package/dist/daemon/worker.js.map +1 -1
  182. package/dist/import-resume.d.ts +163 -0
  183. package/dist/import-resume.d.ts.map +1 -0
  184. package/dist/import-resume.js +267 -0
  185. package/dist/import-resume.js.map +1 -0
  186. package/dist/index.js +242 -33
  187. package/dist/index.js.map +1 -1
  188. package/dist/message-bounds.d.ts +52 -0
  189. package/dist/message-bounds.d.ts.map +1 -0
  190. package/dist/message-bounds.js +157 -0
  191. package/dist/message-bounds.js.map +1 -0
  192. package/dist/output.d.ts +14 -0
  193. package/dist/output.d.ts.map +1 -1
  194. package/dist/output.js +33 -5
  195. package/dist/output.js.map +1 -1
  196. package/dist/private-files.d.ts +126 -0
  197. package/dist/private-files.d.ts.map +1 -0
  198. package/dist/private-files.js +372 -0
  199. package/dist/private-files.js.map +1 -0
  200. package/dist/server-url.d.ts +31 -0
  201. package/dist/server-url.d.ts.map +1 -0
  202. package/dist/server-url.js +47 -0
  203. package/dist/server-url.js.map +1 -0
  204. package/dist/vault-key.d.ts +122 -0
  205. package/dist/vault-key.d.ts.map +1 -0
  206. package/dist/vault-key.js +273 -0
  207. package/dist/vault-key.js.map +1 -0
  208. package/package.json +11 -12
@@ -0,0 +1,1201 @@
1
+ /**
2
+ * One capture daemon per user (engram#612).
3
+ *
4
+ * The worker listens on a local socket that only its user can reach:
5
+ * ~/.engram/daemon.sock on macOS and Linux, a named pipe on Windows. A
6
+ * worker that finds it answered exits at once, so a second start (launchd at
7
+ * login beside `engram start`, or two starts at the same moment) can't put
8
+ * two daemons on the same transcripts, each capturing and sending them.
9
+ * "Running" means it answers, and the answer gives the worker's PID and
10
+ * version.
11
+ *
12
+ * The PID file used to be the only record, and only a liveness test checked
13
+ * it: a file left by a daemon that didn't exit cleanly could name a PID that
14
+ * had since gone to another program, which `engram status` then reported as
15
+ * the daemon and `engram stop` signalled.
16
+ *
17
+ * The socket is one-way. A client gets one line of JSON and the connection
18
+ * ends; nothing a client sends is read, so nothing that reaches the socket
19
+ * can make the daemon do anything. On Windows `engram stop` asks the daemon
20
+ * to stop through a file in ~/.engram instead (STOP_FILE, engram#613),
21
+ * which only the user can write.
22
+ *
23
+ * daemon.pid is still written, for CLIs from before this change, and is
24
+ * trusted only for a process confirmed to be the daemon (identifyProcess).
25
+ *
26
+ * A daemon running as root in the user's ~/.engram is never the daemon
27
+ * (engram#680): a worker started as root exits at once, and one already
28
+ * running as root, which `sudo engram start` or `sudo engram install` left
29
+ * before engram#653, keeps any other from starting while it runs.
30
+ *
31
+ * IMPORTANT: Node built-ins only. worker.ts claims the lock before the
32
+ * native-module preflight, so nothing here may load better-sqlite3, directly
33
+ * or through another module (see launch.ts).
34
+ */
35
+ import { execFileSync } from "node:child_process";
36
+ import { createHash, randomBytes } from "node:crypto";
37
+ import { fstatSync, lstatSync, readdirSync, readFileSync, statSync, unlinkSync } from "node:fs";
38
+ import { createRequire } from "node:module";
39
+ import { connect, createServer } from "node:net";
40
+ import { dirname, join } from "node:path";
41
+ import { isatty } from "node:tty";
42
+ import { rootForAnotherUser } from "./as-root.js";
43
+ import { ENGRAM_DIR, LOG_FILE, PID_FILE } from "./launch.js";
44
+ import { systemJob } from "./launchd.js";
45
+ import { lockedDir, lockedDirFix, lockedDirProblem } from "./ownership.js";
46
+ import { engramCommand } from "./package-runner.js";
47
+ import { powerShellArgs, windowsPowerShellPath } from "./powershell.js";
48
+ import { notifyDesktopBeforeExit } from "./status.js";
49
+ import { ensurePrivateDirSync, readSmallFileSync, writePrivateFileSync } from "../private-files.js";
50
+ /** This package's version, which the daemon gives when it answers. */
51
+ export const VERSION = (() => {
52
+ try {
53
+ const pkg = createRequire(import.meta.url)("../../package.json");
54
+ return typeof pkg.version === "string" ? pkg.version : "unknown";
55
+ }
56
+ catch {
57
+ return "unknown";
58
+ }
59
+ })();
60
+ /** How long a probe waits for the daemon's answer. */
61
+ const PROBE_TIMEOUT_MS = 1_500;
62
+ /** An answer is one short line; a longer one isn't the daemon's. */
63
+ const MAX_ANSWER_BYTES = 1_024;
64
+ /** At most this many clients at once. Each is answered and let go at once. */
65
+ const MAX_CLIENTS = 16;
66
+ /** A client that doesn't take its answer is dropped after this long. */
67
+ const CLIENT_TIMEOUT_MS = 5_000;
68
+ /** Binding again after another start got in the way, at most this often. */
69
+ const LOCK_TRIES = 5;
70
+ /**
71
+ * How long a start waits for a daemon that is stopping: its shutdown waits
72
+ * up to 7 s for a send in progress and 7 s for the last one.
73
+ */
74
+ export const STOPPING_WAIT_MS = 20_000;
75
+ const POLL_MS = 250;
76
+ /** How long a socket just bound is left before checking it is still this daemon's. */
77
+ const SETTLE_MS = 250;
78
+ /** How often the daemon checks that its socket and PID file are still there. */
79
+ const SELF_CHECK_MS = 30_000;
80
+ /** How often the daemon looks for a stop request (STOP_FILE). */
81
+ const STOP_POLL_MS = 1_000;
82
+ /** A stop request is a few dozen bytes: anything longer isn't one. */
83
+ const MAX_STOP_BYTES = 1_024;
84
+ function errCode(err) {
85
+ return err?.code;
86
+ }
87
+ function errorText(err) {
88
+ return err instanceof Error ? err.message : String(err);
89
+ }
90
+ function sleep(ms) {
91
+ return new Promise((resolve) => setTimeout(resolve, ms));
92
+ }
93
+ /**
94
+ * lstat of the socket's path, with BigInt fields. Every plain stat in the
95
+ * process leaves the type of what it found in one buffer Node keeps, and
96
+ * fs.realpathSync, which loads modules, reads that buffer back: when it
97
+ * says socket, a path being resolved stops at the first part already known
98
+ * not to be a link, and that unresolved path is cached. The next package
99
+ * loaded through a symlinked node_modules (as pnpm installs) can then not
100
+ * find what it requires, and `engram status` couldn't open the local queue
101
+ * while a daemon was running (engram#612). A BigInt stat leaves that buffer
102
+ * as it was.
103
+ */
104
+ function lstatSocketPath(path) {
105
+ return lstatSync(path, { bigint: true });
106
+ }
107
+ function lstatOrNull(path) {
108
+ try {
109
+ return lstatSocketPath(path);
110
+ }
111
+ catch {
112
+ return null;
113
+ }
114
+ }
115
+ /** The longest socket path each platform takes, in bytes: sun_path less its NUL. */
116
+ function maxSocketPath(platform) {
117
+ return platform === "linux" ? 107 : 103;
118
+ }
119
+ /**
120
+ * ~/.engram/daemon.sock, or on Windows a named pipe. Pipe names are one
121
+ * namespace for the whole machine, so the name carries a hash of this
122
+ * user's ~/.engram.
123
+ *
124
+ * A socket path longer than the platform takes is cut short by Node 20 and
125
+ * refused by later versions. A home folder that long gets no lock: the
126
+ * daemon still runs, with the PID file as its only record (see
127
+ * claimDaemonLock).
128
+ */
129
+ export function daemonEndpoint(dir = ENGRAM_DIR, platform = process.platform) {
130
+ if (platform === "win32") {
131
+ const id = createHash("sha256").update(dir.toLowerCase()).digest("hex").slice(0, 32);
132
+ return { path: `\\\\.\\pipe\\engram-daemon-${id}`, pipe: true };
133
+ }
134
+ const path = join(dir, "daemon.sock");
135
+ const bytes = Buffer.byteLength(path);
136
+ const max = maxSocketPath(platform);
137
+ if (bytes > max) {
138
+ return { unavailable: `the socket path would be ${bytes} bytes, and the most this system takes is ${max}` };
139
+ }
140
+ return { path, pipe: false };
141
+ }
142
+ function where(endpoint) {
143
+ return endpoint.pipe ? "the daemon's named pipe" : "~/.engram/daemon.sock";
144
+ }
145
+ const OUTPUTS = ["log", "terminal", "deleted", "file", "none"];
146
+ /**
147
+ * Where this process's output goes: `fd`, stderr, which the daemon writes
148
+ * its log lines to, and which every start points at the same place as
149
+ * stdout. Undefined on Windows, which isn't asked, and when it can't be
150
+ * told. Read again each time the daemon answers, so a log deleted or
151
+ * replaced while it runs is seen without a timer. BigInt stats, as for the
152
+ * socket (see lstatSocketPath). Exported for tests.
153
+ */
154
+ export function daemonOutput(fd = 2, log = LOG_FILE, platform = process.platform) {
155
+ if (platform === "win32")
156
+ return undefined;
157
+ let out;
158
+ try {
159
+ out = fstatSync(fd, { bigint: true });
160
+ }
161
+ catch {
162
+ return undefined;
163
+ }
164
+ try {
165
+ const at = statSync(log, { bigint: true });
166
+ if (at.dev === out.dev && at.ino === out.ino)
167
+ return "log";
168
+ }
169
+ catch (err) {
170
+ // None there is an answer: it was deleted, or was never made. Anything
171
+ // else, such as a ~/.engram that can't be searched, isn't.
172
+ const code = errCode(err);
173
+ if (code !== "ENOENT" && code !== "ENOTDIR")
174
+ return undefined;
175
+ }
176
+ if (isatty(fd))
177
+ return "terminal";
178
+ if (out.isFile())
179
+ return out.nlink === 0n ? "deleted" : "file";
180
+ return "none";
181
+ }
182
+ const self = {
183
+ ready: false,
184
+ stopping: false,
185
+ startedAt: new Date().toISOString(),
186
+ vaultKey: undefined,
187
+ };
188
+ function answer(id) {
189
+ const output = daemonOutput();
190
+ return `${JSON.stringify({
191
+ engram: "daemon",
192
+ protocol: 1,
193
+ pid: process.pid,
194
+ version: VERSION,
195
+ started_at: self.startedAt,
196
+ id,
197
+ ready: self.ready,
198
+ stopping: self.stopping,
199
+ stop_file: watchStopFile,
200
+ vault_key_reread: true,
201
+ vault_change_notice: true,
202
+ ...(self.vaultKey === undefined ? {} : { vault_key: self.vaultKey }),
203
+ ...(output === undefined ? {} : { output }),
204
+ })}\n`;
205
+ }
206
+ /**
207
+ * The daemon's answer, or null for anything else. What is printed from it
208
+ * (the version) is checked character by character: whatever holds the
209
+ * socket, a terminal never gets control characters from it.
210
+ */
211
+ export function parseAnswer(line) {
212
+ let value;
213
+ try {
214
+ value = JSON.parse(line);
215
+ }
216
+ catch {
217
+ return null;
218
+ }
219
+ if (typeof value !== "object" || value === null)
220
+ return null;
221
+ const a = value;
222
+ if (a.engram !== "daemon")
223
+ return null;
224
+ if (typeof a.pid !== "number" || !Number.isSafeInteger(a.pid) || a.pid <= 0)
225
+ return null;
226
+ const text = (v, pattern) => typeof v === "string" && pattern.test(v) ? v : undefined;
227
+ return {
228
+ pid: a.pid,
229
+ version: text(a.version, /^[0-9A-Za-z.+-]{1,50}$/),
230
+ startedAt: text(a.started_at, /^[0-9T:.Z-]{1,40}$/),
231
+ id: text(a.id, /^[0-9a-f]{32}$/),
232
+ ready: a.ready === true,
233
+ stopping: a.stopping === true,
234
+ stopFile: a.stop_file === true,
235
+ vaultKeyReread: a.vault_key_reread === true,
236
+ vaultChangeNotice: a.vault_change_notice === true,
237
+ vaultKey: typeof a.vault_key === "boolean" ? a.vault_key : undefined,
238
+ output: OUTPUTS.find((o) => o === a.output),
239
+ };
240
+ }
241
+ /** A server that answers each client with one line and lets it go. */
242
+ function answeringServer(id) {
243
+ const server = createServer((socket) => {
244
+ socket.on("error", () => {
245
+ // the client went away; nothing to do
246
+ });
247
+ socket.setTimeout(CLIENT_TIMEOUT_MS, () => socket.destroy());
248
+ socket.end(answer(id));
249
+ // Whatever the client sends is drained and dropped, never parsed.
250
+ socket.resume();
251
+ });
252
+ server.maxConnections = MAX_CLIENTS;
253
+ return server;
254
+ }
255
+ /**
256
+ * Listen on `endpoint`: null once listening, else the error. The socket
257
+ * file takes its mode from the umask, so the umask is 077 for the bind,
258
+ * which happens inside listen(), and put back right after.
259
+ */
260
+ function listenOn(server, endpoint, log) {
261
+ return new Promise((resolve) => {
262
+ const onError = (err) => {
263
+ server.off("listening", onListening);
264
+ resolve(err);
265
+ };
266
+ const onListening = () => {
267
+ server.off("error", onError);
268
+ // From here on an error (accept failing for lack of file
269
+ // descriptors) is logged: unhandled, it would end the daemon.
270
+ server.on("error", (err) => log(`daemon socket: ${errorText(err)}`));
271
+ resolve(null);
272
+ };
273
+ server.once("error", onError);
274
+ server.once("listening", onListening);
275
+ let umask = null;
276
+ if (!endpoint.pipe) {
277
+ try {
278
+ umask = process.umask(0o077);
279
+ }
280
+ catch {
281
+ // not allowed in a worker thread; ~/.engram is 0700 regardless
282
+ }
283
+ }
284
+ try {
285
+ server.listen(endpoint.path);
286
+ }
287
+ catch (err) {
288
+ onError(err);
289
+ }
290
+ finally {
291
+ if (umask !== null)
292
+ process.umask(umask);
293
+ }
294
+ });
295
+ }
296
+ /** Before connecting: only a socket of the user's own is asked. */
297
+ function checkSocketFile(path) {
298
+ let st;
299
+ try {
300
+ st = lstatSocketPath(path);
301
+ }
302
+ catch (err) {
303
+ if (errCode(err) === "ENOENT")
304
+ return { state: "none", stale: false };
305
+ return { state: "unavailable", reason: `couldn't check ~/.engram/daemon.sock (${errCode(err) ?? errorText(err)})` };
306
+ }
307
+ if (!st.isSocket())
308
+ return { state: "unavailable", reason: "~/.engram/daemon.sock is there but isn't a socket" };
309
+ const uid = process.geteuid?.();
310
+ if (uid !== undefined && st.uid !== BigInt(uid)) {
311
+ return { state: "unavailable", reason: "~/.engram/daemon.sock belongs to another user" };
312
+ }
313
+ return null;
314
+ }
315
+ /** Ask whatever listens on the daemon's endpoint who it is. Never throws. */
316
+ export function probeDaemon(options = {}) {
317
+ const endpoint = options.endpoint ?? daemonEndpoint();
318
+ if ("unavailable" in endpoint)
319
+ return Promise.resolve({ state: "unavailable", reason: endpoint.unavailable });
320
+ if (!endpoint.pipe) {
321
+ const checked = checkSocketFile(endpoint.path);
322
+ if (checked)
323
+ return Promise.resolve(checked);
324
+ }
325
+ const timeoutMs = options.timeoutMs ?? PROBE_TIMEOUT_MS;
326
+ return new Promise((resolve) => {
327
+ let settled = false;
328
+ let received = Buffer.alloc(0);
329
+ const socket = connect(endpoint.path);
330
+ const finish = (probe) => {
331
+ if (settled)
332
+ return;
333
+ settled = true;
334
+ clearTimeout(timer);
335
+ socket.destroy();
336
+ resolve(probe);
337
+ };
338
+ const timer = setTimeout(() => finish({ state: "silent" }), timeoutMs);
339
+ socket.on("data", (chunk) => {
340
+ received = Buffer.concat([received, chunk]);
341
+ const end = received.indexOf(0x0a);
342
+ if (end >= 0) {
343
+ const info = parseAnswer(received.subarray(0, end).toString("utf-8"));
344
+ finish(info ? { state: "answered", info } : { state: "silent" });
345
+ }
346
+ else if (received.length > MAX_ANSWER_BYTES) {
347
+ finish({ state: "silent" });
348
+ }
349
+ });
350
+ socket.on("close", () => finish({ state: "silent" }));
351
+ socket.on("error", (err) => {
352
+ if (err.code === "ECONNREFUSED")
353
+ finish({ state: "none", stale: !endpoint.pipe });
354
+ else if (err.code === "ENOENT")
355
+ finish({ state: "none", stale: false });
356
+ else
357
+ finish({ state: "unavailable", reason: `couldn't reach ${where(endpoint)} (${err.code ?? err.message})` });
358
+ });
359
+ });
360
+ }
361
+ /**
362
+ * Whether the socket file at the endpoint is the one `id`'s server is bound
363
+ * to: it answers with that id, and the file is the same before and after
364
+ * asking. Returns its dev and ino when it is.
365
+ */
366
+ async function boundTo(endpoint, id) {
367
+ const before = lstatOrNull(endpoint.path);
368
+ if (!before)
369
+ return null;
370
+ const probe = await probeDaemon({ endpoint });
371
+ if (probe.state !== "answered" || probe.info.id !== id)
372
+ return null;
373
+ const after = lstatOrNull(endpoint.path);
374
+ if (!after || after.dev !== before.dev || after.ino !== before.ino)
375
+ return null;
376
+ return { dev: before.dev, ino: before.ino };
377
+ }
378
+ /**
379
+ * The daemon named in the PID file, when it is alive and confirmed to be
380
+ * one (and isn't this process): the user's own, or, `root`, one running as
381
+ * root (engram#680).
382
+ */
383
+ export function daemonInPidFile() {
384
+ const pid = pidInFile();
385
+ if (pid === null || pid === process.pid || !alive(pid))
386
+ return null;
387
+ const what = identifyProcess(pid);
388
+ return what === "daemon" || what === "root" ? { pid, root: what === "root" } : null;
389
+ }
390
+ /** The user's own daemon, named in the PID file and confirmed (see daemonInPidFile). */
391
+ export function confirmedDaemonInPidFile() {
392
+ const found = daemonInPidFile();
393
+ return found !== null && !found.root ? found.pid : null;
394
+ }
395
+ /**
396
+ * A daemon running as root for this user (engram#680), which `sudo engram
397
+ * start` or `sudo engram install` started before engram#653: `inFile`, the
398
+ * one the PID file names, or, on macOS, the one `job` runs, the job such an
399
+ * install loaded into launchd's system domain from the user's own plist. A
400
+ * CLI from before this change removed the PID file of a daemon it couldn't
401
+ * signal. Each is looked up unless the caller has, the job only when the
402
+ * PID file names none. Null when none runs.
403
+ */
404
+ export function rootDaemonPid(inFile = daemonInPidFile(), job) {
405
+ if (inFile?.root)
406
+ return inFile.pid;
407
+ const loaded = job === undefined ? systemJob() : job;
408
+ if (loaded?.pid == null || loaded.pid === process.pid)
409
+ return null;
410
+ return identifyProcess(loaded.pid) === "root" ? loaded.pid : null;
411
+ }
412
+ /**
413
+ * Remove a socket file nothing listens on, left by a daemon that didn't exit
414
+ * cleanly (killed, or the machine lost power). It is checked again a moment
415
+ * later, at a random delay, and removed only if it is still the same file
416
+ * and still refuses connections: when two starts find the same stale file,
417
+ * the slower must not remove the socket the faster has bound since. If it
418
+ * does anyway, the faster finds out before it settles (see lockEndpoint).
419
+ */
420
+ async function removeStaleSocket(endpoint, log) {
421
+ const before = lstatOrNull(endpoint.path);
422
+ if (!before)
423
+ return;
424
+ await sleep(100 + Math.floor(Math.random() * 150));
425
+ const again = await probeDaemon({ endpoint });
426
+ if (again.state !== "none" || !again.stale)
427
+ return;
428
+ const after = lstatOrNull(endpoint.path);
429
+ if (!after || after.dev !== before.dev || after.ino !== before.ino)
430
+ return;
431
+ try {
432
+ unlinkSync(endpoint.path);
433
+ log("removed a daemon.sock left by a daemon that didn't exit cleanly");
434
+ }
435
+ catch (err) {
436
+ if (errCode(err) !== "ENOENT")
437
+ log(`couldn't remove a daemon.sock left by an earlier daemon (${errCode(err) ?? errorText(err)})`);
438
+ }
439
+ }
440
+ /** Wait while a daemon that is stopping still holds the endpoint, up to STOPPING_WAIT_MS. */
441
+ async function waitWhileStopping(endpoint) {
442
+ const deadline = Date.now() + STOPPING_WAIT_MS;
443
+ while (Date.now() < deadline) {
444
+ await sleep(POLL_MS);
445
+ const probe = await probeDaemon({ endpoint });
446
+ if (probe.state !== "answered" || !probe.info.stopping)
447
+ return;
448
+ }
449
+ }
450
+ /**
451
+ * Take the endpoint for this process, or find out who has it.
452
+ *
453
+ * Binding is the lock: two binds to one path can't both succeed, and a
454
+ * second named pipe of the same name can't be made. A socket file left by a
455
+ * daemon that died (it refuses connections) is removed and the bind tried
456
+ * again. After binding, the socket must still answer as this server once a
457
+ * stale-socket removal racing this one has had time to land.
458
+ */
459
+ export async function lockEndpoint(endpoint, options = {}) {
460
+ const log = options.log ?? (() => { });
461
+ const settleMs = options.settleMs ?? SETTLE_MS;
462
+ if (!endpoint.pipe) {
463
+ try {
464
+ ensurePrivateDirSync(dirname(endpoint.path));
465
+ }
466
+ catch (err) {
467
+ return { state: "unavailable", reason: `couldn't create ~/.engram (${errCode(err) ?? errorText(err)})` };
468
+ }
469
+ }
470
+ let waitedForStop = false;
471
+ for (let tries = 0; tries < LOCK_TRIES; tries++) {
472
+ const id = randomBytes(16).toString("hex");
473
+ const server = answeringServer(id);
474
+ const err = await listenOn(server, endpoint, log);
475
+ if (err === null) {
476
+ if (endpoint.pipe)
477
+ return { state: "held", held: { server, endpoint, id, dev: 0n, ino: 0n } };
478
+ await sleep(settleMs);
479
+ const bound = await boundTo(endpoint, id);
480
+ if (bound)
481
+ return { state: "held", held: { server, endpoint, id, ...bound } };
482
+ // Another start removed this socket and bound its own. Never close
483
+ // this server: on macOS and Linux that removes the file at the path,
484
+ // by name, and the file there now is the other's.
485
+ server.unref();
486
+ continue;
487
+ }
488
+ // The path is taken. macOS says EEXIST, not EADDRINUSE, when another
489
+ // start binds it at the same moment: bind looks the name up, then makes
490
+ // it, and the other made it in between. Taken for a socket that can't be
491
+ // used here, it left a daemon running without the lock (engram#708).
492
+ if (err.code !== "EADDRINUSE" && err.code !== "EEXIST") {
493
+ return { state: "unavailable", reason: `couldn't listen on ${where(endpoint)} (${err.code ?? err.message})` };
494
+ }
495
+ const probe = await probeDaemon({ endpoint });
496
+ if (probe.state === "answered") {
497
+ if (!probe.info.stopping)
498
+ return { state: "taken", taken: { why: "socket", info: probe.info } };
499
+ if (waitedForStop)
500
+ return { state: "taken", taken: { why: "stopping", pid: probe.info.pid } };
501
+ // `engram stop` and then `engram start`, or launchd starting one
502
+ // while the last finishes: once it has gone, this one takes over.
503
+ waitedForStop = true;
504
+ await waitWhileStopping(endpoint);
505
+ tries--;
506
+ continue;
507
+ }
508
+ if (probe.state === "silent")
509
+ return { state: "taken", taken: { why: "silent" } };
510
+ if (probe.state === "unavailable")
511
+ return { state: "unavailable", reason: probe.reason };
512
+ if (probe.stale) {
513
+ // A socket that refuses connections is normally a dead daemon's. But
514
+ // macOS refuses them too while a live daemon's backlog is full, and a
515
+ // daemon from before engram#612 has no socket at all: a confirmed
516
+ // daemon in the PID file keeps the socket where it is.
517
+ const pid = confirmedDaemonInPidFile();
518
+ if (pid !== null)
519
+ return { state: "taken", taken: { why: "pidfile", pid } };
520
+ await removeStaleSocket(endpoint, log);
521
+ }
522
+ else if (endpoint.pipe) {
523
+ // The pipe's name is taken, and nothing accepts on it: a daemon
524
+ // letting it go. The name is free once its last connection closes.
525
+ await sleep(POLL_MS);
526
+ }
527
+ // Gone since, or removed just now: bind again.
528
+ }
529
+ return { state: "taken", taken: { why: "unknown", tries: LOCK_TRIES } };
530
+ }
531
+ /**
532
+ * Let the endpoint go. On macOS and Linux the socket file is removed only
533
+ * while it is still this server's, and the server is never closed: closing
534
+ * removes whatever file is at the path by then, by name. The process exits
535
+ * right after, which ends the server without touching the path.
536
+ */
537
+ export function unlockEndpoint(held) {
538
+ if (held.endpoint.pipe) {
539
+ held.server.close();
540
+ return;
541
+ }
542
+ const st = lstatOrNull(held.endpoint.path);
543
+ if (st && st.dev === held.dev && st.ino === held.ino) {
544
+ try {
545
+ unlinkSync(held.endpoint.path);
546
+ }
547
+ catch {
548
+ // gone already
549
+ }
550
+ }
551
+ held.server.unref();
552
+ }
553
+ // ── The PID file and processes ──
554
+ /**
555
+ * The PID in daemon.pid: digits only, so "-1" or "0", which would signal
556
+ * every process the user has or the whole process group, never come back.
557
+ */
558
+ export function pidInFile(file = PID_FILE) {
559
+ let text;
560
+ try {
561
+ text = readFileSync(file, "utf-8").trim();
562
+ }
563
+ catch {
564
+ return null;
565
+ }
566
+ if (!/^\d{1,10}$/.test(text))
567
+ return null;
568
+ const pid = Number(text);
569
+ return pid > 0 && pid <= 0x7fffffff ? pid : null;
570
+ }
571
+ /** Remove daemon.pid when it names `pid`, and only then. */
572
+ export function removePidFileIf(pid, file = PID_FILE) {
573
+ if (pidInFile(file) !== pid)
574
+ return;
575
+ try {
576
+ unlinkSync(file);
577
+ }
578
+ catch {
579
+ // gone already
580
+ }
581
+ }
582
+ export function alive(pid) {
583
+ try {
584
+ process.kill(pid, 0);
585
+ return true;
586
+ }
587
+ catch (err) {
588
+ return errCode(err) === "EPERM";
589
+ }
590
+ }
591
+ /**
592
+ * The worker's script, as an install runs it: dist/daemon/worker.js, or
593
+ * worker-main.js from a plist before 0.4.2. A quote may end it: Windows
594
+ * puts a path with a space in it in quotes on the command line.
595
+ */
596
+ const WORKER_SCRIPT = /(?:^|[\s/\\])dist[\\/]daemon[\\/]worker(?:-main)?\.js(?:["\s]|$)/;
597
+ /**
598
+ * What a process that runs `args` as the user `owner` is to the user `me`:
599
+ * their daemon, a daemon running as root (engram#680), or something else.
600
+ * Root's only for a user who isn't root. Pure: the tests pass made-up
601
+ * processes.
602
+ */
603
+ export function processKind(owner, args, me) {
604
+ if (!WORKER_SCRIPT.test(args.trim()))
605
+ return "other";
606
+ if (owner === me)
607
+ return "daemon";
608
+ return owner === 0 && me !== undefined && me !== 0 ? "root" : "other";
609
+ }
610
+ /**
611
+ * Whether `pid` is this user's daemon: a process of the user's running the
612
+ * worker's script. "root": the worker's script running as root, for a user
613
+ * who isn't (engram#680), which the user can't signal. "unknown" when that
614
+ * can't be found out (`ps` or PowerShell failed, or Windows won't say, as
615
+ * for a process run as administrator), which is never taken for the
616
+ * daemon. A daemon started with `engram start --foreground` runs the CLI's
617
+ * script, and is found through its socket only.
618
+ */
619
+ export function identifyProcess(pid) {
620
+ if (process.platform === "win32")
621
+ return identifyOnWindows(pid);
622
+ const uid = process.geteuid?.();
623
+ if (process.platform === "linux") {
624
+ try {
625
+ const owner = statSync(`/proc/${pid}`).uid;
626
+ const args = readFileSync(`/proc/${pid}/cmdline`, "utf-8").split("\0").join(" ");
627
+ return processKind(owner, args, uid);
628
+ }
629
+ catch (err) {
630
+ return errCode(err) === "ENOENT" ? "other" : "unknown";
631
+ }
632
+ }
633
+ let out;
634
+ try {
635
+ out = execFileSync("/bin/ps", ["-ww", "-o", "uid=,args=", "-p", String(pid)], {
636
+ encoding: "utf-8",
637
+ timeout: 2_000,
638
+ stdio: ["ignore", "pipe", "ignore"],
639
+ });
640
+ }
641
+ catch (err) {
642
+ // ps exits 1 when there is no such process.
643
+ return err.status === 1 ? "other" : "unknown";
644
+ }
645
+ const match = /^\s*(\d+)\s+(.*)$/.exec(out.split("\n")[0] ?? "");
646
+ if (!match)
647
+ return "other";
648
+ return processKind(Number(match[1]), match[2], uid);
649
+ }
650
+ /**
651
+ * Every process that runs the worker's script as root, when this user
652
+ * isn't root (engram#680), whatever started it: on macOS, `ps`; on Linux,
653
+ * /proc. None on Windows, or when they can't be listed. Only ever said, in
654
+ * `engram status` and `engram start`: nothing ties one of these to this
655
+ * user, as the PID file or launchd's system domain does.
656
+ */
657
+ export function rootWorkerPids() {
658
+ const me = process.geteuid?.();
659
+ if (me === undefined || me === 0)
660
+ return [];
661
+ const found = [];
662
+ const take = (pid, owner, args) => {
663
+ if (pid !== process.pid && processKind(owner, args, me) === "root")
664
+ found.push(pid);
665
+ };
666
+ if (process.platform === "linux") {
667
+ let entries;
668
+ try {
669
+ entries = readdirSync("/proc");
670
+ }
671
+ catch {
672
+ return [];
673
+ }
674
+ for (const entry of entries) {
675
+ if (!/^\d+$/.test(entry))
676
+ continue;
677
+ try {
678
+ const owner = statSync(`/proc/${entry}`).uid;
679
+ if (owner !== 0)
680
+ continue;
681
+ take(Number(entry), owner, readFileSync(`/proc/${entry}/cmdline`, "utf-8").split("\0").join(" "));
682
+ }
683
+ catch {
684
+ // gone since, or hidden
685
+ }
686
+ }
687
+ return found;
688
+ }
689
+ if (process.platform !== "darwin")
690
+ return [];
691
+ let out;
692
+ try {
693
+ out = execFileSync("/bin/ps", ["-A", "-ww", "-o", "pid=,uid=,args="], {
694
+ encoding: "utf-8",
695
+ timeout: 5_000,
696
+ maxBuffer: 16 * 1024 * 1024,
697
+ stdio: ["ignore", "pipe", "ignore"],
698
+ });
699
+ }
700
+ catch {
701
+ return [];
702
+ }
703
+ if (typeof out !== "string")
704
+ return [];
705
+ for (const line of out.split("\n")) {
706
+ const match = /^\s*(\d+)\s+(\d+)\s+(.*)$/.exec(line);
707
+ if (match)
708
+ take(Number(match[1]), Number(match[2]), match[3]);
709
+ }
710
+ return found;
711
+ }
712
+ // ── Identifying a process on Windows (engram#640) ──
713
+ /**
714
+ * PowerShell's start and its two process queries take a second or two; this
715
+ * leaves room for a busy machine. Past it, "unknown".
716
+ */
717
+ const IDENTIFY_TIMEOUT_MS = 10_000;
718
+ /**
719
+ * What identifies a process on Windows, one PowerShell statement each: its
720
+ * owner, the owner of this PowerShell, which runs as the user, and its
721
+ * command line, as one line of JSON; or "none" when there is no such
722
+ * process. The PID comes in ENGRAM_IDENTIFY_PID, never in the script.
723
+ *
724
+ * The command line comes as its character codes, joined by commas.
725
+ * PowerShell writes to a pipe in the console's code page, which turns what
726
+ * it can't show into something else: on a Japanese system, the second byte
727
+ * of a character can be a backslash, and Windows' "best fit" turns a
728
+ * full-width quote into a plain one. Either would break the JSON, or change
729
+ * what it says. Character codes are plain ASCII, whatever the code page.
730
+ *
731
+ * Cmdlets, operators and casts to plain types only, no .NET calls, so it
732
+ * runs the same where PowerShell is locked down to Constrained Language
733
+ * (AppLocker, WDAC).
734
+ */
735
+ export const IDENTIFY_STATEMENTS = [
736
+ "$ErrorActionPreference = 'Stop'",
737
+ "$ProgressPreference = 'SilentlyContinue'",
738
+ "$target = Get-CimInstance -ClassName Win32_Process -Filter ('ProcessId = ' + [int]$env:ENGRAM_IDENTIFY_PID)",
739
+ "if ($null -eq $target) { 'none'; exit 0 }",
740
+ "$self = Get-CimInstance -ClassName Win32_Process -Filter ('ProcessId = ' + $PID)",
741
+ "$owner = Invoke-CimMethod -InputObject $target -MethodName GetOwnerSid",
742
+ "$me = Invoke-CimMethod -InputObject $self -MethodName GetOwnerSid",
743
+ "$command = $target.CommandLine",
744
+ "if ($null -ne $command) { $command = [int[]][char[]]$command -join ',' }",
745
+ "ConvertTo-Json -Compress -InputObject @{ owner = $owner.Sid; me = $me.Sid; command = $command }",
746
+ ];
747
+ /** How to run IDENTIFY_STATEMENTS for `pid`. */
748
+ export function windowsIdentifyCommand(pid, systemRoot) {
749
+ return {
750
+ file: windowsPowerShellPath(systemRoot),
751
+ args: powerShellArgs(IDENTIFY_STATEMENTS),
752
+ env: { ENGRAM_IDENTIFY_PID: String(pid) },
753
+ };
754
+ }
755
+ function identifyOnWindows(pid) {
756
+ const { file, args, env } = windowsIdentifyCommand(pid);
757
+ let out;
758
+ try {
759
+ out = execFileSync(file, args, {
760
+ encoding: "utf-8",
761
+ env: { ...process.env, ...env },
762
+ stdio: ["ignore", "pipe", "ignore"],
763
+ timeout: IDENTIFY_TIMEOUT_MS,
764
+ windowsHide: true,
765
+ });
766
+ }
767
+ catch {
768
+ // No PowerShell, an error in it, or too slow.
769
+ return "unknown";
770
+ }
771
+ return windowsIdentity(out);
772
+ }
773
+ const SID = /^S-1(?:-\d+)+$/i;
774
+ /** A command line as IDENTIFY_STATEMENTS gives it, or null for anything else. */
775
+ function fromCharCodes(codes) {
776
+ if (!/^(?:\d{1,5}(?:,\d{1,5})*)?$/.test(codes))
777
+ return null;
778
+ let text = "";
779
+ for (const code of codes.match(/\d+/g) ?? []) {
780
+ const unit = Number(code);
781
+ if (unit > 0xffff)
782
+ return null;
783
+ text += String.fromCharCode(unit);
784
+ }
785
+ return text;
786
+ }
787
+ /**
788
+ * What IDENTIFY_STATEMENTS printed, read: "other" for no such process, or
789
+ * another user's; "daemon" for one of the user's running the worker's
790
+ * script; "unknown" when it says too little, as for a process run as
791
+ * administrator, whose owner or command line Windows doesn't give a process
792
+ * that isn't.
793
+ */
794
+ export function windowsIdentity(out) {
795
+ // The last line: anything PowerShell warns of comes before it. Trimming
796
+ // drops a byte-order mark as well.
797
+ const lines = out
798
+ .split(/\r?\n/)
799
+ .map((line) => line.trim())
800
+ .filter(Boolean);
801
+ const last = lines[lines.length - 1];
802
+ if (last === undefined)
803
+ return "unknown";
804
+ if (last === "none")
805
+ return "other";
806
+ let found;
807
+ try {
808
+ found = JSON.parse(last);
809
+ }
810
+ catch {
811
+ return "unknown";
812
+ }
813
+ if (typeof found !== "object" || found === null)
814
+ return "unknown";
815
+ const { owner, me, command } = found;
816
+ if (typeof owner !== "string" || typeof me !== "string" || !SID.test(owner) || !SID.test(me))
817
+ return "unknown";
818
+ if (owner.toUpperCase() !== me.toUpperCase())
819
+ return "other";
820
+ // No command line: Windows didn't give it, as for a process run as administrator.
821
+ const line = typeof command === "string" ? fromCharCodes(command) : null;
822
+ if (line === null)
823
+ return "unknown";
824
+ return WORKER_SCRIPT.test(line) ? "daemon" : "other";
825
+ }
826
+ // ── Stopping on Windows ──
827
+ /**
828
+ * Where `engram stop` asks the daemon to stop on Windows (engram#613).
829
+ * There, process.kill is TerminateProcess: the daemon used to be ended
830
+ * wherever it was, in the middle of a send or of writing its queue. The
831
+ * socket stays one-way, so the request is a file in ~/.engram, which only
832
+ * the user can write: `{"pid": …, "id": …}`, the PID and the id the
833
+ * daemon's answer gave. The daemon looks for it every STOP_POLL_MS and
834
+ * stops as it does for SIGTERM. A daemon the request doesn't name, by both,
835
+ * leaves it alone: a file left from an earlier daemon can name a PID that
836
+ * Windows has given to this one since, but never its id.
837
+ *
838
+ * The supervisor that starts the daemon again after a crash reads it too:
839
+ * a daemon that exits with an error after a request was written was
840
+ * stopped, and isn't started again (see supervise.ts).
841
+ */
842
+ export const STOP_FILE = join(ENGRAM_DIR, "daemon.stop");
843
+ /**
844
+ * The stop request in STOP_FILE, or null when there is none. It must be a
845
+ * small regular file, read without waiting (see readSmallFileSync): a FIFO
846
+ * put there would otherwise hang the daemon on the read.
847
+ */
848
+ export function readStopFile(file = STOP_FILE) {
849
+ const found = readSmallFileSync(file, MAX_STOP_BYTES);
850
+ if (found === null)
851
+ return null;
852
+ let value = null;
853
+ try {
854
+ value = JSON.parse(found.data.toString("utf-8"));
855
+ }
856
+ catch {
857
+ // not a request this version wrote: it still counts as one, for no daemon
858
+ }
859
+ const r = typeof value === "object" && value !== null ? value : {};
860
+ return {
861
+ pid: typeof r.pid === "number" && Number.isSafeInteger(r.pid) && r.pid > 0 ? r.pid : null,
862
+ id: typeof r.id === "string" && /^[0-9a-f]{32}$/.test(r.id) ? r.id : null,
863
+ stamp: found.stamp,
864
+ };
865
+ }
866
+ /** Remove STOP_FILE when the request in it is one `matches` takes. */
867
+ export function removeStopFileIf(matches, file = STOP_FILE) {
868
+ const request = readStopFile(file);
869
+ if (request === null || !matches(request))
870
+ return;
871
+ try {
872
+ unlinkSync(file);
873
+ }
874
+ catch {
875
+ // gone already
876
+ }
877
+ }
878
+ let log = () => { };
879
+ let claim = null;
880
+ let held = null;
881
+ let released = false;
882
+ let checkTimer = null;
883
+ let checking = false;
884
+ let warnedSocket = false;
885
+ /** Whether checkDaemonLock said ~/.engram can't be searched (engram#723). */
886
+ let warnedLocked = false;
887
+ /** Whether this daemon looks for stop requests: set when it claims the lock. */
888
+ let watchStopFile = false;
889
+ let stopTimer = null;
890
+ /** The stamp of the last stop request looked at, so each is read once. */
891
+ let stopSeen = null;
892
+ let stopHandler = () => {
893
+ releaseDaemonLock();
894
+ process.exit(0);
895
+ };
896
+ let displacedHandler = () => {
897
+ log("another daemon has taken over; this one is stopping");
898
+ releaseDaemonLock();
899
+ process.exit(0);
900
+ };
901
+ /**
902
+ * What SIGTERM, SIGINT and SIGHUP do (and SIGBREAK, and a stop request, on
903
+ * Windows): the worker sets its shutdown here once it has one.
904
+ */
905
+ export function setStopHandler(fn) {
906
+ stopHandler = fn;
907
+ }
908
+ /** What happens when another daemon has taken the socket over. */
909
+ export function setDisplacedHandler(fn) {
910
+ displacedHandler = fn;
911
+ }
912
+ /** Answer as ready: modules loaded, capture set up. `engram start` waits for this (waitForWorker). */
913
+ export function markReady() {
914
+ self.ready = true;
915
+ }
916
+ /** Answer as stopping, so a start waits for this one to finish. */
917
+ export function markStopping() {
918
+ self.stopping = true;
919
+ }
920
+ /**
921
+ * Answer whether it has a vault key (engram#698), once it has read it: see
922
+ * DaemonInfo.vaultKey. It never goes back to none: a key read before is
923
+ * used until a restart, and one that can't be read holds sends.
924
+ */
925
+ export function markVaultKey(has) {
926
+ self.vaultKey = has;
927
+ }
928
+ function takenMessage(taken, endpoint) {
929
+ switch (taken.why) {
930
+ case "socket": {
931
+ const version = taken.info.version ? `, version ${taken.info.version}` : "";
932
+ return `another daemon is already running (pid ${taken.info.pid}${version}); this one is exiting`;
933
+ }
934
+ case "silent":
935
+ return `another daemon holds ${where(endpoint)} but isn't answering (busy, or still starting); this one is exiting`;
936
+ case "stopping":
937
+ return `a daemon that is stopping (pid ${taken.pid}) still holds ${where(endpoint)}; this one is exiting`;
938
+ case "pidfile":
939
+ return `another daemon is already running (pid ${taken.pid}); this one is exiting`;
940
+ case "unknown":
941
+ return `couldn't take ${where(endpoint)} after ${taken.tries} tries; this one is exiting`;
942
+ }
943
+ }
944
+ function writePidFile() {
945
+ try {
946
+ ensurePrivateDirSync(ENGRAM_DIR);
947
+ writePrivateFileSync(PID_FILE, String(process.pid), { durable: false });
948
+ }
949
+ catch (err) {
950
+ log(`couldn't write ~/.engram/daemon.pid (${errCode(err) ?? errorText(err)})`);
951
+ }
952
+ }
953
+ /**
954
+ * Every SELF_CHECK_MS: the socket is still this daemon's, and the PID file
955
+ * still names it. A socket removed from under it (a cleanup of ~/.engram)
956
+ * is bound again. One another daemon has bound in its place, and that
957
+ * answers as ready, means that daemon has taken over, and this one stops.
958
+ * Exported for the tests.
959
+ */
960
+ export async function checkDaemonLock() {
961
+ if (checking || released || self.stopping)
962
+ return;
963
+ checking = true;
964
+ try {
965
+ // ~/.engram can't be searched any more (engram#723): neither the socket
966
+ // nor the PID file can be looked at, which isn't another daemon having
967
+ // them, and a PID file written every 30 seconds would only fail. Said
968
+ // once, and checked again once it can be. The daemon goes on with what
969
+ // it opened, and holds capture while config.json can't be read.
970
+ const locked = lockedDir({ dir: ENGRAM_DIR });
971
+ if (locked?.search) {
972
+ if (!warnedLocked) {
973
+ warnedLocked = true;
974
+ log(`~/.engram's permissions keep this daemon from opening the files in it, so it can't check its socket and PID file. ${lockedDirFix(locked)}`);
975
+ }
976
+ return;
977
+ }
978
+ warnedLocked = false;
979
+ const h = held;
980
+ if (h && !h.endpoint.pipe) {
981
+ const st = lstatOrNull(h.endpoint.path);
982
+ if (!st || st.dev !== h.dev || st.ino !== h.ino) {
983
+ const probe = await probeDaemon({ endpoint: h.endpoint });
984
+ if (probe.state === "answered" && probe.info.id !== h.id) {
985
+ // Only to a daemon that is ready. A worker starting while the
986
+ // socket was missing holds it for a moment, then finds this one
987
+ // in the PID file and exits: had this one stopped for it, none
988
+ // would be left. A daemon that has really taken over is ready
989
+ // within seconds, and found so at a later check.
990
+ if (probe.info.ready && !probe.info.stopping)
991
+ displacedHandler();
992
+ return;
993
+ }
994
+ if (probe.state === "none")
995
+ await bindAgain(h);
996
+ else if (!warnedSocket) {
997
+ warnedSocket = true;
998
+ log("~/.engram/daemon.sock was replaced by something that isn't this daemon");
999
+ }
1000
+ }
1001
+ }
1002
+ if (!released && !self.stopping && pidInFile() !== process.pid)
1003
+ writePidFile();
1004
+ }
1005
+ finally {
1006
+ checking = false;
1007
+ }
1008
+ }
1009
+ async function bindAgain(old) {
1010
+ if (lstatOrNull(old.endpoint.path))
1011
+ await removeStaleSocket(old.endpoint, log);
1012
+ const result = await lockEndpoint(old.endpoint, { log });
1013
+ if (result.state === "held") {
1014
+ // The old server stays open, unreachable, until exit: closing it would
1015
+ // remove the new socket file by name.
1016
+ old.server.unref();
1017
+ held = result.held;
1018
+ log("~/.engram/daemon.sock was removed; listening on it again");
1019
+ }
1020
+ else if (result.state === "taken" && result.taken.why === "socket") {
1021
+ // Bound by another daemon since: it has taken over once it is ready
1022
+ // (see checkDaemonLock), and until then this one goes on.
1023
+ if (result.taken.info.ready)
1024
+ displacedHandler();
1025
+ }
1026
+ else if (!warnedSocket) {
1027
+ warnedSocket = true;
1028
+ log(`couldn't listen on ~/.engram/daemon.sock again (${result.state === "unavailable" ? result.reason : result.taken.why})`);
1029
+ }
1030
+ }
1031
+ /**
1032
+ * Stop when STOP_FILE asks this daemon to, by its PID and its id. Every
1033
+ * STOP_POLL_MS while it holds the lock, on Windows. Exported for the tests.
1034
+ */
1035
+ export function checkStopRequest() {
1036
+ if (released || self.stopping || held === null)
1037
+ return;
1038
+ const request = readStopFile();
1039
+ if (request === null || request.stamp === stopSeen)
1040
+ return;
1041
+ stopSeen = request.stamp;
1042
+ if (request.pid !== process.pid || request.id !== held.id)
1043
+ return;
1044
+ log("stop requested ('engram stop')");
1045
+ stopHandler();
1046
+ }
1047
+ /**
1048
+ * Become the daemon, or find that one already runs: worker.ts calls this
1049
+ * before the preflight, so two starts never run `npm rebuild` at once, and
1050
+ * worker-main.ts again for a plist from before 0.4.2 that starts it
1051
+ * directly (engram#469). Only the first call does anything. Logs what it
1052
+ * found; the caller exits on "taken".
1053
+ *
1054
+ * Held, the PID file is written, SIGTERM, SIGINT and SIGHUP stop the
1055
+ * daemon through setStopHandler, and any exit releases both. On Windows a
1056
+ * stop request does too (STOP_FILE), and so does SIGBREAK. One of those
1057
+ * signals that comes before the lock is decided stops it once it is: the
1058
+ * claim is then "stopped" (engram#669).
1059
+ */
1060
+ export function claimDaemonLock(options) {
1061
+ claim ??= claimOnce(options);
1062
+ return claim;
1063
+ }
1064
+ async function claimOnce(options) {
1065
+ log = options.log;
1066
+ // Root, running the daemon for the user (engram#680): `sudo engram start`
1067
+ // with a CLI from before engram#653, or a job such a CLI loaded into
1068
+ // launchd's system domain, started again. As root it would make files in
1069
+ // the user's ~/.engram that their own daemon can't write, and the user
1070
+ // couldn't stop it. It takes nothing: no socket, no PID file.
1071
+ if (rootForAnotherUser()) {
1072
+ const message = `daemon exiting: it runs as root, and Engram's daemon runs as you. Run '${engramCommand("start")}' as yourself, without sudo`;
1073
+ log(message);
1074
+ return { state: "refused", message };
1075
+ }
1076
+ // Before the socket answers: the answer says whether it does.
1077
+ watchStopFile = options.stopFile ?? process.platform === "win32";
1078
+ // Before the socket answers, too: `engram stop` finds the daemon by it,
1079
+ // and it answers from the moment it is bound, a while before the lock is
1080
+ // decided (SETTLE_MS). A signal with no handler ends the process by that
1081
+ // signal, which launchd takes for a crash: it starts the daemon again ten
1082
+ // seconds later (engram#669). One that comes before the lock is decided
1083
+ // is acted on once it is.
1084
+ let deciding = true;
1085
+ let stopAsked = false;
1086
+ const onStop = () => {
1087
+ if (deciding)
1088
+ stopAsked = true;
1089
+ else
1090
+ stopHandler();
1091
+ };
1092
+ process.on("SIGTERM", onStop);
1093
+ process.on("SIGINT", onStop);
1094
+ // The terminal or console a daemon runs in the foreground in was closed.
1095
+ // Windows ends the process about ten seconds later.
1096
+ process.on("SIGHUP", onStop);
1097
+ // Ctrl-Break, in a console on Windows.
1098
+ if (process.platform === "win32")
1099
+ process.on("SIGBREAK", onStop);
1100
+ // A ~/.engram its own permissions keep the user out of (engram#723), as
1101
+ // `chmod -R 600 ~/.engram` leaves it. The daemon can't open, or make,
1102
+ // anything in it: not its socket, so it would run without the lock, and
1103
+ // not its database, which it then dies at. It takes nothing, and exits
1104
+ // with 0, so launchd and systemd leave it stopped. Its log is in that
1105
+ // folder too, so the desktop is told; a signal while that is shown is
1106
+ // swallowed (deciding), not taken for a crash.
1107
+ const locked = lockedDir({ dir: ENGRAM_DIR });
1108
+ if (locked) {
1109
+ const message = `daemon exiting: ${lockedDirProblem(locked, "stopped")}`;
1110
+ log(message);
1111
+ log(lockedDirFix(locked));
1112
+ log(`Then run: ${engramCommand("start")}`);
1113
+ await notifyDesktopBeforeExit("Engram capture has stopped", `${lockedDirProblem(locked)} ${lockedDirFix(locked)}`);
1114
+ return { state: "refused", message };
1115
+ }
1116
+ const endpoint = options.endpoint ?? daemonEndpoint();
1117
+ const result = "unavailable" in endpoint
1118
+ ? { state: "unavailable", reason: endpoint.unavailable }
1119
+ : await lockEndpoint(endpoint, { log, settleMs: options.settleMs });
1120
+ // Nothing from here on waits, so no signal comes in before the return.
1121
+ deciding = false;
1122
+ if (result.state === "taken") {
1123
+ const message = takenMessage(result.taken, endpoint);
1124
+ log(message);
1125
+ return { state: "taken", message, retry: result.taken.why === "unknown" };
1126
+ }
1127
+ // A daemon from before engram#612 has no socket: its PID file, confirmed,
1128
+ // is the only sign of it.
1129
+ const inFile = daemonInPidFile();
1130
+ if (inFile !== null && !inFile.root) {
1131
+ if (result.state === "held")
1132
+ unlockEndpoint(result.held);
1133
+ const message = result.state === "held"
1134
+ ? `an older daemon is already running (pid ${inFile.pid}); this one is exiting. Run '${engramCommand("stop")}' and then '${engramCommand("start")}' to update it`
1135
+ : `another daemon is already running (pid ${inFile.pid}); this one is exiting`;
1136
+ log(message);
1137
+ return { state: "taken", message, retry: false };
1138
+ }
1139
+ // Nor has one running as root (engram#680), which the user can't stop:
1140
+ // two daemons would capture the same transcripts.
1141
+ const root = rootDaemonPid(inFile);
1142
+ if (root !== null) {
1143
+ if (result.state === "held")
1144
+ unlockEndpoint(result.held);
1145
+ const message = `a daemon started with sudo is still running as root (pid ${root}); this one is exiting. Run '${engramCommand("status")}' to see how to stop it`;
1146
+ log(message);
1147
+ return { state: "taken", message, retry: false };
1148
+ }
1149
+ if (stopAsked) {
1150
+ // Never the daemon: its own socket goes, and no PID file was written.
1151
+ if (result.state === "held")
1152
+ unlockEndpoint(result.held);
1153
+ log("asked to stop while starting; this one is exiting");
1154
+ return { state: "stopped" };
1155
+ }
1156
+ if (result.state === "held")
1157
+ held = result.held;
1158
+ else
1159
+ log(`running without the single-daemon lock: ${result.reason}`);
1160
+ writePidFile();
1161
+ process.on("exit", releaseDaemonLock);
1162
+ checkTimer = setInterval(() => void checkDaemonLock(), SELF_CHECK_MS);
1163
+ checkTimer.unref();
1164
+ if (result.state === "held" && watchStopFile) {
1165
+ stopTimer = setInterval(checkStopRequest, STOP_POLL_MS);
1166
+ stopTimer.unref();
1167
+ // A request this daemon stopped for is removed once it has, cleanly.
1168
+ // After an error exit it stays, for the supervisor: that exit came
1169
+ // after `engram stop`, so the daemon isn't started again.
1170
+ process.on("exit", (code) => {
1171
+ if (code === 0)
1172
+ removeStopFileIf((request) => request.pid === process.pid);
1173
+ });
1174
+ }
1175
+ else {
1176
+ watchStopFile = false;
1177
+ }
1178
+ return result.state === "held" ? { state: "held" } : { state: "unavailable", reason: result.reason };
1179
+ }
1180
+ /**
1181
+ * Let the lock go: the PID file first, when it names this process, so a
1182
+ * start that finds the socket gone doesn't then find this process, alive
1183
+ * for a moment more, named as the daemon. Then the socket. Safe to call
1184
+ * more than once, and on every exit.
1185
+ */
1186
+ export function releaseDaemonLock() {
1187
+ if (released)
1188
+ return;
1189
+ released = true;
1190
+ if (checkTimer)
1191
+ clearInterval(checkTimer);
1192
+ if (stopTimer)
1193
+ clearInterval(stopTimer);
1194
+ if (claim === null)
1195
+ return;
1196
+ removePidFileIf(process.pid);
1197
+ if (held)
1198
+ unlockEndpoint(held);
1199
+ held = null;
1200
+ }
1201
+ //# sourceMappingURL=instance.js.map