wu-framework 1.1.14 → 1.1.16

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 (90) hide show
  1. package/LICENSE +39 -39
  2. package/README.md +408 -408
  3. package/dist/wu-framework.cjs.js.map +1 -1
  4. package/dist/wu-framework.dev.js +15151 -15151
  5. package/dist/wu-framework.dev.js.map +1 -1
  6. package/dist/wu-framework.esm.js.map +1 -1
  7. package/dist/wu-framework.umd.js.map +1 -1
  8. package/integrations/astro/README.md +127 -127
  9. package/integrations/astro/WuApp.astro +63 -63
  10. package/integrations/astro/WuShell.astro +39 -39
  11. package/integrations/astro/index.js +68 -68
  12. package/integrations/astro/package.json +38 -38
  13. package/integrations/astro/types.d.ts +53 -53
  14. package/package.json +161 -161
  15. package/src/adapters/angular/ai.js +30 -30
  16. package/src/adapters/angular/index.d.ts +154 -154
  17. package/src/adapters/angular/index.js +932 -932
  18. package/src/adapters/angular.d.ts +3 -3
  19. package/src/adapters/angular.js +3 -3
  20. package/src/adapters/index.js +168 -168
  21. package/src/adapters/lit/ai.js +20 -20
  22. package/src/adapters/lit/index.d.ts +120 -120
  23. package/src/adapters/lit/index.js +721 -721
  24. package/src/adapters/lit.d.ts +3 -3
  25. package/src/adapters/lit.js +3 -3
  26. package/src/adapters/preact/ai.js +33 -33
  27. package/src/adapters/preact/index.d.ts +108 -108
  28. package/src/adapters/preact/index.js +661 -661
  29. package/src/adapters/preact.d.ts +3 -3
  30. package/src/adapters/preact.js +3 -3
  31. package/src/adapters/react/index.js +48 -54
  32. package/src/adapters/react.d.ts +3 -3
  33. package/src/adapters/react.js +3 -3
  34. package/src/adapters/shared.js +64 -64
  35. package/src/adapters/solid/ai.js +32 -32
  36. package/src/adapters/solid/index.d.ts +101 -101
  37. package/src/adapters/solid/index.js +586 -586
  38. package/src/adapters/solid.d.ts +3 -3
  39. package/src/adapters/solid.js +3 -3
  40. package/src/adapters/svelte/ai.js +31 -31
  41. package/src/adapters/svelte/index.d.ts +166 -166
  42. package/src/adapters/svelte/index.js +798 -798
  43. package/src/adapters/svelte.d.ts +3 -3
  44. package/src/adapters/svelte.js +3 -3
  45. package/src/adapters/vanilla/ai.js +30 -30
  46. package/src/adapters/vanilla/index.d.ts +179 -179
  47. package/src/adapters/vanilla/index.js +785 -785
  48. package/src/adapters/vanilla.d.ts +3 -3
  49. package/src/adapters/vanilla.js +3 -3
  50. package/src/adapters/vue/ai.js +52 -52
  51. package/src/adapters/vue/index.d.ts +299 -299
  52. package/src/adapters/vue/index.js +610 -610
  53. package/src/adapters/vue.d.ts +3 -3
  54. package/src/adapters/vue.js +3 -3
  55. package/src/ai/wu-ai-actions.js +261 -261
  56. package/src/ai/wu-ai-agent.js +546 -546
  57. package/src/ai/wu-ai-browser-primitives.js +354 -354
  58. package/src/ai/wu-ai-browser.js +380 -380
  59. package/src/ai/wu-ai-context.js +332 -332
  60. package/src/ai/wu-ai-conversation.js +613 -613
  61. package/src/ai/wu-ai-orchestrate.js +1021 -1021
  62. package/src/ai/wu-ai-permissions.js +381 -381
  63. package/src/ai/wu-ai-provider.js +700 -700
  64. package/src/ai/wu-ai-schema.js +225 -225
  65. package/src/ai/wu-ai-triggers.js +396 -396
  66. package/src/ai/wu-ai.js +804 -804
  67. package/src/core/wu-app.js +236 -236
  68. package/src/core/wu-cache.js +477 -477
  69. package/src/core/wu-core.js +1398 -1398
  70. package/src/core/wu-error-boundary.js +382 -382
  71. package/src/core/wu-event-bus.js +348 -348
  72. package/src/core/wu-hooks.js +350 -350
  73. package/src/core/wu-html-parser.js +190 -190
  74. package/src/core/wu-iframe-sandbox.js +328 -328
  75. package/src/core/wu-loader.js +272 -272
  76. package/src/core/wu-logger.js +134 -134
  77. package/src/core/wu-manifest.js +509 -509
  78. package/src/core/wu-mcp-bridge.js +432 -432
  79. package/src/core/wu-overrides.js +510 -510
  80. package/src/core/wu-performance.js +228 -228
  81. package/src/core/wu-plugin.js +348 -348
  82. package/src/core/wu-prefetch.js +414 -414
  83. package/src/core/wu-proxy-sandbox.js +476 -476
  84. package/src/core/wu-sandbox.js +779 -779
  85. package/src/core/wu-script-executor.js +113 -113
  86. package/src/core/wu-snapshot-sandbox.js +227 -227
  87. package/src/core/wu-strategies.js +256 -256
  88. package/src/core/wu-style-bridge.js +477 -477
  89. package/src/index.js +224 -224
  90. package/src/utils/dependency-resolver.js +327 -327
@@ -1,381 +1,381 @@
1
- /**
2
- * WU-AI-PERMISSIONS: Security, rate limiting, circuit breaker, loop protection
3
- *
4
- * 4-layer defense:
5
- * 1. Permission flags (readStore, writeStore, emitEvents, etc.)
6
- * 2. Rate limiting (per-minute, per-namespace, concurrent)
7
- * 3. Circuit breaker (CLOSED → OPEN → HALF-OPEN)
8
- * 4. Loop protection (depth counter + causal chain tracking)
9
- */
10
-
11
- import { logger } from '../core/wu-logger.js';
12
-
13
- // ─── Permission Defaults ─────────────────────────────────────────
14
-
15
- const DEFAULT_PERMISSIONS = {
16
- readStore: true,
17
- writeStore: false,
18
- emitEvents: true,
19
- readDOM: false,
20
- modifyDOM: false,
21
- executeActions: true,
22
- allowDirectKey: false,
23
- };
24
-
25
- // ─── Circuit Breaker States ──────────────────────────────────────
26
-
27
- const CB_CLOSED = 'closed';
28
- const CB_OPEN = 'open';
29
- const CB_HALF_OPEN = 'half-open';
30
-
31
- // ─── Rate Limiter ────────────────────────────────────────────────
32
-
33
- class RateLimiter {
34
- constructor(config = {}) {
35
- this._maxPerMinute = config.requestsPerMinute ?? 20;
36
- this._maxPerMinutePerNs = config.requestsPerMinutePerNs ?? 10;
37
- this._maxConcurrent = config.maxConcurrent ?? 3;
38
-
39
- this._globalTimestamps = [];
40
- this._nsTimestamps = new Map();
41
- this._concurrent = 0;
42
- }
43
-
44
- configure(config) {
45
- if (config.requestsPerMinute !== undefined) this._maxPerMinute = config.requestsPerMinute;
46
- if (config.requestsPerMinutePerNs !== undefined) this._maxPerMinutePerNs = config.requestsPerMinutePerNs;
47
- if (config.maxConcurrent !== undefined) this._maxConcurrent = config.maxConcurrent;
48
- }
49
-
50
- canSend(namespace = 'default') {
51
- this._pruneOld();
52
-
53
- if (this._concurrent >= this._maxConcurrent) {
54
- return { allowed: false, reason: `Max concurrent (${this._maxConcurrent}) reached` };
55
- }
56
- if (this._globalTimestamps.length >= this._maxPerMinute) {
57
- return { allowed: false, reason: `Global rate limit (${this._maxPerMinute}/min) exceeded` };
58
- }
59
-
60
- const nsTs = this._nsTimestamps.get(namespace) || [];
61
- if (nsTs.length >= this._maxPerMinutePerNs) {
62
- return { allowed: false, reason: `Namespace '${namespace}' rate limit (${this._maxPerMinutePerNs}/min) exceeded` };
63
- }
64
-
65
- return { allowed: true };
66
- }
67
-
68
- recordStart(namespace = 'default') {
69
- const now = Date.now();
70
- this._globalTimestamps.push(now);
71
- if (!this._nsTimestamps.has(namespace)) this._nsTimestamps.set(namespace, []);
72
- this._nsTimestamps.get(namespace).push(now);
73
- this._concurrent++;
74
- }
75
-
76
- recordEnd() {
77
- this._concurrent = Math.max(0, this._concurrent - 1);
78
- }
79
-
80
- _pruneOld() {
81
- const cutoff = Date.now() - 60000;
82
- this._globalTimestamps = this._globalTimestamps.filter(t => t > cutoff);
83
- for (const [ns, timestamps] of this._nsTimestamps) {
84
- const pruned = timestamps.filter(t => t > cutoff);
85
- if (pruned.length === 0) this._nsTimestamps.delete(ns);
86
- else this._nsTimestamps.set(ns, pruned);
87
- }
88
- }
89
-
90
- getStats() {
91
- this._pruneOld();
92
- return {
93
- globalRequestsLastMinute: this._globalTimestamps.length,
94
- concurrent: this._concurrent,
95
- maxPerMinute: this._maxPerMinute,
96
- maxConcurrent: this._maxConcurrent,
97
- };
98
- }
99
- }
100
-
101
- // ─── Circuit Breaker ─────────────────────────────────────────────
102
-
103
- class CircuitBreaker {
104
- constructor(config = {}) {
105
- this._state = CB_CLOSED;
106
- this._failureCount = 0;
107
- this._maxFailures = config.maxFailures ?? 3;
108
- this._cooldownMs = config.cooldownMs ?? 30000;
109
- this._openedAt = 0;
110
- this._rapidFireThreshold = config.rapidFireThreshold ?? 5;
111
- this._rapidFireWindowMs = config.rapidFireWindowMs ?? 2000;
112
- this._recentRequests = [];
113
- }
114
-
115
- configure(config) {
116
- if (config.maxFailures !== undefined) this._maxFailures = config.maxFailures;
117
- if (config.cooldownMs !== undefined) this._cooldownMs = config.cooldownMs;
118
- }
119
-
120
- canPass() {
121
- if (this._state === CB_CLOSED) return { allowed: true };
122
-
123
- if (this._state === CB_OPEN) {
124
- if (Date.now() - this._openedAt >= this._cooldownMs) {
125
- this._state = CB_HALF_OPEN;
126
- logger.wuDebug('[wu-ai] Circuit breaker → HALF-OPEN (testing)');
127
- return { allowed: true };
128
- }
129
- const remainingMs = this._cooldownMs - (Date.now() - this._openedAt);
130
- return { allowed: false, reason: `Circuit breaker OPEN (${Math.ceil(remainingMs / 1000)}s remaining)` };
131
- }
132
-
133
- // HALF-OPEN: allow one request through
134
- return { allowed: true };
135
- }
136
-
137
- recordSuccess() {
138
- if (this._state === CB_HALF_OPEN) {
139
- this._state = CB_CLOSED;
140
- this._failureCount = 0;
141
- logger.wuInfo('[wu-ai] Circuit breaker → CLOSED (recovered)');
142
- } else {
143
- this._failureCount = 0;
144
- }
145
- this._recordRequest();
146
- }
147
-
148
- recordFailure() {
149
- this._failureCount++;
150
- this._recordRequest();
151
-
152
- if (this._state === CB_HALF_OPEN) {
153
- this._tripOpen('Failed during half-open test');
154
- return;
155
- }
156
-
157
- if (this._failureCount >= this._maxFailures) {
158
- this._tripOpen(`${this._failureCount} consecutive failures`);
159
- }
160
- }
161
-
162
- _recordRequest() {
163
- const now = Date.now();
164
- this._recentRequests.push(now);
165
- this._recentRequests = this._recentRequests.filter(t => now - t < this._rapidFireWindowMs);
166
-
167
- if (this._state === CB_CLOSED && this._recentRequests.length >= this._rapidFireThreshold) {
168
- this._tripOpen(`${this._recentRequests.length} requests in ${this._rapidFireWindowMs}ms (rapid fire)`);
169
- }
170
- }
171
-
172
- _tripOpen(reason) {
173
- this._state = CB_OPEN;
174
- this._openedAt = Date.now();
175
- logger.wuWarn(`[wu-ai] Circuit breaker → OPEN: ${reason}. Cooldown: ${this._cooldownMs / 1000}s`);
176
- }
177
-
178
- getState() {
179
- return this._state;
180
- }
181
-
182
- getStats() {
183
- return {
184
- state: this._state,
185
- failureCount: this._failureCount,
186
- maxFailures: this._maxFailures,
187
- cooldownMs: this._cooldownMs,
188
- openedAt: this._openedAt,
189
- };
190
- }
191
-
192
- reset() {
193
- this._state = CB_CLOSED;
194
- this._failureCount = 0;
195
- this._openedAt = 0;
196
- this._recentRequests = [];
197
- }
198
- }
199
-
200
- // ─── Loop Protection ─────────────────────────────────────────────
201
-
202
- class LoopProtection {
203
- constructor(config = {}) {
204
- this._maxDepth = config.maxDepth ?? 3;
205
- this._activeTraces = new Map(); // traceId → count
206
- this._traceLog = []; // last N traces for debugging
207
- this._maxTraceLog = 50;
208
- }
209
-
210
- configure(config) {
211
- if (config.maxDepth !== undefined) this._maxDepth = config.maxDepth;
212
- }
213
-
214
- /**
215
- * Check if a request at the given depth/trace is allowed.
216
- * @param {number} depth - Current AI depth
217
- * @param {string} traceId - Causal chain trace ID
218
- * @returns {{ allowed: boolean, reason?: string }}
219
- */
220
- canProceed(depth, traceId) {
221
- if (depth > this._maxDepth) {
222
- return { allowed: false, reason: `Max AI depth (${this._maxDepth}) exceeded at depth ${depth}` };
223
- }
224
-
225
- if (traceId) {
226
- const count = (this._activeTraces.get(traceId) || 0) + 1;
227
- if (count > this._maxDepth) {
228
- return { allowed: false, reason: `Causal chain '${traceId}' looped ${count} times (max ${this._maxDepth})` };
229
- }
230
- }
231
-
232
- return { allowed: true };
233
- }
234
-
235
- /**
236
- * Record that a trace is being processed.
237
- */
238
- enter(traceId) {
239
- if (!traceId) return;
240
- const count = (this._activeTraces.get(traceId) || 0) + 1;
241
- this._activeTraces.set(traceId, count);
242
-
243
- this._traceLog.push({ traceId, count, timestamp: Date.now() });
244
- if (this._traceLog.length > this._maxTraceLog) {
245
- this._traceLog.shift();
246
- }
247
- }
248
-
249
- /**
250
- * Record that a trace finished processing.
251
- */
252
- exit(traceId) {
253
- if (!traceId) return;
254
- const count = (this._activeTraces.get(traceId) || 0) - 1;
255
- if (count <= 0) this._activeTraces.delete(traceId);
256
- else this._activeTraces.set(traceId, count);
257
- }
258
-
259
- /**
260
- * Generate a new trace ID.
261
- */
262
- createTraceId() {
263
- return `t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
264
- }
265
-
266
- getTraces() {
267
- return [...this._traceLog];
268
- }
269
-
270
- getStats() {
271
- return {
272
- maxDepth: this._maxDepth,
273
- activeTraces: this._activeTraces.size,
274
- traceLogSize: this._traceLog.length,
275
- };
276
- }
277
- }
278
-
279
- // ─── Main Permissions Class ──────────────────────────────────────
280
-
281
- export class WuAIPermissions {
282
- constructor(config = {}) {
283
- this._permissions = { ...DEFAULT_PERMISSIONS };
284
- this.rateLimiter = new RateLimiter(config.rateLimit);
285
- this.circuitBreaker = new CircuitBreaker(config.circuitBreaker);
286
- this.loopProtection = new LoopProtection(config.loopProtection);
287
- this._allowedDomains = config.allowedDomains || [];
288
-
289
- if (config.permissions) {
290
- this.configure(config.permissions);
291
- }
292
- }
293
-
294
- // ── Permission checks ──
295
-
296
- configure(permissions) {
297
- Object.assign(this._permissions, permissions);
298
-
299
- // HARD BLOCK: never allow direct API key in production
300
- if (this._isProduction() && this._permissions.allowDirectKey) {
301
- logger.wuWarn('[wu-ai] allowDirectKey FORCED to false in production');
302
- this._permissions.allowDirectKey = false;
303
- }
304
- }
305
-
306
- check(permission) {
307
- return this._permissions[permission] === true;
308
- }
309
-
310
- getPermissions() {
311
- return { ...this._permissions };
312
- }
313
-
314
- // ── Domain whitelist for action fetch ──
315
-
316
- setAllowedDomains(domains) {
317
- this._allowedDomains = domains;
318
- }
319
-
320
- isDomainAllowed(url) {
321
- if (this._allowedDomains.length === 0) return true;
322
- try {
323
- const hostname = new URL(url).hostname;
324
- return this._allowedDomains.some(pattern => {
325
- if (pattern.startsWith('*.')) {
326
- const suffix = pattern.slice(2);
327
- return hostname === suffix || hostname.endsWith('.' + suffix);
328
- }
329
- return hostname === pattern;
330
- });
331
- } catch {
332
- return false;
333
- }
334
- }
335
-
336
- // ── Full pre-flight check ──
337
-
338
- /**
339
- * Run all checks before sending an AI request.
340
- * @param {{ namespace?: string, depth?: number, traceId?: string }} meta
341
- * @returns {{ allowed: boolean, reason?: string }}
342
- */
343
- preflight(meta = {}) {
344
- // 1. Circuit breaker
345
- const cb = this.circuitBreaker.canPass();
346
- if (!cb.allowed) return cb;
347
-
348
- // 2. Rate limiter
349
- const rl = this.rateLimiter.canSend(meta.namespace);
350
- if (!rl.allowed) return rl;
351
-
352
- // 3. Loop protection
353
- const lp = this.loopProtection.canProceed(meta.depth || 0, meta.traceId);
354
- if (!lp.allowed) return lp;
355
-
356
- return { allowed: true };
357
- }
358
-
359
- // ── Stats ──
360
-
361
- getStats() {
362
- return {
363
- permissions: { ...this._permissions },
364
- rateLimiter: this.rateLimiter.getStats(),
365
- circuitBreaker: this.circuitBreaker.getStats(),
366
- loopProtection: this.loopProtection.getStats(),
367
- allowedDomains: [...this._allowedDomains],
368
- };
369
- }
370
-
371
- // ── Private ──
372
-
373
- _isProduction() {
374
- if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return true;
375
- if (typeof window !== 'undefined') {
376
- const h = window.location?.hostname || '';
377
- return h !== 'localhost' && h !== '127.0.0.1' && h !== '0.0.0.0' && !h.endsWith('.local');
378
- }
379
- return false;
380
- }
381
- }
1
+ /**
2
+ * WU-AI-PERMISSIONS: Security, rate limiting, circuit breaker, loop protection
3
+ *
4
+ * 4-layer defense:
5
+ * 1. Permission flags (readStore, writeStore, emitEvents, etc.)
6
+ * 2. Rate limiting (per-minute, per-namespace, concurrent)
7
+ * 3. Circuit breaker (CLOSED → OPEN → HALF-OPEN)
8
+ * 4. Loop protection (depth counter + causal chain tracking)
9
+ */
10
+
11
+ import { logger } from '../core/wu-logger.js';
12
+
13
+ // ─── Permission Defaults ─────────────────────────────────────────
14
+
15
+ const DEFAULT_PERMISSIONS = {
16
+ readStore: true,
17
+ writeStore: false,
18
+ emitEvents: true,
19
+ readDOM: false,
20
+ modifyDOM: false,
21
+ executeActions: true,
22
+ allowDirectKey: false,
23
+ };
24
+
25
+ // ─── Circuit Breaker States ──────────────────────────────────────
26
+
27
+ const CB_CLOSED = 'closed';
28
+ const CB_OPEN = 'open';
29
+ const CB_HALF_OPEN = 'half-open';
30
+
31
+ // ─── Rate Limiter ────────────────────────────────────────────────
32
+
33
+ class RateLimiter {
34
+ constructor(config = {}) {
35
+ this._maxPerMinute = config.requestsPerMinute ?? 20;
36
+ this._maxPerMinutePerNs = config.requestsPerMinutePerNs ?? 10;
37
+ this._maxConcurrent = config.maxConcurrent ?? 3;
38
+
39
+ this._globalTimestamps = [];
40
+ this._nsTimestamps = new Map();
41
+ this._concurrent = 0;
42
+ }
43
+
44
+ configure(config) {
45
+ if (config.requestsPerMinute !== undefined) this._maxPerMinute = config.requestsPerMinute;
46
+ if (config.requestsPerMinutePerNs !== undefined) this._maxPerMinutePerNs = config.requestsPerMinutePerNs;
47
+ if (config.maxConcurrent !== undefined) this._maxConcurrent = config.maxConcurrent;
48
+ }
49
+
50
+ canSend(namespace = 'default') {
51
+ this._pruneOld();
52
+
53
+ if (this._concurrent >= this._maxConcurrent) {
54
+ return { allowed: false, reason: `Max concurrent (${this._maxConcurrent}) reached` };
55
+ }
56
+ if (this._globalTimestamps.length >= this._maxPerMinute) {
57
+ return { allowed: false, reason: `Global rate limit (${this._maxPerMinute}/min) exceeded` };
58
+ }
59
+
60
+ const nsTs = this._nsTimestamps.get(namespace) || [];
61
+ if (nsTs.length >= this._maxPerMinutePerNs) {
62
+ return { allowed: false, reason: `Namespace '${namespace}' rate limit (${this._maxPerMinutePerNs}/min) exceeded` };
63
+ }
64
+
65
+ return { allowed: true };
66
+ }
67
+
68
+ recordStart(namespace = 'default') {
69
+ const now = Date.now();
70
+ this._globalTimestamps.push(now);
71
+ if (!this._nsTimestamps.has(namespace)) this._nsTimestamps.set(namespace, []);
72
+ this._nsTimestamps.get(namespace).push(now);
73
+ this._concurrent++;
74
+ }
75
+
76
+ recordEnd() {
77
+ this._concurrent = Math.max(0, this._concurrent - 1);
78
+ }
79
+
80
+ _pruneOld() {
81
+ const cutoff = Date.now() - 60000;
82
+ this._globalTimestamps = this._globalTimestamps.filter(t => t > cutoff);
83
+ for (const [ns, timestamps] of this._nsTimestamps) {
84
+ const pruned = timestamps.filter(t => t > cutoff);
85
+ if (pruned.length === 0) this._nsTimestamps.delete(ns);
86
+ else this._nsTimestamps.set(ns, pruned);
87
+ }
88
+ }
89
+
90
+ getStats() {
91
+ this._pruneOld();
92
+ return {
93
+ globalRequestsLastMinute: this._globalTimestamps.length,
94
+ concurrent: this._concurrent,
95
+ maxPerMinute: this._maxPerMinute,
96
+ maxConcurrent: this._maxConcurrent,
97
+ };
98
+ }
99
+ }
100
+
101
+ // ─── Circuit Breaker ─────────────────────────────────────────────
102
+
103
+ class CircuitBreaker {
104
+ constructor(config = {}) {
105
+ this._state = CB_CLOSED;
106
+ this._failureCount = 0;
107
+ this._maxFailures = config.maxFailures ?? 3;
108
+ this._cooldownMs = config.cooldownMs ?? 30000;
109
+ this._openedAt = 0;
110
+ this._rapidFireThreshold = config.rapidFireThreshold ?? 5;
111
+ this._rapidFireWindowMs = config.rapidFireWindowMs ?? 2000;
112
+ this._recentRequests = [];
113
+ }
114
+
115
+ configure(config) {
116
+ if (config.maxFailures !== undefined) this._maxFailures = config.maxFailures;
117
+ if (config.cooldownMs !== undefined) this._cooldownMs = config.cooldownMs;
118
+ }
119
+
120
+ canPass() {
121
+ if (this._state === CB_CLOSED) return { allowed: true };
122
+
123
+ if (this._state === CB_OPEN) {
124
+ if (Date.now() - this._openedAt >= this._cooldownMs) {
125
+ this._state = CB_HALF_OPEN;
126
+ logger.wuDebug('[wu-ai] Circuit breaker → HALF-OPEN (testing)');
127
+ return { allowed: true };
128
+ }
129
+ const remainingMs = this._cooldownMs - (Date.now() - this._openedAt);
130
+ return { allowed: false, reason: `Circuit breaker OPEN (${Math.ceil(remainingMs / 1000)}s remaining)` };
131
+ }
132
+
133
+ // HALF-OPEN: allow one request through
134
+ return { allowed: true };
135
+ }
136
+
137
+ recordSuccess() {
138
+ if (this._state === CB_HALF_OPEN) {
139
+ this._state = CB_CLOSED;
140
+ this._failureCount = 0;
141
+ logger.wuInfo('[wu-ai] Circuit breaker → CLOSED (recovered)');
142
+ } else {
143
+ this._failureCount = 0;
144
+ }
145
+ this._recordRequest();
146
+ }
147
+
148
+ recordFailure() {
149
+ this._failureCount++;
150
+ this._recordRequest();
151
+
152
+ if (this._state === CB_HALF_OPEN) {
153
+ this._tripOpen('Failed during half-open test');
154
+ return;
155
+ }
156
+
157
+ if (this._failureCount >= this._maxFailures) {
158
+ this._tripOpen(`${this._failureCount} consecutive failures`);
159
+ }
160
+ }
161
+
162
+ _recordRequest() {
163
+ const now = Date.now();
164
+ this._recentRequests.push(now);
165
+ this._recentRequests = this._recentRequests.filter(t => now - t < this._rapidFireWindowMs);
166
+
167
+ if (this._state === CB_CLOSED && this._recentRequests.length >= this._rapidFireThreshold) {
168
+ this._tripOpen(`${this._recentRequests.length} requests in ${this._rapidFireWindowMs}ms (rapid fire)`);
169
+ }
170
+ }
171
+
172
+ _tripOpen(reason) {
173
+ this._state = CB_OPEN;
174
+ this._openedAt = Date.now();
175
+ logger.wuWarn(`[wu-ai] Circuit breaker → OPEN: ${reason}. Cooldown: ${this._cooldownMs / 1000}s`);
176
+ }
177
+
178
+ getState() {
179
+ return this._state;
180
+ }
181
+
182
+ getStats() {
183
+ return {
184
+ state: this._state,
185
+ failureCount: this._failureCount,
186
+ maxFailures: this._maxFailures,
187
+ cooldownMs: this._cooldownMs,
188
+ openedAt: this._openedAt,
189
+ };
190
+ }
191
+
192
+ reset() {
193
+ this._state = CB_CLOSED;
194
+ this._failureCount = 0;
195
+ this._openedAt = 0;
196
+ this._recentRequests = [];
197
+ }
198
+ }
199
+
200
+ // ─── Loop Protection ─────────────────────────────────────────────
201
+
202
+ class LoopProtection {
203
+ constructor(config = {}) {
204
+ this._maxDepth = config.maxDepth ?? 3;
205
+ this._activeTraces = new Map(); // traceId → count
206
+ this._traceLog = []; // last N traces for debugging
207
+ this._maxTraceLog = 50;
208
+ }
209
+
210
+ configure(config) {
211
+ if (config.maxDepth !== undefined) this._maxDepth = config.maxDepth;
212
+ }
213
+
214
+ /**
215
+ * Check if a request at the given depth/trace is allowed.
216
+ * @param {number} depth - Current AI depth
217
+ * @param {string} traceId - Causal chain trace ID
218
+ * @returns {{ allowed: boolean, reason?: string }}
219
+ */
220
+ canProceed(depth, traceId) {
221
+ if (depth > this._maxDepth) {
222
+ return { allowed: false, reason: `Max AI depth (${this._maxDepth}) exceeded at depth ${depth}` };
223
+ }
224
+
225
+ if (traceId) {
226
+ const count = (this._activeTraces.get(traceId) || 0) + 1;
227
+ if (count > this._maxDepth) {
228
+ return { allowed: false, reason: `Causal chain '${traceId}' looped ${count} times (max ${this._maxDepth})` };
229
+ }
230
+ }
231
+
232
+ return { allowed: true };
233
+ }
234
+
235
+ /**
236
+ * Record that a trace is being processed.
237
+ */
238
+ enter(traceId) {
239
+ if (!traceId) return;
240
+ const count = (this._activeTraces.get(traceId) || 0) + 1;
241
+ this._activeTraces.set(traceId, count);
242
+
243
+ this._traceLog.push({ traceId, count, timestamp: Date.now() });
244
+ if (this._traceLog.length > this._maxTraceLog) {
245
+ this._traceLog.shift();
246
+ }
247
+ }
248
+
249
+ /**
250
+ * Record that a trace finished processing.
251
+ */
252
+ exit(traceId) {
253
+ if (!traceId) return;
254
+ const count = (this._activeTraces.get(traceId) || 0) - 1;
255
+ if (count <= 0) this._activeTraces.delete(traceId);
256
+ else this._activeTraces.set(traceId, count);
257
+ }
258
+
259
+ /**
260
+ * Generate a new trace ID.
261
+ */
262
+ createTraceId() {
263
+ return `t_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
264
+ }
265
+
266
+ getTraces() {
267
+ return [...this._traceLog];
268
+ }
269
+
270
+ getStats() {
271
+ return {
272
+ maxDepth: this._maxDepth,
273
+ activeTraces: this._activeTraces.size,
274
+ traceLogSize: this._traceLog.length,
275
+ };
276
+ }
277
+ }
278
+
279
+ // ─── Main Permissions Class ──────────────────────────────────────
280
+
281
+ export class WuAIPermissions {
282
+ constructor(config = {}) {
283
+ this._permissions = { ...DEFAULT_PERMISSIONS };
284
+ this.rateLimiter = new RateLimiter(config.rateLimit);
285
+ this.circuitBreaker = new CircuitBreaker(config.circuitBreaker);
286
+ this.loopProtection = new LoopProtection(config.loopProtection);
287
+ this._allowedDomains = config.allowedDomains || [];
288
+
289
+ if (config.permissions) {
290
+ this.configure(config.permissions);
291
+ }
292
+ }
293
+
294
+ // ── Permission checks ──
295
+
296
+ configure(permissions) {
297
+ Object.assign(this._permissions, permissions);
298
+
299
+ // HARD BLOCK: never allow direct API key in production
300
+ if (this._isProduction() && this._permissions.allowDirectKey) {
301
+ logger.wuWarn('[wu-ai] allowDirectKey FORCED to false in production');
302
+ this._permissions.allowDirectKey = false;
303
+ }
304
+ }
305
+
306
+ check(permission) {
307
+ return this._permissions[permission] === true;
308
+ }
309
+
310
+ getPermissions() {
311
+ return { ...this._permissions };
312
+ }
313
+
314
+ // ── Domain whitelist for action fetch ──
315
+
316
+ setAllowedDomains(domains) {
317
+ this._allowedDomains = domains;
318
+ }
319
+
320
+ isDomainAllowed(url) {
321
+ if (this._allowedDomains.length === 0) return true;
322
+ try {
323
+ const hostname = new URL(url).hostname;
324
+ return this._allowedDomains.some(pattern => {
325
+ if (pattern.startsWith('*.')) {
326
+ const suffix = pattern.slice(2);
327
+ return hostname === suffix || hostname.endsWith('.' + suffix);
328
+ }
329
+ return hostname === pattern;
330
+ });
331
+ } catch {
332
+ return false;
333
+ }
334
+ }
335
+
336
+ // ── Full pre-flight check ──
337
+
338
+ /**
339
+ * Run all checks before sending an AI request.
340
+ * @param {{ namespace?: string, depth?: number, traceId?: string }} meta
341
+ * @returns {{ allowed: boolean, reason?: string }}
342
+ */
343
+ preflight(meta = {}) {
344
+ // 1. Circuit breaker
345
+ const cb = this.circuitBreaker.canPass();
346
+ if (!cb.allowed) return cb;
347
+
348
+ // 2. Rate limiter
349
+ const rl = this.rateLimiter.canSend(meta.namespace);
350
+ if (!rl.allowed) return rl;
351
+
352
+ // 3. Loop protection
353
+ const lp = this.loopProtection.canProceed(meta.depth || 0, meta.traceId);
354
+ if (!lp.allowed) return lp;
355
+
356
+ return { allowed: true };
357
+ }
358
+
359
+ // ── Stats ──
360
+
361
+ getStats() {
362
+ return {
363
+ permissions: { ...this._permissions },
364
+ rateLimiter: this.rateLimiter.getStats(),
365
+ circuitBreaker: this.circuitBreaker.getStats(),
366
+ loopProtection: this.loopProtection.getStats(),
367
+ allowedDomains: [...this._allowedDomains],
368
+ };
369
+ }
370
+
371
+ // ── Private ──
372
+
373
+ _isProduction() {
374
+ if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'production') return true;
375
+ if (typeof window !== 'undefined') {
376
+ const h = window.location?.hostname || '';
377
+ return h !== 'localhost' && h !== '127.0.0.1' && h !== '0.0.0.0' && !h.endsWith('.local');
378
+ }
379
+ return false;
380
+ }
381
+ }