@dani-builder/strapi-plugin-agent
v2.0.0
Published
Daniworks Agent plugin registration surface for Strapi 5.
Readme
@dani-builder/strapi-plugin-agent
Strapi 5 plugin with an Agent Admin workspace and server runtime for Daniworks Agent. It exposes the locale-scoped
knowledge-base retrieval services plus POST /api/agent/chat, an SSE endpoint
that emits the public @dani-builder/agent-contract event wire format.
Provider and control-plane integrations are opt-in. A missing provider produces
the terminal provider_unconfigured SSE error before retrieval or any external
request; a missing control-plane URL or token is inert and never attempts a
network request.
Builder calls the serializer registration point only when this optional plugin is installed.
Agent Admin and site settings
The Agent Admin has one editable site configuration, knowledge-source management and conversation logs. Settings read, update and connection-test permissions are independent. Read-only users can inspect but not save. The private site setting is not exposed through generic Content Manager CRUD. MCP provides agent_get_settings and agent_update_settings with the same permissions and validation.
The site configuration controls display name, instructions, in/out scope, tone, source UIDs and tags, document restrictions, global fallback, planner and responder models, retrieval limits, fallback questions, follow-ups and action permissions. UID/tag selection is an OR; document restrictions further intersect it. Empty scope denies retrieval unless explicit global fallback is enabled. An empty document list denies that source. Credentials and action schemas stay in deployment configuration; a changed Qdrant endpoint never receives the deployment endpoint's key.
For existing installations, prepare a v1 snapshot and back up the database before the major upgrade and schema synchronization. Follow the migration guide; existing identities and isolated partitions remain historical records, not new routing options.
RAG services
Consumer applications can use the supported ./rag entry point to construct
OpenAI embeddings and the Qdrant adapter, then compose indexing and retrieval:
import {
createIndexer,
createOpenAiEmbeddings,
createQdrantStore,
createRetrieval,
type IndexerDependencies,
type OpenAiEmbeddingsOptions,
} from "@dani-builder/strapi-plugin-agent/rag";
// Create a controller and embeddings client for each operation.
const resolved = await strapi.plugin("agent").service("settings").resolve();
const controller = new AbortController();
const embeddingsOptions: OpenAiEmbeddingsOptions = {
apiKey: resolved.openaiApiKey,
model: String(resolved.embeddings.model),
dimensions: Number(resolved.embeddings.dimensions),
signal: controller.signal,
};
const embeddings = createOpenAiEmbeddings(embeddingsOptions);
const store = createQdrantStore({
url: String(resolved.qdrant.url),
apiKey: resolved.qdrant.apiKey,
collection: String(resolved.qdrant.collection),
});
// Supply your application's document loader (for example, Strapi Documents API).
declare const getDocument: IndexerDependencies["getDocument"];
const indexer = createIndexer({ embeddings, store, getDocument });
const retrieval = createRetrieval({ embeddings, store });model defaults to text-embedding-3-small. dimensions is optional; when
provided, it must be a positive integer, is sent to OpenAI, and every returned
vector must have that length. Choose a model that supports the requested dimensions
and match the vector size configured on the Qdrant collection. Omitting dimensions
preserves the model's default vector size. An empty input returns [] without a
request; API errors and fetch cancellation propagate to the caller.
The optional signal is forwarded to every embeddings request made by that client.
Use a controller and client per operation so cancellation does not affect unrelated
operations; an aborted signal cannot be reused. The optional fetch accepts an
injected fetch implementation for hosts and tests.
The entry point also exports the dependency, query, result, knowledge-source,
embedding, schema serialization, and vector-store types used by
createIndexer(), reindexSource(), and createRetrieval().
Persistent sessions and limits
POST /api/agent/session issues an owner token and root session. Chat requires that token, a session ID and request ID; an identical completed retry replays the stored result. Restore returns root history, and cancel terminates an in-flight turn. Owner hashing, TTL, quotas, locking and configurable retention remain in effect. Request and restore agentId selectors are rejected. Drain or terminate old sessions before upgrading; Admin detail can inspect an exact historical partition key without merging transcripts. Session metadata is sanitized and allowlisted at issuance.
The planner rewrites a standalone knowledge query and selects a topic using bounded memory and history. Its model is configured separately from the responder. New turns do not emit persona_routing; readers retain support for historical v1 extensions. See the conversation guide for details.
Knowledge-base revision contract
Installed chat uses only sources registered in Agent → Knowledge Base as
Knowledge Sources for model evidence and citations. Adding a source to deployment
retrieval.sources configures retrieval but does not register it as a Knowledge
Source. Hits from an unregistered source remain excluded, and the server logs an
actionable warning with that source UID once per turn, including across concurrent
and fallback searches. Register the source mapping in Knowledge Sources to make
its current, verified documents eligible for evidence.
Registered sources searched with indexedConfigRevision === 0 (never indexed)
or a configured/indexed revision mismatch emit agent.retrieval.stale_index in
the turn ledger and an actionable server warning once per source per turn, even
when Qdrant returns no hits. This covers actual scoped, anchored and global
fallback searches; sources outside the search scope do not trigger the warning.
Current revision filters remain enforced. The Knowledge Sources list shows
재색인 필요 with the stale reason; run a full source reindex in Index Status
to apply mapping changes. The warning does not reindex or reuse older vectors.
knowledge-source.serializerRevision is the persisted integer used when
indexing vectors and filtering Qdrant retrieval. Bump it and force a full
source reindex whenever serializer output semantics change.
serializer.getSerializerFingerprint() (and the retained
getSerializerRevision() alias) returns a checksum of registered override
implementations for diagnostics only. It is not stored in Qdrant and must not
be used as a search revision: JavaScript function source cannot include values
captured from an override closure. If closure state changes output, explicitly
bump the affected source's integer serializerRevision and reindex.
Malformed Qdrant search hits are excluded and emit a structured
agent.qdrant.search_hit_excluded warning. Pass a logger to
createQdrantStore() to route these warnings to the host observability stack.
Query and topic planning
The ./rag entry point exports TurnPlan, TurnPlanner, TurnPlannerContext, createDefaultPlanner, createChatRuntime, retrieval and provider types. A plan contains a standalone searchQuery, a topic and optional fallback diagnostics. It has no catalogue or persona selector. QUERY_TOPIC_REGRESSION_CASES covers query and long-distance topic recall.
Knowledge-base Admin
Agent → 지식베이스 discovers content types and edits source mappings, locales,
relation metadata and JSON publication filters. Manual reindex jobs report document
and chunk counts, sanitized errors and configured/indexed revisions. Clear requires
a selected source and deletes only its points and tracking records. Assign the
kb.read, kb.update, kb.reindex and kb.clear Admin actions independently.
The plugin-owned knowledge-base service assembles settings, embeddings, Qdrant
and serializer overrides. Jobs/locks are process-local; use one writer instance.
Installed chat verifies every search hit against the current published document,
source publication filter and locale before sending evidence to the model or
emitting citations. Its indexed contentHash must match the current extraction,
including title, description, body and URL. Unpublished, deleted, changed or
unverifiable documents are excluded individually; valid neighboring evidence
remains usable and answers can complete with no sources. Verification is mandatory
regardless of the optional conversation-restore revalidateSources setting, and
document reads are shared only within the current turn. Reindex older points that
lack a contentHash before expecting installed chat to use them. Standalone
createRetrieval and createConfiguredChatRuntime retain their composable contracts;
hosts using those factories own current-document verification.
reindexOnRelations schedules published dependents when registered related
targets change through Document Service middleware; see automatic indexing below.
See the knowledge-base guide for API
contracts, extraction limits and daniworks-home migration examples.
Automatic knowledge-base indexing
Registered public source mappings are synchronized by Document Service middleware
at bootstrap. Publish/update/unpublish/delete/discardDraft events use published
reads, the source publishFilter/locales, and component serializer overrides.
config.autoIndexing.debounceMs accepts 500–1500 (default 1000). Related targets
listed in reindexOnRelations schedule published dependents before and after a
change. Provider failures cannot fail content writes; generic document errors are
visible in Agent → 지식베이스. Timers are canceled at shutdown.
An initial full reindex is required. Mapping, serializer and embedding revisions
remain stale until a successful full reindex of the unchanged configuration.
Automatic removal of unpublished/deleted/filtered/empty documents works while
stale and does not require embedding credentials. Search scopes support an optional
embeddingRevision matching indexed payloads. The knowledge-base service's source
list supplies the resolved revision; consumers using public retrieval factories
should pass that value to prevent searching vectors from an older embedding model.
See the migration guide
for replacing consumer registerRagSync wiring and computed-field limitations.
Structured output extensions
Agent output extensions documents
followUps, deployment actions[], Admin permission controls,
validated provider tools, warning logs and the full wire/rendering table.
Direct browser access
Use createAgentClient from @dani-builder/strapi-client with an issued session
token. Configure browserCors: { allowedOrigins: ["https://www.example.com"] }
in the plugin's server config for a separate frontend origin. The default permits
same-origin browsers and No-Origin server calls. Origins must be exact canonical
HTTP origins (no wildcard, path, trailing slash or credentials). The policy handles
preflight and overrides global CORS only for session/chat/cancel, including a custom
Strapi REST prefix; admin and other content routes keep their existing CORS policy.
Browser calls omit cookies and use only the session Bearer token. CMS admin/content
tokens and provider keys must stay on the server.
See browser SDK and origin policy.
Conversation deletion and retention
Admin DELETE /agent/conversations/:key requires
plugin::agent.conversations.delete. A root or isolated conversation key deletes
that entire session, all its conversation partitions, and all turns in one
transaction. The response is { sessionId, conversations, turns } with actual
deleted row counts; unknown keys return 404 conversation_not_found. The deleted
visitor credentials can no longer restore or continue that session.
conversationConfig.retention.days is a positive integer (1–1000000), default
null (automatic deletion off). It measures days after session expiresAt,
not the last turn time. Cleanup runs immediately at bootstrap and hourly thereafter,
resolving current settings on each tick. Only sessions whose expiration is strictly
older than the retention cutoff are deleted, including all partitions and turns.
The Admin field 대화 로그 보존 일수 (세션 만료 후) inherits server settings when
blank/null; null cannot disable a positive retention value set by the server.
