@ours.network/install 0.17.0-nightly.1 → 0.17.0-nightly.3

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 (4) hide show
  1. package/README.md +152 -24
  2. package/install.mjs +425 -75
  3. package/lib/logic.mjs +419 -21
  4. package/package.json +1 -1
package/install.mjs CHANGED
@@ -2,9 +2,16 @@
2
2
  // ours.network — the unified `ours-install` experience (the real UX behind install.sh's thin
3
3
  // bootstrap, and the `ours-install` command once the stack is on the machine).
4
4
  //
5
- // ONE installer for the WHOLE stack — ours core (the daemon) + the harness plugins (Claude Code /
6
- // Codex / Hermes) + ours-fleet + the Telegram connector — for someone who ALREADY has Claude,
7
- // Codex, and/or Hermes.
5
+ // ONE installer for the WHOLE stack — the shared ours daemon + the harness plugins (Claude Code /
6
+ // Codex / Hermes) + ours-fleet + the Telegram connector + Rooms (ours-cowork) — for someone who
7
+ // ALREADY has Claude, Codex, and/or Hermes.
8
+ //
9
+ // TOPOLOGY. Step 1 installs and configures ONE shared daemon and the user picks its listen port
10
+ // there; every consumer below is wired to that endpoint. The Telegram connector may instead be
11
+ // given its OWN daemon — its own port, state directory and boot unit — chosen independently, and
12
+ // defaulting to the shared one so Enter and non-interactive runs keep the historical topology.
13
+ // Rooms answers the same question, plus a third answer the connector has no use for: keeping
14
+ // cowork's own EMBEDDED daemon, which is what every pre-PR#9 cowork install runs (see step 5).
8
15
  // Its whole job: install the stack cleanly, then hand back ONE copy-paste prompt the user drops
9
16
  // into their agent to finish remaining configuration conversationally. Voice API credentials are
10
17
  // the one guided secret flow: interactive, masked, optional, and written atomically with mode 0600.
@@ -20,21 +27,28 @@
20
27
  import { spawn, spawnSync } from 'node:child_process';
21
28
  import { readFileSync, existsSync } from 'node:fs';
22
29
  import { homedir, userInfo, platform as osPlatform, release as osRelease } from 'node:os';
23
- import { join } from 'node:path';
30
+ import { join, resolve } from 'node:path';
24
31
  import { banner, heading, ok, info, warn, c, box, withSpinner, openTty, makeWriter, closeSync } from './lib/ui.mjs';
25
32
  import { askLine, askYesNo, isCancel } from './lib/prompt.mjs';
26
33
  import {
27
34
  suggestPort, parsePort, validateBroker, mergeConfig, parseVersion, parseStatus,
28
35
  detectPlatform, classifyHarnessProbe, buildHandoffPrompt,
29
- voiceSetupStatus,
36
+ voiceSetupStatus, resolveSharedBroker, tgConfigPath, planTgDaemonConfig, daemonEndpoint,
30
37
  DEFAULT_PORT, resolveChannel, pkgSpec,
38
+ validateDaemonPort, planPorts, dedicatedDaemonPaths, DEDICATED_INSTANCES,
39
+ coworkConfigPath, planCoworkConfig, COWORK_DEFAULT_PORT, coworkDaemonMode,
40
+ coworkSupportsExternalDaemon, COWORK_EXTERNAL_MIN_VERSION,
31
41
  } from './lib/logic.mjs';
32
42
  import { atomicWriteConfig } from './lib/config.mjs';
33
43
 
34
44
  const NPM = process.env.OURS_NPM || 'npm';
35
- // Release channel: OURS_CHANNEL=nightly installs @nightly for mcp/tg-connector/plugin
36
- // launchers but keeps @ours.network/fleet at @latest (fleet has no nightly). Default: latest.
37
- const CHANNEL = resolveChannel(process.env.OURS_CHANNEL || process.env.OURS_INSTALL_CHANNEL);
45
+ // Release channel: OURS_CHANNEL=nightly installs each package's PRERELEASE dist-tag —
46
+ // @nightly for mcp/tg-connector/fleet/the plugin launchers, and @latest for cowork,
47
+ // and @next for cowork, whose repo has always called its prerelease line `next`
48
+ // (see PKG_CHANNEL_TAGS in lib/logic.mjs). With no explicit
49
+ // selection the installer follows its OWN channel, so a nightly installer builds a
50
+ // nightly stack instead of silently mixing tags across an architecture boundary.
51
+ const CHANNEL = resolveChannel(process.env.OURS_CHANNEL || process.env.OURS_INSTALL_CHANNEL, pkgVersion());
38
52
  const spec = (pkgKey) => pkgSpec(pkgKey, CHANNEL); // → "@ours.network/<key>@<tag>"
39
53
  let DRY = !!process.env.OURS_INSTALL_DRY_RUN;
40
54
  const SELFHOST_URL = 'ours.network';
@@ -46,10 +60,11 @@ const line = (s = '') => sink(`${s}\n`);
46
60
  const say = (s) => sink(`ours: ${s}\n`);
47
61
 
48
62
  // --- external command helpers (never throw; the installer degrades, it doesn't crash) ----------
49
- function run(bin, args, { capture = false, timeout } = {}) {
63
+ function run(bin, args, { capture = false, timeout, env } = {}) {
50
64
  const r = spawnSync(bin, args, {
51
65
  encoding: 'utf8',
52
66
  timeout,
67
+ env: env ? { ...process.env, ...env } : process.env,
53
68
  stdio: capture ? ['ignore', 'pipe', 'pipe'] : 'inherit',
54
69
  });
55
70
  const timedOut = !!(r.error && (r.error.code === 'ETIMEDOUT' || r.signal === 'SIGTERM'));
@@ -94,9 +109,13 @@ function daemonLifecycleState() {
94
109
  return /^\s*pid:\s*\d+/m.test(status.out) ? 'managed' : 'external';
95
110
  }
96
111
  const daemonRunning = () => daemonLifecycleState() !== 'stopped';
112
+ // The installed version of a global package, INCLUDING any prerelease suffix. The
113
+ // suffix is not cosmetic here: the Rooms daemon guard compares against an exact
114
+ // `0.4.1-nightly.<date>.<sha>` floor, and truncating at the dash would make every
115
+ // 0.4.1 nightly look alike — including ones published before the mode existed.
97
116
  const globalVersion = (pkg) => {
98
117
  const ls = run(NPM, ['ls', '-g', pkg], { capture: true }).out;
99
- const m = ls.match(new RegExp(pkg.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&') + '@([0-9][0-9.]*)'));
118
+ const m = ls.match(new RegExp(pkg.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&') + '@(\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?)'));
100
119
  return m ? m[1] : '';
101
120
  };
102
121
 
@@ -109,6 +128,18 @@ function writeConfigPatch(patch) {
109
128
  return p;
110
129
  }
111
130
 
131
+ // The daemon's state directory, resolved exactly the way packages/core/src/config.ts
132
+ // resolves it (env > config file > ~/.ours). The Telegram connector needs the ABSOLUTE
133
+ // path: the SDK reads the daemon's API token from it and refuses to send that token to
134
+ // a separately-chosen endpoint unless the state dir was chosen just as deliberately.
135
+ function daemonStateDir() {
136
+ const fromEnv = process.env.OURS_STATE_DIR?.trim();
137
+ if (fromEnv) return resolve(fromEnv);
138
+ const fromFile = readConfigObject().stateDir;
139
+ if (typeof fromFile === 'string' && fromFile.trim()) return resolve(fromFile.trim());
140
+ return join(homedir(), '.ours');
141
+ }
142
+
112
143
  function daemonVoiceCapability() {
113
144
  const r = run('ours-mcp', ['voice-status', '--json'], { capture: true, timeout: 6000 });
114
145
  if (!r.ok) return null;
@@ -179,10 +210,13 @@ const USAGE = `ours-install — the unified ours.network stack installer.
179
210
 
180
211
  ours-install [--dry-run] [--help] [--version]
181
212
 
182
- Guided ~3-minute setup for the whole stack: ours core (the daemon), the harness
183
- plugins (Claude Code + Codex + Hermes), ours-fleet, and the Telegram connector — then one
184
- copy-paste hand-off prompt. You approve each step; re-run any time to add a piece
185
- or update.
213
+ Guided ~3-minute setup for the whole stack: the shared ours daemon (you pick its
214
+ port), the harness plugins (Claude Code + Codex + Hermes), ours-fleet, the Telegram
215
+ connector, and Rooms (ours-cowork) — then one copy-paste hand-off prompt. You approve
216
+ each step; re-run any time to add a piece or update.
217
+
218
+ Telegram can share the daemon from step 1 or be given its own (its own port, state
219
+ directory and boot service); Enter keeps the shared one.
186
220
 
187
221
  --dry-run walk the whole flow and print what it WOULD do — install/change nothing
188
222
  --help show this help and exit
@@ -281,56 +315,44 @@ async function main() {
281
315
  line('');
282
316
  cont();
283
317
 
284
- // ============================================================================================
285
- // STEP 0 — the two config questions (asked ONCE, up front). SKIPPED entirely when a daemon is
286
- // already configured (update path reuses its port/broker; delta #1859).
287
- // ============================================================================================
288
318
  const status0 = parseStatus(daemonStatusText());
289
319
  let chosenBroker; // undefined = keep default / existing
290
320
  let chosenPort = status0.port || DEFAULT_PORT;
291
321
  const configFirst = !daemonInstalled;
292
322
 
293
- if (configFirst) {
294
- line(heading('A couple of quick settings'));
295
- // 0a — broker (owner edit #1: SECURE wording; owner edit #2: self-host → website only).
296
- line(info('Your agents connect through a "broker" — a shared meeting point that lets them find'));
297
- line(info("each other. It's secure: your messages are end-to-end encrypted, so the broker never"));
298
- line(info('sees what they say. Almost everyone uses the standard one — just press Enter.'));
299
- const custom = yes(' Use a custom broker address?', false);
300
- if (custom) {
301
- line(info(`(Only needed if you run your own broker. More at ${SELFHOST_URL}.)`));
302
- const entered = ask(' Enter the broker address: ', '');
303
- const v = validateBroker(entered);
304
- if (entered && v.ok && !v.empty) {
305
- // Undo safety net: a mistaken custom entry is one keystroke back to the standard broker.
306
- const keep = yes(` Use "${v.value}"? (No = go back to the standard broker)`, true);
307
- if (keep) { chosenBroker = v.value; line(ok(`broker set to ${chosenBroker}.`)); }
308
- else line(ok('using the standard broker.'));
309
- } else {
310
- if (entered) line(warn(`"${entered}" doesn't look like a ws:// address — using the standard broker.`));
311
- else line(ok('using the standard broker.'));
312
- }
313
- } else {
314
- line(ok('using the standard broker.'));
315
- }
323
+ // Every port this run has committed to, so a later daemon can't be handed one an
324
+ // earlier daemon claimed. A live bind probe cannot see these — nothing is
325
+ // listening on them yet — which is exactly why they're tracked by hand.
326
+ const claimedPorts = [];
327
+ // The finished topology, for the end-of-run cross-check. Each entry is one thing that
328
+ // will try to BIND a port, named so a collision can be reported in the user's terms.
329
+ const topology = [];
330
+ const claimPort = (port, label) => {
331
+ if (!Number.isInteger(port)) return;
332
+ if (!claimedPorts.includes(port)) claimedPorts.push(port);
333
+ if (label) topology.push({ label, port });
334
+ };
316
335
 
317
- // 0b — port: probe 3050; only ask if busy. Minimize the concept.
318
- if (!portTakenSync(DEFAULT_PORT)) {
319
- chosenPort = DEFAULT_PORT;
320
- line(ok(`Using local port ${DEFAULT_PORT}.`));
321
- } else {
322
- line(info(`The standard local port (${DEFAULT_PORT}) is already in use on your machine.`));
323
- let candidate = suggestPort(DEFAULT_PORT + 1, portTakenSync);
324
- const raw = ask(` Pick another number for the ours daemon? ${c.gray(`[Enter for ${candidate}]`)}: `, String(candidate));
325
- const parsed = parsePort(raw, candidate);
326
- candidate = suggestPort(parsed.ok ? parsed.port : candidate, portTakenSync);
327
- chosenPort = candidate;
328
- line(ok(`Using local port ${chosenPort}.`));
336
+ // Ask for ONE daemon's port, validate it, and keep asking until the answer is
337
+ // usable. Enter (and every non-interactive run) takes `def` unchanged — that is
338
+ // what keeps the historical behaviour and scripted installs identical.
339
+ const askDaemonPort = (prompt, def) => {
340
+ let candidate = def;
341
+ for (let attempt = 0; attempt < 3; attempt++) {
342
+ const raw = ask(` ${prompt} ${c.gray(`[Enter for ${candidate}]`)}: `, String(candidate));
343
+ const v = validateDaemonPort(raw, { fallback: candidate, isTaken: portTakenSync, taken: claimedPorts });
344
+ if (v.ok) return v.port;
345
+ line(warn(`${v.reason}.`));
346
+ if (!interactive) break; // no one to re-ask; fall through to a suggestion
347
+ candidate = suggestPort(v.port + 1, (p) => claimedPorts.includes(p) || portTakenSync(p));
348
+ line(info(`Suggesting ${candidate} instead.`));
329
349
  }
330
- line('');
331
- line(ok(`Config ready — broker: ${chosenBroker ? 'custom' : 'standard'}, port: ${chosenPort}.`));
332
- cont();
333
- }
350
+ // Out of attempts (or headless): take the first genuinely free port rather
351
+ // than persisting one we know is unusable.
352
+ const fallback = suggestPort(candidate, (p) => claimedPorts.includes(p) || portTakenSync(p));
353
+ line(ok(`Using port ${fallback}.`));
354
+ return fallback;
355
+ };
334
356
 
335
357
  // Track outcomes for the summary + hand-off.
336
358
  const summary = [];
@@ -417,13 +439,57 @@ async function main() {
417
439
  };
418
440
 
419
441
  // ============================================================================================
420
- // STEP 1 / 4 — ours core (the daemon). Config-first: write config → optional voice → start ONCE.
442
+ // STEP 1 / 5 — the SHARED ours daemon. Its own visible step, and it owns its own configuration
443
+ // (broker + listen port) rather than a nameless "quick settings" preamble: every consumer below
444
+ // is wired to the endpoint chosen HERE, so the choice belongs to the step that makes it.
445
+ // Config-first within the step: choose → write config → optional voice → start ONCE.
421
446
  // ============================================================================================
422
- line(heading('1/4 — ours core (the daemon)'));
423
- line(info('This is the piece that lets your agents talk to each other securely. Everything else'));
424
- line(info('needs it.'));
447
+ line(heading('1/5 — the shared ours daemon'));
448
+ line(info('This is the piece that lets your agents talk to each other securely. The harness'));
449
+ line(info('plugins, ours-fleet and the Telegram connector all connect to it — Telegram can be'));
450
+ line(info('given its own instead, later — and so can Rooms.'));
425
451
  const before = parseVersion(versionBefore);
426
452
 
453
+ if (configFirst) {
454
+ // Broker (owner edit #1: SECURE wording; owner edit #2: self-host → website only).
455
+ line('');
456
+ line(info('Your agents connect through a "broker" — a shared meeting point that lets them find'));
457
+ line(info("each other. It's secure: your messages are end-to-end encrypted, so the broker never"));
458
+ line(info('sees what they say. Almost everyone uses the standard one — just press Enter.'));
459
+ const custom = yes(' Use a custom broker address?', false);
460
+ if (custom) {
461
+ line(info(`(Only needed if you run your own broker. More at ${SELFHOST_URL}.)`));
462
+ const entered = ask(' Enter the broker address: ', '');
463
+ const v = validateBroker(entered);
464
+ if (entered && v.ok && !v.empty) {
465
+ // Undo safety net: a mistaken custom entry is one keystroke back to the standard broker.
466
+ const keep = yes(` Use "${v.value}"? (No = go back to the standard broker)`, true);
467
+ if (keep) { chosenBroker = v.value; line(ok(`broker set to ${chosenBroker}.`)); }
468
+ else line(ok('using the standard broker.'));
469
+ } else {
470
+ if (entered) line(warn(`"${entered}" doesn't look like a ws:// address — using the standard broker.`));
471
+ else line(ok('using the standard broker.'));
472
+ }
473
+ } else {
474
+ line(ok('using the standard broker.'));
475
+ }
476
+
477
+ // Listen port. ALWAYS asked now, so the shared daemon's endpoint is a decision the
478
+ // user makes rather than one they only hear about when 3050 happens to be busy.
479
+ // The default is still 3050 (the next free port when it is taken), so Enter and
480
+ // every non-interactive run land exactly where they always did.
481
+ line('');
482
+ line(info('The daemon listens on a local port. Everything else in this install is pointed at it.'));
483
+ const portDefault = portTakenSync(DEFAULT_PORT) ? suggestPort(DEFAULT_PORT + 1, portTakenSync) : DEFAULT_PORT;
484
+ if (portDefault !== DEFAULT_PORT) line(info(`The standard port (${DEFAULT_PORT}) is already in use on your machine.`));
485
+ chosenPort = askDaemonPort('Which local port should the shared daemon use?', portDefault);
486
+ line(ok(`Shared daemon: port ${chosenPort}, broker ${chosenBroker ? 'custom' : 'standard'}.`));
487
+ line('');
488
+ } else {
489
+ line(ok(`Shared daemon already configured — port ${chosenPort}. Keeping it.`));
490
+ }
491
+ claimPort(chosenPort, 'the shared ours daemon');
492
+
427
493
  if (!daemonInstalled) {
428
494
  const goCore = yes(' Install and start it?', true);
429
495
  if (!goCore) {
@@ -439,10 +505,24 @@ async function main() {
439
505
  const voice = offerVoiceSetup({ readinessAfterStart: true });
440
506
  const started = await act(`ours-mcp start (port ${chosenPort})`, async () => run('ours-mcp', ['start']));
441
507
  const svc = await act('ours-mcp install-service (survives reboot)', async () => run('ours-mcp', ['install-service']));
442
- if (started.ok) line(ok(`ours core ready — running on port ${chosenPort}. No problems.`));
508
+ // `ours-mcp install-service` STOPS the daemon before it writes the unit (core's
509
+ // cmdInstallService), then exits non-zero if `systemctl --user enable --now` fails —
510
+ // no linger, no user bus, a container, WSL without systemd. Left alone that turns a
511
+ // WORKING daemon into no daemon at all, while the line below still said "ready": the
512
+ // human identity and every MCP client then fail against a port nothing is listening
513
+ // on. Put the one shared daemon back up and report what is actually true.
514
+ let running = started.ok;
515
+ if (!DRY && !svc.ok) {
516
+ running = daemonRunning();
517
+ if (!running) {
518
+ line(info('the boot-service step stopped the daemon before it failed — restarting it.'));
519
+ running = run('ours-mcp', ['start']).ok || daemonRunning();
520
+ }
521
+ }
522
+ if (running) line(ok(`ours core ready — running on port ${chosenPort}. No problems.`));
443
523
  else line(warn(`could not auto-start — run '${c.cyan('ours-mcp start')}' to bring it up.`));
444
524
  if (!svc.ok && !svc.dry) line(warn(`boot-service not installed — retry '${c.cyan('ours-mcp install-service')}' later.`));
445
- if (voice.setupRan && !DRY && started.ok) {
525
+ if (voice.setupRan && !DRY && running) {
446
526
  const verified = daemonVoiceCapability();
447
527
  if (verified?.ready) {
448
528
  line(ok(`Voice transcription readiness confirmed (${verified.provider}) after the first start.`));
@@ -455,7 +535,13 @@ async function main() {
455
535
  }
456
536
  }
457
537
  }
458
- record({ key: 'core', label: 'ours core (daemon)', state: started.ok ? 'installed' : 'failed', version: parseVersion(daemonVersionLine()), note: 'starts on boot' });
538
+ record({
539
+ key: 'core',
540
+ label: 'ours core (daemon)',
541
+ state: running ? 'installed' : 'failed',
542
+ version: parseVersion(daemonVersionLine()),
543
+ note: svc.ok ? 'starts on boot' : 'running; no boot service',
544
+ });
459
545
  } else {
460
546
  // Installed: offer an update; never re-ask config; reuse the running port everywhere.
461
547
  const daemonState = daemonLifecycleState();
@@ -593,10 +679,10 @@ async function main() {
593
679
  }
594
680
 
595
681
  // ============================================================================================
596
- // STEP 2 / 4 — harness plugins (Claude Code + Codex + Hermes). The installer drives the plugin
682
+ // STEP 2 / 5 — harness plugins (Claude Code + Codex + Hermes). The installer drives the plugin
597
683
  // CLIs for Claude/Codex; Hermes installs via npm + ours-hermes-install (no CLI driving).
598
684
  // ============================================================================================
599
- line(heading('2/4 — harness plugins'));
685
+ line(heading('2/5 — harness plugins'));
600
686
  line(info('These teach Claude Code, Codex, and Hermes the ours skills, so you can just talk to your'));
601
687
  line(info("agent to message people and set things up. I'll install them for you — no commands to type."));
602
688
  for (const h of harnesses) {
@@ -609,9 +695,9 @@ async function main() {
609
695
  }
610
696
 
611
697
  // ============================================================================================
612
- // STEP 3 / 4 — ours-fleet. Appealing wording (owner edit #4); default YES.
698
+ // STEP 3 / 5 — ours-fleet. Appealing wording (owner edit #4); default YES.
613
699
  // ============================================================================================
614
- line(heading('3/4 — ours-fleet (your always-online agent team)'));
700
+ line(heading('3/5 — ours-fleet (your always-online agent team)'));
615
701
  line(info('This makes your harnesses PERSISTENT: Claude Code and Codex stop being just a terminal'));
616
702
  line(info('session and become always-online daemons that survive a reboot. Stand up your own team'));
617
703
  line(info('of always-online developers, combine harnesses, run several Claude Codes, and link them'));
@@ -639,24 +725,146 @@ async function main() {
639
725
  }
640
726
  cont(goFleet);
641
727
 
728
+ // The broker the WHOLE deployment shares, whichever daemon a consumer talks to.
729
+ const sharedBroker = () => resolveSharedBroker({
730
+ chosenBroker,
731
+ statusBroker: status0.broker,
732
+ configBroker: readConfigObject().brokerUrl,
733
+ });
734
+
735
+ // Provision a daemon that belongs to ONE consumer: its own config file, its own
736
+ // state directory, its own port, and — via core's OURS_SERVICE_NAME — its own boot
737
+ // unit, so `install-service` cannot overwrite the shared daemon's. Returns the
738
+ // endpoint + state dir to wire that consumer to, and whether it came up.
739
+ async function provisionDedicatedDaemon({ instance, port, label }) {
740
+ const { stateDir, configPath: cfgPath, serviceName } = dedicatedDaemonPaths(homedir(), instance);
741
+ const env = { OURS_CONFIG: cfgPath, OURS_STATE_DIR: stateDir, OURS_SERVICE_NAME: serviceName };
742
+ // The dedicated daemon has to exist as a package before it can be started; on a
743
+ // fresh machine step 1 already installed it, but a re-run that skipped core has not.
744
+ await actSpin(`ensuring ${spec('mcp')}…`, `npm i -g ${spec('mcp')}`, () => runAsync(NPM, ['i', '-g', spec('mcp')]));
745
+ const desired = { port, stateDir, serviceName };
746
+ const broker = sharedBroker();
747
+ if (broker) desired.brokerUrl = broker;
748
+ let existing = {};
749
+ try { existing = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch { /* absent or unreadable */ }
750
+ const sameAlready = existing.port === port && existing.stateDir === stateDir && existing.serviceName === serviceName;
751
+ if (sameAlready) {
752
+ line(ok(`The ${label} daemon is already configured on port ${port} — no change.`));
753
+ // Nothing to change AND it is already up: do not touch it. `install-service` STOPS
754
+ // the daemon before rewriting the unit, so re-running it here would bounce a healthy
755
+ // daemon for no reason.
756
+ if (!DRY && run('ours-mcp', ['status'], { capture: true, env }).ok) {
757
+ line(ok(`Dedicated ${label} daemon already running on port ${port} — left alone.`));
758
+ return { endpoint: daemonEndpoint(port), stateDir, serviceName, configPath: cfgPath, running: true, port };
759
+ }
760
+ } else {
761
+ await act(`write ${cfgPath} (dedicated ${label} daemon, port ${port}, state ${stateDir})`, async () => {
762
+ atomicWriteConfig(cfgPath, mergeConfig(existing, desired));
763
+ return { ok: true };
764
+ });
765
+ }
766
+ const started = await act(`ours-mcp start (dedicated ${label} daemon, port ${port})`, async () => run('ours-mcp', ['start'], { env }));
767
+ const svc = await act(`ours-mcp install-service (dedicated ${label} daemon, unit ours-${serviceName})`, async () => run('ours-mcp', ['install-service'], { env }));
768
+ // Same recovery as the shared daemon: install-service STOPS the daemon before it
769
+ // writes the unit, so a failure there leaves nothing listening on this port.
770
+ let running = started.ok;
771
+ if (!DRY && !svc.ok) {
772
+ running = run('ours-mcp', ['status'], { capture: true, env }).ok;
773
+ if (!running) {
774
+ line(info(`the boot-service step stopped the ${label} daemon before it failed — restarting it.`));
775
+ running = run('ours-mcp', ['start'], { env }).ok;
776
+ }
777
+ line(warn(`the ${label} daemon has no boot service — retry '${c.cyan(`OURS_CONFIG=${cfgPath} OURS_SERVICE_NAME=${serviceName} ours-mcp install-service`)}'.`));
778
+ }
779
+ if (running || DRY) line(ok(`Dedicated ${label} daemon ready on port ${port} (state ${stateDir}, unit ours-${serviceName}).`));
780
+ else line(warn(`could not start the dedicated ${label} daemon — run '${c.cyan(`OURS_CONFIG=${cfgPath} ours-mcp start`)}'.`));
781
+ return { endpoint: daemonEndpoint(port), stateDir, serviceName, configPath: cfgPath, running: running || DRY, port };
782
+ }
783
+
784
+ // Ask one consumer whether it uses the COMMON daemon or gets its own. Enter and
785
+ // every non-interactive run answer "common" — the historical topology.
786
+ const askDaemonMode = (what) => {
787
+ line(info(`${what} can share the daemon from step 1, or run against its own isolated one.`));
788
+ line(info('Sharing is right for almost everyone — press Enter. A dedicated daemon gets its own'));
789
+ line(info('port, state directory and boot service, and does not see the shared daemon\'s identities.'));
790
+ return yes(` Give ${what} its OWN dedicated daemon?`, false) ? 'dedicated' : 'common';
791
+ };
792
+
793
+ // Give the Telegram connector the daemon it was assigned: that daemon's loopback
794
+ // endpoint, the state directory that endpoint's API token belongs to, and — for a
795
+ // pre-0.3.3 connector that still meets the daemon at a broker instead — that broker.
796
+ // Idempotent: an unchanged selection writes nothing. Returns { changed, hadPrevious }
797
+ // so the caller can warn about a service unit that froze an older selection.
798
+ async function writeTgDaemonConfig({ endpoint, stateDir }) {
799
+ const path = tgConfigPath(process.env, homedir());
800
+ const desired = {
801
+ daemonUrl: endpoint,
802
+ daemonStateDir: stateDir,
803
+ brokerUrl: sharedBroker(),
804
+ };
805
+ let existing = {};
806
+ try { existing = JSON.parse(readFileSync(path, 'utf8')); } catch { /* absent or unreadable */ }
807
+ const plan = planTgDaemonConfig(existing, desired);
808
+ const hadPrevious = !!(plan.previous.daemonUrl || plan.previous.brokerUrl);
809
+ if (!plan.changed) {
810
+ line(ok(`Telegram connector already points at this daemon (${desired.daemonUrl}) — no change.`));
811
+ return { changed: false, hadPrevious };
812
+ }
813
+ await act(`write ${path} (daemon ${desired.daemonUrl}, state ${stateDir})`, async () => {
814
+ atomicWriteConfig(path, plan.text);
815
+ return { ok: true };
816
+ });
817
+ line(ok(`Telegram connector configured to use this daemon (${desired.daemonUrl}).`));
818
+ return { changed: true, hadPrevious };
819
+ }
820
+
642
821
  // ============================================================================================
643
- // STEP 4 / 4 — Telegram connector. Install-only (no bot tokens here). Then: run as a service?
822
+ // STEP 4 / 5 — Telegram connector. Install-only (no bot tokens here). Then: run as a service?
644
823
  // ============================================================================================
645
- line(heading('4/4 — Telegram connector'));
824
+ line(heading('4/5 — Telegram connector'));
646
825
  line(info('This bridges a Telegram bot to your Ours node, so you can talk to your agent from'));
647
826
  line(info("Telegram. (You'll set up the actual bot later, with your agent — not here.)"));
648
827
  const goTg = yes(' Install it?', false);
649
828
  if (goTg) {
650
829
  await actSpin(`installing ${spec('tg-connector')}…`, `npm i -g ${spec('tg-connector')}`, () => runAsync(NPM, ['i', '-g', spec('tg-connector')]));
830
+ // WHICH daemon — asked independently of every other consumer, and answered
831
+ // "common" by Enter / non-interactive so the historical topology is the default.
832
+ line('');
833
+ const tgMode = askDaemonMode('the Telegram connector');
834
+ let tgDaemon = { endpoint: daemonEndpoint(chosenPort), stateDir: daemonStateDir(), port: chosenPort, mode: 'common' };
835
+ if (tgMode === 'dedicated') {
836
+ const instance = DEDICATED_INSTANCES.telegram;
837
+ const suggested = suggestPort(chosenPort + 1, (p) => claimedPorts.includes(p) || portTakenSync(p));
838
+ const port = askDaemonPort('Which local port should the Telegram daemon use?', suggested);
839
+ claimPort(port, 'the dedicated Telegram daemon');
840
+ const provisioned = await provisionDedicatedDaemon({ instance, port, label: 'Telegram' });
841
+ tgDaemon = { ...provisioned, mode: 'dedicated' };
842
+ } else {
843
+ line(ok(`Telegram will use the shared daemon on port ${chosenPort}.`));
844
+ }
845
+ // POINT IT AT THAT DAEMON — BEFORE it is started or installed as a service.
846
+ // The connector never inherits ~/.ours/config.json (its SDK reports configPath:
847
+ // null unless told otherwise), and `install-service` bakes whatever it resolves
848
+ // into the unit as environment variables that outrank the file from then on. So
849
+ // the daemon's identity has to be in its config BEFORE either happens. See
850
+ // planTgDaemonConfig for why all three keys are written.
851
+ const tgConfigured = await writeTgDaemonConfig(tgDaemon);
852
+ const where = tgDaemon.mode === 'dedicated' ? `its own daemon on port ${tgDaemon.port}` : `the shared daemon on port ${tgDaemon.port}`;
651
853
  const asService = yes(' Keep it running in the background so it starts automatically on boot?', true);
652
854
  if (asService) {
653
855
  const svc = await act('ours-tg-connector install-service (starts on boot)', async () => run('ours-tg-connector', ['install-service']));
654
- if (svc.ok) line(ok('Telegram connector installed and running as a service (starts on boot). No problems.'));
856
+ if (svc.ok) line(ok(`Telegram connector installed and running as a service (starts on boot), pointed at ${where}. No problems.`));
655
857
  else line(warn(`connector installed, but the service didn't start — retry '${c.cyan('ours-tg-connector install-service')}'.`));
656
- record({ key: 'telegram', label: 'Telegram connector', state: 'installed', version: globalVersion('@ours.network/tg-connector'), note: 'service (boot)' });
858
+ record({ key: 'telegram', label: 'Telegram connector', state: 'installed', version: globalVersion('@ours.network/tg-connector'), note: `service (boot) · ${tgDaemon.mode} daemon ${tgDaemon.port}` });
657
859
  } else {
658
- line(ok(`Telegram connector installed. Start it any time with '${c.cyan('ours-tg-connector start')}'. No problems.`));
659
- record({ key: 'telegram', label: 'Telegram connector', state: 'installed', version: globalVersion('@ours.network/tg-connector'), note: 'start on demand' });
860
+ line(ok(`Telegram connector installed, pointed at ${where}. Start it any time with '${c.cyan('ours-tg-connector start')}'. No problems.`));
861
+ // A connector already installed as a service froze its OLD daemon selection into
862
+ // the unit's environment, which outranks the file we just wrote. Config alone
863
+ // cannot repair that — say so plainly rather than let it look fixed.
864
+ if (tgConfigured.changed && tgConfigured.hadPrevious) {
865
+ line(warn(`if you previously ran '${c.cyan('ours-tg-connector install-service')}', re-run it — the old service froze the previous daemon selection in its unit.`));
866
+ }
867
+ record({ key: 'telegram', label: 'Telegram connector', state: 'installed', version: globalVersion('@ours.network/tg-connector'), note: `start on demand · ${tgDaemon.mode} daemon ${tgDaemon.port}` });
660
868
  }
661
869
  } else {
662
870
  line(info('skipped cleanly.'));
@@ -664,6 +872,146 @@ async function main() {
664
872
  }
665
873
  cont(goTg);
666
874
 
875
+ // ============================================================================================
876
+ // STEP 5 / 5 — Rooms (ours-cowork). Two independent things get configured here.
877
+ //
878
+ // ITS OWN SURFACE — the deployment broker, its private state directory, and its loopback
879
+ // console/REST port. Those it has always had.
880
+ //
881
+ // WHICH DAEMON — ours-cowork used to host its own, always. It now supports an EXTERNAL ours
882
+ // daemon (cowork PR #9), so Rooms answers the same common-vs-dedicated question the Telegram
883
+ // connector does, plus a third state the connector does not have: EMBEDDED, cowork's own.
884
+ // Contract (see logic.mjs): the `daemon` block is optional; absent means embedded; external is
885
+ // { mode:'external', endpoint, stateDir } and REQUIRES both halves, because cowork holds no
886
+ // token and its SDK reads <stateDir>/daemon-token.
887
+ //
888
+ // Boot is FAIL-CLOSED on an unreachable endpoint, a non-ours daemon, or a mismatched state
889
+ // directory — there is no embedded fallback. So an install that is ALREADY running embedded is
890
+ // never migrated behind the user's back: non-interactively it is left exactly as it is, and
891
+ // interactively the question is asked plainly before anything is written.
892
+ // ============================================================================================
893
+ line(heading('5/5 — Rooms (ours-cowork)'));
894
+ line(info('Durable mission rooms: a room keeps its own ordered history, and people and agents'));
895
+ line(info('join it as seats. It serves a local web console, and reaches everyone through the'));
896
+ line(info('same broker as the rest of your install.'));
897
+ const goRooms = yes(' Install it?', false);
898
+ if (goRooms) {
899
+ await actSpin(`installing ${spec('cowork')}…`, `npm i -g ${spec('cowork')}`, () => runAsync(NPM, ['i', '-g', spec('cowork')]));
900
+ const roomsStateDir = join(homedir(), '.ours-cowork');
901
+ const cfgPath = coworkConfigPath(process.env, homedir());
902
+ let existingRooms = {};
903
+ try { existingRooms = JSON.parse(readFileSync(cfgPath, 'utf8')); } catch { /* absent or unreadable */ }
904
+ const restDefault = Number.isInteger(existingRooms.rest?.port) ? existingRooms.rest.port : COWORK_DEFAULT_PORT;
905
+ line('');
906
+ line(info('Rooms serves a console on a loopback port — 127.0.0.1 only, never exposed.'));
907
+ // COWORK_DEFAULT_PORT is in RESERVED_PORTS (so no ours daemon can be handed it),
908
+ // so validate this one against the daemon ports only.
909
+ const roomsPort = (() => {
910
+ let candidate = restDefault;
911
+ for (let attempt = 0; attempt < 3; attempt++) {
912
+ const raw = ask(` Which local port should the Rooms console use? ${c.gray(`[Enter for ${candidate}]`)}: `, String(candidate));
913
+ const v = validateDaemonPort(raw, {
914
+ fallback: candidate, isTaken: (p) => (p === restDefault ? false : portTakenSync(p)),
915
+ taken: claimedPorts, reserved: [],
916
+ });
917
+ if (v.ok) return v.port;
918
+ line(warn(`${v.reason}.`));
919
+ if (!interactive) break;
920
+ candidate = suggestPort(v.port + 1, (p) => claimedPorts.includes(p) || portTakenSync(p));
921
+ line(info(`Suggesting ${candidate} instead.`));
922
+ }
923
+ return candidate;
924
+ })();
925
+ claimPort(roomsPort, 'the Rooms console');
926
+
927
+ // WHICH DAEMON. `undefined` means "leave whatever is there alone" — the answer for an
928
+ // existing embedded install nobody asked to migrate.
929
+ const wasEmbedded = coworkDaemonMode(existingRooms) === 'embedded';
930
+ const hadConfig = existsSync(cfgPath);
931
+ // Ask the BUILD, not the channel: this runs after the install above, so the version
932
+ // read here is the one actually on the machine.
933
+ const coworkVersion = globalVersion('@ours.network/cowork');
934
+ const externalSupported = coworkSupportsExternalDaemon(coworkVersion);
935
+ let roomsDaemon;
936
+ let roomsDaemonLabel;
937
+ if (!externalSupported) {
938
+ // The build we just installed predates cowork's external-daemon mode. Its config
939
+ // is a strict document and its boot fails closed, so writing a selection it cannot
940
+ // honour would break Rooms rather than degrade it.
941
+ line(info(`This Rooms build${coworkVersion ? ` (${coworkVersion})` : ''} hosts its own daemon; pointing it at the shared`));
942
+ line(info(`one needs ${COWORK_EXTERNAL_MIN_VERSION} or newer. Re-run with ${c.cyan('OURS_CHANNEL=nightly')} to get it.`));
943
+ roomsDaemonLabel = 'embedded';
944
+ } else if (hadConfig && wasEmbedded && !interactive) {
945
+ // Fail-closed boot makes this migration a real risk; never do it unasked.
946
+ line(info('Rooms already runs its own embedded daemon — leaving that alone.'));
947
+ line(info(`To point it at this install's daemon, re-run ${c.cyan('ours-install')} in a terminal.`));
948
+ roomsDaemonLabel = 'embedded (unchanged)';
949
+ } else {
950
+ line('');
951
+ const roomsMode = askDaemonMode('Rooms');
952
+ if (roomsMode === 'dedicated') {
953
+ const instance = DEDICATED_INSTANCES.rooms;
954
+ const suggested = suggestPort(chosenPort + 1, (p) => claimedPorts.includes(p) || portTakenSync(p));
955
+ const port = askDaemonPort('Which local port should the Rooms daemon use?', suggested);
956
+ claimPort(port, 'the dedicated Rooms daemon');
957
+ const provisioned = await provisionDedicatedDaemon({ instance, port, label: 'Rooms' });
958
+ roomsDaemon = { endpoint: provisioned.endpoint, stateDir: provisioned.stateDir };
959
+ roomsDaemonLabel = `dedicated daemon ${port}`;
960
+ } else {
961
+ roomsDaemon = { endpoint: daemonEndpoint(chosenPort), stateDir: daemonStateDir() };
962
+ roomsDaemonLabel = `common daemon ${chosenPort}`;
963
+ line(ok(`Rooms will use the shared daemon on port ${chosenPort}.`));
964
+ }
965
+ }
966
+
967
+ const roomsPlan = planCoworkConfig(existingRooms, {
968
+ brokerUrl: sharedBroker(),
969
+ stateDir: roomsStateDir,
970
+ restPort: roomsPort,
971
+ daemon: roomsDaemon,
972
+ });
973
+ if (roomsPlan.error) {
974
+ // Only reachable if a daemon selection lost half of itself; a half-written block
975
+ // would fail closed at cowork's boot, so refuse rather than write it.
976
+ line(warn(`not changing the Rooms daemon selection — ${roomsPlan.error}.`));
977
+ } else if (roomsPlan.changed) {
978
+ await act(`write ${cfgPath} (console port ${roomsPort}, state ${roomsStateDir}${roomsDaemon ? `, daemon ${roomsDaemon.endpoint}` : ''})`, async () => {
979
+ atomicWriteConfig(cfgPath, roomsPlan.text);
980
+ return { ok: true };
981
+ });
982
+ if (roomsDaemon) line(ok(`Rooms configured to use ${roomsDaemonLabel} (${roomsDaemon.endpoint}, state ${roomsDaemon.stateDir}).`));
983
+ } else {
984
+ line(ok(`Rooms is already configured for this deployment (console port ${roomsPort}) — no change.`));
985
+ }
986
+ const svc = await act('ours-cowork install-service (starts on boot)', async () => run('ours-cowork', ['install-service']));
987
+ if (svc.ok) {
988
+ line(ok(`Rooms ready — console at ${c.cyan(`http://127.0.0.1:${roomsPort}/`)}, sharing your broker. No problems.`));
989
+ } else {
990
+ line(warn(`Rooms installed, but its service didn't start — retry '${c.cyan('ours-cowork install-service')}'.`));
991
+ line(info(`You can also run it in the foreground: '${c.cyan('ours-cowork web')}'.`));
992
+ }
993
+ record({
994
+ key: 'rooms',
995
+ label: 'Rooms (ours-cowork)',
996
+ state: svc.ok ? 'installed' : 'failed',
997
+ version: coworkVersion,
998
+ note: svc.ok ? `console ${roomsPort} · ${roomsDaemonLabel}` : 'ours-cowork install-service failed',
999
+ });
1000
+ } else {
1001
+ line(info('skipped cleanly — re-run ours-install any time to add it.'));
1002
+ record({ key: 'rooms', label: 'Rooms (ours-cowork)', state: 'skipped' });
1003
+ }
1004
+ cont(goRooms);
1005
+
1006
+ // Last guard on the whole topology: no two daemons in this install may share a port.
1007
+ // Each answer was validated as it was given, but only the finished plan proves the set.
1008
+ const portPlan = planPorts(topology);
1009
+ if (!portPlan.ok) {
1010
+ for (const d of portPlan.duplicates) {
1011
+ line(warn(`port ${d.port} ended up claimed by both ${d.labels[0]} and ${d.labels[1]} — one of them will fail to bind.`));
1012
+ }
1013
+ }
1014
+
667
1015
  return endScreen({ ttyFd, summary, chosenPort, chosenBroker });
668
1016
  }
669
1017
 
@@ -742,7 +1090,9 @@ function endScreen({ ttyFd, summary, chosenPort, chosenBroker }) {
742
1090
  const has = (k) => summary.some((r) => r.key === k && (r.state === 'installed' || r.state === 'current'));
743
1091
  if (has('core')) {
744
1092
  const identityDone = has('identity');
745
- const { text, empty } = buildHandoffPrompt({ identity: !identityDone, fleet: has('fleet'), telegram: has('telegram') });
1093
+ const { text, empty } = buildHandoffPrompt({
1094
+ identity: !identityDone, fleet: has('fleet'), telegram: has('telegram'), rooms: has('rooms'),
1095
+ });
746
1096
  if (empty) {
747
1097
  // Nothing left to finish (identity created in-install, no fleet/Telegram). Don't show an empty box.
748
1098
  line('');