Documentation
¶
Index ¶
- Constants
- Variables
- func AESDecrypt(cryptStr string) []byte
- func AESEncrypt(str string) string
- func AddPushChan(session *melody.Session)
- func AgentInstructionsError(err error, language string) string
- func AgentInstructionsPath() string
- func AppearancePackagePath(kind, name string) string
- func AssetName(name, newID string) string
- func AuthCodeEquals(a, b string) bool
- func AuthThrottleCheck(key string) (retryAfter int)
- func AuthThrottleFail(key string)
- func AuthThrottleReset(key string)
- func BatchGetEmbeddings(texts []string, apiKey, baseURL, model string, dimensions, timeout int) (ret [][]float32, err error)
- func BeginPluginProjectMutation(grant *PluginDevelopmentGrant, name, oldRevision, newRevision string, ...) error
- func BeginPluginProjectMutations(grant *PluginDevelopmentGrant, changes map[string]PluginProjectMutation, ...) error
- func BindableInteractiveSession(app, id string) (*melody.Session, <-chan struct{})
- func BlockCount(fsize int64) int
- func BootL10n(num int, fallback string) string
- func BootMobile(container, appDir, workspaceBaseDir, lang string)
- func BootWithFlags(workspacePath, wdPath, port, readOnly, accessAuthCode, lang, mode string, ...)
- func BoxIDFromDataPath(absPath string) string
- func Broadcast(msg []byte)
- func BroadcastByType(typ, cmd string, code int, msg string, data any)
- func BroadcastByTypeAndApp(typ, app, cmd string, code int, msg string, data any)
- func BroadcastByTypeAndExcludeApp(excludeApp, typ, cmd string, code int, msg string, data any)
- func BuiltInAppearancePath() string
- func CalSha1(b []byte, r io.Reader) ([]byte, error)
- func CeilSize(size int64) int64
- func ChatGPT(msg string, contextMsgs []string, c *AIClient, ...) (ret string, stop bool, err error)
- func ChatGPTService() *chatgpt.Service
- func ChatMessagesToOpenAIResponseInput(messages []openai.ChatCompletionMessage) []any
- func CheckEncryptedIndexCompatibility(db *sql.DB, kind string, schema int) error
- func CheckFileSysStatus()
- func CheckHostSSRF(host string) error
- func CheckSingleLinkRegularFile(file *os.File) error
- func CleanNotExistAssetsTexts(exists func(string) bool)
- func CleanupLegacyFonts(appearanceRoot string) error
- func ClearPushProgress(total int)
- func ClearWorkspaceExitMarker()
- func CloneOpenAIResponseOutput(output []json.RawMessage) []json.RawMessage
- func CloseOIDCSessions()
- func ClosePublishServiceSessions()
- func ClosePushChan(id string)
- func CompactOpenAIResponse(ctx context.Context, client *AIClient, request openai.ChatCompletionRequest, ...) ([]json.RawMessage, *openai.ResponseUsage, error)
- func ConsumeCaptchaChallenge(id, answer string) bool
- func ContainsCJK(text string) bool
- func ContainsSubStr(s string, subStrs []string) bool
- func ContextPushMsg(context map[string]any, msg string)
- func ContextWithAIMessageContents(ctx context.Context, contents []*AIMessageContent) context.Context
- func ContextWithGeminiThoughtSignatureState(ctx context.Context, state *GeminiThoughtSignatureState) context.Context
- func ContextWithGeminiThoughtSummaries(ctx context.Context) context.Context
- func ContextWithOpenAIChatTemperature(ctx context.Context, temperature float32) context.Context
- func ContextWithOpenAIResponsesBaseURL(ctx context.Context, baseURL string) context.Context
- func ContextWithOpenAIResponsesDefaultSampling(ctx context.Context) context.Context
- func Convert2Float(s string) (float64, bool)
- func ConvertIframeToLink(htmlStr string) string
- func ConvertPandoc(dir string, args ...string) (path string, err error)
- func CopyAssetTextForRelink(oldPath, newPath, historyDir string, dryRun bool) (exists bool, err error)
- func CopyDir(src, dst string) error
- func CopyFile(src, dst string) error
- func CopyFileWithChangeTracking(source, destination string) error
- func CopyPath(src, dst string) error
- func CopyUserFile(source, destination string) error
- func CountIf(list any, op string, threshold any) int
- func CountSessions() (ret int)
- func CreateCustomFontTemp() (*os.File, error)
- func CreateOpenAICompletion(ctx context.Context, client *AIClient, protocol string, ...) (openai.ChatCompletionResponse, error)
- func CurrentTimeMillis() int64
- func CurrentTimeSecondsStr() string
- func CustomFontDir() string
- func DataSize() (dataSize, assetsSize int64)
- func Decrypt(key, ciphertext []byte) ([]byte, error)
- func DecryptWithAAD(key, ciphertext, aad []byte) ([]byte, error)
- func DeduplicateWorkspacePaths(paths []string) []string
- func DeepSeekWebFetch(ctx context.Context, options DeepSeekWebOptions, rawURL, format string) (string, error)
- func DeepSeekWebSearch(ctx context.Context, options DeepSeekWebOptions, query string) (string, error)
- func DeriveKey(password string, salt []byte, p Argon2Params) []byte
- func DeriveSubKey(dek []byte, purpose string) []byte
- func DisableFeature(feature string)
- func DiscardCustomFontTemp(tempPath string)
- func EmojiPinYinCompare(str1, str2 string) bool
- func Encrypt(key, plaintext []byte) ([]byte, error)
- func EncryptWithAAD(key, plaintext, aad []byte) ([]byte, error)
- func EncryptedBlockTreeDBPath(boxID string) string
- func EncryptedDBPath(boxID string) string
- func EncryptionNonce(ciphertext []byte) ([]byte, error)
- func EscapeHTML(s string) (ret string)
- func ExceedLargeFileWarningSize(fileSize int) bool
- func ExistsAssetText(asset string) (ret bool)
- func ExpandGlobBrace(pattern string) []string
- func Ext(name string) (ret string)
- func ExtraBodyForModel(model string) map[string]any
- func ExtractArchiveEntry(entry *zip.File, destination string) error
- func FileURLToLocalPath(fileURL string) string
- func FilterFileName(name string) string
- func FilterFilePath(p string) (ret string)
- func FilterIconValue(icon string) (ret string, valid bool)
- func FilterMoveDocFromPaths(fromPaths []string, toPath string) (ret []string)
- func FilterRecentIconValue(icon string) (ret string, valid bool)
- func FilterRecentIconValues(icons []string) (ret []string)
- func FilterSelfChildDocs(paths []string) (ret []string)
- func FilterUploadEmojiFileName(name string) string
- func FilterUploadFileName(name string) string
- func FinishPluginProjectMutation(grant *PluginDevelopmentGrant, name string) error
- func FinishPluginProjectMutations(grant *PluginDevelopmentGrant, paths []string) error
- func GenerateDEK() ([]byte, error)
- func GenerateSalt() ([]byte, error)
- func GetAbsPathInWorkspace(relPath string) (string, error)
- func GetAssetText(asset string) (ret string)
- func GetBootProgress() int32
- func GetBootProgressDetails() (progress int32, details string)
- func GetChildDocDepth(treeAbsPath string) (ret int)
- func GetCloudAccountServer() string
- func GetCloudAssetsServer() string
- func GetCloudForumAssetsServer() string
- func GetCloudServer() string
- func GetCloudSyncServer() string
- func GetCloudWebSocketServer() string
- func GetContainsSubStrs(s string, subStrs []string) (ret []string)
- func GetDataAssetsAbsPath() (ret string)
- func GetDeviceID() string
- func GetDeviceName() string
- func GetDiskUsage(p string) (total, used, free uint64)
- func GetDuplicateName(master string) (ret string)
- func GetEtag(filename string) (etag string, err error)
- func GetEtagByHandle(f io.Reader, size int64) (etag string, err error)
- func GetFilePathsByExts(dirPath string, exts []string) (ret []string)
- func GetLocalIPs() []string
- func GetMimeTypeByExt(filePath string) (ret string)
- func GetMimeTypeByPath(filePath string) (m *mimetype.MIME, ok bool)
- func GetOSPlatform() (plat string)
- func GetOcrJsonText(jsonData []map[string]string) (ret string)
- func GetOrCreateTLSCert() (certPath, keyPath string, err error)
- func GetPrivateIPv4s() (ret []string)
- func GetRemoteAddr(req *http.Request) string
- func GetRequestUrlStringParam(c *gin.Context, key string) string
- func GetRhyBazaarHash(ctx context.Context) string
- func GetRhyResult(ctx context.Context, force bool) (map[string]any, error)
- func GetServerAddrs() (ret []string)
- func GetTodayStart() (ret time.Time)
- func GetTokenEncoding(modelName string) (*tiktoken.Tiktoken, error)
- func GetTreeID(treePath string) string
- func GetUniqueFilename(filePath string) string
- func HTTPRequest(method, rawURL string, headers map[string]string, body string) (statusCode int, contentType string, text string, err error)
- func HasDuplicateQueryValues(r *http.Request) bool
- func HasForwardedHeaders(request *http.Request) bool
- func HasUnclosedHtmlTag(htmlStr string) bool
- func HookUILoaded()
- func HumanizeDiffTime(a, b time.Time, lang string) string
- func HumanizeRelTime(a time.Time, b time.Time, lang string) string
- func HumanizeTime(then time.Time, lang string) string
- func I18nTerm(language, key string) (ret string)
- func ISOMonth(date time.Time) int
- func ISOWeek(date time.Time) int
- func ISOWeekDate(day int, date time.Time) time.Time
- func ISOYear(date time.Time) int
- func ImportCABundle(caCertPEM, caKeyPEM string) error
- func IncBootProgress(progress int32, details string)
- func IndexFixVersion() uint64
- func InitEmojiChars()
- func InitPandoc(customPandocBinPath string)
- func InitTesseract()
- func InitWorkspace(workspacePath, wdPath string)
- func InteractiveSession(app, id string) (*melody.Session, <-chan struct{})
- func IsAbsPathInWorkspace(absPath string) bool
- func IsAnthropicMessagesProtocol(protocol string) bool
- func IsAssetLinkDest(dest []byte, includeServePath bool) bool
- func IsAuthPageKeepaliveRequest(r *http.Request) bool
- func IsAuthSession(session *melody.Session) bool
- func IsBooted() bool
- func IsBrowserRequest(c *gin.Context) bool
- func IsCiphertext(data []byte) bool
- func IsCloudDrivePath(workspaceAbsPath string) bool
- func IsCommonExt(ext string) bool
- func IsCompressibleAssetImage(p string) bool
- func IsCrossSiteFetchSite(site string) bool
- func IsDirRegularOrSymlink(dir fs.DirEntry) bool
- func IsDisabledFeature(feature string) bool
- func IsDisplayableAsset(p string) bool
- func IsEmptyDir(p string) bool
- func IsForbiddenAbsPath(abs string) bool
- func IsForbiddenDataRelPath(rel string) bool
- func IsGeminiInteractionsProtocol(protocol string) bool
- func IsIdle(idleThreshold time.Duration) bool
- func IsIndexFixDirty() bool
- func IsLocalHost(host string) bool
- func IsLocalHostname(hostname string) bool
- func IsLocalOrigin(origin string) bool
- func IsLocalProxyRequest(request *http.Request) bool
- func IsMobileContainer() bool
- func IsMobileWorkspaceBaseDir(path string) bool
- func IsNativeEmoji(value string) bool
- func IsNetworkIconURL(icon string) bool
- func IsOfficeTempFile(assetAbsPath string) bool
- func IsOnline(checkURL string, skipTlsVerify bool, timeout int) bool
- func IsOpenAIResponsesProtocol(protocol string) bool
- func IsPartitionRootPath(path string) bool
- func IsPathRegularDirOrSymlinkDir(path string) bool
- func IsPluginDevelopmentRawPathForbidden(abs string, ancestors bool) bool
- func IsPluginDevelopmentRawWriteForbidden(abs string) bool
- func IsPluginProjectDeliveryPath(abs string) bool
- func IsPluginProjectPath(abs string) bool
- func IsPortOpen(port string) bool
- func IsPossiblyImage(assetPath string) bool
- func IsProtectedAgentStatePath(abs string) bool
- func IsPublishRelativePath(name string) bool
- func IsRelativePath(dest string) bool
- func IsReleaseVer(ver string) bool
- func IsReservedFilename(baseName string) bool
- func IsSecureRequest(request *http.Request) bool
- func IsSensitiveHTMLAssetPath(p string) bool
- func IsSensitivePath(p string) bool
- func IsSensitiveWritePath(p string) bool
- func IsSessionOriginAllowed(origin, host string) bool
- func IsSessionOriginAllowedRequest(r *http.Request) bool
- func IsSessionReady(session *melody.Session) bool
- func IsSymlink(dir fs.DirEntry) bool
- func IsSymlinkPath(absPath string) bool
- func IsSystemMetadataFile(name string) bool
- func IsTLSRequest(request *http.Request) bool
- func IsTesseractExtractable(p string) bool
- func IsTextFileError(err error, code string) bool
- func IsTimeStr(str string) bool
- func IsValidExistingEmojiFileName(name string) bool
- func IsValidIconUnicode(icon string) bool
- func IsValidPandocBin(binPath string) bool
- func IsValidRedirectHost(host string) bool
- func IsValidUploadFileName(name string) bool
- func IsWorkspaceDir(dir string) bool
- func IsWorkspaceLocked(workspacePath string) bool
- func LangToBCP47(lang string) string
- func LangToLegacy(lang string) string
- func LastID(p string) (name, id string)
- func LegacyAgentInstructionsPath() string
- func LegacyFontReplacement(relativePath string) string
- func LinkTarget(htmlStr, linkBase string) (ret string)
- func ListAvailableModels(apiKey, apiBaseURL string, timeout int) (models []string, err error)
- func LoadAssetsTexts()
- func LogDatabaseSize(dbPath string)
- func LogWebSocketError(session *melody.Session, channel string, err error)
- func MarkIndexClean(version uint64) bool
- func MarkIndexFixDirty()
- func MarkTLSEnforced()
- func MarshalOpenAIResponseOutput(output []any) ([]json.RawMessage, error)
- func MatchGlob(filename, pattern string) bool
- func MigrateAppearanceSyncIgnore() error
- func Millisecond2Time(t int64) time.Time
- func NaturalCompare(str1, str2 string) bool
- func NeedCaptcha() bool
- func NeedWarnDiskUsage(dataSize int64) bool
- func NewCaptchaChallenge(answer string) string
- func NewCustomReqClient() *req.Client
- func NewLute() (ret *lute.Lute)
- func NewOpenAIClient(apiKey, apiBaseURL string, headers ...map[string]string) *openai.Client
- func NewStdLute() (ret *lute.Lute)
- func NodeIDByTime(t time.Time) string
- func NormalizeAndResolve(p string) string
- func NormalizeConcurrentReqs(concurrentReqs int, provider int) int
- func NormalizeEndpoint(endpoint string) string
- func NormalizeLocalPath(endpoint string) string
- func NormalizeSysFontsJSON(raw string) string
- func NormalizeTemplatePath(p string) string
- func NormalizeTimeout(timeout int) int
- func NormalizeWebTimeout(timeout int) int
- func OCRAssetKey(asset string) string
- func OpenFileNoFollow(root *os.Root, name string) (*os.File, error)
- func OpenPluginProjectDirectory(abs string, create bool) (*os.Root, error)
- func OpenPublishFile(rootPath, name string) (*os.File, error)
- func OpenPublishReaderFile(rootPath, name string) (*os.File, error)
- func Pandoc(from, to, o, content string) (err error)
- func ParentHPath(hPath string) string
- func ParsePort(portString string) (uint16, error)
- func PinYinCompare(str1, str2 string) bool
- func PinYinCompare4FileTree(str1, str2 string) bool
- func PluginProjectDigest(data []byte) string
- func PluginProjectPrivateDir(taskID string) string
- func PluginProjectRegularFile(info os.FileInfo) bool
- func PluginProjectRoot(taskID string) string
- func PluginProjectTreeRevision(inventory map[string]string) string
- func PluginProjectsDir() string
- func PrepareLockScreenWallpaper(reader io.Reader) ([]byte, error)
- func PushBackgroundTask(data map[string]any)
- func PushBoxDocFeatureChanged()
- func PushClearAllMsg()
- func PushClearMsg(msgId string)
- func PushClearMsgWithApp(app, msgId string)
- func PushClearProgress()
- func PushDownloadProgress(id string, percent float32)
- func PushEndlessProgress(msg string)
- func PushErrMsg(msg string, timeout int) (msgId string)
- func PushErrMsgWithApp(app, msg string, timeout int) (msgId string)
- func PushEvent(event *Result)
- func PushKernelPluginState(name string, state int)
- func PushMsg(msg string, timeout int) (msgId string)
- func PushMsgWithApp(app, msg string, timeout int) (msgId string)
- func PushNodeOCRQueue(n *ast.Node)
- func PushProgress(code, current, total int, msg string)
- func PushProtyleLoading(rootID, msg string)
- func PushReloadDoc(rootID string)
- func PushReloadDocInfo(docInfo map[string]any)
- func PushReloadEmojiConf()
- func PushReloadFiletree()
- func PushReloadProtyle(rootID string)
- func PushReloadTag()
- func PushSaveDoc(rootID, typ string, sources any)
- func PushSetDefRefCount(rootID, blockID string, defIDs []string, refCount, rootRefCount int)
- func PushSetRefDynamicText(rootID, blockID, defBlockID, refText, boxID string)
- func PushStatusBar(msg string)
- func PushTxErr(msg string, code int, data any)
- func PushUpdateIDs(ids map[string]string)
- func PushUpdateMsg(msgId string, msg string, timeout int)
- func PushUpdateMsgWithApp(app, msgId, msg string, timeout int)
- func RandString(length int) string
- func RandomBuiltinEmoji() string
- func RandomSleep(minMills, maxMills int)
- func ReadLockScreenWallpaper(confDir string) ([]byte, error)
- func ReadSkill(name string, enabledUserSkills []string) (string, error)
- func ReadTextFile(root *os.Root, p string) (string, error)
- func ReadUserFile(p string) ([]byte, error)
- func ReadWorkspacePaths() (ret []string, err error)
- func RecheckPluginProjectGrant(ctx context.Context, expected *PluginDevelopmentGrant) error
- func RecordPluginProjectArtifact(grant *PluginDevelopmentGrant, artifact *PluginProjectArtifact) error
- func RefreshActivity()
- func RefreshRhyResultJob()
- func ReloadPublishServiceSessions()
- func ReloadUI()
- func ReloadUIResetScroll()
- func RemoveAssetText(asset string)
- func RemoveDatabaseFile(dbPath string)
- func RemoveEmojiInvisible(text string) (ret string)
- func RemoveEmptyDir(p string) (err error)
- func RemoveID(name string) string
- func RemoveInvalid(text string) (ret string)
- func RemoveInvalidRetainCtrl(text string) (ret string)
- func RemoveLockScreenWallpaper(confDir string) error
- func RemovePushChan(session *melody.Session)
- func RemoveRedundantSpace(str string) string
- func RemoveSkill(name string) error
- func RemoveWorkspacePath(paths []string, target string) []string
- func RemoveWorkspaceSession(session *SessionData)
- func RenameEmojiFile(oldPath, newPath string) error
- func RenameSkill(oldName, newName string) error
- func RenderOAuthCallbackPage(lang, title, message string, success bool) []byte
- func RenderOAuthRedirectPage(lang, title, target string) []byte
- func ReplaceNewline(text, replaceWith string) string
- func ReportFileSysFatalError(err error)
- func Rerank(query string, documents []string, options RerankOptions) (indices []int, scores []float64, err error)
- func ResolveLongestExistingParent(absPath string) string
- func ResolveRealPath(path string) (string, error)
- func RestrictConfFilePermissions()
- func RestrictSecretFile(path string)
- func RuntimeInfo(ctx context.Context) string
- func SHA256Hash(data []byte) string
- func SQLitePageCacheDSN() string
- func SSRFSafeDialer(timeout time.Duration) *net.Dialer
- func SanitizeHTML(h string) string
- func SanitizeName(name string) string
- func SanitizeSVG(svgInput string) (string, error)
- func SaveAssetsTexts()
- func SaveLockScreenWallpaper(confDir string, data []byte) error
- func SaveSkill(name, content string) error
- func ServeMultiplexed(ln net.Listener, handler http.Handler, certPath, keyPath string, ...) (*http.Server, *http.Server, error)
- func SessionCookieKeys(cookieKey string) (hashKey, blockKey []byte, err error)
- func SessionsByType(typ string) (ret []*melody.Session)
- func SetAssetText(asset, text string)
- func SetBootDetails(details string)
- func SetBooted()
- func SetHomeDir(homeDir string) error
- func SetLocalIPs(addresses []string)
- func SetNetworkProxy(proxyURL string, useSystem bool)
- func SetTLSRequired(required bool)
- func ShortPathForBootingDisplay(p string) string
- func ShouldRedirectToTLS(request *http.Request) bool
- func ShutdownHTTPServers(ctx context.Context, servers ...*http.Server)
- func SizeOfDirectory(path string) (size int64, err error)
- func SkillsDir() string
- func SnapshotPluginProject(root *os.Root, authorize func(string) error) (map[string][]byte, error)
- func SplitFileAnnotationRef(reference string) (assetLink, annotationID string)
- func SupportsOpenAIResponsesCompaction(ctx context.Context) bool
- func TLSEnforced() bool
- func TLSRedirectHandler(handler http.Handler) http.Handler
- func TLSRequired() bool
- func TestEmbeddingModel(apiKey, apiBaseURL, model string, dimensions, timeout int) (matched bool, dims int, err error)
- func TestModel(apiKey, apiBaseURL, protocol, model string, timeout int, ...) (available []string, matched bool, err error)
- func TestRerankModel(options RerankOptions) (matched bool, err error)
- func TextFileRevision(content []byte) string
- func TimeFromID(id string) (ret string)
- func ToFloat64(v any) (float64, bool)
- func TrimSpaceInPath(p string) string
- func TruncateLenFileName(name string) (ret string)
- func TruncateRunes(text string, maxRunes int) string
- func TruncateToolOutput(text, sessionID string) string
- func TruncateUTF8Bytes(text string, maxBytes int) string
- func UIProcessCount() (ret int)
- func UTF82GBK(src string) ([]byte, error)
- func UnescapeHTML(s string) (ret string)
- func UnlockWorkspace()
- func UserSkillsDir() string
- func ValidateAIProviderHeaders(headers map[string]string) error
- func ValidateDecisionImage(image DecisionImage) error
- func ValidateDecisionImageDetail(detail string) error
- func ValidateDecisionJSON(data json.RawMessage) error
- func ValidateDecisionQuestions(questions map[string]DecisionQuestion) error
- func ValidateDecisionQuestionsForProvider(provider string, questions map[string]DecisionQuestion) error
- func ValidateGeneratedImage(data []byte) (mimeType, extension string, err error)
- func ValidateID(idArg string) error
- func ValidateOptionalID(idArg string) error
- func ValidatePluginProjectFile(name string) error
- func ValidateTextFileContent(content string) error
- func ValidateTextFilePath(p string) error
- func WaitBindableInteractiveSession(ctx context.Context, app, id string) (*melody.Session, <-chan struct{})
- func WaitForTesseractInit()
- func WaitForTesseractInitContext(ctx context.Context) error
- func WaitForUILoaded()
- func WaitInteractiveSession(ctx context.Context, app, id string, expected *melody.Session) bool
- func WaitWorkspaceExitProcess(ctx context.Context, state WorkspaceExitState) error
- func WebFetch(rawURL, format string) (string, error)
- func WebFetchContext(ctx context.Context, rawURL, format string, timeout int) (string, error)
- func WebSearchContext(ctx context.Context, query, exaApiKey string, timeout int) (string, error)
- func Weekday(date time.Time) int
- func WeekdayCN(date time.Time) string
- func WeekdayCN2(date time.Time) string
- func WithPluginDevelopmentAccess(ctx context.Context, check func(string) (*PluginDevelopmentGrant, error)) context.Context
- func WithPluginProjectLockContext(ctx context.Context, taskID string, fn func() error) error
- func WithPluginProjectSource(ctx context.Context, write bool, ...) error
- func WrapGeminiThoughtSignatureTransport(base openai.HTTPDoer) openai.HTTPDoer
- func WriteFileByMmap(filePath string, data []byte) (err error)
- func WriteFileIfUnchanged(path string, original, data []byte) error
- func WriteFilePaths(paths []string) error
- func WriteFileWithChangeTracking(path string, data []byte) error
- func WriteFileWithPreflight(path string, data []byte, useMmap bool, check func([]byte) error) error
- func WriteUserFile(p string, data []byte) error
- func WriteWorkspacePaths(workspacePaths []string) (err error)
- type AIClient
- type AIMessageContent
- type AgentInstructions
- type Argon2Params
- type AssetTextRelinkMapping
- type AssetTextRelinkPlan
- type AssetTextRelinkResult
- type AtomicValue
- type AvailableModel
- type BlockStatResult
- type BuiltinSkillInfo
- type CustomFont
- type DecisionAnswer
- type DecisionBlock
- type DecisionImage
- type DecisionInputTokensDetails
- type DecisionOptions
- type DecisionQuestion
- type DecisionResult
- type DecisionState
- type DecisionUsage
- type DeepSeekWebOptions
- type Font
- type GeminiThoughtSignatureState
- type GenerateImageRequest
- type GeneratedImage
- type InstallSkillResult
- type Markdown
- type Notifications
- type OpenAICompletionStream
- type OpenAIImageAdapter
- type OperationWatchdog
- type Optional
- type PandocRuntime
- type Performance
- type PluginDevelopmentGrant
- type PluginProjectArtifact
- type PluginProjectExcludedFile
- type PluginProjectFile
- type PluginProjectMutation
- type PluginProjectStatus
- func GetPluginProjectStatus(ctx context.Context, taskID string) (ret *PluginProjectStatus, err error)
- func InspectPluginProjectSource(abs string, authorize func(string) error, selected ...[]string) (*PluginProjectStatus, error)
- func PluginProjectArtifactStatus(grant *PluginDevelopmentGrant, root *os.Root) (*PluginProjectStatus, error)
- func PreparePluginProject(ctx context.Context, taskID string, authorize func(string) error, ...) (ret *PluginProjectStatus, err error)
- func RestorePluginProject(ctx context.Context, taskID, expectedRevision string) (ret *PluginProjectStatus, err error)
- type PreparedImage
- type PushMode
- type RerankOptions
- type RerankRequestFormat
- type Result
- type SessionData
- type SkillFileData
- type SkillFileEntry
- type SkillFileRequest
- type SkillInfo
- type SkillInstallation
- type SkillInstallationInfo
- type SkillLoadResult
- type StatusBar
- type TesseractProvider
- type TextEdit
- type TextEditRange
- type TextFileError
- type TextFileMutation
- type TextFileMutationResult
- type UserSkillInfo
- type WorkspaceExitState
- type WorkspaceSession
- type WorkspaceStorage
Constants ¶
const ( BuiltinPluginSkillID = "builtin:" + PluginDevelopmentSkillName BuiltinPluginSkillVersion = "1.0.0" )
const ( TLSCACertFilename = "ca.crt" TLSCAKeyFilename = "ca.key" TLSCertFilename = "cert.pem" TLSKeyFilename = "key.pem" )
const ( BazaarStatServer = "https://bazaar.b3logfile.com" // 集市包统计服务地址,七牛云,全球 CDN BazaarOSSServer = "https://oss.b3logfile.com" // 云端对象存储地址,七牛云,仅用于读取集市包,全球 CDN )
const ( MaxCustomFontSize int64 = 64 * 1024 * 1024 CustomFontFamilyPrefix = "SiYuanCustomFont-" )
const ( DecisionProviderTypeSafe = "typesafe" DecisionProviderOpenAI = "openai" )
const ( BLOCK_BITS = 22 // Indicate that the blocksize is 4M BLOCK_SIZE = 1 << BLOCK_BITS )
const ( FontSpacingProportional = "proportional" FontSpacingDual = "dual" FontSpacingMonospace = "monospace" FontSpacingCharacterCell = "character-cell" )
const ( OpenAIProtocolChatCompletions = "openai" OpenAIProtocolResponses = "openai-responses" )
const ( PluginProjectMissingRevision = "missing" PluginProjectMaxFiles = 1024 PluginProjectMaxFileBytes int64 = 16 * 1024 * 1024 PluginProjectMaxBytes int64 = 64 * 1024 * 1024 )
const ( EvtSQLHistoryRebuild = "sql.history.rebuild" EvtSQLAssetContentRebuild = "sql.assetContent.rebuild" )
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:未指定排序规则,按照笔记本优先于文档树获取排序规则 )
const ( TextFileRevisionConflict = "revision_conflict" TextFileInvalidPath = "invalid_path" TextFileUnsupportedEncoding = "unsupported_encoding" TextFileTooLarge = "too_large" TextFileBackupFailed = "backup_failed" TextFileResultUnknown = "result_unknown" TextFileWriteFailed = "write_failed" TextFileCancelled = "cancelled" )
const ( // ClientTLSHeader 由本机的固定端口反向代理写入,标记客户端到反代这一跳是否使用 TLS。 // 反代以 HTTPS 回源内核,若不额外标记,内核会把明文客户端的连接误判为 TLS。 ClientTLSHeader = "X-SiYuan-Client-TLS" // ClientTLSHeaderValue 为标记 TLS 的头部取值。 ClientTLSHeaderValue = "1" // ClientTLSHeaderPlaintextValue 为标记客户端使用明文连接的头部取值。 ClientTLSHeaderPlaintextValue = "0" // StrictTransportSecurityValue 为 HTTPS 响应附加的 HSTS 策略,有效期一年。 StrictTransportSecurityValue = "max-age=31536000" )
const ( PushProgressCodeProgressed = 0 // 有进度 PushProgressCodeEndless = 1 // 无进度 PushProgressCodeEnd = 2 // 关闭进度 )
const ( ContainerStd = "std" // 桌面端 ContainerDocker = "docker" // Docker 容器端 ContainerAndroid = "android" // Android 端 ContainerIOS = "ios" // iOS 端 ContainerHarmony = "harmony" // 鸿蒙端 LocalHost = "127.0.0.1" // 伺服地址 FixedPort = "6806" // 固定端口 )
const AnthropicProtocolMessages = "anthropic-messages"
const DatabaseVer = "202607031200"
DatabaseVer 数据库版本。 格式:yyyyMMddHHmm。修改表结构时需要更新此值,启动时会检测版本变化, 若不一致则自动移除旧数据库文件并重建表结构,同时触发全量重建索引。
const DecisionJSONMaxBytes = 256 * 1024
const DecisionMaxBytes = 1024 * 1024
DecisionMaxBytes 限制单次请求和响应的内存占用,不替代供应商的 token 限制。
const DefaultLargeFileWarningSize = 8
const DefaultUseSingleLineSave = true
const ( // EncryptionSpec 表示 AES-GCM 密文信封规范版本。 EncryptionSpec byte = 1 )
const GeminiProtocolInteractions = "gemini-interactions"
const LocalProxyHeader = "X-Siyuan-Local-Proxy"
LocalProxyHeader 是内置 fixed-port 代理回源时携带的进程内标记头。 第三方反向代理无法得知该标记,带转发头的请求不能再据此获得本机信任。
const LockScreenWallpaperMaxBytes = 10 << 20
const MaxAgentInstructionsSize = 32 * 1024
const MaxTextFileBytes = 8 * 1024 * 1024
const MaxToolOutputChars = 40000
const MaxUIProcessCount = 64
MaxUIProcessCount UI 进程注册表条目数上限。
const OperationStallLogName = "operation-stall.log"
const PluginDevelopmentSkillName = "siyuan-plugin-development"
const ( // SQLFlushInterval 为数据库事务队列写入间隔。 SQLFlushInterval = 3000 * time.Millisecond )
const SessionCookieName = "siyuan"
SessionCookieName 是会话 Cookie 的名称。Cookie 不按端口隔离,同一主机上的各工作空间共用该 Cookie。
const StatusBarVersion = 1
StatusBar 底部状态栏配置。https://github.com/siyuan-note/siyuan/issues/16236
const Ver = "3.8.10"
Variables ¶
var ( TesseractBin = "tesseract" TesseractEnabled bool TesseractMaxSize = 2 * 1000 * uint64(1000) TesseractLangs []string )
var ( NodeOCRQueue []string NodeOCRQueueLock = sync.Mutex{} )
var ( SSL = false UserAgent = "SiYuan/" + Ver )
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"} )
var ( UseSingleLineSave = NewAtomicValue(DefaultUseSingleLineSave) // UseSingleLineSave 是否使用单行保存 .sy 和数据库 .json 文件。 LargeFileWarningSize = NewAtomicValue(DefaultLargeFileWarningSize) // LargeFileWarningSize 大文件警告大小,单位:MB )
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{} )
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") )
var ( WebSocketServer *melody.Melody // ReloadDocInfoGuard 由 model 层注入,在广播 docInfo 前检查 box 是否仍处于可广播状态。 // 加密笔记本锁定后返回 false,防止 500ms 延迟任务在锁定后泄漏明文元数据。 ReloadDocInfoGuard func(boxID string) bool )
var ( RunInContainer = false // 是否运行在容器中 SiYuanAccessAuthCodeBypass = false // 是否跳过空锁屏密码检查 AttachUI = false // 是否绑定桌面 UI 进程生命周期(Electron 拉起时为 true,手动 serve 为 false) EnablePprof = false // 是否注册未鉴权的调试端点,仅调试时显式开启,切勿在对外开放的实例上使用 FixedPortEnabled = true // 是否启动额外的 6806 固定端口反代,不影响主服务监听端口 )
var ( HttpServer *http.Server // HTTP 伺服器实例 HttpsServer *http.Server // HTTPS 伺服器实例 HttpServing = false // 是否 HTTP 伺服已经可用 SafeMode = false // 是否以安全模式启动:禁用代码片段、插件、自定义主题与图标 )
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 )
var ( ServerURL *url.URL // 内核服务 URL ServerPort = "0" // HTTP/WebSocket 端口,0 为使用随机端口 ReadOnly bool AccessAuthCode string Lang = "" Container string // docker, android, ios, harmony, std ISMicrosoftStore bool // 桌面端是否是微软商店版 )
var CLILogLevel string
CLILogLevel 在 CLI 子命令通过 --log-level 显式指定日志级别时被设置,model.InitConf 末尾据此跳过对 logging.SetLogLevel 的覆盖,使命令行参数优先于 conf.json 的 system.logLevel。
var CurrentCloudRegion = 0
var DisabledFeatures []string
var ErrAgentInstructionsConflict = errors.New("AGENTS.md changed; reload it before saving")
var ErrAgentInstructionsLocationConflict = errors.New("data/ai/AGENTS.md and data/storage/ai/AGENTS.md differ; merge the files and remove the old file")
var ErrAgentInstructionsTooLarge = errors.New("AGENTS.md must be at most 32 KiB")
var ErrDecisionRefused = errors.New("decision provider refused to answer a question")
ErrDecisionRefused 区分供应商拒答和格式错误,不携带原始响应或笔记正文。
var ErrFileChanged = errors.New("source changed during operation")
ErrFileChanged 表示扫描后的源文件已变化,调用方必须保留当前文件并重新读取。
var ErrInvalidID = errors.New("invalid ID argument")
ErrInvalidID 表示块或笔记本 ID 不是合法的 SiYuan ID 形态。
var ErrInvalidLockScreenWallpaper = errors.New("invalid lock screen wallpaper")
var ErrPandocNotFound = errors.New("not found executable pandoc")
var IsExiting = atomic.Bool{}
IsExiting 是否正在退出程序。
var IsUILoaded atomic.Bool
IsUILoaded 是否已经加载了 UI。
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 标准语言代码。
var LocalProxyToken = newLocalProxyToken()
LocalProxyToken 是仅存在于当前进程内的随机标记,由内置 fixed-port 代理注入。
var MarkdownSettings = NewAtomicValue(NewMarkdown())
MarkdownSettings 运行时 Markdown 配置。
var MobileOSVer string
MobileOSVer 移动端操作系统版本。
var Mode = "prod"
var Mode = "dev"
var NotificationsCfg = NewAtomicValue[*Notifications](nil)
var (
RhyCacheDuration = int64(3600 * 6)
)
var SK = []byte("696D897C9AA0611B")
var SearchCaseSensitive = NewAtomicValue(false)
var SearchHanSensitive = NewAtomicValue(true)
SearchHanSensitive 是否区分繁简,由 sql.SetHanSensitive 维护;默认 true 与既往行为一致
var StatusBarCfg = NewAtomicValue[*StatusBar](nil)
var SystemTempDir = os.TempDir()
SystemTempDir 保存工作空间初始化重定向之前的系统临时目录。
var WrongAuthCount int
Functions ¶
func AESDecrypt ¶
func AESEncrypt ¶
func AddPushChan ¶
func AgentInstructionsError ¶
func AgentInstructionsPath ¶
func AgentInstructionsPath() string
func AppearancePackagePath ¶
AppearancePackagePath 按包名区分内置资源和参与同步的第三方资源。
func AuthCodeEquals ¶
AuthCodeEquals 恒定时间比较认证码,避免通过响应时间差异猜测秘密。
func AuthThrottleCheck ¶
AuthThrottleCheck 返回 key 剩余锁定秒数,0 表示未锁定。
func BatchGetEmbeddings ¶
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 ¶
BindableInteractiveSession 只绑定当前有效的非发布主窗口,界面就绪检查由联网确认阶段执行。
func BlockCount ¶
func BootL10n ¶
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 ¶
BoxIDFromDataPath 从 data 目录下的绝对路径反推 boxID。 路径形如 <DataDir>/<boxID>/...,切出紧跟在 DataDir 后的一段;供文件系统层判断是否需整体解密、 以及 API 层判断资源是否属于加密笔记本。若不在 DataDir 下或 boxID 非合法 ID 模式,返回空串。
func BroadcastByType ¶
BroadcastByType 广播所有实例上 typ 类型的会话。
func BroadcastByTypeAndApp ¶
func BuiltInAppearancePath ¶
func BuiltInAppearancePath() string
BuiltInAppearancePath 返回当前运行模式下内置外观资源的目录。
func ChatGPTService ¶
ChatGPTService 按主机配置目录保存账户,移动端复用 BootMobile 配置的私有 HomeDir。
func ChatMessagesToOpenAIResponseInput ¶
func ChatMessagesToOpenAIResponseInput(messages []openai.ChatCompletionMessage) []any
func CheckEncryptedIndexCompatibility ¶
CheckEncryptedIndexCompatibility 将索引版本保存在受 SQLCipher 认证的表中,拒绝复用缺少版本或参数不匹配的旧索引。 schema 由各索引维护,修改表结构时递增;索引重建由已认证源文档的调用方负责。
func CheckFileSysStatus ¶
func CheckFileSysStatus()
func CheckHostSSRF ¶
CheckHostSSRF 校验主机名解析出的 IP 不落在内网/回环等不可达地址段, 防止智能体被诱导发起 SSRF 攻击。web_fetch 与 http_request 共用此校验。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-rg26-cg95-gq6p
func CheckSingleLinkRegularFile ¶
CheckSingleLinkRegularFile 在 Windows 上从文件句柄读取链接数,因为 FileInfo.Sys 不提供该字段。 无法确定链接数时拒绝操作。
func CleanupLegacyFonts ¶
CleanupLegacyFonts 在新版资源复制成功后清理原版历史字体,不递归删除目录或跟随符号链接。
func ClearPushProgress ¶
func ClearPushProgress(total int)
func ClearWorkspaceExitMarker ¶
func ClearWorkspaceExitMarker()
ClearWorkspaceExitMarker 仅在持有工作空间锁时清理临时状态,避免删除下一次启动的状态。
func CloneOpenAIResponseOutput ¶
func CloneOpenAIResponseOutput(output []json.RawMessage) []json.RawMessage
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 ¶
ConsumeCaptchaChallenge 校验验证码并立即删除挑战,同一挑战只能使用一次; ID 未知、挑战已过期或答案错误时返回 false。
func ContainsCJK ¶
func ContainsSubStr ¶
func ContextPushMsg ¶
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 ¶
ContextWithGeminiThoughtSummaries 请求 Gemini 返回可展示的思考摘要,仅用于 Agent 主响应。
func ContextWithOpenAIChatTemperature ¶
Chat 请求用上下文区分显式温度与未设置值,避免 SDK 的 omitempty 丢失零温度。
func ContextWithOpenAIResponsesBaseURL ¶
ContextWithOpenAIResponsesBaseURL 根据端点附加 Responses 请求兼容选项。
func ContextWithOpenAIResponsesDefaultSampling ¶
ContextWithOpenAIResponsesDefaultSampling 让未选择采样配置的调用方使用服务端默认值。 仅影响 Responses;其他调用方显式设置的零温度仍按原值发送。
func Convert2Float ¶
func ConvertIframeToLink ¶
func CopyAssetTextForRelink ¶
func CopyAssetTextForRelink(oldPath, newPath, historyDir string, dryRun bool) (exists bool, err error)
CopyAssetTextForRelink 复制 OCR 元数据,保留源资源的识别结果,并拒绝覆盖不同的目标结果。
func CopyFileWithChangeTracking ¶
CopyFileWithChangeTracking 复制单个文件并保留权限和时间,在目标文件锁内标记内容变化。
func CopyPath ¶
CopyPath 把源路径复制到目标路径,目录递归复制。 与 gulu.File.Copy 不同,这里按 0755 建立目录、不保留源文件权限,用于 CLI 与 MCP 的 file copy 工具。
func CopyUserFile ¶
CopyUserFile 的外部来源或目标可能被其他程序占用,错误交由导入、导出调用方处理。
func CountIf ¶
CountIf 统计数字列表中满足指定比较条件的元素个数。 op 为比较操作符:"gt"/"lt"/"eq"/"ge"/"le",threshold 为比较阈值。 例如 CountIf(values, "gt", 0) 统计大于 0 的个数。非数字元素按 0 处理。
func CountSessions ¶
func CountSessions() (ret int)
func CreateCustomFontTemp ¶
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 DecryptWithAAD ¶
DecryptWithAAD 对应 EncryptWithAAD 的解密。格式无效、AAD 不匹配或密文被篡改时返回错误。
func DeepSeekWebFetch ¶
func DeepSeekWebSearch ¶
func DeriveKey ¶
func DeriveKey(password string, salt []byte, p Argon2Params) []byte
DeriveKey 用 Argon2id 从密码派生密钥。同一 password+salt+params 多次调用结果一致。
func DeriveSubKey ¶
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 Encrypt ¶
Encrypt 用 AES-256-GCM 加密。每次调用生成随机 nonce,因此同一明文多次加密结果不同。 返回格式:magic(4B) || spec(1B) || algorithm(1B) || nonceLength(1B) || nonce || ciphertext || GCM tag(16B)。
func EncryptWithAAD ¶
EncryptWithAAD 用 AES-256-GCM 加密并绑定 AAD(附加认证数据)。 AAD 不被加密,但参与 GCM 认证——解密时必须提供相同 AAD,否则认证失败。 把用途/boxID/路径等元数据放入 AAD,可防止同 box 内密文被替换用途或路径(bind 到上下文)。 返回格式与 Encrypt 一致,但 AAD 参与校验。
func EncryptedBlockTreeDBPath ¶
EncryptedBlockTreeDBPath 返回加密笔记本的独立 SQLCipher blocktree db 文件路径。
func EncryptedDBPath ¶
EncryptedDBPath 返回加密笔记本的独立 SQLCipher db 文件路径。 与 siyuan.db 同放 temp 目录,文件名带 boxID 区分多个加密笔记本。db 是可重建的索引,非原始内容。
func EncryptionNonce ¶
EncryptionNonce 从 AES-GCM 密文信封中提取 nonce。
func EscapeHTML ¶
func ExistsAssetText ¶
func ExpandGlobBrace ¶
ExpandGlobBrace 把包含 {a,b} 的 glob 模式展开为多个不含花括号的模式。 不含花括号时原样返回单个模式。
func ExtraBodyForModel ¶
ExtraBodyForModel 按模型名大小写不敏感匹配内置清单,返回需注入的额外请求参数;无匹配返回 nil。
func ExtractArchiveEntry ¶
ExtractArchiveEntry 把 zip 条目解出到 destination,目录条目只创建目录。 文件条目按 0755 建立父目录并把修改时间对齐到条目时间;调用方负责路径越界校验。
func FileURLToLocalPath ¶
FileURLToLocalPath 将 file:// URL 转为本地文件路径。
func FilterFileName ¶
func FilterFilePath ¶
func FilterIconValue ¶
func FilterMoveDocFromPaths ¶
func FilterRecentIconValue ¶
func FilterRecentIconValues ¶
func FilterSelfChildDocs ¶
func FilterUploadFileName ¶
func FinishPluginProjectMutation ¶
func FinishPluginProjectMutation(grant *PluginDevelopmentGrant, name string) error
func FinishPluginProjectMutations ¶
func FinishPluginProjectMutations(grant *PluginDevelopmentGrant, paths []string) error
func GetAbsPathInWorkspace ¶
func GetAssetText ¶
func GetBootProgress ¶
func GetBootProgress() int32
func GetBootProgressDetails ¶
func GetChildDocDepth ¶
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 GetDataAssetsAbsPath ¶
func GetDataAssetsAbsPath() (ret string)
func GetDeviceID ¶
func GetDeviceID() string
func GetDeviceName ¶
func GetDeviceName() string
func GetDiskUsage ¶
func GetDuplicateName ¶
func GetFilePathsByExts ¶
func GetLocalIPs ¶
func GetLocalIPs() []string
func GetMimeTypeByExt ¶
func GetOSPlatform ¶
func GetOSPlatform() (plat string)
func GetOcrJsonText ¶
GetOcrJsonText 提取并连接所有 text 字段的函数
func GetOrCreateTLSCert ¶
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 GetRequestUrlStringParam ¶
GetRequestUrlStringParam extracts a string parameter from URL (path or query parameters).
func GetRhyBazaarHash ¶
func GetServerAddrs ¶
func GetServerAddrs() (ret []string)
func GetTodayStart ¶
func GetTokenEncoding ¶
GetTokenEncoding 共享离线分词器;未知模型使用 cl100k_base 估算,不下载词表。
func GetUniqueFilename ¶
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 ¶
HasDuplicateQueryValues 判断请求查询参数中是否存在重复键。
func HasForwardedHeaders ¶
HasForwardedHeaders 判断请求是否携带反向代理转发头。 这些头可能由调用方伪造,反向代理未经改写时不能作为本机信任依据。
func HasUnclosedHtmlTag ¶
func HookUILoaded ¶
func HookUILoaded()
func ISOMonth ¶
ISOMonth returns the month in which the Thursday of the ISO 8601 week of date occurs.
func ISOWeek ¶
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 ¶
ISOWeekDate returns the date of the specified day of the week in the ISO 8601 week of date. day: Monday=1, ..., Sunday=7.
func ImportCABundle ¶
ImportCABundle imports a CA certificate and private key from PEM-encoded strings.
func IncBootProgress ¶
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 ¶
InteractiveSession 仅接受已就绪的非发布主窗口;空标识不能退化成广播。
func IsAbsPathInWorkspace ¶
func IsAssetLinkDest ¶
func IsAuthPageKeepaliveRequest ¶
IsAuthPageKeepaliveRequest 判断是否为授权页保持连接请求,避免非常驻内存内核自动退出。 该请求无需认证,但连接必须被隔离在广播池之外。 https://github.com/siyuan-note/insider/issues/1099
func IsAuthSession ¶
func IsBrowserRequest ¶
IsBrowserRequest 判断请求是否来自浏览器(非 SiYuan 原生客户端)。 原生客户端(桌面 Electron、Android/iOS/Harmony)的 User-Agent 均以 "SiYuan/" 开头, 其余视为浏览器。该口径与前端 getFrontend()、Electron 主进程为各窗口设置的 UA 前缀 (app/electron/window/mainWindow.ts 等)以及 session 鉴权中既有的 HasPrefix(ua, "SiYuan/") 判断保持一致。
func IsCiphertext ¶
IsCiphertext 判断给定字节是否以加密信封魔数开头(即是否为密文)。 供历史索引等无法取得 boxID/DEK 的路径做防御性检测:读到密文时跳过解析而非按 JSON 报错, 避免加密笔记本的 AV 等对象因路径迁移(同步、导入、历史布局变化)落到全局位置时产生噪声错误。
func IsCloudDrivePath ¶
func IsCommonExt ¶
func IsCrossSiteFetchSite ¶
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 ¶
func IsDisabledFeature ¶
IsDisabledFeature 查询原生端启动时禁用的功能,不修改用户配置。
func IsDisplayableAsset ¶
func IsForbiddenAbsPath ¶
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 ¶
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 IsLocalHost ¶
func IsLocalHostname ¶
func IsLocalOrigin ¶
func IsLocalProxyRequest ¶
IsLocalProxyRequest 判断请求是否由内置 fixed-port 代理转发。
func IsMobileContainer ¶
func IsMobileContainer() bool
IsMobileContainer 表示当前内核运行在 Android、iOS 或鸿蒙客户端上。
func IsMobileWorkspaceBaseDir ¶
IsMobileWorkspaceBaseDir 判断路径是否为移动端保留的工作空间基目录。
func IsNativeEmoji ¶
func IsNetworkIconURL ¶
func IsOfficeTempFile ¶
IsOfficeTempFile 判断是否为 Office(Word/Excel/PowerPoint/WPS)打开文档时生成的临时文件。 这些文件名以 `~$` 开头,且被宿主程序独占,尝试读取会触发 filelock 的致命错误,需跳过。
func IsPartitionRootPath ¶
IsPartitionRootPath checks if the given path is a partition root path.
func IsPluginDevelopmentRawPathForbidden ¶
IsPluginDevelopmentRawPathForbidden 同时检查词法路径和链接目标;目录变更还保护宿主管理根的祖先。
func IsPluginProjectPath ¶
func IsPortOpen ¶
func IsPossiblyImage ¶
IsPossiblyImage 模糊判断指定文件链接是否可能是图片。
func IsProtectedAgentStatePath ¶
IsProtectedAgentStatePath 保护服务器运行状态,保留会话 output 目录的普通只读访问。
func IsPublishRelativePath ¶
IsPublishRelativePath 限定发布资源使用无歧义的相对路径,各平台采用相同的分段规则。
func IsRelativePath ¶
func IsReleaseVer ¶
IsReleaseVer 判断是否为正式版(不含 alpha、beta、rc 等预发布标识)。
func IsReservedFilename ¶
func IsSecureRequest ¶
IsSecureRequest 判断请求是否可以安全地承载会话凭据: 客户端连接使用 TLS,或来自本机(本机明文与内核自身 HTTPS 回源等价,且桌面端与浏览器扩展依赖本机明文)。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr
func IsSensitiveHTMLAssetPath ¶
IsSensitiveHTMLAssetPath 允许剪贴板引用用户文档及系统临时文件,仍检查凭据、工作空间私有目录和符号链接目标。
func IsSensitivePath ¶
IsSensitivePath 对传入路径做统一的敏感性检测。
为防止通过符号链接绕过黑名单,对工作空间外的路径会额外解析符号链接后再检查一次:这是 globalCopyFiles 等接受工作空间外绝对路径的接口的攻击面。工作空间内的路径不解析符号链接, 一是因为工作空间内文件(如 assets 中指向外部目录的符号链接)可能合法地指向工作空间外, 对其解析后执行系统目录前缀检查会误伤;二是避免在高 QPS 的伺服热路径上引入额外的 stat 开销。 目标尚未创建时解析最长已存在的父目录,避免别名下的新文件绕过敏感目录检查。
func IsSensitiveWritePath ¶
IsSensitiveWritePath 判断工作空间外的写入目标是否敏感。
除共用的敏感路径规则外,写方向额外拒绝家目录下第一层以 . 开头的路径:这些位置是 shell 初始化、 用户数据与浏览器配置的入口,写入即可获得持久化能力,而正常导出不会选择点目录。 工作空间内的目标不受这条规则影响,避免工作空间本身位于家目录点目录时误伤。
func IsSessionOriginAllowed ¶
IsSessionOriginAllowed 校验会话 Cookie 认证请求的 Origin,防止跨站请求伪造 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hhm2-g993-p656
func IsSessionOriginAllowedRequest ¶
IsSessionOriginAllowedRequest 校验会话认证请求:应用入口的顶层 GET 页面导航可放行, 其他跨源请求拒绝,其余请求继续校验 Origin。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-2w6q-wgc8-q743
func IsSessionReady ¶
IsSessionReady 未声明就绪协议的旧客户端沿用连接后即可接收控制消息的行为。
func IsSystemMetadataFile ¶
IsSystemMetadataFile 判断是否为操作系统自动生成的元数据文件(如 macOS 的 .DS_Store), 这类文件不属于业务数据,判空与清理时应忽略
func IsTLSRequest ¶
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 IsTextFileError ¶
func IsValidExistingEmojiFileName ¶
IsValidExistingEmojiFileName 保留已有表情名中的合法替换字符,新上传文件仍按命名规则清洗。
func IsValidIconUnicode ¶
IsValidIconUnicode 校验图标值是否为合法的十六进制码点序列(连字符分隔): 解码后不允许包含 HTML 元字符,防止图标值被渲染为可执行标记 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-vx5w-qrvp-mmcq
func IsValidPandocBin ¶
func IsValidRedirectHost ¶
IsValidRedirectHost 校验 Host 是否为可以直接拼接跳转地址的合法 authority。
仅接受 host 或 host:port 形式,拒绝凭据、路径、查询、片段与空白字符, 避免被污染的 Host 让 HTTPS 跳转指向站外地址。
func IsValidUploadFileName ¶
func IsWorkspaceLocked ¶
func LangToBCP47 ¶
LangToBCP47 把历史下划线标识映射为 BCP 47 标准语言代码(如 zh_CN → zh-CN)。 不是历史下划线标识时原样返回。
func LangToLegacy ¶
LangToLegacy 把 BCP 47 标准语言代码映射为历史下划线标识(如 zh-CN → zh_CN)。 不是 BCP 47 标准语言代码时原样返回。
func LegacyAgentInstructionsPath ¶
func LegacyAgentInstructionsPath() string
func LegacyFontReplacement ¶
LegacyFontReplacement 返回已知旧字体 URL 对应的新资源路径,仅用于旧文件缺失时的兼容读取。
func LinkTarget ¶
func ListAvailableModels ¶
ListAvailableModels 拉取 Provider 的可用模型清单(GET /v1/models),仅返回模型 ID 列表。 用于兼容不需要模型元数据的调用方。
func LoadAssetsTexts ¶
func LoadAssetsTexts()
func LogDatabaseSize ¶
func LogDatabaseSize(dbPath string)
func LogWebSocketError ¶
LogWebSocketError 忽略正常关闭,记录消息丢弃警告,其他连接错误保留在调试日志中。
func MarkIndexClean ¶
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 MarshalOpenAIResponseOutput ¶
func MarshalOpenAIResponseOutput(output []any) ([]json.RawMessage, error)
func MigrateAppearanceSyncIgnore ¶
func MigrateAppearanceSyncIgnore() error
MigrateAppearanceSyncIgnore 移除旧版生成的隔离块,保留用户规则、换行和编码标记;没有隔离块时不写文件。
func Millisecond2Time ¶
func NaturalCompare ¶
func NeedCaptcha ¶
func NeedCaptcha() bool
func NeedWarnDiskUsage ¶
func NewCaptchaChallenge ¶
NewCaptchaChallenge 保存验证码答案并返回随机挑战 ID,调用方只应把 ID 写入会话;生成失败时返回空字符串。
func NewOpenAIClient ¶
func NewStdLute ¶
func NodeIDByTime ¶
NodeIDByTime 根据指定时间生成符合块 ID 格式的字符串,算法与 ast.NewNodeID() 一致, 仅时间源不同:用于让历史输入(如移动端速记暂存文件名时间戳)回填为块 ID。
func NormalizeAndResolve ¶
NormalizeAndResolve 将路径转为绝对、解析符号链接和目录联接并清理;在需要时转为小写以实现不区分大小写比较。
func NormalizeConcurrentReqs ¶
func NormalizeEndpoint ¶
func NormalizeLocalPath ¶
func NormalizeSysFontsJSON ¶
原生平台仅负责发现可用字体,名称、字重、去重和排序共用内核规则。
func NormalizeTemplatePath ¶
func NormalizeTimeout ¶
func NormalizeWebTimeout ¶
NormalizeWebTimeout 统一网页搜索和抓取的超时秒数。
func OCRAssetKey ¶
OCRAssetKey 保留本地资源的笔记本身份,只合并显示参数和片段;外部地址保留完整查询参数。
func OpenFileNoFollow ¶
OpenFileNoFollow 不跟随最后一个路径分量的链接;Unix 使用非阻塞打开,避免路径被换成 FIFO 后挂起。 调用方必须验证全部父目录,并在读取前检查返回句柄的类型、文件身份及链接数。
func OpenPluginProjectDirectory ¶
OpenPluginProjectDirectory 从工作空间目录句柄逐层打开,拒绝链接及目录身份变化。
func OpenPublishFile ¶
OpenPublishFile 在已打开的目录句柄内逐级读取,拒绝链接和非普通文件,并校验打开前后的文件身份。 即使路径在检查后被替换,读取也不会转向链接目标或授权目录之外。
func OpenPublishReaderFile ¶
OpenPublishReaderFile 打开读者可见的包资源,并在读取前检查请求路径和已打开文件的敏感性。 data/public 按设计公开,仍直接使用 OpenPublishFile,不经过本函数。
func ParentHPath ¶
ParentHPath 返回 hPath 的父路径:去掉最后一个 "/" 段,根路径及单段路径返回 "/"。
func PinYinCompare ¶
func PinYinCompare4FileTree ¶
func PluginProjectDigest ¶
func PluginProjectPrivateDir ¶
func PluginProjectRegularFile ¶
PluginProjectRegularFile 仅做打开前的普通文件预检;打开后还须用跨平台句柄检查硬链接数。
func PluginProjectRoot ¶
func PluginProjectsDir ¶
func PluginProjectsDir() string
func PrepareLockScreenWallpaper ¶
PrepareLockScreenWallpaper 校验实际图片格式和解码尺寸,并移除元数据与透明背景。
func PushBackgroundTask ¶
func PushBoxDocFeatureChanged ¶
func PushBoxDocFeatureChanged()
func PushClearAllMsg ¶
func PushClearAllMsg()
func PushClearMsgWithApp ¶
func PushClearMsgWithApp(app, msgId string)
PushClearMsgWithApp 清除指定实例的单条提示;空消息 ID 不执行清除,避免影响其他任务。
func PushDownloadProgress ¶
func PushEndlessProgress ¶
func PushEndlessProgress(msg string)
func PushErrMsg ¶
func PushErrMsgWithApp ¶
PushErrMsgWithApp 在指定实例显示错误;未指定实例时广播,实例离线时丢弃。
func PushKernelPluginState ¶
func PushMsgWithApp ¶
func PushNodeOCRQueue ¶
func PushProgress ¶
func PushProtyleLoading ¶
func PushProtyleLoading(rootID, msg string)
func PushReloadDoc ¶
func PushReloadDoc(rootID string)
func PushReloadDocInfo ¶
func PushReloadEmojiConf ¶
func PushReloadEmojiConf()
func PushReloadFiletree ¶
func PushReloadFiletree()
func PushReloadProtyle ¶
func PushReloadProtyle(rootID string)
func PushReloadTag ¶
func PushReloadTag()
func PushSaveDoc ¶
func PushSetDefRefCount ¶
func PushSetRefDynamicText ¶
func PushSetRefDynamicText(rootID, blockID, defBlockID, refText, boxID string)
func PushStatusBar ¶
func PushStatusBar(msg string)
func PushUpdateIDs ¶
func PushUpdateMsg ¶
func PushUpdateMsgWithApp ¶
PushUpdateMsgWithApp 在指定实例更新提示;未指定实例时广播,实例离线时丢弃。
func RandString ¶
func RandomBuiltinEmoji ¶
func RandomBuiltinEmoji() string
RandomBuiltinEmoji 返回一个随机的内置 emoji unicode 码点(如 "1f4d6")。
func RandomSleep ¶
func RandomSleep(minMills, maxMills int)
func ReadLockScreenWallpaper ¶
ReadLockScreenWallpaper 不接受客户端路径,并拒绝符号链接、非图片及超限文件。
func ReadUserFile ¶
ReadUserFile 对工作空间外的用户文件返回读取错误,工作空间数据沿用文件锁的错误保护。
func ReadWorkspacePaths ¶
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 ReloadUIResetScroll ¶
func ReloadUIResetScroll()
func RemoveAssetText ¶
func RemoveAssetText(asset string)
func RemoveDatabaseFile ¶
func RemoveDatabaseFile(dbPath string)
func RemoveEmojiInvisible ¶
func RemoveEmptyDir ¶
RemoveEmptyDir 删除仅含系统元数据文件(如 .DS_Store)的目录;若目录仍含业务文件则保留不动
func RemoveInvalid ¶
func RemoveInvalidRetainCtrl ¶
func RemoveLockScreenWallpaper ¶
RemoveLockScreenWallpaper 仅删除专用壁纸,重复恢复默认也能成功。
func RemovePushChan ¶
func RemoveRedundantSpace ¶
func RemoveSkill ¶
func RemoveWorkspacePath ¶
func RemoveWorkspaceSession ¶
func RemoveWorkspaceSession(session *SessionData)
func RenameEmojiFile ¶
RenameEmojiFile 在源和目标文件锁内迁移表情,目标已存在时保留两者,不覆盖文件或合并目录。
func RenameSkill ¶
func RenderOAuthCallbackPage ¶
RenderOAuthCallbackPage 渲染 OAuth 和 OIDC 共用的回调结果页面。
func RenderOAuthRedirectPage ¶
RenderOAuthRedirectPage 在同源结果页加载后进入已校验的站内目标,结束身份提供方的重定向链。
func ReplaceNewline ¶
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 ¶
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 RestrictConfFilePermissions ¶
func RestrictConfFilePermissions()
RestrictConfFilePermissions 收紧工作空间配置目录中凭据文件的权限。conf.json 由 filelock 以 0644 写入, 因此在每次保存后与启动时调用;同目录的 TLS 私钥在启动时一并迁移旧版本遗留的宽松权限。
func RestrictSecretFile ¶
func RestrictSecretFile(path string)
RestrictSecretFile 在文件存在且允许组或其他用户访问时收紧为仅当前用户可读写;失败时保留原权限并记录警告。 Windows 由用户目录的访问控制保护,不处理权限位。
func RuntimeInfo ¶
RuntimeInfo 采集当前内核的运行信息,使用统一诊断字段,避免包含路径、主机名和账户信息。
func SHA256Hash ¶
func SQLitePageCacheDSN ¶
func SQLitePageCacheDSN() string
SQLitePageCacheDSN 设置每个连接的页缓存预算,负值的单位为 KiB。 移动端采用 16 MiB,减少多连接和多个已解锁笔记本的内存压力。
func SSRFSafeDialer ¶
SSRFSafeDialer 返回内核出站请求使用的拨号器,在连接阶段按目标 IP 判断是否允许访问。 非安全模式下放行回环与 RFC1918 私网,以支持插件访问本机或局域网服务,仅记录一次审计日志; 链路本地与未指定地址始终拒绝,避免访问云元数据等仅本机可达的服务。
func SanitizeHTML ¶
func SanitizeName ¶
SanitizeName replaces all non-alphanumeric characters in the input string with underscores.
func SanitizeSVG ¶
SanitizeSVG 使用 XML 语义过滤 SVG,避免 HTML 与 XML 解析规则差异导致活动内容绕过过滤。
func SaveAssetsTexts ¶
func SaveAssetsTexts()
func SaveLockScreenWallpaper ¶
SaveLockScreenWallpaper 原子替换唯一的壁纸,失败时保留原文件。
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 ¶
SessionCookieKeys 由 Cookie 密钥派生会话 Cookie 的签名密钥和 AES-256 加密密钥。 旧格式 Cookie 直接以 Cookie 密钥签名且不加密,无法通过校验,按未登录处理。 Cookie 密钥为空时不派生,会话 Cookie 的编解码随之失败,避免以公开的固定密钥签发会话。
func SessionsByType ¶
func SetAssetText ¶
func SetAssetText(asset, text string)
func SetBootDetails ¶
func SetBootDetails(details string)
func SetHomeDir ¶
SetHomeDir 设置用户配置基路径,配置仍保存在其 .config/siyuan 子目录中。 空参数保留默认目录;显式路径必须能创建配置目录,失败时不回退到系统用户主目录。
func SetLocalIPs ¶
func SetLocalIPs(addresses []string)
func SetNetworkProxy ¶
func ShouldRedirectToTLS ¶
ShouldRedirectToTLS 判断当前请求是否需要被重定向到 HTTPS。
仅在用户开启「启用 HTTPS」且证书可用时生效;本机明文请求放行,否则桌面端、 固定端口反代与浏览器扩展无法连接。CORS 预检不携带凭据且浏览器不跟随跳转,故同样放行。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr
func ShutdownHTTPServers ¶
ShutdownHTTPServers 并行停止 HTTP 和 HTTPS 服务,等待活跃响应完成,超时后关闭剩余连接。
func SizeOfDirectory ¶
func SnapshotPluginProject ¶
SnapshotPluginProject 读取有界不可变字节快照,拒绝所有不安全的受管成员。
func SplitFileAnnotationRef ¶
SplitFileAnnotationRef 分离资源地址和标注 ID,保留资源地址的查询参数及片段,不改变已有引用的编码。
func SupportsOpenAIResponsesCompaction ¶
SupportsOpenAIResponsesCompaction 判断当前端点是否支持原生 Responses 上下文压缩。
func TLSRedirectHandler ¶
TLSRedirectHandler 包装明文 HTTP 处理器:用户开启「启用 HTTPS」且证书可用时, 把来自其他主机的明文请求重定向到 HTTPS,本机明文请求与 CORS 预检放行。
内核通过 cmux 在同一端口同时承载 HTTP 与 HTTPS,固定端口反代与发布服务也是双栈, 仅在监听层无法阻止明文访问,因此三条入口都要经过这里。 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-hpj5-f7cj-vvwr
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 TimeFromID ¶
func TrimSpaceInPath ¶
func TruncateLenFileName ¶
func TruncateRunes ¶
TruncateRunes 按 Unicode 码点截断文本,不附加省略标记。
func TruncateToolOutput ¶
func TruncateUTF8Bytes ¶
TruncateUTF8Bytes 在字节上限内截断有效 UTF-8 文本,保留完整码点,不附加省略标记。
func UnescapeHTML ¶
func UnlockWorkspace ¶
func UnlockWorkspace()
func UserSkillsDir ¶
func UserSkillsDir() string
func ValidateAIProviderHeaders ¶
ValidateAIProviderHeaders 在保存配置和发送请求前校验请求头,不在错误中包含凭据。
func ValidateDecisionImage ¶
func ValidateDecisionImage(image DecisionImage) 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 ¶
ValidateGeneratedImage 校验生成图片的格式、尺寸和体积。
func ValidateID ¶
ValidateID 检查块或笔记本 ID 形态,不合法时返回 ErrInvalidID。 返回错误而不是往调用方的信封里写字,让调用方决定用哪个错误码响应。
func ValidateOptionalID ¶
ValidateOptionalID 与 ValidateID 相同,但把空字符串视为「未提供」而非非法值。 用于可选的对端 ID 等参数,避免调用方各自重复判空。
func ValidatePluginProjectFile ¶
即使出现在允许清单中,也拒绝平台别名及私密、构建依赖和运行时材料。
func ValidateTextFileContent ¶
func ValidateTextFilePath ¶
ValidateTextFilePath 拒绝非规范路径,避免将目录穿越、Windows 别名或其他分隔符静默转换为目标路径。
func WaitBindableInteractiveSession ¶
func WaitBindableInteractiveSession(ctx context.Context, app, id string) (*melody.Session, <-chan struct{})
WaitBindableInteractiveSession 处理升级握手已完成但认证连接尚未登记的短暂窗口。 已登记的无效连接立即拒绝;请求取消后不得等待后续同名连接。
func WaitForTesseractInit ¶
func WaitForTesseractInit()
func WaitForUILoaded ¶
func WaitForUILoaded()
func WaitInteractiveSession ¶
WaitInteractiveSession 最多等待 10 秒让原主窗口报告界面就绪,连接替换、断开或请求失效时终止等待。
func WaitWorkspaceExitProcess ¶
func WaitWorkspaceExitProcess(ctx context.Context, state WorkspaceExitState) error
WaitWorkspaceExitProcess 仅观察进程身份,不打开工作空间、删除标记或终止进程。
func WebFetchContext ¶
func WebSearchContext ¶
func Weekday ¶
Weekday returns the day of the week specified by date. Sunday=0, Monday=1, ..., Saturday=6.
func WeekdayCN ¶
WeekdayCN returns the day of the week specified by date. Sunday=日, Monday=一, ..., Saturday=六.
func WeekdayCN2 ¶
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 WithPluginProjectSource ¶
func WrapGeminiThoughtSignatureTransport ¶
WrapGeminiThoughtSignatureTransport 为 Google OpenAI 兼容端点补充工具调用签名往返支持。 该函数导出仅用于 Agent 集成测试构造本地上游,生产代码通过 NewAIClientWithModel 使用。
func WriteFileByMmap ¶
WriteFileByMmap 使用内存映射按页比较,只覆写发生变化的页,并立即刷新。 全程持有 filelock 的进程内互斥锁,长度变化时调整文件大小;出错时由调用方回退到原子写入。
func WriteFileIfUnchanged ¶
WriteFileIfUnchanged 在同一文件锁内比对扫描源并原子写入;original 为 nil 时要求目标不存在。
func WriteFileWithChangeTracking ¶
WriteFileWithChangeTracking 在释放文件锁前标记写入,保留修改时间的后续操作也不会隐藏内容变化。
func WriteFileWithPreflight ¶
WriteFileWithPreflight 在同一文件锁内检查当前源文件后写入;源不存在时向检查函数传入 nil。 检查失败不创建或截断文件;普通数据沿用按页写入和原子回退,加密数据仅原子替换。
func WriteUserFile ¶
WriteUserFile 将外部目标的权限与占用错误返回给调用方。
func WriteWorkspacePaths ¶
Types ¶
type AIClient ¶
AIClient 共享生成调用的连接配置,按协议选择独立的请求适配器。
func NewAIClientWithModel ¶
NewAIClientWithModel 创建生成客户端,并按模型与端点启用协议适配。 模型请求统一启用思考字段适配,命中清单的模型会注入额外参数,官方 Gemini 端点会保留工具调用签名。
func NewChatGPTClient ¶
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 ¶
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 ¶
func PrepareAssetTextRelinks(mappings []AssetTextRelinkMapping) (*AssetTextRelinkPlan, error)
PrepareAssetTextRelinks 从同一份 OCR 快照计算所有映射,不写文件或内存缓存。
type AssetTextRelinkResult ¶
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 ¶
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 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 DecisionImage ¶
DecisionImage 必须显式提供;正文或 JSON 中的图片链接不会被自动读取。
type DecisionInputTokensDetails ¶
type DecisionInputTokensDetails struct {
CachedTokens int `json:"cached_tokens"`
CacheWriteTokens int `json:"cache_write_tokens"`
}
缓存读写均已包含在 InputTokens 中,不能再次累加。
type DecisionOptions ¶
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 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
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 GeneratedImage ¶
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"` // 是否启用中点代码块快捷输入
}
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 (stream *OpenAICompletionStream) Recv() (openai.ChatCompletionStreamResponse, error)
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 ¶
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]) MarshalJSON ¶
func (*Optional[T]) UnmarshalJSON ¶
type PandocRuntime ¶
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()
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 PluginProjectFile ¶
type PluginProjectMutation ¶
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 PluginProjectArtifactStatus ¶
func PluginProjectArtifactStatus(grant *PluginDevelopmentGrant, root *os.Root) (*PluginProjectStatus, error)
PluginProjectArtifactStatus 只读投影项目及制品状态,调用方须持有项目锁。
func PreparePluginProject ¶
func RestorePluginProject ¶
func RestorePluginProject(ctx context.Context, taskID, expectedRevision string) (ret *PluginProjectStatus, err error)
RestorePluginProject 先持久化整次恢复日志;崩溃可能留下部分恢复结果。 再次恢复只接受各文件记录的旧版或新版字节,不覆盖未知外部修改。
type PreparedImage ¶
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 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"`
}
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)
type SkillFileData ¶
type SkillFileData struct {
Entries []SkillFileEntry
Content *string
Revision string
ReadOnlyReason string
}
func ManageSkillFiles ¶
func ManageSkillFiles(request SkillFileRequest) (SkillFileData, error)
type SkillFileEntry ¶
type SkillFileRequest ¶
type SkillInfo ¶
func DiscoverSkills ¶
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 只解析准确的官方名称;调用方必须先校验可信会话授权。
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 NormalizeStatusBar ¶
NormalizeStatusBar 一次性迁移状态栏消息配置,迁移完成后保留用户的手动设置。
type TesseractProvider ¶
type TesseractProvider struct{}
func (TesseractProvider) Available ¶
func (TesseractProvider) Available() bool
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
¶
- agent_instructions.go
- ai_client.go
- anthropic.go
- anthropic_models.go
- anthropic_stream.go
- appearance.go
- appearance_ignore_migration.go
- appearance_path.go
- atomic_value.go
- builtin_skill.go
- captcha.go
- cert.go
- chatgpt.go
- clipboard.go
- cloud.go
- cmux.go
- compare_write.go
- crypt.go
- custom_font.go
- data_path_boxid.go
- decision.go
- decision_input.go
- decision_provider.go
- deepseek_web.go
- disk.go
- emoji_random.go
- encrypted_index.go
- etag.go
- file.go
- file_annotation.go
- file_copy.go
- file_glob.go
- file_permissions.go
- font.go
- font_android_config.go
- font_bridge.go
- font_platform_linux.go
- fontconfig.go
- gemini_interactions.go
- gemini_interactions_models.go
- gemini_interactions_stream.go
- hpath.go
- http_shutdown.go
- httprequest.go
- i18n.go
- icloud_other.go
- kdf.go
- lang.go
- legacy_font.go
- local_proxy.go
- lockscreen_wallpaper.go
- lute.go
- minimax_image.go
- misc.go
- mmap.go
- net.go
- oauth_callback.go
- ocr.go
- ocr_relink.go
- ocr_relink_batch.go
- openai.go
- openai_completion.go
- openai_gemini.go
- openai_headers.go
- openai_reasoning.go
- operation_watchdog.go
- os.go
- pandoc.go
- path.go
- path_guard.go
- performance.go
- plugin_development.go
- plugin_project.go
- plugin_project_prepare.go
- plugin_project_replan.go
- plugin_project_source.go
- preflight_write.go
- publish_file.go
- publish_file_other.go
- real_path_other.go
- result.go
- rhy.go
- rune.go
- runtime.go
- runtime_filesys.go
- runtime_info.go
- session.go
- skill.go
- skill_manage.go
- skill_provenance.go
- sort.go
- sqlite_cache.go
- system_proxy.go
- system_proxy_linux.go
- system_proxy_macos.go
- text_file.go
- text_file_links_unix.go
- time.go
- tls.go
- tls_cert_manager.go
- tokens.go
- tooloutput.go
- tracked_file.go
- transport.go
- truncate.go
- user_file.go
- web_timeout.go
- webfetch.go
- websearch.go
- websocket.go
- working.go
- working_mobile.go
- workspace_drive.go
- workspace_exit.go
- workspace_exit_process.go
- workspace_storage.go
- zip_entry.go