@runeditrun/rer 0.2.85 → 0.2.86

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/README.md +138 -29
  2. package/cli/README.md +61 -1
  3. package/cli/agent-door.mjs +149 -0
  4. package/cli/agent-fixtures.mjs +16 -0
  5. package/cli/agent-mail.mjs +54 -0
  6. package/cli/agent-network.mjs +64 -0
  7. package/cli/agent-reviewers.mjs +110 -0
  8. package/cli/agent-secrets.mjs +23 -0
  9. package/cli/agent-sponsors.mjs +43 -0
  10. package/cli/agent-surface.mjs +34 -0
  11. package/cli/agent-webhooks.mjs +19 -0
  12. package/cli/authoring.mjs +2 -1
  13. package/cli/business/archive-task.mjs +32 -0
  14. package/cli/business/carry.mjs +3 -1
  15. package/cli/business/catchup-task.mjs +42 -0
  16. package/cli/business/choices.mjs +97 -0
  17. package/cli/business/command.mjs +23 -5
  18. package/cli/business/connect.mjs +19 -7
  19. package/cli/business/detector.mjs +4 -1
  20. package/cli/business/device.mjs +13 -0
  21. package/cli/business/export-inputs.mjs +69 -0
  22. package/cli/business/export-task.mjs +17 -0
  23. package/cli/business/invocation.mjs +8 -1
  24. package/cli/business/keychain.mjs +8 -1
  25. package/cli/business/lease.mjs +11 -1
  26. package/cli/business/local-commands.mjs +79 -31
  27. package/cli/business/outbound.mjs +9 -4
  28. package/cli/business/parsers-config.mjs +8 -7
  29. package/cli/business/parsers-syntax.mjs +7 -3
  30. package/cli/business/permissions.mjs +2 -0
  31. package/cli/business/questions.mjs +89 -9
  32. package/cli/business/setup-command.mjs +49 -0
  33. package/cli/business/setup-company.json +15 -0
  34. package/cli/business/setup-demo.mjs +95 -0
  35. package/cli/business/state.mjs +44 -10
  36. package/cli/business/supervisor.mjs +94 -35
  37. package/cli/business/vendor-door.mjs +230 -0
  38. package/cli/business/vendors/README.md +29 -3
  39. package/cli/business/vendors/common.mjs +8 -6
  40. package/cli/business/vendors/index.mjs +22 -11
  41. package/cli/business/vendors/sorry.mjs +106 -0
  42. package/cli/contract.mjs +2 -2
  43. package/cli/demo-deploy-error.mjs +14 -0
  44. package/cli/demo-native.mjs +4 -1
  45. package/cli/deploy-config.mjs +1 -1
  46. package/cli/deploy-owner-input.mjs +3 -1
  47. package/cli/deploy-variables.mjs +58 -0
  48. package/cli/door-clauses.mjs +157 -0
  49. package/cli/export.mjs +16 -4
  50. package/cli/hosted-output.mjs +17 -7
  51. package/cli/inspect.mjs +4 -0
  52. package/cli/jsonc.mjs +8 -4
  53. package/cli/lifecycle.mjs +3 -1
  54. package/cli/main.mjs +1 -0
  55. package/cli/managed-data-schema.mjs +14 -1
  56. package/cli/portability-empty.mjs +6 -0
  57. package/cli/portability-migrations.mjs +26 -4
  58. package/cli/production-auth.mjs +1 -1
  59. package/cli/production-mail.mjs +8 -2
  60. package/edition-authoring/archive-source.mjs +59 -0
  61. package/edition-authoring/base-copies.mjs +92 -18
  62. package/edition-authoring/cli.mjs +1 -1
  63. package/edition-authoring/edition-migrations.mjs +7 -3
  64. package/edition-authoring/module-closure.mjs +2 -16
  65. package/edition-authoring/workflow-copies.mjs +1 -1
  66. package/edition-authoring/workflow-scripts.mjs +12 -3
  67. package/foundation/runtime/contract-docs.mjs +215 -32
  68. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  69. package/foundation/runtime/contract-prose.mjs +88 -0
  70. package/global/CHANGELOG.md +93 -0
  71. package/global/README.md +138 -29
  72. package/global/door/command.mjs +3 -1
  73. package/global/main.mjs +1 -1
  74. package/modules/agent-door/CLAUSES.md +215 -0
  75. package/modules/agent-door/conformance/audit.mjs +66 -0
  76. package/modules/agent-door/conformance/authority.d.mts +2 -0
  77. package/modules/agent-door/conformance/authority.mjs +17 -0
  78. package/modules/agent-door/conformance/crypto.mjs +36 -0
  79. package/modules/agent-door/conformance/discovery.mjs +61 -0
  80. package/modules/agent-door/conformance/index.mjs +41 -0
  81. package/modules/agent-door/conformance/invocation.mjs +32 -0
  82. package/modules/agent-door/conformance/journey.mjs +112 -0
  83. package/modules/agent-door/conformance/narrowing.d.mts +1 -0
  84. package/modules/agent-door/conformance/narrowing.mjs +21 -0
  85. package/modules/agent-door/conformance/negative.mjs +47 -0
  86. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  87. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  88. package/modules/agent-door/conformance/policy-phases.mjs +75 -0
  89. package/modules/agent-door/conformance/protocol.mjs +145 -0
  90. package/modules/agent-door/conformance/replay.mjs +38 -0
  91. package/modules/agent-door/conformance/schema.mjs +71 -0
  92. package/modules/agent-door/conformance/security.mjs +33 -0
  93. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  94. package/modules/agent-door/conformance/surface.mjs +89 -0
  95. package/modules/agent-door/conformance/target.mjs +18 -0
  96. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  97. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  98. package/modules/agent-door/conformance/webhooks.mjs +30 -0
  99. package/modules/container/image-variables.mjs +8 -2
  100. package/modules/demo-host/README.md +6 -0
  101. package/modules/demo-host/ownership.mjs +39 -0
  102. package/modules/demo-host/plan.mjs +2 -1
  103. package/modules/demo-host/remove.mjs +6 -1
  104. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  105. package/modules/import-kit/schema/importers.schema.json +107 -0
  106. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  107. package/modules/import-kit/src/door/README.md +2 -1
  108. package/modules/import-kit/src/door/admission.ts +5 -3
  109. package/modules/import-kit/src/door/archive.ts +5 -2
  110. package/modules/import-kit/src/door/authority.ts +1 -0
  111. package/modules/import-kit/src/door/grants.ts +1 -1
  112. package/modules/import-kit/src/door/handler.ts +14 -8
  113. package/modules/import-kit/src/door/index.ts +1 -1
  114. package/modules/import-kit/src/door/jobs.ts +40 -0
  115. package/modules/import-kit/src/door/operator.ts +3 -3
  116. package/modules/import-kit/src/door/planning.ts +10 -6
  117. package/modules/import-kit/src/door/protocol.ts +2 -2
  118. package/modules/import-kit/src/door/raw.ts +25 -0
  119. package/modules/import-kit/src/door/refusals.ts +1 -0
  120. package/modules/import-kit/src/door/types.ts +26 -6
  121. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  122. package/modules/import-kit/src/receipt/index.ts +69 -0
  123. package/modules/import-kit/src/receipt/policy.ts +24 -0
  124. package/modules/import-kit/src/receipt/types.ts +64 -0
  125. package/modules/import-kit/src/receipt/uri.ts +45 -0
  126. package/modules/import-kit/src/receipt/validation.ts +87 -0
  127. package/modules/import-kit/src/status/encoding.ts +13 -0
  128. package/modules/import-kit/src/status/evidence.ts +218 -0
  129. package/modules/import-kit/src/status/index.ts +56 -0
  130. package/modules/import-kit/src/status/schema.ts +208 -0
  131. package/modules/import-kit/src/status/types.ts +86 -0
  132. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  133. package/modules/operator-auth/index.d.mts +7 -0
  134. package/modules/operator-auth/service.mjs +2 -0
  135. package/modules/portability/README.md +32 -11
  136. package/modules/portability/bridge.mjs +22 -2
  137. package/modules/portability/copies.mjs +8 -1
  138. package/modules/portability/derived.mjs +33 -0
  139. package/modules/portability/http-errors.mjs +1 -1
  140. package/modules/portability/import.mjs +14 -7
  141. package/package.json +4 -2
  142. package/scripts/publish-check/copy_identities.py +3 -1
  143. package/scripts/publish-check/github_refs.py +32 -13
  144. package/cli/business/opt-ins.mjs +0 -37
@@ -0,0 +1,69 @@
1
+ // The non-secret inputs a leased vendor task carries for its shipped adapter
2
+ // (the executor task view's `export_inputs`, platform executors/tasks.ts): one
3
+ // closed shape per vendor, never a key. Business fills them from the Business's
4
+ // inventory evidence and the owner's answers; a window the plan does not state
5
+ // is the vendor's full history (`since` null or absent).
6
+ //
7
+ // sentry {organization: {id, slug, region: 'us'|'de'}, window: {since}}
8
+ // pagerduty {window: {since}, schedules: 'all'} (the plan moves every rota and
9
+ // keeps PagerDuty as the pager)
10
+ // sorry {page: {host}}
11
+ // uptimerobot needs none.
12
+
13
+ const DAY = 86_400_000;
14
+ const invalid = () => { throw Error('Business returned invalid export inputs for this task.'); };
15
+ const plain = value => value && typeof value === 'object' && !Array.isArray(value) ? value : invalid();
16
+ function closed(value, required, optional = []) {
17
+ plain(value);
18
+ if (Object.keys(value).some(key => !required.includes(key) && !optional.includes(key)) || required.some(key => !Object.hasOwn(value, key))) invalid();
19
+ return value;
20
+ }
21
+ const sourceId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value) ? value : invalid();
22
+ /** The window's start as an ISO instant, or null for the vendor's full history. */
23
+ function since(window) {
24
+ closed(window, [], ['since']);
25
+ const value = window.since ?? null;
26
+ if (value === null) return null;
27
+ if (typeof value !== 'string' || value.length > 40 || !/^\d{4}-\d\d-\d\dT/.test(value) || !Number.isFinite(Date.parse(value))) invalid();
28
+ return new Date(value).toISOString();
29
+ }
30
+
31
+ const shapes = {
32
+ uptimerobot: () => ({}),
33
+ sentry(value, now) {
34
+ closed(value, ['organization', 'window']);
35
+ const organization = closed(value.organization, ['id', 'slug', 'region']);
36
+ if (!['us', 'de'].includes(organization.region)) invalid();
37
+ const id = Number.isSafeInteger(organization.id) && organization.id >= 0 ? String(organization.id) : sourceId(organization.id);
38
+ // Full history: from the start of time, which Sentry answers with all it retains.
39
+ return { organization: { id, slug: sourceId(organization.slug), region: organization.region }, start: since(value.window) ?? new Date(0).toISOString(), end: new Date(now).toISOString() };
40
+ },
41
+ pagerduty(value, now) {
42
+ closed(value, ['window', 'schedules']);
43
+ if (value.schedules !== 'all') invalid();
44
+ // Rotas move into Oncall beside PagerDuty, so the window runs in whole UTC days
45
+ // to two weeks ahead (the coming overrides; the default of Oncall's own
46
+ // exporter). Oncall compares a schedule's final timeline over at most 31 days
47
+ // and refuses a longer one, so the window starts at the plan's `since` or 31
48
+ // days before its end, whichever is later.
49
+ const until = Math.floor(now / DAY) * DAY + 14 * DAY, start = since(value.window), floor = until - 31 * DAY;
50
+ return { start: new Date(start === null ? floor : Math.max(Math.floor(Date.parse(start) / DAY) * DAY, floor)).toISOString(), end: new Date(until).toISOString() };
51
+ },
52
+ sorry(value) {
53
+ closed(value, ['page']);
54
+ const page = closed(value.page, ['host']);
55
+ if (typeof page.host !== 'string' || page.host.length > 253 || !/^[a-z0-9.-]+$/.test(page.host)) invalid();
56
+ return { page: { host: page.host } };
57
+ },
58
+ };
59
+ /** What each vendor's inputs are, in the owner's terms, while a task lacks them. */
60
+ export const inputNeeds = { sentry: 'its Sentry organization and export window', pagerduty: 'its export window', sorry: "its status page's address" };
61
+
62
+ /** The shipped adapter's inputs for `vendor` from the leased task's
63
+ * `export_inputs`, or null when the task carries none yet. */
64
+ export function exportInputs(vendor, task, now = Date.now()) {
65
+ if (!Object.hasOwn(shapes, vendor)) return null;
66
+ if (vendor === 'uptimerobot') return {};
67
+ if (task.export_inputs === undefined || task.export_inputs === null) return null;
68
+ return shapes[vendor](task.export_inputs, now);
69
+ }
@@ -0,0 +1,17 @@
1
+ import { withUploadedBundle, door, checkedPreview, plural } from './vendor-door.mjs';
2
+
3
+ /** Perform a claimed export.vendor: the shipped adapter's bundle uploaded into
4
+ * the app's import door, then the door's plan (a zero-write preview), then
5
+ * completion with the door's upload_id and plan_id and the bundle's SHA-256.
6
+ * Returns the line to say. */
7
+ export function runExport({ lease, task, grant, directory, say, ownerPage }) {
8
+ return withUploadedBundle({ lease, task, grant, directory, say,
9
+ doing: (name, origin, keyed) => `Exporting ${name} through the shipped read-only adapter. ${keyed ? 'The key stays on this computer; records' : 'Records'} go only to the app's import door at ${origin}.` },
10
+ async ({ origin, uploadId, bundle, fresh }) => {
11
+ const preview = await door(await fresh('plan'), { uploadId }, lease.signal), { records, created, updated, unchanged, rejected } = checkedPreview(preview, bundle);
12
+ // Identifiers only: Business reads that plan from the door with its own grants
13
+ // and completes the task only if it is the plan of exactly this bundle.
14
+ return { outputs: { upload_id: uploadId, plan_id: preview.planId, bundle_sha256: bundle.sha256 },
15
+ said: `Import preview ready in ${origin}: ${plural(records, 'source record')}; ${created} to create, ${updated} to update, ${unchanged} unchanged, ${rejected} rejected. Nothing was imported: the owner reviews and approves this move in the browser: ${ownerPage}` };
16
+ });
17
+ }
@@ -1,5 +1,5 @@
1
1
  import { accessSync, statSync, constants } from 'node:fs';
2
- import { delimiter, join, sep } from 'node:path';
2
+ import { delimiter, join, resolve, sep } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
 
5
5
  const npx = 'npx -y @runeditrun/rer';
@@ -23,3 +23,10 @@ export function rerCommand(env = process.env) {
23
23
  if (env.RER_INVOKED_AS) return word(env.RER_INVOKED_AS);
24
24
  return onPath(env.PATH) ? 'rer' : npx;
25
25
  }
26
+
27
+ // A rer business command the person can paste into another shell, such as a
28
+ // terminal outside an agent sandbox: it names the state folder when one was chosen.
29
+ export function businessCommand(verb, env = process.env) {
30
+ const folder = env.RER_BUSINESS_STATE_DIR;
31
+ return `${folder && !folder.includes('\0') ? `RER_BUSINESS_STATE_DIR=${word(resolve(folder))} ` : ''}${rerCommand(env)} business ${verb}`;
32
+ }
@@ -3,12 +3,17 @@ import { randomUUID } from 'node:crypto';
3
3
 
4
4
  const service = 'com.runeditrun.business';
5
5
  const sandboxed = 'an agent sandbox blocks this. Run this one command outside the sandbox (in Codex, approve running it outside the sandbox when it asks), or in your own terminal';
6
+ // Inside a Codex workspace-write sandbox with network on, security answers 161
7
+ // for a write or a removal (UNIX Operation not permitted), even after printing
8
+ // "password has been deleted."; the item stays in the keychain.
9
+ const refusedBySandbox = result => /Operation not permitted|Unable to obtain authorization/.test(result?.stderr ?? '') || result?.code === 161;
6
10
  // Causes come from fixed phrases matched in the tool's diagnostics; the
7
11
  // diagnostics themselves are never printed.
8
12
  function cause(binary, result) {
9
13
  const text = result?.stderr ?? '';
10
14
  if (result?.spawnFailed) return binary === 'secret-tool' ? 'secret-tool is not installed. Install it and unlock a Secret Service session' : `${binary} could not start`;
11
15
  if (/Operation not permitted/.test(text)) return `macOS Keychain refused the write (Operation not permitted); ${sandboxed}`;
16
+ if (result?.code === 161) return `macOS Keychain refused the change (security exited with status 161: Operation not permitted); ${sandboxed}`;
12
17
  if (/Unable to obtain authorization/.test(text)) return `macOS Keychain refused authorization; ${sandboxed}`;
13
18
  if (/User interaction is not allowed|interaction is not allowed/i.test(text)) return 'the keychain is locked and cannot ask for its password here. Unlock it, then try again';
14
19
  if (/autolaunch D-Bus|Cannot spawn a message bus|org\.freedesktop\.secrets/.test(text)) return 'no unlocked Secret Service session is running. Unlock one, then try again';
@@ -17,7 +22,7 @@ function cause(binary, result) {
17
22
  }
18
23
  const unavailable = (operation, binary, result) => {
19
24
  const error = new Error(`OS credential storage could not ${operation} a credential: ${cause(binary, result)}. No credential was written to a file.`);
20
- error.sandboxRefused = /Operation not permitted|Unable to obtain authorization/.test(result?.stderr ?? '');
25
+ error.sandboxRefused = refusedBySandbox(result); error.osStatus = result?.code ?? null;
21
26
  return error;
22
27
  };
23
28
 
@@ -107,6 +112,8 @@ export function createCredentialStore({ platform = process.platform, env = proce
107
112
  ? await call('remove', '/usr/bin/security', ['delete-generic-password', ...macArgs(handle)])
108
113
  : await call('remove', 'secret-tool', ['clear', ...linuxArgs(handle)]);
109
114
  if (result.code !== 0 && !(platform === 'darwin' && result.code === 44)) throw unavailable('remove', binary, result);
115
+ // A refused removal can still print success; only a read-back proves it.
116
+ if (await get(handle) !== null) throw unavailable('remove', binary, { code: result.code, stderr: '' });
110
117
  },
111
118
  };
112
119
  }
@@ -35,6 +35,15 @@ export class Lease {
35
35
  { token, ...(releasing ? { timeout: 5_000 } : { signal: this.signal }) });
36
36
  }
37
37
  send(destination, body) { return this.serial(() => this.post(destination, body)); }
38
+ /** One door grant for one door request of this lease's vendor task (`extra`
39
+ * is `{review: true}` for a catch-up plan the owner reviews). It is not a task
40
+ * event, so the platform takes no client event id: a retry simply asks again. */
41
+ importGrant(action, extra = {}) {
42
+ return this.serial(async () => {
43
+ this.signal.throwIfAborted();
44
+ return this.api.post(taskPath(this.claim.task.id, 'import-grants'), { fence: this.claim.fence, grant_id: this.claim.grant.id, action, ...extra }, { token: await this.token(), signal: this.signal });
45
+ });
46
+ }
38
47
  heartbeat() {
39
48
  return this.serial(async () => {
40
49
  const result = await this.post(taskPath(this.claim.task.id, 'heartbeat'), { checkpoint: this.checkpoint, cursor: this.cursor });
@@ -57,7 +66,8 @@ export class Lease {
57
66
  await saveProgress(this.progress);
58
67
  await this.heartbeat();
59
68
  }
60
- async complete() { clearInterval(this.timer); return this.serial(() => this.post(taskPath(this.claim.task.id, 'complete'), { outputs: {} })); }
69
+ /** Complete the task with the outputs its kind reports (none for a scan). */
70
+ async complete(outputs = {}) { clearInterval(this.timer); return this.serial(() => this.post(taskPath(this.claim.task.id, 'complete'), { outputs })); }
61
71
  async release(reason = 'handover') {
62
72
  clearInterval(this.timer);
63
73
  await this.tail;
@@ -1,26 +1,77 @@
1
- import { readFile, writeFile, unlink, lstat } from 'node:fs/promises';
1
+ import { writeFile, unlink } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
- import { loadState, loadPending, saveState, stateDirectory, removeStateDirectory, credentialHandle } from './state.mjs';
3
+ import { loadState, loadPending, saveState, stateDirectory, removeStateDirectory, removeWorkFiles, credentialHandle, liveSupervisor } from './state.mjs';
4
4
  import { createCredentialStore, readSecret } from './keychain.mjs';
5
5
  import { removeService, serviceStatus } from './service.mjs';
6
- import { removePermissions } from './permissions.mjs';
6
+ import { removePermissions, permissionsAdded } from './permissions.mjs';
7
7
  import { Api, pause } from './api.mjs';
8
8
  import { loadProgress } from './progress.mjs';
9
- import { VENDORS } from './vendors/index.mjs';
10
9
  import { removeCarries } from './carry.mjs';
11
- import { rerCommand } from './invocation.mjs';
10
+ import { KEYED_VENDORS } from './vendors/index.mjs';
11
+ import { vendorHandle } from './vendor-door.mjs';
12
+ import { rerCommand, businessCommand } from './invocation.mjs';
13
+ import { describe } from './errors.mjs';
14
+ import { supportsTaskKind } from './supervisor.mjs';
12
15
 
13
16
  export async function paired() {
14
17
  const state = await loadState();
15
18
  if (!state?.origin || !state.businessId || !state.executorId) throw Error(`This computer is not paired. Run ${rerCommand()} business connect --code CODE.`);
19
+ if (state.revoked) throw Error(`This computer was ${revokedText(state)}`);
16
20
  const credential = await createCredentialStore().get(credentialHandle(state.origin));
17
21
  if (!credential) throw Error(`This computer's Business credential is missing from OS credential storage. Run ${rerCommand()} business disconnect, then connect again with a new code from ${state.origin}/business.`);
18
22
  return { state, credential };
19
23
  }
20
24
 
25
+ // What a revoked computer still keeps here, in the words a person reads.
26
+ const leftoverWords = { credential: 'the local credential is still stored', vendorKeys: 'vendor keys are still stored', service: 'the background service is still installed', permissions: 'the added Claude Code rules are still in place' };
27
+ export function revokedText(state, { cause = false } = {}) {
28
+ const left = (state.revoked?.leftovers ?? []).filter(item => Object.hasOwn(leftoverWords, item));
29
+ if (!left.length) return `revoked on the server. Finish with ${businessCommand('disconnect')}`;
30
+ return `revoked on the server; ${left.map(item => leftoverWords[item]).join(', ')}.${cause && state.revoked.cause ? `\n${state.revoked.cause}` : ''}\nRemove ${left.length === 1 ? 'it' : 'them'} with this one command, run outside the agent sandbox or in your own terminal:\n ${businessCommand('disconnect')}`;
31
+ }
32
+
33
+ /** After the server revoked this computer, remove what this session can and
34
+ * keep a record of the rest, so status says revoked and a later disconnect
35
+ * (outside an agent sandbox) finishes. Returns the leftovers. */
36
+ export async function forgetLocally(state, { stopRun = true } = {}) {
37
+ const leftovers = [], store = state?.origin ? createCredentialStore() : null;
38
+ const attempt = async (item, work) => { try { await work(); } catch (error) { leftovers.push(item); return error; } };
39
+ const directory = stateDirectory();
40
+ if (stopRun) await stopSupervisor(directory);
41
+ await attempt('service', () => removeService());
42
+ await attempt('permissions', () => removePermissions());
43
+ const vendorKeys = [];
44
+ for (const handle of store ? state.vendorHandles ?? [] : []) if (await attempt('vendorKeys', () => store.delete(handle))) vendorKeys.push(handle);
45
+ const refused = store ? await attempt('credential', () => store.delete(credentialHandle(state.origin))) : undefined;
46
+ await removeCarries();
47
+ if (!leftovers.length) { await removeStateDirectory(); return []; }
48
+ const unique = [...new Set(leftovers)];
49
+ const cause = refused && (refused.sandboxRefused ? `macOS Keychain refused to remove it inside this agent sandbox (security exited with status ${refused.osStatus ?? 'unknown'}).` : describe(refused));
50
+ await saveState({ ...state, vendorHandles: vendorKeys, revoked: { at: new Date().toISOString(), leftovers: unique, ...(cause ? { cause } : {}) } });
51
+ await removeWorkFiles();
52
+ return unique;
53
+ }
54
+
55
+ /** The server answered 401 to this computer's own credential: it was revoked
56
+ * (or expired). Remove the credential if this session may, and record what
57
+ * is left so status says revoked and disconnect finishes the rest. */
58
+ export async function revokedByServer(state) {
59
+ const leftovers = [];
60
+ let cause;
61
+ try { await createCredentialStore().delete(credentialHandle(state.origin)); }
62
+ catch (error) { leftovers.push('credential'); cause = error.sandboxRefused ? `macOS Keychain refused to remove it inside this agent sandbox (security exited with status ${error.osStatus ?? 'unknown'}).` : describe(error); }
63
+ if (state.vendorHandles?.length) leftovers.push('vendorKeys');
64
+ if ((await serviceStatus()).installed) leftovers.push('service');
65
+ if (await permissionsAdded()) leftovers.push('permissions');
66
+ const saved = { ...state, revoked: { at: new Date().toISOString(), leftovers, ...(cause ? { cause } : {}) } };
67
+ await saveState(saved);
68
+ await removeWorkFiles(['state.json', 'permissions.json', 'service.json', 'run.lock', 'carried.json']);
69
+ return saved;
70
+ }
71
+
21
72
  export async function vendorKey(action, vendor) {
22
- if (!['add', 'remove'].includes(action) || !VENDORS.includes(vendor)) throw Error('Choose add or remove and a shipped vendor: sentry, uptimerobot, pagerduty, calendly.');
23
- const { state } = await paired(), store = createCredentialStore(), handle = `vendor:${vendor}:read`;
73
+ if (!['add', 'remove'].includes(action) || !KEYED_VENDORS.includes(vendor)) throw Error(`Choose add or remove and a shipped vendor that reads with a key: ${KEYED_VENDORS.join(', ')}. Sorry needs no key.`);
74
+ const { state } = await paired(), store = createCredentialStore(), handle = vendorHandle(vendor);
24
75
  if (action === 'add') {
25
76
  let secret = await readSecret();
26
77
  try { await store.set(handle, secret); } finally { secret = undefined; }
@@ -35,16 +86,10 @@ export async function vendorKey(action, vendor) {
35
86
 
36
87
  async function stopSupervisor(directory) {
37
88
  const lock = join(directory, 'run.lock');
38
- try { await lstat(lock); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
89
+ if (!await liveSupervisor(lock)) return;
39
90
  await writeFile(join(directory, 'disconnect'), '', { mode: 0o600 });
40
91
  for (let attempt = 0; attempt < 100; attempt++) {
41
- try {
42
- const pid = Number(await readFile(lock, 'utf8'));
43
- if (Number.isSafeInteger(pid) && pid > 0) {
44
- try { process.kill(pid, 0); }
45
- catch (error) { if (error.code !== 'ESRCH') throw error; await unlink(lock); return; }
46
- }
47
- } catch (error) { if (error.code === 'ENOENT') return; throw error; }
92
+ if (!await liveSupervisor(lock)) { await unlink(lock).catch(error => { if (error.code !== 'ENOENT') throw error; }); return; }
48
93
  await pause(100);
49
94
  }
50
95
  throw Error('Business supervisor is still stopping. Retry disconnect shortly.');
@@ -58,8 +103,13 @@ async function revoke(origin, credential) {
58
103
  catch (error) { return error.status === 401 ? 'revoked' : [403, 404].includes(error.status) ? 'unsupported' : 'unconfirmed'; }
59
104
  }
60
105
 
106
+ /** Revoke on the server first, then remove the local service, rules, keys and
107
+ * credential. When this session may not remove something (macOS refuses
108
+ * Keychain changes inside an agent sandbox), the computer is still revoked:
109
+ * say so, keep a record so status says revoked, name the one command that
110
+ * finishes outside the sandbox, and exit 0. */
61
111
  export async function disconnect() {
62
- const state = await loadState(), directory = stateDirectory();
112
+ const state = await loadState();
63
113
  const origin = state?.origin ?? (await loadPending())?.origin;
64
114
  const page = origin && (state?.businessId ? `${origin}/business/${encodeURIComponent(state.businessId)}/settings` : `${origin}/business`);
65
115
  const credential = state?.origin ? await createCredentialStore().get(credentialHandle(state.origin)) : null;
@@ -71,18 +121,16 @@ export async function disconnect() {
71
121
  return;
72
122
  }
73
123
  if (revocation === 'unconfirmed') throw Error(`Business did not confirm revocation, so this computer is still connected and its credentials were kept. Retry ${rerCommand()} business disconnect, or revoke it in ${page} and then run disconnect again.`);
74
- await removeService();
75
- await stopSupervisor(directory);
76
- await removePermissions();
77
- if (state) {
78
- const store = createCredentialStore();
79
- for (const handle of state.vendorHandles ?? []) await store.delete(handle);
80
- if (state.origin) await store.delete(credentialHandle(state.origin));
124
+ const wasRevoked = Boolean(state?.revoked);
125
+ const leftovers = await forgetLocally(state);
126
+ if (leftovers.length) {
127
+ const saved = await loadState();
128
+ process.stdout.write(`R${revokedText(saved, { cause: true }).slice(1)}\nUntil then, status says revoked; this computer can no longer reach Business.\n`);
129
+ return;
81
130
  }
82
- await removeCarries();
83
- await removeStateDirectory();
84
131
  process.stdout.write(revocation === 'revoked'
85
- ? 'Business disconnected. Device revoked; local service, credentials and added permissions removed.\n'
132
+ ? `Business disconnected. Device ${wasRevoked ? 'was already revoked' : 'revoked'}; local service, credentials and added permissions removed.\n`
133
+ : wasRevoked ? 'Business disconnected. Device was already revoked on the server; local service, credentials and added permissions removed.\n'
86
134
  : `Business disconnected on this computer: local service, credentials and added permissions removed. Nothing was revoked: no device credential was stored here${page ? `. If this computer still shows in ${page}, revoke it there` : ''}.\n`);
87
135
  }
88
136
 
@@ -91,14 +139,14 @@ export async function status({ json = false } = {}) {
91
139
  if (!state) {
92
140
  process.stdout.write(json ? JSON.stringify({ paired: false, service: 'not_installed', current_task: null, checkpoint: null }) + '\n' : 'Business: not paired.\nService: not installed.\nTask: none.\nCheckpoint: none.\n'); return;
93
141
  }
94
- const stored = state.origin && await createCredentialStore().get(credentialHandle(state.origin));
142
+ const stored = !state.revoked && state.origin && await createCredentialStore().get(credentialHandle(state.origin));
95
143
  const service = await serviceStatus();
96
- const active = (await loadProgress()).current;
144
+ const active = state.revoked ? null : (await loadProgress()).current;
97
145
  if (json) {
98
- process.stdout.write(JSON.stringify({ paired: Boolean(stored), service: service.running ? 'running' : service.installed ? 'stopped' : 'not_installed', current_task: ['discover.local', 'export.vendor'].includes(active?.kind) ? active.kind : null, checkpoint: active?.checkpoint ? { saved: true, uploaded_bytes: Number.isSafeInteger(active.uploadedBytes) ? active.uploadedBytes : 0 } : null }) + '\n');
146
+ process.stdout.write(JSON.stringify({ paired: Boolean(stored), ...(state.revoked ? { revoked: true } : {}), service: service.running ? 'running' : service.installed ? 'stopped' : 'not_installed', current_task: supportsTaskKind(active?.kind) ? active.kind : null, checkpoint: active?.checkpoint ? { saved: true, uploaded_bytes: Number.isSafeInteger(active.uploadedBytes) ? active.uploadedBytes : 0 } : null }) + '\n');
99
147
  return;
100
148
  }
101
- process.stdout.write(`Business: ${stored ? 'paired' : 'credential missing'}.\nService: ${service.running ? 'running' : service.installed ? 'installed, stopped' : 'not installed'}.\n`);
102
- process.stdout.write(`Task: ${['discover.local', 'export.vendor'].includes(active?.kind) ? active.kind : 'none'}.\n`);
149
+ process.stdout.write(`Business: ${state.revoked ? revokedText(state) : stored ? 'paired.' : 'credential missing.'}\nService: ${service.running ? 'running' : service.installed ? 'installed, stopped' : 'not installed'}.\n`);
150
+ process.stdout.write(`Task: ${supportsTaskKind(active?.kind) ? active.kind : 'none'}.\n`);
103
151
  process.stdout.write(`Checkpoint: ${active?.checkpoint ? 'saved' : 'none'}${Number.isSafeInteger(active?.uploadedBytes) ? `; ${active.uploadedBytes} bytes uploaded` : ''}.\n`);
104
152
  }
@@ -1,4 +1,4 @@
1
- import { sensitive, blockedSignal } from './detector.mjs';
1
+ import { sensitive, credentialShaped, blockedSignal } from './detector.mjs';
2
2
 
3
3
  export function assertOutbound(value, knownSecrets = []) {
4
4
  function visit(item) {
@@ -14,10 +14,15 @@ export function assertOutbound(value, knownSecrets = []) {
14
14
  visit(value);
15
15
  }
16
16
 
17
+ /** A vendor export item bound for the owner's own app. Chunks may be fragments
18
+ * of a JSON document, so the complete UTF-8 text is inspected before any network
19
+ * write: the owner's key and every known credential shape are refused. The
20
+ * entropy heuristic for names-only signals does not apply here: vendor records
21
+ * are made of opaque ids, hashes and API links (Sentry's 32-hex event ids,
22
+ * PagerDuty's `self` URLs), and they go only to the owner's own app. */
17
23
  export function assertChunk(bytes, knownSecrets) {
18
- // Chunks may be fragments of a JSON document. The detector sees the complete
19
- // UTF-8 text before any network write, including names and record values.
20
- assertOutbound(Buffer.from(bytes).toString('utf8'), knownSecrets);
24
+ const text = Buffer.from(bytes).toString('utf8');
25
+ if (credentialShaped(text.replace(/[\r\n\t]/g, ' ')) || knownSecrets.some(secret => secret && text.includes(secret))) throw Error('Business outbound detector refused secret-shaped content.');
21
26
  }
22
27
 
23
28
  // Names-only signals share the scanner's field-aware path policy. A locator
@@ -47,7 +47,7 @@ function remainingQuote(source, initial = '') {
47
47
  }
48
48
 
49
49
  function statements(source) {
50
- const result = []; let current = '', quote = '', depth = 0, triple = false;
50
+ const result = []; let current = '', quote = '', depth = 0, triple = false, start = 0;
51
51
  for (let i = 0; i < source.length; i++) {
52
52
  const char = source[i]; current += char;
53
53
  if (quote) {
@@ -59,19 +59,19 @@ function statements(source) {
59
59
  if (source.slice(i, i + 3) === char.repeat(3)) { triple = true; current += source.slice(i + 1, i + 3); i += 2; }
60
60
  } else if (char === '[' || char === '{') depth++;
61
61
  else if (char === ']' || char === '}') depth--;
62
- else if (char === '\n' && depth === 0) { result.push(current.trim()); current = ''; }
62
+ else if (char === '\n' && depth === 0) { result.push({text:current.trim(), offset:start + current.search(/\S/)}); current = ''; start = i + 1; }
63
63
  }
64
- if (current.trim()) result.push(current.trim()); return result;
64
+ if (current.trim()) result.push({text:current.trim(), offset:start + current.search(/\S/)}); return result;
65
65
  }
66
66
 
67
- export function tomlEntries(source) {
67
+ export function tomlEntries(source, { locations = false } = {}) {
68
68
  const entries = []; let table = [];
69
- for (const statement of statements(source)) {
69
+ for (const {text:statement, offset} of statements(source)) {
70
70
  const header = /^(\[\[?)([\s\S]*?)(\]\]?)$/.exec(statement);
71
71
  if (header && header[1].length === header[3].length) {
72
72
  table = keyParts(header[2], true) ?? [];
73
73
  if (table.length) {
74
- entries.push({ path: table, value: undefined });
74
+ entries.push({ path: table, value: undefined, ...(locations ? {offset} : {}) });
75
75
  if (header[1] === '[[') table = [...table, '[]'];
76
76
  }
77
77
  continue;
@@ -79,7 +79,8 @@ export function tomlEntries(source) {
79
79
  const parts = splitOutside(statement, '='); if (parts.length < 2) continue;
80
80
  const keys = keyParts(parts.shift(), true); if (!keys) continue;
81
81
  const path = [...table, ...keys], raw = parts.join('=').trim();
82
- entries.push({ path, value: literal(raw) }); flowEntries(raw, path, '=', entries);
82
+ entries.push({ path, value: literal(raw), ...(locations ? {offset} : {}) });
83
+ flowEntries(raw, path, '=', entries, 0, locations ? offset + statement.indexOf('=') + 1 + parts.join('=').search(/\S/) : undefined);
83
84
  }
84
85
  return entries;
85
86
  }
@@ -72,15 +72,19 @@ export function keyParts(source, dotted = false) {
72
72
  return result.length && result.every(part => part !== undefined) ? result : undefined;
73
73
  }
74
74
 
75
- export function flowEntries(source, path, delimiter, entries, depth = 0) {
75
+ export function flowEntries(source, path, delimiter, entries, depth = 0, offset) {
76
76
  if (depth > 48) return;
77
77
  const value = source.trim();
78
+ if (offset !== undefined) offset += source.search(/\S/);
78
79
  if (value.startsWith('{') && value.endsWith('}')) {
80
+ let cursor = 1;
79
81
  for (const pair of splitOutside(value.slice(1, -1), ',')) {
80
82
  const parts = splitOutside(pair, delimiter); if (parts.length < 2) continue;
81
83
  const keys = keyParts(parts.shift(), delimiter === '='); if (!keys) continue;
82
- const child = [...path, ...keys], raw = parts.join(delimiter).trim();
83
- entries.push({ path: child, value: literal(raw) }); flowEntries(raw, child, delimiter, entries, depth + 1);
84
+ const child = [...path, ...keys], raw = parts.join(delimiter);
85
+ entries.push({ path: child, value: literal(raw), ...(offset === undefined ? {} : {offset:offset + cursor + pair.search(/\S/)}) });
86
+ flowEntries(raw, child, delimiter, entries, depth + 1, offset === undefined ? undefined : offset + cursor + pair.indexOf(delimiter) + 1);
87
+ cursor += pair.length + 1;
84
88
  }
85
89
  } else if (value.startsWith('[') && value.endsWith(']')) {
86
90
  for (const item of splitOutside(value.slice(1, -1), ',')) {
@@ -114,6 +114,8 @@ export async function installPermissions(input = {}) {
114
114
  });
115
115
  }
116
116
 
117
+ export async function permissionsAdded(input = {}) { return await readOptional(paths(input).receipt) !== null; }
118
+
117
119
  /** Re-read current settings and subtract only our additions; preserve all
118
120
  * preexisting rules and unrelated edits rather than restoring an old document.
119
121
  */
@@ -1,8 +1,10 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { Api, identifier } from './api.mjs';
3
3
  import { sensitive } from './detector.mjs';
4
- import { paired } from './local-commands.mjs';
5
- import { applyOptIns } from './opt-ins.mjs';
4
+ import { paired, revokedByServer, revokedText } from './local-commands.mjs';
5
+ import { applyChoices } from './choices.mjs';
6
+ import { businessCommand } from './invocation.mjs';
7
+ import { titledVendor, keyStep, keyed, vendorNames, vendorHandle } from './vendor-door.mjs';
6
8
 
7
9
  const protocolVersion = '2025-11-25';
8
10
  const headers = { Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': protocolVersion };
@@ -37,6 +39,57 @@ export async function nextQuestions(api, signal) {
37
39
  const ownerKinds = new Set(['signup.checkout','connect.cloudflare','connect.github','consent.grant','confirm.inventory','plan.review','wave.approve','switchoff.cancel','cutover.billing','rollback.billing']);
38
40
  export const ownerLink = state => `${state.origin}/business/${encodeURIComponent(identifier(state.businessId))}`;
39
41
 
42
+ // What this computer is waiting for, in the owner's terms. Until its own
43
+ // folder scan has finished, that is the owner's scan permission for the folder
44
+ // connect ran in; afterwards it is the owner's next step in the browser.
45
+ export function waitingFor(state) {
46
+ if (!state.discovered) {
47
+ const folder = state.workingFolder ?? process.cwd();
48
+ return `Waiting for the owner to allow scanning ${folder} (names only). They allow it on Your tools: ${ownerLink(state)}/tools`;
49
+ }
50
+ return `Waiting for the next task. Nothing needs this computer until the owner moves the plan forward: ${ownerLink(state)}`;
51
+ }
52
+ const runWork = { 'discover.local': "this computer's names-only scan of the folders the owner allowed" };
53
+ // The vendor tasks run performs into an app's import door, and what each one is, in the owner's terms.
54
+ const vendorSteps = {
55
+ 'export.vendor': name => `export the owner's ${name} history into its app's import door. It lands as a preview: nothing changes in the app until the owner approves it in the browser.`,
56
+ 'catchup.vendor': name => `bring the owner's recent ${name} changes into its app's import door as a catch-up. Within the owner's standing catch-up approval Business applies it; anything larger waits for the owner's approval in the browser.`,
57
+ 'switchoff.archive': name => `archive the owner's final ${name} export in its app's import door. The app keeps the exact file in its own storage and test-restores it with no writes; cancelling ${name} stays the owner's step.`,
58
+ };
59
+ const vendorStep = task => Object.hasOwn(vendorSteps, task.kind) && task.runner === 'executor' && ['ready', 'leased'].includes(task.state);
60
+ const agentQuestion = task => task.kind === 'classify.row' && task.runner === 'executor' && ['ready', 'leased'].includes(task.state);
61
+
62
+ // A move's owner steps: freezing the old tool, a rollback (its card when Business
63
+ // cannot undo the switch itself) and cancelling at the vendor. Each happens in the
64
+ // browser and is never this computer's agent work.
65
+ const moveSteps = {
66
+ 'freeze.vendor': name => `freeze ${name} (pause changes in it as the move page lists), then confirm the freeze there`,
67
+ rollback: () => 'follow the rollback card for this switch on the move page (Business undoes what it can itself and checks the rest)',
68
+ 'switchoff.cancel': name => `cancel ${name} at the vendor once the move is ready to cancel, then confirm it there (RER never contacts the vendor)`,
69
+ };
70
+ const moveStep = kind => typeof kind !== 'string' ? null : kind.startsWith('rollback.') ? moveSteps.rollback : ['freeze.vendor', 'switchoff.cancel'].includes(kind) ? moveSteps[kind] : null;
71
+ /** The move's page when the task names its tool, else the switch-over board (the Business home, which links each move). */
72
+ function moveLink(state, task) {
73
+ const tool = typeof task.tool_id === 'string' && /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,399}$/.test(task.tool_id) && !sensitive(task.tool_id) ? task.tool_id : null;
74
+ return tool ? `${ownerLink(state)}/moves/${encodeURIComponent(tool)}` : ownerLink(state);
75
+ }
76
+ /** A move's owner step in plain words with its link, or null. The vendor is named from a closed local table. */
77
+ export function ownerStep(task, state) {
78
+ const step = moveStep(task.kind);
79
+ if (!step) return null;
80
+ const vendor = titledVendor(task.kind, task.title);
81
+ return { words: step(vendor ? vendorNames[vendor] : 'the old tool'), link: moveLink(state, task) };
82
+ }
83
+ /** The owner steps of moves that Business lists, as what this computer waits for. */
84
+ export function ownerWaiting(tasks, state) {
85
+ return [...new Set(tasks.map(task => ownerStep(task, state)).filter(Boolean).map(step => `Waiting for the owner to ${step.words}: ${step.link}`))];
86
+ }
87
+
88
+ /** Agent steps that wait on this computer but not on run itself, in plain words. */
89
+ export function agentWaiting(tasks) {
90
+ return tasks.some(agentQuestion) ? [`A question waits for this computer's agent. Answer it with: ${businessCommand('next')}`] : [];
91
+ }
92
+
40
93
  function classification(task) {
41
94
  const toolId = identifier(task.question?.tool_id), vendorId = task.question?.vendor_id;
42
95
  const schema = task.question?.answer_schema, vendors = schema?.properties?.vendor_id?.enum;
@@ -51,17 +104,44 @@ function classification(task) {
51
104
 
52
105
  export async function next() {
53
106
  const signal = AbortSignal.timeout(55_000);
54
- const { state, credential } = await paired();
55
- const api = new Api(state.origin, credential);
56
- await applyOptIns(api, state, { report: false });
57
- const tasks = await nextQuestions(api, signal);
58
- const item = tasks.find(task => task.kind === 'classify.row' || task.runner === 'owner' || ownerKinds.has(task.kind));
59
- if (!item) { process.stdout.write('Nothing yet.\n'); return; }
107
+ const { state, credential } = await paired(), api = new Api(state.origin, credential);
108
+ let tasks;
109
+ try {
110
+ // Each check-in applies the owner's latest choices for this computer.
111
+ await applyChoices(api, state);
112
+ tasks = await nextQuestions(api, signal);
113
+ } catch (error) {
114
+ if (error.status !== 401) throw error;
115
+ throw Error(`Business pairing expired or was revoked. This computer was ${revokedText(await revokedByServer(state))}`);
116
+ }
117
+ // This computer's agent hears its own steps first, then the owner's.
118
+ const item = tasks.find(task => task.kind === 'classify.row' || vendorStep(task)) ?? tasks.find(task => task.runner === 'owner' || ownerKinds.has(task.kind) || moveStep(task.kind));
119
+ if (!item) {
120
+ // Nothing to answer here; say whether run has work, or what it waits for.
121
+ const work = tasks.find(task => Object.hasOwn(runWork, task.kind) && task.state === 'ready');
122
+ if (work) { process.stdout.write(`Ready for run: ${runWork[work.kind]}. Start it with: ${businessCommand('run')}\n`); return; }
123
+ process.stdout.write(`${waitingFor(state)}\nNothing yet.\n`); return;
124
+ }
60
125
  const id = identifier(item.task_id);
61
126
  if (sensitive(id)) throw Error('Business task identifier was refused by the outbound detector.');
127
+ const step = ownerStep(item, state);
128
+ if (step) {
129
+ process.stdout.write(`Owner: ${id}\nOwner step, not this computer's agent work: ${step.words}.\nIn the browser: ${step.link}\n`); return;
130
+ }
62
131
  if (item.runner === 'owner' || ownerKinds.has(item.kind)) {
63
132
  process.stdout.write(`Owner: ${id}\nAnswer in your browser: ${ownerLink(state)}\n`); return;
64
133
  }
134
+ if (Object.hasOwn(vendorSteps, item.kind)) {
135
+ // The vendor is named from a closed local table, never from server text.
136
+ const vendor = titledVendor(item.kind, item.title), name = vendor ? vendorNames[vendor] : 'vendor';
137
+ const stored = vendor && (state.vendorHandles ?? []).includes(vendorHandle(vendor));
138
+ process.stdout.write(`Agent: ${id}\nStep: ${vendorSteps[item.kind](name)}\n`
139
+ + (vendor && !keyed(vendor) ? `Vendor key: none; ${name} is read from its public page, with no key.\n`
140
+ : stored ? `Vendor key: the owner's read-only ${name} key is stored in this computer's OS credential storage. To replace it, ${keyStep(vendor)}\n`
141
+ : `Vendor key: ${keyStep(vendor)}${vendor ? '' : `\n where <vendor> is the tool this step reads: ${Object.keys(vendorNames).filter(keyed).join(' | ')}`}\n`)
142
+ + `Then run: ${businessCommand('run')}\n`);
143
+ return;
144
+ }
65
145
  const { toolId, vendorId, vendors } = classification(item);
66
146
  process.stdout.write(`Agent: ${id}\nTool: ${toolId}\nSuggested vendor: ${vendorId}\nVendors: ${vendors.join(' | ')}\nSuggest how this tool is used. The owner confirms in the browser.\nUsage: ${classifications.join(' | ')}\nRun: rer business answer ${id} <vendor_id|none> <usage> [confidence]\n`);
67
147
  }
@@ -75,7 +155,7 @@ export async function answer(id, vendorId, choice, rawConfidence = '1') {
75
155
  const confidence = Number(rawConfidence);
76
156
  const { state, credential } = await paired(), api = new Api(state.origin, credential), signal = AbortSignal.timeout(55_000);
77
157
  const summary = await (await mcpClient(api, { signal }))('explain_task', { task_id: id });
78
- if (summary.runner === 'owner' || ownerKinds.has(summary.kind)) throw Error(`This item requires the owner in the browser: ${ownerLink(state)}`);
158
+ if (summary.runner === 'owner' || ownerKinds.has(summary.kind) || moveStep(summary.kind)) throw Error(`This item requires the owner in the browser: ${ownerStep(summary, state)?.link ?? ownerLink(state)}`);
79
159
  if (summary.kind !== 'classify.row' || summary.runner !== 'executor') throw Error('This item does not accept a CLI classification answer.');
80
160
  const { vendors } = classification(summary);
81
161
  if (!vendors.includes(vendorId)) throw Error('Choose a catalog vendor id from this question, or none.');
@@ -0,0 +1,49 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { setupDemo } from './setup-demo.mjs';
4
+
5
+ // The platform command prints its receipt as JSON in both human and --json mode.
6
+ export async function setupCommand(args) {
7
+ try { return await setup(args) ?? 0; }
8
+ catch (error) {
9
+ // Paths, cookies and peer bodies must never appear in diagnostics.
10
+ const code=typeof error?.message==='string'&&/^[a-z0-9_]{1,100}$/.test(error.message)?error.message:'demo_setup_failed';
11
+ process.stderr.write(JSON.stringify({code})+'\n');return 1;
12
+ }
13
+ }
14
+
15
+ async function setup(args){
16
+ const usage='Usage: rer business setup --origin URL --session-file FILE --confirm-demo [--hosting managed|assisted|self_host] [--wait-seconds 0..240] [--json]';
17
+ if(args.some(arg => ['--help', '-h'].includes(arg))){process.stdout.write(usage+'\n');return;}
18
+ const options={};
19
+ for(let i=0;i<args.length;i++){
20
+ if(args[i]==='--json'&&!options.json){options.json=true;continue;}
21
+ if(args[i]==='--confirm-demo'){options.confirm=true;continue;}
22
+ if(!['--origin','--session-file','--hosting','--wait-seconds'].includes(args[i])||!args[i+1]||Object.hasOwn(options,args[i]))throw Error('demo_arguments_invalid');
23
+ options[args[i]]=args[++i];
24
+ }
25
+ if(!options.confirm||!options['--origin']||!options['--session-file'])throw Error('demo_confirmation_and_session_file_required');
26
+ const url=new URL(options['--origin']);
27
+ if(url.username||url.password||url.search||url.hash||url.pathname!=='/'||url.protocol!=='https:'&&!(url.protocol==='http:'&&['localhost','127.0.0.1','[::1]'].includes(url.hostname)))throw Error('demo_origin_invalid');
28
+ const hosting=options['--hosting']??'managed',waitSeconds=Number(options['--wait-seconds']??240);
29
+ if(!['managed','assisted','self_host'].includes(hosting)||!Number.isInteger(waitSeconds)||waitSeconds<0||waitSeconds>240)throw Error('demo_arguments_invalid');
30
+ const handle=await open(options['--session-file'],constants.O_RDONLY|constants.O_NOFOLLOW);
31
+ let cookie;
32
+ try{
33
+ const stat=await handle.stat();if(!stat.isFile()||(stat.mode&0o777)!==0o600||stat.uid!==process.getuid()||stat.size>16384)throw Error('demo_session_file_must_be_private');
34
+ cookie=(await handle.readFile('utf8')).trim();
35
+ }finally{await handle.close();}
36
+ if(!/^(?:__Host-)?rer_session=[^\s;]+$/.test(cookie))throw Error('demo_session_file_invalid');
37
+ const session=cookie.slice(cookie.indexOf('=')+1);
38
+ try {
39
+ const receipt=await setupDemo({origin:url.origin,cookie,hosting,waitSeconds});
40
+ const output=JSON.stringify(receipt,null,2)+'\n';
41
+ if(output.includes(session))throw Error('demo_session_in_response');
42
+ process.stdout.write(output);
43
+ if(receipt.complete !== true)return 1;
44
+ return 0;
45
+ } catch(error) {
46
+ if(String(error?.message).includes(session))throw Error('demo_session_in_response');
47
+ throw error;
48
+ }
49
+ }