Table of Contents

πŸ‡«πŸ‡· Version franΓ§aise

Driving crews from the REPL β€” the .cmd.ts β†’ crew.ork.ts bridge

A scripted command is a control plane: it parses what you typed and decides what should happen. A crew is an engine: it does the work. The seam between them is the script-host service, and this page documents that seam β€” the pattern behind an agentic coding assistant built on Orkeon's scripted stack, where *.cmd.ts commands (Orkeon.Cli.Commands.Scripting) drive crew.ork.ts crews (Orkeon.Scripting) over C# ToolBase tools.

Everything below is shipped and runnable from a clone. The ## Run it section at the end launches it.

Architecture: control plane vs engine

REPL (Orkeon.ConsoleApp --runner=scripted-commands)
  β”‚  parses "/cmd args" + free text
  β–Ό
*.cmd.ts  (Orkeon.Cli.Commands.Scripting)              ══ CONTROL PLANE ══
  defineCommand (sync) / defineAsyncCommand (async)        never does the work itself
  β”‚                         β”‚                          β”‚
  β”‚ tools.*  (direct ops)   β”‚ services.get("script-host")β”‚ services.get("commands")
  β–Ό                         β–Ό  .runCrew / .runCrewAsync   β–Ό  .request / .post
ops thin              ══ ENGINE: crew.ork.ts ══       living agent .onCommand(env)
/hello /crews         ScriptHost.RunFromFileAsync       (lightweight reply, no ctx)
                      .body() / ctx.llm.act / budget
                                β”‚ tools.<camelCase>(params)
                                β–Ό
                      C# tools (IBaseTool / ToolBase)
                                β”‚
                      ISessionBufferService Β· ICategoryMemoryStore Β· ICostBudgetManager

The rule the diagram encodes: the command registry is a control plane, not a concurrency engine. All TypeScript runs in Jint β€” single-threaded, with an event loop but no timers β€” so a command, sync or async, never does long work itself. It talks to a host-side engine through the service whitelist, and script-host is that engine for crews. The dispatch side of the same rule is in TypeScript CLI commands.

The script-host service (cmd β†’ crew bridge)

ctx.services.get("script-host") exposes ScriptHostFacade:

Method Semantics
runCrew(name, input?) Loads <crews-dir>/<name>/crew.ork.ts, runs it via ScriptHost.RunFromFileAsync (honours .body() + ctx.llm), waits, returns CrewRunOutput ({ ok, summary?, artifacts?, streamed, error? }). Short crews: the wait is bounded by RunCrewTimeout (below), past which the script receives a TimeoutException.
runCrewAsync(name, input?, options?) Posts the run on a pool thread, returns a ticket immediately. Completion drains to a defineAsyncCommand's completed(result) via the same ticket cycle as commands.post. Long workflows. options takes { chain: "continue" }, { onMain: true } (the crew becomes the conversation) and { exclusive: true } (refused while another exclusive launch of the same crew runs: crew 'x' already running (ticket tN)), described in CLI TypeScript commands.
listCrews() Discovered crew names.

An unknown crew is not an exception: runCrew returns ok: false with crew '<name>' not found under: …. runCrewAsync needs the dispatch substrate AddScriptCommands registers, and throws without it.

ScriptHost runs the file procedurally: a crew that ends with globalThis.crew = crew is not handed to an orchestrator here, it is run the way await crew.run() would run it β€” bodies run, tasks ignored (the two shapes). Write the crews this bridge launches in the procedural shape.

A crew is resolved by name against the directories the host was given: --crews-dir is repeatable, each directory is mounted read-only as /crews, /crews-1, … (CliCrewMountBootstrapper), and the crew called review is the file <dir>/review/crew.ork.ts; the first directory that has it wins. input reaches the crew as globalThis.inputs, a JS object parsed from JSON before evaluation by the ScriptHost pre-execution hook, and the crew's globalThis.result comes back as the summary (a string as is, anything else serialised to JSON).

The same resolution can be configured under Orkeon:Cli:ScriptHost (ScriptHostFacadeOptions):

Key Default Meaning
CrewDirectories empty Virtual directories searched in order; --crews-dir appends to it.
CrewFileName crew.ork.ts The entry file looked up under <dir>/<name>/.
RunCrewTimeout 00:10:00 Bound on one synchronous runCrew; zero or negative disables it.

An agent loop in a crew β€” ctx.llm.act

An interactive agent is an agent whose .body() is the loop: it calls ctx.llm.act(prompt, opts), which runs the LLM ⇄ tool-calling cycle over the agent's own tool catalogue until the model stops asking for tools or maxIterations is reached (src/scripting/Orkeon.Scripting/Typings/context.d.ts, act<T> and ActOptions). The tools the model is offered are the built-ins the agent selected with .tools([...]). It is launched as a crew β€” runCrewAsync(name, { prompt, permissionMode }), the crew passing inputs.permissionMode on to act β€” and not via onCommand, which has no ctx and so cannot reach the LLM. Conversation continuity across runs comes from the singleton ISessionBufferService.

ActOptions.system seeds a real role:"system" message ahead of the user prompt, persisting across every iteration of the tool loop. Without it, act() sends a single user message: identity and tool policy travel with user-level authority, and the providers' native system handling (Anthropic top-level system, cache_control) never fires. A conversation-level system message wins over LlmConfig.SystemMessage on every provider.

ActOptions.context seeds the per-turn context (memory, repository state, earlier turns) as a user message of its own, after system and before the prompt. The prompt stays the last user message, the one the guard and route stages of a decision profile judge, so the context cannot dilute the risk of the request; and system stays the same from turn to turn, keeping its prompt-cache hit.

Parallel read-class tool calls. The tool calls of one model turn that are read-class β€” the tool declares Access Read and its name is on the explicit allow-list (file_read, directory_read, directory_search, count_pattern, glob, grep, rag_search, codebase_*, symbol_*, index_status, node_outline, node_read; the shell session is not on it) β€” run concurrently, bounded by MaxParallelToolCalls (default 4) of Orkeon:Tools:ResultLimits. A write call, or one whose access is Unspecified, is a barrier: a read after it waits for it and sees its effect. The results, and the tool messages sent back to the model, keep the call order. Hooks: for each parallel group, onToolCall runs for every read first (sequentially, in call order, on the engine thread), then the executions, then onToolResult in call order; no callback ever runs concurrently with another. When a sibling faults, is cancelled or throws BudgetExhaustedException, the others complete and are recorded, and the first fault is rethrown after the group. In a host that registers the channel with AddConsoleToolApproval, the approvals that concurrent reads ask are serialised (SerializingToolApprovalChannel); orkeon-repl registers its channel directly, so there two concurrent asks are not queued one at a time (Known limitations). The native loops of a YAML crew and the chat dispatcher fan out the same way; the text-fallback sites (the ChatToolDispatcher text path and LegacyTextAgentLoop) stay sequential.

Permissions and budget

The permission gate is a first-class DI service, IPermissionGate (Orkeon.Application.Interfaces.Security) implemented by ModePermissionGate (Orkeon.Infrastructure.Security), consulted per tool call inside ctx.llm.act. Five modes (bypassPermissions, plan, acceptEdits, default, dontAsk), read/write classification from the tool's own IBaseTool.Access declaration (with a curated read-tool table and codebase_/symbol_/index_ prefixes as fallback), fail-closed on unknown tools and unknown modes. In orkeon-repl, a call the mode asks about is put to the operator (y once, s for the session, n no) through the REPL's approval channel; a call the mode refuses, or one the operator refuses, comes back to the model as DENIED: …, its answer from the tool. A host without a channel refuses the asks. All of it sits behind Orkeon:Security:PermissionGate:Enabled (default false), wired by the REPL and RunnerHost (AddOrkeonPermissionGate), no-op when disabled. In the TUI, Shift+Tab cycles the session's default mode. See opt-in subsystems.

Budget is the other bound: process("autonomous") plus .budget({...}) (AgentExecutionBudget, five dimensions).

The session primitives

Three ports carry what a conversation needs to survive between runs:

  • ISessionBufferService (singleton) β€” the conversation buffer: messages, metadata, head+tail truncation, token estimate. Pivot of the loop and the session commands.
  • ICategoryMemoryStore β€” typed memory CRUD over four categories (user/project/feedback/reference): ListAsync(category, newestFirst), AddAsync (returns the id), ReplaceAsync(id, content) (same id and category, CreatedAt set again), DeleteAsync, GetAsync.
  • ICostBudgetManager β€” cumulative cost/token/call telemetry.

Durable session and start-up script

In the REPL the session survives a restart. With Orkeon:Cli:Session:Persist on (the REPL's default when the key is unset), FileSessionBufferService decorates the in-memory buffer and keeps the last session of each project β€” messages, state bag, id and title β€” at <SessionsDirectory>/<project>-<hash>/last.json through IFileSystemService. The project is the physical workspace root the REPL mounts as /workspace; the file is read once at start, rehydrated without re-validation, and written after each turn and when the REPL exits. A corrupt file starts an empty session. session_store reads the rehydrated buffer like any other.

The typed memory of memory_store survives the same way. With Orkeon:Cli:Memory:Persist on (the REPL's default when the key is unset), FileCategoryMemoryStore keeps the entries of each project at <Orkeon:Cli:Memory:RootDirectory>/<project>-<hash>/memory.json β€” the same project slug as the session file, so the two sit side by side. The file is read at the first access and written after every add, replace or delete; the next id is written with the entries, so an id is never reused after a delete. Off, InMemoryCategoryMemoryStore holds the entries for the life of the process.

Orkeon:Cli:Session:StartScript names a script run once after the host is built: an .ork.ts through the script host, any other file as a shell script. Its stdout, path and source are stored in the state bag under SessionStateKeys.SessionStartOutput and prepended to the first free-text turn, so a start-up script can name the open work. A failing script is logged and never blocks the start.

AddOrkeonSessionTools() exposes them to scripts as six tools β€” session_store, session_snip, token_budget, memory_store, session_cost, session_stats β€” catalogued with everything else in the tool inventory. ISessionBufferService.Truncate, behind session_snip and the truncate operation of session_store, counts turns, not messages: a turn starts at a user message and owns the tool, assistant and note messages that follow it, so a cut never separates a request from its answer or a tool trace from the answer that used it. It answers a SessionTruncation (RemovedCount, KeptFromIndex, which always points at a user message or is -1), and a buffer holding fewer turns than asked is left untouched.

Tools in commands (tools.* in .cmd.ts)

Every engine JsEngineFactory builds has the tools namespace, and the CLI factory is constructed with the built-in tools and the LLM provider, so tools.<camelCase>(params) works in a .cmd.ts handler exactly as it does in a crew. That is how a command does a small piece of work itself instead of paying for a crew β€” reading a file, formatting a report β€” while anything long goes through script-host.

Run it

Two directories, two roles. --commands-dir loads the control plane, --crews-dir supplies the engines. Both point at material shipped in this repository, and neither needs an API key:

# The control plane alone β€” the demo commands in the repo
dotnet run --project src/apps/Orkeon.ConsoleApp -- \
    --runner=scripted-commands \
    --commands-dir examples/cli-ts-commands

# The bridge β€” commands that launch a crew by name through script-host
dotnet run --project src/apps/Orkeon.ConsoleApp -- \
    --runner=scripted-commands \
    --commands-dir examples/cli-ts-commands \
    --crews-dir    examples/cli-ts-commands/crews
scripted> /crews
review

scripted> /review src/Program.cs
src/Program.cs: source file β€” worth a read

scripted> /review-bg examples/README.md
  βœ“ [t1] review-bg β†’ crew:review: done
βœ“ review: examples/README.md: not a source file β€” skipped

The demo crew calls no model, which is why this runs keyless; point an agent's .body() at ctx.llm.act and the same bridge carries a real one. Without the REPL, a crew runs straight from the CLI:

dotnet run --project src/scripting/Orkeon.Scripting.Cli -- run examples/scripting/01-hello-world.ork.ts

The bridge itself is covered by ScriptHostFacadeTests in tests/cli/Orkeon.Cli.Commands.Scripting.Tests/, which exercises crew resolution and the ticket cycle without a key.

Where to go next