@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
@@ -1,21 +1,22 @@
1
- import { join, resolve } from 'node:path';
1
+ import { serverBase } from './gateway.mjs';
2
+ import { join, resolve, isAbsolute, dirname } from 'node:path';
2
3
 
3
4
  const scopes = ['all', 'server', 'client'];
4
5
  const integrations = ['codex', 'claude-code', 'fleet'];
5
6
  const valueFlags = new Map(Object.entries({
6
- '--scope': 'scope', '--action': 'operation', '--mode': 'mode', '--state-dir': 'stateDir',
7
+ '--container-engine': 'containerEngine', '--server-url': 'serverUrl', '--scope': 'scope', '--action': 'operation', '--mode': 'mode', '--state-dir': 'stateDir',
7
8
  '--identity-name': 'identityName', '--integrations': 'integrations', '--fleet-settings': 'fleetSettingsPath',
8
- '--config': 'config', '--sources': 'sources', '--port': 'port', '--cowork-port': 'coworkPort', '--messenger-port': 'messengerPort',
9
+ '--config': 'config', '--sources': 'sources', '--migrate-from': 'migrateFrom', '--port': 'port', '--cowork-port': 'coworkPort', '--messenger-port': 'messengerPort',
9
10
  }));
10
11
  const boolFlags = new Map([['--compatible', 'compatible'], ['--dry-run', 'dryRun'], ['--migrate', 'migrate']]);
11
12
  const allowed = new Set([...valueFlags.values(), ...boolFlags.values(), 'interactive', 'explicitPorts']);
12
13
  const defaults = { port: 3050, coworkPort: 3052, messengerPort: 8420 };
13
- const paths = ['stateDir', 'config', 'sources', 'fleetSettingsPath'];
14
+ const paths = ['stateDir', 'config', 'sources', 'fleetSettingsPath', 'migrateFrom'];
14
15
  const nonempty = value => typeof value === 'string' && value.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(value);
15
16
 
16
17
  export function recommendedMode({ platform, arch, release = '' } = {}) {
17
18
  if (platform === 'linux' && /microsoft|wsl/i.test(release)) return { mode: 'docker', reason: 'Docker is recommended on Windows and WSL.' };
18
- if (platform === 'linux' && arch === 'x64') return { mode: 'packages', reason: 'Native packages are recommended on Linux x64 with a systemd user manager.' };
19
+ if (platform === 'linux' && arch === 'x64') return { mode: 'docker', reason: 'Docker provides the integrated gateway for full-stack setup; native mode is server-only.' };
19
20
  if (platform === 'darwin') return { mode: 'docker', reason: 'Docker is recommended on macOS.' };
20
21
  if (platform === 'win32') return { mode: 'docker', reason: 'Docker is recommended on Windows; run the installer inside WSL with Docker Desktop.' };
21
22
  return { mode: 'docker', reason: 'Docker is recommended for this platform.' };
@@ -29,15 +30,22 @@ export function validateSetupOptions(input, { interactive = input?.interactive =
29
30
  if (!['install', 'update'].includes(options.operation)) throw new Error('Operation must be install or update');
30
31
  const server = options.scope !== 'client';
31
32
  const client = options.scope !== 'server';
33
+ if (options.migrateFrom !== undefined && (!server || options.operation !== 'install')) throw new Error('--migrate-from requires server or all scope and operation install');
34
+ if (options.migrateFrom !== undefined && (!nonempty(options.migrateFrom) || !isAbsolute(options.migrateFrom))) throw new Error('--migrate-from requires an absolute daemon config path');
32
35
  const missing = [];
33
- if (server) for (const [key, flag] of [['mode', '--mode'], ['stateDir', '--state-dir'], ['identityName', '--identity-name']]) if (!nonempty(options[key])) missing.push(flag);
36
+ 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);
34
37
  if (client && options.integrations === undefined) missing.push('--integrations (use none to skip)');
35
38
  if (!server && !nonempty(options.config)) missing.push('--config');
36
- if (server && options.operation === 'update' && options.compatible !== true) missing.push('--compatible');
39
+ if (server && (options.operation === 'update' || options.migrateFrom !== undefined) && options.compatible !== true) missing.push('--compatible');
37
40
  if (Array.isArray(options.integrations) && options.integrations.includes('fleet') && !interactive && !nonempty(options.fleetSettingsPath)) missing.push('--fleet-settings');
38
41
  if (missing.length) throw new Error(`Missing required setup options: ${missing.join(', ')}`);
39
42
  if (options.mode === 'native') options.mode = 'packages';
40
43
  if (server && !['packages', 'docker'].includes(options.mode)) throw new Error('Mode must be packages (or native) or docker');
44
+ if (options.containerEngine !== undefined && (!server || options.mode !== 'docker' || !['docker', 'podman'].includes(options.containerEngine))) throw new Error('--container-engine docker|podman requires server container mode');
45
+ if (options.serverUrl !== undefined) {
46
+ if (!server || options.mode !== 'docker' || options.operation !== 'install') throw new Error('--server-url requires Docker server installation');
47
+ options.serverUrl = serverBase(options.serverUrl);
48
+ }
41
49
  if (server && options.config !== undefined) throw new Error('--config is only valid for client scope');
42
50
  if (!server) for (const key of ['mode', 'stateDir', 'identityName', ...Object.keys(defaults), 'compatible', 'migrate']) {
43
51
  if (options[key] !== undefined) throw new Error(`${key} is only valid for server or all scope`);
@@ -51,7 +59,10 @@ export function validateSetupOptions(input, { interactive = input?.interactive =
51
59
  for (const key of paths) if (options[key] !== undefined && !nonempty(options[key])) throw new Error(`Invalid path for ${key}`);
52
60
  for (const key of ['compatible', 'migrate']) if (options[key] !== undefined && typeof options[key] !== 'boolean') throw new Error(`${key} must be a boolean`);
53
61
  if (server) {
54
- options.identityName = options.identityName.trim();
62
+ if (options.identityName !== undefined) {
63
+ if (!nonempty(options.identityName)) throw new Error('Invalid Human identity name');
64
+ options.identityName = options.identityName.trim();
65
+ }
55
66
  for (const [key, fallback] of Object.entries(defaults)) {
56
67
  options[key] ??= fallback;
57
68
  if (!Number.isInteger(options[key]) || options[key] < 1 || options[key] > 65535) throw new Error(`${key} must be an integer port between 1 and 65535`);
@@ -71,12 +82,15 @@ function expandPaths(options, home) {
71
82
  if (value === '~' || value.startsWith('~/')) {
72
83
  if (!nonempty(home)) throw new Error('Home directory is required to expand ~/ paths');
73
84
  output[key] = resolve(home, value === '~' ? '' : value.slice(2));
74
- } else output[key] = resolve(value);
85
+ } else {
86
+ if (key === 'migrateFrom' && !isAbsolute(value)) throw new Error('--migrate-from requires an absolute daemon config path');
87
+ output[key] = resolve(value);
88
+ }
75
89
  }
76
90
  return output;
77
91
  }
78
92
 
79
- export function parseSetupArgs(argv, { home } = {}) {
93
+ export function parseSetupArgs(argv, { home, validate = true } = {}) {
80
94
  if (!Array.isArray(argv) || !argv.every(arg => typeof arg === 'string')) throw new Error('Arguments must be strings');
81
95
  const options = { interactive: false, explicitPorts: [] };
82
96
  const seen = new Set();
@@ -107,51 +121,139 @@ export function parseSetupArgs(argv, { home } = {}) {
107
121
  if (positional.length && scopes.includes(positional[0])) put('scope', positional.shift());
108
122
  if (positional.length && ['install', 'update'].includes(positional[0])) put('operation', positional.shift());
109
123
  if (positional.length) throw new Error(`Unexpected setup argument: ${positional.join(' ')}`);
110
- return validateSetupOptions(expandPaths(options, home), { interactive: false });
124
+ return validate ? validateSetupOptions(expandPaths(options, home), { interactive: false }) : expandPaths(options, home);
111
125
  }
112
126
 
113
127
  export async function collectSetupOptions(effects) {
114
128
  if (effects.interactive !== true) throw new Error('Interactive setup requires a TTY; provide the complete CLI options instead');
115
129
  const options = { interactive: true, explicitPorts: [] };
116
- options.scope = (await effects.askLine('Set up all, server, or client? ', 'all')).trim();
130
+ const scopeChoices = [
131
+ { value: 'all', label: 'Everything on this computer' },
132
+ { value: 'server', label: 'Server only' },
133
+ { value: 'client', label: 'Connect this computer to an existing server' },
134
+ ];
135
+ 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.');
136
+ options.scope = await effects.select('What would you like to set up?', scopeChoices, 'all');
117
137
  if (!scopes.includes(options.scope)) throw new Error('Scope must be all, server, or client');
118
138
  let existing;
139
+ let pendingMigration;
119
140
  if (options.scope !== 'client') {
120
- options.stateDir = await effects.askLine('Private installation root: ', join(effects.home, '.ours-install'));
141
+ const recommendedRoot = join(effects.home, '.ours-install');
142
+ 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.`);
143
+ const location = await effects.select('Where should server programs and data be stored?', [
144
+ { value: 'recommended', label: `Use the recommended folder (${recommendedRoot})` },
145
+ { value: 'custom', label: 'Choose another folder' },
146
+ ], 'recommended');
147
+ options.stateDir = location === 'recommended' ? recommendedRoot : await effects.askLine('Folder for server programs and data: ', recommendedRoot);
121
148
  options.stateDir = expandPaths({ stateDir: options.stateDir }, effects.home).stateDir;
122
149
  existing = effects.readJson(join(options.stateDir, 'installation.json'));
123
- const legacyRoot = join(effects.home, '.ours');
124
- const legacy = !existing ? effects.readJson(join(legacyRoot, 'config.json')) : null;
125
- if (legacy?.stateDir === legacyRoot) throw new Error(`An existing global daemon was found at ${legacyRoot}, without a managed installation record for the selected root. This form cannot migrate that installation yet. Keep its state; use explicit CLI presets with a different empty directory only if you intend a separate installation.`);
150
+ const migrationJournal = existing?.legacyMigrationSource ? effects.readJson(join(options.stateDir, 'legacy-migration.json')) : null;
151
+ pendingMigration = existing?.legacyMigrationSource && migrationJournal?.phase !== 'complete' ? existing.legacyMigrationSource : null;
152
+ }
153
+ effects.out(pendingMigration
154
+ ? 'An earlier migration is unfinished. Resume it in this same folder to retain the copied data and repair the installation.'
155
+ : existing
156
+ ? 'This folder already contains an installation. Update selects this installer’s release while retaining state; repair reinstalls the retained package selection.'
157
+ : options.scope === 'client' ? 'Install connects your selected apps. Update refreshes their packages while keeping the server connection.'
158
+ : 'Install creates a managed installation in the selected folder. Update requires an installation already recorded there.');
159
+ options.operation = !existing && options.scope !== 'client' ? 'install' : await effects.select('What should happen?', [
160
+ { value: 'install', label: pendingMigration ? 'Resume the unfinished migration' : existing ? 'Repair this installation' : 'Install and configure' },
161
+ { value: 'update', label: 'Update an existing installation' },
162
+ ], existing && !pendingMigration ? 'update' : 'install');
163
+ if (options.scope !== 'client' && options.operation === 'install') {
164
+ const defaultConfig = join(effects.home, '.ours', 'config.json');
165
+ const legacy = !existing ? effects.readJson(defaultConfig) : null;
166
+ const legacyState = nonempty(legacy?.stateDir) ? legacy.stateDir
167
+ : legacy && legacy.stateDir === undefined && nonempty(effects.readJson(join(effects.home, '.ours', 'root.json'))?.name)
168
+ ? join(effects.home, '.ours') : null;
169
+ if (pendingMigration) options.migrateFrom = pendingMigration;
170
+ else if (legacyState) {
171
+ 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.`);
172
+ if (await effects.ask('Upgrade this existing ours installation and keep its data?', true)) options.migrateFrom = defaultConfig;
173
+ else {
174
+ effects.out('A separate installation creates a different server. It does not move or share the identities and messages in the existing installation.');
175
+ 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');
176
+ }
177
+ } else {
178
+ 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.');
179
+ const migration = await effects.select('Should existing ours data be brought over?', [
180
+ { value: 'fresh', label: 'Start a fresh installation' },
181
+ { value: 'migrate', label: 'Bring data from another existing installation' },
182
+ ], 'fresh');
183
+ if (migration === 'migrate') options.migrateFrom = expandPaths({ migrateFrom: await effects.askLine('Existing daemon configuration file: ', '') }, effects.home).migrateFrom;
184
+ }
185
+ if (options.migrateFrom) {
186
+ if (existing && pendingMigration !== options.migrateFrom) throw new Error('--migrate-from requires a new managed installation root; the selected root already has installation.json');
187
+ const sourceConfig = effects.readJson(options.migrateFrom);
188
+ const sourceState = sourceConfig?.stateDir ?? dirname(options.migrateFrom);
189
+ const root = effects.readJson(join(sourceState, 'root.json'));
190
+ if (!nonempty(root?.name)) throw new Error('Cannot read the existing Human identity name; choose the configuration file for a complete existing installation');
191
+ options.identityName = root.name;
192
+ 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.`);
193
+ options.compatible = await effects.ask('Proceed with this release and keep the original state as a recovery copy?', false);
194
+ if (!options.compatible) throw new Error('Migration requires explicit compatibility confirmation (--compatible)');
195
+ }
126
196
  }
127
- options.operation = (await effects.askLine('Install or update? ', existing ? 'update' : 'install')).trim();
128
197
  if (options.scope !== 'client') {
129
198
  const recommendation = recommendedMode({ ...effects.platform, arch: effects.platform?.arch ?? process.arch });
130
- effects.out(`Detected ${effects.platform?.platform ?? 'unknown'} / ${effects.platform?.arch ?? process.arch}. ${recommendation.reason}`);
131
- const defaultMode = existing?.mode ?? recommendation.mode;
132
- options.mode = await effects.askLine('Runtime mode (native or docker): ', defaultMode === 'packages' ? 'native' : defaultMode);
133
- options.identityName = await effects.askLine('What name should others see? ', existing?.messengerIdentity ?? effects.username?.() ?? 'me');
134
- for (const [key, fallback] of Object.entries(defaults)) {
135
- const label = { port: 'Daemon', coworkPort: 'Cowork', messengerPort: 'Messenger' }[key];
136
- const value = await effects.askLine(`${label} port: `, String(existing?.[key] ?? fallback));
137
- if (!/^[1-9]\d*$/.test(value)) throw new Error(`${label} port must be an integer`);
138
- options[key] = Number(value); options.explicitPorts.push(key);
199
+ effects.out(`${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.`);
200
+ options.mode = await effects.select('How should the server run?', [
201
+ { value: 'packages', label: 'Native packages' }, { value: 'docker', label: 'Docker' },
202
+ ], existing?.mode ?? recommendation.mode);
203
+ if (!options.migrateFrom) {
204
+ effects.out(existing ? 'Existing identities and names are retained. This name is used only if a Human identity needs to be created.' : 'Choose the name other people and agents should see for your Human identity.');
205
+ options.identityName = await effects.askLine('What name should others see? ', existing?.messengerIdentity ?? effects.username?.() ?? 'me');
206
+ }
207
+ for (const [key, fallback] of Object.entries(defaults)) options[key] = existing?.[key] ?? fallback;
208
+ if (options.operation === 'update') {
209
+ 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.');
210
+ options.compatible = await effects.ask('Proceed with this update and keep a recovery backup?', false);
139
211
  }
140
- if (options.operation === 'update') options.compatible = await effects.ask('Confirm that the selected update is compatible with retained state?', false);
141
- } else options.config = await effects.askLine('Prepared client profile path: ', join(effects.home, '.ours-client', 'profile.json'));
212
+ } else {
213
+ const savedProfile = join(effects.home, '.ours-client', 'profile.json');
214
+ 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.');
215
+ const connection = await effects.select('Which server connection should this computer use?', [
216
+ { value: 'saved', label: 'Use the saved server connection' }, { value: 'file', label: 'Choose a connection profile file' },
217
+ ], effects.readJson(savedProfile) ? 'saved' : 'file');
218
+ options.config = connection === 'saved' ? savedProfile : await effects.askLine('Connection profile file: ', savedProfile);
219
+ }
142
220
  if (options.scope !== 'server') {
143
221
  const detected = typeof effects.detectHarnesses === 'function' ? await effects.detectHarnesses() : [];
144
- options.integrations = [];
145
- for (const name of integrations) if (await effects.ask(`Install ${name}?`, name === 'fleet' || detected.some(item => item.name === name && item.status === 'ok'))) options.integrations.push(name);
222
+ const selected = integrations.filter(name => name === 'fleet' || detected.some(item => item.name === name && item.status === 'ok'));
223
+ 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.');
224
+ options.integrations = await effects.multiselect('Which integrations should be configured?', [
225
+ { value: 'codex', label: 'Codex' }, { value: 'claude-code', label: 'Claude Code' }, { value: 'fleet', label: 'Fleet — persistent agents' },
226
+ ], selected);
146
227
  if (options.integrations.includes('fleet')) {
147
- const path = await effects.askLine('Fleet settings file (leave empty for the interactive Fleet wizard): ', '');
148
- if (path.trim()) options.fleetSettingsPath = path;
228
+ 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.');
229
+ const fleetMode = await effects.select('How should Fleet be configured?', [
230
+ { value: 'wizard', label: 'Configure interactively with Fleet' }, { value: 'file', label: 'Use a prepared settings file' },
231
+ ], 'wizard');
232
+ if (fleetMode === 'file') options.fleetSettingsPath = await effects.askLine('Fleet settings file: ', '');
233
+ }
234
+ }
235
+ 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.');
236
+ const advanced = await effects.select('Installation settings', [
237
+ { value: 'recommended', label: 'Use recommended settings' }, { value: 'custom', label: 'Customize' },
238
+ ], 'recommended');
239
+ if (advanced === 'custom') {
240
+ if (options.scope !== 'client') {
241
+ effects.out('Ports determine where local apps reach each service. Use three different available ports; an existing installation keeps its recorded ports.');
242
+ for (const key of Object.keys(defaults)) {
243
+ const label = { port: 'Daemon', coworkPort: 'Cowork', messengerPort: 'Messenger' }[key];
244
+ const value = await effects.askLine(`${label} port: `, String(options[key]));
245
+ if (!/^[1-9]\d*$/.test(value)) throw new Error(`${label} port must be an integer`);
246
+ options[key] = Number(value); options.explicitPorts.push(key);
247
+ }
149
248
  }
249
+ 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.');
250
+ const sources = await effects.askLine('Source policy override file (optional): ', '');
251
+ if (sources.trim()) options.sources = sources;
150
252
  }
151
- const sources = await effects.askLine('Source policy override (leave empty for the packaged release): ', '');
152
- if (sources.trim()) options.sources = sources;
153
253
  const validated = validateSetupOptions(expandPaths(options, effects.home), { interactive: true });
154
- effects.out(`Setup: ${validated.operation} ${validated.scope}${validated.mode ? ` using ${validated.mode} in ${validated.stateDir}` : ` from ${validated.config}`}; integrations: ${validated.integrations?.join(', ') || 'none'}.`);
254
+ const scopeLabel = scopeChoices.find(choice => choice.value === validated.scope).label;
255
+ 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}` : ''}.`);
256
+ effects.out('Continue to apply these choices. Cancelling now leaves programs, services and data unchanged.');
155
257
  if (!await effects.ask('Continue with this setup?', false)) throw new Error('Setup cancelled; nothing was changed');
156
258
  return validated;
157
259
  }
package/lib/setup.mjs CHANGED
@@ -1,7 +1,10 @@
1
+ import { validateGatewayClientProfile } from './target.mjs';
2
+ import { gatewayAddress } from './gateway.mjs';
3
+ import { inspectLegacyMigration } from './legacy-migration.mjs';
1
4
  import { join } from 'node:path';
2
5
  import { parseSetupArgs, collectSetupOptions, validateSetupOptions } from './setup-options.mjs';
3
6
  import { parseNetworkArgs, validateHostProfile, InstallUsageError } from './target.mjs';
4
- import { validateInstallation } from './plan.mjs';
7
+ import { clientPackageNames, validateInstallation } from './plan.mjs';
5
8
  import { runServerCommand, runClientCommand } from './orchestrate.mjs';
6
9
  import { banner, heading, info, ok, warn, progress } from './ui.mjs';
7
10
  import { isCancel } from './prompt.mjs';
@@ -9,8 +12,7 @@ import { USAGE } from './usage.mjs';
9
12
  import { validateIdentityName } from './server-onboarding.mjs';
10
13
  import { validateFleetSettings } from './fleet-settings.mjs';
11
14
 
12
- const maintenance = new Set(['status', 'start', 'stop', 'restart', 'rebuild', 'access-issue', 'access-replace', 'backup', 'restore', 'reset']);
13
- const clientPackages = integrations => [...new Set(['sdk', ...(integrations.includes('fleet') ? ['cli'] : []), ...integrations])];
15
+ const maintenance = new Set(['status', 'start', 'stop', 'restart', 'rebuild', 'gateway-enable', 'access-issue', 'access-replace', 'backup', 'restore', 'reset']);
14
16
 
15
17
  export function completeReleasePolicy(retained, supplied) {
16
18
  if (retained?.release) {
@@ -31,53 +33,65 @@ export async function prepareSetupPlan(options, effects) {
31
33
  options = validateSetupOptions(options, { interactive: options.interactive });
32
34
  if (effects.platform?.platform === 'win32') throw new InstallUsageError('Run ours-install inside WSL with Docker Desktop integration on Windows. Direct Windows Node installations are not supported.');
33
35
  const plan = { ...options };
34
- if (options.scope !== 'server' && options.integrations.length) {
36
+ if (options.scope === 'all' && options.mode === 'packages' && options.integrations?.length)
37
+ throw new InstallUsageError('Gateway-only clients require a gateway. Use Docker full-stack setup, or install the native server separately and provision an HTTP gateway before client setup; nothing was changed.');
38
+ if (options.scope !== 'server') {
35
39
  for (const name of ['OURS_API_TOKEN', 'OURS_PORT', 'OURS_STATE_DIR', 'OURS_DAEMON_ID']) {
36
40
  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.`);
37
41
  }
38
42
  }
39
- if (options.scope !== 'client') validateIdentityName(options.identityName);
43
+ if (options.scope !== 'client' && !options.migrateFrom) validateIdentityName(options.identityName);
40
44
  if (options.fleetSettingsPath) validateFleetSettings(readObject(effects, options.fleetSettingsPath, 'Fleet settings'));
41
45
  const policy = options.sources ? readObject(effects, options.sources, 'Source policy') : effects.packagedSourcePolicy();
42
46
  plan.sourcePolicy = policy;
47
+ if (options.migrateFrom) {
48
+ for (const name of ['OURS_API_TOKEN', 'OURS_API_VISIBILITY', 'OURS_STATE_DIR', 'OURS_PORT', 'OURS_DAEMON_ID', 'OURS_DATABASE_PROVIDER', 'OURS_DATABASE_URL']) {
49
+ if (effects.env?.[name]?.trim()) throw new InstallUsageError(`${name} conflicts with legacy migration. Clear it before setup; nothing was changed.`);
50
+ }
51
+ plan.legacyPlan = await (effects.inspectLegacyMigration ?? inspectLegacyMigration)(options, effects);
52
+ plan.sourcePolicy = plan.legacyPlan.journal.sourcePolicy ?? policy;
53
+ plan.identityName = plan.legacyPlan.source?.rootName ?? plan.legacyPlan.journal.identities.find(row => row.kind === 'root')?.name;
54
+ validateIdentityName(plan.identityName);
55
+ }
43
56
  if (options.scope !== 'client') {
44
57
  const value = effects.readJson(join(options.stateDir, 'installation.json'));
45
58
  if (value) {
46
59
  plan.existing = validateInstallation(value, options.stateDir);
60
+ if (options.containerEngine && options.containerEngine !== (plan.existing.containerEngine ?? 'docker')) throw new InstallUsageError('Container engine conflicts with retained installation');
47
61
  if (options.mode !== plan.existing.mode) throw new InstallUsageError('The selected mode conflicts with the retained installation; choose its existing mode or a separate empty directory');
48
62
  for (const key of ['port', 'coworkPort', 'messengerPort']) {
49
63
  if (options.explicitPorts?.includes(key) && options[key] !== plan.existing[key]) throw new InstallUsageError(`${key} conflicts with the retained installation`);
50
64
  plan[key] = plan.existing[key];
51
65
  }
52
- if (options.operation === 'install') {
66
+ if (options.operation === 'install' && !options.migrateFrom) {
53
67
  const retained = readObject(effects, plan.existing.sourcesPath, 'Retained source policy');
54
- plan.sourcePolicy = options.scope === 'server' || !options.integrations?.length ? retained : completeReleasePolicy(retained, options.sources ? policy : null);
68
+ plan.sourcePolicy = options.scope === 'server' ? retained : completeReleasePolicy(retained, options.sources ? policy : null);
55
69
  }
56
70
  } else if (options.operation === 'update') {
57
71
  throw new InstallUsageError('Update requires an existing installation.json; choose install for a new installation');
58
72
  }
59
73
  // Reject a local client already attached to another server before changing the server.
60
- const saved = options.scope === 'all' && options.integrations.length ? effects.readManagedClientProfile() : null;
61
- if (saved && (!plan.existing || saved.expectedInstanceId !== plan.existing.instanceId || saved.endpoint !== `http://127.0.0.1:${plan.port}`)) {
74
+ const saved = options.scope === 'all' ? effects.readManagedClientProfile() : null;
75
+ if (saved && (!plan.existing || saved.expectedInstanceId !== plan.existing.instanceId || saved.endpoint !== (plan.existing?.gateway ? gatewayAddress(plan.existing).base + '/daemon' : `http://127.0.0.1:${plan.port}`))) {
62
76
  throw new InstallUsageError('This user already has clients attached to a different server; their saved connection was not changed');
63
77
  }
64
78
  } else {
65
- const profile = validateHostProfile(readObject(effects, options.config, 'Client profile'));
79
+ const profile = validateGatewayClientProfile(readObject(effects, options.config, 'Client profile'));
66
80
  if (!profile) throw new InstallUsageError('Client profile must contain endpoint, expectedInstanceId and credentialPath');
67
81
  if (!effects.readText(profile.credentialPath)?.trim()) throw new InstallUsageError('Client credential file is missing or empty');
68
82
  plan.profile = profile;
69
83
  const saved = effects.readManagedClientProfile();
70
- if (saved && (saved.endpoint !== profile.endpoint || saved.expectedInstanceId !== profile.expectedInstanceId)) throw new InstallUsageError('Managed clients already select another server; existing connection was not changed');
84
+ if (saved && saved.expectedInstanceId !== profile.expectedInstanceId) throw new InstallUsageError('Managed clients already select another server; existing connection was not changed');
71
85
  if (saved && options.operation === 'install' && !options.sources) plan.sourcePolicy = readObject(effects, saved.installer.sourcesPath, 'Retained client source policy');
72
86
  }
73
87
  // Dry-run never spawns a resolver or acquires an installation lock.
74
88
  if (!options.dryRun) {
75
- if (options.scope === 'all' && options.operation === 'update' && options.integrations.length) {
89
+ if (options.scope === 'all' && options.operation === 'update') {
76
90
  const running = await effects.serverLifecycle(plan.existing, 'status', ['daemon']);
77
91
  if (!running.includes('daemon')) throw new InstallUsageError('Full-stack update requires the selected daemon to be running for client verification. Start it first, or use server update to preserve its stopped state.');
78
92
  }
79
93
  if (options.scope !== 'client') await effects.resolveSourcePolicy(plan.sourcePolicy, 'server');
80
- if (options.scope !== 'server' && options.integrations.length) await effects.resolveSourcePolicy(plan.sourcePolicy, 'client', clientPackages(options.integrations));
94
+ if (options.scope !== 'server') await effects.resolveSourcePolicy(plan.sourcePolicy, 'client', clientPackageNames(options.integrations));
81
95
  }
82
96
  return plan;
83
97
  }
@@ -90,7 +104,7 @@ export async function executeSetupPlan(plan, effects, { server = runServerComman
90
104
  if (plan.dryRun) {
91
105
  effects.out(info('Preview only. No packages, identities, credentials or services will be changed.'));
92
106
  if (plan.scope !== 'client') effects.out(info('Server: prerequisites → runtime preparation/update → retained identity/state restoration → readiness.'));
93
- if (plan.scope !== 'server' && plan.integrations.length) effects.out(info('Clients: private connection → exact packages → selected integrations → Fleet settings when selected.'));
107
+ if (plan.scope !== 'server') effects.out(info('Clients: private connection → exact packages → selected integrations → Fleet settings when selected.'));
94
108
  return 0;
95
109
  }
96
110
  let clientConfig = plan.config;
@@ -108,14 +122,14 @@ export async function executeSetupPlan(plan, effects, { server = runServerComman
108
122
  effects.out(ok('Retained identities verified.'));
109
123
  } else effects.out(info('Daemon remains stopped; stored identities are retained and will restore on the next start.'));
110
124
  }
111
- if (plan.scope === 'all' && plan.integrations.length) {
125
+ if (plan.scope === 'all') {
112
126
  clientPolicy = completeReleasePolicy(readObject(effects, record.sourcesPath, 'Server source policy'), plan.sourcePolicy);
113
127
  effects.out(heading('Connect local clients'));
114
128
  const handoff = await effects.prepareLocalClient(record, plan.integrations, plan.fleetSettingsPath);
115
129
  clientConfig = handoff.configPath;
116
130
  }
117
131
  }
118
- if (plan.scope !== 'server' && plan.integrations.length) {
132
+ if (plan.scope !== 'server') {
119
133
  const result = await client({ role: 'client', operation: 'install', config: clientConfig,
120
134
  integrations: plan.integrations, fleetSettingsPath: plan.fleetSettingsPath, sourcePolicy: clientPolicy,
121
135
  preset: true, nonInteractive: !plan.interactive }, effects);
package/lib/target.mjs CHANGED
@@ -1,3 +1,4 @@
1
+ import { serverBase } from './gateway.mjs';
1
2
  // ours-install v3 — argument handling and daemon detection.
2
3
  //
3
4
  // Pure argument handling and daemon-target selection. The orchestrator
@@ -85,17 +86,30 @@ export function validateHostProfile(value) {
85
86
  const mixed = LEGACY_PROFILE_KEYS.filter((key) => Object.hasOwn(value, key));
86
87
  if (mixed.length) throw profileError(`legacy selection keys cannot be mixed with a host profile (${mixed.join(', ')}).`);
87
88
  const { endpoint, expectedInstanceId, credentialPath } = value;
88
- if (typeof endpoint !== 'string' || endpoint.trim() !== endpoint || endpoint === '') throw profileError('endpoint must be a non-empty HTTP origin.');
89
+ if (typeof endpoint !== 'string' || endpoint.trim() !== endpoint || endpoint === '') throw profileError('endpoint must be a non-empty HTTP or HTTPS base URL.');
89
90
  if (typeof expectedInstanceId !== 'string' || !PROFILE_UUID.test(expectedInstanceId)) throw profileError('expectedInstanceId must be a lowercase UUID.');
90
91
  if (typeof credentialPath !== 'string' || credentialPath === '' || !credentialPath.startsWith('/') || resolve(credentialPath) !== credentialPath) {
91
92
  throw profileError('credentialPath must be a normalized absolute path.');
92
93
  }
93
94
  let url;
94
- try { url = new URL(endpoint); } catch { throw profileError('endpoint must be an HTTP origin.'); }
95
- if (url.protocol !== 'http:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
96
- throw profileError('endpoint must be an HTTP origin without credentials, path, query, or fragment.');
95
+ try { url = new URL(endpoint); } catch { throw profileError('endpoint must be an HTTP or HTTPS base URL.'); }
96
+ if ((url.protocol !== 'http:' && url.protocol !== 'https:') || url.username || url.password || url.search || url.hash) {
97
+ throw profileError('endpoint must be an HTTP or HTTPS base URL without credentials, query, or fragment.');
97
98
  }
98
- return { endpoint: url.origin, expectedInstanceId, credentialPath };
99
+ const endpointBase = serverBase(endpoint);
100
+ if (value.serverUrl !== undefined) {
101
+ const serverUrl = serverBase(value.serverUrl);
102
+ if (endpointBase !== serverUrl + '/daemon') throw profileError('endpoint must select serverUrl/daemon.');
103
+ return { serverUrl, endpoint: endpointBase, expectedInstanceId, credentialPath };
104
+ }
105
+ return { endpoint: endpointBase, expectedInstanceId, credentialPath };
106
+ }
107
+
108
+ /** Client installs require the single gateway even when a legacy server profile exists. */
109
+ export function validateGatewayClientProfile(value) {
110
+ if (!value || typeof value.serverUrl !== 'string') throw profileError('serverUrl is required; enable the server gateway and import its client profile. Direct daemon endpoints are not client routes.');
111
+ const serverUrl = serverBase(value.serverUrl);
112
+ return validateHostProfile({ ...value, endpoint: value.endpoint ?? serverUrl + '/daemon' });
99
113
  }
100
114
 
101
115
  export function resolveProfileSelection({ args, env = {}, home = homedir(), exists, readProfile }) {
@@ -454,10 +468,11 @@ export function searchFreePort(isTaken, { floor = FREE_PORT_FLOOR, reserved = IN
454
468
  export function parseNetworkArgs(argv) {
455
469
  if (!['server', 'client'].includes(argv[0])) return null;
456
470
  const [role, operation] = argv;
457
- const operations = role === 'client' ? ['install'] : ['install', 'status', 'start', 'stop', 'restart', 'access-issue', 'access-replace', 'backup', 'restore', 'reset', 'update', 'rebuild'];
471
+ const operations = role === 'client' ? ['install'] : ['install', 'status', 'start', 'stop', 'restart', 'access-issue', 'access-replace', 'backup', 'restore', 'reset', 'update', 'rebuild', 'gateway-enable'];
458
472
  if (!operations.includes(operation)) throw new InstallUsageError(`Unsupported ${role} operation: ${operation ?? '(missing)'}`);
459
473
  const allowed = role === 'client' ? ['config'] : ['state-dir'];
460
- if (role === 'server' && operation === 'install') allowed.push('mode', 'sources', 'migrate');
474
+ if (role === 'server' && operation === 'install') allowed.push('mode', 'sources', 'migrate', 'container-engine');
475
+ if (role === 'server' && ['install', 'gateway-enable'].includes(operation)) allowed.push('server-url');
461
476
  if (operation === 'access-issue') allowed.push('output');
462
477
  if (['access-replace', 'reset'].includes(operation)) allowed.push('confirm');
463
478
  if (['restore', 'update'].includes(operation)) allowed.push('compatible');
@@ -486,13 +501,14 @@ export function parseNetworkArgs(argv) {
486
501
  } else {
487
502
  const value = inline ?? argv[++i];
488
503
  if (!value || value.startsWith('--')) throw new InstallUsageError(`--${name} requires a value`);
489
- result[key] = name === 'mode' ? value : resolve(value);
504
+ result[key] = ['mode', 'container-engine'].includes(name) ? value : name === 'server-url' ? serverBase(value) : resolve(value);
490
505
  }
491
506
  }
492
507
  const required = role === 'client' ? [] : ['stateDir'];
493
508
  if (operation === 'access-issue') required.push('output');
494
509
  if (['access-replace', 'reset'].includes(operation)) required.push('confirm');
495
510
  for (const key of required) if (!result[key]) throw new InstallUsageError(`${operation} requires --${key.replace(/[A-Z]/g, c => '-' + c.toLowerCase())}`);
511
+ if (result.containerEngine !== undefined && (result.mode !== 'docker' || !['docker', 'podman'].includes(result.containerEngine))) throw new InstallUsageError('--container-engine docker|podman requires --mode docker');
496
512
  if (result.mode && !['packages', 'docker'].includes(result.mode)) throw new InstallUsageError('--mode must be packages or docker');
497
513
  return result;
498
514
  }
package/lib/uninstall.mjs CHANGED
@@ -174,13 +174,13 @@ export function planDaemonRemoval({ stateDir, cliStartedIt }) {
174
174
  const service = {
175
175
  id: 'service',
176
176
  unit: unit.ok ? unit.unit : null,
177
- command: ['ours', 'daemon', 'uninstall-service', '--yes', '--state-dir', dir, '--config', join(dir, 'config.json')],
177
+ command: ['ours-daemon', 'uninstall-service', '--yes', '--state-dir', dir, '--config', join(dir, 'config.json')],
178
178
  note: 'removes the unit managed by the ours CLI',
179
179
  };
180
180
  return [
181
181
  service,
182
182
  cliStartedIt
183
- ? { id: 'stop', command: ['ours', 'daemon', 'stop', '--state-dir', dir, '--config', join(dir, 'config.json')] }
183
+ ? { id: 'stop', command: ['ours-daemon', 'stop', '--state-dir', dir, '--config', join(dir, 'config.json')] }
184
184
  : { id: 'stop-external', command: null, continues: true, note: 'this daemon was not started by the CLI; naming its launcher and continuing' },
185
185
  ];
186
186
  }
package/lib/usage.mjs CHANGED
@@ -4,7 +4,7 @@ export const USAGE = `ours-install — interactive setup or complete CLI presets
4
4
  ours-install
5
5
  Opens the console form. Choose all (server + clients), server, or client;
6
6
  runtime, installation directory, identity, integrations and Fleet settings.
7
- Linux x64 recommends native; macOS/Windows recommend Docker. Windows uses WSL.
7
+ Docker provides the full-stack gateway; native mode is server-only. Windows uses WSL.
8
8
 
9
9
  Full stack, with every required answer preset (no prompts):
10
10
  ours-install --mode docker --state-dir /private/ours --identity-name "Your Name" --integrations codex,fleet --fleet-settings /private/fleet.json
@@ -22,17 +22,21 @@ export const USAGE = `ours-install — interactive setup or complete CLI presets
22
22
  --scope all|server|client preset which parts to configure (default all)
23
23
  --action install|update equivalent to the positional operation
24
24
  --mode docker|native packages is also accepted for native mode
25
+ --container-engine docker|podman server container backend (default Docker); retained for maintenance
25
26
  --state-dir PATH installation root; required for all/server
26
27
  --identity-name NAME desired Human name for a fresh server; existing root is retained
27
28
  --integrations LIST codex,claude-code,fleet; use none to skip clients explicitly
28
29
  --fleet-settings PATH JSON settings for Fleet; mandatory for CLI presets selecting Fleet
29
30
  --config PATH complete connection profile for client-only setup
30
31
  --sources PATH explicit full development source policy override
31
- --port N daemon port (default 3050 on a fresh installation)
32
+ --port N public gateway port for Docker (default 3050; e.g. 4050)
33
+ --server-url URL external gateway URL (Docker install; configure authenticated entry separately)
32
34
  --cowork-port N cowork port (default 3052)
33
35
  --messenger-port N messenger port (default 8420)
34
- --compatible required attestation for server updates of retained state
35
- --migrate explicit legacy access migration during install
36
+ --compatible required for server updates and legacy state migration
37
+ --migrate-from CONFIG migrate an existing daemon into a new managed root; install only
38
+ requires an absolute config path and --compatible
39
+ --migrate explicit legacy credential migration; separate from --migrate-from
36
40
  --dry-run show the validated plan without changing anything
37
41
  --help, -h show help
38
42
  --version, -V print installer version
@@ -44,6 +48,7 @@ Fleet is configured but left stopped for operator review.
44
48
 
45
49
  Scoped maintenance:
46
50
  ours-install server status|start|stop|restart|rebuild --state-dir PATH
51
+ ours-install server gateway-enable --state-dir PATH [--server-url URL]
47
52
  ours-install server access-issue --state-dir PATH --output PATH
48
53
  ours-install server access-replace --state-dir PATH --confirm
49
54
  ours-install server backup|restore server|daemon|telegram|cowork|messenger LABEL --state-dir PATH
@@ -0,0 +1,83 @@
1
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join,resolve } from 'node:path';
3
+ import {parseSetupArgs} from './setup-options.mjs';
4
+ /** Base64 is transport, not encryption. Broad provider credentials are never accepted. */
5
+ export function decodeWorkspacePayload(encoded,now=Date.now()) {
6
+ if(typeof encoded!=='string' || encoded.length>32768 || !/^[A-Za-z0-9_-]+$/.test(encoded.trim()))throw Error('Invalid private workspace payload');
7
+ let p;try{p=JSON.parse(Buffer.from(encoded.trim(),'base64url'));}catch{throw Error('Invalid private workspace payload');}
8
+ const allowed=['version','appOrigin','hostname','rootName','name','surname','connectorToken','invitation','serverCid','challenge'];
9
+ if(!p || Object.keys(p).some(k=>!allowed.includes(k)) || p.version!==1 || !['https://app.ours.network','https://app.ours-tunnel.com'].includes(p.appOrigin) || !/^[a-z0-9][a-z0-9-]{2,60}\.ours-tunnel\.com$/.test(p.hostname) || !/^[a-z0-9-]{2,30}@[a-z0-9-]{2,30}$/.test(p.rootName) || !/^[a-f0-9]{64}$/i.test(p.serverCid))throw Error('Invalid workspace payload boundary');
10
+ for(const key of ['name','surname','connectorToken','invitation'])if(typeof p[key]!=='string' || !p[key].trim() || p[key].length>8192 || /[\x00-\x1f\x7f]/.test(p[key]))throw Error('Invalid private workspace payload');
11
+ if(!p.challenge || !['nonce','accountId','workspaceId'].every(k=>/^[\w-]{43}$/.test(p.challenge[k])) || !Number.isFinite(p.challenge.expiresAt) || p.challenge.expiresAt<=now || p.challenge.expiresAt>now+16*60000)throw Error('Workspace challenge expired or invalid');
12
+ return p;
13
+ }
14
+ export function extractWorkspaceArgs(args){
15
+ const flags=['--setup-workspace','--setup-workspace-file','--workspace-fleet-bin','--fleet-settings'];const values={},rest=[];
16
+ for(let i=0;i<args.length;i++){const at=args[i].indexOf('='),flag=at<0?args[i]:args[i].slice(0,at);if(!flags.includes(flag)){rest.push(args[i]);continue;}if(values[flag]!==undefined)throw Error('Duplicate workspace flag');const value=at<0?args[++i]:args[i].slice(at+1);if(!value || value.startsWith('--'))throw Error('Workspace flag requires a value');values[flag]=value;}
17
+ if(values['--setup-workspace'] && values['--setup-workspace-file'])throw Error('Choose one private payload transport');
18
+ return {values,rest};
19
+ }
20
+ export async function runWorkspaceSetup(args,effects,runSetup){
21
+ const migrateAppOrigin=args.includes('--workspace-migrate-app-origin');
22
+ if(args.filter(arg=>arg==='--workspace-migrate-app-origin').length>1)throw Error('Duplicate workspace migration flag');
23
+ const {values,rest}=extractWorkspaceArgs(args.filter(arg=>arg!=='--workspace-migrate-app-origin'));let encoded;
24
+ if(values['--setup-workspace-file']){const path=resolve(values['--setup-workspace-file']),stat=lstatSync(path);if(!stat.isFile() || stat.isSymbolicLink() || stat.nlink!==1 || stat.uid!==process.getuid?.() || stat.size>32768 || (stat.mode&0o077)!==0)throw Error('Setup file must be owned and private (chmod 600)');encoded=readFileSync(path,'utf8').trim();}
25
+ else if(values['--setup-workspace']==='-'){const chunks=[];let bytes=0;for await(const chunk of process.stdin){bytes+=chunk.length;if(bytes>32768)throw Error('Private payload too large');chunks.push(chunk);}encoded=Buffer.concat(chunks).toString().trim();}
26
+ else encoded=values['--setup-workspace'];
27
+ const p=decodeWorkspacePayload(encoded),fleetBin=values['--workspace-fleet-bin'] || 'ours-fleet';
28
+ const parsed=parseSetupArgs(rest,{home:effects.home,validate:false});
29
+ if(parsed.scope==='server')throw Error('Workspace setup requires all or client scope');
30
+ if(parsed.identityName!==undefined || parsed.integrations!==undefined)throw Error('Workspace setup supplies identity and client integration selection');
31
+ // Check feature availability before changing an installation. Task acceptance uses
32
+ // an exact task-built binary; @latest cannot contain an unmerged feature.
33
+ const root=parsed.stateDir || join(effects.home,'.ours-network','workspace'),fleetSettings=values['--fleet-settings'];
34
+ // The saved gateway profile selects the actual host, including non-default server state.
35
+ // Reuse it directly: server/client reinstall would also rewrite or downgrade retained setup.
36
+ const managed=effects.readManagedClientProfile?.();
37
+ const managedPath=join(effects.home,'.ours-client','profile.json');
38
+ const existingProfile=parsed.config || effects.env?.OURS_CONFIG || (managed?managedPath:undefined);
39
+ const existing=Boolean(existingProfile);
40
+ const marker=join(effects.home,'.ours-client','workspace-setup-pending.json');
41
+ let pending;
42
+ if(existsSync(marker)){
43
+ const stat=lstatSync(marker);
44
+ if(!stat.isFile() || stat.isSymbolicLink() || stat.nlink!==1 || stat.uid!==process.getuid?.() || (stat.mode&0o077)!==0 || stat.size>4096)throw Error('Workspace retry marker must be owned and private');
45
+ pending=JSON.parse(readFileSync(marker,'utf8'));
46
+ if(pending.version!==1 || pending.accountId!==p.challenge.accountId || pending.workspaceId!==p.challenge.workspaceId || pending.appOrigin!==p.appOrigin)throw Error('Pending fresh installation belongs to another workspace; identity was not changed. Resume the original workspace, or back up the host and remove only ~/.ours-client/workspace-setup-pending.json to treat it as existing (preserving its profile)');
47
+ }
48
+ const preserveProfile=existing && !pending;
49
+ if(existing && parsed.scope && parsed.scope!=='client')throw Error('Existing workspace setup requires client scope; root identity was not changed');
50
+ if(!existing && !pending && (existsSync(join(root,'installation.json')) || existsSync(join(effects.home,'fleet.yaml'))))throw Error('Existing host requires its gateway client profile; no new root was created');
51
+ const options=[...rest];
52
+ if(!parsed.scope)options.push('--scope',existing?'client':'all');
53
+ if(existing && !parsed.config)options.push('--config',existingProfile);
54
+ if(!existing){if(!parsed.mode)options.push('--mode','docker');if(!parsed.stateDir)options.push('--state-dir',root);options.push('--identity-name',p.rootName);}
55
+ options.push('--integrations','none');
56
+ parseSetupArgs(options,{home:effects.home});
57
+ if(preserveProfile){
58
+ const version=await effects.run(fleetBin,['version','--json'],{sensitive:true});
59
+ let info;try{info=JSON.parse(version.stdout);}catch{}
60
+ if(!version.ok || !info?.capabilities?.includes('workspace.enroll.preserve-profile-v1'))throw Error('Existing-host setup requires a profile-preserving Fleet release; nothing was changed');
61
+ }
62
+ const help=await effects.run(fleetBin,['workspace-enroll','--help'],{sensitive:true});if(!help.ok)throw Error('Fleet workspace enrollment is unavailable');
63
+ const tunnel=await effects.run('cloudflared',['--version'],{sensitive:true});if(!tunnel.ok)throw Error('Tunnel connector is unavailable');
64
+ if(options.includes('--dry-run')){if(!existing)return runSetup(options,effects);return 0;}
65
+ if(!existing){
66
+ if(!pending){mkdirSync(join(effects.home,'.ours-client'),{recursive:true,mode:0o700});writeFileSync(marker,JSON.stringify({version:1,accountId:p.challenge.accountId,workspaceId:p.challenge.workspaceId,appOrigin:p.appOrigin})+'\n',{mode:0o600,flag:'wx'});}
67
+ const result=await runSetup(options,effects);if(result!==0)return result;
68
+ }
69
+ const selected=existingProfile || effects.readManagedClientProfile();if(!selected)throw Error('Workspace client profile was not installed');
70
+ const env={OURS_CONFIG:existingProfile || managedPath};
71
+ for(const key of ['OURS_PORT','OURS_STATE_DIR','OURS_API_TOKEN','OURS_DAEMON_ID','OURS_DAEMON_URL','OURS_DAEMON_CREDENTIAL_PATH'])env[key]=undefined;
72
+ const fleetHome=effects.env?.OURS_FLEET_HOME || effects.home,fleetConfig=join(fleetHome,'fleet.yaml');
73
+ if(!existsSync(fleetConfig)){
74
+ const initArgs=['init',...(fleetSettings?['--settings',fleetSettings]:[])];
75
+ const initialized=fleetSettings?await effects.run(fleetBin,initArgs,{env}):await effects.runInteractive(fleetBin,initArgs,{env});if(!initialized.ok)throw Error('Fleet configuration incomplete');
76
+ }
77
+ mkdirSync(root,{recursive:true,mode:0o700});const temporary=mkdtempSync(join(root,'.workspace-payload-'));chmodSync(temporary,0o700);
78
+ const payloadFile=join(temporary,'payload');writeFileSync(payloadFile,encoded,{mode:0o600,flag:'wx'});
79
+ try{const enrolled=await effects.run(fleetBin,['workspace-enroll','--file',payloadFile,...(preserveProfile?['--preserve-profile']:[]),...(migrateAppOrigin?['--migrate-app-origin']:[])],{env,stream:true,sensitive:true});if(!enrolled.ok)throw Error('Workspace enrollment incomplete; existing identity and profile were retained');}
80
+ finally{rmSync(temporary,{recursive:true,force:true});}
81
+ if(pending || !existing)rmSync(marker);
82
+ effects.out('Workspace proof submitted. Check verified binding/tunnel status in your account, then scan or paste the private device code.');return 0;
83
+ }