Repository navigation
Expand file tree
/
Copy pathruntime-mount.js
More file actions
697 lines (646 loc) · 24.8 KB
/
Copy pathruntime-mount.js
File metadata and controls
697 lines (646 loc) · 24.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
/**
* Runtime Mount — Trusted Agent context bundle (proofable.runtime-mount.v1).
* Shared shape for CLI, integrators, and the proofable_agent_mount response.
*/
export const RUNTIME_MOUNT_SCHEMA = 'proofable.runtime-mount.v1';
const PROOF_URL_BASE = 'https://proofable.me/proof/';
/**
* @param {string | null | undefined} value
*/
export function normalizeWallet(value) {
const wallet = String(value || '').trim().toLowerCase();
return /^0x[a-f0-9]{40}$/.test(wallet) ? wallet : '';
}
/**
* @param {unknown} value
*/
export function normalizeQHash(value) {
const normalized = String(value || '').trim().toLowerCase();
if (!normalized) return '';
const with0x = normalized.startsWith('0x') ? normalized : `0x${normalized}`;
return /^0x[a-f0-9]{64}$/.test(with0x) ? with0x : '';
}
/**
* @param {unknown} value
*/
function asString(value) {
const trimmed = String(value ?? '').trim();
return trimmed.length > 0 ? trimmed : '';
}
/**
* @param {unknown} value
* @returns {string[]}
*/
function asStringArray(value) {
if (!Array.isArray(value)) return [];
return value.map(item => String(item || '').trim()).filter(Boolean);
}
/**
* @param {Record<string, unknown> | null | undefined} caps
*/
function capabilitiesToArray(caps) {
if (Array.isArray(caps)) return asStringArray(caps);
if (!caps || typeof caps !== 'object') return [];
return Object.entries(caps)
.filter(([, enabled]) => enabled === true)
.map(([key]) => String(key).trim())
.filter(Boolean);
}
/**
* @param {number | null | undefined} expiresAt
*/
export function isDelegationExpired(expiresAt) {
if (expiresAt === null || expiresAt === 0) return false;
const ms = Number(expiresAt);
return Number.isFinite(ms) && ms > 0 && ms <= Date.now();
}
function filterMountedEntries(entries, authorityMode, allowedActions, deniedActions) {
const allowed = new Set(asStringArray(allowedActions));
const denied = new Set(asStringArray(deniedActions));
return (Array.isArray(entries) ? entries : []).filter(entry => {
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return false;
const action = asString(entry.action);
if (!action) return authorityMode === 'controller';
if (denied.has(action)) return false;
return authorityMode === 'controller' || allowed.has(action);
});
}
/**
* @param {Array<Record<string, unknown>>} identities
* @param {{ agentId?: string, agentWallet?: string, identityQHash?: string }} selector
*/
export function pickIdentity(identities, selector) {
const list = Array.isArray(identities) ? identities : [];
const qHash = normalizeQHash(selector.identityQHash);
if (qHash) {
return list.find(row => normalizeQHash(row.qHash) === qHash) || null;
}
const agentId = asString(selector.agentId).toLowerCase();
const agentWallet = normalizeWallet(selector.agentWallet);
if (agentId) {
const byId = list.filter(row => asString(row.agentId).toLowerCase() === agentId);
if (agentWallet) {
return byId.find(row => normalizeWallet(row.agentWallet) === agentWallet) || byId[0] || null;
}
return byId[0] || null;
}
if (agentWallet) {
return list.find(row => normalizeWallet(row.agentWallet) === agentWallet) || null;
}
return null;
}
/**
* @param {Array<Record<string, unknown>>} delegations
* @param {string} controllerWallet
* @param {string} agentWallet
* @param {string} agentId
*/
export function pickActiveDelegation(delegations, controllerWallet, agentWallet, agentId) {
const list = Array.isArray(delegations) ? delegations : [];
const controller = normalizeWallet(controllerWallet);
const agent = normalizeWallet(agentWallet);
const id = asString(agentId).toLowerCase();
const candidates = list.filter(row => {
if (isDelegationExpired(row.expiresAt)) return false;
const rowAgent = normalizeWallet(row.agentWallet);
const rowController = normalizeWallet(row.controllerWallet);
if (agent && rowAgent && rowAgent !== agent) return false;
if (controller && rowController && rowController !== controller) return false;
if (id && row.agentId && asString(row.agentId).toLowerCase() !== id) return false;
return true;
});
return candidates[0] || null;
}
/**
* @param {Record<string, unknown> | null | undefined} identity
* @param {Record<string, unknown> | null | undefined} delegation
*/
export function resolveEffectiveRuntime(identity, delegation) {
void identity;
void delegation;
return null;
}
/**
* @param {unknown} proof
*/
export function extractAgentContextFromProofs(proofs) {
const identities = [];
const delegations = [];
const list = Array.isArray(proofs) ? proofs : [];
for (const proof of list) {
const qHash = asString(proof?.qHash);
const verifiedVerifiers = Array.isArray(proof?.verifiedVerifiers) ? proof.verifiedVerifiers : [];
for (const vv of verifiedVerifiers) {
const verifierId = asString(vv?.verifierId);
const vvData = vv?.data && typeof vv.data === 'object' ? vv.data : {};
if (verifierId === 'agent-identity') {
identities.push({
qHash,
agentId: vvData.agentId || null,
agentWallet: vvData.agentWallet || null,
agentLabel: vvData.agentLabel || vvData.agentId || 'Agent',
agentType: vvData.agentType || 'agent',
description: vvData.description || null,
capabilities: capabilitiesToArray(vvData.capabilities),
skills: Array.isArray(vvData.skills) ? vvData.skills : [],
instructions: vvData.instructions || null,
services: Array.isArray(vvData.services) ? vvData.services : [],
defaultRuntime:
vvData.defaultRuntime && typeof vvData.defaultRuntime === 'object'
? vvData.defaultRuntime
: undefined
});
}
if (verifierId === 'agent-delegation') {
delegations.push({
qHash,
controllerWallet: vvData.controllerWallet || null,
agentWallet: vvData.agentWallet || null,
agentId: vvData.agentId || null,
allowedActions: asStringArray(vvData.allowedActions),
deniedActions: asStringArray(vvData.deniedActions),
allowedOrigins: asStringArray(vvData.allowedOrigins),
runtimePolicy:
vvData.runtimePolicy && typeof vvData.runtimePolicy === 'object'
? vvData.runtimePolicy
: undefined,
expiresAt: vvData.expiresAt ?? null,
isExpired: isDelegationExpired(vvData.expiresAt),
maxSpend: vvData.maxSpend !== null ? String(vvData.maxSpend) : undefined,
instructions: vvData.instructions || null,
skills: Array.isArray(vvData.skills) ? vvData.skills : [],
provider: vvData.provider || vvData.modelProvider || null,
model: vvData.model || null
});
}
}
}
return { identities, delegations };
}
/**
* @param {Record<string, unknown>} input
*/
export function buildRuntimeBundle(input) {
const identity = input.identity || {};
const delegation = input.delegation || null;
const identityQHash = normalizeQHash(input.identityQHash || identity.qHash);
const delegationQHash = delegation
? normalizeQHash(input.delegationQHash || delegation.qHash) || null
: null;
const agentId = asString(identity.agentId);
const agentWallet = normalizeWallet(identity.agentWallet);
const controllerWallet = normalizeWallet(input.controllerWallet || delegation?.controllerWallet);
if (!identityQHash || !agentId || !agentWallet) {
throw new Error('Runtime mount requires verified agent identity (agentId, agentWallet, identityQHash).');
}
// Runtime selection belongs to the execution resolver. Proof metadata is
// preserved for compatibility and display only.
const effectiveRuntime = resolveEffectiveRuntime(identity, delegation);
const deniedActions = delegation ? asStringArray(delegation.deniedActions) : [];
const allowedActions = delegation ? asStringArray(delegation.allowedActions) : undefined;
const requiresHumanApproval =
delegation?.runtimePolicy &&
typeof delegation.runtimePolicy === 'object' &&
delegation.runtimePolicy.requiresHumanApproval === true;
const approvalPolicy = (() => {
if (!delegation?.approvalPolicy || typeof delegation.approvalPolicy !== 'object') {
return null;
}
const normalized = {};
if (typeof delegation.approvalPolicy.humanApprovalRequiredForNewClaims === 'boolean') {
normalized.humanApprovalRequiredForNewClaims =
delegation.approvalPolicy.humanApprovalRequiredForNewClaims;
}
if (typeof delegation.approvalPolicy.preApprovedContentOnly === 'boolean') {
normalized.preApprovedContentOnly =
delegation.approvalPolicy.preApprovedContentOnly;
}
return Object.keys(normalized).length > 0 ? normalized : null;
})();
const capabilities = asStringArray(identity.capabilities);
const skills = Array.isArray(identity.skills) ? identity.skills : [];
const skillIds = skills
.map(skill =>
typeof skill === 'string' ? skill : asString(skill?.id || skill?.label)
)
.filter(Boolean);
const delegations = delegation ? [delegation] : [];
const activeDelegations = delegations.filter(row => !row.isExpired).length;
const authorityMode = delegation
? 'delegated'
: (controllerWallet && controllerWallet === agentWallet ? 'controller' : 'unbound');
const tools = filterMountedEntries(input.tools, authorityMode, allowedActions, deniedActions);
const resources = filterMountedEntries(input.resources, authorityMode, allowedActions, deniedActions);
const secretBindings = (Array.isArray(input.secretBindings) ? input.secretBindings : [])
.filter(entry => entry && typeof entry === 'object' && !Array.isArray(entry))
.map(entry => ({
qHash: normalizeQHash(entry.qHash),
...(asString(entry.alias) ? { alias: asString(entry.alias) } : {})
}))
.filter(entry => entry.qHash);
return {
schema: RUNTIME_MOUNT_SCHEMA,
mountedAt: new Date().toISOString(),
trust: {
identityQHash,
delegationQHash: delegationQHash || null,
identityProofUrl: `${PROOF_URL_BASE}${identityQHash}`,
delegationProofUrl: delegationQHash ? `${PROOF_URL_BASE}${delegationQHash}` : null
},
authority: {
mode: authorityMode,
controllerWallet: controllerWallet || null
},
identity: {
agentId,
agentWallet,
agentLabel: asString(identity.agentLabel) || agentId,
agentType: asString(identity.agentType) || 'agent',
description: asString(identity.description) || undefined,
instructions: asString(identity.instructions) || undefined,
capabilities,
skills,
services: Array.isArray(identity.services) ? identity.services : undefined,
defaultRuntime:
identity.defaultRuntime && typeof identity.defaultRuntime === 'object'
? identity.defaultRuntime
: undefined
},
delegation: delegation
? {
controllerWallet: normalizeWallet(delegation.controllerWallet) || asString(delegation.controllerWallet),
allowedActions,
deniedActions,
runtimePolicy: delegation.runtimePolicy,
approvalPolicy: approvalPolicy || undefined,
expiresAt: delegation.expiresAt ?? null,
isExpired: Boolean(delegation.isExpired),
maxSpend: delegation.maxSpend,
instructions: asString(delegation.instructions) || undefined,
provider: asString(delegation.provider) || undefined,
model: asString(delegation.model) || undefined
}
: null,
effectiveRuntime,
tools,
resources,
secretBindings,
memoryRefs: Array.isArray(input.memoryRefs) ? input.memoryRefs : undefined,
enforce: {
deniedActions,
...(delegation ? { allowedActions } : {}),
...(requiresHumanApproval ? { requiresHumanApproval: true } : {}),
...(approvalPolicy ? { approvalPolicy } : {})
},
contextPack: {
identityCount: 1,
delegationCount: delegations.length,
activeDelegations,
capabilitiesSummary: capabilities.slice(0, 32),
skillsSummary: skillIds.slice(0, 32)
}
};
}
/**
* @param {Record<string, unknown>} profileAgent
*/
export function profileAgentToIdentitySeed(profileAgent) {
return {
qHash: normalizeQHash(profileAgent.identityQHash || profileAgent.qHash) || null,
agentId: profileAgent.agentId,
agentWallet: profileAgent.agentWallet,
agentLabel: profileAgent.agentLabel || profileAgent.name,
agentType: profileAgent.agentType || profileAgent.typeLabel,
description: profileAgent.description,
instructions: profileAgent.instructions,
capabilities: capabilitiesToArray(profileAgent.capabilities),
skills: Array.isArray(profileAgent.skills) ? profileAgent.skills : [],
services: Array.isArray(profileAgent.services) ? profileAgent.services : []
};
}
/**
* @param {import('./runtime-mount.js').RuntimeBundle | Record<string, unknown>} value
*/
export function isRuntimeBundle(value) {
return Boolean(value && typeof value === 'object' && value.schema === RUNTIME_MOUNT_SCHEMA);
}
/**
* Resolve mount via MCP (server tool first, then client assembly).
*
* @param {{
* callMcpTool: (args: { name: string, args?: Record<string, unknown>, accessKey?: string, sessionId?: string, signal?: AbortSignal }) => Promise<{ ok: boolean, payload?: unknown, error?: string }>,
* initializeMcp?: () => Promise<{ sessionId: string }>,
* accessKey: string,
* agentId?: string,
* agentWallet?: string,
* identityQHash?: string,
* signal?: AbortSignal
* }} input
*/
export async function resolveRuntimeBundleFromMcp(input) {
const accessKey = asString(input.accessKey);
if (!accessKey) {
throw new Error('Sign in to Proofable or configure an access key before connecting agent context.');
}
const selector = {
agentId: input.agentId,
agentWallet: input.agentWallet,
identityQHash: normalizeQHash(input.identityQHash) || undefined
};
if (!selector.agentId && !selector.agentWallet && !selector.identityQHash) {
throw new Error('Provide agentId, agentWallet, or identityQHash.');
}
let sessionId = '';
if (input.initializeMcp) {
const init = await input.initializeMcp();
sessionId = init.sessionId || '';
}
const mountArgs = {
...(selector.agentId ? { agentId: selector.agentId } : {}),
...(selector.agentWallet ? { agentWallet: selector.agentWallet } : {}),
...(selector.identityQHash ? { identityQHash: selector.identityQHash } : {})
};
const serverMount = await input.callMcpTool({
name: 'proofable_agent_mount',
args: mountArgs,
accessKey,
sessionId,
signal: input.signal
});
if (serverMount.ok) {
const payload = serverMount.payload;
if (isRuntimeBundle(payload)) {
return /** @type {import('./runtime-mount.js').RuntimeBundle} */ (payload);
}
if (payload && typeof payload === 'object' && isRuntimeBundle(payload.data)) {
return /** @type {import('./runtime-mount.js').RuntimeBundle} */ (payload.data);
}
}
const ctx = await input.callMcpTool({
name: 'proofable_context',
args: {},
accessKey,
sessionId,
signal: input.signal
});
if (!ctx.ok) {
throw new Error(ctx.error || 'Could not load profile context. Run `proofable auth --oauth` or set PROOFABLE_ACCESS_KEY and retry.');
}
const ctxPayload = /** @type {Record<string, unknown>} */ (ctx.payload || {});
const profileContext =
ctxPayload.profileContext && typeof ctxPayload.profileContext === 'object'
? /** @type {Record<string, unknown>} */ (ctxPayload.profileContext)
: ctxPayload;
if (profileContext.status === 'auth_required') {
throw new Error('Profile authentication required. Run `proofable auth --oauth` or set PROOFABLE_ACCESS_KEY.');
}
const principal = /** @type {Record<string, unknown>} */ (profileContext.principal || {});
const controllerWallet = normalizeWallet(principal.primaryAccount);
const profileAgents = Array.isArray(profileContext.agents) ? profileContext.agents : [];
let agentWallet = normalizeWallet(selector.agentWallet);
let agentId = asString(selector.agentId);
if (!agentWallet && agentId) {
const row = profileAgents.find(
row => asString(row.agentId).toLowerCase() === agentId.toLowerCase()
);
if (row) {
agentWallet = normalizeWallet(row.agentWallet);
}
}
if (!agentId && agentWallet) {
const row = profileAgents.find(row => normalizeWallet(row.agentWallet) === agentWallet);
if (row) agentId = asString(row.agentId);
}
if (!agentWallet && selector.identityQHash) {
const idProof = await input.callMcpTool({
name: 'proofable_proofs_get',
args: {
qHash: selector.identityQHash,
verifierId: 'agent-identity',
include: 'content'
},
accessKey,
sessionId,
signal: input.signal
});
if (idProof.ok) {
const data = /** @type {Record<string, unknown>} */ (idProof.payload?.data || idProof.payload || {});
const proofs = Array.isArray(data.proofs) ? data.proofs : [];
const extracted = extractAgentContextFromProofs(proofs);
const identity = pickIdentity(extracted.identities, selector);
if (identity) {
agentWallet = normalizeWallet(identity.agentWallet);
agentId = asString(identity.agentId);
}
}
}
if (!agentWallet) {
throw new Error('Could not resolve agent wallet. Check agentId or link the agent on your profile.');
}
const [identityPage, delegationPage] = await Promise.all([
input.callMcpTool({
name: 'proofable_proofs_get',
args: {
identifier: agentWallet,
verifierId: 'agent-identity',
limit: 25,
include: 'content'
},
accessKey,
sessionId,
signal: input.signal
}),
controllerWallet
? input.callMcpTool({
name: 'proofable_proofs_get',
args: {
identifier: controllerWallet,
verifierId: 'agent-delegation',
limit: 50,
include: 'content'
},
accessKey,
sessionId,
signal: input.signal
})
: Promise.resolve({ ok: false })
]);
const identityProofs = identityPage.ok
? /** @type {unknown[]} */ (
identityPage.payload?.data?.proofs || identityPage.payload?.proofs || []
)
: [];
const delegationProofs = delegationPage.ok
? /** @type {unknown[]} */ (
delegationPage.payload?.data?.proofs || delegationPage.payload?.proofs || []
)
: [];
const idCtx = extractAgentContextFromProofs(identityProofs);
const delCtx = extractAgentContextFromProofs(delegationProofs);
let identity = pickIdentity(idCtx.identities, { ...selector, agentId, agentWallet });
if (!identity && profileAgents.length > 0) {
const row = profileAgents.find(
a =>
asString(a.agentId).toLowerCase() === agentId.toLowerCase() ||
normalizeWallet(a.agentWallet) === agentWallet
);
if (row) {
identity = { ...profileAgentToIdentitySeed(row), agentWallet, agentId: agentId || asString(row.agentId) };
}
}
if (!identity) {
throw new Error('Agent identity proof not found. Complete agent setup on proofable.me first.');
}
const delegation = pickActiveDelegation(
delCtx.delegations,
controllerWallet,
agentWallet,
agentId || asString(identity.agentId)
);
return buildRuntimeBundle({
identity,
delegation,
controllerWallet,
identityQHash: asString(identity.qHash || selector.identityQHash),
delegationQHash: delegation ? asString(delegation.qHash) : null,
tools: [],
secretBindings: []
});
}
/**
* @param {import('./runtime-mount.js').RuntimeBundle | Record<string, unknown> | null | undefined} manifest
*/
export function evaluateMountFileHealth(manifest) {
if (!manifest || manifest.schema !== RUNTIME_MOUNT_SCHEMA) {
return {
mountFileValid: false,
missingDelegation: true,
delegationExpired: false,
needsRefresh: true,
reason: 'missing_or_invalid'
};
}
const delegationQHash = asString(manifest.trust?.delegationQHash);
const controllerControlled = manifest.authority?.mode === 'controller';
const missingDelegation = !controllerControlled && !delegationQHash;
const expiresAt = manifest.delegation?.expiresAt;
const delegationExpired =
Boolean(manifest.delegation?.isExpired) || isDelegationExpired(expiresAt);
return {
mountFileValid: true,
missingDelegation,
delegationExpired,
needsRefresh: missingDelegation || delegationExpired,
reason: delegationExpired
? 'delegation_expired'
: missingDelegation
? 'delegation_missing'
: null
};
}
/**
* Evaluate one host action against the current runtime-mount permission bundle.
* Denies when identity or permission state is missing or expired. A denied action
* always wins; delegated authority requires an explicit, non-empty allowlist.
*
* @param {import('./runtime-mount.js').RuntimeMountBundle | Record<string, unknown> | null | undefined} bundle
* @param {string} action
* @param {{ irreversible?: boolean }} [options]
*/
export function evaluateRuntimeAction(bundle, action, options = {}) {
const normalizedAction = asString(action).toLowerCase();
const deny = (code, message) => ({
decision: 'denied',
allowed: false,
action: normalizedAction,
code,
message
});
if (!normalizedAction) {
return deny('ACTION_REQUIRED', 'Provide the action before evaluating permissions.');
}
if (!isRuntimeBundle(bundle)) {
return deny('MOUNT_REQUIRED', 'Load current agent identity and permissions before this action.');
}
const health = evaluateMountFileHealth(bundle);
if (health.delegationExpired) {
return deny('PERMISSION_EXPIRED', 'The agent permission proof has expired.');
}
if (health.missingDelegation) {
return deny('PERMISSION_REQUIRED', 'No current agent permission proof is mounted.');
}
const deniedActions = asStringArray(bundle.enforce?.deniedActions).map(value => value.toLowerCase());
if (deniedActions.includes(normalizedAction)) {
return deny('ACTION_DENIED', `The current permission proof denies ${normalizedAction}.`);
}
const allowedActions = asStringArray(bundle.enforce?.allowedActions).map(value => value.toLowerCase());
if (bundle.authority?.mode === 'delegated' && allowedActions.length === 0) {
return deny('ACTION_NOT_ALLOWED', `The current permission proof does not allow ${normalizedAction}.`);
}
if (allowedActions.length > 0 && !allowedActions.includes(normalizedAction)) {
return deny('ACTION_NOT_ALLOWED', `The current permission proof does not allow ${normalizedAction}.`);
}
if (options.irreversible === true && bundle.enforce?.requiresHumanApproval === true) {
return {
decision: 'approval_required',
allowed: false,
action: normalizedAction,
code: 'HUMAN_APPROVAL_REQUIRED',
message: `Confirm human approval before ${normalizedAction}.`
};
}
return {
decision: 'allowed',
allowed: true,
action: normalizedAction,
code: 'ACTION_ALLOWED',
message: `The current permission proof allows ${normalizedAction}.`
};
}
/**
* Build a runtime mount bundle from a roster (identities + delegations extracted from proofs).
* Non-throwing: returns { error, message } when identity is missing or the bundle cannot be built.
* Selector picks the identity by agentId / agentWallet / identityQHash, then resolves the active
* delegation from the roster. Used by hosted MCP and product app consumers.
*
* @param {{ identities?: Array<Record<string, unknown>>, delegations?: Array<Record<string, unknown>> }} roster
* @param {{ agentId?: string, agentWallet?: string, identityQHash?: string }} selector
* @param {string} controllerWallet
*/
export function buildRuntimeMountFromRoster(roster, selector, controllerWallet, mountContext = {}) {
const identities = Array.isArray(roster?.identities) ? roster.identities : [];
const delegations = Array.isArray(roster?.delegations) ? roster.delegations : [];
const identity = pickIdentity(identities, selector);
if (!identity) {
return {
error: 'identity_not_found',
message: 'No agent-identity proof matches the requested agent.'
};
}
const agentWallet = normalizeWallet(identity.agentWallet);
const agentId = asString(identity.agentId);
const normalizedControllerWallet = normalizeWallet(controllerWallet);
const delegation = pickActiveDelegation(
delegations,
normalizedControllerWallet,
agentWallet,
agentId
);
try {
return buildRuntimeBundle({
identity,
delegation,
controllerWallet: normalizedControllerWallet,
identityQHash: asString(identity.qHash || selector.identityQHash),
delegationQHash: delegation ? asString(delegation.qHash) : null,
tools: mountContext.tools,
resources: mountContext.resources,
secretBindings: mountContext.secretBindings
});
} catch (err) {
return {
error: 'mount_incomplete',
message: err && err.message ? err.message : 'Runtime mount bundle could not be built.'
};
}
}