runwhen-capability
The Python SDK that RunWhen capability images are written against, and rwtask, the task host
that runs them.
A capability is a directory holding a manifest.yaml (what the capability is, what it needs,
which tasks it exposes) and a tasks.py (those tasks, as plain Python functions). A capability
image ships exactly one capability plus this SDK; the runner starts it as a warm executor pod and
hands it requests.
Install
Capability repositories pin a release tag:
# pyproject.toml
dependencies = [
"runwhen-capability @ git+https://github.com/runwhen-contrib/runwhen-capability@v0.4.0",
]
For development against a local checkout, install it first and the capability repo without
dependency resolution:
pip install -e ../runwhen-capability[dev]
pip install --no-deps -e .
Writing tasks
from runwhen_capability import Context, SkipTask, setup, task
@setup(outputs=["tree", "changed"])
def checkout(ctx: Context, repo_url: str, sha: str, base_sha: str | None = None):
tree = ctx.git.checkout(repo_url, sha, credential="repo", optional=True)
return {"tree": tree, "changed": ctx.git.changed_files(tree, base_sha) if base_sha else None}
@task(outputs={"findings": "rw.findings.v1"})
def lint(ctx: Context, tree: str, changed: list[str] | None = None):
if changed == []:
raise SkipTask("no changed files to check")
proc = ctx.run(["ruff", "check", "--output-format=sarif", "."], cwd=tree)
return {"findings": {"findings": ctx.sarif.parse(proc.stdout, root=tree)}}
@setup(outputs=[...]) runs once per request, before any task. Tasks reference its outputs in
the manifest as ${setup.<name>}.
@task(outputs={name: kind}) registers a task. The request's camelCase input names arrive as
snake_case keyword arguments.
Context is the task's only boundary: ctx.credential(name), ctx.run(argv) (bounded output,
timeouts, process-group kill), ctx.artifacts, ctx.git, ctx.sarif, ctx.findings,
ctx.repo_fs, ctx.workdir, ctx.log.
- Each task ends
ok, failed (it raised; error says why) or skipped (it raised
SkipTask(reason); reason says why). Either way the rest of the request still runs. Only
tasks can skip: a setup that raises SkipTask has failed.
Artifacts
A result travels inline and has a size cap. Large or binary output goes out as an artifact
instead: its own upload to the runner, streamed, so memory stays bounded however big it is. The
task returns the ArtifactRef, which serialises as {"$artifact": "<ref>"} -- a reference the
platform resolves to the stored artifact.
A packaged capability also declares the output in its manifest.yaml, under the task's outputs;
that is what the platform reads (the kind in @task(outputs={"dump": "artifact"}) is informational
to the SDK):
# manifest.yaml, under the task
outputs:
dump: { kind: artifact, contentType: text/plain, maxSize: 5Gi }
preview: auto|none is optional, and wildcard: true lets the task write dump/<anything>. A
schema output can opt into spill (see "Size limits" below) with spill: auto.
@task(outputs={"report": "artifact", "dump": "artifact"})
def export(ctx: Context):
with ctx.artifacts.open("report", "text/plain") as out:
out.write(b"first line\n")
out.write(b"second line\n")
run = ctx.artifacts.from_process(["pg_dump", "--schema-only", "app"], "dump")
if run.returncode:
raise RuntimeError(run.stderr)
return {"report": out.ref, "dump": run.ref}
open(name, content_type=None) returns a writer. Leaving the with block normally stores the
artifact (out.ref); leaving it on an exception stores nothing. content_type defaults to the
one the output declares.
add_file(path_or_open_file, name, content_type=None) uploads a file. It re-reads the file, so a
busy runner (503) is retried three times, five seconds apart.
from_process(argv, name, *, content_type="text/plain", timeout=None, env=None) runs argv in
ctx.workdir and streams its stdout as the artifact, returning ProcessArtifact(ref, returncode, stderr). A non-zero exit still completes the artifact, so check returncode. With no timeout
it runs until the request's deadline (and without limit under rwtask run); on a timeout the
process group is killed, nothing is stored, and subprocess.TimeoutExpired is raised.
name is a relative path (no empty, . or .. parts) and must be an artifact output the task
declares.
Once bytes start flowing, the runner abandons an upload that receives no byte for two minutes, so
a writer must keep writing. open and from_process stream, and a stream cannot be replayed:
they raise ArtifactBusyError on a busy runner instead of retrying. For sparse output (a little
now, more many minutes later), write a file under ctx.workdir and add_file it.
Reading. An artifact the platform bound to a task input is read by that input's name:
with ctx.artifacts.input("prior-report") as fh: # a binary stream; close it
header = fh.readline()
path = ctx.artifacts.input_path("prior-report") # a local file, for tools that want a path
input_path downloads once into a cache under the executor's workdir (.rw-artifact-cache/)
that later requests share, verifying the sha256 as it streams (E_ARTIFACT_CORRUPT on a
mismatch). The cache is bounded by RW_ARTIFACT_CACHE_MAX_BYTES (default 1 GiB, least recently
used first). The files are read-only (mode 0444): copy one to edit it. The path stays valid for
the rest of the task. A name the request did not bind raises ArtifactUndeclaredError.
Local mode. Under rwtask run there is no runner, so artifacts are files:
<workdir>/.rw-artifacts/<name> for outputs (with a local_... ref) and
<workdir>/.rw-artifacts/inputs/<name> for inputs (input_path returns that file itself),
<workdir> being ctx.workdir. rwtask run deletes the temporary scope it created when it
finishes, so pass --keep-workdir (or your own --workdir) to look at them.
Size limits. When a request carries maxResultBytes, a result whose posted body (compact JSON)
is larger is replaced by a small failed result,
E_RESULT_TOO_LARGE: ... write large data with ctx.artifacts; with none, nothing is capped. An
output the platform declares spillable is moved to an application/json artifact on its own when
its JSON is over 256 KiB, and replaced by its ref. Where artifacts are switched off or unsupported
it stays inline.
Errors. Every artifact failure is an ArtifactError (from runwhen_capability.errors) with a
.code; an uncaught one fails the task with its message.
from runwhen_capability.errors import ArtifactError
try:
ref = ctx.artifacts.add_file(ctx.workdir / "dump.sql", "dump")
except ArtifactError as exc:
ctx.log.error("could not store the dump: %s", exc.code) # e.g. E_ARTIFACT_TOO_LARGE
raise
Each code the runner can return has its own subclass, so a task can catch just one case:
| Class |
Code |
ArtifactTooLargeError (.max_bytes) |
E_ARTIFACT_TOO_LARGE |
ArtifactUndeclaredError |
E_ARTIFACT_UNDECLARED |
ArtifactExistsError |
E_ARTIFACT_EXISTS |
ArtifactQuotaError |
E_ARTIFACT_QUOTA |
ArtifactLeaseLostError |
E_ARTIFACT_LEASE_LOST |
ArtifactBusyError |
E_ARTIFACT_BUSY |
ArtifactsUnavailableError |
E_ARTIFACTS_DISABLED, E_ARTIFACTS_UNSUPPORTED |
ArtifactError |
E_ARTIFACT_TRANSPORT (the runner could not be reached, or a read was cut short), E_ARTIFACT_RESPONSE (an answer the SDK cannot read), E_ARTIFACT_PATH (a bad name), E_ARTIFACT_CORRUPT, E_ARTIFACT_ABORTED, E_ARTIFACT_ENDED, or HTTP_<status> for an answer with no recognised code |
rwtask
rwtask run <capability-dir> --request request.json [--credentials creds.json]
rwtask run --local <bundle-dir> --task <name> [--inputs '<json>'] [--credentials creds.json]
rwtask serve [--capability-dir DIR] [--allow-bundles]
# RELAY_URL, POOL_ID, EXECUTOR_TOKEN_FILE from the env
rwtask plan <dir> [--prune]
rwtask apply <dir> -m <message> [--prune] [--adopt] [--yes]
rwtask export <dir> [--name NAME ...] [--force]
rwtask test <dir> [--task NAME]
rwtask run is the same code path as rwtask serve, against the local filesystem: a capability
author needs no cluster.
GitOps
rwtask plan/apply/export manage custom capability bundles -- a directory holding a
capability.yaml plus its tasks/, lib/, schemas/, tests/ files (see "Custom capability
bundles" below) -- against the RunWhen platform API, so a repository of them can be reviewed and
merged like any other code:
rwtask plan capabilities/ # find every capability.yaml under the dir, recursively
rwtask apply capabilities/ -m "add pgbouncer-health"
rwtask export capabilities/ --name pgbouncer-health
rwtask plan <dir> validates every capability locally first (a local error prints as
file:line code message and exits 1, with no network call); it then asks the platform API what
apply would change and prints each capability's action (create, update, unchanged,
delete, or conflict -- it exists but is not git-managed) and its file diffs. Exit codes are
Terraform-style, for CI: 0 when nothing would change, 2 when something would, 1 on error.
rwtask apply <dir> -m <message> [--prune] [--adopt] [--yes] plans first, prints the plan, then
applies it. A conflict is refused unless --adopt is given. --prune also removes every
git-managed capability missing from dir. Without --yes on a TTY, it asks for confirmation;
off a TTY (e.g. CI) it proceeds without asking, since there is no one to ask -- the pipeline that
invoked it is the actual gate.
rwtask export <dir> [--name NAME ...] [--force] writes each capability's published files under
<dir>/<name>/. Given no --name, every capability in the workspace is exported. It refuses to
overwrite a local file whose content has changed, unless --force is given.
- All three take
--api-url/--token/--workspace, or the RW_API_URL/RW_API_TOKEN/
RW_WORKSPACE env vars. The token is sent as Authorization: Bearer and never printed.
rwtask test <dir> [--task NAME] runs a capability's own tests locally, with no platform API
involved. For each capability under dir and each of its tasks that has a tests/<task>.json
({"inputs": {...}, "target"?: {...}, "expect"?: {"status": "ok"}}), it runs that task through the
same code path run --local uses and checks the resulting status against expect.status (default
"ok"