@runeditrun/rer 0.2.120 → 0.2.122

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/cli/README.md +173 -5
  2. package/cli/archive.mjs +1 -1
  3. package/cli/authoring.mjs +1 -1
  4. package/cli/browser-runtime.mjs +33 -18
  5. package/cli/business/agent-help.mjs +11 -11
  6. package/cli/business/agent-verbs.mjs +9 -8
  7. package/cli/business/api.mjs +11 -7
  8. package/cli/business/carry.mjs +4 -3
  9. package/cli/business/choices.mjs +1 -1
  10. package/cli/business/command.mjs +33 -11
  11. package/cli/business/connect.mjs +4 -4
  12. package/cli/business/credential-file.mjs +102 -0
  13. package/cli/business/errors.mjs +5 -2
  14. package/cli/business/invocation.mjs +7 -4
  15. package/cli/business/keychain.mjs +6 -2
  16. package/cli/business/local-commands.mjs +9 -3
  17. package/cli/business/mcp-bridge.mjs +2 -1
  18. package/cli/business/questions.mjs +1 -1
  19. package/cli/business/run-child.mjs +5 -5
  20. package/cli/business/run-grant.mjs +27 -8
  21. package/cli/business/run-mask.mjs +8 -1
  22. package/cli/business/scan-command.mjs +1 -1
  23. package/cli/business/service.mjs +4 -2
  24. package/cli/business/state.mjs +2 -2
  25. package/cli/checkout-folders.mjs +1 -1
  26. package/cli/checkout-preparation.mjs +4 -4
  27. package/cli/command-guidance.mjs +9 -0
  28. package/cli/companion/command.mjs +4 -3
  29. package/cli/companion/providers/sandbox.mjs +1 -1
  30. package/cli/companion/setup.mjs +4 -4
  31. package/cli/contract.mjs +8 -8
  32. package/cli/demo.mjs +1 -1
  33. package/cli/deploy-command.mjs +10 -5
  34. package/cli/deploy-hook.mjs +3 -2
  35. package/cli/deploy-inputs.mjs +20 -3
  36. package/cli/deploy-owner-input.mjs +2 -2
  37. package/cli/deploy-settings.mjs +14 -0
  38. package/cli/deploy-source.mjs +1 -1
  39. package/cli/deploy-variables.mjs +7 -1
  40. package/cli/deploy.mjs +6 -4
  41. package/cli/deployment-record.mjs +1 -1
  42. package/cli/dev-identity.mjs +4 -4
  43. package/cli/door-clauses.mjs +2 -2
  44. package/cli/door-mode.mjs +7 -7
  45. package/cli/door.mjs +7 -7
  46. package/cli/errors.mjs +15 -1
  47. package/cli/export-summary.mjs +1 -1
  48. package/cli/export.mjs +1 -1
  49. package/cli/hosted-export.mjs +1 -1
  50. package/cli/hosted-output.mjs +2 -2
  51. package/cli/human-error.mjs +8 -2
  52. package/cli/hydration/browser.mjs +1 -1
  53. package/cli/hydration/check.mjs +1 -1
  54. package/cli/import-summary.mjs +2 -2
  55. package/cli/inspect.mjs +9 -4
  56. package/cli/lifecycle.mjs +10 -10
  57. package/cli/listen.mjs +1 -1
  58. package/cli/listing.mjs +1 -1
  59. package/cli/local-env.mjs +1 -1
  60. package/cli/local.mjs +4 -4
  61. package/cli/managed-server.mjs +36 -13
  62. package/cli/output.mjs +2 -1
  63. package/cli/owner-entry-ready.mjs +92 -0
  64. package/cli/parse.mjs +19 -9
  65. package/cli/port.mjs +3 -3
  66. package/cli/portability-runtime.mjs +16 -0
  67. package/cli/portability.mjs +4 -4
  68. package/cli/production-auth.mjs +4 -2
  69. package/cli/production-mail.mjs +1 -1
  70. package/cli/project.mjs +2 -0
  71. package/cli/rehearse/options.mjs +3 -3
  72. package/cli/release-candidate.mjs +2 -2
  73. package/cli/release.mjs +5 -5
  74. package/cli/server-registry.mjs +3 -3
  75. package/cli/server-resources.mjs +1 -1
  76. package/cli/setup-input.mjs +6 -6
  77. package/cli/signin.mjs +11 -10
  78. package/cli/site-render.mjs +1 -1
  79. package/cli/size/schema.mjs +1 -1
  80. package/cli/size/verify-step.mjs +1 -1
  81. package/cli/transfers.mjs +4 -4
  82. package/edition-authoring/api-source.mjs +121 -0
  83. package/edition-authoring/archive-source.mjs +1 -86
  84. package/edition-authoring/base-copies.mjs +5 -3
  85. package/global/CHANGELOG.md +47 -0
  86. package/global/browser-runtime.mjs +9 -5
  87. package/global/cli/command.mjs +6 -5
  88. package/global/cli/install.mjs +6 -3
  89. package/global/cli/path-link.mjs +11 -22
  90. package/global/cli/repo-command.mjs +4 -3
  91. package/global/cli/repository-contract.mjs +3 -3
  92. package/global/door/command.mjs +39 -38
  93. package/global/door/control.mjs +3 -3
  94. package/global/door/pages.mjs +6 -5
  95. package/global/door/server.mjs +8 -5
  96. package/global/door/sites.mjs +14 -13
  97. package/global/launch/capacity.mjs +2 -2
  98. package/global/launch/dev.mjs +6 -6
  99. package/global/launch/door.mjs +1 -1
  100. package/global/launch/facts.mjs +2 -2
  101. package/global/launch/failure.mjs +1 -1
  102. package/global/launch/prepare.mjs +3 -3
  103. package/global/launch/render.mjs +3 -2
  104. package/global/launch/worker.mjs +1 -1
  105. package/global/list.mjs +4 -4
  106. package/global/main.mjs +32 -31
  107. package/global/registry.mjs +1 -1
  108. package/global/run.mjs +5 -5
  109. package/global/update/command.mjs +5 -5
  110. package/global/update/notice.mjs +1 -1
  111. package/global/version.mjs +1 -1
  112. package/install.sh +17 -4
  113. package/modules/deploy-kit/README.md +11 -3
  114. package/modules/deploy-kit/asset-health.mjs +6 -4
  115. package/modules/deploy-kit/cancellation.mjs +26 -0
  116. package/modules/deploy-kit/d1-import-diagnostics.mjs +3 -2
  117. package/modules/deploy-kit/deploy.mjs +8 -3
  118. package/modules/deploy-kit/diagnostics.mjs +11 -4
  119. package/modules/deploy-kit/health-request.mjs +16 -9
  120. package/modules/deploy-kit/health.mjs +14 -11
  121. package/modules/deploy-kit/owner-cli.mjs +55 -25
  122. package/modules/deploy-kit/owner-remove.mjs +7 -6
  123. package/modules/deploy-kit/owner-secret-copy.mjs +2 -1
  124. package/modules/deploy-kit/owner-secret.mjs +8 -5
  125. package/modules/deploy-kit/owner.mjs +49 -30
  126. package/modules/deploy-kit/provider-transport.mjs +2 -0
  127. package/modules/deploy-kit/provider.mjs +10 -9
  128. package/modules/deploy-kit/readiness-window.mjs +5 -3
  129. package/modules/deploy-kit/site.mjs +1 -1
  130. package/modules/deploy-kit/teardown.mjs +5 -4
  131. package/modules/deploy-kit/validation.mjs +1 -0
  132. package/modules/deploy-kit/worker.mjs +1 -0
  133. package/modules/operator-auth/dev/index.mjs +4 -3
  134. package/modules/operator-auth/dev/sign-in-as.mjs +2 -1
  135. package/modules/operator-auth/dev-gate.mjs +3 -2
  136. package/modules/operator-auth/routes.mjs +2 -1
  137. package/modules/operator-auth/terminal-guidance.mjs +3 -0
  138. package/onboarding/adapter-settings.mjs +1 -0
  139. package/onboarding/adapter.mjs +3 -3
  140. package/onboarding/agent-handoff.mjs +1 -1
  141. package/onboarding/busy.mjs +1 -1
  142. package/onboarding/launcher.mjs +1 -1
  143. package/onboarding/local/environment.mjs +1 -1
  144. package/onboarding/local/operation.mjs +12 -4
  145. package/onboarding/local/owner.mjs +2 -2
  146. package/onboarding/operator-installer.mjs +4 -3
  147. package/onboarding/operator-migrations.mjs +1 -1
  148. package/onboarding/operator-prerequisites.mjs +26 -14
  149. package/onboarding/operator-settings.mjs +28 -0
  150. package/onboarding/process-diagnostics.mjs +2 -2
  151. package/onboarding/project-vite.mjs +1 -1
  152. package/package.json +1 -1
@@ -10,12 +10,12 @@ import { appAddress, appSignInHelp } from '../app-address.mjs';
10
10
  import { agentUsage, agentHelp } from './agent-help.mjs';
11
11
  import { agentFamilies } from './agent-table.mjs';
12
12
 
13
- const usage = `Set up your business: rer business connect --business ID
13
+ const usage = `Set up your business: ~/.local/bin/rer business connect --business ID
14
14
  The Business Connect page names the ID.
15
15
  Business keeps your business name, logo and brand colour together for the apps
16
16
  that support shared Business settings. Choose what to share in your browser.
17
17
 
18
- Advanced commands (Usage: rer business VERB)
18
+ Advanced commands (Usage: ~/.local/bin/rer business VERB)
19
19
  setup --origin URL --session-file FILE --confirm-demo
20
20
  Create the synthetic demo company's Business and its profile
21
21
  --hosting managed|assisted|self_host (default: managed); --json
@@ -41,13 +41,24 @@ Advanced commands (Usage: rer business VERB)
41
41
  disconnect Revoke this computer, then remove local credentials and additions;
42
42
  inside an agent sandbox it names the one command that finishes
43
43
  State lives in $RER_BUSINESS_STATE_DIR when set, otherwise in ~/.rer/business.
44
- In an agent sandbox that writes only inside its working folder, use RER_BUSINESS_STATE_DIR="$PWD/.rer-business".
44
+ Device credentials use OS Keychain/Secret Service unless RER_BUSINESS_CREDENTIAL_DIR is set.
45
+ When set, all public Business commands use atomic 0600 device credential files there,
46
+ in a caller-owned 0700 directory that is not a symlink; unsafe directories are refused.
47
+ Names use a digest of origin and Business ID; secrets never enter names or storage diagnostics.
48
+ This selection never touches OS device credential storage; no automatic migration occurs.
49
+ A sealed launcher must set both directories consistently for every Business invocation,
50
+ including its service process. Example private per-session directories:
51
+ umask 077
52
+ business_session_dir="$(mktemp -d)"
53
+ mkdir "$business_session_dir/state" "$business_session_dir/credentials"
54
+ export RER_BUSINESS_STATE_DIR="$business_session_dir/state"
55
+ export RER_BUSINESS_CREDENTIAL_DIR="$business_session_dir/credentials"
45
56
  ${agentUsage}${appSignInHelp}
46
57
  `;
47
58
 
48
59
  const verbHelp = {
49
60
  ...agentHelp,
50
- setup: `Usage: rer business setup --origin URL --session-file FILE --confirm-demo [--hosting managed|assisted|self_host] [--json]
61
+ setup: `Usage: ~/.local/bin/rer business setup --origin URL --session-file FILE --confirm-demo [--hosting managed|assisted|self_host] [--json]
51
62
  Create the Business for the synthetic demo company in setup-company.json and save
52
63
  its profile, through the platform's owner routes. A repeat reuses that Business and
53
64
  changes nothing when its profile already matches. It provisions no seeds.
@@ -64,31 +75,42 @@ changes nothing when its profile already matches. It provisions no seeds.
64
75
  Exits 0 when the Business exists with that profile; 1 with a named {code} on stderr.
65
76
  ${appSignInHelp}
66
77
  `,
67
- run: `Usage: rer business run --grant G -- <command> [args...]
78
+ run: `Usage: ~/.local/bin/rer business run --grant G -- <command> [args...]
68
79
  Run any software command under this paired agent’s explicit deploy action and grant.
69
80
  The scoped Cloudflare token and account reach only the child environment. Output
70
81
  is masked and cleanup is reported separately; the child’s exit status is kept.
82
+ Before starting, stderr shows the credential's UTC expiry and minutes remaining
83
+ (rounded up). At expiry the command is interrupted and says: run it again to resume.
84
+ The reported caller exit status keeps the child's code or terminating signal
85
+ (normally SIGTERM, shell status 143); a child that handles it keeps its own code.
86
+ A refused exchange starts nothing and exits 1. When Business says why (a pending
87
+ grant's gap), stderr prints it on one line after "Not started:".
71
88
 
72
- Usage: rer business run [--once]
89
+ Usage: ~/.local/bin/rer business run [--once]
73
90
  Work this computer's tasks (the folder scan the owner allows) and check in every
74
91
  25 seconds until stopped. Steps for this computer's agent, such as a seed's Move in,
75
- are shown by rer business next. --once returns after one check-in.
92
+ are shown by ~/.local/bin/rer business next. --once returns after one check-in.
76
93
  Exits 0 completed, idle or waiting for the owner; 1 failed; 2 usage.
77
94
  `,
78
- connect: `Usage: rer business connect --business ID [--origin URL] [--timeout SECONDS]
95
+ connect: `Usage: ~/.local/bin/rer business connect --business ID [--origin URL] [--timeout SECONDS]
79
96
  Pair this computer with a Business. Prints a code and a link: the owner opens the
80
97
  link in a signed-in browser, checks the code and approves. Waits for that (up to
81
- the code's 10 minutes), then keeps the credential in OS credential storage.
98
+ the code's 10 minutes), then keeps the device credential in OS Keychain/Secret Service,
99
+ or an atomic 0600 file when RER_BUSINESS_CREDENTIAL_DIR is set. That directory must
100
+ be caller-owned, mode 0700, and not a symlink; unsafe directories are refused.
101
+ File storage never touches OS device credential storage and does not migrate it.
102
+ Keep both RER_BUSINESS_STATE_DIR and RER_BUSINESS_CREDENTIAL_DIR consistent across
103
+ all Business invocations, including the service process.
82
104
  --business ID The Business to join; the Connect prompt names it.
83
105
  --origin URL Business platform address (default: ${appAddress}).
84
106
  --timeout SECONDS Wait at most this long, then exit 75 with the pairing kept;
85
107
  run the same command again to keep waiting (same code).
86
108
  Exits 0 connected, 1 ended (refused, expired or failed), 2 usage, 75 still waiting.
87
109
  `,
88
- token: `Usage: rer business token
110
+ token: `Usage: ~/.local/bin/rer business token
89
111
  Print an MCP Authorization header object for this computer's paired Business.
90
112
  Send this headersHelper output directly to the MCP client; it contains a credential.
91
- Requires an existing pairing: rer business connect --business ID (the Connect page names the ID).
113
+ Requires an existing pairing: ~/.local/bin/rer business connect --business ID (the Connect page names the ID).
92
114
  `,
93
115
  };
94
116
 
@@ -3,6 +3,7 @@ import { join } from 'node:path';
3
3
  import { Api, originUrl, identifier, pause } from './api.mjs';
4
4
  import { loadState, saveState, credentialHandle, deviceCredentialHandle, loadPending, savePending, clearPending, checkStateWritable, lockPairing } from './state.mjs';
5
5
  import { createCredentialStore } from './keychain.mjs';
6
+ import { credentialLocation } from './credential-file.mjs';
6
7
  import { applyChoices } from './choices.mjs';
7
8
  import { rerCommand, businessCommand } from './invocation.mjs';
8
9
  import { Stopped } from './errors.mjs';
@@ -65,7 +66,7 @@ async function connectDevice({ business, origin, timeout } = {}) {
65
66
  if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}`);
66
67
  if (stored.origin !== origin || stored.businessId !== business) throw Error(`This state folder is connected to Business ${identifier(stored.businessId)} at ${originUrl(stored.origin)}. Run disconnect, or use another RER_BUSINESS_STATE_DIR.`);
67
68
  const credential = await createCredentialStore().get(deviceCredentialHandle(stored));
68
- if (!credential) throw Error('This computer\'s Business credential is missing from OS credential storage. Run disconnect, then connect again.');
69
+ if (!credential) throw Error(`This computer's Business credential is missing from ${credentialLocation()}. Run disconnect, then connect again.`);
69
70
  await unlock(); unlock = undefined;
70
71
  return await connected(new Api(origin, credential), stored, { reconnecting: true });
71
72
  }
@@ -75,8 +76,7 @@ async function connectDevice({ business, origin, timeout } = {}) {
75
76
  validateDevicePairing({ ...pending, business_id: pending.businessId }, origin, business);
76
77
  if (!timestampValid(pending.keep_until) || Date.parse(pending.keep_until) > Date.parse(pending.expires_at) + approvalWindow) throw Error('The saved Business pairing is invalid. Run business disconnect, then connect again.');
77
78
  }
78
- // Both probes precede even the unauthenticated start. Keychain / Secret
79
- // Service handling and the device credential's account are unchanged.
79
+ // Both storage probes precede even the unauthenticated pairing start.
80
80
  const store = createCredentialStore();
81
81
  resume = `${rerCommand()} business connect --business ${business} --origin ${origin}${timeout === undefined ? '' : ` --timeout ${timeout}`}`;
82
82
  try { await store.check(); }
@@ -120,7 +120,7 @@ async function connectDevice({ business, origin, timeout } = {}) {
120
120
  await store.set(handle, result.device_credential);
121
121
  try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
122
122
  await clearPending();
123
- process.stdout.write('Approved. Device credential stored in OS credential storage.\n');
123
+ process.stdout.write(`Approved. Device credential stored in ${credentialLocation()}.\n`);
124
124
  return await connected(new Api(origin, result.device_credential), state);
125
125
  } finally { await clearPending(); }
126
126
  }
@@ -0,0 +1,102 @@
1
+ import { constants } from 'node:fs';
2
+ import { lstat, mkdir, open, rename, unlink } from 'node:fs/promises';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { join, resolve } from 'node:path';
5
+ import { localCause, redact } from './errors.mjs';
6
+ import { rememberDeviceCredential } from './run-mask.mjs';
7
+
8
+ export function credentialDirectory(env = process.env) {
9
+ const value = env.RER_BUSINESS_CREDENTIAL_DIR;
10
+ if (value === undefined) return null;
11
+ if (typeof value !== 'string' || !value.trim() || value.includes('\0')) throw Error('RER_BUSINESS_CREDENTIAL_DIR must name a nonempty private directory.');
12
+ return resolve(value);
13
+ }
14
+
15
+ export const credentialLocation = (env = process.env) => credentialDirectory(env) ?? 'OS credential storage';
16
+
17
+ /** Explicit private storage for a sealed launcher. Never consult OS storage,
18
+ * including when the file is absent or the selected directory is refused. */
19
+ export function fileCredentialStore(directory) {
20
+ const named = () => redact(JSON.stringify(directory));
21
+ const refused = (reason, fix) => Error(`Business credential directory ${named()} ${reason}. ${fix}.`);
22
+ const failed = (operation, error) => refused(`could not ${operation}: ${localCause(error) ?? 'filesystem operation failed'}`, 'Check access and free disk space, then retry');
23
+ const owned = info => typeof process.getuid === 'function' && info.uid === process.getuid();
24
+ async function validate() {
25
+ let info;
26
+ try { info = await lstat(directory); }
27
+ catch (error) {
28
+ if (error.code !== 'ENOENT') throw failed('be checked', error);
29
+ try { await mkdir(directory, { recursive: true, mode: 0o700 }); info = await lstat(directory); }
30
+ catch (error) { throw failed('be created', error); }
31
+ }
32
+ if (info.isSymbolicLink()) throw refused('is a symbolic link', 'Set RER_BUSINESS_CREDENTIAL_DIR to a real directory owned by your user with mode 0700');
33
+ if (!info.isDirectory()) throw refused('is not a directory', 'Set RER_BUSINESS_CREDENTIAL_DIR to a directory owned by your user with mode 0700');
34
+ if (!owned(info)) throw refused('is not owned by the calling user', 'Have its owner change ownership to your user, or choose a directory you own; set its mode to 0700');
35
+ if ((info.mode & 0o7777) !== 0o700) throw refused('must have mode 0700', `Run chmod 700 on ${named()}, then retry`);
36
+ }
37
+ function path(handle) {
38
+ if (typeof handle !== 'string' || !handle) throw Error('Invalid credential handle.');
39
+ const digest = /^device:[a-f0-9]{64}$/.test(handle) ? handle.slice(7) : createHash('sha256').update(handle).digest('hex');
40
+ return join(directory, `${digest}.credential`);
41
+ }
42
+ function checkFile(info) {
43
+ if (!info.isFile() || !owned(info) || (info.mode & 0o7777) !== 0o600) throw refused('contains an unsafe credential file', 'Use a regular credential file owned by your user with mode 0600; remove symbolic links');
44
+ }
45
+ async function existing(file) {
46
+ try { checkFile(await lstat(file)); } catch (error) { if (error.code !== 'ENOENT') throw error; }
47
+ }
48
+ async function syncDirectory() {
49
+ const folder = await open(directory, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
50
+ try { await folder.sync(); } finally { await folder.close(); }
51
+ }
52
+ return {
53
+ validate,
54
+ async check() {
55
+ const handle = `probe:${randomUUID()}`;
56
+ await this.set(handle, randomUUID());
57
+ await this.delete(handle);
58
+ },
59
+ async get(handle) {
60
+ await validate();
61
+ let file;
62
+ try {
63
+ file = await open(path(handle), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
64
+ checkFile(await file.stat());
65
+ const secret = await file.readFile('utf8');
66
+ if (!secret || Buffer.byteLength(secret) > 65536 || /[\x00-\x1f\x7f]/.test(secret)) throw refused('contains an invalid credential file', 'Remove that credential file and pair this computer again');
67
+ return rememberDeviceCredential(secret);
68
+ } catch (error) {
69
+ if (error.code === 'ENOENT') return null;
70
+ if (!error.code) throw error;
71
+ throw failed('read the credential file', error);
72
+ } finally { await file?.close(); }
73
+ },
74
+ async set(handle, secret) {
75
+ if (typeof secret !== 'string' || !secret || Buffer.byteLength(secret) > 65536 || /[\x00-\x1f\x7f]/.test(secret)) throw Error('Enter a nonempty, single-line credential.');
76
+ rememberDeviceCredential(secret);
77
+ await validate();
78
+ const target = path(handle), temporary = join(directory, `.credential-${randomUUID()}.tmp`);
79
+ let file;
80
+ try {
81
+ await existing(target);
82
+ file = await open(temporary, 'wx', 0o600);
83
+ await file.chmod(0o600);
84
+ await file.writeFile(secret, 'utf8');
85
+ await file.sync();
86
+ await file.close(); file = undefined;
87
+ await rename(temporary, target);
88
+ await syncDirectory();
89
+ return handle;
90
+ } catch (error) { if (!error.code) throw error; throw failed('save the credential file', error); }
91
+ finally {
92
+ await file?.close();
93
+ await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw failed('remove a temporary file', error); });
94
+ }
95
+ },
96
+ async delete(handle) {
97
+ await validate();
98
+ try { const target = path(handle); await existing(target); await unlink(target); await syncDirectory(); }
99
+ catch (error) { if (error.code === 'ENOENT') return; if (!error.code) throw error; throw failed('remove the credential file', error); }
100
+ },
101
+ };
102
+ }
@@ -1,3 +1,6 @@
1
+ import { withCommandHelp } from '../command-guidance.mjs';
2
+ import { maskDeviceText } from './run-mask.mjs';
3
+
1
4
  // Every message rer business prints names its cause: a server's reason, a
2
5
  // local system cause, or this CLI's own explanation. Device and task bearers
3
6
  // are redacted wherever a message came from.
@@ -9,7 +12,7 @@ const causes = {
9
12
  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
13
 
11
14
  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, ' ');
15
+ export const redact = text => maskDeviceText(text).replace(/bz_[a-z]+_[A-Za-z0-9_-]+/g, '[credential]').replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ' ');
13
16
 
14
17
  export function describe(error) {
15
18
  if (typeof error?.syscall === 'string' && typeof error.code === 'string') {
@@ -17,7 +20,7 @@ export function describe(error) {
17
20
  }
18
21
  const message = error instanceof Error ? error.message : String(error);
19
22
  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);
23
+ return withCommandHelp(redact(unexpected || !message ? `Business command failed unexpectedly: ${message || 'no reason given'}` : message));
21
24
  }
22
25
 
23
26
  // An exit status other than 1 travels with the error (130 after Ctrl-C).
@@ -21,13 +21,16 @@ export function rerCommand(env = process.env) {
21
21
  // The running entry identifies the invocation even when its dispatcher was
22
22
  // delegated to a checkout's pinned copy in another package/cache directory.
23
23
  if ((process.argv[1] ?? '').split(sep).includes('_npx')) return npx;
24
- if (env.RER_INVOKED_AS) return word(env.RER_INVOKED_AS);
25
- return onPath(env.PATH) ? 'rer' : npx;
24
+ if (env.RER_INVOKED_AS) return env.RER_INVOKED_AS === 'rer' ? '~/.local/bin/rer' : word(env.RER_INVOKED_AS);
25
+ return onPath(env.PATH) ? '~/.local/bin/rer' : npx;
26
26
  }
27
27
 
28
28
  // A rer business command the person can paste into another shell, such as a
29
29
  // terminal outside an agent sandbox: it names the state folder when one was chosen.
30
30
  export function businessCommand(verb, env = process.env) {
31
- const folder = env.RER_BUSINESS_STATE_DIR;
32
- return `${folder && !folder.includes('\0') ? `RER_BUSINESS_STATE_DIR=${word(resolve(folder))} ` : ''}${rerCommand(env)} business ${verb}`;
31
+ const folders = ['RER_BUSINESS_STATE_DIR', 'RER_BUSINESS_CREDENTIAL_DIR'].map(key => {
32
+ const folder = env[key];
33
+ return folder && !folder.includes('\0') ? `${key}=${word(resolve(folder))} ` : '';
34
+ }).join('');
35
+ return `${folders}${rerCommand(env)} business ${verb}`;
33
36
  }
@@ -1,5 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { randomUUID } from 'node:crypto';
3
+ import { credentialDirectory, fileCredentialStore } from './credential-file.mjs';
3
4
 
4
5
  const service = 'com.runeditrun.business';
5
6
  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';
@@ -56,10 +57,13 @@ function checkedSecret(secret) {
56
57
  return secret;
57
58
  }
58
59
 
59
- /** Secrets cross only stdin/stdout pipes, never arguments, files, or exceptions.
60
- * run is a process-edge seam for tests, not a selectable storage backend.
60
+ /** OS secrets cross only stdin/stdout pipes, never arguments or exceptions.
61
+ * The explicit directory switch is resolved before any OS process can start.
62
+ * run remains a process-edge seam for tests.
61
63
  */
62
64
  export function createCredentialStore({ platform = process.platform, env = process.env, run } = {}) {
65
+ const directory = credentialDirectory(env);
66
+ if (directory !== null) return fileCredentialStore(directory);
63
67
  const command = run ?? ((binary, args, input) => execute(binary, args, input, env));
64
68
  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.');
65
69
  const binary = platform === 'darwin' ? 'security' : 'secret-tool';
@@ -2,6 +2,7 @@ import { writeFile, unlink } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
3
  import { loadState, loadPending, saveState, stateDirectory, removeStateDirectory, removeWorkFiles, deviceCredentialHandle, liveSupervisor } from './state.mjs';
4
4
  import { createCredentialStore } from './keychain.mjs';
5
+ import { credentialDirectory, credentialLocation, fileCredentialStore } from './credential-file.mjs';
5
6
  import { removeService, serviceStatus } from './service.mjs';
6
7
  import { removePermissions, permissionsAdded } from './permissions.mjs';
7
8
  import { Api, pause } from './api.mjs';
@@ -16,7 +17,7 @@ export async function paired() {
16
17
  if (!state?.origin || !state.businessId || !state.executorId) throw Error(`This computer is not paired. Run ${rerCommand()} business connect --business ID; the Business Connect page names the ID.`);
17
18
  if (state.revoked) throw Error(`This computer was ${revokedText(state)}`);
18
19
  const credential = await createCredentialStore().get(deviceCredentialHandle(state));
19
- if (!credential) throw Error(`This computer's Business credential is missing from OS credential storage. Run ${rerCommand()} business disconnect, then run ${rerCommand()} business connect --business ID; the Connect page at ${state.origin}/business names the ID.`);
20
+ if (!credential) throw Error(`This computer's Business credential is missing from ${credentialLocation()}. Run ${rerCommand()} business disconnect, then run ${rerCommand()} business connect --business ID; the Connect page at ${state.origin}/business names the ID.`);
20
21
  return { state, credential };
21
22
  }
22
23
 
@@ -115,21 +116,26 @@ export async function disconnect() {
115
116
  ? `Business disconnected. Device ${wasRevoked ? 'was already revoked' : 'revoked'}; local service, credentials and added permissions removed.\n`
116
117
  : wasRevoked ? 'Business disconnected. Device was already revoked on the server; local service, credentials and added permissions removed.\n'
117
118
  : `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`);
119
+ if (credential && credentialDirectory() !== null) process.stdout.write(`Device credential file removed from ${credentialLocation()}.\n`);
118
120
  }
119
121
 
120
122
  export async function status({ json = false } = {}) {
123
+ const directory = credentialDirectory();
124
+ if (directory !== null) await fileCredentialStore(directory).validate();
125
+ const location = credentialLocation();
121
126
  const state = await loadState();
122
127
  if (!state) {
123
- process.stdout.write(json ? JSON.stringify({ paired: false, service: 'not_installed', current_task: null, checkpoint: null }) + '\n' : 'Business: not paired.\nService: not installed.\nTask: none.\nCheckpoint: none.\n'); return;
128
+ process.stdout.write(json ? JSON.stringify({ paired: false, service: 'not_installed', current_task: null, checkpoint: null, credential_storage: location }) + '\n' : `Business: not paired.\nService: not installed.\nTask: none.\nCheckpoint: none.\nCredential storage: ${location}.\n`); return;
124
129
  }
125
130
  const stored = !state.revoked && state.origin && await createCredentialStore().get(deviceCredentialHandle(state));
126
131
  const service = await serviceStatus();
127
132
  const active = state.revoked ? null : (await loadProgress()).current;
128
133
  if (json) {
129
- process.stdout.write(JSON.stringify({ paired: Boolean(stored), ...(state.revoked ? { revoked: true } : {}), service: service.running ? 'running' : service.installed ? 'stopped' : 'not_installed', current_task: supportsTaskKind(active?.kind) ? active.kind : null, checkpoint: active?.checkpoint ? { saved: true, uploaded_bytes: Number.isSafeInteger(active.uploadedBytes) ? active.uploadedBytes : 0 } : null }) + '\n');
134
+ process.stdout.write(JSON.stringify({ paired: Boolean(stored), ...(state.revoked ? { revoked: true } : {}), service: service.running ? 'running' : service.installed ? 'stopped' : 'not_installed', current_task: supportsTaskKind(active?.kind) ? active.kind : null, checkpoint: active?.checkpoint ? { saved: true, uploaded_bytes: Number.isSafeInteger(active.uploadedBytes) ? active.uploadedBytes : 0 } : null, credential_storage: location }) + '\n');
130
135
  return;
131
136
  }
132
137
  process.stdout.write(`Business: ${state.revoked ? revokedText(state) : stored ? 'paired.' : 'credential missing.'}\nService: ${service.running ? 'running' : service.installed ? 'installed, stopped' : 'not installed'}.\n`);
133
138
  process.stdout.write(`Task: ${supportsTaskKind(active?.kind) ? active.kind : 'none'}.\n`);
134
139
  process.stdout.write(`Checkpoint: ${active?.checkpoint ? 'saved' : 'none'}${Number.isSafeInteger(active?.uploadedBytes) ? `; ${active.uploadedBytes} bytes uploaded` : ''}.\n`);
140
+ process.stdout.write(`Credential storage: ${location}.\n`);
135
141
  }
@@ -3,6 +3,7 @@ import { Api } from './api.mjs';
3
3
  import { mcpClient } from './questions.mjs';
4
4
  import { paired } from './local-commands.mjs';
5
5
  import { describe } from './errors.mjs';
6
+ import { maskDeviceText } from './run-mask.mjs';
6
7
 
7
8
  const protocolVersion = '2025-11-25';
8
9
  const forwarded = /^(tools|resources|prompts|completion|logging)\//;
@@ -16,7 +17,7 @@ export async function bridge({ input = process.stdin, output = process.stdout, e
16
17
  const { state, credential } = await paired();
17
18
  return mcpClient(new Api(state.origin, credential));
18
19
  })().catch(error => { session = undefined; throw error; });
19
- const send = message => output.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n');
20
+ const send = message => output.write(maskDeviceText(JSON.stringify({ jsonrpc: '2.0', ...message })) + '\n');
20
21
  const fail = (id, code, text) => send({ id, error: { code, message: text } });
21
22
 
22
23
  async function handle(message) {
@@ -191,7 +191,7 @@ export async function next() {
191
191
  export async function answer(id, vendorId, choice, rawConfidence = '1') {
192
192
  identifier(id);
193
193
  // Reject free text before even looking up the question or minting a bearer.
194
- if (typeof vendorId !== 'string' || !/^[a-z][a-z0-9-]{0,79}$/.test(vendorId) || sensitive(vendorId)) throw Error('Choose a catalog vendor id from rer business next, or none.');
194
+ if (typeof vendorId !== 'string' || !/^[a-z][a-z0-9-]{0,79}$/.test(vendorId) || sensitive(vendorId)) throw Error('Choose a catalog vendor id from ~/.local/bin/rer business next, or none.');
195
195
  if (!classifications.includes(choice)) throw Error(`Choose an enum: ${classifications.join(', ')}.`);
196
196
  if (!/^(?:0(?:\.\d+)?|1(?:\.0+)?)$/.test(rawConfidence)) throw Error('Choose a numeric confidence between 0 and 1.');
197
197
  const confidence = Number(rawConfidence);
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { constants } from 'node:os';
3
- import { commandMask } from './run-mask.mjs';
3
+ import { commandMask, deviceCredentialValues } from './run-mask.mjs';
4
4
 
5
5
  export const signalCode = signal => 128 + (constants.signals[signal] ?? 1);
6
6
  export function childEnvironment(source, credential, account) {
@@ -9,8 +9,8 @@ export function childEnvironment(source, credential, account) {
9
9
  }
10
10
  /** Own one process group, forward interruption, and bound its lifetime to the credential's server expiry. */
11
11
  export async function runChild(command, lease, { signal, source = process.env, output = process.stdout, errors = process.stderr } = {}) {
12
- const values = [lease.credential, lease.account_id], stdout = commandMask(values, output), stderr = commandMask(values, errors);
13
- let child, escalation, expiry, stopped;
12
+ const values = [lease.credential, lease.account_id, ...deviceCredentialValues()], stdout = commandMask(values, output), stderr = commandMask(values, errors);
13
+ let child, escalation, expiry, stopped, credentialExpired = false;
14
14
  const stop = reason => {
15
15
  stopped ??= reason;
16
16
  if (!child?.pid) return;
@@ -26,7 +26,7 @@ export async function runChild(command, lease, { signal, source = process.env, o
26
26
  child.stdout.on('data', stdout.write); child.stderr.on('data', stderr.write);
27
27
  signal?.addEventListener('abort', interrupt, { once: true });
28
28
  if (signal?.aborted) interrupt();
29
- expiry = setTimeout(() => stop('SIGTERM'), Math.max(1, Date.parse(lease.credential_expires_at) - Date.now()));
29
+ expiry = setTimeout(() => { if (!stopped) credentialExpired = true; stop('SIGTERM'); }, Math.max(1, Date.parse(lease.credential_expires_at) - Date.now()));
30
30
  const result = await new Promise(resolve => {
31
31
  let spawnError;
32
32
  child.on('error', error => { spawnError = error; });
@@ -34,7 +34,7 @@ export async function runChild(command, lease, { signal, source = process.env, o
34
34
  : { code: code ?? signalCode(exitSignal ?? stopped ?? 'SIGTERM'), signal: exitSignal }));
35
35
  });
36
36
  if (result.spawnError) errors.write(`Command could not start (${String(result.spawnError).replace(/[^A-Z0-9_]/g, '')}).\n`);
37
- return result;
37
+ return { ...result, credentialExpired };
38
38
  } finally {
39
39
  clearTimeout(expiry); clearTimeout(escalation); signal?.removeEventListener('abort', interrupt);
40
40
  stdout.end(); stderr.end();
@@ -1,10 +1,26 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { Api, identifier } from './api.mjs';
2
+ import { Api, ApiError, identifier } from './api.mjs';
3
+ import { redact } from './errors.mjs';
3
4
  import { paired } from './local-commands.mjs';
4
5
  import { runChild, signalCode } from './run-child.mjs';
5
6
 
6
7
  const route = '/api/business/executors/cloudflare-token';
7
- const usage = 'Usage: rer business run --grant G -- <command> [args...]\n';
8
+ const usage = 'Usage: ~/.local/bin/rer business run --grant G -- <command> [args...]\n';
9
+ const refused = 'Business command refused or its credential exchange failed. Check pairing, selected account, deploy action, grant and Cloudflare consent in Business.';
10
+ // A refused exchange can say why its grant cannot mint (409 {state, gap, catalogue}). Only the gap sentence, whether the
11
+ // grant stays pending and the catalogue's two counts are read: no other key, and never a token, header or value.
12
+ function exchangeGap(body) {
13
+ const gap = typeof body.gap === 'string' ? redact(body.gap).replace(/\s+/g, ' ').trim() : '';
14
+ const count = value => Number.isSafeInteger(value) && value >= 0 ? value : null;
15
+ const rows = count(body.catalogue?.rows), workers = count(body.catalogue?.workers_rows);
16
+ return { gap: gap.length > 2000 ? `${gap.slice(0, 1999)}…` : gap, pending: body.state === 'pending',
17
+ catalogue: rows === null || workers === null ? null : { rows, workers } };
18
+ }
19
+ function refusalLine({ gap, pending, catalogue } = {}) {
20
+ return [gap ? `Not started: ${gap}${/[.!?…]$/.test(gap) ? '' : '.'}` : refused, pending && 'The grant stays pending; nothing was issued.',
21
+ catalogue && `catalogue: ${catalogue.rows} rows, ${catalogue.workers} mention Workers (see the audit row cloudflare.token.catalogue)`]
22
+ .filter(Boolean).join(' ') + '\n';
23
+ }
8
24
  function validLease(value, state, grant, id) {
9
25
  return value?.lease_id === id && value.grant_id === grant && value.business_id === state.businessId && value.executor_id === state.executorId
10
26
  && /^[a-f0-9]{32}$/.test(value.account_id) && typeof value.credential === 'string' && value.credential.length >= 16 && value.credential.length <= 4096
@@ -22,7 +38,7 @@ async function cleanup(api, id) {
22
38
  }
23
39
  export async function cleanupCommand(args) {
24
40
  if (args.length < 1 || args.length > 2 || args[1] !== undefined && args[1] !== '--status' || !/^[a-f0-9-]{36}$/.test(args[0])) {
25
- process.stderr.write('Usage: rer business cleanup LEASE [--status]\n'); return 2;
41
+ process.stderr.write('Usage: ~/.local/bin/rer business cleanup LEASE [--status]\n'); return 2;
26
42
  }
27
43
  const {state, credential} = await paired(), api = new Api(state.origin, credential), id = args[0];
28
44
  try {
@@ -44,17 +60,20 @@ export async function grantCommand(args) {
44
60
  let lease, code = 1, exitSignal;
45
61
  try {
46
62
  // No automatic retry: a lost response may already have minted a child. Cleanup uses the preselected lease id.
47
- lease = await api.post(route, {grant_id: args[1], lease_id: id}, {quiet: true, signal: stop.signal});
63
+ lease = await api.post(route, {grant_id: args[1], lease_id: id}, {quiet: true, signal: stop.signal, detail: exchangeGap});
48
64
  if (!validLease(lease, state, args[1], id) || lease.credential === credential) throw Error('invalid credential exchange');
49
- const result = await runChild(args.slice(3), lease, {signal: stop.signal});
65
+ const expiry = new Date(lease.credential_expires_at).toISOString(), minutes = Math.ceil((Date.parse(expiry) - Date.now()) / 60000);
66
+ process.stderr.write(`Cloud credential expiry: ${expiry} (${minutes} ${minutes === 1 ? 'minute' : 'minutes'} remaining).\n`);
67
+ const result = await runChild(args.slice(3), lease, {signal: stop.signal, source: {...process.env, RER_BUSINESS_GRANT: args[1]}});
50
68
  code = result.code; exitSignal = result.signal;
51
- } catch {
69
+ if (result.credentialExpired) process.stderr.write(`Command stopped because the credential expired; run it again to resume. Caller exit status: ${code}${exitSignal ? ` (${exitSignal})` : ''}.\n`);
70
+ } catch (error) {
52
71
  code = stop.signal.aborted ? signalCode(stop.signal.reason.signal) : 1;
53
- process.stderr.write('Business command refused or its credential exchange failed. Check pairing, selected account, deploy action, grant and Cloudflare consent in Business.\n');
72
+ process.stderr.write(refusalLine(error instanceof ApiError ? error.detail : undefined));
54
73
  } finally {
55
74
  const status = await cleanup(api, id);
56
75
  const expiry = lease && Number.isFinite(Date.parse(lease.credential_expires_at)) ? new Date(lease.credential_expires_at).toISOString() : 'the server-enforced expiry (at most 15 minutes)';
57
- process.stderr.write(`Cloud credential cleanup: ${status}. Lease ${id}.${status === 'unconfirmed' ? ` Credential expiry: ${expiry}. Retry: rer business cleanup ${id}.` : ''}\n`);
76
+ process.stderr.write(`Cloud credential cleanup: ${status}. Lease ${id}.${status === 'unconfirmed' ? ` Credential expiry: ${expiry}. Retry: ~/.local/bin/rer business cleanup ${id}.` : ''}\n`);
58
77
  lease = undefined;
59
78
  for (const [signal, handler] of handlers) process.removeListener(signal, handler);
60
79
  }
@@ -1,9 +1,16 @@
1
1
  import { StringDecoder } from 'node:string_decoder';
2
2
 
3
+ // File-backed device credentials stay in memory only. Use the same encodings
4
+ // for server diagnostics, MCP/agent results and scoped command output.
5
+ const deviceCredentials = new Set();
6
+ export const rememberDeviceCredential = secret => { deviceCredentials.add(secret); return secret; };
7
+ export const deviceCredentialValues = () => [...deviceCredentials];
8
+ export const maskDeviceText = text => commandMask(deviceCredentialValues()).text(String(text));
9
+
3
10
  /** Keep a possible credential prefix across writes; neither chunk boundaries nor EOF release it. */
4
11
  export function commandMask(values, output) {
5
12
  const secrets = [...new Set(values.filter(value => typeof value === 'string' && value).flatMap(value =>
6
- [value, encodeURIComponent(value), Buffer.from(value).toString('base64'), Buffer.from(value).toString('base64url')]))].sort((a, b) => b.length - a.length);
13
+ [value, encodeURIComponent(value), Buffer.from(value).toString('hex'), Buffer.from(value).toString('base64'), Buffer.from(value).toString('base64url')]))].sort((a, b) => b.length - a.length);
7
14
  const decoder = new StringDecoder('utf8');
8
15
  let pending = '';
9
16
  function replace(text) { for (const secret of secrets) text = text.split(secret).join('[credential]'); return text; }
@@ -1,7 +1,7 @@
1
1
  import { scan } from './scan.mjs';
2
2
  import { localCause } from './errors.mjs';
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
+ const usage = 'Usage: ~/.local/bin/rer business scan [DIR...] [--json]\nNames-only local discovery; returns rer-business-signals/1 JSON. No network calls.\n';
5
5
 
6
6
  export async function scanCommand(argv) {
7
7
  if (!argv.length || argv.length === 1 && ['--help', '-h'].includes(argv[0]) || argv[0] === 'scan' && argv.slice(1).some(arg => ['--help', '-h'].includes(arg))) {
@@ -5,6 +5,7 @@ import { dirname, join, isAbsolute } from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
7
  import { stateDirectory } from './state.mjs';
8
+ import { credentialDirectory } from './credential-file.mjs';
8
9
 
9
10
  const label = 'com.runeditrun.business', unit = 'rer-business.service';
10
11
  const digest = text => createHash('sha256').update(text).digest('hex');
@@ -65,8 +66,9 @@ export async function installService(input = {}) {
65
66
  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.');
66
67
  const log = join(o.stateDir, 'service.log'), errorLog = join(o.stateDir, 'service-error.log');
67
68
  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]] : [])];
69
+ // Chosen state and credential folders go with the service; only paths, no secrets.
70
+ const credentials = credentialDirectory();
71
+ const environment = [['HOME', o.home], ['PATH', environmentPath], ...(o.stateDir !== join(o.home, '.rer', 'business') ? [['RER_BUSINESS_STATE_DIR', o.stateDir]] : []), ...(credentials !== null ? [['RER_BUSINESS_CREDENTIAL_DIR', credentials]] : [])];
70
72
  const text = o.platform === 'darwin'
71
73
  ? `<?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
74
  : `[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`;
@@ -28,7 +28,7 @@ async function loadJson(name) {
28
28
  // Under a path that is not a folder (ENOTDIR) nothing can have been saved yet.
29
29
  catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null; throw error; }
30
30
  try { return JSON.parse(text); }
31
- catch { throw Error(`Business could not read ${path}: it is not valid JSON. Remove it, or run rer business disconnect, then connect again.`); }
31
+ catch { throw Error(`Business could not read ${path}: it is not valid JSON. Remove it, or run ~/.local/bin/rer business disconnect, then connect again.`); }
32
32
  }
33
33
 
34
34
  export const loadState = () => loadJson('state.json');
@@ -39,7 +39,7 @@ export async function clearPending() {
39
39
  }
40
40
 
41
41
  // Only non-secret configuration and progress belong here. Credentials and task
42
- // grants remain in the keychain and memory, respectively.
42
+ // grants remain in the selected credential store and memory, respectively.
43
43
  export async function saveState(state) {
44
44
  return saveJson('state.json', state);
45
45
  }
@@ -8,7 +8,7 @@ export async function checkoutFolders(directory) {
8
8
  const path = join(directory, item.name);
9
9
  try {
10
10
  if ((await stat(path)).isDirectory() && (await stat(join(path, 'OPERATIONS.json'))).isFile()) folders.push(await realpath(path));
11
- } catch { /* Not a readable checkout, as in rer list. */ }
11
+ } catch { /* Not a readable checkout, as in ~/.local/bin/rer list. */ }
12
12
  }
13
13
  return [...new Set(folders)];
14
14
  }
@@ -66,18 +66,18 @@ export async function checkoutPreparation(checkout, env = process.env) {
66
66
  let describing = true;
67
67
  try {
68
68
  const entry = await pinnedEntry(checkout);
69
- if (!entry) return { prepared: false, reason: 'the pinned rer package is not installed: run rer install' };
69
+ if (!entry) return { prepared: false, reason: 'the pinned rer package is not installed: run ~/.local/bin/rer install' };
70
70
  const { stdout } = await promisify(execFile)(process.execPath, [entry, 'describe', '--json'], { cwd: checkout, env, maxBuffer: 16 * 1024 * 1024, timeout: 30000 });
71
71
  const described = JSON.parse(stdout);
72
72
  describing = false;
73
73
  const last = await readJson(join(launchPath(checkout, env), 'setup.json'));
74
74
  const needed = await setupNeeded(checkout, described, last);
75
- return { prepared: !needed, ...(needed ? { reason: 'the checkout is not set up yet: run rer setup' } : {}) };
75
+ return { prepared: !needed, ...(needed ? { reason: 'the checkout is not set up yet: run ~/.local/bin/rer setup' } : {}) };
76
76
  } catch (error) {
77
77
  const { createRedaction, credentialValues } = await shared('redaction.mjs');
78
78
  const redaction = createRedaction();
79
79
  redaction.addSecrets(credentialValues(env));
80
- const cause = error.stderr?.trim() || (describing ? `rer describe failed in ${checkout}.` : error.message);
81
- return { prepared: null, reason: `rer describe fails here: ${redaction.redact(cause.split('\n')[0])}` };
80
+ const cause = error.stderr?.trim() || (describing ? `~/.local/bin/rer describe failed in ${checkout}.` : error.message);
81
+ return { prepared: null, reason: `~/.local/bin/rer describe fails here: ${redaction.redact(cause.split('\n')[0])}` };
82
82
  }
83
83
  }
@@ -0,0 +1,9 @@
1
+ // Shared terminal and browser guidance for an installation outside PATH.
2
+ import { terminalHelp as commandNotFoundHelp } from '../modules/operator-auth/terminal-guidance.mjs';
3
+ export { commandNotFoundHelp };
4
+
5
+ export function withCommandHelp(text) {
6
+ const value = String(text);
7
+ return /(?:~\/\.local\/bin\/)?rer (?:[a-z][a-z-]*|--help)\b/.test(value) && !value.includes(commandNotFoundHelp)
8
+ ? `${value}\n${commandNotFoundHelp}` : value;
9
+ }