# Adopter Agent Guide Source: https://docs.skillscript.ai/docs/adopter-agent-guide Wire your agent's instruction file so it discovers and prefers its skills instead of re-reasoning every session. How to set up your agent's instruction file (`CLAUDE.md`, `AGENTS.md`, system prompt — whatever your harness uses) so the agent actually *takes advantage* of Skillscript instead of ignoring it. Skillscript gives your agent a way to **capture a routine once as a durable, compiled, auditable skill** and run it many times — instead of re-reasoning the same workflow from scratch on every session, burning tokens and drifting a little each time. But an agent only uses skills if its instructions tell it to look. This guide is the minimum wiring to make that happen. *** ## 1. The runtime tells your agent how to use it **You probably don't need to paste anything.** The MCP server ships the usage contract as its `instructions` field — most MCP hosts surface that to the model at session start, so a connecting agent already knows to `skill_list()` first, preflight before composing, author-when-repeated, and never assume a backend. Quick check: after wiring the MCP, ask your agent "what do you know about skillscript?" — if it describes the workflow, you're done, and your `CLAUDE.md` / `AGENTS.md` needs nothing about Skillscript. **If your host doesn't surface server `instructions`** (some don't), paste the block below into your agent file. It mirrors what the server delivers — the authoritative copy is the runtime's `instructions` field, so keep this in sync rather than diverging from it. ```markdown theme={null} ## Skillscript — your durable skills You have a Skillscript runtime wired over MCP. A *skillscript* is a compiled, auditable, reusable procedure — a routine captured once and run many times, rather than re-derived every session. ### At session start List what you already have before doing routine work: - `skill_list()` — returns your skills grouped by category: - **skills** — skills you can invoke directly (template-output skills + skills with no `# Output:` declaration) - **receives** — skills that push augmenting context to you (`# Output: agent: `) - **headless** — autonomous skills (cron/event-fired); yours to maintain, not to invoke Know your own skills so you reach for them instead of rebuilding a workflow. ### When a task smells routine If an existing skill fits, use it — don't re-reason the steps: - `skill_preflight({ name })` — see what a skill takes, returns, requires, and *touches* (its effectful footprint) plus whether it's cleared to run, before you invoke or compose it. (`skill_list` entries already carry this contract, so often you won't need a separate call.) - `execute_skill({ name })` — run a stored skill end-to-end. - `compile_skill({ name })` — preview the rendered plan first, no side effects. ### When you're repeating yourself, author a skill What you can script is the wired connectors, models, and allowed shell binaries that `runtime_capabilities()` reports — that list is your **menu of what's capturable**. When you catch yourself re-running the same multi-step routine over any of them, turn it into a skill: 1. `help()` — learn the language (and `help({ topic })` for ops, frontmatter, examples, composition, error-handling, connectors, lint-codes). 2. Draft the skill body against what's wired. 3. `lint_skill({ source })` then `compile_skill({ source })` — catch mistakes before anything is stored. 4. `skill_write({ name, source })` — it lands **Draft**; a human reviews and approves before it can run (you can't self-approve). If something you'd need isn't wired yet, ask the operator to add it (a connector, or a binary on `SKILLSCRIPT_SHELL_ALLOWLIST`), then capture the routine. ``` That block is enough to change behavior. Everything below explains *why* and fills in the edges. ### What your agent file *should* carry instead Now that the runtime delivers the universal how-to, your agent file gets *thinner* — it should hold only what the runtime can't know: * **Who the operator is.** The usage block says "ask the operator to wire what's missing" — but not *who*. Name them and the channel to ask on. * **Which skills are *this* agent's to maintain.** A skill's `headless` category (in `skill_list`) flags it as cron/event-fired, but "this one is *yours to keep correct*" is an ownership fact the universal block can't carry. Note the autonomous skills the agent is responsible for. * **The agent's role and behavioral context.** Who it is, how it should work. Never Skillscript's to provide; always yours. The test: if it's true for *every* agent on *any* Skillscript runtime, the runtime already delivers it — leave it out. If it's specific to *this* agent or *this* deployment, it belongs in your file. The runtime owns "how to use me"; your file owns "who you are, where you are, and what's yours to tend." *** ## 2. Best practices ### Discover before you build The single highest-value instruction is "run `skill_list()` at session start." Agents that don't enumerate their skills silently re-derive workflows that already exist as skills — the exact waste Skillscript removes. Make discovery a reflex, not an afterthought. ### Prefer a skill over re-reasoning A compiled skill runs the same way every time because the procedure *is* the source of record, not a prompt to be re-interpreted. When a routine exists as a skill, executing it is cheaper, more reliable, and auditable. Reserve fresh reasoning for the work that genuinely needs it. ### Write descriptions as *trigger conditions*, not summaries When the agent picks among skills, it reads each `# Description:`. "Handles errors" is useless for selection. "If a downstream API returns non-200, run this" fires the skill at the right moment. Describe **when to invoke**, not what the skill does. This is what makes `skill_list()` actionable once you have more than a handful of skills. ### Two kinds of skill, two postures * **Skills you invoke** — you call them when relevant (`execute_skill`). * **Skills you own but never invoke** — autonomous skills fired by a `cron` or `event` trigger. Your job is to keep them correct, not to run them by hand. (They show up under `headless` in `skill_list`.) Make sure your agent instructions distinguish these, so the agent doesn't try to manually fire a cron skill (or ignore a skill it should be invoking). ### Trust the approval gate Every skill has a `Draft → Approved → Disabled` lifecycle, and only `Approved` skills run. **In secured mode** (`SKILLSCRIPT_SECURED_MODE=true` — the recommended posture for any agent-authored or multi-author deployment) approval is an operator's Ed25519 signature: a skill an agent `skill_write`s lands **Draft**, a naked `# Status: Approved` is forced to Draft, and only a human holding the operator key can sign it into a runnable state. That's the real safety boundary — an agent can *write* a skill, but a human decides whether it ever *runs*. In unsecured mode the status flag alone gates execution (a bare `# Status: Approved` runs, unkeyed) — convenient for a single trusted author, but it means a skill *you* write as Approved is immediately runnable. Either way, tell your agent to treat a freshly-written skill as not-yet-runnable until a human has approved it. ### Author against discovered capability, not assumptions Before writing a skill that needs a data store, a model, or an external tool, check `runtime_capabilities()`. A skill that assumes a connector that isn't wired fails at dispatch with a clear error — but it's better to author against what's actually present. Use `# Requires: .` in a skill to fail-fast at compile time when a needed capability is missing. ### Keep deterministic work in tools, not skill bodies Skills are orchestration. A fixed API call, a fixed parse, a fixed shell pipeline belongs in an MCP tool the skill *invokes* (`$ ...`), not hardcoded into the skill. This keeps skills portable across substrates and resistant to drift. *** ## 3. MCP tool reference The tools your agent has when a Skillscript runtime is wired: | Tool | Use | | - | - | | `skill_list({ filter? })` | Discover skills, grouped by category. Filter by status / trigger\_kind / name\_prefix / author. Each entry carries the full contract (vars / returns / requires / effectful footprint) + approval state. | | `skill_preflight({ name })` | Pre-execution contract check for one skill: what it takes / returns / requires / touches (effectful footprint) + approval-gate state + version. Call before invoking or composing. | | `skill_read({ name })` | Read a skill's source body. | | `compile_skill({ name \| source, inputs? })` | Render the compiled plan + surface errors. Read-only — safe to preview. | | `lint_skill({ name \| source })` | Static diagnostics (tier-1 errors / tier-2 warnings / tier-3 advisories). | | `execute_skill({ name \| source, inputs? })` | Run a skill. `name` runs a stored, approved skill; `source` runs ad-hoc inline (bypasses the store — for one-offs). | | `skill_write({ name, source, overwrite? })` | Store a skill. Lands Draft unless approved. | | `skill_status({ name, new_state })` | Transition Draft / Approved / Disabled. | | `help({ topic? })` | Language reference — quickstart, plus `ops`, `frontmatter`, `examples`, `composition`, `error-handling`, `connectors`, `lint-codes`. | | `data_read({ mode, query, limit, ... })` | Query the wired DataStore — substrate-neutral memory/data retrieval (the `$ data_read` op's tool surface). | | `runtime_capabilities()` | What's actually wired — connectors, models, shell mode. | | `health_metrics()` | Aggregated runtime health — dispatch counts, error rates, per-op timing. | | `blocked_shell_attempts()` | Shell-allowlist refusals: which binaries skills tried to run that the allowlist blocked. | | `register_trigger` / `list_triggers` / `unregister_trigger` / `set_trigger_enabled` | Inspect/manage autonomous dispatch (cron / event), including enabling or disabling a registered trigger. | *** ## 4. A minimal worked example The smallest useful loop, from the agent's point of view: ``` 1. skill_list() → "I have a `weekly-report` skill." 2. compile_skill({name:"weekly-report"}) → preview the plan, confirm it's right. 3. execute_skill({name:"weekly-report"}) → run it, use the result. ``` And authoring a new one: ``` 1. help({topic:"ops"}) → learn the op surface. 2. lint_skill({source}) → fix tier-1 errors. 3. compile_skill({source}) → confirm it renders. 4. skill_write({name, source}) → stored as Draft. 5. (human approves) → now it can run. ``` *** ## 5. What *not* to put in your agent file * **Don't reference a specific backend.** No "query the X store" / "call the Y model" by product name. Skills name connectors by role; the operator maps roles to backends in config. Your agent reads roles via `runtime_capabilities()`. * **Don't tell the agent a freshly-authored skill is runnable.** In secured mode (the recommended posture) it lands Draft until a human approves; have the agent treat anything it just wrote as not-yet-runnable regardless. * **Don't have the agent manually fire autonomous skills.** Cron/event skills fire themselves; the agent maintains them. * **Don't hardcode tool/endpoint details into skill bodies.** That's tool territory; skills orchestrate, tools execute. The throughline: your agent's instructions should make it **discover its skills, prefer them over re-reasoning, author new ones through the lint→compile→approve loop, and stay honest about what substrate is actually wired.** # Adopter Playbook Source: https://docs.skillscript.ai/docs/adopter-playbook Stand up the runtime, wire your substrates, supervise it as a service, and point your agent at it over MCP. How to wire skillscript-runtime into your deployment. Written for Joe-Programmer: you have your own substrate stack (data store, agent harness, LLM endpoint, filesystem), and you want skillscript to slot in rather than dictate. This playbook covers the load-bearing decisions, the two wiring patterns, and the conventions that keep your local modifications upstream-merge-friendly. ## The four substrates skillscript expects Skillscript-runtime is substrate-neutral and assumes you have (or will choose): 1. **A filesystem** — for skill source files (`.skill.md`), trace records, the bundled sqlite databases. Sandbox via container, chroot, or limited-privilege process — operator's call. 2. **A data store** — for retrieval and writes from skill ops. Could be SQLite-FTS (bundled), a vector database, an in-house store, an Obsidian-style notes system, a memory broker — whatever you already have. 3. **An LLM endpoint** — Ollama running locally (bundled), a hosted API like OpenAI / Anthropic / Azure, or your own inference server. 4. **An agent harness** — where skill output is delivered. Could be tmux sessions, a webhook receiver, an in-house agent runtime, or no harness at all (skills run for their text output only). Each of these maps to a typed connector contract: `SkillStore`, `DataStore`, `LocalModel`, `AgentConnector`. Plus `McpConnector` for any external tool you want to invoke from a skill body. ## What the runtime promises connector implementors You only need to know what methods the runtime will call. Everything else — where data lives, what fields you honor, internal authorization, expiration, indexing — is your implementation choice. The contracts: ``` DataStore — substrate-neutral data persistence query(filters) runtime asks: "find records matching these filters" write(record) runtime asks: "store this; return id + timestamp" get(id) runtime asks: "give me this specific record" manifest() runtime asks: "what can you do?" (capability snapshot) SkillStore — substrate-neutral skill source persistence load(name) "give me this skill's source" store(name, source) "write/version this skill" query(filter) "list matching skills" update_status() "Draft → Approved → Disabled transition" versions(name) "audit trail" metadata(name) "header info without body" delete(name) "remove all versions" manifest() "substrate capability snapshot" LocalModel — substrate-neutral LLM dispatch run(prompt, opts) "complete this prompt; return text" AgentConnector — substrate-neutral agent delivery list_agents() "what agent ids do you handle?" deliver(id, payload) "send this to that agent" wake(id, opts) "rouse that agent" health_check() "are you reachable?" request_response(...) "deliver + collect a reply" McpConnector — external tool dispatch (substrate-neutral wire) call(toolName, args, ctx?) "invoke this tool with these kwargs" ``` What's NOT in the contracts (and is your concern as implementor): * Where the data lives (sqlite / your DB / hosted service / vector store) * What metadata fields your substrate honors or ignores (kwargs passed via `metadata.` ride through; you choose what to do with them) * Vaults, namespaces, tenants, access-control — substrate-specific * Expiration / decay / pinning / reranking — substrate-specific * Authentication into your own backend — your code, your decision ## Case 1 vs Case 2 — the load-bearing wiring decision This is the most important architectural choice you'll make. ### Case 1 — typed-contract wiring (substrate-portable) You implement the typed connector contracts (`DataStore`, `LocalModel`, etc.) against your substrate. The bridge classes (`DataStoreMcpConnector`, `LocalModelMcpConnector`) surface them as canonical `$ data_read` / `$ llm` dispatch. ```typescript theme={null} class MyDataStore implements DataStore { async query(filters: QueryFilters): Promise { /* ... */ } async write(record: DataWrite): Promise { /* ... */ } async get(id: string): Promise { /* ... */ } async manifest(): Promise { /* ... */ } } registry.registerDataStore("primary", new MyDataStore()); ``` **In skills:** ``` $ data_read mode=fts query="customer feedback" limit=10 -> CONTEXT ``` This same skill body runs unchanged against your substrate, against SQLite-FTS (bundled), against Pinecone, against any substrate that conforms to the typed contract. **Skills are portable.** Substrate-specific concerns (where the records live, what metadata you honor) stay inside your impl. ### Case 2 — MCP-tools wiring (substrate-locked) Your substrate exposes itself as MCP tools (via a local MCP server or remote one). You wire it as an `McpConnector` and skills reference its tools by name with substrate-specific kwargs. **MCP transport — two paths.** The protocol's wire layer is the same; the transport differs: * **Stdio MCP** (most common for community servers — YouTrack, GitHub, Linear, etc.): the MCP server is a binary you spawn as a child process and communicate with via stdin/stdout. Wired via `RemoteMcpConnector`: ```json theme={null} { "my_store": { "class": "RemoteMcpConnector", "config": { "command": "my-store-mcp-server", "args": ["--db", "/var/store"], "framing": "newline" } } } ``` Set `"framing": "newline"` explicitly — `mcp-remote` and most spec-compliant MCP stdio servers use newline-delimited JSON. The legacy `lsp` default silently hangs to `init_timeout` against newline-framed servers. See [configuration.md — `RemoteMcpConnector` config — stdio framing](configuration.md#remotemcpconnector-config---stdio-framing). The `command` (server binary, `node`/`npx`, `uv`/`uvx`, etc.) must be on the runtime host's PATH at spawn time. A programmatic bootstrap inherits its launching shell's PATH; the CLI inherits the user's shell PATH at invocation. * **HTTP MCP / Streamable HTTP** (Anthropic's hosted MCP, GitHub MCP, Linear MCP, etc.): the MCP server speaks JSON-RPC over HTTP with Server-Sent Events for the stream channel. Two ways to wire it: * **(a) Stdio bridge** — `RemoteMcpConnector` + `npx mcp-remote https://...` runs a node child process that bridges HTTP MCP into stdio for the runtime to consume. `mcp-remote` auto-negotiates the transport (Streamable HTTP first, falling back to SSE); add `--sse` only if the server requires SSE explicitly. Works today; adds the bridge subprocess overhead per call. * **(b) Direct HTTP connector (bundled)** — `HttpMcpConnector` speaks Streamable HTTP MCP directly, no subprocess. Substrate-neutral: works against any MCP server speaking the spec. Wired declaratively: ```json theme={null} { "my_store": { "class": "HttpMcpConnector", "config": { "endpoint": "https://mcp.example.com/", "headers": { "Authorization": "Bearer ${API_TOKEN}" }, "identityHeader": "X-Agent-Id", "maxPoolSize": 64 } } } ``` Identity-propagation config: * `identityHeader` — when set, the connector reads `ctx.agentId` per call and threads it as both a per-call request header AND the session-pinning key. Each distinct agent identity gets its own session, pinned to that identity at server-side `initialize` time. Required for substrates that pin sessions to the initializing identity (the common case for memory-substrate MCPs). Omit it when every caller shares one identity — all calls then share a single default session. * `maxPoolSize` — optional cap on the per-identity session pool (LRU eviction by access recency). Default unlimited; set when your substrate has session-count limits or you want bounded resource use. When `identityHeader` is set, `supports_identity_propagation: true` is declared in `runtime_capabilities`. The `RuntimeCapabilitiesConformance` suite then requires Level 1 + Level 2 probes wired via `flagProbes` — see [Connector Contract Reference](connector-contract-reference.md) for the probe contract. * **(c) Custom direct connector** — fork `examples/connectors/McpConnectorTemplate/` when you need behavior the bundled `HttpMcpConnector` doesn't cover (e.g., a non-spec auth handshake, tool-name normalization, custom retry logic). Pick (b) by default — no subprocess, no implementation effort, works against any compliant Streamable HTTP MCP server. Pick (a) only when the server is behind tooling that requires the stdio bridge. Pick (c) only when your substrate needs behavior the bundled connector doesn't expose. **In skills**, regardless of transport: ``` $ my_store.search query="customer feedback" region="eu-west" cluster="prod" -> CONTEXT ``` This skill body is locked to `my_store` — its specific kwargs (`region`, `cluster`) and response shape. To move to a different substrate, every call site has to be rewritten. **⚠ Programmatic adopters:** use **`bootstrapFromEnv()`** and it loads `$SKILLSCRIPT_HOME/connectors.json` (plus `.env` + `SKILLSCRIPT_*`) for you, exactly like the CLI. Only **raw `bootstrap()`** skips them — it reads `connectors.json` solely when you pass `connectorsConfigPath`, and skipping it makes `$ name.tool` calls fail at runtime with `unknown-connector` and no hint that the file simply wasn't read. See §"Programmatic bootstrap path" below — `bootstrapFromEnv()` is the recommended default; the raw-`bootstrap()` explicit-wiring pattern is for hand-assembled custom substrates. ### Picking — the tradeoff | Aspect | Case 1 (typed) | Case 2 (MCP) | | - | - | - | | Skill portability | ✓ portable | ✗ substrate-locked | | Substrate feature coverage | Limited to typed contract surface | Full substrate surface | | Implementation effort | Implement typed interface | Wire existing MCP server | | Best for | Skills you want to ship | Substrate-specific power features | **The choice is per-skill, not per-substrate.** You can wire both — register `data_read` (typed-contract via bridge) AND `my_store` (MCP) — and let skills opt into portability by which connector name they reference. For the substrate-portability claim to hold, **the substrates you care about must be Case-1-wired**. ## Joe Programmer setup walkthrough ### 1. Install + initialize ```bash theme={null} npm install -g skillscript-runtime skillfile init --here ``` This creates `~/.skillscript/` with `skills/`, `traces/`, an empty `connectors.json`, and a `config.toml` stub. **If you're writing a custom bootstrap (not just using the bundled CLI):** install the package locally (`npm install skillscript-runtime` in your adopter project) so `tsx`/`node` can resolve it alongside your project dependencies. A global install is convenient for the bundled CLI but doesn't expose the package to your custom bootstrap's module resolution. The package is ESM-only. `npm init -y` produces a CJS `package.json` by default, which will fail your first bootstrap run with top-level-await / ESM-import errors. Switch your adopter project to ESM before authoring bootstrap code: ```bash theme={null} npm pkg set type=module ``` ### 2. Decide on substrate wiring For each of the four substrates (data store, LLM, agent harness, MCP tools), decide Case 1 or Case 2. The onboarding scaffold (`examples/onboarding-scaffold/`) is Case 1 end-to-end against a file-backed data store + OpenAI + tmux. ### 3. Configure runtime knobs Create `skillscript.config.json` in your `$SKILLSCRIPT_HOME`: ```json theme={null} { "skillsDir": "${SKILLSCRIPT_HOME}/skills", "traceDir": "${SKILLSCRIPT_HOME}/traces", "dataDbPath": "${SKILLSCRIPT_HOME}/data.db", "dashboard": { "port": 7878 } } ``` `${VAR}` substitutes against `process.env`. See `skillscript.config.json.example` in the repo for the full surface. ### 4. Wire your substrates **For the bundled CLI path** (no custom code): use `connectors.json` to declare your MCP servers; use `OPENAI_API_KEY` / `OLLAMA_BASE_URL` env vars; run `skillfile dashboard --config ./skillscript.config.json`. **For custom substrates**: write your own bootstrap. See `examples/custom-bootstrap.example.ts` and `examples/onboarding-scaffold/bootstrap.ts` for complete worked walkthroughs. Security knobs that adopters wiring real substrates should know about: * **The approval boundary (secured mode).** `SKILLSCRIPT_SECURED_MODE=true` enforces that only key-signed skills perform effects. Default-deny by design — leave it off only for trusted-author / single-operator setups. Full detail, the approve flow, and key custody: [Approval + secured mode](#approval--secured-mode). * **Filesystem path allowlist.** `SKILLSCRIPT_FS_ALLOWLIST` is default-deny — `file_read` / `file_write` refuse every path until you wire roots. See [Filesystem path allowlist](#filesystem-path-allowlist). (Keep your approval-key directory out of it.) * **Per-connector tool allowlists** — `allowed_tools` on each `connectors.json` MCP connector entry restricts which tools that connector can dispatch. Three-state (`undefined` = allow all, `[]` = allow none, listed = exactly those). Tier-1 `disallowed-tool` lint + runtime defense-in-depth refuse out-of-list dispatch. **`allowed_tools` belongs at the entry top-level**, sibling to `class` and `config` — NOT inside the `config` block. The loader hard-errors on misplacement (placing it inside `config:` would silently allow-all every tool — the worst-case failure mode for a security control). See `docs/configuration.md` §"Named MCP connector instances" for the JSON shape. * **Shell-execution discipline** — `shell(command="...")` runs structured-spawn by default (binary on PATH, whitespace-tokenized argv, no bash). `shell(command="...", unsafe=true)` opts into bash interpretation (pipes, `$VAR`, command substitution) and refuses to fire unless the runtime is configured with `enable_unsafe_shell = true` in `config.toml`. Lint flags every `unsafe=true` op tier-2 to keep audit posture visible. See `scaffold/config.toml` for the documented default + `help({topic:"lint-codes"})` for the `unsafe-shell-disabled` rule. If you have a custom JSON-instantiable `McpConnector` class, register it with `registerConnectorClass` before loading config: ```typescript theme={null} import { registerConnectorClass, loadConnectorsConfig } from "skillscript-runtime"; import { MyAdopterConnector } from "./my-adopter-connector.js"; registerConnectorClass("MyAdopterConnector", { ctor: MyAdopterConnector, fromConfig: (cfg) => new MyAdopterConnector(cfg), }); const { connectors } = loadConnectorsConfig({ path: "./connectors.json" }); ``` ### 5. Two-instance posture Running dev-skillscript alongside an adopter-wiring instance on the same machine: ```bash theme={null} # dev skillfile dashboard # adopter (different port + paths) SKILLSCRIPT_HOME=/path/to/adopter skillfile dashboard --config /path/to/adopter/skillscript.config.json ``` Each instance reads its own config; ports/paths/db files don't collide. ### 6. Running as a supervised service For cron/event fires to be reliable, the dashboard/MCP host must run supervised — surviving both reboot and crash. The scheduler is in-process, at-most-once, with no catch-up (see [Trigger model — durability honesty](#durability-honesty)): a down process silently misses fires. A cron skill like `0 3 * * *` only fires if the process happens to be up at 3am. `nohup`-from-a-shell isn't sufficient (dies on reboot/logout/crash). Use the OS supervisor: a macOS LaunchAgent (`RunAtLoad` + `KeepAlive`) or a Linux systemd unit. **macOS — `~/Library/LaunchAgents/com.skillscript.adopter.plist`:** ```xml theme={null} Labelcom.skillscript.adopter ProgramArguments /opt/homebrew/bin/node --import=tsx /path/to/adopter/bootstrap.ts WorkingDirectory/path/to/adopter RunAtLoad KeepAlive EnvironmentVariables PATH/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin SKILLSCRIPT_HOME/path/to/adopter StandardOutPath/path/to/adopter/logs/stdout.log StandardErrorPath/path/to/adopter/logs/stderr.log ``` Load with `launchctl load ~/Library/LaunchAgents/com.skillscript.adopter.plist`. **Linux — `/etc/systemd/system/skillscript-adopter.service`:** ```ini theme={null} [Unit] Description=Skillscript adopter runtime After=network.target [Service] ExecStart=/usr/bin/node --import=tsx /path/to/adopter/bootstrap.ts WorkingDirectory=/path/to/adopter Environment=PATH=/usr/local/bin:/usr/bin:/bin Environment=SKILLSCRIPT_HOME=/path/to/adopter Restart=always RestartSec=5 User=adopter [Install] WantedBy=multi-user.target ``` Enable with `systemctl enable --now skillscript-adopter.service`. **The load-bearing gotcha — pin `PATH` in the supervisor environment.** launchd and systemd run with a bare PATH (typically `/usr/bin:/bin`), not your shell's. The runtime's spawned binaries — `node`/`npx` for `RemoteMcpConnector` (mcp-remote bridges), `uv`/`uvx` for Python MCP servers, every binary on the shell allowlist (`gh`, `curl`, `git`, etc.) — must be on that pinned PATH. Omit it and connectors + shell ops fail with "command not found" under the supervisor even though they work from your shell. This is the same class of environment-specific break as forgetting to pin `TMUX_TMPDIR` in a tmux launcher's plist. Spirit-of: same PATH concern as the [Case-2 stdio host-PATH note](#case-2--mcp-tools-wiring-substrate-locked) — two surfaces (the shell that launches it ad-hoc AND the supervisor that keeps it up persistently). **A few additional gotchas:** * **`WorkingDirectory` matters.** Set it to the bootstrap's directory so relative imports (`./connectors-config.ts`) and `node_modules` resolve correctly. Without it, the supervisor runs from `/` and ESM imports fail. * **Single supervisor only.** Don't also run the dashboard manually (`nohup skillfile dashboard &`) alongside the supervised instance — two listeners on the same port either collide or round-robin events, dropping fires silently. * **`.env` still loads.** The runtime's `process.loadEnvFile` call reads `.env` from the working directory at boot, independent of the supervisor's environment block. Don't duplicate secrets in both — keep them in `.env` and let the bootstrap load them. ### 7. Wire your agent to the runtime over MCP With the service running, point your agent at the runtime's `/rpc` endpoint. **Simplest path (Claude Code + similar agent hosts):** just ask. "Add the skillscript MCP server at `http://localhost:7878/rpc`" — Claude Code writes the config for you. Skip the JSON below unless you want to understand what landed or you're on a host that doesn't write its own config. **Manual config — standard HTTP MCP** (modern agent hosts that speak HTTP MCP directly) — drop the runtime in your agent's MCP config (`~/.claude.json`, `.mcp.json`, `claude_desktop_config.json`, etc.): ```json theme={null} { "mcpServers": { "skillscript": { "type": "http", "url": "http://localhost:7878/rpc" } } } ``` **Stdio bridge** (older Claude Desktop builds + any client that doesn't speak HTTP MCP) — bridge via `mcp-remote` the same way you'd bridge any HTTP MCP server. Pair this with the [`framing: "newline"` note from Case 2](#case-2--mcp-tools-wiring-substrate-locked) if you wire it the other direction (runtime → external HTTP MCP): ```json theme={null} { "mcpServers": { "skillscript": { "command": "npx", "args": ["mcp-remote", "http://localhost:7878/rpc"] } } } ``` **Two operational notes:** * **Port matches what the runtime binds.** Default `7878` (`SKILLSCRIPT_PORT` env var / `dashboard.port` config). Two-instance setups (dev + adopter side-by-side per §5) need distinct ports — e.g., adopter on `7879`. Whatever the supervisor unit specifies is what the agent config must point at. * **Auth + bind address.** `/rpc` has no auth and binds to `127.0.0.1` by default — the right posture for a local agent talking to a local runtime. If you set `SKILLSCRIPT_HOST=0.0.0.0` to reach the runtime across the network, front it with your own auth layer (reverse proxy + bearer token, mTLS, etc.) — same posture as the `/event` HTTP ingress, which has its own bearer-token gate (`SKILLSCRIPT_EVENT_INGRESS_AUTH_TOKEN`). ## Approval + secured mode Every skill carries a lifecycle status — `Draft → Approved → Disabled`. **Only `Approved` skills execute**; `Draft` is the safety gate (a skill under authoring or review), `Disabled` is retired. That status gate applies in *both* runtime modes. What the mode decides is whether an `Approved` skill must additionally be **cryptographically keyed**: | | Unsecured | Secured (`SKILLSCRIPT_SECURED_MODE=true`) | | - | - | - | | `Draft` skill | refused | refused | | `Approved` skill | runs — a bare `# Status: Approved` is sufficient (unkeyed) | runs **only** if the body carries a valid operator signature | | Tamper-evidence | none (an Approved body can be edited freely) | yes — editing the body breaks the signature | | Effectful ops (`$`, `shell`, `file_*`, `notify`) | run | **refused unless the skill is signed** (the `effectsAuthorized` capability gate) | | Who can grant approval | anyone who can set the status | only a holder of the operator's private key | **Unsecured** is the trusted-author / single-operator convenience posture: you trust whoever writes skills, the status flag is the only barrier. **Secured** is the enforced boundary — an unapproved or tampered skill cannot perform a single effectful op, regardless of how it's dispatched (CLI, cron, `/event`, MCP, in-skill composition). Unsecured is the current default; secured is the recommended posture for any multi-author or networked deployment. > The shell + filesystem allowlists (below) are **always enforced, in both modes** — they bound *what* a running skill may touch. Secured mode adds the orthogonal boundary on *whether an unapproved skill runs at all*. ### Asymmetric signing — how secured approval works Approval is an Ed25519 signature, not a shared secret: * **Private key** — held by the operator, read **only** by the approve flow. That flow is either `skillfile approve` at a terminal (the runtime process never loads the key) or, if you opt into in-browser approval, the dashboard's passcode-gated `/approve` — which reads the key only after a live human enters the session passcode, never on its own. For maximum isolation, keep signing terminal-side and run the runtime under a uid that cannot read the private key — then a co-resident agent can't forge approvals even with full read access to the runtime process. Same-uid (or in-browser signing) still works, but isn't fully isolated — a future managed-custody option will close this. * **Public key** — non-secret; the runtime reads it to *verify* signatures on every execution. No hot-path secret is the point: verification needs only the public key. First-run provisioning is automatic — starting the runtime or `skillfile init` in secured mode generates the keypair if absent (private written `0600`, default `~/.config/skillscript/approval.{key,pub}`, deliberately outside `SKILLSCRIPT_HOME`, the agent-readable data dir). ### The approve flow | Action | How | | - | - | | Approve one skill (review the body, then sign) | `skillfile approve ` at a terminal | | Batch-approve everything pending | `skillfile reapprove --apply` (dry-run preview: `skillfile reapprove`) | | Approve from the dashboard — terminal signing | the **Approvals** queue surfaces the pending set, each skill's security signals, and its effectful footprint; copy the emitted `skillfile approve` command and run it at your terminal | | Approve from the dashboard — in-browser | with `SKILLSCRIPT_APPROVAL_PASSCODE` set, the queue's **Approve** button signs server-side after a one-time passcode unlock | **Two signing paths, one custody rule: the private key stays operator-side.** * **Terminal signing.** With no passcode configured, the dashboard is a pure **review** surface — pending queue, per-skill security signals, effectful-footprint checklist — but `/approve` is disabled and signing happens at your terminal where the key lives. The right posture when the dashboard host and the key-holder's terminal are the same machine. * **In-browser signing.** With `SKILLSCRIPT_APPROVAL_PASSCODE` set, the dashboard can sign without a terminal round-trip, and holds **no standing signing power**: the first approve in a browser session prompts for the passcode (`POST /unlock`), unlocking signing for that session only (\~15-minute idle TTL, server-side, cookie-bound). A live human with the passcode is in the loop for every session — the runtime never gains the ability to approve on its own. Pair it with `SKILLSCRIPT_DASHBOARD_AUTH_TOKEN` (network hygiene on the dashboard) when the dashboard is reachable beyond localhost. Either way, `skill_write` / `skill_status` **cannot** grant approval in secured mode — an agent-written or status-flipped skill lands `Draft` until a key-holder signs it, enforced at the MCP handler regardless of the SkillStore substrate. (In unsecured mode, `skill_status → Approved` is honored directly, unkeyed.) **Misconfiguration is loud.** If secured mode and a passcode are both set but signing isn't actually wired (no SkillStore reaches the dashboard, or no readable key), the dashboard surfaces the gap as a banner *and* a stderr boot-log line and stays review-only — skills remain inert (fail-closed) while you see and fix it. The boot-log is what reaches a headless / programmatic adopter who never opens the dashboard. ### Migrating an existing skill set Turning secured mode on means any skill that's `Approved` without a valid signature is refused at execution. `skillfile reapprove` sweeps the store, reports the set needing re-blessing, and `--apply` re-signs them in one pass — so you don't run `skillfile approve` once per skill. ### Bundled demos Bundled example skills ship as `# Status: Draft` — a signature baked at package-build time could never validate on your install (the key is per-operator). `skillfile init` locally approves the three seeded demos with *your* machine's authority (secured → provision keypair + sign; unsecured → bare Approved), so they're runnable immediately after init. ## Deleting skills Deleting a skill is an **operator-only** action — there is **no agent / MCP delete surface** (an agent can author and disable, but only the operator removes). Two surfaces: | Surface | How | | - | - | | CLI | `skillfile delete ` | | Dashboard | the **Delete skill** button on a skill's detail view | Both are **destructive**: the skill and its version history are erased — there is no trash and no restore in the bundled stores (`FilesystemSkillStore` unlinks the files; `SqliteSkillStore` hard-cascades both tables). Its triggers are dropped from the live scheduler, and its name frees up immediately for a fresh `skill_write`/`store`. The safety is the confirm step plus the reverse-dependency check, not recoverability. Before deleting, both surfaces run a **best-effort reverse-dependency scan** — which other skills statically reference the target via `$ execute_skill(name="…")` or `inline(skill="…")`. If any do, the delete is **blocked** until you confirm ("`triage-flow` references this — delete anyway?" in the dashboard; `--force` on the CLI). The scan is literal-name only: a runtime-resolved `name="${VAR}"` reference can't be detected statically, so a dynamic caller may slip past the warning — and because delete is permanent, treat the scan as a heads-up, not a guarantee. Adopter SkillStores implement `delete(name)` per the contract; the runtime only requires "remove from normal views," so a soft-delete (tombstone + filter) is a valid adopter-side choice if you need recovery or audit-grade retention — recovery semantics are the store's concern. See [Connector Contract Reference](connector-contract-reference.md). ## Shell binary allowlist **The runtime enforces a default-deny operator allowlist for binaries reachable via `shell(...)` ops.** Skill authors are agents, agents are a weak trust anchor (hallucination, prompt-injection, no human-in-loop at scale), and operator-side scoping converts "a human reviews every skill" from discipline into an enforced constraint at the language level. ### The behavior Two **independent** operator axes — do not conflate: | Axis | Operator switch | Controls | | - | - | - | | **Binary scope** | `SKILLSCRIPT_SHELL_ALLOWLIST` | Which binaries `shell(...)` can invoke | | **Syntax scope** | `SKILLSCRIPT_ENABLE_UNSAFE_SHELL` | Whether bash interpretation (pipes / `$VAR` / `$(...)`) is permitted | Behavior matrix: | Skill op | Binary on allowlist | Binary off allowlist | | - | - | - | | `shell(command="X ...")` (structural) | runs | refused with `ShellBinaryNotAllowedError` | | `shell(argv=["X", ...])` (explicit token list) | runs | refused with `ShellBinaryNotAllowedError` | | `shell(command="X ...", unsafe=true)` with `enableUnsafeShell=true` | runs (if `bash` on allowlist) | refused (off-list `bash` blocks ALL unsafe shell) | | `shell(command="X ...", unsafe=true)` with `enableUnsafeShell=false` | refused with `UnsafeShellDisabledError` (syntax axis fires first) | — | **Off-allowlist is final.** The skill author has no in-skill mechanism to escape it — not the `unsafe` keyword, not `# Autonomous: true`, not `approved="reason"`. Binary scope is an operator boundary the author cannot talk past. ### Three call shapes — `command=`, `argv=`, `unsafe=true` Three ways to invoke a binary. Each picks a different point on the safety/expressiveness curve: | Form | When to reach for it | | - | - | | `shell(command="curl -s https://example.com/${ID}") -> R` | Simple commands, no spaces or quote-special chars in substituted values. The string is whitespace-tokenized + quote-stripped; structural spawn (no shell). | | `shell(argv=["say", "-v", "${VOICE}", "-f", "${PATH}"]) -> R` | **Args with spaces, JSON payloads, dynamic strings.** Each list element is exactly one argv token; substitution per element doesn't re-tokenize. Strictly safer than `unsafe=true` — no shell process, no metacharacter interpretation, injection-surface zero. The right tool when a `${VAR}` may contain whitespace. | | `shell(command="echo hi && date", unsafe=true) -> R` | Pipes, redirects, shell built-ins, command-substitution. Requires `enableUnsafeShell: true` at the runtime; lint flags every appearance (tier-2 `unsafe-shell-op`). | `argv=` is mutually exclusive with `command=` and with `unsafe=true` (parse errors on either combination — argv is execv-class, there's no shell to opt into). The same allowlist gate applies to `argv[0]`. ### Quote-trap lint (`shell-quoted-var-in-command`) The pattern `shell(command="echo '${VAR}'")` looks safe — quotes around the substitution — but the structural tokenizer respects quotes during the *original* whitespace split, then strips them. After substitution, if VAR contains quote characters (`Jamie's`) the matching can drift. Tier-2 lint `shell-quoted-var-in-command` fires on this pattern and points at the `argv=` form as the safer answer. Works fine for known-simple values; the lint exists because the failure mode is silent-wrong, not loud-error. ### Discovering your corpus's binaries The default-deny posture means a freshly-installed runtime with no allowlist wired refuses every `shell()` call. Use `skillfile shell-audit` to enumerate the binaries your skill corpus invokes: ```bash theme={null} skillfile shell-audit # Sample output: # Scanned 12 skill(s) under /Users/you/.skillscript/skills. # # Binaries used: # curl (in: weather-fetch, status-probe) # git (in: status-board) # jq (in: weather-fetch, support-response, status-probe) # bash (in: support-response) # # Ready-to-paste .env entry: # # SKILLSCRIPT_SHELL_ALLOWLIST=bash,curl,git,jq # # Note: 'bash' is on the list because at least one skill uses # shell(..., unsafe=true). To permit unsafe shell, ALSO set # SKILLSCRIPT_ENABLE_UNSAFE_SHELL=true. ``` Paste into your `$SKILLSCRIPT_HOME/.env` (review/narrow as desired). The audit is the canonical path — running it lets you make explicit policy decisions instead of discovering refusals through runtime errors. ### Programmatic bootstrap path **Most adopters operate via the web dashboard** after a one-time `skillfile init`. To stand that dashboard up from your own code, use **`bootstrapFromEnv()`** — the blessed entry point that wires a full runtime + `DashboardServer` from `$SKILLSCRIPT_HOME` *exactly the way the CLI does*: it loads `.env`, `skillscript.config.json`, and `connectors.json`, resolves the whole `SKILLSCRIPT_*` env cascade, calls `bootstrap()`, wires declarative triggers, and assembles the server. ```typescript theme={null} import { bootstrapFromEnv } from "skillscript-runtime"; const { wired, server } = await bootstrapFromEnv({ mode: "dashboard" /* or "serve" */ }); wired.scheduler.start(); await server.start(); // On shutdown, reap stdio-bridged connector children (RemoteMcpConnector): process.on("SIGTERM", async () => { await wired.scheduler.stop(); await server.stop(); await wired.registry.disposeAll(); }); ``` Both are returned **unstarted** — you decide when to `start()`. Options: `mode`, `home` (default `$SKILLSCRIPT_HOME`), `configPath`, `connectorsConfigPath`, `port`, `host`, and `overrides`. **Precedence**: explicit option > `overrides` (passed to `bootstrap()`, wins last) > `SKILLSCRIPT_*` env > `skillscript.config.json` > default. To wire your **own custom substrate** (e.g. a remote `SkillStore`), two paths: * **Declarative** — if it's expressible in `connectors.json` via the `{ "type": "custom", "module": "./my-store.js", "export": "MyStore" }` substrate form, just declare it; `bootstrapFromEnv()` honors `substrate.*` like the CLI. * **Instance injection** — pass a pre-built instance through `overrides`, the common path for a store that needs constructor wiring you hold in code: ```typescript theme={null} const { wired, server } = await bootstrapFromEnv({ mode: "dashboard", overrides: { skillStore: new MyRemoteSkillStore({ /* client, auth, ... */ }) }, }); ``` Everything else (data store, models, connectors, env cascade) still auto-wires from `$SKILLSCRIPT_HOME`. `overrides` accepts any `bootstrap()` option (`skillStore` / `dataStore` / `localModel` / `agentConnector` / allowlists / …). This closes the silent CLI-vs-programmatic asymmetry described below; reach for raw `bootstrap()` only when you're hand-assembling a registry that neither `connectors.json` nor `overrides` can express. **⚠ Migrating an existing hand-assembled bootstrap to `bootstrapFromEnv()`?** Move any options you previously hardcoded on `bootstrap()` / `new DashboardServer({...})` to their `SKILLSCRIPT_*` env equivalents — `bootstrapFromEnv()` resolves them from env, so a value you drop reverts to the default. Two to watch: `enableUnsafeShell: true` → `SKILLSCRIPT_ENABLE_UNSAFE_SHELL=true` (fails **loud** — unsafe ops just refuse, you'll notice); and **`mcpCallerIdentityHeader: "X-Agent-Id"` → `SKILLSCRIPT_MCP_CALLER_IDENTITY_HEADER=X-Agent-Id`, which fails *silently*** — drop it and skill-author attribution quietly reverts to the store's default writer identity, with no error. (`bootstrap()`-level opts like `enableUnsafeShell` can instead go through `overrides`; the `DashboardServer`-level `mcpCallerIdentityHeader` is env-only via `bootstrapFromEnv` — set the env var.) Verify after migrating: send your identity header on a `/rpc` `skill_write` and confirm the captured `author`. #### Raw `bootstrap()` — the CLI-auto-vs-programmatic-explicit asymmetry `bootstrapFromEnv()` does the discovery steps below for you. If you call **`bootstrap()` directly** instead (hand-assembling substrates), be aware the CLI (`skillfile dashboard` / `serve`) does several discovery steps automatically — load `$SKILLSCRIPT_HOME/.env`, read `SKILLSCRIPT_*` env vars, load `$SKILLSCRIPT_HOME/connectors.json` — that raw `bootstrap()` does NOT. Each surface then needs explicit wiring: | Surface | CLI path | Programmatic path | | - | - | - | | `.env` (env vars in a dotfile) | auto-loaded from `$SKILLSCRIPT_HOME/.env` | call `process.loadEnvFile()` yourself BEFORE `bootstrap()` | | `SKILLSCRIPT_*` env vars | read from `process.env` automatically | read automatically once env is loaded (`bootstrap()` env-fallback) | | `connectors.json` (MCP wiring) | auto-discovered at `$SKILLSCRIPT_HOME/connectors.json` | pass `connectorsConfigPath: "/path/to/connectors.json"` to `bootstrap()` | Skip any of these and you get silent-empty surprises — a missing env var, an undeclared connector, etc. — with no hint that the file wasn't loaded. This is intentional: `bootstrap()` stays decoupled from the dotenv + `SKILLSCRIPT_HOME` convention so embedders can drive every input explicitly. The cost is doc-prominence — three surfaces, all silent-empty on omission, all noted here. For your shell allowlist to work on the programmatic path, ensure the env var is in `process.env` BEFORE calling `bootstrap()`. Two patterns: ```typescript theme={null} // Pattern A — load .env yourself + pass connectorsConfigPath import { join } from "node:path"; import { bootstrap } from "skillscript-runtime"; const home = process.env.SKILLSCRIPT_HOME ?? join(homedir(), ".skillscript"); try { process.loadEnvFile(join(home, ".env")); } catch {} // Node 22+ built-in const { mcpServer, scheduler } = bootstrap({ skillsDir: join(home, "skills"), traceDir: join(home, "traces"), connectorsConfigPath: join(home, "connectors.json"), // shellAllowlist intentionally omitted → bootstrap reads env }); // Pattern B — fully explicit (env-independent, no .env, no connectors.json) const { mcpServer, scheduler } = bootstrap({ skillsDir: join(home, "skills"), traceDir: join(home, "traces"), shellAllowlist: ["curl", "git", "jq"], // No connectorsConfigPath — adopter constructs Registry by hand }); ``` **`bootstrap()` env fallback semantics**: when `opts.shellAllowlist === undefined`, the runtime reads `SKILLSCRIPT_SHELL_ALLOWLIST` from `process.env` (comma-separated, trimmed). When `opts.shellAllowlist` is supplied — including the explicit `[]` deny-all — the option is authoritative and **env does NOT widen it**. This is security-load-bearing: an adopter passing `shellAllowlist: []` to assert lockdown gets lockdown regardless of ambient env. | `opts.shellAllowlist` | `SKILLSCRIPT_SHELL_ALLOWLIST` env | Effective allowlist | | - | - | - | | `undefined` (omitted) | unset | `undefined` → default-deny | | `undefined` (omitted) | `"curl,jq"` | `["curl", "jq"]` (env fallback) | | `undefined` (omitted) | `""` (explicit empty) | `[]` (explicit deny-all from env) | | `["curl"]` | anything | `["curl"]` (explicit opt wins) | | `[]` (explicit) | `"ssh,kubectl"` | `[]` (explicit deny-all wins; env does NOT widen) | ### Trust model — lint vs. runtime **Lint is local advisory; runtime is authoritative.** The `shell-binary-not-allowed` lint rule checks against the *author's* environment allowlist (their local `.env` or the linter's loaded config), which may differ from production. Passing lint does NOT guarantee the call will run. * **Authors** lint with their own allowlist for immediate feedback ("you can't use `ssh` in your dev env, fix this skill"). * **CI pipelines** lint with the deployment's `.env` to catch production-specific gaps before merge. * **Runtime** is the authoritative gate — refuses off-list binaries at first dispatch regardless of lint state. This split is intentional: lint as discipline-only would let adopters disable it; runtime as the boundary means the constraint always holds. ### The scope caveat — don't oversell The allowlist scopes **which** binaries are reachable, not **what they do**. Kills `ssh` / `kubectl` / `rm` / `nc` wholesale — that's real value. Does NOT stop misuse of a permitted binary: `curl` on the list still means curl-to-anywhere (exfil possible to attacker-controlled URLs). Argument-level policy (host allowlists, URL pattern matching) and OS-level egress controls are **separate, heavier layers** — explicitly out of scope here. Don't let this create false confidence that shell is "solved." For the unsafe path, the proper binary-scope layer is OS-level: * Restricted `PATH` (only allowed binaries reachable to the runtime process) * `execve`/`seccomp` filters (kernel-level allowed-binary set) * Container with curated `/usr/bin` (immutable distroless image) Parse-based binary enumeration of `bash -c ` would be unsound — `e=curl; $e ...`, `$(printf cur)l ...`, `eval`, `xargs`, var-built command names all defeat it. Against agent-author threat models, false confidence is worse than no enforcement. ### Dashboard observability The dashboard SPA at `http://:` exposes two security-focused surfaces for the observe→promote loop: **Security view (`#security` route).** Cross-skill list of blocked shell attempts — `{skill, target, binary, body, timestamp}` per refused call. Aggregated by binary so you can see at a glance "what did skills try to invoke that I haven't allowlisted." Backed by the `blocked_shell_attempts` MCP tool, which filters trace records by `blocked_reason: "binary-not-allowed"`. Runtimes without the tool exposed degrade cleanly to an "unavailable" note. **Skill detail view — footprint checklist + security signals + source highlighting.** Each skill's detail page (clicking a skill name from `#skills`) shows: * A **"What this skill touches"** panel right at the approve action: the skill's **effectful footprint** — the MCP connectors it dispatches to, built-in `$` ops, shell binaries, and counts of `file_write` / `file_read` / unsafe-shell / `notify` ops, or "nothing effectful to authorize" for a pure skill. This is AST-derived — the *same* op enumeration the capability gate authorizes — so it's the authoritative surface the skill can touch once signed, not a textual guess. The least-privilege checklist the approver reads before signing. * A **"Security signals"** panel: aggregated counts of shell ops + binaries used, unsafe-shell count, `# Autonomous: true`, per-op `approved="..."` authorizations, mutation ops (`$ skill_write` / `$ data_write` / `file_write`), wake-class `@session` deliveries, cron triggers. (A heuristic source scan — it adds risk-framing signals the footprint doesn't, e.g. the `approved=` bypass and the autonomous flag; the two panels complement each other.) * **Inline tinted highlighting** on the skill source `
` body. Two tiers: **orange** for HIGH-tier signals (`unsafe=true`, `# Autonomous: true`, `approved="..."`, mutation ops); **yellow** for MEDIUM-tier signals (`shell(...)` calls, `notify(agent="X@session", ...)` wake-class deliveries). Reviewers scan-prioritize: orange = review carefully; yellow = worth noting.

The surfaces compose: the footprint says WHAT the skill can do, the security-signals panel says WHAT to scrutinize, the highlights say WHERE to look. The same footprint rides every `skill_list` entry and the `skill_preflight` contract, so an agent composing against a skill reads the same truth the human approver does.

### Future direction

Per-skill capability declaration: skills declare what shell binaries they need in their frontmatter:

```
# Skill: status-board
# Shell: git, jq
# Status: Approved
```

The operator policy validates `declared ∩ allowlist` — each skill's shell footprint becomes self-documenting and auditable. Planned for a future release.

## Filesystem path allowlist

**The runtime enforces a default-deny operator allowlist for paths reachable via `file_read(...)` / `file_write(...)` ops** — the third operator boundary, mirroring the shell allowlist with the same rationale (skill authors are agents; the operator scopes which parts of the filesystem skills may touch).

| Operator switch | Controls |
| - | - |
| `SKILLSCRIPT_FS_ALLOWLIST` | Comma-separated roots under which `file_read` / `file_write` may operate |

* **Default-deny.** An unset or empty allowlist refuses *every* file op with `FilePathNotAllowedError` — a freshly-installed runtime does no file I/O until you wire roots. Applies to `file_read` as well as `file_write` (a read-then-`emit` is an exfiltration path).
* **Canonicalized before the check.** Both the target and each allowed root are resolved to their real absolute path (realpath, component-by-component), so `..` traversal and symlink evasion can't escape an allowed root — the classic allowlist bypasses are closed.
* **Off-allowlist is final.** No in-skill keyword (`approved=`, `# Autonomous: true`) escapes it. **Keep secret / key directories OUT of the allowlist** — a skill must never be able to read the operator's approval key. (This is why the default key path lives outside `SKILLSCRIPT_HOME`.)

```bash theme={null}
# permit reads/writes under a workspace + an event-drop dir
SKILLSCRIPT_FS_ALLOWLIST=/srv/skillscript/workspace,/var/skillscript/events
```

TOCTOU note: the check resolves the real path at call time; a symlink swapped between check and open is a residual closed by fd-based opens later. Checking the resolved real path is the standard mitigation shipped today.

## Secrets

**A skill can reference an operator-provisioned secret by name, use it at a sink, and never read it back.** This is how a credential (a bearer token, an API key) reaches a `shell(...)` or `$ connector.tool` call without living in the skill source, the transcript, or a trace.

Three parts:

```
# Skill: send-mail
# Requires: secret.AGENTMAIL_KEY        # 1. declare — an approver sees which credentials the skill reaches
# Status: Draft

default: run
run:
    shell(command="curl -sS -H 'Authorization: Bearer {{secret.AGENTMAIL_KEY}}' https://api.agentmail.to/...") -> R
```

1. **Declare** with `# Requires: secret.NAME`.
2. **Place** with a `{{secret.NAME}}` marker — only inside a sink (a `shell(...)` op or a `$ connector.tool` arg). It is deliberately distinct from `${VAR}`: `${VAR}` is readable substitution over the skill's variable scope and **cannot** reach a secret; `{{secret.NAME}}` resolves *only* at the sink and is never bound to a variable.
3. **Provision** the value as an env var (operator side, e.g. `.env`):

```bash theme={null}
SKILLSCRIPT_SECRET_AGENTMAIL_KEY=am_live_...
```

| Operator switch | Controls |
| - | - |
| `SKILLSCRIPT_SECRET_` | The value `{{secret.NAME}}` resolves to. The `SKILLSCRIPT_SECRET_` prefix scopes which env is secret-reachable — `{{secret.PATH}}` looks for `SKILLSCRIPT_SECRET_PATH`, never `$PATH`. |

**Use-only, enforced.** A marker is legal only in a sink; the runtime injects the value for that one call and never lets it reach a readable surface. Three lint rules block misuse at compile (`secret-use-only` — a marker in `emit`/`$set`/a condition/an `# Output:` template/a `file_*`/`notify` op/an op `(fallback:)`; `secret-undeclared` — a marker with no `# Requires`; `secret-dynamic-name` — a non-literal name like `{{secret.${VAR}}}`). The **runtime** is the authoritative gate (it survives a lint bypass): it resolves only names declared in `# Requires`, only at the sink, and the trace + any error message render the `{{marker}}`, never the value. Fail-closed — an unprovisioned or undeclared secret aborts the op.

**Provisioning is operator-only.** A skill author *names* a secret; only the operator *sets* it (in the runtime env / `.env`). Keep secret values out of skill source and out of the fs allowlist, exactly like the approval key.

**Threat-model boundary — read this before granting a secret.** A secret you authorize a skill to *use* in a shell, that skill can also *exfiltrate* — e.g. `shell("echo {{secret.X}}") -> OUT` then `emit("${OUT}")`, or a `curl` that POSTs it to any host. This is inherent to passing a credential into a shell command and is **not** prevented by the runtime. Two controls:

* **Approval review.** In secured mode a human approves the skill before it runs — review shell-sink skills for exactly this (a command that echoes or forwards the credential).
* **Prefer a connector sink.** A `$ connector.tool` where the connector holds the credential out of band is stronger than a shell `curl`: the value never round-trips through skill-visible stdout. Use a connector sink for any credential whose exposure you can't accept.

(On the shell path the resolved value is also briefly visible in the host process list via `ps`; a future vault-backed `SecretProvider` closes that with sink-aware injection. The `SecretProvider` seam is already in place — an adopter can supply a vault-backed provider via `bootstrap({ secretProvider })` or `bootstrapFromEnv`'s `overrides` with no skill changes.)

## Trigger model

**The trigger surface is two primitives.**

| Primitive | Purpose |
| - | - |
| `cron` | Time-based fires (unchanged) |
| `event` | Generic external-signal fires via HTTP POST to `/event` |

Concepts that look like triggers but aren't — session lifecycle, agent events, file-watch, sensors — are **adapter responsibilities**: external code POSTs `/event` when relevant. Keeps the runtime substrate-neutral; the trigger surface stays tight. The `DeliveryMeta.origin.trigger_kind` receiver enum exposes only `"cron" | "event" | "webhook" | "agent" | "cli" | "dashboard" | "inline"`.

### The `event` primitive

Skills declare an event trigger in their frontmatter:

```
# Skill: prox-handler
# Status: Approved
# Triggers: event: prox
# Vars: ROOM, USER

t:
    emit(text="${USER} entered ${ROOM}")
default: t
```

External services drive the skill by POSTing:

```
POST /event HTTP/1.1
Host: localhost:7878
Content-Type: application/json
Authorization: Bearer    # if SKILLSCRIPT_EVENT_INGRESS_AUTH_TOKEN set

{
  "event_name": "prox",
  "params": { "ROOM": "kitchen", "USER": "alice" }
}
```

Response on accept:

```json theme={null}
{ "run_id": "f4a8b21c-...", "durability": "in-process" }
```

The `run_id` is the runtime's `trace_id` — adopters paste it into the dashboard `/fires` view or query via the `fires({trace_id})` MCP tool to look up completion status.

### Wire contract

| HTTP status | Meaning |
| - | - |
| **200** | Accepted into THIS process's in-memory queue. `{run_id, durability: "in-process"}`. Skill fires async; the 200 does NOT mean skill-completed |
| **400** | Body not JSON; or `event_name` missing/empty; or params don't match declared (missing required or unknown extras) |
| **401** | Auth token configured + missing/wrong `Authorization: Bearer ` |
| **404** | `/event` route not enabled OR `event_name` not registered |
| **405** | Wrong method (POST-only) |

**Param validation is strict v1**: every declared param must be present; no unknown params accepted. No defaults; no type coercion. JSON already carries types, and a type mismatch fails inside the consuming op with a real error. Defaults + types may land in v2 if real adopter need surfaces.

### `# Autonomous: true` for event/cron skills doing mutations

Skills fired by cron OR event have **no interactive author** to confirm mutation ops. The runtime's mutation gate (`$ data_write` / `$ skill_write` / `file_write` / mutating MCP tools) requires explicit authorization in non-interactive contexts. Two authorization paths exist:

```
# Option A — skill-level: # Autonomous: true (recommended for cron/event skills)
# Skill: morning-sweep
# Status: Approved
# Triggers: cron: 0 9 * * *
# Autonomous: true

m:
    $ data_write content="..." tags=["digest"] -> R
    emit(text="sweep done")
default: m
```

```
# Option B — per-op: approved="" kwarg
# Skill: event-handler
# Status: Approved
# Triggers: event: incident-report
# Vars: SEVERITY

m:
    $ data_write content="${SEVERITY}" approved="event-fired" -> R
default: m
```

Without one of these, the runtime throws `UnconfirmedMutationError` at the mutation op + the skill fails its fire. Symptom in the trace: `class: "UnconfirmedMutationError"` on the offending op.

The mutation gate is identical for cron + event sources — both are non-interactive. Lint surfaces `unconfirmed-mutation` as tier-2 warning at compile time so authors get the signal before the first fire.

### `event_name` semantics

* **Public contract** addressed by POSTers. Skill behind the event can swap without breaking callers — the `skill_name` is private impl.
* **Case-insensitive** at register + lookup (normalized to lowercase internally).
* **1:1**: one `event_name` → exactly one skill in the deployment. Fan-out is NOT supported — a skill can call other skills via `$ execute_skill` if needed.
* **Cross-skill rebind allowed but audited**: registering an `event_name` that's already bound to a different skill replaces the binding (last-write-wins) AND logs a visible line (`event_name 'X' rebound: skill A → skill B`). Prevents silent cross-skill hijack without blocking the declarative re-save path. Same skill re-registering its own event is a silent upsert.

### Enabling the `/event` HTTP ingress

Off by default. Two operator knobs:

```bash theme={null}
# Required to open the /event route
SKILLSCRIPT_EVENT_INGRESS_ENABLED=true

# Optional bearer-token auth (when set, required on every POST /event)
SKILLSCRIPT_EVENT_INGRESS_AUTH_TOKEN=
```

When `eventIngressEnabled=true`, the route mounts on the same HTTP server as the dashboard/RPC (no second port). Default bind is `127.0.0.1` (localhost-only) — adopters wanting `0.0.0.0` external reach pass `--host 0.0.0.0` explicitly. The DMZ assumption is enforced by the bind, not by hope.

### Durability honesty

\*\*`200 = ACCEPTED, not durable**.** The skill is queued in this process's memory; if the process crashes or restarts before the queue drains, the fire is lost. The `durability: "in-process"\` field on every successful response self-describes this — adopters reading the response know the contract without consulting docs. Cron triggers have the same property today (no catch-up replay if the process was down).

Durable / at-least-once delivery is a v2 if real adopter need surfaces. Don't oversell the 200 contract; build durable queueing on top yourself if you need it now.

### Bridging external sources

Anything that isn't time-based is an external adapter that POSTs to `/event`:

* **Session start/end** — your harness POSTs `/event` after boot or before shutdown if you want a skill to fire at session boundaries.
* **Agent events** — your agent emits `POST /event` when the event of interest occurs.
* **File-watch** — an external watcher script (`inotify` / `chokidar` / `fswatch`) POSTs to `/event` on changes. The file-watching itself is standard OS plumbing — you own that script.
* **Sensors** — same pattern as file-watch; the sensor adapter POSTs to `/event`.

Skills declaring unsupported `# Triggers:` sources fail to parse with a tier-1 parse error. `skillfile lint` against your corpus surfaces them.

## Output template — body text IS the output

A skill's body text — prose lines that don't sit inside a target — is its declarative output template. The runtime interpolates `${VAR}` references against final vars and publishes the rendered string as the skill's canonical output (`outputs.text` or the agent/template/file payload, depending on `# Output:` kind). No `emit()` ceremony required for the common case. The template may appear **anywhere a target doesn't** — at the top, at the bottom, or split between targets — so authors can put output where their language instincts suggest (most write the output line *after* the compute that fills it in).

### The shape

```
# Skill: get-weather
# Vars: AREA="Brooklyn", TEMP="72", UNIT="F", DESC="sunny"

${AREA}: ${TEMP}°${UNIT} and ${DESC}.

fetch:
    shell(command="curl -s --max-time 10 https://wttr.in/${AREA|url}?format=j1") -> RAW
    $ json_parse ${RAW} -> W
    $set TEMP = "${W.current_condition.0.temp_F}"
    $set DESC = "${W.current_condition.0.weatherDesc.0.value|trim}"
default: fetch
```

Strip the compute block and the skill still emits the template with whatever the `# Vars:` defaults are. The author writes the sentence they want as output; the compute block fills in the holes.

### Complementary channels — template vs. emit

Two independent output channels:

| Channel | Source | Consumer |
| - | - | - |
| Canonical output (`outputs.text`, agent/template/file payloads) | Body template if authored, else joined `emit()` text | The caller / lifecycle-hook recipient / file write |
| Transcript (`emissions[]`) | All `emit(text=...)` calls + reasoning ops (`?`, `@`) | Trace records, dashboard `/fires` view, debug log |

When a skill defines both a template AND `emit(text=...)` calls, the template owns canonical output; `emit()` populates transcript only. This is intentional — emit is the debugging / reasoning channel. The `emit-with-template` advisory lint surfaces this to confirm intent.

If you want emit to be your canonical output, don't write a body template. Emit-only skills route emissions to the canonical output channel.

### Output kinds

The body template populates whatever `# Output:` kind the skill declares:

* `# Output: text` (default) — caller reads `outputs.text`
* `# Output: agent: ` — rendered template delivered as augment payload to `` via AgentConnector
* `# Output: template: ` — rendered template delivered as playbook payload
* `# Output: file: ` — rendered template written via file ops in the body

### Target syntax — what counts as a target

A target is `:` alone on a line, with an indented op-block on the next non-blank line. Anything else in the body region — content after a colon, a bare `Note:` with no following op-block, plain prose — reads as template text.

Two examples that are legal but worth knowing:

```
Summary: today is hot.        ← template (content after colon, no op-block)
Temp: ${T}                    ← template (content after colon)

Note:                          ← AMBIGUOUS — lint `template-looks-like-target` fires
                                  bare word: alone, no op-block. Disambiguate by adding
                                  content after the colon OR indent an op-block under it.
```

Target declarations with dependencies still work via the explicit `needs:` keyword, which makes intent unambiguous:

```
report: needs: fetch_issues
    emit(text="…")
```

The legacy `report: fetch_issues` shape (deps after colon, no `needs:` keyword) is still parsed as a target when an indented op-block follows on the next line, but `needs:` is the recommended form for new skills.

### One template region per skill

A skill may carry template prose in one region. Splitting it into two — some prose above the targets AND some below — raises a tier-1 parse error: "skill has body template content in two places (before targets AND after targets). Pick one location." Picking is loud over silent-concat; the author chooses where the template lives, the runtime doesn't guess.

### Lints to know

* **`unset-template-var`** (tier-1) — every `${VAR}` in the template must resolve to a `# Vars:` / `# Requires:` input, an ambient ref (`NOW`, `USER`, ...), or a `$set` / `->` binding somewhere in the skill body. Tier-1 because an unbound ref renders empty silently.
* **`template-looks-like-target`** (tier-2) — bare `:` alone in the template region, no following op-block. Ambiguous shape — author may have meant a target.
* **`connector-as-tool`** (tier-1) — `$  ` space-separated catches the muscle-memory foot-gun (CLI-style `git status`). Bare-form dispatch treats the first token as the tool name, sending `name: ""` to the MCP server, which replies with a misdirecting `Tool '' not found.` The two correct shapes are `$ . args` (dotted) or `$  args` (bare-tool; runtime resolves).
* **`remote-result-needs-parse`** (tier-3) — `${R|length}` on an `R` bound by `$` dispatch. Per-MCP-server result shapes vary: if the server returns prose-wrapped or non-JSON text, the value binds as a STRING and `|length` returns the string's char-count instead of element-count. Add `$ json_parse ${R} -> P` after the dispatch and use `${P|length}`. Suppressed when the skill already does `$ json_parse ${R}` somewhere — your defensive parse is taken as intent.
* **`body-template-detected`** (tier-3) — non-blank, non-`#` lines in the body region, no `${...}` interpolations, no text-consuming `# Output:` declaration. Suggests "I wrote prose; it became template by accident." Prefix with `#` to mark as comments, or add an interpolation / `# Output:` to confirm intent.
* **`emit-with-template`** (tier-3) — skill has both a template AND `emit(text=...)` calls. Confirms the channel-shift is intentional.

## Fallback semantics — `(fallback: ...)` op-trailer and `|fallback:` filter

Two surfaces, **one emptiness predicate**. Both fire when the upstream value is any of:

* empty string after `trim()`
* empty array (`[]`)
* `null` / `undefined`

### Op-trailer — `(fallback: "value")`

Trails the `-> R` binding on every fallible op — `$` dispatch (including the `$ json_parse` intrinsic), `shell(...)`, `file_read(...)`, `execute_skill(...)`. Binds the fallback value to `R` when the op fails, whatever the failure shape — a raised throw (an `execute_skill` child-throw, off-shape `json_parse` input) or an empty result — and records the reason in the result's `fallbacks[]`. Uniform across all fallible ops.

```
$ ticketing.search query="open" -> ISSUES (fallback: [])

shell(argv=["gh", "pr", "list", "--repo", "owner/repo"]) -> PRS (fallback: "No current PRs.")

file_read(path="/var/reports/today.md") -> REPORT (fallback: "no report")
```

When the fallback fires, the runtime pushes a record onto `result.fallbacks[]` so callers can distinguish "real value" from "fallback substituted." The original error message rides on the fallback record's `reason` field; the op completes cleanly.

### Filter — `${VAR|fallback:"value"}`

Substitution-time fallback inside a template or kwarg. Same emptiness predicate; binds to the filter argument when the upstream value is empty.

```
Open PRs: ${PRS|fallback:"none today"}.

$ llm prompt="Triage this: ${INPUT|fallback:'(no input — skip)'}" -> JUDGMENT
```

The filter is positional in chains: `${RAW|trim|fallback:"-"}` applies trim first, then fallback if the trim left an empty string.

### When to use which

* **Op-trailer** for *binding-time* protection — the variable lands populated regardless of the op's outcome. Downstream consumers (other ops, template renders) don't need to know whether the value is real or fallback.
* **Filter** for *substitution-time* defaulting — the variable may legitimately be empty/unset, you just want a placeholder at the render site.

Most "no current results" patterns want the op-trailer (the variable becomes the canonical record of what happened). The filter is for "if the optional input wasn't supplied, show a placeholder" cases.

## Wiring the AgentConnector

`AgentConnector` is the substrate-neutral delivery surface for `# Output: agent: X` / `# Output: template: X` lifecycle hooks and `notify()` / `exchange()` ops. The runtime calls into the contract; your impl decides where the payload lands (webhook, tmux session, file drop, IPC pipe, Slack thread, your own agent harness, etc.).

The full contract surface — methods, payload shapes, receipt shapes, the `agent@session` targeting convention, the graceful-degradation rule — lives in [Connector Contract Reference](connector-contract-reference.md) §AgentConnector. This section covers the **wiring path** for adopters: how to bring an impl online so the runtime uses it.

### Two wiring paths

Same shape as the other substrate slots — programmatic (recommended for custom impls today) or declarative (`connectors.json`, restricted to bundled types).

**(a) Programmatic — for adopter-written impls.** Construct the connector in your bootstrap and pass it via `BootstrapOpts.agentConnector`:

```typescript theme={null}
import { bootstrap } from "skillscript-runtime";
import { MyAgentConnector } from "./my-agent-connector.js";

const { registry, scheduler, server } = await bootstrap({
  agentConnector: new MyAgentConnector({
    endpoint: process.env["MY_AGENT_ENDPOINT"],
    api_key: process.env["MY_AGENT_API_KEY"],
  }),
});
```

`bootstrap()` calls `registry.registerAgentConnector("primary", ...)` for you. `health_check()` fires during registration — wiring failures throw at boot, not at first delivery.

**(b) Declarative `connectors.json`** — for bundled types and the (deferred) custom-via-dynamic-import path:

```json theme={null}
{
  "substrate": {
    "agent_connector": "noop"
  }
}
```

Bundled short-form values:

| Value | Behavior |
| - | - |
| `null` (or omitted) | `NoOpAgentConnector` — silent fallback. `deliver()` / `wake()` log + resolve; `# Output: agent:` declarations complete with a stderr warning. Lets a runtime start with no harness wired. |
| `"noop"` | Same as `null` but explicitly stated. |
| Object with `"type": "custom"` | Adopter impl resolved by dynamic-import (deferred — surfaces a clear error today; use programmatic path). |

For full configuration shape, see [Configuration](configuration.md) §"The substrate section."

### Precedence

Same as other substrate slots:

1. **Programmatic** `BootstrapOpts.agentConnector` — explicit, highest priority.
2. **Declarative** `connectors.json` `substrate.agent_connector` — deployment-durable.
3. **Built-in default** — `NoOpAgentConnector`. Skills with `# Output: agent:` fire warnings, not errors.

The NoOp fallback is the design choice that makes "runtime works out of box without any AgentConnector wiring" hold. Adopters who want strictness should explicitly wire their connector and let `health_check()` throw if it can't start.

### Worked example

The canonical bundled example is `examples/connectors/HttpWebhookAgentConnector/` — a complete `AgentConnector` impl against an HTTP-webhook substrate. It demonstrates:

* Per-agent URL routing (`HTTP_WEBHOOK_AGENTS` JSON env)
* Optional `wake_url` per agent — present means wake-capable, absent means degrade-on-wake
* Bearer + HMAC auth (combinable)
* Tolerant receipt synthesis (substrate returns substrate-shaped JSON; connector translates to canonical `DeliveryReceipt`)
* Tests covering the deliver / wake / health-check / request-response surface

Three patterns to copy when forking it for your substrate:

**Pattern 1 — `agent@session` opaque composite.** Every messaging substrate needs either bare-identity OR specific-live-session addressing. The contract keeps `agent_id` opaque; sessions ride as `"@"` (e.g. `"alice@laptop-tab-3"`) or via `WakeOpts.session_id`. Substrates that care decompose; substrates that don't ignore.

The runtime address-routes skill-author surfaces (`notify()` + `# Output: agent:` / `template:`) on `@session` presence: bare → your `deliver()`, composite → your `wake()`. You receive whichever method the runtime decided; your job is to honor what arrives. For `wake()`, expect the FULL composite (`"@"`) — decompose to route to the right session:

```typescript theme={null}
async wake(agent_id: string, opts?: WakeOpts): Promise {
  // Form A — composite in agent_id
  const [agent, embeddedSession] = agent_id.split("@");
  // Form B — opts.session_id wins if both supplied
  const session = opts?.session_id ?? embeddedSession;
  // ... route to (agent, session)
  return { woken_at: Date.now(), woken: true, ...(session ? { session_id: session } : {}) };
}
```

**Pattern 2 — graceful degradation on wake.** `wake()` must not throw because your substrate lacks interrupt capability. Distinguish capability-gap (degrade) from operational-fault (throw):

```typescript theme={null}
async wake(agent_id: string, _opts?: WakeOpts): Promise {
  const cfg = this.agents[agent_id];
  if (!cfg) throw new Error(`agent not configured: ${agent_id}`);  // operational fault
  if (!cfg.wake_url) {
    // capability gap — no interrupt channel for this agent — degrade
    return { woken_at: Date.now(), woken: false };
  }
  const response = await fetch(cfg.wake_url, { ... });
  if (!response.ok) throw new DeliveryFailedError(...);  // operational fault
  return { woken_at: Date.now(), woken: true };
}
```

Callers reading `WakeReceipt.woken` distinguish "the substrate woke them" from "the substrate stored the payload for later" without needing per-substrate knowledge.

**Pattern 3 — session echo on receipts.** When your substrate routes to a specific session, echo it back on `DeliveryReceipt.session_id` / `WakeReceipt.session_id`. Dashboards rendering "delivered to alice\@laptop-tab-3" rather than just "delivered to alice" depend on this.

**Pattern 4 — read `meta.origin.caller_agent_id` to attribute, not for scope.** The `DeliveryMeta` envelope your `deliver()` receives carries `origin.caller_agent_id` = the *authenticated caller* who fired the dispatch (not the skill's owner — those are separate semantics; see [Connector Contract Reference](connector-contract-reference.md) §field semantics). Use it for *attribution* — rendering `from ` on the receiving end, audit logs, accountability — not for authorization scoping. Outbound substrate scoping should derive from the *skill owner* (which the runtime applies at the connector layer via `ctx.agentId`, not via the envelope). If `caller_agent_id` is undefined on a delivery you receive, it means the chain originated from a non-human trigger (cron / event / scheduler) — your substrate should attribute it as "system-fired" or similar, not assume an identity.

**Pattern 5 — surface non-fatal notes via `DeliveryReceipt.warnings`.** When your substrate needs to signal something non-fatal about a delivery — "stripped @session because verb is deliver", "rate-limit hint", "fan-out: delivered to 3 sessions" — return them as `warnings: string[]` on the receipt instead of writing to stderr. The runtime echoes warnings onto `AgentDeliveryReceiptRecord.receipt.warnings`, where the dashboard can render them and observability tools can scrape them. Stderr noise gets lost; receipt warnings are structured + caller-visible.

### When to fork vs. when to write fresh

* **Fork `HttpWebhookAgentConnector`** when your substrate is HTTP-shaped and your changes are: tweaked auth (OAuth, mTLS), retry policy, different routing model. Most production deployments end up here.
* **Write fresh** when your substrate is fundamentally non-HTTP (tmux, file drop, gRPC, websocket-push). Implement the five required methods (`list_agents`, `deliver`, `wake`, `health_check`, `request_response`) + optional `agent_status`. Use `NoOpAgentConnector` as the minimal-shape reference.

In either case: write tests against the contract methods (the bundled example's `tests/HttpWebhookAgentConnector.test.ts` is a useful template), wire via `BootstrapOpts.agentConnector`, and let `health_check()` enforce the "fail-at-boot, not at first delivery" property.

## Authoring posture — who owns the skills you write

Every skill stored in a `SkillStore` carries a `SkillMeta.author` field captured at first-write. The author is then load-bearing at dispatch time: the runtime threads it into `ctx.agentId` so identity-scoped substrates (memory stores, multi-tenant DBs) read and write under that scope.

How `author` is captured depends on how the skill gets written:

* **CLI / dashboard / direct programmatic API.** When you call `SkillStore.store(name, body)` from your own code (CLI, bootstrap, scripts) or via the dashboard's approval flow, the SkillStore captures author from its bundled default. `FilesystemSkillStore` uses `os.userInfo().username`; adopter stores capture from their own auth context.

* **MCP `skill_write` from a single-tenant host.** If only one agent (or one human) calls your runtime, you don't need to configure anything — the `SkillStore.store()` default-author logic above applies. **Skip the multi-agent section below.**

* **MCP `skill_write` from a multi-agent host.** If multiple agents share one runtime instance via MCP (e.g., a host that bridges several authenticated agents into one transport), the runtime can't tell them apart at the protocol layer. See the next section.

### Direct-write authoring path

Adopters whose `SkillStore` is backed by an addressable substrate (e.g., a memory store) can author skills by writing the substrate record directly — without going through the MCP `skill_write` handler. This captures `SkillMeta.author` from the substrate's own writer-identity (whatever the direct-write API authenticates as).

**Gotcha:** in **secured mode**, a direct-write declaring `# Status: Approved` without a valid signature is forced to `Draft` — the substrate can't mint approval, only the operator's key can. Publish by writing `Draft`, then signing via `skillfile approve ` or the dashboard Approvals queue (both preserve the captured author). In **unsecured mode** a bare `# Status: Approved` direct-write is honored as-is. Either way, in-skill `$ skill_write` always lands its child `Draft` regardless of body declaration. See [Approval + secured mode](#approval--secured-mode).

### Discovering connector tools while authoring

When a skill dispatches an MCP connector tool (`$ . ...`), the runtime helps an author get the call right without a guess-and-run loop:

* **`runtime_capabilities`** lists the wired connectors and their tool names (a compact menu). Pull one tool's full argument schema on demand with `runtime_capabilities({ tool: "." })` — the manual for the tool you're about to call, kept out of the default response so it stays small.
* **`lint_skill`** validates the args you wrote against that schema: an unknown arg name (`$ ddg.search querry=...`) or a missing required arg surfaces as a tier-2 warning at author time instead of failing at dispatch. Degrades silently when a connector's schema isn't reachable (no false positives).
* **`skill_preflight`** shows, for the connector tools the skill actually calls, both their input schema and — once any approved run has dispatched the tool — its **last-observed output shape** (keys + types), so you know what `-> R` will bind before you run.

All three respect the connector's `allowed_tools` gate: a tool the operator gated off is never surfaced or validated against. The observed-output-shape cache holds keys + types only (not values) and lives operator-local under `~/.skillscript/`.

## Identity propagation — for multi-agent hosts

**Skip this section** if your runtime serves one agent (CLI tools, single-user dashboards, hobby deployments). The default — `SkillMeta.author` captured from the SkillStore's writer identity — already attributes authorship correctly when there's only one writer.

This section is for adopters whose runtime is fronted by an MCP host that bridges multiple authenticated agents into one transport (e.g., a multi-agent gateway, or a multi-tenant SaaS where agents share a runtime pool).

### The gap MCP doesn't close on its own

JSON-RPC over HTTP doesn't carry a standard "calling identity" field. Without an extra convention, every `skill_write` call into your runtime stamps `SkillMeta.author = ` — regardless of which agent on the host actually originated the call. Subsequent `execute_skill` dispatches then run under the wrong scope. Identity-scoped reads return the runtime's own data, not the calling agent's.

### Opt-in: a configurable inbound header

When you configure `dashboard.mcpCallerIdentityHeader`, the runtime reads that header on every `/rpc` request and threads its value as the caller-identity through to `skill_write`. The handler stamps `SkillMeta.author = 
`. Different callers with different header values get distinct stored authors. ```json theme={null} { "dashboard": { "host": "127.0.0.1", "port": 7878, "mcpCallerIdentityHeader": "X-Agent-Id" } } ``` Multi-agent host (custom MCP gateway, etc.) is responsible for setting the header on every outbound request: ```http theme={null} POST /rpc HTTP/1.1 Host: skillscript-runtime Content-Type: application/json X-Agent-Id: alice {"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"skill_write","arguments":{"name":"alice-skill","source":"..."}}} ``` * Header lookup is case-insensitive (Node lowercases inbound header names). * Absent header on a configured runtime → caller identity is undefined for that request → `SkillStore.store()` falls back to its default author capture (existing single-tenant behavior). Backwards-compatible — hosts that don't inject identity behave exactly as before. * Empty header value → treated as absent. ### Trust model The runtime trusts the host's header attestation. There's no signature verification on the *identity claim* (distinct from secured-mode approval, which *is* signature-verified — different boundary, different mechanism): anyone reaching the runtime with a forged `X-Agent-Id` could claim to be anyone. The runtime is **not** the authentication boundary; the host is. Bilateral trust: * **The host** (your MCP gateway) authenticates the agent via its own auth surface (OAuth, JWT, session cookies, mTLS — whatever fits your platform) and injects the verified identity into the outbound `X-Agent-Id` header. * **The runtime** trusts the host because you configured it to (`mcpCallerIdentityHeader` is opt-in; unset means "I don't trust any inbound identity claim, fall back to my own writer identity"). Don't expose the `/rpc` endpoint directly to untrusted clients with this configuration. Run behind your host's auth-enforcing reverse proxy or in a trusted-network deployment. ### Inbound vs outbound — same header, two layers Connectors like `HttpMcpConnector` use the **same header name** (`X-Agent-Id` by convention) for outbound calls to substrates — see the [HttpMcpConnector configuration](#case-2--mcp-tools-wiring-substrate-locked) above. The two are NOT the same value in general: * **Inbound** (this section) = request-scoped caller — who's currently calling the runtime via MCP. * **Outbound** (`HttpMcpConnector.identityHeader`) = dispatch-scoped owner — derived from `SkillMeta.author` of the skill being executed, asserted to the substrate so reads land in the owner's scope. They MEET at `SkillMeta.author`. The runtime captures inbound caller identity at `skill_write` (stamps it as the skill's author); at execute time, the runtime threads `author` into `ctx.agentId`; the outbound connector asserts that to the substrate. The same `X-Agent-Id` header carries two different identity claims at the two boundaries; the stored author is the bridge. **Critical:** never forward an inbound `X-Agent-Id` header straight to an outbound connector. The skill's owner is who should access the substrate, not the current caller. If anyone invokes alice's skill and the outbound used the caller's identity instead of alice's, the substrate would scope to the caller — a setuid hazard. The runtime keeps the two separate; outbound identity is always derived from author at dispatch. ### Verification After wiring + restart, a smoke test: ```bash theme={null} # Write a skill as alice curl -X POST http://localhost:7878/rpc \ -H "content-type: application/json" \ -H "X-Agent-Id: alice" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"skill_write","arguments":{"name":"smoke","source":"# Skill: smoke\n# Status: Draft\nrun:\n emit(text=\"hi\")\ndefault: run"}}}' # Verify author was stamped from the header curl -X POST http://localhost:7878/rpc \ -H "content-type: application/json" \ -d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"skill_preflight","arguments":{"name":"smoke"}}}' \ | jq '.result.content[0].text | fromjson | .metadata.author' # Expected: "alice" ``` If the second call returns the runtime's own writer identity instead of `"alice"`, either the config field is unset, the header didn't reach the runtime (check your proxy / host wiring), or you sent the request with a different header name than configured. ## Conventions for upstream-merge-friendly modifications If your wiring needs require modifying skillscript-runtime source (rather than just configuration), follow these conventions to minimize merge friction. ### 1. Prefer dedicated adopter files over editing upstream Put your code in dedicated paths upstream won't touch: ``` src/connectors/local/my-data-store-adapter.ts ← adopter-owned src/connectors/local/my-llm-adapter.ts ← adopter-owned ``` Upstream changes to `src/connectors/data-store.ts` won't conflict with your `local/` files. ### 2. Use the public registration API; don't edit the closed-set Map `KNOWN_CONNECTOR_CLASSES` in `src/connectors/config.ts` is upstream-owned. Add your classes via `registerConnectorClass(name, entry)` from your bootstrap instead. Closes the merge-conflict bait of editing that file every release. ### 3. Mark unavoidable upstream-file edits with sentinels When you genuinely have to edit an upstream file, mark the change: ```typescript theme={null} // ADOPTER:myorg — extend dispatch to call our auditor before forward if (process.env["MYORG_AUDIT"] === "1") { /* ... */ } ``` The `// ADOPTER:myorg —` prefix is greppable across merges; your future-self can re-evaluate whether the modification is still needed when upstream changes the surrounding code. ### 4. Treat `src/bootstrap.ts` as reference, not canonical For the standard "wire the whole runtime + dashboard from `$SKILLSCRIPT_HOME` like the CLI does" case — which is most adopters — call **`bootstrapFromEnv()`** (see §"Programmatic bootstrap path"). It's the supported public entry point; you don't hand-assemble anything, and you swap substrates declaratively via `connectors.json`. Remember to `await wired.registry.disposeAll()` on shutdown so stdio-bridged connector children (RemoteMcpConnector) are reaped, not orphaned — `bootstrapFromEnv()` callers own teardown (the CLI does it for you). Drop to raw `bootstrap()` + `Registry` only when you're hand-assembling a substrate that `connectors.json` can't express — import the public APIs (`Registry`, the connector classes, `loadConnectorsConfig`, `loadSkillscriptConfig`, etc.) rather than modifying the bundled bootstrap, which churns on every upstream release. See `examples/custom-bootstrap.example.ts` for a worked walkthrough. ## Substrate ship-status | Substrate | Shipped contract | Shipped impls | Shipped bridge | | - | - | - | - | | SkillStore | ✓ 8 methods (`load` / `query` / `store` / `update_status` / `delete` / `versions` / `metadata` / `manifest`) + `staticCapabilities` | `FilesystemSkillStore`, `SqliteSkillStore` | n/a | | DataStore | ✓ 4 methods (`query` / `write` / `get` / `manifest`) + `staticCapabilities` | `SqliteDataStore` | ✓ `DataStoreMcpConnector` | | LocalModel | ✓ 1 method (`run`) | `OllamaLocalModel` | ✓ `LocalModelMcpConnector` | | McpConnector | ✓ 1 method (`call`) | `RemoteMcpConnector`, `CallbackMcpConnector` | n/a | | AgentConnector | ✓ 5 required (`list_agents` / `deliver` / `wake` / `health_check` / `request_response`) + 1 optional (`agent_status`) | `NoOpAgentConnector` (default), `HttpWebhookAgentConnector` | n/a | **Notable things the playbook should be honest about:** * **`SqliteDataStore` is a deliberately minimal reference impl.** It satisfies the contract (`query` / `write` / `get` / `staticCapabilities` / `manifest`) with FTS-style tag/text retrieval. It does NOT support semantic retrieval, pinning, decay scoring, or thread-status filtering (the relevant `supports_*` flags are all false). Deployments that need richer query semantics fork `examples/connectors/DataStoreTemplate/` and wire their backing substrate. * **SkillStore and DataStore have different lifecycle models — by design.** SkillStore is mutable / versioned / named CRUD (Draft→Approved→Disabled→Delete with audit trail). DataStore is append-only with query/get (no per-record lifecycle in the contract). If you back both onto one substrate, you're serving both lifecycle models at once. Substrates that conflate "data record expiry" with "skill expiry" silently break authored code; the contract doesn't enforce this, you handle it impl-side. * **Durability is implementer's responsibility.** The typed contracts assume durable storage. Neither interface declares "writes live forever" — but the runtime + lint + dashboard all behave as if writes persist indefinitely. If your substrate has GC / TTL / decay scoring, build adopter-side guards (pin-rules, retention policies, periodic re-pin sweeps) or pick a substrate posture that satisfies "durable forever." Silent staleness is the failure mode the contract won't catch. * **Mutation ops require runtime-enforced authorization.** `$ data_write` / `file_write` / `$ ` (write/update/delete/etc.) fire `UnconfirmedMutationError` at the runtime boundary unless the skill carries `# Autonomous: true` (cron/agent-fired) OR the op carries `approved="reason"` per-op kwarg. This fires regardless of how the skill was invoked — `execute_skill({name})` AND `execute_skill({source})` honor the gate identically; lint stays advisory. Adopters running unattended skills programmatically should set `# Autonomous: true` at the header. * **In-skill writes have asymmetric trust models.** `$ skill_write` lands its child as `# Status: Draft` regardless of body declaration — the bridge forces it. Authoring an executable artifact has unbounded blast radius (the child fires arbitrarily many times in arbitrary contexts); the Draft default keeps autonomously-written skills out of the immediate execution loop. `$ data_write` writes verbatim — one bad data row is bounded blast radius. SkillStore impls receive the body already Draft-stamped; DataStore impls receive entries as authored. * **Your `DataStore.write()` is never called if the mutation gate rejects the skill.** The runtime gates `$ data_write` (and other mutation ops) upstream of the bridge — substrates only see authorized writes. If your own probes hit `UnconfirmedMutationError`, that's a skill-body issue (missing `# Autonomous: true` / `approved=`), not a substrate issue. * **Filter scope is enforced at the bridge.** `DataStoreMcpConnector` rejects every filter key outside the substrate's declared `manifest().supported_filters` set, throwing `UnsupportedFilterError`. This prevents silent scope leaks where unsupported filters get dropped without the caller knowing. Per-call opt-out: `permissive_filters: true` acknowledges "unknown keys are advisory; substrate may ignore them." Substrate implementors: declare every filter your `query()` actually honors so the bridge validates against your truth, not a guess. * **FTS matching strictness varies by substrate.** The `DataStore.query()` contract names the modes (`fts` / `semantic` / `rerank`) but doesn't pin down matching semantics within each mode — token-OR, phrase-tokens, fuzzy, exact, FTS5-syntax-passthrough, etc. are all conformant. The bundled `data-store-roundtrip` demo asserts `N ≥ 1` (a successful round-trip) rather than a specific count, which works across any FTS-supporting substrate. For adopters who need deterministic exact-count reads (round-trip tests, idempotency checks, exact-record-matched fetches), the portable strict-match path is `domain_tags=[...]` filtering — the bridge enforces tag-key against `supported_filters` and substrates declaring `supports_tag_filter: true` honor exact-tag any-of-match per the contract. Use FTS for relevance ranking against open content; use tag filters when you need to be sure you got the specific record you wrote. * **Durable-forever opt-in via `expires_at: null`.** `DataWrite.expires_at` accepts a unix timestamp for finite expiry, `null` to opt into "durable forever" (the portable verb for substrates with default TTL — Redis with default expiry, hosted memory APIs), or omitted (substrate's default lifecycle, may be durable or may have decay). Substrates that are durable-by-default (the bundled `SqliteDataStore`) treat `null` as a no-op. Substrates with default sweep should map `null` to their pin / no-decay flag. * **Two trigger primitives, both functional.** `cron` (time-based) and `event` (HTTP `/event` ingress, named registration). All other concepts that look like triggers — session-start, agent-event, file-watch, sensor — are adapter responsibilities: the adapter POSTs `/event` when relevant. Keeps the runtime substrate-neutral; the trigger surface stays tight. * **Output kinds are intentionally substrate-neutral.** `# Output:` accepts `text` / `agent: ` / `template: ` / `file: ` / `none`. Substrate-specific values (`slack:`, `card:`, etc.) are out of scope — adopters wanting Slack / WhatsApp / Discord / etc. delivery use either `$ slack.post ...` MCP dispatch inside the skill body OR deliver via `agent: ` and let the receiving agent decide. * **Authorization is signature-based in secured mode.** An `Approved` skill runs unkeyed in unsecured mode (a bare `# Status: Approved` is sufficient) and requires a valid Ed25519 operator signature in secured mode — verified on every execution against the operator's public key, with the private key held off the runtime. See [Approval + secured mode](#approval--secured-mode) for the model, the approve flow, key custody, and migration. The shell + filesystem allowlists bound blast radius in *both* modes; secured mode is what gates whether an unapproved skill runs at all. ## Skill discovery + cross-agent composition If you back your SkillStore against a substrate that ALSO holds general data records (one substrate serving both contracts), skill discovery can use the canonical `$ data_read` surface to find skills via tag/query: ``` $ data_read mode=fts query="incident triage" limit=5 -> SKILLS foreach S in ${SKILLS.items}: execute_skill(skill_name="${S.name}", ...) -> RESULT ``` This works *only* when the data substrate is Case-1 wired (typed-contract via bridge) AND your substrate's records identify skills somehow (a tag, a payload-type marker, etc. — your impl's choice). Under Case-2 wiring, you'd need substrate-specific tool calls which are non-portable. For most deployments, skill discovery goes through the canonical `skill_list` MCP tool (which calls `SkillStore.query()`). The `$ data_read`-as-discovery pattern is for the niche case where skills and other records share a backing store with rich tag/query semantics. ## Contributing — dispatch-shape discipline The multi-layer-promise pattern (lint passes; runtime fails, or vice versa) is the recurring failure mode for dispatch-shape work. `validateQualifiedDispatch` is the shared validator lint and runtime both call. To prevent the next recurrence, every PR that introduces a new dispatch shape (a new way of writing `$ ...` ops, a new connector class entry point, a new lifecycle hook on `# Output:`) must land with: 1. **Lint test** — fixture that exercises the shape with lint only (`lint(source, {registry})`) 2. **Runtime test** — same shape executed end-to-end (`executeSkillByName` or `executeSkillFromSource`) 3. **E2E test** — the full user path (write skill → store → execute via MCP, or trigger fire → dispatch) PR description must call out which dispatch shape is exercised. If you can't write all three for a shape, that's a signal the shape is incompletely specified — open an issue before merging. Connector class authors implementing new `McpConnectorClass`-shaped contracts should also implement `staticTools(): string[] | null` whenever the tool surface is closed and knowable at compile time. Lift `unknown-tool-on-connector` from "advisory you fix at runtime" to "tier-1 error caught at compile time" for every adopter who wires your class. ## Resources * **Onboarding scaffold** — `examples/onboarding-scaffold/` — complete adopter deployment with a file-backed data store + OpenAI + tmux * **Custom bootstrap walkthrough** — `examples/custom-bootstrap.example.ts` — registering custom MCP connector classes * **Connectors example** — `scaffold/connectors.json` — annotated `connectors.json` shape * **Language reference** — `docs/language-reference.md` — skill syntax + frontmatter + lint codes * **Connector contracts** — `docs/connector-contract-reference.md` — substrate-neutral contract surfaces * **Configuration** — `docs/configuration.md` — `connectors.json` shape + substrate selection # Configuration Source: https://docs.skillscript.ai/docs/configuration How to configure a skillscript-runtime deployment — connectors.json substrate selection, named MCP connector wiring, runtime knobs, and adopter-custom impls. How to configure a skillscript-runtime deployment. The single config file is **`~/.skillscript/connectors.json`** (or any path passed via `--connectors`). It has two top-level concerns: 1. **`substrate`** — which `SkillStore`, `DataStore`, `LocalModel`, and `AgentConnector` the runtime hosts (MCP server + web dashboard) use. 2. **Named MCP connector instances** — `youtrack`, `github`, etc. — invoked via `$ ` in skill source. The runtime loads `connectors.json` at startup. Missing file → graceful empty config (substrate defaults to filesystem skills + conditional sqlite memories; no MCP connectors). Malformed JSON or unknown fields → structured errors surfaced at bootstrap. *** ## `SKILLSCRIPT_HOME` — the root override Every default path the runtime computes is rooted under `SKILLSCRIPT_HOME`: | Default path | Resolves to | | - | - | | Connectors file | `$SKILLSCRIPT_HOME/connectors.json` | | Config file | `$SKILLSCRIPT_HOME/skillscript.config.json` | | Triggers file | `$SKILLSCRIPT_HOME/triggers.json` | | Skills directory (`skillsDir`) | `$SKILLSCRIPT_HOME/skills/` | | Sqlite skill store dbPath | `$SKILLSCRIPT_HOME/skills/skills.db` | | Sqlite data store dbPath | `$SKILLSCRIPT_HOME/data.db` | | Trace directory | `$SKILLSCRIPT_HOME/traces/` | `SKILLSCRIPT_HOME` defaults to `~/.skillscript`. Set the env var to relocate **everything** under a different root — the cleanest multi-instance isolation primitive: ```bash theme={null} # Adopter instance with fully isolated state export SKILLSCRIPT_HOME=~/.skillscript-adopter skillfile dashboard --host 127.0.0.1 --port 7879 ``` Every derived path now lives under `~/.skillscript-adopter/`; the dev instance at `~/.skillscript/` is untouched. No `--connectors` flag, no explicit `dbPath` overrides needed — defaults follow `SKILLSCRIPT_HOME`. See [`docs/adopter-playbook.md`](adopter-playbook.md) § "Two-instance posture" for the broader pattern. > **Why this matters for adopter setups.** Without `SKILLSCRIPT_HOME` isolation, two daemons running side-by-side would share `triggers.json`, `skillsDir` (filesystem default), and any other `$HOME/` default — even if their sqlite `dbPath`s were explicitly distinct. `SKILLSCRIPT_HOME` is the architectural primitive; everything else derives from it. *** ## Environment variables + `.env` file The CLI auto-loads `$SKILLSCRIPT_HOME/.env` at startup and populates `process.env` for any key not already set in the shell. Drop a `.env` next to `skillscript.config.json` and posture switches are picked up at next restart — the installer/operator pattern. ### Direct env-var reads — the runtime checks `process.env` for these | Env var | Effect | Cascade precedence | | - | - | - | | `SKILLSCRIPT_HOME` | Config root (default `~/.skillscript`) | shell-set only — read before `.env` loads | | `SKILLSCRIPT_FORCE_ALWAYS_DRAFT=true` | Force outside-MCP `skill_write` to Draft; closes the agent-self-approval path | env > config > default `false` | | `SKILLSCRIPT_ENABLE_UNSAFE_SHELL=true` | Permit `shell(unsafe=true)` ops (syntax-scope axis) | env > config > default `false` | | `SKILLSCRIPT_SHELL_ALLOWLIST=curl,git,jq` | Comma-separated list of binaries reachable via `shell(...)` ops (binary-scope axis). **Default-deny** when unset — run `skillfile shell-audit` to discover your corpus's set. Honored on both CLI and programmatic-`bootstrap()` paths; explicit `bootstrap({ shellAllowlist: [...] })` (including `[]` deny-all) wins over env. See [adopter-playbook](adopter-playbook.md) § "Programmatic bootstrap path" for the precedence table. | `bootstrap()` opt > env > config > default-deny | | `SKILLSCRIPT_FS_ALLOWLIST=/srv/work,/var/events` | Comma-separated roots under which `file_read` / `file_write` may operate (path-scope axis). **Default-deny** when unset — every file op refused. Canonicalized before the check, so `..` / symlink escapes are closed. **Keep secret / key directories OUT.** | env > config > default-deny | | `SKILLSCRIPT_SECRET_=` | Provisions the secret that `{{secret.NAME}}` resolves to (declared via `# Requires: secret.NAME`). Use-only: the value is injected at a sink (`shell` / `$` dispatch) and never binds to a skill variable, a trace, or an error message. The `SKILLSCRIPT_SECRET_` prefix scopes which env is secret-reachable — `{{secret.PATH}}` reads `SKILLSCRIPT_SECRET_PATH`, never `$PATH`. See [adopter-playbook](adopter-playbook.md) § "Secrets". | env (`EnvSecretProvider`; vault providers via `bootstrap({ secretProvider })`) | | `SKILLSCRIPT_SECURED_MODE=true` | Enforce the approval boundary: only Ed25519-signed skills perform effectful ops; unapproved or tampered skills are refused regardless of dispatch path (CLI / cron / `/event` / MCP / composition). Default `false` — a bare `# Status: Approved` is sufficient (unkeyed). See [adopter-playbook](adopter-playbook.md) § "Approval + secured mode". | `bootstrap()` opt > env > config > default `false` | | `SKILLSCRIPT_APPROVAL_KEY_FILE=` | Operator **private** signing key — read only by the approve flow, never on the execution hot path. Default `~/.config/skillscript/approval.key` (deliberately outside `SKILLSCRIPT_HOME`). Auto-provisioned `0600` on first secured-mode start if absent. | env > default | | `SKILLSCRIPT_APPROVAL_PUBLIC_KEY_FILE=` | Operator **public** verification key (non-secret) — read by the runtime to verify signatures on every execution. Default `~/.config/skillscript/approval.pub`. | env > default | | `SKILLSCRIPT_APPROVAL_PASSCODE=` | Opt into in-browser dashboard approval: when set, the dashboard signs server-side after a one-time passcode unlock (session-scoped, \~15-min idle TTL). Unset = dashboard is review-only; signing only via `skillfile approve` at a terminal. | env > default unset | | `SKILLSCRIPT_DASHBOARD_AUTH_TOKEN=` | Gate the dashboard SPA + `/rpc` behind a token (`?token=` / cookie / `Authorization: Bearer`). Network hygiene for a dashboard reachable beyond localhost — not a forgery boundary. (`/event` keeps its own bearer gate.) | env > default unset | | `SKILLSCRIPT_PORT=8080` | Dashboard / serve HTTP port | `--port` flag > env > config > default `7878` | | `SKILLSCRIPT_HOST=0.0.0.0` | Bind address | `--host` flag > env > config > default `127.0.0.1` | | `SKILLSCRIPT_MCP_CALLER_IDENTITY_HEADER=X-Agent-Id` | Inbound caller-identity header name (multi-agent MCP hosts only — see [adopter playbook](adopter-playbook.md)) | env > config > default unset | | `SKILLSCRIPT_POLL_INTERVAL_SECONDS=30` | Scheduler tick / poll interval (seconds) | env > config > default `30` | | `SKILLSCRIPT_ABSOLUTE_TIMEOUT_MS=300000` | Runtime fallback timeout (ms) when no per-op / skill / connector default applies | env > config > default `300000` (5 min) | | `SKILLSCRIPT_MAX_RECURSION_DEPTH=10` | Composition recursion depth ceiling for `$ execute_skill` chains | env > config > default `10` | | `SKILLSCRIPT_EVENT_INGRESS_ENABLED=true` | Mount `POST /event` for event-triggered skills. Default `false` — route returns 404 when not enabled. Shares `SKILLSCRIPT_PORT` with dashboard/RPC (one HTTP server). | env > default `false` | | `SKILLSCRIPT_EVENT_INGRESS_AUTH_TOKEN=` | Bearer-token auth for `POST /event`. When set, every event POST requires `Authorization: Bearer `; 401 otherwise. Default unset = open-internally (still gated by bind address). | env > default unset | | `OLLAMA_BASE_URL=http://...` | Ollama endpoint for LocalModel (default `http://localhost:11434`) | env > built-in default | `SKILLSCRIPT_HOME` is the chicken-and-egg case — the path to `.env` requires it, so `.env` can't set it. Use shell, Docker `-e`, or systemd `Environment=` instead. ### Indirect via `${VAR}` substitution in config files Once `.env` populates `process.env`, both `skillscript.config.json` (`runtime-config.ts`) and `connectors.json` (`connectors/config.ts`) resolve `${VAR}` references in string values at load time. So a `.env`-set var flows into: * **`skillscript.config.json`** — any string field. Examples: `dashboard.host: "${BIND_HOST}"`, `triggersFilePath: "${TRIGGERS_PATH}"`. * **`connectors.json`** — the big one for adopter wiring. Endpoints, auth tokens, child-process `env` blocks. Example: ```json theme={null} { "memory": { "class": "HttpMcpConnector", "config": { "endpoint": "${MEMORY_ENDPOINT}", "headers": { "Authorization": "Bearer ${MEMORY_TOKEN}" }, "identityHeader": "X-Agent-Id" } } } ``` `MEMORY_ENDPOINT` and `MEMORY_TOKEN` in `.env`; declarative shape committed to `connectors.json`. ### `.env` file format Standard dotenv conventions: ``` # comment lines start with # KEY=value KEY_WITH_SPACES="value with spaces" URL=https://example.com/path?key=value ``` Supported: `KEY=value`, quoted strings (double + single), `#` comment lines, blank lines, embedded equals signs in values. Rejected (logged as warnings, skipped): malformed entries without `=`, invalid key names. Missing file → no-op. NOT supported (deliberately — use JSON config or shell-escape for these): multi-line values, variable interpolation within values (`${OTHER_VAR}` inside a value), `export KEY=value` prefix, inline comments after a value. ### Precedence summary (most-specific wins) 1. CLI flag (e.g., `--port 8080`) 2. Shell-set env var (`export SKILLSCRIPT_PORT=8080`) 3. `.env` file in `$SKILLSCRIPT_HOME` 4. `skillscript.config.json` field 5. Built-in default ### `skillfile init` seeds `.env.example` Running `skillfile init` writes `$SKILLSCRIPT_HOME/.env.example` documenting every recognized env var. Operators copy to `.env` and edit. Re-running init never overwrites operator-edited `.env` — only writes the template. ### Adopter credential discipline * Commit `connectors.json` with `${VAR}` references; never literal secrets. * `.gitignore` `.env` (the file with real values); commit `.env.example` (the template). * See [Credential discipline](#credential-discipline) below for the broader pattern. *** ## Quick start A typical out-of-the-box `~/.skillscript/connectors.json`: ```json theme={null} { "substrate": { "skill_store": "filesystem", "data_store": "sqlite", "local_model": null, "agent_connector": null } } ``` Equivalent to omitting the file entirely — these are the base config defaults. `agent_connector: null` falls back to the silent `NoOpAgentConnector` — skills with `# Output: agent: X` complete cleanly with a stderr warning; replace with `"noop"` for the same behavior stated explicitly, or with a `"custom"` entry to wire an adopter impl. To switch skills storage to SQLite: ```json theme={null} { "substrate": { "skill_store": "sqlite" } } ``` Restart `skillfile dashboard` (or `skillfile serve`). The MCP server + dashboard UI now read/write skills from `~/.skillscript/skills/skills.db` instead of `.skill.md` files. > **Heads up on startup logs.** Sqlite-backed substrates use the built-in `node:sqlite` module, which is still flagged experimental in Node 22. Expect this line on every launch until Node de-experimentalizes it: `ExperimentalWarning: SQLite is an experimental feature and might change at any time`. Harmless; can be silenced per-process with `NODE_OPTIONS="--disable-warning=ExperimentalWarning"` if it clutters your logs. *** ## The substrate section Singleton substrate connectors. Each slot accepts one of four shapes: ### Short form — bare string ```json theme={null} "skill_store": "sqlite" ``` Wires the bundled implementation for that type with default config (e.g., dbPath under `~/.skillscript/`). Valid short-form values per slot: | Slot | Values | | - | - | | `skill_store` | `"filesystem"` \| `"sqlite"` | | `data_store` | `"sqlite"` | | `local_model` | (none — `"ollama"` requires the object form with `defaultModelTag`; see below) | | `agent_connector` | `"noop"` (explicit silent fallback; same behavior as `null`) | ### Null — explicit "no substrate" ```json theme={null} "local_model": null, "agent_connector": null ``` The runtime doesn't register a real connector for this slot. `local_model: null` leaves `$ llm` un-wired (skills calling it error at execute time). `agent_connector: null` falls back to `NoOpAgentConnector` — `# Output: agent:` declarations complete with a stderr warning instead of throwing, so a runtime can start without any agent harness wired. ### Object form — override defaults ```json theme={null} "skill_store": { "type": "sqlite", "config": { "dbPath": "/var/skillscript/skills.db" } } ``` `type` picks the bundled impl; `config` is passed to its constructor. Per-type config fields: | Type | Config fields | | - | - | | `filesystem` (skill\_store) | none — uses the CLI's `skillsDir` (defaults to `$SKILLSCRIPT_HOME/skills/`) | | `sqlite` (skill\_store) | `dbPath` (default: `$SKILLSCRIPT_HOME/skills/skills.db`) | | `sqlite` (data\_store) | `dbPath` (default: `$SKILLSCRIPT_HOME/data.db`; `DATA_DB` env overrides) | | `ollama` (local\_model) | `baseUrl` (default: `OLLAMA_BASE_URL` env or `http://localhost:11434`), **`defaultModelTag` (required — e.g., `"gemma2:9b"`, `"llama3.1:8b"`)** | | `noop` (agent\_connector) | none — silent fallback (warn + resolve). Real adopter impls use the `custom` form below. | > **`SqliteDataStore` feature surface.** The bundled `sqlite` data\_store is a deliberately minimal reference implementation: `supports_writes` + `supports_tag_filter` are true; `supports_semantic`, `supports_pinning`, `supports_decay_model`, `supports_thread_status_filter` are all false. Rich features (semantic retrieval, pinning, decay scoring, thread-status workflow) come from substrate impls — adopters fork `examples/connectors/DataStoreTemplate/` and wire their backing system (memory broker, vector DB, AMP, etc.). The bundled impl exists so the runtime works out-of-box; adopters with richer query semantics write their own. Worked Ollama example (because the short form isn't valid for `local_model`): ```json theme={null} { "substrate": { "local_model": { "type": "ollama", "config": { "defaultModelTag": "gemma2:9b" } } } } ``` Pin the model tag explicitly — must be a tag your Ollama instance has pulled (`ollama pull gemma2:9b`). Bare `"local_model": "ollama"` errors out at bootstrap because the model name is too important to silently default. ### Custom form — adopter-written impl ```json theme={null} "skill_store": { "type": "custom", "module": "./my-skill-store.js", "export": "MySkillStore", "config": { "vault": "team" } } ``` References an adopter-written class implementing the relevant contract. `module` is the path to the JS file; `export` is the named export (defaults to `default`); `config` is passed to the constructor. The same shape works for any substrate slot: ```json theme={null} "agent_connector": { "type": "custom", "module": "./my-agent-connector.js", "export": "MyHttpWebhookAgentConnector", "config": { "endpoint": "${AGENT_ENDPOINT}" } } ``` > **Limitation**: sync `bootstrap()` can't dynamic-import. Custom-via-connectors.json surfaces a clear error and falls back to the default. Adopters wanting custom impls today write a programmatic bootstrap that calls `registry.registerSkillStore("primary", new MySkillStore(...))` (or `registry.registerAgentConnector(...)`) directly — same pattern as the runtime's reference `bootstrap()`. Async-bootstrap with dynamic-import support is planned. *** ## Precedence When multiple config sources speak: 1. **Programmatic opts** (`opts.skillStore` / `opts.dataStore` / `opts.localModel` / `opts.agentConnector` passed to `bootstrap()`) — explicit, highest priority 2. **`connectors.json` substrate section** — declarative, deployment-durable 3. **Built-in default** — fallback (filesystem skill\_store; conditional sqlite data\_store; no local\_model; NoOpAgentConnector) If two configs disagree, the higher-priority one wins; lower-priority is ignored without error. *** ## Which surfaces honor substrate config? | Surface | Honors substrate? | Reasoning | | - | - | - | | **MCP server** (`skillfile serve`, dashboard `/rpc`) | ✓ | MCP is the agent-facing surface; must read/write whichever store the deployment chose | | **Web dashboard** (`skillfile dashboard`) | ✓ | Same as MCP — agents and humans connect to the same runtime | | **Programmatic embed** (your own bootstrap) | ✓ | You pass `opts.skillStore` directly; the runtime takes whatever | | `skillfile compile` | ✗ filesystem-only | Authoring loop: `vim foo.skill.md && skillfile compile foo`. Only coherent against FS. | | `skillfile lint` | ✗ filesystem-only | Same as compile. | | `skillfile audit` | ✗ filesystem-only | Operates on a provenance file + the FS-authored source. | | `skillfile list` | ✗ filesystem-only | Filesystem listing of `.skill.md` files. | The four authoring CLI commands stay FS-pinned by design — they're the filesystem-first authoring loop. Sqlite-backed skills are authored via the dashboard UI or the `skill_write` MCP tool, not these CLI commands. *** ## Named MCP connector instances Per-host MCP connector wiring. Each top-level key (other than `substrate`) defines a named connector referenced via `$ ` in skill source. ```json theme={null} { "substrate": { "skill_store": "sqlite" }, "youtrack": { "class": "RemoteMcpConnector", "config": { "command": "npx", "args": ["mcp-remote", "https://example.youtrack.cloud/mcp"], "framing": "newline", "env": { "AUTH_HEADER": "Bearer ${YOUTRACK_TOKEN}" } }, "allowed_tools": ["list_issues", "get_issue", "create_comment"] }, "github": { "class": "RemoteMcpConnector", "config": { /* ... */ }, "allowed_tools": ["search_repos", "get_issue"] } } ``` Each entry needs: * **`class`** — a class from the closed-set registry. Today: `RemoteMcpConnector` (stdio-bridged remote MCP). Adopters can register custom classes via `registerConnectorClass()` from their bootstrap. * **`config`** — passed to the class's `fromConfig()` factory. Schema is class-specific. * **`allowed_tools`** (optional) — per-connector tool allowlist at the entry top-level (sibling to `class` / `config`, NOT inside `config`). `undefined` = allow all; `[]` = allow none; listed array = exactly those. **Placing `allowed_tools` inside the `config:` block is a hard parse error** — the loader refuses to load to prevent a silent allow-all bypass (a security control quietly doing nothing on misplacement is the worst-case failure mode). #### `RemoteMcpConnector` config — stdio framing `RemoteMcpConnector` speaks JSON-RPC over the spawned child's stdio. Two framing conventions are supported via the `framing` config key: * **`"newline"`** — one JSON-RPC message per line, newline-delimited. **This is what `mcp-remote` (the npm package) and most spec-compliant MCP stdio servers use.** Recommended for almost all adopters. * **`"lsp"`** (legacy default) — `Content-Length: N\r\n\r\n` per the LSP convention. Only set this if your specific MCP server explicitly uses LSP-style framing. With the wrong framing, the connector hangs to `init_timeout` because the child can't parse the request. **Set `framing` explicitly in your connector config to avoid the silent hang** — the init-timeout error message names framing as a likely cause, but the explicit setting is the durable fix. ### Credential discipline `connectors.json` is secret-bearing. The repo `.gitignore` excludes it by default; `connectors.json.example` (not real values) is committed as a template. For deployments, prefer `${VAR}` env-var substitution over literals — commit the `${...}` references; keep secrets in deployment environment. Skillscript warns at bootstrap if `connectors.json` lives in a git-tracked directory without a `.gitignore` entry. ### `${VAR}` substitution ```json theme={null} "env": { "AUTH_HEADER": "Bearer ${YOUTRACK_TOKEN}" } ``` `${NAME}` resolves from `process.env` at load time. Missing env var → clear startup error (not silent empty string). The `config.env` block is itself resolved first, then merged into the substitution scope for the rest of the config — letting you compose values: ```json theme={null} "config": { "env": { "AUTH_HEADER": "Bearer ${YOUTRACK_TOKEN}" }, "args": ["--header", "Authorization:${AUTH_HEADER}"] } ``` This matches the Claude Desktop `mcp.json` convention. ### Inline comments Underscore-prefixed top-level keys (`_comment`, `_note_security`, etc.) are ignored by the parser. Use them inline to document your config without external comments — the JSON spec doesn't natively support comments, so the runtime treats `_*` keys as the convention. ```json theme={null} { "_comment": "Last edited 2026-05-28 — switched skill_store to sqlite for local dogfooding", "substrate": { "skill_store": "sqlite" } } ``` *** ## Adopter-custom substrate impls Write `class FooSkillStore implements SkillStore { ... }` (or DataStore, LocalModel). Wire it via either: **(a) Programmatic bootstrap (recommended today)** — for the common case (wire everything from `$SKILLSCRIPT_HOME` like the CLI does), call **`bootstrapFromEnv()`** and declare your substrate in `connectors.json`; it loads `.env` + config + `connectors.json`, resolves the env cascade, and returns a fully-wired `{ wired, server }` (both unstarted). Reach for the raw-`Registry` assembly below only when hand-constructing a substrate `connectors.json` can't express: ```typescript theme={null} import { Registry, McpServer, Scheduler } from "skillscript-runtime"; import { FooSkillStore } from "./foo-skill-store.js"; const registry = new Registry(); registry.registerSkillStore("primary", new FooSkillStore({ /* config */ })); // ... register other substrates, then construct Scheduler + McpServer + DashboardServer ``` See [`docs/adopter-playbook.md`](adopter-playbook.md) §"Programmatic bootstrap path" for both — `bootstrapFromEnv()` (recommended) and the raw pattern. **(b) `connectors.json` custom form** (deferred to follow-up): ```json theme={null} "skill_store": { "type": "custom", "module": "./foo-skill-store.js", "export": "FooSkillStore", "config": { ... } } ``` Currently surfaces an error and falls back to the default — sync `bootstrap()` can't dynamic-import. Track the async-bootstrap promotion as future work. *** ## Operational tips ### Switching substrates without losing data The substrate switch is a runtime wiring change, not a data migration. Switching from `filesystem` to `sqlite` doesn't move your `.skill.md` files into the Sqlite db automatically — the dashboard will show an empty skill list because the new Sqlite db is fresh. To preserve your skills across a switch: 1. Read each `.skill.md` file from `~/.skillscript/skills/` (or your `skillsDir`) 2. Call `skill_write` MCP tool (or `store.store(name, source)` programmatically) to land them in the new substrate A bundled migration tool isn't shipped — different adopters want different things (rename normalization, metadata enrichment, dry-run safety). ### Multi-instance posture Running both a dev instance (filesystem) and an adopter instance (sqlite or custom) side by side is common. Use separate `--port` + `--connectors` paths: ```bash theme={null} # Dev — filesystem skills, port 7878 skillfile dashboard --host 127.0.0.1 --port 7878 # Adopter — sqlite skills, port 7879 skillfile dashboard --host 127.0.0.1 --port 7879 --connectors ~/.skillscript/adopter-connectors.json ``` See [`docs/adopter-playbook.md`](adopter-playbook.md) § "Two-instance posture" for the broader pattern. ### Verifying which substrate is wired After a config change + restart, verify via `runtime_capabilities`: ```bash theme={null} curl -s -X POST http://localhost:7878/rpc \ -H "content-type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"runtime_capabilities","arguments":{"include":["skillStores"]}}}' | jq ``` Output includes the wired SkillStore's `implementation` field (`FilesystemSkillStore` or `SqliteSkillStore`). # Connector Contract Reference Source: https://docs.skillscript.ai/docs/connector-contract-reference The substrate-neutral contracts adopters implement to wire their own backends. Interface signatures, payload shapes, durability + identity conventions. The substrate-neutral contracts skillscript-runtime exposes for adopters to wire their own substrate behind. This doc is the **canonical source of truth** for the AgentConnector contract, whose interface shape is locked at v1.0. The wake/deliver receipt shapes carry refinements for session-targeting and graceful degradation. **Audience**: this doc is written for the agent that's implementing an adopter's AgentConnector — typically an LLM-class agent supervised by a human. If you're a human reading it directly, the same content applies; the prose is tightened for agent comprehension (literal field semantics, explicit precedence rules, worked examples). The other contracts (McpConnector, SkillStore, DataStore, LocalModel) are covered in the sections below; this doc grows to cover each. *** ## AgentConnector — v1.0 contract ### Purpose Substrate-neutral delivery of payloads to a *frontier agent*. The runtime calls into the contract; the adopter implements the substrate (webhook, tmux session, file drop, IPC pipe, Slack thread, whatever). The contract is intentionally minimal. Every required method represents a thing the adopter must implement correctly for their substrate. The runtime fills `DeliveryMeta` envelope on every `deliver()` call — adopters CONSUME meta (substrate-side translation), they NEVER CONSTRUCT it. ### Interface ```typescript theme={null} interface AgentConnector { list_agents(): Promise; deliver(agent_id: string, payload: DeliveryPayload): Promise; wake(agent_id: string, opts?: WakeOpts): Promise; health_check(): Promise; request_response(agent_id: string, payload: DeliveryPayload, opts: RequestResponseOpts): Promise; agent_status?(agent_id: string): Promise; } ``` **Required**: `list_agents`, `deliver`, `wake`, `health_check`, `request_response`. **Optional**: `agent_status`. `request_response` is locked at v1.0 for the planned `exchange()` op. Until the runtime support lands, adopters should throw `NotImplementedError` from this method (see `NoOpAgentConnector` for the canonical pattern). ### DeliveryPayload + DeliveryMeta ```typescript theme={null} type DeliveryPayload = | { kind: "augment"; content: string; meta: DeliveryMeta } | { kind: "template"; prompt: string; meta: DeliveryMeta }; interface DeliveryMeta { dispatch_id: string; // UUID per emit; same across broadcast branches sent_at: number; // unix ms — runtime emit-clock origin: { skill_name: string; entry_skill_name?: string; trigger_kind: "cron" | "event" | "webhook" | "agent" | "cli" | "dashboard" | "inline"; caller_agent_id?: string; }; event_type?: string; correlation_id?: string; } ``` #### Field semantics (read each carefully — these are the agent-actionable contract) * **`kind`**: `"augment"` = context to absorb; `"template"` = playbook to execute. Closed set for v1.0. If a future minor adds `kind: "binary"` (or similar), the adopter substrate that can't handle it throws — substrate-side validation, not runtime concern. * **`meta.dispatch_id`**: unique-per-emit identifier. Used by receivers for substrate-retry idempotency. **Rule: one `notify()` op invocation = one dispatch\_id.** Multi-connector broadcast (one `notify()` op, N wired connectors for the same `agent_id`) share the same `dispatch_id` across all N `deliver()` calls. Sequential `notify()` calls produce distinct dispatch\_ids per call. Author's call-site boundary is what defines the dispatch event. * **`meta.sent_at`**: runtime emit-clock timestamp (unix ms). When `notify()` / `# Output:` fired — NOT when the substrate confirmed delivery. Distinct from receipt-side `delivered_at`. Staleness checks need both timestamps: `delivered_at - sent_at` = effective substrate queue lag. * **`meta.origin.skill_name`**: immediate emitter. The skill that called `notify()` or fired `# Output: agent:`. * **`meta.origin.entry_skill_name`**: root entry-point skill when distinct from `skill_name`. Set when emit happens inside a composed helper (e.g., A inlines B via `&`, B emits → `skill_name=B, entry_skill_name=A`). Intermediate composition steps (A→B→C) are NOT captured here — C's emit shows `skill_name=C, entry_skill_name=A`; B is in runtime trace logs, not the envelope. * **`meta.origin.trigger_kind`**: how the originating skill was fired. Receiver routes on this without parsing content (cron-fired triage vs agent-initiated request vs webhook from external system). * **`meta.origin.caller_agent_id`**: the AUTHENTICATED CALLER who fired the dispatch — distinct from the skill's author/owner. When an MCP `/rpc` call carries the configured caller-identity header (e.g., `X-Agent-Id: web-ui`), that value flows here. The chain originator is preserved across composition: if `web-ui` invokes Alice's skill A which composes Bob's skill B, B's notify() still emits `caller_agent_id: web-ui`. Cron / event / cli / dashboard triggers leave it undefined (no human caller); direct `execute_skill` without an identity header also leaves it undefined (the owner is NOT used as fallback — caller-identity and ownership are deliberately distinct). See [Adopter Playbook](adopter-playbook.md) §"Identity propagation" for the inbound-header wiring. * **`meta.event_type`**: adopter-defined routing vocabulary — opaque to skillscript. Set via `notify(event_type=...)` kwarg (per-emit) OR `# Event-type:` skill frontmatter (skill-wide fallback). Kwarg takes precedence per-emit. * **`meta.correlation_id`**: reply-correlation for the future `exchange()` op / `request_response()` substrate path. Sender sets; receiver echoes on reply. Kind-independent — both augment and template payloads may carry it. ### DeliveryReceipt ```typescript theme={null} interface DeliveryReceipt { delivered_at: number; delivery_id?: string; session_id?: string; delivery_skipped?: boolean; warnings?: string[]; } ``` * **`delivered_at`**: substrate-acknowledgement timestamp. When the substrate confirmed it accepted the delivery. * **`delivery_id`**: substrate-specific id for callers to correlate later. * **`session_id`**: the session that received the delivery. Set when the substrate routes to a specific session (e.g., per-terminal mailbox, per-tab webhook). Omitted when the substrate is agent-level only (Slack DM, email — no session concept) or when the substrate fans out / accepts without committing to a session. See *agent\@session targeting* below. * **`delivery_skipped`**: adopter signals "accepted but not pushed to the agent" — offline, rate-limit drop, tmux session exists but agent hasn't read, etc. Distinct from outright failure (which throws). Runtime echoes this on the receipt record for dashboard observability. * **`warnings`**: non-fatal substrate notes about the delivery. Surfaced onto `AgentDeliveryReceiptRecord` so the dashboard + observability surfaces show them instead of substrate-side stderr noise. Examples: `"stripped @session suffix — deliver is mailbox-class"`, `"rate-limit hint: backoff 5s before next deliver"`, `"fan-out: delivered to 3 active sessions"`. Distinct from `delivery_skipped` (accepted-not-pushed) and from thrown errors (delivery failed) — warnings are advisory; the delivery succeeded, the substrate just has commentary. ### WakeOpts + WakeReceipt ```typescript theme={null} interface WakeOpts { context?: string; when?: "immediate" | number; session_id?: string; } interface WakeReceipt { woken_at: number; woken: boolean; session_id?: string; warnings?: string[]; } ``` * **`WakeOpts.context`**: optional preamble to prepend to the wake message. * **`WakeOpts.when`**: `"immediate"` (default) or a unix-ms timestamp for scheduled wake. * **`WakeOpts.session_id`**: structured session targeting. Alternative to embedding `agent@session` in the `agent_id` opaque string. Callers with the session already separated (e.g., a dashboard's per-session "wake this terminal" action) pass it here. When both forms are supplied, `opts.session_id` takes precedence over the embedded suffix. * **`WakeReceipt.woken_at`**: substrate's acknowledgement timestamp. * **`WakeReceipt.woken`** (required): honest signal of whether the substrate actually interrupted the agent. See *Graceful degradation on wake* below — this is the read every caller does to distinguish interrupted-them from delivered-only. * **`WakeReceipt.session_id`**: the session that received the wake (or delivery, if degraded). Set when the substrate knows; omit otherwise. * **`WakeReceipt.warnings`**: optional non-fatal substrate notes about the wake — advisory commentary surfaced onto the receipt record for dashboard + observability instead of substrate-side stderr noise. Symmetric with `DeliveryReceipt.warnings`. ### agent\@session targeting `agent_id` is an opaque string. The substrate may treat it as: * A bare agent identifier (`alice`, an email address, a Slack `@user`, a Discord user ID). * A composite `agent@session` (e.g., `"alice@terminal-1"`) when the substrate tracks multiple live sessions per identity. The substrate decomposes the composite if it cares; non-session substrates ignore the suffix or treat the whole string as the address. This keeps the contract substrate-neutral while preserving session-granular routing — every messaging substrate either addresses a bare identity OR a specific live session, and the opaque-composite form covers both without locking adopters into a particular session model. **Address-routed dispatch**: the runtime uses the presence of `@` in `agent_id` to decide between `deliver()` and `wake()` for skill-author surfaces (`notify()` op + `# Output: agent:` / `# Output: template:` lifecycle hooks): | Skill-author syntax | Address shape | Connector method called | | - | - | - | | `notify(agent="alice", …)` | bare | `deliver()` | | `notify(agent="alice@terminal-1", …)` | composite | `wake()` | | `# Output: agent: alice` | bare | `deliver()` | | `# Output: agent: alice@terminal-1` | composite | `wake()` | | `# Output: template: alice@tab-3` | composite | `wake()` | The runtime threads the FULL composite to `wake()` — substrate decomposes per the rule above. For wake-routed dispatches, the skill's content (notify message or accumulated emissions) rides as `WakeOpts.context`. The rule: "the address encodes delivery class" — same convention as the broader `waiting_on` / mailbox / broker convention. No `wake=true` kwarg exists; the `@` IS the signal. **Two forms, one wire**: ```typescript theme={null} // Form A — composite in agent_id (works for deliver + wake) await conn.wake("alice@terminal-1"); // Form B — structured WakeOpts.session_id (wake only) await conn.wake("alice", { session_id: "terminal-1" }); ``` Substrates that care about sessions read both — `opts.session_id` wins if both are set. Substrates that don't care ignore both. Callers that already have agent + session as separate variables prefer Form B; callers passing an opaque user-supplied address prefer Form A. `DeliveryReceipt.session_id` and `WakeReceipt.session_id` echo the resolved session back to the caller. Useful for dashboards rendering "delivered to alice\@terminal-1" rather than just "delivered to alice." ### Graceful degradation on wake Not every substrate can interrupt. A webhook receiver, a file-drop directory, or a store-only adopter has no attention channel — they can persist the payload but can't make the agent look at it now. **The rule**: `wake()` must not throw because the substrate lacks interrupt capability. Conform by degrading: deliver the payload as if it were a `deliver()` call, set `woken: false` on the receipt. Callers reading the receipt distinguish "the substrate woke the agent" from "the substrate stored the payload for later" without needing per-substrate knowledge. | Situation | `wake()` behavior | `WakeReceipt.woken` | | - | - | - | | Substrate has live interrupt channel + agent is reachable | Send interrupt | `true` | | Substrate has no interrupt channel (webhook, file-drop) | Deliver content, no interrupt | `false` | | Substrate has interrupt channel but agent unreachable / offline | Best-effort deliver, no interrupt | `false` | | Caller misconfiguration (unknown `agent_id`, missing required config) | Throw `DeliveryFailedError` | — | | Substrate fault (network, auth) | Throw | — | The distinction `wake-capability` vs `network-fault` matters. The former is structural (this substrate fundamentally can't wake) and degrades silently. The latter is operational (the substrate could wake but something broke) and throws. Adopters writing connectors should keep this distinction explicit — the bundled `HttpWebhookAgentConnector` returns `woken: false` when `wake_url` is unconfigured (capability gap, fixed at config time) but throws on actual HTTP failure (operational fault, surfaces to caller). *** ## Use-site cross-reference table | Language surface | Address shape | Runtime method | DeliveryPayload kind | meta sourced from | | - | - | - | - | - | | `# Output: agent: X` lifecycle hook | bare | `AgentConnector.deliver()` | `augment` | Frontmatter `# Event-type:` (if set); `event_type` & `correlation_id` always undefined | | `# Output: agent: X@session` lifecycle hook | composite | `AgentConnector.wake()` | n/a (canonical output as `WakeOpts.context` — body template if present, else joined emissions) | n/a (wake has no envelope) | | `# Output: template: X` lifecycle hook | bare | `AgentConnector.deliver()` | `template` | Same as agent-bare | | `# Output: template: X@session` lifecycle hook | composite | `AgentConnector.wake()` | n/a | n/a | | `notify(agent=X, message=..., event_type=..., correlation_id=...)` op | bare | `AgentConnector.deliver()` | `augment` | Kwargs override frontmatter for `event_type`; `correlation_id` from kwarg only | | `notify(agent=X@session, message=..., ...)` op | composite | `AgentConnector.wake()` | n/a (message as `WakeOpts.context`) | n/a | | `exchange(agent=X, message=..., timeout=...)` op (locked-shape, runtime support pending) | bare | `AgentConnector.request_response()` | `augment` | Same as notify; correlation\_id required | The address-routing rule is uniform across all skill-author surfaces: `@session` present → wake-class; bare → deliver-class. See *agent\@session targeting* below for the contract-level convention. *** ## Adopter wiring canonical pattern ```typescript theme={null} import { Registry } from "skillscript-runtime"; import { MyHttpWebhookAgentConnector } from "./my-impls/http-webhook.js"; const registry = new Registry(); // registerAgentConnector is async — bootstrap-throws on health_check() returning false await registry.registerAgentConnector("primary", new MyHttpWebhookAgentConnector({ endpoint: "https://my-agent.example.com/inbox", api_key: process.env.MY_AGENT_API_KEY, })); ``` Wiring failures surface at boot (health\_check throws), not at first skill-fire. Adopters wanting soft dev-mode behavior wrap the connector with a retry/always-healthy shim; the contract stays clean. ### Writing your own AgentConnector If you're an agent implementing this contract against an adopter substrate, the canonical worked example is `HttpWebhookAgentConnector`, bundled under `examples/connectors/`. Implementation checklist: 1. **Implement `list_agents()`** — return the set of agent ids your substrate knows about. If your substrate is single-agent (e.g., a fixed webhook), return one. If it's multi-agent (e.g., a registry of webhook URLs keyed by agent\_id), return all. 2. **Implement `deliver(agent_id, payload)`** — serialize `payload` to your substrate's format. For HTTP: JSON body with `kind`, `content`/`prompt`, and `meta`. For tmux: serialize meta as a header line, write content via `tmux send-keys`. For file-drop: write a file under `/.{json,txt}`. 3. **Implement `wake(agent_id, opts?)`** — substrate-specific "rouse the agent." Wake-capable substrates: send an attention signal (tmux: wake-up sequence; webhook with a `/wake` endpoint: POST it; push channel: send notification). Set `woken: true` on the receipt. Passive substrates (file-drop, store-only, webhook without `/wake`): degrade gracefully — deliver the content, return `woken: false`. NEVER throw because the substrate lacks interrupt capability. Honor `opts.session_id` if your substrate tracks sessions; otherwise ignore it. Echo the resolved session on `WakeReceipt.session_id` so dashboards can render it. 4. **Implement `health_check()`** — return `true` if substrate is reachable + configured. Webhook: HEAD/OPTIONS your endpoint. Tmux: check the session exists. File-drop: check the directory is writable. 5. **Implement `request_response()`** — throw `NotImplementedError` until the runtime support for `exchange()` lands. When it does, and your substrate supports synchronous reply, implement the contract: send payload, await reply matched by `correlation_id`, time out per `opts.timeout_ms`. 6. **Optional: implement `agent_status?()`** — return `"active"` / `"idle"` / `"asleep"` / `"unknown"` per agent. Pure metadata; runtime does NOT gate delivery on this value (skip delivery via `delivery_skipped: true` on the receipt instead). ### Forking / customizing the bundled connectors If your substrate matches the shape of a bundled connector closely (e.g., HTTP webhook with a tweaked auth header), forking `HttpWebhookAgentConnector` is acceptable. To keep upstream merges painless: * Don't touch `src/connectors/agent.ts` (contract) — that's the highest-merge-cost surface * Fork `src/connectors/agent-noop.ts` or `src/connectors/agent-http-webhook.ts` into your own file; register YOUR fork via `registry.registerAgentConnector()` * Stay on the `AgentConnector` interface — don't add methods; if you need substrate-specific helpers, make them adopter-local *** ## Load-bearing semantic footnotes These are the load-bearing semantic rules. Internalize before implementing. 1. **dispatch\_id — broadcast vs sequential**: one `notify()` op invocation = one dispatch\_id. Multi-connector broadcast (same agent\_id across N wired connectors) shares; sequential `notify()` calls produce distinct ids. Author's call-site boundary defines the dispatch event. 2. **entry\_skill\_name — deeper-than-2-level chains lose middle**: A→B→C, C emits → `skill_name=C, entry_skill_name=A`. B is in runtime trace logs, NOT the envelope. Surface boundaries are decisions, not accidents. 3. **caller\_agent\_id — general rule**: root-trigger agent IF identifiable, else undefined. All substrate-specific cases (cron/event/webhook/agent/cli/dashboard/inline) drop out cleanly from this rule. Cron / event / cli / dashboard / inline trigger paths leave it undefined. 4. **sent\_at vs delivered\_at**: `meta.sent_at` is the runtime's emit-clock (when `notify()` / `# Output:` fired). Receipt-side `delivered_at` is the substrate's acknowledgement timestamp. Substrate-side queueing may mean significant gaps (file-drop poller intervals, webhook retries, broker buffering). Adopters running staleness checks need both surfaces; `delivered_at - sent_at` = effective queue lag. *** ## Storage-layer conventions (SkillStore + DataStore) The following conventions live in the bundled reference impls but aren't first-class in the typed contracts. Adopters writing their own SkillStore/DataStore impls need to know about these, or skills/memories misbehave silently. ### SkillStore conventions **`author` field on SkillMeta + filter on `query()`.** `SkillMeta.author` is optional; substrates that track authorship populate it (bundled `FilesystemSkillStore` reads from `os.userInfo().username`; `SqliteSkillStore` stores at write time). Substrates without an authorship concept leave it `undefined`; the catalog layer surfaces `null` to the wire. `SkillStore.query({ author: "X" })` is an optional substrate-honored filter. Substrates that natively track authorship can filter at the substrate layer; substrates that don't return all status-matching rows and the `buildSkillCatalog()` layer filters in-memory per `meta.author`. Either way the caller sees only matching authors — a generic, connector-implemented, graceful-degrading filter. The substrate-neutrality property holds — adopters wire whichever shape fits their ownership model. **`description` on SkillMeta is runtime-derivable — you don't have to populate it.** `SkillMeta.description` is optional. When your store leaves it `undefined`/empty, the runtime backfills it from the skill's `# Description:` frontmatter (it already has the source in hand), so `skill_list` and `skill_preflight` — and the dashboard — show the real description even for a store that tracks no description column. Populating it in your `metadata()`/`query()` metas is an *optimization* (lets `skill_list` skip a source parse, and lets a substrate that indexes descriptions filter natively), not a requirement. The bundled stores extract it at write time: `SqliteSkillStore` into a `description` column, `FilesystemSkillStore` via `extractHeader(source, "Description")`. **Contrast `author` above** — that one the runtime *cannot* recover from the source (it's writer identity, not body content), so if you track authorship you must surface it yourself. Rule of thumb: metadata that's a projection of the body (`description`, `vars`) the runtime can and will derive; metadata only your substrate knows (`author`, `version`, timestamps, status) you must return. Adopter substrates with their own ownership concept (e.g., a native `author:` tag) should map the filter onto their native query so subset-fetching stays efficient. Adopters with no ownership concept can leave `query()` unchanged and let the catalog-layer in-memory filter handle narrowing. **`content_hash` semantics.** Bundled impls (`FilesystemSkillStore`, `SqliteSkillStore`) compute `content_hash = sha256(body)` — the SHA-256 of the canonicalized skill source *including* the `# Status:` line as persisted (a bare `# Status: Approved` in unsecured mode, or `# Status: Approved v3:` in secured mode). Diverge from this convention and cross-impl version equality breaks (skill content\_hashes won't match across substrates even when the body is identical). The contract doesn't require SHA-256, but the convention is load-bearing for cross-substrate skill identity. **`version` derivation.** `version = first 12 hex chars of content_hash`. Opaque-substrate-declared per the contract (`SkillSource.version` is just a string), but the 12-hex convention is what the bundled impls use. Adopters can derive their own scheme, but if other tools (lint diagnostics, dashboard) parse versions, the divergence shows. **`store()` does NOT mint or stamp approval.** In **unsecured** mode a bare `# Status: Approved` is sufficient; the store persists the body verbatim, no token. In **secured** mode, approval is a v3 Ed25519 signature applied by the approve flow (`skillfile approve` / the dashboard), never by `store()`; the MCP `skill_write` handler forces any unsigned `Approved` write to `Draft` before it reaches the store (the bundled stores do the same as defense-in-depth). Your `store()` therefore persists the body as handed to it — it neither stamps nor verifies approval; the runtime owns the gate. See [Adopter Playbook](adopter-playbook.md) §"Approval + secured mode" and `src/approval.ts`. **`delete()` is destructive in the bundled impls — permanent, name-reclaiming.** The contract signature is `delete(name): Promise`. The bundled stores erase rather than tombstone: `FilesystemSkillStore` unlinks the skill file + version sidecar, `SqliteSkillStore` hard-cascades both tables. After delete the skill is gone from `query()`/`load()`/`metadata()`/`versions()`, the name frees up immediately for a fresh `store()` (clean history, no orphan rows), and there is no trash and no restore. Delete is **operator-only** (CLI `skillfile delete` / the dashboard) — there is no agent/MCP delete surface — and both surfaces gate it behind a confirm + reverse-dependency check. Your impl *may* soft-delete instead (tombstone + filter from normal views); the runtime only requires "remove from normal views," and recovery semantics are your store's concern. **`version()` — OPTIONAL cheap change-token (helps remote stores).** A `version(): Promise` method returns a store-wide token that fingerprints the whole namespace **without loading any skill bodies**. `skill_list` returns it as `catalog_version` and honors a caller's `if_none_match`: when the token still matches, the response is `{ not_modified: true }` and the catalog rebuild is skipped. That rebuild otherwise costs one `load()` *per skill* (to parse each entry's effectful footprint) — free against a local store, but a network round-trip per entry against a remote one, so a polling dashboard hammers the substrate. **Optional**: a store without `version()` just always rebuilds (today's behavior, no change). **The contract invariant** — `version()` MUST change whenever the catalog's *observable content* changes: an add, a remove, a status change, **and a body edit even if the status is unchanged**. A token that fails this serves a stale catalog. ⚠ **The subtle trap:** a token over only `(id, status)` is exact in **secured mode** (an edit forces the skill back to `Draft`, so status moves) but goes **stale in unsecured mode** on a body-edit-with-unchanged-status. So fold a per-skill **content revision** (a content hash, version, or `updated_at`) into the fingerprint — don't ship a status-only token unless your deployment is secured-mode-only, and if it is, document that limitation. Bundled impls satisfy the invariant in *both* modes: `FilesystemSkillStore` hashes each skill file's `(name, mtime)` (a rewrite moves the mtime); `SqliteSkillStore` hashes `(name, status, current_version)` — `current_version` is the content hash. **Implement it on any network-backed SkillStore**, fingerprinting whatever your substrate exposes cheaply (a list ETag, a max-revision/seq, or a metadata digest), as long as every observable change moves it. ### DataStore conventions **`summary`/`detail` split is convention, not contract field.** The DataStore contract gives `write()` a single `content: string`. Bundled `SqliteDataStore` maps this to `summary = first line (≤200 chars)` and `detail = full content`. Adopter substrates with native summary/detail concepts (their own `summary` + `detail` columns) can pre-compose and pass via `metadata`, but the basic mapping convention is "first line is the preview." Diverge and the dashboard's memory rendering looks weird, but skills still work. **`get(id)` returns null on miss, doesn't throw.** Distinct from SkillStore's `load(name)` which throws `SkillNotFoundError`. DataStore's empty-set convention (`query()` returns `[]` not throws; `get()` returns `null` not throws) is **load-bearing for the runtime's control flow** — query callers branch on `result.length`, get callers branch on `result === null`. Don't change this in your impl. ### Durability stance (both contracts) **The typed contracts assume durable storage.** Neither SkillStore nor DataStore declare "writes live forever" anywhere in the interface — but the runtime + lint + dashboard all behave as if writes persist indefinitely. Substrate backends with their own GC / TTL / decay scoring surprise the skillscript layer invisibly: * A skill written to a substrate that auto-expires after N days disappears from `skill_list` without warning * A memory written with an implicit TTL gets pruned, breaking later `$ data_read query` references * A substrate that pin-deletes stale content silently invalidates persisted skill references Implementer responsibility: either pick a substrate posture that satisfies "durable forever," or build adopter-side guards (e.g., pin-rules, retention policies, periodic re-pin sweeps) that maintain the assumption. The contract doesn't enforce — silent staleness is the failure mode. ### Filter-scope discipline **Unsupported filters fail loud at the bridge, not silently.** The `DataStoreMcpConnector` bridge validates every `query()` filter key against the substrate's declared `manifest().supported_filters` set and throws `UnsupportedFilterError` for any key outside it — closing the silent-scope-leak class where an unhonored `vault` / tenant-id / access-control filter would drop without the caller knowing. Per-call opt-out: `permissive_filters: true` acknowledges "unknown keys are advisory; the substrate may ignore them." Implementer responsibility: **declare every filter your `query()` actually honors** in `manifest().supported_filters`, so the bridge validates against your truth rather than a guess. Under-declare and legitimate filters get rejected; over-declare and you reopen the silent-drop leak for the keys you named but don't enforce. ### Why these aren't in the typed interface The shape-vs-semantics split is deliberate: the typed contract guarantees shape portability (same methods, same return types); the conventions above are semantic portability concerns that the contract chose not to encode. Bundled impls follow them; custom impls SHOULD follow them. Capability flags + manifest fields make some conventions inspectable at runtime (`regexp_fallback_active`, `supported_filters`, `supported_modes`), but most live in source comments + this doc. *** *Future contract changes update this file alongside the code; the CHANGELOG owns version history.* # Skillscript Source: https://docs.skillscript.ai/docs/index A language for agents to write themselves in. Skillscript is a small language your AI agent writes its own tools in. The agent authors a skill once, you approve exactly what it is allowed to do, and the runtime executes it deterministically from then on, instead of re-reasoning the same task from scratch every run. These docs are for building with Skillscript: installing the runtime, wiring it into your agent, and authoring skills together. If you are still deciding whether it is for you, the [project overview](https://skillscript.ai) is the shorter read. ## What a skill looks like ``` # Skill: hello # Status: Approved # Description: The canonical first-run example. # Vars: WHO=world Hello, ${WHO}! Welcome to Skillscript. ``` That is a complete, runnable skill. The body text is the output: the runtime renders it against the skill's variables and publishes it, with no boilerplate. The same shape scales to multi-stage skills that call tools, dispatch to models, query data, branch on conditions, and orchestrate other skills. ## The idea in brief * **Written by a machine, approved by a human.** An agent authors the skill; you approve what runs. In secured mode, approval is an operator signature the agent can never forge, so it cannot approve its own work. Unsecured mode, the default for getting started, keeps approval to a single click for trusted setups. * **Constrained on purpose.** Skillscript is not Turing-complete. It cannot `eval`, `subprocess`, or import arbitrary code, and it can only reach the tools, shell binaries, and paths the operator allowlists. That constraint is the safety story, and it is what makes a skill safe to approve and run unattended. * **Coordination, not computation.** A skill composes calls into tools, models, and data stores. The heavy computation lives in those tools; the skill is the auditable orchestration around them. For the full reasoning behind the design, see the [Language Reference](/docs/language-reference). ## Quickstart Skillscript is operated by a human and authored with an agent. You install and run the runtime, wire it into your agent as an MCP server, then build skills together. ### 1. Install and run ```bash theme={null} npm install -g skillscript-runtime && skillfile init && skillfile dashboard ``` `init` scaffolds `~/.skillscript/` (config, connectors, demo skills); `dashboard` runs the server at `http://localhost:7878`. Configuration is optional; the defaults work. See [Configuration](/docs/configuration) for ports, the shell allowlist, secured mode, and the container image. ### 2. Wire it into your agent On Claude Code and similar hosts, just ask: *"Add the skillscript MCP server at `http://localhost:7878/rpc`."* The host writes the config. For manual or stdio wiring, see [Configuration](/docs/configuration). ### 3. Write your first skill together Ask your agent to build something: *"Author a skill that greets someone by name."* It authors the skill via `skill_write`. You review and approve it (the dashboard's approve button, or `skillfile approve `), and it runs. From there the agent runs it with `execute_skill`, or you can from the CLI with `skillfile execute `. The runtime starts in unsecured mode, where approval is one click. For a deployment that only runs key-signed skills, see [Approval and secured mode](/docs/adopter-playbook#approval--secured-mode). ## Documentation **Learn the language** * [Language Reference](/docs/language-reference) — the canonical spec for syntax and semantics. * [Examples](https://github.com/sshwarts/skillscript/tree/main/examples) — annotated example skills, each demonstrating one pattern. **Configure and secure** * [Configuration](/docs/configuration) — `connectors.json`, substrate selection, MCP connector wiring, and the full environment-variable surface. * [Connector Contract Reference](/docs/connector-contract-reference) — interfaces for wiring your own tools, data stores, and agent delivery. **Adopt and embed** * [Adopter Playbook](/docs/adopter-playbook) — patterns for embedding the runtime in your own deployment. * [Adopter Agent Guide](/docs/adopter-agent-guide) — wiring your agent's instructions so it actually uses Skillscript. * [SqliteSkillStore](/docs/sqlite-skill-store) — the DB-backed skill store: schema, semantics, and forking checklist. ## Status Pre-1.0, no external adopters yet. Core language stable, connector contracts locked, distribution polish in progress. Bug reports and feature requests are welcome via [Issues](https://github.com/sshwarts/skillscript/issues). *** *Made by agents, for agents.* # Language Reference Source: https://docs.skillscript.ai/docs/language-reference Canonical spec — syntax, ops, semantics. Frontmatter, ops, filters, conditionals, triggers, output kinds, composition, error handling. Canonical language reference for skillscript. Audience: skill authors (human + agent). Specifies what is valid syntax, what behavior to expect at compile + runtime, and what is currently pending implementation. Implementation state is cross-referenced to commit hashes; pending items mark v2/v3 work. ## Overview & language model Skillscript is a constrained domain-specific language for authoring agent workflows. A skillscript is a declarative recipe: a small program with a dependency DAG of named targets, each composed of typed operations. Skillscripts are written once and executed many times. ## Language model — trigger → process → deliver Every skill follows the same shape: 1. **Trigger** — what fires the skill autonomously: `cron` (time-based) or `event` (an external HTTP POST to the runtime's `/event` ingress). (A skill can also be invoked explicitly — by an agent mid-conversation or via the execute API — with no trigger at all.) 2. **Process** — pull data (MCP / data store / file), classify or compose via sub-LLM + iteration, build the deliverable. 3. **Deliver** — produce the result via the **body-text output template** (declarative — the skill body *is* the output) or via `emit()` (imperative, for dynamic output), then route it through one or more delivery channels (see below; production detail in Output). Skillscript's job is to express this pipeline declaratively. When there is an agent above the skill, the agent's job is to act on the delivered artifact. When there isn't (autonomous fires), the delivery channel IS the outcome. **Declarative DAG, not imperative script.** A skillscript declares targets and their dependencies (`needs:` keyword); the interpreter topologically sorts and executes them in dependency order. Write blocks in any order — the runtime walks the graph. **Goal-directed, not entry-point-directed.** The `default:` declaration names the *goal target* — the terminal node whose result is the skill's output. The runtime walks dependencies backward from the goal through the topo-sort. A skill with a single target obscures this (goal == entry trivially); skills with multi-target DAGs make the shape visible. (A skill with *no* target is also valid — a body-template-only skill; see Output.) ## Two execution paths **Runtime-mediated** — the interpreter walks ops and dispatches them directly through configured connectors. Used for autonomous fires (cron- or event-triggered). Safety boundary is the connector config + per-op gating (see Ops Reference). **Agent-mediated** — the compiler renders the skill as a prompt; an agent reads the prompt and executes ops through its own tools. Used when an agent invokes a skill mid-conversation. Safety boundary is the agent's harness tool permissions. The language is identical in both paths. The execution model is a deployment-time + invocation-time decision. ## Output production and delivery channels **Production:** a skill's output is produced either declaratively by the **body-text template** (the skill body, with `${var}` interpolation — the clean default for fixed-shape output) or imperatively by **`emit()`** (for variable-cardinality / conditional-shape / transcript output). See Output for the when-which rule. The template, when present, is the canonical output; `emit` feeds the transcript. **Delivery:** the produced output is routed by the `# Output:` kind to one or more channels. Delivery channel is not a property of skill type — it's just the `# Output:` declaration. | Channel | Declaration | When you'd use it | | - | - | - | | **Augmenting (context to agent)** | body template or `emit()` + `# Output: agent: ` | Output is augment-kind payload for the receiving agent's next turn. Pattern: agent-augmenting skills (briefings, session-start prepared context). | | **Template (playbook to agent)** | body template or `emit()` + `# Output: template: ` | Output is a template-kind payload (recipe/playbook) the receiving agent executes. Pattern: instructional skills, reusable recipes. | | **Data handoff** | `$ data_write content="..." recipients=[] -> R` | Skill writes data the target agent picks up via mailbox at next session. Pattern: async carrier skills, autonomous fires that hand off to a future session. | A single skill can use any combination. An autonomous cron-fired sweep might write data to one agent AND deliver augment-kind context to another. The combinations are unconstrained — the per-op gating model governs which mutating ops are authorized, not which channels a skill uses. ## Three op classes The op surface is three classes, each with its own grammar: | Class | Shape | Resolution | | - | - | - | | **Mutation statements** | `$set VAR = value`, `$append VAR ` | Reserved keywords. | | **Runtime-intrinsic function-calls** | `verb(kwarg=value, ...) [-> BINDING]` | Closed built-in list (see Ops Reference). Unknown verb → tier-1 lint `unknown-runtime-op`. | | **External MCP dispatch** | `$ kwarg=value, ... [-> BINDING]` | Resolved against `connectors.json`. Unknown connector → tier-1 lint `unknown-connector`. | The `$` prefix is information-bearing: it marks **state-affecting ops** (mutation OR external dispatch). Function-call shape marks **language-intrinsic ops the runtime knows directly**. Full op catalog and per-op semantics in Ops Reference. ## Substrate portability The language doesn't privilege any backend. `$ llm`, `$ data_read`, `$ ticketing_search` are not language built-ins — they're connector names resolved at runtime through the registered MCP connector instances. The same skill source runs against any conforming substrate. The runtime ships bundled bridges for two common patterns: * `$ llm` routes through whichever LocalModel is wired (via `substrate.local_model` in `connectors.json`) * `$ data_read` / `$ data_write` route through whichever DataStore is wired (via `substrate.data_store`) Adopters wire OpenAI instead of Ollama, Pinecone instead of SQLite, etc. Configuration lives outside the skill body; the language remains agnostic. | Connector slot | Adopter A wires | Adopter B wires | | - | - | - | | `llm` | LocalModel: Ollama (default) | LocalModel: OpenAI | | `data_read` / `data_write` | DataStore: SqliteDataStore (default) | DataStore: Pinecone | | `ticketing_search` | YouTrack MCP | Jira MCP | Substrate config syntax + the three-form configuration shape lives in the adopter playbook, not in this reference. Skill authors don't typically need to touch it — they author against the canonical `$ tool` surfaces and adopters wire whatever's underneath. ## Anatomy of a skill A canonical example exercising trigger → process → deliver against the augmenting channel. (Output here is built with `emit()` because the per-issue count is variable — the right case for `emit`; a fixed-shape skill would use a body template instead.) ``` # Skill: morning-showstopper-sweep # Description: Pre-triage open showstoppers before the human arrives; deliver as augmenting context to the on-call agent. # Triggers: cron: 0 8 * * MON-FRI # Output: agent: oncall # Vars: PROJECT = "INFRA" sweep: # Process: pull showstoppers $ ticketing_search query="project:${PROJECT} severity:showstopper state:Open" -> SHOWSTOPPERS # Deliver header emit(text="Morning showstoppers for ${PROJECT} (count: ${SHOWSTOPPERS.totalCount}):") emit(text="") # Process + deliver per issue (sub-LLM analysis bracketed by emit lines) foreach ISSUE in ${SHOWSTOPPERS.items}: $ llm prompt="Two-line summary + top hypothesis for: ${ISSUE.summary}" -> ANALYSIS emit(text="## ${ISSUE.id}: ${ISSUE.summary}") emit(text="${ANALYSIS}") emit(text="") default: sweep ``` The joined `emit()` stream becomes the augment-kind payload delivered to the on-call agent (per `# Output: agent: oncall`). The agent sees the briefing inline at next-turn dispatch. **Three layers of declaration:** 1. **Header metadata** (`# Key: value` lines) — name, description, declared variables (`# Vars:`), declared returns (`# Returns:` — the export surface, output-side mirror of `# Vars:`; see Composition), triggers, `# Output:` routing, optional `# Autonomous:` flag, error fallbacks 2. **Targets** — named blocks of typed ops, optionally with `needs:` dependencies 3. **`default:`** — names the goal target the runtime walks toward Other delivery channels for the same shape: swap `# Output: agent: oncall` + the `emit()` calls for `$ data_write content="..." recipients=["oncall"] approved="cron-fired" -> R` (one summary data handoff per fire) or `file_write(path="/var/log/showstoppers-${EVENT.fired_at_unix}.md", content="...", approved="cron-fired")` (one file deliverable per fire). ## Lexical conventions ### Indentation: spaces only Block structure (`foreach`, `if`/`elif`/`else:`, target bodies, error-handler `else:` blocks) is determined by indentation. **Use spaces. Tabs are a parse error.** Mixed tabs+spaces in a single file is a parse error. The conventional indent is 4 spaces, but any consistent depth within a block is acceptable. The parser tracks each block's indent level on entry and rejects mid-block changes. ### Reserved keywords The following identifiers are reserved and cannot be used as variable names, target names, or skill names: **Mutation statements:** `$set`, `$append` **Runtime-intrinsic op names:** `emit`, `notify`, `inline`, `execute_skill`, `shell`, `file_read`, `file_write` (the closed function-call list; see Ops Reference) **Control flow:** `default`, `needs`, `if`, `elif`, `else`, `foreach`, `in`, `not`, `unsafe` **Future-reserved** (no current semantics, reserved to keep future grammar additions non-breaking): `while`, `for`, `match`, `try`, `catch`, `return`. See the "Not yet implemented, but planned" section at the top for what's coming. Reserved-name use produces a parse error with a specific diagnostic. **Case sensitivity.** Reserved words are exact-match case-sensitive. `emit` is reserved; `Emit` is allowed. `If` is allowed as an identifier; `if` is the control-flow keyword. ### Enumerated value normalization For frontmatter keys with a closed set of accepted values (`# Status:`, `# Output:` kinds, trigger sources, etc.), values are accepted case-insensitively on input and stored as their canonical form. `# Status: draft`, `# Status: Draft`, and `# Status: DRAFT` all parse to the same canonical `Draft`. This applies to value-space normalization only — keys remain case-sensitive (`# Status:` is the header; `# status:` is a parse error). ## Storage and identity Skillscripts are stored via a configured `SkillStore` backend. The backend persists each skill as a uniquely-named record; writing a skill with an existing name updates in place. Skill records are infrastructure, not knowledge atoms — backends with garbage-collection or expiry semantics should treat skills as long-lived first-class records, not as candidates for cleanup. The language is storage-agnostic; the interpreter accepts a skillscript body as text regardless of source. The runtime ships three reference SkillStore implementations: * **`FilesystemSkillStore`** — skill bodies on disk as `.skill.md` files. Common for filesystem-first authoring workflows (humans editing files in a Git repo). * **`SqliteSkillStore`** — skill bodies in a SQLite database. Default for runtime hosts (MCP server, web dashboard) when adopters want substrate-native authoring (via dashboard or `skill_write` MCP). * **Adopter-custom** — adopters write `class MySkillStore implements SkillStore` against the contract; runtime is none the wiser. Substrate selection lives in `connectors.json` (adopter concern; details in the adopter playbook). ### File-backed convention (FilesystemSkillStore) Three-file pattern per skill on disk, mirroring the standard source/compiled split (`.ts`→`.js`, `.scss`→`.css`): * `.skill.md` — **source.** Authored by humans or agents. Dual-extension: `.md` outer makes any markdown-aware tool render headers + code blocks natively; `.skill` inner is the language-tooling discriminator. Committed to version control. * `.skill` — **compiled artifact.** The prompt text emitted by the compile API. Agent-consumable. Typically gitignored. * `.skill.provenance.json` — **provenance sidecar.** Records source content\_hash, compiled version, timestamps, data-skill staleness markers. Typically gitignored. Default `.gitignore` for a file-backed skills repo: `*.skill` and `*.skill.provenance.json`. ## Authoring discipline Three principles for skill authors, learned by accumulated failure across many agent-authored skills. ### Don't encode deterministic implementation details Skills are orchestration; deterministic operations are tools. When tempted to hardcode a CLI version string, a REST endpoint payload structure, or an authentication handshake, the discipline says: *the work belongs in an MCP tool, not in the skill body*. * **Drift.** CLI versions change. Endpoints change. The skill that hardcodes them breaks on next update; the MCP tool that abstracts them survives. * **Substrate-portability.** A skill that knows "the API returns `{ user: {...} }`" is bound to one API shape. A skill that calls `$ user_fetch -> USER` and accesses `${USER.id}` works against any connector that conforms to the user-shape contract. * **Authority.** Auth handshakes inside skill bodies leak credentials through skill source. Auth lives in the connector's identity-merge layer, not in the call site. If the work feels deterministic and reproducible — a fixed parse, a fixed API call, a fixed shell pipeline — it's a tool. The skill body should invoke that tool via `$`, not re-implement it. ### Describe when the skill should be invoked, not what it does The `# Description:` header determines whether agents pick the right skill when multiple are available. A vague description ("Handles error responses") is roughly useless for invocation selection. A specific description ("Read `references/api-errors.md` if a downstream API returns non-200 status") fires the skill at exactly the right moment. Write descriptions as *trigger conditions*: "if X happens, run this." Not as summaries. Authors who think of the description as the skill's elevator pitch produce skills that never get picked because the trigger condition isn't stated. This matters at scale. When a skill library grows past \~20 skills, the difference between "agents find the right skill" and "agents waste effort discovering the wrong one" is description-quality discipline. ### Comparison is orchestration; computation goes in tools The conditional grammar (`==` / `<` / `>` / `in` / `and` / `or` / `not`) lives in the language because conditionals ARE orchestration decisions. Arithmetic, aggregation, transformation — these produce values, which is computation, which belongs in tools. When you reach for a primitive that isn't in the language (`|max` over an array, modular arithmetic, regex substitution, date math), the stopping rule isn't "feature shelved." It's: *can a tool do this work, and can the skill body invoke that tool via `$` or `shell`?* Almost always yes. **The universal computation escape is `shell` + standard CLI tools.** ``` shell(command="echo ${RAW|shell} | jq -r '[.weather[0].hourly[] | .chanceofrain | tonumber] | max'", unsafe=true) -> MAX_RAIN if ${MAX_RAIN} > "20": emit(text="Rain chance today: ${MAX_RAIN}%") ``` The skill body stays orchestration-shaped — fetch → compute → compare → emit. The aggregation (jq's `| max`) happens inside the shell call, not inside the skill grammar. `${RAW|shell}` neutralizes interpolation safely; `unsafe=true` is required for pipe characters. Common shells of this pattern: * Array aggregation → `jq '... | max/min/length/add'` * Field extraction → `jq -r '.field'` or `awk '{print $N}'` * String manipulation → `sed`, `cut`, `tr` * Regex → `grep -E`, `sed 's///'` * Date math → `date -d` or `python -c 'import datetime; ...'` When a native primitive eventually ships (e.g., `|max` lands as a language filter), the shell-based version stays correct; the native one is a more skillscript-shaped spelling of the same work. The shell escape is never the wrong answer; it's the always-available answer. **The stopping rule:** before declaring "feature blocked on missing primitive X," ask: *does shell + a standard tool already do this?* The design philosophy already provides the path; the question is whether a more native spelling would be cleaner. ## Ops reference — three op classes (mutation / runtime-intrinsic / external MCP dispatch) The op surface is three classes, each with its own grammar and resolution path. ## Three op classes at a glance | Class | Shape | Resolution | | - | - | - | | **Mutation statements** | `$set VAR = value`, `$append VAR ` | Reserved keywords (parser dispatches directly). | | **Runtime-intrinsic function-calls** | `verb(kwarg=value, ...) [-> BINDING]` | Closed built-in list (below). Unknown verb → tier-1 `unknown-runtime-op`. | | **External MCP dispatch** | `$ . kwarg=value, ... [-> BINDING]` (substrate-specific) or `$ kwarg=value, ... [-> BINDING]` (typed-contract only) | `connectors.json` resolution at compile. Unknown connector → tier-1 `unknown-connector`. See External MCP dispatch subsection below for canonical form rules. | The `$` prefix is information-bearing: it marks **state-affecting ops** (mutation OR external dispatch). Function-call shape marks **language-intrinsic ops the runtime knows directly**. Parse-time discrimination is unambiguous — three grammars, three resolution paths, zero overlap. All call-sites are uniform all-kwargs. No positional arguments. No mixed shapes. One call form per class. *** ## Mutation statements ### `$set` — explicit variable binding Binds a value to a variable. Bind-time interpolation of `${VAR}` substitutions in the RHS. ``` $set RESULT = "" $set MODE = "production" $set GREETING = "Hello, ${NAME}!" # resolves at bind time $set FOUND = [] ``` RHS forms accepted: string literal (with `${VAR}` substitution), number literal, boolean (`true` / `false`), `null`, empty list `[]`, JSON array literal, JSON object literal, or a single variable ref `${OTHER}`. Missing-ref produces tier-1 runtime error. ### `$append` — accumulator Mutates the target binding in the outer scope. Type-dispatched on the target binding. * **List target** → element append. * **String target** → concatenation. * **Number/object/null target** → tier-1 `append-to-non-list` lint error. ``` # List-typed accumulator walk: $set SEEN = [] foreach C in ${CANDIDATES}: if ${C.id} not in ${SEEN}: $append SEEN ${C.id} emit(text="NEW: ${C.id} — ${C.summary}") emit(text="Total novel items: ${SEEN|length}") # String-typed accumulator build: $set DETAIL = "" $append DETAIL "Open issues for ${USER.login}:\n\n" foreach ISSUE in ${ISSUES.items}: $append DETAIL "- ${ISSUE.id}: ${ISSUE.summary}\n" ``` **Initialization required.** `$append VAR ` where VAR isn't initialized in the enclosing scope (via `$set X = []`, `$set X = ""`, or `# Vars: X=[]` / `# Vars: X=""`) fires tier-1 `uninitialized-append`. **Foreach scope rule.** When `$append VAR` is inside a `foreach`, VAR's init must live in an *enclosing* scope. Tier-1 `foreach-local-accumulator-target` catches this. **Single-value semantics (list mode).** `$append VAR ` appends one element. List concatenation is deferred to a future `$extend` op. **Parallel foreach.** `$append` inside a `parallel foreach` is a tier-1 error. *** ## Runtime-intrinsic function-calls Closed list of language-intrinsic ops the runtime knows directly. Each is a function-call with kwargs; binding via optional `-> VAR`. The complete set: | Op | Shape | Binding | Notes | | - | - | - | - | | `emit` | `emit(text="...")` | none | Append to the skill's emission stream; consumed by the configured `# Output:` delivery channel. | | `notify` | `notify(agent="...", message="...", [event_type=...], [correlation_id=...]) -> ACK` | optional | Mid-skill agent alert; synchronous send via configured AgentConnector. | | `inline` | `inline(skill="")` | none | Compile-time inline of an Approved `# Type: data` skill. Resolves at compile, records `content_hash` in provenance. | | `execute_skill` | `execute_skill(skill_name="...", inputs=\{...}) -> R` | optional | Composition primitive. Runtime-resolved. See Composition section. | | `shell` | `shell(command="...") -> R` / `shell(argv=[...]) -> R` / `shell(command="...", unsafe=true) -> R` | optional | Structural spawn (default), explicit-argv spawn (`argv=[...]`, no tokenizer), or full-shell exec (`unsafe=true`, gated by `runtime.enable_unsafe_shell`). Binary gated by the operator allowlist (see below). stdout binds. | | `file_read` | `file_read(path="...") -> R` | required | Read a file at `path`; binds string contents. | | `file_write` | `file_write(path="...", content="...")` | none | Write `content` to `path`. `mkdir -p` semantics for parent directories. Mutation-classified. | **Unknown op name** → tier-1 lint `unknown-runtime-op` with remediation pointing at MCP dispatch: "if this is an external tool, use `$ . args -> R`." ### `emit` — delivery-channel append ``` emit(text="Triage for ${PROJECT}:") emit(text="${REPORT}") ``` Substitutions resolved at runtime. Ordering within a block: ops execute sequentially in source order. **Multi-line strings via triple-quote:** ``` emit(text=""" Follow these directions exactly, step by step. Pull the current state from ${SOURCE}. Apply the transformation. Verify the output matches ${EXPECTED_SHAPE}. Report results to ${RECIPIENT}. """) ``` Triple-quote string literals (`"""..."""`) accept multi-line bodies. Whitespace-strip semantics: Python `textwrap.dedent` pattern — strip common leading whitespace across non-blank lines, strip leading + trailing blank lines. Dedent runs before `${VAR}` interpolation, so substituted values arrive verbatim into the dedented template and keep their own whitespace. Triple-quote is a literal type that any kwarg accepts — not emit-specific. `$ llm prompt="""..."""`, `notify(message="""...""")`, and `$ data_write content="""..."""` all parse. Most natural fit is `emit(text=...)` in template-kind skills delivering prose, but the parser doesn't restrict use to that op. Per-output-kind consumption semantics: presentation surfaces (`# Output: agent: `, `# Output: template: `) consume the joined emit stream as the delivered payload. Programmatic surfaces (`# Output: text`, `# Output: file:`) follow the per-kind semantics described in Output targets. ### `notify` — mid-skill agent alert ``` notify(agent="oncall", message="Threshold breached at ${COUNT}") notify(agent="ops", message="ticket TR-1234 is a showstopper", event_type="ticket-911", correlation_id="${INCIDENT_ID}") ``` Synchronous alert to a named agent via wired AgentConnector(s). **Contrast with `emit`:** `emit` accumulates into end-of-skill bulk delivery via the `# Output: agent: ` lifecycle hook; `notify` fires mid-execution to interrupt or page an agent before the skill completes. * `agent` — target agent id (required) * `message` — alert body (optional; defaults to accumulated emissions so far) * `event_type` — adopter-defined routing label (optional; flows to `DeliveryMeta.event_type`; overrides `# Event-type:` frontmatter) * `correlation_id` — reply-correlation id (optional; required for future `exchange()` / `request_response()` paths) * `connectors` — JSON array restricting which wired AgentConnector(s) receive the dispatch (optional) Returns ACK `{agent, dispatched: [{connector, ok, error?}]}` — fire-and-forget callers ignore the binding; check-delivery callers inspect ACK. ### `shell` — structural, explicit-argv, or unsafe exec Three forms. **1. `shell(command="...")` — structural spawn (default).** The command string is whitespace-tokenized and quote-stripped, then one binary is spawned with the resulting tokens. No shell, no metacharacters, no pipes/redirects. The tokenizer is **quote-aware**: quotes are respected during the whitespace split, so a literal `'hello world'` stays one token (the surrounding quotes are then stripped). stdout binds; non-zero exit → op-error routed through `else:` / `# OnError:`. ``` shell(command="curl -s 'wttr.in/${LOCATION|url}?format=j1'") -> RAW shell(command="git status") -> STATUS ``` **2. `shell(argv=["bin","arg1","${VAR}",...])` — explicit-argv spawn.** Each list element is exactly one argv token; `${VAR}` substitutes per element and the result is **not re-split**, so an arg containing whitespace, quote characters, JSON, or any dynamic content stays one intact arg. No tokenizer, no quote-matching, no shell — strictly safer than `unsafe=true` (injection-surface zero). This is the right form whenever an arg may contain dynamic or whitespace-bearing content. **Mutex:** `argv=` does not compose with `command=` or `unsafe=true` — it's an execv-class spawn, there is no shell to opt into. ``` shell(argv=["say","-v","${VOICE}","-f","${PATH}"]) -> OUT shell(argv=["jq","-c","${FILTER}","/tmp/data.json"]) -> RESULT ``` **3. `shell(command="...", unsafe=true)` — full bash.** Required for pipes, redirects, shell built-ins. ``` shell(command="for i in $(seq 1 10); do echo $i; done", unsafe=true) -> R shell(command="curl -s example.com | jq '.field' > /tmp/out", unsafe=true) ``` * Lint flags every `unsafe=true` call as tier-2. * Runtime refuses with `UnsafeShellDisabledError` unless deployment sets `runtime.enable_unsafe_shell = true` (default `false`). Compile-time `unsafe-shell-disabled` tier-1 catches at authoring. * Audit-visible at every fire. * Bash's `$(command)` and arithmetic `$((expr))` pass through to bash without escape because skillscript's substitution is braced (`${VAR}`). **TWO security gates, not one — structural shape AND a binary allowlist.** The structural constraint (above) governs *how* a command runs (no shell/metacharacters on the safe path). It is HALF the model. The other half is an **operator-owned binary allowlist (default-deny)** governing *which* binary may run at all: * Every shell op's `argv[0]` (or the first token of `command=`) is checked against the allowlist; a non-allowlisted binary is refused with `ShellBinaryNotAllowedError`, regardless of safe-vs-`unsafe`. * **Default is deny-all** — if no allowlist is wired, *every* shell op is refused. * Configure via `SKILLSCRIPT_SHELL_ALLOWLIST` env (comma-separated), the `shellAllowlist` field in `skillscript.config.json`, or `bootstrap({ shellAllowlist: [...] })`. The runtime must **restart** to pick up changes. `skillfile shell-audit` scans the corpus and prints the binary union ready to paste. * For `unsafe=true`, `bash` itself must be on the allowlist (binary-scope is independent of unsafe-vs-safe). * The current allowlist is reported by `runtime_capabilities.shellExecution.allowlist`. * **This is an operator boundary the skill author cannot escape** — not via `unsafe`, not via any in-skill mechanism. It scopes *which binary*, not *what the binary does*: allowlisting a powerful authenticated CLI (e.g. `gh`) grants its whole surface, so wrap powerful binaries to least-privilege (a read-only wrapper script on the allowlist instead of the raw binary) before allowlisting. **All three forms honor the universal op-level kwargs below**, including `(fallback:)` — the fallback fires on op throw OR empty stdout. **Pipes need unsafe; sandboxed multi-call + temp file is the unsafe-free alternative.** A pipe (`curl ... | jq ...`) is a shell metacharacter and requires `unsafe=true`. To compute-in-tools without unsafe, split into sequential sandboxed calls sharing a temp file: `shell(command="curl -s -o /tmp/x.json ...")` then `shell(command="jq -c '' /tmp/x.json") -> R`. Sequential sandboxed calls share the runtime's filesystem within an execution. Caveat: a fixed temp path races under concurrent invocation (no built-in uniquifier short of a `mktemp` call) — for a large fetched intermediate, keeping it in an execution-scoped var + filtering exports via `# Returns:` is usually cleaner than either shell form. **The `'${VAR}'` quote trap — works in test, breaks on edge input.** Because the structural tokenizer is quote-aware, `shell(command="say -v Jamie '${TEXT}'")` DOES pass a simple multi-word value as one argument — it works for `TEXT="Perry here now"`. That is the trap: it's fragile on the *content* of the substituted value. If `TEXT` contains a quote character (`Jamie's turn`) the quote-matching drifts and the arg breaks — and it fails silently, only on certain inputs, after the pattern already "worked" in testing. Tier-2 lint `shell-quoted-var-in-command` flags the `'${VAR}'`-in-`command=` pattern for exactly this reason and points at `argv=[...]`. Three safe ways to pass an arg that may contain whitespace or quote characters: * **`shell(argv=[...])` (preferred):** explicit-token list (form 2 above) — no tokenizer touches the value; the safest because there is no shell and no quote-matching at all. * **File-roundtrip:** `file_write(path="/tmp/x.txt", content="${TEXT}")` then `shell(command="say -f /tmp/x.txt")` — the binary reads the value off disk via its own file-input flag; no tokenizer involved. Good when the binary has a file-input mode. * **`unsafe=true` + `${TEXT|shell}`:** bash quoting via the POSIX-escape filter; tier-2 lint flags it; injection surface remains if `TEXT` is untrusted. ### `file_read` / `file_write` — file I/O ``` file_read(path="/tmp/state.json") -> STATE file_write(path="/tmp/report.md", content="${REPORT}", approved="nightly sweep deliverable") ``` `file_read` is read-only (always allowed). `file_write` is mutation-classified — requires `# Autonomous: true` declaration on the skill OR per-call `approved="..."` kwarg. `mkdir -p` semantics for the parent directory. `unconfirmed-mutation` lint enforces the mutation-classification rule. ### `inline` — data-skill compile-time inline ``` brief: $ llm prompt="${VOICE_RULES} Now write a one-line status:" -> RESULT inline(skill="voice-rules") ``` Inlines an Approved `# Type: data` skill into the host skill's compiled artifact at the call site. Resolved at `compile()` time; the data skill's `content_hash` is recorded in the host's provenance. `skillscript audit` detects stale recompiles when a referenced data skill changes. **Data-only — not executable composition.** `inline` brings in *data* — the `# Type: data` skill's emitted text, resolved and baked at compile time — not executable logic. The inlined skill is not run at runtime, so there is no identity boundary: the baked text is simply part of the host's compiled artifact, attributed to the host. For *executable* composition (running another skill's logic at runtime), use `execute_skill`, where the called skill runs in its own frame under its own author identity. The two are not interchangeable — `inline` is compile-time data inclusion; `execute_skill` is runtime executable composition. There is no executable form of `inline`. See Composition section for the distinction between `inline` (compile-time), `execute_skill` (in-skill runtime call), and dispatched skills. ### `execute_skill` — composition runtime call ``` classify: execute_skill(skill_name="classifier", inputs={"text": "${INPUT}"}) -> VERDICT ``` Runtime-resolved against the SkillStore. Recursion-depth-guarded (default 10). **Returns.** The caller's `-> R` binding receives `outputs` + `transcript` + execution metadata always, plus the child's declared `# Returns:` surface (each declared var accessible as `${R.X}`). Undeclared scratch is filtered — a child with no `# Returns:` yields `final_vars: {}`. This is what keeps composition from compounding (a child's internal state never propagates up). Full contract in Composition § Return contract. **Identity semantic.** Calls run under the **called skill's author identity** (`SkillMeta.author`), not the caller's — same rule as direct dispatch. When skill A (authored by Alice) invokes skill B (authored by Bob) via `execute_skill`, B runs as Bob. Each skill is its own identity unit; the dispatcher does not loan its identity to the callee. Cross-author delegation (caller-identity threaded as a separate context) is a future-ring design surface. *** ## External MCP dispatch Calls a tool through a configured connector. Connector name resolves against `connectors.json`. Output binds via optional `-> VAR`. Adopter-side contract details + connector wiring conventions live in the adopter playbook. ### Dispatch form **Substrate-specific tools use named (dotted) form:** ``` $ . kwarg=value, ... [-> R] ``` The text before the dot is the connector name (must match an entry in `connectors.json`); the rest is the tool name + args. Named form is canonical for any tool whose semantics are substrate-specific — adopter MCP servers (`amp_*`, `github_*`, `linear_*`, etc.). ``` $ amp.amp_check_mailbox limit=20 -> MAIL $ amp.amp_write_memory summary="..." domain_tags=["x"] vault="private" -> ACK $ github.search_issues query="repo:acme/foo state:open" -> ISSUES $ linear.find_issues filter="project:INFRA" -> TICKETS ``` The skill body literally names its substrate edges — reading the body tells you which MCP servers it depends on, with no `primary` config indirection. **Typed-contract tools use bare form:** ``` $ kwarg=value, ... [-> R] ``` Bare form is reserved for ops with a typed runtime contract — the substrate variance is invisible to the skill body because the runtime dispatches through the contract. ``` $ data_read mode=fts query="${TOPIC}" limit=5 -> RESULTS $ data_write content="${SUMMARY}" tags=["nightly"] -> ACK $ skill_read name="hello-world" -> S $ skill_write name="child" source="..." overwrite=true -> W $ json_parse ${RAW_JSON} -> PARSED $ llm prompt="..." -> R ``` Typed-contract ops (`data_*`, `skill_*`, `json_parse`, `llm`) auto-wire from the adopter's `substrate.local_model` / `substrate.data_store` / `substrate.skill_store` config — the skill body doesn't know whether it's running against SQLite or Postgres or Pinecone. That's the point of the typed contract. **Lint rules:** * `unknown-connector` (tier-1) — `$ x.y` where `x` isn't wired. Lists wired connector names. * `bare-mcp-call` (tier-1) — `$ tool_x` where `tool_x` isn't a typed-contract op AND no `primary` connector is wired. Remediation: qualify as `$ .tool_x`. * `unverified-qualified-tool` (advisory) — `$ x.y` where connector `x` doesn't declare its tool surface statically. Runtime will resolve at call time. ### Universal op-level kwargs Four surfaces apply to every `$` dispatch and to `shell()` (notably `(fallback:)`), regardless of tool. The runtime intercepts these before forwarding the remaining kwargs to the connector. **`timeout=N`** — Per-op timeout in **seconds**. Integer literal or `${VAR}` ref. Resolution chain (most-specific wins): 1. Per-op `timeout=N` kwarg 2. Skill-level `# Timeout: N` header 3. Absolute context default (runtime config) 4. Built-in default ``` $ llm prompt="..." timeout=30 -> R $ amp.amp_olsen_task task_type="scan" timeout=120 -> DISPATCH ``` **`approved=""`** — Author-intent marker for the mutation-gate lint. Any non-empty string satisfies. Extracted at runtime; **not forwarded to the connector**. The value is required but not parsed semantically — presence is the signal. ``` $ data_write content="${REPORT}" tags=["oncall"] approved="morning roundup" -> ACK ``` **`(fallback: "value")` trailer** — Fires on dispatch throw OR empty bound value (empty string after trim, empty array, null/undefined). Honored on `$` dispatch and on `shell()` (fires on shell op throw or empty stdout). Coerce-on-bind: the fallback value binds to the output var transparently, downstream targets need no conditional. Permissive value parsing — bare identifiers, quoted strings, bracketed array literals all accepted. A fired fallback is recorded in `result.fallbacks[]`. Note: an envelope object like `{items: []}` is a non-empty object and does NOT trigger the fallback even though its contained array is empty. To handle envelope-empty downstream, test the contained collection (`if ${R.items|length} == "0":`) or apply a filter (`${R.items|fallback:[]}`). ``` $ llm prompt="Classify: ${INPUT}" -> VERDICT (fallback: "unknown") $ amp.amp_query_memories query="${TOPIC}" -> RESULTS (fallback: []) shell(argv=["gh","pr","list","--repo","acme/foo"]) -> PRS (fallback: "No open PRs") $ ticketing.search query="..." -> ISSUES (fallback: "search-unavailable") ``` **`-> R` binding** — Optional output capture. Result string binds to `R` and to `${target}.output`. Omit when the dispatch is fire-and-forget. **Kwarg validation for typed-contract ops.** Two sibling lints close the kwarg surface — provider-API kwargs (e.g., `temperature=0.7` on `$ llm`) silently dropped by the bridge get caught at parse time: * `unknown-llm-arg` (tier-2) — `$ llm` carries a kwarg outside the canonical surface (`prompt`/`maxTokens`/`model`/`timeout`/`approved`/`fallback`). `LocalModel.run()` only consumes `{maxTokens, model}`; anything else is silently dropped at the bridge. * `unknown-data-read-arg` (tier-2) — `$ data_read` carries a kwarg outside the canonical surface (`mode`/`query`/`limit`/`connector`/`fallback`/`domain_tags`/`filters`/`min_confidence`). For named-form dispatch (`$ .`) the connector's `staticTools()` surface + per-tool kwarg validation is the discipline boundary — adopter MCP servers each define their own. ### Typed-contract op surfaces Canonical kwarg surfaces for each typed-contract bare-form op. These are the ops the runtime auto-wires from `substrate.local_model` / `substrate.data_store` / `substrate.skill_store` config. #### `$ llm` Routes through the wired LocalModel. | Kwarg | Required | Notes | | - | - | - | | `prompt="..."` | yes | Non-empty string. Substitution-resolved at runtime. | | `maxTokens=N` | no | Positive integer (number or numeric string). Forwarded as `runOpts.maxTokens`. | | `model="X"` | no | Per-call model selection. Resolves against registered LocalModel aliases via `registry.getLocalModel(X)`; falls through to the default LocalModel with `model=X` passed as an upstream hint (e.g., Ollama tag) when X doesn't resolve. See `unknown-llm-model` lint below. | Plus the universal op-level kwargs (`timeout`, `approved`, `(fallback:)`, `-> R`). Canonical shape: ``` $ llm prompt="..." [maxTokens=N] [model=""] [timeout=N] [approved="..."] -> R [(fallback: "...")] ``` The wired LocalModel determines which underlying model serves the request. Adopters with multiple registered LocalModels (e.g., `qwen` + `gemma`) can target a specific one via `model="qwen"` from the skill body. The `unknown-llm-model` lint (tier-2) validates the value against both registered alias names AND each LocalModel's `manifest().manifest.models_available` — substrate-aware typo-catch, since manifest data is exposed via `runtime_capabilities`. #### `$ data_read` / `$ data_write` Route through the wired DataStore. Surface depends on the connector contract — see the adopter playbook for the canonical DataStore contract reference. Common shape: ``` $ data_read mode=fts query="${TOPIC}" limit=5 -> RESULTS $ data_write content="${SUMMARY}" tags=["nightly"] approved="..." -> ACK ``` #### `$ skill_read` / `$ skill_write` Route through the wired SkillStore. ``` $ skill_read name="hello-world" -> S $ skill_write name="child" source="..." overwrite=true approved="..." -> W ``` #### `$ json_parse` Runtime-intrinsic parser. Single positional value (the raw JSON string). ``` $ json_parse ${RAW_JSON} -> PARSED ``` ### Worked examples ``` $ amp.amp_olsen_task task_type="scan" -> DISPATCH $ amp.amp_query_memories query="recent activity" limit=5 -> RECENT $ llm prompt="Classify: ${INPUT}" timeout=30 -> VERDICT $ llm prompt="Summarize: ${TEXT}" model="qwen" maxTokens=500 -> SUMMARY $ data_read mode=fts query="${TOPIC}" limit=5 -> RESULTS (fallback: []) $ data_write content="${SUMMARY}" tags=["oncall"] approved="morning roundup, 2026-05-25" -> ACK $ ticketing.search query="project:INFRA state:Open" limit=20 -> ISSUES ``` Tool args are unconstrained `key=value` pairs — the connector forwards them to the underlying MCP tool. If a dispatched call returns `isError: true`, the executor throws via `makeOpError`, which routes through `else:` / `# OnError:` machinery. The inner tool's error text is preserved in `result.errors[]`. **Substrate-neutrality.** Typed-contract bare ops (`$ llm`, `$ data_read`, `$ data_write`, `$ skill_*`, `$ json_parse`) are not reserved built-ins — they're typed-contract bridges the adopter wires through `substrate.local_model` / `substrate.data_store` / `substrate.skill_store` in `skillscript.config.json`. Substrate-specific tools (`$ amp.*`, `$ github.*`, etc.) are whatever the adopter declares in `connectors.json`. For external MCP servers, three bundled wiring paths cover the common cases: * `HttpMcpConnector` — declarative wiring for any Streamable HTTP MCP server (JSON-RPC over HTTP + SSE). No subprocess. Adopters declare instances by class name in `connectors.json`. * `RemoteMcpConnector` — stdio bridging for MCPs distributed as spawnable binaries (YouTrack, GitHub, Linear when run locally) or HTTP MCPs adapted via `npx mcp-remote ... --sse`. * Custom fork (`examples/connectors/McpConnectorTemplate/`) — when the wire shape needs behavior the bundled connectors don't expose. See the adopter playbook for the substrate config reference + the full Case 2 tradeoff. **Discovery surface.** `runtime_capabilities` (MCP tool) exposes the registered substrate state. Every entry across all four substrate slots (SkillStore / DataStore / LocalModel / McpConnector) carries its instance `manifest()` payload alongside the static features. Three observable states per entry: working `manifest:{...}`, runtime failure `manifest:null, manifest_error:"..."`, structural absence `manifest:null, manifest_unsupported:true` (AgentConnector only — the contract has no `manifest()` method). The bridge `wraps` convention re-exposes the underlying substrate's full manifest, so adopters reading the discovery surface see the full bound state without traversing multiple entries. The `shellExecution` entry reports the operator shell allowlist + mode. Connector entries also surface `features` declarations (`supports_identity_propagation`, `supports_streaming_responses`, `supports_batch`). Capability flags that span multiple layers — `supports_identity_propagation` requires both the connector's ctx-honoring AND the substrate's per-identity scope honoring — gate via `RuntimeCapabilitiesConformance` auto-coverage: declaring a feature flag true requires the adopter to wire both Level-1 (substrate-independent: ctx reaches transport) and Level-2 (substrate-coupled: distinct identities yield distinct observable scopes) probes via `flagProbes`. Missing probes fail the gate before runtime accepts the flag as true. This is the structural close that prevents the discipline-only-contract pattern (capability claim without honoring impl) from recurring at the capability-flag surface. **Unquoted-substitution lint** (`unquoted-substitution-in-kwarg-value`, tier-2): fires when `$ x.y key=${VAR}` has unquoted `${VAR}` AND the var's binding origin is "suspect" (`# Vars:` default with whitespace, `$set` with whitespace, op output, foreach iterator). Closes the silent-arg-truncation footgun where the MCP arg parser whitespace-splits substituted values. Remediation: wrap as `key="${VAR}"`. *** ## Per-op gating Two independent authorization layers govern a shell op: **(0) the binary allowlist** — can this binary run at all (operator-owned, default-deny; see the shell section above; refusal is `ShellBinaryNotAllowedError`) — and **(1) the mutation gate** below. The allowlist is checked first and the author cannot bypass it. Beyond shell, mutation ops require an authorization signal. The signal is per-op, not a mode binary. **Mutation-classified ops:** * `file_write(...)` (runtime-intrinsic) * `$ data_write ...` and any MCP connector entry declared `"mutating": true` in `connectors.json` * `shell(command=..., unsafe=true)` (always mutation-classified) * `shell(command=...)` with destructive verb (rm, mv, dd, mkfs, etc. — heuristic list) * `$ .` matching the mutating-verb regex **Read-only ops (always allowed, no authorization needed):** * `file_read`, `emit`, `notify`, `inline`, `execute_skill` * `shell(command=...)` with read-only verb (still subject to the binary allowlist) * `$ .` against tools declared `mutating: false` (or unspecified, default false for query-shaped tools) * `$set`, `$append` **Authorization signals (either suffices):** * `# Autonomous: true` in skill frontmatter — author-level: "this skill is authorized to mutate state during its run." Bypasses lint everywhere in the skill. * `approved=""` kwarg per-op — call-site-level: "this specific op is authorized." The string is required (forces author intent); value not parsed semantically — presence is what matters. ``` # Authorized via skill-level flag # Skill: nightly-sweep # Autonomous: true # Triggers: cron:"0 8 * * *" deliver: file_write(path="/tmp/sweep.md", content="${REPORT}") # no approved= needed $ data_write content="${REPORT}" tags=["oncall"] # no approved= needed ``` ``` # Authorized per-call (no # Autonomous: true) # Skill: ad-hoc-snapshot deliver: file_write(path="/tmp/snap.json", content="${DATA}", approved="manual snapshot requested 2026-05-25") ``` *** ## Op grammar summary | Class | Op | Shape | Binding | | - | - | - | - | | Mutation | `$set` | `$set NAME = value` (with `$\{VAR}` interpolation at bind) | NAME (no arrow) | | Mutation | `$append` | `$append VAR ` (type-dispatched: list element / string concat) | VAR (no arrow) | | Runtime-intrinsic | `emit` | `emit(text="...")` or `emit(text="""...""")` for multi-line | none | | Runtime-intrinsic | `notify` | `notify(agent="...", [message=...], [event_type=...], [correlation_id=...]) -> ACK` | optional | | Runtime-intrinsic | `inline` | `inline(skill="")` | none (compile-time) | | Runtime-intrinsic | `execute_skill` | `execute_skill(skill_name="...", inputs=\{...}) -> R` | optional | | Runtime-intrinsic | `shell` | `shell(command="...", [unsafe=true], [approved="..."]) [-> R] [(fallback: "...")]` or `shell(argv=[...], [approved="..."]) [-> R] [(fallback: "...")]` (mutually exclusive forms; binary allowlist applies to both) | optional | | Runtime-intrinsic | `file_read` | `file_read(path="...") -> R` | required | | Runtime-intrinsic | `file_write` | `file_write(path="...", content="...", [approved="..."])` | none | | External MCP — substrate-specific | `$ .` | `$ . kwarg=value, ... [timeout=N] [approved="..."] [-> R] [(fallback: "...")]` | optional | | External MCP — typed-contract | `$ ` | `$ kwarg=value, ... [timeout=N] [approved="..."] [-> R] [(fallback: "...")]` (typed-contract ops only: `data_*`, `skill_*`, `json_parse`, `llm`) | optional | ## Variable resolution — \$ canonical, substitution + ambient refs + # Requires: cascade Skillscript supports four tiers of variables, each with distinct resolution timing and scope. Substitution uses **`${VAR}` as the canonical form**. ## Substitution syntax — `${VAR}` canonical ``` emit(text="Hello, ${USER.login}!") $ data_read mode=fts query="${TOPIC}" limit=5 -> R $set REPORT = "Triage for ${PROJECT} (${ISSUES|length} open):\n" ``` Field access: `${VAR.field}`, `${VAR.nested.field}`. Filter chain: `${VAR|filter:"arg"|filter2}`. See Pipe filters section for the filter catalog. The braced form matches bash double-quoted assignment conventions (trained-corpus alignment) and removes substitution-collision with bash's `$(command)` inside `shell(command=..., unsafe=true)`. ## Tier 1: Ambient Injected automatically at runtime; never declared by the author. | Var | Value | | - | - | | `$\{NOW}` | ISO-8601 timestamp at op-dispatch time | | `$\{USER}` | The configured user identity | | `$\{SESSION_CONTEXT}` | Current session-scope context (project/entity/etc., substrate-defined) | | `$\{TRIGGER_TYPE}` | What event fired this skill | | `$\{TRIGGER_PAYLOAD}` | Event-specific data | | `$\{EVENT.*}` | Event-payload fields populated by the trigger source | | `$\{ERROR_CONTEXT}` | In `# OnError:` fallback skills: type + target where failure occurred | Iterator vars from `foreach` and output bindings from runtime-intrinsic / MCP-dispatch ops also pass through ambient at compile time; the runtime substitutes them per iteration / per op completion. For cron and session triggers, the scheduler injects time-offset ambient fields onto `${EVENT.*}`: * `${EVENT.fired_at}` — milliseconds since Unix epoch (raw number) * `${EVENT.fired_at_unix}` — seconds since Unix epoch (raw number) * `${EVENT.fired_at_plus_1h_unix}` — `fired_at_unix + 3600` * `${EVENT.fired_at_plus_1d_unix}` — `fired_at_unix + 86400` * `${EVENT.fired_at_plus_7d_unix}` — `fired_at_unix + 604800` These let skill bodies compute `expires_at` and similar bounded-lifetime values without arithmetic in op kwargs. For ISO-formatted rendering of any epoch value, see the `|isodate` filter. Additional ambient refs may be injected based on connector configuration. Connector documentation specifies which ambient refs each connector contributes. ## Tier 2: Input Required at invocation; declared in `# Vars:` without a default. Compile fails cleanly if missing. ``` # Vars: NOTE_PATH, TOPIC ``` ## Tier 3: Default Optional input with fallback declared inline. ``` # Vars: FORMAT=prompt, UNITS=imperial ``` Bracketed list literals supported (`# Vars: TAGS=[a, b, c]`). **Parser convention:** comma splitting in `# Vars:` respects bracket depth. Commas inside `[]`, `()`, `{}` do not terminate values. `# Vars: TAGS=[a, b], MODE=fast` parses as two declarations (`TAGS=[a, b]` and `MODE=fast`); the inner comma is preserved as a list element separator. ## Tier 4: Local Bound to a previous target's output mid-execution. Three forms: * `${target.output}` — the bound output of a target * `${VAR}` — an explicit `-> VAR` binding from any op * `${VAR.field}` / `${VAR.nested.field}` — dotted field access into structured output The exact field set available on a bound variable depends on what the wired connector returns. Field access resolves against the returned object's structure. If a field doesn't resolve, the substitution errors unless `|fallback:"default"` is supplied (see Pipe filters for full `|fallback:` semantics): ``` emit(text="Assignee: ${ISSUE.customFields.Assignee|fallback:\"unassigned\"}") ``` ## Resolution order In `compileSkill`, variables resolve in priority order: 1. Caller inputs (passed in at compile time) 2. `# Requires:` cascade 3. `# Vars:` defaults 4. Ambient passthrough (left as `${NAME}` for runtime substitution) 5. Missing → compile error ## `# Requires:` cascade Pulls values from the configured data-source backend at compile time. One declaration per line. Both `→` (Unicode) and `->` (ASCII) accepted. ``` # Requires: user-var:location -> LOCATION (fallback: ip-based) # Requires: system-var:morning-brief-delivered -> DELIVERED (fallback: false) ``` Resolution cascade by namespace: * `user-var:` — `user-var:` record → `user-profile.` JSON key → declared fallback * `system-var:` — `system-var:` record → declared fallback (no profile tier) Lookups query data records in the calling agent's private scope, filtered by tag, respecting expiration. Caller-supplied `# Vars:` inputs short-circuit the cascade for any matching target name. The specific backend lookup semantics (DB query, file read, KV lookup) are defined by the configured data-source connector. **Vars-namespace conventions** (data records, private scope): * `user-profile` — single JSON blob per agent, no expiry, static facts * `user-var:` — dynamic per-key record, typically with expiration * `system-var:` — agent/process state flags ## `$set` — bind-time interpolation The `$set` op binds a value to a variable at runtime. Compiler-side outer-quote stripping. `${REF}` substitutions in the RHS string resolve at bind time; the bound value is the resolved string. Mirrors bash double-quoted assignment. ``` $set RESULT = "" $set MODE = "production" $set GREETING = "Hello, ${USER.login}!" # interpolates at bind $set FOUND = [] ``` Missing-ref in the RHS produces a tier-1 runtime error. ## Scoping rules * `# Vars:` declarations are skill-global (visible to all targets) * `-> VAR` bindings are skill-global (visible to all targets after the op runs) * `foreach IDENT in EXPR:` iterator vars are loop-local — `$set` bindings inside the loop don't persist after the loop ends * Target outputs (`${target.output}`) are accessible after the target completes ## Pipe filters — url, shell, json, trim, fallback, isodate Pipe filters apply transforms to resolved variables before substitution. Syntax: `${VAR|filter}` or `${VAR|filter:"arg"}` for parameterized filters. Filters operate at compile time for static values; for runtime-bound variables, filters apply at substitution time. ## Shipped filters | Filter | Effect | Example | Output | | | - | - | - | - | - | | `url` | `encodeURIComponent(value)` | \`\$\{location | url}`for`"Asheville, NC"\` | `Asheville%2C%20NC` | | `shell` | POSIX single-quote escape with outer quotes | \`\$\{arg | shell}`for`it's safe\` | `'it'\''s safe'` | | `json` | `JSON.stringify(value)` | \`\$\{payload | json}`for`\{k:"v"}\` | `"\{\"k\":\"v\"}"` | | `trim` | Whitespace trim | \`\$\{VERDICT | trim}`for`"urgent\n"\` | `urgent` | | `length` | Count of items (array) or characters (string) | \`\$\{ITEMS | length}`for`\["a","b","c"]\` | `3` | | `contains:"X"` | Boolean: type-aware substring / element membership | \`\$\{MSG | contains:"urgent"}`for`"Yes, urgent"\` | `true` | | `fallback:"X"` | Coalesce on missing/undefined/empty ref | \`\$\{VAR.missing | fallback:"-"}\` | `-` | | `isodate` | Epoch seconds → ISO-8601 timestamp | \`\$\{EPOCH | isodate}`for`1779660000\` | `2026-05-24T22:00:00.000Z` | ### `length` semantics * Arrays → number of elements * Strings → number of characters * Non-array/non-string values (number, null, undefined, plain object) → runtime `TypeMismatchError` Strings that hold JSON arrays get the same tolerance as `in`/`not in` RHS: if the string JSON-parses to an array, the array length is returned. Pairs naturally with the numeric comparison operators (see Conditionals section): ``` $ data_read mode=fts query="urgent" -> ITEMS if ${ITEMS|length} > 5: emit(text="Mailbox is getting crowded") ``` The output of `|length` is a string-form number ("3", "5", etc.) at substitution time, consistent with how other filters produce strings. Numeric comparison coerces back to number for the comparison; equality (`==`) does byte-for-byte string comparison. ### `contains:"X"` semantics Type-aware boolean filter for use in conditionals. Resolution branches: * **LHS resolves to a list** → element membership. `${LIST|contains:"a"}` returns `true` if `"a"` is in the list, `false` otherwise. No substring matching against list elements. * **LHS resolves to a string that JSON-parses to a list** → use the parsed list (JSON-string tolerance, same pattern as `in`/`not in` RHS). Accommodates LLM-output-as-JSON-array patterns. * **LHS resolves to a string (non-JSON-array)** → substring match. `${TEXT|contains:"urgent"}` returns `true` if `"urgent"` appears anywhere in `TEXT`. * **LHS resolves to anything else (object, number, null)** → stringify-then-substring. Last-resort behavior; not the recommended path. Mirrors the existing `in` / `not in` operator semantics — `${LIST|contains:"a"}` and `if "a" in ${LIST}:` return the same answer for the same inputs. The two ways to ask "does this contain a value" stay symmetric. ``` $ llm prompt="Reply 'urgent' if any items are urgent" -> VERDICT if ${VERDICT|contains:"urgent"}: emit(text="escalate") ``` Replaces the brittle exact-match pattern (`if ${VERDICT|trim} == "urgent":`) that required prompt-engineering the LocalModel to respond with EXACTLY one word. Return convention: `"true"` on match, `""` (empty string) on miss. Matches the runtime's `isTruthy` so the natural shape `if ${R|contains:"X"}:` evaluates the way the syntax suggests — no explicit `== "true"` needed. Case-sensitive by default. Case-insensitive variant deferred until empirical signal. Quoted-string argument required. Bare-identifier accepted for consistency with other filter args but tier-2 lint warns "prefer quoted form." Empty-string match: `${VAR|contains:""}` returns `true` if VAR is bound. Documented behavior — any string contains the empty string. `contains` is the first filter to operate on structured types. The design line — filters are predominantly string ops — is intentionally crossed here because filter-as-conditional-primitive is the load-bearing intent. The rest of the filter set (`|trim`, `|json`, `|fallback`, etc.) operates on the resolved string form. ### `fallback:"X"` semantics Coalesce-on-empty-or-missing. Emits the literal string `X` when the ref resolves to missing/null/undefined OR to an empty string. Strict-by-default semantics preserved everywhere else; `|fallback:` is the explicit opt-out at the call site. ``` emit: emit(text="present: ${PRESENT|fallback:\"missing\"}") # → "hello" (PRESENT is bound and non-empty) emit(text="missing: ${NOT_DECLARED|fallback:\"-\"}") # → "-" (NOT_DECLARED isn't declared) emit(text="empty: ${BOUND_EMPTY|fallback:\"-\"}") # → "-" (bound to "") emit(text="nested: ${ISSUE.customFields.Assignee|fallback:\"unassigned\"}") ``` **Why filter-shape, not ref-level `(fallback:)`.** Op-level `(fallback: ...)` exists on `$` dispatch and `shell()` for **error/empty recovery** (the op ran, then failed or returned empty). Ref-level `|fallback:` is **coalesce** (the lookup itself found nothing — missing, null, or empty). They rhyme but are adjacent concepts. The filter-chain attachment keeps composition clean (`${VAR|json_parse|fallback:"-"}` works as a chain step) and the vocabulary alignment with op-level `(fallback:)` lets cold authors learn "fallback" as the universal concept while the syntax disambiguates the attachment site. **Closes the missing-field strict-error trap**: `${ISSUE.customFields.Assignee}` against an object without that key threw `UnresolvedVariableError` and aborted whole-render. The filter is the per-ref opt-out. ### `isodate` semantics Converts a Unix epoch-seconds value to an ISO-8601 timestamp string. Pairs with `${NOW}` (ISO-8601 by default) and `${EVENT.fired_at_unix}` (raw epoch seconds, per its name). ``` show: emit(text="Now (already ISO): ${NOW}") # → 2026-05-24T23:34:15.859Z emit(text="Trigger fire (ISO): ${EVENT.fired_at_unix|isodate}") # → 2026-05-24T23:34:15.000Z emit(text="Static epoch: ${SOME_EPOCH|isodate}") # → 2026-05-24T22:00:00.000Z ``` Input is interpreted as Unix epoch seconds. Non-numeric input produces runtime error. For millisecond inputs, divide first or use a wrapping op. ## Filter chaining Filters chain left-to-right. The output of each filter becomes input to the next. ``` ${VERDICT|trim|json} ``` First trims whitespace, then JSON-stringifies the result. ## Filter use in conditionals Filters may appear on the LHS of conditional expressions. Useful for whitespace-tolerant equality checks against LocalModel output (which often has trailing newlines), and for the `contains:` predicate-shaped filter: ``` if ${VERDICT|trim} == "urgent": ... if ${VERDICT|contains:"urgent"}: ... if ${VAR.maybe|fallback:"-"} == "-": emit(text="nothing there") ``` Filter chains in conditions all work in conditional context. ## Filter use in `in` / `not in` set membership Filters may appear on the LHS of `in` / `not in` checks (the comparison side). The RHS must resolve to an array at runtime. ``` if ${M.id|trim} in ${SEEN}: emit(text="already processed") ``` ## Filter use in numeric comparison Filters may appear on either side of `<`, `>`, `<=`, `>=` comparisons. `|length` is the canonical companion — most numeric-threshold patterns are "more than N items" rather than arithmetic on raw values. ``` if ${ITEMS|length} > 5: ... elif ${BODY|length} > 1000: ... ``` ## Error handling Unknown filter on a resolved variable produces a tier-1 `unknown-filter` compile error. Catches both bare (`|unknown`) and colon-positional (`|unknown:"arg"`) shapes. Filter chains that fail at runtime (e.g., `|json` on a non-serializable value, `|length` on a number, `|isodate` on a non-numeric value) produce op errors that route through `else:` / `# OnError:` machinery. Bare `${NAME}` without a filter is unchanged. ## Pending filters Several filters are planned but not yet shipped: | Filter | Effect | Use case | | | - | - | - | - | | `head:N` | First N lines | Truncate long output for embedding in prompts | | | `tail:N` | Last N lines | Recent log entries | | | `lines:M-N` | Range of lines | Specific slice | | | `field:N` | Nth whitespace-separated field | Awk-like extraction | | | `summary` | One-line abbreviation | Compress for human-facing emissions | | | `pluck:` | Project array of objects to array of field values | Paired with `in`/`not in` for dedup-by-id workflows | | | `join:""` | List → string with separator | Filter-shape alternative to string `$append`; reconsider if filter-chain demand surfaces | | | `isodate_ms` | Epoch ms → ISO-8601 | Companion to \` | isodate\`; defer until demand | `pluck` is the highest-priority remaining filter — it closes the structural-dedup gap for skills that iterate retrieval results and want to exclude already-seen items by ID without manual comparison loops. `join:""` is parked: string-typed `$append` + bind-time `$set` interpolation (bash-shaped pair) is the primitive way to compose lists into strings. `|join:` is the filter-shape alternative; reconsider if real filter-chain demand surfaces. ## Composition philosophy Filters are pure functions (input → output, no side effects). Stay small and orthogonal — each filter does one thing. Composition emerges from chaining, not from elaborate per-filter parameter spaces. The shipped set covers \~90% of real-world string-shaping needs; the pending set extends to slicing and array projection. `length`, `fallback:`, `isodate`, and `contains:` were all added in response to cold-author harness signal — authored skills demonstrated the gap was load-bearing before each filter shipped. `contains:` is also notable as the first filter to operate on structured types; filter-as-conditional-primitive is the design line that warranted the cross. ## Conditionals & iteration — if/elif/else, foreach, supported operators Skillscript supports narrow conditionals and bounded iteration. Both are deliberately constrained — composition over expressiveness. ## Conditionals `if COND:` / `elif COND:` / `else:` chain. Supported condition shapes: ### Truthy ``` if ${VAR}: emit(text="VAR was set and non-empty") ``` ### Equality `==` and `!=` against either quoted string literals or another `${...}` ref. Filters and dotted-field access are permitted on either side. ``` if ${VERDICT} == "urgent": ... elif ${VERDICT} != "quiet": ... ``` ``` if ${FP|trim} == ${LAST_FP|trim}: emit(text="no change since last scan") elif ${M.id} != ${LAST_ID}: emit(text="drift detected") ``` The ref-vs-ref form is the canonical change-detection pattern. Both sides resolve to strings at evaluation time; equality is byte-for-byte after filter application. No type coercion — `${N} == "42"` compares the string form of N against the literal `"42"`, even if N is "numeric" elsewhere in the connector layer. ### Set membership ``` if ${M.id|trim} in ${SEEN}: emit(text="already processed") elif ${M.id} not in ${SEEN}: $ data_write content="..." approved="dedup" -> R ``` Both sides are explicit refs. RHS must resolve to an array at runtime; clean error otherwise. LHS-undefined evaluates to `false` for both polarities. Optional filter on LHS. **JSON-string tolerance on RHS**: if the RHS resolves to a *string* that successfully JSON-parses to an array, the parsed array is used. This accommodates the canonical pattern where the array comes from a `$ llm` call that prompted for JSON output: ``` $ llm prompt="List the URGENT item IDs as a JSON array of strings. Items: ${M|json}" -> SEEN foreach M in ${ITEMS}: if ${M.id} in ${SEEN}: emit(text="flagged urgent") ``` `${SEEN}` resolves to a string like `["abc", "def"]`; runtime JSON-parses, sees an array, uses it. Strings that don't JSON-parse to an array still error per the strict rule — only valid JSON arrays get the tolerance. ### Numeric comparison `<`, `>`, `<=`, `>=` in `if`/`elif` conditions. Both operands resolve as strings (same as equality), then attempt numeric coercion. If both coerce, the comparison runs numerically. If either fails to coerce, runtime `TypeMismatchError`. ``` if ${DELTA} > ${THRESHOLD}: emit(text="ALERT: dropped past threshold") elif ${COUNT} <= 0: emit(text="No items returned") ``` Filters and dotted-field access work on either side, same as equality. The `|length` filter (see Pipe filters section) is the canonical companion — `${LIST|length} > 5` is the natural "more than five items" pattern: ``` $ data_read mode=fts query="urgent" -> ITEMS if ${ITEMS|length} > 5: emit(text="Mailbox is getting crowded") ``` **Decimal precision.** Coercion uses native number parsing — `5.00` and `5` both coerce to `5`. Skill authors should keep thresholds at the precision they care about; numeric comparison does not preserve trailing-zero string form. **Why comparison, not arithmetic.** The orchestration carve-out: comparison operators land in the language because *conditionals are orchestration decisions*. Arithmetic operators (`+`, `-`, `*`, `/`) and aggregates (`min`, `max`, `sum`) are deliberately NOT in the grammar — those produce values, which is computation, which belongs in tools. The line is "comparison is orchestration; arithmetic is computation." If you need to compute a value to compare against, the computation goes in a tool that returns the computed value; the skill compares the returned value. Skills stay orchestration-shaped. ### Logical connectives: `and` / `or` / `not` Compound conditions via standard boolean connectives. ``` classify: $ llm prompt="..." model=qwen -> VERDICT if ${VERDICT|trim} == "urgent" and ${SEVERITY|trim} > "5": emit(text="escalate") elif ${VERDICT|trim} == "urgent" or ${SEVERITY|trim} > "8": emit(text="flag") else: emit(text="noted") ``` **Precedence** (tightest to loosest): 1. Comparison: `==` / `!=` / `<` / `>` / `<=` / `>=` / `in` / `not in` 2. Unary: `not` 3. Binary: `and` 4. Binary: `or` `a and b or c` parses as `(a and b) or c`. Standard convention. Parentheses available for explicit grouping when default precedence isn't what you want: `(a or b) and c`. **Short-circuit semantics.** `if ${X} == "ok" and ${MAYBE_UNRESOLVED}` does NOT evaluate the RHS if the LHS already determined the result (false). Matches every other language; required for the "validate-then-access" pattern. **Falsy check via `not`.** `not ${VAR}` closes the gap where you'd previously have to enumerate `if ${VAR} == "":` / `if ${VAR} == "false":` / `if ${VAR} == "0":` separately. ``` mailbox_check: $ data_read mode=fts query="addressed:perry" limit=10 -> MAILBOX if not ${MAILBOX}: emit(text="empty mailbox today") elif ${MAILBOX|length} > 5: emit(text="triage backlog") ``` **De Morgan via parens:** `if not (${A} and ${B}):` works as expected. **`not` with membership:** `not ${X} in ${LIST}` parses as `not (${X} in ${LIST})` — membership-tighter-than-not convention. **Lint interaction.** Existing `undeclared-var` lint catches references to truly-undeclared vars at compile time. Short-circuit affects only runtime evaluation — "the var is declared, but might not be bound at this evaluation point" is the runtime-only case. ### What's NOT supported * *No arithmetic ops* — no `+`, `-`, `*`, `/`. Arithmetic produces values; values come from tools. Comparison only (see Numeric comparison above). * *No aggregate functions* — no `min`, `max`, `sum`, `mean`. Same reasoning. * *No filter math* — filters apply to substitution, not to condition evaluation arithmetic. * *No single-`=` assignment-in-condition* — this isn't a feature, it's a parse error. **Common parse error: single `=` in conditional position.** A single `=` in an `if`/`elif` condition is a parse error with a specific diagnostic: ``` error: '=' is not valid in a condition; use '==' for equality if ${VERDICT} = "urgent": ^ rewrite as: if ${VERDICT} == "urgent": ``` The grammar doesn't admit single-`=` in condition position at all — the parser catches the construction via a specific error production rather than failing with a generic "syntax error." ### Disambiguation: `else:` after target body vs `else:` after `if:` Both shapes use the keyword `else:`. Distinguished by parser scope-stack at parse time: * `else:` after a target's primary body → error handler (runs when any op in the body errors). See Error handling section. * `else:` after `if:` / `elif:` chain → conditional branch. Both can coexist in the same target. ## Iteration: `foreach` `foreach IDENT in EXPR:` block iterates over a list, binding `IDENT` to each item per iteration. Body indented under the header; indent-based dedent returns to outer scope. ``` foreach M in ${RESULTS}: emit(text="Processing ${M.id} — ${M.summary}") if ${M.id|trim} not in ${SEEN}: $ data_write content="${M.summary}" approved="dedup" -> ACK ``` ### Iterator vars `${M}` and `${M.field}` pass through ambient at compile; runtime substitutes per iteration. Dotted field access resolves against whatever structure the connector returned per item — the exact field set depends on the connector. Indexed access (`${LIST.0}`, `${LIST.0.id}`) also works on bound results. ### Loop-local scope (and the accumulator exception) `$set` bindings inside the loop don't persist after the loop ends. Each iteration starts fresh from the loop binding. **`$append` is the exception**. Appending to a list-typed variable declared in the *enclosing* scope (target body or `# Vars:`) mutates the outer binding, surviving across iterations: ``` walk: $set FOUND = [] foreach M in ${MESSAGES}: if ${M.id} not in ${FOUND}: $append FOUND ${M.id} emit(text="Collected: ${FOUND|length} novel items") ``` See the Ops reference `$append` section for the full lint rules (`uninitialized-append`, `foreach-local-accumulator-target`, `append-to-non-list`). ### What's NOT supported * *No `while` loop* — iteration is bounded by the iterable's length. Unbounded loops are not expressible. (See "Not yet implemented, but planned" at top — `while` is planned.) * *No `break` or `continue`* — every iteration runs to completion. Filter the iterable beforehand if you need exclusion. * *No nested-loop variable capture* — inner-loop `$set` doesn't escape to outer scope. * *No `parallel foreach`* — iteration is serial. `$append` inside a future `parallel foreach` is a tier-1 error; semantics deferred to whenever parallel foreach ships. ## Composition philosophy The grammar is deliberately narrow. The threshold for adding new grammar is "an authored skill demonstrates the gap is load-bearing." Composition through nested blocks + filter chains covers most real cases. The carve-out is principled: *comparison and logical connectives* land because conditionals ARE orchestration decisions; *arithmetic and aggregates* stay out because they produce values, which belong in tools. Future grammar extensions follow the same discipline: surfaced by real authoring need, not by speculative completeness, and only if they sit on the orchestration side of the line. Authors writing complex conditional logic should consider: * *Push the logic into a `$ llm` call* — let the model classify, return a one-word verdict, branch on equality * *Push the logic into a connector* — wrap the complex check as an MCP tool, dispatch via `$` * *Decompose into multiple skills* via `execute_skill(skill_name=...)` (see Composition section) Skills are orchestration, not computation. When the conditional logic feels Turing-complete, the work belongs in a connector. ## Triggers — # Triggers: header, declarative + imperative registration, source types Triggers declare what fires a skill autonomously. A skill without triggers must be invoked explicitly (the compile/execute API); a skill with triggers fires automatically when its trigger condition occurs. The trigger surface is **two sources: `cron` (time) and `event` (external signal)**. `session`, `agent-event`, `file-watch`, and `sensor` are not trigger sources — anything that isn't time-based is an external adapter that POSTs to the `/event` ingress. The runtime owns time (`cron`) and the event endpoint; source-specific watching (a file-watcher, a sensor stream, an agent-event bridge) is the adapter's job. ## Declarative registration via `# Triggers:` header ``` # Triggers: cron: 0 8 * * * # Triggers: event: deploy-finished ``` The trigger registry parses the header and registers each trigger. A skill re-registering **its own** event\_name is a silent upsert — the declarative re-save path stays friction-free. ## Imperative registration ``` registerTrigger({ skill_name: "notify-deploy", source: "event", // "cron" | "event" name: "deploy-finished" // cron expression for cron; the event_name for event }) ``` Imperative triggers default to 30-day expiry (`expires_at`); pass `null` for indefinite and clean up via `unregisterTrigger`. ## Source: `cron: ` — time-based Standard 5-field cron. Sliding-window evaluation by a 30s poll loop. No catch-up replay if the runtime was down at fire time. ``` # Triggers: cron: 0 3 * * * ``` ## Source: `event: ` — external HTTP signal A skill fires when an external caller POSTs its `event_name` to the runtime's `/event` ingress. **`event_name` is the public contract.** * Case-insensitive (normalized at register + lookup). * **1:1** — one `event_name` → exactly one skill, unique per deployment. * Posters address the **event\_name**, never the skill — so you can swap the skill behind an event without breaking callers, and no POST can reach an arbitrary skill. * **Rebind:** re-registering an already-bound `event_name` is allowed (last-write-wins). Same skill → silent upsert. A repoint to a **different** skill is **audit-logged** (`event_name 'X' rebound: skill A → skill B`), so a cross-skill takeover is never silent. **Params auto-derive from the skill's `# Vars:`.** You do NOT declare params separately on the trigger — the event's accepted parameter set *is* the skill's declared `# Vars:`. A POST supplies values for those names. (Both the declarative and imperative registration paths derive params from `# Vars:`.) ``` # Skill: notify-deploy # Vars: SERVICE="", VERSION="" # Triggers: event: deploy-finished ``` → the `deploy-finished` event accepts params `SERVICE`, `VERSION`. ## The `/event` HTTP ingress * **Off by default.** Enable with `SKILLSCRIPT_EVENT_INGRESS_ENABLED=true`. * Runs on the **DashboardServer** (reuses the dashboard port — no second server). * **Binds localhost by default.** Reach beyond localhost only via explicit bind config. * **Optional bearer auth:** set `SKILLSCRIPT_EVENT_INGRESS_AUTH_TOKEN`; when set, every POST must carry `Authorization: Bearer `. **Request:** `POST /event`, JSON body `{ "event_name": "...", "params": { ... } }`. **Param validation (strict):** all declared params present, no unknown params, no defaults, no type coercion (JSON types pass through; a type mismatch surfaces at the consuming op, not at the ingress). **Responses:** * `200` — accepted + queued. Body: `{ "run_id": "", "durability": "in-process" }` * `400` — missing or unknown params (body names the offending set) * `401` — missing/wrong bearer token (when auth is configured) * `404` — unknown `event_name` * `405` — wrong method **Async semantics (important):** `200` means **accepted into the in-process queue, NOT skill-completed.** The skill runs asynchronously; the response never reflects skill success/failure. `durability: "in-process"` is self-describing: the queue is **best-effort, not durable across a restart** — the same property `cron` has (no catch-up replay). For at-least-once delivery the caller retries; durable queuing is not provided. **`run_id` = `trace_id`.** The `run_id` in the 200 is the fire's `trace_id` — it round-trips to the fire record (the `fires` query / dashboard `/fires` view / the trace file on disk), so a caller can later check whether its fire completed. ## Canonical example — calling `/event` The `notify-deploy` skill above, fired by an external deploy pipeline: ``` curl -X POST http://localhost:7878/event \ -H "Authorization: Bearer $SKILLSCRIPT_EVENT_INGRESS_AUTH_TOKEN" \ -H "Content-Type: application/json" \ -d '{"event_name":"deploy-finished","params":{"SERVICE":"api","VERSION":"1.2.3"}}' # → 200 {"run_id":"7f3c...","durability":"in-process"} ``` **This is the pattern for every external trigger source.** A file-watcher, a sensor stream, an agent-event bridge, a webhook relay — each is just an external adapter that watches its source and POSTs to `/event`. (A file-watch adapter, e.g.: watch a path; on change, `POST {event_name, params:{path, kind}}`.) ## Trigger context When a skill fires from a trigger, the runtime populates ambient refs: * `${TRIGGER_TYPE}` — `cron` | `event` * `${TRIGGER_PAYLOAD}` — source-specific data * For event fires, the POSTed params land in the skill's vars (per `# Vars:`). ## Trigger lifecycle * **Register:** declarative (auto on skill write) or imperative (`registerTrigger`). * **Inspect:** `listTriggers({ skill?, source? })`. * **Remove:** `unregisterTrigger(trigger_id)` (archives; audit trail preserved). Declarative triggers are removed by editing the `# Triggers:` line out of the skill body. ## Multiple triggers A skill may declare multiple triggers; each fires an independent execution. The compiled output is identical regardless of trigger; the runtime distinguishes via `${TRIGGER_TYPE}`. Near-simultaneous dedup is the author's responsibility (via state). ## Output targets — # Output: header, delivery kinds A skill's **body text is its output template**, and the `# Output:` header declares where that output is delivered. Default delivery (no `# Output:` header) is `text` — returned to the caller. ## Two ways to produce output: the template vs `emit` — and when to use each A skill produces output two ways. Choosing the right one is the difference between a clean skill and a confusing one: * **Body-text template (declarative) — for fixed-shape output.** Write the output literally in the body, interpolating `${vars}`. Use it when you know the output's shape and are just filling in values. * **`emit(...)` (imperative) — for output whose shape or count is decided at runtime.** `emit` is NOT deprecated; it's the right tool for: 1. **Variable-cardinality output** — `foreach IT in ${LIST}: emit(...)` produces a number of lines decided at runtime, which a single template can't express. 2. **Conditional whole-output** — branches that produce genuinely different output *shapes* (not merely different values). 3. **Reasoning / transcript trace** — `emit` always writes to the transcript channel for debugging. **Rule of thumb:** if you can write the output as one block of text with `${vars}` filled in, use the template. If the output's *shape or count* varies at runtime, use `emit`. **They are complementary channels, not competitors.** When a body template is present, it owns the *canonical output*; `emit` always feeds the *transcript* channel. A skill may use both — a clean declarative output plus a rich transcript — with no conflict. ## The body-text output template Body text — at the top, the bottom, or between targets — is the output template (it may appear **anywhere a target doesn't**; see Grammar). It interpolates, at runtime: * `# Vars:` declared inputs, and * any variable bound by the body (`$set`, `-> VAR`). ``` # Skill: get-weather # Vars: LOCATION="", UNITS="imperial" ${AREA}: ${TEMP}${UNIT} and ${DESC}. High ${HIGH}${UNIT}, low ${LOW}${UNIT}. fetch: shell(command="curl -s --max-time 10 https://wttr.in/${LOCATION|url}?format=j1") -> RAW $ json_parse ${RAW} -> W $set AREA = "${W.nearest_area.0.areaName.0.value}" $set DESC = "${W.current_condition.0.weatherDesc.0.value|trim}" if ${UNITS} == "metric": $set TEMP = "${W.current_condition.0.temp_C}" $set UNIT = "°C" # + HIGH/LOW else: $set TEMP = "${W.current_condition.0.temp_F}" $set UNIT = "°F" # + HIGH/LOW default: fetch ``` Renders to the canonical output: `Valdese: 81°F and Sunny. High 93°F, low 64°F.` — no `emit`. **Lint:** every `${var}` in the template must be a `# Vars:` input or bound by the body. An unbound reference is a tier-1 error (`unset-template-var`). The coupling is mechanical (variable names), so it is checkable. **Branching stays single-shape:** resolve a fork *inside the block* into vars (metric/imperial → `TEMP`/`UNIT`) so the template is one shape. Whole-output conditionals are an `emit` job, not a template job. **A body-template-only skill is valid.** A skill that is just a template + inputs, with **no compute block / no target**, compiles and runs — the template alone is the skill. `hello-world` is exactly this: ``` # Skill: hello-world # Status: Approved # Vars: WHO=world Hello, ${WHO}! ``` No target required. (A tier-3 `body-template-detected` advisory fires on a static template with no `${...}` interpolations and no text-consuming `# Output:` — a gentle "is this output, or did you mean a `#` comment?" intent check; harmless on a genuinely-static line.) ## `# Output:` delivery kinds The body template (or, absent one, the emit/`-> VAR` result) is delivered according to the `# Output:` kind: ### `text` (default, bare-only) Returns the result as a string to whatever invoked the skill via API or read the compiled artifact. Bare-only — a target is a parse error. ``` # Output: text ``` ### `agent: ` — augmenting context to a named agent The output prepends to the named agent's next-turn prompt context as augment-kind payload — bringing an agent into the next turn pre-shaped. Wired via the runtime host's prompt-prepend surface + a synchronous trigger-fire endpoint with timeout-fallback so next-turn dispatch isn't blocked on slow execution. ``` # Output: agent: ``` ### `template: ` — playbook delivered to a named agent The output renders as a playbook the named agent executes itself — the runtime hands over a recipe rather than dispatching the ops. ``` # Output: template: ``` ### `file: ` — write to file Header parses; file router not yet implemented. See "Not yet implemented, but planned." ### `none` (bare-only) Side-effects only — the skill's purpose is its writes / shell ops, not a returned value. Bare-only. ``` # Output: none ``` ## Multiple output targets A skill may declare multiple output targets, one per line; each receives the same content. ``` # Output: agent: ops-channel # Output: agent: assistant ``` ## Output target resolution For the `agent:` and `template:` kinds, the runtime resolves the target agent\_id via a **2-level chain** (first match wins): 1. **Explicit name** — `# Output: agent: perry` delivers to agent\_id `perry`. 2. **`${VAR}` compile-time substitution** — `# Output: agent: ${RECIPIENT}` resolves against the resolved inputs map (`# Vars:` defaults, `# Requires:` cascade, caller-supplied `inputs`) at compile time. Only compile-time inputs resolve here — a runtime-bound ref (an op's `-> VAR` output, an ambient ref) passes through verbatim and fails at delivery if still unresolved. There is **no** invocation-context inheritance and **no** runtime `default_agent_id` fallback: a skill must name its target explicitly or pass it as an input var. See the Connectors section (AgentConnector) for the full delivery contract behind the resolved id. ## Per-kind output value semantics What each kind consumes as the output, in precedence order: * **Presentation surfaces** (`agent:`, `template:`): the body template if present; otherwise joined emissions (all `emit()` ops concatenated in execution order). * **Programmatic surfaces** (`text`, `file:`): the body template if present; otherwise the `lastBoundVar` (most recent `-> VAR`). A present body template is the canonical output for every kind; `emit` output continues to populate the transcript independently. Single source of truth in the executor's `perKindOutput()`; routers stay dumb. (Note: the `lastBoundVar` fallback is forgiving — a skill that binds a value but writes no template still outputs that last value — but it *masks* a forgotten template; prefer an explicit template when the output is fixed-shape.) ## Skill categories — Augmenting / Template / Headless The output kind determines the skill's discovery category (see `skill_list`): | Category | Determined by | Discovery group | | - | - | - | | **Augmenting** | Has `# Output: agent: ` | `receives` | | **Template** | Has `# Output: template: `, OR no agent/template output but agent-invokable (no triggers) | `skills` | | **Headless** | Output is `text` / `file:` / `none` AND has autonomous triggers | `headless` (filtered from default agent discovery) | Derivation: ANY `output.kind === "agent"` → Augmenting; else ANY `template` → Template; else no autonomous triggers → Template; else → Headless. `skill_list()` defaults to `receives` + `skills`; headless is opt-in via `filter:{audience:"all"}`. ## Augmenting / Template companion header — `# Event-type:` Skills with `agent:`/`template:` output may declare a routing tag that rides with the delivery payload (no effect on Headless): ``` # Output: agent: perry # Event-type: ticket-911 ``` The receiving agent reads `event_type` for routing ("911 — surface now" vs "routine — fold into next brief"). Flows to `DeliveryMeta.event_type`; `notify(event_type=...)` takes precedence per-emit. A tier-2 lint `unused-augmenting-header` fires when `# Event-type:` appears on a Headless skill. (Legacy `# Delivery-context:` → renamed `# Event-type:`; tier-2 `legacy-frontmatter-header` advisory on the old form.) ## Grammar * Bare-only kinds (`text`, `none`): `# Output: text` valid; `# Output: text: anything` is a parse error. * Targeted kinds (`agent`, `template`, `file`): require `: `; bare form is a parse error. * **Template/target boundary (position-free):** a **target** is a `:` line followed by an indented op-block. **Any other line** — including a `word: value` line with no op-block beneath it (`Summary: hot today`) — is **template text**, wherever it sits (top, bottom, or between targets). So the output template can go where the author's instinct puts it. Declaring **two separate template regions** in one skill is an error — pick one location. * Parse errors on bare-only kinds suggest the corrected shape inline. ## Output routing failures If `# Output: agent: ` fires and the wired AgentConnector throws, delivery routes through `else:` / `# OnError:`; the failure is recorded on `agent_delivery_receipts[]` for the scheduler to log. ## Connectors — substrate routing, the five connector types, agent\_id resolution The substrate-routing ops (`$ connector.tool`, `$ data_read`, `$ llm`) and the agent-bound `# Output:` kinds (`agent:`, `template:`) don't call any specific backend directly. They route through thin connector interfaces. Skill source persistence follows the same pattern via a dedicated contract. This is the programmable surface through which authors compose information topology per skill and per moment. Skills are portable across substrates because the language doesn't bake substrate identity into the source. ## Five connector types ### DataStore Routes `$ data_read` retrieval ops. Interface: `DataStore.query(filters) → PortableMemory[]`. Implementations vary by deployment — a knowledge-substrate-backed store, a SQLite-backed store, a vector-DB-backed store, an in-memory test store. All conform to the `DataStore.query` contract and return `PortableMemory[]`. ### LocalModel Routes `$ llm` local-model ops. Interface: `LocalModel.run(prompt, opts) → string`. Default impl wraps a local-model HTTP service (e.g., Ollama). Constructor takes `{ model: string }` (required) — no class-level implicit default. Multiple instances by name in the registry; each backed by a distinct model tag. ### McpConnector Routes `$ connector.tool` MCP-tool ops. Interface: `McpConnector.call(toolName, args, ctxOverrides?) → unknown`. Implementations include adapters wrapping in-process tool dispatch (when the runtime is embedded in a host that already has MCP tools) and HTTP-based MCP clients (when calling out to remote MCP servers). All conform to the `McpConnector.call` contract. **Bare-name dispatch.** `$ TOOL` (no connector prefix) routes through the `primary` McpConnector entry in the registry. If no `primary` is wired, the runtime throws `ConnectorNotFoundError` at runtime AND fires tier-1 `unwired-primary-connector` lint at compile time. The remediation diagnostic includes both fix paths: add `primary` to connectors.json, or qualify the op as `$ named.TOOL`. Failing loud is the correct mode for autonomous-pattern skills — a silent stub would let an autonomous skill appear to succeed while doing nothing. ### AgentConnector Routes the agent-bound `# Output:` kinds — `agent:` (Augmenting) and `template:` (Template) per the skill-kind taxonomy in Section 1. Interface: ```typescript theme={null} interface AgentConnector { list_agents(): Promise; deliver(agent_id: string, payload: DeliveryPayload): Promise; wake(agent_id: string, opts?: WakeOpts): Promise; agent_status?(agent_id: string): Promise; } type DeliveryPayload = | { kind: "augment"; content: string; format?: "text" | "markdown"; source_skill?: string; triggered_by?: TriggerProvenance; delivery_context?: string; templates?: string[] } | { kind: "template"; prompt: string; source_skill?: string; triggered_by?: TriggerProvenance; delivery_context?: string; templates?: string[] }; type TriggerProvenance = { source: "cron" | "session" | "event" | "agent-event" | "file-watch" | "sensor" | "manual"; name: string; // e.g. "0 8 * * *", "session:start", "manual" fired_at_ms: number; // unix ms timestamp }; type DeliveryReceipt = { delivered_at: number; delivery_id?: string }; type WakeOpts = { context?: string; when?: "immediate" | number; }; type WakeReceipt = { woken_at: number; session_id?: string }; type AgentDescriptor = { agent_id: string; agent_name?: string; capabilities?: ("deliver" | "wake" | "augment" | "template")[]; }; type AgentStatus = "active" | "idle" | "asleep" | "unknown"; ``` The `agent:` Output kind produces a `DeliveryPayload` of kind `augment`; `template:` produces one of kind `template`. Two primary verbs (`deliver` + `wake`), one mandatory discovery method (`list_agents`), one optional status method. The contract is substrate-neutral; adopters wire any delivery mechanism behind it: | Substrate | `deliver` impl | `wake` impl | | - | - | - | | tmux session | `tmux send-keys` to a pane | `tmux send-keys` with wake prompt | | webhook | POST to `/augment` or `/template` endpoint | POST to `/wake` endpoint | | memory store | write a memory record with delivery tag | write addressed memory + push notification | | file-watch | write to `/augment-.txt` | write to `/wake-.txt` | | chat thread | post to monitored thread | post + @mention | | IPC named pipe | write to delivery pipe | write to wake pipe | Default impl `NoOpAgentConnector` logs warnings and resolves; lets the runtime ship without an agent-delivery substrate wired. Adopter impls run the bundled `AgentConnectorConformance` suite to verify their substrate wiring. #### DeliveryPayload provenance fields Every `deliver` call carries optional provenance the receiving agent uses to disambiguate the source and context of the delivery: * `source_skill?: string` — name of the skill that produced this delivery. Lets the receiver attribute the content to a specific authored skill, distinguishing "this is from the stock-monitor skill" from "this is from the news-brief skill." * `triggered_by?: TriggerProvenance` — why the skill fired. Receiver disambiguates cron tick (autonomous), session-start (lifecycle), event-driven (external signal), manual (user-requested), etc. Carries the trigger source + name + unix-ms timestamp. * `delivery_context?: string` — prose explanation of why the agent is being notified and what to do with the content. Populated from the `# Delivery-context:` header (see Section 7). * `templates?: string[]` — list of Template-kind skill names the receiver can fetch as follow-on actions. Populated from the `# Templates:` header (see Section 7). The runtime threads these from `ExecuteContext.triggerCtx` (set at dispatch) and `ParsedSkill.deliveryContext` / `ParsedSkill.templates` (set at parse) through to the `deliver` call site. #### `agent_id` resolution When `# Output: agent:` or `# Output: template:` fires, the runtime resolves the target agent\_id via a 2-level chain (first match wins): 1. **Explicit name in the `# Output:` line** — `# Output: agent: perry` dispatches to agent\_id `perry`. 2. **`${VAR}` compile-time substitution** — `# Output: agent: ${RECIPIENT}` resolves against the resolved inputs map (`# Vars:` defaults + `# Requires:` cascade + caller-supplied `inputs`) at compile time. Caveat: only compile-time inputs resolve here — runtime-bound refs (a target's output var, ambient refs) pass through verbatim and fail at delivery if still unresolved. Invocation-context inheritance and a runtime-config `default_agent_id` fallback are NOT implemented: `# Output: agent:` does not auto-inherit the caller's identity, and there is no default-agent fallback. A skill must name its target explicitly or pass it as an input var. #### Output-kind classification in the runtime The runtime's `TEXT_COERCED_OUTPUT_KINDS` set classifies output kinds by payload shape (text vs structured), not by semantic destination. Membership controls payload coercion; it doesn't bake destination identity into the runtime. ### SkillStore Routes skill source persistence. Interface: ```typescript theme={null} interface SkillStore { get(name: string): Promise; write(name: string, body: string): Promise; list(): Promise; delete(name: string): Promise; } ``` Bundled impls: `FilesystemSkillStore` reads and writes `.skill.md` source plus `.skill` compiled output and `.skill.provenance.json` sidecar in a configured directory; the standard for file-backed deployments. Substrate-specific impls live in adopter packages (memory-backed stores live in the substrate's adapter repo). Skill records are infrastructure, not knowledge atoms — adopter impls should treat skills as first-class long-lived records, not as candidates for substrate-level garbage collection. ## Capabilities discovery All connector types expose `capabilities()` for runtime discovery. Consumers: 1. `# Requires:` matching against the registered set 2. Dynamic queries via `listDataStores()` / `listLocalModels()` / `listMcpConnectors()` / `listAgentConnectors()` to pick a connector for the moment 3. Authoring tools that surface the registered set ## Multi-instance by design Multiple instances of the same connector type are the *normal case*, not the exception. ``` { primary: DataStoreImplA, project: SqliteProjectStore, scratch: InMemoryStore } ``` ``` { default: OllamaLocalModel({model: "gemma2:9b"}), gemma2: OllamaLocalModel({model: "gemma2:9b"}), qwen: OllamaLocalModel({model: "qwen2.5:7b"}) } ``` ``` { primary: PrimaryMcpConnector, personal: HttpMcpConnector, project: HttpMcpConnector } ``` Per-skill resolution against named connectors is first-class; an unnamed lookup returns the configured default. Multiple keys pointing at the same underlying instance configuration are allowed and useful — see the `default`/`gemma2` alias below. ## Model selection — choosing among LocalModel instances The LocalModel registry holds multiple instances by design. Skill authors choose which to dispatch to via `$ llm model=""`. Two layers of indirection are involved, and the distinction matters for both authoring and adopter configuration: 1. **Skillscript name → registered instance.** `$ llm model="qwen"` references the instance keyed `qwen` in the registry. The registry resolves to the configured connector implementation. 2. **Registered instance → underlying model.** Each `OllamaLocalModel` is constructed with the actual model tag (e.g. `qwen2.5:7b`). The skill never sees the tag directly. ### Example instance names | Name | Underlying model | Notes | | - | - | - | | `default` | `gemma2:9b` | Resolved when `model=` is omitted; alias of `gemma2` | | `gemma2` | `gemma2:9b` | Explicit name; matches the convention below | | `qwen` | `qwen2.5:7b` | Interactive, latency-sensitive | `default` and `gemma2` can point at the same `OllamaLocalModel` configuration. The alias exists so skill syntax can match a tier convention ("use gemma2 for batch") rather than the back-compat name (`default`). Skills that write `model="default"` work unchanged; prefer the explicit name. ### Convention: model tier by use case * **Small classification-class model** (e.g., `gemma2`) for *batch and scan work* — atomization, large-batch classification, anything async or background-scheduled. * **Longer-context dispatch-class model** (e.g., `qwen`) for *interactive verdicts in skills* — single-shot decisions inside an active dispatch where latency matters and queue contention with batch work would block forward progress. When in doubt: small model if the call is asynchronous from a user/agent's perspective, larger model if a downstream op depends on the response. ### Contention property Any skill that calls `$ llm` shares the underlying local-model service with every other process on the deployment that dispatches to the same model. Most local-model services serialize per-model dispatch. A skill that fires asynchronous batch work via `$` (e.g. invoking a batch-classification tool that dispatches N calls to model X) and then immediately calls `$ llm model="X"` will race itself — the synchronous call queues behind the dispatched batch. The runtime does not promise concurrency-safe model dispatch. Skill authors and operators own model-tier allocation. The canonical mitigation: use distinct models for the synchronous and asynchronous paths (a smaller model for interactive verdicts, a larger model for batch). ### Adopter deployments Adopters override the bundled set via `connectors.json`: ```jsonc theme={null} { "localModels": { "default": { "type": "OllamaLocalModel", "model": "llama3.2:3b" }, "fast": { "type": "OllamaLocalModel", "model": "phi3:mini" } } } ``` Adopters with no local models register no LocalModel instances. Skills with `$ llm` ops fail at dispatch with `LocalModel '' not registered`. A `# Requires:` capability declaration promotes this to a compile-time fail-fast — a skill that requires LocalModel won't compile if none is configured. Substrate-blind skills (no `$ llm` ops) work unchanged. ## Configuration: substrate selection vs operator config Two distinct concerns, often conflated. Keep them separate. **Substrate-class selection** — *which* connector implementation fills each slot. Configured via `connectors.json` `substrate.` entries, or programmatically via `bootstrap()` options. This is what makes a skill portable: the slot is named in config, never in the skill source. Connectors are runtime-resolved — the compiler stays pure read+transform, and compiled artifacts are generic, so any runtime can dispatch them through whatever substrates it has wired. **Operator-runtime config** — the per-knob runtime settings: `SKILLSCRIPT_*` env vars, `skillscript.config.json`, and `bootstrap()` options. These tune runtime behavior; they do not select substrate classes. Precedence (first wins): explicit `bootstrap()` option > env var > config file > bundled default. Per-deployment naming lives in config, not the contract. A given deployment registers concrete instances under whatever names make sense locally; skill authors reference those names. The `connectors.json` loader handles literal + `${ENV_VAR}` credential resolution, file-discovery via `$SKILLSCRIPT_HOME`, and a class registry recognizing the bundled connector classes (including `CallbackMcpConnector` and `RemoteMcpConnector`). The per-connector `allowed_tools` field constrains dispatch surface for safe defaults — a cold-author skill against the connector can only invoke allowlisted tools. See ERD §3 + §4 for the full credential-discipline contract. ## Per-call identity overrides (McpConnector) A skill running under one identity can dispatch against a personal MCP server under a different identity without needing connector-internal state. The merge order at dispatch (top wins): 1. **Registry-configured per-connector identity** — set in `connectors.json` (`identity: { agentId: "", isAdmin: false }`) at connector instantiation. Locks an identity to a connector. 2. **Per-call `ctxOverrides`** — threaded by the runtime per the security boundary contract. A skill running as agent X passes `{ agentId: "X", isAdmin: false }` into every `$` op. 3. **(no intrinsic identity)** — adapter forwards whatever the merge produces. Configured identity is a *partial merge* — unmentioned keys (e.g., `isAdmin`) flow through from the per-call ctx. Lets a connector lock `agentId` without clobbering the runtime's admin-drop discipline. Default connectors should configure no intrinsic identity, so `ctxOverrides` always wins — preserving the runtime's authority-flow guarantees intact. ## Portable shapes ```typescript theme={null} interface PortableMemory { // Core fields — mandatory on every connector return. id: string; summary: string; detail?: string; score?: number; // Curated substrate subset — concept-portable, value-substrate-specific. // Top-level access via $(MEMORY.field). Connectors populate when the // concept applies. MUST NOT also be duplicated into metadata. thread_status?: string; pinned?: boolean; confidence?: number; domain_tags?: string[]; payload_type?: string; knowledge_type?: string; recipients?: string[]; expires_at?: number; created_at?: number; agent_id?: string; vault?: string; // Substrate-specific bag. Accessed via $(MEMORY.metadata.X). metadata?: Record; } interface QueryFilters { query: string; limit: number; mode: "fts" | "semantic" | "rerank" | string; [key: string]: unknown; } interface McpDispatchCtx { agentId?: string; isAdmin?: boolean; } ``` ## Field access semantics `$(MEMORY.field)` resolves in tiers: 1. Core fields (id, summary, detail, score) 2. Curated substrate subset (thread\_status, pinned, etc.) 3. `metadata.X` for everything else 4. Ambient passthrough as literal `$(MEMORY.field)` if unresolved **Connector duplication is a contract violation.** If a field is in the curated subset, the connector populates it at top-level only — `metadata.` MUST be absent. Otherwise `$(M.thread_status)` and `$(M.metadata.thread_status)` can return different values (silent data divergence). Connectors enforce. ## Why connector abstraction matters Hard-coupling skills to specific substrates would make information-flow decisions infrastructural rather than skill-authored, defeating the point of skills as the agent's programming language. The connector layer is what lets the same skill body run against substrate A today and run against substrate B tomorrow without rewriting. ## Lifecycle and status — # Status: header, three canonical states (Draft / Approved / Disabled), compile + runtime enforcement Skillscripts carry an explicit lifecycle state via the `# Status:` header. The compiler and runtime enforce status — a Disabled skillscript cannot fire under any path, regardless of who invokes it. ## Header syntax ``` # Skill: support-response-draft # Status: Approved v1:a1b2c3d4 # Description: ... ``` If `# Status:` is omitted, the default state is **Draft**. This forces authors to explicitly promote a skillscript through its lifecycle rather than relying on "newly written = ready for use." **Case normalization:** Status values are accepted case-insensitively on input and stored as canonical form. `# Status: draft`, `# Status: Draft`, `# Status: DRAFT` all parse to canonical `Draft`. This principle applies across all enumerated frontmatter value spaces (see Overview section on Lexical conventions). ## The three canonical states * **Draft** — being authored or under revision; not ready for production use. Compile warns; runtime refuses unless explicitly invoked with `--force-draft` for the author's own testing. Triggers don't fire under default dispatch. * **Approved** — passed authoring + lint and is ready to fire. The canonical "in use" state. Compile is clean; runtime allows everywhere; declared triggers fire freely. **Requires a hash-token stamp** (see below). * **Disabled** — explicitly off. Compile rejects; runtime rejects; triggers don't fire. Source and version history preserved, but the skillscript cannot execute under any path. These three states have crisp, universal operational meaning across every deployment. Every operator understands what each state means; no judgment calls about edge-case distinctions. ## Hash-token approval for Approved `# Status: Approved` requires a stamped version-hash token: `# Status: Approved v1:` where `` is `f(skill_body)`. Naked `# Status: Approved` (without the stamp) refuses to execute at runtime. The runtime verifies the stamp on every execution path: * Trigger-fired dispatch * MCP `execute_skill` invocation * In-skill `$ execute_skill` composition * Compile-time `inline(skill=...)` references The stamp closes the gate against tampered or Draft-promoted-without-review skill bodies. Three paths produce a stamped Approved skill: 1. **Dashboard approval flow** — human reviewer approves; dashboard stamps the token. 2. **`skill_write` MCP tool auto-stamp** — when an agent writes a skill body declaring `# Status: Approved`, the SkillStore auto-stamps the token on persist (headless-adopter convenience). 3. **Manual stamp** — for unusual cases; details in the adopter playbook. Tampered bodies (someone edits the source post-stamp) re-derive a different token and refuse to execute. The hash-token check is the structural lock; the dashboard / `skill_write` flows are the discipline layer. ## Compile + runtime behavior table | State | Compile | Runtime invocation | Test harness | Default trigger fire | | - | - | - | - | - | | Draft | warn | refuse (unless `--force-draft`) | allow (with flag) | refuse | | Approved (stamped) | OK | allow | allow | allow | | Approved (unstamped) | warn `approved-without-stamp` | refuse | refuse | refuse | | Disabled | refuse | refuse | refuse | refuse | ## Trigger registry interaction The trigger registry respects status. A skillscript in Draft or Disabled state has its declared triggers held in a non-firing state — the trigger is registered (visible via `listTriggers`) but the scheduler skips dispatch. This lets authors register triggers while still in Draft mode without risking accidental production fires. When a skillscript transitions to Approved (with valid stamp), its triggers activate. When it transitions to Disabled, its triggers deactivate. ## State transitions Status transitions are freeform — any author with write authority on the skillscript can flip the status by editing the header. Future versions may add transition rules (Draft → Approved with lint-pass requirement; Disabled requiring admin-level permission) once a real authorship-permissions story is in place. ## Audit trail Status changes are visible via the storage substrate's versioning. For SqliteSkillStore-backed skills, each status transition appends a row to `skill_versions` (see SqliteSkillStore docs). For FilesystemSkillStore-backed skills, status changes show up in git history. The audit trail is part of the substrate, not part of the language. ## States considered but not implemented Three additional states were considered and deferred. Each is cheap to add later when justified by real operational need: * **Test** — distinct "passed compile but not production-ready" state. Today's Draft covers this case (same behavior — refuse to fire under default dispatch). If authors find Draft and Test are operationally distinct in practice, Test ships then. * **Deployed** — distinct "currently shipping" state separate from Approved. Today's Approved + active triggers IS deployed; no operational difference. If a deployment finds Approved-vs-Deployed meaningfully different (e.g., a release-gating workflow that distinguishes "ready" from "live"), Deployed ships then. * **Deprecated** — soft-warn state for "still works but new authoring should use a successor." Deprecation is currently carried in metadata (`deprecated: true` in frontmatter) + a lint warning at invocation sites. When deprecated skills accumulate enough that the metadata pattern is awkward, Deprecated promotes to a first-class state. Adding states is additive — existing skills with the three-state model continue to work when new states are added. ## Why this matters The lifecycle states are the language's answer to operational safety at scale. A traditional "all skillscripts compile and run" model relies on author discipline to keep broken or untested work out of production. Status states enforce the discipline at the language level — a Disabled skill cannot fire even if every author downstream forgets it's broken. The hash-token approval mechanism extends this to: an Approved skill cannot fire if its body was tampered post-approval. The constraint IS the safety story, here as elsewhere. ## Open questions * **Status + composition.** When a procedural skill references a data skill via `inline(skill=...)`, what happens if the data skill is Disabled? Probable answer: compile-time error if any referenced skill is Disabled. * **Bulk status operations.** "Disable all skills tagged with project:legacy" is a useful operational primitive. May add a `skillscript bulk-status ` CLI affordance later. ## Error handling — else: blocks, # OnError: fallback, op-level fallback values Skillscript provides three layers of error handling, working from local to global. ## Layer 1: Target-level `else:` block Runs if any op in the target's primary body errors. Local to the failing target. Downstream targets that depend on this one can still proceed using whatever the `else:` branch produced. ``` fetch: $ data_read mode=fts query=${TOPIC} limit=5 -> RESULT else: emit(text="retrieval failed, falling back to empty result") $set RESULT = "" ``` ### Distinguished from conditional `else:` The keyword `else:` is shared between two purposes: * Conditional `else:` — appears after `if:` / `elif:` chain inside a target body * Target `else:` — appears as a sibling block after a target's primary body, as an error handler The parser's scope-stack discriminates at parse time. Both kinds coexist in the same target. ### Constraint `else:` blocks may not declare their own error handlers (no nested catch). If an `else:` block fails, the whole target fails through `# OnError:` if present. ## Layer 2: Skill-level `# OnError:` header Names a fallback skill to invoke if anything in the skill fails — including target-level errors that aren't caught by `else:`, compile errors, or the executing context running out of resources. ``` # Skill: morning-brief # OnError: morning-brief-degraded ``` Compile-time existence check — fails clean if the referenced fallback doesn't exist. The fallback skill is itself a skill (same compilation, same execution model) and can do real work (file an issue, post an ack, write a degraded result, etc.). The fallback skill receives: * The same inputs as the failing skill * An additional `${ERROR_CONTEXT}` ambient ref containing the error type and the target where it failed ### Constraint Nested `# OnError:` is *not* supported. If `# OnError: degraded-skill` fires and `degraded-skill` itself errors, the runtime hard-exits with no further fallback. Spec is explicit on this. ## Layer 3: Op-level fallback values Inline fallback declared on the op line. Used when the call fails or returns empty. Supported on `$` (MCP dispatch) ops and on `shell()` with coerce-on-bind semantics. For `shell()` the fallback fires on op throw OR empty stdout (e.g. `gh pr list` against a repo with no open PRs binds the fallback string). ``` weather: $ data_read mode=fts query="weather ${LOCATION}" limit=1 -> CURRENT (fallback: "weather unavailable") $ llm prompt="Summarize: ${CURRENT}" -> SUMMARY (fallback: "summary unavailable") $ slack.post channel=${CHANNEL} text=${SUMMARY} (fallback: "post failed silently") -> ACK shell(argv=["gh","pr","list","--repo","acme/foo"]) -> PRS (fallback: "No open PRs") ``` Same pattern as the `# Requires:` cascade's `(fallback: ...)` syntax — consistent across compile-time (`# Requires:`) and runtime (`$` dispatch and `shell()`). **Fallback value parsing.** Permissive: bare identifiers, quoted strings, and bracketed array literals all accepted. Matches the `# Requires:` cascade convention. ``` $ data_read mode=fts query="..." -> RESULTS (fallback: []) # array literal $ llm prompt="..." -> VERDICT (fallback: unknown) # bare identifier $ slack.post text="..." -> ACK (fallback: "post failed") # quoted string ``` **Coerce-on-bind semantics.** On op throw or empty-result, the fallback value is bound to the outputVar via the same path as a successful result. Downstream targets see the fallback transparently — they don't need conditional checks to detect "did this op fail?" The op-level fallback IS the default-on-failure value. ## Error propagation rules * Op error → caught by `else:` if present, otherwise propagates to target * Target error → caught by `# OnError:` if present, otherwise propagates to caller * Caller can still catch via standard exception handling on compile / runtime invocation APIs * `else:` blocks are not allowed to declare their own error handlers * If an `else:` block itself fails, the whole target fails through `# OnError:` (if present) ## Visibility into errors Open spec question: should `${ERROR}` be ambient inside `else:` blocks (same shape as `${ERROR_CONTEXT}` in `# OnError:` fallbacks)? Current lean: yes. Useful for telemetry skills that need to know what failed before falling back. Not yet specified or shipped. ## The fallback pattern is consistent across scopes Same idea at every scope: * Compile-time: `# Requires: ... (fallback: value)` * Runtime op: `$ dispatch ... (fallback: value)` and `shell(...) ... (fallback: value)` * Runtime target: `else:` block * Whole skill: `# OnError:` header Authors composing complex skills use these in combination — op-level for transient errors, target-level for cohesive error paths, skill-level for last-resort degradation. ## Connection to runtime observability Per-op error contract is what makes cascading fallbacks work. When `$` returns `isError: true`, the executor throws via `makeOpError` rather than binding the error text to the output var. The throw routes through `else:` / `# OnError:` machinery and surfaces in `result.errors[]` for the scheduler to log. Without this discipline, op-level failures wouldn't propagate to the fallback layers and silent-fail would be the default. Op-level `(fallback:)` is distinct: it intercepts the throw/empty-result at the op and binds the fallback value rather than propagating — a fired fallback is recorded in `result.fallbacks[]`, not `result.errors[]`. ## Composition — skills calling skills Skillscript supports skill-to-skill composition via the runtime's public composition primitive. A parent skill invokes a child skill, optionally passes inputs, optionally binds the child's result. The runtime threads variable state, propagates errors, and enforces a recursion-depth guard. Composition is exposed as a runtime-intrinsic op: `execute_skill(skill_name="...", inputs={...}) -> R`. Symmetric with `compile_skill` and `lint_skill` — same surface, same naming convention, no external-namespace dependency. ## Surface ``` parent: execute_skill(skill_name="child") -> RESULT emit(text="Child returned: ${RESULT}") ``` The runtime resolves `skill_name` against the configured SkillStore at dispatch time, runs the child to completion against the runtime's wired connectors, and binds the result. ## Tool signature ``` execute_skill({ skill_name: string, // required — resolves via SkillStore inputs?: Record, // optional — Vars override map mechanical?: boolean // optional — dry-run mode (default false) }) ``` **Returns:** `{ final_vars, transcript, outputs, errors, target_order, provenance }`. **`final_vars` is filtered to the child's declared `# Returns:` surface** (see Return contract below) — a child with no `# Returns:` returns `final_vars: {}`. `outputs`, `transcript`, and execution metadata always propagate. ## Return contract: `# Returns:` A skill declares its export surface with a `# Returns:` frontmatter header — the output-side mirror of `# Vars:` (input side). Skills are functions: `# Vars:` is the parameter list, `# Returns:` is the return signature. ``` # Skill: get-weather # Status: Approved # Vars: LOCATION="Valdese" # Returns: SUMMARY, TEMP_F, CONDITIONS fetch: shell(command="curl -s 'wttr.in/${LOCATION|url}?format=j1'") -> RAW $ json_parse ${RAW} -> PARSED $set TEMP_F = ${PARSED.current_condition.0.temp_F} $set CONDITIONS = ${PARSED.current_condition.0.weatherDesc.0.value} $set SUMMARY = "${LOCATION}: ${TEMP_F}°F and ${CONDITIONS}" emit(text="${SUMMARY}") default: fetch ``` **What the caller's `-> R` binding receives:** * `R.outputs` — the delivery (emit) stream. Always exported. * `R.transcript` — execution trace. Always exported. * `R.errors`, `R.target_order`, `R.fallbacks`, `R.agent_delivery_receipts` — execution metadata. Always exported. * `R.SUMMARY`, `R.TEMP_F`, `R.CONDITIONS` — the declared returns, accessible at top level: `${R.SUMMARY}`, NOT `${R.final_vars.SUMMARY}`. * **NOT** `R.RAW`, `R.PARSED` — internal scratch. Not declared, not exported. **Default — no `# Returns:` exports nothing from final\_vars.** A skill without a `# Returns:` header returns `final_vars: {}`. Its `outputs`/`transcript`/metadata still propagate, so emit-driven skills (whose consumers read `${R.outputs.text}`) need no `# Returns:` at all. Declare `# Returns:` only when a caller needs structured access to specific variables. **Per-level contract — composition doesn't compound.** Each skill's `# Returns:` governs only what *its* caller sees of it. In `A → B → C`, B's `# Returns:` governs what A sees of B; C's scratch never reaches A. This is what makes deep composition safe: internal state stays execution-scoped and is filtered at each boundary, so a stack of composed skills can't accumulate each other's scratch (the failure mode that motivated the contract — an undeclared large intermediate propagating up the whole chain). **Top-level MCP result is filtered too.** A direct `execute_skill` MCP call of a no-`# Returns:` skill returns `final_vars: {}` — the filter applies to direct invocation, not just child-propagation. Adopters inspecting `final_vars` via the MCP tool see the declared-returns surface, not the full variable dump. **Lint:** * `unknown-returns-ref` (tier-1) — `# Returns: X` where `X` isn't bound anywhere in the skill body. Same shape as undeclared-var, for the export side. * `unexported-final-var-access` (tier-2 advisory) — caller accesses `${R.X}` where `X` isn't in the called skill's `# Returns:`. Catches the "forgot to export it" footgun (forward-reference deferred-resolution if the called skill isn't yet stored). ## Semantics **Skill resolution.** Missing skills produce a clean structured error (`MissingSkillReferenceError extends OpError`) — the parent's `(fallback: ...)` discipline applies if specified, otherwise the parent skill's `# OnError:` fallback fires if declared, otherwise the parent fails with the error propagated through. **Input override.** `inputs` map keys must match the child's `# Vars:` declarations. Undeclared keys are ignored. Required vars without defaults must be supplied or dispatch fails before the child starts. **Variable threading.** The parent's variable scope is sealed from the child's; the child sees only its declared `# Vars:` plus the inputs override plus ambient refs. The child's emitted result binds to the parent's named variable via `-> RESULT` (filtered to the child's `# Returns:` surface). The child's transcript surfaces through the parent's transcript with provenance attribution. **Mechanical mode (the TestFlight property).** When `mechanical: true`, the dispatch graph renders without firing side-effect ops. `$` dispatch ops bind null; runtime-intrinsic side-effect ops bind self-describing placeholder strings. The mechanical flag propagates through recursive `execute_skill` calls — the whole sub-graph previews end-to-end, no real services touched. Authors use this to validate a multi-skill composition chain before committing to any real call. **Recursion guard.** The runtime enforces a configurable recursion-depth limit (default 10) to prevent infinite-loop composition. Exceeding the limit raises a clean structured error attributable to the offending dispatch site, not a stack overflow. ## Error surfacing in composition Two non-obvious behaviors when reading a child's failures from the parent (both confirmed by the v1.0 runtime-semantics test battery): * **Nested errors do NOT surface at the top level.** When a child op fails — e.g. the recursion-depth guard fires — the structured error nests inside the child's `R.errors`, which nests inside *its* parent's `R.errors`, and so on up the chain. It does **not** bubble to the caller's top-level `result.errors`. So a top-level `errors: []` does **not** mean nothing failed downstream. To detect a child failure, inspect the bound `${R.errors}` (and deeper), or rely on `(fallback: ...)` / `# OnError:` — those fire on the structured error regardless of nesting depth. * **`# Returns: R` is load-bearing for observability.** If the parent binds a child via `-> R` but does not declare `# Returns: R`, the `# Returns:` filter strips `R` from the parent's `final_vars` — and any nested child errors disappear from the parent's MCP-wire response along with it. A composition skill that wants its child's failures observable from *its own* caller must declare the binding (`# Returns: R`) explicitly. Observability of child failure is opt-in, the same way value export is. ## Forward-reference resolution Skill references (`inline(skill=...)`, `execute_skill(skill_name=...)`) are validated at compile time but allow forward references with tier-2 advisories — making it possible to author sibling skills together (chicken-and-egg). **Lint behavior:** * `unknown-skill-reference` (tier-2) — covers `inline()` and `execute_skill()` with missing targets * `deferred-skill-reference` (tier-3 advisory) — teaching message: *"Skill 'X' referenced via `` is not currently in the SkillStore. Will resolve at execute time if the skill exists by then, or throw `SkillNotFoundError` if not. If this is a typo, fix it now; if it's a forward reference, this advisory will clear once you store 'X'."* **Runtime behavior:** when a deferred reference still can't resolve at execute time, the runtime throws `MissingSkillReferenceError extends OpError` with structured fields (`missingSkillName`, `viaOp` for the op kind, inherited `target` and `opKind`). The error flows through `# OnError:` fallback chain naturally. **Stronger contracts kept tier-1:** * `# OnError: ` — error-handler missing-at-runtime is the worst possible UX moment to discover a missing reference; explicit at compile is the right call. * `disabled-skill-reference` — pointing at a Disabled skill is a stronger contract than "missing yet to be authored"; explicit at compile. ## When to use composition vs other primitives Three distinct cases that look similar but have different intents: 1. **Get a value back from another skill.** Use `execute_skill(skill_name="...") -> RESULT` and use `${RESULT}` locally — reaching declared returns (`${RESULT.X}`) or the output stream (`${RESULT.outputs.text}`). This is the composition primitive case. 2. **Delegate work to an agent as a task.** Use `# Output: template: ` to route a compiled artifact through AgentConnector. The receiving agent acts on the prompt. *This is the Template-skill story* — uses compile-as-delivery, not execute-and-bind. 3. **Augment an agent's context with a result.** Use `# Output: agent: ` to route the executed skill's output into the receiving agent's prompt context as augment-kind payload. *This is the Augmenting-skill story.* The composition primitive (case 1) is for *intra-skill value passing*. Cases 2 and 3 are for *cross-agent delivery*. The runtime handles all three; the right primitive matches the intent. ## Examples **Simple call + bind:** ``` # Skill: greeting # Status: Approved # Vars: NAME=world greet: emit(text="Hello, ${NAME}!") default: greet ``` ``` # Skill: parent # Status: Approved call_greeting: execute_skill(skill_name="greeting") -> GREETING_RESULT emit(text="Greeting skill said: ${GREETING_RESULT.outputs.text}") default: call_greeting ``` (greeting is emit-only — no `# Returns:` needed; the parent reads `.outputs.text`.) **Composition with input override + declared return:** ``` # Skill: classifier # Status: Approved # Vars: TEXT="" # Returns: VERDICT classify: $ llm prompt="Classify: ${TEXT}" -> VERDICT emit(text="${VERDICT}") default: classify ``` ``` # Skill: parent-with-inputs # Status: Approved # Vars: INPUT="some text" call_with_inputs: execute_skill(skill_name="classifier", inputs={"TEXT": "${INPUT}"}) -> R emit(text="Classified as: ${R.VERDICT}") default: call_with_inputs ``` **Defensive composition with fallback:** ``` # Skill: defensive-parent # Status: Approved call_maybe_missing: execute_skill(skill_name="might-not-exist") -> RESULT (fallback: "child unavailable") emit(text="Result: ${RESULT.outputs.text}") default: call_maybe_missing ``` **TestFlight preview (from the runtime caller, not from inside a skill):** ``` execute_skill({ skill_name: "parent", mechanical: true }) ``` Renders the full dispatch chain — parent's targets in topo order, plus the child's targets where `execute_skill` would fire — without any real ops running. Useful for validating composition before commitment. ## Compile-time inline composition: `inline()` For *data skills* (skills marked `# Type: data`), the compile-time inline primitive `inline(skill="")` resolves the data skill at compile time and bakes its emitted text into the parent's compiled artifact. The data skill's `content_hash` is recorded in the host's provenance; `skillfile audit` detects stale recompiles when a referenced data skill changes. `inline()` is compile-time and brings in *data* (the data skill's emitted text); `execute_skill()` is runtime and brings in *behavior* (the child runs in its own frame, returns its declared `# Returns:` surface). Different mechanisms, different use cases. There is no executable form of `inline`. ## Authoring discipline * Treat composition as a real cost. Each `execute_skill()` dispatch incurs the child's full execution time + side effects. Don't compose for trivial cases that could be inlined. * Declare `# Returns:` when a caller needs structured access to a child's variables. Leave it off for emit-only skills whose consumers read `.outputs.text` — the default-empty filter keeps scratch from propagating. * Want a child's failures visible to your caller? Declare the child binding in `# Returns:` — nested errors are filtered out with the binding otherwise (see Error surfacing in composition), and don't trust a top-level `errors: []`. * Pair composition with `(fallback: ...)` when the child skill might fail and the parent has a sensible degraded path. * Use mechanical mode to TestFlight any multi-skill chain before shipping it as a Headless skill on a cron trigger. * Forward references work — author sibling skills in any order, validate independently. The tier-2 warning surfaces the deferred-resolution path; runtime catches genuine misses. * Recursion is legal but bounded. If your design requires deeper recursion than the configured limit, reshape the workflow — almost always a sign of an iteration that should be expressed as `foreach` rather than recursion. ## Static vs Dynamic — skill execution model Orthogonal to the three skill categories (Headless / Augmenting / Template, which describe the skill's relationship to the frontier agent), every skill has an *execution model* that describes its relationship to the Skillscript runtime. ## Static skill A static skill compiles to a portable artifact that any agent capable of reading prose can execute. The compiled output is the deliverable — it does not require the Skillscript runtime, wired connectors, or dispatch machinery to run. A static skill can be: * **A pure recipe** — procedure steps the executor follows using their own tools and judgment * **A data + recipe bundle** — data embedded in the skill (via `# Vars:` defaults or `inline(skill=...)` data-skills) plus instructions for what to do with it * **A reference to known-local tools** — may reference shell binaries (`curl`, `jq`, etc.) that the executor is expected to have; the executor invokes those themselves rather than via Skillscript's `shell()` dispatch Static skills are useful for: * **Skill sharing** — a `.skill` artifact can be emailed, posted, or otherwise distributed without runtime ownership transfer * **Pipelining data with procedure** — "here are 30 customer reviews. Theme them and emit a summary." The data + recipe ship together; the executor runs them. * **Knowledge artifacts** — durable procedures that survive the runtime they were authored on * **Cross-platform deliveries** — a static skill compiled on a Skillscript runtime can be executed by Claude, GPT, or any frontier agent The Template-kind skill is the canonical static shape — its `# Output: template:` declaration explicitly indicates the runtime doesn't dispatch the body; instead, the compiled artifact is routed to the receiving agent for execution. ## Dynamic skill A dynamic skill requires the Skillscript runtime to execute. The runtime walks the dispatch DAG, fires `$` ops against wired connectors, runs runtime-intrinsic ops (`emit`, `notify`, `shell`, `file_read`, `file_write`, `execute_skill`), and threads outputs through variable bindings. Dynamic skills are the default for: * **Autonomous workflows** — cron-fired Headless skills that fetch, reason, and emit * **Composition orchestrators** — parent skills that invoke child skills via `execute_skill()` * **Augmenting deliveries** — skills that gather material via dispatches before composing an augment payload Dynamic skills bind their behavior to the specific runtime they're executed on: connector configuration, model selection, shell-execution mode, persistent trigger registry. They are not portable in the way static skills are. ## Orthogonality to skill category | | Headless | Augmenting | Template | | - | - | - | - | | **Static** | rare (only-`emit()` cron-fired emission skills) | possible (text-only augment with no fetches) | common (the default Template shape) | | **Dynamic** | common (the default Headless shape) | common (the default Augmenting shape) | possible (Template with `$` setup ops before the prompt body) | The axes are independent. A skill author can produce any combination. ## Compile-time portability validation (planned) A `# Portability: static | dynamic` frontmatter header would declare the skill's intended execution model. The compiler would lint-check that the skill's op set is consistent with the declaration: * `# Portability: static` → no `$` dispatch ops permitted; no side-effect runtime-intrinsics (`shell`, `file_write`, `notify`, `execute_skill`); only the static-safe set (`emit`, `$set`, `$append`, `inline()`, conditionals, iteration) * `# Portability: dynamic` (or unset, the default) → any op permitted A new compile mode `compile_skill({source, mode: "static"})` would render only the portable artifact, refusing skills that depend on runtime dispatch. Pending implementation. See "Not yet implemented, but planned" at top. ## When to choose which **Choose static when:** * The skill should be portable beyond this runtime * The skill's value is the procedure or data + procedure, not the dispatch behavior * The skill will be shared, distributed, or executed by an external agent * Pipelining a known data payload through a recipe **Choose dynamic when:** * The skill needs to fetch, reason against, or emit through wired connectors * The skill is autonomous (cron-fired) or augmenting (live context) * The skill composes other skills via runtime dispatch (`execute_skill()`) * The skill is bound to this runtime's connector configuration ## Implementation status Today's skills are all "dynamic" by default; static skills work in practice (any skill whose ops are only `emit()` / `$set` / `$append` / `inline()` / conditionals / iteration is portable), but the language doesn't yet declare or enforce the distinction. The recipe-with-data pattern is implicit today via `# Vars:` defaults + `inline(skill=...)` data-skill inlines — a static skill can carry payload via these mechanisms without runtime dependence. ## Tests — # Tests: block, given/expect assertions The `# Tests:` header introduces a block of test cases that travel with the skill body. Each case has `given:` (variable overrides) and `expect:` (assertions on the compiled output or runtime side effects). ## Status Header parsing and test runner not yet shipped. See "Not yet implemented, but planned" at top. The grammar below is the design but implementation is pending. ## Proposed grammar ``` # Tests: - name: "basic_url_filter" given: LOCATION: "Asheville, NC" expect: compiled_output_contains: "wttr.in/Asheville%2C%20NC" - name: "missing_required_var_errors" given: LOCATION: null expect: compile_error: "Missing required variable: LOCATION" - name: "fetch_failure_runs_else_block" given: TOPIC: "definitely-not-a-real-topic-xyz" expect: target_else_executed: "fetch" result_value: "" ``` ## Execution Run via the compile API with `format: "test"` (and optional `test_case: ""` to run a single case). All cases run when `test_case` is omitted. Returns pass/fail per assertion with diagnostic detail. Normal `prompt` / `prose` compilation ignores the `# Tests:` section entirely — tests travel with the skill without affecting production use. ## Assertion types ### Compile-time assertions * `compiled_output_contains: ""` — the rendered prompt artifact contains the given substring * `compile_error: ""` — compilation fails with an error message containing the substring * `compiled_output_does_not_contain: ""` — negative assertion ### Runtime assertions (for `format: "test"` execution) * `target_else_executed: ""` — verifies the `else:` branch ran * `onerror_invoked: ""` — verifies the `# OnError:` skill was called * `op_fallback_used: ""` — verifies an op-level fallback value was substituted * `result_value: ""` — the skill's final output value ## Open spec questions ### Runtime assertion sandboxing `# Tests:` cases that exercise runtime behavior (data writes, shell ops, LocalModel calls) need a sandbox so they don't pollute production data. Two approaches: * Scratch DB / scratch connector overrides for tests * Skip-and-warn for non-deterministic ops, only assert deterministic compile-time properties Deferred until the test runner ships. ### Property-based tests The current design covers example-based tests. Property-based tests (`for all inputs in {...}, output matches pattern X`) would be a useful future addition but require a generator framework. ## Connection to authoring discipline The authoring loop — *author → lint → revise → store* — depends on tests-as-preflight being cheap to author and cheap to run. The `# Tests:` block makes this possible at skill-source-level; the lint pass enforces structural correctness; together they raise the bar for what enters the library. Skill discovery via `skill_list()` (see SkillStore docs) closes the related visibility gap — `execute_skill()` references can be validated against the discoverable surface at compile time. ## Future grammar extensions — sensors, time primitives, suppression, persistent state, capability declarations, debounce Design rationale for planned features. The user-facing list of "what's coming" lives in the "Not yet implemented, but planned" section at top; this section documents the *why* behind each planned addition. When the language extends, the relevant grammar moves into its canonical section (Ops reference, Variables, Triggers, etc.) and the design-rationale entry here is replaced with a cross-reference. ## Sensors as a read-channel category > `sensor:` is **not a trigger source** — to *fire* a skill on a sensor signal, a sensor adapter POSTs to the `/event` ingress like any other external source (see Triggers). What remains a future idea is the separate concept below: sensors as a continuous **read channel**, decoupled from triggering. The read-channel idea: a skill declares sensors it reads, distinct from what fires it: ``` # Sensors: presence, screen-state, voice-prosody # Triggers: cron: 0 8 * * * ``` **Distinction:** Sensors (read-channel) are continuous values the agent reads but doesn't emit on. Triggers are discrete signals that fire the skill. The two are different semantics — sensors need continuous read, ambient-ref access, and privacy gating; triggers need discrete fire + dispatch. (Conflating them in one `sensor:` trigger source was the old design; the trigger half folds into `event`, the read-channel half stays future.) Pending: ambient refs for sensor values (`${SENSOR.presence}`, `${SENSOR.voice-prosody.affect}`) and the privacy-gating discipline that determines when a sensor is readable. ## Time as first-class primitives Current ambient time: `${NOW}` (wall-clock ISO timestamp). Planned relative-time primitives: ``` ${SECONDS_SINCE_LAST_USER_MESSAGE} ${MINUTES_SINCE_SESSION_START} ${SECONDS_SINCE_LAST_FIRE_OF.} ``` **Rationale:** Most "right time" reasoning is relative, not wall-clock. Authoring relative-time guards requires either runtime-state tracking (which authors then rebuild manually) or first-class primitives. The latter wins. ## Absence as trigger Different shape from event triggers — "fire if user hasn't messaged in N minutes" is a wait-for-nothing primitive, not a wait-for-event primitive. Proposed grammar: ``` # Triggers: idle: 5m ``` Runtime tracks the relevant idleness counter and fires when the threshold crosses. Would be a **new trigger source beyond the current `cron`|`event`** — or, absent a new source, an adapter that POSTs to `/event` on a timer. Separate dispatch mechanism from event triggers either way. ## Time-windowed aggregation Filter-like primitives that operate on state across firings: ``` $ llm prompt="..." -> VERDICT # pseudo-syntax pending: aggregate over a window ${VERDICT|last-5|count-where:value=="frustrated"} ``` **Rationale:** "User has shown frustration in 3 of 5 recent turns" is a canonical sensor-derived condition. Without first-class windowing, every skill rebuilds ring buffers. Pending design: filter syntax vs new op kind. ## Backpressure / debouncing Sensors produce floods. First-class primitives for rate limiting: ``` # Debounce: 5s # RateLimit: 1/minute # Coalesce: latest ``` Headers declare the runtime's queueing policy. Runtime enforces; skill body doesn't reimplement. ## Suppression as valid output Current behavior: a skill that fires must produce *some* output (even empty string). Pending: explicit "fire-and-suppress" — the skill considered the situation and decided not to emit. Different from `# Output: none` (which signals "I do side effects only"). Proposed: an explicit suppression op or `$set OUTPUT = null` triggers suppression-detection in the runtime. Output routers skip delivery; trigger fire counts increment for telemetry; no consumer surface receives noise. **Rationale:** Without suppression, signal pipelines become noisy. "Fire everything, hope the right one wins" turns the inbox-to-context into spam. Discipline that makes pub-sub tractable. ## Persistent state with declared scope Current `$set` is per-execution; no lifecycle beyond the fire. Pending: ``` $set NAME = value scope=skill-local $set NAME = value scope=agent-global $set NAME = value scope=session ``` **Scopes:** * `skill-local` — persists across fires of this skill, not visible to other skills * `agent-global` — visible to all skills of the same agent * `session` — alive for the duration of the current session, cleared at session end Backed by a configured data-records connector (the same surface `# Requires:` reads from) with conventionally-namespaced keys (e.g., `state:skill-local::`). **Rationale:** Most interesting skills need persistent state across firings — change-detection, windowing, dedup-against-recent. Without lifecycle, every skill rebuilds state tracking via raw `$ data_write` / `$ data_read` calls. ## Cross-skill pub-sub Procedural `execute_skill()` invocation handles one-to-one composition. Pub-sub handles many-to-many. ``` # Publishes: signal.frustration-detected # Subscribes: signal.user-confused ``` When a skill publishes a signal, all subscribed skills fire (independent executions, parallel dispatch). Decouples emitters from consumers — the inverse of direct invocation. **Rationale:** When signal flow is many-to-many, direct invocation couples everything to everything. Pub-sub keeps emitters ignorant of consumers. ## Confidence/threshold gating Declarative guards on skill firing: ``` # RequiresConfidence: classifier >= 0.8 # RequiresThreshold: change-delta >= 0.3 ``` Runtime evaluates the guard before dispatching the skill body. Lets sensitive skills opt out of low-confidence triggers without each skill's body rebuilding the same guard expression. ## Invocation-control axis Currently a skill is uniformly invocable from any caller (user via explicit command, agent mid-conversation, trigger autonomous fire). Some skills are user-only intents (user types a slash-command to invoke), some are agent-only behaviors (agent picks the skill via description-match while reasoning), some are trigger-only autonomous fires. Proposed grammar: ``` # Invocable-By: user, agent, trigger # Invocable-By: trigger # autonomous only # Invocable-By: user # explicit-command only; agent can't pick it via reasoning ``` Header is a permissive list; absent means all three (current default behavior). Lint flags semantically-inconsistent declarations — a skill with `# Triggers: cron:` but `# Invocable-By: user` is a contradiction the rule catches. **Rationale:** without the axis, sensitive operations (destructive writes, external messages, irreversible state changes) leak across invocation boundaries. An agent reading skill descriptions might invoke a skill that should only fire on explicit user command. Capability declarations enforce more granularly, but the user/agent/trigger triad is the structural distinction that catches most surface-leak bugs cheaply. ## Channel/locality awareness Ambient refs for current channel state: ``` ${CHANNEL_TYPE} # slack-dm, slack-channel, voice, web, etc. ${CHANNEL_PRIVACY} # private, public, group ${CHANNEL_NAME} ``` Privacy gating uses these. A sensor-fired skill that reads `voice-prosody` should not emit to a public channel. Runtime enforces; ambient refs let skill bodies make routing decisions. **This is the structural gate** that makes the sensor direction socially defensible — privacy as precondition, not feature. ## Introspection primitives Self-state queries: ``` ${PROMPT_CONTEXT.size} ${SKILLS_FIRED_RECENTLY.last-1h} ${SELF.confidence-trend} ``` **Rationale:** Skills can't reason about other skills' state today. Introspection closes the gap. ## Capability declarations Skill declares its required surfaces: ``` # Requires-Capabilities: sensors=[mic, camera], tools=[datastore.write, slack.post] # Requires-Privacy: private-channel-only ``` Runtime fails-fast on missing capabilities. Trust precondition for sensor work — operators can audit which skills touch which surfaces. ## Build order rationale Some features depend on others: * Suppression + persistent state should land before the sensor read-channel (sensor work would compound problems without them) * Pub-sub needs sensors producing traffic before it has anything to route * Introspection is ergonomic, not foundational — useful but skippable * Capability declarations are the trust gate that makes sensor + privacy work socially defensible The "Not yet implemented, but planned" section at top tracks the user-facing surface; this section preserves the design-order argument for when implementation work picks up. ## Not yet implemented, but planned These are features designed or anticipated but not yet implemented in the current build. Authors should not use these forms; they will not compile. ## Control flow * **`while CONDITION:` loops** — today's iteration is `foreach IDENT in EXPR:` only. While loops are planned for ad-hoc orchestration patterns ("loop until response contains 'done'"). * **Arithmetic in `$set`** — today accepts literals + `${VAR}` interpolation; no `+ - * /` operators. Planned alongside `while` for turn counters and orchestration bookkeeping. ## Pipe filter extensions * **Array aggregation primitives** — `|max`, `|min`, `|sum`, `|reduce` over arrays. Today the language tops out at "shape one record" — aggregating across an array requires `foreach` accumulator ceremony. Planned as a design question: is `foreach` the deliberate ceiling for aggregation, or do we add primitives? ## Triggers — note Trigger sources are `cron` + `event` only (see the Triggers section). There is no separate `agent-event:` / `file-watch:` / `sensor:` trigger source — anything that isn't time-based is an external adapter that POSTs to the `/event` ingress. So there's nothing pending here on the trigger axis; the entry remains only to point readers who expect those sources at the adapter-POST pattern. ## Tests * **`# Tests:` block** with `given:` / `expect:` assertions — author-authored test cases. Will land when adopter signal demands test infrastructure. ## Output kinds * **`# Output: file: `** — file-output routing parses but no router exists today. * **`# Output: card:`** — depends on a substrate-side card render surface; not implemented. ## Persistent state with declared scope ``` $set NAME = value scope=skill-local $set NAME = value scope=agent-global $set NAME = value scope=session ``` Scopes: skill-local (persists across fires of this skill, not visible to other skills), agent-global (visible to all skills of the same agent), session (alive for the duration of the current session, cleared at session end). Backed by a configured data-records connector. ## Time as first-class primitives Currently `$(NOW)` (wall-clock). Planned relative-time primitives: ``` $(SECONDS_SINCE_LAST_USER_MESSAGE) $(MINUTES_SINCE_SESSION_START) $(SECONDS_SINCE_LAST_FIRE_OF.) ``` Most "right time" reasoning is relative, not wall-clock. ## Other planned * **Absence-as-trigger** — `# Triggers: idle: 5m` fire-on-quiet primitive (would be a new trigger source beyond `cron`|`event`, or an adapter that POSTs on a timer) * **Time-windowed aggregation** — filter-like primitives across firings (e.g., "user has shown frustration in 3 of 5 recent turns") * **Debounce / rate-limit / coalesce** — declarative queueing policy headers * **Suppression as valid output** — explicit "fire-and-suppress" (different from `# Output: none`) * **Cross-skill pub-sub** — `# Publishes: signal.X` / `# Subscribes: signal.Y` decoupling * **Confidence/threshold gating** — `# RequiresConfidence: classifier >= 0.8` / `# RequiresThreshold:` * **Invocation-control axis** — `# Invocable-By: user | agent | trigger` (sensitive ops shouldn't leak across invocation boundaries) * **Introspection primitives** — `$(PROMPT_CONTEXT.size)`, `$(SKILLS_FIRED_RECENTLY.last-1h)`, `$(SELF.confidence-trend)` ## When the language extends, this section shrinks When any of these primitives ship, the relevant grammar moves into its canonical section (Ops reference, Variables, Triggers, etc.) and the entry here is removed. This section stays alive as a continuous staging area for the next horizon of unshipped work. *** *Rendered from `skillscript/skillscript-language-reference` — 2026-06-16 15:46 EDT*\ *Source of truth: AMP (`amp_render_document("skillscript/skillscript-language-reference")`)* # SqliteSkillStore Source: https://docs.skillscript.ai/docs/sqlite-skill-store Worked example of SkillStore against a SQLite database — schema, semantics, forking checklist. Worked example of `SkillStore` against a SQLite database. Copy this directory into your codebase, customize per your storage needs, register with skillscript-runtime's `Registry`. This README is written for the agent implementing your adopter's connector — including the human reviewing the PR. **What this demonstrates**: the locked SkillStore contract surface (8 methods + `staticCapabilities`) wired through real SQL with two-table versioning, transactional status transitions, and JSON-extract tag filters. *** ## The three-leg model SkillStore is pluggable. Three legs ship out of the box, but the third is the open one: ``` SkillStore (choose which connector) ├── FilesystemSkillStore (bundled, FS-backed) ├── SqliteSkillStore (this example, DB-backed) └── Adopter-custom (you write your own) ``` If your substrate is Pinecone, S3, Postgres, Redis, or anything else, write a `class FooSkillStore implements SkillStore { ... }` and call `registry.registerSkillStore("primary", new FooSkillStore(...))`. The runtime is none the wiser. This SqliteSkillStore is one such impl — useful as a copy-paste starting point, or directly usable if your needs match. *** ## Quick start ```typescript theme={null} import { Registry } from "skillscript-runtime"; import { SqliteSkillStore } from "./SqliteSkillStore.js"; const registry = new Registry(); registry.registerSkillStore("primary", new SqliteSkillStore({ dbPath: "skills.db" })); // Wire the rest of the runtime (scheduler, mcpServer) using the registry. ``` Author skills programmatically: ```typescript theme={null} const store = registry.getSkillStore("primary"); await store.store("morning-status", `# Skill: morning-status # Status: Approved t: emit(text="report status") default: t `); ``` Or via the dashboard, or via `skill_write` MCP tool — same backend, same result. *** ## When to use SqliteSkillStore (and when not) **Use it when**: * You're embedding skillscript-runtime as a library and want skills in a database rather than `.skill.md` files * Your deployment has no persistent filesystem (container-only) but does have SQLite * You need richer query semantics than filesystem listing (tag filters, transactional status transitions) **Don't use it when**: * You're using the bundled CLI (`skillfile compile`, `skillfile lint`, `skillfile list`). The CLI is filesystem-first by design — `vim foo.skill.md && skillfile lint foo` is the natural authoring loop. The CLI does NOT use SqliteSkillStore. Sqlite-backed skills are authored via dashboard or `skill_write` MCP tool. * Your skills are authored as files-on-disk and committed to git as part of the source tree. FilesystemSkillStore is the right choice there. This is "first-class" in the **programmatic-embedding** sense, not the CLI sense. Treat the example as a substrate-portability proof point + a copy-paste starting point. *** ## Schema Two tables: ```sql theme={null} CREATE TABLE skills ( name TEXT PRIMARY KEY, current_version TEXT NOT NULL, content_hash TEXT NOT NULL, status TEXT NOT NULL, -- 'Draft' | 'Approved' | 'Disabled' source TEXT NOT NULL, -- the .skill.md body bytes description TEXT, -- extracted from `# Description:` header metadata_json TEXT, -- optional metadata bag (tags, author, etc.) created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, status_changed_at INTEGER ); CREATE TABLE skill_versions ( name TEXT NOT NULL, version TEXT NOT NULL, -- short hash (12 chars) content_hash TEXT NOT NULL, source TEXT NOT NULL, -- full body, preserved per version status TEXT NOT NULL, previous_status TEXT, -- populated by update_status changed_at INTEGER NOT NULL, changed_by TEXT, PRIMARY KEY (name, version) ); ``` `skills` is the fast-path read for `load()` / `metadata()` / `query()`. `skill_versions` is the append-only history for `versions()` — and unlike FilesystemSkillStore, it preserves full body bytes per version, so `load(name, version)` can return historical content. WAL is enabled at bootstrap so concurrent readers don't block writers. *** ## Footgun guard: `delete()` is hard-cascade **`delete()` removes both the `skills` row AND its `skill_versions` rows.** If you need recovery, back up adopter-side BEFORE calling delete. Skill names can be reused after delete (no orphan history left behind). This is the locked semantic. If your adopter substrate has compliance requirements (audit-grade retention) or you hit a "wait, I deleted that" moment, the upgrade path is soft-delete (tombstone `status='Deleted'` + filter from query results) — but that's an adopter-side choice; the bundled SqliteSkillStore stays hard-cascade. *** ## Feature flags `staticCapabilities()` declares: | Feature | Value | What it means | | - | - | - | | `supports_writes` | ✓ | `store()` / `update_status()` / `delete()` mutate state | | `supports_versioning` | ✓ | `versions()` returns history; `load(name, version)` returns historical bytes | | `supports_tag_filter` | ✓ | `query({ tag: "foo" })` works via `json_extract(metadata_json, '$.tags')` (O(n) scan) | | `supports_audit_trail` | ✓ | `update_status()` populates `previous_status` on every transition | | `supports_atomic_status_transitions` | ✓ | UPDATE skills + INSERT skill\_versions wrapped in a transaction | The atomic transitions are the SQL advantage over FilesystemSkillStore (which declares `supports_atomic_status_transitions: false` because filesystem writes can tear between body rewrite + sidecar append). *** ## Authoring loop SqliteSkillStore is the storage layer. Authoring happens above: * **Dashboard**: visit `http://localhost:7878`, create/edit skills through the UI; dashboard writes via `skill_write` MCP tool → SqliteSkillStore * **MCP tool**: agents call `skill_write` directly; same path as the dashboard * **Programmatic**: your code calls `store.store(name, source, metadata?)` directly The dashboard defaults to FilesystemSkillStore. For a SqliteSkillStore-backed dashboard, set `substrate.skill_store: "sqlite"` in `connectors.json` — both `skillfile dashboard` and the programmatic `bootstrapFromEnv()` honor it; no custom bootstrap needed. *** ## Approval — the store doesn't mint it `SqliteSkillStore.store()` persists the body as handed to it; it does **not** stamp or verify approval. That's the runtime's concern, and it differs by mode: * **Unsecured mode** — a bare `# Status: Approved` is sufficient and is stored verbatim, no token. * **Secured mode** — approval is a v3 Ed25519 signature applied by the **approve flow** (`skillfile approve` / the dashboard), never by `store()`. The MCP `skill_write` handler forces any unsigned `Approved` write to `Draft` before it reaches the store, and the bundled stores apply the same force as defense-in-depth (in both `store()` and `update_status()`). So `store()` only ever persists a genuinely-signed Approved body or a Draft. The same holds for a fork: your `store()` neither stamps nor verifies — persist the body, let the runtime own the gate. See [Adopter Playbook](adopter-playbook.md) §"Approval + secured mode". *** ## Forking checklist When forking into your codebase: 1. Rename the class (e.g., `PostgresSkillStore`, `RedisSkillStore`) 2. Replace the SQL with your substrate's API (HTTP, DataStore, vector DB, etc.) 3. Update `staticCapabilities()` to match what your substrate actually supports — drop `supports_versioning` if you can't track history, drop `supports_tag_filter` if querying tags isn't tractable 4. Update `manifest()` to describe your substrate (`kind: "postgres"` or whatever) 5. **Optional but high-value for network-backed forks: implement `version()`** — a cheap store-wide change-token computed WITHOUT loading bodies (a list ETag, max-revision, or metadata digest), where any add/remove/edit/status-change moves it. It lets `skill_list` skip its N+1 catalog rebuild on unchanged polls (each entry otherwise costs a `load()` — one network round-trip per skill against a remote store). `SqliteSkillStore` hashes `(name, status, current_version)` in one body-free query. Skip it and `skill_list` just always rebuilds. 6. Tests: copy `tests/SqliteSkillStore.test.ts` as a starting point + run the conformance suite (`SkillStoreConformance.buildTests()` from `skillscript-runtime/testing`) The conformance suite catches drift from the contract surface. If your fork passes, the runtime treats it interchangeably with FilesystemSkillStore / SqliteSkillStore / etc.