@runeditrun/rer 0.2.54 → 0.2.56

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
@@ -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
 
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.56
4
+
5
+ - **Run pages keep inline words and paths whole.** Inline code wraps only between words, so seed names such as `run-linen`, repository paths and start commands no longer split mid-word. Command blocks stay clear of Copy and copied text keeps its original bytes. Seeds receive the template on their next Base-copy refresh (#266).
6
+
7
+ ## 0.2.55
8
+
9
+ - **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).
10
+
3
11
  ## 0.2.54
4
12
 
5
13
  - **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).
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
 
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.54",
3
+ "version": "0.2.56",
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
- }