Scripting the workbench¶
Audience: language authors and anyone extending the workbench · ~10 min read · Prerequisites: The Language Editor
What it is¶
The workbench API lets code call what the workbench does: read and edit the model, run the checks, the generator and the
type checker, run a program, run tests, parse and print text, undo and redo. The same object, workbench, is available in the
Model Console and inside the code of a concept (a check, a constraint, an intention, a generator, a
type rule). This page covers the first release of it. The design and the plan for the rest are in the
developer guide.
Where contributions show up
In the Theia IDE (browser and desktop) a command you register, and the status entries, menu entries and panes a script or language contributes, are drawn: in the
menus, the command palette and the status bar, with their tooltips and key bindings, and removed again when you dispose them. The standalone webview lists registered commands under Tools > Registered Commands; it and VS Code record
the other contributions but do not draw them yet (workbench.ui.drawsContributions is false there). Calling something the host lacks fails with an UnavailableError that says why.
When you'd use it¶
- A check or intention needs a result the model does not hold (run the generator, ask for the type of another node).
- You want a one-off batch edit that is one undo step and rolls back if it fails.
- You are writing a plugin and need one stable entry point instead of importing engine modules.
Where workbench comes from¶
- In the Model Console it is a name you can use:
workbench.checks.run().errors. - In concept code every hook context carries it, lazily, so a hook that does not use it pays nothing:
// a check that warns about an expression that prints very long
check({ node, lang, workbench, report }) {
const text = workbench.surface.print(node, { lang });
if (text.length > 200) report.warn("this expression prints as more than 200 characters");
}
report, report.warn and report.error take the node to flag as a second argument and the problem in plain words as a third:
report.warn("rate is blank", undefined, { reason: "The interest rate is missing.", hint: "Click the blank spot and type a value." }).
The message stays the developer text; workbench.checks.run().issues and strukts check --json hand the plain words on as explain.
Which model a call means
A call that does not name its target (workbench.model.active(), workbench.checks.run() with no root) uses the active
model, and in this release only a host that registers one provides it. Today that is the Model Console, while it is
open. From a hook, pass what you already hold, as above (lang, and root or a node where a call takes one). Keep hook
calls cheap: reading and printing are, but running the generator or the whole check pass once per node is not.
workbench.capabilities says what this host can do. A call to something the host lacks throws UnavailableError; branch on
workbench.capabilities.has("editor") when a script must work headless too.
Read the model¶
workbench.model.active() is the model open in the editor. It returns the same fluent objects the console uses
(nodes, roots, ancestors, child, property).
const model = workbench.model.active();
assert(model.nodes("Plus").length === 1, "one plus in the sample");
const result = workbench.checks.run();
assert(typeof result.errors === "number");
return result.issues.length;
Build a node by hand¶
workbench.model.node(head, ...children) builds a node of the concept head holding children (values, nodes, or handles, which are copied). It is not
attached anywhere. A head whose concept is registered gives a real concept instance, which a hand-written { id, head, children } does not; the children
are not checked against the concept's slots. The result is a raw node: print it, wrap it with model.of, or put it in a parent's children.
const sum = workbench.model.node("plus", 1, 2);
assert(sum.head === "plus" && sum.children.length === 2, "built by head");
const text = workbench.surface.print(workbench.model.node("block", sum));
assert(text.includes("1 + 2"), "printed: " + text);
return text;
Edit atomically¶
workbench.transaction(fn) runs fn as one step: one undo entry, one model.changed event. If fn throws, every edit is
rolled back and the error is rethrown. fn must be synchronous. A transaction can touch several roots or models; undo then
reverts them together.
const stmts = () => workbench.model.root().children("stmts");
const before = stmts().length;
// the statement of "y = 4", taken from a parsed copy; the root's first slot is its name, the statements are in `stmts`
const added = workbench.model.of(workbench.surface.parse("y = 4\n")).roots()[0].children("stmts")[0];
workbench.transaction(() => workbench.model.root().append("stmts", added), { label: "add y" });
assert(stmts().length === before + 1);
let failed = false;
try {
workbench.transaction(() => {
stmts().at(-1).delete();
throw new Error("changed my mind");
});
} catch {
failed = true;
}
assert(failed && stmts().length === before + 1, "the failed transaction left the model alone");
A transaction covers the active model by itself. To edit another model of the project, fetch it with
workbench.project.model("name") and name it in the transaction, so it is rolled back, undone and canonicalized with the rest:
workbench.transaction(fn, { also: [workbench.project.target("name")] }). An edit to a model you did not name still applies,
but it is not part of any undo step.
Headless models and undo
With an editor open, edits go through the editor and its normal undo. A headless model (a script that holds roots) has its own undo stack, and the transaction is the unit of undo: edits made outside a transaction are not undoable there.
Undo, redo and snapshots¶
const stmts = () => workbench.model.root().children("stmts");
workbench.history.mark("before");
const n = stmts().length;
workbench.transaction(() => stmts().at(-1).delete(), { label: "drop last" });
assert(stmts().length === n - 1);
assert(workbench.history.undo(), "undid the transaction");
assert(stmts().length === n);
workbench.transaction(() => stmts().at(-1).delete());
workbench.history.restore("before");
assert(stmts().length === n, "restored the marked state");
Run tools¶
The generator, the type checker, the evaluator and the tests are all one call. run and tests.run return a Task: await
it for the result, or call cancel() to stop it at the next step.
const task = workbench.run.run();
const { output } = await task;
assert(output.join("").includes("3"), "printed the sum");
return output;
run.run() returns the raw value of the last statement. To compare it with text, run.format(value) prints it in the notation of the language's own grammar
(a KernelF list as list(1, 2), a record as #P{x = 1}), and in Core's notation when the grammar has no formatter of its own.
const { value } = await workbench.run.run();
const text = workbench.run.format(value);
assert(typeof text === "string", "formatted as text");
return text;
const node = workbench.surface.parse("z = 1 + 2\n");
const text = workbench.surface.print(node);
assert(text.includes("z = 1 + 2"));
return text;
The quiet variants are for the editor's own plumbing
checks.results, types.analyze/types.infer, surface.parseRaw/parseChecked, generator.plan({ resolveLang }) and run.createEvaluator are the same
engine calls the IDE makes after every edit. They return the raw result (per-node maps, an evaluator you drive yourself) and write no audit entry and
fire no event, so use checks.run, run.run and the rest in scripts: those are the audited ones, and what a listener or the audit log will see.
Listen for changes¶
workbench.on(event, handler) returns a disposable. A handler that throws is reported and the others still run. A handler
that edits the model has its edit queued until the current event finishes, then applied as its own step; a loop of such
edits stops at a depth limit with a clear message.
Anything you register on behalf of a language or script should go through an owner, so it disappears when that owner does:
const stmts = () => workbench.model.root().children("stmts");
const extra = () => workbench.model.of(workbench.surface.parse("w = 0\n")).roots()[0].children("stmts")[0];
const seen = [];
const scope = workbench.owner("script:demo");
scope.on("model.changed", (e) => seen.push(e.label));
workbench.transaction(() => workbench.model.root().append("stmts", extra()), { label: "from demo" });
assert(seen.join() === "from demo");
scope.dispose();
workbench.transaction(() => stmts().at(-1).delete(), { label: "after dispose" });
assert(seen.length === 1, "the disposed owner no longer hears events");
Every edit and run is also written to a bounded in-memory log: workbench.audit.query({ kind: "transaction" }). Wrap code in
workbench.withOrigin("action:myAction", () => ...) to label what it causes.
Project scripts¶
A script is the body of an async function with workbench, args, log and cancelled(); return gives its result.
workbench.scripts.run(text) runs text you hold. A project can also keep scripts in files named *.script.js (found up to four
folders deep, skipping node_modules, generated and build) or list them in project.json:
{
"scripts": [{ "name": "tidy", "file": "tools/tidy.js", "description": "Normalise the model" }],
"triggers": [{ "on": "open", "script": "tidy" }, { "on": "save", "script": "report" }]
}
workbench.scripts.list() lists them, workbench.scripts.runFile("tidy") runs one, and workbench.scripts.fire("open") runs the
open triggers in order (a failing or untrusted one is reported in the result and the rest still run). A script found in a
project is arbitrary code, so the host must say it is trusted first; a host that has no trust policy runs nothing it
discovered. From the command line that decision is --trust-project-code. Edits a script makes inside workbench.transaction
carry the origin script:<name> in the audit log.
The Workbench Scripts sample (File > Load Sample…, or samples/workbench-scripts/ in the repository) is a ready-made project (the IDE puts the scripts in your copy of the sample, so Run Workbench Script… finds them straight away) with three scripts (a report, an atomic edit with
arguments, an open trigger), the project.json that lists them, and the exact commands to run them. Its scripts are tested on every test run.
In the IDE¶
Run Workbench Script… (Tools menu, or the command palette) lists the project's scripts, asks which to run, and shows what it logged and returned in the Messages panel. The first time you run a script, and again after you change it, the IDE asks you to confirm: it is JavaScript with access to the project's files. Your approval is remembered for that exact text. In a restricted workspace (VS Code's Restricted Mode) no project script runs at all, approved or not.
project.json triggers run on their own when a project opens ("on": "open") and after the model is saved ("on": "save"). Because
nobody chose to run them at that moment, a trigger runs only a script you approved before, whatever the trust setting; any other
trigger script is skipped with a Messages line that tells you to run it once with the command. A trigger that edits the model makes the
app save again, so triggers do not fire again for a short while after one ran, and not while one is running.
Scripts and tests¶
A script does something; a test expects something. When you want to check what the workbench API does to a model (and have the result in the Tests pane,
strukts test and Verify), write it as a JS test: describe / it / expect with the same
workbench, each test on its own copy of the model. workbench.tests.run() runs a model's tests from a script; it takes an optional trust hook
(default: the same trust the script itself runs under).
Files, programs and prompts¶
These need something from the host, so each is off until the host provides it (check workbench.capabilities). Every call
returns a promise.
workbench.fs:read,readJson,list,exists, and, where the host allows writing,write,writeJson,mkdir,remove. Paths are relative to the project folder;.., absolute paths and drive letters are always refused.workbench.shell.run(command, args, { cwd, timeoutMs }): runs a program with an argument list (no shell, so nothing is expanded) and resolves with{ code, stdout, stderr, timedOut }.workbench.prompts.ask / confirm / choose: ask the person. A headless run has nobody to ask, so answers are supplied up front (--answer 'label=value'); a prompt without an answer fails the script instead of waiting.await workbench.project.save()writes the model back to its files (where the host can write);workbench.project.models()andworkbench.project.model(name)reach the project's other models.
// the cookbook host answers up front, like a headless run
const name = await workbench.prompts.ask("Who?");
assert(name === "Ada");
assert((await workbench.prompts.confirm("Sure?")) === true);
The screen: messages, cursor, windows, preferences¶
workbench.ui.message(text, level) writes to the Messages panel; workbench.ui.selection() and select(nodeId) read and move the
editor's cursor; workbench.ui.panes.list() / open(id) / close(id) control the bottom tool windows (in the standalone app; in Theia
the windows belong to Theia and ui.panes is off). workbench.prefs.get / set / list read and write the same preferences as the
Settings page, and workbench.on("prefs.changed", ...) hears a change made there.
workbench.ui.message("hello from a script", "warning");
const rows = workbench.prefs.list();
assert(rows.length > 0, "the host lists its preferences");
const flag = rows.find((r) => typeof r.value === "boolean");
workbench.prefs.set(flag.key, !flag.value);
assert(workbench.prefs.get(flag.key) === !flag.value);
workbench.prefs.set(flag.key, flag.value);
A status entry, menu entry or pane that a language or script adds goes through workbench.ui.status.add, workbench.ui.menus.add and
workbench.ui.contribute.pane. Each needs an id, a label (its accessible name) and a description (tooltip and screen-reader text);
an entry without them is refused. Pass an owner id so the entry disappears with it. A host that draws contributions says so in
workbench.capabilities (ui.contributions); the IDE does not yet.
Git and collaboration¶
workbench.git.status(), branches(), log(n) and diff(file) read the project's repository; stage, unstage, stageAll,
commit(message), checkout, fetch, pull and push change it and need the separate git.write capability. They go through the
same code as the Source Control views, so a script and the views never disagree. workbench.collab.state(), isActive(), isHost()
and participants() report the Live Model Session; starting or joining one stays in the UI.
In an embedded editor¶
mountEditor(...) returns a handle with a workbench over that one editor: the model, the editor, checks, generator, run, types,
history and events work on it. Everything that needs a project, files, Git, a debugger or the IDE's windows reports
UnavailableError, and workbench.capabilities says which.
Contribute actions, commands and listeners from a language¶
A concept can offer more than its own editing behaviour. Its contributes() method returns actions (offered on a node,
named in menus), commands (callable by id) and event handlers:
class Report extends Concept() {
head = "report";
contributes() {
return {
actions: [{
id: "refresh",
label: "Refresh this report",
menus: ["context", "palette"],
isApplicable: ({ node }) => node.children.length > 0,
run: ({ node, workbench }) => workbench.transaction(() => { /* edit the node */ }, { label: "refresh" }),
}],
commands: [{ id: "reports.count", run: (args, { workbench }) => workbench.model.active().nodes("Report").length }],
events: { "checks.finished": ({ errors }, { lang }) => { /* react */ } },
};
}
}
In the IDE the active document's language (and the languages it imports) is activated for you while the document is open, and withdrawn when you move to another language. An action that lists "context" in its menus appears in the editor's right-click menu under Actions, for the node under the cursor and only when its isApplicable accepts it. Elsewhere, nothing is live until the language is activated: workbench.languages.activate(lang) registers everything its
concepts declare under the owner language:<name>, and deactivate (or disposing the returned handle) removes it all.
A subconcept inherits its parent's contributions; an action with the same id replaces the parent's for the subconcept's
nodes. workbench.actions.list({ node }) shows what applies to a node, workbench.actions.run(id, { node }) runs one, and
workbench.commands.execute(id, args) runs a command. Every run is audited with the origin action:<id> or
command:<id>.
You can register a command without a language too; give it an owner so it disappears with it:
const owner = "script:demo";
workbench.commands.register({ id: "demo.add", label: "Add", run: ([a, b]) => a + b }, owner);
assert(workbench.commands.has("demo.add"));
assert(workbench.commands.execute("demo.add", [2, 3]) === 5);
workbench.owners.dispose(owner);
assert(!workbench.commands.has("demo.add"), "gone with its owner");
A language cannot rewrite itself
Code that runs for language L (a check, an action, a command) gets a workbench whose languages write methods refuse to
modify L while it runs, and throw InvalidEditError. It may edit any other language. A project script, which belongs to no
language, may edit any.
Edit a language¶
workbench.languages can create a language and change its concepts and enums with the same calls the Language Editor uses.
A change tells you which nodes of the open model lost their concept (orphans); nothing is deleted behind your back.
Persist with await workbench.languages.save(language).
const demo = workbench.languages.create({ name: "cookbook-demo", concepts: [{ head: "thing", slots: [] }] });
try {
assert(workbench.languages.concepts("cookbook-demo").some((c) => c.head === "thing"));
const gone = workbench.languages.deleteConcept(demo, "thing");
assert(typeof gone.orphans === "number");
workbench.languages.setConcept(demo, { head: "item", slots: [] });
assert(workbench.languages.find("cookbook-demo").getConcept("item"));
} finally {
workbench.languages.remove(demo);
}
assert(workbench.languages.find("cookbook-demo") === null);
A language can declare the API major it was written for in its language.json ("apiVersion": "0"). Activating a language
whose major differs from the workbench's returns a warning (activation.warnings) and is audited; it still activates.
Commands¶
workbench.commands.list() lists every command you can run: the application's own (everything in the command palette and the menus)
and the ones languages and scripts registered. workbench.commands.execute(id) runs one and returns what it returned. An application
command runs through the active document's handlers, so one the document cannot run right now (for example Run Generator in a
document without a generator) fails with UnavailableError; each row's runnable tells you beforehand. Registering a command with an id
that is already an application command is refused. Every run is audited with the origin command:<id>.
A command you register can say where a host with menus lists it and which key runs it: menu ("file", "edit", "view", "run", "navigate", "tools" (the default) or "help") and keybinding (in Theia's grammar, e.g. "ctrlcmd+alt+k"). A command with a description shows it as the menu tooltip. A key binding that collides with an existing one is refused: the command is not drawn and a warning says why.
const rows = workbench.commands.list();
assert(Array.isArray(rows));
assert(rows.every((r) => typeof r.id === "string" && (r.source === "registry" || r.source === "host")));
Find your way around¶
workbench.help() lists every namespace with a one-line summary and marks the ones this host does not provide; workbench.help("git")
lists one namespace's members and says why it is off. workbench.describe() returns the same as data (namespaces, capabilities,
who registered which listener, action, command or contribution), which is what an API explorer draws.
const text = workbench.help();
assert(text.includes("checks") && text.includes("transaction"));
const d = workbench.describe();
assert(d.namespaces.some((n) => n.name === "model" && n.available));
assert(workbench.help("checks").includes("run"));
In the Model Console, print(workbench.help()) shows the list, and typing workbench. (or workbench.checks., ...) offers the API's members from the live object. Workbench API Explorer (command palette, Tools) shows the same in a window: every namespace on this host, which are unavailable and why, and what languages and scripts have registered.
Typings for your language¶
workbench.languages.typings() returns a TypeScript declaration generated from the language: the concept heads, their
capitalised names and every concept's slots. It is virtual: generated in memory, never written to disk.
const dts = workbench.languages.typings();
assert(dts.includes("type Head ="));
return dts.length;
Errors you will meet¶
| Error | When |
|---|---|
NotFoundError |
a node id, language name or snapshot does not exist |
UnavailableError |
the host lacks the capability (for example no editor is open) |
InvalidEditError |
an edit was refused, or a transaction body was asynchronous |
CancelledError |
a task was cancelled |
All extend WorkbenchError, which carries a stable code.