@runeditrun/rer 0.2.95 → 0.2.96
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 +14 -3
- package/cli/README.md +2 -1
- package/cli/agent-door.mjs +4 -0
- package/cli/business/carry-files.mjs +29 -2
- package/cli/business/carry.mjs +26 -11
- package/cli/business/choices.mjs +7 -3
- package/cli/business/connect.mjs +6 -5
- package/cli/business/invocation.mjs +3 -2
- package/cli/business/local-commands.mjs +6 -6
- package/cli/business/questions.mjs +4 -1
- package/cli/business/state.mjs +4 -1
- package/cli/checkout-folders.mjs +14 -0
- package/cli/checkout-preparation.mjs +83 -0
- package/cli/door-clauses.mjs +3 -2
- package/cli/hosted-output.mjs +10 -1
- package/foundation/runtime/contract-docs.mjs +1 -1
- package/global/CHANGELOG.md +32 -0
- package/global/README.md +14 -3
- package/global/cli/layout.mjs +3 -0
- package/global/launch/facts.mjs +1 -29
- package/global/launch/state.mjs +3 -6
- package/global/list.mjs +9 -15
- package/modules/agent-door/conformance/index.mjs +13 -4
- package/modules/agent-door/conformance/policy-phases.mjs +28 -1
- package/modules/agent-door/conformance/relay.mjs +63 -0
- package/modules/agent-door/conformance/unpair.mjs +47 -0
- package/onboarding/operator-migrations.mjs +5 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,7 +25,8 @@ contract document generation and checking. `rer door clauses --check` reports
|
|
|
25
25
|
missing or stale requirements without writing; use `--cwd DIR` to select a seed.
|
|
26
26
|
Writing requires a `Shared duties (Base)` table and skips duties listed in its
|
|
27
27
|
`Base duty` column. Unlisted duties are synchronized as clauses; a missing table
|
|
28
|
-
refuses the write. The read-only check
|
|
28
|
+
refuses the write. The read-only check skips the same listed duties; without a
|
|
29
|
+
table it checks all thirteen clause definitions.
|
|
29
30
|
The CLI can sync a contract before runtime adoption; regenerate the seed's source lock last.
|
|
30
31
|
See [agent door adoption](https://github.com/runeditrun/base/blob/main/modules/agent-door/ADOPTING.md#contract-clauses).
|
|
31
32
|
|
|
@@ -557,7 +558,10 @@ a headers helper. That output is a short-lived credential: connect it directly
|
|
|
557
558
|
to the MCP client and do not paste it into an agent transcript.
|
|
558
559
|
|
|
559
560
|
`rer business status` shows local pairing, service state and progress without
|
|
560
|
-
printing checkpoints or vendor data.
|
|
561
|
+
printing checkpoints or vendor data. Device credentials are stored separately
|
|
562
|
+
for each Business on an origin; disconnect also finds an older per-origin
|
|
563
|
+
credential through its original pairing record and revokes it once.
|
|
564
|
+
`rer business disconnect` revokes this
|
|
561
565
|
device through device-authenticated `DELETE /api/business/executors/self` before
|
|
562
566
|
removing its service, device and vendor credentials, state and introduced Claude
|
|
563
567
|
rules, preserving preexisting settings and unrelated edits. It says "Device
|
|
@@ -583,7 +587,14 @@ an explicit error. Revocation stops the supervisor on its next 401; it then
|
|
|
583
587
|
removes the device credential if it may and `status` says revoked. While it
|
|
584
588
|
waits, `run` says what for: the owner's permission to scan the folder connect
|
|
585
589
|
ran in (with the Your tools link) until this computer's scan is done, then the
|
|
586
|
-
owner's next step.
|
|
590
|
+
owner's next step.
|
|
591
|
+
If the server reports that this computer's scan failed, run and next instead
|
|
592
|
+
point the owner to **Retry** on **Your tools**, without asking for consent again.
|
|
593
|
+
Connect, next and run carry the Business profile into first-party checkouts
|
|
594
|
+
shown by `rer list` in the current or original pairing folder, including stopped
|
|
595
|
+
apps, as well as running and previously carried apps. Each skipped checkout
|
|
596
|
+
is named with its cause; a folder with no apps gets a next step.
|
|
597
|
+
It removes `run.lock` on every exit, including Ctrl-C,
|
|
587
598
|
SIGTERM and a closed terminal (SIGHUP); a lock whose process is gone, or that
|
|
588
599
|
has not been refreshed for two minutes, is cleared on the next start.
|
|
589
600
|
|
package/cli/README.md
CHANGED
|
@@ -595,7 +595,8 @@ into a seed's `CONTRACT.md` and runs its contract-docs generator and check.
|
|
|
595
595
|
It requires the seed's `Shared duties (Base)` table and skips duties listed
|
|
596
596
|
in its `Base duty` column; only unlisted duties need clause synchronization.
|
|
597
597
|
Without that table it refuses before writing any files.
|
|
598
|
-
`rer door clauses --check` names missing or stale
|
|
598
|
+
`rer door clauses --check` skips the same listed duties, names missing or stale
|
|
599
|
+
unlisted clauses and exits nonzero; without a table it checks all thirteen duties.
|
|
599
600
|
`--cwd DIR` selects the seed root. Existing statuses, evidence and gaps survive,
|
|
600
601
|
new clauses start missing, and seed-owned AGENT and SURFACE clauses stay intact.
|
|
601
602
|
Run the edition's source-lock command last. See
|
package/cli/agent-door.mjs
CHANGED
|
@@ -20,6 +20,9 @@ import { verificationHistory } from './agent-history.mjs';
|
|
|
20
20
|
import { journeyFixtures } from './agent-journey-fixtures.mjs';
|
|
21
21
|
import { verificationAgentInitializer } from './agent-initializer.mjs';
|
|
22
22
|
|
|
23
|
+
// Unpairing re-serves the installation without the Business trust it was paired with.
|
|
24
|
+
const pairedBindings = ['RER_OWNER_CLAIM_ISSUER', 'RER_OWNER_CLAIM_INSTALLATION_ID', 'RER_OWNER_CLAIM_APP_ORIGIN', 'RER_OWNER_CLAIM_PUBLIC_KEYS', 'RER_BUSINESS_TRUST'];
|
|
25
|
+
|
|
23
26
|
function finish(result, report) {
|
|
24
27
|
if (result.capabilities) report(`Agent capabilities (${result.capabilities.mode}): declared=${result.capabilities.declared.join(',')}; refused=${result.capabilities.refused.join(',')}; unscoped=${result.capabilities.unscoped.join(',')}.`);
|
|
25
28
|
for (const point of result.points) report(`${point.ok ? 'PASS' : 'FAIL'} ${point.id}${point.ok || !point.detail ? '' : `: ${point.detail}`}`);
|
|
@@ -152,6 +155,7 @@ export async function checkAgentDoor(root, { declaration, setupManifest, owner,
|
|
|
152
155
|
const result = await runAgentDoorConformance({ fetch: request, origin: hosted.origin, surface: declared.surface,
|
|
153
156
|
signer: { issuer, installationId, kid, privateKey: pair.privateKey }, person: sponsors[0], sponsors: sponsors.filter(person => !negativeOnly.has(person.label)), webhooks, business, prove, ...journey, nativeStep, prepare, invoke: workerDriver?.run(hosted),
|
|
154
157
|
initializeAgent: initializeAgent && (({ agentId, person }) => initializeAgent({ agentId, person, request, origin: hosted.origin, mail: network.mail, fixtures: network.fixtures })),
|
|
158
|
+
unpair: () => hosted.rebind(pairedBindings),
|
|
155
159
|
});
|
|
156
160
|
const points = [...result.points, ...reviewers.points()];
|
|
157
161
|
return finish({ ...result, points, ok: points.every(point => point.ok) }, report);
|
|
@@ -4,6 +4,8 @@ import { randomUUID } from 'node:crypto';
|
|
|
4
4
|
import { loadState, stateDirectory } from './state.mjs';
|
|
5
5
|
import { serversDirectory } from '../server-registry.mjs';
|
|
6
6
|
import { alive } from '../../modules/job-queue/identity.mjs';
|
|
7
|
+
import { checkoutFolders } from '../checkout-folders.mjs';
|
|
8
|
+
import { checkoutPreparation } from '../checkout-preparation.mjs';
|
|
7
9
|
|
|
8
10
|
const carryPath = checkout => join(checkout, '.rer/local/business.json');
|
|
9
11
|
const registryPath = () => join(stateDirectory(), 'carried.json');
|
|
@@ -85,13 +87,38 @@ async function liveCheckouts() {
|
|
|
85
87
|
return [...new Set(checkouts)];
|
|
86
88
|
}
|
|
87
89
|
|
|
88
|
-
export async function carryCheckouts(refused) {
|
|
90
|
+
export async function carryCheckouts(refused, state) {
|
|
89
91
|
const checkouts = new Map();
|
|
90
92
|
try { for (const checkout of await recordedCheckouts()) checkouts.set(checkout, { checkout, live: false }); }
|
|
91
93
|
catch (error) { refused(error); }
|
|
92
94
|
try { for (const checkout of await liveCheckouts()) checkouts.set(checkout, { checkout, live: true }); }
|
|
93
95
|
catch (error) { refused(error); }
|
|
94
|
-
|
|
96
|
+
// Include prepared/stopped checkouts, using the same immediate-folder door as
|
|
97
|
+
// rer list, both here and where this Business originally paired.
|
|
98
|
+
for (const directory of new Set([process.cwd(), state?.workingFolder].filter(Boolean))) {
|
|
99
|
+
try {
|
|
100
|
+
const listed = [];
|
|
101
|
+
if (await regular(join(directory, 'OPERATIONS.json'), false, true)) listed.push(directory);
|
|
102
|
+
listed.push(...await checkoutFolders(directory));
|
|
103
|
+
for (const checkout of listed) {
|
|
104
|
+
if (!checkouts.has(checkout)) checkouts.set(checkout, { checkout, live: true });
|
|
105
|
+
}
|
|
106
|
+
} catch (error) { refused(error, directory); }
|
|
107
|
+
}
|
|
108
|
+
const ready = [];
|
|
109
|
+
for (const item of checkouts.values()) {
|
|
110
|
+
try {
|
|
111
|
+
if (await firstParty(item.checkout).catch(() => false)) {
|
|
112
|
+
const status = await checkoutPreparation(item.checkout);
|
|
113
|
+
if (!status.prepared) {
|
|
114
|
+
refused(Object.assign(Error(status.reason), { preparation: true }), item.checkout);
|
|
115
|
+
continue;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
ready.push(item);
|
|
119
|
+
} catch (error) { refused(error, item.checkout); }
|
|
120
|
+
}
|
|
121
|
+
return ready;
|
|
95
122
|
}
|
|
96
123
|
|
|
97
124
|
export async function removeCarries() {
|
package/cli/business/carry.mjs
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { Api } from './api.mjs';
|
|
2
2
|
import { createCredentialStore } from './keychain.mjs';
|
|
3
|
-
import {
|
|
3
|
+
import { deviceCredentialHandle, loadState } from './state.mjs';
|
|
4
4
|
import { localCause } from './errors.mjs';
|
|
5
5
|
import { carryCheckouts, firstParty, writeCarry } from './carry-files.mjs';
|
|
6
6
|
export { removeCarries } from './carry-files.mjs';
|
|
7
7
|
|
|
8
8
|
const launched = Symbol.for('rer.business.carry.launched');
|
|
9
|
+
const summaries = new Map();
|
|
9
10
|
|
|
10
11
|
export function buildCarry(state, self) {
|
|
11
12
|
const business = self?.business;
|
|
@@ -25,31 +26,45 @@ export function buildCarry(state, self) {
|
|
|
25
26
|
logo_url: logo };
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
function warning(origin, error, checkout) {
|
|
29
|
+
function warning(origin, error, checkout, report = true) {
|
|
29
30
|
// Do not echo server text, response fields or transport messages: they can contain credentials.
|
|
30
31
|
const reason = error.status ? `the server refused the request (HTTP ${error.status})`
|
|
31
32
|
: error.name === 'TimeoutError' || error.name === 'AbortError' ? 'the server did not answer within 5 seconds'
|
|
32
33
|
: error.message?.startsWith('Could not reach the Business server at ') ? 'the server is unreachable'
|
|
33
34
|
: error.message === 'credential unavailable' ? 'the Business credential is unavailable in OS credential storage'
|
|
34
|
-
:
|
|
35
|
-
|
|
35
|
+
: error.preparation ? error.message
|
|
36
|
+
: localCause(error) ?? (['the response names another Business', 'the Business profile is invalid', 'the checkout is not first-party', 'the carry path is linked or not a regular file', 'the existing file is not a carry for this paired Business', 'the carry registry is invalid', 'the checkout is not set up yet: run rer setup'].includes(error.message) ? error.message : 'the Business profile could not be refreshed');
|
|
37
|
+
const step = error.code === 'ENOENT' ? ' Open the app with rer dev --cwd FOLDER, then run business next again.' : '';
|
|
38
|
+
const text = `Business carry at ${origin}${checkout ? ` for ${JSON.stringify(checkout)}` : ''}: ${reason}; keeping any local carry.${step}\n`;
|
|
39
|
+
if (report) process.stderr.write(text);
|
|
40
|
+
return text;
|
|
36
41
|
}
|
|
37
42
|
|
|
38
|
-
export async function carryCheckIn(state, self) {
|
|
43
|
+
export async function carryCheckIn(state, self, { summarize = false } = {}) {
|
|
39
44
|
try {
|
|
40
45
|
if (!state?.origin || !state.businessId || !state.executorId || state.revoked) return;
|
|
41
46
|
const carry = buildCarry(state, self);
|
|
42
|
-
|
|
43
|
-
const checkouts = [], unchanged = [];
|
|
47
|
+
const checkouts = [], unchanged = [], skipped = [];
|
|
44
48
|
let failed = 0;
|
|
45
|
-
const refused = (error, checkout) => { failed++; warning(state.origin, error, checkout); };
|
|
46
|
-
for (const { checkout, live } of await carryCheckouts(refused)) {
|
|
49
|
+
const refused = (error, checkout) => { failed++; skipped.push({ checkout, warning: warning(state.origin, error, checkout, false) }); };
|
|
50
|
+
for (const { checkout, live } of await carryCheckouts(refused, state)) {
|
|
47
51
|
try {
|
|
52
|
+
if (!carry) {
|
|
53
|
+
skipped.push({ checkout, warning: `Business carry skipped for ${JSON.stringify(checkout)}: the server did not provide this Business's profile; retry business next after the server supports profile sharing.\n` });
|
|
54
|
+
failed++; continue;
|
|
55
|
+
}
|
|
48
56
|
const changed = await writeCarry(checkout, carry, { existingOnly: !live });
|
|
49
57
|
(changed ? checkouts : unchanged).push(checkout);
|
|
50
58
|
} catch (error) { refused(error, checkout); }
|
|
51
59
|
}
|
|
52
|
-
|
|
60
|
+
// Changed/unchanged writes describe the same carried set. Sorting keeps
|
|
61
|
+
// filesystem and registry order from repeating a long-running run's report.
|
|
62
|
+
const signature = JSON.stringify({ carried: [...checkouts, ...unchanged].sort(), skipped: skipped.map(item => item.warning).sort() });
|
|
63
|
+
const key = JSON.stringify([state.origin, state.businessId, state.executorId]);
|
|
64
|
+
const summaryChanged = !summarize || summaries.get(key) !== signature;
|
|
65
|
+
if (summarize) summaries.set(key, signature);
|
|
66
|
+
if (summaryChanged) for (const item of skipped) process.stderr.write(item.warning);
|
|
67
|
+
return { name: carry?.name ?? state.businessId, checkouts, unchanged, failed, summaryChanged };
|
|
53
68
|
} catch (error) { warning(state.origin, error); }
|
|
54
69
|
}
|
|
55
70
|
|
|
@@ -71,7 +86,7 @@ export async function refreshCheckout(checkout) {
|
|
|
71
86
|
if (!await firstParty(checkout)) return;
|
|
72
87
|
state = await loadState();
|
|
73
88
|
if (!state?.origin || !state.businessId || !state.executorId || state.revoked) return;
|
|
74
|
-
const credential = await createCredentialStore().get(
|
|
89
|
+
const credential = await createCredentialStore().get(deviceCredentialHandle(state));
|
|
75
90
|
if (!credential) throw Error('credential unavailable');
|
|
76
91
|
await refreshCarry(new Api(state.origin, credential), state, { checkout });
|
|
77
92
|
} catch (error) { warning(state?.origin ?? 'the paired origin', error); }
|
package/cli/business/choices.mjs
CHANGED
|
@@ -55,7 +55,10 @@ export async function applyChoices(api, state, { reconnecting = false } = {}) {
|
|
|
55
55
|
// nothing is decided yet. On a new computer this first request activates it.
|
|
56
56
|
try { self = await api.get('/api/business/executors/self'); }
|
|
57
57
|
catch (error) { if (![403, 404].includes(error.status)) throw error; }
|
|
58
|
-
|
|
58
|
+
// Use the server's per-computer scan state, rather than interpreting every
|
|
59
|
+
// unfinished scan as missing consent. Do not persist paths from the response.
|
|
60
|
+
state.localScan = self?.local_scan ? { allowed: self.local_scan.allowed === true, state: self.local_scan.state } : undefined;
|
|
61
|
+
const carried = await carryCheckIn(state, self, { summarize: true });
|
|
59
62
|
const decided = Object.fromEntries(names.map(name => [name, typeof self?.optIns?.[name] === 'boolean' ? self.optIns[name] : null]));
|
|
60
63
|
// The agent this computer reported when it paired, as the owner's browser words its choices:
|
|
61
64
|
// the Claude Code rules apply only to Claude Code. An unknown agent (no route yet) decides nothing.
|
|
@@ -87,16 +90,17 @@ export async function applyChoices(api, state, { reconnecting = false } = {}) {
|
|
|
87
90
|
}
|
|
88
91
|
const undecided = names.filter(name => decided[name] === null && !inapplicable[name]);
|
|
89
92
|
if (undecided.length) {
|
|
90
|
-
once(
|
|
93
|
+
once('undecided', `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
94
|
}
|
|
92
95
|
once('choices-next-step', `After choosing this computer's permissions in Business, run ${businessCommand('next')} to apply them and see the next task.\n`);
|
|
93
|
-
if (carried) {
|
|
96
|
+
if (carried?.summaryChanged) {
|
|
94
97
|
const count = carried.checkouts.length;
|
|
95
98
|
process.stdout.write(count
|
|
96
99
|
? `Refreshed ${count} local app carry ${count === 1 ? 'file' : 'files'} for ${JSON.stringify(carried.name)}:\n${carried.checkouts.map(checkout => ` - ${join(checkout, '.rer/local/business.json')}\n`).join('')}Supporting apps apply these values when they read their carry file.\n`
|
|
97
100
|
: `No local app carry files changed for ${JSON.stringify(carried.name)}.\n`);
|
|
98
101
|
for (const checkout of carried.unchanged) process.stdout.write(`Already current: ${join(checkout, '.rer/local/business.json')}\n`);
|
|
99
102
|
if (carried.failed) process.stdout.write(`${carried.failed} local app carry ${carried.failed === 1 ? 'file could' : 'files could'} not be refreshed; see the carry warnings.\n`);
|
|
103
|
+
if (!count && !carried.unchanged.length && !carried.failed) process.stdout.write(`No local apps were found. Run ${businessCommand('next')} in the folder where rer list shows your apps.\n`);
|
|
100
104
|
}
|
|
101
105
|
return { applied: lines.length, serviceInstalled };
|
|
102
106
|
}
|
package/cli/business/connect.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { homedir } from 'node:os';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { Api, originUrl, identifier, pause } from './api.mjs';
|
|
4
|
-
import { loadState, saveState, credentialHandle, loadPending, savePending, clearPending, checkStateWritable } from './state.mjs';
|
|
4
|
+
import { loadState, saveState, credentialHandle, deviceCredentialHandle, loadPending, savePending, clearPending, checkStateWritable } from './state.mjs';
|
|
5
5
|
import { createCredentialStore } from './keychain.mjs';
|
|
6
6
|
import { applyChoices } from './choices.mjs';
|
|
7
7
|
import { rerCommand, businessCommand } from './invocation.mjs';
|
|
@@ -30,7 +30,7 @@ export async function connect({ code, origin } = {}) {
|
|
|
30
30
|
if (stored) {
|
|
31
31
|
if (stored.revoked) throw Error(`This computer was ${revokedText(stored)}\nThen connect with a new code from ${stored.origin}/business.`);
|
|
32
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.`);
|
|
33
|
-
const credential = await createCredentialStore().get(
|
|
33
|
+
const credential = await createCredentialStore().get(deviceCredentialHandle(stored));
|
|
34
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.`);
|
|
35
35
|
await connected(new Api(origin, credential), stored, { reconnecting: true });
|
|
36
36
|
return;
|
|
@@ -41,8 +41,8 @@ export async function connect({ code, origin } = {}) {
|
|
|
41
41
|
// Refuse before redeeming the one-use code or collecting an approval when this
|
|
42
42
|
// session cannot keep the pairing or store the device credential.
|
|
43
43
|
await checkStateWritable();
|
|
44
|
-
const store = createCredentialStore()
|
|
45
|
-
try { await store.
|
|
44
|
+
const store = createCredentialStore();
|
|
45
|
+
try { await store.check(); }
|
|
46
46
|
catch (error) {
|
|
47
47
|
const outside = error.sandboxRefused ? ` Approve this command outside the sandbox: ${rerCommand()} business connect${code ? ` --code ${code}` : ''} --origin ${origin}. Every other business command runs inside the sandbox.` : '';
|
|
48
48
|
throw Error(`${error.message}${outside} ${pending ? 'The saved pairing was kept; run connect again once this is fixed.' : nothingSent}`);
|
|
@@ -87,7 +87,8 @@ export async function connect({ code, origin } = {}) {
|
|
|
87
87
|
if (result?.status === 'paired') {
|
|
88
88
|
if (typeof result.device_credential !== 'string') throw Error('Business server returned an invalid device credential.');
|
|
89
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 } : {}) };
|
|
90
|
+
const state = { version: 1, credentialVersion: 2, origin, businessId: identifier(result.business_id), executorId: identifier(result.executor_id), vendorHandles: [], awakeConsent: false, ...(folder ? { workingFolder: folder } : {}) };
|
|
91
|
+
const handle = credentialHandle(origin, state.businessId);
|
|
91
92
|
// No authenticated request (including activation) before both durable writes.
|
|
92
93
|
await store.set(handle, result.device_credential);
|
|
93
94
|
try { await saveState(state); } catch (error) { await store.delete(handle); throw error; }
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { accessSync, statSync, constants } from 'node:fs';
|
|
2
2
|
import { delimiter, join, resolve, sep } from 'node:path';
|
|
3
|
-
import { fileURLToPath } from 'node:url';
|
|
4
3
|
|
|
5
4
|
const npx = 'npx -y @runeditrun/rer';
|
|
6
5
|
const word = value => /^[A-Za-z0-9_./~:@%+=,-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
|
|
@@ -19,7 +18,9 @@ function onPath(path = '') {
|
|
|
19
18
|
// An npx run leaves nothing installed; install.sh says which launcher it ran
|
|
20
19
|
// (RER_INVOKED_AS), since it adds that launcher to PATH only for itself.
|
|
21
20
|
export function rerCommand(env = process.env) {
|
|
22
|
-
|
|
21
|
+
// The running entry identifies the invocation even when its dispatcher was
|
|
22
|
+
// delegated to a checkout's pinned copy in another package/cache directory.
|
|
23
|
+
if ((process.argv[1] ?? '').split(sep).includes('_npx')) return npx;
|
|
23
24
|
if (env.RER_INVOKED_AS) return word(env.RER_INVOKED_AS);
|
|
24
25
|
return onPath(env.PATH) ? 'rer' : npx;
|
|
25
26
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { writeFile, unlink } from 'node:fs/promises';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
|
-
import { loadState, loadPending, saveState, stateDirectory, removeStateDirectory, removeWorkFiles,
|
|
3
|
+
import { loadState, loadPending, saveState, stateDirectory, removeStateDirectory, removeWorkFiles, deviceCredentialHandle, liveSupervisor } from './state.mjs';
|
|
4
4
|
import { createCredentialStore, readSecret } from './keychain.mjs';
|
|
5
5
|
import { removeService, serviceStatus } from './service.mjs';
|
|
6
6
|
import { removePermissions, permissionsAdded } from './permissions.mjs';
|
|
@@ -17,7 +17,7 @@ export async function paired() {
|
|
|
17
17
|
const state = await loadState();
|
|
18
18
|
if (!state?.origin || !state.businessId || !state.executorId) throw Error(`This computer is not paired. Run ${rerCommand()} business connect --code CODE.`);
|
|
19
19
|
if (state.revoked) throw Error(`This computer was ${revokedText(state)}`);
|
|
20
|
-
const credential = await createCredentialStore().get(
|
|
20
|
+
const credential = await createCredentialStore().get(deviceCredentialHandle(state));
|
|
21
21
|
if (!credential) throw Error(`This computer's Business credential is missing from OS credential storage. Run ${rerCommand()} business disconnect, then connect again with a new code from ${state.origin}/business.`);
|
|
22
22
|
return { state, credential };
|
|
23
23
|
}
|
|
@@ -42,7 +42,7 @@ export async function forgetLocally(state, { stopRun = true } = {}) {
|
|
|
42
42
|
await attempt('permissions', () => removePermissions());
|
|
43
43
|
const vendorKeys = [];
|
|
44
44
|
for (const handle of store ? state.vendorHandles ?? [] : []) if (await attempt('vendorKeys', () => store.delete(handle))) vendorKeys.push(handle);
|
|
45
|
-
const refused = store ? await attempt('credential', () => store.delete(
|
|
45
|
+
const refused = store ? await attempt('credential', () => store.delete(deviceCredentialHandle(state))) : undefined;
|
|
46
46
|
await removeCarries();
|
|
47
47
|
if (!leftovers.length) { await removeStateDirectory(); return []; }
|
|
48
48
|
const unique = [...new Set(leftovers)];
|
|
@@ -58,7 +58,7 @@ export async function forgetLocally(state, { stopRun = true } = {}) {
|
|
|
58
58
|
export async function revokedByServer(state) {
|
|
59
59
|
const leftovers = [];
|
|
60
60
|
let cause;
|
|
61
|
-
try { await createCredentialStore().delete(
|
|
61
|
+
try { await createCredentialStore().delete(deviceCredentialHandle(state)); }
|
|
62
62
|
catch (error) { leftovers.push('credential'); cause = error.sandboxRefused ? `macOS Keychain refused to remove it inside this agent sandbox (security exited with status ${error.osStatus ?? 'unknown'}).` : describe(error); }
|
|
63
63
|
if (state.vendorHandles?.length) leftovers.push('vendorKeys');
|
|
64
64
|
if ((await serviceStatus()).installed) leftovers.push('service');
|
|
@@ -112,7 +112,7 @@ export async function disconnect() {
|
|
|
112
112
|
const state = await loadState();
|
|
113
113
|
const origin = state?.origin ?? (await loadPending())?.origin;
|
|
114
114
|
const page = origin && (state?.businessId ? `${origin}/business/${encodeURIComponent(state.businessId)}/settings` : `${origin}/business`);
|
|
115
|
-
const credential = state?.origin ? await createCredentialStore().get(
|
|
115
|
+
const credential = state?.origin ? await createCredentialStore().get(deviceCredentialHandle(state)) : null;
|
|
116
116
|
const revocation = credential ? await revoke(state.origin, credential) : 'not_sent';
|
|
117
117
|
// Until the server confirms, the device stays connected: keep its credential
|
|
118
118
|
// and everything else so disconnect can run again after browser revocation.
|
|
@@ -139,7 +139,7 @@ export async function status({ json = false } = {}) {
|
|
|
139
139
|
if (!state) {
|
|
140
140
|
process.stdout.write(json ? JSON.stringify({ paired: false, service: 'not_installed', current_task: null, checkpoint: null }) + '\n' : 'Business: not paired.\nService: not installed.\nTask: none.\nCheckpoint: none.\n'); return;
|
|
141
141
|
}
|
|
142
|
-
const stored = !state.revoked && state.origin && await createCredentialStore().get(
|
|
142
|
+
const stored = !state.revoked && state.origin && await createCredentialStore().get(deviceCredentialHandle(state));
|
|
143
143
|
const service = await serviceStatus();
|
|
144
144
|
const active = state.revoked ? null : (await loadProgress()).current;
|
|
145
145
|
if (json) {
|
|
@@ -43,7 +43,10 @@ export const ownerLink = state => `${state.origin}/business/${encodeURIComponent
|
|
|
43
43
|
// folder scan has finished, that is the owner's scan permission for the folder
|
|
44
44
|
// connect ran in; afterwards it is the owner's next step in the browser.
|
|
45
45
|
export function waitingFor(state) {
|
|
46
|
+
if (state.localScan?.state === 'failed') return `This computer's scan failed. The owner can press Retry on Your tools: ${ownerLink(state)}/tools`;
|
|
47
|
+
if (state.localScan?.state === 'done') return `Waiting for the next task. Nothing needs this computer until the owner moves the plan forward: ${ownerLink(state)}`;
|
|
46
48
|
if (!state.discovered) {
|
|
49
|
+
if (state.localScan?.allowed) return `Waiting for this computer's allowed scan to run. Check its progress on Your tools: ${ownerLink(state)}/tools`;
|
|
47
50
|
const folder = state.workingFolder ?? process.cwd();
|
|
48
51
|
return `Waiting for the owner to allow scanning ${folder} (names only). They allow it on Your tools: ${ownerLink(state)}/tools`;
|
|
49
52
|
}
|
|
@@ -143,7 +146,7 @@ export async function next() {
|
|
|
143
146
|
return;
|
|
144
147
|
}
|
|
145
148
|
const { toolId, vendorId, vendors } = classification(item);
|
|
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:
|
|
149
|
+
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: ${businessCommand(`answer ${id} <vendor_id|none> <usage> [confidence]`)}\n`);
|
|
147
150
|
}
|
|
148
151
|
|
|
149
152
|
export async function answer(id, vendorId, choice, rawConfidence = '1') {
|
package/cli/business/state.mjs
CHANGED
|
@@ -15,7 +15,10 @@ export function stateDirectory() {
|
|
|
15
15
|
if (chosen.includes('\0')) throw Error('RER_BUSINESS_STATE_DIR must name a folder.');
|
|
16
16
|
return resolve(chosen);
|
|
17
17
|
}
|
|
18
|
-
export const credentialHandle = origin => `device:${createHash('sha256').update(origin).digest('hex')}`;
|
|
18
|
+
export const credentialHandle = (origin, businessId) => `device:${createHash('sha256').update(businessId ? JSON.stringify([origin, businessId]) : origin).digest('hex')}`;
|
|
19
|
+
// Old pairing records still own the per-origin key, which disconnect revokes
|
|
20
|
+
// and removes once. New pairings never read or overwrite that legacy key.
|
|
21
|
+
export const deviceCredentialHandle = state => credentialHandle(state.origin, state.credentialVersion === 2 ? state.businessId : undefined);
|
|
19
22
|
|
|
20
23
|
async function loadJson(name) {
|
|
21
24
|
const path = join(stateDirectory(), name);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// The immediate checkout folders shown by rer list. No recursive disk search.
|
|
2
|
+
import { readdir, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export async function checkoutFolders(directory) {
|
|
6
|
+
const folders = [];
|
|
7
|
+
for (const item of await readdir(directory, { withFileTypes: true })) {
|
|
8
|
+
const path = join(directory, item.name);
|
|
9
|
+
try {
|
|
10
|
+
if ((await stat(path)).isDirectory() && (await stat(join(path, 'OPERATIONS.json'))).isFile()) folders.push(await realpath(path));
|
|
11
|
+
} catch { /* Not a readable checkout, as in rer list. */ }
|
|
12
|
+
}
|
|
13
|
+
return [...new Set(folders)];
|
|
14
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Read-only setup facts shared by the launcher, list and portable Business carry.
|
|
2
|
+
// Vendored commands cannot import global/launch, so these rules live with the CLI.
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { execFile } from 'node:child_process';
|
|
5
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
6
|
+
import { basename, join } from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { promisify } from 'node:util';
|
|
9
|
+
import { serversDirectory } from './server-registry.mjs';
|
|
10
|
+
import { exactVersion } from './package-mode.mjs';
|
|
11
|
+
import { shared } from './shared.mjs';
|
|
12
|
+
|
|
13
|
+
async function readJson(path) {
|
|
14
|
+
try { return JSON.parse(await readFile(path, 'utf8')); }
|
|
15
|
+
catch (error) { if (error.code === 'ENOENT' || error instanceof SyntaxError) return undefined; throw error; }
|
|
16
|
+
}
|
|
17
|
+
async function mtime(path) { try { return (await stat(path)).mtimeMs; } catch (error) { if (error.code === 'ENOENT') return undefined; throw error; } }
|
|
18
|
+
|
|
19
|
+
export function launchPath(checkout, env = process.env) {
|
|
20
|
+
const name = basename(checkout).toLowerCase().replace(/[^a-z0-9-]+/g, '-').slice(0, 40) || 'checkout';
|
|
21
|
+
return join(serversDirectory(env), 'launches', `${name}-${createHash('sha256').update(checkout).digest('hex').slice(0, 12)}`);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
// A checkout is set up when its pin's describe says so (`local.prepared`, from
|
|
25
|
+
// rer-cli-2); for older pins, when its primary private settings file holds
|
|
26
|
+
// anything. The pin's describe names it (`local.settings`, where the pin has it).
|
|
27
|
+
export async function hasSettings(root, described) {
|
|
28
|
+
if (typeof described?.local?.prepared === 'boolean') return described.local.prepared;
|
|
29
|
+
const primary = described?.local?.settings?.[0] ?? '.dev.vars';
|
|
30
|
+
try { return (await stat(join(root, primary))).size > 0; } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Every pin's setup saves its answers file only once it has finished, so a
|
|
34
|
+
// file newer than this launcher's record of its own attempt (its start for
|
|
35
|
+
// 'running', its end for 'failed') is a setup that finished after it.
|
|
36
|
+
async function finishedSince(root, described, at) {
|
|
37
|
+
const saved = await mtime(join(root, described?.local?.installerState ?? '.seed/installer', 'setup-answers.json'));
|
|
38
|
+
return saved !== undefined && typeof at === 'number' && saved > at;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Setup runs on a checkout with no saved settings ('fresh'). When a setup this
|
|
42
|
+
// launcher started did not finish ('running' after a kill, or 'failed') and no
|
|
43
|
+
// setup has finished since, it runs again ('resume') and keeps what the earlier
|
|
44
|
+
// attempt saved. A checkout set up any other way is never set up again.
|
|
45
|
+
// A checkout that is not prepared but already holds an owner (a setting a newer
|
|
46
|
+
// manifest added is missing) resumes too, so the saved owner and origin are
|
|
47
|
+
// kept; one without a saved owner gets the local owner ('fresh').
|
|
48
|
+
export async function setupNeeded(root, described, last) {
|
|
49
|
+
if (!await hasSettings(root, described)) return described?.local?.ownerSaved === true ? 'resume' : 'fresh';
|
|
50
|
+
if (!last || last.state === 'done') return undefined;
|
|
51
|
+
return await finishedSince(root, described, last.at) ? undefined : 'resume';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const bundledEntry = fileURLToPath(new URL('../bin/rer.mjs', import.meta.url));
|
|
55
|
+
async function pinnedEntry(checkout) {
|
|
56
|
+
const manifest = await readJson(join(checkout, 'package.json')).catch(() => null);
|
|
57
|
+
const declared = manifest?.devDependencies?.['@runeditrun/rer'] ?? manifest?.dependencies?.['@runeditrun/rer'];
|
|
58
|
+
const installed = declared && (await readJson(join(checkout, 'node_modules/@runeditrun/rer/package.json')).catch(() => null))?.version;
|
|
59
|
+
if (declared && !(installed && (installed === declared || !exactVersion.test(declared)))) return null;
|
|
60
|
+
if (declared) return join(checkout, 'node_modules/@runeditrun/rer/bin/rer.mjs');
|
|
61
|
+
const vendored = join(checkout, 'scripts/rer.mjs');
|
|
62
|
+
return await stat(vendored).then(info => info.isFile()).catch(() => false) ? vendored : bundledEntry;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function checkoutPreparation(checkout, env = process.env) {
|
|
66
|
+
let describing = true;
|
|
67
|
+
try {
|
|
68
|
+
const entry = await pinnedEntry(checkout);
|
|
69
|
+
if (!entry) return { prepared: false, reason: 'the pinned rer package is not installed: run rer install' };
|
|
70
|
+
const { stdout } = await promisify(execFile)(process.execPath, [entry, 'describe', '--json'], { cwd: checkout, env, maxBuffer: 16 * 1024 * 1024, timeout: 30000 });
|
|
71
|
+
const described = JSON.parse(stdout);
|
|
72
|
+
describing = false;
|
|
73
|
+
const last = await readJson(join(launchPath(checkout, env), 'setup.json'));
|
|
74
|
+
const needed = await setupNeeded(checkout, described, last);
|
|
75
|
+
return { prepared: !needed, ...(needed ? { reason: 'the checkout is not set up yet: run rer setup' } : {}) };
|
|
76
|
+
} catch (error) {
|
|
77
|
+
const { createRedaction, credentialValues } = await shared('redaction.mjs');
|
|
78
|
+
const redaction = createRedaction();
|
|
79
|
+
redaction.addSecrets(credentialValues(env));
|
|
80
|
+
const cause = error.stderr?.trim() || (describing ? `rer describe failed in ${checkout}.` : error.message);
|
|
81
|
+
return { prepared: null, reason: `rer describe fails here: ${redaction.redact(cause.split('\n')[0])}` };
|
|
82
|
+
}
|
|
83
|
+
}
|
package/cli/door-clauses.mjs
CHANGED
|
@@ -65,7 +65,7 @@ function headings(lines) {
|
|
|
65
65
|
});
|
|
66
66
|
}
|
|
67
67
|
|
|
68
|
-
function sharedDuties(original) {
|
|
68
|
+
function sharedDuties(original, required) {
|
|
69
69
|
const lines = original.split(/\r?\n/), outline = headings(lines);
|
|
70
70
|
const cells = line => line?.trim().replace(/^\|/, '').replace(/(?<!\\)\|$/, '').split(/(?<!\\)\|/).map(cell => cell.trim());
|
|
71
71
|
const section = outline.find(item => item.level === 2 && item.title.trim() === 'Shared duties (Base)');
|
|
@@ -85,6 +85,7 @@ function sharedDuties(original) {
|
|
|
85
85
|
}
|
|
86
86
|
return duties;
|
|
87
87
|
}
|
|
88
|
+
if (!required) return new Set();
|
|
88
89
|
fail('CONTRACT.md needs a Shared duties (Base) table with a Base duty column before --write. Add the table, then retry; no files were written.');
|
|
89
90
|
}
|
|
90
91
|
|
|
@@ -164,7 +165,7 @@ export async function doorClausesCommand(args, env = process.env) {
|
|
|
164
165
|
const file = resolve(root, 'CONTRACT.md');
|
|
165
166
|
if (!existsSync(file)) fail('No CONTRACT.md found. Run rer door clauses from the seed root or pass --cwd DIR.');
|
|
166
167
|
const original = read(file);
|
|
167
|
-
const inherited = mode === '--write'
|
|
168
|
+
const inherited = sharedDuties(original, mode === '--write');
|
|
168
169
|
const { text, changed } = synchronize(original, definitions(canonical(root)).filter(clause => !inherited.has(clause.id)));
|
|
169
170
|
if (changed.length) console.log(`Agent clauses: ${changed.join(', ')}.`);
|
|
170
171
|
if (mode === '--check' && changed.length) return 1;
|
package/cli/hosted-output.mjs
CHANGED
|
@@ -191,7 +191,16 @@ export async function serveHosted(root, { declaration: declarationPath = 'deploy
|
|
|
191
191
|
if (typeof sql !== 'string' || !/^\s*SELECT\b/i.test(sql) || sql.includes(';')) throw new RerError('hosted_database_invalid', 'Verification state access is read-only SELECT.', 1);
|
|
192
192
|
return db.prepare(sql);
|
|
193
193
|
} };
|
|
194
|
-
},
|
|
194
|
+
},
|
|
195
|
+
// The same installation again without the named bindings: its Worker restarts, its storage and other bindings stay.
|
|
196
|
+
// Handles taken before it (preparation, history) end; take any later ones from the hosted object again.
|
|
197
|
+
rebind: async names => {
|
|
198
|
+
const app = options.workers.find(worker => worker.name === 'app');
|
|
199
|
+
for (const name of names) delete app.bindings[name];
|
|
200
|
+
await mf.setOptions(convertV4MiniflareOptions(options));
|
|
201
|
+
loopback = await mf.ready;
|
|
202
|
+
},
|
|
203
|
+
close: () => { release(); return mf.dispose(); },
|
|
195
204
|
fetch: (path, { headers, origin = HOSTED_ORIGIN, ...init } = {}) => {
|
|
196
205
|
if (!origins.includes(origin)) throw new RerError('agent_door_origin', 'Agent conformance request must use a declared hosted installation origin.', 1);
|
|
197
206
|
return loopbackFetch(loopback, { ...init, redirect: 'manual', headers: { ...headers, 'x-rer-original-url': `${origin}/${path}` } });
|
|
@@ -555,7 +555,7 @@ const covId = new RegExp(`^${clauseIdSource}$`);
|
|
|
555
555
|
const covHeading = /^(#{1,6})\s+(.+?)\s*#*\s*$/;
|
|
556
556
|
const covDefinition = new RegExp(`^(?:#{1,6}\\s+|(?:[-*+]\\s+)?\\*\\*)(${clauseIdSource})\\s+[—–-]\\s+`);
|
|
557
557
|
const covSplit = text => text.replace(/\r\n?/g, '\n').split('\n');
|
|
558
|
-
const covGenerated = text => /^\uFEFF?<!-- Generated from CONTRACT\.md by contract-docs\./.test(covSplit(text)[0]);
|
|
558
|
+
const covGenerated = text => /^\uFEFF?<!-- Generated from CONTRACT\.md by (?:scripts\/)?contract-docs\./.test(covSplit(text)[0]);
|
|
559
559
|
const covNormalize = text => typeof text === 'string' ? withoutQuoteMarkers(text).replace(/^\s*(?:[-*+]\s+|\d+[.)]\s+)/, '').replace(/[`*_]/g, '').replace(/\s+/gu, '') : '';
|
|
560
560
|
const covKey = entry => JSON.stringify([entry.file, entry.line, entry.cell ?? '']);
|
|
561
561
|
const covLabel = entry => `${entry.file}:${entry.line}${entry.cell ? ` (${entry.cell})` : ''}`;
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.96
|
|
4
|
+
|
|
5
|
+
### Business stop
|
|
6
|
+
|
|
7
|
+
- A stopped or detached Business (signed `detached:true` or the owner's stop) ends every Business-derived authority in the agent door. No Business access token is admitted for any subject, and calls a Business token held for approval or left waiting for admission are refused as `sponsor_unavailable` without a native effect, so approvals held before the stop do not execute after it. `person:` and `role:` approver and reviewer refs match nobody. Seed credentials, native sessions, embedded invocation, `sponsor` refs and the subject mapping are unchanged, so signed policy naming Business people is still adopted and its Pause and revoked lists apply.
|
|
8
|
+
- `PeopleAdapter` gains an optional `businessStopped()` that custom adapters should implement; `Principal` records its admission `source`. Agent conformance proves `BASE-AGENT-004.6` on the seed side (`004.6.seed-*`) and, when the driver can unpair, `BASE-AGENT-004.7`; `rer verify` unpairs by re-serving the same installation without its owner-claim and Business trust bindings.
|
|
9
|
+
|
|
10
|
+
### Business carry and scan
|
|
11
|
+
|
|
12
|
+
- `rer business` connect, next and run carry the Business profile into the first-party checkouts that `rer list` shows in the current or original pairing folder, including stopped apps, as well as running and previously carried apps. A checkout that `rer list` shows as not set up is not written to; it is named with its reason, and a folder with no apps gets a next step.
|
|
13
|
+
- A scan that failed on this computer is told apart from a wait for the owner's consent: run and next point to **Retry** on **Your tools** instead of asking for consent again, and report an allowed scan that is still running or finished.
|
|
14
|
+
- Commands that Business output suggests echo how `rer` was invoked: the installed `rer`, `npx -y @runeditrun/rer`, or the launcher path `install.sh` ran.
|
|
15
|
+
- Each Business on an origin keeps its own device credential, so a second Business no longer overwrites the first and disconnect revokes each one. An older per-origin credential is found through its original pairing record and revoked once.
|
|
16
|
+
- The carry summary prints once for an unchanged result instead of repeating at each check-in of a long-running `rer business run`; skipped-checkout reasons print with it.
|
|
17
|
+
|
|
18
|
+
### Setup output
|
|
19
|
+
|
|
20
|
+
- `rer setup` prints the local D1 migrations it applied once, from the durable ledger, instead of repeating Wrangler's full migration table after each migration.
|
|
21
|
+
|
|
22
|
+
### Shared duties clause check
|
|
23
|
+
|
|
24
|
+
- `rer door clauses --check` skips the same inherited duties as `--write` when the seed's `## Shared duties (Base)` table lists them, and names only missing or stale unlisted clauses. Without that table it still checks all thirteen duties. `--write` still requires the table.
|
|
25
|
+
- Contract-document coverage treats a generated view headed by a seed's `scripts/contract-docs` generator as generated.
|
|
26
|
+
|
|
27
|
+
### Run page
|
|
28
|
+
|
|
29
|
+
- The "Run it yourself" path on the /run page is badged "On your computer" instead of "100% free".
|
|
30
|
+
|
|
31
|
+
### Seed-door decision relay
|
|
32
|
+
|
|
33
|
+
- Add the signed Business decision pull at `/api/rer/agent-decisions`, with bounded public audit projections, erasure-aware feed triggers and default-seed migration 0040. Business stop and pairing checks refuse with empty 404s. Seeds that refresh to 0.2.96 must land the relay migration (copy `0040_agent_door_relay.sql`), the `POST /api/rer/agent-decisions` route line and the `agent_door_relay` erasure-map entry in the same commit: until they do, `rer verify` fails `BASE-AGENT-009.relay`. Recipe: `modules/agent-door/ADOPTING.md`. The route ships dark: the Business sees nothing until it starts pulling, but the migration's table and triggers record decisions from adoption.
|
|
34
|
+
|
|
3
35
|
## 0.2.95
|
|
4
36
|
|
|
5
37
|
### Native agent erasure and safe replay
|
package/global/README.md
CHANGED
|
@@ -25,7 +25,8 @@ contract document generation and checking. `rer door clauses --check` reports
|
|
|
25
25
|
missing or stale requirements without writing; use `--cwd DIR` to select a seed.
|
|
26
26
|
Writing requires a `Shared duties (Base)` table and skips duties listed in its
|
|
27
27
|
`Base duty` column. Unlisted duties are synchronized as clauses; a missing table
|
|
28
|
-
refuses the write. The read-only check
|
|
28
|
+
refuses the write. The read-only check skips the same listed duties; without a
|
|
29
|
+
table it checks all thirteen clause definitions.
|
|
29
30
|
The CLI can sync a contract before runtime adoption; regenerate the seed's source lock last.
|
|
30
31
|
See [agent door adoption](https://github.com/runeditrun/base/blob/main/modules/agent-door/ADOPTING.md#contract-clauses).
|
|
31
32
|
|
|
@@ -557,7 +558,10 @@ a headers helper. That output is a short-lived credential: connect it directly
|
|
|
557
558
|
to the MCP client and do not paste it into an agent transcript.
|
|
558
559
|
|
|
559
560
|
`rer business status` shows local pairing, service state and progress without
|
|
560
|
-
printing checkpoints or vendor data.
|
|
561
|
+
printing checkpoints or vendor data. Device credentials are stored separately
|
|
562
|
+
for each Business on an origin; disconnect also finds an older per-origin
|
|
563
|
+
credential through its original pairing record and revokes it once.
|
|
564
|
+
`rer business disconnect` revokes this
|
|
561
565
|
device through device-authenticated `DELETE /api/business/executors/self` before
|
|
562
566
|
removing its service, device and vendor credentials, state and introduced Claude
|
|
563
567
|
rules, preserving preexisting settings and unrelated edits. It says "Device
|
|
@@ -583,7 +587,14 @@ an explicit error. Revocation stops the supervisor on its next 401; it then
|
|
|
583
587
|
removes the device credential if it may and `status` says revoked. While it
|
|
584
588
|
waits, `run` says what for: the owner's permission to scan the folder connect
|
|
585
589
|
ran in (with the Your tools link) until this computer's scan is done, then the
|
|
586
|
-
owner's next step.
|
|
590
|
+
owner's next step.
|
|
591
|
+
If the server reports that this computer's scan failed, run and next instead
|
|
592
|
+
point the owner to **Retry** on **Your tools**, without asking for consent again.
|
|
593
|
+
Connect, next and run carry the Business profile into first-party checkouts
|
|
594
|
+
shown by `rer list` in the current or original pairing folder, including stopped
|
|
595
|
+
apps, as well as running and previously carried apps. Each skipped checkout
|
|
596
|
+
is named with its cause; a folder with no apps gets a next step.
|
|
597
|
+
It removes `run.lock` on every exit, including Ctrl-C,
|
|
587
598
|
SIGTERM and a closed terminal (SIGHUP); a lock whose process is gone, or that
|
|
588
599
|
has not been refreshed for two minutes, is cleared on the next start.
|
|
589
600
|
|
package/global/cli/layout.mjs
CHANGED
|
@@ -32,6 +32,9 @@ if [ -z "$node" ]; then
|
|
|
32
32
|
echo "rer: Node is missing. Run: curl -fsSL https://runeditrun.com/install.sh | sh" >&2
|
|
33
33
|
exit 127
|
|
34
34
|
fi
|
|
35
|
+
RER_INVOKED_AS=rer
|
|
36
|
+
if [ "$(command -v rer 2>/dev/null || true)" != "$0" ]; then RER_INVOKED_AS="$0"; fi
|
|
37
|
+
export RER_INVOKED_AS
|
|
35
38
|
exec "$node" "$root/current/global/rer.mjs" "$@"
|
|
36
39
|
`;
|
|
37
40
|
}
|
package/global/launch/facts.mjs
CHANGED
|
@@ -40,35 +40,7 @@ export async function needsInstall(root, last) {
|
|
|
40
40
|
return false;
|
|
41
41
|
}
|
|
42
42
|
|
|
43
|
-
|
|
44
|
-
// rer-cli-2); for older pins, when its primary private settings file holds
|
|
45
|
-
// anything. The pin's describe names it (`local.settings`, where the pin has it).
|
|
46
|
-
export async function hasSettings(root, described) {
|
|
47
|
-
if (typeof described?.local?.prepared === 'boolean') return described.local.prepared;
|
|
48
|
-
const primary = described?.local?.settings?.[0] ?? '.dev.vars';
|
|
49
|
-
try { return (await stat(join(root, primary))).size > 0; } catch (error) { if (error.code === 'ENOENT') return false; throw error; }
|
|
50
|
-
}
|
|
51
|
-
|
|
52
|
-
// Every pin's setup saves its answers file only once it has finished, so a
|
|
53
|
-
// file newer than this launcher's record of its own attempt (its start for
|
|
54
|
-
// 'running', its end for 'failed') is a setup that finished after it.
|
|
55
|
-
async function finishedSince(root, described, at) {
|
|
56
|
-
const saved = await mtime(join(root, described?.local?.installerState ?? '.seed/installer', 'setup-answers.json'));
|
|
57
|
-
return saved !== undefined && typeof at === 'number' && saved > at;
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
// Setup runs on a checkout with no saved settings ('fresh'). When a setup this
|
|
61
|
-
// launcher started did not finish ('running' after a kill, or 'failed') and no
|
|
62
|
-
// setup has finished since, it runs again ('resume') and keeps what the earlier
|
|
63
|
-
// attempt saved. A checkout set up any other way is never set up again.
|
|
64
|
-
// A checkout that is not prepared but already holds an owner (a setting a newer
|
|
65
|
-
// manifest added is missing) resumes too, so the saved owner and origin are
|
|
66
|
-
// kept; one without a saved owner gets the local owner ('fresh').
|
|
67
|
-
export async function setupNeeded(root, described, last) {
|
|
68
|
-
if (!await hasSettings(root, described)) return described?.local?.ownerSaved === true ? 'resume' : 'fresh';
|
|
69
|
-
if (!last || last.state === 'done') return undefined;
|
|
70
|
-
return await finishedSince(root, described, last.at) ? undefined : 'resume';
|
|
71
|
-
}
|
|
43
|
+
export { hasSettings, setupNeeded } from '../../cli/checkout-preparation.mjs';
|
|
72
44
|
|
|
73
45
|
// Only a positive listener observation justifies saying another process took it.
|
|
74
46
|
export async function portTaken(port) {
|
package/global/launch/state.mjs
CHANGED
|
@@ -9,16 +9,13 @@
|
|
|
9
9
|
// server.json that server's PID and start time, and the process rer spawned
|
|
10
10
|
// stop.json when rer dev --stop last ran: a launch requested before it stops
|
|
11
11
|
// pin-install.json the process installing the checkout's pinned rer package
|
|
12
|
-
import { createHash } from 'node:crypto';
|
|
13
12
|
import { appendFile, link, mkdir, readFile, readdir, realpath, rm, writeFile } from 'node:fs/promises';
|
|
14
|
-
import {
|
|
13
|
+
import { join } from 'node:path';
|
|
15
14
|
import { processInfo } from '../../modules/job-queue/processes.mjs';
|
|
16
15
|
import { serversDirectory } from '../registry.mjs';
|
|
17
16
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
return join(serversDirectory(env), 'launches', `${name}-${createHash('sha256').update(checkout).digest('hex').slice(0, 12)}`);
|
|
21
|
-
}
|
|
17
|
+
import { launchPath } from '../../cli/checkout-preparation.mjs';
|
|
18
|
+
export { launchPath };
|
|
22
19
|
|
|
23
20
|
export async function launchDirectory(checkout, env = process.env) {
|
|
24
21
|
const directory = launchPath(checkout, env);
|
package/global/list.mjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// rer list [DIR] [--json]: the immediate subfolders of DIR that hold an
|
|
2
2
|
// OPERATIONS.json, newest change first, with what rer dev can do for each.
|
|
3
3
|
import { execFile } from 'node:child_process';
|
|
4
|
-
import {
|
|
4
|
+
import { realpath, stat } from 'node:fs/promises';
|
|
5
5
|
import { join, resolve } from 'node:path';
|
|
6
6
|
import { promisify } from 'node:util';
|
|
7
|
-
import { descriptorProfile
|
|
7
|
+
import { descriptorProfile } from './checkout.mjs';
|
|
8
8
|
import { liveServers } from './registry.mjs';
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { checkoutPreparation } from '../cli/checkout-preparation.mjs';
|
|
10
|
+
import { checkoutFolders } from '../cli/checkout-folders.mjs';
|
|
11
11
|
|
|
12
12
|
const run = promisify(execFile);
|
|
13
13
|
const reasons = {
|
|
@@ -27,12 +27,10 @@ async function entry(path, running) {
|
|
|
27
27
|
if (!result.launchable) result.reason = reasons[facts.profile] ?? `OPERATIONS.json is version ${facts.version ?? '(none)'}, which rer does not run`;
|
|
28
28
|
result.prepared = null;
|
|
29
29
|
if (profile === 'first-party') {
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if (
|
|
34
|
-
else try { result.prepared = !await setupNeeded(path, await describeCheckout(path, dispatcher(path).entry, process.env), await setupState.read(launchPath(path))); }
|
|
35
|
-
catch (failure) { result.launchable = false; result.reason = `rer describe fails here: ${failure.message.split('\n')[0]}`; }
|
|
30
|
+
const status = await checkoutPreparation(path);
|
|
31
|
+
result.prepared = status.prepared;
|
|
32
|
+
if (status.reason) result.reason = status.reason;
|
|
33
|
+
if (status.prepared === null) result.launchable = false;
|
|
36
34
|
}
|
|
37
35
|
result.url = running.get(path) ?? null;
|
|
38
36
|
result.changedAt = new Date(await changed(path)).toISOString();
|
|
@@ -45,11 +43,7 @@ export async function listCommand(args) {
|
|
|
45
43
|
let directory;
|
|
46
44
|
try { directory = await realpath(resolve(positional[0] ?? '.')); } catch { process.stderr.write(`rer list: ${resolve(positional[0] ?? '.')} is not a folder.\n`); return 3; }
|
|
47
45
|
const running = new Map((await liveServers()).map(record => [record.checkout, record.url]));
|
|
48
|
-
const folders =
|
|
49
|
-
for (const item of await readdir(directory, { withFileTypes: true })) {
|
|
50
|
-
const path = join(directory, item.name);
|
|
51
|
-
try { if ((await stat(path)).isDirectory() && (await stat(join(path, 'OPERATIONS.json'))).isFile()) folders.push(await realpath(path)); } catch {}
|
|
52
|
-
}
|
|
46
|
+
const folders = await checkoutFolders(directory);
|
|
53
47
|
const checkouts = [];
|
|
54
48
|
for (let i = 0; i < folders.length; i += 4) checkouts.push(...await Promise.all(folders.slice(i, i + 4).map(path => entry(path, running))));
|
|
55
49
|
checkouts.sort((a, b) => b.changedAt.localeCompare(a.changedAt) || a.name.localeCompare(b.name));
|
|
@@ -7,19 +7,21 @@ import { createProtocol } from './protocol.mjs';
|
|
|
7
7
|
import { autonomousPolicy, heldPolicy } from './crypto.mjs';
|
|
8
8
|
import { discoverDoor, listedDoor } from './discovery.mjs';
|
|
9
9
|
import { runJourney } from './journey.mjs';
|
|
10
|
-
import { unsetPolicy, removalPhase, blockedPhases, pausePhase, consentRevocationPhase } from './policy-phases.mjs';
|
|
10
|
+
import { unsetPolicy, removalPhase, blockedPhases, pausePhase, consentRevocationPhase, agentRevocationPhase } from './policy-phases.mjs';
|
|
11
|
+
import { unpairPhase } from './unpair.mjs';
|
|
11
12
|
import { negativePhase } from './negative.mjs';
|
|
12
13
|
import { replayAdmissionPhase } from './replay.mjs';
|
|
13
14
|
import { webhookPhase } from './webhooks.mjs';
|
|
14
15
|
import { recordSecurityPhase } from './security.mjs';
|
|
15
16
|
import { crossSponsorPhase } from './sponsors.mjs';
|
|
16
|
-
import { auditPhase } from './audit.mjs';
|
|
17
|
+
import { auditPhase, auditRows } from './audit.mjs';
|
|
18
|
+
import { relayPhase } from './relay.mjs';
|
|
17
19
|
import { invocationPhase } from './invocation.mjs';
|
|
18
20
|
|
|
19
21
|
export { validateAgentSurface } from './surface.mjs';
|
|
20
22
|
|
|
21
23
|
/** Run against a fresh, real installation using its HTTP and person doors. */
|
|
22
|
-
export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare, initializeAgent }) {
|
|
24
|
+
export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare, initializeAgent, unpair }) {
|
|
23
25
|
const validation = validateAgentSurface(surface), points = [...validation.points];
|
|
24
26
|
if (!validation.ok) return { ok: false, points };
|
|
25
27
|
const capabilities = capabilitySet(surface.capabilities);
|
|
@@ -34,7 +36,11 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
|
|
|
34
36
|
}
|
|
35
37
|
}
|
|
36
38
|
await c.phase('BASE-AGENT-001.transport', () => discoverDoor(c));
|
|
37
|
-
await c.phase('BASE-AGENT-007.phase0', () =>
|
|
39
|
+
await c.phase('BASE-AGENT-007.phase0', async () => {
|
|
40
|
+
await unsetPolicy(c, true);
|
|
41
|
+
// No Business envelope existed for these audits, so they cannot be relayed.
|
|
42
|
+
c.unattributedAuditIds = new Set((await auditRows(c, { agents: [null], includeFixtures: true })).rows.map(row => row.id));
|
|
43
|
+
});
|
|
38
44
|
await c.phase('BASE-AGENT-007.phase1', () => removalPhase(c));
|
|
39
45
|
await c.phase('BASE-AGENT-013.phase2', async () => { await c.adopt(autonomousPolicy()); await c.prepare('autonomous'); await listedDoor(c); await runJourney(c, 'autonomous', { injections: true, replay: true }); });
|
|
40
46
|
await c.phase('BASE-AGENT-013.phase3', async () => { await c.prepare('held'); await c.adopt(heldPolicy()); await runJourney(c, 'held', { held: true }); });
|
|
@@ -42,6 +48,7 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
|
|
|
42
48
|
await c.phase('BASE-AGENT-011.phase5', () => pausePhase(c));
|
|
43
49
|
await c.phase('BASE-AGENT-004.phase6', () => negativePhase(c));
|
|
44
50
|
await c.phase('BASE-AGENT-004.consent', () => consentRevocationPhase(c));
|
|
51
|
+
await c.phase('BASE-AGENT-004.6.seed', () => agentRevocationPhase(c, initializeAgent));
|
|
45
52
|
if (invoke) await c.phase('BASE-AGENT-012.invocation', () => invocationPhase(c, invoke));
|
|
46
53
|
if (nativeJourney) await c.phase('BASE-AGENT-013.native-journey', async () => { await nativeJourney({ tool: c.tool }); c.add('BASE-AGENT-013.native-journey', true); });
|
|
47
54
|
if (surface.tools.some(tool => tool.authority === 'none')) await c.phase('BASE-AGENT-005.no-subject', () => recordSecurityPhase(c));
|
|
@@ -50,6 +57,8 @@ export async function runAgentDoorConformance({ fetch, invoke, origin, surface,
|
|
|
50
57
|
await c.phase('BASE-AGENT-subset.refusals', () => refusalPhase(c));
|
|
51
58
|
if (capabilities.mode === 'declared' && offers(surface.capabilities, 'subscriptions')) await c.phase('BASE-AGENT-subset.subscriptions', () => subscriptionPhase(c));
|
|
52
59
|
await c.phase('BASE-AGENT-009.phase7', () => auditPhase(c));
|
|
60
|
+
await c.phase('BASE-AGENT-009.relay', () => relayPhase(c));
|
|
53
61
|
if (sponsors.length > 1) await c.phase('BASE-AGENT-004.cross-sponsor', () => crossSponsorPhase(c, sponsors, initializeAgent));
|
|
62
|
+
if (unpair) await c.phase('BASE-AGENT-004.7', () => unpairPhase(c, unpair, sponsors));
|
|
54
63
|
return { ok: points.every(point => point.ok), points, capabilities };
|
|
55
64
|
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { isDeepStrictEqual } from 'node:util';
|
|
2
2
|
import { webcrypto } from 'node:crypto';
|
|
3
|
-
import {
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { accessToken, autonomousPolicy, policyEnvelope, signJws, seconds } from './crypto.mjs';
|
|
4
5
|
import { errorCode } from './protocol.mjs';
|
|
5
6
|
import { nativeStepHook } from './step-hooks.mjs';
|
|
6
7
|
import { erasedStep } from './erasure.mjs';
|
|
@@ -129,3 +130,29 @@ export async function consentRevocationPhase(c) {
|
|
|
129
130
|
await c.adopt(autonomousPolicy());
|
|
130
131
|
c.add('BASE-AGENT-004.consent-no-effect', isDeepStrictEqual(before, await c.witness()), 'A call under revoked consent changed native state.');
|
|
131
132
|
}
|
|
133
|
+
|
|
134
|
+
/** The installation's own revocation ends an agent's Business tokens: a fresh token for the same agent is refused. */
|
|
135
|
+
export async function agentRevocationPhase(c, initializeAgent) {
|
|
136
|
+
await c.adopt(autonomousPolicy());
|
|
137
|
+
await c.prepare('revocation');
|
|
138
|
+
const agentId = `rer-conformance-${randomUUID()}`, throwaway = { ...c, agentId, consent: randomUUID() };
|
|
139
|
+
if (initializeAgent) {
|
|
140
|
+
try { await initializeAgent({ agentId, person: c.person }); }
|
|
141
|
+
catch {
|
|
142
|
+
c.add('BASE-AGENT-001.agent-initializer', false, 'Native agent initialization failed; no captured mail, credentials or fixture values are logged.');
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const witness = { name: c.surface.witness.tool, arguments: c.resolve(c.surface.witness.args) };
|
|
147
|
+
const call = async method => c.mcp(method, method === 'tools/call' ? witness : {}, { token: await accessToken(throwaway), track: false });
|
|
148
|
+
const challenged = answer => answer.status === 401 && /resource_metadata="/.test(answer.headers.get('www-authenticate') ?? '');
|
|
149
|
+
const admitted = await call('tools/call');
|
|
150
|
+
c.add('BASE-AGENT-004.6.seed-admitted', admitted.status === 200 && admitted.result?.structuredContent !== undefined && !admitted.result.isError, 'A throwaway agent must be admitted before its revocation.');
|
|
151
|
+
const before = await c.witness();
|
|
152
|
+
const revoke = await c.personRequest(`/agents/api/agents/${encodeURIComponent(agentId)}/revoke`, { method: 'POST', body: '{}' });
|
|
153
|
+
await revoke.body?.cancel();
|
|
154
|
+
c.add('BASE-AGENT-004.6.seed-revoke', revoke.status === 200, 'The signed-in owner must be able to revoke the throwaway agent through the person door.');
|
|
155
|
+
const refused = await call('tools/call'), listed = await call('tools/list');
|
|
156
|
+
c.add('BASE-AGENT-004.6.seed-revoked', challenged(refused) && challenged(listed), 'After the installation revokes an agent, a fresh Business token for the same agent must receive 401 with a resource_metadata challenge on every method.');
|
|
157
|
+
c.add('BASE-AGENT-004.6.seed-unchanged', isDeepStrictEqual(before, await c.witness()), 'A call under a revoked agent changed native state, or the main agent lost access.');
|
|
158
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { randomUUID, webcrypto } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { seconds, signJws } from './crypto.mjs';
|
|
4
|
+
import { auditRows } from './audit-rows.mjs';
|
|
5
|
+
|
|
6
|
+
const liveKeys = ['id','seq','at','tool','disposition','outcome','code','revision','classes','agent','consent','execution_of','replay_of','approval','review','resources','resource_count'].sort();
|
|
7
|
+
const erasedKeys = ['id','seq','at','erased','tool','classes','disposition','agent'].sort();
|
|
8
|
+
const keys = (value, expected) => value && typeof value === 'object' && !Array.isArray(value) && isDeepStrictEqual(Object.keys(value).sort(), expected);
|
|
9
|
+
|
|
10
|
+
/** Exercise the signed pull against the same hosted door and its native audit. */
|
|
11
|
+
export async function relayPhase(c) {
|
|
12
|
+
const path = '/api/rer/agent-decisions', iat = seconds(c.now);
|
|
13
|
+
const payload = { v:1, iss:c.signer.issuer, aud:c.origin, sub:c.signer.installationId, business:c.business, after:0, limit:200, iat, exp:iat+60, jti:randomUUID() };
|
|
14
|
+
const sign = value => signJws(c.signer.privateKey, c.signer.kid, 'rer-agent-decisions+jwt', value);
|
|
15
|
+
const request = pull => c.request(path, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({pull}) });
|
|
16
|
+
const pull = await sign(payload), first = await request(pull), raw = await first.text();
|
|
17
|
+
c.add('BASE-AGENT-009.relay.route', first.status === 200, `Signed decision pull must return 200, got ${first.status}.`);
|
|
18
|
+
if (first.status !== 200) return;
|
|
19
|
+
let page = JSON.parse(raw), after = 0;
|
|
20
|
+
const projections = [];
|
|
21
|
+
for (let count = 0; ; count++) {
|
|
22
|
+
const shaped = keys(page, ['cursor','decisions','head','more']) && Array.isArray(page.decisions) && page.decisions.length <= 200 &&
|
|
23
|
+
Number.isSafeInteger(page.head) && page.head >= 0 && Number.isSafeInteger(page.cursor) && page.cursor >= after &&
|
|
24
|
+
page.cursor === (page.decisions.at(-1)?.seq ?? after) && page.more === (page.cursor < page.head) &&
|
|
25
|
+
Buffer.byteLength(JSON.stringify(page)) <= 65536 && page.decisions.every((row, index, rows) =>
|
|
26
|
+
keys(row, row.erased === true ? erasedKeys : liveKeys) && Number.isSafeInteger(row.seq) && row.seq > (rows[index-1]?.seq ?? after));
|
|
27
|
+
c.add(`BASE-AGENT-009.relay.page.${count}`, shaped, 'Decision page must be closed, ordered, bounded and carry its exact cursor and head.');
|
|
28
|
+
if (!shaped) return;
|
|
29
|
+
projections.push(...page.decisions);
|
|
30
|
+
if (!page.more) break;
|
|
31
|
+
if (count >= 99 || page.cursor <= after) throw new Error('Decision relay did not advance within 100 pages');
|
|
32
|
+
after = page.cursor;
|
|
33
|
+
const response = await request(await sign({...payload, after}));
|
|
34
|
+
if (response.status !== 200) throw new Error(`Decision page HTTP ${response.status}`);
|
|
35
|
+
page = await response.json();
|
|
36
|
+
}
|
|
37
|
+
const audit = (await auditRows(c, {agents:[null], includeFixtures:true})).rows;
|
|
38
|
+
const expected = audit.filter(row => !c.unattributedAuditIds?.has(row.id) && (row.door === 'mcp' && row.consent != null || row.tombstone && projections.some(item => item.id === row.id)));
|
|
39
|
+
c.add('BASE-AGENT-009.relay.unattributed', projections.every(row => !c.unattributedAuditIds?.has(row.id)), 'Calls before the first adopted envelope must stay out of the Business feed.');
|
|
40
|
+
const reviews = new Map((expected.some(row => row.review) ? (await c.personJson('/agents/api/reviews')).reviews : []).map(row => [row.id,row]));
|
|
41
|
+
c.add('BASE-AGENT-009.relay.count', projections.length > 0 && projections.length === expected.length && new Set(projections.map(row => row.id)).size === projections.length, 'Exactly one projection must exist per Business MCP audit, including erased decisions.');
|
|
42
|
+
for (const row of expected) {
|
|
43
|
+
const projected = projections.find(item => item.id === row.id);
|
|
44
|
+
const common = {id:row.id,seq:projected?.seq,at:row.at,tool:row.tool,classes:row.classes.map(item=>item.class),disposition:row.decision,agent:row.agent.id};
|
|
45
|
+
let value;
|
|
46
|
+
if (row.tombstone) value = {...common,erased:true};
|
|
47
|
+
else {
|
|
48
|
+
const links = row.tool === 'resources/read' && typeof row.resource === 'string' ? [row.resource] : row.resources ?? [];
|
|
49
|
+
const approval = row.approval ? (await c.personJson(`/agents/api/approvals/${encodeURIComponent(row.approval.id)}`)).approval : null;
|
|
50
|
+
value = {...common,outcome:row.outcome,code:row.code && /^[a-z][a-z0-9_]{0,63}$/.test(row.code)?row.code:null,revision:row.revision,consent:row.consent,
|
|
51
|
+
execution_of:row.decision_id,replay_of:row.replay_of,approval:approval?{state:approval.state,expires_at:approval.expires_at}:null,
|
|
52
|
+
review:row.review?{state:reviews.get(row.review.id)?.state}:null,resources:links.filter(uri=>typeof uri==='string' && uri.length<=512).slice(0,8),resource_count:row.tool==='resources/read'?links.length:row.resource_count??links.length};
|
|
53
|
+
}
|
|
54
|
+
c.add(`BASE-AGENT-009.relay.decision.${row.id}`, isDeepStrictEqual(projected,value), 'Projection must equal only the public audit fields and current approval/review state.');
|
|
55
|
+
}
|
|
56
|
+
const replay = await request(pull);
|
|
57
|
+
c.add('BASE-AGENT-009.relay.replay', replay.status === 200 && await replay.text() === raw, 'The same pull must return byte-identical content.');
|
|
58
|
+
const empty = await request(await sign({...payload,after:page.cursor}));
|
|
59
|
+
c.add('BASE-AGENT-009.relay.cursor', empty.status === 200 && isDeepStrictEqual(await empty.json(),{decisions:[],cursor:page.cursor,head:page.head,more:false}), 'Pulling after the final cursor must return an empty page.');
|
|
60
|
+
const foreign = await webcrypto.subtle.generateKey({name:'ECDSA',namedCurve:'P-256'},true,['sign','verify']);
|
|
61
|
+
const refused = await request(await signJws(foreign.privateKey,c.signer.kid,'rer-agent-decisions+jwt',payload));
|
|
62
|
+
c.add('BASE-AGENT-009.relay.foreign', refused.status === 401 && isDeepStrictEqual(await refused.json(),{code:'relay_unauthenticated'}), 'A foreign signature must return only 401 relay_unauthenticated.');
|
|
63
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { accessToken, autonomousPolicy } from './crypto.mjs';
|
|
4
|
+
|
|
5
|
+
const challenged = response => response.status === 401 && /resource_metadata="/.test(response.headers.get('www-authenticate') ?? '');
|
|
6
|
+
const version = '2026-07-28';
|
|
7
|
+
|
|
8
|
+
/** After the driver unpairs the installation, Business tokens end and native access stays.
|
|
9
|
+
* Probes go straight to the origin: policy renewal is no longer possible once unpaired. */
|
|
10
|
+
export async function unpairPhase(c, unpair, sponsors) {
|
|
11
|
+
if (typeof unpair !== 'function') throw new TypeError('Unpair conformance requires the driver to provide unpair().');
|
|
12
|
+
await c.adopt(autonomousPolicy());
|
|
13
|
+
await c.prepare('unpair');
|
|
14
|
+
const raw = (path, init = {}) => c.fetch(new URL(path, `${c.origin}/`).href, { redirect: 'manual', ...init });
|
|
15
|
+
let id = 0;
|
|
16
|
+
const rpc = async (method, token, params = {}) => {
|
|
17
|
+
const response = await raw('/mcp', { method: 'POST', headers: {
|
|
18
|
+
Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', Origin: c.origin, 'MCP-Protocol-Version': version, 'Mcp-Method': method,
|
|
19
|
+
...(method === 'tools/call' ? { 'Mcp-Name': params.name } : {}), Authorization: `Bearer ${token}`,
|
|
20
|
+
}, body: JSON.stringify({ jsonrpc: '2.0', id: ++id, method, params: { ...params, _meta: { 'io.modelcontextprotocol/protocolVersion': version, 'io.modelcontextprotocol/clientCapabilities': {} } } }) });
|
|
21
|
+
const body = await response.json().catch(() => ({}));
|
|
22
|
+
return { response, body };
|
|
23
|
+
};
|
|
24
|
+
const witness = { name: c.surface.witness.tool, arguments: c.resolve(c.surface.witness.args) };
|
|
25
|
+
const principals = [['owner', c.person], ...sponsors.slice(1).map(person => [`cross-sponsor.${person.label}`, person])];
|
|
26
|
+
const tokens = new Map();
|
|
27
|
+
for (const [label, person] of principals) tokens.set(label, await accessToken({ ...c, person, agentId: `rer-conformance-${randomUUID()}`, consent: randomUUID() }));
|
|
28
|
+
const metadata = async () => (await (await raw('/.well-known/oauth-protected-resource/mcp')).json().catch(() => ({}))).authorization_servers;
|
|
29
|
+
const clients = [...c.clients.entries()];
|
|
30
|
+
for (const [label, token] of tokens) {
|
|
31
|
+
const listed = await rpc('tools/list', token);
|
|
32
|
+
c.add(`BASE-AGENT-004.7.paired.${label}`, listed.response.status === 200 && Array.isArray(listed.body.result?.tools), 'A Business token must be admitted while the installation is paired.');
|
|
33
|
+
}
|
|
34
|
+
c.add('BASE-AGENT-004.7.paired.metadata', isDeepStrictEqual(await metadata(), [c.signer.issuer]), 'Paired metadata must name the Business issuer.');
|
|
35
|
+
await unpair();
|
|
36
|
+
for (const [label, token] of tokens) {
|
|
37
|
+
const listed = await rpc('tools/list', token), called = await rpc('tools/call', token, witness);
|
|
38
|
+
c.add(`BASE-AGENT-004.7.token.${label}`, challenged(listed.response) && challenged(called.response), 'After unpairing, a Business token from the same signer must receive 401 with a resource_metadata challenge on every method.');
|
|
39
|
+
}
|
|
40
|
+
c.add('BASE-AGENT-004.7.metadata', isDeepStrictEqual(await metadata(), []), 'After unpairing, protected resource metadata must name no authorization server.');
|
|
41
|
+
const state = await raw('/agents/api/state', { headers: { Origin: c.origin, Cookie: c.person.cookie } }), body = await state.json().catch(() => ({}));
|
|
42
|
+
c.add('BASE-AGENT-004.7.session', state.status === 200 && body.paired === false, 'After unpairing, the owner session must still read the door state, now unpaired.');
|
|
43
|
+
for (const [label, client] of clients) {
|
|
44
|
+
const listed = await rpc('tools/list', client.token);
|
|
45
|
+
c.add(`BASE-AGENT-004.7.native.${label}`, listed.response.status === 200 && Array.isArray(listed.body.result?.tools), 'After unpairing, a declared native fixture client must still be admitted.');
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -39,8 +39,12 @@ export async function migrateOperator(context, database) {
|
|
|
39
39
|
await writePrivateFile(path, JSON.stringify({ name: config.name, compatibility_date: config.compatibility_date,
|
|
40
40
|
d1_databases: [{ ...binding, migrations_dir: inventory, migrations_pattern: `${inventory}/*.sql` }] }));
|
|
41
41
|
try {
|
|
42
|
+
// Wrangler redraws the full history after every migration. Keep warnings and
|
|
43
|
+
// errors, then name the migrations actually applied from the durable ledger.
|
|
44
|
+
const pending = names.filter(name => !before.has(name));
|
|
45
|
+
if (pending.length) store.report(`Applying ${pending.length} local migrations.`);
|
|
42
46
|
await context.run(labels.migrate, 'pnpm', ['exec', 'wrangler', 'd1', 'migrations', 'apply', database,
|
|
43
|
-
'--local', '--persist-to', state, '--config', path], { step: 'setup' });
|
|
47
|
+
'--local', '--persist-to', state, '--config', path], { step: 'setup', env: { ...process.env, WRANGLER_LOG: 'warn' } });
|
|
44
48
|
const after = await appliedNames(state, table);
|
|
45
49
|
const applied = names.filter(name => !before.has(name) && after.has(name));
|
|
46
50
|
if (applied.length) store.report(`Applied local migrations: ${applied.join(', ')}`);
|