@ours.network/install 1.2.1-nightly.2 → 1.2.1-nightly.20

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 (46) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +337 -12
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +16 -12
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +21 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1111 -4265
  10. package/assets/release.json +33 -19
  11. package/assets/scripts/build/build-common.mjs +1 -1
  12. package/assets/scripts/build/build-sdk.mjs +6 -1
  13. package/assets/scripts/maintenance/build-context.mjs +1 -1
  14. package/assets/scripts/maintenance/daemon-owner.mjs +15 -0
  15. package/assets/scripts/maintenance/docker-layout-conversion.mjs +7 -3
  16. package/assets/scripts/maintenance/release-graph.mjs +18 -1
  17. package/assets/scripts/maintenance/state-operation.mjs +4 -2
  18. package/assets/scripts/runtime/client-setup.mjs +3 -3
  19. package/assets/scripts/runtime/entrypoint.sh +1 -1
  20. package/assets/scripts/runtime/legacy-import.mjs +103 -0
  21. package/assets/sources.json +46 -28
  22. package/install.mjs +5 -1
  23. package/lib/build-transition.mjs +1 -0
  24. package/lib/client-cli.mjs +127 -0
  25. package/lib/container-engine.mjs +127 -0
  26. package/lib/docker-conversion-runtime.mjs +3 -2
  27. package/lib/docker-layout-installation.mjs +2 -1
  28. package/lib/docker-runtime-repair.mjs +152 -0
  29. package/lib/effects.mjs +264 -125
  30. package/lib/gateway-transition.mjs +87 -0
  31. package/lib/gateway.mjs +142 -0
  32. package/lib/legacy-migration.mjs +213 -0
  33. package/lib/legacy-state.mjs +205 -0
  34. package/lib/managed-cli.mjs +164 -0
  35. package/lib/orchestrate.mjs +114 -38
  36. package/lib/plan.mjs +22 -9
  37. package/lib/podman-preflight.mjs +40 -0
  38. package/lib/prompt.mjs +113 -119
  39. package/lib/server-onboarding.mjs +63 -16
  40. package/lib/setup-options.mjs +137 -35
  41. package/lib/setup.mjs +30 -16
  42. package/lib/target.mjs +24 -8
  43. package/lib/uninstall.mjs +2 -2
  44. package/lib/usage.mjs +9 -4
  45. package/lib/workspace-setup.mjs +83 -0
  46. package/package.json +4 -2
package/lib/plan.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { validateContainerEngine } from './container-engine.mjs';
2
+ import { gatewayAddress } from './gateway.mjs';
1
3
  // ours-install v3 — daemon creation and boot-service installation.
2
4
  //
3
5
  // Pure planning code, like lib/target.mjs: the orchestrator
@@ -97,7 +99,7 @@ export function launchdLabelForStateDir(stateDir) {
97
99
  export function classifyUnit(text) {
98
100
  if (text === null || text === undefined) return { kind: 'absent' };
99
101
  const s = String(text);
100
- if (s.startsWith(CLI_UNIT_MARKER)) return { kind: 'cli-managed' };
102
+ if ((s.startsWith(CLI_UNIT_MARKER) || s.startsWith('# Managed by @ours.network/daemon'))) return { kind: 'cli-managed' };
101
103
  const looksLikeOursMcp = /ExecStart=.*\bours-mcp\b/.test(s)
102
104
  || /^Description=ours MCP daemon\b/m.test(s)
103
105
  || (/^Environment=OURS_STATE_DIR=/m.test(s) && /^Environment=OURS_TRANSPORT=http$/m.test(s));
@@ -138,7 +140,7 @@ export function planServiceInstall({ stateDir, home, readText, platform = 'linux
138
140
  platform,
139
141
  reason: 'no-service-manager',
140
142
  message: `installing a boot service is not available on ${platform} — the ours CLI supports Linux user systemd and macOS launchd`,
141
- manual: ['ours', 'daemon', 'serve', '--config'],
143
+ manual: ['ours-daemon', 'serve', '--config'],
142
144
  };
143
145
  }
144
146
 
@@ -224,7 +226,7 @@ export function serviceInstallCommand({ stateDir, adoptLegacyUnit = false }) {
224
226
  // --json so the caller can read back whether the unit actually CHANGED rather
225
227
  // than assuming it did. --force is reachable only through the explicit argument
226
228
  // above, and the CLI refuses to overwrite a unit it did not write.
227
- const cmd = ['ours', 'daemon', 'install-service', '--yes', '--json', '--state-dir', dir, '--config', join(dir, 'config.json')];
229
+ const cmd = ['ours-daemon', 'install-service', '--yes', '--json', '--state-dir', dir, '--config', join(dir, 'config.json')];
228
230
  if (adoptLegacyUnit) cmd.push('--force');
229
231
  return cmd;
230
232
  }
@@ -265,20 +267,20 @@ export function planDaemonSteps(target, { cliVersionChanged = false, cliStartedI
265
267
  const steps = [{ id: 'cli', label: 'install the ours-sdk CLI', command: ['npm', 'i', '-g', '@ours.network/cli'] }];
266
268
  steps.push({ id: 'config', label: `write ${join(dir, 'config.json')}`, port: target.port });
267
269
  if (target.action === 'create') {
268
- steps.push({ id: 'start', label: `start the daemon on port ${target.port}`, command: ['ours', 'daemon', 'start', '--config', join(dir, 'config.json')] });
270
+ steps.push({ id: 'start', label: `start the daemon on port ${target.port}`, command: ['ours-daemon', 'start', '--config', join(dir, 'config.json')] });
269
271
  } else if (cliVersionChanged) {
270
272
  // `ours daemon stop` refuses to signal a daemon it did not start, so a
271
273
  // daemon under another launcher is left running and the caller says which
272
274
  // launcher must be restarted instead.
273
275
  steps.push(cliStartedIt
274
- ? { id: 'restart', label: 'restart the daemon (package version changed)', command: ['ours', 'daemon', 'restart', '--config', join(dir, 'config.json')] }
276
+ ? { id: 'restart', label: 'restart the daemon (package version changed)', command: ['ours-daemon', 'restart', '--config', join(dir, 'config.json')] }
275
277
  : { id: 'restart-external', label: 'daemon was not started by the CLI — restart it with its own launcher', command: null });
276
278
  }
277
279
  steps.push({ id: 'service', label: 'install the boot service', command: serviceInstallCommand({ stateDir: dir }) });
278
280
  return steps;
279
281
  }
280
282
 
281
- export const SERVER_PACKAGES = ['sdk', 'cli', 'mcp', 'tg-connector', 'cowork', 'messenger-server'].map(n => `@ours.network/${n}`);
283
+ export const SERVER_PACKAGES = ['sdk', 'cli', 'daemon', 'tg-connector', 'cowork', 'messenger-server'].map(n => `@ours.network/${n}`);
282
284
  export const SERVER_DEPENDENCIES = {
283
285
  daemon: [], telegram: ['daemon'], cowork: ['daemon'], messenger: ['daemon'],
284
286
  };
@@ -356,15 +358,21 @@ export function installationPaths(record) {
356
358
  }
357
359
 
358
360
  export function validateInstallation(record, root) {
361
+ if (record) validateContainerEngine(record);
359
362
  if (!record || ![1, 2].includes(record.schema) || !['docker', 'packages'].includes(record.mode)
360
363
  || record.root !== root || record.configPath !== installationPaths(record).config
361
364
  || record.sourcesPath !== join(root, 'sources.json') || record.workDir !== join(root, 'runtime')
362
365
  || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(record.instanceId ?? '')
363
366
  || !/^ours-[a-z0-9]+$/.test(record.project ?? '')
364
367
  || (record.sourcePolicyHash !== undefined && !/^[0-9a-f]{64}$/.test(record.sourcePolicyHash))
365
- || !Array.isArray(record.services) || record.services[0] !== 'daemon' || new Set(record.services).size !== record.services.length || record.services.some(s => !SERVER_SERVICES.includes(s))) {
368
+ || !Array.isArray(record.services) || record.services[0] !== 'daemon' || new Set(record.services).size !== record.services.length || record.services.some(s => !SERVER_SERVICES.includes(s) && !(s === 'gateway' && record.gateway?.version === 1))) {
366
369
  throw new Error('Invalid or conflicting installation selection');
367
370
  }
371
+ if (record.gateway !== undefined && (record.schema !== 2 || record.mode !== 'docker' || record.gateway?.version !== 1
372
+ || Object.keys(record.gateway).some(key => !['version', 'serverUrl'].includes(key)) || record.services.at(-1) !== 'gateway')) {
373
+ throw new Error('Invalid gateway installation selection');
374
+ }
375
+ if (record.gateway) gatewayAddress(record);
368
376
  if (record.layoutConversion !== undefined) {
369
377
  // DEPRECATED (introduced in 2.0): legacy managed-layout conversion only.
370
378
  // Removal target: 3.0, after supported installs convert and upgrade inputs
@@ -380,7 +388,8 @@ export function validateInstallation(record, root) {
380
388
  throw new Error('Invalid layout conversion record');
381
389
  }
382
390
  validateInstallation(source, root);
383
- if (['mode', 'instanceId', 'project', 'sourcesPath', 'workDir'].some(key => source[key] !== record[key])
391
+ if (JSON.stringify(source.containerBinding) !== JSON.stringify(record.containerBinding)) throw new Error('Conflicting conversion backend');
392
+ if (['mode', 'containerEngine', 'instanceId', 'project', 'sourcesPath', 'workDir'].some(key => source[key] !== record[key])
384
393
  || JSON.stringify(source.services) !== JSON.stringify(record.services)
385
394
  || conversion.runningServices.some(service => !source.services.includes(service))) {
386
395
  throw new Error('Conflicting layout conversion source');
@@ -402,7 +411,7 @@ export function validateInstallation(record, root) {
402
411
  throw new Error('Invalid server build transition');
403
412
  }
404
413
  validateInstallation(candidate, candidate.root);
405
- for (const key of ['schema', 'mode', 'instanceId', 'services', 'port', 'coworkPort', 'messengerPort', 'messengerIdentity', 'uid', 'gid']) {
414
+ for (const key of ['schema', 'mode', 'containerEngine', 'containerBinding', 'instanceId', 'services', 'gateway', 'port', 'coworkPort', 'messengerPort', 'messengerIdentity', 'uid', 'gid']) {
406
415
  if (JSON.stringify(candidate[key]) !== JSON.stringify(record[key])) throw new Error('Conflicting server build candidate');
407
416
  }
408
417
  }
@@ -470,3 +479,7 @@ export function consumerServiceState(text, service, platform) {
470
479
  }
471
480
  return matches === 1 ? selected : undefined;
472
481
  }
482
+
483
+ export function clientPackageNames(integrations) {
484
+ return [...new Set(['sdk', 'cli', ...(integrations.some(name => ['codex', 'claude-code'].includes(name)) ? ['mcp'] : []), ...integrations])];
485
+ }
@@ -0,0 +1,40 @@
1
+ import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { tmpdir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { runContainer } from './container-engine.mjs';
6
+
7
+ export const PROBE_IMAGE = 'docker.io/library/nginx:1.28-alpine@sha256:a8b39bd9cf0f83869a2162827a0caf6137ddf759d50a171451b335cecc87d236';
8
+ /** Behavioral checks, in disposable resources, before touching installation storage. */
9
+ export async function qualifyPodman(effects, record) {
10
+ const root = mkdtempSync(join(tmpdir(), 'ours-podman-preflight-'));
11
+ const project = `ours-probe-${randomUUID()}`;
12
+ const file = join(root, 'compose.json'), overlay = join(root, 'reset.yaml');
13
+ const common = { image: PROBE_IMAGE, entrypoint: ['/bin/sh', '-ec'], read_only: true, cap_drop: ['ALL'], security_opt: ['no-new-privileges:true'] };
14
+ writeFileSync(file, JSON.stringify({ services: {
15
+ prepare: { ...common, user: '0:0', network_mode: 'none', cap_add: ['CHOWN', 'DAC_OVERRIDE'],
16
+ command: ['mkdir -p /storage/state/daemon /storage/state/sibling; chmod 700 /storage/state/daemon; chown 1000:1000 /storage/state/daemon'],
17
+ volumes: [{ type: 'volume', source: 'data', target: '/storage', volume: { nocopy: true } }] },
18
+ probe: { ...common, user: '1000:1000', command: ['test ! -e /data/sibling; test "$(stat -c %a /data)" = 700; nslookup -type=A probe.; echo ready > /data/probe; sleep 120'],
19
+ healthcheck: { test: ['CMD-SHELL', 'test -s /data/probe'], interval: '1s', timeout: '2s', retries: 10 },
20
+ volumes: [{ type: 'volume', source: 'data', target: '/data', volume: { nocopy: true, subpath: 'state/daemon' } }] },
21
+ }, volumes: { data: {} } }), { mode: 0o600 });
22
+ writeFileSync(overlay, 'services:\n probe:\n ports: !reset []\n', { mode: 0o600 });
23
+ const compose = args => runContainer(effects, record, ['compose', '-p', project, '-f', file, '-f', overlay, ...args], { timeout: 180000 });
24
+ try {
25
+ await compose(['config', '--format', 'json']);
26
+ await compose(['run', '--rm', '--no-deps', '-T', 'prepare']);
27
+ await compose(['up', '-d', '--no-build', '--wait', 'probe']);
28
+ const result = await compose(['ps', '--format', 'json']);
29
+ const rows = result.stdout.trim().startsWith('[') ? JSON.parse(result.stdout) : result.stdout.trim().split('\n').map(s => JSON.parse(s));
30
+ if (!rows.some(r => r.Service === 'probe' && r.State === 'running')) throw new Error('Compose JSON status is incompatible');
31
+ await compose(['exec', '-T', 'probe', '/bin/sh', '-ec', 'test -s /data/probe; test ! -e /data/state']);
32
+ } catch (cause) {
33
+ let logs = '';
34
+ try { logs = (await compose(['logs', '--no-color', '--tail', '30'])).stdout; } catch {}
35
+ throw new Error(`Podman capability check failed (Compose !reset/wait/status, DNS, rootless UID, volume subpath): ${cause.message}\n${logs}`, { cause });
36
+ } finally {
37
+ try { await compose(['down', '--volumes', '--remove-orphans']); }
38
+ finally { rmSync(root, { recursive: true, force: true }); }
39
+ }
40
+ }
package/lib/prompt.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  // Interactive prompts drawn on the controlling terminal (/dev/tty), so they work under
2
2
  // `curl | bash` (where stdin/stdout are the pipe). Synchronous, dependency-free: line prompts via
3
- // fs.readSync, and a raw-mode checkbox multi-select. When there is no tty or OURS_ASSUME_YES is
3
+ // fs.readSync, and raw-mode single/multiple choices. When there is no tty or OURS_ASSUME_YES is
4
4
  // set, every prompt returns its default without reading — the headless/CI path never blocks.
5
5
  import { readSync } from 'node:fs';
6
6
  import { spawnSync } from 'node:child_process';
@@ -30,77 +30,66 @@ function readByte(fd) {
30
30
  }
31
31
  }
32
32
 
33
- // askLine: print `prompt` and read a line. We read in RAW mode with signal generation OFF (stty
34
- // -icanon -echo -isig) so Ctrl+C arrives as the byte 0x03 that we turn into a clean InstallCancelled
35
- // — rather than a SIGINT that a blocked synchronous readSync would defer forever (the old
36
- // "^C^C^C… and keeps going" bug). We echo/backspace ourselves since -echo is off. If stty isn't
37
- // available (not a real tty), fall back to a plain cooked read. Throws InstallCancelled on Ctrl+C.
38
- export function askLine(write, fd, prompt, def = '') {
33
+ // Decode incrementally: a terminal read may split a UTF-8 code point across bytes.
34
+ // Fatal decoding rejects malformed input instead of storing a corrupted name or path.
35
+ function textEntry(write, fd, prompt, def, secret, {
36
+ read = readByte, enterRaw = enterSelectionMode,
37
+ } = {}) {
39
38
  if (fd == null || ASSUME_YES()) return def;
40
- write(prompt);
41
-
42
- const saved = spawnSync('stty', ['-g'], { stdio: [fd, 'pipe', 'ignore'], encoding: 'utf8' });
43
- const rawOk = saved.status === 0
44
- && spawnSync('stty', ['-icanon', '-echo', '-isig', 'min', '1', 'time', '0'], { stdio: [fd, 'ignore', 'ignore'] }).status === 0;
45
- const restore = () => { if (rawOk) spawnSync('stty', (saved.stdout || '').trim() ? [(saved.stdout || '').trim()] : ['sane'], { stdio: [fd, 'ignore', 'ignore'] }); };
46
-
47
- let s = '';
39
+ let restore;
40
+ try { restore = enterRaw(fd); } catch (error) {
41
+ // A secret must never fall back to an echoing cooked terminal.
42
+ if (secret && isCancel(error)) { write(`${prompt}\n`); return null; }
43
+ throw error;
44
+ }
45
+ let decoder = new TextDecoder('utf-8', { fatal: true });
46
+ let pending = false;
47
+ const characters = [];
48
48
  try {
49
+ write(prompt);
49
50
  for (;;) {
50
- const b = readByte(fd);
51
- if (b === null || b === 0x04) break; // EOF / Ctrl+D → take the default
52
- if (b === 0x03) { restore(); write('^C'); throw new InstallCancelled(); } // Ctrl+C
53
- if (b === 0x0a || b === 0x0d) { if (rawOk) write('\n'); break; } // Enter
54
- if (b === 0x7f || b === 0x08) { if (s.length) { s = s.slice(0, -1); if (rawOk) write('\b \b'); } continue; } // backspace
55
- if (b < 0x20) continue; // ignore other control bytes
56
- s += String.fromCharCode(b);
57
- if (rawOk) write(String.fromCharCode(b)); // manual echo
51
+ const byte = read(fd);
52
+ if (byte == null || byte === 0x03 || byte === 0x04) throw new InstallCancelled();
53
+ if (byte === 0x7f || byte === 0x08) {
54
+ if (pending) {
55
+ decoder = new TextDecoder('utf-8', { fatal: true });
56
+ pending = false;
57
+ } else if (characters.length) {
58
+ characters.pop();
59
+ if (!secret) write('\b \b');
60
+ }
61
+ continue;
62
+ }
63
+ if (byte === 0x0a || byte === 0x0d) {
64
+ try { decoder.decode(); } catch { throw new InstallCancelled(); }
65
+ write('\n');
66
+ const answer = characters.join('').trim();
67
+ return answer === '' ? def : answer;
68
+ }
69
+ if (byte < 0x20) {
70
+ if (pending) throw new InstallCancelled();
71
+ continue;
72
+ }
73
+ let decoded;
74
+ try { decoded = decoder.decode(Uint8Array.of(byte), { stream: true }); }
75
+ catch { throw new InstallCancelled(); }
76
+ pending = decoded.length === 0;
77
+ for (const character of decoded) {
78
+ characters.push(character);
79
+ if (!secret) write(character);
80
+ }
58
81
  }
59
82
  } finally {
60
83
  restore();
61
84
  }
62
- const ans = s.trim();
63
- return ans === '' ? def : ans;
64
85
  }
65
86
 
66
- // Secret variant of askLine: identical cancellation/backspace/default semantics, but typed
67
- // characters are never echoed (not even as placeholder stars). This keeps provider keys out of
68
- // terminal scrollback, curl|bash output, and captured CI logs.
69
- export function askSecret(write, fd, prompt, def = '') {
70
- if (fd == null || ASSUME_YES()) return def;
71
-
72
- const saved = spawnSync('stty', ['-g'], { stdio: [fd, 'pipe', 'ignore'], encoding: 'utf8' });
73
- const rawOk = saved.status === 0
74
- && spawnSync('stty', ['-icanon', '-echo', '-isig', 'min', '1', 'time', '0'], { stdio: [fd, 'ignore', 'ignore'] }).status === 0;
75
- const restore = () => {
76
- if (rawOk) spawnSync('stty', (saved.stdout || '').trim() ? [(saved.stdout || '').trim()] : ['sane'], { stdio: [fd, 'ignore', 'ignore'] });
77
- };
78
- if (!rawOk) {
79
- // Fail closed: a cooked fallback would echo the secret. Returning null lets the caller
80
- // explain that secure input is unavailable without ever reading a credential.
81
- write(`${prompt}\n`);
82
- return null;
83
- }
84
- // Disable echo BEFORE displaying the prompt. Otherwise an automated or very fast typist can
85
- // submit bytes in the small prompt→stty window and have the terminal driver echo the secret.
86
- write(prompt);
87
+ export function askLine(write, fd, prompt, def = '', controls) {
88
+ return textEntry(write, fd, prompt, def, false, controls);
89
+ }
87
90
 
88
- let s = '';
89
- try {
90
- for (;;) {
91
- const b = readByte(fd);
92
- if (b === null || b === 0x04) break;
93
- if (b === 0x03) { restore(); write('^C'); throw new InstallCancelled(); }
94
- if (b === 0x0a || b === 0x0d) { write('\n'); break; }
95
- if (b === 0x7f || b === 0x08) { if (s.length) s = s.slice(0, -1); continue; }
96
- if (b < 0x20) continue;
97
- s += String.fromCharCode(b);
98
- }
99
- } finally {
100
- restore();
101
- }
102
- const ans = s.trim();
103
- return ans === '' ? def : ans;
91
+ export function askSecret(write, fd, prompt, def = '', controls) {
92
+ return textEntry(write, fd, prompt, def, true, controls);
104
93
  }
105
94
 
106
95
  // askYesNo: y/n with a default shown in caps. Returns boolean.
@@ -111,69 +100,74 @@ export function askYesNo(write, fd, prompt, def = false) {
111
100
  return /^y/i.test(ans);
112
101
  }
113
102
 
114
- // checkboxSelect: raw-mode multi-select drawn on the tty. ↑/↓ (or k/j) move, Space toggles, Enter
115
- // confirms, a/n = all/none, q cancels (selects nothing). Returns the selected names in order.
116
- // `specs` are { name, label } (optionally { checked }). No-tty → returns pre-checked defaults.
117
- export function checkboxSelect(write, fd, specs, { title } = {}) {
118
- const names = specs.map((s) => s.name);
119
- const labels = specs.map((s) => s.label);
120
- const sel = specs.map((s) => (s.checked ? 1 : 0));
121
- const n = specs.length;
122
- const chosen = () => names.filter((_, i) => sel[i] === 1);
123
-
124
- if (fd == null) return chosen();
125
-
126
- // Enter raw mode via `stty` on the tty fd (NOT tty.ReadStream.setRawMode, which would flip the
127
- // fd to non-blocking and break our fs.readSync). Save the current settings and restore them
128
- // after. If stty is unavailable / this isn't a real tty, fall back to the pre-checked defaults.
103
+ // Keep terminal controls injectable so key sequences and cleanup can be checked without a TTY.
104
+ function enterSelectionMode(fd) {
129
105
  const saved = spawnSync('stty', ['-g'], { stdio: [fd, 'pipe', 'ignore'], encoding: 'utf8' });
130
- if (saved.status !== 0) return chosen();
131
- const savedMode = (saved.stdout || '').trim();
132
- const setRaw = spawnSync('stty', ['-echo', '-icanon', 'min', '1', 'time', '0'], { stdio: [fd, 'ignore', 'ignore'] });
133
- if (setRaw.status !== 0) return chosen();
134
- const restore = () => spawnSync('stty', savedMode ? [savedMode] : ['sane'], { stdio: [fd, 'ignore', 'ignore'] });
135
-
136
- let cur = 0;
137
- let drawn = 0;
106
+ if (saved.status !== 0 || !saved.stdout?.trim()) throw new InstallCancelled();
107
+ const restore = () => spawnSync('stty', [saved.stdout.trim()], { stdio: [fd, 'ignore', 'ignore'] });
108
+ const raw = spawnSync('stty', ['-echo', '-icanon', '-isig', 'min', '1', 'time', '0'], { stdio: [fd, 'ignore', 'ignore'] });
109
+ if (raw.status !== 0) { restore(); throw new InstallCancelled(); }
110
+ return restore;
111
+ }
138
112
 
113
+ function choose(write, fd, question, choices, defaults, multiple, {
114
+ read = readByte, enterRaw = enterSelectionMode,
115
+ } = {}) {
116
+ if (!choices.length) throw new Error('A choice prompt requires at least one choice');
117
+ const selected = choices.map(choice => defaults.includes(choice.value));
118
+ let current = Math.max(0, selected.indexOf(true));
119
+ const result = () => multiple
120
+ ? choices.filter((_, i) => selected[i]).map(choice => choice.value)
121
+ : choices[current].value;
122
+ if (fd == null || ASSUME_YES()) return result();
123
+ const restore = enterRaw(fd);
124
+ let drawn = false;
125
+ const next = () => {
126
+ const byte = read(fd);
127
+ if (byte == null || byte === 0x03 || byte === 0x04) throw new InstallCancelled();
128
+ return byte;
129
+ };
139
130
  const redraw = () => {
140
- if (drawn) write(`\x1b[${n}A`); // rewind over the previous frame
141
- drawn = 1;
142
- for (let i = 0; i < n; i++) {
143
- const box = sel[i] ? c.green('[x]') : '[ ]';
144
- const point = i === cur ? c.cyan('> ') : ' ';
145
- write(`\r\x1b[K ${point}${box} ${labels[i]}\n`);
146
- }
131
+ if (drawn) write(`\x1b[${choices.length}A`);
132
+ drawn = true;
133
+ choices.forEach((choice, i) => {
134
+ const marker = multiple ? (selected[i] ? c.green('[x]') : '[ ]') : (i === current ? c.green('(●)') : '( )');
135
+ write(`\r\x1b[K ${i === current ? c.cyan('> ') : ' '}${marker} ${choice.label}\n`);
136
+ });
147
137
  };
148
-
149
- write(` ${title || 'Choose — ' + c.bold('↑/↓') + ' move, ' + c.bold('Space') + ' toggle, ' + c.bold('Enter') + ' confirm (a=all, n=none)'}:\n`);
150
- redraw();
151
-
152
- loop: for (;;) {
153
- const b = readByte(fd);
154
- if (b === null) break;
155
- switch (b) {
156
- case 0x1b: { // ESC — arrow key sequence \x1b [ A/B
157
- const b1 = readByte(fd);
158
- if (b1 === 0x5b || b1 === 0x4f) { // '[' or 'O'
159
- const b2 = readByte(fd);
160
- if (b2 === 0x41) cur = (cur - 1 + n) % n; // up
161
- else if (b2 === 0x42) cur = (cur + 1) % n; // down
138
+ try {
139
+ write(`\x1b[?25l ${question}\n ${c.bold('↑/↓')} move${multiple ? ', ' + c.bold('Space') + ' toggle' : ''}, ${c.bold('Enter')} confirm\n`);
140
+ redraw();
141
+ for (;;) {
142
+ const byte = next();
143
+ if (byte === 0x0d || byte === 0x0a) return result();
144
+ if (byte === 0x1b) {
145
+ const prefix = next();
146
+ if (prefix === 0x5b || prefix === 0x4f) {
147
+ const direction = next();
148
+ if (direction === 0x41) current = (current - 1 + choices.length) % choices.length;
149
+ if (direction === 0x42) current = (current + 1) % choices.length;
162
150
  }
163
- break;
164
- }
165
- case 0x6b: case 0x4b: cur = (cur - 1 + n) % n; break; // k/K
166
- case 0x6a: case 0x4a: cur = (cur + 1) % n; break; // j/J
167
- case 0x20: sel[cur] = 1 - sel[cur]; break; // space
168
- case 0x61: case 0x41: for (let i = 0; i < n; i++) sel[i] = 1; break; // a/A
169
- case 0x6e: case 0x4e: for (let i = 0; i < n; i++) sel[i] = 0; break; // n/N
170
- case 0x71: case 0x51: for (let i = 0; i < n; i++) sel[i] = 0; break loop; // q/Q cancel
171
- case 0x0d: case 0x0a: break loop; // enter
172
- default: break;
151
+ } else if (multiple && byte === 0x20) selected[current] = !selected[current];
152
+ redraw();
173
153
  }
174
- redraw();
154
+ } finally {
155
+ try { restore(); } finally { write('\x1b[?25h'); }
175
156
  }
157
+ }
176
158
 
177
- restore();
178
- return chosen();
159
+ export function select(write, fd, question, choices, defaultValue, controls) {
160
+ return choose(write, fd, question, choices, [defaultValue], false, controls);
161
+ }
162
+
163
+ export function multiselect(write, fd, question, choices, defaults = [], controls) {
164
+ return choose(write, fd, question, choices, defaults, true, controls);
165
+ }
166
+
167
+ // Preserve the existing component selection API using the same keyboard implementation.
168
+ export function checkboxSelect(write, fd, specs, { title } = {}) {
169
+ if (!specs.length) return [];
170
+ return multiselect(write, fd, title || 'Choose components',
171
+ specs.map(({ name, label }) => ({ value: name, label })),
172
+ specs.filter(spec => spec.checked).map(spec => spec.name));
179
173
  }
@@ -1,3 +1,4 @@
1
+ import { gatewayAddress } from './gateway.mjs';
1
2
  /** Human bootstrap and local client handoff through the existing owner interfaces. */
2
3
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { join, resolve, isAbsolute } from 'node:path';
@@ -28,16 +29,56 @@ function validateRecord(record) {
28
29
  }
29
30
 
30
31
  export function createServerOnboarding(effects, { compose, localEnv, bin }) {
31
- async function identityCommand(record, args) {
32
- const result = record.mode === 'docker'
33
- ? await compose(record, ['exec', '-T', 'daemon', 'node', '/opt/ours/node_modules/@ours.network/cli/dist/cli.js', ...args, '--config', '/var/lib/ours/config.json', '--state-dir', '/var/lib/ours', '--json'])
34
- : await effects.run(bin(record, 'ours'), [...args, '--config', record.configPath, '--state-dir', installationPaths(record).daemon, '--json'], { env: localEnv(record) });
32
+ // CLI client commands only accept gateway profiles in current releases. Use
33
+ // the installed SDK against the selected local daemon and its private file.
34
+ const identityScript = `
35
+ import { createRequire } from 'node:module';
36
+ import { pathToFileURL } from 'node:url';
37
+ import { randomUUID } from 'node:crypto';
38
+ const selection = JSON.parse(process.argv[1]);
39
+ const require = createRequire(selection.anchor);
40
+ const { attachOursClient } = await import(pathToFileURL(require.resolve('@ours.network/sdk/client')).href);
41
+ const client = await attachOursClient({ endpoint: selection.endpoint,
42
+ expectedInstanceId: selection.instanceId, credentialPath: selection.credentialPath,
43
+ sessionMode: 'external', leaseToken: randomUUID(), env: {} });
44
+ try {
45
+ const result = selection.operation === 'list' ? await client.listIdentities()
46
+ : await client.createRootIdentity({ name: selection.name, bio: '',
47
+ exposeLocal: true, localAutoAccept: true, skipIfRootExists: true });
48
+ process.stdout.write(JSON.stringify(result));
49
+ } catch (error) {
50
+ process.stdout.write(JSON.stringify({ onboardingError: error.code || 'OWNER_OPERATION_FAILED' }));
51
+ } finally {
52
+ try { await client.releaseLease(); } finally { await client.close(); }
53
+ }
54
+ `;
55
+ async function identityCommand(record, operation, name) {
56
+ validateRecord(record);
57
+ const docker = record.mode === 'docker';
58
+ const selection = {
59
+ operation, ...(name === undefined ? {} : { name }),
60
+ endpoint: `http://127.0.0.1:${docker ? 3050 : record.port}`,
61
+ instanceId: record.instanceId,
62
+ credentialPath: docker ? '/var/lib/ours/daemon-token' : join(installationPaths(record).daemon, 'daemon-token'),
63
+ anchor: docker ? '/opt/ours/package.json' : join(record.workDir, 'package.json'),
64
+ };
65
+ const args = ['--input-type=module', '-e', identityScript, JSON.stringify(selection)];
66
+ const result = docker
67
+ ? await compose(record, ['exec', '-T', 'daemon', 'node', ...args])
68
+ : await effects.run(process.execPath, args, { env: localEnv(record), sensitive: true });
35
69
  if (result.code !== undefined && result.code !== 0) throw new Error('Owner identity operation failed');
36
- try { return JSON.parse(result.stdout); }
70
+ let value;
71
+ try { value = JSON.parse(result.stdout); }
37
72
  catch { throw new Error('Owner identity operation returned malformed JSON'); }
73
+ if (value?.onboardingError) {
74
+ const error = new Error('Owner identity operation failed');
75
+ error.code = value.onboardingError;
76
+ throw error;
77
+ }
78
+ return value;
38
79
  }
39
80
  async function identities(record) {
40
- const rows = await identityCommand(record, ['identity', 'list']);
81
+ const rows = await identityCommand(record, 'list');
41
82
  if (!Array.isArray(rows) || rows.some(row => !row || typeof row.name !== 'string'
42
83
  || (!['root', 'role'].includes(row.kind) && !['reconciling', 'awaiting-root', 'migration-failed', 'refresh-failed'].includes(row.status))
43
84
  || (row.kind && (typeof row.cid !== 'string' || !row.cid)))) throw new Error('Owner identity list is malformed');
@@ -50,6 +91,7 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
50
91
  return { name: root.name, cid: root.cid, created: false };
51
92
  }
52
93
  return {
94
+ async serverListIdentities(record) { return (await identities(record)).rows; },
53
95
  async serverEnsureIdentity(record, name) {
54
96
  validateRecord(record);
55
97
  validateIdentityName(name);
@@ -58,10 +100,11 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
58
100
  if (prior.rows.some(row => row.name === name)) throw new Error('Requested Human identity name already exists; no identity was changed');
59
101
  effects.out?.(`Creating Human identity ${name}; retaining ${prior.rows.length} existing identities.`);
60
102
  try {
61
- await identityCommand(record, ['identity', 'create-root', '--name', name, '--skip-if-root-exists', 'true']);
103
+ await identityCommand(record, 'create-root', name);
62
104
  } catch (error) {
63
- // ROOT_EXISTS is currently a CLI error. A concurrent creator is safe only
105
+ // A concurrent creator is safe only
64
106
  // when the authoritative list now contains a root; other errors stay errors.
107
+ if (error.code !== 'ROOT_EXISTS') throw error;
65
108
  const after = await identities(record);
66
109
  if (after.root) return retained(after);
67
110
  throw error;
@@ -74,14 +117,15 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
74
117
  },
75
118
  async prepareLocalClient(record, integrations, fleetSettingsPath) {
76
119
  validateRecord(record);
77
- if (!Array.isArray(integrations) || !integrations.length || new Set(integrations).size !== integrations.length
120
+ if (!Array.isArray(integrations) || new Set(integrations).size !== integrations.length
78
121
  || integrations.some(name => !['codex', 'claude-code', 'fleet'].includes(name))) throw new Error('Client integrations must select codex, claude-code and/or fleet');
79
122
  if (fleetSettingsPath !== undefined) {
80
123
  if (typeof fleetSettingsPath !== 'string' || !isAbsolute(fleetSettingsPath) || resolve(fleetSettingsPath) !== fleetSettingsPath) throw new Error('Fleet settings path must be absolute');
81
124
  const settings = JSON.parse(readFileSync(fleetSettingsPath, 'utf8'));
82
125
  if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('Fleet settings must be a JSON object');
83
126
  }
84
- const endpoint = `http://127.0.0.1:${record.port}`;
127
+ const serverUrl = record.gateway ? gatewayAddress(record).base : undefined;
128
+ const endpoint = serverUrl ? `${serverUrl}/daemon` : `http://127.0.0.1:${record.port}`;
85
129
  const current = effects.readManagedClientProfile();
86
130
  if (current && (current.endpoint !== endpoint || current.expectedInstanceId !== record.instanceId)) throw new Error('Managed client already selects another server; no credential was issued');
87
131
  privatePath(record.root, true);
@@ -92,13 +136,16 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
92
136
  const published = join(root, 'issued-' + randomUUID());
93
137
  const credential = join(stage, 'credential');
94
138
  try {
95
- effects.out?.('Issuing a separate local client credential with the retained server authority.');
96
- try { await effects.serverAccess(record, 'access-issue', { output: credential }); }
97
- catch { throw new Error('Client credential issuance failed; existing profiles were retained'); }
98
- const stat = privatePath(credential);
99
- if (stat.size > 4096 || !readFileSync(credential, 'utf8').trim()) throw new Error('Issued client credential is empty or invalid');
139
+ if (!current) {
140
+ effects.out?.('Issuing a separate local client credential with the retained server authority.');
141
+ try { await effects.serverAccess(record, 'access-issue', { output: credential }); }
142
+ catch { throw new Error('Client credential issuance failed; existing profiles were retained'); }
143
+ }
144
+ const retainedCredential = current?.credentialPath ?? credential;
145
+ const stat = privatePath(retainedCredential);
146
+ if (stat.size > 4096 || !readFileSync(retainedCredential, 'utf8').trim()) throw new Error('Issued client credential is empty or invalid');
100
147
  const profile = {
101
- ...validateHostProfile({ endpoint, expectedInstanceId: record.instanceId, credentialPath: join(published, 'credential') }),
148
+ ...validateHostProfile({ ...(serverUrl ? { serverUrl } : {}), endpoint, expectedInstanceId: record.instanceId, credentialPath: current?.credentialPath ?? join(published, 'credential') }),
102
149
  installer: { integrations: [...integrations], ...(fleetSettingsPath !== undefined ? { fleetSettingsPath } : {}) },
103
150
  };
104
151
  writeFileSync(join(stage, 'profile.json'), JSON.stringify(profile, null, 2) + '\n', { flag: 'wx', mode: 0o600 });