@runeditrun/rer 0.2.119 → 0.2.120
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 +40 -0
- package/cli/business/agent-args.mjs +60 -0
- package/cli/business/agent-help.mjs +53 -0
- package/cli/business/agent-output.mjs +38 -0
- package/cli/business/agent-table.mjs +32 -0
- package/cli/business/agent-verbs.mjs +132 -0
- package/cli/business/agent-wait.mjs +28 -0
- package/cli/business/command.mjs +18 -2
- package/cli/business/mcp-bridge.mjs +58 -0
- package/cli/business/questions.mjs +32 -9
- package/cli/business/run-child.mjs +42 -0
- package/cli/business/run-grant.mjs +65 -0
- package/cli/business/run-mask.mjs +21 -0
- package/global/CHANGELOG.md +15 -0
- package/package.json +1 -1
package/cli/README.md
CHANGED
|
@@ -697,3 +697,43 @@ unattempted sizes `complete:false`; these files keep the existing statement name
|
|
|
697
697
|
SQL and bound parameters and carry diagnostic flow summaries. Missing work never
|
|
698
698
|
produces a passing growth verdict. See the size section of
|
|
699
699
|
[the command contract](../export/SEED-COMMAND-CONTRACT.md#statement-size-and-growth-sc-15).
|
|
700
|
+
|
|
701
|
+
## Run a command with a Business grant
|
|
702
|
+
|
|
703
|
+
Pair with the Business using `rer business connect --business ID`. The owner
|
|
704
|
+
approves this agent, ticks **Run software commands with an approved cloud grant**,
|
|
705
|
+
Connects Cloudflare, selects the exact Business account and approves a per-agent
|
|
706
|
+
grant with explicit resource permissions and expiry. These choices install nothing.
|
|
707
|
+
|
|
708
|
+
```sh
|
|
709
|
+
rer business run --grant GRANT_ID -- rer deploy
|
|
710
|
+
rer business run --grant GRANT_ID -- any-command 'argument with spaces'
|
|
711
|
+
```
|
|
712
|
+
|
|
713
|
+
`cloudflare.token` in the Business MCP describes the exchange without returning a
|
|
714
|
+
credential. Only the paired rer exchange receives a child token; the parent OAuth
|
|
715
|
+
credential stays on the trusted server. The command gets `CLOUDFLARE_API_TOKEN`
|
|
716
|
+
and `CLOUDFLARE_ACCOUNT_ID` in its environment. Cloudflare credential aliases from
|
|
717
|
+
the caller environment are removed. No shell is inserted and arguments after
|
|
718
|
+
`--`, including help flags, are passed unchanged. Existing `run [--once]` continues
|
|
719
|
+
its computer check-in behavior.
|
|
720
|
+
|
|
721
|
+
This is an environment boundary, not a sandbox. The selected process and its
|
|
722
|
+
descendants can read and use the credential, and a malicious process can disclose
|
|
723
|
+
it or read other files or OS credentials available to the same user. Use software
|
|
724
|
+
you trust. Output masks the credential and common encoded forms across chunk
|
|
725
|
+
boundaries; it cannot hide every transformation a malicious process invents.
|
|
726
|
+
Commands may load their own files and credentials. The wrapper supplies only the
|
|
727
|
+
approved credential, never retries with broader or ambient access, and does not
|
|
728
|
+
protect a process from its own deliberate credential loading.
|
|
729
|
+
|
|
730
|
+
The child expires after at most 15 minutes, bounded also by the grant and the
|
|
731
|
+
provider authorization. The wrapper interrupts a command at that expiry. It
|
|
732
|
+
requests revocation after success, failure, signals or spawn failure; SIGKILL,
|
|
733
|
+
crashes, network loss and lost acknowledgements may leave a token until server
|
|
734
|
+
expiry. Child exit codes and Unix terminating signals are preserved. Cleanup has
|
|
735
|
+
its own stderr status, including **unconfirmed**, which is never called revoked.
|
|
736
|
+
The safe lease ID in that status supports `rer business cleanup LEASE` to retry
|
|
737
|
+
revocation and `rer business cleanup LEASE --status` to read its status. Cleanup
|
|
738
|
+
needs the original pairing, but does not require the removed deploy action or an
|
|
739
|
+
active grant. No child token is saved in state, OS storage, logs or MCP output.
|
|
@@ -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;
|
package/cli/business/command.mjs
CHANGED
|
@@ -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 [
|
|
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 {
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createInterface } from 'node:readline';
|
|
2
|
+
import { Api } from './api.mjs';
|
|
3
|
+
import { mcpClient } from './questions.mjs';
|
|
4
|
+
import { paired } from './local-commands.mjs';
|
|
5
|
+
import { describe } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const protocolVersion = '2025-11-25';
|
|
8
|
+
const forwarded = /^(tools|resources|prompts|completion|logging)\//;
|
|
9
|
+
|
|
10
|
+
/** A local stdio MCP server for an agent (Claude Code, Codex): newline-delimited JSON-RPC in, the same out. Calls go to the
|
|
11
|
+
* Business MCP with a bearer minted from this computer's pairing and minted again when it nears expiry or is refused, so the
|
|
12
|
+
* agent never holds a token. Only protocol messages are written to stdout; everything else goes to stderr. */
|
|
13
|
+
export async function bridge({ input = process.stdin, output = process.stdout, errors = process.stderr } = {}) {
|
|
14
|
+
let session;
|
|
15
|
+
const connection = () => session ??= (async () => {
|
|
16
|
+
const { state, credential } = await paired();
|
|
17
|
+
return mcpClient(new Api(state.origin, credential));
|
|
18
|
+
})().catch(error => { session = undefined; throw error; });
|
|
19
|
+
const send = message => output.write(JSON.stringify({ jsonrpc: '2.0', ...message }) + '\n');
|
|
20
|
+
const fail = (id, code, text) => send({ id, error: { code, message: text } });
|
|
21
|
+
|
|
22
|
+
async function handle(message) {
|
|
23
|
+
const { id, method, params } = message;
|
|
24
|
+
if (typeof method !== 'string') return;
|
|
25
|
+
if (id === undefined || id === null) return; // A notification needs no answer.
|
|
26
|
+
try {
|
|
27
|
+
if (method === 'ping') return send({ id, result: {} });
|
|
28
|
+
const upstream = await connection();
|
|
29
|
+
if (method === 'initialize') {
|
|
30
|
+
const { capabilities, instructions } = upstream.initialized;
|
|
31
|
+
return send({ id, result: { protocolVersion, capabilities: capabilities ?? {}, serverInfo: { name: 'rer-business', version: '1.0.0' }, ...(typeof instructions === 'string' ? { instructions } : {}) } });
|
|
32
|
+
}
|
|
33
|
+
if (!forwarded.test(method)) return fail(id, -32601, `Method not found: ${method.slice(0, 80)}`);
|
|
34
|
+
const response = await upstream.exchange(method, params ?? {});
|
|
35
|
+
if (response.error) {
|
|
36
|
+
const { code, message: text, data } = response.error;
|
|
37
|
+
return send({ id, error: { code: Number.isInteger(code) ? code : -32000, message: describe(Error(String(text ?? 'Business refused the request.'))), ...(data !== undefined ? { data } : {}) } });
|
|
38
|
+
}
|
|
39
|
+
send({ id, result: response.result });
|
|
40
|
+
} catch (error) {
|
|
41
|
+
errors.write(describe(error) + '\n');
|
|
42
|
+
fail(id, -32000, describe(error));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const pending = new Set();
|
|
47
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
48
|
+
for await (const line of lines) {
|
|
49
|
+
if (!line.trim()) continue;
|
|
50
|
+
let message;
|
|
51
|
+
try { message = JSON.parse(line); } catch { fail(null, -32700, 'Parse error'); continue; }
|
|
52
|
+
if (message === null || typeof message !== 'object' || Array.isArray(message)) { fail(null, -32600, 'Invalid request'); continue; }
|
|
53
|
+
const work = handle(message).finally(() => pending.delete(work));
|
|
54
|
+
pending.add(work);
|
|
55
|
+
}
|
|
56
|
+
await Promise.all(pending);
|
|
57
|
+
return 0;
|
|
58
|
+
}
|
|
@@ -9,24 +9,47 @@ const protocolVersion = '2025-11-25';
|
|
|
9
9
|
const headers = { Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': protocolVersion };
|
|
10
10
|
export const classifications = ['uses', 'sells', 'both', 'product-dependency'];
|
|
11
11
|
|
|
12
|
+
/** One MCP session on the Business server. The returned function calls a tool and returns its structuredContent (it throws when
|
|
13
|
+
* the tool refuses); `.call` returns the raw tool result, `.exchange` the raw JSON-RPC response for any method, `.initialized` the
|
|
14
|
+
* server's initialize result. The short-lived bearer is minted again within 30 seconds of expiry, and once on a 401. */
|
|
12
15
|
export async function mcpClient(api, { taskId, signal } = {}) {
|
|
13
|
-
|
|
14
|
-
const
|
|
16
|
+
let minted = await api.mintToken('mcp', { taskId, signal });
|
|
17
|
+
const remint = async () => { minted = await api.mintToken('mcp', { taskId, signal }); };
|
|
15
18
|
let sequence = 0;
|
|
19
|
+
async function post(body) {
|
|
20
|
+
if (Date.parse(minted.expires_at) - Date.now() < 30_000) await remint();
|
|
21
|
+
const send = () => api.post('/api/business/mcp', body, { token: minted.access_token, signal, headers });
|
|
22
|
+
try { return await send(); } catch (error) {
|
|
23
|
+
if (error.status !== 401) throw error;
|
|
24
|
+
await remint();
|
|
25
|
+
return send();
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
async function exchange(method, params, notification = false) {
|
|
29
|
+
const id = ++sequence;
|
|
30
|
+
const result = await post({ jsonrpc: '2.0', ...(!notification ? { id } : {}), method, params });
|
|
31
|
+
if (notification) return null;
|
|
32
|
+
if (!result || result.id !== id || !result.error === !result.result) throw Error('Business MCP operation was refused.');
|
|
33
|
+
return result;
|
|
34
|
+
}
|
|
16
35
|
async function rpc(method, params, notification = false) {
|
|
17
|
-
const result = await
|
|
18
|
-
if (
|
|
19
|
-
|
|
20
|
-
return result.result;
|
|
36
|
+
const result = await exchange(method, params, notification);
|
|
37
|
+
if (result?.error) throw Error('Business MCP operation was refused.');
|
|
38
|
+
return result?.result;
|
|
21
39
|
}
|
|
22
40
|
const initialized = await rpc('initialize', { protocolVersion, capabilities: {}, clientInfo: { name: 'rer-business', version: '1.0.0' } });
|
|
23
41
|
if (initialized.protocolVersion !== protocolVersion) throw Error('Business MCP protocol revision is unsupported.');
|
|
24
42
|
await rpc('notifications/initialized', {}, true);
|
|
25
|
-
|
|
26
|
-
const
|
|
43
|
+
const call = async (name, args = {}) => {
|
|
44
|
+
const response = await exchange('tools/call', { name, arguments: args });
|
|
45
|
+
if (response.error) throw Error(`Business MCP refused ${name}${typeof response.error.message === 'string' ? `: ${response.error.message.slice(0, 300)}` : ''}.`);
|
|
46
|
+
return response.result;
|
|
47
|
+
};
|
|
48
|
+
return Object.assign(async (name, args = {}) => {
|
|
49
|
+
const result = await call(name, args);
|
|
27
50
|
if (result?.isError || !result?.structuredContent) throw Error('Business task action is unavailable. Use the browser to check its requirements.');
|
|
28
51
|
return result.structuredContent;
|
|
29
|
-
};
|
|
52
|
+
}, { call, exchange, initialized });
|
|
30
53
|
}
|
|
31
54
|
|
|
32
55
|
export async function nextQuestions(api, signal) {
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { constants } from 'node:os';
|
|
3
|
+
import { commandMask } from './run-mask.mjs';
|
|
4
|
+
|
|
5
|
+
export const signalCode = signal => 128 + (constants.signals[signal] ?? 1);
|
|
6
|
+
export function childEnvironment(source, credential, account) {
|
|
7
|
+
const env = Object.fromEntries(Object.entries(source).filter(([key]) => !/^(?:CLOUDFLARE_|CF_|MANAGED_CLOUDFLARE_)/i.test(key)));
|
|
8
|
+
return { ...env, CLOUDFLARE_API_TOKEN: credential, CLOUDFLARE_ACCOUNT_ID: account };
|
|
9
|
+
}
|
|
10
|
+
/** Own one process group, forward interruption, and bound its lifetime to the credential's server expiry. */
|
|
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;
|
|
14
|
+
const stop = reason => {
|
|
15
|
+
stopped ??= reason;
|
|
16
|
+
if (!child?.pid) return;
|
|
17
|
+
const send = sig => { try { if (process.platform === 'win32') child.kill(sig); else process.kill(-child.pid, sig); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
|
|
18
|
+
send(reason);
|
|
19
|
+
escalation ??= setTimeout(() => send('SIGKILL'), 3000);
|
|
20
|
+
};
|
|
21
|
+
const interrupt = () => stop(signal.reason?.signal ?? 'SIGTERM');
|
|
22
|
+
try {
|
|
23
|
+
if (signal?.aborted) return { code: signalCode(signal.reason?.signal ?? 'SIGTERM'), signal: signal.reason?.signal };
|
|
24
|
+
child = spawn(command[0], command.slice(1), { env: childEnvironment(source, lease.credential, lease.account_id),
|
|
25
|
+
stdio: ['inherit', 'pipe', 'pipe'], shell: false, detached: process.platform !== 'win32' });
|
|
26
|
+
child.stdout.on('data', stdout.write); child.stderr.on('data', stderr.write);
|
|
27
|
+
signal?.addEventListener('abort', interrupt, { once: true });
|
|
28
|
+
if (signal?.aborted) interrupt();
|
|
29
|
+
expiry = setTimeout(() => stop('SIGTERM'), Math.max(1, Date.parse(lease.credential_expires_at) - Date.now()));
|
|
30
|
+
const result = await new Promise(resolve => {
|
|
31
|
+
let spawnError;
|
|
32
|
+
child.on('error', error => { spawnError = error; });
|
|
33
|
+
child.on('close', (code, exitSignal) => resolve(spawnError ? { code: spawnError.code === 'ENOENT' ? 127 : 126, spawnError: spawnError.code }
|
|
34
|
+
: { code: code ?? signalCode(exitSignal ?? stopped ?? 'SIGTERM'), signal: exitSignal }));
|
|
35
|
+
});
|
|
36
|
+
if (result.spawnError) errors.write(`Command could not start (${String(result.spawnError).replace(/[^A-Z0-9_]/g, '')}).\n`);
|
|
37
|
+
return result;
|
|
38
|
+
} finally {
|
|
39
|
+
clearTimeout(expiry); clearTimeout(escalation); signal?.removeEventListener('abort', interrupt);
|
|
40
|
+
stdout.end(); stderr.end();
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { Api, identifier } from './api.mjs';
|
|
3
|
+
import { paired } from './local-commands.mjs';
|
|
4
|
+
import { runChild, signalCode } from './run-child.mjs';
|
|
5
|
+
|
|
6
|
+
const route = '/api/business/executors/cloudflare-token';
|
|
7
|
+
const usage = 'Usage: rer business run --grant G -- <command> [args...]\n';
|
|
8
|
+
function validLease(value, state, grant, id) {
|
|
9
|
+
return value?.lease_id === id && value.grant_id === grant && value.business_id === state.businessId && value.executor_id === state.executorId
|
|
10
|
+
&& /^[a-f0-9]{32}$/.test(value.account_id) && typeof value.credential === 'string' && value.credential.length >= 16 && value.credential.length <= 4096
|
|
11
|
+
&& !/[\s\x00-\x1f\x7f]/.test(value.credential) && value.cleanup_status === 'active' && value.provider_credential_revoked === false
|
|
12
|
+
&& Number.isFinite(Date.parse(value.credential_expires_at)) && Date.parse(value.credential_expires_at) > Date.now()
|
|
13
|
+
&& Date.parse(value.credential_expires_at) <= Date.now() + 900_000;
|
|
14
|
+
}
|
|
15
|
+
async function cleanup(api, id) {
|
|
16
|
+
try {
|
|
17
|
+
const value = await api.post(`${route}/${id}/revoke`, {}, { quiet: true, timeout: 15000 });
|
|
18
|
+
if (value?.lease_id === id && ['revoked', 'expired'].includes(value.cleanup_status)
|
|
19
|
+
&& (value.cleanup_status !== 'revoked' || value.provider_credential_revoked === true)) return value.cleanup_status;
|
|
20
|
+
} catch { /* A lost acknowledgement is unconfirmed, never success. */ }
|
|
21
|
+
return 'unconfirmed';
|
|
22
|
+
}
|
|
23
|
+
export async function cleanupCommand(args) {
|
|
24
|
+
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;
|
|
26
|
+
}
|
|
27
|
+
const {state, credential} = await paired(), api = new Api(state.origin, credential), id = args[0];
|
|
28
|
+
try {
|
|
29
|
+
const value = args[1] ? await api.request('GET', `${route}/${id}`, undefined, { quiet: true }) : null;
|
|
30
|
+
const status = args[1] ? value?.lease_id === id && ['issuing','active','revoked','unconfirmed','expired'].includes(value.cleanup_status) ? value.cleanup_status : 'unconfirmed' : await cleanup(api, id);
|
|
31
|
+
process.stderr.write(`Cloud credential cleanup: ${status}. Lease ${id}.\n`);
|
|
32
|
+
return ['revoked','expired'].includes(status) ? 0 : 1;
|
|
33
|
+
} catch { process.stderr.write(`Cloud credential cleanup: unconfirmed. Lease ${id}.\n`); return 1; }
|
|
34
|
+
}
|
|
35
|
+
export async function grantCommand(args) {
|
|
36
|
+
if (args[0] !== '--grant' || !args[1] || args[2] !== '--' || !args[3]) { process.stderr.write(usage); return 2; }
|
|
37
|
+
try { identifier(args[1]); } catch { process.stderr.write(usage); return 2; }
|
|
38
|
+
const {state, credential} = await paired(), api = new Api(state.origin, credential), id = randomUUID();
|
|
39
|
+
const stop = new AbortController(), handlers = new Map();
|
|
40
|
+
for (const signal of ['SIGINT','SIGTERM','SIGHUP']) {
|
|
41
|
+
const handler = () => { if (!stop.signal.aborted) stop.abort({signal}); };
|
|
42
|
+
handlers.set(signal, handler); process.on(signal, handler);
|
|
43
|
+
}
|
|
44
|
+
let lease, code = 1, exitSignal;
|
|
45
|
+
try {
|
|
46
|
+
// 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});
|
|
48
|
+
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});
|
|
50
|
+
code = result.code; exitSignal = result.signal;
|
|
51
|
+
} catch {
|
|
52
|
+
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');
|
|
54
|
+
} finally {
|
|
55
|
+
const status = await cleanup(api, id);
|
|
56
|
+
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`);
|
|
58
|
+
lease = undefined;
|
|
59
|
+
for (const [signal, handler] of handlers) process.removeListener(signal, handler);
|
|
60
|
+
}
|
|
61
|
+
// Keep the child's exit status even if cleanup is unconfirmed; cleanup has its own explicit status above.
|
|
62
|
+
exitSignal ??= stop.signal.reason?.signal;
|
|
63
|
+
if (exitSignal && process.platform !== 'win32') { process.kill(process.pid, exitSignal); await new Promise(resolve => setImmediate(resolve)); }
|
|
64
|
+
return code;
|
|
65
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
2
|
+
|
|
3
|
+
/** Keep a possible credential prefix across writes; neither chunk boundaries nor EOF release it. */
|
|
4
|
+
export function commandMask(values, output) {
|
|
5
|
+
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);
|
|
7
|
+
const decoder = new StringDecoder('utf8');
|
|
8
|
+
let pending = '';
|
|
9
|
+
function replace(text) { for (const secret of secrets) text = text.split(secret).join('[credential]'); return text; }
|
|
10
|
+
function write(chunk) {
|
|
11
|
+
pending = replace(pending + decoder.write(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)));
|
|
12
|
+
let held = 0;
|
|
13
|
+
for (const secret of secrets) for (let count = Math.min(secret.length - 1, pending.length); count > held; count--)
|
|
14
|
+
if (pending.endsWith(secret.slice(0, count))) { held = count; break; }
|
|
15
|
+
const ready = pending.slice(0, pending.length - held);
|
|
16
|
+
pending = pending.slice(pending.length - held);
|
|
17
|
+
if (ready) output.write(ready);
|
|
18
|
+
}
|
|
19
|
+
return { write, end() { pending = replace(pending + decoder.end()); if (pending) output.write('[credential]'); pending = ''; },
|
|
20
|
+
text: replace };
|
|
21
|
+
}
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.120
|
|
4
|
+
|
|
5
|
+
### Commands under an approved Business grant
|
|
6
|
+
|
|
7
|
+
- `rer business run --grant G -- <command> [args...]` exchanges this computer's pairing and explicit grant for a short-lived scoped Cloudflare child credential. It removes inherited Cloudflare credential aliases, passes arguments without a shell and preserves the child's exit code or Unix terminating signal. Existing `run [--once]` check-ins remain available.
|
|
8
|
+
- The wrapper masks the credential and common encoded forms in output, interrupts the command at credential expiry and requests cleanup after completion or interruption. Cleanup reports revoked, expired or unconfirmed separately from the child result; `rer business cleanup LEASE [--status]` retries revocation or reads its status. This environment boundary is not a sandbox: run trusted software, and an unconfirmed cleanup can leave the credential usable until server expiry.
|
|
9
|
+
|
|
10
|
+
### Agent commands and stdio MCP
|
|
11
|
+
|
|
12
|
+
- Paired agents can call Business tools for installed apps, changes, updates, domains, imports, profiles, plans and owner sign-in actions, subject to the server's available tools and the owner's grants. `rer business tools` discovers tools and `rer business call TOOL` reaches tools without a dedicated verb. Flags accept structured JSON or file input; `--json` returns structured results.
|
|
13
|
+
- Change and update following supports bounded waits. A change request can wait for its preview and, with explicit `--publish`, request publication and wait for live. Refusals, unavailable tools and unfinished waits retain distinct outcomes and actionable guidance.
|
|
14
|
+
- `rer business mcp` forwards newline-delimited JSON-RPC over stdio to the Business MCP. The paired client refreshes its short-lived bearer near expiry and once after a 401; protocol output stays on stdout and diagnostics on stderr.
|
|
15
|
+
|
|
16
|
+
These CLI changes require the matching Business server, pairing, owner approvals and grants. This preparation establishes no live-provider, Managed deployment, seed adoption or production result. The actual source diff changes no portability, import-kit, product migrations or archive format identity; the browser advice change is not included.
|
|
17
|
+
|
|
3
18
|
## 0.2.119
|
|
4
19
|
|
|
5
20
|
### Large installation archive inventories
|