Files
NianJiu 832b5fede8 ci: close 6 production test gate blind spots and add Lite E2E smoke test
Why:
PR CI previously left six production-critical paths unverified:
1. .github/workflows/app.yml ran without PostgreSQL/ParadeDB or Redis service
   containers and left WEKNORA_*_POSTGRES_DSN / WEKNORA_TEST_REDIS_ADDR unset,
   causing all PostgreSQL migration, row-locking, pgvector, catalog, and
   multi-replica Redis tests to 100% t.Skip (masking a step-down regression in
   TestPostgresMigrationsServeAgentHistory once migrations >000106 were added).
2. app.yml invoked go vet/test without -tags sqlite_fts5, causing SQLite FTS5
   retriever tests under internal/application/repository/retriever/sqlite to
   100% t.Skip.
3. Desktop build-tag checks only ran ./internal/container, missing
   ./internal/application/service, ./cmd/desktop, and darwin/windows
   cross-compilation of ./internal/localsandbox/{seatbelt,winhost}, while
   release-lite.yml remained pinned to GO_VERSION=1.24 (go.mod requires 1.26.0).
4. The standalone client/ Go SDK module was excluded by app.yml (!client/**)
   and ignored by cli.yml / cli-e2e.yml / pre-push hooks despite cli/
   depending on ../client (masking unformatted files and a Unix-only 0o640
   permission assertion on Windows in client/).
5. High-concurrency packages (internal/stream, internal/sandbox,
   internal/agent, internal/im) ran without -race, and PR CI had no
   zero-external-dependency Lite mode end-to-end smoke test.

What:
- Provision paradedb/paradedb:v0.25.11-pg17 and redis:7.0-alpine services in
  app.yml, create isolated disposable test databases, and inject all
  PostgreSQL/Redis test DSNs with WEKNORA_REQUIRE_INTEGRATION=1; fix
  TestPostgresMigrationsServeAgentHistory to migrate down before 000106 and
  back up instead of stepping -1 from HEAD.
- Pass -tags sqlite_fts5 across app.yml and git hooks while keeping an explicit
  non-FTS5 run for TestSaveWorksWhenTheFTS5ModuleIsNotCompiledIn.
- Vet, test, and build ./internal/container, ./internal/application/service,
  and ./cmd/desktop with -tags desktop,sqlite_fts5; isolate cgo-only pg_query
  and gojieba bindings behind !cgo stubs so darwin/arm64 and windows/amd64
  cross-compilation of ./internal/localsandbox/... runs on Linux CI; align
  release-lite.yml GO_VERSION to 1.26.
- Watch client/** in cli.yml, cli-e2e.yml, and git pre-push hooks, running
  client gofmt, build, vet, and -race tests across Linux, macOS, and Windows,
  and fix the pre-existing gofmt drift and Windows permission assertion in
  client/ uncovered by the new gate.
- Enable -race on internal/{stream,sandbox,agent,im}/... and add
  tests/lite_smoke/lite_e2e_test.go exercising a real WeKnora-lite subprocess
  end-to-end (auth, models, KB, Markdown upload/indexing, vector+FTS5 search,
  SSE RAG chat, message persistence, and SIGTERM shutdown).
2026-11-18 15:10:24 +08:00
..
2025-08-05 15:08:07 +08:00
2025-08-05 15:08:07 +08:00
2025-08-05 15:08:07 +08:00
2026-08-05 14:42:51 +08:00

WeKnora HTTP Client

This package provides a client library for interacting with WeKnora services, supporting all HTTP-based interface calls, making it easier for other modules to integrate with WeKnora services without having to write HTTP request code directly.

Main Features

The client includes the following main functional modules:

  1. Session Management: Create, retrieve, update, and delete sessions
  2. Knowledge Base Management: Create, retrieve, update, and delete knowledge bases
  3. Knowledge Management: Add, retrieve, and delete knowledge content
  4. Workspace Management: CRUD operations for workspaces
  5. Knowledge Q&A: Supports regular Q&A and streaming Q&A
  6. Chunk Management: Query, update, and delete knowledge chunks
  7. Message Management: Retrieve and delete session messages
  8. Model Management: Create, retrieve, update, and delete models
  9. Evaluation Function: Start evaluation tasks and get evaluation results
  10. Sandbox skills: Install a skill onto a sandbox config (zip upload, or ClawHub / SkillHub / GitHub source) and configure the environment variables it needs
  11. Long-term memory: The caller's cross-session memories (settings, items, confirm/reject, topics, document affinity, export, consolidate)
  12. Auth: Login, refresh tokens, and switch the active workspace (SwitchTenant records the last-active-tenant preference)

Usage

Creating Client Instance

import (
    "context"
    "github.com/Tencent/WeKnora/client"
    "time"
)

// Create client instance
apiClient := client.NewClient(
    "http://api.example.com", 
    client.WithToken("your-auth-token"),
    client.WithTimeout(30*time.Second),
)

Workspace Configuration

You can set a default workspace with WithTenantID; the client will automatically send the X-Tenant-ID header:

tenantID := uint64(10000)
apiClient := client.NewClient(
    "http://api.example.com",
    client.WithToken("your-auth-token"),
    client.WithTenantID(tenantID),
)

If a single request needs a different workspace, set TenantID in the request context. The value can be a uint64, *uint64, or a numeric string, and it will take precedence over the client default:

ctx := context.WithValue(context.Background(), "TenantID", uint64(10000))
// Pass ctx into any client method to switch to workspace 10000 for that request

Example: Create Knowledge Base and Upload File

// Create knowledge base
kb := &client.KnowledgeBase{
    Name:        "Test Knowledge Base",
    Description: "This is a test knowledge base",
    ChunkingConfig: client.ChunkingConfig{
        ChunkSize:    500,
        ChunkOverlap: 50,
        Separators:   []string{"\n\n", "\n", ". ", "? ", "! "},
    },
    ImageProcessingConfig: client.ImageProcessingConfig{
        ModelID: "image_model_id",
    },
    EmbeddingModelID: "embedding_model_id",
    SummaryModelID:   "summary_model_id",
}

kb, err := apiClient.CreateKnowledgeBase(context.Background(), kb)
if err != nil {
    // Handle error
}

// Upload knowledge file with metadata
metadata := map[string]string{
    "source": "local",
    "type":   "document",
}
knowledge, err := apiClient.CreateKnowledgeFromFile(context.Background(), kb.ID, "path/to/file.pdf", metadata)
if err != nil {
    // Handle error
}

// Download original files from one knowledge base as a ZIP (max 200 IDs, 512 MiB)
err = apiClient.DownloadKnowledgeFiles(context.Background(), kb.ID, []string{knowledge.ID}, "knowledge-files.zip")
if err != nil {
    // Handle error
}

Example: Create Session and Chat

// Create session
sessionRequest := &client.CreateSessionRequest{
    KnowledgeBaseID: knowledgeBaseID,
    SessionStrategy: &client.SessionStrategy{
        MaxRounds:        10,
        EnableRewrite:    true,
        FallbackStrategy: "fixed_answer",
        FallbackResponse: "Sorry, I cannot answer this question",
        EmbeddingTopK:    5,
        KeywordThreshold: 0.5,
        VectorThreshold:  0.7,
        RerankModelID:    "rerank_model_id",
        RerankTopK:       3,
        RerankThreshold:  0.8,
        SummaryModelID:   "summary_model_id",
    },
}

session, err := apiClient.CreateSession(context.Background(), sessionRequest)
if err != nil {
    // Handle error
}

// Regular Q&A
answer, err := apiClient.KnowledgeQA(context.Background(), session.ID, &client.KnowledgeQARequest{
    Query: "What is artificial intelligence?",
})
if err != nil {
    // Handle error
}

// Streaming Q&A
err = apiClient.KnowledgeQAStream(context.Background(), session.ID, &client.KnowledgeQARequest{Query: "What is machine learning?"}, func(response *client.StreamResponse) error {
    // Handle each response chunk
    fmt.Print(response.Content)
    return nil
})
if err != nil {
    // Handle error
}

Example: Managing Models

// Create model
modelRequest := &client.CreateModelRequest{
    Name:        "Test Model",
    Type:        client.ModelTypeChat,
    Source:      client.ModelSourceInternal,
    Description: "This is a test model",
    Parameters: client.ModelParameters{
        "temperature": 0.7,
        "top_p":       0.9,
    },
    IsDefault: true,
}
model, err := apiClient.CreateModel(context.Background(), modelRequest)
if err != nil {
    // Handle error
}

// List all models
models, err := apiClient.ListModels(context.Background())
if err != nil {
    // Handle error
}

Example: Managing Knowledge Chunks

// List knowledge chunks
chunks, total, err := apiClient.ListKnowledgeChunks(context.Background(), knowledgeID, 1, 10)
if err != nil {
    // Handle error
}

// Update chunk
updateRequest := &client.UpdateChunkRequest{
    Content:   "Updated chunk content",
    IsEnabled: true,
}
updatedChunk, err := apiClient.UpdateChunk(context.Background(), knowledgeID, chunkID, updateRequest)
if err != nil {
    // Handle error
}

Example: Getting Session Messages

// Get recent messages
messages, err := apiClient.GetRecentMessages(context.Background(), sessionID, 10)
if err != nil {
    // Handle error
}

// Get messages before a specific time
beforeTime := time.Now().Add(-24 * time.Hour)
olderMessages, err := apiClient.GetMessagesBefore(context.Background(), sessionID, beforeTime, 10)
if err != nil {
    // Handle error
}

Example: Install a sandbox skill from a registry

source must be explicit: @owner/slug for ClawHub, a full https://clawhub.ai/skills-sh/owner/repo/slug (or skills-sh:owner/repo/slug) for federated skills.sh listings, or a full GitHub / SkillHub URL. Bare owner/slug is rejected.

skillID, err := apiClient.InstallSandboxSkillFromSource(
    context.Background(), sandboxConfigID, "@owner/slug")
if err != nil {
    // Handle error
}
_ = skillID // follow /sandbox-configs/{id}/skills/{skillID}/install-events

Example: Stop a stuck install

After a process restart the row may sit at installing with nothing running, which hides retry and uninstall. Stop rewrites the row immediately (and cancels the in-process goroutine if one is still alive). Then retry or uninstall as usual.

skill, err := apiClient.StopSandboxSkill(context.Background(), sandboxConfigID, skillID)
if err != nil {
    // Handle error
}
_ = skill

Example: Retry a failed install

Installs usually fail for reasons the bundle cannot fix — an unreachable sandbox, a package index that timed out. The server still holds the archive, so the retry needs nothing from you.

skillID, err := apiClient.ReinstallSandboxSkill(context.Background(), sandboxConfigID, skillID)
if err != nil {
    // Handle error
}

Example: Browse files of an installed skill

files, err := apiClient.ListSandboxSkillFiles(context.Background(), sandboxConfigID, skillID)
if err != nil {
    // Handle error
}
content, err := apiClient.GetSandboxSkillFile(context.Background(), sandboxConfigID, skillID, "SKILL.md")
if err != nil {
    // Handle error
}
_ = files
_ = content

Example: Configure a skill's environment variables

A skill declares the environment variables it needs when it is installed. Values live in two layers: a workspace value an admin sets for everybody, and a per-identity value that overrides it for the caller alone. No endpoint reads a stored value back; they only report whether one is set.

An API key and a web login are different identities: a personal value entered through the web UI does not apply to runs driven by an API key. Prefer workspace values for integrations.

// Workspace-wide, applies to everybody; requires Admin or above
skill, err := apiClient.SetSandboxSkillEnvValues(
    context.Background(), sandboxConfigID, skillID,
    map[string]string{"TAVILY_API_KEY": "tvly-xxxxx"})
if err != nil {
    // Handle error
}

// Applies to the calling identity alone
err = apiClient.SetMySkillEnvVar(
    context.Background(), skillID, "TAVILY_API_KEY", "tvly-yyyyy")
if err != nil {
    // Handle error
}

// See what is still unset. Clearing a value is a delete, not a write of ""
groups, err := apiClient.ListMyEnvVars(context.Background())
if err != nil {
    // Handle error
}
_ = skill
_ = groups

Complete Example

Please refer to the ExampleUsage function in the example.go file, which demonstrates the complete usage flow of the client.