@runeditrun/rer 0.2.85 → 0.2.86
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +138 -29
- package/cli/README.md +61 -1
- 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/business/archive-task.mjs +32 -0
- package/cli/business/carry.mjs +3 -1
- package/cli/business/catchup-task.mjs +42 -0
- package/cli/business/choices.mjs +97 -0
- package/cli/business/command.mjs +23 -5
- package/cli/business/connect.mjs +19 -7
- 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 +79 -31
- 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 -9
- 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 +94 -35
- 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/contract.mjs +2 -2
- package/cli/demo-deploy-error.mjs +14 -0
- package/cli/demo-native.mjs +4 -1
- package/cli/deploy-config.mjs +1 -1
- package/cli/deploy-owner-input.mjs +3 -1
- package/cli/deploy-variables.mjs +58 -0
- package/cli/door-clauses.mjs +157 -0
- package/cli/export.mjs +16 -4
- package/cli/hosted-output.mjs +17 -7
- package/cli/inspect.mjs +4 -0
- package/cli/jsonc.mjs +8 -4
- package/cli/lifecycle.mjs +3 -1
- package/cli/main.mjs +1 -0
- package/cli/managed-data-schema.mjs +14 -1
- package/cli/portability-empty.mjs +6 -0
- package/cli/portability-migrations.mjs +26 -4
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +8 -2
- package/edition-authoring/archive-source.mjs +59 -0
- package/edition-authoring/base-copies.mjs +92 -18
- 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 +215 -32
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/global/CHANGELOG.md +93 -0
- package/global/README.md +138 -29
- package/global/door/command.mjs +3 -1
- package/global/main.mjs +1 -1
- 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/image-variables.mjs +8 -2
- package/modules/demo-host/README.md +6 -0
- 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/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/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/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 +1 -0
- 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 +32 -11
- package/modules/portability/bridge.mjs +22 -2
- package/modules/portability/copies.mjs +8 -1
- package/modules/portability/derived.mjs +33 -0
- package/modules/portability/http-errors.mjs +1 -1
- package/modules/portability/import.mjs +14 -7
- package/package.json +4 -2
- package/scripts/publish-check/copy_identities.py +3 -1
- package/scripts/publish-check/github_refs.py +32 -13
- package/cli/business/opt-ins.mjs +0 -37
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { contained } from './project.mjs';
|
|
5
|
+
import { RerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const invalid = () => new RerError('agent_reviewer_invalid', 'verification.reviewers must name at most eight unique {label,email,initializer} native reviewer lifecycles.', 1);
|
|
8
|
+
const failed = () => new RerError('agent_reviewer_failed', 'The native reviewer lifecycle did not return its confirmed session through the disposable installation.', 1);
|
|
9
|
+
const canonicalEmail = value => typeof value === 'string' && value === value.trim().toLowerCase() && /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(value);
|
|
10
|
+
const mailboxAge = 300_000, maxBytes = 65_536, maxMessages = 20;
|
|
11
|
+
const mailProvider = request => {
|
|
12
|
+
const url = new URL(request.url);
|
|
13
|
+
return request.method !== 'POST' ? null : url.origin === 'https://api.resend.com' && url.pathname === '/emails' ? 'resend'
|
|
14
|
+
: url.origin === 'https://api.sendgrid.com' && url.pathname === '/v3/mail/send' ? 'sendgrid'
|
|
15
|
+
: url.origin === 'https://api.cloudflare.com' && /^\/client\/v4\/accounts\/[^/]+\/email\/sending\/send$/.test(url.pathname) ? 'cloudflare' : null;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** Test tooling only: observe accepted paid mail edges for explicitly declared
|
|
19
|
+
* reviewers. Native invitation, proof consumption and authority stay in the app. */
|
|
20
|
+
export async function verificationReviewers(root, declaration, ownerEmail) {
|
|
21
|
+
const entries = new Map(), messages = [], completed = new Set(), attempted = new Set();
|
|
22
|
+
let closed = false;
|
|
23
|
+
if (declaration !== undefined) {
|
|
24
|
+
if (!Array.isArray(declaration) || !declaration.length || declaration.length > 8) throw invalid();
|
|
25
|
+
for (const value of declaration) {
|
|
26
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key => !['label', 'email', 'initializer'].includes(key))
|
|
27
|
+
|| !/^[a-z][a-z0-9-]{0,63}$/.test(value.label) || !canonicalEmail(value.email) || value.email === ownerEmail
|
|
28
|
+
|| entries.has(value.label) || [...entries.values()].some(entry => entry.email === value.email) || typeof value.initializer !== 'string') throw invalid();
|
|
29
|
+
await contained(root, value.initializer);
|
|
30
|
+
let initialize;
|
|
31
|
+
try { initialize = (await import(pathToFileURL(resolve(root, value.initializer)))).default; }
|
|
32
|
+
catch { throw invalid(); }
|
|
33
|
+
if (typeof initialize !== 'function') throw invalid();
|
|
34
|
+
entries.set(value.label, { ...value, initialize });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function prune() {
|
|
38
|
+
const cutoff = Date.now() - mailboxAge;
|
|
39
|
+
for (let i = messages.length - 1; i >= 0; i--) if (messages[i].at < cutoff) messages.splice(i, 1);
|
|
40
|
+
}
|
|
41
|
+
function read(email, options = {}) {
|
|
42
|
+
if (closed || !options || typeof options !== 'object' || Array.isArray(options) || Object.keys(options).some(key => !['limit', 'maxAgeMs', 'after'].includes(key))) throw failed();
|
|
43
|
+
const { limit = 10, maxAgeMs = mailboxAge, after = 0 } = options;
|
|
44
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > maxMessages || !Number.isInteger(maxAgeMs) || maxAgeMs < 1 || maxAgeMs > mailboxAge || !Number.isFinite(after) || after < 0) throw failed();
|
|
45
|
+
prune();
|
|
46
|
+
return messages.filter(message => message.to.includes(email) && message.at >= Math.max(after, Date.now() - maxAgeMs))
|
|
47
|
+
.slice(-limit).map(({ to: _to, ...message }) => ({ ...message }));
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
observes: request => !closed && entries.size > 0 && mailProvider(request) !== null,
|
|
51
|
+
// Read only clones, and never expose headers, provider credentials or another
|
|
52
|
+
// mailbox. A rejected submission cannot become a delivered invitation.
|
|
53
|
+
async capture(request, response) {
|
|
54
|
+
if (closed || !entries.size || request.method !== 'POST' || !response.ok) return;
|
|
55
|
+
const provider = mailProvider(request);
|
|
56
|
+
if (!provider || Number(request.headers.get('content-length')) > maxBytes) return;
|
|
57
|
+
const reader = request.body?.getReader();
|
|
58
|
+
if (!reader) return;
|
|
59
|
+
const chunks = []; let bytes = 0;
|
|
60
|
+
try {
|
|
61
|
+
for (;;) {
|
|
62
|
+
const { done, value } = await reader.read();
|
|
63
|
+
if (done) break;
|
|
64
|
+
bytes += value.byteLength;
|
|
65
|
+
if (bytes > maxBytes) { void reader.cancel().catch(() => {}); return; }
|
|
66
|
+
chunks.push(value);
|
|
67
|
+
}
|
|
68
|
+
} finally { reader.releaseLock(); }
|
|
69
|
+
let body, acknowledgement;
|
|
70
|
+
try {
|
|
71
|
+
body = JSON.parse(await new Blob(chunks).text());
|
|
72
|
+
if (provider !== 'sendgrid') acknowledgement = await response.json();
|
|
73
|
+
} catch { return; }
|
|
74
|
+
if (closed) return;
|
|
75
|
+
if (provider === 'resend' && typeof acknowledgement?.id !== 'string'
|
|
76
|
+
|| provider === 'sendgrid' && response.status !== 202
|
|
77
|
+
|| provider === 'cloudflare' && acknowledgement?.success !== true) return;
|
|
78
|
+
const array = value => Array.isArray(value) ? value : value ? [value] : [];
|
|
79
|
+
const recipients = provider === 'sendgrid' ? array(body?.personalizations).flatMap(item => array(item?.to).map(to => to?.email)) : array(body?.to);
|
|
80
|
+
const to = [...entries.values()].map(entry => entry.email).filter(email => recipients.includes(email)
|
|
81
|
+
&& (provider !== 'cloudflare' || array(acknowledgement.result?.accepted).includes(email)));
|
|
82
|
+
if (!to.length) return;
|
|
83
|
+
const content = provider === 'sendgrid' ? array(body?.content) : [];
|
|
84
|
+
const text = provider === 'sendgrid' ? content.find(item => item?.type === 'text/plain')?.value : body?.text;
|
|
85
|
+
const html = provider === 'sendgrid' ? content.find(item => item?.type === 'text/html')?.value : body?.html;
|
|
86
|
+
prune();
|
|
87
|
+
messages.push({ id: randomUUID(), at: Date.now(), to, subject: typeof body?.subject === 'string' ? body.subject : '',
|
|
88
|
+
text: typeof text === 'string' ? text : '', html: typeof html === 'string' ? html : '' });
|
|
89
|
+
if (messages.length > maxMessages) messages.shift();
|
|
90
|
+
},
|
|
91
|
+
async initialize(label, owner, { request, origin, returnTo = '/' }) {
|
|
92
|
+
if (closed || !entries.has(label) || attempted.has(label) || !owner || typeof owner.cookie !== 'string' || !owner.cookie || owner.cookie.length > 16_384) throw failed();
|
|
93
|
+
attempted.add(label);
|
|
94
|
+
const entry = entries.get(label);
|
|
95
|
+
try {
|
|
96
|
+
const response = await entry.initialize({ request, origin, label, email: entry.email, owner: { email: ownerEmail, cookie: owner.cookie },
|
|
97
|
+
returnTo, mail: Object.freeze({ read: options => read(entry.email, options) }) });
|
|
98
|
+
if (closed || !(response instanceof Response) || response.status !== 303 || response.redirected) throw failed();
|
|
99
|
+
const cookie = response.headers.getSetCookie().map(value => value.split(';', 1)[0]).join('; ');
|
|
100
|
+
await response.body?.cancel();
|
|
101
|
+
if (!cookie || cookie === owner.cookie) throw failed();
|
|
102
|
+
completed.add(label);
|
|
103
|
+
return { email: entry.email, cookie };
|
|
104
|
+
} catch { throw failed(); }
|
|
105
|
+
},
|
|
106
|
+
points: () => [...entries.keys()].map(label => ({ id: `BASE-AGENT-001.reviewer.${label}.native-session`, ok: completed.has(label),
|
|
107
|
+
...(!completed.has(label) ? { detail: 'Declared native reviewer lifecycle did not complete.' } : {}) })),
|
|
108
|
+
close() { closed = true; messages.length = 0; },
|
|
109
|
+
};
|
|
110
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { contained } from './project.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
// Trusted test tooling gets only this disposable installation's declared D1
|
|
7
|
+
// handles. Neither the accessor nor its values become an application route.
|
|
8
|
+
export async function verificationSecrets(root, source, database) {
|
|
9
|
+
if (source === undefined) return {};
|
|
10
|
+
try {
|
|
11
|
+
if (typeof source !== 'string' || !source.endsWith('.mjs')) throw new Error();
|
|
12
|
+
await contained(root, source);
|
|
13
|
+
const read = (await import(pathToFileURL(resolve(root, source)))).default;
|
|
14
|
+
if (typeof read !== 'function') throw new Error();
|
|
15
|
+
const values = await read({ database });
|
|
16
|
+
if (!values || typeof values !== 'object' || Array.isArray(values) || !Object.keys(values).length
|
|
17
|
+
|| Object.entries(values).some(([key, value]) => !/^[A-Z][A-Z0-9_]{0,63}$/.test(key) || typeof value !== 'string' || !value || value.length > 16384)) throw new Error();
|
|
18
|
+
return values;
|
|
19
|
+
} catch {
|
|
20
|
+
// Accessor errors may contain a secret or a database row. Never report them.
|
|
21
|
+
throw new RerError('agent_secret_source_invalid', 'verification.network.secretSource must be a contained .mjs accessor returning nonempty named string secrets from the disposable installation.', 1);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { resolve } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { contained } from './project.mjs';
|
|
5
|
+
import { RerError } from './errors.mjs';
|
|
6
|
+
|
|
7
|
+
const defaultEmail = 'synthetic-base-1@example.com';
|
|
8
|
+
const ownerBindingValues = ['issuer', 'installationId', 'appOrigin', 'publicKeys', 'email', 'sub', 'token', 'sessionSecret'];
|
|
9
|
+
|
|
10
|
+
export async function verificationOwner(root, value = {}) {
|
|
11
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
12
|
+
|| Object.keys(value).some(key => !['email', 'emailField', 'tokenField', 'bindings', 'initializer'].includes(key))) throw new RerError('agent_owner_invalid', 'verification.owner must declare only email, emailField, tokenField, bindings and initializer.', 1);
|
|
13
|
+
const email = value.email ?? defaultEmail;
|
|
14
|
+
if (typeof email !== 'string' || email !== email.trim().toLowerCase() || !/^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/.test(email)) throw new RerError('agent_owner_invalid', 'verification.owner.email must be a canonical owner email.', 1);
|
|
15
|
+
for (const key of ['emailField', 'tokenField']) if (value[key] !== undefined && !/^[A-Z][A-Z0-9_]{0,63}$/.test(value[key])) throw new RerError('agent_owner_invalid', `verification.owner.${key} must name a production binding.`, 1);
|
|
16
|
+
if (value.bindings !== undefined && (!value.bindings || typeof value.bindings !== 'object' || Array.isArray(value.bindings)
|
|
17
|
+
|| Object.entries(value.bindings).some(([name, source]) => !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name) || !ownerBindingValues.includes(source)))) throw new RerError('agent_owner_invalid', `verification.owner.bindings must map native binding names to ${ownerBindingValues.join(', ')}.`, 1);
|
|
18
|
+
let initialize;
|
|
19
|
+
if (value.initializer !== undefined) {
|
|
20
|
+
await contained(root, value.initializer);
|
|
21
|
+
initialize = (await import(pathToFileURL(resolve(root, value.initializer)))).default;
|
|
22
|
+
if (typeof initialize !== 'function') throw new RerError('agent_owner_invalid', 'verification.owner.initializer must default-export an async owner initializer.', 1);
|
|
23
|
+
}
|
|
24
|
+
return { ...value, email, initialize };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function verificationSponsors(root, verification) {
|
|
28
|
+
const owner = verification.owner ?? {};
|
|
29
|
+
if (verification.sponsors === undefined) return [{ ...await verificationOwner(root, owner), sub: randomUUID() }];
|
|
30
|
+
const values = verification.sponsors;
|
|
31
|
+
if (!Array.isArray(values) || !values.length || values.length > 16) throw new RerError('agent_sponsors_invalid', 'verification.sponsors must contain one to sixteen labelled principals.', 1);
|
|
32
|
+
const labels = new Set(), emails = new Set(), result = [];
|
|
33
|
+
for (const [index, value] of values.entries()) {
|
|
34
|
+
if (!value || typeof value !== 'object' || typeof value.label !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value.label) || labels.has(value.label)) throw new RerError('agent_sponsors_invalid', 'Every verification sponsor needs a unique stable label.', 1);
|
|
35
|
+
const { label, role = 'member', ...declaration } = value;
|
|
36
|
+
if (!['admin', 'member'].includes(role)) throw new RerError('agent_sponsors_invalid', 'Additional sponsor roles must be admin or member.', 1);
|
|
37
|
+
const native = await verificationOwner(root, { ...(index === 0 ? owner : {}), ...declaration });
|
|
38
|
+
if (emails.has(native.email) || index > 0 && !native.initialize) throw new RerError('agent_sponsors_invalid', 'Additional verification sponsors need distinct emails and a native lifecycle initializer.', 1);
|
|
39
|
+
labels.add(label); emails.add(native.email);
|
|
40
|
+
result.push({ ...native, label, role, sub: randomUUID() });
|
|
41
|
+
}
|
|
42
|
+
return result;
|
|
43
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { validateAgentSurface } from '../modules/agent-door/conformance/surface.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
/** Read only edition declarations; never import the application's tool code. */
|
|
7
|
+
export async function readAgentSurface(root) {
|
|
8
|
+
let source;
|
|
9
|
+
try { source = await readFile(join(root, 'agent-surface.json'), 'utf8'); }
|
|
10
|
+
catch (error) {
|
|
11
|
+
if (error.code === 'ENOENT') return undefined;
|
|
12
|
+
throw new RerError('agent_surface_invalid', 'Cannot read agent-surface.json. Restore the edition\'s agent declaration.', 1);
|
|
13
|
+
}
|
|
14
|
+
let surface;
|
|
15
|
+
try { surface = JSON.parse(source); }
|
|
16
|
+
catch { throw new RerError('agent_surface_invalid', 'agent-surface.json must contain valid JSON.', 1); }
|
|
17
|
+
let contract;
|
|
18
|
+
try { contract = await readFile(join(root, 'CONTRACT.md'), 'utf8'); }
|
|
19
|
+
catch (error) { if (error.code !== 'ENOENT') throw new RerError('agent_surface_invalid', 'Cannot read CONTRACT.md to check the agent surface clauses.', 1); }
|
|
20
|
+
return { surface, contract };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export async function agentSurfaceClauses(root) {
|
|
24
|
+
let declaration;
|
|
25
|
+
try { declaration = await readAgentSurface(root); }
|
|
26
|
+
catch (error) {
|
|
27
|
+
if (!(error instanceof RerError)) throw error;
|
|
28
|
+
return [{ id: 'SC-14.agents.declaration', ok: false, message: error.message }];
|
|
29
|
+
}
|
|
30
|
+
if (!declaration) return [{ id: 'SC-14.agents.undeclared', ok: true }];
|
|
31
|
+
return validateAgentSurface(declaration.surface, { contract: declaration.contract }).points.map(({ id, ok, detail }) => ({
|
|
32
|
+
id: `SC-14.agents.${id}`, ok, ...(!ok ? { message: detail } : {}),
|
|
33
|
+
}));
|
|
34
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { resolve } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
import { contained } from './project.mjs';
|
|
4
|
+
import { RerError } from './errors.mjs';
|
|
5
|
+
|
|
6
|
+
export async function verificationWebhooks(root, config, secrets) {
|
|
7
|
+
if (config === undefined) return undefined;
|
|
8
|
+
try {
|
|
9
|
+
if (!config || typeof config !== 'object' || Array.isArray(config) || Object.keys(config).some(key => !['module', 'prepare'].includes(key))
|
|
10
|
+
|| typeof config.module !== 'string' || !Array.isArray(config.prepare) || !config.prepare.length || !config.prepare.every(value => typeof value === 'string')) throw new Error();
|
|
11
|
+
await contained(root, config.module);
|
|
12
|
+
const build = (await import(pathToFileURL(resolve(root, config.module)))).default;
|
|
13
|
+
if (typeof build !== 'function') throw new Error();
|
|
14
|
+
return { prepare: config.prepare, requests: async context => {
|
|
15
|
+
try { return await build({ ...context, secrets }); }
|
|
16
|
+
catch { throw new Error('The seed webhook request builder could not construct its per-run signature probes.'); }
|
|
17
|
+
} };
|
|
18
|
+
} catch { throw new RerError('agent_webhooks_invalid', 'verification.webhooks must name a contained request-builder module and preparation journey steps.', 1); }
|
|
19
|
+
}
|
package/cli/authoring.mjs
CHANGED
|
@@ -9,7 +9,8 @@ export function authoringCommand(options) {
|
|
|
9
9
|
return options.verb === 'adopt-edition' ? adoptEdition(options.cwd) : refreshCopies(options.cwd, copyOptions([
|
|
10
10
|
...(options.editionMigration ? options.editionMigration.split(',').flatMap(id => ['--edition-migration', id]) : []),
|
|
11
11
|
options.ref, '--record', options.record ?? 'base-copies.json',
|
|
12
|
-
...(options.base ? ['--base', resolve(options.cwd, options.base)] : []),
|
|
12
|
+
...(options.base ? ['--base', resolve(options.cwd, options.base)] : []),
|
|
13
|
+
...(options.baseArchive ? ['--base-archive', resolve(options.cwd, options.baseArchive)] : []), ...(options.offline ? ['--offline'] : []),
|
|
13
14
|
], 1));
|
|
14
15
|
} catch (error) { throw refuse(error.message); }
|
|
15
16
|
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { withUploadedBundle, door, DOOR_ID, count, plural } from './vendor-door.mjs';
|
|
2
|
+
|
|
3
|
+
// Key order is not part of the door's counts; compare them as values.
|
|
4
|
+
const stable = value => JSON.stringify(value, (_, item) => item && typeof item === 'object' && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Perform a claimed switchoff.archive: the vendor's final export uploaded into
|
|
8
|
+
* the app's import door, kept there by the door's `archive` action as the tool's
|
|
9
|
+
* archive in the app's own storage (`business-archive/<tool>/<takenAt>`, the tool
|
|
10
|
+
* being the vendor's namespace), then read back by the door's `restore-check`,
|
|
11
|
+
* which parses it and writes nothing native. Run checks that the archive and its
|
|
12
|
+
* test-restore are exactly this bundle, then completes with the archive_id and
|
|
13
|
+
* the bundle's SHA-256; Business runs its own restore-check before the task is
|
|
14
|
+
* done. Returns the line to say.
|
|
15
|
+
*/
|
|
16
|
+
export function runArchive({ lease, task, grant, directory, say, ownerPage }) {
|
|
17
|
+
const takenAt = new Date().toISOString();
|
|
18
|
+
return withUploadedBundle({ lease, task, grant, directory, say,
|
|
19
|
+
doing: (name, origin, keyed) => `Archiving the final ${name} export through the shipped read-only adapter. ${keyed ? 'The key stays on this computer; the archive' : 'The archive'} goes only to the app's import door at ${origin} and stays in the app's own storage.` },
|
|
20
|
+
async ({ vendor, name, origin, uploadId, bundle, fresh }) => {
|
|
21
|
+
const kept = await door(await fresh('archive'), { uploadId, tool: vendor, takenAt }, lease.signal);
|
|
22
|
+
const [input, unique, rejected] = ['input', 'unique', 'rejected'].map(field => count(kept.counts?.[field]));
|
|
23
|
+
if (typeof kept.archiveId !== 'string' || !DOOR_ID.test(kept.archiveId) || kept.key !== `business-archive/${vendor}/${takenAt}` || kept.tool !== vendor
|
|
24
|
+
|| kept.takenAt !== takenAt || kept.bundleSha256 !== bundle.sha256 || kept.bytes !== bundle.size || [input, unique, rejected].includes(null)) throw Error("The app's import door returned an invalid archive answer.");
|
|
25
|
+
// The door reads its own copy back and parses it as a restore would, with no native writes.
|
|
26
|
+
const restored = await door(await fresh('restore-check'), { archiveId: kept.archiveId }, lease.signal);
|
|
27
|
+
if (restored.archiveId !== kept.archiveId || restored.key !== kept.key || restored.bundleSha256 !== bundle.sha256 || restored.bytes !== bundle.size
|
|
28
|
+
|| stable(restored.counts) !== stable(kept.counts) || !Array.isArray(restored.rejected)) throw Error(`The app's test-restore of the ${name} archive does not match the exported file. The archive was not reported.`);
|
|
29
|
+
return { outputs: { archive_id: kept.archiveId, bundle_sha256: bundle.sha256 },
|
|
30
|
+
said: `Archive kept in ${origin} as ${kept.key}: ${plural(bundle.size, 'byte')}, ${plural(unique, 'source record')}, test-restored with no writes (${rejected} rejected). Business test-restores it again itself; cancelling ${name} stays the owner's step in the browser: ${ownerPage}` };
|
|
31
|
+
});
|
|
32
|
+
}
|
package/cli/business/carry.mjs
CHANGED
|
@@ -98,9 +98,11 @@ export async function carryLive(state, self) {
|
|
|
98
98
|
try {
|
|
99
99
|
const carry = buildCarry(state, self);
|
|
100
100
|
if (!carry) return;
|
|
101
|
+
const checkouts = [];
|
|
101
102
|
for (const checkout of await liveCheckouts()) {
|
|
102
|
-
try { await writeCarry(checkout, carry); } catch (error) { warning(state.origin, error); }
|
|
103
|
+
try { await writeCarry(checkout, carry); checkouts.push(checkout); } catch (error) { warning(state.origin, error); }
|
|
103
104
|
}
|
|
105
|
+
return { name: carry.name, checkouts };
|
|
104
106
|
} catch (error) { warning(state.origin, error); }
|
|
105
107
|
}
|
|
106
108
|
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { withUploadedBundle, door, checkedPreview, plural } from './vendor-door.mjs';
|
|
2
|
+
|
|
3
|
+
// Why the door refused a catch-up under the owner's standing approval
|
|
4
|
+
// (import-kit door, "Catch-up and recovery": `catchup_requires_proposal:<reason>`).
|
|
5
|
+
const beyond = {
|
|
6
|
+
empty_baseline: 'the app holds no earlier import to compare with',
|
|
7
|
+
source_records_gone: 'records were removed in the old tool',
|
|
8
|
+
native_or_mapping_conflict: 'records changed in the app since they were imported',
|
|
9
|
+
rejected_or_unmapped_records: 'some records cannot be brought over as they are',
|
|
10
|
+
change_must_be_under_five_percent: '5% or more of the records changed',
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Perform a claimed catchup.vendor: the vendor's current export uploaded into the
|
|
15
|
+
* app's import door, then a catch-up plan of it (a zero-write preview of what
|
|
16
|
+
* changed since the import). Business mints the plan grant under the owner's
|
|
17
|
+
* standing catch-up approval when one covers this tool; the door then refuses a
|
|
18
|
+
* change at or above its bound, and run asks for a plan grant for the owner's
|
|
19
|
+
* review instead. Completion reports the door's upload_id and plan_id and the
|
|
20
|
+
* bundle's SHA-256; Business applies the plan under the standing approval or
|
|
21
|
+
* after the owner approves it. Returns the line to say.
|
|
22
|
+
*/
|
|
23
|
+
export function runCatchup({ lease, task, grant, directory, say, ownerPage }) {
|
|
24
|
+
return withUploadedBundle({ lease, task, grant, directory, say,
|
|
25
|
+
doing: (name, origin, keyed) => `Bringing over recent ${name} changes 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}.` },
|
|
26
|
+
async ({ origin, uploadId, bundle, fresh }) => {
|
|
27
|
+
let planGrant = await fresh('plan'), refused = null, preview;
|
|
28
|
+
try { preview = await door(planGrant, { uploadId, catchup: true }, lease.signal); }
|
|
29
|
+
catch (error) {
|
|
30
|
+
const reason = planGrant.catchup === 'bounded' && /^catchup_requires_proposal:([a-z0-9_]+)$/.exec(error.doorCode ?? '')?.[1];
|
|
31
|
+
if (!reason) throw error;
|
|
32
|
+
refused = Object.hasOwn(beyond, reason) ? beyond[reason] : 'it is more than that approval covers';
|
|
33
|
+
planGrant = await fresh('plan', { review: true });
|
|
34
|
+
preview = await door(planGrant, { uploadId, catchup: true }, lease.signal);
|
|
35
|
+
}
|
|
36
|
+
const { records, created, updated, unchanged, gone, rejected } = checkedPreview(preview, bundle);
|
|
37
|
+
const planned = `Catch-up planned in ${origin}: ${plural(records, 'source record')}; ${created} new, ${updated} changed, ${unchanged} unchanged, ${gone} gone, ${rejected} rejected.`;
|
|
38
|
+
return { outputs: { upload_id: uploadId, plan_id: preview.planId, bundle_sha256: bundle.sha256 },
|
|
39
|
+
said: planGrant.catchup === 'bounded' ? `${planned} It is within the owner's standing catch-up approval, so Business applies it and checks the result.`
|
|
40
|
+
: `${planned} ${refused ? `It needs the owner's own approval (${refused}): nothing` : 'Nothing'} changes in the app until the owner approves this catch-up in the browser: ${ownerPage}` };
|
|
41
|
+
});
|
|
42
|
+
}
|
|
@@ -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
|
+
}
|
package/cli/business/command.mjs
CHANGED
|
@@ -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';
|
|
@@ -10,25 +11,42 @@ Business keeps your business name, logo and brand colour together for the apps
|
|
|
10
11
|
that support shared Business settings. Choose what to share in your browser.
|
|
11
12
|
|
|
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
|
|
13
18
|
scan [DIR...] [--json] Names-only local discovery
|
|
14
19
|
connect [--code CODE] [--origin URL]
|
|
15
20
|
Pair this computer, waiting until the owner approves in the browser
|
|
16
21
|
(up to the code's 10 minutes); run it again to resume
|
|
17
22
|
Connect carries the Business name into local apps
|
|
18
|
-
run [--once]
|
|
19
|
-
|
|
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
|
|
20
34
|
answer ID VENDOR USAGE [CONFIDENCE]
|
|
21
35
|
Catalog vendor or none; uses, sells, both, product-dependency
|
|
22
|
-
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
|
|
23
38
|
token MCP headersHelper output; send directly to the MCP client
|
|
24
39
|
status [--json] Pairing, service, current task and checkpoint
|
|
25
|
-
disconnect Revoke this computer, then remove local credentials and additions
|
|
26
|
-
|
|
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.
|
|
27
44
|
State lives in $RER_BUSINESS_STATE_DIR when set, otherwise in ~/.rer/business.
|
|
28
45
|
In an agent sandbox that writes only inside its working folder, use RER_BUSINESS_STATE_DIR="$PWD/.rer-business".
|
|
29
46
|
`;
|
|
30
47
|
|
|
31
48
|
export async function businessCommand(argv) {
|
|
49
|
+
if (argv[0] === 'setup') return setupCommand(argv.slice(1));
|
|
32
50
|
if (!argv.length || argv[0] !== 'scan' && argv.some(arg => ['--help', '-h'].includes(arg))) { process.stdout.write(usage); return 0; }
|
|
33
51
|
if (argv[0] === 'scan') return scanCommand(argv);
|
|
34
52
|
try {
|
package/cli/business/connect.mjs
CHANGED
|
@@ -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 {
|
|
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,10 +28,11 @@ 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
|
|
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; }
|
|
@@ -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:
|
|
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
|
|
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
|
|
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
|
|
34
|
+
return credentialShaped(text) || highEntropy(text, /[A-Za-z0-9_+\/=\-]{24,}/g);
|
|
32
35
|
}
|
|
33
36
|
|
|
34
37
|
function sensitivePath(path) {
|
package/cli/business/device.mjs
CHANGED
|
@@ -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
|
+
}
|