@ours.network/install 1.2.1-nightly.6 → 1.2.1-nightly.61

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 (65) hide show
  1. package/GATEWAY_SETUP.md +178 -0
  2. package/README.md +573 -9
  3. package/ROOTLESS_PODMAN_VALIDATION.md +210 -0
  4. package/assets/Dockerfile +15 -12
  5. package/assets/Dockerfile.gateway +5 -0
  6. package/assets/docker-compose.yaml +8 -1
  7. package/assets/fleet-settings.example.json +48 -0
  8. package/assets/gateway-entrypoint.sh +37 -0
  9. package/assets/release-lock.json +1221 -4516
  10. package/assets/release.json +37 -19
  11. package/assets/scripts/build/build-common.mjs +10 -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 +22 -7
  16. package/assets/scripts/maintenance/recover-notifications.mjs +36 -0
  17. package/assets/scripts/maintenance/release-graph.mjs +18 -1
  18. package/assets/scripts/maintenance/state-operation.mjs +76 -8
  19. package/assets/scripts/runtime/README.md +7 -0
  20. package/assets/scripts/runtime/client-setup.mjs +105 -20
  21. package/assets/scripts/runtime/daemon-client-prefix.mjs +115 -0
  22. package/assets/scripts/runtime/dependency-ready.mjs +13 -0
  23. package/assets/scripts/runtime/diagnostics.mjs +72 -0
  24. package/assets/scripts/runtime/entrypoint.sh +5 -1
  25. package/assets/scripts/runtime/health-messenger.mjs +7 -6
  26. package/assets/scripts/runtime/healthcheck.mjs +49 -15
  27. package/assets/scripts/runtime/notifications-gateway.mjs +90 -0
  28. package/assets/scripts/runtime/recover.mjs +202 -0
  29. package/assets/scripts/runtime/start-cowork.sh +5 -0
  30. package/assets/scripts/runtime/start-messenger.sh +29 -4
  31. package/assets/scripts/runtime/start-telegram.sh +5 -0
  32. package/assets/scripts/runtime/supervise.mjs +35 -0
  33. package/assets/sources.json +54 -28
  34. package/install.mjs +7 -2
  35. package/lib/boot-readiness.mjs +96 -0
  36. package/lib/build-transition.mjs +16 -0
  37. package/lib/client-cli.mjs +127 -0
  38. package/lib/container-engine.mjs +127 -0
  39. package/lib/diagnostics.mjs +1 -0
  40. package/lib/docker-conversion-runtime.mjs +7 -4
  41. package/lib/docker-layout-installation.mjs +2 -1
  42. package/lib/docker-recovery.mjs +60 -0
  43. package/lib/docker-runtime-repair.mjs +49 -14
  44. package/lib/effects.mjs +482 -140
  45. package/lib/gateway-transition.mjs +87 -0
  46. package/lib/gateway.mjs +227 -0
  47. package/lib/legacy-migration.mjs +13 -2
  48. package/lib/orchestrate-uninstall.mjs +23 -6
  49. package/lib/orchestrate.mjs +335 -44
  50. package/lib/ownership.mjs +63 -0
  51. package/lib/plan.mjs +37 -11
  52. package/lib/podman-preflight.mjs +40 -0
  53. package/lib/product.mjs +69 -0
  54. package/lib/removal-plan.mjs +437 -0
  55. package/lib/removal.mjs +749 -0
  56. package/lib/server-onboarding.mjs +182 -16
  57. package/lib/server-ports.mjs +17 -0
  58. package/lib/setup-options.mjs +119 -29
  59. package/lib/setup.mjs +93 -22
  60. package/lib/target.mjs +24 -8
  61. package/lib/uninstall.mjs +2 -2
  62. package/lib/usage.mjs +35 -9
  63. package/lib/welcome.mjs +219 -0
  64. package/lib/workspace-setup.mjs +154 -0
  65. package/package.json +4 -2
@@ -1,9 +1,13 @@
1
+ import { gatewayAddress } from './gateway.mjs';
1
2
  /** Human bootstrap and local client handoff through the existing owner interfaces. */
2
3
  import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
4
  import { join, resolve, isAbsolute } from 'node:path';
4
5
  import { randomUUID } from 'node:crypto';
5
6
  import { installationPaths } from './plan.mjs';
6
7
  import { validateHostProfile } from './target.mjs';
8
+ import { isPluginOnly, PLUGIN_ONLY_INTEGRATIONS } from './product.mjs';
9
+ /** Read by Fleet beside the profile credential; bound to one server installation. */
10
+ export const NOTIFICATIONS_PRODUCER_FILE = 'notifications-producer.json';
7
11
 
8
12
  export function validateIdentityName(name) {
9
13
  if (typeof name !== 'string' || [...name].length < 1 || [...name].length > 64 || name !== name.normalize('NFC')
@@ -20,6 +24,17 @@ function privatePath(path, directory = false) {
20
24
  }
21
25
  return stat;
22
26
  }
27
+ /** True only when this server answers the saved credential with 401/403; unreachable is not proof. */
28
+ export async function retainedCredentialRefused(profile, { fetchImpl = fetch, timeoutMs = 5000 } = {}) {
29
+ let token;
30
+ try { token = readFileSync(profile.credentialPath, 'utf8').trim(); } catch { return false; }
31
+ if (!token) return false;
32
+ try {
33
+ const response = await fetchImpl(`${profile.endpoint}/version`, { redirect: 'error', signal: AbortSignal.timeout(timeoutMs), headers: { 'x-ours-api-token': token } });
34
+ return response.status === 401 || response.status === 403;
35
+ } catch { return false; }
36
+ }
37
+
23
38
  function validateRecord(record) {
24
39
  if (!record || !['packages', 'docker'].includes(record.mode) || typeof record.root !== 'string'
25
40
  || !isAbsolute(record.root) || resolve(record.root) !== record.root
@@ -28,16 +43,67 @@ function validateRecord(record) {
28
43
  }
29
44
 
30
45
  export function createServerOnboarding(effects, { compose, localEnv, bin }) {
31
- async function identityCommand(record, args) {
32
- const result = record.mode === 'docker'
33
- ? await compose(record, ['exec', '-T', 'daemon', 'node', '/opt/ours/node_modules/@ours.network/cli/dist/cli.js', ...args, '--config', '/var/lib/ours/config.json', '--state-dir', '/var/lib/ours', '--json'])
34
- : await effects.run(bin(record, 'ours'), [...args, '--config', record.configPath, '--state-dir', installationPaths(record).daemon, '--json'], { env: localEnv(record) });
46
+ // CLI client commands only accept gateway profiles in current releases. Use
47
+ // the installed SDK against the selected local daemon and its private file.
48
+ const identityScript = `
49
+ import { createRequire } from 'node:module';
50
+ import { pathToFileURL } from 'node:url';
51
+ import { randomUUID } from 'node:crypto';
52
+ const selection = JSON.parse(process.argv[1]);
53
+ const require = createRequire(selection.anchor);
54
+ const { attachOursClient } = await import(pathToFileURL(require.resolve('@ours.network/sdk/client')).href);
55
+ const client = await attachOursClient({ endpoint: selection.endpoint,
56
+ expectedInstanceId: selection.instanceId, credentialPath: selection.credentialPath,
57
+ sessionMode: 'external', leaseToken: randomUUID(), env: {} });
58
+ // The lease this short-lived client takes is released exactly once. An operation is not reported as done
59
+ // while that release is incomplete, and what failed first is what is reported.
60
+ let output, released = false;
61
+ try {
62
+ const result = selection.operation === 'list' ? await client.listIdentities()
63
+ : selection.operation === 'create-role' ? { created: await client.createIdentity({ name: selection.name, bio: '',
64
+ exposeLocal: true, localAutoAccept: true }), current: await client.currentIdentity() }
65
+ : selection.operation === 'describe-role' ? (await client.chooseIdentity({ name: selection.name, force: false }),
66
+ { current: await client.currentIdentity() })
67
+ : await client.createRootIdentity({ name: selection.name, bio: '',
68
+ exposeLocal: true, localAutoAccept: true, skipIfRootExists: true });
69
+ released = true;
70
+ const release = await client.releaseLease();
71
+ output = release?.failed > 0 ? { onboardingError: 'LEASE_RELEASE_INCOMPLETE' } : result;
72
+ } catch (error) {
73
+ output = { onboardingError: error.code || 'OWNER_OPERATION_FAILED' };
74
+ if (!released) try { await client.releaseLease(); } catch {}
75
+ } finally {
76
+ try { await client.close(); } catch {}
77
+ }
78
+ process.stdout.write(JSON.stringify(output));
79
+ `;
80
+ async function identityCommand(record, operation, name) {
81
+ validateRecord(record);
82
+ const docker = record.mode === 'docker';
83
+ const selection = {
84
+ operation, ...(name === undefined ? {} : { name }),
85
+ endpoint: `http://127.0.0.1:${docker ? 3050 : record.port}`,
86
+ instanceId: record.instanceId,
87
+ credentialPath: docker ? '/var/lib/ours/daemon-token' : join(installationPaths(record).daemon, 'daemon-token'),
88
+ anchor: docker ? '/opt/ours/package.json' : join(record.workDir, 'package.json'),
89
+ };
90
+ const args = ['--input-type=module', '-e', identityScript, JSON.stringify(selection)];
91
+ const result = docker
92
+ ? await compose(record, ['exec', '-T', 'daemon', 'node', ...args])
93
+ : await effects.run(process.execPath, args, { env: localEnv(record), sensitive: true });
35
94
  if (result.code !== undefined && result.code !== 0) throw new Error('Owner identity operation failed');
36
- try { return JSON.parse(result.stdout); }
95
+ let value;
96
+ try { value = JSON.parse(result.stdout); }
37
97
  catch { throw new Error('Owner identity operation returned malformed JSON'); }
98
+ if (value?.onboardingError) {
99
+ const error = new Error('Owner identity operation failed');
100
+ error.code = value.onboardingError;
101
+ throw error;
102
+ }
103
+ return value;
38
104
  }
39
105
  async function identities(record) {
40
- const rows = await identityCommand(record, ['identity', 'list']);
106
+ const rows = await identityCommand(record, 'list');
41
107
  if (!Array.isArray(rows) || rows.some(row => !row || typeof row.name !== 'string'
42
108
  || (!['root', 'role'].includes(row.kind) && !['reconciling', 'awaiting-root', 'migration-failed', 'refresh-failed'].includes(row.status))
43
109
  || (row.kind && (typeof row.cid !== 'string' || !row.cid)))) throw new Error('Owner identity list is malformed');
@@ -59,10 +125,11 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
59
125
  if (prior.rows.some(row => row.name === name)) throw new Error('Requested Human identity name already exists; no identity was changed');
60
126
  effects.out?.(`Creating Human identity ${name}; retaining ${prior.rows.length} existing identities.`);
61
127
  try {
62
- await identityCommand(record, ['identity', 'create-root', '--name', name, '--skip-if-root-exists', 'true']);
128
+ await identityCommand(record, 'create-root', name);
63
129
  } catch (error) {
64
- // ROOT_EXISTS is currently a CLI error. A concurrent creator is safe only
130
+ // A concurrent creator is safe only
65
131
  // when the authoritative list now contains a root; other errors stay errors.
132
+ if (error.code !== 'ROOT_EXISTS') throw error;
66
133
  const after = await identities(record);
67
134
  if (after.root) return retained(after);
68
135
  throw error;
@@ -73,16 +140,100 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
73
140
  effects.out?.(`Human identity ${after.root.name} is ready.`);
74
141
  return { name: after.root.name, cid: after.root.cid, created: true };
75
142
  },
143
+ /**
144
+ * The person's own identity under the Human root, which Messenger runs as. An identity of that name is
145
+ * used only when the daemon itself describes it as a permanent role of exactly the retained root;
146
+ * nothing else is renamed or adopted.
147
+ */
148
+ async serverEnsureMessengerIdentity(record, name) {
149
+ validateRecord(record);
150
+ validateIdentityName(name);
151
+ const listed = row => row?.kind === 'role' && row.temp === null && typeof row.cid === 'string';
152
+ const taken = () => new Error('Requested Messenger identity name is already used by another identity; no identity was changed');
153
+ const prior = await identities(record);
154
+ if (!prior.root) throw new Error('Messenger identity requires the Human identity; no identity was changed');
155
+ // The list has no parent column. What the daemon describes for the identity, bound for a moment, names its root.
156
+ const under = (current, row) => current?.name === name && current.temporary === false && current.isRoot === false
157
+ && current.described === true && typeof current.roleId === 'string' && current.roleId !== ''
158
+ && typeof current.cid === 'string' && current.cid === row.cid
159
+ && typeof current.rootCid === 'string' && current.rootCid.toLowerCase() === String(prior.root.cid).toLowerCase();
160
+ const adopt = async rows => {
161
+ const row = rows.rows.find(candidate => candidate.name === name);
162
+ if (rows.root?.cid !== prior.root.cid || !listed(row)) throw taken();
163
+ const { current } = await identityCommand(record, 'describe-role', name);
164
+ if (!under(current, row)) throw taken();
165
+ return row;
166
+ };
167
+ if (prior.rows.some(row => row.name === name)) {
168
+ const row = await adopt(prior);
169
+ effects.out?.(`Retained Messenger identity ${name}.`);
170
+ return { name, cid: row.cid, created: false };
171
+ }
172
+ effects.out?.(`Creating Messenger identity ${name} under ${prior.root.name}; retaining ${prior.rows.length} existing identities.`);
173
+ let result;
174
+ try {
175
+ result = await identityCommand(record, 'create-role', name);
176
+ } catch (error) {
177
+ // Only a name collision can mean a concurrent creator; any other failure is reported as it is.
178
+ if (error.code !== 'NAME_TAKEN') throw error;
179
+ // That creator is accepted only when the authoritative list now shows the name under the same root.
180
+ const after = await identities(record);
181
+ if (!after.rows.some(row => row.name === name)) throw error;
182
+ const row = await adopt(after);
183
+ return { name, cid: row.cid, created: false };
184
+ }
185
+ const after = await identities(record);
186
+ const row = after.rows.find(candidate => candidate.name === name);
187
+ if (result?.created?.hierarchy !== 'role' || result.created.underRoot !== prior.root.name || after.root?.cid !== prior.root.cid
188
+ || !listed(row) || result.created.info?.cid !== row.cid || !under(result.current, row))
189
+ throw new Error('Messenger identity creation completed without a usable identity under the Human identity');
190
+ effects.out?.(`Messenger identity ${name} is ready.`);
191
+ return { name, cid: row.cid, created: true };
192
+ },
193
+ async serverEnsureHumanProfile(record, human) {
194
+ validateRecord(record);
195
+ for (const key of ['name', 'surname']) if (typeof human[key] !== 'string' || !human[key].trim() || human[key].length > 100 || /[\x00-\x1f\x7f]/.test(human[key])) throw new Error('Invalid Messenger human profile');
196
+ // Messenger owns the profile lifecycle. Never rename the daemon root or
197
+ // overwrite a profile already present on a retained installation.
198
+ const script = `
199
+ import { readFileSync } from 'node:fs';
200
+ const selection = JSON.parse(process.argv[1]);
201
+ const token = readFileSync(selection.credentialPath, 'utf8').trim();
202
+ const base = selection.base;
203
+ async function request(path, value) {
204
+ const response = await fetch(base + '/api/' + path, { method: value === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(15000), headers: { 'X-Ours-Api-Token': token, ...(value === undefined ? {} : { 'Content-Type': 'application/json', Origin: selection.origin, 'X-Ours-Messenger-CSRF': '1' }) }, ...(value === undefined ? {} : { body: JSON.stringify(value) }) });
205
+ if (!response.ok) { await response.body?.cancel(); throw new Error('Messenger human profile operation failed (HTTP ' + response.status + ')'); }
206
+ return response.json();
207
+ }
208
+ const identity = await request('identity');
209
+ if (identity.humanProfile) process.stdout.write('Retained Messenger Name and Surname.');
210
+ else { await request('identity/profile', selection.human); process.stdout.write('Messenger Name and Surname initialized.'); }
211
+ `;
212
+ const docker = record.mode === 'docker';
213
+ const selection = { base: `http://127.0.0.1:${docker ? 8420 : record.messengerPort}`,
214
+ // Behind the gateway Messenger accepts mutations only from the gateway origin.
215
+ origin: record.gateway ? gatewayAddress(record).origin : `http://127.0.0.1:${record.messengerPort}`,
216
+ credentialPath: docker ? '/credentials/messenger/daemon-token' : installationPaths(record).credentials.messenger,
217
+ human: { name: human.name, surname: human.surname } };
218
+ const args = ['--input-type=module', '-e', script, JSON.stringify(selection)];
219
+ const result = docker ? await compose(record, ['exec', '-T', 'messenger', 'node', ...args])
220
+ : await effects.run(process.execPath, args, { env: localEnv(record), sensitive: true });
221
+ if (result.code !== undefined && result.code !== 0) throw new Error('Messenger human profile initialization failed');
222
+ effects.out?.(result.stdout);
223
+ },
76
224
  async prepareLocalClient(record, integrations, fleetSettingsPath) {
77
225
  validateRecord(record);
78
- if (!Array.isArray(integrations) || !integrations.length || new Set(integrations).size !== integrations.length
226
+ if (!Array.isArray(integrations) || new Set(integrations).size !== integrations.length
79
227
  || integrations.some(name => !['codex', 'claude-code', 'fleet'].includes(name))) throw new Error('Client integrations must select codex, claude-code and/or fleet');
228
+ if (isPluginOnly(record) && integrations.some(name => !PLUGIN_ONLY_INTEGRATIONS.includes(name))) throw new Error('Collaboration tools connect Claude Code and Codex; Fleet is part of the complete workspace');
80
229
  if (fleetSettingsPath !== undefined) {
81
230
  if (typeof fleetSettingsPath !== 'string' || !isAbsolute(fleetSettingsPath) || resolve(fleetSettingsPath) !== fleetSettingsPath) throw new Error('Fleet settings path must be absolute');
82
231
  const settings = JSON.parse(readFileSync(fleetSettingsPath, 'utf8'));
83
232
  if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('Fleet settings must be a JSON object');
84
233
  }
85
- const endpoint = `http://127.0.0.1:${record.port}`;
234
+ // Plugin-only clients reach the daemon's own client prefix on the published loopback port.
235
+ const serverUrl = record.gateway ? gatewayAddress(record).base : isPluginOnly(record) ? `http://127.0.0.1:${record.port}` : undefined;
236
+ const endpoint = serverUrl ? `${serverUrl}/daemon` : `http://127.0.0.1:${record.port}`;
86
237
  const current = effects.readManagedClientProfile();
87
238
  if (current && (current.endpoint !== endpoint || current.expectedInstanceId !== record.instanceId)) throw new Error('Managed client already selects another server; no credential was issued');
88
239
  privatePath(record.root, true);
@@ -93,16 +244,31 @@ export function createServerOnboarding(effects, { compose, localEnv, bin }) {
93
244
  const published = join(root, 'issued-' + randomUUID());
94
245
  const credential = join(stage, 'credential');
95
246
  try {
96
- effects.out?.('Issuing a separate local client credential with the retained server authority.');
97
- try { await effects.serverAccess(record, 'access-issue', { output: credential }); }
98
- catch { throw new Error('Client credential issuance failed; existing profiles were retained'); }
99
- const stat = privatePath(credential);
100
- if (stat.size > 4096 || !readFileSync(credential, 'utf8').trim()) throw new Error('Issued client credential is empty or invalid');
247
+ // After `server access-replace` the retained credential is refused by this
248
+ // same server; a repeat setup replaces it rather than keeping a dead one.
249
+ const replace = current && effects.credentialRefused ? await effects.credentialRefused(current) : false;
250
+ if (replace) effects.out?.('The saved client credential is no longer accepted by this server; issuing a replacement.');
251
+ if (!current || replace) {
252
+ effects.out?.('Issuing a separate local client credential with the retained server authority.');
253
+ try { await effects.serverAccess(record, 'access-issue', { output: credential }); }
254
+ catch (cause) { throw new Error('Client credential issuance failed; existing profiles were retained', { cause }); }
255
+ }
256
+ const retainedCredential = current && !replace ? current.credentialPath : credential;
257
+ const stat = privatePath(retainedCredential);
258
+ if (stat.size > 4096 || !readFileSync(retainedCredential, 'utf8').trim()) throw new Error('Issued client credential is empty or invalid');
101
259
  const profile = {
102
- ...validateHostProfile({ endpoint, expectedInstanceId: record.instanceId, credentialPath: join(published, 'credential') }),
260
+ ...validateHostProfile({ ...(serverUrl ? { serverUrl } : {}), endpoint, expectedInstanceId: record.instanceId, credentialPath: current && !replace ? current.credentialPath : join(published, 'credential') }),
103
261
  installer: { integrations: [...integrations], ...(fleetSettingsPath !== undefined ? { fleetSettingsPath } : {}) },
104
262
  };
105
263
  writeFileSync(join(stage, 'profile.json'), JSON.stringify(profile, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
264
+ // Fleet on this host produces agent notifications through the server gateway.
265
+ // A runtime without the notification service prepares no producer credential.
266
+ const issued = record.gateway ? await compose(record, ['run', '--rm', '--no-deps', '-T', '--entrypoint', 'cat', 'messenger', '/var/lib/ours-notifications/fleet-producer'], { sensitive: true, allowCodes: [1] }) : null;
267
+ if (issued && (issued.code ?? 0) === 0) {
268
+ const token = String(issued.stdout ?? '');
269
+ if (!/^[A-Za-z0-9_-]{32,256}$/.test(token)) throw new Error('Notification producer credential is invalid; repeat server install');
270
+ writeFileSync(join(stage, NOTIFICATIONS_PRODUCER_FILE), JSON.stringify({ schema: 1, serverUrl, expectedInstanceId: record.instanceId, token }) + '\n', { flag: 'wx', mode: 0o600 });
271
+ }
106
272
  // Publish the complete pair in one rename. Managed-default activation and
107
273
  // package/source selection remain the normal client installer's job.
108
274
  renameSync(stage, published);
@@ -0,0 +1,17 @@
1
+ /** Fresh selections only; retained installations keep their recorded addresses. */
2
+ export function selectServerPorts(record, isTaken, explicitPorts = [], out = () => {}) {
3
+ const reserved = new Set([3051]);
4
+ for (const key of ['port', 'coworkPort', 'messengerPort']) {
5
+ const preferred = record[key];
6
+ let selected = preferred;
7
+ while (reserved.has(selected) || isTaken(selected)) {
8
+ if (explicitPorts.includes(key)) throw Error(`Requested ${key} ${preferred} is unavailable; select another explicit port`);
9
+ selected++;
10
+ if (selected > 65535) throw Error(`No free loopback port available for ${key}`);
11
+ }
12
+ reserved.add(selected);
13
+ record[key] = selected;
14
+ if (selected !== preferred) out(`${key}: ${preferred} is unavailable; selected loopback port ${selected}`);
15
+ }
16
+ return record;
17
+ }
@@ -1,21 +1,25 @@
1
+ import { hostname } from 'node:os';
2
+ import { serverBase } from './gateway.mjs';
1
3
  import { join, resolve, isAbsolute, dirname } from 'node:path';
4
+ import { PRODUCTS, PLUGIN_ONLY, PLUGIN_ONLY_INTEGRATIONS } from './product.mjs';
2
5
 
3
6
  const scopes = ['all', 'server', 'client'];
4
7
  const integrations = ['codex', 'claude-code', 'fleet'];
5
8
  const valueFlags = new Map(Object.entries({
6
- '--scope': 'scope', '--action': 'operation', '--mode': 'mode', '--state-dir': 'stateDir',
7
- '--identity-name': 'identityName', '--integrations': 'integrations', '--fleet-settings': 'fleetSettingsPath',
9
+ '--container-engine': 'containerEngine', '--server-url': 'serverUrl', '--scope': 'scope', '--action': 'operation', '--mode': 'mode', '--state-dir': 'stateDir',
10
+ '--username': 'localUsername', '--name': 'name', '--surname': 'surname', '--hostname': 'hostname',
11
+ '--identity-name': 'identityName', '--integrations': 'integrations', '--fleet-settings': 'fleetSettingsPath', '--fleet-task-workflow': 'fleetTaskWorkflowAgents',
8
12
  '--config': 'config', '--sources': 'sources', '--migrate-from': 'migrateFrom', '--port': 'port', '--cowork-port': 'coworkPort', '--messenger-port': 'messengerPort',
9
13
  }));
10
- const boolFlags = new Map([['--compatible', 'compatible'], ['--dry-run', 'dryRun'], ['--migrate', 'migrate']]);
11
- const allowed = new Set([...valueFlags.values(), ...boolFlags.values(), 'interactive', 'explicitPorts']);
14
+ const boolFlags = new Map([['--compatible', 'compatible'], ['--dry-run', 'dryRun'], ['--migrate', 'migrate'], ['--disable-fleet-agents-setup', 'disableFleetAgentsSetup']]);
15
+ const allowed = new Set([...valueFlags.values(), ...boolFlags.values(), 'interactive', 'explicitPorts', 'product']);
12
16
  const defaults = { port: 3050, coworkPort: 3052, messengerPort: 8420 };
13
17
  const paths = ['stateDir', 'config', 'sources', 'fleetSettingsPath', 'migrateFrom'];
14
18
  const nonempty = value => typeof value === 'string' && value.trim().length > 0 && !/[\x00-\x1f\x7f]/.test(value);
15
19
 
16
20
  export function recommendedMode({ platform, arch, release = '' } = {}) {
17
21
  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.' };
22
+ if (platform === 'linux' && arch === 'x64') return { mode: 'docker', reason: 'Docker provides the integrated gateway for full-stack setup; native mode is server-only.' };
19
23
  if (platform === 'darwin') return { mode: 'docker', reason: 'Docker is recommended on macOS.' };
20
24
  if (platform === 'win32') return { mode: 'docker', reason: 'Docker is recommended on Windows; run the installer inside WSL with Docker Desktop.' };
21
25
  return { mode: 'docker', reason: 'Docker is recommended for this platform.' };
@@ -31,17 +35,65 @@ export function validateSetupOptions(input, { interactive = input?.interactive =
31
35
  const client = options.scope !== 'server';
32
36
  if (options.migrateFrom !== undefined && (!server || options.operation !== 'install')) throw new Error('--migrate-from requires server or all scope and operation install');
33
37
  if (options.migrateFrom !== undefined && (!nonempty(options.migrateFrom) || !isAbsolute(options.migrateFrom))) throw new Error('--migrate-from requires an absolute daemon config path');
38
+ const suppliedHuman = ['localUsername', 'name', 'surname'].some(key => options[key] !== undefined);
39
+ if (suppliedHuman) {
40
+ for (const key of ['localUsername', 'name', 'surname']) if (!nonempty(options[key])) throw new Error(`Missing human profile option: ${key}`);
41
+ if (!/^[a-z0-9][a-z0-9-]{0,29}$/.test(options.localUsername)) throw new Error('Local username must contain 1–30 lowercase letters, digits or hyphens');
42
+ for (const key of ['name', 'surname']) {
43
+ if (options[key].trim().length > 100) throw new Error(`${key} must contain at most 100 characters`);
44
+ options[key] = options[key].trim();
45
+ }
46
+ // Name and Surname together name the person's own identity, which Messenger runs as.
47
+ const person = `${options.name} ${options.surname}`;
48
+ if ([...person].length > 64 || person !== person.normalize('NFC') || /[\\/\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}]/u.test(person))
49
+ throw new Error('Name and Surname together must contain at most 64 NFC characters, including the space between them, without slashes or control characters');
50
+ options.hostname = options.hostname?.trim() || defaultHostname();
51
+ 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
+ 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
+ } else if (options.hostname !== undefined) throw new Error('--hostname requires username, name and surname');
56
+ if (options.disableFleetAgentsSetup !== undefined && typeof options.disableFleetAgentsSetup !== 'boolean') throw new Error('disableFleetAgentsSetup must be a boolean');
57
+ if (options.disableFleetAgentsSetup && options.fleetSettingsPath) throw new Error('--disable-fleet-agents-setup conflicts with --fleet-settings');
58
+ if (options.fleetTaskWorkflowAgents !== undefined) {
59
+ // Fleet owns what the workflow is; the installer only carries which agents the operator named.
60
+ const agents = options.fleetTaskWorkflowAgents;
61
+ if (!Array.isArray(agents) || !agents.length || agents.some(name => typeof name !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) || new Set(agents).size !== agents.length)
62
+ throw new Error('--fleet-task-workflow requires unique Fleet agent names separated by commas');
63
+ if (!options.integrations?.includes?.('fleet')) throw new Error('--fleet-task-workflow requires the fleet integration');
64
+ if (options.disableFleetAgentsSetup) throw new Error('--fleet-task-workflow conflicts with --disable-fleet-agents-setup: no agents are configured by this run');
65
+ options.fleetTaskWorkflowAgents = [...agents];
66
+ }
67
+ if (options.product !== undefined) {
68
+ if (!PRODUCTS.includes(options.product)) throw new Error('Product must be workspace or plugin-only');
69
+ if (options.product === PLUGIN_ONLY) {
70
+ if (!server) throw new Error('--plugin-only installs the daemon on this computer; it cannot be combined with client scope');
71
+ 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
+ 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
+ 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']]) {
75
+ if (options[key] !== undefined && options[key] !== false) throw new Error(`${flag} belongs to the complete workspace and cannot be combined with --plugin-only`);
76
+ }
77
+ if (options.explicitPorts?.some?.(key => key !== 'port')) throw new Error('--plugin-only uses one port; --cowork-port and --messenger-port do not apply');
78
+ options.mode ??= 'docker';
79
+ }
80
+ }
34
81
  const missing = [];
35
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);
36
83
  if (client && options.integrations === undefined) missing.push('--integrations (use none to skip)');
37
84
  if (!server && !nonempty(options.config)) missing.push('--config');
38
85
  if (server && (options.operation === 'update' || options.migrateFrom !== undefined) && options.compatible !== true) missing.push('--compatible');
39
- if (Array.isArray(options.integrations) && options.integrations.includes('fleet') && !interactive && !nonempty(options.fleetSettingsPath)) missing.push('--fleet-settings');
86
+ if (Array.isArray(options.integrations) && options.integrations.includes('fleet') && !interactive && !options.disableFleetAgentsSetup && !nonempty(options.fleetSettingsPath)) missing.push('--fleet-settings');
40
87
  if (missing.length) throw new Error(`Missing required setup options: ${missing.join(', ')}`);
41
88
  if (options.mode === 'native') options.mode = 'packages';
42
89
  if (server && !['packages', 'docker'].includes(options.mode)) throw new Error('Mode must be packages (or native) or docker');
90
+ if (options.containerEngine !== undefined && (!server || options.mode !== 'docker' || !['docker', 'podman'].includes(options.containerEngine))) throw new Error('--container-engine docker|podman requires server container mode');
91
+ if (options.serverUrl !== undefined) {
92
+ if (!server || options.mode !== 'docker' || options.operation !== 'install') throw new Error('--server-url requires Docker server installation');
93
+ options.serverUrl = serverBase(options.serverUrl);
94
+ }
43
95
  if (server && options.config !== undefined) throw new Error('--config is only valid for client scope');
44
- if (!server) for (const key of ['mode', 'stateDir', 'identityName', ...Object.keys(defaults), 'compatible', 'migrate']) {
96
+ if (!server) for (const key of ['mode', 'stateDir', 'identityName', 'localUsername', 'name', 'surname', 'hostname', ...Object.keys(defaults), 'compatible', 'migrate']) {
45
97
  if (options[key] !== undefined) throw new Error(`${key} is only valid for server or all scope`);
46
98
  }
47
99
  if (!client && (options.integrations !== undefined || options.fleetSettingsPath !== undefined)) throw new Error('--integrations and --fleet-settings require all or client scope');
@@ -84,7 +136,7 @@ function expandPaths(options, home) {
84
136
  return output;
85
137
  }
86
138
 
87
- export function parseSetupArgs(argv, { home } = {}) {
139
+ export function parseSetupArgs(argv, { home, validate = true } = {}) {
88
140
  if (!Array.isArray(argv) || !argv.every(arg => typeof arg === 'string')) throw new Error('Arguments must be strings');
89
141
  const options = { interactive: false, explicitPorts: [] };
90
142
  const seen = new Set();
@@ -98,6 +150,10 @@ export function parseSetupArgs(argv, { home } = {}) {
98
150
  if (!arg.startsWith('-')) { positional.push(arg); continue; }
99
151
  const equal = arg.indexOf('=');
100
152
  const flag = equal < 0 ? arg : arg.slice(0, equal);
153
+ if (flag === '--plugin-only') {
154
+ if (equal >= 0) throw new Error(`${flag} takes no value`);
155
+ put('product', PLUGIN_ONLY); continue;
156
+ }
101
157
  if (boolFlags.has(flag)) {
102
158
  if (equal >= 0) throw new Error(`${flag} takes no value`);
103
159
  put(boolFlags.get(flag), true); continue;
@@ -107,6 +163,7 @@ export function parseSetupArgs(argv, { home } = {}) {
107
163
  if (!nonempty(value) || value.startsWith('--')) throw new Error(`${flag} requires a value`);
108
164
  const key = valueFlags.get(flag);
109
165
  if (key === 'integrations') put(key, value === 'none' ? [] : value.split(',').map(item => item.trim()));
166
+ else if (key === 'fleetTaskWorkflowAgents') put(key, value.split(',').map(item => item.trim()));
110
167
  else if (Object.hasOwn(defaults, key)) {
111
168
  if (!/^[1-9]\d*$/.test(value)) throw new Error(`${flag} requires an integer port`);
112
169
  put(key, Number(value)); options.explicitPorts.push(key);
@@ -115,30 +172,34 @@ export function parseSetupArgs(argv, { home } = {}) {
115
172
  if (positional.length && scopes.includes(positional[0])) put('scope', positional.shift());
116
173
  if (positional.length && ['install', 'update'].includes(positional[0])) put('operation', positional.shift());
117
174
  if (positional.length) throw new Error(`Unexpected setup argument: ${positional.join(' ')}`);
118
- return validateSetupOptions(expandPaths(options, home), { interactive: false });
175
+ return validate ? validateSetupOptions(expandPaths(options, home), { interactive: false }) : expandPaths(options, home);
176
+ }
177
+
178
+ export function defaultHostname() {
179
+ return hostname().toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/^[^a-z0-9]+/, '').slice(0, 30) || 'workspace';
119
180
  }
120
181
 
121
- export async function collectSetupOptions(effects) {
182
+ export async function collectSetupOptions(effects, presets = {}) {
122
183
  if (effects.interactive !== true) throw new Error('Interactive setup requires a TTY; provide the complete CLI options instead');
123
- const options = { interactive: true, explicitPorts: [] };
184
+ const options = { ...presets, interactive: true, explicitPorts: presets.explicitPorts ?? [] };
124
185
  const scopeChoices = [
125
186
  { value: 'all', label: 'Everything on this computer' },
126
187
  { value: 'server', label: 'Server only' },
127
188
  { value: 'client', label: 'Connect this computer to an existing server' },
128
189
  ];
129
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.');
130
- options.scope = await effects.select('What would you like to set up?', scopeChoices, 'all');
191
+ options.scope ??= await effects.select('What would you like to set up?', scopeChoices, 'all');
131
192
  if (!scopes.includes(options.scope)) throw new Error('Scope must be all, server, or client');
132
193
  let existing;
133
194
  let pendingMigration;
134
195
  if (options.scope !== 'client') {
135
196
  const recommendedRoot = join(effects.home, '.ours-install');
136
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.`);
137
- const location = await effects.select('Where should server programs and data be stored?', [
198
+ const location = options.stateDir ? 'preset' : await effects.select('Where should server programs and data be stored?', [
138
199
  { value: 'recommended', label: `Use the recommended folder (${recommendedRoot})` },
139
200
  { value: 'custom', label: 'Choose another folder' },
140
201
  ], 'recommended');
141
- options.stateDir = location === 'recommended' ? recommendedRoot : await effects.askLine('Folder for server programs and data: ', recommendedRoot);
202
+ options.stateDir ??= location === 'recommended' ? recommendedRoot : await effects.askLine('Folder for server programs and data: ', recommendedRoot);
142
203
  options.stateDir = expandPaths({ stateDir: options.stateDir }, effects.home).stateDir;
143
204
  existing = effects.readJson(join(options.stateDir, 'installation.json'));
144
205
  const migrationJournal = existing?.legacyMigrationSource ? effects.readJson(join(options.stateDir, 'legacy-migration.json')) : null;
@@ -150,7 +211,7 @@ export async function collectSetupOptions(effects) {
150
211
  ? 'This folder already contains an installation. Update selects this installer’s release while retaining state; repair reinstalls the retained package selection.'
151
212
  : options.scope === 'client' ? 'Install connects your selected apps. Update refreshes their packages while keeping the server connection.'
152
213
  : 'Install creates a managed installation in the selected folder. Update requires an installation already recorded there.');
153
- options.operation = !existing && options.scope !== 'client' ? 'install' : await effects.select('What should happen?', [
214
+ options.operation ??= !existing && options.scope !== 'client' ? 'install' : await effects.select('What should happen?', [
154
215
  { value: 'install', label: pendingMigration ? 'Resume the unfinished migration' : existing ? 'Repair this installation' : 'Install and configure' },
155
216
  { value: 'update', label: 'Update an existing installation' },
156
217
  ], existing && !pendingMigration ? 'update' : 'install');
@@ -160,7 +221,8 @@ export async function collectSetupOptions(effects) {
160
221
  const legacyState = nonempty(legacy?.stateDir) ? legacy.stateDir
161
222
  : legacy && legacy.stateDir === undefined && nonempty(effects.readJson(join(effects.home, '.ours', 'root.json'))?.name)
162
223
  ? join(effects.home, '.ours') : null;
163
- if (pendingMigration) options.migrateFrom = pendingMigration;
224
+ if (options.migrateFrom) { /* Explicit selection is validated below. */ }
225
+ else if (pendingMigration) options.migrateFrom = pendingMigration;
164
226
  else if (legacyState) {
165
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.`);
166
228
  if (await effects.ask('Upgrade this existing ours installation and keep its data?', true)) options.migrateFrom = defaultConfig;
@@ -184,41 +246,69 @@ export async function collectSetupOptions(effects) {
184
246
  if (!nonempty(root?.name)) throw new Error('Cannot read the existing Human identity name; choose the configuration file for a complete existing installation');
185
247
  options.identityName = root.name;
186
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.`);
187
- options.compatible = await effects.ask('Proceed with this release and keep the original state as a recovery copy?', false);
249
+ options.compatible ??= await effects.ask('Proceed with this release and keep the original state as a recovery copy?', false);
188
250
  if (!options.compatible) throw new Error('Migration requires explicit compatibility confirmation (--compatible)');
189
251
  }
190
252
  }
191
253
  if (options.scope !== 'client') {
192
254
  const recommendation = recommendedMode({ ...effects.platform, arch: effects.platform?.arch ?? process.arch });
193
- 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.`);
194
- options.mode = await effects.select('How should the server run?', [
195
- { value: 'packages', label: 'Native packages' }, { value: 'docker', label: 'Docker' },
196
- ], existing?.mode ?? recommendation.mode);
255
+ // Native runs the server only: local clients need the container gateway. A retained
256
+ // 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)
259
+ 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);
267
+ options.mode = runtime === 'podman' ? 'docker' : runtime;
268
+ if (runtime === 'podman') options.containerEngine = 'podman';
197
269
  if (!options.migrateFrom) {
198
- 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.');
199
- options.identityName = await effects.askLine('What name should others see? ', existing?.messengerIdentity ?? effects.username?.() ?? 'me');
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): ', '');
200
290
  }
201
- for (const [key, fallback] of Object.entries(defaults)) options[key] = existing?.[key] ?? fallback;
291
+ for (const [key, fallback] of Object.entries(defaults)) options[key] ??= existing?.[key] ?? fallback;
202
292
  if (options.operation === 'update') {
203
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.');
204
- options.compatible = await effects.ask('Proceed with this update and keep a recovery backup?', false);
294
+ options.compatible ??= await effects.ask('Proceed with this update and keep a recovery backup?', false);
205
295
  }
206
296
  } else {
207
297
  const savedProfile = join(effects.home, '.ours-client', 'profile.json');
208
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.');
209
- const connection = await effects.select('Which server connection should this computer use?', [
299
+ const connection = options.config ? 'preset' : await effects.select('Which server connection should this computer use?', [
210
300
  { value: 'saved', label: 'Use the saved server connection' }, { value: 'file', label: 'Choose a connection profile file' },
211
301
  ], effects.readJson(savedProfile) ? 'saved' : 'file');
212
- options.config = connection === 'saved' ? savedProfile : await effects.askLine('Connection profile file: ', savedProfile);
302
+ options.config ??= connection === 'saved' ? savedProfile : await effects.askLine('Connection profile file: ', savedProfile);
213
303
  }
214
304
  if (options.scope !== 'server') {
215
305
  const detected = typeof effects.detectHarnesses === 'function' ? await effects.detectHarnesses() : [];
216
306
  const selected = integrations.filter(name => name === 'fleet' || detected.some(item => item.name === name && item.status === 'ok'));
217
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.');
218
- options.integrations = await effects.multiselect('Which integrations should be configured?', [
308
+ options.integrations ??= await effects.multiselect('Which integrations should be configured?', [
219
309
  { value: 'codex', label: 'Codex' }, { value: 'claude-code', label: 'Claude Code' }, { value: 'fleet', label: 'Fleet — persistent agents' },
220
310
  ], selected);
221
- if (options.integrations.includes('fleet')) {
311
+ if (options.integrations.includes('fleet') && !options.disableFleetAgentsSetup && !options.fleetSettingsPath) {
222
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.');
223
313
  const fleetMode = await effects.select('How should Fleet be configured?', [
224
314
  { value: 'wizard', label: 'Configure interactively with Fleet' }, { value: 'file', label: 'Use a prepared settings file' },