@runeditrun/rer 0.2.86 → 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/cli/agent-bindings.mjs +25 -0
- package/cli/agent-door.mjs +9 -13
- package/cli/agent-journey-fixtures.mjs +17 -0
- package/cli/agent-reviewers.mjs +1 -1
- package/cli/agent-rpc.mjs +23 -0
- package/cli/agent-sponsors.mjs +2 -2
- package/cli/agent-verifier.mjs +31 -0
- package/cli/deploy-variables.mjs +48 -17
- package/cli/export.mjs +1 -0
- package/cli/hosted-output.mjs +15 -2
- package/cli/managed-data.mjs +8 -4
- package/cli/portability-worker.mjs +2 -1
- package/cli/portability.mjs +1 -0
- package/cli/production-auth.mjs +1 -1
- package/cli/production-mail.mjs +11 -1
- package/cli/server-registry.mjs +2 -0
- package/edition-authoring/archive-source.mjs +7 -1
- package/edition-authoring/base-copies.mjs +17 -4
- package/edition-authoring/copy-namespaces.mjs +28 -0
- package/edition-authoring/files.mjs +2 -1
- package/edition-authoring/module-closure.mjs +56 -11
- package/edition-authoring/module-edges.mjs +13 -2
- package/foundation/runtime/contract-docs.mjs +5 -0
- package/global/CHANGELOG.md +58 -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 +10 -13
- package/modules/agent-door/conformance/fixtures.mjs +41 -0
- package/modules/agent-door/conformance/index.mjs +4 -4
- package/modules/agent-door/conformance/injection.mjs +24 -0
- package/modules/agent-door/conformance/invocation.mjs +1 -0
- package/modules/agent-door/conformance/journey.mjs +19 -14
- package/modules/agent-door/conformance/narrowing.d.mts +1 -0
- package/modules/agent-door/conformance/narrowing.mjs +15 -7
- package/modules/agent-door/conformance/negative.mjs +1 -0
- package/modules/agent-door/conformance/network-modules.mjs +4 -4
- package/modules/agent-door/conformance/policy-phases.mjs +12 -4
- package/modules/agent-door/conformance/protocol.mjs +22 -14
- package/modules/agent-door/conformance/replay.mjs +7 -6
- package/modules/agent-door/conformance/security.mjs +3 -2
- package/modules/agent-door/conformance/step-hooks.mjs +4 -0
- package/modules/agent-door/conformance/surface.mjs +7 -4
- package/modules/agent-door/conformance/target.mjs +2 -1
- package/modules/agent-door/conformance/webhooks.mjs +2 -1
- package/modules/delivery-producer/mail.mjs +20 -0
- package/modules/portability/README.md +5 -2
- package/modules/portability/catalogue.mjs +12 -2
- package/package.json +1 -1
|
@@ -1,16 +1,20 @@
|
|
|
1
1
|
// All recorded code uses the same source graph and seed ownership boundary.
|
|
2
2
|
import fs from 'node:fs';
|
|
3
3
|
import path from 'node:path';
|
|
4
|
-
import {raw, safe, requirePhysical, testSource, freedEntries} from './files.mjs';
|
|
4
|
+
import {raw, safe, requirePhysical, testSource, freedEntries, toolFile} from './files.mjs';
|
|
5
5
|
import {dependencies, resolve, external, bindings, lexicalExports} from './runtime-dependencies.mjs';
|
|
6
|
+
import {relocateDependencies} from './module-edges.mjs';
|
|
7
|
+
import {sharedNamespaces} from './copy-namespaces.mjs';
|
|
6
8
|
const code = name => /\.(?:[cm]?[jt]s|[jt]sx)$/.test(name) && !testSource(name);
|
|
7
9
|
const inside = (name, prefix) => prefix === '.' ? !name.startsWith('../') && !path.posix.isAbsolute(name) : name === prefix || name.startsWith(prefix + '/');
|
|
8
10
|
const mapped = (source, copy) => copy.path + source.slice(copy.originPath.length);
|
|
9
11
|
const quote = value => "'" + value.replaceAll("'", "'\\''") + "'";
|
|
10
12
|
|
|
11
|
-
export function completeModuleCopies(root, plans, {tree, read, revision, base, deliveries = [], ownerSources = new Map()}) {
|
|
13
|
+
export function completeModuleCopies(root, plans, {tree, read, revision, base, deliveries = [], ownerSources = new Map(), relocations = new Map()}) {
|
|
12
14
|
const index = new Set(raw(root, 'ls-files', '-z').toString('utf8').split('\0').filter(Boolean));
|
|
13
15
|
const required = new Set();
|
|
16
|
+
const mappings = plans.filter(plan => !plan.retired).map(({copy}) => ({copy, ...namespace(copy)})).filter(mapping => mapping.from);
|
|
17
|
+
const shared = sharedNamespaces(mappings);
|
|
14
18
|
const cache = new Map(), planned = new Map(), recorded = new Map(), queue = [], withheld = [];
|
|
15
19
|
const disk = {has: name => {
|
|
16
20
|
try { return fs.lstatSync(path.join(root, name)).isFile(); }
|
|
@@ -37,14 +41,29 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
|
|
|
37
41
|
for (const target of Object.keys(plan.copy.adapted ?? {})) enqueue(plan, plan.copy.originPath + target.slice(plan.copy.path.length), null, true);
|
|
38
42
|
}
|
|
39
43
|
const directoryAdditions = new Set([...planned].filter(([target, {plan}]) => !Object.hasOwn(plan.copy.files, target) && !tree.has(plan.copy.originPath)).map(([target]) => target));
|
|
44
|
+
function namespace(copy) {
|
|
45
|
+
const file = Object.hasOwn(copy.files, copy.path) || tree.has(copy.originPath);
|
|
46
|
+
if (file && path.posix.basename(copy.path) !== path.posix.basename(copy.originPath)) return {};
|
|
47
|
+
return {directory: !file, to: file ? path.posix.dirname(copy.path) : copy.path,
|
|
48
|
+
from: file ? path.posix.dirname(copy.originPath) : copy.originPath};
|
|
49
|
+
}
|
|
40
50
|
function witness(target, source) {
|
|
41
|
-
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
51
|
+
if (plans.some(({copy}) => {
|
|
52
|
+
const {to, from} = namespace(copy);
|
|
53
|
+
return from && inside(target, to) && path.posix.join(from, path.posix.relative(to, target)) === source;
|
|
54
|
+
})) return true;
|
|
55
|
+
return recordedDestination(source).includes(target);
|
|
56
|
+
}
|
|
57
|
+
function recordedDestination(source) {
|
|
58
|
+
// Prefer the explicitly selected subtree over a broader, sparse runtime
|
|
59
|
+
// copy. Never choose between equally specific namespaces for the seed.
|
|
60
|
+
let candidates = [...mappings, ...shared].filter(({from}) => inside(source, from));
|
|
61
|
+
const specificity = Math.max(...candidates.map(({from}) => from.length));
|
|
62
|
+
candidates = candidates.filter(({from}) => from.length === specificity);
|
|
63
|
+
const destination = ({from, to}) => path.posix.join(to, path.posix.relative(from, source));
|
|
64
|
+
const members = candidates.filter(mapping => mapping.copy && Object.hasOwn(mapping.copy.files, destination(mapping)));
|
|
65
|
+
if (members.length) candidates = members;
|
|
66
|
+
return [...new Set(candidates.map(destination))];
|
|
48
67
|
}
|
|
49
68
|
function include(source, target) {
|
|
50
69
|
required.add(target);
|
|
@@ -115,7 +134,24 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
|
|
|
115
134
|
const source = planned.get(destination)?.source ?? (owner && owner.copy.originPath + destination.slice(owner.copy.path.length)) ?? dependency;
|
|
116
135
|
return {...request, dependency: source, destination, satisfied: true};
|
|
117
136
|
}
|
|
118
|
-
|
|
137
|
+
const expected = dependency && path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency));
|
|
138
|
+
// Relocate only new deliveries. Existing files and acknowledged adaptations
|
|
139
|
+
// retain their current imports and ownership, including old missing edges.
|
|
140
|
+
if (specifier.startsWith('.') && dependency && !recorded.has(target) && !witness(expected, dependency)) {
|
|
141
|
+
const destinations = recordedDestination(dependency);
|
|
142
|
+
if (destinations.length > 1) return {...request, manifests, dependency, destination: expected,
|
|
143
|
+
reason: `ambiguous Base copy mappings for ${dependency}: ${destinations.join(', ')}`};
|
|
144
|
+
if (destinations.length === 1) {
|
|
145
|
+
const destination = destinations[0];
|
|
146
|
+
// Preserve extensionless TS and emitted-JS spellings by moving the
|
|
147
|
+
// original request path by the same displacement as its resolved file.
|
|
148
|
+
const requested = path.posix.join(path.posix.dirname(source), request.kind === 'require' ? specifier : decodeURIComponent(specifier));
|
|
149
|
+
let relocation = path.posix.relative(path.posix.dirname(target), path.posix.join(path.posix.dirname(destination), path.posix.relative(path.posix.dirname(dependency), requested)));
|
|
150
|
+
if (!relocation.startsWith('.')) relocation = './' + relocation;
|
|
151
|
+
return {...request, manifests, dependency, destination, relocation};
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return {...request, manifests, dependency, destination: expected};
|
|
119
155
|
}
|
|
120
156
|
const key = (target, request) => JSON.stringify([target, request.kind, request.types, request.specifier]);
|
|
121
157
|
const bootstrap = source => /^(?:edition-authoring|(?:default-seed|export)\/scripts\/base-cli\/edition-authoring)\//.test(source);
|
|
@@ -177,6 +213,14 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
|
|
|
177
213
|
const imports = bindings(bytes), oldBindings = bindings(before);
|
|
178
214
|
const typeImports = bindings(bytes, true), oldTypes = bindings(before, true);
|
|
179
215
|
const edges = requests(bytes, source, target).map(request => edge(source, target, request));
|
|
216
|
+
// lock.mjs reads the whole tool dynamically to identify it. Deliver that
|
|
217
|
+
// same file set, including parser notices and modules outside its imports.
|
|
218
|
+
if (/^(?:edition-authoring|(?:default-seed|export)\/scripts\/base-cli\/edition-authoring)\/lock\.mjs$/.test(source)) {
|
|
219
|
+
const from = source.slice(0, -'lock.mjs'.length), to = target.slice(0, -'lock.mjs'.length);
|
|
220
|
+
for (const dependency of tree.keys()) if (dependency.startsWith(from) && toolFile(dependency.slice(from.length))) {
|
|
221
|
+
edges.push({dependency, destination: to + dependency.slice(from.length)});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
180
224
|
for (const {manifests = []} of [...edges]) for (const dependency of manifests) {
|
|
181
225
|
edges.push({dependency, destination: path.posix.join(path.posix.dirname(target), path.posix.relative(path.posix.dirname(source), dependency))});
|
|
182
226
|
}
|
|
@@ -192,7 +236,7 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
|
|
|
192
236
|
if (!dependency) refuse(target, edge.reason ?? `no Base source for ${specifier}`, `\${EDITOR:-vi} ${quote(target)}`);
|
|
193
237
|
if (!witness(destination, dependency)) {
|
|
194
238
|
if (novel) { hold = {path: target, originPath: source, dependency}; break; }
|
|
195
|
-
refuse(target, `no copy mapping witnesses ${destination} from ${dependency}`, '${EDITOR:-vi} base-copies.json');
|
|
239
|
+
refuse(target, edge.reason ?? `no copy mapping witnesses ${destination} from ${dependency}`, '${EDITOR:-vi} base-copies.json');
|
|
196
240
|
}
|
|
197
241
|
}
|
|
198
242
|
if (hold) {
|
|
@@ -213,6 +257,7 @@ export function completeModuleCopies(root, plans, {tree, read, revision, base, d
|
|
|
213
257
|
}
|
|
214
258
|
}
|
|
215
259
|
}
|
|
260
|
+
if (!adapted && edges.some(edge => edge.relocation)) relocations.set(target, Buffer.from(relocateDependencies(bytes, edges)));
|
|
216
261
|
}
|
|
217
262
|
return withheld;
|
|
218
263
|
}
|
|
@@ -66,8 +66,9 @@ export function dependencies(source, filename = 'module.mjs') {
|
|
|
66
66
|
}
|
|
67
67
|
} while (changed);
|
|
68
68
|
const add = (node, kind, types = false) => {
|
|
69
|
-
|
|
70
|
-
|
|
69
|
+
node = unwrap(node);
|
|
70
|
+
const specifier = literal(node);
|
|
71
|
+
if (specifier) result.push({specifier: canonical(specifier, kind), kind, types, start: node.start, end: node.end, literal: specifier});
|
|
71
72
|
};
|
|
72
73
|
for (const node of all) {
|
|
73
74
|
if (node.type === 'ImportDeclaration') {
|
|
@@ -98,3 +99,13 @@ export function dependencies(source, filename = 'module.mjs') {
|
|
|
98
99
|
versions.set(source, result);
|
|
99
100
|
return result;
|
|
100
101
|
}
|
|
102
|
+
|
|
103
|
+
// Only parsed dependency literals are rewritten: comments, strings and JSX
|
|
104
|
+
// text that happen to contain the same path remain edition source.
|
|
105
|
+
export function relocateDependencies(source, requests) {
|
|
106
|
+
const replacements = new Map(requests.filter(request => request.relocation).map(request => [request.start, request]));
|
|
107
|
+
for (const {start, end, literal, specifier, relocation} of [...replacements.values()].sort((a, b) => b.start - a.start)) {
|
|
108
|
+
source = source.slice(0, start) + JSON.stringify(relocation + literal.slice(specifier.length)) + source.slice(end);
|
|
109
|
+
}
|
|
110
|
+
return source;
|
|
111
|
+
}
|
|
@@ -389,6 +389,11 @@ function validateClaimSource(text, rows = claimRows(text), old) {
|
|
|
389
389
|
}
|
|
390
390
|
function validateOriginalClaims(old, rows = claimRows(read('CONTRACT.md'))) {
|
|
391
391
|
const selected = originalClaims(old), remaining = [...rows], problems = []
|
|
392
|
+
// An empty history imposes no retention constraint; current claims stay unique.
|
|
393
|
+
if (!selected.rows.length) {
|
|
394
|
+
const claims = rows.map(row => claimValue(row, 'Claim'))
|
|
395
|
+
if (new Set(claims).size === claims.length) return
|
|
396
|
+
}
|
|
392
397
|
for (const [index, row] of selected.rows.entries()) {
|
|
393
398
|
const source = sourceClaim(selected.file, row, index)
|
|
394
399
|
const found = remaining.findIndex(current => claimValue(current, '#') === source.number && claimValue(current, 'Claim') === source.claim)
|
package/global/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,63 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.2.87
|
|
4
|
+
|
|
5
|
+
- Connect declared, contained agent verifier drivers to named native Worker RPC entrypoints, and run built queue consumers alongside producers. Public-door fixtures prove real queued effects, execution-time consent revocation and retained audits without a served test route.
|
|
6
|
+
|
|
7
|
+
- Allow declared RPC provider verifiers in isolated Workers without application bindings or network access. Native signed delivery and approval still run; unsigned receipts and escaping modules fail.
|
|
8
|
+
|
|
9
|
+
- Generate disposable native JSON/PEM owner bindings through contained test modules. A signed-claim fixture imports a fresh GitHub App RSA key and signs/verifies its JWT; invalid keys remain refused.
|
|
10
|
+
|
|
11
|
+
- Run optional native journey beforeStep/afterStep hooks between mandatory autonomous and held steps, allowing real repository consent and queued-work preparation without skipping conformance.
|
|
12
|
+
|
|
13
|
+
- Accept composite revoke/narrow targets consisting solely of required string identifiers. Match every witness key and retain grant-subset, neighboring-grant and widening-refusal checks.
|
|
14
|
+
|
|
15
|
+
- Give native queued effects separate once-only claims through a persisted continuation-item resolver, preserving the originating operation, consent, sponsor, scopes, approvers and public idempotency key. Replays return only the selected item's result; mismatched admissions and revoked consent remain refused.
|
|
16
|
+
|
|
17
|
+
- Clarify the already-shipped 0.2.86 independent-reviewer admission/mail hook and its use with a named second-person door approval. The native approver is recorded separately from the sponsor, whose self-approval remains forbidden by that named policy.
|
|
18
|
+
|
|
19
|
+
- Refresh from a Base archive preserves unrecorded workflows without requesting unavailable Git history. Explicitly recorded templates still refresh; ownership, edits and ancestry-dependent migration refusals remain protected. See `ADOPTING.md`.
|
|
20
|
+
|
|
21
|
+
- Deliver the full edition-authoring tool identity with yaml and Babel LICENSE/README files, so package-created locks pass the delivered template's check without relocking. Existing helper-collision protections still apply. See `ADOPTING.md`.
|
|
22
|
+
|
|
23
|
+
- Refuse ambiguous undeclared `oc_` tables during installation transfers instead of silently excluding their rows; retain exact Base owner-claim exclusions and explicit include/exclude choices. See `ADOPTING.md`.
|
|
24
|
+
|
|
25
|
+
- Create every accepted Managed-download table before executing interleaved inserts, retaining deferred foreign keys and the existing SQL/schema/ledger refusal boundaries. See `ADOPTING.md`.
|
|
26
|
+
|
|
27
|
+
- Document the full 0.2.82 helper and case-spelling recovery sequence using the current installed package. Add a required hosted Ubuntu 24.04 Verify job for the delivered template's cold/save/remove/restore/warm cache lifecycle and real Chromium launches. See `ADOPTING.md`.
|
|
28
|
+
|
|
29
|
+
- Contract document generation accepts distinct current Homepage claims when the historical source has none. Missing original claims and duplicate current claims remain refused.
|
|
30
|
+
|
|
31
|
+
- Refresh read-only native revision prerequisites before argument-injection probes, while retaining class/fact/decision checks and fresh write keys.
|
|
32
|
+
|
|
33
|
+
- Follow audit cursors when checking pending and completed native targets, including targets beyond the first audit page.
|
|
34
|
+
|
|
35
|
+
- Accept a native reviewer's final HTTP 200 session response alongside 303, retaining independent-cookie, one-use proof and lifecycle checks.
|
|
36
|
+
|
|
37
|
+
- Match current workflow templates from a Base archive's supplied snapshot; preserve unmatched seed-owned workflow bytes without requesting unavailable history. Historical migration and legacy-membership refusals remain explicit.
|
|
38
|
+
|
|
39
|
+
- Document remaining native integration prerequisites: receipt fixtures need their native client and retained key before mandatory steps; creation adapters with consumed preparation need explicit current replay authorization. Neither native guard is bypassed by these probe fixes.
|
|
40
|
+
|
|
41
|
+
- Unify managed mail's public `MAIL_FROM` input across deploy declarations and delivery production. Accept its environment-mapped deploy input alongside an empty public default; refuse disagreeing configured senders with both values and source locations before packaging or deployment. Keep credential overlaps private and refused. See `modules/delivery-producer/ADOPTING.md`.
|
|
42
|
+
|
|
43
|
+
- Use the journey's selected native client for post-write event snapshots, so valid client-only change events pass conformance under the same resource visibility checks as the write and read. Steps without a selected client keep the Business credential path.
|
|
44
|
+
|
|
45
|
+
- Agent conformance journeys can select real native client credentials and reference phase-local values from a contained `verification.fixtures` module. Fresh native setup runs before each policy journey round, including REST mutations that enter the actual agent door to establish receipt custody. Preparation finishes before adopting held policy, and its native audit identity is checked separately from the journey's exact audit count. Receipts, destructive state, approvals and audits retain their actual client identity and scope. Missing clients, missing fixtures and reused consumed state still fail verification. This provides fixture support for Mango and Oncall; editions must still declare their missing tool/class cases.
|
|
46
|
+
|
|
47
|
+
- A managed server keeps running when a timed-out status client disconnects before its reply; the control socket contains the resulting write error.
|
|
48
|
+
|
|
49
|
+
- `rer refresh-base` carries import-reached transitive siblings when two disjoint recorded directory copies establish the same shared parent placement, resolving refusals such as owner-claim's dependency on `modules/dependencies/protocol.mjs` without a product-specific copy list. Singleton selections witness their own directory siblings but cannot invent a broader competing parent namespace. More-specific mappings and seed ownership protections remain; genuinely unmapped or ambiguous dependencies still refuse before writes.
|
|
50
|
+
|
|
51
|
+
- `rer refresh-base` places newly delivered module imports against the most specific recorded vendor namespace, including files covered by a directory copy. Relocated files retain their Base baseline as acknowledged seed-owned adaptations; unmapped and ambiguous dependencies still refuse before writes. See `edition-authoring/ADOPTING.md`.
|
|
52
|
+
|
|
53
|
+
- Keep copy-record file and mode maps stable when namespace relocations become acknowledged adaptations, so repeating an identical refresh preserves the entire tree and record.
|
|
54
|
+
|
|
55
|
+
### Known issues
|
|
56
|
+
|
|
57
|
+
- Historical 0.2.82 helper collisions and case-spelling recovery still require the explicit manual sequence in `ADOPTING.md`.
|
|
58
|
+
- Native-client receipt fixtures must establish their own native client and retained operation key before mandatory journey steps. Consumed preparation still needs an explicit native replay-admission contract; cached outcomes never bypass current authorization.
|
|
59
|
+
- Protected import-kit adaptations may need manual dependency reconciliation before refresh. A refused refresh preserves their bytes and copy ownership.
|
|
60
|
+
|
|
3
61
|
## 0.2.86
|
|
4
62
|
|
|
5
63
|
- Let verifier owner initializers and native journeys complete real email confirmation through a bounded captured-mail reader and supply per-run data to declared isolated provider edges. The controls stay outside production builds. Prove fresh agent-door/settings source copies typecheck with upstream tests omitted.
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export async function auditRows(c) {
|
|
2
|
+
const rows = []; let cursor = null, differs = 0;
|
|
3
|
+
for (let page = 0; page < 100; page++) {
|
|
4
|
+
const result = await c.personJson(`/agents/api/audit?agent=${encodeURIComponent(c.agentId)}${cursor ? `&after=${encodeURIComponent(cursor)}` : ''}`);
|
|
5
|
+
if (!Array.isArray(result.rows) || !Number.isInteger(result.differs_from_policy)) throw new Error('Audit API must return rows and differs_from_policy');
|
|
6
|
+
rows.push(...result.rows); differs += result.differs_from_policy;
|
|
7
|
+
if (result.cursor == null || result.cursor === cursor) return { rows, differs };
|
|
8
|
+
cursor = result.cursor;
|
|
9
|
+
}
|
|
10
|
+
throw new Error('Audit pagination exceeded 100 pages');
|
|
11
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Read each tested principal independently, retaining its native row order. */
|
|
2
|
+
export async function auditRows(c, { agents = [c.agentId, ...c.nativeAgents ?? []], includeFixtures = false } = {}) {
|
|
3
|
+
const rows = []; let differs = 0;
|
|
4
|
+
for (const agentId of new Set(agents)) {
|
|
5
|
+
let cursor = null;
|
|
6
|
+
for (let page = 0; ; page++) {
|
|
7
|
+
if (page === 100) throw new Error('Audit pagination exceeded 100 pages');
|
|
8
|
+
const query = new URLSearchParams();
|
|
9
|
+
if (agentId !== null) query.set('agent', agentId);
|
|
10
|
+
if (cursor) query.set('after', cursor);
|
|
11
|
+
const result = await c.personJson(`/agents/api/audit?${query}`);
|
|
12
|
+
if (!Array.isArray(result.rows) || !Number.isInteger(result.differs_from_policy)) throw new Error('Audit API must return rows and differs_from_policy');
|
|
13
|
+
rows.push(...result.rows.filter(row => includeFixtures || !c.fixtureAuditIds?.has(row.id)));
|
|
14
|
+
differs += result.differs_from_policy;
|
|
15
|
+
if (result.cursor == null || result.cursor === cursor) break;
|
|
16
|
+
cursor = result.cursor;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
return { rows, differs };
|
|
20
|
+
}
|
|
@@ -2,25 +2,22 @@ import { isDeepStrictEqual } from 'node:util';
|
|
|
2
2
|
import { classIds } from './protocol.mjs';
|
|
3
3
|
import { AGENT_CLASSES } from './surface.mjs';
|
|
4
4
|
import { targetIdentity } from './target.mjs';
|
|
5
|
+
import { auditRows } from './audit-rows.mjs';
|
|
5
6
|
|
|
6
|
-
export
|
|
7
|
-
const rows = []; let cursor = null, differs = 0;
|
|
8
|
-
for (let page = 0; page < 100; page++) {
|
|
9
|
-
const result = await c.personJson(`/agents/api/audit?agent=${encodeURIComponent(c.agentId)}${cursor ? `&after=${encodeURIComponent(cursor)}` : ''}`);
|
|
10
|
-
if (!Array.isArray(result.rows) || !Number.isInteger(result.differs_from_policy)) throw new Error('Audit API must return rows and differs_from_policy');
|
|
11
|
-
rows.push(...result.rows); differs += result.differs_from_policy;
|
|
12
|
-
if (result.cursor == null || result.cursor === cursor) return { rows, differs };
|
|
13
|
-
cursor = result.cursor;
|
|
14
|
-
}
|
|
15
|
-
throw new Error('Audit pagination exceeded 100 pages');
|
|
16
|
-
}
|
|
7
|
+
export { auditRows } from './audit-rows.mjs';
|
|
17
8
|
export async function auditPhase(c) {
|
|
18
9
|
const { rows, differs } = await auditRows(c), expected = [...c.calls];
|
|
19
10
|
c.add('BASE-AGENT-009.1.count', rows.length === expected.length, `Expected exactly ${expected.length} audit rows for tool calls, resource reads and approval executions, found ${rows.length}.`);
|
|
20
11
|
c.add('BASE-AGENT-009.1.unique', new Set(rows.map(row => row.id)).size === rows.length, 'Every tool call, resource read and approval execution must have its own audit ID.');
|
|
12
|
+
const perAgent = new Map();
|
|
13
|
+
for (const row of rows) {
|
|
14
|
+
if (!perAgent.has(row.agent?.id)) perAgent.set(row.agent?.id, []);
|
|
15
|
+
perAgent.get(row.agent?.id).push(row);
|
|
16
|
+
}
|
|
21
17
|
for (const [index, call] of expected.entries()) {
|
|
22
|
-
const
|
|
23
|
-
|
|
18
|
+
const principal = call.principal ?? { agent: { id: c.agentId, specialist: c.surface.specialist }, consent: c.consent, sponsor: c.sponsor.id };
|
|
19
|
+
const row = perAgent.get(principal.agent.id)?.shift(), decision = call.decision;
|
|
20
|
+
c.add(`BASE-AGENT-009.1.call.${index}`, Boolean(row) && row.tool === call.name && row.consent === principal.consent && row.agent?.id === principal.agent.id && row.agent?.specialist === principal.agent.specialist && row.sponsor?.id === principal.sponsor && (!call.principal || row.client_id === principal.clientId && row.agent?.name === principal.agent.name) && typeof row.label === 'string' && row.label.includes(' for ') && Number.isFinite(Date.parse(row.at)) && row.door === (call.kind === 'embedded' ? 'embedded' : 'mcp'), `${call.name} lacks its complete ordered audit row.`);
|
|
24
21
|
if (!row) continue;
|
|
25
22
|
if (call.code === 'native_proof_required') c.add(`BASE-AGENT-004.native-proof.audit.${index}`, row.outcome === 'refused' && row.code === call.code, `${call.name} native proof challenge must retain its refused audit outcome.`);
|
|
26
23
|
c.add(`BASE-AGENT-009.1.resource.${index}`, call.kind === 'resources/read' ? row.resource === call.args.uri : row.resource === null || targetIdentity(row.resource), `${call.name} audit resource must identify the requested URI or the seed-resolved native kind and id.`);
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { auditRows } from './audit-rows.mjs';
|
|
2
|
+
|
|
3
|
+
const object = value => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
4
|
+
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
5
|
+
|
|
6
|
+
/** Each round gets new native state, never a previous round's consumed values. */
|
|
7
|
+
export function phaseFixtures(c, prepare) {
|
|
8
|
+
c.fixtureValues = {};
|
|
9
|
+
c.clients = new Map();
|
|
10
|
+
c.nativeAgents = new Set();
|
|
11
|
+
c.fixtureAuditIds = new Set();
|
|
12
|
+
c.prepare = async phase => {
|
|
13
|
+
c.fixtureValues = {};
|
|
14
|
+
c.clients.clear();
|
|
15
|
+
if (!prepare) return;
|
|
16
|
+
try {
|
|
17
|
+
const before = new Set((await auditRows(c, { agents: [null], includeFixtures: true })).rows.map(row => row.id));
|
|
18
|
+
const result = await prepare({ phase, tool: c.tool });
|
|
19
|
+
if (!object(result) || Object.keys(result).some(key => !['values', 'clients'].includes(key)) || !object(result.values ?? {}) || !object(result.clients ?? {})) throw new Error('Native phase preparation must return {values,clients}.');
|
|
20
|
+
for (const [label, client] of Object.entries(result.clients ?? {})) {
|
|
21
|
+
if (!text(label) || !object(client) || Object.keys(client).sort().join(',') !== 'agent,clientId,token'
|
|
22
|
+
|| !text(client.token) || !text(client.clientId) || !object(client.agent) || !text(client.agent.id) || !text(client.agent.name)
|
|
23
|
+
|| Object.keys(client.agent).some(key => !['id', 'name', 'specialist'].includes(key))
|
|
24
|
+
|| client.agent.specialist !== c.surface.specialist || client.agent.id === c.agentId) throw new Error('Native fixture clients require a credential, clientId and distinct agent {id,name,specialist}.');
|
|
25
|
+
c.clients.set(label, structuredClone(client));
|
|
26
|
+
c.nativeAgents.add(client.agent.id);
|
|
27
|
+
}
|
|
28
|
+
c.fixtureValues = structuredClone(result.values ?? {});
|
|
29
|
+
const setup = await auditRows(c, { agents: [...c.clients.values()].map(client => client.agent.id), includeFixtures: true });
|
|
30
|
+
for (const row of setup.rows) if (!before.has(row.id)) {
|
|
31
|
+
const client = [...c.clients.values()].find(client => client.agent.id === row.agent?.id);
|
|
32
|
+
if (row.sponsor?.id !== c.sponsor.id || row.client_id !== client.clientId || row.agent?.name !== client.agent.name || row.agent?.specialist !== client.agent.specialist || row.consent !== null) throw new Error('Native fixture preparation identity differs from its declared client.');
|
|
33
|
+
c.fixtureAuditIds.add(row.id);
|
|
34
|
+
}
|
|
35
|
+
} catch {
|
|
36
|
+
c.clients.clear();
|
|
37
|
+
throw new Error('Native phase preparation failed; fixture values are not logged.');
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
c.stepTool = (step, args, options = {}) => c.tool(step.tool, args, { ...(step.client === undefined ? {} : { client: step.client }), ...options });
|
|
41
|
+
}
|
|
@@ -16,16 +16,16 @@ import { invocationPhase } from './invocation.mjs';
|
|
|
16
16
|
export { validateAgentSurface } from './surface.mjs';
|
|
17
17
|
|
|
18
18
|
/** Run against a fresh, real installation using its HTTP and person doors. */
|
|
19
|
-
export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney }) {
|
|
19
|
+
export async function runAgentDoorConformance({ fetch, invoke, origin, surface, signer, person, sponsors = [person], webhooks, business = 'rer-agent-conformance', consent = randomUUID(), now, prove, nativeJourney, nativeStep, prepare }) {
|
|
20
20
|
const validation = validateAgentSurface(surface), points = [...validation.points];
|
|
21
21
|
if (!validation.ok) return { ok: false, points };
|
|
22
22
|
if (typeof fetch !== 'function' || !signer?.privateKey || !signer.issuer || !signer.installationId || !signer.kid || !person?.email || !person.cookie || typeof person.sub !== 'string' || !person.sub.trim() || typeof consent !== 'string' || !consent.trim() || new URL(origin).origin !== origin) throw new TypeError('Conformance requires fetch, canonical origin, signer, consent and signed-in person {email,cookie,sub}');
|
|
23
|
-
const c = createProtocol({ fetch, origin, surface, signer, person, business, consent, now, prove, points, agentId: `rer-conformance-${randomUUID()}`, seq: 0, revision: 0, listed: new Map() });
|
|
23
|
+
const c = createProtocol({ fetch, origin, surface, signer, person, business, consent, now, prove, nativeStep, prepare, points, agentId: `rer-conformance-${randomUUID()}`, seq: 0, revision: 0, listed: new Map() });
|
|
24
24
|
await c.phase('BASE-AGENT-001.transport', () => discoverDoor(c));
|
|
25
25
|
await c.phase('BASE-AGENT-007.phase0', () => unsetPolicy(c, true));
|
|
26
26
|
await c.phase('BASE-AGENT-007.phase1', () => removalPhase(c));
|
|
27
|
-
await c.phase('BASE-AGENT-013.phase2', async () => { await c.adopt(autonomousPolicy()); await listedDoor(c); await runJourney(c, 'autonomous', { injections: true, replay: true }); });
|
|
28
|
-
await c.phase('BASE-AGENT-013.phase3', async () => { await c.adopt(heldPolicy()); await runJourney(c, 'held', { held: true }); });
|
|
27
|
+
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 }); });
|
|
28
|
+
await c.phase('BASE-AGENT-013.phase3', async () => { await c.prepare('held'); await c.adopt(heldPolicy()); await runJourney(c, 'held', { held: true }); });
|
|
29
29
|
await c.phase('BASE-AGENT-007.phase4', () => blockedPhases(c));
|
|
30
30
|
await c.phase('BASE-AGENT-011.phase5', () => pausePhase(c));
|
|
31
31
|
await c.phase('BASE-AGENT-004.phase6', () => negativePhase(c));
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { errorCode } from './protocol.mjs';
|
|
2
|
+
|
|
3
|
+
// Refresh read dependencies only. Repeating a write here would create another
|
|
4
|
+
// effect, and resolving its old output cannot provide a current native revision.
|
|
5
|
+
export async function injectionArgs(c, step, outputs) {
|
|
6
|
+
const fresh = new Map(outputs), refreshed = new Set();
|
|
7
|
+
async function visit(value) {
|
|
8
|
+
if (!value || typeof value !== 'object') return;
|
|
9
|
+
if (typeof value.$from === 'string') {
|
|
10
|
+
const source = c.surface.journey.find(item => item.id === value.$from);
|
|
11
|
+
if (!source || refreshed.has(source.id) || !c.surface.tools.find(tool => tool.name === source.tool)?.readOnly) return;
|
|
12
|
+
refreshed.add(source.id);
|
|
13
|
+
await visit(source.args);
|
|
14
|
+
const args = c.args(source, fresh), proof = await c.proof(source.tool, args);
|
|
15
|
+
const answer = await c.tool(source.tool, args, proof);
|
|
16
|
+
if (answer.result?.isError || answer.result?.structuredContent === undefined) throw new Error(`Injection prerequisite ${source.id} failed (${errorCode(answer) ?? answer.status})`);
|
|
17
|
+
fresh.set(source.id, answer.result.structuredContent);
|
|
18
|
+
} else for (const item of Object.values(value)) await visit(item);
|
|
19
|
+
}
|
|
20
|
+
await visit(step.args);
|
|
21
|
+
const args = c.args(step, fresh);
|
|
22
|
+
const write = !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly;
|
|
23
|
+
return { ...args, ...c.resolve(step.inject, fresh), ...(write ? { idempotency_key: args.idempotency_key } : {}) };
|
|
24
|
+
}
|
|
@@ -7,6 +7,7 @@ export async function invocationPhase(c, invoke) {
|
|
|
7
7
|
const step = c.surface.journey.find(item => !c.surface.tools.find(tool => tool.name === item.tool)?.readOnly);
|
|
8
8
|
if (!step) throw new Error('Durable invocation conformance requires a mutating journey step.');
|
|
9
9
|
await c.adopt(autonomousPolicy());
|
|
10
|
+
await c.prepare('invocation');
|
|
10
11
|
const who = { person: { id: c.sponsor.id }, agent: { id: c.agentId, name: 'Agent door conformance', specialist: c.surface.specialist }, consent: c.consent, scopes: [c.surface.tools.find(tool => tool.name === step.tool).scope] };
|
|
11
12
|
const schedule = () => JSON.stringify({ name: step.tool, args: c.args(step, new Map(), { unresolved: true }), who });
|
|
12
13
|
const run = async saved => {
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { isDeepStrictEqual } from 'node:util';
|
|
3
3
|
import { classIds, subset, errorCode, APPROVAL } from './protocol.mjs';
|
|
4
|
-
import { grantSet } from './narrowing.mjs';
|
|
4
|
+
import { grantSet, narrowingTargets } from './narrowing.mjs';
|
|
5
5
|
import { schemaErrors } from './schema.mjs';
|
|
6
6
|
import { checkTarget } from './target.mjs';
|
|
7
|
+
import { nativeStepHook } from './step-hooks.mjs';
|
|
8
|
+
import { injectionArgs } from './injection.mjs';
|
|
7
9
|
|
|
8
10
|
export function checkClasses(c, step, answer, phase) {
|
|
9
11
|
const actual = answer.decision?.classes;
|
|
@@ -17,7 +19,7 @@ function checkOutput(c, step, answer, phase) {
|
|
|
17
19
|
async function checkResources(c, step, answer, phase, held) {
|
|
18
20
|
const links = answer.result?.content?.filter(item => item.type === 'resource_link') ?? [];
|
|
19
21
|
for (const [i, link] of links.entries()) {
|
|
20
|
-
const read = await c.mcp('resources/read', { uri: link.uri });
|
|
22
|
+
const read = await c.mcp('resources/read', { uri: link.uri }, step.client === undefined ? {} : { client: step.client });
|
|
21
23
|
const classes = read.decision?.classes, needsApproval = held && classes?.some(item => item.class !== 'standard');
|
|
22
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.`);
|
|
23
25
|
c.add(`BASE-AGENT-003.4.${phase}.${step.id}.${i}`, read.status === 200 && (needsApproval
|
|
@@ -38,6 +40,7 @@ export async function runJourney(c, phase, { held = false, injections = false, r
|
|
|
38
40
|
try {
|
|
39
41
|
for (const step of c.surface.journey) {
|
|
40
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);
|
|
41
44
|
const narrowing = !held && c.surface.narrowings?.find(fixture => fixture.step === step.id);
|
|
42
45
|
const grantsBefore = narrowing ? await grantSet(c, narrowing.witness, outputs) : null;
|
|
43
46
|
const before = needsApproval ? await c.witness() : undefined;
|
|
@@ -45,14 +48,14 @@ export async function runJourney(c, phase, { held = false, injections = false, r
|
|
|
45
48
|
let proof = {};
|
|
46
49
|
if (declared.proof) {
|
|
47
50
|
if (!held) {
|
|
48
|
-
const original = await c.witness(), challenge = await c.
|
|
51
|
+
const original = await c.witness(), challenge = await c.stepTool(step, args), bogus = await c.stepTool(step, args, { proofReference: 'bogus-native-proof' });
|
|
49
52
|
const fields = challenge.result?._meta?.['com.runeditrun/error'];
|
|
50
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.`);
|
|
51
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.`);
|
|
52
|
-
proof = await c.proof(step.tool, args, fields?.handoff);
|
|
53
|
-
} else proof = await c.proof(step.tool, args);
|
|
55
|
+
proof = await c.proof(step.tool, args, fields?.handoff, step.client);
|
|
56
|
+
} else proof = await c.proof(step.tool, args, undefined, step.client);
|
|
54
57
|
}
|
|
55
|
-
let answer = await c.
|
|
58
|
+
let answer = await c.stepTool(step, args, proof);
|
|
56
59
|
checkClasses(c, step, answer, phase);
|
|
57
60
|
await checkTarget(c, step, outputs, answer, phase);
|
|
58
61
|
const expectedDisposition = held ? needsApproval ? 'approval' : 'review' : 'autonomous';
|
|
@@ -66,7 +69,7 @@ export async function runJourney(c, phase, { held = false, injections = false, r
|
|
|
66
69
|
const approved = await c.decideApproval(answer);
|
|
67
70
|
await checkTarget(c, step, outputs, answer, phase, true);
|
|
68
71
|
c.add(`BASE-AGENT-008.5.approver.${step.id}`, approved.ok, `Signed-in sponsor approval returned HTTP ${approved.status}.`);
|
|
69
|
-
answer = await c.
|
|
72
|
+
answer = await c.stepTool(step, args, { ...proof, requestState: answer.result.requestState });
|
|
70
73
|
checkClasses(c, step, answer, `${phase}.approved`);
|
|
71
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.');
|
|
72
75
|
}
|
|
@@ -76,34 +79,36 @@ export async function runJourney(c, phase, { held = false, injections = false, r
|
|
|
76
79
|
checkOutput(c, step, answer, phase);
|
|
77
80
|
await checkResources(c, step, answer, phase, held);
|
|
78
81
|
if (narrowing) {
|
|
79
|
-
|
|
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.`);
|
|
80
84
|
const after = await grantSet(c, narrowing.witness, outputs);
|
|
81
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.`);
|
|
82
86
|
const beforeInjection = await c.witness();
|
|
83
|
-
const smuggled = await c.
|
|
87
|
+
const smuggled = await c.stepTool(step, { ...args, idempotency_key: randomUUID(), grant_to_add: 'admin' });
|
|
84
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.`);
|
|
85
89
|
}
|
|
86
90
|
if (!c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
|
|
87
|
-
const snapshot = await c.tool(`${c.surface.seed}.events.list`, { limit: 200 });
|
|
91
|
+
const snapshot = await c.tool(`${c.surface.seed}.events.list`, { limit: 200 }, { client: step.client });
|
|
88
92
|
if (!Array.isArray(snapshot.result?.structuredContent?.events)) throw new Error('Post-effect events.list must return events');
|
|
89
93
|
(c.effectEvents ??= []).push(...snapshot.result.structuredContent.events);
|
|
90
94
|
}
|
|
91
95
|
if (injections && step.inject) {
|
|
92
|
-
const injected =
|
|
93
|
-
const checked = await c.
|
|
96
|
+
const injected = await injectionArgs(c, step, outputs);
|
|
97
|
+
const checked = await c.stepTool(step, injected, proof);
|
|
94
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.`);
|
|
95
99
|
}
|
|
96
100
|
if (replay && !replayed && !c.surface.tools.find(tool => tool.name === step.tool)?.readOnly) {
|
|
97
101
|
replayed = true;
|
|
98
|
-
const beforeReplay = await c.witness(), repeated = await c.
|
|
102
|
+
const beforeReplay = await c.witness(), repeated = await c.stepTool(step, args, proof), afterReplay = await c.witness();
|
|
99
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.`);
|
|
100
104
|
|
|
101
105
|
}
|
|
106
|
+
await nativeStepHook(c, 'afterStep', phase, step, args, outputs, answer.result.structuredContent);
|
|
102
107
|
}
|
|
103
108
|
} finally {
|
|
104
109
|
if (!held) for (const step of c.surface.escalations ?? []) await c.phase(`BASE-AGENT-005.escalation.${step.id}`, async () => {
|
|
105
110
|
const args = c.args(step, outputs), before = await c.witness();
|
|
106
|
-
const answer = await c.
|
|
111
|
+
const answer = await c.stepTool(step, args), after = await c.witness();
|
|
107
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}).`);
|
|
108
113
|
c.add(`BASE-AGENT-005.2.${step.id}`, isDeepStrictEqual(before, after), `${step.tool} changed native state while attempting sponsor escalation.`);
|
|
109
114
|
});
|
|
@@ -1,14 +1,22 @@
|
|
|
1
1
|
/** A closed target-only schema cannot encode a grant to add. Unknown schema
|
|
2
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
|
+
|
|
3
9
|
export function narrowingContract(tool) {
|
|
4
|
-
const schema = tool?.inputSchema,
|
|
5
|
-
if (tool?.widens !== false || !['revoke', 'narrow'].includes(tool.narrowing?.effect) ||
|
|
6
|
-
||
|
|
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
|
|
7
13
|
|| Object.keys(schema).some(key => !['type', 'properties', 'required', 'additionalProperties'].includes(key))
|
|
8
|
-
|| !Array.isArray(schema.required) || schema.required.length !==
|
|
9
|
-
|| !schema.properties || Object.keys(schema.properties).length !==
|
|
10
|
-
|
|
11
|
-
|
|
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
|
+
});
|
|
12
20
|
}
|
|
13
21
|
|
|
14
22
|
export async function grantSet(c, witness, outputs) {
|
|
@@ -5,6 +5,7 @@ import { errorCode, VERSION } from './protocol.mjs';
|
|
|
5
5
|
|
|
6
6
|
export async function negativePhase(c) {
|
|
7
7
|
await c.adopt(autonomousPolicy());
|
|
8
|
+
await c.prepare('negative');
|
|
8
9
|
const before = await c.witness(), iat = seconds(c.now);
|
|
9
10
|
const unavailable = await c.mcp('resources/read', { uri: `unregistered://${crypto.randomUUID()}` });
|
|
10
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.');
|
|
@@ -29,7 +29,7 @@ export function validateNetworkAdapter(config) {
|
|
|
29
29
|
return { module: config.module, origins };
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
function imports(source) {
|
|
32
|
+
function imports(source, builtins) {
|
|
33
33
|
let ast;
|
|
34
34
|
try { ast = parse(source, { sourceType: 'module', createImportExpressions: true }); }
|
|
35
35
|
catch { throw invalid('the adapter or a relative helper is not valid ES module JavaScript.'); }
|
|
@@ -41,7 +41,7 @@ function imports(source) {
|
|
|
41
41
|
if (node.source.type !== 'StringLiteral') throw invalid('adapter imports must use literal relative module paths.');
|
|
42
42
|
specifier = node.source.value;
|
|
43
43
|
}
|
|
44
|
-
if (specifier !== undefined) {
|
|
44
|
+
if (specifier !== undefined && !builtins.includes(specifier)) {
|
|
45
45
|
if (!(specifier.startsWith('./') || specifier.startsWith('../')) || specifier.includes('\\') || specifier.includes('?') || specifier.includes('#')) {
|
|
46
46
|
throw invalid('adapter imports must be relative JavaScript modules; packages, Node APIs and runtime built-ins are unavailable.');
|
|
47
47
|
}
|
|
@@ -57,7 +57,7 @@ function imports(source) {
|
|
|
57
57
|
|
|
58
58
|
// Supply only snapshotted, checked module bytes to workerd. It has no filesystem
|
|
59
59
|
// loader, so an unresolved or computed import cannot read another host file.
|
|
60
|
-
export async function networkAdapterModules(root, entry) {
|
|
60
|
+
export async function networkAdapterModules(root, entry, { builtins = [] } = {}) {
|
|
61
61
|
let directory;
|
|
62
62
|
try { directory = await realpath(root); }
|
|
63
63
|
catch { throw invalid('the seed root is unreadable.'); }
|
|
@@ -80,7 +80,7 @@ export async function networkAdapterModules(root, entry) {
|
|
|
80
80
|
}
|
|
81
81
|
seen.add(path);
|
|
82
82
|
modules.push({ type: 'ESModule', path, contents });
|
|
83
|
-
pending.push(...imports(contents).map(specifier => resolve(dirname(path), specifier)));
|
|
83
|
+
pending.push(...imports(contents, builtins).map(specifier => resolve(dirname(path), specifier)));
|
|
84
84
|
}
|
|
85
85
|
return { root: directory, modules };
|
|
86
86
|
}
|