Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

fix(api): return processing errors as error envelopes (#1744)

Qin Haojie121b6e1cab48
diff --git a/crates/ov_cli/src/client.rs b/crates/ov_cli/src/client.rs
index ab2cfb3ce..687de73c2 100644
--- a/crates/ov_cli/src/client.rs
+++ b/crates/ov_cli/src/client.rs
@@ -10,6 +10,29 @@ use zip::write::FileOptions;
use crate::error::{Error, Result};
+fn api_error_from_envelope(json: &Value, status: StatusCode) -> String {
+ let error_code = json
+ .get("error")
+ .and_then(|e| e.get("code"))
+ .and_then(|c| c.as_str());
+ let error_msg = json
+ .get("error")
+ .and_then(|e| e.get("message"))
+ .and_then(|m| m.as_str())
+ .map(|s| s.to_string())
+ .or_else(|| {
+ json.get("detail")
+ .and_then(|d| d.as_str())
+ .map(|s| s.to_string())
+ })
+ .unwrap_or_else(|| format!("HTTP error {}", status));
+
+ match error_code {
+ Some(code) => format!("[{}] {}", code, error_msg),
+ None => error_msg,
+ }
+}
+
/// High-level HTTP client for OpenViking API
#[derive(Clone)]
pub struct HttpClient {
@@ -292,25 +315,7 @@ impl HttpClient {
// Handle HTTP errors
if !status.is_success() {
- let error_code = json
- .get("error")
- .and_then(|e| e.get("code"))
- .and_then(|c| c.as_str());
- let error_msg = json
- .get("error")
- .and_then(|e| e.get("message"))
- .and_then(|m| m.as_str())
- .map(|s| s.to_string())
- .or_else(|| {
- json.get("detail")
- .and_then(|d| d.as_str())
- .map(|s| s.to_string())
- })
- .unwrap_or_else(|| format!("HTTP error {}", status));
- return Err(Error::Api(match error_code {
- Some(code) => format!("[{}] {}", code, error_msg),
- None => error_msg,
- }));
+ return Err(Error::Api(api_error_from_envelope(&json, status)));
}
// Handle API errors (status == success but body has error)
@@ -1031,7 +1036,8 @@ impl HttpClient {
#[cfg(test)]
mod tests {
- use super::HttpClient;
+ use super::{HttpClient, api_error_from_envelope};
+ use reqwest::StatusCode;
use serde_json::json;
use std::collections::HashMap;
@@ -1126,4 +1132,36 @@ mod tests {
assert!(body.get("regenerate_semantics").is_none());
assert!(body.get("revectorize").is_none());
}
+
+ #[test]
+ fn standard_error_envelope_formats_api_error() {
+ let body = json!({
+ "status": "error",
+ "error": {
+ "code": "PROCESSING_ERROR",
+ "message": "Parse error: boom"
+ }
+ });
+
+ assert_eq!(
+ api_error_from_envelope(&body, StatusCode::INTERNAL_SERVER_ERROR),
+ "[PROCESSING_ERROR] Parse error: boom"
+ );
+ }
+
+ #[test]
+ fn successful_result_status_failed_stays_domain_status() {
+ let envelope = json!({
+ "status": "ok",
+ "result": {
+ "status": "failed",
+ "task_id": "task-1",
+ "error": "boom"
+ }
+ });
+ let result = envelope.get("result").unwrap();
+
+ assert_eq!(result["status"], "failed");
+ assert_eq!(result["task_id"], "task-1");
+ }
}
diff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.md
index 5835e2ff6..381e79e87 100644
--- a/docs/en/api/01-overview.md
+++ b/docs/en/api/01-overview.md
@@ -181,6 +181,11 @@ All HTTP API responses follow a unified format:
}
```
+The top-level `status` describes whether the HTTP API request succeeded. Some successful
+operations return domain-level status fields inside `result`, such as
+`"status": "success"`, `"status": "accepted"`, or task states. Those fields are not API
+transport errors.
+
**Error**
```json
@@ -194,6 +199,15 @@ All HTTP API responses follow a unified format:
}
```
+HTTP errors always use the top-level error envelope. Synchronous processing failures, such as
+resource parsing or synchronous reindex failures, are returned as non-2xx responses with
+`status="error"` and an `error` object. Clients should not look for `result.status="error"` to
+detect request failure.
+
+Python HTTP SDKs (`SyncHTTPClient` and `AsyncHTTPClient`) raise the corresponding
+`OpenVikingError` subclass for this envelope. For example, `PROCESSING_ERROR` is raised as
+`ProcessingError`.
+
## CLI Output Format
### Table Mode (default)
@@ -267,8 +281,10 @@ Compact JSON with status wrapper (when `--compact` is true, which is the default
| `PERMISSION_DENIED` | 403 | Insufficient permissions |
| `RESOURCE_EXHAUSTED` | 429 | Rate limit exceeded |
| `FAILED_PRECONDITION` | 412 | Precondition failed |
+| `CONFLICT` | 409 | Operation conflicts with an in-progress task or existing state |
| `DEADLINE_EXCEEDED` | 504 | Operation timed out |
| `UNAVAILABLE` | 503 | Service unavailable |
+| `PROCESSING_ERROR` | 500 | Resource or semantic processing failed |
| `INTERNAL` | 500 | Internal server error |
| `UNIMPLEMENTED` | 501 | Feature not implemented |
| `EMBEDDING_FAILED` | 500 | Embedding generation failed |
diff --git a/docs/en/api/02-resources.md b/docs/en/api/02-resources.md
index 2c712758e..d048a209f 100644
--- a/docs/en/api/02-resources.md
+++ b/docs/en/api/02-resources.md
@@ -122,6 +122,24 @@ openviking add-resource ./documents/guide.md --reason "User guide documentation"
}
```
+**Synchronous Processing Error**
+
+If ingestion fails before producing a resource, raw HTTP returns the standard error envelope
+with a non-2xx HTTP status. For example:
+
+```json
+{
+ "status": "error",
+ "error": {
+ "code": "PROCESSING_ERROR",
+ "message": "Parse error: [Errno 2] No such file or directory: 'git'"
+ }
+}
+```
+
+`SyncHTTPClient`, `AsyncHTTPClient`, and CLI commands surface this as an error instead of
+returning a successful result with `result.status="error"`.
+
**Example: Add from URL**
**Python SDK (Embedded / HTTP)**
diff --git a/docs/en/api/04-skills.md b/docs/en/api/04-skills.md
index 24938ca7a..ceade9702 100644
--- a/docs/en/api/04-skills.md
+++ b/docs/en/api/04-skills.md
@@ -129,6 +129,23 @@ openviking add-skill ./my-skill/ [--wait]
}
```
+**Synchronous Processing Error**
+
+If skill parsing or processing fails synchronously, raw HTTP returns the standard error
+envelope with a non-2xx HTTP status:
+
+```json
+{
+ "status": "error",
+ "error": {
+ "code": "PROCESSING_ERROR",
+ "message": "Skill parse error: invalid skill metadata"
+ }
+}
+```
+
+The Python HTTP SDKs raise the mapped exception for this response.
+
**Example: Add from MCP Tool**
**Python SDK (Embedded / HTTP)**
diff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.md
index 5332cf3df..7dd5ae43b 100644
--- a/docs/zh/api/01-overview.md
+++ b/docs/zh/api/01-overview.md
@@ -181,6 +181,10 @@ client.close()
}
```
+顶层 `status` 表示本次 HTTP API 请求是否成功。某些成功响应会在 `result` 中返回业务状态,
+例如 `"status": "success"`、`"status": "accepted"` 或任务状态。这些字段不是 API
+传输层错误。
+
**错误**
```json
@@ -194,6 +198,13 @@ client.close()
}
```
+HTTP 错误始终使用顶层错误 envelope。资源解析、同步 reindex 等同步处理失败会返回非 2xx
+响应,顶层为 `status="error"`,并包含 `error` 对象。客户端不应通过
+`result.status="error"` 判断请求失败。
+
+Python HTTP SDK(`SyncHTTPClient` 和 `AsyncHTTPClient`)会把该 envelope 映射为对应的
+`OpenVikingError` 子类。例如 `PROCESSING_ERROR` 会抛出 `ProcessingError`。
+
## CLI 输出格式
### Table 模式(默认)
@@ -268,8 +279,10 @@ openviking -o json ls viking://resources/
| `PERMISSION_DENIED` | 403 | 权限不足 |
| `RESOURCE_EXHAUSTED` | 429 | 超出速率限制 |
| `FAILED_PRECONDITION` | 412 | 前置条件不满足 |
+| `CONFLICT` | 409 | 操作与正在进行的任务或已有状态冲突 |
| `DEADLINE_EXCEEDED` | 504 | 操作超时 |
| `UNAVAILABLE` | 503 | 服务不可用 |
+| `PROCESSING_ERROR` | 500 | 资源或语义处理失败 |
| `INTERNAL` | 500 | 内部服务器错误 |
| `UNIMPLEMENTED` | 501 | 功能未实现 |
| `EMBEDDING_FAILED` | 500 | Embedding 生成失败 |
diff --git a/docs/zh/api/02-resources.md b/docs/zh/api/02-resources.md
index 3e2cbb4e1..566184714 100644
--- a/docs/zh/api/02-resources.md
+++ b/docs/zh/api/02-resources.md
@@ -122,6 +122,23 @@ openviking add-resource ./documents/guide.md --reason "User guide documentation"
}
```
+**同步处理错误**
+
+如果导入在生成资源前失败,裸 HTTP 会返回标准错误 envelope,并使用非 2xx HTTP 状态码。例如:
+
+```json
+{
+ "status": "error",
+ "error": {
+ "code": "PROCESSING_ERROR",
+ "message": "Parse error: [Errno 2] No such file or directory: 'git'"
+ }
+}
+```
+
+`SyncHTTPClient`、`AsyncHTTPClient` 和 CLI 命令会把它作为错误抛出/展示,而不是返回
+`result.status="error"` 的成功结果。
+
**示例:从 URL 添加**
**Python SDK (Embedded / HTTP)**
diff --git a/docs/zh/api/04-skills.md b/docs/zh/api/04-skills.md
index bcf5ced2b..45ca6be6f 100644
--- a/docs/zh/api/04-skills.md
+++ b/docs/zh/api/04-skills.md
@@ -129,6 +129,22 @@ openviking add-skill ./my-skill/ [--wait]
}
```
+**同步处理错误**
+
+如果 skill 解析或处理同步失败,裸 HTTP 会返回标准错误 envelope,并使用非 2xx HTTP 状态码:
+
+```json
+{
+ "status": "error",
+ "error": {
+ "code": "PROCESSING_ERROR",
+ "message": "Skill parse error: invalid skill metadata"
+ }
+}
+```
+
+Python HTTP SDK 会把该响应映射为对应异常。
+
**示例:从 MCP Tool 添加**
**Python SDK (Embedded / HTTP)**
diff --git a/openviking/server/responses.py b/openviking/server/responses.py
new file mode 100644
index 000000000..65a90866c
--- /dev/null
+++ b/openviking/server/responses.py
@@ -0,0 +1,86 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: AGPL-3.0
+"""Helpers for building consistent HTTP API response envelopes."""
+
+from typing import Any, Dict, Optional
+
+from fastapi.responses import JSONResponse
+
+from openviking.server.models import ERROR_CODE_TO_HTTP_STATUS, ErrorInfo, Response
+
+
+def _message_from_business_error(result: Dict[str, Any]) -> str:
+ message = result.get("message")
+ if isinstance(message, str) and message:
+ return message
+
+ errors = result.get("errors")
+ if isinstance(errors, list) and errors:
+ first = errors[0]
+ if isinstance(first, str) and first:
+ return first
+ if isinstance(first, dict):
+ first_message = first.get("message")
+ if isinstance(first_message, str) and first_message:
+ return first_message
+ return str(first)
+
+ return "Operation failed"
+
+
+def response_from_result(
+ result: Any,
+ *,
+ telemetry: Optional[Dict[str, Any]] = None,
+):
+ """Build a standard API response from a synchronous operation result.
+
+ Some service-layer operations historically returned ``{"status": "error"}``
+ instead of raising an ``OpenVikingError``. At the HTTP boundary those are
+ request failures, not successful results with an inner error payload.
+ """
+ if isinstance(result, dict) and result.get("status") == "error":
+ code = result.get("code") or "PROCESSING_ERROR"
+ if not isinstance(code, str) or not code:
+ code = "PROCESSING_ERROR"
+
+ details = result.get("details")
+ error = ErrorInfo(
+ code=code,
+ message=_message_from_business_error(result),
+ details=details if isinstance(details, dict) else None,
+ )
+ content = Response(
+ status="error",
+ error=error,
+ telemetry=telemetry,
+ ).model_dump(exclude_none=True)
+ return JSONResponse(
+ status_code=ERROR_CODE_TO_HTTP_STATUS.get(code, 500),
+ content=content,
+ )
+
+ return Response(
+ status="ok",
+ result=result,
+ telemetry=telemetry,
+ ).model_dump(exclude_none=True)
+
+
+def error_response(
+ code: str,
+ message: str,
+ *,
+ details: Optional[Dict[str, Any]] = None,
+ telemetry: Optional[Dict[str, Any]] = None,
+):
+ """Build a standard API error response with the mapped HTTP status."""
+ content = Response(
+ status="error",
+ error=ErrorInfo(code=code, message=message, details=details),
+ telemetry=telemetry,
+ ).model_dump(exclude_none=True)
+ return JSONResponse(
+ status_code=ERROR_CODE_TO_HTTP_STATUS.get(code, 500),
+ content=content,
+ )
diff --git a/openviking/server/routers/content.py b/openviking/server/routers/content.py
index 5326e42c9..1512a1807 100644
--- a/openviking/server/routers/content.py
+++ b/openviking/server/routers/content.py
@@ -13,7 +13,8 @@ from openviking.pyagfs.exceptions import AGFSClientError, AGFSNotFoundError
from openviking.server.auth import get_request_context, require_role
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext, Role
-from openviking.server.models import ErrorInfo, Response
+from openviking.server.models import Response
+from openviking.server.responses import error_response, response_from_result
from openviking.server.routers.maintenance import (
REINDEX_TASK_TYPE,
ReindexRequest,
@@ -193,10 +194,7 @@ async def reindex(
viking_fs = get_viking_fs()
if not await viking_fs.exists(uri, ctx=ctx):
- return Response(
- status="error",
- error=ErrorInfo(code="NOT_FOUND", message=f"URI not found: {uri}"),
- )
+ return error_response("NOT_FOUND", f"URI not found: {uri}")
service = get_service()
tracker = get_task_tracker()
@@ -208,15 +206,9 @@ async def reindex(
owner_account_id=ctx.account_id,
owner_user_id=ctx.user.user_id,
):
- return Response(
- status="error",
- error=ErrorInfo(
- code="CONFLICT",
- message=f"URI {uri} already has a reindex in progress",
- ),
- )
+ return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
result = await _do_reindex(service, uri, body.regenerate, ctx)
- return Response(status="ok", result=result)
+ return response_from_result(result)
task = tracker.create_if_no_running(
REINDEX_TASK_TYPE,
@@ -225,13 +217,7 @@ async def reindex(
owner_user_id=ctx.user.user_id,
)
if task is None:
- return Response(
- status="error",
- error=ErrorInfo(
- code="CONFLICT",
- message=f"URI {uri} already has a reindex in progress",
- ),
- )
+ return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
asyncio.create_task(
_background_reindex_tracked(service, uri, body.regenerate, ctx, task.task_id)
)
diff --git a/openviking/server/routers/maintenance.py b/openviking/server/routers/maintenance.py
index a258bc598..24a6330ad 100644
--- a/openviking/server/routers/maintenance.py
+++ b/openviking/server/routers/maintenance.py
@@ -10,7 +10,8 @@ from pydantic import BaseModel
from openviking.server.auth import require_role
from openviking.server.dependencies import get_service
from openviking.server.identity import RequestContext, Role
-from openviking.server.models import ErrorInfo, Response
+from openviking.server.models import Response
+from openviking.server.responses import error_response, response_from_result
from openviking_cli.utils import get_logger
logger = get_logger(__name__)
@@ -51,10 +52,7 @@ async def reindex(
# Validate URI exists
if not await viking_fs.exists(uri, ctx=ctx):
- return Response(
- status="error",
- error=ErrorInfo(code="NOT_FOUND", message=f"URI not found: {uri}"),
- )
+ return error_response("NOT_FOUND", f"URI not found: {uri}")
service = get_service()
tracker = get_task_tracker()
@@ -67,15 +65,9 @@ async def reindex(
owner_account_id=ctx.account_id,
owner_user_id=ctx.user.user_id,
):
- return Response(
- status="error",
- error=ErrorInfo(
- code="CONFLICT",
- message=f"URI {uri} already has a reindex in progress",
- ),
- )
+ return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
result = await _do_reindex(service, uri, body.regenerate, ctx)
- return Response(status="ok", result=result)
+ return response_from_result(result)
else:
# Async path: run in background, return task_id for polling
task = tracker.create_if_no_running(
@@ -85,13 +77,7 @@ async def reindex(
owner_user_id=ctx.user.user_id,
)
if task is None:
- return Response(
- status="error",
- error=ErrorInfo(
- code="CONFLICT",
- message=f"URI {uri} already has a reindex in progress",
- ),
- )
+ return error_response("CONFLICT", f"URI {uri} already has a reindex in progress")
asyncio.create_task(
_background_reindex_tracked(service, uri, body.regenerate, ctx, task.task_id)
)
diff --git a/openviking/server/routers/resources.py b/openviking/server/routers/resources.py
index 0d9703402..5a36ff7d8 100644
--- a/openviking/server/routers/resources.py
+++ b/openviking/server/routers/resources.py
@@ -17,7 +17,7 @@ from openviking.server.local_input_guard import (
require_remote_resource_source,
resolve_uploaded_temp_file_id,
)
-from openviking.server.models import Response
+from openviking.server.responses import response_from_result
from openviking.server.telemetry import run_operation
from openviking.telemetry import TelemetryRequest
from openviking_cli.exceptions import InvalidArgumentError
@@ -179,11 +179,7 @@ async def temp_upload(
telemetry=telemetry,
fn=_upload,
)
- return Response(
- status="ok",
- result=execution.result,
- telemetry=execution.telemetry,
- ).model_dump(exclude_none=True)
+ return response_from_result(execution.result, telemetry=execution.telemetry)
@router.post("/resources")
@@ -244,11 +240,7 @@ async def add_resource(
**kwargs,
),
)
- return Response(
- status="ok",
- result=execution.result,
- telemetry=execution.telemetry,
- ).model_dump(exclude_none=True)
+ return response_from_result(execution.result, telemetry=execution.telemetry)
@router.post("/skills")
@@ -276,8 +268,4 @@ async def add_skill(
allow_local_path_resolution=allow_local_path_resolution,
),
)
- return Response(
- status="ok",
- result=execution.result,
- telemetry=execution.telemetry,
- ).model_dump(exclude_none=True)
+ return response_from_result(execution.result, telemetry=execution.telemetry)
diff --git a/tests/server/test_api_fs_content_endpoint_suite.py b/tests/server/test_api_fs_content_endpoint_suite.py
index 46445b5d1..0a2e84527 100644
--- a/tests/server/test_api_fs_content_endpoint_suite.py
+++ b/tests/server/test_api_fs_content_endpoint_suite.py
@@ -205,7 +205,7 @@ async def test_reindex_missing_uri_returns_not_found_error_payload(client, monke
"/api/v1/content/reindex",
json={"uri": "viking://resources/missing", "wait": True},
)
- _assert_error(response, status_code=200, error_code="NOT_FOUND")
+ _assert_error(response, status_code=404, error_code="NOT_FOUND")
async def test_reindex_sync_conflict_returns_error_payload(client, monkeypatch):
@@ -225,7 +225,65 @@ async def test_reindex_sync_conflict_returns_error_payload(client, monkeypatch):
"/api/v1/content/reindex",
json={"uri": "viking://resources/conflict", "wait": True},
)
- _assert_error(response, status_code=200, error_code="CONFLICT")
+ _assert_error(response, status_code=409, error_code="CONFLICT")
+
+
+async def test_reindex_sync_business_error_returns_error_envelope(client, monkeypatch):
+ async def fake_do_reindex(service, uri, regenerate, ctx):
+ return {"status": "error", "message": "bad summarize"}
+
+ monkeypatch.setattr(
+ "openviking.storage.viking_fs.get_viking_fs",
+ lambda: _FakeVikingFS(True),
+ )
+ monkeypatch.setattr(
+ "openviking.service.task_tracker.get_task_tracker",
+ lambda: _FakeTracker(has_running=False),
+ )
+ monkeypatch.setattr(
+ "openviking.server.routers.content.get_service",
+ lambda: SimpleNamespace(),
+ )
+ monkeypatch.setattr("openviking.server.routers.content._do_reindex", fake_do_reindex)
+ response = await client.post(
+ "/api/v1/content/reindex",
+ json={"uri": "viking://resources/demo", "wait": True, "regenerate": True},
+ )
+ _assert_error(
+ response,
+ status_code=500,
+ error_code="PROCESSING_ERROR",
+ message_fragment="bad summarize",
+ )
+
+
+async def test_maintenance_reindex_sync_business_error_returns_error_envelope(client, monkeypatch):
+ async def fake_do_reindex(service, uri, regenerate, ctx):
+ return {"status": "error", "message": "bad maintenance summarize"}
+
+ monkeypatch.setattr(
+ "openviking.storage.viking_fs.get_viking_fs",
+ lambda: _FakeVikingFS(True),
+ )
+ monkeypatch.setattr(
+ "openviking.service.task_tracker.get_task_tracker",
+ lambda: _FakeTracker(has_running=False),
+ )
+ monkeypatch.setattr(
+ "openviking.server.routers.maintenance.get_service",
+ lambda: SimpleNamespace(),
+ )
+ monkeypatch.setattr("openviking.server.routers.maintenance._do_reindex", fake_do_reindex)
+ response = await client.post(
+ "/api/v1/maintenance/reindex",
+ json={"uri": "viking://resources/demo", "wait": True, "regenerate": True},
+ )
+ _assert_error(
+ response,
+ status_code=500,
+ error_code="PROCESSING_ERROR",
+ message_fragment="bad maintenance summarize",
+ )
async def test_reindex_sync_success_returns_ok_payload(client, monkeypatch):
diff --git a/tests/server/test_api_resources.py b/tests/server/test_api_resources.py
index d5f1c96c0..ebb4bdb23 100644
--- a/tests/server/test_api_resources.py
+++ b/tests/server/test_api_resources.py
@@ -134,6 +134,62 @@ async def test_add_resource_with_telemetry_includes_resource_breakdown(
}
+async def test_add_resource_business_error_uses_error_envelope(
+ client: httpx.AsyncClient,
+ service,
+ monkeypatch,
+):
+ async def fake_add_resource(**kwargs):
+ return {
+ "status": "error",
+ "errors": ["Parse error: boom"],
+ "source_path": kwargs["path"],
+ }
+
+ monkeypatch.setattr(service.resources, "add_resource", fake_add_resource)
+
+ resp = await client.post(
+ "/api/v1/resources",
+ json={
+ "path": "https://example.com/bad.md",
+ "reason": "test resource",
+ },
+ )
+
+ assert resp.status_code == 500
+ body = resp.json()
+ assert body["status"] == "error"
+ assert "result" not in body
+ assert body["error"]["code"] == "PROCESSING_ERROR"
+ assert body["error"]["message"] == "Parse error: boom"
+
+
+async def test_add_skill_business_error_uses_error_envelope(
+ client: httpx.AsyncClient,
+ service,
+ monkeypatch,
+):
+ async def fake_add_skill(**kwargs):
+ return {
+ "status": "error",
+ "errors": [{"message": "Skill parse error: boom"}],
+ }
+
+ monkeypatch.setattr(service.resources, "add_skill", fake_add_skill)
+
+ resp = await client.post(
+ "/api/v1/skills",
+ json={"data": {"name": "bad-skill"}},
+ )
+
+ assert resp.status_code == 500
+ body = resp.json()
+ assert body["status"] == "error"
+ assert "result" not in body
+ assert body["error"]["code"] == "PROCESSING_ERROR"
+ assert body["error"]["message"] == "Skill parse error: boom"
+
+
async def test_add_resource_with_summary_only_telemetry(
client: httpx.AsyncClient,
sample_markdown_file,
diff --git a/tests/server/test_http_client_sdk.py b/tests/server/test_http_client_sdk.py
index b7d92289f..279394ec6 100644
--- a/tests/server/test_http_client_sdk.py
+++ b/tests/server/test_http_client_sdk.py
@@ -7,11 +7,12 @@ import asyncio
import io
import zipfile
+import httpx
import pytest
import pytest_asyncio
from openviking_cli.client.http import AsyncHTTPClient
-from openviking_cli.exceptions import FailedPreconditionError
+from openviking_cli.exceptions import ConflictError, FailedPreconditionError, ProcessingError
from tests.server.conftest import SAMPLE_MD_CONTENT, TEST_TMP_DIR
@@ -55,6 +56,43 @@ async def test_sdk_add_resource(http_client):
assert result["root_uri"].startswith("viking://")
+async def test_sdk_add_resource_raises_processing_error_for_business_error(
+ http_client,
+ monkeypatch,
+):
+ client, svc = http_client
+
+ async def fake_add_resource(**kwargs):
+ return {
+ "status": "error",
+ "errors": ["Parse error: boom"],
+ }
+
+ monkeypatch.setattr(svc.resources, "add_resource", fake_add_resource)
+
+ with pytest.raises(ProcessingError, match="Parse error: boom"):
+ await client.add_resource(path="https://example.com/bad.md", wait=True)
+
+
+def test_sdk_maps_conflict_error_envelope():
+ client = AsyncHTTPClient(url="http://127.0.0.1:1933")
+ response = httpx.Response(
+ 409,
+ json={
+ "status": "error",
+ "error": {
+ "code": "CONFLICT",
+ "message": "URI viking://resources/demo already has a reindex in progress",
+ },
+ },
+ )
+
+ with pytest.raises(ConflictError, match="already has a reindex in progress") as exc_info:
+ client._handle_response_data(response)
+
+ assert exc_info.value.code == "CONFLICT"
+
+
async def test_sdk_add_skill_from_local_file(http_client):
client, _ = http_client
f = TEST_TMP_DIR / "sdk_skill.md"