Stof 0.10: Safe by Default, Errors You Can Read, and a Language Server
Stof 0.10 is out. It's the biggest release since Stof started, and almost all of it serves one goal: making it safe and easy to run logic you didn't write, whether it came from a model, a customer, or another team.
That meant tightening the sandbox, making every error something a person or a model can read and fix, closing off behaviors that quietly produced wrong answers, and giving you better tools to write Stof yourself. This post covers 0.10.0 through 0.10.9, along with stof-cli 0.13 and version 0.3 of the VS Code extension. It was updated on October 20 for 0.10.7 and 0.10.8, and on November 3 for 0.10.9.
npm i @formata/stof@latest # TypeScript / JavaScript
pip install -U stof # Python
cargo add stof # Rust
cargo install stof-cli # CLI, including the language server
Most documents run unchanged, but a few fixes are breaking. Read Breaking Changes before you upgrade.
Sandboxed by Default
Before 0.10, an embedded document in Rust or Python could read and write files, read environment variables, and make network requests unless the host removed those libraries. That's the wrong default for logic you don't fully trust.
Now an embedded document reaches nothing outside itself unless your app opts in:
const doc = await StofDoc.new(rulesFromAModel);
doc.allowHttp(['api.example.com']); // the Http library, for these hosts only (0.10.4)
doc.setMaxExecutionTime(50); // every call fails after 50ms (0.10.4)
- Files and environment are off until
allow_system()(Rust, Python). - Network is off until
allow_http()(Rust, Python) orallowHttp()(JavaScript). In JavaScript,allowHttp()also gives documentsHttp.fetch, backed by the platform's fetch, so you don't need your own. - An allowlist limits requests to the hosts you name. A request to any other host, or a redirect to one, fails.
- Time limits are now yours to set. The default is still 2 minutes, and a runaway loop fails that one call and nothing else.
The stof CLI turns everything on, since it runs documents on your own machine. See Using Stof in Your App.
Errors You Can Read
Errors were the most common complaint about Stof, and they're the thing that matters most when a model writes the code: an error it can read is an error it can fix.
Runtime errors now say what went wrong in plain language, show the line, and give the Stof call stack:
error: cannot multiply null: the right value is null or missing (use ?? to give a default)
--> pricing.stof:4:9
|
4 | units * self.rat
| ^
at root.plan.total (pricing.stof:4:9)
at root.main (pricing.stof:10:5)
Parse errors show the file, line, and column with a caret. Argument errors say exactly what's wrong: missing argument 'units' for total(units: int, rate?: float). And names that can't be anything are caught when the document is parsed, before they turn into a confusing null:
warning: unknown name 'team' in fn root.main (main.stof:4:9): not a parameter, variable,
or root, so it is always null (use self.team for a field)
Your app gets the same messages and call stacks from call and run, in every language.
Fewer Silent Wrong Answers
A few long-standing behaviors gave wrong results without complaint. They're now fixed or reported:
- Math with null is an error.
3 * nullused to be3. Now it throws, so a misspelled field can't become a wrong price. Use??for defaults. - Functions have their own scope. A function could read its caller's variables, so a typo could quietly bind to the wrong value. Now named functions see only their parameters and their own variables. Arrow functions still see the function they're written in.
- Paths start at a root.
team.nameused to find any object namedteamanywhere in the document. Now it means the root namedteam, and the warning above catches the mistake. - Numbers behave. Number methods return a new value instead of changing the original. Integer overflow becomes a float instead of wrapping negative, division by zero gives infinity instead of crashing, and unit conversions use exact factors.
typeofbinds tightly (0.10.2).typeof x == 'obj'is now(typeof x) == 'obj', as you'd expect.
Temporary Objects with using
Objects in a Stof document stay until something removes them. That's fine for a document you run once, but a policy that runs on every request for months can pile up temporary objects. 0.10.3 adds using: declare a temporary object with it, and it's dropped when its block or function ends, however it ends:
orders: {}
fn check(total: float) -> bool {
using order = new { total: total, tax: total * 0.2 } on self.orders;
order.total + order.tax < 1000
}
#[main]
fn main() {
pln(self.check(500));
pln(self.check(900));
pln(self.orders.children().len()); // 0: both were dropped
}self.handle(using new { .. }) does the same for an object passed straight into a call. And stof test --leaks runs each test on its own and fails any test that leaves objects behind, saying where they are. See Memory Management.
Destructuring
0.10.5 adds destructuring, which a data language really should have. Take values apart into variables in one step, from objects, maps, lists, and tuples, and in loops:
user: {
name: 'Ada'
age: 36
address: { city: 'London' }
}
#[main]
fn main() {
const { name, age: years, role = 'member', address: { city } } = self.user;
pln(`${name}, ${years}, ${role}, ${city}`);
const [first, _, third] = ['a', 'b', 'c'];
pln(first + third);
for (const (key, value) in map(('calls', 100), ('seats', 5))) {
pln(`${key} = ${value}`);
}
}Workflows From Types
obj.run() runs an object's #[run] steps, and in 0.10.6 it works the way you'd expect with types. Steps run in the order they're written. A type's steps run on every instance, each step once. An instance can replace a step by giving one the same name, remove one with null, or add its own, and a number moves any step before or after the rest:
#[type]
Onboarding: {
str email: ''
list log: []
#[run]
fn check() { self.log.push_back('checked ' + self.email); }
#[run]
fn welcome() { self.log.push_back('welcome email'); }
}
Onboarding team: {
email: 'team@example.com'
#[run]
fn welcome() { self.log.push_back('team welcome email'); }
#[run(-1)]
fn verify() { self.log.push_back('verified'); }
}
#[main]
fn main() {
self.team.run();
pln(self.team.log);
}run(steps = ['check']) runs just the steps you name. See Object Run.
HTML and XML
0.10.7 adds html and xml formats, so a document can become a page, a component tree, or an XML file. An object is an element, and its fields, in order, are what's inside it. #[tag] names an element, #[attr] makes a field an attribute, and #[text] writes a value as text:
#[type]
#[tag('li')]
Plan: {
#[attr('data-id')] str id: ''
#[text] str name: ''
}
#[tag('ul')]
plans: {
#[attr('class')] kind: 'plans'
list items: [
new Plan { id: 'free', name: 'Free' },
new Plan { id: 'pro', name: '<b>Pro</b>' },
]
}
#[main]
fn main() {
pln(stringify('html', self.plans));
}The HTML is safe to put in a page, whatever the document holds, including a view a model wrote. Text and attribute values are always escaped, scripts, styles, frames, event handlers, and javascript: URLs are never written, and a host can allow exactly the elements it renders with doc.allowHtmlTags([..]). Functions marked #[attr] or #[text] are called when the object is exported, async ones included, so part of a view can be computed. XML parses back too: parse(src, obj, 'xml'). See Formats.
Editing Stof Text in Place
Exporting a document again rewrites all of it. When people also edit the text by hand (Ex. a settings page saving into a hand-written policy), 0.10.8 can change just what you name, by path, and leave everything else exactly as it was: comments, formatting, and every other definition.
const text = `// Pricing for the Pro plan
pro: {
price: 20 // per seat
seats: 5
}`;
const next = StofDoc.edit(text, [
{ set: 'pro.price', value: 24 }, // a JSON value
{ set: 'pro.storage', stof: '50GB' }, // Stof source, added in the object's style
]);
// // Pricing for the Pro plan
// pro: {
// price: 24 // per seat
// seats: 5
// storage: 50GB
// }
set_fn, remove, and rename work the same way, and StofDoc.outline(text) lists every field and function with its path and source. Nothing in the text runs while it's outlined or edited, so it's safe to use on text a user or a model sent. It's in Python (Doc.edit) and Rust (stof::parser::edit) too. See Using Stof in Your App.
Readable Stof Export
stringify('stof', obj) now writes Stof a person or a model can read and edit, instead of the exact graph form: objects with their types and attributes, values as literals (50GB, set(..), map((k, v))), and functions as their source:
#[type]
Plan: {
str name: ''
fn monthly(seats: int) -> float { seats * self.price }
}
Plan pro: {
name: 'Pro'
price: 20
storage: 50GB
features: set('sso', 'audit')
}
#[main]
fn main() {
pln(stringify('stof', self));
}Keeping each function's source costs memory, so apps turn it on before parsing with doc.keepSource(). Without it, functions are written as data blocks, which still load and run. The CLI and this site keep source. stof:graph is the exact form, with object IDs and compiled functions. See Formats.
Smaller Additions
Lib::func()always calls the library, even when an object or variable has the same name:Num::round(x, 2).Lib?::func()gives null when the library isn't there, which is handy for optional host libraries.- Null-safe calls anywhere in a path:
self.plugins?.on_save(). - Qualified type names:
<Geometry.Point>finds the typePointunderGeometry, from anywhere in the document. - Assigning to computed targets:
self.customer(id).plan = 'pro'andlist[0].name = 'a'. - Trailing commas in calls and parameter lists (0.10.3).
- New asserts:
assert_nullandassert_not_null, plusinf()andnan(). - JavaScript: plain objects passed to
callarrive as maps (like Python dicts), library functions can declare parameter names for named arguments, and a rejected promise in an async library function now throws inside Stof, sotry/catchworks. - Python:
Doc.get,set,call, andbinary_exporthave sensible defaults. List.map,filter, andanytake a function (0.10.7):prices.map((p: int): float => p * 1.2).Obj.set(name, value)andObj.unset(name)(0.10.8) set or remove the field with exactly that name, so a name can have dots:limits.set('api.calls', 1000).- A variable declared without a type takes no type from its value (0.10.8):
let x = self.price;and thenx = 'text'works. A declared type still holds.
Fixed in 0.10.6
- Left to right. Operators and template strings evaluated their right side first, so side effects ran out of order. Everything now runs left to right.
- Arrow functions keep their variables. An arrow passed to another function, or stored and called later, now sees the variables around where it was made, and can update them.
- Calls that return nothing give null where a value is expected (
const x = self.log();,f(self.log())), instead of an internal error. - Parsing into an object again merges into its nested objects instead of replacing them, so loading the same config twice, or a partial update, does what you'd expect.
plnin the browser writes to the console.
Fixed in 0.10.7
obj.run()awaits async steps, so each step finishes before the next one starts.- Functions run in the order they're written for
funcs(attributes),#[main],#[test], anddoc.run('attr'). The order used to change between runs. sort_byis stable, and an error in its compare function fails the sort instead of leaving the list unsorted.- A cast that isn't possible says so, with both types: "cannot cast (int, str) to tup".
New in 0.10.9
- Messages on asserts: every assert takes an optional last argument, written first in the error.
assert_eq(total, 42, 'total after the refund')fails with "total after the refund: '43' does not equal '42'". - The message of a caught error:
catch (e, message)gives you the readable message next to the error code, to log or show.eis the same as before, so code that compares codes keeps working. Infinity,-Infinity, andNaNliterals, and JSON, YAML, TOML, and binary documents keep them: JSON writes the strings"Infinity","-Infinity", and"NaN"(it used to writenull) and reads them back as numbers, and YAML uses its own.infand.nan.quiet()turns off everything a document prints (warnings, test progress,pln) for apps that log their own way. Results and errors still come back.- A clearer warning for a common mistake:
{ b: 1 }inside a function is a map whose key is the variableb, not an object. The warning now says so, and showsnew { b: 1 }. - Dropped objects are freed. Every object created and dropped stayed in memory for the life of the document (about 1.5 to 9 KB each). Long-running documents now stay flat.
- A sturdier runtime. A new robustness test runs about 60,000 broken and edge-case inputs on every build, including in CI: every library function with odd values, every format with garbage, and every test file cut off and randomly edited. It found and fixed a hang in
nanoid, crashes in string functions on text that isn't ASCII, an XML export that failed one time in six, and a few integer overflows. In JavaScript, a synchronous call back into a running document now throws a clear error instead of crashing the module.
Faster
- Parsing: a 5,000-line document (the Limitr pricing spec) parses 60 times faster, from 2.9s to 0.05s. Parsing is a runtime operation in Stof, so this matters every time logic is loaded or swapped.
- Calls: function calls are about twice as fast (200,000 calls went from 2.9s to 1.5s), and loops are faster too (a million iterations went from 4.1s to 3.0s).
- Large documents (0.10.4):
drop,funcs(attributes = ..), and method calls on objects with many fields no longer slow down as a document grows.
Half the Memory
0.10.8 cuts what a running document holds by about half. An empty document went from 2.2 MB to 0.24 MB, and the Limitr pricing engine from 7.4 MB to 3.5 MB. That matters when an app keeps a document per customer or per request. Binary documents (BSTF) didn't change: files written by 0.10.7 load in 0.10.8, and the reverse.
Safer, Too
A fuzzing sweep over the test suite (40,000 parsed documents, 20,000 corrupted binary documents) found parser hangs, stack overflows, panics, and an out-of-memory crash in binary decoding. All are fixed: no known input crashes or hangs the runtime. All 13 cargo audit advisories in dependencies are fixed too.
Tools
- A language server.
stof lsp, in stof-cli 0.13, gives editors errors and warnings as you type, an outline, go to definition, hover with doc comments and library docs, completion, find references, and rename. Files in a package are checked together. - VS Code extension 0.3 uses it, and its highlighting is updated for the new syntax. Get it on the Marketplace.
- The CLI exits with an error code when a run, test, or parse fails, so it fits in CI, and
stof test --leakschecks for leftover objects. - A new agent skill. The Stof skill teaches AI coding agents to write correct Stof. It's rewritten from 1,900 lines to about 400, every example in it is tested. In our evaluation, agents using it solved all three tasks on the first try, with every test passing.
- New docs. This site has been rewritten alongside the release, with a cookbook of real uses and a playground with a scratch pad, a test runner, and shareable links.
Breaking Changes
| Change | Before | Now | What to do |
|---|---|---|---|
| Sandbox | Rust and Python documents could use files, environment variables, and the network by default | Nothing outside the document unless the host opts in | Call allow_system() or allow_http() (Rust, Python), or allowHttp() (JS) |
| Paths | a.b found any object named a | a must be a root | Use self.a.b, super.a.b, or root.a.b |
| Function scope | Functions could read their caller's variables | Only their own parameters and variables | Pass values as arguments |
| Math with null | 3 * null == 3 | An error | Use ??, and start totals at 0 |
| Number methods | x.round(2) changed x | Returns a new value | x = x.round(2) |
| Template strings | Could add numbers; null printed as empty | Always a string; null prints null | Format numbers explicitly |
| Imports | Relative to the working directory | Relative to the importing file | Fix paths that assumed the working directory |
return | return x without ; mis-parsed | return x; needs its semicolon | Add the ; |
| Integers | Overflow wrapped; / 0 crashed | Overflow becomes a float; / 0 is inf | |
typeof (0.10.2) | Took the rest of the expression | Binds to the next value | Use typeof (a + b) for an expression |
stof export (0.10.8) | The exact graph form, with IDs | Readable Stof | Use stof:graph for the exact form |
Rust LibFunc params (0.10.8) | params: vector![..] | params: params![..] | Change the macro |
| JSON infinity and NaN (0.10.9) | Written as null | Written as "Infinity", "-Infinity", "NaN", and read back as numbers | Nothing, unless another reader expects null |
| Printed infinity (0.10.9) | inf, -inf, NaN | Infinity, -Infinity, NaN | Update text comparisons |
| JS calls during a step (0.10.9) | A synchronous call from a library function into the running document crashed the module | Throws "the document is busy"; async calls (await doc.call) work as before | Call back with the async methods |
The full changelog has every change, including the Rust API details.
Tell Us
If something breaks when you upgrade, or you build something with Stof, tell us on Discord or open an issue on GitHub.
