From 8f36ea22290c15a6151bbd6a1a834926d3c685ea Mon Sep 17 00:00:00 2001 From: nullkey Date: Fri, 26 Jun 2026 20:40:59 +0800 Subject: [PATCH] feat(sdk): typed errors, enums, and KB model config for the CLI Adds the client-library surface the agent-first CLI builds on: - named server error-code constants + typed *APIError from non-2xx responses, - MessageSearchMode / AgentMode / KBSelectionMode and model type/source enumerators so the CLI validates flags against the server vocabulary, - SetKBModelConfig for binding embedding/chat models to a knowledge base. --- client/agent.go | 2 +- client/agent_manage.go | 40 +++++++++++++++++++++++++++ client/client.go | 58 +++++++++++++++++++++++++++++++++++++++- client/initialization.go | 27 ++++++++++++++++++- client/knowledge.go | 2 +- client/mcp_service.go | 25 +++++++++++++++++ client/message.go | 27 ++++++++++++++++++- client/model.go | 24 +++++++++++++++++ client/session.go | 6 ++--- 9 files changed, 203 insertions(+), 8 deletions(-) diff --git a/client/agent.go b/client/agent.go index 3f669735..330f8080 100644 --- a/client/agent.go +++ b/client/agent.go @@ -94,7 +94,7 @@ func (c *Client) AgentQAStreamWithRequest(ctx context.Context, if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + return newAPIError(resp.StatusCode, body) } // Process SSE stream diff --git a/client/agent_manage.go b/client/agent_manage.go index 92ee1428..190aca6c 100644 --- a/client/agent_manage.go +++ b/client/agent_manage.go @@ -28,6 +28,46 @@ type Agent struct { CreatorName string `json:"creator_name,omitempty"` } +// AgentMode is an agent's operating mode (AgentConfig.AgentMode). It mirrors +// the server constants in internal/types/custom_agent.go. +type AgentMode string + +const ( + // AgentModeQuickAnswer is the RAG mode for quick Q&A. + AgentModeQuickAnswer AgentMode = "quick-answer" + // AgentModeSmartReasoning is the ReAct mode for multi-step reasoning. + AgentModeSmartReasoning AgentMode = "smart-reasoning" +) + +// AllAgentModes returns every agent operating mode the server recognises, in a +// stable order. Use this instead of re-typing the set so callers can't drift +// from the SDK. +func AllAgentModes() []AgentMode { + return []AgentMode{AgentModeQuickAnswer, AgentModeSmartReasoning} +} + +// KBSelectionMode controls how an agent selects knowledge bases +// (AgentConfig.KBSelectionMode). It mirrors the server's documented values +// ("all" | "selected" | "none") in internal/types/custom_agent.go. +type KBSelectionMode string + +const ( + // KBSelectionModeAll retrieves across every knowledge base. + KBSelectionModeAll KBSelectionMode = "all" + // KBSelectionModeSelected retrieves only the agent's attached KBs + // (AgentConfig.KnowledgeBases). + KBSelectionModeSelected KBSelectionMode = "selected" + // KBSelectionModeNone disables knowledge base retrieval. + KBSelectionModeNone KBSelectionMode = "none" +) + +// AllKBSelectionModes returns every KB selection mode the server recognises, in +// a stable order. Use this instead of re-typing the set so callers can't drift +// from the SDK. +func AllKBSelectionModes() []KBSelectionMode { + return []KBSelectionMode{KBSelectionModeAll, KBSelectionModeSelected, KBSelectionModeNone} +} + // AgentConfig represents the configuration for an agent. // Field names and JSON tags mirror internal/types.CustomAgentConfig. type AgentConfig struct { diff --git a/client/client.go b/client/client.go index 9e6c7e0e..02d8182b 100644 --- a/client/client.go +++ b/client/client.go @@ -225,13 +225,69 @@ func (c *Client) Raw(ctx context.Context, method, path string, body interface{}) return c.doRequest(ctx, method, path, body, nil) } +// APIError is a typed non-2xx HTTP response from the WeKnora API. Recover it +// with errors.As to branch on the HTTP status or the server's structured error +// code without parsing the Error() string: +// +// var apiErr *client.APIError +// if errors.As(err, &apiErr) && apiErr.StatusCode == 404 { ... } +// +// Error() intentionally preserves the legacy "HTTP error : " +// format so existing string-matching consumers keep working unchanged. +type APIError struct { + StatusCode int // HTTP status (401, 404, 409, 429, 500, …) + Body string // raw response body + Code int // server's structured error code ({"code":N}); 0 when absent/non-JSON +} + +func (e *APIError) Error() string { + return fmt.Sprintf("HTTP error %d: %s", e.StatusCode, e.Body) +} + +// Server error codes are the values of the {"code":N} field in an error +// response body, surfaced as APIError.Code. These mirror the generic codes in +// the server's internal/errors/errors.go so consumers branch on a named +// constant instead of a magic number. Domain-specific codes (2xxx+) are +// omitted until a consumer needs to branch on one. +const ( + ServerErrBadRequest = 1000 + ServerErrUnauthorized = 1001 + ServerErrForbidden = 1002 + ServerErrNotFound = 1003 + ServerErrMethodNotAllowed = 1004 + ServerErrConflict = 1005 + ServerErrTooManyRequests = 1006 + ServerErrInternalServer = 1007 + ServerErrServiceUnavailable = 1008 + ServerErrTimeout = 1009 + ServerErrValidation = 1010 +) + +// newAPIError builds an *APIError from a non-2xx response's status and raw body, +// extracting the server's structured {"code":N} when the body is JSON. +func newAPIError(status int, body []byte) *APIError { + return &APIError{StatusCode: status, Body: string(body), Code: extractServerCode(body)} +} + +// extractServerCode pulls the server's structured error code from a JSON error +// body ({"code":1003,...}). Returns 0 when the body isn't JSON or carries no code. +func extractServerCode(body []byte) int { + var env struct { + Code int `json:"code"` + } + if json.Unmarshal(body, &env) == nil { + return env.Code + } + return 0 +} + // parseResponse parses an HTTP response func parseResponse(resp *http.Response, target interface{}) error { defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + return newAPIError(resp.StatusCode, body) } if target == nil { diff --git a/client/initialization.go b/client/initialization.go index c26f2e31..cbbab475 100644 --- a/client/initialization.go +++ b/client/initialization.go @@ -65,7 +65,11 @@ func (c *Client) InitializeByKB(ctx context.Context, kbID string, config *Initia return parseResponse(resp, nil) } -// UpdateKBConfig updates the model configuration for a knowledge base +// UpdateKBConfig updates the model configuration for a knowledge base. +// +// Deprecated: the PUT /initialization/config endpoint binds KBModelConfigRequest +// (fields llmModelId / embeddingModelId), not InitializationConfig, so this +// method sends a shape the server rejects. Use SetKBModelConfig instead. func (c *Client) UpdateKBConfig(ctx context.Context, kbID string, config *InitializationConfig) error { resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/initialization/config/%s", kbID), config, nil) if err != nil { @@ -74,6 +78,27 @@ func (c *Client) UpdateKBConfig(ctx context.Context, kbID string, config *Initia return parseResponse(resp, nil) } +// KBModelConfig points a knowledge base at already-registered models. Field +// names match the server's KBModelConfigRequest (PUT +// /initialization/config/:kbId). LLMModelID is required server-side; +// EmbeddingModelID is optional (omitted when RAG indexing is disabled). +type KBModelConfig struct { + LLMModelID string `json:"llmModelId"` + EmbeddingModelID string `json:"embeddingModelId,omitempty"` +} + +// SetKBModelConfig binds a knowledge base to already-registered models via PUT +// /initialization/config/:kbId. Register models first with CreateModel; the +// server rejects unknown model ids and refuses to change the embedding model of +// a KB that already has documents. +func (c *Client) SetKBModelConfig(ctx context.Context, kbID string, cfg *KBModelConfig) error { + resp, err := c.doRequest(ctx, http.MethodPut, fmt.Sprintf("/api/v1/initialization/config/%s", kbID), cfg, nil) + if err != nil { + return err + } + return parseResponse(resp, nil) +} + // CheckOllamaStatus checks if Ollama is running and accessible func (c *Client) CheckOllamaStatus(ctx context.Context) (bool, error) { resp, err := c.doRequest(ctx, http.MethodGet, "/api/v1/initialization/ollama/status", nil, nil) diff --git a/client/knowledge.go b/client/knowledge.go index 35455bbd..8bfbe299 100644 --- a/client/knowledge.go +++ b/client/knowledge.go @@ -441,7 +441,7 @@ func (c *Client) OpenKnowledgeFile(ctx context.Context, knowledgeID string) (str if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) _ = resp.Body.Close() - return "", nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + return "", nil, newAPIError(resp.StatusCode, body) } filename := filenameFromContentDisposition(resp.Header.Get("Content-Disposition")) return filename, resp.Body, nil diff --git a/client/mcp_service.go b/client/mcp_service.go index f5680c04..ba603515 100644 --- a/client/mcp_service.go +++ b/client/mcp_service.go @@ -212,3 +212,28 @@ func (c *Client) GetMCPServiceResources(ctx context.Context, serviceID string) ( } return result.Data, nil } + +// ResolveToolApprovalRequest is the body for resolving a pending tool-approval +// raised during an agent run (session ask). Decision is "approve" or "reject". +// ModifiedArgs optionally replaces the tool call arguments on approve; it must +// be a JSON object when present. +type ResolveToolApprovalRequest struct { + Decision string `json:"decision"` + Reason string `json:"reason,omitempty"` + ModifiedArgs json.RawMessage `json:"modified_args,omitempty"` +} + +// ResolveToolApproval resolves a pending tool approval by id. +// Server route: POST /api/v1/agent/tool-approvals/{pending_id}. +func (c *Client) ResolveToolApproval(ctx context.Context, pendingID string, req *ResolveToolApprovalRequest) error { + path := fmt.Sprintf("/api/v1/agent/tool-approvals/%s", pendingID) + resp, err := c.doRequest(ctx, http.MethodPost, path, req, nil) + if err != nil { + return err + } + var response struct { + Success bool `json:"success"` + Message string `json:"message,omitempty"` + } + return parseResponse(resp, &response) +} diff --git a/client/message.go b/client/message.go index 9eeda4fd..b5c59e3c 100644 --- a/client/message.go +++ b/client/message.go @@ -104,7 +104,32 @@ func (c *Client) GetMessagesBefore( return c.LoadMessages(ctx, sessionID, limit, &beforeTime) } -// SearchMessagesRequest defines the request structure for searching messages +// MessageSearchMode is the search strategy for SearchMessages. It mirrors the +// server enum in internal/types/message.go. +type MessageSearchMode string + +const ( + // MessageSearchModeKeyword searches by keyword only. + MessageSearchModeKeyword MessageSearchMode = "keyword" + // MessageSearchModeVector searches by vector similarity only. + MessageSearchModeVector MessageSearchMode = "vector" + // MessageSearchModeHybrid combines keyword and vector search (server default). + MessageSearchModeHybrid MessageSearchMode = "hybrid" +) + +// AllMessageSearchModes returns every search mode the server recognises, in a +// stable order. Callers (CLI flag validation, docs) should use this instead of +// re-typing the set so they can't drift from the SDK. +func AllMessageSearchModes() []MessageSearchMode { + return []MessageSearchMode{ + MessageSearchModeKeyword, MessageSearchModeVector, MessageSearchModeHybrid, + } +} + +// SearchMessagesRequest defines the request structure for searching messages. +// Mode is a plain string mirroring the server's request DTO; pass a +// MessageSearchMode constant cast to string, or leave empty for the server +// default (hybrid). type SearchMessagesRequest struct { Query string `json:"query"` Mode string `json:"mode"` diff --git a/client/model.go b/client/model.go index 0f7617fc..5c691e5b 100644 --- a/client/model.go +++ b/client/model.go @@ -21,6 +21,15 @@ const ( ModelTypeASR ModelType = "ASR" // ASR (Automatic Speech Recognition) model ) +// AllModelTypes returns every model type the server recognises, in a stable +// order. Callers (CLI flag validation, docs) should use this instead of +// re-typing the string set, so they can't drift from the SDK. +func AllModelTypes() []ModelType { + return []ModelType{ + ModelTypeEmbedding, ModelTypeRerank, ModelTypeKnowledgeQA, ModelTypeVLLM, ModelTypeASR, + } +} + // ModelSource represents the source of the model type ModelSource string @@ -44,6 +53,21 @@ const ( ModelSourceAzureOpenAI ModelSource = "azure_openai" // Azure OpenAI model ) +// AllModelSources returns every model source the server recognises, in a stable +// order. This is the broad set used for FILTERING existing records (model +// list --source); creating a model only supports local/remote (the provider +// identity goes in ModelParameters.provider). Use this instead of re-typing +// the set so callers can't drift from the SDK. +func AllModelSources() []ModelSource { + return []ModelSource{ + ModelSourceLocal, ModelSourceRemote, ModelSourceAliyun, ModelSourceZhipu, + ModelSourceVolcengine, ModelSourceDeepseek, ModelSourceHunyuan, ModelSourceMinimax, + ModelSourceOpenAI, ModelSourceGemini, ModelSourceMimo, ModelSourceSiliconFlow, + ModelSourceJina, ModelSourceOpenRouter, ModelSourceNvidia, ModelSourceNovita, + ModelSourceAzureOpenAI, + } +} + // ModelParameters model parameters type ModelParameters map[string]interface{} diff --git a/client/session.go b/client/session.go index b7cf9c75..a762ff04 100644 --- a/client/session.go +++ b/client/session.go @@ -281,7 +281,7 @@ func (c *Client) KnowledgeQAStream( if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) - err := fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + err := newAPIError(resp.StatusCode, body) debugLogger.Debug("request_error_status", "error", err) return err } @@ -370,7 +370,7 @@ func (c *Client) ContinueStream( if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + return newAPIError(resp.StatusCode, body) } // Use bufio to read SSE data line by line @@ -478,7 +478,7 @@ func (c *Client) SearchKnowledge(ctx context.Context, request *SearchKnowledgeRe if resp.StatusCode < 200 || resp.StatusCode >= 300 { body, _ := io.ReadAll(resp.Body) - err := fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + err := newAPIError(resp.StatusCode, body) debugLogger.Debug("request_error_status", "error", err) return nil, err }