@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.
- package/README.md +156 -50
- package/cli/README.md +78 -2
- package/cli/agent-door.mjs +149 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-mail.mjs +54 -0
- package/cli/agent-network.mjs +64 -0
- package/cli/agent-reviewers.mjs +110 -0
- package/cli/agent-secrets.mjs +23 -0
- package/cli/agent-sponsors.mjs +43 -0
- package/cli/agent-surface.mjs +34 -0
- package/cli/agent-webhooks.mjs +19 -0
- package/cli/authoring.mjs +2 -1
- package/cli/bounded.mjs +1 -1
- package/cli/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +151 -0
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +29 -6
- package/cli/business/connect.mjs +20 -8
- package/cli/business/detector.mjs +4 -1
- package/cli/business/device.mjs +13 -0
- package/cli/business/export-inputs.mjs +69 -0
- package/cli/business/export-task.mjs +17 -0
- package/cli/business/invocation.mjs +8 -1
- package/cli/business/keychain.mjs +8 -1
- package/cli/business/lease.mjs +11 -1
- package/cli/business/local-commands.mjs +80 -30
- package/cli/business/outbound.mjs +9 -4
- package/cli/business/parsers-config.mjs +8 -7
- package/cli/business/parsers-syntax.mjs +7 -3
- package/cli/business/permissions.mjs +2 -0
- package/cli/business/questions.mjs +89 -6
- package/cli/business/setup-command.mjs +49 -0
- package/cli/business/setup-company.json +15 -0
- package/cli/business/setup-demo.mjs +95 -0
- package/cli/business/state.mjs +44 -10
- package/cli/business/supervisor.mjs +97 -32
- package/cli/business/vendor-door.mjs +230 -0
- package/cli/business/vendors/README.md +29 -3
- package/cli/business/vendors/common.mjs +8 -6
- package/cli/business/vendors/index.mjs +22 -11
- package/cli/business/vendors/sorry.mjs +106 -0
- package/cli/container-transfer.mjs +2 -2
- package/cli/contract.mjs +7 -7
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +6 -2
- package/cli/deploy-command.mjs +6 -4
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +58 -0
- package/cli/deploy.mjs +9 -7
- package/cli/door-clauses.mjs +157 -0
- package/cli/errors.mjs +1 -1
- package/cli/export.mjs +16 -4
- package/cli/hosted-output.mjs +17 -7
- package/cli/human-error.mjs +20 -0
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +26 -6
- package/cli/main.mjs +2 -1
- package/cli/managed-data-schema.mjs +127 -0
- package/cli/managed-data-zip.mjs +116 -0
- package/cli/managed-data.mjs +110 -0
- package/cli/managed-server.mjs +25 -14
- package/cli/native-owner-entry.mjs +86 -0
- package/cli/output.mjs +3 -2
- package/cli/parse.mjs +2 -2
- package/cli/portability-empty.mjs +65 -0
- package/cli/portability-migrations.mjs +33 -9
- package/cli/portability-policy.mjs +5 -2
- package/cli/portability-worker.mjs +15 -6
- package/cli/portability.mjs +30 -8
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +8 -2
- package/cli/ready-summary.mjs +9 -0
- package/cli/run-transfers.mjs +37 -0
- package/cli/runtime-front-door.mjs +4 -4
- package/cli/server-proxy.mjs +4 -3
- package/cli/server-registry.mjs +13 -8
- package/cli/site.mjs +6 -1
- package/cli/transfers.mjs +17 -4
- package/edition-authoring/archive-source.mjs +59 -0
- package/edition-authoring/base-copies.mjs +147 -25
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/module-closure.mjs +2 -16
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +218 -34
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/foundation/runtime/run-data.d.mts +1 -0
- package/foundation/runtime/run-data.mjs +2 -0
- package/global/CHANGELOG.md +126 -0
- package/global/README.md +156 -50
- package/global/cli/command.mjs +8 -2
- package/global/cli/install.mjs +4 -5
- package/global/cli/path-link.mjs +3 -2
- package/global/cli/repo-command.mjs +3 -7
- package/global/door/command.mjs +3 -1
- package/global/launch/dev.mjs +12 -2
- package/global/launch/facts.mjs +2 -2
- package/global/launch/render.mjs +16 -9
- package/global/launch/state.mjs +4 -4
- package/global/main.mjs +13 -8
- package/install.sh +17 -6
- package/modules/agent-door/CLAUSES.md +215 -0
- package/modules/agent-door/conformance/audit.mjs +66 -0
- package/modules/agent-door/conformance/authority.d.mts +2 -0
- package/modules/agent-door/conformance/authority.mjs +17 -0
- package/modules/agent-door/conformance/crypto.mjs +36 -0
- package/modules/agent-door/conformance/discovery.mjs +61 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/invocation.mjs +32 -0
- package/modules/agent-door/conformance/journey.mjs +112 -0
- package/modules/agent-door/conformance/narrowing.d.mts +1 -0
- package/modules/agent-door/conformance/narrowing.mjs +21 -0
- package/modules/agent-door/conformance/negative.mjs +47 -0
- package/modules/agent-door/conformance/network-modules.mjs +86 -0
- package/modules/agent-door/conformance/network-runtime.mjs +46 -0
- package/modules/agent-door/conformance/policy-phases.mjs +75 -0
- package/modules/agent-door/conformance/protocol.mjs +145 -0
- package/modules/agent-door/conformance/replay.mjs +38 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +33 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/surface.mjs +89 -0
- package/modules/agent-door/conformance/target.mjs +18 -0
- package/modules/agent-door/conformance/tool-name.d.mts +1 -0
- package/modules/agent-door/conformance/tool-name.mjs +7 -0
- package/modules/agent-door/conformance/webhooks.mjs +30 -0
- package/modules/container/README.md +6 -1
- package/modules/container/adapters/d1-limits.mjs +286 -0
- package/modules/container/adapters/d1-sqlite.mjs +95 -0
- package/modules/container/adapters/d1-workerd-preload.mjs +19 -0
- package/modules/container/adapters/d1-workerd-setup.mjs +26 -0
- package/modules/container/adapters/d1-workerd.mjs +5 -0
- package/modules/container/adapters/sqlite-worker.mjs +5 -3
- package/modules/container/build.mjs +1 -0
- package/modules/container/image-variables.mjs +14 -3
- package/modules/container/transfer.mjs +14 -4
- package/modules/container/worker-engine.mjs +3 -3
- package/modules/demo-host/README.md +6 -0
- package/modules/demo-host/build.mjs +1 -0
- package/modules/demo-host/native/prepare.mjs +2 -1
- package/modules/demo-host/native/sql.mjs +7 -2
- package/modules/demo-host/ownership.mjs +39 -0
- package/modules/demo-host/plan.mjs +2 -1
- package/modules/demo-host/remove.mjs +6 -1
- package/modules/deploy-kit/README.md +22 -2
- package/modules/deploy-kit/d1-import-diagnostics.mjs +56 -0
- package/modules/deploy-kit/d1-import.mjs +17 -5
- package/modules/deploy-kit/diagnostics.mjs +29 -3
- package/modules/deploy-kit/owner-cli.mjs +20 -7
- package/modules/deploy-kit/provider-transport.mjs +19 -4
- package/modules/deploy-kit/provider.mjs +57 -22
- package/modules/deploy-kit/readiness-window.mjs +1 -1
- package/modules/deploy-kit/site.mjs +8 -3
- package/modules/deploy-kit/worker.mjs +4 -4
- package/modules/import-kit/schema/importer-verification-receipt.schema.json +171 -0
- package/modules/import-kit/schema/importers.schema.json +107 -0
- package/modules/import-kit/src/d1/README.md +23 -4
- package/modules/import-kit/src/d1/atomic-prefix.ts +2 -2
- package/modules/import-kit/src/d1/budget.ts +15 -7
- package/modules/import-kit/src/d1/column-layout.ts +5 -0
- package/modules/import-kit/src/d1/creation.ts +15 -8
- package/modules/import-kit/src/d1/database.ts +3 -3
- package/modules/import-kit/src/d1/erasure-pages.ts +2 -1
- package/modules/import-kit/src/d1/erasure.ts +2 -2
- package/modules/import-kit/src/d1/jobs.ts +10 -6
- package/modules/import-kit/src/d1/plans.ts +14 -8
- package/modules/import-kit/src/d1/retirement.ts +2 -2
- package/modules/import-kit/src/d1/sets.ts +1 -3
- package/modules/import-kit/src/d1/staged-creation.ts +3 -3
- package/modules/import-kit/src/door/ADOPTING.md +20 -0
- package/modules/import-kit/src/door/README.md +2 -1
- package/modules/import-kit/src/door/admission.ts +5 -3
- package/modules/import-kit/src/door/archive.ts +5 -2
- package/modules/import-kit/src/door/authority.ts +1 -0
- package/modules/import-kit/src/door/grants.ts +1 -1
- package/modules/import-kit/src/door/handler.ts +14 -8
- package/modules/import-kit/src/door/index.ts +1 -1
- package/modules/import-kit/src/door/jobs.ts +40 -0
- package/modules/import-kit/src/door/limits.ts +1 -1
- package/modules/import-kit/src/door/operator.ts +3 -3
- package/modules/import-kit/src/door/planning.ts +10 -6
- package/modules/import-kit/src/door/protocol.ts +2 -2
- package/modules/import-kit/src/door/raw.ts +25 -0
- package/modules/import-kit/src/door/refusals.ts +2 -1
- package/modules/import-kit/src/door/types.ts +26 -6
- package/modules/import-kit/src/receipt/encoding.ts +37 -0
- package/modules/import-kit/src/receipt/index.ts +69 -0
- package/modules/import-kit/src/receipt/policy.ts +24 -0
- package/modules/import-kit/src/receipt/types.ts +64 -0
- package/modules/import-kit/src/receipt/uri.ts +45 -0
- package/modules/import-kit/src/receipt/validation.ts +87 -0
- package/modules/import-kit/src/status/encoding.ts +13 -0
- package/modules/import-kit/src/status/evidence.ts +218 -0
- package/modules/import-kit/src/status/index.ts +56 -0
- package/modules/import-kit/src/status/schema.ts +208 -0
- package/modules/import-kit/src/status/types.ts +86 -0
- package/modules/operator-auth/accounts/delegated.mjs +48 -0
- package/modules/operator-auth/index.d.mts +7 -0
- package/modules/operator-auth/service.mjs +2 -0
- package/modules/portability/README.md +138 -9
- package/modules/portability/backfills.mjs +9 -8
- package/modules/portability/bridge.mjs +32 -5
- package/modules/portability/catalogue.mjs +12 -5
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/files.mjs +4 -3
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/http.mjs +3 -3
- package/modules/portability/import.mjs +29 -13
- package/modules/portability/index.d.mts +4 -3
- package/modules/portability/index.mjs +1 -1
- package/modules/portability/ledgers.mjs +3 -2
- package/modules/portability/legacy-safety.mjs +11 -2
- package/modules/portability/migration-history.mjs +2 -2
- package/modules/portability/progress.mjs +1 -0
- package/modules/portability/restore-empty.mjs +12 -0
- package/modules/release/github-verify.mjs +11 -2
- package/onboarding/adapter.mjs +35 -6
- package/onboarding/app-fetch.mjs +6 -4
- package/onboarding/development-runtime.mjs +19 -0
- package/onboarding/local/operation.mjs +45 -27
- package/onboarding/loopback-fetch.mjs +16 -0
- package/onboarding/operator-installer.mjs +2 -4
- package/onboarding/process-diagnostics.mjs +6 -2
- package/onboarding/production-runtime.mjs +4 -2
- package/onboarding/readiness.mjs +1 -0
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/scripts/publish-check/public_hygiene.py +1 -1
- package/cli/business/opt-ins.mjs +0 -33
|
@@ -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
|
-
|
|
19
|
-
|
|
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)
|
|
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)
|
|
83
|
-
entries.push({ path: child, value: literal(raw)
|
|
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,7 +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';
|
|
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';
|
|
5
8
|
|
|
6
9
|
const protocolVersion = '2025-11-25';
|
|
7
10
|
const headers = { Accept: 'application/json, text/event-stream', 'MCP-Protocol-Version': protocolVersion };
|
|
@@ -36,6 +39,57 @@ export async function nextQuestions(api, signal) {
|
|
|
36
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']);
|
|
37
40
|
export const ownerLink = state => `${state.origin}/business/${encodeURIComponent(identifier(state.businessId))}`;
|
|
38
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
|
+
|
|
39
93
|
function classification(task) {
|
|
40
94
|
const toolId = identifier(task.question?.tool_id), vendorId = task.question?.vendor_id;
|
|
41
95
|
const schema = task.question?.answer_schema, vendors = schema?.properties?.vendor_id?.enum;
|
|
@@ -50,15 +104,44 @@ function classification(task) {
|
|
|
50
104
|
|
|
51
105
|
export async function next() {
|
|
52
106
|
const signal = AbortSignal.timeout(55_000);
|
|
53
|
-
const { state, credential } = await paired();
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
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
|
+
}
|
|
57
125
|
const id = identifier(item.task_id);
|
|
58
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
|
+
}
|
|
59
131
|
if (item.runner === 'owner' || ownerKinds.has(item.kind)) {
|
|
60
132
|
process.stdout.write(`Owner: ${id}\nAnswer in your browser: ${ownerLink(state)}\n`); return;
|
|
61
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
|
+
}
|
|
62
145
|
const { toolId, vendorId, vendors } = classification(item);
|
|
63
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`);
|
|
64
147
|
}
|
|
@@ -72,7 +155,7 @@ export async function answer(id, vendorId, choice, rawConfidence = '1') {
|
|
|
72
155
|
const confidence = Number(rawConfidence);
|
|
73
156
|
const { state, credential } = await paired(), api = new Api(state.origin, credential), signal = AbortSignal.timeout(55_000);
|
|
74
157
|
const summary = await (await mcpClient(api, { signal }))('explain_task', { task_id: id });
|
|
75
|
-
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)}`);
|
|
76
159
|
if (summary.kind !== 'classify.row' || summary.runner !== 'executor') throw Error('This item does not accept a CLI classification answer.');
|
|
77
160
|
const { vendors } = classification(summary);
|
|
78
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
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"synthetic": true,
|
|
3
|
+
"name": "Juniper Harbor Software — Synthetic demo",
|
|
4
|
+
"profile": {
|
|
5
|
+
"display_name": "Juniper Harbor Software — Synthetic demo",
|
|
6
|
+
"legal_name": "Juniper Harbor Software Inc. (synthetic)",
|
|
7
|
+
"country": "US",
|
|
8
|
+
"state": "Delaware",
|
|
9
|
+
"state_of_organization": "Delaware",
|
|
10
|
+
"entity_type": "Corporation",
|
|
11
|
+
"currency": "USD",
|
|
12
|
+
"timezone": "America/New_York",
|
|
13
|
+
"brand_color": "#245943"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
// Mirrored from runeditrun/platform 0261033177e8e05284c037369ee9c3a85922a8aa, scripts/business/demo.mjs.
|
|
2
|
+
import { readFile } from 'node:fs/promises';
|
|
3
|
+
const company = JSON.parse(await readFile(new URL('./setup-company.json', import.meta.url), 'utf8'));
|
|
4
|
+
export const demoPolicy={schema:'rer-agent-policy/1',catalogue:'rer-agent-classes/1',rules:[
|
|
5
|
+
{id:'internal',class:'standard',do:'autonomous'},
|
|
6
|
+
{id:'context',class:'sensitive',do:'autonomous'},
|
|
7
|
+
{id:'owner',class:'*',do:'approval',approver:['role:owner'],wait:'P1D'},
|
|
8
|
+
],spend:{none:true}};
|
|
9
|
+
|
|
10
|
+
/** The only injectable boundary is HTTP. Tokens, cookies, policy envelopes and peer bodies never enter the receipt. */
|
|
11
|
+
export async function setupDemo({origin,cookie,hosting='managed',waitSeconds=240,fetch:request=globalThis.fetch,now=Date.now,wait=ms=>new Promise(resolve=>setTimeout(resolve,ms))}) {
|
|
12
|
+
const api=async(path,method='GET',body,token)=>{
|
|
13
|
+
let response;
|
|
14
|
+
try{response=await request(new URL(path,origin),{method,redirect:'manual',signal:AbortSignal.timeout(60000),headers:{Origin:origin,Cookie:cookie,'Content-Type':'application/json',...(token?{'X-RER-Demo-Seed-Token':token}:{})},...(body===undefined?{}:{body:JSON.stringify(body)})});}
|
|
15
|
+
catch{throw Error('platform_transport_unavailable');}
|
|
16
|
+
let answer;try{answer=await response.json();}catch{throw Error(`platform_http_${response.status}`);}
|
|
17
|
+
if(!response.ok){const code=answer?.code;throw Error(typeof code==='string'&&/^[a-z0-9_]{1,100}$/.test(code)?code:`platform_http_${response.status}`);}
|
|
18
|
+
return answer;
|
|
19
|
+
};
|
|
20
|
+
const businesses=(await api('/api/business')).businesses;
|
|
21
|
+
let business=businesses.find(row=>row.name===company.name);
|
|
22
|
+
if(!business){
|
|
23
|
+
business=(await api('/api/business','POST',{name:company.name,default_hosting:hosting,executor_preference:hosting==='self_host'?'local':'managed'})).business;
|
|
24
|
+
await api('/api/business/'+encodeURIComponent(business.id)+'/profile','PUT',company.profile);
|
|
25
|
+
}
|
|
26
|
+
if(business.default_hosting!==hosting)throw Error('existing_demo_hosting_differs');
|
|
27
|
+
const root='/api/business/'+encodeURIComponent(business.id),initial=await api(root+'/demo');
|
|
28
|
+
// Return exactly the same projection after the first successful run and on every repeat.
|
|
29
|
+
if(initial.complete)return initial;
|
|
30
|
+
const pending=initial.seeds.filter(seed=>seed.adopted&&!seed.complete);
|
|
31
|
+
if(!pending.length)return initial;
|
|
32
|
+
let policy=await api(root+'/agents/policy');
|
|
33
|
+
if(policy.paused)throw Error('demo_is_paused_resume_as_owner');
|
|
34
|
+
const errors=new Map(),credentials=new Map(),ready=pending.filter(seed=>seed.provisioned);
|
|
35
|
+
let waiting=pending.filter(seed=>!seed.provisioned);
|
|
36
|
+
if(waiting.length){
|
|
37
|
+
const plan=await api(root+'/demo/plan','POST',{confirmed:true});
|
|
38
|
+
if(plan.plan_id&&!plan.approved)await api(root+'/plans/'+encodeURIComponent(plan.plan_id)+'/approve','POST',{});
|
|
39
|
+
const deadline=now()+waitSeconds*1000;
|
|
40
|
+
do{
|
|
41
|
+
await api(root+'/demo/advance','POST',{});
|
|
42
|
+
const status=await api(root+'/demo'),apps=(await api(root+'/apps')).apps,next=[];
|
|
43
|
+
for(const seed of waiting){
|
|
44
|
+
const current=status.seeds.find(row=>row.app===seed.app),installed=apps.find(row=>row.app===seed.app);
|
|
45
|
+
if(current?.provisioned)ready.push(current);
|
|
46
|
+
else if(installed?.failure||installed?.stage==='failed')errors.set(seed.app,'M4 provisioning failed');
|
|
47
|
+
else if(installed?.waits?.length||installed?.answers_needed?.length)errors.set(seed.app,'M4 setup needs hosting, payment, domain or app answers');
|
|
48
|
+
else next.push(seed);
|
|
49
|
+
}
|
|
50
|
+
waiting=next;
|
|
51
|
+
if(waiting.length&&now()<deadline)await wait(Math.min(3000,Math.max(0,deadline-now())));
|
|
52
|
+
}while(waiting.length&&now()<deadline);
|
|
53
|
+
for(const seed of waiting)errors.set(seed.app,'Run the same command to resume provisioning');
|
|
54
|
+
}
|
|
55
|
+
const eligible=[];
|
|
56
|
+
for(const seed of ready){
|
|
57
|
+
try{
|
|
58
|
+
// This is the shared Business sender, not a demo-specific settings signer or transport.
|
|
59
|
+
const settings=await api(root+'/settings/deliver','POST',{});
|
|
60
|
+
const delivery=settings.deliveries.find(row=>row.installation_id===seed.installation_id);
|
|
61
|
+
if(!delivery||delivery.state!=='delivered')throw Error(delivery?.code??'settings_not_delivered');
|
|
62
|
+
if(policy.revision&&!seed.no_policy_refused)throw Error('no_policy_probe_requires_fresh_demo');
|
|
63
|
+
const issued=await api(root+'/agents/seed-token','POST',{seed:seed.app,installation_id:seed.installation_id,
|
|
64
|
+
agent:{id:'demo:'+business.id,name:'Synthetic demo setup'},scopes:seed.scopes});
|
|
65
|
+
credentials.set(seed.app,issued.access_token);
|
|
66
|
+
if(!policy.revision&&!seed.no_policy_refused)await api(root+'/demo/apps/'+encodeURIComponent(seed.app)+'/door','POST',{phase:'unset'},issued.access_token);
|
|
67
|
+
eligible.push(seed);
|
|
68
|
+
}catch(error){errors.set(seed.app,error.message);}
|
|
69
|
+
}
|
|
70
|
+
if(eligible.length&&!policy.revision){
|
|
71
|
+
let draft=policy.draft;
|
|
72
|
+
if(draft&&JSON.stringify(draft.document)!==JSON.stringify(demoPolicy))throw Error('existing_policy_draft_requires_owner_review');
|
|
73
|
+
if(!draft)draft=(await api(root+'/agents/policy/revisions','POST',{document:demoPolicy})).revision;
|
|
74
|
+
await api(root+'/agents/policy/revisions/'+draft.revision+'/confirm','POST',{digest:draft.document_sha256});
|
|
75
|
+
policy=await api(root+'/agents/policy');
|
|
76
|
+
}
|
|
77
|
+
const seeded=[];
|
|
78
|
+
for(const seed of eligible){
|
|
79
|
+
try{await api(root+'/demo/apps/'+encodeURIComponent(seed.app)+'/door','POST',{phase:'seed'},credentials.get(seed.app));seeded.push(seed);}
|
|
80
|
+
catch(error){errors.set(seed.app,error.message);}
|
|
81
|
+
}
|
|
82
|
+
if(seeded.length){
|
|
83
|
+
await api(root+'/pause','POST',{paused:true});
|
|
84
|
+
let allPaused=true;
|
|
85
|
+
for(const seed of seeded){
|
|
86
|
+
try{await api(root+'/demo/apps/'+encodeURIComponent(seed.app)+'/door','POST',{phase:'paused'},credentials.get(seed.app));}
|
|
87
|
+
catch(error){allPaused=false;errors.set(seed.app,error.message);}
|
|
88
|
+
}
|
|
89
|
+
if(allPaused)await api(root+'/pause','POST',{paused:false});
|
|
90
|
+
}
|
|
91
|
+
credentials.clear();
|
|
92
|
+
const receipt=await api(root+'/demo');
|
|
93
|
+
for(const seed of receipt.seeds)if(!seed.complete&&errors.has(seed.app))seed.cause=errors.get(seed.app);
|
|
94
|
+
return receipt;
|
|
95
|
+
}
|
package/cli/business/state.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { mkdir, readFile, readdir, writeFile, rename, chmod, open, unlink, rm, rmdir, lstat } from 'node:fs/promises';
|
|
1
|
+
import { mkdir, readFile, readdir, writeFile, rename, chmod, open, unlink, rm, rmdir, lstat, utimes } from 'node:fs/promises';
|
|
2
|
+
import { readFileSync, unlinkSync } from 'node:fs';
|
|
2
3
|
import { dirname, join, resolve } from 'node:path';
|
|
3
4
|
import { homedir } from 'node:os';
|
|
4
5
|
import { createHash, randomUUID } from 'node:crypto';
|
|
@@ -81,7 +82,15 @@ export async function checkStateWritable() {
|
|
|
81
82
|
|
|
82
83
|
// Files this CLI writes in its state folder. A folder named by RER_BUSINESS_STATE_DIR
|
|
83
84
|
// may hold other things, so only these are removed from it.
|
|
84
|
-
const owned = /^(?:(?:state|pairing|progress|permissions|service)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
|
|
85
|
+
const owned = /^(?:(?:state|pairing|progress|permissions|service|carried)\.json|run\.lock|disconnect|service(?:-error)?\.log|discovery-[A-Za-z0-9_.:-]+\.(?:json|tmp)|export-[0-9a-f]{32}\.bundle|.*[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.tmp(?:\.check)?)$/;
|
|
86
|
+
/** After a revocation whose local cleanup was refused, keep only what a later
|
|
87
|
+
* disconnect needs to finish: the state and the receipts of what remains. */
|
|
88
|
+
export async function removeWorkFiles(keep = ['state.json', 'permissions.json', 'service.json']) {
|
|
89
|
+
let entries;
|
|
90
|
+
try { entries = await readdir(stateDirectory()); } catch (error) { if (error.code === 'ENOENT') return; throw error; }
|
|
91
|
+
for (const name of entries) if (owned.test(name) && !keep.includes(name)) await rm(join(stateDirectory(), name), { force: true });
|
|
92
|
+
}
|
|
93
|
+
|
|
85
94
|
export async function removeStateDirectory() {
|
|
86
95
|
const directory = stateDirectory();
|
|
87
96
|
if (!chosenStateDirectory()) {
|
|
@@ -96,22 +105,47 @@ export async function removeStateDirectory() {
|
|
|
96
105
|
await rmdir(directory).catch(error => { if (!['ENOENT', 'ENOTEMPTY', 'EEXIST'].includes(error.code)) throw error; });
|
|
97
106
|
}
|
|
98
107
|
|
|
108
|
+
// run.lock holds the supervisor's process id, and its time is refreshed while
|
|
109
|
+
// it runs. A lock whose process is gone, or that has not been refreshed for
|
|
110
|
+
// two minutes (a process id a sandbox cannot check), is stale and replaced.
|
|
111
|
+
const lockFresh = 120_000;
|
|
112
|
+
export const lockPath = () => join(stateDirectory(), 'run.lock');
|
|
113
|
+
export async function liveSupervisor(path = lockPath()) {
|
|
114
|
+
let text, info;
|
|
115
|
+
try { [text, info] = await Promise.all([readFile(path, 'utf8'), lstat(path)]); }
|
|
116
|
+
catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
117
|
+
// A lock is written right after it is created; give an empty one a moment.
|
|
118
|
+
if (!text) return Date.now() - info.mtimeMs < 5_000 ? 'starting' : null;
|
|
119
|
+
const pid = Number(text);
|
|
120
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return null;
|
|
121
|
+
try { process.kill(pid, 0); }
|
|
122
|
+
catch (error) { if (error.code === 'ESRCH') return null; if (error.code !== 'EPERM') throw error; }
|
|
123
|
+
return Date.now() - info.mtimeMs > lockFresh ? null : pid;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Take run.lock, replacing a stale one. The returned release removes it; it is
|
|
127
|
+
* also removed on every exit of this process, including after a signal. */
|
|
99
128
|
export async function lockSupervisor() {
|
|
100
|
-
const directory = stateDirectory();
|
|
129
|
+
const directory = stateDirectory(), path = lockPath();
|
|
101
130
|
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
102
|
-
const path = join(directory, 'run.lock');
|
|
103
131
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
104
132
|
try {
|
|
105
133
|
const file = await open(path, 'wx', 0o600);
|
|
106
134
|
await file.writeFile(String(process.pid)); await file.close();
|
|
107
|
-
|
|
135
|
+
const refresh = setInterval(() => { const now = new Date(); utimes(path, now, now).catch(() => {}); }, 30_000);
|
|
136
|
+
refresh.unref();
|
|
137
|
+
const exit = () => { try { if (readFileSync(path, 'utf8') === String(process.pid)) unlinkSync(path); } catch { /* Already gone. */ } };
|
|
138
|
+
process.once('exit', exit);
|
|
139
|
+
const release = async () => { clearInterval(refresh); process.off('exit', exit); exit(); };
|
|
140
|
+
// A signal is often followed closely by SIGKILL (an agent closing its
|
|
141
|
+
// terminal), so a signal handler removes the lock synchronously at once.
|
|
142
|
+
release.now = exit;
|
|
143
|
+
return release;
|
|
108
144
|
} catch (error) {
|
|
109
145
|
if (error.code !== 'EEXIST') throw error;
|
|
110
|
-
const pid =
|
|
111
|
-
if (
|
|
112
|
-
|
|
113
|
-
catch (check) { if (check.code !== 'ESRCH') throw check; }
|
|
114
|
-
await unlink(path);
|
|
146
|
+
const pid = await liveSupervisor(path);
|
|
147
|
+
if (pid) throw Error(`A Business supervisor is already running for this computer${pid === 'starting' ? '' : ` (process ${pid})`}. Let it keep working, or stop it before starting another.`);
|
|
148
|
+
await unlink(path).catch(error => { if (error.code !== 'ENOENT') throw error; });
|
|
115
149
|
}
|
|
116
150
|
}
|
|
117
151
|
throw Error('Could not acquire Business supervisor lock.');
|