How-to guides › Write handlers in TypeScript or Python

How-to guides

Handlers in TypeScript or Python

A project's behaviour can live in .py or .ts files beside the model, where your editor's tooling helps. archec binds each function to its place in the model by name. It copies the code into the Arche project, and brings back code you edit in the Arche app. This page is about those files; the contract with Arche is handlers.md.

A first code file#

Save this as main.arche. The counter's fn main has no body in the model: it takes the def main of counter.py.

project "Counter" {
  handlers python
}

message TICK { n: int32 }

component Counter "Counter" {
  code "counter.py"
  out tx: data sends TICK
  var n:  int32 = 0
  fn main
}

component Display "Display" {
  in rx: data receives TICK
}

system Desk {
  part counter: Counter
  part display: Display
  counter.tx -> display.rx
}
Diagram: Desk
What archec draws from this code: Desk

And this as counter.py, beside it:

from arche import *

async def main(self):
    while True:
        await wait(ms(10))
        self.n += 1
        send(self.tx, TICK(n=self.n))

Run it:

$ archec sim main.arche --for 30ms
Counter — system Desk, 30.000 ms simulated
   10.000 ms  counter.tx → display.rx  TICK {"n":1}
   20.000 ms  counter.tx → display.rx  TICK {"n":2}
   30.000 ms  counter.tx → display.rx  TICK {"n":3}

3 message(s), 0 state change(s)

archec stubs main.arche writes a typed arche package, so your editor knows the names from arche import * brings in. It writes the package in .arche/typings, not beside your code:

$ archec stubs main.arche
✓ .arche/typings/arche/__init__.pyi
✓ .arche/typings/arche/_model.pyi
  pyright: extraPaths = [".arche/typings"] under [tool.pyright] in pyproject.toml · mypy: mypy_path = ".arche/typings"

__init__.pyi holds Arche's helpers, and is the same for every model. _model.pyi holds this model's messages and constants. The VS Code extension writes the same files on its own, and Pylance finds them with no setting (see editor.md).

On the command line, tell the checker where the package is. In pyproject.toml:

[tool.pyright]
extraPaths = [".arche/typings"]

[tool.mypy]
mypy_path = ".arche/typings"

Use pyright's extraPaths, not stubPath: with stubPath pyright finds the names but warns that the module has no source.

  • A main file with another name has its own folder: archec stubs bench.arche writes .arche/typings/bench/arche/, and prints the path to use.
  • --out <dir> writes the package in the folder you name.
  • --beside writes one arche.py beside the .py files, as earlier versions did.
  • The folder has its own .gitignore: git ignores it, and it is written again from the model.

The handler language#

A project says the language its behaviour is written in:

  • project { handlers typescript }. This is what archec new writes.
  • python.
  • arche: the action language, which archec translates.

TypeScript bodies get self. When a message triggered them, they also get msg, an object { name, …fields }. The API is Arche's: await wait(ms(10)), send(self.out, MSG({ f: 1 })), await goto("Run").

archec reads TypeScript without TypeScript installed. It runs it in archec sim, writes .arche/typings/arche.d.ts for the editor (archec stubs), and tells Arche the language in simulation.yaml. For an example, see examples/ts-handlers.

Some TypeScript is portable: it keeps to what the action language says. That is assignments, if, while, counted for, send, goto, wait, log, Math, the part's functions and msg.field. archec gen --target c|embassy|go translates portable TypeScript as it translates ```arche, and archec difftest compares it with its C. For anything else, archec check names the construct (ts-portable), and the generated code has a TODO (handlers.md).

To move a model to another language, run archec convert-handlers main.arche --to typescript (or python, arche). It rewrites the model's blocks, code files and guards in place.

  • From ```arche, the result is exact.
  • From Python and TypeScript, it goes statement by statement.
  • What does not translate is kept as a TODO(convert) comment. archec check keeps reporting it until you rewrite it.

Code in .py and .ts files#

This section is about Python bodies kept in .py files beside the model. The next one is about the way back from the Arche app and the simulator.

A body that the action language can say reads better as a ```arche block: see concepts. Longer code reads better in a .ts or .py file, with your editor's tooling. A .ts file binds the same way; its functions look like export function main(self: Ctrl) { … }.

component ctrl {
  code "ctrl.py"
  fn main                                  // ← def main(self) in ctrl.py
  in sense: i2c receives SAMPLE { on-receive on_sense }
  states { state Off; state On { on-enter enter_on } }   // on-exit: def on_exit_On, by its name
}
Diagram: ctrl
What archec draws from this code: ctrl

How a def binds to the model:

  • A fn with no block takes the def of the same name.
  • Every code property takes the def it names: on-enter, on-exit, on-receive, on-write, body, and a transition's / action.
  • Some names bind with nothing written: on_enter_<State>, on_exit_<State>, on_receive_<port> and on_write_<MEMORY>.
  • code on the project or on a system is a shared file. Its defs bind only when they are named.
  • A def's parameters are self and the fn's arguments. For a hook, they are the names Arche gives that hook: msg, rise, from_, writer, and so on.
  • A def with no self is a plain function, as a library's .py has them. It binds to a fn whose parameters have the same names, in the same order: def gcd(a, b) binds to fn gcd(a: int64, b: int64) -> int64. A bare fn gcd, which says no parameters, takes the def's.
  • A def's docstring becomes the element's description.

Arche keeps Python inside its project files. So archec copies each body in. The Arche project is the same as the one you would get with the same code written inline.

  • archec fmt --extract-code --write moves existing blocks out to files: one file per component, or one file with --extract-code=behaviour.py. It is tested to change nothing in the result.
  • The imports, constants and helper functions at the top of the file are copied into the bodies that use them.
  • Each body gets its own copy. So a top-level name cannot keep state between calls, and a function that changes one is an error. Keep state on the component instead (var n, self.n).
  • from arche import * is for the editor only. archec stubs writes a typed arche package in .arche/typings, with Arche's helpers and the model's messages and constants. The VS Code extension writes it on its own. Then Pylance or pyright complete and check the code.

Python that the action language cannot say#

Some Python has no translation: a list that grows, a dict, an int past 64 bits, numpy. Such a body still runs in simulation:

  • archec sim runs it in a real python3, and the page in Pyodide (sim.md). A code "x.py" file is loaded as a module, so its imports, helpers and classes are there.
  • Arche's simulator runs it, as it runs all Python.
  • archec sim main.arche --doctest runs the file's doctests.

Two properties say what such code needs:

component Primes {
  simulation-only                 // it runs in simulation and on a host, not on a microcontroller
  pip "sympy>=1.12"               // what its Python imports; archec sim prints the pip command when missing
  code "primes.py"
  fn primes_below(n: int64) -> any
}
Diagram: Primes
What archec draws from this code: Primes
  • simulation-only: the C, C++, Rust (Embassy) and Go generators refuse a deployment that puts it on a microcontroller, and say why. A process on Linux keeps it. (sim.md)
  • pip: the packages, as pip takes them. pip "python>=3.14" asks for a Python version: archec sim then looks for python3.14 on the PATH.

A value that is a list, a dict or an object is typed any in the model (or T[], or a struct with the dict's keys). sim.md says how each value crosses.

The way back: code edited in Arche, and simulator errors#

Every build writes .archec/sourcemap.json into the project. It records where each piece of code comes from, and the text it had.

Code edited in the Arche app goes back to its source#

archec pull main.arche --write compares three things:

  1. what the last build wrote;
  2. what the Arche project holds now;
  3. what your sources give now.

Code changed only in Arche is written back where it came from: into the def of the .py file, or into the ``` block of the .arche file. A def becomes async def if the new body awaits.

  • Code changed on both sides is a conflict. It is left for you to merge.
  • A change to the top-level code copied into a body is left for you too. Edit that in the .py file.
  • A build refuses to overwrite code that was edited in Arche and not pulled. --force drops that code.
  • In VS Code, saving in Arche offers the pull. The setting arche.pullOnChange is ask, always or never. The pull is applied as one edit you can undo. Arche: Pull Code Changes does it by hand.

Only code comes back. Positions, names and other edits made in the app are still overwritten by the next build.

Simulator errors point at your lines#

Arche reports an error on a line of its copy, for example ZeroDivisionError (Controller › Control loop, line 4).

  • archec test and archec run build, run arche-cli, and add the source line: (Controller › Control loop, line 4 → ctrl.py:32).
  • archec where main.arche "<error>" does it for any text. So does arche-cli test out | archec where main.arche -.
  • In VS Code, Arche: Run Tests puts each error on its line in the Problems view. Arche: Go to Simulator Error… takes an error pasted from the Arche app.
  • A state's on-enter and on-exit share one label in Arche's messages. So both lines are offered.

Limits#

These limits are described above; here they are in one place.

  • Python that the action language cannot say is not translated: archec gen writes a TODO for it on a host, and refuses it on a microcontroller when the component says simulation-only. It runs in simulation only.

  • convert-handlers translates Python and TypeScript statement by statement. What it cannot translate stays as a TODO(convert) comment for you to rewrite.

  • A top-level name in a .py file cannot keep state between calls: each body gets its own copy. Keep state on the component.

  • A change to top-level code that was copied into a body is not pulled back from Arche. Edit it in the .py file.

  • Only code comes back from the Arche app. Positions, names and other edits made there are overwritten by the next build.

  • A state's on-enter and on-exit share one label in Arche's messages, so an error there points at both lines.