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
feat(sdk): 支持 Go HTTP SDK (#2680)
Qin Haojiea59fd048f139
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex 39920e3a3..26ff18b1f 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -74,6 +74,42 @@ client = ov.SyncHTTPClient(client.initialize()```+#### Go SDK Client++The Go SDK is an HTTP-only client for Client-Server mode. It is published from+the main repository as the `sdk/go` module.++```bash+go get github.com/volcengine/OpenViking/sdk/go+```++```go+client, err := openviking.NewClient(openviking.Config{+ BaseURL: "http://localhost:1933",+ APIKey: "your-key",+})+if err != nil {+ return err+}+defer client.CloseIdleConnections()+```++The Go SDK sends the same identity headers as the Python HTTP client:++| Config field | HTTP header |+|--------------|-------------|+| `APIKey` | `X-API-Key` |+| `Account` | `X-OpenViking-Account` |+| `User` | `X-OpenViking-User` |+| `ActorPeerID` | `X-OpenViking-Actor-Peer` |++For normal `api_key` deployments, `APIKey` is enough because the server derives+tenant identity from the key. Set `Account` and `User` only for trusted+deployments or gateways that explicitly forward tenant identity.++It does not implement Python embedded mode or legacy `agent_id` compatibility.+See [`sdk/go/README.md`](../../../sdk/go/README.md) for package-level examples.+When `url` is not explicitly provided, the HTTP client automatically reads connection information from `ovcli.conf`. `ovcli.conf` is a configuration file shared between the HTTP client and CLI. Default path: `~/.openviking/ovcli.conf`. You can also specify the path via environment variable:```bash@@ -353,7 +389,31 @@ Below are all HTTP API endpoints provided by OpenViking, grouped by functional m|--------|------|-------------|| POST | `/api/v1/resources/temp_upload` | Upload local file for raw HTTP resource / pack import || POST | `/api/v1/resources` | Add resource (supports URL or temp_file_id) |++### Skills++| Method | Path | Description |+|--------|------|-------------|+| GET | `/api/v1/skills` | List installed skills || POST | `/api/v1/skills` | Add skill |+| POST | `/api/v1/skills/find` | Search installed skills |+| POST | `/api/v1/skills/validate` | Validate skill payload |+| GET | `/api/v1/skills/{skill_name}` | Get skill |+| PUT | `/api/v1/skills/{skill_name}` | Update skill |+| DELETE | `/api/v1/skills/{skill_name}` | Delete skill |++### Watches++| Method | Path | Description |+|--------|------|-------------|+| GET | `/api/v1/watches` | List watches or get one by `to_uri` |+| GET | `/api/v1/watches/{task_id}` | Get watch |+| PATCH | `/api/v1/watches` | Update watch by `to_uri` |+| PATCH | `/api/v1/watches/{task_id}` | Update watch by task ID |+| DELETE | `/api/v1/watches` | Delete watch by `to_uri` |+| DELETE | `/api/v1/watches/{task_id}` | Delete watch by task ID |+| POST | `/api/v1/watches/trigger` | Trigger watch by `to_uri` |+| POST | `/api/v1/watches/{task_id}/trigger` | Trigger watch by task ID |### Packdiff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.mdindex e890bc389..127a42d8b 100644--- a/docs/en/api/02-resources.md+++ b/docs/en/api/02-resources.md@@ -316,6 +316,19 @@ client.add_resource()```+**Go SDK**++```go+result, err := client.AddResource(ctx, "./documents/guide.md", &openviking.AddResourceOptions{+ Reason: "User guide documentation",+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["root_uri"])+```+**CLI**```bash@@ -508,6 +521,34 @@ curl -X DELETE "http://localhost:1933/api/v1/watches?to_uri=viking://resources/g-H "X-API-Key: your-key"```+**Python SDK**++```python+watches = client.list_watches(active_only=True)+client.update_watch(to_uri="viking://resources/guide.md", is_active=False)+client.trigger_watch(to_uri="viking://resources/guide.md")+client.delete_watch(to_uri="viking://resources/guide.md")+```++**Go SDK**++```go+watches, err := client.ListWatches(ctx, &openviking.ListWatchesOptions{+ ActiveOnly: true,+})+updated, err := client.UpdateWatch(ctx, openviking.UpdateWatchOptions{+ ToURI: "viking://resources/guide.md",+ IsActive: openviking.Bool(false),+})+triggered, err := client.TriggerWatch(ctx, openviking.WatchRef{+ ToURI: "viking://resources/guide.md",+})+deleted, err := client.DeleteWatch(ctx, openviking.WatchRef{+ ToURI: "viking://resources/guide.md",+})+_, _, _, _ = watches, updated, triggered, deleted+```+**CLI** (subcommands of `ov task watch`)```bash@@ -633,6 +674,18 @@ result = client.add_skill("./skills/my-skill.json")client.wait_processed()```+**Go SDK**++```go+result, err := client.AddSkill(ctx, "./skills/my-skill.json", &openviking.AddSkillOptions{+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["uri"])+```+**CLI**```bash@@ -768,6 +821,12 @@ curl -X POST http://localhost:1933/api/v1/resources/temp_upload \The `add_resource`, `add_skill` and other endpoints in the Python SDK automatically handle local file uploads, no need to call this endpoint manually. To opt into distributed shared temporary uploads in HTTP client mode, set `upload.mode` to `"shared"` in `ovcli.conf`.+**Go SDK**++`client.AddResource`, `client.AddSkill`, `client.ImportOVPack`, and+`client.RestoreOVPack` automatically call `temp_upload` for local files. Set+`openviking.Config{UploadMode: "shared"}` to request shared temporary uploads.+**CLI**CLI commands also automatically handle local file uploads, no need to call this endpoint manually.diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.mdindex 535a6597d..8ae142a49 100644--- a/docs/en/api/04-skills.md+++ b/docs/en/api/04-skills.md@@ -321,6 +321,18 @@ result = client.add_skill("./skills/my-skill/", wait=True)client.wait_processed()```+**Go SDK**++```go+result, err := client.AddSkill(ctx, "./skills/my-skill/", &openviking.AddSkillOptions{+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["uri"])+```+**CLI**```bash@@ -414,61 +426,60 @@ The Python HTTP SDK raises the corresponding mapped exception for this response.## Skill Management Operations+The Python HTTP SDK and Go SDK expose dedicated skill management methods:+`list_skills`, `find_skills`, `validate_skill`, `get_skill`, `update_skill`,+and `delete_skill` in Python; `ListSkills`, `FindSkills`, `ValidateSkill`,+`GetSkill`, `UpdateSkill`, and `DeleteSkill` in Go. The general+filesystem/content/retrieval methods still work for URI-level access.+### List Skills**Python SDK**```python-# List all skills-skills = client.ls("viking://user/skills/")-for skill in skills:- print(f"{skill['name']}")+skills = client.list_skills(node_limit=1000)+for skill in skills["skills"]:+ print(skill["name"])+```-# Simple list (names only-names = client.ls("viking://user/skills/", simple=True)-print(names)+**Go SDK**++```go+skills, err := client.ListSkills(ctx, nil)+_ = skills```**HTTP API**```bash-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://user/skills/" \+curl -X GET "http://localhost:1933/api/v1/skills?node_limit=1000" \-H "X-API-Key: your-key"```-### Read Skill Content+### Read Skill**Python SDK**```python-uri = "viking://user/skills/search-web/"--# L0: Brief description-abstract = client.abstract(uri)-print(f"Abstract: {abstract}")+skill = client.get_skill("search-web", include_content=True, include_files=True)+print(skill["name"])+print(skill.get("content"))+```-# L1: Parameters and usage overview-overview = client.overview(uri)-print(f"Overview: {overview}")+**Go SDK**-# L2: Full skill documentation-content = client.read(uri)-print(f"Content: {content}")+```go+skill, err := client.GetSkill(ctx, "search-web", &openviking.GetSkillOptions{+ IncludeContent: openviking.Bool(true),+ IncludeFiles: openviking.Bool(true),+})+_ = skill```**HTTP API**```bash-# L0: Brief description-curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://user/skills/search-web/" \- -H "X-API-Key: your-key"--# L1: Parameters and usage overview-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://user/skills/search-web/" \- -H "X-API-Key: your-key"--# L2: Full skill documentation-curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://user/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/skills/search-web?include_content=true&include_files=true" \-H "X-API-Key: your-key"```@@ -477,44 +488,83 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://user/skills/**Python SDK**```python-# Semantic search for skills-results = client.find(- "search the internet",- target_uri="viking://user/skills/",- limit=5-)+results = client.find_skills("search the internet", limit=5)-for ctx in results.skills:- print(f"Skill: {ctx.uri}")- print(f"Score: {ctx.score:.3f}")- print(f"Description: {ctx.abstract}")+for skill in results["skills"]:+ print(skill["name"], skill["score"])+```++**Go SDK**++```go+results, err := client.FindSkills(ctx, "search the internet", &openviking.FindSkillsOptions{+ Limit: 5,+})+_ = results```**HTTP API**```bash-curl -X POST http://localhost:1933/api/v1/search/find \+curl -X POST http://localhost:1933/api/v1/skills/find \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"query": "search the internet",- "target_uri": "viking://user/skills/","limit": 5}'```+### Validate and Update Skills++**Python SDK**++```python+validated = client.validate_skill({"name": "search-web", "description": "..."})+updated = client.update_skill("search-web", "./skills/search-web", wait=True)+```++**Go SDK**++```go+validated, err := client.ValidateSkill(ctx, map[string]any{+ "name": "search-web",+ "description": "...",+}, nil)+updated, err := client.UpdateSkill(ctx, "search-web", "./skills/search-web", &openviking.UpdateSkillOptions{+ Wait: true,+})+_, _ = validated, updated+```++**HTTP API**++```bash+curl -X POST http://localhost:1933/api/v1/skills/validate \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{"data": {"name": "search-web", "description": "..."}}'+```+### Delete Skills**Python SDK**```python-client.rm("viking://user/skills/old-skill/", recursive=True)+client.delete_skill("old-skill")+```++**Go SDK**++```go+deleted, err := client.DeleteSkill(ctx, "old-skill")+_ = deleted```**HTTP API**```bash-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://user/skills/old-skill/&recursive=true" \+curl -X DELETE "http://localhost:1933/api/v1/skills/old-skill" \-H "X-API-Key: your-key"```diff --git a/docs/en/api/05-sessions.md b/docs/en/api/05-sessions.mdindex 10ac3f29c..7837639da 100644--- a/docs/en/api/05-sessions.md+++ b/docs/en/api/05-sessions.md@@ -82,6 +82,18 @@ result = await client.create_session(session_id="my-custom-session-id")print(f"Session ID: {result['session_id']}")```+**Go SDK**++```go+session, err := client.CreateSession(ctx, &openviking.CreateSessionOptions{+ SessionID: "my-custom-session-id",+})+if err != nil {+ return err+}+fmt.Println(session["session_id"])+```+**CLI**```bash@@ -149,6 +161,18 @@ for s in sessions:print(f"{s['session_id']} -> {s['uri']}")```+**Go SDK**++```go+sessions, err := client.ListSessions(ctx)+if err != nil {+ return err+}+for _, session := range sessions {+ fmt.Println(session)+}+```+**CLI**```bash@@ -236,6 +260,26 @@ print(f"Commits: {info['commit_count']}")info = await client.get_session("a1b2c3d4", auto_create=True)```+**Go SDK**++```go+// Get an existing session.+info, err := client.GetSession(ctx, "a1b2c3d4", nil)+if err != nil {+ return err+}+fmt.Println(info["message_count"])++// Get or create session.+info, err = client.GetSession(ctx, "a1b2c3d4", &openviking.GetSessionOptions{+ AutoCreate: true,+})+if err != nil {+ return err+}+fmt.Println(info["session_id"])+```+**CLI**```bash@@ -342,6 +386,16 @@ print(context["latest_archive_overview"])print(len(context["messages"]))```+**Go SDK**++```go+contextPayload, err := client.GetSessionContext(ctx, "a1b2c3d4", 128000)+if err != nil {+ return err+}+fmt.Println(contextPayload["latest_archive_overview"])+```+**CLI**```bash@@ -436,6 +490,16 @@ print(archive["overview"])print(len(archive["messages"]))```+**Go SDK**++```go+archive, err := client.GetSessionArchive(ctx, "a1b2c3d4", "archive_002")+if err != nil {+ return err+}+fmt.Println(archive["archive_id"])+```+**CLI**```bash@@ -532,6 +596,14 @@ client = ov.Client(base_url="http://localhost:1933", api_key="your-key")await client.delete_session("a1b2c3d4")```+**Go SDK**++```go+if err := client.DeleteSession(ctx, "a1b2c3d4"); err != nil {+ return err+}+```+**CLI**```bash@@ -719,6 +791,19 @@ await client.add_message()```+**Go SDK**++```go+result, err := client.AddMessage(ctx, "a1b2c3d4", "user", openviking.AddMessageOptions{+ Content: openviking.String("How do I authenticate users?"),+ PeerID: "web-visitor-alice",+})+if err != nil {+ return err+}+fmt.Println(result["message_count"])+```+**CLI**```bash@@ -809,6 +894,20 @@ result = await client.batch_add_messages(print(f"Added: {result['added']}, Total: {result['message_count']}")```+**Go SDK**++```go+result, err := client.BatchAddMessages(ctx, "a1b2c3d4", []openviking.Message{+ {Role: "user", Content: openviking.String("How do I authenticate users?")},+ {Role: "assistant", Content: openviking.String("You can use OAuth 2.0 for authentication.")},+ {Role: "user", Content: openviking.String("Any specific recommendations?")},+}, nil)+if err != nil {+ return err+}+fmt.Println(result["added"], result["message_count"])+```+**CLI**```bash@@ -877,31 +976,6 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \-d '{"skill": {"uri": "viking://user/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'```-**Python SDK**--```python-import openviking as ov--client = ov.Client(base_url="http://localhost:1933", api_key="your-key")--# Record used contexts-await client.session_used(- session_id="a1b2c3d4",- contexts=["viking://resources/docs/auth/"]-)--# Record used skill-await client.session_used(- session_id="a1b2c3d4",- skill={- "uri": "viking://user/skills/search-web/",- "input": {"query": "OAuth"},- "output": "Results...",- "success": True- }-)-```-**Response Example**```json@@ -988,6 +1062,25 @@ if task["status"] == "completed":print(f"Memories extracted: {total}")```+**Go SDK**++```go+commit, err := client.CommitSession(ctx, "a1b2c3d4", &openviking.CommitSessionOptions{+ KeepRecentCount: 0,+})+if err != nil {+ return err+}+fmt.Println(commit["status"], commit["task_id"])++taskID, _ := commit["task_id"].(string)+task, err := client.GetTask(ctx, taskID)+if err != nil {+ return err+}+fmt.Println(task["status"])+```+**CLI**```bash@@ -1015,7 +1108,7 @@ ov session commit a1b2c3d4#### 1. API Implementation Introduction-HTTP API only. Trigger memory extraction immediately for an existing session without creating a new commit task.+Trigger memory extraction immediately for an existing session without creating a new commit task.**Code Entries:**- `openviking/server/routers/sessions.py:extract_session()` - HTTP route@@ -1097,6 +1190,18 @@ task = await client.get_task(task_id="uuid-xxx")print(f"Status: {task['status']}")```+**Go SDK**++```go+task, err := client.GetTask(ctx, "uuid-xxx")+if err != nil {+ return err+}+if task != nil {+ fmt.Println(task["status"])+}+```+**Response Example (resource import in progress)**```json@@ -1159,10 +1264,11 @@ print(f"Status: {task['status']}")#### 1. API Implementation Introduction-HTTP API only. List background tasks visible to the current caller, supporting filtering by type, status, resource.+List background tasks visible to the current caller, supporting filtering by type, status, resource.**Code Entries:**- `openviking/server/routers/tasks.py:list_tasks()` - HTTP route+- `openviking_cli/client/base.py:BaseClient.list_tasks()` - Python SDK#### 2. Interface and Parameter Description@@ -1188,6 +1294,38 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++tasks = await client.list_tasks(+ task_type="session_commit",+ status="running",+ limit=20,+)+for task in tasks:+ print(task["task_id"], task["status"])+```++**Go SDK**++```go+tasks, err := client.ListTasks(ctx, &openviking.ListTasksOptions{+ TaskType: "session_commit",+ Status: "running",+ Limit: 20,+})+if err != nil {+ return err+}+for _, task := range tasks {+ fmt.Println(task)+}+```+**Response Example**```json@@ -1357,13 +1495,6 @@ if results.resources:)])-- # Track actually used contexts- await client.session_used(- session_id=session_id,- contexts=[results.resources[0].uri]- )-# Commit session (returns immediately; summary + memory extraction runs in background)commit_result = await client.commit_session(session_id)print(f"Task ID: {commit_result['task_id']}")@@ -1431,14 +1562,6 @@ if session_info["message_count"] > 10:await client.commit_session(session_id)```-### Track What's Actually Used--```python-# Only mark contexts that were actually helpful-if context_was_useful:- await client.session_used(session_id=session_id, contexts=[ctx.uri])-```-### Use Session Context for Search```pythondiff --git a/docs/en/api/06-retrieval.md b/docs/en/api/06-retrieval.mdindex fac4cde6d..a38647dc5 100644--- a/docs/en/api/06-retrieval.md+++ b/docs/en/api/06-retrieval.md@@ -220,6 +220,22 @@ results = client.find()```+**Go SDK**++```go+result, err := client.Find(ctx, "how to authenticate users", &openviking.FindOptions{+ TargetURI: "viking://resources/docs",+ Limit: 10,+ ContextType: []string{"resource"},+})+if err != nil {+ return err+}+for _, item := range result.Resources {+ fmt.Println(item.URI, item.Score)+}+```+**CLI**```bash@@ -406,6 +422,20 @@ for ctx in results.resources:print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")```+**Go SDK**++```go+result, err := client.Search(ctx, "best practices", &openviking.SearchOptions{+ SessionID: "abc123",+ ContextType: "skill",+ Limit: 10,+})+if err != nil {+ return err+}+fmt.Println(result.Total)+```+**CLI**```bash@@ -544,6 +574,18 @@ for match in results['matches']:print(f" {match['content']}")```+**Go SDK**++```go+result, err := client.Grep(ctx, "viking://resources", "authentication", &openviking.GrepOptions{+ CaseInsensitive: true,+})+if err != nil {+ return err+}+fmt.Println(result["count"])+```+**CLI**```bash@@ -644,6 +686,16 @@ results = client.glob("**/*.py", "viking://resources")print(f"Found {results['count']} Python files")```+**Go SDK**++```go+result, err := client.Glob(ctx, "**/*.md", "viking://resources")+if err != nil {+ return err+}+fmt.Println(result["count"])+```+**CLI**```bashdiff --git a/docs/en/api/07-system.md b/docs/en/api/07-system.mdindex 87f6ada38..ba84b90b5 100644--- a/docs/en/api/07-system.md+++ b/docs/en/api/07-system.md@@ -66,6 +66,16 @@ healthy = client.health()print(f"Healthy: {healthy}")```+**Go SDK**++```go+healthy, err := client.Health(ctx)+if err != nil {+ return err+}+fmt.Println(healthy)+```+**CLI**```bash@@ -262,6 +272,16 @@ print(report["ok"])print(report["missing_records"])```+**Go SDK**++```go+report, err := client.CheckConsistency(ctx, "viking://resources/my-project")+if err != nil {+ return err+}+fmt.Println(report["ok"])+```+**CLI**```bash@@ -339,6 +359,18 @@ status = client.wait_processed(timeout=60.0)print(f"Processing complete: {status}")```+**Go SDK**++```go+status, err := client.WaitProcessed(ctx, &openviking.WaitProcessedOptions{+ Timeout: openviking.Float64(60),+})+if err != nil {+ return err+}+fmt.Println(status)+```+**CLI**```bash@@ -436,6 +468,19 @@ result = client.reindex(print(result["status"])```+**Go SDK**++```go+result, err := client.Reindex(ctx, "viking://resources", &openviking.ReindexOptions{+ Mode: "vectors_only",+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["status"])+```+**HTTP API**```@@ -597,6 +642,16 @@ print(client.observer.queue)# TOTAL 0 0 20 0 20```+**Go SDK**++```go+status, err := client.QueueStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bash@@ -664,6 +719,16 @@ print(client.observer.vikingdb().is_healthy) # Trueprint(client.observer.vikingdb().status) # Status table string```+**Go SDK**++```go+status, err := client.VikingDBStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bash@@ -728,6 +793,16 @@ print(client.observer.models)# vlm yes ...```+**Go SDK**++```go+status, err := client.ModelsStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bash@@ -970,6 +1045,16 @@ print(client.observer.system())# [system] (healthy)```+**Go SDK**++```go+status, err := client.GetStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bashdiff --git a/docs/en/api/08-admin.md b/docs/en/api/08-admin.mdindex ec842ce64..515b68d3e 100644--- a/docs/en/api/08-admin.md+++ b/docs/en/api/08-admin.md@@ -162,6 +162,16 @@ print(f"Admin user: {result['admin_user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")```+**Go SDK**++```go+result, err := client.AdminCreateAccount(ctx, "acme", "alice")+if err != nil {+ return err+}+fmt.Println(result["account_id"])+```+**CLI**```bash@@ -233,6 +243,16 @@ for account in accounts:print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")```+**Go SDK**++```go+accounts, err := client.AdminListAccounts(ctx)+if err != nil {+ return err+}+fmt.Println(accounts)+```+**CLI**```bash@@ -309,6 +329,16 @@ result = client.admin_delete_account("acme")print(f"Account deleted: {result['deleted']}")```+**Go SDK**++```go+result, err := client.AdminDeleteAccount(ctx, "acme")+if err != nil {+ return err+}+fmt.Println(result["deleted"])+```+**CLI**```bash@@ -393,6 +423,16 @@ print(f"User registered: {result['user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")```+**Go SDK**++```go+result, err := client.AdminRegisterUser(ctx, "acme", "bob", "user")+if err != nil {+ return err+}+fmt.Println(result["user_id"])+```+**CLI**```bash@@ -482,6 +522,16 @@ for user in users:print(f"User: {user['user_id']}, role: {user['role']}")```+**Go SDK**++```go+users, err := client.AdminListUsers(ctx, "acme")+if err != nil {+ return err+}+fmt.Println(users)+```+**CLI**```bash@@ -562,6 +612,16 @@ result = client.admin_remove_user("acme", "bob")print(f"User deleted: {result['deleted']}")```+**Go SDK**++```go+result, err := client.AdminRemoveUser(ctx, "acme", "bob")+if err != nil {+ return err+}+fmt.Println(result["deleted"])+```+**CLI**```bash@@ -643,6 +703,16 @@ result = client.admin_set_role("acme", "bob", "admin")print(f"User: {result['user_id']}, new role: {result['role']}")```+**Go SDK**++```go+result, err := client.AdminSetRole(ctx, "acme", "bob", "admin")+if err != nil {+ return err+}+fmt.Println(result["role"])+```+**CLI**```bash@@ -722,6 +792,16 @@ result = client.admin_regenerate_key("acme", "bob")print(f"New user key: {result['user_key']}")```+**Go SDK**++```go+result, err := client.AdminRegenerateKey(ctx, "acme", "bob")+if err != nil {+ return err+}+fmt.Println(result["user_key"])+```+**CLI**```bash@@ -817,6 +897,18 @@ curl -X POST http://localhost:1933/api/v1/admin/migrate \-d '{"action": "cleanup"}'```+**Go SDK**++```go+result, err := client.AdminMigrate(ctx, &openviking.AdminMigrateOptions{+ Cleanup: false,+})+if err != nil {+ return err+}+fmt.Println(result["task_id"])+```+**CLI**```bashdiff --git a/docs/en/api/99-api-doc-writing-guide.md b/docs/en/api/99-api-doc-writing-guide.mdindex 57f2662d9..e8bdd993b 100644--- a/docs/en/api/99-api-doc-writing-guide.md+++ b/docs/en/api/99-api-doc-writing-guide.md@@ -63,6 +63,12 @@ Explain the purpose of this API, point to the corresponding code entry, and brie<SDK call example>```+**Go SDK**++```go+<SDK call example>+```+**CLI**```bash@@ -125,9 +131,16 @@ Each API is organized in the following three parts:Provide in order:- HTTP API (method + path + curl example)- Python SDK example+- Go SDK example, when it adds endpoint-specific value and can stay concise- CLI example- Response example+Keep API documentation organized around API modules and individual operations,+not around client languages. SDK snippets should be short call examples inside+the relevant operation's Usage Examples. Put language-specific quick references,+walkthroughs, and combined workflows in that SDK's own documentation instead of+adding language-owned sections to API module pages.+## Example: Complete API Documentation````markdowndiff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex d1919874c..b77a05746 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -74,6 +74,38 @@ client = ov.SyncHTTPClient(client.initialize()```+#### Go SDK 客户端++Go SDK 是 Client-Server 模式下的 HTTP-only 客户端,作为主仓库的 `sdk/go` 独立 Go module 发布。++```bash+go get github.com/volcengine/OpenViking/sdk/go+```++```go+client, err := openviking.NewClient(openviking.Config{+ BaseURL: "http://localhost:1933",+ APIKey: "your-key",+})+if err != nil {+ return err+}+defer client.CloseIdleConnections()+```++Go SDK 发送的身份请求头与 Python HTTP client 一致:++| Config 字段 | HTTP Header |+|-------------|-------------|+| `APIKey` | `X-API-Key` |+| `Account` | `X-OpenViking-Account` |+| `User` | `X-OpenViking-User` |+| `ActorPeerID` | `X-OpenViking-Actor-Peer` |++普通 `api_key` 部署下只需要设置 `APIKey`,服务端会从 API key 推导租户身份。只有在 trusted 部署或网关显式透传租户身份时,才需要设置 `Account` 和 `User`。++Go SDK 不支持 Python embedded 模式,也不保留旧 `agent_id` 兼容路径。更多示例见 [`sdk/go/README_CN.md`](../../../sdk/go/README_CN.md)。+未显式传入 `url` 时,HTTP 客户端会自动从 `ovcli.conf` 读取连接信息。`ovcli.conf` 是 HTTP 客户端和 CLI 共享的配置文件,默认路径 `~/.openviking/ovcli.conf`,也可通过环境变量指定:```bash@@ -353,7 +385,31 @@ JSON 输出 - 错误:|------|------|------|| POST | `/api/v1/resources/temp_upload` | 临时文件上传(用于后续资源导入) || POST | `/api/v1/resources` | 添加资源(支持 URL 或 temp_file_id) |++### 技能端点++| 方法 | 路径 | 说明 |+|------|------|------|+| GET | `/api/v1/skills` | 列出已安装技能 || POST | `/api/v1/skills` | 添加技能 |+| POST | `/api/v1/skills/find` | 搜索已安装技能 |+| POST | `/api/v1/skills/validate` | 校验技能 payload |+| GET | `/api/v1/skills/{skill_name}` | 获取技能 |+| PUT | `/api/v1/skills/{skill_name}` | 更新技能 |+| DELETE | `/api/v1/skills/{skill_name}` | 删除技能 |++### Watch 端点++| 方法 | 路径 | 说明 |+|------|------|------|+| GET | `/api/v1/watches` | 列出 watch,或按 `to_uri` 查询单个 watch |+| GET | `/api/v1/watches/{task_id}` | 获取 watch |+| PATCH | `/api/v1/watches` | 按 `to_uri` 更新 watch |+| PATCH | `/api/v1/watches/{task_id}` | 按 task ID 更新 watch |+| DELETE | `/api/v1/watches` | 按 `to_uri` 删除 watch |+| DELETE | `/api/v1/watches/{task_id}` | 按 task ID 删除 watch |+| POST | `/api/v1/watches/trigger` | 按 `to_uri` 触发 watch |+| POST | `/api/v1/watches/{task_id}/trigger` | 按 task ID 触发 watch |### Pack 端点diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.mdindex 799ba46e6..a4f5ec440 100644--- a/docs/zh/api/02-resources.md+++ b/docs/zh/api/02-resources.md@@ -309,6 +309,19 @@ client.add_resource()```+**Go SDK**++```go+result, err := client.AddResource(ctx, "./documents/guide.md", &openviking.AddResourceOptions{+ Reason: "User guide documentation",+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["root_uri"])+```+**CLI**```bash@@ -502,6 +515,34 @@ curl -X DELETE "http://localhost:1933/api/v1/watches?to_uri=viking://resources/g-H "X-API-Key: your-key"```+**Python SDK**++```python+watches = client.list_watches(active_only=True)+client.update_watch(to_uri="viking://resources/guide.md", is_active=False)+client.trigger_watch(to_uri="viking://resources/guide.md")+client.delete_watch(to_uri="viking://resources/guide.md")+```++**Go SDK**++```go+watches, err := client.ListWatches(ctx, &openviking.ListWatchesOptions{+ ActiveOnly: true,+})+updated, err := client.UpdateWatch(ctx, openviking.UpdateWatchOptions{+ ToURI: "viking://resources/guide.md",+ IsActive: openviking.Bool(false),+})+triggered, err := client.TriggerWatch(ctx, openviking.WatchRef{+ ToURI: "viking://resources/guide.md",+})+deleted, err := client.DeleteWatch(ctx, openviking.WatchRef{+ ToURI: "viking://resources/guide.md",+})+_, _, _, _ = watches, updated, triggered, deleted+```+**CLI**(`ov task watch` 子命令)```bash@@ -626,6 +667,18 @@ result = client.add_skill("./skills/my-skill.json")client.wait_processed()```+**Go SDK**++```go+result, err := client.AddSkill(ctx, "./skills/my-skill.json", &openviking.AddSkillOptions{+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["uri"])+```+**CLI**```bash@@ -761,6 +814,12 @@ curl -X POST http://localhost:1933/api/v1/resources/temp_upload \Python SDK 中的 `add_resource`、`add_skill` 等接口会自动处理本地文件上传,无需手动调用此接口。在 Python HTTP client 模式下,如果要启用分布式 shared 临时上传,可以在 `ovcli.conf` 中设置 `upload.mode = "shared"`。+**Go SDK**++`client.AddResource`、`client.AddSkill`、`client.ImportOVPack` 和+`client.RestoreOVPack` 会为本地文件自动调用 `temp_upload`。如需 shared 临时上传,设置+`openviking.Config{UploadMode: "shared"}`。+**CLI**CLI 命令也会自动处理本地文件上传,无需手动调用此接口。diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.mdindex 09bb67996..14dd17968 100644--- a/docs/zh/api/04-skills.md+++ b/docs/zh/api/04-skills.md@@ -321,6 +321,18 @@ result = client.add_skill("./skills/my-skill/", wait=True)client.wait_processed()```+**Go SDK**++```go+result, err := client.AddSkill(ctx, "./skills/my-skill/", &openviking.AddSkillOptions{+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["uri"])+```+**CLI**:```bash@@ -414,61 +426,59 @@ Python HTTP SDK 会把该响应映射为对应异常(`ProcessingError`)。## 技能管理操作+Python HTTP SDK 和 Go SDK 都暴露专用技能管理方法。Python 方法包括+`list_skills`、`find_skills`、`validate_skill`、`get_skill`、`update_skill`+和 `delete_skill`;Go 方法包括 `ListSkills`、`FindSkills`、`ValidateSkill`、+`GetSkill`、`UpdateSkill` 和 `DeleteSkill`。通用文件系统、内容和检索方法仍可用于 URI 级访问。+### 列出技能**Python SDK**:```python-# 列出所有技能-skills = client.ls("viking://user/skills/")-for skill in skills:- print(f"{skill['name']}")+skills = client.list_skills(node_limit=1000)+for skill in skills["skills"]:+ print(skill["name"])+```-# 简单列表(仅名称)-names = client.ls("viking://user/skills/", simple=True)-print(names)+**Go SDK**:++```go+skills, err := client.ListSkills(ctx, nil)+_ = skills```**HTTP API**:```bash-curl -X GET "http://localhost:1933/api/v1/fs/ls?uri=viking://user/skills/" \+curl -X GET "http://localhost:1933/api/v1/skills?node_limit=1000" \-H "X-API-Key: your-key"```-### 读取技能内容+### 读取技能**Python SDK**:```python-uri = "viking://user/skills/search-web/"--# L0:简要描述-abstract = client.abstract(uri)-print(f"Abstract: {abstract}")+skill = client.get_skill("search-web", include_content=True, include_files=True)+print(skill["name"])+print(skill.get("content"))+```-# L1:参数和使用概览-overview = client.overview(uri)-print(f"Overview: {overview}")+**Go SDK**:-# L2:完整技能文档-content = client.read(uri)-print(f"Content: {content}")+```go+skill, err := client.GetSkill(ctx, "search-web", &openviking.GetSkillOptions{+ IncludeContent: openviking.Bool(true),+ IncludeFiles: openviking.Bool(true),+})+_ = skill```**HTTP API**:```bash-# L0:简要描述-curl -X GET "http://localhost:1933/api/v1/content/abstract?uri=viking://user/skills/search-web/" \- -H "X-API-Key: your-key"--# L1:参数和使用概览-curl -X GET "http://localhost:1933/api/v1/content/overview?uri=viking://user/skills/search-web/" \- -H "X-API-Key: your-key"--# L2:完整技能文档-curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://user/skills/search-web/" \+curl -X GET "http://localhost:1933/api/v1/skills/search-web?include_content=true&include_files=true" \-H "X-API-Key: your-key"```@@ -477,44 +487,83 @@ curl -X GET "http://localhost:1933/api/v1/content/read?uri=viking://user/skills/**Python SDK**:```python-# 语义搜索技能-results = client.find(- "search the internet",- target_uri="viking://user/skills/",- limit=5-)+results = client.find_skills("search the internet", limit=5)-for ctx in results.skills:- print(f"Skill: {ctx.uri}")- print(f"Score: {ctx.score:.3f}")- print(f"Description: {ctx.abstract}")+for skill in results["skills"]:+ print(skill["name"], skill["score"])+```++**Go SDK**:++```go+results, err := client.FindSkills(ctx, "search the internet", &openviking.FindSkillsOptions{+ Limit: 5,+})+_ = results```**HTTP API**:```bash-curl -X POST http://localhost:1933/api/v1/search/find \+curl -X POST http://localhost:1933/api/v1/skills/find \-H "Content-Type: application/json" \-H "X-API-Key: your-key" \-d '{"query": "search the internet",- "target_uri": "viking://user/skills/","limit": 5}'```+### 校验和更新技能++**Python SDK**:++```python+validated = client.validate_skill({"name": "search-web", "description": "..."})+updated = client.update_skill("search-web", "./skills/search-web", wait=True)+```++**Go SDK**:++```go+validated, err := client.ValidateSkill(ctx, map[string]any{+ "name": "search-web",+ "description": "...",+}, nil)+updated, err := client.UpdateSkill(ctx, "search-web", "./skills/search-web", &openviking.UpdateSkillOptions{+ Wait: true,+})+_, _ = validated, updated+```++**HTTP API**:++```bash+curl -X POST http://localhost:1933/api/v1/skills/validate \+ -H "Content-Type: application/json" \+ -H "X-API-Key: your-key" \+ -d '{"data": {"name": "search-web", "description": "..."}}'+```+### 删除技能**Python SDK**:```python-client.rm("viking://user/skills/old-skill/", recursive=True)+client.delete_skill("old-skill")+```++**Go SDK**:++```go+deleted, err := client.DeleteSkill(ctx, "old-skill")+_ = deleted```**HTTP API**:```bash-curl -X DELETE "http://localhost:1933/api/v1/fs?uri=viking://user/skills/old-skill/&recursive=true" \+curl -X DELETE "http://localhost:1933/api/v1/skills/old-skill" \-H "X-API-Key: your-key"```diff --git a/docs/zh/api/05-sessions.md b/docs/zh/api/05-sessions.mdindex 12b6f54d5..ea54e3af4 100644--- a/docs/zh/api/05-sessions.md+++ b/docs/zh/api/05-sessions.md@@ -82,6 +82,18 @@ result = await client.create_session(session_id="my-custom-session-id")print(f"Session ID: {result['session_id']}")```+**Go SDK**++```go+session, err := client.CreateSession(ctx, &openviking.CreateSessionOptions{+ SessionID: "my-custom-session-id",+})+if err != nil {+ return err+}+fmt.Println(session["session_id"])+```+**CLI**```bash@@ -149,6 +161,18 @@ for s in sessions:print(f"{s['session_id']} -> {s['uri']}")```+**Go SDK**++```go+sessions, err := client.ListSessions(ctx)+if err != nil {+ return err+}+for _, session := range sessions {+ fmt.Println(session)+}+```+**CLI**```bash@@ -236,6 +260,26 @@ print(f"Commits: {info['commit_count']}")info = await client.get_session("a1b2c3d4", auto_create=True)```+**Go SDK**++```go+// 获取已有会话+info, err := client.GetSession(ctx, "a1b2c3d4", nil)+if err != nil {+ return err+}+fmt.Println(info["message_count"])++// 获取或创建会话+info, err = client.GetSession(ctx, "a1b2c3d4", &openviking.GetSessionOptions{+ AutoCreate: true,+})+if err != nil {+ return err+}+fmt.Println(info["session_id"])+```+**CLI**```bash@@ -342,6 +386,16 @@ print(context["latest_archive_overview"])print(len(context["messages"]))```+**Go SDK**++```go+contextPayload, err := client.GetSessionContext(ctx, "a1b2c3d4", 128000)+if err != nil {+ return err+}+fmt.Println(contextPayload["latest_archive_overview"])+```+**CLI**```bash@@ -436,6 +490,16 @@ print(archive["overview"])print(len(archive["messages"]))```+**Go SDK**++```go+archive, err := client.GetSessionArchive(ctx, "a1b2c3d4", "archive_002")+if err != nil {+ return err+}+fmt.Println(archive["archive_id"])+```+**CLI**```bash@@ -532,6 +596,14 @@ client = ov.Client(base_url="http://localhost:1933", api_key="your-key")await client.delete_session("a1b2c3d4")```+**Go SDK**++```go+if err := client.DeleteSession(ctx, "a1b2c3d4"); err != nil {+ return err+}+```+**CLI**```bash@@ -693,6 +765,19 @@ await client.add_message()```+**Go SDK**++```go+result, err := client.AddMessage(ctx, "a1b2c3d4", "user", openviking.AddMessageOptions{+ Content: openviking.String("How do I authenticate users?"),+ PeerID: "web-visitor-alice",+})+if err != nil {+ return err+}+fmt.Println(result["message_count"])+```+**CLI**```bash@@ -783,6 +868,20 @@ result = await client.batch_add_messages(print(f"Added: {result['added']}, Total: {result['message_count']}")```+**Go SDK**++```go+result, err := client.BatchAddMessages(ctx, "a1b2c3d4", []openviking.Message{+ {Role: "user", Content: openviking.String("How do I authenticate users?")},+ {Role: "assistant", Content: openviking.String("You can use OAuth 2.0 for authentication.")},+ {Role: "user", Content: openviking.String("Any specific recommendations?")},+}, nil)+if err != nil {+ return err+}+fmt.Println(result["added"], result["message_count"])+```+**CLI**```bash@@ -851,31 +950,6 @@ curl -X POST http://localhost:1933/api/v1/sessions/a1b2c3d4/used \-d '{"skill": {"uri": "viking://user/skills/search-web/", "input": {"query": "OAuth"}, "output": "Results...", "success": true}}'```-**Python SDK**--```python-import openviking as ov--client = ov.Client(base_url="http://localhost:1933", api_key="your-key")--# 记录使用的上下文-await client.session_used(- session_id="a1b2c3d4",- contexts=["viking://resources/docs/auth/"]-)--# 记录使用的技能-await client.session_used(- session_id="a1b2c3d4",- skill={- "uri": "viking://user/skills/search-web/",- "input": {"query": "OAuth"},- "output": "Results...",- "success": True- }-)-```-**响应示例**```json@@ -962,6 +1036,25 @@ if task["status"] == "completed":print(f"Memories extracted: {total}")```+**Go SDK**++```go+commit, err := client.CommitSession(ctx, "a1b2c3d4", &openviking.CommitSessionOptions{+ KeepRecentCount: 0,+})+if err != nil {+ return err+}+fmt.Println(commit["status"], commit["task_id"])++taskID, _ := commit["task_id"].(string)+task, err := client.GetTask(ctx, taskID)+if err != nil {+ return err+}+fmt.Println(task["status"])+```+**CLI**```bash@@ -989,7 +1082,7 @@ ov session commit a1b2c3d4#### 1. API 实现介绍-仅 HTTP API。立即对已有会话触发一次记忆提取,不会额外创建新的 commit 任务。+立即对已有会话触发一次记忆提取,不会额外创建新的 commit 任务。**代码入口**:- `openviking/server/routers/sessions.py:extract_session()` - HTTP 路由@@ -1071,6 +1164,18 @@ task = await client.get_task(task_id="uuid-xxx")print(f"Status: {task['status']}")```+**Go SDK**++```go+task, err := client.GetTask(ctx, "uuid-xxx")+if err != nil {+ return err+}+if task != nil {+ fmt.Println(task["status"])+}+```+**响应示例(资源导入进行中)**```json@@ -1131,10 +1236,11 @@ print(f"Status: {task['status']}")#### 1. API 实现介绍-仅 HTTP API。列出当前调用方可见的后台任务,支持按类型、状态、资源过滤。+列出当前调用方可见的后台任务,支持按类型、状态、资源过滤。**代码入口**:- `openviking/server/routers/tasks.py:list_tasks()` - HTTP 路由+- `openviking_cli/client/base.py:BaseClient.list_tasks()` - Python SDK#### 2. 接口和参数说明@@ -1160,6 +1266,38 @@ curl -X GET "http://localhost:1933/api/v1/tasks?task_type=session_commit&status=-H "X-API-Key: your-key"```+**Python SDK**++```python+import openviking as ov++client = ov.Client(base_url="http://localhost:1933", api_key="your-key")++tasks = await client.list_tasks(+ task_type="session_commit",+ status="running",+ limit=20,+)+for task in tasks:+ print(task["task_id"], task["status"])+```++**Go SDK**++```go+tasks, err := client.ListTasks(ctx, &openviking.ListTasksOptions{+ TaskType: "session_commit",+ Status: "running",+ Limit: 20,+})+if err != nil {+ return err+}+for _, task := range tasks {+ fmt.Println(task)+}+```+**响应示例**```json@@ -1329,13 +1467,6 @@ if results.resources:)])-- # 跟踪实际使用的上下文- await client.session_used(- session_id=session_id,- contexts=[results.resources[0].uri]- )-# 提交会话(立即返回,后台执行摘要生成和记忆提取)commit_result = await client.commit_session(session_id)print(f"Task ID: {commit_result['task_id']}")@@ -1403,14 +1534,6 @@ if session_info["message_count"] > 10:await client.commit_session(session_id)```-### 跟踪实际使用的内容--```python-# 仅标记实际有帮助的上下文-if context_was_useful:- await client.session_used(session_id=session_id, contexts=[ctx.uri])-```-### 使用会话上下文进行搜索```pythondiff --git a/docs/zh/api/06-retrieval.md b/docs/zh/api/06-retrieval.mdindex b44debf06..40fb0400b 100644--- a/docs/zh/api/06-retrieval.md+++ b/docs/zh/api/06-retrieval.md@@ -221,6 +221,22 @@ results = client.find()```+**Go SDK**++```go+result, err := client.Find(ctx, "how to authenticate users", &openviking.FindOptions{+ TargetURI: "viking://resources/docs",+ Limit: 10,+ ContextType: []string{"resource"},+})+if err != nil {+ return err+}+for _, item := range result.Resources {+ fmt.Println(item.URI, item.Score)+}+```+**CLI**```bash@@ -408,6 +424,20 @@ for ctx in results.resources:print(f"Found: {ctx.uri} (score: {ctx.score:.3f})")```+**Go SDK**++```go+result, err := client.Search(ctx, "best practices", &openviking.SearchOptions{+ SessionID: "abc123",+ ContextType: "skill",+ Limit: 10,+})+if err != nil {+ return err+}+fmt.Println(result.Total)+```+**CLI**```bash@@ -546,6 +576,18 @@ for match in results['matches']:print(f" {match['content']}")```+**Go SDK**++```go+result, err := client.Grep(ctx, "viking://resources", "authentication", &openviking.GrepOptions{+ CaseInsensitive: true,+})+if err != nil {+ return err+}+fmt.Println(result["count"])+```+**CLI**```bash@@ -646,6 +688,16 @@ results = client.glob("**/*.py", "viking://resources")print(f"Found {results['count']} Python files")```+**Go SDK**++```go+result, err := client.Glob(ctx, "**/*.md", "viking://resources")+if err != nil {+ return err+}+fmt.Println(result["count"])+```+**CLI**```bashdiff --git a/docs/zh/api/07-system.md b/docs/zh/api/07-system.mdindex 0e986d0ad..d82b612c4 100644--- a/docs/zh/api/07-system.md+++ b/docs/zh/api/07-system.md@@ -66,6 +66,16 @@ healthy = client.health()print(f"Healthy: {healthy}")```+**Go SDK**++```go+healthy, err := client.Health(ctx)+if err != nil {+ return err+}+fmt.Println(healthy)+```+**CLI**```bash@@ -256,6 +266,16 @@ print(report["ok"])print(report["missing_records"])```+**Go SDK**++```go+report, err := client.CheckConsistency(ctx, "viking://resources/my-project")+if err != nil {+ return err+}+fmt.Println(report["ok"])+```+**CLI**```bash@@ -333,6 +353,18 @@ status = client.wait_processed(timeout=60.0)print(f"Processing complete: {status}")```+**Go SDK**++```go+status, err := client.WaitProcessed(ctx, &openviking.WaitProcessedOptions{+ Timeout: openviking.Float64(60),+})+if err != nil {+ return err+}+fmt.Println(status)+```+**CLI**```bash@@ -430,6 +462,19 @@ result = client.reindex(print(result["status"])```+**Go SDK**++```go+result, err := client.Reindex(ctx, "viking://resources", &openviking.ReindexOptions{+ Mode: "vectors_only",+ Wait: true,+})+if err != nil {+ return err+}+fmt.Println(result["status"])+```+**HTTP API**```@@ -591,6 +636,16 @@ print(client.observer.queue)# TOTAL 0 0 20 0 20```+**Go SDK**++```go+status, err := client.QueueStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bash@@ -658,6 +713,16 @@ print(client.observer.vikingdb().is_healthy) # Trueprint(client.observer.vikingdb().status) # 状态表字符串```+**Go SDK**++```go+status, err := client.VikingDBStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bash@@ -722,6 +787,16 @@ print(client.observer.models)# vlm yes ...```+**Go SDK**++```go+status, err := client.ModelsStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bash@@ -964,6 +1039,16 @@ print(client.observer.system())# [system] (healthy)```+**Go SDK**++```go+status, err := client.GetStatus(ctx)+if err != nil {+ return err+}+fmt.Println(status["is_healthy"])+```+**CLI**```bashdiff --git a/docs/zh/api/08-admin.md b/docs/zh/api/08-admin.mdindex 60172d923..ddb08acdf 100644--- a/docs/zh/api/08-admin.md+++ b/docs/zh/api/08-admin.md@@ -162,6 +162,16 @@ print(f"Admin user: {result['admin_user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")```+**Go SDK**++```go+result, err := client.AdminCreateAccount(ctx, "acme", "alice")+if err != nil {+ return err+}+fmt.Println(result["account_id"])+```+**CLI**```bash@@ -231,6 +241,16 @@ for account in accounts:print(f"Account: {account['account_id']}, created: {account['created_at']}, users: {account['user_count']}")```+**Go SDK**++```go+accounts, err := client.AdminListAccounts(ctx)+if err != nil {+ return err+}+fmt.Println(accounts)+```+**CLI**```bash@@ -307,6 +327,16 @@ result = client.admin_delete_account("acme")print(f"Account deleted: {result['deleted']}")```+**Go SDK**++```go+result, err := client.AdminDeleteAccount(ctx, "acme")+if err != nil {+ return err+}+fmt.Println(result["deleted"])+```+**CLI**```bash@@ -391,6 +421,16 @@ print(f"User registered: {result['user_id']}")print(f"User key: {result.get('user_key', '(not exposed in trusted mode)')}")```+**Go SDK**++```go+result, err := client.AdminRegisterUser(ctx, "acme", "bob", "user")+if err != nil {+ return err+}+fmt.Println(result["user_id"])+```+**CLI**```bash@@ -480,6 +520,16 @@ for user in users:print(f"User: {user['user_id']}, role: {user['role']}")```+**Go SDK**++```go+users, err := client.AdminListUsers(ctx, "acme")+if err != nil {+ return err+}+fmt.Println(users)+```+**CLI**```bash@@ -559,6 +609,16 @@ result = client.admin_remove_user("acme", "bob")print(f"User deleted: {result['deleted']}")```+**Go SDK**++```go+result, err := client.AdminRemoveUser(ctx, "acme", "bob")+if err != nil {+ return err+}+fmt.Println(result["deleted"])+```+**CLI**```bash@@ -640,6 +700,16 @@ result = client.admin_set_role("acme", "bob", "admin")print(f"User: {result['user_id']}, new role: {result['role']}")```+**Go SDK**++```go+result, err := client.AdminSetRole(ctx, "acme", "bob", "admin")+if err != nil {+ return err+}+fmt.Println(result["role"])+```+**CLI**```bash@@ -719,6 +789,16 @@ result = client.admin_regenerate_key("acme", "bob")print(f"New user key: {result['user_key']}")```+**Go SDK**++```go+result, err := client.AdminRegenerateKey(ctx, "acme", "bob")+if err != nil {+ return err+}+fmt.Println(result["user_key"])+```+**CLI**```bash@@ -814,6 +894,18 @@ curl -X POST http://localhost:1933/api/v1/admin/migrate \-d '{"action": "cleanup"}'```+**Go SDK**++```go+result, err := client.AdminMigrate(ctx, &openviking.AdminMigrateOptions{+ Cleanup: false,+})+if err != nil {+ return err+}+fmt.Println(result["task_id"])+```+**CLI**```bashdiff --git a/docs/zh/api/99-api-doc-writing-guide.md b/docs/zh/api/99-api-doc-writing-guide.mdindex 1410ce3de..545938ad9 100644--- a/docs/zh/api/99-api-doc-writing-guide.md+++ b/docs/zh/api/99-api-doc-writing-guide.md@@ -63,6 +63,12 @@ API 文档按模块组织,每个模块一个文件,使用两位数字序号<SDK 调用示例>```+**Go SDK**++```go+<SDK 调用示例>+```+**CLI**```bash@@ -124,9 +130,14 @@ API 文档按模块组织,每个模块一个文件,使用两位数字序号按顺序提供:- HTTP API(方法 + 路径 + curl 示例)- Python SDK 示例+- Go SDK 示例(当它能补充说明该接口的调用形态,且可以保持简短时)- CLI 示例- 响应示例+API 文档应按 API 模块和具体接口组织,而不是按客户端语言组织。SDK 片段只作为对应接口+“使用示例”中的简短调用示例出现。语言专属 quick reference、完整 walkthrough 或跨接口串联流程+应放在该 SDK 自己的文档中,不应新增到 API 模块页面里。+## 示例:完整接口文档````markdowndiff --git a/openviking/async_client.py b/openviking/async_client.pyindex af79e8574..53926b42c 100644--- a/openviking/async_client.py+++ b/openviking/async_client.py@@ -246,6 +246,22 @@ class AsyncOpenViking:await self._ensure_initialized()return await self._client.get_task(task_id)+ async def list_tasks(+ self,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """List background tasks visible to the current caller."""+ await self._ensure_initialized()+ return await self._client.list_tasks(+ task_type=task_type,+ status=status,+ resource_id=resource_id,+ limit=limit,+ )+async def reindex(self,uri: str,diff --git a/openviking/client/local.py b/openviking/client/local.pyindex dcd0732ba..bca521406 100644--- a/openviking/client/local.py+++ b/openviking/client/local.py@@ -10,6 +10,7 @@ from typing import Any, Dict, List, Optional, Unionfrom openviking.core.peer_id import normalize_peer_id, normalize_peer_selectorfrom openviking.server.identity import RequestContext, Rolefrom openviking.service import OpenVikingService+from openviking.service.task_tracker import get_task_trackerfrom openviking.telemetry import TelemetryRequestfrom openviking.telemetry.execution import (attach_telemetry_payload,@@ -530,6 +531,24 @@ class LocalClient(BaseClient):"""Query background task status."""return await self._service.sessions.get_commit_task(task_id, self._ctx)+ async def list_tasks(+ self,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: int = 50,+ ) -> List[Dict[str, Any]]:+ """List background tasks visible to the current caller."""+ tasks = await get_task_tracker().list_tasks(+ task_type=task_type,+ status=status,+ resource_id=resource_id,+ limit=limit,+ account_id=self._ctx.account_id,+ user_id=self._ctx.user.user_id,+ )+ return [task.to_dict() for task in tasks]+async def add_message(self,session_id: str,diff --git a/openviking/sync_client.py b/openviking/sync_client.pyindex 58e6cfeec..2d04fb872 100644--- a/openviking/sync_client.py+++ b/openviking/sync_client.py@@ -160,6 +160,23 @@ class SyncOpenViking:"""Query background task status."""return run_async(self._async_client.get_task(task_id))+ def list_tasks(+ self,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """List background tasks visible to the current caller."""+ return run_async(+ self._async_client.list_tasks(+ task_type=task_type,+ status=status,+ resource_id=resource_id,+ limit=limit,+ )+ )+def reindex(self,uri: str,diff --git a/openviking_cli/client/base.py b/openviking_cli/client/base.pyindex fef970372..dbac2cd85 100644--- a/openviking_cli/client/base.py+++ b/openviking_cli/client/base.py@@ -339,6 +339,22 @@ class BaseClient(ABC):"""...+ @abstractmethod+ async def get_task(self, task_id: str) -> Optional[Dict[str, Any]]:+ """Query background task status."""+ ...++ @abstractmethod+ async def list_tasks(+ self,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: int = 50,+ ) -> List[Dict[str, Any]]:+ """List background tasks visible to the current caller."""+ ...+# ============= Pack =============@abstractmethoddiff --git a/openviking_cli/client/http.py b/openviking_cli/client/http.pyindex 13bee0266..e6331de6e 100644--- a/openviking_cli/client/http.py+++ b/openviking_cli/client/http.py@@ -558,6 +558,231 @@ class AsyncHTTPClient(BaseClient):response_data = self._handle_response_data(response)return self._attach_telemetry(response_data.get("result"), response_data)+ # ============= Skill Management =============++ async def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:+ """List installed agent skills."""+ response = await self._http.get(+ "/api/v1/skills",+ params={"node_limit": node_limit},+ )+ return self._handle_response(response)++ async def find_skills(+ self,+ query: str,+ limit: int = 10,+ score_threshold: Optional[float] = None,+ level: Optional[List[int]] = None,+ telemetry: TelemetryRequest = False,+ ) -> Dict[str, Any]:+ """Find installed agent skills by semantic search."""+ telemetry = self._validate_telemetry(telemetry)+ payload: Dict[str, Any] = {+ "query": query,+ "limit": limit,+ "score_threshold": score_threshold,+ "level": level,+ "telemetry": telemetry,+ }+ response = await self._http.post("/api/v1/skills/find", json=payload)+ response_data = self._handle_response_data(response)+ return self._attach_telemetry(response_data.get("result"), response_data)++ async def validate_skill(+ self,+ data: Any,+ strict: bool = False,+ source_path: Optional[str] = None,+ skill_dir_name: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Validate a skill payload without installing it."""+ payload: Dict[str, Any] = {"data": data, "strict": strict}+ if source_path is not None:+ payload["source_path"] = source_path+ if skill_dir_name is not None:+ payload["skill_dir_name"] = skill_dir_name+ response = await self._http.post("/api/v1/skills/validate", json=payload)+ return self._handle_response(response)++ async def get_skill(+ self,+ skill_name: str,+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ ) -> Dict[str, Any]:+ """Get one installed agent skill."""+ params: Dict[str, Any] = {+ "include_files": include_files,+ "include_source": include_source,+ }+ if include_content is not None:+ params["include_content"] = include_content+ if level is not None:+ params["level"] = level+ response = await self._http.get(f"/api/v1/skills/{skill_name}", params=params)+ return self._handle_response(response)++ async def update_skill(+ self,+ skill_name: str,+ data: Any,+ wait: bool = False,+ timeout: Optional[float] = None,+ source_metadata: Optional[Dict[str, Any]] = None,+ telemetry: TelemetryRequest = False,+ ) -> Dict[str, Any]:+ """Replace an installed agent skill."""+ telemetry = self._validate_telemetry(telemetry)+ request_data: Dict[str, Any] = {+ "wait": wait,+ "timeout": timeout,+ "source_metadata": source_metadata,+ "telemetry": telemetry,+ }++ if isinstance(data, str):+ path_obj = Path(data)+ if path_obj.exists():+ if path_obj.is_dir():+ zip_path = self._zip_directory(data)+ try:+ request_data["temp_file_id"] = await self._upload_temp_file(zip_path)+ finally:+ Path(zip_path).unlink(missing_ok=True)+ elif path_obj.is_file():+ request_data["temp_file_id"] = await self._upload_temp_file(data)+ else:+ request_data["data"] = data+ else:+ request_data["data"] = data+ else:+ request_data["data"] = data++ response = await self._http.put(+ f"/api/v1/skills/{skill_name}",+ json=request_data,+ )+ response_data = self._handle_response_data(response)+ return self._attach_telemetry(response_data.get("result"), response_data)++ async def delete_skill(self, skill_name: str) -> Dict[str, Any]:+ """Remove an installed agent skill."""+ response = await self._http.delete(f"/api/v1/skills/{skill_name}")+ return self._handle_response(response)++ # ============= Watch Management =============++ async def list_watches(+ self,+ active_only: bool = False,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """List watch tasks, or get one by target URI."""+ params: Dict[str, Any] = {"active_only": active_only}+ if to_uri is not None:+ params["to_uri"] = VikingURI.normalize(to_uri)+ response = await self._http.get("/api/v1/watches", params=params)+ return self._handle_response(response)++ async def get_watch(+ self,+ task_id: str,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Get one watch task by task ID, optionally cross-checking the target URI."""+ params = {}+ if to_uri is not None:+ params["to_uri"] = VikingURI.normalize(to_uri)+ response = await self._http.get(f"/api/v1/watches/{task_id}", params=params)+ return self._handle_response(response)++ async def update_watch(+ self,+ task_id: Optional[str] = None,+ *,+ to_uri: Optional[str] = None,+ watch_interval: Optional[float] = None,+ is_active: Optional[bool] = None,+ reason: Optional[str] = None,+ instruction: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Partially update a watch task by task ID or target URI."""+ if not task_id and not to_uri:+ raise ValueError("Either task_id or to_uri is required")+ payload: Dict[str, Any] = {}+ if watch_interval is not None:+ payload["watch_interval"] = watch_interval+ if is_active is not None:+ payload["is_active"] = is_active+ if reason is not None:+ payload["reason"] = reason+ if instruction is not None:+ payload["instruction"] = instruction+ if task_id:+ params = {}+ if to_uri is not None:+ params["to_uri"] = VikingURI.normalize(to_uri)+ response = await self._http.patch(+ f"/api/v1/watches/{task_id}",+ params=params,+ json=payload,+ )+ else:+ response = await self._http.patch(+ "/api/v1/watches",+ params={"to_uri": VikingURI.normalize(to_uri)},+ json=payload,+ )+ return self._handle_response(response)++ async def delete_watch(+ self,+ task_id: Optional[str] = None,+ *,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Delete a watch task by task ID or target URI."""+ if not task_id and not to_uri:+ raise ValueError("Either task_id or to_uri is required")+ if task_id:+ params = {}+ if to_uri is not None:+ params["to_uri"] = VikingURI.normalize(to_uri)+ response = await self._http.delete(f"/api/v1/watches/{task_id}", params=params)+ else:+ response = await self._http.delete(+ "/api/v1/watches",+ params={"to_uri": VikingURI.normalize(to_uri)},+ )+ return self._handle_response(response)++ async def trigger_watch(+ self,+ task_id: Optional[str] = None,+ *,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Schedule a watch task for immediate background execution."""+ if not task_id and not to_uri:+ raise ValueError("Either task_id or to_uri is required")+ if task_id:+ params = {}+ if to_uri is not None:+ params["to_uri"] = VikingURI.normalize(to_uri)+ response = await self._http.post(+ f"/api/v1/watches/{task_id}/trigger",+ params=params,+ )+ else:+ response = await self._http.post(+ "/api/v1/watches/trigger",+ params={"to_uri": VikingURI.normalize(to_uri)},+ )+ return self._handle_response(response)+async def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:"""Wait for all processing to complete."""http_timeout = timeout if timeout else 600.0@@ -942,6 +1167,24 @@ class AsyncHTTPClient(BaseClient):return Nonereturn self._handle_response(response)+ async def list_tasks(+ self,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """List background tasks visible to the current caller."""+ params: Dict[str, Any] = {"limit": limit}+ if task_type is not None:+ params["task_type"] = task_type+ if status is not None:+ params["status"] = status+ if resource_id is not None:+ params["resource_id"] = resource_id+ response = await self._http.get("/api/v1/tasks", params=params)+ return self._handle_response(response)+async def commit_session(self,session_id: str,diff --git a/openviking_cli/client/sync_http.py b/openviking_cli/client/sync_http.pyindex f7b1b0ff0..fb29ef322 100644--- a/openviking_cli/client/sync_http.py+++ b/openviking_cli/client/sync_http.py@@ -190,6 +190,23 @@ class SyncHTTPClient:"""Query background task status."""return run_async(self._async_client.get_task(task_id))+ def list_tasks(+ self,+ task_type: Optional[str] = None,+ status: Optional[str] = None,+ resource_id: Optional[str] = None,+ limit: int = 50,+ ) -> list[dict[str, Any]]:+ """List background tasks visible to the current caller."""+ return run_async(+ self._async_client.list_tasks(+ task_type=task_type,+ status=status,+ resource_id=resource_id,+ limit=limit,+ )+ )+def reindex(self,uri: str,@@ -276,6 +293,150 @@ class SyncHTTPClient:self._async_client.add_skill(data, wait=wait, timeout=timeout, telemetry=telemetry))+ # ============= Skill Management =============++ def list_skills(self, node_limit: int = 1000) -> Dict[str, Any]:+ """List installed agent skills."""+ return run_async(self._async_client.list_skills(node_limit=node_limit))++ def find_skills(+ self,+ query: str,+ limit: int = 10,+ score_threshold: Optional[float] = None,+ level: Optional[List[int]] = None,+ telemetry: TelemetryRequest = False,+ ) -> Dict[str, Any]:+ """Find installed agent skills by semantic search."""+ return run_async(+ self._async_client.find_skills(+ query=query,+ limit=limit,+ score_threshold=score_threshold,+ level=level,+ telemetry=telemetry,+ )+ )++ def validate_skill(+ self,+ data: Any,+ strict: bool = False,+ source_path: Optional[str] = None,+ skill_dir_name: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Validate a skill payload without installing it."""+ return run_async(+ self._async_client.validate_skill(+ data=data,+ strict=strict,+ source_path=source_path,+ skill_dir_name=skill_dir_name,+ )+ )++ def get_skill(+ self,+ skill_name: str,+ include_content: Optional[bool] = None,+ include_files: bool = True,+ include_source: bool = False,+ level: Optional[int] = None,+ ) -> Dict[str, Any]:+ """Get one installed agent skill."""+ return run_async(+ self._async_client.get_skill(+ skill_name,+ include_content=include_content,+ include_files=include_files,+ include_source=include_source,+ level=level,+ )+ )++ def update_skill(+ self,+ skill_name: str,+ data: Any,+ wait: bool = False,+ timeout: Optional[float] = None,+ source_metadata: Optional[Dict[str, Any]] = None,+ telemetry: TelemetryRequest = False,+ ) -> Dict[str, Any]:+ """Replace an installed agent skill."""+ return run_async(+ self._async_client.update_skill(+ skill_name,+ data,+ wait=wait,+ timeout=timeout,+ source_metadata=source_metadata,+ telemetry=telemetry,+ )+ )++ def delete_skill(self, skill_name: str) -> Dict[str, Any]:+ """Remove an installed agent skill."""+ return run_async(self._async_client.delete_skill(skill_name))++ # ============= Watch Management =============++ def list_watches(+ self,+ active_only: bool = False,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """List watch tasks, or get one by target URI."""+ return run_async(self._async_client.list_watches(active_only=active_only, to_uri=to_uri))++ def get_watch(+ self,+ task_id: str,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Get one watch task by task ID, optionally cross-checking the target URI."""+ return run_async(self._async_client.get_watch(task_id, to_uri=to_uri))++ def update_watch(+ self,+ task_id: Optional[str] = None,+ *,+ to_uri: Optional[str] = None,+ watch_interval: Optional[float] = None,+ is_active: Optional[bool] = None,+ reason: Optional[str] = None,+ instruction: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Partially update a watch task by task ID or target URI."""+ return run_async(+ self._async_client.update_watch(+ task_id,+ to_uri=to_uri,+ watch_interval=watch_interval,+ is_active=is_active,+ reason=reason,+ instruction=instruction,+ )+ )++ def delete_watch(+ self,+ task_id: Optional[str] = None,+ *,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Delete a watch task by task ID or target URI."""+ return run_async(self._async_client.delete_watch(task_id, to_uri=to_uri))++ def trigger_watch(+ self,+ task_id: Optional[str] = None,+ *,+ to_uri: Optional[str] = None,+ ) -> Dict[str, Any]:+ """Schedule a watch task for immediate background execution."""+ return run_async(self._async_client.trigger_watch(task_id, to_uri=to_uri))+def wait_processed(self, timeout: Optional[float] = None) -> Dict[str, Any]:"""Wait for all processing to complete."""return run_async(self._async_client.wait_processed(timeout))diff --git a/sdk/go/README.md b/sdk/go/README.mdnew file mode 100644index 000000000..28dbf2407--- /dev/null+++ b/sdk/go/README.md@@ -0,0 +1,213 @@+# OpenViking Go SDK++The Go SDK is an HTTP client for a running OpenViking server. It lives in the+main OpenViking repository as an independent Go module.++```bash+go get github.com/volcengine/OpenViking/sdk/go+```++## Client Setup++```go+package main++import (+ "context"+ "fmt"+ "log"+ "time"++ openviking "github.com/volcengine/OpenViking/sdk/go"+)++func main() {+ ctx := context.Background()++ client, err := openviking.NewClient(openviking.Config{+ BaseURL: "http://localhost:1933",+ APIKey: "your-key",+ Timeout: 120 * time.Second,+ })+ if err != nil {+ log.Fatal(err)+ }+ defer client.CloseIdleConnections()++ ok, err := client.Health(ctx)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Println("healthy:", ok)+}+```++The client sends the same identity headers as the Python HTTP client:++| Config field | HTTP header |+|--------------|-------------|+| `APIKey` | `X-API-Key` |+| `Account` | `X-OpenViking-Account` |+| `User` | `X-OpenViking-User` |+| `ActorPeerID` | `X-OpenViking-Actor-Peer` |++For the common `api_key` deployment mode, `APIKey` is enough because the server+derives account and user identity from the key. Set `Account` and `User` only+for trusted deployments or gateways where the upstream explicitly forwards+tenant identity through OpenViking headers.++This SDK is HTTP-only. It does not implement Python embedded mode or legacy+`agent_id` compatibility.++## Common Operations++```go+// Add a local file or remote URL. Local files/directories are uploaded first.+resource, err := client.AddResource(ctx, "./docs/readme.md", &openviking.AddResourceOptions{+ To: "viking://resources/docs",+ Wait: true,+})++// Read and update content.+content, err := client.Read(ctx, "viking://resources/docs/readme.md", 0, -1)+updated, err := client.Write(ctx, "viking://resources/docs/readme.md", content+"\n\nUpdated.", &openviking.WriteOptions{+ Mode: "replace",+ Wait: true,+})++// Find relevant context.+results, err := client.Find(ctx, "how do I configure auth?", &openviking.FindOptions{+ TargetURI: "viking://resources/docs",+ Limit: 10,+ ContextType: []string{"resource"},+})+for _, item := range results.Resources {+ fmt.Println(item.URI, item.Score)+}++// Work with sessions.+session, err := client.CreateSession(ctx, &openviking.CreateSessionOptions{+ SessionID: "demo-session",+})+_, err = client.AddMessage(ctx, "demo-session", "user", openviking.AddMessageOptions{+ Content: openviking.String("remember this deployment decision"),+})+commit, err := client.CommitSession(ctx, "demo-session", &openviking.CommitSessionOptions{+ KeepRecentCount: 2,+})++_, _, _ = resource, updated, session+_ = commit+```++## API Coverage++The Go SDK v1 intentionally follows the Python HTTP client surface.++Implemented:++| Area | Go methods |+|------|------------|+| Resource and skill import | `AddResource`, `AddSkill`, `WaitProcessed` |+| Skill management | `ListSkills`, `FindSkills`, `ValidateSkill`, `GetSkill`, `UpdateSkill`, `DeleteSkill` |+| Watch management | `ListWatches`, `GetWatch`, `UpdateWatch`, `DeleteWatch`, `TriggerWatch` |+| Filesystem and content | `List`, `Tree`, `Stat`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `Reindex` |+| Retrieval | `Find`, `Search`, `Grep`, `Glob` |+| Sessions and tasks | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |+| Packs | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` |+| System and observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |+| Admin | `AdminCreateAccount`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminMigrate` |++Not implemented in Go SDK v1:++| Area | Reason |+|------|--------|+| Python embedded mode | Go SDK is HTTP-only. |+| Legacy `agent_id` compatibility | New SDKs use `ActorPeerID` only. |+| Privacy config routes | Server-only management surface today; not in Python HTTP client. |+| Metrics endpoint | Prometheus text scrape endpoint, not a JSON SDK API. |+| Console/debug/backend-sync/session tool-result endpoints | Operational or server-only endpoints outside Python HTTP client parity. |++## Files, Directories, and Packs++`AddResource` and `AddSkill` accept local files and directories. Directory+uploads are zipped by the SDK, symlinks are skipped, and the resulting archive+is uploaded to `/api/v1/resources/temp_upload` before the final API call.++```go+_, err := client.AddSkill(ctx, "./skills/search-web", &openviking.AddSkillOptions{+ Wait: true,+})++skills, err := client.ListSkills(ctx, nil)+found, err := client.FindSkills(ctx, "search the web", &openviking.FindSkillsOptions{+ Limit: 5,+})+_, _ = skills, found++exported, err := client.ExportOVPack(ctx, "viking://resources/docs", "./backups", nil)+restored, err := client.RestoreOVPack(ctx, exported, &openviking.ImportPackOptions{+ OnConflict: "overwrite",+})++_, _ = exported, restored+```++## Watch Management++`AddResource` creates a watch when `WatchInterval` is greater than zero.+The dedicated watch methods manage existing tasks:++```go+watches, err := client.ListWatches(ctx, &openviking.ListWatchesOptions{+ ActiveOnly: true,+})+updated, err := client.UpdateWatch(ctx, openviking.UpdateWatchOptions{+ ToURI: "viking://resources/docs",+ WatchInterval: openviking.Float64(30),+ IsActive: openviking.Bool(true),+})+triggered, err := client.TriggerWatch(ctx, openviking.WatchRef{+ ToURI: "viking://resources/docs",+})++_, _, _ = watches, updated, triggered+```++## Error Handling++OpenViking API errors return `*openviking.Error`.++```go+_, err := client.Read(ctx, "viking://resources/missing.md", 0, -1)+if openviking.IsCode(err, "NOT_FOUND") {+ fmt.Println("missing resource")+}++var apiErr *openviking.Error+if errors.As(err, &apiErr) {+ fmt.Println(apiErr.Code, apiErr.StatusCode, apiErr.Details)+}+```++## Test++```bash+cd sdk/go+go test ./...+```++## Smoke Test Against a Server++Edit the constants at the top of `examples/basic_usage/main.go`, then run:++```bash+cd sdk/go+go run ./examples/basic_usage+```++The script creates a temporary Markdown file, imports it as an OpenViking+resource, reads and updates it, runs semantic retrieval, exercises watch and+skill management APIs, then creates a multi-message session, commits it,+polls the memory extraction task, and searches both user and peer-scoped+memories.diff --git a/sdk/go/README_CN.md b/sdk/go/README_CN.mdnew file mode 100644index 000000000..9576fae52--- /dev/null+++ b/sdk/go/README_CN.md@@ -0,0 +1,118 @@+# OpenViking Go SDK++Go SDK 是面向 OpenViking Server 的 HTTP 客户端,作为独立 Go module 放在主仓库 `sdk/go` 下。++```bash+go get github.com/volcengine/OpenViking/sdk/go+```++## 初始化++```go+client, err := openviking.NewClient(openviking.Config{+ BaseURL: "http://localhost:1933",+ APIKey: "your-key",+ Timeout: 120 * time.Second,+})+if err != nil {+ log.Fatal(err)+}+defer client.CloseIdleConnections()+```++Go SDK 发送的身份请求头与 Python HTTP client 一致:++| Config 字段 | HTTP Header |+|-------------|-------------|+| `APIKey` | `X-API-Key` |+| `Account` | `X-OpenViking-Account` |+| `User` | `X-OpenViking-User` |+| `ActorPeerID` | `X-OpenViking-Actor-Peer` |++普通 `api_key` 部署下只需要设置 `APIKey`,服务端会从 API key 推导 account/user 身份。只有在 trusted 部署或网关显式透传租户身份时,才需要设置 `Account` 和 `User`。++Go SDK 仅支持 HTTP 模式,不支持 Python embedded 模式,也不保留旧 `agent_id` 兼容路径。++## 已实现接口++| 模块 | Go 方法 |+|------|---------|+| 资源和技能导入 | `AddResource`, `AddSkill`, `WaitProcessed` |+| 技能管理 | `ListSkills`, `FindSkills`, `ValidateSkill`, `GetSkill`, `UpdateSkill`, `DeleteSkill` |+| Watch 管理 | `ListWatches`, `GetWatch`, `UpdateWatch`, `DeleteWatch`, `TriggerWatch` |+| 文件系统和内容 | `List`, `Tree`, `Stat`, `Mkdir`, `Remove`, `Move`, `Read`, `Abstract`, `Overview`, `Write`, `Reindex` |+| 检索 | `Find`, `Search`, `Grep`, `Glob` |+| 会话和任务 | `CreateSession`, `ListSessions`, `GetSession`, `SessionExists`, `GetSessionContext`, `GetSessionArchive`, `DeleteSession`, `AddMessage`, `BatchAddMessages`, `CommitSession`, `GetTask`, `ListTasks` |+| OVPack | `ExportOVPack`, `BackupOVPack`, `ImportOVPack`, `RestoreOVPack` |+| 系统和 observer | `Health`, `CheckConsistency`, `GetStatus`, `IsHealthy`, `QueueStatus`, `VikingDBStatus`, `ModelsStatus` |+| 管理接口 | `AdminCreateAccount`, `AdminListAccounts`, `AdminDeleteAccount`, `AdminRegisterUser`, `AdminListUsers`, `AdminRemoveUser`, `AdminSetRole`, `AdminRegenerateKey`, `AdminMigrate` |++## 暂未实现接口++Go SDK v1 的边界是对齐当前 Python HTTP client,不覆盖所有 server 路由。++| 模块 | 原因 |+|------|------|+| Python embedded 模式 | Go SDK 是纯 HTTP SDK。 |+| 旧 `agent_id` 兼容 | 新 SDK 只使用 `ActorPeerID`。 |+| Privacy config 路由 | 当前属于 server-only 管理面,Python HTTP client 未公开。 |+| Metrics endpoint | Prometheus 文本抓取端点,不是标准 JSON SDK API。 |+| Console/debug/backend-sync/session tool-result 等端点 | 属于运维或 server-only 能力,未纳入 Python HTTP client parity。 |++## 技能和 Watch 示例++```go+_, err := client.AddSkill(ctx, "./skills/search-web", &openviking.AddSkillOptions{+ Wait: true,+})++skills, err := client.ListSkills(ctx, nil)+found, err := client.FindSkills(ctx, "search the web", &openviking.FindSkillsOptions{+ Limit: 5,+})+_, _ = skills, found+```++`AddResource` 在 `WatchInterval > 0` 时会创建 watch;已有任务可用专用 watch 方法管理:++```go+watches, err := client.ListWatches(ctx, &openviking.ListWatchesOptions{+ ActiveOnly: true,+})+updated, err := client.UpdateWatch(ctx, openviking.UpdateWatchOptions{+ ToURI: "viking://resources/docs",+ WatchInterval: openviking.Float64(30),+ IsActive: openviking.Bool(true),+})+triggered, err := client.TriggerWatch(ctx, openviking.WatchRef{+ ToURI: "viking://resources/docs",+})+_, _, _ = watches, updated, triggered+```++## 验证脚本++编辑 `examples/basic_usage/main.go` 顶部常量:++```go+const (+ baseURL = "http://localhost:1933"+ apiKey = "your-key"+)+```++运行:++```bash+cd sdk/go+go run ./examples/basic_usage+```++脚本会创建一个临时 Markdown 文件,导入为 OpenViking resource,读取并更新内容,执行语义检索,验证 watch 和 skill 管理接口,然后创建多消息 session、commit、轮询记忆抽取任务,并检索用户记忆和 peer-scoped 记忆。++## 测试++```bash+cd sdk/go+go test ./...+```diff --git a/sdk/go/admin.go b/sdk/go/admin.gonew file mode 100644index 000000000..079630d17--- /dev/null+++ b/sdk/go/admin.go@@ -0,0 +1,85 @@+package openviking++import (+ "context"+ "net/http"+ "net/url"+)++// AdminCreateAccount creates an account with its first admin user.+func (c *Client) AdminCreateAccount(ctx context.Context, accountID, adminUserID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts", nil, map[string]any{+ "account_id": accountID,+ "admin_user_id": adminUserID,+ }, &result)+ return result, err+}++// AdminListAccounts lists accounts.+func (c *Client) AdminListAccounts(ctx context.Context) ([]any, error) {+ var result []any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts", nil, nil, &result)+ return result, err+}++// AdminDeleteAccount deletes an account and all associated users.+func (c *Client) AdminDeleteAccount(ctx context.Context, accountID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, "/api/v1/admin/accounts/"+url.PathEscape(accountID), nil, nil, &result)+ return result, err+}++// AdminRegisterUser registers a user in an account.+func (c *Client) AdminRegisterUser(ctx context.Context, accountID, userID, role string) (map[string]any, error) {+ if role == "" {+ role = "user"+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users", nil, map[string]any{+ "user_id": userID,+ "role": role,+ }, &result)+ return result, err+}++// AdminListUsers lists users in an account.+func (c *Client) AdminListUsers(ctx context.Context, accountID string) ([]any, error) {+ var result []any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users", nil, nil, &result)+ return result, err+}++// AdminRemoveUser removes a user from an account.+func (c *Client) AdminRemoveUser(ctx context.Context, accountID, userID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users/"+url.PathEscape(userID), nil, nil, &result)+ return result, err+}++// AdminSetRole changes a user's role.+func (c *Client) AdminSetRole(ctx context.Context, accountID, userID, role string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users/"+url.PathEscape(userID)+"/role", nil, map[string]any{+ "role": role,+ }, &result)+ return result, err+}++// AdminRegenerateKey regenerates a user's API key.+func (c *Client) AdminRegenerateKey(ctx context.Context, accountID, userID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/accounts/"+url.PathEscape(accountID)+"/users/"+url.PathEscape(userID)+"/key", nil, nil, &result)+ return result, err+}++// AdminMigrate starts legacy data migration or cleanup.+func (c *Client) AdminMigrate(ctx context.Context, opts *AdminMigrateOptions) (map[string]any, error) {+ action := "migrate"+ if opts != nil && opts.Cleanup {+ action = "cleanup"+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/admin/migrate", nil, map[string]any{"action": action}, &result)+ return result, err+}diff --git a/sdk/go/client.go b/sdk/go/client.gonew file mode 100644index 000000000..62e324979--- /dev/null+++ b/sdk/go/client.go@@ -0,0 +1,78 @@+package openviking++import (+ "fmt"+ "net/http"+ "net/url"+ "strings"+ "time"+)++const defaultTimeout = 60 * time.Second++// Client is an HTTP client for an OpenViking server.+type Client struct {+ baseURL string+ httpClient *http.Client+ apiKey string+ account string+ user string+ actorPeerID string+ extraHeaders map[string]string+ profile bool+ uploadMode string+}++// NewClient creates an OpenViking HTTP client.+func NewClient(cfg Config) (*Client, error) {+ if strings.TrimSpace(cfg.BaseURL) == "" {+ return nil, fmt.Errorf("openviking: BaseURL is required")+ }+ baseURL := strings.TrimRight(cfg.BaseURL, "/")+ parsed, err := url.Parse(baseURL)+ if err != nil || parsed.Scheme == "" || parsed.Host == "" {+ return nil, fmt.Errorf("openviking: invalid BaseURL %q", cfg.BaseURL)+ }++ httpClient := cfg.HTTPClient+ if httpClient == nil {+ timeout := cfg.Timeout+ if timeout == 0 {+ timeout = defaultTimeout+ }+ httpClient = &http.Client{Timeout: timeout}+ }++ headers := make(map[string]string, len(cfg.ExtraHeaders))+ for k, v := range cfg.ExtraHeaders {+ headers[k] = v+ }++ return &Client{+ baseURL: baseURL,+ httpClient: httpClient,+ apiKey: cfg.APIKey,+ account: cfg.Account,+ user: cfg.User,+ actorPeerID: cfg.ActorPeerID,+ extraHeaders: headers,+ profile: cfg.Profile,+ uploadMode: cfg.UploadMode,+ }, nil+}++// CloseIdleConnections closes idle HTTP connections owned by the underlying client.+func (c *Client) CloseIdleConnections() {+ if c == nil || c.httpClient == nil {+ return+ }+ c.httpClient.CloseIdleConnections()+}++// NormalizeURI normalizes a short OpenViking URI into viking:// form.+func NormalizeURI(uri string) string {+ if strings.HasPrefix(uri, "viking://") {+ return uri+ }+ return "viking://" + strings.TrimLeft(uri, "/")+}diff --git a/sdk/go/client_test.go b/sdk/go/client_test.gonew file mode 100644index 000000000..9b7d11cfb--- /dev/null+++ b/sdk/go/client_test.go@@ -0,0 +1,542 @@+package openviking++import (+ "archive/zip"+ "context"+ "encoding/json"+ "errors"+ "io"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func testClient(t *testing.T, handler http.Handler) (*Client, func()) {+ t.Helper()+ server := httptest.NewServer(handler)+ client, err := NewClient(Config{+ BaseURL: server.URL,+ APIKey: "key",+ Account: "acct",+ User: "alice",+ ActorPeerID: "peer-1",+ Profile: true,+ UploadMode: "shared",+ })+ if err != nil {+ t.Fatal(err)+ }+ return client, server.Close+}++func writeOK(t *testing.T, w http.ResponseWriter, result any) {+ t.Helper()+ w.Header().Set("Content-Type", "application/json")+ if err := json.NewEncoder(w).Encode(map[string]any{+ "status": "ok",+ "result": result,+ }); err != nil {+ t.Fatal(err)+ }+}++func writeAPIError(t *testing.T, w http.ResponseWriter, status int, code string, details map[string]any) {+ t.Helper()+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(status)+ if err := json.NewEncoder(w).Encode(map[string]any{+ "status": "error",+ "error": map[string]any{+ "code": code,+ "message": "not found",+ "details": details,+ },+ }); err != nil {+ t.Fatal(err)+ }+}++func readJSONBody(t *testing.T, r *http.Request) map[string]any {+ t.Helper()+ var body map[string]any+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {+ t.Fatal(err)+ }+ return body+}++func TestFindSendsHeadersQueryAndBody(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/v1/search/find" {+ t.Fatalf("path = %s", r.URL.Path)+ }+ if r.Method != http.MethodPost {+ t.Fatalf("method = %s", r.Method)+ }+ if got := r.URL.Query().Get("profile"); got != "1" {+ t.Fatalf("profile query = %q", got)+ }+ if got := r.Header.Get("X-API-Key"); got != "key" {+ t.Fatalf("X-API-Key = %q", got)+ }+ if got := r.Header.Get("X-OpenViking-Account"); got != "acct" {+ t.Fatalf("X-OpenViking-Account = %q", got)+ }+ if got := r.Header.Get("X-OpenViking-User"); got != "alice" {+ t.Fatalf("X-OpenViking-User = %q", got)+ }+ if got := r.Header.Get("X-OpenViking-Actor-Peer"); got != "peer-1" {+ t.Fatalf("X-OpenViking-Actor-Peer = %q", got)+ }+ body := readJSONBody(t, r)+ if got := body["query"]; got != "auth" {+ t.Fatalf("query = %#v", got)+ }+ if got := body["target_uri"]; got != "viking://resources/docs" {+ t.Fatalf("target_uri = %#v", got)+ }+ if got := body["limit"]; got != float64(5) {+ t.Fatalf("limit = %#v", got)+ }+ writeOK(t, w, map[string]any{+ "resources": []map[string]any{+ {"uri": "viking://resources/docs/api.md", "context_type": "resource", "score": 0.9},+ },+ })+ }))+ defer closeServer()++ result, err := client.Find(context.Background(), "auth", &FindOptions{+ TargetURI: "resources/docs",+ Limit: 5,+ ContextType: []string{"resource"},+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(result.Resources) != 1 || result.Resources[0].URI != "viking://resources/docs/api.md" {+ t.Fatalf("unexpected result: %#v", result)+ }+}++func TestErrorEnvelopePreservesCodeDetailsAndStatus(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writeAPIError(t, w, http.StatusNotFound, "NOT_FOUND", map[string]any{"resource": "viking://resources/missing"})+ }))+ defer closeServer()++ _, err := client.Read(context.Background(), "resources/missing", 0, -1)+ if err == nil {+ t.Fatal("expected error")+ }+ var apiErr *Error+ if !errors.As(err, &apiErr) {+ t.Fatalf("expected *Error, got %T", err)+ }+ if apiErr.Code != "NOT_FOUND" || apiErr.StatusCode != http.StatusNotFound {+ t.Fatalf("unexpected error: %#v", apiErr)+ }+ if apiErr.Details["resource"] != "viking://resources/missing" {+ t.Fatalf("details = %#v", apiErr.Details)+ }+}++func TestAddResourceUploadsLocalFile(t *testing.T) {+ dir := t.TempDir()+ filePath := filepath.Join(dir, "note.md")+ if err := os.WriteFile(filePath, []byte("hello"), 0o644); err != nil {+ t.Fatal(err)+ }++ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/v1/resources/temp_upload":+ if err := r.ParseMultipartForm(1 << 20); err != nil {+ t.Fatal(err)+ }+ if got := r.FormValue("upload_mode"); got != "shared" {+ t.Fatalf("upload_mode = %q", got)+ }+ file, header, err := r.FormFile("file")+ if err != nil {+ t.Fatal(err)+ }+ defer file.Close()+ if header.Filename != "note.md" {+ t.Fatalf("filename = %q", header.Filename)+ }+ content, err := io.ReadAll(file)+ if err != nil {+ t.Fatal(err)+ }+ if string(content) != "hello" {+ t.Fatalf("content = %q", string(content))+ }+ writeOK(t, w, map[string]any{"temp_file_id": "tmp-file"})+ case "/api/v1/resources":+ body := readJSONBody(t, r)+ if body["temp_file_id"] != "tmp-file" {+ t.Fatalf("temp_file_id = %#v", body["temp_file_id"])+ }+ if body["source_name"] != "note.md" {+ t.Fatalf("source_name = %#v", body["source_name"])+ }+ if body["directly_upload_media"] != true {+ t.Fatalf("directly_upload_media = %#v", body["directly_upload_media"])+ }+ writeOK(t, w, map[string]any{"uri": "viking://resources/note.md"})+ default:+ t.Fatalf("unexpected path %s", r.URL.Path)+ }+ }))+ defer closeServer()++ result, err := client.AddResource(context.Background(), filePath, nil)+ if err != nil {+ t.Fatal(err)+ }+ if result["uri"] != "viking://resources/note.md" {+ t.Fatalf("result = %#v", result)+ }+}++func TestAddSkillUploadsDirectoryZip(t *testing.T) {+ dir := t.TempDir()+ if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte("# Skill"), 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.Mkdir(filepath.Join(dir, "references"), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "references", "a.md"), []byte("ref"), 0o644); err != nil {+ t.Fatal(err)+ }++ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api/v1/resources/temp_upload":+ reader, err := r.MultipartReader()+ if err != nil {+ t.Fatal(err)+ }+ var zipBytes []byte+ for {+ part, err := reader.NextPart()+ if errors.Is(err, io.EOF) {+ break+ }+ if err != nil {+ t.Fatal(err)+ }+ if part.FormName() == "file" {+ zipBytes, err = io.ReadAll(part)+ if err != nil {+ t.Fatal(err)+ }+ }+ }+ names := zipEntryNames(t, zipBytes)+ if !contains(names, "SKILL.md") || !contains(names, "references/a.md") {+ t.Fatalf("zip names = %#v", names)+ }+ writeOK(t, w, map[string]any{"temp_file_id": "skill-upload"})+ case "/api/v1/skills":+ body := readJSONBody(t, r)+ if body["temp_file_id"] != "skill-upload" {+ t.Fatalf("temp_file_id = %#v", body["temp_file_id"])+ }+ if _, ok := body["data"]; ok {+ t.Fatalf("unexpected data field: %#v", body)+ }+ writeOK(t, w, map[string]any{"uri": "viking://user/skills/demo"})+ default:+ t.Fatalf("unexpected path %s", r.URL.Path)+ }+ }))+ defer closeServer()++ if _, err := client.AddSkill(context.Background(), dir, nil); err != nil {+ t.Fatal(err)+ }+}++func TestSkillManagementRequests(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.Method + " " + r.URL.Path {+ case "GET /api/v1/skills":+ if got := r.URL.Query().Get("node_limit"); got != "77" {+ t.Fatalf("node_limit = %q", got)+ }+ writeOK(t, w, map[string]any{"total": 1})+ case "POST /api/v1/skills/find":+ body := readJSONBody(t, r)+ if body["query"] != "browser automation" || body["limit"] != float64(3) {+ t.Fatalf("find body = %#v", body)+ }+ levels, ok := body["level"].([]any)+ if !ok || len(levels) != 2 || levels[0] != float64(0) || levels[1] != float64(1) {+ t.Fatalf("level = %#v", body["level"])+ }+ writeOK(t, w, map[string]any{"skills": []any{}})+ case "POST /api/v1/skills/validate":+ body := readJSONBody(t, r)+ if body["strict"] != true || body["source_path"] != "SKILL.md" {+ t.Fatalf("validate body = %#v", body)+ }+ writeOK(t, w, map[string]any{"valid": true})+ case "GET /api/v1/skills/demo":+ query := r.URL.Query()+ if query.Get("include_content") != "true" ||+ query.Get("include_files") != "false" ||+ query.Get("include_source") != "true" ||+ query.Get("level") != "1" {+ t.Fatalf("get skill query = %s", r.URL.RawQuery)+ }+ writeOK(t, w, map[string]any{"name": "demo"})+ case "PUT /api/v1/skills/demo":+ body := readJSONBody(t, r)+ if body["wait"] != true {+ t.Fatalf("wait = %#v", body["wait"])+ }+ if _, ok := body["data"].(map[string]any); !ok {+ t.Fatalf("data = %#v", body["data"])+ }+ if _, ok := body["source_metadata"].(map[string]any); !ok {+ t.Fatalf("source_metadata = %#v", body["source_metadata"])+ }+ writeOK(t, w, map[string]any{"updated": true})+ case "DELETE /api/v1/skills/demo":+ writeOK(t, w, map[string]any{"deleted": true})+ default:+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.String())+ }+ }))+ defer closeServer()++ if _, err := client.ListSkills(context.Background(), &ListSkillsOptions{NodeLimit: 77}); err != nil {+ t.Fatal(err)+ }+ threshold := 0.4+ if _, err := client.FindSkills(context.Background(), "browser automation", &FindSkillsOptions{+ Limit: 3,+ ScoreThreshold: &threshold,+ Level: []int{0, 1},+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.ValidateSkill(context.Background(), map[string]any{"name": "demo"}, &ValidateSkillOptions{+ Strict: true,+ SourcePath: "SKILL.md",+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.GetSkill(context.Background(), "demo", &GetSkillOptions{+ IncludeContent: Bool(true),+ IncludeFiles: Bool(false),+ IncludeSource: true,+ Level: Int(1),+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.UpdateSkill(context.Background(), "demo", map[string]any{"name": "demo"}, &UpdateSkillOptions{+ Wait: true,+ SourceMetadata: map[string]any{"source": "test"},+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.DeleteSkill(context.Background(), "demo"); err != nil {+ t.Fatal(err)+ }+}++func TestWatchManagementRequests(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.Method + " " + r.URL.Path {+ case "GET /api/v1/watches":+ query := r.URL.Query()+ if query.Get("active_only") != "true" || query.Get("to_uri") != "viking://resources/guide.md" {+ t.Fatalf("list query = %s", r.URL.RawQuery)+ }+ writeOK(t, w, map[string]any{"total": 1})+ case "GET /api/v1/watches/task-1":+ if got := r.URL.Query().Get("to_uri"); got != "viking://resources/guide.md" {+ t.Fatalf("get to_uri = %q", got)+ }+ writeOK(t, w, map[string]any{"task_id": "task-1"})+ case "PATCH /api/v1/watches/task-1":+ if got := r.URL.Query().Get("to_uri"); got != "viking://resources/guide.md" {+ t.Fatalf("patch to_uri = %q", got)+ }+ body := readJSONBody(t, r)+ if body["watch_interval"] != float64(30) || body["is_active"] != false {+ t.Fatalf("patch body = %#v", body)+ }+ if body["reason"] != "" || body["instruction"] != "refresh docs" {+ t.Fatalf("patch text fields = %#v", body)+ }+ writeOK(t, w, map[string]any{"updated": true})+ case "POST /api/v1/watches/task-1/trigger":+ writeOK(t, w, map[string]any{"triggered": true})+ case "DELETE /api/v1/watches":+ if got := r.URL.Query().Get("to_uri"); got != "viking://resources/guide.md" {+ t.Fatalf("delete to_uri = %q", got)+ }+ writeOK(t, w, map[string]any{"deleted": true})+ default:+ t.Fatalf("unexpected request %s %s", r.Method, r.URL.String())+ }+ }))+ defer closeServer()++ ctx := context.Background()+ if _, err := client.ListWatches(ctx, &ListWatchesOptions{+ ActiveOnly: true,+ ToURI: "resources/guide.md",+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.GetWatch(ctx, "task-1", "resources/guide.md"); err != nil {+ t.Fatal(err)+ }+ if _, err := client.UpdateWatch(ctx, UpdateWatchOptions{+ TaskID: "task-1",+ ToURI: "resources/guide.md",+ WatchInterval: Float64(30),+ IsActive: Bool(false),+ Reason: String(""),+ Instruction: String("refresh docs"),+ }); err != nil {+ t.Fatal(err)+ }+ if _, err := client.TriggerWatch(ctx, WatchRef{TaskID: "task-1"}); err != nil {+ t.Fatal(err)+ }+ if _, err := client.DeleteWatch(ctx, WatchRef{ToURI: "resources/guide.md"}); err != nil {+ t.Fatal(err)+ }+}++func zipEntryNames(t *testing.T, content []byte) []string {+ t.Helper()+ reader, err := zip.NewReader(strings.NewReader(string(content)), int64(len(content)))+ if err != nil {+ t.Fatal(err)+ }+ names := make([]string, 0, len(reader.File))+ for _, f := range reader.File {+ names = append(names, f.Name)+ }+ return names+}++func contains(values []string, want string) bool {+ for _, value := range values {+ if value == want {+ return true+ }+ }+ return false+}++func TestExportOVPackWritesFile(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/api/v1/pack/export" {+ t.Fatalf("path = %s", r.URL.Path)+ }+ body := readJSONBody(t, r)+ if body["uri"] != "viking://resources/docs" {+ t.Fatalf("uri = %#v", body["uri"])+ }+ w.Header().Set("Content-Type", "application/octet-stream")+ if _, err := w.Write([]byte("OVPACK")); err != nil {+ t.Fatal(err)+ }+ }))+ defer closeServer()++ outPath, err := client.ExportOVPack(context.Background(), "resources/docs", t.TempDir(), nil)+ if err != nil {+ t.Fatal(err)+ }+ content, err := os.ReadFile(outPath)+ if err != nil {+ t.Fatal(err)+ }+ if string(content) != "OVPACK" {+ t.Fatalf("content = %q", string(content))+ }+}++func TestSessionExistsHandlesNotFound(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ writeAPIError(t, w, http.StatusNotFound, "NOT_FOUND", map[string]any{"type": "session"})+ }))+ defer closeServer()++ exists, err := client.SessionExists(context.Background(), "missing")+ if err != nil {+ t.Fatal(err)+ }+ if exists {+ t.Fatal("expected missing session")+ }+}++func TestListTasksRequest(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet {+ t.Fatalf("method = %s", r.Method)+ }+ if r.URL.Path != "/api/v1/tasks" {+ t.Fatalf("path = %s", r.URL.Path)+ }+ query := r.URL.Query()+ if query.Get("task_type") != "session_commit" ||+ query.Get("status") != "running" ||+ query.Get("resource_id") != "session-1" ||+ query.Get("limit") != "20" {+ t.Fatalf("query = %s", r.URL.RawQuery)+ }+ writeOK(t, w, []map[string]any{+ {"task_id": "task-1", "status": "running"},+ })+ }))+ defer closeServer()++ tasks, err := client.ListTasks(context.Background(), &ListTasksOptions{+ TaskType: "session_commit",+ Status: "running",+ ResourceID: "session-1",+ Limit: 20,+ })+ if err != nil {+ t.Fatal(err)+ }+ if len(tasks) != 1 {+ t.Fatalf("tasks = %#v", tasks)+ }+}++func TestHealth(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/health" {+ t.Fatalf("path = %s", r.URL.Path)+ }+ w.Header().Set("Content-Type", "application/json")+ if _, err := w.Write([]byte(`{"status":"ok"}`)); err != nil {+ t.Fatal(err)+ }+ }))+ defer closeServer()++ ok, err := client.Health(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ if !ok {+ t.Fatal("expected healthy")+ }+}diff --git a/sdk/go/errors.go b/sdk/go/errors.gonew file mode 100644index 000000000..ccf1e9e63--- /dev/null+++ b/sdk/go/errors.go@@ -0,0 +1,37 @@+package openviking++import (+ "errors"+ "fmt"+)++// Error is returned for OpenViking API failures.+type Error struct {+ Code string+ Message string+ Details map[string]any+ StatusCode int+}++func (e *Error) Error() string {+ if e == nil {+ return "<nil>"+ }+ if e.Code == "" {+ return e.Message+ }+ return fmt.Sprintf("%s: %s", e.Code, e.Message)+}++// IsCode reports whether err is an OpenViking API error with the given code.+func IsCode(err error, code string) bool {+ var apiErr *Error+ return errors.As(err, &apiErr) && apiErr.Code == code+}++// ErrorInfo mirrors the API error object inside an OpenViking response envelope.+type ErrorInfo struct {+ Code string `json:"code"`+ Message string `json:"message"`+ Details map[string]any `json:"details,omitempty"`+}diff --git a/sdk/go/examples/basic_usage/main.go b/sdk/go/examples/basic_usage/main.gonew file mode 100644index 000000000..aa4e1db7a--- /dev/null+++ b/sdk/go/examples/basic_usage/main.go@@ -0,0 +1,439 @@+package main++import (+ "context"+ "fmt"+ "log"+ "os"+ "path/filepath"+ "time"++ openviking "github.com/volcengine/OpenViking/sdk/go"+)++const (+ baseURL = "http://localhost:1940"+ apiKey = "" // Set this when your OpenViking server requires authentication.+)++func main() {+ ctx := context.Background()++ client, err := openviking.NewClient(openviking.Config{+ BaseURL: baseURL,+ APIKey: apiKey,+ Timeout: 120 * time.Second,+ })+ if err != nil {+ log.Fatal(err)+ }+ defer client.CloseIdleConnections()++ fmt.Println("1. Health check")+ healthy, err := client.Health(ctx)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" healthy=%v\n", healthy)++ tmpFile := createDemoFile()+ defer os.RemoveAll(filepath.Dir(tmpFile))++ resourceRoot := fmt.Sprintf(+ "viking://resources/go-sdk-smoke/%d",+ time.Now().Unix(),+ )+ resourceURI := resourceRoot + "/demo.md"++ fmt.Println("2. Add local resource")+ resource, err := client.AddResource(ctx, tmpFile, &openviking.AddResourceOptions{+ To: resourceRoot,+ Reason: "Go SDK smoke test",+ Wait: true,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" resource=%v\n", resource)++ fmt.Println("3. Wait for background processing")+ waitResult, err := client.WaitProcessed(ctx, &openviking.WaitProcessedOptions{+ Timeout: openviking.Float64(120),+ })+ if err != nil {+ fmt.Printf(" wait warning: %v\n", err)+ } else {+ fmt.Printf(" wait=%v\n", waitResult)+ }++ fmt.Println("4. List and read the resource")+ entries, err := client.List(ctx, resourceRoot, &openviking.ListOptions{+ Recursive: true,+ Simple: true,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" entries=%v\n", entries)++ content, err := client.Read(ctx, resourceURI, 0, -1)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" read=%q\n", content)++ fmt.Println("5. Write and find")+ _, err = client.Write(ctx, resourceURI, content+"\n\nGo SDK write check.", &openviking.WriteOptions{+ Mode: "replace",+ Wait: true,+ })+ if err != nil {+ log.Fatal(err)+ }++ findResult, err := client.Find(ctx, "Go SDK smoke test", &openviking.FindOptions{+ TargetURI: "viking://resources/go-sdk-smoke",+ Limit: 5,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" find resources=%d memories=%d skills=%d\n",+ len(findResult.Resources),+ len(findResult.Memories),+ len(findResult.Skills),+ )+ for _, item := range findResult.Resources {+ fmt.Printf(" - %s score=%.3f\n", item.URI, item.Score)+ }++ watchRoot := resourceRoot + "-watch"+ fmt.Println("6. Watch management")+ watchResource, err := client.AddResource(ctx, tmpFile, &openviking.AddResourceOptions{+ To: watchRoot,+ Reason: "Go SDK watch smoke test",+ Wait: true,+ WatchInterval: 60,+ })+ if err != nil {+ fmt.Printf(" watch create skipped: %v\n", err)+ } else {+ fmt.Printf(" watch resource=%v\n", watchResource)+ defer func() {+ if _, err := client.DeleteWatch(context.Background(), openviking.WatchRef{ToURI: watchRoot}); err != nil {+ fmt.Printf(" watch cleanup warning: %v\n", err)+ }+ }()++ watches, err := client.ListWatches(ctx, &openviking.ListWatchesOptions{+ ActiveOnly: true,+ ToURI: watchRoot,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" watch=%v\n", watches)++ paused, err := client.UpdateWatch(ctx, openviking.UpdateWatchOptions{+ ToURI: watchRoot,+ IsActive: openviking.Bool(false),+ Reason: openviking.String("Paused by Go SDK smoke test"),+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" paused=%v\n", paused)++ resumed, err := client.UpdateWatch(ctx, openviking.UpdateWatchOptions{+ ToURI: watchRoot,+ IsActive: openviking.Bool(true),+ WatchInterval: openviking.Float64(60),+ Instruction: openviking.String("Refresh this resource for Go SDK smoke validation."),+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" resumed=%v\n", resumed)++ triggered, err := client.TriggerWatch(ctx, openviking.WatchRef{ToURI: watchRoot})+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" triggered=%v\n", triggered)+ }++ fmt.Println("7. Skill management")+ skillName := fmt.Sprintf("go-sdk-smoke-%d", time.Now().Unix())+ skillDir := createDemoSkill(skillName, "Validate the OpenViking Go SDK smoke flow.")+ defer os.RemoveAll(skillDir)++ validation, err := client.ValidateSkill(ctx, map[string]any{+ "name": skillName,+ "description": "Validate the OpenViking Go SDK smoke flow.",+ "content": "# " + skillName + "\n\nUse this skill to validate the Go SDK smoke flow.",+ }, &openviking.ValidateSkillOptions{+ Strict: true,+ SkillDirName: skillName,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" validation=%v\n", validation)++ skill, err := client.AddSkill(ctx, skillDir, &openviking.AddSkillOptions{+ Wait: true,+ Timeout: openviking.Float64(120),+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" skill=%v\n", skill)+ defer func() {+ if _, err := client.DeleteSkill(context.Background(), skillName); err != nil {+ fmt.Printf(" skill cleanup warning: %v\n", err)+ }+ }()++ skills, err := client.ListSkills(ctx, nil)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" skills total=%v\n", skills["total"])++ gotSkill, err := client.GetSkill(ctx, skillName, &openviking.GetSkillOptions{+ IncludeContent: openviking.Bool(true),+ IncludeFiles: openviking.Bool(true),+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" got skill name=%v files=%v\n", gotSkill["name"], gotSkill["files"])++ updateDemoSkill(skillDir, skillName, "Updated by Go SDK smoke test.")+ updatedSkill, err := client.UpdateSkill(ctx, skillName, skillDir, &openviking.UpdateSkillOptions{+ Wait: true,+ Timeout: openviking.Float64(120),+ SourceMetadata: map[string]any{+ "type": "example",+ "operation": "basic_usage",+ },+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" updated skill=%v\n", updatedSkill)++ foundSkills, err := client.FindSkills(ctx, "Go SDK smoke validation", &openviking.FindSkillsOptions{+ Limit: 5,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" found skills total=%v\n", foundSkills["total"])++ fmt.Println("8. Session message and commit")+ sessionID := fmt.Sprintf("go-sdk-smoke-%d", time.Now().Unix())+ memoryMarker := "go-sdk-memory-marker-" + sessionID+ peerID := "go-sdk-peer-" + sessionID+ peerMarker := "go-sdk-peer-marker-" + sessionID+ session, err := client.CreateSession(ctx, &openviking.CreateSessionOptions{+ SessionID: sessionID,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" session=%v\n", session)++ messages := []openviking.Message{+ {+ Role: "user",+ Content: openviking.String("Please remember this durable Go SDK validation marker: " + memoryMarker + "."),+ },+ {+ Role: "assistant",+ Content: openviking.String("Understood. I will remember that the Go SDK validation marker is " + memoryMarker + "."),+ },+ {+ Role: "user",+ Content: openviking.String(+ "My OpenViking Go SDK preference is that examples should exercise resources, watches, skills, session commits, and memory retrieval without requiring Account or User constants.",+ ),+ },+ {+ Role: "assistant",+ Content: openviking.String(+ "I will treat that as a durable preference for the OpenViking Go SDK example workflow.",+ ),+ },+ {+ Role: "user",+ PeerID: peerID,+ Content: openviking.String(+ "I am the peer for this smoke test. Please remember my peer marker " + peerMarker + " and that I care about peer-scoped memory retrieval.",+ ),+ },+ {+ Role: "assistant",+ Content: openviking.String(+ "I will remember that peer " + peerID + " uses marker " + peerMarker + " for peer-scoped Go SDK validation.",+ ),+ },+ }+ batch, err := client.BatchAddMessages(ctx, sessionID, messages, nil)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" batch messages=%v\n", batch)++ sessionContext, err := client.GetSessionContext(ctx, sessionID, 4096)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" context=%v\n", sessionContext)++ commit, err := client.CommitSession(ctx, sessionID, &openviking.CommitSessionOptions{+ KeepRecentCount: 0,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" commit=%v\n", commit)++ if taskID, _ := commit["task_id"].(string); taskID != "" {+ task, err := waitForTask(ctx, client, taskID, 3*time.Minute)+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" commit task=%v\n", task)+ } else {+ fmt.Println(" commit did not create a background task; no messages were archived.")+ }+ tasks, err := client.ListTasks(ctx, &openviking.ListTasksOptions{+ TaskType: "session_commit",+ ResourceID: sessionID,+ Limit: 5,+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" recent session commit tasks=%d\n", len(tasks))++ memoryResults, err := client.Find(ctx, memoryMarker, &openviking.FindOptions{+ TargetURI: "viking://user/memories",+ Limit: 5,+ ContextType: []string{"memory"},+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" memory hits=%d\n", len(memoryResults.Memories))+ for _, item := range memoryResults.Memories {+ fmt.Printf(" - memory %s score=%.3f\n", item.URI, item.Score)+ }+ if len(memoryResults.Memories) == 0 {+ fmt.Printf(" memory retrieval warning: no memory hit for marker %q\n", memoryMarker)+ }++ peerClient, err := openviking.NewClient(openviking.Config{+ BaseURL: baseURL,+ APIKey: apiKey,+ ActorPeerID: peerID,+ Timeout: 120 * time.Second,+ })+ if err != nil {+ log.Fatal(err)+ }+ defer peerClient.CloseIdleConnections()++ peerMemoryResults, err := peerClient.Find(ctx, peerMarker, &openviking.FindOptions{+ TargetURI: "viking://user/memories",+ Limit: 5,+ ContextType: []string{"memory"},+ })+ if err != nil {+ log.Fatal(err)+ }+ fmt.Printf(" peer memory hits=%d peer_id=%s\n", len(peerMemoryResults.Memories), peerID)+ for _, item := range peerMemoryResults.Memories {+ fmt.Printf(" - peer memory %s score=%.3f\n", item.URI, item.Score)+ }+ if len(peerMemoryResults.Memories) == 0 {+ fmt.Printf(" peer memory retrieval warning: no memory hit for marker %q\n", peerMarker)+ }++ fmt.Println("Go SDK smoke test completed.")+}++func createDemoFile() string {+ dir, err := os.MkdirTemp("", "openviking-go-sdk-smoke-*")+ if err != nil {+ log.Fatal(err)+ }+ path := filepath.Join(dir, "demo.md")+ content := `# OpenViking Go SDK Smoke Test++This file was created by sdk/go/examples/basic_usage.++It verifies resource, watch, skill, retrieval, session commit, memory retrieval, and peer-scoped memory APIs.+`+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {+ log.Fatal(err)+ }+ return path+}++func createDemoSkill(name string, description string) string {+ dir, err := os.MkdirTemp("", name+"-*")+ if err != nil {+ log.Fatal(err)+ }+ writeDemoSkill(dir, name, description)+ return dir+}++func updateDemoSkill(dir string, name string, description string) {+ writeDemoSkill(dir, name, description)+}++func writeDemoSkill(dir string, name string, description string) {+ content := fmt.Sprintf(`---+name: %s+description: %s+---++# %s++Use this temporary skill to validate OpenViking Go SDK skill management.++## When To Use++Use it only while running sdk/go/examples/basic_usage.+`, name, description, name)+ if err := os.WriteFile(filepath.Join(dir, "SKILL.md"), []byte(content), 0o644); err != nil {+ log.Fatal(err)+ }+}++func waitForTask(ctx context.Context, client *openviking.Client, taskID string, timeout time.Duration) (map[string]any, error) {+ deadline := time.Now().Add(timeout)+ for {+ task, err := client.GetTask(ctx, taskID)+ if err != nil {+ return nil, err+ }+ if task != nil {+ status := fmt.Sprint(task["status"])+ stage := fmt.Sprint(task["stage"])+ if status == "completed" || stage == "completed" {+ return task, nil+ }+ if status == "failed" || status == "error" || stage == "failed" || stage == "error" {+ return task, fmt.Errorf("task %s ended with status=%s stage=%s", taskID, status, stage)+ }+ }+ if time.Now().After(deadline) {+ return task, fmt.Errorf("timed out waiting for task %s", taskID)+ }+ time.Sleep(2 * time.Second)+ }+}diff --git a/sdk/go/filesystem.go b/sdk/go/filesystem.gonew file mode 100644index 000000000..ca003d7c3--- /dev/null+++ b/sdk/go/filesystem.go@@ -0,0 +1,171 @@+package openviking++import (+ "context"+ "net/http"+ "net/url"+)++// List lists directory contents.+func (c *Client) List(ctx context.Context, uri string, opts *ListOptions) ([]any, error) {+ if opts == nil {+ opts = &ListOptions{Output: "original", AbsLimit: 256, NodeLimit: 1000}+ }+ output := opts.Output+ if output == "" {+ output = "original"+ }+ absLimit := opts.AbsLimit+ if absLimit == 0 {+ absLimit = 256+ }+ nodeLimit := opts.NodeLimit+ if nodeLimit == 0 {+ nodeLimit = 1000+ }+ query := url.Values{}+ query.Set("uri", NormalizeURI(uri))+ queryBool(query, "simple", opts.Simple)+ queryBool(query, "recursive", opts.Recursive)+ query.Set("output", output)+ queryInt(query, "abs_limit", absLimit)+ queryBool(query, "show_all_hidden", opts.ShowAllHidden)+ queryInt(query, "node_limit", nodeLimit)+ var result []any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/fs/ls", query, nil, &result)+ return result, err+}++// Tree returns a directory tree.+func (c *Client) Tree(ctx context.Context, uri string, opts *TreeOptions) ([]map[string]any, error) {+ if opts == nil {+ opts = &TreeOptions{Output: "original", AbsLimit: 128, NodeLimit: 1000}+ }+ output := opts.Output+ if output == "" {+ output = "original"+ }+ absLimit := opts.AbsLimit+ if absLimit == 0 {+ absLimit = 128+ }+ nodeLimit := opts.NodeLimit+ if nodeLimit == 0 {+ nodeLimit = 1000+ }+ query := url.Values{}+ query.Set("uri", NormalizeURI(uri))+ query.Set("output", output)+ queryInt(query, "abs_limit", absLimit)+ queryBool(query, "show_all_hidden", opts.ShowAllHidden)+ queryInt(query, "node_limit", nodeLimit)+ var result []map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/fs/tree", query, nil, &result)+ return result, err+}++// Stat returns metadata for a URI.+func (c *Client) Stat(ctx context.Context, uri string) (map[string]any, error) {+ query := url.Values{"uri": []string{NormalizeURI(uri)}}+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/fs/stat", query, nil, &result)+ return result, err+}++// Mkdir creates a directory.+func (c *Client) Mkdir(ctx context.Context, uri string, description string) error {+ payload := map[string]any{"uri": NormalizeURI(uri)}+ setString(payload, "description", description)+ return c.doJSON(ctx, http.MethodPost, "/api/v1/fs/mkdir", nil, payload, nil)+}++// Remove deletes a URI.+func (c *Client) Remove(ctx context.Context, uri string, opts *RemoveOptions) error {+ if opts == nil {+ opts = &RemoveOptions{}+ }+ query := url.Values{}+ query.Set("uri", NormalizeURI(uri))+ queryBool(query, "recursive", opts.Recursive)+ queryBool(query, "wait", opts.Wait)+ if opts.Timeout != nil {+ queryFloat(query, "timeout", *opts.Timeout)+ }+ return c.doJSON(ctx, http.MethodDelete, "/api/v1/fs", query, nil, nil)+}++// Move moves a URI to another URI.+func (c *Client) Move(ctx context.Context, fromURI, toURI string) error {+ return c.doJSON(ctx, http.MethodPost, "/api/v1/fs/mv", nil, map[string]any{+ "from_uri": NormalizeURI(fromURI),+ "to_uri": NormalizeURI(toURI),+ }, nil)+}++// Read reads file content.+func (c *Client) Read(ctx context.Context, uri string, offset int, limit int) (string, error) {+ query := url.Values{}+ query.Set("uri", NormalizeURI(uri))+ queryInt(query, "offset", offset)+ queryInt(query, "limit", limit)+ var result string+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/content/read", query, nil, &result)+ return result, err+}++// Abstract reads L0 abstract content.+func (c *Client) Abstract(ctx context.Context, uri string) (string, error) {+ query := url.Values{"uri": []string{NormalizeURI(uri)}}+ var result string+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/content/abstract", query, nil, &result)+ return result, err+}++// Overview reads L1 overview content.+func (c *Client) Overview(ctx context.Context, uri string) (string, error) {+ query := url.Values{"uri": []string{NormalizeURI(uri)}}+ var result string+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/content/overview", query, nil, &result)+ return result, err+}++// Write writes text content and refreshes related semantics/vectors.+func (c *Client) Write(ctx context.Context, uri string, content string, opts *WriteOptions) (map[string]any, error) {+ if opts == nil {+ opts = &WriteOptions{Mode: "replace"}+ }+ mode := opts.Mode+ if mode == "" {+ mode = "replace"+ }+ payload := map[string]any{+ "uri": NormalizeURI(uri),+ "content": content,+ "mode": mode,+ "wait": opts.Wait,+ }+ setFloatPtr(payload, "timeout", opts.Timeout)+ setAny(payload, "telemetry", opts.Telemetry)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/content/write", nil, payload, &result)+ return result, err+}++// Reindex triggers reindexing for a URI.+func (c *Client) Reindex(ctx context.Context, uri string, opts *ReindexOptions) (map[string]any, error) {+ if opts == nil {+ opts = &ReindexOptions{Mode: "vectors_only", Wait: true}+ }+ mode := opts.Mode+ if mode == "" {+ mode = "vectors_only"+ }+ payload := map[string]any{+ "uri": NormalizeURI(uri),+ "mode": mode,+ "wait": opts.Wait,+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/content/reindex", nil, payload, &result)+ return result, err+}diff --git a/sdk/go/go.mod b/sdk/go/go.modnew file mode 100644index 000000000..0fbb95958--- /dev/null+++ b/sdk/go/go.mod@@ -0,0 +1,3 @@+module github.com/volcengine/OpenViking/sdk/go++go 1.22diff --git a/sdk/go/helpers.go b/sdk/go/helpers.gonew file mode 100644index 000000000..b1c506e62--- /dev/null+++ b/sdk/go/helpers.go@@ -0,0 +1,93 @@+package openviking++import (+ "net/url"+ "strconv"+)++func setString(m map[string]any, key, value string) {+ if value != "" {+ m[key] = value+ }+}++func setAny(m map[string]any, key string, value any) {+ if value != nil {+ m[key] = value+ }+}++func setQueryString(values url.Values, key, value string) {+ if value != "" {+ values.Set(key, value)+ }+}++func setFloatPtr(m map[string]any, key string, value *float64) {+ if value != nil {+ m[key] = *value+ }+}++func boolValue(ptr *bool, fallback bool) bool {+ if ptr == nil {+ return fallback+ }+ return *ptr+}++// String returns a string pointer for request fields that must distinguish empty from omitted.+func String(s string) *string {+ return &s+}++// Bool returns a bool pointer for optional request fields.+func Bool(v bool) *bool {+ return &v+}++// Int returns an int pointer for optional request fields.+func Int(v int) *int {+ return &v+}++// Float64 returns a float64 pointer for optional request fields.+func Float64(v float64) *float64 {+ return &v+}++func queryBool(values url.Values, key string, value bool) {+ values.Set(key, strconv.FormatBool(value))+}++func queryInt(values url.Values, key string, value int) {+ values.Set(key, strconv.Itoa(value))+}++func queryFloat(values url.Values, key string, value float64) {+ values.Set(key, strconv.FormatFloat(value, 'f', -1, 64))+}++func normalizeTarget(target any) any {+ switch v := target.(type) {+ case nil:+ return ""+ case string:+ if v == "" {+ return ""+ }+ return NormalizeURI(v)+ case []string:+ uris := make([]string, 0, len(v))+ for _, uri := range v {+ if uri == "" {+ uris = append(uris, uri)+ } else {+ uris = append(uris, NormalizeURI(uri))+ }+ }+ return uris+ default:+ return v+ }+}diff --git a/sdk/go/pack.go b/sdk/go/pack.gonew file mode 100644index 000000000..a9f02a8f6--- /dev/null+++ b/sdk/go/pack.go@@ -0,0 +1,144 @@+package openviking++import (+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "strings"+)++// ExportOVPack exports a URI into a local .ovpack file.+func (c *Client) ExportOVPack(ctx context.Context, uri, to string, opts *PackOptions) (string, error) {+ includeVectors := opts != nil && opts.IncludeVectors+ outPath := packOutputPath(to, uri, "export")+ err := c.downloadPack(ctx, "/api/v1/pack/export", map[string]any{+ "uri": NormalizeURI(uri),+ "include_vectors": includeVectors,+ }, outPath)+ return outPath, err+}++// BackupOVPack backs up public scopes into a local restore-only .ovpack file.+func (c *Client) BackupOVPack(ctx context.Context, to string, opts *PackOptions) (string, error) {+ includeVectors := opts != nil && opts.IncludeVectors+ outPath := packOutputPath(to, "", "openviking-backup")+ err := c.downloadPack(ctx, "/api/v1/pack/backup", map[string]any{+ "include_vectors": includeVectors,+ }, outPath)+ return outPath, err+}++func packOutputPath(to, uri, fallback string) string {+ if to == "" {+ to = "."+ }+ out := to+ if info, err := os.Stat(to); err == nil && info.IsDir() {+ name := fallback+ if uri != "" {+ trimmed := strings.TrimRight(strings.TrimSpace(uri), "/")+ if last := filepath.Base(trimmed); last != "." && last != "/" && last != "" {+ name = last+ }+ }+ out = filepath.Join(to, name+".ovpack")+ } else if !strings.HasSuffix(out, ".ovpack") {+ out += ".ovpack"+ }+ return out+}++func (c *Client) downloadPack(ctx context.Context, path string, payload map[string]any, outPath string) error {+ if err := os.MkdirAll(filepath.Dir(outPath), 0o755); err != nil {+ return err+ }+ body, err := json.Marshal(payload)+ if err != nil {+ return err+ }+ req, err := c.newRequest(ctx, http.MethodPost, path, nil, strings.NewReader(string(body)))+ if err != nil {+ return err+ }+ req.Header.Set("Content-Type", "application/json")+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ data, readErr := io.ReadAll(resp.Body)+ if readErr != nil {+ return readErr+ }+ env, err := decodeEnvelope(resp.StatusCode, data)+ if err != nil {+ return err+ }+ if env.Error != nil {+ return apiError(resp.StatusCode, env.Error)+ }+ return &Error{Code: "UNKNOWN", Message: envelopeDetail(env, resp.StatusCode, data), StatusCode: resp.StatusCode}+ }+ file, err := os.Create(outPath)+ if err != nil {+ return err+ }+ defer file.Close()+ _, err = io.Copy(file, resp.Body)+ return err+}++// ImportOVPack imports a local .ovpack under parent.+func (c *Client) ImportOVPack(ctx context.Context, filePath, parent string, opts *ImportPackOptions) (string, error) {+ tempID, err := c.uploadPackFile(ctx, filePath)+ if err != nil {+ return "", err+ }+ payload := map[string]any{+ "parent": NormalizeURI(parent),+ "temp_file_id": tempID,+ }+ if opts != nil {+ setString(payload, "on_conflict", opts.OnConflict)+ setString(payload, "vector_mode", opts.VectorMode)+ }+ var result struct {+ URI string `json:"uri"`+ }+ err = c.doJSON(ctx, http.MethodPost, "/api/v1/pack/import", nil, payload, &result)+ return result.URI, err+}++// RestoreOVPack restores a local backup .ovpack.+func (c *Client) RestoreOVPack(ctx context.Context, filePath string, opts *ImportPackOptions) (string, error) {+ tempID, err := c.uploadPackFile(ctx, filePath)+ if err != nil {+ return "", err+ }+ payload := map[string]any{"temp_file_id": tempID}+ if opts != nil {+ setString(payload, "on_conflict", opts.OnConflict)+ setString(payload, "vector_mode", opts.VectorMode)+ }+ var result struct {+ URI string `json:"uri"`+ }+ err = c.doJSON(ctx, http.MethodPost, "/api/v1/pack/restore", nil, payload, &result)+ return result.URI, err+}++func (c *Client) uploadPackFile(ctx context.Context, filePath string) (string, error) {+ info, err := os.Stat(filePath)+ if err != nil {+ return "", err+ }+ if info.IsDir() {+ return "", fmt.Errorf("openviking: %s is a directory, expected .ovpack file", filePath)+ }+ return c.uploadTempFile(ctx, filePath)+}diff --git a/sdk/go/resources.go b/sdk/go/resources.gonew file mode 100644index 000000000..5c54b3a4a--- /dev/null+++ b/sdk/go/resources.go@@ -0,0 +1,45 @@+package openviking++import (+ "context"+ "fmt"+ "net/http"+)++// AddResource imports a local path or remote URL into OpenViking resources.+func (c *Client) AddResource(ctx context.Context, path string, opts *AddResourceOptions) (map[string]any, error) {+ if opts == nil {+ opts = &AddResourceOptions{}+ }+ if opts.To != "" && opts.Parent != "" {+ return nil, fmt.Errorf("openviking: cannot specify both To and Parent")+ }+ payload := map[string]any{+ "reason": opts.Reason,+ "instruction": opts.Instruction,+ "wait": opts.Wait,+ "strict": opts.Strict,+ "directly_upload_media": boolValue(opts.DirectlyUploadMedia, true),+ "watch_interval": opts.WatchInterval,+ "args": map[string]any{},+ }+ setString(payload, "to", opts.To)+ setString(payload, "parent", opts.Parent)+ setString(payload, "ignore_dirs", opts.IgnoreDirs)+ setString(payload, "include", opts.Include)+ setString(payload, "exclude", opts.Exclude)+ setFloatPtr(payload, "timeout", opts.Timeout)+ if opts.PreserveStructure != nil {+ payload["preserve_structure"] = *opts.PreserveStructure+ }+ setAny(payload, "telemetry", opts.Telemetry)+ if opts.Args != nil {+ payload["args"] = opts.Args+ }+ if err := c.addLocalUpload(ctx, payload, path, true); err != nil {+ return nil, err+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/resources", nil, payload, &result)+ return result, err+}diff --git a/sdk/go/retrieval.go b/sdk/go/retrieval.gonew file mode 100644index 000000000..dac7931c0--- /dev/null+++ b/sdk/go/retrieval.go@@ -0,0 +1,95 @@+package openviking++import (+ "context"+ "net/http"+)++// Find performs semantic search without session context.+func (c *Client) Find(ctx context.Context, queryText string, opts *FindOptions) (*FindResult, error) {+ if opts == nil {+ opts = &FindOptions{}+ }+ limit := opts.Limit+ if limit == 0 {+ limit = 10+ }+ actualLimit := limit+ if opts.NodeLimit != nil {+ actualLimit = *opts.NodeLimit+ }+ payload := map[string]any{+ "query": queryText,+ "target_uri": normalizeTarget(opts.TargetURI),+ "limit": actualLimit,+ }+ setAny(payload, "score_threshold", opts.ScoreThreshold)+ setAny(payload, "filter", opts.Filter)+ setAny(payload, "context_type", opts.ContextType)+ setAny(payload, "telemetry", opts.Telemetry)+ var result FindResult+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/search/find", nil, payload, &result)+ return &result, err+}++// Search performs semantic search with optional session context.+func (c *Client) Search(ctx context.Context, queryText string, opts *SearchOptions) (*FindResult, error) {+ if opts == nil {+ opts = &SearchOptions{}+ }+ limit := opts.Limit+ if limit == 0 {+ limit = 10+ }+ actualLimit := limit+ if opts.NodeLimit != nil {+ actualLimit = *opts.NodeLimit+ }+ payload := map[string]any{+ "query": queryText,+ "target_uri": normalizeTarget(opts.TargetURI),+ "limit": actualLimit,+ }+ setString(payload, "session_id", opts.SessionID)+ setAny(payload, "score_threshold", opts.ScoreThreshold)+ setAny(payload, "filter", opts.Filter)+ setAny(payload, "context_type", opts.ContextType)+ setAny(payload, "telemetry", opts.Telemetry)+ var result FindResult+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/search/search", nil, payload, &result)+ return &result, err+}++// Grep searches file content by pattern.+func (c *Client) Grep(ctx context.Context, uri, pattern string, opts *GrepOptions) (map[string]any, error) {+ if opts == nil {+ opts = &GrepOptions{}+ }+ payload := map[string]any{+ "uri": NormalizeURI(uri),+ "pattern": pattern,+ "case_insensitive": opts.CaseInsensitive,+ }+ if opts.NodeLimit != nil {+ payload["node_limit"] = *opts.NodeLimit+ }+ if opts.ExcludeURI != "" {+ payload["exclude_uri"] = NormalizeURI(opts.ExcludeURI)+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/search/grep", nil, payload, &result)+ return result, err+}++// Glob finds files by glob pattern.+func (c *Client) Glob(ctx context.Context, pattern string, uri string) (map[string]any, error) {+ if uri == "" {+ uri = "viking://"+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/search/glob", nil, map[string]any{+ "pattern": pattern,+ "uri": NormalizeURI(uri),+ }, &result)+ return result, err+}diff --git a/sdk/go/sessions.go b/sdk/go/sessions.gonew file mode 100644index 000000000..ba740980f--- /dev/null+++ b/sdk/go/sessions.go@@ -0,0 +1,153 @@+package openviking++import (+ "context"+ "errors"+ "fmt"+ "net/http"+ "net/url"+)++// CreateSession creates a session.+func (c *Client) CreateSession(ctx context.Context, opts *CreateSessionOptions) (map[string]any, error) {+ if opts == nil {+ opts = &CreateSessionOptions{}+ }+ payload := map[string]any{}+ setString(payload, "session_id", opts.SessionID)+ setAny(payload, "memory_policy", opts.MemoryPolicy)+ setAny(payload, "telemetry", opts.Telemetry)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions", nil, payload, &result)+ return result, err+}++// ListSessions lists sessions.+func (c *Client) ListSessions(ctx context.Context) ([]any, error) {+ var result []any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/sessions", nil, nil, &result)+ return result, err+}++// GetSession returns session details.+func (c *Client) GetSession(ctx context.Context, sessionID string, opts *GetSessionOptions) (map[string]any, error) {+ query := url.Values{}+ if opts != nil && opts.AutoCreate {+ query.Set("auto_create", "true")+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/sessions/"+url.PathEscape(sessionID), query, nil, &result)+ return result, err+}++// SessionExists reports whether a session exists.+func (c *Client) SessionExists(ctx context.Context, sessionID string) (bool, error) {+ _, err := c.GetSession(ctx, sessionID, nil)+ if err == nil {+ return true, nil+ }+ if IsCode(err, "NOT_FOUND") {+ return false, nil+ }+ return false, err+}++// GetSessionContext returns assembled session context.+func (c *Client) GetSessionContext(ctx context.Context, sessionID string, tokenBudget int) (map[string]any, error) {+ if tokenBudget == 0 {+ tokenBudget = 128000+ }+ query := url.Values{}+ queryInt(query, "token_budget", tokenBudget)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/context", query, nil, &result)+ return result, err+}++// GetSessionArchive returns one completed archive.+func (c *Client) GetSessionArchive(ctx context.Context, sessionID, archiveID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/archives/"+url.PathEscape(archiveID), nil, nil, &result)+ return result, err+}++// DeleteSession deletes a session.+func (c *Client) DeleteSession(ctx context.Context, sessionID string) error {+ return c.doJSON(ctx, http.MethodDelete, "/api/v1/sessions/"+url.PathEscape(sessionID), nil, nil, nil)+}++// AddMessage appends a message to a session.+func (c *Client) AddMessage(ctx context.Context, sessionID, role string, opts AddMessageOptions) (map[string]any, error) {+ payload := map[string]any{"role": role}+ if len(opts.Parts) > 0 {+ payload["parts"] = opts.Parts+ } else if opts.Content != nil {+ payload["content"] = *opts.Content+ } else {+ return nil, fmt.Errorf("openviking: AddMessage requires Content or Parts")+ }+ setString(payload, "created_at", opts.CreatedAt)+ setString(payload, "peer_id", opts.PeerID)+ setAny(payload, "telemetry", opts.Telemetry)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/messages", nil, payload, &result)+ return result, err+}++// BatchAddMessages appends multiple messages to a session.+func (c *Client) BatchAddMessages(ctx context.Context, sessionID string, messages []Message, opts *BatchAddMessagesOptions) (map[string]any, error) {+ payload := map[string]any{"messages": messages}+ if opts != nil {+ setAny(payload, "telemetry", opts.Telemetry)+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/messages/batch", nil, payload, &result)+ return result, err+}++// CommitSession archives and extracts memories for a session.+func (c *Client) CommitSession(ctx context.Context, sessionID string, opts *CommitSessionOptions) (map[string]any, error) {+ if opts == nil {+ opts = &CommitSessionOptions{}+ }+ payload := map[string]any{+ "keep_recent_count": opts.KeepRecentCount,+ }+ setAny(payload, "telemetry", opts.Telemetry)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/sessions/"+url.PathEscape(sessionID)+"/commit", nil, payload, &result)+ return result, err+}++// GetTask returns a task or nil when it does not exist.+func (c *Client) GetTask(ctx context.Context, taskID string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/tasks/"+url.PathEscape(taskID), nil, nil, &result)+ if err != nil {+ if IsCode(err, "NOT_FOUND") {+ return nil, nil+ }+ var apiErr *Error+ if errors.As(err, &apiErr) && apiErr.StatusCode == http.StatusNotFound {+ return nil, nil+ }+ return nil, err+ }+ return result, nil+}++// ListTasks lists background tasks visible to the caller.+func (c *Client) ListTasks(ctx context.Context, opts *ListTasksOptions) ([]any, error) {+ query := url.Values{}+ if opts != nil {+ setQueryString(query, "task_type", opts.TaskType)+ setQueryString(query, "status", opts.Status)+ setQueryString(query, "resource_id", opts.ResourceID)+ if opts.Limit > 0 {+ queryInt(query, "limit", opts.Limit)+ }+ }+ var result []any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/tasks", query, nil, &result)+ return result, err+}diff --git a/sdk/go/skills.go b/sdk/go/skills.gonew file mode 100644index 000000000..7a65e727d--- /dev/null+++ b/sdk/go/skills.go@@ -0,0 +1,142 @@+package openviking++import (+ "context"+ "net/http"+ "net/url"+)++// AddSkill registers a skill from raw data, a local file, or a local directory.+func (c *Client) AddSkill(ctx context.Context, data any, opts *AddSkillOptions) (map[string]any, error) {+ if opts == nil {+ opts = &AddSkillOptions{}+ }+ payload := map[string]any{+ "wait": opts.Wait,+ }+ setFloatPtr(payload, "timeout", opts.Timeout)+ setAny(payload, "telemetry", opts.Telemetry)+ if err := c.attachSkillData(ctx, payload, data); err != nil {+ return nil, err+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/skills", nil, payload, &result)+ return result, err+}++// ListSkills lists installed agent skills.+func (c *Client) ListSkills(ctx context.Context, opts *ListSkillsOptions) (map[string]any, error) {+ nodeLimit := 1000+ if opts != nil && opts.NodeLimit != 0 {+ nodeLimit = opts.NodeLimit+ }+ query := url.Values{}+ queryInt(query, "node_limit", nodeLimit)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/skills", query, nil, &result)+ return result, err+}++// FindSkills finds installed agent skills by semantic search.+func (c *Client) FindSkills(ctx context.Context, queryText string, opts *FindSkillsOptions) (map[string]any, error) {+ if opts == nil {+ opts = &FindSkillsOptions{}+ }+ limit := opts.Limit+ if limit == 0 {+ limit = 10+ }+ payload := map[string]any{+ "query": queryText,+ "limit": limit,+ }+ setAny(payload, "score_threshold", opts.ScoreThreshold)+ if len(opts.Level) > 0 {+ payload["level"] = opts.Level+ }+ setAny(payload, "telemetry", opts.Telemetry)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/skills/find", nil, payload, &result)+ return result, err+}++// ValidateSkill validates a skill payload without installing it.+func (c *Client) ValidateSkill(ctx context.Context, data any, opts *ValidateSkillOptions) (map[string]any, error) {+ payload := map[string]any{"data": data}+ if opts != nil {+ payload["strict"] = opts.Strict+ setString(payload, "source_path", opts.SourcePath)+ setString(payload, "skill_dir_name", opts.SkillDirName)+ } else {+ payload["strict"] = false+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/skills/validate", nil, payload, &result)+ return result, err+}++// GetSkill returns one installed agent skill.+func (c *Client) GetSkill(ctx context.Context, skillName string, opts *GetSkillOptions) (map[string]any, error) {+ query := url.Values{}+ includeFiles := true+ if opts != nil {+ if opts.IncludeFiles != nil {+ includeFiles = *opts.IncludeFiles+ }+ if opts.IncludeContent != nil {+ queryBool(query, "include_content", *opts.IncludeContent)+ }+ queryBool(query, "include_source", opts.IncludeSource)+ if opts.Level != nil {+ queryInt(query, "level", *opts.Level)+ }+ } else {+ queryBool(query, "include_source", false)+ }+ queryBool(query, "include_files", includeFiles)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/skills/"+url.PathEscape(skillName), query, nil, &result)+ return result, err+}++// UpdateSkill replaces an installed agent skill.+func (c *Client) UpdateSkill(ctx context.Context, skillName string, data any, opts *UpdateSkillOptions) (map[string]any, error) {+ if opts == nil {+ opts = &UpdateSkillOptions{}+ }+ payload := map[string]any{+ "wait": opts.Wait,+ }+ setFloatPtr(payload, "timeout", opts.Timeout)+ setAny(payload, "source_metadata", opts.SourceMetadata)+ setAny(payload, "telemetry", opts.Telemetry)+ if err := c.attachSkillData(ctx, payload, data); err != nil {+ return nil, err+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPut, "/api/v1/skills/"+url.PathEscape(skillName), nil, payload, &result)+ return result, err+}++// DeleteSkill removes an installed agent skill.+func (c *Client) DeleteSkill(ctx context.Context, skillName string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, "/api/v1/skills/"+url.PathEscape(skillName), nil, nil, &result)+ return result, err+}++func (c *Client) attachSkillData(ctx context.Context, payload map[string]any, data any) error {+ path, ok := data.(string)+ if !ok {+ payload["data"] = data+ return nil+ }+ if err := c.addLocalUpload(ctx, payload, path, false); err != nil {+ return err+ }+ if _, ok := payload["path"]; ok {+ delete(payload, "path")+ payload["data"] = path+ }+ return nil+}diff --git a/sdk/go/system.go b/sdk/go/system.gonew file mode 100644index 000000000..62c7157a0--- /dev/null+++ b/sdk/go/system.go@@ -0,0 +1,84 @@+package openviking++import (+ "context"+ "encoding/json"+ "net/http"+)++// WaitProcessed waits until all queued processing completes.+func (c *Client) WaitProcessed(ctx context.Context, opts *WaitProcessedOptions) (map[string]any, error) {+ payload := map[string]any{}+ if opts != nil && opts.Timeout != nil {+ payload["timeout"] = *opts.Timeout+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/system/wait", nil, payload, &result)+ return result, err+}++// CheckConsistency checks filesystem/vector-index consistency for a URI subtree.+func (c *Client) CheckConsistency(ctx context.Context, uri string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, "/api/v1/system/consistency", nil, map[string]any{"uri": NormalizeURI(uri)}, &result)+ return result, err+}++// Health checks whether the server health endpoint reports ok.+func (c *Client) Health(ctx context.Context) (bool, error) {+ req, err := c.newRequest(ctx, http.MethodGet, "/health", nil, nil)+ if err != nil {+ return false, err+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return false, err+ }+ defer resp.Body.Close()+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return false, nil+ }+ var payload struct {+ Status string `json:"status"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&payload); err != nil {+ return false, err+ }+ return payload.Status == "ok", nil+}++// QueueStatus returns queue observer status.+func (c *Client) QueueStatus(ctx context.Context) (map[string]any, error) {+ return c.observerStatus(ctx, "/api/v1/observer/queue")+}++// VikingDBStatus returns vector DB observer status.+func (c *Client) VikingDBStatus(ctx context.Context) (map[string]any, error) {+ return c.observerStatus(ctx, "/api/v1/observer/vikingdb")+}++// ModelsStatus returns model observer status.+func (c *Client) ModelsStatus(ctx context.Context) (map[string]any, error) {+ return c.observerStatus(ctx, "/api/v1/observer/models")+}++// GetStatus returns overall observer status.+func (c *Client) GetStatus(ctx context.Context) (map[string]any, error) {+ return c.observerStatus(ctx, "/api/v1/observer/system")+}++func (c *Client) observerStatus(ctx context.Context, path string) (map[string]any, error) {+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, path, nil, nil, &result)+ return result, err+}++// IsHealthy checks the observer system status.+func (c *Client) IsHealthy(ctx context.Context) (bool, error) {+ status, err := c.GetStatus(ctx)+ if err != nil {+ return false, err+ }+ healthy, _ := status["is_healthy"].(bool)+ return healthy, nil+}diff --git a/sdk/go/transport.go b/sdk/go/transport.gonew file mode 100644index 000000000..eed9b0d78--- /dev/null+++ b/sdk/go/transport.go@@ -0,0 +1,164 @@+package openviking++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"+ "strings"+)++type responseEnvelope struct {+ Status string `json:"status"`+ Result json.RawMessage `json:"result,omitempty"`+ Error *ErrorInfo `json:"error,omitempty"`+ Telemetry json.RawMessage `json:"telemetry,omitempty"`+ Profile []string `json:"profile,omitempty"`+}++func (c *Client) newRequest(ctx context.Context, method, path string, query url.Values, body io.Reader) (*http.Request, error) {+ if !strings.HasPrefix(path, "/") {+ path = "/" + path+ }+ u, err := url.Parse(c.baseURL + path)+ if err != nil {+ return nil, err+ }+ values := u.Query()+ for k, vs := range query {+ for _, v := range vs {+ values.Add(k, v)+ }+ }+ if c.profile {+ values.Set("profile", "1")+ }+ u.RawQuery = values.Encode()++ req, err := http.NewRequestWithContext(ctx, method, u.String(), body)+ if err != nil {+ return nil, err+ }+ if c.apiKey != "" {+ req.Header.Set("X-API-Key", c.apiKey)+ }+ if c.account != "" {+ req.Header.Set("X-OpenViking-Account", c.account)+ }+ if c.user != "" {+ req.Header.Set("X-OpenViking-User", c.user)+ }+ if c.actorPeerID != "" {+ req.Header.Set("X-OpenViking-Actor-Peer", c.actorPeerID)+ }+ for k, v := range c.extraHeaders {+ req.Header.Set(k, v)+ }+ return req, nil+}++func (c *Client) doJSON(ctx context.Context, method, path string, query url.Values, payload any, out any) error {+ var body io.Reader+ if payload != nil {+ buf, err := json.Marshal(payload)+ if err != nil {+ return err+ }+ body = bytes.NewReader(buf)+ }+ req, err := c.newRequest(ctx, method, path, query, body)+ if err != nil {+ return err+ }+ if payload != nil {+ req.Header.Set("Content-Type", "application/json")+ }+ resp, err := c.httpClient.Do(req)+ if err != nil {+ return err+ }+ defer resp.Body.Close()++ data, err := io.ReadAll(resp.Body)+ if err != nil {+ return err+ }+ env, err := decodeEnvelope(resp.StatusCode, data)+ if err != nil {+ return err+ }+ if env.Error != nil {+ return apiError(resp.StatusCode, env.Error)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return &Error{+ Code: "UNKNOWN",+ Message: envelopeDetail(env, resp.StatusCode, data),+ StatusCode: resp.StatusCode,+ }+ }+ if out == nil || len(env.Result) == 0 || string(env.Result) == "null" {+ return nil+ }+ return json.Unmarshal(env.Result, out)+}++func decodeEnvelope(statusCode int, data []byte) (*responseEnvelope, error) {+ if len(bytes.TrimSpace(data)) == 0 {+ return &responseEnvelope{Status: "ok"}, nil+ }+ var env responseEnvelope+ if err := json.Unmarshal(data, &env); err != nil {+ if statusCode >= 200 && statusCode < 300 {+ return nil, err+ }+ return nil, &Error{+ Code: "UNKNOWN",+ Message: fmt.Sprintf("HTTP %d: %s", statusCode, strings.TrimSpace(string(data))),+ StatusCode: statusCode,+ }+ }+ if env.Status == "error" && env.Error == nil {+ env.Error = &ErrorInfo{Code: "UNKNOWN", Message: envelopeDetail(&env, statusCode, data)}+ }+ return &env, nil+}++func envelopeDetail(env *responseEnvelope, statusCode int, data []byte) string {+ if env != nil {+ if env.Error != nil && env.Error.Message != "" {+ return env.Error.Message+ }+ var detail struct {+ Detail any `json:"detail"`+ }+ if err := json.Unmarshal(data, &detail); err == nil && detail.Detail != nil {+ return fmt.Sprint(detail.Detail)+ }+ }+ text := strings.TrimSpace(string(data))+ if text == "" {+ return fmt.Sprintf("HTTP %d", statusCode)+ }+ return fmt.Sprintf("HTTP %d: %s", statusCode, text)+}++func apiError(statusCode int, info *ErrorInfo) *Error {+ code := info.Code+ if code == "" {+ code = "UNKNOWN"+ }+ msg := info.Message+ if msg == "" {+ msg = "Unknown error"+ }+ return &Error{+ Code: code,+ Message: msg,+ Details: info.Details,+ StatusCode: statusCode,+ }+}diff --git a/sdk/go/types.go b/sdk/go/types.gonew file mode 100644index 000000000..343fc40cc--- /dev/null+++ b/sdk/go/types.go@@ -0,0 +1,291 @@+package openviking++import (+ "net/http"+ "time"+)++// Config configures an HTTP OpenViking client.+type Config struct {+ BaseURL string+ APIKey string+ Account string+ User string+ ActorPeerID string+ Timeout time.Duration++ ExtraHeaders map[string]string+ HTTPClient *http.Client+ Profile bool+ UploadMode string+}++// AddResourceOptions controls AddResource.+type AddResourceOptions struct {+ To string+ Parent string+ Reason string+ Instruction string+ Wait bool+ Timeout *float64+ Strict bool+ IgnoreDirs string+ Include string+ Exclude string+ DirectlyUploadMedia *bool+ PreserveStructure *bool+ WatchInterval float64+ Args map[string]any+ Telemetry any+}++// AddSkillOptions controls AddSkill.+type AddSkillOptions struct {+ Wait bool+ Timeout *float64+ Telemetry any+}++// ListSkillsOptions controls ListSkills.+type ListSkillsOptions struct {+ NodeLimit int+}++// FindSkillsOptions controls FindSkills.+type FindSkillsOptions struct {+ Limit int+ ScoreThreshold *float64+ Level []int+ Telemetry any+}++// ValidateSkillOptions controls ValidateSkill.+type ValidateSkillOptions struct {+ Strict bool+ SourcePath string+ SkillDirName string+}++// GetSkillOptions controls GetSkill.+type GetSkillOptions struct {+ IncludeContent *bool+ IncludeFiles *bool+ IncludeSource bool+ Level *int+}++// UpdateSkillOptions controls UpdateSkill.+type UpdateSkillOptions struct {+ Wait bool+ Timeout *float64+ SourceMetadata map[string]any+ Telemetry any+}++// WaitProcessedOptions controls WaitProcessed.+type WaitProcessedOptions struct {+ Timeout *float64 `json:"timeout,omitempty"`+}++// ListWatchesOptions controls ListWatches.+type ListWatchesOptions struct {+ ActiveOnly bool+ ToURI string+}++// WatchRef identifies a watch task by task ID or target URI.+type WatchRef struct {+ TaskID string+ ToURI string+}++// UpdateWatchOptions controls UpdateWatch.+type UpdateWatchOptions struct {+ TaskID string+ ToURI string+ WatchInterval *float64+ IsActive *bool+ Reason *string+ Instruction *string+}++// ListOptions controls List.+type ListOptions struct {+ Simple bool+ Recursive bool+ Output string+ AbsLimit int+ ShowAllHidden bool+ NodeLimit int+}++// TreeOptions controls Tree.+type TreeOptions struct {+ Output string+ AbsLimit int+ ShowAllHidden bool+ NodeLimit int+}++// RemoveOptions controls Remove.+type RemoveOptions struct {+ Recursive bool+ Wait bool+ Timeout *float64+}++// WriteOptions controls Write.+type WriteOptions struct {+ Mode string+ Wait bool+ Timeout *float64+ Telemetry any+}++// ReindexOptions controls Reindex.+type ReindexOptions struct {+ Mode string+ Wait bool+}++// FindOptions controls Find.+type FindOptions struct {+ TargetURI any+ Limit int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ Telemetry any+}++// SearchOptions controls Search.+type SearchOptions struct {+ TargetURI any+ SessionID string+ Limit int+ NodeLimit *int+ ScoreThreshold *float64+ Filter map[string]any+ ContextType any+ Telemetry any+}++// GrepOptions controls Grep.+type GrepOptions struct {+ CaseInsensitive bool+ NodeLimit *int+ ExcludeURI string+}++// CreateSessionOptions controls CreateSession.+type CreateSessionOptions struct {+ SessionID string+ MemoryPolicy map[string]any+ Telemetry any+}++// GetSessionOptions controls GetSession.+type GetSessionOptions struct {+ AutoCreate bool+}++// AddMessageOptions controls AddMessage.+type AddMessageOptions struct {+ Content *string+ Parts []map[string]any+ CreatedAt string+ PeerID string+ Telemetry any+}++// Message is one session message payload for BatchAddMessages.+type Message struct {+ Role string `json:"role"`+ Content *string `json:"content,omitempty"`+ Parts []map[string]any `json:"parts,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`+ PeerID string `json:"peer_id,omitempty"`+}++// BatchAddMessagesOptions controls BatchAddMessages.+type BatchAddMessagesOptions struct {+ Telemetry any+}++// CommitSessionOptions controls CommitSession.+type CommitSessionOptions struct {+ KeepRecentCount int+ Telemetry any+}++// ListTasksOptions controls ListTasks.+type ListTasksOptions struct {+ TaskType string+ Status string+ ResourceID string+ Limit int+}++// PackOptions controls ovpack export/backup.+type PackOptions struct {+ IncludeVectors bool+}++// ImportPackOptions controls ovpack import/restore.+type ImportPackOptions struct {+ OnConflict string+ VectorMode string+}++// AdminMigrateOptions controls AdminMigrate.+type AdminMigrateOptions struct {+ Cleanup bool+}++// FindResult is the structured retrieval response returned by Find and Search.+type FindResult struct {+ Memories []MatchedContext `json:"memories,omitempty"`+ Resources []MatchedContext `json:"resources,omitempty"`+ Skills []MatchedContext `json:"skills,omitempty"`+ QueryPlan *QueryPlan `json:"query_plan,omitempty"`+ QueryResults []map[string]any `json:"query_results,omitempty"`+ Total int `json:"total,omitempty"`+}++// MatchedContext is one retrieval hit.+type MatchedContext struct {+ URI string `json:"uri,omitempty"`+ ContextType string `json:"context_type,omitempty"`+ Level int `json:"level,omitempty"`+ Abstract string `json:"abstract,omitempty"`+ Overview string `json:"overview,omitempty"`+ Category string `json:"category,omitempty"`+ Score float64 `json:"score,omitempty"`+ MatchReason string `json:"match_reason,omitempty"`+ Relations []RelatedContext `json:"relations,omitempty"`+}++// RelatedContext is a related context reference attached to a retrieval hit.+type RelatedContext struct {+ URI string `json:"uri,omitempty"`+ Reason string `json:"reason,omitempty"`+ Score float64 `json:"score,omitempty"`+ Relation string `json:"relation,omitempty"`+ RelationID string `json:"relation_id,omitempty"`+}++// QueryPlan describes search query expansion details when the server returns them.+type QueryPlan struct {+ Queries []TypedQuery `json:"queries,omitempty"`+ Raw map[string]any `json:"-"`+}++// TypedQuery is a query generated for a specific context type.+type TypedQuery struct {+ Query string `json:"query,omitempty"`+ ContextType string `json:"context_type,omitempty"`+ Intent string `json:"intent,omitempty"`+ Priority int `json:"priority,omitempty"`+ TargetDirectories []string `json:"target_directories,omitempty"`+}diff --git a/sdk/go/upload.go b/sdk/go/upload.gonew file mode 100644index 000000000..4bb354b17--- /dev/null+++ b/sdk/go/upload.go@@ -0,0 +1,181 @@+package openviking++import (+ "archive/zip"+ "bytes"+ "context"+ "encoding/json"+ "io"+ "mime/multipart"+ "net/http"+ "os"+ "path/filepath"+ "strings"+)++func zipDirectory(dir string) (string, error) {+ root, err := filepath.Abs(dir)+ if err != nil {+ return "", err+ }+ tmp, err := os.CreateTemp("", "openviking-upload-*.zip")+ if err != nil {+ return "", err+ }+ zipPath := tmp.Name()+ defer tmp.Close()++ zw := zip.NewWriter(tmp)+ defer zw.Close()++ err = filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {+ if walkErr != nil {+ return walkErr+ }+ if path == root {+ return nil+ }+ if entry.Type()&os.ModeSymlink != 0 {+ if entry.IsDir() {+ return filepath.SkipDir+ }+ return nil+ }+ if entry.IsDir() {+ return nil+ }+ if !entry.Type().IsRegular() {+ return nil+ }+ abs, err := filepath.Abs(path)+ if err != nil {+ return err+ }+ if relToRoot, err := filepath.Rel(root, abs); err != nil || strings.HasPrefix(relToRoot, "..") {+ return nil+ }+ rel, err := filepath.Rel(root, path)+ if err != nil {+ return err+ }+ rel = filepath.ToSlash(rel)+ w, err := zw.Create(rel)+ if err != nil {+ return err+ }+ f, err := os.Open(path)+ if err != nil {+ return err+ }+ defer f.Close()+ _, err = io.Copy(w, f)+ return err+ })+ if err != nil {+ _ = os.Remove(zipPath)+ return "", err+ }+ return zipPath, nil+}++func (c *Client) uploadTempFile(ctx context.Context, filePath string) (string, error) {+ file, err := os.Open(filePath)+ if err != nil {+ return "", err+ }+ defer file.Close()++ var body bytes.Buffer+ writer := multipart.NewWriter(&body)+ part, err := writer.CreateFormFile("file", filepath.Base(filePath))+ if err != nil {+ return "", err+ }+ if _, err := io.Copy(part, file); err != nil {+ return "", err+ }+ if c.uploadMode != "" {+ if err := writer.WriteField("upload_mode", c.uploadMode); err != nil {+ return "", err+ }+ }+ if err := writer.Close(); err != nil {+ return "", err+ }++ req, err := c.newRequest(ctx, http.MethodPost, "/api/v1/resources/temp_upload", nil, &body)+ if err != nil {+ return "", err+ }+ req.Header.Set("Content-Type", writer.FormDataContentType())++ resp, err := c.httpClient.Do(req)+ if err != nil {+ return "", err+ }+ defer resp.Body.Close()++ data, err := io.ReadAll(resp.Body)+ if err != nil {+ return "", err+ }+ env, err := decodeEnvelope(resp.StatusCode, data)+ if err != nil {+ return "", err+ }+ if env.Error != nil {+ return "", apiError(resp.StatusCode, env.Error)+ }+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {+ return "", &Error{Code: "UNKNOWN", Message: envelopeDetail(env, resp.StatusCode, data), StatusCode: resp.StatusCode}+ }+ var result struct {+ TempFileID string `json:"temp_file_id"`+ }+ if len(env.Result) > 0 && string(env.Result) != "null" {+ if err := json.Unmarshal(env.Result, &result); err != nil {+ return "", err+ }+ }+ return result.TempFileID, nil+}++func (c *Client) addLocalUpload(ctx context.Context, payload map[string]any, path string, includeSourceName bool) error {+ info, err := os.Stat(path)+ if err != nil {+ if os.IsNotExist(err) {+ payload["path"] = path+ return nil+ }+ return err+ }+ if info.IsDir() {+ if includeSourceName {+ payload["source_name"] = filepath.Base(path)+ }+ zipPath, err := zipDirectory(path)+ if err != nil {+ return err+ }+ defer os.Remove(zipPath)+ tempID, err := c.uploadTempFile(ctx, zipPath)+ if err != nil {+ return err+ }+ payload["temp_file_id"] = tempID+ return nil+ }+ if info.Mode().IsRegular() {+ if includeSourceName {+ payload["source_name"] = filepath.Base(path)+ }+ tempID, err := c.uploadTempFile(ctx, path)+ if err != nil {+ return err+ }+ payload["temp_file_id"] = tempID+ return nil+ }+ payload["path"] = path+ return nil+}diff --git a/sdk/go/watches.go b/sdk/go/watches.gonew file mode 100644index 000000000..75afcd507--- /dev/null+++ b/sdk/go/watches.go@@ -0,0 +1,98 @@+package openviking++import (+ "context"+ "fmt"+ "net/http"+ "net/url"+)++// ListWatches lists watch tasks, or returns one by target URI.+func (c *Client) ListWatches(ctx context.Context, opts *ListWatchesOptions) (map[string]any, error) {+ query := url.Values{}+ activeOnly := false+ if opts != nil {+ activeOnly = opts.ActiveOnly+ if opts.ToURI != "" {+ query.Set("to_uri", NormalizeURI(opts.ToURI))+ }+ }+ queryBool(query, "active_only", activeOnly)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/watches", query, nil, &result)+ return result, err+}++// GetWatch gets one watch task by task ID, optionally cross-checking the target URI.+func (c *Client) GetWatch(ctx context.Context, taskID string, toURI string) (map[string]any, error) {+ query := url.Values{}+ if toURI != "" {+ query.Set("to_uri", NormalizeURI(toURI))+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodGet, "/api/v1/watches/"+url.PathEscape(taskID), query, nil, &result)+ return result, err+}++// UpdateWatch partially updates a watch task by task ID or target URI.+func (c *Client) UpdateWatch(ctx context.Context, opts UpdateWatchOptions) (map[string]any, error) {+ if opts.TaskID == "" && opts.ToURI == "" {+ return nil, fmt.Errorf("openviking: UpdateWatch requires TaskID or ToURI")+ }+ payload := map[string]any{}+ setFloatPtr(payload, "watch_interval", opts.WatchInterval)+ if opts.IsActive != nil {+ payload["is_active"] = *opts.IsActive+ }+ if opts.Reason != nil {+ payload["reason"] = *opts.Reason+ }+ if opts.Instruction != nil {+ payload["instruction"] = *opts.Instruction+ }+ if len(payload) == 0 {+ return nil, fmt.Errorf("openviking: UpdateWatch requires at least one field to update")+ }+ path, query := watchPathAndQuery(opts.TaskID, opts.ToURI)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPatch, path, query, payload, &result)+ return result, err+}++// DeleteWatch deletes a watch task by task ID or target URI.+func (c *Client) DeleteWatch(ctx context.Context, ref WatchRef) (map[string]any, error) {+ if ref.TaskID == "" && ref.ToURI == "" {+ return nil, fmt.Errorf("openviking: DeleteWatch requires TaskID or ToURI")+ }+ path, query := watchPathAndQuery(ref.TaskID, ref.ToURI)+ var result map[string]any+ err := c.doJSON(ctx, http.MethodDelete, path, query, nil, &result)+ return result, err+}++// TriggerWatch schedules a watch task for immediate background execution.+func (c *Client) TriggerWatch(ctx context.Context, ref WatchRef) (map[string]any, error) {+ if ref.TaskID == "" && ref.ToURI == "" {+ return nil, fmt.Errorf("openviking: TriggerWatch requires TaskID or ToURI")+ }+ path, query := watchPathAndQuery(ref.TaskID, ref.ToURI)+ if ref.TaskID != "" {+ path += "/trigger"+ } else {+ path = "/api/v1/watches/trigger"+ }+ var result map[string]any+ err := c.doJSON(ctx, http.MethodPost, path, query, nil, &result)+ return result, err+}++func watchPathAndQuery(taskID string, toURI string) (string, url.Values) {+ query := url.Values{}+ if toURI != "" {+ query.Set("to_uri", NormalizeURI(toURI))+ }+ if taskID != "" {+ return "/api/v1/watches/" + url.PathEscape(taskID), query+ }+ return "/api/v1/watches", query+}