Skip to main content

krysta · noa

Sandboxed code execution for AI agents.

Run untrusted Python and JavaScript inside an isolated Docker sandbox — no network access, memory limits, live streaming telemetry, and structured crash reporting. Built for agent loops, eval harnesses, and production guardrails.

pip install krysta

What you get

Sandboxed execution Python 3.11 or Node 20 in Docker — no network, 128 MB RAM cap
Live SSE streaming stdout, stderr, rules, and lifecycle events in real time
Dual mode async for live events, or await for a resolved ExecutionTrace
Crash telemetry Structured CrashInfo with error type, message, line number, stack
Stateful sessions spawn() mounts a persistent /workspace for multi-turn loops
Client-side validation RuleEngine + ExecutionTrace for offline rule checks

Quickstart

import asyncio
from krysta.noa import Noa

async def main():
    async with Noa() as noa:
        trace = await noa.execute(
            language="python",
            code='print("hello from noa")',
            timeout_ms=8000,
        )

    print(trace.exit_code)      # 0
    print(trace.duration_ms)    # 1020
    print(trace.stdout_lines)   # [{"type": "stdout", "text": "hello from noa"}]

asyncio.run(main())

The async with block manages the HTTP client lifecycle. Always enter it before calling execute().


execute()

noa.execute(
    language="python",   # "python" | "javascript"
    code=None,           # source string
    code_path=None,      # or path to a local file (max 256 KB)
    timeout_ms=10000,    # 1–60000 ms
    session_id=None,     # pin to a persistent sandbox session
)

Either code or code_path is required.

Await a full trace

async with Noa() as noa:
    trace = await noa.execute(language="python", code="print('hi')")

print(trace.exit_code)
print(trace.duration_ms)

Stream events live

async with Noa() as noa:
    async for event in noa.execute(language="python", code=long_running_code):
        if event["type"] == "stdout":
            print("→", event["text"], end="", flush=True)
        elif event["type"] == "done":
            print("\n[done]")

ExecutionTrace

Field Type Description
job_id str Unique job identifier
exit_code int | None 0 clean, 1 crash, None no terminal event
duration_ms int Wall-clock execution time (daemon-side)
memory_used_mb float Peak RSS in MB. 0.0 on very fast exits or crashes
timeout_hit bool True if killed by the timeout enforcer
stdout_lines list[dict] [{"type": "stdout", "text": "..."}] per line
stderr_lines list[str] Raw stderr. Includes full traceback on crash
crash CrashInfo | None None on clean exit, populated on non-zero exit

CrashInfo

trace = await noa.execute(language="python", code="x = 1 / 0")

if trace.crash:
    print(trace.crash.error_type)   # ZeroDivisionError
    print(trace.crash.message)      # division by zero
    print(trace.crash.line_number)  # 1
    print(trace.crash.stack_trace)  # [...]

Streaming events

Every execute() call yields event dicts:

type When Notes
system Start e.g. EXECUTION_STARTED
stdout During run One line per yield (server batches are expanded automatically)
stderr During run Error output, tracebacks
rules Near end text is JSON list of rule results
metrics Near end text contains duration_ms
done Success Exit code 0
timeout Killed Exceeded timeout_ms
error Failure Non-zero exit or infrastructure error

Safety rules

Returned in the rules event and via noa.validate(trace):

Rule Category Checks
NoNetworkCallsRule security No outbound network calls
ExitCodeZeroRule security Clean exit (code 0)
MemoryLimitRule security Stayed under 128 MB
NoFilesystemAccessRule security No FS access outside /workspace
ValidJsonRule optional Stdout is valid JSON

Static pre-checks run before Docker: code containing urllib, requests, fetch, or filesystem patterns like open() (without a session) is rejected immediately.


Stateful sessions

Use spawn() when an agent writes files, reruns, and needs state to persist between executions:

import uuid
from krysta.noa import spawn

async with spawn(runtime="python", session_id=str(uuid.uuid4())) as sandbox:
    async for _ in sandbox.execute(code="open('/workspace/data.txt','w').write('hello')"):
        pass
    async for event in sandbox.execute(code="print(open('/workspace/data.txt').read())"):
        if event["type"] == "stdout":
            print(event["text"])  # hello
  • Without session_id, a random UUID is assigned automatically.
  • File I/O is only permitted inside /workspace when a session is active.
  • Network remains blocked in all cases.

Agent patterns

Generate → run → fix loop

async def agent_loop(noa, code):
    for attempt in range(3):
        stderr_lines = []
        async for event in noa.execute(language="python", code=code, timeout_ms=15000):
            if event["type"] == "stderr":
                stderr_lines.append(event["text"])
            elif event["type"] == "done":
                return code
            elif event["type"] == "error":
                code = await your_llm_fix(code, stderr_lines)
                break
    raise RuntimeError("agent failed after retries")

JSON contract

Agents should emit one JSON document on stdout for ValidJsonRule to pass:

code = """
import json
result = {"answer": 42, "confidence": 0.99}
print(json.dumps(result))
"""

Parallel jobs

import asyncio

async with Noa() as noa:
    traces = await asyncio.gather(
        noa.execute(language="python", code='print("job 1")'),
        noa.execute(language="python", code='print("job 2")'),
        noa.execute(language="python", code='print("job 3")'),
    )

Error handling

from krysta.exceptions import KrystaGatewayError, KrystaTimeoutError

try:
    async with Noa() as noa:
        trace = await noa.execute(language="python", code=code)
except ValueError as e:
    # missing code/code_path, or payload > 256 KB
    ...
except RuntimeError as e:
    # execute() called outside async with, or stream dropped before jobId
    ...
except KrystaTimeoutError:
    # SSE channel timed out — network level, not sandbox level — retry
    ...
except KrystaGatewayError as e:
    # gateway down, bad status, SSE failure
    ...

# sandbox timeout is NOT an exception — check the trace
if trace.timeout_hit:
    print("job killed by sandbox timeout enforcer")
Exception Cause
ValueError No code/code_path, or file > 256 KB
RuntimeError Client not in async with, or stream dropped before job ID assigned
KrystaGatewayError Gateway unreachable, non-202, non-JSON, SSE failure
KrystaTimeoutError HTTP/SSE transport timeout (distinct from timeout_hit)
KrystaSandboxError Sandbox-level failure from rule engine

Troubleshooting

Symptom Fix
KrystaGatewayError on submit Check network connectivity and gateway status
Empty stdout but done received Rare race on fast jobs — retry; SDK replays from Redis on reconnect
NoNetworkCallsRule FAIL Remove requests, urllib, fetch from agent code
NoFilesystemAccessRule FAIL Use spawn(session_id=...) and stay inside /workspace
ValidJsonRule FAIL Print exactly one JSON object on stdout
SSE timeout Increase timeout_ms; check Redis/broker health
Connection dropped before jobId Network blip during submit — retry execute()

PyPI

https://pypi.org/project/krysta/


License

MIT

Metadata

Release files for krysta 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for krysta 1.1.1
File Size Uploaded Provenance Actions
krysta-1.1.1.tar.gz 19.7 kB Without provenance Details for krysta-1.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for krysta 1.1.1
File Interpreter ABI Platform Actions
krysta-1.1.1-py3-none-any.whl Python 3 none any Details for krysta-1.1.1-py3-none-any.whl

Total release size: 38.0 kB

Release files / krysta-1.1.1.tar.gz

Download URL krysta-1.1.1.tar.gz
Size 19.7 kB
Tags Source
SHA-256 checksum
How to use checksums
e85265b5a9bbbcce28c3eec8f4ea36052294aa5ac5513c57b3070809c5d35cae
BLAKE2b-256 checksum
How to use checksums
310fbede999170bc4af2afd16821ac25926d79b362d19901fa4b8e4c9b4c321d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.4

Release files / krysta-1.1.1-py3-none-any.whl

Download URL krysta-1.1.1-py3-none-any.whl
Size 18.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
eb6b4ff11aa8f4291e768492ad326a712ea8cb9c9c4814e134d4a5fd65935248
BLAKE2b-256 checksum
How to use checksums
94be0935609fdca5747a42ada94ca902f923ca190ebe36f35bc81b37c1f6f120
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.12.4

Security for krysta 1.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page