π«π· Version franΓ§aise
Write a crew in TypeScript
Orkeon crews are usually shown in YAML. They can also be written in TypeScript, in a file
called something.ork.ts, and that surface is larger than the YAML one: agents can carry real
code, tools can be written inline, and a body can drive its own LLM β tool loop.
This guide takes you from one agent to a three-agent crew with a dependency graph and a file on the way out. Every command below runs from a clone with no API key β the runtime falls back to an echo provider when none is configured.
If you want signatures rather than narrative, go to the Scripting DSL reference.
Thirty seconds
dotnet run --project src/scripting/Orkeon.Scripting.Cli -- \
run examples/scripting/01-hello-world.ork.ts
Without its version line and its comment, that file is:
const greeter = agentBuilder()
.name("Greeter").role("Greeter").goal("Greet the user")
.body((input, ctx) => "Hello from Orkeon Scripting!")
.build();
const crew = crewBuilder().name("greeting-crew").withAgent(greeter).build();
globalThis.result = await crew.run();
Three things are already true here and worth naming. agentBuilder(), crewBuilder() and
friends are globals β there is nothing to import. The .body() is the agent: here it
returns a string and no model is called. And the last line, await crew.run(), is not a
detail of style: it selects the engine. Its assignment to globalThis.result is what
orkeon run prints β the run's output and one entry per agent under tasks; without it,
{"result": null}.
The thing to understand first: there are two shapes
A .ork.ts file is handed to one of two different engines, and the file chooses which by
how it ends. orkeon run reads your source looking for an assignment to globalThis.crew.
| Procedural | Declarative | |
|---|---|---|
| the file ends with | await crew.run() |
globalThis.crew = crew |
runs agent .body() |
yes, one per agent | no |
honours withTask, process, manager |
no | yes |
--validate without running |
type-checks and bundles it, never runs it | loads the crew |
These are opposites, not two spellings of the same thing. The procedural engine iterates the
agents and never looks at tasks. The declarative adapter never invokes a .body().
The rule: if you write .body(), you are procedural. If you write withTask, you are
declarative. Never both in one file.
A crew with three carefully written tasks that ends with await crew.run() still runs,
prints a result, and ignores every task; it logs a warning saying so, and the declarative
shape warns symmetrically about the .body() it will never invoke. The run is still wrong,
but not silently. That is the single most expensive mistake in this DSL, which is why it is
the first thing on this page rather than a footnote.
Shape A β the declarative crew
This is the shape for "several agents, several steps, one of them depends on another". The
worked example is
examples/scripting/crew-review-desk/:
three agents review a diff and leave a markdown report.
Agents
// pickTools is not a global: it is the example's own helper (tools/index.ts).
import { pickTools } from "./tools/index.ts";
const scanner = agentBuilder()
.name("scanner")
.role("Change scanner")
.goal("Establish what a change touches, factually and without judgement")
.backstory(`Reads diffs for a living. Reports scope and refuses to speculate about
intent. Everything downstream depends on this being boring and correct.`)
.tools(["file_read", "directory_read"])
.withAutonomousTools(pickTools("diff_stats", "touched_files"))
.maxIterations(6)
.build();
In this shape role, goal and backstory are the prompt (role is required). Vague ones
produce vague agents. The procedural engine does not send them: there, your body's own
ctx.llm calls are the whole prompt.
Tools, three surfaces
An agent reaches tools three ways, and they are not interchangeable:
- Built-ins by name β
.tools(["file_read", "directory_read"]). Resolved from the host catalogue, and in this shape the resolution is strict: a name that is not registered fails the run rather than quietly leaving the agent one tool short. (The procedural engine checks the same names whenctx.llm.actruns: an unknown one rejects the call with anUnknownToolError.) - TypeScript tools as instances β
.withAutonomousTools([...]), built withtoolBuilder(). They travel with the script, so they need no host registration. In the procedural shape a body calls them directly (diffStats.execute({ diff })), andctx.llm.actoffers them to the model next to the built-ins β when the model calls one, itsexecuteruns in the script. - Imperatively, from a body β
tools.fileRead({ path }), camelCased, procedural shape only.
Writing a tool takes a schema and a handler. Note the type argument: TypeScript does not read
your JSON schema, so state the shape it promises or input is unknown.
const diffStats = toolBuilder<{ diff: string }, { added: number; removed: number }>()
.name("diff_stats")
.description("Counts added and removed lines in a unified diff")
.withSchema({
type: "object",
properties: { diff: { type: "string", description: "Unified diff text" } },
required: ["diff"],
})
.execute((input) => {
const lines = input.diff.split("\n");
const added = lines.filter((l) => l.startsWith("+") && !l.startsWith("+++")).length;
const removed = lines.filter((l) => l.startsWith("-") && !l.startsWith("---")).length;
return { added, removed };
})
.build();
Tasks, and the DAG
Tasks carry the work. withContext is what builds the dependency graph: a task that declares
another as context runs after it and receives its output.
const review = taskBuilder()
.name("review")
.agent(reviewer)
.description("Using the scope report, review the same diff. Judge each flag.")
.expectedOutput("A list of findings, each with a verdict and a one-line justification")
.withContext(scan) // <- runs after `scan`, and is handed its output
.build();
expectedOutput is not decoration either β it is the contract shown to the model.
Deliverables
A task can write its output to a file:
.deliverable({ path: "/output/review.md", source: "final_message", format: "markdown" })
source is final_message (the framework saves the final answer), structured_output (it saves
the schema-checked JSON), tool_call (the agent writes the file itself: give it file_write, or
docx_writer, xlsx_writer, image_generation, firefox for those formats, or the load warns and
orkeon run --validate prints a WARNING: line) or none (no file). See
deliverables checked at load.
/output is a virtual mount. Without it the run still succeeds and the file simply has
nowhere to land.
The handoff
const crew = crewBuilder()
.name("review-desk")
.process("sequential")
.withAgents([scanner, reviewer, reporter])
.withTasks([scan, review, report])
.build();
globalThis.crew = crew; // <- NOT `await crew.run()`
Now the definition can be checked without running anything β no key, no model, about two seconds:
dotnet run --project src/scripting/Orkeon.Scripting.Cli -- \
run examples/scripting/crew-review-desk/main.ork.ts --validate
VALIDATION OK: β¦/crew-review-desk/main.ork.ts (agents=3, tasks=3, tools resolved=5)
That check is only available on this shape, and it is a good reason to prefer it: it catches
an unregistered tool name or a task pointing at an undeclared agent before you spend a token.
On a procedural file --validate checks what it can without running it β the version
directive, the types, the esbuild bundle β and prints VALIDATION OK: β¦ (procedural script: bundled, not run); it never evaluates it. Only the entry file's own source is read for the
handoff: a script that assigns globalThis.crew inside an imported helper is procedural, for
orkeon run as for --validate.
Shape B β the procedural script
Here the agent's .body() is the program. Use it when the logic is yours and the LLM is a
subroutine, or when there is no LLM at all.
const calculator = agentBuilder()
.name("Calculator").role("Computer").goal("Sum a list of numbers")
.body((input, ctx) => {
const total = [1, 2, 3, 4, 5].reduce((a, n) => a + n, 0);
ctx.log.info(`computed total = ${total}`);
return total;
})
.build();
await crewBuilder().withAgent(calculator).build().run();
ctx.llm.act β an agent loop in nine lines
act runs the LLM β tool-call cycle over the agent's tools β the built-ins it selected with
.tools([...]) and its withAutonomousTool instances β until the model stops asking for
tools or maxIterations (default 10) is reached. It resolves to { output, iterations }:
.body(async (input, ctx) => {
const run = await ctx.llm.act("Summarise the release note in /script/notes.md", {
system: "You are terse. Two sentences, no preamble.",
maxIterations: 5,
onDelta: (d) => ctx.log.info(d),
});
return run.output;
})
system seeds a real role:"system" message that persists across every iteration. Without
it, act() sends a single user message β identity and tool policy travelling with user-level
authority, and the providers' native system handling never firing. The agent's role and
goal are not added for you: in this shape, system is where they go.
State
An agent can carry state, and there is exactly one legal way to change it:
.withState(() => ({ count: 0 }))
.body(async (input, ctx) => {
await ctx.state.with(prev => ({ ...prev, count: prev.count + 1 }));
return ctx.state.count;
})
with() replaces the state with what the callback returns, under a mutex β so spread the
fields you are not changing. Assigning directly (ctx.state.count = 1) throws: the state is a
proxy whose set trap exists to make that loud rather than lost.
Inputs, memory, errors
const topic = (globalThis.inputs?.topic as string) ?? "coffee";
β¦ run examples/scripting/10-inputs-and-memory.ork.ts --inputs '{"topic":"orkeon"}'
ctx.memory.crew and ctx.memory.agent are scoped key/value stores of the script β not the crew's
memory that .memory(true) turns on, which stores each task's result and recalls the closest ones before
each task, run after run (Memory system).
What the run reports is
globalThis.result β assign it explicitly: a file with a top-level await runs wrapped in an
async function, so its last expression is never the result, and a top-level const result
stays local to the wrapper.
onError returns an action built from a factory β not a string:
.onError((err) => ErrorAction.retry({ delay: 10, max: 3 }))
ErrorAction.fail(), .skip(), .fallback(value), .retry({...}). Returning anything the
runtime does not recognise becomes fail(). The handler receives { code, message, exception, attempt, agent }; branch on err.code (rate_limit, network, timeout, validationβ¦).
Editor setup
Run orkeon typings in your project: it writes orkeon.d.ts into ./.orkeon/, and your
script opens with /// <reference path="./.orkeon/orkeon.d.ts" />. The file comes from the
tool, so it matches the runtime β run the verb again after updating. To pin or diff the
typings of a release, each GitHub Release attaches them as orkeon-typings-<version>.tar.gz
(Editor setup). In a clone, building
Orkeon.Scripting also writes it under that project's bin/<configuration>/net10.0/dist/
from src/scripting/Orkeon.Scripting/Typings/*.d.ts. Then copy
tools/scripting-typecheck/tsconfig.base.json.
Three of its options are load-bearing, and skipping them produces errors that have nothing to do with your code:
moduleDetection: "force"β otherwise top-levelawait crew.run()is rejected (TS1375) and a top-levelconst crewcollides with thecrewglobal (TS2451).target/libES2022β what the engine supports.types: []β there is no Node here.process,requireandBufferdo not exist.
What the runtime actually is
.ork.ts is transpiled by esbuild and executed by Jint. That has consequences worth
knowing before you are surprised by them:
- It is TypeScript syntax, not the TypeScript compiler. The runtime strips types and never
checks them;
orkeon run --validatedoes, withtscwhen it is installed (unlessOrkeon:Scripting:Toolchain:TypeCheckisOff, and before every run when it isAlways) β which is why the tsconfig above matters. - There is no Node and no DOM. No
fs, nofetch, noprocess. File access goes through tools;ctx.signalis a .NET cancellation token, not anAbortSignal. - One thread, no timers. Promises and
awaitwork β every continuation runs on the one thread that drives the script β but there is nosetTimeout. A synchronous host call that waits (the CLI'srunCrew/requestbridges) blocks the whole script; an awaited one (ctx.llm.*,tools.*,ctx.delegate,ctx.receive) only suspends its own chain, and the others keep running. importworks between your own files, resolved relative to the script: esbuild bundles them when the file is run from disk, asorkeon rundoes.
Errors and what they mean
| Message | Cause |
|---|---|
did not assign globalThis.crew |
A runner that loads only the declarative shape (the orkeon-host daemon, a host calling ScriptHost.LoadCrewFromFileAsync) handed a file ending in await crew.run(). |
| The crew runs but every task is ignored | The reverse: withTask in a file ending with await crew.run(). |
Crew configuration references unknown tool(s): x |
A name in .tools([...]) the host catalogue does not have. The message lists every name that is available. |
Agent 'a' lists unknown tool(s) in .tools([...]) (an UnknownToolError) |
The procedural twin: ctx.llm.act refuses to run, before any model call, on an agent whose .tools([...]) names a tool the host does not offer. The message lists what is available. |
FSM transition 'a.b' targets undeclared state 'c' |
A target that is not a key of states. |
stateGraph literal must declare an edge from START |
edges written as an array. It is an object keyed by source node. |
stateGraph 'β¦' has an invalid topology: β¦ Graph has no path from START to END. |
No static route; add one or use a conditional edge. |
StateMutationOutsideWithException |
ctx.state.x = β¦ instead of ctx.state.with(...). |
.concurrency must be positive / .concurrency(1) is the only value accepted |
.concurrency(n) with n β€ 0 or n > 1: an agent's concurrency is a mutex. |
RecursiveAgentInvocationException |
ctx.spawn of an agent with the caller's own name, or ctx.delegate / crew.runAgent of the calling agent itself. |
.llm(...) takes an LlmConfig |
A model name or a { provider, model } literal handed to .llm(...). Write .llm(llm.model("β¦")); the provider is the host's. |
.withAutonomousTool(tool) takes what toolBuilder()β¦build() returns |
A name or a plain object. Built-ins go in .tools([...]). |
| A retry that never happens | onError returning a string instead of ErrorAction.retry({...}). |
Deliberately out of scope
On the declarative path globalThis.inputs is never planted, and budget() bounds the crew
only under .process("autonomous") β any other process refuses the crew; .body() does
nothing there either. There is no conditional-inclusion method β guard the withAgent/withTask
call with an if instead. ctx.llm.embed returns a stub vector. The full list, with what
each one actually does, is in
Design limits.
Where to go next
- Scripting DSL reference β every method, and which shape honours it.
- Scripting DSL β architecture β what the runtime is and where it sits.
- Driving crews from the REPL β running a crew from a
.cmd.tscommand. examples/scripting/β every snippet above, runnable.