Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

docs(artifacts): update README to reflect new producer API, events, and regenerate RPC

Steven Enamakel4a535ad44fee
diff --git a/crates/openhuman-core/src/agent/artifacts/README.md b/crates/openhuman-core/src/agent/artifacts/README.md
index 4c7a7b0d58..9009bc3541 100644
--- a/crates/openhuman-core/src/agent/artifacts/README.md
+++ b/crates/openhuman-core/src/agent/artifacts/README.md
@@ -1,87 +1,123 @@
# artifacts
-Metadata domain for agent-generated artifacts (presentations, documents, images, and other files the agent produces). It owns the on-disk layout under `<workspace>/artifacts/`, persists per-artifact `meta.json` records, and exposes read/delete RPC controllers in the `ai` namespace. It does **not** generate artifact content itself — it is a thin, sandboxed metadata store + listing/retrieval/deletion surface over a workspace subdirectory.
-
-## Responsibilities
-
-- Define artifact metadata types (`ArtifactMeta`, `ArtifactKind`, `ArtifactStatus`) with case-insensitive string parsing and lowercase serde.
-- Persist artifact metadata to `<workspace>/artifacts/<id>/meta.json` (`save_artifact_meta`).
-- List artifacts with pagination, sorted by `created_at` descending, skipping corrupt/unreadable `meta.json` entries (`list_artifacts`).
-- Retrieve a single artifact by ID, returning metadata plus a computed `absolute_path` (`get_artifact` / `ai_get_artifact`).
-- Delete an artifact directory and all its contents (`delete_artifact`).
-- Enforce path-traversal sandboxing on artifact IDs and resolved paths so callers cannot escape the artifacts root.
-- Expose `ai.list_artifacts`, `ai.get_artifact`, `ai.delete_artifact` RPC controllers.
+Metadata store and lifecycle for agent-generated files (presentations,
+documents, images) under `<workspace_dir>/artifacts/`. Producer tools
+(`tools/impl/presentation`, `tools/impl/document`) call this module to
+reserve an artifact directory, write their bytes, and flip the record to
+`Ready` or `Failed`; the module publishes the matching bus events, persists
+`meta.json` / `args.json`, and exposes `ai.*` RPC controllers plus three
+agent tools for listing, fetching, deleting, and regenerating. It never
+renders artifact content itself.
## Key files
| File | Role |
| --- | --- |
-| `crates/openhuman-core/src/agent/artifacts/mod.rs` | Export-only: `mod` decls + re-exports of `ArtifactKind`/`ArtifactMeta`/`ArtifactStatus` and the controller-schema/registry pair. |
-| `crates/openhuman-core/src/agent/artifacts/types.rs` | Serde domain types: `ArtifactKind` (presentation/document/image/other), `ArtifactStatus` (pending/ready/failed), `ArtifactMeta`. Each enum has `as_str`/`parse` (case-insensitive, fall back to `Other`/`Pending`). |
-| `crates/openhuman-core/src/agent/artifacts/ops.rs` | Business logic returning `RpcOutcome<Value>`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`. Validates non-empty IDs, computes/guards `absolute_path`. `DEFAULT_LIMIT=50`, `MAX_LIMIT=200`. |
-| `crates/openhuman-core/src/agent/artifacts/store.rs` | Persistence over `tokio::fs`: `artifacts_root`, `save_artifact_meta`, `list_artifacts`, `get_artifact`, `delete_artifact`, plus `validate_artifact_id` / `assert_within_root` sandboxing helpers. |
-| `crates/openhuman-core/src/agent/artifacts/schemas.rs` | Controller schemas (`all_controller_schemas`), registry (`all_registered_controllers`), and `handle_*` fns delegating to `ops.rs`; param-parsing helpers (`read_required`, `read_optional_u64`, `type_name`). |
-| `crates/openhuman-core/src/agent/artifacts/tools.rs` | Agent tools `ArtifactListTool`, `ArtifactGetTool`, `ArtifactDeleteTool` — thin shims over `ops.rs` that unwrap the `RpcOutcome` and return the inner JSON as `ToolResult`. |
-| `crates/openhuman-core/src/agent/artifacts/ops_tests.rs` | Sibling test suite for `ops.rs` (via `#[path]`). |
-| `crates/openhuman-core/src/agent/artifacts/store_tests.rs` | Sibling test suite for `store.rs` (via `#[path]`). |
+| `mod.rs` | `mod` decls and re-exports: `ArtifactKind` / `ArtifactMeta` / `ArtifactStatus`, the producer API (`create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes`), and `all_artifacts_controller_schemas` / `all_artifacts_registered_controllers`. |
+| `types.rs` | `ArtifactKind` (presentation/document/image/other), `ArtifactStatus` (pending/ready/failed), `ArtifactMeta`. Enums serialize lowercase; `parse` is case-insensitive and never errors (unknown kind → `Other`, unknown status → `Pending`). `ArtifactMeta.error` and `.thread_id` are optional, `skip_serializing_if` none. |
+| `store.rs` | All filesystem I/O over `tokio::fs`: `artifacts_root`, `create_artifact`, `finalize_artifact`, `fail_artifact`, `read_artifact_bytes` (`pub`); `save_artifact_meta`, `save_artifact_args`, `read_artifact_args`, `list_artifacts`, `get_artifact`, `delete_artifact` (`pub(crate)`); `validate_artifact_id` / `assert_within_root` sandboxing; the `REGENERATE_TARGET_ID` task-local; `sanitize_filename_stem`. |
+| `ops.rs` | RPC business logic returning `RpcOutcome<Value>`: `ai_list_artifacts`, `ai_get_artifact`, `ai_delete_artifact`, `ai_regenerate`. `DEFAULT_LIMIT = 50`, `MAX_LIMIT = 200`. The regenerate path that re-runs `PresentationTool` is `#[cfg(feature = "documents")]`; without the feature `ai_regenerate` returns an error. |
+| `schemas.rs` | `ControllerSchema`s and `handle_*` fns for the four `ai.*` controllers; param helpers `read_required`, `read_optional_u64`, `read_optional_string` (whitespace-only → absent), `type_name`. |
+| `tools.rs` | `ArtifactListTool`, `ArtifactGetTool`, `ArtifactDeleteTool` — shims over `ops` that unwrap the `RpcOutcome` and return `outcome.value` as the `ToolResult` string. |
+| `*_tests.rs` | Sibling test files for each of the above (`#[path]`). |
## Public surface
-- `ArtifactKind`, `ArtifactMeta`, `ArtifactStatus` (re-exported from `types`).
-- `all_artifacts_controller_schemas` / `all_artifacts_registered_controllers` (re-exported from `schemas`, wired into the core registry).
-- `ops::{ai_list_artifacts, ai_get_artifact, ai_delete_artifact}` (called by the schema handlers; referenced by fully-qualified path).
-- `store::*` functions are `pub(crate)` — usable inside the crate (e.g. a future producer calling `save_artifact_meta`).
+- `ArtifactKind`, `ArtifactMeta`, `ArtifactStatus`.
+- Producer API, `pub` and re-exported from `mod.rs`:
+ - `create_artifact(workspace_dir, kind, title, extension) -> (ArtifactMeta, PathBuf)` — mints a UUID (or reuses `REGENERATE_TARGET_ID`), creates `<root>/<id>/`, writes a `Pending` `meta.json`, publishes `ArtifactPending`, and returns the absolute path the producer should write to (`<id>/<sanitized-title>.<ext>`).
+ - `finalize_artifact(workspace_dir, id, size_bytes)` — `Pending → Ready`, publishes `ArtifactReady`; no-op if already `Ready` with the same size.
+ - `fail_artifact(workspace_dir, id, reason)` — `→ Failed`, stores `meta.error`, publishes `ArtifactFailed`. Logs only `reason.len()`, not the reason.
+ - `read_artifact_bytes(workspace_dir, id)` — the one sanctioned id → bytes path; refuses non-`Ready` records.
+- `store::save_artifact_args` is `pub(crate)` and called directly by the producers right after `create_artifact` (best-effort; failure only forfeits regeneration).
+- `all_artifacts_controller_schemas` / `all_artifacts_registered_controllers`.
## RPC / controllers
-All in the `ai` namespace:
+Namespace `ai`. Registered in `core/all.rs` under `DomainGroup::Agent` via
+`all_artifacts_registered_controllers()`; `all_artifacts_controller_schemas()`
+is used by `schemas_tests.rs` to check every function has a schema and a
+handler. Handlers load config through `config::rpc::load_config_with_timeout()`
+and trim string params.
| Method | Inputs | Output |
| --- | --- | --- |
-| `ai.list_artifacts` | `offset?: u64` (default 0), `limit?: u64` (default 50, cap 200) | `{ artifacts: ArtifactMeta[], total, offset, limit }` |
-| `ai.get_artifact` | `artifact_id: string` (required) | flat `ArtifactMeta` fields + `absolute_path` |
-| `ai.delete_artifact` | `artifact_id: string` (required) | `{ artifact_id, deleted: bool }` |
-
-`get_artifact` output is intentionally flat (no opaque `artifact` wrapper). Handlers load config via `config::rpc::load_config_with_timeout()` and trim the `artifact_id`.
+| `ai.list_artifacts` | `offset?: u64` (default 0), `limit?: u64` (default 50, cap 200), `thread_id?: string` | `{ artifacts: ArtifactMeta[], total, offset, limit }` — `total` is the count after the `thread_id` filter |
+| `ai.get_artifact` | `artifact_id: string` | flat `ArtifactMeta` fields + `absolute_path` (root joined with `meta.path`) |
+| `ai.delete_artifact` | `artifact_id: string` | `{ artifact_id, deleted: true }` |
+| `ai.regenerate` | `artifact_id`, `thread_id`, `client_id` (all required) | `{ artifact_id, regenerated: true, is_error }` |
+
+`ai.regenerate` only accepts `kind == presentation`, reloads `args.json`,
+and re-runs `PresentationTool` inside `REGENERATE_TARGET_ID.scope(id, ..)`
+and `APPROVAL_CHAT_CONTEXT.scope({thread_id, client_id}, ..)` so the same id
+is reused and the Pending/Ready/Failed events route back to the originating
+chat. The RPC result is an ack; the card state comes from the socket events.
+When `thread_id` is given to `list_artifacts`, legacy records with no
+`thread_id` are excluded.
## Agent tools
-`tools.rs` exposes three LLM-callable wrappers over `ops.rs`, re-exported crate-wide through `crate::tools::mod`'s `pub use crate::agent::artifacts::tools::*`:
+Constructed in `tools/ops.rs` (unconditionally) and re-exported through
+`tools/mod.rs` (`pub use crate::agent::artifacts::tools::*`).
| Tool | Permission | Behavior |
| --- | --- | --- |
-| `artifact_list` | default (read-only) | Lists artifacts newest-first via `ops::ai_list_artifacts`; supports `offset`/`limit`. |
-| `artifact_get` | default (read-only) | Fetches one artifact's metadata + `absolute_path` via `ops::ai_get_artifact`. |
-| `artifact_delete` | `Dangerous` | Irreversibly deletes an artifact directory via `ops::ai_delete_artifact`. Ships **default-OFF**; must be opted in through the tool toggle map (`TOOL_ID_TO_RUST_NAMES` in `crate::tools::user_filter`). |
+| `artifact_list` | default | `ops::ai_list_artifacts(.., thread_id = None)` — always the whole workspace; the per-thread filter is RPC-only. `offset` / `limit` args. Concurrency-safe. |
+| `artifact_get` | default | `ops::ai_get_artifact`; `artifact_id` required. Concurrency-safe. |
+| `artifact_delete` | `Dangerous` | `ops::ai_delete_artifact`. Default-OFF: listed as its own `ToolFamily` (`id: "artifact_delete"`, `default_enabled: false`) in `TOOL_FAMILIES` in `tools/user_filter.rs`; `artifact_list` / `artifact_get` are deliberately not in that map so they cannot be toggled off. |
-Each tool is a thin shim: it validates/reads its args, calls the matching `ops` function, and serializes the returned `RpcOutcome.value` as the tool result. `artifact_list` deliberately lists the full workspace (no per-chat filtering) so agent orchestration sees everything it has produced; the per-chat filter is an RPC-only concern.
+There is no regenerate tool; regeneration is RPC-only.
## Events
-None. No `bus.rs`; the module publishes/subscribes to no `DomainEvent`s.
+Published by `store.rs` on `crate::core::bus::BUS` (no `bus.rs`; this module
+subscribes to nothing):
-## Persistence
+- `DomainEvent::ArtifactPending` — from `create_artifact`.
+- `DomainEvent::ArtifactReady` — from `finalize_artifact` on a real transition.
+- `DomainEvent::ArtifactFailed` — from `fail_artifact`.
-- Root: `<workspace_dir>/artifacts/` (auto-created via `create_dir_all` in `artifacts_root`).
-- Per artifact: `<workspace>/artifacts/<id>/meta.json` (pretty-printed `ArtifactMeta`).
-- `workspace_dir` is read from `Config` (`config.workspace_dir`).
-- No database; entirely filesystem-backed via `tokio::fs`. Listing scans subdirectories and skips entries whose `meta.json` is missing or corrupt (logged at `warn`).
+All three carry `thread_id` / `client_id` read from the
+`security::approval::APPROVAL_CHAT_CONTEXT` task-local; outside a chat turn
+(CLI, cron, sub-agents) both are `None` and the
+`web_chat::artifact_surface` subscriber (`web_chat/event_bus.rs`) drops the
+event.
-## Dependencies
+## Persistence
-- `crate::config::Config` / `config::rpc` — source of `workspace_dir` and config loading in handlers.
-- `crate::core::all::{ControllerFuture, RegisteredController}` and `crate::core::{ControllerSchema, FieldSchema, TypeSchema}` — controller registry + schema types.
-- `crate::rpc::RpcOutcome` — ops return type / handler JSON conversion.
-- External crates: `tokio::fs`, `serde`/`serde_json`, `chrono` (timestamps).
+- Root `<workspace_dir>/artifacts/`, created on demand by `artifacts_root`.
+- `<root>/<id>/meta.json` — pretty-printed `ArtifactMeta`.
+- `<root>/<id>/args.json` — verbatim producer-tool args, written by the
+ producer via `save_artifact_args`, read by `ai_regenerate`. Absent for
+ artifacts created before it existed, which makes them non-regenerable.
+- `<root>/<id>/<stem>.<ext>` — the artifact bytes; `meta.path` is the
+ `<id>/<filename>` relative path.
+- `list_artifacts` scans root subdirectories, sorts by `created_at`
+ descending, applies the `thread_id` filter before pagination, and skips
+ entries whose `meta.json` is missing or corrupt (`warn!`, not an error).
+- Regeneration reuses the existing directory and preserves the original
+ `created_at` so the artifact keeps its position in the sorted list.
## Used by
-- `crates/openhuman-core/src/core/all.rs` — registered in the global controller registry via `all_artifacts_registered_controllers()`. `all_artifacts_controller_schemas()` is exported alongside for domain-local schema-coverage tests; the crate-wide `/schema` list (`core::all::all_controller_schemas`) is derived from registered controllers, not called separately per domain. No other in-crate consumer of `save_artifact_meta` was found, so artifact creation is not yet wired from a producer domain.
+- `tools/impl/presentation/mod.rs` and `tools/impl/document/mod.rs`
+ (`documents` feature; in `scripts/ci/product-features.txt`, not in Cargo
+ defaults) — the only producers. Presentation also uses
+ `read_artifact_bytes` for its image pipeline.
+- `web_chat/event_bus.rs` — bridges the three events to web-channel
+ `artifact_*` events.
+- `core/all.rs` — controller registry.
## Notes / gotchas
-- **Path-traversal hardening is layered**: `validate_artifact_id` rejects empty/`.`/`..`, `/` or `\`, absolute paths, and Windows drive-letter paths; `assert_within_root` re-checks the resolved path stays under the artifacts root before any write/read/delete; `ai_get_artifact` independently re-validates that `meta.path` does not escape the root when computing `absolute_path` (defends against a corrupt/adversarial stored `meta.path`).
-- `list_artifacts` is **lossy by design** — bad `meta.json` files are skipped (warned), not surfaced as errors, so a single corrupt artifact never breaks the whole listing.
-- Enum `parse` never errors: unknown `kind` → `Other`, unknown `status` → `Pending`.
-- `store.rs` carries a dead-code `_assert_status_used` helper to keep `ArtifactStatus` referenced outside tests.
-- Verbose `[artifacts]` `log::debug!`/`warn!` prefixes throughout, per repo logging conventions.
+- Path-traversal hardening is layered: `validate_artifact_id` rejects
+ empty, `.`, `..`, anything containing `/` or `\`, absolute paths, and
+ `X:` drive-letter prefixes; `assert_within_root` re-checks every resolved
+ path; `ai_get_artifact` and `read_artifact_bytes` additionally re-check
+ that a stored `meta.path` does not escape the root.
+- `create_artifact` rejects empty titles/extensions and extensions
+ containing `/`, `\`, or `.`. Filename stems are lowercased ASCII
+ `[a-z0-9_-]`, capped at 80 chars, fallback `artifact`.
+- `store.rs` keeps a dead-code `_assert_status_used` helper so
+ `ArtifactStatus` is referenced outside tests.
+- Log prefix is `[artifacts]` (`[tool][artifacts]` in `tools.rs`).