YA Claw
Workspace-native single-node agent runtime and web service for the ya-mono workspace.
Scope
YA Claw packages a durable runtime shell around ya-agent-sdk with:
- one persistent workspace resolved through
WorkspaceProvider
- reusable agent profiles
- explicitly selected installable capability plugins through an SDK-owned manifest
- resumable sessions and runs
- in-process active handles and live transports over SQL-owned async task state
- session schedules for timed execution
- SQLite-first durable state with optional PostgreSQL
- local filesystem session continuity and exported state
- a bundled web shell for local and self-hosted use
- bridge adapters that connect external event sources to the YA Claw service
Current Direction
The target single-node shape runs as one web service.
Process memory owns active handles, live delivery transports, and best-effort scheduling coordination. Async-task state, completion intent, parent inbox/continuation targeting, and delivery disposition remain canonical relational state; only the SQL-backed post-run owner dispatches completion, and portable delivery completes only after canonical parent application.
SQLite is the default durable store.
PostgreSQL remains an optional storage backend for deployments that prefer an external relational database.
Layout
Key areas in this package:
.env.example — runtime environment example
spec/ — architecture and runtime design documents
tests/ — runtime tests
ya_claw/api/ — HTTP API surface
ya_claw/bridge/ — external bridge adapters and event handling
ya_claw/app.py and ya_claw/cli.py — application entrypoints
ya_claw/config.py — runtime configuration
Runtime Shape
The runtime shape is:
- one YA Claw web service
- one in-process runtime state manager
- one session scheduler
- one bridge subsystem for external channels
- one shared bearer token for HTTP access
- one SQLite database by default
- optional PostgreSQL
- one runtime data directory for sensitive session continuity
- one persistent workspace directory
- one bundled web shell
Runtime Architecture Notes
This section is the maintainer index for implementation details that affect code changes across YA Claw.
Model Price Updates
The FastAPI lifespan owns one pydantic_ai.prices.update_in_background() handle from
application startup through shutdown, including startup failure cleanup. It stays
alive across all sessions, runs, and subagents in that application process. Individual
SDK runtimes do not start or stop downloads.
The upstream worker downloads immediately and then hourly. Startup and requests never
wait for the download; failures retain existing prices, and early responses may still
be unpriced. Recorded usage snapshots are not automatically repriced. Each service
process owns its own updater; restarting the process triggers another download.
Standalone SDK hosts should likewise call this method at application startup and
stop() at shutdown. See the SDK guide.
Runtime Defaults
YA_CLAW_API_TOKEN is required before service startup.
/api/v1/claw/info exposes service build metadata from YA_CLAW_SERVICE_VERSION, YA_CLAW_SERVICE_COMMIT, YA_CLAW_SERVICE_BUILD, and YA_CLAW_SERVICE_IMAGE; Docker builds inject these values for UI display.
- SQLite is the default durable store at
~/.ya-claw/ya_claw.sqlite3; file-backed SQLite engines use WAL and a 30-second busy timeout for the runtime's concurrent readers and writers.
YA_CLAW_DATA_DIR defaults to ~/.ya-claw/data.
YA_CLAW_WORKSPACE_DIR defaults to ~/.ya-claw/data/workspace.
- Browser workspace downloads are capped at 100 MiB by default; configure
YA_CLAW_WORKSPACE_DOWNLOAD_MAX_BYTES to change the enforced per-file limit. The server enforces the cap both before and during streaming.
GET /api/v1/sessions/{session_id}/workspace/files uses stable case-insensitive name ordering. Send limit, then continue with the opaque next_cursor while has_more is true; the name-key cursor prevents inserts or deletes before the cursor from shifting later pages. offset, next_offset, and the truncated alias remain available for backwards compatibility, but new clients should use cursor/next_cursor.
- The default Docker workspace image is
ghcr.io/wh1isper/ya-claw-workspace:latest.
- Session metadata lives in the database; committed continuity blobs live in the local run store.
Implementation Conventions
- Runtime code is organized around
ya_claw/api/, ya_claw/controller/, and ya_claw/orm/.
- Foundational execution modules live under
ya_claw/execution/.
- Workspace provider modules live under
ya_claw/workspace/.
- Internal data objects use Pydantic
BaseModel.
- Code prefers explicit typing and
isinstance checks.
- The session API is the high-level surface; the run API is the low-level surface.
- SQLite tests use the session-scoped
initialize_sqlite_database fixture, which copies a schema-only template into each isolated database; avoid per-test Base.metadata.create_all calls.
Session and Run Persistence
- Committed continuity blobs live in
run-store/{run_id}/state.json and run-store/{run_id}/message.json.
message.json stores the compacted replay list of AGUI-aligned events as a top-level JSON array.
state.json stores the bounded latest cumulative usage/cost snapshot. Claw normalizes SDK snapshots to the outer run ID, accumulates deferred-tool continuation segments, and indexes the bounded snapshot in internal run metadata. Run detail may fall back through state and replay for legacy or active runs; paginated summaries never scan full state blobs.
- Input payloads use
input_parts; run records preserve input_parts as original JSON-compatible payloads for replay and UI reconstruction.
- Successful run records store final
output_text directly in the database.
- Session GET exposes paginated runs with optional raw
input_parts and compacted message replay lists, returns optional top-level committed state/message from head_success_run_id, and derives session status from the latest run.
- Session turns API returns successful completed turns with raw
input_parts and output_text.
- Run GET returns
session + run + optional state + optional message.
- Run trace API returns compact tool-call/tool-response projections from
message.json.
- Rerun can explicitly target failed or interrupted runs through
restore_from_run_id.
- JSON run/session create routes return JSON consistently; foreground SSE creation uses
POST /api/v1/runs:stream, POST /api/v1/sessions:stream, and POST /api/v1/sessions/{session_id}/runs:stream.
Execution Coordination
- Active handles, live events, schedule dispatch, and bridge transports stay in the runtime process; relational rows remain the authority for runs, async tasks, input, and completion delivery.
- Built-in run orchestration lives in
ya_claw/execution/coordinator.py; it retains SQL scheduling, workspace, HITL, memory, and delivery ownership while composing the SDK AgentExecutionHarness for each native segment.
- New ordinary runs and new child spawns resolve model/runtime behavior from the selected execution profile. Existing or resumed async-child executions restore the exact immutable descriptor persisted with their SQL execution record; profile drift, reseeding, or route deletion cannot redefine them.
YA_CLAW_DEFAULT_PROFILE defaults to default.
YA_CLAW_CAPABILITY_PLUGIN_MANIFEST optionally names one strict SDK plugin manifest;
omission means no external plugins, while an explicit missing or invalid file is fatal.
- Runtime instance heartbeat lives in
runtime_instances.
- Run records carry claim ownership through
claimed_by and claimed_at.
- The built-in
session toolset lets agents inspect their current session through internal HTTP client tools list_session_turns and get_run_trace; session ID and bearer token stay inside the client resource.
Workspace Providers and Docker Runtime
LocalWorkspaceProvider uses LocalFileOperator plus policy-driven LocalShell over the real workspace path. Claw passes resolved shell sandbox policy for local sandbox execution; raw host shell is controlled by explicit policy.
DockerWorkspaceProvider uses Docker mounts through SandboxEnvironment; file operations map the service-visible workspace path to /workspace, and Docker shell uses /workspace. Managed temporary storage lives at a hidden .tmp/ya-agent-<id> path below that shared workspace mount, including for reused containers; each owned instance contains a self-ignoring .gitignore, and no per-run bind mount is required.
- Docker shell execution requires a Docker CLI on the service runtime
PATH plus Docker Engine API access. The official Dockerfile.ya-claw image bundles the CLI; custom images and host installs must provide it, and mounting docker.sock alone is insufficient.
YA_CLAW_WORKSPACE_PROVIDER_DOCKER_HOST_WORKSPACE_DIR provides the Docker daemon-visible host mount path when the YA Claw service itself runs in Docker.
- Docker workspace containers receive UID/GID envs (
YA_CLAW_WORKSPACE_UID, YA_CLAW_WORKSPACE_GID, YA_CLAW_HOST_UID, YA_CLAW_HOST_GID) from the service process by default or from YA_CLAW_WORKSPACE_PROVIDER_DOCKER_UID/GID.
Dockerfile.ya-claw can drop service execution privileges through YA_CLAW_RUN_UID and YA_CLAW_RUN_GID.
- The official workspace image defaults to UID/GID 1000 through build args.
Bridge Runtime
- Bridge adapter types are enumerated through
BridgeAdapterType; the built-in adapters are github and lark.
- Bridge deployment dispatch uses
BridgeDispatchMode (embedded, manual) and stays separate from run execution dispatch (queue, async, stream).
embedded is the default bridge dispatch mode and runs adapter tasks under BridgeSupervisor in the same HTTP server lifespan as ExecutionSupervisor.
manual starts the HTTP server with bridge dispatch managed outside the server lifespan.
- GitHub bridge ingress polls every notification reason for an ordinary account with a classic PAT, routes Issue/PR subjects, and applies
YA_CLAW_BRIDGE_GITHUB_ALLOWED_SENDERS with exact case-insensitive logins or *.
- GitHub Issue/PR resources map one-to-one to durable sessions and inherit the configured default workspace. Every triggering comment or new subject body must explicitly mention the bridge account, including follow-ups; neither
* nor notification reason bypasses this rule. The bridge resolves actual comments (including delayed explicit mentions), applies the sender allowlist, and deduplicates by comment ID/version; subject-only inputs retain versioned notification IDs. Repeated mentions reuse the resource's persisted session across run completion and service restart.
- After durable comment ingestion, the bridge adds an
eyes reaction. Pending reactions survive restart and retry without resubmitting the task; no immediate acknowledgement reply is requested from the model.
- Lark bridge event allowlist comes from
YA_CLAW_BRIDGE_LARK_EVENT_TYPES; defaults cover im.chat.member.bot.added_v1, im.chat.member.user.added_v1, im.message.receive_v1, and drive.notice.comment_add_v1.
- Lark message events map
(adapter, tenant_key, chat_id) one-to-one to a session.
- Other accepted Lark events use
chat_id when present and fall back to stable event or Drive conversation keys.
- Each accepted inbound event creates a bridge-triggered run after event/message dedupe.
- GitHub replies/actions are performed by the agent from the workspace with bundled
gh; YA_CLAW_BRIDGE_GITHUB_TOKEN is exposed there as GH_TOKEN.
- Lark bridge replies/actions are performed by the agent from the workspace with
lark-cli.
- Workspace environments receive
GH_TOKEN from GitHub bridge settings and LARK_APP_ID / LARK_APP_SECRET from process env or Lark bridge app settings.
Session Memory
- Session memory is workspace-native.
- Paired internal
session_type="memory" sessions run background extract/summary jobs with trigger type memory.
- Memory jobs share the source workspace sandbox and use the same profile tool surface as the primary agent.
- Memory content lives in workspace files:
memory/MEMORY.md, memory/CHANGELOG.md, and memory/YYYYMMDD-event.md files with YAML frontmatter (name, description).
memory/MEMORY.md is a compact durable brief for stable facts loaded by the main agent. Detailed chronology, file catalogs, and event lists belong in event files and memory/CHANGELOG.md.
- Memory extract and summary agents use fixed XML-style prompts from
ya_claw/memory/extract_prompt.py and ya_claw/memory/summary_prompt.py.
- Primary conversation runs load workspace guidance from
AGENTS.md and inject memory in the system prompt via WorkspaceMemoryStore, loading memory/MEMORY.md plus event file frontmatter as separate XML-style blocks.
memory-context is registered in injected_context_tags, so SDK trim-mode handoff removes historical memory context from prompt history.
- Memory orchestration state lives in
session_memory_states.
- Session list/detail responses expose
memory_state.
- Manual endpoints are
memory:extract and memory:summarize.
- File browsing should use workspace filetree APIs.
Installation
Recommended standalone install with uv:
uv tool install 'ya-claw[rs]'
ya-clawd version
[rs] passes ya-agent-sdk[all,rs] into the runtime and installs the native Rust filesystem search binding. The equivalent extra-dependency form is:
uv tool install ya-claw --with ya-ripgrep-core
ya-ripgrep-core is a library dependency, so --with is the matching uv form; --with-executables-from applies to companion packages that also expose CLI executables.
Pip can install the same runtime shape:
pip install 'ya-claw[rs]'
Capability Plugins
Install each trusted plugin distribution into the YA Claw service's Python environment,
not only into a Docker workspace container. For an isolated uv tool installation:
uv tool install 'ya-claw[rs]' --with acme-agent-plugin
Then point YA Claw at the SDK's strict manifest:
YA_CLAW_CAPABILITY_PLUGIN_MANIFEST=/etc/ya-claw/plugins.toml
schema_version = 1
entry_points = ["acme.search"]
[[capabilities]]
name = "acme.search"
arguments = { result_limit = 10 }
entry_points explicitly selects installed Python types for the process catalog.
capabilities appends ordered grants to every admitted root profile spec before its
immutable descriptor is fingerprinted and persisted. Installation alone grants nothing,
and YA Claw never ambiently loads all installed entry points.
The manifest path is optional; omission produces an empty external catalog. An explicit
missing path, invalid TOML, unknown field, unsupported version, missing or duplicate
entry point, import failure, grant argument signature mismatch, or catalog collision
stops startup. Manifest arguments are durable non-secret configuration; secret-like
keys are rejected recursively. This name-based guard cannot detect a secret stored under
a neutral key. Provide live credentials and authority through typed runtime dependencies
or host APIs instead.
Root manifest grants do not enter named children or self forks. A selected type may be
used by a child only when that child's native AgentSpec.capabilities explicitly grants
it. Before a root descriptor is fingerprinted or persisted, YA Claw performs native
static-plan construction with ClawAgentContext, the selected custom types, and fresh
base host capabilities; plugin factory values and combined ordering therefore fail at
admission rather than after a run is queued. Runtime entry still validates dynamic
Environment and resource contributions.
YA Claw resolves the file once before application startup and uses the same catalog
snapshot for profile admission, async children, retained plans, recovery, memory runs,
and runtime construction. Restart the service after changing the file or distribution.
The official image does not include third-party plugins. Build a derived service image
that installs the distribution into /opt/venv, mount the manifest read-only, and set
its in-container path: