@terminals-tech/sdk 1.0.0-rc.2 → 2.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +62 -20
  2. package/dist/{WebContainerManager-SHXC5VKI.js → WebContainerManager-NUGGUIWB.js} +2 -2
  3. package/dist/catalog-XA5VYWXG.js +16 -0
  4. package/dist/{chunk-PWAHFID5.js → chunk-D4MOOUDY.js} +3 -3
  5. package/dist/{chunk-FOXUEYWK.js → chunk-GOQHOLBG.js} +4 -3
  6. package/dist/{chunk-PUZ2S62E.js → chunk-ICFYWOI5.js} +61 -36
  7. package/dist/chunk-PKINKOW2.js +335 -0
  8. package/dist/chunk-PWEICJ47.js +30 -0
  9. package/dist/{chunk-BKB3MD5Y.js → chunk-Q4W3IUTD.js} +73 -12
  10. package/dist/{chunk-BCOQMFKT.js → chunk-TO7ETE5K.js} +2 -2
  11. package/dist/{chunk-Q2VI6ICE.js → chunk-UB5OINTA.js} +1 -1
  12. package/dist/{chunk-Q4B7YS7T.js → chunk-WJCIX7RO.js} +9 -69
  13. package/dist/{chunk-3CEM77QZ.js → chunk-WT6L6DK3.js} +30 -2
  14. package/dist/{chunk-UKVUPKZP.js → chunk-Y5WLSLLW.js} +1 -1
  15. package/dist/{container-lite-KQX3NMPY.js → container-lite-Q3O3EP6R.js} +9 -9
  16. package/dist/core.machine.orchestrator-NW73YDTL.js +24 -0
  17. package/dist/{demo-VXMGMJNK.js → demo-WARANXBT.js} +11 -11
  18. package/dist/{hvm-DRQK2MUT.js → hvm-A7DGZ3Q5.js} +1 -1
  19. package/dist/index.cjs +65114 -12973
  20. package/dist/index.d.cts +643 -146
  21. package/dist/index.d.ts +643 -146
  22. package/dist/index.js +2460 -454
  23. package/dist/{neuro-state-XHRGIRVO.js → neuro-state-KINIFV2D.js} +6 -6
  24. package/dist/{nodes-DXKYDTVO.js → nodes-TWQZUZRM.js} +153 -13
  25. package/dist/pglite-adapter-43IOUBMV.js +50 -0
  26. package/dist/{registry-BL3TDQDB.js → registry-UARRB6CF.js} +9 -9
  27. package/dist/resolver-ALOJSOK5.js +24 -0
  28. package/dist/{scheduler-H6Q53IMI.js → scheduler-SAQJLKXJ.js} +52 -45
  29. package/dist/sematon-2EUEZESN.js +19 -0
  30. package/dist/{server-7DM74VFW.js → server-JXM4Y2T6.js} +1 -1
  31. package/dist/{skills-KLTTT2RM.js → skills-XOFGMUP4.js} +2 -2
  32. package/dist/{stack-CHDAFU2S.js → stack-4QQCK7MG.js} +17 -15
  33. package/dist/{supabaseService-6AYP2VY3.js → supabaseService-O4ZFFLZP.js} +2 -2
  34. package/dist/{webcontainer-3LDJVIIL.js → webcontainer-PMWNRO4I.js} +2 -2
  35. package/package.json +10 -4
  36. package/dist/{chunk-SHPGIVDH.js → chunk-P4D4RNAV.js} +4 -4
package/dist/index.js CHANGED
@@ -1,3 +1,23 @@
1
+ import {
2
+ calculateSemanticDensity,
3
+ conditionalEntropy,
4
+ cosineSimilarity,
5
+ createSematon,
6
+ entropy,
7
+ estimateComplexity,
8
+ foldSematon,
9
+ isRealizable,
10
+ jointEntropy,
11
+ jsDivergence,
12
+ klDivergence,
13
+ measurePreservation,
14
+ mutualInformation,
15
+ normalize,
16
+ sematonDensity,
17
+ sematonDistance,
18
+ sematonEntropy,
19
+ unfoldSematon
20
+ } from "./chunk-PKINKOW2.js";
1
21
  import {
2
22
  ensureSkillsRegistered,
3
23
  getAllSkills,
@@ -5,7 +25,7 @@ import {
5
25
  getSkillCount,
6
26
  getSkillsByCategory,
7
27
  registerSkill
8
- } from "./chunk-UKVUPKZP.js";
28
+ } from "./chunk-Y5WLSLLW.js";
9
29
  import {
10
30
  createDAG,
11
31
  createDelegationChain,
@@ -24,19 +44,11 @@ import {
24
44
  wrapTo2Pi,
25
45
  wrapToPi
26
46
  } from "./chunk-WU4OTGJE.js";
27
- import "./chunk-3CEM77QZ.js";
28
- import "./chunk-BYXBJQAS.js";
29
- import {
30
- SKILL_CATEGORIES,
31
- SKILL_RANKS,
32
- SKILL_RUN_STATUSES,
33
- SKILL_TIERS
34
- } from "./chunk-ABCK4FWN.js";
35
47
  import {
36
48
  createInteractionWithEvents,
37
49
  formatAddress,
38
50
  parseAddress
39
- } from "./chunk-BCOQMFKT.js";
51
+ } from "./chunk-TO7ETE5K.js";
40
52
  import {
41
53
  createEventBus,
42
54
  createSignalBus,
@@ -44,16 +56,24 @@ import {
44
56
  getSignalBus,
45
57
  subscribeToSignals
46
58
  } from "./chunk-2WTYE4SW.js";
59
+ import "./chunk-BYXBJQAS.js";
60
+ import {
61
+ SKILL_CATEGORIES,
62
+ SKILL_RANKS,
63
+ SKILL_RUN_STATUSES,
64
+ SKILL_TIERS
65
+ } from "./chunk-ABCK4FWN.js";
47
66
  import {
48
67
  secureValidate,
49
68
  validateWithSchema
50
- } from "./chunk-FOXUEYWK.js";
69
+ } from "./chunk-GOQHOLBG.js";
70
+ import "./chunk-QJFKEQHF.js";
51
71
  import {
52
72
  unbrand,
53
73
  untrusted,
54
74
  validated
55
75
  } from "./chunk-EXI3LJVJ.js";
56
- import "./chunk-QJFKEQHF.js";
76
+ import "./chunk-WT6L6DK3.js";
57
77
  import "./chunk-XPJ63Y6T.js";
58
78
  import {
59
79
  createCircuitBreaker,
@@ -66,10 +86,207 @@ import {
66
86
  // ../../lib/terminals-tech/sdk/terminal.ts
67
87
  var terminal_exports = {};
68
88
  __export(terminal_exports, {
89
+ Terminal: () => Terminal,
69
90
  createInteraction: () => createInteractionWithEvents,
70
91
  createInteractionWithEvents: () => createInteractionWithEvents
71
92
  });
72
93
 
94
+ // ../agent-sdk/src/result.ts
95
+ function extractText(outputs) {
96
+ const keys = Object.keys(outputs);
97
+ if (keys.length === 0) return "";
98
+ const lastKey = keys[keys.length - 1];
99
+ const lastOutput = outputs[lastKey];
100
+ if (typeof lastOutput === "string") return lastOutput;
101
+ if (lastOutput && typeof lastOutput === "object" && "result" in lastOutput) {
102
+ const result = lastOutput.result;
103
+ return typeof result === "string" ? result : JSON.stringify(result);
104
+ }
105
+ return JSON.stringify(lastOutput);
106
+ }
107
+ function toTerminalResult(sematon) {
108
+ const { payload, witness } = sematon;
109
+ const outputs = payload.outputs ?? {};
110
+ const entries = Object.entries(outputs);
111
+ const steps = [];
112
+ const agents = [];
113
+ for (let i = 0; i < entries.length; i++) {
114
+ const [id, output] = entries[i];
115
+ steps.push({ agent: id, output, index: i });
116
+ agents.push({ id, output });
117
+ }
118
+ return {
119
+ text: extractText(outputs),
120
+ coherence: witness.R,
121
+ receipt: sematon,
122
+ steps,
123
+ agents,
124
+ duration: payload.duration
125
+ };
126
+ }
127
+
128
+ // ../agent-sdk/src/terminal.ts
129
+ function generateTerminalId() {
130
+ return `term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 6)}`;
131
+ }
132
+ function buildNodes(agents, task) {
133
+ return agents.map((agent, idx) => ({
134
+ id: `agent-${idx}`,
135
+ nodeRef: "provider.chat.v1",
136
+ config: {
137
+ role: agent.role,
138
+ capabilities: agent.capabilities ?? [],
139
+ prompt: task
140
+ }
141
+ }));
142
+ }
143
+ function buildEdges(agents) {
144
+ const edges = [];
145
+ for (let i = 0; i < agents.length - 1; i++) {
146
+ edges.push({
147
+ from: `agent-${i}`,
148
+ to: `agent-${i + 1}`
149
+ });
150
+ }
151
+ return edges;
152
+ }
153
+ function buildManifest(id, config) {
154
+ return {
155
+ id,
156
+ version: "1.0.0",
157
+ name: `Terminal ${id}`,
158
+ nodes: buildNodes(config.agents, config.task),
159
+ edges: buildEdges(config.agents),
160
+ layer: "L4"
161
+ };
162
+ }
163
+ function flattenOutputs(outputs) {
164
+ if (!outputs) return {};
165
+ const result = {};
166
+ for (const [nodeId, nodeOutput] of outputs) {
167
+ result[nodeId] = nodeOutput;
168
+ }
169
+ return result;
170
+ }
171
+ var Terminal = class _Terminal {
172
+ /** Unique terminal identifier */
173
+ id;
174
+ config;
175
+ manifest;
176
+ constructor(id, config) {
177
+ this.id = id;
178
+ this.config = config;
179
+ this.manifest = buildManifest(id, config);
180
+ }
181
+ /**
182
+ * Create a new Terminal from semantic configuration.
183
+ *
184
+ * Translates the developer-friendly config into internal stack manifests,
185
+ * registers required nodes, and returns a ready-to-run Terminal.
186
+ */
187
+ static async create(config) {
188
+ if (!config.agents || config.agents.length === 0) {
189
+ throw new Error("Terminal.create requires at least one agent");
190
+ }
191
+ if (!config.task || config.task.trim().length === 0) {
192
+ throw new Error("Terminal.create requires a non-empty task");
193
+ }
194
+ const id = generateTerminalId();
195
+ await import("./nodes-TWQZUZRM.js").catch(
196
+ (err2) => console.warn("[Terminal.create] Node catalog init warning:", err2)
197
+ );
198
+ await import("./catalog-XA5VYWXG.js").catch(
199
+ (err2) => console.warn("[Terminal.create] Catalog init warning:", err2)
200
+ );
201
+ return new _Terminal(id, config);
202
+ }
203
+ /**
204
+ * Execute the terminal workflow and return a Sematon-wrapped result.
205
+ *
206
+ * Uses OrchestratorV0 to run the DAG, then wraps the output
207
+ * in a Sematon<TerminalRunResult> with convergence witness.
208
+ */
209
+ async run() {
210
+ const startTime = Date.now();
211
+ const threshold = this.config.coherence?.threshold ?? 0.6;
212
+ const { createSematon: createSematon2 } = await import("./sematon-2EUEZESN.js");
213
+ const { OrchestratorV0 } = await import("./core.machine.orchestrator-NW73YDTL.js");
214
+ const { resolveNode } = await import("./catalog-XA5VYWXG.js");
215
+ const orchestrator = new OrchestratorV0(
216
+ resolveNode
217
+ );
218
+ let runResult;
219
+ try {
220
+ runResult = await orchestrator.run(this.manifest, {
221
+ terminalId: this.id,
222
+ configOverrides: this.config.provider ? Object.fromEntries(
223
+ this.manifest.nodes.map((n) => [
224
+ n.id,
225
+ {
226
+ provider: this.config.provider,
227
+ model: this.config.model
228
+ }
229
+ ])
230
+ ) : void 0
231
+ });
232
+ } finally {
233
+ orchestrator.dispose();
234
+ }
235
+ const duration = Date.now() - startTime;
236
+ const outputs = flattenOutputs(runResult.outputs);
237
+ const R = runResult.succeeded ? 0.85 : 0.2;
238
+ const converged = R >= threshold && runResult.succeeded;
239
+ const witness = {
240
+ R,
241
+ activationEntropy: Object.keys(outputs).length > 0 ? 2.5 : 0,
242
+ converged,
243
+ step: this.manifest.nodes.length
244
+ };
245
+ const payload = { outputs, duration };
246
+ return createSematon2({
247
+ kind: "custom",
248
+ payload,
249
+ witness,
250
+ source: `terminal:${this.id}`
251
+ });
252
+ }
253
+ /**
254
+ * Static convenience: create and run a terminal in one call.
255
+ * Returns a developer-friendly TerminalResult instead of a raw Sematon.
256
+ */
257
+ static async run(config) {
258
+ const terminal = await _Terminal.create(config);
259
+ const sematon = await terminal.run();
260
+ return toTerminalResult(sematon);
261
+ }
262
+ /**
263
+ * Chain a new terminal execution from a previous Sematon result.
264
+ *
265
+ * Extracts `prev.payload.outputs` and injects them as `previousOutputs`
266
+ * in the config overrides, then creates a new Terminal, runs it, and
267
+ * returns the new Sematon.
268
+ */
269
+ static async chain(prev, config) {
270
+ const prevPayload = prev.payload;
271
+ const previousOutputs = prevPayload?.outputs ?? {};
272
+ const fullConfig = {
273
+ agents: config.agents ?? [{ role: "assistant" }],
274
+ task: config.task ?? "Continue from previous results",
275
+ coherence: config.coherence,
276
+ provider: config.provider,
277
+ model: config.model
278
+ };
279
+ const terminal = await _Terminal.create(fullConfig);
280
+ for (const node of terminal.manifest.nodes) {
281
+ node.config = {
282
+ ...node.config,
283
+ previousOutputs
284
+ };
285
+ }
286
+ return terminal.run();
287
+ }
288
+ };
289
+
73
290
  // ../../lib/terminals-tech/sdk/core.ts
74
291
  var core_exports = {};
75
292
  __export(core_exports, {
@@ -275,165 +492,6 @@ function createBridge(from, to, iso) {
275
492
  };
276
493
  }
277
494
 
278
- // ../../lib/terminals-tech/core/L0/information.ts
279
- function entropy(probabilities) {
280
- if (probabilities.length === 0) return 0;
281
- const sum = probabilities.reduce((a, b) => a + b, 0);
282
- const normalized = sum === 0 ? probabilities : probabilities.map((p) => p / sum);
283
- return normalized.reduce((h, p) => {
284
- if (p <= 0) return h;
285
- return h - p * Math.log2(p);
286
- }, 0);
287
- }
288
- function jointEntropy(jointProbabilities) {
289
- const flat = jointProbabilities.flat();
290
- return entropy(flat);
291
- }
292
- function conditionalEntropy(jointProbabilities) {
293
- const hXY = jointEntropy(jointProbabilities);
294
- const pX = jointProbabilities.map((row) => row.reduce((a, b) => a + b, 0));
295
- const hX = entropy(pX);
296
- return hXY - hX;
297
- }
298
- function mutualInformation(pX, pY, pXY) {
299
- const hX = entropy(pX);
300
- const hY = entropy(pY);
301
- const hXY = jointEntropy(pXY);
302
- return Math.max(0, hX + hY - hXY);
303
- }
304
- function measurePreservation(source, transformed, roundTrip) {
305
- if (source.length === 0) {
306
- return {
307
- retention: 1,
308
- sourceEntropy: 0,
309
- targetEntropy: 0,
310
- mutualInfo: 0,
311
- lossless: true
312
- };
313
- }
314
- const sourceFreq = countFrequencies(source.map(String));
315
- const transformedFreq = countFrequencies(transformed.map(String));
316
- const n = source.length;
317
- const sourceProbabilities = Object.values(sourceFreq).map((c) => c / n);
318
- const transformedProbabilities = Object.values(transformedFreq).map((c) => c / n);
319
- const sourceEntropy = entropy(sourceProbabilities);
320
- const targetEntropy = entropy(transformedProbabilities);
321
- let retention = 1;
322
- let lossless = true;
323
- if (roundTrip) {
324
- const matches = source.filter((s, i) => String(s) === String(roundTrip[i])).length;
325
- retention = matches / source.length;
326
- lossless = matches === source.length;
327
- } else {
328
- const sourceCardinality = Object.keys(sourceFreq).length;
329
- const targetCardinality = Object.keys(transformedFreq).length;
330
- retention = Math.min(1, targetCardinality / sourceCardinality);
331
- lossless = targetCardinality >= sourceCardinality;
332
- }
333
- const minEntropy = Math.min(sourceEntropy, targetEntropy);
334
- const mutualInfo = retention * minEntropy;
335
- return {
336
- retention,
337
- sourceEntropy,
338
- targetEntropy,
339
- mutualInfo,
340
- lossless
341
- };
342
- }
343
- function calculateSemanticDensity(tokens, baselineTokensPerBit = 2) {
344
- if (tokens.length === 0) {
345
- return {
346
- tokenCount: 0,
347
- informationBits: 0,
348
- density: 0,
349
- compressionRatio: 1
350
- };
351
- }
352
- const freq = countFrequencies(tokens);
353
- const probabilities = Object.values(freq).map((c) => c / tokens.length);
354
- const informationBits = entropy(probabilities) * tokens.length;
355
- const density = tokens.length > 0 ? informationBits / tokens.length : 0;
356
- const baselineBits = tokens.length / baselineTokensPerBit;
357
- const compressionRatio = baselineBits > 0 ? informationBits / baselineBits : 1;
358
- return {
359
- tokenCount: tokens.length,
360
- informationBits,
361
- density,
362
- compressionRatio
363
- };
364
- }
365
- function estimateComplexity(data) {
366
- if (data.length === 0) return 0;
367
- const seen = /* @__PURE__ */ new Set();
368
- let uniqueSubstrings = 0;
369
- const windowSize = 8;
370
- for (let i = 0; i <= data.length - windowSize; i++) {
371
- const substr = data.slice(i, i + windowSize);
372
- if (!seen.has(substr)) {
373
- seen.add(substr);
374
- uniqueSubstrings++;
375
- }
376
- }
377
- const totalPatterns = Math.max(1, data.length - windowSize + 1);
378
- return uniqueSubstrings / totalPatterns;
379
- }
380
- function klDivergence(p, q) {
381
- if (p.length !== q.length) {
382
- throw new Error("Distributions must have same length");
383
- }
384
- let divergence = 0;
385
- for (let i = 0; i < p.length; i++) {
386
- if (p[i] > 0 && q[i] > 0) {
387
- divergence += p[i] * Math.log2(p[i] / q[i]);
388
- } else if (p[i] > 0 && q[i] === 0) {
389
- return Infinity;
390
- }
391
- }
392
- return divergence;
393
- }
394
- function jsDivergence(p, q) {
395
- if (p.length !== q.length) {
396
- throw new Error("Distributions must have same length");
397
- }
398
- const m = p.map((pi, i) => 0.5 * (pi + q[i]));
399
- let jsd = 0;
400
- for (let i = 0; i < p.length; i++) {
401
- if (p[i] > 0 && m[i] > 0) {
402
- jsd += 0.5 * p[i] * Math.log2(p[i] / m[i]);
403
- }
404
- if (q[i] > 0 && m[i] > 0) {
405
- jsd += 0.5 * q[i] * Math.log2(q[i] / m[i]);
406
- }
407
- }
408
- return jsd;
409
- }
410
- function countFrequencies(values) {
411
- const freq = {};
412
- for (const v of values) {
413
- const key = String(v);
414
- freq[key] = (freq[key] || 0) + 1;
415
- }
416
- return freq;
417
- }
418
- function normalize(values) {
419
- const sum = values.reduce((a, b) => a + b, 0);
420
- if (sum === 0) return values.map(() => 1 / values.length);
421
- return values.map((v) => v / sum);
422
- }
423
- function cosineSimilarity(a, b) {
424
- if (a.length !== b.length || a.length === 0) return 0;
425
- let dot = 0;
426
- let normA = 0;
427
- let normB = 0;
428
- for (let i = 0; i < a.length; i++) {
429
- dot += a[i] * b[i];
430
- normA += a[i] * a[i];
431
- normB += b[i] * b[i];
432
- }
433
- const denominator = Math.sqrt(normA) * Math.sqrt(normB);
434
- return denominator === 0 ? 0 : dot / denominator;
435
- }
436
-
437
495
  // ../../lib/terminals-tech/core/L0/derivation.ts
438
496
  function extractShape(value) {
439
497
  if (value === null) {
@@ -627,143 +685,6 @@ function canEmbed(source, target) {
627
685
  return true;
628
686
  }
629
687
 
630
- // ../../lib/terminals-tech/core/L0/sematon.ts
631
- var sematonCounter = 0;
632
- function fnv1a(input) {
633
- let hash = 2166136261;
634
- for (let i = 0; i < input.length; i++) {
635
- hash ^= input.charCodeAt(i);
636
- hash = Math.imul(hash, 16777619);
637
- }
638
- return (hash >>> 0).toString(16).padStart(8, "0");
639
- }
640
- function computePayloadEntropy(payload) {
641
- const json = JSON.stringify(payload);
642
- if (!json || json.length === 0) return 0;
643
- const freq = {};
644
- for (let i = 0; i < json.length; i++) {
645
- const ch = json[i];
646
- freq[ch] = (freq[ch] || 0) + 1;
647
- }
648
- const probabilities = Object.values(freq).map((c) => c / json.length);
649
- return entropy(probabilities);
650
- }
651
- function computeDensity(payload, entropyBits) {
652
- const json = JSON.stringify(payload);
653
- const tokenCount = json ? json.split(/\s+|[,{}[\]":]+/).filter(Boolean).length : 0;
654
- return tokenCount > 0 ? entropyBits / tokenCount : 0;
655
- }
656
- function generatePadicAddress(kind, counter) {
657
- const kindIndex = [
658
- "signal",
659
- "context",
660
- "fractal",
661
- "witness",
662
- "combinator",
663
- "interaction",
664
- "custom"
665
- ].indexOf(kind);
666
- return `${kindIndex}.0.${counter}`;
667
- }
668
- function createSematon(config) {
669
- const counter = ++sematonCounter;
670
- const id = `sem_${config.kind}_${counter}_${Date.now().toString(36)}`;
671
- const payloadEntropy = computePayloadEntropy(config.payload);
672
- const density = computeDensity(config.payload, payloadEntropy);
673
- const padicAddress = config.padicAddress ?? generatePadicAddress(config.kind, counter);
674
- const hashInput = [
675
- config.kind,
676
- JSON.stringify(config.payload),
677
- config.witness.R.toFixed(6),
678
- config.witness.converged.toString(),
679
- padicAddress
680
- ].join("|");
681
- const shapeHash = fnv1a(hashInput);
682
- const constructive = config.witness.converged && Number.isFinite(payloadEntropy) && payloadEntropy > 0 && JSON.stringify(config.payload) !== "null" && JSON.stringify(config.payload) !== "undefined";
683
- const impedance = density > 0 && config.witness.R > 0 ? payloadEntropy / (density * config.witness.R) : Infinity;
684
- return {
685
- id,
686
- kind: config.kind,
687
- payload: config.payload,
688
- witness: { ...config.witness },
689
- padicAddress,
690
- entropy: payloadEntropy,
691
- density,
692
- impedance,
693
- shapeHash,
694
- constructive,
695
- createdAt: Date.now(),
696
- source: config.source ?? "unknown"
697
- };
698
- }
699
- function sematonEntropy(sematon) {
700
- return sematon.entropy;
701
- }
702
- function sematonDensity(sematon) {
703
- return sematon.density;
704
- }
705
- function isRealizable(sematon) {
706
- return sematon.constructive;
707
- }
708
- function sematonDistance(a, b) {
709
- const vecA = payloadToVector(a.payload);
710
- const vecB = payloadToVector(b.payload);
711
- const cosSim = cosineSimilarity(vecA, vecB);
712
- const rProximity = 1 - Math.abs(a.witness.R - b.witness.R);
713
- const similarity = 0.7 * Math.max(0, cosSim) + 0.3 * rProximity;
714
- return 1 - similarity;
715
- }
716
- function payloadToVector(payload) {
717
- const json = JSON.stringify(payload);
718
- const vec = new Array(128).fill(0);
719
- if (!json) return vec;
720
- for (let i = 0; i < json.length; i++) {
721
- const code = json.charCodeAt(i);
722
- if (code < 128) {
723
- vec[code]++;
724
- }
725
- }
726
- const sum = vec.reduce((s, v) => s + v, 0);
727
- if (sum > 0) {
728
- for (let i = 0; i < vec.length; i++) {
729
- vec[i] /= sum;
730
- }
731
- }
732
- return vec;
733
- }
734
- function foldSematon(sematon) {
735
- return {
736
- id: sematon.id,
737
- kind: sematon.kind,
738
- payload: JSON.stringify(sematon.payload),
739
- witness: { ...sematon.witness },
740
- padicAddress: sematon.padicAddress,
741
- entropy: sematon.entropy,
742
- density: sematon.density,
743
- impedance: sematon.impedance,
744
- shapeHash: sematon.shapeHash,
745
- constructive: sematon.constructive,
746
- createdAt: sematon.createdAt,
747
- source: sematon.source
748
- };
749
- }
750
- function unfoldSematon(folded) {
751
- return {
752
- id: folded.id,
753
- kind: folded.kind,
754
- payload: JSON.parse(folded.payload),
755
- witness: { ...folded.witness },
756
- padicAddress: folded.padicAddress,
757
- entropy: folded.entropy,
758
- density: folded.density,
759
- impedance: folded.impedance,
760
- shapeHash: folded.shapeHash,
761
- constructive: folded.constructive,
762
- createdAt: folded.createdAt,
763
- source: folded.source
764
- };
765
- }
766
-
767
688
  // ../../lib/terminals-tech/core/L0/realizability.ts
768
689
  var traceCounter = 0;
769
690
  function createRealizabilityStep(index, inputs, outputs, witness) {
@@ -938,6 +859,85 @@ __export(brain_exports, {
938
859
  wrapToPi: () => wrapToPi
939
860
  });
940
861
 
862
+ // ../../lib/terminals-tech/core/primitives/coherence-heuristics.ts
863
+ var DEFAULT_HEDGING_PATTERNS = [
864
+ /\bi think\b/gi,
865
+ /\bmaybe\b/gi,
866
+ /\bperhaps\b/gi,
867
+ /\bpossibly\b/gi,
868
+ /\buncertain\b/gi,
869
+ /\bmight\b/gi
870
+ ];
871
+ var DEFAULT_CONTRADICTION_PATTERNS = [
872
+ /\bhowever\b.*\bnot\b/gi,
873
+ /\bbut\b.*\bnot\b/gi,
874
+ /\bcontrary\b/gi,
875
+ /\bcontradicts?\b/gi
876
+ ];
877
+ var DEFAULT_STRUCTURE_PATTERN = /[-*\u2022]\s|^\d+\.|#{1,3}\s/m;
878
+ var DEFAULT_ACTION_PATTERN = /\b(do|make|create|implement|use|try|start|begin|ensure|verify)\b/gi;
879
+ var DEFAULT_QUALIFIER_PATTERN = /\b(very|really|extremely|quite|somewhat|fairly)\b/gi;
880
+ function detectHedging(text, patterns = DEFAULT_HEDGING_PATTERNS) {
881
+ const hedgeCount = patterns.reduce(
882
+ (count, pattern) => count + (text.match(pattern)?.length ?? 0),
883
+ 0
884
+ );
885
+ const wordCount = text.split(/\s+/).length;
886
+ const hedgeRatio = hedgeCount / Math.max(wordCount / 50, 1);
887
+ return Math.min(1, hedgeRatio * 0.2);
888
+ }
889
+ function detectContradictions(text, patterns = DEFAULT_CONTRADICTION_PATTERNS) {
890
+ let score = 0;
891
+ for (const pattern of patterns) {
892
+ const matches = text.match(pattern);
893
+ if (matches) {
894
+ score += matches.length * 0.1;
895
+ }
896
+ }
897
+ return Math.min(1, score);
898
+ }
899
+ function measureTopicDivergence(current, history) {
900
+ if (history.length === 0) return 0;
901
+ const currentTerms = new Set(current.toLowerCase().split(/\s+/));
902
+ const historyTerms = new Set(
903
+ history.flatMap((h) => h.toLowerCase().split(/\s+/))
904
+ );
905
+ const overlap = [...currentTerms].filter((t) => historyTerms.has(t)).length;
906
+ const overlapRatio = overlap / currentTerms.size;
907
+ return overlapRatio < 0.1 ? 0.2 : 0;
908
+ }
909
+ function scoreStructure(text, config) {
910
+ const structurePattern = config?.structurePattern ?? DEFAULT_STRUCTURE_PATTERN;
911
+ const actionPattern = config?.actionPattern ?? DEFAULT_ACTION_PATTERN;
912
+ const qualifierPattern = config?.qualifierPattern ?? DEFAULT_QUALIFIER_PATTERN;
913
+ const minWords = config?.minWords ?? 10;
914
+ const maxWords = config?.maxWords ?? 500;
915
+ let adjustment = 0;
916
+ const wordCount = text.split(/\s+/).length;
917
+ if (wordCount < minWords) adjustment -= 0.2;
918
+ if (wordCount > maxWords) adjustment -= 0.1;
919
+ if (structurePattern.test(text)) adjustment += 0.1;
920
+ const actionMatches = text.match(actionPattern);
921
+ if (actionMatches && actionMatches.length > 2) adjustment += 0.1;
922
+ const qualifierCount = (text.match(qualifierPattern) ?? []).length;
923
+ if (qualifierCount > 5) adjustment -= 0.1;
924
+ return adjustment;
925
+ }
926
+ function computeFactOverlap(text, facts) {
927
+ if (facts.length === 0) return 0;
928
+ const textTerms = new Set(
929
+ text.toLowerCase().split(/\W+/).filter((t) => t.length > 2)
930
+ );
931
+ let totalOverlap = 0;
932
+ for (const fact of facts) {
933
+ const factTerms = fact.toLowerCase().split(/\W+/).filter((t) => t.length > 2);
934
+ if (factTerms.length === 0) continue;
935
+ const matched = factTerms.filter((t) => textTerms.has(t)).length;
936
+ totalOverlap += matched / factTerms.length;
937
+ }
938
+ return totalOverlap / facts.length;
939
+ }
940
+
941
941
  // ../../lib/terminals-tech/brains/core/core.brain.coherence.ts
942
942
  var DEFAULT_CONFIG = {
943
943
  groundingWeight: 0.4,
@@ -947,75 +947,20 @@ var DEFAULT_CONFIG = {
947
947
  };
948
948
  function calculateGrounding(output, groundTruth) {
949
949
  if (!groundTruth || groundTruth.length === 0) {
950
- const hedgingPatterns = [
951
- /\bi think\b/gi,
952
- /\bmaybe\b/gi,
953
- /\bperhaps\b/gi,
954
- /\bpossibly\b/gi,
955
- /\buncertain\b/gi,
956
- /\bmight\b/gi
957
- ];
958
- const hedgeCount = hedgingPatterns.reduce(
959
- (count, pattern) => count + (output.match(pattern)?.length || 0),
960
- 0
961
- );
962
- const wordCount = output.split(/\s+/).length;
963
- const hedgeRatio = hedgeCount / Math.max(wordCount / 50, 1);
964
- return Math.max(0, 1 - hedgeRatio * 0.2);
965
- }
966
- const outputTerms = new Set(
967
- output.toLowerCase().split(/\W+/).filter((t) => t.length > 2)
968
- );
969
- let totalOverlap = 0;
970
- for (const fact of groundTruth) {
971
- const factTerms = fact.toLowerCase().split(/\W+/).filter((t) => t.length > 2);
972
- if (factTerms.length === 0) continue;
973
- const matched = factTerms.filter((t) => outputTerms.has(t)).length;
974
- totalOverlap += matched / factTerms.length;
950
+ return Math.max(0, 1 - detectHedging(output));
975
951
  }
976
- return totalOverlap / groundTruth.length;
952
+ return computeFactOverlap(output, groundTruth);
977
953
  }
978
954
  function calculateInternal(output, history) {
979
955
  const sentences = output.split(/[.!?]+/).filter((s) => s.trim());
980
956
  if (sentences.length < 2) return 1;
981
- const negations = [
982
- /\bhowever\b.*\bnot\b/gi,
983
- /\bbut\b.*\bnot\b/gi,
984
- /\bcontrary\b/gi,
985
- /\bcontradicts?\b/gi
986
- ];
987
- let contradictionScore = 0;
988
- for (const pattern of negations) {
989
- const matches = output.match(pattern);
990
- if (matches) {
991
- contradictionScore += matches.length * 0.1;
992
- }
993
- }
994
- if (history && history.length > 0) {
995
- const currentTerms = new Set(output.toLowerCase().split(/\s+/));
996
- const historyTerms = new Set(history.flatMap((h) => h.toLowerCase().split(/\s+/)));
997
- const overlap = [...currentTerms].filter((t) => historyTerms.has(t)).length;
998
- const overlapRatio = overlap / currentTerms.size;
999
- if (overlapRatio < 0.1) {
1000
- contradictionScore += 0.2;
1001
- }
1002
- }
1003
- return Math.max(0, 1 - contradictionScore);
957
+ const contradictionPenalty = detectContradictions(output);
958
+ const divergencePenalty = history && history.length > 0 ? measureTopicDivergence(output, history) : 0;
959
+ return Math.max(0, 1 - contradictionPenalty - divergencePenalty);
1004
960
  }
1005
961
  function calculateCrystallization(output) {
1006
- let score = 1;
1007
- const wordCount = output.split(/\s+/).length;
1008
- if (wordCount < 10) score -= 0.2;
1009
- if (wordCount > 500) score -= 0.1;
1010
- const hasStructure = /[-*•]\s|^\d+\.|#{1,3}\s/m.test(output);
1011
- if (hasStructure) score += 0.1;
1012
- const actionWords = /\b(do|make|create|implement|use|try|start|begin|ensure|verify)\b/gi;
1013
- const actionMatches = output.match(actionWords);
1014
- if (actionMatches && actionMatches.length > 2) score += 0.1;
1015
- const qualifiers = /\b(very|really|extremely|quite|somewhat|fairly)\b/gi;
1016
- const qualifierCount = (output.match(qualifiers) || []).length;
1017
- if (qualifierCount > 5) score -= 0.1;
1018
- return Math.max(0, Math.min(1, score));
962
+ const adjustment = scoreStructure(output);
963
+ return Math.max(0, Math.min(1, 1 + adjustment));
1019
964
  }
1020
965
  function calculateCoherence(input, config = {}) {
1021
966
  const cfg = { ...DEFAULT_CONFIG, ...config };
@@ -1269,75 +1214,2130 @@ var SIGNAL_CODE_TO_EVENT = {
1269
1214
  [SKILL_SIGNAL_CODES.SKILL_ERROR]: "skill:error"
1270
1215
  };
1271
1216
 
1272
- // ../../lib/terminals-tech/axon/protocol.ts
1273
- var AXON_CONSTANTS = {
1274
- HEADER_SIZE: 16,
1275
- MAX_MESSAGE_SIZE: 1024 * 64,
1276
- // 64KB
1277
- TICK_RATE_MS: 16
1278
- // ~60Hz
1217
+ // ../../lib/terminals-tech/sdk/manifold.ts
1218
+ var manifold_exports = {};
1219
+ __export(manifold_exports, {
1220
+ annihilate: () => annihilate,
1221
+ manifold: () => manifold
1222
+ });
1223
+
1224
+ // ../../lib/terminals-tech/core/L0/dmt-55dim-combinatorial.ts
1225
+ var DMT55CombinatorialEngine = class {
1226
+ constructor() {
1227
+ }
1228
+ /**
1229
+ * Treat the observer configuration mapping:
1230
+ * 1 sat = 18 ordinal dimensions = 37 DMT
1231
+ */
1232
+ getObserverConfiguration(sats) {
1233
+ const ordinalDimensions = sats * 18;
1234
+ const dmtDimensions = sats * 37;
1235
+ return {
1236
+ sats,
1237
+ ordinalDimensions,
1238
+ dmtDimensions,
1239
+ totalDimensions: ordinalDimensions + dmtDimensions
1240
+ // 55 per sat
1241
+ };
1242
+ }
1243
+ /**
1244
+ * Continuous generation of evidence via MicroLM architecture
1245
+ */
1246
+ generateMicroLMEvidence(sats) {
1247
+ const config = this.getObserverConfiguration(sats);
1248
+ const manifoldState = Array.from(
1249
+ { length: config.totalDimensions },
1250
+ () => Math.random() * 2 - 1
1251
+ );
1252
+ const evidence = {
1253
+ evidenceId: `microlm-ev-${Date.now()}-${Math.floor(Math.random() * 1e3)}`,
1254
+ confidence: 0.85 + Math.random() * 0.14,
1255
+ manifoldState,
1256
+ timestamp: Date.now()
1257
+ };
1258
+ emitSignal("mesh_update", "L1", "L3", {
1259
+ node: "DMT55Engine",
1260
+ evidence,
1261
+ config
1262
+ });
1263
+ return evidence;
1264
+ }
1279
1265
  };
1280
- function highLevelToSDKMessage(msg) {
1281
- const parseOrCreate = (addr) => {
1282
- try {
1283
- return parseAddress(addr);
1284
- } catch {
1285
- return { layer: "L3", nodeType: "agent", nodeId: addr };
1266
+ var dmt55Engine = new DMT55CombinatorialEngine();
1267
+
1268
+ // ../../lib/terminals-tech/brains/state-mirror.ts
1269
+ import { BehaviorSubject } from "rxjs";
1270
+ var DEFAULT_STATE = {
1271
+ activeUrl: "/",
1272
+ focusedComponent: null,
1273
+ recentIntents: [],
1274
+ audioEntropy: 0.5,
1275
+ nanoFoldActive: false,
1276
+ coherenceR: 0,
1277
+ activeProject: null
1278
+ };
1279
+ var StateMirror = class {
1280
+ state$ = new BehaviorSubject(DEFAULT_STATE);
1281
+ bridgeOwnerId = null;
1282
+ bridgeOrder = [];
1283
+ constructor() {
1284
+ this.initSubscriptions();
1285
+ }
1286
+ initSubscriptions() {
1287
+ if (typeof window === "undefined") return;
1288
+ const bus = getSignalBus();
1289
+ bus.subscribe("audio_metrics_update", (signal) => {
1290
+ const payload = signal.payload;
1291
+ if (payload && typeof payload.entropy === "number") {
1292
+ this.update({ audioEntropy: payload.entropy });
1293
+ }
1294
+ });
1295
+ bus.subscribe("ui_surface_opened", (signal) => {
1296
+ const payload = signal.payload;
1297
+ if (payload && payload.surface) {
1298
+ this.update({ focusedComponent: payload.surface });
1299
+ }
1300
+ });
1301
+ bus.subscribe("intent_signal_emitted", (signal) => {
1302
+ const payload = signal.payload;
1303
+ if (payload && payload.intent) {
1304
+ const current = this.state$.value.recentIntents;
1305
+ this.update({ recentIntents: [payload.intent, ...current].slice(0, 5) });
1306
+ }
1307
+ });
1308
+ }
1309
+ /** Gets the observable stream of state changes */
1310
+ get stream$() {
1311
+ return this.state$.asObservable();
1312
+ }
1313
+ /** Gets a synchronous snapshot of the current state */
1314
+ get snapshot() {
1315
+ return this.state$.value;
1316
+ }
1317
+ claimBridge(bridgeId) {
1318
+ this.bridgeOrder = [...this.bridgeOrder.filter((id) => id !== bridgeId), bridgeId];
1319
+ this.bridgeOwnerId = bridgeId;
1320
+ }
1321
+ releaseBridge(bridgeId) {
1322
+ this.bridgeOrder = this.bridgeOrder.filter((id) => id !== bridgeId);
1323
+ if (this.bridgeOwnerId === bridgeId) {
1324
+ this.bridgeOwnerId = this.bridgeOrder[this.bridgeOrder.length - 1] ?? null;
1286
1325
  }
1287
- };
1288
- const mapProtocolType = (type) => {
1289
- if (!type) return void 0;
1290
- if (type === "mcp" || type === "a2a") return type;
1291
- return "internal";
1292
- };
1293
- return {
1294
- id: msg.id,
1295
- type: msg.type,
1296
- source: parseOrCreate(msg.source),
1297
- target: parseOrCreate(msg.target),
1298
- payload: msg.payload,
1299
- meta: {
1300
- timestamp: msg.meta.timestamp,
1301
- traceId: msg.meta.traceId,
1302
- priority: msg.meta.priority,
1303
- correlationId: msg.meta.correlationId,
1304
- ttl: msg.meta.ttl,
1305
- sessionId: msg.meta.sessionId,
1306
- interactionId: msg.meta.interactionId
1326
+ }
1327
+ /** Partially updates the mirror state */
1328
+ update(partial) {
1329
+ const next = { ...this.state$.value, ...partial };
1330
+ this.state$.next(next);
1331
+ }
1332
+ /**
1333
+ * Bridge-scoped update to prevent multiple mounted app shells from racing
1334
+ * against the same singleton mirror.
1335
+ */
1336
+ updateFromBridge(bridgeId, partial) {
1337
+ if (!this.bridgeOrder.includes(bridgeId)) {
1338
+ this.claimBridge(bridgeId);
1339
+ }
1340
+ if (this.bridgeOwnerId && this.bridgeOwnerId !== bridgeId) {
1341
+ return;
1342
+ }
1343
+ this.bridgeOwnerId = bridgeId;
1344
+ this.update(partial);
1345
+ }
1346
+ /**
1347
+ * Flattens the continuous state into a dense text manifold.
1348
+ * This is passed to the ObserverKernel to ground it in the immediate UI/UX reality.
1349
+ */
1350
+ encodeToManifold() {
1351
+ const s = this.snapshot;
1352
+ return `
1353
+ [StateMirror: Active]
1354
+ Location: ${s.activeUrl}
1355
+ Focus: ${s.focusedComponent || "ambient"}
1356
+ Workspace: ${s.activeProject || "global"}
1357
+ Acoustic Entropy: ${s.audioEntropy.toFixed(3)}
1358
+ Resonance R: ${s.coherenceR.toFixed(3)}
1359
+ NanoFold Topology: ${s.nanoFoldActive ? "Rendering" : "Collapsed"}
1360
+ Recent Intents: ${s.recentIntents.length > 0 ? s.recentIntents.join(" -> ") : "None"}
1361
+ `.trim();
1362
+ }
1363
+ };
1364
+ var globalStateMirror = new StateMirror();
1365
+
1366
+ // ../../lib/terminals-tech/brains/observable-evidence.ts
1367
+ function metricToneFromValue(value, invert = false) {
1368
+ const normalized = invert ? 1 - value : value;
1369
+ if (normalized >= 0.85) return "mint";
1370
+ if (normalized >= 0.6) return "cyan";
1371
+ if (normalized >= 0.35) return "violet";
1372
+ return "amber";
1373
+ }
1374
+ function toneColor(tone) {
1375
+ switch (tone) {
1376
+ case "mint":
1377
+ return "#6EE7B7";
1378
+ case "cyan":
1379
+ return "#67E8F9";
1380
+ case "violet":
1381
+ return "#A78BFA";
1382
+ case "amber":
1383
+ return "#FBBF24";
1384
+ default:
1385
+ return "#67E8F9";
1386
+ }
1387
+ }
1388
+ function buildStatus(constructive, witness) {
1389
+ if (constructive) return "constructive";
1390
+ if (witness.converged || witness.R >= 0.75) return "stable";
1391
+ if (witness.R >= 0.35) return "searching";
1392
+ return "ambient";
1393
+ }
1394
+ function buildThoughtspace(witness, constructive, strategyLabel, entropyLabel) {
1395
+ const stabilityTone = metricToneFromValue(witness.R);
1396
+ const entropyTone = metricToneFromValue(witness.activationEntropy, true);
1397
+ const routeTone = constructive ? "violet" : "amber";
1398
+ return [
1399
+ {
1400
+ id: "stability",
1401
+ shape: "circle",
1402
+ label: "Core",
1403
+ detail: `This dot is the center of the thought. Bigger + brighter means the pattern is holding together (R=${witness.R.toFixed(2)}).`,
1404
+ color: toneColor(stabilityTone),
1405
+ x: 52,
1406
+ y: 44,
1407
+ size: 12 + witness.R * 10,
1408
+ opacity: 0.65 + witness.R * 0.3
1307
1409
  },
1308
- protocol: msg.protocol ? {
1309
- type: mapProtocolType(msg.protocol.type) ?? "internal",
1310
- version: msg.protocol.version,
1311
- originalMessage: msg.protocol.originalMessage
1312
- } : void 0,
1313
- capability: msg.capability
1314
- };
1410
+ {
1411
+ id: "entropy",
1412
+ shape: "diamond",
1413
+ label: "Search",
1414
+ detail: `This shape shows how noisy the signal is. ${entropyLabel}`,
1415
+ color: toneColor(entropyTone),
1416
+ x: 22 + witness.activationEntropy * 18,
1417
+ y: 78 - witness.activationEntropy * 18,
1418
+ size: 8 + witness.activationEntropy * 9,
1419
+ opacity: 0.45 + witness.activationEntropy * 0.4
1420
+ },
1421
+ {
1422
+ id: "route",
1423
+ shape: "triangle",
1424
+ label: "Route",
1425
+ detail: `This pointer shows which engine is carrying the thought right now: ${strategyLabel}.`,
1426
+ color: toneColor(routeTone),
1427
+ x: 82,
1428
+ y: constructive ? 30 : 62,
1429
+ size: 10 + (constructive ? 4 : 0),
1430
+ opacity: constructive ? 0.9 : 0.6
1431
+ }
1432
+ ];
1315
1433
  }
1316
- function sdkMessageToHighLevel(msg) {
1317
- const mapProtocolType = (type) => {
1318
- if (!type) return void 0;
1319
- if (type === "mcp" || type === "a2a" || type === "internal") return type;
1320
- return "internal";
1321
- };
1434
+ function parseFoldedPayload(payload) {
1435
+ if (typeof payload !== "string") return payload;
1436
+ try {
1437
+ return JSON.parse(payload);
1438
+ } catch {
1439
+ return payload;
1440
+ }
1441
+ }
1442
+ function toReduction(payload) {
1443
+ if (!payload || typeof payload !== "object") return {};
1444
+ const reduction = payload.reduction;
1445
+ if (!reduction || typeof reduction !== "object") return {};
1446
+ return reduction;
1447
+ }
1448
+ function toContextHint(payload) {
1449
+ if (!payload || typeof payload !== "object") return void 0;
1450
+ const candidate = payload.contextSnapshot;
1451
+ return typeof candidate === "string" && candidate.length > 0 ? candidate : void 0;
1452
+ }
1453
+ function buildObservableEvidenceFromSematon(sematon, title) {
1454
+ const payload = parseFoldedPayload(sematon.payload);
1455
+ const reduction = toReduction(payload);
1456
+ const status = buildStatus(sematon.constructive, sematon.witness);
1457
+ const strategyLabel = reduction.strategy ?? reduction.runtime ?? sematon.source;
1458
+ const entropyLabel = sematon.witness.activationEntropy >= 0.7 ? "Higher means the system is still exploring a lot of possibilities." : "Lower means the system has narrowed into a smaller, steadier shape.";
1322
1459
  return {
1323
- id: msg.id,
1324
- type: msg.type,
1325
- source: formatAddress(msg.source),
1326
- target: formatAddress(msg.target),
1327
- payload: msg.payload,
1328
- meta: {
1329
- timestamp: msg.meta.timestamp,
1330
- traceId: msg.meta.traceId,
1331
- priority: msg.meta.priority,
1332
- correlationId: msg.meta.correlationId,
1333
- ttl: msg.meta.ttl,
1334
- sessionId: msg.meta.sessionId,
1335
- interactionId: msg.meta.interactionId
1336
- },
1337
- protocol: msg.protocol ? {
1338
- type: mapProtocolType(msg.protocol.type) ?? "internal",
1339
- version: msg.protocol.version,
1340
- originalMessage: msg.protocol.originalMessage
1460
+ id: sematon.id,
1461
+ source: sematon.source,
1462
+ title: title ?? (sematon.source.includes("ohm") || sematon.source.includes("Ohm") ? "Ohm Thoughtspace" : "Observable Evidence"),
1463
+ summary: sematon.constructive ? "The pattern held together and can be built on again." : sematon.witness.converged ? "The pattern is stable, but it is not yet a reusable construction." : "The system is still searching for a stable shape.",
1464
+ status,
1465
+ constructive: sematon.constructive,
1466
+ witness: sematon.witness,
1467
+ strategy: reduction.strategy,
1468
+ runtime: reduction.runtime,
1469
+ durationMs: reduction.durationMs,
1470
+ metrics: [
1471
+ {
1472
+ id: "stability",
1473
+ label: "Stability",
1474
+ value: sematon.witness.R.toFixed(2),
1475
+ detail: "How locked-in the thought is. Closer to 1 means the pattern is holding together instead of wobbling.",
1476
+ tone: metricToneFromValue(sematon.witness.R)
1477
+ },
1478
+ {
1479
+ id: "signal",
1480
+ label: "Signal",
1481
+ value: sematon.witness.activationEntropy.toFixed(2),
1482
+ detail: "How noisy the search still is. Higher means more exploring, lower means more focus.",
1483
+ tone: metricToneFromValue(sematon.witness.activationEntropy, true)
1484
+ },
1485
+ {
1486
+ id: "route",
1487
+ label: "Route",
1488
+ value: strategyLabel,
1489
+ detail: "Which engine is carrying the construction right now. This tells you where the work actually happened.",
1490
+ tone: sematon.constructive ? "violet" : "amber"
1491
+ },
1492
+ {
1493
+ id: "buildable",
1494
+ label: "Buildable",
1495
+ value: sematon.constructive ? "yes" : "not yet",
1496
+ detail: "If this says yes, the result can be reused and extended instead of collapsing when you touch it.",
1497
+ tone: sematon.constructive ? "mint" : "amber"
1498
+ }
1499
+ ],
1500
+ thoughtspace: buildThoughtspace(
1501
+ sematon.witness,
1502
+ sematon.constructive,
1503
+ strategyLabel,
1504
+ entropyLabel
1505
+ ),
1506
+ contextHint: toContextHint(payload),
1507
+ observedAt: sematon.createdAt ?? Date.now()
1508
+ };
1509
+ }
1510
+
1511
+ // ../../lib/py2bend/parser.ts
1512
+ function tokenizeLines(source) {
1513
+ return source.split("\n").map((raw, i) => {
1514
+ const text = raw;
1515
+ const trimmed = raw.trimStart();
1516
+ const indent2 = raw.length - trimmed.length;
1517
+ return { text: trimmed, indent: indent2, lineNo: i + 1 };
1518
+ }).filter((l) => l.text.length > 0 && !l.text.startsWith("#"));
1519
+ }
1520
+ var Cursor = class {
1521
+ constructor(lines, pos = 0) {
1522
+ this.lines = lines;
1523
+ this.pos = pos;
1524
+ }
1525
+ done() {
1526
+ return this.pos >= this.lines.length;
1527
+ }
1528
+ peek() {
1529
+ return this.done() ? null : this.lines[this.pos];
1530
+ }
1531
+ advance() {
1532
+ return this.lines[this.pos++];
1533
+ }
1534
+ /** Collect the body block: all lines with indent > parentIndent */
1535
+ collectBlock(parentIndent) {
1536
+ const block = [];
1537
+ while (!this.done()) {
1538
+ const next = this.peek();
1539
+ if (next.indent <= parentIndent) break;
1540
+ block.push(this.advance());
1541
+ }
1542
+ return block;
1543
+ }
1544
+ };
1545
+ var UNSUPPORTED_KEYWORDS = [
1546
+ /^async\s+def\b/,
1547
+ /^await\b/,
1548
+ /^yield\b/,
1549
+ /^import\b/,
1550
+ /^from\s+\S+\s+import\b/,
1551
+ /^with\b/,
1552
+ /^assert\b/,
1553
+ /^raise\b/,
1554
+ /^del\b/,
1555
+ /^global\b/,
1556
+ /^nonlocal\b/
1557
+ ];
1558
+ function parsePython(source) {
1559
+ const errors = [];
1560
+ const lines = tokenizeLines(source);
1561
+ validateIndentation(lines, errors);
1562
+ if (errors.some((error) => error.severity === "error")) {
1563
+ return { ast: null, errors };
1564
+ }
1565
+ try {
1566
+ const cursor = new Cursor(lines);
1567
+ const body = parseBlock(cursor, -1, errors);
1568
+ return { ast: { type: "Module", body }, errors };
1569
+ } catch (e) {
1570
+ errors.push({
1571
+ message: e.message,
1572
+ severity: "error"
1573
+ });
1574
+ return { ast: null, errors };
1575
+ }
1576
+ }
1577
+ function parseBlock(cursor, parentIndent, errors) {
1578
+ const stmts = [];
1579
+ while (!cursor.done()) {
1580
+ const line = cursor.peek();
1581
+ if (line.indent <= parentIndent) break;
1582
+ cursor.advance();
1583
+ const stmt = parseStatement(line, cursor, errors);
1584
+ if (stmt) stmts.push(stmt);
1585
+ }
1586
+ return stmts;
1587
+ }
1588
+ function parseStatement(line, cursor, errors) {
1589
+ const text = line.text;
1590
+ for (const pattern of UNSUPPORTED_KEYWORDS) {
1591
+ if (pattern.test(text)) {
1592
+ errors.push({
1593
+ message: `Unsupported syntax: ${text}`,
1594
+ line: line.lineNo,
1595
+ severity: "error"
1596
+ });
1597
+ cursor.collectBlock(line.indent);
1598
+ return null;
1599
+ }
1600
+ }
1601
+ if (text.startsWith("@")) {
1602
+ const decorators = [text.slice(1).trim()];
1603
+ while (!cursor.done() && cursor.peek().text.startsWith("@")) {
1604
+ decorators.push(cursor.advance().text.slice(1).trim());
1605
+ }
1606
+ if (!cursor.done()) {
1607
+ const defLine = cursor.advance();
1608
+ const stmt = parseStatement(defLine, cursor, errors);
1609
+ if (stmt && stmt.type === "FunctionDef") {
1610
+ stmt.decorators = decorators;
1611
+ }
1612
+ return stmt;
1613
+ }
1614
+ return null;
1615
+ }
1616
+ if (text.startsWith("def ")) {
1617
+ return parseFunctionDef(text, line, cursor, errors);
1618
+ }
1619
+ if (text.startsWith("class ")) {
1620
+ return parseClassDef(text, line, cursor, errors);
1621
+ }
1622
+ if (text.startsWith("if ")) {
1623
+ return parseIf(text, line, cursor, errors);
1624
+ }
1625
+ if (text.startsWith("for ")) {
1626
+ return parseFor(text, line, cursor, errors);
1627
+ }
1628
+ if (text.startsWith("while ")) {
1629
+ return parseWhile(text, line, cursor, errors);
1630
+ }
1631
+ if (text.startsWith("try:")) {
1632
+ return parseTry(line, cursor, errors);
1633
+ }
1634
+ if (text === "return" || text.startsWith("return ")) {
1635
+ return parseReturn(text, line, errors);
1636
+ }
1637
+ if (text === "pass") {
1638
+ return null;
1639
+ }
1640
+ if (text.startsWith("elif ") || text === "else:" || text.startsWith("except")) {
1641
+ cursor.collectBlock(line.indent);
1642
+ return null;
1643
+ }
1644
+ const augMatch = text.match(
1645
+ /^([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*(\+\=|\-\=|\*\=|\/\=|\/\/\=|%\=|\*\*\=|&\=|\|\=)\s*(.+)$/
1646
+ );
1647
+ if (augMatch) {
1648
+ return {
1649
+ type: "AugAssign",
1650
+ target: augMatch[1],
1651
+ op: augMatch[2],
1652
+ value: parseExpr(augMatch[3].trim(), line.lineNo, errors)
1653
+ };
1654
+ }
1655
+ const assignMatch = text.match(
1656
+ /^([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*(?:\[[^\]]+\])?)\s*=\s*(.+)$/
1657
+ );
1658
+ if (assignMatch) {
1659
+ const afterTarget = text.slice(assignMatch[1].length).trimStart();
1660
+ if (afterTarget.startsWith("==")) {
1661
+ } else {
1662
+ return {
1663
+ type: "Assign",
1664
+ target: assignMatch[1],
1665
+ value: parseExpr(assignMatch[2].trim(), line.lineNo, errors)
1666
+ };
1667
+ }
1668
+ }
1669
+ const expr = parseExpr(text, line.lineNo, errors);
1670
+ return {
1671
+ type: "Expr",
1672
+ value: expr
1673
+ };
1674
+ }
1675
+ function parseFunctionDef(text, line, cursor, errors) {
1676
+ const nameMatch = text.match(/^def\s+([A-Za-z_][A-Za-z0-9_]*)\s*\(/);
1677
+ const openParenIdx = text.indexOf("(");
1678
+ const closeParenIdx = openParenIdx >= 0 ? findMatchingClose(text, openParenIdx, "(", ")") : -1;
1679
+ if (!nameMatch || openParenIdx < 0 || closeParenIdx < 0) {
1680
+ errors.push({
1681
+ message: `Invalid function definition: ${text}`,
1682
+ line: line.lineNo,
1683
+ severity: "error"
1684
+ });
1685
+ cursor.collectBlock(line.indent);
1686
+ return {
1687
+ type: "FunctionDef",
1688
+ name: "unknown",
1689
+ params: [],
1690
+ body: [],
1691
+ decorators: []
1692
+ };
1693
+ }
1694
+ const trailing = text.slice(closeParenIdx + 1).trim();
1695
+ if (!trailing.startsWith(":")) {
1696
+ errors.push({
1697
+ message: `Invalid function definition: ${text}`,
1698
+ line: line.lineNo,
1699
+ severity: "error"
1700
+ });
1701
+ cursor.collectBlock(line.indent);
1702
+ return {
1703
+ type: "FunctionDef",
1704
+ name: nameMatch[1],
1705
+ params: [],
1706
+ body: [],
1707
+ decorators: []
1708
+ };
1709
+ }
1710
+ const name = nameMatch[1];
1711
+ const paramsStr = text.slice(openParenIdx + 1, closeParenIdx).trim();
1712
+ const params = paramsStr ? splitArgs(paramsStr).map((param) => extractParameterName(param)).filter((param) => Boolean(param)) : [];
1713
+ const bodyLines = cursor.collectBlock(line.indent);
1714
+ const bodyCursor = new Cursor(bodyLines);
1715
+ const body = parseBlock(bodyCursor, line.indent, errors);
1716
+ return {
1717
+ type: "FunctionDef",
1718
+ name,
1719
+ params,
1720
+ body,
1721
+ decorators: []
1722
+ };
1723
+ }
1724
+ function parseClassDef(text, line, cursor, errors) {
1725
+ const match = text.match(/^class\s+([A-Za-z_][A-Za-z0-9_]*)(?:\(([^)]*)\))?\s*:/);
1726
+ if (!match) {
1727
+ errors.push({
1728
+ message: `Invalid class definition: ${text}`,
1729
+ line: line.lineNo,
1730
+ severity: "error"
1731
+ });
1732
+ cursor.collectBlock(line.indent);
1733
+ return { type: "ClassDef", name: "unknown", bases: [], body: [] };
1734
+ }
1735
+ const name = match[1];
1736
+ const basesStr = match[2]?.trim() ?? "";
1737
+ const bases = basesStr ? basesStr.split(",").map((b) => b.trim()) : [];
1738
+ const bodyLines = cursor.collectBlock(line.indent);
1739
+ const bodyCursor = new Cursor(bodyLines);
1740
+ const body = parseBlock(bodyCursor, line.indent, errors);
1741
+ return { type: "ClassDef", name, bases, body };
1742
+ }
1743
+ function parseIf(text, line, cursor, errors) {
1744
+ const condStr = text.replace(/^if\s+/, "").replace(/\s*:\s*$/, "");
1745
+ const test = parseExpr(condStr, line.lineNo, errors);
1746
+ const bodyLines = cursor.collectBlock(line.indent);
1747
+ const bodyCursor = new Cursor(bodyLines);
1748
+ const body = parseBlock(bodyCursor, line.indent, errors);
1749
+ let orelse = [];
1750
+ if (!cursor.done()) {
1751
+ const next = cursor.peek();
1752
+ if (next.indent === line.indent && next.text.startsWith("elif ")) {
1753
+ cursor.advance();
1754
+ const elifText = next.text.replace(/^elif\s+/, "if ");
1755
+ const elifIf = parseIf(elifText, next, cursor, errors);
1756
+ orelse = [elifIf];
1757
+ } else if (next.indent === line.indent && next.text === "else:") {
1758
+ cursor.advance();
1759
+ const elseLines = cursor.collectBlock(line.indent);
1760
+ const elseCursor = new Cursor(elseLines);
1761
+ orelse = parseBlock(elseCursor, line.indent, errors);
1762
+ }
1763
+ }
1764
+ return { type: "If", test, body, orelse };
1765
+ }
1766
+ function parseFor(text, line, cursor, errors) {
1767
+ const match = text.match(/^for\s+([A-Za-z_][A-Za-z0-9_]*)\s+in\s+(.+)\s*:\s*$/);
1768
+ if (!match) {
1769
+ errors.push({
1770
+ message: `Invalid for loop: ${text}`,
1771
+ line: line.lineNo,
1772
+ severity: "error"
1773
+ });
1774
+ cursor.collectBlock(line.indent);
1775
+ return {
1776
+ type: "For",
1777
+ target: "unknown",
1778
+ iter: { type: "Name", id: "unknown" },
1779
+ body: []
1780
+ };
1781
+ }
1782
+ const target = match[1];
1783
+ const iterExpr = parseExpr(match[2].trim(), line.lineNo, errors);
1784
+ const bodyLines = cursor.collectBlock(line.indent);
1785
+ const bodyCursor = new Cursor(bodyLines);
1786
+ const body = parseBlock(bodyCursor, line.indent, errors);
1787
+ return { type: "For", target, iter: iterExpr, body };
1788
+ }
1789
+ function parseWhile(text, line, cursor, errors) {
1790
+ const condStr = text.replace(/^while\s+/, "").replace(/\s*:\s*$/, "");
1791
+ const test = parseExpr(condStr, line.lineNo, errors);
1792
+ const bodyLines = cursor.collectBlock(line.indent);
1793
+ const bodyCursor = new Cursor(bodyLines);
1794
+ const body = parseBlock(bodyCursor, line.indent, errors);
1795
+ return { type: "While", test, body };
1796
+ }
1797
+ function parseTry(line, cursor, errors) {
1798
+ const tryBodyLines = cursor.collectBlock(line.indent);
1799
+ const tryCursor = new Cursor(tryBodyLines);
1800
+ const tryBody = parseBlock(tryCursor, line.indent, errors);
1801
+ let handler = null;
1802
+ if (!cursor.done()) {
1803
+ const next = cursor.peek();
1804
+ if (next.indent === line.indent && next.text.startsWith("except")) {
1805
+ cursor.advance();
1806
+ const exceptMatch = next.text.match(
1807
+ /^except\s*(?:([A-Za-z_][A-Za-z0-9_]*))?(?:\s+as\s+([A-Za-z_][A-Za-z0-9_]*))?\s*:\s*$/
1808
+ );
1809
+ const handlerType = exceptMatch?.[1] ?? null;
1810
+ const handlerName = exceptMatch?.[2] ?? null;
1811
+ const handlerBodyLines = cursor.collectBlock(line.indent);
1812
+ const handlerCursor = new Cursor(handlerBodyLines);
1813
+ const handlerBody = parseBlock(handlerCursor, line.indent, errors);
1814
+ handler = { type: handlerType, name: handlerName, body: handlerBody };
1815
+ }
1816
+ }
1817
+ return { type: "Try", body: tryBody, handler };
1818
+ }
1819
+ function parseReturn(text, line, errors) {
1820
+ const valueStr = text.replace(/^return\s*/, "").trim();
1821
+ if (!valueStr) {
1822
+ return { type: "Return", value: null };
1823
+ }
1824
+ return { type: "Return", value: parseExpr(valueStr, line.lineNo, errors) };
1825
+ }
1826
+ function parseExpr(text, lineNo, errors) {
1827
+ text = text.trim();
1828
+ if (!text) {
1829
+ return { type: "Constant", value: null, kind: "none" };
1830
+ }
1831
+ if (text.startsWith("lambda")) {
1832
+ return parseLambda(text, lineNo, errors);
1833
+ }
1834
+ return parseBoolOr(text, lineNo, errors);
1835
+ }
1836
+ function parseLambda(text, lineNo, errors) {
1837
+ const match = text.match(/^lambda\s*([^:]*)\s*:\s*(.+)$/);
1838
+ if (!match) {
1839
+ return {
1840
+ type: "Lambda",
1841
+ params: [],
1842
+ body: { type: "Constant", value: null, kind: "none" }
1843
+ };
1844
+ }
1845
+ const paramsStr = match[1].trim();
1846
+ const params = paramsStr ? paramsStr.split(",").map((p) => p.trim()) : [];
1847
+ const body = parseExpr(match[2].trim(), lineNo, errors);
1848
+ return { type: "Lambda", params, body };
1849
+ }
1850
+ function parseBoolOr(text, lineNo, errors) {
1851
+ const parts = splitTopLevel(text, " or ");
1852
+ if (parts.length === 1) return parseBoolAnd(parts[0], lineNo, errors);
1853
+ const values = parts.map((p) => parseBoolAnd(p, lineNo, errors));
1854
+ return { type: "BoolOp", op: "or", values };
1855
+ }
1856
+ function parseBoolAnd(text, lineNo, errors) {
1857
+ const parts = splitTopLevel(text, " and ");
1858
+ if (parts.length === 1) return parseNot(parts[0], lineNo, errors);
1859
+ const values = parts.map((p) => parseNot(p, lineNo, errors));
1860
+ return { type: "BoolOp", op: "and", values };
1861
+ }
1862
+ function parseNot(text, lineNo, errors) {
1863
+ text = text.trim();
1864
+ if (text.startsWith("not ")) {
1865
+ const operand = parseNot(text.slice(4).trim(), lineNo, errors);
1866
+ return { type: "UnaryOp", op: "not", operand };
1867
+ }
1868
+ return parseComparison(text, lineNo, errors);
1869
+ }
1870
+ var COMPARISON_OPS = [" not in ", " in ", "<=", ">=", "!=", "==", "<", ">"];
1871
+ function parseComparison(text, lineNo, errors) {
1872
+ let bestIdx = -1;
1873
+ let bestOp = "";
1874
+ for (const op of COMPARISON_OPS) {
1875
+ const idx = findTopLevel(text, op);
1876
+ if (idx !== -1 && (bestIdx === -1 || idx < bestIdx)) {
1877
+ bestIdx = idx;
1878
+ bestOp = op;
1879
+ }
1880
+ }
1881
+ if (bestIdx === -1) {
1882
+ return parseAddSub(text, lineNo, errors);
1883
+ }
1884
+ const left2 = parseAddSub(text.slice(0, bestIdx).trim(), lineNo, errors);
1885
+ const right2 = parseComparison(text.slice(bestIdx + bestOp.length).trim(), lineNo, errors);
1886
+ if (right2.type === "Compare") {
1887
+ const rightCmp = right2;
1888
+ return {
1889
+ type: "Compare",
1890
+ left: left2,
1891
+ ops: [bestOp.trim(), ...rightCmp.ops],
1892
+ comparators: [rightCmp.left, ...rightCmp.comparators]
1893
+ };
1894
+ }
1895
+ return {
1896
+ type: "Compare",
1897
+ left: left2,
1898
+ ops: [bestOp.trim()],
1899
+ comparators: [right2]
1900
+ };
1901
+ }
1902
+ function parseAddSub(text, lineNo, errors) {
1903
+ let parenDepth = 0;
1904
+ let bracketDepth = 0;
1905
+ let braceDepth = 0;
1906
+ let inStr = null;
1907
+ let splitIdx = -1;
1908
+ let splitOp = "";
1909
+ for (let i = text.length - 1; i >= 1; i--) {
1910
+ const ch = text[i];
1911
+ if ((ch === '"' || ch === "'") && text[i - 1] !== "\\") {
1912
+ if (inStr === ch) {
1913
+ inStr = null;
1914
+ continue;
1915
+ } else if (!inStr) {
1916
+ inStr = ch;
1917
+ continue;
1918
+ }
1919
+ }
1920
+ if (inStr) continue;
1921
+ if (ch === ")") parenDepth++;
1922
+ else if (ch === "(") parenDepth--;
1923
+ else if (ch === "]") bracketDepth++;
1924
+ else if (ch === "[") bracketDepth--;
1925
+ else if (ch === "}") braceDepth++;
1926
+ else if (ch === "{") braceDepth--;
1927
+ if (parenDepth === 0 && bracketDepth === 0 && braceDepth === 0) {
1928
+ if ((ch === "+" || ch === "-") && text[i - 1] !== "*" && text[i + 1] !== "=" && text[i - 1] !== "=") {
1929
+ const before = text.slice(0, i).trim();
1930
+ if (before.length > 0 && !before.endsWith("(") && !before.endsWith(",") && !before.endsWith("[")) {
1931
+ splitIdx = i;
1932
+ splitOp = ch;
1933
+ break;
1934
+ }
1935
+ }
1936
+ }
1937
+ }
1938
+ if (splitIdx === -1) {
1939
+ return parseMulDiv(text, lineNo, errors);
1940
+ }
1941
+ const left2 = parseAddSub(text.slice(0, splitIdx).trim(), lineNo, errors);
1942
+ const right2 = parseMulDiv(text.slice(splitIdx + 1).trim(), lineNo, errors);
1943
+ return { type: "BinOp", left: left2, op: splitOp, right: right2 };
1944
+ }
1945
+ function parseMulDiv(text, lineNo, errors) {
1946
+ let parenDepth = 0;
1947
+ let bracketDepth = 0;
1948
+ let braceDepth = 0;
1949
+ let inStr = null;
1950
+ let splitIdx = -1;
1951
+ let splitOp = "";
1952
+ for (let i = text.length - 1; i >= 0; i--) {
1953
+ const ch = text[i];
1954
+ if ((ch === '"' || ch === "'") && (i === 0 || text[i - 1] !== "\\")) {
1955
+ if (inStr === ch) {
1956
+ inStr = null;
1957
+ continue;
1958
+ } else if (!inStr) {
1959
+ inStr = ch;
1960
+ continue;
1961
+ }
1962
+ }
1963
+ if (inStr) continue;
1964
+ if (ch === ")") parenDepth++;
1965
+ else if (ch === "(") parenDepth--;
1966
+ else if (ch === "]") bracketDepth++;
1967
+ else if (ch === "[") bracketDepth--;
1968
+ else if (ch === "}") braceDepth++;
1969
+ else if (ch === "{") braceDepth--;
1970
+ if (parenDepth === 0 && bracketDepth === 0 && braceDepth === 0) {
1971
+ if (ch === "*" && i > 0 && text[i - 1] !== "*" && (i + 1 >= text.length || text[i + 1] !== "*")) {
1972
+ splitIdx = i;
1973
+ splitOp = "*";
1974
+ break;
1975
+ }
1976
+ if (ch === "/" && i > 0) {
1977
+ if (text[i - 1] === "/") {
1978
+ splitIdx = i - 1;
1979
+ splitOp = "//";
1980
+ break;
1981
+ }
1982
+ splitIdx = i;
1983
+ splitOp = "/";
1984
+ break;
1985
+ }
1986
+ if (ch === "%") {
1987
+ splitIdx = i;
1988
+ splitOp = "%";
1989
+ break;
1990
+ }
1991
+ }
1992
+ }
1993
+ if (splitIdx === -1) {
1994
+ return parsePower(text, lineNo, errors);
1995
+ }
1996
+ const left2 = parseMulDiv(text.slice(0, splitIdx).trim(), lineNo, errors);
1997
+ const right2 = parsePower(text.slice(splitIdx + splitOp.length).trim(), lineNo, errors);
1998
+ return { type: "BinOp", left: left2, op: splitOp, right: right2 };
1999
+ }
2000
+ function parsePower(text, lineNo, errors) {
2001
+ const idx = findTopLevel(text, "**");
2002
+ if (idx === -1) {
2003
+ return parseUnary(text, lineNo, errors);
2004
+ }
2005
+ const left2 = parseUnary(text.slice(0, idx).trim(), lineNo, errors);
2006
+ const right2 = parsePower(text.slice(idx + 2).trim(), lineNo, errors);
2007
+ return { type: "BinOp", left: left2, op: "**", right: right2 };
2008
+ }
2009
+ function parseUnary(text, lineNo, errors) {
2010
+ text = text.trim();
2011
+ if (text.startsWith("-") && text.length > 1) {
2012
+ const rest = text.slice(1).trim();
2013
+ if (rest && !/^\d/.test(rest)) {
2014
+ const operand = parseUnary(rest, lineNo, errors);
2015
+ return { type: "UnaryOp", op: "-", operand };
2016
+ }
2017
+ }
2018
+ if (text.startsWith("+") && text.length > 1) {
2019
+ const rest = text.slice(1).trim();
2020
+ if (rest && !/^\d/.test(rest)) {
2021
+ const operand = parseUnary(rest, lineNo, errors);
2022
+ return { type: "UnaryOp", op: "+", operand };
2023
+ }
2024
+ }
2025
+ return parsePostfix(text, lineNo, errors);
2026
+ }
2027
+ function parsePostfix(text, lineNo, errors) {
2028
+ text = text.trim();
2029
+ let node = parsePrimary(text, lineNo, errors);
2030
+ const parsed = parsePrimaryWithPostfix(text, lineNo, errors);
2031
+ return parsed;
2032
+ }
2033
+ function parsePrimaryWithPostfix(text, lineNo, errors) {
2034
+ text = text.trim();
2035
+ let pos = 0;
2036
+ const { node, endPos } = parsePrimaryAt(text, pos, lineNo, errors);
2037
+ pos = endPos;
2038
+ let current = node;
2039
+ while (pos < text.length) {
2040
+ const ch = text[pos];
2041
+ if (ch === ".") {
2042
+ pos++;
2043
+ const attrMatch = text.slice(pos).match(/^[A-Za-z_][A-Za-z0-9_]*/);
2044
+ if (attrMatch) {
2045
+ const attr = attrMatch[0];
2046
+ pos += attr.length;
2047
+ current = { type: "Attribute", value: current, attr };
2048
+ } else {
2049
+ break;
2050
+ }
2051
+ } else if (ch === "[") {
2052
+ const closeIdx = findMatchingClose(text, pos, "[", "]");
2053
+ if (closeIdx === -1) break;
2054
+ const sliceStr = text.slice(pos + 1, closeIdx).trim();
2055
+ const sliceNode = parseExpr(sliceStr, lineNo, errors);
2056
+ current = { type: "Subscript", value: current, slice: sliceNode };
2057
+ pos = closeIdx + 1;
2058
+ } else if (ch === "(") {
2059
+ const closeIdx = findMatchingClose(text, pos, "(", ")");
2060
+ if (closeIdx === -1) break;
2061
+ const argsStr = text.slice(pos + 1, closeIdx).trim();
2062
+ const { args, kwargs } = parseCallArgs(argsStr, lineNo, errors);
2063
+ current = { type: "Call", func: current, args, kwargs };
2064
+ pos = closeIdx + 1;
2065
+ } else if (ch === " " || ch === " ") {
2066
+ pos++;
2067
+ } else {
2068
+ break;
2069
+ }
2070
+ }
2071
+ return current;
2072
+ }
2073
+ function parsePrimaryAt(text, pos, lineNo, errors) {
2074
+ while (pos < text.length && (text[pos] === " " || text[pos] === " ")) pos++;
2075
+ if (pos >= text.length) {
2076
+ return {
2077
+ node: { type: "Constant", value: null, kind: "none" },
2078
+ endPos: pos
2079
+ };
2080
+ }
2081
+ const remaining = text.slice(pos);
2082
+ if (remaining[0] === "(") {
2083
+ const closeIdx = findMatchingClose(text, pos, "(", ")");
2084
+ if (closeIdx !== -1) {
2085
+ const inner = text.slice(pos + 1, closeIdx).trim();
2086
+ const node = parseExpr(inner, lineNo, errors);
2087
+ return { node, endPos: closeIdx + 1 };
2088
+ }
2089
+ }
2090
+ if (remaining[0] === "[") {
2091
+ const closeIdx = findMatchingClose(text, pos, "[", "]");
2092
+ if (closeIdx !== -1) {
2093
+ const inner = text.slice(pos + 1, closeIdx).trim();
2094
+ const elts = inner ? splitArgs(inner).map((e) => parseExpr(e.trim(), lineNo, errors)) : [];
2095
+ return {
2096
+ node: { type: "List", elts },
2097
+ endPos: closeIdx + 1
2098
+ };
2099
+ }
2100
+ }
2101
+ if (remaining[0] === "{") {
2102
+ const closeIdx = findMatchingClose(text, pos, "{", "}");
2103
+ if (closeIdx !== -1) {
2104
+ const inner = text.slice(pos + 1, closeIdx).trim();
2105
+ const keys = [];
2106
+ const values = [];
2107
+ if (inner) {
2108
+ const entries = splitArgs(inner);
2109
+ for (const entry of entries) {
2110
+ const colonIdx = findTopLevel(entry, ":");
2111
+ if (colonIdx !== -1) {
2112
+ keys.push(parseExpr(entry.slice(0, colonIdx).trim(), lineNo, errors));
2113
+ values.push(parseExpr(entry.slice(colonIdx + 1).trim(), lineNo, errors));
2114
+ }
2115
+ }
2116
+ }
2117
+ return {
2118
+ node: { type: "Dict", keys, values },
2119
+ endPos: closeIdx + 1
2120
+ };
2121
+ }
2122
+ }
2123
+ if (remaining[0] === '"' || remaining[0] === "'") {
2124
+ const quote = remaining[0];
2125
+ if (remaining.startsWith(quote + quote + quote)) {
2126
+ const endQuote = remaining.indexOf(quote + quote + quote, 3);
2127
+ if (endQuote !== -1) {
2128
+ const value = remaining.slice(3, endQuote);
2129
+ return {
2130
+ node: { type: "Constant", value, kind: "str" },
2131
+ endPos: pos + endQuote + 3
2132
+ };
2133
+ }
2134
+ }
2135
+ let i = 1;
2136
+ while (i < remaining.length) {
2137
+ if (remaining[i] === "\\" && i + 1 < remaining.length) {
2138
+ i += 2;
2139
+ continue;
2140
+ }
2141
+ if (remaining[i] === quote) {
2142
+ const value = remaining.slice(1, i);
2143
+ return {
2144
+ node: { type: "Constant", value, kind: "str" },
2145
+ endPos: pos + i + 1
2146
+ };
2147
+ }
2148
+ i++;
2149
+ }
2150
+ return {
2151
+ node: {
2152
+ type: "Constant",
2153
+ value: remaining.slice(1),
2154
+ kind: "str"
2155
+ },
2156
+ endPos: pos + remaining.length
2157
+ };
2158
+ }
2159
+ if ((remaining[0] === "f" || remaining[0] === "F") && remaining.length > 1 && (remaining[1] === '"' || remaining[1] === "'")) {
2160
+ const quote = remaining[1];
2161
+ let i = 2;
2162
+ while (i < remaining.length) {
2163
+ if (remaining[i] === "\\" && i + 1 < remaining.length) {
2164
+ i += 2;
2165
+ continue;
2166
+ }
2167
+ if (remaining[i] === quote) {
2168
+ const value = remaining.slice(2, i);
2169
+ return {
2170
+ node: { type: "Constant", value, kind: "str" },
2171
+ endPos: pos + i + 1
2172
+ };
2173
+ }
2174
+ i++;
2175
+ }
2176
+ return {
2177
+ node: {
2178
+ type: "Constant",
2179
+ value: remaining.slice(2),
2180
+ kind: "str"
2181
+ },
2182
+ endPos: pos + remaining.length
2183
+ };
2184
+ }
2185
+ const numMatch = remaining.match(/^-?\d+(\.\d+)?/);
2186
+ if (numMatch) {
2187
+ const numStr = numMatch[0];
2188
+ const isFloat = numStr.includes(".");
2189
+ return {
2190
+ node: {
2191
+ type: "Constant",
2192
+ value: isFloat ? parseFloat(numStr) : parseInt(numStr, 10),
2193
+ kind: isFloat ? "float" : "int"
2194
+ },
2195
+ endPos: pos + numStr.length
2196
+ };
2197
+ }
2198
+ const identMatch = remaining.match(/^[A-Za-z_][A-Za-z0-9_]*/);
2199
+ if (identMatch) {
2200
+ const id = identMatch[0];
2201
+ const endPos = pos + id.length;
2202
+ if (id === "True") {
2203
+ return {
2204
+ node: { type: "Constant", value: true, kind: "bool" },
2205
+ endPos
2206
+ };
2207
+ }
2208
+ if (id === "False") {
2209
+ return {
2210
+ node: { type: "Constant", value: false, kind: "bool" },
2211
+ endPos
2212
+ };
2213
+ }
2214
+ if (id === "None") {
2215
+ return {
2216
+ node: { type: "Constant", value: null, kind: "none" },
2217
+ endPos
2218
+ };
2219
+ }
2220
+ return {
2221
+ node: { type: "Name", id },
2222
+ endPos
2223
+ };
2224
+ }
2225
+ errors.push({
2226
+ message: `Unexpected token: ${remaining.slice(0, 20)}`,
2227
+ line: lineNo,
2228
+ severity: "error"
2229
+ });
2230
+ return {
2231
+ node: { type: "Name", id: remaining.trim() },
2232
+ endPos: pos + remaining.length
2233
+ };
2234
+ }
2235
+ function parsePrimary(text, lineNo, errors) {
2236
+ const { node } = parsePrimaryAt(text, 0, lineNo, errors);
2237
+ return node;
2238
+ }
2239
+ function splitTopLevel(text, delimiter) {
2240
+ const parts = [];
2241
+ let parenDepth = 0;
2242
+ let bracketDepth = 0;
2243
+ let braceDepth = 0;
2244
+ let inStr = null;
2245
+ let start = 0;
2246
+ for (let i = 0; i <= text.length - delimiter.length; i++) {
2247
+ const ch = text[i];
2248
+ if ((ch === '"' || ch === "'") && (i === 0 || text[i - 1] !== "\\")) {
2249
+ if (inStr === ch) {
2250
+ inStr = null;
2251
+ continue;
2252
+ } else if (!inStr) {
2253
+ inStr = ch;
2254
+ continue;
2255
+ }
2256
+ }
2257
+ if (inStr) continue;
2258
+ if (ch === "(") parenDepth++;
2259
+ else if (ch === ")") parenDepth--;
2260
+ else if (ch === "[") bracketDepth++;
2261
+ else if (ch === "]") bracketDepth--;
2262
+ else if (ch === "{") braceDepth++;
2263
+ else if (ch === "}") braceDepth--;
2264
+ if (parenDepth === 0 && bracketDepth === 0 && braceDepth === 0 && text.slice(i, i + delimiter.length) === delimiter) {
2265
+ parts.push(text.slice(start, i).trim());
2266
+ start = i + delimiter.length;
2267
+ i = start - 1;
2268
+ }
2269
+ }
2270
+ parts.push(text.slice(start).trim());
2271
+ return parts;
2272
+ }
2273
+ function findTopLevel(text, needle) {
2274
+ let parenDepth = 0;
2275
+ let bracketDepth = 0;
2276
+ let braceDepth = 0;
2277
+ let inStr = null;
2278
+ for (let i = 0; i <= text.length - needle.length; i++) {
2279
+ const ch = text[i];
2280
+ if ((ch === '"' || ch === "'") && (i === 0 || text[i - 1] !== "\\")) {
2281
+ if (inStr === ch) {
2282
+ inStr = null;
2283
+ continue;
2284
+ } else if (!inStr) {
2285
+ inStr = ch;
2286
+ continue;
2287
+ }
2288
+ }
2289
+ if (inStr) continue;
2290
+ if (ch === "(") parenDepth++;
2291
+ else if (ch === ")") parenDepth--;
2292
+ else if (ch === "[") bracketDepth++;
2293
+ else if (ch === "]") bracketDepth--;
2294
+ else if (ch === "{") braceDepth++;
2295
+ else if (ch === "}") braceDepth--;
2296
+ if (parenDepth === 0 && bracketDepth === 0 && braceDepth === 0 && text.slice(i, i + needle.length) === needle) {
2297
+ return i;
2298
+ }
2299
+ }
2300
+ return -1;
2301
+ }
2302
+ function findMatchingClose(text, openIdx, open, close) {
2303
+ let depth = 0;
2304
+ let inStr = null;
2305
+ for (let i = openIdx; i < text.length; i++) {
2306
+ const ch = text[i];
2307
+ if ((ch === '"' || ch === "'") && (i === 0 || text[i - 1] !== "\\")) {
2308
+ if (inStr === ch) {
2309
+ inStr = null;
2310
+ continue;
2311
+ } else if (!inStr) {
2312
+ inStr = ch;
2313
+ continue;
2314
+ }
2315
+ }
2316
+ if (inStr) continue;
2317
+ if (ch === open) depth++;
2318
+ else if (ch === close) {
2319
+ depth--;
2320
+ if (depth === 0) return i;
2321
+ }
2322
+ }
2323
+ return -1;
2324
+ }
2325
+ function splitArgs(text) {
2326
+ return splitTopLevel(text, ",");
2327
+ }
2328
+ function extractParameterName(param) {
2329
+ const trimmed = param.trim();
2330
+ if (!trimmed || trimmed === "*" || trimmed === "/") return null;
2331
+ const match = trimmed.match(/^\*{0,2}([A-Za-z_][A-Za-z0-9_]*)/);
2332
+ return match?.[1] ?? null;
2333
+ }
2334
+ function opensBlock(text) {
2335
+ return text === "else:" || text.startsWith("except") || /^(def|class|if|elif|for|while)\b/.test(text) && text.trimEnd().endsWith(":") || text === "try:";
2336
+ }
2337
+ function validateIndentation(lines, errors) {
2338
+ const indentStack = [0];
2339
+ let indentUnit = null;
2340
+ let previousOpenedBlock = false;
2341
+ for (const line of lines) {
2342
+ const currentIndent = line.indent;
2343
+ let topIndent = indentStack[indentStack.length - 1];
2344
+ if (currentIndent > topIndent) {
2345
+ const delta = currentIndent - topIndent;
2346
+ if (!previousOpenedBlock) {
2347
+ errors.push({
2348
+ message: `Unexpected indentation on line ${line.lineNo}`,
2349
+ line: line.lineNo,
2350
+ severity: "error"
2351
+ });
2352
+ }
2353
+ if (indentUnit === null) {
2354
+ indentUnit = delta;
2355
+ } else if (delta !== indentUnit) {
2356
+ errors.push({
2357
+ message: `Inconsistent indentation width on line ${line.lineNo}`,
2358
+ line: line.lineNo,
2359
+ severity: "error"
2360
+ });
2361
+ }
2362
+ indentStack.push(currentIndent);
2363
+ topIndent = currentIndent;
2364
+ } else if (currentIndent < topIndent) {
2365
+ while (indentStack.length > 1 && currentIndent < topIndent) {
2366
+ indentStack.pop();
2367
+ topIndent = indentStack[indentStack.length - 1];
2368
+ }
2369
+ if (currentIndent !== topIndent) {
2370
+ errors.push({
2371
+ message: `Inconsistent dedent on line ${line.lineNo}`,
2372
+ line: line.lineNo,
2373
+ severity: "error"
2374
+ });
2375
+ }
2376
+ }
2377
+ previousOpenedBlock = opensBlock(line.text);
2378
+ }
2379
+ }
2380
+ function parseCallArgs(text, lineNo, errors) {
2381
+ if (!text.trim()) return { args: [], kwargs: [] };
2382
+ const parts = splitArgs(text);
2383
+ const args = [];
2384
+ const kwargs = [];
2385
+ for (const part of parts) {
2386
+ const trimmed = part.trim();
2387
+ const kwMatch = trimmed.match(/^([A-Za-z_][A-Za-z0-9_]*)\s*=(?!=)\s*(.+)$/);
2388
+ if (kwMatch) {
2389
+ kwargs.push({
2390
+ key: kwMatch[1],
2391
+ value: parseExpr(kwMatch[2].trim(), lineNo, errors)
2392
+ });
2393
+ } else {
2394
+ args.push(parseExpr(trimmed, lineNo, errors));
2395
+ }
2396
+ }
2397
+ return { args, kwargs };
2398
+ }
2399
+
2400
+ // ../../lib/py2bend/transforms.ts
2401
+ function transformModule(ast) {
2402
+ return {
2403
+ type: "BendModule",
2404
+ source: "Module",
2405
+ body: transformNodes(ast.body)
2406
+ };
2407
+ }
2408
+ function transformNodes(nodes) {
2409
+ return nodes.map(transformNode);
2410
+ }
2411
+ function transformNode(node) {
2412
+ switch (node.type) {
2413
+ case "FunctionDef":
2414
+ return transformFunctionDef(node);
2415
+ case "For":
2416
+ return transformFor(node);
2417
+ case "While":
2418
+ return transformWhile(node);
2419
+ case "ClassDef":
2420
+ return transformClass(node);
2421
+ case "Try":
2422
+ return transformTry(node);
2423
+ default:
2424
+ return passthrough(node);
2425
+ }
2426
+ }
2427
+ function transformFunctionDef(node) {
2428
+ return {
2429
+ type: "BendFunctionDef",
2430
+ source: "FunctionDef",
2431
+ name: node.name,
2432
+ params: node.params,
2433
+ body: transformNodes(node.body),
2434
+ decorators: node.decorators
2435
+ };
2436
+ }
2437
+ function transformFor(node) {
2438
+ const accumulator = findAccumulator(node.body);
2439
+ return {
2440
+ type: "BendFold",
2441
+ source: "For",
2442
+ target: node.target,
2443
+ iter: node.iter,
2444
+ body: transformNodes(node.body),
2445
+ accumulator
2446
+ };
2447
+ }
2448
+ function findAccumulator(body) {
2449
+ for (const stmt of body) {
2450
+ if (stmt.type === "AugAssign") {
2451
+ return stmt.target;
2452
+ }
2453
+ }
2454
+ return null;
2455
+ }
2456
+ function transformWhile(node) {
2457
+ return {
2458
+ type: "BendLoop",
2459
+ source: "While",
2460
+ test: node.test,
2461
+ body: transformNodes(node.body),
2462
+ stateVars: collectLoopStateVars(node.body)
2463
+ };
2464
+ }
2465
+ function collectLoopStateVars(body) {
2466
+ const vars = /* @__PURE__ */ new Set();
2467
+ for (const stmt of body) {
2468
+ if (stmt.type === "Assign") {
2469
+ const target = stmt.target;
2470
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(target)) {
2471
+ vars.add(target);
2472
+ }
2473
+ }
2474
+ if (stmt.type === "AugAssign") {
2475
+ const target = stmt.target;
2476
+ if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(target)) {
2477
+ vars.add(target);
2478
+ }
2479
+ }
2480
+ }
2481
+ return Array.from(vars);
2482
+ }
2483
+ function transformClass(node) {
2484
+ const fields = extractFields(node.body);
2485
+ const methods = [];
2486
+ for (const member of node.body) {
2487
+ if (member.type === "FunctionDef") {
2488
+ methods.push(transformFunctionDef(member));
2489
+ }
2490
+ }
2491
+ return {
2492
+ type: "BendObject",
2493
+ source: "ClassDef",
2494
+ name: node.name,
2495
+ bases: node.bases,
2496
+ fields,
2497
+ methods
2498
+ };
2499
+ }
2500
+ function extractFields(body) {
2501
+ const fields = [];
2502
+ const initMethod = body.find(
2503
+ (n) => n.type === "FunctionDef" && n.name === "__init__"
2504
+ );
2505
+ if (!initMethod) return fields;
2506
+ for (const stmt of initMethod.body) {
2507
+ if (stmt.type === "Assign") {
2508
+ const assign = stmt;
2509
+ const fieldMatch = assign.target.match(/^self\.([A-Za-z_][A-Za-z0-9_]*)$/);
2510
+ if (fieldMatch) {
2511
+ fields.push(fieldMatch[1]);
2512
+ }
2513
+ }
2514
+ }
2515
+ return fields;
2516
+ }
2517
+ function transformTry(node) {
2518
+ return {
2519
+ type: "BendWith",
2520
+ source: "Try",
2521
+ body: transformNodes(node.body),
2522
+ handler: node.handler ? {
2523
+ name: node.handler.name,
2524
+ type: node.handler.type,
2525
+ body: transformNodes(node.handler.body)
2526
+ } : null
2527
+ };
2528
+ }
2529
+ function passthrough(node) {
2530
+ return {
2531
+ type: "BendPassthrough",
2532
+ source: node.type,
2533
+ node
2534
+ };
2535
+ }
2536
+
2537
+ // ../../lib/py2bend/media-stdlib.ts
2538
+ var MEDIA_BUILTIN_MAP = {
2539
+ // Frame generation
2540
+ "render_frame": "Media/render_frame",
2541
+ "encode_video": "Media/encode_video",
2542
+ "encode_audio": "Media/encode_audio",
2543
+ // Kuramoto utilities
2544
+ "kuramoto_step": "Phase/kuramoto_step",
2545
+ "order_parameter": "Phase/order_parameter",
2546
+ // Audio synthesis
2547
+ "oscillator": "Audio/oscillator",
2548
+ "mix_channels": "Audio/mix",
2549
+ "soft_clip": "Audio/soft_clip",
2550
+ "fade": "Audio/fade",
2551
+ // Math shortcuts
2552
+ "linspace": "List/linspace",
2553
+ "zeros": "List/zeros",
2554
+ "sin": "Num/sin",
2555
+ "cos": "Num/cos",
2556
+ "tanh": "Num/tanh",
2557
+ "exp": "Num/exp",
2558
+ "log2": "Num/log2",
2559
+ "pi": "Num/pi"
2560
+ };
2561
+
2562
+ // ../../lib/py2bend/stdlib.ts
2563
+ var BUILTIN_MAP = {
2564
+ len: "List/len",
2565
+ print: "IO/print",
2566
+ range: "List/range",
2567
+ int: "Num/to_int",
2568
+ float: "Num/to_float",
2569
+ str: "Str/from",
2570
+ bool: "Bool/from",
2571
+ abs: "Num/abs",
2572
+ min: "Num/min",
2573
+ max: "Num/max",
2574
+ sum: "List/sum",
2575
+ sorted: "List/sort",
2576
+ reversed: "List/reverse",
2577
+ enumerate: "List/enumerate",
2578
+ zip: "List/zip",
2579
+ map: "List/map",
2580
+ filter: "List/filter",
2581
+ any: "List/any",
2582
+ all: "List/all",
2583
+ isinstance: "Type/is",
2584
+ type: "Type/of",
2585
+ input: "IO/input",
2586
+ open: "IO/open",
2587
+ round: "Num/round",
2588
+ list: "List/from",
2589
+ dict: "Map/from",
2590
+ tuple: "Tuple/from",
2591
+ set: "Set/from",
2592
+ // Media builtins (from media-stdlib.ts)
2593
+ ...MEDIA_BUILTIN_MAP
2594
+ };
2595
+ var OP_MAP = {
2596
+ "+": "+",
2597
+ "-": "-",
2598
+ "*": "*",
2599
+ "/": "/",
2600
+ "//": "/",
2601
+ "%": "%",
2602
+ "**": "**",
2603
+ "&": "&",
2604
+ "|": "|",
2605
+ "==": "==",
2606
+ "!=": "!=",
2607
+ "<": "<",
2608
+ ">": ">",
2609
+ "<=": "<=",
2610
+ ">=": ">=",
2611
+ and: "&",
2612
+ or: "|",
2613
+ not: "!",
2614
+ in: "List/contains",
2615
+ "not in": "List/not_contains"
2616
+ };
2617
+
2618
+ // ../../lib/py2bend/codegen.ts
2619
+ function generateBend(module) {
2620
+ const lines = [];
2621
+ for (const node of module.body) {
2622
+ lines.push(generateNode(node, 0));
2623
+ }
2624
+ return lines.join("\n\n") + "\n";
2625
+ }
2626
+ function generateNode(node, depth) {
2627
+ switch (node.type) {
2628
+ case "BendFunctionDef":
2629
+ return generateFunctionDef(node, depth);
2630
+ case "BendFold":
2631
+ return generateFold(node, depth);
2632
+ case "BendLoop":
2633
+ return generateLoop(node, depth);
2634
+ case "BendObject":
2635
+ return generateObject(node, depth);
2636
+ case "BendWith":
2637
+ return generateWith(node, depth);
2638
+ case "BendPassthrough":
2639
+ return generatePassthrough(node, depth);
2640
+ default:
2641
+ return indent(depth) + `# unsupported: ${node.type}`;
2642
+ }
2643
+ }
2644
+ function generateFunctionDef(node, depth) {
2645
+ const params = node.params.join(", ");
2646
+ const head = `${indent(depth)}def ${node.name}(${params}):`;
2647
+ const bodyLines = node.body.map((n) => generateNode(n, depth + 1));
2648
+ if (bodyLines.length === 0) {
2649
+ return head + "\n" + indent(depth + 1) + "return *";
2650
+ }
2651
+ return head + "\n" + bodyLines.join("\n");
2652
+ }
2653
+ function generateFold(node, depth) {
2654
+ const iterExpr = generateExpr(node.iter, depth);
2655
+ const head = `${indent(depth)}fold ${iterExpr}:`;
2656
+ const consCase = `${indent(depth + 1)}case List/Cons:`;
2657
+ const bodyLines = node.body.map((n) => generateNode(n, depth + 2));
2658
+ const nilCase = `${indent(depth + 1)}case List/Nil:`;
2659
+ const nilBody = node.accumulator ? `${indent(depth + 2)}${node.accumulator}` : `${indent(depth + 2)}*`;
2660
+ return [head, consCase, ...bodyLines, nilCase, nilBody].join("\n");
2661
+ }
2662
+ function generateLoop(node, depth) {
2663
+ const testExpr = generateExpr(node.test, depth);
2664
+ const head = `${indent(depth)}bend x = 0:`;
2665
+ const whenLine = `${indent(depth + 1)}when ${testExpr}:`;
2666
+ const bodyLines = node.body.map((n) => generateNode(n, depth + 2));
2667
+ const forkLine = `${indent(depth + 2)}fork(x + 1)`;
2668
+ const elseLine = `${indent(depth + 1)}else:`;
2669
+ const elseBody = `${indent(depth + 2)}x`;
2670
+ return [head, whenLine, ...bodyLines, forkLine, elseLine, elseBody].join(
2671
+ "\n"
2672
+ );
2673
+ }
2674
+ function generateObject(node, depth) {
2675
+ const fieldsStr = node.fields.length > 0 ? ` { ${node.fields.join(", ")} }` : "";
2676
+ const head = `${indent(depth)}object ${node.name}${fieldsStr}`;
2677
+ if (node.methods.length === 0) {
2678
+ return head;
2679
+ }
2680
+ const nonInitMethods = node.methods.filter((m) => m.name !== "__init__");
2681
+ if (nonInitMethods.length === 0) {
2682
+ return head;
2683
+ }
2684
+ const methodLines = nonInitMethods.map(
2685
+ (m) => generateFunctionDef(m, depth)
2686
+ );
2687
+ return head + "\n\n" + methodLines.join("\n\n");
2688
+ }
2689
+ function generateWith(node, depth) {
2690
+ const head = `${indent(depth)}with Result:`;
2691
+ const bodyLines = node.body.map((n) => generateNode(n, depth + 1));
2692
+ if (!node.handler) {
2693
+ return [head, ...bodyLines].join("\n");
2694
+ }
2695
+ const handlerLines = node.handler.body.map(
2696
+ (n) => generateNode(n, depth + 1)
2697
+ );
2698
+ const handlerHead = node.handler.name ? `${indent(depth)}catch ${node.handler.name}:` : `${indent(depth)}catch _err:`;
2699
+ return [head, ...bodyLines, handlerHead, ...handlerLines].join("\n");
2700
+ }
2701
+ function generatePassthrough(node, depth) {
2702
+ return generatePyStatement(node.node, depth);
2703
+ }
2704
+ function generatePyStatement(node, depth) {
2705
+ switch (node.type) {
2706
+ case "Return":
2707
+ return generateReturn(node, depth);
2708
+ case "Assign":
2709
+ return generateAssign(node, depth);
2710
+ case "AugAssign":
2711
+ return generateAugAssign(node, depth);
2712
+ case "If":
2713
+ return generateIf(node, depth);
2714
+ case "Expr":
2715
+ return indent(depth) + generateExpr(node.value, depth);
2716
+ default:
2717
+ return indent(depth) + generateExpr(node, depth);
2718
+ }
2719
+ }
2720
+ function generateReturn(node, depth) {
2721
+ if (!node.value) {
2722
+ return `${indent(depth)}return *`;
2723
+ }
2724
+ return `${indent(depth)}return ${generateExpr(node.value, depth)}`;
2725
+ }
2726
+ function generateAssign(node, depth) {
2727
+ return `${indent(depth)}let ${node.target} = ${generateExpr(node.value, depth)}`;
2728
+ }
2729
+ function generateAugAssign(node, depth) {
2730
+ const op = node.op.slice(0, -1);
2731
+ const mappedOp = OP_MAP[op] ?? op;
2732
+ return `${indent(depth)}let ${node.target} = (${node.target} ${mappedOp} ${generateExpr(node.value, depth)})`;
2733
+ }
2734
+ function generateIf(node, depth) {
2735
+ const testExpr = generateExpr(node.test, depth);
2736
+ const head = `${indent(depth)}if ${testExpr}:`;
2737
+ const bodyLines = node.body.map(
2738
+ (n) => generatePyStatement(n, depth + 1)
2739
+ );
2740
+ if (!node.orelse || node.orelse.length === 0) {
2741
+ return [head, ...bodyLines].join("\n");
2742
+ }
2743
+ const elseLine = `${indent(depth)}else:`;
2744
+ const elseLines = node.orelse.map(
2745
+ (n) => generatePyStatement(n, depth + 1)
2746
+ );
2747
+ return [head, ...bodyLines, elseLine, ...elseLines].join("\n");
2748
+ }
2749
+ function generateExpr(node, _depth) {
2750
+ switch (node.type) {
2751
+ case "Name":
2752
+ return node.id;
2753
+ case "Constant":
2754
+ return generateConstant(node);
2755
+ case "BinOp": {
2756
+ const binop = node;
2757
+ const mappedOp = OP_MAP[binop.op] ?? binop.op;
2758
+ return `(${generateExpr(binop.left, _depth)} ${mappedOp} ${generateExpr(binop.right, _depth)})`;
2759
+ }
2760
+ case "UnaryOp": {
2761
+ const unary = node;
2762
+ const mappedOp = OP_MAP[unary.op] ?? unary.op;
2763
+ if (mappedOp === "!") {
2764
+ return `(!${generateExpr(unary.operand, _depth)})`;
2765
+ }
2766
+ return `(${mappedOp}${generateExpr(unary.operand, _depth)})`;
2767
+ }
2768
+ case "Compare": {
2769
+ const cmp = node;
2770
+ if (cmp.ops.length === 1) {
2771
+ const mappedOp = OP_MAP[cmp.ops[0]] ?? cmp.ops[0];
2772
+ return `(${generateExpr(cmp.left, _depth)} ${mappedOp} ${generateExpr(cmp.comparators[0], _depth)})`;
2773
+ }
2774
+ const parts = [];
2775
+ let prevExpr = generateExpr(cmp.left, _depth);
2776
+ for (let i = 0; i < cmp.ops.length; i++) {
2777
+ const mappedOp = OP_MAP[cmp.ops[i]] ?? cmp.ops[i];
2778
+ const rightExpr = generateExpr(cmp.comparators[i], _depth);
2779
+ parts.push(`(${prevExpr} ${mappedOp} ${rightExpr})`);
2780
+ prevExpr = rightExpr;
2781
+ }
2782
+ return parts.join(" & ");
2783
+ }
2784
+ case "BoolOp": {
2785
+ const boolop = node;
2786
+ const mappedOp = OP_MAP[boolop.op] ?? boolop.op;
2787
+ const exprs = boolop.values.map((v) => generateExpr(v, _depth));
2788
+ return `(${exprs.join(` ${mappedOp} `)})`;
2789
+ }
2790
+ case "Call": {
2791
+ const call = node;
2792
+ const funcName = generateExpr(call.func, _depth);
2793
+ const mappedName = BUILTIN_MAP[funcName] ?? funcName;
2794
+ const args = call.args.map((a) => generateExpr(a, _depth));
2795
+ const kwargs = call.kwargs.map(
2796
+ (kw) => `${kw.key}=${generateExpr(kw.value, _depth)}`
2797
+ );
2798
+ const allArgs = [...args, ...kwargs].join(", ");
2799
+ return `${mappedName}(${allArgs})`;
2800
+ }
2801
+ case "Attribute": {
2802
+ const attr = node;
2803
+ return `${generateExpr(attr.value, _depth)}.${attr.attr}`;
2804
+ }
2805
+ case "Subscript": {
2806
+ const sub = node;
2807
+ return `List/get(${generateExpr(sub.value, _depth)}, ${generateExpr(sub.slice, _depth)})`;
2808
+ }
2809
+ case "List": {
2810
+ const list = node;
2811
+ const elts = list.elts.map((e) => generateExpr(e, _depth));
2812
+ return `[${elts.join(", ")}]`;
2813
+ }
2814
+ case "Dict": {
2815
+ const dict = node;
2816
+ const entries = dict.keys.map(
2817
+ (k, i) => `${generateExpr(k, _depth)}: ${generateExpr(dict.values[i], _depth)}`
2818
+ );
2819
+ return `{${entries.join(", ")}}`;
2820
+ }
2821
+ case "Lambda": {
2822
+ const lam = node;
2823
+ const params = lam.params.join(", ");
2824
+ return `@${params} ${generateExpr(lam.body, _depth)}`;
2825
+ }
2826
+ default:
2827
+ return `/* unsupported: ${node.type} */`;
2828
+ }
2829
+ }
2830
+ function generateConstant(node) {
2831
+ switch (node.kind) {
2832
+ case "str":
2833
+ return `"${String(node.value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
2834
+ case "int":
2835
+ case "float":
2836
+ return String(node.value);
2837
+ case "bool":
2838
+ return node.value ? "True" : "False";
2839
+ case "none":
2840
+ return "*";
2841
+ default:
2842
+ return String(node.value);
2843
+ }
2844
+ }
2845
+ function indent(depth) {
2846
+ return " ".repeat(depth);
2847
+ }
2848
+
2849
+ // ../../lib/py2bend/index.ts
2850
+ function compile(pythonSource) {
2851
+ const warnings = [];
2852
+ const { ast, errors: parseErrors } = parsePython(pythonSource);
2853
+ if (!ast) {
2854
+ return {
2855
+ bend: "",
2856
+ errors: parseErrors,
2857
+ warnings
2858
+ };
2859
+ }
2860
+ const errors = parseErrors.filter((e) => e.severity === "error");
2861
+ const parseWarnings = parseErrors.filter((e) => e.severity === "warning");
2862
+ warnings.push(...parseWarnings.map((w) => w.message));
2863
+ const bendModule = transformModule(ast);
2864
+ const bend = generateBend(bendModule);
2865
+ return {
2866
+ bend,
2867
+ errors,
2868
+ warnings
2869
+ };
2870
+ }
2871
+
2872
+ // ../../lib/hermes/hvm-bridge.ts
2873
+ var HermesHVMBridge = class {
2874
+ metrics = {
2875
+ totalReductions: 0,
2876
+ lastDurationMs: 0,
2877
+ avgDurationMs: 0,
2878
+ lastStrategy: "none"
2879
+ };
2880
+ /**
2881
+ * Create an HVM-compatible manifest from Bend source.
2882
+ * Returns a NodeManifestV0 with a "wasm-hvm" entrypoint pointing
2883
+ * to an .hvm module for the HVM runner to execute.
2884
+ */
2885
+ createManifest(bendSource) {
2886
+ return {
2887
+ id: `hermes-bend-${Date.now()}`,
2888
+ version: "1.0.0",
2889
+ kind: "custom",
2890
+ name: "Hermes Bend Execution",
2891
+ runtimes: ["wasm-hvm"],
2892
+ entrypoints: {
2893
+ "wasm-hvm": {
2894
+ module: "hermes-compiled.hvm",
2895
+ function: "main"
2896
+ }
2897
+ },
2898
+ metadata: {
2899
+ source: "py2bend",
2900
+ bendSource
2901
+ }
2902
+ };
2903
+ }
2904
+ /**
2905
+ * Compute logit bias hints from py2bend compilation structure.
2906
+ * Analyzes the Bend output for structural features (fold count,
2907
+ * bend count, object count) and maps them to control token bias
2908
+ * hints that downstream adapters can translate into provider-specific
2909
+ * logit_bias token IDs.
2910
+ */
2911
+ computeLogitBias(compiled) {
2912
+ const lines = compiled.bend.split("\n");
2913
+ const bias = {};
2914
+ let foldCount = 0;
2915
+ let bendCount = 0;
2916
+ let objectCount = 0;
2917
+ for (const line of lines) {
2918
+ const trimmed = line.trim();
2919
+ if (trimmed.startsWith("fold")) foldCount++;
2920
+ if (trimmed.startsWith("bend")) bendCount++;
2921
+ if (trimmed.startsWith("object")) objectCount++;
2922
+ }
2923
+ if (foldCount > 0) {
2924
+ bias["control:decompose"] = 0.15 * Math.min(foldCount, 5);
2925
+ bias["control:structure"] = 0.1;
2926
+ }
2927
+ if (bendCount > 0) {
2928
+ bias["control:parallel"] = 0.15 * Math.min(bendCount, 5);
2929
+ bias["control:branch"] = 0.1;
2930
+ }
2931
+ if (objectCount > 0) {
2932
+ bias["control:synthesize"] = 0.1 * Math.min(objectCount, 5);
2933
+ }
2934
+ return bias;
2935
+ }
2936
+ /**
2937
+ * Execute Bend source through the HVM runner.
2938
+ * Dynamically imports runInHVM, creates a manifest, executes,
2939
+ * and updates internal reduction metrics.
2940
+ */
2941
+ async executeBend(bendSource) {
2942
+ const manifest = this.createManifest(bendSource);
2943
+ try {
2944
+ const { runInHVM } = await import("./hvm-A7DGZ3Q5.js");
2945
+ const output = await runInHVM(
2946
+ manifest,
2947
+ { bendSource },
2948
+ { stackId: "hermes", nodeId: "bend-exec" }
2949
+ );
2950
+ const hvmResult = output != null && typeof output === "object" ? output : {};
2951
+ const rawHvm = hvmResult._hvm;
2952
+ const hvm = rawHvm != null && typeof rawHvm === "object" ? rawHvm : {};
2953
+ const durationMs = typeof hvm.durationMs === "number" ? hvm.durationMs : 0;
2954
+ this.metrics.totalReductions++;
2955
+ this.metrics.lastDurationMs = durationMs;
2956
+ this.metrics.lastStrategy = typeof hvm.strategy === "string" ? hvm.strategy : "unknown";
2957
+ this.metrics.avgDurationMs = (this.metrics.avgDurationMs * (this.metrics.totalReductions - 1) + durationMs) / this.metrics.totalReductions;
2958
+ return {
2959
+ result: hvmResult.result,
2960
+ reduced: typeof hvm.reduced === "boolean" ? hvm.reduced : false,
2961
+ strategy: typeof hvm.strategy === "string" ? hvm.strategy : "unknown",
2962
+ durationMs,
2963
+ ...typeof hvmResult.error === "string" ? { error: hvmResult.error } : {}
2964
+ };
2965
+ } catch (error) {
2966
+ console.warn("[HermesHVMBridge] executeBend failed:", error);
2967
+ const message = error instanceof Error ? error.message : String(error);
2968
+ return {
2969
+ result: null,
2970
+ reduced: false,
2971
+ strategy: "error",
2972
+ durationMs: 0,
2973
+ error: message
2974
+ };
2975
+ }
2976
+ }
2977
+ /** Returns a snapshot of current reduction metrics */
2978
+ getMetrics() {
2979
+ return { ...this.metrics };
2980
+ }
2981
+ };
2982
+
2983
+ // ../../lib/terminals-tech/sdk/manifold.ts
2984
+ function now() {
2985
+ return typeof performance !== "undefined" ? performance.now() : Date.now();
2986
+ }
2987
+ function clamp(value, min, max) {
2988
+ return Math.min(max, Math.max(min, value));
2989
+ }
2990
+ function normalizeWhitespace(value) {
2991
+ return value.replace(/\s+/g, " ").trim();
2992
+ }
2993
+ function toPythonProjection(intent, context) {
2994
+ const normalizedIntent = normalizeWhitespace(intent);
2995
+ const normalizedContext = normalizeWhitespace(context).slice(0, 180);
2996
+ const target = normalizeWhitespace(intent.replace(/[^a-zA-Z0-9 ]/g, "")).slice(0, 80);
2997
+ return [
2998
+ "def collapsed_intent(context_state):",
2999
+ ` # Intent: ${normalizedIntent.replace(/#/g, "")}`,
3000
+ ` # Context: ${normalizedContext.replace(/#/g, "")}`,
3001
+ ` target = ${JSON.stringify(target || normalizedIntent || "resolve")}`,
3002
+ " return target"
3003
+ ].join("\n");
3004
+ }
3005
+ function computeNormalizedEntropy(value) {
3006
+ if (!value) return 0;
3007
+ const counts = /* @__PURE__ */ new Map();
3008
+ for (const ch of value) {
3009
+ counts.set(ch, (counts.get(ch) ?? 0) + 1);
3010
+ }
3011
+ let bits = 0;
3012
+ for (const count of counts.values()) {
3013
+ const p = count / value.length;
3014
+ bits -= p * Math.log2(p);
3015
+ }
3016
+ return clamp(bits / 6, 0, 1);
3017
+ }
3018
+ function deriveSteps(bend, maxSteps, durationMs) {
3019
+ const structuralLines = bend.split("\n").map((line) => line.trim()).filter(Boolean).length;
3020
+ const runtimeUnits = durationMs ? Math.ceil(durationMs) : 0;
3021
+ return clamp(Math.max(structuralLines, runtimeUnits, 1), 1, maxSteps);
3022
+ }
3023
+ function buildResultMessage(reduction, steps) {
3024
+ if (reduction.reduced) {
3025
+ return `Manifold annihilated through ${reduction.strategy} in ${reduction.durationMs.toFixed(2)}ms across ${steps} reduction units.`;
3026
+ }
3027
+ if (reduction.errors.length > 0) {
3028
+ return `Manifold annihilation failed after compilation: ${reduction.errors[0]}`;
3029
+ }
3030
+ if (reduction.compiled) {
3031
+ return `Manifold compiled to Bend but did not reduce in HVM. Strategy: ${reduction.strategy}.`;
3032
+ }
3033
+ return reduction.errors[0] ? `Manifold annihilation failed at compile boundary: ${reduction.errors[0]}` : "Manifold annihilation failed before structural reduction.";
3034
+ }
3035
+ async function annihilate(intent, context, options = {}) {
3036
+ const maxSteps = options.maxSteps ?? 2e3;
3037
+ const threshold = options.convergenceThreshold ?? 0.9;
3038
+ const gravity = options.gravity ?? 2.5;
3039
+ const gravityScale = clamp(gravity / 2.5, 0.5, 1.5);
3040
+ const resolvedContext = context ?? globalStateMirror.encodeToManifold();
3041
+ const config = dmt55Engine.getObserverConfiguration(1);
3042
+ const evidence = dmt55Engine.generateMicroLMEvidence(1);
3043
+ emitSignal("mesh_update", "L4", "L3", {
3044
+ type: "manifold_annihilation_start",
3045
+ intentLength: intent.length,
3046
+ contextLength: resolvedContext.length,
3047
+ dimensions: config.totalDimensions,
3048
+ gravity
3049
+ });
3050
+ const pythonSource = intent.includes("def ") || intent.includes("class ") ? intent : toPythonProjection(intent, resolvedContext);
3051
+ const compileStart = now();
3052
+ const compileResult = compile(pythonSource);
3053
+ const compileDurationMs = now() - compileStart;
3054
+ const compileErrors = compileResult.errors.map((error) => error.message);
3055
+ const hvmBridge = new HermesHVMBridge();
3056
+ const logitBias = hvmBridge.computeLogitBias(compileResult);
3057
+ let reduction = {
3058
+ compiled: compileErrors.length === 0,
3059
+ reduced: false,
3060
+ strategy: "compile-only",
3061
+ runtime: "compile-only",
3062
+ durationMs: compileDurationMs,
3063
+ warnings: [...compileResult.warnings],
3064
+ errors: compileErrors,
3065
+ logitBias
3066
+ };
3067
+ if (reduction.compiled && compileResult.bend.trim().length > 0) {
3068
+ const hvmExecution = await hvmBridge.executeBend(compileResult.bend);
3069
+ const runtimeErrors = [...compileErrors, ...hvmExecution.error ? [hvmExecution.error] : []];
3070
+ reduction = {
3071
+ compiled: true,
3072
+ reduced: hvmExecution.reduced,
3073
+ strategy: hvmExecution.strategy,
3074
+ runtime: "wasm-hvm",
3075
+ durationMs: hvmExecution.durationMs || compileDurationMs,
3076
+ warnings: [...compileResult.warnings],
3077
+ errors: hvmExecution.reduced ? [] : runtimeErrors,
3078
+ logitBias
3079
+ };
3080
+ }
3081
+ const steps = deriveSteps(compileResult.bend, maxSteps, reduction.durationMs);
3082
+ const entropySeed = reduction.reduced ? `${compileResult.bend}
3083
+ ${JSON.stringify(reduction.logitBias)}` : reduction.errors.join(" | ") || compileErrors.join(" | ") || intent;
3084
+ const activationEntropy = computeNormalizedEntropy(entropySeed);
3085
+ let R = evidence.confidence;
3086
+ if (!reduction.compiled) {
3087
+ R = clamp(
3088
+ 0.18 + compileResult.warnings.length * 0.01 - compileErrors.length * 0.03 + (gravityScale - 1) * 0.04,
3089
+ 0.05,
3090
+ 0.58
3091
+ );
3092
+ } else if (reduction.reduced) {
3093
+ const speedBonus = clamp((0.08 - reduction.durationMs / 2500) * gravityScale, 0, 0.08);
3094
+ const strategyBonus = reduction.strategy === "wasm" || reduction.strategy === "hvm-core" ? 0.03 : 0;
3095
+ const warningPenalty = Math.min(reduction.warnings.length * 0.01, 0.05);
3096
+ R = clamp(threshold + 0.02 + speedBonus + strategyBonus - warningPenalty, threshold, 0.99);
3097
+ } else {
3098
+ R = clamp(
3099
+ 0.62 - reduction.warnings.length * 0.02 + (gravityScale - 1) * 0.03,
3100
+ 0.3,
3101
+ threshold - 0.01
3102
+ );
3103
+ }
3104
+ const result = buildResultMessage(reduction, steps);
3105
+ const sematon = createSematon({
3106
+ kind: "interaction",
3107
+ payload: {
3108
+ result,
3109
+ steps,
3110
+ intent,
3111
+ contextSnapshot: resolvedContext.substring(0, 140),
3112
+ bendCode: reduction.compiled ? compileResult.bend : void 0,
3113
+ reduction
3114
+ },
3115
+ witness: {
3116
+ R,
3117
+ activationEntropy,
3118
+ converged: reduction.reduced && R >= threshold,
3119
+ step: steps
3120
+ },
3121
+ source: "manifold_annihilation"
3122
+ });
3123
+ const observableEvidence = buildObservableEvidenceFromSematon(sematon, "Reduction Witness");
3124
+ emitSignal("sematon_created", "L4", "L3", {
3125
+ sematonId: sematon.id,
3126
+ source: "manifold_annihilation"
3127
+ });
3128
+ emitSignal("sematon_realized", "L4", "L3", {
3129
+ sematonId: sematon.id,
3130
+ converged: sematon.witness.converged
3131
+ });
3132
+ emitSignal("mesh_update", "L4", "L3", {
3133
+ type: "manifold_annihilation_complete",
3134
+ sematonId: sematon.id,
3135
+ R,
3136
+ durationMs: reduction.durationMs,
3137
+ strategy: reduction.strategy,
3138
+ observableEvidence
3139
+ });
3140
+ return sematon;
3141
+ }
3142
+ var manifold = {
3143
+ annihilate
3144
+ };
3145
+
3146
+ // ../../lib/terminals-tech/sdk/observer.ts
3147
+ var observer_exports = {};
3148
+ __export(observer_exports, {
3149
+ ObserverKernel: () => ObserverKernel,
3150
+ disposeObserverKernel: () => disposeObserverKernel,
3151
+ getObserverKernel: () => getObserverKernel
3152
+ });
3153
+ import { BehaviorSubject as BehaviorSubject2 } from "rxjs";
3154
+ var ObserverKernel = class {
3155
+ id;
3156
+ heartbeatHz;
3157
+ mirror;
3158
+ activeNeurons = /* @__PURE__ */ new Map();
3159
+ coherenceR$ = new BehaviorSubject2(0);
3160
+ pulseTimer = null;
3161
+ constructor(config) {
3162
+ this.id = config.id;
3163
+ this.heartbeatHz = config.heartbeatHz ?? 60;
3164
+ this.mirror = config.stateMirror ?? globalStateMirror;
3165
+ }
3166
+ get coherence() {
3167
+ return this.coherenceR$.value;
3168
+ }
3169
+ get isRunning() {
3170
+ return this.pulseTimer !== null;
3171
+ }
3172
+ /** Starts the continuous heartbeat */
3173
+ start() {
3174
+ if (this.pulseTimer) return;
3175
+ const intervalMs = 1e3 / this.heartbeatHz;
3176
+ this.pulseTimer = setInterval(() => this.pulse(), intervalMs);
3177
+ getSignalBus().emit("mesh_update", "L4", "L3", {
3178
+ type: "observer_started",
3179
+ observerId: this.id
3180
+ });
3181
+ }
3182
+ /** Stops the heartbeat */
3183
+ stop() {
3184
+ if (this.pulseTimer) {
3185
+ clearInterval(this.pulseTimer);
3186
+ this.pulseTimer = null;
3187
+ }
3188
+ }
3189
+ /** The continuous observation loop */
3190
+ pulse() {
3191
+ const state = this.mirror.snapshot;
3192
+ const targetR = state.coherenceR;
3193
+ const currentR = this.coherenceR$.value;
3194
+ const nextR = currentR * 0.95 + targetR * 0.05;
3195
+ this.coherenceR$.next(nextR);
3196
+ }
3197
+ /** Equips a new geometric constraint (Neuron) onto the observer */
3198
+ equipNeuron(neuron) {
3199
+ this.activeNeurons.set(neuron.id, neuron);
3200
+ getSignalBus().emit("mesh_update", "L4", "L3", {
3201
+ type: "neuron_equipped",
3202
+ observerId: this.id,
3203
+ neuronId: neuron.id
3204
+ });
3205
+ }
3206
+ /** Unequips a Neuron */
3207
+ unequipNeuron(neuronId) {
3208
+ this.activeNeurons.delete(neuronId);
3209
+ }
3210
+ /** Replace the active neuron field in one operation. */
3211
+ syncNeurons(neurons) {
3212
+ this.activeNeurons.clear();
3213
+ for (const neuron of neurons) {
3214
+ this.activeNeurons.set(neuron.id, neuron);
3215
+ }
3216
+ getSignalBus().emit("mesh_update", "L4", "L3", {
3217
+ type: "observer_field_synced",
3218
+ observerId: this.id,
3219
+ neuronCount: neurons.length
3220
+ });
3221
+ }
3222
+ /**
3223
+ * The core execution path:
3224
+ * Flattens the active Neurons + StateMirror context, then drops them into the Annihilator.
3225
+ */
3226
+ async resolve(intent) {
3227
+ this.pulse();
3228
+ const contextManifold = this.mirror.encodeToManifold();
3229
+ let injectedIntent = intent;
3230
+ if (this.activeNeurons.size > 0) {
3231
+ const neuronIds = Array.from(this.activeNeurons.keys()).join(", ");
3232
+ injectedIntent = `
3233
+ @apply_neurons(${neuronIds})
3234
+ ${intent}
3235
+ `.trim();
3236
+ }
3237
+ return await annihilate(injectedIntent, contextManifold, {
3238
+ convergenceThreshold: 0.9,
3239
+ gravity: 2.5
3240
+ });
3241
+ }
3242
+ };
3243
+ var OBSERVER_IDLE_TTL_MS = 5 * 60 * 1e3;
3244
+ var observerRegistry = /* @__PURE__ */ new Map();
3245
+ function pruneObserverRegistry(now2) {
3246
+ for (const [id, entry] of observerRegistry.entries()) {
3247
+ if (entry.kernel.isRunning) continue;
3248
+ if (now2 - entry.lastUsedAt > OBSERVER_IDLE_TTL_MS) {
3249
+ observerRegistry.delete(id);
3250
+ }
3251
+ }
3252
+ }
3253
+ function disposeObserverKernel(id) {
3254
+ const entry = observerRegistry.get(id);
3255
+ if (!entry) return;
3256
+ entry.kernel.stop();
3257
+ observerRegistry.delete(id);
3258
+ }
3259
+ function getObserverKernel(id, config = {}) {
3260
+ const now2 = Date.now();
3261
+ pruneObserverRegistry(now2);
3262
+ const existing = observerRegistry.get(id);
3263
+ if (existing) {
3264
+ existing.lastUsedAt = now2;
3265
+ return existing.kernel;
3266
+ }
3267
+ const kernel = new ObserverKernel({ id, ...config });
3268
+ observerRegistry.set(id, { kernel, lastUsedAt: now2 });
3269
+ return kernel;
3270
+ }
3271
+
3272
+ // ../../lib/terminals-tech/axon/protocol.ts
3273
+ var AXON_CONSTANTS = {
3274
+ HEADER_SIZE: 16,
3275
+ MAX_MESSAGE_SIZE: 1024 * 64,
3276
+ // 64KB
3277
+ TICK_RATE_MS: 16
3278
+ // ~60Hz
3279
+ };
3280
+ function highLevelToSDKMessage(msg) {
3281
+ const parseOrCreate = (addr) => {
3282
+ try {
3283
+ return parseAddress(addr);
3284
+ } catch {
3285
+ return { layer: "L3", nodeType: "agent", nodeId: addr };
3286
+ }
3287
+ };
3288
+ const mapProtocolType = (type) => {
3289
+ if (!type) return void 0;
3290
+ if (type === "mcp" || type === "a2a") return type;
3291
+ return "internal";
3292
+ };
3293
+ return {
3294
+ id: msg.id,
3295
+ type: msg.type,
3296
+ source: parseOrCreate(msg.source),
3297
+ target: parseOrCreate(msg.target),
3298
+ payload: msg.payload,
3299
+ meta: {
3300
+ timestamp: msg.meta.timestamp,
3301
+ traceId: msg.meta.traceId,
3302
+ priority: msg.meta.priority,
3303
+ correlationId: msg.meta.correlationId,
3304
+ ttl: msg.meta.ttl,
3305
+ sessionId: msg.meta.sessionId,
3306
+ interactionId: msg.meta.interactionId
3307
+ },
3308
+ protocol: msg.protocol ? {
3309
+ type: mapProtocolType(msg.protocol.type) ?? "internal",
3310
+ version: msg.protocol.version,
3311
+ originalMessage: msg.protocol.originalMessage
3312
+ } : void 0,
3313
+ capability: msg.capability
3314
+ };
3315
+ }
3316
+ function sdkMessageToHighLevel(msg) {
3317
+ const mapProtocolType = (type) => {
3318
+ if (!type) return void 0;
3319
+ if (type === "mcp" || type === "a2a" || type === "internal") return type;
3320
+ return "internal";
3321
+ };
3322
+ return {
3323
+ id: msg.id,
3324
+ type: msg.type,
3325
+ source: formatAddress(msg.source),
3326
+ target: formatAddress(msg.target),
3327
+ payload: msg.payload,
3328
+ meta: {
3329
+ timestamp: msg.meta.timestamp,
3330
+ traceId: msg.meta.traceId,
3331
+ priority: msg.meta.priority,
3332
+ correlationId: msg.meta.correlationId,
3333
+ ttl: msg.meta.ttl,
3334
+ sessionId: msg.meta.sessionId,
3335
+ interactionId: msg.meta.interactionId
3336
+ },
3337
+ protocol: msg.protocol ? {
3338
+ type: mapProtocolType(msg.protocol.type) ?? "internal",
3339
+ version: msg.protocol.version,
3340
+ originalMessage: msg.protocol.originalMessage
1341
3341
  } : void 0,
1342
3342
  capability: msg.capability
1343
3343
  };
@@ -1817,13 +3817,15 @@ function createAxonBus() {
1817
3817
  }
1818
3818
 
1819
3819
  // src/index.ts
1820
- var SDK_VERSION = "1.0.0-rc.1";
3820
+ var SDK_VERSION = "1.0.0";
1821
3821
  export {
1822
3822
  brain_exports as Brain,
1823
3823
  core_exports as Core,
1824
3824
  InMemoryAxonBus,
1825
3825
  L0_exports as L0,
3826
+ manifold_exports as Manifold,
1826
3827
  mesh_exports as Mesh,
3828
+ observer_exports as Observer,
1827
3829
  protocol_exports as Protocol,
1828
3830
  ProtocolBridge,
1829
3831
  SDK_VERSION,
@@ -1832,6 +3834,29 @@ export {
1832
3834
  createAxonBus,
1833
3835
  createProtocolBridge
1834
3836
  };
3837
+ /**
3838
+ * ELI5 Result Types for @terminals-tech/agent
3839
+ *
3840
+ * Wraps internal Sematon<TerminalRunResult> into developer-friendly types.
3841
+ * Theory stays in the engine; developers get plain objects.
3842
+ *
3843
+ * @license MIT
3844
+ * @module agent/result
3845
+ */
3846
+ /**
3847
+ * Terminal.create() Developer API
3848
+ *
3849
+ * The developer-facing entry point for creating and running multi-agent
3850
+ * terminal workflows. Translates semantic configuration into the internal
3851
+ * StackManifestV0 / OrchestratorV0 infrastructure and wraps results as
3852
+ * Sematon<TerminalRunResult>.
3853
+ *
3854
+ * This is a headless API -- no React, no "use client".
3855
+ *
3856
+ * @license BUSL-1.1
3857
+ * @copyright 2026 Intuition Labs LLC. All rights reserved. Patent Pending.
3858
+ * @module agent-sdk/terminal
3859
+ */
1835
3860
  /**
1836
3861
  * L0 Category Theory Primitives
1837
3862
  *
@@ -1852,25 +3877,6 @@ export {
1852
3877
  * @copyright © 2026 Intuition Labs LLC. All rights reserved. Patent Pending.
1853
3878
  * @module core/L0/derivation
1854
3879
  */
1855
- /**
1856
- * L0 Sematon — The Smallest Meaning-Bearing Unit
1857
- *
1858
- * The sematon is the atomic unit of operational meaning in Terminals OS.
1859
- * It carries a typed payload, convergence witness, p-adic address,
1860
- * information-theoretic metrics, and a constructor flag that guarantees
1861
- * the Deutsch-Marletto invariant: after transforming an input, the
1862
- * sematon retains the ability to transform again.
1863
- *
1864
- * The sematon unifies Signal<T>, ContextNode, FractalSnapshot,
1865
- * ConvergenceWitness, and CombinatorEvent into a single formal type
1866
- * at the L0 foundation layer.
1867
- *
1868
- * Core Engine Primitive.
1869
- *
1870
- * @license BUSL-1.1
1871
- * @copyright © 2026 Intuition Labs LLC. All rights reserved. Patent Pending.
1872
- * @module core/L0/sematon
1873
- */
1874
3880
  /**
1875
3881
  * L0 Realizability Trace — Constructor Proof Runtime
1876
3882
  *