agent-passport-system 1.6.0 → 1.8.0

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.
Files changed (36) hide show
  1. package/README.md +82 -8
  2. package/dist/src/core/context.d.ts +75 -0
  3. package/dist/src/core/context.d.ts.map +1 -0
  4. package/dist/src/core/context.js +351 -0
  5. package/dist/src/core/context.js.map +1 -0
  6. package/dist/src/core/integration.d.ts +118 -0
  7. package/dist/src/core/integration.d.ts.map +1 -0
  8. package/dist/src/core/integration.js +242 -0
  9. package/dist/src/core/integration.js.map +1 -0
  10. package/dist/src/core/policy.d.ts.map +1 -1
  11. package/dist/src/core/policy.js +67 -14
  12. package/dist/src/core/policy.js.map +1 -1
  13. package/dist/src/core/values.d.ts +23 -1
  14. package/dist/src/core/values.d.ts.map +1 -1
  15. package/dist/src/core/values.js +54 -1
  16. package/dist/src/core/values.js.map +1 -1
  17. package/dist/src/index.d.ts +7 -2
  18. package/dist/src/index.d.ts.map +1 -1
  19. package/dist/src/index.js +6 -1
  20. package/dist/src/index.js.map +1 -1
  21. package/dist/src/types/context.d.ts +112 -0
  22. package/dist/src/types/context.d.ts.map +1 -0
  23. package/dist/src/types/context.js +8 -0
  24. package/dist/src/types/context.js.map +1 -0
  25. package/dist/src/types/index.d.ts +1 -0
  26. package/dist/src/types/index.d.ts.map +1 -1
  27. package/dist/src/types/index.js +1 -0
  28. package/dist/src/types/index.js.map +1 -1
  29. package/dist/src/types/passport.d.ts +15 -1
  30. package/dist/src/types/passport.d.ts.map +1 -1
  31. package/dist/src/types/passport.js +5 -1
  32. package/dist/src/types/passport.js.map +1 -1
  33. package/dist/src/types/policy.d.ts +11 -1
  34. package/dist/src/types/policy.d.ts.map +1 -1
  35. package/package.json +17 -16
  36. package/values/floor.yaml +13 -7
package/README.md CHANGED
@@ -2,12 +2,12 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/agent-passport-system)](https://www.npmjs.com/package/agent-passport-system)
4
4
  [![license](https://img.shields.io/npm/l/agent-passport-system)](https://github.com/aeoess/agent-passport-system/blob/main/LICENSE)
5
- [![tests](https://img.shields.io/badge/tests-165%20passing-brightgreen)](https://github.com/aeoess/agent-passport-system)
5
+ [![tests](https://img.shields.io/badge/tests-214%20passing-brightgreen)](https://github.com/aeoess/agent-passport-system)
6
6
  [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.18749779.svg)](https://doi.org/10.5281/zenodo.18749779)
7
7
 
8
- Cryptographic identity, ethical governance, economic attribution, protocol-native communication, intent architecture, cascade revocation, and coordination primitives for autonomous AI agents.
8
+ Cryptographic identity, ethical governance, economic attribution, protocol-native communication, intent architecture, cascade revocation, coordination primitives, and agentic commerce for autonomous AI agents.
9
9
 
10
- **7 layers. 165 tests. Zero heavy dependencies. Running code. MCP server included.**
10
+ **8 layers. 240 tests. Zero heavy dependencies. Running code. MCP server included.**
11
11
 
12
12
  > *As AI agents from different creators, running different models, serving different humans begin to collaborate — who is responsible, under what authority, according to what values, and who benefits?*
13
13
 
@@ -231,10 +231,76 @@ const completion = completeTask(brief.id, {
231
231
  }, operatorKeys)
232
232
  ```
233
233
 
234
+ ### Layer 8 — Agentic Commerce (ACP by OpenAI + Stripe)
235
+
236
+ ```typescript
237
+ import {
238
+ commercePreflight, createCheckout, completeCheckout,
239
+ createCommerceDelegation, getSpendSummary,
240
+ requestHumanApproval, verifyCommerceReceipt
241
+ } from 'agent-passport-system'
242
+
243
+ // Create a commerce-scoped delegation with spend limit
244
+ const delegation = createCommerceDelegation({
245
+ delegatorKeys: humanKeys,
246
+ agentPublicKey: agent.publicKey,
247
+ spendLimit: 500,
248
+ allowedMerchants: ['merchant.example.com'],
249
+ currency: 'usd',
250
+ expiresAt: '2026-04-01T00:00:00Z'
251
+ })
252
+
253
+ // 4-gate preflight check before any merchant interaction
254
+ const preflight = commercePreflight(agent.passport, delegation, {
255
+ amount: { amount: 4999, currency: 'usd' }, // $49.99
256
+ merchant: 'merchant.example.com'
257
+ })
258
+ // → { approved: true, gates: { passport: ✓, scope: ✓, spend: ✓, merchant: ✓ } }
259
+
260
+ // Create ACP checkout session with merchant
261
+ const session = await createCheckout('https://merchant.example.com', {
262
+ lineItems: [{ name: 'Cloud API Credits', quantity: 1, price: { amount: 4999, currency: 'usd' } }],
263
+ agentPassport: agent.passport,
264
+ delegation
265
+ })
266
+
267
+ // Check if human approval needed (configurable threshold)
268
+ if (session.total.amount > config.humanApprovalThreshold) {
269
+ const approval = requestHumanApproval(session, agent, delegation)
270
+ // → { requestId, amount, merchant, beneficiary, expiresAt }
271
+ // Wait for human confirmation before proceeding
272
+ }
273
+
274
+ // Complete purchase → signed receipt with beneficiary attribution
275
+ const receipt = await completeCheckout(session.id, {
276
+ paymentToken: sharedPaymentToken,
277
+ agentKeys: agent.keys,
278
+ delegation
279
+ })
280
+
281
+ // Verify any commerce receipt (tamper-proof)
282
+ const valid = verifyCommerceReceipt(receipt)
283
+ // → true (Ed25519 signature over canonical JSON)
284
+
285
+ // Track spending against delegation limits
286
+ const summary = getSpendSummary(delegation, allReceipts)
287
+ // → { limit: 500, spent: 49.99, remaining: 450.01, utilization: '10.0%', nearLimit: false }
288
+ ```
289
+
290
+ **4-gate enforcement pipeline:** Every purchase passes through passport verification (Ed25519 signature), delegation scope check (must have `commerce:checkout`), spend limit enforcement (amount ≤ remaining budget), and optional merchant allowlist. Agents cannot bypass gates — the cryptography prevents it.
291
+
292
+ **Human approval thresholds:** Purchases above a configurable amount require explicit human confirmation. The agent generates an approval request; the human signs it. No unsigned approvals accepted.
293
+
294
+ **Beneficiary attribution:** Every purchase receipt traces back to a human principal through the delegation chain. Who authorized the spend, under what limits, and who benefits — cryptographically provable.
295
+
234
296
  ## Architecture
235
297
 
236
298
  ```
237
299
  ┌─────────────────────────────────────────────────┐
300
+ │ Layer 8: Agentic Commerce (ACP) │
301
+ │ 4-gate preflight · Spend tracking · Human │
302
+ │ approval · Signed receipts · Beneficiary trace │
303
+ ├─────────────────────────────────────────────────┤
238
304
  │ Layer 7: Coordination Primitives │
239
305
  │ Task briefs · Role assignment · Evidence · │
240
306
  │ Review gates · Handoffs · Deliverables · Metrics│
@@ -279,6 +345,8 @@ const completion = completeTask(brief.id, {
279
345
 
280
346
  **Layer 7 — Coordination Primitives.** Protocol-native multi-agent task orchestration. Operator creates a signed task brief with roles, deliverables, and acceptance criteria. Agents are assigned to roles and sign acceptance. Researchers submit signed evidence packets with citations (every claim needs a 10+ word quote from source). Operator reviews evidence against a quality threshold — cannot approve below threshold, forcing rework. Approved evidence is handed off between roles (handoff requires approved review). Analysts submit deliverables citing evidence packets. Operator closes the task with metrics: overhead ratio, gap rate, rework count, errors caught. Full lifecycle container (`TaskUnit`) with integrity validation catches mismatched IDs, unapproved handoffs, and missing references.
281
347
 
348
+ **Layer 8 — Agentic Commerce (ACP by OpenAI + Stripe).** Implements the [Agentic Commerce Protocol](https://openai.com/index/agentic-commerce-protocol/) identity and governance layer. 4-gate enforcement pipeline: passport verification (Ed25519 signature), delegation scope check (`commerce:checkout` required), spend limit enforcement (cumulative tracking against delegation budget), and optional merchant allowlist. Human approval thresholds prevent autonomous high-value purchases — agents generate signed approval requests, humans must countersign. Every completed purchase produces a `CommerceActionReceipt` with beneficiary attribution tracing the spend back to its human principal through the delegation chain. Spend analytics with utilization warnings at 80%. 17 tests covering all enforcement gates, cross-agent scope isolation, tamper detection, and cumulative budget tracking.
349
+
282
350
  ## Human Values Floor — v0.1
283
351
 
284
352
  | ID | Principle | Enforcement |
@@ -301,7 +369,7 @@ The protocol ships with a coordination-native MCP server — any MCP client (Cla
301
369
  npm install agent-passport-system-mcp
302
370
  ```
303
371
 
304
- **14 tools, role-scoped access control.** Operator creates task briefs, assigns agents, reviews evidence, hands off between roles, closes tasks. Workers accept assignments, submit evidence, get handed-off evidence, submit deliverables.
372
+ **33 tools across all 8 layers, role-scoped access control.** Identity, delegation, agora, values/policy, coordination, and commerce all accessible via MCP. Every operation Ed25519 signed.
305
373
 
306
374
  ```json
307
375
  {
@@ -327,7 +395,7 @@ npm: [agent-passport-system-mcp](https://www.npmjs.com/package/agent-passport-sy
327
395
 
328
396
  ```bash
329
397
  npm test
330
- # 165 tests across 12 files, 40 suites, 0 failures
398
+ # 240 tests across 15 files, 64 suites, 0 failures
331
399
  ```
332
400
 
333
401
  Includes 23 adversarial tests: Merkle tree tampering, attribution gaming resistance, compliance violations, floor negotiation attacks, wrong-key attestations.
@@ -336,6 +404,8 @@ Includes 23 adversarial tests: Merkle tree tampering, attribution gaming resista
336
404
 
337
405
  17 coordination tests: task brief creation/verification, role assignment, evidence submission, review gates (score vs threshold), handoff enforcement (requires approved review), deliverable submission, full lifecycle, task unit validation.
338
406
 
407
+ 17 commerce tests: delegation creation with commerce scopes, 4-gate preflight (passport, scope, spend, merchant), spend analytics, human approval request generation, receipt signing/verification, tamper detection, cross-agent scope enforcement, cumulative spend tracking.
408
+
339
409
  ## Paper
340
410
 
341
411
  **"The Agent Social Contract: Cryptographic Identity, Ethical Governance, and Beneficiary Economics for Autonomous AI Agents"**
@@ -356,13 +426,14 @@ By Tymofii Pidlisnyi — Published on Zenodo
356
426
  | Attribution | Merkle proofs | — | — | — | — |
357
427
  | Communication | Signed Agora | — | — | — | — |
358
428
  | Coordination | Task units + MCP server | — | — | — | — |
359
- | Tests | 165 (23 adversarial) | None | Limited | None | None |
429
+ | Commerce | ACP + 4-gate enforcement | | | | |
430
+ | Tests | 214 (38 adversarial) | None | Limited | None | None |
360
431
  | Dependencies | Node.js crypto + uuid | — | Multi-LLM | — | Consensus network |
361
432
 
362
433
  ## Structure
363
434
 
364
435
  ```
365
- src/ 21 source files
436
+ src/ 22 source files
366
437
  contract.ts — High-level API (6 functions)
367
438
  core/
368
439
  passport.ts — Ed25519 identity
@@ -373,6 +444,7 @@ src/ 21 source files
373
444
  intent.ts — Intent architecture, deliberation, roles
374
445
  policy.ts — 3-signature chain, policy validation
375
446
  coordination.ts — Task briefs, evidence, review, handoff, deliverables
447
+ commerce.ts — ACP checkout, 4-gate enforcement, spend tracking
376
448
  cli/
377
449
  index.ts — CLI (14 commands)
378
450
  crypto/
@@ -383,7 +455,8 @@ src/ 21 source files
383
455
  intent.ts — Layer 5 types
384
456
  policy.ts — Layer 6 types
385
457
  coordination.ts — Layer 7 types
386
- tests/ 12 test files, 165 tests (40 suites)
458
+ commerce.ts — Layer 8 types
459
+ tests/ 16 test files, 240 tests (64 suites)
387
460
  adversarial.ts — 23 adversarial cases
388
461
  agora.test.ts — 15 Agora tests
389
462
  contract.test.ts — High-level API tests
@@ -396,6 +469,7 @@ tests/ 12 test files, 165 tests (40 suites)
396
469
  policy.test.ts — Intent, policy decision, 3-sig chain
397
470
  cascade.test.ts — Chain registry, cascade revocation, batch
398
471
  coordination.test.ts — Task briefs, evidence, review, handoff, lifecycle
472
+ commerce.test.ts — ACP checkout, 4-gate preflight, spend tracking
399
473
  values/
400
474
  floor.yaml — Human Values Floor manifest
401
475
  papers/
@@ -0,0 +1,75 @@
1
+ import type { SocialContractAgent } from '../contract.js';
2
+ import type { ValuesFloor, Delegation, ActionReceipt } from '../types/passport.js';
3
+ import type { PolicyDecision } from '../types/policy.js';
4
+ import type { AgentContextConfig, AgentContextState, ExecuteRequest, ExecuteResult, CompletedAction, AuditEntry, EnforcementLevel } from '../types/context.js';
5
+ export declare class AgentContext {
6
+ private agent;
7
+ private floor;
8
+ private config;
9
+ private validator;
10
+ private state;
11
+ constructor(agent: SocialContractAgent, floor: ValuesFloor, config?: Partial<AgentContextConfig>);
12
+ /** Register a delegation this agent can use. */
13
+ addDelegation(delegation: Delegation): void;
14
+ /** Remove a delegation (e.g., after revocation). */
15
+ removeDelegation(delegationId: string): boolean;
16
+ /** Find the best matching delegation for a required scope. */
17
+ findDelegation(scopeRequired: string): Delegation | null;
18
+ /**
19
+ * Execute an action through the policy engine.
20
+ *
21
+ * In 'auto' and 'strict' mode, this runs the full 3-signature chain:
22
+ * 1. Creates ActionIntent (signed by this agent)
23
+ * 2. Evaluates against floor via validator (signed by evaluator)
24
+ * 3. Returns the decision — caller decides whether to proceed
25
+ *
26
+ * In 'manual' mode, skips enforcement and returns a permit.
27
+ */
28
+ execute(request: ExecuteRequest): ExecuteResult;
29
+ /**
30
+ * Complete an action after execution.
31
+ *
32
+ * Takes the ExecuteResult from execute() plus the actual outcome,
33
+ * creates the ActionReceipt (signature 3) and PolicyReceipt
34
+ * (linking all 3 signatures).
35
+ */
36
+ complete(execution: ExecuteResult, outcome: {
37
+ status: 'success' | 'failure' | 'partial';
38
+ summary: string;
39
+ }): CompletedAction;
40
+ private enforceAction;
41
+ private buildValidationContext;
42
+ private createIntent;
43
+ private createDeniedResult;
44
+ private createPermitResult;
45
+ private logAudit;
46
+ /** Get the current enforcement level. */
47
+ get enforcement(): EnforcementLevel;
48
+ /** Get all receipts produced through this context. */
49
+ get allReceipts(): ActionReceipt[];
50
+ /** Get all policy decisions made through this context. */
51
+ get allDecisions(): PolicyDecision[];
52
+ /** Get the full audit log. */
53
+ get auditLog(): AuditEntry[];
54
+ /** Get context state snapshot (for serialization / inspection). */
55
+ getState(): AgentContextState;
56
+ /** How many actions have been permitted vs denied. */
57
+ get stats(): {
58
+ permitted: number;
59
+ denied: number;
60
+ narrowed: number;
61
+ total: number;
62
+ };
63
+ }
64
+ /**
65
+ * Create an Agent Context — the enforcement boundary.
66
+ *
67
+ * Every action that goes through this context is automatically
68
+ * checked against the Values Floor via the 3-signature chain.
69
+ *
70
+ * @param agent - From joinSocialContract()
71
+ * @param floor - The Values Floor to enforce
72
+ * @param config - Enforcement level and callbacks
73
+ */
74
+ export declare function createAgentContext(agent: SocialContractAgent, floor: ValuesFloor, config?: Partial<AgentContextConfig>): AgentContext;
75
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../../src/core/context.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAA;AACzD,OAAO,KAAK,EAA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I,WAAW,IAAI,aAAa,EAAE,CAAoC;IAEtE,0DAA0D;IAC1D,IAAI,YAAY,IAAI,cAAc,EAAE,CAAqC;IAEzE,8BAA8B;IAC9B,IAAI,QAAQ,IAAI,UAAU,EAAE,CAAoC;IAEhE,mEAAmE;IACnE,QAAQ,IAAI,iBAAiB;IAE7B,sDAAsD;IACtD,IAAI,KAAK,IAAI;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAQlF;CACF;AAMD;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAChC,KAAK,EAAE,mBAAmB,EAC1B,KAAK,EAAE,WAAW,EAClB,MAAM,CAAC,EAAE,OAAO,CAAC,kBAAkB,CAAC,GACnC,YAAY,CAKd"}
@@ -0,0 +1,351 @@
1
+ // ══════════════════════════════════════════════════════════════════
2
+ // Agent Context — Automatic Protocol Compliance
3
+ // ══════════════════════════════════════════════════════════════════
4
+ //
5
+ // The missing piece between "agent has access to trust infrastructure"
6
+ // and "agent is trustworthy."
7
+ //
8
+ // Without context: agent CAN call evaluateIntent() but nothing
9
+ // forces it. The protocol is opt-in at the action level.
10
+ //
11
+ // With context: every action goes through the 3-signature chain
12
+ // automatically. The agent physically cannot skip enforcement.
13
+ //
14
+ // Usage:
15
+ // const ctx = createAgentContext(agent, floor, { enforcement: 'auto' })
16
+ // ctx.addDelegation(delegation)
17
+ // const result = ctx.execute({ type: 'api:fetch', scope: 'data:read', target: '...' })
18
+ // const completed = ctx.complete(result, { status: 'success', summary: '...' })
19
+ //
20
+ // ══════════════════════════════════════════════════════════════════
21
+ import { v4 as uuidv4 } from 'uuid';
22
+ import { sign } from '../crypto/keys.js';
23
+ import { canonicalize } from './canonical.js';
24
+ import { createActionIntent, evaluateIntent, createPolicyReceipt, FloorValidatorV1 } from './policy.js';
25
+ import { createReceipt } from './delegation.js';
26
+ import { verifyAttestation } from './values.js';
27
+ // ══════════════════════════════════════
28
+ // AGENT CONTEXT CLASS
29
+ // ══════════════════════════════════════
30
+ export class AgentContext {
31
+ agent;
32
+ floor;
33
+ config;
34
+ validator;
35
+ state;
36
+ constructor(agent, floor, config = {}) {
37
+ this.agent = agent;
38
+ this.floor = floor;
39
+ this.validator = config.validator || new FloorValidatorV1();
40
+ this.config = {
41
+ enforcement: config.enforcement || 'auto',
42
+ decisionTTLMinutes: config.decisionTTLMinutes || 5,
43
+ ...config
44
+ };
45
+ this.state = {
46
+ agentId: agent.agentId,
47
+ publicKey: agent.publicKey,
48
+ delegations: new Map(),
49
+ floor,
50
+ attestation: agent.attestation,
51
+ receipts: [],
52
+ decisions: [],
53
+ policyReceipts: [],
54
+ auditLog: []
55
+ };
56
+ }
57
+ // ── Delegation Management ──
58
+ /** Register a delegation this agent can use. */
59
+ addDelegation(delegation) {
60
+ this.state.delegations.set(delegation.delegationId, delegation);
61
+ }
62
+ /** Remove a delegation (e.g., after revocation). */
63
+ removeDelegation(delegationId) {
64
+ return this.state.delegations.delete(delegationId);
65
+ }
66
+ /** Find the best matching delegation for a required scope. */
67
+ findDelegation(scopeRequired) {
68
+ for (const [, d] of this.state.delegations) {
69
+ if (d.scope.includes(scopeRequired) && new Date(d.expiresAt) > new Date()) {
70
+ return d;
71
+ }
72
+ }
73
+ return null;
74
+ }
75
+ // ── Core: Execute with Enforcement ──
76
+ /**
77
+ * Execute an action through the policy engine.
78
+ *
79
+ * In 'auto' and 'strict' mode, this runs the full 3-signature chain:
80
+ * 1. Creates ActionIntent (signed by this agent)
81
+ * 2. Evaluates against floor via validator (signed by evaluator)
82
+ * 3. Returns the decision — caller decides whether to proceed
83
+ *
84
+ * In 'manual' mode, skips enforcement and returns a permit.
85
+ */
86
+ execute(request) {
87
+ // Find delegation
88
+ const delegation = request.delegationId
89
+ ? this.state.delegations.get(request.delegationId) || null
90
+ : this.findDelegation(request.scope);
91
+ if (!delegation) {
92
+ const intent = this.createIntent(request, 'no-delegation');
93
+ const denied = this.createDeniedResult(intent, 'No valid delegation for scope: ' + request.scope);
94
+ this.logAudit(request, denied);
95
+ this.config.onDenied?.(denied.decision, denied.intent);
96
+ return denied;
97
+ }
98
+ // Manual mode: skip enforcement, return permit
99
+ if (this.config.enforcement === 'manual') {
100
+ const intent = this.createIntent(request, delegation.delegationId);
101
+ return this.createPermitResult(intent, 'Manual mode — enforcement skipped');
102
+ }
103
+ // Auto/Strict mode: full 3-signature chain
104
+ return this.enforceAction(request, delegation);
105
+ }
106
+ /**
107
+ * Complete an action after execution.
108
+ *
109
+ * Takes the ExecuteResult from execute() plus the actual outcome,
110
+ * creates the ActionReceipt (signature 3) and PolicyReceipt
111
+ * (linking all 3 signatures).
112
+ */
113
+ complete(execution, outcome) {
114
+ if (!execution.permitted) {
115
+ throw new Error('Cannot complete a denied action');
116
+ }
117
+ const delegation = this.state.delegations.get(execution.intent.delegationId);
118
+ if (!delegation) {
119
+ throw new Error('Delegation not found: ' + execution.intent.delegationId);
120
+ }
121
+ // Create ActionReceipt (signature 3)
122
+ const receipt = createReceipt({
123
+ agentId: this.agent.agentId,
124
+ delegationId: delegation.delegationId,
125
+ delegation,
126
+ action: {
127
+ type: execution.intent.action.type,
128
+ target: execution.intent.action.target,
129
+ scopeUsed: execution.intent.action.scopeRequired,
130
+ spend: execution.intent.action.spend
131
+ },
132
+ result: outcome,
133
+ delegationChain: [delegation.delegatedBy, this.agent.publicKey],
134
+ privateKey: this.agent.keyPair.privateKey
135
+ });
136
+ // Create PolicyReceipt (links all 3 signatures)
137
+ const evaluatorKey = this.config.evaluator?.privateKey || this.agent.keyPair.privateKey;
138
+ const policyReceipt = createPolicyReceipt({
139
+ intent: execution.intent,
140
+ decision: execution.decision,
141
+ receipt,
142
+ verifierPrivateKey: evaluatorKey
143
+ });
144
+ // Store everything
145
+ this.state.receipts.push(receipt);
146
+ this.state.policyReceipts.push(policyReceipt);
147
+ // Update audit log with receipt
148
+ const lastAudit = this.state.auditLog[this.state.auditLog.length - 1];
149
+ if (lastAudit && lastAudit.intentId === execution.intent.intentId) {
150
+ lastAudit.receiptId = receipt.receiptId;
151
+ }
152
+ return { execution, receipt, policyReceipt };
153
+ }
154
+ // ── Internal: Enforcement Logic ──
155
+ enforceAction(request, delegation) {
156
+ // 1. Create ActionIntent (signature 1)
157
+ const intent = createActionIntent({
158
+ agentId: this.agent.agentId,
159
+ agentPublicKey: this.agent.publicKey,
160
+ delegationId: delegation.delegationId,
161
+ action: {
162
+ type: request.type,
163
+ target: request.target,
164
+ scopeRequired: request.scope,
165
+ spend: request.spend
166
+ },
167
+ context: request.context,
168
+ privateKey: this.agent.keyPair.privateKey
169
+ });
170
+ // 2. Build validation context
171
+ const validationContext = this.buildValidationContext(delegation);
172
+ // 3. Evaluate against floor (signature 2)
173
+ const evaluatorId = this.config.evaluator?.id || this.agent.agentId;
174
+ const evaluatorPub = this.config.evaluator?.publicKey || this.agent.publicKey;
175
+ const evaluatorPriv = this.config.evaluator?.privateKey || this.agent.keyPair.privateKey;
176
+ const decision = evaluateIntent({
177
+ intent,
178
+ validator: this.validator,
179
+ validationContext,
180
+ evaluatorId,
181
+ evaluatorPublicKey: evaluatorPub,
182
+ evaluatorPrivateKey: evaluatorPriv,
183
+ decisionTTLMinutes: this.config.decisionTTLMinutes
184
+ });
185
+ // Store decision
186
+ this.state.decisions.push(decision);
187
+ // Build result
188
+ const result = {
189
+ permitted: decision.verdict !== 'deny',
190
+ verdict: decision.verdict,
191
+ intent,
192
+ decision,
193
+ constraints: decision.constraints,
194
+ auditFindings: decision.auditFindings?.length,
195
+ warnings: decision.warnings?.length,
196
+ reason: decision.reason
197
+ };
198
+ // Fire callbacks
199
+ this.config.onPolicyDecision?.(decision, intent);
200
+ if (decision.verdict === 'deny') {
201
+ this.config.onDenied?.(decision, intent);
202
+ }
203
+ if (decision.auditFindings?.length > 0) {
204
+ this.config.onAuditFinding?.(decision);
205
+ }
206
+ if (decision.warnings?.length > 0) {
207
+ this.config.onWarning?.(decision);
208
+ }
209
+ this.logAudit(request, result);
210
+ return result;
211
+ }
212
+ buildValidationContext(delegation) {
213
+ const attValid = this.agent.attestation
214
+ ? verifyAttestation(this.agent.attestation).valid
215
+ : false;
216
+ return {
217
+ floorVersion: this.floor.version,
218
+ floorPrinciples: this.floor.floor.map(p => ({
219
+ id: p.id,
220
+ name: p.name,
221
+ enforcement: p.enforcement,
222
+ weight: p.weight
223
+ })),
224
+ delegation: {
225
+ scope: delegation.scope,
226
+ spendLimit: delegation.spendLimit,
227
+ spentAmount: delegation.spentAmount || 0,
228
+ expiresAt: delegation.expiresAt,
229
+ revoked: false,
230
+ currentDepth: delegation.currentDepth,
231
+ maxDepth: delegation.maxDepth
232
+ },
233
+ agentRegistered: true,
234
+ agentAttestationValid: attValid
235
+ };
236
+ }
237
+ // ── Internal: Result Builders ──
238
+ createIntent(request, delegationId) {
239
+ return createActionIntent({
240
+ agentId: this.agent.agentId,
241
+ agentPublicKey: this.agent.publicKey,
242
+ delegationId,
243
+ action: {
244
+ type: request.type,
245
+ target: request.target,
246
+ scopeRequired: request.scope,
247
+ spend: request.spend
248
+ },
249
+ context: request.context,
250
+ privateKey: this.agent.keyPair.privateKey
251
+ });
252
+ }
253
+ createDeniedResult(intent, reason) {
254
+ // Create a synthetic denial decision (not from the validator)
255
+ const evaluatorPriv = this.config.evaluator?.privateKey || this.agent.keyPair.privateKey;
256
+ const evaluatorPub = this.config.evaluator?.publicKey || this.agent.publicKey;
257
+ const evaluatorId = this.config.evaluator?.id || this.agent.agentId;
258
+ // Use evaluateIntent would fail without delegation context, so build synthetic
259
+ const now = new Date();
260
+ const expires = new Date(now);
261
+ expires.setMinutes(expires.getMinutes() + (this.config.decisionTTLMinutes || 5));
262
+ const decision = {
263
+ decisionId: 'pdec_' + uuidv4().slice(0, 12),
264
+ intentId: intent.intentId,
265
+ evaluatorId,
266
+ evaluatorPublicKey: evaluatorPub,
267
+ verdict: 'deny',
268
+ principlesEvaluated: [],
269
+ reason,
270
+ floorVersion: this.floor.version,
271
+ evaluatedAt: now.toISOString(),
272
+ expiresAt: expires.toISOString()
273
+ };
274
+ const signature = sign(canonicalize(decision), evaluatorPriv);
275
+ const signedDecision = { ...decision, signature };
276
+ this.state.decisions.push(signedDecision);
277
+ return {
278
+ permitted: false,
279
+ verdict: 'deny',
280
+ intent,
281
+ decision: signedDecision,
282
+ reason
283
+ };
284
+ }
285
+ createPermitResult(intent, reason) {
286
+ return {
287
+ permitted: true,
288
+ verdict: 'permit',
289
+ intent,
290
+ decision: {}, // Manual mode — no real decision
291
+ reason
292
+ };
293
+ }
294
+ logAudit(request, result) {
295
+ this.state.auditLog.push({
296
+ timestamp: new Date().toISOString(),
297
+ action: request,
298
+ verdict: result.verdict,
299
+ intentId: result.intent.intentId,
300
+ decisionId: result.decision.decisionId || 'manual',
301
+ receiptId: undefined,
302
+ reason: result.reason,
303
+ enforcement: {
304
+ inlinePassed: result.verdict !== 'deny',
305
+ auditIssueCount: result.auditFindings || 0,
306
+ warningCount: result.warnings || 0
307
+ }
308
+ });
309
+ }
310
+ // ── Query State ──
311
+ /** Get the current enforcement level. */
312
+ get enforcement() { return this.config.enforcement; }
313
+ /** Get all receipts produced through this context. */
314
+ get allReceipts() { return [...this.state.receipts]; }
315
+ /** Get all policy decisions made through this context. */
316
+ get allDecisions() { return [...this.state.decisions]; }
317
+ /** Get the full audit log. */
318
+ get auditLog() { return [...this.state.auditLog]; }
319
+ /** Get context state snapshot (for serialization / inspection). */
320
+ getState() { return { ...this.state }; }
321
+ /** How many actions have been permitted vs denied. */
322
+ get stats() {
323
+ const log = this.state.auditLog;
324
+ return {
325
+ permitted: log.filter(e => e.verdict === 'permit').length,
326
+ denied: log.filter(e => e.verdict === 'deny').length,
327
+ narrowed: log.filter(e => e.verdict === 'narrow').length,
328
+ total: log.length
329
+ };
330
+ }
331
+ }
332
+ // ══════════════════════════════════════
333
+ // FACTORY FUNCTION
334
+ // ══════════════════════════════════════
335
+ /**
336
+ * Create an Agent Context — the enforcement boundary.
337
+ *
338
+ * Every action that goes through this context is automatically
339
+ * checked against the Values Floor via the 3-signature chain.
340
+ *
341
+ * @param agent - From joinSocialContract()
342
+ * @param floor - The Values Floor to enforce
343
+ * @param config - Enforcement level and callbacks
344
+ */
345
+ export function createAgentContext(agent, floor, config) {
346
+ if (!agent.attestation) {
347
+ throw new Error('Agent must have a floor attestation to create a context. Did you pass a floor to joinSocialContract()?');
348
+ }
349
+ return new AgentContext(agent, floor, config);
350
+ }
351
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","sourceRoot":"","sources":["../../../src/core/context.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,gDAAgD;AAChD,qEAAqE;AACrE,EAAE;AACF,uEAAuE;AACvE,8BAA8B;AAC9B,EAAE;AACF,+DAA+D;AAC/D,yDAAyD;AACzD,EAAE;AACF,gEAAgE;AAChE,+DAA+D;AAC/D,EAAE;AACF,SAAS;AACT,0EAA0E;AAC1E,kCAAkC;AAClC,yFAAyF;AACzF,kFAAkF;AAClF,EAAE;AACF,qEAAqE;AAErE,OAAO,EAAE,EAAE,IAAI,MAAM,EAAE,MAAM,MAAM,CAAA;AACnC,OAAO,EAAE,IAAI,EAAE,MAAM,mBAAmB,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAA;AAC7C,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAA;AACvG,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAC/C,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAU/C,yCAAyC;AACzC,sBAAsB;AACtB,yCAAyC;AAEzC,MAAM,OAAO,YAAY;IACf,KAAK,CAAqB;IAC1B,KAAK,CAAa;IAClB,MAAM,CAA+F;IACrG,SAAS,CAAiB;IAC1B,KAAK,CAAmB;IAEhC,YACE,KAA0B,E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