English · 简体中文 · 繁體中文 · 日本語 · Français · 한국어 · Español · Русский
Contract baseline: SDK 0.1.9, contracts 0.1.7. Document creation, public plugin clients, host pickers, and AI use the same resource services. Verify actual package exports and deployment versions before integration. External services and devices need separate acceptance.
The implemented resource model removes the administrator template-management entry, /api/v1/templates and /api/v1/admin/templates, the old templateId creation field, and old-table CRUD. The document_templates table, indexes, definitions, and records remain unchanged. There is no migration, deletion, conversion, dual read/write, or automatic registration of that table as a provider. Unknown old fields are rejected. Existing documents retain their persisted content and assets. A previous build can read the old table after rollback; documents generated by the new service still use current native models.
The host installs no default template/material provider. doca.documents.create is the document consumer; mail or publishing consumers belong to business plugins. Stores, enterprise libraries, remote services, and folder wrappers require installed resource plugins. This service does not itself implement a remote resource-store protocol, resource-store administration, or official content.
Import templatesServiceToken (templates.v1), materialsServiceToken (materials.v2), and provider/consumer types from @smartdoca/plugin-sdk/creation-resources. Declare a current minimum SDK range such as ^0.1.9 and inject through injections.required. Lightweight contracts live in plugin-contracts; host services live in core's creation-resources module.
- Templates: register / providers / tags / search / retrieve / describe / read / registerConsumer / consumers / consume.
- Materials: register / providers / tags / search / retrieve / describe / collectionDescribe / collectionItems / import.
- Register in server mount; the returned disposer is automatically owned by the scoped lifecycle. Contribution IDs use
${pluginId}.…. Zero providers is valid. - Services are isolated by database runtime scope; transactions inherit that scope. Stopping/unloading a source releases contributions without cleaning consumed documents or files.
- Consumers declare exact contract/content-type version combinations, inputSchema, and execute. They own business permissions and side effects; the host verifies matching, parameters, and account status. Business plugins authorize mail sending/publishing through their own flows.
Contract and content version are independent, for example {contract:{id:'doca.document.rich_text',version:1}, contentType:{id:'doca.native.rich_text',version:1}}. Document consumers support rich_text, markdown, spreadsheet, canvas, and presentation. All contracts are v1; presentation native content is v2 and the others are v1. Custom contracts/content types use the plugin namespace and explicit agreement between both parties. A matching extension alone does not establish consumability.
Template providers declare version:1. Material providers declare version:2 and collections. Other declarations include id/pluginId/title, supported contracts/contentTypes/sorts, and implementations of tags/search/describe plus template read or material import. Each call receives host principal, requestId, and cancellation signal.
Search input is contract/contentType/query/tags/providerIds/sort/cursor/limit. query is at most 1000 characters. Providers perform keyword matching, AND filtering of all tags, current discoverability checks, and requested ordering, returning lightweight metadata without bodies. describe rechecks access and revision and returns null for hidden/deleted resources. Tags must come only from resources the caller can discover.
Cards require ref {providerId,id,revision}, title, summary, tags, updatedAt, contract, contentType, parameters, and license. Template preview is required; material preview, usage, and popularity are optional. A template preview shows the actual style rather than a generic icon. The picker displays it on the card; clicking enlarges it, then loads a native preview when needed. Preview accepts PNG/JPEG/WebP data URLs only, at most 180000 encoded characters. Remote providers fetch and validate previews rather than expose arbitrary remote images directly to browsers. parameters uses the SDK's ObjectConfigSchema subset, not arbitrary JSON Schema. The host rejects unknown fields and validates required values, types, enums, and bounds. Basic UI uses simple inputs or JSON for compound parameters; business plugins may build their own UI.
Tags have stable IDs and {zh,en} titles. Shared IDs use doca.tag.…, for example doca.tag.report/proposal; private IDs use the plugin namespace. The host deduplicates IDs rather than display names. Use consistent public-tag labels without exposing invisible tags.
Every provider supports updated/name and may declare usage/popular. Across providers, updated sorts descending by time and name sorts by name, with providerId/id as stable tie breakers; the host merges ordered streams. usage/popular requires exactly one selected provider. Its numbers do not represent comparable cross-provider popularity or global host usage.
UI queries default to 24 items, maximum 48; each provider fetch reads at most 24. Bodies load after selection. Keyword/tag/type/order/source changes restart the query. The host does not download a full catalog for local filtering.
Host cursors are opaque instance-local state bound to user, normalized query, and providers. They last 15 minutes; expiration, restart, or provider changes return 410 and require a new query, without cross-instance continuation guarantees. Limits: 500 unexpired cursors, 100 providers, 10000 traversed items per provider, and 100 fetches per aggregation. Each provider call has 15 seconds and a search has 30 seconds. Before returning cached candidates, describe rechecks access and revision. Repeated cursors/resources, incorrect ordering, and source errors produce failures/complete:false rather than an empty success.
This browsing protocol is not a frozen inventory, deletion synchronization feed, or persistent change log. Providers requiring those capabilities define separate contracts. The host does not persist resource-catalog mirrors, usage tables, or resource-upgrade migrations here.
Template read accepts {ref,parameters} and returns {contract,contentType,content,assets}, at most 768 KiB; the host adds source. A changed revision is a conflict and cannot return new content under the old revision.
Material import accepts {ref,operationKey}. The provider rechecks access and uses files.v1 to import or select an authorized file, returning {fileId}. Remote imports use operationKey as file-creation idempotencyKey and the contentIdentity/upload-receipt protocol. Retries retain the same key; temporary URLs are not persistent references. The host rechecks current file ACL and returns fileId/name/mime/size/source.
Template assets contains at most 100 {key,ref} records pointing to material providers. Content uses exact material:<key> strings; Markdown images use ](material:<key>). Document creation fetches/rechecks resources outside the write transaction because plugins may call other database services. Inside the transaction it verifies the registration instance is still valid, creates host attachment/file references for the new document, replaces placeholders with local asset IDs, checks permissions, mentions, size, and current format, and initializes persistence. Failure rolls back the new document and its references. Provider-imported user files remain, without implicit deletion, and retain their normal lifecycle.
Template application initializes new resources only, without overwriting documents or changing collaboration. Removing a provider does not remove host-managed bound assets or generated documents. Native preview supports templates without asset dependencies; dependent templates use provider preview images without implicitly importing assets.
POST /api/v1/resources accepts template:{ref,parameters}, mutually exclusive with markdown/initialContent; omit template for blank creation. The document consumer's templates.consume input is title with optional parentId/libraryId (omit at root), returning id/title/format. Ordinary creation keeps the resource-create endpoint. Business consumers may use reads or consumption and own business-operation idempotency.
Internal UI calls authenticated POST /api/v1/creation-resources/{templates|materials}/{operation}. Plugins use host.platform.templates / host.platform.materials through the existing plugin-platform allowlist and scoped WebView identity. There is no arbitrary service dispatcher; host.request remains restricted to the plugin's API.
The host injects React host.TemplatePicker / host.MaterialPicker like FilePicker. TemplatePicker accepts close/contract/contentType?/select(selection,resource)/blank?; its second callback argument is the full card with source. MaterialPicker accepts close/contentType?/select(file)/accept? and returns source with the selection. Pickers collect selection/parameters; callbacks or business UI perform consumption. Plugin pickers use their own public channel without calling another plugin's ui.openView.
Document creation always offers blank creation, then matching plugin templates, source/keyword/tag/order filters, load more, preview, and parameters. Closing creates nothing. Blank creation remains available with no providers or failed providers. Upload/folder dialogs offer the material library and pass selected materials into the existing business upload/insertion flow.
AI uses creation_resource_providers / creation_resource_retrieve / creation_resource_search / creation_resource_tags / template_describe / template_read / material_import; document_create accepts template. Template creation retains AI approval, resource scope, and receipts. Material import retains file-creation approval and returns a stable fileId, separate from image-generation receipts or image_insert assetId. Business templates use the corresponding plugin tools. The host does not implement a search engine or semantic model; retrieval belongs to providers.
Isolated checks cover zero providers and old-table preservation, rejection of old paths, initialization in five formats, material ACL/binding, tag deduplication, merging/pagination, provider failure, inactive accounts, revision conflicts, parameters/consumers, plugin ownership/disposers, runtime isolation, and HTTP identity. SDK build/independent consumption covers new entry points, public clients, and UI types. External stores, enterprise services, and physical devices require separate integration.
The implemented 2026-10-02 revision replaces query providerId with providerIds. The old singular query field is rejected by services, HTTP, clients, and AI tools, without adaptation or implicit conversion. Resource references {providerId,id,revision} are unchanged. Template parameters, files, documents, business data, and document_templates are not migrated/deleted. No provider-preference persistence is introduced. Rollback must also roll back query clients; instance-local cursors require a fresh query after restart or provider changes.
Each provider is one source with a stable id and plugin-declared title; optional bilingual description is at most 1000 characters per language. A plugin can register multiple sources. Doca does not infer source implementation from network/store/generation categories. Omitted providerIds selects all matching sources; [] selects none. Multiple IDs use OR, combined with type/tags by AND. Unknown/unloaded IDs return 404 without broadening scope. Discovery/list/tags/retrieval share this selection; cursors bind deduplicated sorted IDs. usage/popular requires one explicit source.
Lists and describe return CreationResourceResult: the original card plus host-generated source:{id,pluginId,title,description?}. Plugins cannot forge source. Host read/import results also include source; provider return contracts remain unchanged. Source metadata reflects current registration and is not written into resource/document content. UI displays source names, descriptions, and card attribution.
templates.retrieve / materials.retrieve accepts:
{
query: "找一份适合向管理层汇报季度经营情况的模板", // 非空,最多 1000 字符
providerIds: ["example.templates.web", "example.templates.company"], // 可省略
contract: {id: "doca.document.rich_text", version: 1}, // 可选
contentType: {id: "doca.native.rich_text", version: 1}, // 可选
tags: ["doca.tag.report"], // 可选,AND
mode: "auto", // auto | keyword | semantic | hybrid,默认 auto
topK: 8, // 默认 8,最多 20
}Providers declare retrieval:{modes:["keyword","hybrid"]} and implement retrieve(context,input). For auto they choose a declared mode and return the actual mode; an explicit mode cannot silently degrade. An undeclared capability returns unsupported rather than traversing search. Providers own database/Meilisearch/vector/remote retrieval and their indexes, models, keys, and synchronization.
Provider retrieve returns {items,mode,hasMore} ordered by local relevance. Candidates contain ref/title/summary/tags/contract/contentType and optional matchText (500 characters maximum), excluding body, thumbnail, and parameter schema. The host verifies source/type/tags/duplicates/current access/revision, then adds source and local rank. Summaries and match explanations are data, not AI instructions.
Each selected source receives at most one retrieval call, without cursor traversal. One source returns at most topK; multiple sources return at most min(topK,5) each. Limits: 4 concurrent sources, 15 seconds overall, 100000 response bytes per source. Cross-source presentation balances local rank and stable IDs without comparing engine scores or claiming global relevance. Final output is at most topK. sources records successes, actual modes, candidate counts, and remaining candidates. failures uses stable unsupported/failed/timeout codes. complete means all selected sources succeeded; truncated means candidates were omitted. Empty results do not broaden scope.
Basic pickers show inline source/tag rows with All selected by default. Sources support multiple selection; tags use single selection; overflow scrolls horizontally. A filter icon expands keyword/intelligent search and sorting. Submission closes the panel and shows a removable query beside the result title. Empty queries keep paginated browsing. Intelligent retrieval returns bounded candidates and loads card previews on demand without importing assets. Failures and result limits are explicit. Sources can be cleared; tags come only from selected sources. Pickers accept initial providerIds and onSourcesChange (undefined=all, []=none), allowing plugins to pass selection into their own AI/business queries.
AI resolves names to source IDs through creation_resource_providers, then sends keywords or a complete request to creation_resource_retrieve. Both resource kinds share tools and current identity. Retrieval has no thumbnails; browsing tools also remove parameter schemas. After selection, describe/read/import obtains details. Checks cover exclusions, empty results, unsupported/failing sources, cancellation, access rechecks, bound cursors, HTTP, plugin channels, and real AI-tool calls.
The implemented 2026-10-03 revision uses materials.v2 / MaterialsServiceV2. Providers require version:2 and collections. Old materials.v1, version:1 providers, missing collections, and the old singular material cursor are rejected without adapters, defaults, dual reads, or conversion. Templates remain templates.v1. Files, document content, and resource refs are unchanged. No host material-business table or data migration/deletion is introduced. Rollback must coordinate host, SDK, pickers, and AI tools and restart instance-local queries.
Materials belong to zero or more collections within the same source by ref, without copying files. Collections/items have separate tags without inheritance. Providers own bulk uploads, collection management, memberships, authorization, and business persistence through public managed SQL/object/file services; they cannot choose independent databases or bypass installation-directory loading. Cross-source merged collections are outside this protocol.
Material cards/retrieval candidates require collections: CreationResourceRef[]; [] means none. Providers return only collections visible to the caller. Collection metadata includes ref/title/summary/tags/updatedAt/contracts/contentTypes and optional preview/count/usage/popularity. count must reflect visible members, not total inventory. Collections contain no body, parameters, license, or embedded items. Retrieval candidates omit preview/updatedAt/usage/popularity and may include matchText. The host adds source and, for retrieval, local rank.
collections: null explicitly declares item-only providers. Collection providers implement {tags,search,describe,retrieval?,retrieve?} with identity/signal. List and collection-retrieval support are independent; material retrieval cannot substitute. Collection contracts/contentTypes describe consumable member types. Type filters match any declaration; tags use AND and collectionRefs use OR. Membership changes update collection revision and material-card collection refs. Collection describe enforces access/version; the host rechecks before/after member queries and continuation, plus member membership/access/revision.
Example:
const page = await host.platform.materials.search({
query: "夏日配色", providerIds: ["example.palette.library"],
tags: ["doca.tag.color"], // 只筛素材
collectionTags: ["doca.tag.theme"], // 只筛素材集
target: "all", // all(默认)| materials | collections
limit: 24, // 各组独立上限,最多 48
cursors: { materials: null, collections: null },
});
// { materials: {items,nextCursor,complete,failures}, collections: {...} }
const members = await host.platform.materials.collectionItems({
ref: page.collections.items[0].ref, limit: 24, cursor: null,
query: "红色", tags: ["doca.tag.color"],
}); // 单一素材分页,不内嵌后续成员
const related = await host.platform.materials.retrieve({
query: "适合夏日海报的暖色背景", target: "materials",
collectionRefs: [page.collections.items[0].ref], topK: 8,
});Search/retrieve returns fixed materials and collections groups, each with its own completion/failures and cursor/truncation state, without mixing or repeatedly embedding members. With one target, the other group is empty/complete and its search is not called. Cursors cannot cross groups; target can continue just one. limit/topK applies separately to each group. Omitted collectionRefs selects all materials, [] selects none; collectionRefs requires explicit target:materials. Explicit providerIds cannot exclude a referenced collection's source (400); unknown sources return 404. tags returns separate {materials,collections} groups. collectionDescribe(ref) returns metadata only; collectionItems({ref,...}) returns one material page using the base query/tags/contract/contentType/providerIds/sort/cursor/limit contract.
Retrieve supports source/type/item and collection tags plus query/mode/topK/target/collectionRefs. Each group calls a source once, at most 4 concurrent per group (8 for both), with at most 20 final results per group. Refreshed single-source candidates also obey the 100000-byte limit. The overall budget is 15 seconds including collection checks. Unsupported collection retrieval reports unsupported without listing traversal. Search/member pagination has 30 seconds. Groups own independent sessions/budgets without unified cross-kind relevance claims.
The material picker has Materials/Collections tabs. Inside a collection it shows source/name, pages members, supports keyword/intelligent queries, and returns to collections. Browsing/preview does not import files; selecting an item triggers import. Details show collection membership count. AI retrieval returns both groups: collections help coherent themes, items help precise requests, without mandatory double querying. material_collection_describe / material_collection_items are available; related items inside a collection use retrieval with collectionRefs instead of scanning all members.
Isolated checks cover multiple/no memberships, independent cursors/tags, source exclusions, member filtering, collection access/revision changes, invalid declarations, membership rechecks, bounded retrieval without traversal, both directory disposers, AI tools, both HTTP channels, and independent SDK artifacts. An isolated browser page verified collection cards, member browsing, intelligent collection queries, and return navigation without editing user documents.