@terminals-tech/sdk 1.0.0-rc.1 → 1.0.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 (82) hide show
  1. package/README.md +15 -19
  2. package/dist/WebContainerManager-4LIOGRVM.js +22 -0
  3. package/dist/browser-http-client-ZQLDWZMU.js +317 -0
  4. package/dist/cache-VKYSQRXX.js +45 -0
  5. package/dist/capabilities-MIPUMBLL.js +96 -0
  6. package/dist/chunk-2ESYSVXG.js +48 -0
  7. package/dist/chunk-2WTYE4SW.js +190 -0
  8. package/dist/chunk-3LFMIVJM.js +40 -0
  9. package/dist/chunk-ABCK4FWN.js +136 -0
  10. package/dist/chunk-AFDUOYHD.js +2060 -0
  11. package/dist/chunk-BCOQMFKT.js +265 -0
  12. package/dist/chunk-BYXBJQAS.js +0 -0
  13. package/dist/chunk-DKFJIILR.js +9798 -0
  14. package/dist/chunk-EXI3LJVJ.js +51 -0
  15. package/dist/chunk-FOXUEYWK.js +42 -0
  16. package/dist/chunk-GJWAJAX3.js +173 -0
  17. package/dist/chunk-H3POJCFA.js +333 -0
  18. package/dist/chunk-KASHT6C5.js +784 -0
  19. package/dist/chunk-KHR7ZYCX.js +4034 -0
  20. package/dist/chunk-L45BSQDJ.js +296 -0
  21. package/dist/chunk-LLGZTP3G.js +5521 -0
  22. package/dist/chunk-NTMBOESX.js +152 -0
  23. package/dist/chunk-OCLSAUCD.js +474 -0
  24. package/dist/chunk-OSSRZOGC.js +190 -0
  25. package/dist/chunk-PPFTKJDB.js +497 -0
  26. package/dist/chunk-PWAHFID5.js +381 -0
  27. package/dist/chunk-Q2VI6ICE.js +188 -0
  28. package/dist/chunk-QJFKEQHF.js +6460 -0
  29. package/dist/chunk-QWXPVB2L.js +320 -0
  30. package/dist/chunk-QWZRZKLZ.js +896 -0
  31. package/dist/chunk-STMI72WH.js +1005 -0
  32. package/dist/chunk-TSQ3BGLA.js +11945 -0
  33. package/dist/chunk-UJDUQNE2.js +79 -0
  34. package/dist/chunk-VZA2NUH3.js +118 -0
  35. package/dist/chunk-WGBCRNMB.js +1817 -0
  36. package/dist/chunk-WU4OTGJE.js +752 -0
  37. package/dist/chunk-XPJ63Y6T.js +70 -0
  38. package/dist/chunk-Y2EULKA2.js +172 -0
  39. package/dist/chunk-YJEZWCYV.js +94 -0
  40. package/dist/chunk-ZVO47SQV.js +150 -0
  41. package/dist/container-lite-QD3CRLS4.js +327 -0
  42. package/dist/core-H2UUDATO.js +146 -0
  43. package/dist/crypto-D4LMI2RN.js +45 -0
  44. package/dist/db-BWC2GGBN.js +50 -0
  45. package/dist/demo-T655Z5S4.js +87 -0
  46. package/dist/diagnostics-6RQTBR6I.js +113 -0
  47. package/dist/dist-OPDCWARF.js +727 -0
  48. package/dist/dist-VXJEKX3T.js +2441 -0
  49. package/dist/dist-VYGJXGUS.js +1008 -0
  50. package/dist/embeddings-7QXTXUMC.js +15 -0
  51. package/dist/embeddings-MAEWWUHW.js +9 -0
  52. package/dist/graph-RKMNE2X5.js +36 -0
  53. package/dist/hvm-CBEP3M4F.js +126 -0
  54. package/dist/index.cjs +49874 -8001
  55. package/dist/index.d.cts +1629 -1363
  56. package/dist/index.d.ts +1629 -1363
  57. package/dist/index.js +2462 -8130
  58. package/dist/mcp-NK34ZNM5.js +101 -0
  59. package/dist/mcp-client-service-browser-SGB2K3VZ.js +14 -0
  60. package/dist/neuro-state-XHRGIRVO.js +498 -0
  61. package/dist/nodes-K6GKI2FM.js +364 -0
  62. package/dist/package-EXUIU2RL.js +93 -0
  63. package/dist/package-VGL7HYTO.js +106 -0
  64. package/dist/package-XHMLOAQ4.js +98 -0
  65. package/dist/pg-events-QJAM2HIP.js +15 -0
  66. package/dist/pglite-adapter-43IOUBMV.js +50 -0
  67. package/dist/pgliteService-IUGNNOVU.js +258 -0
  68. package/dist/policy-IRJCM6FS.js +13 -0
  69. package/dist/registry-5WTDYQVQ.js +26 -0
  70. package/dist/registry-FW63E7FE.js +16 -0
  71. package/dist/registry-ZQ2IBLF6.js +9 -0
  72. package/dist/resolver-ALOJSOK5.js +24 -0
  73. package/dist/scheduler-B5CEYKWT.js +127 -0
  74. package/dist/secret-store-H7273UIT.js +18 -0
  75. package/dist/server-VW6DYDLH.js +18 -0
  76. package/dist/skills-VN7IN7SJ.js +6375 -0
  77. package/dist/stack-4KWCQQP7.js +103 -0
  78. package/dist/storage-L7MWNSPG.js +13 -0
  79. package/dist/supabaseService-6AYP2VY3.js +476 -0
  80. package/dist/topology-CIWWNVAN.js +13 -0
  81. package/dist/webcontainer-XWCE56F3.js +281 -0
  82. package/package.json +9 -3
@@ -0,0 +1,101 @@
1
+ import {
2
+ isNetworkAllowed,
3
+ requireNetworkApproval
4
+ } from "./chunk-UJDUQNE2.js";
5
+ import "./chunk-WGBCRNMB.js";
6
+ import "./chunk-3LFMIVJM.js";
7
+ import "./chunk-AFDUOYHD.js";
8
+ import "./chunk-NTMBOESX.js";
9
+ import "./chunk-2ESYSVXG.js";
10
+
11
+ // ../../lib/terminals-tech/machines/core/runners/mcp.ts
12
+ function extractUrls(input) {
13
+ const urls = [];
14
+ const extract = (obj) => {
15
+ if (typeof obj === "string") {
16
+ try {
17
+ const url = new URL(obj);
18
+ if (url.protocol === "http:" || url.protocol === "https:") {
19
+ urls.push(obj);
20
+ }
21
+ } catch {
22
+ }
23
+ } else if (Array.isArray(obj)) {
24
+ obj.forEach(extract);
25
+ } else if (obj && typeof obj === "object") {
26
+ Object.values(obj).forEach(extract);
27
+ }
28
+ };
29
+ extract(input);
30
+ return urls;
31
+ }
32
+ async function runMcpNode(manifest, input, ctx) {
33
+ const mcpConfig = manifest.mcp;
34
+ const server = mcpConfig?.server;
35
+ if (server) {
36
+ const allowed = isNetworkAllowed(ctx.policies, server) || await requireNetworkApproval(ctx.stackId, ctx.nodeId, ctx.policies, server);
37
+ if (!allowed) {
38
+ return {
39
+ input,
40
+ runtime: "mcp:policy-denied",
41
+ error: `MCP server egress denied: ${server}`
42
+ };
43
+ }
44
+ }
45
+ const inputUrls = extractUrls(input);
46
+ for (const url of inputUrls) {
47
+ const allowed = isNetworkAllowed(ctx.policies, url) || await requireNetworkApproval(ctx.stackId, ctx.nodeId, ctx.policies, url);
48
+ if (!allowed) {
49
+ return {
50
+ input,
51
+ runtime: "mcp:policy-denied",
52
+ error: `Network egress denied for URL in input: ${url}`
53
+ };
54
+ }
55
+ }
56
+ const { MCPClientServiceBrowser } = await import("./mcp-client-service-browser-SGB2K3VZ.js");
57
+ const mcpClient = MCPClientServiceBrowser.getInstance();
58
+ const servers = mcpClient.getServers();
59
+ const targetServer = servers.find(
60
+ (s) => s.id === mcpConfig?.provider || s.name === mcpConfig?.provider || s.process?.serverUrl === server
61
+ );
62
+ if (!targetServer) {
63
+ return {
64
+ input,
65
+ runtime: "mcp:error",
66
+ error: `No MCP server available for provider: ${mcpConfig?.provider || "unknown"}`
67
+ };
68
+ }
69
+ const toolName = mcpConfig?.tool || input.tool;
70
+ if (toolName) {
71
+ try {
72
+ const result = await mcpClient.executeTool(targetServer.id, toolName, input);
73
+ return {
74
+ input,
75
+ runtime: "mcp",
76
+ serverId: targetServer.id,
77
+ tool: toolName,
78
+ result
79
+ };
80
+ } catch (error) {
81
+ return {
82
+ input,
83
+ runtime: "mcp:error",
84
+ serverId: targetServer.id,
85
+ tool: toolName,
86
+ error: error.message
87
+ };
88
+ }
89
+ }
90
+ return {
91
+ input,
92
+ runtime: "mcp",
93
+ serverId: targetServer.id,
94
+ serverName: targetServer.name,
95
+ status: targetServer.status,
96
+ availableTools: targetServer.tools?.map((t) => t.name) || []
97
+ };
98
+ }
99
+ export {
100
+ runMcpNode
101
+ };
@@ -0,0 +1,14 @@
1
+ import {
2
+ KNOWN_MCP_SERVERS,
3
+ MCPClientServiceBrowser,
4
+ mcp_client_service_browser_default
5
+ } from "./chunk-DKFJIILR.js";
6
+ import "./chunk-KHR7ZYCX.js";
7
+ import "./chunk-OSSRZOGC.js";
8
+ import "./chunk-QJFKEQHF.js";
9
+ import "./chunk-2ESYSVXG.js";
10
+ export {
11
+ KNOWN_MCP_SERVERS,
12
+ MCPClientServiceBrowser,
13
+ mcp_client_service_browser_default as default
14
+ };
@@ -0,0 +1,498 @@
1
+ import {
2
+ onOrchestratorEvent
3
+ } from "./chunk-Q2VI6ICE.js";
4
+ import "./chunk-PWAHFID5.js";
5
+ import "./chunk-Y2EULKA2.js";
6
+ import "./chunk-BCOQMFKT.js";
7
+ import {
8
+ getSignalBus
9
+ } from "./chunk-2WTYE4SW.js";
10
+ import "./chunk-FOXUEYWK.js";
11
+ import "./chunk-EXI3LJVJ.js";
12
+ import "./chunk-QJFKEQHF.js";
13
+ import "./chunk-ZVO47SQV.js";
14
+ import "./chunk-WGBCRNMB.js";
15
+ import "./chunk-3LFMIVJM.js";
16
+ import "./chunk-AFDUOYHD.js";
17
+ import "./chunk-NTMBOESX.js";
18
+ import "./chunk-2ESYSVXG.js";
19
+
20
+ // ../../lib/terminals-tech/brains/neuro-state.ts
21
+ import { BehaviorSubject as BehaviorSubject2, combineLatest as combineLatest2, interval, map as map2 } from "rxjs";
22
+
23
+ // ../../lib/terminals-tech/brains/core/coherence-streams.ts
24
+ import { BehaviorSubject, combineLatest, distinctUntilChanged, map } from "rxjs";
25
+ var DEFAULT_WEIGHTS = {
26
+ grounding: 0.4,
27
+ internal: 0.3,
28
+ crystallization: 0.3
29
+ };
30
+ var CoherenceStreams = class {
31
+ // ========== Internal State Subjects ==========
32
+ loadLevel$ = new BehaviorSubject("normal");
33
+ groundingFactors$ = new BehaviorSubject([]);
34
+ internalFactors$ = new BehaviorSubject([]);
35
+ crystallizationFactors$ = new BehaviorSubject([]);
36
+ // ========== Public Observable Streams ==========
37
+ /**
38
+ * Grounding score stream (0-1).
39
+ * Computed from weighted average of grounding factors.
40
+ */
41
+ grounding$;
42
+ /**
43
+ * Internal consistency score stream (0-1).
44
+ * Computed from weighted average of internal factors.
45
+ */
46
+ internal$;
47
+ /**
48
+ * Crystallization score stream (0-1).
49
+ * Computed from weighted average of crystallization factors.
50
+ */
51
+ crystallization$;
52
+ /**
53
+ * Overall coherence score stream (0-1).
54
+ * Weighted combination of grounding, internal, and crystallization.
55
+ */
56
+ overall$;
57
+ /**
58
+ * Complete coherence snapshot stream.
59
+ * Emits full metrics object with all dimensions and factors.
60
+ */
61
+ snapshot$;
62
+ constructor() {
63
+ this.grounding$ = this.groundingFactors$.pipe(
64
+ map((factors) => this.computeWeightedAverage(factors)),
65
+ distinctUntilChanged()
66
+ );
67
+ this.internal$ = this.internalFactors$.pipe(
68
+ map((factors) => this.computeWeightedAverage(factors)),
69
+ distinctUntilChanged()
70
+ );
71
+ this.crystallization$ = this.crystallizationFactors$.pipe(
72
+ map((factors) => this.computeWeightedAverage(factors)),
73
+ distinctUntilChanged()
74
+ );
75
+ this.overall$ = combineLatest([this.grounding$, this.internal$, this.crystallization$]).pipe(
76
+ map(
77
+ ([grounding, internal, crystallization]) => grounding * DEFAULT_WEIGHTS.grounding + internal * DEFAULT_WEIGHTS.internal + crystallization * DEFAULT_WEIGHTS.crystallization
78
+ ),
79
+ distinctUntilChanged()
80
+ );
81
+ this.snapshot$ = combineLatest([
82
+ this.grounding$,
83
+ this.internal$,
84
+ this.crystallization$,
85
+ this.overall$,
86
+ this.loadLevel$,
87
+ this.groundingFactors$,
88
+ this.internalFactors$,
89
+ this.crystallizationFactors$
90
+ ]).pipe(
91
+ map(
92
+ ([
93
+ grounding,
94
+ internal,
95
+ crystallization,
96
+ overall,
97
+ loadLevel,
98
+ gFactors,
99
+ iFactors,
100
+ cFactors
101
+ ]) => ({
102
+ grounding,
103
+ internal,
104
+ crystallization,
105
+ overall,
106
+ timestamp: Date.now(),
107
+ loadLevel,
108
+ groundingFactors: gFactors,
109
+ internalFactors: iFactors,
110
+ crystallizationFactors: cFactors
111
+ })
112
+ )
113
+ );
114
+ }
115
+ // ========== Public API: State Updates ==========
116
+ /**
117
+ * Update the system load level.
118
+ * Affects coherence calculation strategies.
119
+ *
120
+ * @param level - New load level
121
+ */
122
+ updateLoadLevel(level) {
123
+ this.loadLevel$.next(level);
124
+ }
125
+ /**
126
+ * Add or update a grounding factor.
127
+ * If factor with same ID exists, it is replaced.
128
+ *
129
+ * @param factor - Grounding factor to add/update
130
+ */
131
+ addGroundingFactor(factor) {
132
+ const factors = this.groundingFactors$.value;
133
+ const index = factors.findIndex((f) => f.id === factor.id);
134
+ if (index >= 0) {
135
+ factors[index] = factor;
136
+ this.groundingFactors$.next([...factors]);
137
+ } else {
138
+ this.groundingFactors$.next([...factors, factor]);
139
+ }
140
+ }
141
+ /**
142
+ * Remove a grounding factor by ID.
143
+ *
144
+ * @param id - Factor ID to remove
145
+ */
146
+ removeGroundingFactor(id) {
147
+ const factors = this.groundingFactors$.value.filter((f) => f.id !== id);
148
+ this.groundingFactors$.next(factors);
149
+ }
150
+ /**
151
+ * Add or update an internal consistency factor.
152
+ *
153
+ * @param factor - Internal factor to add/update
154
+ */
155
+ addInternalFactor(factor) {
156
+ const factors = this.internalFactors$.value;
157
+ const index = factors.findIndex((f) => f.id === factor.id);
158
+ if (index >= 0) {
159
+ factors[index] = factor;
160
+ this.internalFactors$.next([...factors]);
161
+ } else {
162
+ this.internalFactors$.next([...factors, factor]);
163
+ }
164
+ }
165
+ /**
166
+ * Remove an internal consistency factor by ID.
167
+ *
168
+ * @param id - Factor ID to remove
169
+ */
170
+ removeInternalFactor(id) {
171
+ const factors = this.internalFactors$.value.filter((f) => f.id !== id);
172
+ this.internalFactors$.next(factors);
173
+ }
174
+ /**
175
+ * Add or update a crystallization factor.
176
+ *
177
+ * @param factor - Crystallization factor to add/update
178
+ */
179
+ addCrystallizationFactor(factor) {
180
+ const factors = this.crystallizationFactors$.value;
181
+ const index = factors.findIndex((f) => f.id === factor.id);
182
+ if (index >= 0) {
183
+ factors[index] = factor;
184
+ this.crystallizationFactors$.next([...factors]);
185
+ } else {
186
+ this.crystallizationFactors$.next([...factors, factor]);
187
+ }
188
+ }
189
+ /**
190
+ * Remove a crystallization factor by ID.
191
+ *
192
+ * @param id - Factor ID to remove
193
+ */
194
+ removeCrystallizationFactor(id) {
195
+ const factors = this.crystallizationFactors$.value.filter((f) => f.id !== id);
196
+ this.crystallizationFactors$.next(factors);
197
+ }
198
+ /**
199
+ * Clear all factors and reset to defaults.
200
+ */
201
+ reset() {
202
+ this.groundingFactors$.next([]);
203
+ this.internalFactors$.next([]);
204
+ this.crystallizationFactors$.next([]);
205
+ this.loadLevel$.next("normal");
206
+ }
207
+ // ========== Public API: Snapshot Accessors ==========
208
+ /**
209
+ * Get current coherence metrics (synchronous snapshot).
210
+ *
211
+ * @returns Current coherence metrics
212
+ */
213
+ getCurrentMetrics() {
214
+ const grounding = this.computeWeightedAverage(this.groundingFactors$.value);
215
+ const internal = this.computeWeightedAverage(this.internalFactors$.value);
216
+ const crystallization = this.computeWeightedAverage(this.crystallizationFactors$.value);
217
+ const overall = grounding * DEFAULT_WEIGHTS.grounding + internal * DEFAULT_WEIGHTS.internal + crystallization * DEFAULT_WEIGHTS.crystallization;
218
+ return {
219
+ grounding,
220
+ internal,
221
+ crystallization,
222
+ overall,
223
+ timestamp: Date.now()
224
+ };
225
+ }
226
+ /**
227
+ * Get current load level.
228
+ *
229
+ * @returns Current load level
230
+ */
231
+ getCurrentLoadLevel() {
232
+ return this.loadLevel$.value;
233
+ }
234
+ /**
235
+ * Get current grounding factors.
236
+ *
237
+ * @returns Array of current grounding factors
238
+ */
239
+ getGroundingFactors() {
240
+ return [...this.groundingFactors$.value];
241
+ }
242
+ /**
243
+ * Get current internal factors.
244
+ *
245
+ * @returns Array of current internal factors
246
+ */
247
+ getInternalFactors() {
248
+ return [...this.internalFactors$.value];
249
+ }
250
+ /**
251
+ * Get current crystallization factors.
252
+ *
253
+ * @returns Array of current crystallization factors
254
+ */
255
+ getCrystallizationFactors() {
256
+ return [...this.crystallizationFactors$.value];
257
+ }
258
+ // ========== Private Helpers ==========
259
+ /**
260
+ * Compute weighted average of factors.
261
+ * Returns 0 if no factors present.
262
+ *
263
+ * @param factors - Array of factors with weight and value
264
+ * @returns Weighted average (0-1)
265
+ */
266
+ computeWeightedAverage(factors) {
267
+ if (factors.length === 0) {
268
+ return 0;
269
+ }
270
+ const totalWeight = factors.reduce((sum, f) => sum + f.weight, 0);
271
+ if (totalWeight === 0) {
272
+ return 0;
273
+ }
274
+ const weightedSum = factors.reduce((sum, f) => sum + f.weight * f.value, 0);
275
+ return Math.max(0, Math.min(1, weightedSum / totalWeight));
276
+ }
277
+ };
278
+ var globalCoherenceStreams = new CoherenceStreams();
279
+
280
+ // ../../lib/terminals-tech/mesh/convergence.ts
281
+ var DEFAULT_CONFIG = {
282
+ staleThresholdMs: 6e4,
283
+ // 1 minute
284
+ healthDecayRate: 0.1,
285
+ maxRetries: 3,
286
+ alertThreshold: 0.5
287
+ };
288
+ var taskStates = /* @__PURE__ */ new Map();
289
+ var agentStates = /* @__PURE__ */ new Map();
290
+ var metricsHistory = [];
291
+ function registerTask(id, status) {
292
+ const existing = taskStates.get(id);
293
+ const now = Date.now();
294
+ const task = existing ? {
295
+ ...existing,
296
+ status,
297
+ ...status === "running" && !existing.startedAt ? { startedAt: now } : {},
298
+ ...status === "completed" || status === "failed" ? { completedAt: now } : {}
299
+ } : {
300
+ id,
301
+ status,
302
+ createdAt: now,
303
+ retries: 0
304
+ };
305
+ taskStates.set(id, task);
306
+ return task;
307
+ }
308
+ function recordTaskCompletion(taskId, agentId, success) {
309
+ const task = taskStates.get(taskId);
310
+ if (task) {
311
+ task.status = success ? "completed" : "failed";
312
+ task.completedAt = Date.now();
313
+ if (!success) {
314
+ task.retries++;
315
+ }
316
+ }
317
+ const agent = agentStates.get(agentId);
318
+ if (agent) {
319
+ if (success) {
320
+ agent.completedTasks++;
321
+ } else {
322
+ agent.failedTasks++;
323
+ }
324
+ agent.status = "idle";
325
+ agent.currentTask = void 0;
326
+ agent.lastActivity = Date.now();
327
+ }
328
+ }
329
+ function calculateMetrics(config = {}) {
330
+ const cfg = { ...DEFAULT_CONFIG, ...config };
331
+ const now = Date.now();
332
+ const tasks = Array.from(taskStates.values());
333
+ const agents = Array.from(agentStates.values());
334
+ const pendingTasks = tasks.filter((t) => t.status === "pending" || t.status === "running");
335
+ const staleTasks = pendingTasks.filter((t) => now - t.createdAt > cfg.staleThresholdMs).length;
336
+ let agePressure = 0;
337
+ if (pendingTasks.length > 0) {
338
+ const totalAge = pendingTasks.reduce((sum, t) => sum + (now - t.createdAt), 0);
339
+ const avgAge = totalAge / pendingTasks.length;
340
+ agePressure = Math.min(1, avgAge / (cfg.staleThresholdMs * 2));
341
+ }
342
+ const fiveMinutesAgo = now - 3e5;
343
+ const recentCompleted = tasks.filter(
344
+ (t) => (t.status === "completed" || t.status === "failed") && t.completedAt && t.completedAt >= fiveMinutesAgo
345
+ ).length;
346
+ const throughput = recentCompleted / 5;
347
+ const completedTasks = tasks.filter((t) => t.status === "completed" || t.status === "failed");
348
+ const failedTasks = tasks.filter((t) => t.status === "failed");
349
+ const errorRate = completedTasks.length > 0 ? failedTasks.length / completedTasks.length : 0;
350
+ const activeAgents = agents.filter((a) => a.status === "working").length;
351
+ const idleAgents = agents.filter((a) => a.status === "idle").length;
352
+ let healthScore = 1;
353
+ healthScore -= agePressure * 0.3;
354
+ healthScore -= errorRate * 0.3;
355
+ healthScore -= staleTasks / Math.max(pendingTasks.length, 1) * 0.2;
356
+ if (idleAgents > 0 && pendingTasks.length > 0) {
357
+ healthScore -= 0.1;
358
+ }
359
+ healthScore = Math.max(0, Math.min(1, healthScore));
360
+ const metrics = {
361
+ healthScore,
362
+ agePressure,
363
+ staleTasks,
364
+ activeAgents,
365
+ throughput,
366
+ errorRate,
367
+ timestamp: now
368
+ };
369
+ metricsHistory.push(metrics);
370
+ if (metricsHistory.length > 100) {
371
+ metricsHistory.shift();
372
+ }
373
+ return metrics;
374
+ }
375
+
376
+ // ../../lib/terminals-tech/brains/neuro-state.ts
377
+ var POLL_INTERVAL_MS = 2e3;
378
+ var K_ADAPT_THRESHOLD = 0.1;
379
+ var NeuroState = class {
380
+ // Observable for convergence metrics (polled)
381
+ convergence$ = new BehaviorSubject2(calculateMetrics());
382
+ // Subscription for cleanup
383
+ pollSubscription = null;
384
+ // Last K emitted (for hysteresis)
385
+ _lastEmittedK = null;
386
+ // Unified state stream
387
+ state$;
388
+ constructor() {
389
+ if (typeof window !== "undefined") {
390
+ this.pollSubscription = interval(POLL_INTERVAL_MS).subscribe(() => {
391
+ this.convergence$.next(calculateMetrics());
392
+ });
393
+ this.initBridgeListeners();
394
+ }
395
+ this.state$ = combineLatest2([globalCoherenceStreams.snapshot$, this.convergence$]).pipe(
396
+ map2(([coherence, convergence]) => {
397
+ const mood = this.deriveMood(coherence, convergence);
398
+ return {
399
+ coherence,
400
+ convergence,
401
+ load: coherence.loadLevel,
402
+ mood,
403
+ timestamp: Date.now()
404
+ };
405
+ })
406
+ );
407
+ if (typeof window !== "undefined") {
408
+ this.state$.subscribe(({ convergence }) => {
409
+ this._adaptCoupling(convergence.healthScore);
410
+ });
411
+ }
412
+ }
413
+ /**
414
+ * Emit adaptation_required signal to update Kuramoto coupling K in ReticulumNode.
415
+ *
416
+ * K formula: K = 0.5 + healthScore × 2.5 maps [0,1] → [0.5, 3.0]
417
+ * - healthScore=0 → K=0.5 (minimal coupling, oscillators drift)
418
+ * - healthScore=1 → K=3.0 (strong coupling, enforces synchrony)
419
+ *
420
+ * Hysteresis guard: only emits if |K - lastK| > K_ADAPT_THRESHOLD.
421
+ * This prevents signal storms from tiny healthScore micro-fluctuations.
422
+ */
423
+ _adaptCoupling(healthScore) {
424
+ const K = 0.5 + healthScore * 2.5;
425
+ if (this._lastEmittedK !== null && Math.abs(K - this._lastEmittedK) < K_ADAPT_THRESHOLD) {
426
+ return;
427
+ }
428
+ this._lastEmittedK = K;
429
+ getSignalBus().emit("adaptation_required", "L4", "L3", {
430
+ type: "kuramoto_coupling",
431
+ K,
432
+ healthScore
433
+ });
434
+ }
435
+ /**
436
+ * Derives the high-level "Mood" of the system based on
437
+ * internal coherence and external convergence health.
438
+ */
439
+ deriveMood(coherence, convergence) {
440
+ if (coherence.loadLevel === "critical" || convergence.healthScore < 0.3) {
441
+ return "overloaded";
442
+ }
443
+ if (coherence.overall > 0.8 && convergence.throughput > 10) {
444
+ return "flow";
445
+ }
446
+ if (coherence.overall > 0.7) {
447
+ return "focused";
448
+ }
449
+ if (coherence.overall < 0.4 && (convergence.activeAgents || 0) > 0) {
450
+ return "chaotic";
451
+ }
452
+ return "dormant";
453
+ }
454
+ /**
455
+ * Manual refresh of convergence metrics
456
+ */
457
+ refreshConvergence() {
458
+ this.convergence$.next(calculateMetrics());
459
+ }
460
+ /**
461
+ * Cleanup subscriptions to prevent memory leaks
462
+ */
463
+ dispose() {
464
+ this.pollSubscription?.unsubscribe();
465
+ this.pollSubscription = null;
466
+ }
467
+ /**
468
+ * Initialize listeners for L2->L3 bridge events to update convergence state.
469
+ * This ensures the "Brain" is aware of "Body" (Orchestrator) actions.
470
+ */
471
+ initBridgeListeners() {
472
+ onOrchestratorEvent((data) => {
473
+ switch (data.type) {
474
+ case "run_start":
475
+ registerTask(data.event.runId, "running");
476
+ break;
477
+ case "run_complete":
478
+ recordTaskCompletion(
479
+ data.event.runId,
480
+ "orchestrator-agent",
481
+ // Default agent ID for L2
482
+ data.event.success
483
+ );
484
+ this.refreshConvergence();
485
+ break;
486
+ case "node_complete":
487
+ if (!data.event.success) {
488
+ }
489
+ break;
490
+ }
491
+ });
492
+ }
493
+ };
494
+ var neuroState = new NeuroState();
495
+ export {
496
+ NeuroState,
497
+ neuroState
498
+ };