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
fix: align TypeScript SDK with server contracts (#3159)
yufeng5bfa9b617ecf
diff --git a/.github/workflows/typescript-sdk-release.yml b/.github/workflows/typescript-sdk-release.ymlindex 9d9b6b543..56140a7c4 100644--- a/.github/workflows/typescript-sdk-release.yml+++ b/.github/workflows/typescript-sdk-release.yml@@ -30,7 +30,7 @@ jobs:npm run typechecknpm run format:checknpm run build- npm run test:browser+ npm run test:node-typesnpm testnpm pack --dry-run- name: Validate release tagdiff --git a/docs/en/api/01-overview.md b/docs/en/api/01-overview.mdindex 8de8ac434..a12d4c9b7 100644--- a/docs/en/api/01-overview.md+++ b/docs/en/api/01-overview.md@@ -112,8 +112,8 @@ See [`sdk/go/README.md`](../../../sdk/go/README.md) for package-level examples.#### JavaScript/TypeScript SDK Client-The JavaScript/TypeScript SDK is an HTTP-only client for Node.js 18+ and modern-browsers. It ships ESM, CommonJS and TypeScript declarations.+The JavaScript/TypeScript SDK is an HTTP-only client for Node.js 18+. It ships+ESM, CommonJS and TypeScript declarations.```bashnpm install @openviking/sdkdiff --git a/docs/zh/api/01-overview.md b/docs/zh/api/01-overview.mdindex 9ab4bc50a..8936e5081 100644--- a/docs/zh/api/01-overview.md+++ b/docs/zh/api/01-overview.md@@ -108,8 +108,8 @@ Go SDK 不支持 Python embedded 模式,也不保留旧 `agent_id` 兼容路#### JavaScript/TypeScript SDK 客户端-JavaScript/TypeScript SDK 是面向 Node.js 18+ 和现代浏览器的 HTTP-only 客户端,-同时发布 ESM、CommonJS 和 TypeScript 类型声明。+JavaScript/TypeScript SDK 是面向 Node.js 18+ 的 HTTP-only 客户端,同时发布+ESM、CommonJS 和 TypeScript 类型声明。```bashnpm install @openviking/sdkdiff --git a/sdk/go/client_test.go b/sdk/go/client_test.goindex 2aac76607..f94e55123 100644--- a/sdk/go/client_test.go+++ b/sdk/go/client_test.go@@ -5,6 +5,7 @@ import ("context""encoding/json""errors"+ "fmt""io""net/http""net/http/httptest"@@ -942,7 +943,12 @@ func TestExportOVPackWritesFile(t *testing.T) {}))defer closeServer()- outPath, err := client.ExportOVPack(context.Background(), "resources/docs", t.TempDir(), nil)+ directory := t.TempDir()+ existingPath := filepath.Join(directory, "docs.ovpack")+ if err := os.WriteFile(existingPath, []byte("old-backup"), 0o600); err != nil {+ t.Fatal(err)+ }+ outPath, err := client.ExportOVPack(context.Background(), "resources/docs", directory, nil)if err != nil {t.Fatal(err)}@@ -953,6 +959,49 @@ func TestExportOVPackWritesFile(t *testing.T) {if string(content) != "OVPACK" {t.Fatalf("content = %q", string(content))}+ if matches, err := filepath.Glob(filepath.Join(directory, ".docs.ovpack-*.tmp")); err != nil || len(matches) != 0 {+ t.Fatalf("temporary files = %v, err = %v", matches, err)+ }+}++func TestBackupOVPackDoesNotPublishInterruptedDownload(t *testing.T) {+ client, closeServer := testClient(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.Header().Set("Content-Type", "application/octet-stream")+ w.Header().Set("Content-Length", "20")+ if _, err := w.Write([]byte("partial")); err != nil {+ t.Fatal(err)+ }+ }))+ defer closeServer()++ for _, existingOutput := range []bool{true, false} {+ t.Run(fmt.Sprintf("existing=%t", existingOutput), func(t *testing.T) {+ directory := t.TempDir()+ outPath := filepath.Join(directory, "backup.ovpack")+ if existingOutput {+ if err := os.WriteFile(outPath, []byte("known-good-backup"), 0o600); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := client.BackupOVPack(context.Background(), outPath, nil); err == nil {+ t.Fatal("expected interrupted download to fail")+ }+ content, err := os.ReadFile(outPath)+ if existingOutput {+ if err != nil {+ t.Fatal(err)+ }+ if string(content) != "known-good-backup" {+ t.Fatalf("content = %q", string(content))+ }+ } else if !os.IsNotExist(err) {+ t.Fatalf("expected no final file, err = %v", err)+ }+ if matches, err := filepath.Glob(filepath.Join(directory, ".backup.ovpack-*.tmp")); err != nil || len(matches) != 0 {+ t.Fatalf("temporary files = %v, err = %v", matches, err)+ }+ })+ }}func TestSessionExistsHandlesNotFound(t *testing.T) {diff --git a/sdk/go/pack.go b/sdk/go/pack.goindex a9f02a8f6..2a71a4c23 100644--- a/sdk/go/pack.go+++ b/sdk/go/pack.go@@ -84,13 +84,29 @@ func (c *Client) downloadPack(ctx context.Context, path string, payload map[stri}return &Error{Code: "UNKNOWN", Message: envelopeDetail(env, resp.StatusCode, data), StatusCode: resp.StatusCode}}- file, err := os.Create(outPath)+ file, err := os.CreateTemp(filepath.Dir(outPath), "."+filepath.Base(outPath)+"-*.tmp")if err != nil {return err}- defer file.Close()- _, err = io.Copy(file, resp.Body)- return err+ tempPath := file.Name()+ keepTemp := true+ defer func() {+ if keepTemp {+ _ = os.Remove(tempPath)+ }+ }()+ if _, err := io.Copy(file, resp.Body); err != nil {+ _ = file.Close()+ return err+ }+ if err := file.Close(); err != nil {+ return err+ }+ if err := os.Rename(tempPath, outPath); err != nil {+ return err+ }+ keepTemp = false+ return nil}// ImportOVPack imports a local .ovpack under parent.diff --git a/sdk/python/openviking_sdk/client.py b/sdk/python/openviking_sdk/client.pyindex 946e68e85..891bfa6ec 100644--- a/sdk/python/openviking_sdk/client.py+++ b/sdk/python/openviking_sdk/client.py@@ -78,6 +78,25 @@ def _image_to_data_uri(data: bytes | bytearray | memoryview, file_name: str = ""return f"data:{_image_mime_type(file_name)};base64,{encoded}"+def _atomic_write_bytes(path: Path, data: bytes) -> None:+ temporary = tempfile.NamedTemporaryFile(+ mode="wb",+ dir=path.parent,+ prefix=f".{path.name}-",+ suffix=".tmp",+ delete=False,+ )+ temporary_path = Path(temporary.name)+ try:+ with temporary:+ temporary.write(data)+ os.replace(temporary_path, path)+ except BaseException:+ temporary.close()+ temporary_path.unlink(missing_ok=True)+ raise++def _normalize_image_input(image: Any) -> Optional[str]:if image is None:return None@@ -1273,8 +1292,7 @@ class AsyncHTTPClient:)if not response.is_success:self._handle_response(response)- with open(to_path, "wb") as f:- f.write(response.content)+ _atomic_write_bytes(to_path, response.content)return str(to_path)async def backup_ovpack(self, to: str, include_vectors: bool = False) -> str:@@ -1289,8 +1307,7 @@ class AsyncHTTPClient:)if not response.is_success:self._handle_response(response)- with open(to_path, "wb") as f:- f.write(response.content)+ _atomic_write_bytes(to_path, response.content)return str(to_path)async def import_ovpack(diff --git a/sdk/python/tests/test_async_client_behaviors.py b/sdk/python/tests/test_async_client_behaviors.pyindex 659f5841f..c3cc01894 100644--- a/sdk/python/tests/test_async_client_behaviors.py+++ b/sdk/python/tests/test_async_client_behaviors.py@@ -707,6 +707,9 @@ async def test_export_and_backup_ovpack_append_default_suffixes(tmp_path):backup_response = SimpleNamespace(is_success=True, content=b"backup")fake_http = SimpleNamespace(post=AsyncMock(side_effect=[export_response, backup_response]))client._http = fake_http+ existing_export = tmp_path / "exports" / "demo.ovpack"+ existing_export.parent.mkdir()+ existing_export.write_bytes(b"old-backup")export_path = await client.export_ovpack("/resources/demo/", str(tmp_path / "exports" / "demo"))backup_path = await client.backup_ovpack(str(tmp_path / "backup-dir"))@@ -717,6 +720,27 @@ async def test_export_and_backup_ovpack_append_default_suffixes(tmp_path):assert Path(backup_path).read_bytes() == b"backup"+async def test_backup_ovpack_preserves_existing_file_when_replace_fails(tmp_path):+ client = AsyncHTTPClient(url="http://localhost:1933")+ client._http = SimpleNamespace(+ post=AsyncMock(+ return_value=SimpleNamespace(is_success=True, content=b"new-backup")+ )+ )+ output = tmp_path / "backup.ovpack"+ output.write_bytes(b"known-good-backup")++ with patch(+ "openviking_sdk.client.os.replace", side_effect=OSError("replace failed")+ ):+ with pytest.raises(OSError, match="replace failed"):+ await client.backup_ovpack(str(output))++ assert output.read_bytes() == b"known-good-backup"+ assert list(tmp_path.iterdir()) == [output]++@pytest.mark.asyncioasync def test_import_ovpack_fails_fast_when_local_file_is_missing(tmp_path):client = AsyncHTTPClient(url="http://localhost:1933")diff --git a/sdk/typescript/README.md b/sdk/typescript/README.mdindex 43271edef..8b66df46d 100644--- a/sdk/typescript/README.md+++ b/sdk/typescript/README.md@@ -1,6 +1,6 @@# @openviking/sdk-Lightweight JavaScript and TypeScript HTTP client for an existing OpenViking server. It targets modern browsers and Node.js 18+ and has no runtime dependencies.+Lightweight JavaScript and TypeScript HTTP client for an existing OpenViking server. It targets Node.js 18+ and has no runtime dependencies.```bashnpm install @openviking/sdk@@ -12,8 +12,6 @@ import { OpenVikingClient } from "@openviking/sdk";const client = new OpenVikingClient({baseUrl: "http://127.0.0.1:1933",apiKey: "your-key",- // Optional: keep this aligned with deployments that require an upload mode.- uploadMode: "proxy",});const results = await client.search("deployment guide", {@@ -22,9 +20,24 @@ const results = await client.search("deployment guide", {});```-The client follows the same HTTP API, identity headers, response envelope and error codes as `openviking-sdk` for Python and the Go SDK. It supports resources and skills, filesystem/content operations, retrieval, sessions, tasks, watches, observer status and tenant administration.+The client follows the same HTTP API, identity headers, response envelope and error codes as `openviking-sdk` for Python and the Go SDK. It supports resources and skills, filesystem/content operations, relations, retrieval, sessions, OVPack files, snapshots, tasks, watches, observer status and tenant administration.-Local browser files can be passed as `Blob` or `File`. In Node.js, an existing string path is uploaded automatically (directories are zipped); other strings are sent to the server as URLs or server-side paths. Browsers cannot read arbitrary local paths, so browser applications should use a URL or file object.+Existing local file paths are uploaded automatically, and local directories are zipped before upload. Other strings are sent to the server as URLs or server-side paths.++Deployments using shared temporary storage can set `uploadMode: "shared"`; the server also accepts `"local"` (the default).++OVPack exports and backups follow the Python and Go SDK contract: they are streamed to a Node.js local file and return its final path.++```ts+const packPath = await client.exportOVPack(+ "viking://resources/docs",+ "./backups",+);+await client.importOVPack(packPath, "viking://resources", {+ onConflict: "overwrite",+ vectorMode: "auto",+});+```## Releasediff --git a/sdk/typescript/README_CN.md b/sdk/typescript/README_CN.mdindex cf9d27d63..10a6b2802 100644--- a/sdk/typescript/README_CN.md+++ b/sdk/typescript/README_CN.md@@ -1,6 +1,6 @@# @openviking/sdk-OpenViking 的轻量级 JavaScript/TypeScript HTTP SDK,面向现代浏览器和 Node.js 18+,没有运行时依赖。+OpenViking 的轻量级 JavaScript/TypeScript HTTP SDK,面向 Node.js 18+,没有运行时依赖。```bashnpm install @openviking/sdk@@ -12,8 +12,6 @@ import { OpenVikingClient } from "@openviking/sdk";const client = new OpenVikingClient({baseUrl: "http://127.0.0.1:1933",apiKey: "your-key",- // 可选:部分部署会要求指定上传模式。- uploadMode: "proxy",});const results = await client.search("部署文档", {@@ -22,9 +20,24 @@ const results = await client.search("部署文档", {});```-SDK 与 Python `openviking-sdk`、Go SDK 使用相同的 HTTP API、身份请求头、响应信封和错误码,覆盖资源与技能、文件系统与内容、检索、会话、任务、Watch、Observer 状态和租户管理接口。+SDK 与 Python `openviking-sdk`、Go SDK 使用相同的 HTTP API、身份请求头、响应信封和错误码,覆盖资源与技能、文件系统与内容、资源关系、检索、会话、OVPack、快照、任务、Watch、Observer 状态和租户管理接口。-浏览器本地文件可直接传入 `Blob` 或 `File`。Node.js 中存在的字符串路径会自动上传(目录会先压缩);其他字符串会作为 URL 或服务端路径发送。浏览器无法读取任意本地路径,因此浏览器场景应传 URL 或文件对象。+Node.js 中存在的本地文件路径会自动上传,目录会先压缩后上传;其他字符串会作为 URL 或服务端路径发送。++使用共享临时存储的部署可设置 `uploadMode: "shared"`;服务端也接受 `"local"`(默认值)。++OVPack 导出和备份与 Python、Go SDK 契约一致:内容会流式写入 Node.js 本地文件,并返回最终文件路径。++```ts+const packPath = await client.exportOVPack(+ "viking://resources/docs",+ "./backups",+);+await client.importOVPack(packPath, "viking://resources", {+ onConflict: "overwrite",+ vectorMode: "auto",+});+```## 发布diff --git a/sdk/typescript/package.json b/sdk/typescript/package.jsonindex 2f0c381ac..d98e56e33 100644--- a/sdk/typescript/package.json+++ b/sdk/typescript/package.json@@ -22,7 +22,7 @@"format": "prettier --write src tests","format:check": "prettier --check src tests","test": "vitest run",- "test:browser": "esbuild dist/index.js --bundle --platform=browser --format=esm --outfile=/tmp/openviking-sdk-browser.js",+ "test:node-types": "tsc --project tests/node-consumer/tsconfig.json","typecheck": "tsc --noEmit"},"engines": { "node": ">=18" },diff --git a/sdk/typescript/src/client.ts b/sdk/typescript/src/client.tsindex 59d46b85b..f5013c460 100644--- a/sdk/typescript/src/client.ts+++ b/sdk/typescript/src/client.ts@@ -1,10 +1,19 @@import { OpenVikingError } from "./errors.js";-import { zipSync } from "fflate/browser";+import {+ nodeImagePathToDataURI,+ nodePathToBlob,+ packOutputPath,+ writeResponseToFile,+} from "./node-files.js";+import { OpenVikingTransport, type TransportOptions } from "./transport.js";import type {AddResourceOptions,ClientConfig,CreateSessionOptions,FindResult,+ GitBlob,+ GitCommitOptions,+ GitRestoreOptions,JsonObject,ListOptions,GetSkillOptions,@@ -12,7 +21,6 @@ import type {ImportPackOptions,Message,RequestOptions,- ResponseEnvelope,SearchOptions,TaskListOptions,TreeOptions,@@ -27,62 +35,6 @@ const compact = (value: JsonObject): JsonObject =>),);const pathPart = (value: string): string => encodeURIComponent(value);-const isBlobLike = (value: unknown): value is Blob => {- if (!value || typeof value !== "object") return false;- const candidate = value as Partial<Blob>;- return (- typeof candidate.arrayBuffer === "function" &&- typeof candidate.type === "string" &&- typeof candidate.size === "number"- );-};-const blobFilename = (value: Blob, fallback: string): string => {- const name = (value as Blob & { name?: unknown }).name;- return typeof name === "string" && name ? name : fallback;-};--async function nodePathToBlob(- path: string,-): Promise<{ blob: Blob; filename: string; sourceName?: string } | undefined> {- if (typeof process === "undefined" || !process.versions?.node)- return undefined;- // Keep Node built-ins as runtime-only imports so browser bundlers do not- // attempt to resolve them while building the browser branch.- const fsSpecifier = "node:fs/promises";- const pathSpecifier = "node:path";- const fs = await import(fsSpecifier);- const nodePath = await import(pathSpecifier);- let stat;- try {- stat = await fs.stat(path);- } catch (error) {- if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;- throw error;- }- if (stat.isFile())- return {- blob: new Blob([await fs.readFile(path)]),- filename: nodePath.basename(path),- sourceName: nodePath.basename(path),- };- if (!stat.isDirectory()) return undefined;- const files: Record<string, Uint8Array> = {};- const walk = async (directory: string, prefix = ""): Promise<void> => {- for (const entry of await fs.readdir(directory, { withFileTypes: true })) {- if (entry.isSymbolicLink()) continue;- const fullPath = nodePath.join(directory, entry.name);- const archivePath = prefix ? `${prefix}/${entry.name}` : entry.name;- if (entry.isDirectory()) await walk(fullPath, archivePath);- else if (entry.isFile()) files[archivePath] = await fs.readFile(fullPath);- }- };- await walk(path);- return {- blob: new Blob([zipSync(files)]),- filename: `${nodePath.basename(path)}.zip`,- sourceName: nodePath.basename(path),- };-}/** Normalize a short OpenViking URI to the canonical `viking://` form. */export const normalizeURI = (uri: string): string =>@@ -91,117 +43,27 @@ export const normalizeURI = (uri: string): string =>/** HTTP client for an existing OpenViking server. */export class OpenVikingClient {readonly baseUrl: string;- private readonly fetcher: typeof globalThis.fetch;- private readonly headers: Headers;- private readonly timeout: number;- private readonly profile: boolean;- private readonly uploadMode: string | undefined;+ private readonly transport: OpenVikingTransport;/** Create a client with explicit connection and identity configuration. */constructor(config: ClientConfig) {- if (!config.baseUrl?.trim())- throw new TypeError("OpenViking: baseUrl is required");- const url = new URL(config.baseUrl);- if (!/^https?:$/.test(url.protocol))- throw new TypeError("OpenViking: baseUrl must use http or https");- this.baseUrl = config.baseUrl.replace(/\/+$/, "");- this.fetcher = config.fetch ?? globalThis.fetch;- if (!this.fetcher)- throw new TypeError("OpenViking: fetch is not available");- this.timeout = config.timeout ?? 60_000;- this.profile = config.profile ?? false;- this.uploadMode = config.uploadMode;- this.headers = new Headers(config.headers);- if (config.apiKey) this.headers.set("X-API-Key", config.apiKey);- if (config.account)- this.headers.set("X-OpenViking-Account", config.account);- if (config.user) this.headers.set("X-OpenViking-User", config.user);- if (config.actorPeerId)- this.headers.set("X-OpenViking-Actor-Peer", config.actorPeerId);+ this.transport = new OpenVikingTransport(config);+ this.baseUrl = this.transport.baseUrl;}- private async request<T>(+ private request<T>(method: string,path: string,- options: {- query?: JsonObject;- body?: unknown;- form?: FormData;- signal?: AbortSignal;- } = {},+ options: TransportOptions = {},): Promise<T> {- const url = new URL(- `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`,- );- for (const [key, value] of Object.entries(options.query ?? {})) {- if (value !== undefined && value !== null && value !== "")- url.searchParams.set(key, String(value));- }- if (this.profile) url.searchParams.set("profile", "1");- const headers = new Headers(this.headers);- let body: BodyInit | undefined;- if (options.form) body = options.form;- else if (options.body !== undefined) {- headers.set("Content-Type", "application/json");- body = JSON.stringify(options.body);- }- const controller = new AbortController();- const abort = () => controller.abort(options.signal?.reason);- options.signal?.addEventListener("abort", abort, { once: true });- const timer = setTimeout(- () =>- controller.abort(new DOMException("Request timed out", "TimeoutError")),- this.timeout,- );- try {- const init: RequestInit = { method, headers, signal: controller.signal };- if (body !== undefined) init.body = body;- const response = await this.fetcher(url, init);- const text = await response.text();- let envelope: ResponseEnvelope<T> = {};- if (text) {- try {- envelope = JSON.parse(text) as ResponseEnvelope<T>;- } catch (cause) {- throw new OpenVikingError(`HTTP ${response.status}: ${text}`, {- statusCode: response.status,- cause,- });- }- }- if (envelope.error || envelope.status === "error" || !response.ok) {- const info = envelope.error;- throw new OpenVikingError(- info?.message ?? String(envelope.detail ?? `HTTP ${response.status}`),- compact({- code: info?.code,- details: info?.details,- statusCode: response.status,- }) as { code?: string; details?: JsonObject; statusCode?: number },- );- }- return envelope.result as T;- } catch (error) {- if (error instanceof OpenVikingError) throw error;- if (controller.signal.aborted)- throw new OpenVikingError("Request timed out or was aborted", {- code: "DEADLINE_EXCEEDED",- cause: error,- });- throw new OpenVikingError(- error instanceof Error ? error.message : "Network request failed",- { code: "UNAVAILABLE", cause: error },- );- } finally {- clearTimeout(timer);- options.signal?.removeEventListener("abort", abort);- }+ return this.transport.request<T>(method, path, options);}private async upload(file: Blob, filename = "upload"): Promise<string> {const form = new FormData();form.set("file", file, filename);- if (this.uploadMode) form.set("upload_mode", this.uploadMode);+ if (this.transport.uploadMode)+ form.set("upload_mode", this.transport.uploadMode);const result = await this.request<{ temp_file_id: string }>("POST","/api/v1/resources/temp_upload",@@ -215,63 +77,30 @@ export class OpenVikingClient {return result.temp_file_id;}- private async download(path: string, body: JsonObject): Promise<Blob> {- const controller = new AbortController();- const timer = setTimeout(- () =>- controller.abort(new DOMException("Request timed out", "TimeoutError")),- this.timeout,+ private async downloadToFile(+ path: string,+ body: JsonObject,+ output: string,+ signal?: AbortSignal,+ ): Promise<string> {+ return this.transport.consume(+ "POST",+ path,+ { body, ...(signal ? { signal } : {}) },+ async (response) => {+ if (+ !response.ok ||+ response.headers.get("content-type")?.includes("json")+ )+ return this.transport.parseResponse<never>(response);+ return writeResponseToFile(response, output);+ },);- try {- const headers = new Headers(this.headers);- headers.set("Content-Type", "application/json");- const response = await this.fetcher(`${this.baseUrl}${path}`, {- method: "POST",- headers,- body: JSON.stringify(body),- signal: controller.signal,- });- if (!response.ok) {- const text = await response.text();- try {- const envelope = JSON.parse(text) as ResponseEnvelope<never>;- throw new OpenVikingError(- envelope.error?.message ??- String(envelope.detail ?? `HTTP ${response.status}`),- compact({- code: envelope.error?.code,- details: envelope.error?.details,- statusCode: response.status,- }) as { code?: string; details?: JsonObject; statusCode?: number },- );- } catch (error) {- if (error instanceof OpenVikingError) throw error;- throw new OpenVikingError(`HTTP ${response.status}: ${text}`, {- statusCode: response.status,- cause: error,- });- }- }- return response.blob();- } catch (error) {- if (error instanceof OpenVikingError) throw error;- if (controller.signal.aborted)- throw new OpenVikingError("Request timed out", {- code: "DEADLINE_EXCEEDED",- cause: error,- });- throw new OpenVikingError(- error instanceof Error ? error.message : "Network request failed",- { code: "UNAVAILABLE", cause: error },- );- } finally {- clearTimeout(timer);- }}- /** Add a remote URL, browser Blob/File, or Node.js local file/directory as a resource. */+ /** Add a remote URL or Node.js local file/directory as a resource. */async addResource(- source: string | Blob,+ source: string,options: AddResourceOptions = {},): Promise<JsonObject> {if (options.to && options.parent)@@ -296,24 +125,17 @@ export class OpenVikingClient {: undefined,telemetry: options.telemetry,});- const local =- typeof source === "string" ? await nodePathToBlob(source) : undefined;+ const local = await nodePathToBlob(source);if (local) {body.temp_file_id = await this.upload(local.blob, local.filename);body.source_name = local.sourceName;- } else if (typeof source === "string") body.path = source;- else if (isBlobLike(source)) {- body.temp_file_id = await this.upload(- source,- blobFilename(source, "resource"),- );- }+ } else body.path = source;return this.request("POST", "/api/v1/resources", { body });}- /** Install a skill from inline data, a Blob/File, or an existing Node.js path. */+ /** Install a skill from inline data or an existing Node.js path. */async addSkill(- source: unknown | Blob,+ source: unknown,options: WaitOptions & { targetUri?: string } = {},): Promise<JsonObject> {const body: JsonObject = compact({@@ -326,12 +148,7 @@ export class OpenVikingClient {typeof source === "string" ? await nodePathToBlob(source) : undefined;if (local)body.temp_file_id = await this.upload(local.blob, local.filename);- else if (isBlobLike(source)) {- body.temp_file_id = await this.upload(- source,- blobFilename(source, "skill"),- );- } else body.data = source;+ else body.data = source;return this.request("POST", "/api/v1/skills", { body });}/** List installed skills. */@@ -402,7 +219,7 @@ export class OpenVikingClient {/** Replace an installed skill. */async updateSkill(name: string,- source: unknown | Blob,+ source: unknown,options: WaitOptions & {sourceMetadata?: JsonObject;targetUri?: string;@@ -419,12 +236,7 @@ export class OpenVikingClient {typeof source === "string" ? await nodePathToBlob(source) : undefined;if (local)body.temp_file_id = await this.upload(local.blob, local.filename);- else if (isBlobLike(source)) {- body.temp_file_id = await this.upload(- source,- blobFilename(source, "skill"),- );- } else body.data = source;+ else body.data = source;return this.request("PUT", `/api/v1/skills/${pathPart(name)}`, { body });}/** Delete an installed skill. */@@ -515,18 +327,14 @@ export class OpenVikingClient {query: string,options: SearchOptions,): Promise<FindResult> {- let imageUrl =- typeof options.image === "string" ? options.image : undefined;- if (isBlobLike(options.image)) {- const bytes = new Uint8Array(await options.image.arrayBuffer());- let binary = "";- for (const byte of bytes) binary += String.fromCharCode(byte);- imageUrl = `data:${options.image.type || "application/octet-stream"};base64,${btoa(binary)}`;+ let imageUrl: string | undefined;+ if (typeof options.image === "string") {+ imageUrl = (await nodeImagePathToDataURI(options.image)) ?? options.image;}return this.request("POST", `/api/v1/search/${kind}`, {body: compact({query,- target_uri: options.targetUri ?? "viking://",+ target_uri: options.targetUri ?? "",image_url: imageUrl,session_id: kind === "search" ? options.sessionId : undefined,limit: options.nodeLimit ?? options.limit ?? 10,@@ -571,6 +379,37 @@ export class OpenVikingClient {body: { pattern, uri: normalizeURI(uri), node_limit: nodeLimit },});}+ /** Return relations associated with a resource. */+ relations(uri: string): Promise<unknown[]> {+ return this.request("GET", "/api/v1/relations", {+ query: { uri: normalizeURI(uri) },+ });+ }+ /** Create one or more resource relations. */+ async link(+ fromUri: string,+ toUris: string | string[],+ reason = "",+ ): Promise<void> {+ await this.request("POST", "/api/v1/relations/link", {+ body: {+ from_uri: normalizeURI(fromUri),+ to_uris: Array.isArray(toUris)+ ? toUris.map(normalizeURI)+ : normalizeURI(toUris),+ reason,+ },+ });+ }+ /** Remove a resource relation. */+ async unlink(fromUri: string, toUri: string): Promise<void> {+ await this.request("DELETE", "/api/v1/relations/link", {+ body: {+ from_uri: normalizeURI(fromUri),+ to_uri: normalizeURI(toUri),+ },+ });+ }/** List directory contents. */list(uri: string, options: ListOptions = {}): Promise<unknown[]> {@@ -786,15 +625,21 @@ export class OpenVikingClient {`/api/v1/sessions/${pathPart(sessionId)}/messages/batch`,{body: compact({- messages: messages.map((m) =>- compact({- role: m.role,- content: m.content,- parts: m.parts,- created_at: m.createdAt,- peer_id: m.peerId,- }),- ),+ messages: messages.map((message) => {+ if (message.content === undefined && !message.parts?.length) {+ throw new TypeError(+ "OpenViking: each message requires content or parts",+ );+ }+ const parts = message.parts?.length ? message.parts : undefined;+ return compact({+ role: message.role,+ content: parts ? undefined : message.content,+ parts,+ created_at: message.createdAt,+ peer_id: message.peerId,+ });+ }),telemetry,}),},@@ -812,31 +657,45 @@ export class OpenVikingClient {{ body: compact({ keep_recent_count: keepRecentCount, telemetry }) },);}- /** Export a resource subtree as an OVPack blob. */- exportOVPack(uri: string, includeVectors = false): Promise<Blob> {- return this.download("/api/v1/pack/export", {- uri: normalizeURI(uri),- include_vectors: includeVectors,- });+ /** Export a resource subtree to a local OVPack file. */+ async exportOVPack(+ uri: string,+ to: string,+ includeVectors = false,+ options: RequestOptions = {},+ ): Promise<string> {+ const output = await packOutputPath(to, uri, "export");+ return this.downloadToFile(+ "/api/v1/pack/export",+ { uri: normalizeURI(uri), include_vectors: includeVectors },+ output,+ options.signal,+ );}- /** Back up public scopes as a restore-only OVPack blob. */- backupOVPack(includeVectors = false): Promise<Blob> {- return this.download("/api/v1/pack/backup", {- include_vectors: includeVectors,- });+ /** Back up public scopes to a local restore-only OVPack file. */+ async backupOVPack(+ to: string,+ includeVectors = false,+ options: RequestOptions = {},+ ): Promise<string> {+ const output = await packOutputPath(to, undefined, "openviking-backup");+ return this.downloadToFile(+ "/api/v1/pack/backup",+ { include_vectors: includeVectors },+ output,+ options.signal,+ );}- /** Import an OVPack blob or Node.js local file under a parent URI. */+ /** Import a local OVPack file under a parent URI. */async importOVPack(- source: string | Blob,+ source: string,parent: string,options: ImportPackOptions = {},): Promise<string> {- const local =- typeof source === "string" ? await nodePathToBlob(source) : undefined;- const blob = local?.blob ?? (isBlobLike(source) ? source : undefined);- if (!blob)+ const local = await nodePathToBlob(source, { allowDirectory: false });+ if (!local)throw new TypeError(- "OpenViking: importOVPack requires a Blob or an existing Node.js local file",+ "OpenViking: importOVPack requires an existing Node.js local file",);const result = await this.request<{ uri: string }>("POST",@@ -844,10 +703,7 @@ export class OpenVikingClient {{body: compact({parent: normalizeURI(parent),- temp_file_id: await this.upload(- blob,- local?.filename ?? "import.ovpack",- ),+ temp_file_id: await this.upload(local.blob, local.filename),on_conflict: options.onConflict,vector_mode: options.vectorMode,}),@@ -855,27 +711,22 @@ export class OpenVikingClient {);return result.uri;}- /** Restore an OVPack backup blob or Node.js local file. */+ /** Restore a local OVPack backup file. */async restoreOVPack(- source: string | Blob,+ source: string,options: ImportPackOptions = {},): Promise<string> {- const local =- typeof source === "string" ? await nodePathToBlob(source) : undefined;- const blob = local?.blob ?? (isBlobLike(source) ? source : undefined);- if (!blob)+ const local = await nodePathToBlob(source, { allowDirectory: false });+ if (!local)throw new TypeError(- "OpenViking: restoreOVPack requires a Blob or an existing Node.js local file",+ "OpenViking: restoreOVPack requires an existing Node.js local file",);const result = await this.request<{ uri: string }>("POST","/api/v1/pack/restore",{body: compact({- temp_file_id: await this.upload(- blob,- local?.filename ?? "restore.ovpack",- ),+ temp_file_id: await this.upload(local.blob, local.filename),on_conflict: options.onConflict,vector_mode: options.vectorMode,}),@@ -916,21 +767,14 @@ export class OpenVikingClient {}/** Check the raw server health endpoint. */async health(options: RequestOptions = {}): Promise<boolean> {- const controller = new AbortController();- const abort = () => controller.abort(options.signal?.reason);- options.signal?.addEventListener("abort", abort, { once: true });- const timer = setTimeout(() => controller.abort(), this.timeout);- try {- const response = await this.fetcher(`${this.baseUrl}/health`, {- headers: this.headers,- signal: controller.signal,- });- if (!response.ok) return false;- return ((await response.json()) as { status?: string }).status === "ok";- } finally {- clearTimeout(timer);- options.signal?.removeEventListener("abort", abort);- }+ return this.transport.consume(+ "GET",+ "/health",+ options,+ async (response) =>+ response.ok &&+ ((await response.json()) as { status?: string }).status === "ok",+ );}/** Check filesystem/index consistency. */checkConsistency(uri: string): Promise<JsonObject> {@@ -954,6 +798,86 @@ export class OpenVikingClient {modelsStatus(): Promise<JsonObject> {return this.request("GET", "/api/v1/observer/models");}+ /** Return whether the observer system reports healthy. */+ async isHealthy(): Promise<boolean> {+ return (await this.getStatus()).is_healthy === true;+ }+ /** Create a filesystem snapshot. */+ gitCommit(options: GitCommitOptions): Promise<JsonObject> {+ return this.request("POST", "/api/v1/snapshot/commit", {+ body: compact({+ message: options.message,+ paths: options.paths,+ branch: options.branch ?? "main",+ author_name: options.authorName,+ author_email: options.authorEmail,+ }),+ });+ }+ /** Restore filesystem content from a previous snapshot. */+ gitRestore(options: GitRestoreOptions): Promise<JsonObject> {+ return this.request("POST", "/api/v1/snapshot/restore", {+ body: compact({+ project_dir: options.projectDir,+ source_commit: options.sourceCommit,+ branch: options.branch ?? "main",+ dry_run: options.dryRun ?? false,+ message: options.message,+ author_name: options.authorName,+ author_email: options.authorEmail,+ }),+ });+ }+ /** Return snapshot metadata or a raw file from a snapshot. */+ gitShow(targetRef: string, path?: string): Promise<JsonObject | GitBlob> {+ return this.transport.consume(+ "GET",+ "/api/v1/snapshot/show",+ { query: { target_ref: targetRef, path } },+ async (response) => {+ if (+ response.ok &&+ response.headers+ .get("content-type")+ ?.startsWith("application/octet-stream")+ ) {+ const bytes = new Uint8Array(await response.arrayBuffer());+ return {+ oid: response.headers.get("x-snapshot-oid") ?? "",+ size: Number(+ response.headers.get("x-snapshot-size") ?? bytes.length,+ ),+ bytes,+ };+ }+ return this.transport.parseResponse<JsonObject>(response);+ },+ );+ }+ /** Return snapshot history from newest to oldest. */+ gitLog(branch = "main", limit = 20): Promise<JsonObject[]> {+ return this.request("GET", "/api/v1/snapshot/log", {+ query: { branch, limit },+ });+ }+ /** Return the account `.ovgitignore` content. */+ async gitGetIgnore(): Promise<string> {+ const result = await this.request<unknown>(+ "GET",+ "/api/v1/snapshot/ignore",+ );+ return typeof result === "string" ? result : "";+ }+ /** Set the account `.ovgitignore` content. */+ async gitSetIgnore(content: string): Promise<void> {+ await this.request("PUT", "/api/v1/snapshot/ignore", {+ body: { content },+ });+ }+ /** Delete the account `.ovgitignore` file. */+ async gitDeleteIgnore(): Promise<void> {+ await this.request("DELETE", "/api/v1/snapshot/ignore");+ }/** Create a tenant account and its first administrator. */adminCreateAccount(accountId: string,diff --git a/sdk/typescript/src/node-files.ts b/sdk/typescript/src/node-files.tsnew file mode 100644index 000000000..f74bd798d--- /dev/null+++ b/sdk/typescript/src/node-files.ts@@ -0,0 +1,153 @@+import { zipSync } from "fflate";+import { OpenVikingError } from "./errors.js";++const NODE_FS_SPECIFIER = "node:fs/promises";+const NODE_PATH_SPECIFIER = "node:path";+const IMAGE_REFERENCE_PREFIXES = [+ "data:image/",+ "http://",+ "https://",+ "viking://",+] as const;++const nodeFs = () => import(NODE_FS_SPECIFIER);+const nodePath = () => import(NODE_PATH_SPECIFIER);++const statOrUndefined = async (path: string) => {+ try {+ return await (await nodeFs()).stat(path);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;+ throw error;+ }+};++const bytesToDataURI = (bytes: Uint8Array, mimeType: string): string => {+ let binary = "";+ for (const byte of bytes) binary += String.fromCharCode(byte);+ return `data:${mimeType};base64,${btoa(binary)}`;+};++const imageMimeType = (path: string): string => {+ const extension = path.toLowerCase().match(/\.[^.\\/]+$/)?.[0];+ const mimeTypes: Record<string, string> = {+ ".avif": "image/avif",+ ".bmp": "image/bmp",+ ".gif": "image/gif",+ ".ico": "image/x-icon",+ ".jpeg": "image/jpeg",+ ".jpg": "image/jpeg",+ ".png": "image/png",+ ".svg": "image/svg+xml",+ ".tif": "image/tiff",+ ".tiff": "image/tiff",+ ".webp": "image/webp",+ };+ return (extension && mimeTypes[extension]) || "image/png";+};++/** Convert an existing Node.js image path to a request-safe data URI. */+export async function nodeImagePathToDataURI(+ path: string,+): Promise<string | undefined> {+ if (IMAGE_REFERENCE_PREFIXES.some((prefix) => path.startsWith(prefix)))+ return undefined;+ const stat = await statOrUndefined(path);+ if (!stat?.isFile()) return undefined;+ return bytesToDataURI(+ await (await nodeFs()).readFile(path),+ imageMimeType(path),+ );+}++/** Read a Node.js file or zip a directory for temporary upload. */+export async function nodePathToBlob(+ path: string,+ options: { allowDirectory?: boolean } = {},+): Promise<{ blob: Blob; filename: string; sourceName?: string } | undefined> {+ // Keep built-in specifiers dynamic so bundled ESM and CommonJS outputs share+ // this implementation without eager filesystem initialization.+ const [fs, paths, stat] = await Promise.all([+ nodeFs(),+ nodePath(),+ statOrUndefined(path),+ ]);+ if (!stat) return undefined;+ if (stat.isFile())+ return {+ blob: new Blob([await fs.readFile(path)]),+ filename: paths.basename(path),+ sourceName: paths.basename(path),+ };+ if (!stat.isDirectory()) return undefined;+ if (options.allowDirectory === false)+ throw new TypeError(+ `OpenViking: ${path} is a directory, expected an OVPack file`,+ );+ const files: Record<string, Uint8Array> = {};+ const walk = async (directory: string, prefix = ""): Promise<void> => {+ for (const entry of await fs.readdir(directory, { withFileTypes: true })) {+ if (entry.isSymbolicLink()) continue;+ const fullPath = paths.join(directory, entry.name);+ const archivePath = prefix ? `${prefix}/${entry.name}` : entry.name;+ if (entry.isDirectory()) await walk(fullPath, archivePath);+ else if (entry.isFile()) files[archivePath] = await fs.readFile(fullPath);+ }+ };+ await walk(path);+ return {+ blob: new Blob([zipSync(files)]),+ filename: `${paths.basename(path)}.zip`,+ sourceName: paths.basename(path),+ };+}++/** Resolve the Python/Go-compatible local destination for an OVPack. */+export async function packOutputPath(+ to: string,+ uri: string | undefined,+ fallback: string,+): Promise<string> {+ const [fs, paths] = await Promise.all([nodeFs(), nodePath()]);+ let output = to || ".";+ if ((await statOrUndefined(output))?.isDirectory()) {+ const name = uri+ ? paths.basename(uri.trim().replace(/\/+$/, "")) || fallback+ : fallback;+ output = paths.join(output, `${name}.ovpack`);+ }+ if (!output.endsWith(".ovpack")) output += ".ovpack";+ await fs.mkdir(paths.dirname(output), { recursive: true });+ return output;+}++/** Stream a web response body into a Node.js local file. */+export async function writeResponseToFile(+ response: Response,+ output: string,+): Promise<string> {+ if (!response.body)+ throw new OpenVikingError("Download response did not include a body", {+ code: "INTERNAL",+ });+ const [fs, paths] = await Promise.all([nodeFs(), nodePath()]);+ const temporaryDirectory = await fs.mkdtemp(+ paths.join(paths.dirname(output), `.${paths.basename(output)}-`),+ );+ const temporaryPath = paths.join(temporaryDirectory, "download");+ let file: Awaited<ReturnType<typeof fs.open>> | undefined;+ try {+ file = await fs.open(temporaryPath, "wx");+ for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>)+ await file.writeFile(chunk);+ await file.close();+ file = undefined;+ await fs.rename(temporaryPath, output);+ return output;+ } finally {+ await file?.close().catch(() => undefined);+ await fs+ .rm(temporaryDirectory, { recursive: true, force: true })+ .catch(() => undefined);+ }+}diff --git a/sdk/typescript/src/transport.ts b/sdk/typescript/src/transport.tsnew file mode 100644index 000000000..eb51cb2c4--- /dev/null+++ b/sdk/typescript/src/transport.ts@@ -0,0 +1,141 @@+import { OpenVikingError } from "./errors.js";+import type {+ ClientConfig,+ JsonObject,+ ResponseEnvelope,+ UploadMode,+} from "./types.js";++const compact = (value: JsonObject): JsonObject =>+ Object.fromEntries(+ Object.entries(value).filter(+ ([, item]) => item !== undefined && item !== null,+ ),+ );++export interface TransportOptions {+ query?: JsonObject;+ body?: unknown;+ form?: FormData;+ signal?: AbortSignal;+}++/** Internal HTTP module shared by JSON and binary SDK operations. */+export class OpenVikingTransport {+ readonly baseUrl: string;+ readonly uploadMode: UploadMode | undefined;+ private readonly fetcher: typeof globalThis.fetch;+ private readonly headers: Headers;+ private readonly timeout: number;+ private readonly profile: boolean;++ constructor(config: ClientConfig) {+ if (!config.baseUrl?.trim())+ throw new TypeError("OpenViking: baseUrl is required");+ const url = new URL(config.baseUrl);+ if (!/^https?:$/.test(url.protocol))+ throw new TypeError("OpenViking: baseUrl must use http or https");+ this.baseUrl = config.baseUrl.replace(/\/+$/, "");+ this.fetcher = config.fetch ?? globalThis.fetch;+ if (!this.fetcher)+ throw new TypeError("OpenViking: fetch is not available");+ this.timeout = config.timeout ?? 60_000;+ this.profile = config.profile ?? false;+ this.uploadMode = config.uploadMode;+ this.headers = new Headers(config.headers);+ if (config.apiKey) this.headers.set("X-API-Key", config.apiKey);+ if (config.account)+ this.headers.set("X-OpenViking-Account", config.account);+ if (config.user) this.headers.set("X-OpenViking-User", config.user);+ if (config.actorPeerId)+ this.headers.set("X-OpenViking-Actor-Peer", config.actorPeerId);+ }++ request<T>(+ method: string,+ path: string,+ options: TransportOptions = {},+ ): Promise<T> {+ return this.consume(method, path, options, (response) =>+ this.parseResponse<T>(response),+ );+ }++ async consume<T>(+ method: string,+ path: string,+ options: TransportOptions,+ consume: (response: Response) => Promise<T>,+ ): Promise<T> {+ const url = new URL(+ `${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`,+ );+ for (const [key, value] of Object.entries(options.query ?? {})) {+ if (value !== undefined && value !== null && value !== "")+ url.searchParams.set(key, String(value));+ }+ if (this.profile) url.searchParams.set("profile", "1");+ const headers = new Headers(this.headers);+ let body: string | FormData | undefined;+ if (options.form) body = options.form;+ else if (options.body !== undefined) {+ headers.set("Content-Type", "application/json");+ body = JSON.stringify(options.body);+ }+ const controller = new AbortController();+ const abort = () => controller.abort(options.signal?.reason);+ options.signal?.addEventListener("abort", abort, { once: true });+ if (options.signal?.aborted) abort();+ const timer = setTimeout(+ () =>+ controller.abort(new DOMException("Request timed out", "TimeoutError")),+ this.timeout,+ );+ try {+ const init: RequestInit = { method, headers, signal: controller.signal };+ if (body !== undefined) init.body = body;+ return await consume(await this.fetcher(url, init));+ } catch (error) {+ if (error instanceof OpenVikingError) throw error;+ if (controller.signal.aborted)+ throw new OpenVikingError("Request timed out or was aborted", {+ code: "DEADLINE_EXCEEDED",+ cause: error,+ });+ throw new OpenVikingError(+ error instanceof Error ? error.message : "Network request failed",+ { code: "UNAVAILABLE", cause: error },+ );+ } finally {+ clearTimeout(timer);+ options.signal?.removeEventListener("abort", abort);+ }+ }++ async parseResponse<T>(response: Response): Promise<T> {+ const text = await response.text();+ let envelope: ResponseEnvelope<T> = {};+ if (text) {+ try {+ envelope = JSON.parse(text) as ResponseEnvelope<T>;+ } catch (cause) {+ throw new OpenVikingError(`HTTP ${response.status}: ${text}`, {+ statusCode: response.status,+ cause,+ });+ }+ }+ if (envelope.error || envelope.status === "error" || !response.ok) {+ const info = envelope.error;+ throw new OpenVikingError(+ info?.message ?? String(envelope.detail ?? `HTTP ${response.status}`),+ compact({+ code: info?.code,+ details: info?.details,+ statusCode: response.status,+ }) as { code?: string; details?: JsonObject; statusCode?: number },+ );+ }+ return envelope.result as T;+ }+}diff --git a/sdk/typescript/src/types.ts b/sdk/typescript/src/types.tsindex 266d7da50..e6769e439 100644--- a/sdk/typescript/src/types.ts+++ b/sdk/typescript/src/types.ts@@ -2,6 +2,15 @@export type JsonObject = Record<string, unknown>;/** One target URI or multiple target scopes. */export type TargetURI = string | string[];+/** Header values accepted without requiring the DOM-only `HeadersInit` alias. */+export type ClientHeaders =+ Headers | Record<string, string> | [string, string][];+/** Temporary upload storage mode supported by the OpenViking server. */+export type UploadMode = "local" | "shared";+/** Conflict policy accepted when importing an OVPack. */+export type PackConflictPolicy = "fail" | "overwrite" | "skip";+/** Vector handling strategy accepted when importing an OVPack. */+export type PackVectorMode = "auto" | "recompute" | "require";/** Connection, identity and transport configuration. */export interface ClientConfig {@@ -11,19 +20,44 @@ export interface ClientConfig {user?: string;actorPeerId?: string;timeout?: number;- headers?: HeadersInit;+ headers?: ClientHeaders;fetch?: typeof globalThis.fetch;profile?: boolean;- uploadMode?: string;+ uploadMode?: UploadMode;}-/** A browser file/blob, a Node.js local path, a remote URL, or inline skill data. */-export type UploadSource = string | Blob;+/** A Node.js local path or remote URL accepted by resource APIs. */+export type UploadSource = string;/** Options shared by OVPack import and restore operations. */export interface ImportPackOptions {- onConflict?: string;- vectorMode?: string;+ onConflict?: PackConflictPolicy;+ vectorMode?: PackVectorMode;+}++/** Options for creating a filesystem snapshot. */+export interface GitCommitOptions {+ message: string;+ paths?: string[];+ branch?: string;+ authorName?: string;+ authorEmail?: string;+}+/** Options for restoring a filesystem snapshot. */+export interface GitRestoreOptions {+ sourceCommit: string;+ projectDir?: string;+ branch?: string;+ dryRun?: boolean;+ message?: string;+ authorName?: string;+ authorEmail?: string;+}+/** Raw file returned by a snapshot lookup. */+export interface GitBlob {+ oid: string;+ size: number;+ bytes: Uint8Array;}/** Per-request cancellation options. */@@ -54,7 +88,7 @@ export interface AddResourceOptions extends WaitOptions {/** Semantic retrieval options. */export interface SearchOptions {targetUri?: TargetURI;- image?: string | Blob;+ image?: string;sessionId?: string;limit?: number;nodeLimit?: number;@@ -119,7 +153,7 @@ export interface GetSkillOptions {includeFiles?: boolean;includeSource?: boolean;level?: number;- targetUri?: TargetURI;+ targetUri?: string;}/** Fields that can be changed on a watch task. */export interface UpdateWatchOptions {diff --git a/sdk/typescript/tests/client.test.ts b/sdk/typescript/tests/client.test.tsindex 203c222fd..11abe1cd7 100644--- a/sdk/typescript/tests/client.test.ts+++ b/sdk/typescript/tests/client.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from "vitest";-import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";import {@@ -47,6 +47,22 @@ describe("OpenVikingClient", () => {});});+ it("uses the Python/Go empty default retrieval target", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(ok({ resources: [] }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.search("hello");++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toMatchObject({+ target_uri: "",+ });+ });+it("maps response envelopes to typed errors", async () => {const fetcher = vi.fn<typeof fetch>().mockResolvedValue(new Response(@@ -83,45 +99,84 @@ describe("OpenVikingClient", () => {);});- it("uploads blobs through the shared resource upload endpoint", async () => {- const fetcher = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(ok({ temp_file_id: "temp-1" }))- .mockResolvedValueOnce(ok({ task_id: "task-1" }));- const client = new OpenVikingClient({- baseUrl: "https://example.com",- fetch: fetcher,- });- await client.addResource(new Blob(["hello"], { type: "text/plain" }));- expect(String(fetcher.mock.calls[0]![0])).toBe(- "https://example.com/api/v1/resources/temp_upload",- );- expect(fetcher.mock.calls[0]![1]?.body).toBeInstanceOf(FormData);- expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toMatchObject({- temp_file_id: "temp-1",- });+ it("converts an existing Node.js image path to a data URI", async () => {+ const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-image-"));+ const path = join(directory, "photo.png");+ await writeFile(path, new Uint8Array([137, 80, 78, 71]));+ try {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.find("", { image: path });++ const body = JSON.parse(String(fetcher.mock.calls[0]![1]?.body));+ expect(body.image_url).toBe("data:image/png;base64,iVBORw==");+ } finally {+ await rm(directory, { recursive: true, force: true });+ }});- it("preserves browser file names and sends the configured upload mode", async () => {- const fetcher = vi- .fn<typeof fetch>()- .mockResolvedValueOnce(ok({ temp_file_id: "temp-file" }))- .mockResolvedValueOnce(ok({ task_id: "task-file" }));+ it("uses the MIME type for a local BMP image", async () => {+ const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-image-"));+ const path = join(directory, "photo.bmp");+ await writeFile(path, new Uint8Array([66, 77]));+ try {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.find("", { image: path });++ const body = JSON.parse(String(fetcher.mock.calls[0]![1]?.body));+ expect(body.image_url).toBe("data:image/bmp;base64,Qk0=");+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ });++ it.each([+ `data:image/png;base64,${"A".repeat(8192)}`,+ "http://example.com/photo.png",+ "https://example.com/photo.png",+ "viking://resources/photo.png",+ ])(+ "passes image references through without filesystem access",+ async (image) => {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.search("", { image });++ const body = JSON.parse(String(fetcher.mock.calls[0]![1]?.body));+ expect(body.image_url).toBe(image);+ },+ );++ it("normalizes empty parts consistently in batch messages", async () => {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(ok({}));const client = new OpenVikingClient({baseUrl: "https://example.com",fetch: fetcher,- uploadMode: "proxy",});- const file = new Blob(["# guide"], { type: "text/markdown" }) as Blob & {- name: string;- };- Object.defineProperty(file, "name", { value: "guide.md" });- await client.addResource(file);+ await client.batchAddMessages("session", [+ { role: "user", content: "hello", parts: [] },+ ]);- const form = fetcher.mock.calls[0]![1]?.body as FormData;- expect((form.get("file") as File).name).toBe("guide.md");- expect(form.get("upload_mode")).toBe("proxy");+ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ messages: [{ role: "user", content: "hello" }],+ });+ expect(() =>+ client.batchAddMessages("session", [{ role: "user", parts: [] }]),+ ).toThrow("each message requires content or parts");});it("maps typed watch options to the server contract", async () => {@@ -188,16 +243,23 @@ describe("OpenVikingClient", () => {});it("maps non-JSON upload failures to OpenVikingError", async () => {- const fetcher = vi- .fn<typeof fetch>()- .mockResolvedValue(new Response("gateway failure", { status: 502 }));- const client = new OpenVikingClient({- baseUrl: "https://example.com",- fetch: fetcher,- });- await expect(client.addResource(new Blob(["hello"]))).rejects.toMatchObject(- { statusCode: 502 },- );+ const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-error-"));+ const path = join(directory, "resource.md");+ await writeFile(path, "hello");+ try {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(new Response("gateway failure", { status: 502 }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });+ await expect(client.addResource(path)).rejects.toMatchObject({+ statusCode: 502,+ });+ } finally {+ await rm(directory, { recursive: true, force: true });+ }});it("uploads an existing Node.js local file instead of sending its path to the server", async () => {@@ -212,8 +274,15 @@ describe("OpenVikingClient", () => {const client = new OpenVikingClient({baseUrl: "https://example.com",fetch: fetcher,+ uploadMode: "shared",});await client.addResource(path);+ expect(String(fetcher.mock.calls[0]![0])).toBe(+ "https://example.com/api/v1/resources/temp_upload",+ );+ const form = fetcher.mock.calls[0]![1]?.body as FormData;+ expect((form.get("file") as File).name).toBe("resource.md");+ expect(form.get("upload_mode")).toBe("shared");expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toMatchObject({ temp_file_id: "temp-local", source_name: "resource.md" },);@@ -221,4 +290,259 @@ describe("OpenVikingClient", () => {await rm(directory, { recursive: true, force: true });}});++ it("streams OVPack exports to a normalized local file", async () => {+ const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-pack-"));+ try {+ await writeFile(join(directory, "docs.ovpack"), "old-backup");+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(new Response(new Uint8Array([1, 2, 3])));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ profile: true,+ });++ const output = await client.exportOVPack(+ "viking://resources/docs",+ directory,+ true,+ );++ expect(output).toBe(join(directory, "docs.ovpack"));+ expect(await readFile(output)).toEqual(Buffer.from([1, 2, 3]));+ expect(await readdir(directory)).toEqual(["docs.ovpack"]);+ const [url, init] = fetcher.mock.calls[0]!;+ expect(new URL(String(url)).searchParams.get("profile")).toBe("1");+ expect(JSON.parse(String(init?.body))).toEqual({+ uri: "viking://resources/docs",+ include_vectors: true,+ });+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ });++ it.each([true, false])(+ "preserves the final OVPack when a download stream fails",+ async (existingOutput) => {+ const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-pack-"));+ const output = join(directory, "backup.ovpack");+ if (existingOutput) await writeFile(output, "known-good-backup");+ let pulls = 0;+ try {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(+ new Response(+ new ReadableStream({+ pull(controller) {+ if (pulls++ === 0)+ controller.enqueue(new TextEncoder().encode("partial"));+ else controller.error(new Error("connection reset"));+ },+ }),+ {+ status: 200,+ headers: { "Content-Type": "application/octet-stream" },+ },+ ),+ );+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await expect(client.backupOVPack(output)).rejects.toMatchObject({+ code: "UNAVAILABLE",+ });++ if (existingOutput)+ expect(await readFile(output, "utf8")).toBe("known-good-backup");+ else+ await expect(readFile(output)).rejects.toMatchObject({+ code: "ENOENT",+ });+ expect(await readdir(directory)).toEqual(+ existingOutput ? ["backup.ovpack"] : [],+ );+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ },+ );++ it("maps structured OVPack download failures", async () => {+ const fetcher = vi.fn<typeof fetch>().mockResolvedValue(+ new Response(+ JSON.stringify({+ status: "error",+ error: { code: "FORBIDDEN", message: "denied" },+ }),+ { status: 403 },+ ),+ );+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await expect(client.backupOVPack("backup")).rejects.toMatchObject({+ code: "FORBIDDEN",+ statusCode: 403,+ });+ });++ it("maps non-JSON OVPack download failures", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValue(new Response("gateway failure", { status: 502 }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await expect(client.backupOVPack("backup")).rejects.toMatchObject({+ statusCode: 502,+ });+ });++ it("cancels OVPack downloads on timeout", async () => {+ const fetcher = vi.fn<typeof fetch>().mockImplementation(+ async (_input, init) =>+ new Promise<Response>((_resolve, reject) => {+ init?.signal?.addEventListener("abort", () =>+ reject(init.signal?.reason),+ );+ }),+ );+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ timeout: 5,+ });++ await expect(client.backupOVPack("backup")).rejects.toMatchObject({+ code: "DEADLINE_EXCEEDED",+ });+ });++ it("forwards caller cancellation to OVPack downloads", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockImplementation(async (_input, init) => {+ if (init?.signal?.aborted) throw init.signal.reason;+ return new Response(new Uint8Array([1]));+ });+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });+ const controller = new AbortController();+ controller.abort(new Error("cancelled"));++ await expect(+ client.backupOVPack("backup", false, { signal: controller.signal }),+ ).rejects.toMatchObject({ code: "DEADLINE_EXCEEDED" });+ });++ it("rejects directories before importing or restoring OVPack files", async () => {+ const directory = await mkdtemp(join(tmpdir(), "openviking-sdk-pack-dir-"));+ try {+ const fetcher = vi.fn<typeof fetch>();+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await expect(+ client.importOVPack(directory, "viking://resources"),+ ).rejects.toThrow("expected an OVPack file");+ await expect(client.restoreOVPack(directory)).rejects.toThrow(+ "expected an OVPack file",+ );+ expect(fetcher).not.toHaveBeenCalled();+ } finally {+ await rm(directory, { recursive: true, force: true });+ }+ });++ it("maps relation and snapshot APIs to the Python contracts", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(ok([]))+ .mockResolvedValueOnce(ok({}))+ .mockResolvedValueOnce(ok({}))+ .mockResolvedValueOnce(ok({ oid: "commit" }))+ .mockResolvedValueOnce(ok({ is_healthy: true }));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.relations("resources/a");+ await client.link("resources/a", ["resources/b"]);+ await client.unlink("resources/a", "resources/b");+ await client.gitCommit({ message: "snapshot" });+ await expect(client.isHealthy()).resolves.toBe(true);++ expect(String(fetcher.mock.calls[0]![0])).toContain(+ "uri=viking%3A%2F%2Fresources%2Fa",+ );+ expect(JSON.parse(String(fetcher.mock.calls[1]![1]?.body))).toMatchObject({+ from_uri: "viking://resources/a",+ to_uris: ["viking://resources/b"],+ });+ expect(JSON.parse(String(fetcher.mock.calls[3]![1]?.body))).toEqual({+ message: "snapshot",+ branch: "main",+ });+ });++ it("supports snapshot restore, binary show, log and ignore operations", async () => {+ const fetcher = vi+ .fn<typeof fetch>()+ .mockResolvedValueOnce(ok({ oid: "restored" }))+ .mockResolvedValueOnce(+ new Response(new Uint8Array([4, 5]), {+ headers: {+ "Content-Type": "application/octet-stream",+ "X-Snapshot-Oid": "blob-1",+ "X-Snapshot-Size": "2",+ },+ }),+ )+ .mockResolvedValueOnce(ok([{ oid: "commit-1" }]))+ .mockResolvedValueOnce(ok("*.tmp\n"))+ .mockResolvedValueOnce(ok(null))+ .mockResolvedValueOnce(ok(null));+ const client = new OpenVikingClient({+ baseUrl: "https://example.com",+ fetch: fetcher,+ });++ await client.gitRestore({ sourceCommit: "old", dryRun: true });+ await expect(+ client.gitShow("main", "viking://resources/a"),+ ).resolves.toEqual({+ oid: "blob-1",+ size: 2,+ bytes: new Uint8Array([4, 5]),+ });+ await expect(client.gitLog()).resolves.toEqual([{ oid: "commit-1" }]);+ await expect(client.gitGetIgnore()).resolves.toBe("*.tmp\n");+ await client.gitSetIgnore("*.log\n");+ await client.gitDeleteIgnore();++ expect(JSON.parse(String(fetcher.mock.calls[0]![1]?.body))).toEqual({+ source_commit: "old",+ branch: "main",+ dry_run: true,+ });+ expect(+ new URL(String(fetcher.mock.calls[1]![0])).searchParams.get("path"),+ ).toBe("viking://resources/a");+ expect(JSON.parse(String(fetcher.mock.calls[4]![1]?.body))).toEqual({+ content: "*.log\n",+ });+ });});diff --git a/sdk/typescript/tests/node-consumer/index.ts b/sdk/typescript/tests/node-consumer/index.tsnew file mode 100644index 000000000..acdef1158--- /dev/null+++ b/sdk/typescript/tests/node-consumer/index.ts@@ -0,0 +1,22 @@+import { OpenVikingClient } from "../../dist/index.js";++export const client = new OpenVikingClient({+ baseUrl: "https://example.com",+});++// @ts-expect-error the server only accepts local or shared temporary uploads.+new OpenVikingClient({ baseUrl: "https://example.com", uploadMode: "proxy" });++client.getSkill("demo", { targetUri: "viking://agent/skills" });+// @ts-expect-error getSkill accepts one concrete skill root, not multiple roots.+client.getSkill("demo", { targetUri: ["viking://agent/skills"] });++client.exportOVPack("viking://resources/docs", "./docs.ovpack");+client.importOVPack("./docs.ovpack", "viking://resources", {+ onConflict: "overwrite",+ vectorMode: "auto",+});+// @ts-expect-error OVPack conflict policies are restricted by the server.+client.restoreOVPack("./docs.ovpack", { onConflict: "replace" });+client.gitCommit({ message: "snapshot", branch: "main" });+client.relations("viking://resources/docs");diff --git a/sdk/typescript/tests/node-consumer/tsconfig.json b/sdk/typescript/tests/node-consumer/tsconfig.jsonnew file mode 100644index 000000000..7f88f5379--- /dev/null+++ b/sdk/typescript/tests/node-consumer/tsconfig.json@@ -0,0 +1,13 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "lib": ["ES2022"],+ "types": ["node"],+ "strict": true,+ "skipLibCheck": false,+ "noEmit": true+ },+ "include": ["index.ts"]+}diff --git a/sdk/typescript/tsconfig.json b/sdk/typescript/tsconfig.jsonindex 5ebe65d40..58c9326e2 100644--- a/sdk/typescript/tsconfig.json+++ b/sdk/typescript/tsconfig.json@@ -3,7 +3,7 @@"target": "ES2022","module": "ESNext","moduleResolution": "Bundler",- "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "lib": ["ES2022"],"types": ["node"],"strict": true,"noUncheckedIndexedAccess": true,@@ -11,5 +11,6 @@"declaration": true,"skipLibCheck": true},- "include": ["src", "tests"]+ "include": ["src", "tests/client.test.ts"],+ "exclude": ["tests/node-consumer"]}