@runeditrun/rer 0.2.119 → 0.2.121

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/cli/README.md CHANGED
@@ -100,6 +100,25 @@ For older installations without an answer record, a runtime selection outside
100
100
  the installer field's choices cannot replace an adapter-declared local choice.
101
101
  Explicit answers and recorded installer choices still undergo strict validation.
102
102
 
103
+ ## Browser prerequisites
104
+
105
+ Signed: Run Edit Run fleet, 2026-11-16.
106
+
107
+ `rer doctor` and `rer describe` inspect the checkout's Playwright registry
108
+ without launching or downloading a browser. Headless verification needs only
109
+ `chromium-headless-shell` when that Playwright pin provides it; older pins use
110
+ `chromium`. A checkout that also runs headed Chromium declares
111
+ `browser: { headless: false }` in its command adapter. That adds full Chromium
112
+ to verification's headless prerequisite. `rer run` also honors `--headed` and
113
+ `--debug` in the selected Playwright script or its forwarded arguments.
114
+
115
+ Missing executables are named with their use and one browser-only command
116
+ using the checkout's resolved Playwright CLI. Run that command from the checkout
117
+ root to acquire browsers without verification. `rer install` installs locked
118
+ dependencies without browsers. The first `rer verify` (or declared Playwright
119
+ `rer run`) downloads the required target; a headless-only checkout downloads
120
+ only the headless shell, using the pin's own platform and revision.
121
+
103
122
  ## Back up and restore this installation
104
123
 
105
124
  Use `rer export` / `rer import` to back up and restore this installation. This
@@ -292,6 +311,36 @@ anything is built or uploaded. The seed owns what an installation does with mail
292
311
  off, and turning mail on later is a `rer deploy --set-secret` of the provider
293
312
  inputs the seed documents.
294
313
 
314
+ A seed can opt into a switchable public selector with one `deploy.json` edit:
315
+
316
+ ```json
317
+ {
318
+ "publicSettings": ["MAIL_PROVIDER"],
319
+ "vars": { "MAIL_PROVIDER": "none" },
320
+ "secrets": [
321
+ { "binding": "MAIL_PROVIDER", "environment": "MAIL_PROVIDER", "optional": true }
322
+ ]
323
+ }
324
+ ```
325
+
326
+ Merge these entries into the existing declaration, keeping its other settings
327
+ and credentials. Retain the same `MAIL_PROVIDER=none` default in Wrangler vars
328
+ and the managed spec's `publicVariableNames`; the selector stays public in the
329
+ managed artifact, outside its secret names. `rer check` accepts this explicit
330
+ public default plus optional transport and reports conflicting source defaults.
331
+ `rer doctor` names the supported declaration when a source overlap is refused.
332
+ Declarations without this combination keep their previous behavior.
333
+
334
+ Use `rer deploy --set-secret MAIL_PROVIDER=sendgrid --set-secret MAIL_API_KEY
335
+ --env-file deploy.env` with the seed's declared sender and credential inputs.
336
+ The existing name-only form still reads the declared environment mapping.
337
+ `NAME=VALUE` is accepted only for opted-in public settings; credentials still
338
+ come from the environment or an owned 0600 `--env-file` and remain masked.
339
+ `rer deploy --unset-secret MAIL_PROVIDER,MAIL_API_KEY` removes those overrides
340
+ and restores the declared public default in the same Worker version. A plain
341
+ deploy preserves a held override. These changes use the existing ownership,
342
+ grouped-version and recovery machinery and preserve the admitted owner.
343
+
295
344
  The adapter must apply that selection to the runtime as well as pass preflight.
296
345
  For example, the foundation declares optional `MAIL_PROVIDER` and `MAIL_FROM`
297
346
  environment-to-binding mappings in `deploy.json`, and makes `MAIL_API_KEY`
@@ -697,3 +746,43 @@ unattempted sizes `complete:false`; these files keep the existing statement name
697
746
  SQL and bound parameters and carry diagnostic flow summaries. Missing work never
698
747
  produces a passing growth verdict. See the size section of
699
748
  [the command contract](../export/SEED-COMMAND-CONTRACT.md#statement-size-and-growth-sc-15).
749
+
750
+ ## Run a command with a Business grant
751
+
752
+ Pair with the Business using `rer business connect --business ID`. The owner
753
+ approves this agent, ticks **Run software commands with an approved cloud grant**,
754
+ Connects Cloudflare, selects the exact Business account and approves a per-agent
755
+ grant with explicit resource permissions and expiry. These choices install nothing.
756
+
757
+ ```sh
758
+ rer business run --grant GRANT_ID -- rer deploy
759
+ rer business run --grant GRANT_ID -- any-command 'argument with spaces'
760
+ ```
761
+
762
+ `cloudflare.token` in the Business MCP describes the exchange without returning a
763
+ credential. Only the paired rer exchange receives a child token; the parent OAuth
764
+ credential stays on the trusted server. The command gets `CLOUDFLARE_API_TOKEN`
765
+ and `CLOUDFLARE_ACCOUNT_ID` in its environment. Cloudflare credential aliases from
766
+ the caller environment are removed. No shell is inserted and arguments after
767
+ `--`, including help flags, are passed unchanged. Existing `run [--once]` continues
768
+ its computer check-in behavior.
769
+
770
+ This is an environment boundary, not a sandbox. The selected process and its
771
+ descendants can read and use the credential, and a malicious process can disclose
772
+ it or read other files or OS credentials available to the same user. Use software
773
+ you trust. Output masks the credential and common encoded forms across chunk
774
+ boundaries; it cannot hide every transformation a malicious process invents.
775
+ Commands may load their own files and credentials. The wrapper supplies only the
776
+ approved credential, never retries with broader or ambient access, and does not
777
+ protect a process from its own deliberate credential loading.
778
+
779
+ The child expires after at most 15 minutes, bounded also by the grant and the
780
+ provider authorization. The wrapper interrupts a command at that expiry. It
781
+ requests revocation after success, failure, signals or spawn failure; SIGKILL,
782
+ crashes, network loss and lost acknowledgements may leave a token until server
783
+ expiry. Child exit codes and Unix terminating signals are preserved. Cleanup has
784
+ its own stderr status, including **unconfirmed**, which is never called revoked.
785
+ The safe lease ID in that status supports `rer business cleanup LEASE` to retry
786
+ revocation and `rer business cleanup LEASE --status` to read its status. Cleanup
787
+ needs the original pairing, but does not require the removed deploy action or an
788
+ active grant. No child token is saved in state, OS storage, logs or MCP output.
@@ -10,7 +10,7 @@ import { RerError } from './errors.mjs';
10
10
  import { shared } from './shared.mjs';
11
11
 
12
12
  export const browserRepair = 'rer install';
13
- export const browserDownload = 'rer verify downloads them the first time it runs';
13
+ export const browserDownload = 'rer verify downloads the required browser on first use; rer install installs dependencies, not browsers';
14
14
 
15
15
  export function checkoutPlaywright(root, { required = true } = {}) {
16
16
  const require = createRequire(join(root, 'package.json'));
@@ -33,42 +33,57 @@ export function checkoutPlaywright(root, { required = true } = {}) {
33
33
  if (required) throw new RerError('browser_dependency_missing', `The checkout's Playwright is missing. Run ${browserRepair} to install its locked dependencies; verification requires playwright-core, @playwright/test or playwright.`, 3);
34
34
  }
35
35
 
36
- export async function browserDoctor(root) {
36
+ // Verification uses headless Chromium. A checkout that also needs headed
37
+ // Chromium declares commandAdapter.browser = { headless: false }.
38
+ export async function browserDoctor(root, { headless = true } = {}) {
37
39
  let resolved;
38
40
  try { resolved = checkoutPlaywright(root); }
39
41
  catch (error) { return { ok: false, issue: error instanceof RerError ? error.message : `The checkout's Playwright could not be inspected. Run ${browserRepair}.`, fix: browserRepair, executables: [] }; }
42
+ const shell = resolved.registry.findExecutable('chromium-headless-shell');
43
+ const names = headless && shell ? ['chromium-headless-shell'] : ['chromium', ...(shell ? ['chromium-headless-shell'] : [])];
40
44
  const executables = [];
41
- for (const name of ['chromium', 'chromium-headless-shell']) {
45
+ for (const name of names) {
42
46
  // Releases before the separate headless shell use the Chromium executable.
43
- const executable = resolved.registry.findExecutable(name);
44
- if (!executable && name === 'chromium-headless-shell') continue;
47
+ const executable = name === 'chromium-headless-shell' ? shell : resolved.registry.findExecutable(name);
45
48
  const path = executable?.executablePath();
46
49
  let ok = false;
47
50
  if (path) try { await access(path, process.platform === 'win32' ? constants.F_OK : constants.X_OK); ok = true; } catch {}
48
- executables.push({ name, ...(path ? { path } : {}), ok });
51
+ const reason = name === 'chromium-headless-shell' ? 'headless verification' : headless ? 'headless verification with this Playwright pin (no separate headless shell)' : 'declared headed browser use';
52
+ executables.push({ name, ...(path ? { path } : {}), ok, reason });
49
53
  }
50
54
  // Not yet downloaded is the normal state until a command needs the browser.
51
- const missing = executables.filter(executable => !executable.ok).map(executable => executable.name);
52
- return { ok: true, package: resolved.name, executables, ...(missing.length ? { note: `Playwright browsers not downloaded yet: ${missing.join(', ')}; ${browserDownload}.` } : {}) };
55
+ const missing = executables.filter(executable => !executable.ok);
56
+ const target = headless && shell ? 'chromium-headless-shell' : 'chromium';
57
+ const command = browserInstallCommand(root, resolved.cli, target);
58
+ return { ok: true, package: resolved.name, headless, executables, ...(missing.length ? { command, note: `Playwright browser not downloaded yet: ${missing.map(({ name, reason }) => `${name} (needed for ${reason})`).join(', ')}. Browser-only install: ${command}; ${browserDownload}.` } : {}) };
53
59
  }
54
60
 
55
- export async function ensureChromium(root, store, signal, { required = true } = {}) {
61
+ // Quote project-relative paths for a command copied into the checkout's shell.
62
+ function browserInstallCommand(root, cli, target) {
63
+ const path = relative(root, cli).split('\\').join('/');
64
+ const quoted = /^[a-zA-Z0-9_./@-]+$/.test(path) ? path : process.platform === 'win32' ? `"${path}"` : "'" + path.replaceAll("'", "'\\''") + "'";
65
+ return `pnpm exec node ${quoted} install ${target}`;
66
+ }
67
+
68
+ export async function ensureChromium(root, store, signal, { required = true, ...use } = {}) {
56
69
  // A first-party adapter without browser dependencies remains valid.
57
70
  // Verification requires Playwright; rer run provisions it when declared.
58
71
  const resolved = checkoutPlaywright(root, { required });
59
72
  if (!resolved) return;
60
- if (await browsersPresent(root)) return;
61
- const { cli } = resolved;
73
+ const browser = await browserDoctor(root, use);
74
+ if (!browser.note) return;
75
+ const target = browser.headless && resolved.registry.findExecutable('chromium-headless-shell') ? 'chromium-headless-shell' : 'chromium';
62
76
  const { dependencyEnvironment } = await shared('dependency-environment.mjs');
63
77
  const env = dependencyEnvironment();
64
78
  if (process.env.PLAYWRIGHT_BROWSERS_PATH !== undefined) env.PLAYWRIGHT_BROWSERS_PATH = process.env.PLAYWRIGHT_BROWSERS_PATH;
65
- await store.run('Installing Chromium and its headless shell from the checkout’s Playwright', 'pnpm', ['exec', 'node', cli, 'install', 'chromium'], { cwd: root, signal, env, display: `pnpm exec node ${relative(root, cli)} install chromium` });
66
- const absent = (await browserDoctor(root)).executables.filter(executable => !executable.ok).map(executable => executable.name);
67
- if (absent.length) throw new RerError('browser_install_incomplete', `The checkout's Playwright did not install every browser it pins (missing: ${absent.join(', ')}). Run the same command again; it retries the download.`, 3);
79
+ await store.run(`Installing ${target} from the checkout’s Playwright`, 'pnpm', ['exec', 'node', resolved.cli, 'install', target], { cwd: root, signal, env, display: browser.command });
80
+ const after = await browserDoctor(root, use);
81
+ const absent = after.executables.filter(executable => !executable.ok).map(executable => executable.name);
82
+ if (absent.length) throw new RerError('browser_install_incomplete', `The checkout's Playwright did not install the required browser (missing: ${absent.join(', ')}). Run ${browser.command} again; it retries the download.`, 3);
68
83
  }
69
84
 
70
- // Whether every browser the checkout's Playwright pins is on disk.
71
- export async function browsersPresent(root) {
72
- const browser = await browserDoctor(root).catch(() => undefined);
85
+ // Whether the executables needed by this checkout's declared use are on disk.
86
+ export async function browsersPresent(root, use) {
87
+ const browser = await browserDoctor(root, use).catch(() => undefined);
73
88
  return Boolean(browser?.ok && !browser.note);
74
89
  }
@@ -0,0 +1,60 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { aliases } from './agent-table.mjs';
3
+
4
+ const booleans = new Set(['json', 'wait', 'publish', 'help']);
5
+ const numbers = new Set(['timeout', 'interval']);
6
+ export class Usage extends Error {}
7
+
8
+ const snake = flag => (aliases[flag] ?? flag).replaceAll('-', '_');
9
+ // A value that starts like JSON is sent as JSON; @FILE reads a JSON (or text) file. Anything else is text.
10
+ async function value(flag, text) {
11
+ let source = text;
12
+ if (text.startsWith('@')) {
13
+ try { source = (await readFile(text.slice(1), 'utf8')).trim(); } catch { throw new Usage(`Could not read ${text.slice(1)} for --${flag}.`); }
14
+ if (!/^[[{]/.test(source)) return source;
15
+ }
16
+ if (!/^[[{]/.test(source)) return source;
17
+ try { return JSON.parse(source); } catch { throw new Usage(`--${flag} is not valid JSON.`); }
18
+ }
19
+
20
+ /** Flags and bare words to { arguments, control, positional }. Flags become arguments (kebab-case to snake_case); --json,
21
+ * --wait, --publish, --timeout SECONDS and --interval SECONDS steer rer itself; --args JSON adds a whole arguments object. */
22
+ export async function parseArguments(args) {
23
+ const control = {}, named = {}, words = [];
24
+ for (let index = 0; index < args.length; index++) {
25
+ const token = args[index];
26
+ if (token === '-h') { control.help = true; continue; }
27
+ if (!token.startsWith('--') || token === '--') { words.push(token); continue; }
28
+ const [flag, inline] = token.slice(2).split(/=(.*)/s, 2);
29
+ if (!/^[a-z][a-z0-9-]{0,40}$/.test(flag)) throw new Usage(`Unknown flag ${token.slice(0, 40)}.`);
30
+ if (booleans.has(flag)) { control[flag] = true; continue; }
31
+ const text = inline ?? args[++index];
32
+ if (text === undefined || inline === undefined && text.startsWith('--')) throw new Usage(`A value is required for --${flag}.`);
33
+ const target = numbers.has(flag) ? control : named;
34
+ const key = numbers.has(flag) ? flag : snake(flag);
35
+ if (Object.hasOwn(target, key)) throw new Usage(`Repeated flag --${flag}.`);
36
+ if (numbers.has(flag)) {
37
+ const number = Number(text);
38
+ if (!Number.isFinite(number) || number <= 0 || number > 86400) throw new Usage(`--${flag} takes a number of seconds.`);
39
+ control[flag] = number;
40
+ } else named[key] = await value(flag, text);
41
+ }
42
+ const { args: whole, ...rest } = named;
43
+ if (whole !== undefined && (whole === null || typeof whole !== 'object' || Array.isArray(whole))) throw new Usage('--args takes a JSON object.');
44
+ for (const key of Object.keys(whole ?? {})) if (Object.hasOwn(rest, key)) throw new Usage(`${key} is given both as a flag and in --args.`);
45
+ return { arguments: { ...whole, ...rest }, control, words };
46
+ }
47
+
48
+ /** Put the bare words into the row's positional argument: free text for a sentence, exactly one word for an identifier. */
49
+ export function place(row, parsed) {
50
+ const { words } = parsed, into = row.positional;
51
+ if (!words.length) return parsed.arguments;
52
+ if (!into) throw new Usage(`Unexpected word "${words[0].slice(0, 40)}". Pass values as --flag VALUE.`);
53
+ if (Object.hasOwn(parsed.arguments, into)) throw new Usage(`${into} is given both as a flag and as words.`);
54
+ if (into !== 'intent' && words.length > 1) throw new Usage(`Expected one ${into.replaceAll('_', '-')}, got ${words.length} words.`);
55
+ return { ...parsed.arguments, [into]: words.join(' ') };
56
+ }
57
+
58
+ export function missing(row, argumentsObject) {
59
+ return (row.required ?? []).filter(name => argumentsObject[name] === undefined);
60
+ }
@@ -0,0 +1,53 @@
1
+ import { rows, families } from './agent-table.mjs';
2
+
3
+ const verb = name => name.split(' ')[1];
4
+ const exits = `Exits 0 done, 1 refused or failed (the server's message is printed), 2 usage, 3 not built yet, 75 still working when\n--timeout ran out. A verb the owner has not granted this computer names where the owner grants it: Business, under Computers.`;
5
+ const flags = `
6
+ --app ID, --installation-id ID The installed app (from rer business installations list)
7
+ --FLAG VALUE Any other flag is an argument of the tool: --change-id, --preparation-id,
8
+ --domain-id, --request-key, --method, --surface, --hostname, --public-path
9
+ (kebab-case becomes snake_case). A value that starts with { or [ is JSON;
10
+ @FILE reads a file. --args JSON gives the whole arguments object
11
+ --json Print the tool's structuredContent as JSON (progress goes to stderr)
12
+ --wait, --timeout SECONDS, --interval SECONDS
13
+ Follow to the end where the verb supports it (default 1800 s, polling every 15 s)
14
+ ${exits}`;
15
+
16
+ /** The lines the advanced-commands help adds for the agent verbs. */
17
+ export const agentUsage = `
18
+ Agent verbs (Usage: rer business FAMILY VERB [--flags] [--json])
19
+ Act on the company's installed apps from this computer, with no browser. Needs rer business connect first.
20
+ ${Object.entries(rows).map(([name, row]) => ` ${name.padEnd(24)} ${row.about}`).join('\n')}
21
+ tools List the tools the Business server offers
22
+ call TOOL [--flags] Call a tool that has no verb of its own yet
23
+ mcp A local stdio MCP server for Claude Code or Codex: add \`rer business mcp\` as a server
24
+ and the agent never handles a token
25
+ change request --app ID "WHAT TO CHANGE" [--wait] [--publish]
26
+ --wait follows the change to its preview; --publish also publishes it and waits for live
27
+ ${exits}
28
+ `;
29
+
30
+ const family = name => Object.entries(rows).filter(([key]) => key.split(' ')[0] === name)
31
+ .map(([key, row]) => ` ${verb(key).padEnd(22)} ${row.about}`).join('\n');
32
+ const help = name => `Usage: rer business ${name} VERB [--flags] [--json]
33
+ ${family(name)}
34
+ ${flags}
35
+ `;
36
+
37
+ export const agentHelp = {
38
+ ...Object.fromEntries(families.map(name => [name, help(name)])),
39
+ tools: `Usage: rer business tools [--json]
40
+ List the tools the Business server offers: name and a one-line description. Use rer business call TOOL to call one that has no verb.
41
+ `,
42
+ call: `Usage: rer business call TOOL [--flag VALUE ...] [--args JSON] [--json]
43
+ Call any Business tool by name, such as installation.status. Flags become the tool's arguments (kebab-case to snake_case).
44
+ Exits 0 done, 1 refused or failed, 3 not built yet.
45
+ `,
46
+ mcp: `Usage: rer business mcp
47
+ Run a local MCP server on stdin and stdout (newline-delimited JSON-RPC, revision 2025-11-25) that forwards to the Business
48
+ MCP. It keeps the short-lived bearer fresh from this computer's pairing, so the agent that starts it never handles a token.
49
+ Claude Code: claude mcp add business -- rer business mcp
50
+ Codex: add [mcp_servers.business] with command = "rer" and args = ["business", "mcp"]
51
+ Needs rer business connect first. Only protocol messages go to stdout; diagnostics go to stderr.
52
+ `,
53
+ };
@@ -0,0 +1,38 @@
1
+ import { redact } from './errors.mjs';
2
+
3
+ const scalar = value => value === null || ['string', 'number', 'boolean'].includes(typeof value);
4
+ export const clean = (value, limit = 300) => redact(typeof value === 'string' ? value : JSON.stringify(value)).replace(/\s+/g, ' ').trim().slice(0, limit);
5
+
6
+ // One plain line for an object: its scalar fields as key=value, nested values as compact JSON.
7
+ function item(object) {
8
+ if (scalar(object)) return clean(object);
9
+ return Object.entries(object).filter(([, value]) => value !== null && value !== undefined).map(([key, value]) => `${key}=${clean(value, 120)}`).join(' ');
10
+ }
11
+
12
+ /** A tool result as a few plain lines. */
13
+ export function plain(tool, data) {
14
+ if (tool === 'installations.list' && Array.isArray(data.installations)) {
15
+ if (!data.installations.length) return ['No apps are installed for this company yet.'];
16
+ return data.installations.map(app => [app.installation_id, app.app, app.name, app.state, app.version, app.app_url].filter(part => part !== undefined && part !== null).map(part => clean(part, 120)).join(' '));
17
+ }
18
+ const lines = [];
19
+ for (const [key, value] of Object.entries(data)) {
20
+ if (value === null || value === undefined) continue;
21
+ if (Array.isArray(value)) { lines.push(`${key}: ${value.length ? '' : 'none'}`.trimEnd(), ...value.map(entry => ` - ${item(entry)}`)); }
22
+ else if (scalar(value)) lines.push(`${key}: ${clean(value)}`);
23
+ else lines.push(`${key}: ${item(value)}`);
24
+ }
25
+ return lines.length ? lines : ['Done.'];
26
+ }
27
+
28
+ /** Why a tool refused, in words the person reading an agent's transcript can act on. */
29
+ export function refusalText(data, ownerPage) {
30
+ const message = typeof data?.message === 'string' && data.message ? clean(data.message, 500) : null;
31
+ if (data?.status === 'not_built') return `Not built yet: ${message ?? 'Business has not built this yet.'}`;
32
+ if (data?.status === 'action_not_granted') {
33
+ const action = typeof data.action === 'string' ? clean(data.action, 80) : 'this action';
34
+ return `The owner has not let this computer do "${action}". The owner grants it in Business, under Computers: ${ownerPage}`;
35
+ }
36
+ const code = typeof data?.code === 'string' ? ` (${clean(data.code, 80)})` : '';
37
+ return `Business refused: ${message ?? data?.status ?? 'no reason given'}${code}`;
38
+ }
@@ -0,0 +1,32 @@
1
+ // The agent verbs: `rer business FAMILY VERB` is one row here. A row names the Business MCP tool it calls, the argument a bare
2
+ // word fills (positional), the arguments the call needs (required) and whether --wait follows it to its end (wait). A new
3
+ // tool needs one row; `rer business call TOOL --flag value` reaches a tool that has none yet.
4
+ export const rows = {
5
+ 'installations list': { tool: 'installations.list', about: 'The apps installed for this company, with their state and address' },
6
+ 'installation status': { tool: 'installation.status', positional: 'installation_id', required: ['installation_id'], about: 'One installed app: state, version, hosting, progress' },
7
+ 'change request': { tool: 'change.request', positional: 'intent', required: ['installation_id', 'intent'], wait: 'change', about: 'Ask for a change to an app, in plain words' },
8
+ 'change follow': { tool: 'change.follow', positional: 'change_id', required: ['change_id'], wait: 'change', about: 'Where a requested change is, and what happens next' },
9
+ 'change publish': { tool: 'change.publish', positional: 'change_id', required: ['change_id'], about: 'Publish a change whose preview is ready' },
10
+ 'update list': { tool: 'update.list', positional: 'installation_id', required: ['installation_id'], about: 'Updates available for an app' },
11
+ 'update prepare': { tool: 'update.prepare', positional: 'installation_id', required: ['installation_id'], about: 'Prepare the app for its next update' },
12
+ 'update build': { tool: 'update.build', positional: 'installation_id', required: ['installation_id', 'preparation_id'], about: 'Build a prepared update' },
13
+ 'update follow': { tool: 'update.follow', positional: 'installation_id', required: ['installation_id'], wait: 'update', about: 'Where an update is' },
14
+ 'domain set': { tool: 'domain.set', positional: 'domain', required: ['domain'], about: "Set the company's domain" },
15
+ 'domain prove': { tool: 'domain.prove', required: ['method'], about: 'Prove the domain: --method txt|cloudflare' },
16
+ 'domain attach': { tool: 'domain.attach', positional: 'hostname', required: ['installation_id', 'surface', 'hostname'], about: 'Give an app surface a hostname (--public-path optional)' },
17
+ 'domain records': { tool: 'domain.records', positional: 'installation_id', required: ['installation_id'], about: 'The DNS records an app needs' },
18
+ 'domain check': { tool: 'domain.check', required: ['installation_id', 'domain_id'], about: 'Check that a domain is attached and answering' },
19
+ 'domain remove': { tool: 'domain.remove', required: ['installation_id', 'domain_id'], about: 'Detach a domain from an app' },
20
+ 'import start': { tool: 'import.start', positional: 'installation_id', required: ['installation_id'], about: "Start moving an old tool's data into an app" },
21
+ 'import follow': { tool: 'import.follow', positional: 'installation_id', required: ['installation_id'], about: 'Where an import is' },
22
+ 'profile set': { tool: 'business.profile.set', required: ['profile'], about: 'Save the business profile: --profile JSON or --profile @FILE' },
23
+ 'plan draft': { tool: 'plan.draft', about: 'Draft the plan: --FIELD VALUE, or --args JSON' },
24
+ 'plan read': { tool: 'plan.read', about: 'Read the plan' },
25
+ 'plan request-approval': { tool: 'plan.request_approval', about: 'Ask the owner to approve the plan' },
26
+ 'app owner-signed-in': { tool: 'app.owner_signed_in', positional: 'installation_id', required: ['installation_id'], about: 'Has the owner signed in to the app yet' },
27
+ 'app send-sign-in-link': { tool: 'app.send_sign_in_link', positional: 'installation_id', required: ['installation_id'], about: 'Email the owner a sign-in link to the app' },
28
+ };
29
+ // Short flag names for argument names, so `--app ID` is `--installation-id ID`.
30
+ export const aliases = { app: 'installation_id' };
31
+ export const families = [...new Set(Object.keys(rows).map(name => name.split(' ')[0]))];
32
+ export const agentFamilies = new Set([...families, 'tools', 'mcp', 'call']);
@@ -0,0 +1,132 @@
1
+ import { Api } from './api.mjs';
2
+ import { mcpClient, ownerLink } from './questions.mjs';
3
+ import { paired } from './local-commands.mjs';
4
+ import { describe } from './errors.mjs';
5
+ import { businessCommand } from './invocation.mjs';
6
+ import { rows } from './agent-table.mjs';
7
+ import { parseArguments, place, missing, Usage } from './agent-args.mjs';
8
+ import { plain, refusalText, clean } from './agent-output.mjs';
9
+ import { waitFor, failedState, stateName, exitStillWaiting } from './agent-wait.mjs';
10
+ import { agentUsage } from './agent-help.mjs';
11
+
12
+ export const exitNotBuilt = 3;
13
+
14
+ class Refused extends Error {
15
+ constructor(data) { super(data?.message ?? 'Business refused the action.'); this.data = data; }
16
+ }
17
+
18
+ // A tool's structuredContent, or the refusal it came back with.
19
+ async function invoke(session, tool, args) {
20
+ const result = await session.call(tool, args);
21
+ if (result?.isError) throw new Refused(result.structuredContent ?? { status: 'refused', message: result.content?.find?.(part => part?.type === 'text')?.text });
22
+ if (!result?.structuredContent || typeof result.structuredContent !== 'object') throw Error(`Business returned no result for ${tool}.`);
23
+ return result.structuredContent;
24
+ }
25
+
26
+ const idOf = (data, key) => data[key]?.id ?? data[`${key}_id`];
27
+
28
+ async function change(row, args, control, session, say) {
29
+ let data = await invoke(session, row.tool, args);
30
+ const id = idOf(data, 'change') ?? args.change_id;
31
+ if (typeof id === 'string') say(`Change ${clean(id, 80)}: ${clean(stateName(data) ?? 'requested', 60)}`);
32
+ if (!control.wait && !control.publish) {
33
+ if (row.tool === 'change.request' && typeof id === 'string') say(`Follow it with: ${businessCommand(`change follow ${id} --wait`)}`);
34
+ return data;
35
+ }
36
+ if (typeof id !== 'string') throw Error('Business did not name the change, so there is nothing to follow.');
37
+ const options = { say: state => say(`Change ${id}: ${state}`), timeout: control.timeout, interval: control.interval, from: stateName(data) };
38
+ const follow = () => invoke(session, 'change.follow', { change_id: id });
39
+ let waited = await waitFor(follow, options);
40
+ if (waited.ended && control.publish && !failedState(waited.data) && waited.data.next === 'publish') {
41
+ const published = await invoke(session, 'change.publish', { change_id: id });
42
+ say(`Change ${id}: ${stateName(published) ?? 'publishing'}`);
43
+ waited = await waitFor(follow, { ...options, publishing: true, from: stateName(published) ?? 'publishing' });
44
+ }
45
+ data = waited.data;
46
+ if (!waited.ended) throw Object.assign(Error(`Still working after ${control.timeout ?? 1800} seconds. Keep waiting with: ${businessCommand(`change follow ${id} --wait`)}`), { exitCode: exitStillWaiting, data });
47
+ if (failedState(data)) throw Object.assign(Error(`The change ${stateName(data)}: ${clean(data.change?.message ?? data.message ?? 'no reason given', 300)}`), { exitCode: 1, data });
48
+ if (data.next === 'ask_owner') say('The owner needs to answer something in Business before this can go on.');
49
+ else if (data.next === 'publish') say(`Its preview is ready. Publish it with: ${businessCommand(`change publish ${id}`)}`);
50
+ return data;
51
+ }
52
+
53
+ async function update(row, args, control, session, say) {
54
+ const data = await invoke(session, row.tool, args);
55
+ if (!control.wait) return data;
56
+ const waited = await waitFor(() => invoke(session, 'update.follow', args), { say: state => say(`Update ${args.installation_id}: ${state}`), timeout: control.timeout, interval: control.interval });
57
+ if (!waited.ended) throw Object.assign(Error(`Still working after ${control.timeout ?? 1800} seconds. Keep waiting with: ${businessCommand(`update follow ${args.installation_id} --wait`)}`), { exitCode: exitStillWaiting, data: waited.data });
58
+ if (failedState(waited.data)) throw Object.assign(Error(`The update ${stateName(waited.data)}.`), { exitCode: 1, data: waited.data });
59
+ return waited.data;
60
+ }
61
+ const waiters = { change, update };
62
+
63
+ async function work(row, parsed, session, out) {
64
+ const args = place(row, parsed), absent = missing(row, args), { control } = parsed;
65
+ if (absent.length) throw new Usage(`${row.tool} needs ${absent.map(name => `--${name.replaceAll('_', '-')}`).join(', ')}. Run rer business ${row.name.split(' ')[0]} --help.`);
66
+ for (const flag of ['wait', 'publish']) {
67
+ if (control[flag] && !(row.wait && (flag === 'wait' || row.tool.startsWith('change.')))) throw new Usage(`${row.name} does not take --${flag}.`);
68
+ }
69
+ const say = line => out.line(line);
70
+ out.result(row.tool, row.wait ? await waiters[row.wait](row, args, control, session, say) : await invoke(session, row.tool, args));
71
+ }
72
+
73
+ // Lines for a person go to stdout; with --json only the final structuredContent does, and progress goes to stderr.
74
+ function output(json) {
75
+ return {
76
+ line: text => (json ? process.stderr : process.stdout).write(text + '\n'),
77
+ result: (tool, data) => { if (json) process.stdout.write(JSON.stringify(data) + '\n'); else for (const line of plain(tool, data)) process.stdout.write(line + '\n'); },
78
+ };
79
+ }
80
+
81
+ async function listTools(session, json) {
82
+ const tools = [];
83
+ let cursor;
84
+ for (let page = 0; page < 20; page++) {
85
+ const response = await session.exchange('tools/list', cursor ? { cursor } : {});
86
+ if (response.error) throw Error('Business MCP refused tools/list.');
87
+ tools.push(...(Array.isArray(response.result?.tools) ? response.result.tools : []));
88
+ cursor = response.result?.nextCursor;
89
+ if (!cursor) break;
90
+ }
91
+ if (json) process.stdout.write(JSON.stringify({ tools }) + '\n');
92
+ else for (const tool of tools) process.stdout.write(`${clean(tool.name, 80)} ${clean(String(tool.description ?? '').split('\n')[0], 160)}`.trimEnd() + '\n');
93
+ }
94
+
95
+ function usage(text) { process.stderr.write(`${text}\n${agentUsage}`); return 2; }
96
+
97
+ export async function agentCommand(argv) {
98
+ const [first, second, ...rest] = argv;
99
+ if (first === 'mcp') return (await import('./mcp-bridge.mjs')).bridge();
100
+ let row, tail = rest;
101
+ if (first === 'tools') { row = { name: 'tools' }; tail = [second, ...rest].filter(item => item !== undefined); }
102
+ else if (first === 'call') {
103
+ if (!/^[a-z][a-z0-9_.]{0,80}$/.test(second ?? '')) return usage('Name the tool: rer business call TOOL [--flag VALUE].');
104
+ row = { name: `call ${second}`, tool: second };
105
+ } else {
106
+ row = rows[`${first} ${second}`] && { name: `${first} ${second}`, ...rows[`${first} ${second}`] };
107
+ if (!row) return usage(`Unknown command: rer business ${first}${second ? ` ${clean(second, 40)}` : ''}.`);
108
+ }
109
+ let parsed;
110
+ try { parsed = await parseArguments(tail); } catch (error) { if (error instanceof Usage) return usage(error.message); throw error; }
111
+ const out = output(parsed.control.json);
112
+ let state;
113
+ try {
114
+ const connection = await paired();
115
+ state = connection.state;
116
+ const session = await mcpClient(new Api(state.origin, connection.credential));
117
+ if (row.name === 'tools') await listTools(session, parsed.control.json);
118
+ else await work(row, parsed, session, out);
119
+ return 0;
120
+ } catch (error) {
121
+ if (error instanceof Usage) return usage(error.message);
122
+ if (error instanceof Refused) {
123
+ const text = refusalText(error.data, ownerLink(state));
124
+ if (parsed.control.json) process.stdout.write(JSON.stringify(error.data ?? {}) + '\n');
125
+ process.stderr.write(text + '\n');
126
+ return error.data?.status === 'not_built' ? exitNotBuilt : 1;
127
+ }
128
+ if (error.data && parsed.control.json) process.stdout.write(JSON.stringify(error.data) + '\n');
129
+ process.stderr.write(describe(error) + '\n');
130
+ return error.exitCode ?? 1;
131
+ }
132
+ }
@@ -0,0 +1,28 @@
1
+ import { pause } from './api.mjs';
2
+ import { clean } from './agent-output.mjs';
3
+
4
+ export const exitStillWaiting = 75;
5
+ // What a follow result says. A change or an update is `{change|update: {state, ...}, next}`; next tells the agent what to do.
6
+ const stateOf = data => data.change?.state ?? data.update?.state ?? data.import?.state ?? data.state;
7
+ const finished = new Set(['live', 'failed', 'refused', 'done']);
8
+ const stops = new Set(['publish', 'done', 'ask_owner']);
9
+
10
+ /** Poll `follow()` every interval until the work ends or the timeout passes, saying each state change through `say`.
11
+ * `publishing` waits through next=publish (a publish just made is not done yet): only live, done, ask_owner, failed or
12
+ * refused end it. Returns { data, ended }; ended is false when the timeout ran out first. */
13
+ export async function waitFor(follow, { say, timeout = 1800, interval = 15, publishing = false, from }) {
14
+ const deadline = Date.now() + timeout * 1000;
15
+ let last = from, data;
16
+ for (;;) {
17
+ data = await follow();
18
+ const state = stateOf(data), next = data.next;
19
+ if (state !== last) say(`${clean(state ?? 'unknown', 60)}${typeof data.change?.title === 'string' ? ` (${clean(data.change.title, 100)})` : ''}`);
20
+ last = state;
21
+ const over = finished.has(state) || next === 'ask_owner' || next === 'done' || !publishing && stops.has(next) || state === undefined && next === undefined;
22
+ if (over) return { data, ended: true };
23
+ if (Date.now() + interval * 1000 > deadline) return { data, ended: false };
24
+ await pause(interval * 1000);
25
+ }
26
+ }
27
+ export const failedState = data => ['failed', 'refused'].includes(stateOf(data));
28
+ export const stateName = stateOf;
@@ -7,6 +7,8 @@ import { run } from './supervisor.mjs';
7
7
  import { describe } from './errors.mjs';
8
8
  import { identifier, originUrl } from './api.mjs';
9
9
  import { appAddress, appSignInHelp } from '../app-address.mjs';
10
+ import { agentUsage, agentHelp } from './agent-help.mjs';
11
+ import { agentFamilies } from './agent-table.mjs';
10
12
 
11
13
  const usage = `Set up your business: rer business connect --business ID
12
14
  The Business Connect page names the ID.
@@ -21,6 +23,9 @@ Advanced commands (Usage: rer business VERB)
21
23
  connect --business ID [--origin URL] [--timeout SECONDS]
22
24
  Print a code and link for the owner to approve in a signed-in browser
23
25
  Connect carries the Business name into local apps
26
+ run --grant G -- <command> [args...]
27
+ Run a command with an approved scoped cloud credential; revoked after
28
+ cleanup LEASE [--status] Retry cleanup or read its safe status
24
29
  run [--once] Work this computer's tasks: the folder scan the owner allows. Says what
25
30
  it is doing and what it waits for; applies the owner's choices at each
26
31
  check-in
@@ -37,10 +42,11 @@ Advanced commands (Usage: rer business VERB)
37
42
  inside an agent sandbox it names the one command that finishes
38
43
  State lives in $RER_BUSINESS_STATE_DIR when set, otherwise in ~/.rer/business.
39
44
  In an agent sandbox that writes only inside its working folder, use RER_BUSINESS_STATE_DIR="$PWD/.rer-business".
40
- ${appSignInHelp}
45
+ ${agentUsage}${appSignInHelp}
41
46
  `;
42
47
 
43
48
  const verbHelp = {
49
+ ...agentHelp,
44
50
  setup: `Usage: rer business setup --origin URL --session-file FILE --confirm-demo [--hosting managed|assisted|self_host] [--json]
45
51
  Create the Business for the synthetic demo company in setup-company.json and save
46
52
  its profile, through the platform's owner routes. A repeat reuses that Business and
@@ -58,7 +64,12 @@ changes nothing when its profile already matches. It provisions no seeds.
58
64
  Exits 0 when the Business exists with that profile; 1 with a named {code} on stderr.
59
65
  ${appSignInHelp}
60
66
  `,
61
- run: `Usage: rer business run [--once]
67
+ run: `Usage: rer business run --grant G -- <command> [args...]
68
+ Run any software command under this paired agent’s explicit deploy action and grant.
69
+ The scoped Cloudflare token and account reach only the child environment. Output
70
+ is masked and cleanup is reported separately; the child’s exit status is kept.
71
+
72
+ Usage: rer business run [--once]
62
73
  Work this computer's tasks (the folder scan the owner allows) and check in every
63
74
  25 seconds until stopped. Steps for this computer's agent, such as a seed's Move in,
64
75
  are shown by rer business next. --once returns after one check-in.
@@ -82,8 +93,13 @@ Requires an existing pairing: rer business connect --business ID (the Connect pa
82
93
  };
83
94
 
84
95
  export async function businessCommand(argv) {
96
+ if (argv[0] === 'run' && argv[1] === '--grant' || argv[0] === 'cleanup') {
97
+ try { const commands = await import('./run-grant.mjs'); return await (argv[0] === 'cleanup' ? commands.cleanupCommand(argv.slice(1)) : commands.grantCommand(argv.slice(1))); }
98
+ catch (error) { process.stderr.write(describe(error) + '\n'); return 1; }
99
+ }
85
100
  if (Object.hasOwn(verbHelp, argv[0]) && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(verbHelp[argv[0]]); return 0; }
86
101
  if (argv[0] === 'setup') return setupCommand(argv.slice(1));
102
+ if (agentFamilies.has(argv[0])) return (await import('./agent-verbs.mjs')).agentCommand(argv);
87
103
  if (!argv.length || argv[0] !== 'scan' && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(usage); return 0; }
88
104
  if (argv[0] === 'scan') return scanCommand(argv);
89
105
  try {