@ours.network/install 0.17.0 → 0.18.0-nightly.2

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.
@@ -0,0 +1,349 @@
1
+ // ours-install v3 — the real side effects.
2
+ //
3
+ // Every mutation the installer can perform lives here and nowhere else, behind
4
+ // the same contract lib/orchestrate.mjs is tested against. Keeping them in one
5
+ // small file is the point: it is the only place to audit for "does this touch
6
+ // the machine", and it is what makes the fake used in the tests a faithful
7
+ // stand-in rather than an approximation.
8
+ //
9
+ // NOTE: nothing here runs systemctl. systemd is reached ONLY through
10
+ // `ours daemon install-service`, which owns the marker check, the baked
11
+ // state-directory guard and the enable/reload. The installer never touches a
12
+ // unit file or the service manager directly.
13
+
14
+ import { spawnSync, execFileSync } from 'node:child_process';
15
+ import { existsSync, readFileSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
16
+ import { homedir, userInfo, platform as osPlatform, release as osRelease } from 'node:os';
17
+ import { dirname, join, resolve } from 'node:path';
18
+ import { atomicWriteConfig, snapshotConfig, restoreConfig } from './config.mjs';
19
+ import { askYesNo, askLine as askLineOnTty } from './prompt.mjs';
20
+ import { classifyHarnessProbe } from './logic.mjs';
21
+ import { classifyStateDir } from './detect.mjs';
22
+
23
+ /** GET http://127.0.0.1:<port>/state-dir — the unauthenticated identity probe. */
24
+ async function probePort(port, { timeoutMs = 1500 } = {}) {
25
+ const controller = new AbortController();
26
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
27
+ try {
28
+ const res = await fetch(`http://127.0.0.1:${port}/state-dir`, { signal: controller.signal });
29
+ if (!res.ok) return { ok: false, reason: `HTTP ${res.status}` };
30
+ const body = await res.json();
31
+ if (typeof body?.stateDir !== 'string') return { ok: false, reason: 'no stateDir in reply' };
32
+ return { ok: true, stateDir: body.stateDir };
33
+ } catch (error) {
34
+ return { ok: false, reason: error?.name === 'AbortError' ? 'timed out' : String(error?.message ?? error) };
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Is this port bound? Probed in a throwaway child so a bind attempt cannot leave
42
+ * a listener behind in this process — the same technique the existing installer
43
+ * uses (install.mjs portTakenSync).
44
+ */
45
+ function portTakenSync(port) {
46
+ const src = `const net=require('net');const s=net.createServer();s.once('error',e=>{process.exit(e.code==='EADDRINUSE'?3:0)});s.listen(${port},'127.0.0.1',()=>{s.close(()=>process.exit(0))});`;
47
+ return spawnSync(process.execPath, ['-e', src], { stdio: 'ignore' }).status === 3;
48
+ }
49
+
50
+ function readJsonFile(path) {
51
+ try {
52
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
53
+ return parsed && typeof parsed === 'object' ? parsed : null;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ function readTextFile(path) {
60
+ try {
61
+ return readFileSync(path, 'utf8');
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ function installedVersionOf(pkg) {
68
+ try {
69
+ const out = execFileSync('npm', ['ls', '-g', '--depth', '0', '--json', pkg], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
70
+ return JSON.parse(out)?.dependencies?.[pkg]?.version ?? null;
71
+ } catch {
72
+ // Unreadable is NOT "new enough": the cowork gate fails closed on null.
73
+ return null;
74
+ }
75
+ }
76
+
77
+ /**
78
+ * A read-only command probe that NEVER throws and NEVER inherits stdio.
79
+ *
80
+ * Separate from `run` on purpose. `run` is for mutations and throws on a
81
+ * non-zero exit, because a failed mutation is news. Detection is the opposite:
82
+ * a non-zero exit IS the answer, and a hung wrapper must be killed rather than
83
+ * waited on. Mixing the two would mean either detection crashes a run or a
84
+ * failed install passes silently.
85
+ */
86
+ function capture(cmd, args, { timeout, env = process.env } = {}) {
87
+ const r = spawnSync(cmd, args, { encoding: 'utf8', timeout, stdio: ['ignore', 'pipe', 'pipe'], env });
88
+ const timedOut = !!(r.error && (r.error.code === 'ETIMEDOUT' || r.signal === 'SIGTERM'));
89
+ return {
90
+ ok: !r.error && r.status === 0,
91
+ code: r.status ?? -1,
92
+ stdout: r.stdout ?? '',
93
+ stderr: r.stderr ?? '',
94
+ timedOut,
95
+ };
96
+ }
97
+
98
+ // The two harnesses that are DRIVEN CLIs. The `name` is the one lib/extras.mjs
99
+ // plans against; the `command` is what actually lives on PATH.
100
+ export const DRIVEN_HARNESSES = [
101
+ { name: 'claude-code', command: 'claude', label: 'Claude Code' },
102
+ { name: 'codex', command: 'codex', label: 'Codex' },
103
+ ];
104
+
105
+ /**
106
+ * Alias-safety, unchanged from v2: three read-only observations, then the pure
107
+ * classifier decides. The harness is NEVER called in a way that can hang —
108
+ * `--version` is spawned directly (no shell, so a real PATH binary) under a hard
109
+ * timeout, and the shell `type` lookup is timeout-guarded too.
110
+ */
111
+ function detectDrivenHarness({ name, command, label }, env) {
112
+ const onPath = capture('bash', ['-c', `command -v ${command}`], { env }).ok;
113
+ const probe = capture(command, ['--version'], { timeout: 6000, env });
114
+ const versionOk = probe.ok && /\d+\.\d+/.test(probe.stdout);
115
+ const shell = env.SHELL || '/bin/bash';
116
+ const typeProbe = capture(shell, ['-ic', `type -t ${command} 2>/dev/null`], { timeout: 4000, env });
117
+ const verdict = classifyHarnessProbe({
118
+ onPath, versionOk, timedOut: probe.timedOut, shellType: (typeProbe.stdout || '').trim(),
119
+ });
120
+ return { name, command, label, ...verdict };
121
+ }
122
+
123
+ /**
124
+ * Hermes is detected DIFFERENTLY, and it is not an inconsistency. Its ours
125
+ * plugin never calls a `hermes` binary — `ours-hermes-install` writes
126
+ * ~/.hermes/config.yaml and the skills — so "can we drive it?" is the wrong
127
+ * question. Per the plugin's own prerequisites, presence IS the config
128
+ * directory. The CLI probe still runs, purely to enrich detection.
129
+ */
130
+ function detectHermesHarness(env, home) {
131
+ const dir = env.HERMES_DIR || join(home, '.hermes');
132
+ const dirPresent = existsSync(dir);
133
+ const cli = detectDrivenHarness({ name: 'hermes', command: 'hermes', label: 'Hermes' }, env);
134
+ return {
135
+ name: 'hermes',
136
+ command: 'hermes',
137
+ label: 'Hermes',
138
+ status: dirPresent || cli.status === 'ok' ? 'ok' : 'absent',
139
+ detail: dirPresent ? `config dir ${dir} present` : cli.detail,
140
+ };
141
+ }
142
+
143
+ /**
144
+ * Best-effort clipboard copy (pbcopy / wl-copy / xclip / clip.exe). The hard
145
+ * timeout is load-bearing: xclip holds the selection and would otherwise keep
146
+ * the installer alive after its own summary.
147
+ */
148
+ function copyToClipboard(text) {
149
+ const tools = [['pbcopy', []], ['wl-copy', []], ['xclip', ['-selection', 'clipboard']], ['clip.exe', []]];
150
+ for (const [bin, args] of tools) {
151
+ try {
152
+ const r = spawnSync(bin, args, { input: text, timeout: 2000 });
153
+ if (!r.error && (r.status === 0 || r.status == null)) return true;
154
+ } catch { /* try the next one */ }
155
+ }
156
+ return false;
157
+ }
158
+
159
+ /**
160
+ * Every DAEMON state directory on this machine.
161
+ *
162
+ * ONE DEFINITION OF WHAT A DAEMON IS, and this function is why that matters.
163
+ *
164
+ * It used to count any `~/.ours*` directory containing a config.json. Two of those
165
+ * are not daemons on a perfectly normal machine: `~/.ours-telegram/config.json` is
166
+ * the Telegram connector's and `~/.ours-cowork/config.json` is cowork's. So the
167
+ * uninstaller reported "@ours.network/cli kept — still used by the daemon at
168
+ * ~/.ours-telegram", and two things followed silently:
169
+ *
170
+ * · planGlobalPackages kept cli, mcp and the plugin packages FOREVER on any
171
+ * machine with the connector installed, naming a connector's config directory
172
+ * as a daemon;
173
+ * · worse, planPluginRemoval's `lastDaemon` went false, so the whole harness
174
+ * plugin phase was skipped — with a reason that was not true. A plain
175
+ * interactive `ours-uninstall` on a machine with the connector removed no
176
+ * plugins at all.
177
+ *
178
+ * The selection screen had already closed exactly this: config.json is the one
179
+ * piece of evidence that is AMBIGUOUS, so it cannot be the test. That predicate
180
+ * lives in lib/detect.mjs and this now calls it rather than keeping a second,
181
+ * naive copy that drifted. A daemon is identified by an artefact only a daemon
182
+ * writes, or by a config whose SHAPE is a daemon's.
183
+ *
184
+ * Still deliberately conservative about WHERE it looks: only `~/.ours` and its
185
+ * `~/.ours*` siblings. A state directory somewhere else is not found, and an
186
+ * unreadable home means "there might be others", not "there are none" — because
187
+ * the caller uses this to decide whether a GLOBAL package is still needed, and
188
+ * being wrong the optimistic way uninstalls the CLI out from under a running
189
+ * daemon.
190
+ */
191
+ function knownStateDirsIn(home) {
192
+ const found = [];
193
+ const io = { exists: existsSync, readJson: readJsonFile };
194
+ const consider = (dir) => { if (classifyStateDir(dir, io).isDaemon) found.push(dir); };
195
+ consider(join(home, '.ours'));
196
+ try {
197
+ for (const entry of readdirSync(home, { withFileTypes: true })) {
198
+ if (!entry.isDirectory() || !entry.name.startsWith('.ours') || entry.name === '.ours') continue;
199
+ consider(join(home, entry.name));
200
+ }
201
+ } catch { /* an unreadable home is not evidence that there are no others */ }
202
+ return found;
203
+ }
204
+
205
+ /**
206
+ * Build the real effects. `write` and `ttyFd` come from the caller's UI layer so
207
+ * the orchestrator never reaches for a terminal itself.
208
+ */
209
+ export function realEffects({ write, ttyFd, env = process.env, home = homedir(), out, version = null } = {}) {
210
+ return {
211
+ home,
212
+ env,
213
+ version,
214
+ // Preflight reads the machine rather than asking the orchestrator to.
215
+ platform: { platform: osPlatform(), release: osRelease() },
216
+ nodeVersion: process.versions.node,
217
+ exists: (path) => existsSync(path),
218
+ knownStateDirs: () => knownStateDirsIn(home),
219
+ // The only irreversible effect in this package, and the reason it takes no
220
+ // pattern and no parent: the caller passes ONE resolved directory that the
221
+ // pure planner already gated four ways, and this deletes exactly that.
222
+ removeDir: (path) => { rmSync(resolve(path), { recursive: true, force: true }); },
223
+ removeFile: (path) => { rmSync(resolve(path), { force: true }); },
224
+ // Rewrites a config file we do NOT own, so it keeps the file's own mode
225
+ // rather than imposing 0600: tightening the permissions of somebody else's
226
+ // ~/.codex/config.toml is a side effect nobody asked this to have.
227
+ //
228
+ // DO NOT "IMPROVE" THIS TO 0600. It looks like a security improvement, which
229
+ // is exactly why someone will try — but this file is the operator's, not
230
+ // ours, and the only thing we were invited to do to it is remove our own
231
+ // block. Changing its mode on the way past is an uninvited change to a file
232
+ // we happened to be holding, and a tool that does that once is a tool you
233
+ // cannot let near your configs.
234
+ writeText: (path, text) => {
235
+ const mode = (() => { try { return statSync(path).mode & 0o777; } catch { return 0o644; } })();
236
+ const temp = `${path}.tmp-${process.pid}`;
237
+ writeFileSync(temp, text, { encoding: 'utf8', mode });
238
+ renameSync(temp, path);
239
+ },
240
+ username: () => { try { return userInfo().username || 'me'; } catch { return 'me'; } },
241
+ detectHarnesses: () => [
242
+ ...DRIVEN_HARNESSES.map((h) => detectDrivenHarness(h, env)),
243
+ detectHermesHarness(env, home),
244
+ ],
245
+ clipboard: (text) => copyToClipboard(text),
246
+ brokerUrl: env.OURS_BROKER_URL ?? 'wss://broker1.ours.network',
247
+ now: () => Date.now(),
248
+ probe: (port) => probePort(port),
249
+ isTaken: (port) => portTakenSync(port),
250
+ readJson: readJsonFile,
251
+ readText: readTextFile,
252
+ writeJson: (path, text) => {
253
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
254
+ atomicWriteConfig(path, text);
255
+ },
256
+ // The two halves of a config rollback (lib/journal.mjs). Deliberately the
257
+ // SAME pair the nightly installer uses, from lib/config.mjs, rather than a
258
+ // second implementation: `snapshot` records bytes and mode, and `restore`
259
+ // either writes those bytes back at their original mode or DELETES a file
260
+ // that did not exist before this run. Both are ordinary reads and writes of a
261
+ // file this installer was already writing — no new class of side effect
262
+ // enters the package here.
263
+ snapshot: (path) => snapshotConfig(path),
264
+ restore: (path, snapshot) => restoreConfig(path, snapshot),
265
+ // `extraEnv` is the daemon pair (see daemonEnv). It is applied to THIS
266
+ // invocation only and never to the installer's own process: a state
267
+ // directory selected by one run must not leak into anything the operator
268
+ // starts afterwards.
269
+ run: async (cmd, args, { env: extraEnv = null } = {}) => {
270
+ // Always built from this layer's OWN env rather than left to spawnSync's
271
+ // implicit inheritance, so what a child receives is a property of the
272
+ // effects object a caller constructed and not of whatever ambient shell
273
+ // the installer happened to start in.
274
+ const childEnv = { ...env, ...(extraEnv ?? {}) };
275
+ const r = spawnSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], env: childEnv });
276
+ if (r.status !== 0) {
277
+ const detail = (r.stderr || r.stdout || '').trim().split('\n').slice(-3).join('; ');
278
+ throw new Error(`${cmd} ${args.join(' ')} exited ${r.status}${detail ? `: ${detail}` : ''}`);
279
+ }
280
+ return { ok: true, code: r.status, stdout: r.stdout ?? '' };
281
+ },
282
+ // The ONE invocation that must keep the user's terminal: `ours-mcp
283
+ // voice-setup` is an interactive command with its own masked prompts, and
284
+ // piping its stdio would hang it forever waiting on input nobody can type.
285
+ // It is otherwise the same contract as `run` — including the environment,
286
+ // so an interactive command reaches the same daemon a piped one would.
287
+ runInteractive: async (cmd, args, { env: extraEnv = null } = {}) => {
288
+ const r = spawnSync(cmd, args, { stdio: 'inherit', env: { ...env, ...(extraEnv ?? {}) } });
289
+ return { ok: !r.error && r.status === 0, code: r.status ?? -1 };
290
+ },
291
+ installedVersion: installedVersionOf,
292
+ out: out ?? ((line) => process.stdout.write(`${line}\n`)),
293
+ // Never called when assumeYes: the orchestrator takes the default itself.
294
+ ask: async (prompt, def = false) => (ttyFd == null ? def : askYesNo(write, ttyFd, ` ${prompt} `, def)),
295
+ askLine: async (prompt, def = '') => (ttyFd == null ? def : askLineOnTty(write, ttyFd, ` ${prompt} `, def)),
296
+ };
297
+ }
298
+
299
+ export const __testables = { probePort, portTakenSync, readJsonFile, readTextFile, installedVersionOf, knownStateDirsIn };
300
+
301
+ // -----------------------------------------------------------------------------
302
+ // THE PAIR
303
+ // -----------------------------------------------------------------------------
304
+
305
+ /**
306
+ * The environment that names ONE daemon, for a single child invocation.
307
+ *
308
+ * Spec §2's rule is that a state directory and an endpoint always travel
309
+ * together; "endpoint selected, state directory defaulted" must be unreachable.
310
+ * Every consumer downstream — ours-mcp's proxy, ours-fleet's per-role resolver,
311
+ * ours-hermes-install — reads these three names and falls back to `~/.ours` for
312
+ * whichever one is missing. So a HALF pair does not fail: it silently attaches
313
+ * to the default daemon while the operator was told a different one was chosen.
314
+ *
315
+ * That is why this is a function and not three assignments at the call sites.
316
+ * There is exactly one place a daemon environment can be built, it takes both
317
+ * halves as arguments, and it refuses rather than emit a partial one.
318
+ *
319
+ * The three names, not two, are deliberate: OURS_CONFIG alone would leave the
320
+ * port to whatever config.json happens to say, which is exactly the stale-file
321
+ * divergence lib/target.mjs's second lookup exists to survive.
322
+ */
323
+ export const DAEMON_ENV_KEYS = ['OURS_CONFIG', 'OURS_STATE_DIR', 'OURS_PORT'];
324
+
325
+ export function daemonEnv(stateDir, port) {
326
+ const dir = typeof stateDir === 'string' ? stateDir.trim() : '';
327
+ if (!dir) throw new Error('daemonEnv requires a state directory: refusing to build half of the daemon pair');
328
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
329
+ throw new Error('daemonEnv requires a port between 1 and 65535: refusing to build half of the daemon pair');
330
+ }
331
+ const resolved = resolve(dir);
332
+ return {
333
+ OURS_CONFIG: join(resolved, 'config.json'),
334
+ OURS_STATE_DIR: resolved,
335
+ OURS_PORT: String(port),
336
+ };
337
+ }
338
+
339
+ /** Is this environment a whole pair (or nothing at all)? Never one half. */
340
+ export function isWholeDaemonEnv(env) {
341
+ if (env == null) return true;
342
+ const present = DAEMON_ENV_KEYS.filter((k) => typeof env[k] === 'string' && env[k] !== '');
343
+ if (present.length === 0) return true;
344
+ if (present.length !== DAEMON_ENV_KEYS.length) return false;
345
+ return env.OURS_CONFIG === join(resolve(env.OURS_STATE_DIR), 'config.json');
346
+ }
347
+
348
+ /** The state directory a default run targets, for callers that need it early. */
349
+ export const defaultStateDir = (home = homedir()) => join(home, '.ours');