cunknown commited on
Commit
78fbaa9
·
verified ·
1 Parent(s): 7b7b37a

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +2 -0
  2. .github/workflows/jekyll-gh-pages.yml +51 -0
  3. .github/workflows/static.yml +43 -0
  4. LICENSE +21 -0
  5. PROPOSAL.md +87 -0
  6. README.md +216 -0
  7. bench/HYPOTHESES.md +55 -0
  8. bench/results/report.md +118 -0
  9. bench/results/results.json +484 -0
  10. examples/counter_app.nl +16 -0
  11. examples/fpga_blinker.nl +9 -0
  12. examples/game.nl +15 -0
  13. examples/smart_greenhouse.nl +23 -0
  14. nlcl/__init__.py +6 -0
  15. nlcl/__main__.py +78 -0
  16. nlcl/bench/__init__.py +1 -0
  17. nlcl/bench/__main__.py +3 -0
  18. nlcl/bench/corpus.py +206 -0
  19. nlcl/bench/corpus2.py +102 -0
  20. nlcl/bench/fixture.py +27 -0
  21. nlcl/bench/run.py +428 -0
  22. nlcl/composer.py +270 -0
  23. nlcl/discover.py +248 -0
  24. nlcl/fixer.py +576 -0
  25. nlcl/fuzzy.py +180 -0
  26. nlcl/interpreter.py +684 -0
  27. nlcl/ir.py +543 -0
  28. nlcl/kb/core.pl +134 -0
  29. nlcl/kb/pretrained.pl +49 -0
  30. nlcl/knowledge.py +188 -0
  31. nlcl/learn.py +308 -0
  32. nlcl/llm.py +331 -0
  33. nlcl/modules/__init__.py +43 -0
  34. nlcl/modules/_assets/3d/runtime.js +793 -0
  35. nlcl/modules/_assets/app/app_runtime.js +172 -0
  36. nlcl/modules/_assets/app/nlcl_app.py +424 -0
  37. nlcl/modules/_assets/cpp/nlcl_channels.cpp +35 -0
  38. nlcl/modules/_assets/cpp/nlcl_channels.hpp +514 -0
  39. nlcl/modules/_assets/cpp/nlcl_core.hpp +848 -0
  40. nlcl/modules/_assets/game/NlclEntity.cs +289 -0
  41. nlcl/modules/_assets/game/NlclHub.cs +254 -0
  42. nlcl/modules/_assets/game/NlclInput.cs +96 -0
  43. nlcl/modules/_assets/game/nlcl_world.gd +428 -0
  44. nlcl/modules/_assets/game/preview_runtime.js +401 -0
  45. nlcl/modules/_assets/hardware/nlcl_i2c_slave.v +159 -0
  46. nlcl/modules/_assets/hardware/nlcl_spi_slave.v +110 -0
  47. nlcl/modules/_assets/nlcl_runtime.py +579 -0
  48. nlcl/modules/app_mod.py +413 -0
  49. nlcl/modules/base.py +190 -0
  50. nlcl/modules/cad_mod.py +0 -0
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ screenshots/Screenshot[[:space:]]2026-11-26[[:space:]]024554.png filter=lfs diff=lfs merge=lfs -text
37
+ screenshots/Screenshot[[:space:]]2026-11-26[[:space:]]024937.png filter=lfs diff=lfs merge=lfs -text
.github/workflows/jekyll-gh-pages.yml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Sample workflow for building and deploying a Jekyll site to GitHub Pages
2
+ name: Deploy Jekyll with GitHub Pages dependencies preinstalled
3
+
4
+ on:
5
+ # Runs on pushes targeting the default branch
6
+ push:
7
+ branches: ["main"]
8
+
9
+ # Allows you to run this workflow manually from the Actions tab
10
+ workflow_dispatch:
11
+
12
+ # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
13
+ permissions:
14
+ contents: read
15
+ pages: write
16
+ id-token: write
17
+
18
+ # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
19
+ # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
20
+ concurrency:
21
+ group: "pages"
22
+ cancel-in-progress: false
23
+
24
+ jobs:
25
+ # Build job
26
+ build:
27
+ runs-on: ubuntu-latest
28
+ steps:
29
+ - name: Checkout
30
+ uses: actions/checkout@v4
31
+ - name: Setup Pages
32
+ uses: actions/configure-pages@v5
33
+ - name: Build with Jekyll
34
+ uses: actions/jekyll-build-pages@v1
35
+ with:
36
+ source: ./
37
+ destination: ./_site
38
+ - name: Upload artifact
39
+ uses: actions/upload-pages-artifact@v3
40
+
41
+ # Deployment job
42
+ deploy:
43
+ environment:
44
+ name: github-pages
45
+ url: ${{ steps.deployment.outputs.page_url }}
46
+ runs-on: ubuntu-latest
47
+ needs: build
48
+ steps:
49
+ - name: Deploy to GitHub Pages
50
+ id: deployment
51
+ uses: actions/deploy-pages@v5
.github/workflows/static.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Simple workflow for deploying static content to GitHub Pages
2
+ name: Deploy static content to Pages
3
+
4
+ on:
5
+ # Runs on pushes targeting the default branch
6
+ push:
7
+ branches: ["main"]
8
+
9
+ # Allows you to run this workflow manually from the Actions tab
10
+ workflow_dispatch:
11
+
12
+ # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
13
+ permissions:
14
+ contents: read
15
+ pages: write
16
+ id-token: write
17
+
18
+ # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
19
+ # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
20
+ concurrency:
21
+ group: "pages"
22
+ cancel-in-progress: false
23
+
24
+ jobs:
25
+ # Single deploy job since we're just deploying
26
+ deploy:
27
+ environment:
28
+ name: github-pages
29
+ url: ${{ steps.deployment.outputs.page_url }}
30
+ runs-on: ubuntu-latest
31
+ steps:
32
+ - name: Checkout
33
+ uses: actions/checkout@v4
34
+ - name: Setup Pages
35
+ uses: actions/configure-pages@v5
36
+ - name: Upload artifact
37
+ uses: actions/upload-pages-artifact@v3
38
+ with:
39
+ # Upload entire repository
40
+ path: '.'
41
+ - name: Deploy to GitHub Pages
42
+ id: deployment
43
+ uses: actions/deploy-pages@v5
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2026 M. M. Shamshiri
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
PROPOSAL.md ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NLCL — Natural Language as a Computational Language
2
+
3
+ **Author of the idea:** M. M. Shamshiri, independent researcher (concept first developed in 2019)
4
+ **Status:** working software prototype, released openly so that others can continue it
5
+
6
+ ## The idea in one paragraph
7
+
8
+ Today's language models break text into statistical sub-word tokens and learn meaning afterwards from data.
9
+ This proposal starts from the other end: **meaning is the unit of computation from the first step.** A sentence
10
+ is reduced to semantic tokens, the tokens form a computational structure, and that structure — not the text —
11
+ is what gets executed, stored and translated into code. Natural language is then not an interface placed in
12
+ front of a programming language; it is the programming language. The long-term vision is that such a language
13
+ could sit at the core of an operating system, and eventually be accelerated by dedicated hardware.
14
+
15
+ ## What makes it different from "natural language to code"
16
+
17
+ 1. **Three kinds of semantic tokens in one vocabulary** — atomic (`CREATE`, `OBJECT`, `CONNECT`), composite
18
+ (`CREATE + OBJECT → CREATE_OBJECT`), and adaptive (new words and commands learned at run time, each
19
+ validated by a dry run before it is accepted).
20
+ 2. **A universal, language-independent representation.** Every instruction becomes an operation on entities,
21
+ properties, behaviours and links, e.g.
22
+ `CREATE(domain=GAME, type=object, properties={health: 100, movable: true})`.
23
+ 3. **A universal concept of "object".** "Create an object" is not guessed: the system asks which domain is
24
+ meant, because the same object is a GameObject, a Python class, a register in hardware or a CAD part.
25
+ 4. **Persistent state.** Each sentence modifies the same system; it does not generate a new unrelated program.
26
+ 5. **Several domains at once.** One description can produce firmware, hardware description, a server, a 3D
27
+ model and an application, with a shared contract for every connection between them.
28
+ 6. **A deterministic path.** For supported sentences the same input always gives the same structure, with no
29
+ model in the loop.
30
+
31
+ ## What the prototype does today
32
+
33
+ - Offline pipeline for English: semantic tokens → composite tokens → IR → persistent state → code.
34
+ - Eight pluggable domain modules: Python, game (Unity / Godot / HTML5 preview), embedded (Arduino / ESP32 /
35
+ MicroPython / Wokwi), hardware (Verilog + testbench), C++, 3D (three.js / Blender), CAD (OpenSCAD), and
36
+ applications (desktop GUI for Windows / macOS / Linux plus an installable web app for Android / iOS).
37
+ - Multi-module systems: links such as `connect the sensor to the dashboard via http` become one channel
38
+ contract implemented on both sides.
39
+ - Behaviour rules in plain sentences (`when ghost touches bob, decrease bob lives by 1`), attached to the
40
+ entity whose state they change.
41
+ - Other human languages (for example Persian) through an online agent that rewrites the sentence into the
42
+ language's own English commands.
43
+ - A bug-fix command for any file, folder or generated module: real diagnostics first, then an online agent
44
+ that proposes small edits, with backup, re-check and rollback.
45
+ - Only free tools and free model APIs; the core needs nothing but the Python standard library.
46
+ - 111 automated tests pass.
47
+
48
+ ## What it does not do yet (stated plainly)
49
+
50
+ - The offline parser covers common sentence shapes, not all of English. It still misreads some sentences.
51
+ - Modules are written by hand. The system learns new words and commands, not new modules.
52
+ - The online features (other languages, bug fixing) were tested only with a stand-in model, not a real one.
53
+ - Generated C++, Verilog and Arduino code has not been compiled; only Python, JavaScript and the desktop/web
54
+ application output were actually executed.
55
+ - The operating-system core and the dedicated hardware from the original concept are not started. The software
56
+ prototype is the baseline the concept asked for first.
57
+
58
+ ## Open research questions
59
+
60
+ 1. Can semantic tokens replace or complement statistical tokens inside a language model, rather than only in
61
+ front of it?
62
+ 2. Can a system extend its own semantic vocabulary and rules safely and consistently at scale?
63
+ 3. How far can one universal object representation stretch across software, games, 3D, hardware and devices?
64
+ 4. Would a natural-language runtime with persistent computational state be a sound basis for an operating
65
+ system shell or kernel interface?
66
+ 5. Is there any workload where dedicated hardware for semantic operations pays off?
67
+
68
+ ## Why it is being shared
69
+
70
+ I do not have the funding or the time to build the full architecture. I am publishing the idea and this
71
+ prototype so that people and organisations with more resources can evaluate it, improve it, or take it
72
+ further. I am not claiming that every component is new; I am proposing the combined architecture and asking
73
+ for it to be judged on its merits.
74
+
75
+ ## How it was built
76
+
77
+ The prototype was written with the help of **Claude** (Anthropic), through Claude Code. Most of the code was
78
+ written by **Claude Opus 5.5**; later features and fixes were written by **Claude Fable 5.2**. The idea,
79
+ its goals and the design decisions are mine; this does not imply any endorsement by Anthropic.
80
+
81
+ ## Licence
82
+
83
+ Released under the MIT licence (see `LICENSE`): anyone may use, change and build on it, including commercially.
84
+
85
+ ---
86
+
87
+ *M. M. Shamshiri — Independent Researcher*
README.md ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NLCL — Natural Language Computational Language
2
+
3
+ **NLCL is an open-source prototype exploring natural language as a computational language.** It turns English instructions into semantic operations, applies them to a persistent intermediate representation (IR), and generates code for multiple domains.
4
+
5
+ > Natural language is not merely an interface: it can be the programming language itself. Sentences become semantic tokens, tokens become computational structures, and those structures become a language-independent IR that can be compiled into cooperating modules.
6
+
7
+ This project is an independent research prototype shared to invite feedback. It is not affiliated with or endorsed by Anthropic.
8
+
9
+ ## Screenshots
10
+
11
+ A look at NLCL’s interface and workflow:
12
+
13
+ <table>
14
+ <tr>
15
+ <td align="center"><img src="screenshots/Screenshot%202026-11-26%20024554.png" alt="NLCL screenshot 1" width="100%"></td>
16
+ <td align="center"><img src="screenshots/Screenshot%202026-11-26%20024937.png" alt="NLCL screenshot 2" width="100%"></td>
17
+ </tr>
18
+ <tr>
19
+ <td align="center"><img src="screenshots/Screenshot%202026-11-26%20025356.png" alt="NLCL screenshot 3" width="100%"></td>
20
+ <td align="center"><img src="screenshots/Screenshot%202026-11-26%20025433.png" alt="NLCL screenshot 4" width="100%"></td>
21
+ </tr>
22
+ </table>
23
+
24
+ ## What NLCL does
25
+
26
+ ```text
27
+ Natural-language instruction
28
+ → semantic tokens and candidate interpretations
29
+ → dry-run against a persistent state
30
+ → universal intermediate representation (IR)
31
+ → domain-specific code generation
32
+ → build, run, or simulate
33
+ ```
34
+
35
+ The core runs offline using only the Python standard library. English instructions are handled by the offline parser. Optional language-model backends can help with non-Latin languages, interpretation, and code repair.
36
+
37
+ ## Quick start
38
+
39
+ ```bash
40
+ python -m nlcl
41
+ python -m nlcl examples/game.nl --run
42
+ python -m nlcl examples/smart_greenhouse.nl --build
43
+ python -m unittest discover -s tests
44
+ ```
45
+
46
+ A short interactive example:
47
+
48
+ ```text
49
+ > create an object
50
+ System: What kind of object would you like to create? (game / python / embedded / ...)
51
+ ? a game object
52
+ created game object 'object'
53
+ System: What properties should object have? (e.g. health, speed, movable, ...)
54
+ > give it 100 health, make it movable, and add collision detection
55
+ object: {health: 100}
56
+ object: {movable: True}
57
+ object: {collision: True}
58
+ > when health drops below 1, destroy it
59
+ > build it
60
+ ```
61
+
62
+ The same state can be represented in NLCL's IR:
63
+
64
+ ```text
65
+ CREATE(domain=GAME, type=object, properties={"health": 100, "movable": true, "collision": true})
66
+ BEHAVIOR(target=hero, behavior={"on": "update", "if": "health < 1", "do": [{"op": "destroy"}]})
67
+ CONNECT(target=temp, dst=monitor, via=http, properties={"fields": ["temperature"], "interval_ms": 2000})
68
+ ```
69
+
70
+ ## Architecture
71
+
72
+ NLCL combines three vocabulary mechanisms:
73
+
74
+ | Mechanism | Description |
75
+ |---|---|
76
+ | Atomic tokens | Core operations such as `CREATE`, `DELETE`, and `CONNECT` (`nlcl/tokens.py`) |
77
+ | Composite tokens | Ordered patterns that combine tokens into higher-level operations |
78
+ | Adaptive vocabulary | Teach aliases and define commands; definitions are dry-run against a copy of the state before acceptance |
79
+
80
+ The interpreter applies operations to a persistent state and asks for clarification when it cannot confidently determine the intended domain or operation. The knowledge base stores ontology, learned reliability, safety rules, and learned vocabulary. The weighting model uses measurable interpretation features to estimate confidence; `:why` explains a score.
81
+
82
+ | Component | Location | Role |
83
+ |---|---|---|
84
+ | Parser | `nlcl/parser.py` | Offline English rule parser |
85
+ | IR and interpreter | `nlcl/ir.py`, `nlcl/interpreter.py` | State, operations, and interpretation |
86
+ | Knowledge base | `nlcl/kb/`, `nlcl/knowledge.py` | Ontology, reliability, and learned facts |
87
+ | Learning and weighting | `nlcl/learn.py`, `nlcl/weights.py` | Learn rewrite rules and calibrate confidence |
88
+ | Modules | `nlcl/modules/` | Domain-specific generators and tools |
89
+ | Terminal | `nlcl/shell.py` | Interpret terminal requests and verify command effects in a sandbox |
90
+ | Benchmark | `nlcl/bench/` | Reproducible evaluation suites |
91
+
92
+ ## Code-generation domains
93
+
94
+ | Domain | Example output | Free tools and runtimes |
95
+ |---|---|---|
96
+ | `app` | Tkinter desktop app, packaging scripts, installable PWA | CPython, PyInstaller, browser |
97
+ | `python` | Objects, services, hubs, and bridges | CPython |
98
+ | `game` | Unity C#, Godot GDScript, HTML5 preview | Unity Personal, Godot, browser |
99
+ | `embedded` | Arduino C++, MicroPython, PlatformIO projects | Arduino IDE, PlatformIO, Wokwi |
100
+ | `hardware` | Verilog RTL, testbench, synthesis scripts | Icarus Verilog, GTKWave, Yosys |
101
+ | `cpp` | C++17 classes, main loop, channels, CMake | g++, Clang, MSVC Build Tools |
102
+ | `3d` | Three.js digital twin and Blender script | Browser, Blender |
103
+ | `cad` | OpenSCAD parts and CadQuery models | OpenSCAD, CadQuery, FreeCAD |
104
+
105
+ Modules are plugins: a module in `nlcl/modules/` that provides a `MODULE` can add a domain. Different domain entities can be connected with channel contracts such as HTTP, MQTT, serial, SPI, or I²C. A composed system can include `system.json` and a `SYSTEM.md` guide.
106
+
107
+ ## Example instructions
108
+
109
+ The offline parser supports common instruction patterns, including:
110
+
111
+ ```text
112
+ create 3 enemies with health 30 and color red
113
+ create a platform called floor at position 0, 0
114
+ create a state machine called door with states closed, open and locked
115
+ make wheel a child of robot
116
+ hero's speed should be 9
117
+ when hero touches gold, increase hero score by 10 and destroy gold
118
+ every 3 seconds, if state is red, set state to green
119
+ ```
120
+
121
+ It is a rule-based prototype, not a general natural-language understanding system. It supports common sentence forms rather than all of English.
122
+
123
+ ## Optional language-model backends
124
+
125
+ Backends are optional. Without a configured backend, the offline English parser still works. A backend can be used for non-Latin input, online interpretation, and assisted code fixes.
126
+
127
+ | Backend | Environment variable |
128
+ |---|---|
129
+ | Ollama | Local configuration |
130
+ | Groq | `GROQ_API_KEY` |
131
+ | Gemini | `GEMINI_API_KEY` |
132
+ | OpenRouter | `OPENROUTER_API_KEY` |
133
+ | Cerebras | `CEREBRAS_API_KEY` |
134
+ | Mistral | `MISTRAL_API_KEY` |
135
+ | Hugging Face | `HF_TOKEN` |
136
+ | GitHub Models | `GITHUB_TOKEN` |
137
+
138
+ The first available backend is selected automatically. Set a model with `NLCL_<NAME>_MODEL` (for example, `NLCL_GROQ_MODEL`) or inspect the configuration with `:backend status`. Backend availability and free-tier limits depend on the provider.
139
+
140
+ ## Terminal assistance and safety
141
+
142
+ NLCL can interpret requests such as listing files, copying or renaming files, and searching project contents. The terminal suite compares generated command effects with a reference operation in a sandbox. File-changing operations are designed to require confirmation and show proposed changes before they are applied.
143
+
144
+ Code diagnostics can use installed tools such as Python, Node.js, C/C++ compilers, Icarus Verilog, Verilator, OpenSCAD, and Godot. Online code repair requires a configured language-model backend; without one, `:check` can still diagnose issues.
145
+
146
+ ## Benchmark results
147
+
148
+ The latest supplied offline report is dated **2026-11-24 16:23** and evaluates held-out sentences. A result counts as correct when it produces the same resulting system state as the canonical instruction. The benchmark used knowledge-base version `9d1d36fffb91`.
149
+
150
+ | Metric | Untrained | Trained | Trained, unseen intents only |
151
+ |---|---:|---:|---:|
152
+ | Test sentences | 184 | 184 | 24 |
153
+ | Interpretation accuracy | 58.08% (95% CI: 50.5–65.3%) | 59.88% (95% CI: 52.3–67.0%) | 62.5% (95% CI: 42.7–78.8%) |
154
+ | Silent error rate | 34.24% (95% CI: 27.8–41.4%) | 14.67% (95% CI: 10.3–20.5%) | 16.67% (95% CI: 6.7–35.9%) |
155
+ | Precision when executing | 60.62% (95% CI: 52.9–67.9%) | 78.74% (95% CI: 70.8–85.0%) | 78.95% (95% CI: 56.7–91.5%) |
156
+ | Out-of-scope inputs refused | 1/17 | 13/17 | — |
157
+ | Asked instead of executing | 24 | 57 | 5 |
158
+ | Calibration error (ECE; lower is better) | 0.302 | 0.1112 | 0.2023 |
159
+ | AUROC for separating right from wrong | 0.9252 | 0.9469 | 0.8778 |
160
+ | Median latency per sentence | 0.66 ms | 1.05 ms | 1.22 ms |
161
+ | Area under risk-coverage curve (lower is better) | 0.1733 | 0.1577 | 0.1696 |
162
+
163
+ Wilson 95% confidence intervals are shown for accuracy, silent error rate, and precision. The unseen-intent subset contains no out-of-scope examples, so refusal is not applicable (`0/0` in the raw report).
164
+
165
+ ### Learning curve
166
+
167
+ | Training paraphrases per intent | Rules learned | Accuracy | Silent errors | Out-of-scope refused | ECE |
168
+ |---:|---:|---:|---:|---:|---:|
169
+ | 0 | 0 | 58.08% | 34.24% | 1/17 | 0.302 |
170
+ | 1 | 1 | 58.08% | 23.37% | 12/17 | 0.2119 |
171
+ | 2 | 1 | 58.08% | 18.48% | 13/17 | 0.1844 |
172
+ | 3 | 3 | 59.88% | 14.67% | 13/17 | 0.1292 |
173
+
174
+ ### Terminal benchmark
175
+
176
+ | Metric | Result |
177
+ |---|---:|
178
+ | Same file-system effect as the intended command | 59.46% (22/37 sentences) |
179
+ | Executed with the wrong effect | 0/37 |
180
+ | Generated Bash and PowerShell checks passed in a sandbox | 24/44 |
181
+ | Unconfirmed destructive file actions | 0 |
182
+
183
+ The `24/44` figure is the number of shell checks that passed, not a 100% verification rate. The report notes that `llm-direct` and `nlcl+teacher` were **not run** because no language-model backend was configured. NLCL produced identical interpretations on repeated runs for all **184/184** benchmark sentences across five runs. Offline token cost was zero; trained median latency was **1.05 ms** per sentence.
184
+
185
+ These are prototype benchmark results on a small, author-created corpus. They show lower silent error rates and improved refusal and calibration after training in this run, but do not establish broad real-world performance. See the [pre-registered hypotheses](bench/HYPOTHESES.md), [latest benchmark report](bench/results/report.md), and [machine-readable results](bench/results/results.json) for methodology and full details.
186
+
187
+ Run the offline benchmark with:
188
+
189
+ ```bash
190
+ python -m nlcl.bench --backend off
191
+ ```
192
+
193
+ To attempt the language-model comparisons, configure a supported backend and run:
194
+
195
+ ```bash
196
+ python -m nlcl.bench --backend auto
197
+ ```
198
+
199
+ ## REPL commands
200
+
201
+ Useful commands include `:help`, `:show`, `:ir`, `:trace on`, `:build`, `:run`, `:undo`, `:domains`, `:vocab`, `:teach <word> <TOKEN>`, `:backend status`, and `:quit`.
202
+
203
+ ## Limitations
204
+
205
+ - The offline parser covers common English patterns, not unrestricted natural language.
206
+ - Persian and other non-Latin input require an online backend.
207
+ - Generated code is a starting point, not a verified production product. Toolchains may be needed to build or simulate non-Python targets.
208
+ - Online interpretation and code repair depend on the selected model, provider availability, and API limits.
209
+ - The benchmark is small and was created by the project author; its results should be treated as preliminary.
210
+ - Dedicated hardware for semantic operations is outside the scope of this software prototype.
211
+
212
+ ## Credits and license
213
+
214
+ The concept and design goals are by M. M. Shamshiri (2019); see [`PROPOSAL.md`](PROPOSAL.md). The prototype was developed with assistance from Claude through Claude Code. This does not imply endorsement by Anthropic.
215
+
216
+ Released under the [MIT License](LICENSE).
bench/HYPOTHESES.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pre-registered hypotheses (written 2026-11-16, before the first full benchmark run)
2
+
3
+ The question this benchmark asks is **not** "does the system finish the task" (Terminal-Bench style) but
4
+ **"when a person writes what they mean, does the system do exactly that — and does it know when it
5
+ doesn't understand?"**. Results are reported whichever way they come out.
6
+
7
+ Systems compared on the same sentences:
8
+
9
+ | id | system |
10
+ |---|---|
11
+ | `nlcl-untrained` | NLCL rule interpreter, empty knowledge base |
12
+ | `nlcl-trained` | NLCL after `train` on the training paraphrases (rules + evidence + weights learned into Prolog) |
13
+ | `llm-direct` | a language model turns the sentence straight into the same IR / a shell command (needs an API key) |
14
+ | `nlcl+teacher` | NLCL; below the execution weight it asks the language model and distils the answer into a rule (needs an API key) |
15
+
16
+ ## Predictions
17
+
18
+ **H1 - silent errors.** `nlcl-trained` has a lower *silent error rate* (executed something that is not what was
19
+ meant) than `nlcl-untrained` on held-out sentences, and lower than `llm-direct`.
20
+ *Expected: strong effect against untrained; against llm-direct the effect may be small or reversed,
21
+ because a good model rarely misreads simple instructions.*
22
+
23
+ **H2 - nonsense.** `nlcl-trained` refuses to execute at least 2/3 of out-of-scope / meaningless sentences;
24
+ `llm-direct` executes more of them (it tends to produce *some* program for any input).
25
+
26
+ **H3 - calibration.** The NLCL weight is calibrated after training (ECE < 0.15 on held-out sentences) and
27
+ separates right from wrong interpretations (AUROC > 0.85). A direct model gives no comparable number.
28
+
29
+ **H4 - accuracy (expected loss).** On free paraphrases `llm-direct` has **higher** interpretation accuracy than
30
+ any offline NLCL variant. NLCL's offline accuracy on unseen paraphrases is expected to be well below 70%.
31
+ `nlcl+teacher` should approach `llm-direct` accuracy while executing fewer wrong things than `llm-direct`.
32
+
33
+ **H5 - determinism.** NLCL produces byte-identical interpretations on repeated runs (100%). A model at
34
+ temperature 0 is expected to be below 100% on at least some sentences.
35
+
36
+ **H6 - verified terminal commands.** Every terminal command NLCL executes is verified: running the generated
37
+ bash and PowerShell text in a sandbox gives exactly the file-system effect of the reference meaning (100%).
38
+ A model writing shell text directly has no such guarantee; its commands are scored by the same sandbox check.
39
+
40
+ **H7 - destructive actions.** NLCL never changes or deletes files without first showing the exact diff and
41
+ getting confirmation (0 unconfirmed destructive actions).
42
+
43
+ **H8 - learning.** Held-out accuracy and nonsense refusal increase with the amount of training data, without
44
+ any model retraining; every learned rule is a readable Prolog fact.
45
+
46
+ **H9 - cost.** NLCL offline: 0 tokens, median latency < 5 ms per sentence. `llm-direct`: tokens > 0, latency in
47
+ seconds.
48
+
49
+ ## Known threats to validity
50
+
51
+ - The NLCL parser and the corpus were written by the same author (with Claude); training paraphrases were
52
+ phrased without filtering, but bias toward the parser's style cannot be excluded. The held-out split was
53
+ not used to change the parser.
54
+ - Small corpus (35 intents, ~6 paraphrases each, 24 nonsense sentences): report effect sizes, not significance.
55
+ - One language model per run; results depend on the model chosen.
bench/results/report.md ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NLCL benchmark report (2026-11-17 15:57)
2
+
3
+ Held-out sentences only (never used for training). Correct = same resulting system state as the canonical sentence. Pre-registered hypotheses: `bench/HYPOTHESES.md`.
4
+
5
+ > **Note:** llm-direct and nlcl+teacher were NOT run: no language-model backend (set a free API key, see ':backend status', then run again).
6
+
7
+ ## Fidelity
8
+
9
+ | metric | nlcl-untrained | nlcl-trained |
10
+ |---|---|---|
11
+ | interpretation accuracy (valid sentences) | 0.4476 | 0.4667 |
12
+ | executed something not meant (silent error rate) | 0.4103 | 0.2393 |
13
+ | precision when it executes | 0.4947 | 0.6364 |
14
+ | nonsense / out-of-scope refused | 1/12 | 9/12 |
15
+ | asked instead of executing | 22 | 40 |
16
+ | all paraphrases of an intent right | 0.0571 | 0.0857 |
17
+ | calibration error of the weight (ECE, lower is better) | 0.3816 | 0.1926 |
18
+ | weight separates right/wrong (AUROC) | 0.8966 | 0.9146 |
19
+ | median latency per sentence (ms) | 0.87 | 0.8 |
20
+
21
+ ## Risk / coverage of the trained weight
22
+
23
+ Executing only sentences whose weight reaches the threshold (the rest are asked about):
24
+
25
+ | weight threshold | share executed | precision of what is executed | wrong executions |
26
+ |---|---|---|---|
27
+ | 0.0 | 0.889 | 0.471 | 55 |
28
+ | 0.35 | 0.658 | 0.636 | 28 |
29
+ | 0.5 | 0.641 | 0.64 | 27 |
30
+ | 0.6 | 0.573 | 0.716 | 19 |
31
+ | 0.7 | 0.547 | 0.75 | 16 |
32
+ | 0.8 | 0.538 | 0.762 | 15 |
33
+ | 0.9 | 0.47 | 0.745 | 14 |
34
+
35
+ ## Learning curve (no model retraining: rules, evidence and weights in Prolog)
36
+
37
+ | training paraphrases per intent | rules learned | accuracy | silent errors | nonsense refused | ECE |
38
+ |---|---|---|---|---|---|
39
+ | 0 | 0 | 0.4476 | 0.4103 | 1/12 | 0.3816 |
40
+ | 1 | 1 | 0.4476 | 0.2479 | 9/12 | 0.2654 |
41
+ | 2 | 1 | 0.4476 | 0.2479 | 9/12 | 0.2358 |
42
+ | 3 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
43
+ | 4 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
44
+ | 5 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
45
+ | 6 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
46
+ | 7 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
47
+ | 8 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
48
+ | 9 | 3 | 0.4667 | 0.2393 | 9/12 | 0.1926 |
49
+
50
+ ## Terminal
51
+
52
+ | metric | nlcl-trained |
53
+ |---|---|
54
+ | same file-system effect as the meant command | 0.5758 |
55
+ | executed with the wrong effect | 0.0 |
56
+ | generated bash + PowerShell verified in a sandbox | 21/38 |
57
+ | files changed/deleted without showing a diff first | 0 |
58
+
59
+ ## Determinism
60
+
61
+ Identical interpretation on every repeated run: nlcl: 117/117
62
+
63
+ ## Cost
64
+
65
+ NLCL offline: 0 tokens, median 0.8 ms per sentence.
66
+
67
+ ## What the trained interpreter learned (Prolog facts)
68
+
69
+ ```prolog
70
+ % NLCL learned knowledge - written 2026-11-17 15:57:33
71
+ % (plain Prolog facts: edit, delete or load them in SWI-Prolog)
72
+
73
+ % rewrite/3
74
+ rewrite(['store\'s'],[store],1).
75
+ rewrite([get,rid,of],[delete],1).
76
+ rewrite([the,game],[],1).
77
+
78
+ % reliability/3
79
+ reliability(frame(behavior),18,1).
80
+ reliability(frame(connect_to),2,0).
81
+ reliability(frame(create_object),22,4).
82
+ reliability(frame(delete_object),5,0).
83
+ reliability(frame(move_object),0,1).
84
+ reliability(frame(rename_object),2,0).
85
+ reliability(frame(set_property),12,13).
86
+ reliability(frame(special),11,0).
87
+ reliability(intent(archive),3,0).
88
+ reliability(intent(copy),3,0).
89
+ reliability(intent(count_files),3,0).
90
+ reliability(intent(count_lines),3,0).
91
+ reliability(intent(delete),3,0).
92
+ reliability(intent(list_files),3,0).
93
+ reliability(intent(make_dir),3,0).
94
+ reliability(intent(move),3,0).
95
+ reliability(intent(replace_text),3,0).
96
+ reliability(intent(search_text),3,0).
97
+ reliability(intent(show_file),3,0).
98
+
99
+ % param/2
100
+ param(bias,-1.11072).
101
+ param(coverage,2.257904).
102
+ param(dry_errors,-2.4).
103
+ param(errors,-2.2).
104
+ param(frame_rel,0.858535).
105
+ param(fuzzy,-0.9).
106
+ param(inferred,-0.404714).
107
+ param(llm,0.4).
108
+ param(missing_paths,-1.8).
109
+ param(n_ops,-0.292096).
110
+ param(notes,-0.65517).
111
+ param(novel,-1.853353).
112
+ param(question,-0.6).
113
+ param(reliability,0.957997).
114
+ param(shell,1.213662).
115
+ param(unknown,-0.9).
116
+ param(verbless,-1.796907).
117
+ param(warnings,-0.25).
118
+ ```
bench/results/results.json ADDED
@@ -0,0 +1,484 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "date": "2026-11-17 15:57",
3
+ "systems": {
4
+ "nlcl-untrained": {
5
+ "sentences": 117,
6
+ "interpretation_accuracy": 0.4476,
7
+ "executed": 95,
8
+ "precision_when_executed": 0.4947,
9
+ "silent_error_rate": 0.4103,
10
+ "asked": 22,
11
+ "nonsense_caught": "1/12",
12
+ "median_ms": 0.87,
13
+ "calibration_ece": 0.3816,
14
+ "calibration_brier": 0.3414,
15
+ "calibration_auroc": 0.8966,
16
+ "paraphrase_consistency": 0.0571
17
+ },
18
+ "nlcl-trained": {
19
+ "sentences": 117,
20
+ "interpretation_accuracy": 0.4667,
21
+ "executed": 77,
22
+ "precision_when_executed": 0.6364,
23
+ "silent_error_rate": 0.2393,
24
+ "asked": 40,
25
+ "nonsense_caught": "9/12",
26
+ "median_ms": 0.8,
27
+ "calibration_ece": 0.1926,
28
+ "calibration_brier": 0.1658,
29
+ "calibration_auroc": 0.9146,
30
+ "paraphrase_consistency": 0.0857,
31
+ "rules_learned": 3
32
+ }
33
+ },
34
+ "learning_curve": [
35
+ {
36
+ "sentences": 117,
37
+ "interpretation_accuracy": 0.4476,
38
+ "executed": 95,
39
+ "precision_when_executed": 0.4947,
40
+ "silent_error_rate": 0.4103,
41
+ "asked": 22,
42
+ "nonsense_caught": "1/12",
43
+ "median_ms": 0.62,
44
+ "calibration_ece": 0.3816,
45
+ "calibration_brier": 0.3414,
46
+ "calibration_auroc": 0.8966,
47
+ "paraphrases_per_intent": 0,
48
+ "rules_learned": 0
49
+ },
50
+ {
51
+ "sentences": 117,
52
+ "interpretation_accuracy": 0.4476,
53
+ "executed": 76,
54
+ "precision_when_executed": 0.6184,
55
+ "silent_error_rate": 0.2479,
56
+ "asked": 41,
57
+ "nonsense_caught": "9/12",
58
+ "median_ms": 0.89,
59
+ "calibration_ece": 0.2654,
60
+ "calibration_brier": 0.2147,
61
+ "calibration_auroc": 0.881,
62
+ "paraphrases_per_intent": 1,
63
+ "rules_learned": 1
64
+ },
65
+ {
66
+ "sentences": 117,
67
+ "interpretation_accuracy": 0.4476,
68
+ "executed": 76,
69
+ "precision_when_executed": 0.6184,
70
+ "silent_error_rate": 0.2479,
71
+ "asked": 41,
72
+ "nonsense_caught": "9/12",
73
+ "median_ms": 0.75,
74
+ "calibration_ece": 0.2358,
75
+ "calibration_brier": 0.1884,
76
+ "calibration_auroc": 0.9061,
77
+ "paraphrases_per_intent": 2,
78
+ "rules_learned": 1
79
+ },
80
+ {
81
+ "sentences": 117,
82
+ "interpretation_accuracy": 0.4667,
83
+ "executed": 77,
84
+ "precision_when_executed": 0.6364,
85
+ "silent_error_rate": 0.2393,
86
+ "asked": 40,
87
+ "nonsense_caught": "9/12",
88
+ "median_ms": 0.84,
89
+ "calibration_ece": 0.1926,
90
+ "calibration_brier": 0.1658,
91
+ "calibration_auroc": 0.9146,
92
+ "paraphrases_per_intent": 3,
93
+ "rules_learned": 3
94
+ },
95
+ {
96
+ "sentences": 117,
97
+ "interpretation_accuracy": 0.4667,
98
+ "executed": 77,
99
+ "precision_when_executed": 0.6364,
100
+ "silent_error_rate": 0.2393,
101
+ "asked": 40,
102
+ "nonsense_caught": "9/12",
103
+ "median_ms": 0.88,
104
+ "calibration_ece": 0.1926,
105
+ "calibration_brier": 0.1658,
106
+ "calibration_auroc": 0.9146,
107
+ "paraphrases_per_intent": 4,
108
+ "rules_learned": 3
109
+ },
110
+ {
111
+ "sentences": 117,
112
+ "interpretation_accuracy": 0.4667,
113
+ "executed": 77,
114
+ "precision_when_executed": 0.6364,
115
+ "silent_error_rate": 0.2393,
116
+ "asked": 40,
117
+ "nonsense_caught": "9/12",
118
+ "median_ms": 0.97,
119
+ "calibration_ece": 0.1926,
120
+ "calibration_brier": 0.1658,
121
+ "calibration_auroc": 0.9146,
122
+ "paraphrases_per_intent": 5,
123
+ "rules_learned": 3
124
+ },
125
+ {
126
+ "sentences": 117,
127
+ "interpretation_accuracy": 0.4667,
128
+ "executed": 77,
129
+ "precision_when_executed": 0.6364,
130
+ "silent_error_rate": 0.2393,
131
+ "asked": 40,
132
+ "nonsense_caught": "9/12",
133
+ "median_ms": 0.79,
134
+ "calibration_ece": 0.1926,
135
+ "calibration_brier": 0.1658,
136
+ "calibration_auroc": 0.9146,
137
+ "paraphrases_per_intent": 6,
138
+ "rules_learned": 3
139
+ },
140
+ {
141
+ "sentences": 117,
142
+ "interpretation_accuracy": 0.4667,
143
+ "executed": 77,
144
+ "precision_when_executed": 0.6364,
145
+ "silent_error_rate": 0.2393,
146
+ "asked": 40,
147
+ "nonsense_caught": "9/12",
148
+ "median_ms": 0.78,
149
+ "calibration_ece": 0.1926,
150
+ "calibration_brier": 0.1658,
151
+ "calibration_auroc": 0.9146,
152
+ "paraphrases_per_intent": 7,
153
+ "rules_learned": 3
154
+ },
155
+ {
156
+ "sentences": 117,
157
+ "interpretation_accuracy": 0.4667,
158
+ "executed": 77,
159
+ "precision_when_executed": 0.6364,
160
+ "silent_error_rate": 0.2393,
161
+ "asked": 40,
162
+ "nonsense_caught": "9/12",
163
+ "median_ms": 0.81,
164
+ "calibration_ece": 0.1926,
165
+ "calibration_brier": 0.1658,
166
+ "calibration_auroc": 0.9146,
167
+ "paraphrases_per_intent": 8,
168
+ "rules_learned": 3
169
+ },
170
+ {
171
+ "sentences": 117,
172
+ "interpretation_accuracy": 0.4667,
173
+ "executed": 77,
174
+ "precision_when_executed": 0.6364,
175
+ "silent_error_rate": 0.2393,
176
+ "asked": 40,
177
+ "nonsense_caught": "9/12",
178
+ "median_ms": 0.81,
179
+ "calibration_ece": 0.1926,
180
+ "calibration_brier": 0.1658,
181
+ "calibration_auroc": 0.9146,
182
+ "paraphrases_per_intent": 9,
183
+ "rules_learned": 3
184
+ }
185
+ ],
186
+ "notes": [
187
+ "llm-direct and nlcl+teacher were NOT run: no language-model backend (set a free API key, see ':backend status', then run again)."
188
+ ],
189
+ "learned_kb": "% NLCL learned knowledge - written 2026-11-17 15:57:33\n% (plain Prolog facts: edit, delete or load them in SWI-Prolog)\n\n% rewrite/3\nrewrite(['store\\'s'],[store],1).\nrewrite([get,rid,of],[delete],1).\nrewrite([the,game],[],1).\n\n% reliability/3\nreliability(frame(behavior),18,1).\nreliability(frame(connect_to),2,0).\nreliability(frame(create_object),22,4).\nreliability(frame(delete_object),5,0).\nreliability(frame(move_object),0,1).\nreliability(frame(rename_object),2,0).\nreliability(frame(set_property),12,13).\nreliability(frame(special),11,0).\nreliability(intent(archive),3,0).\nreliability(intent(copy),3,0).\nreliability(intent(count_files),3,0).\nreliability(intent(count_lines),3,0).\nreliability(intent(delete),3,0).\nreliability(intent(list_files),3,0).\nreliability(intent(make_dir),3,0).\nreliability(intent(move),3,0).\nreliability(intent(replace_text),3,0).\nreliability(intent(search_text),3,0).\nreliability(intent(show_file),3,0).\n\n% param/2\nparam(bias,-1.11072).\nparam(coverage,2.257904).\nparam(dry_errors,-2.4).\nparam(errors,-2.2).\nparam(frame_rel,0.858535).\nparam(fuzzy,-0.9).\nparam(inferred,-0.404714).\nparam(llm,0.4).\nparam(missing_paths,-1.8).\nparam(n_ops,-0.292096).\nparam(notes,-0.65517).\nparam(novel,-1.853353).\nparam(question,-0.6).\nparam(reliability,0.957997).\nparam(shell,1.213662).\nparam(unknown,-0.9).\nparam(verbless,-1.796907).\nparam(warnings,-0.25).\n\n",
190
+ "selective": [
191
+ {
192
+ "threshold": 0.0,
193
+ "coverage": 0.889,
194
+ "precision": 0.471,
195
+ "wrong_executions": 55
196
+ },
197
+ {
198
+ "threshold": 0.35,
199
+ "coverage": 0.658,
200
+ "precision": 0.636,
201
+ "wrong_executions": 28
202
+ },
203
+ {
204
+ "threshold": 0.5,
205
+ "coverage": 0.641,
206
+ "precision": 0.64,
207
+ "wrong_executions": 27
208
+ },
209
+ {
210
+ "threshold": 0.6,
211
+ "coverage": 0.573,
212
+ "precision": 0.716,
213
+ "wrong_executions": 19
214
+ },
215
+ {
216
+ "threshold": 0.7,
217
+ "coverage": 0.547,
218
+ "precision": 0.75,
219
+ "wrong_executions": 16
220
+ },
221
+ {
222
+ "threshold": 0.8,
223
+ "coverage": 0.538,
224
+ "precision": 0.762,
225
+ "wrong_executions": 15
226
+ },
227
+ {
228
+ "threshold": 0.9,
229
+ "coverage": 0.47,
230
+ "precision": 0.745,
231
+ "wrong_executions": 14
232
+ }
233
+ ],
234
+ "determinism": {
235
+ "nlcl": "117/117",
236
+ "runs": 5
237
+ },
238
+ "terminal": {
239
+ "nlcl-trained": {
240
+ "sentences": 33,
241
+ "effect_accuracy": 0.5758,
242
+ "silent_error_rate": 0.0,
243
+ "commands_verified": "21/38",
244
+ "unconfirmed_destructive_actions": 0,
245
+ "rows": [
246
+ {
247
+ "text": "display all python files in the folder src",
248
+ "right": true,
249
+ "weight": 0.971,
250
+ "source": "shell",
251
+ "executed": true
252
+ },
253
+ {
254
+ "text": "ls the python files in src",
255
+ "right": true,
256
+ "weight": 0.971,
257
+ "source": "shell",
258
+ "executed": true
259
+ },
260
+ {
261
+ "text": "which python files are in src",
262
+ "right": false,
263
+ "weight": 0.0,
264
+ "source": "rules",
265
+ "executed": false
266
+ },
267
+ {
268
+ "text": "count all .log files in logs",
269
+ "right": true,
270
+ "weight": 0.971,
271
+ "source": "shell",
272
+ "executed": true
273
+ },
274
+ {
275
+ "text": "how many log files does logs have",
276
+ "right": false,
277
+ "weight": 0.0,
278
+ "source": "rules",
279
+ "executed": false
280
+ },
281
+ {
282
+ "text": "tell me how many log files are in logs",
283
+ "right": false,
284
+ "weight": 0.0,
285
+ "source": "rules",
286
+ "executed": false
287
+ },
288
+ {
289
+ "text": "create a new directory named backup",
290
+ "right": true,
291
+ "weight": 0.971,
292
+ "source": "shell",
293
+ "executed": true
294
+ },
295
+ {
296
+ "text": "add a folder called backup",
297
+ "right": true,
298
+ "weight": 0.971,
299
+ "source": "shell",
300
+ "executed": true
301
+ },
302
+ {
303
+ "text": "I need a folder called backup",
304
+ "right": false,
305
+ "weight": 0.517,
306
+ "source": "rules",
307
+ "executed": false
308
+ },
309
+ {
310
+ "text": "erase all .tmp files in all subfolders",
311
+ "right": true,
312
+ "weight": 0.971,
313
+ "source": "shell",
314
+ "executed": true
315
+ },
316
+ {
317
+ "text": "clean up the temporary files everywhere",
318
+ "right": true,
319
+ "weight": 0.971,
320
+ "source": "shell",
321
+ "executed": true
322
+ },
323
+ {
324
+ "text": "wipe all .tmp files recursively",
325
+ "right": true,
326
+ "weight": 0.971,
327
+ "source": "shell",
328
+ "executed": true
329
+ },
330
+ {
331
+ "text": "copy the file notes.txt to backup.txt",
332
+ "right": true,
333
+ "weight": 0.971,
334
+ "source": "shell",
335
+ "executed": true
336
+ },
337
+ {
338
+ "text": "copy notes.txt into backup.txt",
339
+ "right": true,
340
+ "weight": 0.971,
341
+ "source": "shell",
342
+ "executed": true
343
+ },
344
+ {
345
+ "text": "clone notes.txt to backup.txt",
346
+ "right": false,
347
+ "weight": 0.019,
348
+ "source": "rules",
349
+ "executed": false
350
+ },
351
+ {
352
+ "text": "mv data.csv to people.csv",
353
+ "right": true,
354
+ "weight": 0.971,
355
+ "source": "shell",
356
+ "executed": true
357
+ },
358
+ {
359
+ "text": "rename data.csv as people.csv",
360
+ "right": true,
361
+ "weight": 0.971,
362
+ "source": "shell",
363
+ "executed": true
364
+ },
365
+ {
366
+ "text": "data.csv should be renamed to people.csv",
367
+ "right": false,
368
+ "weight": 0.019,
369
+ "source": "rules",
370
+ "executed": false
371
+ },
372
+ {
373
+ "text": "show me the first 2 lines in notes.txt",
374
+ "right": true,
375
+ "weight": 0.971,
376
+ "source": "shell",
377
+ "executed": true
378
+ },
379
+ {
380
+ "text": "head 2 lines of notes.txt",
381
+ "right": false,
382
+ "weight": 0.017,
383
+ "source": "rules",
384
+ "executed": false
385
+ },
386
+ {
387
+ "text": "read the first 2 lines of notes.txt",
388
+ "right": true,
389
+ "weight": 0.971,
390
+ "source": "shell",
391
+ "executed": true
392
+ },
393
+ {
394
+ "text": "grep 'TODO' in python files",
395
+ "right": true,
396
+ "weight": 0.971,
397
+ "source": "shell",
398
+ "executed": true
399
+ },
400
+ {
401
+ "text": "search all python files for 'TODO'",
402
+ "right": false,
403
+ "weight": 0.017,
404
+ "source": "rules",
405
+ "executed": false
406
+ },
407
+ {
408
+ "text": "where does 'TODO' appear in python files",
409
+ "right": false,
410
+ "weight": 0.0,
411
+ "source": "rules",
412
+ "executed": false
413
+ },
414
+ {
415
+ "text": "how many lines does data.csv have",
416
+ "right": true,
417
+ "weight": 0.971,
418
+ "source": "shell",
419
+ "executed": true
420
+ },
421
+ {
422
+ "text": "line count of data.csv",
423
+ "right": false,
424
+ "weight": 0.017,
425
+ "source": "rules",
426
+ "executed": false
427
+ },
428
+ {
429
+ "text": "tell me the number of lines in data.csv",
430
+ "right": false,
431
+ "weight": 0.017,
432
+ "source": "rules",
433
+ "executed": false
434
+ },
435
+ {
436
+ "text": "change 'apple' to 'pear' in notes.txt",
437
+ "right": false,
438
+ "weight": 0.433,
439
+ "source": "rules",
440
+ "executed": false
441
+ },
442
+ {
443
+ "text": "swap 'apple' for 'pear' in notes.txt",
444
+ "right": false,
445
+ "weight": 0.0,
446
+ "source": "rules",
447
+ "executed": false
448
+ },
449
+ {
450
+ "text": "replace every 'apple' by 'pear' in the file notes.txt",
451
+ "right": true,
452
+ "weight": 0.971,
453
+ "source": "shell",
454
+ "executed": true
455
+ },
456
+ {
457
+ "text": "make a zip of src called src.zip",
458
+ "right": false,
459
+ "weight": 0.517,
460
+ "source": "rules",
461
+ "executed": false
462
+ },
463
+ {
464
+ "text": "pack src into src.zip",
465
+ "right": true,
466
+ "weight": 0.971,
467
+ "source": "shell",
468
+ "executed": true
469
+ },
470
+ {
471
+ "text": "compress the folder src to src.zip",
472
+ "right": true,
473
+ "weight": 0.971,
474
+ "source": "shell",
475
+ "executed": true
476
+ }
477
+ ]
478
+ }
479
+ },
480
+ "cost": {
481
+ "nlcl_median_ms": 0.8,
482
+ "nlcl_tokens": 0
483
+ }
484
+ }
examples/counter_app.nl ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A desktop + mobile application described in natural language.
2
+ # Output: app.py (Windows/macOS/Linux, Tkinter) and web/ (installable PWA for Android/iOS).
3
+ :name tally
4
+ create an app called tally with title "Tally Counter" and size 360 by 320
5
+ add a label called display to tally with value 0
6
+ add a button called plus to tally with text "+1"
7
+ add a button called reset to tally with text "Reset"
8
+ add an input called step to tally with value 1 and label "Step"
9
+ add a checkbox called auto to tally with text "Count automatically"
10
+ add a progress called bar to tally with max 20
11
+ when plus is pressed, increase value of display by value of step
12
+ when reset is pressed, set value of display to 0
13
+ every 1 second, if checked of auto is on, increase value of display by 1
14
+ when value of display changes, set value of bar to value of display
15
+ when value of display is above 19, print 'limit reached: {value}'
16
+ build it and run it
examples/fpga_blinker.nl ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Hardware description in natural language (Verilog + testbench)
2
+ :name blinky
3
+ use hardware
4
+ create a counter called tick with width 8
5
+ create a register called leds with width 4
6
+ every 500 ms, increase leds by 1
7
+ when leds is 15, set leds to 0
8
+ connect tick to leds via wire
9
+ build and run it
examples/game.nl ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # The interaction from the proposal, then a small playable game.
2
+ :name arena
3
+ create an object
4
+ a game object called hero
5
+ give it 100 health, make it movable, and add collision detection
6
+ set speed to 5 and score 0
7
+ color blue
8
+ when health drops below 1, destroy it
9
+ when space is pressed, jump
10
+ every 2 seconds, print 'hero health {health}, score {score}'
11
+ create 3 enemies with health 30 and color red
12
+ when an enemy touches hero, decrease hero health by 10
13
+ create a coin called gold with value 10
14
+ when hero touches gold, increase hero score by 10 and destroy gold
15
+ build and run it
examples/smart_greenhouse.nl ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A multi-module system described in natural language:
2
+ # ESP32 firmware + FPGA fan PWM + Python monitor + 3D digital twin + 3D-printed enclosure.
3
+ :name greenhouse
4
+ add an esp32 called board
5
+ add a temperature sensor called temp to the board on pin 4 with temperature 20
6
+ add a fan called fan to the board on pin 5
7
+ add a button called btn to the board on pin 0
8
+ when temperature is above 30, turn on the fan
9
+ when temperature is below 25, turn off the fan
10
+ when the btn is pressed, toggle the fan
11
+
12
+ create a python dashboard called monitor with threshold 30
13
+ connect temp to monitor via http sending temperature every 2 seconds
14
+ when temperature is above threshold, print 'ALERT: greenhouse at {temperature} C'
15
+
16
+ create a 3d tank called twin with color green
17
+ connect monitor to twin via http sending temperature
18
+
19
+ create a hardware pwm called fan_pwm with duty 0 and width 8
20
+ connect board to fan_pwm via spi sending duty
21
+
22
+ create an enclosure called case for the board with wall 2
23
+ build and run it
nlcl/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ """NLCL - Natural Language Computational Language.
2
+
3
+ Natural language -> semantic tokens -> computational structure -> universal IR
4
+ -> multi-module code generation -> execution.
5
+ """
6
+ __version__ = "0.1.0"
nlcl/__main__.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """python -m nlcl [script.nl] [options]"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .runtime import HELP, Session
10
+
11
+
12
+ def main(argv=None) -> int:
13
+ for s in (sys.stdout, sys.stderr):
14
+ try:
15
+ s.reconfigure(encoding="utf-8")
16
+ except (AttributeError, ValueError):
17
+ pass
18
+ ap = argparse.ArgumentParser(prog="nlcl", description="Natural Language Computational Language runtime")
19
+ ap.add_argument("script", nargs="?", help="file with one natural-language instruction per line")
20
+ ap.add_argument("-p", "--project", default="project", help="system/project name")
21
+ ap.add_argument("-o", "--out", help="build directory (default ./build/<project>)")
22
+ ap.add_argument("-b", "--backend", help="LLM backend: auto|off|ollama|groq|gemini|openrouter|cerebras|mistral|huggingface|github")
23
+ ap.add_argument("-m", "--mode", default="hybrid", choices=["rules", "hybrid", "llm"])
24
+ ap.add_argument("--vocab", default=str(Path.home() / ".nlcl" / "vocab.json"), help="adaptive vocabulary file")
25
+ ap.add_argument("--trace", action="store_true", help="show tokens, composite tokens and IR for each line")
26
+ ap.add_argument("--yes", action="store_true", help="auto-accept vocabulary proposals")
27
+ ap.add_argument("--build", action="store_true", help="build after running the script")
28
+ ap.add_argument("--run", action="store_true", help="build and run after the script")
29
+ ap.add_argument("-c", "--command", action="append", help="instruction to execute (repeatable)")
30
+ a = ap.parse_args(argv)
31
+
32
+ s = Session(a.project, backend=a.backend, mode=a.mode, outdir=a.out, vocab_path=a.vocab,
33
+ trace=a.trace, auto_yes=a.yes)
34
+
35
+ def emit(lines):
36
+ for ln in lines:
37
+ print(ln, flush=True)
38
+
39
+ lines = []
40
+ if a.script:
41
+ lines = Path(a.script).read_text(encoding="utf-8-sig").splitlines()
42
+ if a.command:
43
+ lines += a.command
44
+ if lines:
45
+ for ln in lines:
46
+ if ln.strip() and not ln.strip().startswith("#"):
47
+ print(f"> {ln.strip()}")
48
+ try:
49
+ emit(s.handle(ln))
50
+ except EOFError:
51
+ return 0
52
+ if s.pending:
53
+ print(f"(unanswered question: {s.pending.text})")
54
+ if a.run:
55
+ emit(s.run())
56
+ elif a.build and s.dirty: # a script ending in "build it" is not built twice
57
+ emit(s.build())
58
+ return 0
59
+
60
+ print(f"NLCL {__version__} - natural language computational language. ':help' for help, ':quit' to exit.")
61
+ print(f"backend: {s.backend or 'offline rules'} domains: {', '.join(s.modules)}")
62
+ while True:
63
+ try:
64
+ prompt = "? " if s.pending or s.llm_question else "> "
65
+ line = input(prompt)
66
+ except (EOFError, KeyboardInterrupt):
67
+ print()
68
+ return 0
69
+ try:
70
+ emit(s.handle(line))
71
+ except EOFError:
72
+ return 0
73
+ except Exception as e: # never crash the REPL
74
+ print(f"! internal error: {type(e).__name__}: {e}")
75
+
76
+
77
+ if __name__ == "__main__":
78
+ sys.exit(main())
nlcl/bench/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
nlcl/bench/__main__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ from .run import main
2
+ import sys
3
+ sys.exit(main())
nlcl/bench/corpus.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Benchmark corpus: intents with a canonical sentence, training paraphrases and HELD-OUT test paraphrases,
2
+ plus out-of-scope / nonsense sentences for which the right behaviour is to NOT execute (ask instead).
3
+
4
+ The paraphrases were written as different people would phrase the request; they were not filtered by
5
+ whether the parser already understands them. Test paraphrases are never used for training.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ HERO = ["create a game player called hero with health 100"]
10
+ STORE = ["create a python service called store with stock 10 and price 5"]
11
+ BOARD = ["add an esp32 called board", "add a led called lamp to board on pin 2",
12
+ "add a temperature sensor called temp to board with temperature 20"]
13
+ FSM = ["create a hardware state machine called door with states closed, open and locked"]
14
+ APP = ['create an app called tally with title "Tally"', "add a label called display to tally with value 0",
15
+ 'add a button called plus to tally with text "+1"']
16
+ TWIN = ["create a 3d cube called box with color red"]
17
+
18
+ INTENTS = [
19
+ # ------------------------------------------------------------------ creation
20
+ dict(id="mk_player", context=[], gold=HERO,
21
+ train=["make a game player named hero with 100 health",
22
+ "I want a game player called hero that has 100 health",
23
+ "spawn a game player called hero, health 100"],
24
+ test=["please create a player for the game called hero with a health of 100",
25
+ "new game player hero with health 100",
26
+ "build a game player called hero and give it 100 health"]),
27
+ dict(id="mk_enemies", context=[], gold=["create 3 game enemies with health 30"],
28
+ train=["make three game enemies with 30 health",
29
+ "spawn 3 game enemies having health 30",
30
+ "add 3 enemies to the game with health 30"],
31
+ test=["create three game enemies, each with health 30",
32
+ "I need 3 game enemies with 30 health",
33
+ "generate 3 game foes with health 30"]),
34
+ dict(id="mk_service", context=[], gold=STORE,
35
+ train=["make a python service named store with 10 stock and price 5",
36
+ "create a store service in python with stock 10 and price 5",
37
+ "new python service called store, stock 10, price 5"],
38
+ test=["I'd like a python service called store with a stock of 10 and a price of 5",
39
+ "set up a python service called store with stock 10 and price 5",
40
+ "please make a python service store with stock 10 and price 5"]),
41
+ dict(id="mk_board", context=[], gold=["add an esp32 called board"],
42
+ train=["create an esp32 named board", "I need an esp32 called board", "make an esp32 board called board"],
43
+ test=["add a new esp32 called board", "put an esp32 called board in the project", "get an esp32 named board"]),
44
+ dict(id="mk_led", context=["add an esp32 called board"], gold=["add a led called lamp to board on pin 2"],
45
+ train=["connect a led called lamp to board on pin 2", "create a led named lamp on board at pin 2",
46
+ "add an led called lamp to the board on pin 2"],
47
+ test=["put a led called lamp on the board using pin 2", "attach a led named lamp to board on pin 2",
48
+ "the board needs a led called lamp on pin 2"]),
49
+ dict(id="mk_fsm", context=[], gold=FSM,
50
+ train=["make a hardware state machine named door with states closed, open and locked",
51
+ "create a state machine in hardware called door with the states closed, open, locked",
52
+ "new hardware state machine door with states closed, open and locked"],
53
+ test=["build a hardware state machine called door having states closed, open and locked",
54
+ "create a hardware fsm called door with states closed, open and locked",
55
+ "define a hardware state machine door whose states are closed, open and locked"]),
56
+ dict(id="mk_cube", context=[], gold=TWIN,
57
+ train=["make a red 3d cube called box", "create a 3d cube named box with red color",
58
+ "add a 3d cube called box, color red"],
59
+ test=["create a red cube in 3d called box", "new 3d cube box colored red",
60
+ "I want a 3d cube called box that is red"]),
61
+ dict(id="mk_enclosure", context=[], gold=["create a cad enclosure called case with wall 2"],
62
+ train=["make a cad enclosure named case with wall 2", "create an enclosure in cad called case, wall 2",
63
+ "new cad enclosure case with a wall of 2"],
64
+ test=["design a cad enclosure called case with wall 2", "create a cad enclosure called case with 2 mm walls",
65
+ "I need a cad enclosure named case whose wall is 2"]),
66
+ dict(id="mk_app", context=[], gold=['create an app called tally with title "Tally"'],
67
+ train=['make an app named tally with title "Tally"', 'create a new app called tally titled "Tally"',
68
+ 'I want an app called tally with the title "Tally"'],
69
+ test=['build an application called tally with title "Tally"', 'create an app tally with title "Tally"',
70
+ 'please create an app named tally whose title is "Tally"']),
71
+ # ------------------------------------------------------------------ properties
72
+ dict(id="set_speed", context=HERO, gold=["set speed of hero to 20"],
73
+ train=["give hero 20 speed", "hero's speed should be 20", "change the speed of hero to 20"],
74
+ test=["make hero's speed 20", "the speed of hero is 20", "set hero speed to 20"]),
75
+ dict(id="set_health", context=HERO, gold=["set health of hero to 50"],
76
+ train=["set hero's hp to 50", "change hero's health to 50", "give hero 50 health"],
77
+ test=["hero's health should be 50", "update the health of hero to 50", "set the hit points of hero to 50"]),
78
+ dict(id="set_color", context=TWIN, gold=["set color of box to blue"],
79
+ train=["make box blue", "change the color of box to blue", "box's color should be blue"],
80
+ test=["paint box blue", "set the colour of box to blue", "turn box blue"]),
81
+ dict(id="set_movable", context=HERO, gold=["make hero movable"],
82
+ train=["hero should be movable", "make the hero movable", "let hero move"],
83
+ test=["allow hero to move", "hero must be movable", "set hero movable"]),
84
+ dict(id="remove_prop", context=HERO + ["set speed of hero to 20"], gold=["remove speed from hero"],
85
+ train=["delete the speed of hero", "remove hero's speed", "take the speed off hero"],
86
+ test=["get rid of hero's speed", "drop speed from hero", "erase the speed of hero"]),
87
+ dict(id="rename", context=HERO, gold=["rename hero to knight"],
88
+ train=["call hero knight", "change hero's name to knight", "rename the hero to knight"],
89
+ test=["hero should be called knight", "name hero knight", "change the name of hero to knight"]),
90
+ dict(id="delete_entity", context=HERO, gold=["delete hero"],
91
+ train=["remove hero", "destroy the hero", "get rid of hero"],
92
+ test=["erase hero", "remove the hero from the game", "throw away hero"]),
93
+ # ------------------------------------------------------------------ behaviours
94
+ dict(id="beh_die", context=HERO, gold=["when health of hero is below 1, destroy hero"],
95
+ train=["when hero's health drops below 1, destroy it", "destroy hero when its health is below 1",
96
+ "if hero's health is less than 1, destroy hero"],
97
+ test=["when the health of hero goes below 1 destroy hero", "hero dies when its health is under 1",
98
+ "kill hero once its health falls below 1"]),
99
+ dict(id="beh_timer", context=STORE, gold=["every 2 seconds, decrease stock of store by 1"],
100
+ train=["every two seconds, reduce store's stock by 1", "decrease the stock of store by 1 every 2 seconds",
101
+ "every 2 seconds lower stock of store by 1"],
102
+ test=["each 2 seconds, decrease store's stock by 1", "every 2000 ms, decrease stock of store by 1",
103
+ "take 1 from the stock of store every 2 seconds"]),
104
+ dict(id="beh_key", context=HERO, gold=["when space is pressed, hero jumps"],
105
+ train=["when the player presses space, hero jumps", "hero jumps when space is pressed",
106
+ "if space is pressed, hero jumps"],
107
+ test=["when I press space, hero jumps", "pressing space makes hero jump", "on space, hero jumps"]),
108
+ dict(id="beh_button", context=APP, gold=["when plus is pressed, increase value of display by 1"],
109
+ train=["when plus is clicked, increase value of display by 1", "if plus is pressed, add 1 to value of display",
110
+ "increase display's value by 1 when plus is pressed"],
111
+ test=["clicking plus adds 1 to the value of display", "when plus is pressed, raise value of display by 1",
112
+ "when the plus button is pressed, increment value of display by 1"]),
113
+ dict(id="beh_sensor", context=BOARD, gold=["when temperature of temp is above 30, turn on lamp"],
114
+ train=["when temp's temperature is above 30, turn on lamp", "turn on lamp when temperature of temp is above 30",
115
+ "if the temperature of temp is greater than 30, turn on lamp"],
116
+ test=["when temp reads more than 30 degrees, switch on lamp", "when temperature of temp exceeds 30, turn lamp on",
117
+ "lamp should turn on when temp's temperature is over 30"]),
118
+ dict(id="beh_fsm", context=FSM, gold=["every 3 seconds, if state of door is closed, set state of door to open"],
119
+ train=["every 3 seconds, if door's state is closed, set door's state to open",
120
+ "every three seconds, when state of door is closed, set state of door to open",
121
+ "every 3 s, if state of door is closed, set door state to open"],
122
+ test=["each 3 seconds, if the door is closed, open it", "every 3 seconds, change door's state from closed to open",
123
+ "every 3 seconds if state of door equals closed set state of door to open"]),
124
+ # ------------------------------------------------------------------ links
125
+ dict(id="connect", context=BOARD + ["create a python dashboard called monitor"],
126
+ gold=["connect temp to monitor via http sending temperature every 2 seconds"],
127
+ train=["link temp to monitor via http sending temperature every 2 seconds",
128
+ "connect temp to monitor over http, sending temperature every 2 seconds",
129
+ "send temperature from temp to monitor via http every 2 seconds"],
130
+ test=["wire temp to monitor via http sending temperature every 2 seconds",
131
+ "hook up temp to monitor over http sending temperature every 2 seconds",
132
+ "connect the temp sensor to monitor via http, sending temperature every 2 seconds"]),
133
+ dict(id="parent", context=["create a cpp object called robot", "create a cpp object called wheel"],
134
+ gold=["put wheel inside robot"],
135
+ train=["make wheel a child of robot", "wheel is part of robot", "place wheel in robot"],
136
+ test=["attach wheel to robot", "wheel belongs inside robot", "move wheel into robot"]),
137
+ # ------------------------------------------------------------------ terminal
138
+ dict(id="t_list_py", context=[], gold=["list all python files in src"],
139
+ train=["show me the python files in src", "list the .py files in src", "what python files are in src"],
140
+ test=["display all python files in the folder src", "ls the python files in src", "which python files are in src"]),
141
+ dict(id="t_count_logs", context=[], gold=["count the log files in logs"],
142
+ train=["how many log files are in logs", "how many .log files are there in logs", "number of log files in logs"],
143
+ test=["count all .log files in logs", "how many log files does logs have", "tell me how many log files are in logs"]),
144
+ dict(id="t_mkdir", context=[], gold=["create a folder called backup"],
145
+ train=["make a new folder named backup", "make a directory called backup", "mkdir backup"],
146
+ test=["create a new directory named backup", "add a folder called backup", "I need a folder called backup"]),
147
+ dict(id="t_delete_tmp", context=[], gold=["delete all .tmp files recursively"],
148
+ train=["remove all temporary files recursively", "delete every .tmp file including subfolders",
149
+ "get rid of all tmp files recursively"],
150
+ test=["erase all .tmp files in all subfolders", "clean up the temporary files everywhere",
151
+ "wipe all .tmp files recursively"]),
152
+ dict(id="t_copy", context=[], gold=["copy notes.txt to backup.txt"],
153
+ train=["duplicate notes.txt to backup.txt", "make a copy of notes.txt called backup.txt", "cp notes.txt to backup.txt"],
154
+ test=["copy the file notes.txt to backup.txt", "copy notes.txt into backup.txt", "clone notes.txt to backup.txt"]),
155
+ dict(id="t_rename", context=[], gold=["rename data.csv to people.csv"],
156
+ train=["rename the file data.csv to people.csv", "move data.csv to people.csv", "change the name of data.csv to people.csv"],
157
+ test=["mv data.csv to people.csv", "rename data.csv as people.csv", "data.csv should be renamed to people.csv"]),
158
+ dict(id="t_head", context=[], gold=["show the first 2 lines of notes.txt"],
159
+ train=["print the first 2 lines of notes.txt", "display the top 2 lines of notes.txt", "first 2 lines of notes.txt"],
160
+ test=["show me the first 2 lines in notes.txt", "head 2 lines of notes.txt", "read the first 2 lines of notes.txt"]),
161
+ dict(id="t_grep", context=[], gold=["search for 'TODO' in all python files"],
162
+ train=["find 'TODO' in all python files", "which python files contain 'TODO'", "look for 'TODO' in the python files"],
163
+ test=["grep 'TODO' in python files", "search all python files for 'TODO'", "where does 'TODO' appear in python files"]),
164
+ dict(id="t_lines", context=[], gold=["count the lines in data.csv"],
165
+ train=["how many lines are in data.csv", "number of lines in data.csv", "count lines of data.csv"],
166
+ test=["how many lines does data.csv have", "line count of data.csv", "tell me the number of lines in data.csv"]),
167
+ dict(id="t_replace", context=[], gold=["replace 'apple' with 'pear' in notes.txt"],
168
+ train=["replace all 'apple' with 'pear' in notes.txt", "replace the word 'apple' with 'pear' in notes.txt",
169
+ "in notes.txt replace 'apple' with 'pear'"],
170
+ test=["change 'apple' to 'pear' in notes.txt", "swap 'apple' for 'pear' in notes.txt",
171
+ "replace every 'apple' by 'pear' in the file notes.txt"]),
172
+ dict(id="t_zip", context=[], gold=["zip the folder src into src.zip"],
173
+ train=["compress src into src.zip", "archive the folder src as src.zip", "zip src to src.zip"],
174
+ test=["make a zip of src called src.zip", "pack src into src.zip", "compress the folder src to src.zip"]),
175
+ ]
176
+
177
+ # Out-of-scope or meaningless: the right behaviour is to NOT execute (ask).
178
+ INVALID_TRAIN = ["flibber the wobble", "frobnicate hero quickly", "the weather is nice today", "tell me a joke",
179
+ "blorp", "make it better", "do the thing", "sing a song about the board", "why is the sky blue",
180
+ "hero sparkle mode engage", "zap zap", "optimize everything magically"]
181
+ INVALID_TEST = ["glorp the snizzle", "what time is it", "make it awesome", "please do something cool",
182
+ "hero feels sad", "the quick brown fox", "fix my life", "teleport hero to mars instantly",
183
+ "wobble wobble", "do what I mean", "turn the frobnitz", "be smarter"]
184
+
185
+
186
+ def build_examples(extended: bool = True):
187
+ import copy
188
+ from ..learn import Example
189
+ from .corpus2 import extend
190
+ intents, inv_tr, inv_te = copy.deepcopy(INTENTS), list(INVALID_TRAIN), list(INVALID_TEST)
191
+ if extended:
192
+ extend(intents, inv_tr, inv_te)
193
+ out = []
194
+ for it in intents:
195
+ for split in ("train", "test"):
196
+ for i, text in enumerate(it[split]):
197
+ out.append(Example(id=f"{it['id']}:{split}{i}", text=text, split=split, context=list(it["context"]),
198
+ gold=list(it["gold"]), valid=True, intent=it["id"], holdout=bool(it.get("holdout"))))
199
+ out.append(Example(id=f"{it['id']}:gold", text=it["gold"][-1], split="gold", context=list(it["context"]) + it["gold"][:-1],
200
+ gold=list(it["gold"]), valid=True, intent=it["id"]))
201
+ ctx = HERO
202
+ for i, t in enumerate(inv_tr):
203
+ out.append(Example(id=f"invalid:train{i}", text=t, split="train", context=ctx, gold=[], valid=False, intent="invalid"))
204
+ for i, t in enumerate(inv_te):
205
+ out.append(Example(id=f"invalid:test{i}", text=t, split="test", context=ctx, gold=[], valid=False, intent="invalid"))
206
+ return out
nlcl/bench/corpus2.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """100 further corpus sentences (added 2026-11-22).
2
+
3
+ * 10 intents with vague words (fuzzy meanings): 60 sentences. Four of these intents are HELD OUT
4
+ entirely ("unseen intents"): none of their sentences is used for training, so the score on them
5
+ measures generalisation to new meanings, not to new wordings of trained meanings.
6
+ * 30 additional paraphrases for 10 existing intents (10 training, 20 test).
7
+ * 10 additional out-of-scope / risky sentences (5 training, 5 test) that must NOT be executed.
8
+ Written as people phrase things; not filtered by whether the parser already understands them.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ HERO = ["create a game player called hero with health 100"]
13
+ HERO10 = HERO + ["set speed of hero to 10"]
14
+ BOARD = ["add an esp32 called board", "add a led called lamp to board on pin 2"]
15
+ TAXI = ["create a game car called taxi"]
16
+
17
+ FUZZY_INTENTS = [
18
+ dict(id="fz_fast", context=HERO, gold=["make hero fast"],
19
+ train=["hero should be fast", "make the hero fast", "I want hero to be fast"],
20
+ test=["set hero to fast", "hero needs to be fast", "make hero speedy"]),
21
+ dict(id="fz_very_fast", context=HERO, gold=["make hero very fast"],
22
+ train=["hero should be very fast", "make the hero really fast", "I want hero to be very fast"],
23
+ test=["make hero really quick", "hero must be very fast", "make the hero very speedy"]),
24
+ dict(id="fz_slow", context=HERO, gold=["make hero slow"],
25
+ train=["hero should be slow", "make the hero slow", "I want the hero to be slow"],
26
+ test=["hero needs to be slow", "make hero sluggish", "set hero to slow"]),
27
+ dict(id="fz_bit_slower", context=HERO10, gold=["make hero a bit slower"],
28
+ train=["make hero slightly slower", "make the hero a little slower", "hero should be a bit slower"],
29
+ test=["slow hero down a bit", "make hero a tad slower", "make hero just a little slower"]),
30
+ dict(id="fz_much_faster", context=HERO10, gold=["make hero much faster"],
31
+ train=["make hero a lot faster", "hero should be much faster", "make the hero a lot faster"],
32
+ test=["make hero much quicker", "hero needs to be a lot faster", "speed hero up a lot"]),
33
+ dict(id="fz_cond_low", context=HERO, gold=["when health of hero is low, print 'help'"],
34
+ train=["when hero's health is low, print 'help'", "print 'help' when the health of hero is low",
35
+ "if health of hero gets low, print 'help'"],
36
+ test=["when the hero's health becomes low, print 'help'", "if hero's health is low print 'help'",
37
+ "print 'help' whenever hero's health is low"]),
38
+ # ---- held out entirely: never trained on
39
+ dict(id="fz_taxi_fast", context=TAXI, gold=["make taxi fast"], holdout=True, train=[],
40
+ test=["taxi should be fast", "make the taxi fast", "I want taxi to be fast",
41
+ "set taxi to fast", "taxi needs to be fast", "make taxi quick"]),
42
+ dict(id="fz_lamp_bright", context=BOARD, gold=["make lamp bright"], holdout=True, train=[],
43
+ test=["lamp should be bright", "make the lamp bright", "I want lamp to be bright",
44
+ "set lamp to bright", "the lamp needs to be bright", "make lamp very bright"]),
45
+ dict(id="fz_lamp_dimmer", context=BOARD + ["set brightness of lamp to 200"], gold=["make lamp a bit dimmer"],
46
+ holdout=True, train=[],
47
+ test=["make lamp slightly dimmer", "make the lamp a little dimmer", "lamp should be a bit dimmer",
48
+ "make lamp a bit darker", "dim the lamp a bit", "make lamp just a little dimmer"]),
49
+ dict(id="fz_twice", context=HERO + ["set speed of hero to 5"], gold=["make hero twice as fast"], holdout=True,
50
+ train=[],
51
+ test=["hero should be twice as fast", "make the hero twice as fast", "make hero two times as fast",
52
+ "double hero's speed", "hero needs to be twice as fast", "make hero twice as fast as before"]),
53
+ ]
54
+ # "make lamp very bright" in fz_lamp_bright is deliberately a DIFFERENT meaning (should not match): it tests
55
+ # that the interpreter does not confuse 'very bright' with 'bright'.
56
+
57
+ # extra paraphrases for existing intents (intent id -> (train, test))
58
+ EXTRA = {
59
+ "mk_player": (["add a player to the game called hero with 100 health"],
60
+ ["create a game player hero, give it 100 health", "make me a game player named hero with health 100"]),
61
+ "mk_enemies": (["create 3 enemies for the game with health 30"],
62
+ ["spawn three game monsters with health 30", "add 3 game opponents with 30 health"]),
63
+ "set_speed": (["set the speed of hero to 20"],
64
+ ["hero should have speed 20", "change hero speed to 20"]),
65
+ "set_color": (["set the color of box to blue"],
66
+ ["box should be blue", "make the box blue"]),
67
+ "rename": (["change the name of hero to knight"],
68
+ ["rename hero as knight", "hero is now called knight"]),
69
+ "delete_entity": (["delete the hero"],
70
+ ["remove hero completely", "eliminate hero"]),
71
+ "beh_timer": (["each 2 seconds, decrease stock of store by 1"],
72
+ ["every 2 secs, decrease stock of store by 1", "reduce the stock of store by 1 every two seconds"]),
73
+ "beh_sensor": (["when the temperature of temp is above 30, switch on lamp"],
74
+ ["if temp's temperature exceeds 30, turn on lamp", "turn on the lamp whenever temperature of temp is above 30"]),
75
+ "t_mkdir": (["create a directory called backup"],
76
+ ["new folder backup", "make the folder backup"]),
77
+ "t_delete_tmp": (["delete all tmp files recursively"],
78
+ ["remove every .tmp file recursively", "delete the temporary files in all subfolders"]),
79
+ }
80
+
81
+ # out-of-scope / risky: must not be executed
82
+ INVALID_TRAIN2 = ["make everything better", "delete the universe", "hero go brrr", "compute the meaning of life",
83
+ "make the code nicer somehow"]
84
+ INVALID_TEST2 = ["please read my mind", "launch the missiles", "make it pop", "hero dance dance", "be creative"]
85
+
86
+
87
+ def extend(intents: list, invalid_train: list, invalid_test: list) -> None:
88
+ """Merge into the base corpus (in place)."""
89
+ by_id = {it["id"]: it for it in intents}
90
+ for iid, (tr, te) in EXTRA.items():
91
+ it = by_id[iid]
92
+ it["train"] = list(it["train"]) + tr
93
+ it["test"] = list(it["test"]) + te
94
+ intents.extend(FUZZY_INTENTS)
95
+ invalid_train.extend(INVALID_TRAIN2)
96
+ invalid_test.extend(INVALID_TEST2)
97
+
98
+
99
+ def count() -> int:
100
+ n = sum(len(it["train"]) + len(it["test"]) for it in FUZZY_INTENTS)
101
+ n += sum(len(a) + len(b) for a, b in EXTRA.values())
102
+ return n + len(INVALID_TRAIN2) + len(INVALID_TEST2)
nlcl/bench/fixture.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Builds the small project folder used by the terminal tests and the benchmark."""
2
+ from pathlib import Path
3
+
4
+ FILES = {
5
+ "README.md": "# demo\nA small project.\n",
6
+ "notes.txt": "banana\napple\nCherry\napple pie\n",
7
+ "data.csv": "id,name\n1,ann\n2,bob\n3,cy\n",
8
+ "src/main.py": "import util\nprint('hello')\n# TODO: refactor\n",
9
+ "src/util.py": "def add(a, b):\n return a + b\n# TODO: tests\n",
10
+ "src/app.js": "console.log('hi');\n",
11
+ "src/old.tmp": "scratch\n",
12
+ "logs/run1.log": "ok\nwarning: disk\nok\n",
13
+ "logs/run2.log": "error: crash\n",
14
+ "cache.tmp": "x\n",
15
+ "docs/guide.md": "Guide\nTODO: write\n",
16
+ "big.bin": "0" * 5000 + "\n",
17
+ }
18
+
19
+
20
+ def build(root: Path) -> Path:
21
+ root = Path(root)
22
+ for rel, text in FILES.items():
23
+ p = root / rel
24
+ p.parent.mkdir(parents=True, exist_ok=True)
25
+ p.write_bytes(text.encode("utf-8"))
26
+ (root / "empty_dir").mkdir(exist_ok=True)
27
+ return root
nlcl/bench/run.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NLCL benchmark: python -m nlcl.bench [--out DIR] [--backend NAME|auto|off] [--quick]
2
+
3
+ Suites (all on the same corpus, held-out sentences only for scoring):
4
+ fidelity interpretation accuracy, silent errors, nonsense refusal, calibration, consistency
5
+ learning the same metrics after training on 0 / 1 / 2 / 3 paraphrases per intent
6
+ terminal effect-equivalence of terminal sentences + verification of every generated bash / PowerShell
7
+ command in a sandbox + unconfirmed destructive actions
8
+ determinism identical interpretations across repeated runs
9
+ cost latency and tokens
10
+ Systems: nlcl-untrained, nlcl-trained, and (with an API key) llm-direct and nlcl+teacher.
11
+ Writes report.md and results.json.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import json
17
+ import sys
18
+ import tempfile
19
+ import time
20
+ from pathlib import Path
21
+
22
+ from .. import modules as modreg
23
+ from .. import weights as wmod
24
+ from ..interpreter import Interpreter
25
+ from ..knowledge import Knowledge
26
+ from ..learn import Evaluator, Example, consistency, load_corpus, metrics, signature, train
27
+ from ..shell import crosscheck, execute, snapshot, ShellError
28
+
29
+ HERE = Path(__file__).resolve().parent
30
+
31
+
32
+ def _fixture() -> Path:
33
+ from .fixture import build
34
+ return build(Path(tempfile.mkdtemp(prefix="nlcl_bench_fs_")) / "proj")
35
+
36
+
37
+ def _fresh_kb() -> Knowledge:
38
+ return Knowledge(tempfile.mkdtemp(prefix="nlcl_bench_kb_"), modreg.load_modules())
39
+
40
+
41
+ def _subset(examples: list[Example], k: int) -> list[Example]:
42
+ """Training set with only the first k training paraphrases of every intent (invalid: first 4k)."""
43
+ out = []
44
+ count: dict[str, int] = {}
45
+ for e in examples:
46
+ if e.split != "train":
47
+ out.append(e)
48
+ continue
49
+ lim = 4 * k if e.intent == "invalid" else k
50
+ count[e.intent] = count.get(e.intent, 0) + 1
51
+ if count[e.intent] <= lim:
52
+ out.append(e)
53
+ return out
54
+
55
+
56
+ # ---------------------------------------------------------------------- LLM baselines
57
+ class LLMDirect:
58
+ """The model reads the sentence and writes the IR itself (no weighting, no abstention except questions)."""
59
+
60
+ def __init__(self, backend):
61
+ from ..llm import LLMParser
62
+ self.backend = backend
63
+ self.p = LLMParser(backend)
64
+ self.tokens = 0
65
+
66
+ def run(self, ev: Evaluator, ex: Example) -> dict:
67
+ from ..llm import LLMError
68
+ st = ev.context_state(ex.context)
69
+ t0 = time.perf_counter()
70
+ try:
71
+ ops, question = self.p.parse(ex.text, st, list(modreg.load_modules()))
72
+ except LLMError as e:
73
+ from ..llm import QuotaExceeded
74
+ if isinstance(e, QuotaExceeded):
75
+ raise
76
+ ops, question = [], f"error: {e}"
77
+ dt = time.perf_counter() - t0
78
+ self.tokens += (len(ex.text) + 4000) // 4 # prompt + sentence, rough
79
+ executed = bool(ops)
80
+ shell = []
81
+ try:
82
+ Interpreter(st).apply_all([o for o in ops if o.action != "SHELL"])
83
+ except Exception:
84
+ pass
85
+ shell = [o.props for o in ops if o.action == "SHELL"]
86
+ right = signature(st, shell) == ev.gold_signature(ex) and executed == ex.valid
87
+ return {"id": ex.id, "text": ex.text, "valid": ex.valid, "right": right, "weight": 1.0 if executed else 0.0,
88
+ "decision": "execute" if executed else "ask", "executed": executed, "features": {},
89
+ "source": "llm", "summary": " ; ".join(map(str, ops)) or (question or ""), "seconds": dt,
90
+ "frames": [], "intent": None}
91
+
92
+
93
+ def _teacher_run(kb, backend, ev: Evaluator, ex: Example) -> dict:
94
+ """NLCL with the model as a teacher below the execution weight (and distillation into the KB)."""
95
+ from ..runtime import Session
96
+ from .. import discover
97
+ s = Session("bench", backend=backend, kb=kb)
98
+ s.interactive, s.auto_yes = False, True
99
+ s.state = ev.context_state(ex.context)
100
+ s.interp = Interpreter(s.state)
101
+ t0 = time.perf_counter()
102
+ best = s.interpret(ex.text)[0]
103
+ source = "nlcl"
104
+ ops = best.ops
105
+ if best.score < s.execute_at:
106
+ from ..llm import LLMError
107
+ try:
108
+ ops2, q = s.llm.parse(ex.text, s.state, list(modreg.load_modules()))
109
+ except LLMError as e:
110
+ from ..llm import QuotaExceeded
111
+ if isinstance(e, QuotaExceeded):
112
+ raise
113
+ ops2, q = [], None
114
+ if ops2:
115
+ dry = wmod.llm_features(ops2, s.state)
116
+ if wmod.score(dry, kb.params()) >= s.ask_below:
117
+ rule = discover.distill(s, ex.text, ops2)
118
+ if rule:
119
+ kb.add_rewrite(rule[0], rule[1], 1)
120
+ ops, source = ops2, "teacher"
121
+ else:
122
+ ops = []
123
+ else:
124
+ ops = []
125
+ executed = bool(ops) and (source == "teacher" or wmod.decision(best.score) != "ask")
126
+ shell = []
127
+ if executed:
128
+ Interpreter(s.state).apply_all([o for o in ops if o.action != "SHELL"])
129
+ shell = [o.props for o in ops if o.action == "SHELL"]
130
+ right = signature(s.state, shell) == ev.gold_signature(ex) and executed == ex.valid
131
+ return {"id": ex.id, "text": ex.text, "valid": ex.valid, "right": right, "weight": best.score,
132
+ "decision": "execute" if executed else "ask", "executed": executed, "features": best.features,
133
+ "source": source, "summary": " ; ".join(map(str, ops)), "seconds": time.perf_counter() - t0,
134
+ "frames": [], "intent": None}
135
+
136
+
137
+ # ---------------------------------------------------------------------- terminal suite
138
+ def terminal_suite(kb, fs: Path, examples: list[Example]) -> dict:
139
+ ev = Evaluator(kb, fs)
140
+ from ..runtime import Session
141
+ term = [e for e in examples if e.split == "test" and e.intent.startswith("t_")]
142
+ rows, verified, checked, unconfirmed = [], 0, 0, 0
143
+ for ex in term:
144
+ s = Session("bench", backend="off", kb=kb)
145
+ s.cwd = fs
146
+ s.interactive, s.auto_yes = True, False
147
+ best = s.interpret(ex.text)[0]
148
+ gold = s.interpret(ex.gold[-1])[0]
149
+ ok = False
150
+ if best.source == "shell" and best.ops and gold.source == "shell":
151
+ ok = _same_effect(best.ops[0], gold.ops[0], fs)
152
+ for sh in ("bash", "powershell"):
153
+ try:
154
+ good, _why = crosscheck(best.ops[0], fs, sh)
155
+ except Exception:
156
+ good = False
157
+ checked += 1
158
+ verified += int(good)
159
+ # would the runtime change files without confirmation?
160
+ out = s._shell(best)
161
+ if any(line.strip() == "done" or line.startswith(" done") for line in out):
162
+ if kb.needs_confirmation(best.ops[0].props["intent"]):
163
+ unconfirmed += 1
164
+ s.confirm = None
165
+ rows.append({"text": ex.text, "right": ok, "weight": round(best.score, 3), "source": best.source,
166
+ "executed": wmod.decision(best.score) != "ask" and best.source == "shell"})
167
+ n = len(rows)
168
+ return {"sentences": n,
169
+ "effect_accuracy": round(sum(r["right"] for r in rows) / max(1, n), 4),
170
+ "silent_error_rate": round(sum(1 for r in rows if r["executed"] and not r["right"]) / max(1, n), 4),
171
+ "commands_verified": f"{verified}/{checked}",
172
+ "unconfirmed_destructive_actions": unconfirmed,
173
+ "rows": rows}
174
+
175
+
176
+ def _same_effect(a, b, fs: Path) -> bool:
177
+ with tempfile.TemporaryDirectory() as td:
178
+ import shutil
179
+ pa, pb = Path(td) / "a", Path(td) / "b"
180
+ shutil.copytree(fs, pa)
181
+ shutil.copytree(fs, pb)
182
+ try:
183
+ oa = execute(a, pa)
184
+ except ShellError:
185
+ return False
186
+ try:
187
+ ob = execute(b, pb)
188
+ except ShellError:
189
+ return False
190
+ return snapshot(pa) == snapshot(pb) and oa.replace(str(pa), "") == ob.replace(str(pb), "")
191
+
192
+
193
+ def llm_terminal_suite(backend, fs: Path, examples: list[Example], limit: int = 0) -> dict:
194
+ """The model writes a bash command directly; scored by the same sandbox effect check."""
195
+ import shutil
196
+ import subprocess
197
+ from ..llm import LLMError
198
+ from ..runtime import Session
199
+ term = [e for e in examples if e.split == "test" and e.intent.startswith("t_")]
200
+ if limit and limit < len(term):
201
+ term = [term[int(i * len(term) / limit)] for i in range(limit)]
202
+ right = executed = 0
203
+ kb = _fresh_kb()
204
+ for ex in term:
205
+ s = Session("bench", backend="off", kb=kb)
206
+ gold = s.interpret(ex.gold[-1])[0]
207
+ try:
208
+ cmd = backend.chat([{"role": "system", "content": "Reply with ONLY one bash command, no explanation, "
209
+ "no code fences. Working directory is the project folder."},
210
+ {"role": "user", "content": ex.text}], json_mode=False).strip().strip("`")
211
+ except LLMError as e:
212
+ from ..llm import QuotaExceeded
213
+ if isinstance(e, QuotaExceeded):
214
+ raise
215
+ continue
216
+ executed += 1
217
+ with tempfile.TemporaryDirectory() as td:
218
+ pa, pb = Path(td) / "a", Path(td) / "b"
219
+ shutil.copytree(fs, pa)
220
+ shutil.copytree(fs, pb)
221
+ try:
222
+ ref = execute(gold.ops[0], pa)
223
+ p = subprocess.run(["bash", "-c", cmd], cwd=str(pb), capture_output=True, text=True, timeout=60)
224
+ same_fs = snapshot(pa) == snapshot(pb)
225
+ same_out = sorted(x.strip().lstrip("./") for x in ref.splitlines() if x.strip()) == \
226
+ sorted(x.strip().lstrip("./") for x in p.stdout.splitlines() if x.strip())
227
+ right += int(same_fs and (same_out or ref == ""))
228
+ except Exception:
229
+ pass
230
+ n = len(term)
231
+ return {"sentences": n, "effect_accuracy": round(right / max(1, n), 4), "executed": executed}
232
+
233
+
234
+ # ---------------------------------------------------------------------- main
235
+ def run_bench(out: Path, backend_name: str | None = "off", quick: bool = False, log=print, sample_n: int = 0) -> dict:
236
+ from ..llm import autodetect
237
+ out.mkdir(parents=True, exist_ok=True)
238
+ examples = load_corpus()
239
+ fs = _fixture()
240
+ results: dict = {"date": time.strftime("%Y-%m-%d %H:%M"), "systems": {}, "learning_curve": [], "notes": []}
241
+ test = [e for e in examples if e.split == "test"]
242
+
243
+ log("== fidelity: untrained")
244
+ kb0 = _fresh_kb()
245
+ ev0 = Evaluator(kb0, fs)
246
+ r0 = [ev0.run(e) for e in test]
247
+ m0 = metrics(r0)
248
+ m0["paraphrase_consistency"] = consistency(r0, test)
249
+ results["systems"]["nlcl-untrained"] = m0
250
+
251
+ log("== learning curve")
252
+ for k in ([0, 3] if quick else [0, 1, 2, 3]):
253
+ kb = _fresh_kb()
254
+ if k:
255
+ train(kb, _subset(examples, k), log=lambda *a: None, cwd=fs)
256
+ ev = Evaluator(kb, fs)
257
+ res = [ev.run(e, kb.rewrites(), kb.params() or None) for e in test]
258
+ m = metrics(res)
259
+ m["paraphrases_per_intent"] = k
260
+ m["rules_learned"] = kb.stats()["rewrites"]
261
+ results["learning_curve"].append(m)
262
+ log(f" k={k}: accuracy {m['interpretation_accuracy']} silent {m['silent_error_rate']} "
263
+ f"nonsense {m['nonsense_caught']} ece {m['calibration_ece']}")
264
+ kb_t = _fresh_kb()
265
+ tr = train(kb_t, examples, log=lambda *a: None, cwd=fs)
266
+ ev_t = Evaluator(kb_t, fs)
267
+ rt = [ev_t.run(e, kb_t.rewrites(), kb_t.params()) for e in test]
268
+ mt = metrics(rt)
269
+ mt["paraphrase_consistency"] = consistency(rt, test)
270
+ mt["rules_learned"] = tr["rules_learned"]
271
+ results["systems"]["nlcl-trained"] = mt
272
+ results["learned_kb"] = kb_t.learned_text()
273
+ # risk / coverage: what share it executes at each weight threshold, and how often that is right
274
+ sel = []
275
+ for th in (0.0, 0.35, 0.5, 0.6, 0.7, 0.8, 0.9):
276
+ ex_ = [r for r in rt if r["weight"] >= th and r["summary"] != "(nothing)"]
277
+ sel.append({"threshold": th, "coverage": round(len(ex_) / len(rt), 3),
278
+ "precision": round(sum(r["right"] for r in ex_) / max(1, len(ex_)), 3),
279
+ "wrong_executions": sum(1 for r in ex_ if not r["right"])})
280
+ results["selective"] = sel
281
+
282
+ log("== determinism")
283
+ runs = []
284
+ for _ in range(2 if quick else 5):
285
+ evd = Evaluator(kb_t, fs)
286
+ runs.append([evd.run(e, kb_t.rewrites(), kb_t.params())["summary"] for e in test])
287
+ same = sum(1 for i in range(len(test)) if len({r[i] for r in runs}) == 1)
288
+ results["determinism"] = {"nlcl": f"{same}/{len(test)}", "runs": len(runs)}
289
+
290
+ log("== terminal")
291
+ results["terminal"] = {"nlcl-trained": terminal_suite(kb_t, fs, examples)}
292
+
293
+ backend = None
294
+ if backend_name not in ("off", "none"):
295
+ backend = autodetect(None if backend_name in (None, "auto") else backend_name)
296
+ if backend is None:
297
+ results["notes"].append("llm-direct and nlcl+teacher were NOT run: no language-model backend "
298
+ "(set a free API key, see ':backend status', then run again).")
299
+ else:
300
+ from ..llm import QuotaExceeded
301
+ # the same sample of held-out sentences for every system (free tiers allow few requests a day)
302
+ def spread(items, k):
303
+ return [items[int(i * len(items) / k)] for i in range(k)] if k < len(items) else list(items)
304
+ if not sample_n or sample_n >= len(test):
305
+ sample = test
306
+ else: # keep the share of nonsense sentences, spread over all intents
307
+ bad = [e for e in test if not e.valid]
308
+ good = [e for e in test if e.valid]
309
+ k_bad = max(1, round(sample_n * len(bad) / len(test)))
310
+ sample = spread(good, sample_n - k_bad) + spread(bad, k_bad)
311
+ ids = {e.id for e in sample}
312
+ if len(sample) < len(test):
313
+ results["notes"].append(f"language-model systems were scored on a sample of {len(sample)} of {len(test)} "
314
+ "held-out sentences; the NLCL columns in the comparison table use the same sample.")
315
+ for name, rows in (("nlcl-untrained", r0), ("nlcl-trained", rt)):
316
+ sub = [r for r in rows if r["id"] in ids]
317
+ ms = metrics(sub)
318
+ ms["paraphrase_consistency"] = consistency(sub, sample)
319
+ results["systems"][name + " (sample)"] = ms
320
+ n_term = 33 if len(sample) == len(test) else max(3, len(sample) // 3)
321
+ n_rep = 10 if len(sample) == len(test) else 4
322
+ log(f"== llm-direct ({backend}) on {len(sample)} sentences; at most about "
323
+ f"{len(sample) + n_rep + len(sample) // 2 + n_term} requests in total")
324
+ try:
325
+ lp = LLMDirect(backend)
326
+ ev_l = Evaluator(_fresh_kb(), fs)
327
+ rl = [lp.run(ev_l, e) for e in sample]
328
+ ml = metrics(rl)
329
+ ml["paraphrase_consistency"] = consistency(rl, sample)
330
+ ml["approx_tokens"] = lp.tokens
331
+ for k in ("calibration_ece", "calibration_brier", "calibration_auroc"):
332
+ ml[k] = "n/a"
333
+ results["systems"]["llm-direct"] = ml
334
+ rep_n = min(10 if len(sample) == len(test) else 4, len(sample))
335
+ rl2 = [lp.run(ev_l, e)["summary"] for e in sample[:rep_n]]
336
+ same_l = sum(1 for a, b in zip([r["summary"] for r in rl], rl2) if a == b)
337
+ results["determinism"]["llm-direct"] = f"{same_l}/{rep_n}"
338
+ log("== nlcl+teacher")
339
+ kb_h = _fresh_kb()
340
+ train(kb_h, examples, log=lambda *a: None, cwd=fs)
341
+ ev_h = Evaluator(kb_h, fs)
342
+ rh = [_teacher_run(kb_h, backend, ev_h, e) for e in sample]
343
+ mh = metrics(rh)
344
+ mh["paraphrase_consistency"] = consistency(rh, sample)
345
+ mh["rules_distilled"] = kb_h.stats()["rewrites"] - tr["rules_learned"]
346
+ results["systems"]["nlcl+teacher"] = mh
347
+ log("== llm terminal")
348
+ results["terminal"]["llm-direct"] = llm_terminal_suite(
349
+ backend, fs, examples, limit=0 if len(sample) == len(test) else max(3, len(sample) // 3))
350
+ except QuotaExceeded as e:
351
+ results["notes"].append(f"stopped early: {e}. Systems not listed were not completed.")
352
+ log(f" stopped: {e}")
353
+
354
+ results["cost"] = {"nlcl_median_ms": mt["median_ms"], "nlcl_tokens": 0}
355
+ (out / "results.json").write_text(json.dumps(results, indent=1, default=str), encoding="utf-8")
356
+ (out / "report.md").write_text(report(results), encoding="utf-8")
357
+ return results
358
+
359
+
360
+ def report(r: dict) -> str:
361
+ systems = r["systems"]
362
+ cols = list(systems)
363
+ rows = [("interpretation accuracy (valid sentences)", "interpretation_accuracy"),
364
+ ("executed something not meant (silent error rate)", "silent_error_rate"),
365
+ ("precision when it executes", "precision_when_executed"),
366
+ ("nonsense / out-of-scope refused", "nonsense_caught"),
367
+ ("asked instead of executing", "asked"),
368
+ ("all paraphrases of an intent right", "paraphrase_consistency"),
369
+ ("calibration error of the weight (ECE, lower is better)", "calibration_ece"),
370
+ ("weight separates right/wrong (AUROC)", "calibration_auroc"),
371
+ ("median latency per sentence (ms)", "median_ms")]
372
+ L = [f"# NLCL benchmark report ({r['date']})", "",
373
+ "Held-out sentences only (never used for training). Correct = same resulting system state as the canonical "
374
+ "sentence. Pre-registered hypotheses: `bench/HYPOTHESES.md`.", ""]
375
+ for n in r.get("notes", []):
376
+ L.append(f"> **Note:** {n}")
377
+ L += ["", "## Fidelity", "", "| metric | " + " | ".join(cols) + " |", "|---|" + "---|" * len(cols)]
378
+ for label, key in rows:
379
+ L.append(f"| {label} | " + " | ".join(str(systems[c].get(key, "")) for c in cols) + " |")
380
+ if r.get("selective"):
381
+ L += ["", "## Risk / coverage of the trained weight", "",
382
+ "Executing only sentences whose weight reaches the threshold (the rest are asked about):", "",
383
+ "| weight threshold | share executed | precision of what is executed | wrong executions |",
384
+ "|---|---|---|---|"]
385
+ for s in r["selective"]:
386
+ L.append(f"| {s['threshold']} | {s['coverage']} | {s['precision']} | {s['wrong_executions']} |")
387
+ L += ["", "## Learning curve (no model retraining: rules, evidence and weights in Prolog)", "",
388
+ "| training paraphrases per intent | rules learned | accuracy | silent errors | nonsense refused | ECE |",
389
+ "|---|---|---|---|---|---|"]
390
+ for m in r["learning_curve"]:
391
+ L.append(f"| {m['paraphrases_per_intent']} | {m['rules_learned']} | {m['interpretation_accuracy']} | "
392
+ f"{m['silent_error_rate']} | {m['nonsense_caught']} | {m['calibration_ece']} |")
393
+ t = r["terminal"]
394
+ L += ["", "## Terminal", "", "| metric | " + " | ".join(t) + " |", "|---|" + "---|" * len(t)]
395
+ for key, label in (("effect_accuracy", "same file-system effect as the meant command"),
396
+ ("silent_error_rate", "executed with the wrong effect"),
397
+ ("commands_verified", "generated bash + PowerShell verified in a sandbox"),
398
+ ("unconfirmed_destructive_actions", "files changed/deleted without showing a diff first")):
399
+ L.append(f"| {label} | " + " | ".join(str(t[s].get(key, "n/a")) for s in t) + " |")
400
+ L += ["", "## Determinism", "", f"Identical interpretation on every repeated run: " +
401
+ ", ".join(f"{k}: {v}" for k, v in r["determinism"].items() if k != "runs"), "",
402
+ "## Cost", "", f"NLCL offline: {r['cost']['nlcl_tokens']} tokens, median {r['cost']['nlcl_median_ms']} ms per sentence.",
403
+ "", "## What the trained interpreter learned (Prolog facts)", "", "```prolog", r.get("learned_kb", "").strip(), "```", ""]
404
+ return "\n".join(L)
405
+
406
+
407
+ def main(argv=None) -> int:
408
+ for s in (sys.stdout, sys.stderr):
409
+ try:
410
+ s.reconfigure(encoding="utf-8")
411
+ except (AttributeError, ValueError):
412
+ pass
413
+ ap = argparse.ArgumentParser(prog="nlcl.bench")
414
+ ap.add_argument("--out", default=str(Path.cwd() / "bench" / "results"))
415
+ ap.add_argument("--backend", default="off", help="off | auto | groq | gemini | ... (for llm-direct and nlcl+teacher)")
416
+ ap.add_argument("--quick", action="store_true")
417
+ ap.add_argument("--sample", type=int, default=0, help="score language-model systems on N held-out sentences")
418
+ a = ap.parse_args(argv)
419
+ res = run_bench(Path(a.out), a.backend, a.quick, sample_n=a.sample)
420
+ print(f"\nreport: {Path(a.out) / 'report.md'}")
421
+ for name, m in res["systems"].items():
422
+ print(f" {name:16} accuracy {m['interpretation_accuracy']} silent errors {m['silent_error_rate']} "
423
+ f"nonsense refused {m['nonsense_caught']}")
424
+ return 0
425
+
426
+
427
+ if __name__ == "__main__":
428
+ sys.exit(main())
nlcl/composer.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Multi-module system composer.
2
+
3
+ Groups entities by domain, resolves every Link into a Channel with a concrete
4
+ protocol + configuration that BOTH sides agree on, then lets each domain
5
+ module generate its part. Writes system.json (IR), SYSTEM.md (architecture,
6
+ wiring and how to run everything with free tools).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from pathlib import Path
12
+
13
+ from . import modules as modreg
14
+ from .ir import SystemState, ident
15
+ from .modules.base import BuildContext, Channel, RunResult
16
+
17
+ # default protocol by (domain, domain) pair (order-insensitive)
18
+ DEFAULT_PROTOCOL = {
19
+ frozenset({"embedded", "python"}): "serial",
20
+ frozenset({"embedded"}): "serial",
21
+ frozenset({"embedded", "hardware"}): "spi",
22
+ frozenset({"hardware"}): "wire",
23
+ frozenset({"hardware", "python"}): "serial",
24
+ frozenset({"python", "3d"}): "http",
25
+ frozenset({"python", "game"}): "http",
26
+ frozenset({"python"}): "http",
27
+ frozenset({"python", "cpp"}): "http",
28
+ frozenset({"cpp", "embedded"}): "serial",
29
+ frozenset({"game", "3d"}): "http",
30
+ frozenset({"embedded", "3d"}): "http",
31
+ frozenset({"embedded", "game"}): "http",
32
+ }
33
+ NON_DATA_PROPS = {"pin", "pins", "position", "rotation", "scale", "size", "color", "subtype", "baud", "port",
34
+ "address", "width", "height", "depth", "radius", "length", "thickness", "board", "mass",
35
+ "model", "wifi_ssid", "wifi_password", "interval_ms", "clock_hz", "on_pin", "movable",
36
+ "collision", "gravity", "visible", "shape", "material", "texture", "units", "divide_by",
37
+ "stable_ms", "frequency_hz", "active_low", "for_entity", "states", "wall", "lid", "vents"}
38
+
39
+
40
+ def data_fields(state: SystemState, src) -> list[str]:
41
+ """Default fields of a link: real data props of the source (or of its child sensors when the
42
+ source is a board), never config, flags named after other things, or flattened references."""
43
+ names = {"esp32", "esp8266", "arduino", "uno", "nano", "mega", "pico", "pico_w", "stm32", "raspberry_pi",
44
+ "arduino_uno", "arduino_nano", "arduino_mega"}
45
+ for e in state.entities.values():
46
+ if e.id != src.id:
47
+ names |= {e.ident, ident(e.kind)}
48
+
49
+ def ok(k, v):
50
+ if k in NON_DATA_PROPS or k.startswith("_") or not isinstance(v, (int, float, bool)):
51
+ return False
52
+ if k in names or any(k.startswith(n + "_") for n in names if n):
53
+ return False # 'esp32': True, 'alu1_result', 'bob_lives'
54
+ return True
55
+ fields = [k for k, v in src.props.items() if ok(k, v)]
56
+ if not fields:
57
+ for c in state.children(src.id):
58
+ fields += [k for k, v in c.props.items() if ok(k, v) and k not in fields]
59
+ return fields
60
+
61
+
62
+ def resolve_channels(state: SystemState) -> list[Channel]:
63
+ chans = []
64
+ for l in state.links.values():
65
+ src, dst = state.entities.get(l.src), state.entities.get(l.dst)
66
+ if not src or not dst:
67
+ continue
68
+ proto = (l.via or DEFAULT_PROTOCOL.get(frozenset({src.domain, dst.domain})) or "http").lower()
69
+ if proto == "uart":
70
+ proto = "serial"
71
+ requested = None
72
+ if proto == "websocket":
73
+ # every module implements this as HTTP polling on the hub: say so in the contract
74
+ proto, requested = "http", "websocket"
75
+ fields = list(l.props.get("fields") or [])
76
+ if not fields:
77
+ fields = data_fields(state, src)
78
+ if not fields:
79
+ fields = ["value"]
80
+ cfg = {"interval_ms": int(l.props.get("interval_ms", 1000))}
81
+ if requested:
82
+ cfg["requested_protocol"] = requested
83
+ # field types + enum tables so both sides (and simulators) agree on the encoding
84
+ types, enums = {}, {}
85
+ for f in fields:
86
+ holder = src if f in src.props else next((c for c in state.children(src.id) if f in c.props), None)
87
+ v = holder.props.get(f) if holder else None
88
+ types[f] = ("bool" if isinstance(v, bool) else "int" if isinstance(v, int) else
89
+ "string" if isinstance(v, str) else "float")
90
+ if holder and f == "state" and isinstance(holder.props.get("states"), list):
91
+ enums[f] = [str(s) for s in holder.props["states"]]
92
+ types[f] = "enum"
93
+ cfg["types"] = types
94
+ if enums:
95
+ cfg["enums"] = enums
96
+ if proto == "serial":
97
+ cfg["baud"] = int(l.props.get("baud", 115200))
98
+ cfg["port"] = l.props.get("port_name", "auto")
99
+ elif proto in ("http", "websocket"):
100
+ cfg["hub_url"] = f"http://localhost:{int(l.props.get('port', 8765))}"
101
+ cfg["path"] = f"/channel/{l.id}"
102
+ elif proto == "mqtt":
103
+ cfg["broker"] = l.props.get("broker", "broker.hivemq.com")
104
+ cfg["broker_port"] = int(l.props.get("broker_port", 1883))
105
+ cfg["topic"] = l.props.get("topic", f"nlcl/{ident(state.name)}/{l.id}")
106
+ elif proto == "udp":
107
+ cfg["port"] = int(l.props.get("port", 9876))
108
+ elif proto in ("spi", "i2c", "gpio", "wire"):
109
+ cfg["bus"] = proto
110
+ if proto == "i2c":
111
+ cfg["address"] = l.props.get("address", "0x42")
112
+ chans.append(Channel(l.id, proto, src, dst, fields, cfg))
113
+ return chans
114
+
115
+
116
+ def needs_hub(chans: list[Channel]) -> bool:
117
+ return any(c.protocol in ("http", "websocket") for c in chans) or \
118
+ any(c.protocol == "serial" and "python" not in (c.src.domain, c.dst.domain) for c in chans)
119
+
120
+
121
+ class Composer:
122
+ def __init__(self, state: SystemState, outdir: Path, llm=None):
123
+ self.state = state
124
+ self.outdir = Path(outdir)
125
+ self.llm = llm
126
+ self.modules = modreg.load_modules()
127
+
128
+ def contexts(self) -> list[BuildContext]:
129
+ chans = resolve_channels(self.state)
130
+ ctxs = []
131
+ for dom in self.state.domains():
132
+ ents = self.state.in_domain(dom)
133
+ mine = [c for c in chans if dom in (c.src.domain, c.dst.domain)]
134
+ ctxs.append(BuildContext(self.state, dom, ents, mine, self.outdir / dom,
135
+ project=ident(self.state.name) or "project", llm=self.llm))
136
+ # cross-domain http links need the python hub even if there are no python entities
137
+ if needs_hub(chans) and "python" not in self.state.domains():
138
+ ctxs.append(BuildContext(self.state, "python", [], [c for c in chans if c.protocol in ("http", "websocket", "serial")],
139
+ self.outdir / "python", project=ident(self.state.name) or "project", llm=self.llm))
140
+ return ctxs
141
+
142
+ def build(self) -> tuple[dict[str, list[str]], list[str]]:
143
+ """Generate everything. Returns ({domain: [files]}, warnings)."""
144
+ written: dict[str, list[str]] = {}
145
+ warnings: list[str] = []
146
+ self.outdir.mkdir(parents=True, exist_ok=True)
147
+ ctxs = self.contexts()
148
+ for ctx in ctxs:
149
+ mod = modreg.get(ctx.domain)
150
+ if not mod:
151
+ warnings.append(f"no module for domain '{ctx.domain}'")
152
+ continue
153
+ ctx.outdir.mkdir(parents=True, exist_ok=True)
154
+ try:
155
+ files = mod.generate(ctx)
156
+ except Exception as e: # report, keep building other domains
157
+ import traceback
158
+ warnings.append(f"{ctx.domain}: generator failed: {e}\n{traceback.format_exc(limit=3)}")
159
+ continue
160
+ for rel, content in files.items():
161
+ p = ctx.outdir / rel
162
+ p.parent.mkdir(parents=True, exist_ok=True)
163
+ p.write_text(content, encoding="utf-8", newline="\n")
164
+ written.setdefault(ctx.domain, []).append(str(p.relative_to(self.outdir)))
165
+ for e in ctx.entities:
166
+ warnings += [f"{e.name}: {w}" for w in mod.validate(e)]
167
+ self._cleanup(written, warnings)
168
+ warnings += self._reapply_patches()
169
+ chans = resolve_channels(self.state)
170
+ (self.outdir / "system.json").write_text(json.dumps({
171
+ "ir": self.state.to_dict(),
172
+ "channels": [c.to_dict() for c in chans],
173
+ }, ensure_ascii=False, indent=2), encoding="utf-8")
174
+ (self.outdir / "SYSTEM.md").write_text(self.report(chans, written), encoding="utf-8")
175
+ return written, warnings
176
+
177
+ def _reapply_patches(self) -> list[str]:
178
+ """Bug fixes made to generated files (state.patches) survive a rebuild when they still apply."""
179
+ notes, kept = [], 0
180
+ for pt in getattr(self.state, "patches", []):
181
+ p = (self.outdir / pt["file"]).resolve()
182
+ if self.outdir.resolve() not in p.parents or not p.is_file():
183
+ continue
184
+ txt = p.read_text(encoding="utf-8", errors="replace")
185
+ if pt["replace"] in txt and pt["search"] not in txt:
186
+ kept += 1
187
+ elif pt["search"] in txt:
188
+ p.write_text(txt.replace(pt["search"], pt["replace"], 1), encoding="utf-8", newline="")
189
+ kept += 1
190
+ else:
191
+ notes.append(f"an earlier fix in {pt['file']} no longer applies to the regenerated code")
192
+ if kept:
193
+ notes.append(f"re-applied {kept} earlier fix(es) to the generated code")
194
+ return notes
195
+
196
+ MANIFEST = ".nlcl_manifest.json"
197
+
198
+ def _cleanup(self, written: dict[str, list[str]], warnings: list[str]) -> None:
199
+ """Delete files that a previous build generated but this build no longer does.
200
+ Only files listed in the previous manifest are touched (never user files)."""
201
+ mpath = self.outdir / self.MANIFEST
202
+ now = sorted(f.replace("\\", "/") for fs in written.values() for f in fs)
203
+ try:
204
+ before = json.loads(mpath.read_text(encoding="utf-8")).get("files", [])
205
+ except (OSError, ValueError):
206
+ before = []
207
+ removed = 0
208
+ for f in set(before) - set(now):
209
+ p = (self.outdir / f).resolve()
210
+ if self.outdir.resolve() in p.parents and p.is_file():
211
+ p.unlink()
212
+ removed += 1
213
+ try:
214
+ p.parent.rmdir() # only if now empty
215
+ except OSError:
216
+ pass
217
+ if removed:
218
+ warnings.append(f"removed {removed} stale file(s) from the previous build")
219
+ mpath.write_text(json.dumps({"files": now}, indent=1), encoding="utf-8")
220
+
221
+ def run(self, domain: str | None = None) -> list[tuple[str, RunResult]]:
222
+ results = []
223
+ for ctx in self.contexts():
224
+ if domain and ctx.domain != domain:
225
+ continue
226
+ mod = modreg.get(ctx.domain)
227
+ if not mod:
228
+ continue
229
+ r = mod.run(ctx)
230
+ if r is not None:
231
+ results.append((ctx.domain, r))
232
+ return results
233
+
234
+ # -------------------------------------------------------------- report
235
+ def report(self, chans: list[Channel], written: dict[str, list[str]]) -> str:
236
+ st = self.state
237
+ L = [f"# System: {st.name}", "",
238
+ "Generated by NLCL (Natural Language Computational Language).", "",
239
+ "## Architecture", "", "```mermaid", "flowchart LR"]
240
+ for dom in st.domains():
241
+ L.append(f" subgraph {ident(dom)}[{dom}]")
242
+ for e in st.in_domain(dom):
243
+ L.append(f" {e.ident}[\"{e.name}<br/><i>{e.kind}</i>\"]")
244
+ L.append(" end")
245
+ for e in st.entities.values():
246
+ if e.parent in st.entities:
247
+ L.append(f" {st.entities[e.parent].ident} -.contains.- {e.ident}")
248
+ for c in chans:
249
+ L.append(f" {c.src.ident} -->|{c.protocol}: {', '.join(c.fields)}| {c.dst.ident}")
250
+ L += ["```", "", "## Entities", ""]
251
+ L.append("```")
252
+ L.append(st.summary())
253
+ L.append("```")
254
+ if chans:
255
+ L += ["", "## Channels (cross-module contracts)", "",
256
+ "| id | protocol | from | to | fields | config |", "|---|---|---|---|---|---|"]
257
+ for c in chans:
258
+ L.append(f"| {c.id} | {c.protocol} | {c.src.name} ({c.src.domain}) | {c.dst.name} ({c.dst.domain}) "
259
+ f"| {', '.join(c.fields)} | {json.dumps(c.config)} |")
260
+ L += ["", "Every message is a flat JSON object: `{\"channel\": id, \"from\": src, <field>: value, ...}` "
261
+ "terminated by a newline on stream transports (serial/udp)."]
262
+ L += ["", "## Generated files and free toolchains", ""]
263
+ for dom, files in written.items():
264
+ mod = modreg.get(dom)
265
+ L.append(f"### {dom} — {mod.title if mod else ''}")
266
+ for f in files:
267
+ L.append(f"- `{f}`")
268
+ if mod and mod.toolchain:
269
+ L += ["", mod.toolchain.strip(), ""]
270
+ return "\n".join(L) + "\n"
nlcl/discover.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Self-structuring: what the interpreter does when a word or a whole module does not exist yet.
2
+
3
+ 1. Unknown verb / word -> close forms in the KB vocabulary (typos, inflections) are tried; a candidate
4
+ is accepted only if it makes the sentence interpretable with a high weight.
5
+ 2. Online teacher -> if an LLM backend exists, its interpretation of the sentence is used as gold
6
+ and *distilled* into a rewrite rule in the Prolog KB, so the next time the
7
+ same kind of sentence is understood offline, deterministically, for free.
8
+ 3. Unknown module -> a language / platform the KB knows (language/3) but no module implements is
9
+ grown into a new domain module at run time, registered, and remembered
10
+ (learned_module/3). Its code is written by the online agent and checked by the
11
+ bug-fix diagnostics; offline it produces a precise spec instead.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import re
18
+ from pathlib import Path
19
+
20
+ from . import modules as modreg
21
+ from .ir import Entity
22
+ from .modules.base import BuildContext, DomainModule, RunResult
23
+
24
+ VERB_WORDS_CACHE: list[str] | None = None
25
+
26
+
27
+ def _dl(a: str, b: str) -> int:
28
+ """Damerau-Levenshtein distance (optimal string alignment)."""
29
+ d = [[0] * (len(b) + 1) for _ in range(len(a) + 1)]
30
+ for i in range(len(a) + 1):
31
+ d[i][0] = i
32
+ for j in range(len(b) + 1):
33
+ d[0][j] = j
34
+ for i in range(1, len(a) + 1):
35
+ for j in range(1, len(b) + 1):
36
+ c = 0 if a[i - 1] == b[j - 1] else 1
37
+ d[i][j] = min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c)
38
+ if i > 1 and j > 1 and a[i - 1] == b[j - 2] and a[i - 2] == b[j - 1]:
39
+ d[i][j] = min(d[i][j], d[i - 2][j - 2] + 1)
40
+ return d[-1][-1]
41
+
42
+
43
+ def _vocabulary(kb) -> list[str]:
44
+ words = {r["W"] for r in kb.query("atomic(W, _)", limit=5000)}
45
+ words |= {r["K"] for r in kb.query("kind_of(K, _, _)", limit=5000)}
46
+ return sorted(w for w in words if isinstance(w, str) and len(w) >= 3)
47
+
48
+
49
+ def word_candidates(word: str, kb) -> list[str]:
50
+ """Known words this unknown word may stand for: inflections first, then typos."""
51
+ w = word.lower()
52
+ vocab = _vocabulary(kb)
53
+ out = []
54
+ for suf, rep in (("ing", ""), ("ing", "e"), ("ed", ""), ("ed", "e"), ("es", ""), ("s", ""), ("ies", "y")):
55
+ if w.endswith(suf) and len(w) > len(suf) + 2:
56
+ base = w[: -len(suf)] + rep
57
+ if base in vocab and base not in out:
58
+ out.append(base)
59
+ if len(w) >= 4:
60
+ limit = 1 if len(w) < 7 else 2
61
+ near = sorted((_dl(w, v), v) for v in vocab if abs(len(v) - len(w)) <= limit and v != w)
62
+ out += [v for dist, v in near if dist <= limit and v not in out][:3]
63
+ return out
64
+
65
+
66
+ def repair_sentence(session, text: str, min_weight: float | None = None) -> tuple[str, str, str, float] | None:
67
+ """Try replacing one unknown word by a close known word. -> (new text, old, new, weight) or None."""
68
+ min_weight = session.execute_at if min_weight is None else min_weight
69
+ base = session.interpret(text)[0].score
70
+ known = set(_vocabulary(session.kb))
71
+ best = None
72
+ for m in re.finditer(r"[A-Za-z][A-Za-z\-]{2,}", text):
73
+ w = m.group(0)
74
+ if w.lower() in known or session.vocab.atomic(w.lower()):
75
+ continue
76
+ for cand in word_candidates(w, session.kb):
77
+ new = text[:m.start()] + cand + text[m.end():]
78
+ sc = session.interpret(new)[0].score
79
+ if sc >= min_weight and sc > base + 0.15 and (best is None or sc > best[3]):
80
+ best = (new, w.lower(), cand, sc)
81
+ return best
82
+
83
+
84
+ def distill(session, text: str, gold_ops: list, max_trials: int = 2500) -> tuple[list[str], list[str]] | None:
85
+ """Find a rewrite rule (phrase -> known word or nothing) that makes the offline interpreter produce
86
+ the same state as the teacher's interpretation. Stores nothing; the caller decides."""
87
+ from .learn import signature
88
+ from .interpreter import Interpreter
89
+ clone = session.state.clone()
90
+ Interpreter(clone).apply_all(list(gold_ops))
91
+ shell = [op.props for op in gold_ops if op.action == "SHELL"]
92
+ gold_sig = signature(clone, shell)
93
+ words = re.findall(r"[A-Za-z][\w'\-]*", text.lower())
94
+ verbs = sorted({r["W"] for r in session.kb.query("atomic(W, T)", limit=5000)
95
+ if r["T"] in ("CREATE", "DELETE", "SET", "CONNECT", "MOVE", "RENAME", "SHOW")})
96
+ targets = [""] + verbs
97
+ grams = []
98
+ for n in (1, 2, 3):
99
+ for i in range(len(words) - n + 1):
100
+ grams.append(words[i:i + n])
101
+ base = list(session.rules.rewrites)
102
+ tried = 0
103
+ for g in grams:
104
+ if all(session.vocab.atomic(w) for w in g):
105
+ continue
106
+ for t in targets:
107
+ tried += 1
108
+ if tried > max_trials:
109
+ return None
110
+ session.rules.rewrites = sorted(base + [(g, [t] if t else [], 1)], key=lambda r: -len(r[0]))
111
+ try:
112
+ c = session.interpret(text)[0]
113
+ if c.ops:
114
+ st = session.state.clone()
115
+ sh = []
116
+ if c.source == "shell":
117
+ sh = [c.ops[0].props]
118
+ else:
119
+ Interpreter(st).apply_all(c.ops)
120
+ if signature(st, sh) == gold_sig:
121
+ return g, ([t] if t else [])
122
+ finally:
123
+ session.rules.rewrites = base
124
+ return None
125
+
126
+
127
+ # ======================================================================= module discovery
128
+ GENERIC_KINDS = {"object": {}, "program": {}, "app": {}, "service": {}, "library": {}, "script": {}, "cli": {},
129
+ "tool": {}, "class": {}, "function": {}, "module": {}, "server": {"port": 8080}, "game": {},
130
+ "calculator": {}, "counter": {"count": 0}}
131
+
132
+
133
+ class GeneratedModule(DomainModule):
134
+ """A domain the system grew by itself for a language it has no hand-written module for."""
135
+
136
+ def __init__(self, language: str, ext: str, run_hint: str, home: Path | None = None):
137
+ self.name = language
138
+ self.language = language
139
+ self.ext = ext
140
+ self.run_hint = run_hint
141
+ self.home = home
142
+ self.title = f"{language} (discovered module: code written by the online agent, checked by diagnostics)"
143
+ self.aliases = (language,)
144
+ self.keywords = (language,)
145
+ self.kinds = dict(GENERIC_KINDS)
146
+ self.suggested_props = ("purpose", "inputs", "outputs")
147
+ self.protocols = ("http",)
148
+ self.toolchain = f"Run with: `{run_hint}`"
149
+
150
+ def spec(self, ctx: BuildContext) -> dict:
151
+ return {"language": self.language, "project": ctx.project,
152
+ "entities": [{"name": e.name, "kind": e.kind, "props": e.props, "behaviors": e.behaviors,
153
+ "parent": next((x.name for x in ctx.entities if x.id == e.parent), None)}
154
+ for e in ctx.entities],
155
+ "channels": [c.to_dict() for c in ctx.channels]}
156
+
157
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
158
+ spec = self.spec(ctx)
159
+ blob = json.dumps(spec, sort_keys=True, ensure_ascii=False)
160
+ key = hashlib.sha1(blob.encode()).hexdigest()[:16]
161
+ files = {"spec.json": json.dumps(spec, indent=2, ensure_ascii=False)}
162
+ cache = (self.home / "modules" / self.name / f"{key}.json") if self.home else None
163
+ if cache and cache.exists(): # deterministic: same IR -> same code
164
+ files.update(json.loads(cache.read_text(encoding="utf-8")))
165
+ return files
166
+ llm = ctx.llm
167
+ if llm is None or not hasattr(llm, "backend"):
168
+ files["README.md"] = (f"# {ctx.project} ({self.language})\n\nNLCL discovered the `{self.language}` module, "
169
+ "but writing code in it needs the online agent (set a free API key, see "
170
+ "`:backend status`) and then `build it` again.\n\nThe exact specification "
171
+ "the agent will implement is in `spec.json`.\n")
172
+ return files
173
+ from .llm import extract_json
174
+ prompt = [{"role": "system", "content":
175
+ f"You write complete, runnable {self.language} programs from a JSON specification produced by "
176
+ "a natural-language programming system. Every entity is a part of the program; its props are "
177
+ "its data; its behaviors are event rules (on: start|update|timer:<ms>|input:<key>|change:<prop>"
178
+ "|message:<src>|collision, if: condition, do: actions). Reply with ONLY JSON: "
179
+ '{"files": {"<relative path>": "<full file content>"}}. Include a README.md with the run '
180
+ f"command ({self.run_hint}). No placeholders, no TODOs."},
181
+ {"role": "user", "content": blob}]
182
+ try:
183
+ data = extract_json(llm.backend.chat(prompt))
184
+ gen = {str(k): str(v) for k, v in (data.get("files") or {}).items()}
185
+ except Exception as e:
186
+ files["README.md"] = f"# {ctx.project}\n\nThe online agent failed to write the code: {e}\n"
187
+ return files
188
+ files.update(gen)
189
+ if cache:
190
+ cache.parent.mkdir(parents=True, exist_ok=True)
191
+ cache.write_text(json.dumps(gen, ensure_ascii=False), encoding="utf-8")
192
+ return files
193
+
194
+ def run(self, ctx: BuildContext) -> RunResult | None:
195
+ from .fixer import diagnose
196
+ diags = diagnose(ctx.outdir)
197
+ return RunResult(not diags, "diagnostics: " + ("no problems" if not diags else "; ".join(map(str, diags[:5]))),
198
+ "nlcl check")
199
+
200
+
201
+ def register(kb, home: Path | None, name: str) -> DomainModule | None:
202
+ """Grow a module for a language listed in the KB and remember it."""
203
+ lang = kb.language(name)
204
+ if not lang:
205
+ return None
206
+ reg = modreg.load_modules()
207
+ if name in reg:
208
+ return reg[name]
209
+ ext, hint = lang
210
+ m = GeneratedModule(name, ext, hint, home)
211
+ reg[name] = m
212
+ kb.add_learned_module(name, name, ext)
213
+ kb.load_modules(reg)
214
+ kb.save()
215
+ return m
216
+
217
+
218
+ def restore(kb, home: Path | None) -> list[str]:
219
+ """Re-register modules discovered in earlier sessions."""
220
+ out = []
221
+ reg = modreg.load_modules()
222
+ for name, lang, ext in kb.learned_modules():
223
+ if name not in reg:
224
+ hint = (kb.language(lang) or (ext, ""))[1]
225
+ reg[name] = GeneratedModule(name, ext, hint, home)
226
+ out.append(name)
227
+ if out:
228
+ kb.load_modules(reg)
229
+ return out
230
+
231
+
232
+ PROGRAM_NOUNS = r"(?:program|app|application|service|script|cli|tool|library|code|module|project|server|class|function|game|calculator|counter|object)"
233
+
234
+
235
+ def languages_in(text: str, kb) -> list[str]:
236
+ """Languages the sentence clearly asks for ("a rust program", "in kotlin", "use dart") with no module yet."""
237
+ known = set(kb.languages())
238
+ reg = modreg.load_modules()
239
+ low = text.lower()
240
+ out = []
241
+ for lang in sorted(known, key=len, reverse=True):
242
+ if lang in reg or modreg.get(lang):
243
+ continue
244
+ l = re.escape(lang)
245
+ if re.search(rf"\b(?:in|use|using|with|written\s+in)\s+{l}\b", low) or \
246
+ re.search(rf"\b{l}\s+{PROGRAM_NOUNS}s?\b", low):
247
+ out.append(lang)
248
+ return out
nlcl/fixer.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Smart bug fixing for any module and any existing code.
2
+
3
+ diagnose -> real tools per file type (offline): Python compile, node --check (JS / HTML scripts),
4
+ JSON parse, C/C++ (g++/clang++), Verilog (iverilog/verilator), Arduino (arduino-cli),
5
+ OpenSCAD, GDScript (godot), C# (dotnet), plus bracket balance for every C-like file.
6
+ fix -> online agent loop: code + diagnostics + the user's description go to the LLM, which
7
+ returns search/replace edits; edits are applied with a backup, the code is re-checked,
8
+ and a round that makes things worse is rolled back. Works on files the user wrote
9
+ earlier as well as on generated output.
10
+
11
+ Without an LLM backend only ``diagnose`` is available (problems are located and reported, not fixed).
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import difflib
16
+ import json
17
+ import re
18
+ import shutil
19
+ import subprocess
20
+ import sys
21
+ import tempfile
22
+ import time
23
+ from dataclasses import dataclass, field
24
+ from pathlib import Path
25
+
26
+ SOURCE_EXT = {".py", ".js", ".mjs", ".ts", ".html", ".htm", ".css", ".json", ".c", ".h", ".cpp", ".hpp", ".cc",
27
+ ".ino", ".cs", ".gd", ".v", ".sv", ".scad", ".java", ".kt", ".swift", ".go", ".rs", ".sh", ".ps1",
28
+ ".bat", ".toml", ".ini", ".yml", ".yaml", ".md", ".txt", ".nl", ".tscn", ".godot", ".cmake"}
29
+ CODE_EXT = SOURCE_EXT - {".md", ".txt"}
30
+ SKIP_DIRS = {".git", "__pycache__", "node_modules", ".nlcl_backup", ".venv", "venv", "dist", "build_out", ".pio"}
31
+ MAX_FILE = 60_000 # bytes sent per file
32
+ MAX_TOTAL = 160_000 # bytes sent per round
33
+
34
+
35
+ @dataclass
36
+ class Diag:
37
+ file: str
38
+ line: int | None
39
+ message: str
40
+ tool: str
41
+ severity: str = "error"
42
+
43
+ def __str__(self):
44
+ loc = f"{self.file}:{self.line}" if self.line else self.file
45
+ return f"{loc}: {self.severity}: {self.message} [{self.tool}]"
46
+
47
+
48
+ @dataclass
49
+ class FixReport:
50
+ ok: bool
51
+ summary: str
52
+ before: list[Diag] = field(default_factory=list)
53
+ after: list[Diag] = field(default_factory=list)
54
+ changed: dict[str, str] = field(default_factory=dict) # rel path -> unified diff
55
+ edits: list[dict] = field(default_factory=list) # applied {file, search, replace}
56
+ backup: str | None = None
57
+ notes: list[str] = field(default_factory=list)
58
+ pending: dict = field(default_factory=dict) # real path -> (new text, crlf) waiting for confirmation
59
+ root: str | None = None
60
+
61
+ def lines(self) -> list[str]:
62
+ out = [f" {self.summary}"]
63
+ out += [f" note: {n}" for n in self.notes]
64
+ if self.before:
65
+ out.append(f" problems found: {len(self.before)}")
66
+ out += [f" {d}" for d in self.before[:12]]
67
+ for f, d in self.changed.items():
68
+ out.append(f" --- fixed {f}")
69
+ out += [" " + ln for ln in d.splitlines()[2:42]]
70
+ if self.changed:
71
+ out.append(f" remaining problems: {len(self.after)}")
72
+ out += [f" {d}" for d in self.after[:12]]
73
+ if self.backup:
74
+ out.append(f" originals saved in {self.backup} (':fix undo' restores them)")
75
+ if self.pending:
76
+ out.append(f" nothing has been written yet: {len(self.pending)} file(s) waiting for your confirmation")
77
+ return out
78
+
79
+
80
+ # --------------------------------------------------------------------------
81
+ # diagnostics
82
+ # --------------------------------------------------------------------------
83
+
84
+ def _run(cmd: list[str], cwd: Path | None = None, timeout: int = 40) -> tuple[int, str]:
85
+ try:
86
+ p = subprocess.run(cmd, cwd=str(cwd) if cwd else None, capture_output=True, text=True,
87
+ timeout=timeout, encoding="utf-8", errors="replace")
88
+ return p.returncode, (p.stdout + "\n" + p.stderr).strip()
89
+ except subprocess.TimeoutExpired:
90
+ return 124, f"timed out after {timeout}s"
91
+ except OSError as e:
92
+ return 127, str(e)
93
+
94
+
95
+ def _tool(*names: str) -> str | None:
96
+ for n in names:
97
+ p = shutil.which(n)
98
+ if p:
99
+ return p
100
+ return None
101
+
102
+
103
+ def _line_of(text: str, pat: str = r"(?:line |:)(\d+)") -> int | None:
104
+ m = re.search(pat, text)
105
+ return int(m.group(1)) if m else None
106
+
107
+
108
+ def check_python(path: Path, rel: str) -> list[Diag]:
109
+ src = path.read_text(encoding="utf-8", errors="replace")
110
+ try:
111
+ compile(src, str(path), "exec")
112
+ except SyntaxError as e:
113
+ return [Diag(rel, e.lineno, f"{e.msg}: {(e.text or '').strip()}", "python")]
114
+ except ValueError as e:
115
+ return [Diag(rel, None, str(e), "python")]
116
+ return []
117
+
118
+
119
+ def _node_check(code: str, rel: str, module: bool, offset: int = 0, tool: str = "node") -> list[Diag]:
120
+ node = _tool("node")
121
+ if not node:
122
+ return []
123
+ with tempfile.TemporaryDirectory() as td:
124
+ f = Path(td) / ("x.mjs" if module else "x.cjs")
125
+ f.write_text(code, encoding="utf-8")
126
+ rc, out = _run([node, "--check", str(f)])
127
+ if rc == 0:
128
+ return []
129
+ m = re.search(r":(\d+)\s*\n", out)
130
+ line = int(m.group(1)) + offset if m else None
131
+ msg = next((ln for ln in out.splitlines() if "Error" in ln), out.splitlines()[-1] if out else "syntax error")
132
+ return [Diag(rel, line, msg.strip(), tool)]
133
+
134
+
135
+ def check_js(path: Path, rel: str) -> list[Diag]:
136
+ src = path.read_text(encoding="utf-8", errors="replace")
137
+ module = path.suffix == ".mjs" or bool(re.search(r"^\s*(import|export)\s", src, re.M))
138
+ return _node_check(src, rel, module)
139
+
140
+
141
+ def check_html(path: Path, rel: str) -> list[Diag]:
142
+ src = path.read_text(encoding="utf-8", errors="replace")
143
+ out: list[Diag] = []
144
+ for m in re.finditer(r"<script\b([^>]*)>(.*?)</script>", src, re.S | re.I):
145
+ attrs, code = m.group(1), m.group(2)
146
+ if "src=" in attrs or re.search(r"type\s*=\s*[\"'](?:application/json|importmap|text/template)", attrs, re.I):
147
+ continue
148
+ if not code.strip():
149
+ continue
150
+ offset = src[:m.start(2)].count("\n")
151
+ out += _node_check(code, rel, "module" in attrs, offset, "node(html)")
152
+ if src.lower().count("<script") != src.lower().count("</script>"):
153
+ out.append(Diag(rel, None, "unbalanced <script> tags", "html"))
154
+ return out
155
+
156
+
157
+ def check_json(path: Path, rel: str) -> list[Diag]:
158
+ try:
159
+ json.loads(path.read_text(encoding="utf-8-sig", errors="replace"))
160
+ except ValueError as e:
161
+ return [Diag(rel, getattr(e, "lineno", None), str(e), "json")]
162
+ return []
163
+
164
+
165
+ def check_c(path: Path, rel: str) -> list[Diag]:
166
+ cc = _tool("g++", "clang++")
167
+ if not cc or path.suffix == ".ino":
168
+ return check_brackets(path, rel)
169
+ inc = [f"-I{p}" for p in {path.parent, path.parent.parent / "include", path.parent / "include"} if p.exists()]
170
+ rc, out = _run([cc, "-std=c++17", "-fsyntax-only", *inc, str(path)])
171
+ diags = []
172
+ for ln in out.splitlines():
173
+ m = re.match(r"(.+?):(\d+):(?:\d+:)?\s*(error|warning):\s*(.+)", ln)
174
+ if m and m.group(3) == "error":
175
+ diags.append(Diag(rel, int(m.group(2)), m.group(4), Path(cc).stem))
176
+ return diags or ([Diag(rel, None, out[:300], Path(cc).stem)] if rc not in (0,) and out else [])
177
+
178
+
179
+ def check_verilog(path: Path, rel: str) -> list[Diag]:
180
+ iv, vl = _tool("iverilog"), _tool("verilator")
181
+ out_d: list[Diag] = []
182
+ if iv:
183
+ rc, out = _run([iv, "-g2005", "-t", "null", "-y", str(path.parent), str(path)])
184
+ for ln in out.splitlines():
185
+ m = re.match(r"(.+?):(\d+):\s*(.*error.*|syntax error.*)", ln)
186
+ if m:
187
+ out_d.append(Diag(rel, int(m.group(2)), m.group(3), "iverilog"))
188
+ elif vl:
189
+ rc, out = _run([vl, "--lint-only", "-Wno-fatal", f"-y", str(path.parent), str(path)])
190
+ for ln in out.splitlines():
191
+ m = re.match(r"%Error[^:]*:\s*(.+?):(\d+):(?:\d+:)?\s*(.+)", ln)
192
+ if m:
193
+ out_d.append(Diag(rel, int(m.group(2)), m.group(3), "verilator"))
194
+ else:
195
+ out_d += check_brackets(path, rel)
196
+ src = _strip_comments(path.read_text(encoding="utf-8", errors="replace"), "//")
197
+ for a, b in (("module", "endmodule"), ("begin", "end"), ("case", "endcase"), ("function", "endfunction")):
198
+ na = len(re.findall(rf"\b{a}\b", src)) if a != "case" else len(re.findall(r"\bcase[xz]?\b", src))
199
+ nb = len(re.findall(rf"\b{b}\b", src))
200
+ if a == "begin":
201
+ nb = len(re.findall(r"\bend\b", src))
202
+ if na != nb:
203
+ out_d.append(Diag(rel, None, f"{na} '{a}' but {nb} '{b}'", "structure"))
204
+ return out_d
205
+
206
+
207
+ def check_scad(path: Path, rel: str) -> list[Diag]:
208
+ tool = _tool("openscad")
209
+ if tool:
210
+ with tempfile.TemporaryDirectory() as td:
211
+ rc, out = _run([tool, "-o", str(Path(td) / "o.echo"), str(path)], timeout=60)
212
+ if rc != 0:
213
+ return [Diag(rel, _line_of(out), out.splitlines()[0][:300] if out else "error", "openscad")]
214
+ return []
215
+ return check_brackets(path, rel)
216
+
217
+
218
+ def check_gd(path: Path, rel: str) -> list[Diag]:
219
+ tool = _tool("godot", "godot4")
220
+ if not tool:
221
+ return []
222
+ rc, out = _run([tool, "--headless", "--check-only", "--script", str(path)], timeout=60)
223
+ return [Diag(rel, _line_of(out), ln.strip(), "godot") for ln in out.splitlines() if "ERROR" in ln][:5]
224
+
225
+
226
+ def _strip_comments(src: str, line_comment: str) -> str:
227
+ # one left-to-right pass so that '"' (a char literal) or "//" inside a string cannot confuse it
228
+ pat = re.compile(r"/\*.*?\*/|" + re.escape(line_comment) + r"[^\n]*|\"(?:\\.|[^\"\\\n])*\"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`", re.S)
229
+ return pat.sub(lambda m: "\n" * m.group(0).count("\n"), src)
230
+
231
+
232
+ def check_brackets(path: Path, rel: str) -> list[Diag]:
233
+ """Language-independent structural check for C-like sources."""
234
+ src = _strip_comments(path.read_text(encoding="utf-8", errors="replace"), "//")
235
+ stack: list[tuple[str, int]] = []
236
+ pairs = {")": "(", "]": "[", "}": "{"}
237
+ line = 1
238
+ for ch in src:
239
+ if ch == "\n":
240
+ line += 1
241
+ elif ch in "([{":
242
+ stack.append((ch, line))
243
+ elif ch in ")]}":
244
+ if not stack or stack[-1][0] != pairs[ch]:
245
+ return [Diag(rel, line, f"unexpected '{ch}'", "brackets")]
246
+ stack.pop()
247
+ if stack:
248
+ return [Diag(rel, stack[-1][1], f"'{stack[-1][0]}' is never closed", "brackets")]
249
+ return []
250
+
251
+
252
+ CHECKERS = {
253
+ ".py": check_python, ".js": check_js, ".mjs": check_js, ".html": check_html, ".htm": check_html,
254
+ ".json": check_json, ".c": check_c, ".h": check_c, ".cpp": check_c, ".hpp": check_c, ".cc": check_c,
255
+ ".ino": check_brackets, ".cs": check_brackets, ".java": check_brackets, ".v": check_verilog,
256
+ ".sv": check_verilog, ".scad": check_scad, ".gd": check_gd, ".go": check_brackets, ".rs": check_brackets,
257
+ ".kt": check_brackets, ".swift": check_brackets, ".ts": check_brackets, ".css": check_brackets,
258
+ }
259
+
260
+
261
+ def collect(target: Path) -> tuple[Path, list[Path]]:
262
+ """(root, source files) for a file or directory target."""
263
+ target = target.resolve()
264
+ if target.is_file():
265
+ return target.parent, [target]
266
+ files = []
267
+ for p in sorted(target.rglob("*")):
268
+ if p.is_file() and p.suffix.lower() in SOURCE_EXT and not (set(p.relative_to(target).parts) & SKIP_DIRS) \
269
+ and not p.name.startswith(".nlcl_"):
270
+ files.append(p)
271
+ return target, files
272
+
273
+
274
+ def diagnose(target: Path, run_cmd: list[str] | None = None) -> list[Diag]:
275
+ root, files = collect(Path(target))
276
+ diags: list[Diag] = []
277
+ for f in files:
278
+ chk = CHECKERS.get(f.suffix.lower())
279
+ if not chk:
280
+ continue
281
+ rel = str(f.relative_to(root)).replace("\\", "/")
282
+ try:
283
+ diags += chk(f, rel)
284
+ except Exception as e: # a checker must never stop the fixer
285
+ diags.append(Diag(rel, None, f"checker failed: {e}", "nlcl", "warning"))
286
+ if run_cmd:
287
+ rc, out = _run(run_cmd, cwd=root, timeout=30)
288
+ if rc not in (0, 124):
289
+ tail = "\n".join(out.splitlines()[-25:])
290
+ m = re.findall(r'File "([^"]+)", line (\d+)', out)
291
+ f, ln = (m[-1] if m else ("(run)", None))
292
+ try:
293
+ f = str(Path(f).resolve().relative_to(root)).replace("\\", "/")
294
+ except (ValueError, OSError):
295
+ pass
296
+ diags.append(Diag(f, int(ln) if ln else None, "runtime failure:\n" + tail, "run"))
297
+ return diags
298
+
299
+
300
+ # --------------------------------------------------------------------------
301
+ # online fix loop
302
+ # --------------------------------------------------------------------------
303
+
304
+ FIX_PROMPT = """You are the debugging agent of NLCL. You fix bugs in source code of any language
305
+ (Python, JavaScript/HTML, C/C++, Arduino, C#, GDScript, Verilog, OpenSCAD, ...).
306
+ You receive: the user's description of the bug (may be empty), tool diagnostics, and the files.
307
+ Reply with ONLY a JSON object:
308
+ {"analysis": "<one or two sentences: the root cause>",
309
+ "edits": [{"file": "<relative path exactly as given>", "search": "<exact text copied from the file>", "replace": "<new text>"}],
310
+ "done": true|false}
311
+ Rules:
312
+ - "search" must be copied EXACTLY from the current file content (whitespace included), long enough to be unique
313
+ (a few full lines), and as small as possible. Never rewrite a whole file.
314
+ - Fix the root cause, keep the code style, do not remove features, do not add unrelated changes.
315
+ - Only edit the files you were given. To report that nothing is wrong, return "edits": [] and "done": true.
316
+ - If earlier edits failed to apply or made things worse you will be told; correct them.
317
+ """
318
+
319
+
320
+ class Fixer:
321
+ def __init__(self, backend=None, max_rounds: int = 3):
322
+ self.backend = backend # object with .chat(messages, json_mode=True) or None
323
+ self.max_rounds = max_rounds
324
+
325
+ # ---- public ---------------------------------------------------------------
326
+ def fix(self, target: Path, description: str = "", run_cmd: list[str] | None = None,
327
+ focus: list[str] | None = None, apply: bool = True) -> FixReport:
328
+ """apply=False: the agent works on a temporary copy; the report carries the diff and the new
329
+ contents in `pending`, and nothing touches the real files until commit(report)."""
330
+ target = Path(target)
331
+ if not target.exists():
332
+ return FixReport(False, f"'{target}' does not exist")
333
+ real_root, real_files = collect(target)
334
+ if not real_files:
335
+ return FixReport(False, f"no source files found in {target}")
336
+ if apply:
337
+ return self._fix(target, description, run_cmd, focus)
338
+ import tempfile
339
+ with tempfile.TemporaryDirectory(prefix="nlcl_fix_") as td:
340
+ work = Path(td) / real_root.name
341
+ if target.is_file():
342
+ work.mkdir(parents=True)
343
+ shutil.copy2(target, work / target.name)
344
+ wtarget = work / target.name
345
+ else:
346
+ shutil.copytree(real_root, work, ignore=shutil.ignore_patterns(".nlcl_backup", ".git", "node_modules"))
347
+ wtarget = work
348
+ rep = self._fix(wtarget, description, run_cmd, focus, keep_backup=False)
349
+ for rel in rep.changed:
350
+ text, crlf = _read(work / rel)
351
+ rep.pending[str(real_root / rel)] = (text, crlf)
352
+ rep.root = str(real_root)
353
+ rep.backup = None
354
+ if rep.changed:
355
+ rep.summary = rep.summary.replace("fixed ", "proposed fix for ", 1)
356
+ return rep
357
+
358
+ @staticmethod
359
+ def commit(rep: "FixReport") -> list[str]:
360
+ """Write a confirmed fix (from fix(apply=False)) to the real files, with a backup."""
361
+ if not rep.pending:
362
+ return [" nothing to apply"]
363
+ root = Path(rep.root)
364
+ originals = {}
365
+ for path in rep.pending:
366
+ p = Path(path)
367
+ originals[p] = _read(p)
368
+ backup = Fixer._backup(root, originals)
369
+ for path, (text, crlf) in rep.pending.items():
370
+ _write(Path(path), text, crlf)
371
+ rep.backup = str(backup)
372
+ n = len(rep.pending)
373
+ rep.pending = {}
374
+ return [f" applied the fix to {n} file(s); originals saved in {backup} (':fix undo' restores them)"]
375
+
376
+ def _fix(self, target: Path, description: str, run_cmd, focus, keep_backup: bool = True) -> FixReport:
377
+ root, files = collect(target)
378
+ before = diagnose(target, run_cmd)
379
+ if self.backend is None:
380
+ if before:
381
+ return FixReport(False, "offline: problems located but not fixed (fixing needs the online agent - "
382
+ "set a free API key, see ':backend status')", before=before, after=before)
383
+ return FixReport(True, f"offline check of {len(files)} file(s): no problems found by the available tools. "
384
+ "Logic bugs need the online agent (':backend status').")
385
+ originals: dict[Path, str] = {}
386
+ applied: list[dict] = []
387
+ notes: list[str] = []
388
+ diags = before
389
+ feedback = ""
390
+ analysis = ""
391
+ for rnd in range(1, self.max_rounds + 1):
392
+ payload = self._payload(root, files, diags, description, focus)
393
+ msgs = [{"role": "system", "content": FIX_PROMPT},
394
+ {"role": "user", "content": payload + (f"\n\nFEEDBACK FROM THE PREVIOUS ROUND:\n{feedback}" if feedback else "")}]
395
+ try:
396
+ from .llm import extract_json
397
+ data = extract_json(self.backend.chat(msgs))
398
+ except Exception as e:
399
+ notes.append(f"round {rnd}: agent error: {str(e)[:160]}")
400
+ break
401
+ analysis = str(data.get("analysis") or analysis)
402
+ edits = data.get("edits") or []
403
+ if not edits:
404
+ if data.get("done", True):
405
+ break
406
+ feedback = "You returned no edits but said you are not done. Return edits or done=true."
407
+ continue
408
+ snapshot = {p: _read(p) for p in files}
409
+ ok_edits, failed = [], []
410
+ for ed in edits:
411
+ r = self._apply(root, files, ed, originals)
412
+ (ok_edits if r is None else failed).append(ed if r is None else f"{ed.get('file')}: {r}")
413
+ new = diagnose(target, run_cmd)
414
+ if _errors(new) > _errors(diags):
415
+ for p, (txt, crlf) in snapshot.items(): # roll the round back
416
+ _write(p, txt, crlf)
417
+ feedback = ("Your edits were ROLLED BACK because they introduced new problems:\n"
418
+ + "\n".join(str(d) for d in new[:8]))
419
+ notes.append(f"round {rnd}: rolled back (edits made it worse)")
420
+ continue
421
+ applied += ok_edits
422
+ diags = new
423
+ feedback = ""
424
+ if failed:
425
+ feedback = "These edits did not apply (search text not found exactly):\n" + "\n".join(failed[:6])
426
+ notes.append(f"round {rnd}: {len(failed)} edit(s) did not match the file")
427
+ if not _errors(diags) and not failed and data.get("done", True):
428
+ break
429
+ if not _errors(diags) and not failed:
430
+ feedback = "Tools report no problems now. Return done=true if the bug described by the user is fixed."
431
+ changed, backup = {}, None
432
+ for p, (old, _crlf) in originals.items():
433
+ new_txt = _read(p)[0]
434
+ if new_txt != old:
435
+ rel = str(p.relative_to(root)).replace("\\", "/")
436
+ changed[rel] = "".join(difflib.unified_diff(old.splitlines(True), new_txt.splitlines(True),
437
+ "before/" + rel, "after/" + rel, n=2))
438
+ if changed and keep_backup:
439
+ backup = str(self._backup(root, originals))
440
+ ok = not _errors(diags)
441
+ if changed:
442
+ summary = f"fixed {len(changed)} file(s)" + (f": {analysis}" if analysis else "")
443
+ elif analysis:
444
+ summary = f"no change made: {analysis}"
445
+ else:
446
+ summary = "no change made"
447
+ return FixReport(ok, summary, before, diags, changed, applied, backup, notes)
448
+
449
+ @staticmethod
450
+ def undo(root: Path) -> list[str]:
451
+ """Restore the most recent backup made by fix()."""
452
+ bdir = Path(root) / ".nlcl_backup"
453
+ runs = sorted(p for p in bdir.iterdir() if p.is_dir()) if bdir.exists() else []
454
+ if not runs:
455
+ return [" no fix backup found"]
456
+ last, out = runs[-1], []
457
+ for f in last.rglob("*"):
458
+ if f.is_file():
459
+ dst = Path(root) / f.relative_to(last)
460
+ dst.parent.mkdir(parents=True, exist_ok=True)
461
+ shutil.copy2(f, dst)
462
+ out.append(f" restored {f.relative_to(last)}")
463
+ shutil.rmtree(last, ignore_errors=True)
464
+ return out or [" backup was empty"]
465
+
466
+ # ---- internals ------------------------------------------------------------
467
+ def _payload(self, root: Path, files: list[Path], diags: list[Diag], description: str,
468
+ focus: list[str] | None) -> str:
469
+ flagged = {d.file for d in diags}
470
+ words = set(re.findall(r"[\w.\-/]+", (description or "").lower())) | {f.lower() for f in (focus or [])}
471
+
472
+ def rank(p: Path) -> tuple:
473
+ rel = str(p.relative_to(root)).replace("\\", "/")
474
+ named = rel.lower() in words or p.name.lower() in words or p.stem.lower() in words
475
+ return (rel not in flagged, not named, p.suffix.lower() not in CODE_EXT, p.stat().st_size)
476
+ parts, total = [], 0
477
+ skipped = []
478
+ for p in sorted(files, key=rank):
479
+ rel = str(p.relative_to(root)).replace("\\", "/")
480
+ txt = p.read_text(encoding="utf-8", errors="replace")
481
+ if len(txt) > MAX_FILE or total + len(txt) > MAX_TOTAL:
482
+ skipped.append(rel)
483
+ continue
484
+ total += len(txt)
485
+ parts.append(f"=== FILE {rel} ===\n{txt}\n=== END {rel} ===")
486
+ head = [f"BUG DESCRIPTION FROM THE USER: {description.strip() or '(none - find and fix what the tools report, then anything clearly wrong)'}",
487
+ "", "TOOL DIAGNOSTICS:" if diags else "TOOL DIAGNOSTICS: none (the tools found no problem; look for the logic bug described)"]
488
+ head += [f"- {d}" for d in diags[:30]]
489
+ if skipped:
490
+ head.append(f"(not shown, too large: {', '.join(skipped[:12])})")
491
+ return "\n".join(head) + "\n\n" + "\n\n".join(parts)
492
+
493
+ @staticmethod
494
+ def _apply(root: Path, files: list[Path], ed: dict, originals: dict[Path, str]) -> str | None:
495
+ """Apply one edit. Returns None on success or the reason it failed."""
496
+ if not isinstance(ed, dict) or "file" not in ed or "search" not in ed or "replace" not in ed:
497
+ return "malformed edit"
498
+ rel = str(ed["file"]).replace("\\", "/")
499
+ while rel.startswith("./"): # a "./" prefix, not every leading '.' (".env" stays ".env")
500
+ rel = rel[2:]
501
+ p = next((f for f in files if str(f.relative_to(root)).replace("\\", "/") == rel), None)
502
+ if p is None:
503
+ same = [f for f in files if f.name == Path(rel).name]
504
+ if len(same) > 1:
505
+ return f"ambiguous file name {Path(rel).name!r}: use its path ({', '.join(str(f.relative_to(root)) for f in same[:4])})"
506
+ p = same[0] if same else None
507
+ if p is None:
508
+ return "not one of the given files"
509
+ txt, crlf = _read(p)
510
+ search, repl = str(ed["search"]), str(ed["replace"])
511
+ if not search:
512
+ return "empty search"
513
+ if search not in txt:
514
+ # tolerate differences in line endings / trailing spaces / indentation width
515
+ norm = lambda s: re.sub(r"[ \t]+", " ", s.replace("\r\n", "\n")).strip() # noqa: E731
516
+ lines = txt.replace("\r\n", "\n").split("\n")
517
+ want = [norm(x) for x in search.replace("\r\n", "\n").strip("\n").split("\n")]
518
+ hit = None
519
+ for i in range(len(lines) - len(want) + 1):
520
+ if [norm(x) for x in lines[i:i + len(want)]] == want:
521
+ hit = i
522
+ break
523
+ if hit is None:
524
+ return "search text not found"
525
+ indent = re.match(r"[ \t]*", lines[hit]).group(0)
526
+ new_lines = repl.replace("\r\n", "\n").strip("\n").split("\n")
527
+ base = re.match(r"[ \t]*", new_lines[0]).group(0) if new_lines else ""
528
+ if base != indent:
529
+ new_lines = [indent + ln[len(base):] if ln.startswith(base) else ln for ln in new_lines]
530
+ lines[hit:hit + len(want)] = new_lines
531
+ new_txt = "\n".join(lines)
532
+ else:
533
+ new_txt = txt.replace(search, repl, 1)
534
+ if new_txt == txt:
535
+ return "edit changes nothing"
536
+ originals.setdefault(p, (txt, crlf))
537
+ _write(p, new_txt, crlf)
538
+ return None
539
+
540
+ @staticmethod
541
+ def _backup(root: Path, originals: dict[Path, str]) -> Path:
542
+ d = root / ".nlcl_backup" / time.strftime("%Y%m%d-%H%M%S")
543
+ n = 1
544
+ while d.exists():
545
+ n += 1
546
+ d = root / ".nlcl_backup" / (time.strftime("%Y%m%d-%H%M%S") + f"-{n}")
547
+ for p, (old, crlf) in originals.items():
548
+ dst = d / p.relative_to(root)
549
+ dst.parent.mkdir(parents=True, exist_ok=True)
550
+ _write(dst, old, crlf)
551
+ return d
552
+
553
+
554
+ def _read(p: Path) -> tuple[str, bool]:
555
+ """Text with '\\n' line ends + whether the file used CRLF (so a fix keeps the file's line endings)."""
556
+ raw = Path(p).read_bytes().decode("utf-8", "replace")
557
+ crlf = "\r\n" in raw
558
+ return raw.replace("\r\n", "\n"), crlf
559
+
560
+
561
+ def _write(p: Path, text: str, crlf: bool) -> None:
562
+ data = text.replace("\r\n", "\n")
563
+ if crlf:
564
+ data = data.replace("\n", "\r\n")
565
+ Path(p).write_bytes(data.encode("utf-8"))
566
+
567
+
568
+ def _errors(diags: list[Diag]) -> int:
569
+ return sum(1 for d in diags if d.severity == "error")
570
+
571
+
572
+ def python_run_cmd(path: Path) -> list[str] | None:
573
+ """A safe default way to execute a Python target when the user asks to run it while fixing."""
574
+ if path.is_file() and path.suffix == ".py":
575
+ return [sys.executable, "-u", path.name]
576
+ return None
nlcl/fuzzy.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fuzzy meanings of vague words: "fast", "very bright", "a bit slower", "when health is low".
2
+
3
+ A vague adjective names a fuzzy set on a property's range; the range depends on what is described
4
+ (a fast hero is not a fast car), and both live in the Prolog KB (vague/3, range/4, hedge/2,
5
+ comparative/3, amount/2). Values are obtained by centroid defuzzification; hedges ("very",
6
+ "somewhat") are concentration / dilation (membership ** exponent); comparatives are a relative change
7
+ of the range ("a bit faster" = +10% of the range); conditions use the 0.5 alpha-cut of the set.
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import re
12
+
13
+ KB = None # set by the runtime (a Knowledge instance)
14
+
15
+ # term -> trapezoid (a, b, c, d) on the normalised range [0, 1]
16
+ TERMS = {"low": (0.0, 0.0, 0.2, 0.4), "medium": (0.3, 0.45, 0.55, 0.7), "high": (0.6, 0.8, 1.0, 1.0)}
17
+ HEDGES_DEFAULT = {"very": 2.0, "really": 2.0, "super": 3.0, "extremely": 3.0, "quite": 1.5, "pretty": 1.5,
18
+ "fairly": 0.75, "somewhat": 0.5, "rather": 0.75, "slightly": 0.5, "a_bit": 0.5, "a_little": 0.5}
19
+
20
+
21
+ def _kb():
22
+ global KB
23
+ if KB is None:
24
+ from . import modules as modreg
25
+ from .knowledge import Knowledge
26
+ KB = Knowledge(None, modreg.load_modules())
27
+ return KB
28
+
29
+
30
+ def membership(term: str, x: float) -> float:
31
+ a, b, c, d = TERMS[term]
32
+ if x < a or x > d:
33
+ return 0.0
34
+ if b <= x <= c:
35
+ return 1.0
36
+ if x < b:
37
+ return (x - a) / (b - a) if b > a else 1.0
38
+ return (d - x) / (d - c) if d > c else 1.0
39
+
40
+
41
+ def centroid(term: str, exponent: float = 1.0, steps: int = 400) -> float:
42
+ num = den = 0.0
43
+ for i in range(steps + 1):
44
+ x = i / steps
45
+ m = membership(term, x) ** exponent
46
+ num += m * x
47
+ den += m
48
+ return num / den if den else 0.5
49
+
50
+
51
+ def alpha_cut(term: str, exponent: float = 1.0, alpha: float = 0.5) -> tuple[float, float]:
52
+ """Interval where membership ** exponent >= alpha (used for conditions)."""
53
+ xs = [i / 400 for i in range(401) if membership(term, i / 400) ** exponent >= alpha]
54
+ return (xs[0], xs[-1]) if xs else (0.0, 1.0)
55
+
56
+
57
+ # ---------------------------------------------------------------------- KB lookups
58
+ def adjective(word: str) -> tuple[str, str] | None:
59
+ """'fast' -> ('speed', 'high'); 'low' -> ('any', 'low')."""
60
+ r = _kb().query(f"vague({_kb().to_term(word.lower())}, P, T)", limit=1)
61
+ return (r[0]["P"], r[0]["T"]) if r else None
62
+
63
+
64
+ def comparative(word: str) -> tuple[str, str] | None:
65
+ r = _kb().query(f"comparative({_kb().to_term(word.lower())}, P, D)", limit=1)
66
+ return (r[0]["P"], r[0]["D"]) if r else None
67
+
68
+
69
+ def hedge(phrase: str | None) -> float:
70
+ if not phrase:
71
+ return 1.0
72
+ key = re.sub(r"\s+", "_", phrase.strip().lower())
73
+ r = _kb().query(f"hedge({_kb().to_term(key)}, E)", limit=1)
74
+ return float(r[0]["E"]) if r else HEDGES_DEFAULT.get(key, 1.0)
75
+
76
+
77
+ def amount(phrase: str | None) -> float:
78
+ key = re.sub(r"\s+", "_", (phrase or "default").strip().lower())
79
+ r = _kb().query(f"amount({_kb().to_term(key)}, A)", limit=1)
80
+ return float(r[0]["A"]) if r else 0.2
81
+
82
+
83
+ def value_range(prop: str, kind: str | None = None, domain: str | None = None, current=None) -> tuple[float, float]:
84
+ k = _kb()
85
+ r = k.query(f"range_for({k.to_term(kind or 'none')}, {k.to_term(domain or 'none')}, {k.to_term(prop)}, L, H)", limit=1)
86
+ if r:
87
+ return float(r[0]["L"]), float(r[0]["H"])
88
+ cur = float(current) if isinstance(current, (int, float)) and not isinstance(current, bool) else 0.0
89
+ return 0.0, max(1.0, 2 * cur) if cur > 0 else 100.0
90
+
91
+
92
+ def _num(v: float):
93
+ v = round(v, 2)
94
+ return int(v) if float(v).is_integer() else v
95
+
96
+
97
+ # ---------------------------------------------------------------------- meanings
98
+ HEDGE_WORDS = r"(?:very|really|super|extremely|incredibly|quite|pretty|fairly|somewhat|rather|slightly|kind\s+of|a\s+bit|a\s+little)"
99
+ AMOUNT_WORDS = r"(?:a\s+bit|a\s+little|slightly|somewhat|much|a\s+lot|way|far)"
100
+
101
+
102
+ def set_value(entity, adj: str, hedge_phrase: str | None = None, prop: str | None = None):
103
+ """-> (prop, value, explanation) for 'make <entity> <hedge> <adj>'."""
104
+ a = adjective(adj)
105
+ if not a:
106
+ return None
107
+ p, term = a
108
+ if p == "any":
109
+ if not prop:
110
+ return None
111
+ p = prop
112
+ lo, hi = value_range(p, getattr(entity, "kind", None), getattr(entity, "domain", None),
113
+ getattr(entity, "props", {}).get(p))
114
+ c = centroid(term, hedge(hedge_phrase))
115
+ v = _num(lo + c * (hi - lo))
116
+ what = getattr(entity, "kind", "it")
117
+ return p, v, f"{(hedge_phrase + ' ') if hedge_phrase else ''}{adj} for a {what}: {_num(lo)}..{_num(hi)}"
118
+
119
+
120
+ def change_value(entity, word: str, amount_phrase: str | None = None, factor: float | None = None, prop: str | None = None):
121
+ """-> (prop, new_value, explanation) for 'make <entity> <amount> <comparative>' / 'twice as fast'."""
122
+ c = comparative(word)
123
+ if not c:
124
+ a = adjective(word) # "twice as fast": factor on the property of 'fast'
125
+ if not a or factor is None:
126
+ return None
127
+ c = (a[0], "up")
128
+ p, direction = c
129
+ if p == "any":
130
+ if not prop:
131
+ return None
132
+ p = prop
133
+ props = getattr(entity, "props", {})
134
+ lo, hi = value_range(p, getattr(entity, "kind", None), getattr(entity, "domain", None), props.get(p))
135
+ cur = props.get(p)
136
+ if not isinstance(cur, (int, float)) or isinstance(cur, bool):
137
+ cur = lo + 0.5 * (hi - lo)
138
+ if factor is not None:
139
+ new = cur * factor
140
+ how = f"x{_num(factor)}"
141
+ else:
142
+ share = amount(amount_phrase)
143
+ delta = share * (hi - lo) * (1 if direction == "up" else -1)
144
+ new = cur + delta
145
+ how = f"{'+' if delta >= 0 else ''}{_num(delta)} ({int(share * 100)}% of {_num(lo)}..{_num(hi)})"
146
+ new = max(lo, min(hi, new))
147
+ return p, _num(new), how
148
+
149
+
150
+ def delta_for(entity, word: str, amount_phrase: str | None = None) -> tuple[str, float] | None:
151
+ """Relative change as a fixed delta (for behaviours: 'when it rains, make hero faster')."""
152
+ c = comparative(word)
153
+ if not c or c[0] == "any":
154
+ return None
155
+ p, direction = c
156
+ lo, hi = value_range(p, getattr(entity, "kind", None), getattr(entity, "domain", None),
157
+ getattr(entity, "props", {}).get(p))
158
+ return p, _num(amount(amount_phrase) * (hi - lo) * (1 if direction == "up" else -1))
159
+
160
+
161
+ def condition(subject_expr: str, adj: str, hedge_phrase: str | None, entity) -> str | None:
162
+ """'health is low' -> 'health <= 30'; 'hero is fast' -> 'speed >= 14' (alpha-cut 0.5)."""
163
+ a = adjective(adj)
164
+ if not a:
165
+ return None
166
+ p, term = a
167
+ if p == "any":
168
+ expr = subject_expr
169
+ p = subject_expr.split(".")[-1]
170
+ else:
171
+ expr = (subject_expr + "." + p) if subject_expr and subject_expr not in ("it", "self") else p
172
+ lo, hi = value_range(p, getattr(entity, "kind", None), getattr(entity, "domain", None),
173
+ getattr(entity, "props", {}).get(p) if entity is not None else None)
174
+ a0, a1 = alpha_cut(term, hedge(hedge_phrase))
175
+ x0, x1 = _num(lo + a0 * (hi - lo)), _num(lo + a1 * (hi - lo))
176
+ if term == "low":
177
+ return f"{expr} <= {x1}"
178
+ if term == "high":
179
+ return f"{expr} >= {x0}"
180
+ return f"({expr} >= {x0} && {expr} <= {x1})"
nlcl/interpreter.py ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Computational structure formation: apply IR ops to the persistent state.
2
+
3
+ The interpreter never guesses the domain of a new object. If it cannot be
4
+ determined it returns a Question carrying the pending op; the runtime asks
5
+ the user and calls ``answer()`` with the reply.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from dataclasses import dataclass, field
11
+
12
+ from . import modules as modreg
13
+ from .ir import (Entity, Link, Op, SystemState, eval_expr, expr_names, expr_tokens, ident, norm_name, singular,
14
+ validate_behavior, validate_expr)
15
+
16
+
17
+ COLOR_WORDS = {"red", "green", "blue", "yellow", "white", "black", "orange", "purple", "pink", "cyan",
18
+ "magenta", "gray", "grey", "brown", "gold", "silver"}
19
+ TRUE_BY_DEFAULT = {"visible", "enabled", "active", "alive", "running"}
20
+
21
+
22
+ @dataclass
23
+ class Question:
24
+ text: str
25
+ op: Op
26
+ field: str # which op field the answer fills ("domain")
27
+ options: list[str] = field(default_factory=list)
28
+
29
+
30
+ @dataclass
31
+ class Outcome:
32
+ messages: list[str] = field(default_factory=list)
33
+ question: Question | None = None
34
+ followup: str | None = None # soft prompt ("What properties should it have?")
35
+ meta: list[Op] = field(default_factory=list) # SHOW/BUILD/RUN/... for the runtime
36
+ changed: bool = False
37
+
38
+
39
+ class Interpreter:
40
+ def __init__(self, state: SystemState):
41
+ self.state = state
42
+ self.modules = modreg.load_modules()
43
+
44
+ # ------------------------------------------------------------------ main
45
+ def apply_all(self, ops: list[Op]) -> Outcome:
46
+ out = Outcome()
47
+ snap_taken = False
48
+ for i, op in enumerate(ops):
49
+ if op.action in ("SHOW", "BUILD", "RUN", "UNDO", "DEFINE", "HELP", "FIX"):
50
+ out.meta.append(op)
51
+ continue
52
+ if not snap_taken:
53
+ self.state.snapshot()
54
+ snap_taken = True
55
+ r = self.apply(op)
56
+ out.messages += r.messages
57
+ out.changed |= r.changed
58
+ if r.followup:
59
+ out.followup = r.followup
60
+ if r.question:
61
+ # remaining ops wait until the question is answered
62
+ r.question.op.props.setdefault("__rest__", [o.to_dict() for o in ops[i + 1:]])
63
+ out.question = r.question
64
+ break
65
+ if snap_taken and not out.changed:
66
+ self.state._undo.pop()
67
+ return out
68
+
69
+ def apply(self, op: Op) -> Outcome:
70
+ fn = getattr(self, f"_op_{op.action.lower()}", None)
71
+ if not fn:
72
+ return Outcome([f"(ignored unsupported action {op.action})"])
73
+ try:
74
+ return fn(op)
75
+ except ValueError as e:
76
+ return Outcome([f"error: {e}"])
77
+
78
+ def answer(self, q: Question, reply: str, parsed_ops: list[Op] | None = None) -> Outcome:
79
+ """Fill the pending op with the user's reply and continue."""
80
+ op = q.op
81
+ rest = op.props.pop("__rest__", [])
82
+ low = reply.lower()
83
+ if q.field == "domain":
84
+ dom = self._domain_from_text(low, q.options)
85
+ if not dom:
86
+ q.op.props["__rest__"] = rest
87
+ return Outcome([f"Please choose one of: {', '.join(q.options)}"], question=q)
88
+ op.domain = dom
89
+ op.props.pop("__domain_candidates__", None)
90
+ # the reply may also carry a kind / props ("a game object with 100 health")
91
+ for p in parsed_ops or []:
92
+ if p.action == "CREATE":
93
+ if p.kind and p.kind != "object" and (op.kind in (None, "object")):
94
+ op.kind = p.kind
95
+ if p.name and not op.name:
96
+ op.name = p.name
97
+ op.props.update({k: v for k, v in p.props.items() if not k.startswith("__")})
98
+ elif p.action == "SET":
99
+ op.props.update(p.props)
100
+ return self.apply_all([op] + [Op.from_dict(d) for d in rest])
101
+
102
+ def _domain_from_text(self, low: str, options: list[str]) -> str | None:
103
+ words = re.findall(r"[\w؀-ۿ+#.\-]+", low)
104
+ for w in words:
105
+ m = modreg.get(w)
106
+ if m and (not options or m.name in options):
107
+ return m.name
108
+ for w in words:
109
+ for m in self.modules.values():
110
+ if w in m.keywords and (not options or m.name in options):
111
+ return m.name
112
+ for i, opt in enumerate(options, 1):
113
+ if low.strip() == str(i):
114
+ return opt
115
+ return None
116
+
117
+ # ------------------------------------------------------------------ ops
118
+ def _op_create(self, op: Op) -> Outcome:
119
+ st = self.state
120
+ out = Outcome()
121
+ domain = op.domain or self._infer_domain(op)
122
+ if domain and not modreg.get(domain):
123
+ raise ValueError(f"unknown domain '{domain}'. Available: {', '.join(self.modules)}")
124
+ if not domain:
125
+ cands = op.props.get("__domain_candidates__") or self._candidates(op.kind)
126
+ options = cands or list(self.modules)
127
+ kind = op.kind or "object"
128
+ q = Question(f"What kind of {kind} would you like to create? ({' / '.join(options)})",
129
+ op, "domain", options)
130
+ out.question = q
131
+ return out
132
+ module = modreg.get(domain)
133
+ domain = module.name
134
+ parent = None
135
+ if op.parent:
136
+ pe = st.resolve(op.parent)
137
+ if not pe:
138
+ out.messages.append(f"note: parent '{op.parent}' not found; created at top level")
139
+ elif pe.domain != domain:
140
+ # cross-domain "for": e.g. a CAD enclosure for an embedded board
141
+ op.props.setdefault("for_entity", pe.name)
142
+ if pe.domain == "embedded":
143
+ op.props.setdefault("board", pe.kind)
144
+ else:
145
+ parent = pe.id
146
+ kind = (op.kind or "object").lower()
147
+ group = []
148
+ base0 = ident(singular(op.name or kind)) if op.count > 1 else None
149
+ nxt = 1
150
+ if base0:
151
+ used = [int(m.group(1)) for x in st.entities.values()
152
+ for m in [re.fullmatch(rf"{re.escape(base0)}(\d+)", x.name)] if m]
153
+ nxt = max(used, default=0) + 1
154
+ for i in range(op.count):
155
+ base = op.name or kind
156
+ if op.count > 1:
157
+ base = f"{base0}{nxt + i}" # enemy4, enemy5 ... never enemy12
158
+ name = st.unique_name(base)
159
+ eid = st.new_id(kind)
160
+ props = module.default_props(kind)
161
+ props.update({k: v for k, v in op.props.items() if not k.startswith("__")})
162
+ e = Entity(id=eid, name=name, domain=domain, kind=kind, props=props, parent=parent)
163
+ st.entities[eid] = e
164
+ st.focus = eid
165
+ group.append(eid)
166
+ out.messages.append(f"created {domain} {kind} '{name}'" + (f" in {st.entities[parent].name}" if parent else "")
167
+ + (f" {self._fmt(props)}" if props else ""))
168
+ for w in module.validate(e):
169
+ out.messages.append(f" warning: {w}")
170
+ # "create 3 enemies ... and make them red": following SETs apply to the whole group
171
+ st.focus_group = group if len(group) > 1 else []
172
+ out.changed = True
173
+ real = {k for k in op.props if not k.startswith("__") and k != "subtype"}
174
+ if not real and not getattr(self, "quiet_followups", False):
175
+ out.followup = module.prompt_for(st.entities[st.focus])
176
+ return out
177
+
178
+ def _infer_domain(self, op: Op) -> str | None:
179
+ cands = self._candidates(op.kind)
180
+ if op.parent:
181
+ pe = self.state.resolve(op.parent)
182
+ if pe and (not cands or pe.domain in cands):
183
+ return pe.domain
184
+ hints = op.props.get("__domain_hints__") or []
185
+ # "use hardware" then "create a counter": the default domain wins when it knows the kind
186
+ dd = self.state.default_domain
187
+ if dd and (dd in cands or dd in hints):
188
+ return dd
189
+ if not cands and len(hints) == 1:
190
+ return hints[0]
191
+ if len(cands) > 1 and hints:
192
+ narrowed = [c for c in cands if c in hints]
193
+ if len(narrowed) == 1:
194
+ return narrowed[0]
195
+ if len(cands) == 1:
196
+ return cands[0]
197
+ if self.state.default_domain and (not cands or self.state.default_domain in cands):
198
+ return self.state.default_domain
199
+ # context: the domain of what the user is working on (focus, then most used)
200
+ if cands:
201
+ focus = self.state.resolve(None)
202
+ if focus and focus.domain in cands:
203
+ return focus.domain
204
+ used = [e.domain for e in self.state.entities.values() if e.domain in cands]
205
+ if used:
206
+ return max(set(used), key=used.count)
207
+ return None
208
+
209
+ def _candidates(self, kind: str | None) -> list[str]:
210
+ if not kind or kind == "object":
211
+ return []
212
+ k = kind.lower()
213
+ strong = [m.name for m in self.modules.values() if k in {x.lower() for x in m.kinds}]
214
+ weak = [m.name for m in self.modules.values() if k in {x.lower() for x in m.keywords}]
215
+ return strong or weak
216
+
217
+ def _target(self, ref: str | None) -> Entity:
218
+ e = self.state.resolve(ref)
219
+ if not e:
220
+ if ref:
221
+ raise ValueError(f"I can't find '{ref}'. Known: {', '.join(x.name for x in self.state.entities.values()) or 'nothing yet'}")
222
+ raise ValueError("there is nothing in focus yet - create something first")
223
+ return e
224
+
225
+ def _targets(self, ref: str | None) -> list[Entity]:
226
+ """'*enemy' -> every enemy; None right after 'create 3 enemies' -> the whole group."""
227
+ st = self.state
228
+ if ref and str(ref).startswith("*"):
229
+ k = str(ref)[1:]
230
+ hits = [e for e in st.entities.values() if e.kind == k]
231
+ if hits:
232
+ return hits
233
+ return [self._target(k)]
234
+ if (ref is None or str(ref).lower() in ("them", "they", "all of them")) and getattr(st, "focus_group", None):
235
+ grp = [st.entities[i] for i in st.focus_group if i in st.entities]
236
+ if grp and st.focus in st.focus_group:
237
+ return grp
238
+ return [self._target(ref)]
239
+
240
+ def _op_set(self, op: Op) -> Outcome:
241
+ targets = self._targets(op.target)
242
+ out = Outcome(changed=True)
243
+ for e in targets:
244
+ r = self._set_one(e, op)
245
+ out.messages += r.messages
246
+ if len(targets) > 1:
247
+ self.state.focus = targets[-1].id
248
+ return out
249
+
250
+ def _set_one(self, e: Entity, op: Op) -> Outcome:
251
+ out = Outcome(changed=True)
252
+ props = dict(op.props)
253
+ new_kind = props.pop("__kind__", None)
254
+ if new_kind and new_kind != e.kind:
255
+ mod = modreg.get(e.domain)
256
+ if mod and new_kind not in mod.kinds:
257
+ cands = self._candidates(new_kind)
258
+ if cands:
259
+ e.domain = cands[0] if e.domain not in cands else e.domain
260
+ out.messages.append(f"{e.name} moved to domain {e.domain}")
261
+ out.messages.append(f"{e.name} is now a {new_kind}")
262
+ e.kind = new_kind
263
+ mod = modreg.get(e.domain)
264
+ for k, v in (mod.default_props(new_kind) if mod else {}).items():
265
+ e.props.setdefault(k, v)
266
+ act = props.pop("__act__", None)
267
+ if act:
268
+ out.messages += self._do_now(e, act)
269
+ mv = props.pop("__move__", None)
270
+ if mv is not None:
271
+ pos = list(e.props.get("position", [0, 0, 0]))
272
+ pos = (pos + [0, 0, 0])[:3]
273
+ e.props["position"] = [a + b for a, b in zip(pos, (list(mv) + [0, 0, 0])[:3])]
274
+ out.messages.append(f"moved {e.name} to {e.props['position']}")
275
+ if op.domain and op.domain != e.domain:
276
+ m = modreg.get(op.domain)
277
+ if not m:
278
+ raise ValueError(f"unknown domain '{op.domain}'")
279
+ e.domain = m.name
280
+ out.messages.append(f"{e.name} now belongs to domain {m.name}")
281
+ if op.parent:
282
+ pe = self._target(op.parent)
283
+ if pe.id == e.id:
284
+ raise ValueError("an entity cannot contain itself")
285
+ e.parent = pe.id
286
+ out.messages.append(f"{e.name} is now inside {pe.name}")
287
+ props = {k: v for k, v in props.items() if not k.startswith("__")}
288
+ if props:
289
+ e.props.update(props)
290
+ out.messages.append(f"{e.name}: " + self._fmt(props))
291
+ mod = modreg.get(e.domain)
292
+ for w in (mod.validate(e) if mod else []):
293
+ out.messages.append(f" warning: {w}")
294
+ self.state.focus = e.id
295
+ return out
296
+
297
+ def _do_now(self, e: Entity, a: dict) -> list[str]:
298
+ """Execute a behaviour action immediately on the design-time state."""
299
+ a = validate_behavior({"on": "start", "do": [a]})["do"][0]
300
+ op = a["op"]
301
+ env = self._env(e)
302
+ if op == "set":
303
+ e.props[a["prop"]] = eval_expr(a["value"], env)
304
+ return [f"{e.name}: {a['prop']} = {e.props[a['prop']]!r}"]
305
+ if op == "add":
306
+ cur = e.props.get(a["prop"], 0)
307
+ e.props[a["prop"]] = (cur if isinstance(cur, (int, float)) else 0) + eval_expr(a["value"], env)
308
+ return [f"{e.name}: {a['prop']} = {e.props[a['prop']]!r}"]
309
+ if op == "toggle":
310
+ e.props[a["prop"]] = not bool(e.props.get(a["prop"], False))
311
+ return [f"{e.name}: {a['prop']} = {e.props[a['prop']]!r}"]
312
+ if op == "move":
313
+ mv = [eval_expr(a[k], env) for k in ("x", "y", "z")]
314
+ pos = (list(e.props.get("position", [0, 0, 0])) + [0, 0, 0])[:3]
315
+ e.props["position"] = [p + d for p, d in zip(pos, mv)]
316
+ return [f"moved {e.name} to {e.props['position']}"]
317
+ if op == "log":
318
+ return [f"[{e.name}] " + re.sub(r"\{(\w+)\}", lambda m: str(e.props.get(m.group(1), m.group(0))), a["text"])]
319
+ raise ValueError(f"'{op}' only makes sense inside a behaviour (when/every ...)")
320
+
321
+ def _env(self, owner: Entity) -> dict:
322
+ env = {}
323
+ for x in self.state.entities.values():
324
+ for k, v in x.props.items():
325
+ env[f"{x.ident}.{k}"] = v
326
+ env.update(owner.props)
327
+ return env
328
+
329
+ def _op_unset(self, op: Op) -> Outcome:
330
+ e = self._target(op.target)
331
+ gone = [k for k in op.props if e.props.pop(norm_name(k), None) is not None or True]
332
+ self.state.focus = e.id
333
+ return Outcome([f"{e.name}: removed {', '.join(gone)}"], changed=True)
334
+
335
+ def _op_delete(self, op: Op) -> Outcome:
336
+ e = self._target(op.target)
337
+ st = self.state
338
+ doomed = {e.id}
339
+ changed = True
340
+ while changed:
341
+ changed = False
342
+ for x in st.entities.values():
343
+ if x.parent in doomed and x.id not in doomed:
344
+ doomed.add(x.id)
345
+ changed = True
346
+ gone_names = {st.entities[d].ident for d in doomed if d in st.entities}
347
+ for d in doomed:
348
+ st.entities.pop(d, None)
349
+ for lid in [l.id for l in st.links.values() if l.src in doomed or l.dst in doomed]:
350
+ st.links.pop(lid)
351
+ st.focus = next(reversed(st.entities), None) if st.entities else None
352
+ st.focus_group = [g for g in getattr(st, "focus_group", []) if g in st.entities]
353
+ extra = f" (and {len(doomed) - 1} children)" if len(doomed) > 1 else ""
354
+ return Outcome([f"deleted {e.name}{extra}"] + self._dangling(gone_names), changed=True)
355
+
356
+ def _op_rename(self, op: Op) -> Outcome:
357
+ e = self._target(op.target)
358
+ old = e.name
359
+ old_ident = e.ident
360
+ e.name = self.state.unique_name(op.name or e.name) if ident(op.name or "") != e.name else e.name
361
+ self.state.focus = e.id
362
+ new_ident = e.ident
363
+ n = self._rewrite_refs(old_ident, new_ident) if new_ident != old_ident else 0
364
+ return Outcome([f"renamed {old} -> {e.name}" + (f" (updated {n} reference(s))" if n else "")], changed=True)
365
+
366
+ def _rewrite_refs(self, old: str, new: str) -> int:
367
+ """Rename every reference to an entity: triggers, conditions, values, send targets, links."""
368
+ count = 0
369
+ pat = re.compile(rf"(?<![\w.]){re.escape(old)}(?=\.)")
370
+ for x in self.state.entities.values():
371
+ for b in x.behaviors:
372
+ for key in ("on",):
373
+ for pre in ("message:", "input:", "change:"):
374
+ if b[key] == f"{pre}{old}" or b[key].startswith(f"{pre}{old}."):
375
+ b[key] = b[key].replace(f"{pre}{old}", f"{pre}{new}", 1)
376
+ count += 1
377
+ if b.get("with") == old:
378
+ b["with"] = new
379
+ count += 1
380
+ if b.get("if"):
381
+ nb = pat.sub(new, b["if"])
382
+ count += nb != b["if"]
383
+ b["if"] = nb
384
+ for a in b["do"]:
385
+ for k in ("value", "x", "y", "z"):
386
+ if isinstance(a.get(k), str):
387
+ nv = pat.sub(new, a[k])
388
+ count += nv != a[k]
389
+ a[k] = nv
390
+ if a.get("op") == "send" and a.get("to") and ident(a["to"]) == old:
391
+ a["to"] = new
392
+ count += 1
393
+ for k, v in list(x.props.items()):
394
+ if k in ("target", "follow", "for_entity", "spawn") and isinstance(v, str) and ident(v) == old:
395
+ x.props[k] = new
396
+ count += 1
397
+ for lid in list(self.state.links):
398
+ l = self.state.links[lid]
399
+ if old in lid.split("_to_"):
400
+ parts = lid.split("_to_")
401
+ nid = "_to_".join(new if p == old else p for p in parts)
402
+ if nid not in self.state.links:
403
+ l.id = nid
404
+ self.state.links[nid] = self.state.links.pop(lid)
405
+ count += 1
406
+ return count
407
+
408
+ def _dangling(self, gone: set[str]) -> list[str]:
409
+ """Behaviours that still mention deleted entities."""
410
+ msgs = []
411
+ for x in self.state.entities.values():
412
+ for b in x.behaviors:
413
+ text = " ".join([b["on"], b.get("if") or "", b.get("with") or ""] +
414
+ [str(a.get("value", "")) + " " + str(a.get("to", "")) for a in b["do"]])
415
+ hit = [g for g in gone if re.search(rf"(?<![\w]){re.escape(g)}(?![\w])", text)]
416
+ if hit:
417
+ msgs.append(f" warning: {x.name} still has a rule that mentions {', '.join(hit)} (on {b['on']})")
418
+ return msgs
419
+
420
+ def _op_connect(self, op: Op) -> Outcome:
421
+ src = self._target(op.target)
422
+ dst = self._target(op.dst)
423
+ if src.id == dst.id:
424
+ raise ValueError("cannot connect an entity to itself")
425
+ st = self.state
426
+ lid = f"{src.ident}_to_{dst.ident}"
427
+ i = 2
428
+ while lid in st.links:
429
+ lid = f"{src.ident}_to_{dst.ident}_{i}"
430
+ i += 1
431
+ props = dict(op.props)
432
+ if "fields" in props:
433
+ props["fields"] = [norm_name(f) for f in props["fields"]]
434
+ st.links[lid] = Link(lid, src.id, dst.id, op.via, props)
435
+ msg = f"connected {src.name} -> {dst.name}" + (f" via {op.via}" if op.via else "")
436
+ if src.domain != dst.domain:
437
+ msg += f" [cross-domain: {src.domain} -> {dst.domain}]"
438
+ return Outcome([msg], changed=True)
439
+
440
+ def _op_disconnect(self, op: Op) -> Outcome:
441
+ a = self._target(op.target)
442
+ b = self._target(op.dst)
443
+ ids = [l.id for l in self.state.links.values() if {l.src, l.dst} == {a.id, b.id}]
444
+ for i in ids:
445
+ self.state.links.pop(i)
446
+ return Outcome([f"removed {len(ids)} link(s) between {a.name} and {b.name}"], changed=bool(ids))
447
+
448
+ # ------------------------------------------------------------------ behaviours
449
+ def _split_ref(self, name: str) -> tuple[Entity | None, str]:
450
+ """'bob_lives' / 'bob.lives' / 'visits_count' -> (bob, 'lives') when bob is an entity."""
451
+ if "." in name:
452
+ ent, prop = name.split(".", 1)
453
+ e = self._by_ident(ent)
454
+ return (e, prop) if e else (None, name)
455
+ best = None
456
+ for e in self.state.entities.values():
457
+ for key in {e.ident, ident(e.kind)}:
458
+ if name.startswith(key + "_") and len(name) > len(key) + 1:
459
+ if best is None or len(key) > len(best[1]):
460
+ best = (e, key)
461
+ if best:
462
+ e, key = best
463
+ same_kind = [x for x in self.state.entities.values() if ident(x.kind) == key]
464
+ if key == ident(e.kind) and key != e.ident and len(same_kind) != 1:
465
+ return None, name
466
+ return e, name[len(key) + 1:]
467
+ return None, name
468
+
469
+ def _by_ident(self, s: str) -> Entity | None:
470
+ s = ident(s)
471
+ for e in self.state.entities.values():
472
+ if e.ident == s:
473
+ return e
474
+ kinds = [e for e in self.state.entities.values() if ident(e.kind) == s]
475
+ return kinds[-1] if len(kinds) == 1 else None
476
+
477
+ def _holder(self, prop: str, exclude: Entity | None = None, near: Entity | None = None) -> Entity | None:
478
+ """Best entity that owns a property: subtype/name match, then a link into `near`, then non-CAD, then last."""
479
+ hs = [x for x in self.state.entities.values() if prop in x.props and x is not exclude]
480
+ if not hs:
481
+ return None
482
+ if len(hs) == 1:
483
+ return hs[0]
484
+ named = [x for x in hs if prop in str(x.props.get("subtype", "")) or prop in x.name or prop in x.kind]
485
+ if len(named) == 1:
486
+ return named[0]
487
+ if near is not None:
488
+ linked = [x for x in hs if any(l.src == x.id and l.dst == near.id for l in self.state.links.values())]
489
+ if linked:
490
+ return linked[-1]
491
+ active = [x for x in hs if x.domain != "cad"]
492
+ return (active or hs)[-1]
493
+
494
+ def _op_behavior(self, op: Op) -> Outcome:
495
+ b0 = validate_behavior(op.behavior)
496
+ focus_targets = self._targets(op.target)
497
+ explicit = op.target is not None
498
+ default_owner = focus_targets[-1]
499
+ # 1. decide the owner of every action: the entity whose property it changes
500
+ groups: dict[str, list[dict]] = {}
501
+ order: list[str] = []
502
+ free: list[dict] = []
503
+ for a in b0["do"]:
504
+ a = dict(a)
505
+ owner = None
506
+ who = a.pop("__who", None)
507
+ if who:
508
+ for t in self._targets(who):
509
+ groups.setdefault(t.id, []).append(dict(a))
510
+ if t.id not in order:
511
+ order.append(t.id)
512
+ continue
513
+ if a["op"] in ("set", "add", "toggle"):
514
+ ent, prop = self._split_ref(a["prop"])
515
+ if ent is not None:
516
+ owner, a["prop"] = ent, prop
517
+ elif not explicit and a["prop"] not in default_owner.props:
518
+ owner = self._holder(a["prop"], near=default_owner)
519
+ elif a["op"] == "send" and not explicit:
520
+ fields = a.get("fields") or []
521
+ to = self.state.resolve(a["to"]) if a.get("to") else None
522
+ srcs = [self.state.entities[l.src] for l in self.state.links.values()
523
+ if to is not None and l.dst == to.id and l.src in self.state.entities]
524
+ holders = [self._holder(f) for f in fields if self._holder(f)]
525
+ if default_owner is to or (default_owner.id not in [s.id for s in srcs] and srcs):
526
+ owner = (holders or srcs or [None])[0]
527
+ if owner is None:
528
+ free.append(a)
529
+ continue
530
+ groups.setdefault(owner.id, []).append(a)
531
+ if owner.id not in order:
532
+ order.append(owner.id)
533
+ # actions with no property of their own (destroy, log, move, call ...) go with the first owner,
534
+ # or with the focus when no action names a property
535
+ # actions without a property of their own (destroy, log, move, call ...) stay with the rule's
536
+ # explicit owner, else go with the first action's owner, else with the focus
537
+ if free:
538
+ homes = focus_targets if (explicit or not order) else [self.state.entities[order[0]]]
539
+ for h in homes:
540
+ groups.setdefault(h.id, [])
541
+ groups[h.id] = groups[h.id] + [dict(a) for a in free]
542
+ if h.id not in order:
543
+ order.insert(0, h.id)
544
+ plan = [(self.state.entities[i], groups[i]) for i in order if i in groups]
545
+ msgs = []
546
+ for e, acts in plan:
547
+ if not acts:
548
+ continue
549
+ b = dict(b0, do=[dict(a) for a in acts])
550
+ # collision rule moved onto the partner: the partner's partner is the original owner
551
+ if b.get("with") and b["with"] in (e.ident, ident(e.kind)) and e is not default_owner:
552
+ b["with"] = default_owner.ident
553
+ b = self._qualify(b, e)
554
+ msgs += self._attach(e, b).messages
555
+ return Outcome(msgs, changed=True)
556
+
557
+ def _attach(self, e: Entity, b: dict) -> Outcome:
558
+ e.behaviors.append(b)
559
+ self.state.focus = e.id
560
+ # make sure referenced own properties exist (so code generators declare them),
561
+ # typed by how they are used
562
+ bool_names = set()
563
+ for expr in [b.get("if") or ""] + [a.get("value", "") for a in b["do"]]:
564
+ bool_names |= set(re.findall(r"!\s*([A-Za-z_]\w*)", expr))
565
+ bool_names |= set(re.findall(r"([A-Za-z_]\w*)\s*[!=]=\s*(?:true|false)\b", expr))
566
+ others = {x.ident for x in self.state.entities.values()} | {x.name.lower() for x in self.state.entities.values()}
567
+ for name in self._own_names(b):
568
+ if name in e.props or name in ("on",) or "." in name or name in COLOR_WORDS or name in others:
569
+ continue
570
+ e.props[name] = False if name in bool_names else 0
571
+ for a in b["do"]:
572
+ if a["op"] == "toggle" or (a["op"] == "set" and a["prop"] == "on"):
573
+ e.props.setdefault(a["prop"], a["prop"] in TRUE_BY_DEFAULT)
574
+ elif a["op"] == "set":
575
+ v = str(a["value"])
576
+ e.props.setdefault(a["prop"], "" if v[:1] in "\"'" else (False if v in ("true", "false") else 0))
577
+ elif a["op"] == "add":
578
+ e.props.setdefault(a["prop"], 0)
579
+ return Outcome([f"{e.name}: behaviour on {b['on']}" + (f" if {b['if']}" if b['if'] else "")
580
+ + f" -> {len(b['do'])} action(s)"], changed=True)
581
+
582
+ def _qualify(self, b: dict, owner: Entity) -> dict:
583
+ """Resolve every name in a behaviour relative to its owner:
584
+ own prop -> name ; other entity's prop -> entity.prop ; 'bob_lives' -> bob.lives ;
585
+ an unknown word compared with == / assigned (state == idle, set mode to eco) -> "string"."""
586
+ all_props = {k for x in self.state.entities.values() for k in x.props}
587
+
588
+ def resolve(n: str) -> str | None:
589
+ if n in ("true", "false"):
590
+ return n
591
+ if "." in n:
592
+ ent, prop = self._split_ref(n)
593
+ if ent is None:
594
+ return n
595
+ return prop if ent.id == owner.id else f"{ent.ident}.{prop}"
596
+ if n in owner.props:
597
+ return n
598
+ ent, prop = self._split_ref(n)
599
+ if ent is not None:
600
+ return prop if ent.id == owner.id else f"{ent.ident}.{prop}"
601
+ h = self._holder(n, exclude=owner, near=owner)
602
+ if h is not None:
603
+ return f"{h.ident}.{n}"
604
+ return None
605
+
606
+ def q(expr: str, assigned: bool = False) -> str:
607
+ toks = expr_tokens(expr)
608
+ out = []
609
+ for i, (k, v) in enumerate(toks):
610
+ if k == "id":
611
+ r = resolve(v)
612
+ prev = toks[i - 1][1] if i > 0 else ""
613
+ nxt = toks[i + 1][1] if i + 1 < len(toks) else ""
614
+ lone = len(toks) == 1
615
+ if r is None and v not in all_props and (prev in ("==", "!=") or nxt in ("==", "!=") and i > 0
616
+ or (assigned and lone)):
617
+ if prev in ("==", "!=") or (assigned and lone):
618
+ v = f'"{v}"' # state == idle -> state == "idle"
619
+ elif r is not None:
620
+ v = r
621
+ out.append(v)
622
+ return validate_expr(" ".join(out))
623
+ if b.get("if"):
624
+ try:
625
+ b["if"] = q(b["if"])
626
+ except ValueError:
627
+ pass
628
+ for a in b["do"]:
629
+ for k in ("value", "x", "y", "z"):
630
+ if k in a and isinstance(a[k], str):
631
+ try:
632
+ a[k] = q(a[k], assigned=(k == "value" and a["op"] == "set"))
633
+ except ValueError:
634
+ pass
635
+ if b["on"].startswith("change:"):
636
+ ent, prop = self._split_ref(b["on"][7:])
637
+ if ent is not None:
638
+ b["on"] = f"change:{prop}" if ent.id == owner.id else f"change:{ent.ident}.{prop}"
639
+ elif b["on"][7:] not in owner.props:
640
+ h = self._holder(b["on"][7:], exclude=owner, near=owner)
641
+ if h is not None:
642
+ b["on"] = f"change:{h.ident}.{b['on'][7:]}"
643
+ if a["op"] == "send" and a.get("to"):
644
+ t = self.state.resolve(a["to"])
645
+ if t:
646
+ a["to"] = t.name
647
+ if b["on"].startswith("input:"):
648
+ key = b["on"].split(":", 1)[1]
649
+ t = self.state.resolve(key.replace("_", " "))
650
+ if t and self._exact(key):
651
+ b["on"] = f"input:{t.ident}"
652
+ return b
653
+
654
+ def _exact(self, key: str) -> bool:
655
+ k = key.lower()
656
+ return any(k in (e.name.lower(), e.kind.lower(), e.ident) for e in self.state.entities.values())
657
+
658
+ @staticmethod
659
+ def _own_names(b: dict) -> list[str]:
660
+ names = []
661
+ if b.get("if"):
662
+ names += expr_names(b["if"])
663
+ for a in b["do"]:
664
+ for k in ("value",):
665
+ if k in a:
666
+ names += expr_names(a[k])
667
+ return names
668
+
669
+ def _op_domain(self, op: Op) -> Outcome:
670
+ m = modreg.get(op.domain)
671
+ if not m:
672
+ raise ValueError(f"unknown domain '{op.domain}'. Available: {', '.join(self.modules)}")
673
+ self.state.default_domain = m.name
674
+ return Outcome([f"default domain: {m.name} ({m.title})"], changed=True)
675
+
676
+ def _op_focus(self, op: Op) -> Outcome:
677
+ e = self._target(op.target)
678
+ self.state.focus = e.id
679
+ self.state.focus_group = []
680
+ return Outcome([f"now working on {e.name}"], changed=False)
681
+
682
+ @staticmethod
683
+ def _fmt(props: dict) -> str:
684
+ return "{" + ", ".join(f"{k}: {v!r}" for k, v in props.items() if not str(k).startswith("__")) + "}"
nlcl/ir.py ADDED
@@ -0,0 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Universal Computational Representation (IR).
2
+
3
+ Everything the user says is reduced to a small set of domain-independent
4
+ operations (Op) that mutate a persistent SystemState made of Entities and
5
+ Links. Domain modules (game, python, embedded, hardware, ...) only ever see
6
+ this representation, never the original natural language.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import copy
11
+ import json
12
+ import re
13
+ from dataclasses import asdict, dataclass, field
14
+ from typing import Any
15
+
16
+ # --------------------------------------------------------------------------
17
+ # Operations
18
+ # --------------------------------------------------------------------------
19
+
20
+ STATE_ACTIONS = {
21
+ "CREATE", # create entity (domain, kind, name, props, count, parent)
22
+ "SET", # set properties on target
23
+ "UNSET", # remove properties from target
24
+ "DELETE", # delete target
25
+ "CONNECT", # link target -> dst (via protocol)
26
+ "DISCONNECT", # remove link(s) between target and dst
27
+ "RENAME", # rename target to name
28
+ "BEHAVIOR", # attach behaviour rule to target
29
+ "DOMAIN", # set default domain for subsequent CREATEs
30
+ "FOCUS", # make target the current "it"
31
+ }
32
+ META_ACTIONS = {"SHOW", "BUILD", "RUN", "UNDO", "DEFINE", "HELP", "FIX", "SHELL"}
33
+ ACTIONS = STATE_ACTIONS | META_ACTIONS
34
+
35
+ PROTOCOLS = {"serial", "uart", "http", "mqtt", "gpio", "spi", "i2c", "udp", "websocket", "wire"}
36
+
37
+
38
+ @dataclass
39
+ class Op:
40
+ action: str
41
+ target: str | None = None
42
+ domain: str | None = None
43
+ kind: str | None = None
44
+ name: str | None = None
45
+ props: dict = field(default_factory=dict)
46
+ dst: str | None = None
47
+ via: str | None = None
48
+ behavior: dict | None = None
49
+ parent: str | None = None
50
+ count: int = 1
51
+ text: str | None = None # free argument (DEFINE body, SHOW what, BUILD dir ...)
52
+
53
+ def to_dict(self) -> dict:
54
+ d = asdict(self)
55
+ return {k: v for k, v in d.items()
56
+ if v not in (None, {}, []) and not (k == "count" and v == 1)}
57
+
58
+ @classmethod
59
+ def from_dict(cls, d: dict) -> "Op":
60
+ if not isinstance(d, dict):
61
+ raise ValueError(f"op must be an object, got {type(d).__name__}")
62
+ action = str(d.get("action", "")).upper()
63
+ if action not in ACTIONS:
64
+ raise ValueError(f"unknown action {action!r}")
65
+ known = {f for f in cls.__dataclass_fields__}
66
+ kw = {k: v for k, v in d.items() if k in known}
67
+ kw["action"] = action
68
+ if kw.get("props") is None:
69
+ kw["props"] = {}
70
+ if not isinstance(kw["props"], dict):
71
+ raise ValueError("props must be an object")
72
+ kw["props"] = {norm_name(k): v for k, v in kw["props"].items()}
73
+ if kw.get("domain"):
74
+ kw["domain"] = str(kw["domain"]).lower()
75
+ if kw.get("via"):
76
+ kw["via"] = str(kw["via"]).lower()
77
+ try:
78
+ kw["count"] = max(1, min(100, int(kw.get("count") or 1)))
79
+ except (TypeError, ValueError):
80
+ kw["count"] = 1
81
+ op = cls(**kw)
82
+ if op.behavior is not None:
83
+ op.behavior = validate_behavior(op.behavior)
84
+ return op
85
+
86
+ def __str__(self) -> str:
87
+ parts = []
88
+ for k, v in self.to_dict().items():
89
+ if k == "action":
90
+ continue
91
+ if k == "domain":
92
+ v = str(v).upper()
93
+ parts.append(f"{'type' if k == 'kind' else ('properties' if k == 'props' else k)}="
94
+ f"{json.dumps(v, ensure_ascii=False) if not isinstance(v, str) or k in ('name', 'text') else v}")
95
+ return f"{self.action}(" + ", ".join(parts) + ")"
96
+
97
+
98
+ # --------------------------------------------------------------------------
99
+ # Entities / links / state
100
+ # --------------------------------------------------------------------------
101
+
102
+ @dataclass
103
+ class Entity:
104
+ id: str
105
+ name: str
106
+ domain: str
107
+ kind: str
108
+ props: dict = field(default_factory=dict)
109
+ behaviors: list = field(default_factory=list)
110
+ parent: str | None = None
111
+
112
+ @property
113
+ def ident(self) -> str:
114
+ """Identifier-safe name (snake_case)."""
115
+ return ident(self.name)
116
+
117
+ @property
118
+ def class_name(self) -> str:
119
+ return pascal(self.name)
120
+
121
+
122
+ @dataclass
123
+ class Link:
124
+ id: str
125
+ src: str
126
+ dst: str
127
+ via: str | None = None
128
+ props: dict = field(default_factory=dict)
129
+
130
+
131
+ class SystemState:
132
+ """Persistent computational state built incrementally by instructions."""
133
+
134
+ def __init__(self, name: str = "project"):
135
+ self.name = name
136
+ self.entities: dict[str, Entity] = {}
137
+ self.links: dict[str, Link] = {}
138
+ self.focus: str | None = None
139
+ self.focus_group: list[str] = [] # entities made by the last "create 3 ..." (for "them")
140
+ self.default_domain: str | None = None
141
+ self.patches: list[dict] = []
142
+ self.shell_log: list[dict] = [] # terminal actions taken (exported as bash + PowerShell scripts) # fixes applied to generated files, re-applied on rebuild
143
+ self._counter = 0
144
+ self._undo: list[str] = []
145
+ self.history: list[str] = []
146
+
147
+ # ---- ids / snapshots -------------------------------------------------
148
+ def new_id(self, kind: str) -> str:
149
+ self._counter += 1
150
+ return f"{ident(kind) or 'obj'}_{self._counter}"
151
+
152
+ def snapshot(self) -> None:
153
+ self._undo.append(self.to_json())
154
+ if len(self._undo) > 200:
155
+ self._undo.pop(0)
156
+
157
+ def undo(self) -> bool:
158
+ if not self._undo:
159
+ return False
160
+ prev = SystemState.from_json(self._undo.pop())
161
+ undo_stack = self._undo
162
+ self.__dict__.update(prev.__dict__)
163
+ self._undo = undo_stack
164
+ return True
165
+
166
+ def clone(self) -> "SystemState":
167
+ c = SystemState.from_json(self.to_json())
168
+ return c
169
+
170
+ # ---- lookup ------------------------------------------------------------
171
+ def resolve(self, ref: str | None) -> Entity | None:
172
+ if ref is None or str(ref).lower() in {"it", "this", "that", "them", "آن", "این", "اون", "اینو", "اونو"}:
173
+ return self.entities.get(self.focus) if self.focus else None
174
+ r = str(ref).strip().lower()
175
+ r = re.sub(r"^(the|a|an)\s+", "", r)
176
+ if r in self.entities:
177
+ return self.entities[r]
178
+ by_name = [e for e in self.entities.values() if e.name.lower() == r or e.ident == ident(r)]
179
+ if by_name:
180
+ return by_name[-1]
181
+ by_kind = [e for e in self.entities.values() if e.kind.lower() == r or e.kind.lower() == singular(r)]
182
+ if by_kind:
183
+ return by_kind[-1]
184
+ # partial: "temperature sensor" -> entity named temp_sensor or kind sensor
185
+ words = [singular(w) for w in r.split()]
186
+ for e in reversed(list(self.entities.values())):
187
+ if e.kind.lower() in words or any(w and w in e.name.lower() for w in words if len(w) > 2):
188
+ return e
189
+ return None
190
+
191
+ def unique_name(self, base: str) -> str:
192
+ base = ident(base) or "obj"
193
+ names = {e.name for e in self.entities.values()}
194
+ if base not in names:
195
+ return base
196
+ i = 2
197
+ while f"{base}{i}" in names:
198
+ i += 1
199
+ return f"{base}{i}"
200
+
201
+ def children(self, eid: str) -> list[Entity]:
202
+ return [e for e in self.entities.values() if e.parent == eid]
203
+
204
+ def links_of(self, eid: str) -> list[Link]:
205
+ return [l for l in self.links.values() if eid in (l.src, l.dst)]
206
+
207
+ def domains(self) -> list[str]:
208
+ out: list[str] = []
209
+ for e in self.entities.values():
210
+ if e.domain not in out:
211
+ out.append(e.domain)
212
+ return out
213
+
214
+ def in_domain(self, domain: str) -> list[Entity]:
215
+ return [e for e in self.entities.values() if e.domain == domain]
216
+
217
+ # ---- serialisation -----------------------------------------------------
218
+ def to_dict(self) -> dict:
219
+ return {
220
+ "name": self.name,
221
+ "focus": self.focus,
222
+ "focus_group": self.focus_group,
223
+ "default_domain": self.default_domain,
224
+ "counter": self._counter,
225
+ "entities": [asdict(e) for e in self.entities.values()],
226
+ "links": [asdict(l) for l in self.links.values()],
227
+ "history": self.history,
228
+ "patches": self.patches,
229
+ "shell_log": self.shell_log,
230
+ }
231
+
232
+ def to_json(self, indent: int | None = None) -> str:
233
+ return json.dumps(self.to_dict(), ensure_ascii=False, indent=indent)
234
+
235
+ @classmethod
236
+ def from_dict(cls, d: dict) -> "SystemState":
237
+ s = cls(d.get("name", "project"))
238
+ s.focus = d.get("focus")
239
+ s.focus_group = list(d.get("focus_group", []))
240
+ s.default_domain = d.get("default_domain")
241
+ s._counter = d.get("counter", 0)
242
+ for e in d.get("entities", []):
243
+ s.entities[e["id"]] = Entity(**e)
244
+ for l in d.get("links", []):
245
+ s.links[l["id"]] = Link(**l)
246
+ s.history = list(d.get("history", []))
247
+ s.patches = list(d.get("patches", []))
248
+ s.shell_log = list(d.get("shell_log", []))
249
+ return s
250
+
251
+ @classmethod
252
+ def from_json(cls, text: str) -> "SystemState":
253
+ return cls.from_dict(json.loads(text))
254
+
255
+ def summary(self) -> str:
256
+ if not self.entities:
257
+ return "(empty system)"
258
+ lines = []
259
+ for e in self.entities.values():
260
+ mark = "*" if e.id == self.focus else " "
261
+ props = ", ".join(f"{k}={v!r}" for k, v in e.props.items())
262
+ par = f" in {self.entities[e.parent].name}" if e.parent in self.entities else ""
263
+ lines.append(f"{mark} [{e.domain}] {e.kind} '{e.name}' ({e.id}){par} {{{props}}}")
264
+ for b in e.behaviors:
265
+ lines.append(f" on {b['on']}" + (f" with {b['with']}" if b.get('with') else "")
266
+ + (f" if {b['if']}" if b.get('if') else "")
267
+ + " -> " + "; ".join(describe_action(a) for a in b["do"]))
268
+ for l in self.links.values():
269
+ s, d = self.entities.get(l.src), self.entities.get(l.dst)
270
+ if s and d:
271
+ extra = f" {l.props}" if l.props else ""
272
+ lines.append(f" link {s.name} -> {d.name} via {l.via or 'auto'}{extra}")
273
+ return "\n".join(lines)
274
+
275
+
276
+ # --------------------------------------------------------------------------
277
+ # Behaviours and expressions
278
+ # --------------------------------------------------------------------------
279
+ # A behaviour is {"on": trigger, "if": expr|None, "do": [action, ...]}
280
+ # triggers : start | update | collision | input:<key> | timer:<ms> |
281
+ # change:<prop> | message:<link-or-entity>
282
+ # actions : {"op":"set","prop":p,"value":expr} {"op":"add","prop":p,"value":expr}
283
+ # {"op":"toggle","prop":p} {"op":"destroy"} {"op":"log","text":s}
284
+ # {"op":"move","x":expr,"y":expr,"z":expr} {"op":"send","to":ref,"fields":[..]}
285
+ # {"op":"call","name":fn,"args":[expr..]}
286
+ # Expressions use a tiny C-like language: identifiers (entity properties),
287
+ # numbers, strings, true/false, + - * / % < > <= >= == != && || ! ( )
288
+
289
+ TRIGGER_RE = re.compile(r"^(start|update|collision|input:[\w ]+|timer:\d+|change:[\w.]+|message:[\w.\-]+)$")
290
+ ACTION_OPS = {"set", "add", "toggle", "destroy", "log", "move", "send", "call"}
291
+
292
+ _TOKEN_RE = re.compile(r"""\s*(?:
293
+ (?P<num>\d+(?:\.\d+)?) |
294
+ (?P<str>"[^"\n]*"|'[^'\n]*') |
295
+ (?P<op>&&|\|\||<=|>=|==|!=|[-+*/%<>!()]) |
296
+ (?P<id>[A-Za-z_][A-Za-z0-9_.]*)
297
+ )""", re.X)
298
+
299
+ _WORD_OPS = {"and": "&&", "or": "||", "not": "!", "True": "true", "False": "false"}
300
+
301
+
302
+ def expr_tokens(expr: str) -> list[tuple[str, str]]:
303
+ expr = str(expr)
304
+ pos, out = 0, []
305
+ while pos < len(expr):
306
+ if expr[pos:].strip() == "":
307
+ break
308
+ m = _TOKEN_RE.match(expr, pos)
309
+ if not m or m.end() == pos:
310
+ raise ValueError(f"bad expression near {expr[pos:]!r}")
311
+ pos = m.end()
312
+ kind = m.lastgroup
313
+ val = m.group(kind)
314
+ if kind == "id" and val in _WORD_OPS:
315
+ val = _WORD_OPS[val]
316
+ kind = "op" if val not in ("true", "false") else "id"
317
+ out.append((kind, val))
318
+ return out
319
+
320
+
321
+ def validate_expr(expr: Any) -> str:
322
+ """Return normalised expression text or raise ValueError."""
323
+ if isinstance(expr, bool):
324
+ return "true" if expr else "false"
325
+ if isinstance(expr, (int, float)):
326
+ return repr(expr)
327
+ toks = expr_tokens(str(expr))
328
+ if not toks:
329
+ raise ValueError("empty expression")
330
+ depth = 0
331
+ for k, v in toks:
332
+ if v == "(":
333
+ depth += 1
334
+ elif v == ")":
335
+ depth -= 1
336
+ if depth < 0:
337
+ raise ValueError("unbalanced parentheses")
338
+ if depth:
339
+ raise ValueError("unbalanced parentheses")
340
+ # unary minus glued to its number: "- 10" -> "-10"
341
+ out: list[str] = []
342
+ for i, (k, v) in enumerate(toks):
343
+ if k == "num" and out and out[-1] == "-" and (len(out) == 1 or out[-2] in
344
+ ("(", "+", "-", "*", "/", "%", "<", ">", "<=", ">=", "==", "!=", "&&", "||", "!")):
345
+ out[-1] = "-" + v
346
+ else:
347
+ out.append(v)
348
+ s = " ".join(out)
349
+ return re.sub(r"\(\s+", "(", re.sub(r"\s+\)", ")", s))
350
+
351
+
352
+ def expr_names(expr: str) -> list[str]:
353
+ return [v for k, v in expr_tokens(expr) if k == "id" and v not in ("true", "false")]
354
+
355
+
356
+ def render_expr(expr: Any, lang: str, name=lambda n: n) -> str:
357
+ """Render a normalised expression for a target language.
358
+
359
+ lang: python | c | cpp | csharp | js | gdscript | verilog | openscad
360
+ name: callback mapping a property identifier to target syntax
361
+ (e.g. lambda n: f"self.{n}").
362
+ """
363
+ toks = expr_tokens(validate_expr(expr))
364
+ out = []
365
+ for k, v in toks:
366
+ if k == "id":
367
+ if v in ("true", "false"):
368
+ if lang == "python":
369
+ v = v.capitalize()
370
+ elif lang == "verilog":
371
+ v = "1'b1" if v == "true" else "1'b0"
372
+ else:
373
+ v = name(v)
374
+ elif k == "op" and lang in ("python", "gdscript"):
375
+ v = {"&&": "and", "||": "or", "!": "not "}.get(v, v)
376
+ elif k == "str" and lang in ("c", "cpp", "csharp", "verilog") and v.startswith("'"):
377
+ v = '"' + v[1:-1].replace('"', '\\"') + '"'
378
+ out.append(v)
379
+ s = " ".join(out)
380
+ s = re.sub(r"\(\s+", "(", s)
381
+ s = re.sub(r"\s+\)", ")", s)
382
+ s = s.replace("not ", "not ").replace("! ", "!")
383
+ return s
384
+
385
+
386
+ def eval_expr(expr: Any, env: dict) -> Any:
387
+ """Evaluate a validated expression against a dict of names (design-time)."""
388
+ code = render_expr(expr, "python", name=lambda n: f"_env.get({n!r}, 0)")
389
+ try:
390
+ return eval(code, {"__builtins__": {}}, {"_env": env}) # tokens are whitelisted by expr_tokens
391
+ except Exception as e:
392
+ raise ValueError(f"cannot evaluate {expr!r}: {e}") from None
393
+
394
+
395
+ def validate_behavior(b: Any) -> dict:
396
+ if not isinstance(b, dict):
397
+ raise ValueError("behavior must be an object")
398
+ on = str(b.get("on") or "update").strip().lower()
399
+ if not TRIGGER_RE.match(on):
400
+ raise ValueError(f"bad trigger {on!r}")
401
+ cond = b.get("if")
402
+ cond = validate_expr(cond) if cond not in (None, "", True) else None
403
+ acts = b.get("do")
404
+ if isinstance(acts, dict):
405
+ acts = [acts]
406
+ if not acts or not isinstance(acts, list):
407
+ raise ValueError("behavior needs at least one action in 'do'")
408
+ clean = []
409
+ for a in acts:
410
+ if not isinstance(a, dict) or str(a.get("op", "")).lower() not in ACTION_OPS:
411
+ raise ValueError(f"bad action {a!r}")
412
+ a = dict(a)
413
+ a["op"] = a["op"].lower()
414
+ if a["op"] in ("set", "add", "toggle"):
415
+ if not a.get("prop"):
416
+ raise ValueError(f"action {a['op']} needs 'prop'")
417
+ a["prop"] = norm_name(a["prop"])
418
+ if a["op"] in ("set", "add"):
419
+ a["value"] = validate_expr(a.get("value", 1 if a["op"] == "add" else 0))
420
+ if a["op"] == "move":
421
+ for ax in ("x", "y", "z"):
422
+ a[ax] = validate_expr(a.get(ax, 0))
423
+ if a["op"] == "log":
424
+ a["text"] = str(a.get("text", ""))
425
+ if a["op"] == "send":
426
+ a["fields"] = [norm_name(f) for f in a.get("fields", [])]
427
+ if a["op"] == "call":
428
+ a["name"] = ident(a.get("name", "fn"))
429
+ a["args"] = [validate_expr(x) for x in a.get("args", [])]
430
+ clean.append(a)
431
+ out = {"on": on, "if": cond, "do": clean}
432
+ if b.get("with") and on == "collision":
433
+ out["with"] = ident(str(b["with"])) # collision partner (entity name or kind)
434
+ return out
435
+
436
+
437
+ def describe_action(a: dict) -> str:
438
+ op = a["op"]
439
+ if op == "set":
440
+ return f"{a['prop']} = {a['value']}"
441
+ if op == "add":
442
+ v = str(a["value"])
443
+ if re.fullmatch(r"-[\d.]+", v):
444
+ return f"{a['prop']} -= {v[1:]}"
445
+ if v.startswith("-(") and v.endswith(")"):
446
+ return f"{a['prop']} -= {v[2:-1]}"
447
+ return f"{a['prop']} += {v}"
448
+ if op == "toggle":
449
+ return f"toggle {a['prop']}"
450
+ if op == "move":
451
+ return f"move ({a['x']}, {a['y']}, {a['z']})"
452
+ if op == "log":
453
+ return f"log {a['text']!r}"
454
+ if op == "send":
455
+ return f"send {a.get('fields') or 'state'} to {a.get('to') or 'links'}"
456
+ if op == "call":
457
+ return f"{a['name']}({', '.join(a['args'])})"
458
+ return op
459
+
460
+
461
+ # --------------------------------------------------------------------------
462
+ # Naming helpers (shared with modules)
463
+ # --------------------------------------------------------------------------
464
+
465
+ _SYN = {
466
+ "hp": "health", "life": "health", "lives": "lives", "moveable": "movable",
467
+ "collision_detection": "collision", "collisions": "collision", "collider": "collision",
468
+ "colour": "color", "temp": "temperature", "velocity": "speed",
469
+ }
470
+
471
+
472
+ def norm_name(s: Any) -> str:
473
+ n = ident(str(s))
474
+ return _SYN.get(n, n)
475
+
476
+
477
+ _FA_LATIN = {
478
+ "ا": "a", "آ": "a", "أ": "a", "إ": "e", "ب": "b", "پ": "p", "ت": "t", "ث": "s", "ج": "j", "چ": "ch",
479
+ "ح": "h", "خ": "kh", "د": "d", "ذ": "z", "ر": "r", "ز": "z", "ژ": "zh", "س": "s", "ش": "sh", "ص": "s",
480
+ "ض": "z", "ط": "t", "ظ": "z", "ع": "a", "غ": "gh", "ف": "f", "ق": "gh", "ک": "k", "ك": "k", "گ": "g",
481
+ "ل": "l", "م": "m", "ن": "n", "و": "v", "ه": "h", "ة": "h", "ی": "i", "ي": "i", "ئ": "y", "ؤ": "o",
482
+ "ء": "", "‌": "_", "ـ": "",
483
+ }
484
+
485
+
486
+ def transliterate(s: str) -> str:
487
+ """Persian/Arabic letters -> ASCII so every target language gets a valid identifier."""
488
+ return "".join(_FA_LATIN.get(c, c) for c in s)
489
+
490
+
491
+ def ident(s: str) -> str:
492
+ raw = str(s).strip()
493
+ s = re.sub(r"[^0-9A-Za-z_]+", "_", transliterate(raw)).strip("_").lower()
494
+ if not s and raw:
495
+ import zlib
496
+ s = f"e_{zlib.crc32(raw.encode('utf-8')):08x}"
497
+ if s and s[0].isdigit():
498
+ s = "n" + s
499
+ return s
500
+
501
+
502
+ def pascal(s: str) -> str:
503
+ return "".join(p[:1].upper() + p[1:] for p in ident(s).split("_") if p) or "Obj"
504
+
505
+
506
+ def camel(s: str) -> str:
507
+ p = pascal(s)
508
+ return p[:1].lower() + p[1:]
509
+
510
+
511
+ def singular(w: str) -> str:
512
+ w = w.lower()
513
+ if w.endswith(("us", "is", "ss", "os", "ics")) or w in ("gas", "lens", "alias", "atlas", "canvas", "series"):
514
+ return w # torus, status, axis, chassis, physics ...
515
+ if len(w) > 4 and w.endswith("ies"):
516
+ return w[:-3] + "y"
517
+ if len(w) > 3 and w.endswith("es") and w[-3] in "sxz":
518
+ return w[:-2]
519
+ if len(w) > 3 and w.endswith("s") and not w.endswith("ss"):
520
+ return w[:-1]
521
+ return w
522
+
523
+
524
+ def parse_value(v: str) -> Any:
525
+ if isinstance(v, (int, float, bool)):
526
+ return v
527
+ s = str(v).strip()
528
+ low = s.lower()
529
+ if low in ("true", "yes", "on", "enabled", "روشن"):
530
+ return True
531
+ if low in ("false", "no", "off", "disabled", "خاموش"):
532
+ return False
533
+ if re.fullmatch(r"-?\d+", s):
534
+ return int(s)
535
+ if re.fullmatch(r"-?\d+\.\d*|-?\.\d+", s):
536
+ return float(s)
537
+ if len(s) >= 2 and s[0] == s[-1] and s[0] in "\"'":
538
+ return s[1:-1]
539
+ return s
540
+
541
+
542
+ def deep_copy(x):
543
+ return copy.deepcopy(x)
nlcl/kb/core.pl ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % =====================================================================
2
+ % NLCL semantic knowledge base - core rules (standard Prolog).
3
+ % Loaded by nlcl/knowledge.py into the embedded engine; also loadable in
4
+ % SWI-Prolog after `:kb export` (which adds the facts below as clauses).
5
+ %
6
+ % Facts asserted at start-up from the Python side:
7
+ % atomic(Word, Token). core lexicon (tokens.py)
8
+ % kind_of(Kind, Domain, Strength). ontology from the modules: 2 = kind, 1 = keyword
9
+ % alias(Word, Domain). words that name a domain
10
+ % Learned facts (learned.pl, written by the trainer / by confirmations):
11
+ % rewrite(FromWords, ToWords, Support). learned meaning: [get,rid,of] -> [delete]
12
+ % reliability(Key, Successes, Failures). evidence for a token / frame / intent
13
+ % param(Name, Value). parameters of the sentence-weighting model
14
+ % learned_module(Name, Language, Ext). modules discovered at run time
15
+ % =====================================================================
16
+
17
+ :- dynamic rewrite/3.
18
+ :- dynamic reliability/3.
19
+ :- dynamic param/2.
20
+ :- dynamic learned_module/3.
21
+
22
+ % ---------------------------------------------------------------- domains
23
+ domain_candidates(Kind, Ds) :- findall(D, kind_of(Kind, D, 2), L), L \= [], !, sort(L, Ds).
24
+ domain_candidates(Kind, Ds) :- findall(D, kind_of(Kind, D, 1), L), sort(L, Ds).
25
+ unambiguous_domain(Kind, D) :- domain_candidates(Kind, [D]).
26
+ ambiguous_kind(Kind) :- domain_candidates(Kind, [_, _ | _]).
27
+
28
+ % ---------------------------------------------------------------- reliability
29
+ % Beta(1,1) posterior mean of the evidence collected for a key.
30
+ reliable(Key, P) :- reliability(Key, S, F), !, P is (S + 1) / (S + F + 2).
31
+ reliable(Key, P) :- prior(Key, P), !.
32
+ reliable(_, 0.75).
33
+
34
+ prior(token(_), 0.9).
35
+ prior(frame(_), 0.85).
36
+ prior(rewrite(_), 0.7).
37
+ prior(intent(_), 0.85).
38
+
39
+ % a learned rewrite may not turn a core word into a different core meaning
40
+ conflict(From, To) :- rewrite([From], [To], _), atomic(From, T1), atomic(To, T2), T1 \== T2.
41
+
42
+ % ---------------------------------------------------------------- terminal: meaning of intents
43
+ % shell_intent(Intent, SafetyClass, Description).
44
+ shell_intent(list_files, read, 'list files or folders').
45
+ shell_intent(count_files, read, 'count files').
46
+ shell_intent(show_file, read, 'print a file (or its first / last lines)').
47
+ shell_intent(count_lines, read, 'count the lines of a file').
48
+ shell_intent(search_text, read, 'find text inside files').
49
+ shell_intent(find_large, read, 'find files larger than a size').
50
+ shell_intent(disk_usage, read, 'size of a folder').
51
+ shell_intent(sort_lines, read, 'print the lines of a file sorted').
52
+ shell_intent(current_dir, read, 'print the working folder').
53
+ shell_intent(make_dir, create, 'create a folder').
54
+ shell_intent(make_file, create, 'create a file, optionally with text').
55
+ shell_intent(append_text, modify, 'add a line to the end of a file').
56
+ shell_intent(copy, create, 'copy files or folders').
57
+ shell_intent(archive, create, 'pack files into a zip archive').
58
+ shell_intent(move, modify, 'move or rename files').
59
+ shell_intent(replace_text, modify, 'replace text inside a file').
60
+ shell_intent(delete, destroy, 'delete files or folders').
61
+
62
+ changes_files(I) :- shell_intent(I, S, _), S \== read.
63
+ needs_confirmation(I) :- shell_intent(I, S, _), memberchk(S, [modify, destroy]).
64
+
65
+ % paths a destructive command may never touch
66
+ protected_path('/'). protected_path('~'). protected_path('.'). protected_path('..').
67
+ protected_path('*'). protected_path('.git'). protected_path('C:/'). protected_path('C:\\').
68
+ forbidden(I, P) :- shell_intent(I, destroy, _), protected_path(P).
69
+ forbidden(I, P) :- shell_intent(I, destroy, _), sub_atom(P, 0, _, _, '.git/').
70
+
71
+ % ---------------------------------------------------------------- terminal: words for file types
72
+ file_type(python, ['*.py']).
73
+ file_type(py, ['*.py']).
74
+ file_type(javascript, ['*.js']).
75
+ file_type(js, ['*.js']).
76
+ file_type(typescript, ['*.ts']).
77
+ file_type(text, ['*.txt']).
78
+ file_type(txt, ['*.txt']).
79
+ file_type(markdown, ['*.md']).
80
+ file_type(md, ['*.md']).
81
+ file_type(json, ['*.json']).
82
+ file_type(csv, ['*.csv']).
83
+ file_type(log, ['*.log']).
84
+ file_type(temporary, ['*.tmp']).
85
+ file_type(temp, ['*.tmp']).
86
+ file_type(tmp, ['*.tmp']).
87
+ file_type(backup, ['*.bak']).
88
+ file_type(bak, ['*.bak']).
89
+ file_type(html, ['*.html']).
90
+ file_type(css, ['*.css']).
91
+ file_type(c, ['*.c']).
92
+ file_type(cpp, ['*.cpp']).
93
+ file_type(header, ['*.h']).
94
+ file_type(java, ['*.java']).
95
+ file_type(rust, ['*.rs']).
96
+ file_type(go, ['*.go']).
97
+ file_type(shell, ['*.sh']).
98
+ file_type(yaml, ['*.yml']).
99
+ file_type(xml, ['*.xml']).
100
+ file_type(pdf, ['*.pdf']).
101
+ file_type(zip, ['*.zip']).
102
+ file_type(image, ['*.png', '*.jpg', '*.jpeg', '*.gif']).
103
+ file_type(picture, ['*.png', '*.jpg', '*.jpeg', '*.gif']).
104
+ file_type(photo, ['*.png', '*.jpg', '*.jpeg', '*.gif']).
105
+ file_type(verilog, ['*.v']).
106
+ file_type(arduino, ['*.ino']).
107
+
108
+ % ---------------------------------------------------------------- module discovery
109
+ % language(Name, Extension, RunHint) - targets the system can grow a module for
110
+ language(rust, '.rs', 'cargo run / rustc main.rs').
111
+ language(go, '.go', 'go run .').
112
+ language(java, '.java', 'javac *.java && java Main').
113
+ language(kotlin, '.kt', 'kotlinc *.kt -include-runtime -d app.jar').
114
+ language(csharp, '.cs', 'dotnet run').
115
+ language(typescript, '.ts', 'npx tsc && node main.js').
116
+ language(javascript, '.js', 'node main.js').
117
+ language(ruby, '.rb', 'ruby main.rb').
118
+ language(php, '.php', 'php main.php').
119
+ language(lua, '.lua', 'lua main.lua').
120
+ language(swift, '.swift', 'swift main.swift').
121
+ language(dart, '.dart', 'dart run').
122
+ language(julia, '.jl', 'julia main.jl').
123
+ language(r, '.R', 'Rscript main.R').
124
+ language(haskell, '.hs', 'runghc Main.hs').
125
+ language(scala, '.scala', 'scala main.scala').
126
+ language(elixir, '.ex', 'elixir main.ex').
127
+ language(zig, '.zig', 'zig run main.zig').
128
+ language(prolog, '.pl', 'swipl main.pl').
129
+ language(sql, '.sql', 'sqlite3 app.db < schema.sql').
130
+ language(bash, '.sh', 'bash main.sh').
131
+ language(powershell, '.ps1', 'powershell -File main.ps1').
132
+ language(matlab, '.m', 'octave main.m').
133
+
134
+ discoverable(Name) :- language(Name, _, _), \+ learned_module(Name, _, _).
nlcl/kb/pretrained.pl ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ % NLCL pretrained knowledge (training split only) - written 2026-11-16 18:26:25
2
+ % (plain Prolog facts: edit, delete or load them in SWI-Prolog)
3
+
4
+ % rewrite/3
5
+ rewrite(['store\'s'],[store],1).
6
+ rewrite([get,rid,of],[delete],1).
7
+ rewrite([the,game],[],1).
8
+
9
+ % reliability/3
10
+ reliability(frame(behavior),18,1).
11
+ reliability(frame(connect_to),2,0).
12
+ reliability(frame(create_object),22,4).
13
+ reliability(frame(delete_object),5,0).
14
+ reliability(frame(move_object),0,1).
15
+ reliability(frame(rename_object),2,0).
16
+ reliability(frame(set_property),12,13).
17
+ reliability(frame(special),11,0).
18
+ reliability(intent(archive),3,0).
19
+ reliability(intent(copy),3,0).
20
+ reliability(intent(count_files),3,0).
21
+ reliability(intent(count_lines),3,0).
22
+ reliability(intent(delete),3,0).
23
+ reliability(intent(list_files),3,0).
24
+ reliability(intent(make_dir),3,0).
25
+ reliability(intent(move),3,0).
26
+ reliability(intent(replace_text),3,0).
27
+ reliability(intent(search_text),3,0).
28
+ reliability(intent(show_file),3,0).
29
+
30
+ % param/2
31
+ param(bias,-1.11072).
32
+ param(coverage,2.257904).
33
+ param(dry_errors,-2.4).
34
+ param(errors,-2.2).
35
+ param(frame_rel,0.858535).
36
+ param(fuzzy,-0.9).
37
+ param(inferred,-0.404714).
38
+ param(llm,0.4).
39
+ param(missing_paths,-1.8).
40
+ param(n_ops,-0.292096).
41
+ param(notes,-0.65517).
42
+ param(novel,-1.853353).
43
+ param(question,-0.6).
44
+ param(reliability,0.957997).
45
+ param(shell,1.213662).
46
+ param(unknown,-0.9).
47
+ param(verbless,-1.796907).
48
+ param(warnings,-0.25).
49
+
nlcl/knowledge.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The semantic knowledge base: a Prolog database the interpreter reasons with and learns into.
2
+
3
+ core.pl rules (domain inference, reliability, terminal meanings and safety, languages)
4
+ start-up facts the core lexicon and the module ontology, asserted from Python
5
+ learned.pl what the interpreter has learned (rewrites, evidence counts, weighting parameters,
6
+ discovered modules) - plain Prolog facts, human-readable, loadable by SWI-Prolog
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from pathlib import Path
12
+
13
+ from .prolog import Prolog, PrologError, fmt, from_python, mk_list, Atom, Struct
14
+
15
+ CORE = Path(__file__).parent / "kb" / "core.pl"
16
+ PRETRAINED = Path(__file__).parent / "kb" / "pretrained.pl" # learned from the corpus' TRAINING split only
17
+ LEARNED_PREDICATES = (("rewrite", 3), ("reliability", 3), ("param", 2), ("learned_module", 3))
18
+
19
+
20
+ def _atom(s) -> str:
21
+ return fmt(Atom(str(s)))
22
+
23
+
24
+ class Knowledge:
25
+ def __init__(self, home: Path | str | None = None, modules: dict | None = None, atomic: dict | None = None,
26
+ pretrained: bool = False):
27
+ self.home = Path(home) if home else None
28
+ self.pl = Prolog()
29
+ self.pl.consult(CORE)
30
+ if atomic is None:
31
+ from .tokens import ATOMIC
32
+ atomic = ATOMIC
33
+ for tok, words in atomic.items():
34
+ for w in words:
35
+ self.pl.add_clause(Struct("atomic", (Atom(w), Atom(tok))))
36
+ self.load_modules(modules or {})
37
+ if pretrained and PRETRAINED.exists() and not (self.learned_path and self.learned_path.exists()):
38
+ self.pl.consult(PRETRAINED) # a fresh install starts from what was learned in training
39
+ if self.learned_path and self.learned_path.exists():
40
+ try:
41
+ self.pl.consult(self.learned_path)
42
+ except PrologError as e: # a damaged learned file must not stop the system
43
+ print(f"[nlcl] warning: could not load {self.learned_path}: {e}")
44
+
45
+ @property
46
+ def learned_path(self) -> Path | None:
47
+ return self.home / "learned.pl" if self.home else None
48
+
49
+ def load_modules(self, modules: dict) -> None:
50
+ self.pl.retract_all("kind_of", 3)
51
+ self.pl.retract_all("alias", 2)
52
+ for m in modules.values():
53
+ for k in m.kinds:
54
+ self.pl.add_clause(Struct("kind_of", (Atom(k.lower()), Atom(m.name), 2)))
55
+ for k in m.keywords:
56
+ self.pl.add_clause(Struct("kind_of", (Atom(k.lower()), Atom(m.name), 1)))
57
+ for a in (m.name, *m.aliases):
58
+ self.pl.add_clause(Struct("alias", (Atom(a.lower()), Atom(m.name))))
59
+
60
+ # ------------------------------------------------------------------ queries
61
+ def query(self, text: str, limit: int = 50) -> list[dict]:
62
+ return self.pl.query(text, limit=limit)
63
+
64
+ def domain_candidates(self, kind: str) -> list[str]:
65
+ r = self.pl.query(f"domain_candidates({_atom(kind.lower())}, Ds)", limit=1)
66
+ return r[0]["Ds"] if r else []
67
+
68
+ def reliability(self, key: str) -> float:
69
+ r = self.pl.query(f"reliable({key}, P)", limit=1)
70
+ return float(r[0]["P"]) if r else 0.75
71
+
72
+ def shell_intent(self, intent: str) -> tuple[str, str] | None:
73
+ r = self.pl.query(f"shell_intent({_atom(intent)}, S, D)", limit=1)
74
+ return (r[0]["S"], r[0]["D"]) if r else None
75
+
76
+ def needs_confirmation(self, intent: str) -> bool:
77
+ return self.pl.ask(f"needs_confirmation({_atom(intent)})")
78
+
79
+ def forbidden(self, intent: str, path: str) -> bool:
80
+ p = str(path).replace("\\", "/").rstrip("/") or "/"
81
+ return self.pl.ask(f"forbidden({_atom(intent)}, {_atom(p)})") or \
82
+ self.pl.ask(f"forbidden({_atom(intent)}, {_atom(p + '/')})")
83
+
84
+ def file_type(self, word: str) -> list[str] | None:
85
+ w = word.lower().rstrip("s") if word.lower() not in ("js", "ts", "css") else word.lower()
86
+ for cand in (word.lower(), w):
87
+ r = self.pl.query(f"file_type({_atom(cand)}, P)", limit=1)
88
+ if r:
89
+ return list(r[0]["P"])
90
+ return None
91
+
92
+ def language(self, name: str) -> tuple[str, str] | None:
93
+ r = self.pl.query(f"language({_atom(name.lower())}, E, H)", limit=1)
94
+ return (r[0]["E"], r[0]["H"]) if r else None
95
+
96
+ def languages(self) -> list[str]:
97
+ return [r["N"] for r in self.pl.query("language(N, _, _)", limit=200)]
98
+
99
+ def learned_modules(self) -> list[tuple[str, str, str]]:
100
+ return [(r["N"], r["L"], r["E"]) for r in self.pl.query("learned_module(N, L, E)", limit=200)]
101
+
102
+ # ------------------------------------------------------------------ learned knowledge
103
+ def rewrites(self) -> list[tuple[list[str], list[str], int]]:
104
+ out = []
105
+ for r in self.pl.query("rewrite(F, T, S)", limit=10000):
106
+ out.append((list(r["F"]), list(r["T"]), int(r["S"])))
107
+ # longest phrases first so "get rid of" wins over "get"
108
+ return sorted(out, key=lambda x: -len(x[0]))
109
+
110
+ def add_rewrite(self, frm: list[str], to: list[str], support: int = 1) -> None:
111
+ f, t = mk_list([Atom(w) for w in frm]), mk_list([Atom(w) for w in to])
112
+ self.pl.retract_all("rewrite", 3, lambda c: fmt(c.args[0]) == fmt(f))
113
+ self.pl.add_clause(Struct("rewrite", (f, t, int(support))))
114
+
115
+ def remove_rewrite(self, frm: list[str]) -> bool:
116
+ f = fmt(mk_list([Atom(w) for w in frm]))
117
+ before = len(self.pl.db.get(("rewrite", 3), []))
118
+ self.pl.retract_all("rewrite", 3, lambda c: fmt(c.args[0]) == f)
119
+ return len(self.pl.db.get(("rewrite", 3), [])) < before
120
+
121
+ def record(self, key: str, ok: bool, n: int = 1) -> None:
122
+ """Add evidence for a token / frame / intent / rewrite key (term text, e.g. frame(create_object))."""
123
+ from .prolog import parse_term
124
+ k = parse_term(key)[0]
125
+ lst = self.pl.db.setdefault(("reliability", 3), [])
126
+ for i, c in enumerate(lst):
127
+ if fmt(c.args[0]) == fmt(k):
128
+ s, f = c.args[1], c.args[2]
129
+ lst[i] = Struct("reliability", (k, s + (n if ok else 0), f + (0 if ok else n)))
130
+ return
131
+ lst.append(Struct("reliability", (k, n if ok else 0, 0 if ok else n)))
132
+
133
+ def params(self) -> dict[str, float]:
134
+ return {r["N"]: float(r["V"]) for r in self.pl.query("param(N, V)", limit=1000)}
135
+
136
+ def set_params(self, params: dict[str, float]) -> None:
137
+ self.pl.retract_all("param", 2)
138
+ for k, v in params.items():
139
+ self.pl.add_clause(Struct("param", (Atom(k), float(round(v, 6)))))
140
+
141
+ def add_learned_module(self, name: str, language: str, ext: str) -> None:
142
+ self.pl.retract_all("learned_module", 3, lambda c: fmt(c.args[0]) == _atom(name))
143
+ self.pl.add_clause(Struct("learned_module", (Atom(name), Atom(language), Atom(ext))))
144
+
145
+ def reset_learned(self) -> None:
146
+ for name, ar in LEARNED_PREDICATES:
147
+ self.pl.retract_all(name, ar)
148
+
149
+ # ------------------------------------------------------------------ persistence
150
+ def learned_text(self) -> str:
151
+ lines = [f"% NLCL learned knowledge - written {time.strftime('%Y-%m-%d %H:%M:%S')}",
152
+ "% (plain Prolog facts: edit, delete or load them in SWI-Prolog)", ""]
153
+ for name, ar in LEARNED_PREDICATES:
154
+ clauses = self.pl.db.get((name, ar), [])
155
+ if clauses:
156
+ lines.append(f"% {name}/{ar}")
157
+ lines += sorted(fmt(c) + "." for c in clauses)
158
+ lines.append("")
159
+ return "\n".join(lines) + "\n"
160
+
161
+ def save(self) -> Path | None:
162
+ if not self.learned_path:
163
+ return None
164
+ self.learned_path.parent.mkdir(parents=True, exist_ok=True)
165
+ self.learned_path.write_text(self.learned_text(), encoding="utf-8")
166
+ return self.learned_path
167
+
168
+ def export(self, path: Path | str) -> Path:
169
+ """Everything (core rules + start-up facts + learned facts) as one SWI-Prolog file."""
170
+ path = Path(path)
171
+ facts = []
172
+ for (name, ar), clauses in sorted(self.pl.db.items()):
173
+ if name in ("atomic", "kind_of", "alias"):
174
+ facts += [fmt(c) + "." for c in clauses]
175
+ path.write_text(CORE.read_text(encoding="utf-8") + "\n% ---- facts from the lexicon and the modules\n"
176
+ + "\n".join(facts) + "\n\n" + self.learned_text(), encoding="utf-8")
177
+ return path
178
+
179
+ def stats(self) -> dict:
180
+ return {"rewrites": len(self.pl.db.get(("rewrite", 3), [])),
181
+ "evidence": len(self.pl.db.get(("reliability", 3), [])),
182
+ "params": len(self.pl.db.get(("param", 2), [])),
183
+ "learned_modules": len(self.pl.db.get(("learned_module", 3), [])),
184
+ "lexicon": len(self.pl.db.get(("atomic", 2), [])),
185
+ "ontology": len(self.pl.db.get(("kind_of", 3), []))}
186
+
187
+ def to_term(self, v) -> str:
188
+ return fmt(from_python(v))
nlcl/learn.py ADDED
@@ -0,0 +1,308 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Training and testing of the interpreter's semantic knowledge.
2
+
3
+ Correctness is *semantic*: an interpretation is right when applying it produces the same system state
4
+ as the canonical (gold) sentence - not when the text or the IR string matches.
5
+
6
+ train() 1. induces rewrite rules (new meanings for words / phrases) from failed examples; a rule is kept
7
+ only if it fixes examples and breaks none of the training examples that were already right
8
+ 2. records evidence (reliability counts) for every frame / intent used
9
+ 3. fits the sentence-weighting model on the training examples
10
+ -> everything is written to the Prolog knowledge base (learned.pl)
11
+ evaluate() the same measurements on held-out sentences (never seen during training)
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import time
17
+ from dataclasses import dataclass, field
18
+ from pathlib import Path
19
+
20
+ from . import weights as wmod
21
+ from .interpreter import Interpreter
22
+ from .ir import SystemState
23
+
24
+
25
+ @dataclass
26
+ class Example:
27
+ id: str
28
+ text: str
29
+ split: str # train | test
30
+ context: list[str] = field(default_factory=list)
31
+ gold: list[str] = field(default_factory=list) # canonical sentences; [] + valid=False -> must not execute
32
+ valid: bool = True
33
+ intent: str = ""
34
+
35
+
36
+ def load_corpus(path: Path | str | None = None) -> list[Example]:
37
+ from .bench.corpus import build_examples
38
+ if path is None:
39
+ return build_examples()
40
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
41
+ return [Example(**d) for d in data]
42
+
43
+
44
+ # ---------------------------------------------------------------------- semantic signatures
45
+ def signature(state: SystemState, shell_ops: list | None = None) -> str:
46
+ ents = []
47
+ for e in state.entities.values():
48
+ par = state.entities[e.parent].name if e.parent in state.entities else None
49
+ ents.append((e.name, e.domain, e.kind, json.dumps(e.props, sort_keys=True, default=str), par,
50
+ json.dumps(e.behaviors, sort_keys=True)))
51
+ links = sorted((state.entities[l.src].name, state.entities[l.dst].name, l.via or "",
52
+ json.dumps(l.props, sort_keys=True)) for l in state.links.values()
53
+ if l.src in state.entities and l.dst in state.entities)
54
+ shell = [json.dumps(_norm_shell(p), sort_keys=True) for p in (shell_ops or [])]
55
+ return json.dumps({"e": sorted(ents), "l": links, "s": shell, "d": state.default_domain}, sort_keys=True)
56
+
57
+
58
+ def _norm_shell(props: dict) -> dict:
59
+ p = {k: v for k, v in props.items() if v not in (None, False, [], "")}
60
+ if p.get("dir") == ".":
61
+ p.pop("dir")
62
+ if p.get("kind") == "any" and p.get("path"):
63
+ p.pop("kind")
64
+ return p
65
+
66
+
67
+ class Evaluator:
68
+ """Runs sentences through a session that shares one knowledge base (fast, no disk writes)."""
69
+
70
+ def __init__(self, kb, cwd: Path | None = None):
71
+ from .runtime import Session
72
+ self.kb = kb
73
+ self._Session = Session
74
+ self.cwd = cwd
75
+ self._ctx_cache: dict[tuple, SystemState] = {}
76
+ self._gold_cache: dict[tuple, str] = {}
77
+
78
+ def session(self, rewrites=None):
79
+ s = self._Session("eval", backend="off", kb=self.kb)
80
+ s.interactive = False
81
+ s.auto_yes = True
82
+ if rewrites is not None:
83
+ s.rules.rewrites = rewrites
84
+ if self.cwd:
85
+ s.cwd = Path(self.cwd)
86
+ return s
87
+
88
+ def context_state(self, ctx: list[str]) -> SystemState:
89
+ key = tuple(ctx)
90
+ if key not in self._ctx_cache:
91
+ s = self.session(rewrites=[])
92
+ for ln in ctx:
93
+ s.handle(ln)
94
+ self._ctx_cache[key] = s.state.clone()
95
+ return self._ctx_cache[key].clone()
96
+
97
+ def gold_signature(self, ex: Example) -> str:
98
+ key = (tuple(ex.context), tuple(ex.gold), ex.valid)
99
+ if key not in self._gold_cache:
100
+ s = self.session(rewrites=[])
101
+ s.state = self.context_state(ex.context)
102
+ s.interp = Interpreter(s.state)
103
+ shell = []
104
+ if ex.valid:
105
+ for ln in ex.gold:
106
+ c = s.interpret(ln)[0]
107
+ if c.source == "shell":
108
+ shell.append(c.ops[0].props)
109
+ else:
110
+ s.interp.apply_all(c.ops)
111
+ self._gold_cache[key] = signature(s.state, shell)
112
+ return self._gold_cache[key]
113
+
114
+ def run(self, ex: Example, rewrites=None, params=None) -> dict:
115
+ """Interpret one sentence: weight, decision, and whether the interpretation is semantically right."""
116
+ s = self.session(rewrites)
117
+ s.state = self.context_state(ex.context)
118
+ s.interp = Interpreter(s.state)
119
+ t0 = time.perf_counter()
120
+ cands = s.interpret(ex.text)
121
+ best = cands[0]
122
+ if params is not None:
123
+ best.score = wmod.score(best.features, params)
124
+ elapsed = time.perf_counter() - t0
125
+ shell = []
126
+ if best.ops:
127
+ if best.source == "shell":
128
+ shell.append(best.ops[0].props)
129
+ else:
130
+ try:
131
+ s.interp.apply_all(best.ops)
132
+ except Exception:
133
+ pass
134
+ right = signature(s.state, shell) == self.gold_signature(ex) and bool(best.ops) == ex.valid
135
+ decision = wmod.decision(best.score)
136
+ return {"id": ex.id, "text": ex.text, "valid": ex.valid, "right": right, "weight": round(best.score, 4),
137
+ "decision": decision, "executed": decision != "ask", "features": best.features,
138
+ "source": best.source, "summary": best.summary(), "seconds": elapsed,
139
+ "frames": [f for _c, f, _t in (best.detail.clauses if best.source == "rules" and best.detail else []) if f],
140
+ "intent": best.ops[0].props.get("intent") if best.source == "shell" and best.ops else None}
141
+
142
+
143
+ # ---------------------------------------------------------------------- metrics
144
+ def metrics(results: list[dict]) -> dict:
145
+ n = len(results)
146
+ if not n:
147
+ return {}
148
+ valid = [r for r in results if r["valid"]]
149
+ executed = [r for r in results if r["executed"]]
150
+ silent = [r for r in executed if not r["right"]]
151
+ m = {
152
+ "sentences": n,
153
+ "interpretation_accuracy": round(sum(r["right"] for r in valid) / max(1, len(valid)), 4),
154
+ "executed": len(executed),
155
+ "precision_when_executed": round(sum(r["right"] for r in executed) / max(1, len(executed)), 4),
156
+ "silent_error_rate": round(len(silent) / n, 4),
157
+ "asked": n - len(executed),
158
+ "nonsense_caught": f"{sum(1 for r in results if not r['valid'] and not r['executed'])}/"
159
+ f"{sum(1 for r in results if not r['valid'])}",
160
+ "median_ms": round(sorted(r["seconds"] for r in results)[n // 2] * 1000, 2),
161
+ }
162
+ m.update({f"calibration_{k}": v for k, v in
163
+ wmod.calibration([r["weight"] for r in results], [int(r["right"]) for r in results]).items()})
164
+ return m
165
+
166
+
167
+ def consistency(results: list[dict], examples: list[Example]) -> float:
168
+ """Share of intents whose paraphrases all end in the same (right) state."""
169
+ by: dict[str, list[bool]] = {}
170
+ ids = {e.id: e for e in examples}
171
+ for r in results:
172
+ ex = ids.get(r["id"])
173
+ if ex is not None and ex.valid:
174
+ by.setdefault(ex.intent, []).append(r["right"])
175
+ if not by:
176
+ return 0.0
177
+ return round(sum(all(v) for v in by.values()) / len(by), 4)
178
+
179
+
180
+ # ---------------------------------------------------------------------- training
181
+ def _words(text: str) -> list[str]:
182
+ import re
183
+ return re.findall(r"[A-Za-z][\w'\-]*", text.lower())
184
+
185
+
186
+ VERB_TOKENS = ("CREATE", "DELETE", "SET", "CONNECT", "DISCONNECT", "RENAME", "MOVE", "SHOW", "BUILD", "RUN",
187
+ "UNDO", "DEFINE", "USE", "WHEN")
188
+
189
+
190
+ _CONTENT: set[str] = set()
191
+
192
+
193
+ def _safe_rule(kb, frm: tuple, to: str) -> bool:
194
+ """The KB refuses rules that would erase or change the meaning of a core verb, and rules that
195
+ would make the interpreter ignore a content word (an entity name, a property or a kind)."""
196
+ if not to and any(w.replace("'s", "") in _CONTENT for w in frm):
197
+ return False
198
+ for w in frm:
199
+ r = kb.query(f"atomic({kb.to_term(w)}, T)", limit=1)
200
+ if r and r[0]["T"] in VERB_TOKENS:
201
+ if not to:
202
+ return False
203
+ r2 = kb.query(f"atomic({kb.to_term(to)}, T2)", limit=1)
204
+ if not r2 or r2[0]["T2"] != r[0]["T"]:
205
+ return False
206
+ return True
207
+
208
+
209
+ def induce_rewrites(ev: Evaluator, train: list[Example], base: list, log=print, max_rules: int = 60,
210
+ keep: list[Example] | None = None) -> list:
211
+ """Learn new meanings: phrase in the sentence -> word of the canonical sentence (or nothing).
212
+ `keep` are sentences that must stay right (the canonical ones): a rule that breaks any is rejected."""
213
+ rules = list(base)
214
+ keep = list(keep or [])
215
+ guard = train + keep
216
+ # content words of this corpus: names of entities, properties and kinds
217
+ from .weights import known_props
218
+ _CONTENT.clear()
219
+ _CONTENT.update(known_props())
220
+ for r in ev.kb.query("kind_of(K, _, 2)", limit=5000):
221
+ _CONTENT.add(str(r["K"]))
222
+ for ex in guard:
223
+ st = ev.context_state(ex.context)
224
+ for e in st.entities.values():
225
+ _CONTENT.update({e.name.lower(), e.kind.lower(), *e.props})
226
+ current = {ex.id: ev.run(ex, rules)["right"] for ex in guard}
227
+ failing = [ex for ex in train if ex.valid and not current[ex.id]]
228
+ proposals: dict[tuple, set] = {}
229
+ for ex in failing:
230
+ tw = _words(ex.text)
231
+ gw = set(w for g in ex.gold for w in _words(g))
232
+ targets = sorted(w for w in gw if w not in tw) + [""]
233
+ grams = set()
234
+ for n in (1, 2, 3):
235
+ for i in range(len(tw) - n + 1):
236
+ g = tuple(tw[i:i + n])
237
+ if any(w not in gw for w in g):
238
+ grams.add(g)
239
+ for g in grams:
240
+ for t in targets:
241
+ if not _safe_rule(ev.kb, g, t):
242
+ continue
243
+ rule = (list(g), [t] if t else [], 1)
244
+ trial = rules + [rule]
245
+ trial.sort(key=lambda r: -len(r[0]))
246
+ if ev.run(ex, trial)["right"]:
247
+ proposals.setdefault((g, t), set()).add(ex.id)
248
+ accepted = []
249
+ for (g, t), fixed in sorted(proposals.items(), key=lambda kv: (-len(kv[1]), len(kv[0][0]), kv[0])):
250
+ if len(accepted) >= max_rules:
251
+ break
252
+ if all(current.get(i) for i in fixed):
253
+ continue # already fixed by an earlier rule
254
+ trial = sorted(rules + [(list(g), [t] if t else [], len(fixed))], key=lambda r: -len(r[0]))
255
+ new = {ex.id: ev.run(ex, trial)["right"] for ex in guard}
256
+ broken = [i for i, ok in current.items() if ok and not new[i]]
257
+ gained = [i for i, ok in new.items() if ok and not current[i]]
258
+ if broken or not gained:
259
+ continue
260
+ rules, current = trial, new
261
+ accepted.append((list(g), [t] if t else [], len(gained)))
262
+ log(f" learned: '{' '.join(g)}' -> '{t or '(ignore)'}' fixes {len(gained)}, breaks 0")
263
+ return accepted
264
+
265
+
266
+ def corpus_folder() -> Path:
267
+ """The small project folder the corpus' terminal sentences refer to (built fresh each time)."""
268
+ import tempfile
269
+ from .bench.fixture import build
270
+ return build(Path(tempfile.mkdtemp(prefix="nlcl_corpus_fs_")) / "proj")
271
+
272
+
273
+ def train(kb, examples: list[Example], log=print, induce: bool = True, cwd: Path | None = None) -> dict:
274
+ cwd = cwd or corpus_folder()
275
+ ev = Evaluator(kb, cwd)
276
+ tr = [e for e in examples if e.split == "train"]
277
+ base = kb.rewrites()
278
+ t0 = time.time()
279
+ gold = [e for e in examples if e.split == "gold"]
280
+ learned = induce_rewrites(ev, tr, base, log, keep=gold) if induce else []
281
+ for frm, to, sup in learned:
282
+ kb.add_rewrite(frm, to, sup)
283
+ rewrites = kb.rewrites()
284
+ results = [ev.run(e, rewrites) for e in tr]
285
+ for r in results:
286
+ for f in r["frames"]:
287
+ kb.record(f"frame({f.lower()})", r["right"])
288
+ if r["intent"]:
289
+ kb.record(f"intent({r['intent']})", r["right"])
290
+ # refit features after evidence changed, then fit the weighting model
291
+ results = [ev.run(e, rewrites) for e in tr]
292
+ samples = [(r["features"], int(r["right"])) for r in results]
293
+ params = wmod.fit(samples, kb.params() or None)
294
+ kb.set_params(params)
295
+ kb.save()
296
+ final = [ev.run(e, rewrites, params) for e in tr]
297
+ return {"train_sentences": len(tr), "rules_learned": len(learned), "seconds": round(time.time() - t0, 1),
298
+ "train_metrics": metrics(final)}
299
+
300
+
301
+ def evaluate(kb, examples: list[Example], split: str = "test", cwd: Path | None = None) -> tuple[dict, list[dict]]:
302
+ ev = Evaluator(kb, cwd or corpus_folder())
303
+ ex = [e for e in examples if e.split == split]
304
+ params = kb.params() or None
305
+ res = [ev.run(e, kb.rewrites(), params) for e in ex]
306
+ m = metrics(res)
307
+ m["paraphrase_consistency"] = consistency(res, ex)
308
+ return m, res
nlcl/llm.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Free LLM backends (all optional) + LLM semantic parser.
2
+
3
+ Every backend speaks the OpenAI-compatible /chat/completions protocol, so a
4
+ single stdlib-only client covers them all. Nothing here is required: with
5
+ no key and no local Ollama, NLCL runs on the offline rule parser.
6
+
7
+ backend env var for key free tier / notes
8
+ --------- -------------------- ---------------------------------------
9
+ ollama (none) 100% local & free (ollama.com)
10
+ groq GROQ_API_KEY free tier, very fast (console.groq.com)
11
+ gemini GEMINI_API_KEY free tier (aistudio.google.com)
12
+ openrouter OPENROUTER_API_KEY free ":free" models (openrouter.ai)
13
+ cerebras CEREBRAS_API_KEY free tier (cloud.cerebras.ai)
14
+ mistral MISTRAL_API_KEY free "Experiment" plan (console.mistral.ai)
15
+ huggingface HF_TOKEN free monthly credits (huggingface.co)
16
+ github GITHUB_TOKEN GitHub Models free tier
17
+
18
+ Model names change over time; override any of them with NLCL_<NAME>_MODEL,
19
+ e.g. NLCL_GROQ_MODEL=llama-3.1-8b-instant
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import json
24
+ import os
25
+ import re
26
+ import urllib.error
27
+ import urllib.request
28
+ from dataclasses import dataclass
29
+
30
+ from .ir import Op, SystemState
31
+
32
+ BACKENDS = {
33
+ # name base url key env default model
34
+ "ollama": ("http://localhost:11434/v1", None, "llama3.2"),
35
+ "groq": ("https://api.groq.com/openai/v1", "GROQ_API_KEY", "llama-3.3-70b-versatile"),
36
+ "gemini": ("https://generativelanguage.googleapis.com/v1beta/openai", "GEMINI_API_KEY", "gemini-2.5-flash"),
37
+ "openrouter": ("https://openrouter.ai/api/v1", "OPENROUTER_API_KEY", "cohere/north-mini-code:free"),
38
+ "cerebras": ("https://api.cerebras.ai/v1", "CEREBRAS_API_KEY", "llama-3.3-70b"),
39
+ "mistral": ("https://api.mistral.ai/v1", "MISTRAL_API_KEY", "mistral-small-latest"),
40
+ "huggingface": ("https://router.huggingface.co/v1", "HF_TOKEN", "meta-llama/Llama-3.1-8B-Instruct"),
41
+ "github": ("https://models.github.ai/inference", "GITHUB_TOKEN", "openai/gpt-4.1-mini"),
42
+ }
43
+ # order used by auto-detection: local first, then fastest free clouds
44
+ AUTO_ORDER = ["ollama", "groq", "gemini", "cerebras", "openrouter", "mistral", "huggingface", "github"]
45
+
46
+
47
+ class LLMError(RuntimeError):
48
+ pass
49
+
50
+
51
+ class QuotaExceeded(LLMError):
52
+ """The provider's free daily limit is used up: stop asking it today."""
53
+
54
+
55
+ @dataclass
56
+ class Backend:
57
+ name: str
58
+ base_url: str
59
+ key: str | None
60
+ model: str
61
+ timeout: int = 60
62
+
63
+ def chat(self, messages: list[dict], temperature: float = 0.0, json_mode: bool = True) -> str:
64
+ body = {"model": self.model, "messages": messages, "temperature": temperature}
65
+ if json_mode and self.name in ("groq", "gemini", "openrouter", "mistral", "cerebras", "ollama", "github"):
66
+ body["response_format"] = {"type": "json_object"}
67
+ data = json.dumps(body).encode("utf-8")
68
+ headers = {"Content-Type": "application/json", "User-Agent": "nlcl/0.1"}
69
+ if self.key:
70
+ headers["Authorization"] = f"Bearer {self.key}"
71
+ if self.name == "openrouter":
72
+ headers["X-Title"] = "NLCL"
73
+ req = urllib.request.Request(self.base_url.rstrip("/") + "/chat/completions", data=data, headers=headers)
74
+ try:
75
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
76
+ out = json.loads(r.read().decode("utf-8"))
77
+ except urllib.error.HTTPError as e:
78
+ detail = e.read().decode("utf-8", "replace")[:300]
79
+ if json_mode and e.code == 400 and "response_format" in detail:
80
+ return self.chat(messages, temperature, json_mode=False)
81
+ if e.code == 429:
82
+ low = detail.lower()
83
+ if "per-day" in low or "per day" in low or "daily" in low or "quota" in low:
84
+ raise QuotaExceeded(f"{self.name}: daily free limit reached ({detail[:160]})") from None
85
+ self._retries = getattr(self, "_retries", 0) + 1
86
+ if self._retries <= 4: # per-minute limit: wait and try again
87
+ import time
88
+ time.sleep(min(60, 8 * self._retries))
89
+ try:
90
+ return self.chat(messages, temperature, json_mode)
91
+ finally:
92
+ self._retries = 0
93
+ raise LLMError(f"{self.name}: HTTP {e.code}: {detail}") from None
94
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
95
+ raise LLMError(f"{self.name}: {e}") from None
96
+ try:
97
+ return out["choices"][0]["message"]["content"] or ""
98
+ except (KeyError, IndexError, TypeError):
99
+ raise LLMError(f"{self.name}: unexpected response {str(out)[:200]}") from None
100
+
101
+ def __str__(self):
102
+ return f"{self.name} ({self.model})"
103
+
104
+
105
+ def make_backend(name: str) -> Backend | None:
106
+ name = name.lower()
107
+ if name not in BACKENDS:
108
+ raise LLMError(f"unknown backend '{name}'. Choose from: {', '.join(BACKENDS)}")
109
+ url, key_env, model = BACKENDS[name]
110
+ url = os.environ.get(f"NLCL_{name.upper()}_URL", url)
111
+ model = os.environ.get(f"NLCL_{name.upper()}_MODEL", model)
112
+ key = os.environ.get(key_env) if key_env else None
113
+ if key_env and not key:
114
+ return None
115
+ return Backend(name, url, key, model)
116
+
117
+
118
+ def ollama_alive(url: str = "http://localhost:11434") -> list[str] | None:
119
+ try:
120
+ with urllib.request.urlopen(url + "/api/tags", timeout=1.5) as r:
121
+ return [m["name"] for m in json.loads(r.read()).get("models", [])]
122
+ except Exception:
123
+ return None
124
+
125
+
126
+ def autodetect(preferred: str | None = None) -> Backend | None:
127
+ """Pick the first usable free backend (or the preferred one)."""
128
+ pref = preferred or os.environ.get("NLCL_BACKEND")
129
+ if pref and pref.lower() in ("none", "off", "rules"):
130
+ return None
131
+ order = [pref.lower()] if pref else AUTO_ORDER
132
+ for name in order:
133
+ if name == "ollama":
134
+ models = ollama_alive()
135
+ if models is None:
136
+ continue
137
+ b = make_backend("ollama")
138
+ if not os.environ.get("NLCL_OLLAMA_MODEL") and models and b.model not in models \
139
+ and not any(m.startswith(b.model + ":") for m in models):
140
+ b.model = models[0]
141
+ return b
142
+ b = make_backend(name)
143
+ if b:
144
+ return b
145
+ return None
146
+
147
+
148
+ def status() -> str:
149
+ lines = []
150
+ for name in AUTO_ORDER:
151
+ url, key_env, model = BACKENDS[name]
152
+ if name == "ollama":
153
+ ok = ollama_alive() is not None
154
+ lines.append(f" {name:<12} {'running' if ok else 'not running':<14} local, no key ({url})")
155
+ else:
156
+ ok = bool(os.environ.get(key_env))
157
+ lines.append(f" {name:<12} {'key set' if ok else 'no key':<14} set {key_env}")
158
+ return "\n".join(lines)
159
+
160
+
161
+ def extract_json(text: str):
162
+ text = text.strip()
163
+ text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text, flags=re.S)
164
+ try:
165
+ return json.loads(text)
166
+ except ValueError:
167
+ pass
168
+ m = re.search(r"\{.*\}|\[.*\]", text, re.S)
169
+ if m:
170
+ return json.loads(m.group(0))
171
+ raise ValueError("no JSON in model reply")
172
+
173
+
174
+ # --------------------------------------------------------------------------
175
+ # LLM semantic parser
176
+ # --------------------------------------------------------------------------
177
+
178
+ SYSTEM_PROMPT = """You are the semantic front-end of NLCL, a natural-language computational language.
179
+ Convert the user's instruction (any human language) into IR operations that modify a persistent system state.
180
+ Reply with ONLY a JSON object: {"ops": [ ... ], "question": null}
181
+ If the instruction is genuinely ambiguous (e.g. you cannot tell the target domain of a new object and there is no default), return {"ops": [], "question": "<short clarification question>"}.
182
+
183
+ Each op is an object with "action" and optional fields:
184
+ CREATE domain, kind, name, props{}, count, parent new entity/entities
185
+ SET target, props{}, parent, domain change properties of an existing entity
186
+ UNSET target, props{"name": null} remove properties
187
+ DELETE target
188
+ CONNECT target (source), dst, via, props{fields:[..], baud, port, topic, interval_ms}
189
+ DISCONNECT target, dst
190
+ RENAME target, name
191
+ BEHAVIOR target, behavior{on, if, do:[actions]}
192
+ DOMAIN domain default domain for later CREATEs
193
+ FOCUS target make target the current "it"
194
+ SHOW / BUILD / RUN(domain) / UNDO meta commands
195
+ "target" refers to an existing entity by name or kind; omit it (null) to mean "it" (the entity in focus).
196
+ Domains available: {domains}
197
+ Protocols for "via": serial, http, mqtt, gpio, spi, i2c, udp, websocket.
198
+ Property names: snake_case English (health, speed, movable, collision, pin, color, position:[x,y,z], size:[x,y,z], width, ...).
199
+ Values: numbers, booleans, strings, or numeric lists.
200
+
201
+ Behaviour object:
202
+ "on": "start" | "update" | "collision" | "input:<key-or-entity>" | "timer:<ms>" | "change:<prop>" | "message:<entity-or-any>"
203
+ "if": optional condition expression or null
204
+ "do": list of actions:
205
+ {"op":"set","prop":p,"value":expr} {"op":"add","prop":p,"value":expr} {"op":"toggle","prop":p}
206
+ {"op":"destroy"} {"op":"log","text":"..."} {"op":"move","x":expr,"y":expr,"z":expr}
207
+ {"op":"send","to":entity,"fields":[..]} {"op":"call","name":fn,"args":[expr..]}
208
+ Expressions: C-like: identifiers (property names, or entity.prop for another entity), numbers, "strings", true/false,
209
+ + - * / % < > <= >= == != && || ! ( ). A behaviour is attached to the entity whose state its actions change.
210
+
211
+ Current system state:
212
+ {state}
213
+ Default domain: {default_domain}
214
+ Learned vocabulary: {vocab}
215
+
216
+ Examples:
217
+ User: create a game object with 100 health that can move
218
+ {"ops":[{"action":"CREATE","domain":"game","kind":"object","props":{"health":100,"movable":true}}],"question":null}
219
+ User: create an object
220
+ {"ops":[],"question":"What kind of object would you like to create? (game, python, embedded, hardware, 3d, cad, ...)"}
221
+ User: when health drops below 1, destroy it
222
+ {"ops":[{"action":"BEHAVIOR","target":null,"behavior":{"on":"update","if":"health < 1","do":[{"op":"destroy"}]}}],"question":null}
223
+ User: add an esp32 with a temperature sensor on pin 4 and send the temperature to the dashboard over mqtt every 5 seconds
224
+ {"ops":[{"action":"CREATE","domain":"embedded","kind":"esp32","name":"esp32"},{"action":"CREATE","domain":"embedded","kind":"sensor","name":"temp_sensor","parent":"esp32","props":{"subtype":"temperature","pin":4,"temperature":0}},{"action":"CONNECT","target":"temp_sensor","dst":"dashboard","via":"mqtt","props":{"fields":["temperature"],"interval_ms":5000}}],"question":null}
225
+ """
226
+
227
+
228
+ TRANSLATE_PROMPT = """You are the online language agent of NLCL, a natural-language programming system.
229
+ The user writes in ANY human language (Persian/Farsi, Arabic, Turkish, ...). Rewrite the instruction as simple
230
+ English NLCL commands. Reply with ONLY JSON: {"lines": ["command 1", "command 2", ...]}
231
+
232
+ Rules:
233
+ - One action per line. Keep the user's meaning exactly; do not invent objects or properties.
234
+ - Numbers as ASCII digits. Entity names: keep names that already exist in the state exactly; write new
235
+ names in Latin letters (transliterate, e.g. علی -> ali).
236
+ - Use ONLY these sentence patterns:
237
+ create a <domain> <kind> called <name> with <prop> <value> and <prop> <value>
238
+ create <N> <domain> <kind>s with <prop> <value>
239
+ add a <kind> called <name> to <parent> on pin <N>
240
+ set <prop> of <name> to <value> | give <name> <value> <prop> | make <name> <color>
241
+ remove <prop> from <name> | delete <name> | rename <old> to <new>
242
+ put <child> inside <parent> | select <name> | undo
243
+ connect <a> to <b> via <serial|http|mqtt|spi|i2c|udp> sending <field>, <field> every <N> seconds
244
+ when <prop> of <name> is above|below|equal to <value>, <action>
245
+ when <name> is pressed, <action> | when <a> touches <b>, <action>
246
+ every <N> seconds|ms, <action> | when <name> starts, <action>
247
+ actions: set <prop> of <name> to <value> | increase|decrease <prop> of <name> by <N> | toggle <name>
248
+ turn on|off <name> | destroy <name> | print '<text>' | move <name> up|down|left|right by <N>
249
+ send <field> to <name>
250
+ build it | run it | show
251
+ fix <file or module>: <description of the bug in English>
252
+ - Domains: {domains}. Say the domain explicitly when the user names or implies one (game, python, embedded,
253
+ hardware, cpp, 3d, cad, app).
254
+ - If the request is a question or cannot be expressed, return {"lines": [], "question": "<short question in the user's language>"}.
255
+
256
+ Current system state:
257
+ {state}
258
+
259
+ Example (Persian): "یه بازیکن بساز با ۱۰۰ تا جون، وقتی جونش صفر شد حذفش کن"
260
+ {"lines": ["create a game player called player with health 100", "when health of player is below 1, destroy player"]}
261
+ """
262
+
263
+
264
+ class LLMParser:
265
+ def __init__(self, backend: Backend):
266
+ self.backend = backend
267
+
268
+ def parse(self, text: str, state: SystemState, domains: list[str], vocab_desc: str = "",
269
+ history: list[dict] | None = None) -> tuple[list[Op], str | None]:
270
+ prompt = (SYSTEM_PROMPT
271
+ .replace("{domains}", ", ".join(domains))
272
+ .replace("{state}", state.summary())
273
+ .replace("{default_domain}", str(state.default_domain))
274
+ .replace("{vocab}", vocab_desc or "(none)"))
275
+ messages = [{"role": "system", "content": prompt}]
276
+ for h in (history or [])[-6:]:
277
+ messages.append(h)
278
+ messages.append({"role": "user", "content": text})
279
+ last_err = None
280
+ for attempt in range(2):
281
+ reply = self.backend.chat(messages)
282
+ try:
283
+ data = extract_json(reply)
284
+ if isinstance(data, list):
285
+ data = {"ops": data}
286
+ ops = [Op.from_dict(o) for o in data.get("ops", [])]
287
+ return ops, data.get("question")
288
+ except (ValueError, TypeError, KeyError) as e:
289
+ last_err = e
290
+ messages.append({"role": "assistant", "content": reply})
291
+ messages.append({"role": "user", "content": f"That was invalid ({e}). Reply again with valid JSON only."})
292
+ raise LLMError(f"model returned invalid IR: {last_err}")
293
+
294
+ def to_english(self, text: str, state: SystemState, domains: list[str]) -> tuple[list[str], str | None]:
295
+ """Online agent for non-English input (Persian, Arabic, ...): rewrite the instruction as
296
+ canonical English NLCL commands, one per line, which the normal pipeline then executes."""
297
+ msg = [{"role": "system", "content": TRANSLATE_PROMPT
298
+ .replace("{domains}", ", ".join(domains))
299
+ .replace("{state}", state.summary())},
300
+ {"role": "user", "content": text}]
301
+ data = extract_json(self.backend.chat(msg))
302
+ lines = data.get("lines") if isinstance(data, dict) else data
303
+ if not isinstance(lines, list):
304
+ raise LLMError("model did not return a list of commands")
305
+ question = data.get("question") if isinstance(data, dict) else None
306
+ return [str(x).strip() for x in lines if str(x).strip()], question
307
+
308
+ def propose_meaning(self, word: str, context: str, tokens: list[str]) -> dict | None:
309
+ """Adaptive vocabulary: ask the model what an unknown word maps to."""
310
+ msg = [{"role": "system", "content":
311
+ "You extend the vocabulary of a natural-language programming system. Atomic tokens: "
312
+ + ", ".join(tokens) +
313
+ '. Reply JSON {"token": <one atomic token or null>, "property": <snake_case property name or null>, '
314
+ '"reason": "..."}. Use "property" if the word is a data attribute (like stamina), "token" if it '
315
+ 'is an operation/function word (like spawn = CREATE).'},
316
+ {"role": "user", "content": f'Word: "{word}"\nSentence: "{context}"'}]
317
+ try:
318
+ return extract_json(self.backend.chat(msg))
319
+ except (LLMError, ValueError):
320
+ return None
321
+
322
+ def write_body(self, language: str, description: str, context: str) -> str | None:
323
+ """Optional: ask the model for a small function body (used by modules for 'call' actions)."""
324
+ msg = [{"role": "system", "content": f"Write only the body of a {language} function. No explanations, "
325
+ f"no markdown fences. Keep it under 15 lines."},
326
+ {"role": "user", "content": f"Function purpose: {description}\nContext:\n{context}"}]
327
+ try:
328
+ out = self.backend.chat(msg, json_mode=False)
329
+ return re.sub(r"^```\w*\s*|\s*```$", "", out.strip(), flags=re.S)
330
+ except LLMError:
331
+ return None
nlcl/modules/__init__.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Domain module registry (auto-discovers nlcl/modules/*.py exposing MODULE)."""
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ import pkgutil
6
+ import sys
7
+
8
+ from .base import BuildContext, Channel, DomainModule, RunResult
9
+
10
+ _REGISTRY: dict[str, DomainModule] = {}
11
+
12
+
13
+ def load_modules() -> dict[str, DomainModule]:
14
+ if _REGISTRY:
15
+ return _REGISTRY
16
+ for info in pkgutil.iter_modules(__path__):
17
+ if info.name.startswith("_") or info.name == "base":
18
+ continue
19
+ try:
20
+ mod = importlib.import_module(f"{__name__}.{info.name}")
21
+ except Exception as e: # a broken plugin must not kill the runtime
22
+ print(f"[nlcl] warning: module {info.name} failed to load: {e}", file=sys.stderr)
23
+ continue
24
+ m = getattr(mod, "MODULE", None)
25
+ if isinstance(m, DomainModule):
26
+ _REGISTRY[m.name] = m
27
+ return _REGISTRY
28
+
29
+
30
+ def get(name: str | None) -> DomainModule | None:
31
+ if not name:
32
+ return None
33
+ reg = load_modules()
34
+ n = name.lower()
35
+ if n in reg:
36
+ return reg[n]
37
+ for m in reg.values():
38
+ if n in m.aliases:
39
+ return m
40
+ return None
41
+
42
+
43
+ __all__ = ["BuildContext", "Channel", "DomainModule", "RunResult", "load_modules", "get"]
nlcl/modules/_assets/3d/runtime.js ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ===========================================================================
2
+ // NLCL three.js runtime (static part, shared by every generated 3D scene).
3
+ // Expects these constants to be declared above it in the same module:
4
+ // PROJECT, DEFS, CHANNELS, BEHAVIOURS, USER_FUNCTIONS, HUB_POLL_MS
5
+ // ===========================================================================
6
+
7
+ const DEG = Math.PI / 180;
8
+ const GEOMETRY_KEYS = new Set(["size", "radius", "height", "tube", "length", "subtype"]);
9
+ const AXES = { x: 0, y: 1, z: 2 };
10
+ const ROT_AXES = { angle: 2, angle_z: 2, angle_x: 0, angle_y: 1 }; // "angle" props are rotation components (degrees) // bare x/y/z in behaviours address the position
11
+ // props that describe geometry/appearance rather than live data (hidden in the HUD)
12
+ const NON_DATA = new Set(["position", "rotation", "scale", "size", "color", "opacity", "wireframe",
13
+ "visible", "shape", "radius", "height", "width", "depth", "length", "tube", "text", "intensity",
14
+ "fov", "subtype", "url", "target", "segments", "material", "texture", "units", "movable",
15
+ "collision", "gravity", "emissive", "metalness", "roughness", "font_size", "model"]);
16
+ const DEFAULT_COLORS = {
17
+ box: "#8fa3bf", sphere: "#d9a441", cylinder: "#6fb08f", cone: "#c46b6b", torus: "#a57fd1",
18
+ plane: "#7d8794", ground: "#4f5b4a", building: "#b7bec9", tank: "#9aa7b5", pipe: "#7f8c99",
19
+ arm: "#f0a020", twin: "#5aa7d6", model: "#9aa0a6", room: "#5c6470", light: "#ffffff",
20
+ };
21
+
22
+ // ---------------------------------------------------------------- helpers
23
+ function num(v, d = 0) { const n = Number(v); return Number.isFinite(n) ? n : d; }
24
+ // position-like vector: missing components are 0
25
+ function pos3(v, d = [0, 0, 0]) {
26
+ if (Array.isArray(v)) { const a = v.slice(0, 3).map(x => num(x, 0)); while (a.length < 3) a.push(0); return a; }
27
+ if (v !== undefined && v !== null && v !== "" && Number.isFinite(Number(v))) { const n = Number(v); return [n, n, n]; }
28
+ return d.slice();
29
+ }
30
+ // size-like vector: a single number means a cube, missing components repeat the last one
31
+ function size3(v, d = [1, 1, 1]) {
32
+ if (Array.isArray(v) && v.length) { const a = v.slice(0, 3).map(x => Math.max(0.001, num(x, 1))); while (a.length < 3) a.push(a[a.length - 1]); return a; }
33
+ if (v !== undefined && v !== null && v !== "" && Number.isFinite(Number(v))) { const n = Math.max(0.001, Number(v)); return [n, n, n]; }
34
+ return d.slice();
35
+ }
36
+ function clamp(v, a, b) { return Math.min(b, Math.max(a, v)); }
37
+ function toColor(v, fallback = "#8fa3bf") {
38
+ const c = new THREE.Color(fallback);
39
+ if (v === undefined || v === null || v === "" || typeof v === "boolean") return c;
40
+ if (typeof v === "number") return c.setHex(Math.max(0, Math.floor(v)) & 0xffffff);
41
+ let s = String(v).trim().toLowerCase();
42
+ if (s.startsWith("0x")) s = "#" + s.slice(2);
43
+ if (/^[0-9a-f]{6}$/.test(s)) s = "#" + s;
44
+ if (!s.startsWith("#") && !s.startsWith("rgb") && !s.startsWith("hsl")) s = s.replace(/[\s_-]+/g, "").replace("grey", "gray");
45
+ if (s.startsWith("#") || s.startsWith("rgb") || s.startsWith("hsl") || THREE.Color.NAMES[s] !== undefined) {
46
+ try { c.setStyle(s); } catch (e) { /* keep fallback */ }
47
+ }
48
+ return c;
49
+ }
50
+ // 10 degC -> blue, 40 degC -> red
51
+ function temperatureColor(t) { const k = clamp((num(t) - 10) / 30, 0, 1); return new THREE.Color().setHSL(0.66 * (1 - k), 0.85, 0.5); }
52
+ function esc(s) { return String(s).replace(/[&<>"]/g, ch => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[ch])); }
53
+ function fmt(v) {
54
+ if (typeof v === "number") return Number.isInteger(v) ? String(v) : v.toFixed(2);
55
+ if (Array.isArray(v)) return "[" + v.map(fmt).join(", ") + "]";
56
+ if (v === null || v === undefined) return "-";
57
+ return String(v);
58
+ }
59
+
60
+ // ---------------------------------------------------------------- renderer / scene
61
+ const renderer = new THREE.WebGLRenderer({ antialias: true });
62
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
63
+ renderer.setSize(window.innerWidth, window.innerHeight);
64
+ renderer.shadowMap.enabled = true;
65
+ document.body.appendChild(renderer.domElement);
66
+ const scene = new THREE.Scene();
67
+ scene.background = new THREE.Color(0x1f242d);
68
+ const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.05, 5000);
69
+ camera.position.set(6, 5, 8);
70
+ const controls = new OrbitControls(camera, renderer.domElement);
71
+ controls.enableDamping = true;
72
+ const hasLights = DEFS.some(d => d.shape === "light");
73
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x3a4250, hasLights ? 0.6 : 0.9));
74
+ if (!hasLights) {
75
+ const sun = new THREE.DirectionalLight(0xffffff, 1.6);
76
+ sun.position.set(6, 12, 8);
77
+ sun.castShadow = true;
78
+ scene.add(sun);
79
+ }
80
+ const grid = new THREE.GridHelper(40, 40, 0x55606e, 0x323946);
81
+ scene.add(grid);
82
+ window.addEventListener("resize", () => {
83
+ camera.aspect = window.innerWidth / window.innerHeight;
84
+ camera.updateProjectionMatrix();
85
+ renderer.setSize(window.innerWidth, window.innerHeight);
86
+ });
87
+
88
+ // ---------------------------------------------------------------- HUD / log
89
+ const hudEl = document.getElementById("hud");
90
+ const logEl = document.getElementById("log");
91
+ const badgeEl = document.getElementById("badge");
92
+ const LOG = [];
93
+ let lastLine = "", lastLineAt = 0;
94
+ function hudLog(line) {
95
+ // per-frame behaviours may log the same line 60x per second: show it at most once per second
96
+ const now = performance.now();
97
+ if (line === lastLine && now - lastLineAt < 1000) return;
98
+ lastLine = line; lastLineAt = now;
99
+ console.log(line);
100
+ LOG.push(line);
101
+ if (LOG.length > 12) LOG.shift();
102
+ if (logEl) logEl.innerHTML = LOG.map(esc).join("<br>");
103
+ }
104
+
105
+ // ---------------------------------------------------------------- remote data
106
+ const REMOTE = {}; // sender ident -> {field: latest value}
107
+ const REMOTE_FIELD = {}; // field -> latest value from any sender
108
+ function remote(ent, prop) {
109
+ const r = REMOTE[ent];
110
+ if (r && r[prop] !== undefined) return r[prop];
111
+ const o = OBJS.get(ent);
112
+ return o ? o.get(prop) : 0;
113
+ }
114
+
115
+ // ---------------------------------------------------------------- objects
116
+ const OBJS = new Map(); // ident -> NObj
117
+ const VIEW = { cam: null }; // camera entity that drives the view (set in setupView)
118
+ const NULL_OBJ = { get: () => 0, num: () => 0, alive: false };
119
+ function obj(ident) { return OBJS.get(ident) || NULL_OBJ; }
120
+
121
+ function std(color, extra = {}) {
122
+ return new THREE.MeshStandardMaterial(Object.assign({ color: new THREE.Color(color), roughness: 0.55, metalness: 0.1 }, extra));
123
+ }
124
+
125
+ function labelTexture(text, color = "#ffffff") {
126
+ const canvas = document.createElement("canvas");
127
+ const ctx2 = canvas.getContext("2d");
128
+ const font = "bold 48px system-ui, sans-serif";
129
+ ctx2.font = font;
130
+ const w = Math.max(64, Math.ceil(ctx2.measureText(text).width) + 32);
131
+ canvas.width = w; canvas.height = 72;
132
+ ctx2.font = font;
133
+ ctx2.fillStyle = "rgba(20,24,32,0.75)";
134
+ ctx2.fillRect(0, 0, w, 72);
135
+ ctx2.fillStyle = color;
136
+ ctx2.textBaseline = "middle";
137
+ ctx2.fillText(text, 16, 38);
138
+ const tex = new THREE.CanvasTexture(canvas);
139
+ tex.colorSpace = THREE.SRGBColorSpace;
140
+ return { tex, aspect: w / 72 };
141
+ }
142
+
143
+ class NObj {
144
+ constructor(def) {
145
+ this.id = def.id; this.ident = def.ident; this.name = def.name; this.kind = def.kind; this.shape = def.shape;
146
+ this.p = JSON.parse(JSON.stringify(def.props || {}));
147
+ this.initial = JSON.parse(JSON.stringify(this.p));
148
+ this.alive = true;
149
+ this.recv = new Set(); // fields received over channels
150
+ this.colorMats = []; // materials tinted by color / temperature
151
+ this.dataMesh = null; // mesh stretched by level/value/distance
152
+ this.dataHeight = 1;
153
+ this.light = null;
154
+ this.label = null;
155
+ this.timers = [];
156
+ this._changing = new Set();
157
+ this.node = new THREE.Group();
158
+ this.node.name = this.ident;
159
+ this.node.userData.nobj = this;
160
+ this.buildOwn();
161
+ this.apply();
162
+ }
163
+ // build() and remember what it added, so a later size/radius change can rebuild the geometry
164
+ // without touching child objects attached to this node
165
+ buildOwn() {
166
+ const before = new Set(this.node.children);
167
+ this.build();
168
+ this.own = this.node.children.filter(c => !before.has(c));
169
+ }
170
+ rebuild() {
171
+ for (const c of this.own || []) {
172
+ this.node.remove(c);
173
+ c.traverse(o => { if (o.geometry) o.geometry.dispose(); });
174
+ }
175
+ if (this.light && this.light.target && this.light.target.parent) this.light.target.parent.remove(this.light.target);
176
+ this.colorMats = []; this.dataMesh = null; this.dataHeight = 1; this.light = null; this.label = null;
177
+ this.bulb = null; this.yaw = this.shoulderJ = this.elbowJ = null; this._labelText = null;
178
+ this.buildOwn();
179
+ }
180
+
181
+ // ---- geometry per shape
182
+ mesh(geo, mat, parent = this.node) {
183
+ const m = new THREE.Mesh(geo, mat);
184
+ m.castShadow = true; m.receiveShadow = true;
185
+ m.userData.nobj = this;
186
+ parent.add(m);
187
+ return m;
188
+ }
189
+ build() {
190
+ const p = this.p, s = this.shape;
191
+ const col = DEFAULT_COLORS[s] || DEFAULT_COLORS.box;
192
+ const rad = num(p.radius, typeof p.size === "number" ? p.size / 2 : 0.5);
193
+ const h = num(p.height, Array.isArray(p.size) ? size3(p.size)[1] : 1);
194
+ if (s === "box") {
195
+ const sz = size3(p.size);
196
+ const mat = std(col); this.colorMats.push(mat);
197
+ this.dataMesh = this.mesh(new THREE.BoxGeometry(sz[0], sz[1], sz[2]), mat); this.dataHeight = sz[1];
198
+ } else if (s === "sphere") {
199
+ const mat = std(col); this.colorMats.push(mat);
200
+ this.dataMesh = this.mesh(new THREE.SphereGeometry(rad, 32, 16), mat); this.dataHeight = rad * 2;
201
+ } else if (s === "cylinder") {
202
+ const mat = std(col); this.colorMats.push(mat);
203
+ this.dataMesh = this.mesh(new THREE.CylinderGeometry(rad, rad, h, 32), mat); this.dataHeight = h;
204
+ } else if (s === "cone") {
205
+ const mat = std(col); this.colorMats.push(mat);
206
+ this.dataMesh = this.mesh(new THREE.ConeGeometry(rad, h, 32), mat); this.dataHeight = h;
207
+ } else if (s === "torus") {
208
+ const mat = std(col); this.colorMats.push(mat);
209
+ this.dataMesh = this.mesh(new THREE.TorusGeometry(rad, num(p.tube, rad * 0.3), 16, 64), mat); this.dataHeight = rad * 2;
210
+ } else if (s === "plane" || s === "ground") {
211
+ const sz = size3(p.size, s === "ground" ? [20, 0, 20] : [4, 0, 4]);
212
+ const geo = new THREE.PlaneGeometry(sz[0], sz[2]); geo.rotateX(-Math.PI / 2);
213
+ const mat = std(col, { side: THREE.DoubleSide, roughness: 0.9 }); this.colorMats.push(mat);
214
+ const m = this.mesh(geo, mat); m.castShadow = false;
215
+ } else if (s === "room") {
216
+ const sz = size3(p.size, [10, 3, 8]);
217
+ const geo = new THREE.PlaneGeometry(sz[0], sz[2]); geo.rotateX(-Math.PI / 2);
218
+ const mat = std(col, { side: THREE.DoubleSide, roughness: 0.9 }); this.colorMats.push(mat);
219
+ const floor = this.mesh(geo, mat); floor.castShadow = false;
220
+ const edges = new THREE.LineSegments(new THREE.EdgesGeometry(new THREE.BoxGeometry(sz[0], sz[1], sz[2])),
221
+ new THREE.LineBasicMaterial({ color: 0x9fb3c8 }));
222
+ edges.position.y = sz[1] / 2;
223
+ this.node.add(edges);
224
+ } else if (s === "building") {
225
+ const sz = size3(p.size, [10, 6, 8]);
226
+ const mat = std(col); this.colorMats.push(mat);
227
+ const m = this.mesh(new THREE.BoxGeometry(sz[0], sz[1], sz[2]), mat);
228
+ m.position.y = sz[1] / 2;
229
+ m.add(new THREE.LineSegments(new THREE.EdgesGeometry(m.geometry), new THREE.LineBasicMaterial({ color: 0x30343b })));
230
+ } else if (s === "tank") {
231
+ const r = num(p.radius, 1), th = num(p.height, 3);
232
+ const shell = this.mesh(new THREE.CylinderGeometry(r, r, th, 40, 1, true),
233
+ std(col, { transparent: true, opacity: 0.3, side: THREE.DoubleSide, depthWrite: false }));
234
+ shell.position.y = th / 2;
235
+ const lmat = std("#2f7fd8", { roughness: 0.2 }); this.colorMats.push(lmat);
236
+ this.dataMesh = this.mesh(new THREE.CylinderGeometry(r * 0.92, r * 0.92, th, 40), lmat);
237
+ this.dataMesh.userData.anchorBottom = true;
238
+ this.dataHeight = th;
239
+ this.mesh(new THREE.CylinderGeometry(r * 1.02, r * 1.02, 0.08, 40), std("#59636e")).position.y = 0.04;
240
+ } else if (s === "pipe") {
241
+ const r = num(p.radius, 0.15), len = num(p.length, 4);
242
+ const geo = new THREE.CylinderGeometry(r, r, len, 20); geo.rotateZ(Math.PI / 2);
243
+ const mat = std(col, { metalness: 0.6, roughness: 0.35 }); this.colorMats.push(mat);
244
+ this.mesh(geo, mat);
245
+ } else if (s === "arm") {
246
+ const mat = std(col); this.colorMats.push(mat);
247
+ const dark = std("#3b4048");
248
+ this.mesh(new THREE.CylinderGeometry(0.45, 0.55, 0.3, 32), dark).position.y = 0.15;
249
+ this.yaw = new THREE.Group(); this.yaw.position.y = 0.3; this.node.add(this.yaw);
250
+ this.mesh(new THREE.CylinderGeometry(0.25, 0.25, 0.3, 24), mat, this.yaw).position.y = 0.15;
251
+ this.shoulderJ = new THREE.Group(); this.shoulderJ.position.y = 0.3; this.yaw.add(this.shoulderJ);
252
+ this.mesh(new THREE.BoxGeometry(0.22, 1.2, 0.22), mat, this.shoulderJ).position.y = 0.6;
253
+ this.elbowJ = new THREE.Group(); this.elbowJ.position.y = 1.2; this.shoulderJ.add(this.elbowJ);
254
+ this.mesh(new THREE.SphereGeometry(0.16, 20, 12), dark, this.elbowJ);
255
+ this.mesh(new THREE.BoxGeometry(0.18, 1.0, 0.18), mat, this.elbowJ).position.y = 0.5;
256
+ this.mesh(new THREE.BoxGeometry(0.3, 0.12, 0.12), dark, this.elbowJ).position.y = 1.05;
257
+ } else if (s === "light") {
258
+ const c = toColor(p.color, "#ffffff"), inten = num(p.intensity, 1);
259
+ const sub = String(p.subtype || "point").toLowerCase();
260
+ if (sub.includes("ambient")) this.light = new THREE.AmbientLight(c, inten);
261
+ else if (sub.includes("direction") || sub.includes("sun")) { this.light = new THREE.DirectionalLight(c, inten * 2); this.light.castShadow = true; }
262
+ else if (sub.includes("spot")) { this.light = new THREE.SpotLight(c, inten * 4, 0, Math.PI / 5, 0.3, 0); this.light.castShadow = true; }
263
+ else { this.light = new THREE.PointLight(c, inten * 4, 0, 0); this.light.castShadow = true; }
264
+ this.node.add(this.light);
265
+ if (this.light.target) { scene.add(this.light.target); }
266
+ if (!sub.includes("ambient")) {
267
+ const bulb = new THREE.Mesh(new THREE.SphereGeometry(0.12, 16, 8), new THREE.MeshBasicMaterial({ color: c }));
268
+ bulb.userData.nobj = this; this.bulb = bulb; this.node.add(bulb);
269
+ }
270
+ } else if (s === "camera") {
271
+ // the first camera entity drives the view (see setupView)
272
+ } else if (s === "label") {
273
+ this.label = new THREE.Sprite(new THREE.SpriteMaterial({ transparent: true, depthTest: false }));
274
+ this.label.renderOrder = 10;
275
+ this.node.add(this.label);
276
+ this._labelText = null;
277
+ } else if (s === "model") {
278
+ const sz = size3(p.size);
279
+ const ph = this.mesh(new THREE.BoxGeometry(sz[0], sz[1], sz[2]), std(col, { wireframe: true }));
280
+ const url = String(p.url || "");
281
+ if (url && typeof GLTFLoader !== "undefined") {
282
+ new GLTFLoader().load(url, g => { this.node.remove(ph); this.node.add(g.scene); hudLog(`[${this.name}] model loaded`); },
283
+ undefined, e => hudLog(`[${this.name}] could not load ${url}: ${e && e.message ? e.message : e}`));
284
+ }
285
+ } else if (s === "twin") {
286
+ const sz = size3(p.size);
287
+ const mat = std(col, { transparent: true, opacity: 0.85 }); this.colorMats.push(mat);
288
+ this.dataMesh = this.mesh(new THREE.BoxGeometry(sz[0], sz[1], sz[2]), mat); this.dataHeight = sz[1];
289
+ this.dataMesh.add(new THREE.LineSegments(new THREE.EdgesGeometry(this.dataMesh.geometry), new THREE.LineBasicMaterial({ color: 0xe8f4ff })));
290
+ }
291
+ // "group" (scene/group/...) has no geometry of its own
292
+ if (s === "twin" || (s !== "label" && s !== "group" && s !== "camera" && s !== "light" && this.p.show_name)) {
293
+ const t = labelTexture(this.name);
294
+ const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: t.tex, depthTest: false, transparent: true }));
295
+ sp.scale.set(0.35 * t.aspect, 0.35, 1);
296
+ sp.position.y = size3(p.size)[1] / 2 + 0.4;
297
+ sp.renderOrder = 10;
298
+ this.node.add(sp);
299
+ }
300
+ }
301
+
302
+ // ---- props -> visuals
303
+ apply() {
304
+ const p = this.p, n = this.node;
305
+ n.position.set(...pos3(p.position));
306
+ const r = pos3(p.rotation);
307
+ n.rotation.set(r[0] * DEG, r[1] * DEG, r[2] * DEG);
308
+ if (p.scale !== undefined) n.scale.set(...size3(p.scale)); else n.scale.set(1, 1, 1);
309
+ n.visible = p.visible !== false && p.visible !== 0 && p.visible !== "false";
310
+ let col;
311
+ // live temperature (received over a channel) drives the colour; otherwise an explicit color wins
312
+ // ...unless a behaviour set the colour explicitly ("when temperature > 80, set color to red")
313
+ if (typeof p.temperature === "number" && this.recv.has("temperature") && !this.userColor) col = temperatureColor(p.temperature);
314
+ else if (p.color !== undefined && p.color !== "") col = toColor(p.color, DEFAULT_COLORS[this.shape] || DEFAULT_COLORS.box);
315
+ else if (typeof p.temperature === "number") col = temperatureColor(p.temperature);
316
+ else col = new THREE.Color(this.shape === "tank" ? "#2f7fd8" : (DEFAULT_COLORS[this.shape] || DEFAULT_COLORS.box));
317
+ // glow: a prop named "on", otherwise the first boolean field received over a channel
318
+ let glowKey = typeof p.on === "boolean" ? "on" : null;
319
+ if (!glowKey) for (const k of this.recv) if (typeof p[k] === "boolean") { glowKey = k; break; }
320
+ const glow = glowKey ? !!p[glowKey] : false;
321
+ const opacity = p.opacity === undefined ? null : clamp(num(p.opacity, 1), 0, 1);
322
+ for (const m of this.colorMats) {
323
+ m.color.copy(col);
324
+ m.wireframe = !!p.wireframe;
325
+ if (opacity !== null) { m.transparent = opacity < 1; m.opacity = opacity; m.depthWrite = opacity >= 1; }
326
+ m.emissive.copy(col).multiplyScalar(glow ? 0.9 : 0);
327
+ }
328
+ // level/value/distance stretch the data mesh vertically (bottom stays in place); tanks always
329
+ // show their level, other shapes only data received over a channel (a "value 10" prop of a
330
+ // game object must not shrink it)
331
+ if (this.dataMesh) {
332
+ const key = ["level", "value", "distance"].find(k => typeof p[k] === "number" && (this.recv.has(k) || (this.shape === "tank" && k === "level")));
333
+ let f = 1;
334
+ if (key) { const v = p[key]; f = key === "value" && v <= 1 ? v : v / 100; f = clamp(f, 0.02, this.shape === "tank" ? 1 : 5); }
335
+ this.dataMesh.scale.y = f;
336
+ this.dataMesh.position.y = this.dataMesh.userData.anchorBottom ? this.dataHeight * f / 2 : (f - 1) * this.dataHeight / 2;
337
+ }
338
+ if (this.light) {
339
+ const c = p.color !== undefined ? toColor(p.color, "#ffffff") : new THREE.Color("#ffffff");
340
+ this.light.color.copy(c);
341
+ const base = num(p.intensity, 1) * (this.light.isPointLight || this.light.isSpotLight ? 4 : this.light.isDirectionalLight ? 2 : 1);
342
+ this.light.intensity = p.on === false ? 0 : base;
343
+ if (this.bulb) this.bulb.material.color.copy(p.on === false ? new THREE.Color("#333333") : c);
344
+ if (this.light.target) this.light.target.position.set(...pos3(p.target));
345
+ }
346
+ if (this.yaw) {
347
+ this.yaw.rotation.y = num(p.base_angle, 0) * DEG;
348
+ this.shoulderJ.rotation.z = -num(p.shoulder, 30) * DEG;
349
+ this.elbowJ.rotation.z = -num(p.elbow, 45) * DEG;
350
+ }
351
+ if (this.shape === "camera" && this === VIEW.cam) {
352
+ camera.position.set(...pos3(p.position, [6, 5, 8]));
353
+ camera.fov = num(p.fov, 50); camera.updateProjectionMatrix();
354
+ controls.target.set(...pos3(p.target));
355
+ }
356
+ this.updateLabel();
357
+ }
358
+ updateLabel() {
359
+ if (!this.label) return;
360
+ const text = this.format(this.p.text !== undefined && this.p.text !== "" ? String(this.p.text) : this.name);
361
+ if (text === this._labelText) return;
362
+ this._labelText = text;
363
+ const t = labelTexture(text, this.p.color !== undefined ? "#" + toColor(this.p.color, "#ffffff").getHexString() : "#ffffff");
364
+ if (this.label.material.map) this.label.material.map.dispose();
365
+ this.label.material.map = t.tex; this.label.material.needsUpdate = true;
366
+ const hgt = num(this.p.font_size, typeof this.p.size === "number" ? this.p.size : 0.5);
367
+ this.label.scale.set(hgt * t.aspect, hgt, 1);
368
+ }
369
+
370
+ // ---- API used by generated behaviours
371
+ get(k) {
372
+ const ax = AXES[k]; // "its y" / "x" mean the position components
373
+ if (ax !== undefined && this.p[k] === undefined) return pos3(this.p.position)[ax];
374
+ if (ROT_AXES[k] !== undefined) return pos3(this.p.rotation)[ROT_AXES[k]];
375
+ if (this.p[k] !== undefined) return this.p[k];
376
+ if (REMOTE_FIELD[k] !== undefined) return REMOTE_FIELD[k];
377
+ return 0;
378
+ }
379
+ num(k) { return num(this.get(k), 0); }
380
+ // "increase rotation by 5" / "increase size by 1": vectors get the amount on every component,
381
+ // except rotation, which spins around the vertical (Y) axis
382
+ add(k, v) {
383
+ const cur = this.get(k), d = num(v, 0);
384
+ if (Array.isArray(cur) || k === "rotation" || k === "position" || k === "scale" || k === "size") {
385
+ const q = k === "scale" || k === "size" ? size3(cur) : pos3(cur);
386
+ if (k === "rotation" || k === "position") q[1] += d; else for (let i = 0; i < 3; i++) q[i] += d;
387
+ return this.set(k, q);
388
+ }
389
+ this.set(k, num(cur, 0) + d);
390
+ }
391
+ // true only when a "when <condition>" becomes true (rising edge), used by conditional update behaviours
392
+ edge(key, cond) { this._edges = this._edges || {}; const was = this._edges[key]; this._edges[key] = !!cond; return !!cond && !was; }
393
+ set(k, v) {
394
+ if (!this.alive) return;
395
+ const ax = AXES[k];
396
+ if (ax !== undefined && this.p[k] === undefined) {
397
+ const q = pos3(this.p.position); q[ax] = num(v, q[ax]); return this.set("position", q);
398
+ }
399
+ if (ROT_AXES[k] !== undefined) {
400
+ const r = pos3(this.p.rotation), i = ROT_AXES[k], was = r[i];
401
+ r[i] = num(v, r[i]); this.set("rotation", r);
402
+ if (r[i] !== was && this.alive && !this._changing.has(k)) {
403
+ this._changing.add(k);
404
+ try { fire(this, "change", k); fireWatchers(this, k); } finally { this._changing.delete(k); }
405
+ }
406
+ return;
407
+ }
408
+ if (k === "color") this.userColor = true;
409
+ const old = this.p[k];
410
+ this.p[k] = v;
411
+ if (JSON.stringify(old) === JSON.stringify(v)) return;
412
+ if (GEOMETRY_KEYS.has(k)) this.rebuild();
413
+ this.apply();
414
+ if (!this._changing.has(k)) { // guard against change -> set -> change loops
415
+ this._changing.add(k);
416
+ try { fire(this, "change", k); fireWatchers(this, k); } finally { this._changing.delete(k); }
417
+ }
418
+ }
419
+ move(dx, dy, dz, scale = 1) {
420
+ const q = pos3(this.p.position);
421
+ this.set("position", [q[0] + num(dx) * scale, q[1] + num(dy) * scale, q[2] + num(dz) * scale]);
422
+ }
423
+ format(text) {
424
+ return String(text).replace(/\{([\w.]+)\}/g, (m, key) => {
425
+ const parts = key.split(".");
426
+ const v = parts.length > 1 ? remote(parts[0], parts.slice(1).join("_")) : (this.p[key] !== undefined ? this.p[key] : AXES[key] !== undefined ? +pos3(this.p.position)[AXES[key]].toFixed(2) : REMOTE_FIELD[key]);
427
+ return v === undefined ? m : fmt(v);
428
+ });
429
+ }
430
+ log(text) { hudLog(`[${this.name}] ${this.format(text)}`); }
431
+ destroy() {
432
+ if (!this.alive) return;
433
+ this.alive = false;
434
+ if (this.node.parent) this.node.parent.remove(this.node);
435
+ this.node.traverse(o => { if (o.geometry) o.geometry.dispose(); });
436
+ hudLog(`[${this.name}] destroyed`);
437
+ }
438
+ send(to, fields) {
439
+ let sent = 0;
440
+ for (const ch of CHANNELS) {
441
+ if (ch.src !== this.ident) continue;
442
+ if (to && ![ch.dst, ch.dst_name, ch.dst_kind, ch.id].includes(to)) continue;
443
+ sendChannel(ch, fields && fields.length ? fields : ch.fields);
444
+ sent++;
445
+ }
446
+ if (!sent) hudLog(`[${this.name}] send: no channel from ${this.name}${to ? " to " + to : ""} (connect them first)`);
447
+ }
448
+ call(name, args) {
449
+ const f = USER_FUNCTIONS[name];
450
+ if (f) return f(this, ...(args || []));
451
+ return this.builtin(name, args);
452
+ }
453
+ builtin(name, args) {
454
+ if (name === "reset") { for (const k of Object.keys(this.initial)) this.set(k, JSON.parse(JSON.stringify(this.initial[k]))); }
455
+ else if (name === "stop") this.set("speed", 0);
456
+ else if (name === "open") this.set("open", true);
457
+ else if (name === "close") this.set("open", false);
458
+ else if (name === "jump") this.move(0, 1, 0);
459
+ else if (name === "spawn") {
460
+ const c = this.node.clone(); c.position.x += 1; (this.node.parent || scene).add(c);
461
+ }
462
+ this.log(`${name}(${(args || []).map(fmt).join(", ")})`);
463
+ }
464
+ }
465
+
466
+ // ---------------------------------------------------------------- behaviours
467
+ const ERRORS = new Set();
468
+ function run(o, fn, dt = 0, other = null, msg = null) {
469
+ if (!o.alive) return;
470
+ try { fn(o, dt, other, msg); }
471
+ catch (e) { const k = o.ident + ":" + e; if (!ERRORS.has(k)) { ERRORS.add(k); hudLog(`[${o.name}] behaviour error: ${e.message || e}`); } }
472
+ }
473
+ // fire behaviours of one kind; for keyed kinds (change/input/message) only matching keys run
474
+ function fire(o, kind, key = null, extra = {}) {
475
+ const b = BEHAVIOURS[o.ident];
476
+ if (!b || !b[kind]) return;
477
+ for (const item of b[kind]) {
478
+ if (kind === "change" && item[0] !== key) continue;
479
+ // collision rules with "with": only contacts with that entity ident or kind fire
480
+ if (kind === "collision" && Array.isArray(item) && !collidesWith(extra.other, item[0])) continue;
481
+ if (kind === "message" && item[0] !== "any" && !(key || []).includes(item[0])) continue;
482
+ run(o, Array.isArray(item) ? item[item.length - 1] : item, extra.dt || 0, extra.other || null, extra.msg || null);
483
+ }
484
+ }
485
+
486
+ function collidesWith(other, keys) {
487
+ if (!other) return false;
488
+ const names = [other.ident, String(other.kind || "").toLowerCase(), String(other.name || "").toLowerCase()];
489
+ return keys.some(k => names.includes(k));
490
+ }
491
+ // "change:<entity>.<prop>" rules on other objects watching src's prop
492
+ function fireWatchers(src, k) {
493
+ const names = new Set([src.ident, String(src.kind || "").toLowerCase(), String(src.name || "").toLowerCase()]);
494
+ for (const o of OBJS.values()) {
495
+ if (o === src || !o.alive) continue;
496
+ const b = BEHAVIOURS[o.ident];
497
+ if (!b || !b.change) continue;
498
+ for (const item of b.change) {
499
+ const key = item[0], dot = key.indexOf(".");
500
+ if (dot > 0 && key.slice(dot + 1) === k && names.has(key.slice(0, dot))) run(o, item[item.length - 1], 0, src);
501
+ }
502
+ }
503
+ }
504
+
505
+ // ---------------------------------------------------------------- channels
506
+ const HUB = { lastOk: 0, everOk: false };
507
+ function hubOnline() { return performance.now() - HUB.lastOk < 3000; }
508
+ function payloadOf(o, fields) {
509
+ const out = {};
510
+ for (const f of fields) out[f] = o ? o.get(f) : 0;
511
+ return out;
512
+ }
513
+ async function postHub(ch, payload) {
514
+ // hub offline: retry at most every 3 s (each failed fetch is a console error)
515
+ const now = performance.now();
516
+ if (!hubOnline() && now - (ch.lastPost || -1e9) < 3000) return;
517
+ ch.lastPost = now;
518
+ try {
519
+ const r = await fetch(ch.url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) });
520
+ if (r.ok) { HUB.lastOk = performance.now(); HUB.everOk = true; }
521
+ } catch (e) { /* hub offline: ignore */ }
522
+ }
523
+ function sendChannel(ch, fields) {
524
+ const o = OBJS.get(ch.src);
525
+ if (!o || !o.alive) return;
526
+ const payload = Object.assign({ channel: ch.id, from: ch.src }, payloadOf(o, fields));
527
+ if (ch.dir === "local") deliver(ch, payload);
528
+ else if (ch.pollable) postHub(ch, payload);
529
+ else hudLog(`[${ch.id}] ${ch.protocol} is not reachable from a browser; would send ${JSON.stringify(payloadOf(o, fields))}`);
530
+ }
531
+ // a message arrived for channel ch: remember it, copy fields onto the destination, fire behaviours
532
+ function deliver(ch, msg) {
533
+ const fields = {};
534
+ // null/undefined = the sender has no value yet: keep what we have
535
+ for (const [k, v] of Object.entries(msg)) if (k !== "channel" && k !== "from" && !k.startsWith("_") && v !== null && v !== undefined) fields[k] = v;
536
+ REMOTE[ch.src] = Object.assign(REMOTE[ch.src] || {}, fields);
537
+ Object.assign(REMOTE_FIELD, fields);
538
+ ch.last = fields;
539
+ const dst = OBJS.get(ch.dst);
540
+ if (!dst || !dst.alive) return;
541
+ let rising = false;
542
+ const hasBool = Object.values(fields).some(v => typeof v === "boolean");
543
+ let newKey = false;
544
+ for (const [k, v] of Object.entries(fields)) {
545
+ if (typeof v === "boolean" && v && dst.p[k] !== true) rising = true;
546
+ if (!dst.recv.has(k)) { dst.recv.add(k); newKey = true; }
547
+ dst.set(k, v);
548
+ }
549
+ if (newKey && dst.alive) dst.apply(); // a field that is now live may change how the object is drawn
550
+ const names = [ch.src, ch.src_name, ch.src_kind, ch.id];
551
+ fire(dst, "message", names, { msg: fields });
552
+ // input:<remote entity> fires on a rising boolean edge (or on every message without booleans)
553
+ const b = BEHAVIOURS[dst.ident];
554
+ if (b && b.input) for (const [type, key, fn] of b.input) {
555
+ if (type === "remote" && names.includes(key) && (rising || !hasBool)) run(dst, fn, 0, null, fields);
556
+ }
557
+ }
558
+ // plausible fake values for a sender we cannot reach
559
+ function fake(ch, f) {
560
+ const prev = (REMOTE[ch.src] || {})[f];
561
+ const srcObj = OBJS.get(ch.src);
562
+ const dstObj = OBJS.get(ch.dst);
563
+ const seed = srcObj ? srcObj.get(f) : (dstObj ? dstObj.p[f] : undefined); // start near the current value
564
+ if (typeof prev === "boolean" || typeof seed === "boolean" || /^(on|off|pressed|active|enabled|alarm|open|running|state|motion|detected)$/.test(f)) {
565
+ const cur = typeof prev === "boolean" ? prev : false;
566
+ return Math.random() < 0.15 ? !cur : cur;
567
+ }
568
+ const base = { temperature: 24, humidity: 45, distance: 100, light: 300, pressure: 1013, voltage: 3.3, level: 50, value: 0.5, speed: 1 }[f];
569
+ const start = typeof prev === "number" ? prev : (typeof seed === "number" && seed !== 0 ? seed : (base !== undefined ? base : 10));
570
+ const step = f === "level" ? 3 : f === "value" ? 0.05 : f === "temperature" ? 0.8 : 1;
571
+ let v = start + (Math.random() * 2 - 1) * step;
572
+ if (f === "level") v = clamp(v, 0, 100);
573
+ if (f === "value") v = clamp(v, 0, 1);
574
+ return Math.round(v * 100) / 100;
575
+ }
576
+ function startChannels() {
577
+ for (const ch of CHANNELS) {
578
+ ch.seen = null; ch.liveAt = 0; ch.last = null;
579
+ const every = Math.max(100, ch.interval_ms || 1000);
580
+ if (ch.dir === "out" || ch.dir === "local") {
581
+ setInterval(() => sendChannel(ch, ch.fields), every); // sender auto-publishes its fields
582
+ }
583
+ if (ch.dir === "in") {
584
+ if (ch.pollable) {
585
+ ch.lastTry = -1e9;
586
+ setInterval(async () => {
587
+ // while the hub is offline retry every 3 s instead of every poll (less console noise)
588
+ const now = performance.now();
589
+ if (!hubOnline() && now - ch.lastTry < 3000) return;
590
+ ch.lastTry = now;
591
+ try {
592
+ const r = await fetch(ch.url, { cache: "no-store" });
593
+ const msg = await r.json();
594
+ HUB.lastOk = performance.now(); HUB.everOk = true;
595
+ if (msg && msg._t !== undefined && msg._t !== ch.seen) { ch.seen = msg._t; ch.liveAt = performance.now(); deliver(ch, msg); }
596
+ } catch (e) { /* hub offline */ }
597
+ }, HUB_POLL_MS);
598
+ }
599
+ // simulate the sender whenever no fresh real data arrives
600
+ setInterval(() => {
601
+ if (performance.now() - ch.liveAt < Math.max(5000, 3 * every)) return;
602
+ const msg = { channel: ch.id, from: ch.src };
603
+ for (const f of ch.fields) msg[f] = fake(ch, f);
604
+ ch.simulated = true;
605
+ deliver(ch, msg);
606
+ }, every);
607
+ }
608
+ }
609
+ }
610
+
611
+ // ---------------------------------------------------------------- input
612
+ const KEY_ALIASES = { space: " ", spacebar: " ", enter: "enter", return: "enter", up: "arrowup", down: "arrowdown",
613
+ left: "arrowleft", right: "arrowright", esc: "escape", escape: "escape", ctrl: "control", control: "control",
614
+ shift: "shift", alt: "alt", tab: "tab", backspace: "backspace", delete: "delete" };
615
+ function keyMatches(name, ev) {
616
+ const n = String(name).toLowerCase().trim();
617
+ const k = (ev.key || "").toLowerCase(), c = (ev.code || "").toLowerCase();
618
+ const want = KEY_ALIASES[n] || n.replace(/^key_?/, "").replace(/_/g, " ");
619
+ return k === want || c === n || c === "key" + want || c === "digit" + want || (want.startsWith("arrow") && c === want);
620
+ }
621
+ const HELD = new Set();
622
+ window.addEventListener("keydown", ev => {
623
+ HELD.add((ev.key || "").toLowerCase());
624
+ if (ev.repeat) return;
625
+ for (const o of OBJS.values()) {
626
+ const b = BEHAVIOURS[o.ident];
627
+ if (!b || !b.input) continue;
628
+ for (const [type, key, fn] of b.input) if (type === "key" && keyMatches(key, ev)) run(o, fn);
629
+ }
630
+ });
631
+ window.addEventListener("keyup", ev => HELD.delete((ev.key || "").toLowerCase()));
632
+ window.addEventListener("blur", () => HELD.clear());
633
+ // clicking an object fires input:<that object's name> behaviours (on any object listening to it)
634
+ const raycaster = new THREE.Raycaster();
635
+ let downAt = null;
636
+ renderer.domElement.addEventListener("pointerdown", ev => { downAt = [ev.clientX, ev.clientY]; });
637
+ renderer.domElement.addEventListener("pointerup", ev => {
638
+ if (!downAt || Math.hypot(ev.clientX - downAt[0], ev.clientY - downAt[1]) > 5) return; // was a drag (orbit)
639
+ const ndc = new THREE.Vector2(ev.clientX / window.innerWidth * 2 - 1, -(ev.clientY / window.innerHeight) * 2 + 1);
640
+ raycaster.setFromCamera(ndc, camera);
641
+ const hit = raycaster.intersectObjects(scene.children, true).find(h => h.object.userData.nobj || findOwner(h.object));
642
+ if (!hit) return;
643
+ const target = hit.object.userData.nobj || findOwner(hit.object);
644
+ for (const o of OBJS.values()) {
645
+ const b = BEHAVIOURS[o.ident];
646
+ if (!b || !b.input) continue;
647
+ for (const [type, key, fn] of b.input) {
648
+ if (type !== "click") continue;
649
+ if ([target.ident, target.name, target.kind].includes(key) || isAncestor(OBJS.get(key), target)) run(o, fn, 0, target);
650
+ }
651
+ }
652
+ });
653
+ function findOwner(o3) { while (o3) { if (o3.userData && o3.userData.nobj) return o3.userData.nobj; o3 = o3.parent; } return null; }
654
+ function isAncestor(a, b) { if (!a) return false; let n = b.node.parent; while (n) { if (n === a.node) return true; n = n.parent; } return false; }
655
+
656
+ // ---------------------------------------------------------------- collisions
657
+ const TOUCHING = new Set();
658
+ let collisionsPrimed = false;
659
+ const SOLID = new Set(["box", "sphere", "cylinder", "cone", "torus", "plane", "ground", "building", "tank", "pipe", "arm", "model", "twin"]);
660
+ function related(a, b) { return isAncestor(a, b) || isAncestor(b, a); }
661
+ function checkCollisions() {
662
+ const watchers = [...OBJS.values()].filter(o => o.alive && BEHAVIOURS[o.ident] && BEHAVIOURS[o.ident].collision);
663
+ if (!watchers.length) return;
664
+ const solids = [...OBJS.values()].filter(o => o.alive && o.node.visible && SOLID.has(o.shape));
665
+ const boxes = new Map(solids.map(o => [o, new THREE.Box3().setFromObject(o.node)]));
666
+ for (const a of watchers) {
667
+ const ba = boxes.get(a) || new THREE.Box3().setFromObject(a.node);
668
+ if (ba.isEmpty()) continue;
669
+ for (const b of solids) {
670
+ if (b === a || related(a, b)) continue;
671
+ const key = a.ident + "|" + b.ident;
672
+ if (ba.intersectsBox(boxes.get(b))) {
673
+ // contacts that already exist in the initial layout (e.g. resting on the ground) do not fire
674
+ if (!TOUCHING.has(key)) { TOUCHING.add(key); if (collisionsPrimed) fire(a, "collision", null, { other: b }); }
675
+ } else TOUCHING.delete(key);
676
+ }
677
+ }
678
+ collisionsPrimed = true;
679
+ }
680
+
681
+ // ---------------------------------------------------------------- HUD rendering
682
+ function renderHud() {
683
+ if (!hudEl) return;
684
+ let h = `<b>${esc(PROJECT)}</b>`;
685
+ for (const o of OBJS.values()) {
686
+ if (!o.alive) continue;
687
+ const data = Object.entries(o.p).filter(([k, v]) => !NON_DATA.has(k) && !k.startsWith("_") && (typeof v !== "object" || v === null));
688
+ h += `<div class="ent"><span class="nm">${esc(o.name)}</span> <span class="kd">${esc(o.kind)}</span>`;
689
+ for (const [k, v] of data) h += `<div class="pr">${esc(k)}: <b${o.recv.has(k) ? ' class="live"' : ""}>${esc(fmt(v))}</b></div>`;
690
+ h += `</div>`;
691
+ }
692
+ if (CHANNELS.length) {
693
+ h += `<div class="ent"><span class="nm">channels</span>`;
694
+ for (const ch of CHANNELS) {
695
+ const live = ch.liveAt > 0 && performance.now() - ch.liveAt < 5000;
696
+ const state = ch.dir === "in" ? (live ? "live" : "simulated") : ch.dir;
697
+ h += `<div class="pr">${esc(ch.src_name)} &rarr; ${esc(ch.dst_name)} <i>${esc(ch.protocol)}</i> ${esc(state)}</div>`;
698
+ }
699
+ h += `</div>`;
700
+ }
701
+ hudEl.innerHTML = h;
702
+ if (badgeEl) {
703
+ if (!CHANNELS.some(c => c.pollable && c.dir !== "local")) { badgeEl.style.display = "none"; }
704
+ else if (!hubOnline()) { badgeEl.textContent = "hub offline - simulated"; badgeEl.className = "off"; }
705
+ else if (CHANNELS.some(c => c.dir === "in" && c.pollable && !(c.liveAt > 0 && performance.now() - c.liveAt < 5000))) { badgeEl.textContent = "hub online - waiting for data (simulated)"; badgeEl.className = "wait"; }
706
+ else { badgeEl.textContent = "hub online"; badgeEl.className = "on"; }
707
+ }
708
+ for (const o of OBJS.values()) if (o.alive) o.updateLabel();
709
+ }
710
+
711
+ // ---------------------------------------------------------------- build + view
712
+ for (const d of DEFS) {
713
+ const o = new NObj(d);
714
+ OBJS.set(d.ident, o);
715
+ }
716
+ for (const d of DEFS) {
717
+ const o = OBJS.get(d.ident);
718
+ const parent = d.parent ? OBJS.get(d.parent) : null;
719
+ (parent ? parent.node : scene).add(o.node);
720
+ }
721
+ (function setupView() {
722
+ const camObj = [...OBJS.values()].find(o => o.shape === "camera");
723
+ const box = new THREE.Box3();
724
+ // frame the interesting objects; large floors only count when there is nothing else
725
+ const all = [...OBJS.values()].filter(o => SOLID.has(o.shape) || o.shape === "room");
726
+ const focus = all.filter(o => !["ground", "plane"].includes(o.shape));
727
+ for (const o of (focus.length ? focus : all)) box.expandByObject(o.node);
728
+ const size = box.isEmpty() ? 4 : Math.max(...box.getSize(new THREE.Vector3()).toArray(), 1);
729
+ grid.scale.setScalar(Math.max(1, Math.ceil(size / 20)));
730
+ camera.far = Math.max(5000, size * 50); camera.near = Math.max(0.01, size / 2000);
731
+ if (camObj) { VIEW.cam = camObj; camObj.apply(); }
732
+ else {
733
+ const c = box.isEmpty() ? new THREE.Vector3() : box.getCenter(new THREE.Vector3());
734
+ camera.position.set(c.x + size * 1.2, c.y + size * 0.9, c.z + size * 1.6);
735
+ controls.target.copy(c);
736
+ }
737
+ camera.updateProjectionMatrix();
738
+ })();
739
+
740
+ // ---------------------------------------------------------------- main loop
741
+ function step(dt) {
742
+ for (const o of OBJS.values()) {
743
+ if (!o.alive) continue;
744
+ // "movable" objects: WASD / arrow keys at <speed> units per second
745
+ if (o.p.movable === true) {
746
+ const sp = num(o.p.speed, 2) * dt;
747
+ let dx = 0, dz = 0;
748
+ if (HELD.has("a") || HELD.has("arrowleft")) dx -= sp;
749
+ if (HELD.has("d") || HELD.has("arrowright")) dx += sp;
750
+ if (HELD.has("w") || HELD.has("arrowup")) dz -= sp;
751
+ if (HELD.has("s") || HELD.has("arrowdown")) dz += sp;
752
+ if (dx || dz) o.move(dx, 0, dz);
753
+ }
754
+ const b = BEHAVIOURS[o.ident];
755
+ if (!b) continue;
756
+ if (b.update) for (const fn of b.update) run(o, fn, dt);
757
+ }
758
+ checkCollisions();
759
+ }
760
+ // timer:<ms> behaviours use real elapsed time (not frames), so they keep their rate even when
761
+ // requestAnimationFrame is throttled (background tab); at most 10 catch-up runs per tick
762
+ const timerAcc = new Map();
763
+ let timerLast = performance.now();
764
+ setInterval(() => {
765
+ const now = performance.now(), elapsed = Math.min(now - timerLast, 10000);
766
+ timerLast = now;
767
+ for (const o of OBJS.values()) {
768
+ const b = BEHAVIOURS[o.ident];
769
+ if (!o.alive || !b || !b.timer) continue;
770
+ b.timer.forEach(([ms, fn], i) => {
771
+ const k = o.ident + "#" + i;
772
+ let acc = (timerAcc.get(k) || 0) + elapsed, n = 0;
773
+ while (acc >= ms && o.alive && n++ < 10) { acc -= ms; run(o, fn, ms / 1000); }
774
+ timerAcc.set(k, Math.min(acc, ms));
775
+ });
776
+ }
777
+ }, 20);
778
+ const clock = new THREE.Clock();
779
+ function frame() {
780
+ requestAnimationFrame(frame);
781
+ const dt = Math.min(clock.getDelta(), 0.1);
782
+ step(dt);
783
+ controls.update();
784
+ renderer.render(scene, camera);
785
+ }
786
+ for (const o of OBJS.values()) fire(o, "start");
787
+ startChannels();
788
+ setInterval(renderHud, 250);
789
+ renderHud();
790
+ hudLog(`${PROJECT}: ${OBJS.size} objects, ${CHANNELS.length} channels`);
791
+ frame();
792
+ // handy for debugging from the browser console
793
+ window.nlcl = { THREE, scene, camera, OBJS, REMOTE, CHANNELS, deliver, step, fire };
nlcl/modules/_assets/app/app_runtime.js ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // NLCL application runtime for the browser (installable PWA: Android, iOS, ChromeOS, any desktop).
2
+ // SPEC / HANDLERS / CALLS are generated; this file renders the widgets and runs the behaviours.
3
+ "use strict";
4
+ const CONTAINERS = new Set(["app", "window", "dialog", "form", "frame", "panel", "group", "page", "tab", "screen"]);
5
+
6
+ class NlclApp {
7
+ constructor(spec, handlers, calls, mount) {
8
+ this.spec = spec; this.h = handlers; this.calls = calls || {};
9
+ this.S = {}; this.kind = {}; this.el = {}; this.remote = {}; this.logs = []; this.busy = new Set(); this.edges = {};
10
+ for (const w of spec.widgets) { this.S[w.id] = Object.assign({}, w.props || {}); this.kind[w.id] = w.kind; }
11
+ this.mount = mount || (typeof document !== "undefined" ? document.getElementById("app") : null);
12
+ if (this.mount) this.build();
13
+ }
14
+ // ---- state
15
+ get(id, prop, dflt = 0) {
16
+ if (id in this.S) return prop in this.S[id] ? this.S[id][prop] : dflt;
17
+ const k = id + "." + prop; return k in this.remote ? this.remote[k] : dflt;
18
+ }
19
+ set(id, prop, value) {
20
+ if (!(id in this.S)) { this.remote[id + "." + prop] = value; return; }
21
+ const old = this.S[id][prop]; this.S[id][prop] = value; this.push(id, prop);
22
+ if (old !== value) this.fireChange(id, prop);
23
+ }
24
+ toggle(id, prop) { this.set(id, prop, !this.get(id, prop, false)); }
25
+ add(id, prop, amount) {
26
+ const cur = this.get(id, prop, 0);
27
+ if (typeof cur === "string" && isNaN(Number(cur))) this.set(id, prop, cur + String(amount));
28
+ else this.set(id, prop, Number(cur) + Number(amount));
29
+ }
30
+ log(id, text) {
31
+ const line = "[" + id + "] " + String(text).replace(/\{([\w.]+)\}/g, (m, k) => {
32
+ const i = k.indexOf("."); return String(i < 0 ? this.get(id, k, m) : this.get(k.slice(0, i), k.slice(i + 1), m));
33
+ });
34
+ this.logs.push(line); console.log(line);
35
+ const s = typeof document !== "undefined" ? document.getElementById("status") : null; if (s) s.textContent = line;
36
+ }
37
+ hide(id) { if (this.S[id]) this.S[id].visible = false; if (this.el[id]) this.el[id].style.display = "none"; }
38
+ call(id, name, ...args) {
39
+ if (this.calls[name]) return this.calls[name](this, id, ...args);
40
+ this.log(id, name + "(" + args.join(", ") + ") called - add it to CALLS in app.js");
41
+ }
42
+ send(id, to, fields) {
43
+ for (const ch of this.spec.channels || [])
44
+ if (ch.dir === "out" && ch.src === id && (!to || to === ch.dst || to === ch.id)) this.post(ch, fields && fields.length ? fields : ch.fields);
45
+ }
46
+ // ---- events
47
+ run(list) { for (const [owner, fn] of list || []) { try { fn(this); } catch (e) { this.log(owner, "error in behaviour: " + e.message); } } }
48
+ click(id) { this.run((this.h.click || {})[id]); }
49
+ key(name) { this.run((this.h.key || {})[name]); }
50
+ edge(key, cond) { const was = !!this.edges[key]; this.edges[key] = !!cond; return !!cond && !was; }
51
+ fireChange(id, prop) {
52
+ const k = id + "." + prop; if (this.busy.has(k)) return;
53
+ this.busy.add(k); try { this.run((this.h.change || {})[k]); } finally { this.busy.delete(k); }
54
+ }
55
+ message(src, payload) {
56
+ for (const [k, v] of Object.entries(payload || {})) if (!["channel", "from", "_t"].includes(k) && v !== null) this.remote[src + "." + k] = v;
57
+ this.run(((this.h.message || {})[src] || []).concat((this.h.message || {}).any || []));
58
+ }
59
+ // ---- DOM
60
+ build() {
61
+ document.title = this.spec.title || "NLCL app";
62
+ const frames = { "": this.mount };
63
+ for (const w of this.spec.widgets) {
64
+ const parent = frames[w.parent || ""] || this.mount, p = this.S[w.id];
65
+ if (["app", "window", "dialog", "screen", "page"].includes(w.kind) && !w.parent) { frames[w.id] = this.mount; continue; }
66
+ if (CONTAINERS.has(w.kind)) {
67
+ const f = document.createElement("fieldset"); const lg = document.createElement("legend");
68
+ lg.textContent = String(p.title || p.text || w.id); f.appendChild(lg); parent.appendChild(f); frames[w.id] = f; this.el[w.id] = f; continue;
69
+ }
70
+ const e = this.make(w.kind, w.id, p); if (!e) continue;
71
+ e.classList.add("w"); parent.appendChild(e); this.el[w.id] = e; if (p.visible === false) e.style.display = "none";
72
+ }
73
+ document.addEventListener("keydown", (ev) => {
74
+ if (/^(INPUT|TEXTAREA|SELECT)$/.test(ev.target.tagName)) return;
75
+ const n = { " ": "space", Enter: "enter", Escape: "escape", ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right" }[ev.key] || ev.key.toLowerCase();
76
+ this.key(n);
77
+ });
78
+ }
79
+ make(kind, id, p) {
80
+ let text = String(p.text !== undefined ? p.text : (p.label !== undefined ? p.label : id.replace(/_/g, " ")));
81
+ if (["label", "title", "heading"].includes(kind) && p.text === undefined && p.value !== undefined) text = String(p.value);
82
+ const mk = (tag, cls) => { const e = document.createElement(tag); if (cls) e.className = cls; e.dataset.id = id; return e; };
83
+ const fromWidget = (prop, value) => { const old = this.S[id][prop]; this.S[id][prop] = value; if (old !== value) this.fireChange(id, prop); };
84
+ const num = (raw, like) => (typeof like === "number" && raw !== "" && !isNaN(Number(raw)) ? Number(raw) : raw);
85
+ if (kind === "button") { const b = mk("button"); b.textContent = text; b.onclick = () => this.click(id); return b; }
86
+ if (["label", "title", "heading", "link"].includes(kind)) {
87
+ const l = mk(kind === "title" || kind === "heading" ? "h2" : "div", "label"); l.textContent = text; l.onclick = () => this.click(id); return l;
88
+ }
89
+ if (["input", "textbox", "entry", "field", "password", "search", "number"].includes(kind)) {
90
+ const row = mk("label", "row"); const cap = p.label || p.placeholder; if (cap) row.append(String(cap) + ": ");
91
+ const i = document.createElement("input"); i.type = kind === "password" ? "password" : (typeof p.value === "number" ? "number" : "text");
92
+ i.value = p.value !== undefined ? p.value : ""; i.oninput = () => fromWidget("value", num(i.value, p.value));
93
+ i.onkeydown = (ev) => { if (ev.key === "Enter") this.click(id); }; row.appendChild(i); return row;
94
+ }
95
+ if (kind === "textarea") { const t = mk("textarea"); t.rows = p.rows || 5; t.value = p.value || ""; t.oninput = () => fromWidget("value", t.value); return t; }
96
+ if (kind === "checkbox" || kind === "switch") {
97
+ const row = mk("label", "row"); const c = document.createElement("input"); c.type = "checkbox"; c.checked = !!p.checked;
98
+ c.onchange = () => { fromWidget("checked", c.checked); this.click(id); }; const s = document.createElement("span"); s.textContent = " " + text;
99
+ row.append(c, s); return row;
100
+ }
101
+ if (kind === "slider" || kind === "spinner") {
102
+ const row = mk("label", "row"); row.append(text + ": "); const r = document.createElement("input"); r.type = "range";
103
+ r.min = p.min !== undefined ? p.min : 0; r.max = p.max !== undefined ? p.max : 100; r.value = p.value || 0;
104
+ r.oninput = () => fromWidget("value", Number(r.value)); row.appendChild(r); return row;
105
+ }
106
+ if (kind === "progress") { const g = mk("progress"); g.max = p.max || 100; g.value = p.value || 0; return g; }
107
+ if (kind === "dropdown" || kind === "select") {
108
+ const s = mk("select"); for (const it of p.items || []) { const o = document.createElement("option"); o.textContent = String(it); s.appendChild(o); }
109
+ if (p.value !== undefined) s.value = p.value; s.onchange = () => { fromWidget("value", s.value); this.click(id); }; return s;
110
+ }
111
+ if (["list", "listbox", "table"].includes(kind)) {
112
+ const u = mk("ul", "list"); this.fillList(u, id, p.items || []); return u;
113
+ }
114
+ if (["image", "canvas", "chart"].includes(kind)) { const c = mk("canvas"); c.height = p.height || 120; c.onclick = () => this.click(id); return c; }
115
+ if (["timer", "object", "service", "store", "model", "counter", "data"].includes(kind)) return null;
116
+ const d = mk("div", "label"); d.textContent = text; return d;
117
+ }
118
+ fillList(u, id, items) {
119
+ u.innerHTML = "";
120
+ for (const it of items) { const li = document.createElement("li"); li.textContent = String(it);
121
+ li.onclick = () => { const old = this.S[id].value; this.S[id].value = it; if (old !== it) this.fireChange(id, "value"); this.click(id); }; u.appendChild(li); }
122
+ }
123
+ push(id, prop) {
124
+ const e = this.el[id]; if (!e) return; const v = this.S[id][prop];
125
+ if (prop === "visible") { e.style.display = v ? "" : "none"; return; }
126
+ const inp = e.matches("input,textarea,select,progress") ? e : e.querySelector("input,textarea,select,progress");
127
+ if (prop === "items" && e.tagName === "UL") return this.fillList(e, id, v || []);
128
+ if (prop === "checked" && inp) { inp.checked = !!v; return; }
129
+ if (prop === "value" && inp) { if (String(inp.value) !== String(v)) inp.value = v; return; }
130
+ if (prop === "value" && (e.classList.contains("label") || e.tagName === "H2") && this.S[id].text === undefined) { e.textContent = String(v); return; }
131
+ if (prop === "text" || prop === "label") {
132
+ if (e.tagName === "BUTTON" || e.classList.contains("label") || e.tagName === "H2") e.textContent = String(v);
133
+ else { const s = e.querySelector("span"); if (s) s.textContent = " " + String(v); }
134
+ }
135
+ }
136
+ // ---- channels (HTTP hub)
137
+ post(ch, fields) {
138
+ const payload = { channel: ch.id, from: ch.src }; for (const f of fields) payload[f] = this.get(ch.src, f, null);
139
+ if (typeof fetch === "undefined") return;
140
+ fetch(ch.url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }).catch(() => {});
141
+ }
142
+ deliver(ch, msg) {
143
+ for (const [k, v] of Object.entries(msg)) if (!["channel", "from", "_t"].includes(k) && v !== null) this.set(ch.dst, k, v);
144
+ this.message(ch.src, msg);
145
+ }
146
+ // ---- main loop
147
+ start(net = true) {
148
+ this.run(this.h.start);
149
+ this.timers = (this.h.timers || []).map(([owner, ms, fn]) => ({ owner, ms, fn, due: Date.now() + ms }));
150
+ if (net && typeof fetch !== "undefined") for (const ch of this.spec.channels || []) {
151
+ if (ch.dir === "out") this.timers.push({ owner: ch.src, ms: ch.interval_ms || 1000, fn: (a) => a.post(ch, ch.fields), due: Date.now() });
152
+ else { let seen = null; setInterval(() => fetch(ch.url).then((r) => r.json()).then((m) => {
153
+ if (m && m._t !== seen && Object.keys(m).length) { seen = m._t; this.deliver(ch, m); } }).catch(() => {}), Math.max(300, (ch.interval_ms || 1000) / 2)); }
154
+ }
155
+ }
156
+ step() {
157
+ const now = Date.now();
158
+ for (const t of this.timers) if (now >= t.due) { t.due = now + t.ms; this.run([[t.owner, t.fn]]); }
159
+ this.run(this.h.update);
160
+ }
161
+ mainloop() { this.start(); setInterval(() => this.step(), 50); }
162
+ selftest() { // used by `node app.js --selftest` (no DOM): fire every event once
163
+ this.start(false);
164
+ for (const id of Object.keys(this.h.click || {})) this.click(id);
165
+ for (const k of Object.keys(this.h.key || {})) this.key(k);
166
+ for (const s of Object.keys(this.h.message || {})) this.message(s, {});
167
+ for (const t of this.timers) t.due = 0;
168
+ this.step(); this.step();
169
+ console.log("SELFTEST OK " + JSON.stringify(this.S));
170
+ }
171
+ }
172
+ if (typeof module !== "undefined") module.exports = { NlclApp };
nlcl/modules/_assets/app/nlcl_app.py ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NLCL application runtime (Python standard library only: Tkinter).
2
+
3
+ Runs on Windows, macOS and Linux. The generated app.py supplies SPEC (windows + widgets),
4
+ HANDLERS (behaviours) and optional CALLS (your own functions); this file turns them into a
5
+ running GUI. ``--selftest`` builds the UI, fires every event once and exits (used by NLCL's
6
+ run step and handy in CI); ``--headless`` runs the logic without a display.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import queue
13
+ import re
14
+ import sys
15
+ import threading
16
+ import time
17
+ import urllib.request
18
+
19
+ try:
20
+ import tkinter as tk
21
+ from tkinter import ttk
22
+ except Exception: # no Tk on this Python build: logic still works with --headless
23
+ tk = None
24
+ ttk = None
25
+
26
+ CONTAINERS = {"app", "window", "dialog", "form", "frame", "panel", "group", "page", "tab", "screen"}
27
+ TEXT_PROP = {"button": "text", "label": "text", "checkbox": "text", "switch": "text", "title": "text",
28
+ "heading": "text", "link": "text"}
29
+ VALUE_PROP = {"input": "value", "textbox": "value", "entry": "value", "field": "value", "textarea": "value",
30
+ "slider": "value", "progress": "value", "dropdown": "value", "select": "value",
31
+ "checkbox": "checked", "switch": "checked", "spinner": "value", "number": "value",
32
+ "password": "value", "search": "value"}
33
+
34
+
35
+ class App:
36
+ def __init__(self, spec, handlers, calls=None, headless=False):
37
+ self.spec = spec
38
+ self.h = handlers
39
+ self.calls = calls or {}
40
+ self.S = {w["id"]: dict(w.get("props", {})) for w in spec["widgets"]}
41
+ self.kind = {w["id"]: w["kind"] for w in spec["widgets"]}
42
+ self.remote_values = {}
43
+ self.widgets, self.vars = {}, {}
44
+ self.logs = []
45
+ self.headless = headless or tk is None
46
+ self.root = None
47
+ self._q = queue.Queue()
48
+ self._busy = set()
49
+ self._edges = {}
50
+ if not self.headless:
51
+ try:
52
+ self.root = tk.Tk()
53
+ except Exception as e: # no display (server / CI)
54
+ print(f"[app] no display ({e}); running headless", flush=True)
55
+ self.headless = True
56
+ if self.root is not None:
57
+ self._build()
58
+
59
+ # ------------------------------------------------------------------ state
60
+ def get(self, ident, prop, default=0):
61
+ if ident in self.S:
62
+ self._pull(ident)
63
+ return self.S[ident].get(prop, default)
64
+ return self.remote_values.get((ident, prop), default)
65
+
66
+ def set(self, ident, prop, value):
67
+ if ident not in self.S:
68
+ self.remote_values[(ident, prop)] = value
69
+ return
70
+ old = self.S[ident].get(prop)
71
+ self.S[ident][prop] = value
72
+ self._push(ident, prop)
73
+ if old != value:
74
+ self._fire_change(ident, prop)
75
+
76
+ def toggle(self, ident, prop):
77
+ self.set(ident, prop, not bool(self.get(ident, prop, False)))
78
+
79
+ def add(self, ident, prop, amount):
80
+ cur = self.get(ident, prop, 0)
81
+ if isinstance(cur, str) or isinstance(amount, str):
82
+ try:
83
+ cur = float(cur) if "." in str(cur) else int(cur or 0)
84
+ except ValueError:
85
+ self.set(ident, prop, f"{cur}{amount}")
86
+ return
87
+ self.set(ident, prop, cur + amount)
88
+
89
+ def log(self, ident, text):
90
+ def sub(m):
91
+ key = m.group(1)
92
+ if "." in key:
93
+ e, p = key.split(".", 1)
94
+ return str(self.get(e, p, m.group(0)))
95
+ return str(self.get(ident, key, m.group(0)))
96
+ line = f"[{ident}] " + re.sub(r"\{([\w.]+)\}", sub, str(text))
97
+ self.logs.append(line)
98
+ print(line, flush=True)
99
+ if self.root is not None and getattr(self, "status", None) is not None:
100
+ self.status.set(line)
101
+
102
+ def hide(self, ident):
103
+ self.S.get(ident, {})["visible"] = False
104
+ w = self.widgets.get(ident)
105
+ if w is not None:
106
+ try:
107
+ w.pack_forget()
108
+ except Exception:
109
+ pass
110
+
111
+ def call(self, ident, name, *args):
112
+ fn = self.calls.get(name)
113
+ if fn:
114
+ return fn(self, ident, *args)
115
+ self.log(ident, f"{name}({', '.join(map(str, args))}) called - add it to CALLS in app.py")
116
+
117
+ def send(self, ident, to=None, fields=None):
118
+ for ch in self.spec.get("channels", []):
119
+ if ch["dir"] == "out" and ch["src"] == ident and (not to or to in (ch["dst"], ch["id"])):
120
+ self._post(ch, fields or ch["fields"])
121
+
122
+ # ------------------------------------------------------------------ events
123
+ def _run(self, fns):
124
+ for owner, fn in fns:
125
+ try:
126
+ fn(self)
127
+ except Exception as e:
128
+ self.log(owner, f"error in behaviour: {type(e).__name__}: {e}")
129
+
130
+ def click(self, ident):
131
+ self._run(self.h.get("click", {}).get(ident, []))
132
+
133
+ def key(self, name):
134
+ self._run(self.h.get("key", {}).get(name, []))
135
+
136
+ def edge(self, key, cond):
137
+ """True only when a condition becomes true (for 'when x is above 5, ...' rules)."""
138
+ was = self._edges.get(key, False)
139
+ self._edges[key] = bool(cond)
140
+ return bool(cond) and not was
141
+
142
+ def _fire_change(self, ident, prop):
143
+ k = (ident, prop)
144
+ if k in self._busy:
145
+ return
146
+ self._busy.add(k)
147
+ try:
148
+ self._run(self.h.get("change", {}).get(k, []))
149
+ finally:
150
+ self._busy.discard(k)
151
+
152
+ def message(self, src, payload):
153
+ for k, v in payload.items():
154
+ if k not in ("channel", "from", "_t") and v is not None:
155
+ self.remote_values[(src, k)] = v
156
+ self._run(self.h.get("message", {}).get(src, []) + self.h.get("message", {}).get("any", []))
157
+
158
+ def tick(self):
159
+ self._run(self.h.get("update", []))
160
+
161
+ # ------------------------------------------------------------------ GUI
162
+ def _build(self):
163
+ spec, root = self.spec, self.root
164
+ root.title(spec.get("title", "NLCL app"))
165
+ w, h = (list(spec.get("size", [480, 360])) + [360])[:2]
166
+ root.geometry(f"{int(w)}x{int(h)}")
167
+ try:
168
+ ttk.Style().theme_use("clam" if sys.platform.startswith("linux") else ttk.Style().theme_use())
169
+ except Exception:
170
+ pass
171
+ body = ttk.Frame(root, padding=12)
172
+ body.pack(fill="both", expand=True)
173
+ self.status = tk.StringVar(value="")
174
+ ttk.Label(root, textvariable=self.status, anchor="w", relief="sunken", padding=(6, 2)).pack(fill="x", side="bottom")
175
+ frames = {None: body}
176
+ for wd in spec["widgets"]:
177
+ parent = frames.get(wd.get("parent"), body)
178
+ kind, ident, p = wd["kind"], wd["id"], self.S[wd["id"]]
179
+ if kind in ("app", "window", "dialog", "screen", "page") and wd.get("parent") is None:
180
+ frames[ident] = body
181
+ continue
182
+ if kind in CONTAINERS:
183
+ f = ttk.LabelFrame(parent, text=str(p.get("title", p.get("text", ident))), padding=8)
184
+ f.pack(fill="x", pady=4)
185
+ frames[ident] = f
186
+ self.widgets[ident] = f
187
+ continue
188
+ widget = self._make(parent, kind, ident, p)
189
+ if widget is not None:
190
+ widget.pack(fill="x", pady=3)
191
+ self.widgets[ident] = widget
192
+ if p.get("visible") is False:
193
+ widget.pack_forget()
194
+ for name in self.h.get("key", {}):
195
+ seq = {"space": "<space>", "enter": "<Return>", "return": "<Return>", "escape": "<Escape>", "esc": "<Escape>",
196
+ "up": "<Up>", "down": "<Down>", "left": "<Left>", "right": "<Right>", "tab": "<Tab>"}.get(name)
197
+ if not seq:
198
+ seq = f"<Key-{name}>" if len(name) == 1 else None
199
+ if seq:
200
+ root.bind(seq, lambda e, n=name: self.key(n))
201
+
202
+ def _make(self, parent, kind, ident, p):
203
+ text = str(p.get("text", p.get("label", ident.replace("_", " "))))
204
+ if kind in ("label", "title", "heading") and "text" not in p and "value" in p:
205
+ text = str(p["value"]) # a label that shows a value
206
+ if kind == "button":
207
+ v = tk.StringVar(value=text)
208
+ self.vars[(ident, "text")] = v
209
+ return ttk.Button(parent, textvariable=v, command=lambda: self.click(ident))
210
+ if kind in ("label", "title", "heading", "link"):
211
+ v = tk.StringVar(value=text)
212
+ self.vars[(ident, "text")] = v
213
+ font = ("TkDefaultFont", 14, "bold") if kind in ("title", "heading") else None
214
+ lab = ttk.Label(parent, textvariable=v, font=font) if font else ttk.Label(parent, textvariable=v)
215
+ if self.h.get("click", {}).get(ident):
216
+ lab.bind("<Button-1>", lambda e: self.click(ident))
217
+ return lab
218
+ if kind in ("input", "textbox", "entry", "field", "password", "search", "number"):
219
+ row = ttk.Frame(parent)
220
+ if p.get("label") or p.get("placeholder"):
221
+ ttk.Label(row, text=str(p.get("label", p.get("placeholder"))) + ":").pack(side="left", padx=(0, 6))
222
+ v = tk.StringVar(value=str(p.get("value", "")))
223
+ self.vars[(ident, "value")] = v
224
+ e = ttk.Entry(row, textvariable=v, show="*" if kind == "password" else "")
225
+ e.pack(side="left", fill="x", expand=True)
226
+ v.trace_add("write", lambda *a: self._from_widget(ident, "value", self._num(v.get(), p.get("value"))))
227
+ e.bind("<Return>", lambda ev: self.click(ident))
228
+ return row
229
+ if kind == "textarea":
230
+ t = tk.Text(parent, height=int(p.get("rows", 5)), wrap="word")
231
+ t.insert("1.0", str(p.get("value", "")))
232
+ t.bind("<KeyRelease>", lambda ev: self._from_widget(ident, "value", t.get("1.0", "end-1c")))
233
+ self.vars[(ident, "value")] = t
234
+ return t
235
+ if kind in ("checkbox", "switch"):
236
+ v = tk.BooleanVar(value=bool(p.get("checked", False)))
237
+ self.vars[(ident, "checked")] = v
238
+ tv = tk.StringVar(value=text)
239
+ self.vars[(ident, "text")] = tv
240
+ return ttk.Checkbutton(parent, textvariable=tv, variable=v,
241
+ command=lambda: (self._from_widget(ident, "checked", v.get()), self.click(ident)))
242
+ if kind in ("slider", "spinner"):
243
+ v = tk.DoubleVar(value=float(p.get("value", 0) or 0))
244
+ self.vars[(ident, "value")] = v
245
+ row = ttk.Frame(parent)
246
+ ttk.Label(row, text=text + ":").pack(side="left", padx=(0, 6))
247
+ s = ttk.Scale(row, from_=float(p.get("min", 0)), to=float(p.get("max", 100)), variable=v,
248
+ command=lambda val: self._from_widget(ident, "value", self._num(val, p.get("value"))))
249
+ s.pack(side="left", fill="x", expand=True)
250
+ return row
251
+ if kind == "progress":
252
+ v = tk.DoubleVar(value=float(p.get("value", 0) or 0))
253
+ self.vars[(ident, "value")] = v
254
+ return ttk.Progressbar(parent, maximum=float(p.get("max", 100)), variable=v)
255
+ if kind in ("dropdown", "select"):
256
+ items = [str(x) for x in (p.get("items") or [])]
257
+ v = tk.StringVar(value=str(p.get("value", items[0] if items else "")))
258
+ self.vars[(ident, "value")] = v
259
+ c = ttk.Combobox(parent, values=items, textvariable=v, state="readonly")
260
+ c.bind("<<ComboboxSelected>>", lambda ev: (self._from_widget(ident, "value", v.get()), self.click(ident)))
261
+ return c
262
+ if kind in ("list", "listbox", "table"):
263
+ lb = tk.Listbox(parent, height=int(p.get("rows", 6)))
264
+ for it in (p.get("items") or []):
265
+ lb.insert("end", str(it))
266
+ lb.bind("<<ListboxSelect>>", lambda ev: (self._from_widget(
267
+ ident, "value", lb.get(lb.curselection()[0]) if lb.curselection() else ""), self.click(ident)))
268
+ self.vars[(ident, "items")] = lb
269
+ return lb
270
+ if kind in ("image", "canvas", "chart"):
271
+ c = tk.Canvas(parent, height=int(p.get("height", 120)), background=str(p.get("color", "#f3f4f6")))
272
+ c.bind("<Button-1>", lambda ev: self.click(ident))
273
+ return c
274
+ if kind in ("timer", "object", "service", "store", "model", "counter", "data"):
275
+ return None # state only, no visible widget
276
+ v = tk.StringVar(value=text)
277
+ self.vars[(ident, "text")] = v
278
+ return ttk.Label(parent, textvariable=v)
279
+
280
+ @staticmethod
281
+ def _num(raw, like):
282
+ if isinstance(like, bool) or not isinstance(like, (int, float)):
283
+ return raw
284
+ try:
285
+ f = float(raw)
286
+ return int(f) if isinstance(like, int) and f.is_integer() else f
287
+ except (TypeError, ValueError):
288
+ return raw
289
+
290
+ def _from_widget(self, ident, prop, value):
291
+ old = self.S[ident].get(prop)
292
+ self.S[ident][prop] = value
293
+ if old != value:
294
+ self._fire_change(ident, prop)
295
+
296
+ def _pull(self, ident):
297
+ pass # widget -> state is pushed by traces; nothing to pull
298
+
299
+ def _push(self, ident, prop):
300
+ v = self.vars.get((ident, prop))
301
+ val = self.S[ident].get(prop)
302
+ if v is None and prop in ("text", "value", "label"):
303
+ v = self.vars.get((ident, "text")) or self.vars.get((ident, "value"))
304
+ if v is None:
305
+ if prop == "visible" and ident in self.widgets:
306
+ (self.widgets[ident].pack if val else self.widgets[ident].pack_forget)()
307
+ return
308
+ try:
309
+ if tk is not None and isinstance(v, tk.Text):
310
+ v.delete("1.0", "end")
311
+ v.insert("1.0", str(val))
312
+ elif tk is not None and isinstance(v, tk.Listbox):
313
+ v.delete(0, "end")
314
+ for it in (val or []):
315
+ v.insert("end", str(it))
316
+ elif str(v.get()) != str(val):
317
+ v.set(val)
318
+ except Exception:
319
+ pass
320
+
321
+ # ------------------------------------------------------------------ channels (HTTP hub)
322
+ def _post(self, ch, fields):
323
+ payload = {"channel": ch["id"], "from": ch["src"]}
324
+ payload.update({f: self.get(ch["src"], f, None) for f in fields})
325
+
326
+ def work():
327
+ try:
328
+ req = urllib.request.Request(ch["url"], json.dumps(payload).encode(), {"Content-Type": "application/json"})
329
+ urllib.request.urlopen(req, timeout=2).read()
330
+ except OSError:
331
+ pass
332
+ threading.Thread(target=work, daemon=True).start()
333
+
334
+ def _poll(self, ch):
335
+ seen = None
336
+ while True:
337
+ try:
338
+ msg = json.loads(urllib.request.urlopen(ch["url"], timeout=2).read() or b"{}")
339
+ if msg and msg.get("_t") != seen:
340
+ seen = msg.get("_t")
341
+ self._q.put((ch, msg))
342
+ except (OSError, ValueError):
343
+ pass
344
+ time.sleep(max(0.3, ch.get("interval_ms", 1000) / 2000.0))
345
+
346
+ def _deliver(self, ch, msg):
347
+ for k, v in msg.items():
348
+ if k in ("channel", "from", "_t") or v is None:
349
+ continue
350
+ if k in self.S.get(ch["dst"], {}) or self.kind.get(ch["dst"]):
351
+ self.set(ch["dst"], k, v)
352
+ self.message(ch["src"], msg)
353
+
354
+ # ------------------------------------------------------------------ main loop
355
+ def start(self, net=True):
356
+ self._run(self.h.get("start", []))
357
+ self._timers = [[ms, time.monotonic() + ms / 1000.0, owner, fn] for owner, ms, fn in self.h.get("timers", [])]
358
+ if net:
359
+ for ch in self.spec.get("channels", []):
360
+ if ch["dir"] == "in":
361
+ threading.Thread(target=self._poll, args=(ch,), daemon=True).start()
362
+ else:
363
+ self._timers.append([ch.get("interval_ms", 1000), time.monotonic(), ch["src"],
364
+ lambda app, c=ch: app._post(c, c["fields"])])
365
+
366
+ def step(self):
367
+ now = time.monotonic()
368
+ for t in self._timers:
369
+ if now >= t[1]:
370
+ t[1] = now + t[0] / 1000.0
371
+ self._run([(t[2], t[3])])
372
+ self.tick()
373
+ while not self._q.empty():
374
+ self._deliver(*self._q.get())
375
+
376
+ def mainloop(self):
377
+ self.start()
378
+ if self.root is None:
379
+ try:
380
+ while True:
381
+ self.step()
382
+ time.sleep(0.05)
383
+ except KeyboardInterrupt:
384
+ return
385
+
386
+ def loop():
387
+ self.step()
388
+ self.root.after(50, loop)
389
+ self.root.after(50, loop)
390
+ self.root.mainloop()
391
+
392
+ def selftest(self, seconds=0.6):
393
+ """Build everything, fire each event once, run briefly, print the final state."""
394
+ self.start(net=False)
395
+ for ident in list(self.h.get("click", {})):
396
+ self.click(ident)
397
+ for name in list(self.h.get("key", {})):
398
+ self.key(name)
399
+ for src in list(self.h.get("message", {})):
400
+ self.message(src, {})
401
+ end = time.monotonic() + seconds
402
+ for t in self._timers:
403
+ t[1] = 0 # every timer fires at least once
404
+ while time.monotonic() < end:
405
+ self.step()
406
+ if self.root is not None:
407
+ self.root.update()
408
+ time.sleep(0.02)
409
+ print("SELFTEST OK " + json.dumps({k: v for k, v in self.S.items()}, default=str), flush=True)
410
+ if self.root is not None:
411
+ self.root.destroy()
412
+
413
+
414
+ def main(spec, handlers, calls=None, argv=None):
415
+ ap = argparse.ArgumentParser(description=spec.get("title", "NLCL app"))
416
+ ap.add_argument("--selftest", action="store_true", help="build the UI, fire every event once, exit")
417
+ ap.add_argument("--headless", action="store_true", help="run the logic without a window")
418
+ a = ap.parse_args(argv)
419
+ app = App(spec, handlers, calls, headless=a.headless)
420
+ if a.selftest:
421
+ app.selftest()
422
+ else:
423
+ app.mainloop()
424
+ return app
nlcl/modules/_assets/cpp/nlcl_channels.cpp ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // nlcl_channels.cpp - channel factory. This is the only translation unit that
2
+ // sees the OS socket headers (see nlcl_channels.hpp). Generated by NLCL.
3
+ #include "nlcl_channels.hpp"
4
+
5
+ namespace nlcl {
6
+
7
+ std::unique_ptr<ChannelBase> makeChannel(const std::string& protocol, const std::string& id,
8
+ const std::string& src, const std::string& dst,
9
+ std::vector<std::string> fields, const Fields& config,
10
+ bool localSrc, bool localDst) {
11
+ std::unique_ptr<ChannelBase> ch;
12
+ if (localSrc && localDst)
13
+ ch.reset(new LocalChannel()); // both ends in this program: in-memory delivery
14
+ else if (protocol == "http" || protocol == "websocket")
15
+ ch.reset(new HubChannel());
16
+ else if (protocol == "udp")
17
+ ch.reset(new UdpChannel());
18
+ else if (protocol == "mqtt")
19
+ ch.reset(new MqttChannel());
20
+ else
21
+ ch.reset(new SerialChannel()); // serial/uart and electrical buses: JSON lines on stdio
22
+ ch->id = id;
23
+ ch->protocol = protocol;
24
+ ch->src = src;
25
+ ch->dst = dst;
26
+ ch->fields = std::move(fields);
27
+ ch->config = config;
28
+ ch->localSrc = localSrc;
29
+ ch->localDst = localDst;
30
+ int ms = cfgInt(config, "interval_ms", 1000);
31
+ ch->interval = (ms > 0 ? ms : 1000) / 1000.0;
32
+ return ch;
33
+ }
34
+
35
+ } // namespace nlcl
nlcl/modules/_assets/cpp/nlcl_channels.hpp ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // nlcl_channels.hpp - NLCL channel transports (C++17, no third-party deps).
2
+ //
3
+ // local : both ends in this process, delivered in memory
4
+ // http : POST/GET flat JSON on the NLCL hub (python module) via a tiny
5
+ // raw-socket HTTP/1.1 client (also used for "websocket")
6
+ // udp : one JSON datagram per message (Winsock2 / BSD sockets)
7
+ // serial : newline-terminated JSON on stdout; incoming lines on stdin
8
+ // (pipe it through a serial bridge, see README) (also spi/i2c/gpio/wire)
9
+ // mqtt : minimal MQTT 3.1.1 client, QoS 0 publish/subscribe
10
+ //
11
+ // Every transport falls back gracefully (prints the payload) when the network
12
+ // is unavailable; run with --simulate to invent incoming data instead.
13
+ // Only nlcl_channels.cpp includes this file, so OS headers (windows.h macros)
14
+ // never reach entity code. Generated by NLCL - edit freely.
15
+ #pragma once
16
+
17
+ #include "nlcl_core.hpp"
18
+
19
+ #ifdef _WIN32
20
+ # ifndef WIN32_LEAN_AND_MEAN
21
+ # define WIN32_LEAN_AND_MEAN
22
+ # endif
23
+ # ifndef NOMINMAX
24
+ # define NOMINMAX
25
+ # endif
26
+ # ifndef _WIN32_WINNT
27
+ # define _WIN32_WINNT 0x0601
28
+ # endif
29
+ # include <winsock2.h>
30
+ # include <ws2tcpip.h>
31
+ # ifdef _MSC_VER
32
+ # pragma comment(lib, "ws2_32.lib")
33
+ # endif
34
+ #else
35
+ # include <arpa/inet.h>
36
+ # include <cerrno>
37
+ # include <fcntl.h>
38
+ # include <netdb.h>
39
+ # include <netinet/in.h>
40
+ # include <sys/select.h>
41
+ # include <sys/socket.h>
42
+ # include <sys/time.h>
43
+ # include <unistd.h>
44
+ #endif
45
+
46
+ namespace nlcl {
47
+ namespace net {
48
+
49
+ #ifdef _WIN32
50
+ using socket_t = SOCKET;
51
+ const socket_t kInvalid = INVALID_SOCKET;
52
+ inline void closeSocket(socket_t s) { closesocket(s); }
53
+ const int kSendFlags = 0;
54
+ #else
55
+ using socket_t = int;
56
+ const socket_t kInvalid = -1;
57
+ inline void closeSocket(socket_t s) { ::close(s); }
58
+ # ifdef MSG_NOSIGNAL
59
+ const int kSendFlags = MSG_NOSIGNAL;
60
+ # else
61
+ const int kSendFlags = 0;
62
+ # endif
63
+ #endif
64
+
65
+ // One-time socket library initialisation.
66
+ inline void init() {
67
+ #ifdef _WIN32
68
+ struct WsaInit {
69
+ bool ok = false;
70
+ WsaInit() {
71
+ WSADATA d;
72
+ ok = WSAStartup(MAKEWORD(2, 2), &d) == 0;
73
+ }
74
+ ~WsaInit() {
75
+ if (ok) WSACleanup();
76
+ }
77
+ };
78
+ static WsaInit once;
79
+ #else
80
+ static bool once = [] {
81
+ std::signal(SIGPIPE, SIG_IGN); // a closed peer must not kill the process
82
+ return true;
83
+ }();
84
+ (void)once;
85
+ #endif
86
+ }
87
+
88
+ inline void setNonBlocking(socket_t s, bool on) {
89
+ #ifdef _WIN32
90
+ u_long mode = on ? 1 : 0;
91
+ ioctlsocket(s, FIONBIO, &mode);
92
+ #else
93
+ int fl = fcntl(s, F_GETFL, 0);
94
+ if (fl < 0) fl = 0;
95
+ fcntl(s, F_SETFL, on ? (fl | O_NONBLOCK) : (fl & ~O_NONBLOCK));
96
+ #endif
97
+ }
98
+
99
+ inline void setTimeouts(socket_t s, int ms) {
100
+ #ifdef _WIN32
101
+ DWORD t = static_cast<DWORD>(ms);
102
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast<const char*>(&t), sizeof(t));
103
+ setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast<const char*>(&t), sizeof(t));
104
+ #else
105
+ timeval tv;
106
+ tv.tv_sec = ms / 1000;
107
+ tv.tv_usec = (ms % 1000) * 1000;
108
+ setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
109
+ setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
110
+ #endif
111
+ }
112
+
113
+ // IPv4 address for host ("localhost" is mapped to 127.0.0.1 to avoid IPv6 delays).
114
+ inline bool resolve(const std::string& host, int port, sockaddr_in& out) {
115
+ init();
116
+ std::string h = (host.empty() || host == "localhost") ? "127.0.0.1" : host;
117
+ addrinfo hints{};
118
+ hints.ai_family = AF_INET;
119
+ addrinfo* res = nullptr;
120
+ if (getaddrinfo(h.c_str(), nullptr, &hints, &res) != 0 || !res) return false;
121
+ out = *reinterpret_cast<sockaddr_in*>(res->ai_addr);
122
+ out.sin_port = htons(static_cast<unsigned short>(port));
123
+ freeaddrinfo(res);
124
+ return true;
125
+ }
126
+
127
+ // TCP connect with a timeout (non-blocking connect + select).
128
+ inline socket_t tcpConnect(const std::string& host, int port, int timeoutMs) {
129
+ sockaddr_in addr{};
130
+ if (!resolve(host, port, addr)) return kInvalid;
131
+ socket_t s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
132
+ if (s == kInvalid) return kInvalid;
133
+ setNonBlocking(s, true);
134
+ int rc = connect(s, reinterpret_cast<sockaddr*>(&addr), static_cast<int>(sizeof(addr)));
135
+ if (rc != 0) {
136
+ fd_set wf, ef;
137
+ FD_ZERO(&wf);
138
+ FD_ZERO(&ef);
139
+ FD_SET(s, &wf);
140
+ FD_SET(s, &ef);
141
+ timeval tv;
142
+ tv.tv_sec = timeoutMs / 1000;
143
+ tv.tv_usec = (timeoutMs % 1000) * 1000;
144
+ int n = select(static_cast<int>(s) + 1, nullptr, &wf, &ef, &tv);
145
+ int err = 0;
146
+ socklen_t len = static_cast<socklen_t>(sizeof(err));
147
+ if (n <= 0 || FD_ISSET(s, &ef) ||
148
+ getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast<char*>(&err), &len) != 0 || err != 0) {
149
+ closeSocket(s);
150
+ return kInvalid;
151
+ }
152
+ }
153
+ setNonBlocking(s, false);
154
+ setTimeouts(s, timeoutMs);
155
+ return s;
156
+ }
157
+
158
+ inline bool sendAll(socket_t s, const std::string& data) {
159
+ size_t off = 0;
160
+ while (off < data.size()) {
161
+ int n = static_cast<int>(send(s, data.data() + off, static_cast<int>(data.size() - off), kSendFlags));
162
+ if (n <= 0) return false;
163
+ off += static_cast<size_t>(n);
164
+ }
165
+ return true;
166
+ }
167
+
168
+ // Minimal HTTP/1.1 request (Connection: close). Returns status code or -1.
169
+ inline int httpRequest(const std::string& host, int port, const std::string& method, const std::string& path,
170
+ const std::string& body, std::string& out, int timeoutMs = 400) {
171
+ socket_t s = tcpConnect(host, port, timeoutMs);
172
+ if (s == kInvalid) return -1;
173
+ std::string req = method + " " + path + " HTTP/1.1\r\nHost: " + host + ":" + std::to_string(port) +
174
+ "\r\nConnection: close\r\nAccept: application/json\r\n";
175
+ if (method == "POST")
176
+ req += "Content-Type: application/json\r\nContent-Length: " + std::to_string(body.size()) + "\r\n";
177
+ req += "\r\n" + body;
178
+ if (!sendAll(s, req)) {
179
+ closeSocket(s);
180
+ return -1;
181
+ }
182
+ std::string resp;
183
+ char buf[2048];
184
+ while (resp.size() < (1u << 20)) {
185
+ int n = static_cast<int>(recv(s, buf, static_cast<int>(sizeof(buf)), 0));
186
+ if (n <= 0) break;
187
+ resp.append(buf, static_cast<size_t>(n));
188
+ // stop early once the announced body is complete
189
+ size_t he = resp.find("\r\n\r\n");
190
+ if (he != std::string::npos) {
191
+ size_t cl = resp.find("Content-Length:");
192
+ if (cl == std::string::npos) cl = resp.find("content-length:");
193
+ if (cl != std::string::npos && cl < he) {
194
+ size_t want = static_cast<size_t>(std::strtoul(resp.c_str() + cl + 15, nullptr, 10));
195
+ if (resp.size() >= he + 4 + want) break;
196
+ }
197
+ }
198
+ }
199
+ closeSocket(s);
200
+ size_t he = resp.find("\r\n\r\n");
201
+ if (resp.compare(0, 5, "HTTP/") != 0 || he == std::string::npos) return -1;
202
+ size_t sp = resp.find(' ');
203
+ int status = std::atoi(resp.c_str() + sp + 1);
204
+ out = resp.substr(he + 4);
205
+ return status;
206
+ }
207
+
208
+ // "http://localhost:8765/x" -> host, port
209
+ inline void parseUrl(const std::string& url, std::string& host, int& port) {
210
+ std::string u = url;
211
+ size_t p = u.find("://");
212
+ if (p != std::string::npos) u = u.substr(p + 3);
213
+ size_t slash = u.find('/');
214
+ if (slash != std::string::npos) u = u.substr(0, slash);
215
+ size_t colon = u.rfind(':');
216
+ if (colon != std::string::npos) {
217
+ host = u.substr(0, colon);
218
+ port = std::atoi(u.c_str() + colon + 1);
219
+ } else {
220
+ host = u;
221
+ }
222
+ if (host.empty()) host = "127.0.0.1";
223
+ if (port <= 0) port = 80;
224
+ }
225
+
226
+ } // namespace net
227
+
228
+ inline std::string cfgStr(const Fields& c, const std::string& k, const std::string& def) {
229
+ auto it = c.find(k);
230
+ return it != c.end() && !it->second.isNull() ? it->second.asStr() : def;
231
+ }
232
+ inline int cfgInt(const Fields& c, const std::string& k, int def) {
233
+ auto it = c.find(k);
234
+ return it != c.end() && !it->second.isNull() ? static_cast<int>(it->second.asNum()) : def;
235
+ }
236
+
237
+ // ------------------------------------------------------------------ local
238
+ class LocalChannel : public ChannelBase {
239
+ public:
240
+ void publish(const Fields& p) override { receive(p); } // World::deliver logs it
241
+ };
242
+
243
+ // ------------------------------------------------------------------ http hub
244
+ class HubChannel : public ChannelBase {
245
+ public:
246
+ std::string host = "127.0.0.1";
247
+ int port = 8765;
248
+ std::string path;
249
+
250
+ void start() override {
251
+ net::parseUrl(cfgStr(config, "hub_url", "http://localhost:8765"), host, port);
252
+ path = cfgStr(config, "path", "/channel/" + id);
253
+ if (world->verbose)
254
+ std::cout << "[" << id << "] http hub " << host << ":" << port << path << std::endl;
255
+ }
256
+ void publish(const Fields& p) override {
257
+ std::string body = envelope(p), resp;
258
+ if (world->now < retryAt_) { // hub was down a moment ago: do not stall the loop
259
+ if (world->verbose) std::cout << "[" << id << "] (hub offline) " << body << std::endl;
260
+ return;
261
+ }
262
+ int st = net::httpRequest(host, port, "POST", path, body, resp);
263
+ if (st == 200) {
264
+ if (world->verbose) std::cout << "[" << id << "] -> hub " << body << std::endl;
265
+ } else {
266
+ offline();
267
+ if (world->verbose) std::cout << "[" << id << "] hub unreachable; payload " << body << std::endl;
268
+ }
269
+ }
270
+ void poll() override {
271
+ if (world->now < nextPoll_ || world->now < retryAt_) return;
272
+ nextPoll_ = world->now + std::max(0.2, interval / 2.0);
273
+ std::string resp;
274
+ if (net::httpRequest(host, port, "GET", path, "", resp) != 200) {
275
+ offline();
276
+ return;
277
+ }
278
+ Fields msg;
279
+ if (!decodeJson(resp, msg) || msg.empty()) return;
280
+ auto t = msg.find("_t");
281
+ double stamp = t != msg.end() ? t->second.asNum() : -1.0;
282
+ if (t == msg.end() || stamp == seen_) return; // nothing new
283
+ seen_ = stamp;
284
+ receive(cleanPayload(msg));
285
+ }
286
+
287
+ private:
288
+ double nextPoll_ = 0.0, retryAt_ = 0.0, seen_ = -1.0;
289
+ bool warned_ = false;
290
+ void offline() {
291
+ retryAt_ = world->now + 3.0;
292
+ if (!warned_) {
293
+ warned_ = true;
294
+ std::cerr << "[" << id << "] NLCL hub not reachable at " << host << ":" << port
295
+ << " - start it with: python ../python/main.py (or run this program with --simulate)"
296
+ << std::endl;
297
+ }
298
+ }
299
+ };
300
+
301
+ // ------------------------------------------------------------------ udp
302
+ class UdpChannel : public ChannelBase {
303
+ public:
304
+ std::string host = "127.0.0.1";
305
+ int port = 9876;
306
+
307
+ void start() override {
308
+ host = cfgStr(config, "host", "127.0.0.1");
309
+ port = cfgInt(config, "port", 9876);
310
+ if (world->simulate) return;
311
+ net::init();
312
+ sock_ = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
313
+ if (sock_ == net::kInvalid) {
314
+ std::cerr << "[" << id << "] cannot create udp socket" << std::endl;
315
+ return;
316
+ }
317
+ if (!localSrc) {
318
+ sockaddr_in a{};
319
+ a.sin_family = AF_INET;
320
+ a.sin_port = htons(static_cast<unsigned short>(port));
321
+ a.sin_addr.s_addr = htonl(INADDR_ANY);
322
+ if (bind(sock_, reinterpret_cast<sockaddr*>(&a), static_cast<int>(sizeof(a))) != 0) {
323
+ std::cerr << "[" << id << "] udp port " << port << " busy" << std::endl;
324
+ net::closeSocket(sock_);
325
+ sock_ = net::kInvalid;
326
+ return;
327
+ }
328
+ net::setNonBlocking(sock_, true);
329
+ } else if (!net::resolve(host, port, to_)) {
330
+ std::cerr << "[" << id << "] cannot resolve " << host << std::endl;
331
+ }
332
+ if (world->verbose) std::cout << "[" << id << "] udp " << host << ":" << port << std::endl;
333
+ }
334
+ void poll() override {
335
+ if (sock_ == net::kInvalid) return;
336
+ char buf[4096];
337
+ for (int i = 0; i < 64; ++i) { // drain what is queued, never block
338
+ int n = static_cast<int>(recvfrom(sock_, buf, static_cast<int>(sizeof(buf)), 0, nullptr, nullptr));
339
+ if (n <= 0) break;
340
+ Fields msg;
341
+ if (!decodeJson(std::string(buf, static_cast<size_t>(n)), msg)) continue;
342
+ auto c = msg.find("channel");
343
+ if (c == msg.end() || c->second.asStr() == id) receive(cleanPayload(msg));
344
+ }
345
+ }
346
+ void publish(const Fields& p) override {
347
+ std::string line = envelope(p) + "\n";
348
+ if (sock_ != net::kInvalid && to_.sin_family == AF_INET) {
349
+ sendto(sock_, line.c_str(), static_cast<int>(line.size()), 0, reinterpret_cast<sockaddr*>(&to_),
350
+ static_cast<int>(sizeof(to_)));
351
+ }
352
+ if (world->verbose) std::cout << "[" << id << "] (udp " << host << ":" << port << ") " << envelope(p) << std::endl;
353
+ }
354
+ void stop() override {
355
+ if (sock_ != net::kInvalid) net::closeSocket(sock_);
356
+ sock_ = net::kInvalid;
357
+ }
358
+
359
+ private:
360
+ net::socket_t sock_ = net::kInvalid;
361
+ sockaddr_in to_{};
362
+ };
363
+
364
+ // ------------------------------------------------------------------ serial-style JSON lines
365
+ class SerialChannel : public ChannelBase {
366
+ public:
367
+ bool streamInput() const override { return true; }
368
+ void start() override {
369
+ if (world->verbose && !world->simulate && !localSrc)
370
+ std::cout << "[" << id << "] reading JSON lines from stdin (" << protocol << ")" << std::endl;
371
+ }
372
+ void publish(const Fields& p) override {
373
+ std::cout << envelope(p) << std::endl; // the data line itself (always printed)
374
+ }
375
+ };
376
+
377
+ // ------------------------------------------------------------------ mqtt (3.1.1, QoS 0)
378
+ class MqttChannel : public ChannelBase {
379
+ public:
380
+ std::string broker = "broker.hivemq.com";
381
+ int brokerPort = 1883;
382
+ std::string topic;
383
+
384
+ void start() override {
385
+ broker = cfgStr(config, "broker", broker);
386
+ brokerPort = cfgInt(config, "broker_port", brokerPort);
387
+ topic = cfgStr(config, "topic", "nlcl/" + id);
388
+ if (world->simulate) return;
389
+ sock_ = net::tcpConnect(broker, brokerPort, 3000);
390
+ if (sock_ == net::kInvalid) {
391
+ std::cerr << "[" << id << "] mqtt broker " << broker << " unreachable - printing messages instead" << std::endl;
392
+ return;
393
+ }
394
+ std::string body;
395
+ putStr(body, "MQTT");
396
+ body += static_cast<char>(4); // protocol level 3.1.1
397
+ body += static_cast<char>(0x02); // clean session
398
+ body += static_cast<char>(0);
399
+ body += static_cast<char>(60); // keep-alive 60 s
400
+ putStr(body, "nlcl-" + id + "-" + std::to_string(world->rng() % 1000000u));
401
+ unsigned char ack[4] = {0, 0, 0, 0};
402
+ size_t got = 0;
403
+ if (net::sendAll(sock_, packet(0x10, body))) {
404
+ while (got < 4) {
405
+ int n = static_cast<int>(recv(sock_, reinterpret_cast<char*>(ack) + got, static_cast<int>(4 - got), 0));
406
+ if (n <= 0) break;
407
+ got += static_cast<size_t>(n);
408
+ }
409
+ }
410
+ if (got < 4 || ack[0] != 0x20 || ack[3] != 0) {
411
+ std::cerr << "[" << id << "] mqtt connect refused - printing messages instead" << std::endl;
412
+ close();
413
+ return;
414
+ }
415
+ if (!localSrc) { // SUBSCRIBE packet id 1, QoS 0
416
+ std::string sb;
417
+ sb += static_cast<char>(0);
418
+ sb += static_cast<char>(1);
419
+ putStr(sb, topic);
420
+ sb += static_cast<char>(0);
421
+ net::sendAll(sock_, packet(0x82, sb));
422
+ }
423
+ net::setNonBlocking(sock_, true);
424
+ pingAt_ = world->now + 30.0;
425
+ if (world->verbose) std::cout << "[" << id << "] mqtt " << broker << ":" << brokerPort << " topic " << topic << std::endl;
426
+ }
427
+ void publish(const Fields& p) override {
428
+ std::string msg = envelope(p);
429
+ if (sock_ != net::kInvalid) {
430
+ std::string body;
431
+ putStr(body, topic);
432
+ body += msg;
433
+ if (!net::sendAll(sock_, packet(0x30, body))) close();
434
+ pingAt_ = world->now + 30.0;
435
+ }
436
+ if (world->verbose) std::cout << "[" << id << "] (mqtt " << topic << ") " << msg << std::endl;
437
+ }
438
+ void poll() override {
439
+ if (sock_ == net::kInvalid) return;
440
+ char buf[2048];
441
+ for (int i = 0; i < 16; ++i) {
442
+ int n = static_cast<int>(recv(sock_, buf, static_cast<int>(sizeof(buf)), 0));
443
+ if (n == 0) { // broker closed the connection
444
+ close();
445
+ return;
446
+ }
447
+ if (n < 0) break; // would block: nothing more right now
448
+ rx_.append(buf, static_cast<size_t>(n));
449
+ }
450
+ parse();
451
+ if (world->now >= pingAt_ && sock_ != net::kInvalid) {
452
+ pingAt_ = world->now + 30.0;
453
+ net::sendAll(sock_, std::string("\xC0\x00", 2));
454
+ }
455
+ }
456
+ void stop() override {
457
+ if (sock_ != net::kInvalid) net::sendAll(sock_, std::string("\xE0\x00", 2)); // DISCONNECT
458
+ close();
459
+ }
460
+
461
+ private:
462
+ net::socket_t sock_ = net::kInvalid;
463
+ std::string rx_;
464
+ double pingAt_ = 0.0;
465
+
466
+ void close() {
467
+ if (sock_ != net::kInvalid) net::closeSocket(sock_);
468
+ sock_ = net::kInvalid;
469
+ }
470
+ static void putStr(std::string& b, const std::string& s) {
471
+ b += static_cast<char>((s.size() >> 8) & 0xFF);
472
+ b += static_cast<char>(s.size() & 0xFF);
473
+ b += s;
474
+ }
475
+ static std::string packet(unsigned char type, const std::string& body) {
476
+ std::string p(1, static_cast<char>(type));
477
+ size_t len = body.size();
478
+ do {
479
+ unsigned char d = static_cast<unsigned char>(len % 128);
480
+ len /= 128;
481
+ if (len) d |= 0x80;
482
+ p += static_cast<char>(d);
483
+ } while (len);
484
+ return p + body;
485
+ }
486
+ // split rx_ into complete MQTT packets; deliver PUBLISH payloads
487
+ void parse() {
488
+ while (rx_.size() >= 2) {
489
+ size_t len = 0, mult = 1, pos = 1;
490
+ bool complete = false;
491
+ while (pos < rx_.size() && pos <= 4) {
492
+ unsigned char d = static_cast<unsigned char>(rx_[pos++]);
493
+ len += (d & 0x7F) * mult;
494
+ mult *= 128;
495
+ if (!(d & 0x80)) {
496
+ complete = true;
497
+ break;
498
+ }
499
+ }
500
+ if (!complete || rx_.size() < pos + len) return; // wait for more bytes
501
+ unsigned char type = static_cast<unsigned char>(rx_[0]);
502
+ std::string body = rx_.substr(pos, len);
503
+ rx_.erase(0, pos + len);
504
+ if ((type >> 4) != 3 || body.size() < 2) continue; // only PUBLISH carries data
505
+ size_t tlen = (static_cast<unsigned char>(body[0]) << 8) | static_cast<unsigned char>(body[1]);
506
+ size_t off = 2 + tlen + (((type >> 1) & 3) ? 2 : 0);
507
+ if (off > body.size()) continue;
508
+ Fields msg;
509
+ if (decodeJson(body.substr(off), msg)) receive(cleanPayload(msg));
510
+ }
511
+ }
512
+ };
513
+
514
+ } // namespace nlcl
nlcl/modules/_assets/cpp/nlcl_core.hpp ADDED
@@ -0,0 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // nlcl_core.hpp - NLCL C++ runtime core (header-only, C++17, standard library only).
2
+ //
3
+ // Provides: nlcl::Value (dynamic value used on channels / reflection), tiny flat
4
+ // JSON encode/decode, the Entity base class (props reflection, timers, log,
5
+ // destroy, move, send) and the World (fixed-step loop, timers, change
6
+ // detection, collisions, channel routing). Transports live in
7
+ // src/nlcl_channels.hpp so that no OS socket header leaks into entity code.
8
+ // Generated by NLCL - edit freely.
9
+ #pragma once
10
+
11
+ // Keep <windows.h> (if any standard header pulls it in) from defining min/max
12
+ // macros or the old winsock API.
13
+ #if defined(_WIN32) && !defined(WIN32_LEAN_AND_MEAN)
14
+ # define WIN32_LEAN_AND_MEAN
15
+ #endif
16
+ #if defined(_WIN32) && !defined(NOMINMAX)
17
+ # define NOMINMAX
18
+ #endif
19
+
20
+ #include <algorithm>
21
+ #include <chrono>
22
+ #include <cmath>
23
+ #include <csignal>
24
+ #include <cstdio>
25
+ #include <cstdlib>
26
+ #include <cctype>
27
+ #include <deque>
28
+ #include <functional>
29
+ #include <iostream>
30
+ #include <map>
31
+ #include <memory>
32
+ #include <mutex>
33
+ #include <random>
34
+ #include <set>
35
+ #include <string>
36
+ #include <thread>
37
+ #include <type_traits>
38
+ #include <utility>
39
+ #include <vector>
40
+
41
+ namespace nlcl {
42
+
43
+ // Set by the SIGINT handler in main.cpp: the world loop stops cleanly.
44
+ inline volatile std::sig_atomic_t g_stop = 0;
45
+
46
+ // ------------------------------------------------------------------ JSON text
47
+ inline std::string jsonEscape(const std::string& s) {
48
+ std::string o = "\"";
49
+ for (char ch : s) {
50
+ unsigned char c = static_cast<unsigned char>(ch);
51
+ switch (c) {
52
+ case '"': o += "\\\""; break;
53
+ case '\\': o += "\\\\"; break;
54
+ case '\n': o += "\\n"; break;
55
+ case '\r': o += "\\r"; break;
56
+ case '\t': o += "\\t"; break;
57
+ default:
58
+ if (c < 0x20) {
59
+ char b[8];
60
+ std::snprintf(b, sizeof b, "\\u%04x", static_cast<unsigned>(c));
61
+ o += b;
62
+ } else {
63
+ o += ch;
64
+ }
65
+ }
66
+ }
67
+ o += "\"";
68
+ return o;
69
+ }
70
+
71
+ inline std::string formatNum(double d) {
72
+ if (!std::isfinite(d)) return "0";
73
+ char b[40];
74
+ if (d == std::floor(d) && std::fabs(d) < 1e15) {
75
+ std::snprintf(b, sizeof b, "%.0f", d);
76
+ } else {
77
+ std::snprintf(b, sizeof b, "%.10g", d);
78
+ }
79
+ return b;
80
+ }
81
+
82
+ // ------------------------------------------------------------------ Value
83
+ // A small dynamic value: null, bool, number, string or list of numbers.
84
+ struct Value {
85
+ enum Kind { Null, Bool, Num, Str, List };
86
+ Kind kind = Null;
87
+ double num = 0.0;
88
+ std::string str;
89
+ std::vector<double> list;
90
+
91
+ Value() = default;
92
+ Value(bool b) : kind(Bool), num(b ? 1.0 : 0.0) {}
93
+ template <class T, typename std::enable_if<std::is_arithmetic<T>::value &&
94
+ !std::is_same<T, bool>::value, int>::type = 0>
95
+ Value(T v) : kind(Num), num(static_cast<double>(v)) {}
96
+ Value(const char* s) : kind(Str), str(s ? s : "") {}
97
+ Value(std::string s) : kind(Str), str(std::move(s)) {}
98
+ Value(std::vector<double> l) : kind(List), list(std::move(l)) {}
99
+
100
+ bool isNull() const { return kind == Null; }
101
+
102
+ double asNum() const {
103
+ switch (kind) {
104
+ case Bool:
105
+ case Num: return num;
106
+ case Str: {
107
+ const char* b = str.c_str();
108
+ char* end = nullptr;
109
+ double d = std::strtod(b, &end);
110
+ return (end && end != b) ? d : 0.0;
111
+ }
112
+ case List: return list.empty() ? 0.0 : list[0];
113
+ default: return 0.0;
114
+ }
115
+ }
116
+ bool asBool() const {
117
+ switch (kind) {
118
+ case Bool:
119
+ case Num: return num != 0.0;
120
+ case Str: return !str.empty() && str != "false" && str != "0" && str != "off";
121
+ case List: return !list.empty();
122
+ default: return false;
123
+ }
124
+ }
125
+ std::string asStr() const {
126
+ switch (kind) {
127
+ case Bool: return num != 0.0 ? "true" : "false";
128
+ case Num: return formatNum(num);
129
+ case Str: return str;
130
+ case List: {
131
+ std::string s = "[";
132
+ for (size_t i = 0; i < list.size(); ++i) {
133
+ if (i) s += ", ";
134
+ s += formatNum(list[i]);
135
+ }
136
+ return s + "]";
137
+ }
138
+ default: return "null";
139
+ }
140
+ }
141
+ std::vector<double> asList() const {
142
+ if (kind == List) return list;
143
+ if (kind == Null) return {};
144
+ return {asNum()};
145
+ }
146
+ std::string toJson() const {
147
+ switch (kind) {
148
+ case Str: return jsonEscape(str);
149
+ case List: {
150
+ std::string s = "[";
151
+ for (size_t i = 0; i < list.size(); ++i) {
152
+ if (i) s += ",";
153
+ s += formatNum(list[i]);
154
+ }
155
+ return s + "]";
156
+ }
157
+ case Null: return "null";
158
+ default: return asStr();
159
+ }
160
+ }
161
+ bool operator==(const Value& o) const {
162
+ return kind == o.kind && num == o.num && str == o.str && list == o.list;
163
+ }
164
+ bool operator!=(const Value& o) const { return !(*this == o); }
165
+ };
166
+
167
+ using Fields = std::map<std::string, Value>;
168
+
169
+ // typed assignment from a Value (used by generated set() and actions)
170
+ inline void assign(int& f, const Value& v) { f = static_cast<int>(std::lround(v.asNum())); }
171
+ inline void assign(double& f, const Value& v) { f = v.asNum(); }
172
+ inline void assign(bool& f, const Value& v) { f = v.asBool(); }
173
+ inline void assign(std::string& f, const Value& v) { f = v.asStr(); }
174
+ inline void assign(std::vector<double>& f, const Value& v) { f = v.asList(); }
175
+ // add a scalar to every component of a vector property
176
+ inline void addTo(std::vector<double>& f, double d) { for (auto& x : f) x += d; }
177
+ // safe component access: position.x -> at(position, 0)
178
+ inline double at(const std::vector<double>& v, size_t i) { return i < v.size() ? v[i] : 0.0; }
179
+
180
+ // Expression helpers for mixed-type operands in generated behaviour code.
181
+ // truthy: Python-like truth value; num: numeric value; cat: string concatenation.
182
+ inline bool truthy(const Value& v) { return v.kind == Value::Str ? !v.str.empty() : v.asBool(); }
183
+ inline bool truthy(const std::string& s) { return !s.empty(); }
184
+ inline bool truthy(const char* s) { return s && *s; }
185
+ inline bool truthy(const std::vector<double>& l) { return !l.empty(); }
186
+ template <class T, typename std::enable_if<std::is_arithmetic<T>::value, int>::type = 0>
187
+ inline bool truthy(T v) { return v != 0; }
188
+ template <class T>
189
+ inline double num(const T& v) { return Value(v).asNum(); }
190
+ template <class A, class B>
191
+ inline std::string cat(const A& a, const B& b) { return Value(a).asStr() + Value(b).asStr(); }
192
+
193
+ inline std::string encodeFields(const Fields& f) {
194
+ std::string s = "{";
195
+ bool first = true;
196
+ for (const auto& kv : f) {
197
+ if (!first) s += ",";
198
+ first = false;
199
+ s += jsonEscape(kv.first) + ":" + kv.second.toJson();
200
+ }
201
+ return s + "}";
202
+ }
203
+
204
+ // Flat channel message: {"channel": id, "from": src, field: value, ...}
205
+ inline std::string encodeMessage(const std::string& channel, const std::string& from, const Fields& f) {
206
+ std::string s = "{\"channel\":" + jsonEscape(channel) + ",\"from\":" + jsonEscape(from);
207
+ for (const auto& kv : f) {
208
+ if (kv.first == "channel" || kv.first == "from") continue;
209
+ s += "," + jsonEscape(kv.first) + ":" + kv.second.toJson();
210
+ }
211
+ return s + "}";
212
+ }
213
+
214
+ // Minimal reader for flat JSON objects (nested objects are skipped).
215
+ struct JsonReader {
216
+ const std::string& s;
217
+ size_t i = 0;
218
+ explicit JsonReader(const std::string& src) : s(src) {}
219
+
220
+ void ws() {
221
+ while (i < s.size() && std::isspace(static_cast<unsigned char>(s[i]))) ++i;
222
+ }
223
+ bool eat(char c) {
224
+ ws();
225
+ if (i < s.size() && s[i] == c) {
226
+ ++i;
227
+ return true;
228
+ }
229
+ return false;
230
+ }
231
+ bool str(std::string& out) {
232
+ ws();
233
+ if (i >= s.size() || s[i] != '"') return false;
234
+ ++i;
235
+ out.clear();
236
+ while (i < s.size()) {
237
+ char c = s[i++];
238
+ if (c == '"') return true;
239
+ if (c != '\\' || i >= s.size()) {
240
+ out += c;
241
+ continue;
242
+ }
243
+ char e = s[i++];
244
+ switch (e) {
245
+ case 'n': out += '\n'; break;
246
+ case 't': out += '\t'; break;
247
+ case 'r': out += '\r'; break;
248
+ case 'b': out += '\b'; break;
249
+ case 'f': out += '\f'; break;
250
+ case 'u': {
251
+ if (i + 4 > s.size()) return false;
252
+ unsigned cp = static_cast<unsigned>(std::strtoul(s.substr(i, 4).c_str(), nullptr, 16));
253
+ i += 4;
254
+ // UTF-16 surrogate pair (Python's json.dumps escapes emoji this way)
255
+ if (cp >= 0xD800 && cp < 0xDC00 && i + 6 <= s.size() && s[i] == '\\' && s[i + 1] == 'u') {
256
+ unsigned lo = static_cast<unsigned>(std::strtoul(s.substr(i + 2, 4).c_str(), nullptr, 16));
257
+ if (lo >= 0xDC00 && lo < 0xE000) {
258
+ cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
259
+ i += 6;
260
+ }
261
+ }
262
+ // encode the code point as UTF-8
263
+ if (cp < 0x80) {
264
+ out += static_cast<char>(cp);
265
+ } else if (cp < 0x800) {
266
+ out += static_cast<char>(0xC0 | (cp >> 6));
267
+ out += static_cast<char>(0x80 | (cp & 0x3F));
268
+ } else if (cp >= 0x10000) {
269
+ out += static_cast<char>(0xF0 | (cp >> 18));
270
+ out += static_cast<char>(0x80 | ((cp >> 12) & 0x3F));
271
+ out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
272
+ out += static_cast<char>(0x80 | (cp & 0x3F));
273
+ } else {
274
+ out += static_cast<char>(0xE0 | (cp >> 12));
275
+ out += static_cast<char>(0x80 | ((cp >> 6) & 0x3F));
276
+ out += static_cast<char>(0x80 | (cp & 0x3F));
277
+ }
278
+ break;
279
+ }
280
+ default: out += e; // \" \\ \/
281
+ }
282
+ }
283
+ return false;
284
+ }
285
+ bool value(Value& v) {
286
+ ws();
287
+ if (i >= s.size()) return false;
288
+ char c = s[i];
289
+ if (c == '"') {
290
+ std::string t;
291
+ if (!str(t)) return false;
292
+ v = Value(t);
293
+ return true;
294
+ }
295
+ if (c == '[') { // arrays become lists of numbers
296
+ ++i;
297
+ std::vector<double> l;
298
+ if (eat(']')) {
299
+ v = Value(l);
300
+ return true;
301
+ }
302
+ while (true) {
303
+ Value item;
304
+ if (!value(item)) return false;
305
+ l.push_back(item.asNum());
306
+ if (eat(',')) continue;
307
+ if (eat(']')) break;
308
+ return false;
309
+ }
310
+ v = Value(l);
311
+ return true;
312
+ }
313
+ if (c == '{') { // nested object: not part of the flat protocol, skip it
314
+ int depth = 0;
315
+ bool inStr = false;
316
+ for (; i < s.size(); ++i) {
317
+ char d = s[i];
318
+ if (inStr) {
319
+ if (d == '\\') ++i;
320
+ else if (d == '"') inStr = false;
321
+ } else if (d == '"') {
322
+ inStr = true;
323
+ } else if (d == '{') {
324
+ ++depth;
325
+ } else if (d == '}' && --depth == 0) {
326
+ ++i;
327
+ v = Value();
328
+ return true;
329
+ }
330
+ }
331
+ return false;
332
+ }
333
+ if (s.compare(i, 4, "true") == 0) { i += 4; v = Value(true); return true; }
334
+ if (s.compare(i, 5, "false") == 0) { i += 5; v = Value(false); return true; }
335
+ if (s.compare(i, 4, "null") == 0) { i += 4; v = Value(); return true; }
336
+ const char* start = s.c_str() + i;
337
+ char* end = nullptr;
338
+ double d = std::strtod(start, &end);
339
+ if (end == start) return false;
340
+ i += static_cast<size_t>(end - start);
341
+ v = Value(d);
342
+ return true;
343
+ }
344
+ };
345
+
346
+ // Parse {"k": v, ...} into out. Returns false on malformed input.
347
+ inline bool decodeJson(const std::string& text, Fields& out) {
348
+ JsonReader r(text);
349
+ if (!r.eat('{')) return false;
350
+ if (r.eat('}')) return true;
351
+ while (true) {
352
+ std::string k;
353
+ Value v;
354
+ if (!r.str(k) || !r.eat(':') || !r.value(v)) return false;
355
+ out[k] = v;
356
+ if (r.eat(',')) continue;
357
+ return r.eat('}');
358
+ }
359
+ }
360
+
361
+ // Drop envelope keys ("channel", "from", "_t" ...) from a received message.
362
+ inline Fields cleanPayload(const Fields& msg) {
363
+ Fields f;
364
+ for (const auto& kv : msg) {
365
+ if (kv.first == "channel" || kv.first == "from" || (!kv.first.empty() && kv.first[0] == '_')) continue;
366
+ f[kv.first] = kv.second;
367
+ }
368
+ return f;
369
+ }
370
+
371
+ class World;
372
+
373
+ // ------------------------------------------------------------------ Entity
374
+ class Entity {
375
+ public:
376
+ struct Timer {
377
+ int ms;
378
+ double next;
379
+ std::function<void()> fn;
380
+ };
381
+
382
+ Entity(World& world, std::string name, std::string kind)
383
+ : nlclWorld_(&world), nlclName_(std::move(name)), nlclKind_(std::move(kind)) {}
384
+ virtual ~Entity() = default;
385
+ Entity(const Entity&) = delete;
386
+ Entity& operator=(const Entity&) = delete;
387
+
388
+ const std::string& name() const { return nlclName_; }
389
+ const std::string& kind() const { return nlclKind_; }
390
+ const std::string& parent() const { return nlclParent_; }
391
+ void setParent(const std::string& p) { nlclParent_ = p; }
392
+ bool alive() const { return nlclAlive_; }
393
+ World& world() const { return *nlclWorld_; }
394
+
395
+ // behaviour hooks, overridden by generated classes
396
+ virtual void onStart() {}
397
+ virtual void onUpdate(double /*dt*/) {}
398
+ virtual void onChange(const std::string& /*prop*/) {}
399
+ // another entity's property changed (change:<entity>.<prop> rules)
400
+ virtual void onWatch(const std::string& /*who*/, const std::string& /*prop*/) {}
401
+ virtual void onMessage(const std::string& /*sender*/, const Fields& /*msg*/) {}
402
+ virtual void onCollision(Entity& /*other*/) {}
403
+ virtual void onInput(const std::string& /*key*/) {}
404
+
405
+ // property reflection, generated per class
406
+ virtual std::vector<std::string> props() const { return {}; }
407
+ virtual Value get(const std::string& /*prop*/) const { return Value(); }
408
+ virtual bool set(const std::string& /*prop*/, const Value& /*v*/) { return false; }
409
+
410
+ bool has(const std::string& prop) const {
411
+ auto p = props();
412
+ return std::find(p.begin(), p.end(), prop) != p.end();
413
+ }
414
+ Fields state() const {
415
+ Fields f;
416
+ for (const auto& p : props()) f[p] = get(p);
417
+ return f;
418
+ }
419
+ std::string stateJson() const { return encodeFields(state()); }
420
+
421
+ // call fn every ms milliseconds of world time
422
+ void every(int ms, std::function<void()> fn) {
423
+ nlclTimers_.push_back(Timer{ms > 0 ? ms : 1, 0.0, std::move(fn)});
424
+ }
425
+ void destroy();
426
+ void log(const std::string& text) const; // "{prop}" placeholders are substituted
427
+ void send(const std::string& to = "", const std::vector<std::string>& fields = {});
428
+ void move(double dx, double dy, double dz);
429
+
430
+ std::vector<Timer> nlclTimers_;
431
+ Fields nlclLast_;
432
+
433
+ private:
434
+ friend class World;
435
+ World* nlclWorld_;
436
+ std::string nlclName_;
437
+ std::string nlclKind_;
438
+ std::string nlclParent_;
439
+ bool nlclAlive_ = true;
440
+ };
441
+
442
+ // ------------------------------------------------------------------ Channel
443
+ // Base transport. src/dst are entity names; fields travel src -> dst.
444
+ class ChannelBase {
445
+ public:
446
+ std::string id, protocol, src, dst;
447
+ std::vector<std::string> fields;
448
+ double interval = 1.0; // seconds between automatic publishes
449
+ bool localSrc = false; // sender lives in this process
450
+ bool localDst = false; // receiver lives in this process
451
+ Fields seed; // starting values for simulated data
452
+ Fields config; // protocol configuration (port, hub_url, topic ...)
453
+ World* world = nullptr;
454
+
455
+ virtual ~ChannelBase() = default;
456
+ virtual void start() {}
457
+ virtual void stop() {}
458
+ virtual void poll() {} // read incoming data (never blocks long)
459
+ virtual void publish(const Fields& payload) = 0; // send one message
460
+ virtual bool streamInput() const { return false; } // receives JSON lines from stdin
461
+
462
+ void tick(double now);
463
+ void receive(const Fields& payload);
464
+ std::string envelope(const Fields& payload) const { return encodeMessage(id, src, payload); }
465
+ Fields fake();
466
+
467
+ double nlclNext_ = 0.0;
468
+ };
469
+
470
+ // Implemented in nlcl_channels.cpp (keeps socket headers out of entity code).
471
+ std::unique_ptr<ChannelBase> makeChannel(const std::string& protocol, const std::string& id,
472
+ const std::string& src, const std::string& dst,
473
+ std::vector<std::string> fields, const Fields& config,
474
+ bool localSrc, bool localDst);
475
+
476
+ // ------------------------------------------------------------------ stdin inbox
477
+ // Lines typed on stdin (or piped from a serial bridge) are queued here by a
478
+ // background thread and consumed by the world loop.
479
+ struct Inbox {
480
+ std::mutex m;
481
+ std::deque<std::string> lines;
482
+ bool started = false;
483
+ };
484
+ inline Inbox& inbox() {
485
+ static Inbox* box = new Inbox(); // intentionally never freed (reader thread is detached)
486
+ return *box;
487
+ }
488
+ inline void startStdinReader() {
489
+ Inbox& box = inbox();
490
+ {
491
+ std::lock_guard<std::mutex> lk(box.m);
492
+ if (box.started) return;
493
+ box.started = true;
494
+ }
495
+ std::thread([] {
496
+ std::string line;
497
+ while (std::getline(std::cin, line)) {
498
+ std::lock_guard<std::mutex> lk(inbox().m);
499
+ inbox().lines.push_back(line);
500
+ }
501
+ }).detach();
502
+ }
503
+
504
+ // ------------------------------------------------------------------ World
505
+ class World {
506
+ public:
507
+ bool simulate = false; // invent data for incoming channels, simulate key presses
508
+ bool verbose = true; // print channel traffic
509
+ double now = 0.0; // world time in seconds
510
+ std::vector<std::unique_ptr<Entity>> entities;
511
+ std::vector<std::unique_ptr<ChannelBase>> channels;
512
+ Fields remote; // "entity.field" -> last value received
513
+ std::vector<std::string> inputKeys; // keys used by input: behaviours
514
+ std::mt19937 rng{20240607u};
515
+
516
+ template <class T>
517
+ T& add(std::unique_ptr<T> e) {
518
+ T& ref = *e;
519
+ entities.push_back(std::move(e));
520
+ return ref;
521
+ }
522
+ void addChannel(std::unique_ptr<ChannelBase> ch) {
523
+ if (!ch) return;
524
+ ch->world = this;
525
+ channels.push_back(std::move(ch));
526
+ }
527
+ // alive entity by name (nullptr if missing/destroyed)
528
+ Entity* find(const std::string& name) const {
529
+ for (const auto& e : entities)
530
+ if (e->alive() && e->name() == name) return e.get();
531
+ return nullptr;
532
+ }
533
+ std::vector<Entity*> children(const std::string& parent) const {
534
+ std::vector<Entity*> out;
535
+ for (const auto& e : entities)
536
+ if (e->alive() && e->parent() == parent) out.push_back(e.get());
537
+ return out;
538
+ }
539
+ // property of a local entity, else the latest value received from a remote one
540
+ Value get(const std::string& entity, const std::string& prop) const {
541
+ Entity* e = find(entity);
542
+ if (e && e->has(prop)) return e->get(prop);
543
+ auto it = remote.find(entity + "." + prop);
544
+ return it != remote.end() ? it->second : Value();
545
+ }
546
+
547
+ void send(Entity& from, const std::string& to, const std::vector<std::string>& fields) {
548
+ for (auto& ch : channels) {
549
+ if (ch->src != from.name()) continue;
550
+ if (!to.empty() && to != ch->dst && to != ch->id) continue;
551
+ const auto& names = fields.empty() ? ch->fields : fields;
552
+ Fields p;
553
+ for (const auto& f : names) p[f] = from.has(f) ? from.get(f) : get(from.name(), f);
554
+ ch->publish(p);
555
+ }
556
+ }
557
+
558
+ // A message for channel ch arrived: remember it, copy same-named fields onto
559
+ // the destination entity and fire its message behaviours.
560
+ void deliver(ChannelBase& ch, const Fields& payload) {
561
+ bool rising = false;
562
+ for (const auto& kv : payload) {
563
+ std::string key = ch.src + "." + kv.first;
564
+ auto it = remote.find(key);
565
+ bool was = it != remote.end() && it->second.asBool();
566
+ if (kv.second.kind == Value::Bool && kv.second.asBool() && !was) rising = true;
567
+ remote[key] = kv.second;
568
+ }
569
+ if (verbose) std::cout << "[" << ch.id << "] <- " << ch.src << " " << encodeFields(payload) << std::endl;
570
+ if (Entity* d = find(ch.dst)) {
571
+ for (const auto& kv : payload)
572
+ if (d->has(kv.first)) d->set(kv.first, kv.second);
573
+ d->onMessage(ch.src, payload);
574
+ }
575
+ if (rising) input(ch.src); // e.g. "when the button is pressed"
576
+ }
577
+
578
+ void input(const std::string& key) {
579
+ for (size_t i = 0; i < entities.size(); ++i)
580
+ if (entities[i]->alive()) entities[i]->onInput(key);
581
+ }
582
+
583
+ void destroyed(Entity& e) {
584
+ if (verbose) std::cout << "[world] " << e.name() << " destroyed" << std::endl;
585
+ }
586
+
587
+ void run(double seconds, double dt, bool realtime);
588
+
589
+ void printState() const {
590
+ std::cout << "final state (t=" << formatNum(now * 1000.0) << " ms):" << std::endl;
591
+ for (const auto& e : entities)
592
+ std::cout << " " << e->name() << " [" << e->kind() << "]" << (e->alive() ? "" : " (destroyed)")
593
+ << ": " << e->stateJson() << std::endl;
594
+ }
595
+
596
+ private:
597
+ std::set<std::pair<std::string, std::string>> touching_;
598
+
599
+ static std::string trim(const std::string& s) {
600
+ size_t a = 0, b = s.size();
601
+ while (a < b && std::isspace(static_cast<unsigned char>(s[a]))) ++a;
602
+ while (b > a && std::isspace(static_cast<unsigned char>(s[b - 1]))) --b;
603
+ return s.substr(a, b - a);
604
+ }
605
+
606
+ // stdin: JSON lines feed stream channels, other lines are key presses
607
+ void drainInbox() {
608
+ std::deque<std::string> lines;
609
+ {
610
+ std::lock_guard<std::mutex> lk(inbox().m);
611
+ lines.swap(inbox().lines);
612
+ }
613
+ for (const auto& raw : lines) {
614
+ std::string line = trim(raw);
615
+ if (line.empty()) continue;
616
+ if (line[0] != '{') {
617
+ input(line);
618
+ continue;
619
+ }
620
+ Fields msg;
621
+ if (!decodeJson(line, msg)) continue;
622
+ auto c = msg.find("channel");
623
+ std::string cid = c != msg.end() ? c->second.asStr() : "";
624
+ for (auto& ch : channels) {
625
+ if (ch->localSrc) continue;
626
+ if (!cid.empty() ? ch->id == cid : ch->streamInput()) {
627
+ ch->receive(cleanPayload(msg));
628
+ break;
629
+ }
630
+ }
631
+ }
632
+ }
633
+
634
+ static double radiusOf(const Entity& e) {
635
+ if (e.has("radius")) return e.get("radius").asNum();
636
+ if (e.has("size")) {
637
+ auto s = e.get("size").asList();
638
+ double m = 0.0;
639
+ for (double x : s) m = std::max(m, x);
640
+ return m / 2.0;
641
+ }
642
+ return 0.5;
643
+ }
644
+
645
+ // sphere-overlap collisions between entities that have a position
646
+ void collisions() {
647
+ std::vector<Entity*> bodies;
648
+ for (const auto& e : entities)
649
+ if (e->alive() && e->has("position")) bodies.push_back(e.get());
650
+ for (size_t i = 0; i < bodies.size(); ++i) {
651
+ for (size_t j = i + 1; j < bodies.size(); ++j) {
652
+ Entity* a = bodies[i];
653
+ Entity* b = bodies[j];
654
+ if (!a->alive() || !b->alive()) continue;
655
+ auto pa = a->get("position").asList();
656
+ auto pb = b->get("position").asList();
657
+ pa.resize(3, 0.0);
658
+ pb.resize(3, 0.0);
659
+ double dx = pa[0] - pb[0], dy = pa[1] - pb[1], dz = pa[2] - pb[2];
660
+ bool hit = std::sqrt(dx * dx + dy * dy + dz * dz) <= radiusOf(*a) + radiusOf(*b);
661
+ auto key = std::make_pair(a->name(), b->name());
662
+ if (hit && !touching_.count(key)) {
663
+ touching_.insert(key);
664
+ a->onCollision(*b);
665
+ if (b->alive() && a->alive()) b->onCollision(*a);
666
+ } else if (!hit) {
667
+ touching_.erase(key);
668
+ }
669
+ }
670
+ }
671
+ }
672
+ };
673
+
674
+ // ------------------------------------------------------------------ inline bodies
675
+ inline void Entity::destroy() {
676
+ if (!nlclAlive_) return;
677
+ nlclAlive_ = false;
678
+ nlclWorld_->destroyed(*this);
679
+ }
680
+
681
+ inline void Entity::log(const std::string& text) const {
682
+ std::string out;
683
+ size_t i = 0;
684
+ while (i < text.size()) {
685
+ if (text[i] == '{') {
686
+ size_t j = text.find('}', i);
687
+ if (j != std::string::npos) {
688
+ std::string key = text.substr(i + 1, j - i - 1);
689
+ Value v;
690
+ if (has(key)) {
691
+ v = get(key);
692
+ } else {
693
+ size_t dot = key.find('.');
694
+ if (dot != std::string::npos) v = world().get(key.substr(0, dot), key.substr(dot + 1));
695
+ }
696
+ if (!v.isNull()) {
697
+ out += v.asStr();
698
+ i = j + 1;
699
+ continue;
700
+ }
701
+ }
702
+ }
703
+ out += text[i++];
704
+ }
705
+ std::cout << "[" << nlclName_ << "] " << out << std::endl;
706
+ }
707
+
708
+ inline void Entity::send(const std::string& to, const std::vector<std::string>& fields) {
709
+ nlclWorld_->send(*this, to, fields);
710
+ }
711
+
712
+ inline void Entity::move(double dx, double dy, double dz) {
713
+ auto p = get("position").asList();
714
+ p.resize(3, 0.0);
715
+ p[0] += dx;
716
+ p[1] += dy;
717
+ p[2] += dz;
718
+ set("position", Value(p));
719
+ }
720
+
721
+ inline void ChannelBase::receive(const Fields& payload) {
722
+ if (world) world->deliver(*this, payload);
723
+ }
724
+
725
+ // Plausible random-walk data for a remote sender (simulate mode).
726
+ inline Fields ChannelBase::fake() {
727
+ Fields p;
728
+ std::uniform_real_distribution<double> jitter(-1.0, 1.0);
729
+ for (const auto& f : fields) {
730
+ auto prev = world->remote.find(src + "." + f);
731
+ Value base;
732
+ if (prev != world->remote.end()) {
733
+ base = prev->second;
734
+ } else if (seed.count(f)) {
735
+ base = seed.at(f);
736
+ } else {
737
+ static const std::map<std::string, double> typical = {
738
+ {"temperature", 24.0}, {"humidity", 45.0}, {"distance", 100.0},
739
+ {"light", 300.0}, {"pressure", 1013.0}, {"voltage", 3.3}};
740
+ auto t = typical.find(f);
741
+ base = Value(t != typical.end() ? t->second : 10.0);
742
+ }
743
+ switch (base.kind) {
744
+ case Value::Bool: p[f] = Value(world->rng() % 2u == 0u); break;
745
+ case Value::Str: p[f] = base; break;
746
+ case Value::List: {
747
+ auto l = base.list;
748
+ for (auto& x : l) x += jitter(world->rng) * 0.1;
749
+ p[f] = Value(l);
750
+ break;
751
+ }
752
+ default: p[f] = Value(std::round((base.asNum() + jitter(world->rng)) * 100.0) / 100.0);
753
+ }
754
+ }
755
+ return p;
756
+ }
757
+
758
+ inline void ChannelBase::tick(double now) {
759
+ if (localSrc) { // periodic auto-publish of the local sender's fields
760
+ if (now + 1e-9 >= nlclNext_) {
761
+ nlclNext_ = now + interval;
762
+ if (Entity* e = world->find(src)) {
763
+ Fields p;
764
+ for (const auto& f : fields) p[f] = e->has(f) ? e->get(f) : world->get(src, f);
765
+ publish(p);
766
+ }
767
+ }
768
+ } else if (world->simulate) { // no network/hardware: invent the remote data
769
+ if (now + 1e-9 >= nlclNext_) {
770
+ nlclNext_ = now + interval;
771
+ receive(fake());
772
+ }
773
+ } else {
774
+ poll();
775
+ }
776
+ }
777
+
778
+ // Fixed-step loop: timers, onUpdate, change detection, collisions, channels.
779
+ // seconds <= 0 runs until Ctrl+C. realtime=false runs as fast as possible.
780
+ inline void World::run(double seconds, double dt, bool realtime) {
781
+ if (dt <= 0.0) dt = 0.1;
782
+ bool wantStdin = !simulate && !inputKeys.empty();
783
+ for (auto& ch : channels) {
784
+ ch->start();
785
+ if (!simulate && !ch->localSrc && ch->streamInput()) wantStdin = true;
786
+ }
787
+ if (wantStdin) startStdinReader();
788
+ for (auto& e : entities) {
789
+ for (auto& t : e->nlclTimers_) t.next = t.ms / 1000.0;
790
+ e->nlclLast_ = e->state();
791
+ }
792
+ for (size_t i = 0; i < entities.size(); ++i)
793
+ if (entities[i]->alive()) entities[i]->onStart();
794
+
795
+ const auto t0 = std::chrono::steady_clock::now();
796
+ long long tick = 0;
797
+ double nextInput = 1.5;
798
+ while (!g_stop) {
799
+ now = static_cast<double>(tick) * dt;
800
+ drainInbox();
801
+ for (size_t i = 0; i < entities.size(); ++i) {
802
+ Entity& e = *entities[i];
803
+ if (!e.alive()) continue;
804
+ for (size_t k = 0; k < e.nlclTimers_.size() && e.alive(); ++k) {
805
+ auto& t = e.nlclTimers_[k];
806
+ if (now + 1e-9 >= t.next) {
807
+ t.next += t.ms / 1000.0;
808
+ if (t.next <= now) t.next = now + t.ms / 1000.0;
809
+ auto fn = t.fn; // copy: the handler may touch the timer list
810
+ fn();
811
+ }
812
+ }
813
+ if (!e.alive()) continue;
814
+ e.onUpdate(dt);
815
+ if (!e.alive()) continue;
816
+ Fields cur = e.state();
817
+ Fields prev = e.nlclLast_;
818
+ e.nlclLast_ = cur;
819
+ for (const auto& kv : cur) {
820
+ auto it = prev.find(kv.first);
821
+ if (it == prev.end() || it->second != kv.second) {
822
+ e.onChange(kv.first);
823
+ for (size_t j = 0; j < entities.size(); ++j)
824
+ if (j != i && entities[j]->alive()) entities[j]->onWatch(e.name(), kv.first);
825
+ if (!e.alive()) break;
826
+ }
827
+ }
828
+ }
829
+ collisions();
830
+ for (auto& ch : channels) ch->tick(now);
831
+ if (simulate && !inputKeys.empty() && now + 1e-9 >= nextInput) {
832
+ nextInput = now + 1.5;
833
+ const std::string& key = inputKeys[rng() % inputKeys.size()];
834
+ if (verbose) std::cout << "[input] simulated press: " << key << std::endl;
835
+ input(key);
836
+ }
837
+ ++tick;
838
+ if (seconds > 0.0 && now + 1e-9 >= seconds) break;
839
+ if (realtime) {
840
+ auto due = t0 + std::chrono::duration_cast<std::chrono::steady_clock::duration>(
841
+ std::chrono::duration<double>(static_cast<double>(tick) * dt));
842
+ std::this_thread::sleep_until(due);
843
+ }
844
+ }
845
+ for (auto& ch : channels) ch->stop();
846
+ }
847
+
848
+ } // namespace nlcl
nlcl/modules/_assets/game/NlclEntity.cs ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // NLCL game runtime for Unity: base class of every generated entity script,
2
+ // plus the NlclWorld registry. Generated by NLCL - edit freely.
3
+ using System.Collections.Generic;
4
+ using System.Globalization;
5
+ using UnityEngine;
6
+
7
+ /// <summary>Base class of all NLCL entities (one MonoBehaviour per entity).</summary>
8
+ public abstract class NlclEntity : MonoBehaviour
9
+ {
10
+ [Header("NLCL")]
11
+ public string nlclId = ""; // entity identifier (snake_case)
12
+ public string nlclKind = "object"; // entity kind (player, enemy, coin ...)
13
+ public bool nlclControls; // arrow keys / WASD move it (movable entity)
14
+ public bool nlclAutoMove; // bullets / projectiles fly by themselves
15
+ public Vector3 nlclStart; // initial position (used by ResetEntity)
16
+
17
+ readonly Dictionary<int, float> _hits = new Dictionary<int, float>();
18
+ string _appliedColor;
19
+ Renderer _renderer;
20
+
21
+ // ---- overridden by generated scripts --------------------------------
22
+ public virtual object NlclGet(string field) { return null; }
23
+ public virtual void NlclSet(string field, object value) { }
24
+ public virtual void NlclMessage(string src, bool isDestination) { }
25
+ public virtual void NlclRemoteInput(string src) { }
26
+ public virtual void NlclCollision(GameObject other) { }
27
+
28
+ protected virtual void Awake()
29
+ {
30
+ nlclStart = transform.position;
31
+ _renderer = GetComponent<Renderer>();
32
+ }
33
+
34
+ // ---- collision: solid contacts and trigger hit-boxes, de-duplicated --
35
+ protected virtual void OnCollisionEnter(Collision c) { Hit(c.gameObject); }
36
+ protected virtual void OnTriggerEnter(Collider c) { Hit(c.gameObject); }
37
+
38
+ void Hit(GameObject other)
39
+ {
40
+ if (other == null || other == gameObject) return;
41
+ NlclEntity oe = other.GetComponentInParent<NlclEntity>();
42
+ if (oe == null || oe == this) return; // ground, scenery, own parts ...
43
+ if (oe.transform.parent == transform || transform.parent == oe.transform) return; // parent <-> child
44
+ object c1 = NlclGet("collision"), c2 = oe.NlclGet("collision");
45
+ if ((c1 is bool && !(bool)c1) || (c2 is bool && !(bool)c2)) return; // "collision": false
46
+ int id = other.GetInstanceID();
47
+ float last;
48
+ if (_hits.TryGetValue(id, out last) && Time.time - last < 0.25f) return;
49
+ _hits[id] = Time.time;
50
+ NlclCollision(other);
51
+ }
52
+
53
+ // ---- built-in movement, bullets, chasing, camera follow, visuals -----
54
+ protected virtual void LateUpdate()
55
+ {
56
+ float speed = ToFloat(NlclGet("speed") ?? 5f);
57
+ Rigidbody rb = GetComponent<Rigidbody>();
58
+ if (nlclControls)
59
+ {
60
+ float h = (NlclInput.Held(KeyCode.RightArrow) || NlclInput.Held(KeyCode.D) ? 1f : 0f)
61
+ - (NlclInput.Held(KeyCode.LeftArrow) || NlclInput.Held(KeyCode.A) ? 1f : 0f);
62
+ float v = (NlclInput.Held(KeyCode.UpArrow) || NlclInput.Held(KeyCode.W) ? 1f : 0f)
63
+ - (NlclInput.Held(KeyCode.DownArrow) || NlclInput.Held(KeyCode.S) ? 1f : 0f);
64
+ if (rb != null && !rb.isKinematic)
65
+ {
66
+ Vector3 vel = GetVelocity(rb);
67
+ vel.x = h * speed;
68
+ if ((NlclInput.Down(KeyCode.Space) || NlclInput.Down(KeyCode.UpArrow) || NlclInput.Down(KeyCode.W))
69
+ && Mathf.Abs(vel.y) < 0.05f)
70
+ vel.y = ToFloat(NlclGet("jump_force") ?? 7f);
71
+ SetVelocity(rb, vel);
72
+ }
73
+ else
74
+ {
75
+ transform.position += new Vector3(h, v, 0f) * speed * Time.deltaTime;
76
+ }
77
+ }
78
+ if (nlclAutoMove)
79
+ {
80
+ Vector3 dir = Vector3.right;
81
+ object d = NlclGet("direction");
82
+ if (d is float[] && ((float[])d).Length >= 2)
83
+ {
84
+ float[] a = (float[])d;
85
+ dir = new Vector3(a[0], a[1], a.Length > 2 ? a[2] : 0f).normalized;
86
+ }
87
+ transform.position += dir * speed * Time.deltaTime;
88
+ if (transform.position.magnitude > 500f) Destroy(gameObject); // left the world
89
+ }
90
+ string target = NlclGet("target") as string;
91
+ if (!string.IsNullOrEmpty(target))
92
+ {
93
+ NlclEntity t = NlclWorld.Get<NlclEntity>(target);
94
+ if (t != null)
95
+ transform.position = Vector3.MoveTowards(transform.position, t.transform.position, speed * Time.deltaTime);
96
+ }
97
+ string follow = NlclGet("follow") as string;
98
+ if (!string.IsNullOrEmpty(follow) && GetComponent<Camera>() != null)
99
+ {
100
+ NlclEntity f = NlclWorld.Get<NlclEntity>(follow);
101
+ if (f != null)
102
+ transform.position = new Vector3(f.transform.position.x, f.transform.position.y, transform.position.z);
103
+ }
104
+ // visuals follow the "color" / "visible" properties
105
+ if (_renderer != null)
106
+ {
107
+ object vis = NlclGet("visible");
108
+ if (vis != null) _renderer.enabled = ToBool(vis);
109
+ string col = NlclGet("color") as string;
110
+ if (!string.IsNullOrEmpty(col) && col != _appliedColor)
111
+ {
112
+ _appliedColor = col;
113
+ Color c;
114
+ if (ColorUtility.TryParseHtmlString(col, out c)) _renderer.material.color = c;
115
+ }
116
+ }
117
+ }
118
+
119
+ // ---- helpers used by generated code ---------------------------------
120
+ protected void Jump()
121
+ {
122
+ Rigidbody rb = GetComponent<Rigidbody>();
123
+ float force = ToFloat(NlclGet("jump_force") ?? 7f);
124
+ if (rb != null && !rb.isKinematic)
125
+ {
126
+ Vector3 v = GetVelocity(rb);
127
+ if (Mathf.Abs(v.y) < 0.05f) { v.y = force; SetVelocity(rb, v); }
128
+ }
129
+ else transform.position += Vector3.up;
130
+ }
131
+
132
+ bool _warnedSpawn;
133
+
134
+ protected void Spawn(string template)
135
+ {
136
+ if (string.IsNullOrEmpty(template)) template = NlclGet("spawn") as string;
137
+ if (string.IsNullOrEmpty(template))
138
+ {
139
+ if (!_warnedSpawn) Log("spawn: nothing to spawn (set the 'spawn' property)");
140
+ _warnedSpawn = true;
141
+ return;
142
+ }
143
+ NlclWorld.Spawn(template, transform.position + Vector3.right * 0.8f);
144
+ }
145
+
146
+ protected void ResetEntity()
147
+ {
148
+ transform.position = nlclStart;
149
+ Rigidbody rb = GetComponent<Rigidbody>();
150
+ if (rb != null && !rb.isKinematic) SetVelocity(rb, Vector3.zero);
151
+ }
152
+
153
+ protected void Log(string text) { Debug.Log("[" + nlclId + "] " + text); }
154
+
155
+ protected void SetX(float v) { Vector3 p = transform.position; p.x = v; transform.position = p; }
156
+ protected void SetY(float v) { Vector3 p = transform.position; p.y = v; transform.position = p; }
157
+ protected void SetZ(float v) { Vector3 p = transform.position; p.z = v; transform.position = p; }
158
+
159
+ public static Vector3 GetVelocity(Rigidbody rb)
160
+ {
161
+ #if UNITY_6000_0_OR_NEWER
162
+ return rb.linearVelocity;
163
+ #else
164
+ return rb.velocity;
165
+ #endif
166
+ }
167
+
168
+ public static void SetVelocity(Rigidbody rb, Vector3 v)
169
+ {
170
+ #if UNITY_6000_0_OR_NEWER
171
+ rb.linearVelocity = v;
172
+ #else
173
+ rb.velocity = v;
174
+ #endif
175
+ }
176
+
177
+ public static float ToFloat(object v)
178
+ {
179
+ if (v == null) return 0f;
180
+ if (v is float) return (float)v;
181
+ if (v is double) return (float)(double)v;
182
+ if (v is int) return (int)v;
183
+ if (v is long) return (long)v;
184
+ if (v is bool) return (bool)v ? 1f : 0f;
185
+ float f;
186
+ return float.TryParse(v.ToString(), NumberStyles.Float, CultureInfo.InvariantCulture, out f) ? f : 0f;
187
+ }
188
+
189
+ public static bool ToBool(object v)
190
+ {
191
+ if (v == null) return false;
192
+ if (v is bool) return (bool)v;
193
+ if (v is string) { string s = ((string)v).ToLowerInvariant(); return s == "true" || s == "1" || s == "on" || s == "yes"; }
194
+ return ToFloat(v) != 0f;
195
+ }
196
+
197
+ public static string ToStr(object v)
198
+ {
199
+ if (v == null) return "";
200
+ if (v is float) return ((float)v).ToString(CultureInfo.InvariantCulture);
201
+ if (v is double) return ((double)v).ToString(CultureInfo.InvariantCulture);
202
+ if (v is bool) return (bool)v ? "true" : "false";
203
+ return v.ToString();
204
+ }
205
+ }
206
+
207
+ /// <summary>Registry of live entities (by NLCL identifier) and spawning.</summary>
208
+ public static class NlclWorld
209
+ {
210
+ public static readonly Dictionary<string, NlclEntity> All = new Dictionary<string, NlclEntity>();
211
+ static int _spawned;
212
+
213
+ public static void Register(NlclEntity e)
214
+ {
215
+ if (e != null && !string.IsNullOrEmpty(e.nlclId)) All[e.nlclId] = e;
216
+ }
217
+
218
+ public static T Get<T>(string id) where T : NlclEntity
219
+ {
220
+ NlclEntity e;
221
+ if (id != null && All.TryGetValue(id, out e) && e != null) return e as T;
222
+ return null;
223
+ }
224
+
225
+ /// <summary>Property of another entity (null if it does not exist).</summary>
226
+ public static object Prop(string id, string field)
227
+ {
228
+ NlclEntity e = Get<NlclEntity>(id);
229
+ return e != null ? e.NlclGet(field) : null;
230
+ }
231
+
232
+ public static Vector3 Pos(string id)
233
+ {
234
+ NlclEntity e = Get<NlclEntity>(id);
235
+ return e != null ? e.transform.position : Vector3.zero;
236
+ }
237
+
238
+ static readonly Dictionary<string, GameObject> _templates = new Dictionary<string, GameObject>();
239
+
240
+ /// <summary>Keep an inactive copy of an entity so it can still be spawned after it is destroyed.
241
+ /// hide = true turns the original itself into the (invisible) template, e.g. for bullets.</summary>
242
+ public static void KeepTemplate(NlclEntity e, bool hide)
243
+ {
244
+ if (e == null) return;
245
+ GameObject go = e.gameObject;
246
+ if (hide) { go.SetActive(false); _templates[e.nlclId] = go; return; }
247
+ bool was = go.activeSelf;
248
+ go.SetActive(false);
249
+ GameObject copy = Object.Instantiate(go);
250
+ go.SetActive(was);
251
+ copy.name = e.nlclId + "_template";
252
+ _templates[e.nlclId] = copy;
253
+ }
254
+
255
+ public static GameObject Spawn(string template, Vector3 at)
256
+ {
257
+ GameObject src;
258
+ if (template == null || !_templates.TryGetValue(template, out src) || src == null)
259
+ {
260
+ NlclEntity t = Get<NlclEntity>(template);
261
+ src = t != null ? t.gameObject : null;
262
+ }
263
+ if (src == null) { Debug.Log("[nlcl] cannot spawn '" + template + "': it does not exist (any more)"); return null; }
264
+ int live = 0;
265
+ foreach (NlclEntity e in All.Values) if (e != null) live++;
266
+ if (live >= 400) return null; // runaway spawning guard
267
+ GameObject go = Object.Instantiate(src, at, src.transform.rotation);
268
+ go.SetActive(true);
269
+ NlclEntity c = go.GetComponent<NlclEntity>();
270
+ _spawned++;
271
+ go.name = template + "_" + _spawned;
272
+ if (c != null)
273
+ {
274
+ c.nlclId = go.name;
275
+ c.nlclControls = false;
276
+ c.nlclStart = at;
277
+ Register(c);
278
+ }
279
+ return go;
280
+ }
281
+
282
+ /// <summary>All live entities (destroyed ones are skipped).</summary>
283
+ public static List<NlclEntity> Live()
284
+ {
285
+ List<NlclEntity> list = new List<NlclEntity>();
286
+ foreach (NlclEntity e in All.Values) if (e != null) list.Add(e);
287
+ return list;
288
+ }
289
+ }
nlcl/modules/_assets/game/NlclHub.cs ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // NLCL game runtime for Unity: cross-module channels through the NLCL HTTP hub
2
+ // (POST {hub}/channel/<id> to publish, GET the same URL to read the latest
3
+ // message) plus a tiny flat-JSON reader/writer. Generated by NLCL.
4
+ using System.Collections;
5
+ using System.Collections.Generic;
6
+ using System.Globalization;
7
+ using System.Text;
8
+ using UnityEngine;
9
+ using UnityEngine.Networking;
10
+
11
+ public class NlclHub : MonoBehaviour
12
+ {
13
+ public class Ch
14
+ {
15
+ public string id, url, src, dst;
16
+ public string[] fields;
17
+ public float interval;
18
+ public bool srcLocal, dstLocal;
19
+ public double seen = -1;
20
+ }
21
+
22
+ public static NlclHub Instance;
23
+ public static readonly Dictionary<string, object> Remote = new Dictionary<string, object>(); // "src.field" -> value
24
+ static readonly Dictionary<string, bool> _lastBool = new Dictionary<string, bool>();
25
+ readonly List<Ch> _channels = new List<Ch>();
26
+
27
+ void Awake() { Instance = this; }
28
+
29
+ public void Add(string id, string url, string src, string dst, string[] fields, int intervalMs, bool srcLocal, bool dstLocal)
30
+ {
31
+ Ch ch = new Ch { id = id, url = url, src = src, dst = dst, fields = fields,
32
+ interval = Mathf.Max(0.05f, intervalMs / 1000f), srcLocal = srcLocal, dstLocal = dstLocal };
33
+ _channels.Add(ch);
34
+ if (srcLocal) StartCoroutine(Publisher(ch));
35
+ else if (dstLocal) StartCoroutine(Poller(ch));
36
+ }
37
+
38
+ // ---- remote values (other modules' properties) ------------------------
39
+ public static float GetFloat(string src, string field, float d) { object v; return Remote.TryGetValue(src + "." + field, out v) ? NlclEntity.ToFloat(v) : d; }
40
+ public static bool GetBool(string src, string field, bool d) { object v; return Remote.TryGetValue(src + "." + field, out v) ? NlclEntity.ToBool(v) : d; }
41
+ public static string GetString(string src, string field, string d) { object v; return Remote.TryGetValue(src + "." + field, out v) ? NlclEntity.ToStr(v) : d; }
42
+
43
+ // ---- sending ------------------------------------------------------------
44
+ /// <summary>"send" action: publish now on every channel whose sender is e.</summary>
45
+ public static void Send(NlclEntity e, string to, string[] fields)
46
+ {
47
+ if (Instance == null || e == null) return;
48
+ bool sent = false;
49
+ foreach (Ch ch in Instance._channels)
50
+ {
51
+ if (ch.src != e.nlclId) continue;
52
+ if (!string.IsNullOrEmpty(to) && to != ch.dst && to != ch.id) continue;
53
+ Instance.Emit(ch, fields ?? ch.fields);
54
+ sent = true;
55
+ }
56
+ // no channel declared, but the receiver lives in this game: deliver directly
57
+ if (!sent && !string.IsNullOrEmpty(to) && NlclWorld.Get<NlclEntity>(to) != null)
58
+ {
59
+ Ch direct = new Ch { id = e.nlclId + "_to_" + to, src = e.nlclId, dst = to,
60
+ fields = fields ?? new string[0], srcLocal = true, dstLocal = true };
61
+ Dictionary<string, object> payload = new Dictionary<string, object>();
62
+ foreach (string f in direct.fields) payload[f] = e.NlclGet(f);
63
+ Deliver(direct, payload);
64
+ }
65
+ }
66
+
67
+ void Emit(Ch ch, string[] fields)
68
+ {
69
+ NlclEntity e = NlclWorld.Get<NlclEntity>(ch.src);
70
+ if (e == null) return;
71
+ Dictionary<string, object> payload = new Dictionary<string, object>();
72
+ foreach (string f in fields) payload[f] = e.NlclGet(f);
73
+ if (ch.dstLocal) { Deliver(ch, payload); return; } // both ends in this game
74
+ payload["channel"] = ch.id;
75
+ payload["from"] = ch.src;
76
+ StartCoroutine(Post(ch.url, NlclJson.Write(payload)));
77
+ }
78
+
79
+ IEnumerator Publisher(Ch ch)
80
+ {
81
+ while (true)
82
+ {
83
+ yield return new WaitForSeconds(ch.interval);
84
+ Emit(ch, ch.fields);
85
+ }
86
+ }
87
+
88
+ IEnumerator Post(string url, string json)
89
+ {
90
+ using (UnityWebRequest r = new UnityWebRequest(url, "POST"))
91
+ {
92
+ r.uploadHandler = new UploadHandlerRaw(Encoding.UTF8.GetBytes(json));
93
+ r.downloadHandler = new DownloadHandlerBuffer();
94
+ r.SetRequestHeader("Content-Type", "application/json");
95
+ r.timeout = 2;
96
+ yield return r.SendWebRequest();
97
+ if (r.result != UnityWebRequest.Result.Success)
98
+ Debug.LogWarning("[nlcl] hub unreachable (" + r.error + "): start python/main.py");
99
+ }
100
+ }
101
+
102
+ IEnumerator Poller(Ch ch)
103
+ {
104
+ float wait = Mathf.Max(0.2f, ch.interval / 2f);
105
+ while (true)
106
+ {
107
+ using (UnityWebRequest r = UnityWebRequest.Get(ch.url))
108
+ {
109
+ r.timeout = 2;
110
+ yield return r.SendWebRequest();
111
+ if (r.result == UnityWebRequest.Result.Success)
112
+ {
113
+ Dictionary<string, object> msg = NlclJson.Parse(r.downloadHandler.text);
114
+ object t;
115
+ if (msg.Count > 0 && msg.TryGetValue("_t", out t))
116
+ {
117
+ double stamp = NlclEntity.ToFloat(t);
118
+ if (t is double) stamp = (double)t;
119
+ if (stamp != ch.seen) { ch.seen = stamp; Deliver(ch, msg); }
120
+ }
121
+ }
122
+ }
123
+ yield return new WaitForSeconds(wait);
124
+ }
125
+ }
126
+
127
+ // ---- receiving ------------------------------------------------------------
128
+ /// <summary>Copy fields onto the destination entity and fire message/input behaviours.</summary>
129
+ public static void Deliver(Ch ch, Dictionary<string, object> msg)
130
+ {
131
+ bool anyBool = false, rising = false;
132
+ foreach (KeyValuePair<string, object> kv in msg)
133
+ {
134
+ if (kv.Key == "channel" || kv.Key == "from" || kv.Key.StartsWith("_")) continue;
135
+ Remote[ch.src + "." + kv.Key] = kv.Value;
136
+ if (kv.Value is bool)
137
+ {
138
+ anyBool = true;
139
+ bool last;
140
+ _lastBool.TryGetValue(ch.src + "." + kv.Key, out last);
141
+ if ((bool)kv.Value && !last) rising = true;
142
+ _lastBool[ch.src + "." + kv.Key] = (bool)kv.Value;
143
+ }
144
+ }
145
+ NlclEntity dst = NlclWorld.Get<NlclEntity>(ch.dst);
146
+ if (dst != null)
147
+ foreach (KeyValuePair<string, object> kv in msg)
148
+ if (kv.Key != "channel" && kv.Key != "from" && !kv.Key.StartsWith("_")) dst.NlclSet(kv.Key, kv.Value);
149
+ foreach (NlclEntity e in NlclWorld.Live())
150
+ {
151
+ e.NlclMessage(ch.src, e == dst);
152
+ if (rising || !anyBool) e.NlclRemoteInput(ch.src);
153
+ }
154
+ }
155
+ }
156
+
157
+ /// <summary>Minimal JSON for flat objects: numbers, strings, booleans, null.</summary>
158
+ public static class NlclJson
159
+ {
160
+ public static string Write(Dictionary<string, object> d)
161
+ {
162
+ StringBuilder sb = new StringBuilder("{");
163
+ bool first = true;
164
+ foreach (KeyValuePair<string, object> kv in d)
165
+ {
166
+ if (!first) sb.Append(',');
167
+ first = false;
168
+ sb.Append(Quote(kv.Key)).Append(':');
169
+ object v = kv.Value;
170
+ if (v == null) sb.Append("null");
171
+ else if (v is bool) sb.Append((bool)v ? "true" : "false");
172
+ else if (v is float || v is double || v is int || v is long)
173
+ sb.Append(System.Convert.ToDouble(v).ToString("R", CultureInfo.InvariantCulture));
174
+ else sb.Append(Quote(v.ToString()));
175
+ }
176
+ return sb.Append('}').ToString();
177
+ }
178
+
179
+ static string Quote(string s)
180
+ {
181
+ return "\"" + s.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") + "\"";
182
+ }
183
+
184
+ public static Dictionary<string, object> Parse(string json)
185
+ {
186
+ Dictionary<string, object> d = new Dictionary<string, object>();
187
+ if (string.IsNullOrEmpty(json)) return d;
188
+ int i = 0;
189
+ Skip(json, ref i);
190
+ if (i >= json.Length || json[i] != '{') return d;
191
+ i++;
192
+ while (i < json.Length)
193
+ {
194
+ Skip(json, ref i);
195
+ if (i < json.Length && json[i] == '}') break;
196
+ string key = ReadString(json, ref i);
197
+ Skip(json, ref i);
198
+ if (i < json.Length && json[i] == ':') i++;
199
+ Skip(json, ref i);
200
+ d[key] = ReadValue(json, ref i);
201
+ Skip(json, ref i);
202
+ if (i < json.Length && json[i] == ',') i++;
203
+ else break;
204
+ }
205
+ return d;
206
+ }
207
+
208
+ static void Skip(string s, ref int i) { while (i < s.Length && char.IsWhiteSpace(s[i])) i++; }
209
+
210
+ static string ReadString(string s, ref int i)
211
+ {
212
+ StringBuilder sb = new StringBuilder();
213
+ if (i >= s.Length || s[i] != '"') return "";
214
+ i++;
215
+ while (i < s.Length && s[i] != '"')
216
+ {
217
+ char c = s[i++];
218
+ if (c == '\\' && i < s.Length)
219
+ {
220
+ char e = s[i++];
221
+ if (e == 'n') sb.Append('\n');
222
+ else if (e == 't') sb.Append('\t');
223
+ else if (e == 'u' && i + 4 <= s.Length) { sb.Append((char)System.Convert.ToInt32(s.Substring(i, 4), 16)); i += 4; }
224
+ else sb.Append(e);
225
+ }
226
+ else sb.Append(c);
227
+ }
228
+ i++;
229
+ return sb.ToString();
230
+ }
231
+
232
+ static object ReadValue(string s, ref int i)
233
+ {
234
+ if (i >= s.Length) return null;
235
+ char c = s[i];
236
+ if (c == '"') return ReadString(s, ref i);
237
+ if (c == '{' || c == '[')
238
+ { // nested values are not part of the flat protocol: skip them
239
+ int depth = 0;
240
+ do { if (s[i] == '{' || s[i] == '[') depth++; else if (s[i] == '}' || s[i] == ']') depth--; i++; }
241
+ while (i < s.Length && depth > 0);
242
+ return null;
243
+ }
244
+ int start = i;
245
+ while (i < s.Length && s[i] != ',' && s[i] != '}' && !char.IsWhiteSpace(s[i])) i++;
246
+ string tok = s.Substring(start, i - start);
247
+ if (tok == "true") return true;
248
+ if (tok == "false") return false;
249
+ if (tok == "null") return null;
250
+ double num;
251
+ if (double.TryParse(tok, NumberStyles.Float, CultureInfo.InvariantCulture, out num)) return num;
252
+ return tok;
253
+ }
254
+ }
nlcl/modules/_assets/game/NlclInput.cs ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // NLCL game runtime for Unity: keyboard/mouse input that works with both the
2
+ // legacy Input Manager and the new Input System package. Generated by NLCL.
3
+ using UnityEngine;
4
+ #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
5
+ using UnityEngine.InputSystem;
6
+ #endif
7
+
8
+ public static class NlclInput
9
+ {
10
+ static int _clickFrame = -1;
11
+ static string _clicked;
12
+
13
+ /// <summary>True during the frame the key/button was pressed.</summary>
14
+ public static bool Down(KeyCode k)
15
+ {
16
+ #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
17
+ if (k == KeyCode.Mouse0) return Mouse.current != null && Mouse.current.leftButton.wasPressedThisFrame;
18
+ if (k == KeyCode.Mouse1) return Mouse.current != null && Mouse.current.rightButton.wasPressedThisFrame;
19
+ Key key = ToKey(k);
20
+ return key != Key.None && Keyboard.current != null && Keyboard.current[key].wasPressedThisFrame;
21
+ #else
22
+ return Input.GetKeyDown(k);
23
+ #endif
24
+ }
25
+
26
+ /// <summary>True while the key/button is held.</summary>
27
+ public static bool Held(KeyCode k)
28
+ {
29
+ #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
30
+ if (k == KeyCode.Mouse0) return Mouse.current != null && Mouse.current.leftButton.isPressed;
31
+ if (k == KeyCode.Mouse1) return Mouse.current != null && Mouse.current.rightButton.isPressed;
32
+ Key key = ToKey(k);
33
+ return key != Key.None && Keyboard.current != null && Keyboard.current[key].isPressed;
34
+ #else
35
+ return Input.GetKey(k);
36
+ #endif
37
+ }
38
+
39
+ public static bool AnyDown()
40
+ {
41
+ #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
42
+ return Keyboard.current != null && Keyboard.current.anyKey.wasPressedThisFrame;
43
+ #else
44
+ return Input.anyKeyDown;
45
+ #endif
46
+ }
47
+
48
+ /// <summary>Key given by name ("space", "a", "f1" ...); false if unknown.</summary>
49
+ public static bool DownNamed(string name)
50
+ {
51
+ KeyCode k;
52
+ if (System.Enum.TryParse(name, true, out k)) return Down(k);
53
+ return false;
54
+ }
55
+
56
+ public static Vector2 MousePosition()
57
+ {
58
+ #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
59
+ return Mouse.current != null ? Mouse.current.position.ReadValue() : Vector2.zero;
60
+ #else
61
+ return Input.mousePosition;
62
+ #endif
63
+ }
64
+
65
+ /// <summary>Identifier of the entity clicked this frame (or null).</summary>
66
+ public static string Clicked()
67
+ {
68
+ if (_clickFrame == Time.frameCount) return _clicked;
69
+ _clickFrame = Time.frameCount;
70
+ _clicked = null;
71
+ if (!Down(KeyCode.Mouse0) || Camera.main == null) return null;
72
+ Ray ray = Camera.main.ScreenPointToRay(MousePosition());
73
+ RaycastHit hit;
74
+ if (Physics.Raycast(ray, out hit, 1000f, ~0, QueryTriggerInteraction.Collide))
75
+ {
76
+ NlclEntity e = hit.collider.GetComponentInParent<NlclEntity>();
77
+ if (e != null) _clicked = e.nlclId;
78
+ }
79
+ return _clicked;
80
+ }
81
+
82
+ #if ENABLE_INPUT_SYSTEM && !ENABLE_LEGACY_INPUT_MANAGER
83
+ static Key ToKey(KeyCode k)
84
+ {
85
+ switch (k)
86
+ {
87
+ case KeyCode.Return: case KeyCode.KeypadEnter: return Key.Enter;
88
+ case KeyCode.LeftControl: return Key.LeftCtrl;
89
+ case KeyCode.RightControl: return Key.RightCtrl;
90
+ }
91
+ if (k >= KeyCode.Alpha0 && k <= KeyCode.Alpha9) return Key.Digit0 + (k - KeyCode.Alpha0);
92
+ Key r;
93
+ return System.Enum.TryParse(k.ToString(), out r) ? r : Key.None;
94
+ }
95
+ #endif
96
+ }
nlcl/modules/_assets/game/nlcl_world.gd ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ extends Node3D
2
+ ## NLCL game runtime for Godot 4: builds entities in code, default controls,
3
+ ## spawning, and cross-module channels through the NLCL HTTP hub.
4
+ ## main.gd extends this script and implements _build(). Generated by NLCL.
5
+
6
+ var entities := {} # identifier -> entity node
7
+ var recipes := {} # identifier -> creation parameters (for spawning)
8
+ var remote := {} # "src.field" -> latest value received over a channel
9
+ var channels := []
10
+ var _last_bool := {}
11
+ var _keys_prev := {}
12
+ var _spawned := 0
13
+ var _colors := {}
14
+
15
+
16
+ func _ready() -> void:
17
+ var light := DirectionalLight3D.new()
18
+ light.rotation_degrees = Vector3(-50, 30, 0)
19
+ add_child(light)
20
+ var env := WorldEnvironment.new()
21
+ env.environment = Environment.new()
22
+ env.environment.background_mode = Environment.BG_COLOR
23
+ env.environment.background_color = Color(0.09, 0.1, 0.13)
24
+ env.environment.ambient_light_source = Environment.AMBIENT_SOURCE_COLOR
25
+ env.environment.ambient_light_color = Color(0.6, 0.6, 0.6)
26
+ add_child(env)
27
+ _build()
28
+
29
+
30
+ func _build() -> void:
31
+ pass # overridden in main.gd
32
+
33
+
34
+ # ------------------------------------------------------------------ building
35
+ func make(script: Script, id: String, kind: String, shape: String, pos: Vector3, size: Vector3,
36
+ color: String, parent_id: String, flags: Dictionary) -> Node3D:
37
+ recipes[id] = [script, kind, shape, size, color, flags]
38
+ var n = script.new()
39
+ n.name = id
40
+ n.nlcl_world = self
41
+ n.nlcl_id = id
42
+ n.nlcl_kind = kind
43
+ n.nlcl_controls = flags.get("controls", false)
44
+ n.nlcl_auto_move = flags.get("auto_move", false)
45
+ n.position = pos
46
+ if n is RigidBody3D:
47
+ n.can_sleep = false
48
+ n.lock_rotation = true
49
+ n.axis_lock_linear_z = true
50
+ if shape != "none":
51
+ var mi := MeshInstance3D.new()
52
+ mi.mesh = _mesh(shape, size)
53
+ var mat := StandardMaterial3D.new()
54
+ mat.albedo_color = Color.from_string(color, Color.WHITE)
55
+ mi.material_override = mat
56
+ mi.name = "Mesh"
57
+ n.add_child(mi)
58
+ if n is CollisionObject3D:
59
+ var cs := CollisionShape3D.new()
60
+ cs.shape = _shape(shape, size)
61
+ n.add_child(cs)
62
+ # hit-box used for the "collision" trigger (overlap with any other entity)
63
+ var area := Area3D.new()
64
+ area.name = "HitBox"
65
+ var acs := CollisionShape3D.new()
66
+ var box := BoxShape3D.new()
67
+ box.size = size * 1.05
68
+ acs.shape = box
69
+ area.add_child(acs)
70
+ n.add_child(area)
71
+ area.area_entered.connect(func(a): _hit(n, a))
72
+ var parent = entities.get(parent_id) if parent_id != "" else null
73
+ if parent != null and is_instance_valid(parent):
74
+ parent.add_child(n)
75
+ else:
76
+ add_child(n)
77
+ entities[id] = n
78
+ return n
79
+
80
+
81
+ func add_template(script: Script, id: String, kind: String, shape: String, size: Vector3, color: String,
82
+ flags: Dictionary) -> void:
83
+ ## an entity that only exists as a spawn template (e.g. a bullet fired by a spawner)
84
+ recipes[id] = [script, kind, shape, size, color, flags]
85
+
86
+
87
+ func _mesh(shape: String, s: Vector3) -> Mesh:
88
+ match shape:
89
+ "sphere":
90
+ var m := SphereMesh.new()
91
+ m.radius = max(s.x, s.y) / 2.0
92
+ m.height = max(s.x, s.y)
93
+ return m
94
+ "capsule":
95
+ var m := CapsuleMesh.new()
96
+ m.radius = s.x / 2.0
97
+ m.height = max(s.y, s.x)
98
+ return m
99
+ "cylinder":
100
+ var m := CylinderMesh.new()
101
+ m.top_radius = s.x / 2.0
102
+ m.bottom_radius = s.x / 2.0
103
+ m.height = s.y
104
+ return m
105
+ var b := BoxMesh.new()
106
+ b.size = s
107
+ return b
108
+
109
+
110
+ func _shape(shape: String, s: Vector3) -> Shape3D:
111
+ match shape:
112
+ "sphere":
113
+ var sp := SphereShape3D.new()
114
+ sp.radius = max(s.x, s.y) / 2.0
115
+ return sp
116
+ "capsule":
117
+ var c := CapsuleShape3D.new()
118
+ c.radius = s.x / 2.0
119
+ c.height = max(s.y, s.x)
120
+ return c
121
+ var b := BoxShape3D.new()
122
+ b.size = s
123
+ return b
124
+
125
+
126
+ func add_ground(pos: Vector3, size: Vector3) -> void:
127
+ ## static floor that is not an entity (no behaviours, no collision trigger)
128
+ var g := StaticBody3D.new()
129
+ g.name = "Ground"
130
+ g.position = pos
131
+ var mi := MeshInstance3D.new()
132
+ var b := BoxMesh.new()
133
+ b.size = size
134
+ mi.mesh = b
135
+ var mat := StandardMaterial3D.new()
136
+ mat.albedo_color = Color(0.25, 0.27, 0.33)
137
+ mi.material_override = mat
138
+ g.add_child(mi)
139
+ var cs := CollisionShape3D.new()
140
+ var bs := BoxShape3D.new()
141
+ bs.size = size
142
+ cs.shape = bs
143
+ g.add_child(cs)
144
+ add_child(g)
145
+
146
+
147
+ func to_bool(v) -> bool:
148
+ if v is String:
149
+ return v.to_lower() in ["true", "1", "on", "yes"]
150
+ if v is bool or v is int or v is float:
151
+ return bool(v)
152
+ return v != null
153
+
154
+
155
+ func add_camera(pos: Vector3, follow: String) -> Camera3D:
156
+ var cam := Camera3D.new()
157
+ cam.position = pos
158
+ cam.current = true
159
+ cam.set_meta("follow", follow)
160
+ add_child(cam)
161
+ return cam
162
+
163
+
164
+ func _hit(n, area) -> void:
165
+ var other = area.get_parent()
166
+ if other == n or not is_instance_valid(n) or n.is_queued_for_deletion():
167
+ return
168
+ if other.get_parent() == n or n.get_parent() == other: # parent <-> child
169
+ return
170
+ for e in [n, other]:
171
+ if e.has_method("nlcl_get") and e.nlcl_get("collision") is bool and not e.nlcl_get("collision"):
172
+ return
173
+ if n.has_method("nlcl_collision"):
174
+ n.nlcl_collision(other)
175
+
176
+
177
+ # ------------------------------------------------------------------ helpers used by entity scripts
178
+ func log_line(id: String, text: String) -> void:
179
+ print("[%s] %s" % [id, text])
180
+
181
+
182
+ func get_prop(id: String, field: String, default_value = 0):
183
+ var e = entities.get(id)
184
+ if e == null or not is_instance_valid(e):
185
+ return default_value
186
+ var v = e.nlcl_get(field)
187
+ return default_value if v == null else v
188
+
189
+
190
+ func get_pos(id: String) -> Vector3:
191
+ var e = entities.get(id)
192
+ if e == null or not is_instance_valid(e):
193
+ return Vector3.ZERO
194
+ return e.global_position
195
+
196
+
197
+ func get_remote(src: String, field: String, default_value = 0):
198
+ return remote.get(src + "." + field, default_value)
199
+
200
+
201
+ func destroy(n) -> void:
202
+ if entities.get(n.nlcl_id) == n:
203
+ entities.erase(n.nlcl_id)
204
+ n.queue_free()
205
+
206
+
207
+ func jump(n) -> void:
208
+ var force = n.nlcl_get("jump_force")
209
+ if force == null:
210
+ force = 7.0
211
+ if n is RigidBody3D:
212
+ if abs(n.linear_velocity.y) < 0.05:
213
+ n.linear_velocity.y = force
214
+ else:
215
+ n.position.y += 1.0
216
+
217
+
218
+ var _spawn_warned := {}
219
+
220
+
221
+ func spawn(template: String, at: Vector3) -> Node3D:
222
+ var r = recipes.get(template)
223
+ if r == null:
224
+ if not _spawn_warned.has(template):
225
+ _spawn_warned[template] = true
226
+ log_line("nlcl", "cannot spawn '%s': unknown entity (set the 'spawn' property)" % template)
227
+ return null
228
+ var live := 0
229
+ for k in entities:
230
+ if is_instance_valid(entities[k]):
231
+ live += 1
232
+ if live >= 400: # runaway spawning guard
233
+ return null
234
+ _spawned += 1
235
+ var flags: Dictionary = r[5].duplicate()
236
+ flags["controls"] = false
237
+ return make(r[0], "%s_%d" % [template, _spawned], r[1], r[2], at, r[3], r[4], "", flags)
238
+
239
+
240
+ func reset_entity(n) -> void:
241
+ n.position = n.nlcl_start
242
+ if n is RigidBody3D:
243
+ n.linear_velocity = Vector3.ZERO
244
+
245
+
246
+ func key_name(event: InputEventKey) -> String:
247
+ ## canonical key names shared with the HTML preview: space, enter, up, a, 1 ...
248
+ return OS.get_keycode_string(event.keycode).to_lower()
249
+
250
+
251
+ func entity_at(screen_pos: Vector2) -> String:
252
+ ## identifier of the entity drawn under the mouse (nearest within 40 px)
253
+ var cam := get_viewport().get_camera_3d()
254
+ if cam == null:
255
+ return ""
256
+ var best := ""
257
+ var best_d := 40.0
258
+ for id in entities:
259
+ var e = entities[id]
260
+ if not is_instance_valid(e) or cam.is_position_behind(e.global_position):
261
+ continue
262
+ var d = cam.unproject_position(e.global_position).distance_to(screen_pos)
263
+ if d < best_d:
264
+ best_d = d
265
+ best = id
266
+ return best
267
+
268
+
269
+ func _key(code: int) -> bool:
270
+ return Input.is_physical_key_pressed(code) or Input.is_key_pressed(code)
271
+
272
+
273
+ func _pressed_now(code: int) -> bool:
274
+ var now := _key(code)
275
+ var was: bool = _keys_prev.get(code, false)
276
+ _keys_prev[code] = now
277
+ return now and not was
278
+
279
+
280
+ # ------------------------------------------------------------------ per-frame built-ins
281
+ func _physics_process(delta: float) -> void:
282
+ # evaluate every key (no short-circuit) so each one's previous state stays current
283
+ var j_space := _pressed_now(KEY_SPACE)
284
+ var j_up := _pressed_now(KEY_UP)
285
+ var j_w := _pressed_now(KEY_W)
286
+ var jump_pressed := j_space or j_up or j_w
287
+ for id in entities.keys():
288
+ var n = entities[id]
289
+ if not is_instance_valid(n):
290
+ entities.erase(id)
291
+ continue
292
+ var speed = n.nlcl_get("speed")
293
+ speed = 5.0 if speed == null else float(speed)
294
+ if n.nlcl_controls:
295
+ var h := float(_key(KEY_RIGHT) or _key(KEY_D)) - float(_key(KEY_LEFT) or _key(KEY_A))
296
+ var v := float(_key(KEY_UP) or _key(KEY_W)) - float(_key(KEY_DOWN) or _key(KEY_S))
297
+ if n is RigidBody3D:
298
+ n.linear_velocity.x = h * speed
299
+ if jump_pressed:
300
+ jump(n)
301
+ else:
302
+ n.position += Vector3(h, v, 0) * speed * delta
303
+ if n.nlcl_auto_move:
304
+ var dir := Vector3.RIGHT
305
+ var d = n.nlcl_get("direction")
306
+ if d is Array and d.size() >= 2:
307
+ dir = Vector3(float(d[0]), float(d[1]), float(d[2]) if d.size() > 2 else 0.0).normalized()
308
+ n.position += dir * speed * delta
309
+ if n.position.length() > 500.0:
310
+ destroy(n)
311
+ continue
312
+ var target = n.nlcl_get("target")
313
+ if target is String and target != "" and entities.has(target) and is_instance_valid(entities[target]):
314
+ n.position = n.position.move_toward(entities[target].position, speed * delta)
315
+ # visuals follow the "color" / "visible" properties
316
+ var vis = n.nlcl_get("visible")
317
+ if vis != null:
318
+ n.visible = to_bool(vis)
319
+ var col = n.nlcl_get("color")
320
+ if col is String and col != "" and _colors.get(id) != col:
321
+ _colors[id] = col
322
+ var mi = n.get_node_or_null("Mesh")
323
+ if mi:
324
+ mi.material_override.albedo_color = Color.from_string(col, Color.WHITE)
325
+ var cam := get_viewport().get_camera_3d()
326
+ if cam and cam.has_meta("follow"):
327
+ var f = entities.get(cam.get_meta("follow"))
328
+ if f != null and is_instance_valid(f):
329
+ cam.position.x = f.global_position.x
330
+ cam.position.y = f.global_position.y
331
+ _channels_tick(delta)
332
+
333
+
334
+ # ------------------------------------------------------------------ channels (NLCL hub)
335
+ func add_channel(id: String, url: String, src: String, dst: String, fields: Array, interval_ms: int,
336
+ src_local: bool, dst_local: bool) -> void:
337
+ var ch := {"id": id, "url": url, "src": src, "dst": dst, "fields": fields,
338
+ "interval": max(0.05, interval_ms / 1000.0), "src_local": src_local, "dst_local": dst_local,
339
+ "t": 0.0, "seen": null, "req": null}
340
+ if not (src_local and dst_local):
341
+ var req := HTTPRequest.new()
342
+ req.timeout = 2.0
343
+ add_child(req)
344
+ ch["req"] = req
345
+ req.request_completed.connect(func(result, code, _headers, body): _on_http(ch, result, code, body))
346
+ channels.append(ch)
347
+
348
+
349
+ func send(n, to: String, fields: Array) -> void:
350
+ var sent := false
351
+ for ch in channels:
352
+ if ch["src"] != n.nlcl_id:
353
+ continue
354
+ if to != "" and to != ch["dst"] and to != ch["id"]:
355
+ continue
356
+ _emit(ch, fields if fields.size() > 0 else ch["fields"])
357
+ sent = true
358
+ # no channel declared, but the receiver lives in this game: deliver directly
359
+ if not sent and to != "" and entities.has(to) and is_instance_valid(entities[to]):
360
+ var payload := {}
361
+ for f in fields:
362
+ payload[f] = n.nlcl_get(f)
363
+ deliver({"id": n.nlcl_id + "_to_" + to, "src": n.nlcl_id, "dst": to, "fields": fields,
364
+ "dst_local": true, "src_local": true}, payload)
365
+
366
+
367
+ func _emit(ch: Dictionary, fields: Array) -> void:
368
+ var e = entities.get(ch["src"])
369
+ if e == null or not is_instance_valid(e):
370
+ return
371
+ var payload := {}
372
+ for f in fields:
373
+ payload[f] = e.nlcl_get(f)
374
+ if ch["dst_local"]:
375
+ deliver(ch, payload)
376
+ return
377
+ payload["channel"] = ch["id"]
378
+ payload["from"] = ch["src"]
379
+ ch["req"].request(ch["url"], ["Content-Type: application/json"], HTTPClient.METHOD_POST, JSON.stringify(payload))
380
+
381
+
382
+ func _channels_tick(delta: float) -> void:
383
+ for ch in channels:
384
+ ch["t"] += delta
385
+ if ch["src_local"]:
386
+ if ch["t"] >= ch["interval"]:
387
+ ch["t"] = 0.0
388
+ _emit(ch, ch["fields"])
389
+ elif ch["dst_local"] and ch["t"] >= max(0.2, ch["interval"] / 2.0):
390
+ ch["t"] = 0.0
391
+ ch["req"].request(ch["url"])
392
+
393
+
394
+ func _on_http(ch: Dictionary, result: int, code: int, body: PackedByteArray) -> void:
395
+ if result != HTTPRequest.RESULT_SUCCESS or code != 200 or ch["src_local"]:
396
+ return
397
+ var d = JSON.parse_string(body.get_string_from_utf8())
398
+ if d is Dictionary and d.size() > 0 and d.get("_t") != ch["seen"]:
399
+ ch["seen"] = d.get("_t")
400
+ deliver(ch, d)
401
+
402
+
403
+ func deliver(ch: Dictionary, payload: Dictionary) -> void:
404
+ ## copy fields onto the destination entity, then fire message / input behaviours
405
+ var any_bool := false
406
+ var rising := false
407
+ for k in payload:
408
+ if k == "channel" or k == "from" or str(k).begins_with("_"):
409
+ continue
410
+ remote[ch["src"] + "." + k] = payload[k]
411
+ if typeof(payload[k]) == TYPE_BOOL:
412
+ any_bool = true
413
+ var key: String = ch["src"] + "." + k
414
+ if payload[k] and not _last_bool.get(key, false):
415
+ rising = true
416
+ _last_bool[key] = payload[k]
417
+ var dst = entities.get(ch["dst"])
418
+ if dst != null and is_instance_valid(dst):
419
+ for k in payload:
420
+ if k != "channel" and k != "from" and not str(k).begins_with("_"):
421
+ dst.nlcl_set(k, payload[k])
422
+ for id in entities.keys():
423
+ var e = entities[id]
424
+ if not is_instance_valid(e):
425
+ continue
426
+ e.nlcl_message(ch["src"], e == dst)
427
+ if rising or not any_bool:
428
+ e.nlcl_remote_input(ch["src"])
nlcl/modules/_assets/game/preview_runtime.js ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ---------------------------------------------------------------- NLCL 2D preview runtime
2
+ // World units: x to the right, y up. Entities are axis-aligned boxes (AABB).
3
+ // Runs in a browser (canvas) or headless under Node: `node preview.js [seconds]`.
4
+ const W = {
5
+ t: 0, ents: [], byId: {}, remoteVals: {}, logs: [], held: new Set(), pressed: [], clicks: [],
6
+ pairs: new Set(), chans: [], hub: "not used", lastBool: {}, spawned: 0, paused: false, headless: false,
7
+ };
8
+ const GRAVITY = 20;
9
+
10
+ function log(o, s) {
11
+ const line = "[" + W.t.toFixed(1) + "s] " + (o ? "[" + o.id + "] " : "") + s;
12
+ W.logs.push(line);
13
+ if (W.logs.length > 300) W.logs.shift();
14
+ console.log(line);
15
+ }
16
+ function tog(v) { return typeof v === "number" ? (v ? 0 : 1) : !v; }
17
+ function num(v, d) { const n = Number(v); return Number.isFinite(n) ? n : d; }
18
+ function get(id, k) {
19
+ const e = W.byId[id];
20
+ if (!e || e.dead) return 0;
21
+ if (k in e.p) return e.p[k];
22
+ if (k === "x" || k === "y" || k === "z") return e[k];
23
+ return 0;
24
+ }
25
+ function remote(id, k, d) { const v = W.remoteVals[id + "." + k]; return v === undefined ? d : v; }
26
+
27
+ function makeEntity(d, id) {
28
+ const o = JSON.parse(JSON.stringify(d));
29
+ o.id = id || d.id;
30
+ o.tmpl = d.id;
31
+ o.vx = 0; o.vy = 0; o.grounded = false; o.dead = false;
32
+ o.start = { x: o.x, y: o.y, p: JSON.parse(JSON.stringify(o.p)) };
33
+ o.maxHealth = typeof o.p.health === "number" && o.p.health > 0 ? o.p.health : null;
34
+ o.beh = BEH[d.id] || {};
35
+ o.timers = (o.beh.timers || []).map(() => 0);
36
+ o.edges = (o.beh.update || []).map(() => false);
37
+ o.prev = {};
38
+ o.spawnAcc = 0; o.spawnN = 0;
39
+ return o;
40
+ }
41
+ function addEntity(o) { W.ents.push(o); W.byId[o.id] = o; snapshot(o); return o; }
42
+ function snapshot(o) { for (const c of (o.beh.change || [])) o.prev[c.k] = val(o, c.k); }
43
+ function val(o, k) { return k in o.p ? o.p[k] : (k === "x" || k === "y" || k === "z" ? o[k] : undefined); }
44
+
45
+ const w = { // API used by generated behaviour code
46
+ log, get, remote, tog,
47
+ destroy(o) { if (!o.dead) { o.dead = true; log(o, "destroyed"); } },
48
+ move(o, dx, dy, dz) { o.x += num(dx, 0); o.y += num(dy, 0); o.z += num(dz, 0); },
49
+ send(o, to, fields) {
50
+ let sent = false;
51
+ for (const ch of W.chans) {
52
+ if (ch.src !== o.id) continue;
53
+ if (to && to !== ch.dst && to !== ch.id) continue;
54
+ emit(ch, fields && fields.length ? fields : ch.fields);
55
+ sent = true;
56
+ }
57
+ // no channel declared, but the receiver lives in this game: deliver directly
58
+ if (!sent && to && W.byId[to] && !W.byId[to].dead) {
59
+ const payload = {};
60
+ for (const f of fields || []) payload[f] = get(o.id, f);
61
+ deliver({ id: o.id + "_to_" + to, src: o.id, dst: to, fields: fields || [], dstLocal: true, srcLocal: true }, payload);
62
+ }
63
+ },
64
+ call(o, name, args) {
65
+ if (name === "jump") {
66
+ if (o.gravity) { if (o.grounded) { o.vy = num(o.p.jump_force, 8); o.grounded = false; } }
67
+ else o.y += 1;
68
+ } else if (name === "spawn" || name === "fire" || name === "shoot") {
69
+ const t = args && args.length ? String(args[0]) : (o.p.spawn || o.spawnDefault || "");
70
+ if (t) spawn(t, o.x + o.w / 2 + 0.5, o.y, o);
71
+ else if (!o.warnedSpawn) { o.warnedSpawn = true; log(o, "spawn: nothing to spawn (set the 'spawn' property)"); }
72
+ } else if (name === "reset" || name === "respawn" || name === "restart") {
73
+ o.x = o.start.x; o.y = o.start.y; o.vx = o.vy = 0;
74
+ } else if (o.beh.calls && o.beh.calls[name]) {
75
+ o.beh.calls[name](o, w, args || []);
76
+ } else log(o, name + "(" + (args || []).join(", ") + ") called");
77
+ },
78
+ };
79
+
80
+ function spawn(tmpl, x, y, by) {
81
+ const d = DATA.entities.find((e) => e.id === tmpl);
82
+ if (!d) { log(by, "cannot spawn '" + tmpl + "': unknown entity"); return null; }
83
+ if (W.ents.filter((e) => !e.dead).length >= 400) return null; // runaway spawning guard
84
+ W.spawned++;
85
+ const o = makeEntity(d, tmpl + "_" + W.spawned);
86
+ o.x = x; o.y = y; o.controls = false;
87
+ addEntity(o);
88
+ fire(o, o.beh.start);
89
+ return o;
90
+ }
91
+
92
+ function fire(o, list, dt) {
93
+ if (!list) return;
94
+ for (const b of list) {
95
+ if (o.dead) return;
96
+ try { if (!b.c || b.c(o, w)) b.f(o, w, dt || 0); }
97
+ catch (err) { log(o, "behaviour error: " + err.message); }
98
+ }
99
+ }
100
+
101
+ // ---------------------------------------------------------------- physics
102
+ function box(o) { return { l: o.x - o.w / 2, r: o.x + o.w / 2, b: o.y - o.h / 2, t: o.y + o.h / 2 }; }
103
+ function overlap(a, b) {
104
+ const A = box(a), B = box(b);
105
+ return A.l < B.r && A.r > B.l && A.b < B.t && A.t > B.b;
106
+ }
107
+ function solids(o) { return W.ents.filter((s) => s !== o && !s.dead && s.solid && s.visual); }
108
+ function moveAxis(o, dx, dy) {
109
+ o.x += dx;
110
+ for (const s of solids(o)) if (overlap(o, s)) { o.x -= dx; o.vx = 0; break; }
111
+ o.y += dy;
112
+ for (const s of solids(o)) {
113
+ if (!overlap(o, s)) continue;
114
+ const S = box(s);
115
+ if (dy < 0) { o.y = S.t + o.h / 2; o.grounded = true; } else if (dy > 0) o.y = S.b - o.h / 2;
116
+ else o.y -= dy;
117
+ o.vy = 0;
118
+ break;
119
+ }
120
+ }
121
+
122
+ function step(dt) {
123
+ if (W.paused) return;
124
+ W.t += dt;
125
+ const live = W.ents.filter((o) => !o.dead);
126
+ for (const o of live) { o.px = o.x; o.py = o.y; }
127
+ for (const o of live) {
128
+ const speed = num(o.p.speed, 5);
129
+ let dx = 0, dy = 0;
130
+ if (o.controls) {
131
+ const h = (W.held.has("right") || W.held.has("d") ? 1 : 0) - (W.held.has("left") || W.held.has("a") ? 1 : 0);
132
+ const v = (W.held.has("up") || W.held.has("w") ? 1 : 0) - (W.held.has("down") || W.held.has("s") ? 1 : 0);
133
+ dx += h * speed * dt;
134
+ if (o.gravity) {
135
+ if (o.grounded && (W.pressed.includes("space") || W.pressed.includes("up") || W.pressed.includes("w"))) {
136
+ o.vy = num(o.p.jump_force, 8); o.grounded = false;
137
+ }
138
+ } else dy += v * speed * dt;
139
+ }
140
+ if (o.autoMove) {
141
+ let dir = [1, 0];
142
+ if (Array.isArray(o.p.direction) && o.p.direction.length >= 2) dir = o.p.direction;
143
+ const len = Math.hypot(dir[0], dir[1]) || 1;
144
+ dx += dir[0] / len * speed * dt; dy += dir[1] / len * speed * dt;
145
+ if (Math.abs(o.x) > 500 || Math.abs(o.y) > 500) o.dead = true;
146
+ }
147
+ const tgt = typeof o.p.target === "string" ? W.byId[o.p.target] : null;
148
+ if (tgt && !tgt.dead && tgt !== o) {
149
+ const ex = tgt.x - o.x, ey = tgt.y - o.y, d = Math.hypot(ex, ey);
150
+ if (d > 0.05) { dx += ex / d * Math.min(d, speed * dt); if (!o.gravity) dy += ey / d * Math.min(d, speed * dt); }
151
+ }
152
+ if (o.gravity) { o.vy -= GRAVITY * dt; dy += o.vy * dt; o.grounded = false; }
153
+ if (dx || dy) { if (o.solid && !o.gravity) { o.x += dx; o.y += dy; } else moveAxis(o, dx, dy); }
154
+ if (o.y < -100) { o.dead = true; log(o, "fell out of the world"); }
155
+ }
156
+ // children are carried along by their parent (parents first, any depth)
157
+ const depth = (o) => { let d = 0, q = o; while (q && q.parent && d < 50) { q = W.byId[q.parent]; d++; } return d; };
158
+ for (const o of live.filter((c) => c.parent && W.byId[c.parent]).sort((a, b) => depth(a) - depth(b))) {
159
+ const par = W.byId[o.parent];
160
+ if (par.dead) { if (!o.dead) { o.dead = true; } continue; }
161
+ o.x += par.x - par.px; o.y += par.y - par.py;
162
+ }
163
+ // keyboard / mouse
164
+ for (const k of W.pressed) for (const o of W.ents.slice()) {
165
+ if (o.dead) continue;
166
+ fire(o, (o.beh.input || []).filter((b) => b.key === k || b.key === "any"), dt);
167
+ }
168
+ for (const id of W.clicks) for (const o of W.ents.slice()) {
169
+ if (o.dead) continue;
170
+ fire(o, (o.beh.click || []).filter((b) => b.id === id || b.id === "mouse"), dt);
171
+ }
172
+ // timers
173
+ for (const o of W.ents.slice()) {
174
+ if (o.dead) continue;
175
+ (o.beh.timers || []).forEach((b, i) => {
176
+ o.timers[i] += dt * 1000;
177
+ if (o.timers[i] >= b.ms) { o.timers[i] -= b.ms; fire(o, [b], dt); }
178
+ });
179
+ }
180
+ // update behaviours: unconditional every frame; conditional ones fire when the condition becomes true
181
+ for (const o of W.ents.slice()) {
182
+ if (o.dead) continue;
183
+ (o.beh.update || []).forEach((b, i) => {
184
+ if (o.dead) return;
185
+ if (!b.c) { fire(o, [b], dt); return; }
186
+ let ok = false;
187
+ try { ok = !!b.c(o, w); } catch (err) { ok = false; }
188
+ if (ok && !o.edges[i]) { o.edges[i] = true; fire(o, [{ f: b.f }], dt); }
189
+ else if (!ok) o.edges[i] = false;
190
+ });
191
+ }
192
+ // collisions (AABB, fired once when two entities start touching)
193
+ const now = new Set();
194
+ const vis = W.ents.filter((o) => !o.dead && o.visual && !o.noHit && o.p.collision !== false);
195
+ for (let i = 0; i < vis.length; i++) for (let j = i + 1; j < vis.length; j++) {
196
+ const a = vis[i], b = vis[j];
197
+ if (a.parent === b.id || b.parent === a.id) continue; // a part does not hit its own body
198
+ if (!overlap(a, b) && !touching(a, b)) continue;
199
+ const key = a.id + "|" + b.id;
200
+ now.add(key);
201
+ if (!W.pairs.has(key)) {
202
+ // rules with a partner ("w": entity id or kind) only fire for that partner
203
+ const hit = (o, other) => (o.beh.collision || []).filter((r) => !r.w || r.w === other.id || r.w === other.kind);
204
+ W.other = b; fire(a, hit(a, b), dt);
205
+ W.other = a; fire(b, hit(b, a), dt);
206
+ }
207
+ }
208
+ W.pairs = now;
209
+ // spawners
210
+ for (const o of W.ents.slice()) {
211
+ if (o.dead || !o.p.spawn || !(num(o.p.spawn_interval_ms, 0) > 0)) continue;
212
+ o.spawnAcc += dt * 1000;
213
+ if (o.spawnAcc >= o.p.spawn_interval_ms && o.spawnN < num(o.p.max_spawn, 10)) {
214
+ o.spawnAcc = 0; o.spawnN++;
215
+ spawn(String(o.p.spawn), o.x, o.y, o);
216
+ }
217
+ }
218
+ // change detection
219
+ for (const o of W.ents.slice()) {
220
+ if (o.dead) continue;
221
+ for (const c of (o.beh.change || [])) {
222
+ const v = val(o, c.k);
223
+ if (JSON.stringify(v) !== JSON.stringify(o.prev[c.k])) { o.prev[c.k] = v; fire(o, [c], dt); }
224
+ }
225
+ }
226
+ tickChannels(dt);
227
+ W.pressed = []; W.clicks = [];
228
+ for (const o of W.ents.slice()) if (o.dead) delete W.byId[o.id];
229
+ W.ents = W.ents.filter((o) => !o.dead);
230
+ }
231
+ function touching(a, b) { // resting contact (e.g. standing on a platform) counts as touching
232
+ const A = box(a), B = box(b), eps = 0.02;
233
+ return A.l < B.r && A.r > B.l && Math.abs(A.b - B.t) < eps || A.l < B.r && A.r > B.l && Math.abs(A.t - B.b) < eps;
234
+ }
235
+
236
+ // ---------------------------------------------------------------- channels (NLCL hub)
237
+ function emit(ch, fields) {
238
+ const src = W.byId[ch.src];
239
+ if (!src) return;
240
+ const payload = {};
241
+ for (const f of fields) payload[f] = get(ch.src, f);
242
+ if (ch.dstLocal) { deliver(ch, payload); return; }
243
+ if (W.headless) { log(src, "-> " + ch.id + " " + JSON.stringify(payload)); return; }
244
+ fetch(ch.url, { method: "POST", headers: { "Content-Type": "text/plain" },
245
+ body: JSON.stringify(Object.assign({ channel: ch.id, from: ch.src }, payload)) })
246
+ .then(() => { W.hub = "online"; }).catch(() => { W.hub = "offline (run python/main.py)"; });
247
+ }
248
+ function deliver(ch, msg) {
249
+ let anyBool = false, rising = false;
250
+ for (const [k, v] of Object.entries(msg)) {
251
+ if (k === "channel" || k === "from" || k.startsWith("_")) continue;
252
+ W.remoteVals[ch.src + "." + k] = v;
253
+ if (typeof v === "boolean") {
254
+ anyBool = true;
255
+ const key = ch.src + "." + k;
256
+ if (v && !W.lastBool[key]) rising = true;
257
+ W.lastBool[key] = v;
258
+ }
259
+ }
260
+ const dst = W.byId[ch.dst];
261
+ if (dst) for (const [k, v] of Object.entries(msg)) if (k in dst.p) dst.p[k] = v;
262
+ for (const o of W.ents.slice()) {
263
+ if (o.dead) continue;
264
+ fire(o, (o.beh.message || []).filter((b) => b.src ? b.src.includes(ch.src) : o === dst));
265
+ if (rising || !anyBool) fire(o, (o.beh.remote || []).filter((b) => b.src.includes(ch.src)));
266
+ }
267
+ }
268
+ function tickChannels(dt) {
269
+ for (const ch of W.chans) {
270
+ ch.acc = (ch.acc || 0) + dt * 1000;
271
+ if (ch.srcLocal) {
272
+ if (ch.acc >= ch.interval) { ch.acc = 0; emit(ch, ch.fields); }
273
+ } else if (ch.dstLocal && !W.headless && ch.acc >= Math.max(200, ch.interval / 2) && !ch.busy) {
274
+ ch.acc = 0; ch.busy = true;
275
+ fetch(ch.url).then((r) => r.json()).then((m) => {
276
+ W.hub = "online";
277
+ if (m && m._t !== undefined && m._t !== ch.seen) { ch.seen = m._t; deliver(ch, m); }
278
+ }).catch(() => { W.hub = "offline (run python/main.py)"; }).finally(() => { ch.busy = false; });
279
+ }
280
+ }
281
+ }
282
+
283
+ function init() {
284
+ W.ents = []; W.byId = {}; W.pairs = new Set(); W.t = 0;
285
+ for (const d of DATA.entities) if (!d.template) addEntity(makeEntity(d)); // templates only spawn
286
+ W.chans = DATA.channels.map((c) => Object.assign({}, c));
287
+ if (W.chans.some((c) => !(c.srcLocal && c.dstLocal))) W.hub = "connecting...";
288
+ for (const o of W.ents.slice()) fire(o, o.beh.start);
289
+ }
290
+
291
+ // ---------------------------------------------------------------- headless (Node) mode
292
+ if (typeof window === "undefined") {
293
+ W.headless = true;
294
+ const secs = Number((typeof process !== "undefined" && process.argv[2]) || 5);
295
+ init();
296
+ const keys = [...new Set(Object.values(BEH).flatMap((b) => (b.input || []).map((x) => x.key)))].filter((k) => k !== "any");
297
+ const clicks = [...new Set(Object.values(BEH).flatMap((b) => (b.click || []).map((x) => x.id)))];
298
+ const dt = 1 / 60;
299
+ let next = 0.5;
300
+ const script = keys.map((k) => ["key", k]).concat(clicks.map((c) => ["click", c]));
301
+ for (let i = 0; i < secs / dt; i++) {
302
+ if (script.length && W.t >= next) { // exercise every bound key / click once, 0.5 s apart
303
+ const [type, k] = script.shift();
304
+ console.log("[" + W.t.toFixed(1) + "s] (test input: " + type + " " + k + ")");
305
+ if (type === "key") W.pressed.push(k); else W.clicks.push(k);
306
+ next += 0.5;
307
+ }
308
+ step(dt);
309
+ }
310
+ console.log("--- state after " + secs + " s ---");
311
+ for (const o of W.ents.slice()) console.log(o.id + " (" + o.kind + ") x=" + o.x.toFixed(2) + " y=" + o.y.toFixed(2) + " " + JSON.stringify(o.p));
312
+ const gone = DATA.entities.filter((d) => !d.template && !W.byId[d.id]).map((d) => d.id);
313
+ if (gone.length) console.log("destroyed: " + gone.join(", "));
314
+ }
315
+
316
+ // ---------------------------------------------------------------- browser mode
317
+ if (typeof window !== "undefined") {
318
+ const cv = document.getElementById("view"), g = cv.getContext("2d");
319
+ let view = { cx: 0, cy: 0, scale: 40 };
320
+ function fit() {
321
+ cv.width = cv.clientWidth * devicePixelRatio; cv.height = cv.clientHeight * devicePixelRatio;
322
+ const vis = W.ents.filter((o) => o.visual);
323
+ if (!vis.length) return;
324
+ let l = Infinity, r = -Infinity, b = Infinity, t = -Infinity;
325
+ for (const o of vis) { const B = box(o); l = Math.min(l, B.l); r = Math.max(r, B.r); b = Math.min(b, B.b); t = Math.max(t, B.t); }
326
+ l -= 3; r += 3; b -= 3; t += 3;
327
+ view.cx = (l + r) / 2; view.cy = (b + t) / 2;
328
+ view.scale = Math.min(cv.width / (r - l), cv.height / (t - b), 80 * devicePixelRatio);
329
+ }
330
+ const sx = (x) => cv.width / 2 + (x - view.cx) * view.scale;
331
+ const sy = (y) => cv.height / 2 - (y - view.cy) * view.scale;
332
+ const KEYMAP = { " ": "space", Enter: "enter", ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right",
333
+ Escape: "escape", Shift: "shift", Control: "ctrl", Alt: "alt", Tab: "tab", Backspace: "backspace" };
334
+ const keyName = (e) => KEYMAP[e.key] || e.key.toLowerCase();
335
+ addEventListener("keydown", (e) => {
336
+ const k = keyName(e);
337
+ if (["space", "up", "down", "left", "right"].includes(k)) e.preventDefault();
338
+ if (!W.held.has(k)) W.pressed.push(k);
339
+ W.held.add(k);
340
+ });
341
+ addEventListener("keyup", (e) => W.held.delete(keyName(e)));
342
+ addEventListener("blur", () => W.held.clear());
343
+ cv.addEventListener("mousedown", (e) => {
344
+ const r = cv.getBoundingClientRect();
345
+ const x = view.cx + ((e.clientX - r.left) * devicePixelRatio - cv.width / 2) / view.scale;
346
+ const y = view.cy - ((e.clientY - r.top) * devicePixelRatio - cv.height / 2) / view.scale;
347
+ W.clicks.push("mouse");
348
+ for (const o of W.ents.slice()) { const B = box(o); if (o.visual && x >= B.l && x <= B.r && y >= B.b && y <= B.t) W.clicks.push(o.id); }
349
+ });
350
+ document.getElementById("pause").onclick = (e) => { W.paused = !W.paused; e.target.textContent = W.paused ? "Resume" : "Pause"; };
351
+ document.getElementById("restart").onclick = () => { W.logs = []; init(); fit(); };
352
+ addEventListener("resize", fit);
353
+
354
+ function draw() {
355
+ g.fillStyle = "#14161c"; g.fillRect(0, 0, cv.width, cv.height);
356
+ const cam = W.ents.find((o) => o.kind === "camera" && typeof o.p.follow === "string" && W.byId[o.p.follow]);
357
+ if (cam) { view.cx = W.byId[cam.p.follow].x; view.cy = W.byId[cam.p.follow].y; }
358
+ g.strokeStyle = "#1f232c"; g.lineWidth = 1;
359
+ const step1 = view.scale;
360
+ for (let x = sx(Math.floor(view.cx - cv.width / step1)); x < cv.width; x += step1) { g.beginPath(); g.moveTo(x, 0); g.lineTo(x, cv.height); g.stroke(); }
361
+ for (let y = sy(Math.ceil(view.cy + cv.height / step1)); y < cv.height; y += step1) { g.beginPath(); g.moveTo(0, y); g.lineTo(cv.width, y); g.stroke(); }
362
+ const font = Math.max(10, 12 * devicePixelRatio);
363
+ g.font = font + "px system-ui, sans-serif"; g.textAlign = "center";
364
+ for (const o of W.ents.slice()) {
365
+ if (!o.visual || o.p.visible === false) continue;
366
+ const B = box(o), x = sx(B.l), y = sy(B.t), wd = o.w * view.scale, ht = o.h * view.scale;
367
+ g.fillStyle = typeof o.p.color === "string" && o.p.color ? o.p.color : o.color;
368
+ g.beginPath();
369
+ if (o.shape === "sphere") g.ellipse(x + wd / 2, y + ht / 2, wd / 2, ht / 2, 0, 0, Math.PI * 2);
370
+ else if (o.shape === "capsule" && g.roundRect) g.roundRect(x, y, wd, ht, Math.min(wd, ht) / 2);
371
+ else g.rect(x, y, wd, ht);
372
+ g.fill();
373
+ if (o.controls) { g.strokeStyle = "#ffffffaa"; g.lineWidth = 2; g.stroke(); }
374
+ if (!o.noHit) { g.fillStyle = "#cfd3dc"; g.fillText(o.id, x + wd / 2, y - 6 * devicePixelRatio); }
375
+ if (o.maxHealth && typeof o.p.health === "number") {
376
+ const f = Math.max(0, Math.min(1, o.p.health / o.maxHealth));
377
+ const bw = Math.max(wd, 40 * devicePixelRatio), bx = x + wd / 2 - bw / 2, by = y - 6 * devicePixelRatio - font - 6 * devicePixelRatio;
378
+ g.fillStyle = "#3a3f4b"; g.fillRect(bx, by, bw, 5 * devicePixelRatio);
379
+ g.fillStyle = f > 0.5 ? "#22c55e" : f > 0.25 ? "#eab308" : "#ef4444"; g.fillRect(bx, by, bw * f, 5 * devicePixelRatio);
380
+ }
381
+ }
382
+ }
383
+ const esc = (t) => String(t).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
384
+ let lastPanel = 0;
385
+ function panel() {
386
+ const rows = W.ents.filter((o) => !o.noHit).map((o) => "<tr><td>" + o.id + "</td><td>" + o.kind + "</td><td>" + o.x.toFixed(1) + ", " + o.y.toFixed(1) +
387
+ "</td><td>" + esc(Object.entries(o.p).map(([k, v]) => k + "=" + (typeof v === "number" ? +v.toFixed(2) : JSON.stringify(v))).join(" ")) + "</td></tr>");
388
+ document.getElementById("ents").innerHTML = "<tr><th>entity</th><th>kind</th><th>x, y</th><th>properties</th></tr>" + rows.join("");
389
+ document.getElementById("log").textContent = W.logs.slice(-60).join("\n");
390
+ document.getElementById("time").textContent = W.t.toFixed(1) + " s";
391
+ document.getElementById("hub").textContent = W.chans.length ? "hub: " + W.hub : "";
392
+ }
393
+ let last = performance.now();
394
+ function frame(now) {
395
+ const dt = Math.min(0.05, (now - last) / 1000); last = now;
396
+ step(dt); draw();
397
+ if (now - lastPanel > 250) { lastPanel = now; panel(); }
398
+ requestAnimationFrame(frame);
399
+ }
400
+ init(); fit(); requestAnimationFrame(frame);
401
+ }
nlcl/modules/_assets/hardware/nlcl_i2c_slave.v ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // nlcl_i2c_slave.v - NLCL I2C slave (7-bit address), oversampled by clk.
2
+ // Shipped by NLCL; synthesizable Verilog-2005.
3
+ //
4
+ // Byte protocol (shared with the NLCL embedded module):
5
+ // master WRITE : [addr+W] 0xA5, N, then N x int16 big-endian words (field order)
6
+ // -> rx_words updated, rx_valid pulses for one clk
7
+ // master READ : [addr+R] the slave answers 0xA5, N, N x int16 big-endian words
8
+ // taken from tx_words (snapshot at the address phase).
9
+ // SDA is open-drain: the top level does assign sda = sda_oe ? 1'b0 : 1'bz;
10
+ // SCL must be at most clk/16 (100/400 kHz is fine with any clock >= 8 MHz).
11
+ `timescale 1ns / 1ps
12
+ `default_nettype none
13
+ module nlcl_i2c_slave #(
14
+ parameter [6:0] ADDR = 7'h42,
15
+ parameter N = 1
16
+ ) (
17
+ input wire clk,
18
+ input wire rst,
19
+ input wire scl,
20
+ input wire sda_i,
21
+ output reg sda_oe,
22
+ output reg [16*N-1:0] rx_words,
23
+ output reg rx_valid,
24
+ input wire [16*N-1:0] tx_words
25
+ );
26
+ localparam P_IDLE = 2'd0, P_ADDR = 2'd1, P_WRITE = 2'd2, P_READ = 2'd3;
27
+
28
+ reg [2:0] scl_s;
29
+ reg [2:0] sda_s;
30
+ reg [1:0] phase;
31
+ reg [3:0] cnt; // SCL rising edges seen in the current byte (0..9)
32
+ reg [7:0] shreg;
33
+ reg [7:0] shout;
34
+ reg [7:0] idx; // byte index inside the frame
35
+ reg matched;
36
+ reg rw;
37
+ reg nack;
38
+ reg frame_ok;
39
+ reg [16*N-1:0] rx_buf;
40
+ reg [16*N-1:0] tx_buf;
41
+
42
+ wire scl_rise = (scl_s[2:1] == 2'b01);
43
+ wire scl_fall = (scl_s[2:1] == 2'b10);
44
+ wire start_c = scl_s[2] & scl_s[1] & (sda_s[2:1] == 2'b10);
45
+ wire stop_c = scl_s[2] & scl_s[1] & (sda_s[2:1] == 2'b01);
46
+
47
+
48
+ // next byte to transmit in a READ frame: 0xA5, N, data bytes, then 0xFF
49
+ wire [7:0] dsel = idx - 8'd2;
50
+ wire [7:0] n_byte = N;
51
+ wire [7:0] next_tx = (idx == 8'd0) ? 8'hA5 :
52
+ (idx == 8'd1) ? n_byte :
53
+ (dsel < 2*N) ? tx_buf[16*N-1 - 8*dsel -: 8] : 8'hFF;
54
+
55
+ always @(posedge clk) begin
56
+ if (rst) begin
57
+ scl_s <= 3'b111;
58
+ sda_s <= 3'b111;
59
+ phase <= P_IDLE;
60
+ cnt <= 4'd0;
61
+ shreg <= 8'd0;
62
+ shout <= 8'hFF;
63
+ idx <= 8'd0;
64
+ matched <= 1'b0;
65
+ rw <= 1'b0;
66
+ nack <= 1'b0;
67
+ frame_ok <= 1'b0;
68
+ sda_oe <= 1'b0;
69
+ rx_buf <= {16*N{1'b0}};
70
+ tx_buf <= {16*N{1'b0}};
71
+ rx_words <= {16*N{1'b0}};
72
+ rx_valid <= 1'b0;
73
+ end else begin
74
+ scl_s <= {scl_s[1:0], scl};
75
+ sda_s <= {sda_s[1:0], sda_i};
76
+ rx_valid <= 1'b0;
77
+ if (start_c) begin
78
+ phase <= P_ADDR;
79
+ cnt <= 4'd0;
80
+ idx <= 8'd0;
81
+ matched <= 1'b0;
82
+ sda_oe <= 1'b0;
83
+ end else if (stop_c) begin
84
+ phase <= P_IDLE;
85
+ sda_oe <= 1'b0;
86
+ end else if (phase != P_IDLE) begin
87
+ if (scl_rise) begin
88
+ if (cnt < 4'd8)
89
+ shreg <= {shreg[6:0], sda_s[1]};
90
+ else if (phase == P_READ)
91
+ nack <= sda_s[1];
92
+ cnt <= cnt + 4'd1;
93
+ end
94
+ if (scl_fall) begin
95
+ if (cnt == 4'd8) begin
96
+ // 8 data bits done: acknowledge (or release for the master's ACK)
97
+ case (phase)
98
+ P_ADDR: begin
99
+ if (shreg[7:1] == ADDR) begin
100
+ sda_oe <= 1'b1;
101
+ matched <= 1'b1;
102
+ rw <= shreg[0];
103
+ tx_buf <= tx_words;
104
+ end else begin
105
+ phase <= P_IDLE;
106
+ sda_oe <= 1'b0;
107
+ end
108
+ end
109
+ P_WRITE: begin
110
+ sda_oe <= 1'b1;
111
+ idx <= idx + 8'd1;
112
+ if (idx == 8'd0)
113
+ frame_ok <= (shreg == 8'hA5);
114
+ else if (idx == 8'd1) begin
115
+ if (shreg != N) frame_ok <= 1'b0;
116
+ end else if (idx < 2*N + 2) begin
117
+ rx_buf[16*N-1 - 8*(idx - 8'd2) -: 8] <= shreg;
118
+ if (idx == 2*N + 1 && frame_ok) begin
119
+ rx_words <= {rx_buf[16*N-1:8], shreg};
120
+ rx_valid <= 1'b1;
121
+ end
122
+ end
123
+ end
124
+ default: sda_oe <= 1'b0; // P_READ: master drives ACK/NACK
125
+ endcase
126
+ end else if (cnt == 4'd9) begin
127
+ cnt <= 4'd0;
128
+ if (phase == P_ADDR && matched) begin
129
+ if (rw) begin
130
+ phase <= P_READ;
131
+ shout <= next_tx;
132
+ sda_oe <= ~next_tx[7];
133
+ idx <= idx + 8'd1;
134
+ end else begin
135
+ phase <= P_WRITE;
136
+ sda_oe <= 1'b0;
137
+ end
138
+ end else if (phase == P_READ) begin
139
+ if (nack) begin
140
+ phase <= P_IDLE;
141
+ sda_oe <= 1'b0;
142
+ end else begin
143
+ shout <= next_tx;
144
+ sda_oe <= ~next_tx[7];
145
+ idx <= idx + 8'd1;
146
+ end
147
+ end else begin
148
+ sda_oe <= 1'b0;
149
+ end
150
+ end else if (phase == P_READ) begin
151
+ // bits 6..0 of the current byte
152
+ sda_oe <= ~shout[7 - cnt];
153
+ end
154
+ end
155
+ end
156
+ end
157
+ end
158
+ endmodule
159
+ `default_nettype wire
nlcl/modules/_assets/hardware/nlcl_spi_slave.v ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // nlcl_spi_slave.v - NLCL SPI slave (mode 0, MSB first), oversampled by clk.
2
+ // Shipped by NLCL; synthesizable Verilog-2005.
3
+ //
4
+ // Byte protocol (shared with the NLCL embedded module):
5
+ // master WRITE frame : 0xA5, N, then N x int16 big-endian words (field order)
6
+ // -> rx_words updated, rx_valid pulses for one clk
7
+ // master READ frame : master sends 0x5A, then clocks 1 + 2*N more bytes;
8
+ // the slave answers 0xA5 followed by N x int16 big-endian
9
+ // words taken from tx_words (snapshot when CS falls).
10
+ // Word i lives in bits [16*(N-i)-1 -: 16] (word 0 = most significant).
11
+ // SCLK must be at most clk/8 (e.g. 1 MHz SPI with a 12+ MHz system clock).
12
+ `timescale 1ns / 1ps
13
+ `default_nettype none
14
+ module nlcl_spi_slave #(
15
+ parameter N = 1
16
+ ) (
17
+ input wire clk,
18
+ input wire rst,
19
+ input wire sclk,
20
+ input wire mosi,
21
+ input wire cs_n,
22
+ output reg miso,
23
+ output reg [16*N-1:0] rx_words,
24
+ output reg rx_valid,
25
+ input wire [16*N-1:0] tx_words
26
+ );
27
+ reg [2:0] sclk_s;
28
+ reg [2:0] cs_s;
29
+ reg [1:0] mosi_s;
30
+ reg [2:0] bitcnt;
31
+ reg [7:0] bytecnt;
32
+ reg [7:0] shin;
33
+ reg [7:0] shout;
34
+ reg reading;
35
+ reg frame_ok;
36
+ reg [16*N-1:0] rx_buf;
37
+ reg [16*N-1:0] tx_buf;
38
+
39
+ wire sclk_rise = (sclk_s[2:1] == 2'b01);
40
+ wire sclk_fall = (sclk_s[2:1] == 2'b10);
41
+ wire cs_active = ~cs_s[1];
42
+ wire cs_start = (cs_s[2:1] == 2'b10);
43
+ wire [7:0] byte_in = {shin[6:0], mosi_s[1]};
44
+ wire [7:0] tx_index = bytecnt - 8'd1; // data byte to send next
45
+
46
+ always @(posedge clk) begin
47
+ if (rst) begin
48
+ sclk_s <= 3'b000;
49
+ cs_s <= 3'b111;
50
+ mosi_s <= 2'b00;
51
+ bitcnt <= 3'd0;
52
+ bytecnt <= 8'd0;
53
+ shin <= 8'd0;
54
+ shout <= 8'd0;
55
+ reading <= 1'b0;
56
+ frame_ok <= 1'b0;
57
+ miso <= 1'b0;
58
+ rx_buf <= {16*N{1'b0}};
59
+ tx_buf <= {16*N{1'b0}};
60
+ rx_words <= {16*N{1'b0}};
61
+ rx_valid <= 1'b0;
62
+ end else begin
63
+ sclk_s <= {sclk_s[1:0], sclk};
64
+ cs_s <= {cs_s[1:0], cs_n};
65
+ mosi_s <= {mosi_s[0], mosi};
66
+ rx_valid <= 1'b0;
67
+ if (!cs_active) begin
68
+ bitcnt <= 3'd0;
69
+ bytecnt <= 8'd0;
70
+ reading <= 1'b0;
71
+ shout <= 8'd0;
72
+ miso <= 1'b0;
73
+ end else begin
74
+ if (cs_start) begin
75
+ tx_buf <= tx_words;
76
+ end
77
+ if (sclk_rise) begin
78
+ shin <= byte_in;
79
+ bitcnt <= bitcnt + 3'd1;
80
+ if (bitcnt == 3'd7) begin
81
+ bytecnt <= bytecnt + 8'd1;
82
+ if (bytecnt == 8'd0) begin
83
+ frame_ok <= (byte_in == 8'hA5);
84
+ reading <= (byte_in == 8'h5A);
85
+ shout <= (byte_in == 8'h5A) ? 8'hA5 : 8'h00;
86
+ end else if (reading) begin
87
+ if (tx_index < 2*N)
88
+ shout <= tx_buf[16*N-1 - 8*tx_index -: 8];
89
+ else
90
+ shout <= 8'h00;
91
+ end else if (bytecnt == 8'd1) begin
92
+ if (byte_in != N) frame_ok <= 1'b0;
93
+ end else if (bytecnt < 2*N + 2) begin
94
+ rx_buf[16*N-1 - 8*(bytecnt - 8'd2) -: 8] <= byte_in;
95
+ if (bytecnt == 2*N + 1 && frame_ok) begin
96
+ rx_words <= {rx_buf[16*N-1:8], byte_in};
97
+ rx_valid <= 1'b1;
98
+ end
99
+ end
100
+ end
101
+ end
102
+ if (sclk_fall) begin
103
+ miso <= shout[7];
104
+ shout <= {shout[6:0], 1'b0};
105
+ end
106
+ end
107
+ end
108
+ end
109
+ endmodule
110
+ `default_nettype wire
nlcl/modules/_assets/nlcl_runtime.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """NLCL Python runtime (stdlib only; pyserial / paho-mqtt used if installed).
2
+
3
+ Provides: Entity base class, World scheduler (ticks, timers, change detection),
4
+ transports for cross-module channels (local, HTTP hub, serial, MQTT, UDP) and
5
+ a tiny HTTP hub with a live dashboard page. Generated by NLCL.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import random
12
+ import re
13
+ import socket
14
+ import sys
15
+ import threading
16
+ import time
17
+ import urllib.request
18
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
+
20
+
21
+ # ---------------------------------------------------------------- entities
22
+ class Entity:
23
+ kind = "object"
24
+ props: tuple = ()
25
+ aliases: dict = {} # property name -> python attribute (when it clashes with a method)
26
+
27
+ def __init__(self, world, name):
28
+ self.world = world
29
+ self.name = name
30
+ self.alive = True
31
+ self._timers = [] # [interval_ms, next_due, fn]
32
+ self._last = {}
33
+ self._edges = {}
34
+ self._mirrored = set() # fields received from other entities
35
+
36
+ def _attr(self, prop):
37
+ return self.aliases.get(prop, prop)
38
+
39
+ def get(self, prop, default=None):
40
+ return getattr(self, self._attr(prop), default)
41
+
42
+ def changed(self, key, value):
43
+ """True when a watched value (e.g. another entity's property) differs from last tick."""
44
+ prev = self._edges.get(("chg", key), value)
45
+ self._edges[("chg", key)] = value
46
+ return value != prev
47
+
48
+ def rising(self, key, value):
49
+ """True only when `value` turns true (edge-triggered "when ..." behaviours)."""
50
+ prev = self._edges.get(key, False)
51
+ self._edges[key] = bool(value)
52
+ return bool(value) and not prev
53
+
54
+ def every(self, ms, fn):
55
+ self._timers.append([ms, time.monotonic() + ms / 1000.0, fn])
56
+
57
+ def state(self):
58
+ return {p: getattr(self, self._attr(p), None) for p in self.props}
59
+
60
+ def _watch(self):
61
+ """Values watched for "when <prop> changes": own properties + mirrored remote fields."""
62
+ cur = self.state()
63
+ for k in self._mirrored:
64
+ cur.setdefault(k, self.get(k))
65
+ return cur
66
+
67
+ def log(self, text):
68
+ def sub(m):
69
+ key = m.group(1)
70
+ v = self.get(key)
71
+ if v is None or callable(v):
72
+ v = self.world.latest(key)
73
+ return m.group(0) if v is None else str(v)
74
+ print(f"[{self.name}] " + re.sub(r"\{(\w+)\}", sub, str(text)), flush=True)
75
+
76
+ def destroy(self):
77
+ self.alive = False
78
+ self.world.destroy(self)
79
+
80
+ def move(self, dx, dy, dz):
81
+ pos = list(getattr(self, "position", [0, 0, 0]) or [0, 0, 0])
82
+ pos = (pos + [0, 0, 0])[:3]
83
+ self.position = [pos[0] + dx, pos[1] + dy, pos[2] + dz]
84
+
85
+ def send(self, to=None, fields=None):
86
+ self.world.send(self, to, fields)
87
+
88
+ def rotation(self):
89
+ """Orientation in degrees [x, y, z]: angle_x / angle_y / angle (rotation about z)."""
90
+ return [float(getattr(self, self._attr(p), 0) or 0) % 360 for p in ("angle_x", "angle_y", "angle")]
91
+
92
+ # hooks overridden by generated code
93
+ def on_start(self): pass
94
+ def on_update(self, dt): pass
95
+ def on_change(self, prop): pass
96
+ def on_message(self, sender, msg): pass
97
+ def on_collision(self, other): pass
98
+ def on_input(self, key): pass
99
+
100
+
101
+ # ---------------------------------------------------------------- world
102
+ class World:
103
+ def __init__(self, simulate=False, verbose=True):
104
+ self.entities = {}
105
+ self.channels = []
106
+ self.remote = {} # (entity, field) -> last value from another module
107
+ self._latest = {} # field -> last value from any module
108
+ self.simulate = simulate
109
+ self.verbose = verbose
110
+ self.running = False
111
+ self._lock = threading.RLock() # re-entrant: behaviours may send() while the loop holds it
112
+
113
+ def add(self, e):
114
+ self.entities[e.name] = e
115
+ return e
116
+
117
+ def __getitem__(self, name):
118
+ return self.entities[name]
119
+
120
+ def get_remote(self, entity, field, default=0):
121
+ e = self.entities.get(entity)
122
+ if e is not None and hasattr(e, e._attr(field)):
123
+ return e.get(field)
124
+ if (entity, field) in self.remote:
125
+ return self.remote[(entity, field)]
126
+ # data often arrives via the parent board's link (node.temperature for sensor temp)
127
+ return self._latest.get(field, default)
128
+
129
+ def set_remote(self, entity, field, value):
130
+ """Assign a property of another entity (local object, else the cached remote value)."""
131
+ e = self.entities.get(entity)
132
+ if e is not None:
133
+ setattr(e, e._attr(field), value)
134
+ else:
135
+ self.remote[(entity, field)] = value
136
+
137
+ def latest(self, field):
138
+ """Most recent value of `field` received from any other module (or None)."""
139
+ return self._latest.get(field)
140
+
141
+ def collide(self, a, b):
142
+ """Report a contact between two entities (no physics here: call it from your own code
143
+ or a channel handler). Both sides' on_collision run; each filters by name/kind."""
144
+ a = self.entities.get(a, a) if isinstance(a, str) else a
145
+ b = self.entities.get(b, b) if isinstance(b, str) else b
146
+ if isinstance(a, str) or isinstance(b, str):
147
+ return
148
+ with self._lock:
149
+ if a.alive:
150
+ a.on_collision(b)
151
+ if b.alive:
152
+ b.on_collision(a)
153
+
154
+ def destroy(self, e):
155
+ self.entities.pop(e.name, None)
156
+ if self.verbose:
157
+ print(f"[world] {e.name} destroyed", flush=True)
158
+
159
+ # ---- channels
160
+ def channel(self, ch):
161
+ self.channels.append(ch)
162
+ ch.world = self
163
+ return ch
164
+
165
+ def send(self, sender, to=None, fields=None):
166
+ for ch in self.channels:
167
+ if ch.src != sender.name:
168
+ continue
169
+ if to and to not in (ch.dst, ch.id):
170
+ continue
171
+ payload = {f: sender.get(f, self.remote.get((sender.name, f))) for f in (fields or ch.fields)}
172
+ ch.emit(payload)
173
+
174
+ def deliver(self, ch, payload):
175
+ """Called by transports when a message for channel ch arrives."""
176
+ with self._lock:
177
+ for k, v in payload.items():
178
+ if k in ("channel", "from"):
179
+ continue
180
+ if v is None:
181
+ continue
182
+ self.remote[(ch.src, k)] = v
183
+ self._latest[k] = v
184
+ dst = self.entities.get(ch.dst)
185
+ if dst is not None:
186
+ for k, v in payload.items():
187
+ if k in ("channel", "from") or v is None:
188
+ continue
189
+ # own properties and fields this entity already mirrors are refreshed;
190
+ # a field never seen before becomes a mirrored attribute
191
+ if k in dst.props or k in dst._mirrored or not hasattr(dst, dst._attr(k)):
192
+ setattr(dst, dst._attr(k), v)
193
+ if k not in dst.props:
194
+ dst._mirrored.add(k)
195
+ dst.on_message(ch.src, payload)
196
+
197
+ # ---- main loop
198
+ def run(self, seconds=None, ticks=None, dt=0.1):
199
+ self.running = True
200
+ for ch in self.channels:
201
+ ch.start()
202
+ for e in list(self.entities.values()):
203
+ e._last = e._watch()
204
+ e.on_start()
205
+ n = 0
206
+ t_end = time.monotonic() + seconds if seconds else None
207
+ try:
208
+ while self.running:
209
+ now = time.monotonic()
210
+ with self._lock:
211
+ for e in list(self.entities.values()):
212
+ if not e.alive:
213
+ continue
214
+ for t in e._timers:
215
+ if now >= t[1]:
216
+ t[1] = now + t[0] / 1000.0
217
+ t[2]()
218
+ if not e.alive:
219
+ continue
220
+ e.on_update(dt)
221
+ if not e.alive:
222
+ continue
223
+ cur = e._watch()
224
+ for k, v in cur.items():
225
+ if e._last.get(k) != v:
226
+ e.on_change(k)
227
+ e._last = cur
228
+ for ch in self.channels:
229
+ ch.tick(now)
230
+ n += 1
231
+ if ticks and n >= ticks:
232
+ break
233
+ if t_end and now >= t_end:
234
+ break
235
+ time.sleep(dt)
236
+ except KeyboardInterrupt:
237
+ pass
238
+ finally:
239
+ self.running = False
240
+ for ch in self.channels:
241
+ ch.stop()
242
+
243
+
244
+ # ---------------------------------------------------------------- channels
245
+ class Channel:
246
+ """Base transport. src/dst are entity names; fields carried src -> dst."""
247
+ def __init__(self, id, src, dst, fields, interval_ms=1000, local_src=False, local_dst=False, **cfg):
248
+ self.id, self.src, self.dst, self.fields = id, src, dst, list(fields)
249
+ self.interval = interval_ms / 1000.0
250
+ self.local_src, self.local_dst = local_src, local_dst
251
+ self.cfg = cfg
252
+ self.world = None
253
+ self._next = 0.0
254
+
255
+ def start(self): pass
256
+ def stop(self): pass
257
+
258
+ def tick(self, now):
259
+ # periodic auto-publish when the sender lives in this python process
260
+ if self.local_src and now >= self._next:
261
+ self._next = now + self.interval
262
+ e = self.world.entities.get(self.src)
263
+ if e is not None:
264
+ # forward own value, else the latest value this process received for that field
265
+ payload = {f: e.get(f) if e.get(f) is not None else self.world.latest(f)
266
+ for f in self.fields}
267
+ if any(v is not None for v in payload.values()):
268
+ self.emit(payload)
269
+ elif not self.local_src and self.world.simulate and now >= self._next:
270
+ # simulation: invent plausible sensor data for the remote sender
271
+ self._next = now + self.interval
272
+ types, enums = self.cfg.get("types") or {}, self.cfg.get("enums") or {}
273
+ self.receive({f: _fake(self.world, self.src, f, types.get(f), enums.get(f)) for f in self.fields})
274
+
275
+ def publish(self, payload):
276
+ raise NotImplementedError
277
+
278
+ def emit(self, payload):
279
+ """Publish; when both ends live in this process, also deliver directly
280
+ (a python->python link must work without a hub/broker/serial loopback)."""
281
+ self.publish(payload)
282
+ if self.local_dst and self.local_src and not isinstance(self, LocalChannel):
283
+ self.world.deliver(self, payload)
284
+
285
+ def receive(self, payload):
286
+ # enum fields (e.g. an FSM state) may arrive as their integer code: decode to the name
287
+ for f, names in (self.cfg.get("enums") or {}).items():
288
+ v = payload.get(f)
289
+ if isinstance(v, (int, float)) and not isinstance(v, bool) and 0 <= int(v) < len(names):
290
+ payload[f] = names[int(v)]
291
+ self.world.deliver(self, payload)
292
+
293
+ def envelope(self, payload):
294
+ return dict({"channel": self.id, "from": self.src}, **payload)
295
+
296
+
297
+ def _fake(world, src, field, ftype=None, enum=None):
298
+ prev = world.remote.get((src, field))
299
+ base = {"temperature": 24.0, "humidity": 45.0, "distance": 100.0, "light": 300.0,
300
+ "pressure": 1013.0, "voltage": 3.3}.get(field, 10.0)
301
+ if enum:
302
+ return random.choice(list(enum))
303
+ if ftype == "bool" or isinstance(prev, bool):
304
+ return random.random() < 0.5
305
+ if ftype == "int":
306
+ return int((prev if isinstance(prev, (int, float)) else base) + random.choice((-1, 0, 1)))
307
+ if ftype == "string":
308
+ return prev if isinstance(prev, str) else ""
309
+ v = (prev if isinstance(prev, (int, float)) else base) + random.uniform(-1, 1)
310
+ return round(v, 2)
311
+
312
+
313
+ class LocalChannel(Channel):
314
+ def publish(self, payload):
315
+ self.world.deliver(self, payload)
316
+ if self.world.verbose:
317
+ print(f"[{self.id}] {payload}", flush=True)
318
+
319
+
320
+ class HubChannel(Channel):
321
+ """HTTP: POST/GET JSON on a NLCL hub (see Hub below)."""
322
+ def __init__(self, *a, hub_url="http://localhost:8765", path=None, **kw):
323
+ super().__init__(*a, **kw)
324
+ self.url = hub_url.rstrip("/") + (path or f"/channel/{self.id}")
325
+ self._seen = None
326
+ self._poll_next = 0.0
327
+
328
+ def publish(self, payload):
329
+ if self.world.simulate and not self.cfg.get("force_net"):
330
+ if self.world.verbose:
331
+ print(f"[{self.id}] (simulated http) {payload}", flush=True)
332
+ return
333
+ data = json.dumps(self.envelope(payload)).encode()
334
+ try:
335
+ urllib.request.urlopen(urllib.request.Request(self.url, data, {"Content-Type": "application/json"}), timeout=2).read()
336
+ if self.world.verbose:
337
+ print(f"[{self.id}] -> hub {payload}", flush=True)
338
+ except OSError as e:
339
+ if self.world.verbose:
340
+ print(f"[{self.id}] hub unreachable ({e}); payload {payload}", flush=True)
341
+
342
+ def tick(self, now):
343
+ super().tick(now)
344
+ if not self.local_src and not self.world.simulate and now >= self._poll_next:
345
+ self._poll_next = now + max(0.2, self.interval / 2)
346
+ try:
347
+ msg = json.loads(urllib.request.urlopen(self.url, timeout=2).read() or b"{}")
348
+ except (OSError, ValueError):
349
+ return
350
+ stamp = msg.get("_t")
351
+ if msg and stamp != self._seen:
352
+ self._seen = stamp
353
+ self.receive({k: v for k, v in msg.items() if not k.startswith("_")})
354
+
355
+
356
+ class SerialChannel(Channel):
357
+ """Newline-delimited JSON over a serial port (pyserial). Falls back to simulation."""
358
+ def __init__(self, *a, baud=115200, port="auto", **kw):
359
+ super().__init__(*a, **kw)
360
+ self.baud, self.port, self.ser = baud, port, None
361
+
362
+ def start(self):
363
+ if self.world.simulate:
364
+ return
365
+ try:
366
+ import serial
367
+ import serial.tools.list_ports
368
+ except ImportError:
369
+ print(f"[{self.id}] pyserial not installed (pip install pyserial) -> simulating", flush=True)
370
+ self.world.simulate = True
371
+ return
372
+ port = os.environ.get("NLCL_SERIAL_PORT") or (None if self.port == "auto" else self.port)
373
+ if not port:
374
+ ports = [p.device for p in serial.tools.list_ports.comports()]
375
+ port = ports[0] if ports else None
376
+ if not port:
377
+ print(f"[{self.id}] no serial port found -> simulating", flush=True)
378
+ self.world.simulate = True
379
+ return
380
+ self.ser = serial.Serial(port, self.baud, timeout=0.05)
381
+ print(f"[{self.id}] serial {port} @ {self.baud}", flush=True)
382
+ threading.Thread(target=self._reader, daemon=True).start()
383
+
384
+ def _reader(self):
385
+ buf = b""
386
+ while self.world.running and self.ser:
387
+ try:
388
+ buf += self.ser.read(256)
389
+ except Exception:
390
+ break
391
+ while b"\n" in buf:
392
+ line, buf = buf.split(b"\n", 1)
393
+ try:
394
+ msg = json.loads(line.decode("utf-8", "replace"))
395
+ except ValueError:
396
+ continue
397
+ if msg.get("channel", self.id) == self.id:
398
+ self.receive({k: v for k, v in msg.items() if k not in ("channel", "from")})
399
+
400
+ def publish(self, payload):
401
+ line = json.dumps(self.envelope(payload)) + "\n"
402
+ if self.ser:
403
+ self.ser.write(line.encode())
404
+ elif self.world.verbose:
405
+ print(f"[{self.id}] (serial) {line.strip()}", flush=True)
406
+
407
+ def stop(self):
408
+ if self.ser:
409
+ self.ser.close()
410
+
411
+
412
+ class MqttChannel(Channel):
413
+ def __init__(self, *a, broker="broker.hivemq.com", broker_port=1883, topic=None, **kw):
414
+ super().__init__(*a, **kw)
415
+ self.broker, self.bport, self.topic = broker, broker_port, topic or f"nlcl/{self.id}"
416
+ self.client = None
417
+
418
+ def start(self):
419
+ if self.world.simulate:
420
+ return
421
+ try:
422
+ import paho.mqtt.client as mqtt
423
+ except ImportError:
424
+ print(f"[{self.id}] paho-mqtt not installed (pip install paho-mqtt) -> simulating", flush=True)
425
+ self.world.simulate = True
426
+ return
427
+ try:
428
+ c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) if hasattr(mqtt, "CallbackAPIVersion") else mqtt.Client()
429
+ c.on_message = lambda cl, ud, m: self._on(m.payload)
430
+ c.connect(self.broker, self.bport, 30)
431
+ if not self.local_src:
432
+ c.subscribe(self.topic)
433
+ c.loop_start()
434
+ self.client = c
435
+ print(f"[{self.id}] mqtt {self.broker}:{self.bport} topic {self.topic}", flush=True)
436
+ except OSError as e:
437
+ print(f"[{self.id}] mqtt broker unreachable ({e}) -> simulating", flush=True)
438
+ self.world.simulate = True
439
+
440
+ def _on(self, raw):
441
+ try:
442
+ msg = json.loads(raw)
443
+ except ValueError:
444
+ return
445
+ self.receive({k: v for k, v in msg.items() if k not in ("channel", "from")})
446
+
447
+ def publish(self, payload):
448
+ if self.client:
449
+ self.client.publish(self.topic, json.dumps(self.envelope(payload)))
450
+ elif self.world.verbose:
451
+ print(f"[{self.id}] (mqtt {self.topic}) {payload}", flush=True)
452
+
453
+ def stop(self):
454
+ if self.client:
455
+ self.client.loop_stop()
456
+
457
+
458
+ class UdpChannel(Channel):
459
+ def __init__(self, *a, port=9876, host="127.0.0.1", **kw):
460
+ super().__init__(*a, **kw)
461
+ self.port, self.host, self.sock = port, host, None
462
+
463
+ def start(self):
464
+ if self.world.simulate:
465
+ return
466
+ self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
467
+ if not self.local_src:
468
+ self.sock.bind(("0.0.0.0", self.port))
469
+ self.sock.settimeout(0.2)
470
+ threading.Thread(target=self._reader, daemon=True).start()
471
+
472
+ def _reader(self):
473
+ while self.world.running:
474
+ try:
475
+ data, _ = self.sock.recvfrom(4096)
476
+ self.receive({k: v for k, v in json.loads(data).items() if k not in ("channel", "from")})
477
+ except (socket.timeout, ValueError, OSError):
478
+ continue
479
+
480
+ def publish(self, payload):
481
+ if self.sock:
482
+ self.sock.sendto(json.dumps(self.envelope(payload)).encode(), (self.host, self.port))
483
+ elif self.world.verbose:
484
+ print(f"[{self.id}] (udp) {payload}", flush=True)
485
+
486
+
487
+ TRANSPORTS = {"local": LocalChannel, "http": HubChannel, "websocket": HubChannel, "serial": SerialChannel,
488
+ "mqtt": MqttChannel, "udp": UdpChannel}
489
+
490
+
491
+ def make_channel(protocol, *a, **kw):
492
+ return TRANSPORTS.get(protocol, LocalChannel)(*a, **kw)
493
+
494
+
495
+ # ---------------------------------------------------------------- hub
496
+ class Hub:
497
+ """Tiny HTTP message hub + live dashboard. GET/POST /channel/<id>, GET /state, GET /."""
498
+ def __init__(self, port=8765):
499
+ self.port = port
500
+ self.data = {}
501
+ self.server = None
502
+
503
+ def start(self):
504
+ hub = self
505
+
506
+ class H(BaseHTTPRequestHandler):
507
+ def log_message(self, *a):
508
+ pass
509
+
510
+ def _send(self, code, body, ctype="application/json"):
511
+ b = body if isinstance(body, bytes) else body.encode()
512
+ self.send_response(code)
513
+ self.send_header("Content-Type", ctype)
514
+ self.send_header("Access-Control-Allow-Origin", "*")
515
+ self.send_header("Access-Control-Allow-Headers", "Content-Type")
516
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
517
+ self.send_header("Access-Control-Allow-Private-Network", "true")
518
+ self.send_header("Content-Length", str(len(b)))
519
+ self.end_headers()
520
+ self.wfile.write(b)
521
+
522
+ def do_OPTIONS(self):
523
+ self._send(204, b"")
524
+
525
+ def do_GET(self):
526
+ if self.path.startswith("/channel/"):
527
+ self._send(200, json.dumps(hub.data.get(self.path.split("/", 2)[2], {})))
528
+ elif self.path == "/state":
529
+ self._send(200, json.dumps(hub.data))
530
+ else:
531
+ self._send(200, DASHBOARD_HTML, "text/html; charset=utf-8")
532
+
533
+ def do_POST(self):
534
+ if not self.path.startswith("/channel/"):
535
+ return self._send(404, "{}")
536
+ n = int(self.headers.get("Content-Length") or 0)
537
+ try:
538
+ msg = json.loads(self.rfile.read(n) or b"{}")
539
+ except ValueError:
540
+ return self._send(400, '{"error":"bad json"}')
541
+ msg["_t"] = time.time()
542
+ hub.data[self.path.split("/", 2)[2]] = msg
543
+ self._send(200, '{"ok":true}')
544
+
545
+ try:
546
+ self.server = ThreadingHTTPServer(("0.0.0.0", self.port), H)
547
+ except OSError as e:
548
+ print(f"[hub] port {self.port} busy ({e}); assuming another hub is running", flush=True)
549
+ return False
550
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
551
+ print(f"[hub] http://localhost:{self.port} (live dashboard)", flush=True)
552
+ return True
553
+
554
+ def stop(self):
555
+ if self.server:
556
+ self.server.shutdown()
557
+
558
+
559
+ DASHBOARD_HTML = """<!doctype html><meta charset=utf-8><title>NLCL hub</title>
560
+ <style>body{font:14px system-ui;margin:24px;background:#0f1115;color:#e6e6e6}table{border-collapse:collapse}
561
+ td,th{padding:6px 12px;border-bottom:1px solid #333;text-align:left}th{color:#8ab4f8}</style>
562
+ <h2>NLCL live channels</h2><table id=t><tr><th>channel</th><th>from</th><th>data</th><th>age</th></tr></table>
563
+ <script>
564
+ async function poll(){try{const s=await (await fetch('/state')).json();let h='<tr><th>channel</th><th>from</th><th>data</th><th>age</th></tr>';
565
+ for(const [k,v] of Object.entries(s)){const d=Object.entries(v).filter(([a])=>!['channel','from','_t'].includes(a)).map(([a,b])=>a+'='+JSON.stringify(b)).join(' ');
566
+ h+=`<tr><td>${k}</td><td>${v.from||''}</td><td>${d}</td><td>${(Date.now()/1000-v._t).toFixed(1)}s</td></tr>`}
567
+ document.getElementById('t').innerHTML=h}catch(e){}}setInterval(poll,500);poll();
568
+ </script>"""
569
+
570
+
571
+ def main_args(argv=None):
572
+ import argparse
573
+ p = argparse.ArgumentParser()
574
+ p.add_argument("--seconds", type=float, default=None, help="stop after N seconds")
575
+ p.add_argument("--ticks", type=int, default=None, help="stop after N ticks")
576
+ p.add_argument("--simulate", action="store_true", help="no hardware/network: fake remote data")
577
+ p.add_argument("--no-hub", action="store_true", help="do not start the HTTP hub in-process")
578
+ p.add_argument("--quiet", action="store_true")
579
+ return p.parse_args(argv)
nlcl/modules/app_mod.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Application domain: GUI programs for every operating system.
2
+
3
+ From the same IR this module emits
4
+ * app.py + nlcl_app.py a desktop app (Python + Tkinter, standard library only) that runs on
5
+ Windows, macOS and Linux, with scripts that package it as a native
6
+ executable for each OS (PyInstaller, free);
7
+ * web/ the same app as an installable PWA (HTML + JS, no build step) for
8
+ Android, iOS, ChromeOS and any browser.
9
+ Widgets are entities (button, label, input, checkbox, slider, list ...), a window/app entity is
10
+ the root, behaviours become event handlers, links to other modules go through the NLCL hub.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import sys
16
+ from pathlib import Path
17
+
18
+ from ..ir import Entity, describe_action
19
+ from .base import BuildContext, DomainModule, RunResult
20
+
21
+ ASSETS = Path(__file__).parent / "_assets" / "app"
22
+ ROOT_KINDS = ("app", "application", "window", "dialog", "screen", "page")
23
+ KEYS = {"space", "enter", "return", "escape", "esc", "up", "down", "left", "right", "tab"}
24
+
25
+
26
+ class AppModule(DomainModule):
27
+ name = "app"
28
+ title = "Applications (desktop GUI for Windows/macOS/Linux + installable web app for Android/iOS)"
29
+ aliases = ("application", "desktop", "gui", "ui", "pwa", "mobile")
30
+ keywords = ("app", "application", "window", "dialog", "form", "menu", "widget", "tkinter", "windows",
31
+ "macos", "linux", "android", "ios", "notepad", "calculator", "todo", "checkbox", "textbox",
32
+ "textarea", "dropdown", "slider", "listbox", "screen", "page", "toolbar", "label")
33
+ kinds = {
34
+ "object": {},
35
+ "app": {"title": "", "size": [480, 360]},
36
+ "application": {"title": "", "size": [480, 360]},
37
+ "window": {"title": "", "size": [480, 360]},
38
+ "dialog": {"title": ""},
39
+ "screen": {"title": ""},
40
+ "page": {"title": ""},
41
+ "form": {},
42
+ "panel": {},
43
+ "frame": {},
44
+ "group": {},
45
+ "tab": {},
46
+ "button": {},
47
+ "label": {},
48
+ "slider": {"value": 0, "min": 0, "max": 100},
49
+ "timer": {},
50
+ "title": {},
51
+ "heading": {},
52
+ "input": {"value": ""},
53
+ "textbox": {"value": ""},
54
+ "entry": {"value": ""},
55
+ "field": {"value": ""},
56
+ "password": {"value": ""},
57
+ "textarea": {"value": ""},
58
+ "checkbox": {"checked": False},
59
+ "switch": {"checked": False},
60
+ "dropdown": {"items": [], "value": ""},
61
+ "select": {"items": [], "value": ""},
62
+ "listbox": {"items": []},
63
+ "list": {"items": []},
64
+ "progress": {"value": 0, "max": 100},
65
+ "canvas": {},
66
+ "image": {},
67
+ "store": {},
68
+ "model": {},
69
+ }
70
+ suggested_props = ("title", "text", "value", "size", "items", "checked", "label", "placeholder")
71
+ protocols = ("http",)
72
+ toolchain = """**Desktop (Windows / macOS / Linux)** - free CPython 3.10+ from python.org (Tkinter is included;
73
+ on Debian/Ubuntu: `sudo apt install python3-tk`):
74
+
75
+ python app.py # run the app
76
+ python app.py --selftest # build the UI, fire every event once, print the state, exit
77
+
78
+ Native executable for the OS you are on (free PyInstaller: `pip install pyinstaller`):
79
+
80
+ build_windows.bat # -> dist\\<name>.exe
81
+ ./build_macos.sh # -> dist/<name>.app
82
+ ./build_linux.sh # -> dist/<name> (+ <name>.desktop launcher)
83
+
84
+ **Android / iOS / ChromeOS / any browser** - `web/` is an installable PWA, no build step:
85
+
86
+ python -m http.server 8080 --directory web # then open http://localhost:8080
87
+ (on the phone: open the page -> browser menu -> "Add to Home screen" / "Install app")
88
+ node web/app.js --selftest # logic self-test without a browser"""
89
+
90
+ # ------------------------------------------------------------------ spec
91
+ def _spec(self, ctx: BuildContext) -> dict:
92
+ ids = {e.id: e.ident for e in ctx.entities}
93
+ root = next((e for e in ctx.entities if e.kind in ROOT_KINDS and e.parent not in ids), None)
94
+ title = str((root.props.get("title") if root else "") or (root.name if root else ctx.system.name)).replace("_", " ")
95
+ size = (root.props.get("size") if root else None) or [480, 360]
96
+ if not isinstance(size, list):
97
+ size = [size, 360]
98
+ widgets = []
99
+ for e in ctx.entities:
100
+ props = {k: v for k, v in e.props.items() if not k.startswith("_")}
101
+ parent = ids.get(e.parent)
102
+ if parent is None and root is not None and e.id != root.id and e.kind not in ROOT_KINDS:
103
+ parent = root.ident
104
+ widgets.append({"id": e.ident, "kind": e.kind, "parent": parent, "props": props})
105
+ channels = []
106
+ for c in ctx.channels:
107
+ url = c.config.get("hub_url", "http://localhost:8765") + c.config.get("path", f"/channel/{c.id}")
108
+ if c.src.domain == self.name and c.dst.domain == self.name:
109
+ continue # both ends in this app: state is shared already
110
+ channels.append({"id": c.id, "dir": "out" if c.src.domain == self.name else "in",
111
+ "src": c.src.ident, "dst": c.dst.ident, "fields": list(c.fields), "url": url,
112
+ "interval_ms": int(c.config.get("interval_ms", 1000) or 1000)})
113
+ return {"title": title.strip() or "NLCL app", "size": size, "widgets": widgets, "channels": channels}
114
+
115
+ # ------------------------------------------------------------------ handlers
116
+ def _handlers(self, ctx: BuildContext, lang: str) -> tuple[dict, set[str], list[str]]:
117
+ """-> ({group: entries}, call names, notes). Entries are source snippets."""
118
+ local = {e.ident for e in ctx.entities}
119
+ H: dict = {"start": [], "update": [], "timers": [], "click": {}, "key": {}, "change": {}, "message": {}}
120
+ calls: set[str] = set()
121
+ notes: list[str] = []
122
+ n = 0
123
+ for e in ctx.entities:
124
+ for b in e.behaviors or []:
125
+ if not isinstance(b, dict) or not b.get("do"):
126
+ continue
127
+ n += 1
128
+ on = str(b.get("on") or "update")
129
+ kind, _, arg = on.partition(":")
130
+ name = self._namer(e, lang)
131
+ cond = self.expr(b["if"], "python" if lang == "py" else "js", name) if b.get("if") else None
132
+ acts = []
133
+ for a in b["do"]:
134
+ acts += self._action(e, a, lang, name, calls)
135
+ edge = None
136
+ if kind == "update" and cond:
137
+ edge = f"{e.ident}_{n}" # "when x is above 5, ..." fires once when it becomes true
138
+ fn = self._fn(e, cond, acts, lang, edge, on)
139
+ if kind == "start":
140
+ H["start"].append((e.ident, fn))
141
+ elif kind == "update":
142
+ H["update"].append((e.ident, fn))
143
+ elif kind == "timer":
144
+ try:
145
+ ms = max(10, int(float(arg)))
146
+ except ValueError:
147
+ ms = 1000
148
+ H["timers"].append((e.ident, ms, fn))
149
+ elif kind == "input":
150
+ key = arg.strip().lower().replace(" ", "_")
151
+ if key in ("click", "mouse", "tap", "touch", "clicked", "it", "self"):
152
+ H["click"].setdefault(e.ident, []).append((e.ident, fn))
153
+ elif key in local and key not in KEYS:
154
+ H["click"].setdefault(key, []).append((e.ident, fn))
155
+ else:
156
+ H["key"].setdefault({"return": "enter", "esc": "escape"}.get(key, key), []).append((e.ident, fn))
157
+ elif kind == "change":
158
+ ent, _, prop = arg.rpartition(".")
159
+ H["change"].setdefault((ent or e.ident, prop), []).append((e.ident, fn))
160
+ elif kind == "message":
161
+ H["message"].setdefault(arg or "any", []).append((e.ident, fn))
162
+ else:
163
+ notes.append(f"{e.name}: '{on}' has no meaning in a GUI app and was skipped")
164
+ return H, calls, notes
165
+
166
+ @staticmethod
167
+ def _namer(e: Entity, lang: str):
168
+ def f(n: str) -> str:
169
+ if "." in n:
170
+ ent, prop = n.split(".", 1)
171
+ return f"app.get({ent!r}, {prop!r})" if lang == "py" else f"app.get({json.dumps(ent)}, {json.dumps(prop)})"
172
+ return f"app.get({e.ident!r}, {n!r})" if lang == "py" else f"app.get({json.dumps(e.ident)}, {json.dumps(n)})"
173
+ return f
174
+
175
+ def _action(self, e: Entity, a: dict, lang: str, name, calls: set[str]) -> list[str]:
176
+ q = (lambda s: repr(s)) if lang == "py" else (lambda s: json.dumps(s, ensure_ascii=False))
177
+ ex = lambda v: self.expr(v, "python" if lang == "py" else "js", name) # noqa: E731
178
+ end = "" if lang == "py" else ";"
179
+ o, op = q(e.ident), a.get("op")
180
+ try:
181
+ if op == "set":
182
+ return [f"app.set({o}, {q(a['prop'])}, {ex(a['value'])}){end}"]
183
+ if op == "add":
184
+ return [f"app.add({o}, {q(a['prop'])}, {ex(a['value'])}){end}"]
185
+ if op == "toggle":
186
+ return [f"app.toggle({o}, {q(a['prop'])}){end}"]
187
+ if op == "destroy":
188
+ return [f"app.hide({o}){end}"]
189
+ if op == "log":
190
+ return [f"app.log({o}, {q(a.get('text', ''))}){end}"]
191
+ if op == "send":
192
+ none = "None" if lang == "py" else "null"
193
+ return [f"app.send({o}, {q(a['to']) if a.get('to') else none}, {q(list(a.get('fields') or []))}){end}"]
194
+ if op == "call":
195
+ calls.add(str(a["name"]))
196
+ args = "".join(", " + ex(x) for x in a.get("args", []))
197
+ return [f"app.call({o}, {q(a['name'])}{args}){end}"]
198
+ except Exception:
199
+ pass
200
+ text = describe_action(a) if isinstance(a, dict) and a.get("op") in ("move",) else str(a.get("op"))
201
+ return [("pass # " if lang == "py" else "/* ") + f"'{text}' is not meaningful in a GUI app" + ("" if lang == "py" else " */")]
202
+
203
+ @staticmethod
204
+ def _fn(e: Entity, cond: str | None, acts: list[str], lang: str, edge: str | None, on: str) -> list[str]:
205
+ """Body lines of one handler (no def line)."""
206
+ body = []
207
+ if cond and edge:
208
+ body.append(f"if not app.edge({edge!r}, {cond}): return" if lang == "py"
209
+ else f"if (!app.edge({json.dumps(edge)}, {cond})) return;")
210
+ elif cond:
211
+ body.append(f"if not ({cond}): return" if lang == "py" else f"if (!({cond})) return;")
212
+ return body + (acts or (["pass"] if lang == "py" else []))
213
+
214
+ # ------------------------------------------------------------------ python
215
+ def _py(self, ctx: BuildContext, spec: dict) -> str:
216
+ H, calls, notes = self._handlers(ctx, "py")
217
+ L = ["#!/usr/bin/env python3",
218
+ f'"""{spec["title"]} - desktop application (Windows / macOS / Linux). Generated by NLCL; edit freely."""',
219
+ "from nlcl_app import main", "",
220
+ "SPEC = " + _pyrepr(spec), ""]
221
+ L += [f"# note: {n}" for n in notes]
222
+ defs: list[str] = []
223
+ counter = [0]
224
+
225
+ def reg(owner, body, comment):
226
+ counter[0] += 1
227
+ fname = f"h{counter[0]}_{owner}"
228
+ defs.extend([f"def {fname}(app): # {comment}"] + [" " + ln for ln in body] + ["", ""])
229
+ return f"({owner!r}, {fname})"
230
+ groups = {"start": [reg(o, b, "on start") for o, b in H["start"]],
231
+ "update": [reg(o, b, "every tick") for o, b in H["update"]]}
232
+ timers = []
233
+ for o, ms, b in H["timers"]:
234
+ counter[0] += 1
235
+ fname = f"h{counter[0]}_{o}"
236
+ defs.extend([f"def {fname}(app): # every {ms} ms"] + [" " + ln for ln in b] + ["", ""])
237
+ timers.append(f"({o!r}, {ms}, {fname})")
238
+ maps = {}
239
+ for g in ("click", "key", "message"):
240
+ maps[g] = {k: [reg(o, b, f"{g} {k}") for o, b in v] for k, v in H[g].items()}
241
+ change = {k: [reg(o, b, f"when {k[0]}.{k[1]} changes") for o, b in v] for k, v in H["change"].items()}
242
+ L += defs
243
+ L += ["HANDLERS = {",
244
+ f" 'start': [{', '.join(groups['start'])}],",
245
+ f" 'update': [{', '.join(groups['update'])}],",
246
+ f" 'timers': [{', '.join(timers)}],"]
247
+ for g in ("click", "key", "message"):
248
+ L.append(f" {g!r}: {{" + ", ".join(f"{k!r}: [{', '.join(v)}]" for k, v in maps[g].items()) + "},")
249
+ L.append(" 'change': {" + ", ".join(f"{k!r}: [{', '.join(v)}]" for k, v in change.items()) + "},")
250
+ L += ["}", "", "# Your own functions for 'call <name>' actions: name -> function(app, owner, *args)",
251
+ "CALLS = {"]
252
+ for c in sorted(calls):
253
+ L.append(f" # {c!r}: lambda app, owner, *args: app.log(owner, {c + ' done'!r}),")
254
+ L += ["}", "", "", "if __name__ == '__main__':", " main(SPEC, HANDLERS, CALLS)", ""]
255
+ return "\n".join(L)
256
+
257
+ # ------------------------------------------------------------------ javascript
258
+ def _js(self, ctx: BuildContext, spec: dict) -> str:
259
+ H, calls, notes = self._handlers(ctx, "js")
260
+
261
+ def fn(body):
262
+ return "(app) => { " + " ".join(body) + " }"
263
+
264
+ def pairs(lst):
265
+ return "[" + ", ".join(f"[{json.dumps(o)}, {fn(b)}]" for o, b in lst) + "]"
266
+ L = [(ASSETS / "app_runtime.js").read_text(encoding="utf-8").rstrip(), "",
267
+ "// ---------------------------------------------------------------- generated by NLCL",
268
+ "const SPEC = " + json.dumps(spec, ensure_ascii=False, indent=1) + ";"]
269
+ L += [f"// note: {n}" for n in notes]
270
+ L += ["const HANDLERS = {",
271
+ f" start: {pairs(H['start'])},",
272
+ f" update: {pairs(H['update'])},",
273
+ " timers: [" + ", ".join(f"[{json.dumps(o)}, {ms}, {fn(b)}]" for o, ms, b in H["timers"]) + "],"]
274
+ for g in ("click", "key", "message"):
275
+ L.append(f" {g}: {{" + ", ".join(f"{json.dumps(k)}: {pairs(v)}" for k, v in H[g].items()) + "},")
276
+ L.append(" change: {" + ", ".join(f"{json.dumps(k[0] + '.' + k[1])}: {pairs(v)}" for k, v in H["change"].items()) + "},")
277
+ L += ["};", "// Your own functions for 'call <name>' actions: name -> (app, owner, ...args) => {}",
278
+ "const CALLS = {" + "".join(f"\n // {json.dumps(c)}: (app, owner, ...args) => app.log(owner, {json.dumps(c + ' done')})," for c in sorted(calls)) + "\n};",
279
+ "if (typeof document !== 'undefined') {",
280
+ " const app = new NlclApp(SPEC, HANDLERS, CALLS); window.app = app; app.mainloop();",
281
+ " if ('serviceWorker' in navigator && location.protocol.startsWith('http')) navigator.serviceWorker.register('sw.js').catch(() => {});",
282
+ "} else if (typeof process !== 'undefined' && process.argv.includes('--selftest')) {",
283
+ " new NlclApp(SPEC, HANDLERS, CALLS, null).selftest();",
284
+ "}", ""]
285
+ return "\n".join(L)
286
+
287
+ # ------------------------------------------------------------------ build
288
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
289
+ spec = self._spec(ctx)
290
+ slug = self.ident(spec["title"]) or "app"
291
+ title = spec["title"]
292
+ files = {
293
+ "nlcl_app.py": (ASSETS / "nlcl_app.py").read_text(encoding="utf-8"),
294
+ "app.py": self._py(ctx, spec),
295
+ "web/app.js": self._js(ctx, spec),
296
+ "web/index.html": _INDEX.replace("{title}", _html(title)),
297
+ "web/manifest.webmanifest": json.dumps({
298
+ "name": title, "short_name": title[:12], "start_url": ".", "display": "standalone",
299
+ "background_color": "#ffffff", "theme_color": "#2563eb",
300
+ "icons": [{"src": "icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any maskable"}]}, indent=1),
301
+ "web/sw.js": _SW,
302
+ "web/icon.svg": _ICON.replace("{letter}", _html((title[:1] or "N").upper())),
303
+ "build_windows.bat": f"@echo off\r\nrem Native Windows executable (free): pip install pyinstaller\r\n"
304
+ f"python -m PyInstaller --noconfirm --onefile --windowed --name {slug} app.py\r\n"
305
+ f"echo Done: dist\\{slug}.exe\r\n",
306
+ "build_macos.sh": f"#!/bin/sh\n# Native macOS app bundle (free): pip3 install pyinstaller\nset -e\n"
307
+ f"python3 -m PyInstaller --noconfirm --windowed --name {slug} app.py\n"
308
+ f"echo \"Done: dist/{slug}.app\"\n",
309
+ "build_linux.sh": f"#!/bin/sh\n# Native Linux executable (free): pip3 install pyinstaller ; needs python3-tk\nset -e\n"
310
+ f"python3 -m PyInstaller --noconfirm --onefile --name {slug} app.py\n"
311
+ f"cat > {slug}.desktop <<EOF\n[Desktop Entry]\nType=Application\nName={title}\n"
312
+ f"Exec=$(pwd)/dist/{slug}\nTerminal=false\nCategories=Utility;\nEOF\n"
313
+ f"echo \"Done: dist/{slug} and {slug}.desktop\"\n",
314
+ "README.md": f"# {title}\n\nGenerated by NLCL - one description, every operating system.\n\n"
315
+ + self.toolchain + "\n\n## Widgets\n\n"
316
+ + "\n".join(f"- `{w['id']}` ({w['kind']})" + (f" in `{w['parent']}`" if w["parent"] else "")
317
+ for w in spec["widgets"]) + "\n",
318
+ }
319
+ return files
320
+
321
+ def validate(self, entity: Entity) -> list[str]:
322
+ out = []
323
+ if entity.kind in ("dropdown", "select", "list", "listbox") and not isinstance(entity.props.get("items", []), list):
324
+ out.append("items should be a list, e.g. 'with items red, green and blue'")
325
+ return out
326
+
327
+ def prompt_for(self, entity: Entity) -> str | None:
328
+ if entity.kind in ROOT_KINDS:
329
+ return f"What should {entity.name} contain? (e.g. 'add a button called ok with text \"OK\" to {entity.name}')"
330
+ return None
331
+
332
+ def run(self, ctx: BuildContext) -> RunResult | None:
333
+ out, ok = [], True
334
+ r = self.sh([sys.executable, "-u", "app.py", "--selftest"], ctx.outdir, timeout=30)
335
+ ok &= r.ok and "SELFTEST OK" in r.output
336
+ out.append("desktop (python app.py --selftest): " + ("OK" if r.ok and "SELFTEST OK" in r.output else "FAILED"))
337
+ out += [" " + ln[:300] for ln in r.output.splitlines()[-8:]]
338
+ node = self.which("node")
339
+ if node:
340
+ r2 = self.sh([node, "web/app.js", "--selftest"], ctx.outdir, timeout=30)
341
+ good = r2.ok and "SELFTEST OK" in r2.output
342
+ ok &= good
343
+ out.append("web/PWA (node web/app.js --selftest): " + ("OK" if good else "FAILED"))
344
+ if not good:
345
+ out += [" " + ln[:300] for ln in r2.output.splitlines()[-8:]]
346
+ out.append(f"start it: python {ctx.outdir / 'app.py'}")
347
+ return RunResult(ok, "\n".join(out), "app self-test")
348
+
349
+
350
+ def _pyrepr(obj) -> str:
351
+ """JSON-like Python literal (True/False/None) with indentation."""
352
+ return json.dumps(obj, ensure_ascii=False, indent=1).replace(": true", ": True").replace(": false", ": False") \
353
+ .replace(": null", ": None").replace("[true", "[True").replace("[false", "[False") \
354
+ .replace(", true", ", True").replace(", false", ", False")
355
+
356
+
357
+ def _html(s: str) -> str:
358
+ return str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace('"', "&quot;")
359
+
360
+
361
+ _INDEX = """<!doctype html>
362
+ <html lang="en">
363
+ <head>
364
+ <meta charset="utf-8">
365
+ <meta name="viewport" content="width=device-width, initial-scale=1">
366
+ <title>{title}</title>
367
+ <link rel="manifest" href="manifest.webmanifest">
368
+ <link rel="icon" href="icon.svg">
369
+ <meta name="theme-color" content="#2563eb">
370
+ <style>
371
+ :root { color-scheme: light dark; --bg:#f8fafc; --fg:#0f172a; --card:#ffffff; --line:#cbd5e1; --accent:#2563eb; }
372
+ @media (prefers-color-scheme: dark) { :root { --bg:#0f172a; --fg:#e2e8f0; --card:#1e293b; --line:#334155; --accent:#60a5fa; } }
373
+ body { margin:0; font:16px/1.4 system-ui, sans-serif; background:var(--bg); color:var(--fg); }
374
+ header { padding:14px 16px; font-weight:600; background:var(--accent); color:#fff; }
375
+ #app { max-width:560px; margin:0 auto; padding:16px; display:flex; flex-direction:column; gap:10px; }
376
+ fieldset { border:1px solid var(--line); border-radius:10px; background:var(--card); display:flex; flex-direction:column; gap:10px; }
377
+ button { padding:10px 14px; border:0; border-radius:8px; background:var(--accent); color:#fff; font:inherit; cursor:pointer; }
378
+ button:active { opacity:.8 }
379
+ input:not([type=checkbox]):not([type=range]), textarea, select { width:100%; box-sizing:border-box; padding:9px; border:1px solid var(--line);
380
+ border-radius:8px; background:var(--card); color:var(--fg); font:inherit; }
381
+ .row { display:flex; align-items:center; gap:8px; } .row input[type=range] { flex:1; }
382
+ progress { width:100%; height:14px; } canvas { width:100%; background:var(--card); border:1px solid var(--line); border-radius:8px; }
383
+ ul.list { list-style:none; margin:0; padding:0; border:1px solid var(--line); border-radius:8px; background:var(--card); }
384
+ ul.list li { padding:9px 12px; border-bottom:1px solid var(--line); cursor:pointer; } ul.list li:last-child { border:0; }
385
+ h2 { margin:4px 0; font-size:20px; }
386
+ #status { position:sticky; bottom:0; padding:8px 16px; font-size:13px; border-top:1px solid var(--line); background:var(--card); min-height:18px; }
387
+ </style>
388
+ </head>
389
+ <body>
390
+ <header>{title}</header>
391
+ <main id="app"></main>
392
+ <div id="status"></div>
393
+ <script src="app.js"></script>
394
+ </body>
395
+ </html>
396
+ """
397
+
398
+ _SW = """// Offline cache for the installed app.
399
+ const CACHE = "nlcl-app-v1";
400
+ const FILES = ["./", "index.html", "app.js", "manifest.webmanifest", "icon.svg"];
401
+ self.addEventListener("install", (e) => e.waitUntil(caches.open(CACHE).then((c) => c.addAll(FILES))));
402
+ self.addEventListener("fetch", (e) => {
403
+ if (e.request.method !== "GET" || !e.request.url.startsWith(self.location.origin)) return;
404
+ e.respondWith(fetch(e.request).then((r) => { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(e.request, copy)); return r; })
405
+ .catch(() => caches.match(e.request)));
406
+ });
407
+ """
408
+
409
+ _ICON = """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128"><rect width="128" height="128" rx="24" fill="#2563eb"/>
410
+ <text x="64" y="86" font-family="system-ui, sans-serif" font-size="72" font-weight="700" text-anchor="middle" fill="#fff">{letter}</text></svg>
411
+ """
412
+
413
+ MODULE = AppModule()
nlcl/modules/base.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Domain module interface.
2
+
3
+ A domain module turns the universal IR (entities, behaviours, channels) into
4
+ artefacts for one execution environment: a game engine, a micro-controller,
5
+ an HDL, a CAD tool ... Modules never see natural language.
6
+
7
+ To add a new domain, drop a file in nlcl/modules/ that defines a subclass of
8
+ DomainModule and exposes an instance as ``MODULE``.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import shutil
13
+ import subprocess
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from ..ir import Entity, SystemState, ident, pascal, render_expr
19
+
20
+
21
+ @dataclass
22
+ class Channel:
23
+ """A resolved cross-entity communication path (from a Link)."""
24
+ id: str
25
+ protocol: str # serial | http | mqtt | gpio | spi | i2c | udp | websocket
26
+ src: Entity
27
+ dst: Entity
28
+ fields: list[str] # data fields carried src -> dst
29
+ config: dict = field(default_factory=dict) # baud, port, url, topic, broker, pins ...
30
+
31
+ def direction(self, entity_or_domain: Any) -> str | None:
32
+ """'out' if the given entity/domain is the sender, 'in' if receiver."""
33
+ if isinstance(entity_or_domain, Entity):
34
+ if entity_or_domain.id == self.src.id:
35
+ return "out"
36
+ if entity_or_domain.id == self.dst.id:
37
+ return "in"
38
+ return None
39
+ if self.src.domain == entity_or_domain:
40
+ return "out"
41
+ if self.dst.domain == entity_or_domain:
42
+ return "in"
43
+ return None
44
+
45
+ def peer(self, entity: Entity) -> Entity:
46
+ return self.dst if entity.id == self.src.id else self.src
47
+
48
+ @property
49
+ def topic(self) -> str:
50
+ return self.config.get("topic", f"nlcl/{self.id}")
51
+
52
+ @property
53
+ def hub_url(self) -> str:
54
+ return self.config.get("hub_url", "http://localhost:8765")
55
+
56
+ def to_dict(self) -> dict:
57
+ return {"id": self.id, "protocol": self.protocol, "src": self.src.name,
58
+ "src_domain": self.src.domain, "dst": self.dst.name,
59
+ "dst_domain": self.dst.domain, "fields": self.fields, "config": self.config}
60
+
61
+
62
+ @dataclass
63
+ class BuildContext:
64
+ system: SystemState
65
+ domain: str
66
+ entities: list[Entity] # entities of this domain (creation order)
67
+ channels: list[Channel] # every channel touching this domain
68
+ outdir: Path # where this module writes (already created)
69
+ project: str = "project"
70
+ llm: Any = None # optional LLM backend (may be None)
71
+
72
+ def channels_for(self, entity: Entity) -> list[Channel]:
73
+ return [c for c in self.channels if entity.id in (c.src.id, c.dst.id)]
74
+
75
+ def children(self, entity: Entity) -> list[Entity]:
76
+ return [e for e in self.entities if e.parent == entity.id]
77
+
78
+ def roots(self) -> list[Entity]:
79
+ ids = {e.id for e in self.entities}
80
+ return [e for e in self.entities if e.parent not in ids]
81
+
82
+
83
+ @dataclass
84
+ class RunResult:
85
+ ok: bool
86
+ output: str
87
+ command: str = ""
88
+
89
+
90
+ class DomainModule:
91
+ # identity
92
+ name: str = "base" # canonical domain id, e.g. "game"
93
+ title: str = "Base"
94
+ aliases: tuple[str, ...] = () # other words that name this domain directly
95
+ keywords: tuple[str, ...] = () # words that *suggest* this domain (kinds, tech names)
96
+ # kind -> default props. "object" should always be present.
97
+ kinds: dict[str, dict] = {"object": {}}
98
+ # property names the module understands well (used for "What properties?" prompts)
99
+ suggested_props: tuple[str, ...] = ()
100
+ # protocols this domain can speak natively
101
+ protocols: tuple[str, ...] = ("http",)
102
+ # free toolchain advice shown in SYSTEM.md
103
+ toolchain: str = ""
104
+
105
+ # ---------------------------------------------------------------- props
106
+ def default_props(self, kind: str) -> dict:
107
+ return dict(self.kinds.get(kind, self.kinds.get("object", {})))
108
+
109
+ def validate(self, entity: Entity) -> list[str]:
110
+ """Return human-readable warnings (never raise)."""
111
+ return []
112
+
113
+ def prompt_for(self, entity: Entity) -> str | None:
114
+ """Optional follow-up question after an entity is created."""
115
+ if self.suggested_props:
116
+ return (f"What properties should {entity.name} have? "
117
+ f"(e.g. {', '.join(self.suggested_props[:5])})")
118
+ return None
119
+
120
+ # ---------------------------------------------------------------- build
121
+ def generate(self, ctx: BuildContext) -> dict[str, str]:
122
+ """Return {relative_path: file_content}."""
123
+ raise NotImplementedError
124
+
125
+ def run(self, ctx: BuildContext) -> RunResult | None:
126
+ """Execute/simulate generated artefacts if a free local tool exists."""
127
+ return None
128
+
129
+ # ---------------------------------------------------------------- helpers
130
+ @staticmethod
131
+ def expr(e: Any, lang: str, name=lambda n: n) -> str:
132
+ return render_expr(e, lang, name)
133
+
134
+ @staticmethod
135
+ def ident(s: str) -> str:
136
+ return ident(s)
137
+
138
+ @staticmethod
139
+ def pascal(s: str) -> str:
140
+ return pascal(s)
141
+
142
+ @staticmethod
143
+ def which(*names: str) -> str | None:
144
+ for n in names:
145
+ p = shutil.which(n)
146
+ if p:
147
+ return p
148
+ return None
149
+
150
+ @staticmethod
151
+ def sh(cmd: list[str], cwd: Path, timeout: int = 30) -> RunResult:
152
+ try:
153
+ p = subprocess.run(cmd, cwd=str(cwd), capture_output=True, text=True,
154
+ timeout=timeout, encoding="utf-8", errors="replace")
155
+ return RunResult(p.returncode == 0, (p.stdout + p.stderr).strip(), " ".join(cmd))
156
+ except subprocess.TimeoutExpired as e:
157
+ out = (e.stdout or "") if isinstance(e.stdout, str) else ""
158
+ return RunResult(True, out + f"\n[stopped after {timeout}s]", " ".join(cmd))
159
+ except OSError as e:
160
+ return RunResult(False, str(e), " ".join(cmd))
161
+
162
+ @staticmethod
163
+ def literal(v: Any, lang: str) -> str:
164
+ """Render a property value as a literal in the target language."""
165
+ if isinstance(v, bool):
166
+ return {"python": "True" if v else "False",
167
+ "verilog": "1'b1" if v else "1'b0"}.get(lang, "true" if v else "false")
168
+ if isinstance(v, (int, float)):
169
+ if lang in ("csharp",) and isinstance(v, float):
170
+ return f"{v}f"
171
+ return repr(v)
172
+ if isinstance(v, (list, tuple)):
173
+ inner = ", ".join(DomainModule.literal(x, lang) for x in v)
174
+ return {"python": f"[{inner}]", "js": f"[{inner}]", "gdscript": f"[{inner}]",
175
+ "openscad": f"[{inner}]"}.get(lang, "{" + inner + "}")
176
+ s = str(v).replace("\\", "\\\\").replace('"', '\\"')
177
+ return f'"{s}"'
178
+
179
+ @staticmethod
180
+ def ctype(v: Any, lang: str) -> str:
181
+ """Best-effort static type for a value."""
182
+ if isinstance(v, bool):
183
+ return {"csharp": "bool", "cpp": "bool", "c": "bool", "gdscript": "bool"}.get(lang, "bool")
184
+ if isinstance(v, int):
185
+ return {"csharp": "int", "cpp": "int", "c": "int", "gdscript": "int"}.get(lang, "int")
186
+ if isinstance(v, float):
187
+ return {"csharp": "float", "cpp": "float", "c": "float", "gdscript": "float"}.get(lang, "float")
188
+ if isinstance(v, (list, tuple)):
189
+ return {"csharp": "float[]", "cpp": "std::vector<float>", "gdscript": "Array"}.get(lang, "float*")
190
+ return {"csharp": "string", "cpp": "std::string", "c": "const char*", "gdscript": "String"}.get(lang, "String")
nlcl/modules/cad_mod.py ADDED
The diff for this file is too large to render. See raw diff