@runeditrun/rer 0.2.84 → 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 (236) hide show
  1. package/README.md +156 -50
  2. package/cli/README.md +78 -2
  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/bounded.mjs +1 -1
  14. package/cli/business/archive-task.mjs +32 -0
  15. package/cli/business/carry.mjs +151 -0
  16. package/cli/business/catchup-task.mjs +42 -0
  17. package/cli/business/choices.mjs +97 -0
  18. package/cli/business/command.mjs +29 -6
  19. package/cli/business/connect.mjs +20 -8
  20. package/cli/business/detector.mjs +4 -1
  21. package/cli/business/device.mjs +13 -0
  22. package/cli/business/export-inputs.mjs +69 -0
  23. package/cli/business/export-task.mjs +17 -0
  24. package/cli/business/invocation.mjs +8 -1
  25. package/cli/business/keychain.mjs +8 -1
  26. package/cli/business/lease.mjs +11 -1
  27. package/cli/business/local-commands.mjs +80 -30
  28. package/cli/business/outbound.mjs +9 -4
  29. package/cli/business/parsers-config.mjs +8 -7
  30. package/cli/business/parsers-syntax.mjs +7 -3
  31. package/cli/business/permissions.mjs +2 -0
  32. package/cli/business/questions.mjs +89 -6
  33. package/cli/business/setup-command.mjs +49 -0
  34. package/cli/business/setup-company.json +15 -0
  35. package/cli/business/setup-demo.mjs +95 -0
  36. package/cli/business/state.mjs +44 -10
  37. package/cli/business/supervisor.mjs +97 -32
  38. package/cli/business/vendor-door.mjs +230 -0
  39. package/cli/business/vendors/README.md +29 -3
  40. package/cli/business/vendors/common.mjs +8 -6
  41. package/cli/business/vendors/index.mjs +22 -11
  42. package/cli/business/vendors/sorry.mjs +106 -0
  43. package/cli/container-transfer.mjs +2 -2
  44. package/cli/contract.mjs +7 -7
  45. package/cli/demo-deploy-error.mjs +14 -0
  46. package/cli/demo-native.mjs +6 -2
  47. package/cli/deploy-command.mjs +6 -4
  48. package/cli/deploy-config.mjs +1 -1
  49. package/cli/deploy-owner-input.mjs +3 -1
  50. package/cli/deploy-variables.mjs +58 -0
  51. package/cli/deploy.mjs +9 -7
  52. package/cli/door-clauses.mjs +157 -0
  53. package/cli/errors.mjs +1 -1
  54. package/cli/export.mjs +16 -4
  55. package/cli/hosted-output.mjs +17 -7
  56. package/cli/human-error.mjs +20 -0
  57. package/cli/inspect.mjs +4 -0
  58. package/cli/jsonc.mjs +8 -4
  59. package/cli/lifecycle.mjs +26 -6
  60. package/cli/main.mjs +2 -1
  61. package/cli/managed-data-schema.mjs +127 -0
  62. package/cli/managed-data-zip.mjs +116 -0
  63. package/cli/managed-data.mjs +110 -0
  64. package/cli/managed-server.mjs +25 -14
  65. package/cli/native-owner-entry.mjs +86 -0
  66. package/cli/output.mjs +3 -2
  67. package/cli/parse.mjs +2 -2
  68. package/cli/portability-empty.mjs +65 -0
  69. package/cli/portability-migrations.mjs +33 -9
  70. package/cli/portability-policy.mjs +5 -2
  71. package/cli/portability-worker.mjs +15 -6
  72. package/cli/portability.mjs +30 -8
  73. package/cli/production-auth.mjs +1 -1
  74. package/cli/production-mail.mjs +8 -2
  75. package/cli/ready-summary.mjs +9 -0
  76. package/cli/run-transfers.mjs +37 -0
  77. package/cli/runtime-front-door.mjs +4 -4
  78. package/cli/server-proxy.mjs +4 -3
  79. package/cli/server-registry.mjs +13 -8
  80. package/cli/site.mjs +6 -1
  81. package/cli/transfers.mjs +17 -4
  82. package/edition-authoring/archive-source.mjs +59 -0
  83. package/edition-authoring/base-copies.mjs +147 -25
  84. package/edition-authoring/cli.mjs +1 -1
  85. package/edition-authoring/edition-migrations.mjs +7 -3
  86. package/edition-authoring/module-closure.mjs +2 -16
  87. package/edition-authoring/workflow-copies.mjs +1 -1
  88. package/edition-authoring/workflow-scripts.mjs +12 -3
  89. package/foundation/runtime/contract-docs.mjs +218 -34
  90. package/foundation/runtime/contract-prose-patterns.mjs +14 -0
  91. package/foundation/runtime/contract-prose.mjs +88 -0
  92. package/foundation/runtime/run-data.d.mts +1 -0
  93. package/foundation/runtime/run-data.mjs +2 -0
  94. package/global/CHANGELOG.md +126 -0
  95. package/global/README.md +156 -50
  96. package/global/cli/command.mjs +8 -2
  97. package/global/cli/install.mjs +4 -5
  98. package/global/cli/path-link.mjs +3 -2
  99. package/global/cli/repo-command.mjs +3 -7
  100. package/global/door/command.mjs +3 -1
  101. package/global/launch/dev.mjs +12 -2
  102. package/global/launch/facts.mjs +2 -2
  103. package/global/launch/render.mjs +16 -9
  104. package/global/launch/state.mjs +4 -4
  105. package/global/main.mjs +13 -8
  106. package/install.sh +17 -6
  107. package/modules/agent-door/CLAUSES.md +215 -0
  108. package/modules/agent-door/conformance/audit.mjs +66 -0
  109. package/modules/agent-door/conformance/authority.d.mts +2 -0
  110. package/modules/agent-door/conformance/authority.mjs +17 -0
  111. package/modules/agent-door/conformance/crypto.mjs +36 -0
  112. package/modules/agent-door/conformance/discovery.mjs +61 -0
  113. package/modules/agent-door/conformance/index.mjs +41 -0
  114. package/modules/agent-door/conformance/invocation.mjs +32 -0
  115. package/modules/agent-door/conformance/journey.mjs +112 -0
  116. package/modules/agent-door/conformance/narrowing.d.mts +1 -0
  117. package/modules/agent-door/conformance/narrowing.mjs +21 -0
  118. package/modules/agent-door/conformance/negative.mjs +47 -0
  119. package/modules/agent-door/conformance/network-modules.mjs +86 -0
  120. package/modules/agent-door/conformance/network-runtime.mjs +46 -0
  121. package/modules/agent-door/conformance/policy-phases.mjs +75 -0
  122. package/modules/agent-door/conformance/protocol.mjs +145 -0
  123. package/modules/agent-door/conformance/replay.mjs +38 -0
  124. package/modules/agent-door/conformance/schema.mjs +71 -0
  125. package/modules/agent-door/conformance/security.mjs +33 -0
  126. package/modules/agent-door/conformance/sponsors.mjs +68 -0
  127. package/modules/agent-door/conformance/surface.mjs +89 -0
  128. package/modules/agent-door/conformance/target.mjs +18 -0
  129. package/modules/agent-door/conformance/tool-name.d.mts +1 -0
  130. package/modules/agent-door/conformance/tool-name.mjs +7 -0
  131. package/modules/agent-door/conformance/webhooks.mjs +30 -0
  132. package/modules/container/README.md +6 -1
  133. package/modules/container/adapters/d1-limits.mjs +286 -0
  134. package/modules/container/adapters/d1-sqlite.mjs +95 -0
  135. package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
  136. package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
  137. package/modules/container/adapters/d1-workerd.mjs +5 -0
  138. package/modules/container/adapters/sqlite-worker.mjs +5 -3
  139. package/modules/container/build.mjs +1 -0
  140. package/modules/container/image-variables.mjs +14 -3
  141. package/modules/container/transfer.mjs +14 -4
  142. package/modules/container/worker-engine.mjs +3 -3
  143. package/modules/demo-host/README.md +6 -0
  144. package/modules/demo-host/build.mjs +1 -0
  145. package/modules/demo-host/native/prepare.mjs +2 -1
  146. package/modules/demo-host/native/sql.mjs +7 -2
  147. package/modules/demo-host/ownership.mjs +39 -0
  148. package/modules/demo-host/plan.mjs +2 -1
  149. package/modules/demo-host/remove.mjs +6 -1
  150. package/modules/deploy-kit/README.md +22 -2
  151. package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
  152. package/modules/deploy-kit/d1-import.mjs +17 -5
  153. package/modules/deploy-kit/diagnostics.mjs +29 -3
  154. package/modules/deploy-kit/owner-cli.mjs +20 -7
  155. package/modules/deploy-kit/provider-transport.mjs +19 -4
  156. package/modules/deploy-kit/provider.mjs +57 -22
  157. package/modules/deploy-kit/readiness-window.mjs +1 -1
  158. package/modules/deploy-kit/site.mjs +8 -3
  159. package/modules/deploy-kit/worker.mjs +4 -4
  160. package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
  161. package/modules/import-kit/schema/importers.schema.json +107 -0
  162. package/modules/import-kit/src/d1/README.md +23 -4
  163. package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
  164. package/modules/import-kit/src/d1/budget.ts +15 -7
  165. package/modules/import-kit/src/d1/column-layout.ts +5 -0
  166. package/modules/import-kit/src/d1/creation.ts +15 -8
  167. package/modules/import-kit/src/d1/database.ts +3 -3
  168. package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
  169. package/modules/import-kit/src/d1/erasure.ts +2 -2
  170. package/modules/import-kit/src/d1/jobs.ts +10 -6
  171. package/modules/import-kit/src/d1/plans.ts +14 -8
  172. package/modules/import-kit/src/d1/retirement.ts +2 -2
  173. package/modules/import-kit/src/d1/sets.ts +1 -3
  174. package/modules/import-kit/src/d1/staged-creation.ts +3 -3
  175. package/modules/import-kit/src/door/ADOPTING.md +20 -0
  176. package/modules/import-kit/src/door/README.md +2 -1
  177. package/modules/import-kit/src/door/admission.ts +5 -3
  178. package/modules/import-kit/src/door/archive.ts +5 -2
  179. package/modules/import-kit/src/door/authority.ts +1 -0
  180. package/modules/import-kit/src/door/grants.ts +1 -1
  181. package/modules/import-kit/src/door/handler.ts +14 -8
  182. package/modules/import-kit/src/door/index.ts +1 -1
  183. package/modules/import-kit/src/door/jobs.ts +40 -0
  184. package/modules/import-kit/src/door/limits.ts +1 -1
  185. package/modules/import-kit/src/door/operator.ts +3 -3
  186. package/modules/import-kit/src/door/planning.ts +10 -6
  187. package/modules/import-kit/src/door/protocol.ts +2 -2
  188. package/modules/import-kit/src/door/raw.ts +25 -0
  189. package/modules/import-kit/src/door/refusals.ts +2 -1
  190. package/modules/import-kit/src/door/types.ts +26 -6
  191. package/modules/import-kit/src/receipt/encoding.ts +37 -0
  192. package/modules/import-kit/src/receipt/index.ts +69 -0
  193. package/modules/import-kit/src/receipt/policy.ts +24 -0
  194. package/modules/import-kit/src/receipt/types.ts +64 -0
  195. package/modules/import-kit/src/receipt/uri.ts +45 -0
  196. package/modules/import-kit/src/receipt/validation.ts +87 -0
  197. package/modules/import-kit/src/status/encoding.ts +13 -0
  198. package/modules/import-kit/src/status/evidence.ts +218 -0
  199. package/modules/import-kit/src/status/index.ts +56 -0
  200. package/modules/import-kit/src/status/schema.ts +208 -0
  201. package/modules/import-kit/src/status/types.ts +86 -0
  202. package/modules/operator-auth/accounts/delegated.mjs +48 -0
  203. package/modules/operator-auth/index.d.mts +7 -0
  204. package/modules/operator-auth/service.mjs +2 -0
  205. package/modules/portability/README.md +138 -9
  206. package/modules/portability/backfills.mjs +9 -8
  207. package/modules/portability/bridge.mjs +32 -5
  208. package/modules/portability/catalogue.mjs +12 -5
  209. package/modules/portability/copies.mjs +8 -1
  210. package/modules/portability/derived.mjs +33 -0
  211. package/modules/portability/files.mjs +4 -3
  212. package/modules/portability/http-errors.mjs +1 -1
  213. package/modules/portability/http.mjs +3 -3
  214. package/modules/portability/import.mjs +29 -13
  215. package/modules/portability/index.d.mts +4 -3
  216. package/modules/portability/index.mjs +1 -1
  217. package/modules/portability/ledgers.mjs +3 -2
  218. package/modules/portability/legacy-safety.mjs +11 -2
  219. package/modules/portability/migration-history.mjs +2 -2
  220. package/modules/portability/progress.mjs +1 -0
  221. package/modules/portability/restore-empty.mjs +12 -0
  222. package/modules/release/github-verify.mjs +11 -2
  223. package/onboarding/adapter.mjs +35 -6
  224. package/onboarding/app-fetch.mjs +6 -4
  225. package/onboarding/development-runtime.mjs +19 -0
  226. package/onboarding/local/operation.mjs +45 -27
  227. package/onboarding/loopback-fetch.mjs +16 -0
  228. package/onboarding/operator-installer.mjs +2 -4
  229. package/onboarding/process-diagnostics.mjs +6 -2
  230. package/onboarding/production-runtime.mjs +4 -2
  231. package/onboarding/readiness.mjs +1 -0
  232. package/package.json +4 -2
  233. package/scripts/publish-check/copy_identities.py +3 -1
  234. package/scripts/publish-check/github_refs.py +32 -13
  235. package/scripts/publish-check/public_hygiene.py +1 -1
  236. package/cli/business/opt-ins.mjs +0 -33
@@ -0,0 +1,97 @@
1
+ import { basename } from 'node:path';
2
+ import { installService, removeService } from './service.mjs';
3
+ import { installPermissions, removePermissions } from './permissions.mjs';
4
+ import { saveState } from './state.mjs';
5
+ import { carryLive } from './carry.mjs';
6
+ import { businessCommand } from './invocation.mjs';
7
+ import { describe } from './errors.mjs';
8
+
9
+ // The owner's choices for this computer, as the browser words them. The
10
+ // server's field names stay internal.
11
+ export const choices = {
12
+ installPermissions: 'Add rules so Claude Code never reads your secret files',
13
+ awakeConsent: 'Keep this computer awake while it works',
14
+ installService: 'Install the background service',
15
+ };
16
+ const names = Object.keys(choices);
17
+
18
+ const effects = {
19
+ installPermissions: { true: () => installPermissions({ consent: true }), false: () => removePermissions() },
20
+ awakeConsent: { true: async () => {}, false: async () => {} },
21
+ installService: { true: () => installService({ consent: true }), false: () => removeService() },
22
+ };
23
+ const said = {
24
+ installPermissions: { true: 'allowed; the rules are in Claude Code settings', false: 'not allowed; no rules added' },
25
+ awakeConsent: { true: 'allowed while an export runs', false: 'not allowed' },
26
+ installService: { true: 'allowed; the service is installed and works tasks after this chat ends', false: 'not allowed; no service installed' },
27
+ };
28
+
29
+ // What this process already told the person, so a long-running supervisor
30
+ // reports each refusal or open question once rather than on every check-in.
31
+ const reported = new Set();
32
+ const once = (key, text) => { if (reported.has(key)) return; reported.add(key); process.stdout.write(text); };
33
+
34
+ // Choices with no way to take effect for the agent on this computer. The rules
35
+ // are Claude Code's own settings, so they apply only when the computer's agent
36
+ // is Claude Code. For Codex, which has no equivalent Business can write yet, and
37
+ // for any other agent, nothing is written under ~/.claude and nothing asks for a
38
+ // run outside the sandbox. It is recorded and said once.
39
+ const notApplicable = {
40
+ installPermissions: {
41
+ codex: 'Secret-file rules do not apply on Codex: Business has no way yet to stop Codex from reading your secret files, so it added no rules and needs nothing more for this choice.\n',
42
+ other: 'Secret-file rules do not apply on this computer: Business writes them only for Claude Code, and this computer\'s agent is not Claude Code, so it added no rules and needs nothing more for this choice.\n',
43
+ },
44
+ };
45
+
46
+ /** Read the owner's choices (GET /executors/self) and apply each one that
47
+ * changed since this computer last applied it, then say which were applied.
48
+ * connect, run and next all call this, so connect never has to run again.
49
+ * A choice that cannot be applied here (an agent sandbox that cannot write
50
+ * outside its folder) is named with its cause and tried again next check-in.
51
+ */
52
+ export async function applyChoices(api, state, { reconnecting = false } = {}) {
53
+ let self;
54
+ // A server without this route answers a device credential with 403 (or 404):
55
+ // nothing is decided yet. On a new computer this first request activates it.
56
+ try { self = await api.get('/api/business/executors/self'); }
57
+ catch (error) { if (![403, 404].includes(error.status)) throw error; }
58
+ const carried = await carryLive(state, self);
59
+ const decided = Object.fromEntries(names.map(name => [name, typeof self?.optIns?.[name] === 'boolean' ? self.optIns[name] : null]));
60
+ // The agent this computer reported when it paired, as the owner's browser words its choices:
61
+ // the Claude Code rules apply only to Claude Code. An unknown agent (no route yet) decides nothing.
62
+ const agent = self?.device?.agent_kind?.value;
63
+ const inapplicable = Object.fromEntries(Object.entries(notApplicable).filter(() => agent && agent !== 'claude').map(([name, text]) => [name, text[agent] ?? text.other]));
64
+ const applied = state.applied ?? {}, lines = [], refused = [], unavailable = [];
65
+ let serviceInstalled = false;
66
+ for (const name of names) {
67
+ if (inapplicable[name]) {
68
+ if (applied[name] !== 'not-applicable') { applied[name] = 'not-applicable'; unavailable.push(inapplicable[name]); }
69
+ continue;
70
+ }
71
+ const choice = decided[name];
72
+ if (choice === null || applied[name] === choice) continue;
73
+ try {
74
+ await effects[name][choice]();
75
+ applied[name] = choice;
76
+ if (name === 'installService' && choice) serviceInstalled = true;
77
+ lines.push(` - ${choices[name]}: ${said[name][choice]}\n`);
78
+ } catch (error) { refused.push({ name, error }); }
79
+ }
80
+ state.applied = applied;
81
+ state.awakeConsent = applied.awakeConsent === true;
82
+ if (lines.length || unavailable.length) await saveState(state);
83
+ if (lines.length) process.stdout.write(`Applied the owner's choices for this computer:\n${lines.join('')}`);
84
+ for (const text of unavailable) process.stdout.write(text);
85
+ for (const { name, error } of refused) {
86
+ once(`refused:${name}:${error.message}`, `Not applied yet: ${choices[name]}. ${describe(error)} The run and next commands try again at each check-in; to apply it now, run ${businessCommand('next')} outside the agent sandbox or in your own terminal.\n`);
87
+ }
88
+ const undecided = names.filter(name => decided[name] === null && !inapplicable[name]);
89
+ if (undecided.length) {
90
+ once(`undecided:${undecided.join()}`, `The owner has not chosen yet:\n${undecided.map(name => ` - ${choices[name]}\n`).join('')}They choose on this computer's row in ${state.origin}/business/${encodeURIComponent(state.businessId)}/settings; the run and next commands apply the choices at their next check-in, ${reconnecting ? 'without pairing again' : 'so connect does not need to run again'}.\n`);
91
+ }
92
+ once('choices-next-step', `After choosing this computer's apps or settings in Business, run ${businessCommand('next')} to apply them and see the next task.\n`);
93
+ if (carried) once(`carry:${JSON.stringify(carried)}`, carried.checkouts.length
94
+ ? `Apps on this computer now show ${JSON.stringify(carried.name)}: ${carried.checkouts.map(checkout => JSON.stringify(basename(checkout))).join(', ')}.\n`
95
+ : `No apps on this computer were updated to show ${JSON.stringify(carried.name)}.\n`);
96
+ return { applied: lines.length, serviceInstalled };
97
+ }
@@ -1,3 +1,4 @@
1
+ import { setupCommand } from './setup-command.mjs';
1
2
  import { scanCommand } from './scan-command.mjs';
2
3
  import { connect } from './connect.mjs';
3
4
  import { vendorKey, disconnect, status } from './local-commands.mjs';
@@ -5,25 +6,47 @@ import { next, answer, token } from './questions.mjs';
5
6
  import { run } from './supervisor.mjs';
6
7
  import { describe } from './errors.mjs';
7
8
 
8
- const usage = `Usage: rer business VERB
9
+ const usage = `Set up your business: rer business connect
10
+ Business keeps your business name, logo and brand colour together for the apps
11
+ that support shared Business settings. Choose what to share in your browser.
12
+
13
+ Advanced commands (Usage: rer business VERB)
14
+ setup --origin URL --session-file FILE --confirm-demo
15
+ Provision the synthetic Run your business demo
16
+ --hosting managed|assisted|self_host (default: managed)
17
+ --wait-seconds 0..240 (default: 240); --json
9
18
  scan [DIR...] [--json] Names-only local discovery
10
19
  connect [--code CODE] [--origin URL]
11
20
  Pair this computer, waiting until the owner approves in the browser
12
21
  (up to the code's 10 minutes); run it again to resume
13
- run [--once] Run consented local discovery; vendor upload integration pending
14
- next Return one templated question or nothing yet within 60 seconds
22
+ Connect carries the Business name into local apps
23
+ run [--once] Work this computer's tasks: the folder scan the owner allows, then
24
+ vendor exports into each app's import door (a preview the owner
25
+ approves), catch-ups (applied within the owner's standing approval,
26
+ else reviewed by the owner) and the final archive the app keeps and
27
+ test-restores; the vendor key stays in OS credential storage. Says
28
+ what it is doing and waiting for; applies the owner's choices at
29
+ each check-in
30
+ next Apply the owner's choices, then return one templated question, the
31
+ agent's next step, an owner step with its browser link (freeze,
32
+ rollback card, cancellation; never agent work), or nothing yet
33
+ within 60 seconds
15
34
  answer ID VENDOR USAGE [CONFIDENCE]
16
35
  Catalog vendor or none; uses, sells, both, product-dependency
17
- vendor-key add|remove VENDOR Keep a vendor key in OS credential storage
36
+ vendor-key add|remove VENDOR Keep a read-only vendor key in OS credential storage; the owner
37
+ types it in their own terminal, never in chat or a command
18
38
  token MCP headersHelper output; send directly to the MCP client
19
39
  status [--json] Pairing, service, current task and checkpoint
20
- disconnect Revoke this computer, then remove local credentials and additions
21
- Vendors: sentry, uptimerobot, pagerduty, calendly. Owner approvals stay in the browser.
40
+ disconnect Revoke this computer, then remove local credentials and additions;
41
+ inside an agent sandbox it names the one command that finishes
42
+ Vendors: sentry, uptimerobot, pagerduty, calendly (with a read-only key); sorry (its public page,
43
+ no key). Owner approvals stay in the browser.
22
44
  State lives in $RER_BUSINESS_STATE_DIR when set, otherwise in ~/.rer/business.
23
45
  In an agent sandbox that writes only inside its working folder, use RER_BUSINESS_STATE_DIR="$PWD/.rer-business".
24
46
  `;
25
47
 
26
48
  export async function businessCommand(argv) {
49
+ if (argv[0] === 'setup') return setupCommand(argv.slice(1));
27
50
  if (!argv.length || argv[0] !== 'scan' && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(usage); return 0; }
28
51
  if (argv[0] === 'scan') return scanCommand(argv);
29
52
  try {
@@ -3,10 +3,11 @@ import { join } from 'node:path';
3
3
  import { Api, originUrl, identifier, pause } from './api.mjs';
4
4
  import { loadState, saveState, credentialHandle, loadPending, savePending, clearPending, checkStateWritable } from './state.mjs';
5
5
  import { createCredentialStore } from './keychain.mjs';
6
- import { applyOptIns } from './opt-ins.mjs';
7
- import { rerCommand } from './invocation.mjs';
6
+ import { applyChoices } from './choices.mjs';
7
+ import { rerCommand, businessCommand } from './invocation.mjs';
8
8
  import { Stopped } from './errors.mjs';
9
- import { deviceName, workingFolder } from './device.mjs';
9
+ import { agentKind, deviceName, workingFolder } from './device.mjs';
10
+ import { revokedText } from './local-commands.mjs';
10
11
 
11
12
  // Approval moves the server's pairing expiry to ten minutes after approval, and
12
13
  // approval can come up to the code's own expiry. Keep the pending pairing until
@@ -27,15 +28,16 @@ export async function connect({ code, origin } = {}) {
27
28
  let pending = await loadPending();
28
29
  origin = originUrl(origin ?? stored?.origin ?? pending?.origin);
29
30
  if (stored) {
31
+ if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}\nThen connect with a new code from ${stored.origin}/business.`);
30
32
  if (stored.origin !== origin) throw Error(`This computer is already connected to Business at ${stored.origin}. Run ${rerCommand()} business disconnect before connecting it elsewhere.`);
31
33
  const credential = await createCredentialStore().get(credentialHandle(origin));
32
34
  if (!credential) throw Error(`This computer's Business credential is missing from OS credential storage. Run ${rerCommand()} business disconnect, then connect again with a new code from ${origin}/business.`);
33
- await applyOptIns(new Api(origin, credential), stored);
35
+ await connected(new Api(origin, credential), stored, { reconnecting: true });
34
36
  return;
35
37
  }
36
38
  if (pending && Date.parse(pending.expires_at) <= Date.now()) { await clearPending(); pending = null; }
37
39
  if (pending && (pending.origin !== origin || code && pending.code !== code)) throw Error(`Business is already waiting for approval of another code${pending.origin === origin ? '' : ` at ${pending.origin}`}. Run ${rerCommand()} business connect to resume it, or ${rerCommand()} business disconnect to drop it before using another code.`);
38
- if (!pending && !code) throw Error(`Business needs a pairing code. Open ${origin}/business, then run ${rerCommand()} business connect --code CODE --origin ${origin}.`);
40
+ if (!pending && !code) throw Error(`Set up your business: Business shares your business name, logo and brand colour with apps that support it. Open ${origin}/business; sign up free there if you have no account. Choose what to share there. Back in this terminal, run this same command again with --code followed by the code you copied from that page.`);
39
41
  // Refuse before redeeming the one-use code or collecting an approval when this
40
42
  // session cannot keep the pairing or store the device credential.
41
43
  await checkStateWritable();
@@ -60,7 +62,7 @@ export async function connect({ code, origin } = {}) {
60
62
  const name = deviceName(), folder = workingFolder();
61
63
  const response = await api.post('/api/business/executors/pair', {
62
64
  code, ...(name ? { device_name: name } : {}), ...(folder ? { working_folder: folder } : {}),
63
- os: process.platform === 'darwin' ? 'macos' : 'linux', agent_kind: process.env.CODEX_HOME ? 'codex' : process.env.CLAUDECODE ? 'claude' : 'other', capabilities,
65
+ os: process.platform === 'darwin' ? 'macos' : 'linux', agent_kind: agentKind(), capabilities,
64
66
  }).catch(error => { throw error.status === 401 ? Error(`Business did not accept code ${code}: it has expired or was already used${error.reason ? ` (the server said: ${error.reason})` : ''}. Create a new code in ${origin}/business.`) : error; });
65
67
  const expires = Math.min(Date.now() + 600_000, Date.parse(response?.expires_at));
66
68
  if (response?.status !== 'pending_approval' || !/^\d{6}$/.test(response.confirmation_number) || typeof response.pairing_token !== 'string' || !response.pairing_token || !Number.isFinite(expires) || expires <= Date.now()) throw Error('Business server returned an invalid pairing response.');
@@ -84,13 +86,14 @@ export async function connect({ code, origin } = {}) {
84
86
  }
85
87
  if (result?.status === 'paired') {
86
88
  if (typeof result.device_credential !== 'string') throw Error('Business server returned an invalid device credential.');
87
- const state = { version: 1, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false };
89
+ const folder = workingFolder();
90
+ const state = { version: 1, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false, ...(folder ? { workingFolder: folder } : {}) };
88
91
  // No authenticated request (including activation) before both durable writes.
89
92
  await store.set(handle, result.device_credential);
90
93
  try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
91
94
  await clearPending();
92
95
  process.stdout.write('Approved. Device credential stored in OS credential storage.\n');
93
- await applyOptIns(new Api(origin, result.device_credential), state);
96
+ await connected(new Api(origin, result.device_credential), state);
94
97
  return;
95
98
  }
96
99
  if (['denied', 'refused', 'expired'].includes(result?.status)) {
@@ -110,6 +113,15 @@ export async function connect({ code, origin } = {}) {
110
113
  }
111
114
  }
112
115
 
116
+ // The first device-authenticated request activates the computer and applies
117
+ // the owner's choices; later choices reach it through run and next.
118
+ async function connected(api, state, options) {
119
+ const { serviceInstalled } = await applyChoices(api, state, options);
120
+ process.stdout.write(`This computer is connected to Business at ${state.origin}.\n`);
121
+ if (serviceInstalled || state.applied?.installService === true) process.stdout.write('The background service works tasks after this chat ends.\n');
122
+ process.stdout.write(`Run ${businessCommand('next')} to apply the owner's latest choices and see the next task.\n`);
123
+ }
124
+
113
125
  export function localRoot(path) {
114
126
  if (typeof path !== 'string' || !path || path.includes('\0')) throw Error('Task has an invalid consented scan root.');
115
127
  return path === '~' ? homedir() : path.startsWith('~/') ? join(homedir(), path.slice(2)) : path;
@@ -27,8 +27,11 @@ function highEntropy(text, tokens) {
27
27
  return false;
28
28
  }
29
29
 
30
+ /** A known credential shape (private keys, provider token prefixes, JWTs, SSH keys, certificates). */
31
+ export const credentialShaped = text => shapes.some(pattern => pattern.test(text));
32
+
30
33
  export function sensitive(text) {
31
- return shapes.some(pattern => pattern.test(text)) || highEntropy(text, /[A-Za-z0-9_+\/=\-]{24,}/g);
34
+ return credentialShaped(text) || highEntropy(text, /[A-Za-z0-9_+\/=\-]{24,}/g);
32
35
  }
33
36
 
34
37
  function sensitivePath(path) {
@@ -18,3 +18,16 @@ function loginName() { try { return userInfo().username; } catch { return ''; }
18
18
  export function workingFolder(folder = process.cwd()) {
19
19
  return typeof folder === 'string' && folder.startsWith('/') && folder.length <= 1000 && !/[\x00-\x1f\x7f]/.test(folder) ? folder : '';
20
20
  }
21
+
22
+ /** The agent running this command, as the pairing reports it. Codex sets
23
+ * CODEX_THREAD_ID (or CODEX_SANDBOX) in every command it runs, so those two mark
24
+ * a command Codex itself is running and win; Claude Code sets CLAUDECODE. Only
25
+ * then does CODEX_HOME count: it is a user setting Codex reads, and anyone who
26
+ * exports it in a shell profile passes it on to Claude Code and its commands, so
27
+ * it is no proof of Codex. Anything else is "other".
28
+ */
29
+ export function agentKind(env = process.env) {
30
+ if (env.CODEX_THREAD_ID || env.CODEX_SANDBOX) return 'codex';
31
+ if (env.CLAUDECODE) return 'claude';
32
+ return env.CODEX_HOME ? 'codex' : 'other';
33
+ }
@@ -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,25 +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
- import { rerCommand } from './invocation.mjs';
9
+ import { removeCarries } from './carry.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';
11
15
 
12
16
  export async function paired() {
13
17
  const state = await loadState();
14
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)}`);
15
20
  const credential = await createCredentialStore().get(credentialHandle(state.origin));
16
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.`);
17
22
  return { state, credential };
18
23
  }
19
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
+
20
72
  export async function vendorKey(action, vendor) {
21
- if (!['add', 'remove'].includes(action) || !VENDORS.includes(vendor)) throw Error('Choose add or remove and a shipped vendor: sentry, uptimerobot, pagerduty, calendly.');
22
- 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);
23
75
  if (action === 'add') {
24
76
  let secret = await readSecret();
25
77
  try { await store.set(handle, secret); } finally { secret = undefined; }
@@ -34,16 +86,10 @@ export async function vendorKey(action, vendor) {
34
86
 
35
87
  async function stopSupervisor(directory) {
36
88
  const lock = join(directory, 'run.lock');
37
- try { await lstat(lock); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
89
+ if (!await liveSupervisor(lock)) return;
38
90
  await writeFile(join(directory, 'disconnect'), '', { mode: 0o600 });
39
91
  for (let attempt = 0; attempt < 100; attempt++) {
40
- try {
41
- const pid = Number(await readFile(lock, 'utf8'));
42
- if (Number.isSafeInteger(pid) && pid > 0) {
43
- try { process.kill(pid, 0); }
44
- catch (error) { if (error.code !== 'ESRCH') throw error; await unlink(lock); return; }
45
- }
46
- } 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; }
47
93
  await pause(100);
48
94
  }
49
95
  throw Error('Business supervisor is still stopping. Retry disconnect shortly.');
@@ -57,8 +103,13 @@ async function revoke(origin, credential) {
57
103
  catch (error) { return error.status === 401 ? 'revoked' : [403, 404].includes(error.status) ? 'unsupported' : 'unconfirmed'; }
58
104
  }
59
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. */
60
111
  export async function disconnect() {
61
- const state = await loadState(), directory = stateDirectory();
112
+ const state = await loadState();
62
113
  const origin = state?.origin ?? (await loadPending())?.origin;
63
114
  const page = origin && (state?.businessId ? `${origin}/business/${encodeURIComponent(state.businessId)}/settings` : `${origin}/business`);
64
115
  const credential = state?.origin ? await createCredentialStore().get(credentialHandle(state.origin)) : null;
@@ -70,17 +121,16 @@ export async function disconnect() {
70
121
  return;
71
122
  }
72
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.`);
73
- await removeService();
74
- await stopSupervisor(directory);
75
- await removePermissions();
76
- if (state) {
77
- const store = createCredentialStore();
78
- for (const handle of state.vendorHandles ?? []) await store.delete(handle);
79
- 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;
80
130
  }
81
- await removeStateDirectory();
82
131
  process.stdout.write(revocation === 'revoked'
83
- ? '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'
84
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`);
85
135
  }
86
136
 
@@ -89,14 +139,14 @@ export async function status({ json = false } = {}) {
89
139
  if (!state) {
90
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;
91
141
  }
92
- const stored = state.origin && await createCredentialStore().get(credentialHandle(state.origin));
142
+ const stored = !state.revoked && state.origin && await createCredentialStore().get(credentialHandle(state.origin));
93
143
  const service = await serviceStatus();
94
- const active = (await loadProgress()).current;
144
+ const active = state.revoked ? null : (await loadProgress()).current;
95
145
  if (json) {
96
- 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');
97
147
  return;
98
148
  }
99
- process.stdout.write(`Business: ${stored ? 'paired' : 'credential missing'}.\nService: ${service.running ? 'running' : service.installed ? 'installed, stopped' : 'not installed'}.\n`);
100
- 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`);
101
151
  process.stdout.write(`Checkpoint: ${active?.checkpoint ? 'saved' : 'none'}${Number.isSafeInteger(active?.uploadedBytes) ? `; ${active.uploadedBytes} bytes uploaded` : ''}.\n`);
102
152
  }