Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
docs: add tabbed API examples (#3185)
yufeng91a8f030849d
diff --git a/.github/workflows/_docs.yml b/.github/workflows/_docs.ymlindex 5350d24c4..259232618 100644--- a/.github/workflows/_docs.yml+++ b/.github/workflows/_docs.yml@@ -24,8 +24,12 @@ jobs:run: npm ciworking-directory: docs- - name: Test docs search- run: npm run test:search+ - name: Test docs theme+ run: npm run test:theme+ working-directory: docs++ - name: Check API reference+ run: npm run check:apiworking-directory: docs- name: Build docsdiff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.tsindex 25221b83c..e648cbebc 100644--- a/docs/.vitepress/config.ts+++ b/docs/.vitepress/config.ts@@ -54,12 +54,16 @@ const zhSectionNames: Record<string, string> = {const navLabels = {en: {- guide: 'Guide',+ start: 'Getting Started',+ concepts: 'Concepts',+ guide: 'Guides',api: 'API Reference',faq: 'FAQ',about: 'About'},zh: {+ start: '快速开始',+ concepts: '核心概念',guide: '指南',api: 'API 参考',faq: '常见问题',@@ -96,12 +100,23 @@ function sidebarSection(dir: string, title: string, collapsed = true): DefaultThreturn { text: title, collapsed, items }}-function localizedGuideSidebarItems(locale: 'en' | 'zh'): DefaultTheme.SidebarItem[] {+function localizedSectionSidebarItems(+ locale: 'en' | 'zh',+ section: 'getting-started' | 'concepts' | 'guides' | 'agent-integrations' | 'migration'+): DefaultTheme.SidebarItem[] {+ const labels = locale === 'zh' ? zhSectionNames : sectionNames+ return [sidebarSection(`${locale}/${section}`, labels[section], false)]+}++function localizedGroupedSidebarItems(+ locale: 'en' | 'zh',+ sections: ReadonlyArray<'getting-started' | 'guides' | 'agent-integrations' | 'migration'>,+ activeSection: 'getting-started' | 'guides' | 'agent-integrations' | 'migration'+): DefaultTheme.SidebarItem[] {const labels = locale === 'zh' ? zhSectionNames : sectionNames- const sections = ['getting-started', 'concepts', 'guides', 'agent-integrations', 'migration']- return sections.map((section, index) =>- sidebarSection(`${locale}/${section}`, labels[section], index !== 0)+ return sections.map((section) =>+ sidebarSection(`${locale}/${section}`, labels[section], section !== activeSection))}@@ -120,14 +135,18 @@ const designSidebar: DefaultTheme.SidebarItem[] = []const enNav: DefaultTheme.NavItem[] = [- { text: navLabels.en.guide, link: '/en/getting-started/01-introduction', activeMatch: '/en/(getting-started|concepts|guides|agent-integrations|migration)/' },+ { text: navLabels.en.start, link: '/en/getting-started/01-introduction', activeMatch: '/en/(getting-started|agent-integrations)/' },+ { text: navLabels.en.concepts, link: '/en/concepts/01-architecture', activeMatch: '/en/concepts/' },+ { text: navLabels.en.guide, link: '/en/guides/01-configuration', activeMatch: '/en/(guides|migration)/' },{ text: navLabels.en.api, link: '/en/api/01-overview', activeMatch: '/en/api/' },{ text: navLabels.en.faq, link: '/en/faq/faq', activeMatch: '/en/faq/' },{ text: navLabels.en.about, link: '/en/about/01-about-us', activeMatch: '/en/about/' }]const zhNav: DefaultTheme.NavItem[] = [- { text: navLabels.zh.guide, link: '/zh/getting-started/01-introduction', activeMatch: '/zh/(getting-started|concepts|guides|agent-integrations|migration)/' },+ { text: navLabels.zh.start, link: '/zh/getting-started/01-introduction', activeMatch: '/zh/(getting-started|agent-integrations)/' },+ { text: navLabels.zh.concepts, link: '/zh/concepts/01-architecture', activeMatch: '/zh/concepts/' },+ { text: navLabels.zh.guide, link: '/zh/guides/01-configuration', activeMatch: '/zh/(guides|migration)/' },{ text: navLabels.zh.api, link: '/zh/api/01-overview', activeMatch: '/zh/api/' },{ text: navLabels.zh.faq, link: '/zh/faq/faq', activeMatch: '/zh/faq/' },{ text: navLabels.zh.about, link: '/zh/about/01-about-us', activeMatch: '/zh/about/' }@@ -349,12 +368,15 @@ export default defineConfig({link: '/en/',themeConfig: {nav: enNav,+ outline: {+ level: [2, 3]+ },sidebar: {- '/en/getting-started/': localizedGuideSidebarItems('en'),- '/en/concepts/': localizedGuideSidebarItems('en'),- '/en/guides/': localizedGuideSidebarItems('en'),- '/en/agent-integrations/': localizedGuideSidebarItems('en'),- '/en/migration/': localizedGuideSidebarItems('en'),+ '/en/getting-started/': localizedGroupedSidebarItems('en', ['getting-started', 'agent-integrations'], 'getting-started'),+ '/en/concepts/': localizedSectionSidebarItems('en', 'concepts'),+ '/en/guides/': localizedGroupedSidebarItems('en', ['guides', 'migration'], 'guides'),+ '/en/agent-integrations/': localizedGroupedSidebarItems('en', ['getting-started', 'agent-integrations'], 'agent-integrations'),+ '/en/migration/': localizedGroupedSidebarItems('en', ['guides', 'migration'], 'migration'),'/en/api/': localizedReferenceSidebarItems('en'),'/en/about/': localizedAboutSidebarItems('en'),'/design/': designSidebar@@ -370,16 +392,17 @@ export default defineConfig({themeConfig: {nav: zhNav,sidebar: {- '/zh/getting-started/': localizedGuideSidebarItems('zh'),- '/zh/concepts/': localizedGuideSidebarItems('zh'),- '/zh/guides/': localizedGuideSidebarItems('zh'),- '/zh/agent-integrations/': localizedGuideSidebarItems('zh'),- '/zh/migration/': localizedGuideSidebarItems('zh'),+ '/zh/getting-started/': localizedGroupedSidebarItems('zh', ['getting-started', 'agent-integrations'], 'getting-started'),+ '/zh/concepts/': localizedSectionSidebarItems('zh', 'concepts'),+ '/zh/guides/': localizedGroupedSidebarItems('zh', ['guides', 'migration'], 'guides'),+ '/zh/agent-integrations/': localizedGroupedSidebarItems('zh', ['getting-started', 'agent-integrations'], 'agent-integrations'),+ '/zh/migration/': localizedGroupedSidebarItems('zh', ['guides', 'migration'], 'migration'),'/zh/api/': localizedReferenceSidebarItems('zh'),'/zh/about/': localizedAboutSidebarItems('zh')},outline: {- label: '页面导航'+ label: '页面导航',+ level: [2, 3]},docFooter: {prev: '上一页',diff --git a/docs/.vitepress/theme/ApiExampleTabsEnhancer.vue b/docs/.vitepress/theme/ApiExampleTabsEnhancer.vuenew file mode 100644index 000000000..615b8e39a--- /dev/null+++ b/docs/.vitepress/theme/ApiExampleTabsEnhancer.vue@@ -0,0 +1,200 @@+<script setup lang="ts">+import { nextTick, onMounted, onUnmounted, watch } from 'vue'+import { useRoute } from 'vitepress'+import {+ exampleHeading,+ isApiReferencePath,+ isSharedSectionLabel,+ preferredLanguage,+ shouldSynchronizeExampleTabs,+ type ExampleLanguage+} from './api-example-tabs'++const route = useRoute()+const STORAGE_KEY = 'openviking-api-example-language'+const CHANGE_EVENT = 'openviking-api-example-language-change'+let observer: MutationObserver | undefined+let frame = 0+let tabGroup = 0++function strongHeadingLabel(element: Element) {+ if (!element.matches('p')) return undefined+ const strong = element.querySelector(':scope > strong:first-child')+ return strong ? element.textContent?.trim() : undefined+}++function headingLanguage(element: Element) {+ const label = strongHeadingLabel(element)+ return label ? exampleHeading(label) : undefined+}++function isSharedSection(element: Element) {+ const label = strongHeadingLabel(element)+ return label ? isSharedSectionLabel(label) : false+}++function activate(container: HTMLElement, key: string, broadcast = true) {+ const available = Array.from(+ container.querySelectorAll<HTMLElement>(':scope > [data-api-example]')+ )+ const selected = available.some((panel) => panel.dataset.apiExample === key)+ ? key+ : available[0]?.dataset.apiExample+ if (!selected) return++ for (const panel of available) panel.hidden = panel.dataset.apiExample !== selected+ const buttons = container.querySelectorAll<HTMLButtonElement>(+ ':scope > [role="tablist"] button'+ )+ for (const button of buttons) {+ const active = button.dataset.language === selected+ button.classList.toggle('is-active', active)+ button.setAttribute('aria-selected', String(active))+ button.tabIndex = active ? 0 : -1+ }+ if (broadcast && container.dataset.apiExampleKind === 'language') {+ localStorage.setItem(STORAGE_KEY, selected)+ window.dispatchEvent(new CustomEvent(CHANGE_EVENT, { detail: selected }))+ }+}++function activatePreservingViewport(container: HTMLElement, key: string) {+ const tablist = container.querySelector<HTMLElement>(':scope > [role="tablist"]')+ const anchorTop = tablist?.getBoundingClientRect().top+ activate(container, key)+ if (anchorTop === undefined || !tablist) return+ const offset = tablist.getBoundingClientRect().top - anchorTop+ if (offset) window.scrollBy({ top: offset, behavior: 'instant' })+}++function handleTabKeydown(event: KeyboardEvent, container: HTMLElement) {+ const buttons = Array.from(+ container.querySelectorAll<HTMLButtonElement>(':scope > [role="tablist"] button')+ )+ const currentIndex = buttons.indexOf(event.currentTarget as HTMLButtonElement)+ if (currentIndex < 0) return++ let nextIndex: number | undefined+ if (event.key === 'ArrowLeft') nextIndex = (currentIndex - 1 + buttons.length) % buttons.length+ else if (event.key === 'ArrowRight') nextIndex = (currentIndex + 1) % buttons.length+ else if (event.key === 'Home') nextIndex = 0+ else if (event.key === 'End') nextIndex = buttons.length - 1+ if (nextIndex === undefined) return++ event.preventDefault()+ const nextButton = buttons[nextIndex]+ nextButton.focus()+ activatePreservingViewport(container, nextButton.dataset.language ?? '')+}++function enhanceDocument() {+ if (!isApiReferencePath(route.path)) return+ const doc = document.querySelector('.vp-doc')+ if (!doc) return+ const storedLanguage = localStorage.getItem(STORAGE_KEY)+ let initialLanguage: string | undefined++ const headings = Array.from(doc.querySelectorAll('p')).filter(+ (element) => headingLanguage(element) && !element.closest('.api-example-tabs')+ )++ for (const firstHeading of headings) {+ if (!firstHeading.isConnected || firstHeading.closest('.api-example-tabs')) continue+ const parent = firstHeading.parentElement+ if (!parent) continue++ const groups: { language: ExampleLanguage; nodes: Element[] }[] = []+ let node: Element | null = firstHeading+ while (node) {+ if (node.matches('h2, h3, h4, hr')) break+ if (groups.length && isSharedSection(node)) break+ const currentLanguage = headingLanguage(node)+ if (currentLanguage) {+ if (groups.length && groups[0].language.kind !== currentLanguage.kind) break+ if (groups.some((group) => group.language.key === currentLanguage.key)) break+ groups.push({ language: currentLanguage, nodes: [node] })+ }+ else {+ if (!groups.length) break+ groups.at(-1)?.nodes.push(node)+ }+ node = node.nextElementSibling+ }++ if (groups.length < 2) continue+ const container = document.createElement('div')+ container.className = 'api-example-tabs'+ container.dataset.apiExampleKind = groups[0].language.kind+ const tablist = document.createElement('div')+ tablist.className = 'api-example-tabs__tablist'+ tablist.setAttribute('role', 'tablist')+ tablist.setAttribute('aria-label', 'API examples')+ container.append(tablist)+ parent.insertBefore(container, firstHeading)+ const groupId = `api-example-tabs-${tabGroup++}`++ for (const group of groups) {+ const button = document.createElement('button')+ button.type = 'button'+ button.setAttribute('role', 'tab')+ button.id = `${groupId}-tab-${group.language.key}`+ button.setAttribute('aria-controls', `${groupId}-panel-${group.language.key}`)+ button.dataset.language = group.language.key+ button.textContent = group.language.label+ button.addEventListener('click', () => {+ activatePreservingViewport(container, group.language.key)+ })+ button.addEventListener('keydown', (event) => handleTabKeydown(event, container))+ tablist.append(button)++ const panel = document.createElement('div')+ panel.id = `${groupId}-panel-${group.language.key}`+ panel.setAttribute('role', 'tabpanel')+ panel.setAttribute('aria-labelledby', button.id)+ panel.dataset.apiExample = group.language.key+ panel.className = 'api-example-tabs__panel'+ for (const child of group.nodes) panel.append(child)+ container.append(panel)+ }+ if (groups[0].language.kind === 'language') {+ initialLanguage = preferredLanguage(storedLanguage, initialLanguage, groups[0].language.key)+ activate(container, initialLanguage, false)+ }+ else activate(container, groups[0].language.key, false)+ }+}++function scheduleEnhancement() {+ window.cancelAnimationFrame(frame)+ frame = window.requestAnimationFrame(enhanceDocument)+}++function sync(event: Event) {+ const key = (event as CustomEvent<string>).detail+ for (const container of document.querySelectorAll<HTMLElement>('.api-example-tabs')) {+ if (!shouldSynchronizeExampleTabs(container.dataset.apiExampleKind)) continue+ activate(container, key, false)+ }+}++async function enhanceAfterRender() {+ await nextTick()+ scheduleEnhancement()+}++watch(() => route.path, enhanceAfterRender)+onMounted(() => {+ enhanceAfterRender()+ observer = new MutationObserver(scheduleEnhancement)+ const content = document.querySelector('.VPContent')+ if (content) observer.observe(content, { childList: true, subtree: true })+ window.addEventListener(CHANGE_EVENT, sync)+})+onUnmounted(() => {+ observer?.disconnect()+ window.cancelAnimationFrame(frame)+ window.removeEventListener(CHANGE_EVENT, sync)+})+</script>++<template><span class="api-example-tabs-enhancer" aria-hidden="true" /></template>diff --git a/docs/.vitepress/theme/CopyMarkdownButton.vue b/docs/.vitepress/theme/CopyMarkdownButton.vueindex d8b37faad..ac3a53457 100644--- a/docs/.vitepress/theme/CopyMarkdownButton.vue+++ b/docs/.vitepress/theme/CopyMarkdownButton.vue@@ -1,6 +1,7 @@<script setup lang="ts">import { useData, withBase } from 'vitepress'import { ref, computed, onMounted, onBeforeUnmount } from 'vue'+import { hasPageLlmsTxt } from './llms-txt'const { frontmatter, page } = useData()@@ -58,7 +59,7 @@ function onOutsideClick(e: MouseEvent) {onMounted(() => document.addEventListener('click', onOutsideClick))onBeforeUnmount(() => document.removeEventListener('click', onOutsideClick))-const isDoc = computed(() => page.value.relativePath !== 'index.md')+const isDoc = computed(() => hasPageLlmsTxt(page.value.relativePath))</script><template>diff --git a/docs/.vitepress/theme/LlmsTxtLink.vue b/docs/.vitepress/theme/LlmsTxtLink.vueindex 79b8fbe8c..3108a2b16 100644--- a/docs/.vitepress/theme/LlmsTxtLink.vue+++ b/docs/.vitepress/theme/LlmsTxtLink.vue@@ -1,6 +1,7 @@<script setup lang="ts">import { useData, withBase } from 'vitepress'-import { computed } from 'vue'+import { computed, ref } from 'vue'+import { hasPageLlmsTxt } from './llms-txt'const { page } = useData()@@ -9,38 +10,130 @@ const llmsUrl = computed(() => {return withBase(`/${pagePath}/llms.txt`)})-const isDoc = computed(() => page.value.relativePath !== 'index.md')+const isDoc = computed(() => hasPageLlmsTxt(page.value.relativePath))+const copied = ref(false)+const copyFailed = ref(false)+let resetTimer: ReturnType<typeof window.setTimeout> | undefined++const isZh = computed(() => page.value.relativePath.startsWith('zh/'))+const copyLabel = computed(() => {+ if (copyFailed.value) return isZh.value ? '复制失败' : 'Copy failed'+ if (copied.value) return isZh.value ? '已复制' : 'Copied'+ return isZh.value ? '复制' : 'Copy'+})++async function writeClipboard(text: string) {+ try {+ await navigator.clipboard.writeText(text)+ return+ } catch {+ const textarea = document.createElement('textarea')+ textarea.value = text+ textarea.setAttribute('readonly', '')+ textarea.style.position = 'fixed'+ textarea.style.opacity = '0'+ document.body.appendChild(textarea)+ textarea.select()+ const copied = document.execCommand('copy')+ textarea.remove()+ if (!copied) throw new Error('Copy command was rejected')+ }+}++async function copyLlmsTxt() {+ window.clearTimeout(resetTimer)+ copied.value = false+ copyFailed.value = false++ try {+ const response = await fetch(llmsUrl.value)+ if (!response.ok) throw new Error(`Failed to load llms.txt: ${response.status}`)+ await writeClipboard(await response.text())+ copied.value = true+ } catch {+ copyFailed.value = true+ }++ resetTimer = window.setTimeout(() => {+ copied.value = false+ copyFailed.value = false+ }, 2000)+}</script><template><div v-if="isDoc" class="llms-link-wrap"><a :href="llmsUrl" target="_blank" rel="noopener" class="llms-link">- <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ ><path d="M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z"/><path d="M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z"/></svg>llms.txt</a>+ <button type="button" class="llms-copy" :class="{ 'is-copied': copied }" @click="copyLlmsTxt">+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="14"+ height="14"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ stroke-width="2"+ stroke-linecap="round"+ stroke-linejoin="round"+ >+ <rect width="14" height="14" x="8" y="8" rx="2" ry="2"/>+ <path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>+ </svg>+ {{ copyLabel }}+ </button></div></template><style scoped>.llms-link-wrap {display: inline-flex;+ align-items: center;+ gap: 12px;margin-bottom: 8px;}-.llms-link {+.llms-link,+.llms-copy {display: inline-flex;align-items: center;gap: 5px;color: var(--vp-c-text-2);font-size: 13px;+}++.llms-link {text-decoration: none;transition: color 0.2s;}-.llms-link:hover {+.llms-copy {+ padding: 0;+ border: 0;+ background: transparent;+ cursor: pointer;+ font-family: inherit;+ transition: color 0.2s;+}++.llms-link:hover,+.llms-copy:hover,+.llms-copy.is-copied {color: var(--vp-c-brand-1);}</style>diff --git a/docs/.vitepress/theme/api-example-tabs.test.ts b/docs/.vitepress/theme/api-example-tabs.test.tsnew file mode 100644index 000000000..2c674609e--- /dev/null+++ b/docs/.vitepress/theme/api-example-tabs.test.ts@@ -0,0 +1,104 @@+import assert from 'node:assert/strict'+import test from 'node:test'++import {+ exampleLanguage,+ responseExample,+ isApiReferencePath,+ isSharedSectionLabel,+ preferredLanguage,+ shouldSynchronizeExampleTabs+} from './api-example-tabs.ts'+import { hasPageLlmsTxt } from './llms-txt.ts'++test('hides llms.txt actions on index pages without generated artifacts', () => {+ assert.equal(hasPageLlmsTxt('index.md'), false)+ assert.equal(hasPageLlmsTxt('en/index.md'), false)+ assert.equal(hasPageLlmsTxt('zh/index.md'), false)+ assert.equal(hasPageLlmsTxt('en/api/01-overview.md'), true)+})++test('recognizes language headings with punctuation and qualifiers', () => {+ assert.equal(exampleLanguage('HTTP API:')?.key, 'http')+ assert.equal(exampleLanguage('CLI (subcommands of resources)')?.key, 'cli')+})++test('recognizes transport and result response variants', () => {+ assert.deepEqual(responseExample('HTTP API 响应 (JSON, `wait=true`)'), {+ key: 'response-http', label: 'HTTP (wait=true)', kind: 'response'+ })+ assert.equal(responseExample('CLI 响应 (JSON 格式,使用 -o json)')?.label, 'CLI JSON')+ assert.equal(responseExample('Response (Directory)')?.label, 'Directory')+ assert.equal(responseExample('响应(Memory)')?.label, 'Memory')+ assert.equal(responseExample('异步响应(`wait=false`)')?.key, 'response-async')+})++test('keeps localized response variant keys distinct', () => {+ const file = responseExample('响应(文件)')+ const directory = responseExample('响应(目录)')+ const importing = responseExample('响应示例(资源导入进行中)')+ const completed = responseExample('响应示例(完成)')++ assert.equal(file?.key, 'response-文件')+ assert.equal(directory?.key, 'response-目录')+ assert.notEqual(file?.key, directory?.key)+ assert.notEqual(importing?.key, completed?.key)+})++test('synchronizes language tabs without resetting response tabs', () => {+ assert.equal(shouldSynchronizeExampleTabs('language'), true)+ assert.equal(shouldSynchronizeExampleTabs('response'), false)+ assert.equal(shouldSynchronizeExampleTabs(undefined), false)+})++test('recognizes response and note variants as shared sections', () => {+ for (const label of [+ 'Response',+ 'Response Examples',+ 'Result fields',+ 'Error Response',+ 'CLI override flags',+ 'MCP (agent control plane)',+ 'Notes:',+ '返回字段说明',+ '说明:'+ ]) {+ assert.equal(isSharedSectionLabel(label), true, label)+ }+ for (const label of [+ 'Python SDK (Embedded / HTTP)',+ 'TypeScript SDK',+ 'Go SDK',+ 'HTTP API',+ 'CLI (via ovcli.conf)',+ 'Response (File)',+ 'HTTP API Response (JSON)',+ '响应(applied)',+ '响应示例(完成)'+ ]) {+ assert.equal(isSharedSectionLabel(label), false, label)+ }+ for (const label of [+ 'Basic Search',+ 'Image Search',+ 'Search with Target URI Limitation',+ '基础搜索',+ '图片搜索',+ '使用 Target URI 限定搜索范围'+ ]) {+ assert.equal(isSharedSectionLabel(label), false, label)+ }+})++test('limits enhancement to localized API reference pages', () => {+ assert.equal(isApiReferencePath('/en/api/03-filesystem'), true)+ assert.equal(isApiReferencePath('/zh/api/04-skills'), true)+ assert.equal(isApiReferencePath('/OpenViking/en/api/11-snapshot'), true)+ assert.equal(isApiReferencePath('/en/guides/04-authentication'), false)+})++test('keeps one initial language across all groups', () => {+ assert.equal(preferredLanguage(null, undefined, 'typescript'), 'typescript')+ assert.equal(preferredLanguage(null, 'typescript', 'python'), 'typescript')+ assert.equal(preferredLanguage('go', 'typescript', 'python'), 'go')+})diff --git a/docs/.vitepress/theme/api-example-tabs.ts b/docs/.vitepress/theme/api-example-tabs.tsnew file mode 100644index 000000000..ae6ede449--- /dev/null+++ b/docs/.vitepress/theme/api-example-tabs.ts@@ -0,0 +1,87 @@+export interface ExampleLanguage {+ key: string+ label: string+ kind: 'language' | 'response'+}++export function exampleLanguage(label: string): ExampleLanguage | undefined {+ const normalized = label.trim().replace(/[::]$/, '').trim()+ const languageHeading = (name: string) =>+ new RegExp(`^(?:${name})(?:\\s*\\([^)]*\\))?$`, 'i').test(normalized)++ if (languageHeading('python sdk')) return { key: 'python', label: 'Python', kind: 'language' }+ if (languageHeading('typescript sdk|javascript sdk')) {+ return { key: 'typescript', label: 'TypeScript', kind: 'language' }+ }+ if (languageHeading('go sdk')) return { key: 'go', label: 'Go', kind: 'language' }+ if (languageHeading('http api')) return { key: 'http', label: 'HTTP', kind: 'language' }+ if (languageHeading('cli')) return { key: 'cli', label: 'CLI', kind: 'language' }+ return undefined+}++function responseKey(value: string): string {+ const normalized = value+ .normalize('NFKC')+ .toLowerCase()+ .replace(/[^\p{L}\p{N}]+/gu, '-')+ .replace(/^-|-$/g, '')+ return `response-${normalized}`+}++export function shouldSynchronizeExampleTabs(kind: string | undefined): boolean {+ return kind === 'language'+}++export function responseExample(label: string): ExampleLanguage | undefined {+ const normalized = label.trim().replace(/[::]$/, '').trim()+ const http = normalized.match(/^HTTP API (?:Response|响应)(.*)$/i)+ if (http) {+ const wait = http[1].match(/wait\s*=\s*(true|false)/i)?.[1]?.toLowerCase()+ return {+ key: wait === 'false' ? 'response-http-async' : 'response-http',+ label: wait ? `HTTP (wait=${wait})` : 'HTTP',+ kind: 'response'+ }+ }+ const cli = normalized.match(/^CLI (?:Response|响应)(.*)$/i)+ if (cli) {+ const json = /json/i.test(cli[1])+ return { key: json ? 'response-cli-json' : 'response-cli', label: json ? 'CLI JSON' : 'CLI', kind: 'response' }+ }+ const variant = normalized.match(/^(?:Response|响应)\s*[((]([^))]+)[))]$/i)+ if (variant) return { key: responseKey(variant[1]), label: variant[1], kind: 'response' }+ if (/^(?:Synchronous response|同步响应)/i.test(normalized)) {+ return { key: 'response-sync', label: /同步/.test(normalized) ? '同步' : 'Synchronous', kind: 'response' }+ }+ if (/^(?:Asynchronous response|异步响应)/i.test(normalized)) {+ return { key: 'response-async', label: /异步/.test(normalized) ? '异步' : 'Asynchronous', kind: 'response' }+ }+ const example = normalized.match(/^(?:Response Example|响应示例)\s*[((]([^))]+)[))]$/i)+ if (example) {+ return { key: responseKey(example[1]), label: example[1], kind: 'response' }+ }+ return undefined+}++export function exampleHeading(label: string): ExampleLanguage | undefined {+ return exampleLanguage(label) ?? responseExample(label)+}++export function isSharedSectionLabel(label: string): boolean {+ const normalized = label.trim().replace(/[::]$/, '').trim()+ return exampleHeading(label) === undefined && /^(?:(?:error )?response\b|响应|result fields?\b|notes?\b|cli override flags?\b|mcp\b|返回|说明)/i.test(+ normalized+ )+}++export function isApiReferencePath(path: string): boolean {+ return /(?:^|\/)(?:en|zh)\/api(?:\/|$)/.test(path)+}++export function preferredLanguage(+ storedLanguage: string | null,+ currentLanguage: string | undefined,+ firstAvailableLanguage: string+): string {+ return storedLanguage ?? currentLanguage ?? firstAvailableLanguage+}diff --git a/docs/.vitepress/theme/custom.css b/docs/.vitepress/theme/custom.cssindex c7f38c8a4..4ba356eef 100644--- a/docs/.vitepress/theme/custom.css+++ b/docs/.vitepress/theme/custom.css@@ -1,4 +1,5 @@:root {+ --vp-layout-max-width: 100vw;--vp-c-brand-1: #0f766e;--vp-c-brand-2: #115e59;--vp-c-brand-3: #14b8a6;@@ -13,6 +14,27 @@--vp-font-family-mono: "SFMono-Regular", Consolas, "Liberation Mono", monospace;}+@media (min-width: 1280px) {+ .VPContent .VPDoc.has-aside > .container > .content {+ flex: 1 1 0;+ min-width: 0;+ padding-right: 16px;+ padding-left: 16px;+ width: auto;+ }++ .VPContent .VPDoc.has-aside > .container > .content > .content-container {+ width: 100%;+ max-width: 1200px;+ }+}++@media (min-width: 1600px) {+ :root {+ --vp-layout-max-width: calc(100vw - 176px);+ }+}+.dark {--vp-c-brand-1: #5eead4;--vp-c-brand-2: #2dd4bf;@@ -329,3 +351,60 @@grid-template-columns: 1fr;}}+.doc-page-actions {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 16px;+ margin-bottom: 16px;+}++.doc-page-actions > .llms-link-wrap,+.doc-page-actions > .copy-md-wrap {+ margin-bottom: 0;+}++@media (max-width: 640px) {+ .doc-page-actions {+ align-items: center;+ flex-wrap: wrap;+ }+}++.api-example-tabs {+ margin: 20px 0 28px;+}++.api-example-tabs__tablist {+ display: flex;+ gap: 4px;+ overflow-x: auto;+ margin-bottom: 12px;+ padding-bottom: 1px;+ border-bottom: 1px solid var(--vp-c-divider);+}++.api-example-tabs__tablist button {+ flex: 0 0 auto;+ padding: 7px 12px;+ border: 0;+ border-bottom: 2px solid transparent;+ background: transparent;+ color: var(--vp-c-text-2);+ font: inherit;+ font-size: 14px;+ font-weight: 600;+ cursor: pointer;+}++.api-example-tabs__tablist button:hover { color: var(--vp-c-text-1); }+.api-example-tabs__tablist button.is-active {+ border-bottom-color: var(--vp-c-brand-1);+ color: var(--vp-c-brand-1);+}++.api-example-tabs > p:has(> strong:first-child) { margin-top: 0; }+.api-example-tabs > div[class*='language-'] { margin: 0; }+.api-example-tabs__panel > p:first-child { margin-top: 0; }+.api-example-tabs__panel > div[class*='language-'] { margin: 0; }+.api-example-tabs-enhancer { display: none; }diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.tsindex f64625294..a29008625 100644--- a/docs/.vitepress/theme/index.ts+++ b/docs/.vitepress/theme/index.ts@@ -4,6 +4,7 @@ import type { EnhanceAppContext } from 'vitepress'import CopyMarkdownButton from './CopyMarkdownButton.vue'import LlmsTxtLink from './LlmsTxtLink.vue'import OpenVikingSearch from './OpenVikingSearch.vue'+import ApiExampleTabsEnhancer from './ApiExampleTabsEnhancer.vue'import { trackPageView } from './track'import './custom.css'@@ -302,8 +303,11 @@ export default {extends: DefaultTheme,Layout() {return h(DefaultTheme.Layout, null, {- 'doc-before': () => h(CopyMarkdownButton),- 'doc-footer-before': () => h(LlmsTxtLink),+ 'doc-before': () => h('div', { class: 'doc-page-actions' }, [+ h(LlmsTxtLink),+ h(CopyMarkdownButton)+ ]),+ 'doc-after': () => h(ApiExampleTabsEnhancer),'nav-bar-content-before': () => h(OpenVikingSearch)})},diff --git a/docs/.vitepress/theme/llms-txt.ts b/docs/.vitepress/theme/llms-txt.tsnew file mode 100644index 000000000..f5da15a08--- /dev/null+++ b/docs/.vitepress/theme/llms-txt.ts@@ -0,0 +1,3 @@+export function hasPageLlmsTxt(relativePath: string): boolean {+ return relativePath !== 'index.md' && !relativePath.endsWith('/index.md')+}diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex 8a8f2bb4f..f68138145 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -368,6 +368,16 @@ client.add_resource()```+**TypeScript SDK**++```typescript+const task = await client.addResource("https://example.com/docs", {+ to: "viking://resources/docs/",+ wait: true,+});+console.log(task);+```+**Go SDK**```go@@ -742,6 +752,13 @@ result = client.add_skill("./skills/my-skill.json")client.wait_processed()```+**TypeScript SDK**++```typescript+const task = await client.addSkill("./my-skill", { wait: true });+console.log(task);+```+**Go SDK**```godiff --git a/docs/en/api/03-filesystem.md b/docs/en/api/03-filesystem.mdindex 1f41d0edc..17891ca31 100644--- a/docs/en/api/03-filesystem.md+++ b/docs/en/api/03-filesystem.md@@ -37,6 +37,7 @@ Read L0 abstract (~100 tokens summary).|-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI (must be a directory) |+**Python SDK (Embedded / HTTP)**```python@@ -45,6 +46,13 @@ print(f"Abstract: {abstract}")# Output: "Documentation for the project API, covering authentication, endpoints..."```+**TypeScript SDK**++```typescript+const abstract = await client.abstract("viking://resources/docs/");+console.log(abstract);+```+**Go SDK**```go@@ -72,6 +80,7 @@ curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://resourceopenviking abstract viking://resources/docs/```+**Response**```json@@ -94,6 +103,7 @@ Read L1 overview, applies to directories.|-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI (must be a directory) |+**Python SDK (Embedded / HTTP)**```python@@ -101,6 +111,13 @@ overview = client.overview("viking://resources/docs/")print(f"Overview:\n{overview}")```+**TypeScript SDK**++```typescript+const overview = await client.overview("viking://resources/docs/");+console.log(overview);+```+**Go SDK**```go@@ -128,6 +145,7 @@ curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resourceopenviking overview viking://resources/docs/```+**Response**```json@@ -158,6 +176,7 @@ Read L2 full content.- `read()` accepts file URIs only. Passing an existing directory URI returns `INVALID_ARGUMENT` (`400`), not `NOT_FOUND`. This error carries a structured `details` payload — `details.expected` is `"file"`, `details.actual` is `"directory"`, and `details.resource` is the offending URI (present on the HTTP path) — so clients can detect a file-vs-directory mismatch programmatically (for example, fall back to `list`) instead of string-matching the message.- Public URI parameters accept `resources` and `user` scopes. For session files, use `viking://user/{user_id}/sessions/{session_id}` or the backward-compatible `viking://session/{session_id}` alias. Internal scopes such as `temp` and `queue` return `INVALID_URI`.+**Python SDK (Embedded / HTTP)**```python@@ -165,6 +184,13 @@ content = client.read("viking://resources/docs/api.md")print(f"Content:\n{content}")```+**TypeScript SDK**++```typescript+const content = await client.read("viking://resources/docs/api.md", 0, -1);+console.log(content);+```+**Go SDK**```go@@ -192,6 +218,7 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://resources/doopenviking read viking://resources/docs/api.md```+**Response**```json@@ -226,6 +253,7 @@ Update an existing file, or create a new one when `mode="create"`, and automatic- File content is updated before the API returns. `wait` only controls whether the call waits for semantic/vector refresh to finish.- The public API no longer accepts `regenerate_semantics` or `revectorize`; write always refreshes related semantics and vectors.+**Python SDK (Embedded / HTTP)**```python@@ -238,6 +266,12 @@ result = client.write(print(result["root_uri"])```+**TypeScript SDK**++```typescript+await client.write("viking://resources/docs/new.md", "# New document\n", { wait: true });+```+**Go SDK**```go@@ -282,6 +316,7 @@ openviking write viking://resources/docs/api.md \--wait```+**Response**```json@@ -325,7 +360,7 @@ List directory contents.| uri | str | Yes | - | Viking URI || simple | bool | No | False | Return only relative paths || recursive | bool | No | False | List all subdirectories recursively |-| output | str | No | `agent` | Output format: `agent` or `original` |+| output | str | No | HTTP: `agent`; SDKs: `original` | Output format: `agent` or `original` || abs_limit | int | No | 256 | Abstract length limit for `agent` output || show_all_hidden | bool | No | False | Include hidden files like `-a` || node_limit | int | No | 1000 | Maximum number of results |@@ -344,6 +379,7 @@ List directory contents.}```+**Python SDK (Embedded / HTTP)**```python@@ -353,6 +389,13 @@ for entry in entries:print(f"{entry['name']} - {type_str}")```+**TypeScript SDK**++```typescript+const entries = await client.list("viking://resources/docs/", { simple: true });+console.log(entries);+```+**Go SDK**```go@@ -391,6 +434,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&recursivopenviking ls viking://resources/ [--simple] [--recursive]```+**Response**```json@@ -421,12 +465,13 @@ Get directory tree structure.| Parameter | Type | Required | Default | Description ||-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI |-| output | str | No | `agent` | Output format: `agent` or `original` |-| abs_limit | int | No | 256 | Abstract length limit for `agent` output |+| output | str | No | HTTP: `agent`; SDKs: `original` | Output format: `agent` or `original` |+| abs_limit | int | No | HTTP: 256; SDKs: 128 | Abstract length limit for `agent` output || show_all_hidden | bool | No | False | Include hidden files like `-a` || node_limit | int | No | 1000 | Maximum number of results || level_limit | int | No | 3 | Maximum directory depth to traverse |+**Python SDK (Embedded / HTTP)**```python@@ -436,6 +481,13 @@ for entry in entries:print(f"{entry['rel_path']} - {type_str}")```+**TypeScript SDK**++```typescript+const tree = await client.tree("viking://resources/docs/", { nodeLimit: 100 });+console.log(tree);+```+**Go SDK**```go@@ -465,6 +517,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/tree?uri=viking://resources/" \openviking tree viking://resources/my-project/```+**Response**```json@@ -502,6 +555,7 @@ Get file or directory status information. For directories, returns the count of|-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI |+**Python SDK (Embedded / HTTP)**```python@@ -515,6 +569,13 @@ if dir_info.get('isDir'):print(f"Item count: {dir_info.get('count')}")```+**TypeScript SDK**++```typescript+const metadata = await client.stat("viking://resources/docs/api.md");+console.log(metadata);+```+**Go SDK**```go@@ -543,6 +604,7 @@ openviking stat viking://resources/my-project/docs/api.mdopenviking stat viking://resources/my-project/docs```+**Response (File)**```json@@ -596,6 +658,7 @@ Get logical extended attributes for a file or directory.|-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI |+**Python SDK (HTTP)**```python@@ -603,6 +666,13 @@ attrs = client.attrs("viking://resources/docs/api.md")print(attrs["attrs"]["tags"])```+**TypeScript SDK**++```typescript+const attributes = await client.attrs("viking://resources/docs/api.md");+console.log(attributes);+```+**Go SDK**```go@@ -643,6 +713,7 @@ openviking attrs set-tags viking://resources/docs --tags team=search --mode appeDirectory targets update the directory semantic records; `recursive=true` also updates existing descendant files and directory semantic records.+**Response (Resource)**```json@@ -694,6 +765,7 @@ Create a directory.| uri | str | Yes | - | Viking URI for the new directory || description | str | No | `null` | Initial directory description. When provided, it is written to `.abstract.md` and queued for L0 vectorization. |+**Python SDK (Embedded / HTTP)**```python@@ -701,6 +773,12 @@ client.mkdir("viking://resources/new-project/")client.mkdir("viking://resources/new-project/", description="API docs directory")```+**TypeScript SDK**++```typescript+await client.mkdir("viking://resources/docs/guides/", "Project guides");+```+**Go SDK**```go@@ -732,6 +810,7 @@ openviking mkdir viking://resources/new-project/openviking mkdir viking://resources/new-project/ --description "API docs directory"```+**Response**```json@@ -760,6 +839,7 @@ Invalid URI formats, unsupported schemes, and non-public scopes return `INVALID_| uri | str | Yes | - | Viking URI to remove || recursive | bool | No | False | Remove directory recursively |+**Python SDK (Embedded / HTTP)**```python@@ -767,9 +847,13 @@ Invalid URI formats, unsupported schemes, and non-public scopes return `INVALID_client.rm("viking://resources/docs/old.md")# Remove directory recursively-result = client.rm("viking://resources/old-project/", recursive=True)-if 'estimated_deleted_count' in result:- print(f"Deleted {result['estimated_deleted_count']} items")+client.rm("viking://resources/old-project/", recursive=True)+```++**TypeScript SDK**++```typescript+await client.remove("viking://resources/docs/old.md", { wait: true });```**Go SDK**@@ -805,6 +889,7 @@ curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/old-projeopenviking rm viking://resources/old.md [--recursive]```+**Response (Single file)**```json@@ -847,6 +932,7 @@ Move file or directory.| from_uri | str | Yes | - | Source Viking URI || to_uri | str | Yes | - | Destination Viking URI |+**Python SDK (Embedded / HTTP)**```python@@ -856,6 +942,15 @@ client.mv()```+**TypeScript SDK**++```typescript+await client.move(+ "viking://resources/docs/old.md",+ "viking://resources/docs/new.md",+);+```+**Go SDK**```go@@ -886,6 +981,7 @@ curl -X POST http://localhost:1933/api/v1/fs/mv \openviking mv viking://resources/old-name/ viking://resources/new-name/```+**Response**```json@@ -916,6 +1012,7 @@ Search content by pattern.| node_limit | int | No | 256 | Maximum number of results. Omitted requests default to 256; pass a larger integer when you need more results || level_limit | int | No | Python SDK: 5; HTTP API / CLI / Go SDK: 10 | Maximum directory depth to traverse. The Go SDK currently uses the HTTP API default. |+**Python SDK (Embedded / HTTP)**```python@@ -932,6 +1029,13 @@ for match in results['matches']:print(f" {match['content']}")```+**TypeScript SDK**++```typescript+const matches = await client.grep("viking://resources/docs/", "authentication");+console.log(matches);+```+**Go SDK**```go@@ -969,6 +1073,7 @@ curl -X POST http://localhost:1933/api/v1/search/grep \openviking grep "authentication" --uri viking://resources/ [--ignore-case]```+**Response**```json@@ -1000,7 +1105,8 @@ Match files by pattern.|-----------|------|----------|---------|-------------|| pattern | str | Yes | - | Glob pattern (e.g., `**/*.md`) || uri | str | No | "viking://" | Starting URI |-| node_limit | int | No | None | Maximum number of results |+| node_limit | int | No | 256 | Maximum number of results |+**Python SDK (Embedded / HTTP)**@@ -1016,6 +1122,13 @@ results = client.glob("**/*.py", "viking://resources/")print(f"Found {results['count']} Python files")```+**TypeScript SDK**++```typescript+const matches = await client.glob("**/*.md", "viking://resources/docs/");+console.log(matches);+```+**Go SDK**```go@@ -1050,6 +1163,7 @@ curl -X POST http://localhost:1933/api/v1/search/glob \openviking glob "**/*.md" [--uri viking://resources/]```+**Response**```json@@ -1080,6 +1194,7 @@ Create relations between resources.| to_uris | str or List[str] | Yes | - | Target URI(s) || reason | str | No | "" | Reason for the link |+**Python SDK (Embedded / HTTP)**```python@@ -1101,6 +1216,19 @@ client.link()```+**TypeScript SDK**++```typescript+await client.link(+ "viking://resources/docs/api/",+ [+ "viking://resources/docs/auth/",+ "viking://resources/docs/errors/",+ ],+ "Related documentation",+);+```+**HTTP API**```@@ -1135,6 +1263,7 @@ curl -X POST http://localhost:1933/api/v1/relations/link \openviking link viking://resources/docs/auth/ viking://resources/docs/security/ --reason "Security best practices"```+**Response**```json@@ -1160,6 +1289,7 @@ Get relations for a resource.|-----------|------|----------|---------|-------------|| uri | str | Yes | - | Viking URI |+**Python SDK (Embedded / HTTP)**```python@@ -1169,6 +1299,13 @@ for rel in relations:print(f" Reason: {rel['reason']}")```+**TypeScript SDK**++```typescript+const relations = await client.relations("viking://resources/docs/auth/");+console.log(relations);+```+**HTTP API**```@@ -1186,6 +1323,7 @@ curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/openviking relations viking://resources/docs/auth/```+**Response**```json@@ -1212,6 +1350,7 @@ Remove a relation.| from_uri | str | Yes | - | Source URI || to_uri | str | Yes | - | Target URI to unlink |+**Python SDK (Embedded / HTTP)**```python@@ -1221,6 +1360,15 @@ client.unlink()```+**TypeScript SDK**++```typescript+await client.unlink(+ "viking://resources/docs/auth/",+ "viking://resources/docs/security/",+);+```+**HTTP API**```@@ -1243,6 +1391,7 @@ curl -X DELETE http://localhost:1933/api/v1/relations/link \openviking unlink viking://resources/docs/auth/ viking://resources/docs/security/```+**Response**```json@@ -1264,7 +1413,7 @@ Export a resource tree as a `.ovpack` file.#### 1. API Implementation Overview-Packages all resources under the specified URI into a `.ovpack` file for backup or migration. Requires ROOT or ADMIN permissions.+Packages all resources under the specified URI into a `.ovpack` file for backup or migration. Available to ROOT, ADMIN, and USER roles; normal URI access controls still apply.**Processing Flow**:1. Verify user permissions@@ -1296,10 +1445,11 @@ Packages all resources under the specified URI into a `.ovpack` file for backup| uri | string | Yes | - | Viking URI to export || include_vectors | boolean | No | false | Include a pure-dense vector snapshot; hybrid index types are rejected |-**Permission Requirements**: ROOT or ADMIN+**Permission Requirements**: ROOT, ADMIN, or USER#### 3. Usage Examples+**HTTP API**```@@ -1330,6 +1480,17 @@ client.initialize()# Note: Export functionality is primarily used via CLI```+**TypeScript SDK**++```typescript+const outputPath = await client.exportOVPack(+ "viking://resources/docs/",+ "./exports/docs.ovpack",+ true,+);+console.log(outputPath);+```+**Go SDK**```go@@ -1355,6 +1516,7 @@ ov export viking://resources/my-project/ ./exports/my-project.ovpackov export viking://resources/my-project/ ./exports/my-project.ovpack --include-vectors```+**Response Example**This endpoint directly returns a file stream (`Content-Type: application/zip`), does not return a JSON envelope.@@ -1367,7 +1529,7 @@ Import a `.ovpack` file.#### 1. API Implementation Overview-Imports a `.ovpack` file to a specified location for restoring or migrating data. Requires ROOT or ADMIN permissions.+Imports a `.ovpack` file to a specified location for restoring or migrating data. Available to ROOT, ADMIN, and USER roles; normal URI access controls still apply.**Processing Flow**:1. Verify user permissions@@ -1392,7 +1554,7 @@ Imports a `.ovpack` file to a specified location for restoring or migrating data| on_conflict | string | No | fail | Conflict policy: `fail`, `overwrite`, or `skip` || vector_mode | string | No | auto | Vector handling: `auto`, `recompute`, or `require` |-**Permission Requirements**: ROOT or ADMIN+**Permission Requirements**: ROOT, ADMIN, or USER**Behavior Notes**:- The API no longer accepts `vectorize` or `force`.@@ -1411,6 +1573,7 @@ Imports a `.ovpack` file to a specified location for restoring or migrating data#### 3. Usage Examples+**HTTP API**```@@ -1451,6 +1614,20 @@ client.initialize()# Note: Import functionality is primarily used via CLI```+**TypeScript SDK**++```typescript+const uri = await client.importOVPack(+ "./exports/docs.ovpack",+ "viking://resources/",+ {+ onConflict: "overwrite",+ vectorMode: "auto",+ },+);+console.log(uri);+```+**Go SDK**```go@@ -1482,6 +1659,7 @@ ov import ./exports/my-project.ovpack viking://resources/imported/ --on-conflictov import ./exports/my-project.ovpack viking://resources/imported/ --vector-mode require```+**Response Example**```jsondiff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.mdindex 8ae142a49..4645b6920 100644--- a/docs/en/api/04-skills.md+++ b/docs/en/api/04-skills.md@@ -321,6 +321,12 @@ result = client.add_skill("./skills/my-skill/", wait=True)client.wait_processed()```+**TypeScript SDK**++```typescript+await client.addSkill("./my-skill", { wait: true });+```+**Go SDK**```go@@ -442,6 +448,12 @@ for skill in skills["skills"]:print(skill["name"])```+**TypeScript SDK**++```typescript+console.log(await client.listSkills());+```+**Go SDK**```go@@ -466,6 +478,12 @@ print(skill["name"])print(skill.get("content"))```+**TypeScript SDK**++```typescript+console.log(await client.getSkill("my-skill"));+```+**Go SDK**```go@@ -494,6 +512,12 @@ for skill in results["skills"]:print(skill["name"], skill["score"])```+**TypeScript SDK**++```typescript+console.log(await client.findSkills("database migration"));+```+**Go SDK**```go@@ -524,6 +548,16 @@ validated = client.validate_skill({"name": "search-web", "description": "..."})updated = client.update_skill("search-web", "./skills/search-web", wait=True)```+**TypeScript SDK**++```typescript+console.log(await client.validateSkill({+ name: "search-web",+ description: "Search the web for current information",+ content: "# search-web\n\nSearch the web for current information.",+}));+```+**Go SDK**```go@@ -554,6 +588,12 @@ curl -X POST http://localhost:1933/api/v1/skills/validate \client.delete_skill("old-skill")```+**TypeScript SDK**++```typescript+await client.deleteSkill("my-skill");+```+**Go SDK**```godiff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex 3ab7ee36d..aaecb6349 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -82,6 +82,13 @@ result = await client.create_session(session_id="my-custom-session-id")print(f"Session ID: {result['session_id']}")```+**TypeScript SDK**++```typescript+const session = await client.createSession();+console.log(session);+```+**Go SDK**```go@@ -161,6 +168,12 @@ for s in sessions:print(f"{s['session_id']} -> {s['uri']}")```+**TypeScript SDK**++```typescript+console.log(await client.listSessions());+```+**Go SDK**```go@@ -260,6 +273,12 @@ print(f"Commits: {info['commit_count']}")info = await client.get_session("a1b2c3d4", auto_create=True)```+**TypeScript SDK**++```typescript+console.log(await client.getSession("session-id"));+```+**Go SDK**```go@@ -386,6 +405,12 @@ print(context["latest_archive_overview"])print(len(context["messages"]))```+**TypeScript SDK**++```typescript+console.log(await client.getSessionContext("session-id"));+```+**Go SDK**```go@@ -490,6 +515,12 @@ print(archive["overview"])print(len(archive["messages"]))```+**TypeScript SDK**++```typescript+console.log(await client.getSessionArchive("session-id", "archive-id"));+```+**Go SDK**```go@@ -596,6 +627,12 @@ client = ov.Client(base_url="http://localhost:1933", api_key="your-key")await client.delete_session("a1b2c3d4")```+**TypeScript SDK**++```typescript+await client.deleteSession("session-id");+```+**Go SDK**```go@@ -791,6 +828,12 @@ await client.add_message()```+**TypeScript SDK**++```typescript+await client.addMessage("session-id", { role: "user", content: "Hello" });+```+**Go SDK**```go@@ -894,6 +937,15 @@ result = await client.batch_add_messages(print(f"Added: {result['added']}, Total: {result['message_count']}")```+**TypeScript SDK**++```typescript+await client.batchAddMessages("session-id", [+ { role: "user", content: "Hello" },+ { role: "assistant", content: "Hi" },+]);+```+**Go SDK**```go@@ -1063,6 +1115,12 @@ if task["status"] == "completed":print(f"Memories extracted: {total}")```+**TypeScript SDK**++```typescript+console.log(await client.commitSession("session-id"));+```+**Go SDK**```go@@ -1207,6 +1265,12 @@ task = await client.get_task(task_id="uuid-xxx")print(f"Status: {task['status']}")```+**TypeScript SDK**++```typescript+console.log(await client.getTask("task-id"));+```+**Go SDK**```go@@ -1328,6 +1392,12 @@ for task in tasks:print(task["task_id"], task["status"])```+**TypeScript SDK**++```typescript+console.log(await client.listTasks());+```+**Go SDK**```godiff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex 292aba745..6d01551b7 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -241,6 +241,12 @@ results = client.find()```+**TypeScript SDK**++```typescript+console.log(await client.find("authentication", { targetUri: "viking://resources/docs/" }));+```+**Go SDK**```go@@ -475,6 +481,12 @@ for ctx in results.resources:results = client.search("similar poster", image="/path/to/poster.png")```+**TypeScript SDK**++```typescript+console.log(await client.search("authentication", { targetUri: "viking://resources/docs/" }));+```+**Go SDK**```go@@ -631,6 +643,12 @@ for match in results['matches']:print(f" {match['content']}")```+**TypeScript SDK**++```typescript+console.log(await client.grep("viking://resources/docs/", "authentication"));+```+**Go SDK**```go@@ -745,6 +763,12 @@ results = client.glob("**/*.py", "viking://resources", node_limit=1024)print(f"Found {results['count']} Python files")```+**TypeScript SDK**++```typescript+console.log(await client.glob("**/*.md", "viking://resources/docs/"));+```+**Go SDK**```godiff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex db81939de..ff6b4454e 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -66,6 +66,12 @@ healthy = client.health()print(f"Healthy: {healthy}")```+**TypeScript SDK**++```typescript+console.log(await client.health());+```+**Go SDK**```go@@ -202,6 +208,12 @@ status = client.get_status()print(status)```+**TypeScript SDK**++```typescript+console.log(await client.getStatus());+```+**CLI**```bash@@ -272,6 +284,12 @@ print(report["ok"])print(report["missing_records"])```+**TypeScript SDK**++```typescript+console.log(await client.checkConsistency("viking://resources/"));+```+**Go SDK**```go@@ -359,6 +377,12 @@ status = client.wait_processed(timeout=60.0)print(f"Processing complete: {status}")```+**TypeScript SDK**++```typescript+console.log(await client.waitProcessed(60));+```+**Go SDK**```go@@ -468,6 +492,12 @@ result = client.reindex(print(result["status"])```+**TypeScript SDK**++```typescript+console.log(await client.reindex("viking://resources/docs/"));+```+**Go SDK**```go@@ -641,6 +671,12 @@ print(client.observer.queue)# TOTAL 0 0 20 0 20```+**TypeScript SDK**++```typescript+console.log(await client.queueStatus());+```+**Go SDK**```go@@ -718,6 +754,12 @@ print(client.observer.vikingdb().is_healthy) # Trueprint(client.observer.vikingdb().status) # Status table string```+**TypeScript SDK**++```typescript+console.log(await client.vikingDBStatus());+```+**Go SDK**```go@@ -792,6 +834,12 @@ print(client.observer.models)# vlm yes ...```+**TypeScript SDK**++```typescript+console.log(await client.modelsStatus());+```+**Go SDK**```godiff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex be13ec156..021f2c17d 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -180,6 +180,12 @@ result = client.admin_create_account()```+**TypeScript SDK**++```typescript+console.log(await client.adminCreateAccount("account-id", "admin-user-id"));+```+**Go SDK**```go@@ -276,6 +282,12 @@ for account in accounts:print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")```+**TypeScript SDK**++```typescript+console.log(await client.adminListAccounts());+```+**Go SDK**```go@@ -362,6 +374,12 @@ result = client.admin_delete_account("acme")print(f"Account deleted: {result['deleted']}")```+**TypeScript SDK**++```typescript+await client.adminDeleteAccount("account-id");+```+**Go SDK**```go@@ -470,6 +488,12 @@ result = client.admin_register_user()```+**TypeScript SDK**++```typescript+console.log(await client.adminRegisterUser("account-id", "user-id", "user"));+```+**Go SDK**```go@@ -581,6 +605,12 @@ for user in users:print(f"User: {user['user_id']}, role: {user['role']}")```+**TypeScript SDK**++```typescript+console.log(await client.adminListUsers("account-id"));+```+**Go SDK**```go@@ -671,6 +701,12 @@ result = client.admin_remove_user("acme", "bob")print(f"User deleted: {result['deleted']}")```+**TypeScript SDK**++```typescript+await client.adminRemoveUser("account-id", "user-id");+```+**Go SDK**```go@@ -762,6 +798,12 @@ result = client.admin_set_role("acme", "bob", "admin")print(f"User: {result['user_id']}, new role: {result['role']}")```+**TypeScript SDK**++```typescript+await client.adminSetRole("account-id", "user-id", "admin");+```+**Go SDK**```go@@ -854,6 +896,12 @@ result = client.admin_regenerate_key("acme", "bob", seed="bob-new-seed")print(f"New user key: {result['user_key']}")```+**TypeScript SDK**++```typescript+console.log(await client.adminRegenerateKey("account-id", "user-id"));+```+**Go SDK**```go@@ -947,24 +995,34 @@ POST /api/v1/admin/migrate#### 3. Usage Examples-**Run migration**+**HTTP API**```bash+# Run migrationcurl -X POST http://localhost:1933/api/v1/admin/migrate \-H "Content-Type: application/json" \-H "X-API-Key: <root-key>" \-d '{"action": "migrate"}'-```--**Clean old namespaces**-```bash+# Clean old namespacescurl -X POST http://localhost:1933/api/v1/admin/migrate \-H "Content-Type: application/json" \-H "X-API-Key: <root-key>" \-d '{"action": "cleanup"}'```+**Python SDK**++```python+print(client.admin_migrate(cleanup=False))+```++**TypeScript SDK**++```typescript+console.log(await client.adminMigrate(false));+```+**Go SDK**```godiff --git a/docs/en/api/11-snapshot.md b/docs/en/api/11-snapshot.mdindex 1bbd8d08e..e69442cab 100644--- a/docs/en/api/11-snapshot.md+++ b/docs/en/api/11-snapshot.md@@ -55,6 +55,12 @@ result = client.snapshot.commit(print(result["commit_oid"])```+**TypeScript SDK**++```typescript+console.log(await client.gitCommit({ message: "Update docs", paths: ["resources/docs"] }));+```+**HTTP API**```@@ -127,6 +133,12 @@ for commit in history:print(commit["oid"], commit["message"])```+**TypeScript SDK**++```typescript+console.log(await client.gitLog("main", 20));+```+**HTTP API**```@@ -200,6 +212,12 @@ print(meta["message"], meta["parents"])blob = client.snapshot.show("3f2a1b9c", path="viking://resources/my_project/guide.md")```+**TypeScript SDK**++```typescript+console.log(await client.gitShow("main", "viking://resources/docs/api.md"));+```+> Note: when reading a file (`path` given), the **Embedded (local) client** returns raw `bytes`, while the **HTTP client** returns a `{"oid": str, "size": int, "bytes": bytes}` dict.**HTTP API**@@ -298,6 +316,15 @@ plan = client.snapshot.restore(print(plan["diff"])```+**TypeScript SDK**++```typescript+console.log(await client.gitRestore({+ projectDir: "viking://resources/docs",+ sourceCommit: "3f2a1b9c",+}));+```+**HTTP API**```@@ -404,6 +431,12 @@ Reads the account `.ovgitignore` content; returns an empty string when the filecontent = client.snapshot.get_gitignore()```+**TypeScript SDK**++```typescript+console.log(await client.gitGetIgnore());+```+**HTTP API**```@@ -448,6 +481,12 @@ Writes the account `.ovgitignore` content (overwrites). The size limit (64 KiB)client.snapshot.set_gitignore(content="*.log\n")```+**TypeScript SDK**++```typescript+await client.gitSetIgnore("*.tmp\n.cache/\n");+```+**HTTP API**```@@ -488,6 +527,12 @@ Deletes the account `.ovgitignore`. Missing is success (idempotent).client.snapshot.delete_gitignore()```+**TypeScript SDK**++```typescript+await client.gitDeleteIgnore();+```+**HTTP API**```diff --git a/docs/en/api/99-api-doc-writing-guide.md b/docs/en/api/99-api-doc-writing-guide.mdindex e8bdd993b..9e1b8f01a 100644--- a/docs/en/api/99-api-doc-writing-guide.md+++ b/docs/en/api/99-api-doc-writing-guide.md@@ -47,19 +47,15 @@ Explain the purpose of this API, point to the corresponding code entry, and brie#### 3. Usage Examples-**HTTP API**--```-<HTTP Method> <Path>-```+**Python SDK**-```bash-<curl example>+```python+<SDK call example>```-**Python SDK**+**TypeScript SDK**-```python+```typescript<SDK call example>```@@ -69,6 +65,16 @@ Explain the purpose of this API, point to the corresponding code entry, and brie<SDK call example>```+**HTTP API**++```+<HTTP Method> <Path>+```++```bash+<curl example>+```+**CLI**```bash@@ -128,13 +134,17 @@ Each API is organized in the following three parts:#### 3. Usage Examples-Provide in order:-- HTTP API (method + path + curl example)+When an operation presents all transports together, prefer this order:- Python SDK example+- TypeScript SDK example- Go SDK example, when it adds endpoint-specific value and can stay concise+- HTTP API (method + path + curl example)- CLI example- Response example+For an existing operation with a workflow-specific structure, keep the local+structure stable and place TypeScript next to the other SDK examples.+Keep API documentation organized around API modules and individual operations,not around client languages. SDK snippets should be short call examples insidethe relevant operation's Usage Examples. Put language-specific quick references,diff --git a/docs/package.json b/docs/package.jsonindex d7d42f56f..3ca1b3e32 100644--- a/docs/package.json+++ b/docs/package.json@@ -7,6 +7,8 @@"docs:dev": "vitepress dev . --host 0.0.0.0","docs:build": "vitepress build .","docs:preview": "vitepress preview . --host 0.0.0.0",+ "check:api": "node scripts/check-api-reference.mjs",+ "test:theme": "node --experimental-strip-types --test .vitepress/theme/*.test.ts","test:search": "node --experimental-strip-types --test .vitepress/theme/openviking-search-*.test.ts"},"devDependencies": {diff --git a/docs/scripts/check-api-reference.mjs b/docs/scripts/check-api-reference.mjsnew file mode 100644index 000000000..573046e6d--- /dev/null+++ b/docs/scripts/check-api-reference.mjs@@ -0,0 +1,246 @@+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'++const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')+const routerDir = path.join(repoRoot, 'openviking/server/routers')+const apiDocs = ['zh', 'en'].flatMap((locale) =>+ fs.readdirSync(path.join(repoRoot, 'docs', locale, 'api'))+ .filter((file) => file.endsWith('.md') && !file.startsWith('01-') && !file.startsWith('99-'))+ .map((file) => path.join(repoRoot, 'docs', locale, 'api', file))+)++function normalizePath(value) {+ const pathname = value.split('?')[0].replace(/\/$/, '') || '/'+ return pathname.replace(/\{[^}]+\}/g, '{}')+}++function closingDelimiter(source, openingIndex, opening = '(', closing = ')') {+ let depth = 0+ let quote = ''+ let escaped = false+ for (let index = openingIndex; index < source.length; index++) {+ const character = source[index]+ if (quote) {+ if (escaped) escaped = false+ else if (character === '\\') escaped = true+ else if (character === quote) quote = ''+ continue+ }+ if (character === '"' || character === "'" || character === '`') {+ quote = character+ continue+ }+ if (character === opening) depth+++ else if (character === closing && --depth === 0) return index+ }+ return -1+}++function splitTopLevel(source) {+ const parts = []+ let start = 0+ const stack = []+ let quote = ''+ let escaped = false+ const pairs = { '(': ')', '[': ']', '{': '}' }+ for (let index = 0; index < source.length; index++) {+ const character = source[index]+ if (quote) {+ if (escaped) escaped = false+ else if (character === '\\') escaped = true+ else if (character === quote) quote = ''+ continue+ }+ if (character === '"' || character === "'" || character === '`') quote = character+ else if (pairs[character]) stack.push(pairs[character])+ else if (character === stack.at(-1)) stack.pop()+ else if (character === ',' && stack.length === 0) {+ parts.push(source.slice(start, index).trim())+ start = index + 1+ }+ }+ const tail = source.slice(start).trim()+ if (tail) parts.push(tail)+ return parts+}++const routes = new Map()+for (const file of fs.readdirSync(routerDir).filter((name) => name.endsWith('.py'))) {+ const source = fs.readFileSync(path.join(routerDir, file), 'utf8')+ const prefix = source.match(/router\s*=\s*APIRouter\([^)]*prefix=["']([^"']+)/s)?.[1] ?? ''+ for (const match of source.matchAll(/@router\.(get|post|put|patch|delete)\(\s*["']([^"']*)/g)) {+ const definition = source.indexOf('def ', match.index + match[0].length)+ const opening = source.indexOf('(', definition)+ const closing = closingDelimiter(source, opening)+ const signature = closing < 0 ? '' : source.slice(opening + 1, closing)+ const routePath = prefix + match[2]+ const pathParameters = new Set(+ Array.from(routePath.matchAll(/\{([^}]+)\}/g), (item) => item[1])+ )+ const query = new Map()+ for (const parameter of splitTopLevel(signature)) {+ const queryMatch = parameter.match(/^([A-Za-z_]\w*)\s*:[\s\S]*?=\s*Query\(([\s\S]*)\)$/)+ if (queryMatch) {+ query.set(queryMatch[1], /^\s*\.\.\.(?:\s*,|\s*$)/.test(queryMatch[2]))+ continue+ }++ const defaultMatch = parameter.match(/^([A-Za-z_]\w*)\s*:[\s\S]*?=\s*([\s\S]+)$/)+ if (!defaultMatch || pathParameters.has(defaultMatch[1])) continue+ if (+ /^(?:Path|Depends|Body|Header|Cookie|File|Form|Security)\s*\(/.test(defaultMatch[2])+ ) continue+ query.set(defaultMatch[1], false)+ }+ routes.set(`${match[1].toUpperCase()} ${normalizePath(routePath)}`, { query, pathParameters })+ }+}++const clientSource = fs.readFileSync(path.join(repoRoot, 'sdk/typescript/src/client.ts'), 'utf8')+const clientMethods = new Map()+for (const match of clientSource.matchAll(/^ (?:async )?([A-Za-z][A-Za-z0-9]*)\s*\(/gm)) {+ const opening = clientSource.indexOf('(', match.index)+ const closing = closingDelimiter(clientSource, opening)+ if (closing < 0) continue+ const parameters = splitTopLevel(clientSource.slice(opening + 1, closing))+ const required = parameters.filter((parameter) => {+ const declaration = parameter.split(':', 1)[0]+ return !declaration.includes('?') && !parameter.includes('=') && !parameter.startsWith('...')+ }).length+ clientMethods.set(match[1], {+ required,+ maximum: parameters.some((parameter) => parameter.startsWith('...'))+ ? Infinity+ : parameters.length,+ parameters+ })+}++const errors = []+let httpExamples = 0+let typescriptCalls = 0+const curlUrlPattern = String.raw`["']?https?:\/\/[^/\s"']+(\/[A-Za-z0-9_{}<>?=&./:-]+)`+const explicitCurlPattern = new RegExp(+ String.raw`\bcurl\b[^\n]*?(?:-X|--request)\s+(GET|POST|PUT|PATCH|DELETE)\s+` ++ curlUrlPattern,+ 'g'+)+const implicitGetCurlPattern = new RegExp(+ String.raw`\bcurl\b(?![^\n]*(?:-X|--request))[^\n]*?` + curlUrlPattern,+ 'g'+)+for (const file of apiDocs) {+ const source = fs.readFileSync(file, 'utf8')+ const relative = path.relative(repoRoot, file)+ const httpReferences = [+ ...Array.from(+ source.matchAll(/^\s*(GET|POST|PUT|PATCH|DELETE)\s+(\/[A-Za-z0-9_{}?=&./:-]+)/gm),+ (match) => [match[1], match[2]]+ ),+ ...Array.from(+ source.matchAll(explicitCurlPattern),+ (match) => [match[1], match[2]]+ ),+ ...Array.from(+ source.matchAll(implicitGetCurlPattern),+ (match) => ['GET', match[1]]+ )+ ]+ for (const [method, documentedPath] of httpReferences) {+ const normalizedPath = normalizePath(documentedPath)+ const route = `${method} ${normalizedPath}`+ httpExamples+++ let contract = routes.get(route)+ if (!contract) {+ for (const [candidate, candidateContract] of routes) {+ const [candidateMethod, candidatePath] = candidate.split(' ', 2)+ if (candidateMethod !== method) continue+ const pattern = candidatePath+ .replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+ .replace(/\\\{\\\}/g, '[^/]+')+ if (new RegExp(`^${pattern}$`).test(normalizedPath)) {+ contract = candidateContract+ break+ }+ }+ }+ if (!contract) {+ errors.push(`${relative}: unknown HTTP route ${route}`)+ continue+ }+ const documentedPathParameters = new Set(+ Array.from(documentedPath.split('?')[0].matchAll(/\{([^}]+)\}/g), (item) => item[1])+ )+ if (documentedPathParameters.size) {+ for (const name of documentedPathParameters) {+ if (!contract.pathParameters.has(name)) {+ errors.push(`${relative}: ${route} has unknown path parameter ${name}`)+ }+ }+ for (const name of contract.pathParameters) {+ if (!documentedPathParameters.has(name)) {+ errors.push(`${relative}: ${route} is missing path parameter ${name}`)+ }+ }+ }+ const queryNames = new Set(+ (documentedPath.split('?')[1] ?? '')+ .split('&')+ .filter(Boolean)+ .map((item) => item.split('=')[0])+ )+ for (const name of queryNames) {+ if (!contract.query.has(name)) {+ errors.push(`${relative}: ${route} has unknown query parameter ${name}`)+ }+ }+ for (const [name, required] of contract.query) {+ if (required && !queryNames.has(name)) {+ errors.push(`${relative}: ${route} is missing required query parameter ${name}`)+ }+ }+ }+ for (const block of source.matchAll(/```(?:typescript|ts)\n([\s\S]*?)\n```/g)) {+ for (const call of block[1].matchAll(/\bclient\.([A-Za-z][A-Za-z0-9]*)\s*\(/g)) {+ typescriptCalls+++ const contract = clientMethods.get(call[1])+ if (!contract) {+ errors.push(`${relative}: unknown TypeScript SDK method client.${call[1]}()`)+ continue+ }+ const opening = call.index + call[0].lastIndexOf('(')+ const closing = closingDelimiter(block[1], opening)+ if (closing < 0) {+ errors.push(`${relative}: could not parse TypeScript SDK call client.${call[1]}()`)+ continue+ }+ const args = splitTopLevel(block[1].slice(opening + 1, closing))+ const argumentCount = args.length+ if (argumentCount < contract.required || argumentCount > contract.maximum) {+ const expected = contract.required === contract.maximum+ ? String(contract.required)+ : `${contract.required}-${contract.maximum}`+ errors.push(+ `${relative}: client.${call[1]}() has ${argumentCount} arguments; expected ${expected}`+ )+ }+ for (let index = 0; index < Math.min(args.length, contract.parameters.length); index++) {+ const type = contract.parameters[index].match(/:\s*([^=]+?)(?:\s*=|$)/)?.[1]?.trim()+ if (type === 'string' && /^[{[]/.test(args[index])) {+ errors.push(`${relative}: client.${call[1]}() argument ${index + 1} must be a string`)+ }+ }+ }+ }+}++if (errors.length) {+ console.error(errors.join('\n'))+ process.exitCode = 1+} else {+ console.log(+ `API reference check passed: ${httpExamples} HTTP examples with query contracts, ` ++ `${typescriptCalls} TypeScript SDK calls with signature contracts`+ )+}diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 5f70e8331..9b7a2445a 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -358,6 +358,16 @@ client.add_resource()```+**TypeScript SDK**++```typescript+const task = await client.addResource("https://example.com/docs", {+ to: "viking://resources/docs/",+ wait: true,+});+console.log(task);+```+**Go SDK**```go@@ -731,6 +741,13 @@ result = client.add_skill("./skills/my-skill.json")client.wait_processed()```+**TypeScript SDK**++```typescript+const task = await client.addSkill("./my-skill", { wait: true });+console.log(task);+```+**Go SDK**```godiff --git a/docs/zh/api/03-filesystem.md b/docs/zh/api/03-filesystem.mdindex 9ac9d53a8..dba97c43c 100644--- a/docs/zh/api/03-filesystem.md+++ b/docs/zh/api/03-filesystem.md@@ -37,6 +37,7 @@ Phase 1 有意把范围控制得比较小:|------|------|------|--------|------|| uri | str | 是 | - | Viking URI(必须是目录) |+**Python SDK (Embedded / HTTP)**```python@@ -45,6 +46,13 @@ print(f"Abstract: {abstract}")# Output: "Documentation for the project API, covering authentication, endpoints..."```+**TypeScript SDK**++```typescript+const abstract = await client.abstract("viking://resources/docs/");+console.log(abstract);+```+**Go SDK**```go@@ -72,6 +80,7 @@ curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://resourceopenviking abstract viking://resources/docs/```+**响应**```json@@ -94,6 +103,7 @@ openviking abstract viking://resources/docs/|------|------|------|--------|------|| uri | str | 是 | - | Viking URI(必须是目录) |+**Python SDK (Embedded / HTTP)**```python@@ -101,6 +111,13 @@ overview = client.overview("viking://resources/docs/")print(f"Overview:\n{overview}")```+**TypeScript SDK**++```typescript+const overview = await client.overview("viking://resources/docs/");+console.log(overview);+```+**Go SDK**```go@@ -128,6 +145,7 @@ curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://resourceopenviking overview viking://resources/docs/```+**响应**```json@@ -158,6 +176,7 @@ openviking overview viking://resources/docs/- `read()` 只接受文件 URI。传入已存在的目录 URI 时返回 `INVALID_ARGUMENT`(`400`),而不是 `NOT_FOUND`。该错误会携带结构化的 `details` 字段——`details.expected` 为 `"file"`,`details.actual` 为 `"directory"`,`details.resource` 为出错的 URI(HTTP 路径上会带上)——客户端据此即可以编程方式判断"文件 vs 目录"不匹配(例如回退到 `list`),而无需对错误消息做字符串匹配。- 公开 URI 参数接受 `resources` 和 `user` 作用域。访问 session 文件时,使用 `viking://user/{user_id}/sessions/{session_id}`,也可以使用向后兼容的 `viking://session/{session_id}` 别名。`temp`、`queue` 等内部作用域会返回 `INVALID_URI`。+**Python SDK (Embedded / HTTP)**```python@@ -165,6 +184,13 @@ content = client.read("viking://resources/docs/api.md")print(f"Content:\n{content}")```+**TypeScript SDK**++```typescript+const content = await client.read("viking://resources/docs/api.md", 0, -1);+console.log(content);+```+**Go SDK**```go@@ -192,6 +218,7 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://resources/doopenviking read viking://resources/docs/api.md```+**响应**```json@@ -226,6 +253,7 @@ openviking read viking://resources/docs/api.md- 文件内容会在 API 返回前完成更新;`wait` 只控制是否等待语义/向量刷新完成。- 公共 API 已不再接受 `regenerate_semantics` 或 `revectorize`;写入后一定会自动刷新相关语义与向量。+**Python SDK (Embedded / HTTP)**```python@@ -238,6 +266,12 @@ result = client.write(print(result["root_uri"])```+**TypeScript SDK**++```typescript+await client.write("viking://resources/docs/new.md", "# New document\n", { wait: true });+```+**Go SDK**```go@@ -282,6 +316,7 @@ openviking write viking://resources/docs/api.md \--wait```+**响应**```json@@ -325,7 +360,7 @@ openviking write viking://resources/docs/api.md \| uri | str | 是 | - | Viking URI || simple | bool | 否 | False | 仅返回相对路径 || recursive | bool | 否 | False | 递归列出所有子目录 |-| output | str | 否 | `agent` | 输出格式:`agent` 或 `original` |+| output | str | 否 | HTTP:`agent`;SDK:`original` | 输出格式:`agent` 或 `original` || abs_limit | int | 否 | 256 | `agent` 输出中的摘要长度限制 || show_all_hidden | bool | 否 | False | 像 `-a` 一样包含隐藏文件 || node_limit | int | 否 | 1000 | 最大返回节点数 |@@ -345,6 +380,7 @@ openviking write viking://resources/docs/api.md \}```+**Python SDK (Embedded / HTTP)**```python@@ -354,6 +390,13 @@ for entry in entries:print(f"{entry['name']} - {type_str}")```+**TypeScript SDK**++```typescript+const entries = await client.list("viking://resources/docs/", { simple: true });+console.log(entries);+```+**Go SDK**```go@@ -392,6 +435,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://resources/&recursivopenviking ls viking://resources/ [--simple] [--recursive]```+**响应**```json@@ -422,12 +466,13 @@ openviking ls viking://resources/ [--simple] [--recursive]| 参数 | 类型 | 必填 | 默认值 | 说明 ||------|------|------|--------|------|| uri | str | 是 | - | Viking URI |-| output | str | 否 | `agent` | 输出格式:`agent` 或 `original` |-| abs_limit | int | 否 | 256 | `agent` 输出中的摘要长度限制 |+| output | str | 否 | HTTP:`agent`;SDK:`original` | 输出格式:`agent` 或 `original` |+| abs_limit | int | 否 | HTTP:256;SDK:128 | `agent` 输出中的摘要长度限制 || show_all_hidden | bool | 否 | False | 像 `-a` 一样包含隐藏文件 || node_limit | int | 否 | 1000 | 最大返回节点数 || level_limit | int | 否 | 3 | 最大目录遍历深度 |+**Python SDK (Embedded / HTTP)**```python@@ -437,6 +482,13 @@ for entry in entries:print(f"{entry['rel_path']} - {type_str}")```+**TypeScript SDK**++```typescript+const tree = await client.tree("viking://resources/docs/", { nodeLimit: 100 });+console.log(tree);+```+**Go SDK**```go@@ -466,6 +518,7 @@ curl -X GET "http://localhost:1933/api/v1/fs/tree?uri=viking://resources/" \openviking tree viking://resources/my-project/```+**响应**```json@@ -503,6 +556,7 @@ openviking tree viking://resources/my-project/|------|------|------|--------|------|| uri | str | 是 | - | Viking URI |+**Python SDK (Embedded / HTTP)**```python@@ -516,6 +570,13 @@ if dir_info.get('isDir'):print(f"Item count: {dir_info.get('count')}")```+**TypeScript SDK**++```typescript+const metadata = await client.stat("viking://resources/docs/api.md");+console.log(metadata);+```+**Go SDK**```go@@ -544,6 +605,7 @@ openviking stat viking://resources/my-project/docs/api.mdopenviking stat viking://resources/my-project/docs```+**响应(文件)**```json@@ -597,6 +659,7 @@ openviking stat viking://resources/my-project/docs|------|------|------|--------|------|| uri | str | 是 | - | Viking URI |+**Python SDK (HTTP)**```python@@ -604,6 +667,13 @@ attrs = client.attrs("viking://resources/docs/api.md")print(attrs["attrs"]["tags"])```+**TypeScript SDK**++```typescript+const attributes = await client.attrs("viking://resources/docs/api.md");+console.log(attributes);+```+**Go SDK**```go@@ -644,6 +714,7 @@ openviking attrs set-tags viking://resources/docs --tags team=search --mode appe目录目标会更新目录语义记录;`recursive=true` 还会更新已有子文件和子目录语义记录。+**响应(Resource)**```json@@ -695,6 +766,7 @@ openviking attrs set-tags viking://resources/docs --tags team=search --mode appe| uri | str | 是 | - | 新目录的 Viking URI || description | str | 否 | `null` | 目录初始说明。传入后会写入 `.abstract.md`,并进入目录 L0 向量化队列。 |+**Python SDK (Embedded / HTTP)**```python@@ -702,6 +774,12 @@ client.mkdir("viking://resources/new-project/")client.mkdir("viking://resources/new-project/", description="接口文档目录")```+**TypeScript SDK**++```typescript+await client.mkdir("viking://resources/docs/guides/", "Project guides");+```+**Go SDK**```go@@ -733,6 +811,7 @@ openviking mkdir viking://resources/new-project/openviking mkdir viking://resources/new-project/ --description "接口文档目录"```+**响应**```json@@ -761,6 +840,7 @@ URI 格式非法、scheme 不支持或使用非公开作用域时返回 `INVALID| uri | str | 是 | - | 要删除的 Viking URI || recursive | bool | 否 | False | 递归删除目录 |+**Python SDK (Embedded / HTTP)**```python@@ -768,9 +848,13 @@ URI 格式非法、scheme 不支持或使用非公开作用域时返回 `INVALIDclient.rm("viking://resources/docs/old.md")# 递归删除目录-result = client.rm("viking://resources/old-project/", recursive=True)-if 'estimated_deleted_count' in result:- print(f"Deleted {result['estimated_deleted_count']} items")+client.rm("viking://resources/old-project/", recursive=True)+```++**TypeScript SDK**++```typescript+await client.remove("viking://resources/docs/old.md", { wait: true });```**Go SDK**@@ -806,6 +890,7 @@ curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://resources/old-projeopenviking rm viking://resources/old.md [--recursive]```+**响应(单个文件)**```json@@ -848,6 +933,7 @@ openviking rm viking://resources/old.md [--recursive]| from_uri | str | 是 | - | 源 Viking URI || to_uri | str | 是 | - | 目标 Viking URI |+**Python SDK (Embedded / HTTP)**```python@@ -857,6 +943,15 @@ client.mv()```+**TypeScript SDK**++```typescript+await client.move(+ "viking://resources/docs/old.md",+ "viking://resources/docs/new.md",+);+```+**Go SDK**```go@@ -887,6 +982,7 @@ curl -X POST http://localhost:1933/api/v1/fs/mv \openviking mv viking://resources/old-name/ viking://resources/new-name/```+**响应**```json@@ -917,6 +1013,7 @@ openviking mv viking://resources/old-name/ viking://resources/new-name/| node_limit | int | 否 | 256 | 最大返回节点数。省略时默认使用 256;如需更多结果,请显式传入更大的整数 || level_limit | int | 否 | Python SDK: 5;HTTP API / CLI / Go SDK: 10 | 最大目录遍历深度。Go SDK 当前使用 HTTP API 默认值。 |+**Python SDK (Embedded / HTTP)**```python@@ -933,6 +1030,13 @@ for match in results['matches']:print(f" {match['content']}")```+**TypeScript SDK**++```typescript+const matches = await client.grep("viking://resources/docs/", "authentication");+console.log(matches);+```+**Go SDK**```go@@ -970,6 +1074,7 @@ curl -X POST http://localhost:1933/api/v1/search/grep \openviking grep "authentication" --uri viking://resources/ [--ignore-case]```+**响应**```json@@ -1003,6 +1108,7 @@ openviking grep "authentication" --uri viking://resources/ [--ignore-case]| uri | str | 否 | "viking://" | 起始 URI || node_limit | int | 否 | 256 | 最大返回匹配数。省略时默认使用 256;如需更多结果,请显式传入更大的整数 |+**Python SDK (Embedded / HTTP)**```python@@ -1017,6 +1123,13 @@ results = client.glob("**/*.py", "viking://resources/")print(f"Found {results['count']} Python files")```+**TypeScript SDK**++```typescript+const matches = await client.glob("**/*.md", "viking://resources/docs/");+console.log(matches);+```+**Go SDK**```go@@ -1051,6 +1164,7 @@ curl -X POST http://localhost:1933/api/v1/search/glob \openviking glob "**/*.md" [--uri viking://resources/]```+**响应**```json@@ -1081,6 +1195,7 @@ openviking glob "**/*.md" [--uri viking://resources/]| to_uris | str 或 List[str] | 是 | - | 目标 URI || reason | str | 否 | "" | 关联原因 |+**Python SDK (Embedded / HTTP)**```python@@ -1102,6 +1217,19 @@ client.link()```+**TypeScript SDK**++```typescript+await client.link(+ "viking://resources/docs/api/",+ [+ "viking://resources/docs/auth/",+ "viking://resources/docs/errors/",+ ],+ "Related documentation",+);+```+**HTTP API**```@@ -1136,6 +1264,7 @@ curl -X POST http://localhost:1933/api/v1/relations/link \openviking link viking://resources/docs/auth/ viking://resources/docs/security/ --reason "Security best practices"```+**响应**```json@@ -1161,6 +1290,7 @@ openviking link viking://resources/docs/auth/ viking://resources/docs/security/|------|------|------|--------|------|| uri | str | 是 | - | Viking URI |+**Python SDK (Embedded / HTTP)**```python@@ -1170,6 +1300,13 @@ for rel in relations:print(f" Reason: {rel['reason']}")```+**TypeScript SDK**++```typescript+const relations = await client.relations("viking://resources/docs/auth/");+console.log(relations);+```+**HTTP API**```@@ -1187,6 +1324,7 @@ curl -X GET "http://localhost:1933/api/v1/relations?uri=viking://resources/docs/openviking relations viking://resources/docs/auth/```+**响应**```json@@ -1213,6 +1351,7 @@ openviking relations viking://resources/docs/auth/| from_uri | str | 是 | - | 源 URI || to_uri | str | 是 | - | 要取消关联的目标 URI |+**Python SDK (Embedded / HTTP)**```python@@ -1222,6 +1361,15 @@ client.unlink()```+**TypeScript SDK**++```typescript+await client.unlink(+ "viking://resources/docs/auth/",+ "viking://resources/docs/security/",+);+```+**HTTP API**```@@ -1244,6 +1392,7 @@ curl -X DELETE http://localhost:1933/api/v1/relations/link \openviking unlink viking://resources/docs/auth/ viking://resources/docs/security/```+**响应**```json@@ -1265,7 +1414,7 @@ openviking unlink viking://resources/docs/auth/ viking://resources/docs/security#### 1. API 实现介绍-将指定 URI 下的所有资源打包成 `.ovpack` 格式文件,用于备份或迁移。需要 ROOT 或 ADMIN 权限。+将指定 URI 下的所有资源打包成 `.ovpack` 格式文件,用于备份或迁移。ROOT、ADMIN 和 USER 角色均可使用,仍受常规 URI 访问控制约束。**处理流程**:1. 验证用户权限@@ -1297,10 +1446,11 @@ openviking unlink viking://resources/docs/auth/ viking://resources/docs/security| uri | string | 是 | - | 要导出的 Viking URI || include_vectors | boolean | 否 | false | 导出纯 dense 向量快照;底层 index type 为 hybrid 时会拒绝 |-**权限要求**:ROOT 或 ADMIN+**权限要求**:ROOT、ADMIN 或 USER#### 3. 使用示例+**HTTP API**```@@ -1331,6 +1481,17 @@ client.initialize()# 注意:导出功能主要通过 CLI 使用```+**TypeScript SDK**++```typescript+const outputPath = await client.exportOVPack(+ "viking://resources/docs/",+ "./exports/docs.ovpack",+ true,+);+console.log(outputPath);+```+**Go SDK**```go@@ -1356,6 +1517,7 @@ ov export viking://resources/my-project/ ./exports/my-project.ovpackov export viking://resources/my-project/ ./exports/my-project.ovpack --include-vectors```+**响应示例**此接口直接返回文件流(`Content-Type: application/zip`),不返回 JSON 包装体。@@ -1368,7 +1530,7 @@ ov export viking://resources/my-project/ ./exports/my-project.ovpack --include-v#### 1. API 实现介绍-将 `.ovpack` 文件导入到指定位置,用于恢复或迁移数据。需要 ROOT 或 ADMIN 权限。+将 `.ovpack` 文件导入到指定位置,用于恢复或迁移数据。ROOT、ADMIN 和 USER 角色均可使用,仍受常规 URI 访问控制约束。**处理流程**:1. 验证用户权限@@ -1393,7 +1555,7 @@ ov export viking://resources/my-project/ ./exports/my-project.ovpack --include-v| on_conflict | string | 否 | fail | 冲突策略:`fail`、`overwrite` 或 `skip` || vector_mode | string | 否 | auto | 向量处理方式:`auto`、`recompute` 或 `require` |-**权限要求**:ROOT 或 ADMIN+**权限要求**:ROOT、ADMIN 或 USER**行为说明**:- API 已不再接受 `vectorize` 或 `force`。@@ -1412,6 +1574,7 @@ ov export viking://resources/my-project/ ./exports/my-project.ovpack --include-v#### 3. 使用示例+**HTTP API**```@@ -1452,6 +1615,20 @@ client.initialize()# 注意:导入功能主要通过 CLI 使用```+**TypeScript SDK**++```typescript+const uri = await client.importOVPack(+ "./exports/docs.ovpack",+ "viking://resources/",+ {+ onConflict: "overwrite",+ vectorMode: "auto",+ },+);+console.log(uri);+```+**Go SDK**```go@@ -1483,6 +1660,7 @@ ov import ./exports/my-project.ovpack viking://resources/imported/ --on-conflictov import ./exports/my-project.ovpack viking://resources/imported/ --vector-mode require```+**响应示例**```jsondiff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.mdindex 14dd17968..f71c2012f 100644--- a/docs/zh/api/04-skills.md+++ b/docs/zh/api/04-skills.md@@ -199,6 +199,12 @@ This tool wraps the MCP tool `search-web`. Call this when the user needs functio#### 3. 使用示例+**TypeScript SDK**++```typescript+await client.addSkill("./my-skill", { wait: true });+```+**HTTP API**:```@@ -441,6 +447,13 @@ for skill in skills["skills"]:print(skill["name"])```+**TypeScript SDK**++```typescript+const skills = await client.listSkills();+console.log(skills);+```+**Go SDK**:```go@@ -465,6 +478,13 @@ print(skill["name"])print(skill.get("content"))```+**TypeScript SDK**++```typescript+const skill = await client.getSkill("my-skill");+console.log(skill);+```+**Go SDK**:```go@@ -493,6 +513,13 @@ for skill in results["skills"]:print(skill["name"], skill["score"])```+**TypeScript SDK**++```typescript+const skills = await client.findSkills("database migration");+console.log(skills);+```+**Go SDK**:```go@@ -523,6 +550,17 @@ validated = client.validate_skill({"name": "search-web", "description": "..."})updated = client.update_skill("search-web", "./skills/search-web", wait=True)```+**TypeScript SDK**++```typescript+const result = await client.validateSkill({+ name: "search-web",+ description: "Search the web for current information",+ content: "# search-web\n\nSearch the web for current information.",+});+console.log(result);+```+**Go SDK**:```go@@ -553,6 +591,12 @@ curl -X POST http://localhost:1933/api/v1/skills/validate \client.delete_skill("old-skill")```+**TypeScript SDK**++```typescript+await client.deleteSkill("my-skill");+```+**Go SDK**:```godiff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 14232098d..b04709468 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -82,6 +82,13 @@ result = await client.create_session(session_id="my-custom-session-id")print(f"Session ID: {result['session_id']}")```+**TypeScript SDK**++```typescript+const session = await client.createSession();+console.log(session);+```+**Go SDK**```go@@ -161,6 +168,12 @@ for s in sessions:print(f"{s['session_id']} -> {s['uri']}")```+**TypeScript SDK**++```typescript+console.log(await client.listSessions());+```+**Go SDK**```go@@ -260,6 +273,12 @@ print(f"Commits: {info['commit_count']}")info = await client.get_session("a1b2c3d4", auto_create=True)```+**TypeScript SDK**++```typescript+console.log(await client.getSession("session-id"));+```+**Go SDK**```go@@ -386,6 +405,12 @@ print(context["latest_archive_overview"])print(len(context["messages"]))```+**TypeScript SDK**++```typescript+console.log(await client.getSessionContext("session-id"));+```+**Go SDK**```go@@ -490,6 +515,12 @@ print(archive["overview"])print(len(archive["messages"]))```+**TypeScript SDK**++```typescript+console.log(await client.getSessionArchive("session-id", "archive-id"));+```+**Go SDK**```go@@ -596,6 +627,12 @@ client = ov.Client(base_url="http://localhost:1933", api_key="your-key")await client.delete_session("a1b2c3d4")```+**TypeScript SDK**++```typescript+await client.deleteSession("session-id");+```+**Go SDK**```go@@ -765,6 +802,12 @@ await client.add_message()```+**TypeScript SDK**++```typescript+await client.addMessage("session-id", { role: "user", content: "Hello" });+```+**Go SDK**```go@@ -868,6 +911,15 @@ result = await client.batch_add_messages(print(f"Added: {result['added']}, Total: {result['message_count']}")```+**TypeScript SDK**++```typescript+await client.batchAddMessages("session-id", [+ { role: "user", content: "Hello" },+ { role: "assistant", content: "Hi" },+]);+```+**Go SDK**```go@@ -1037,6 +1089,12 @@ if task["status"] == "completed":print(f"Memories extracted: {total}")```+**TypeScript SDK**++```typescript+console.log(await client.commitSession("session-id"));+```+**Go SDK**```go@@ -1181,6 +1239,12 @@ task = await client.get_task(task_id="uuid-xxx")print(f"Status: {task['status']}")```+**TypeScript SDK**++```typescript+console.log(await client.getTask("task-id"));+```+**Go SDK**```go@@ -1300,6 +1364,12 @@ for task in tasks:print(task["task_id"], task["status"])```+**TypeScript SDK**++```typescript+console.log(await client.listTasks());+```+**Go SDK**```godiff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex affc8a8c1..f81aa6b58 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -242,6 +242,12 @@ results = client.find()```+**TypeScript SDK**++```typescript+console.log(await client.find("authentication", { targetUri: "viking://resources/docs/" }));+```+**Go SDK**```go@@ -477,6 +483,12 @@ for ctx in results.resources:results = client.search("similar poster", image="/path/to/poster.png")```+**TypeScript SDK**++```typescript+console.log(await client.search("authentication", { targetUri: "viking://resources/docs/" }));+```+**Go SDK**```go@@ -633,6 +645,12 @@ for match in results['matches']:print(f" {match['content']}")```+**TypeScript SDK**++```typescript+console.log(await client.grep("viking://resources/docs/", "authentication"));+```+**Go SDK**```go@@ -747,6 +765,12 @@ results = client.glob("**/*.py", "viking://resources", node_limit=1024)print(f"Found {results['count']} Python files")```+**TypeScript SDK**++```typescript+console.log(await client.glob("**/*.md", "viking://resources/docs/"));+```+**Go SDK**```godiff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex aef1b2e82..97e921082 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -66,6 +66,12 @@ healthy = client.health()print(f"Healthy: {healthy}")```+**TypeScript SDK**++```typescript+console.log(await client.health());+```+**Go SDK**```go@@ -202,6 +208,12 @@ status = client.get_status()print(status)```+**TypeScript SDK**++```typescript+console.log(await client.getStatus());+```+**CLI**```bash@@ -266,6 +278,12 @@ print(report["ok"])print(report["missing_records"])```+**TypeScript SDK**++```typescript+console.log(await client.checkConsistency("viking://resources/"));+```+**Go SDK**```go@@ -353,6 +371,12 @@ status = client.wait_processed(timeout=60.0)print(f"Processing complete: {status}")```+**TypeScript SDK**++```typescript+console.log(await client.waitProcessed(60));+```+**Go SDK**```go@@ -462,6 +486,12 @@ result = client.reindex(print(result["status"])```+**TypeScript SDK**++```typescript+console.log(await client.reindex("viking://resources/docs/"));+```+**Go SDK**```go@@ -635,6 +665,12 @@ print(client.observer.queue)# TOTAL 0 0 20 0 20```+**TypeScript SDK**++```typescript+console.log(await client.queueStatus());+```+**Go SDK**```go@@ -712,6 +748,12 @@ print(client.observer.vikingdb().is_healthy) # Trueprint(client.observer.vikingdb().status) # 状态表字符串```+**TypeScript SDK**++```typescript+console.log(await client.vikingDBStatus());+```+**Go SDK**```go@@ -786,6 +828,12 @@ print(client.observer.models)# vlm yes ...```+**TypeScript SDK**++```typescript+console.log(await client.modelsStatus());+```+**Go SDK**```godiff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 5076c4de5..d73a66d9b 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -180,6 +180,12 @@ result = client.admin_create_account()```+**TypeScript SDK**++```typescript+console.log(await client.adminCreateAccount("account-id", "admin-user-id"));+```+**Go SDK**```go@@ -274,6 +280,12 @@ for account in accounts:print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")```+**TypeScript SDK**++```typescript+console.log(await client.adminListAccounts());+```+**Go SDK**```go@@ -360,6 +372,12 @@ result = client.admin_delete_account("acme")print(f"Account deleted: {result['deleted']}")```+**TypeScript SDK**++```typescript+await client.adminDeleteAccount("account-id");+```+**Go SDK**```go@@ -468,6 +486,12 @@ result = client.admin_register_user()```+**TypeScript SDK**++```typescript+console.log(await client.adminRegisterUser("account-id", "user-id", "user"));+```+**Go SDK**```go@@ -579,6 +603,12 @@ for user in users:print(f"User: {user['user_id']}, role: {user['role']}")```+**TypeScript SDK**++```typescript+console.log(await client.adminListUsers("account-id"));+```+**Go SDK**```go@@ -668,6 +698,12 @@ result = client.admin_remove_user("acme", "bob")print(f"User deleted: {result['deleted']}")```+**TypeScript SDK**++```typescript+await client.adminRemoveUser("account-id", "user-id");+```+**Go SDK**```go@@ -759,6 +795,12 @@ result = client.admin_set_role("acme", "bob", "admin")print(f"User: {result['user_id']}, new role: {result['role']}")```+**TypeScript SDK**++```typescript+await client.adminSetRole("account-id", "user-id", "admin");+```+**Go SDK**```go@@ -851,6 +893,12 @@ result = client.admin_regenerate_key("acme", "bob", seed="bob-new-seed")print(f"New user key: {result['user_key']}")```+**TypeScript SDK**++```typescript+console.log(await client.adminRegenerateKey("account-id", "user-id"));+```+**Go SDK**```go@@ -944,24 +992,34 @@ POST /api/v1/admin/migrate#### 3. 使用示例-**执行迁移**+**HTTP API**```bash+# 执行迁移curl -X POST http://localhost:1933/api/v1/admin/migrate \-H "Content-Type: application/json" \-H "X-API-Key: <root-key>" \-d '{"action": "migrate"}'-```--**清理旧 namespace**-```bash+# 清理旧 namespacecurl -X POST http://localhost:1933/api/v1/admin/migrate \-H "Content-Type: application/json" \-H "X-API-Key: <root-key>" \-d '{"action": "cleanup"}'```+**Python SDK**++```python+print(client.admin_migrate(cleanup=False))+```++**TypeScript SDK**++```typescript+console.log(await client.adminMigrate(false));+```+**Go SDK**```godiff --git a/docs/zh/api/11-snapshot.md b/docs/zh/api/11-snapshot.mdindex fea142838..f15675d11 100644--- a/docs/zh/api/11-snapshot.md+++ b/docs/zh/api/11-snapshot.md@@ -55,6 +55,12 @@ result = client.snapshot.commit(print(result["commit_oid"])```+**TypeScript SDK**++```typescript+console.log(await client.gitCommit({ message: "Update docs", paths: ["resources/docs"] }));+```+**HTTP API**```@@ -127,6 +133,12 @@ for commit in history:print(commit["oid"], commit["message"])```+**TypeScript SDK**++```typescript+console.log(await client.gitLog("main", 20));+```+**HTTP API**```@@ -200,6 +212,12 @@ print(meta["message"], meta["parents"])blob = client.snapshot.show("3f2a1b9c", path="viking://resources/my_project/guide.md")```+**TypeScript SDK**++```typescript+console.log(await client.gitShow("main", "viking://resources/docs/api.md"));+```+> 注意:带 `path` 读取文件内容时,**Embedded(本地)客户端**直接返回原始 `bytes`;**HTTP 客户端**返回 `{"oid": str, "size": int, "bytes": bytes}` 字典。**HTTP API**@@ -298,6 +316,15 @@ plan = client.snapshot.restore(print(plan["diff"])```+**TypeScript SDK**++```typescript+console.log(await client.gitRestore({+ projectDir: "viking://resources/docs",+ sourceCommit: "3f2a1b9c",+}));+```+**HTTP API**```@@ -404,6 +431,12 @@ ov snapshot restore 3f2a1b9c viking://resources/my_project --dry-run -o jsoncontent = client.snapshot.get_gitignore()```+**TypeScript SDK**++```typescript+console.log(await client.gitGetIgnore());+```+**HTTP API**```@@ -448,6 +481,12 @@ ov snapshot ignore-get -o jsonclient.snapshot.set_gitignore(content="*.log\n")```+**TypeScript SDK**++```typescript+await client.gitSetIgnore("*.tmp\n.cache/\n");+```+**HTTP API**```@@ -488,6 +527,12 @@ ov snapshot ignore-set --file ./my-rules -o jsonclient.snapshot.delete_gitignore()```+**TypeScript SDK**++```typescript+await client.gitDeleteIgnore();+```+**HTTP API**```diff --git a/docs/zh/api/99-api-doc-writing-guide.md b/docs/zh/api/99-api-doc-writing-guide.mdindex 545938ad9..0c4eef8ac 100644--- a/docs/zh/api/99-api-doc-writing-guide.md+++ b/docs/zh/api/99-api-doc-writing-guide.md@@ -47,19 +47,15 @@ API 文档按模块组织,每个模块一个文件,使用两位数字序号#### 3. 使用示例-**HTTP API**--```-<HTTP 方法> <路径>-```+**Python SDK**-```bash-<curl 示例>+```python+<SDK 调用示例>```-**Python SDK**+**TypeScript SDK**-```python+```typescript<SDK 调用示例>```@@ -69,6 +65,16 @@ API 文档按模块组织,每个模块一个文件,使用两位数字序号<SDK 调用示例>```+**HTTP API**++```+<HTTP 方法> <路径>+```++```bash+<curl 示例>+```+**CLI**```bash@@ -127,13 +133,17 @@ API 文档按模块组织,每个模块一个文件,使用两位数字序号#### 3. 使用示例-按顺序提供:-- HTTP API(方法 + 路径 + curl 示例)+当一个接口并列展示所有调用方式时,建议按以下顺序提供:- Python SDK 示例+- TypeScript SDK 示例- Go SDK 示例(当它能补充说明该接口的调用形态,且可以保持简短时)+- HTTP API(方法 + 路径 + curl 示例)- CLI 示例- 响应示例+如果现有接口因工作流说明采用了特殊结构,应保持该局部结构稳定,并将 TypeScript 放在其他+SDK 示例附近。+API 文档应按 API 模块和具体接口组织,而不是按客户端语言组织。SDK 片段只作为对应接口“使用示例”中的简短调用示例出现。语言专属 quick reference、完整 walkthrough 或跨接口串联流程应放在该 SDK 自己的文档中,不应新增到 API 模块页面里。