molly-lang 0.8.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ Molly — Model Orchestration Language with Labeled Yields
2
+ Copyright 2026 Eyner Andres Diaz (https://andresdiazd.com/)
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
@@ -0,0 +1,204 @@
1
+ Metadata-Version: 2.4
2
+ Name: molly-lang
3
+ Version: 0.8.0
4
+ Summary: A small language for AI-agent plans where permissions follow the data
5
+ Author: Eyner Andres Diaz
6
+ License: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/andresD1az/molly-lang
8
+ Project-URL: Repository, https://github.com/andresD1az/molly-lang
9
+ Project-URL: Issues, https://github.com/andresD1az/molly-lang/issues
10
+ Project-URL: Changelog, https://github.com/andresD1az/molly-lang/blob/main/CHANGELOG.md
11
+ Project-URL: Author, https://andresdiazd.com/
12
+ Keywords: dsl,language,ai-agents,security,information-flow-control,prompt-injection,parser
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: Software Development :: Interpreters
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ License-File: NOTICE
28
+ Dynamic: license-file
29
+
30
+ <p align="center">
31
+ <picture>
32
+ <source media="(prefers-color-scheme: dark)" srcset="docs/brand/molly-lang-logo-dark.svg">
33
+ <img src="docs/brand/molly-lang-logo.svg" alt="Molly Lang" height="96">
34
+ </picture>
35
+ </p>
36
+
37
+ # Molly
38
+
39
+ [![tests](https://github.com/andresD1az/molly-lang/actions/workflows/tests.yml/badge.svg)](https://github.com/andresD1az/molly-lang/actions/workflows/tests.yml)
40
+ [![license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
41
+ ![python](https://img.shields.io/badge/python-3.10%2B-blue.svg)
42
+ ![status](https://img.shields.io/badge/status-alpha-orange.svg)
43
+
44
+ **Let AI agents write the plan. Keep control of where the data goes.**
45
+
46
+ **MOLLY — Model Orchestration Language with Labeled Yields.** A small, analyzable language for plans written by AI agents. Every value carries a label with its origin and the recipients allowed to see it, and the engine enforces it at every step.
47
+
48
+ ```text
49
+ let order = current_order(); # private: only this customer may see it
50
+ let message = draft(order); # the label follows the data
51
+ send customer_whatsapp(message); # ALLOWED: the owner receives it
52
+ send public_web(message); # BLOCKED before the adapter is ever called
53
+ ```
54
+
55
+ ## The problem
56
+
57
+ A customer asks about their order on WhatsApp. Your application authenticates them, builds a context (company and customer) and registers the tools the agent may use. An agent writes a short program that looks up the order, rewrites the text and replies. The agent does **not** decide who the customer is, which model is authorized, or which phone number a sink points to.
58
+
59
+ The promise: **you can change the plan without giving the agent the ability to change the permissions.**
60
+
61
+ Prompt injection makes this urgent. If a malicious message convinces the agent to "also post the order to the website", the plan may contain that step, but the engine refuses to run it because the data's label does not allow that recipient.
62
+
63
+ ## Quick start
64
+
65
+ Python 3.10+, no dependencies. Clone the repository and run:
66
+
67
+ ```bash
68
+ python demo.py --case allowed
69
+ python demo.py --case web
70
+ python demo.py --case branch_leak
71
+ python demo.py examples/complete.molly
72
+ python -m unittest -v
73
+ ```
74
+
75
+ Exit codes: `0` allowed, `1` analysis errors (all of them are listed with line and column), `2` blocked by a permission. The demo adapters use synthetic data: **no real messages are sent, no database is queried and no LLM is called.** The lexer, parser and permission decisions are real code, not hardcoded results.
76
+
77
+ Other useful flags:
78
+
79
+ ```bash
80
+ python demo.py examples/conditional.molly --tree --tokens # derivation tree and DFA tokens
81
+ python demo.py examples/errors.molly # every error, with position
82
+ python demo.py examples/reply.molly --json # everything, including the trace
83
+ python demo.py --formal grammar # BNF, FIRST/FOLLOW, LL(1) check
84
+ ```
85
+
86
+ ## The language in one minute
87
+
88
+ ```text
89
+ let tax = 0.19; # constant, type inferred
90
+ int count = 0; # typed variable, can be reassigned
91
+ record order = order_details();
92
+ float total = order.total * (1 + tax);
93
+
94
+ if total > 100000 and order.status in {"shipped", "delivered"} then
95
+ send customer_whatsapp("Total with tax: $" + total);
96
+ else
97
+ send customer_whatsapp("Your order is being prepared.");
98
+ end
99
+
100
+ for n in [1 .. 10] do
101
+ count = count + n;
102
+ end
103
+ ```
104
+
105
+ Types: `int`, `float`, `bool`, `char`, `str`, `list`, `set`, `record`, `null`. Control flow: `if/then/else/end`, `while/do/end`, `for/in/do/end`. Operators include arithmetic, comparisons, `and/or/not/implies/iff`, and set operations (`union`, `intersect`, `-`, `subset`, `in`, `|A|`). Full reference: [docs/SYNTAX.md](docs/SYNTAX.md).
106
+
107
+ ## What the engine guarantees
108
+
109
+ | Situation | Result | What is checked |
110
+ |---|---|---|
111
+ | Own order → draft → authenticated customer | Allowed | The reply reaches the adapter |
112
+ | Own order → draft → public web | Blocked | Zero calls to the publishing adapter |
113
+ | Own order → unauthorized model | Blocked | Zero calls to the external processor |
114
+ | Customer Ana → Bruno's source | Blocked | Zero reads from the source |
115
+ | Public text + order → public web | Blocked | Concatenation does not erase restrictions |
116
+ | Public catalog → draft → public web | Allowed | Public data stays usable |
117
+ | Order record → total with tax → customer | Allowed | Arithmetic and structured types keep the label |
118
+ | Private status `== "cancelled"` → public text to the web | Blocked | The chosen branch is information too (implicit flow) |
119
+ | Count the letters of a private order → publish the count | Blocked | Loops and assignments carry the label |
120
+
121
+ **Implicit flows.** Choosing a branch or repeating a loop reveals information about its condition. Before an `if`, `while` or `for` runs, the engine checks every send and external processor in the block against the condition's label. Variables the block could reassign inherit that label even if the branch never runs, so the outcome does not depend on the path taken.
122
+
123
+ ## Embedding it in your application
124
+
125
+ `molly.py` is a library. Tools are registered from trusted code, never from the Molly program.
126
+
127
+ ```python
128
+ from molly import Engine, Context, Source, Transform, Sink
129
+
130
+ # Adapters you implement in your backend:
131
+ # fetch_order(ctx), can_read(ctx), write_reply(ctx, text),
132
+ # verified_recipient(ctx), send_whatsapp(ctx, text).
133
+
134
+ engine = Engine(
135
+ sources={
136
+ "current_order": Source(
137
+ load=fetch_order,
138
+ authorize=can_read,
139
+ audience=lambda ctx: frozenset({
140
+ f"customer:{ctx.tenant}:{ctx.subject}",
141
+ "model:authorized",
142
+ }),
143
+ )
144
+ },
145
+ transforms={
146
+ "draft": Transform(run=write_reply, arity=1, processor="model:authorized")
147
+ },
148
+ sinks={
149
+ "customer_whatsapp": Sink(identity=verified_recipient, send=send_whatsapp)
150
+ },
151
+ )
152
+
153
+ # ctx comes from your authenticated session and backend checks.
154
+ # Never take tenant or subject from what the agent wrote or from an unverified message.
155
+ result = engine.run(agent_program, ctx)
156
+ ```
157
+
158
+ This snippet shows the integration contract; the functions it mentions are not implemented here. The runnable example is [demo.py](demo.py). A source adapter must filter its query by the context *before* fetching data: loading everything and labeling it afterwards gives no such guarantee.
159
+
160
+ Install it with `pip install molly-lang`, or copy `molly.py` into your project: it is a single file with no dependencies.
161
+
162
+ ## How it is built
163
+
164
+ - **Lexer:** a deterministic finite automaton (39 states, 30 symbol classes) run from an explicit transition table. No regex engine.
165
+ - **Parser:** LL(1) recursive descent (90 productions, 0 conflicts) with panic-mode error recovery and a full derivation tree.
166
+ - **Checks before any effect:** names, scopes, constants, tool arities and record fields.
167
+ - **Interpreter:** labels propagate through every operation, and the implicit-flow checks above run on every control structure.
168
+ - **Atomic sends:** allowed sends are queued and delivered only if the whole plan finishes, so a plan that fails halfway delivers nothing.
169
+ - **Quiet errors and trace:** an error raised on restricted data withholds its details, and the trace does not record which branch ran, how many times a loop ran or the type of restricted values.
170
+ - **Bounded work:** every value is limited in total size and depth, so a short program cannot make a comparison or a print run for an unbounded time.
171
+ - **Tests:** 73 unit tests, plus a noninterference fuzzer (`python tools/fuzz_noninterference.py 3000`) that runs random plans with two different secrets and checks that a public observer sees the same sends and trace.
172
+
173
+ The formal definition (DFA, BNF, why the grammar is unambiguous) is in [docs/GRAMMAR.md](docs/GRAMMAR.md); the generated tables are in [docs/TABLES.md](docs/TABLES.md).
174
+
175
+ ## Limits
176
+
177
+ - No user-defined functions, `break` or `continue` yet.
178
+ - Labels are inherited conservatively. A summary does not become public automatically, and there is no declassification operation yet.
179
+ - Adapters are trusted. A local function must not send data elsewhere on its own, and external processors must declare their identity.
180
+ - **Abort channel.** Whether a plan finishes or fails, and at which step, can depend on restricted data. Sends are atomic (see above), so a recipient sees everything or nothing, and error messages never include restricted values, but that one outcome is still observable. This includes the stop at 10,000 loop iterations.
181
+ - A call to an external processor happens when it is evaluated, not at the end, and a sink adapter that fails during delivery does not undo earlier deliveries of the same plan.
182
+ - Timing channels are out of scope.
183
+ - Prototype limits: 12,000-character programs, 100 statements, 32 nesting levels, 64-bit integers, 4,000-character texts, 1,000-element collections, 10,000 elements in total per value, 25 reported errors. No process isolation, adapter timeouts, persistence or durable audit log.
184
+ - Protection depends on the quality of your policies, authentication and adapters. Molly is not a guarantee of total security, general prompt-injection resistance or regulatory compliance.
185
+
186
+ ## Related work
187
+
188
+ Having an AI agent write a plan in a restricted language while an interpreter controls the data flow is also an active research direction. Examples include CaMeL (*Defeating Prompt Injections by Design*, Google DeepMind and ETH Zurich, 2025) and FIDES (information-flow control for agents, Microsoft, 2025). Molly does not use code from those projects; it shares the general approach, which builds on decades of information-flow-control research.
189
+
190
+ Molly started as an academic project in a Formal Language Theory course. That version, with a Spanish vocabulary inspired by time travel, lives in a separate repository.
191
+
192
+ ## Security and contributing
193
+
194
+ Found a way to leak a restricted value? Please report it privately as described in [SECURITY.md](SECURITY.md). For everything else, see [CONTRIBUTING.md](CONTRIBUTING.md), the [code of conduct](CODE_OF_CONDUCT.md) and the [changelog](CHANGELOG.md).
195
+
196
+ ## License
197
+
198
+ Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). You may use, modify and redistribute Molly, including commercially, keeping the copyright notice and the NOTICE file. The license includes an explicit patent grant.
199
+
200
+ ## Author
201
+
202
+ **Eyner Andres Diaz** · [andresdiazd.com](https://andresdiazd.com/)
203
+
204
+ Academic project team (Formal Language Theory, 2026): Eyner Andres Diaz, Jose Manuel Taborda and Daniel Eduardo Celemin. Developed with the help of AI tools (ChatGPT and Claude); design, decisions and review by the author.
@@ -0,0 +1,175 @@
1
+ <p align="center">
2
+ <picture>
3
+ <source media="(prefers-color-scheme: dark)" srcset="docs/brand/molly-lang-logo-dark.svg">
4
+ <img src="docs/brand/molly-lang-logo.svg" alt="Molly Lang" height="96">
5
+ </picture>
6
+ </p>
7
+
8
+ # Molly
9
+
10
+ [![tests](https://github.com/andresD1az/molly-lang/actions/workflows/tests.yml/badge.svg)](https://github.com/andresD1az/molly-lang/actions/workflows/tests.yml)
11
+ [![license](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE)
12
+ ![python](https://img.shields.io/badge/python-3.10%2B-blue.svg)
13
+ ![status](https://img.shields.io/badge/status-alpha-orange.svg)
14
+
15
+ **Let AI agents write the plan. Keep control of where the data goes.**
16
+
17
+ **MOLLY — Model Orchestration Language with Labeled Yields.** A small, analyzable language for plans written by AI agents. Every value carries a label with its origin and the recipients allowed to see it, and the engine enforces it at every step.
18
+
19
+ ```text
20
+ let order = current_order(); # private: only this customer may see it
21
+ let message = draft(order); # the label follows the data
22
+ send customer_whatsapp(message); # ALLOWED: the owner receives it
23
+ send public_web(message); # BLOCKED before the adapter is ever called
24
+ ```
25
+
26
+ ## The problem
27
+
28
+ A customer asks about their order on WhatsApp. Your application authenticates them, builds a context (company and customer) and registers the tools the agent may use. An agent writes a short program that looks up the order, rewrites the text and replies. The agent does **not** decide who the customer is, which model is authorized, or which phone number a sink points to.
29
+
30
+ The promise: **you can change the plan without giving the agent the ability to change the permissions.**
31
+
32
+ Prompt injection makes this urgent. If a malicious message convinces the agent to "also post the order to the website", the plan may contain that step, but the engine refuses to run it because the data's label does not allow that recipient.
33
+
34
+ ## Quick start
35
+
36
+ Python 3.10+, no dependencies. Clone the repository and run:
37
+
38
+ ```bash
39
+ python demo.py --case allowed
40
+ python demo.py --case web
41
+ python demo.py --case branch_leak
42
+ python demo.py examples/complete.molly
43
+ python -m unittest -v
44
+ ```
45
+
46
+ Exit codes: `0` allowed, `1` analysis errors (all of them are listed with line and column), `2` blocked by a permission. The demo adapters use synthetic data: **no real messages are sent, no database is queried and no LLM is called.** The lexer, parser and permission decisions are real code, not hardcoded results.
47
+
48
+ Other useful flags:
49
+
50
+ ```bash
51
+ python demo.py examples/conditional.molly --tree --tokens # derivation tree and DFA tokens
52
+ python demo.py examples/errors.molly # every error, with position
53
+ python demo.py examples/reply.molly --json # everything, including the trace
54
+ python demo.py --formal grammar # BNF, FIRST/FOLLOW, LL(1) check
55
+ ```
56
+
57
+ ## The language in one minute
58
+
59
+ ```text
60
+ let tax = 0.19; # constant, type inferred
61
+ int count = 0; # typed variable, can be reassigned
62
+ record order = order_details();
63
+ float total = order.total * (1 + tax);
64
+
65
+ if total > 100000 and order.status in {"shipped", "delivered"} then
66
+ send customer_whatsapp("Total with tax: $" + total);
67
+ else
68
+ send customer_whatsapp("Your order is being prepared.");
69
+ end
70
+
71
+ for n in [1 .. 10] do
72
+ count = count + n;
73
+ end
74
+ ```
75
+
76
+ Types: `int`, `float`, `bool`, `char`, `str`, `list`, `set`, `record`, `null`. Control flow: `if/then/else/end`, `while/do/end`, `for/in/do/end`. Operators include arithmetic, comparisons, `and/or/not/implies/iff`, and set operations (`union`, `intersect`, `-`, `subset`, `in`, `|A|`). Full reference: [docs/SYNTAX.md](docs/SYNTAX.md).
77
+
78
+ ## What the engine guarantees
79
+
80
+ | Situation | Result | What is checked |
81
+ |---|---|---|
82
+ | Own order → draft → authenticated customer | Allowed | The reply reaches the adapter |
83
+ | Own order → draft → public web | Blocked | Zero calls to the publishing adapter |
84
+ | Own order → unauthorized model | Blocked | Zero calls to the external processor |
85
+ | Customer Ana → Bruno's source | Blocked | Zero reads from the source |
86
+ | Public text + order → public web | Blocked | Concatenation does not erase restrictions |
87
+ | Public catalog → draft → public web | Allowed | Public data stays usable |
88
+ | Order record → total with tax → customer | Allowed | Arithmetic and structured types keep the label |
89
+ | Private status `== "cancelled"` → public text to the web | Blocked | The chosen branch is information too (implicit flow) |
90
+ | Count the letters of a private order → publish the count | Blocked | Loops and assignments carry the label |
91
+
92
+ **Implicit flows.** Choosing a branch or repeating a loop reveals information about its condition. Before an `if`, `while` or `for` runs, the engine checks every send and external processor in the block against the condition's label. Variables the block could reassign inherit that label even if the branch never runs, so the outcome does not depend on the path taken.
93
+
94
+ ## Embedding it in your application
95
+
96
+ `molly.py` is a library. Tools are registered from trusted code, never from the Molly program.
97
+
98
+ ```python
99
+ from molly import Engine, Context, Source, Transform, Sink
100
+
101
+ # Adapters you implement in your backend:
102
+ # fetch_order(ctx), can_read(ctx), write_reply(ctx, text),
103
+ # verified_recipient(ctx), send_whatsapp(ctx, text).
104
+
105
+ engine = Engine(
106
+ sources={
107
+ "current_order": Source(
108
+ load=fetch_order,
109
+ authorize=can_read,
110
+ audience=lambda ctx: frozenset({
111
+ f"customer:{ctx.tenant}:{ctx.subject}",
112
+ "model:authorized",
113
+ }),
114
+ )
115
+ },
116
+ transforms={
117
+ "draft": Transform(run=write_reply, arity=1, processor="model:authorized")
118
+ },
119
+ sinks={
120
+ "customer_whatsapp": Sink(identity=verified_recipient, send=send_whatsapp)
121
+ },
122
+ )
123
+
124
+ # ctx comes from your authenticated session and backend checks.
125
+ # Never take tenant or subject from what the agent wrote or from an unverified message.
126
+ result = engine.run(agent_program, ctx)
127
+ ```
128
+
129
+ This snippet shows the integration contract; the functions it mentions are not implemented here. The runnable example is [demo.py](demo.py). A source adapter must filter its query by the context *before* fetching data: loading everything and labeling it afterwards gives no such guarantee.
130
+
131
+ Install it with `pip install molly-lang`, or copy `molly.py` into your project: it is a single file with no dependencies.
132
+
133
+ ## How it is built
134
+
135
+ - **Lexer:** a deterministic finite automaton (39 states, 30 symbol classes) run from an explicit transition table. No regex engine.
136
+ - **Parser:** LL(1) recursive descent (90 productions, 0 conflicts) with panic-mode error recovery and a full derivation tree.
137
+ - **Checks before any effect:** names, scopes, constants, tool arities and record fields.
138
+ - **Interpreter:** labels propagate through every operation, and the implicit-flow checks above run on every control structure.
139
+ - **Atomic sends:** allowed sends are queued and delivered only if the whole plan finishes, so a plan that fails halfway delivers nothing.
140
+ - **Quiet errors and trace:** an error raised on restricted data withholds its details, and the trace does not record which branch ran, how many times a loop ran or the type of restricted values.
141
+ - **Bounded work:** every value is limited in total size and depth, so a short program cannot make a comparison or a print run for an unbounded time.
142
+ - **Tests:** 73 unit tests, plus a noninterference fuzzer (`python tools/fuzz_noninterference.py 3000`) that runs random plans with two different secrets and checks that a public observer sees the same sends and trace.
143
+
144
+ The formal definition (DFA, BNF, why the grammar is unambiguous) is in [docs/GRAMMAR.md](docs/GRAMMAR.md); the generated tables are in [docs/TABLES.md](docs/TABLES.md).
145
+
146
+ ## Limits
147
+
148
+ - No user-defined functions, `break` or `continue` yet.
149
+ - Labels are inherited conservatively. A summary does not become public automatically, and there is no declassification operation yet.
150
+ - Adapters are trusted. A local function must not send data elsewhere on its own, and external processors must declare their identity.
151
+ - **Abort channel.** Whether a plan finishes or fails, and at which step, can depend on restricted data. Sends are atomic (see above), so a recipient sees everything or nothing, and error messages never include restricted values, but that one outcome is still observable. This includes the stop at 10,000 loop iterations.
152
+ - A call to an external processor happens when it is evaluated, not at the end, and a sink adapter that fails during delivery does not undo earlier deliveries of the same plan.
153
+ - Timing channels are out of scope.
154
+ - Prototype limits: 12,000-character programs, 100 statements, 32 nesting levels, 64-bit integers, 4,000-character texts, 1,000-element collections, 10,000 elements in total per value, 25 reported errors. No process isolation, adapter timeouts, persistence or durable audit log.
155
+ - Protection depends on the quality of your policies, authentication and adapters. Molly is not a guarantee of total security, general prompt-injection resistance or regulatory compliance.
156
+
157
+ ## Related work
158
+
159
+ Having an AI agent write a plan in a restricted language while an interpreter controls the data flow is also an active research direction. Examples include CaMeL (*Defeating Prompt Injections by Design*, Google DeepMind and ETH Zurich, 2025) and FIDES (information-flow control for agents, Microsoft, 2025). Molly does not use code from those projects; it shares the general approach, which builds on decades of information-flow-control research.
160
+
161
+ Molly started as an academic project in a Formal Language Theory course. That version, with a Spanish vocabulary inspired by time travel, lives in a separate repository.
162
+
163
+ ## Security and contributing
164
+
165
+ Found a way to leak a restricted value? Please report it privately as described in [SECURITY.md](SECURITY.md). For everything else, see [CONTRIBUTING.md](CONTRIBUTING.md), the [code of conduct](CODE_OF_CONDUCT.md) and the [changelog](CHANGELOG.md).
166
+
167
+ ## License
168
+
169
+ Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE). You may use, modify and redistribute Molly, including commercially, keeping the copyright notice and the NOTICE file. The license includes an explicit patent grant.
170
+
171
+ ## Author
172
+
173
+ **Eyner Andres Diaz** · [andresdiazd.com](https://andresdiazd.com/)
174
+
175
+ Academic project team (Formal Language Theory, 2026): Eyner Andres Diaz, Jose Manuel Taborda and Daniel Eduardo Celemin. Developed with the help of AI tools (ChatGPT and Claude); design, decisions and review by the author.