@runeditrun/rer 0.2.62 → 0.2.63

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,36 +371,57 @@ 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 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
386
- unlocked desktop Secret Service session.
387
-
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
397
- absolute Node and CLI paths. No model process is started.
374
+ redeems a browser-created code, prints a six-digit confirmation number for
375
+ approval in the browser that created it, and waits in the foreground until the
376
+ owner approves or refuses there or the code expires (ten minutes). It exits 0
377
+ only once the computer is active: the credential is stored and the server has
378
+ seen the computer. A refusal or expiry exits 1 with the server's reason.
379
+ Interrupting it (Ctrl-C, or an agent's tool timeout) keeps the redeemed pairing:
380
+ run `rer business connect` again to resume the same pairing and number; a new
381
+ server pairing is never started until the old one is refused, expired or
382
+ disconnected. The waiting line names the command that works from the agent's
383
+ own shell: `rer` when it is on PATH, the launcher install.sh wrote, or
384
+ `npx -y @runeditrun/rer` after an npx run. Pending tokens are kept until the
385
+ code's expiry plus the ten minutes the server allows after an approval, so an
386
+ approval near the code's end can still be collected.
387
+
388
+ State lives in `$RER_BUSINESS_STATE_DIR` when it is set, and in `~/.rer/business`
389
+ otherwise. `RER_STATE_DIR` is `rer demo`'s variable and Business never reads it.
390
+ Connect also sends the computer's plain name (its host name's first word group,
391
+ without the login name, at most 64 characters) and the folder it runs in, so the
392
+ browser can show which computer this is and prefill the scan folder.
393
+ Before redeeming the code (or collecting an approval), connect proves
394
+ it can write that folder and that OS credential storage accepts a write; if
395
+ either fails it stops, names the folder or the cause, and the code still works.
396
+ Device credentials stay in macOS Keychain or Linux Secret Service; there is no
397
+ plaintext credential store. Linux needs `secret-tool` and an unlocked desktop
398
+ Secret Service session. Every failure names its cause: the server's reason, the
399
+ local system cause, or what to change.
400
+
401
+ The owner chooses three things on the computer's row in the browser: "Add rules
402
+ so Claude Code never reads your secret files" (Claude Code user Read deny
403
+ rules), "Keep this computer awake while it works" (export-scoped macOS wake
404
+ prevention) and "Install the background service" (a launchd or systemd user
405
+ service). Connect reads them as `optIns` from device-authenticated
406
+ `GET /api/business/executors/self`, with keys `installPermissions`,
407
+ `awakeConsent` and `installService`; the CLI prints only the sentences. Only
408
+ `true` enables an option. Undecided (`null`) options are listed with a browser
409
+ link; an older server without this route (it answers 403 or 404) leaves all
410
+ options undecided. Run connect again after the owner decides. The first
411
+ device-authenticated request happens after both the credential and local
412
+ pairing state are stored, so a storage failure cannot activate the computer.
413
+ A service installed with `RER_BUSINESS_STATE_DIR` set keeps that folder. Background
414
+ services use absolute Node and CLI paths. No model process is started.
398
415
 
399
416
  An agent can run `npx -y @runeditrun/rer business connect --code ABCD-1234 --origin URL`
400
417
  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
418
+ allow network access, set `RER_BUSINESS_STATE_DIR="$PWD/.rer-business"` so state stays
419
+ inside the working folder, and put npm's cache there too with
420
+ `npm_config_cache="$PWD/.rer/npm"`. macOS refuses Keychain writes from inside
421
+ that sandbox, so connect stops before redeeming and asks for this one command to
422
+ run outside the sandbox (in Codex, approve running that command outside the
423
+ sandbox when it asks); later commands
424
+ only read the credential and run inside the sandbox. Do not install a
404
425
  background service or change user settings unless the owner enables those
405
426
  options and the sandbox permits their locations.
406
427
 
@@ -1,4 +1,5 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
+ import { redact } from './errors.mjs';
2
3
 
3
4
  export function originUrl(value = 'https://app.runeditrun.com') {
4
5
  let url;
@@ -10,13 +11,46 @@ export function originUrl(value = 'https://app.runeditrun.com') {
10
11
  return url.origin;
11
12
  }
12
13
 
14
+ // The server's own reason travels with its status: platform errors answer
15
+ // {error, requestId}. It is shown as one bounded line of text, never as markup.
13
16
  export class ApiError extends Error {
14
- constructor(status) {
15
- super(status === 401 ? 'Business pairing was revoked or expired. Reconnect in your browser.' : `Business server refused the request (HTTP ${status}).`);
16
- this.status = status;
17
+ constructor(status, reason = null, requestId = null) {
18
+ const said = reason ? ` The server said: ${reason}${/[.!?]$/.test(reason) ? '' : '.'}` : '';
19
+ const reference = requestId ? ` Reference ${requestId}.` : '';
20
+ super((status === 401 ? 'Business pairing was revoked or expired. Reconnect in your browser.' : `Business server refused the request (HTTP ${status}).`) + said + reference);
21
+ this.status = status; this.reason = reason; this.requestId = requestId;
17
22
  }
18
23
  }
19
24
 
25
+ async function refusal(response) {
26
+ let text = '';
27
+ try { text = (await response.text()).slice(0, 4096); } catch { /* The status alone is the reason. */ }
28
+ let body = null;
29
+ try { body = JSON.parse(text); } catch { /* A plain-text reason is used as it is. */ }
30
+ const line = value => typeof value === 'string' && value.trim() ? redact(value).replace(/\s+/g, ' ').trim().slice(0, 300) : null;
31
+ const reason = body && typeof body === 'object' ? line(body.error) ?? line(body.message) : /^\s*</.test(text) ? null : line(text);
32
+ const requestId = body && typeof body === 'object' && typeof body.requestId === 'string' && /^[A-Za-z0-9_.:-]{1,80}$/.test(body.requestId) ? body.requestId : null;
33
+ return new ApiError(response.status, reason, requestId);
34
+ }
35
+
36
+ const network = {
37
+ ECONNREFUSED: 'the connection was refused; check that the server is running',
38
+ ENOTFOUND: 'its name did not resolve; network access may be off in this session',
39
+ EAI_AGAIN: 'its name did not resolve; network access may be off in this session',
40
+ EPERM: 'the network was blocked (Operation not permitted); allow network access for this session',
41
+ EACCES: 'the network was blocked (permission denied); allow network access for this session',
42
+ ECONNRESET: 'the connection was reset',
43
+ ETIMEDOUT: 'the connection timed out',
44
+ EHOSTUNREACH: 'the host is unreachable',
45
+ ENETUNREACH: 'the network is unreachable',
46
+ };
47
+ function unreachable(origin, error) {
48
+ const code = error?.cause?.code ?? error?.code;
49
+ const cause = error?.name === 'TimeoutError' ? 'it did not answer within 30 seconds'
50
+ : network[code] ?? (code ? `the request failed (${code})` : `the request failed (${error?.cause?.message ?? error?.message ?? 'no reason given'})`);
51
+ return Error(`Could not reach the Business server at ${origin}: ${redact(cause)}.`);
52
+ }
53
+
20
54
  export class Api {
21
55
  constructor(origin, credential) { this.origin = originUrl(origin); this.credential = credential; }
22
56
  async mintToken(audience, { taskId, signal } = {}) {
@@ -42,9 +76,9 @@ export class Api {
42
76
  headers: { ...headers, 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
43
77
  ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(timeout)]) : AbortSignal.timeout(timeout),
44
78
  });
45
- } catch (error) { if (signal?.aborted) throw signal.reason; throw Error('Could not reach the Business server.'); }
46
- if (!response.ok) { await response.body?.cancel(); throw new ApiError(response.status); }
47
- // Never print server errors or evidence; even successful bodies are untrusted.
79
+ } catch (error) { if (signal?.aborted) throw signal.reason; throw unreachable(this.origin, error); }
80
+ if (!response.ok) throw await refusal(response);
81
+ // Successful bodies are untrusted: callers validate them and print only fields they template.
48
82
  if (response.status === 202 && response.headers.get('content-length') === '0' || response.status === 204) return null;
49
83
  const text = await response.text();
50
84
  if (!text) return null;
@@ -3,11 +3,13 @@ import { connect } from './connect.mjs';
3
3
  import { vendorKey, disconnect, status } from './local-commands.mjs';
4
4
  import { next, answer, token } from './questions.mjs';
5
5
  import { run } from './supervisor.mjs';
6
+ import { describe } from './errors.mjs';
6
7
 
7
8
  const usage = `Usage: rer business VERB
8
9
  scan [DIR...] [--json] Names-only local discovery
9
10
  connect [--code CODE] [--origin URL]
10
- Pair or resume; the owner approves and chooses opt-ins in the browser
11
+ Pair this computer, waiting until the owner approves in the browser
12
+ (up to the code's 10 minutes); run it again to resume
11
13
  run [--once] Run consented local discovery; vendor upload integration pending
12
14
  next Return one templated question or nothing yet within 60 seconds
13
15
  answer ID VENDOR USAGE [CONFIDENCE]
@@ -17,6 +19,8 @@ const usage = `Usage: rer business VERB
17
19
  status [--json] Pairing, service, current task and checkpoint
18
20
  disconnect Revoke this computer, then remove local credentials and additions
19
21
  Vendors: sentry, uptimerobot, pagerduty, calendly. Owner approvals stay in the browser.
22
+ State lives in $RER_BUSINESS_STATE_DIR when set, otherwise in ~/.rer/business.
23
+ In an agent sandbox that writes only inside its working folder, use RER_BUSINESS_STATE_DIR="$PWD/.rer-business".
20
24
  `;
21
25
 
22
26
  export async function businessCommand(argv) {
@@ -41,11 +45,9 @@ export async function businessCommand(argv) {
41
45
  else return invalid();
42
46
  return 0;
43
47
  } catch (error) {
44
- // All messages emitted here are authored by this CLI, never server/vendor or
45
- // OS diagnostics. Unexpected errors can contain paths or credential material.
46
- const message = error instanceof Error && /^(?:Business |This computer |This item |Choose |OS credential |Enter |Credential |A terminal |Installing |Changing |Keeping |Could not (?:reach the Business|keep this Mac|start the Business|stop the Business|reload the Business)|Claude |The Business |A Business |Another process |Run rer )/.test(error.message)
47
- ? error.message : 'Business command failed. Check pairing, OS credential storage and browser task requirements.';
48
- process.stderr.write(message + '\n'); return 1;
48
+ // Name the cause: the server's reason, the local cause or this CLI's own
49
+ // explanation. Bearers are redacted from every message.
50
+ process.stderr.write(describe(error) + '\n'); return error?.exitCode ?? 1;
49
51
  }
50
52
  }
51
53
  function invalid() { process.stderr.write(usage); return 2; }
@@ -1,10 +1,12 @@
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, loadPending, savePending, clearPending } from './state.mjs';
4
+ import { loadState, saveState, credentialHandle, loadPending, savePending, clearPending, checkStateWritable } from './state.mjs';
5
5
  import { createCredentialStore } from './keychain.mjs';
6
6
  import { applyOptIns } from './opt-ins.mjs';
7
7
  import { rerCommand } from './invocation.mjs';
8
+ import { Stopped } from './errors.mjs';
9
+ import { deviceName, workingFolder } from './device.mjs';
8
10
 
9
11
  // Approval moves the server's pairing expiry to ten minutes after approval, and
10
12
  // approval can come up to the code's own expiry. Keep the pending pairing until
@@ -13,65 +15,99 @@ const approvalWindow = 600_000;
13
15
 
14
16
  export const capabilities = ['discover.local', 'export.vendor:sentry', 'export.vendor:uptimerobot', 'export.vendor:pagerduty', 'export.vendor:calendly'];
15
17
 
18
+ const clock = time => new Date(time).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
19
+ const nothingSent = 'Nothing was sent, so the pairing code still works.';
20
+
21
+ /** Pair (or resume a saved pairing) and wait in the foreground until the owner
22
+ * approves or refuses in the browser, or the code expires. Exit 0 means the
23
+ * computer is active: its credential is stored and the server has seen it.
24
+ */
16
25
  export async function connect({ code, origin } = {}) {
17
26
  const stored = await loadState();
18
27
  let pending = await loadPending();
19
28
  origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
20
29
  if (stored) {
21
- if (stored.origin !== origin) throw Error('Business is paired to another origin. Disconnect before pairing again.');
30
+ if (stored.origin !== origin) throw Error(`This computer is already connected to Business at ${stored.origin}. Run ${rerCommand()} business disconnect before connecting it elsewhere.`);
22
31
  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.');
32
+ if (!credential) throw Error(`This computer's Business credential is missing from OS credential storage. Run ${rerCommand()} business disconnect, then connect again with a new code from ${origin}/business.`);
24
33
  await applyOptIns(new Api(origin, credential), stored);
25
34
  return;
26
35
  }
27
36
  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}.`);
37
+ if (pending && (pending.origin !== origin || code && pending.code !== code)) throw Error(`Business is already waiting for approval of another code${pending.origin === origin ? '' : ` at ${pending.origin}`}. Run ${rerCommand()} business connect to resume it, or ${rerCommand()} business disconnect to drop it before using another code.`);
38
+ if (!pending && !code) throw Error(`Business needs a pairing code. Open ${origin}/business, then run ${rerCommand()} business connect --code CODE --origin ${origin}.`);
39
+ // Refuse before redeeming the one-use code or collecting an approval when this
40
+ // session cannot keep the pairing or store the device credential.
41
+ await checkStateWritable();
30
42
  const store = createCredentialStore(), handle = credentialHandle(origin);
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);
34
- const api = new Api(origin);
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
+ try { await store.get(handle); await store.check(); }
44
+ catch (error) {
45
+ const outside = error.sandboxRefused ? ` Approve this command outside the sandbox: ${rerCommand()} business connect${code ? ` --code ${code}` : ''} --origin ${origin}. Every other business command runs inside the sandbox.` : '';
46
+ throw Error(`${error.message}${outside} ${pending ? 'The saved pairing was kept; run connect again once this is fixed.' : nothingSent}`);
43
47
  }
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;
48
+
49
+ // Ctrl-C or a stopped tool call never strands a pairing: the redeemed pairing
50
+ // is saved before waiting, and a collected credential is stored before exit.
51
+ const stop = new AbortController();
52
+ const stopWith = signal => () => stop.abort(signal);
53
+ const onInterrupt = stopWith('SIGINT'), onTerminate = stopWith('SIGTERM');
54
+ process.on('SIGINT', onInterrupt); process.on('SIGTERM', onTerminate);
55
+ try {
56
+ const api = new Api(origin);
57
+ if (!pending) {
58
+ // The computer's plain name and the folder connect runs in help the owner
59
+ // recognise this computer and prefill the scan folder; each is left out when empty.
60
+ const name = deviceName(), folder = workingFolder();
61
+ const response = await api.post('/api/business/executors/pair', {
62
+ code, ...(name ? { device_name: name } : {}), ...(folder ? { working_folder: folder } : {}),
63
+ os: process.platform === 'darwin' ? 'macos' : 'linux', agent_kind: process.env.CODEX_HOME ? 'codex' : process.env.CLAUDECODE ? 'claude' : 'other', capabilities,
64
+ }).catch(error => { throw error.status === 401 ? Error(`Business did not accept code ${code}: it has expired or was already used${error.reason ? ` (the server said: ${error.reason})` : ''}. Create a new code in ${origin}/business.`) : error; });
65
+ const expires = Math.min(Date.now() + 600_000, Date.parse(response?.expires_at));
66
+ 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.');
67
+ pending = { origin, code, pairing_token: response.pairing_token, confirmation_number: response.confirmation_number, code_expires_at: new Date(expires).toISOString(), expires_at: new Date(expires + approvalWindow).toISOString() };
68
+ await savePending(pending);
62
69
  }
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.');
70
+ const resume = `${rerCommand()} business connect --origin ${origin}`;
71
+ const until = pending.code_expires_at ? ` until ${clock(pending.code_expires_at)}, when the code expires` : ' until the code expires';
72
+ process.stdout.write(`Confirmation number: ${pending.confirmation_number}\nCompare this number in the browser that created the code, then approve there.\nWaiting for approval in ${origin}/business${until}. Keep this command running.\nIf it stops, run ${resume} to resume this pairing.\n`);
73
+ while (Date.now() < Date.parse(pending.expires_at)) {
74
+ if (stop.signal.aborted) break;
75
+ let result;
76
+ try { result = await api.post('/api/business/executors/pair', { pairing_token: pending.pairing_token }, { signal: stop.signal }); }
77
+ catch (error) {
78
+ if (stop.signal.aborted) break;
79
+ if ([401, 403, 410].includes(error.status)) {
80
+ await clearPending();
81
+ throw Error(`Business pairing ended without approval: the owner refused it, or the code expired${error.reason ? ` (the server said: ${error.reason})` : ''}. Create a new code in ${origin}/business and run connect with it.`);
82
+ }
83
+ throw error;
84
+ }
85
+ if (result?.status === 'paired') {
86
+ if (typeof result.device_credential !== 'string') throw Error('Business server returned an invalid device credential.');
87
+ const state = { version: 1, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false };
88
+ // No authenticated request (including activation) before both durable writes.
89
+ await store.set(handle, result.device_credential);
90
+ try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
91
+ await clearPending();
92
+ process.stdout.write('Approved. Device credential stored in OS credential storage.\n');
93
+ await applyOptIns(new Api(origin, result.device_credential), state);
94
+ return;
95
+ }
96
+ if (['denied', 'refused', 'expired'].includes(result?.status)) {
97
+ await clearPending();
98
+ throw Error(`Business pairing was ${result.status === 'expired' ? 'not approved before the code expired' : 'refused in the browser'}. Create a new code in ${origin}/business and run connect with it.`);
99
+ }
100
+ if (result?.status !== 'authorization_pending') throw Error('Business server returned an invalid pairing status.');
101
+ try { await pause(Math.max(1, Math.min(5, Number(result.interval) || 5)) * 1000, stop.signal); } catch { break; }
65
102
  }
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;
103
+ if (stop.signal.aborted) {
104
+ throw new Stopped(`Stopped waiting for approval. The pairing is saved: run ${resume} to resume it${pending.code_expires_at ? ` before ${clock(pending.code_expires_at)}` : ''}.`, stop.signal.reason === 'SIGTERM' ? 143 : 130);
70
105
  }
71
- await pause(Math.max(1, Math.min(5, Number(result.interval) || 5)) * 1000);
106
+ await clearPending();
107
+ throw Error(`Business pairing code expired before it was approved. Create a new code in ${origin}/business and run connect with it.`);
108
+ } finally {
109
+ process.off('SIGINT', onInterrupt); process.off('SIGTERM', onTerminate);
72
110
  }
73
- await clearPending();
74
- throw Error('Business browser pairing expired. Create a new code in the browser.');
75
111
  }
76
112
 
77
113
  export function localRoot(path) {
@@ -0,0 +1,20 @@
1
+ import { hostname, userInfo } from 'node:os';
2
+
3
+ /** A plain name for this computer, from its host name: the first label only,
4
+ * words instead of dashes, the login name removed, at most 64 characters, and
5
+ * never a path. Empty when nothing plain is left, so the server names the
6
+ * computer by its system and agent instead.
7
+ */
8
+ export function deviceName({ host = hostname(), user = loginName() } = {}) {
9
+ let name = String(host).split('.')[0].replace(/[\x00-\x1f\x7f/\\]/g, ' ').replace(/[-_]+/g, ' ');
10
+ // The login name, and the possessive Apple host names add to a person's name ("jamess").
11
+ if (user && user.length > 1) name = name.replace(new RegExp(`(?<![\\p{L}\\p{N}])${user.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}s?(?![\\p{L}\\p{N}])`, 'giu'), ' ');
12
+ return Array.from(name.replace(/\s+/g, ' ').trim()).slice(0, 64).join('').trim();
13
+ }
14
+ function loginName() { try { return userInfo().username; } catch { return ''; } }
15
+
16
+ /** The absolute folder connect runs in, as the platform accepts it: an
17
+ * absolute path without control characters, at most 1000 characters. */
18
+ export function workingFolder(folder = process.cwd()) {
19
+ return typeof folder === 'string' && folder.startsWith('/') && folder.length <= 1000 && !/[\x00-\x1f\x7f]/.test(folder) ? folder : '';
20
+ }
@@ -0,0 +1,26 @@
1
+ // Every message rer business prints names its cause: a server's reason, a
2
+ // local system cause, or this CLI's own explanation. Device and task bearers
3
+ // are redacted wherever a message came from.
4
+ const causes = {
5
+ EACCES: 'permission denied', EPERM: 'not permitted here (an agent sandbox can block this)', EROFS: 'the disk is read-only',
6
+ ENOSPC: 'the disk is full', EDQUOT: 'the disk quota is used up', ENOENT: 'it does not exist', ENOTDIR: 'part of the path is not a folder',
7
+ EEXIST: 'it already exists', EISDIR: 'it is a folder', ELOOP: 'it is a symbolic link loop', EMFILE: 'too many files are open', EBUSY: 'it is busy',
8
+ };
9
+ const actions = { open: 'open', mkdir: 'create', write: 'write', rename: 'replace', unlink: 'remove', rmdir: 'remove', rm: 'remove', chmod: 'protect', read: 'read', lstat: 'check', stat: 'check', scandir: 'list', access: 'check' };
10
+
11
+ export const localCause = error => typeof error?.code === 'string' ? causes[error.code] ? `${causes[error.code]} (${error.code})` : error.code : null;
12
+ export const redact = text => String(text).replace(/bz_[a-z]+_[A-Za-z0-9_-]+/g, '[credential]').replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ' ');
13
+
14
+ export function describe(error) {
15
+ if (typeof error?.syscall === 'string' && typeof error.code === 'string') {
16
+ return redact(`Business could not ${actions[error.syscall] ?? error.syscall} ${error.path ?? 'a local file'}: ${localCause(error)}.`);
17
+ }
18
+ const message = error instanceof Error ? error.message : String(error);
19
+ const unexpected = [TypeError, RangeError, SyntaxError, ReferenceError].some(type => error instanceof type);
20
+ return redact(unexpected || !message ? `Business command failed unexpectedly: ${message || 'no reason given'}` : message);
21
+ }
22
+
23
+ // An exit status other than 1 travels with the error (130 after Ctrl-C).
24
+ export class Stopped extends Error {
25
+ constructor(message, exitCode) { super(message); this.exitCode = exitCode; }
26
+ }
@@ -1,22 +1,40 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
2
3
 
3
4
  const service = 'com.runeditrun.business';
4
- const unavailable = () => new Error('OS credential storage is unavailable or locked. Unlock macOS Keychain or install and unlock Linux Secret Service (secret-tool); otherwise use the wizard or Managed. No credential was written to a file.');
5
+ const sandboxed = 'an agent sandbox blocks this. Run this one command outside the sandbox (in Codex, approve running it outside the sandbox when it asks), or in your own terminal';
6
+ // Causes come from fixed phrases matched in the tool's diagnostics; the
7
+ // diagnostics themselves are never printed.
8
+ function cause(binary, result) {
9
+ const text = result?.stderr ?? '';
10
+ if (result?.spawnFailed) return binary === 'secret-tool' ? 'secret-tool is not installed. Install it and unlock a Secret Service session' : `${binary} could not start`;
11
+ if (/Operation not permitted/.test(text)) return `macOS Keychain refused the write (Operation not permitted); ${sandboxed}`;
12
+ if (/Unable to obtain authorization/.test(text)) return `macOS Keychain refused authorization; ${sandboxed}`;
13
+ if (/User interaction is not allowed|interaction is not allowed/i.test(text)) return 'the keychain is locked and cannot ask for its password here. Unlock it, then try again';
14
+ if (/autolaunch D-Bus|Cannot spawn a message bus|org\.freedesktop\.secrets/.test(text)) return 'no unlocked Secret Service session is running. Unlock one, then try again';
15
+ if (result?.timedOut) return `${binary} did not answer within 30 seconds`;
16
+ return `${binary} exited with status ${result?.code ?? 'unknown'}. Unlock macOS Keychain, or install and unlock Linux Secret Service (secret-tool), then try again`;
17
+ }
18
+ const unavailable = (operation, binary, result) => {
19
+ const error = new Error(`OS credential storage could not ${operation} a credential: ${cause(binary, result)}. No credential was written to a file.`);
20
+ error.sandboxRefused = /Operation not permitted|Unable to obtain authorization/.test(result?.stderr ?? '');
21
+ return error;
22
+ };
5
23
 
6
24
  // All process output stays in memory. In particular, never attach a child error:
7
25
  // OS tools may put credential material in their diagnostics.
8
26
  function execute(command, args, input, env) {
9
- return new Promise((resolve, reject) => {
27
+ return new Promise(resolve => {
10
28
  const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
11
29
  const out = [], err = []; let size = 0, failed = false;
12
30
  const timer = setTimeout(() => { failed = true; child.kill('SIGKILL'); }, 30000);
13
31
  const collect = list => chunk => { size += chunk.length; if (size > 262144) { failed = true; child.kill('SIGKILL'); } else list.push(chunk); };
14
32
  child.stdout.on('data', collect(out)); child.stderr.on('data', collect(err));
15
33
  child.stdin.on('error', () => {});
16
- child.on('error', () => { clearTimeout(timer); reject(unavailable()); });
34
+ child.on('error', () => { clearTimeout(timer); resolve({ code: null, spawnFailed: true, stdout: '', stderr: '' }); });
17
35
  child.on('close', code => {
18
36
  clearTimeout(timer);
19
- if (failed || code === null) reject(unavailable());
37
+ if (failed || code === null) resolve({ code: null, timedOut: true, stdout: '', stderr: Buffer.concat(err).toString('utf8') });
20
38
  else resolve({ code, stdout: Buffer.concat(out).toString('utf8'), stderr: Buffer.concat(err).toString('utf8') });
21
39
  });
22
40
  child.stdin.end(input);
@@ -38,44 +56,57 @@ function checkedSecret(secret) {
38
56
  */
39
57
  export function createCredentialStore({ platform = process.platform, env = process.env, run } = {}) {
40
58
  const command = run ?? ((binary, args, input) => execute(binary, args, input, env));
41
- if (!['darwin', 'linux'].includes(platform)) throw unavailable();
42
- const call = async (...args) => { try { return await command(...args); } catch { throw unavailable(); } };
59
+ if (!['darwin', 'linux'].includes(platform)) throw new Error('OS credential storage is available only on macOS (Keychain) and Linux (Secret Service). No credential was written to a file.');
60
+ const binary = platform === 'darwin' ? 'security' : 'secret-tool';
61
+ const call = async (operation, ...args) => {
62
+ let result;
63
+ try { result = await command(...args); } catch { throw unavailable(operation, binary, { spawnFailed: true }); }
64
+ if (result.spawnFailed || result.timedOut) throw unavailable(operation, binary, result);
65
+ return result;
66
+ };
43
67
  const macArgs = handle => ['-s', service, '-a', handle];
44
68
  const linuxArgs = handle => ['application', service, 'handle', handle];
45
69
  async function get(handle) {
46
70
  checkedHandle(handle);
47
71
  const result = platform === 'darwin'
48
- ? await call('/usr/bin/security', ['find-generic-password', ...macArgs(handle), '-w'])
49
- : await call('secret-tool', ['lookup', ...linuxArgs(handle)]);
72
+ ? await call('read', '/usr/bin/security', ['find-generic-password', ...macArgs(handle), '-w'])
73
+ : await call('read', 'secret-tool', ['lookup', ...linuxArgs(handle)]);
50
74
  if (platform === 'darwin' && result.code === 44 || platform === 'linux' && result.code === 1 && !result.stderr.trim()) return null;
51
- if (result.code !== 0) throw unavailable();
75
+ if (result.code !== 0) throw unavailable('read', binary, result);
52
76
  return result.stdout.replace(/\r?\n$/, '');
53
77
  }
54
78
  return {
55
79
  get,
80
+ /** Write and remove a throwaway item, so a store that reads but refuses
81
+ * writes (an agent sandbox) is found before anything is redeemed. */
82
+ async check() {
83
+ const handle = `probe:${randomUUID()}`;
84
+ await this.set(handle, randomUUID());
85
+ await this.delete(handle);
86
+ },
56
87
  async set(handle, secret) {
57
88
  checkedHandle(handle); checkedSecret(secret);
58
89
  if (platform === 'darwin') {
59
90
  // Interactive security receives the hex password on stdin. Hex also avoids
60
91
  // its command tokenizer interpreting quotes/backslashes in a vendor key.
61
92
  const hex = Buffer.from(secret, 'utf8').toString('hex');
62
- const result = await call('/usr/bin/security', ['-q', '-p', ''], `add-generic-password -U -s ${service} -a ${handle} -X ${hex}\n`);
63
- if (result.code !== 0 || result.stderr.trim()) throw unavailable();
93
+ const result = await call('save', '/usr/bin/security', ['-q', '-p', ''], `add-generic-password -U -s ${service} -a ${handle} -X ${hex}\n`);
94
+ if (result.code !== 0 || result.stderr.trim()) throw unavailable('save', binary, result);
64
95
  } else {
65
- const result = await call('secret-tool', ['store', '--label=Run Edit Run Business', ...linuxArgs(handle)], secret);
66
- if (result.code !== 0) throw unavailable();
96
+ const result = await call('save', 'secret-tool', ['store', '--label=Run Edit Run Business', ...linuxArgs(handle)], secret);
97
+ if (result.code !== 0) throw unavailable('save', binary, result);
67
98
  }
68
99
  // security's interactive exit status alone does not establish command success.
69
- if (await get(handle) !== secret) throw unavailable();
100
+ if (await get(handle) !== secret) throw unavailable('save', binary, { code: 0, stderr: '' });
70
101
  return handle;
71
102
  },
72
103
  async delete(handle) {
73
104
  checkedHandle(handle);
74
105
  if (await get(handle) === null) return;
75
106
  const result = platform === 'darwin'
76
- ? await call('/usr/bin/security', ['delete-generic-password', ...macArgs(handle)])
77
- : await call('secret-tool', ['clear', ...linuxArgs(handle)]);
78
- if (result.code !== 0 && !(platform === 'darwin' && result.code === 44)) throw unavailable();
107
+ ? await call('remove', '/usr/bin/security', ['delete-generic-password', ...macArgs(handle)])
108
+ : await call('remove', 'secret-tool', ['clear', ...linuxArgs(handle)]);
109
+ if (result.code !== 0 && !(platform === 'darwin' && result.code === 44)) throw unavailable('remove', binary, result);
79
110
  },
80
111
  };
81
112
  }
@@ -1,6 +1,6 @@
1
- import { readFile, writeFile, unlink, rm, rmdir, lstat } from 'node:fs/promises';
2
- import { dirname, join } from 'node:path';
3
- import { loadState, loadPending, saveState, stateDirectory, credentialHandle } from './state.mjs';
1
+ import { readFile, writeFile, unlink, lstat } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { loadState, loadPending, saveState, stateDirectory, removeStateDirectory, 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';
@@ -13,7 +13,7 @@ export async function paired() {
13
13
  const state = await loadState();
14
14
  if (!state?.origin || !state.businessId || !state.executorId) throw Error(`This computer is not paired. Run ${rerCommand()} business connect --code CODE.`);
15
15
  const credential = await createCredentialStore().get(credentialHandle(state.origin));
16
- if (!credential) throw Error('Business device credential is missing. Reconnect in your browser.');
16
+ if (!credential) throw Error(`This computer's Business credential is missing from OS credential storage. Run ${rerCommand()} business disconnect, then connect again with a new code from ${state.origin}/business.`);
17
17
  return { state, credential };
18
18
  }
19
19
 
@@ -78,9 +78,7 @@ export async function disconnect() {
78
78
  for (const handle of state.vendorHandles ?? []) await store.delete(handle);
79
79
  if (state.origin) await store.delete(credentialHandle(state.origin));
80
80
  }
81
- await rm(directory, { recursive: true, force: true });
82
- // Remove only an empty parent; other rer commands may own it.
83
- await rmdir(dirname(directory)).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
81
+ await removeStateDirectory();
84
82
  process.stdout.write(revocation === 'revoked'
85
83
  ? 'Business disconnected. Device revoked; local service, credentials and added permissions removed.\n'
86
84
  : `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`);
@@ -3,22 +3,31 @@ import { installPermissions } from './permissions.mjs';
3
3
  import { saveState } from './state.mjs';
4
4
  import { rerCommand } from './invocation.mjs';
5
5
 
6
- export const optInNames = ['installPermissions', 'awakeConsent', 'installService'];
6
+ // The server's field names stay internal; people see the browser's sentences.
7
+ export const optIns = {
8
+ installPermissions: 'Add rules so Claude Code never reads your secret files',
9
+ awakeConsent: 'Keep this computer awake while it works',
10
+ installService: 'Install the background service',
11
+ };
12
+ const optInNames = Object.keys(optIns);
7
13
 
8
14
  export async function applyOptIns(api, state) {
9
15
  let self;
10
16
  // A server without this route answers a device credential with 403 (or 404):
11
- // nothing is decided yet.
17
+ // nothing is decided yet. This first authenticated request activates the computer.
12
18
  try { self = await api.get('/api/business/executors/self'); }
13
19
  catch (error) { if (![403, 404].includes(error.status)) throw error; }
14
20
  const decisions = Object.fromEntries(optInNames.map(name => [name, self?.optIns?.[name] === true ? true : self?.optIns?.[name] === false ? false : null]));
15
21
  if (decisions.installPermissions === true) await installPermissions({ consent: true });
16
22
  state.awakeConsent = decisions.awakeConsent === true;
17
23
  await saveState(state);
24
+ process.stdout.write(`This computer is connected to Business at ${state.origin}.\n`);
18
25
  if (decisions.installService === true) {
19
26
  await installService({ consent: true });
20
- process.stdout.write('Business background service installed.\n');
27
+ process.stdout.write('The background service is installed and works tasks after this chat ends.\n');
21
28
  } else process.stdout.write(`Run ${rerCommand()} business run to work tasks.\n`);
22
29
  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`);
30
+ if (undecided.length) {
31
+ process.stdout.write(`The owner has not chosen yet:\n${undecided.map(name => ` - ${optIns[name]}\n`).join('')}Ask them to choose on this computer's row in ${state.origin}/business/${encodeURIComponent(state.businessId)}/settings, then run ${rerCommand()} business connect again to apply the choices.\n`);
32
+ }
24
33
  }
@@ -2,6 +2,7 @@ import { mkdir, readFile, writeFile, unlink, rename, lstat, open, rmdir } from '
2
2
  import { homedir } from 'node:os';
3
3
  import { join, dirname, isAbsolute } from 'node:path';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
+ import { stateDirectory } from './state.mjs';
5
6
 
6
7
  export const BUSINESS_DENY_RULES = Object.freeze([
7
8
  'Read(**/secrets/**)', 'Read(**/.ssh/**)', 'Read(**/.aws/**)', 'Read(**/.gnupg/**)',
@@ -16,7 +17,8 @@ export const BUSINESS_DENY_RULES = Object.freeze([
16
17
 
17
18
  const hash = text => text === null ? null : createHash('sha256').update(text).digest('hex');
18
19
  const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
19
- function paths({ home = homedir(), stateDir = join(home, '.rer', 'business') } = {}) {
20
+ function paths(input = {}) {
21
+ const home = input.home ?? homedir(), stateDir = input.stateDir ?? (input.home === undefined ? stateDirectory() : join(home, '.rer', 'business'));
20
22
  if (!isAbsolute(home) || !isAbsolute(stateDir)) throw new Error('Business permission paths must be absolute.');
21
23
  return { settings: join(home, '.claude', 'settings.json'), receipt: join(stateDir, 'permissions.json'), stateDir };
22
24
  }
@@ -1,6 +1,6 @@
1
1
  import { basename } from 'node:path';
2
2
 
3
- const outputs = new Set(['node_modules', 'vendor', '.git', 'dist', 'build', 'target', 'coverage', '.next', '.nuxt', '.output', '.cache', '.venv', 'venv', '__pycache__', '.terraform', '.pulumi', '.wrangler', '.rer', '.seed', 'playwright-report', 'test-results']);
3
+ const outputs = new Set(['node_modules', 'vendor', '.git', 'dist', 'build', 'target', 'coverage', '.next', '.nuxt', '.output', '.cache', '.venv', 'venv', '__pycache__', '.terraform', '.pulumi', '.wrangler', '.rer', '.rer-business', '.seed', 'playwright-report', 'test-results']);
4
4
  const tools = new Set(['.claude', '.codex', '.cursor', '.worktrees', '.idea', '.vscode', '.vscode-insiders', '.windsurf', '.continue', '.zed', '.aider', '.gemini', '.opencode']);
5
5
 
6
6
  export const toolDirectory = path => path.split('/').some(part => tools.has(part.toLowerCase()));
@@ -1,4 +1,5 @@
1
1
  import { scan } from './scan.mjs';
2
+ import { localCause } from './errors.mjs';
2
3
 
3
4
  const usage = 'Usage: rer business scan [DIR...] [--json]\nNames-only local discovery; returns rer-business-signals/1 JSON. No network calls.\n';
4
5
 
@@ -19,9 +20,11 @@ export async function scanCommand(argv) {
19
20
  const result = await scan(directories.length ? directories : [process.cwd()]);
20
21
  process.stdout.write(JSON.stringify(result) + '\n');
21
22
  return 0;
22
- } catch {
23
- // Node/format errors can contain input paths, keys or source excerpts.
24
- process.stderr.write('Business scan could not read a local input. No scan document was emitted.\n');
23
+ } catch (error) {
24
+ // Node/format errors can contain input paths, keys or source excerpts, so
25
+ // only the system cause is named.
26
+ const cause = localCause(error);
27
+ process.stderr.write(`Business scan could not read a local input${cause ? ` (${cause})` : ', or one was not in a format it reads'}. No scan document was emitted.\n`);
25
28
  return 1;
26
29
  }
27
30
  }
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
4
4
  import { dirname, join, isAbsolute } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
+ import { stateDirectory } from './state.mjs';
7
8
 
8
9
  const label = 'com.runeditrun.business', unit = 'rer-business.service';
9
10
  const digest = text => createHash('sha256').update(text).digest('hex');
@@ -16,7 +17,7 @@ function execute(binary, args) {
16
17
  function options(input = {}) {
17
18
  const home = input.home ?? homedir(), platform = input.platform ?? process.platform;
18
19
  if (!isAbsolute(home) || !['darwin', 'linux'].includes(platform)) throw new Error('Business background services require macOS or Linux and an absolute home directory.');
19
- const stateDir = input.stateDir ?? join(home, '.rer', 'business');
20
+ const stateDir = input.stateDir ?? (input.home === undefined ? stateDirectory() : join(home, '.rer', 'business'));
20
21
  if (!isAbsolute(stateDir)) throw new Error('Business service state directory must be absolute.');
21
22
  return { ...input, home, platform, stateDir, run: input.run ?? execute };
22
23
  }
@@ -64,9 +65,11 @@ export async function installService(input = {}) {
64
65
  if (!isAbsolute(node) || !isAbsolute(entrypoint) || !(await stat(node)).isFile() || !(await stat(entrypoint)).isFile()) throw new Error('Business requires an absolute Node executable and rer entrypoint.');
65
66
  const log = join(o.stateDir, 'service.log'), errorLog = join(o.stateDir, 'service-error.log');
66
67
  const environmentPath = `${dirname(node)}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`;
68
+ // A state folder chosen with RER_BUSINESS_STATE_DIR goes with the service.
69
+ const environment = [['HOME', o.home], ['PATH', environmentPath], ...(o.stateDir !== join(o.home, '.rer', 'business') ? [['RER_BUSINESS_STATE_DIR', o.stateDir]] : [])];
67
70
  const text = o.platform === 'darwin'
68
- ? `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${label}</string>\n<key>ProgramArguments</key><array>${[node, entrypoint, 'business', 'run'].map(arg => `<string>${xml(arg)}</string>`).join('')}</array>\n<key>EnvironmentVariables</key><dict><key>HOME</key><string>${xml(o.home)}</string><key>PATH</key><string>${xml(environmentPath)}</string></dict>\n<key>WorkingDirectory</key><string>${xml(o.home)}</string>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>30</integer><key>Umask</key><integer>63</integer>\n<key>StandardOutPath</key><string>${xml(log)}</string><key>StandardErrorPath</key><string>${xml(errorLog)}</string>\n</dict></plist>\n`
69
- : `[Unit]\nDescription=Run Edit Run Business executor\nAfter=network-online.target\n\n[Service]\nType=simple\nExecStart=${[node, entrypoint, 'business', 'run'].map(value => unitValue(value).replaceAll('$', () => '$$')).join(' ')}\nWorkingDirectory=${unitValue(o.home)}\nEnvironment=${unitValue(`HOME=${o.home}`)} ${unitValue(`PATH=${environmentPath}`)}\nRestart=on-failure\nRestartSec=30\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
71
+ ? `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${label}</string>\n<key>ProgramArguments</key><array>${[node, entrypoint, 'business', 'run'].map(arg => `<string>${xml(arg)}</string>`).join('')}</array>\n<key>EnvironmentVariables</key><dict>${environment.map(([key, value]) => `<key>${key}</key><string>${xml(value)}</string>`).join('')}</dict>\n<key>WorkingDirectory</key><string>${xml(o.home)}</string>\n<key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict>\n<key>ThrottleInterval</key><integer>30</integer><key>Umask</key><integer>63</integer>\n<key>StandardOutPath</key><string>${xml(log)}</string><key>StandardErrorPath</key><string>${xml(errorLog)}</string>\n</dict></plist>\n`
72
+ : `[Unit]\nDescription=Run Edit Run Business executor\nAfter=network-online.target\n\n[Service]\nType=simple\nExecStart=${[node, entrypoint, 'business', 'run'].map(value => unitValue(value).replaceAll('$', () => '$$')).join(' ')}\nWorkingDirectory=${unitValue(o.home)}\nEnvironment=${environment.map(([key, value]) => unitValue(`${key}=${value}`)).join(' ')}\nRestart=on-failure\nRestartSec=30\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
70
73
  const existing = await readOptional(path), oldReceipt = await readOptional(receiptPath);
71
74
  if (existing !== null && (!oldReceipt || JSON.parse(oldReceipt).hash !== digest(existing))) throw new Error('A background service already exists at the Business service path; it was not overwritten.');
72
75
  if (oldReceipt && existing !== null && existing !== text) throw new Error('Remove the existing Business service before changing its installation paths.');
@@ -1,20 +1,33 @@
1
- import { mkdir, readFile, writeFile, rename, chmod, open, unlink } from 'node:fs/promises';
2
- import { join } from 'node:path';
1
+ import { mkdir, readFile, readdir, writeFile, rename, chmod, open, unlink, rm, rmdir, lstat } from 'node:fs/promises';
2
+ import { dirname, join, resolve } from 'node:path';
3
3
  import { homedir } from 'node:os';
4
4
  import { createHash, randomUUID } from 'node:crypto';
5
+ import { localCause } from './errors.mjs';
5
6
 
6
- export const stateDirectory = () => join(homedir(), '.rer', 'business');
7
+ // RER_BUSINESS_STATE_DIR names the folder itself, for agent sandboxes that may write only
8
+ // inside their working folder. Without it the state lives in ~/.rer/business.
9
+ // RER_STATE_DIR belongs to rer demo and is never read here.
10
+ export const chosenStateDirectory = () => Boolean(process.env.RER_BUSINESS_STATE_DIR);
11
+ export function stateDirectory() {
12
+ const chosen = process.env.RER_BUSINESS_STATE_DIR;
13
+ if (!chosen) return join(homedir(), '.rer', 'business');
14
+ if (chosen.includes('\0')) throw Error('RER_BUSINESS_STATE_DIR must name a folder.');
15
+ return resolve(chosen);
16
+ }
7
17
  export const credentialHandle = origin => `device:${createHash('sha256').update(origin).digest('hex')}`;
8
18
 
9
- export async function loadState() {
10
- try { return JSON.parse(await readFile(join(stateDirectory(), 'state.json'), 'utf8')); }
11
- catch (error) { if (error.code === 'ENOENT') return null; throw error; }
19
+ async function loadJson(name) {
20
+ const path = join(stateDirectory(), name);
21
+ let text;
22
+ try { text = await readFile(path, 'utf8'); }
23
+ // Under a path that is not a folder (ENOTDIR) nothing can have been saved yet.
24
+ catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null; throw error; }
25
+ try { return JSON.parse(text); }
26
+ catch { throw Error(`Business could not read ${path}: it is not valid JSON. Remove it, or run rer business disconnect, then connect again.`); }
12
27
  }
13
28
 
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
- }
29
+ export const loadState = () => loadJson('state.json');
30
+ export const loadPending = () => loadJson('pairing.json');
18
31
  export const savePending = pending => saveJson('pairing.json', pending);
19
32
  export async function clearPending() {
20
33
  await unlink(join(stateDirectory(), 'pairing.json')).catch(error => { if (error.code !== 'ENOENT') throw error; });
@@ -39,6 +52,50 @@ async function saveJson(name, value) {
39
52
  } finally { await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; }); }
40
53
  }
41
54
 
55
+ /** Before a one-use code is spent or an approval collected, prove the state
56
+ * folder takes the same private create, write and replace the pairing needs.
57
+ * Folders made only for the check are removed again, so a refused connect
58
+ * leaves nothing behind.
59
+ */
60
+ export async function checkStateWritable() {
61
+ const directory = stateDirectory(), probe = join(directory, `${randomUUID()}.tmp`), created = [];
62
+ for (let path = directory; path !== dirname(path); path = dirname(path)) {
63
+ try { await lstat(path); break; } catch (error) { if (error.code !== 'ENOENT') break; created.push(path); }
64
+ }
65
+ try {
66
+ await mkdir(directory, { recursive: true, mode: 0o700 });
67
+ await chmod(directory, 0o700);
68
+ await writeFile(probe, '{}\n', { mode: 0o600, flag: 'wx' });
69
+ await rename(probe, probe + '.check');
70
+ await unlink(probe + '.check');
71
+ } catch (error) {
72
+ await unlink(probe).catch(() => {});
73
+ const fix = chosenStateDirectory()
74
+ ? 'Allow writes to that folder in this session, or set RER_BUSINESS_STATE_DIR to a folder this session can write'
75
+ : 'Allow writes to that folder, or set RER_BUSINESS_STATE_DIR to a folder this session can write (in Codex, one inside the working folder, such as RER_BUSINESS_STATE_DIR="$PWD/.rer-business")';
76
+ throw Error(`Business cannot save its state in ${directory}: ${localCause(error) ?? error.message}. Nothing was sent, so the pairing code still works. ${fix}, then run connect again.`);
77
+ } finally {
78
+ for (const path of created) await rmdir(path).catch(() => {});
79
+ }
80
+ }
81
+
82
+ // Files this CLI writes in its state folder. A folder named by RER_BUSINESS_STATE_DIR
83
+ // may hold other things, so only these are removed from it.
84
+ const owned = /^(?:(?:state|pairing|progress|permissions|service)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
85
+ export async function removeStateDirectory() {
86
+ const directory = stateDirectory();
87
+ if (!chosenStateDirectory()) {
88
+ await rm(directory, { recursive: true, force: true });
89
+ // Remove only an empty parent; other rer commands may own it.
90
+ await rmdir(dirname(directory)).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
91
+ return;
92
+ }
93
+ let entries;
94
+ try { entries = await readdir(directory); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
95
+ for (const name of entries) if (owned.test(name)) await rm(join(directory, name), { force: true });
96
+ await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
97
+ }
98
+
42
99
  export async function lockSupervisor() {
43
100
  const directory = stateDirectory();
44
101
  await mkdir(directory, { recursive: true, mode: 0o700 });
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.63
4
+
5
+ - **Business connect waits for approval and keeps durable state (#277).** Pairing resumes after interruption, sends a readable device name and working folder, and accepts an explicit `RER_BUSINESS_STATE_DIR` when the usual state folder is unwritable. A refused macOS Keychain write stops before redeeming the code and explains how to approve the command outside the sandbox. Browser choices remain authoritative.
6
+ - **Setup fields and groups can declare their audience (#297).** Public fields accept `audience: "owner" | "developer"`, inherit group audience, and default to owner. Invalid audiences and an owner field inside a developer group are refused. Local installer and terminal setup keep their existing active-field visibility; managed consumers can use the metadata.
7
+
3
8
  ## 0.2.62
4
9
 
5
10
  - **Themed demo gates keep waiting visibly disabled (#292).** Waiting, working and other non-actionable buttons use muted outlines from the seed’s theme tokens. Turnstile explicitly follows the card’s painted light/dark scheme, including declared dark media tokens.
package/global/README.md CHANGED
@@ -371,36 +371,57 @@ 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 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
386
- unlocked desktop Secret Service session.
387
-
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
397
- absolute Node and CLI paths. No model process is started.
374
+ redeems a browser-created code, prints a six-digit confirmation number for
375
+ approval in the browser that created it, and waits in the foreground until the
376
+ owner approves or refuses there or the code expires (ten minutes). It exits 0
377
+ only once the computer is active: the credential is stored and the server has
378
+ seen the computer. A refusal or expiry exits 1 with the server's reason.
379
+ Interrupting it (Ctrl-C, or an agent's tool timeout) keeps the redeemed pairing:
380
+ run `rer business connect` again to resume the same pairing and number; a new
381
+ server pairing is never started until the old one is refused, expired or
382
+ disconnected. The waiting line names the command that works from the agent's
383
+ own shell: `rer` when it is on PATH, the launcher install.sh wrote, or
384
+ `npx -y @runeditrun/rer` after an npx run. Pending tokens are kept until the
385
+ code's expiry plus the ten minutes the server allows after an approval, so an
386
+ approval near the code's end can still be collected.
387
+
388
+ State lives in `$RER_BUSINESS_STATE_DIR` when it is set, and in `~/.rer/business`
389
+ otherwise. `RER_STATE_DIR` is `rer demo`'s variable and Business never reads it.
390
+ Connect also sends the computer's plain name (its host name's first word group,
391
+ without the login name, at most 64 characters) and the folder it runs in, so the
392
+ browser can show which computer this is and prefill the scan folder.
393
+ Before redeeming the code (or collecting an approval), connect proves
394
+ it can write that folder and that OS credential storage accepts a write; if
395
+ either fails it stops, names the folder or the cause, and the code still works.
396
+ Device credentials stay in macOS Keychain or Linux Secret Service; there is no
397
+ plaintext credential store. Linux needs `secret-tool` and an unlocked desktop
398
+ Secret Service session. Every failure names its cause: the server's reason, the
399
+ local system cause, or what to change.
400
+
401
+ The owner chooses three things on the computer's row in the browser: "Add rules
402
+ so Claude Code never reads your secret files" (Claude Code user Read deny
403
+ rules), "Keep this computer awake while it works" (export-scoped macOS wake
404
+ prevention) and "Install the background service" (a launchd or systemd user
405
+ service). Connect reads them as `optIns` from device-authenticated
406
+ `GET /api/business/executors/self`, with keys `installPermissions`,
407
+ `awakeConsent` and `installService`; the CLI prints only the sentences. Only
408
+ `true` enables an option. Undecided (`null`) options are listed with a browser
409
+ link; an older server without this route (it answers 403 or 404) leaves all
410
+ options undecided. Run connect again after the owner decides. The first
411
+ device-authenticated request happens after both the credential and local
412
+ pairing state are stored, so a storage failure cannot activate the computer.
413
+ A service installed with `RER_BUSINESS_STATE_DIR` set keeps that folder. Background
414
+ services use absolute Node and CLI paths. No model process is started.
398
415
 
399
416
  An agent can run `npx -y @runeditrun/rer business connect --code ABCD-1234 --origin URL`
400
417
  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
418
+ allow network access, set `RER_BUSINESS_STATE_DIR="$PWD/.rer-business"` so state stays
419
+ inside the working folder, and put npm's cache there too with
420
+ `npm_config_cache="$PWD/.rer/npm"`. macOS refuses Keychain writes from inside
421
+ that sandbox, so connect stops before redeeming and asks for this one command to
422
+ run outside the sandbox (in Codex, approve running that command outside the
423
+ sandbox when it asks); later commands
424
+ only read the credential and run inside the sandbox. Do not install a
404
425
  background service or change user settings unless the owner enables those
405
426
  options and the sandbox permits their locations.
406
427
 
@@ -104,6 +104,10 @@
104
104
  "help": {
105
105
  "type": "string"
106
106
  },
107
+ "audience": {
108
+ "enum": ["owner", "developer"],
109
+ "description": "Audience inherited by this group's public fields: owner when absent, or developer. An explicit owner field inside a developer group is invalid. This metadata does not change local installer or rer setup visibility."
110
+ },
107
111
  "presentations": {
108
112
  "type": "array",
109
113
  "items": {
@@ -141,6 +145,10 @@
141
145
  "secret"
142
146
  ]
143
147
  },
148
+ "audience": {
149
+ "enum": ["owner", "developer"],
150
+ "description": "Public fields only: owner or developer. When absent, inherit the group's audience, or owner without a group audience. An explicit owner value inside a developer group is invalid. This metadata does not change local installer or rer setup visibility; secret visibility uses ownerVisible and input."
151
+ },
144
152
  "required": {
145
153
  "type": "boolean"
146
154
  },
@@ -6,6 +6,11 @@ export const SETUP_SCHEMA_ID = 'urn:rer:setup:1';
6
6
 
7
7
  const PUBLIC_KINDS = new Set(['text', 'email', 'url', 'select', 'colour', 'timezone']);
8
8
 
9
+ /** Effective audience of a validated public field, including its group default. */
10
+ export function setupFieldAudience(field, groups) {
11
+ return field.audience ?? groups.find(group => group.id === field.group)?.audience ?? 'owner';
12
+ }
13
+
9
14
  /** Match a validated condition against raw public input; whitespace is a value. */
10
15
  export function setupConditionMatches(condition, values) {
11
16
  const value = values[condition.field];
@@ -131,6 +136,7 @@ export function setupManifestSemanticErrors(data) {
131
136
  if (field.group !== undefined && !groups.has(field.group)) fail(`${path}.group`, 'group must reference a declared group');
132
137
 
133
138
  if (isSecret) {
139
+ if (Object.hasOwn(field, 'audience')) fail(`${path}.audience`, `${field.name}: secret fields cannot declare audience`);
134
140
  for (const name of ['default', 'prefill', 'options', 'runtimeEditable']) {
135
141
  if (Object.hasOwn(field, name)) fail(`${path}.${name}`, 'secret fields cannot declare public input metadata');
136
142
  }
@@ -144,6 +150,9 @@ export function setupManifestSemanticErrors(data) {
144
150
  fail(`${path}.ownerVisible`, 'only generated or explicitly entered secret values may be shown to the owner');
145
151
  }
146
152
  } else {
153
+ if (field.audience === 'owner' && groups.get(field.group)?.audience === 'developer') {
154
+ fail(`${path}.audience`, `${field.name} cannot declare owner audience inside developer group ${field.group}`);
155
+ }
147
156
  for (const name of ['generate', 'ownerVisible', 'input']) {
148
157
  if (Object.hasOwn(field, name)) fail(`${path}.${name}`, 'public fields cannot declare secret metadata');
149
158
  }
@@ -320,6 +329,11 @@ export function validateSetupManifest(schema, data) {
320
329
  if (schema?.$id !== SETUP_SCHEMA_ID) throw new Error('Expected setup schema version 1');
321
330
  checkSchema(schema);
322
331
  const errors = validate(schema, data);
323
- if (errors.length) return errors;
332
+ if (errors.length) return errors.map(error => {
333
+ const match = error.match(/^(\$\.(fields|groups)\[(\d+)\]\.audience):/);
334
+ if (!match) return error;
335
+ const item = data[match[2]][Number(match[3])];
336
+ return `${match[1]}: ${item.name ?? item.id} audience must be "owner" or "developer"`;
337
+ });
324
338
  return setupManifestSemanticErrors(data);
325
339
  }
@@ -1,4 +1,4 @@
1
- import {parseSetupManifestBytes, validateSetupManifest, setupConditionMatches, validateSetupValue} from './schema/setup-validation.mjs';
1
+ import {parseSetupManifestBytes, validateSetupManifest, setupConditionMatches, validateSetupValue, setupFieldAudience} from './schema/setup-validation.mjs';
2
2
  import {createModel} from './ui/model-core.mjs';
3
3
  import {installerInputs} from './installer-inputs.mjs';
4
4
 
@@ -41,6 +41,7 @@ export function createInstallerModel(manifest,presentation={},options={}) {
41
41
  for(const field of manifest.fields){
42
42
  fields[field.name]={
43
43
  ...field,type:field.kind==='secret'?'password':field.kind==='colour'?'color':field.kind==='email'?'email':field.kind==='url'?'url':'text',
44
+ ...(field.kind==='secret'?{}:{audience:setupFieldAudience(field,manifest.groups)}),
44
45
  artwork:field.name===nameKey||['url','colour'].includes(field.kind),
45
46
  autocomplete:field.kind==='secret'&&field.input==='entered'?'new-password':'off',
46
47
  optional:!field.required,options:field.options?.map(option=>[option.value,option.label]),
@@ -55,7 +56,7 @@ export function createInstallerModel(manifest,presentation={},options={}) {
55
56
  const groupIds=new Set(manifest.groups.map(group=>group.id));
56
57
  const generatedId=preferred=>{let id=preferred,index=1;while(groupIds.has(id))id=preferred+'-'+index++;groupIds.add(id);return id;};
57
58
  const groups=[...(manifest.fields.some(field=>!field.group)?[{id:generatedId('ungrouped'),title:manifest.title,keys:manifest.fields.filter(field=>!field.group).map(field=>field.name)}]:[]),
58
- ...manifest.groups.map(group=>({...group,title:group.label,keys:manifest.fields.filter(field=>field.group===group.id).map(field=>field.name)})),...own.groups.map(group=>({...group,id:generatedId(group.id)}))];
59
+ ...manifest.groups.map(group=>({...group,audience:group.audience??'owner',title:group.label,keys:manifest.fields.filter(field=>field.group===group.id).map(field=>field.name)})),...own.groups.map(group=>({...group,id:generatedId(group.id)}))];
59
60
  const safeKeys=Object.keys(fields).filter(key=>fields[key].type!=='password');
60
61
  const defaults=Object.fromEntries(manifest.fields.filter(field=>field.kind!=='secret'&&field.default!==undefined).map(field=>[field.name,field.default]));
61
62
  const internal={...presentation,product:presentation.product??{name:manifest.title},fields,safeKeys,secretScopes,setupGroups:groups,
@@ -69,7 +70,7 @@ export function createInstallerModel(manifest,presentation={},options={}) {
69
70
  model.fieldDefinition=(key,draft)=>fields[key]?.definition?.(draft)??fields[key];
70
71
  const originalSummaryKeys=model.summaryKeys;
71
72
  model.summaryKeys=(draft,state)=>originalSummaryKeys(draft,state).filter(key=>model.fieldVisible(key,draft));
72
- model.groupDefinition=(group,draft)=>{const variant=group.presentations?.find(item=>setupConditionMatches(item.when,draft));return {...group,...variant,title:variant?.label??group.title};};
73
+ model.groupDefinition=(group,draft)=>{const variant=group.presentations?.find(item=>setupConditionMatches(item.when,draft));return {...group,audience:group.audience??'owner',...variant,title:variant?.label??group.title};};
73
74
  model.groupKeys=(group,draft)=>group.keys.filter(key=>model.fieldVisible(key,draft)).map((key,index)=>({key,index,order:model.fieldDefinition(key,draft).order??index})).sort((a,b)=>a.order-b.order||a.index-b.index).map(item=>item.key);
74
75
  model.validateInput=(input,known={})=>{
75
76
  if(!input||typeof input!=='object'||Array.isArray(input))throw Error('Provide setup inputs from rer-setup.json.');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.62",
3
+ "version": "0.2.63",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",