@runeditrun/rer 0.2.53 → 0.2.55

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.
package/README.md CHANGED
@@ -371,18 +371,39 @@ formats and syntax may yield no signals.
371
371
  ## Business device commands
372
372
 
373
373
  `rer business connect --code ABCD-1234 [--origin https://app.runeditrun.com]`
374
- redeems a browser-created code, prints a six-digit confirmation number and waits
375
- for approval in the browser that created it. Device credentials stay in macOS
376
- Keychain or Linux Secret Service. A missing or locked Secret Service refuses;
377
- there is no plaintext credential store. Linux needs `secret-tool` and an
374
+ redeems a browser-created code and prints a six-digit confirmation number for
375
+ approval in the browser that created it. Without a terminal it returns while
376
+ approval is pending. Run `rer business connect` again in a later turn to resume
377
+ the same pairing and number; a new server pairing is never started until the
378
+ old one is refused, expired or disconnected. The waiting line names the command
379
+ that works from the agent's own shell: `rer` when it is on PATH, the launcher
380
+ install.sh wrote, or `npx -y @runeditrun/rer` after an npx run. Pending tokens
381
+ are kept in the private CLI config directory until the code's expiry plus the
382
+ ten minutes the server allows after an approval, so an approval near the code's
383
+ end can still be collected. Device credentials stay in macOS
384
+ Keychain or Linux Secret Service. A missing or locked store refuses before the
385
+ one-use code is redeemed; there is no plaintext credential store. Linux needs `secret-tool` and an
378
386
  unlocked desktop Secret Service session.
379
387
 
380
- In a terminal, connect asks separately before adding Claude Code user Read deny
381
- rules, allowing export-scoped macOS wake prevention, and installing a launchd
382
- or systemd user service. Only the exact answer `yes` opts in. Noninteractive
383
- connect pairs but leaves those optional changes off. Background services use
388
+ The owner chooses Claude Code user Read deny rules, export-scoped macOS wake
389
+ prevention, and a launchd or systemd user service in the browser. Connect reads
390
+ `optIns` from device-authenticated `GET /api/business/executors/self`, with keys
391
+ `installPermissions`, `awakeConsent` and `installService`. Only `true` enables
392
+ an option. Undecided (`null`) options print a browser link; an older server
393
+ without this route (it answers 403 or 404) leaves all options undecided. Run connect again after the
394
+ owner decides. The first device-authenticated request happens after both the
395
+ credential and local pairing state are stored, so a storage failure cannot
396
+ activate the computer. Background services use
384
397
  absolute Node and CLI paths. No model process is started.
385
398
 
399
+ An agent can run `npx -y @runeditrun/rer business connect --code ABCD-1234 --origin URL`
400
+ directly, without a global installation. In Codex's workspace-write sandbox,
401
+ allow network access and the CLI's config directory (`~/.rer`), and put npm's
402
+ cache inside the working folder with `npm_config_cache="$PWD/.rer/npm"`.
403
+ Later turns can omit `--code` to resume the saved request. Do not install a
404
+ background service or change user settings unless the owner enables those
405
+ options and the sandbox permits their locations.
406
+
386
407
  `rer business vendor-key add sentry` requires hidden credential entry in a
387
408
  terminal, stores it in the OS keychain and prints only `sentry:read`.
388
409
  `remove` deletes it. The same commands support `uptimerobot`, `pagerduty` and
@@ -402,10 +423,16 @@ a headers helper. That output is a short-lived credential: connect it directly
402
423
  to the MCP client and do not paste it into an agent transcript.
403
424
 
404
425
  `rer business status` shows local pairing, service state and progress without
405
- printing checkpoints or vendor data. `rer business disconnect` removes the
406
- service, device and vendor credentials, state and introduced Claude rules,
407
- preserving preexisting settings and unrelated edits. Revocation in the browser
408
- removes remote authority; disconnect removes the local installation's additions.
426
+ printing checkpoints or vendor data. `rer business disconnect` revokes this
427
+ device through device-authenticated `DELETE /api/business/executors/self` before
428
+ removing its service, device and vendor credentials, state and introduced Claude
429
+ rules, preserving preexisting settings and unrelated edits. It says "Device
430
+ revoked" only after the server confirms (`{"revoked":true}`, or 401 for a device
431
+ already revoked). A server without that route (403 or 404) leaves the computer
432
+ connected: disconnect says so, names the browser page to revoke it in and keeps
433
+ everything for a later disconnect. Any other failure exits 1 and also keeps the
434
+ credential for a retry. With no stored device credential, nothing is sent and
435
+ disconnect removes the local additions without claiming a revocation.
409
436
 
410
437
  `rer business run` performs consented `discover.local` tasks through claims,
411
438
  short-lived task bearers, quota-bound uploads, 60-second heartbeats and server
package/cli/README.md CHANGED
@@ -336,6 +336,16 @@ declaration refuses completion. A kit or custom-hook deploy, except `--dry-run`,
336
336
  first refuses uncommitted tracked source, naming the files, before any build or
337
337
  upload.
338
338
 
339
+ For a hosted owner claim, deploy reuses the name saved by `rer setup` in the
340
+ checkout's `.seed/installer/setup-answers.json`, under the adapter's
341
+ `input.names.name` field (default `displayName`). If no name is known,
342
+ interactive deploy asks once and saves it there. For unattended deployment,
343
+ `rer deploy --non-interactive --owner-name 'Maya Chen'` supplies the name;
344
+ without a saved or supplied name, it refuses before upload. Names use the same
345
+ validation as `setup --owner-name`: nonblank, at most 200 characters and no
346
+ Unicode Cc or Cf control characters. Nameless installers retain their existing
347
+ deployment behavior.
348
+
339
349
  `--env-file` values are available in the command's preflight, custom hook and
340
350
  child build environment and are redacted; the caller environment is restored
341
351
  on success and failure. `--remove`, `--set-secret` and `--unset-secret` always go
@@ -29,13 +29,18 @@ export class Api {
29
29
  return result;
30
30
  }
31
31
  async post(path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
32
+ return this.request('POST', path, body, { token, signal, timeout, headers });
33
+ }
34
+ async get(path) { return this.request('GET', path); }
35
+ async delete(path) { return this.request('DELETE', path); }
36
+ async request(method, path, body, { token = this.credential, signal, timeout = 30_000, headers = {} } = {}) {
32
37
  if (!path.startsWith('/api/business/') || path.includes('..') || path.includes('?') || path.includes('#')) throw Error('Invalid Business route.');
33
38
  let response;
34
39
  try {
35
40
  response = await fetch(this.origin + path, {
36
- method: 'POST', redirect: 'error',
41
+ method, redirect: 'error',
37
42
  headers: { ...headers, 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
38
- body: JSON.stringify(body), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
43
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
39
44
  });
40
45
  } catch (error) { if (signal?.aborted) throw signal.reason; throw Error('Could not reach the Business server.'); }
41
46
  if (!response.ok) { await response.body?.cancel(); throw new ApiError(response.status); }
@@ -6,8 +6,8 @@ import { run } from './supervisor.mjs';
6
6
 
7
7
  const usage = `Usage: rer business VERB
8
8
  scan [DIR...] [--json] Names-only local discovery
9
- connect --code CODE [--origin URL]
10
- Pair, compare a number in your browser, then opt in to a service
9
+ connect [--code CODE] [--origin URL]
10
+ Pair or resume; the owner approves and chooses opt-ins in the browser
11
11
  run [--once] Run consented local discovery; vendor upload integration pending
12
12
  next Return one templated question or nothing yet within 60 seconds
13
13
  answer ID VENDOR USAGE [CONFIDENCE]
@@ -15,7 +15,7 @@ const usage = `Usage: rer business VERB
15
15
  vendor-key add|remove VENDOR Keep a vendor key in OS credential storage
16
16
  token MCP headersHelper output; send directly to the MCP client
17
17
  status [--json] Pairing, service, current task and checkpoint
18
- disconnect Remove local service, credentials and added permissions
18
+ disconnect Revoke this computer, then remove local credentials and additions
19
19
  Vendors: sentry, uptimerobot, pagerduty, calendly. Owner approvals stay in the browser.
20
20
  `;
21
21
 
@@ -31,7 +31,7 @@ export async function businessCommand(argv) {
31
31
  if (!['--code', '--origin'].includes(name) || !args[index + 1] || args[index + 1].startsWith('--') || Object.hasOwn(options, name.slice(2))) return invalid();
32
32
  options[name.slice(2)] = args[index + 1];
33
33
  }
34
- if (typeof options.code !== 'string' || !/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(options.code)) return invalid();
34
+ if (options.code !== undefined && !/^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$/.test(options.code)) return invalid();
35
35
  await connect(options);
36
36
  } else if (verb === 'vendor-key' && args.length === 2) await vendorKey(...args);
37
37
  else if (verb === 'answer' && [3, 4].includes(args.length)) await answer(...args);
@@ -1,47 +1,77 @@
1
1
  import { homedir } from 'node:os';
2
2
  import { join } from 'node:path';
3
3
  import { Api, originUrl, identifier, pause } from './api.mjs';
4
- import { loadState, saveState, credentialHandle } from './state.mjs';
4
+ import { loadState, saveState, credentialHandle, loadPending, savePending, clearPending } from './state.mjs';
5
5
  import { createCredentialStore } from './keychain.mjs';
6
- import { installService } from './service.mjs';
7
- import { installPermissions } from './permissions.mjs';
8
- import { consent } from './prompts.mjs';
6
+ import { applyOptIns } from './opt-ins.mjs';
7
+ import { rerCommand } from './invocation.mjs';
8
+
9
+ // Approval moves the server's pairing expiry to ten minutes after approval, and
10
+ // approval can come up to the code's own expiry. Keep the pending pairing until
11
+ // then and let the server decide whether it was approved in time.
12
+ const approvalWindow = 600_000;
9
13
 
10
14
  export const capabilities = ['discover.local', 'export.vendor:sentry', 'export.vendor:uptimerobot', 'export.vendor:pagerduty', 'export.vendor:calendly'];
11
15
 
12
- export async function connect({ code, origin }) {
13
- origin = originUrl(origin);
14
- if (await loadState()) throw Error('Business has local pairing state. Disconnect before pairing again.');
16
+ export async function connect({ code, origin } = {}) {
17
+ const stored = await loadState();
18
+ let pending = await loadPending();
19
+ origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
20
+ if (stored) {
21
+ if (stored.origin !== origin) throw Error('Business is paired to another origin. Disconnect before pairing again.');
22
+ const credential = await createCredentialStore().get(credentialHandle(origin));
23
+ if (!credential) throw Error('Business device credential is missing. Disconnect and create a new browser pairing code.');
24
+ await applyOptIns(new Api(origin, credential), stored);
25
+ return;
26
+ }
27
+ if (pending && Date.parse(pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
28
+ if (pending && (pending.origin !== origin || code && pending.code !== code)) throw Error('Business has a pending pairing. Resume it or disconnect before using another code or origin.');
29
+ if (!pending && !code) throw Error(`Business needs a browser pairing code. Open ${origin}/business, then run ${rerCommand()} business connect --code CODE --origin ${origin}.`);
15
30
  const store = createCredentialStore(), handle = credentialHandle(origin);
16
- // Fail before redeeming the one-use browser code if the OS store is absent.
17
- if (await store.get(handle)) throw Error('A Business credential already exists for this origin. Disconnect it before pairing again.');
31
+ // Refuse before redeeming the one-use code or collecting an approval when the
32
+ // OS credential store cannot hold the device credential.
33
+ await store.get(handle);
18
34
  const api = new Api(origin);
19
- const pending = await api.post('/api/business/executors/pair', {
20
- code, os: process.platform === 'darwin' ? 'macos' : 'linux', agent_kind: 'other', capabilities,
21
- });
22
- if (pending.status !== 'pending_approval' || !/^\d{6}$/.test(pending.confirmation_number) || typeof pending.pairing_token !== 'string') throw Error('Business server returned an invalid pairing response.');
23
- process.stdout.write(`Confirmation number: ${pending.confirmation_number}\nCompare this number in the browser that created the code, then approve. Waiting for browser approval.\n`);
24
- const expires = Math.min(Date.now() + 600_000, Date.parse(pending.expires_at));
25
- if (!Number.isFinite(expires)) throw Error('Business server returned an invalid pairing expiry.');
26
- let result;
27
- while (Date.now() < expires) {
28
- result = await api.post('/api/business/executors/pair', { pairing_token: pending.pairing_token });
29
- if (result.status === 'paired') break;
30
- if (result.status !== 'authorization_pending') throw Error('Business server returned an invalid pairing status.');
35
+ if (!pending) {
36
+ const response = await api.post('/api/business/executors/pair', {
37
+ code, os: process.platform === 'darwin' ? 'macos' : 'linux', agent_kind: process.env.CODEX_HOME ? 'codex' : process.env.CLAUDECODE ? 'claude' : 'other', capabilities,
38
+ });
39
+ const expires = Math.min(Date.now() + 600_000, Date.parse(response?.expires_at));
40
+ if (response?.status !== 'pending_approval' || !/^\d{6}$/.test(response.confirmation_number) || typeof response.pairing_token !== 'string' || !response.pairing_token || !Number.isFinite(expires) || expires <= Date.now()) throw Error('Business server returned an invalid pairing response.');
41
+ pending = { origin, code, pairing_token: response.pairing_token, confirmation_number: response.confirmation_number, expires_at: new Date(expires + approvalWindow).toISOString() };
42
+ await savePending(pending);
43
+ }
44
+ process.stdout.write(`Confirmation number: ${pending.confirmation_number}\nCompare this number in the browser that created the code, then approve.\n`);
45
+ while (Date.now() < Date.parse(pending.expires_at)) {
46
+ let result;
47
+ try { result = await api.post('/api/business/executors/pair', { pairing_token: pending.pairing_token }); }
48
+ catch (error) {
49
+ if ([401, 403, 410].includes(error.status)) { await clearPending(); throw Error('Business browser pairing was refused or expired. Create a new code in the browser.'); }
50
+ throw error;
51
+ }
52
+ if (result?.status === 'paired') {
53
+ if (typeof result.device_credential !== 'string') throw Error('Business server returned an invalid device credential.');
54
+ const state = { version: 1, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false };
55
+ // No authenticated request (including activation) before both durable writes.
56
+ await store.set(handle, result.device_credential);
57
+ try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
58
+ await clearPending();
59
+ process.stdout.write('Business paired. Device credential stored in OS keychain.\n');
60
+ await applyOptIns(new Api(origin, result.device_credential), state);
61
+ return;
62
+ }
63
+ if (['denied', 'refused', 'expired'].includes(result?.status)) {
64
+ await clearPending(); throw Error('Business browser pairing was refused or expired. Create a new code in the browser.');
65
+ }
66
+ if (result?.status !== 'authorization_pending') throw Error('Business server returned an invalid pairing status.');
67
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
68
+ process.stdout.write(`Waiting for the owner in ${origin}/business. After approval, run ${rerCommand()} business connect --origin ${origin} again to resume this pairing.\n`);
69
+ return;
70
+ }
31
71
  await pause(Math.max(1, Math.min(5, Number(result.interval) || 5)) * 1000);
32
72
  }
33
- if (result?.status !== 'paired' || typeof result.device_credential !== 'string') throw Error('Browser approval expired. Create a new pairing code in the browser.');
34
- const state = { version: 1, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false };
35
- await store.set(handle, result.device_credential);
36
- try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
37
- process.stdout.write('Business paired. Device credential stored in OS keychain.\n');
38
- if (await consent('Add secret-file Read deny rules to Claude Code user settings?')) await installPermissions({ consent: true });
39
- if (process.platform === 'darwin') state.awakeConsent = await consent('Keep this Mac awake only while an export task lease is active?');
40
- await saveState(state);
41
- if (await consent('Install a user background service running rer business run after this chat?')) {
42
- await installService({ consent: true });
43
- process.stdout.write('Business background service installed.\n');
44
- } else process.stdout.write('Run rer business run in a terminal to work tasks.\n');
73
+ await clearPending();
74
+ throw Error('Business browser pairing expired. Create a new code in the browser.');
45
75
  }
46
76
 
47
77
  export function localRoot(path) {
@@ -26,7 +26,10 @@ function inputs(task, grant, checkpoint, stateDir) {
26
26
  if (!object(task) || task.kind !== 'discover.local' || !object(grant)) fail('requires a scoped local discovery grant');
27
27
  identifier(task.id); identifier(grant.id); identifier(grant.consent?.id);
28
28
  if (grant.task_id !== task.id || !integer(task.fence) || task.fence < 1 || grant.fence !== task.fence) fail('grant does not match the claimed task and fence');
29
- if (grant.destination !== `/api/business/tasks/${encodeURIComponent(task.id)}/uploads`) fail('grant has an invalid upload destination');
29
+ const upload = typeof grant.destination === 'string' && /^\/api\/business\/tasks\/([^/]+)\/uploads$/.exec(grant.destination);
30
+ let destination;
31
+ try { destination = upload && `/api/business/tasks/${decodeURIComponent(upload[1])}/uploads`; } catch { fail('grant has an invalid upload destination'); }
32
+ if (destination !== `/api/business/tasks/${task.id}/uploads`) fail('grant has an invalid upload destination');
30
33
  if (!integer(grant.quota_bytes) || grant.quota_bytes < 1 || grant.quota_bytes > QUOTA_BYTES || !integer(grant.uploaded_bytes) || grant.uploaded_bytes > grant.quota_bytes) fail('grant has invalid byte limits');
31
34
  const paths = grant.consent.scope?.paths;
32
35
  if (!Array.isArray(paths) || !paths.length || paths.some(path => typeof path !== 'string' || /[\u0000-\u001f\u007f]/u.test(path) || !(isAbsolute(path) || path.startsWith('~/')))) fail('consent must contain absolute or home-relative scoped paths');
@@ -0,0 +1,25 @@
1
+ import { accessSync, statSync, constants } from 'node:fs';
2
+ import { delimiter, join, sep } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ const npx = 'npx -y @runeditrun/rer';
6
+ const word = value => /^[A-Za-z0-9_./~:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
7
+
8
+ function onPath(path = '') {
9
+ // npm exec puts node_modules/.bin directories on PATH only for its own run.
10
+ for (const directory of path.split(delimiter).filter(entry => entry && !entry.endsWith(join('node_modules', '.bin')))) {
11
+ const candidate = join(directory, 'rer');
12
+ try { accessSync(candidate, constants.X_OK); if (statSync(candidate).isFile()) return true; }
13
+ catch (error) { if (!['ENOENT', 'EACCES', 'ENOTDIR'].includes(error.code)) throw error; }
14
+ }
15
+ return false;
16
+ }
17
+
18
+ // How the person runs this rer again from their own shell in a later turn.
19
+ // An npx run leaves nothing installed; install.sh says which launcher it ran
20
+ // (RER_INVOKED_AS), since it adds that launcher to PATH only for itself.
21
+ export function rerCommand(env = process.env) {
22
+ if (fileURLToPath(import.meta.url).split(sep).includes('_npx')) return npx;
23
+ if (env.RER_INVOKED_AS) return word(env.RER_INVOKED_AS);
24
+ return onPath(env.PATH) ? 'rer' : npx;
25
+ }
@@ -62,7 +62,7 @@ export class Lease {
62
62
  clearInterval(this.timer);
63
63
  await this.tail;
64
64
  if (!this.bearer) await this.token();
65
- return this.post(taskPath(this.claim.task.id, 'release'), { reason, checkpoint: this.checkpoint }, { releasing: true });
65
+ return this.post(taskPath(this.claim.task.id, 'release'), { reason, checkpoint: { ...this.checkpoint, ...(reason === 'failed' ? { status: 'failed' } : {}) } }, { releasing: true });
66
66
  }
67
67
  async close() { clearInterval(this.timer); clearInterval(this.deadline); await this.tail; }
68
68
  }
@@ -1,16 +1,17 @@
1
1
  import { readFile, writeFile, unlink, rm, rmdir, lstat } from 'node:fs/promises';
2
2
  import { dirname, join } from 'node:path';
3
- import { loadState, saveState, stateDirectory, credentialHandle } from './state.mjs';
3
+ import { loadState, loadPending, saveState, stateDirectory, credentialHandle } from './state.mjs';
4
4
  import { createCredentialStore, readSecret } from './keychain.mjs';
5
5
  import { removeService, serviceStatus } from './service.mjs';
6
6
  import { removePermissions } from './permissions.mjs';
7
- import { pause } from './api.mjs';
7
+ import { Api, pause } from './api.mjs';
8
8
  import { loadProgress } from './progress.mjs';
9
9
  import { VENDORS } from './vendors/index.mjs';
10
+ import { rerCommand } from './invocation.mjs';
10
11
 
11
12
  export async function paired() {
12
13
  const state = await loadState();
13
- if (!state?.origin || !state.businessId || !state.executorId) throw Error('This computer is not paired. Run rer business connect --code CODE.');
14
+ if (!state?.origin || !state.businessId || !state.executorId) throw Error(`This computer is not paired. Run ${rerCommand()} business connect --code CODE.`);
14
15
  const credential = await createCredentialStore().get(credentialHandle(state.origin));
15
16
  if (!credential) throw Error('Business device credential is missing. Reconnect in your browser.');
16
17
  return { state, credential };
@@ -48,8 +49,27 @@ async function stopSupervisor(directory) {
48
49
  throw Error('Business supervisor is still stopping. Retry disconnect shortly.');
49
50
  }
50
51
 
52
+ // 'revoked' once the server confirms, or answers 401 for a device it already
53
+ // revoked; 'unsupported' when it refuses device revocation (403 or 404, as a
54
+ // server without this route does); otherwise 'unconfirmed'.
55
+ async function revoke(origin, credential) {
56
+ try { return (await new Api(origin, credential).delete('/api/business/executors/self'))?.revoked === true ? 'revoked' : 'unconfirmed'; }
57
+ catch (error) { return error.status === 401 ? 'revoked' : [403, 404].includes(error.status) ? 'unsupported' : 'unconfirmed'; }
58
+ }
59
+
51
60
  export async function disconnect() {
52
61
  const state = await loadState(), directory = stateDirectory();
62
+ const origin = state?.origin ?? (await loadPending())?.origin;
63
+ const page = origin && (state?.businessId ? `${origin}/business/${encodeURIComponent(state.businessId)}/settings` : `${origin}/business`);
64
+ const credential = state?.origin ? await createCredentialStore().get(credentialHandle(state.origin)) : null;
65
+ const revocation = credential ? await revoke(state.origin, credential) : 'not_sent';
66
+ // Until the server confirms, the device stays connected: keep its credential
67
+ // and everything else so disconnect can run again after browser revocation.
68
+ if (revocation === 'unsupported') {
69
+ process.stdout.write(`This computer is still connected to Business: the server would not revoke it from this computer. Revoke it in ${page}, then run ${rerCommand()} business disconnect again to remove its local service, credentials and added permissions.\n`);
70
+ return;
71
+ }
72
+ if (revocation === 'unconfirmed') throw Error(`Business did not confirm revocation, so this computer is still connected and its credentials were kept. Retry ${rerCommand()} business disconnect, or revoke it in ${page} and then run disconnect again.`);
53
73
  await removeService();
54
74
  await stopSupervisor(directory);
55
75
  await removePermissions();
@@ -61,7 +81,9 @@ export async function disconnect() {
61
81
  await rm(directory, { recursive: true, force: true });
62
82
  // Remove only an empty parent; other rer commands may own it.
63
83
  await rmdir(dirname(directory)).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
64
- process.stdout.write('Business disconnected. Local service, credentials and added permissions removed.\n');
84
+ process.stdout.write(revocation === 'revoked'
85
+ ? 'Business disconnected. Device revoked; local service, credentials and added permissions removed.\n'
86
+ : `Business disconnected on this computer: local service, credentials and added permissions removed. Nothing was revoked: no device credential was stored here${page ? `. If this computer still shows in ${page}, revoke it there` : ''}.\n`);
65
87
  }
66
88
 
67
89
  export async function status({ json = false } = {}) {
@@ -0,0 +1,24 @@
1
+ import { installService } from './service.mjs';
2
+ import { installPermissions } from './permissions.mjs';
3
+ import { saveState } from './state.mjs';
4
+ import { rerCommand } from './invocation.mjs';
5
+
6
+ export const optInNames = ['installPermissions', 'awakeConsent', 'installService'];
7
+
8
+ export async function applyOptIns(api, state) {
9
+ let self;
10
+ // A server without this route answers a device credential with 403 (or 404):
11
+ // nothing is decided yet.
12
+ try { self = await api.get('/api/business/executors/self'); }
13
+ catch (error) { if (![403, 404].includes(error.status)) throw error; }
14
+ const decisions = Object.fromEntries(optInNames.map(name => [name, self?.optIns?.[name] === true ? true : self?.optIns?.[name] === false ? false : null]));
15
+ if (decisions.installPermissions === true) await installPermissions({ consent: true });
16
+ state.awakeConsent = decisions.awakeConsent === true;
17
+ await saveState(state);
18
+ if (decisions.installService === true) {
19
+ await installService({ consent: true });
20
+ process.stdout.write('Business background service installed.\n');
21
+ } else process.stdout.write(`Run ${rerCommand()} business run to work tasks.\n`);
22
+ const undecided = optInNames.filter(name => decisions[name] === null);
23
+ if (undecided.length) process.stdout.write(`Ask the owner to decide ${undecided.join(', ')} in ${state.origin}/business/${encodeURIComponent(state.businessId)}/settings, then run ${rerCommand()} business connect again.\n`);
24
+ }
@@ -11,16 +11,31 @@ export async function loadState() {
11
11
  catch (error) { if (error.code === 'ENOENT') return null; throw error; }
12
12
  }
13
13
 
14
+ export async function loadPending() {
15
+ try { return JSON.parse(await readFile(join(stateDirectory(), 'pairing.json'), 'utf8')); }
16
+ catch (error) { if (error.code === 'ENOENT') return null; throw error; }
17
+ }
18
+ export const savePending = pending => saveJson('pairing.json', pending);
19
+ export async function clearPending() {
20
+ await unlink(join(stateDirectory(), 'pairing.json')).catch(error => { if (error.code !== 'ENOENT') throw error; });
21
+ }
22
+
14
23
  // Only non-secret configuration and progress belong here. Credentials and task
15
24
  // grants remain in the keychain and memory, respectively.
16
25
  export async function saveState(state) {
26
+ return saveJson('state.json', state);
27
+ }
28
+
29
+ // A short-lived pairing poll token must survive agent turns. It is not a
30
+ // device credential; keep it private, expiring, and separate from paired state.
31
+ async function saveJson(name, value) {
17
32
  const directory = stateDirectory();
18
33
  await mkdir(directory, { recursive: true, mode: 0o700 });
19
34
  await chmod(directory, 0o700);
20
35
  const temporary = join(directory, `${randomUUID()}.tmp`);
21
36
  try {
22
- await writeFile(temporary, JSON.stringify(state) + '\n', { mode: 0o600, flag: 'wx' });
23
- await rename(temporary, join(directory, 'state.json'));
37
+ await writeFile(temporary, JSON.stringify(value) + '\n', { mode: 0o600, flag: 'wx' });
38
+ await rename(temporary, join(directory, name));
24
39
  } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
25
40
  }
26
41
 
package/cli/contract.mjs CHANGED
@@ -11,7 +11,7 @@ const definitions = {
11
11
  build: [['--site'], 'Production build with private local settings excluded and restored. --site instead writes the static run site (homepage, /run, docs) to its declared folder and prints that folder.'],
12
12
  verify: [[], 'Run the complete internal verification target.'],
13
13
  reset: [['--yes'], 'Confirmed removal of the declared local inventory only.'],
14
- deploy: [['--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the one-time setup token, then removes the token. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
14
+ deploy: [['--owner-name', '--environment', '--dry-run', '--site', '--demo', '--host', '--env-file', '--image', '--bind-address', '--http-port', '--https-port', '--remove', '--yes', '--set-secret', '--unset-secret', '--rotate-secret'], 'Owner-account deployment and health; dry run performs local validation/build only. Builds and deploy hooks run with the checkout\'s local settings files moved aside, and a build output holding one (.dev.vars, .env) is refused. Declared secrets come from the environment or --env-file (an owned 0600 KEY=VALUE file); a new Worker gets the local setup owner and fresh generated secrets when they are not given. rer keeps the secrets it generates in .rer/deploy/ENVIRONMENT.secrets.env (0600) and reuses them on every redeploy; it refuses to generate a replacement for one a live Worker holds, and --rotate-secret NAME[,NAME] replaces them on purpose. After a healthy deploy rer claims the setup owner on the hosted app with the saved setup owner name and the one-time setup token, then removes the token. If the installer declares an owner-name field and no name is saved, deploy asks once and saves it; --non-interactive requires --owner-name NAME before any upload. --set-secret NAME[,NAME] (each value from the environment or --env-file; repeat the flag or join names with commas) and --unset-secret NAME[,NAME] change those secrets of the deployed Worker without a build, all of them in one new Worker version or none, and record that version; a missing value refuses before any change. --remove --yes deletes what this environment\'s deploy record says rer created (Worker, D1, R2, KV, queues), reads back that each is gone, and touches nothing else. --site deploys the run site instead: an assets-only Worker on its custom domain with www redirected; with --dry-run it builds the site and prints the plan with no provider request. --demo deploys the hosted demo instead (deploy-demo.json): a front Worker on demo.<domain> giving each visitor their own signed-in, throwaway native Worker isolate of this seed with real public reads/checks and simulated external writes; --dry-run writes it to .rer/demo-host with no provider request; --demo --remove --yes deletes that demo (its Worker, demo.<domain> Custom Domain, each only while the record its deploy left proves it the demo\'s), reads back that each is gone, and is a no-op once it is.'],
15
15
  export: [['--target', '--output', '--origin', '--session-file'], 'Complete supported archive of the local copy on this computer, with integrity and exclusions, written to --output. The hosted install cannot be exported yet: --origin or --target remote refuses (exit 2) before any effect and names the command that saves the hosted database.'],
16
16
  import: [['--target', '--input', '--journal', '--origin', '--session-file', '--yes', '--legacy-v1', '--acknowledge-unverified-metadata', '--output'], 'Confirmed atomic restore into an empty destination; --journal LATER_ARCHIVE also fences rows that installation erased since. Backup-only local v1 recovery requires --legacy-v1 --acknowledge-unverified-metadata and a new --output v2 archive; --journal requires normal v2 import.'],
17
17
  doctor: [[], 'Read-only installed tool, configuration and state diagnostics.'],
@@ -6,6 +6,7 @@ import { invalid, refuse, RerError } from './errors.mjs';
6
6
  import { ownerDeploy } from './deploy.mjs';
7
7
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
8
8
  import { claimHostedOwner } from './deploy-owner.mjs';
9
+ import { deployOwnerInput } from './deploy-owner-input.mjs';
9
10
  import { checkHostedSetup, hostedSetupFailure } from './deploy-setup.mjs';
10
11
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
11
12
  import { observeOwner, ownerExchangeFailure } from './deploy-observation.mjs';
@@ -94,6 +95,7 @@ export async function deployCommand(context) {
94
95
  const production = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
95
96
  await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed: context.setupSeed, adapter, declarationPath: path, options });
96
97
  const sourceSha = options.dryRun ? undefined : committedSource(root, options);
98
+ const ownerInput = await deployOwnerInput(context);
97
99
  const { env, supplied, generated, reused, rotated } = await deployEnvironment({ root, options, declaration, setupManifest, settings, localOnlyKeys });
98
100
  const { createRedaction } = await shared('redaction.mjs');
99
101
  const redaction = createRedaction();
@@ -125,7 +127,7 @@ export async function deployCommand(context) {
125
127
  Object.assign(process.env, env);
126
128
  // The hook builds and uploads by itself: it never sees the checkout's local settings.
127
129
  deployed = await withoutLocalSettings(root, { settings: [...(Array.isArray(adapter.settings) ? adapter.settings : []), adapter.hooks?.secrets?.file], operationToken: context.operationToken },
128
- () => adapter.deploy({ ...context, linkDependencies: async (origin, token) => link(token, origin) }));
130
+ () => adapter.deploy({ ...context, input: ownerInput.input, linkDependencies: async (origin, token) => link(token, origin) }));
129
131
  } finally {
130
132
  for (const key of Object.keys(process.env)) if (!Object.hasOwn(saved, key)) delete process.env[key];
131
133
  Object.assign(process.env, saved);
@@ -150,7 +152,7 @@ export async function deployCommand(context) {
150
152
  if (typeof deployed.setupToken === 'string' && deployed.setupToken) addSecret(deployed.setupToken);
151
153
  const sentSecrets = (uploaded?.sentSecrets ?? []).filter(binding => uploaded.propagation.matchesToken(binding, env[declaration.secrets.find(item => item.binding === binding)?.environment]));
152
154
  const kit = state ? { secret: (extra, values) => command('secret', extra, values), recordClaim: outcome => command('record-owner', ['--outcome', outcome]) } : { token: deployed.setupToken || undefined };
153
- claimed = await claimHostedOwner({ hook: adapter.hooks?.owner, setupManifest, declaration, deployed: { ...state, sentSecrets, propagation:deployed.propagation ?? uploaded?.propagation, origin, owner: claimed, observedOwner: () => claims.at(-1)?.outcome }, env, supplied, ...kit, addSecret, beforeClaim: token => link(token, origin), store, signal: context.signal });
155
+ claimed = await claimHostedOwner({ hook: adapter.hooks?.owner, setupManifest, declaration, deployed: { ...state, sentSecrets, propagation:deployed.propagation ?? uploaded?.propagation, origin, owner: claimed, observedOwner: () => claims.at(-1)?.outcome }, env, ...ownerInput, supplied, ...kit, addSecret, beforeClaim: token => link(token, origin), store, signal: context.signal });
154
156
  if (!linked) await linkDependencies?.(origin);
155
157
  step = 'verify hosted setup';
156
158
  await checkHostedSetup({ origin, claimed: claimed ?? state?.ownerClaim?.outcome ?? claims.at(-1)?.outcome, signal: context.signal });
@@ -0,0 +1,35 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { invalid, missing } from './errors.mjs';
3
+ import { validOwnerName } from './parse.mjs';
4
+ import { savedSetupAnswers, rememberSetupAnswers } from './setup-answers.mjs';
5
+ import { shared } from './shared.mjs';
6
+
7
+ // Resolve the installer identity before building or uploading. Names are safe
8
+ // installer answers, not runtime secrets, and use the same custody as setup.
9
+ export async function deployOwnerInput({ root, adapter, setupSeed, options, signal }) {
10
+ const key = adapter.input?.names?.name ?? 'displayName';
11
+ if (!setupSeed?.model.fields[key]) {
12
+ if (options.ownerName !== undefined) throw invalid('This installer does not declare an owner-name field; --owner-name is unsupported.');
13
+ return { input: {} };
14
+ }
15
+ const project = { root, adapter, setupSeed };
16
+ const input = await savedSetupAnswers(project, setupSeed.model) ?? {};
17
+ let displayName = options.ownerName ?? input[key];
18
+ if (displayName === undefined && adapter.hooks?.secrets) {
19
+ const { readSettings } = await shared('adapter-settings.mjs');
20
+ displayName = (await readSettings(root, adapter.hooks.secrets)).values[key];
21
+ }
22
+ const advice = 'Deploy needs your owner name; run rer deploy --owner-name "Your name" (or rer setup --owner-name "Your name"). Nothing was uploaded.';
23
+ if (!displayName?.trim()) {
24
+ if (options.dryRun) return { input };
25
+ if (options.nonInteractive || options.json || !process.stdin.isTTY) throw missing(advice);
26
+ const prompt = createInterface({ input: process.stdin, output: process.stderr });
27
+ const closed = new Promise((_, reject) => prompt.once('close', () => reject(missing(advice))));
28
+ try { displayName = await Promise.race([prompt.question('Your name (hosted owner): ', { signal }), closed]); }
29
+ finally { prompt.close(); }
30
+ }
31
+ if (!validOwnerName(displayName)) throw invalid('Provide a valid owner name.');
32
+ input[key] = displayName;
33
+ if (!options.dryRun) await rememberSetupAnswers(project, input);
34
+ return { input, displayName };
35
+ }
@@ -13,7 +13,7 @@ import { randomBytes } from 'node:crypto';
13
13
  // deploy hook's own: rer claims with the `token` it returned, else the one rer
14
14
  // gave it, and leaves that token with the hook.
15
15
  // `beforeClaim(token)` runs while the token is live (dependency approvals need it).
16
- export async function claimHostedOwner({ hook, setupManifest, declaration, deployed, env, supplied = [], secret, token: hookToken, addSecret, beforeClaim, recordClaim, inspect, store, signal, fetch = globalThis.fetch }) {
16
+ export async function claimHostedOwner({ hook, setupManifest, declaration, deployed, env, input = {}, displayName, supplied = [], secret, token: hookToken, addSecret, beforeClaim, recordClaim, inspect, store, signal, fetch = globalThis.fetch }) {
17
17
  const claim = setupManifest?.steps?.find(step => step.type === 'owner-claim');
18
18
  if (!hook || !['object', 'function'].includes(typeof hook) || Array.isArray(hook) || !deployed.origin) {
19
19
  if (declaration.secrets?.some(item => item.binding === (claim?.tokenField ?? 'SETUP_TOKEN'))) throw ownerFailure('the owner bootstrap hook is unavailable');
@@ -52,7 +52,7 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
52
52
  return retire(linked.ownerOutcome);
53
53
  }
54
54
  if (typeof hook === 'function') {
55
- const context = { origin: deployed.origin, vars: { ...env, [tokenKey]: token }, input: {}, store, signal, ownerClaim: claim, fail: () => ownerFailure('the seed owner hook failed') };
55
+ const context = { origin: deployed.origin, vars: { ...env, [tokenKey]: token }, input, store, signal, ownerClaim: claim, fail: () => ownerFailure('the seed owner hook failed') };
56
56
  let observed, exchanges = [];
57
57
  try {
58
58
  if (deployed.observedOwner) await hook(context);
@@ -69,7 +69,7 @@ export async function claimHostedOwner({ hook, setupManifest, declaration, deplo
69
69
  if (!['claimed', 'kept'].includes(outcome)) throw ownerFailure('the seed owner hook did not confirm its bootstrap exchange');
70
70
  return retire(outcome);
71
71
  }
72
- const displayName = (typeof hook.displayName === 'function' ? hook.displayName({}) : undefined) || 'Owner';
72
+ displayName = (typeof hook.displayName === 'function' ? hook.displayName(input) : undefined) || displayName || 'Owner';
73
73
  let response, code = 'no code';
74
74
  try {
75
75
  response = await ownerClaimRequest(fetch, new URL(hook.path ?? '/auth/bootstrap', deployed.origin), { method: 'POST',
package/cli/deploy.mjs CHANGED
@@ -10,6 +10,7 @@ import { packageBuild } from '../modules/deploy-kit/prepare.mjs';
10
10
  import { refuseLocalModels } from '../modules/deploy-kit/local-only.mjs';
11
11
  import { deployEnvironment, deployAgain } from './deploy-inputs.mjs';
12
12
  import { claimHostedOwner } from './deploy-owner.mjs';
13
+ import { deployOwnerInput } from './deploy-owner-input.mjs';
13
14
  import { checkHostedSetup, hostedSetupFailure } from './deploy-setup.mjs';
14
15
  import { mutationReadinessFailure } from './deploy-readiness.mjs';
15
16
  import { committedSource } from './deploy-source.mjs';
@@ -21,7 +22,7 @@ import { withoutLocalSettings, refuseLocalEnvOutput } from './local-env.mjs';
21
22
 
22
23
  export function ownerDeploy(declarationPath, lifecycle) {
23
24
  // rer verify serves the build with this declaration's vars and secrets.
24
- return Object.assign(async ({ root, options, store, signal, operationToken, localOnlyKeys = [], checkBuild = async () => {}, setupManifest, setupSeed, linkDependencies }) => {
25
+ return Object.assign(async ({ root, options, store, signal, operationToken, localOnlyKeys = [], checkBuild = async () => {}, setupManifest, setupSeed, linkDependencies, adapter = lifecycle }) => {
25
26
  try { await refuseLocalModels(root); } catch { throw refuse('Deploy refuses the local-only key file .rer/local/models.json. Remove live-dev credentials before deployment.'); }
26
27
  const path = await contained(root, declarationPath);
27
28
  let declaration; try { declaration = JSON.parse(await readFile(path, 'utf8')); } catch { throw invalid('Malformed owner-account deploy declaration.'); }
@@ -37,11 +38,12 @@ export function ownerDeploy(declarationPath, lifecycle) {
37
38
  const recordedState = change.length ? await deploymentRecord(root, options) : undefined;
38
39
  // A dry run reads the settings file too, so a refused key fails here and not only on the real deploy.
39
40
  if (options.dryRun && options.envFile) await deployEnvironment({ root, options, declaration, localOnlyKeys });
40
- let production;
41
+ let production, ownerInput;
41
42
  if (!change.length) {
42
43
  production = await deployEnvironment({ root, options, declaration, setupManifest, settings: lifecycle.settings, localOnlyKeys });
43
44
  await requireProductionAuth({ root, declaration, env: production.env, setupManifest, setupSeed, adapter: lifecycle, declarationPath, options });
44
45
  if (!options.dryRun) committedSource(root, options);
46
+ ownerInput = await deployOwnerInput({ root, adapter, setupSeed, options, signal });
45
47
  await withoutLocalSettings(root, { settings: lifecycle.settings, operationToken }, () => lifecycle.run(root, {}, store, () => {}, signal, { verb: 'build', operationToken }));
46
48
  await checkBuild();
47
49
  await refuseLocalEnvOutput(root);
@@ -112,7 +114,7 @@ export function ownerDeploy(declarationPath, lifecycle) {
112
114
  step = 'claim owner';
113
115
  const { liveSecrets, retiredSecrets, ownerClaim } = await owner('inspect', [], env, {propagation:deployed.propagation});
114
116
  const linked = token => linkDependencies?.(deployed.origin, token);
115
- const claimed = await claimHostedOwner({ hook: lifecycle.hooks?.owner, setupManifest, declaration, deployed: { ...deployed, propagation:deployed.propagation, liveSecrets, retiredSecrets, ownerClaim }, env, supplied, addSecret: value => { redaction.addSecrets([value]); store.addSecrets?.([value]); },
117
+ const claimed = await claimHostedOwner({ hook: lifecycle.hooks?.owner, setupManifest, declaration, deployed: { ...deployed, propagation:deployed.propagation, liveSecrets, retiredSecrets, ownerClaim }, env, ...ownerInput, supplied, addSecret: value => { redaction.addSecrets([value]); store.addSecrets?.([value]); },
116
118
  secret: (extra, values) => owner('secret', extra, values), beforeClaim: linked, recordClaim: outcome => owner('record-owner', ['--outcome', outcome]), inspect: () => owner('inspect', [], env, {propagation:deployed.propagation}), store, signal });
117
119
  // A seed that claims its owner its own way links with the token it was given.
118
120
  if (claimed === undefined) await linked(env[declared(claim?.tokenField ?? 'SETUP_TOKEN')?.environment]);
package/cli/parse.mjs CHANGED
@@ -5,6 +5,7 @@ import { isLoopbackHost } from '../modules/operator-auth/loopback.mjs';
5
5
  import { normalizeEmail } from '../modules/operator-auth/policy.mjs';
6
6
  const booleans = new Set(['--help', '--json', '--non-interactive', '--yes', '--dry-run', '--stop', '--detach', '--foreground', '--no-queue', '--login', '--legacy-v1', '--acknowledge-unverified-metadata', '--door', '--direct', '--site', '--remove', '--demo']);
7
7
  export const mailbox = value => typeof value === 'string' && value.length <= 254 && /^[a-zA-Z0-9.!+_%\-]+@[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)+$/.test(value);
8
+ export const validOwnerName = value => typeof value === 'string' && Boolean(value.trim()) && value.length <= 200 && !/[\p{Cc}\p{Cf}]/u.test(value);
8
9
  // A loopback host: the shared predicate (including `*.localhost` door names),
9
10
  // plus `::1` as --host and a bracket-stripped hostname spell it.
10
11
  export const loopback = host => host === '::1' || isLoopbackHost(host);
@@ -81,7 +82,7 @@ export function parse(argv, cwd = process.cwd(), { independent = false, deferTai
81
82
  if(options.platform !== undefined && !['workers','container'].includes(options.platform))throw invalid('Platform must be workers or container.');
82
83
  if (options.host !== undefined && !(verb === 'deploy' && options.platform === 'container') && !listenHost(options.host)) throw refuse('Host must be exactly 127.0.0.1, localhost or ::1.');
83
84
  if (options.ownerEmail !== undefined) { if (!mailbox(options.ownerEmail)) throw invalid('Provide a valid plain owner mailbox.'); options.ownerEmail = options.ownerEmail.toLowerCase(); }
84
- if (options.ownerName !== undefined && (options.ownerName.length > 200 || /[\p{Cc}\p{Cf}]/u.test(options.ownerName))) throw invalid('Provide a valid owner name.');
85
+ if (options.ownerName !== undefined && !validOwnerName(options.ownerName)) throw invalid('Provide a valid owner name.');
85
86
  if (options.target !== undefined && !['local', 'remote'].includes(options.target)) throw invalid('Target must be local or remote.');
86
87
  if (options.profile !== undefined && options.profile !== 'first-party') throw invalid('The supported explicit profile is first-party.');
87
88
  if (options.environment !== undefined && !/^[a-z][a-z0-9-]{0,39}$/.test(options.environment)) throw invalid('Provide a valid deployment environment name.');
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.55
4
+
5
+ - **Business works across agent turns.** `business connect` resumes browser-approved pairing without terminal prompts, prints a runnable npx or installed-launcher resume command, and reads browser opt-ins after credential storage. Local discovery accepts raw and encoded task upload paths and reports failed work. Disconnect revokes the device on the server before removing its local credential; an unsupported or unconfirmed revocation keeps the connection and explains the browser action (#248).
6
+
7
+ ## 0.2.54
8
+
9
+ - **Dev launch handoffs keep the requested lifetime.** An explicit `rer dev --foreground` or `--detach` survives preparation that installs a checkout’s pinned rer and hands off to its launcher. The default terminal behavior stays the same (#258).
10
+ - **Hosted installs keep the setup owner name.** Deploy carries the name saved by setup into hosted owner bootstrap. When a declared name is missing, interactive deploy asks once and saves it; unattended deploy requires `--owner-name` before uploading. Installers without a name field keep their existing behavior (#257).
11
+
3
12
  ## 0.2.53
4
13
 
5
14
  - **Dropdowns share one themed chevron rule.** Base's operator app and installer draw a 12 px chevron 14 px from the right border with 40 px end padding. Exported seeds can copy `selectStyle` from `src/base/select-style.ts`; its gradient strokes follow the theme color and work under the seed's content security policy. Focus, disabled, right-to-left and forced-color states are included (#247).
package/global/README.md CHANGED
@@ -371,18 +371,39 @@ formats and syntax may yield no signals.
371
371
  ## Business device commands
372
372
 
373
373
  `rer business connect --code ABCD-1234 [--origin https://app.runeditrun.com]`
374
- redeems a browser-created code, prints a six-digit confirmation number and waits
375
- for approval in the browser that created it. Device credentials stay in macOS
376
- Keychain or Linux Secret Service. A missing or locked Secret Service refuses;
377
- there is no plaintext credential store. Linux needs `secret-tool` and an
374
+ redeems a browser-created code and prints a six-digit confirmation number for
375
+ approval in the browser that created it. Without a terminal it returns while
376
+ approval is pending. Run `rer business connect` again in a later turn to resume
377
+ the same pairing and number; a new server pairing is never started until the
378
+ old one is refused, expired or disconnected. The waiting line names the command
379
+ that works from the agent's own shell: `rer` when it is on PATH, the launcher
380
+ install.sh wrote, or `npx -y @runeditrun/rer` after an npx run. Pending tokens
381
+ are kept in the private CLI config directory until the code's expiry plus the
382
+ ten minutes the server allows after an approval, so an approval near the code's
383
+ end can still be collected. Device credentials stay in macOS
384
+ Keychain or Linux Secret Service. A missing or locked store refuses before the
385
+ one-use code is redeemed; there is no plaintext credential store. Linux needs `secret-tool` and an
378
386
  unlocked desktop Secret Service session.
379
387
 
380
- In a terminal, connect asks separately before adding Claude Code user Read deny
381
- rules, allowing export-scoped macOS wake prevention, and installing a launchd
382
- or systemd user service. Only the exact answer `yes` opts in. Noninteractive
383
- connect pairs but leaves those optional changes off. Background services use
388
+ The owner chooses Claude Code user Read deny rules, export-scoped macOS wake
389
+ prevention, and a launchd or systemd user service in the browser. Connect reads
390
+ `optIns` from device-authenticated `GET /api/business/executors/self`, with keys
391
+ `installPermissions`, `awakeConsent` and `installService`. Only `true` enables
392
+ an option. Undecided (`null`) options print a browser link; an older server
393
+ without this route (it answers 403 or 404) leaves all options undecided. Run connect again after the
394
+ owner decides. The first device-authenticated request happens after both the
395
+ credential and local pairing state are stored, so a storage failure cannot
396
+ activate the computer. Background services use
384
397
  absolute Node and CLI paths. No model process is started.
385
398
 
399
+ An agent can run `npx -y @runeditrun/rer business connect --code ABCD-1234 --origin URL`
400
+ directly, without a global installation. In Codex's workspace-write sandbox,
401
+ allow network access and the CLI's config directory (`~/.rer`), and put npm's
402
+ cache inside the working folder with `npm_config_cache="$PWD/.rer/npm"`.
403
+ Later turns can omit `--code` to resume the saved request. Do not install a
404
+ background service or change user settings unless the owner enables those
405
+ options and the sandbox permits their locations.
406
+
386
407
  `rer business vendor-key add sentry` requires hidden credential entry in a
387
408
  terminal, stores it in the OS keychain and prints only `sentry:read`.
388
409
  `remove` deletes it. The same commands support `uptimerobot`, `pagerduty` and
@@ -402,10 +423,16 @@ a headers helper. That output is a short-lived credential: connect it directly
402
423
  to the MCP client and do not paste it into an agent transcript.
403
424
 
404
425
  `rer business status` shows local pairing, service state and progress without
405
- printing checkpoints or vendor data. `rer business disconnect` removes the
406
- service, device and vendor credentials, state and introduced Claude rules,
407
- preserving preexisting settings and unrelated edits. Revocation in the browser
408
- removes remote authority; disconnect removes the local installation's additions.
426
+ printing checkpoints or vendor data. `rer business disconnect` revokes this
427
+ device through device-authenticated `DELETE /api/business/executors/self` before
428
+ removing its service, device and vendor credentials, state and introduced Claude
429
+ rules, preserving preexisting settings and unrelated edits. It says "Device
430
+ revoked" only after the server confirms (`{"revoked":true}`, or 401 for a device
431
+ already revoked). A server without that route (403 or 404) leaves the computer
432
+ connected: disconnect says so, names the browser page to revoke it in and keeps
433
+ everything for a later disconnect. Any other failure exits 1 and also keeps the
434
+ credential for a retry. With no stored device credential, nothing is sent and
435
+ disconnect removes the local additions without claiming a revocation.
409
436
 
410
437
  `rer business run` performs consented `discover.local` tasks through claims,
411
438
  short-lived task bearers, quota-bound uploads, 60-second heartbeats and server
@@ -41,8 +41,9 @@ async function writeLauncher(paths) {
41
41
 
42
42
  // The next step, then (when needed) the exact line that puts rer on PATH, last.
43
43
  // install.sh running a command itself, and rer update, set RER_INSTALL_NO_NEXT.
44
+ // Business connect also suppresses PATH advice: it uses the launcher directly.
44
45
  async function closing(paths) {
45
- const advice = await pathAdvice(paths);
46
+ const advice = process.env.RER_INSTALL_NO_PATH ? '' : await pathAdvice(paths);
46
47
  return `${process.env.RER_INSTALL_NO_NEXT ? '' : 'Next, start an app: rer dev <owner>/<repo>\n'}${advice ? advice + '\n' : ''}`;
47
48
  }
48
49
 
@@ -35,7 +35,7 @@ export async function launchDev(target) {
35
35
  }
36
36
  // An invocation the pinned dispatcher refuses goes straight to it, so the
37
37
  // refusal is its own, with nothing prepared first.
38
- if (!await accepted(target.root, devArgs)) return delegate(target, ['dev', ...devArgs]);
38
+ if (!await accepted(target.root, devArgs)) return delegateDev(target);
39
39
  const checkout = await realpath(target.root), directory = await launchDirectory(checkout);
40
40
  if (devArgs.includes('--stop')) {
41
41
  try { return await stopLaunch(target, devArgs, { checkout, directory }); }
@@ -47,6 +47,14 @@ export async function launchDev(target) {
47
47
  return detach ? detached(target, devArgs, directory, out, doorStart) : foreground(target, devArgs, directory, out, doorStart);
48
48
  }
49
49
 
50
+ // Preparation can install a pin whose entry is another global launcher. Keep
51
+ // the caller's lifetime flags across that handoff. The internal front-door
52
+ // marker reaches other launchers, but never the public dispatcher.
53
+ function delegateDev(target) {
54
+ const { launcher } = dispatcher(target.root);
55
+ return delegate(target, launcher ? target.args : target.args.filter(arg => arg !== '--door-start'));
56
+ }
57
+
50
58
  async function doorCapable(root) {
51
59
  try { return Boolean((await describeCheckout(root, dispatcher(root).entry, process.env)).door); } catch { return true; }
52
60
  }
@@ -72,7 +80,7 @@ async function foreground(target, devArgs, directory, out, doorStart) {
72
80
  catch (failure) { if (!(failure instanceof LaunchFailure)) throw failure; out.failure(failure); return failure.exitCode; }
73
81
  finally { clearInterval(heartbeat); log.end(); }
74
82
  Object.assign(process.env, prepared.added);
75
- return delegate(target, ['dev', ...devArgs]);
83
+ return delegateDev(target);
76
84
  }
77
85
 
78
86
  async function detached(target, devArgs, directory, out, doorStart) {
package/install.sh CHANGED
@@ -141,15 +141,21 @@ if (process.argv[5] !== '' && Number(process.argv[5]) !== total) stop('the archi
141
141
  NODE
142
142
  mkdir "$work/stage"
143
143
  tar -xzf "$work/rer.tgz" -C "$work/stage" || fail "could not unpack rer $version; nothing was installed."
144
- # It ends with the next step and, when rer is not on PATH in new terminals,
145
- # the exact line that puts it there (no npx: Node may be rer's own).
144
+ # A supplied command replaces the app next step. Business connect runs the
145
+ # launcher directly, so it also needs no PATH advice.
146
146
  no_next=
147
+ no_path=
147
148
  if [ "$#" -gt 0 ]; then no_next=1; fi
148
- RER_INSTALL_CHANNEL=script RER_INSTALL_NO_NEXT=$no_next "$node_binary" "$work/stage/package/global/rer.mjs" cli install </dev/null \
149
+ if [ "${1:-}" = business ] && [ "${2:-}" = connect ]; then no_path=1; fi
150
+ RER_INSTALL_CHANNEL=script RER_INSTALL_NO_NEXT=$no_next RER_INSTALL_NO_PATH=$no_path "$node_binary" "$work/stage/package/global/rer.mjs" cli install </dev/null \
149
151
  || fail "rer cli install failed; any previous install is still selected."
150
152
  if [ "$#" -eq 0 ]; then return; fi
153
+ # The command can tell the person how to run rer again from their own shell,
154
+ # where ~/.local/bin may not be on PATH yet.
155
+ RER_INVOKED_AS="$HOME/.local/bin/rer"
156
+ if [ "$(command -v rer 2>/dev/null || true)" = "$RER_INVOKED_AS" ]; then RER_INVOKED_AS=rer; fi
151
157
  PATH="$PATH:$HOME/.local/bin"
152
- export PATH
158
+ export PATH RER_INVOKED_AS
153
159
  "$HOME/.local/bin/rer" "$@"
154
160
  }
155
161
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.53",
3
+ "version": "0.2.55",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,12 +0,0 @@
1
- import { createInterface } from 'node:readline/promises';
2
-
3
- // Consent can never be inferred from a flag, a prior pairing, or a default.
4
- export async function consent(question) {
5
- if (!process.stdin.isTTY || !process.stdout.isTTY) {
6
- process.stderr.write(`${question} Run connect in a terminal to answer yes.\n`);
7
- return false;
8
- }
9
- const terminal = createInterface({ input: process.stdin, output: process.stdout });
10
- try { return (await terminal.question(`${question} [yes/no] `)).trim().toLowerCase() === 'yes'; }
11
- finally { terminal.close(); }
12
- }