@ours.network/install 1.2.1-nightly.51 → 1.2.1-nightly.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
3
  "channel": "nightly",
4
- "installerVersion": "1.2.1-nightly.51",
4
+ "installerVersion": "1.2.1-nightly.53",
5
5
  "packages": {
6
6
  "@ours.network/sdk": {
7
7
  "version": "3.8.1-nightly.18",
@@ -2,7 +2,7 @@
2
2
  "release": {
3
3
  "schema": 1,
4
4
  "channel": "nightly",
5
- "installerVersion": "1.2.1-nightly.51",
5
+ "installerVersion": "1.2.1-nightly.53",
6
6
  "packages": {
7
7
  "@ours.network/sdk": {
8
8
  "version": "3.8.1-nightly.18",
package/lib/effects.mjs CHANGED
@@ -25,7 +25,7 @@ import { dirname, join, resolve } from 'node:path';
25
25
  import { connect as netConnect } from 'node:net';
26
26
  import { clientPackageNames, maintenanceServices, installationPaths, validateInstallation, consumerServiceState, unitNameForStateDir, launchdLabelForStateDir, messengerServicePlan, selectSourcePackages, resolveSourcePolicy, SERVER_SERVICES } from './plan.mjs';
27
27
  import { validateHostProfile, validateGatewayClientProfile } from './target.mjs';
28
- import { serverBase, validateGatewayDiscovery, gatewayCompose, gatewayNginx, gatewayAddress } from './gateway.mjs';
28
+ import { serverBase, validateGatewayDiscovery, gatewayCompose, gatewayNginx, gatewayAddress, gatewayReadinessScript, describeGatewayReadiness } from './gateway.mjs';
29
29
  import { createServerOnboarding, retainedCredentialRefused } from './server-onboarding.mjs';
30
30
  import { atomicWriteConfig, snapshotConfig, restoreConfig } from './config.mjs';
31
31
  import { select as selectOnTty, multiselect as multiselectOnTty, askLine as askLineOnTty } from './prompt.mjs';
@@ -855,28 +855,11 @@ export function networkEffects(effects) {
855
855
  async removeGatewayContainer(record) { await compose(record, ['rm', '-f', 'gateway']); },
856
856
  async verifyGateway(record) {
857
857
  const { prefix } = gatewayAddress(record);
858
- const script = `const fs=require('node:fs');let stage='selection';(async()=>{
859
- const base=${JSON.stringify('http://gateway:8080' + prefix)};
860
- const get=async(path,options={})=>{const r=await fetch(base+path,{...options,redirect:'error',signal:AbortSignal.timeout(5000)});if(!r.ok)throw Error('Gateway readiness HTTP '+r.status);return r.json();};
861
- const selection=await get('/daemon/selection');
862
- if(selection.instanceId!==${JSON.stringify(record.instanceId)})throw Error('Gateway daemon instance mismatch');
863
- stage='unauthenticated-management';
864
- const denied=await fetch(base+'/cowork/management/rpc',{method:'POST',redirect:'error',signal:AbortSignal.timeout(5000),headers:{'content-type':'application/json'},body:'{}'});
865
- await denied.body?.cancel();if(denied.status!==401)throw Error('Gateway management does not reject unauthenticated requests');
866
- stage='credential';
867
- const token=fs.readFileSync('/var/lib/ours/daemon-token','utf8').trim();
868
- const headers={'x-ours-api-token':token,'content-type':'application/json'};
869
- stage='authenticated-daemon';
870
- const identities=await get('/daemon/identities',{headers});
871
- if(!Array.isArray(identities.identities))throw Error('Gateway daemon API invalid');
872
- stage='authenticated-management';
873
- const result=await get('/cowork/management/rpc',{method:'POST',headers,body:JSON.stringify({version:1,id:'installer-readiness',method:'room.list',params:{}})});
874
- if(result.version!==1||result.id!=='installer-readiness'||!Array.isArray(result.result)||result.error)throw Error('Gateway Cowork management unavailable');
875
- })().catch(error=>{const code=error.cause?.code;process.stdout.write('gateway-readiness:'+stage+':'+(['EAI_AGAIN','ENOTFOUND','ECONNREFUSED','ETIMEDOUT'].includes(code)?code:'CHECK_FAILED'));process.exitCode=1;});`;
858
+ const script = gatewayReadinessScript({ base: 'http://gateway:8080' + prefix, instanceId: record.instanceId });
876
859
  const result = await compose(record, ['exec', '-T', 'daemon', 'node', '-e', script], { sensitive: true, allowCodes: [1] });
877
860
  if (result.code === 1) {
878
- const match = /^gateway-readiness:(selection|unauthenticated-management|credential|authenticated-daemon|authenticated-management):(EAI_AGAIN|ENOTFOUND|ECONNREFUSED|ETIMEDOUT|CHECK_FAILED)$/.exec(result.stdout.trim());
879
- const detail = match ? ` (${match[1]}, ${match[2]})` : '';
861
+ const described = describeGatewayReadiness(result.stdout);
862
+ const detail = described ? ` (${described})` : '';
880
863
  throw new Error(`Gateway readiness failed${detail}. Keep installation state intact; check the managed gateway startup and network connection, then retry setup.`);
881
864
  }
882
865
  },
package/lib/gateway.mjs CHANGED
@@ -157,3 +157,71 @@ http {
157
157
  }
158
158
  `;
159
159
  }
160
+
161
+ /** How long the gateway readiness probe keeps retrying a dependency that is still starting. */
162
+ export const GATEWAY_READINESS_WAIT_MS = 60_000;
163
+ const GATEWAY_READINESS_RETRY_MS = 1_000;
164
+ const READINESS_KIND = /^(EAI_AGAIN|ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EPIPE|UND_ERR_SOCKET|UND_ERR_CONNECT_TIMEOUT|TIMEOUT|HTTP_[1-5][0-9][0-9]|INVALID|RPC_ERROR|CHECK_FAILED)$/;
165
+
166
+ /**
167
+ * Node script the installer runs inside the daemon container to prove the
168
+ * gateway serves the daemon and Cowork management with the installation's
169
+ * credential. Services restored by an update may still be starting, so a
170
+ * transient result (a 502/503/504 without an RPC error body, a request
171
+ * timeout, a refused, reset or dropped connection — including one dropped
172
+ * while the body is read — or a name not yet resolvable) is
173
+ * retried until one total `deadlineMs` across every stage and attempt; each
174
+ * request is capped to the time left. Anything else — a wrong instance,
175
+ * 401/403, a well-formed RPC error under any status, any other status or an
176
+ * invalid body — fails at once. The probe only reads; nothing else is retried. Output carries stage and a fixed kind only,
177
+ * never the token or a response body.
178
+ */
179
+ export function gatewayReadinessScript({ base, instanceId, tokenPath = '/var/lib/ours/daemon-token',
180
+ deadlineMs = GATEWAY_READINESS_WAIT_MS, retryMs = GATEWAY_READINESS_RETRY_MS }) {
181
+ return `const fs=require('node:fs');const base=${JSON.stringify(base)};const instanceId=${JSON.stringify(instanceId)};
182
+ const tokenPath=${JSON.stringify(tokenPath)};const deadline=Date.now()+${Number(deadlineMs)};const retryMs=${Number(retryMs)};
183
+ const NET=['EAI_AGAIN','ENOTFOUND','ECONNREFUSED','ECONNRESET','ETIMEDOUT','EPIPE','UND_ERR_SOCKET','UND_ERR_CONNECT_TIMEOUT'];
184
+ class Check extends Error{constructor(kind,transient){super(kind);this.kind=kind;this.transient=transient;}}
185
+ const status=s=>new Check('HTTP_'+s,s===502||s===503||s===504);
186
+ const request=async(path,options)=>{const left=Math.max(1,Math.min(5000,deadline-Date.now()));
187
+ try{return await fetch(base+path,{...options,redirect:'error',signal:AbortSignal.timeout(left)});}
188
+ catch(e){const code=e?.cause?.code;if(NET.includes(code))throw new Check(code,true);if(e?.name==='TimeoutError'||e?.cause?.name==='TimeoutError')throw new Check('TIMEOUT',true);throw new Check('CHECK_FAILED',false);}};
189
+ const json=async(path,options={})=>{const r=await request(path,options);
190
+ if(!r.ok){let body;try{body=await r.json();}catch{}
191
+ // A well-formed RPC error is the service's answer, whatever the status: never retried.
192
+ if(body&&typeof body==='object'&&body.version===1&&body.error)throw new Check('RPC_ERROR',false);throw status(r.status);}
193
+ // The request signal also bounds the body: a stalled body is a timeout, not an invalid answer.
194
+ // A connection dropped mid-body is transport, not content; only a parse failure is invalid.
195
+ try{return await r.json();}catch(e){if(e?.name==='TimeoutError'||e?.name==='AbortError')throw new Check('TIMEOUT',true);
196
+ const code=e?.cause?.code;if(NET.includes(code))throw new Check(code,true);throw new Check('INVALID',false);}};
197
+ let stage='selection';
198
+ const attempt=async()=>{
199
+ stage='selection';const selection=await json('/daemon/selection');
200
+ if(selection?.instanceId!==instanceId)throw new Check('INVALID',false);
201
+ stage='unauthenticated-management';
202
+ const denied=await request('/cowork/management/rpc',{method:'POST',headers:{'content-type':'application/json'},body:'{}'});
203
+ await denied.body?.cancel();if(denied.status!==401)throw status(denied.status);
204
+ stage='credential';let token;try{token=fs.readFileSync(tokenPath,'utf8').trim();}catch{throw new Check('CHECK_FAILED',false);}
205
+ const headers={'x-ours-api-token':token,'content-type':'application/json'};
206
+ stage='authenticated-daemon';const identities=await json('/daemon/identities',{headers});
207
+ if(!Array.isArray(identities?.identities))throw new Check('INVALID',false);
208
+ stage='authenticated-management';
209
+ const result=await json('/cowork/management/rpc',{method:'POST',headers,body:JSON.stringify({version:1,id:'installer-readiness',method:'room.list',params:{}})});
210
+ if(result?.version!==1||result.id!=='installer-readiness'||!Array.isArray(result.result)||result.error)throw new Check('INVALID',false);
211
+ };
212
+ (async()=>{let attempts=0;for(;;){attempts++;try{await attempt();return;}catch(e){
213
+ const c=e instanceof Check?e:new Check('CHECK_FAILED',false);
214
+ if(!c.transient||Date.now()+retryMs>=deadline){process.stdout.write('gateway-readiness:'+stage+':'+c.kind+':'+attempts+(c.transient?':transient':''));process.exitCode=1;return;}
215
+ await new Promise(r=>setTimeout(r,retryMs));}}})();`;
216
+ }
217
+
218
+ /** Operator text for a failed readiness probe; `undefined` when the output is not the probe's. */
219
+ export function describeGatewayReadiness(stdout) {
220
+ const match = /^gateway-readiness:(selection|unauthenticated-management|credential|authenticated-daemon|authenticated-management):([A-Z0-9_]+):([0-9]{1,6})(:transient)?$/.exec(String(stdout).trim());
221
+ if (!match || !READINESS_KIND.test(match[2])) return undefined;
222
+ const [, stage, kind, attempts, transient] = match;
223
+ const what = kind.startsWith('HTTP_') ? `HTTP ${kind.slice(5)}` : kind;
224
+ return transient
225
+ ? `${stage}, ${what}; still not ready after ${attempts} attempts over ${GATEWAY_READINESS_WAIT_MS / 1000}s`
226
+ : `${stage}, ${what}`;
227
+ }
@@ -1069,6 +1069,116 @@ export async function runFleetManagedCliSetup(args, effects, plan, target) {
1069
1069
  return { state: declared.every(role => good.includes(role.setup.state)) ? 'prepared' : 'attention', report };
1070
1070
  }
1071
1071
 
1072
+ export const FLEET_SERVICE_REFRESH_CAPABILITY = 'service.refresh-v1';
1073
+
1074
+ /** Order matters only for the supervisor: it stops and resumes agents, so it goes last. */
1075
+ const FLEET_RESTART_ORDER = ['web', 'watchdogs', 'supervisor'];
1076
+ const FLEET_RESTART_TIMEOUT_MS = 120_000;
1077
+
1078
+ /** Whether this installer runs inside `unit`'s cgroup, where restarting it would kill this run. */
1079
+ function insideUnit(effects, unit) {
1080
+ const cgroup = effects.readText('/proc/self/cgroup');
1081
+ return cgroup === null || cgroup.split('\n').some(line => line.split(':').slice(2).join(':').split('/').includes(unit));
1082
+ }
1083
+
1084
+ /** The platform's own restart command for a Fleet service definition. */
1085
+ function fleetRestartCommand(effects, service) {
1086
+ return effects.platform.platform === 'darwin'
1087
+ ? `launchctl kickstart -k gui/$(id -u)/${basename(service.path, '.plist')}`
1088
+ : `systemctl --user try-restart ${basename(service.path)}`;
1089
+ }
1090
+
1091
+ /**
1092
+ * An active Fleet service started from the replaced release keeps running it.
1093
+ * Restart each one that `service refresh` reports running a stale release once
1094
+ * its definition starts this release, then confirm with the read-only
1095
+ * `service check` that it now runs this release. The restart is systemd's
1096
+ * `try-restart`, which acts only on an active unit, so a service stopped at
1097
+ * any point is never started. A service whose definition still points
1098
+ * elsewhere, launchd, or the unit hosting this run is left alone with a notice
1099
+ * naming the manual restart; a running state Fleet cannot determine is never
1100
+ * restarted and is reported as unconfirmed.
1101
+ */
1102
+ async function restartStaleFleetServices(effects, fleet, shown, env, services) {
1103
+ const attention = [];
1104
+ for (const service of services.filter(service => service.running === 'unknown' && (service.state === 'refreshed' || service.state === 'current'))) {
1105
+ attention.push(service.service);
1106
+ effects.out(warn(`Could not confirm which release the Fleet ${service.service} service is running; if it is running and was started before this update, restart it: ${fleetRestartCommand(effects, service)}${service.service === 'supervisor' ? ' (agents resume through their supervisor)' : ''}.`));
1107
+ }
1108
+ const stale = services.filter(service => service.running === 'stale')
1109
+ .sort((a, b) => FLEET_RESTART_ORDER.indexOf(a.service) - FLEET_RESTART_ORDER.indexOf(b.service));
1110
+ if (!stale.length) return attention;
1111
+ const linux = effects.platform.platform === 'linux';
1112
+ const restarted = [];
1113
+ for (const service of stale) {
1114
+ const unit = basename(service.path);
1115
+ const left = why => { attention.push(service.service); effects.out(warn(`Running Fleet ${service.service} service still uses the previous release: ${why}; when convenient: ${fleetRestartCommand(effects, service)}${service.service === 'supervisor' ? ' (agents resume through their supervisor)' : ''}.`)); };
1116
+ if (!linux) { left('this installer restarts Fleet services only under systemd'); continue; }
1117
+ if (service.state !== 'refreshed' && service.state !== 'current') { left('its definition does not start this release yet, so a restart would not help'); continue; }
1118
+ if (insideUnit(effects, unit)) { left('this installer runs inside it, so restarting it would stop this run'); continue; }
1119
+ try {
1120
+ // try-restart: a unit stopped since the report was taken stays stopped.
1121
+ await effects.run('systemctl', ['--user', 'try-restart', unit], { timeout: FLEET_RESTART_TIMEOUT_MS });
1122
+ restarted.push(service);
1123
+ } catch (error) {
1124
+ left(`restarting it failed (${installerFailure(error)})`);
1125
+ }
1126
+ }
1127
+ if (!restarted.length) return attention;
1128
+ let checked;
1129
+ try {
1130
+ const result = await effects.run(fleet, ['service', 'check', '--json'], { env, allowCodes: [1] });
1131
+ checked = JSON.parse(result.stdout ?? '').services;
1132
+ if (!Array.isArray(checked)) throw new Error('unrecognised report');
1133
+ } catch (error) {
1134
+ effects.out(warn(`Restarted Fleet ${restarted.map(service => service.service).join(', ')} service, but could not confirm which release it runs (${installerFailure(error)}); check: ${shown} service check`));
1135
+ return [...attention, ...restarted.map(service => service.service)];
1136
+ }
1137
+ for (const service of restarted) {
1138
+ const now = checked.find(entry => entry.service === service.service);
1139
+ if (now?.running === 'current') effects.out(ok(`Restarted Fleet ${service.service} service; it now runs this release${service.service === 'supervisor' ? ' and resumes its agents' : ''}.`));
1140
+ else {
1141
+ attention.push(service.service);
1142
+ effects.out(warn(now?.running === 'stopped'
1143
+ ? `Fleet ${service.service} service is not running after the restart (it was stopped, or exited); this installer did not start it. Check: systemctl --user status ${basename(service.path)}`
1144
+ : `Restarted Fleet ${service.service} service, but it is not confirmed on this release (${now?.running ?? 'not reported'}); check: systemctl --user status ${basename(service.path)}`));
1145
+ }
1146
+ }
1147
+ return attention;
1148
+ }
1149
+
1150
+ /**
1151
+ * Fleet service definitions pin the release tree that wrote them, and an update
1152
+ * installs a new tree. Ask the installed Fleet to re-point its own existing
1153
+ * definitions (it never creates, starts, stops or restarts a service), then
1154
+ * restart only the services that were already running the replaced release.
1155
+ */
1156
+ export async function runFleetServiceRefresh(args, effects, plan, target) {
1157
+ const fleet = args.acquiredFleet || plan.init[0];
1158
+ const env = target.mode === 'host-profile' ? profileEnv(target) : daemonEnv(target.stateDir, target.port);
1159
+ const capabilities = await effects.fleetCapabilities(fleet, env);
1160
+ if (!capabilities.includes(FLEET_SERVICE_REFRESH_CAPABILITY)) return { state: 'unavailable' };
1161
+ const shown = fleet === plan.init[0] ? fleet : shellQuote(fleet);
1162
+ const manual = `${shown} service refresh`;
1163
+ let services;
1164
+ try {
1165
+ const result = await effects.run(fleet, ['service', 'refresh', '--json'], { env });
1166
+ services = JSON.parse(result.stdout ?? '').services;
1167
+ if (!Array.isArray(services)) throw new Error('unrecognised report');
1168
+ } catch (error) {
1169
+ effects.out(warn(`Fleet service definitions were not refreshed (${installerFailure(error)}). After a reboot the previous Fleet release may start; retry: ${manual}`));
1170
+ return { state: 'failed' };
1171
+ }
1172
+ for (const service of services) {
1173
+ if (service.state === 'refreshed') effects.out(ok(`Fleet ${service.service} service now starts this release (${service.path}).`));
1174
+ if (service.state === 'unrecognized') effects.out(warn(`Fleet ${service.service} service definition was left unchanged: ${service.detail ?? 'not generated by Fleet'} (${service.path}).`));
1175
+ if (service.state === 'stale') effects.out(warn(`Fleet ${service.service} service still starts another release${service.detail ? `: ${service.detail}` : ''}; retry: ${manual}`));
1176
+ if (service.state === 'reload-failed') effects.out(warn(`Fleet ${service.service} service definition was updated, but the service manager did not reload it, so it still starts the previous release${service.detail ? ` (${service.detail})` : ''}; retry: systemctl --user daemon-reload`));
1177
+ }
1178
+ const unrestarted = await restartStaleFleetServices(effects, fleet, shown, env, services);
1179
+ return { state: unrestarted.length || services.some(service => service.state !== 'refreshed' && service.state !== 'current' && service.state !== 'absent') ? 'attention' : 'refreshed', services };
1180
+ }
1181
+
1072
1182
  /** Install Fleet and let its interactive wizard publish the owned configuration. */
1073
1183
  export async function runFleetPhase(args, effects, { target, isDefaultStateDir }) {
1074
1184
  effects.out(heading('ours-fleet (your always-online agent team)'));
@@ -1089,7 +1199,12 @@ export async function runFleetPhase(args, effects, { target, isDefaultStateDir }
1089
1199
  if (!install.ok) return { key: 'fleet', label: plan.label, state: 'failed', note: 'Fleet installation failed' };
1090
1200
  effects.out(ok('Fleet CLI installed; agent and model setup deferred to the App. Existing Fleet configuration was retained.'));
1091
1201
  // A retained configuration may already declare the workflow; its generated policy names the package path this run just replaced.
1092
- if (!args.dryRun && effects.readText(plan.configPath) !== null) await runFleetManagedCliSetup(args, effects, plan, target);
1202
+ // A retained configuration means Fleet was set up before, so its service
1203
+ // definitions may pin the release this run just replaced.
1204
+ if (!args.dryRun && effects.readText(plan.configPath) !== null) {
1205
+ await runFleetManagedCliSetup(args, effects, plan, target);
1206
+ await runFleetServiceRefresh(args, effects, plan, target);
1207
+ }
1093
1208
  return { key: 'fleet', label: plan.label, state: 'installed', note: 'agents setup deferred' };
1094
1209
  }
1095
1210
  // Fleet owns its v2 manifest, roles, models and permissions. With no prepared
@@ -1116,6 +1231,7 @@ export async function runFleetPhase(args, effects, { target, isDefaultStateDir }
1116
1231
  }
1117
1232
  effects.out(ok('ours-fleet installed and initialized; no fleet roles were started.'));
1118
1233
  if (!args.dryRun) await runFleetManagedCliSetup(args, effects, plan, target);
1234
+ if (!args.dryRun) await runFleetServiceRefresh(args, effects, plan, target);
1119
1235
  if (plan.instruction) effects.out(info(plan.instruction));
1120
1236
  return { key: 'fleet', label: plan.label, state: 'installed', note: `configured at ${plan.configPath}; stopped` };
1121
1237
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ours.network/install",
3
- "version": "1.2.1-nightly.51",
3
+ "version": "1.2.1-nightly.53",
4
4
  "private": false,
5
5
  "description": "The all-in-one ours.network installer: one shared daemon, MCP, cowork, Telegram, Fleet initialization, harness plugins, Human identity, progress UI, and guided next steps.",
6
6
  "type": "module",