WeKnora/client
lyingbug 4d4acec418
feat(assistant): manage agents and skills, separate history, refresh pages (#4344)
* feat(assistant): let the assistant manage agents

Expose custom agents to the operation catalog (list, get, create, copy,
update, delete) plus read-only model and MCP service lookups, so the
assistant can set up agents end to end.

- Add PATCH /api/v1/agents/:id. PUT replaces the whole config, so a
  one-field change from the assistant would wipe the rest; PATCH only
  overlays the fields it carries and reuses the PUT validation path.
- Add x-agent-detail so long fields such as the system prompt are only
  projected for single-object reads, not lists.
- Add label_param so a create without a target is labelled by its name.
- The approval card lists agent setting changes and resolves model,
  knowledge base and MCP IDs to names.
- Deny sharing, publishing channels, credentials and OAuth routes; model
  and MCP endpoints, headers and secrets are never projected.
- Update the assistant prompt, starters, API docs and Go SDK.

* feat(assistant): list skills and configure agent skill scope

- Expose usable skill names for an agent sandbox without exposing skill
  administration or connection settings to the model.
- Validate PATCH selections against the workspace sandbox usable set so
  invented names and missing sandbox selections cannot be saved.
- Show skill changes in approvals and align the assistant prompt, API
  documentation, and Go SDK with focused refusal and projection tests.

* feat(assistant): isolate conversation history

- Keep assistant conversations out of ordinary session lists, search, artifacts and delete-all cleanup.
- Add private, paginated assistant history with session switching, confirmed deletion and stale-session recovery.
- Backfill session kinds safely on Postgres and SQLite, preserve kinds on forks, and align API docs and SDK coverage.

* feat(assistant): refresh pages after successful data changes

- Carry decoded mutation targets through live tool-result events without
  exposing refresh metadata to the model or persisted chat history.
- Coalesce page and selector refreshes, update document drawers, and warn
  about changed agents while preserving open editor drafts.
- Cover mutation, approval, stream, lifecycle and cache behavior with Go
  and Node tests using the existing frontend runner and component fixtures.

* feat(assistant): add agent page context and resource scope limits

- Attach verified agent context and persist personal scope across turns and approvals.
- Enforce resource boundaries before operation and Wiki approvals, including edited arguments.
- Add scope controls, translations, API and SDK support, and regression coverage.

* refactor(assistant): remove the scope limit

The scope picker confused users and duplicated what RBAC and the access
level already enforce. Keep the agent page context: the agent editor
still publishes agent_id and the backend still verifies it.

* feat(assistant): render operation and product-doc results

Show find/run operations and WeKnora docs as structured cards instead of raw JSON.

* feat(assistant): default new agents to smart-reasoning

Quick-answer cannot call MCP, and agent.update could not change the mode. New agents now start in smart-reasoning, and a patch can switch agent_mode.

* fix: resolve assistant management CI failures
2026-10-15 21:43:20 +08:00
..
README.md feat(knowledge): add batch file downloads (#3300) 2026-09-16 15:40:10 +08:00
README_EN.md feat(knowledge): add batch file downloads (#3300) 2026-09-16 15:40:10 +08:00
agent.go feat(agent): add the built-in WeKnora assistant with an operation catalog (#4302) 2026-10-15 12:18:30 +08:00
agent_manage.go feat(assistant): manage agents and skills, separate history, refresh pages (#4344) 2026-10-15 21:43:20 +08:00
agent_manage_test.go feat(assistant): manage agents and skills, separate history, refresh pages (#4344) 2026-10-15 21:43:20 +08:00
auth.go fix(auth): record last-active-tenant preference on SwitchTenant (#2922) 2026-09-01 15:43:40 +08:00
chunk.go feat: Support filtering chunks by multiple chunk_type params 2026-05-25 19:14:46 +08:00
client.go feat(sdk): typed errors, enums, and KB model config for the CLI 2026-07-06 22:53:01 +08:00
env_var.go ui(sandbox): redesign personal sandbox secrets settings 2026-08-27 16:55:09 +08:00
evaluation.go init commit 2025-08-05 15:08:07 +08:00
example.go feat(client): enhance knowledge file upload with process configuration support 2026-06-09 20:38:24 +08:00
faq.go feat: add matched question field to FAQ search results 2026-01-26 16:32:18 +08:00
go.mod init commit 2025-08-05 15:08:07 +08:00
go.sum init commit 2025-08-05 15:08:07 +08:00
initialization.go feat: support editing document summaries (#2752) 2026-08-20 14:54:53 +08:00
knowledge.go fix(client): make multipart uploads replayable (#3989) 2026-10-08 01:28:12 +08:00
knowledgebase.go feat(retrieval): unify rerank across search APIs and expose diagnostics (#3675) 2026-09-24 20:41:49 +08:00
knowledgebase_duplicate_test.go Simplify KB duplicate API and improve naming/docs coverage. 2026-07-08 20:55:54 +08:00
log.go feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider 2026-05-18 11:10:19 +08:00
log_test.go feat(cli): --log-level + kb/agent status & check + cross-cutting refactor 2026-05-18 11:10:19 +08:00
mcp_endpoint.go feat(mcp): add built-in MCP server with per-workspace endpoints (#3371) 2026-09-17 22:40:05 +08:00
mcp_service.go feat(agent): persist human-in-the-loop prompts with a shared broker (#4250) 2026-10-14 20:37:28 +08:00
memory.go chore: prepare v0.8.0 release notes and version bump 2026-09-03 14:46:44 +08:00
message.go style(client): gofmt message.go 2026-08-05 14:42:51 +08:00
message_suggestion.go feat(agent): add question suggestions with after-answer follow-ups 2026-07-14 11:17:25 +08:00
model.go feat: add LiteLLM as a model provider (#2923) 2026-09-01 12:21:03 +08:00
organization.go chore(client): remove redeclared `UserInfo` in client package 2026-03-24 11:52:15 +08:00
resource_urls.go feat(api): honor resource_urls=public on hybrid-search 2026-08-26 17:40:54 +08:00
resource_urls_test.go fix(api): address resource_urls review follow-ups 2026-08-05 14:42:51 +08:00
retrieval.go feat(retrieval): unify rerank across search APIs and expose diagnostics (#3675) 2026-09-24 20:41:49 +08:00
session.go feat(assistant): manage agents and skills, separate history, refresh pages (#4344) 2026-10-15 21:43:20 +08:00
session_test.go feat(assistant): manage agents and skills, separate history, refresh pages (#4344) 2026-10-15 21:43:20 +08:00
skill.go fix(client): make multipart uploads replayable (#3989) 2026-10-08 01:28:12 +08:00
sse.go fix(client): accumulate multiline SSE data (#2122) 2026-09-25 22:23:38 +08:00
stream_errors.go fix(cli): align stream error handling after output-mode merge 2026-07-03 00:30:34 +08:00
stream_errors_test.go fix(cli): align stream error handling after output-mode merge 2026-07-03 00:30:34 +08:00
streaming_test.go fix(client): accept optional spaces in SSE event fields (#3975) 2026-10-08 01:28:38 +08:00
system.go fix: filter menus by deployment capabilities (#2674) 2026-08-13 20:18:48 +08:00
tag.go feat: 为 FAQ 和标签引入 seq_id 支持 2026-01-14 17:13:44 +08:00
tenant.go feat: support updating API key configuration 2026-08-12 11:43:03 +08:00
web_search.go feat: add agent management functionality 2026-03-09 17:34:13 +08:00

README_EN.md

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, "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.