util

package
v0.0.0-...-c1ba7d0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: AGPL-3.0 Imports: 113 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BuiltinPluginSkillID      = "builtin:" + PluginDevelopmentSkillName
	BuiltinPluginSkillVersion = "1.0.0"
)
View Source
const (
	TLSCACertFilename = "ca.crt"
	TLSCAKeyFilename  = "ca.key"
	TLSCertFilename   = "cert.pem"
	TLSKeyFilename    = "key.pem"
)
View Source
const (
	BazaarStatServer = "https://bazaar.b3logfile.com" // 集市包统计服务地址,七牛云,全球 CDN
	BazaarOSSServer  = "https://oss.b3logfile.com"    // 云端对象存储地址,七牛云,仅用于读取集市包,全球 CDN

	BazaarRepo    = "https://github.com/siyuan-note/bazaar"      // 集市仓库,用于集市资源更新
	CommunityRepo = "https://github.com/siyuan-community/siyuan" // 社区版仓库,用于更新
)
View Source
const (
	MaxCustomFontSize      int64 = 64 * 1024 * 1024
	CustomFontFamilyPrefix       = "SiYuanCustomFont-"
)
View Source
const (
	DecisionProviderTypeSafe = "typesafe"
	DecisionProviderOpenAI   = "openai"
)
View Source
const (
	BLOCK_BITS = 22 // Indicate that the blocksize is 4M
	BLOCK_SIZE = 1 << BLOCK_BITS
)
View Source
const (
	FontSpacingProportional  = "proportional"
	FontSpacingDual          = "dual"
	FontSpacingMonospace     = "monospace"
	FontSpacingCharacterCell = "character-cell"
)
View Source
const (
	OpenAIProtocolChatCompletions = "openai"
	OpenAIProtocolResponses       = "openai-responses"
)
View Source
const (
	PluginProjectMissingRevision       = "missing"
	PluginProjectMaxFiles              = 1024
	PluginProjectMaxFileBytes    int64 = 16 * 1024 * 1024
	PluginProjectMaxBytes        int64 = 64 * 1024 * 1024
)
View Source
const (
	EvtSQLHistoryRebuild      = "sql.history.rebuild"
	EvtSQLAssetContentRebuild = "sql.assetContent.rebuild"
)
View Source
const (
	SortModeNameASC         = iota // 0:文件名字母升序
	SortModeNameDESC               // 1:文件名字母降序
	SortModeUpdatedASC             // 2:文件更新时间升序
	SortModeUpdatedDESC            // 3:文件更新时间降序
	SortModeAlphanumASC            // 4:文件名自然数升序
	SortModeAlphanumDESC           // 5:文件名自然数降序
	SortModeCustom                 // 6:自定义排序
	SortModeRefCountASC            // 7:引用数升序
	SortModeRefCountDESC           // 8:引用数降序
	SortModeCreatedASC             // 9:文件创建时间升序
	SortModeCreatedDESC            // 10:文件创建时间降序
	SortModeSizeASC                // 11:文件大小升序
	SortModeSizeDESC               // 12:文件大小降序
	SortModeSubDocCountASC         // 13:子文档数升序
	SortModeSubDocCountDESC        // 14:子文档数降序
	SortModeFileTree               // 15:使用文档树排序规则

	SortModeUnassigned = 256 // 256:未指定排序规则,按照笔记本优先于文档树获取排序规则
)
View Source
const (
	TextFileRevisionConflict    = "revision_conflict"
	TextFileInvalidPath         = "invalid_path"
	TextFileUnsupportedEncoding = "unsupported_encoding"
	TextFileTooLarge            = "too_large"
	TextFileBackupFailed        = "backup_failed"
	TextFileResultUnknown       = "result_unknown"
	TextFileWriteFailed         = "write_failed"
	TextFileCancelled           = "cancelled"
)
View Source
const (
	// ClientTLSHeader 由本机的固定端口反向代理写入,标记客户端到反代这一跳是否使用 TLS。
	// 反代以 HTTPS 回源内核,若不额外标记,内核会把明文客户端的连接误判为 TLS。
	ClientTLSHeader = "X-SiYuan-Client-TLS"

	// ClientTLSHeaderValue 为标记 TLS 的头部取值。
	ClientTLSHeaderValue = "1"

	// ClientTLSHeaderPlaintextValue 为标记客户端使用明文连接的头部取值。
	ClientTLSHeaderPlaintextValue = "0"

	// StrictTransportSecurityValue 为 HTTPS 响应附加的 HSTS 策略,有效期一年。
	StrictTransportSecurityValue = "max-age=31536000"
)
View Source
const (
	PushProgressCodeProgressed = 0 // 有进度
	PushProgressCodeEndless    = 1 // 无进度
	PushProgressCodeEnd        = 2 // 关闭进度
)
View Source
const (
	ContainerStd     = "std"     // 桌面端
	ContainerDocker  = "docker"  // Docker 容器端
	ContainerAndroid = "android" // Android 端
	ContainerIOS     = "ios"     // iOS 端
	ContainerHarmony = "harmony" // 鸿蒙端

	LocalHost = "127.0.0.1" // 伺服地址
	FixedPort = "6806"      // 固定端口
)
View Source
const AnthropicProtocolMessages = "anthropic-messages"
View Source
const DatabaseVer = "202607031200"

DatabaseVer 数据库版本。 格式:yyyyMMddHHmm。修改表结构时需要更新此值,启动时会检测版本变化, 若不一致则自动移除旧数据库文件并重建表结构,同时触发全量重建索引。

View Source
const DecisionJSONMaxBytes = 256 * 1024
View Source
const DecisionMaxBytes = 1024 * 1024

DecisionMaxBytes 限制单次请求和响应的内存占用,不替代供应商的 token 限制。

View Source
const DefaultLargeFileWarningSize = 8
View Source
const DefaultUseSingleLineSave = true
View Source
const (
	// EncryptionSpec 表示 AES-GCM 密文信封规范版本。
	EncryptionSpec byte = 1
)
View Source
const GeminiProtocolInteractions = "gemini-interactions"
View Source
const LocalProxyHeader = "X-Siyuan-Local-Proxy"

LocalProxyHeader 是内置 fixed-port 代理回源时携带的进程内标记头。 第三方反向代理无法得知该标记,带转发头的请求不能再据此获得本机信任。

View Source
const LockScreenWallpaperMaxBytes = 10 << 20
View Source
const MaxAgentInstructionsSize = 32 * 1024
View Source
const MaxTextFileBytes = 8 * 1024 * 1024
View Source
const MaxToolOutputChars = 40000
View Source
const MaxUIProcessCount = 64

MaxUIProcessCount UI 进程注册表条目数上限。

View Source
const OperationStallLogName = "operation-stall.log"
View Source
const PluginDevelopmentSkillName = "siyuan-plugin-development"
View Source
const (
	// SQLFlushInterval 为数据库事务队列写入间隔。
	SQLFlushInterval = 3000 * time.Millisecond
)
View Source
const SessionCookieName = "siyuan"

SessionCookieName 是会话 Cookie 的名称。Cookie 不按端口隔离,同一主机上的各工作空间共用该 Cookie。

View Source
const StatusBarVersion = 1

StatusBar 底部状态栏配置。https://github.com/siyuan-note/siyuan/issues/16236

View Source
const Ver = "3.8.10"

Variables

View Source
var (
	TesseractBin     = "tesseract"
	TesseractEnabled bool
	TesseractMaxSize = 2 * 1000 * uint64(1000)
	TesseractLangs   []string
)
View Source
var (
	NodeOCRQueue     []string
	NodeOCRQueueLock = sync.Mutex{}
)
View Source
var (
	SSL       = false
	UserAgent = "SiYuan/" + Ver
)
View Source
var (
	SiYuanAssetsImage = []string{".apng", ".ico", ".cur", ".jpg", ".jpe", ".jpeg", ".jfif", ".pjp", ".pjpeg", ".png", ".gif", ".webp", ".bmp", ".svg", ".avif", ".tiff", ".tif", ".heic", ".heif"}
	SiYuanAssetsAudio = []string{".mp3", ".wav", ".ogg", ".m4a", ".aac", ".flac"}
	SiYuanAssetsVideo = []string{".mov", ".weba", ".mkv", ".mp4", ".webm"}
)
View Source
var (
	UseSingleLineSave    = NewAtomicValue(DefaultUseSingleLineSave)    // UseSingleLineSave 是否使用单行保存 .sy 和数据库 .json 文件。
	LargeFileWarningSize = NewAtomicValue(DefaultLargeFileWarningSize) // LargeFileWarningSize 大文件警告大小,单位:MB
)
View Source
var (
	Langs           = map[string]map[int]string{}
	TimeLangs       = map[string]map[string]any{}
	TaskActionLangs = map[string]map[string]any{}
	TrayMenuLangs   = map[string]map[string]any{}
	AttrViewLangs   = map[string]map[string]any{}
)
View Source
var (
	ErrSkillBinary   = errors.New("binary files cannot be edited as text")
	ErrSkillEncoding = errors.New("only UTF-8 text files can be edited")
	ErrSkillTooLarge = errors.New("text files must be at most 8 MiB")
)
View Source
var (
	WebSocketServer *melody.Melody

	// ReloadDocInfoGuard 由 model 层注入,在广播 docInfo 前检查 box 是否仍处于可广播状态。
	// 加密笔记本锁定后返回 false,防止 500ms 延迟任务在锁定后泄漏明文元数据。
	ReloadDocInfoGuard func(boxID string) bool
)
View Source
var (
	RunInContainer             = false // 是否运行在容器中
	SiYuanAccessAuthCodeBypass = false // 是否跳过空锁屏密码检查
	AttachUI                   = false // 是否绑定桌面 UI 进程生命周期(Electron 拉起时为 true,手动 serve 为 false)
	EnablePprof                = false // 是否注册未鉴权的调试端点,仅调试时显式开启,切勿在对外开放的实例上使用
	FixedPortEnabled           = true  // 是否启动额外的 6806 固定端口反代,不影响主服务监听端口
)
View Source
var (
	HttpServer  *http.Server // HTTP 伺服器实例
	HttpsServer *http.Server // HTTPS 伺服器实例
	HttpServing = false      // 是否 HTTP 伺服已经可用

	SafeMode = false // 是否以安全模式启动:禁用代码片段、插件、自定义主题与图标
)
View Source
var (
	HomeDir = systemHomeDir

	WorkingDir, _ = os.Getwd()

	WorkspaceDir       string        // 工作空间目录路径
	WorkspaceName      string        // 工作空间名称
	WorkspaceLock      *flock.Flock  // 工作空间锁
	ConfDir            string        // 配置目录路径
	DataDir            string        // 数据目录路径
	RepoDir            string        // 仓库目录路径
	HistoryDir         string        // 数据历史目录路径
	TempDir            string        // 临时目录路径
	QueueDir           string        // 队列目录路径
	LogPath            string        // 配置目录下的日志文件 siyuan.log 路径
	DBName             = "siyuan.db" // SQLite 数据库文件名
	DBPath             string        // SQLite 数据库文件路径
	HistoryDBPath      string        // SQLite 历史数据库文件路径
	AssetContentDBPath string        // SQLite 资源文件内容数据库文件路径
	BlockTreeDBPath    string        // 区块树数据库文件路径
	AppearancePath     string        // 配置目录下的外观目录 appearance/ 路径
	ThemesPath         string        // 数据目录下的第三方主题 themes/ 路径
	IconsPath          string        // 数据目录下的第三方图标 icons/ 路径
	SnippetsPath       string        // 数据目录下的 snippets/ 路径
	ShortcutsPath      string        // 用户家目录下的快捷方式目录路径 home/.config/siyuan/shortcuts/

	UIProcessIDs = sync.Map{} // UI 进程 ID
)
View Source
var (
	ServerURL  *url.URL // 内核服务 URL
	ServerPort = "0"    // HTTP/WebSocket 端口,0 为使用随机端口

	ReadOnly       bool
	AccessAuthCode string
	Lang           = ""

	Container        string // docker, android, ios, harmony, std
	ISMicrosoftStore bool   // 桌面端是否是微软商店版
)
View Source
var CLILogLevel string

CLILogLevel 在 CLI 子命令通过 --log-level 显式指定日志级别时被设置,model.InitConf 末尾据此跳过对 logging.SetLogLevel 的覆盖,使命令行参数优先于 conf.json 的 system.logLevel。

View Source
var CurrentCloudRegion = 0
View Source
var DisabledFeatures []string
View Source
var ErrAgentInstructionsConflict = errors.New("AGENTS.md changed; reload it before saving")
View Source
var ErrAgentInstructionsLocationConflict = errors.New("data/ai/AGENTS.md and data/storage/ai/AGENTS.md differ; merge the files and remove the old file")
View Source
var ErrAgentInstructionsTooLarge = errors.New("AGENTS.md must be at most 32 KiB")
View Source
var ErrDecisionRefused = errors.New("decision provider refused to answer a question")

ErrDecisionRefused 区分供应商拒答和格式错误,不携带原始响应或笔记正文。

View Source
var ErrFileChanged = errors.New("source changed during operation")

ErrFileChanged 表示扫描后的源文件已变化,调用方必须保留当前文件并重新读取。

View Source
var ErrInvalidID = errors.New("invalid ID argument")

ErrInvalidID 表示块或笔记本 ID 不是合法的 SiYuan ID 形态。

View Source
var ErrInvalidLockScreenWallpaper = errors.New("invalid lock screen wallpaper")
View Source
var ErrPandocNotFound = errors.New("not found executable pandoc")
View Source
var IsExiting = atomic.Bool{}

IsExiting 是否正在退出程序。

View Source
var IsUILoaded atomic.Bool

IsUILoaded 是否已经加载了 UI。

View Source
var LangLegacyToBCP47 = map[string]string{
	"zh_CN":  "zh-CN",
	"zh_CHT": "zh-TW",
	"en_US":  "en",
	"de_DE":  "de",
	"fr_FR":  "fr",
	"es_ES":  "es",
	"pt_BR":  "pt-BR",
	"it_IT":  "it",
	"ja_JP":  "ja",
	"ko_KR":  "ko",
	"ru_RU":  "ru",
	"uk_UA":  "uk",
	"pl_PL":  "pl",
	"nl_NL":  "nl",
	"ar_SA":  "ar",
	"he_IL":  "he",
	"hi_IN":  "hi",
	"id_ID":  "id",
	"th_TH":  "th",
	"tr_TR":  "tr",
	"sk_SK":  "sk",
	"sr_RS":  "sr",
}

langLegacyToBCP47 从历史下划线标识映射到 BCP 47 标准语言代码。

View Source
var LocalProxyToken = newLocalProxyToken()

LocalProxyToken 是仅存在于当前进程内的随机标记,由内置 fixed-port 代理注入。

View Source
var MarkdownSettings = NewAtomicValue(NewMarkdown())

MarkdownSettings 运行时 Markdown 配置。

View Source
var MobileOSVer string

MobileOSVer 移动端操作系统版本。

View Source
var Mode = "prod"

var Mode = "dev"

View Source
var NotificationsCfg = NewAtomicValue[*Notifications](nil)
View Source
var (
	RhyCacheDuration = int64(3600 * 6)
)
View Source
var SK = []byte("696D897C9AA0611B")
View Source
var SearchCaseSensitive = NewAtomicValue(false)
View Source
var SearchHanSensitive = NewAtomicValue(true)

SearchHanSensitive 是否区分繁简,由 sql.SetHanSensitive 维护;默认 true 与既往行为一致

View Source
var StatusBarCfg = NewAtomicValue[*StatusBar](nil)
View Source
var SystemTempDir = os.TempDir()

SystemTempDir 保存工作空间初始化重定向之前的系统临时目录。

View Source
var WrongAuthCount int

Functions

func AESDecrypt

func AESDecrypt(cryptStr string) []byte

func AESEncrypt

func AESEncrypt(str string) string

func AddPushChan

func AddPushChan(session *melody.Session)

func AgentInstructionsError

func AgentInstructionsError(err error, language string) string

func AgentInstructionsPath

func AgentInstructionsPath() string

func AppearancePackagePath

func AppearancePackagePath(kind, name string) string

AppearancePackagePath 按包名区分内置资源和参与同步的第三方资源。

func AssetName

func AssetName(name, newID string) string

func AuthCodeEquals

func AuthCodeEquals(a, b string) bool

AuthCodeEquals 恒定时间比较认证码,避免通过响应时间差异猜测秘密。

func AuthThrottleCheck

func AuthThrottleCheck(key string) (retryAfter int)

AuthThrottleCheck 返回 key 剩余锁定秒数,0 表示未锁定。

func AuthThrottleFail

func AuthThrottleFail(key string)

AuthThrottleFail 记录一次认证失败,达到阈值后按指数退避锁定。

func AuthThrottleReset

func AuthThrottleReset(key string)

AuthThrottleReset 认证成功后清除失败计数。

func BatchGetEmbeddings

func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, dimensions, timeout int) (ret [][]float32, err error)

func BeginPluginProjectMutation

func BeginPluginProjectMutation(grant *PluginDevelopmentGrant, name, oldRevision, newRevision string, temporaryPaths ...string) error

func BeginPluginProjectMutations

func BeginPluginProjectMutations(grant *PluginDevelopmentGrant, changes map[string]PluginProjectMutation, temporaryPaths ...string) error

Begin/Finish 在 WithPluginProjectSource 的锁内执行;重命名的两个路径共用一条操作日志。

func BindableInteractiveSession

func BindableInteractiveSession(app, id string) (*melody.Session, <-chan struct{})

BindableInteractiveSession 只绑定当前有效的非发布主窗口,界面就绪检查由联网确认阶段执行。

func BlockCount

func BlockCount(fsize int64) int

func BootL10n

func BootL10n(num int, fallback string) string

BootL10n 返回启动进度文案的本地化字符串。

按当前界面语言(util.Lang,来自 conf.json)查 util.Langs 中 _kernel 块的整数键, 依次回退到英文、再回退到调用方传入的 fallback 英文文案。 这样在首启 InitConf() 尚未加载完语言文件时也能显示原文,不会出现空串。

func BootMobile

func BootMobile(container, appDir, workspaceBaseDir, lang string)

func BootWithFlags

func BootWithFlags(workspacePath, wdPath, port, readOnly, accessAuthCode, lang, mode string, ssl, attachUI, safeMode, enablePprof, fixedPort bool)

BootWithFlags 接收已解析的启动参数,完成环境变量回退、全局变量赋值、工作空间初始化与加锁。

func BoxIDFromDataPath

func BoxIDFromDataPath(absPath string) string

BoxIDFromDataPath 从 data 目录下的绝对路径反推 boxID。 路径形如 <DataDir>/<boxID>/...,切出紧跟在 DataDir 后的一段;供文件系统层判断是否需整体解密、 以及 API 层判断资源是否属于加密笔记本。若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。

func Broadcast

func Broadcast(msg []byte)

func BroadcastByType

func BroadcastByType(typ, cmd string, code int, msg string, data any)

BroadcastByType 广播所有实例上 typ 类型的会话。

func BroadcastByTypeAndApp

func BroadcastByTypeAndApp(typ, app, cmd string, code int, msg string, data any)

func BroadcastByTypeAndExcludeApp

func BroadcastByTypeAndExcludeApp(excludeApp, typ, cmd string, code int, msg string, data any)

func BuiltInAppearancePath

func BuiltInAppearancePath() string

BuiltInAppearancePath 返回当前运行模式下内置外观资源的目录。

func CalSha1

func CalSha1(b []byte, r io.Reader) ([]byte, error)

func CeilSize

func CeilSize(size int64) int64

func ChatGPT

func ChatGPT(msg string, contextMsgs []string, c *AIClient, apiBaseURL, protocol, model string, maxTokens int,
	temperature float64, timeout int) (ret string, stop bool, err error)

func ChatGPTService

func ChatGPTService() *chatgpt.Service

ChatGPTService 按主机配置目录保存账户,移动端复用 BootMobile 配置的私有 HomeDir。

func ChatMessagesToOpenAIResponseInput

func ChatMessagesToOpenAIResponseInput(messages []openai.ChatCompletionMessage) []any

func CheckEncryptedIndexCompatibility

func CheckEncryptedIndexCompatibility(db *sql.DB, kind string, schema int) error

CheckEncryptedIndexCompatibility 将索引版本保存在受 SQLCipher 认证的表中,拒绝复用缺少版本或参数不匹配的旧索引。 schema 由各索引维护,修改表结构时递增;索引重建由已认证源文档的调用方负责。

func CheckFileSysStatus

func CheckFileSysStatus()

func CheckHostSSRF

func CheckHostSSRF(host string) error

CheckHostSSRF 校验主机名解析出的 IP 不落在内网/回环等不可达地址段, 防止智能体被诱导发起 SSRF 攻击。web_fetch 与 http_request 共用此校验。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rg26-cg95-gq6p

func CheckSingleLinkRegularFile

func CheckSingleLinkRegularFile(file *os.File) error

CheckSingleLinkRegularFile 在 Windows 上从文件句柄读取链接数,因为 FileInfo.Sys 不提供该字段。 无法确定链接数时拒绝操作。

func CleanNotExistAssetsTexts

func CleanNotExistAssetsTexts(exists func(string) bool)

func CleanupLegacyFonts

func CleanupLegacyFonts(appearanceRoot string) error

CleanupLegacyFonts 在新版资源复制成功后清理原版历史字体,不递归删除目录或跟随符号链接。

func ClearPushProgress

func ClearPushProgress(total int)

func ClearWorkspaceExitMarker

func ClearWorkspaceExitMarker()

ClearWorkspaceExitMarker 仅在持有工作空间锁时清理临时状态,避免删除下一次启动的状态。

func CloneOpenAIResponseOutput

func CloneOpenAIResponseOutput(output []json.RawMessage) []json.RawMessage

func CloseOIDCSessions

func CloseOIDCSessions()

CloseOIDCSessions 关闭仅通过 OIDC 认证的 WebSocket 连接。

func ClosePublishServiceSessions

func ClosePublishServiceSessions()

ClosePublishServiceSessions 关闭所有发布服务的 WebSocket 连接

func ClosePushChan

func ClosePushChan(id string)

func CompactOpenAIResponse

func CompactOpenAIResponse(ctx context.Context, client *AIClient, request openai.ChatCompletionRequest,
	responseInput []any) ([]json.RawMessage, *openai.ResponseUsage, error)

func ConsumeCaptchaChallenge

func ConsumeCaptchaChallenge(id, answer string) bool

ConsumeCaptchaChallenge 校验验证码并立即删除挑战,同一挑战只能使用一次; ID 未知、挑战已过期或答案错误时返回 false。

func ContainsCJK

func ContainsCJK(text string) bool

func ContainsSubStr

func ContainsSubStr(s string, subStrs []string) bool

func ContextPushMsg

func ContextPushMsg(context map[string]any, msg string)

func ContextWithAIMessageContents

func ContextWithAIMessageContents(ctx context.Context, contents []*AIMessageContent) context.Context

ContextWithAIMessageContents 按助手消息顺序附加原生内容,图片降级不会改变消息对应关系。

func ContextWithGeminiThoughtSignatureState

func ContextWithGeminiThoughtSignatureState(ctx context.Context, state *GeminiThoughtSignatureState) context.Context

func ContextWithGeminiThoughtSummaries

func ContextWithGeminiThoughtSummaries(ctx context.Context) context.Context

ContextWithGeminiThoughtSummaries 请求 Gemini 返回可展示的思考摘要,仅用于 Agent 主响应。

func ContextWithOpenAIChatTemperature

func ContextWithOpenAIChatTemperature(ctx context.Context, temperature float32) context.Context

Chat 请求用上下文区分显式温度与未设置值,避免 SDK 的 omitempty 丢失零温度。

func ContextWithOpenAIResponsesBaseURL

func ContextWithOpenAIResponsesBaseURL(ctx context.Context, baseURL string) context.Context

ContextWithOpenAIResponsesBaseURL 根据端点附加 Responses 请求兼容选项。

func ContextWithOpenAIResponsesDefaultSampling

func ContextWithOpenAIResponsesDefaultSampling(ctx context.Context) context.Context

ContextWithOpenAIResponsesDefaultSampling 让未选择采样配置的调用方使用服务端默认值。 仅影响 Responses;其他调用方显式设置的零温度仍按原值发送。

func Convert2Float

func Convert2Float(s string) (float64, bool)
func ConvertIframeToLink(htmlStr string) string

func ConvertPandoc

func ConvertPandoc(dir string, args ...string) (path string, err error)
func CopyAssetTextForRelink(oldPath, newPath, historyDir string, dryRun bool) (exists bool, err error)

CopyAssetTextForRelink 复制 OCR 元数据,保留源资源的识别结果,并拒绝覆盖不同的目标结果。

func CopyDir

func CopyDir(src, dst string) error

CopyDir 递归复制目录内容到目标目录。

func CopyFile

func CopyFile(src, dst string) error

CopyFile 按字节复制单个文件内容,不保留源文件的权限与修改时间。

func CopyFileWithChangeTracking

func CopyFileWithChangeTracking(source, destination string) error

CopyFileWithChangeTracking 复制单个文件并保留权限和时间,在目标文件锁内标记内容变化。

func CopyPath

func CopyPath(src, dst string) error

CopyPath 把源路径复制到目标路径,目录递归复制。 与 gulu.File.Copy 不同,这里按 0755 建立目录、不保留源文件权限,用于 CLI 与 MCP 的 file copy 工具。

func CopyUserFile

func CopyUserFile(source, destination string) error

CopyUserFile 的外部来源或目标可能被其他程序占用,错误交由导入、导出调用方处理。

func CountIf

func CountIf(list any, op string, threshold any) int

CountIf 统计数字列表中满足指定比较条件的元素个数。 op 为比较操作符:"gt"/"lt"/"eq"/"ge"/"le",threshold 为比较阈值。 例如 CountIf(values, "gt", 0) 统计大于 0 的个数。非数字元素按 0 处理。

func CountSessions

func CountSessions() (ret int)

func CreateCustomFontTemp

func CreateCustomFontTemp() (*os.File, error)

func CreateOpenAICompletion

func CreateOpenAICompletion(ctx context.Context, client *AIClient, protocol string,
	request openai.ChatCompletionRequest, responseInput []any) (openai.ChatCompletionResponse, error)

func CurrentTimeMillis

func CurrentTimeMillis() int64

func CurrentTimeSecondsStr

func CurrentTimeSecondsStr() string

func CustomFontDir

func CustomFontDir() string

func DataSize

func DataSize() (dataSize, assetsSize int64)

func Decrypt

func Decrypt(key, ciphertext []byte) ([]byte, error)

Decrypt 对应 Encrypt 的解密。密钥错误、格式无效或密文被篡改时返回错误。

func DecryptWithAAD

func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error)

DecryptWithAAD 对应 EncryptWithAAD 的解密。格式无效、AAD 不匹配或密文被篡改时返回错误。

func DeduplicateWorkspacePaths

func DeduplicateWorkspacePaths(paths []string) []string

func DeepSeekWebFetch

func DeepSeekWebFetch(ctx context.Context, options DeepSeekWebOptions, rawURL, format string) (string, error)

func DeepSeekWebSearch

func DeepSeekWebSearch(ctx context.Context, options DeepSeekWebOptions, query string) (string, error)

func DeriveKey

func DeriveKey(password string, salt []byte, p Argon2Params) []byte

DeriveKey 用 Argon2id 从密码派生密钥。同一 password+salt+params 多次调用结果一致。

func DeriveSubKey

func DeriveSubKey(dek []byte, purpose string) []byte

DeriveSubKey 用 HKDF-SHA256 从主 DEK 派生用途隔离的子密钥。 同一 (dek, purpose) 多次调用结果一致;不同 purpose 派生出相互独立的子密钥, 实现用途分离——.sy/assets/AV 各用独立子密钥,互不可替代,限制单点密钥泄漏的影响面。

func DisableFeature

func DisableFeature(feature string)

func DiscardCustomFontTemp

func DiscardCustomFontTemp(tempPath string)

func EmojiPinYinCompare

func EmojiPinYinCompare(str1, str2 string) bool

func Encrypt

func Encrypt(key, plaintext []byte) ([]byte, error)

Encrypt 用 AES-256-GCM 加密。每次调用生成随机 nonce,因此同一明文多次加密结果不同。 返回格式:magic(4B) || spec(1B) || algorithm(1B) || nonceLength(1B) || nonce || ciphertext || GCM tag(16B)。

func EncryptWithAAD

func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error)

EncryptWithAAD 用 AES-256-GCM 加密并绑定 AAD(附加认证数据)。 AAD 不被加密,但参与 GCM 认证——解密时必须提供相同 AAD,否则认证失败。 把用途/boxID/路径等元数据放入 AAD,可防止同 box 内密文被替换用途或路径(bind 到上下文)。 返回格式与 Encrypt 一致,但 AAD 参与校验。

func EncryptedBlockTreeDBPath

func EncryptedBlockTreeDBPath(boxID string) string

EncryptedBlockTreeDBPath 返回加密笔记本的独立 SQLCipher blocktree db 文件路径。

func EncryptedDBPath

func EncryptedDBPath(boxID string) string

EncryptedDBPath 返回加密笔记本的独立 SQLCipher db 文件路径。 与 siyuan.db 同放 temp 目录,文件名带 boxID 区分多个加密笔记本。db 是可重建的索引,非原始内容。

func EncryptionNonce

func EncryptionNonce(ciphertext []byte) ([]byte, error)

EncryptionNonce 从 AES-GCM 密文信封中提取 nonce。

func EscapeHTML

func EscapeHTML(s string) (ret string)

func ExceedLargeFileWarningSize

func ExceedLargeFileWarningSize(fileSize int) bool

func ExistsAssetText

func ExistsAssetText(asset string) (ret bool)

func ExpandGlobBrace

func ExpandGlobBrace(pattern string) []string

ExpandGlobBrace 把包含 {a,b} 的 glob 模式展开为多个不含花括号的模式。 不含花括号时原样返回单个模式。

func Ext

func Ext(name string) (ret string)

func ExtraBodyForModel

func ExtraBodyForModel(model string) map[string]any

ExtraBodyForModel 按模型名大小写不敏感匹配内置清单,返回需注入的额外请求参数;无匹配返回 nil。

func ExtractArchiveEntry

func ExtractArchiveEntry(entry *zip.File, destination string) error

ExtractArchiveEntry 把 zip 条目解出到 destination,目录条目只创建目录。 文件条目按 0755 建立父目录并把修改时间对齐到条目时间;调用方负责路径越界校验。

func FileURLToLocalPath

func FileURLToLocalPath(fileURL string) string

FileURLToLocalPath 将 file:// URL 转为本地文件路径。

func FilterFileName

func FilterFileName(name string) string

func FilterFilePath

func FilterFilePath(p string) (ret string)

func FilterIconValue

func FilterIconValue(icon string) (ret string, valid bool)

func FilterMoveDocFromPaths

func FilterMoveDocFromPaths(fromPaths []string, toPath string) (ret []string)

func FilterRecentIconValue

func FilterRecentIconValue(icon string) (ret string, valid bool)

func FilterRecentIconValues

func FilterRecentIconValues(icons []string) (ret []string)

func FilterSelfChildDocs

func FilterSelfChildDocs(paths []string) (ret []string)

func FilterUploadEmojiFileName

func FilterUploadEmojiFileName(name string) string

func FilterUploadFileName

func FilterUploadFileName(name string) string

func FinishPluginProjectMutation

func FinishPluginProjectMutation(grant *PluginDevelopmentGrant, name string) error

func FinishPluginProjectMutations

func FinishPluginProjectMutations(grant *PluginDevelopmentGrant, paths []string) error

func GenerateDEK

func GenerateDEK() ([]byte, error)

GenerateDEK 生成随机数据密钥(32 字节,AES-256)。

func GenerateSalt

func GenerateSalt() ([]byte, error)

GenerateSalt 生成随机 salt(16 字节)。

func GetAbsPathInWorkspace

func GetAbsPathInWorkspace(relPath string) (string, error)

func GetAssetText

func GetAssetText(asset string) (ret string)

func GetBootProgress

func GetBootProgress() int32

func GetBootProgressDetails

func GetBootProgressDetails() (progress int32, details string)

func GetChildDocDepth

func GetChildDocDepth(treeAbsPath string) (ret int)

func GetCloudAccountServer

func GetCloudAccountServer() string

func GetCloudAssetsServer

func GetCloudAssetsServer() string

func GetCloudForumAssetsServer

func GetCloudForumAssetsServer() string

func GetCloudServer

func GetCloudServer() string

func GetCloudSyncServer

func GetCloudSyncServer() string

func GetCloudWebSocketServer

func GetCloudWebSocketServer() string

func GetContainsSubStrs

func GetContainsSubStrs(s string, subStrs []string) (ret []string)

func GetDataAssetsAbsPath

func GetDataAssetsAbsPath() (ret string)

func GetDeviceID

func GetDeviceID() string

func GetDeviceName

func GetDeviceName() string

func GetDiskUsage

func GetDiskUsage(p string) (total, used, free uint64)

func GetDuplicateName

func GetDuplicateName(master string) (ret string)

func GetEtag

func GetEtag(filename string) (etag string, err error)

func GetEtagByHandle

func GetEtagByHandle(f io.Reader, size int64) (etag string, err error)

func GetFilePathsByExts

func GetFilePathsByExts(dirPath string, exts []string) (ret []string)

func GetLocalIPs

func GetLocalIPs() []string

func GetMimeTypeByExt

func GetMimeTypeByExt(filePath string) (ret string)

func GetMimeTypeByPath

func GetMimeTypeByPath(filePath string) (m *mimetype.MIME, ok bool)

func GetOSPlatform

func GetOSPlatform() (plat string)

func GetOcrJsonText

func GetOcrJsonText(jsonData []map[string]string) (ret string)

GetOcrJsonText 提取并连接所有 text 字段的函数

func GetOrCreateTLSCert

func GetOrCreateTLSCert() (certPath, keyPath string, err error)

GetOrCreateTLSCert returns paths to existing TLS certificates or generates new ones signed by a local CA. Certificates are stored in the conf directory of the workspace.

func GetPrivateIPv4s

func GetPrivateIPv4s() (ret []string)

GetPrivateIPv4s 获取本地所有的私有 IPv4 地址(排除虚拟网卡)

func GetRemoteAddr

func GetRemoteAddr(req *http.Request) string

func GetRequestUrlStringParam

func GetRequestUrlStringParam(c *gin.Context, key string) string

GetRequestUrlStringParam extracts a string parameter from URL (path or query parameters).

func GetRhyBazaarHash

func GetRhyBazaarHash(ctx context.Context) string

func GetRhyResult

func GetRhyResult(ctx context.Context, force bool) (map[string]any, error)

func GetServerAddrs

func GetServerAddrs() (ret []string)

func GetTodayStart

func GetTodayStart() (ret time.Time)

func GetTokenEncoding

func GetTokenEncoding(modelName string) (*tiktoken.Tiktoken, error)

GetTokenEncoding 共享离线分词器;未知模型使用 cl100k_base 估算,不下载词表。

func GetTreeID

func GetTreeID(treePath string) string

func GetUniqueFilename

func GetUniqueFilename(filePath string) string

func HTTPRequest

func HTTPRequest(method, rawURL string, headers map[string]string, body string) (statusCode int, contentType string, text string, err error)

HTTPRequest 发起一次通用 HTTP 调用,供智能体 http_request 工具使用。 与 WebFetch 不同:本函数不做 HTML→Markdown 转换,文本类响应(含 JSON/XML)原样返回, 便于智能体直接消费 REST API 的 JSON 输出。method 取值:GET/POST/PUT/DELETE/PATCH。 返回的 text 为响应正文(文本类)或落盘后的文件路径(二进制类)。

func HasDuplicateQueryValues

func HasDuplicateQueryValues(r *http.Request) bool

HasDuplicateQueryValues 判断请求查询参数中是否存在重复键。

func HasForwardedHeaders

func HasForwardedHeaders(request *http.Request) bool

HasForwardedHeaders 判断请求是否携带反向代理转发头。 这些头可能由调用方伪造,反向代理未经改写时不能作为本机信任依据。

func HasUnclosedHtmlTag

func HasUnclosedHtmlTag(htmlStr string) bool

func HookUILoaded

func HookUILoaded()

func HumanizeDiffTime

func HumanizeDiffTime(a, b time.Time, lang string) string

func HumanizeRelTime

func HumanizeRelTime(a time.Time, b time.Time, lang string) string

func HumanizeTime

func HumanizeTime(then time.Time, lang string) string

func I18nTerm

func I18nTerm(language, key string) (ret string)

func ISOMonth

func ISOMonth(date time.Time) int

ISOMonth returns the month in which the Thursday of the ISO 8601 week of date occurs.

func ISOWeek

func ISOWeek(date time.Time) int

ISOWeek returns the ISO 8601 week number in which date occurs. Week ranges from 1 to 53. Jan 01 to Jan 03 of year n might belong to week 52 or 53 of year n-1, and Dec 29 to Dec 31 might belong to week 1 of year n+1.

func ISOWeekDate

func ISOWeekDate(day int, date time.Time) time.Time

ISOWeekDate returns the date of the specified day of the week in the ISO 8601 week of date. day: Monday=1, ..., Sunday=7.

func ISOYear

func ISOYear(date time.Time) int

ISOYear returns the ISO 8601 year in which date occurs.

func ImportCABundle

func ImportCABundle(caCertPEM, caKeyPEM string) error

ImportCABundle imports a CA certificate and private key from PEM-encoded strings.

func IncBootProgress

func IncBootProgress(progress int32, details string)

func IndexFixVersion

func IndexFixVersion() uint64

func InitEmojiChars

func InitEmojiChars()

func InitPandoc

func InitPandoc(customPandocBinPath string)

func InitTesseract

func InitTesseract()

func InitWorkspace

func InitWorkspace(workspacePath, wdPath string)

func InteractiveSession

func InteractiveSession(app, id string) (*melody.Session, <-chan struct{})

InteractiveSession 仅接受已就绪的非发布主窗口;空标识不能退化成广播。

func IsAbsPathInWorkspace

func IsAbsPathInWorkspace(absPath string) bool

func IsAnthropicMessagesProtocol

func IsAnthropicMessagesProtocol(protocol string) bool

func IsAssetLinkDest

func IsAssetLinkDest(dest []byte, includeServePath bool) bool

func IsAuthPageKeepaliveRequest

func IsAuthPageKeepaliveRequest(r *http.Request) bool

IsAuthPageKeepaliveRequest 判断是否为授权页保持连接请求,避免非常驻内存内核自动退出。 该请求无需认证,但连接必须被隔离在广播池之外。 https://github.com/siyuan-note/insider/issues/1099

func IsAuthSession

func IsAuthSession(session *melody.Session) bool

func IsBooted

func IsBooted() bool

func IsBrowserRequest

func IsBrowserRequest(c *gin.Context) bool

IsBrowserRequest 判断请求是否来自浏览器(非 SiYuan 原生客户端)。 原生客户端(桌面 Electron、Android/iOS/Harmony)的 User-Agent 均以 "SiYuan/" 开头, 其余视为浏览器。该口径与前端 getFrontend()、Electron 主进程为各窗口设置的 UA 前缀 (app/electron/window/mainWindow.ts 等)以及 session 鉴权中既有的 HasPrefix(ua, "SiYuan/") 判断保持一致。

func IsCiphertext

func IsCiphertext(data []byte) bool

IsCiphertext 判断给定字节是否以加密信封魔数开头(即是否为密文)。 供历史索引等无法取得 boxID/DEK 的路径做防御性检测:读到密文时跳过解析而非按 JSON 报错, 避免加密笔记本的 AV 等对象因路径迁移(同步、导入、历史布局变化)落到全局位置时产生噪声错误。

func IsCloudDrivePath

func IsCloudDrivePath(workspaceAbsPath string) bool

func IsCommonExt

func IsCommonExt(ext string) bool

func IsCompressibleAssetImage

func IsCompressibleAssetImage(p string) bool

func IsCrossSiteFetchSite

func IsCrossSiteFetchSite(site string) bool

IsCrossSiteFetchSite 根据 Sec-Fetch-Site 请求头判断是否为浏览器发起的跨站请求。 浏览器为所有请求携带 Sec-Fetch-Site,取值 same-origin(同源)、same-site(同站跨源)、 cross-site(跨站)、none(用户直接输入地址等);跨站顶层 GET 导航不携带 Origin, 仅凭 Origin 无法识别,因此需要结合该请求头判断。未携带时视为非浏览器客户端。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743

func IsDirRegularOrSymlink(dir fs.DirEntry) bool

func IsDisabledFeature

func IsDisabledFeature(feature string) bool

IsDisabledFeature 查询原生端启动时禁用的功能,不修改用户配置。

func IsDisplayableAsset

func IsDisplayableAsset(p string) bool

func IsEmptyDir

func IsEmptyDir(p string) bool

IsEmptyDir 判断目录是否为空,忽略系统元数据文件(如 .DS_Store)

func IsForbiddenAbsPath

func IsForbiddenAbsPath(abs string) bool

IsForbiddenAbsPath 判断绝对路径是否为敏感路径,HTTP 文件 API(kernel/api/file.go 的 refuseToAccess) 与 MCP 文件工具(kernel/mcp/tools/file.go 的 resolvePath)共用同一黑名单: conf 目录下的 conf.json 与 TLS 密钥材料、data/snippets/conf.json、data/templates 目录、 data/.siyuan/publishAccess.json、笔记本目录下的 .siyuan 内部文件以及 temp 目录下的 siyuan.log 日志文件。

func IsForbiddenDataRelPath

func IsForbiddenDataRelPath(rel string) bool

IsForbiddenDataRelPath 判断数据目录下的相对路径是否指向敏感位置(data/snippets/conf.json、 data/templates 目录、data/.siyuan/publishAccess.json 以及笔记本目录下的 .siyuan 内部文件 如 conf.json、sort.json、历史快照和 notebook-crypto-backup.json)。历史快照与仓库 diff 检出 中的文件副本位于其他绝对路径下,无法用 IsForbiddenAbsPath 的精确匹配拦截,因此 /history 与 /repo/diff 路由(kernel/server/serve.go)在去掉快照目录前缀后按数据相对路径调用本函数进行片段匹配。

func IsGeminiInteractionsProtocol

func IsGeminiInteractionsProtocol(protocol string) bool

func IsIdle

func IsIdle(idleThreshold time.Duration) bool

IsIdle 自上次用户活动以来是否已超过 idleThreshold。

func IsIndexFixDirty

func IsIndexFixDirty() bool

IsIndexFixDirty 返回是否存在未订正的变更(上次订正后有新用户活动)。

func IsLocalHost

func IsLocalHost(host string) bool

func IsLocalHostname

func IsLocalHostname(hostname string) bool

func IsLocalOrigin

func IsLocalOrigin(origin string) bool

func IsLocalProxyRequest

func IsLocalProxyRequest(request *http.Request) bool

IsLocalProxyRequest 判断请求是否由内置 fixed-port 代理转发。

func IsMobileContainer

func IsMobileContainer() bool

IsMobileContainer 表示当前内核运行在 Android、iOS 或鸿蒙客户端上。

func IsMobileWorkspaceBaseDir

func IsMobileWorkspaceBaseDir(path string) bool

IsMobileWorkspaceBaseDir 判断路径是否为移动端保留的工作空间基目录。

func IsNativeEmoji

func IsNativeEmoji(value string) bool

func IsNetworkIconURL

func IsNetworkIconURL(icon string) bool

func IsOfficeTempFile

func IsOfficeTempFile(assetAbsPath string) bool

IsOfficeTempFile 判断是否为 Office(Word/Excel/PowerPoint/WPS)打开文档时生成的临时文件。 这些文件名以 `~$` 开头,且被宿主程序独占,尝试读取会触发 filelock 的致命错误,需跳过。

func IsOnline

func IsOnline(checkURL string, skipTlsVerify bool, timeout int) bool

func IsOpenAIResponsesProtocol

func IsOpenAIResponsesProtocol(protocol string) bool

func IsPartitionRootPath

func IsPartitionRootPath(path string) bool

IsPartitionRootPath checks if the given path is a partition root path.

func IsPathRegularDirOrSymlinkDir

func IsPathRegularDirOrSymlinkDir(path string) bool

func IsPluginDevelopmentRawPathForbidden

func IsPluginDevelopmentRawPathForbidden(abs string, ancestors bool) bool

IsPluginDevelopmentRawPathForbidden 同时检查词法路径和链接目标;目录变更还保护宿主管理根的祖先。

func IsPluginDevelopmentRawWriteForbidden

func IsPluginDevelopmentRawWriteForbidden(abs string) bool

func IsPluginProjectDeliveryPath

func IsPluginProjectDeliveryPath(abs string) bool

func IsPluginProjectPath

func IsPluginProjectPath(abs string) bool

func IsPortOpen

func IsPortOpen(port string) bool

func IsPossiblyImage

func IsPossiblyImage(assetPath string) bool

IsPossiblyImage 模糊判断指定文件链接是否可能是图片。

func IsProtectedAgentStatePath

func IsProtectedAgentStatePath(abs string) bool

IsProtectedAgentStatePath 保护服务器运行状态,保留会话 output 目录的普通只读访问。

func IsPublishRelativePath

func IsPublishRelativePath(name string) bool

IsPublishRelativePath 限定发布资源使用无歧义的相对路径,各平台采用相同的分段规则。

func IsRelativePath

func IsRelativePath(dest string) bool

func IsReleaseVer

func IsReleaseVer(ver string) bool

IsReleaseVer 判断是否为正式版(不含 alpha、beta、rc 等预发布标识)。

func IsReservedFilename

func IsReservedFilename(baseName string) bool

func IsSecureRequest

func IsSecureRequest(request *http.Request) bool

IsSecureRequest 判断请求是否可以安全地承载会话凭据: 客户端连接使用 TLS,或来自本机(本机明文与内核自身 HTTPS 回源等价,且桌面端与浏览器扩展依赖本机明文)。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr

func IsSensitiveHTMLAssetPath

func IsSensitiveHTMLAssetPath(p string) bool

IsSensitiveHTMLAssetPath 允许剪贴板引用用户文档及系统临时文件,仍检查凭据、工作空间私有目录和符号链接目标。

func IsSensitivePath

func IsSensitivePath(p string) bool

IsSensitivePath 对传入路径做统一的敏感性检测。

为防止通过符号链接绕过黑名单,对工作空间外的路径会额外解析符号链接后再检查一次:这是 globalCopyFiles 等接受工作空间外绝对路径的接口的攻击面。工作空间内的路径不解析符号链接, 一是因为工作空间内文件(如 assets 中指向外部目录的符号链接)可能合法地指向工作空间外, 对其解析后执行系统目录前缀检查会误伤;二是避免在高 QPS 的伺服热路径上引入额外的 stat 开销。 目标尚未创建时解析最长已存在的父目录,避免别名下的新文件绕过敏感目录检查。

func IsSensitiveWritePath

func IsSensitiveWritePath(p string) bool

IsSensitiveWritePath 判断工作空间外的写入目标是否敏感。

除共用的敏感路径规则外,写方向额外拒绝家目录下第一层以 . 开头的路径:这些位置是 shell 初始化、 用户数据与浏览器配置的入口,写入即可获得持久化能力,而正常导出不会选择点目录。 工作空间内的目标不受这条规则影响,避免工作空间本身位于家目录点目录时误伤。

func IsSessionOriginAllowed

func IsSessionOriginAllowed(origin, host string) bool

IsSessionOriginAllowed 校验会话 Cookie 认证请求的 Origin,防止跨站请求伪造 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hhm2-g993-p656

func IsSessionOriginAllowedRequest

func IsSessionOriginAllowedRequest(r *http.Request) bool

IsSessionOriginAllowedRequest 校验会话认证请求:应用入口的顶层 GET 页面导航可放行, 其他跨源请求拒绝,其余请求继续校验 Origin。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743

func IsSessionReady

func IsSessionReady(session *melody.Session) bool

IsSessionReady 未声明就绪协议的旧客户端沿用连接后即可接收控制消息的行为。

func IsSymlink(dir fs.DirEntry) bool

IsSymlink 判断目录条目是否为符号链接或目录联接。

func IsSymlinkPath

func IsSymlinkPath(absPath string) bool

IsSymlinkPath 判断现有路径是否为符号链接或目录联接。

func IsSystemMetadataFile

func IsSystemMetadataFile(name string) bool

IsSystemMetadataFile 判断是否为操作系统自动生成的元数据文件(如 macOS 的 .DS_Store), 这类文件不属于业务数据,判空与清理时应忽略

func IsTLSRequest

func IsTLSRequest(request *http.Request) bool

IsTLSRequest 判断这条客户端连接是否使用 TLS。

内核在同一端口上通过 cmux 同时承载 HTTP 与 HTTPS,入站方向由 request.TLS 区分; 固定端口反代以 HTTPS 回源内核,由它写入的 ClientTLSHeader 标记客户端侧的真实连接方式。 该头部仅在直连对端为本机时优先采信,区分客户端协议与回源协议,其他连接只判断实际 TLS 状态。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr

func IsTesseractExtractable

func IsTesseractExtractable(p string) bool

func IsTextFileError

func IsTextFileError(err error, code string) bool

func IsTimeStr

func IsTimeStr(str string) bool

func IsValidExistingEmojiFileName

func IsValidExistingEmojiFileName(name string) bool

IsValidExistingEmojiFileName 保留已有表情名中的合法替换字符,新上传文件仍按命名规则清洗。

func IsValidIconUnicode

func IsValidIconUnicode(icon string) bool

IsValidIconUnicode 校验图标值是否为合法的十六进制码点序列(连字符分隔): 解码后不允许包含 HTML 元字符,防止图标值被渲染为可执行标记 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-vx5w-qrvp-mmcq

func IsValidPandocBin

func IsValidPandocBin(binPath string) bool

func IsValidRedirectHost

func IsValidRedirectHost(host string) bool

IsValidRedirectHost 校验 Host 是否为可以直接拼接跳转地址的合法 authority。

仅接受 host 或 host:port 形式,拒绝凭据、路径、查询、片段与空白字符, 避免被污染的 Host 让 HTTPS 跳转指向站外地址。

func IsValidUploadFileName

func IsValidUploadFileName(name string) bool

func IsWorkspaceDir

func IsWorkspaceDir(dir string) bool

IsWorkspaceDir 判断指定目录是否是工作空间目录。

func IsWorkspaceLocked

func IsWorkspaceLocked(workspacePath string) bool

func LangToBCP47

func LangToBCP47(lang string) string

LangToBCP47 把历史下划线标识映射为 BCP 47 标准语言代码(如 zh_CN → zh-CN)。 不是历史下划线标识时原样返回。

func LangToLegacy

func LangToLegacy(lang string) string

LangToLegacy 把 BCP 47 标准语言代码映射为历史下划线标识(如 zh-CN → zh_CN)。 不是 BCP 47 标准语言代码时原样返回。

func LastID

func LastID(p string) (name, id string)

func LegacyAgentInstructionsPath

func LegacyAgentInstructionsPath() string

func LegacyFontReplacement

func LegacyFontReplacement(relativePath string) string

LegacyFontReplacement 返回已知旧字体 URL 对应的新资源路径,仅用于旧文件缺失时的兼容读取。

func LinkTarget

func LinkTarget(htmlStr, linkBase string) (ret string)

func ListAvailableModels

func ListAvailableModels(apiKey, apiBaseURL string, timeout int) (models []string, err error)

ListAvailableModels 拉取 Provider 的可用模型清单(GET /v1/models),仅返回模型 ID 列表。 用于兼容不需要模型元数据的调用方。

func LoadAssetsTexts

func LoadAssetsTexts()

func LogDatabaseSize

func LogDatabaseSize(dbPath string)

func LogWebSocketError

func LogWebSocketError(session *melody.Session, channel string, err error)

LogWebSocketError 忽略正常关闭,记录消息丢弃警告,其他连接错误保留在调试日志中。

func MarkIndexClean

func MarkIndexClean(version uint64) bool

MarkIndexClean acknowledges only the generation captured before a successful repair.

func MarkIndexFixDirty

func MarkIndexFixDirty()

MarkIndexFixDirty records a change without treating background writes as user activity.

func MarkTLSEnforced

func MarkTLSEnforced()

MarkTLSEnforced 记录进程已经开始提供 HTTPS 服务。

func MarshalOpenAIResponseOutput

func MarshalOpenAIResponseOutput(output []any) ([]json.RawMessage, error)

func MatchGlob

func MatchGlob(filename, pattern string) bool

MatchGlob 判断文件名是否匹配 glob 模式,模式支持 {a,b} 形式的展开。

func MigrateAppearanceSyncIgnore

func MigrateAppearanceSyncIgnore() error

MigrateAppearanceSyncIgnore 移除旧版生成的隔离块,保留用户规则、换行和编码标记;没有隔离块时不写文件。

func Millisecond2Time

func Millisecond2Time(t int64) time.Time

func NaturalCompare

func NaturalCompare(str1, str2 string) bool

func NeedCaptcha

func NeedCaptcha() bool

func NeedWarnDiskUsage

func NeedWarnDiskUsage(dataSize int64) bool

func NewCaptchaChallenge

func NewCaptchaChallenge(answer string) string

NewCaptchaChallenge 保存验证码答案并返回随机挑战 ID,调用方只应把 ID 写入会话;生成失败时返回空字符串。

func NewCustomReqClient

func NewCustomReqClient() *req.Client

NewCustomReqClient 创建自定义 req 客户端

func NewLute

func NewLute() (ret *lute.Lute)

func NewOpenAIClient

func NewOpenAIClient(apiKey, apiBaseURL string, headers ...map[string]string) *openai.Client

func NewStdLute

func NewStdLute() (ret *lute.Lute)

func NodeIDByTime

func NodeIDByTime(t time.Time) string

NodeIDByTime 根据指定时间生成符合块 ID 格式的字符串,算法与 ast.NewNodeID() 一致, 仅时间源不同:用于让历史输入(如移动端速记暂存文件名时间戳)回填为块 ID。

func NormalizeAndResolve

func NormalizeAndResolve(p string) string

NormalizeAndResolve 将路径转为绝对、解析符号链接和目录联接并清理;在需要时转为小写以实现不区分大小写比较。

func NormalizeConcurrentReqs

func NormalizeConcurrentReqs(concurrentReqs int, provider int) int

func NormalizeEndpoint

func NormalizeEndpoint(endpoint string) string

func NormalizeLocalPath

func NormalizeLocalPath(endpoint string) string

func NormalizeSysFontsJSON

func NormalizeSysFontsJSON(raw string) string

原生平台仅负责发现可用字体,名称、字重、去重和排序共用内核规则。

func NormalizeTemplatePath

func NormalizeTemplatePath(p string) string

func NormalizeTimeout

func NormalizeTimeout(timeout int) int

func NormalizeWebTimeout

func NormalizeWebTimeout(timeout int) int

NormalizeWebTimeout 统一网页搜索和抓取的超时秒数。

func OCRAssetKey

func OCRAssetKey(asset string) string

OCRAssetKey 保留本地资源的笔记本身份,只合并显示参数和片段;外部地址保留完整查询参数。

func OpenFileNoFollow

func OpenFileNoFollow(root *os.Root, name string) (*os.File, error)

OpenFileNoFollow 不跟随最后一个路径分量的链接;Unix 使用非阻塞打开,避免路径被换成 FIFO 后挂起。 调用方必须验证全部父目录,并在读取前检查返回句柄的类型、文件身份及链接数。

func OpenPluginProjectDirectory

func OpenPluginProjectDirectory(abs string, create bool) (*os.Root, error)

OpenPluginProjectDirectory 从工作空间目录句柄逐层打开,拒绝链接及目录身份变化。

func OpenPublishFile

func OpenPublishFile(rootPath, name string) (*os.File, error)

OpenPublishFile 在已打开的目录句柄内逐级读取,拒绝链接和非普通文件,并校验打开前后的文件身份。 即使路径在检查后被替换,读取也不会转向链接目标或授权目录之外。

func OpenPublishReaderFile

func OpenPublishReaderFile(rootPath, name string) (*os.File, error)

OpenPublishReaderFile 打开读者可见的包资源,并在读取前检查请求路径和已打开文件的敏感性。 data/public 按设计公开,仍直接使用 OpenPublishFile,不经过本函数。

func Pandoc

func Pandoc(from, to, o, content string) (err error)

func ParentHPath

func ParentHPath(hPath string) string

ParentHPath 返回 hPath 的父路径:去掉最后一个 "/" 段,根路径及单段路径返回 "/"。

func ParsePort

func ParsePort(portString string) (uint16, error)

func PinYinCompare

func PinYinCompare(str1, str2 string) bool

func PinYinCompare4FileTree

func PinYinCompare4FileTree(str1, str2 string) bool

func PluginProjectDigest

func PluginProjectDigest(data []byte) string

func PluginProjectPrivateDir

func PluginProjectPrivateDir(taskID string) string

func PluginProjectRegularFile

func PluginProjectRegularFile(info os.FileInfo) bool

PluginProjectRegularFile 仅做打开前的普通文件预检;打开后还须用跨平台句柄检查硬链接数。

func PluginProjectRoot

func PluginProjectRoot(taskID string) string

func PluginProjectTreeRevision

func PluginProjectTreeRevision(inventory map[string]string) string

func PluginProjectsDir

func PluginProjectsDir() string

func PrepareLockScreenWallpaper

func PrepareLockScreenWallpaper(reader io.Reader) ([]byte, error)

PrepareLockScreenWallpaper 校验实际图片格式和解码尺寸,并移除元数据与透明背景。

func PushBackgroundTask

func PushBackgroundTask(data map[string]any)

func PushBoxDocFeatureChanged

func PushBoxDocFeatureChanged()

func PushClearAllMsg

func PushClearAllMsg()

func PushClearMsg

func PushClearMsg(msgId string)

PushClearMsg 会清空指定消息。

func PushClearMsgWithApp

func PushClearMsgWithApp(app, msgId string)

PushClearMsgWithApp 清除指定实例的单条提示;空消息 ID 不执行清除,避免影响其他任务。

func PushClearProgress

func PushClearProgress()

PushClearProgress 取消进度遮罩。

func PushDownloadProgress

func PushDownloadProgress(id string, percent float32)

func PushEndlessProgress

func PushEndlessProgress(msg string)

func PushErrMsg

func PushErrMsg(msg string, timeout int) (msgId string)

func PushErrMsgWithApp

func PushErrMsgWithApp(app, msg string, timeout int) (msgId string)

PushErrMsgWithApp 在指定实例显示错误;未指定实例时广播,实例离线时丢弃。

func PushEvent

func PushEvent(event *Result)

func PushKernelPluginState

func PushKernelPluginState(name string, state int)

func PushMsg

func PushMsg(msg string, timeout int) (msgId string)

func PushMsgWithApp

func PushMsgWithApp(app, msg string, timeout int) (msgId string)

func PushNodeOCRQueue

func PushNodeOCRQueue(n *ast.Node)

func PushProgress

func PushProgress(code, current, total int, msg string)

func PushProtyleLoading

func PushProtyleLoading(rootID, msg string)

func PushReloadDoc

func PushReloadDoc(rootID string)

func PushReloadDocInfo

func PushReloadDocInfo(docInfo map[string]any)

func PushReloadEmojiConf

func PushReloadEmojiConf()

func PushReloadFiletree

func PushReloadFiletree()

func PushReloadProtyle

func PushReloadProtyle(rootID string)

func PushReloadTag

func PushReloadTag()

func PushSaveDoc

func PushSaveDoc(rootID, typ string, sources any)

func PushSetDefRefCount

func PushSetDefRefCount(rootID, blockID string, defIDs []string, refCount, rootRefCount int)

func PushSetRefDynamicText

func PushSetRefDynamicText(rootID, blockID, defBlockID, refText, boxID string)

func PushStatusBar

func PushStatusBar(msg string)

func PushTxErr

func PushTxErr(msg string, code int, data any)

func PushUpdateIDs

func PushUpdateIDs(ids map[string]string)

func PushUpdateMsg

func PushUpdateMsg(msgId string, msg string, timeout int)

func PushUpdateMsgWithApp

func PushUpdateMsgWithApp(app, msgId, msg string, timeout int)

PushUpdateMsgWithApp 在指定实例更新提示;未指定实例时广播,实例离线时丢弃。

func RandString

func RandString(length int) string

func RandomBuiltinEmoji

func RandomBuiltinEmoji() string

RandomBuiltinEmoji 返回一个随机的内置 emoji unicode 码点(如 "1f4d6")。

func RandomSleep

func RandomSleep(minMills, maxMills int)

func ReadLockScreenWallpaper

func ReadLockScreenWallpaper(confDir string) ([]byte, error)

ReadLockScreenWallpaper 不接受客户端路径,并拒绝符号链接、非图片及超限文件。

func ReadSkill

func ReadSkill(name string, enabledUserSkills []string) (string, error)

func ReadTextFile

func ReadTextFile(root *os.Root, p string) (string, error)

func ReadUserFile

func ReadUserFile(p string) ([]byte, error)

ReadUserFile 对工作空间外的用户文件返回读取错误,工作空间数据沿用文件锁的错误保护。

func ReadWorkspacePaths

func ReadWorkspacePaths() (ret []string, err error)

func RecheckPluginProjectGrant

func RecheckPluginProjectGrant(ctx context.Context, expected *PluginDevelopmentGrant) error

后续检查必须仍是同一任务、同一冻结方案,不能借用期间替换的新授权。

func RecordPluginProjectArtifact

func RecordPluginProjectArtifact(grant *PluginDevelopmentGrant, artifact *PluginProjectArtifact) error

RecordPluginProjectArtifact 在 ZIP 原子发布后、项目锁内记录制品。

func RefreshActivity

func RefreshActivity()

RefreshActivity 刷新用户最近活动时间,并标记索引可能已脏(需要订正)。 在 model.Activity 中间件中,对 /api/transactions* 写操作请求调用。

func RefreshRhyResultJob

func RefreshRhyResultJob()

func ReloadPublishServiceSessions

func ReloadPublishServiceSessions()

ReloadPublishServiceSessions 通知所有已打开的发布服务页面刷新,使发布插件设置立即生效。

func ReloadUI

func ReloadUI()

func ReloadUIResetScroll

func ReloadUIResetScroll()

func RemoveAssetText

func RemoveAssetText(asset string)

func RemoveDatabaseFile

func RemoveDatabaseFile(dbPath string)

func RemoveEmojiInvisible

func RemoveEmojiInvisible(text string) (ret string)

func RemoveEmptyDir

func RemoveEmptyDir(p string) (err error)

RemoveEmptyDir 删除仅含系统元数据文件(如 .DS_Store)的目录;若目录仍含业务文件则保留不动

func RemoveID

func RemoveID(name string) string

func RemoveInvalid

func RemoveInvalid(text string) (ret string)

func RemoveInvalidRetainCtrl

func RemoveInvalidRetainCtrl(text string) (ret string)

func RemoveLockScreenWallpaper

func RemoveLockScreenWallpaper(confDir string) error

RemoveLockScreenWallpaper 仅删除专用壁纸,重复恢复默认也能成功。

func RemovePushChan

func RemovePushChan(session *melody.Session)

func RemoveRedundantSpace

func RemoveRedundantSpace(str string) string

func RemoveSkill

func RemoveSkill(name string) error

func RemoveWorkspacePath

func RemoveWorkspacePath(paths []string, target string) []string

func RemoveWorkspaceSession

func RemoveWorkspaceSession(session *SessionData)

func RenameEmojiFile

func RenameEmojiFile(oldPath, newPath string) error

RenameEmojiFile 在源和目标文件锁内迁移表情,目标已存在时保留两者,不覆盖文件或合并目录。

func RenameSkill

func RenameSkill(oldName, newName string) error

func RenderOAuthCallbackPage

func RenderOAuthCallbackPage(lang, title, message string, success bool) []byte

RenderOAuthCallbackPage 渲染 OAuth 和 OIDC 共用的回调结果页面。

func RenderOAuthRedirectPage

func RenderOAuthRedirectPage(lang, title, target string) []byte

RenderOAuthRedirectPage 在同源结果页加载后进入已校验的站内目标,结束身份提供方的重定向链。

func ReplaceNewline

func ReplaceNewline(text, replaceWith string) string

func ReportFileSysFatalError

func ReportFileSysFatalError(err error)

func Rerank

func Rerank(query string, documents []string, options RerankOptions) (indices []int, scores []float64, err error)

Rerank 调用重排服务对 query 与候选文档逐对精排。endpoint 为完整重排端点地址,不同服务商路径无统一标准 (Jina /v1/rerank、阿里云 compatible-api/v1/reranks、Cohere /v1/rerank 等),由用户照文档填写。 返回的 indices 与 scores 均按 relevance_score 降序,indices 指向传入 documents 的下标。 对每条 document 文本按 rerankDocTextMaxRunes 截断,防超服务端 token 限制并保证 UTF-8 完整。 topN 语义:topN <= 0 时不传 top_n(服务端默认返回全部文档评分,搜索场景用此避免被服务端 top_n 上限截断); topN > 0 时透传给服务端,仅用于测试连通性等只需少量结果的场景。

func ResolveLongestExistingParent

func ResolveLongestExistingParent(absPath string) string

ResolveLongestExistingParent 解析 absPath 中最长已存在部分的符号链接或目录联接,拼回剩余路径。 例如 absPath = /workspace/data/link/newdir/file,其中 /workspace/data/link 是指向 /workspace/data/<encBoxID>/ 的 symlink,newdir/file 尚不存在: 返回 /workspace/data/<encBoxID>/newdir/file。

func ResolveRealPath

func ResolveRealPath(path string) (string, error)

func RestrictConfFilePermissions

func RestrictConfFilePermissions()

RestrictConfFilePermissions 收紧工作空间配置目录中凭据文件的权限。conf.json 由 filelock 以 0644 写入, 因此在每次保存后与启动时调用;同目录的 TLS 私钥在启动时一并迁移旧版本遗留的宽松权限。

func RestrictSecretFile

func RestrictSecretFile(path string)

RestrictSecretFile 在文件存在且允许组或其他用户访问时收紧为仅当前用户可读写;失败时保留原权限并记录警告。 Windows 由用户目录的访问控制保护,不处理权限位。

func RuntimeInfo

func RuntimeInfo(ctx context.Context) string

RuntimeInfo 采集当前内核的运行信息,使用统一诊断字段,避免包含路径、主机名和账户信息。

func SHA256Hash

func SHA256Hash(data []byte) string

func SQLitePageCacheDSN

func SQLitePageCacheDSN() string

SQLitePageCacheDSN 设置每个连接的页缓存预算,负值的单位为 KiB。 移动端采用 16 MiB,减少多连接和多个已解锁笔记本的内存压力。

func SSRFSafeDialer

func SSRFSafeDialer(timeout time.Duration) *net.Dialer

SSRFSafeDialer 返回内核出站请求使用的拨号器,在连接阶段按目标 IP 判断是否允许访问。 非安全模式下放行回环与 RFC1918 私网,以支持插件访问本机或局域网服务,仅记录一次审计日志; 链路本地与未指定地址始终拒绝,避免访问云元数据等仅本机可达的服务。

func SanitizeHTML

func SanitizeHTML(h string) string

func SanitizeName

func SanitizeName(name string) string

SanitizeName replaces all non-alphanumeric characters in the input string with underscores.

func SanitizeSVG

func SanitizeSVG(svgInput string) (string, error)

SanitizeSVG 使用 XML 语义过滤 SVG,避免 HTML 与 XML 解析规则差异导致活动内容绕过过滤。

func SaveAssetsTexts

func SaveAssetsTexts()

func SaveLockScreenWallpaper

func SaveLockScreenWallpaper(confDir string, data []byte) error

SaveLockScreenWallpaper 原子替换唯一的壁纸,失败时保留原文件。

func SaveSkill

func SaveSkill(name, content string) error

func ServeMultiplexed

func ServeMultiplexed(ln net.Listener, handler http.Handler, certPath, keyPath string, httpServer, httpsServer *http.Server) (*http.Server, *http.Server, error)

ServeMultiplexed 在同一个 listener 上同时承载 HTTP 与 HTTPS(含 HTTP/2)。

httpServer / httpsServer 用于承载两种连接的 *http.Server,传 nil 时内部自行创建。 返回实际使用的两个 server,方便调用方在需要时关闭其上的活跃连接(如发布服务)。

注意:cmux 派生出的 listener 内部嵌入的是底层 root listener,对其调用 Close 实际会关闭 root, 因此 HTTP 与 HTTPS 必须使用各自的 *http.Server,不能共用——否则共用 server 的 Close 会把 root 一并关掉,导致 m.Serve 提前返回非关闭类错误。

func SessionCookieKeys

func SessionCookieKeys(cookieKey string) (hashKey, blockKey []byte, err error)

SessionCookieKeys 由 Cookie 密钥派生会话 Cookie 的签名密钥和 AES-256 加密密钥。 旧格式 Cookie 直接以 Cookie 密钥签名且不加密,无法通过校验,按未登录处理。 Cookie 密钥为空时不派生,会话 Cookie 的编解码随之失败,避免以公开的固定密钥签发会话。

func SessionsByType

func SessionsByType(typ string) (ret []*melody.Session)

func SetAssetText

func SetAssetText(asset, text string)

func SetBootDetails

func SetBootDetails(details string)

func SetBooted

func SetBooted()

func SetHomeDir

func SetHomeDir(homeDir string) error

SetHomeDir 设置用户配置基路径,配置仍保存在其 .config/siyuan 子目录中。 空参数保留默认目录;显式路径必须能创建配置目录,失败时不回退到系统用户主目录。

func SetLocalIPs

func SetLocalIPs(addresses []string)

func SetNetworkProxy

func SetNetworkProxy(proxyURL string, useSystem bool)

func SetTLSRequired

func SetTLSRequired(required bool)

SetTLSRequired 记录用户是否开启了「启用 HTTPS」。

func ShortPathForBootingDisplay

func ShortPathForBootingDisplay(p string) string

func ShouldRedirectToTLS

func ShouldRedirectToTLS(request *http.Request) bool

ShouldRedirectToTLS 判断当前请求是否需要被重定向到 HTTPS。

仅在用户开启「启用 HTTPS」且证书可用时生效;本机明文请求放行,否则桌面端、 固定端口反代与浏览器扩展无法连接。CORS 预检不携带凭据且浏览器不跟随跳转,故同样放行。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr

func ShutdownHTTPServers

func ShutdownHTTPServers(ctx context.Context, servers ...*http.Server)

ShutdownHTTPServers 并行停止 HTTP 和 HTTPS 服务,等待活跃响应完成,超时后关闭剩余连接。

func SizeOfDirectory

func SizeOfDirectory(path string) (size int64, err error)

func SkillsDir

func SkillsDir() string

func SnapshotPluginProject

func SnapshotPluginProject(root *os.Root, authorize func(string) error) (map[string][]byte, error)

SnapshotPluginProject 读取有界不可变字节快照,拒绝所有不安全的受管成员。

func SplitFileAnnotationRef

func SplitFileAnnotationRef(reference string) (assetLink, annotationID string)

SplitFileAnnotationRef 分离资源地址和标注 ID,保留资源地址的查询参数及片段,不改变已有引用的编码。

func SupportsOpenAIResponsesCompaction

func SupportsOpenAIResponsesCompaction(ctx context.Context) bool

SupportsOpenAIResponsesCompaction 判断当前端点是否支持原生 Responses 上下文压缩。

func TLSEnforced

func TLSEnforced() bool

TLSEnforced 返回当前进程是否已经在提供 HTTPS 服务。

func TLSRedirectHandler

func TLSRedirectHandler(handler http.Handler) http.Handler

TLSRedirectHandler 包装明文 HTTP 处理器:用户开启「启用 HTTPS」且证书可用时, 把来自其他主机的明文请求重定向到 HTTPS,本机明文请求与 CORS 预检放行。

内核通过 cmux 在同一端口同时承载 HTTP 与 HTTPS,固定端口反代与发布服务也是双栈, 仅在监听层无法阻止明文访问,因此三条入口都要经过这里。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr

func TLSRequired

func TLSRequired() bool

TLSRequired 返回用户是否开启了「启用 HTTPS」。

func TestEmbeddingModel

func TestEmbeddingModel(apiKey, apiBaseURL, model string, dimensions, timeout int) (matched bool, dims int, err error)

TestEmbeddingModel 测试嵌入模型可用性,发送极简文本并返回首个向量维度。 返回值:matched 表示是否连通成功,dimensions 为返回的向量维度(便于核对配置), err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。

func TestModel

func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int, headers ...map[string]string) (available []string, matched bool, err error)

TestModel 测试模型可用性。先按协议拉取可用模型清单, 再按 Provider 协议发送极简文本生成请求,确认所选协议实际可用。 返回值:available 为可用模型清单(仅 ListModels 成功时填充),matched 表示 model 是否可用, err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。

func TestRerankModel

func TestRerankModel(options RerankOptions) (matched bool, err error)

TestRerankModel 测试重排模型可用性,用极简 query+documents 发一次重排请求验证连通性与鉴权。 返回值:matched 表示是否连通成功,err 为请求错误(鉴权失败、网络异常、模型不存在等,原样返回便于调用方展示原因)。

func TextFileRevision

func TextFileRevision(content []byte) string

func TimeFromID

func TimeFromID(id string) (ret string)

func ToFloat64

func ToFloat64(v any) (float64, bool)

ToFloat64 将常用数值/字符串类型转换为 float64。

func TrimSpaceInPath

func TrimSpaceInPath(p string) string

func TruncateLenFileName

func TruncateLenFileName(name string) (ret string)

func TruncateRunes

func TruncateRunes(text string, maxRunes int) string

TruncateRunes 按 Unicode 码点截断文本,不附加省略标记。

func TruncateToolOutput

func TruncateToolOutput(text, sessionID string) string

func TruncateUTF8Bytes

func TruncateUTF8Bytes(text string, maxBytes int) string

TruncateUTF8Bytes 在字节上限内截断有效 UTF-8 文本,保留完整码点,不附加省略标记。

func UIProcessCount

func UIProcessCount() (ret int)

UIProcessCount 获取 UI 进程注册表条目数。

func UTF82GBK

func UTF82GBK(src string) ([]byte, error)

UTF82GBK transform UTF8 rune into GBK byte array.

func UnescapeHTML

func UnescapeHTML(s string) (ret string)

func UnlockWorkspace

func UnlockWorkspace()

func UserSkillsDir

func UserSkillsDir() string

func ValidateAIProviderHeaders

func ValidateAIProviderHeaders(headers map[string]string) error

ValidateAIProviderHeaders 在保存配置和发送请求前校验请求头,不在错误中包含凭据。

func ValidateDecisionImage

func ValidateDecisionImage(image DecisionImage) error

func ValidateDecisionImageDetail

func ValidateDecisionImageDetail(detail string) error

func ValidateDecisionJSON

func ValidateDecisionJSON(data json.RawMessage) error

ValidateDecisionJSON 校验原生 JSON 的服务端限制,不将数字转换为 float64。

func ValidateDecisionQuestions

func ValidateDecisionQuestions(questions map[string]DecisionQuestion) error

func ValidateDecisionQuestionsForProvider

func ValidateDecisionQuestionsForProvider(provider string, questions map[string]DecisionQuestion) error

func ValidateGeneratedImage

func ValidateGeneratedImage(data []byte) (mimeType, extension string, err error)

ValidateGeneratedImage 校验生成图片的格式、尺寸和体积。

func ValidateID

func ValidateID(idArg string) error

ValidateID 检查块或笔记本 ID 形态,不合法时返回 ErrInvalidID。 返回错误而不是往调用方的信封里写字,让调用方决定用哪个错误码响应。

func ValidateOptionalID

func ValidateOptionalID(idArg string) error

ValidateOptionalID 与 ValidateID 相同,但把空字符串视为「未提供」而非非法值。 用于可选的对端 ID 等参数,避免调用方各自重复判空。

func ValidatePluginProjectFile

func ValidatePluginProjectFile(name string) error

即使出现在允许清单中,也拒绝平台别名及私密、构建依赖和运行时材料。

func ValidateTextFileContent

func ValidateTextFileContent(content string) error

func ValidateTextFilePath

func ValidateTextFilePath(p string) error

ValidateTextFilePath 拒绝非规范路径,避免将目录穿越、Windows 别名或其他分隔符静默转换为目标路径。

func WaitBindableInteractiveSession

func WaitBindableInteractiveSession(ctx context.Context, app, id string) (*melody.Session, <-chan struct{})

WaitBindableInteractiveSession 处理升级握手已完成但认证连接尚未登记的短暂窗口。 已登记的无效连接立即拒绝;请求取消后不得等待后续同名连接。

func WaitForTesseractInit

func WaitForTesseractInit()

func WaitForTesseractInitContext

func WaitForTesseractInitContext(ctx context.Context) error

func WaitForUILoaded

func WaitForUILoaded()

func WaitInteractiveSession

func WaitInteractiveSession(ctx context.Context, app, id string, expected *melody.Session) bool

WaitInteractiveSession 最多等待 10 秒让原主窗口报告界面就绪,连接替换、断开或请求失效时终止等待。

func WaitWorkspaceExitProcess

func WaitWorkspaceExitProcess(ctx context.Context, state WorkspaceExitState) error

WaitWorkspaceExitProcess 仅观察进程身份,不打开工作空间、删除标记或终止进程。

func WebFetch

func WebFetch(rawURL, format string) (string, error)

func WebFetchContext

func WebFetchContext(ctx context.Context, rawURL, format string, timeout int) (string, error)

func WebSearchContext

func WebSearchContext(ctx context.Context, query, exaApiKey string, timeout int) (string, error)

func Weekday

func Weekday(date time.Time) int

Weekday returns the day of the week specified by date. Sunday=0, Monday=1, ..., Saturday=6.

func WeekdayCN

func WeekdayCN(date time.Time) string

WeekdayCN returns the day of the week specified by date. Sunday=日, Monday=一, ..., Saturday=六.

func WeekdayCN2

func WeekdayCN2(date time.Time) string

WeekdayCN2 returns the day of the week specified by date. Sunday=天, Monday=一, ..., Saturday=六.

func WithPluginDevelopmentAccess

func WithPluginDevelopmentAccess(ctx context.Context, check func(string) (*PluginDevelopmentGrant, error)) context.Context

WithPluginDevelopmentAccess 将每次执行前重新校验的服务器回调放入私有上下文键。

func WithPluginProjectLockContext

func WithPluginProjectLockContext(ctx context.Context, taskID string, fn func() error) error

func WithPluginProjectSource

func WithPluginProjectSource(ctx context.Context, write bool, fn func(*PluginDevelopmentGrant, *os.Root) error) error

func WrapGeminiThoughtSignatureTransport

func WrapGeminiThoughtSignatureTransport(base openai.HTTPDoer) openai.HTTPDoer

WrapGeminiThoughtSignatureTransport 为 Google OpenAI 兼容端点补充工具调用签名往返支持。 该函数导出仅用于 Agent 集成测试构造本地上游,生产代码通过 NewAIClientWithModel 使用。

func WriteFileByMmap

func WriteFileByMmap(filePath string, data []byte) (err error)

WriteFileByMmap 使用内存映射按页比较,只覆写发生变化的页,并立即刷新。 全程持有 filelock 的进程内互斥锁,长度变化时调整文件大小;出错时由调用方回退到原子写入。

func WriteFileIfUnchanged

func WriteFileIfUnchanged(path string, original, data []byte) error

WriteFileIfUnchanged 在同一文件锁内比对扫描源并原子写入;original 为 nil 时要求目标不存在。

func WriteFilePaths

func WriteFilePaths(paths []string) error

当前仅在 Windows、macOS 上实现,其他平台返回错误

func WriteFileWithChangeTracking

func WriteFileWithChangeTracking(path string, data []byte) error

WriteFileWithChangeTracking 在释放文件锁前标记写入,保留修改时间的后续操作也不会隐藏内容变化。

func WriteFileWithPreflight

func WriteFileWithPreflight(path string, data []byte, useMmap bool, check func([]byte) error) error

WriteFileWithPreflight 在同一文件锁内检查当前源文件后写入;源不存在时向检查函数传入 nil。 检查失败不创建或截断文件;普通数据沿用按页写入和原子回退,加密数据仅原子替换。

func WriteUserFile

func WriteUserFile(p string, data []byte) error

WriteUserFile 将外部目标的权限与占用错误返回给调用方。

func WriteWorkspacePaths

func WriteWorkspacePaths(workspacePaths []string) (err error)

Types

type AIClient

type AIClient struct {
	*openai.Client

	ChatGPT bool
	// contains filtered or unexported fields
}

AIClient 共享生成调用的连接配置,按协议选择独立的请求适配器。

func NewAIClientWithModel

func NewAIClientWithModel(apiKey, apiBaseURL, model string, headers ...map[string]string) *AIClient

NewAIClientWithModel 创建生成客户端,并按模型与端点启用协议适配。 模型请求统一启用思考字段适配,命中清单的模型会注入额外参数,官方 Gemini 端点会保留工具调用签名。

func NewChatGPTClient

func NewChatGPTClient(accountID string) *AIClient

NewChatGPTClient 使用可刷新账户凭证,并固定公开套餐端点及请求能力。

type AIMessageContent

type AIMessageContent struct {
	Protocol string            `json:"protocol"`
	Version  int               `json:"version"`
	Blocks   []json.RawMessage `json:"blocks"`
}

AIMessageContent 保存供应商原生内容,显示文本与恢复上下文分别使用各自的表示。

func CloneAIMessageContent

func CloneAIMessageContent(content *AIMessageContent) *AIMessageContent

type AgentInstructions

type AgentInstructions struct {
	Content  string
	Revision string
}

func ReadAgentInstructions

func ReadAgentInstructions() (AgentInstructions, error)

func SaveAgentInstructions

func SaveAgentInstructions(content, revision string) (saved AgentInstructions, migrated bool, err error)

修订校验和原子替换共用临界区,失败时保留原文;空内容同样是有效版本。 migrated 标识迁移已写入新位置或移除旧文件,供调用者在部分失败时也通知同步。

type Argon2Params

type Argon2Params struct {
	Memory      uint32 `json:"memory"`      // 单次派生占用的内存,单位 KB
	Iterations  uint32 `json:"iterations"`  // 遍历内存的次数
	Parallelism uint8  `json:"parallelism"` // 并行线程数
	KeyLength   uint32 `json:"keyLength"`   // 输出密钥长度,单位字节
}

Argon2Params 是 Argon2id 密钥派生函数的参数。参数本身不是秘密,会随配置落盘,以便跨平台一致地派生密钥。 默认值遵循 OWASP 2023 推荐(64 MB 内存 / 3 次迭代 / 4 线程 / 32 字节输出)。

func DefaultArgon2Params

func DefaultArgon2Params() Argon2Params

DefaultArgon2Params 返回 OWASP 2023 推荐的 Argon2id 参数。

func ValidateArgon2Params

func ValidateArgon2Params(p Argon2Params) (Argon2Params, error)

ValidateArgon2Params 校验 Argon2id 参数是否在合理范围内,防止恶意备份设置极大内存导致 OOM, 或过弱参数降低安全性。

type AssetTextRelinkMapping

type AssetTextRelinkMapping struct{ OldPath, NewPath string }

type AssetTextRelinkPlan

type AssetTextRelinkPlan struct {
	Results []AssetTextRelinkResult
	// contains filtered or unexported fields
}
func PrepareAssetTextRelinks(mappings []AssetTextRelinkMapping) (*AssetTextRelinkPlan, error)

PrepareAssetTextRelinks 从同一份 OCR 快照计算所有映射,不写文件或内存缓存。

func (*AssetTextRelinkPlan) Save

func (p *AssetTextRelinkPlan) Save(historyDir string, selected []int) ([]int, error)

Save 将通过预检的映射合并为一次保存,保留源键;同值重试不生成历史或写入文件。

type AssetTextRelinkResult

type AssetTextRelinkResult struct {
	Exists  bool
	Changed bool
	Reason  string
}

type AtomicValue

type AtomicValue[T any] struct {
	// contains filtered or unexported fields
}

AtomicValue 发布运行时派生值,读方不会与设置写入竞争。

func NewAtomicValue

func NewAtomicValue[T any](value T) *AtomicValue[T]

func (*AtomicValue[T]) Load

func (value *AtomicValue[T]) Load() T

func (*AtomicValue[T]) Store

func (value *AtomicValue[T]) Store(next T)

type AvailableModel

type AvailableModel struct {
	ID            string
	ContextLength int
}

AvailableModel 描述 Provider 返回的模型及其可选上下文窗口。

func ListAvailableModelsWithContext

func ListAvailableModelsWithContext(apiKey, apiBaseURL string, timeout int, headers ...map[string]string) (models []AvailableModel, err error)

ListAvailableModelsWithContext 拉取 Provider 的模型清单及可选上下文窗口。 通用 OpenAI 兼容接口不保证返回上下文长度,缺失或非法时保留模型并将 ContextLength 置为 0。

func ListProviderModels

func ListProviderModels(apiKey, baseURL, protocol string, timeout int, headers ...map[string]string) ([]AvailableModel, error)

ListProviderModels 按提供商协议读取模型清单,保持通用接口的返回结构。

type BlockStatResult

type BlockStatResult struct {
	RuneCount  int `json:"runeCount"`
	WordCount  int `json:"wordCount"`
	LinkCount  int `json:"linkCount"`
	ImageCount int `json:"imageCount"`
	RefCount   int `json:"refCount"`
	BlockCount int `json:"blockCount"`
}

type BuiltinSkillInfo

type BuiltinSkillInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Source      string `json:"source"`
	Version     string `json:"version"`
	Digest      string `json:"digest"`
	Enabled     bool   `json:"enabled"`
}

func BuiltinPluginSkill

func BuiltinPluginSkill(disabled []string) (*BuiltinSkillInfo, error)

BuiltinPluginSkill 返回可用于授权绑定的版本、全部资源摘要及当前启用状态,不返回正文。

func DiscoverBuiltinSkills

func DiscoverBuiltinSkills(disabled []string) []BuiltinSkillInfo

DiscoverBuiltinSkills 独立于普通技能列表,防止斜杠菜单绕过官方流程选择。

type CustomFont

type CustomFont struct {
	ID          string   `json:"id"`
	Family      string   `json:"family"`
	Weight      int      `json:"weight"`
	DisplayName string   `json:"displayName"`
	Aliases     []string `json:"aliases,omitempty"`
	Spacing     string   `json:"spacing,omitempty"`
	URL         string   `json:"url"`
	// contains filtered or unexported fields
}

func GetCustomFontFile

func GetCustomFontFile(id string) (string, *CustomFont, bool)

func InstallCustomFont

func InstallCustomFont(tempPath string) (*CustomFont, bool, error)

func LoadCustomFonts

func LoadCustomFonts() []*CustomFont

func RemoveCustomFont

func RemoveCustomFont(id string) (*CustomFont, error)

type DecisionAnswer

type DecisionAnswer struct {
	Type          string              `json:"type"`
	Choice        *string             `json:"choice,omitempty"`
	Score         *float64            `json:"score,omitempty"`
	Noul          *float64            `json:"noul,omitempty"`
	Probabilities map[string]*float64 `json:"probabilities,omitempty"`
	Confidence    *float64            `json:"confidence,omitempty"`
	Legend        map[string]string   `json:"legend,omitempty"`
}

type DecisionBlock

type DecisionBlock struct {
	ID       string `json:"id"`
	Markdown string `json:"markdown"`
}

type DecisionImage

type DecisionImage struct {
	URL    string `json:"image_url"`
	Detail string `json:"detail,omitempty"`
}

DecisionImage 必须显式提供;正文或 JSON 中的图片链接不会被自动读取。

type DecisionInputTokensDetails

type DecisionInputTokensDetails struct {
	CachedTokens     int `json:"cached_tokens"`
	CacheWriteTokens int `json:"cache_write_tokens"`
}

缓存读写均已包含在 InputTokens 中,不能再次累加。

type DecisionOptions

type DecisionOptions struct {
	Provider, Endpoint, APIKey, Model string
	Timeout                           int
}

type DecisionQuestion

type DecisionQuestion struct {
	Type         string          `json:"type"`
	Instructions string          `json:"instructions"`
	Criteria     json.RawMessage `json:"criteria,omitempty"`
	Images       []DecisionImage `json:"-"`
}

type DecisionResult

type DecisionResult struct {
	Model   string                    `json:"model"`
	Answers map[string]DecisionAnswer `json:"answers"`
	Usage   DecisionUsage             `json:"usage"`
}

func EvaluateDecision

func EvaluateDecision(ctx context.Context, options DecisionOptions, state DecisionState, questions map[string]DecisionQuestion) (*DecisionResult, error)

EvaluateDecision 发送一次判断请求,不重试、不截断原文,也不将缺失或无效答案转换为分数。

type DecisionState

type DecisionState struct {
	Context string          `json:"context,omitempty"`
	Text    string          `json:"text,omitempty"`
	Blocks  []DecisionBlock `json:"blocks,omitempty"`
	Data    json.RawMessage `json:"data,omitempty"`
	Images  []DecisionImage `json:"-"`
}

type DecisionUsage

type DecisionUsage struct {
	InputTokens        int                         `json:"input_tokens"`
	OutputTokens       int                         `json:"output_tokens"`
	InputTokensDetails *DecisionInputTokensDetails `json:"input_tokens_details,omitempty"`
}

type DeepSeekWebOptions

type DeepSeekWebOptions struct {
	APIKey  string
	Timeout int
}

type Font

type Font struct {
	Family      string   `json:"family"`            // 对应 CSS font-family
	Weight      int      `json:"weight"`            // 对应 CSS font-weight
	DisplayName string   `json:"displayName"`       // 给人看的名称 (Family + Subfamily)
	Aliases     []string `json:"aliases,omitempty"` // 用于字体搜索的本地化名称和内部名称
	Spacing     string   `json:"spacing,omitempty"` // 字体间距分类
	// contains filtered or unexported fields
}

func LoadSysFonts

func LoadSysFonts() []*Font

func ReadSysFonts

func ReadSysFonts() []*Font

独立桌面工具与工作空间共用字体枚举、名称解析和排序,不依赖工作空间配置。

type GeminiThoughtSignatureState

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

GeminiThoughtSignatureState 保存同一次 Agent 请求中的 Gemini 工具调用签名。 签名是不透明值,只按工具调用 ID 写入和读取,不进行解码或修改。

func NewGeminiThoughtSignatureState

func NewGeminiThoughtSignatureState() *GeminiThoughtSignatureState

func (*GeminiThoughtSignatureState) Get

func (s *GeminiThoughtSignatureState) Get(callID string) string

func (*GeminiThoughtSignatureState) Set

func (s *GeminiThoughtSignatureState) Set(callID, signature string)

func (*GeminiThoughtSignatureState) TaggedSummariesAvailable

func (s *GeminiThoughtSignatureState) TaggedSummariesAvailable() bool

type GenerateImageRequest

type GenerateImageRequest struct {
	Prompt       string
	Size         string
	Quality      string
	OutputFormat string
}

type GeneratedImage

type GeneratedImage struct {
	Data          []byte
	MIMEType      string
	Extension     string
	RevisedPrompt string
}

type InstallSkillResult

type InstallSkillResult struct {
	Names        []string `json:"names"`
	Descriptions []string `json:"descriptions"`
}

InstallSkillResult 记录一次安装落地的 skill 列表

func InstallSkill

func InstallSkill(rawURL string) (*InstallSkillResult, error)

InstallSkill 从 GitHub 仓库或直链下载并安装 skill 到 SkillsDir()。 支持的输入:owner/repo 简写、整条 "npx skills add owner/repo -g" 命令、 完整 GitHub 仓库/子目录/commit URL、raw SKILL.md 直链、release zip 直链。

type Markdown

type Markdown struct {
	InlineAsterisk               bool  `json:"inlineAsterisk"`               // 是否启用行级 * 语法
	InlineUnderscore             bool  `json:"inlineUnderscore"`             // 是否启用行级 _ 语法
	InlineSup                    bool  `json:"inlineSup"`                    // 是否启用行级上标
	InlineSub                    bool  `json:"inlineSub"`                    // 是否启用行级下标
	InlineTag                    bool  `json:"inlineTag"`                    // 是否启用行级标签
	InlineMath                   bool  `json:"inlineMath"`                   // 是否启用行级公式
	InlineStrikethrough          bool  `json:"inlineStrikethrough"`          // 是否启用行级删除线
	InlineFullWidthStrikethrough bool  `json:"inlineFullWidthStrikethrough"` // 是否启用全角行级删除线
	BlockFullWidthTaskList       *bool `json:"blockFullWidthTaskList"`       // 是否启用全角任务列表快捷输入
	InlineMark                   bool  `json:"inlineMark"`                   // 是否启用行级标记
	CodeBlockMiddleDot           *bool `json:"codeBlockMiddleDot"`           // 是否启用中点代码块快捷输入
}

func NewMarkdown

func NewMarkdown() *Markdown

NewMarkdown 返回独立的默认语法配置,不引用运行时设置。

type Notifications

type Notifications struct {
	DocTreeMaxList         bool  `json:"docTreeMaxList"`                   // 文档面板展开上限提示,默认启用
	TagMaxList             bool  `json:"tagMaxList"`                       // 标签面板展开上限提示,默认启用
	WorkspaceNotSSD        bool  `json:"workspaceNotSSD"`                  // 工作空间未放置在固态硬盘警告,默认启用
	BrowserCompatibility   bool  `json:"browserCompatibility"`             // 浏览器兼容性提示,默认启用
	SelectAllTip           *bool `json:"selectAllTip,omitempty"`           // 编辑器全选提示,nil 时默认启用
	SelectAllIncompleteTip *bool `json:"selectAllIncompleteTip,omitempty"` // 编辑器全选不完整提示,nil 时默认启用
	FormatPainterTip       *bool `json:"formatPainterTip,omitempty"`       // 格式刷启用和退出提示,nil 时默认启用
}

Notifications 外观通知开关配置。https://github.com/siyuan-note/siyuan/issues/17797 Appearance.Notifications 为 nil 时表示旧配置尚未迁移,整体按默认启用处理。

func NewNotifications

func NewNotifications() *Notifications

NewNotifications 创建默认全部启用的通知配置。新增内置通知时在此统一调整默认值,避免多处分散。

type OpenAICompletionStream

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

OpenAICompletionStream 将各生成协议的流式输出统一为 Chat 增量, 让现有上层渲染、重试和工具执行逻辑保持一致。

func CreateOpenAICompletionStream

func CreateOpenAICompletionStream(ctx context.Context, client *AIClient, protocol string,
	request openai.ChatCompletionRequest, responseInput []any) (*OpenAICompletionStream, error)

func (*OpenAICompletionStream) Close

func (stream *OpenAICompletionStream) Close()

func (*OpenAICompletionStream) NativeContent

func (stream *OpenAICompletionStream) NativeContent() *AIMessageContent

func (*OpenAICompletionStream) Recv

func (*OpenAICompletionStream) ResponseOutput

func (stream *OpenAICompletionStream) ResponseOutput() []json.RawMessage

type OpenAIImageAdapter

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

func NewOpenAIImageAdapter

func NewOpenAIImageAdapter(apiKey, apiBaseURL, model string, timeout int, headers ...map[string]string) *OpenAIImageAdapter

func (*OpenAIImageAdapter) Generate

func (adapter *OpenAIImageAdapter) Generate(ctx context.Context, request GenerateImageRequest) (GeneratedImage, error)

type OperationWatchdog

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

OperationWatchdog 在操作仍未返回时记录阶段和调用栈,不取消操作、不改变数据写入顺序。

func WatchOperation

func WatchOperation(name, stage string) *OperationWatchdog

func (*OperationWatchdog) Finish

func (w *OperationWatchdog) Finish()

func (*OperationWatchdog) Stage

func (w *OperationWatchdog) Stage(stage string)

type Optional

type Optional[T any] struct {
	Value  T
	Exists bool
	IsNull bool
}

Optional is a generic type that represents an optional value, which can be in one of three states:

  • not set (Exists=false)
  • set to a non-null value (Exists=true, IsNull=false)
  • explicitly set to null (Exists=true, IsNull=true).

This allows distinguishing between "not provided" and "explicitly null" when unmarshaling JSON.

func (Optional[T]) HasValue

func (o Optional[T]) HasValue() bool

func (Optional[T]) IsZero

func (o Optional[T]) IsZero() bool

func (Optional[T]) MarshalJSON

func (o Optional[T]) MarshalJSON() ([]byte, error)

func (*Optional[T]) UnmarshalJSON

func (o *Optional[T]) UnmarshalJSON(data []byte) error

type PandocRuntime

type PandocRuntime struct {
	BinPath         string
	TemplatePath    string
	ColorFilterPath string
}

func GetPandocRuntime

func GetPandocRuntime() PandocRuntime

type Performance

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

Performance 记录单次同步操作的阶段耗时;名称和计数键仅使用代码内固定值,不写入正文或路径。

func BeginPerformance

func BeginPerformance(operation string) *Performance

BeginPerformance 仅在进程启动前设置 SIYUAN_PERFORMANCE=1 时分配记录,默认不采样。

func (*Performance) Count

func (p *Performance) Count(name string, value int64)

Count 保存当前操作的规模,不采集进程全局内存以免混淆并发请求的归属。

func (*Performance) Finish

func (p *Performance) Finish()

func (*Performance) Stage

func (p *Performance) Stage(stage string)

Stage 结束上一个阶段;相同名称的多个阶段累计耗时。

type PluginDevelopmentGrant

type PluginDevelopmentGrant struct {
	SessionID      string
	TaskID         string
	PlanHash       string
	PlanVersion    int
	SkillVersion   string
	SkillDigest    string
	Frontend       string
	PackageName    string
	SourceRoot     string
	SourcePath     string
	SourceRevision string
	AllowFiles     []string
}

PluginDevelopmentGrant 只由智能体运行时从服务器保存的确认记录投影,不接受工具 JSON 构造。

func RequirePluginDevelopment

func RequirePluginDevelopment(ctx context.Context, operation string) (*PluginDevelopmentGrant, error)

type PluginProjectArtifact

type PluginProjectArtifact struct {
	PackagePath     string            `json:"packagePath"`
	PackageHash     string            `json:"packageHash"`
	SourceRevision  string            `json:"sourceRevision"`
	PackageName     string            `json:"packageName"`
	Version         string            `json:"version"`
	Frontend        string            `json:"frontend"`
	FileListDigest  string            `json:"fileListDigest"`
	PackagerVersion string            `json:"packagerVersion"`
	Checks          map[string]string `json:"checks"`
	DeliveryPath    string            `json:"deliveryPath,omitempty"`
	DownloadURL     string            `json:"downloadURL,omitempty"`
}

type PluginProjectExcludedFile

type PluginProjectExcludedFile struct {
	Path   string `json:"path"`
	Reason string `json:"reason"`
}

type PluginProjectFile

type PluginProjectFile struct {
	Path     string `json:"path"`
	Revision string `json:"revision"`
	Bytes    int64  `json:"bytes"`
}

type PluginProjectMutation

type PluginProjectMutation struct {
	OldRevision string `json:"oldRevision"`
	NewRevision string `json:"newRevision"`
}

type PluginProjectStatus

type PluginProjectStatus struct {
	TaskID           string                      `json:"taskId,omitempty"`
	Prepared         bool                        `json:"prepared"`
	SourceRoot       string                      `json:"sourceRoot,omitempty"`
	SourceRevision   string                      `json:"sourceRevision"`
	BaselineRevision string                      `json:"baselineRevision,omitempty"`
	Files            []PluginProjectFile         `json:"files"`
	Excluded         []PluginProjectExcludedFile `json:"excluded,omitempty"`
	Pending          bool                        `json:"pending"`
	ExternalChanges  bool                        `json:"externalChanges"`
	PlanMismatch     bool                        `json:"planMismatch"`
	Artifact         *PluginProjectArtifact      `json:"artifact,omitempty"`
	RecoveryScope    string                      `json:"recoveryScope,omitempty"`
}

func GetPluginProjectStatus

func GetPluginProjectStatus(ctx context.Context, taskID string) (ret *PluginProjectStatus, err error)

func InspectPluginProjectSource

func InspectPluginProjectSource(abs string, authorize func(string) error, selected ...[]string) (*PluginProjectStatus, error)

func PluginProjectArtifactStatus

func PluginProjectArtifactStatus(grant *PluginDevelopmentGrant, root *os.Root) (*PluginProjectStatus, error)

PluginProjectArtifactStatus 只读投影项目及制品状态,调用方须持有项目锁。

func PreparePluginProject

func PreparePluginProject(ctx context.Context, taskID string, authorize func(string) error, expectedSourceRevision ...string) (ret *PluginProjectStatus, err error)

func RestorePluginProject

func RestorePluginProject(ctx context.Context, taskID, expectedRevision string) (ret *PluginProjectStatus, err error)

RestorePluginProject 先持久化整次恢复日志;崩溃可能留下部分恢复结果。 再次恢复只接受各文件记录的旧版或新版字节,不覆盖未知外部修改。

type PreparedImage

type PreparedImage struct {
	Data       []byte
	MIMEType   string
	Width      int
	Height     int
	SourceSize int
}

func PrepareModelImage

func PrepareModelImage(data []byte, maxBytes, maxPixels, maxEdge int) (PreparedImage, error)

PrepareModelImage 校验并按需缩放图片,尽量保留多模态模型支持的原始格式和图片质量。

type PushMode

type PushMode int
const (
	PushModeBroadcast                   PushMode = 0 // 所有应用所有会话广播
	PushModeSingleSelf                  PushMode = 1 // 自我应用会话单播
	PushModeBroadcastExcludeSelf        PushMode = 2 // 非自我会话广播
	PushModeBroadcastExcludeSelfApp     PushMode = 4 // 非自我应用所有会话广播
	PushModeBroadcastApp                PushMode = 5 // 单个应用内所有会话广播
	PushModeBroadcastMainExcludeSelfApp PushMode = 6 // 非自我应用主会话广播
)

type RerankOptions

type RerankOptions struct {
	APIKey        string
	Endpoint      string
	Model         string
	RequestFormat RerankRequestFormat
	TopN          int
	Timeout       int
}

type RerankRequestFormat

type RerankRequestFormat string
const (
	RerankRequestFormatCohere    RerankRequestFormat = "cohere"
	RerankRequestFormatDashScope RerankRequestFormat = "dashscope"
)

type Result

type Result struct {
	Cmd       string         `json:"cmd"`
	ReqId     float64        `json:"reqId"`
	AppId     string         `json:"app"`
	SessionId string         `json:"sid"`
	PushMode  PushMode       `json:"pushMode"`
	Callback  any            `json:"callback"`
	Code      int            `json:"code"`
	Msg       string         `json:"msg"`
	Data      any            `json:"data"`
	Context   map[string]any `json:"context,omitempty"`
}

func NewCmdResult

func NewCmdResult(cmdName string, cmdId float64, pushMode PushMode) *Result

func NewResult

func NewResult() *Result

func (*Result) Bytes

func (r *Result) Bytes() []byte

type SessionData

type SessionData struct {
	Workspaces map[string]*WorkspaceSession // <WorkspacePath, WorkspaceSession>
}

SessionData represents the session.

func GetSession

func GetSession(c *gin.Context) *SessionData

GetSession returns session of the specified context.

func (*SessionData) Clear

func (sd *SessionData) Clear(c *gin.Context)

func (*SessionData) Save

func (sd *SessionData) Save(c *gin.Context) error

Save saves the current session of the specified context.

type SkillFileData

type SkillFileData struct {
	Entries        []SkillFileEntry
	Content        *string
	Revision       string
	ReadOnlyReason string
}

func ManageSkillFiles

func ManageSkillFiles(request SkillFileRequest) (SkillFileData, error)

type SkillFileEntry

type SkillFileEntry struct {
	Path     string
	IsDir    bool
	Editable bool
}

type SkillFileRequest

type SkillFileRequest struct {
	Action   string
	Path     string
	Target   string
	Content  string
	Revision string
}

type SkillInfo

type SkillInfo struct {
	Name        string `json:"name"`
	Description string `json:"description"`
}

func DiscoverSkills

func DiscoverSkills(enabledUserSkills []string) []SkillInfo

type SkillInstallation

type SkillInstallation struct {
	Name          string `json:"name"`
	URL           string `json:"url"`
	SourceScope   string `json:"sourceScope"`
	Repository    string `json:"repository,omitempty"`
	Ref           string `json:"ref,omitempty"`
	Subdirectory  string `json:"subdirectory,omitempty"`
	Commit        string `json:"commit,omitempty"`
	Digest        string `json:"digest"`
	InstalledAt   string `json:"installedAt"`
	SiYuanVersion string `json:"siyuanVersion"`
}

type SkillInstallationInfo

type SkillInstallationInfo struct {
	SkillInfo
	Installation *SkillInstallation `json:"installation"`
}

func DiscoverSkillInstallations

func DiscoverSkillInstallations(enabledUserSkills []string) ([]SkillInstallationInfo, error)

安装摘要是历史内容标识,不在列举时扫描当前目录,也不代表内容可信。

type SkillLoadResult

type SkillLoadResult struct {
	Name               string
	Source             string
	ID                 string
	Version            string
	Digest             string
	Content            string
	ResourcePath       string
	Resources          []string
	ResourcesTruncated bool
	SkillDir           string
}

SkillLoadResult 描述技能正文激活或单个资源读取的结果。

func LoadBuiltinSkill

func LoadBuiltinSkill(locator string, disabled []string) (*SkillLoadResult, error)

LoadBuiltinSkill 只解析准确的官方名称;调用方必须先校验可信会话授权。

func LoadSkill

func LoadSkill(locator string, enabledUserSkills []string) (*SkillLoadResult, error)

LoadSkill 按技能名加载正文,或按“技能名/相对路径”加载单个文本资源。

type StatusBar

type StatusBar struct {
	Version                                   int  `json:"version"`
	MsgTaskDatabaseIndexCommitDisabled        bool `json:"msgTaskDatabaseIndexCommitDisabled"`
	MsgTaskHistoryDatabaseIndexCommitDisabled bool `json:"msgTaskHistoryDatabaseIndexCommitDisabled"`
	MsgTaskAssetDatabaseIndexCommitDisabled   bool `json:"msgTaskAssetDatabaseIndexCommitDisabled"`
	MsgTaskHistoryGenerateFileDisabled        bool `json:"msgTaskHistoryGenerateFileDisabled"`
	MsgDataSyncDisabled                       bool `json:"msgDataSyncDisabled"`
}

func NewStatusBar

func NewStatusBar(mobile bool) *StatusBar

NewStatusBar 创建适合当前容器的状态栏消息默认配置。

func NormalizeStatusBar

func NormalizeStatusBar(statusBar *StatusBar, mobile bool) *StatusBar

NormalizeStatusBar 一次性迁移状态栏消息配置,迁移完成后保留用户的手动设置。

type TesseractProvider

type TesseractProvider struct{}

func (TesseractProvider) Available

func (TesseractProvider) Available() bool

func (TesseractProvider) Recognize

func (TesseractProvider) Recognize(parent context.Context, imgAbsPath string) (ret []map[string]string, err error)

type TextEdit

type TextEdit struct {
	OldText string `json:"oldText"`
	NewText string `json:"newText"`
}

type TextEditRange

type TextEditRange struct {
	Index     int `json:"index"`
	StartByte int `json:"startByte"`
	EndByte   int `json:"endByte"`
}

func ApplyTextEdits

func ApplyTextEdits(original string, edits []TextEdit) (string, []TextEditRange, error)

ApplyTextEdits 在同一份原始字节内容中定位全部锚点;重叠出现也视为不唯一,例如「aaa」中的「aa」。

type TextFileError

type TextFileError struct {
	Code    string `json:"code"`
	Message string `json:"message"`
	Written bool   `json:"written"`
	// contains filtered or unexported fields
}

TextFileError 说明目标是否可能已变化;result_unknown 必须先读取目标核实,不能直接重试修改。

func NewTextFileError

func NewTextFileError(code string, err error) *TextFileError

NewTextFileError 将结果码与错误原因分别保存,保留错误链供调用方判断。

func (*TextFileError) Error

func (e *TextFileError) Error() string

func (*TextFileError) Unwrap

func (e *TextFileError) Unwrap() error

type TextFileMutation

type TextFileMutation struct {
	Content          string
	Edits            []TextEdit // nil 表示条件写入,非 nil 表示增量编辑
	ExpectedRevision string
	IfAbsent         bool
	DryRun           bool
	// Validate 在提交前重新检查宿主持有的当前授权。
	Validate     func() error
	BeforeCommit func(oldRevision, newRevision string, temporaryPaths ...string) error
	AfterCommit  func() error
}

type TextFileMutationResult

type TextFileMutationResult struct {
	OldRevision   string          `json:"oldRevision"`
	NewRevision   string          `json:"newRevision"`
	Ranges        []TextEditRange `json:"ranges,omitempty"`
	DryRun        bool            `json:"dryRun"`
	Diff          string          `json:"diff,omitempty"`
	DiffTruncated bool            `json:"diffTruncated"`
}

func MutateTextFile

func MutateTextFile(ctx context.Context, root *os.Root, p string, request TextFileMutation) (TextFileMutationResult, error)

func MutateTextFileName

func MutateTextFileName(ctx context.Context, root *os.Root, p, target string, request TextFileMutation) (ret TextFileMutationResult, err error)

MutateTextFileName 支持带版本条件的文件删除(target 为空)和重命名(目标不得存在),也可移动二进制资源。 重命名前后两个名称都必须写入日志;项目锁和目标复核保护协议内写入,不承诺对外部写入的原子比较交换。

type UserSkillInfo

type UserSkillInfo struct {
	ID          string `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description"`
	Enabled     bool   `json:"enabled"`
	Shadowed    bool   `json:"shadowed"`
}

func DiscoverUserSkills

func DiscoverUserSkills(enabledUserSkills []string) []UserSkillInfo

type WorkspaceExitState

type WorkspaceExitState struct {
	Version          int    `json:"version"`
	PID              int    `json:"pid"`
	StartedAt        int64  `json:"startedAt"`
	Port             string `json:"port"`
	Phase            string `json:"phase"`
	ProcessStartedAt int64  `json:"processStartedAt,omitempty"` // 操作系统报告的创建时间;旧版标记缺少此字段。
}

func MarkWorkspaceExiting

func MarkWorkspaceExiting() *WorkspaceExitState

MarkWorkspaceExiting 记录当前退出请求,供桌面宿主在重新启动时等待旧内核结束。 该文件只用于提示,工作空间的独占访问仍由文件锁保证。

func (*WorkspaceExitState) SetPhase

func (state *WorkspaceExitState) SetPhase(phase string)

SetPhase 保留退出批次,等待更新选择或同步失败处理时仍允许宿主识别并接管。

type WorkspaceSession

type WorkspaceSession struct {
	AccessAuthCodeVersion string // 锁屏密码的 HMAC 摘要,会话不保存密码原文;修改密码后既有会话随之失效
	OIDCSessionVersion    string
	DesktopSessionID      string `json:",omitempty"` // 未记住的本机桌面登录所属内核启动批次
	OIDCBinding           string
	CaptchaID             string // 服务端验证码挑战 ID,验证码答案不写入会话
}

func GetWorkspaceSession

func GetWorkspaceSession(session *SessionData) (ret *WorkspaceSession)

type WorkspaceStorage

type WorkspaceStorage struct {
	Directories  map[string]int64
	AssetsSize   int64
	TotalSize    int64
	CalculatedAt int64
}

func GetWorkspaceStorage

func GetWorkspaceStorage(ctx context.Context, workspacePath string) (WorkspaceStorage, error)

GetWorkspaceStorage 合并同一工作空间的并发扫描,完成后不缓存,手动刷新读取最新文件大小。

Source Files

Jump to

Keyboard shortcuts

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