@private.me/xbind 3.0.2 → 3.0.4

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 (222) hide show
  1. package/README.md +2366 -204
  2. package/dist-standalone/_deps/mldsa-wasm/dist/mldsa.js +1 -1920
  3. package/dist-standalone/_deps/shared/cjs/errors.js +1 -729
  4. package/dist-standalone/_deps/shared/cjs/index.js +1 -463
  5. package/dist-standalone/_deps/shared/cjs/types.js +1 -315
  6. package/dist-standalone/_deps/shared/errors.js +1 -244
  7. package/dist-standalone/_deps/shared/index.js +1 -72
  8. package/dist-standalone/_deps/shared/types.js +1 -86
  9. package/dist-standalone/_deps/ux-helpers/cjs/errors.js +1 -1
  10. package/dist-standalone/_deps/ux-helpers/cjs/index.js +1 -1
  11. package/dist-standalone/_deps/ux-helpers/cjs/pagination.js +1 -1
  12. package/dist-standalone/_deps/ux-helpers/cjs/progress.js +1 -1
  13. package/dist-standalone/_deps/ux-helpers/cjs/search.js +1 -1
  14. package/dist-standalone/_deps/ux-helpers/cjs/types.js +1 -1
  15. package/dist-standalone/_deps/ux-helpers/errors.js +1 -1
  16. package/dist-standalone/_deps/ux-helpers/index.js +1 -1
  17. package/dist-standalone/_deps/ux-helpers/pagination.js +1 -1
  18. package/dist-standalone/_deps/ux-helpers/progress.js +1 -1
  19. package/dist-standalone/_deps/ux-helpers/search.js +1 -1
  20. package/dist-standalone/_deps/xchange/auto-accept.js +1 -1
  21. package/dist-standalone/_deps/xchange/cjs/auto-accept.js +1 -1
  22. package/dist-standalone/_deps/xchange/cjs/errors.js +1 -1
  23. package/dist-standalone/_deps/xchange/cjs/index.js +1 -1
  24. package/dist-standalone/_deps/xchange/cjs/invite-client.js +1 -1
  25. package/dist-standalone/_deps/xchange/cjs/lazy-init.js +1 -1
  26. package/dist-standalone/_deps/xchange/cjs/trust-integration.js +1 -1
  27. package/dist-standalone/_deps/xchange/cjs/xchange.js +1 -1
  28. package/dist-standalone/_deps/xchange/errors.js +1 -1
  29. package/dist-standalone/_deps/xchange/index.js +1 -1
  30. package/dist-standalone/_deps/xchange/invite-client.js +1 -1
  31. package/dist-standalone/_deps/xchange/lazy-init.js +1 -1
  32. package/dist-standalone/_deps/xchange/trust-integration.js +1 -1
  33. package/dist-standalone/_deps/xchange/xchange.js +1 -1
  34. package/dist-standalone/_deps/xregistry/cjs/discovery.js +1 -1
  35. package/dist-standalone/_deps/xregistry/cjs/errors.js +1 -1
  36. package/dist-standalone/_deps/xregistry/cjs/index.js +1 -1
  37. package/dist-standalone/_deps/xregistry/cjs/registry.js +1 -1
  38. package/dist-standalone/_deps/xregistry/cjs/schema.js +1 -1
  39. package/dist-standalone/_deps/xregistry/cjs/types.js +1 -1
  40. package/dist-standalone/_deps/xregistry/discovery.js +1 -1
  41. package/dist-standalone/_deps/xregistry/errors.js +1 -1
  42. package/dist-standalone/_deps/xregistry/index.js +1 -1
  43. package/dist-standalone/_deps/xregistry/registry.js +1 -1
  44. package/dist-standalone/_deps/xregistry/schema.js +1 -1
  45. package/dist-standalone/_deps/xregistry/types.js +1 -1
  46. package/dist-standalone/agent-call.d.ts +2 -2
  47. package/dist-standalone/agent-call.js +1 -659
  48. package/dist-standalone/agent-sdk.js +1 -328
  49. package/dist-standalone/agent.d.ts +2 -0
  50. package/dist-standalone/agent.js +1 -1800
  51. package/dist-standalone/approval.js +1 -193
  52. package/dist-standalone/async-iterators.d.ts +3 -3
  53. package/dist-standalone/async-iterators.js +1 -382
  54. package/dist-standalone/auth.js +1 -219
  55. package/dist-standalone/auto-accept.js +1 -229
  56. package/dist-standalone/backup-config.js +1 -201
  57. package/dist-standalone/backup.js +1 -326
  58. package/dist-standalone/batch-operations.js +1 -388
  59. package/dist-standalone/cancellation.js +1 -477
  60. package/dist-standalone/checkpoint.js +1 -186
  61. package/dist-standalone/circuit-breaker.js +1 -468
  62. package/dist-standalone/cjs/agent-call.js +1 -701
  63. package/dist-standalone/cjs/agent-sdk.js +1 -332
  64. package/dist-standalone/cjs/agent.js +1 -1837
  65. package/dist-standalone/cjs/approval.js +1 -199
  66. package/dist-standalone/cjs/async-iterators.js +1 -392
  67. package/dist-standalone/cjs/auth.js +1 -225
  68. package/dist-standalone/cjs/auto-accept.js +1 -233
  69. package/dist-standalone/cjs/backup-config.js +1 -207
  70. package/dist-standalone/cjs/backup.js +1 -330
  71. package/dist-standalone/cjs/batch-operations.js +1 -397
  72. package/dist-standalone/cjs/cancellation.js +1 -490
  73. package/dist-standalone/cjs/checkpoint.js +1 -193
  74. package/dist-standalone/cjs/circuit-breaker.js +1 -476
  75. package/dist-standalone/cjs/cli/init.js +1 -492
  76. package/dist-standalone/cjs/config-validation.js +1 -522
  77. package/dist-standalone/cjs/connect.js +1 -312
  78. package/dist-standalone/cjs/connection-pool.js +1 -506
  79. package/dist-standalone/cjs/correlation-id.js +1 -339
  80. package/dist-standalone/cjs/crypto-utils.js +1 -176
  81. package/dist-standalone/cjs/debug-mode.js +1 -534
  82. package/dist-standalone/cjs/did-document.js +1 -101
  83. package/dist-standalone/cjs/did-privateme.js +1 -130
  84. package/dist-standalone/cjs/did-web.js +1 -201
  85. package/dist-standalone/cjs/discovery.js +1 -462
  86. package/dist-standalone/cjs/dual-mode.js +1 -251
  87. package/dist-standalone/cjs/email-templates.js +1 -313
  88. package/dist-standalone/cjs/email-transport.js +1 -239
  89. package/dist-standalone/cjs/envelope.js +1 -538
  90. package/dist-standalone/cjs/errors.js +1 -913
  91. package/dist-standalone/cjs/event-emitter.js +1 -461
  92. package/dist-standalone/cjs/gateway-state.js +1 -55
  93. package/dist-standalone/cjs/gateway-transport.js +1 -120
  94. package/dist-standalone/cjs/graceful-degradation.js +1 -403
  95. package/dist-standalone/cjs/guardrails.js +1 -223
  96. package/dist-standalone/cjs/health-check.js +1 -336
  97. package/dist-standalone/cjs/http-compat.js +1 -272
  98. package/dist-standalone/cjs/http-status-map.js +1 -571
  99. package/dist-standalone/cjs/identity.js +1 -645
  100. package/dist-standalone/cjs/index.js +1 -406
  101. package/dist-standalone/cjs/invitation.js +1 -421
  102. package/dist-standalone/cjs/invite.js +1 -328
  103. package/dist-standalone/cjs/key-agreement.js +1 -335
  104. package/dist-standalone/cjs/lazy-init.js +1 -300
  105. package/dist-standalone/cjs/logger.js +1 -291
  106. package/dist-standalone/cjs/loopback-transport.js +1 -0
  107. package/dist-standalone/cjs/mdns-discovery.js +1 -202
  108. package/dist-standalone/cjs/nonce-store.js +1 -80
  109. package/dist-standalone/cjs/pairing-manager.js +1 -223
  110. package/dist-standalone/cjs/plugin-system.js +1 -264
  111. package/dist-standalone/cjs/plugins/logging.js +1 -168
  112. package/dist-standalone/cjs/plugins/metrics.js +1 -181
  113. package/dist-standalone/cjs/plugins/validation.js +1 -302
  114. package/dist-standalone/cjs/policy.js +1 -320
  115. package/dist-standalone/cjs/progress-callbacks.js +1 -583
  116. package/dist-standalone/cjs/redis-nonce-store.js +1 -76
  117. package/dist-standalone/cjs/registry-middleware.js +1 -50
  118. package/dist-standalone/cjs/retry-strategies.js +1 -544
  119. package/dist-standalone/cjs/retry-transport.js +1 -102
  120. package/dist-standalone/cjs/runtime/browser.js +1 -533
  121. package/dist-standalone/cjs/runtime/edge.js +1 -526
  122. package/dist-standalone/cjs/runtime/react-native.js +1 -394
  123. package/dist-standalone/cjs/security-policy.js +1 -245
  124. package/dist-standalone/cjs/serialization.js +1 -1040
  125. package/dist-standalone/cjs/split-channel.js +1 -225
  126. package/dist-standalone/cjs/subscription-proof.js +1 -230
  127. package/dist-standalone/cjs/succession.js +1 -148
  128. package/dist-standalone/cjs/timeouts.js +1 -412
  129. package/dist-standalone/cjs/trace-context.js +1 -424
  130. package/dist-standalone/cjs/trace-spans.js +1 -495
  131. package/dist-standalone/cjs/transport.js +1 -63
  132. package/dist-standalone/cjs/trust-registry.js +1 -991
  133. package/dist-standalone/cjs/types/error-response.js +1 -56
  134. package/dist-standalone/cjs/vault-auth.js +1 -178
  135. package/dist-standalone/cjs/vault-store-loader.js +1 -194
  136. package/dist-standalone/cjs/verify.js +1 -25
  137. package/dist-standalone/cjs/version-info.js +1 -543
  138. package/dist-standalone/cjs/xfetch.js +1 -340
  139. package/dist-standalone/cli/init.js +1 -455
  140. package/dist-standalone/cli/setup.js +1 -514
  141. package/dist-standalone/cli/types.js +1 -27
  142. package/dist-standalone/cli/xbind.js +1 -148
  143. package/dist-standalone/config-validation.js +1 -513
  144. package/dist-standalone/connect.js +1 -274
  145. package/dist-standalone/connection-pool.js +1 -500
  146. package/dist-standalone/correlation-id.js +1 -326
  147. package/dist-standalone/crypto-utils.d.ts +2 -7
  148. package/dist-standalone/crypto-utils.js +1 -157
  149. package/dist-standalone/debug-mode.js +1 -510
  150. package/dist-standalone/did-document.js +1 -96
  151. package/dist-standalone/did-privateme.js +1 -121
  152. package/dist-standalone/did-web.js +1 -196
  153. package/dist-standalone/discovery.js +1 -458
  154. package/dist-standalone/dual-mode.js +1 -247
  155. package/dist-standalone/email-templates.js +1 -309
  156. package/dist-standalone/email-transport.d.ts +2 -2
  157. package/dist-standalone/email-transport.js +1 -232
  158. package/dist-standalone/envelope.js +1 -525
  159. package/dist-standalone/errors.d.ts +13 -3
  160. package/dist-standalone/errors.js +1 -896
  161. package/dist-standalone/event-emitter.js +1 -456
  162. package/dist-standalone/gateway-state.d.ts +1 -1
  163. package/dist-standalone/gateway-state.js +1 -51
  164. package/dist-standalone/gateway-transport.js +1 -116
  165. package/dist-standalone/graceful-degradation.js +1 -396
  166. package/dist-standalone/guardrails.js +1 -216
  167. package/dist-standalone/health-check.d.ts +5 -1
  168. package/dist-standalone/health-check.js +1 -332
  169. package/dist-standalone/http-compat.d.ts +1 -1
  170. package/dist-standalone/http-compat.js +1 -267
  171. package/dist-standalone/http-status-map.js +1 -561
  172. package/dist-standalone/identity.js +1 -619
  173. package/dist-standalone/index.d.ts +15 -4
  174. package/dist-standalone/index.js +1 -78
  175. package/dist-standalone/invitation.js +1 -415
  176. package/dist-standalone/invite.js +1 -324
  177. package/dist-standalone/key-agreement.js +1 -325
  178. package/dist-standalone/lazy-init.d.ts +11 -6
  179. package/dist-standalone/lazy-init.js +1 -295
  180. package/dist-standalone/logger.js +1 -285
  181. package/dist-standalone/loopback-transport.d.ts +87 -0
  182. package/dist-standalone/loopback-transport.js +1 -0
  183. package/dist-standalone/mdns-discovery.js +1 -195
  184. package/dist-standalone/nonce-store.js +1 -76
  185. package/dist-standalone/pairing-manager.js +1 -219
  186. package/dist-standalone/plugin-system.js +1 -257
  187. package/dist-standalone/plugins/logging.js +1 -163
  188. package/dist-standalone/plugins/metrics.d.ts +4 -4
  189. package/dist-standalone/plugins/metrics.js +1 -176
  190. package/dist-standalone/plugins/validation.js +1 -297
  191. package/dist-standalone/policy.js +1 -315
  192. package/dist-standalone/progress-callbacks.js +1 -576
  193. package/dist-standalone/redis-nonce-store.js +1 -72
  194. package/dist-standalone/registry-middleware.js +1 -47
  195. package/dist-standalone/retry-strategies.js +1 -534
  196. package/dist-standalone/retry-transport.js +1 -98
  197. package/dist-standalone/runtime/browser.js +1 -516
  198. package/dist-standalone/runtime/edge.js +1 -511
  199. package/dist-standalone/runtime/react-native.d.ts +1 -1
  200. package/dist-standalone/runtime/react-native.js +1 -383
  201. package/dist-standalone/security-policy.js +1 -239
  202. package/dist-standalone/serialization.js +1 -1031
  203. package/dist-standalone/split-channel.d.ts +1 -1
  204. package/dist-standalone/split-channel.js +1 -219
  205. package/dist-standalone/subscription-proof.js +1 -224
  206. package/dist-standalone/succession.js +1 -142
  207. package/dist-standalone/timeouts.js +1 -398
  208. package/dist-standalone/trace-context.js +1 -414
  209. package/dist-standalone/trace-spans.js +1 -488
  210. package/dist-standalone/transport.d.ts +1 -1
  211. package/dist-standalone/transport.js +1 -59
  212. package/dist-standalone/trust-registry.d.ts +3 -3
  213. package/dist-standalone/trust-registry.js +1 -950
  214. package/dist-standalone/types/error-response.js +1 -52
  215. package/dist-standalone/vault-auth.js +1 -174
  216. package/dist-standalone/vault-store-loader.d.ts +9 -0
  217. package/dist-standalone/vault-store-loader.js +1 -187
  218. package/dist-standalone/verify.js +1 -16
  219. package/dist-standalone/version-info.js +1 -530
  220. package/dist-standalone/xfetch.js +1 -335
  221. package/package.json +1 -1
  222. package/share1.dat +0 -0
@@ -1,302 +1 @@
1
- "use strict";
2
- /**
3
- * @module plugins/validation
4
- * Validation plugin for xBind plugin system
5
- *
6
- * Validates payloads, envelopes, and ensures data integrity before processing.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.CommonRules = exports.ValidationPlugin = void 0;
10
- exports.createValidationPlugin = createValidationPlugin;
11
- const shared_1 = require("../../_deps/shared/index.js");
12
- /**
13
- * Validation plugin implementation.
14
- * Validates all data before processing to ensure integrity and compliance.
15
- */
16
- class ValidationPlugin {
17
- name = 'validation';
18
- version = '1.0.0';
19
- description = 'Validates payloads and envelopes before processing';
20
- priority = 5; // Execute very early
21
- options;
22
- validationErrors = [];
23
- constructor(options = {}) {
24
- this.options = {
25
- maxPayloadSize: options.maxPayloadSize ?? 10 * 1024 * 1024, // 10MB
26
- maxEnvelopeSize: options.maxEnvelopeSize ?? 15 * 1024 * 1024, // 15MB
27
- allowedScopes: options.allowedScopes ?? [],
28
- customRules: options.customRules ?? [],
29
- strictMode: options.strictMode ?? false,
30
- validateSchema: options.validateSchema ?? false,
31
- };
32
- }
33
- onInit() {
34
- return (0, shared_1.ok)(undefined);
35
- }
36
- onDestroy() {
37
- this.validationErrors = [];
38
- return (0, shared_1.ok)(undefined);
39
- }
40
- onSend(payload, context) {
41
- // Validate payload size
42
- const sizeResult = this.validatePayloadSize(payload);
43
- if (sizeResult.ok === false) {
44
- this.recordError('payload_size', sizeResult.error);
45
- return (0, shared_1.err)(sizeResult.error);
46
- }
47
- // Validate scope
48
- if (context.scope) {
49
- const scopeResult = this.validateScope(context.scope);
50
- if (scopeResult.ok === false) {
51
- this.recordError('scope', scopeResult.error);
52
- return (0, shared_1.err)(scopeResult.error);
53
- }
54
- }
55
- // Validate payload structure
56
- const structureResult = this.validatePayloadStructure(payload);
57
- if (structureResult.ok === false) {
58
- this.recordError('payload_structure', structureResult.error);
59
- return (0, shared_1.err)(structureResult.error);
60
- }
61
- // Apply custom rules
62
- for (const rule of this.options.customRules) {
63
- if (!rule.appliesTo || rule.appliesTo.includes('send')) {
64
- const error = rule.validate(payload, context);
65
- if (error) {
66
- this.recordError(rule.name, error);
67
- return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
68
- }
69
- }
70
- }
71
- return (0, shared_1.ok)({ payload });
72
- }
73
- onReceive(envelope, context) {
74
- // Validate envelope size
75
- const sizeResult = this.validateEnvelopeSize(envelope);
76
- if (sizeResult.ok === false) {
77
- this.recordError('envelope_size', sizeResult.error);
78
- return (0, shared_1.err)(sizeResult.error);
79
- }
80
- // Validate envelope structure
81
- const structureResult = this.validateEnvelopeStructure(envelope);
82
- if (structureResult.ok === false) {
83
- this.recordError('envelope_structure', structureResult.error);
84
- return (0, shared_1.err)(structureResult.error);
85
- }
86
- // Apply custom rules
87
- for (const rule of this.options.customRules) {
88
- if (!rule.appliesTo || rule.appliesTo.includes('receive')) {
89
- const error = rule.validate(envelope, context);
90
- if (error) {
91
- this.recordError(rule.name, error);
92
- return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
93
- }
94
- }
95
- }
96
- return (0, shared_1.ok)({ payload: envelope });
97
- }
98
- onEncrypt(plaintext, context) {
99
- // Validate plaintext is not empty
100
- if (plaintext.length === 0) {
101
- this.recordError('plaintext_empty', 'Plaintext cannot be empty');
102
- return (0, shared_1.err)('VALIDATION_FAILED:PLAINTEXT_EMPTY');
103
- }
104
- // Validate plaintext size
105
- if (plaintext.length > this.options.maxPayloadSize) {
106
- this.recordError('plaintext_size', `Plaintext exceeds max size: ${plaintext.length} bytes`);
107
- return (0, shared_1.err)(`VALIDATION_FAILED:PLAINTEXT_TOO_LARGE:${plaintext.length}`);
108
- }
109
- // Apply custom rules
110
- for (const rule of this.options.customRules) {
111
- if (!rule.appliesTo || rule.appliesTo.includes('encrypt')) {
112
- const error = rule.validate(plaintext, context);
113
- if (error) {
114
- this.recordError(rule.name, error);
115
- return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
116
- }
117
- }
118
- }
119
- return (0, shared_1.ok)({ payload: plaintext });
120
- }
121
- onDecrypt(plaintext, context) {
122
- // Validate plaintext is not empty
123
- if (plaintext.length === 0) {
124
- this.recordError('plaintext_empty', 'Decrypted plaintext is empty');
125
- return (0, shared_1.err)('VALIDATION_FAILED:DECRYPTED_EMPTY');
126
- }
127
- // Apply custom rules
128
- for (const rule of this.options.customRules) {
129
- if (!rule.appliesTo || rule.appliesTo.includes('decrypt')) {
130
- const error = rule.validate(plaintext, context);
131
- if (error) {
132
- this.recordError(rule.name, error);
133
- return (0, shared_1.err)(`VALIDATION_FAILED:${rule.name}:${error}`);
134
- }
135
- }
136
- }
137
- return (0, shared_1.ok)({ payload: plaintext });
138
- }
139
- /**
140
- * Get all validation errors.
141
- */
142
- getValidationErrors() {
143
- return [...this.validationErrors];
144
- }
145
- /**
146
- * Clear validation errors.
147
- */
148
- clearErrors() {
149
- this.validationErrors = [];
150
- }
151
- /**
152
- * Add a custom validation rule.
153
- */
154
- addRule(rule) {
155
- this.options.customRules.push(rule);
156
- }
157
- /**
158
- * Remove a custom validation rule by name.
159
- */
160
- removeRule(name) {
161
- const index = this.options.customRules.findIndex((r) => r.name === name);
162
- if (index === -1) {
163
- return false;
164
- }
165
- this.options.customRules.splice(index, 1);
166
- return true;
167
- }
168
- validatePayloadSize(payload) {
169
- const size = this.estimateSize(payload);
170
- if (size > this.options.maxPayloadSize) {
171
- return (0, shared_1.err)(`VALIDATION_FAILED:PAYLOAD_TOO_LARGE:${size}>${this.options.maxPayloadSize}`);
172
- }
173
- return (0, shared_1.ok)(undefined);
174
- }
175
- validateEnvelopeSize(envelope) {
176
- const size = this.estimateSize(envelope);
177
- if (size > this.options.maxEnvelopeSize) {
178
- return (0, shared_1.err)(`VALIDATION_FAILED:ENVELOPE_TOO_LARGE:${size}>${this.options.maxEnvelopeSize}`);
179
- }
180
- return (0, shared_1.ok)(undefined);
181
- }
182
- validateScope(scope) {
183
- if (this.options.allowedScopes.length > 0 && !this.options.allowedScopes.includes(scope)) {
184
- return (0, shared_1.err)(`VALIDATION_FAILED:SCOPE_NOT_ALLOWED:${scope}`);
185
- }
186
- return (0, shared_1.ok)(undefined);
187
- }
188
- validatePayloadStructure(payload) {
189
- if (payload === null || payload === undefined) {
190
- return (0, shared_1.err)('VALIDATION_FAILED:PAYLOAD_NULL_OR_UNDEFINED');
191
- }
192
- // Validate can be serialized to JSON
193
- try {
194
- JSON.stringify(payload);
195
- }
196
- catch (error) {
197
- return (0, shared_1.err)(`VALIDATION_FAILED:PAYLOAD_NOT_SERIALIZABLE:${String(error)}`);
198
- }
199
- return (0, shared_1.ok)(undefined);
200
- }
201
- validateEnvelopeStructure(envelope) {
202
- // Validate required fields
203
- if (!('v' in envelope) && !('version' in envelope)) {
204
- return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_VERSION');
205
- }
206
- if (!envelope.sender) {
207
- return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_SENDER');
208
- }
209
- if (!envelope.recipient) {
210
- return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_RECIPIENT');
211
- }
212
- if (!('payload' in envelope) && !('ciphertext' in envelope)) {
213
- return (0, shared_1.err)('VALIDATION_FAILED:ENVELOPE_MISSING_CIPHERTEXT');
214
- }
215
- return (0, shared_1.ok)(undefined);
216
- }
217
- estimateSize(value) {
218
- if (value instanceof Uint8Array) {
219
- return value.length;
220
- }
221
- try {
222
- return JSON.stringify(value).length;
223
- }
224
- catch {
225
- return 0;
226
- }
227
- }
228
- recordError(rule, error) {
229
- this.validationErrors.push({
230
- timestamp: Date.now(),
231
- rule,
232
- error,
233
- });
234
- // Keep only last 1000 errors
235
- if (this.validationErrors.length > 1000) {
236
- this.validationErrors.shift();
237
- }
238
- }
239
- }
240
- exports.ValidationPlugin = ValidationPlugin;
241
- /**
242
- * Create a validation plugin with options.
243
- */
244
- function createValidationPlugin(options) {
245
- return new ValidationPlugin(options);
246
- }
247
- /**
248
- * Common validation rules.
249
- */
250
- exports.CommonRules = {
251
- /**
252
- * Validate payload contains required fields.
253
- */
254
- requireFields(fields) {
255
- return {
256
- name: 'require_fields',
257
- appliesTo: ['send'],
258
- validate: (value) => {
259
- if (typeof value !== 'object' || value === null) {
260
- return 'Payload must be an object';
261
- }
262
- const obj = value;
263
- const missing = fields.filter((field) => !(field in obj));
264
- if (missing.length > 0) {
265
- return `Missing required fields: ${missing.join(', ')}`;
266
- }
267
- return null;
268
- },
269
- };
270
- },
271
- /**
272
- * Validate DID format.
273
- */
274
- validateDIDFormat() {
275
- return {
276
- name: 'did_format',
277
- appliesTo: ['send', 'receive'],
278
- validate: (value, context) => {
279
- if (context.recipient && !context.recipient.startsWith('did:')) {
280
- return `Invalid DID format: ${context.recipient}`;
281
- }
282
- return null;
283
- },
284
- };
285
- },
286
- /**
287
- * Validate timestamp is recent.
288
- */
289
- validateTimestamp(maxAgeMs = 300000) {
290
- return {
291
- name: 'timestamp_freshness',
292
- appliesTo: ['receive'],
293
- validate: (value, context) => {
294
- const age = Date.now() - context.timestamp;
295
- if (age > maxAgeMs) {
296
- return `Timestamp too old: ${age}ms > ${maxAgeMs}ms`;
297
- }
298
- return null;
299
- },
300
- };
301
- },
302
- };
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.CommonRules=exports.ValidationPlugin=void 0,exports.createValidationPlugin=createValidationPlugin;const shared_1=require("../../_deps/shared/index.js");class ValidationPlugin{name="validation";version="1.0.0";description="Validates payloads and envelopes before processing";priority=5;options;validationErrors=[];constructor(e={}){this.options={maxPayloadSize:e.maxPayloadSize??10485760,maxEnvelopeSize:e.maxEnvelopeSize??15728640,allowedScopes:e.allowedScopes??[],customRules:e.customRules??[],strictMode:e.strictMode??!1,validateSchema:e.validateSchema??!1}}onInit(){return(0,shared_1.ok)(void 0)}onDestroy(){return this.validationErrors=[],(0,shared_1.ok)(void 0)}onSend(e,r){const t=this.validatePayloadSize(e);if(!1===t.ok)return this.recordError("payload_size",t.error),(0,shared_1.err)(t.error);if(r.scope){const e=this.validateScope(r.scope);if(!1===e.ok)return this.recordError("scope",e.error),(0,shared_1.err)(e.error)}const i=this.validatePayloadStructure(e);if(!1===i.ok)return this.recordError("payload_structure",i.error),(0,shared_1.err)(i.error);for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("send")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}onReceive(e,r){const t=this.validateEnvelopeSize(e);if(!1===t.ok)return this.recordError("envelope_size",t.error),(0,shared_1.err)(t.error);const i=this.validateEnvelopeStructure(e);if(!1===i.ok)return this.recordError("envelope_structure",i.error),(0,shared_1.err)(i.error);for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("receive")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}onEncrypt(e,r){if(0===e.length)return this.recordError("plaintext_empty","Plaintext cannot be empty"),(0,shared_1.err)("VALIDATION_FAILED:PLAINTEXT_EMPTY");if(e.length>this.options.maxPayloadSize)return this.recordError("plaintext_size",`Plaintext exceeds max size: ${e.length} bytes`),(0,shared_1.err)(`VALIDATION_FAILED:PLAINTEXT_TOO_LARGE:${e.length}`);for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("encrypt")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}onDecrypt(e,r){if(0===e.length)return this.recordError("plaintext_empty","Decrypted plaintext is empty"),(0,shared_1.err)("VALIDATION_FAILED:DECRYPTED_EMPTY");for(const t of this.options.customRules)if(!t.appliesTo||t.appliesTo.includes("decrypt")){const i=t.validate(e,r);if(i)return this.recordError(t.name,i),(0,shared_1.err)(`VALIDATION_FAILED:${t.name}:${i}`)}return(0,shared_1.ok)({payload:e})}getValidationErrors(){return[...this.validationErrors]}clearErrors(){this.validationErrors=[]}addRule(e){this.options.customRules.push(e)}removeRule(e){const r=this.options.customRules.findIndex(r=>r.name===e);return-1!==r&&(this.options.customRules.splice(r,1),!0)}validatePayloadSize(e){const r=this.estimateSize(e);return r>this.options.maxPayloadSize?(0,shared_1.err)(`VALIDATION_FAILED:PAYLOAD_TOO_LARGE:${r}>${this.options.maxPayloadSize}`):(0,shared_1.ok)(void 0)}validateEnvelopeSize(e){const r=this.estimateSize(e);return r>this.options.maxEnvelopeSize?(0,shared_1.err)(`VALIDATION_FAILED:ENVELOPE_TOO_LARGE:${r}>${this.options.maxEnvelopeSize}`):(0,shared_1.ok)(void 0)}validateScope(e){return this.options.allowedScopes.length>0&&!this.options.allowedScopes.includes(e)?(0,shared_1.err)(`VALIDATION_FAILED:SCOPE_NOT_ALLOWED:${e}`):(0,shared_1.ok)(void 0)}validatePayloadStructure(e){if(null==e)return(0,shared_1.err)("VALIDATION_FAILED:PAYLOAD_NULL_OR_UNDEFINED");try{JSON.stringify(e)}catch(e){return(0,shared_1.err)(`VALIDATION_FAILED:PAYLOAD_NOT_SERIALIZABLE:${String(e)}`)}return(0,shared_1.ok)(void 0)}validateEnvelopeStructure(e){return"v"in e||"version"in e?e.sender?e.recipient?"payload"in e||"ciphertext"in e?(0,shared_1.ok)(void 0):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_CIPHERTEXT"):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_RECIPIENT"):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_SENDER"):(0,shared_1.err)("VALIDATION_FAILED:ENVELOPE_MISSING_VERSION")}estimateSize(e){if(e instanceof Uint8Array)return e.length;try{return JSON.stringify(e).length}catch{return 0}}recordError(e,r){this.validationErrors.push({timestamp:Date.now(),rule:e,error:r}),this.validationErrors.length>1e3&&this.validationErrors.shift()}}function createValidationPlugin(e){return new ValidationPlugin(e)}exports.ValidationPlugin=ValidationPlugin,exports.CommonRules={requireFields:e=>({name:"require_fields",appliesTo:["send"],validate:r=>{if("object"!=typeof r||null===r)return"Payload must be an object";const t=r,i=e.filter(e=>!(e in t));return i.length>0?`Missing required fields: ${i.join(", ")}`:null}}),validateDIDFormat:()=>({name:"did_format",appliesTo:["send","receive"],validate:(e,r)=>r.recipient&&!r.recipient.startsWith("did:")?`Invalid DID format: ${r.recipient}`:null}),validateTimestamp:(e=3e5)=>({name:"timestamp_freshness",appliesTo:["receive"],validate:(r,t)=>{const i=Date.now()-t.timestamp;return i>e?`Timestamp too old: ${i}ms > ${e}ms`:null}})};
@@ -1,320 +1 @@
1
- "use strict";
2
- /**
3
- * @module policy
4
- * PolicyEngine for agent.call() constraint enforcement
5
- *
6
- * Enforces spending limits, rate limits, scope restrictions, and data filters
7
- * on agent tool calls. Separate from SecurityPolicy (risk classification).
8
- */
9
- Object.defineProperty(exports, "__esModule", { value: true });
10
- exports.PolicyEngine = void 0;
11
- exports.getGlobalPolicyEngine = getGlobalPolicyEngine;
12
- const shared_1 = require("../_deps/shared/index.js");
13
- const agent_call_js_1 = require("./agent-call.js");
14
- /**
15
- * PolicyEngine - Enforces constraints on agent.call() requests
16
- *
17
- * Tracks:
18
- * - Per-transaction spending limits
19
- * - Daily spending limits
20
- * - Rate limits (calls per minute)
21
- * - Allowed tools/scopes
22
- *
23
- * Thread-safe for concurrent requests from the same agent.
24
- */
25
- class PolicyEngine {
26
- /** Rate limit tracker by agent DID */
27
- rateLimits = new Map();
28
- /** Daily spending tracker by agent DID */
29
- dailySpending = new Map();
30
- /** Monthly spending tracker by agent DID */
31
- monthlySpending = new Map();
32
- /**
33
- * Evaluate a policy against a request
34
- *
35
- * @param agentDID - Agent DID making the request
36
- * @param tool - Tool being called (e.g., "stripe:createCharge")
37
- * @param params - Tool parameters
38
- * @param constraints - Policy constraints to enforce
39
- * @returns Policy evaluation result
40
- */
41
- evaluate(agentDID, tool, params, constraints) {
42
- // Check allowed tools
43
- if (constraints.allowedTools && constraints.allowedTools.length > 0) {
44
- const [service] = tool.split(':');
45
- const isAllowed = constraints.allowedTools.some((allowed) => allowed === tool || allowed === `${service}:*` || allowed === '*');
46
- if (!isAllowed) {
47
- const details = {
48
- requested: tool,
49
- allowed: constraints.allowedTools,
50
- constraint: 'tool',
51
- fix: `Update policy.allowedTools to include "${tool}" or "${service}:*" or request approval`,
52
- };
53
- return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Tool "${tool}" is not allowed by policy`, details));
54
- }
55
- }
56
- // Check scopes
57
- if (constraints.scopes && constraints.scopes.length > 0) {
58
- // Extract scope from params if present
59
- const scope = typeof params === 'object' && params !== null && 'scope' in params
60
- ? params.scope
61
- : undefined;
62
- if (scope && !constraints.scopes.includes(scope)) {
63
- const details = {
64
- requested: scope,
65
- allowed: constraints.scopes,
66
- constraint: 'scope',
67
- fix: `Update policy.scopes to include "${scope}" or request additional permissions`,
68
- };
69
- return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Scope "${scope}" is not allowed by policy`, details));
70
- }
71
- }
72
- // Check rate limits
73
- if (constraints.limits?.callsPerMinute) {
74
- const rateCheck = this.checkRateLimit(agentDID, constraints.limits.callsPerMinute);
75
- if (!rateCheck.ok) {
76
- return rateCheck;
77
- }
78
- }
79
- // Check spending limits (if amount is in params)
80
- const amount = this.extractAmount(params);
81
- if (amount !== null) {
82
- // Check per-transaction limit
83
- if (constraints.limits?.amountPerTxn && amount > constraints.limits.amountPerTxn) {
84
- const details = {
85
- requested: amount,
86
- allowed: constraints.limits.amountPerTxn,
87
- constraint: 'amountPerTxn',
88
- fix: `Reduce amount to ${constraints.limits.amountPerTxn} or less, or update policy.limits.amountPerTxn`,
89
- };
90
- return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} exceeds per-transaction limit of ${constraints.limits.amountPerTxn}`, details));
91
- }
92
- // Check daily limit
93
- if (constraints.limits?.dailyAmount) {
94
- const dailyCheck = this.checkDailyLimit(agentDID, amount, constraints.limits.dailyAmount);
95
- if (!dailyCheck.ok) {
96
- return dailyCheck;
97
- }
98
- }
99
- // Check monthly limit
100
- if (constraints.limits?.monthlyAmount) {
101
- const monthlyCheck = this.checkMonthlyLimit(agentDID, amount, constraints.limits.monthlyAmount);
102
- if (!monthlyCheck.ok) {
103
- return monthlyCheck;
104
- }
105
- }
106
- }
107
- // All checks passed
108
- return (0, shared_1.ok)(undefined);
109
- }
110
- /**
111
- * Record a successful call (for rate limiting)
112
- *
113
- * @param agentDID - Agent DID
114
- */
115
- recordCall(agentDID) {
116
- const now = Date.now();
117
- const entry = this.rateLimits.get(agentDID) ?? {
118
- calls: [],
119
- windowStart: now,
120
- };
121
- entry.calls.push(now);
122
- // Clean up old calls (older than 1 minute)
123
- const oneMinuteAgo = now - 60000;
124
- entry.calls = entry.calls.filter((timestamp) => timestamp > oneMinuteAgo);
125
- this.rateLimits.set(agentDID, entry);
126
- }
127
- /**
128
- * Record successful spending (for daily and monthly limits)
129
- *
130
- * @param agentDID - Agent DID
131
- * @param amount - Amount spent
132
- */
133
- recordSpending(agentDID, amount) {
134
- const today = this.getCurrentDay();
135
- const thisMonth = this.getCurrentMonth();
136
- // Update daily spending
137
- const dailyEntry = this.dailySpending.get(agentDID);
138
- if (dailyEntry && dailyEntry.day === today) {
139
- dailyEntry.amount += amount;
140
- }
141
- else {
142
- this.dailySpending.set(agentDID, {
143
- amount,
144
- day: today,
145
- });
146
- }
147
- // Update monthly spending
148
- const monthlyEntry = this.monthlySpending.get(agentDID);
149
- if (monthlyEntry && monthlyEntry.month === thisMonth) {
150
- monthlyEntry.amount += amount;
151
- }
152
- else {
153
- this.monthlySpending.set(agentDID, {
154
- amount,
155
- month: thisMonth,
156
- });
157
- }
158
- }
159
- /**
160
- * Get current rate limit status for an agent
161
- *
162
- * @param agentDID - Agent DID
163
- * @returns Calls in current minute
164
- */
165
- getCurrentRateLimit(agentDID) {
166
- const entry = this.rateLimits.get(agentDID);
167
- if (!entry)
168
- return 0;
169
- const now = Date.now();
170
- const oneMinuteAgo = now - 60000;
171
- // Count calls in last minute
172
- return entry.calls.filter((timestamp) => timestamp > oneMinuteAgo).length;
173
- }
174
- /**
175
- * Get current daily spending for an agent
176
- *
177
- * @param agentDID - Agent DID
178
- * @returns Amount spent today
179
- */
180
- getDailySpending(agentDID) {
181
- const today = this.getCurrentDay();
182
- const entry = this.dailySpending.get(agentDID);
183
- if (!entry || entry.day !== today)
184
- return 0;
185
- return entry.amount;
186
- }
187
- /**
188
- * Get current monthly spending for an agent
189
- *
190
- * @param agentDID - Agent DID
191
- * @returns Amount spent this month
192
- */
193
- getMonthlySpending(agentDID) {
194
- const thisMonth = this.getCurrentMonth();
195
- const entry = this.monthlySpending.get(agentDID);
196
- if (!entry || entry.month !== thisMonth)
197
- return 0;
198
- return entry.amount;
199
- }
200
- /**
201
- * Reset all limits for an agent (for testing)
202
- *
203
- * @param agentDID - Agent DID
204
- */
205
- reset(agentDID) {
206
- this.rateLimits.delete(agentDID);
207
- this.dailySpending.delete(agentDID);
208
- this.monthlySpending.delete(agentDID);
209
- }
210
- /**
211
- * Check rate limit
212
- */
213
- checkRateLimit(agentDID, limit) {
214
- const current = this.getCurrentRateLimit(agentDID);
215
- if (current >= limit) {
216
- const details = {
217
- requested: current + 1,
218
- allowed: limit,
219
- constraint: 'callsPerMinute',
220
- current,
221
- fix: `Wait before making additional calls, or update policy.limits.callsPerMinute to a higher value`,
222
- };
223
- return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Rate limit exceeded: ${current}/${limit} calls per minute`, details));
224
- }
225
- return (0, shared_1.ok)(undefined);
226
- }
227
- /**
228
- * Check daily spending limit
229
- */
230
- checkDailyLimit(agentDID, amount, limit) {
231
- const current = this.getDailySpending(agentDID);
232
- const newTotal = current + amount;
233
- if (newTotal > limit) {
234
- const remaining = limit - current;
235
- const details = {
236
- requested: amount,
237
- allowed: limit,
238
- constraint: 'dailyAmount',
239
- current,
240
- newTotal,
241
- fix: remaining > 0
242
- ? `Reduce amount to ${remaining} or less (remaining today), or update policy.limits.dailyAmount`
243
- : `Daily limit already reached. Wait until tomorrow or update policy.limits.dailyAmount`,
244
- };
245
- return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} would exceed daily limit: ${newTotal}/${limit} (current: ${current})`, details));
246
- }
247
- return (0, shared_1.ok)(undefined);
248
- }
249
- /**
250
- * Extract amount from params
251
- */
252
- extractAmount(params) {
253
- if (typeof params !== 'object' || params === null)
254
- return null;
255
- const obj = params;
256
- // Check common amount field names
257
- if (typeof obj.amount === 'number')
258
- return obj.amount;
259
- if (typeof obj.value === 'number')
260
- return obj.value;
261
- if (typeof obj.price === 'number')
262
- return obj.price;
263
- if (typeof obj.total === 'number')
264
- return obj.total;
265
- return null;
266
- }
267
- /**
268
- * Get current day identifier (YYYY-MM-DD in UTC)
269
- */
270
- getCurrentDay() {
271
- const now = new Date();
272
- return now.toISOString().split('T')[0] ?? '';
273
- }
274
- /**
275
- * Get current month identifier (YYYY-MM in UTC)
276
- */
277
- getCurrentMonth() {
278
- const now = new Date();
279
- const iso = now.toISOString();
280
- return iso.substring(0, 7); // YYYY-MM
281
- }
282
- /**
283
- * Check monthly spending limit
284
- */
285
- checkMonthlyLimit(agentDID, amount, limit) {
286
- const current = this.getMonthlySpending(agentDID);
287
- const newTotal = current + amount;
288
- if (newTotal > limit) {
289
- const remaining = limit - current;
290
- const details = {
291
- requested: amount,
292
- allowed: limit,
293
- constraint: 'dailyAmount', // Reuse constraint type (will add monthlyAmount later)
294
- current,
295
- newTotal,
296
- fix: remaining > 0
297
- ? `Reduce amount to ${remaining} or less (remaining this month), or update policy.limits.monthlyAmount`
298
- : `Monthly limit already reached. Wait until next month or update policy.limits.monthlyAmount`,
299
- };
300
- return (0, shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION, `Amount ${amount} would exceed monthly limit: ${newTotal}/${limit} (current: ${current})`, details));
301
- }
302
- return (0, shared_1.ok)(undefined);
303
- }
304
- }
305
- exports.PolicyEngine = PolicyEngine;
306
- /**
307
- * Global policy engine instance (singleton)
308
- */
309
- let globalPolicyEngine = null;
310
- /**
311
- * Get the global policy engine instance
312
- *
313
- * @returns PolicyEngine instance
314
- */
315
- function getGlobalPolicyEngine() {
316
- if (!globalPolicyEngine) {
317
- globalPolicyEngine = new PolicyEngine();
318
- }
319
- return globalPolicyEngine;
320
- }
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.PolicyEngine=void 0,exports.getGlobalPolicyEngine=getGlobalPolicyEngine;const shared_1=require("../_deps/shared/index.js"),agent_call_js_1=require("./agent-call.js");class PolicyEngine{rateLimits=new Map;dailySpending=new Map;monthlySpending=new Map;evaluate(t,e,n,o){if(o.allowedTools&&o.allowedTools.length>0){const[t]=e.split(":");if(!o.allowedTools.some(n=>n===e||n===`${t}:*`||"*"===n)){const n={requested:e,allowed:o.allowedTools,constraint:"tool",fix:`Update policy.allowedTools to include "${e}" or "${t}:*" or request approval`};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Tool "${e}" is not allowed by policy`,n))}}if(o.scopes&&o.scopes.length>0){const t="object"==typeof n&&null!==n&&"scope"in n?n.scope:void 0;if(t&&!o.scopes.includes(t)){const e={requested:t,allowed:o.scopes,constraint:"scope",fix:`Update policy.scopes to include "${t}" or request additional permissions`};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Scope "${t}" is not allowed by policy`,e))}}if(o.limits?.callsPerMinute){const e=this.checkRateLimit(t,o.limits.callsPerMinute);if(!e.ok)return e}const i=this.extractAmount(n);if(null!==i){if(o.limits?.amountPerTxn&&i>o.limits.amountPerTxn){const t={requested:i,allowed:o.limits.amountPerTxn,constraint:"amountPerTxn",fix:`Reduce amount to ${o.limits.amountPerTxn} or less, or update policy.limits.amountPerTxn`};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Amount ${i} exceeds per-transaction limit of ${o.limits.amountPerTxn}`,t))}if(o.limits?.dailyAmount){const e=this.checkDailyLimit(t,i,o.limits.dailyAmount);if(!e.ok)return e}if(o.limits?.monthlyAmount){const e=this.checkMonthlyLimit(t,i,o.limits.monthlyAmount);if(!e.ok)return e}}return(0,shared_1.ok)(void 0)}recordCall(t){const e=Date.now(),n=this.rateLimits.get(t)??{calls:[],windowStart:e};n.calls.push(e);const o=e-6e4;n.calls=n.calls.filter(t=>t>o),this.rateLimits.set(t,n)}recordSpending(t,e){const n=this.getCurrentDay(),o=this.getCurrentMonth(),i=this.dailySpending.get(t);i&&i.day===n?i.amount+=e:this.dailySpending.set(t,{amount:e,day:n});const l=this.monthlySpending.get(t);l&&l.month===o?l.amount+=e:this.monthlySpending.set(t,{amount:e,month:o})}getCurrentRateLimit(t){const e=this.rateLimits.get(t);if(!e)return 0;const n=Date.now()-6e4;return e.calls.filter(t=>t>n).length}getDailySpending(t){const e=this.getCurrentDay(),n=this.dailySpending.get(t);return n&&n.day===e?n.amount:0}getMonthlySpending(t){const e=this.getCurrentMonth(),n=this.monthlySpending.get(t);return n&&n.month===e?n.amount:0}reset(t){this.rateLimits.delete(t),this.dailySpending.delete(t),this.monthlySpending.delete(t)}checkRateLimit(t,e){const n=this.getCurrentRateLimit(t);if(n>=e){const t={requested:n+1,allowed:e,constraint:"callsPerMinute",current:n,fix:"Wait before making additional calls, or update policy.limits.callsPerMinute to a higher value"};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Rate limit exceeded: ${n}/${e} calls per minute`,t))}return(0,shared_1.ok)(void 0)}checkDailyLimit(t,e,n){const o=this.getDailySpending(t),i=o+e;if(i>n){const t=n-o,l={requested:e,allowed:n,constraint:"dailyAmount",current:o,newTotal:i,fix:t>0?`Reduce amount to ${t} or less (remaining today), or update policy.limits.dailyAmount`:"Daily limit already reached. Wait until tomorrow or update policy.limits.dailyAmount"};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Amount ${e} would exceed daily limit: ${i}/${n} (current: ${o})`,l))}return(0,shared_1.ok)(void 0)}extractAmount(t){if("object"!=typeof t||null===t)return null;const e=t;return"number"==typeof e.amount?e.amount:"number"==typeof e.value?e.value:"number"==typeof e.price?e.price:"number"==typeof e.total?e.total:null}getCurrentDay(){return(new Date).toISOString().split("T")[0]??""}getCurrentMonth(){return(new Date).toISOString().substring(0,7)}checkMonthlyLimit(t,e,n){const o=this.getMonthlySpending(t),i=o+e;if(i>n){const t=n-o,l={requested:e,allowed:n,constraint:"dailyAmount",current:o,newTotal:i,fix:t>0?`Reduce amount to ${t} or less (remaining this month), or update policy.limits.monthlyAmount`:"Monthly limit already reached. Wait until next month or update policy.limits.monthlyAmount"};return(0,shared_1.err)(new agent_call_js_1.AgentError(agent_call_js_1.AgentErrorCode.POLICY_VIOLATION,`Amount ${e} would exceed monthly limit: ${i}/${n} (current: ${o})`,l))}return(0,shared_1.ok)(void 0)}}exports.PolicyEngine=PolicyEngine;let globalPolicyEngine=null;function getGlobalPolicyEngine(){return globalPolicyEngine||(globalPolicyEngine=new PolicyEngine),globalPolicyEngine}