@ours.network/install 2.1.4 → 2.1.7

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.
@@ -1,7 +1,10 @@
1
1
  import { hostname } from 'node:os';
2
2
  import { serverBase } from './gateway.mjs';
3
- import { join, resolve, isAbsolute, dirname } from 'node:path';
3
+ import { join, resolve } from 'node:path';
4
4
  import { PRODUCTS, PLUGIN_ONLY, PLUGIN_ONLY_INTEGRATIONS } from './product.mjs';
5
+ import { MIGRATE_FROM_UNSUPPORTED, refuseOldLayout } from './plan.mjs';
6
+ import { InstallUsageError } from './target.mjs';
7
+ import { heading, info, warn } from './ui.mjs';
5
8
 
6
9
  const scopes = ['all', 'server', 'client'];
7
10
  const integrations = ['codex', 'claude-code', 'fleet'];
@@ -9,12 +12,12 @@ const valueFlags = new Map(Object.entries({
9
12
  '--container-engine': 'containerEngine', '--server-url': 'serverUrl', '--scope': 'scope', '--action': 'operation', '--mode': 'mode', '--state-dir': 'stateDir',
10
13
  '--username': 'localUsername', '--name': 'name', '--surname': 'surname', '--hostname': 'hostname',
11
14
  '--identity-name': 'identityName', '--integrations': 'integrations', '--fleet-settings': 'fleetSettingsPath', '--fleet-task-workflow': 'fleetTaskWorkflowAgents',
12
- '--config': 'config', '--sources': 'sources', '--migrate-from': 'migrateFrom', '--port': 'port', '--cowork-port': 'coworkPort', '--messenger-port': 'messengerPort',
15
+ '--config': 'config', '--sources': 'sources', '--port': 'port', '--cowork-port': 'coworkPort', '--messenger-port': 'messengerPort',
13
16
  }));
14
17
  const boolFlags = new Map([['--compatible', 'compatible'], ['--dry-run', 'dryRun'], ['--migrate', 'migrate'], ['--disable-fleet-agents-setup', 'disableFleetAgentsSetup']]);
15
18
  const allowed = new Set([...valueFlags.values(), ...boolFlags.values(), 'interactive', 'explicitPorts', 'product']);
16
19
  const defaults = { port: 3050, coworkPort: 3052, messengerPort: 8420 };
17
- const paths = ['stateDir', 'config', 'sources', 'fleetSettingsPath', 'migrateFrom'];
20
+ const paths = ['stateDir', 'config', 'sources', 'fleetSettingsPath'];
18
21
  const nonempty = value => typeof value === 'string' && value.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(value);
19
22
 
20
23
  export function recommendedMode({ platform, arch, release = '' } = {}) {
@@ -27,14 +30,13 @@ export function recommendedMode({ platform, arch, release = '' } = {}) {
27
30
 
28
31
  export function validateSetupOptions(input, { interactive = input?.interactive === true } = {}) {
29
32
  if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('Setup options must be an object');
33
+ if (input.migrateFrom !== undefined) throw new InstallUsageError(MIGRATE_FROM_UNSUPPORTED);
30
34
  for (const key of Object.keys(input)) if (!allowed.has(key)) throw new Error(`Unknown setup option: ${key}`);
31
35
  const options = { ...input, scope: input.scope ?? 'all', operation: input.operation ?? 'install', interactive };
32
36
  if (!scopes.includes(options.scope)) throw new Error('Scope must be all, server, or client');
33
37
  if (!['install', 'update'].includes(options.operation)) throw new Error('Operation must be install or update');
34
38
  const server = options.scope !== 'client';
35
39
  const client = options.scope !== 'server';
36
- if (options.migrateFrom !== undefined && (!server || options.operation !== 'install')) throw new Error('--migrate-from requires server or all scope and operation install');
37
- if (options.migrateFrom !== undefined && (!nonempty(options.migrateFrom) || !isAbsolute(options.migrateFrom))) throw new Error('--migrate-from requires an absolute daemon config path');
38
40
  const suppliedHuman = ['localUsername', 'name', 'surname'].some(key => options[key] !== undefined);
39
41
  if (suppliedHuman) {
40
42
  for (const key of ['localUsername', 'name', 'surname']) if (!nonempty(options[key])) throw new Error(`Missing human profile option: ${key}`);
@@ -50,8 +52,8 @@ export function validateSetupOptions(input, { interactive = input?.interactive =
50
52
  options.hostname = options.hostname?.trim() || defaultHostname();
51
53
  if (!/^[a-z0-9][a-z0-9-]{0,29}$/.test(options.hostname)) throw new Error('Hostname must contain 1–30 lowercase letters, digits or hyphens');
52
54
  const identity = `${options.localUsername}@${options.hostname}`;
53
- if (options.migrateFrom === undefined && options.identityName !== undefined && options.identityName !== identity) throw new Error('--identity-name conflicts with username and hostname');
54
- if (options.migrateFrom === undefined) options.identityName = identity;
55
+ if (options.identityName !== undefined && options.identityName !== identity) throw new Error('--identity-name conflicts with username and hostname');
56
+ options.identityName = identity;
55
57
  } else if (options.hostname !== undefined) throw new Error('--hostname requires username, name and surname');
56
58
  if (options.disableFleetAgentsSetup !== undefined && typeof options.disableFleetAgentsSetup !== 'boolean') throw new Error('disableFleetAgentsSetup must be a boolean');
57
59
  if (options.disableFleetAgentsSetup && options.fleetSettingsPath) throw new Error('--disable-fleet-agents-setup conflicts with --fleet-settings');
@@ -71,7 +73,7 @@ export function validateSetupOptions(input, { interactive = input?.interactive =
71
73
  if (options.mode !== undefined && !['docker'].includes(options.mode)) throw new Error('--plugin-only runs the daemon in Docker or Podman; native packages are not supported for it');
72
74
  if (options.integrations?.some?.(name => !PLUGIN_ONLY_INTEGRATIONS.includes(name))) throw new Error('--plugin-only connects Claude Code and/or Codex; Fleet is part of the complete workspace');
73
75
  for (const [key, flag] of [['fleetSettingsPath', '--fleet-settings'], ['fleetTaskWorkflowAgents', '--fleet-task-workflow'], ['disableFleetAgentsSetup', '--disable-fleet-agents-setup'],
74
- ['name', '--name'], ['surname', '--surname'], ['migrateFrom', '--migrate-from'], ['serverUrl', '--server-url']]) {
76
+ ['name', '--name'], ['surname', '--surname'], ['serverUrl', '--server-url']]) {
75
77
  if (options[key] !== undefined && options[key] !== false) throw new Error(`${flag} belongs to the complete workspace and cannot be combined with --plugin-only`);
76
78
  }
77
79
  if (options.explicitPorts?.some?.(key => key !== 'port')) throw new Error('--plugin-only uses one port; --cowork-port and --messenger-port do not apply');
@@ -79,10 +81,10 @@ export function validateSetupOptions(input, { interactive = input?.interactive =
79
81
  }
80
82
  }
81
83
  const missing = [];
82
- if (server) for (const [key, flag] of [['mode', '--mode'], ['stateDir', '--state-dir'], ...(options.migrateFrom === undefined ? [['identityName', '--identity-name']] : [])]) if (!nonempty(options[key])) missing.push(flag);
84
+ if (server) for (const [key, flag] of [['mode', '--mode'], ['stateDir', '--state-dir'], ['identityName', '--identity-name']]) if (!nonempty(options[key])) missing.push(flag);
83
85
  if (client && options.integrations === undefined) missing.push('--integrations (use none to skip)');
84
86
  if (!server && !nonempty(options.config)) missing.push('--config');
85
- if (server && (options.operation === 'update' || options.migrateFrom !== undefined) && options.compatible !== true) missing.push('--compatible');
87
+ if (server && options.operation === 'update' && options.compatible !== true) missing.push('--compatible');
86
88
  if (Array.isArray(options.integrations) && options.integrations.includes('fleet') && !interactive && !options.disableFleetAgentsSetup && !nonempty(options.fleetSettingsPath)) missing.push('--fleet-settings');
87
89
  if (missing.length) throw new Error(`Missing required setup options: ${missing.join(', ')}`);
88
90
  if (options.mode === 'native') options.mode = 'packages';
@@ -128,10 +130,7 @@ function expandPaths(options, home) {
128
130
  if (value === '~' || value.startsWith('~/')) {
129
131
  if (!nonempty(home)) throw new Error('Home directory is required to expand ~/ paths');
130
132
  output[key] = resolve(home, value === '~' ? '' : value.slice(2));
131
- } else {
132
- if (key === 'migrateFrom' && !isAbsolute(value)) throw new Error('--migrate-from requires an absolute daemon config path');
133
- output[key] = resolve(value);
134
- }
133
+ } else output[key] = resolve(value);
135
134
  }
136
135
  return output;
137
136
  }
@@ -158,6 +157,7 @@ export function parseSetupArgs(argv, { home, validate = true } = {}) {
158
157
  if (equal >= 0) throw new Error(`${flag} takes no value`);
159
158
  put(boolFlags.get(flag), true); continue;
160
159
  }
160
+ if (flag === '--migrate-from') throw new InstallUsageError(MIGRATE_FROM_UNSUPPORTED);
161
161
  if (!valueFlags.has(flag)) throw new Error(`Unknown setup flag: ${flag}`);
162
162
  const value = equal < 0 ? argv[++i] : arg.slice(equal + 1);
163
163
  if (!nonempty(value) || value.startsWith('--')) throw new Error(`${flag} requires a value`);
@@ -179,6 +179,92 @@ export function defaultHostname() {
179
179
  return hostname().toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 30) || 'workspace';
180
180
  }
181
181
 
182
+ const personText = /[\\/\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u;
183
+ const personPart = value => nonempty(value) && value.trim().length <= 100 && !personText.test(value.trim());
184
+ const profileChecks = {
185
+ localUsername: value => /^[a-z0-9][a-z0-9-]{0,29}$/.test(value),
186
+ name: personPart, surname: personPart,
187
+ hostname: value => value === '' || /^[a-z0-9][a-z0-9-]{0,29}$/.test(value.trim()),
188
+ };
189
+ // The same joined-name rule validateSetupOptions applies.
190
+ const personValid = (name, surname) => {
191
+ const person = `${name.trim()} ${surname.trim()}`;
192
+ return [...person].length <= 64 && person === person.normalize('NFC') && !personText.test(person);
193
+ };
194
+
195
+ // Valid supplied profile values are used silently; only missing or invalid ones are asked.
196
+ async function collectProfile(effects, options) {
197
+ const fields = [
198
+ ['localUsername', 'Local username: ', () => (effects.username?.() ?? 'me').toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 30)],
199
+ ['name', 'Name: ', () => ''], ['surname', 'Surname: ', () => ''], ['hostname', 'Host / machine name (optional): ', () => ''],
200
+ ];
201
+ const valid = key => typeof options[key] === 'string' && profileChecks[key](options[key]);
202
+ const joined = () => !valid('name') || !valid('surname') || personValid(options.name, options.surname);
203
+ fields.splice(0, fields.length, ...fields.filter(([key]) => !valid(key) || (!joined() && (key === 'name' || key === 'surname'))));
204
+ if (!fields.length) return;
205
+ const invalid = fields.filter(([key]) => options[key] !== undefined).map(([key]) => key);
206
+ effects.out(invalid.length ? warn(`Not valid: ${invalid.map(key => ({ localUsername: 'Local username', name: 'Name', surname: 'Surname', hostname: 'Host name' })[key]).join(', ')}. Please enter again.`) : info('Your Ours identity: Name and Surname appear in Messenger.'));
207
+ for (const [key, question, fallback] of fields) {
208
+ for (let attempt = 1; ; attempt++) {
209
+ const value = await effects.askLine(question, fallback());
210
+ if (profileChecks[key](value) && (key !== 'surname' || personValid(options.name, value))) { options[key] = value; break; }
211
+ if (attempt === 3) throw new Error(`Invalid ${key}; nothing was changed`);
212
+ effects.out(warn(key === 'localUsername' || key === 'hostname' ? 'Use 1–30 lowercase letters, digits or hyphens.'
213
+ : 'Use up to 64 characters for Name and Surname together, without slashes or control characters.'));
214
+ }
215
+ }
216
+ }
217
+
218
+ async function integrationDefaults(effects, existing, fleetRequired) {
219
+ const detected = typeof effects.detectHarnesses === 'function' ? await effects.detectHarnesses() : [];
220
+ // A retained full setup keeps the apps it already connected.
221
+ let saved = null;
222
+ try { saved = existing ? effects.readManagedClientProfile?.() : null; } catch { saved = null; }
223
+ const keep = saved && saved.expectedInstanceId === existing.instanceId ? saved.installer?.integrations : undefined;
224
+ const choices = [{ value: 'codex', label: 'Codex' }, { value: 'claude-code', label: 'Claude Code' }, ...(fleetRequired ? [] : [{ value: 'fleet', label: 'Fleet — persistent agents' }])];
225
+ const selected = keep ?? integrations.filter(name => name === 'fleet' || detected.some(item => item.name === name && item.status === 'ok'));
226
+ return { choices, selected };
227
+ }
228
+
229
+ /** The recommended full local setup: a retained installation keeps its folder, runtime and apps; a fresh one uses the defaults. */
230
+ async function recommendedSetup(effects, options, fleetRequired) {
231
+ const stateDir = expandPaths({ stateDir: options.stateDir ?? join(effects.home, '.ours-install') }, effects.home).stateDir;
232
+ const existing = refuseOldLayout(effects.readJson(join(stateDir, 'installation.json')), stateDir, effects.readJson);
233
+ if (existing?.mode === 'packages')
234
+ throw new Error('This installation runs natively, which supports the server only. Choose the server-only setup to maintain it (ours-install server); local clients need an installation that runs in Docker or Podman. Nothing was changed.');
235
+ const engine = existing ? (existing.containerEngine === 'podman' ? 'Podman' : 'Docker') : options.containerEngine === 'podman' ? 'Podman' : 'Docker';
236
+ effects.out(heading(existing ? 'Update Ours on this computer' : 'Install Ours on this computer'));
237
+ effects.out(info(existing ? `Recommended: update your existing Ours in ${stateDir} (${engine}), keeping its identities, data and apps.`
238
+ : `Recommended: the server, Fleet and your detected agent apps, in ${stateDir}, running in ${engine}.`));
239
+ const choice = await effects.select('How would you like to continue?', [
240
+ { value: 'recommended', label: existing ? 'Update with recommended setup' : 'Install recommended setup' },
241
+ { value: 'customize', label: 'Customize' },
242
+ ], 'recommended');
243
+ if (choice !== 'recommended') return null;
244
+ options.stateDir = stateDir;
245
+ options.operation ??= existing ? 'update' : 'install';
246
+ options.mode ??= 'docker';
247
+ if (existing) {
248
+ options.mode = existing.mode;
249
+ if (existing.containerEngine) options.containerEngine = existing.containerEngine;
250
+ }
251
+ const human = ['localUsername', 'name', 'surname'].some(key => options[key] !== undefined);
252
+ // Supplied profile inputs never rename a retained root.
253
+ if (existing?.messengerIdentity && !human) options.identityName ??= existing.messengerIdentity;
254
+ else if (human || options.identityName === undefined) await collectProfile(effects, options);
255
+ for (const [key, fallback] of Object.entries(defaults)) options[key] ??= existing?.[key] ?? fallback;
256
+ if (options.integrations === undefined) {
257
+ const { selected } = await integrationDefaults(effects, existing, fleetRequired);
258
+ options.integrations = fleetRequired || !existing ? [...selected.filter(name => name !== 'fleet'), 'fleet'] : selected;
259
+ }
260
+ if (options.operation === 'update') {
261
+ effects.out(info('The update keeps identities and messages and makes a recovery backup first.'));
262
+ options.compatible ??= await effects.ask('Update now and keep a recovery backup?', true);
263
+ if (!options.compatible) throw new Error('Update cancelled; nothing was changed');
264
+ }
265
+ return validateSetupOptions(expandPaths(options, effects.home), { interactive: true });
266
+ }
267
+
182
268
  export async function collectSetupOptions(effects, presets = {}) {
183
269
  if (effects.interactive !== true) throw new Error('Interactive setup requires a TTY; provide the complete CLI options instead');
184
270
  const options = { ...presets, interactive: true, explicitPorts: presets.explicitPorts ?? [] };
@@ -187,142 +273,100 @@ export async function collectSetupOptions(effects, presets = {}) {
187
273
  { value: 'server', label: 'Server only' },
188
274
  { value: 'client', label: 'Connect this computer to an existing server' },
189
275
  ];
190
- effects.out('Choose what this computer should do. Everything runs the server here and connects your selected apps; client-only uses a server you already have.');
191
- options.scope ??= await effects.select('What would you like to set up?', scopeChoices, 'all');
276
+ if (options.scope === undefined) {
277
+ effects.out(info('Everything runs the server here and connects your apps; client-only uses a server you already have.'));
278
+ options.scope = await effects.select('What would you like to set up?', scopeChoices, 'all');
279
+ }
192
280
  if (!scopes.includes(options.scope)) throw new Error('Scope must be all, server, or client');
281
+ // A full local setup started for the complete workspace (--disable-fleet-agents-setup) always includes Fleet.
282
+ const fleetRequired = options.scope === 'all' && options.disableFleetAgentsSetup === true;
283
+ // A preset full local setup (the App command) starts with one choice: the recommended setup or Customize.
284
+ if (presets.scope === 'all') {
285
+ const recommended = await recommendedSetup(effects, options, fleetRequired);
286
+ if (recommended) return recommended;
287
+ }
193
288
  let existing;
194
- let pendingMigration;
195
289
  if (options.scope !== 'client') {
196
290
  const recommendedRoot = join(effects.home, '.ours-install');
197
- effects.out(`Stores the server programs and data, including identities and messages. The recommended folder is ${recommendedRoot}; choose another only if you want to manage its location yourself.`);
198
- const location = options.stateDir ? 'preset' : await effects.select('Where should server programs and data be stored?', [
199
- { value: 'recommended', label: `Use the recommended folder (${recommendedRoot})` },
200
- { value: 'custom', label: 'Choose another folder' },
201
- ], 'recommended');
202
- options.stateDir ??= location === 'recommended' ? recommendedRoot : await effects.askLine('Folder for server programs and data: ', recommendedRoot);
291
+ if (!options.stateDir) {
292
+ effects.out(info('Ours keeps its programs and data (identities, messages) in one folder.'));
293
+ const location = await effects.select('Where should server programs and data be stored?', [
294
+ { value: 'recommended', label: `${recommendedRoot} (recommended)` },
295
+ { value: 'custom', label: 'Choose another folder' },
296
+ ], 'recommended');
297
+ options.stateDir = location === 'recommended' ? recommendedRoot : await effects.askLine('Folder for server programs and data: ', recommendedRoot);
298
+ }
203
299
  options.stateDir = expandPaths({ stateDir: options.stateDir }, effects.home).stateDir;
204
- existing = effects.readJson(join(options.stateDir, 'installation.json'));
205
- const migrationJournal = existing?.legacyMigrationSource ? effects.readJson(join(options.stateDir, 'legacy-migration.json')) : null;
206
- pendingMigration = existing?.legacyMigrationSource && migrationJournal?.phase !== 'complete' ? existing.legacyMigrationSource : null;
300
+ existing = refuseOldLayout(effects.readJson(join(options.stateDir, 'installation.json')), options.stateDir, effects.readJson);
207
301
  }
208
- effects.out(pendingMigration
209
- ? 'An earlier migration is unfinished. Resume it in this same folder to retain the copied data and repair the installation.'
210
- : existing
211
- ? 'This folder already contains an installation. Update selects this installer’s release while retaining state; repair reinstalls the retained package selection.'
212
- : options.scope === 'client' ? 'Install connects your selected apps. Update refreshes their packages while keeping the server connection.'
213
- : 'Install creates a managed installation in the selected folder. Update requires an installation already recorded there.');
214
- options.operation ??= !existing && options.scope !== 'client' ? 'install' : await effects.select('What should happen?', [
215
- { value: 'install', label: pendingMigration ? 'Resume the unfinished migration' : existing ? 'Repair this installation' : 'Install and configure' },
216
- { value: 'update', label: 'Update an existing installation' },
217
- ], existing && !pendingMigration ? 'update' : 'install');
218
- if (options.scope !== 'client' && options.operation === 'install') {
219
- const defaultConfig = join(effects.home, '.ours', 'config.json');
220
- const legacy = !existing ? effects.readJson(defaultConfig) : null;
221
- const legacyState = nonempty(legacy?.stateDir) ? legacy.stateDir
222
- : legacy && legacy.stateDir === undefined && nonempty(effects.readJson(join(effects.home, '.ours', 'root.json'))?.name)
223
- ? join(effects.home, '.ours') : null;
224
- if (options.migrateFrom) { /* Explicit selection is validated below. */ }
225
- else if (pendingMigration) options.migrateFrom = pendingMigration;
226
- else if (legacyState) {
227
- effects.out(`Found an existing ours installation at ${legacyState}. Upgrade it to keep its identities, messages and settings. The old server will stop; its original state is kept as a recovery copy.`);
228
- if (await effects.ask('Upgrade this existing ours installation and keep its data?', true)) options.migrateFrom = defaultConfig;
229
- else {
230
- effects.out('A separate installation creates a different server. It does not move or share the identities and messages in the existing installation.');
231
- if (!await effects.ask('Create a separate fresh installation and keep the existing daemon unchanged?', false)) throw new Error('Setup cancelled; existing daemon was not changed');
232
- }
233
- } else {
234
- effects.out('Start fresh if you have no existing ours data to bring over. If your old installation is stored elsewhere, select its configuration file to retain its data.');
235
- const migration = await effects.select('Should existing ours data be brought over?', [
236
- { value: 'fresh', label: 'Start a fresh installation' },
237
- { value: 'migrate', label: 'Bring data from another existing installation' },
238
- ], 'fresh');
239
- if (migration === 'migrate') options.migrateFrom = expandPaths({ migrateFrom: await effects.askLine('Existing daemon configuration file: ', '') }, effects.home).migrateFrom;
240
- }
241
- if (options.migrateFrom) {
242
- if (existing && pendingMigration !== options.migrateFrom) throw new Error('--migrate-from requires a new managed installation root; the selected root already has installation.json');
243
- const sourceConfig = effects.readJson(options.migrateFrom);
244
- const sourceState = sourceConfig?.stateDir ?? dirname(options.migrateFrom);
245
- const root = effects.readJson(join(sourceState, 'root.json'));
246
- if (!nonempty(root?.name)) throw new Error('Cannot read the existing Human identity name; choose the configuration file for a complete existing installation');
247
- options.identityName = root.name;
248
- effects.out(`Your existing Human identity, ${root.name}, will be retained; no replacement identity will be created. Migration keeps the original state, but compatibility with an older release cannot be guaranteed automatically.`);
249
- options.compatible ??= await effects.ask('Proceed with this release and keep the original state as a recovery copy?', false);
250
- if (!options.compatible) throw new Error('Migration requires explicit compatibility confirmation (--compatible)');
251
- }
302
+ if (options.operation === undefined) {
303
+ if (existing || options.scope === 'client') {
304
+ effects.out(info(existing ? `Ours is already installed in ${options.stateDir}. Update keeps your identities and data; repair reruns setup.`
305
+ : 'Install connects your apps; update refreshes them and keeps the server connection.'));
306
+ options.operation = await effects.select('What should happen?', [
307
+ { value: 'install', label: existing ? 'Repair this installation' : 'Install and configure' },
308
+ { value: 'update', label: existing ? 'Update (recommended)' : 'Update an existing installation' },
309
+ ], existing ? 'update' : 'install');
310
+ } else options.operation = 'install';
252
311
  }
253
312
  if (options.scope !== 'client') {
254
- const recommendation = recommendedMode({ ...effects.platform, arch: effects.platform?.arch ?? process.arch });
255
313
  // Native runs the server only: local clients need the container gateway. A retained
256
314
  // native installation keeps its mode, so a full setup of it cannot finish.
257
- // (An unfinished migration is resumed in its recorded mode and is validated with the plan.)
258
- if (options.scope === 'all' && existing?.mode === 'packages' && !options.migrateFrom)
315
+ if (options.scope === 'all' && existing?.mode === 'packages')
259
316
  throw new Error('This installation runs natively, which supports the server only. Choose the server-only setup to maintain it (ours-install server); local clients need an installation that runs in Docker or Podman. Nothing was changed.');
260
- const nativeOffered = options.scope === 'server' || existing?.mode === 'packages';
261
- effects.out(nativeOffered
262
- ? `${recommendation.reason} Native runs directly on this computer; Docker runs in containers and needs Docker installed and running. An existing installation must keep its current mode.`
263
- : 'The server runs in containers. Docker and Podman both work; the one you choose must be installed and running. An existing installation must keep its current mode.');
264
- const runtime = options.mode ?? await effects.select('How should the server run?', [
265
- ...(nativeOffered ? [{ value: 'packages', label: 'Native packages' }] : []), { value: 'docker', label: 'Docker' }, { value: 'podman', label: 'Podman' },
266
- ], existing?.mode === 'docker' && existing?.containerEngine === 'podman' ? 'podman' : existing?.mode ?? recommendation.mode);
317
+ // A retained installation keeps its runtime, so there is nothing to choose.
318
+ const retained = existing ? (existing.mode === 'docker' && existing.containerEngine === 'podman' ? 'podman' : existing.mode) : undefined;
319
+ let runtime = options.mode ?? retained;
320
+ if (runtime === undefined) {
321
+ const nativeOffered = options.scope === 'server';
322
+ effects.out(info(nativeOffered ? 'Native runs directly on this computer; Docker and Podman run in containers and must be installed and running.'
323
+ : 'Ours runs in containers; Docker or Podman must be installed and running.'));
324
+ runtime = await effects.select('How should the server run?', [
325
+ { value: 'docker', label: 'Docker (recommended)' }, { value: 'podman', label: 'Podman' },
326
+ ...(nativeOffered ? [{ value: 'packages', label: 'Native packages' }] : []),
327
+ ], recommendedMode({ ...effects.platform, arch: effects.platform?.arch ?? process.arch }).mode);
328
+ }
267
329
  options.mode = runtime === 'podman' ? 'docker' : runtime;
268
330
  if (runtime === 'podman') options.containerEngine = 'podman';
269
- if (!options.migrateFrom) {
270
- if (existing?.messengerIdentity) {
271
- effects.out(`Existing Human identity ${existing.messengerIdentity} and Messenger profile will be retained.`);
272
- // Supplied profile inputs never rename a retained root.
273
- if (!['localUsername', 'name', 'surname'].some(key => options[key] !== undefined)) options.identityName ??= existing.messengerIdentity;
274
- } else if (options.identityName === undefined || options.localUsername !== undefined) {
275
- effects.out('Choose a local username (no global uniqueness check). Name and Surname appear in Messenger; the optional host name identifies this workspace.');
276
- options.localUsername ??= await effects.askLine('Local username: ', (effects.username?.() ?? 'me').toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 30));
277
- options.name ??= await effects.askLine('Name: ', '');
278
- options.surname ??= await effects.askLine('Surname: ', '');
279
- options.hostname ??= await effects.askLine('Host / machine name (optional): ', '');
280
- }
281
- }
282
- if (['localUsername', 'name', 'surname'].some(key => options[key] !== undefined)) {
283
- // Partial profile presets still collect missing fields on retained and
284
- // migration paths; these inputs never replace their authoritative root.
285
- effects.out('Name and Surname initialize a missing Messenger profile; an existing profile is retained.');
286
- options.localUsername ??= await effects.askLine('Local username: ', (effects.username?.() ?? 'me').toLowerCase().replace(/[^a-z0-9-]/g, '-').slice(0, 30));
287
- options.name ??= await effects.askLine('Name: ', '');
288
- options.surname ??= await effects.askLine('Surname: ', '');
289
- options.hostname ??= await effects.askLine('Host / machine name (optional): ', '');
290
- }
331
+ const human = ['localUsername', 'name', 'surname'].some(key => options[key] !== undefined);
332
+ // Supplied profile inputs never rename a retained root.
333
+ if (existing?.messengerIdentity && !human) options.identityName ??= existing.messengerIdentity;
334
+ else if (human || options.identityName === undefined) await collectProfile(effects, options);
291
335
  for (const [key, fallback] of Object.entries(defaults)) options[key] ??= existing?.[key] ?? fallback;
292
336
  if (options.operation === 'update') {
293
- effects.out('The update retains identities and messages and creates a recovery backup before changing stored state. Proceed only if you accept this release for your existing data; compatibility is not automatically guaranteed.');
337
+ effects.out(info('The update keeps identities and messages and makes a recovery backup first; compatibility with older data is not guaranteed.'));
294
338
  options.compatible ??= await effects.ask('Proceed with this update and keep a recovery backup?', false);
295
339
  }
296
340
  } else {
297
341
  const savedProfile = join(effects.home, '.ours-client', 'profile.json');
298
- effects.out('A connection profile identifies the server and its private access credential. Reuse your saved connection or select a profile supplied by the server owner.');
299
- const connection = options.config ? 'preset' : await effects.select('Which server connection should this computer use?', [
300
- { value: 'saved', label: 'Use the saved server connection' }, { value: 'file', label: 'Choose a connection profile file' },
301
- ], effects.readJson(savedProfile) ? 'saved' : 'file');
302
- options.config ??= connection === 'saved' ? savedProfile : await effects.askLine('Connection profile file: ', savedProfile);
342
+ if (!options.config) {
343
+ effects.out(info('A connection profile names the server and its private access credential.'));
344
+ const connection = await effects.select('Which server connection should this computer use?', [
345
+ { value: 'saved', label: 'Use the saved server connection' }, { value: 'file', label: 'Choose a connection profile file' },
346
+ ], effects.readJson(savedProfile) ? 'saved' : 'file');
347
+ options.config = connection === 'saved' ? savedProfile : await effects.askLine('Connection profile file: ', savedProfile);
348
+ }
303
349
  }
304
- if (options.scope !== 'server') {
305
- const detected = typeof effects.detectHarnesses === 'function' ? await effects.detectHarnesses() : [];
306
- const selected = integrations.filter(name => name === 'fleet' || detected.some(item => item.name === name && item.status === 'ok'));
307
- effects.out('Choose the apps to connect. Detected agent apps are selected by default; Fleet configures persistent agents but leaves them stopped. Use Space to toggle choices, then Enter to continue. You can select none.');
308
- options.integrations ??= await effects.multiselect('Which integrations should be configured?', [
309
- { value: 'codex', label: 'Codex' }, { value: 'claude-code', label: 'Claude Code' }, { value: 'fleet', label: 'Fleet — persistent agents' },
310
- ], selected);
350
+ if (options.scope !== 'server' && options.integrations === undefined) {
351
+ const { choices, selected } = await integrationDefaults(effects, existing, fleetRequired);
352
+ effects.out(info(fleetRequired ? 'Fleet is included. Choose agent apps to connect.' : 'Choose apps to connect. Fleet agents stay stopped until you start them.'));
353
+ const chosen = await effects.multiselect('Which integrations should be configured?', choices, selected.filter(name => choices.some(choice => choice.value === name)));
354
+ options.integrations = fleetRequired ? [...chosen.filter(name => name !== 'fleet'), 'fleet'] : chosen;
311
355
  if (options.integrations.includes('fleet') && !options.disableFleetAgentsSetup && !options.fleetSettingsPath) {
312
- effects.out('Fleet needs model and agent settings. Its guided setup asks for these later; a prepared settings file applies your existing choices. Fleet roles will not start automatically.');
356
+ effects.out(info('Fleet needs model and agent settings; its roles will not start automatically.'));
313
357
  const fleetMode = await effects.select('How should Fleet be configured?', [
314
358
  { value: 'wizard', label: 'Configure interactively with Fleet' }, { value: 'file', label: 'Use a prepared settings file' },
315
359
  ], 'wizard');
316
360
  if (fleetMode === 'file') options.fleetSettingsPath = await effects.askLine('Fleet settings file: ', '');
317
361
  }
318
362
  }
319
- effects.out('Recommended settings use the standard service ports and this installer’s packaged release. Customize only if you need different ports or a development package selection.');
363
+ effects.out(info('Recommended settings use the standard ports and this installer’s release.'));
320
364
  const advanced = await effects.select('Installation settings', [
321
365
  { value: 'recommended', label: 'Use recommended settings' }, { value: 'custom', label: 'Customize' },
322
366
  ], 'recommended');
323
367
  if (advanced === 'custom') {
324
368
  if (options.scope !== 'client') {
325
- effects.out('Ports determine where local apps reach each service. Use three different available ports; an existing installation keeps its recorded ports.');
369
+ effects.out(info('Use three different available ports; an existing installation keeps its recorded ports.'));
326
370
  for (const key of Object.keys(defaults)) {
327
371
  const label = { port: 'Daemon', coworkPort: 'Cowork', messengerPort: 'Messenger' }[key];
328
372
  const value = await effects.askLine(`${label} port: `, String(options[key]));
@@ -330,14 +374,13 @@ export async function collectSetupOptions(effects, presets = {}) {
330
374
  options[key] = Number(value); options.explicitPorts.push(key);
331
375
  }
332
376
  }
333
- effects.out('A source override replaces the packaged release selection. Leave it empty for the supported packaged release; use a file only for a deliberate development override.');
377
+ effects.out(info('A source override replaces the packaged release; leave it empty unless you are developing Ours.'));
334
378
  const sources = await effects.askLine('Source policy override file (optional): ', '');
335
379
  if (sources.trim()) options.sources = sources;
336
380
  }
337
381
  const validated = validateSetupOptions(expandPaths(options, effects.home), { interactive: true });
338
382
  const scopeLabel = scopeChoices.find(choice => choice.value === validated.scope).label;
339
- effects.out(`Setup: ${scopeLabel}; ${validated.operation}${validated.mode ? ` using ${validated.mode === 'packages' ? 'native packages' : 'Docker'} in ${validated.stateDir}` : ` from ${validated.config}`}; integrations: ${validated.integrations?.join(', ') || 'none'}${validated.migrateFrom ? `; migrate from: ${validated.migrateFrom}` : ''}.`);
340
- effects.out('Continue to apply these choices. Cancelling now leaves programs, services and data unchanged.');
341
- if (!await effects.ask('Continue with this setup?', false)) throw new Error('Setup cancelled; nothing was changed');
383
+ effects.out(info(`Setup: ${scopeLabel}; ${validated.operation}${validated.mode ? ` using ${validated.mode === 'packages' ? 'native packages' : validated.containerEngine === 'podman' ? 'Podman' : 'Docker'} in ${validated.stateDir}` : ` from ${validated.config}`}; integrations: ${validated.integrations?.join(', ') || 'none'}. Nothing changes until you continue.`));
384
+ if (!await effects.ask('Continue with this setup?', true)) throw new Error('Setup cancelled; nothing was changed');
342
385
  return validated;
343
386
  }
package/lib/setup.mjs CHANGED
@@ -1,19 +1,18 @@
1
1
  import { validateGatewayClientProfile } from './target.mjs';
2
2
  import { gatewayAddress } from './gateway.mjs';
3
- import { inspectLegacyMigration } from './legacy-migration.mjs';
4
- import { join } from 'node:path';
3
+ import { dirname, join } from 'node:path';
5
4
  import { parseSetupArgs, collectSetupOptions, validateSetupOptions } from './setup-options.mjs';
6
5
  import { parseNetworkArgs, validateHostProfile, InstallUsageError } from './target.mjs';
7
- import { clientPackageNames, validateInstallation } from './plan.mjs';
6
+ import { clientPackageNames, validateInstallation, refuseOldLayout, installationPaths, unitNameForStateDir, launchdLabelForStateDir } from './plan.mjs';
8
7
  import { runServerCommand, runClientCommand } from './orchestrate.mjs';
9
- import { banner, heading, info, ok, warn, progress } from './ui.mjs';
8
+ import { banner, c, heading, info, ok, warn, progress } from './ui.mjs';
10
9
  import { isCancel } from './prompt.mjs';
11
10
  import { USAGE } from './usage.mjs';
12
11
  import { validateIdentityName } from './server-onboarding.mjs';
13
12
  import { validateFleetSettings } from './fleet-settings.mjs';
14
13
  import { installerFailure } from './diagnostics.mjs';
15
14
  import { productOf, isPluginOnly, serverRole, PRODUCT_LABELS, PLUGIN_ONLY_INTEGRATIONS } from './product.mjs';
16
- import { collectWelcome, customHarnessGuidance, KEEPS_YOUR_SETUP } from './welcome.mjs';
15
+ import { collectWelcome, customHarnessGuidance, findInstallations, KEEPS_YOUR_SETUP } from './welcome.mjs';
17
16
  import { runRemoval } from './removal.mjs';
18
17
 
19
18
  const maintenance = new Set(['status', 'start', 'stop', 'restart', 'uninstall', 'rebuild', 'gateway-enable', 'access-issue', 'access-replace', 'backup', 'restore', 'reset']);
@@ -44,23 +43,14 @@ export async function prepareSetupPlan(options, effects) {
44
43
  if (effects.env?.[name]?.trim()) throw new InstallUsageError(`${name} conflicts with the selected client profile. Clear this override before full-stack/client setup; nothing was changed.`);
45
44
  }
46
45
  }
47
- if (options.scope !== 'client' && !options.migrateFrom) validateIdentityName(options.identityName);
46
+ if (options.scope !== 'client') validateIdentityName(options.identityName);
48
47
  if (options.fleetSettingsPath) validateFleetSettings(readObject(effects, options.fleetSettingsPath, 'Fleet settings'));
49
48
  const policy = options.sources ? readObject(effects, options.sources, 'Source policy') : effects.packagedSourcePolicy();
50
49
  plan.sourcePolicy = policy;
51
- if (options.migrateFrom) {
52
- for (const name of ['OURS_API_TOKEN', 'OURS_API_VISIBILITY', 'OURS_STATE_DIR', 'OURS_PORT', 'OURS_DAEMON_ID', 'OURS_DATABASE_PROVIDER', 'OURS_DATABASE_URL']) {
53
- if (effects.env?.[name]?.trim()) throw new InstallUsageError(`${name} conflicts with legacy migration. Clear it before setup; nothing was changed.`);
54
- }
55
- plan.legacyPlan = await (effects.inspectLegacyMigration ?? inspectLegacyMigration)(options, effects);
56
- plan.sourcePolicy = plan.legacyPlan.journal.sourcePolicy ?? policy;
57
- plan.identityName = plan.legacyPlan.source?.rootName ?? plan.legacyPlan.journal.identities.find(row => row.kind === 'root')?.name;
58
- validateIdentityName(plan.identityName);
59
- }
60
50
  if (options.scope !== 'client') {
61
51
  const value = effects.readJson(join(options.stateDir, 'installation.json'));
62
52
  if (value) {
63
- plan.existing = validateInstallation(value, options.stateDir);
53
+ plan.existing = validateInstallation(refuseOldLayout(value, options.stateDir, effects.readJson), options.stateDir);
64
54
  // The kind of installation is retained exactly; it is never widened or narrowed implicitly.
65
55
  if (options.product !== undefined && options.product !== productOf(plan.existing))
66
56
  throw new InstallUsageError(`This folder contains ${PRODUCT_LABELS[productOf(plan.existing)].toLowerCase()}. It is kept as it is; nothing was changed. Use a separate empty folder for the other kind of installation, or remove this one first.`);
@@ -71,7 +61,7 @@ export async function prepareSetupPlan(options, effects) {
71
61
  if (options.explicitPorts?.includes(key) && options[key] !== plan.existing[key]) throw new InstallUsageError(`${key} conflicts with the retained installation`);
72
62
  plan[key] = plan.existing[key];
73
63
  }
74
- if (options.operation === 'install' && !options.migrateFrom) {
64
+ if (options.operation === 'install') {
75
65
  const retained = readObject(effects, plan.existing.sourcesPath, 'Retained source policy');
76
66
  plan.sourcePolicy = options.scope === 'server' ? retained : completeReleasePolicy(retained, options.sources ? policy : null);
77
67
  }
@@ -162,9 +152,12 @@ export async function executeSetupPlan(plan, effects, { server = runServerComman
162
152
  preset: true, nonInteractive: !plan.interactive }, effects);
163
153
  if (result !== 0) return result;
164
154
  }
165
- if (plan.retainFleetConfiguration && plan.integrations?.includes('fleet')) effects.out(info('Fleet was updated; your existing Fleet agents and their configuration were kept. Restart running agents when convenient: ours-fleet restart'));
166
- else if (plan.disableFleetAgentsSetup && plan.integrations?.includes('fleet')) effects.out(info('Fleet is installed. Run ours-fleet setup-tunnel with the expiring one-use payload from the App command; a compatible Fleet prints the QR and connection code automatically. Configure agents and models in the App after linking.'));
155
+ effects.out(heading('Your installation summary'));
167
156
  effects.out(ok(`Requested ${plan.operation} completed. Existing identities were retained.`));
157
+ if (plan.scope !== 'client') effects.out(info(`Ours: ${plan.stateDir}, running ${plan.mode === 'packages' ? 'natively' : plan.containerEngine === 'podman' ? 'in Podman' : 'in Docker'}`));
158
+ if (plan.scope !== 'server') effects.out(info(`Connected: ${plan.integrations.map(name => ({ codex: 'Codex', 'claude-code': 'Claude Code', fleet: 'Fleet' })[name]).join(', ') || 'none'}`));
159
+ if (plan.retainFleetConfiguration && plan.integrations?.includes('fleet')) effects.out(info('Fleet was updated; your existing Fleet agents and their configuration were kept. Restart running agents when convenient: ours-fleet restart'));
160
+ else if (plan.disableFleetAgentsSetup && plan.integrations?.includes('fleet')) effects.out(`\n ${c.bold('Next:')} return to the Ours App in your browser and continue to connect this workspace. Agents and models are configured there.\n`);
168
161
  if (plan.integrations?.includes('fleet') && !plan.disableFleetAgentsSetup) effects.out(info('Fleet is configured but stopped. Review its settings, then run ours-fleet doctor, ours-fleet config and ours-fleet up.'));
169
162
  if (isPluginOnly(plan.product) && plan.scope === 'all') {
170
163
  effects.out(info('Collaboration tools are ready. Restart Claude Code and start a new Codex session so they load the Ours tools; then ask your agent to create its Ours identity.'));
@@ -190,6 +183,52 @@ function preparedClaudeMarketplace(effects) {
190
183
  return null;
191
184
  }
192
185
 
186
+ /** Partial presets without --state-dir reuse the one installation already here, as the welcome screen does. */
187
+ async function retainedRoot(presets, effects) {
188
+ if (!['all', 'server'].includes(presets.scope) || presets.stateDir !== undefined) return {};
189
+ const found = findInstallations(effects);
190
+ const usable = found.filter(item => !item.invalid);
191
+ if (usable.length === 1) return { stateDir: usable[0].root };
192
+ if (usable.length > 1) throw new InstallUsageError(`Several Ours installations are on this computer (${usable.map(item => item.root).join(', ')}). Choose one with --state-dir; nothing was changed.`);
193
+ if (found.length) throw new InstallUsageError(`An Ours installation here could not be read (${found.map(item => item.root).join(', ')}). Run ours-install without options to review it; nothing was changed.`);
194
+ return outsideRoot(effects);
195
+ }
196
+
197
+ /**
198
+ * An installation in a folder outside ~/.ours*, found from what it runs: Compose labels name its
199
+ * runtime folder (<root>/runtime), and every native installation uses the same daemon service name.
200
+ */
201
+ async function outsideRoot(effects) {
202
+ const daemon = installationPaths({ root: effects.home }).daemon;
203
+ const service = effects.platform?.platform === 'darwin'
204
+ ? join(effects.home, 'Library/LaunchAgents', `${launchdLabelForStateDir(daemon).label}.plist`)
205
+ : join(effects.home, '.config/systemd/user', unitNameForStateDir(daemon).unit);
206
+ if (effects.exists?.(service)) throw new InstallUsageError(`An Ours service from another folder is set up for your user (${service}). Re-run with --state-dir <its folder> to update it; nothing was changed.`);
207
+ const roots = new Set(), unknown = new Set();
208
+ for (const engine of ['docker', 'podman']) {
209
+ let listed;
210
+ try { listed = await effects.run(engine, ['ps', '-a', '--format', '{{.Label "com.docker.compose.project"}}\t{{.Label "com.docker.compose.project.working_dir"}}']); }
211
+ catch (error) {
212
+ if (error?.code === 'ENOENT') continue;
213
+ // An installed engine that cannot be inspected could hide an installation: never assume there is none.
214
+ throw new InstallUsageError(`Could not check ${engine === 'docker' ? 'Docker' : 'Podman'} for an existing Ours installation. Start it (or fix access for your user) and retry, or re-run with --state-dir <folder>; nothing was changed.`);
215
+ }
216
+ for (const line of listed.stdout.split('\n')) {
217
+ const [project = '', workDir = ''] = line.trim().split('\t');
218
+ // Only Compose-created containers name a project folder; images inherit the project label alone.
219
+ if (!/^ours-/.test(project) || !workDir) continue;
220
+ const root = dirname(workDir);
221
+ let record = null;
222
+ try { record = validateInstallation(effects.readJson(join(root, 'installation.json')), root); } catch { record = null; }
223
+ if (record?.project === project && record.workDir === workDir) roots.add(root);
224
+ else unknown.add(project);
225
+ }
226
+ }
227
+ if (unknown.size) throw new InstallUsageError(`Ours containers without a readable installation are on this computer (${[...unknown].join(', ')}). Re-run with --state-dir <its folder> to update it; nothing was changed.`);
228
+ if (roots.size > 1) throw new InstallUsageError(`Several Ours installations are on this computer (${[...roots].join(', ')}). Choose one with --state-dir; nothing was changed.`);
229
+ return roots.size ? { stateDir: [...roots][0] } : {};
230
+ }
231
+
193
232
  /** The sole executable entry: manual answers and CLI presets share one plan/executor. */
194
233
  export async function runSetup(argv, effects) {
195
234
  try {
@@ -212,8 +251,8 @@ export async function runSetup(argv, effects) {
212
251
  const presets = parseSetupArgs(argv, { home: effects.home, validate: false });
213
252
  try { options = validateSetupOptions(presets, { interactive: false }); }
214
253
  catch (error) {
215
- if (!effects.interactive || effects.env?.OURS_ASSUME_YES || !/^Missing (required setup options|human profile option):/.test(error.message)) throw error;
216
- options = await collectSetupOptions(effects, presets);
254
+ if (!effects.interactive || effects.env?.OURS_ASSUME_YES || !/^(Missing (required setup options|human profile option):|Local username must|Hostname must|(name|surname) must contain|Name and Surname together)/.test(error.message)) throw error;
255
+ options = await collectSetupOptions(effects, { ...presets, ...await retainedRoot(presets, effects) });
217
256
  }
218
257
  }
219
258
  const plan = { ...await prepareSetupPlan(options, effects), ...extra };