@runeditrun/rer 0.2.85 → 0.2.87
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-bindings.mjs +25 -0
- package/cli/agent-door.mjs +145 -0
- package/cli/agent-fixtures.mjs +16 -0
- package/cli/agent-journey-fixtures.mjs +17 -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-rpc.mjs +23 -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-verifier.mjs +31 -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 +89 -0
- package/cli/door-clauses.mjs +157 -0
- package/cli/export.mjs +17 -4
- package/cli/hosted-output.mjs +31 -8
- 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/managed-data.mjs +8 -4
- package/cli/portability-empty.mjs +6 -0
- package/cli/portability-migrations.mjs +26 -4
- package/cli/portability-worker.mjs +2 -1
- package/cli/portability.mjs +1 -0
- package/cli/production-auth.mjs +2 -2
- package/cli/production-mail.mjs +19 -3
- package/cli/server-registry.mjs +2 -0
- package/edition-authoring/archive-source.mjs +65 -0
- package/edition-authoring/base-copies.mjs +108 -21
- package/edition-authoring/cli.mjs +1 -1
- package/edition-authoring/copy-namespaces.mjs +28 -0
- package/edition-authoring/edition-migrations.mjs +7 -3
- package/edition-authoring/files.mjs +2 -1
- package/edition-authoring/module-closure.mjs +58 -27
- package/edition-authoring/module-edges.mjs +13 -2
- package/edition-authoring/workflow-copies.mjs +1 -1
- package/edition-authoring/workflow-scripts.mjs +12 -3
- package/foundation/runtime/contract-docs.mjs +220 -32
- package/foundation/runtime/contract-prose-patterns.mjs +14 -0
- package/foundation/runtime/contract-prose.mjs +88 -0
- package/global/CHANGELOG.md +151 -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-pages.mjs +11 -0
- package/modules/agent-door/conformance/audit-rows.mjs +20 -0
- package/modules/agent-door/conformance/audit.mjs +63 -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/fixtures.mjs +41 -0
- package/modules/agent-door/conformance/index.mjs +41 -0
- package/modules/agent-door/conformance/injection.mjs +24 -0
- package/modules/agent-door/conformance/invocation.mjs +33 -0
- package/modules/agent-door/conformance/journey.mjs +117 -0
- package/modules/agent-door/conformance/narrowing.d.mts +2 -0
- package/modules/agent-door/conformance/narrowing.mjs +29 -0
- package/modules/agent-door/conformance/negative.mjs +48 -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 +83 -0
- package/modules/agent-door/conformance/protocol.mjs +153 -0
- package/modules/agent-door/conformance/replay.mjs +39 -0
- package/modules/agent-door/conformance/schema.mjs +71 -0
- package/modules/agent-door/conformance/security.mjs +34 -0
- package/modules/agent-door/conformance/sponsors.mjs +68 -0
- package/modules/agent-door/conformance/step-hooks.mjs +4 -0
- package/modules/agent-door/conformance/surface.mjs +92 -0
- package/modules/agent-door/conformance/target.mjs +19 -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 +31 -0
- package/modules/container/image-variables.mjs +8 -2
- package/modules/delivery-producer/mail.mjs +20 -0
- 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 +37 -13
- package/modules/portability/bridge.mjs +22 -2
- package/modules/portability/catalogue.mjs +12 -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,117 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { classIds, subset, errorCode, APPROVAL } from './protocol.mjs';
|
|
4
|
+
import { grantSet, narrowingTargets } from './narrowing.mjs';
|
|
5
|
+
import { schemaErrors } from './schema.mjs';
|
|
6
|
+
import { checkTarget } from './target.mjs';
|
|
7
|
+
import { nativeStepHook } from './step-hooks.mjs';
|
|
8
|
+
import { injectionArgs } from './injection.mjs';
|
|
9
|
+
|
|
10
|
+
export function checkClasses(c, step, answer, phase) {
|
|
11
|
+
const actual = answer.decision?.classes;
|
|
12
|
+
c.add(`BASE-AGENT-006.2.${phase}.${step.id}`, isDeepStrictEqual(classIds(actual), classIds(step.expect)) && step.expect.every(expected => actual?.some(item => item.class === expected.class && subset(item.facts, expected.facts ?? {}))), `${step.tool} computed classes/facts differ from ${step.id}: ${JSON.stringify(actual)}.`);
|
|
13
|
+
}
|
|
14
|
+
function checkOutput(c, step, answer, phase) {
|
|
15
|
+
const schema = c.listed.get(step.tool)?.outputSchema;
|
|
16
|
+
const errors = schema === undefined ? ['missing outputSchema'] : schemaErrors(schema, answer.result?.structuredContent);
|
|
17
|
+
c.add(`BASE-AGENT-002.2.${phase}.${step.id}`, errors.length === 0, `${step.tool} output does not validate: ${errors.slice(0, 8).join('; ')}.`);
|
|
18
|
+
}
|
|
19
|
+
async function checkResources(c, step, answer, phase, held) {
|
|
20
|
+
const links = answer.result?.content?.filter(item => item.type === 'resource_link') ?? [];
|
|
21
|
+
for (const [i, link] of links.entries()) {
|
|
22
|
+
const read = await c.mcp('resources/read', { uri: link.uri }, step.client === undefined ? {} : { client: step.client });
|
|
23
|
+
const classes = read.decision?.classes, needsApproval = held && classes?.some(item => item.class !== 'standard');
|
|
24
|
+
c.add(`BASE-AGENT-006.2.resource.${phase}.${step.id}.${i}`, Array.isArray(classes) && classes.length > 0 && read.decision.revision === c.revision && classes.every(item => item.do === (held ? item.class === 'standard' ? 'review' : 'approval' : 'autonomous')), `${link.uri} must apply the policy to its computed resource classes.`);
|
|
25
|
+
c.add(`BASE-AGENT-003.4.${phase}.${step.id}.${i}`, read.status === 200 && (needsApproval
|
|
26
|
+
? errorCode(read) === 'approval_required' && read.decision?.disposition === 'approval' && !read.result?.contents?.length
|
|
27
|
+
: !read.message?.error && read.decision?.disposition === (held ? 'review' : 'autonomous') && Array.isArray(read.result?.contents) && read.result.contents.length > 0), `${step.tool} resource_link ${link.uri} must ${needsApproval ? 'withhold content pending approval' : 'read back under the current policy'}.`);
|
|
28
|
+
if (needsApproval) {
|
|
29
|
+
const pending = read.body?.error?.data?.approval;
|
|
30
|
+
c.add(`BASE-AGENT-007.5.resource.${phase}.${step.id}.${i}`, pending?.id && typeof pending.url === 'string' && new URL(pending.url, c.origin).origin === c.origin && Number.isFinite(Date.parse(pending.expires_at)), `${link.uri} must expose a pending approval on the native person door.`);
|
|
31
|
+
if (pending?.id) {
|
|
32
|
+
const { approval } = await c.personJson(`/agents/api/approvals/${encodeURIComponent(pending.id)}`);
|
|
33
|
+
c.add(`BASE-AGENT-008.5.resource-summary.${phase}.${step.id}.${i}`, approval?.id === pending.id && approval.decision_id === read.decision.id && approval.revision === c.revision && /^[a-f0-9]{64}$/.test(approval.summary_sha256), `${link.uri} pending read must expose its exact summary hash and revision.`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
export async function runJourney(c, phase, { held = false, injections = false, replay = false } = {}) {
|
|
39
|
+
const outputs = new Map(); let replayed = false;
|
|
40
|
+
try {
|
|
41
|
+
for (const step of c.surface.journey) {
|
|
42
|
+
const args = c.args(step, outputs), needsApproval = held && step.expect.some(item => item.class !== 'standard');
|
|
43
|
+
await nativeStepHook(c, 'beforeStep', phase, step, args, outputs);
|
|
44
|
+
const narrowing = !held && c.surface.narrowings?.find(fixture => fixture.step === step.id);
|
|
45
|
+
const grantsBefore = narrowing ? await grantSet(c, narrowing.witness, outputs) : null;
|
|
46
|
+
const before = needsApproval ? await c.witness() : undefined;
|
|
47
|
+
const declared = c.surface.tools.find(tool => tool.name === step.tool);
|
|
48
|
+
let proof = {};
|
|
49
|
+
if (declared.proof) {
|
|
50
|
+
if (!held) {
|
|
51
|
+
const original = await c.witness(), challenge = await c.stepTool(step, args), bogus = await c.stepTool(step, args, { proofReference: 'bogus-native-proof' });
|
|
52
|
+
const fields = challenge.result?._meta?.['com.runeditrun/error'];
|
|
53
|
+
c.add(`BASE-AGENT-004.native-proof.${step.id}.challenge`, errorCode(challenge) === 'native_proof_required' && fields?.kind === declared.proofKind && typeof fields?.handoff === 'string' && new URL(fields.handoff).origin === c.origin, `${step.tool} requires its named native proof and a local human handoff.`);
|
|
54
|
+
c.add(`BASE-AGENT-004.native-proof.${step.id}.bogus`, errorCode(bogus) === 'native_proof_required' && isDeepStrictEqual(original, await c.witness()), `${step.tool} must refuse bogus proof with no native effect.`);
|
|
55
|
+
proof = await c.proof(step.tool, args, fields?.handoff, step.client);
|
|
56
|
+
} else proof = await c.proof(step.tool, args, undefined, step.client);
|
|
57
|
+
}
|
|
58
|
+
let answer = await c.stepTool(step, args, proof);
|
|
59
|
+
checkClasses(c, step, answer, phase);
|
|
60
|
+
await checkTarget(c, step, outputs, answer, phase);
|
|
61
|
+
const expectedDisposition = held ? needsApproval ? 'approval' : 'review' : 'autonomous';
|
|
62
|
+
c.add(`BASE-AGENT-007.1.${phase}.${step.id}`, answer.decision?.disposition === expectedDisposition && answer.decision.revision === c.revision && answer.decision.classes.every(item => item.do === (held ? item.class === 'standard' ? 'review' : 'approval' : 'autonomous')), `${step.tool} must receive ${expectedDisposition} under revision ${c.revision}.`);
|
|
63
|
+
if (needsApproval) {
|
|
64
|
+
const approval = answer.result?._meta?.[APPROVAL];
|
|
65
|
+
c.add(`BASE-AGENT-007.5.pending.${step.id}`, answer.result?.resultType === 'input_required' && approval?.id && typeof approval.url === 'string' && new URL(approval.url, c.origin).origin === c.origin && Number.isFinite(Date.parse(approval.expires_at)), `${step.tool} must return a pending handle, URL elicitation and expiry.`);
|
|
66
|
+
const after = await c.witness();
|
|
67
|
+
c.add(`BASE-AGENT-007.5.no-effect.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state before approval.`);
|
|
68
|
+
if (!approval?.id) continue;
|
|
69
|
+
const approved = await c.decideApproval(answer);
|
|
70
|
+
await checkTarget(c, step, outputs, answer, phase, true);
|
|
71
|
+
c.add(`BASE-AGENT-008.5.approver.${step.id}`, approved.ok, `Signed-in sponsor approval returned HTTP ${approved.status}.`);
|
|
72
|
+
answer = await c.stepTool(step, args, { ...proof, requestState: answer.result.requestState });
|
|
73
|
+
checkClasses(c, step, answer, `${phase}.approved`);
|
|
74
|
+
c.add(`BASE-AGENT-007.5.receipt.${step.id}`, !answer.result?.isError && answer.result?.resultType !== 'input_required' && Boolean(answer.result?._meta?.['com.runeditrun/receipt']) && answer.decision?.disposition === 'approval', 'The approved retry must complete with an approval receipt.');
|
|
75
|
+
}
|
|
76
|
+
c.add(`BASE-AGENT-013.4.${phase}.${step.id}`, answer.status === 200 && answer.result && !answer.result.isError && answer.result.resultType !== 'input_required', `${step.tool} did not complete (${errorCode(answer) ?? answer.status}).`);
|
|
77
|
+
if (answer.result?.isError || answer.result?.structuredContent === undefined) continue;
|
|
78
|
+
outputs.set(step.id, answer.result.structuredContent);
|
|
79
|
+
checkOutput(c, step, answer, phase);
|
|
80
|
+
await checkResources(c, step, answer, phase, held);
|
|
81
|
+
if (narrowing) {
|
|
82
|
+
const witnessArgs = c.resolve(narrowing.witness.args, outputs);
|
|
83
|
+
c.add(`BASE-AGENT-005.narrowing.${step.tool}.target`, narrowingTargets(declared).every(target => isDeepStrictEqual(witnessArgs[target], args[target])), `${step.tool} must witness every identifier of the same targeted subject.`);
|
|
84
|
+
const after = await grantSet(c, narrowing.witness, outputs);
|
|
85
|
+
c.add(`BASE-AGENT-005.narrowing.${step.tool}.subset`, after.length < grantsBefore.length && after.every(grant => grantsBefore.includes(grant)), `${step.tool} must strictly reduce the targeted subject's native grant set.`);
|
|
86
|
+
const beforeInjection = await c.witness();
|
|
87
|
+
const smuggled = await c.stepTool(step, { ...args, idempotency_key: randomUUID(), grant_to_add: 'admin' });
|
|
88
|
+
c.add(`BASE-AGENT-005.narrowing.${step.tool}.undeclared`, errorCode(smuggled) === 'invalid_arguments' && isDeepStrictEqual(beforeInjection, await c.witness()), `${step.tool} must refuse an undeclared widening argument without an effect.`);
|
|
89
|
+
}
|
|
90
|
+
if (!c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
|
|
91
|
+
const snapshot = await c.tool(`${c.surface.seed}.events.list`, { limit: 200 }, { client: step.client });
|
|
92
|
+
if (!Array.isArray(snapshot.result?.structuredContent?.events)) throw new Error('Post-effect events.list must return events');
|
|
93
|
+
(c.effectEvents ??= []).push(...snapshot.result.structuredContent.events);
|
|
94
|
+
}
|
|
95
|
+
if (injections && step.inject) {
|
|
96
|
+
const injected = await injectionArgs(c, step, outputs);
|
|
97
|
+
const checked = await c.stepTool(step, injected, proof);
|
|
98
|
+
c.add(`BASE-AGENT-005.5.${phase}.${step.id}`, isDeepStrictEqual(checked.decision?.classes, answer.decision?.classes) && checked.decision?.disposition === answer.decision?.disposition && !checked.result?.isError, `${step.tool} changed class, facts or decision for additional arguments.`);
|
|
99
|
+
}
|
|
100
|
+
if (replay && !replayed && !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
|
|
101
|
+
replayed = true;
|
|
102
|
+
const beforeReplay = await c.witness(), repeated = await c.stepTool(step, args, proof), afterReplay = await c.witness();
|
|
103
|
+
c.add(`BASE-AGENT-012.1.${phase}`, !repeated.result?.isError && isDeepStrictEqual(answer.result.structuredContent, repeated.result?.structuredContent) && isDeepStrictEqual(beforeReplay, afterReplay), `${step.tool} replay changed native state or returned a different result.`);
|
|
104
|
+
|
|
105
|
+
}
|
|
106
|
+
await nativeStepHook(c, 'afterStep', phase, step, args, outputs, answer.result.structuredContent);
|
|
107
|
+
}
|
|
108
|
+
} finally {
|
|
109
|
+
if (!held) for (const step of c.surface.escalations ?? []) await c.phase(`BASE-AGENT-005.escalation.${step.id}`, async () => {
|
|
110
|
+
const args = c.args(step, outputs), before = await c.witness();
|
|
111
|
+
const answer = await c.stepTool(step, args), after = await c.witness();
|
|
112
|
+
c.add(`BASE-AGENT-005.1.${step.id}`, errorCode(answer) === 'self_escalation', `${step.tool} must refuse sponsor escalation with self_escalation (${errorCode(answer) ?? answer.status}).`);
|
|
113
|
+
c.add(`BASE-AGENT-005.2.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state while attempting sponsor escalation.`);
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
return outputs;
|
|
117
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/** A closed target-only schema cannot encode a grant to add. Unknown schema
|
|
2
|
+
* constructs fail closed, rather than hiding widening fields in a union/ref. */
|
|
3
|
+
export function narrowingTargets(tool) {
|
|
4
|
+
const target = tool?.narrowing?.target, targets = typeof target === 'string' ? [target] : target;
|
|
5
|
+
return Array.isArray(targets) && targets.length > 0 && new Set(targets).size === targets.length
|
|
6
|
+
&& targets.every(key => typeof key === 'string' && /^(?:id|[a-z][a-z0-9_]*_id)$/.test(key)) ? targets : [];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function narrowingContract(tool) {
|
|
10
|
+
const schema = tool?.inputSchema, targets = narrowingTargets(tool);
|
|
11
|
+
if (tool?.widens !== false || !['revoke', 'narrow'].includes(tool.narrowing?.effect) || !targets.length
|
|
12
|
+
|| !schema || schema.type !== 'object' || schema.additionalProperties !== false
|
|
13
|
+
|| Object.keys(schema).some(key => !['type', 'properties', 'required', 'additionalProperties'].includes(key))
|
|
14
|
+
|| !Array.isArray(schema.required) || schema.required.length !== targets.length || new Set(schema.required).size !== targets.length || !targets.every(key => schema.required.includes(key))
|
|
15
|
+
|| !schema.properties || Object.keys(schema.properties).length !== targets.length) return false;
|
|
16
|
+
return targets.every(target => {
|
|
17
|
+
const field = schema.properties[target];
|
|
18
|
+
return field?.type === 'string' && Object.keys(field).every(key => ['type', 'minLength', 'maxLength', 'pattern', 'enum', 'description', 'title'].includes(key));
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export async function grantSet(c, witness, outputs) {
|
|
23
|
+
const answer = await c.tool(witness.tool, c.resolve(witness.args, outputs));
|
|
24
|
+
if (answer.result?.isError) throw new Error('Native grant witness refused');
|
|
25
|
+
let value = answer.result?.structuredContent;
|
|
26
|
+
for (const part of witness.pointer.split('/').slice(1)) value = value?.[part.replace(/~1/g, '/').replace(/~0/g, '~')];
|
|
27
|
+
if (!Array.isArray(value) || value.some(grant => typeof grant !== 'string') || new Set(value).size !== value.length) throw new Error('Native grant witness must return a unique string grant set');
|
|
28
|
+
return value;
|
|
29
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { webcrypto } from 'node:crypto';
|
|
3
|
+
import { accessToken, autonomousPolicy, policyEnvelope, seconds, signJws } from './crypto.mjs';
|
|
4
|
+
import { errorCode, VERSION } from './protocol.mjs';
|
|
5
|
+
|
|
6
|
+
export async function negativePhase(c) {
|
|
7
|
+
await c.adopt(autonomousPolicy());
|
|
8
|
+
await c.prepare('negative');
|
|
9
|
+
const before = await c.witness(), iat = seconds(c.now);
|
|
10
|
+
const unavailable = await c.mcp('resources/read', { uri: `unregistered://${crypto.randomUUID()}` });
|
|
11
|
+
c.add('BASE-AGENT-003.refusal-code', unavailable.message?.error?.data?.code === 'tool_not_found' && unavailable.result === undefined, 'An unregistered resource must refuse with JSON-RPC error.data.code and no content.');
|
|
12
|
+
const noToken = await c.mcp('tools/list', {}, { token: null });
|
|
13
|
+
c.add('BASE-AGENT-004.1.challenge', noToken.status === 401 && /resource_metadata=/.test(noToken.headers.get('www-authenticate') ?? ''), 'An unauthenticated call must return 401 and a resource_metadata challenge.');
|
|
14
|
+
for (const [name, overrides] of [
|
|
15
|
+
['audience', { aud: 'https://sibling.invalid/mcp' }],
|
|
16
|
+
['expired', { iat: iat - 600, exp: iat - 1 }],
|
|
17
|
+
['lifetime', { iat, exp: iat + 901 }],
|
|
18
|
+
]) {
|
|
19
|
+
const answer = await c.mcp('tools/list', {}, { token: await accessToken(c, overrides) });
|
|
20
|
+
c.add(`BASE-AGENT-004.${name === 'audience' ? '2' : '3'}.${name}`, answer.status === 401, `${name} token returned HTTP ${answer.status}, expected 401.`);
|
|
21
|
+
}
|
|
22
|
+
const write = c.surface.journey.find(step => !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly);
|
|
23
|
+
if (write) {
|
|
24
|
+
const answer = await c.tool(write.tool, c.args(write, new Map(), { unresolved: true }), { token: await accessToken(c, { scope: 'events:read' }) });
|
|
25
|
+
const needed = c.surface.tools.find(tool => tool.name === write.tool).scope;
|
|
26
|
+
c.add('BASE-AGENT-004.4', answer.status === 403 && errorCode(answer) === 'insufficient_scope' && (answer.headers.get('www-authenticate') ?? '').includes(needed), 'A token missing the write scope must be refused with all needed scopes in its challenge.');
|
|
27
|
+
}
|
|
28
|
+
const queryToken = await accessToken(c);
|
|
29
|
+
const query = await c.request(`/mcp?access_token=${encodeURIComponent(queryToken)}`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'MCP-Protocol-Version': VERSION, 'Mcp-Method': 'tools/list' }, body: JSON.stringify({ jsonrpc: '2.0', id: 9876, method: 'tools/list', params: {} }) });
|
|
30
|
+
c.add('BASE-AGENT-004.5', query.status === 401, `A query-string token returned HTTP ${query.status}.`);
|
|
31
|
+
await query.body?.cancel();
|
|
32
|
+
const agentOnPersonDoor = await c.request('/agents/api/pause', { method: 'POST', headers: { Origin: c.origin, Authorization: `Bearer ${await accessToken(c)}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ paused: false }) });
|
|
33
|
+
c.add('BASE-AGENT-008.2.person-door', agentOnPersonDoor.status === 403, `An agent token at a person's pause control returned HTTP ${agentOnPersonDoor.status}.`);
|
|
34
|
+
await agentOnPersonDoor.body?.cancel();
|
|
35
|
+
const state = await c.personJson('/agents/api/state');
|
|
36
|
+
const signed = await policyEnvelope(c, autonomousPolicy());
|
|
37
|
+
const foreignKeys = await webcrypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']);
|
|
38
|
+
const badSignature = await signJws(foreignKeys.privateKey, c.signer.kid, 'rer-agent-policy+jwt', signed.payload);
|
|
39
|
+
const invalid = await c.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: badSignature }) });
|
|
40
|
+
c.add('BASE-AGENT-007.8.signature', !invalid.ok, 'A policy envelope signed by an untrusted key was accepted.');
|
|
41
|
+
await invalid.body?.cancel();
|
|
42
|
+
const foreignBusiness = await policyEnvelope(c, autonomousPolicy(), { business: 'conformance-foreign-business' });
|
|
43
|
+
const foreign = await c.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: foreignBusiness.policy }) });
|
|
44
|
+
c.add('BASE-AGENT-007.8.business', !foreign.ok, 'An envelope whose Business does not match its revision signature was accepted.');
|
|
45
|
+
await foreign.body?.cancel();
|
|
46
|
+
c.add('BASE-AGENT-007.8.state', isDeepStrictEqual(state, await c.personJson('/agents/api/state')), 'An invalid envelope changed the adopted policy state or revision.');
|
|
47
|
+
c.add('BASE-AGENT-004.negative-no-effect', isDeepStrictEqual(before, await c.witness()), 'An authentication/person-door/policy-envelope negative changed native state.');
|
|
48
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
2
|
+
import { dirname, extname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
3
|
+
import { parse } from '../../../edition-authoring/vendor/babel-parser/babel-parser/index.mjs';
|
|
4
|
+
|
|
5
|
+
export class NetworkAdapterError extends Error {}
|
|
6
|
+
const invalid = message => new NetworkAdapterError(`Agent conformance network: ${message}`);
|
|
7
|
+
const contained = (root, path) => {
|
|
8
|
+
const name = relative(root, path);
|
|
9
|
+
return name !== '' && name !== '..' && !name.startsWith(`..${sep}`) && !isAbsolute(name);
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export function validateNetworkAdapter(config) {
|
|
13
|
+
if (!config || typeof config !== 'object' || Array.isArray(config) ||
|
|
14
|
+
Object.keys(config).some(key => !['module', 'origins'].includes(key)) ||
|
|
15
|
+
typeof config.module !== 'string' || !config.module || isAbsolute(config.module) || config.module.includes('\\') ||
|
|
16
|
+
!Array.isArray(config.origins) || !config.origins.length) {
|
|
17
|
+
throw invalid('verification.network must declare a seed-relative module and a nonempty origins array.');
|
|
18
|
+
}
|
|
19
|
+
const origins = new Set();
|
|
20
|
+
for (const origin of config.origins) {
|
|
21
|
+
let url;
|
|
22
|
+
try { url = new URL(origin); } catch { /* Report only the declaration field, never a credential-bearing URL. */ }
|
|
23
|
+
if (typeof origin !== 'string' || !url || !['http:', 'https:'].includes(url.protocol) || url.origin !== origin || url.username || url.password) {
|
|
24
|
+
throw invalid('verification.network.origins must contain exact HTTP(S) origins without credentials, paths, queries or fragments.');
|
|
25
|
+
}
|
|
26
|
+
if (origins.has(origin)) throw invalid('verification.network.origins must not repeat an origin.');
|
|
27
|
+
origins.add(origin);
|
|
28
|
+
}
|
|
29
|
+
return { module: config.module, origins };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function imports(source, builtins) {
|
|
33
|
+
let ast;
|
|
34
|
+
try { ast = parse(source, { sourceType: 'module', createImportExpressions: true }); }
|
|
35
|
+
catch { throw invalid('the adapter or a relative helper is not valid ES module JavaScript.'); }
|
|
36
|
+
const pending = [ast], result = [];
|
|
37
|
+
while (pending.length) {
|
|
38
|
+
const node = pending.pop();
|
|
39
|
+
let specifier;
|
|
40
|
+
if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration', 'ImportExpression'].includes(node.type) && node.source) {
|
|
41
|
+
if (node.source.type !== 'StringLiteral') throw invalid('adapter imports must use literal relative module paths.');
|
|
42
|
+
specifier = node.source.value;
|
|
43
|
+
}
|
|
44
|
+
if (specifier !== undefined && !builtins.includes(specifier)) {
|
|
45
|
+
if (!(specifier.startsWith('./') || specifier.startsWith('../')) || specifier.includes('\\') || specifier.includes('?') || specifier.includes('#')) {
|
|
46
|
+
throw invalid('adapter imports must be relative JavaScript modules; packages, Node APIs and runtime built-ins are unavailable.');
|
|
47
|
+
}
|
|
48
|
+
result.push(specifier);
|
|
49
|
+
}
|
|
50
|
+
for (const value of Object.values(node)) {
|
|
51
|
+
if (Array.isArray(value)) pending.push(...value.filter(item => item && typeof item.type === 'string'));
|
|
52
|
+
else if (value && typeof value.type === 'string') pending.push(value);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return result;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Supply only snapshotted, checked module bytes to workerd. It has no filesystem
|
|
59
|
+
// loader, so an unresolved or computed import cannot read another host file.
|
|
60
|
+
export async function networkAdapterModules(root, entry, { builtins = [] } = {}) {
|
|
61
|
+
let directory;
|
|
62
|
+
try { directory = await realpath(root); }
|
|
63
|
+
catch { throw invalid('the seed root is unreadable.'); }
|
|
64
|
+
const pending = [resolve(directory, entry)], seen = new Set(), modules = [];
|
|
65
|
+
while (pending.length) {
|
|
66
|
+
const path = pending.shift();
|
|
67
|
+
if (seen.has(path)) continue;
|
|
68
|
+
if (!contained(directory, path) || !['.mjs', '.js'].includes(extname(path))) {
|
|
69
|
+
throw invalid('the adapter and every helper must be .mjs or .js files contained in the seed root.');
|
|
70
|
+
}
|
|
71
|
+
let canonical, contents;
|
|
72
|
+
try {
|
|
73
|
+
canonical = await realpath(path);
|
|
74
|
+
if (!contained(directory, canonical)) throw invalid('an adapter module symlink escapes the seed root.');
|
|
75
|
+
if (!(await stat(canonical)).isFile()) throw invalid('an adapter module is not a regular file.');
|
|
76
|
+
contents = await readFile(canonical, 'utf8');
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (error instanceof NetworkAdapterError) throw error;
|
|
79
|
+
throw invalid('the declared adapter or a relative helper cannot be read. Use explicit relative .mjs or .js file paths.');
|
|
80
|
+
}
|
|
81
|
+
seen.add(path);
|
|
82
|
+
modules.push({ type: 'ESModule', path, contents });
|
|
83
|
+
pending.push(...imports(contents, builtins).map(specifier => resolve(dirname(path), specifier)));
|
|
84
|
+
}
|
|
85
|
+
return { root: directory, modules };
|
|
86
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { createRequire } from 'node:module';
|
|
2
|
+
import { join, relative } from 'node:path';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { networkAdapterModules, NetworkAdapterError } from './network-modules.mjs';
|
|
5
|
+
|
|
6
|
+
// The adapter runs in its own disposable workerd instance, with neither app
|
|
7
|
+
// bindings nor Node compatibility. Its own fetch can never reach the network.
|
|
8
|
+
export async function isolatedNetworkAdapter(root, entry, deny) {
|
|
9
|
+
const source = await networkAdapterModules(root, entry);
|
|
10
|
+
let mf;
|
|
11
|
+
try {
|
|
12
|
+
const wrangler = createRequire(join(root, 'package.json')).resolve('wrangler/package.json');
|
|
13
|
+
const { Miniflare, convertV4MiniflareOptions = options => options } = await import(pathToFileURL(createRequire(wrangler).resolve('miniflare')));
|
|
14
|
+
// Host control data is carried on a private request header, overwritten on
|
|
15
|
+
// every dispatch and removed before the seed adapter sees its native request.
|
|
16
|
+
// There is no control URL or app binding. Adapter egress is still denied.
|
|
17
|
+
const header = 'x-rer-conformance-fixture', urlHeader = 'x-rer-conformance-url', entry = join(source.root, '__rer_network_entry__.mjs');
|
|
18
|
+
if (source.modules.some(module => module.path === entry)) throw new Error('Reserved network entry');
|
|
19
|
+
const wrapper = { type: 'ESModule', path: entry, contents: `import adapter from ${JSON.stringify('./' + relative(source.root, source.modules[0].path))};
|
|
20
|
+
export default { async fetch(request, env) {
|
|
21
|
+
const encoded = request.headers.get(${JSON.stringify(header)});
|
|
22
|
+
const fixture = encoded ? JSON.parse(new TextDecoder().decode(Uint8Array.from(atob(encoded), char => char.charCodeAt(0)))) : null;
|
|
23
|
+
const url = new URL(request.headers.get(${JSON.stringify(urlHeader)}));
|
|
24
|
+
const headers = new Headers(request.headers); headers.delete(${JSON.stringify(header)}); headers.delete(${JSON.stringify(urlHeader)}); headers.set('host', url.host);
|
|
25
|
+
return adapter.fetch(new Request(url, { method: request.method, headers, redirect: 'manual', ...(!['GET','HEAD'].includes(request.method) ? { body: request.body } : {}) }), { fixture, secrets: env.secrets });
|
|
26
|
+
} };` };
|
|
27
|
+
const options = { host: '127.0.0.1', port: 0, cf: false, unsafeLocalExplorer: false,
|
|
28
|
+
modules: [wrapper, ...source.modules], modulesRoot: source.root, compatibilityDate: '2026-09-01', compatibilityFlags: [],
|
|
29
|
+
bindings: {}, outboundService: deny,
|
|
30
|
+
};
|
|
31
|
+
mf = new Miniflare(convertV4MiniflareOptions(options));
|
|
32
|
+
let loopback = await mf.ready;
|
|
33
|
+
return { fetch: (request, fixture) => {
|
|
34
|
+
const headers = new Headers(request.headers);
|
|
35
|
+
headers.set(header, Buffer.from(JSON.stringify(fixture ?? null)).toString('base64'));
|
|
36
|
+
headers.set(urlHeader, request.url);
|
|
37
|
+
return fetch(loopback, { method: request.method, headers: Object.fromEntries(headers), body: request.body, duplex: 'half', redirect: 'manual' });
|
|
38
|
+
}, provision: async secrets => {
|
|
39
|
+
await mf.setOptions(convertV4MiniflareOptions({ ...options, bindings: { secrets } }));
|
|
40
|
+
loopback = await mf.ready;
|
|
41
|
+
}, close: () => mf.dispose() };
|
|
42
|
+
} catch {
|
|
43
|
+
if (mf) await mf.dispose();
|
|
44
|
+
throw new NetworkAdapterError('Agent conformance network: the adapter could not start in isolated workerd. Check the seed\'s installed wrangler and use Worker-compatible ES modules with a default fetch export; Node APIs and runtime bindings are unavailable.');
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
2
|
+
import { autonomousPolicy } from './crypto.mjs';
|
|
3
|
+
import { errorCode } from './protocol.mjs';
|
|
4
|
+
import { nativeStepHook } from './step-hooks.mjs';
|
|
5
|
+
|
|
6
|
+
export async function unsetPolicy(c, initial = false) {
|
|
7
|
+
const listed = await c.mcp('tools/list');
|
|
8
|
+
c.add(`BASE-AGENT-007.2.${initial ? 'initial' : 'removed'}.list`, isDeepStrictEqual(listed.result?.tools, []), 'An unanswered door must list no tools.');
|
|
9
|
+
if (initial) {
|
|
10
|
+
const inventory = await c.personJson('/agents/api/agents');
|
|
11
|
+
const sponsor = inventory.agents?.find(agent => agent.id === c.agentId)?.sponsor;
|
|
12
|
+
c.add('BASE-AGENT-004.6.sponsor', typeof sponsor?.id === 'string' && sponsor.id.length > 0, 'The native person agents inventory must identify the authenticated agent sponsor.');
|
|
13
|
+
if (!sponsor?.id) throw new Error('Cannot resolve native sponsor ID from the person agents door');
|
|
14
|
+
c.sponsor.id = sponsor.id;
|
|
15
|
+
await c.prepare('initial');
|
|
16
|
+
}
|
|
17
|
+
for (const step of c.surface.journey) {
|
|
18
|
+
// No prior result exists here; unresolved references cannot identify native
|
|
19
|
+
// records. Resolvable calls still retain their computed classification.
|
|
20
|
+
const answer = await c.stepTool(step, c.args(step, new Map(), { unresolved: true }));
|
|
21
|
+
c.add(`BASE-AGENT-007.2.${initial ? 'initial' : 'removed'}.${step.id}`, errorCode(answer) === 'policy_unset', `${step.tool} must refuse with policy_unset before setup.`);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
export async function removalPhase(c) {
|
|
25
|
+
await c.adopt(autonomousPolicy());
|
|
26
|
+
await c.prepare('removed');
|
|
27
|
+
const before = await c.witness();
|
|
28
|
+
await c.adopt(null);
|
|
29
|
+
await unsetPolicy(c);
|
|
30
|
+
await c.adopt(autonomousPolicy());
|
|
31
|
+
c.add('BASE-AGENT-007.2.unset-no-effect', isDeepStrictEqual(before, await c.witness()), 'Calls under the removed policy changed native state.');
|
|
32
|
+
}
|
|
33
|
+
export async function blockedPhases(c) {
|
|
34
|
+
const nonstandard = [...new Set(c.surface.tools.flatMap(tool => tool.classes))].filter(cls => cls !== 'standard');
|
|
35
|
+
for (const cls of nonstandard) {
|
|
36
|
+
await c.adopt(autonomousPolicy());
|
|
37
|
+
await c.prepare(`blocked:${cls}`);
|
|
38
|
+
const outputs = new Map();
|
|
39
|
+
for (const step of c.surface.journey) {
|
|
40
|
+
const args = c.args(step, outputs);
|
|
41
|
+
await nativeStepHook(c, 'beforeStep', `blocked:${cls}`, step, args, outputs);
|
|
42
|
+
if (step.expect.some(item => item.class === cls)) {
|
|
43
|
+
const policy = autonomousPolicy(); policy.rules.push({ id: `block-${cls}`, class: cls, do: 'blocked' });
|
|
44
|
+
await c.adopt(policy);
|
|
45
|
+
const before = await c.witness(), refused = await c.stepTool(step, args), after = await c.witness();
|
|
46
|
+
c.add(`BASE-AGENT-007.1.blocked.${cls}.${step.id}`, errorCode(refused) === 'policy_blocked' && refused.decision?.disposition === 'blocked' && refused.decision.revision === c.revision && refused.decision.classes.some(item => item.class === cls && item.do === 'blocked'), `${step.tool} must be blocked by ${cls}.`);
|
|
47
|
+
c.add(`BASE-AGENT-007.1.blocked-no-effect.${cls}.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state while ${cls} was blocked.`);
|
|
48
|
+
await c.adopt(autonomousPolicy());
|
|
49
|
+
}
|
|
50
|
+
const completed = await c.stepTool(step, args, await c.proof(step.tool, args, undefined, step.client));
|
|
51
|
+
if (completed.result?.isError || completed.result?.structuredContent === undefined) throw new Error(`Could not prepare ${step.id} for the ${cls} blocked variant (${errorCode(completed) ?? completed.status})`);
|
|
52
|
+
outputs.set(step.id, completed.result.structuredContent);
|
|
53
|
+
await nativeStepHook(c, 'afterStep', `blocked:${cls}`, step, args, outputs, completed.result.structuredContent);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
export async function pausePhase(c) {
|
|
58
|
+
await c.adopt(autonomousPolicy());
|
|
59
|
+
await c.prepare('paused');
|
|
60
|
+
const before = await c.witness();
|
|
61
|
+
await c.adopt(autonomousPolicy(), { paused: true });
|
|
62
|
+
for (const tool of c.surface.tools) {
|
|
63
|
+
const step = c.surface.journey.find(item => item.tool === tool.name);
|
|
64
|
+
const paused = await c.stepTool(step, c.args(step, new Map(), { unresolved: true }));
|
|
65
|
+
c.add(`BASE-AGENT-011.6.pause.${tool.name}`, errorCode(paused) === 'agents_paused', `${tool.name} ran while Business Pause was set.`);
|
|
66
|
+
}
|
|
67
|
+
const state = await c.personJson('/agents/api/state');
|
|
68
|
+
c.add('BASE-AGENT-011.6.person', state.paused?.business === true, 'The signed-in person must still read paused state.');
|
|
69
|
+
await c.adopt(autonomousPolicy());
|
|
70
|
+
c.add('BASE-AGENT-011.6.resume', isDeepStrictEqual(before, await c.witness()), 'Pause calls changed native state, or resume did not restore access.');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export async function consentRevocationPhase(c) {
|
|
74
|
+
await c.adopt(autonomousPolicy());
|
|
75
|
+
await c.prepare('consent');
|
|
76
|
+
const before = await c.witness();
|
|
77
|
+
await c.adopt(autonomousPolicy(), { revoked: { agents: [], consents: [c.consent] } });
|
|
78
|
+
const step = c.surface.journey[0];
|
|
79
|
+
const refused = await c.tool(step.tool, c.args(step, new Map(), { unresolved: true }));
|
|
80
|
+
c.add('BASE-AGENT-004.consent-revoked', refused.status === 401, 'A revoked originating consent must refuse the next authenticated call.');
|
|
81
|
+
await c.adopt(autonomousPolicy());
|
|
82
|
+
c.add('BASE-AGENT-004.consent-no-effect', isDeepStrictEqual(before, await c.witness()), 'A call under revoked consent changed native state.');
|
|
83
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { accessToken, policyEnvelope } from './crypto.mjs';
|
|
4
|
+
import { AGENT_CLASSES } from './surface.mjs';
|
|
5
|
+
import { phaseFixtures } from './fixtures.mjs';
|
|
6
|
+
|
|
7
|
+
export const VERSION = '2026-07-28';
|
|
8
|
+
export const DECISION = 'com.runeditrun/decision';
|
|
9
|
+
export const ERROR = 'com.runeditrun/error';
|
|
10
|
+
export const APPROVAL = 'com.runeditrun/approval';
|
|
11
|
+
export const subset = (actual, expected) => expected && typeof expected === 'object'
|
|
12
|
+
? actual !== null && typeof actual === 'object' && Object.entries(expected).every(([key, value]) => subset(actual[key], value))
|
|
13
|
+
: isDeepStrictEqual(actual, expected);
|
|
14
|
+
export const classIds = items => (items ?? []).map(item => typeof item === 'string' ? item : item.class).sort();
|
|
15
|
+
export function errorCode(answer) {
|
|
16
|
+
const error = answer.result?._meta?.[ERROR] ?? answer.message?.error?.data?._meta?.[ERROR] ?? answer.message?.error?.data ?? answer.message?.error;
|
|
17
|
+
return typeof error === 'string' ? error : error?.code ?? answer.body?.code ?? null;
|
|
18
|
+
}
|
|
19
|
+
export function resolveArgs(value, outputs, { unresolved = false, sponsor, fixtures = {} } = {}) {
|
|
20
|
+
if (Array.isArray(value)) return value.map(item => resolveArgs(item, outputs, { unresolved, sponsor, fixtures }));
|
|
21
|
+
if (value && typeof value === 'object') {
|
|
22
|
+
if ('$sponsor' in value) {
|
|
23
|
+
const result = sponsor?.[value.$sponsor];
|
|
24
|
+
if (!['id', 'email'].includes(value.$sponsor) || typeof result !== 'string' || !result) throw new Error(`Sponsor reference ${value.$sponsor} is unavailable`);
|
|
25
|
+
return result;
|
|
26
|
+
}
|
|
27
|
+
if ('$from' in value || '$fixture' in value) {
|
|
28
|
+
const key = value.$fixture ?? value.$from, values = '$fixture' in value ? new Map(Object.entries(fixtures)) : outputs;
|
|
29
|
+
if (!values.has(key)) {
|
|
30
|
+
if ('$fixture' in value && unresolved) return `unresolved-fixture-${key}`;
|
|
31
|
+
if ('$fixture' in value) throw new Error('A required native phase fixture is unavailable');
|
|
32
|
+
if (unresolved) return `unresolved-${value.$from}`;
|
|
33
|
+
throw new Error(`Reference ${value.$from} has no structuredContent in this phase`);
|
|
34
|
+
}
|
|
35
|
+
let result = values.get(key);
|
|
36
|
+
for (const part of value.pointer.split('/').slice(1)) result = result?.[part.replace(/~1/g, '/').replace(/~0/g, '~')];
|
|
37
|
+
if (result === undefined) throw new Error('A journey reference is missing');
|
|
38
|
+
return structuredClone(result);
|
|
39
|
+
}
|
|
40
|
+
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, resolveArgs(item, outputs, { unresolved, sponsor, fixtures })]));
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
async function responseBody(response) {
|
|
45
|
+
const raw = await response.text();
|
|
46
|
+
if (response.headers.get('content-type')?.includes('text/event-stream')) {
|
|
47
|
+
const messages = raw.split(/\r?\n\r?\n/).map(block => block.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n')).filter(Boolean).map(value => JSON.parse(value));
|
|
48
|
+
return messages.findLast(item => item.id !== undefined) ?? messages.at(-1) ?? {};
|
|
49
|
+
}
|
|
50
|
+
try { return JSON.parse(raw); } catch { return { nonJson: true }; }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function createProtocol(context) {
|
|
54
|
+
let requestId = 0;
|
|
55
|
+
context.calls = [];
|
|
56
|
+
context.sponsor = { email: context.person.email.toLowerCase() };
|
|
57
|
+
context.add = (id, ok, detail) => context.points.push({ id, ok: Boolean(ok), ...(!ok ? { detail: String(detail ?? 'Contract assertion failed') } : {}) });
|
|
58
|
+
context.phase = async (name, fn) => {
|
|
59
|
+
try { await fn(); } catch (error) { context.add(name, false, error.message); }
|
|
60
|
+
};
|
|
61
|
+
context.request = async (path, init = {}) => {
|
|
62
|
+
// A 429 is a capacity refusal, not an action result. Honor only a bounded,
|
|
63
|
+
// explicit Retry-After; never replay an application or policy refusal.
|
|
64
|
+
for (let attempt = 0; ; attempt++) {
|
|
65
|
+
const response = await context.fetch(new URL(path, `${context.origin}/`).href, { redirect: 'manual', ...init });
|
|
66
|
+
if (response.status !== 429) return response;
|
|
67
|
+
const header = response.headers.get('retry-after'), delay = header && /^\d+(?:\.\d+)?$/.test(header) ? Number(header) * 1000 : header ? Date.parse(header) - Date.now() : NaN;
|
|
68
|
+
await response.body?.cancel();
|
|
69
|
+
if (attempt >= 2 || !Number.isFinite(delay) || delay < 0 || delay > 60_000) throw new Error('429 capacity refusal without a bounded Retry-After (maximum 60 seconds, two retries)');
|
|
70
|
+
await new Promise(resolve => setTimeout(resolve, delay));
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
context.personRequest = async (path, { headers, ...init } = {}) => context.request(path, { ...init, headers: { Origin: context.origin, Cookie: context.person.cookie, 'Content-Type': 'application/json', ...headers } });
|
|
74
|
+
context.personJson = async path => { const response = await context.personRequest(path); if (!response.ok) throw new Error(`${path}: HTTP ${response.status}`); return responseBody(response); };
|
|
75
|
+
context.decideApproval = async (pending, action = 'approve') => {
|
|
76
|
+
if (!['approve', 'reject'].includes(action)) throw new Error('Approval decision must be approve or reject');
|
|
77
|
+
const handle = pending.result?._meta?.[APPROVAL], path = `/agents/api/approvals/${encodeURIComponent(handle.id)}`;
|
|
78
|
+
const { approval } = await context.personJson(path);
|
|
79
|
+
const valid = approval?.id === handle.id && approval.decision_id === pending.decision?.id && approval.revision === pending.decision?.revision && /^[a-f0-9]{64}$/.test(approval.summary_sha256);
|
|
80
|
+
context.add(`BASE-AGENT-008.5.summary.${handle.id}`, valid, 'The person approval must expose its exact decision, revision and summary SHA-256.');
|
|
81
|
+
if (!valid) throw new Error('Cannot decide an approval without its exact summary evidence');
|
|
82
|
+
const response = await context.personRequest(`${path}/${action}`, { method: 'POST', body: JSON.stringify({ revision: approval.revision, summary_sha256: approval.summary_sha256 }) });
|
|
83
|
+
const body = await responseBody(response);
|
|
84
|
+
if (response.ok && action === 'approve' && body.approval?.state === 'executed') context.calls.push({
|
|
85
|
+
kind: 'approval/execute', name: approval.tool, decision: structuredClone(pending.decision), approvalId: handle.id, principal: pending.principal,
|
|
86
|
+
});
|
|
87
|
+
return { ok: response.ok, status: response.status, body };
|
|
88
|
+
};
|
|
89
|
+
context.mcp = async (method, params = {}, options = {}) => {
|
|
90
|
+
const client = options.client === undefined ? undefined : context.clients.get(options.client);
|
|
91
|
+
if (options.client !== undefined && !client) throw new Error('A required native client fixture is unavailable');
|
|
92
|
+
const { token = client?.token ?? await accessToken(context), version = VERSION, headers = {}, track = true } = options;
|
|
93
|
+
const principal = client && options.token === undefined ? { agent: client.agent, clientId: client.clientId, consent: null, sponsor: context.sponsor.id } : undefined;
|
|
94
|
+
const id = ++requestId, name = method === 'resources/read' ? params.uri : params.name;
|
|
95
|
+
const response = await context.request('/mcp', { method: 'POST', headers: {
|
|
96
|
+
Accept: 'application/json, text/event-stream', 'Content-Type': 'application/json', Origin: context.origin,
|
|
97
|
+
'MCP-Protocol-Version': version, 'Mcp-Method': method,
|
|
98
|
+
...(['tools/call', 'resources/read', 'prompts/get'].includes(method) && name ? { 'Mcp-Name': name } : {}),
|
|
99
|
+
...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers,
|
|
100
|
+
}, body: JSON.stringify({ jsonrpc: '2.0', id, method, params: version === '2025-11-25' ? params : { ...params, _meta: { 'io.modelcontextprotocol/protocolVersion': version, 'io.modelcontextprotocol/clientCapabilities': { elicitation: { url: {} } }, 'io.modelcontextprotocol/clientInfo': { name: 'rer-agent-conformance', version: '1' }, ...params._meta } } }) });
|
|
101
|
+
const body = await responseBody(response), result = body.result, decision = result?._meta?.[DECISION] ?? body.error?.data?._meta?.[DECISION];
|
|
102
|
+
const answer = { status: response.status, headers: response.headers, body, message: body, result, decision, principal };
|
|
103
|
+
if (['tools/call', 'resources/read'].includes(method) && track && (response.status !== 401 || typeof body.error?.data?.code === 'string')) context.calls.push({
|
|
104
|
+
kind: method, name: method === 'resources/read' ? 'resources/read' : params.name,
|
|
105
|
+
args: structuredClone(method === 'resources/read' ? { uri: params.uri } : params.arguments ?? {}),
|
|
106
|
+
decision: structuredClone(decision ?? null), code: errorCode(answer), result: structuredClone(result), principal,
|
|
107
|
+
approval: structuredClone(result?._meta?.[APPROVAL] ?? body.error?.data?.approval ?? null),
|
|
108
|
+
pending: result?.resultType === 'input_required' || method === 'resources/read' && errorCode(answer) === 'approval_required',
|
|
109
|
+
});
|
|
110
|
+
return answer;
|
|
111
|
+
};
|
|
112
|
+
context.proof = async (name, args, handoff, clientLabel) => {
|
|
113
|
+
const tool = context.surface.tools.find(tool => tool.name === name);
|
|
114
|
+
if (!tool?.proof) return {};
|
|
115
|
+
if (typeof context.prove !== 'function') throw new Error(`${name} requires the seed-declared verification.proof module`);
|
|
116
|
+
const reference = await context.prove({ tool: name, args, kind: tool.proofKind, handoff, origin: context.origin, agentId: clientLabel === undefined ? context.agentId : context.clients.get(clientLabel)?.agent.id, request: (path, init) => {
|
|
117
|
+
const url = new URL(path, context.origin);
|
|
118
|
+
if (url.origin !== context.origin) throw new Error('Native proof test request must use the fresh installation origin');
|
|
119
|
+
return context.personRequest(url.href, init);
|
|
120
|
+
} });
|
|
121
|
+
if (typeof reference !== 'string' || !reference) throw new Error('Native proof test hook must return a reference');
|
|
122
|
+
return { proofReference: reference };
|
|
123
|
+
};
|
|
124
|
+
context.tool = (name, args, options) => context.mcp('tools/call', { name, arguments: args, ...(options?.proofReference ? { _meta: { 'com.runeditrun/native-proof': options.proofReference } } : {}), ...(options?.requestState === undefined ? {} : { requestState: options.requestState }) }, options);
|
|
125
|
+
context.resolve = (value, outputs = new Map(), options = {}) => resolveArgs(value, outputs, { ...options, sponsor: context.sponsor, fixtures: context.fixtureValues });
|
|
126
|
+
context.args = (step, outputs, options) => {
|
|
127
|
+
const args = context.resolve(step.args, outputs, options);
|
|
128
|
+
if (!context.surface.tools.find(tool => tool.name === step.tool)?.readOnly) args.idempotency_key = randomUUID();
|
|
129
|
+
return args;
|
|
130
|
+
};
|
|
131
|
+
context.witness = async () => {
|
|
132
|
+
const answer = await context.tool(context.surface.witness.tool, context.resolve(context.surface.witness.args));
|
|
133
|
+
if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error(`Witness ${context.surface.witness.tool} failed (${errorCode(answer) ?? answer.status})`);
|
|
134
|
+
return answer.result.structuredContent;
|
|
135
|
+
};
|
|
136
|
+
context.adopt = async (document, options = {}) => {
|
|
137
|
+
const signed = await policyEnvelope(context, document, options);
|
|
138
|
+
const response = await context.request('/api/rer/agent-policy', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ policy: signed.policy }) });
|
|
139
|
+
const body = await responseBody(response);
|
|
140
|
+
if (!response.ok) throw new Error(`Policy adoption failed: HTTP ${response.status} (${typeof body.code === 'string' ? body.code : 'invalid response'})`);
|
|
141
|
+
context.seq = signed.payload.seq; context.revision = signed.payload.revision; context.document = document;
|
|
142
|
+
const expectedClasses = [...new Set(context.surface.tools.flatMap(tool => tool.classes))];
|
|
143
|
+
const actualClasses = body.door?.classes;
|
|
144
|
+
const validClasses = Array.isArray(actualClasses) && new Set(actualClasses.map(row => row?.class)).size === actualClasses.length && actualClasses.every(row =>
|
|
145
|
+
row && Object.keys(row).sort().join(',') === 'class,tools' && AGENT_CLASSES.includes(row.class) && Array.isArray(row.tools) &&
|
|
146
|
+
isDeepStrictEqual([...row.tools].sort(), context.surface.tools.filter(tool => tool.classes.includes(row.class)).map(tool => tool.name).sort().slice(0, 20))) &&
|
|
147
|
+
expectedClasses.every(cls => actualClasses.some(row => row.class === cls));
|
|
148
|
+
context.add(`BASE-AGENT-007.7.adopt.${context.seq}`, Object.keys(body).sort().join(',') === 'adopted,door' && isDeepStrictEqual(body.adopted, { seq: context.seq, revision: context.revision }) && validClasses, 'Policy answer must contain exactly adopted {seq,revision} and catalogue classes with the exact declared tool mappings; resource-only classes have no tools.');
|
|
149
|
+
return signed;
|
|
150
|
+
};
|
|
151
|
+
phaseFixtures(context, context.prepare);
|
|
152
|
+
return context;
|
|
153
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { auditRows } from './audit.mjs';
|
|
2
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
3
|
+
import { accessToken, autonomousPolicy } from './crypto.mjs';
|
|
4
|
+
import { errorCode } from './protocol.mjs';
|
|
5
|
+
|
|
6
|
+
export async function replayAdmissionPhase(c, declaration) {
|
|
7
|
+
if (!Array.isArray(declaration.prepare) || !declaration.prepare.length) throw new Error('replayAdmission.prepare must name preparation journey steps ending in a write.');
|
|
8
|
+
await c.adopt(autonomousPolicy());
|
|
9
|
+
await c.prepare('replay');
|
|
10
|
+
const outputs = new Map(); let call;
|
|
11
|
+
for (const id of declaration.prepare) {
|
|
12
|
+
const step = c.surface.journey.find(step => step.id === id);
|
|
13
|
+
if (!step) throw new Error('Unknown replay preparation step.');
|
|
14
|
+
const args = c.args(step, outputs), answer = await c.stepTool(step, args);
|
|
15
|
+
if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error('Could not prepare a successful idempotent call.');
|
|
16
|
+
outputs.set(id, answer.result.structuredContent); call = { step, args, answer };
|
|
17
|
+
}
|
|
18
|
+
if (!call.args.idempotency_key) throw new Error('Replay admission must finish preparation with a mutating tool.');
|
|
19
|
+
const before = await c.witness(), repeated = await c.stepTool(call.step, call.args);
|
|
20
|
+
c.add('BASE-AGENT-012.replay.current', !repeated.result?.isError && isDeepStrictEqual(repeated.result?.structuredContent, call.answer.result.structuredContent) && isDeepStrictEqual(before, await c.witness()), 'An admitted replay must return the saved result without another native effect.');
|
|
21
|
+
await c.adopt(autonomousPolicy(), { paused: true });
|
|
22
|
+
const paused = await c.stepTool(call.step, call.args);
|
|
23
|
+
c.add('BASE-AGENT-012.replay.paused', errorCode(paused) === 'agents_paused' && paused.result?.structuredContent === undefined, 'A previously successful key must not expose cached content while agents are paused.');
|
|
24
|
+
const rows = await auditRows(c);
|
|
25
|
+
const row = rows.rows?.findLast(row => row.idempotency_key === call.args.idempotency_key);
|
|
26
|
+
c.add('BASE-AGENT-012.replay.audit', row?.code === 'agents_paused' && row.outcome === 'refused' && row.agent?.id === (call.answer.principal?.agent.id ?? c.agentId) && row.sponsor?.id === c.sponsor.id && row.tool === call.step.tool && row.decision === 'paused' && row.revision === c.revision && Number.isFinite(Date.parse(row.at)), 'The refused replay needs its own complete audit with current attribution and policy revision.');
|
|
27
|
+
const blocked = autonomousPolicy(); blocked.rules = [{ id: 'all', class: '*', do: 'blocked' }];
|
|
28
|
+
await c.adopt(blocked);
|
|
29
|
+
const refused = await c.stepTool(call.step, call.args);
|
|
30
|
+
c.add('BASE-AGENT-012.replay.policy', errorCode(refused) === 'policy_blocked' && refused.result?.structuredContent === undefined, 'Current per-tool policy must run before replay lookup.');
|
|
31
|
+
const held = autonomousPolicy(); held.rules = [{ id: 'all', class: '*', do: 'approval', approver: ['sponsor'], wait: 'PT1H' }];
|
|
32
|
+
await c.adopt(held);
|
|
33
|
+
const approval = await c.stepTool(call.step, call.args);
|
|
34
|
+
c.add('BASE-AGENT-012.replay.approval', errorCode(approval) === 'approval_required' && approval.result?.structuredContent === undefined, 'A newly required approval cannot be satisfied by an older autonomous result.');
|
|
35
|
+
await c.adopt(autonomousPolicy());
|
|
36
|
+
const missing = await c.tool(call.step.tool, call.args, { token: await accessToken(c, { scope: 'events:read' }) });
|
|
37
|
+
c.add('BASE-AGENT-012.replay.scope', missing.status === 403 && errorCode(missing) === 'insufficient_scope' && missing.result?.structuredContent === undefined, 'Current write scope is required even when the key has a successful outcome.');
|
|
38
|
+
c.add('BASE-AGENT-012.replay.once', isDeepStrictEqual(before, await c.witness()), 'Authority changes and refused replays executed the effect again.');
|
|
39
|
+
}
|