
artifactkit
io.github.lefthookhq/artifactkit
Publish, version and share HTML artifacts across agents. Open source, hosted or on your domain.
Documentation
Your artifacts. Bring your own AI. Give the pages you make with AI a home on your own domain. Connect an agent through MCP, HTTP, or the CLI to publish HTML, then let another agent update the same artifact. You control the share link, the stored versions, and the policy that serves the page.
Left Hook runs this shape in production for its staff. artifactkit is the same idea, rebuilt as a
hexagonal core you can extend: swap the store, the signer, the event sink, or the comment backend
without touching the domain.
npm install
npm test # 65 tests: domain, policies, MCP surface, http, and a conformance suite
npm run demo # http://localhost:8788 — publish, share, serve, no cloud account
What it guarantees
- The artifact cannot talk to the network. It is served with
Content-Security-Policy: … connect-src 'none'; sandbox allow-scripts …and an opaque origin, so no fetch, no WebSocket, no cookies, no storage of a real origin. The validator refuses a page that would need any of it, and says why in words an agent can act on. - A page is one file. CSS, JS, images, everything inline; libraries only from an allowlist of CDNs. Under 512 KB by default.
- Versions are append-only. Every update is a new version, and an update carries the version it was based on. A stale write is refused with the current version — never a silent overwrite.
- A share link is a capability, not a login. 43 random characters, revocable, rotatable, and it serves the current version without cookies.
- Staff views are short-lived. An HMAC view token scoped to one artifact id, valid for minutes.
GET /can be a lost-and-found page. Opt in withhome: { signInUrl }: it tells a reader what this host is, how a share link works, and where to sign in. Off by default — seedocs/home.md.
Layout
src/
domain/ pure: no I/O, no framework, no imports from anywhere else in src/
artifact/ the Artifact aggregate: versions, ownership, the update guard
anchor/ how a comment finds its block again after a re-publish
comment/ the CommentThread aggregate
policy/ page contract + CSP, built from the same limits
ports/ the interfaces the core needs (and StoreCapabilities)
application/ use cases: publish, update, get, list, share, unshare, delete, serve, comments
adapters/ implementations: memory, fs, node runtime (clock, ids, HMAC, lock)
http/ driving adapter: a framework-free fetch handler
tests/ domain, policy, anchor, comments, http + a store conformance suite
docs/ architecture, ADRs
Dependencies point inward. domain/ imports nothing but itself; application/ imports domain/
and ports/; only adapters/ and http/ know that a filesystem or node:crypto exists. If you
can see an import crossing that boundary the other way, it is a bug.
Ports
| Port | What the core needs | Reference implementations |
|---|---|---|
ArtifactStore | metadata + share index, with capabilities | memory, fs, Cloudflare KV, Postgres, Supabase |
GrantStore, DocStore | grants and the db capability's documents (ADR 0007; native stores) | memory, fs, KV (docs, state-backed), Postgres, Supabase |
BodyStore | version bodies, keyed <id>/<version> | memory, fs, KV, Postgres, Supabase |
CommentStore | threads and comments | memory, fs, KV, Postgres, Supabase, HTTP (another deployment's REST API) |
Clock, IdSource | time and ids, injectable | node runtime |
TokenSigner | sign/verify a view token | HMAC (swap for KMS) |
EventSink | artifact.published / updated / shared / unshared | console, collecting (tests) |
Lock | optional per-key serialisation | in-process |
On Supabase without a direct connection, artifactkit/adapters/supabase does the same through service-role RPCs (see docs/supabase.md). Postgres is the one to reach for when more than one writer exists, or when comments need to join to
your users: createPostgresAdapter({ query }) takes any pool-like client, carries its own
SCHEMA_SQL, and answers atomicConditionalWrite: true, transactionalBodies: true. The conformance
suite runs against it when ARTIFACTKIT_PG_URL is set:
docker run -d --name artifactkit-pg -e POSTGRES_PASSWORD=artifactkit -p 55444:5432 postgres:16-alpine
ARTIFACTKIT_PG_URL=postgres://postgres:artifactkit@127.0.0.1:55444/postgres npm test
Comments when another app owns the database
artifactkit/adapters/http is a CommentStore that keeps threads in a deployment which already
owns Postgres, over that deployment's documented REST routes. Use it when the process you are
wiring has no database of its own (an MCP server, a CLI, a worker) but the app next to it does:
import { createHttpCommentStore } from '@artifactkitdev/core/adapters/http';
const comments = createHttpCommentStore({
baseUrl: 'https://artifacts.example.com',
headers: { authorization: `Bearer ${process.env.ARTIFACTKIT_TOKEN}` },
});
It speaks exactly four routes: GET /api/artifacts/:id/comments (optionally ?anchors=[…]),
POST /api/artifacts/:id/comments, POST /api/comments/:threadId/replies and
PATCH /api/comments/:threadId. The list route answers ThreadView objects; the adapter unwraps
thread and returns ThreadState[]. Headers are the only credentials it sends — it never invents
a token — and any non-2xx throws with the status and the server's text, so a bad token never looks
like "no comments".
putThread is a reproduction, not an upsert: an unknown thread is opened with its first comment,
missing comments are posted as replies in order, and a status change is a PATCH. It is not
atomic: the core calls putThread with the full new state, so two concurrent writers can both
append the same reply and the app will store both. The owning app assigns thread ids and comment
authors from the authenticated principal, not from the local ThreadState. See
docs/http-comment-store.md for the full caveats.
Behavioural differences are declared
Backends are not equivalent, so each ArtifactStore states what it can promise:
export interface StoreCapabilities {
readonly atomicConditionalWrite: boolean; // can it refuse a stale write atomically?
readonly consistentListings: boolean; // is list() immediately consistent?
readonly transactionalBodies: boolean; // are bodies all-or-nothing with metadata?
}
The reference fs adapter answers false to the first, so updateArtifact serialises through the
Lock port while the memory adapter relies on compare-and-set. Both pass the same conformance
suite; both are honest about what changes. See docs/adr/0002-store-capabilities.md.
Adding an adapter
- Implement the ports. Declare capabilities truthfully.
- Copy
tests/conformance.test.ts's parameter list and add yours. If it fails, the adapter is not finished — do not add an exclusion. - If your backend cannot do compare-and-set, either provide
Lock(single instance) or document the last-writer-wins window in your adapter's docstring. Silence here is how data gets lost.
An adapter is ~100 lines. The Postgres one is the next thing on the list; the schema is in
docs/architecture.md.
Try it
demo.artifactkit.dev issues a token for one artifact, seven days, no account:
curl -X POST https://demo.artifactkit.dev/api/demo/token -H 'content-type: application/json' -d '{}'
curl -X POST https://demo.artifactkit.dev/api/demo/publish \
-H "authorization: Bearer $TOKEN" -H 'content-type: application/json' \
-d '{"title":"Hello","html":"<!doctype html><html><body><h1>Hi</h1></body></html>"}'
docs/demo.md is the abuse model behind those numbers, and how to attach MCP to the same worker.
Deploy
Canonical host: artifactkit.dev; artifactkit.io 301s to it. The reference deployment is a
Cloudflare Worker on KV — wrangler.jsonc, examples/worker.ts, examples/redirect-worker.ts.
npx wrangler kv namespace create ARTIFACTS # id → wrangler.jsonc
npx wrangler secret put VIEW_SECRET
npx wrangler deploy && npx wrangler deploy -c wrangler.redirect.jsonc
npx wrangler dev --local # or: try it with no account (needs .dev.vars)
KV has no compare-and-set and eventually consistent listings; the adapter says so, and
docs/hosting.md says what that means (one writer: fine; concurrent agents: use Postgres).
Artifact state
A published artifact cannot reach the network, so it cannot keep data anywhere by itself. artifactkit
gives it a small key-value store written by the viewer chrome on its behalf — the same shape as
window.storage, plus an optional compare-and-set:
await artifactkit.storage.set('quiz:state', JSON.stringify(state));
const row = await artifactkit.storage.get('quiz:state'); // { value, rev, updatedAt } | null
await artifactkit.storage.set('doc', next, { expectRev: row.rev }); // throws { code: 'conflict' }
Personal by default, { shared: true } for everyone who can see the artifact. 256 KB a value, 20 MB an
artifact. The page learns no URL and no credential: every call is a postMessage to the chrome, which
holds the session. Memory and Postgres do compare-and-set; Cloudflare KV refuses it rather than
pretending. See docs/state.md.
Capabilities
A page written for Claude's published-artifact runtime (claude.use('db'), claude.use('user'), …) runs here
unchanged for the capabilities that are served: user, db, artifact (alias self), comments,
permissions, downloads, assets (uploads served at /_blob/<id>), files (read-only project files as the viewer). A publisher declares them (capabilities: { db: {}, user: { scopes: ['profile'] } };
omit to keep, {} to clear, non-empty is the full set), access is graded view < interact < admin < owner,
and everything still travels one postMessage channel through the viewer chrome: the page learns no URL and no
credential. db has live snapshots, per-path rules and data/users/<id> private even from the owner; agents reach
the same documents through the artifact_data MCP tool and /api/artifacts/{id}/data. Anything not served
(room, sample, mcp, dictation) is refused at publish with the reason, never a silent null.
Every limit and every difference from Claude is stated in docs/capabilities.md;
the design is ADR 0007.
Activity
Every mutation is recorded with a global seq, and GET /api/artifacts/{id}/events?after=<seq> reads
from a cursor — long-polling when you pass wait. That is how a page, a session shelling in, or a
webhook sender follows an artifact without a websocket:
GET /api/artifacts/art_…/events?after=812&wait=25
→ { "events": [{ "seq": 813, "event": { "type": "artifact.state.changed", … } }], "cursor": 813 }
artifact.published / updated / shared / unshared, artifact.state.changed (never with the
value), and comments. Memory, filesystem and Postgres adapters; Postgres is the only one safe across
processes. See docs/activity.md.
Webhooks
Subscribe to events and get a signed POST per delivery — or point the same subscription at Svix and let them own retries and replay.
POST /api/webhooks { "url": "https://example.com/hooks", "kinds": ["artifact.version.published"] }
POST /api/webhooks/drain → { "delivered": 3, "retrying": 0, "deadLettered": 0 }
artifact.created/updated/deleted, version.published, share.created/revoked,
state.changed (never the value), comment.*. HMAC over ${timestamp}.${body} in
x-artifactkit-signature, retries with backoff, dead letters, and auto-disable after repeated
failures. Delivery is a port: createInProcessSender() by default,
createSvixSender() when a hosted sender fits better. See docs/webhooks.md.
Three surfaces
- MCP — seven tools, mountable in any MCP server (below).
- REST — the same use cases behind
/api/artifacts, documented by an OpenAPI 3.1 document at/openapi.jsonand rendered with Scalar at/docs.npm run openapiwritesdocs/openapi.json. - CLI —
npx --package=@artifactkitdev/core artifactkit publish ./q1.html --title "Q1 plan", plusupdate,list,get,edit,share,unshare,rm.--normalizewraps an HTML fragment into a complete document,--capabilities '{"db":{}}'declares the runtime a page uses.publish file.html --id art_…reads the current version and updates it. The CLI checks effective host limits and uses raw upload tickets when available;--inlineretains JSON transport. Point it anywhere withARTIFACTKIT_URL+ARTIFACTKIT_TOKEN. - Upload tickets — for a page too large to pass through an agent's context: the
artifact_upload_urlMCP tool (orPOST /api/uploads) returns a single-use, short-lived URL scoped to one artifact and one operation;curl -T page.htmlit and the page is published or updated with the same version guard and permission checks. See docs/capabilities.md.
MCP
Publish, list, version, and share artifacts from an MCP client. Open a private inline preview with comments and replies in an MCP Apps client, or use the review tools in a text client. Mount the tools on the official SDK or include them in an MCP server you already run. See the review tools and hosting guide.
registerArtifactTools(server, deps, { auth: delegatedAuth(), baseUrl: 'https://artifactkit.dev' });
Auth is optional and is a policy: anonymous (local), bearer (token → owner), delegated (the
host server already authenticated). Ownership is always the authenticated principal, never a
model-supplied argument. Details in docs/hosting.md.
Tracking
Events are already a port (EventSink), so analytics is an adapter, not an instrumentation pass:
posthogTelemetry, otelTelemetry (OTLP/HTTP logs) and fanout live in adapters/telemetry, with
telemetryEventSink mapping artifact.published, artifact.viewed and friends onto them. It sends
the event name, the actor, the artifact id, the version, the channel and a byte count — never the
HTML, the title, an IP, a user agent or anything a reader typed. docs/analytics.md
has the event contract and a PostHog-wired Worker you can deploy: examples/lead-magnet-worker.ts.
The public demo and the demand signal
docs/demo.md is the abuse model for a public instance: Turnstile at signup, one artifact per token,
five versions, 256 KB, seven-day TTL, a separate demo host, and a report queue. POST /api/interest
records "would you pay for hosted" votes from the landing page in site/index.html.
Collaboration and access policy
Optional and off unless wired. Deps.access takes an AccessStore and Deps.state the shared-state store; the
Supabase adapter provides both (apply SUPABASE_COLLABORATION_SCHEMA_SQL after the base schema). AccessSettings
carries a link role (viewer, commenter, contributor, editor, or null for email-only access), named email grants
with the same roles, verified-email commenting and optional lead capture. The pure policy is in
@artifactkitdev/core/domain/access and its use cases in application/access: accessFor grants commenting and
editing to verified identities only, editors may update HTML and shared state but never change settings, ownership
or delete, and the owner always has full access. levelFor maps the stored roles onto the capability levels (viewer
and commenter view, contributor interact, editor admin, plus an orthogonal comment permission; the link
role is capped at view for visitors without a verified email; ADR 0006), and
the capability service uses it whenever an artifact has settings. A link role above viewer is refused where the
deployment cannot identify visitors (wire a PrincipalDirectory or set Deps.verifiesVisitors). Hosts own identity verification, the viewer and every route
check; the built-in REST state and comment routes stay owner-only. See docs/collaboration.md.
Optional audience analytics (adapters/posthog, Deps.analytics)
Deps.analytics accepts an AnalyticsStore. Memory and Supabase adapters provide it; other
adapters can implement the port independently. Supabase deployments apply the exported
SUPABASE_ANALYTICS_SCHEMA_SQL after the base and collaboration schemas. No analytics are
collected unless the port is wired. The HTTP handler records successful audience HTML GETs,
excluding owner preview tokens, HEADs and errors. Signed guest claims may provide stable
visitId and opaque viewerKey; otherwise the handler uses a browser cookie and a new visit ID.
Duplicate visit IDs count once per artifact. Summaries return views, distinct viewers and live
comment counts including replies across versions. Metrics failures do not break page delivery.
These are estimated audience counts, without historical backfill or bot filtering. Hosts should explain cookie/account identity limitations, authorize summary access and own the analytics UI. The view table stores opaque identifiers, not raw emails or IPs; deletion cascades with the artifact.
Component comment bridge (browser/comments, browser/bridge)
Two comment-targeting paths coexist. The host-injected picker (comments: true) needs no artifact code. The
artifact-side installCommentBridge reports ephemeral element geometry (isCommentMessage, commentAnchorId,
bindAnchor for exact/rebound/orphan status) for hosts that draw their own picker. Its anchor type and guard are
exported as ComponentAnchor / isComponentAnchor because CommentAnchor / isCommentAnchor belong to the
picker protocol. See docs/component-comments.md.
Releasing
The npm package is @artifactkitdev/core; its executable remains artifactkit.
Changesets opens version PRs. Publication is a separate manual GitHub Actions workflow using npm
trusted publishing (OIDC), provenance, and Sean's approval through the npm-release environment.
main releases to latest; Changesets prereleases on next release to next.
npm run changeset # choose @artifactkitdev/core, bump and changelog note
npm run typecheck
npm test
npm run test:package # actual packed install, public exports/types and CLI
Sean has secured artifactkit.dev and the artifactkitdev npm organization. Publishing remains
disabled pending the approved first publication and trusted-publisher setup. See the release runbook and agent instructions.
No npm publishing token is stored in Actions, and merging a version PR does not publish.
Status
Working: domain, policies, use cases, memory + fs + Cloudflare KV + Postgres adapters, HTTP serving, REST API
with OpenAPI + Scalar docs, CLI, MCP tools with optional auth, PostHog/OTel telemetry adapters,
comment threads with anchor binding and drift resolution, interest votes, landing page and an
explainer artifact (site/).
Not yet: the React viewer chrome (prototype exists outside this repo), a Postgres adapter, realtime fan-out for comments, notifications. Drafted and next, in that order.
Element comments and viewer chrome
Enable automatic element selection with the host's comments: true serving option, then mount the optional framework-independent @artifactkitdev/core/browser/comments chrome in your trusted viewer. It provides a quiet top-right comment button, an on-demand drawer, replies/resolution, version-aware anchors and configurable document/mockup/presentation/sales-room defaults. No agent-authored instrumentation is needed. See the integration guide and run npm run demo:comments for a local example. Publishing permissions and credentials stay on the host.
A source-checkout presentation starter extracts stable slides, reveal steps and separate presenter data from the supplied InSite reference. Build it with npm run example:presentation; publish only its public HTML if desired.
MIT · © Left Hook
No installation packages available.