@absolutejs/artifacts
The typed lifecycle for things an AI makes.
An AI-generated page, report, plan, email, deck, or image should not disappear into a chat transcript or become an unvalidated blob. It should have a kind, structured content, ownership, provenance, revisions, capabilities, renderers, and an explicit publication lifecycle.
@absolutejs/artifacts provides those contracts without owning your database,
routes, authorization, UI, or hosting.
What it owns
- Structured artifact-kind schemas and runtime validation
- Draft, published, and archived lifecycle states
- Immutable revision history, restoration, and optimistic updates
- Structured content plus opaque references to generated or source files
- Artifact, asset, renderer, and publisher storage interfaces
- In-memory artifact and asset stores for development and tests
- Owner-bound lifecycle tools structurally compatible with AI tool maps
- Provenance fields for model, tool, trace, and source entities
- Standard file-backed kinds for documents, presentations, spreadsheets, datasets, code, images, audio, video, email, archives, and generic files
- An optional bridge to
@absolutejs/ragingestion - Provider-neutral generation registries with atomic multi-file bundles
- Staged, validate-before-commit multi-artifact batches with completion receipts
- Revision-pinned or explicitly live publications
- Durable lifecycle events designed for transactional outboxes
- Per-revision RAG indexing state and an indexing coordinator
- Artifact/source lineage and history-aware asset garbage collection
Your application retains authorization, durable persistence, public tokens, URLs, notifications, analytics, submissions, and product-specific rendering.
Define kinds once
import { Type } from "@sinclair/typebox";
import {
createArtifactService,
createMemoryArtifactAssetStore,
createMemoryArtifactStore,
defineArtifactRegistry,
} from "@absolutejs/artifacts";
const registry = defineArtifactRegistry({
page: {
capabilities: ["archive", "edit", "preview", "publish"],
content: Type.Object({
blocks: Type.Array(
Type.Union([
Type.Object({ heading: Type.String(), type: Type.Literal("hero") }),
Type.Object({ body: Type.String(), type: Type.Literal("text") }),
]),
),
theme: Type.Union([Type.Literal("dark"), Type.Literal("light")]),
}),
label: "Page",
schemaVersion: 1,
},
});
const artifacts = createArtifactService({
assetStore: createMemoryArtifactAssetStore(),
registry,
store: createMemoryArtifactStore(),
});
const page = await artifacts.create("owner-123", {
content: {
blocks: [{ heading: "A real page", type: "hero" }],
theme: "light",
},
createdBy: "agent",
kind: "page",
provenance: { model: "your-model", tool: "create_page" },
title: "Launch page",
});
Every successful create or lifecycle mutation appends an immutable snapshot. Restoring history creates a new private draft instead of rewriting or republishing an old revision:
const history = await artifacts.listRevisions("owner-123", page.id);
const restored = await artifacts.restore("owner-123", page.id, 1);
Production persistence
Use the package-owned Drizzle schema on PostgreSQL, including Neon. The store atomically writes the current artifact, immutable revision, and lifecycle outbox events. It also persists per-revision indexing state and fences every artifact read and mutation by owner.
import {
artifactDrizzleSchema,
createDrizzleArtifactStore,
} from "@absolutejs/artifacts/drizzle";
const store = createDrizzleArtifactStore({ db });
Export artifactDrizzleSchema from your application's Drizzle schema so its
normal migration workflow owns the four tables. Insert and select TypeBoxes
generated directly from those tables are exported from the same entry point;
hosts should reuse them instead of redefining database row schemas.
When a host owner is permanently deleted, call artifacts.purgeOwner(ownerId).
The production store removes its current records, revisions, indexing state,
and outbox events in one transaction; orphaned asset bytes remain subject to
the package's history-aware garbage collector.
File-backed artifact kinds
Use the bundled definitions directly or compose them with application-specific kinds:
import {
defineArtifactRegistry,
standardArtifactDefinitions,
} from "@absolutejs/artifacts";
const registry = defineArtifactRegistry({
...standardArtifactDefinitions,
page: myPageDefinition,
});
File bytes stay in host storage. Artifact records retain opaque references with name, media type, size, checksum, role, and storage URI. The URI is not treated as a public URL and the package reads it only through the configured asset store. Detaching a file does not delete its bytes because older immutable revisions may still reference it.
const report = await artifacts.create("owner-123", {
content: { summary: "Quarterly results" },
createdBy: "agent",
kind: "document",
title: "Q3 report",
});
await artifacts.attach("owner-123", report.id, {
data: pdfBytes,
mediaType: "application/pdf",
name: "q3-report.pdf",
role: "primary",
});
Multiple generated files should use one staged transaction and therefore one artifact revision:
const report = await artifacts.createBundle("owner-123", {
assets: [pdfOutput, docxOutput, thumbnailOutput],
content: { summary: "Quarterly results" },
createdBy: "agent",
kind: "document",
provenance: {
lineage: [{ relation: "generated_from", sourceId: "rag-document-123" }],
tool: "quarterly_report_generator",
},
title: "Q3 report",
});
When one job must produce several artifacts together, stage the complete batch,
run domain validators before persistence, and commit it through a store that
implements createBatch (the package Drizzle and memory stores do):
const staged = await artifacts.stageBatch(
"owner-123",
{
evidence: [{ sourceId: "research-run-123", sourceUrl: sourceUrl }],
items: [
{ artifact: worksheetInput, key: "worksheet" },
{ artifact: reportInput, key: "report" },
],
provenance: { tool: "prospecting_mission", traceId: mission.id },
},
{
validators: [
({ items }) =>
validateDomainEvidence(items).map((message) => ({
code: "evidence_invalid",
message,
})),
],
},
);
const receipt = await staged.commit();
if (receipt.status !== "committed") throw new Error(receipt.error);
Every artifact carries its batch id, item key, evidence, and provenance.
commit() returns the durable reconciliation receipt: artifact ids,
revisions, atomicity, validation outcome, and any archived compensation. The
default mode requires an atomic ArtifactStore.createBatch. Hosts that cannot
provide a transaction may explicitly select archive_on_failure; completed
earlier writes are then archived and reported as rolled_back or
partial_failure. Calling rollback() before commit releases all staged
asset transactions.
Generation
Generators are provider-neutral. They return validated structured content and zero or more file writes; the registry commits those outputs through the same artifact bundle lifecycle:
const generators = createArtifactGeneratorRegistry([
{
kind: "presentation",
name: "company-deck",
generate: async ({ prompt }) => buildPresentation(prompt),
},
]);
const deck = await generators.generate(artifacts, {
createdBy: "agent",
kind: "presentation",
ownerId: member.id,
prompt: "Build the partner launch deck",
});
Generators may expose a validate function. The bundled
validateGeneratedArtifactFormats validator checks CSV row structure, RFC 822
headers, ZIP readability, and PPTX package/XML integrity before persistence.
Generate several independent artifacts with one atomic receipt through the same
registry:
const receipt = await generators.generateBatch(artifacts, {
ownerId: member.id,
items: [
{ createdBy: "agent", key: "deck", kind: "presentation", title: "Deck" },
{ createdBy: "agent", key: "email", kind: "email", title: "Email" },
],
provenance: { tool: "campaign_generator" },
});
Generation validators run after every output is staged and before anything is committed. Validation failures return a rolled-back completion receipt keyed to the invalid output.
RAG ingestion
The optional @absolutejs/artifacts/rag entry point resolves one current or
historical artifact record into the upload contract already accepted by
@absolutejs/rag. Structured content is included as JSON and every attached
file is included without exposing its storage URI:
import { artifactToRAGUploads } from "@absolutejs/artifacts/rag";
import { buildRAGUpsertInputFromUploads } from "@absolutejs/rag";
const revision = await artifacts.getRevision("owner-123", report.id, 2);
const uploads = await artifactToRAGUploads(revision, assetStore);
const upsert = await buildRAGUpsertInputFromUploads({ uploads });
createArtifactRAGIndexCoordinator wraps that conversion with durable
pending, indexed, and failed state. It removes document IDs from the
previous indexed revision after the replacement succeeds. Set failureMode to
"isolate_uploads" to index structured content and assets independently. A bad
asset then produces a typed partial receipt while preserving successful
document ids; obsolete ids are removed only after a fully successful revision.
Events and retention
Every lifecycle mutation supplies its event to the artifact store in the same call that writes the current record and immutable revision. Durable adapters should commit those rows in one database transaction, then workers can consume unprocessed events for RAG indexing, previews, notifications, scanning, or conversion.
Asset collection compares storage candidates with references across every
retained revision. collectAssetGarbage({ dryRun: true }) previews deletion;
only unreferenced objects older than the configured minimum age are eligible.
Compose publishing and rendering
Publishing is an adapter because public access is a host policy:
const artifacts = createArtifactService({
publisher: {
publish: async (artifact, { idempotencyKey }) =>
mintPublicTokenAndUrl(artifact, idempotencyKey),
unpublish: async (artifact, { idempotencyKey }) =>
revokePublicAccess(artifact, idempotencyKey),
},
registry,
store: postgresArtifactStore,
});
Publishing defaults to pinned: the public record names the exact immutable
revision. mode: "live" is an explicit alternative whose revision advances
with later edits.
Renderers are independently registered by artifact kind and output format:
const renderers = createArtifactRendererRegistry([
{
format: "html",
kind: "page",
render: async (artifact) => ({
body: renderSafePage(artifact.content),
mediaType: "text/html; charset=utf-8",
}),
},
]);
The package never treats generated HTML or JavaScript as trusted executable content. Applications should define structured content schemas and render them through controlled adapters.
AI tools
createArtifactTools binds create, list, get, update, publish, and unpublish
operations to one owner. The returned definitions use TypeBox inputs and the
same { description, input, handler } shape used by @absolutejs/ai.
const tools = createArtifactTools({
createdBy: "agent",
ownerId: member.id,
service: artifacts,
});
Only expose the publication tool where the user explicitly controls public access.
License
Business Source License 1.1 — free for your own products, applications, and internal use; you may not offer it as a competing hosted AI artifact-generation, editing, rendering, publishing, or artifact-management service. Converts to Apache 2.0 on July 14, 2030. See LICENSE.
Browser document preview
Install the optional docx-preview peer and import renderDocxPreview from
@absolutejs/artifacts/browser. Pass the original DOCX ArrayBuffer and display
the returned HTML as srcDoc in an iframe with sandbox="". Keep that sandbox:
the renderer disables active content, external resources, HTML chunks and links.
Fetch bytes through your application's authenticated owner-scoped file endpoint.
The browser preview approximates Word layout; always retain the original file.
Pass { allowLinks: true } to preserve validated HTTPS and plain email links.
Use sandbox="allow-popups allow-popups-to-escape-sandbox" for this mode: links
open outside the document sandbox in a new tab with no opener or referrer.
Document scripts and parent-page navigation remain disabled. Links remain
disabled by default. HTTP, executable URLs, credentials, and email parameters
are not accepted.
Formatted Word exports
renderFormattedDocx({ blocks, filename, pageSize: 'letter' }) returns an
ArtifactRenderResult containing editable DOCX bytes. Blocks are paragraphs,
headings, or bullets; runs support bold, italic, and HTTPS/mailto hyperlinks.
No resources are fetched. The default body font is 11.5 points. Documents are
limited to 2,000 blocks and 1 MB of structured input.
For simple generated drafts, documentBlocksFromText(text) recognizes blank-line
paragraphs, #/## headings, -/*/• bullets, **bold**, Markdown links and
bare HTTPS URLs. This is a limited text format, not a complete Markdown renderer;
HTML remains literal text. Layout can vary between Word-compatible applications.