cardtmpl

package
v1.24.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package cardtmpl owns reviewed server-side Adaptive Card templates. It does not dispatch messages; producer modules pass its document to carddispatch.

Package cardtmpl 提供 octo-server 卡片消息基座 (octo-card@1.0) 的模板注册与 渲染能力。所有业务卡片(L2a 平台内置 / L2b 业务自定义)以版本化 Template 形式 注册到 Registry,统一走 Registry.Render 产出经校验的 InteractiveCard payload。

权威契约: docs/platform-card-base.md

Index

Constants

View Source
const (
	ApprovalApproveActionID = "approval-approve"
	ApprovalDenyActionID    = "approval-deny"

	// MaxApprovalCustomActions caps the actions[] on approval_card. Five keeps
	// the terminal card readable on narrow layouts; enlarging it requires a
	// wire-contract review because clients render every button inline.
	MaxApprovalCustomActions = 5
	// MaxApprovalActionTitleRunes matches the shared 80-rune ceiling for
	// button labels; longer copy belongs in title/description.
	MaxApprovalActionTitleRunes = 80
)
View Source
const (
	DocsApproveActionID = "docs-access-approve"
	DocsDenyActionID    = "docs-access-deny"
	// DocsDenyReasonInputID is the id of the (hidden) Input.Text that declares the
	// reviewer deny-reason channel. The reason must ride under a *declared* input
	// id — the card/action endpoint fail-closes on undeclared inputs
	// (pkg/cardmsg.ValidateInputs) — so this id is the cross-repo contract the web
	// deny dialog submits (inputs[DocsDenyReasonInputID]) and the value reaches the
	// docs backend verbatim via DecisionRequest.Inputs.
	DocsDenyReasonInputID = "deny_reason"
)
View Source
const (
	JSONTemplateEngineV1     = "octo-json-template/v1"
	CatalogVisibilityPublic  = "public"
	CatalogVisibilityPrivate = "private"
)
View Source
const (
	MaxExcerptRunes = 300
	// MaxTitleRunes is the render-layer title cap. Exported so producer mapping
	// layers (e.g. modules/notify) can pre-truncate display titles to the exact
	// budget assembleResourceCardBody enforces — a single source of truth for the
	// title cap (G9), used by both the render guard and the ingress truncation.
	MaxTitleRunes = 200
)
View Source
const Protocol = "octo-card@1.0"

Protocol 是本包实现的基座协议版本,写入 metadata.octo.protocol, 供客户端识别能力集合。破坏性变更需 bump 大版本 (§2.1)。

Variables

View Source
var (
	ErrTemplateUnknown = errors.New("cardtmpl: template not registered")
	ErrStateUnknown    = errors.New("cardtmpl: state not declared in manifest")
	ErrFieldsInvalid   = errors.New("cardtmpl: fields did not pass input schema")
	ErrRenderFailed    = errors.New("cardtmpl: render failed post-build")
	ErrRegistryFrozen  = errors.New("cardtmpl: registry frozen")
	ErrActionUnknown   = errors.New("cardtmpl: action not declared by template")
)

典型错误。ErrFieldsInvalid 由调用方翻译为 400 (决策 C1); 其余属内部错误,调用方按 5xx 或降级策略处理。

View Source
var (
	ErrRuntimeCatalogUnavailable     = errors.New("cardtmpl: runtime catalog unavailable")
	ErrRuntimeCatalogDisabled        = errors.New("cardtmpl: runtime catalog template disabled")
	ErrRuntimeCatalogBlocked         = errors.New("cardtmpl: runtime catalog artifact blocked")
	ErrRuntimeCatalogNewSendDisabled = errors.New("cardtmpl: runtime catalog dynamic new-send disabled")
	ErrRuntimeCatalogNotAuthorized   = errors.New("cardtmpl: runtime catalog principal not authorized")
	ErrRuntimeCatalogIntegrity       = errors.New("cardtmpl: runtime catalog integrity failure")
)
View Source
var (
	ErrArtifactCompileBusy = errors.New("cardtmpl: artifact compiler busy")
)
View Source
var ErrUpdateInvalid = errors.New("cardtmpl: invalid card update")

Functions

func AbsoluteHTTPSURL added in v1.12.0

func AbsoluteHTTPSURL(raw string) error

AbsoluteHTTPSURL 是本包"必须为绝对 https URL"规则的**唯一真源**。它用真正的 url.Parse 断言 scheme==https 且 host 非空 —— 正则无法可靠判定 host 存在 (例 "https://?x" / "https://#x" 的 host 为空却能被 `^https://[^/].*$` 之类 的近似 pattern 放行,随后在 Build 内的 requireHTTPS 才失败、被误分类成 render_error 降级)。需要 C1 级字段校验的调用方 (modules/notify preflight) 必须调本函数在 ingress 前置拦截,而不是依赖 schema 的正则近似。

pkg/cardtmpl 内 requireHTTPS (resource.go) 与 renderCore step5 均委托本函数, 保证 preflight 通过 → Build 的 https 校验必然通过 (同一实现,零缝隙)。

func BuildApprovalRequestCard added in v1.11.0

func BuildApprovalRequestCard(input ApprovalRequestCard) (json.RawMessage, error)

BuildApprovalRequestCard is the shared server-owned approval template. Callers provide bounded business identifiers, never an action owner, URL, or arbitrary Adaptive Card JSON. When input.Actions is nil the output is identical to the pre-http-actions release (localized approve/deny buttons); a non-nil Actions slice is required to be 1..MaxApprovalCustomActions long and drives the button set instead.

func BuildApprovalResultCard added in v1.11.0

func BuildApprovalResultCard(result ApprovalResultCard) (json.RawMessage, error)

BuildApprovalResultCard renders the shared terminal/outcome visual for config-only approval consumers. It deliberately has no URL or arbitrary callback-authored layout: the consumer supplies display text only and octo owns the complete Adaptive Card shape.

func BuildDocsAccessRequestBodyWithLang added in v1.12.0

func BuildDocsAccessRequestBodyWithLang(
	lang string,
	webLoginURL string,
	docID string,
	requestID string,
	content DocsApprovalContent,
	actions ApprovalActions,
) (body []interface{}, cardActions []interface{}, deepLink string, err error)

BuildDocsAccessRequestBodyWithLang 抽出 BuildDocsAccessRequestCard 的核心构造逻辑, 只产生 body[] / actions[] / deepLink;不 marshal AC 顶层、不写 metadata。 pilot Template (pkg/cardtmpl/docs_access_request) 调用本函数,由 Registry.Render 统一注入 metadata (metadata.octo.{protocol,template,variant,source} + webUrl)。

lang 由调用方从 i18n.OutboundLanguage(ctx) 提前解析后传入;本函数不再触碰 ctx。

func BuildDocsAccessRequestCard added in v1.11.0

func BuildDocsAccessRequestCard(
	ctx context.Context,
	webLoginURL string,
	docID string,
	requestID string,
	content DocsApprovalContent,
	actions ApprovalActions,
) (json.RawMessage, error)

BuildDocsAccessRequestCard renders the enriched docs access-request approval card: a header line (label + status), a large document title, a requester row (optional avatar + name + role + timestamp), a boxed reason section, a hidden deny-reason input, and the two server-authored Submit actions (+ view-details). The callback route never appears in card bytes; only bounded domain data the registered docs route needs is embedded.

func BuildDocsAccessRequestV3BodyWithLang added in v1.12.0

func BuildDocsAccessRequestV3BodyWithLang(
	lang string,
	webLoginURL string,
	docID string,
	requestID string,
	content DocsAccessRequestV3Content,
	actions ApprovalActions,
) ([]interface{}, string, error)

BuildDocsAccessRequestV3BodyWithLang renders the Forge-aligned pending view. It deliberately reuses BuildDocsAccessRequestBodyWithLang first: all existing validation, deep-link construction, and production Submit data remain the single authority. Only the visual arrangement changes for 0.3.0.

func BuildDocsApprovalOutcomeBodyWithLang added in v1.12.0

func BuildDocsApprovalOutcomeBodyWithLang(
	lang string,
	webLoginURL string,
	docID string,
	content DocsOutcomeContent,
) ([]interface{}, string, error)

BuildDocsApprovalOutcomeBodyWithLang is the fragment-only counterpart used by registry-backed result views. Registry.Render owns metadata and envelope.

func BuildDocsApprovalOutcomeCard added in v1.11.0

func BuildDocsApprovalOutcomeCard(
	ctx context.Context,
	webLoginURL string,
	docID string,
	content DocsOutcomeContent,
) (json.RawMessage, error)

BuildDocsApprovalOutcomeCard renders the terminal (已允许 / 已拒绝) docs card: header (label + colored status) + title + a result box. The denied box surfaces the reviewer's reason. No decision actions remain; view-details stays.

func BuildDocsApprovalOutcomeV3BodyWithLang added in v1.12.0

func BuildDocsApprovalOutcomeV3BodyWithLang(
	lang string,
	webLoginURL string,
	docID string,
	content DocsOutcomeContent,
) ([]interface{}, string, error)

BuildDocsApprovalOutcomeV3BodyWithLang renders the Forge-aligned terminal view while preserving the existing result content and server deep link.

func BuildDocsResourceCard

func BuildDocsResourceCard(
	ctx context.Context,
	webLoginURL string,
	docID string,
	resource ResourceCard,
) (json.RawMessage, error)

BuildDocsResourceCard renders an octo/v1 ResourceCard for a docs-notify notification (docs-backend automated flows: share/comment/access request). The deep-link points at octo-web's /d/:docId standalone route (mirrors summaryDeepLink); labels/attribution mapping stay in the producer module.

func BuildDocsResourceCardBodyWithLang added in v1.12.0

func BuildDocsResourceCardBodyWithLang(
	lang string,
	webLoginURL string,
	docID string,
	resource ResourceCard,
) (body []interface{}, deepLink string, err error)

BuildDocsResourceCardBodyWithLang is the fragment-only counterpart of BuildDocsResourceCard used by Registry-backed octo/v1 display Templates (e.g. pkg/cardtmpl/docs_commented). It returns the assembled body (header + optional excerpt + optional FactSet + in-body ActionSet) and the https deep-link, but does NOT marshal the AC top level or write metadata — that is Registry.Render's job. It shares assembleResourceCardBody with the legacy BuildDocsResourceCard wrapper, so migrated cards render byte-identical bodies.

lang is passed explicitly (resolved by the caller from i18n.OutboundLanguage); this helper never touches ctx, matching BuildDocsAccessRequestBodyWithLang.

func BuildSummaryResourceCard

func BuildSummaryResourceCard(
	ctx context.Context,
	webLoginURL string,
	taskID string,
	spaceID string,
	resource ResourceCard,
) (json.RawMessage, error)

func BuildSummaryResourceCardBodyWithLang added in v1.12.0

func BuildSummaryResourceCardBodyWithLang(
	lang string,
	webLoginURL string,
	taskID string,
	spaceID string,
	resource ResourceCard,
) (body []interface{}, deepLink string, err error)

BuildSummaryResourceCardBodyWithLang is the fragment-only counterpart of BuildSummaryResourceCard for Registry-backed octo/v1 summary Templates (roadmap C PR-2: summary.completed / summary.failed). Shape mirrors BuildDocsResourceCardBodyWithLang — returns the assembled body + https deep-link and never marshals the AC top level or writes metadata; that is Registry.Render's job. Both this helper and the legacy BuildSummaryResourceCard share assembleResourceCardBody, so migrated cards render byte-identical bodies.

func DecodeStrictJSON added in v1.13.0

func DecodeStrictJSON(raw []byte, out any) error

DecodeStrictJSON applies the artifact request JSON rules to an enclosing control-plane object before decoding it into out. Unknown struct fields are rejected in addition to duplicate keys and trailing tokens.

func DecodeStrictJSONObject added in v1.13.0

func DecodeStrictJSONObject(raw []byte) (map[string]any, error)

DecodeStrictJSONObject parses one bounded request object while preserving its already-validated value tree for downstream decoders. It is the single-parse handoff used by the card-template control plane; callers must still reject endpoint-specific unknown fields.

func RecordCallback added in v1.12.0

func RecordCallback(id ID, version, actionID, result string)

RecordCallback records a bounded callback outcome for a registry-backed card. Callers must only pass template/action identifiers resolved from registered metadata and the effective server-authored frame.

func RecordFieldsInvalid added in v1.12.0

func RecordFieldsInvalid(id ID, version string)

RecordFieldsInvalid 是 preflight-only path 的导出入口 (R2-8): caller 在 Registry.Render 之前独立跑 schema 校验(如 modules/notify preflightDocsAccessRequestSchema),失败时 Render 不会被触发,`build_total` 就漏一条 400 路径。此入口只允许 result="fields_invalid",view 传空。 用法与直接调 metricBuildResult 等价,只是限定为 preflight 场景避免误用。

func RenderCatalogCardWithProfiles added in v1.13.0

func RenderCatalogCardWithProfiles(
	ctx context.Context,
	catalog Catalog,
	request CatalogRenderRequest,
) (cardDoc json.RawMessage, profile, renderProfile string, err error)

func SanitizeLine added in v1.12.0

func SanitizeLine(s string) string

SanitizeLine collapses any control character (newline, CR, tab, …) in a caller-supplied string to a single space and trims the result. Text-path (plain-text DM) fallbacks are line-structured, so an embedded "\n" in a caller field (title, excerpt, actor name) could otherwise inject a spoofed attribution/label line. Card rendering has its own defence (escapeMarkdown); this is the text-path equivalent. It is a strict superset of strings.TrimSpace for our inputs. Shared source of truth for modules/notify and each L2a Template's FallbackText — do NOT re-implement (G5, roadmap C).

func SetDefaultCatalog added in v1.13.0

func SetDefaultCatalog(c Catalog)

SetDefaultCatalog installs the process runtime reader. Production installs it once in the composition root before module factories are constructed.

func SetDefaultRegistry added in v1.12.0

func SetDefaultRegistry(r *Registry)

SetDefaultRegistry 由 composition root 一次性调用,注入注册完成 + Freeze 的 Registry。 传 nil 用于 test 隔离。重复调用允许(后者覆盖),但生产 wiring 不应发生。

func SetGlobalMetrics added in v1.12.0

func SetGlobalMetrics(m *Metrics)

SetGlobalMetrics 由 composition root 在 NewMetrics 之后一次性调用。 重复调用允许 (后者覆盖),但生产不应发生。

func TruncateRunes added in v1.12.0

func TruncateRunes(value string, limit int) string

TruncateRunes truncates value to at most limit runes, appending an ellipsis when it actually cuts. Exported so producer mapping layers (modules/notify) can pre-truncate display fields to the same schema/render budgets and preserve card delivery, instead of an over-length field flipping to a C1 400 at preflight (see modules/notify.mapDocsCardFieldsToDisplayJSON / mapSummaryCardFieldsToJSON). Wraps the internal truncateRunes so the render layer and ingress layer share one implementation.

Types

type ApprovalActions added in v1.11.0

type ApprovalActions struct {
	ApproveTitle string
	DenyTitle    string
}

type ApprovalRequestAction added in v1.11.0

type ApprovalRequestAction struct {
	Decision string
	Title    string
}

ApprovalRequestAction lets the caller name a bounded, custom Action.Submit button on the generic approval card. Server owns the action ID, the injected owner/action_type metadata, and the card layout; callers only supply the stable callback token (decision) and a display label (title).

The tokens "approve" and "deny" are reserved for the legacy 2-button template; passing either as Decision returns a validation error to keep the server-derived "approval-<decision>" action IDs collision-free with the legacy ApprovalApproveActionID / ApprovalDenyActionID.

type ApprovalRequestCard added in v1.11.0

type ApprovalRequestCard struct {
	Title       string
	Description string
	Owner       string
	ActionType  string
	Data        map[string]string
	// ApproveTitle and DenyTitle drive the localized 2-button template when
	// Actions is nil/empty. Callers using Actions leave both empty.
	ApproveTitle string
	DenyTitle    string
	// Actions, when non-nil, replaces the approve/deny template with 1..N
	// server-built Action.Submit buttons where N = MaxApprovalCustomActions.
	// A nil slice preserves the legacy approve/deny wire form byte-compatibly;
	// an explicit empty slice is a caller bug and rejected by validation.
	Actions []ApprovalRequestAction
}

type ApprovalResultCard added in v1.11.0

type ApprovalResultCard struct {
	Title   string
	Status  string
	Variant string
	Source  string
}

type ArtifactValidationError added in v1.13.0

type ArtifactValidationError struct {
	Category string
	Document string
	// contains filtered or unexported fields
}

ArtifactValidationError exposes only a bounded category and logical document name to HTTP callers. Cause is retained for server logs.

func (*ArtifactValidationError) Error added in v1.13.0

func (e *ArtifactValidationError) Error() string

func (*ArtifactValidationError) Unwrap added in v1.13.0

func (e *ArtifactValidationError) Unwrap() error

type BuildEnv added in v1.12.0

type BuildEnv struct {
	WebLoginURL string // 绝对 https,deep-link 拼接用
	Lang        string // i18n.OutboundLanguage(ctx) 由调用点解析后传入
	SpaceID     string
}

BuildEnv 是 Template.Build 的环境入参,由调用点统一解析并 typed 传入。 禁止在 Template 内部再解析 ctx (i18n.OutboundLanguage) 或引入 map[string]any 上下文。 若某模板需额外 server-only 上下文 (如 actor UID),走 constructor 依赖注入。

type BuildResult added in v1.12.0

type BuildResult struct {
	Body     []any   // AC body 元素
	Actions  []any   // AC 顶层 actions
	Variant  string  // metadata.octo.variant
	DeepLink string  // metadata.webUrl (可选;非空则须绝对 https,空则省略 webUrl)
	Source   *Source // 覆盖 Meta.Source,nil 表示不覆盖
}

BuildResult 是 Template.Build 的返回值,只承载业务片段。 基座 wrapper (Registry.Render) 负责组装完整 AC 顶层 + payload envelope (type=17 / card / card_version / profile) + 注入 metadata。 模板不 marshal AC 顶层、不写 metadata 字段。

type Bundle added in v1.13.0

type Bundle struct {
	Catalog   CatalogDescriptor          `json:"catalog"`
	Manifest  json.RawMessage            `json:"manifest"`
	Schema    json.RawMessage            `json:"schema"`
	Templates map[string]json.RawMessage `json:"templates"`
	Reports   map[string]json.RawMessage `json:"reports,omitempty"`
	Samples   map[string]json.RawMessage `json:"samples"`
	Goldens   map[string]json.RawMessage `json:"goldens,omitempty"`
}

Bundle is the structured, path-free upload contract for JSON templates. Map keys are bounded logical document names, not caller-controlled paths.

func DecodeBundleJSON added in v1.13.0

func DecodeBundleJSON(raw []byte) (Bundle, error)

DecodeBundleJSON rejects duplicate keys, trailing tokens, invalid UTF-8 and out-of-range numbers before converting the request to the typed Bundle.

func DecodeBundleValue added in v1.13.0

func DecodeBundleValue(parsed any) (Bundle, error)

DecodeBundleValue validates and decodes a bundle from an already strictly parsed JSON value. Control-plane envelopes use it to avoid reparsing the nested bundle after duplicate-key, Unicode, depth, and node checks have already covered the complete request tree.

func LoadJSONBundle added in v1.13.0

func LoadJSONBundle(assets fs.FS, root string, catalog CatalogDescriptor) (Bundle, error)

LoadJSONBundle converts a reviewed embedded handoff into the same structured bundle accepted by the runtime compiler. The schema is read exactly once.

type CanonicalBundle added in v1.13.0

type CanonicalBundle []byte

CanonicalBundle is deterministic JSON used for hashing and immutable persistence. Callers must treat the bytes as read-only.

type CardUpdater added in v1.12.0

type CardUpdater interface {
	ReplaceView(context.Context, UpdateTarget, ID, string, State, json.RawMessage, BuildEnv) error
	Append(context.Context, UpdateTarget, json.RawMessage) error
}

func NewCardUpdater added in v1.12.0

func NewCardUpdater(catalog Catalog, mutator mutationGateway) (CardUpdater, error)

type Catalog added in v1.13.0

Catalog is the runtime-only template surface. Registration and default mutation intentionally remain methods on the boot-time Registry only.

func DefaultCatalog added in v1.13.0

func DefaultCatalog() Catalog

DefaultCatalog returns the installed runtime reader. Tests and pre-overlay binaries safely fall back to an adapter over the current frozen Registry.

type CatalogAccess added in v1.13.0

type CatalogAccess struct {
	Purpose   CatalogPurpose
	Principal CatalogPrincipal
}

type CatalogActionContext added in v1.13.0

type CatalogActionContext struct {
	View ViewKey
	Meta TemplateMeta
}

type CatalogActionRequest added in v1.13.0

type CatalogActionRequest struct {
	CatalogExactRequest
	ActionID string
}

type CatalogDefaultRequest added in v1.13.0

type CatalogDefaultRequest struct {
	Access CatalogAccess
	ID     ID
}

type CatalogDescriptor added in v1.13.0

type CatalogDescriptor struct {
	Engine     string `json:"engine"`
	Visibility string `json:"visibility"`
}

CatalogDescriptor contains governance metadata outside the frozen template manifest. It is part of the canonical artifact identity.

type CatalogExactRequest added in v1.13.0

type CatalogExactRequest struct {
	Access  CatalogAccess
	ID      ID
	Version string
}

type CatalogFallbackRequest added in v1.13.0

type CatalogFallbackRequest struct {
	Access  CatalogAccess
	ID      ID
	Version string
	State   State
	Fields  json.RawMessage
	Lang    string
}

type CatalogPrincipal added in v1.13.0

type CatalogPrincipal struct {
	Kind    CatalogPrincipalKind
	ID      string
	SpaceID string
}

func CatalogPrincipalFromProvenance added in v1.14.0

func CatalogPrincipalFromProvenance(provenance cardmsg.CatalogProvenance) (CatalogPrincipal, error)

CatalogPrincipalFromProvenance 把一个已存储的 wire marker 映射为 catalog principal。marker 先过 strict Validate;wire principal 只有 bot 与 internal_producer 两种(space 是 discover-only grant principal、system 是 内部保留值,都不可能出现在存储帧里),未知类型 fail-close。

type CatalogPrincipalKind added in v1.13.0

type CatalogPrincipalKind string
const (
	CatalogPrincipalBot              CatalogPrincipalKind = "bot"
	CatalogPrincipalInternalProducer CatalogPrincipalKind = "internal_producer"
	CatalogPrincipalSystem           CatalogPrincipalKind = "system"
)

type CatalogPurpose added in v1.13.0

type CatalogPurpose string
const (
	CatalogPurposeNewSend        CatalogPurpose = "new_send"
	CatalogPurposeHistoricalEdit CatalogPurpose = "historical_edit"
	CatalogPurposeActionContext  CatalogPurpose = "action_context"
)

type CatalogRenderRequest added in v1.13.0

type CatalogRenderRequest struct {
	Access  CatalogAccess
	ID      ID
	Version string
	State   State
	Fields  json.RawMessage
	Env     BuildEnv
}

type CompileLimits added in v1.13.0

type CompileLimits struct {
	MaxBundleBytes   int
	MaxDocuments     int
	MaxDocumentBytes int
	MaxViews         int
	MaxStates        int
	MaxSamples       int
	MaxGoldens       int
	MaxJSONDepth     int
	MaxJSONNodes     int

	RequireBoundedSchema bool
	RequireOwner         bool
	RequireProtocol      bool
}

CompileLimits is explicit so tests and future engine contracts can lower budgets. Production callers use DefaultCompileLimits; values above the hard defaults are clamped by normalizeCompileLimits.

func DefaultCompileLimits added in v1.13.0

func DefaultCompileLimits() CompileLimits

type CompiledArtifact added in v1.13.0

type CompiledArtifact struct {
	Template        Template
	Meta            TemplateMeta
	Hash            string
	Bundle          CanonicalBundle
	Engine          string
	Visibility      string
	Owner           string
	ContractVersion string
	// contains filtered or unexported fields
}

CompiledArtifact is the result shared by static registration and the runtime validate/publish control plane. It contains no database or activation state.

func CompileJSONArtifact added in v1.13.0

func CompileJSONArtifact(ctx context.Context, bundle Bundle, limits CompileLimits) (*CompiledArtifact, error)

CompileJSONArtifact validates and compiles an untrusted JSON bundle without panicking or accessing databases, the network, or process configuration.

type DeclaredAction added in v1.12.0

type DeclaredAction struct {
	ID               string   `json:"id"`
	Type             string   `json:"type"`
	AssociatedInputs string   `json:"associatedInputs,omitempty"`
	DataKeys         []string `json:"dataKeys,omitempty"`
	InputIDs         []string `json:"inputIds,omitempty"`
}

DeclaredAction 声明卡片顶层或内联的一个 Action。

type DeclaredInput added in v1.12.0

type DeclaredInput struct {
	ID         string `json:"id"`
	Type       string `json:"type"`
	IsRequired bool   `json:"isRequired,omitempty"`
	IsVisible  bool   `json:"isVisible"`
	MaxLength  int    `json:"maxLength,omitempty"`
}

DeclaredInput 声明卡片内的一个 Input.* 元素。 IsVisible=false 的 hidden input (如 deny_reason) 仍必须出现在 body 中, 是 cardmsg.ValidateInputs 的先决条件。

type DeclaredToggle added in v1.12.0

type DeclaredToggle struct {
	ByActionID    string `json:"byActionId"`
	TargetElement string `json:"targetElement"`
	IsVisible     bool   `json:"isVisible"`
}

DeclaredToggle 描述一个 Action.ToggleVisibility 的目标声明。

type DocsAccessRequestV3Content added in v1.12.0

type DocsAccessRequestV3Content struct {
	DocsApprovalContent
	SourceName          string
	PermissionLabel     string
	PermissionRoleLabel string
	MessageTimeDisplay  string
}

DocsAccessRequestV3Content extends the existing production content contract with the display fields needed by the Forge 0.3.0 header and footer. The embedded DocsApprovalContent remains the authority for validation, escaping, and server-authored action data.

type DocsApprovalContent added in v1.11.0

type DocsApprovalContent struct {
	Title              string
	Actor              string
	ActorAvatar        string
	Timestamp          string
	Reason             string
	RequesterSpaceName string
	RequestedBotNames  []string
	Variant            string
	Source             Source

	HeaderLabel  string // e.g. "文档申请" / "Document access"
	StatusLabel  string // e.g. "待你处理" / "Pending"
	BannerSuffix string // e.g. "申请成为此文档的查看者。" (rendered subtle after the bold actor)
	RoleLabel    string // e.g. "申请人" / "Requester"
	ReasonLabel  string // e.g. "申请原因" / "Reason"
}

DocsApprovalContent carries the enriched docs access-request card fields. All string fields except the *Label ones are caller-supplied display strings that this template escapes (escapeMarkdown) and bounds; the labels are server-owned localized copy (producer picks them by language). ActorAvatar is optional and must be an absolute https URL when present (empty => no avatar column).

type DocsOutcomeContent added in v1.11.0

type DocsOutcomeContent struct {
	Title   string
	Variant string
	Source  Source
	Denied  bool // true => denied (attention), false => approved (good)

	HeaderLabel         string // "文档申请"
	SourceName          string // optional document/source display name
	StatusLabel         string // "已允许" / "已拒绝"
	PermissionLabel     string // optional permission vocabulary beside status
	PermissionRoleLabel string // requested role display label
	ReasonLabel         string // "拒绝原因"
	Reason              string // reviewer deny reason (denied only); "" => omit

	Actor                     string
	ActorAvatar               string
	RequesterSpaceName        string
	RequestedBotNames         []string
	RequestedAtDisplay        string
	RequestReason             string
	BannerSuffix              string
	RoleLabel                 string
	RequestReasonLabel        string
	DecisionOperatorName      string
	DecisionOperatorSpaceName string
	MessageTimeDisplay        string
}

DocsOutcomeContent carries the enriched terminal (已允许 / 已拒绝) card fields. Optional requester/source/permission/time fields let registry-backed 0.3 results preserve the pending-card context; legacy callers may leave them empty.

type Fact

type Fact struct {
	Title string
	Value string
}

type ID added in v1.12.0

type ID string

ID 是模板稳定标识,全小写点分隔 (例 "docs.access-request")。

type InteractionReport added in v1.12.0

type InteractionReport struct {
	Actions []DeclaredAction `json:"actions"`
	Inputs  []DeclaredInput  `json:"inputs"`
	Toggles []DeclaredToggle `json:"toggles,omitempty"`
}

InteractionReport 对应 reports/<view>.interaction.json,注册期反序列化后固化。

type Metrics added in v1.12.0

type Metrics struct {
	// contains filtered or unexported fields
}

Metrics 是 pkg/cardtmpl 自打的指标集合,与 internal/carddispatch.Metrics 分开; 后者只覆盖 Sender.Send 之后的派发结果,看不到 Registry.Lookup / Build 阶段。

label 基数 = 注册表大小 (template_id 值只来自 Template.ID() 硬编码),天花板 可预期 <20,无基数爆炸风险 (§13)。

func NewMetrics added in v1.12.0

func NewMetrics(reg prometheus.Registerer) *Metrics

NewMetrics 构造并注册指标。传 nil registerer 得到 no-op 实例。

type Registry added in v1.12.0

type Registry struct {
	// contains filtered or unexported fields
}

Registry 是进程内模板注册中心。 - Register 只能在 composition root 期调用;Freeze 之后再 Register/SetDefault → panic; - Freeze 之后 Lookup 无锁并发;List / RegisteredForTest 也线程安全。

func DefaultRegistry added in v1.12.0

func DefaultRegistry() *Registry

DefaultRegistry 返回启动期 built-in Registry。未注入 → nil。

func NewRegistry added in v1.12.0

func NewRegistry() *Registry

NewRegistry 构造空注册表。composition root 之后立即 Freeze()。

func (*Registry) ActionView added in v1.12.0

func (r *Registry) ActionView(id ID, version, actionID string) (ViewKey, error)

ActionView resolves one declared Action.Submit to its registered view. It is used by the action ingress after extracting template identity from the effective server-authored frame; OpenUrl and undeclared actions are rejected.

func (*Registry) Freeze added in v1.12.0

func (r *Registry) Freeze()

Freeze 冻结注册表。之后 Register/SetDefault → panic;Lookup 无锁并发。

func (*Registry) List added in v1.12.0

func (r *Registry) List() []TemplateMeta

List 导出已注册模板元数据 (稳定顺序,按 id@version 升序),供 /v1/message/card/templates 使用。 R2-6: 深拷贝 Views / stateIndex / interactions / *ActionContract / Manifest bytes, 保证外部持有者(如 HTTP handler 或 test)修改返值不会影响 Registry 内部 (frozen 后 契约仍不可变)。热路径 Render 走 renderCore 直接读 e.meta 不经过 List,不受影响。

func (*Registry) Lookup added in v1.12.0

func (r *Registry) Lookup(id ID, version string) (Template, error)

Lookup 查找模板。version=="" 走 SetDefault;未命中返 ErrTemplateUnknown。

func (*Registry) Register added in v1.12.0

func (r *Registry) Register(t Template, assets embed.FS, root string)

Register 载入 assets 下的模板契约并注册 t。任何一致性问题 → panic (fail-close)。

  • <root>/manifest.json 必须存在;views/states 完整;owner+actionType 与 t.Meta 一致;
  • <root>/contract/data.schema.json 必须能 Compile 通过;
  • 每个 v2 view 必须有对应 <root>/reports/<view>.interaction.json;
  • <root>/samples/*.json 全部通过 schema 校验;
  • owner 必须在 L2a allowlist 内 (L2b 未开放,前缀 ext.* 也拒绝)。

Register 期 t 只提供未装配 Meta 的骨架实例;真正的 TemplateMeta 由 Register 组装并 用 setMeta 注入回 t (通过运行时接口 metaSetter,由 pilot Template 实现)。

func (*Registry) RegisterJSON added in v1.12.0

func (r *Registry) RegisterJSON(assets embed.FS, root string)

RegisterJSON registers a JSON-mode card from its handoff assets. Every manifest view must declare a `template` path; each file is parsed into a reusable AST at register time. It then delegates to Register, which assembles the TemplateMeta (schema / views / interactions), injects it via SetMeta, and runs the sample self-check — so JSON cards get the identical fail-close registration guarantees as Go cards (missing template / schema / bad sample / whitelist violation all panic at boot, never at first render).

func (*Registry) RegisteredForTest added in v1.12.0

func (r *Registry) RegisteredForTest() []Template

RegisteredForTest 返回与生产相同的注册集合,供 conformance test 用。

func (*Registry) Render added in v1.12.0

func (r *Registry) Render(
	ctx context.Context,
	id ID,
	version string,
	state State,
	fields json.RawMessage,
	env BuildEnv,
) (map[string]any, error)

Render 是"Template.Build → 完整 InteractiveCard payload" 的唯一入口。 业务代码只调 Render;不允许直接调 Template.Build 后自己拼装 payload/metadata。

流水线 (与 docs/platform-card-base.md §5 对齐):

  1. Lookup(id, version) 命中 Template + Meta;
  2. Meta.InputSchema.Validate(fields) + optional JSON-template semantic constraints → 失败返 ErrFieldsInvalid;
  3. Meta.ViewFor(state) 决定 view/profile → 未注册 state 返 ErrStateUnknown;
  4. Template.Build(ctx, state, fields, env) 拿 BuildResult;
  5. BuildResult.DeepLink 可选:非空则校验为绝对 https,空则跳过(无 metadata.webUrl);
  6. 组装 AC 顶层文档 + 注入 metadata.octo.{protocol, template, variant, source};DeepLink 非空时再注入 metadata.webUrl;
  7. 构造 InteractiveCard payload envelope (type=17 / card / card_version / profile);
  8. cardmsg.Validate(payload) → 失败包裹 ErrRenderFailed 返回。

返回:payload 是完整的 map[string]any (含 type=17 与 card),供调用方按需 拆出 payload["card"] 作 carddispatch.Card.Document 使用。

func (*Registry) RenderCard added in v1.12.0

func (r *Registry) RenderCard(
	ctx context.Context,
	id ID,
	version string,
	state State,
	fields json.RawMessage,
	env BuildEnv,
) (cardDoc json.RawMessage, profile string, err error)

RenderCard 是便捷函数:返回 payload["card"] 部分 (裸 AC 文档) 供 carddispatch.Card.Document 直接使用,同时返回 profile 与完整 payload。

func (*Registry) RenderCardWithProfiles added in v1.12.0

func (r *Registry) RenderCardWithProfiles(
	ctx context.Context,
	id ID,
	version string,
	state State,
	fields json.RawMessage,
	env BuildEnv,
) (cardDoc json.RawMessage, profile, renderProfile string, err error)

RenderCardWithProfiles is the envelope-preserving counterpart used by internal dispatch/update paths that must carry both the wire capability profile and the optional visual compatibility profile.

func (*Registry) SetDefault added in v1.12.0

func (r *Registry) SetDefault(id ID, version string)

SetDefault 显式设置某 id 的默认版本。Freeze 之后调用 → panic。

type ResourceCard

type ResourceCard struct {
	IconURL     string
	Title       string
	Attribution string
	Excerpt     string
	Facts       []Fact
	CopyText    string
	// Variant is the stable, low-cardinality identifier the renderer / client
	// can key off to style card families independently (e.g. "summary.completed",
	// "summary.failed", "docs.shared", "docs.commented"). Emitted into
	// `metadata.octo.variant` on the AdaptiveCard root; unknown values pass
	// straight through — the renderer decides whether to specialise.
	// See docs/summary-notify-card.md §2 for the reserved namespace.
	Variant string
	// Source names the originating capability so renderers can surface a
	// "来自 XX" / "From XX" chip / badge (角标) next to the card. Both fields
	// are optional and land in `metadata.octo.source`; the current template
	// does NOT auto-render them into the card body — surfacing is a renderer
	// decision (chip / prefix / silent), which lets the visual pilot stay
	// unchanged while machine consumers already have the source signal.
	Source Source
}

type RuntimeActivation added in v1.13.0

type RuntimeActivation struct {
	Exists   bool
	Version  string
	Status   RuntimeActivationStatus
	Revision uint64
}

type RuntimeActivationStatus added in v1.13.0

type RuntimeActivationStatus string
const (
	RuntimeActivationActive   RuntimeActivationStatus = "active"
	RuntimeActivationDisabled RuntimeActivationStatus = "disabled"
)

type RuntimeArtifactMeta added in v1.13.0

type RuntimeArtifactMeta struct {
	ID              ID
	Version         string
	Source          RuntimeSource
	Engine          string
	Hash            string
	Owner           string
	Visibility      string
	Protocol        string
	ContractVersion string
	Blocked         bool
}

type RuntimeArtifactStore added in v1.13.0

type RuntimeArtifactStore interface {
	LoadActivation(context.Context, ID) (RuntimeActivation, error)
	LoadArtifactMeta(context.Context, ID, string) (RuntimeArtifactMeta, error)
	LoadArtifactBundle(context.Context, ID, string, string) (CanonicalBundle, error)
}

type RuntimeCatalog added in v1.13.0

type RuntimeCatalog struct {
	// contains filtered or unexported fields
}

func NewRuntimeCatalog added in v1.13.0

func NewRuntimeCatalog(
	registry *Registry,
	store RuntimeArtifactStore,
	config RuntimeCatalogConfig,
) (*RuntimeCatalog, error)

func (*RuntimeCatalog) ActionContext added in v1.13.0

func (*RuntimeCatalog) CheckReady added in v1.13.0

func (c *RuntimeCatalog) CheckReady() error

CheckReady reports whether startup reconciliation has established a safe authoritative view for default and dynamic catalog paths. It performs no IO and is intended for the process readiness probe composed by main.

func (*RuntimeCatalog) FallbackText added in v1.13.0

func (c *RuntimeCatalog) FallbackText(ctx context.Context, request CatalogFallbackRequest) (string, error)

func (*RuntimeCatalog) MetaDefault added in v1.13.0

func (c *RuntimeCatalog) MetaDefault(ctx context.Context, request CatalogDefaultRequest) (TemplateMeta, error)

func (*RuntimeCatalog) MetaExact added in v1.13.0

func (c *RuntimeCatalog) MetaExact(ctx context.Context, request CatalogExactRequest) (TemplateMeta, error)

func (*RuntimeCatalog) Render added in v1.13.0

func (c *RuntimeCatalog) Render(ctx context.Context, request CatalogRenderRequest) (map[string]any, error)

type RuntimeCatalogConfig added in v1.13.0

type RuntimeCatalogConfig struct {
	MaxCacheEntries  int
	MaxCacheBytes    int
	CompileTimeout   time.Duration
	CheckReady       func() error
	AuthorizeDynamic RuntimeDynamicAuthorizeFunc
	Hooks            RuntimeCatalogHooks
}

type RuntimeCatalogHooks added in v1.13.0

type RuntimeCatalogHooks struct {
	OnResolve   func(RuntimeSource, string)
	OnCache     func(string)
	OnCacheSize func(entries, bytes int)
}

type RuntimeDynamicAuthorizeFunc added in v1.13.0

type RuntimeDynamicAuthorizeFunc func(context.Context, CatalogAccess, RuntimeArtifactMeta) error

type RuntimeSource added in v1.13.0

type RuntimeSource string
const (
	RuntimeSourceStatic  RuntimeSource = "static"
	RuntimeSourceDynamic RuntimeSource = "dynamic"
)

type Source

type Source struct {
	// Label is a human-readable source name. It is already localized by the
	// caller: producers pass it from their per-language label set
	// (modules/notify summaryLabelsFor/docsLabelsFor, keyed by
	// i18n.OutboundLanguage) — e.g. "智能总结"/"Smart Summary",
	// "文档"/"Docs" — so this template stores whatever localized string it
	// receives and does not itself pick a language.
	Label string
	// IconURL is an optional absolute https icon URL; renderers may use it for
	// the chip. Empty by default (the pilot sets Label only).
	IconURL string
}

Source describes the producer family that authored the card, for both display badging and machine identification. Values are server-picked (never user-supplied) and land in `metadata.octo.source`.

type State added in v1.12.0

type State string

State 是业务状态值 (例 "pending" / "approved" / "rejected")。 每个 State 在 manifest.views[*].states 里只能属于一个 view。

type StaticCatalog added in v1.13.0

type StaticCatalog struct {
	// contains filtered or unexported fields
}

func NewStaticCatalog added in v1.13.0

func NewStaticCatalog(registry *Registry) (*StaticCatalog, error)

func (*StaticCatalog) ActionContext added in v1.13.0

func (*StaticCatalog) FallbackText added in v1.13.0

func (c *StaticCatalog) FallbackText(ctx context.Context, request CatalogFallbackRequest) (string, error)

func (*StaticCatalog) MetaDefault added in v1.13.0

func (c *StaticCatalog) MetaDefault(_ context.Context, request CatalogDefaultRequest) (TemplateMeta, error)

func (*StaticCatalog) MetaExact added in v1.13.0

func (c *StaticCatalog) MetaExact(_ context.Context, request CatalogExactRequest) (TemplateMeta, error)

func (*StaticCatalog) Render added in v1.13.0

func (c *StaticCatalog) Render(ctx context.Context, request CatalogRenderRequest) (map[string]any, error)

type Template added in v1.12.0

type Template interface {
	// Meta 返回注册期固化静态元数据的**防御性深拷贝** (m.Clone())。调用方可安全
	// 读取甚至修改返值而不污染 Registry 内部 —— 冻结后契约必须不可变,直接返回
	// 内部含 map/slice/*ptr 的浅拷贝等于把内部状态交给外部改坏 (还有并发 race)。
	// 因此本方法非零成本 (克隆若干小 map),但 Render 热路径内部直接读 entry.meta
	// 不经过 Meta(),吞吐不受影响 (R3-2)。
	Meta() TemplateMeta

	// Build 渲染指定业务状态下的卡片业务片段。
	// - fields 已经过 Meta().InputSchema 校验;
	// - state 到 view 的映射由 Meta().ViewFor(state) 提供;
	// - 产物只包含业务片段,不 marshal AC 顶层,不写 metadata。
	Build(ctx context.Context, state State, fields json.RawMessage, env BuildEnv) (BuildResult, error)

	// FallbackText 返回纯文本 fallback,渲染失败/低版本客户端/gate 关闭时使用。
	FallbackText(state State, fields json.RawMessage, lang string) (string, error)
}

Template 是每张业务卡实现的接口。3 个行为方法,元数据一次拿走。

type TemplateActionContract added in v1.12.0

type TemplateActionContract struct {
	Owner      string
	ActionType string
}

TemplateActionContract 声明本卡 Submit action 归属的 callback 路由, 与 cardactiondispatch.RouteSpec 的 {owner, action_type} 对齐。 纯展示卡在 TemplateMeta.ActionContract 置 nil。

type TemplateMeta added in v1.12.0

type TemplateMeta struct {
	// ID / Version / Protocol 三字段唯一标识一版本模板。
	ID       ID
	Version  string
	Protocol string
	// RenderProfileCompatibility is the stable type-17 envelope value consumed
	// by clients; empty permanently selects the legacy renderer. The exact Forge
	// artifact remains provenance-only data in Manifest.
	RenderProfileCompatibility string
	// Views 承载 manifest 里所有已声明的视图 (含未激活的占位视图)。
	Views map[ViewKey]ViewSpec
	// ActionContract 非 nil 时,本卡的所有 Action.Submit.data 必须包含
	// {owner:Owner, action_type:ActionType}。校验时机:**注册期、且仅对有 sample 的
	// v2 view**(selfCheckSamples→assertActionContract,遍历顶层与内联 ActionSet)。
	// renderCore 运行期不再重复断言(pilot 由 TestActionContract_ThreeWayConsistency
	// 覆盖)。
	ActionContract *TemplateActionContract
	// Manifest 保留原始 manifest.json bytes,供 /v1/message/card/templates 端点透出。
	Manifest json.RawMessage
	// InputSchema 是调用方入参的 JSON Schema (draft-07);Registry.Render 前置校验。
	InputSchema *jsonschema.Schema
	// Source 是 metadata.octo.source 默认值;BuildResult.Source 非 nil 时覆盖。
	Source Source
	// contains filtered or unexported fields
}

TemplateMeta 是注册期一次性构造的静态元数据。内部持有 map/slice/*ptr, 对外暴露必须经 Clone() 深拷贝 (Template.Meta() / Registry.List()), 保证冻结后契约不可变、并发读安全。

func (TemplateMeta) Clone added in v1.12.0

func (m TemplateMeta) Clone() TemplateMeta

Clone 深拷贝 TemplateMeta,让外部持有者 (Template.Meta() 返值 / List() 返值 / 未来 HTTP 端点) 修改不会影响 Registry 内部 (R3-2:冻结后契约不可变;struct 里 含 map/slice/*ptr 共享,直接返值等于让外部改内部状态,还有并发 race)。 InputSchema 是编译好的 jsonschema.Schema (santhosh-tekuri 库持有),对外只暴露 Validate、内部不可变,故共享指针安全,不深拷贝。

func (TemplateMeta) Interaction added in v1.12.0

func (m TemplateMeta) Interaction(view ViewKey) (InteractionReport, bool)

Interaction 返回 view 的机读交互契约。非 v2 view 返回 ok=false。

func (TemplateMeta) ViewFor added in v1.12.0

func (m TemplateMeta) ViewFor(state State) (ViewKey, bool)

ViewFor 返回 state 归属的视图。业务代码不允许自行维护映射,统一走本方法。

type UpdateTarget added in v1.12.0

type UpdateTarget struct {
	Target     carddispatch.Target
	SenderUID  string
	MessageID  string
	MessageSeq uint32
	CardSeq    int64
}

UpdateTarget binds a render/update to one authoritative stored message. CardSeq is the positive sequence enforced by the CardMutator CAS. ReplaceView requires it strictly greater than the stored frame's card_seq (monotonic, as the CAS mandates). Append additionally requires it to be exactly consecutive (snapshot.CardSeq+1): a progress-frame appender owns its own frame numbering, so a gap signals a lost/out-of-order frame and is rejected as a conflict.

type ViewKey added in v1.12.0

type ViewKey string

ViewKey 是模板内视图名 (例 "pending" / "result")。

type ViewSpec added in v1.12.0

type ViewSpec struct {
	// WireProfile 是渲染 profile,取值 cardmsg.ProfileV1 或 cardmsg.ProfileV2。
	WireProfile string
	// States 是该视图承载的业务状态集合,manifest 内跨 view 唯一。
	States []State
}

ViewSpec 视图静态元数据,由 manifest.views 反序列化得到。

Directories

Path Synopsis
Package aireasoningprocess wires the AI reasoning-process progress card and its immutable successors into the cardtmpl base.
Package aireasoningprocess wires the AI reasoning-process progress card and its immutable successors into the cardtmpl base.
Package docsaccessrequest 实现 L2a pilot 卡片 docs.access-request@0.2.0。
Package docsaccessrequest 实现 L2a pilot 卡片 docs.access-request@0.2.0。
Package docscommented 实现 L2a 平台通知卡 docs.commented@0.1.0。
Package docscommented 实现 L2a 平台通知卡 docs.commented@0.1.0。
Package docsshared 实现 L2a 平台通知卡 docs.shared@0.1.0(v1 纯展示)。
Package docsshared 实现 L2a 平台通知卡 docs.shared@0.1.0(v1 纯展示)。
Package jsontmpl is a dependency-free evaluator for the bounded subset of the Adaptive Card Templating language used by Registry-backed JSON card templates (roadmap E1).
Package jsontmpl is a dependency-free evaluator for the bounded subset of the Adaptive Card Templating language used by Registry-backed JSON card templates (roadmap E1).
Package summarycompleted 实现 L2a 平台通知卡 summary.completed@0.1.0。
Package summarycompleted 实现 L2a 平台通知卡 summary.completed@0.1.0。
Package summaryfailed 实现 L2a 平台通知卡 summary.failed@0.1.0。
Package summaryfailed 实现 L2a 平台通知卡 summary.failed@0.1.0。

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址