Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(teamhub): search the web through saved provider keys

LeoXing0d0b1615c333
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.md
index bff3e418..3beb6ac8 100644
--- a/apps/teamhub/AGENTS.md
+++ b/apps/teamhub/AGENTS.md
@@ -235,6 +235,21 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.
environment key over one saved in the product (`voice_provider_keys`, sealed
with `TEAMHUB_SECRET_ENCRYPTION_KEY`), so a save applies without a restart
on every replica. A save wakes the Node Services voice workers best effort.
+- Web search: `internal/websearch` runs Agent searches and page reads through
+ Tavily, Brave, Firecrawl and You.com with deployment-wide keys in
+ `web_search_keys` (sealed with `TEAMHUB_SECRET_ENCRYPTION_KEY`, read at each
+ call) and the chosen default in `web_search_settings`. TeamHub calls only the
+ providers' fixed API hosts; the CLI reads `direct` pages itself. A search
+ without a backend uses the chosen default, else the first backend with a
+ usable key, else You.com's keyless MCP trial, which TeamHub does not count;
+ a failed call never falls back to another backend. A missing or refused key,
+ or the end of the trial, posts a `search_key` card that stores the request.
+ A key added from that card replays the request first: a provider 401/403
+ leaves the key unsaved and the card open; any other outcome saves it and
+ answers the card `configured` with the backend and the call's results or
+ error code. Any save answers every other pending card `configured` with the
+ saved backend, which the Agent reruns with; saves outside a card use the
+ official check (Brave has none and stays unverified until its first call).
- Local models: `local_computer_model_snapshots` keeps each Computer's latest
model library snapshot and the last host any snapshot carried; removing the
Computer deletes the row in the same transaction. Recording a snapshot
diff --git a/apps/teamhub/internal/agentauth/agentauth.go b/apps/teamhub/internal/agentauth/agentauth.go
index e8cd4ff1..6b1ec121 100644
--- a/apps/teamhub/internal/agentauth/agentauth.go
+++ b/apps/teamhub/internal/agentauth/agentauth.go
@@ -222,7 +222,7 @@ func businessAction(action string) bool {
case "apply_document_semantic_mutation", "ask_user", "check_task", "create_document", "create_task", "create_room", "create_routine", "create_team_md", "delete_routine", "enable_routine", "get_document_comment_thread", "hand_off_to_room", "list_available_agents", "list_routines", "pause_routine", "replace_document_comment_text", "reply_document_comment", "run_routine", "send_direct_message", "send_emoji", "send_message", "send_message_sequence", "send_task", "show_fragment", "stop_task", "upload_artifact_tree", "upload_artifacts",
"add_room_member", "create_agent", "get_agent", "update_agent", "list_connected_apps", "search_app_tools", "execute_app_tool", "manage_auto_reminders",
"get_personal_profile", "write_personal_profile", "start_personal_profile_build", "get_account_profile", "update_account_profile",
- "request_browser_connection", "read_computer_permissions", "request_computer_permission":
+ "request_browser_connection", "read_computer_permissions", "request_computer_permission", "web_search":
return true
}
return knowledgeAction(action)
diff --git a/apps/teamhub/internal/app/app.go b/apps/teamhub/internal/app/app.go
index e19ebcd8..4f56c3e4 100644
--- a/apps/teamhub/internal/app/app.go
+++ b/apps/teamhub/internal/app/app.go
@@ -70,6 +70,7 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicekey"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicemedia"
"github.com/simplexai-labs/linger/apps/teamhub/internal/voicequicknotes"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/websearch"
"github.com/simplexai-labs/linger/apps/teamhub/internal/workitem"
httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
)
@@ -120,6 +121,8 @@ type App struct {
voiceMedia voicemedia.Plane
// voiceKeys resolves the Soniox and xAI keys at each use.
voiceKeys *voicekey.Service
+ // webSearch runs the Agents' web searches with the saved keys.
+ webSearch *websearch.Service
// reconcileVoiceWorkers wakes the Node Services voice workers after a key
// is saved and reports whether they are ready; nil without a Node Services
// link.
@@ -218,7 +221,10 @@ type Deps struct {
VoiceMedia voicemedia.Plane
// VoiceKeyChecker checks a voice provider key before it is saved; nil
// asks the provider's API.
- VoiceKeyChecker voicekey.Checker
+ VoiceKeyChecker voicekey.Checker
+ // WebSearch points web search at fake providers; zero fields use the
+ // providers' APIs.
+ WebSearch websearch.Endpoints
PersonalProfile personalprofile.Generator
PersonalInsight personalinsight.Generator
ProactiveEventJudge proactive.EventJudge
@@ -525,6 +531,9 @@ func (a *App) registerFeatures(ctx context.Context, cfg config.Config, deps Deps
if err := a.registerVoice(cfg, deps, core.artifacts); err != nil {
return err
}
+ if err := a.registerWebSearch(cfg, deps); err != nil {
+ return err
+ }
a.reminders = reminder.New(a.pool)
agentAuthorization := a.registerAgentAuthorization()
if err := a.registerExternalApps(ctx, cfg.ExternalApps, deps.Composio, agentAuthorization); err != nil {
diff --git a/apps/teamhub/internal/app/contract_server_agent_auth.go b/apps/teamhub/internal/app/contract_server_agent_auth.go
index af1b69cb..9c792be7 100644
--- a/apps/teamhub/internal/app/contract_server_agent_auth.go
+++ b/apps/teamhub/internal/app/contract_server_agent_auth.go
@@ -92,3 +92,21 @@ func (a *App) writeAgentAPIErrorWithIssues(
}
c.JSON(status, teamhubagentapi.AgentApiErrorEnvelope{Error: model})
}
+
+// writeAgentAPIErrorWithDetails writes a failure with the machine-readable
+// facts the CLI acts on.
+func (a *App) writeAgentAPIErrorWithDetails(
+ c *gin.Context,
+ status int,
+ code teamhubagentapi.AgentApiErrorCode,
+ message string,
+ details *teamhubagentapi.AgentApiErrorDetails,
+) {
+ requestID := c.GetString("request_id")
+ if requestID == "" {
+ requestID = idgen.New("request")
+ }
+ c.JSON(status, teamhubagentapi.AgentApiErrorEnvelope{Error: teamhubagentapi.AgentApiError{
+ Code: code, Message: message, RequestId: requestID, Details: details,
+ }})
+}
diff --git a/apps/teamhub/internal/app/contract_server_agent_connector.go b/apps/teamhub/internal/app/contract_server_agent_connector.go
index 8d3a678e..66a6f849 100644
--- a/apps/teamhub/internal/app/contract_server_agent_connector.go
+++ b/apps/teamhub/internal/app/contract_server_agent_connector.go
@@ -101,7 +101,7 @@ func (a *App) resolveConnectorAccount(c *gin.Context) {
if isConnectionIDSelector(selector) {
requestedAccount = ""
}
- if roomID, card, ok := a.postConnectorCard(c, token, prompt, typedcard.DecisionCommand{
+ if roomID, card, ok := a.postConnectorCard(c, token, "list_connected_apps", prompt, typedcard.DecisionCommand{
ConnectionAuth: &typedcard.ConnectionAuthDecision{Prompt: prompt, AppKey: input.AppKey, Account: requestedAccount, ReusePending: true},
}); ok {
c.JSON(200, gin.H{"status": "authorization_required", "room_id": roomID, "message_id": card.MessageID, "interaction_id": card.DecisionID})
@@ -128,7 +128,7 @@ func (a *App) requestProviderKey(c *gin.Context, token, appKey string) {
} else {
appKey = ""
}
- if _, _, ok := a.postConnectorCard(c, token, prompt, typedcard.DecisionCommand{
+ if _, _, ok := a.postConnectorCard(c, token, "list_connected_apps", prompt, typedcard.DecisionCommand{
ProviderKey: &typedcard.ProviderKeyDecision{Prompt: prompt, AppKey: appKey},
}); ok {
a.writeAgentAPIError(c, http.StatusConflict, api.AgentApiErrorCodeProviderKeyRequired,
@@ -147,11 +147,11 @@ func (a *App) askForProviderKey(c *gin.Context, token, appKey string, err error)
}
// postConnectorCard posts the card that asks the Agent's Human for what a
-// connector command still needs. It writes the error response itself and
-// reports whether the card was posted.
-func (a *App) postConnectorCard(c *gin.Context, token, prompt string, command typedcard.DecisionCommand) (string, typedcard.CreateResult, bool) {
+// command still needs; action is the command's business action. It writes
+// the error response itself and reports whether the card was posted.
+func (a *App) postConnectorCard(c *gin.Context, token, action, prompt string, command typedcard.DecisionCommand) (string, typedcard.CreateResult, bool) {
c.Header("Cache-Control", "no-store")
- auth, err := a.agentAuth.Authorize(c.Request.Context(), token, "list_connected_apps")
+ auth, err := a.agentAuth.Authorize(c.Request.Context(), token, action)
if a.writeAgentAuthError(c, "request connector authorization", err) {
return "", typedcard.CreateResult{}, false
}
diff --git a/apps/teamhub/internal/app/contract_server_agent_web_search.go b/apps/teamhub/internal/app/contract_server_agent_web_search.go
new file mode 100644
index 00000000..53439a18
--- /dev/null
+++ b/apps/teamhub/internal/app/contract_server_agent_web_search.go
@@ -0,0 +1,278 @@
+package app
+
+import (
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/websearch"
+ api "github.com/simplexai-labs/linger/contracts-go/teamhubagentapi"
+)
+
+// webSearchAction is the business action every web search command runs as.
+const webSearchAction = "web_search"
+
+// authorizeWebSearch decodes a web search command and authorizes its Agent.
+func (a *App) authorizeWebSearch(c *gin.Context, input any, optional bool) (string, bool) {
+ token, ok := a.agentCommandBearer(c)
+ if !ok {
+ return "", false
+ }
+ body, err := io.ReadAll(http.MaxBytesReader(c.Writer, c.Request.Body, 16<<10))
+ if err != nil || !(optional && len(body) == 0) && decodeStrictJSONBytes(body, input) != nil {
+ a.writeAgentAPIError(c, http.StatusBadRequest, api.AgentApiErrorCodeInvalidInput, "Invalid web search request")
+ return "", false
+ }
+ _, err = a.agentAuth.Authorize(c.Request.Context(), token, webSearchAction)
+ if a.writeAgentAuthError(c, "authorize web search", err) {
+ return "", false
+ }
+ c.Header("Cache-Control", "no-store")
+ return token, true
+}
+
+func (a *App) searchAgentWeb(c *gin.Context) {
+ var input api.WebSearchRequest
+ token, ok := a.authorizeWebSearch(c, &input, false)
+ if !ok {
+ return
+ }
+ request := websearch.Request{Command: websearch.CommandSearch, Query: input.Query}
+ if input.Backend != nil {
+ request.Backend = websearch.Backend(*input.Backend)
+ }
+ if input.Limit != nil {
+ // Normalize reads 0 as "use the default"; an explicit 0 is out of range.
+ request.Limit = *input.Limit
+ if request.Limit == 0 {
+ request.Limit = -1
+ }
+ }
+ if input.Recency != nil {
+ request.Recency = string(*input.Recency)
+ }
+ if input.Sites != nil {
+ request.Sites = *input.Sites
+ }
+ a.runAgentWebRequest(c, token, request)
+}
+
+func (a *App) openAgentWebPage(c *gin.Context) {
+ var input api.WebOpenRequest
+ token, ok := a.authorizeWebSearch(c, &input, false)
+ if !ok {
+ return
+ }
+ a.runAgentWebRequest(c, token, websearch.Request{Command: websearch.CommandOpen, Backend: websearch.Backend(input.Backend), URL: input.Url})
+}
+
+// runAgentWebRequest runs one search or page open. A missing or refused key,
+// or the end of the keyless trial, posts (or reuses) the card asking the
+// Agent's Human for a key, storing the request so a key added from the card
+// replays it.
+func (a *App) runAgentWebRequest(c *gin.Context, token string, request websearch.Request) {
+ request, err := websearch.Normalize(request)
+ if err != nil {
+ a.writeAgentAPIError(c, http.StatusBadRequest, api.AgentApiErrorCodeInvalidInput, "Invalid web search request")
+ return
+ }
+ outcome, err := a.webSearch.Run(c.Request.Context(), request)
+ var failure *websearch.Failure
+ switch {
+ case err == nil && outcome.Page != nil:
+ c.JSON(http.StatusOK, outcome.Page)
+ case err == nil:
+ results := outcome.Results
+ if results == nil {
+ results = []websearch.Result{}
+ }
+ c.JSON(http.StatusOK, gin.H{"results": results})
+ case !errors.As(err, &failure):
+ a.logger.Error("web_search.request_failed", "request_id", c.GetString("request_id"), "error_type", fmt.Sprintf("%T", err))
+ a.writeAgentAPIError(c, http.StatusInternalServerError, api.AgentApiErrorCodeInternalError, "Web search could not complete the request")
+ case failure.KeyFailure():
+ a.requestSearchKey(c, token, failure, &request)
+ default:
+ code, status := webSearchFailureStatus(failure)
+ details := &api.AgentApiErrorDetails{Backend: stringRef(string(failure.Backend))}
+ if failure.Code == websearch.CodeQuotaExhausted || failure.Code == websearch.CodeRateLimited {
+ ready := make([]string, len(failure.Ready))
+ for i, b := range failure.Ready {
+ ready[i] = string(b)
+ }
+ details.ReadyBackends = &ready
+ }
+ if seconds := int(failure.RetryAfter.Seconds()); seconds > 0 {
+ details.RetryAfterSeconds = &seconds
+ }
+ a.writeAgentAPIErrorWithDetails(c, status, code, webSearchFailureMessage(failure), details)
+ }
+}
+
+// webSearchFailureStatus maps a call that failed other than on its key to
+// the agent error code and HTTP status.
+func webSearchFailureStatus(failure *websearch.Failure) (api.AgentApiErrorCode, int) {
+ switch failure.Code {
+ case websearch.CodeQuotaExhausted:
+ return api.AgentApiErrorCodeSearchQuotaExhausted, http.StatusPaymentRequired
+ case websearch.CodeRateLimited:
+ return api.AgentApiErrorCodeProviderRateLimited, http.StatusTooManyRequests
+ case websearch.CodeUnsupported:
+ return api.AgentApiErrorCodeInvalidInput, http.StatusBadRequest
+ case websearch.CodePageUnreadable:
+ return api.AgentApiErrorCodeToolExecutionFailed, http.StatusUnprocessableEntity
+ default:
+ return api.AgentApiErrorCodeDependencyUnavailable, http.StatusServiceUnavailable
+ }
+}
+
+func webSearchFailureMessage(failure *websearch.Failure) string {
+ name := websearch.DisplayName(failure.Backend)
+ switch failure.Code {
+ case websearch.CodeQuotaExhausted:
+ return fmt.Sprintf("The %s account has no credit or quota left. Try another ready backend, or tell the user.", name)
+ case websearch.CodeRateLimited:
+ return fmt.Sprintf("%s is rate limiting web search. Wait and retry, or use another ready backend.", name)
+ case websearch.CodeUnsupported:
+ return fmt.Sprintf("%s cannot run this command with these filters; run teamhub web list to see what each backend supports.", name)
+ case websearch.CodePageUnreadable:
+ return fmt.Sprintf("%s could not read this page. Try --backend direct or another backend.", name)
+ default:
+ return fmt.Sprintf("%s could not be reached. Try again later or use another ready backend.", name)
+ }
+}
+
+// searchKeyReasons names a key failure on the card.
+var searchKeyReasons = map[websearch.Code]string{
+ websearch.CodeKeyRequired: "missing", websearch.CodeKeyRejected: "rejected", websearch.CodeFreeLimit: "free_limit",
+}
+
+// postSearchKeyCard posts, or reuses, the card asking the Agent's Human for a
+// web search key. request is the call to replay once a key is added from the
+// card; nil for a connect request. It writes the error response itself when
+// no card could be posted.
+func (a *App) postSearchKeyCard(c *gin.Context, token string, failure *websearch.Failure, request *websearch.Request) (string, typedcard.CreateResult, bool) {
+ decision := &typedcard.SearchKeyDecision{
+ Prompt: searchKeyPrompt(failure), Backend: string(failure.Backend), Suggested: failure.Suggested, Reason: searchKeyReasons[failure.Code],
+ }
+ if request != nil {
+ decision.Request = &typedcard.SearchKeyRequest{
+ Command: request.Command, Backend: string(request.Backend), Query: request.Query, Limit: request.Limit,
+ Recency: request.Recency, Sites: request.Sites, URL: request.URL,
+ }
+ }
+ return a.postConnectorCard(c, token, webSearchAction, decision.Prompt, typedcard.DecisionCommand{SearchKey: decision})
+}
+
+// requestSearchKey posts the key card for a failed call and answers
+// search_key_requested with the card and the backend it shows.
+func (a *App) requestSearchKey(c *gin.Context, token string, failure *websearch.Failure, request *websearch.Request) {
+ roomID, card, ok := a.postSearchKeyCard(c, token, failure, request)
+ if !ok {
+ return
+ }
+ origin := api.AgentApiErrorDetailsOrigin("requested")
+ if failure.Suggested {
+ origin = "suggested"
+ }
+ detailReason := api.AgentApiErrorDetailsReason(searchKeyReasons[failure.Code])
+ a.writeAgentAPIErrorWithDetails(c, http.StatusConflict, api.AgentApiErrorCodeSearchKeyRequested, searchKeyRequestedMessage(failure),
+ &api.AgentApiErrorDetails{
+ Backend: stringRef(string(failure.Backend)), Origin: &origin, Reason: &detailReason,
+ RoomId: &roomID, MessageId: &card.MessageID, InteractionId: &card.DecisionID,
+ })
+}
+
+// searchKeyRequestedMessage tells the Agent to wait for the card: a key saved
+// from it replays the call and wakes the Agent with its results.
+func searchKeyRequestedMessage(failure *websearch.Failure) string {
+ name := websearch.DisplayName(failure.Backend)
+ wait := "a card asking for it is in the chat. End your turn: the card's result wakes you with the results or what to run next. If the user declines, don't retry."
+ switch failure.Code {
+ case websearch.CodeFreeLimit:
+ return "The free web search trial is used up. Waiting for the user to add a web search API key; " + wait
+ case websearch.CodeKeyRejected:
+ return fmt.Sprintf("Waiting for the user to replace the %s API key, which %s no longer accepts; %s", name, name, wait)
+ default:
+ return fmt.Sprintf("Waiting for the user to add a %s API key; %s", name, wait)
+ }
+}
+
+// searchKeyPrompt is the Human-facing ask on the card.
+func searchKeyPrompt(failure *websearch.Failure) string {
+ name := websearch.DisplayName(failure.Backend)
+ switch {
+ case failure.Code == websearch.CodeFreeLimit && failure.Suggested:
+ return fmt.Sprintf("The free web search trial is used up. Please add a web search API key so I can keep searching; %s is suggested.", name)
+ case failure.Code == websearch.CodeFreeLimit:
+ return fmt.Sprintf("The free %s trial is used up. Please add a %s API key so I can keep searching.", name, name)
+ case failure.Code == websearch.CodeKeyRejected:
+ return fmt.Sprintf("%s refused the saved API key. Please add a new key so I can search the web.", name)
+ default:
+ return fmt.Sprintf("Please add a %s API key so I can search the web.", name)
+ }
+}
+
+func (a *App) listAgentWebBackends(c *gin.Context) {
+ var input api.WebBackendsQuery
+ if _, ok := a.authorizeWebSearch(c, &input, true); !ok {
+ return
+ }
+ list, err := a.webSearch.List(c.Request.Context())
+ if err != nil {
+ a.logger.Error("web_search.list_failed", "request_id", c.GetString("request_id"), "error_type", fmt.Sprintf("%T", err))
+ a.writeAgentAPIError(c, http.StatusInternalServerError, api.AgentApiErrorCodeInternalError, "Web search backends could not be listed")
+ return
+ }
+ if input.Backend != nil {
+ kept := []websearch.BackendView{}
+ for _, view := range list.Backends {
+ if string(view.ID) == string(*input.Backend) {
+ kept = append(kept, view)
+ }
+ }
+ if len(kept) == 0 {
+ a.writeAgentAPIError(c, http.StatusBadRequest, api.AgentApiErrorCodeInvalidInput, "Unknown web search backend")
+ return
+ }
+ list.Backends = kept
+ }
+ c.JSON(http.StatusOK, list)
+}
+
+// connectAgentWebBackend answers ready for a backend that can run now, and
+// otherwise posts the card asking the Human for its key.
+func (a *App) connectAgentWebBackend(c *gin.Context) {
+ var input api.WebConnectRequest
+ token, ok := a.authorizeWebSearch(c, &input, false)
+ if !ok {
+ return
+ }
+ backend := websearch.Backend(input.Backend)
+ if !websearch.KeyBackend(backend) {
+ a.writeAgentAPIError(c, http.StatusBadRequest, api.AgentApiErrorCodeInvalidInput, "Unknown web search backend")
+ return
+ }
+ view, err := a.webSearch.Backend(c.Request.Context(), backend)
+ if err != nil {
+ a.logger.Error("web_search.connect_failed", "request_id", c.GetString("request_id"), "error_type", fmt.Sprintf("%T", err))
+ a.writeAgentAPIError(c, http.StatusInternalServerError, api.AgentApiErrorCodeInternalError, "Web search could not complete the request")
+ return
+ }
+ if view.Status == "ready" {
+ c.JSON(http.StatusOK, gin.H{"status": "ready", "backend": view})
+ return
+ }
+ failure := &websearch.Failure{Code: websearch.CodeKeyRequired, Backend: backend}
+ if view.Status == "key_rejected" {
+ failure.Code = websearch.CodeKeyRejected
+ }
+ if roomID, card, ok := a.postSearchKeyCard(c, token, failure, nil); ok {
+ c.JSON(http.StatusOK, gin.H{"status": "connection_requested", "room_id": roomID, "message_id": card.MessageID, "interaction_id": card.DecisionID})
+ }
+}
+
+func stringRef(value string) *string { return &value }
diff --git a/apps/teamhub/internal/app/feature_web_search.go b/apps/teamhub/internal/app/feature_web_search.go
new file mode 100644
index 00000000..06123c71
--- /dev/null
+++ b/apps/teamhub/internal/app/feature_web_search.go
@@ -0,0 +1,178 @@
+package app
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/typedcard"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/websearch"
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+// maxReplayResultBytes bounds the replayed search results a key card hands
+// its Agent; results past it are dropped from the end.
+const maxReplayResultBytes = 24000
+
+// registerWebSearch builds web search over the keys saved in the product,
+// sealed with TEAMHUB_SECRET_ENCRYPTION_KEY. Without that key nothing can be
+// saved and only You.com's keyless trial and direct work.
+func (a *App) registerWebSearch(cfg config.Config, deps Deps) error {
+ box, err := secretBox(cfg.ExternalApps.SecretEncryptionKey)
+ if err != nil {
+ return err
+ }
+ a.webSearch = websearch.New(a.queries, box, deps.WebSearch, a.logger)
+ return nil
+}
+
+func (a *App) listWebSearchBackends(c *gin.Context) {
+ list, err := a.webSearch.List(c.Request.Context())
+ if err != nil {
+ a.internalError(c, "list web search backends", err)
+ return
+ }
+ c.Header("Cache-Control", "no-store")
+ c.JSON(http.StatusOK, list)
+}
+
+// saveWebSearchKey saves one backend's key. From a search_key card it first
+// replays the request the card was posted for with the new key, so the
+// provider proves the key on the call the Agent wanted and the Agent hears
+// its results. Any signed-in Human may save a key; it is never echoed or
+// logged.
+func (a *App) saveWebSearchKey(c *gin.Context) {
+ backend := websearch.Backend(c.Param("backend"))
+ var request httpapi.SaveWebSearchKeyRequest
+ if !websearch.KeyBackend(backend) || decodeJSON(c, &request) != nil {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Web search key request is invalid")
+ return
+ }
+ ctx := c.Request.Context()
+ var replayed *typedcard.SearchKeyReplay
+ var view websearch.BackendView
+ var err error
+ card := typedcard.SearchKeyCard{}
+ if request.DecisionId != nil {
+ card, err = a.typedCards.SearchKeyCardRequest(ctx, currentPrincipal(c).Session.AccountID, *request.DecisionId)
+ switch {
+ case errors.Is(err, typedcard.ErrNotFound):
+ a.writeError(c, http.StatusNotFound, "NOT_FOUND", "The card was not found")
+ return
+ case errors.Is(err, typedcard.ErrForbidden):
+ a.writeError(c, http.StatusForbidden, "FORBIDDEN", "Only the card's decision owner can add a key from it")
+ return
+ case errors.Is(err, typedcard.ErrInvalid):
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "The card does not ask for a web search key")
+ return
+ case err != nil:
+ a.internalError(c, "read web search key card", err)
+ return
+ }
+ }
+ if card.Open && card.Request != nil {
+ var replay websearch.Replay
+ replay, err = a.webSearch.SaveReplayed(ctx, backend, request.ApiKey, webSearchRequestFromCard(*card.Request))
+ if err == nil {
+ view = replay.View
+ replayed = searchKeyReplay(*request.DecisionId, replay)
+ }
+ } else {
+ view, err = a.webSearch.SaveKey(ctx, backend, request.ApiKey)
+ }
+ switch {
+ case errors.Is(err, websearch.ErrInvalid):
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Web search API key is invalid")
+ case errors.Is(err, websearch.ErrKeyRejected):
+ a.writeError(c, http.StatusBadRequest, "WEB_SEARCH_KEY_REJECTED", "The provider rejected this API key")
+ case errors.Is(err, websearch.ErrStorageMissing):
+ a.writeError(c, http.StatusServiceUnavailable, "WEB_SEARCH_KEY_STORAGE_UNAVAILABLE", "This deployment cannot store a web search API key")
+ case errors.Is(err, websearch.ErrProviderUnavailable):
+ a.writeError(c, http.StatusServiceUnavailable, "WEB_SEARCH_PROVIDER_UNAVAILABLE", "The provider could not be reached; try again")
+ case err != nil:
+ a.internalError(c, "save web search key", err)
+ default:
+ // The waiting Agents can search now. A failure leaves those cards for
+ // the user to decline; it never fails the save.
+ if err := a.typedCards.SettleSearchKeys(ctx, string(backend), replayed); err != nil {
+ a.logger.Error("web_search.settle_cards_failed", "backend", string(backend), "error", err)
+ }
+ c.Header("Cache-Control", "no-store")
+ c.JSON(http.StatusOK, view)
+ }
+}
+
+func webSearchRequestFromCard(stored typedcard.SearchKeyRequest) websearch.Request {
+ return websearch.Request{
+ Command: stored.Command, Backend: websearch.Backend(stored.Backend), Query: stored.Query, Limit: stored.Limit,
+ Recency: stored.Recency, Sites: stored.Sites, URL: stored.URL,
+ }
+}
+
+// searchKeyReplay is what the card the key was added from hands its Agent:
+// the results, the page, or the agent error code of the failed call.
+func searchKeyReplay(decisionID string, replay websearch.Replay) *typedcard.SearchKeyReplay {
+ result := &typedcard.SearchKeyReplay{DecisionID: decisionID}
+ switch {
+ case replay.Failure != nil:
+ code, _ := webSearchFailureStatus(replay.Failure)
+ result.ErrorCode = string(code)
+ case replay.Outcome.Page != nil:
+ result.Page, _ = json.Marshal(replay.Outcome.Page)
+ default:
+ results := replay.Outcome.Results
+ if results == nil {
+ results = []websearch.Result{}
+ }
+ for {
+ encoded, _ := json.Marshal(results)
+ if len(encoded) <= maxReplayResultBytes || len(results) == 0 {
+ result.Results = encoded
+ break
+ }
+ results = results[:len(results)-1]
+ }
+ }
+ return result
+}
+
+func (a *App) deleteWebSearchKey(c *gin.Context) {
+ backend := websearch.Backend(c.Param("backend"))
+ if !websearch.KeyBackend(backend) {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Web search backend is invalid")
+ return
+ }
+ if err := a.webSearch.RemoveKey(c.Request.Context(), backend); err != nil {
+ a.internalError(c, "remove web search key", err)
+ return
+ }
+ c.Status(http.StatusNoContent)
+}
+
+func (a *App) setWebSearchDefault(c *gin.Context) {
+ var request httpapi.SetWebSearchDefaultRequest
+ if decodeJSON(c, &request) != nil || !websearch.KeyBackend(websearch.Backend(request.Backend)) {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Web search default request is invalid")
+ return
+ }
+ chosen, err := a.webSearch.SetDefault(c.Request.Context(), websearch.Backend(request.Backend))
+ switch {
+ case errors.Is(err, websearch.ErrNotReady):
+ a.writeError(c, http.StatusConflict, "WEB_SEARCH_KEY_REQUIRED", "Add a working key for this backend first")
+ case err != nil:
+ a.internalError(c, "set web search default", err)
+ default:
+ c.JSON(http.StatusOK, chosen)
+ }
+}
+
+func (a *App) clearWebSearchDefault(c *gin.Context) {
+ chosen, err := a.webSearch.ClearDefault(c.Request.Context())
+ if err != nil {
+ a.internalError(c, "clear web search default", err)
+ return
+ }
+ c.JSON(http.StatusOK, chosen)
+}
diff --git a/apps/teamhub/internal/app/routes_agent_api.go b/apps/teamhub/internal/app/routes_agent_api.go
index f7e617e7..6156bd8c 100644
--- a/apps/teamhub/internal/app/routes_agent_api.go
+++ b/apps/teamhub/internal/app/routes_agent_api.go
@@ -69,6 +69,10 @@ func (a *App) agentAPIRoutes() []contractRoute {
route(http.MethodPost, "/api/agent/v1/tracking-items/list", nil, a.listAgentTrackingItems),
route(http.MethodPost, "/api/agent/v1/tracking-items/update", nil, a.updateAgentTrackingItem),
route(http.MethodPost, "/api/agent/v1/user-questions", nil, a.askAgentUser),
+ route(http.MethodPost, "/api/agent/v1/web/backends/query", nil, a.listAgentWebBackends),
+ route(http.MethodPost, "/api/agent/v1/web/connect", nil, a.connectAgentWebBackend),
+ route(http.MethodPost, "/api/agent/v1/web/open", nil, a.openAgentWebPage),
+ route(http.MethodPost, "/api/agent/v1/web/search", nil, a.searchAgentWeb),
}
}
diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.go
index 5635c625..3aabf0e3 100644
--- a/apps/teamhub/internal/app/routes_public.go
+++ b/apps/teamhub/internal/app/routes_public.go
@@ -234,6 +234,11 @@ func (a *App) publicRoutes() []contractRoute {
route(http.MethodGet, "/v0/voice-sessions/:voiceSessionId/events", httpapi.ListVoiceEventsParams{}, session, a.listVoiceEvents),
route(http.MethodGet, "/v0/voice-sessions/:voiceSessionId/events/stream", httpapi.StreamVoiceEventsParams{}, session, a.streamVoiceEvents),
route(http.MethodGet, "/v0/voice-sessions/:voiceSessionId/transcript-events", httpapi.ListVoiceTranscriptEventsParams{}, session, a.listVoiceTranscriptEvents),
+ route(http.MethodGet, "/v0/web-search/backends", nil, session, a.listWebSearchBackends),
+ route(http.MethodDelete, "/v0/web-search/backends/:backend/key", nil, session, a.deleteWebSearchKey),
+ route(http.MethodPut, "/v0/web-search/backends/:backend/key", nil, session, a.saveWebSearchKey),
+ route(http.MethodDelete, "/v0/web-search/default", nil, session, a.clearWebSearchDefault),
+ route(http.MethodPut, "/v0/web-search/default", nil, session, a.setWebSearchDefault),
route(http.MethodGet, "/v0/work-items/:workItemId", nil, session, a.getWorkItem),
route(http.MethodPatch, "/v0/work-items/:workItemId", httpapi.UpdateWorkItemParams{}, session, a.updateWorkItem),
route(http.MethodDelete, "/v0/work-items/:workItemId/access-grants/:actorId", httpapi.DeleteWorkItemAccessGrantParams{}, session, a.deleteWorkItemAccessGrant),
diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.go
index 251eb8aa..67096774 100644
--- a/apps/teamhub/internal/store/models.go
+++ b/apps/teamhub/internal/store/models.go
@@ -1946,6 +1946,23 @@ type VoiceTranscriptUncertainty struct {
RecoveredAt pgtype.Timestamptz `json:"recovered_at"`
}
+type WebSearchKey struct {
+ Backend string `json:"backend"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+ State string `json:"state"`
+ QuotaRemaining pgtype.Float8 `json:"quota_remaining"`
+ QuotaLimit pgtype.Float8 `json:"quota_limit"`
+ QuotaResetsAt pgtype.Timestamptz `json:"quota_resets_at"`
+ QuotaObservedAt pgtype.Timestamptz `json:"quota_observed_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
+type WebSearchSetting struct {
+ Singleton bool `json:"singleton"`
+ DefaultBackend pgtype.Text `json:"default_backend"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+}
+
type WikiCurrentSource struct {
WikiID pgtype.Text `json:"wiki_id"`
TenantID string `json:"tenant_id"`
diff --git a/apps/teamhub/internal/store/queries/task_delegation.sql b/apps/teamhub/internal/store/queries/task_delegation.sql
index f70364e5..7c4baadb 100644
--- a/apps/teamhub/internal/store/queries/task_delegation.sql
+++ b/apps/teamhub/internal/store/queries/task_delegation.sql
@@ -43,7 +43,7 @@ LIMIT 50;
-- name: ListDelegatedTaskPendingApprovals :many
-- Approvals the Task's AlterEgo is waiting on: Runtime permission cards of
-- its Context and the other approvals it asked for. Connection, computer
--- permission and Document access cards are not approvals.
+-- permission, web search key and Document access cards are not approvals.
SELECT CASE WHEN decision.kind='runtime_permission' THEN 'permission' ELSE 'connector' END::text AS kind,
decision.id,
COALESCE(decision.view->>'title','')::text AS title,
@@ -52,7 +52,7 @@ FROM decisions decision
WHERE decision.tenant_id=sqlc.arg(tenant_id)::text
AND decision.alter_ego_task_id=sqlc.arg(task_id)::text
AND decision.status='pending'
- AND decision.kind NOT IN ('connection_auth','provider_key','browser_connection','computer_permission','document_access')
+ AND decision.kind NOT IN ('connection_auth','provider_key','browser_connection','computer_permission','document_access','search_key')
AND (decision.kind<>'runtime_permission' OR decision.request->>'context_key'=sqlc.arg(context_key)::text)
ORDER BY decision.created_at,decision.id;
diff --git a/apps/teamhub/internal/store/queries/web_search.sql b/apps/teamhub/internal/store/queries/web_search.sql
new file mode 100644
index 00000000..18ac1a30
--- /dev/null
+++ b/apps/teamhub/internal/store/queries/web_search.sql
@@ -0,0 +1,46 @@
+-- name: ListWebSearchKeys :many
+-- At most one row per backend; callers pick the one they need.
+SELECT backend,api_key_ciphertext,state,quota_remaining,quota_limit,quota_resets_at,quota_observed_at
+FROM web_search_keys
+ORDER BY backend;
+
+-- name: UpsertWebSearchKey :exec
+-- A new key starts with no observed quota.
+INSERT INTO web_search_keys (backend,api_key_ciphertext,state)
+VALUES (sqlc.arg(backend)::text,sqlc.arg(api_key_ciphertext)::bytea,sqlc.arg(state)::text)
+ON CONFLICT (backend) DO UPDATE SET
+ api_key_ciphertext=excluded.api_key_ciphertext,state=excluded.state,
+ quota_remaining=NULL,quota_limit=NULL,quota_resets_at=NULL,quota_observed_at=NULL,updated_at=now();
+
+-- name: DeleteWebSearchKey :exec
+DELETE FROM web_search_keys WHERE backend=sqlc.arg(backend)::text;
+
+-- name: MarkWebSearchKeyRejected :exec
+-- Matching the sealed key leaves a key saved since the refused call alone.
+UPDATE web_search_keys SET state='rejected',updated_at=now()
+WHERE backend=sqlc.arg(backend)::text AND api_key_ciphertext=sqlc.arg(api_key_ciphertext)::bytea;
+
+-- name: RecordWebSearchKeyAnswer :exec
+-- An answered call proves the key; quota columns change only when the
+-- response reported quota.
+UPDATE web_search_keys SET state='verified',
+ quota_remaining=CASE WHEN sqlc.arg(has_quota)::boolean THEN sqlc.narg(quota_remaining)::double precision ELSE quota_remaining END,
+ quota_limit=CASE WHEN sqlc.arg(has_quota)::boolean THEN sqlc.narg(quota_limit)::double precision ELSE quota_limit END,
+ quota_resets_at=CASE WHEN sqlc.arg(has_quota)::boolean THEN sqlc.narg(quota_resets_at)::timestamptz ELSE quota_resets_at END,
+ quota_observed_at=CASE WHEN sqlc.arg(has_quota)::boolean THEN now() ELSE quota_observed_at END,
+ updated_at=now()
+WHERE backend=sqlc.arg(backend)::text AND api_key_ciphertext=sqlc.arg(api_key_ciphertext)::bytea;
+
+-- name: GetWebSearchDefaultBackend :one
+SELECT COALESCE(default_backend,'')::text AS default_backend FROM web_search_settings WHERE singleton;
+
+-- name: SetWebSearchDefaultBackend :exec
+INSERT INTO web_search_settings (singleton,default_backend)
+VALUES (true,sqlc.narg(default_backend)::text)
+ON CONFLICT (singleton) DO UPDATE SET default_backend=excluded.default_backend,updated_at=now();
+
+-- name: ClearWebSearchDefaultBackend :exec
+-- Removing a key also drops it as the default, so searches fall back to
+-- TeamHub's order instead of asking for the removed key.
+UPDATE web_search_settings SET default_backend=NULL,updated_at=now()
+WHERE default_backend=sqlc.arg(backend)::text;
diff --git a/apps/teamhub/internal/store/task_delegation.sql.go b/apps/teamhub/internal/store/task_delegation.sql.go
index 3594b7e4..7b4b0b0c 100644
--- a/apps/teamhub/internal/store/task_delegation.sql.go
+++ b/apps/teamhub/internal/store/task_delegation.sql.go
@@ -161,7 +161,7 @@ FROM decisions decision
WHERE decision.tenant_id=$1::text
AND decision.alter_ego_task_id=$2::text
AND decision.status='pending'
- AND decision.kind NOT IN ('connection_auth','provider_key','browser_connection','computer_permission','document_access')
+ AND decision.kind NOT IN ('connection_auth','provider_key','browser_connection','computer_permission','document_access','search_key')
AND (decision.kind<>'runtime_permission' OR decision.request->>'context_key'=$3::text)
ORDER BY decision.created_at,decision.id
`
@@ -182,7 +182,7 @@ type ListDelegatedTaskPendingApprovalsRow struct {
// Approvals the Task's AlterEgo is waiting on: Runtime permission cards of
// its Context and the other approvals it asked for. Connection, computer
-// permission and Document access cards are not approvals.
+// permission, web search key and Document access cards are not approvals.
func (q *Queries) ListDelegatedTaskPendingApprovals(ctx context.Context, arg ListDelegatedTaskPendingApprovalsParams) ([]ListDelegatedTaskPendingApprovalsRow, error) {
rows, err := q.db.Query(ctx, listDelegatedTaskPendingApprovals, arg.TenantID, arg.TaskID, arg.ContextKey)
if err != nil {
diff --git a/apps/teamhub/internal/store/web_search.sql.go b/apps/teamhub/internal/store/web_search.sql.go
new file mode 100644
index 00000000..ea3a5715
--- /dev/null
+++ b/apps/teamhub/internal/store/web_search.sql.go
@@ -0,0 +1,169 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.29.0
+// source: web_search.sql
+
+package store
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const clearWebSearchDefaultBackend = `-- name: ClearWebSearchDefaultBackend :exec
+UPDATE web_search_settings SET default_backend=NULL,updated_at=now()
+WHERE default_backend=$1::text
+`
+
+// Removing a key also drops it as the default, so searches fall back to
+// TeamHub's order instead of asking for the removed key.
+func (q *Queries) ClearWebSearchDefaultBackend(ctx context.Context, backend string) error {
+ _, err := q.db.Exec(ctx, clearWebSearchDefaultBackend, backend)
+ return err
+}
+
+const deleteWebSearchKey = `-- name: DeleteWebSearchKey :exec
+DELETE FROM web_search_keys WHERE backend=$1::text
+`
+
+func (q *Queries) DeleteWebSearchKey(ctx context.Context, backend string) error {
+ _, err := q.db.Exec(ctx, deleteWebSearchKey, backend)
+ return err
+}
+
+const getWebSearchDefaultBackend = `-- name: GetWebSearchDefaultBackend :one
+SELECT COALESCE(default_backend,'')::text AS default_backend FROM web_search_settings WHERE singleton
+`
+
+func (q *Queries) GetWebSearchDefaultBackend(ctx context.Context) (string, error) {
+ row := q.db.QueryRow(ctx, getWebSearchDefaultBackend)
+ var default_backend string
+ err := row.Scan(&default_backend)
+ return default_backend, err
+}
+
+const listWebSearchKeys = `-- name: ListWebSearchKeys :many
+SELECT backend,api_key_ciphertext,state,quota_remaining,quota_limit,quota_resets_at,quota_observed_at
+FROM web_search_keys
+ORDER BY backend
+`
+
+type ListWebSearchKeysRow struct {
+ Backend string `json:"backend"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+ State string `json:"state"`
+ QuotaRemaining pgtype.Float8 `json:"quota_remaining"`
+ QuotaLimit pgtype.Float8 `json:"quota_limit"`
+ QuotaResetsAt pgtype.Timestamptz `json:"quota_resets_at"`
+ QuotaObservedAt pgtype.Timestamptz `json:"quota_observed_at"`
+}
+
+// At most one row per backend; callers pick the one they need.
+func (q *Queries) ListWebSearchKeys(ctx context.Context) ([]ListWebSearchKeysRow, error) {
+ rows, err := q.db.Query(ctx, listWebSearchKeys)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListWebSearchKeysRow{}
+ for rows.Next() {
+ var i ListWebSearchKeysRow
+ if err := rows.Scan(
+ &i.Backend,
+ &i.ApiKeyCiphertext,
+ &i.State,
+ &i.QuotaRemaining,
+ &i.QuotaLimit,
+ &i.QuotaResetsAt,
+ &i.QuotaObservedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const markWebSearchKeyRejected = `-- name: MarkWebSearchKeyRejected :exec
+UPDATE web_search_keys SET state='rejected',updated_at=now()
+WHERE backend=$1::text AND api_key_ciphertext=$2::bytea
+`
+
+type MarkWebSearchKeyRejectedParams struct {
+ Backend string `json:"backend"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+}
+
+// Matching the sealed key leaves a key saved since the refused call alone.
+func (q *Queries) MarkWebSearchKeyRejected(ctx context.Context, arg MarkWebSearchKeyRejectedParams) error {
+ _, err := q.db.Exec(ctx, markWebSearchKeyRejected, arg.Backend, arg.ApiKeyCiphertext)
+ return err
+}
+
+const recordWebSearchKeyAnswer = `-- name: RecordWebSearchKeyAnswer :exec
+UPDATE web_search_keys SET state='verified',
+ quota_remaining=CASE WHEN $1::boolean THEN $2::double precision ELSE quota_remaining END,
+ quota_limit=CASE WHEN $1::boolean THEN $3::double precision ELSE quota_limit END,
+ quota_resets_at=CASE WHEN $1::boolean THEN $4::timestamptz ELSE quota_resets_at END,
+ quota_observed_at=CASE WHEN $1::boolean THEN now() ELSE quota_observed_at END,
+ updated_at=now()
+WHERE backend=$5::text AND api_key_ciphertext=$6::bytea
+`
+
+type RecordWebSearchKeyAnswerParams struct {
+ HasQuota bool `json:"has_quota"`
+ QuotaRemaining pgtype.Float8 `json:"quota_remaining"`
+ QuotaLimit pgtype.Float8 `json:"quota_limit"`
+ QuotaResetsAt pgtype.Timestamptz `json:"quota_resets_at"`
+ Backend string `json:"backend"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+}
+
+// An answered call proves the key; quota columns change only when the
+// response reported quota.
+func (q *Queries) RecordWebSearchKeyAnswer(ctx context.Context, arg RecordWebSearchKeyAnswerParams) error {
+ _, err := q.db.Exec(ctx, recordWebSearchKeyAnswer,
+ arg.HasQuota,
+ arg.QuotaRemaining,
+ arg.QuotaLimit,
+ arg.QuotaResetsAt,
+ arg.Backend,
+ arg.ApiKeyCiphertext,
+ )
+ return err
+}
+
+const setWebSearchDefaultBackend = `-- name: SetWebSearchDefaultBackend :exec
+INSERT INTO web_search_settings (singleton,default_backend)
+VALUES (true,$1::text)
+ON CONFLICT (singleton) DO UPDATE SET default_backend=excluded.default_backend,updated_at=now()
+`
+
+func (q *Queries) SetWebSearchDefaultBackend(ctx context.Context, defaultBackend pgtype.Text) error {
+ _, err := q.db.Exec(ctx, setWebSearchDefaultBackend, defaultBackend)
+ return err
+}
+
+const upsertWebSearchKey = `-- name: UpsertWebSearchKey :exec
+INSERT INTO web_search_keys (backend,api_key_ciphertext,state)
+VALUES ($1::text,$2::bytea,$3::text)
+ON CONFLICT (backend) DO UPDATE SET
+ api_key_ciphertext=excluded.api_key_ciphertext,state=excluded.state,
+ quota_remaining=NULL,quota_limit=NULL,quota_resets_at=NULL,quota_observed_at=NULL,updated_at=now()
+`
+
+type UpsertWebSearchKeyParams struct {
+ Backend string `json:"backend"`
+ ApiKeyCiphertext []byte `json:"api_key_ciphertext"`
+ State string `json:"state"`
+}
+
+// A new key starts with no observed quota.
+func (q *Queries) UpsertWebSearchKey(ctx context.Context, arg UpsertWebSearchKeyParams) error {
+ _, err := q.db.Exec(ctx, upsertWebSearchKey, arg.Backend, arg.ApiKeyCiphertext, arg.State)
+ return err
+}
diff --git a/apps/teamhub/internal/typedcard/alter_ego_approvals.go b/apps/teamhub/internal/typedcard/alter_ego_approvals.go
index 0de590b7..b6d851a1 100644
--- a/apps/teamhub/internal/typedcard/alter_ego_approvals.go
+++ b/apps/teamhub/internal/typedcard/alter_ego_approvals.go
@@ -42,7 +42,7 @@ func (s *Service) ExpireStoppedTaskApprovals(ctx context.Context, tenantID, task
defer tx.Rollback(ctx)
rows, err := tx.Query(ctx, `UPDATE decisions SET status='expired', finished_at=clock_timestamp()
WHERE tenant_id=$1 AND alter_ego_task_id=$2 AND status='pending'
- AND kind NOT IN ('connection_auth','provider_key','browser_connection')
+ AND kind NOT IN ('connection_auth','provider_key','browser_connection','search_key')
RETURNING decider_actor_id, message_id`, tenantID, taskID)
if err != nil {
return err
diff --git a/apps/teamhub/internal/typedcard/decision_connection.go b/apps/teamhub/internal/typedcard/decision_connection.go
index 011ed1e3..275ec840 100644
--- a/apps/teamhub/internal/typedcard/decision_connection.go
+++ b/apps/teamhub/internal/typedcard/decision_connection.go
@@ -421,7 +421,7 @@ func (s *Service) SettleBrowserConnections(ctx context.Context, tenantID, ownerA
}
func (s *Service) settleBrowserConnection(ctx context.Context, id string) error {
- return s.answerConnectionCard(ctx, id, "connected")
+ return s.answerConnectionCard(ctx, id, decisionAnswer{Decision: "connected"}, nil)
}
// SettleProviderKeys answers every pending Composio key card once a key is
@@ -438,14 +438,15 @@ func (s *Service) SettleProviderKeys(ctx context.Context) error {
}
var settleErr error
for _, id := range ids {
- settleErr = errors.Join(settleErr, s.answerConnectionCard(ctx, id, "configured"))
+ settleErr = errors.Join(settleErr, s.answerConnectionCard(ctx, id, decisionAnswer{Decision: "configured"}, nil))
}
return settleErr
}
// answerConnectionCard answers one pending card on its decider's behalf with
-// what happened outside it, and hands the answer to its Agent.
-func (s *Service) answerConnectionCard(ctx context.Context, id, decision string) error {
+// what happened outside it, records result when it is set, and hands the
+// answer to its Agent.
+func (s *Service) answerConnectionCard(ctx context.Context, id string, answer decisionAnswer, result []byte) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
@@ -455,14 +456,14 @@ func (s *Service) answerConnectionCard(ctx context.Context, id, decision string)
if err != nil || !live {
return err
}
- answer, err := json.Marshal(decisionAnswer{Decision: decision})
+ encoded, err := json.Marshal(answer)
if err != nil {
return err
}
var alterEgo bool
- err = tx.QueryRow(ctx, `UPDATE decisions SET status='answered', answer=$2::jsonb,
+ err = tx.QueryRow(ctx, `UPDATE decisions SET status='answered', answer=$2::jsonb, result=coalesce($3::jsonb,result),
decided_at=clock_timestamp(), decided_by_actor_id=decider_actor_id, finished_at=clock_timestamp()
- WHERE id=$1 AND status='pending' RETURNING alter_ego_task_id IS NOT NULL`, id, answer).Scan(&alterEgo)
+ WHERE id=$1 AND status='pending' RETURNING alter_ego_task_id IS NOT NULL`, id, encoded, result).Scan(&alterEgo)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
diff --git a/apps/teamhub/internal/typedcard/decision_search_key.go b/apps/teamhub/internal/typedcard/decision_search_key.go
new file mode 100644
index 00000000..eca4255c
--- /dev/null
+++ b/apps/teamhub/internal/typedcard/decision_search_key.go
@@ -0,0 +1,308 @@
+package typedcard
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "slices"
+ "strconv"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/messagecreation"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// searchKeyBackends are the web search backends a key card may show.
+var searchKeyBackends = []string{"tavily", "brave", "firecrawl", "you"}
+
+// SearchKeyDecision asks a Human for a web search API key. Backend is the one
+// the card shows: the backend the Agent's command named, or, when it named
+// none (Suggested), the first one TeamHub's order still needs a key for.
+// Reason is missing, rejected or free_limit. Request is the search or page
+// open the card was posted for, which TeamHub replays with a key added from
+// the card; nil for a connect request. The Human may add any backend's key
+// instead; saving any web search key answers the card.
+type SearchKeyDecision struct {
+ Prompt string
+ Backend string
+ Suggested bool
+ Reason string
+ Request *SearchKeyRequest
+}
+
+// SearchKeyRequest is a stored web search or page open. Backend is the one
+// the command named, empty when it named none.
+type SearchKeyRequest struct {
+ Command string `json:"command"`
+ Backend string `json:"backend,omitempty"`
+ Query string `json:"query,omitempty"`
+ Limit int `json:"limit,omitempty"`
+ Recency string `json:"recency,omitempty"`
+ Sites []string `json:"sites,omitempty"`
+ URL string `json:"url,omitempty"`
+}
+
+// searchKeyView is what a search_key card shows.
+type searchKeyView struct {
+ Prompt string `json:"prompt"`
+ Backend string `json:"backend"`
+ Origin string `json:"origin"`
+ Reason string `json:"reason"`
+}
+
+func (command SearchKeyDecision) draft() (decisionDraft, error) {
+ prompt, err := normalizeConnectionPrompt(command.Prompt)
+ if err != nil || !slices.Contains(searchKeyBackends, command.Backend) ||
+ !slices.Contains([]string{"missing", "rejected", "free_limit"}, command.Reason) {
+ return decisionDraft{}, ErrInvalid
+ }
+ var request any = struct{}{}
+ if command.Request != nil {
+ if command.Request.Command != "search" && command.Request.Command != "open" {
+ return decisionDraft{}, ErrInvalid
+ }
+ request = command.Request
+ }
+ origin := "requested"
+ if command.Suggested {
+ origin = "suggested"
+ }
+ return decisionDraft{kind: DecisionKindSearchKey, text: prompt, request: request,
+ view: searchKeyView{Prompt: prompt, Backend: command.Backend, Origin: origin, Reason: command.Reason}, connection: true}, nil
+}
+
+// reusePendingSearchKey returns the key card still waiting for the same Human
+// and Agent in this Room, whichever backend it shows: any saved key answers
+// it. The card then shows the latest backend, and keeps the latest request
+// for the replay; a connect request, which has none, leaves the stored one.
+func reusePendingSearchKey(
+ ctx context.Context, tx pgx.Tx, queries *store.Queries, tenantID, roomID, agentID, humanID, alterEgoTaskID string,
+ requestJSON, viewJSON []byte,
+) (CreateResult, bool, error) {
+ eligible, err := connectionAuthParticipants(ctx, tx, tenantID, roomID, humanID, agentID)
+ if err != nil {
+ return CreateResult{}, false, err
+ }
+ if !eligible {
+ return CreateResult{}, false, ErrForbidden
+ }
+ pending, found, err := pendingConnectionCard(ctx, tx, `SELECT message_id,id FROM decisions
+ WHERE tenant_id=$1 AND room_id=$2 AND requested_by_actor_id=$3 AND decider_actor_id=$4
+ AND kind='search_key' AND status='pending' AND alter_ego_task_id IS NOT DISTINCT FROM $5
+ ORDER BY created_at DESC LIMIT 1`, tenantID, roomID, agentID, humanID, optionalText(alterEgoTaskID))
+ if err != nil || !found {
+ return CreateResult{}, false, err
+ }
+ // The Room membership lock CreateDecision holds keeps the card pending
+ // while it is rewritten: every answer takes that lock first.
+ var storedView []byte
+ if err := tx.QueryRow(ctx, `SELECT view FROM decisions WHERE id=$1`, pending.DecisionID).Scan(&storedView); err != nil {
+ return CreateResult{}, false, err
+ }
+ if _, err := tx.Exec(ctx, `UPDATE decisions SET view=$3::jsonb,
+ request=CASE WHEN $2::jsonb='{}'::jsonb THEN request ELSE $2::jsonb END WHERE id=$1`,
+ pending.DecisionID, requestJSON, viewJSON); err != nil {
+ return CreateResult{}, false, err
+ }
+ if !jsonEqual(storedView, viewJSON) {
+ if err := messagecreation.AdvanceCards(ctx, queries, tenantID, agentID, []string{pending.MessageID}); err != nil {
+ return CreateResult{}, false, err
+ }
+ }
+ return pending, true, nil
+}
+
+func jsonEqual(a, b []byte) bool {
+ var left, right any
+ if json.Unmarshal(a, &left) != nil || json.Unmarshal(b, &right) != nil {
+ return bytes.Equal(a, b)
+ }
+ encodedLeft, _ := json.Marshal(left)
+ encodedRight, _ := json.Marshal(right)
+ return bytes.Equal(encodedLeft, encodedRight)
+}
+
+// SearchKeyCard is an open key card a Human adds a key from.
+type SearchKeyCard struct {
+ // Request is the call to replay; nil when a connect request posted the
+ // card.
+ Request *SearchKeyRequest
+ // Open is false once the card has ended; the key is then saved without
+ // a replay.
+ Open bool
+}
+
+// SearchKeyCardRequest returns the request a search_key card stores, for its
+// decision owner adding a key from it. It returns ErrNotFound for a card the
+// caller cannot see, ErrForbidden for one they do not decide, and ErrInvalid
+// for another kind of card.
+func (s *Service) SearchKeyCardRequest(ctx context.Context, accountID, decisionID string) (SearchKeyCard, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return SearchKeyCard{}, err
+ }
+ defer tx.Rollback(ctx)
+ authority, err := store.New(tx).GetDecisionAuthority(ctx, store.GetDecisionAuthorityParams{AccountID: accountID, DecisionID: decisionID})
+ switch {
+ case errors.Is(err, pgx.ErrNoRows):
+ return SearchKeyCard{}, ErrNotFound
+ case err != nil:
+ return SearchKeyCard{}, err
+ case authority.Kind != DecisionKindSearchKey:
+ return SearchKeyCard{}, ErrInvalid
+ case authority.CallerActorID != authority.DeciderActorID:
+ return SearchKeyCard{}, ErrForbidden
+ }
+ card := SearchKeyCard{Open: authority.Open}
+ var request SearchKeyRequest
+ if err := json.Unmarshal(authority.Request, &request); err != nil {
+ return SearchKeyCard{}, err
+ }
+ if request.Command != "" {
+ card.Request = &request
+ }
+ return card, tx.Commit(ctx)
+}
+
+// SearchKeyReplay is what the replay of a card's request returned with the
+// key added from that card: Results for a search, Page for a page open, or
+// the agent error code of a failed call.
+type SearchKeyReplay struct {
+ DecisionID string `json:"-"`
+ Results json.RawMessage `json:"results,omitempty"`
+ Page json.RawMessage `json:"page,omitempty"`
+ ErrorCode string `json:"error_code,omitempty"`
+}
+
+// SettleSearchKeys answers every pending search_key card configured with the
+// backend whose key was just saved, and wakes each waiting Agent. The card the
+// key was added from also records its replay. The key belongs to the
+// deployment, so it answers the cards of every tenant.
+func (s *Service) SettleSearchKeys(ctx context.Context, backend string, replay *SearchKeyReplay) error {
+ if !slices.Contains(searchKeyBackends, backend) {
+ return ErrInvalid
+ }
+ rows, err := s.pool.Query(ctx, `SELECT id FROM decisions WHERE kind='search_key' AND status='pending' ORDER BY id`)
+ if err != nil {
+ return err
+ }
+ ids, err := pgx.CollectRows(rows, pgx.RowTo[string])
+ if err != nil {
+ return err
+ }
+ var replayResult []byte
+ if replay != nil {
+ data, err := json.Marshal(replay)
+ if err != nil {
+ return err
+ }
+ if replayResult, err = json.Marshal(decisionStoredResult{Data: data}); err != nil {
+ return err
+ }
+ }
+ var settleErr error
+ for _, id := range ids {
+ var result []byte
+ if replay != nil && id == replay.DecisionID {
+ result = replayResult
+ }
+ settleErr = errors.Join(settleErr, s.answerConnectionCard(ctx, id, decisionAnswer{Decision: "configured", Backend: backend}, result))
+ }
+ return settleErr
+}
+
+// searchKeyPayload is how an Agent reads a key card's result.
+type searchKeyPayload struct {
+ Decision string `json:"decision"`
+ Backend string `json:"backend,omitempty"`
+ RequestedBackend string `json:"requested_backend,omitempty"`
+ Results json.RawMessage `json:"results,omitempty"`
+ Page json.RawMessage `json:"page,omitempty"`
+ ErrorCode string `json:"error_code,omitempty"`
+}
+
+var searchKeyNames = map[string]struct{ name, key string }{
+ "tavily": {"Tavily", "a Tavily API key"},
+ "brave": {"Brave Search", "a Brave Search key"},
+ "firecrawl": {"Firecrawl", "a Firecrawl API key"},
+ "you": {"You.com", "a You.com API key"},
+}
+
+// searchKeyNoticeText tells the waiting Agent how its key card ended. The
+// decision is in the payload line; the sentence is for the model to read.
+// A replayed call's results come with it, so the Agent need not run it again.
+func searchKeyNoticeText(decisionID string, decision decisionRecord, answer decisionAnswer, result decisionStoredResult) (string, error) {
+ var view searchKeyView
+ if err := json.Unmarshal(decision.View, &view); err != nil {
+ return "", err
+ }
+ var request SearchKeyRequest
+ if len(decision.Request) > 0 {
+ if err := json.Unmarshal(decision.Request, &request); err != nil {
+ return "", err
+ }
+ }
+ var replay SearchKeyReplay
+ if len(result.Data) > 0 {
+ if err := json.Unmarshal(result.Data, &replay); err != nil {
+ return "", err
+ }
+ }
+ alterEgo := decision.AlterEgoTaskID.Valid
+ who, prefix := "The user", "Human interaction "+decisionID+" resolved: "
+ if alterEgo {
+ who, prefix = "The Sponsor", ""
+ }
+ payload := searchKeyPayload{Decision: "deny"}
+ text := who + " declined to add a web search key. Don't retry; tell the user web search needs a key in Connectors."
+ if alterEgo {
+ text = who + " declined to add a web search key. Don't retry; say in your final reply that web search needs a key in Connectors."
+ }
+ if decision.Status == "answered" {
+ // A connect request named its backend; a search without one named none.
+ requested := request.Backend
+ if request.Command == "" {
+ requested = view.Backend
+ }
+ configured := answer.Backend
+ payload = searchKeyPayload{Decision: "configured", Backend: configured, Results: replay.Results, Page: replay.Page, ErrorCode: replay.ErrorCode}
+ text = who + " added " + searchKeyNames[configured].key
+ if requested != "" && requested != configured {
+ payload.RequestedBackend = requested
+ text += " instead of " + searchKeyNames[requested].name
+ }
+ action := "search for " + strconv.Quote(request.Query)
+ if request.Command == "open" {
+ action = "page open of " + request.URL
+ }
+ rerun := " with --backend " + configured
+ if requested == configured {
+ rerun = ""
+ }
+ switch {
+ case len(replay.Results) > 0:
+ text += ". Results of your " + action + " are in the payload below; don't run it again."
+ case len(replay.Page) > 0:
+ text += ". The page from your " + action + " is in the payload below; don't open it again."
+ case replay.ErrorCode != "":
+ text += ", but your " + action + " failed with it (" + replay.ErrorCode + "). Decide whether to run the command again" + rerun + "."
+ default:
+ text += ". Run the command again" + rerun + "."
+ }
+ }
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ return "", err
+ }
+ return prefix + text + "\npayload=" + string(encoded), nil
+}
+
+// searchKeyCardView is the kind's view on a search_key card.
+func searchKeyCardView(view searchKeyView) (json.RawMessage, error) {
+ return json.Marshal(struct {
+ Backend string `json:"backend"`
+ Origin string `json:"origin"`
+ Reason string `json:"reason"`
+ }{view.Backend, view.Origin, view.Reason})
+}
diff --git a/apps/teamhub/internal/typedcard/decision_search_key_test.go b/apps/teamhub/internal/typedcard/decision_search_key_test.go
new file mode 100644
index 00000000..5dd70418
--- /dev/null
+++ b/apps/teamhub/internal/typedcard/decision_search_key_test.go
@@ -0,0 +1,146 @@
+package typedcard
+
+import (
+ "encoding/json"
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+func TestSearchKeyDecisionDraftsItsCard(t *testing.T) {
+ t.Parallel()
+ request := &SearchKeyRequest{Command: "search", Backend: "", Query: "q", Limit: 10}
+ draft, err := DecisionCommand{SearchKey: &SearchKeyDecision{Prompt: " Add a key ", Backend: "tavily", Suggested: true, Reason: "free_limit", Request: request}}.draft()
+ if err != nil || draft.kind != DecisionKindSearchKey || draft.text != "Add a key" || !draft.connection || draft.lifetime != 0 ||
+ draft.view.(searchKeyView) != (searchKeyView{Prompt: "Add a key", Backend: "tavily", Origin: "suggested", Reason: "free_limit"}) ||
+ draft.request.(*SearchKeyRequest) != request {
+ t.Fatalf("search_key draft=%+v err=%v", draft, err)
+ }
+ draft, err = DecisionCommand{SearchKey: &SearchKeyDecision{Prompt: "Add a key", Backend: "brave", Reason: "missing"}}.draft()
+ if err != nil || draft.view.(searchKeyView).Origin != "requested" {
+ t.Fatalf("connect draft=%+v err=%v", draft, err)
+ }
+ if encoded, _ := json.Marshal(draft.request); string(encoded) != "{}" {
+ t.Fatalf("connect request=%s", encoded)
+ }
+ for name, command := range map[string]SearchKeyDecision{
+ "no prompt": {Backend: "tavily", Reason: "missing"},
+ "direct": {Prompt: "a", Backend: "direct", Reason: "missing"},
+ "no backend": {Prompt: "a", Reason: "missing"},
+ "bad reason": {Prompt: "a", Backend: "tavily", Reason: "quota"},
+ "bad command": {Prompt: "a", Backend: "tavily", Reason: "missing", Request: &SearchKeyRequest{Command: "crawl"}},
+ "empty replay": {Prompt: "a", Backend: "tavily", Reason: "missing", Request: &SearchKeyRequest{}},
+ } {
+ if _, err := (DecisionCommand{SearchKey: &command}).draft(); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("%s: err=%v", name, err)
+ }
+ }
+ for _, test := range []struct {
+ command DecisionAnswerCommand
+ valid bool
+ }{{DecisionAnswerCommand{Decision: "deny"}, true}, {DecisionAnswerCommand{Decision: "configured"}, false}, {DecisionAnswerCommand{Decision: "deny", Comment: "no"}, false}} {
+ answer, status, err := normalizeDecisionAnswer(DecisionKindSearchKey, nil, test.command)
+ if test.valid != (err == nil) || test.valid && (status != "denied" || answer.Decision != "deny") {
+ t.Fatalf("%+v: answer=%+v status=%q err=%v", test.command, answer, status, err)
+ }
+ }
+}
+
+// The Agent reads the decision from the payload and what to do next from the
+// sentence: run again with the configured backend, use the replayed results,
+// or stop asking.
+func TestSearchKeyNoticesCarryTheConfiguredBackend(t *testing.T) {
+ t.Parallel()
+ view := func(backend string) []byte {
+ encoded, _ := json.Marshal(searchKeyView{Prompt: "Add a key", Backend: backend, Origin: "requested", Reason: "missing"})
+ return encoded
+ }
+ tavilySearch := []byte(`{"command":"search","backend":"tavily","query":"rust 2026","limit":10}`)
+ implicitSearch := []byte(`{"command":"search","query":"rust 2026","limit":10}`)
+ open := []byte(`{"command":"open","backend":"tavily","url":"https://a.example/x"}`)
+ task := pgtype.Text{String: "task_1", Valid: true}
+ for _, test := range []struct {
+ name string
+ status string
+ view []byte
+ request []byte
+ answer string
+ result string
+ alterEgo pgtype.Text
+ want string
+ }{
+ {"same backend", "answered", view("tavily"), tavilySearch, `{"decision":"configured","backend":"tavily"}`, "", pgtype.Text{},
+ "Human interaction decision_1 resolved: The user added a Tavily API key. Run the command again.\n" +
+ `payload={"decision":"configured","backend":"tavily"}`},
+ {"other backend", "answered", view("tavily"), tavilySearch, `{"decision":"configured","backend":"brave"}`, "", pgtype.Text{},
+ "Human interaction decision_1 resolved: The user added a Brave Search key instead of Tavily. Run the command again with --backend brave.\n" +
+ `payload={"decision":"configured","backend":"brave","requested_backend":"tavily"}`},
+ {"no backend named", "answered", view("tavily"), implicitSearch, `{"decision":"configured","backend":"tavily"}`, "", pgtype.Text{},
+ "The user added a Tavily API key. Run the command again with --backend tavily.\n" + `payload={"decision":"configured","backend":"tavily"}`},
+ {"connect", "answered", view("firecrawl"), []byte(`{}`), `{"decision":"configured","backend":"firecrawl"}`, "", pgtype.Text{},
+ "The user added a Firecrawl API key. Run the command again.\n"},
+ {"declined", "denied", view("tavily"), tavilySearch, `{"decision":"deny"}`, "", pgtype.Text{},
+ "Human interaction decision_1 resolved: The user declined to add a web search key. Don't retry; tell the user web search needs a key in Connectors.\n" +
+ `payload={"decision":"deny"}`},
+ {"declined task", "denied", view("tavily"), tavilySearch, `{"decision":"deny"}`, "", task,
+ "The Sponsor declined to add a web search key. Don't retry; say in your final reply"},
+ {"replayed search", "answered", view("tavily"), tavilySearch, `{"decision":"configured","backend":"brave"}`,
+ `{"outcome":"","data":{"results":[{"title":"T","url":"https://t.example","snippet":"s"}]}}`, pgtype.Text{},
+ `The user added a Brave Search key instead of Tavily. Results of your search for "rust 2026" are in the payload below; don't run it again.` + "\n" +
+ `payload={"decision":"configured","backend":"brave","requested_backend":"tavily","results":[{"title":"T","url":"https://t.example","snippet":"s"}]}`},
+ {"replayed open", "answered", view("tavily"), open, `{"decision":"configured","backend":"tavily"}`,
+ `{"outcome":"","data":{"page":{"url":"https://a.example/x","markdown":"# A","truncated":false}}}`, task,
+ "The Sponsor added a Tavily API key. The page from your page open of https://a.example/x is in the payload below"},
+ {"replay failed", "answered", view("tavily"), tavilySearch, `{"decision":"configured","backend":"brave"}`,
+ `{"outcome":"","data":{"error_code":"search_quota_exhausted"}}`, pgtype.Text{},
+ `but your search for "rust 2026" failed with it (search_quota_exhausted). Decide whether to run the command again with --backend brave.` + "\n" +
+ `payload={"decision":"configured","backend":"brave","requested_backend":"tavily","error_code":"search_quota_exhausted"}`},
+ } {
+ decision := decisionRecord{Kind: DecisionKindSearchKey, Status: test.status, View: test.view, Request: test.request,
+ Answer: []byte(test.answer), AlterEgoTaskID: test.alterEgo}
+ if test.result != "" {
+ decision.Result = []byte(test.result)
+ }
+ text, err := decisionNoticeText("decision_1", decision)
+ if err != nil || !strings.Contains(text, test.want) {
+ t.Fatalf("%s: text=%q err=%v", test.name, text, err)
+ }
+ if test.alterEgo.Valid && strings.HasPrefix(text, "Human interaction") {
+ t.Fatalf("%s: a Task notice names the interaction: %q", test.name, text)
+ }
+ }
+}
+
+func TestEncodeDecisionCardShowsTheSearchKeyView(t *testing.T) {
+ t.Parallel()
+ decider := store.Actor{ID: "actor_alice", Kind: "human", DisplayName: "Alice"}
+ requester := store.Actor{ID: "actor_nova", Kind: "agent", DisplayName: "Nova"}
+ record := store.MessageCard{CardType: "personal_notice", Intent: "decision_requested", Version: 3}
+ view, _ := json.Marshal(searchKeyView{Prompt: "Add a web search key", Backend: "tavily", Origin: "suggested", Reason: "free_limit"})
+ decision := decisionRecord{ID: "decision_s", Kind: DecisionKindSearchKey, Status: "answered", View: view,
+ Request: []byte(`{"command":"search","query":"secret plans"}`),
+ Answer: []byte(`{"decision":"configured","backend":"brave"}`),
+ Result: []byte(`{"outcome":"","data":{"results":[{"title":"T","url":"https://t.example","snippet":"s"}]}}`),
+ DecidedAt: pgtype.Timestamptz{Time: time.Date(2026, 11, 20, 9, 0, 0, 0, time.UTC), Valid: true}}
+ encoded, err := encodeDecisionCard(record, decider, requester, &decider, decision)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var card map[string]any
+ if err := json.Unmarshal(encoded, &card); err != nil {
+ t.Fatal(err)
+ }
+ searchKey := card["search_key"].(map[string]any)
+ if card["title"] != "Add a web search key" || searchKey["backend"] != "tavily" || searchKey["origin"] != "suggested" ||
+ searchKey["reason"] != "free_limit" || card["answer"].(map[string]any)["backend"] != "brave" || card["outcome"] != nil {
+ t.Fatalf("card=%s", encoded)
+ }
+ // The replayed results and the stored request reach only the Agent.
+ if strings.Contains(string(encoded), "secret plans") || strings.Contains(string(encoded), "t.example") {
+ t.Fatalf("card leaks the replay: %s", encoded)
+ }
+}
diff --git a/apps/teamhub/internal/typedcard/decisions.go b/apps/teamhub/internal/typedcard/decisions.go
index 6f4ff122..ae292837 100644
--- a/apps/teamhub/internal/typedcard/decisions.go
+++ b/apps/teamhub/internal/typedcard/decisions.go
@@ -28,9 +28,10 @@ import (
// AnotherMe setup cards end with their answer. A connection authorization
// ends when the OAuth the Human started completes, a Composio key request
// when someone saves the key, a browser connection when
-// the owner connects Chrome, and a computer permission when the Computer
-// reports its permissions granted; a Room creation runs in its decision; a
-// Document access card follows the Document access request it shows.
+// the owner connects Chrome, a computer permission when the Computer reports
+// its permissions granted, and a web search key request when someone saves
+// any web search key; a Room creation runs in its decision; a Document access
+// card follows the Document access request it shows.
const (
DecisionKindConnectorWrite = "connector_write"
DecisionKindAgentChange = "agent_change"
@@ -43,6 +44,7 @@ const (
DecisionKindBrowserConnection = "browser_connection"
DecisionKindRoomCreation = "room_creation"
DecisionKindComputerPermission = "computer_permission"
+ DecisionKindSearchKey = "search_key"
)
// decisionTTL bounds how long a Connector write or Agent change waits for its
@@ -77,6 +79,7 @@ type DecisionCommand struct {
ProviderKey *ProviderKeyDecision
BrowserConnection *BrowserConnectionDecision
ComputerPermission *ComputerPermissionDecision
+ SearchKey *SearchKeyDecision
}
// decisionDraft is a command's card before it is stored.
@@ -97,7 +100,7 @@ func (command DecisionCommand) draft() (decisionDraft, error) {
set := 0
for _, present := range []bool{command.ConnectorWrite != nil, command.AgentChange != nil, command.Question != nil,
command.RuntimePermission != nil, command.ConnectionAuth != nil, command.ProviderKey != nil,
- command.BrowserConnection != nil, command.ComputerPermission != nil} {
+ command.BrowserConnection != nil, command.ComputerPermission != nil, command.SearchKey != nil} {
if present {
set++
}
@@ -137,6 +140,8 @@ func (command DecisionCommand) draft() (decisionDraft, error) {
return command.BrowserConnection.draft()
case command.ComputerPermission != nil:
return command.ComputerPermission.draft()
+ case command.SearchKey != nil:
+ return command.SearchKey.draft()
default:
permission := command.RuntimePermission
if permission.ContextKey == "" || permission.ActionDigest == "" || len(permission.Runtime) == 0 || strings.TrimSpace(permission.Card.Title) == "" {
@@ -299,6 +304,8 @@ func (s *Service) CreateDecision(
pending, found, err = reusePendingBrowserConnection(ctx, tx, authority.TenantID, authority.RoomID, author.ID, decider.ID, command.BrowserConnection.ComputerID, command.AlterEgoTaskID)
case command.ComputerPermission != nil:
pending, found, err = reusePendingComputerPermission(ctx, tx, authority.TenantID, authority.RoomID, author.ID, decider.ID, *command.ComputerPermission, command.AlterEgoTaskID)
+ case command.SearchKey != nil:
+ pending, found, err = reusePendingSearchKey(ctx, tx, queries, authority.TenantID, authority.RoomID, author.ID, decider.ID, command.AlterEgoTaskID, requestJSON, viewJSON)
}
if err != nil {
return CreateResult{}, err
@@ -377,8 +384,8 @@ func optionalText(value string) pgtype.Text {
// DecisionAnswerCommand answers a decision with the fields its kind takes:
// approve or deny with an optional reason for a denial (a Room creation's
// denial requires one), approve with the chosen Connection or deny for a
-// connection authorization, deny for a browser connection or a computer
-// permission, submit with
+// connection authorization, deny for a browser connection, a computer
+// permission or a web search key request, submit with
// answers and an optional note for a question, connected or skipped for the
// apps card, and done or skipped with links and uploads for the sources card.
type DecisionAnswerCommand struct {
@@ -391,11 +398,13 @@ type DecisionAnswerCommand struct {
AttachmentUploadIDs []string
}
-// decisionAnswer is the stored answer.
+// decisionAnswer is the stored answer. Backend is the web search backend
+// whose key answered a search_key card.
type decisionAnswer struct {
Decision string `json:"decision"`
Comment string `json:"comment,omitempty"`
ConnectionID string `json:"connection_id,omitempty"`
+ Backend string `json:"backend,omitempty"`
Answers map[string]any `json:"answers,omitempty"`
Links []string `json:"links,omitempty"`
AttachmentUploadIDs []string `json:"attachment_upload_ids,omitempty"`
@@ -443,10 +452,10 @@ func normalizeDecisionAnswer(kind string, view []byte, command DecisionAnswerCom
return decisionAnswer{}, "", ErrInvalid
}
return decisionAnswer{Decision: command.Decision, ConnectionID: command.ConnectionID}, "denied", nil
- case DecisionKindProviderKey, DecisionKindBrowserConnection, DecisionKindComputerPermission:
- // Only a saved Composio key, the owner's own connection, or the
- // Computer's report that every permission is granted answers the card
- // otherwise.
+ case DecisionKindProviderKey, DecisionKindBrowserConnection, DecisionKindComputerPermission, DecisionKindSearchKey:
+ // Only a saved Composio or web search key, the owner's own
+ // connection, or the Computer's report that every permission is
+ // granted answers the card otherwise.
if command.Decision != "deny" || command.Comment != "" {
return decisionAnswer{}, "", ErrInvalid
}
@@ -883,6 +892,8 @@ func decisionNoticeText(decisionID string, decision decisionRecord) (string, err
return "", err
}
return computerPermissionNoticeText(decisionID, view, decision.Status), nil
+ case DecisionKindSearchKey:
+ return searchKeyNoticeText(decisionID, decision, answer, result)
case DecisionKindProfileSetupApps, DecisionKindProfileSetupSources, DecisionKindRoomCreation:
return "", nil
default:
@@ -926,6 +937,7 @@ type decisionCard struct {
BrowserConnection json.RawMessage `json:"browser_connection,omitempty"`
RoomCreation json.RawMessage `json:"room_creation,omitempty"`
ComputerPermission json.RawMessage `json:"computer_permission,omitempty"`
+ SearchKey json.RawMessage `json:"search_key,omitempty"`
}
// encodeDecisionCard projects one decision card. decidedBy is the Human who
@@ -1011,6 +1023,15 @@ func encodeDecisionCard(
}
case DecisionKindComputerPermission:
card.Title, card.ComputerPermission = computerPermissionTitle, decision.View
+ case DecisionKindSearchKey:
+ var view searchKeyView
+ if err := json.Unmarshal(decision.View, &view); err != nil {
+ return nil, err
+ }
+ card.Title = view.Prompt
+ if card.SearchKey, err = searchKeyCardView(view); err != nil {
+ return nil, err
+ }
default:
return nil, fmt.Errorf("unsupported decision kind %q", decision.Kind)
}
diff --git a/apps/teamhub/internal/websearch/providers.go b/apps/teamhub/internal/websearch/providers.go
new file mode 100644
index 00000000..16067e1f
--- /dev/null
+++ b/apps/teamhub/internal/websearch/providers.go
@@ -0,0 +1,660 @@
+package websearch
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "html"
+ "io"
+ "math"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strconv"
+ "strings"
+ "time"
+ "unicode/utf8"
+)
+
+// The provider APIs. Tests point Endpoints at fakes instead.
+const (
+ DefaultTavilyURL = "https://api.tavily.com"
+ DefaultBraveURL = "https://api.search.brave.com"
+ DefaultFirecrawlURL = "https://api.firecrawl.dev"
+ DefaultYouAPIURL = "https://api.you.com"
+ DefaultYouIndexURL = "https://ydc-index.io"
+ DefaultYouMCPURL = "https://api.you.com/mcp/free"
+)
+
+// Call budgets. A page read waits longer because the provider fetches and
+// renders the page first.
+const (
+ searchTimeout = 20 * time.Second
+ openTimeout = 45 * time.Second
+ checkTimeout = 10 * time.Second
+ maxResponseBody = 8 << 20
+)
+
+// Endpoints are the provider base URLs; an empty field uses the provider's
+// API. Client replaces the default client, which never follows a redirect so
+// a key never reaches another host.
+type Endpoints struct {
+ Tavily, Brave, Firecrawl, YouAPI, YouIndex, YouMCP string
+ Client *http.Client
+}
+
+type providers struct {
+ endpoints Endpoints
+ client *http.Client
+}
+
+func newProviders(endpoints Endpoints) *providers {
+ for _, field := range []struct {
+ value *string
+ fallback string
+ }{
+ {&endpoints.Tavily, DefaultTavilyURL}, {&endpoints.Brave, DefaultBraveURL},
+ {&endpoints.Firecrawl, DefaultFirecrawlURL}, {&endpoints.YouAPI, DefaultYouAPIURL},
+ {&endpoints.YouIndex, DefaultYouIndexURL}, {&endpoints.YouMCP, DefaultYouMCPURL},
+ } {
+ if *field.value == "" {
+ *field.value = field.fallback
+ }
+ *field.value = strings.TrimRight(*field.value, "/")
+ }
+ client := endpoints.Client
+ if client == nil {
+ client = &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
+ }
+ return &providers{endpoints: endpoints, client: client}
+}
+
+// answer is one provider response.
+type answer struct {
+ status int
+ header http.Header
+ body []byte
+}
+
+// call sends one request. A transport failure is CodeProviderUnavailable;
+// the error never carries the URL, which may hold the query.
+func (p *providers) call(ctx context.Context, method, endpoint string, header map[string]string, body any) (answer, error) {
+ var reader io.Reader
+ if body != nil {
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ return answer{}, err
+ }
+ reader = bytes.NewReader(encoded)
+ }
+ request, err := http.NewRequestWithContext(ctx, method, endpoint, reader)
+ if err != nil {
+ return answer{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ request.Header.Set("Accept", "application/json")
+ if body != nil {
+ request.Header.Set("Content-Type", "application/json")
+ }
+ for name, value := range header {
+ request.Header.Set(name, value)
+ }
+ response, err := p.client.Do(request)
+ if err != nil {
+ return answer{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ defer response.Body.Close()
+ read, err := io.ReadAll(io.LimitReader(response.Body, maxResponseBody))
+ if err != nil {
+ return answer{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ return answer{status: response.StatusCode, header: response.Header, body: read}, nil
+}
+
+// classify turns a refused call into a Failure: 401 and 403 refuse the key,
+// 402 and Tavily's 432/433 say the account has no credit left, 429 is a rate
+// limit. A page read the provider could not fetch is unreadable. The
+// provider's text is never kept.
+func classify(b Backend, command string, a answer) error {
+ if a.status >= 200 && a.status < 300 {
+ return nil
+ }
+ failure := &Failure{Code: CodeProviderUnavailable, Backend: b}
+ switch {
+ case a.status == http.StatusUnauthorized || a.status == http.StatusForbidden:
+ failure.Code = CodeKeyRejected
+ case a.status == http.StatusPaymentRequired || b == Tavily && (a.status == 432 || a.status == 433):
+ failure.Code, failure.proved = CodeQuotaExhausted, true
+ case a.status == http.StatusTooManyRequests:
+ failure.Code, failure.proved = CodeRateLimited, true
+ if b == Brave && braveErrorCode(a.body) == "QUOTA_LIMITED" {
+ failure.Code = CodeQuotaExhausted
+ }
+ failure.RetryAfter = retryAfter(a.header)
+ case b == Brave && a.status == http.StatusUnprocessableEntity && braveErrorCode(a.body) == "SUBSCRIPTION_TOKEN_INVALID":
+ failure.Code = CodeKeyRejected
+ case command == CommandOpen && a.status >= 400 && a.status < 500:
+ failure.Code = CodePageUnreadable
+ }
+ return failure
+}
+
+// braveErrorCode reads Brave's machine-readable error code.
+func braveErrorCode(body []byte) string {
+ var envelope struct {
+ Error struct {
+ Code string `json:"code"`
+ } `json:"error"`
+ }
+ _ = json.Unmarshal(body, &envelope)
+ return envelope.Error.Code
+}
+
+func retryAfter(header http.Header) time.Duration {
+ value := header.Get("Retry-After")
+ if value == "" {
+ // Brave reports the reset of each window, the per-second one first.
+ value, _, _ = strings.Cut(header.Get("X-RateLimit-Reset"), ",")
+ }
+ seconds, err := strconv.Atoi(strings.TrimSpace(value))
+ if err != nil || seconds < 0 {
+ return 0
+ }
+ return time.Duration(seconds) * time.Second
+}
+
+// run calls one backend with key. It returns the quota a response reported
+// (Brave's rate-limit headers) for TeamHub to keep.
+func (p *providers) run(ctx context.Context, b Backend, key string, request Request) (Outcome, *Quota, error) {
+ if !supports(b, request) {
+ return Outcome{}, nil, &Failure{Code: CodeUnsupported, Backend: b}
+ }
+ timeout := searchTimeout
+ if request.Command == CommandOpen {
+ timeout = openTimeout
+ }
+ ctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ var (
+ outcome Outcome
+ observed *Quota
+ err error
+ )
+ switch {
+ case b == Tavily && request.Command == CommandSearch:
+ outcome, err = p.tavilySearch(ctx, key, request)
+ case b == Tavily:
+ outcome, err = p.tavilyExtract(ctx, key, request.URL)
+ case b == Brave:
+ outcome, observed, err = p.braveSearch(ctx, key, request)
+ case b == Firecrawl && request.Command == CommandSearch:
+ outcome, err = p.firecrawlSearch(ctx, key, request)
+ case b == Firecrawl:
+ outcome, err = p.firecrawlScrape(ctx, key, request.URL)
+ case b == You && request.Command == CommandSearch:
+ outcome, err = p.youSearch(ctx, key, request)
+ case b == You:
+ outcome, err = p.youExtract(ctx, key, request.URL)
+ default:
+ return Outcome{}, nil, &Failure{Code: CodeUnsupported, Backend: b}
+ }
+ if failure := (*Failure)(nil); errors.As(err, &failure) && failure.Backend == "" {
+ failure.Backend = b
+ }
+ outcome.Backend = b
+ return outcome, observed, err
+}
+
+func bearer(key string) map[string]string { return map[string]string{"Authorization": "Bearer " + key} }
+
+func (p *providers) tavilySearch(ctx context.Context, key string, request Request) (Outcome, error) {
+ body := map[string]any{"query": request.Query, "max_results": request.Limit, "search_depth": "basic", "topic": "general"}
+ if request.Recency != "" {
+ body["time_range"] = request.Recency
+ }
+ if len(request.Sites) > 0 {
+ body["include_domains"] = request.Sites
+ }
+ a, err := p.call(ctx, http.MethodPost, p.endpoints.Tavily+"/search", bearer(key), body)
+ if err != nil {
+ return Outcome{}, err
+ }
+ if err := classify(Tavily, CommandSearch, a); err != nil {
+ return Outcome{}, err
+ }
+ var decoded struct {
+ Results []struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ Content string `json:"content"`
+ PublishedDate string `json:"published_date"`
+ } `json:"results"`
+ }
+ if json.Unmarshal(a.body, &decoded) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ results := make([]Result, 0, len(decoded.Results))
+ for _, item := range decoded.Results {
+ results = appendResult(results, item.Title, item.URL, item.Content, item.PublishedDate)
+ }
+ return Outcome{Results: limitResults(results, request.Limit)}, nil
+}
+
+func (p *providers) tavilyExtract(ctx context.Context, key, pageURL string) (Outcome, error) {
+ a, err := p.call(ctx, http.MethodPost, p.endpoints.Tavily+"/extract", bearer(key),
+ map[string]any{"urls": []string{pageURL}, "format": "markdown", "extract_depth": "basic"})
+ if err != nil {
+ return Outcome{}, err
+ }
+ if err := classify(Tavily, CommandOpen, a); err != nil {
+ return Outcome{}, err
+ }
+ var decoded struct {
+ Results []struct {
+ URL string `json:"url"`
+ Title string `json:"title"`
+ RawContent string `json:"raw_content"`
+ } `json:"results"`
+ }
+ if json.Unmarshal(a.body, &decoded) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ if len(decoded.Results) == 0 {
+ return Outcome{}, &Failure{Code: CodePageUnreadable}
+ }
+ item := decoded.Results[0]
+ return pageOutcome(pageURL, item.URL, item.Title, item.RawContent)
+}
+
+func (p *providers) braveSearch(ctx context.Context, key string, request Request) (Outcome, *Quota, error) {
+ query := url.Values{"q": {request.Query}, "count": {strconv.Itoa(request.Limit)}}
+ if len(request.Sites) == 1 {
+ query.Set("q", request.Query+" site:"+request.Sites[0])
+ }
+ if freshness, ok := map[string]string{"day": "pd", "week": "pw", "month": "pm", "year": "py"}[request.Recency]; ok {
+ query.Set("freshness", freshness)
+ }
+ a, err := p.call(ctx, http.MethodGet, p.endpoints.Brave+"/res/v1/web/search?"+query.Encode(),
+ map[string]string{"X-Subscription-Token": key}, nil)
+ if err != nil {
+ return Outcome{}, nil, err
+ }
+ observed := braveQuota(a.header, time.Now())
+ if err := classify(Brave, CommandSearch, a); err != nil {
+ return Outcome{}, observed, err
+ }
+ var decoded struct {
+ Web struct {
+ Results []struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ Description string `json:"description"`
+ PageAge string `json:"page_age"`
+ Age string `json:"age"`
+ } `json:"results"`
+ } `json:"web"`
+ }
+ if json.Unmarshal(a.body, &decoded) != nil {
+ return Outcome{}, observed, &Failure{Code: CodeProviderUnavailable}
+ }
+ results := make([]Result, 0, len(decoded.Web.Results))
+ for _, item := range decoded.Web.Results {
+ published := item.PageAge
+ if published == "" {
+ published = item.Age
+ }
+ results = appendResult(results, item.Title, item.URL, item.Description, published)
+ }
+ return Outcome{Results: limitResults(results, request.Limit)}, observed, nil
+}
+
+// braveQuota reads the monthly window of Brave's rate-limit headers, which
+// list the per-second window first and the monthly one last.
+func braveQuota(header http.Header, now time.Time) *Quota {
+ last := func(name string) (float64, bool) {
+ values := strings.Split(header.Get(name), ",")
+ value, err := strconv.ParseFloat(strings.TrimSpace(values[len(values)-1]), 64)
+ return value, err == nil && value >= 0 && !math.IsInf(value, 0) && len(values) > 1
+ }
+ remaining, ok := last("X-RateLimit-Remaining")
+ if !ok {
+ return nil
+ }
+ quota := &Quota{From: "last_response", Unit: "requests", Remaining: &remaining, ObservedAt: &now}
+ if limit, ok := last("X-RateLimit-Limit"); ok {
+ quota.Limit = &limit
+ }
+ if reset, ok := last("X-RateLimit-Reset"); ok {
+ resets := now.Add(time.Duration(reset) * time.Second).Truncate(time.Second)
+ quota.ResetsAt = &resets
+ }
+ return quota
+}
+
+func (p *providers) firecrawlSearch(ctx context.Context, key string, request Request) (Outcome, error) {
+ body := map[string]any{"query": request.Query, "limit": request.Limit, "sources": []string{"web"}}
+ if tbs, ok := map[string]string{"day": "qdr:d", "week": "qdr:w", "month": "qdr:m", "year": "qdr:y"}[request.Recency]; ok {
+ body["tbs"] = tbs
+ }
+ a, err := p.call(ctx, http.MethodPost, p.endpoints.Firecrawl+"/v2/search", bearer(key), body)
+ if err != nil {
+ return Outcome{}, err
+ }
+ if err := classify(Firecrawl, CommandSearch, a); err != nil {
+ return Outcome{}, err
+ }
+ var decoded struct {
+ Data struct {
+ Web []struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ Description string `json:"description"`
+ } `json:"web"`
+ } `json:"data"`
+ }
+ if json.Unmarshal(a.body, &decoded) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ results := make([]Result, 0, len(decoded.Data.Web))
+ for _, item := range decoded.Data.Web {
+ results = appendResult(results, item.Title, item.URL, item.Description, "")
+ }
+ return Outcome{Results: limitResults(results, request.Limit)}, nil
+}
+
+func (p *providers) firecrawlScrape(ctx context.Context, key, pageURL string) (Outcome, error) {
+ a, err := p.call(ctx, http.MethodPost, p.endpoints.Firecrawl+"/v2/scrape", bearer(key),
+ map[string]any{"url": pageURL, "formats": []string{"markdown"}, "onlyMainContent": true})
+ if err != nil {
+ return Outcome{}, err
+ }
+ if err := classify(Firecrawl, CommandOpen, a); err != nil {
+ return Outcome{}, err
+ }
+ var decoded struct {
+ Data struct {
+ Markdown string `json:"markdown"`
+ Metadata struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ StatusCode int `json:"statusCode"`
+ } `json:"metadata"`
+ } `json:"data"`
+ }
+ if json.Unmarshal(a.body, &decoded) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ if decoded.Data.Metadata.StatusCode >= 400 {
+ return Outcome{}, &Failure{Code: CodePageUnreadable}
+ }
+ return pageOutcome(pageURL, decoded.Data.Metadata.URL, decoded.Data.Metadata.Title, decoded.Data.Markdown)
+}
+
+func youHeader(key string) map[string]string { return map[string]string{"X-API-Key": key} }
+
+// youWebResults is the web results of You.com's search, from the API and from
+// the keyless MCP tool alike.
+type youWebResults struct {
+ Results struct {
+ Web []struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ Description string `json:"description"`
+ Snippets []string `json:"snippets"`
+ PageAge string `json:"page_age"`
+ } `json:"web"`
+ } `json:"results"`
+}
+
+func (r youWebResults) outcome(limit int) Outcome {
+ results := make([]Result, 0, len(r.Results.Web))
+ for _, item := range r.Results.Web {
+ snippet := item.Description
+ if snippet == "" && len(item.Snippets) > 0 {
+ snippet = item.Snippets[0]
+ }
+ results = appendResult(results, item.Title, item.URL, snippet, item.PageAge)
+ }
+ return Outcome{Results: limitResults(results, limit)}
+}
+
+func youSearchBody(request Request) map[string]any {
+ body := map[string]any{"query": request.Query, "count": request.Limit}
+ if request.Recency != "" {
+ body["freshness"] = request.Recency
+ }
+ return body
+}
+
+func (p *providers) youSearch(ctx context.Context, key string, request Request) (Outcome, error) {
+ a, err := p.call(ctx, http.MethodPost, p.endpoints.YouIndex+"/v1/search", youHeader(key), youSearchBody(request))
+ if err != nil {
+ return Outcome{}, err
+ }
+ if err := classify(You, CommandSearch, a); err != nil {
+ return Outcome{}, err
+ }
+ var decoded youWebResults
+ if json.Unmarshal(a.body, &decoded) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ return decoded.outcome(request.Limit), nil
+}
+
+// youPage is one page of You.com's Extract API, which nests the Markdown
+// under contents.full_page.
+type youPage struct {
+ URL string `json:"url"`
+ Title string `json:"title"`
+ Markdown string `json:"markdown"`
+ Contents struct {
+ FullPage struct {
+ Markdown string `json:"markdown"`
+ } `json:"full_page"`
+ } `json:"contents"`
+}
+
+func (page youPage) markdown() string {
+ if page.Contents.FullPage.Markdown != "" {
+ return page.Contents.FullPage.Markdown
+ }
+ return page.Markdown
+}
+
+func (p *providers) youExtract(ctx context.Context, key, pageURL string) (Outcome, error) {
+ a, err := p.call(ctx, http.MethodPost, p.endpoints.YouIndex+"/v1/extract", youHeader(key),
+ map[string]any{"url": pageURL, "full_page": map[string]any{"extraction_formats": []string{"markdown"}}})
+ if err != nil {
+ return Outcome{}, err
+ }
+ if err := classify(You, CommandOpen, a); err != nil {
+ return Outcome{}, err
+ }
+ var page youPage
+ if json.Unmarshal(a.body, &page) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable}
+ }
+ return pageOutcome(pageURL, page.URL, page.Title, page.markdown())
+}
+
+// check asks the provider's official usage endpoint whether it accepts key,
+// and returns the quota it reports.
+func (p *providers) check(ctx context.Context, b Backend, key string) (Quota, error) {
+ ctx, cancel := context.WithTimeout(ctx, checkTimeout)
+ defer cancel()
+ var (
+ endpoint string
+ header map[string]string
+ )
+ switch b {
+ case Tavily:
+ endpoint, header = p.endpoints.Tavily+"/usage", bearer(key)
+ case Firecrawl:
+ endpoint, header = p.endpoints.Firecrawl+"/v2/team/credit-usage", bearer(key)
+ case You:
+ endpoint, header = p.endpoints.YouAPI+"/v1/billing/account_balance", youHeader(key)
+ default:
+ return Quota{}, ErrInvalid
+ }
+ a, err := p.call(ctx, http.MethodGet, endpoint, header, nil)
+ if err != nil {
+ return Quota{}, ErrProviderUnavailable
+ }
+ switch {
+ case a.status == http.StatusUnauthorized || a.status == http.StatusForbidden:
+ return Quota{}, ErrKeyRejected
+ case a.status < 200 || a.status >= 300:
+ return Quota{}, ErrProviderUnavailable
+ }
+ now := time.Now()
+ return parseQuota(b, a.body, now), nil
+}
+
+// quota reads a saved key's live quota; a failure is reported in the quota.
+func (p *providers) quota(ctx context.Context, b Backend, key string) Quota {
+ quota, err := p.check(ctx, b, key)
+ switch {
+ case errors.Is(err, ErrKeyRejected):
+ return Quota{From: "unavailable", Reason: "key_rejected"}
+ case err != nil:
+ return Quota{From: "unavailable", Reason: "provider_unavailable"}
+ }
+ return quota
+}
+
+// parseQuota reads each provider's usage answer. An answer without the
+// expected numbers still proves the key; its quota is not_reported.
+func parseQuota(b Backend, body []byte, now time.Time) Quota {
+ quota := Quota{From: "provider", ObservedAt: &now}
+ unreported := Quota{From: "unavailable", Reason: "not_reported"}
+ switch b {
+ case Tavily:
+ var decoded struct {
+ Key struct {
+ Usage *float64 `json:"usage"`
+ Limit *float64 `json:"limit"`
+ } `json:"key"`
+ Account struct {
+ CurrentPlan string `json:"current_plan"`
+ PlanUsage *float64 `json:"plan_usage"`
+ PlanLimit *float64 `json:"plan_limit"`
+ } `json:"account"`
+ }
+ if json.Unmarshal(body, &decoded) != nil || decoded.Account.PlanLimit == nil || decoded.Account.PlanUsage == nil {
+ return unreported
+ }
+ remaining, limit := math.Max(0, *decoded.Account.PlanLimit-*decoded.Account.PlanUsage), *decoded.Account.PlanLimit
+ // A per-key cap below the plan's remainder binds first.
+ if decoded.Key.Limit != nil && decoded.Key.Usage != nil && *decoded.Key.Limit-*decoded.Key.Usage < remaining {
+ remaining, limit = math.Max(0, *decoded.Key.Limit-*decoded.Key.Usage), *decoded.Key.Limit
+ }
+ quota.Remaining, quota.Limit, quota.Unit = &remaining, &limit, "credits"
+ quota.Plan = truncateRunes(decoded.Account.CurrentPlan, 200)
+ case Firecrawl:
+ var decoded struct {
+ Data struct {
+ RemainingCredits *float64 `json:"remainingCredits"`
+ PlanCredits *float64 `json:"planCredits"`
+ BillingPeriodEnd string `json:"billingPeriodEnd"`
+ } `json:"data"`
+ }
+ if json.Unmarshal(body, &decoded) != nil || decoded.Data.RemainingCredits == nil {
+ return unreported
+ }
+ remaining := math.Max(0, *decoded.Data.RemainingCredits)
+ quota.Remaining, quota.Unit = &remaining, "credits"
+ if decoded.Data.PlanCredits != nil && *decoded.Data.PlanCredits > 0 {
+ quota.Limit = decoded.Data.PlanCredits
+ }
+ if resets, err := time.Parse(time.RFC3339, decoded.Data.BillingPeriodEnd); err == nil {
+ quota.ResetsAt = &resets
+ }
+ case You:
+ var decoded struct {
+ Data struct {
+ Attributes struct {
+ Balance *float64 `json:"balance"`
+ } `json:"attributes"`
+ } `json:"data"`
+ }
+ if json.Unmarshal(body, &decoded) != nil || decoded.Data.Attributes.Balance == nil {
+ return unreported
+ }
+ // You.com reports the balance in cents.
+ remaining := math.Max(0, *decoded.Data.Attributes.Balance/100)
+ quota.Remaining, quota.Unit = &remaining, "usd"
+ default:
+ return unreported
+ }
+ return quota
+}
+
+var (
+ htmlTag = regexp.MustCompile(`<[^>]*>`)
+ whitespace = regexp.MustCompile(`\s+`)
+)
+
+// plainText strips the markup some providers put in titles and snippets.
+func plainText(value string, limit int) string {
+ value = html.UnescapeString(htmlTag.ReplaceAllString(value, ""))
+ return truncateRunes(strings.TrimSpace(whitespace.ReplaceAllString(value, " ")), limit)
+}
+
+func truncateRunes(value string, limit int) string {
+ if utf8.RuneCountInString(value) <= limit {
+ return value
+ }
+ return string([]rune(value)[:limit])
+}
+
+// appendResult keeps a result with a web URL, bounded as the contract says.
+func appendResult(results []Result, title, link, snippet, published string) []Result {
+ link = strings.TrimSpace(link)
+ if !webURL(link) {
+ return results
+ }
+ return append(results, Result{
+ Title: plainText(title, maxTitleRunes), URL: link, Snippet: plainText(snippet, maxSnippetRunes),
+ PublishedAt: truncateRunes(strings.TrimSpace(published), maxDateRunes),
+ })
+}
+
+func limitResults(results []Result, limit int) []Result {
+ if len(results) > limit {
+ return results[:limit]
+ }
+ return results
+}
+
+// pageOutcome cuts a page at MaxMarkdown characters; an empty page is
+// unreadable.
+func pageOutcome(requested, final, title, markdown string) (Outcome, error) {
+ markdown = strings.TrimSpace(markdown)
+ if markdown == "" {
+ return Outcome{}, &Failure{Code: CodePageUnreadable}
+ }
+ if !webURL(final) {
+ final = requested
+ }
+ page := &Page{URL: final, Title: plainText(title, maxTitleRunes), Markdown: markdown}
+ if utf8.RuneCountInString(markdown) > MaxMarkdown {
+ page.Markdown, page.Truncated = string([]rune(markdown)[:MaxMarkdown]), true
+ }
+ return Outcome{Page: page}, nil
+}
+
+// webURL accepts an absolute http or https URL within the contract's bound.
+func webURL(value string) bool {
+ if value == "" || len(value) > MaxURLBytes {
+ return false
+ }
+ parsed, err := url.Parse(value)
+ return err == nil && (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" && parsed.User == nil
+}
+
+var hostPattern = regexp.MustCompile(`^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$`)
+
+// validHost accepts a lowercase hostname with at least one dot.
+func validHost(value string) bool {
+ return len(value) >= 3 && len(value) <= 253 && hostPattern.MatchString(value)
+}
diff --git a/apps/teamhub/internal/websearch/websearch.go b/apps/teamhub/internal/websearch/websearch.go
new file mode 100644
index 00000000..c7bb63ea
--- /dev/null
+++ b/apps/teamhub/internal/websearch/websearch.go
@@ -0,0 +1,781 @@
+// Package websearch runs the Agents' web searches and page reads through
+// provider APIs, with API keys saved in the product and sealed with the
+// secret box. A key serves the whole deployment and is read from the
+// database at each call, so a save applies on every replica at once. TeamHub
+// calls only the providers' fixed API hosts: it never requests a page URL
+// itself, and the direct backend is fetched by the Agent CLI.
+package websearch
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "log/slog"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+ "unicode"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/secretbox"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// Backend names one web search backend; the values are the contract's.
+type Backend string
+
+// The backends. Direct opens pages on the Agent's computer and never reaches
+// TeamHub's calls.
+const (
+ Tavily Backend = "tavily"
+ Brave Backend = "brave"
+ Firecrawl Backend = "firecrawl"
+ You Backend = "you"
+ Direct Backend = "direct"
+)
+
+// keyOrder is TeamHub's default order: a search without a backend uses the
+// first one with a usable key, then You.com's keyless trial.
+var keyOrder = []Backend{Tavily, Brave, Firecrawl, You}
+
+// KeyBackend reports whether b takes an API key saved in the product.
+func KeyBackend(b Backend) bool { return slices.Contains(keyOrder, b) }
+
+// DisplayName is the provider's name as people know it.
+func DisplayName(b Backend) string { return definitions[b].name }
+
+// The commands and filters a backend may support.
+const (
+ CommandSearch = "search"
+ CommandOpen = "open"
+ FilterRecency = "recency"
+ FilterSite = "site"
+)
+
+// The tiers a backend runs at now.
+const (
+ TierKey = "key"
+ TierFreeTrial = "free_trial"
+ TierNone = "none"
+)
+
+// Bounds of the commands; the contract states the same.
+const (
+ MaxKeyBytes = 512
+ DefaultLimit = 10
+ MaxLimit = 20
+ MaxQueryRunes = 400
+ MaxURLBytes = 2048
+ MaxMarkdown = 20000
+ maxTitleRunes = 300
+ maxSnippetRunes = 500
+ maxDateRunes = 64
+ // quotaTimeout bounds the live quota reads of one listing; a provider
+ // slower than that reports provider_unavailable.
+ quotaTimeout = 5 * time.Second
+)
+
+type definition struct {
+ name string
+ commands []string
+ filters []string
+ maxLimit int
+ maxSites int
+ keyless bool
+ officialCheck bool
+ freeTier string
+ keyURL string
+}
+
+// definitions is the static text and capability of each backend. Firecrawl
+// and You.com take no site filter because their APIs document none.
+var definitions = map[Backend]definition{
+ Tavily: {name: "Tavily", commands: []string{CommandSearch, CommandOpen}, filters: []string{FilterRecency, FilterSite},
+ maxLimit: 20, maxSites: 10, officialCheck: true,
+ freeTier: "1,000 free API credits every month.", keyURL: "https://app.tavily.com/home"},
+ Brave: {name: "Brave Search", commands: []string{CommandSearch}, filters: []string{FilterRecency, FilterSite},
+ maxLimit: 20, maxSites: 1,
+ freeTier: "$5 of free credit every month; sign-up needs a credit card.", keyURL: "https://api-dashboard.search.brave.com/app/keys"},
+ Firecrawl: {name: "Firecrawl", commands: []string{CommandSearch, CommandOpen}, filters: []string{FilterRecency},
+ maxLimit: 20, officialCheck: true,
+ freeTier: "1,000 free credits every month.", keyURL: "https://www.firecrawl.dev/app/api-keys"},
+ You: {name: "You.com", commands: []string{CommandSearch, CommandOpen}, filters: []string{FilterRecency},
+ maxLimit: 20, keyless: true, officialCheck: true,
+ freeTier: "Works without a key as a limited free trial; a key gives full quality and higher limits.", keyURL: "https://you.com/platform"},
+ Direct: {name: "Direct", commands: []string{CommandOpen}, keyless: true},
+}
+
+// freeTrialText describes You.com without a key, where TeamHub counts nothing.
+const freeTrialText = "Free trial without a key: limited searches with lower quality results."
+
+// Save and settings refusals; the handlers map each to an error code.
+var (
+ ErrInvalid = errors.New("the web search request is invalid")
+ ErrStorageMissing = errors.New("the deployment has no secret encryption key")
+ ErrKeyRejected = errors.New("the provider rejected the API key")
+ ErrProviderUnavailable = errors.New("the provider could not be reached")
+ ErrNotReady = errors.New("the backend has no usable key")
+)
+
+// Code classifies a failed provider call.
+type Code string
+
+// The failures of a call. The key failures ask the Human for a key; the
+// others go back to the Agent.
+const (
+ CodeKeyRequired Code = "key_required"
+ CodeKeyRejected Code = "key_rejected"
+ CodeFreeLimit Code = "free_limit"
+ CodeQuotaExhausted Code = "quota_exhausted"
+ CodeRateLimited Code = "rate_limited"
+ CodeUnsupported Code = "unsupported"
+ CodePageUnreadable Code = "page_unreadable"
+ CodeProviderUnavailable Code = "provider_unavailable"
+)
+
+// Failure is a call that did not return results. Errors never carry a key,
+// a query, a URL or provider text.
+type Failure struct {
+ Code Code
+ // Backend failed, or for a key failure is the backend the card shows.
+ Backend Backend
+ // Suggested marks a key failure whose command named no backend, so
+ // TeamHub picked the first backend that still needs a key.
+ Suggested bool
+ // RetryAfter is the provider's wait for a rate limit, when it said.
+ RetryAfter time.Duration
+ // Ready lists the other backends that could run the command now, for a
+ // quota or rate limit.
+ Ready []Backend
+ // proved reports that the provider identified the account while refusing
+ // the call, as a quota or rate limit does.
+ proved bool
+}
+
+func (f *Failure) Error() string {
+ return fmt.Sprintf("web search %s failed: %s", f.Backend, f.Code)
+}
+
+// KeyFailure reports whether the failure asks the Human for a key.
+func (f *Failure) KeyFailure() bool {
+ return f.Code == CodeKeyRequired || f.Code == CodeKeyRejected || f.Code == CodeFreeLimit
+}
+
+// Request is one search or page open.
+type Request struct {
+ Command string `json:"command"`
+ Backend Backend `json:"backend,omitempty"`
+ Query string `json:"query,omitempty"`
+ Limit int `json:"limit,omitempty"`
+ Recency string `json:"recency,omitempty"`
+ Sites []string `json:"sites,omitempty"`
+ URL string `json:"url,omitempty"`
+}
+
+// Result is one search result.
+type Result struct {
+ Title string `json:"title"`
+ URL string `json:"url"`
+ Snippet string `json:"snippet"`
+ PublishedAt string `json:"published_at,omitempty"`
+}
+
+// Page is one opened page, cut at MaxMarkdown characters.
+type Page struct {
+ URL string `json:"url"`
+ Title string `json:"title,omitempty"`
+ Markdown string `json:"markdown"`
+ Truncated bool `json:"truncated"`
+}
+
+// Outcome is what a call returned: Results for a search, Page for an open.
+type Outcome struct {
+ Backend Backend
+ Results []Result
+ Page *Page
+}
+
+// Quota is what is left on a backend's account.
+type Quota struct {
+ From string `json:"from"`
+ Remaining *float64 `json:"remaining,omitempty"`
+ Limit *float64 `json:"limit,omitempty"`
+ Unit string `json:"unit,omitempty"`
+ Plan string `json:"plan,omitempty"`
+ ResetsAt *time.Time `json:"resets_at,omitempty"`
+ ObservedAt *time.Time `json:"observed_at,omitempty"`
+ Reason string `json:"reason,omitempty"`
+}
+
+// BackendView is one backend as the contract's WebSearchBackend.
+type BackendView struct {
+ ID Backend `json:"id"`
+ Name string `json:"name"`
+ Tier string `json:"tier"`
+ TierText string `json:"tier_text,omitempty"`
+ Commands []string `json:"commands"`
+ Filters []string `json:"filters"`
+ MaxLimit int `json:"max_limit"`
+ MaxSites int `json:"max_sites"`
+ Keyless bool `json:"keyless"`
+ OfficialKeyCheck bool `json:"official_key_check"`
+ FreeTier string `json:"free_tier,omitempty"`
+ KeyURL string `json:"key_url,omitempty"`
+ Status string `json:"status"`
+ KeyState string `json:"key_state"`
+ Quota Quota `json:"quota"`
+}
+
+// List is every backend as the contract's WebSearchBackendList.
+type List struct {
+ DefaultSearch Backend `json:"default_search"`
+ ChosenDefault Backend `json:"chosen_default_search,omitempty"`
+ DefaultOpen Backend `json:"default_open"`
+ CanSaveKeys bool `json:"can_save_keys"`
+ Backends []BackendView `json:"backends"`
+}
+
+// Default is the contract's WebSearchDefault.
+type Default struct {
+ DefaultSearch Backend `json:"default_search"`
+ ChosenDefault Backend `json:"chosen_default_search,omitempty"`
+}
+
+// Store is the key and settings tables; *store.Queries implements it.
+type Store interface {
+ ListWebSearchKeys(ctx context.Context) ([]store.ListWebSearchKeysRow, error)
+ UpsertWebSearchKey(ctx context.Context, arg store.UpsertWebSearchKeyParams) error
+ DeleteWebSearchKey(ctx context.Context, backend string) error
+ MarkWebSearchKeyRejected(ctx context.Context, arg store.MarkWebSearchKeyRejectedParams) error
+ RecordWebSearchKeyAnswer(ctx context.Context, arg store.RecordWebSearchKeyAnswerParams) error
+ GetWebSearchDefaultBackend(ctx context.Context) (string, error)
+ SetWebSearchDefaultBackend(ctx context.Context, defaultBackend pgtype.Text) error
+ ClearWebSearchDefaultBackend(ctx context.Context, backend string) error
+}
+
+// Service runs searches and manages the saved keys.
+type Service struct {
+ store Store
+ box *secretbox.Box
+ providers *providers
+ logger *slog.Logger
+
+ mu sync.Mutex
+ // unreadable is the digest of the last row per backend that would not
+ // open, so its warning is logged once.
+ unreadable map[Backend]string
+}
+
+// New returns a Service. A nil box means keys can be neither saved nor read;
+// zero Endpoints fields use the providers' APIs. A nil logger logs to
+// slog.Default.
+func New(keys Store, box *secretbox.Box, endpoints Endpoints, logger *slog.Logger) *Service {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &Service{store: keys, box: box, providers: newProviders(endpoints), logger: logger, unreadable: map[Backend]string{}}
+}
+
+// savedKey is one stored key, opened.
+type savedKey struct {
+ key string
+ sealed []byte
+ state string
+ row store.ListWebSearchKeysRow
+ unusable bool
+}
+
+type keyring map[Backend]savedKey
+
+// usable reports whether b has a saved key the provider has not refused.
+func (k keyring) usable(b Backend) bool {
+ saved, ok := k[b]
+ return ok && !saved.unusable && saved.state != "rejected"
+}
+
+// status is the contract's backend status.
+func (k keyring) status(b Backend) string {
+ saved, ok := k[b]
+ switch {
+ case b == Direct, k.usable(b):
+ return "ready"
+ case ok && !saved.unusable && saved.state == "rejected":
+ return "key_rejected"
+ case b == You:
+ return "ready"
+ default:
+ return "key_required"
+ }
+}
+
+func (s *Service) keys(ctx context.Context) (keyring, error) {
+ rows, err := s.store.ListWebSearchKeys(ctx)
+ if err != nil {
+ return nil, err
+ }
+ ring := keyring{}
+ for _, row := range rows {
+ b := Backend(row.Backend)
+ saved := savedKey{sealed: row.ApiKeyCiphertext, state: row.State, row: row}
+ opened, openErr := []byte(nil), ErrStorageMissing
+ if s.box != nil {
+ opened, openErr = s.box.Open(row.ApiKeyCiphertext)
+ }
+ if openErr != nil {
+ // A key sealed under another encryption key is unusable; the
+ // backend counts as having none, so a new save replaces it.
+ saved.unusable = true
+ s.warnUnreadable(b, row.ApiKeyCiphertext)
+ } else {
+ saved.key = string(opened)
+ }
+ ring[b] = saved
+ }
+ return ring, nil
+}
+
+func (s *Service) warnUnreadable(b Backend, sealed []byte) {
+ if s.box == nil {
+ return
+ }
+ digest := string(sealed)
+ s.mu.Lock()
+ logged := s.unreadable[b] == digest
+ s.unreadable[b] = digest
+ s.mu.Unlock()
+ if !logged {
+ s.logger.Warn("web_search.key_unreadable", "backend", string(b))
+ }
+}
+
+func (s *Service) chosenDefault(ctx context.Context) (Backend, error) {
+ chosen, err := s.store.GetWebSearchDefaultBackend(ctx)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return "", nil
+ }
+ return Backend(chosen), err
+}
+
+// defaultSearch is the backend a search without one uses now: the chosen
+// default even when its key stopped working, so its failure asks for that
+// key instead of silently moving on; else the first backend with a usable
+// key, else You.com's keyless trial.
+func defaultSearch(ring keyring, chosen Backend) Backend {
+ if chosen != "" {
+ return chosen
+ }
+ for _, b := range keyOrder {
+ if ring.usable(b) {
+ return b
+ }
+ }
+ return You
+}
+
+// List returns every backend with its live quota.
+func (s *Service) List(ctx context.Context) (List, error) {
+ ring, err := s.keys(ctx)
+ if err != nil {
+ return List{}, err
+ }
+ chosen, err := s.chosenDefault(ctx)
+ if err != nil {
+ return List{}, err
+ }
+ order := append(slices.Clone(keyOrder), Direct)
+ views := make([]BackendView, len(order))
+ var wg sync.WaitGroup
+ quotaCtx, cancel := context.WithTimeout(ctx, quotaTimeout)
+ defer cancel()
+ for i, b := range order {
+ views[i] = s.view(ring, b)
+ if !ring.usable(b) || b == Brave {
+ continue
+ }
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ views[i].Quota = s.providers.quota(quotaCtx, b, ring[b].key)
+ }()
+ }
+ wg.Wait()
+ list := List{DefaultSearch: defaultSearch(ring, chosen), DefaultOpen: Direct, CanSaveKeys: s.box != nil, Backends: views}
+ if chosen != "" {
+ list.ChosenDefault = chosen
+ }
+ return list, nil
+}
+
+// view is a backend's static text and state; quota is what needs no call.
+func (s *Service) view(ring keyring, b Backend) BackendView {
+ def := definitions[b]
+ view := BackendView{
+ ID: b, Name: def.name, Tier: TierKey, Commands: def.commands, Filters: def.filters,
+ MaxLimit: def.maxLimit, MaxSites: def.maxSites, Keyless: def.keyless, OfficialKeyCheck: def.officialCheck,
+ FreeTier: def.freeTier, KeyURL: def.keyURL, Status: ring.status(b), KeyState: "none",
+ Quota: Quota{From: "unavailable", Reason: "no_key"},
+ }
+ if view.Filters == nil {
+ view.Filters = []string{}
+ }
+ if saved, ok := ring[b]; ok && !saved.unusable {
+ view.KeyState = saved.state
+ }
+ switch {
+ case b == Direct:
+ view.Tier, view.Quota.Reason = TierNone, "not_reported"
+ case b == You && !ring.usable(You) && view.Status == "ready":
+ view.Tier, view.TierText, view.Quota.Reason = TierFreeTrial, freeTrialText, "not_reported"
+ case view.KeyState == "rejected":
+ view.Quota.Reason = "key_rejected"
+ case b == Brave && ring.usable(Brave):
+ view.Quota = braveStoredQuota(ring[Brave].row)
+ }
+ return view
+}
+
+// braveStoredQuota reads the rate-limit headers of Brave's last answer.
+func braveStoredQuota(row store.ListWebSearchKeysRow) Quota {
+ if !row.QuotaObservedAt.Valid {
+ return Quota{From: "unavailable", Reason: "not_observed"}
+ }
+ observed := row.QuotaObservedAt.Time
+ quota := Quota{From: "last_response", Unit: "requests", ObservedAt: &observed}
+ if row.QuotaRemaining.Valid {
+ quota.Remaining = &row.QuotaRemaining.Float64
+ }
+ if row.QuotaLimit.Valid {
+ quota.Limit = &row.QuotaLimit.Float64
+ }
+ if row.QuotaResetsAt.Valid {
+ resets := row.QuotaResetsAt.Time
+ quota.ResetsAt = &resets
+ }
+ return quota
+}
+
+// Backend returns one backend with its live quota.
+func (s *Service) Backend(ctx context.Context, b Backend) (BackendView, error) {
+ if _, ok := definitions[b]; !ok {
+ return BackendView{}, ErrInvalid
+ }
+ list, err := s.List(ctx)
+ if err != nil {
+ return BackendView{}, err
+ }
+ for _, view := range list.Backends {
+ if view.ID == b {
+ return view, nil
+ }
+ }
+ return BackendView{}, ErrInvalid
+}
+
+func validKey(key string) (string, bool) {
+ key = strings.TrimSpace(key)
+ return key, key != "" && len(key) <= MaxKeyBytes && strings.IndexFunc(key, unicode.IsSpace) < 0 &&
+ strings.IndexFunc(key, unicode.IsControl) < 0
+}
+
+// SaveKey checks key with the provider's official endpoint when it has one,
+// then seals and stores it; a Brave key is stored unverified and proven by
+// its first call. It returns the backend after saving.
+func (s *Service) SaveKey(ctx context.Context, b Backend, key string) (BackendView, error) {
+ key, ok := validKey(key)
+ switch {
+ case !KeyBackend(b) || !ok:
+ return BackendView{}, ErrInvalid
+ case s.box == nil:
+ return BackendView{}, ErrStorageMissing
+ }
+ state := "unverified"
+ var quota *Quota
+ if definitions[b].officialCheck {
+ checked, err := s.providers.check(ctx, b, key)
+ if err != nil {
+ return BackendView{}, err
+ }
+ state, quota = "verified", &checked
+ }
+ if err := s.saveSealed(ctx, b, key, state); err != nil {
+ return BackendView{}, err
+ }
+ ring, err := s.keys(ctx)
+ if err != nil {
+ return BackendView{}, err
+ }
+ view := s.view(ring, b)
+ if quota != nil {
+ view.Quota = *quota
+ }
+ return view, nil
+}
+
+// Replay is a stored request run with a candidate key before it was saved.
+type Replay struct {
+ View BackendView
+ Outcome Outcome
+ // Failure is how the call failed, other than refusing the key; the key
+ // was saved anyway.
+ Failure *Failure
+}
+
+// SaveReplayed runs request against b with the candidate key and saves the
+// key unless the provider refused it (ErrKeyRejected). A call that answered,
+// or a quota or rate limit that identified the account, saves the key
+// verified; any other failure saves it unverified.
+func (s *Service) SaveReplayed(ctx context.Context, b Backend, key string, request Request) (Replay, error) {
+ key, ok := validKey(key)
+ switch {
+ case !KeyBackend(b) || !ok:
+ return Replay{}, ErrInvalid
+ case s.box == nil:
+ return Replay{}, ErrStorageMissing
+ }
+ request.Backend = b
+ outcome, observed, err := s.providers.run(ctx, b, key, request)
+ var failure *Failure
+ state := "verified"
+ if err != nil {
+ if !errors.As(err, &failure) {
+ return Replay{}, err
+ }
+ if failure.Code == CodeKeyRejected {
+ return Replay{}, ErrKeyRejected
+ }
+ if !failure.proved {
+ state = "unverified"
+ }
+ }
+ if err := s.saveSealed(ctx, b, key, state); err != nil {
+ return Replay{}, err
+ }
+ ring, err := s.keys(ctx)
+ if err != nil {
+ return Replay{}, err
+ }
+ if observed != nil && ring.usable(b) {
+ s.recordAnswer(ctx, ring[b], b, observed)
+ if ring, err = s.keys(ctx); err != nil {
+ return Replay{}, err
+ }
+ }
+ return Replay{View: s.view(ring, b), Outcome: outcome, Failure: failure}, nil
+}
+
+func (s *Service) saveSealed(ctx context.Context, b Backend, key, state string) error {
+ sealed, err := s.box.Seal([]byte(key))
+ if err != nil {
+ return err
+ }
+ return s.store.UpsertWebSearchKey(ctx, store.UpsertWebSearchKeyParams{Backend: string(b), ApiKeyCiphertext: sealed, State: state})
+}
+
+// RemoveKey deletes b's key and drops b as the chosen default. Removing a key
+// that is not saved succeeds.
+func (s *Service) RemoveKey(ctx context.Context, b Backend) error {
+ if !KeyBackend(b) {
+ return ErrInvalid
+ }
+ if err := s.store.DeleteWebSearchKey(ctx, string(b)); err != nil {
+ return err
+ }
+ return s.store.ClearWebSearchDefaultBackend(ctx, string(b))
+}
+
+// SetDefault makes b the backend a search without one uses; b must be ready.
+func (s *Service) SetDefault(ctx context.Context, b Backend) (Default, error) {
+ if !KeyBackend(b) {
+ return Default{}, ErrInvalid
+ }
+ ring, err := s.keys(ctx)
+ if err != nil {
+ return Default{}, err
+ }
+ if ring.status(b) != "ready" {
+ return Default{}, ErrNotReady
+ }
+ if err := s.store.SetWebSearchDefaultBackend(ctx, pgtype.Text{String: string(b), Valid: true}); err != nil {
+ return Default{}, err
+ }
+ return Default{DefaultSearch: defaultSearch(ring, b), ChosenDefault: b}, nil
+}
+
+// ClearDefault returns searches without a backend to TeamHub's order.
+func (s *Service) ClearDefault(ctx context.Context) (Default, error) {
+ if err := s.store.SetWebSearchDefaultBackend(ctx, pgtype.Text{}); err != nil {
+ return Default{}, err
+ }
+ ring, err := s.keys(ctx)
+ if err != nil {
+ return Default{}, err
+ }
+ return Default{DefaultSearch: defaultSearch(ring, "")}, nil
+}
+
+// Normalize checks a request's shape and applies the default limit. It does
+// not check the backend's capabilities, which depend on the backend that
+// finally runs it.
+func Normalize(request Request) (Request, error) {
+ request.Query = strings.TrimSpace(request.Query)
+ request.URL = strings.TrimSpace(request.URL)
+ switch request.Command {
+ case CommandSearch:
+ if request.Query == "" || len([]rune(request.Query)) > MaxQueryRunes || request.URL != "" ||
+ request.Backend != "" && !KeyBackend(request.Backend) || request.Limit < 0 || request.Limit > MaxLimit ||
+ len(request.Sites) > 10 {
+ return Request{}, ErrInvalid
+ }
+ if request.Limit == 0 {
+ request.Limit = DefaultLimit
+ }
+ switch request.Recency {
+ case "", "day", "week", "month", "year":
+ default:
+ return Request{}, ErrInvalid
+ }
+ for i, site := range request.Sites {
+ site = strings.ToLower(strings.TrimSpace(site))
+ if !validHost(site) || slices.Contains(request.Sites[:i], site) {
+ return Request{}, ErrInvalid
+ }
+ request.Sites[i] = site
+ }
+ case CommandOpen:
+ if request.Query != "" || request.Limit != 0 || request.Recency != "" || len(request.Sites) > 0 ||
+ !webURL(request.URL) || !KeyBackend(request.Backend) || request.Backend == Brave {
+ return Request{}, ErrInvalid
+ }
+ default:
+ return Request{}, ErrInvalid
+ }
+ return request, nil
+}
+
+// supports refuses, before any call, a request the backend cannot honor.
+func supports(b Backend, request Request) bool {
+ def := definitions[b]
+ if !slices.Contains(def.commands, request.Command) {
+ return false
+ }
+ if request.Command != CommandSearch {
+ return true
+ }
+ return request.Limit <= def.maxLimit &&
+ (request.Recency == "" || slices.Contains(def.filters, FilterRecency)) &&
+ (len(request.Sites) == 0 || slices.Contains(def.filters, FilterSite) && len(request.Sites) <= def.maxSites)
+}
+
+// Run runs a normalized request with the saved keys. Without a backend a
+// search uses the default a Human chose as if the command had named it, else
+// TeamHub's order; there is no fallback to another backend after a failure.
+// A key failure names the backend the card should show.
+func (s *Service) Run(ctx context.Context, request Request) (Outcome, error) {
+ ring, err := s.keys(ctx)
+ if err != nil {
+ return Outcome{}, err
+ }
+ b, suggested := request.Backend, false
+ if b == "" {
+ chosen, err := s.chosenDefault(ctx)
+ if err != nil {
+ return Outcome{}, err
+ }
+ b, suggested = defaultSearch(ring, chosen), chosen == ""
+ }
+ if !supports(b, request) {
+ return Outcome{}, &Failure{Code: CodeUnsupported, Backend: b}
+ }
+ keyless := b == You && !ring.usable(You) && (suggested || ring.status(You) == "ready")
+ if !keyless && !ring.usable(b) {
+ code := CodeKeyRequired
+ if ring.status(b) == "key_rejected" {
+ code = CodeKeyRejected
+ }
+ return Outcome{}, &Failure{Code: code, Backend: b, Suggested: suggested}
+ }
+ var outcome Outcome
+ var observed *Quota
+ if keyless {
+ outcome, err = s.providers.runKeyless(ctx, request)
+ } else {
+ outcome, observed, err = s.providers.run(ctx, b, ring[b].key, request)
+ }
+ var failure *Failure
+ switch {
+ case err == nil:
+ if !keyless {
+ s.recordAnswer(ctx, ring[b], b, observed)
+ }
+ outcome.Backend = b
+ return outcome, nil
+ case !errors.As(err, &failure):
+ return Outcome{}, err
+ case failure.Code == CodeKeyRejected && !keyless:
+ failure.Suggested = suggested
+ if markErr := s.store.MarkWebSearchKeyRejected(ctx, store.MarkWebSearchKeyRejectedParams{
+ Backend: string(b), ApiKeyCiphertext: ring[b].sealed,
+ }); markErr != nil {
+ return Outcome{}, markErr
+ }
+ case failure.Code == CodeFreeLimit && suggested:
+ // The command named no backend: the card suggests the first
+ // backend in TeamHub's order that still needs a key.
+ failure.Backend, failure.Suggested = firstNeedingKey(ring), true
+ return Outcome{}, failure
+ case failure.Code == CodeQuotaExhausted || failure.Code == CodeRateLimited:
+ if !keyless {
+ s.recordAnswer(ctx, ring[b], b, observed)
+ }
+ failure.Ready = readyOthers(ring, b, request.Command)
+ }
+ failure.Backend = b
+ return Outcome{}, failure
+}
+
+func firstNeedingKey(ring keyring) Backend {
+ for _, b := range keyOrder {
+ if !ring.usable(b) {
+ return b
+ }
+ }
+ return Tavily
+}
+
+// readyOthers lists the backends other than failed that could run command
+// now, in TeamHub's order.
+func readyOthers(ring keyring, failed Backend, command string) []Backend {
+ ready := []Backend{}
+ for _, b := range keyOrder {
+ if b != failed && ring.status(b) == "ready" && slices.Contains(definitions[b].commands, command) {
+ ready = append(ready, b)
+ }
+ }
+ return ready
+}
+
+// recordAnswer proves a key that answered and keeps Brave's rate-limit
+// headers. It only logs a failure: the call already succeeded.
+func (s *Service) recordAnswer(ctx context.Context, saved savedKey, b Backend, observed *Quota) {
+ if saved.state == "verified" && observed == nil {
+ return
+ }
+ params := store.RecordWebSearchKeyAnswerParams{Backend: string(b), ApiKeyCiphertext: saved.sealed}
+ if observed != nil {
+ params.HasQuota = true
+ if observed.Remaining != nil {
+ params.QuotaRemaining = pgtype.Float8{Float64: *observed.Remaining, Valid: true}
+ }
+ if observed.Limit != nil {
+ params.QuotaLimit = pgtype.Float8{Float64: *observed.Limit, Valid: true}
+ }
+ if observed.ResetsAt != nil {
+ params.QuotaResetsAt = pgtype.Timestamptz{Time: *observed.ResetsAt, Valid: true}
+ }
+ }
+ if err := s.store.RecordWebSearchKeyAnswer(ctx, params); err != nil {
+ s.logger.Warn("web_search.key_answer_not_recorded", "backend", string(b), "error_type", fmt.Sprintf("%T", err))
+ }
+}
diff --git a/apps/teamhub/internal/websearch/websearch_test.go b/apps/teamhub/internal/websearch/websearch_test.go
new file mode 100644
index 00000000..7b31065d
--- /dev/null
+++ b/apps/teamhub/internal/websearch/websearch_test.go
@@ -0,0 +1,673 @@
+package websearch
+
+import (
+ "bytes"
+ "context"
+ "encoding/base64"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/secretbox"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+type memoryStore struct {
+ mu sync.Mutex
+ rows map[string]store.ListWebSearchKeysRow
+ chosen pgtype.Text
+ setting bool
+}
+
+func newMemoryStore() *memoryStore {
+ return &memoryStore{rows: map[string]store.ListWebSearchKeysRow{}}
+}
+
+func (m *memoryStore) ListWebSearchKeys(context.Context) ([]store.ListWebSearchKeysRow, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ rows := []store.ListWebSearchKeysRow{}
+ for _, row := range m.rows {
+ rows = append(rows, row)
+ }
+ return rows, nil
+}
+
+func (m *memoryStore) UpsertWebSearchKey(_ context.Context, arg store.UpsertWebSearchKeyParams) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.rows[arg.Backend] = store.ListWebSearchKeysRow{Backend: arg.Backend, ApiKeyCiphertext: arg.ApiKeyCiphertext, State: arg.State}
+ return nil
+}
+
+func (m *memoryStore) DeleteWebSearchKey(_ context.Context, backend string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ delete(m.rows, backend)
+ return nil
+}
+
+func (m *memoryStore) MarkWebSearchKeyRejected(_ context.Context, arg store.MarkWebSearchKeyRejectedParams) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if row, ok := m.rows[arg.Backend]; ok && bytes.Equal(row.ApiKeyCiphertext, arg.ApiKeyCiphertext) {
+ row.State = "rejected"
+ m.rows[arg.Backend] = row
+ }
+ return nil
+}
+
+func (m *memoryStore) RecordWebSearchKeyAnswer(_ context.Context, arg store.RecordWebSearchKeyAnswerParams) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ row, ok := m.rows[arg.Backend]
+ if !ok || !bytes.Equal(row.ApiKeyCiphertext, arg.ApiKeyCiphertext) {
+ return nil
+ }
+ row.State = "verified"
+ if arg.HasQuota {
+ row.QuotaRemaining, row.QuotaLimit, row.QuotaResetsAt = arg.QuotaRemaining, arg.QuotaLimit, arg.QuotaResetsAt
+ row.QuotaObservedAt = pgtype.Timestamptz{Time: time.Now(), Valid: true}
+ }
+ m.rows[arg.Backend] = row
+ return nil
+}
+
+func (m *memoryStore) GetWebSearchDefaultBackend(context.Context) (string, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if !m.setting {
+ return "", pgx.ErrNoRows
+ }
+ return m.chosen.String, nil
+}
+
+func (m *memoryStore) SetWebSearchDefaultBackend(_ context.Context, value pgtype.Text) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.chosen, m.setting = value, true
+ return nil
+}
+
+func (m *memoryStore) ClearWebSearchDefaultBackend(_ context.Context, backend string) error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ if m.chosen.String == backend {
+ m.chosen = pgtype.Text{}
+ }
+ return nil
+}
+
+func testBox(t *testing.T) *secretbox.Box {
+ t.Helper()
+ box, err := secretbox.New(base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32)))
+ if err != nil {
+ t.Fatal(err)
+ }
+ return box
+}
+
+// seen is one request a fake provider received.
+type seen struct {
+ method, path, query, auth, apiKey, token string
+ body map[string]any
+}
+
+// fakeProviders serves every provider from one server; handle answers each
+// request and records it.
+type fakeProviders struct {
+ mu sync.Mutex
+ requests []seen
+ server *httptest.Server
+}
+
+func newFakeProviders(t *testing.T, handle func(w http.ResponseWriter, r seen)) *fakeProviders {
+ t.Helper()
+ fake := &fakeProviders{}
+ fake.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw, _ := io.ReadAll(r.Body)
+ request := seen{method: r.Method, path: r.URL.Path, query: r.URL.RawQuery, auth: r.Header.Get("Authorization"),
+ apiKey: r.Header.Get("X-API-Key"), token: r.Header.Get("X-Subscription-Token")}
+ _ = json.Unmarshal(raw, &request.body)
+ fake.mu.Lock()
+ fake.requests = append(fake.requests, request)
+ fake.mu.Unlock()
+ handle(w, request)
+ }))
+ t.Cleanup(fake.server.Close)
+ return fake
+}
+
+func (f *fakeProviders) endpoints() Endpoints {
+ return Endpoints{Tavily: f.server.URL + "/tavily", Brave: f.server.URL + "/brave", Firecrawl: f.server.URL + "/firecrawl",
+ YouAPI: f.server.URL + "/youapi", YouIndex: f.server.URL + "/youindex", YouMCP: f.server.URL + "/mcp/free", Client: f.server.Client()}
+}
+
+func (f *fakeProviders) seen() []seen {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]seen(nil), f.requests...)
+}
+
+func writeJSON(w http.ResponseWriter, status int, body string) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(body))
+}
+
+func newTestService(t *testing.T, fake *fakeProviders) (*Service, *memoryStore) {
+ t.Helper()
+ keys := newMemoryStore()
+ return New(keys, testBox(t), fake.endpoints(), nil), keys
+}
+
+func saveRaw(t *testing.T, s *Service, keys *memoryStore, b Backend, key, state string) {
+ t.Helper()
+ sealed, err := s.box.Seal([]byte(key))
+ if err != nil {
+ t.Fatal(err)
+ }
+ _ = keys.UpsertWebSearchKey(t.Context(), store.UpsertWebSearchKeyParams{Backend: string(b), ApiKeyCiphertext: sealed, State: state})
+}
+
+func search(query string) Request {
+ request, err := Normalize(Request{Command: CommandSearch, Query: query})
+ if err != nil {
+ panic(err)
+ }
+ return request
+}
+
+func TestRunSendsEachProviderItsRequestAndNormalizesResults(t *testing.T) {
+ fake := newFakeProviders(t, func(w http.ResponseWriter, r seen) {
+ switch r.path {
+ case "/tavily/search":
+ writeJSON(w, 200, `{"results":[{"title":"T","url":"https://t.example/a","content":"tavily text","published_date":"2026-11-01"},{"title":"bad","url":"javascript:alert(1)","content":"x"}]}`)
+ case "/brave/res/v1/web/search":
+ w.Header().Set("X-RateLimit-Limit", "1, 2000")
+ w.Header().Set("X-RateLimit-Remaining", "0, 1500")
+ w.Header().Set("X-RateLimit-Reset", "1, 86400")
+ writeJSON(w, 200, `{"web":{"results":[{"title":"B &amp; co","url":"https://b.example","description":"a <strong>bold</strong> hit","age":"2 days ago"}]}}`)
+ case "/firecrawl/v2/search":
+ writeJSON(w, 200, `{"success":true,"data":{"web":[{"title":"F","url":"https://f.example","description":"firecrawl"}]}}`)
+ case "/youindex/v1/search":
+ writeJSON(w, 200, `{"results":{"web":[{"title":"Y","url":"https://y.example","snippets":["you snippet"],"page_age":"2026-10-01T00:00:00"}]}}`)
+ default:
+ t.Errorf("unexpected %s %s", r.method, r.path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ })
+ s, keys := newTestService(t, fake)
+ for _, b := range []Backend{Tavily, Brave, Firecrawl, You} {
+ saveRaw(t, s, keys, b, string(b)+"-secret", "verified")
+ }
+ cases := []struct {
+ backend Backend
+ request Request
+ want Result
+ }{
+ {Tavily, Request{Command: CommandSearch, Query: "q one", Limit: 3, Recency: "week", Sites: []string{"Docs.Example.com"}},
+ Result{Title: "T", URL: "https://t.example/a", Snippet: "tavily text", PublishedAt: "2026-11-01"}},
+ {Brave, Request{Command: CommandSearch, Query: "q two", Recency: "day", Sites: []string{"b.example"}},
+ Result{Title: "B & co", URL: "https://b.example", Snippet: "a bold hit", PublishedAt: "2 days ago"}},
+ {Firecrawl, Request{Command: CommandSearch, Query: "q three", Recency: "month"},
+ Result{Title: "F", URL: "https://f.example", Snippet: "firecrawl"}},
+ {You, Request{Command: CommandSearch, Query: "q four", Recency: "year"},
+ Result{Title: "Y", URL: "https://y.example", Snippet: "you snippet", PublishedAt: "2026-10-01T00:00:00"}},
+ }
+ for _, tc := range cases {
+ tc.request.Backend = tc.backend
+ request, err := Normalize(tc.request)
+ if err != nil {
+ t.Fatalf("%s: Normalize = %v", tc.backend, err)
+ }
+ outcome, err := s.Run(t.Context(), request)
+ if err != nil {
+ t.Fatalf("%s: Run = %v", tc.backend, err)
+ }
+ if outcome.Backend != tc.backend || len(outcome.Results) != 1 || outcome.Results[0] != tc.want {
+ t.Fatalf("%s: outcome = %+v", tc.backend, outcome)
+ }
+ }
+ requests := fake.seen()
+ tavily := requests[0]
+ if tavily.auth != "Bearer tavily-secret" || tavily.body["max_results"] != float64(3) || tavily.body["time_range"] != "week" ||
+ tavily.body["include_domains"].([]any)[0] != "docs.example.com" {
+ t.Fatalf("tavily request = %+v", tavily)
+ }
+ brave := requests[1]
+ if brave.token != "brave-secret" || !strings.Contains(brave.query, "freshness=pd") || !strings.Contains(brave.query, "q=q+two+site%3Ab.example") ||
+ !strings.Contains(brave.query, "count=10") {
+ t.Fatalf("brave request = %+v", brave)
+ }
+ if firecrawl := requests[2]; firecrawl.auth != "Bearer firecrawl-secret" || firecrawl.body["tbs"] != "qdr:m" {
+ t.Fatalf("firecrawl request = %+v", firecrawl)
+ }
+ if you := requests[3]; you.apiKey != "you-secret" || you.body["freshness"] != "year" || you.body["count"] != float64(10) {
+ t.Fatalf("you request = %+v", you)
+ }
+ // Brave's monthly window is kept from its headers.
+ row := keys.rows[string(Brave)]
+ if !row.QuotaRemaining.Valid || row.QuotaRemaining.Float64 != 1500 || row.QuotaLimit.Float64 != 2000 || !row.QuotaResetsAt.Valid {
+ t.Fatalf("brave quota row = %+v", row)
+ }
+}
+
+func TestRunClassifiesProviderRefusals(t *testing.T) {
+ type reply struct {
+ status int
+ body string
+ header map[string]string
+ }
+ cases := []struct {
+ name string
+ backend Backend
+ reply reply
+ code Code
+ retry time.Duration
+ }{
+ {"tavily 401", Tavily, reply{401, `{}`, nil}, CodeKeyRejected, 0},
+ {"tavily 432", Tavily, reply{432, `{}`, nil}, CodeQuotaExhausted, 0},
+ {"firecrawl 402", Firecrawl, reply{402, `{}`, nil}, CodeQuotaExhausted, 0},
+ {"you 429", You, reply{429, `{}`, map[string]string{"Retry-After": "7"}}, CodeRateLimited, 7 * time.Second},
+ {"brave token", Brave, reply{422, `{"error":{"code":"SUBSCRIPTION_TOKEN_INVALID"}}`, nil}, CodeKeyRejected, 0},
+ {"brave quota", Brave, reply{429, `{"error":{"code":"QUOTA_LIMITED"}}`, nil}, CodeQuotaExhausted, 0},
+ {"brave rate", Brave, reply{429, `{"error":{"code":"RATE_LIMITED"}}`, map[string]string{"X-RateLimit-Reset": "1, 999"}}, CodeRateLimited, time.Second},
+ {"tavily 500", Tavily, reply{500, `{}`, nil}, CodeProviderUnavailable, 0},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ fake := newFakeProviders(t, func(w http.ResponseWriter, _ seen) {
+ for name, value := range tc.reply.header {
+ w.Header().Set(name, value)
+ }
+ writeJSON(w, tc.reply.status, tc.reply.body)
+ })
+ s, keys := newTestService(t, fake)
+ saveRaw(t, s, keys, tc.backend, "provider-secret", "verified")
+ saveRaw(t, s, keys, Firecrawl, "other-secret", "verified")
+ request := search("private query")
+ request.Backend = tc.backend
+ _, err := s.Run(t.Context(), request)
+ var failure *Failure
+ if !errors.As(err, &failure) || failure.Code != tc.code || failure.Backend != tc.backend || failure.RetryAfter != tc.retry {
+ t.Fatalf("Run = %#v", err)
+ }
+ if strings.Contains(err.Error(), "provider-secret") || strings.Contains(err.Error(), "private") {
+ t.Fatalf("error leaks the request: %v", err)
+ }
+ rejected := keys.rows[string(tc.backend)].State == "rejected"
+ if rejected != (tc.code == CodeKeyRejected) {
+ t.Fatalf("state = %q", keys.rows[string(tc.backend)].State)
+ }
+ if tc.code == CodeQuotaExhausted || tc.code == CodeRateLimited {
+ wantReady := []Backend{Firecrawl, You}
+ switch tc.backend {
+ case Firecrawl:
+ wantReady = []Backend{You}
+ case You:
+ wantReady = []Backend{Firecrawl}
+ }
+ if len(failure.Ready) != len(wantReady) || failure.Ready[0] != wantReady[0] {
+ t.Fatalf("ready = %v, want %v", failure.Ready, wantReady)
+ }
+ }
+ })
+ }
+}
+
+func TestRunRefusesAFilterTheBackendCannotHonorBeforeAnyCall(t *testing.T) {
+ fake := newFakeProviders(t, func(w http.ResponseWriter, _ seen) { writeJSON(w, 200, `{}`) })
+ s, keys := newTestService(t, fake)
+ saveRaw(t, s, keys, Firecrawl, "provider-secret", "verified")
+ saveRaw(t, s, keys, Brave, "provider-secret", "verified")
+ for _, request := range []Request{
+ {Command: CommandSearch, Backend: Firecrawl, Query: "q", Sites: []string{"a.example"}},
+ {Command: CommandSearch, Backend: Brave, Query: "q", Sites: []string{"a.example", "b.example"}},
+ } {
+ normalized, err := Normalize(request)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, err = s.Run(t.Context(), normalized)
+ var failure *Failure
+ if !errors.As(err, &failure) || failure.Code != CodeUnsupported {
+ t.Fatalf("Run = %v", err)
+ }
+ }
+ if requests := fake.seen(); len(requests) != 0 {
+ t.Fatalf("providers were called: %+v", requests)
+ }
+ if _, err := Normalize(Request{Command: CommandOpen, Backend: Brave, URL: "https://a.example"}); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("open with brave = %v", err)
+ }
+ if _, err := Normalize(Request{Command: CommandOpen, URL: "file:///etc/passwd"}); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("open a file URL = %v", err)
+ }
+}
+
+// keylessMCP answers You.com's MCP handshake and then tools/call.
+func keylessMCP(t *testing.T, call func(w http.ResponseWriter, r seen)) func(w http.ResponseWriter, r seen) {
+ return func(w http.ResponseWriter, r seen) {
+ if r.path != "/mcp/free" {
+ t.Errorf("unexpected %s %s", r.method, r.path)
+ w.WriteHeader(http.StatusNotFound)
+ return
+ }
+ switch r.body["method"] {
+ case "initialize":
+ w.Header().Set("Mcp-Session-Id", "session-1")
+ writeJSON(w, 200, `{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{}}}`)
+ case "notifications/initialized":
+ w.WriteHeader(http.StatusAccepted)
+ default:
+ call(w, r)
+ }
+ }
+}
+
+func TestSearchWithoutKeysUsesTheKeylessTrial(t *testing.T) {
+ fake := newFakeProviders(t, keylessMCP(t, func(w http.ResponseWriter, r seen) {
+ params := r.body["params"].(map[string]any)
+ if params["name"] != "you-search" || params["arguments"].(map[string]any)["query"] != "q" {
+ t.Errorf("tools/call = %+v", params)
+ }
+ w.Header().Set("Content-Type", "text/event-stream")
+ _, _ = w.Write([]byte("event: message\ndata: {\"jsonrpc\":\"2.0\",\"method\":\"notifications/message\",\"params\":{}}\n\n" +
+ "data: {\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"structuredContent\":{\"results\":{\"web\":[{\"title\":\"K\",\"url\":\"https://k.example\",\"description\":\"keyless\"}]}}}}\n\n"))
+ }))
+ s, _ := newTestService(t, fake)
+ outcome, err := s.Run(t.Context(), search("q"))
+ if err != nil || outcome.Backend != You || len(outcome.Results) != 1 || outcome.Results[0].Snippet != "keyless" {
+ t.Fatalf("Run = %+v, %v", outcome, err)
+ }
+ requests := fake.seen()
+ if len(requests) != 3 || requests[2].apiKey != "" {
+ t.Fatalf("requests = %+v", requests)
+ }
+}
+
+func TestKeylessFreeLimitAsksForAKey(t *testing.T) {
+ fake := newFakeProviders(t, keylessMCP(t, func(w http.ResponseWriter, _ seen) { writeJSON(w, 429, `{}`) }))
+ s, _ := newTestService(t, fake)
+ _, err := s.Run(t.Context(), search("q"))
+ var failure *Failure
+ if !errors.As(err, &failure) || failure.Code != CodeFreeLimit || failure.Backend != Tavily || !failure.Suggested || !failure.KeyFailure() {
+ t.Fatalf("implicit Run = %#v", err)
+ }
+ request := search("q")
+ request.Backend = You
+ _, err = s.Run(t.Context(), request)
+ if !errors.As(err, &failure) || failure.Code != CodeFreeLimit || failure.Backend != You || failure.Suggested {
+ t.Fatalf("explicit Run = %#v", err)
+ }
+}
+
+func TestRunWithoutAKeyNamesTheBackend(t *testing.T) {
+ fake := newFakeProviders(t, func(w http.ResponseWriter, _ seen) { t.Error("no call expected") })
+ s, keys := newTestService(t, fake)
+ request := search("q")
+ request.Backend = Brave
+ _, err := s.Run(t.Context(), request)
+ var failure *Failure
+ if !errors.As(err, &failure) || failure.Code != CodeKeyRequired || failure.Backend != Brave || failure.Suggested {
+ t.Fatalf("Run = %#v", err)
+ }
+ saveRaw(t, s, keys, Tavily, "provider-secret", "rejected")
+ request.Backend = Tavily
+ if _, err = s.Run(t.Context(), request); !errors.As(err, &failure) || failure.Code != CodeKeyRejected {
+ t.Fatalf("Run with a rejected key = %#v", err)
+ }
+}
+
+func TestDefaultSearchUsesTheChosenDefaultWithoutFallingBack(t *testing.T) {
+ fake := newFakeProviders(t, func(w http.ResponseWriter, r seen) {
+ switch r.path {
+ case "/firecrawl/v2/search":
+ writeJSON(w, 200, `{"data":{"web":[]}}`)
+ case "/brave/res/v1/web/search":
+ writeJSON(w, 200, `{"web":{"results":[]}}`)
+ default:
+ t.Errorf("unexpected %s", r.path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ })
+ s, keys := newTestService(t, fake)
+ saveRaw(t, s, keys, Firecrawl, "provider-secret", "verified")
+ saveRaw(t, s, keys, Brave, "provider-secret", "unverified")
+ saveRaw(t, s, keys, Tavily, "provider-secret", "rejected")
+ outcome, err := s.Run(t.Context(), search("q"))
+ if err != nil || outcome.Backend != Brave {
+ t.Fatalf("order Run = %+v, %v", outcome, err)
+ }
+ if _, err := s.SetDefault(t.Context(), Tavily); !errors.Is(err, ErrNotReady) {
+ t.Fatalf("SetDefault(rejected) = %v", err)
+ }
+ chosen, err := s.SetDefault(t.Context(), Firecrawl)
+ if err != nil || chosen.DefaultSearch != Firecrawl || chosen.ChosenDefault != Firecrawl {
+ t.Fatalf("SetDefault = %+v, %v", chosen, err)
+ }
+ if outcome, err = s.Run(t.Context(), search("q")); err != nil || outcome.Backend != Firecrawl {
+ t.Fatalf("default Run = %+v, %v", outcome, err)
+ }
+ saveRaw(t, s, keys, Firecrawl, "provider-secret", "rejected")
+ var failure *Failure
+ if _, err = s.Run(t.Context(), search("q")); !errors.As(err, &failure) || failure.Code != CodeKeyRejected ||
+ failure.Backend != Firecrawl || failure.Suggested {
+ t.Fatalf("Run with a rejected chosen default = %#v", err)
+ }
+ if list, err := s.List(t.Context()); err != nil || list.DefaultSearch != Firecrawl || list.ChosenDefault != Firecrawl {
+ t.Fatalf("List with a rejected chosen default = %+v, %v", list, err)
+ }
+ if err := s.RemoveKey(t.Context(), Firecrawl); err != nil {
+ t.Fatal(err)
+ }
+ cleared, err := s.ClearDefault(t.Context())
+ if err != nil || cleared.DefaultSearch != Brave || cleared.ChosenDefault != "" {
+ t.Fatalf("ClearDefault = %+v, %v", cleared, err)
+ }
+}
+
+func TestSaveKeyUsesTheOfficialCheck(t *testing.T) {
+ status := 200
+ fake := newFakeProviders(t, func(w http.ResponseWriter, r seen) {
+ if r.path != "/tavily/usage" || r.method != http.MethodGet || !strings.HasPrefix(r.auth, "Bearer tvly-") {
+ t.Errorf("check = %+v", r)
+ }
+ writeJSON(w, status, `{"key":{"usage":10,"limit":null},"account":{"current_plan":"Researcher","plan_usage":100,"plan_limit":1000}}`)
+ })
+ s, keys := newTestService(t, fake)
+ view, err := s.SaveKey(t.Context(), Tavily, " tvly-secret ")
+ if err != nil || view.KeyState != "verified" || view.Status != "ready" || view.Quota.From != "provider" ||
+ *view.Quota.Remaining != 900 || *view.Quota.Limit != 1000 || view.Quota.Plan != "Researcher" {
+ t.Fatalf("SaveKey = %+v, %v", view, err)
+ }
+ if bytes.Contains(keys.rows[string(Tavily)].ApiKeyCiphertext, []byte("tvly-secret")) {
+ t.Fatal("key stored in clear")
+ }
+ status = 401
+ if _, err := s.SaveKey(t.Context(), Tavily, "tvly-other"); !errors.Is(err, ErrKeyRejected) {
+ t.Fatalf("SaveKey(refused) = %v", err)
+ }
+ opened, _ := s.box.Open(keys.rows[string(Tavily)].ApiKeyCiphertext)
+ if string(opened) != "tvly-secret" {
+ t.Fatal("a refused key replaced the saved one")
+ }
+ brave, err := s.SaveKey(t.Context(), Brave, "brave-secret")
+ if err != nil || brave.KeyState != "unverified" || brave.Status != "ready" || brave.Quota.Reason != "not_observed" {
+ t.Fatalf("SaveKey(brave) = %+v, %v", brave, err)
+ }
+ if len(fake.seen()) != 2 {
+ t.Fatal("a Brave key was checked")
+ }
+ for _, key := range []string{"", "has space", strings.Repeat("k", MaxKeyBytes+1)} {
+ if _, err := s.SaveKey(t.Context(), Tavily, key); !errors.Is(err, ErrInvalid) {
+ t.Fatalf("SaveKey(%q) = %v", key, err)
+ }
+ }
+ if _, err := New(newMemoryStore(), nil, fake.endpoints(), nil).SaveKey(t.Context(), Tavily, "k"); !errors.Is(err, ErrStorageMissing) {
+ t.Fatalf("SaveKey without a box = %v", err)
+ }
+}
+
+func TestSaveReplayedRunsTheRequestWithTheCandidateKey(t *testing.T) {
+ status, body := 200, `{"web":{"results":[{"title":"B","url":"https://b.example","description":"hit"}]}}`
+ fake := newFakeProviders(t, func(w http.ResponseWriter, r seen) {
+ if !strings.HasPrefix(r.token, "brave-candidate") {
+ t.Errorf("token = %q", r.token)
+ }
+ writeJSON(w, status, body)
+ })
+ s, keys := newTestService(t, fake)
+ request := search("private query")
+ request.Backend = Tavily
+ replay, err := s.SaveReplayed(t.Context(), Brave, "brave-candidate", request)
+ if err != nil || replay.Failure != nil || len(replay.Outcome.Results) != 1 || replay.View.KeyState != "verified" {
+ t.Fatalf("SaveReplayed = %+v, %v", replay, err)
+ }
+ status, body = 401, `{}`
+ if _, err := s.SaveReplayed(t.Context(), Brave, "brave-candidate2", request); !errors.Is(err, ErrKeyRejected) {
+ t.Fatalf("SaveReplayed(refused) = %v", err)
+ }
+ if opened, _ := s.box.Open(keys.rows[string(Brave)].ApiKeyCiphertext); string(opened) != "brave-candidate" {
+ t.Fatal("a refused key was saved")
+ }
+ for _, tc := range []struct {
+ status int
+ code Code
+ state string
+ }{{429, CodeRateLimited, "verified"}, {503, CodeProviderUnavailable, "unverified"}} {
+ status, body = tc.status, `{}`
+ replay, err := s.SaveReplayed(t.Context(), Brave, "brave-candidate", request)
+ if err != nil || replay.Failure == nil || replay.Failure.Code != tc.code || keys.rows[string(Brave)].State != tc.state {
+ t.Fatalf("HTTP %d: SaveReplayed = %+v, %v, state %q", tc.status, replay, err, keys.rows[string(Brave)].State)
+ }
+ }
+ // A filter the chosen backend cannot honor saves the key unverified
+ // without a call.
+ calls := len(fake.seen())
+ request.Sites = []string{"a.example"}
+ replay, err = s.SaveReplayed(t.Context(), Firecrawl, "fc-candidate", request)
+ if err != nil || replay.Failure == nil || replay.Failure.Code != CodeUnsupported || keys.rows[string(Firecrawl)].State != "unverified" ||
+ len(fake.seen()) != calls {
+ t.Fatalf("SaveReplayed(unsupported) = %+v, %v", replay, err)
+ }
+}
+
+func TestOpenReadsThePageThroughEachBackend(t *testing.T) {
+ long := strings.Repeat("é", MaxMarkdown+5)
+ fake := newFakeProviders(t, func(w http.ResponseWriter, r seen) {
+ switch r.path {
+ case "/tavily/extract":
+ writeJSON(w, 200, `{"results":[{"url":"https://t.example/final","raw_content":"`+long+`"}],"failed_results":[]}`)
+ case "/firecrawl/v2/scrape":
+ writeJSON(w, 200, `{"success":true,"data":{"markdown":"","metadata":{"statusCode":404}}}`)
+ case "/youindex/v1/extract":
+ if r.body["url"] != "https://y.example" {
+ t.Errorf("extract body = %+v", r.body)
+ }
+ writeJSON(w, 200, `{"url":"https://y.example","title":"Y page","contents":{"full_page":{"markdown":"# Y"}}}`)
+ }
+ })
+ s, keys := newTestService(t, fake)
+ for _, b := range []Backend{Tavily, Firecrawl, You} {
+ saveRaw(t, s, keys, b, "provider-secret", "verified")
+ }
+ open := func(b Backend, link string) (Outcome, error) {
+ request, err := Normalize(Request{Command: CommandOpen, Backend: b, URL: link})
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s.Run(t.Context(), request)
+ }
+ outcome, err := open(Tavily, "https://t.example")
+ if err != nil || outcome.Page == nil || !outcome.Page.Truncated || len([]rune(outcome.Page.Markdown)) != MaxMarkdown ||
+ outcome.Page.URL != "https://t.example/final" {
+ t.Fatalf("tavily open = %v", err)
+ }
+ _, err = open(Firecrawl, "https://f.example")
+ var failure *Failure
+ if !errors.As(err, &failure) || failure.Code != CodePageUnreadable || failure.Backend != Firecrawl {
+ t.Fatalf("firecrawl open = %#v", err)
+ }
+ outcome, err = open(You, "https://y.example")
+ if err != nil || outcome.Page.Title != "Y page" || outcome.Page.Markdown != "# Y" || outcome.Page.Truncated {
+ t.Fatalf("you open = %+v, %v", outcome.Page, err)
+ }
+}
+
+func TestKeylessOpenReadsTheExtractOutput(t *testing.T) {
+ fake := newFakeProviders(t, keylessMCP(t, func(w http.ResponseWriter, r seen) {
+ if r.body["params"].(map[string]any)["name"] != "you-extract" {
+ t.Errorf("tools/call = %+v", r.body)
+ }
+ writeJSON(w, 200, `{"jsonrpc":"2.0","id":2,"result":{"structuredContent":{"output":[{"url":"https://k.example","title":"K","markdown":"body"}]}}}`)
+ }))
+ s, _ := newTestService(t, fake)
+ request, err := Normalize(Request{Command: CommandOpen, Backend: You, URL: "https://k.example"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ outcome, err := s.Run(t.Context(), request)
+ if err != nil || outcome.Page.Title != "K" || outcome.Page.Markdown != "body" {
+ t.Fatalf("Run = %+v, %v", outcome, err)
+ }
+}
+
+func TestListReportsTiersStatesAndLiveQuota(t *testing.T) {
+ fake := newFakeProviders(t, func(w http.ResponseWriter, r seen) {
+ switch r.path {
+ case "/firecrawl/v2/team/credit-usage":
+ writeJSON(w, 200, `{"success":true,"data":{"remainingCredits":420,"planCredits":500,"billingPeriodEnd":"2026-12-01T00:00:00Z"}}`)
+ case "/youapi/v1/billing/account_balance":
+ time.Sleep(quotaTimeout + time.Second)
+ writeJSON(w, 200, `{}`)
+ default:
+ t.Errorf("unexpected %s", r.path)
+ }
+ })
+ s, keys := newTestService(t, fake)
+ saveRaw(t, s, keys, Firecrawl, "provider-secret", "verified")
+ saveRaw(t, s, keys, Tavily, "provider-secret", "rejected")
+ saveRaw(t, s, keys, Brave, "provider-secret", "unverified")
+ list, err := s.List(t.Context())
+ if err != nil || list.DefaultSearch != Brave || list.DefaultOpen != Direct || !list.CanSaveKeys || len(list.Backends) != 5 {
+ t.Fatalf("List = %+v, %v", list, err)
+ }
+ byID := map[Backend]BackendView{}
+ for _, view := range list.Backends {
+ byID[view.ID] = view
+ }
+ if v := byID[Tavily]; v.Status != "key_rejected" || v.KeyState != "rejected" || v.Quota.Reason != "key_rejected" || v.Tier != TierKey {
+ t.Fatalf("tavily = %+v", v)
+ }
+ if v := byID[Firecrawl]; v.Status != "ready" || v.Quota.From != "provider" || *v.Quota.Remaining != 420 || *v.Quota.Limit != 500 ||
+ v.Quota.ResetsAt == nil || len(v.Filters) != 1 || v.MaxSites != 0 {
+ t.Fatalf("firecrawl = %+v", v)
+ }
+ if v := byID[You]; v.Status != "ready" || v.Tier != TierFreeTrial || v.TierText == "" || v.Quota.From != "unavailable" || v.Quota.Reason != "not_reported" {
+ t.Fatalf("you = %+v", v)
+ }
+ if v := byID[Direct]; v.Tier != TierNone || v.Status != "ready" || len(v.Commands) != 1 || v.Commands[0] != CommandOpen {
+ t.Fatalf("direct = %+v", v)
+ }
+ saveRaw(t, s, keys, You, "provider-secret", "verified")
+ start := time.Now()
+ list, err = s.List(t.Context())
+ if err != nil || time.Since(start) > quotaTimeout+500*time.Millisecond {
+ t.Fatalf("List took %s, %v", time.Since(start), err)
+ }
+ for _, view := range list.Backends {
+ if view.ID == You && (view.Tier != TierKey || view.Quota.Reason != "provider_unavailable") {
+ t.Fatalf("you with a slow usage endpoint = %+v", view)
+ }
+ }
+}
diff --git a/apps/teamhub/internal/websearch/you_mcp.go b/apps/teamhub/internal/websearch/you_mcp.go
new file mode 100644
index 00000000..c9b6bd44
--- /dev/null
+++ b/apps/teamhub/internal/websearch/you_mcp.go
@@ -0,0 +1,224 @@
+package websearch
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "strings"
+)
+
+// mcpProtocolVersion is the MCP revision TeamHub speaks to You.com's keyless
+// server.
+const mcpProtocolVersion = "2025-06-18"
+
+// runKeyless runs a request on You.com's free MCP server, which needs no key.
+// Its searches are a limited trial: HTTP 429 means the free allowance is used
+// up. TeamHub keeps no count of its own.
+func (p *providers) runKeyless(ctx context.Context, request Request) (Outcome, error) {
+ if !supports(You, request) {
+ return Outcome{}, &Failure{Code: CodeUnsupported, Backend: You}
+ }
+ timeout := searchTimeout
+ if request.Command == CommandOpen {
+ timeout = openTimeout
+ }
+ ctx, cancel := context.WithTimeout(ctx, timeout)
+ defer cancel()
+ session, err := p.mcpInitialize(ctx)
+ if err != nil {
+ return Outcome{}, err
+ }
+ tool, arguments := "you-search", youSearchBody(request)
+ if request.Command == CommandOpen {
+ tool, arguments = "you-extract", map[string]any{"url": request.URL}
+ }
+ result, err := p.mcpCall(ctx, session, 2, "tools/call", map[string]any{"name": tool, "arguments": arguments})
+ if err != nil {
+ return Outcome{}, err
+ }
+ var called struct {
+ IsError bool `json:"isError"`
+ StructuredContent json.RawMessage `json:"structuredContent"`
+ Content []struct {
+ Type string `json:"type"`
+ Text string `json:"text"`
+ } `json:"content"`
+ }
+ if json.Unmarshal(result, &called) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ if called.IsError {
+ if request.Command == CommandOpen {
+ return Outcome{}, &Failure{Code: CodePageUnreadable, Backend: You}
+ }
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ structured := called.StructuredContent
+ if len(structured) == 0 && len(called.Content) > 0 && called.Content[0].Type == "text" {
+ structured = json.RawMessage(called.Content[0].Text)
+ }
+ if request.Command == CommandSearch {
+ var decoded youWebResults
+ if json.Unmarshal(structured, &decoded) != nil {
+ return Outcome{}, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ return decoded.outcome(request.Limit), nil
+ }
+ page, ok := keylessPage(structured)
+ if !ok {
+ return Outcome{}, &Failure{Code: CodePageUnreadable, Backend: You}
+ }
+ outcome, err := pageOutcome(request.URL, page.URL, page.Title, page.markdown())
+ if failure := (*Failure)(nil); errors.As(err, &failure) {
+ failure.Backend = You
+ }
+ return outcome, err
+}
+
+// keylessPage reads the extract tool's output: the page itself, a list of
+// pages, or the Markdown alone.
+func keylessPage(structured json.RawMessage) (youPage, bool) {
+ var wrapper struct {
+ Output json.RawMessage `json:"output"`
+ }
+ if json.Unmarshal(structured, &wrapper) == nil && len(wrapper.Output) > 0 {
+ structured = wrapper.Output
+ }
+ var text string
+ if json.Unmarshal(structured, &text) == nil {
+ return youPage{Markdown: text}, text != ""
+ }
+ var pages []youPage
+ if json.Unmarshal(structured, &pages) == nil {
+ return firstPage(pages)
+ }
+ var page youPage
+ if json.Unmarshal(structured, &page) == nil {
+ return page, page.markdown() != ""
+ }
+ return youPage{}, false
+}
+
+func firstPage(pages []youPage) (youPage, bool) {
+ if len(pages) == 0 {
+ return youPage{}, false
+ }
+ return pages[0], pages[0].markdown() != ""
+}
+
+// mcpInitialize opens a session; a stateless server returns no session ID.
+func (p *providers) mcpInitialize(ctx context.Context) (string, error) {
+ session, _, err := p.mcpPost(ctx, "", map[string]any{
+ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": map[string]any{
+ "protocolVersion": mcpProtocolVersion, "capabilities": map[string]any{},
+ "clientInfo": map[string]any{"name": "teamhub", "version": "1"},
+ },
+ }, 1)
+ if err != nil {
+ return "", err
+ }
+ if _, _, err := p.mcpPost(ctx, session, map[string]any{"jsonrpc": "2.0", "method": "notifications/initialized"}, 0); err != nil {
+ return "", err
+ }
+ return session, nil
+}
+
+func (p *providers) mcpCall(ctx context.Context, session string, id int, method string, params any) (json.RawMessage, error) {
+ _, result, err := p.mcpPost(ctx, session, map[string]any{"jsonrpc": "2.0", "id": id, "method": method, "params": params}, id)
+ return result, err
+}
+
+// mcpPost sends one JSON-RPC message and, for a request (id > 0), returns the
+// result whose id matches, from a JSON or an event-stream answer.
+func (p *providers) mcpPost(ctx context.Context, session string, message any, id int) (string, json.RawMessage, error) {
+ encoded, err := json.Marshal(message)
+ if err != nil {
+ return "", nil, err
+ }
+ request, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoints.YouMCP, bytes.NewReader(encoded))
+ if err != nil {
+ return "", nil, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ request.Header.Set("Content-Type", "application/json")
+ request.Header.Set("Accept", "application/json, text/event-stream")
+ if session != "" {
+ request.Header.Set("Mcp-Session-Id", session)
+ request.Header.Set("MCP-Protocol-Version", mcpProtocolVersion)
+ }
+ response, err := p.client.Do(request)
+ if err != nil {
+ return "", nil, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ defer response.Body.Close()
+ switch {
+ case response.StatusCode == http.StatusTooManyRequests:
+ return "", nil, &Failure{Code: CodeFreeLimit, Backend: You, RetryAfter: retryAfter(response.Header)}
+ case response.StatusCode < 200 || response.StatusCode >= 300:
+ return "", nil, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ if session == "" {
+ session = response.Header.Get("Mcp-Session-Id")
+ }
+ if id == 0 {
+ _, _ = io.Copy(io.Discard, io.LimitReader(response.Body, maxResponseBody))
+ return session, nil, nil
+ }
+ body := io.LimitReader(response.Body, maxResponseBody)
+ var messages []json.RawMessage
+ if strings.HasPrefix(response.Header.Get("Content-Type"), "text/event-stream") {
+ messages = eventStreamData(body)
+ } else if read, err := io.ReadAll(body); err == nil {
+ messages = []json.RawMessage{read}
+ }
+ for _, raw := range messages {
+ var reply struct {
+ ID json.RawMessage `json:"id"`
+ Result json.RawMessage `json:"result"`
+ Error json.RawMessage `json:"error"`
+ }
+ if json.Unmarshal(raw, &reply) != nil || string(reply.ID) != jsonNumber(id) {
+ continue
+ }
+ if len(reply.Error) > 0 || len(reply.Result) == 0 {
+ return session, nil, &Failure{Code: CodeProviderUnavailable, Backend: You}
+ }
+ return session, reply.Result, nil
+ }
+ return session, nil, &Failure{Code: CodeProviderUnavailable, Backend: You}
+}
+
+func jsonNumber(id int) string {
+ encoded, _ := json.Marshal(id)
+ return string(encoded)
+}
+
+// eventStreamData returns the data of each event; notifications may come
+// before the result.
+func eventStreamData(body io.Reader) []json.RawMessage {
+ scanner := bufio.NewScanner(body)
+ scanner.Buffer(make([]byte, 64<<10), maxResponseBody)
+ var events []json.RawMessage
+ var data []string
+ flush := func() {
+ if len(data) > 0 {
+ events = append(events, json.RawMessage(strings.Join(data, "\n")))
+ data = nil
+ }
+ }
+ for scanner.Scan() {
+ line := scanner.Text()
+ if line == "" {
+ flush()
+ continue
+ }
+ if value, ok := strings.CutPrefix(line, "data:"); ok {
+ data = append(data, strings.TrimPrefix(value, " "))
+ }
+ }
+ flush()
+ return events
+}
diff --git a/apps/teamhub/migrations/00885_web_search.sql b/apps/teamhub/migrations/00885_web_search.sql
new file mode 100644
index 00000000..a438ae09
--- /dev/null
+++ b/apps/teamhub/migrations/00885_web_search.sql
@@ -0,0 +1,48 @@
+-- +goose Up
+-- Web search API keys saved in the product, one row per backend, sealed with
+-- TEAMHUB_SECRET_ENCRYPTION_KEY like voice_provider_keys. A key serves every
+-- Human and Agent on the deployment, and TeamHub reads the row at each call,
+-- so a save applies on every replica at once. state is what the provider last
+-- said about the key: verified by its official check or a successful call,
+-- unverified while a provider without an official check (Brave) has answered
+-- no call yet, rejected once it refused the key. The quota columns keep the
+-- last rate-limit headers of a provider that reports quota only on its
+-- responses; a save clears them.
+CREATE TABLE web_search_keys (
+ backend text PRIMARY KEY CHECK (backend IN ('you', 'tavily', 'brave', 'firecrawl')),
+ api_key_ciphertext bytea NOT NULL,
+ state text NOT NULL CHECK (state IN ('verified', 'unverified', 'rejected')),
+ quota_remaining double precision,
+ quota_limit double precision,
+ quota_resets_at timestamp with time zone,
+ quota_observed_at timestamp with time zone,
+ updated_at timestamp with time zone DEFAULT now() NOT NULL
+);
+
+-- The deployment's default web search backend: at most one row. Without a
+-- row or a value, a search uses the first usable backend in TeamHub's order.
+CREATE TABLE web_search_settings (
+ singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
+ default_backend text CHECK (default_backend IN ('you', 'tavily', 'brave', 'firecrawl')),
+ updated_at timestamp with time zone DEFAULT now() NOT NULL
+);
+
+-- A search_key card asks a Human for a web search API key; saving any web
+-- search key answers it.
+ALTER TABLE decisions DROP CONSTRAINT decisions_kind_check;
+ALTER TABLE decisions ADD CONSTRAINT decisions_kind_check CHECK (kind = ANY (ARRAY[
+ 'connector_write', 'agent_change', 'question', 'runtime_permission', 'profile_setup_apps',
+ 'profile_setup_sources', 'connection_auth', 'provider_key', 'browser_connection',
+ 'room_creation', 'computer_permission', 'search_key'
+]));
+
+-- +goose Down
+DELETE FROM decisions WHERE kind = 'search_key';
+ALTER TABLE decisions DROP CONSTRAINT decisions_kind_check;
+ALTER TABLE decisions ADD CONSTRAINT decisions_kind_check CHECK (kind = ANY (ARRAY[
+ 'connector_write', 'agent_change', 'question', 'runtime_permission', 'profile_setup_apps',
+ 'profile_setup_sources', 'connection_auth', 'provider_key', 'browser_connection',
+ 'room_creation', 'computer_permission'
+]));
+DROP TABLE web_search_settings;
+DROP TABLE web_search_keys;
diff --git a/apps/teamhub/tests/integration/web_search_test.go b/apps/teamhub/tests/integration/web_search_test.go
new file mode 100644
index 00000000..1c92ba96
--- /dev/null
+++ b/apps/teamhub/tests/integration/web_search_test.go
@@ -0,0 +1,170 @@
+package integration_test
+
+import (
+ "bytes"
+ "encoding/base64"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/app"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/websearch"
+)
+
+// fakeSearchProviders serves You.com's keyless MCP server (its trial used
+// up), Brave's search API and Tavily's usage endpoint.
+func fakeSearchProviders(t *testing.T) *httptest.Server {
+ t.Helper()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ raw, _ := io.ReadAll(r.Body)
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/mcp/free":
+ var message struct {
+ Method string `json:"method"`
+ }
+ _ = json.Unmarshal(raw, &message)
+ switch message.Method {
+ case "initialize":
+ _, _ = w.Write([]byte(`{"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-06-18","capabilities":{}}}`))
+ case "notifications/initialized":
+ w.WriteHeader(http.StatusAccepted)
+ default:
+ w.WriteHeader(http.StatusTooManyRequests)
+ }
+ case "/brave/res/v1/web/search":
+ if r.Header.Get("X-Subscription-Token") != "brave-good" {
+ w.WriteHeader(http.StatusUnprocessableEntity)
+ _, _ = w.Write([]byte(`{"error":{"code":"SUBSCRIPTION_TOKEN_INVALID"}}`))
+ return
+ }
+ w.Header().Set("X-RateLimit-Remaining", "0, 1999")
+ _, _ = w.Write([]byte(`{"web":{"results":[{"title":"Rust","url":"https://rust.example/news","description":"release notes"}]}}`))
+ case "/tavily/usage":
+ if r.Header.Get("Authorization") != "Bearer tvly-good" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ _, _ = w.Write([]byte(`{"key":{"usage":0},"account":{"current_plan":"Researcher","plan_usage":10,"plan_limit":1000}}`))
+ default:
+ t.Errorf("unexpected provider call %s %s", r.Method, r.URL.Path)
+ w.WriteHeader(http.StatusNotFound)
+ }
+ }))
+ registerIntegrationServerCleanup(t, server)
+ return server
+}
+
+type agentSearchFailure struct {
+ Error struct {
+ Code string `json:"code"`
+ Details struct {
+ Backend string `json:"backend"`
+ Origin string `json:"origin"`
+ Reason string `json:"reason"`
+ MessageID string `json:"message_id"`
+ InteractionID string `json:"interaction_id"`
+ } `json:"details"`
+ } `json:"error"`
+}
+
+// A search that needs a key posts one card, reused and kept current while it
+// waits. A key added from the card is proven by replaying the Agent's search,
+// whose results wake the Agent; a key the provider refuses is not saved. A key
+// saved from Connectors answers the other waiting cards with the backend to
+// use.
+func TestWebSearchAsksForAKeyAndReplaysTheSearchWithIt(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ providers := fakeSearchProviders(t)
+ env, alice, issued, roomID := newAgentCLIIdentity(t, withConfig(func(cfg *config.Config) {
+ cfg.ExternalApps.SecretEncryptionKey = base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{5}, 32))
+ }), withDeps(func(deps *app.Deps) {
+ deps.WebSearch = websearch.Endpoints{
+ Tavily: providers.URL + "/tavily", Brave: providers.URL + "/brave", YouMCP: providers.URL + "/mcp/free", Client: providers.Client(),
+ }
+ }))
+ search := func(body map[string]any) (int, []byte) {
+ t.Helper()
+ return postAgentInRoom(t, env, issued.AccessToken, roomID, "/api/agent/v1/web/search", body)
+ }
+
+ status, body := search(map[string]any{"query": "rust news"})
+ var failure agentSearchFailure
+ decode(t, body, &failure)
+ details := failure.Error.Details
+ if status != http.StatusConflict || failure.Error.Code != "search_key_requested" || details.Backend != "tavily" ||
+ details.Origin != "suggested" || details.Reason != "free_limit" || details.InteractionID == "" {
+ t.Fatalf("search after the free trial: %d %s", status, body)
+ }
+ cardID, cardMessage := details.InteractionID, details.MessageID
+
+ status, body = search(map[string]any{"query": "rust releases", "backend": "brave"})
+ decode(t, body, &failure)
+ if status != http.StatusConflict || failure.Error.Details.InteractionID != cardID || failure.Error.Details.Origin != "requested" {
+ t.Fatalf("second search: %d %s", status, body)
+ }
+ var view, request string
+ if err := env.pool.QueryRow(t.Context(), `SELECT view::text,request::text FROM decisions WHERE id=$1`, cardID).Scan(&view, &request); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(view, `"backend": "brave"`) || !strings.Contains(view, `"reason": "missing"`) || !strings.Contains(request, "rust releases") {
+ t.Fatalf("reused card view=%s request=%s", view, request)
+ }
+
+ code, _, listed := env.request(alice, http.MethodGet, "/v0/web-search/backends", nil, "")
+ var list websearch.List
+ decode(t, listed, &list)
+ if code != http.StatusOK || list.DefaultSearch != websearch.You || !list.CanSaveKeys || len(list.Backends) != 5 ||
+ list.Backends[3].ID != websearch.You || list.Backends[3].Tier != websearch.TierFreeTrial {
+ t.Fatalf("backends: %d %s", code, listed)
+ }
+
+ saveKey := func(backend, key, decisionID string) (int, []byte) {
+ t.Helper()
+ payload := map[string]any{"api_key": key}
+ if decisionID != "" {
+ payload["decision_id"] = decisionID
+ }
+ code, _, body := env.request(alice, http.MethodPut, "/v0/web-search/backends/"+backend+"/key", payload, "")
+ return code, body
+ }
+ if code, body := saveKey("brave", "brave-bad", cardID); code != http.StatusBadRequest || !strings.Contains(string(body), "WEB_SEARCH_KEY_REJECTED") {
+ t.Fatalf("refused key from the card: %d %s", code, body)
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM web_search_keys`); got != 0 {
+ t.Fatalf("a refused key was saved")
+ }
+ if got := countRows(t, env, `SELECT count(*) FROM decisions WHERE id=$1 AND status='pending'`, cardID); got != 1 {
+ t.Fatalf("a refused key ended the card")
+ }
+ if code, body := saveKey("brave", "brave-good", cardID); code != http.StatusOK || !strings.Contains(string(body), `"key_state":"verified"`) {
+ t.Fatalf("key from the card: %d %s", code, body)
+ }
+ assertBrowserCardHandoff(t, env, cardID, cardMessage, "answered", `"backend": "brave"`,
+ `The user added a Brave Search key. Results of your search for "rust releases" are in the payload below`)
+ assertBrowserCardHandoff(t, env, cardID, cardMessage, "answered", `"decision": "configured"`, `"url":"https://rust.example/news"`)
+
+ status, body = search(map[string]any{"query": "rust", "backend": "tavily"})
+ decode(t, body, &failure)
+ if status != http.StatusConflict || failure.Error.Details.InteractionID == cardID {
+ t.Fatalf("tavily search without a key: %d %s", status, body)
+ }
+ tavilyCard, tavilyMessage := failure.Error.Details.InteractionID, failure.Error.Details.MessageID
+ if code, body := saveKey("tavily", "tvly-good", ""); code != http.StatusOK || !strings.Contains(string(body), `"remaining":990`) {
+ t.Fatalf("key from Connectors: %d %s", code, body)
+ }
+ assertBrowserCardHandoff(t, env, tavilyCard, tavilyMessage, "answered", `"backend": "tavily"`,
+ "The user added a Tavily API key. Run the command again.\npayload={\"decision\":\"configured\",\"backend\":\"tavily\"}")
+
+ status, body = search(map[string]any{"query": "rust", "backend": "brave", "limit": 5})
+ if status != http.StatusOK || !strings.Contains(string(body), "release notes") {
+ t.Fatalf("search with the saved key: %d %s", status, body)
+ }
+ if status, body = search(map[string]any{"query": "rust", "backend": "brave", "sites": []string{"a.example", "b.example"}}); status != http.StatusBadRequest {
+ t.Fatalf("two sites on Brave: %d %s", status, body)
+ }
+}
diff --git a/contracts/generated/go/teamhubagentapi/openapi.gen.go b/contracts/generated/go/teamhubagentapi/openapi.gen.go
index 9aed6790..0afd7085 100644
--- a/contracts/generated/go/teamhubagentapi/openapi.gen.go
+++ b/contracts/generated/go/teamhubagentapi/openapi.gen.go
@@ -65,6 +65,8 @@ const (
AgentApiErrorCodeProviderKeyRequired AgentApiErrorCode = "provider_key_required"
AgentApiErrorCodeProviderRateLimited AgentApiErrorCode = "provider_rate_limited"
AgentApiErrorCodeProviderUnavailable AgentApiErrorCode = "provider_unavailable"
+ AgentApiErrorCodeSearchKeyRequested AgentApiErrorCode = "search_key_requested"
+ AgentApiErrorCodeSearchQuotaExhausted AgentApiErrorCode = "search_quota_exhausted"
AgentApiErrorCodeTaskFinishConflict AgentApiErrorCode = "task_finish_conflict"
AgentApiErrorCodeTaskLimitReached AgentApiErrorCode = "task_limit_reached"
AgentApiErrorCodeTeamMdDocumentInvalid AgentApiErrorCode = "team_md_document_invalid"
@@ -133,6 +135,10 @@ func (e AgentApiErrorCode) Valid() bool {
return true
case AgentApiErrorCodeProviderUnavailable:
return true
+ case AgentApiErrorCodeSearchKeyRequested:
+ return true
+ case AgentApiErrorCodeSearchQuotaExhausted:
+ return true
case AgentApiErrorCodeTaskFinishConflict:
return true
case AgentApiErrorCodeTaskLimitReached:
@@ -152,6 +158,45 @@ func (e AgentApiErrorCode) Valid() bool {
}
}
+// Defines values for AgentApiErrorDetailsOrigin.
+const (
+ AgentApiErrorDetailsOriginRequested AgentApiErrorDetailsOrigin = "requested"
+ AgentApiErrorDetailsOriginSuggested AgentApiErrorDetailsOrigin = "suggested"
+)
+
+// Valid indicates whether the value is a known member of the AgentApiErrorDetailsOrigin enum.
+func (e AgentApiErrorDetailsOrigin) Valid() bool {
+ switch e {
+ case AgentApiErrorDetailsOriginRequested:
+ return true
+ case AgentApiErrorDetailsOriginSuggested:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for AgentApiErrorDetailsReason.
+const (
+ AgentApiErrorDetailsReasonFreeLimit AgentApiErrorDetailsReason = "free_limit"
+ AgentApiErrorDetailsReasonMissing AgentApiErrorDetailsReason = "missing"
+ AgentApiErrorDetailsReasonRejected AgentApiErrorDetailsReason = "rejected"
+)
+
+// Valid indicates whether the value is a known member of the AgentApiErrorDetailsReason enum.
+func (e AgentApiErrorDetailsReason) Valid() bool {
+ switch e {
+ case AgentApiErrorDetailsReasonFreeLimit:
+ return true
+ case AgentApiErrorDetailsReasonMissing:
+ return true
+ case AgentApiErrorDetailsReasonRejected:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for AgentAppToolConfirmationPendingStatus.
const (
ConfirmationPending AgentAppToolConfirmationPendingStatus = "confirmation_pending"
@@ -1139,6 +1184,291 @@ func (e TrackingItemUpdateStatus) Valid() bool {
}
}
+// Defines values for WebConnectResponseStatus.
+const (
+ WebConnectResponseStatusConnectionRequested WebConnectResponseStatus = "connection_requested"
+ WebConnectResponseStatusReady WebConnectResponseStatus = "ready"
+)
+
+// Valid indicates whether the value is a known member of the WebConnectResponseStatus enum.
+func (e WebConnectResponseStatus) Valid() bool {
+ switch e {
+ case WebConnectResponseStatusConnectionRequested:
+ return true
+ case WebConnectResponseStatusReady:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebOpenRequestBackend.
+const (
+ WebOpenRequestBackendFirecrawl WebOpenRequestBackend = "firecrawl"
+ WebOpenRequestBackendTavily WebOpenRequestBackend = "tavily"
+ WebOpenRequestBackendYou WebOpenRequestBackend = "you"
+)
+
+// Valid indicates whether the value is a known member of the WebOpenRequestBackend enum.
+func (e WebOpenRequestBackend) Valid() bool {
+ switch e {
+ case WebOpenRequestBackendFirecrawl:
+ return true
+ case WebOpenRequestBackendTavily:
+ return true
+ case WebOpenRequestBackendYou:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendKeyState.
+const (
+ WebSearchBackendKeyStateNone WebSearchBackendKeyState = "none"
+ WebSearchBackendKeyStateRejected WebSearchBackendKeyState = "rejected"
+ WebSearchBackendKeyStateUnverified WebSearchBackendKeyState = "unverified"
+ WebSearchBackendKeyStateVerified WebSearchBackendKeyState = "verified"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendKeyState enum.
+func (e WebSearchBackendKeyState) Valid() bool {
+ switch e {
+ case WebSearchBackendKeyStateNone:
+ return true
+ case WebSearchBackendKeyStateRejected:
+ return true
+ case WebSearchBackendKeyStateUnverified:
+ return true
+ case WebSearchBackendKeyStateVerified:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendStatus.
+const (
+ WebSearchBackendStatusKeyRejected WebSearchBackendStatus = "key_rejected"
+ WebSearchBackendStatusKeyRequired WebSearchBackendStatus = "key_required"
+ WebSearchBackendStatusReady WebSearchBackendStatus = "ready"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendStatus enum.
+func (e WebSearchBackendStatus) Valid() bool {
+ switch e {
+ case WebSearchBackendStatusKeyRejected:
+ return true
+ case WebSearchBackendStatusKeyRequired:
+ return true
+ case WebSearchBackendStatusReady:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendTier.
+const (
+ WebSearchBackendTierFreeTrial WebSearchBackendTier = "free_trial"
+ WebSearchBackendTierKey WebSearchBackendTier = "key"
+ WebSearchBackendTierNone WebSearchBackendTier = "none"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendTier enum.
+func (e WebSearchBackendTier) Valid() bool {
+ switch e {
+ case WebSearchBackendTierFreeTrial:
+ return true
+ case WebSearchBackendTierKey:
+ return true
+ case WebSearchBackendTierNone:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendId.
+const (
+ WebSearchBackendIdBrave WebSearchBackendId = "brave"
+ WebSearchBackendIdDirect WebSearchBackendId = "direct"
+ WebSearchBackendIdFirecrawl WebSearchBackendId = "firecrawl"
+ WebSearchBackendIdTavily WebSearchBackendId = "tavily"
+ WebSearchBackendIdYou WebSearchBackendId = "you"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendId enum.
+func (e WebSearchBackendId) Valid() bool {
+ switch e {
+ case WebSearchBackendIdBrave:
+ return true
+ case WebSearchBackendIdDirect:
+ return true
+ case WebSearchBackendIdFirecrawl:
+ return true
+ case WebSearchBackendIdTavily:
+ return true
+ case WebSearchBackendIdYou:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchCommand.
+const (
+ WebSearchCommandOpen WebSearchCommand = "open"
+ WebSearchCommandSearch WebSearchCommand = "search"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchCommand enum.
+func (e WebSearchCommand) Valid() bool {
+ switch e {
+ case WebSearchCommandOpen:
+ return true
+ case WebSearchCommandSearch:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchFilter.
+const (
+ WebSearchFilterRecency WebSearchFilter = "recency"
+ WebSearchFilterSite WebSearchFilter = "site"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchFilter enum.
+func (e WebSearchFilter) Valid() bool {
+ switch e {
+ case WebSearchFilterRecency:
+ return true
+ case WebSearchFilterSite:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchKeyBackend.
+const (
+ WebSearchKeyBackendBrave WebSearchKeyBackend = "brave"
+ WebSearchKeyBackendFirecrawl WebSearchKeyBackend = "firecrawl"
+ WebSearchKeyBackendTavily WebSearchKeyBackend = "tavily"
+ WebSearchKeyBackendYou WebSearchKeyBackend = "you"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchKeyBackend enum.
+func (e WebSearchKeyBackend) Valid() bool {
+ switch e {
+ case WebSearchKeyBackendBrave:
+ return true
+ case WebSearchKeyBackendFirecrawl:
+ return true
+ case WebSearchKeyBackendTavily:
+ return true
+ case WebSearchKeyBackendYou:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchQuotaFrom.
+const (
+ WebSearchQuotaFromLastResponse WebSearchQuotaFrom = "last_response"
+ WebSearchQuotaFromProvider WebSearchQuotaFrom = "provider"
+ WebSearchQuotaFromUnavailable WebSearchQuotaFrom = "unavailable"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchQuotaFrom enum.
+func (e WebSearchQuotaFrom) Valid() bool {
+ switch e {
+ case WebSearchQuotaFromLastResponse:
+ return true
+ case WebSearchQuotaFromProvider:
+ return true
+ case WebSearchQuotaFromUnavailable:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchQuotaReason.
+const (
+ WebSearchQuotaReasonKeyRejected WebSearchQuotaReason = "key_rejected"
+ WebSearchQuotaReasonNoKey WebSearchQuotaReason = "no_key"
+ WebSearchQuotaReasonNotObserved WebSearchQuotaReason = "not_observed"
+ WebSearchQuotaReasonNotReported WebSearchQuotaReason = "not_reported"
+ WebSearchQuotaReasonProviderUnavailable WebSearchQuotaReason = "provider_unavailable"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchQuotaReason enum.
+func (e WebSearchQuotaReason) Valid() bool {
+ switch e {
+ case WebSearchQuotaReasonKeyRejected:
+ return true
+ case WebSearchQuotaReasonNoKey:
+ return true
+ case WebSearchQuotaReasonNotObserved:
+ return true
+ case WebSearchQuotaReasonNotReported:
+ return true
+ case WebSearchQuotaReasonProviderUnavailable:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchQuotaUnit.
+const (
+ WebSearchQuotaUnitCredits WebSearchQuotaUnit = "credits"
+ WebSearchQuotaUnitRequests WebSearchQuotaUnit = "requests"
+ WebSearchQuotaUnitUsd WebSearchQuotaUnit = "usd"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchQuotaUnit enum.
+func (e WebSearchQuotaUnit) Valid() bool {
+ switch e {
+ case WebSearchQuotaUnitCredits:
+ return true
+ case WebSearchQuotaUnitRequests:
+ return true
+ case WebSearchQuotaUnitUsd:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchRecency.
+const (
+ WebSearchRecencyDay WebSearchRecency = "day"
+ WebSearchRecencyMonth WebSearchRecency = "month"
+ WebSearchRecencyWeek WebSearchRecency = "week"
+ WebSearchRecencyYear WebSearchRecency = "year"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchRecency enum.
+func (e WebSearchRecency) Valid() bool {
+ switch e {
+ case WebSearchRecencyDay:
+ return true
+ case WebSearchRecencyMonth:
+ return true
+ case WebSearchRecencyWeek:
+ return true
+ case WebSearchRecencyYear:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for ResolveConnectorAccount200JSONResponseBodyStatus.
const (
ResolveConnectorAccount200JSONResponseBodyStatusAccountAmbiguous ResolveConnectorAccount200JSONResponseBodyStatus = "account_ambiguous"
@@ -1307,6 +1637,9 @@ type AgentApiError struct {
// Code Stable machine-readable failure classification.
Code AgentApiErrorCode `json:"code"`
+ // Details Machine-readable facts a failure carries for the CLI to act on. A search_key_requested failure names the card it posted and the backend it shows; a quota or rate limit names the backend and the other backends ready now.
+ Details *AgentApiErrorDetails `json:"details,omitempty"`
+
// Issues Safe field-level validation issues, when the failure has actionable paths.
Issues *[]AgentApiErrorIssue `json:"issues,omitempty"`
@@ -1320,6 +1653,26 @@ type AgentApiError struct {
// AgentApiErrorCode Stable machine-readable failure classification.
type AgentApiErrorCode string
+// AgentApiErrorDetails Machine-readable facts a failure carries for the CLI to act on. A search_key_requested failure names the card it posted and the backend it shows; a quota or rate limit names the backend and the other backends ready now.
+type AgentApiErrorDetails struct {
+ Backend *string `json:"backend,omitempty"`
+ InteractionId *string `json:"interaction_id,omitempty"`
+ MessageId *string `json:"message_id,omitempty"`
+
+ // Origin requested when the command named the backend the card shows; suggested when it named none and TeamHub picked one.
+ Origin *AgentApiErrorDetailsOrigin `json:"origin,omitempty"`
+ ReadyBackends *[]string `json:"ready_backends,omitempty"`
+ Reason *AgentApiErrorDetailsReason `json:"reason,omitempty"`
+ RetryAfterSeconds *int `json:"retry_after_seconds,omitempty"`
+ RoomId *string `json:"room_id,omitempty"`
+}
+
+// AgentApiErrorDetailsOrigin requested when the command named the backend the card shows; suggested when it named none and TeamHub picked one.
+type AgentApiErrorDetailsOrigin string
+
+// AgentApiErrorDetailsReason defines model for AgentApiErrorDetails.Reason.
+type AgentApiErrorDetailsReason string
+
// AgentApiErrorEnvelope Standard failure envelope for every TeamHub Agent API operation.
type AgentApiErrorEnvelope struct {
// Error Safe error detail returned by the TeamHub Agent API.
@@ -3053,6 +3406,190 @@ type TrackingItemVersion struct {
Id string `json:"id"`
}
+// WebBackendsQuery defines model for WebBackendsQuery.
+type WebBackendsQuery struct {
+ // Backend A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+ Backend *WebSearchBackendId `json:"backend,omitempty"`
+}
+
+// WebConnectRequest defines model for WebConnectRequest.
+type WebConnectRequest struct {
+ // Backend A backend that takes an API key saved in the product.
+ Backend WebSearchKeyBackend `json:"backend"`
+}
+
+// WebConnectResponse defines model for WebConnectResponse.
+type WebConnectResponse struct {
+ // Backend One backend with the static text a client shows for it and its live state. status is ready when a call would run now: direct always, You.com also without a key, the others with a key that is not rejected.
+ Backend *WebSearchBackend `json:"backend,omitempty"`
+ InteractionId *string `json:"interaction_id,omitempty"`
+ MessageId *string `json:"message_id,omitempty"`
+ RoomId *string `json:"room_id,omitempty"`
+ Status WebConnectResponseStatus `json:"status"`
+}
+
+// WebConnectResponseStatus defines model for WebConnectResponse.Status.
+type WebConnectResponseStatus string
+
+// WebOpenRequest defines model for WebOpenRequest.
+type WebOpenRequest struct {
+ // Backend A backend that opens pages; direct is fetched by the CLI.
+ Backend WebOpenRequestBackend `json:"backend"`
+ Url string `json:"url"`
+}
+
+// WebOpenRequestBackend A backend that opens pages; direct is fetched by the CLI.
+type WebOpenRequestBackend string
+
+// WebOpenResponse defines model for WebOpenResponse.
+type WebOpenResponse struct {
+ Markdown string `json:"markdown"`
+ Title *string `json:"title,omitempty"`
+
+ // Truncated True when the page was longer than the 20,000 characters returned.
+ Truncated bool `json:"truncated"`
+
+ // Url The page's final URL when the provider reports one.
+ Url string `json:"url"`
+}
+
+// WebSearchBackend One backend with the static text a client shows for it and its live state. status is ready when a call would run now: direct always, You.com also without a key, the others with a key that is not rejected.
+type WebSearchBackend struct {
+ Commands []WebSearchCommand `json:"commands"`
+
+ // Filters The search filters the backend honors; any other is refused before a call.
+ Filters []WebSearchFilter `json:"filters"`
+
+ // FreeTier The provider's free allowance, for display.
+ FreeTier *string `json:"free_tier,omitempty"`
+
+ // Id A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+ Id WebSearchBackendId `json:"id"`
+ KeyState WebSearchBackendKeyState `json:"key_state"`
+
+ // KeyUrl Where the Human gets a key.
+ KeyUrl *string `json:"key_url,omitempty"`
+
+ // Keyless Whether the backend works without a saved key.
+ Keyless bool `json:"keyless"`
+
+ // MaxLimit The most results one search returns; 0 for a backend without search.
+ MaxLimit int `json:"max_limit"`
+
+ // MaxSites How many sites one search may name; 0 when it takes no site filter.
+ MaxSites int `json:"max_sites"`
+ Name string `json:"name"`
+
+ // OfficialKeyCheck Whether the provider has an official endpoint TeamHub checks a key with before saving it. Without one the key is saved unverified and proven by its first call.
+ OfficialKeyCheck bool `json:"official_key_check"`
+
+ // Quota What is left on the backend's account. from says where the numbers came from: provider is the provider's official usage endpoint read for this response; last_response is the rate-limit headers of the last call (Brave), as of observed_at; unavailable carries no numbers and reason says why.
+ Quota WebSearchQuota `json:"quota"`
+ Status WebSearchBackendStatus `json:"status"`
+
+ // Tier How a call to the backend runs now. key: with an API key saved in the product (or one it still needs); free_trial: You.com without a key, a limited trial with lower quality results that TeamHub does not count; none: direct, which needs no account.
+ Tier WebSearchBackendTier `json:"tier"`
+
+ // TierText A short display line for the tier, set for free_trial.
+ TierText *string `json:"tier_text,omitempty"`
+}
+
+// WebSearchBackendKeyState defines model for WebSearchBackend.KeyState.
+type WebSearchBackendKeyState string
+
+// WebSearchBackendStatus defines model for WebSearchBackend.Status.
+type WebSearchBackendStatus string
+
+// WebSearchBackendTier How a call to the backend runs now. key: with an API key saved in the product (or one it still needs); free_trial: You.com without a key, a limited trial with lower quality results that TeamHub does not count; none: direct, which needs no account.
+type WebSearchBackendTier string
+
+// WebSearchBackendId A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+type WebSearchBackendId string
+
+// WebSearchBackendList Every backend in TeamHub's default order. default_search is the backend a search without one uses now: the default a Human saved (chosen_default_search) even when its key stopped working, else the first ready backend in that order.
+type WebSearchBackendList struct {
+ Backends []WebSearchBackend `json:"backends"`
+
+ // CanSaveKeys False when the deployment has no TEAMHUB_SECRET_ENCRYPTION_KEY to seal keys with.
+ CanSaveKeys bool `json:"can_save_keys"`
+
+ // ChosenDefaultSearch A backend that takes an API key saved in the product.
+ ChosenDefaultSearch *WebSearchKeyBackend `json:"chosen_default_search,omitempty"`
+ DefaultOpen string `json:"default_open"`
+
+ // DefaultSearch A backend that takes an API key saved in the product.
+ DefaultSearch WebSearchKeyBackend `json:"default_search"`
+}
+
+// WebSearchCommand defines model for WebSearchCommand.
+type WebSearchCommand string
+
+// WebSearchFilter defines model for WebSearchFilter.
+type WebSearchFilter string
+
+// WebSearchKeyBackend A backend that takes an API key saved in the product.
+type WebSearchKeyBackend string
+
+// WebSearchQuota What is left on the backend's account. from says where the numbers came from: provider is the provider's official usage endpoint read for this response; last_response is the rate-limit headers of the last call (Brave), as of observed_at; unavailable carries no numbers and reason says why.
+type WebSearchQuota struct {
+ From WebSearchQuotaFrom `json:"from"`
+
+ // Limit Absent when the provider reports no cap.
+ Limit *float32 `json:"limit,omitempty"`
+
+ // ObservedAt UTC timestamp in RFC 3339 format with an explicit offset.
+ ObservedAt *Timestamp `json:"observed_at,omitempty"`
+ Plan *string `json:"plan,omitempty"`
+
+ // Reason no_key: no key is saved; not_reported: there is no usage endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet; key_rejected: the provider refused the saved key; provider_unavailable: the usage endpoint did not answer in time.
+ Reason *WebSearchQuotaReason `json:"reason,omitempty"`
+ Remaining *float32 `json:"remaining,omitempty"`
+
+ // ResetsAt UTC timestamp in RFC 3339 format with an explicit offset.
+ ResetsAt *Timestamp `json:"resets_at,omitempty"`
+ Unit *WebSearchQuotaUnit `json:"unit,omitempty"`
+}
+
+// WebSearchQuotaFrom defines model for WebSearchQuota.From.
+type WebSearchQuotaFrom string
+
+// WebSearchQuotaReason no_key: no key is saved; not_reported: there is no usage endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet; key_rejected: the provider refused the saved key; provider_unavailable: the usage endpoint did not answer in time.
+type WebSearchQuotaReason string
+
+// WebSearchQuotaUnit defines model for WebSearchQuota.Unit.
+type WebSearchQuotaUnit string
+
+// WebSearchRecency defines model for WebSearchRecency.
+type WebSearchRecency string
+
+// WebSearchRequest defines model for WebSearchRequest.
+type WebSearchRequest struct {
+ // Backend A backend that takes an API key saved in the product.
+ Backend *WebSearchKeyBackend `json:"backend,omitempty"`
+
+ // Limit Defaults to 10.
+ Limit *int `json:"limit,omitempty"`
+ Query string `json:"query"`
+ Recency *WebSearchRecency `json:"recency,omitempty"`
+
+ // Sites Hostnames to search within, up to the backend's max_sites.
+ Sites *[]string `json:"sites,omitempty"`
+}
+
+// WebSearchResponse defines model for WebSearchResponse.
+type WebSearchResponse struct {
+ Results []WebSearchResult `json:"results"`
+}
+
+// WebSearchResult defines model for WebSearchResult.
+type WebSearchResult struct {
+ // PublishedAt The page date as the provider reports it.
+ PublishedAt *string `json:"published_at,omitempty"`
+ Snippet string `json:"snippet"`
+ Title string `json:"title"`
+ Url string `json:"url"`
+}
+
// CLIFileDocumentId defines model for CLIFileDocumentId.
type CLIFileDocumentId = string
@@ -3399,6 +3936,18 @@ type UpdateAgentTrackingItemJSONRequestBody = TrackingItemUpdate
// AskAgentUserJSONRequestBody defines body for AskAgentUser for application/json ContentType.
type AskAgentUserJSONRequestBody = AgentAskUserRequest
+// ListAgentWebBackendsJSONRequestBody defines body for ListAgentWebBackends for application/json ContentType.
+type ListAgentWebBackendsJSONRequestBody = WebBackendsQuery
+
+// ConnectAgentWebBackendJSONRequestBody defines body for ConnectAgentWebBackend for application/json ContentType.
+type ConnectAgentWebBackendJSONRequestBody = WebConnectRequest
+
+// OpenAgentWebPageJSONRequestBody defines body for OpenAgentWebPage for application/json ContentType.
+type OpenAgentWebPageJSONRequestBody = WebOpenRequest
+
+// SearchAgentWebJSONRequestBody defines body for SearchAgentWeb for application/json ContentType.
+type SearchAgentWebJSONRequestBody = WebSearchRequest
+
// AsAgentTextMessageSegment returns the union data inside the AgentCreationMessageSegment as a AgentTextMessageSegment
func (t AgentCreationMessageSegment) AsAgentTextMessageSegment() (AgentTextMessageSegment, error) {
var body AgentTextMessageSegment
diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.go
index 1fa92851..4a82cc97 100644
--- a/contracts/generated/go/teamhubpublic/openapi.gen.go
+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go
@@ -906,6 +906,7 @@ const (
DecisionKindQuestion DecisionKind = "question"
DecisionKindRoomCreation DecisionKind = "room_creation"
DecisionKindRuntimePermission DecisionKind = "runtime_permission"
+ DecisionKindSearchKey DecisionKind = "search_key"
)
// Valid indicates whether the value is a known member of the DecisionKind enum.
@@ -933,6 +934,8 @@ func (e DecisionKind) Valid() bool {
return true
case DecisionKindRuntimePermission:
return true
+ case DecisionKindSearchKey:
+ return true
default:
return false
}
@@ -3545,6 +3548,45 @@ func (e RuntimePermissionDecisionViewKind) Valid() bool {
}
}
+// Defines values for SearchKeyDecisionViewOrigin.
+const (
+ SearchKeyDecisionViewOriginRequested SearchKeyDecisionViewOrigin = "requested"
+ SearchKeyDecisionViewOriginSuggested SearchKeyDecisionViewOrigin = "suggested"
+)
+
+// Valid indicates whether the value is a known member of the SearchKeyDecisionViewOrigin enum.
+func (e SearchKeyDecisionViewOrigin) Valid() bool {
+ switch e {
+ case SearchKeyDecisionViewOriginRequested:
+ return true
+ case SearchKeyDecisionViewOriginSuggested:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for SearchKeyDecisionViewReason.
+const (
+ SearchKeyDecisionViewReasonFreeLimit SearchKeyDecisionViewReason = "free_limit"
+ SearchKeyDecisionViewReasonMissing SearchKeyDecisionViewReason = "missing"
+ SearchKeyDecisionViewReasonRejected SearchKeyDecisionViewReason = "rejected"
+)
+
+// Valid indicates whether the value is a known member of the SearchKeyDecisionViewReason enum.
+func (e SearchKeyDecisionViewReason) Valid() bool {
+ switch e {
+ case SearchKeyDecisionViewReasonFreeLimit:
+ return true
+ case SearchKeyDecisionViewReasonMissing:
+ return true
+ case SearchKeyDecisionViewReasonRejected:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for SetDocumentLinkShareRole.
const (
Editor SetDocumentLinkShareRole = "editor"
@@ -4046,6 +4088,228 @@ func (e VoiceTranscriptEventKind) Valid() bool {
}
}
+// Defines values for WebSearchBackendKeyState.
+const (
+ WebSearchBackendKeyStateNone WebSearchBackendKeyState = "none"
+ WebSearchBackendKeyStateRejected WebSearchBackendKeyState = "rejected"
+ WebSearchBackendKeyStateUnverified WebSearchBackendKeyState = "unverified"
+ WebSearchBackendKeyStateVerified WebSearchBackendKeyState = "verified"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendKeyState enum.
+func (e WebSearchBackendKeyState) Valid() bool {
+ switch e {
+ case WebSearchBackendKeyStateNone:
+ return true
+ case WebSearchBackendKeyStateRejected:
+ return true
+ case WebSearchBackendKeyStateUnverified:
+ return true
+ case WebSearchBackendKeyStateVerified:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendStatus.
+const (
+ WebSearchBackendStatusKeyRejected WebSearchBackendStatus = "key_rejected"
+ WebSearchBackendStatusKeyRequired WebSearchBackendStatus = "key_required"
+ WebSearchBackendStatusReady WebSearchBackendStatus = "ready"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendStatus enum.
+func (e WebSearchBackendStatus) Valid() bool {
+ switch e {
+ case WebSearchBackendStatusKeyRejected:
+ return true
+ case WebSearchBackendStatusKeyRequired:
+ return true
+ case WebSearchBackendStatusReady:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendTier.
+const (
+ WebSearchBackendTierFreeTrial WebSearchBackendTier = "free_trial"
+ WebSearchBackendTierKey WebSearchBackendTier = "key"
+ WebSearchBackendTierNone WebSearchBackendTier = "none"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendTier enum.
+func (e WebSearchBackendTier) Valid() bool {
+ switch e {
+ case WebSearchBackendTierFreeTrial:
+ return true
+ case WebSearchBackendTierKey:
+ return true
+ case WebSearchBackendTierNone:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchBackendId.
+const (
+ WebSearchBackendIdBrave WebSearchBackendId = "brave"
+ WebSearchBackendIdDirect WebSearchBackendId = "direct"
+ WebSearchBackendIdFirecrawl WebSearchBackendId = "firecrawl"
+ WebSearchBackendIdTavily WebSearchBackendId = "tavily"
+ WebSearchBackendIdYou WebSearchBackendId = "you"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchBackendId enum.
+func (e WebSearchBackendId) Valid() bool {
+ switch e {
+ case WebSearchBackendIdBrave:
+ return true
+ case WebSearchBackendIdDirect:
+ return true
+ case WebSearchBackendIdFirecrawl:
+ return true
+ case WebSearchBackendIdTavily:
+ return true
+ case WebSearchBackendIdYou:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchCommand.
+const (
+ WebSearchCommandOpen WebSearchCommand = "open"
+ WebSearchCommandSearch WebSearchCommand = "search"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchCommand enum.
+func (e WebSearchCommand) Valid() bool {
+ switch e {
+ case WebSearchCommandOpen:
+ return true
+ case WebSearchCommandSearch:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchFilter.
+const (
+ WebSearchFilterRecency WebSearchFilter = "recency"
+ WebSearchFilterSite WebSearchFilter = "site"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchFilter enum.
+func (e WebSearchFilter) Valid() bool {
+ switch e {
+ case WebSearchFilterRecency:
+ return true
+ case WebSearchFilterSite:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchKeyBackend.
+const (
+ WebSearchKeyBackendBrave WebSearchKeyBackend = "brave"
+ WebSearchKeyBackendFirecrawl WebSearchKeyBackend = "firecrawl"
+ WebSearchKeyBackendTavily WebSearchKeyBackend = "tavily"
+ WebSearchKeyBackendYou WebSearchKeyBackend = "you"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchKeyBackend enum.
+func (e WebSearchKeyBackend) Valid() bool {
+ switch e {
+ case WebSearchKeyBackendBrave:
+ return true
+ case WebSearchKeyBackendFirecrawl:
+ return true
+ case WebSearchKeyBackendTavily:
+ return true
+ case WebSearchKeyBackendYou:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchQuotaFrom.
+const (
+ WebSearchQuotaFromLastResponse WebSearchQuotaFrom = "last_response"
+ WebSearchQuotaFromProvider WebSearchQuotaFrom = "provider"
+ WebSearchQuotaFromUnavailable WebSearchQuotaFrom = "unavailable"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchQuotaFrom enum.
+func (e WebSearchQuotaFrom) Valid() bool {
+ switch e {
+ case WebSearchQuotaFromLastResponse:
+ return true
+ case WebSearchQuotaFromProvider:
+ return true
+ case WebSearchQuotaFromUnavailable:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchQuotaReason.
+const (
+ WebSearchQuotaReasonKeyRejected WebSearchQuotaReason = "key_rejected"
+ WebSearchQuotaReasonNoKey WebSearchQuotaReason = "no_key"
+ WebSearchQuotaReasonNotObserved WebSearchQuotaReason = "not_observed"
+ WebSearchQuotaReasonNotReported WebSearchQuotaReason = "not_reported"
+ WebSearchQuotaReasonProviderUnavailable WebSearchQuotaReason = "provider_unavailable"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchQuotaReason enum.
+func (e WebSearchQuotaReason) Valid() bool {
+ switch e {
+ case WebSearchQuotaReasonKeyRejected:
+ return true
+ case WebSearchQuotaReasonNoKey:
+ return true
+ case WebSearchQuotaReasonNotObserved:
+ return true
+ case WebSearchQuotaReasonNotReported:
+ return true
+ case WebSearchQuotaReasonProviderUnavailable:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for WebSearchQuotaUnit.
+const (
+ WebSearchQuotaUnitCredits WebSearchQuotaUnit = "credits"
+ WebSearchQuotaUnitRequests WebSearchQuotaUnit = "requests"
+ WebSearchQuotaUnitUsd WebSearchQuotaUnit = "usd"
+)
+
+// Valid indicates whether the value is a known member of the WebSearchQuotaUnit enum.
+func (e WebSearchQuotaUnit) Valid() bool {
+ switch e {
+ case WebSearchQuotaUnitCredits:
+ return true
+ case WebSearchQuotaUnitRequests:
+ return true
+ case WebSearchQuotaUnitUsd:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for WorkItemActivityKind.
const (
WorkItemActivityKindAccessGrantAdded WorkItemActivityKind = "access_grant_added"
@@ -5148,20 +5412,23 @@ type DecisionAnswer struct {
// AttachmentUploadIds Message attachment uploads a profile_setup_sources "done" answer attaches to the Human's message; same rules as message creation.
AttachmentUploadIds *[]AttachmentUploadToken `json:"attachment_upload_ids,omitempty"`
+ // Backend A backend that takes an API key saved in the product.
+ Backend *WebSearchKeyBackend `json:"backend,omitempty"`
+
// Comment The reason given with a denial, or a note with a question's answers.
Comment *string `json:"comment,omitempty"`
// ConnectionId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
ConnectionId *Id `json:"connection_id,omitempty"`
- // Decision approve or deny for connector_write, agent_change, runtime_permission, connection_auth and room_creation; deny or connected (recorded by TeamHub once the owner connects Chrome) for browser_connection; deny or configured (recorded by TeamHub once a Composio key is saved) for provider_key; deny or granted (recorded by TeamHub once the Computer reports every permission granted) for computer_permission; submit for question; connected or skipped for profile_setup_apps; done or skipped for profile_setup_sources.
+ // Decision approve or deny for connector_write, agent_change, runtime_permission, connection_auth and room_creation; deny or connected (recorded by TeamHub once the owner connects Chrome) for browser_connection; deny or configured (recorded by TeamHub once a Composio key is saved) for provider_key and search_key (with the backend whose key was saved); deny or granted (recorded by TeamHub once the Computer reports every permission granted) for computer_permission; submit for question; connected or skipped for profile_setup_apps; done or skipped for profile_setup_sources.
Decision DecisionAnswerDecision `json:"decision"`
// Links Absolute http(s) URLs a profile_setup_sources "done" answer shares; trimmed and deduplicated by TeamHub.
Links *[]string `json:"links,omitempty"`
}
-// DecisionAnswerDecision approve or deny for connector_write, agent_change, runtime_permission, connection_auth and room_creation; deny or connected (recorded by TeamHub once the owner connects Chrome) for browser_connection; deny or configured (recorded by TeamHub once a Composio key is saved) for provider_key; deny or granted (recorded by TeamHub once the Computer reports every permission granted) for computer_permission; submit for question; connected or skipped for profile_setup_apps; done or skipped for profile_setup_sources.
+// DecisionAnswerDecision approve or deny for connector_write, agent_change, runtime_permission, connection_auth and room_creation; deny or connected (recorded by TeamHub once the owner connects Chrome) for browser_connection; deny or configured (recorded by TeamHub once a Composio key is saved) for provider_key and search_key (with the backend whose key was saved); deny or granted (recorded by TeamHub once the Computer reports every permission granted) for computer_permission; submit for question; connected or skipped for profile_setup_apps; done or skipped for profile_setup_sources.
type DecisionAnswerDecision string
// DecisionAnswerValue A radio or checkbox answer names option ids. Any other value is the Human's own written answer, which every option question accepts, so a checkbox answer holds up to 20 options and one written answer.
@@ -5272,7 +5539,10 @@ type DecisionRequestedMessageCard struct {
// RuntimePermission The view of a runtime_permission decision: a tool call that needs the sponsor's approval. title is built by rules from the call and host evidence, never by the judge model; tool and input are the full call.
RuntimePermission *RuntimePermissionDecisionView `json:"runtime_permission,omitempty"`
- // Status For connector_write and agent_change, approved and executing mean TeamHub is running the approved request, and unknown means a run stopped midway and may have taken effect; TeamHub does not run it again. A question or AnotherMe setup card ends answered. An approved runtime_permission lets the Agent retry that one call until expires_at, and ends consumed once it does. An approved connection_auth is authorizing until the OAuth it started completes (succeeded), fails, or expires. A provider_key ends answered when someone saves a Composio key, denied when its Human declines. A browser_connection ends answered when its owner connects, denied when they decline. A room_creation ends succeeded with its Room created, or denied. A computer_permission ends answered once every permission it asks for is granted, denied when its owner declines.
+ // SearchKey The view of a search_key decision: the web search backend the card shows. origin is requested when the Agent's command named it, and suggested when the command named none and nothing was usable, so TeamHub picked the first backend in its order that still needs a key. reason says why: no key is saved (missing), the provider refused the saved one (rejected), or the keyless You.com searches are used up (free_limit). The Human may add a key for any other backend instead; saving any web search key answers the card configured with that backend.
+ SearchKey *SearchKeyDecisionView `json:"search_key,omitempty"`
+
+ // Status For connector_write and agent_change, approved and executing mean TeamHub is running the approved request, and unknown means a run stopped midway and may have taken effect; TeamHub does not run it again. A question or AnotherMe setup card ends answered. An approved runtime_permission lets the Agent retry that one call until expires_at, and ends consumed once it does. An approved connection_auth is authorizing until the OAuth it started completes (succeeded), fails, or expires. A provider_key ends answered when someone saves a Composio key, denied when its Human declines. A browser_connection ends answered when its owner connects, denied when they decline. A room_creation ends succeeded with its Room created, or denied. A computer_permission ends answered once every permission it asks for is granted, denied when its owner declines. A search_key ends answered when someone saves any web search key, denied when its Human declines.
Status DecisionStatus `json:"status"`
// Title What the card asks; a question card's prompt.
@@ -5280,7 +5550,7 @@ type DecisionRequestedMessageCard struct {
Version int64 `json:"version"`
}
-// DecisionStatus For connector_write and agent_change, approved and executing mean TeamHub is running the approved request, and unknown means a run stopped midway and may have taken effect; TeamHub does not run it again. A question or AnotherMe setup card ends answered. An approved runtime_permission lets the Agent retry that one call until expires_at, and ends consumed once it does. An approved connection_auth is authorizing until the OAuth it started completes (succeeded), fails, or expires. A provider_key ends answered when someone saves a Composio key, denied when its Human declines. A browser_connection ends answered when its owner connects, denied when they decline. A room_creation ends succeeded with its Room created, or denied. A computer_permission ends answered once every permission it asks for is granted, denied when its owner declines.
+// DecisionStatus For connector_write and agent_change, approved and executing mean TeamHub is running the approved request, and unknown means a run stopped midway and may have taken effect; TeamHub does not run it again. A question or AnotherMe setup card ends answered. An approved runtime_permission lets the Agent retry that one call until expires_at, and ends consumed once it does. An approved connection_auth is authorizing until the OAuth it started completes (succeeded), fails, or expires. A provider_key ends answered when someone saves a Composio key, denied when its Human declines. A browser_connection ends answered when its owner connects, denied when they decline. A room_creation ends succeeded with its Room created, or denied. A computer_permission ends answered once every permission it asks for is granted, denied when its owner declines. A search_key ends answered when someone saves any web search key, denied when its Human declines.
type DecisionStatus string
// DirectRoomOpenRequest defines model for DirectRoomOpenRequest.
@@ -8443,6 +8713,28 @@ type SaveVoiceProviderKeyRequest struct {
ApiKey string `json:"api_key"`
}
+// SaveWebSearchKeyRequest defines model for SaveWebSearchKeyRequest.
+type SaveWebSearchKeyRequest struct {
+ ApiKey string `json:"api_key"`
+
+ // DecisionId The search_key card the key is added from. TeamHub then runs the search or page open that card was posted for against this backend with the new key before saving it, and answers the card with what that call returned. Without it, or for a card posted by a connect request, the key gets the official check.
+ DecisionId *string `json:"decision_id,omitempty"`
+}
+
+// SearchKeyDecisionView The view of a search_key decision: the web search backend the card shows. origin is requested when the Agent's command named it, and suggested when the command named none and nothing was usable, so TeamHub picked the first backend in its order that still needs a key. reason says why: no key is saved (missing), the provider refused the saved one (rejected), or the keyless You.com searches are used up (free_limit). The Human may add a key for any other backend instead; saving any web search key answers the card configured with that backend.
+type SearchKeyDecisionView struct {
+ // Backend A backend that takes an API key saved in the product.
+ Backend WebSearchKeyBackend `json:"backend"`
+ Origin SearchKeyDecisionViewOrigin `json:"origin"`
+ Reason SearchKeyDecisionViewReason `json:"reason"`
+}
+
+// SearchKeyDecisionViewOrigin defines model for SearchKeyDecisionView.Origin.
+type SearchKeyDecisionViewOrigin string
+
+// SearchKeyDecisionViewReason defines model for SearchKeyDecisionView.Reason.
+type SearchKeyDecisionViewReason string
+
// SendMailCanvasRequest defines model for SendMailCanvasRequest.
type SendMailCanvasRequest struct {
// ConnectionId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
@@ -8487,6 +8779,12 @@ type SetExternalConnectionAutoRemindersRequest struct {
Enabled bool `json:"enabled"`
}
+// SetWebSearchDefaultRequest defines model for SetWebSearchDefaultRequest.
+type SetWebSearchDefaultRequest struct {
+ // Backend A backend that takes an API key saved in the product.
+ Backend WebSearchKeyBackend `json:"backend"`
+}
+
// Sha256 defines model for Sha256.
type Sha256 = string
@@ -9291,6 +9589,121 @@ type VoiceTranscriptEventPage struct {
PartialTranscript *string `json:"partial_transcript,omitempty"`
}
+// WebSearchBackend One backend with the static text a client shows for it and its live state. status is ready when a call would run now: direct always, You.com also without a key, the others with a key that is not rejected.
+type WebSearchBackend struct {
+ Commands []WebSearchCommand `json:"commands"`
+
+ // Filters The search filters the backend honors; any other is refused before a call.
+ Filters []WebSearchFilter `json:"filters"`
+
+ // FreeTier The provider's free allowance, for display.
+ FreeTier *string `json:"free_tier,omitempty"`
+
+ // Id A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+ Id WebSearchBackendId `json:"id"`
+ KeyState WebSearchBackendKeyState `json:"key_state"`
+
+ // KeyUrl Where the Human gets a key.
+ KeyUrl *string `json:"key_url,omitempty"`
+
+ // Keyless Whether the backend works without a saved key.
+ Keyless bool `json:"keyless"`
+
+ // MaxLimit The most results one search returns; 0 for a backend without search.
+ MaxLimit int `json:"max_limit"`
+
+ // MaxSites How many sites one search may name; 0 when it takes no site filter.
+ MaxSites int `json:"max_sites"`
+ Name string `json:"name"`
+
+ // OfficialKeyCheck Whether the provider has an official endpoint TeamHub checks a key with before saving it. Without one the key is saved unverified and proven by its first call.
+ OfficialKeyCheck bool `json:"official_key_check"`
+
+ // Quota What is left on the backend's account. from says where the numbers came from: provider is the provider's official usage endpoint read for this response; last_response is the rate-limit headers of the last call (Brave), as of observed_at; unavailable carries no numbers and reason says why.
+ Quota WebSearchQuota `json:"quota"`
+ Status WebSearchBackendStatus `json:"status"`
+
+ // Tier How a call to the backend runs now. key: with an API key saved in the product (or one it still needs); free_trial: You.com without a key, a limited trial with lower quality results that TeamHub does not count; none: direct, which needs no account.
+ Tier WebSearchBackendTier `json:"tier"`
+
+ // TierText A short display line for the tier, set for free_trial.
+ TierText *string `json:"tier_text,omitempty"`
+}
+
+// WebSearchBackendKeyState defines model for WebSearchBackend.KeyState.
+type WebSearchBackendKeyState string
+
+// WebSearchBackendStatus defines model for WebSearchBackend.Status.
+type WebSearchBackendStatus string
+
+// WebSearchBackendTier How a call to the backend runs now. key: with an API key saved in the product (or one it still needs); free_trial: You.com without a key, a limited trial with lower quality results that TeamHub does not count; none: direct, which needs no account.
+type WebSearchBackendTier string
+
+// WebSearchBackendId A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+type WebSearchBackendId string
+
+// WebSearchBackendList Every backend in TeamHub's default order. default_search is the backend a search without one uses now: the default a Human saved (chosen_default_search) even when its key stopped working, else the first ready backend in that order.
+type WebSearchBackendList struct {
+ Backends []WebSearchBackend `json:"backends"`
+
+ // CanSaveKeys False when the deployment has no TEAMHUB_SECRET_ENCRYPTION_KEY to seal keys with.
+ CanSaveKeys bool `json:"can_save_keys"`
+
+ // ChosenDefaultSearch A backend that takes an API key saved in the product.
+ ChosenDefaultSearch *WebSearchKeyBackend `json:"chosen_default_search,omitempty"`
+ DefaultOpen string `json:"default_open"`
+
+ // DefaultSearch A backend that takes an API key saved in the product.
+ DefaultSearch WebSearchKeyBackend `json:"default_search"`
+}
+
+// WebSearchCommand defines model for WebSearchCommand.
+type WebSearchCommand string
+
+// WebSearchDefault defines model for WebSearchDefault.
+type WebSearchDefault struct {
+ // ChosenDefaultSearch A backend that takes an API key saved in the product.
+ ChosenDefaultSearch *WebSearchKeyBackend `json:"chosen_default_search,omitempty"`
+
+ // DefaultSearch A backend that takes an API key saved in the product.
+ DefaultSearch WebSearchKeyBackend `json:"default_search"`
+}
+
+// WebSearchFilter defines model for WebSearchFilter.
+type WebSearchFilter string
+
+// WebSearchKeyBackend A backend that takes an API key saved in the product.
+type WebSearchKeyBackend string
+
+// WebSearchQuota What is left on the backend's account. from says where the numbers came from: provider is the provider's official usage endpoint read for this response; last_response is the rate-limit headers of the last call (Brave), as of observed_at; unavailable carries no numbers and reason says why.
+type WebSearchQuota struct {
+ From WebSearchQuotaFrom `json:"from"`
+
+ // Limit Absent when the provider reports no cap.
+ Limit *float32 `json:"limit,omitempty"`
+
+ // ObservedAt UTC timestamp in RFC 3339 format with an explicit offset.
+ ObservedAt *Timestamp `json:"observed_at,omitempty"`
+ Plan *string `json:"plan,omitempty"`
+
+ // Reason no_key: no key is saved; not_reported: there is no usage endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet; key_rejected: the provider refused the saved key; provider_unavailable: the usage endpoint did not answer in time.
+ Reason *WebSearchQuotaReason `json:"reason,omitempty"`
+ Remaining *float32 `json:"remaining,omitempty"`
+
+ // ResetsAt UTC timestamp in RFC 3339 format with an explicit offset.
+ ResetsAt *Timestamp `json:"resets_at,omitempty"`
+ Unit *WebSearchQuotaUnit `json:"unit,omitempty"`
+}
+
+// WebSearchQuotaFrom defines model for WebSearchQuota.From.
+type WebSearchQuotaFrom string
+
+// WebSearchQuotaReason no_key: no key is saved; not_reported: there is no usage endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet; key_rejected: the provider refused the saved key; provider_unavailable: the usage endpoint did not answer in time.
+type WebSearchQuotaReason string
+
+// WebSearchQuotaUnit defines model for WebSearchQuota.Unit.
+type WebSearchQuotaUnit string
+
// WorkItem defines model for WorkItem.
type WorkItem struct {
// ArchivedAt UTC timestamp in RFC 3339 format with an explicit offset.
@@ -10347,6 +10760,12 @@ type StartVoiceCaptureJSONRequestBody = VoiceCaptureStartRequest
// CommitVoiceDictationTurnJSONRequestBody defines body for CommitVoiceDictationTurn for application/json ContentType.
type CommitVoiceDictationTurnJSONRequestBody = VoiceDictationCommitRequest
+// SaveWebSearchKeyJSONRequestBody defines body for SaveWebSearchKey for application/json ContentType.
+type SaveWebSearchKeyJSONRequestBody = SaveWebSearchKeyRequest
+
+// SetWebSearchDefaultJSONRequestBody defines body for SetWebSearchDefault for application/json ContentType.
+type SetWebSearchDefaultJSONRequestBody = SetWebSearchDefaultRequest
+
// UpdateWorkItemJSONRequestBody defines body for UpdateWorkItem for application/json ContentType.
type UpdateWorkItemJSONRequestBody = WorkItemUpdateRequest
diff --git a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts
index 9a93288d..e394b50e 100644
--- a/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-agent-api/types.ts
@@ -849,6 +849,86 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/agent/v1/web/search": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Search the web through one backend with the deployment's saved key.
+ * @description Without backend, TeamHub uses the default a Human chose exactly as if the request named it, even when its key stopped working; without a chosen default it uses the first ready backend in the order tavily, brave, firecrawl, you (with a key), then You.com's keyless free tier, and details.origin is suggested. A filter the backend cannot honor is refused before any call. There is no automatic fallback to another backend. When the backend needs a key the deployment lacks, or the provider refused the saved one, or the keyless You.com searches are used up, TeamHub posts (or reuses) a search_key card in the chat and answers 409 search_key_requested; details names the card and the backend it shows. Saving any web search key answers the card and wakes the Agent with the backend to use.
+ */
+ post: operations["searchAgentWeb"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/agent/v1/web/open": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Read one web page as Markdown through a provider backend.
+ * @description Only provider backends open pages here; the CLI fetches direct itself, so TeamHub never requests the page URL. The Markdown is cut at 20,000 characters. Key failures post a search_key card as search does.
+ */
+ post: operations["openAgentWebPage"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/agent/v1/web/backends/query": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * List the web search backends with their state and live quota.
+ * @description Quota is read from each provider's official usage endpoint for this request, in parallel and briefly; a provider that does not answer in time reports quota from=unavailable. backend narrows the list to one.
+ */
+ post: operations["listAgentWebBackends"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/api/agent/v1/web/connect": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /**
+ * Make one web search backend usable, asking the Human for its key through a chat card.
+ * @description A ready backend answers ready with its state and live quota. A backend without a usable key gets a search_key card in the chat (an open one is reused) and answers connection_requested. Saving any web search key answers the card and wakes the Agent with the backend that was configured.
+ */
+ post: operations["connectAgentWebBackend"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/agent/v1/computer/browser-connection": {
parameters: {
query?: never;
@@ -1654,6 +1734,8 @@ export interface components {
| "connection_not_active"
| "app_not_connected"
| "provider_key_required"
+ | "search_key_requested"
+ | "search_quota_exhausted"
| "tool_not_found"
| "invalid_tool_arguments"
| "provider_auth_failed"
@@ -1669,6 +1751,22 @@ export interface components {
code: string;
message: string;
};
+ /** @description Machine-readable facts a failure carries for the CLI to act on. A search_key_requested failure names the card it posted and the backend it shows; a quota or rate limit names the backend and the other backends ready now. */
+ AgentApiErrorDetails: {
+ backend?: string;
+ /**
+ * @description requested when the command named the backend the card shows; suggested when it named none and TeamHub picked one.
+ * @enum {string}
+ */
+ origin?: "requested" | "suggested";
+ /** @enum {string} */
+ reason?: "missing" | "rejected" | "free_limit";
+ room_id?: string;
+ message_id?: string;
+ interaction_id?: string;
+ ready_backends?: string[];
+ retry_after_seconds?: number;
+ };
/** @description Safe error detail returned by the TeamHub Agent API. */
AgentApiError: {
code: components["schemas"]["AgentApiErrorCode"];
@@ -1678,6 +1776,7 @@ export interface components {
request_id: string;
/** @description Safe field-level validation issues, when the failure has actionable paths. */
issues?: components["schemas"]["AgentApiErrorIssue"][];
+ details?: components["schemas"]["AgentApiErrorDetails"];
};
/** @description Standard failure envelope for every TeamHub Agent API operation. */
AgentApiErrorEnvelope: {
@@ -2597,6 +2696,145 @@ export interface components {
/** @description Agent-only Room Message that announces the protocol and carries the Mentions. */
message_id: components["schemas"]["Id"];
};
+ /**
+ * @description A backend that takes an API key saved in the product.
+ * @enum {string}
+ */
+ WebSearchKeyBackend: "tavily" | "brave" | "firecrawl" | "you";
+ /** @enum {string} */
+ WebSearchRecency: "day" | "week" | "month" | "year";
+ WebSearchRequest: {
+ query: string;
+ backend?: components["schemas"]["WebSearchKeyBackend"];
+ /** @description Defaults to 10. */
+ limit?: number;
+ recency?: components["schemas"]["WebSearchRecency"];
+ /** @description Hostnames to search within, up to the backend's max_sites. */
+ sites?: string[];
+ };
+ WebSearchResult: {
+ title: string;
+ /** Format: uri */
+ url: string;
+ snippet: string;
+ /** @description The page date as the provider reports it. */
+ published_at?: string;
+ };
+ WebSearchResponse: {
+ results: components["schemas"]["WebSearchResult"][];
+ };
+ WebOpenRequest: {
+ /** Format: uri */
+ url: string;
+ /**
+ * @description A backend that opens pages; direct is fetched by the CLI.
+ * @enum {string}
+ */
+ backend: "tavily" | "firecrawl" | "you";
+ };
+ WebOpenResponse: {
+ /**
+ * Format: uri
+ * @description The page's final URL when the provider reports one.
+ */
+ url: string;
+ title?: string;
+ markdown: string;
+ /** @description True when the page was longer than the 20,000 characters returned. */
+ truncated: boolean;
+ };
+ /**
+ * @description A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+ * @enum {string}
+ */
+ WebSearchBackendId: "tavily" | "brave" | "firecrawl" | "you" | "direct";
+ WebBackendsQuery: {
+ backend?: components["schemas"]["WebSearchBackendId"];
+ };
+ /** @enum {string} */
+ WebSearchCommand: "search" | "open";
+ /** @enum {string} */
+ WebSearchFilter: "recency" | "site";
+ /** @description What is left on the backend's account. from says where the numbers came from: provider is the provider's official usage endpoint read for this response; last_response is the rate-limit headers of the last call (Brave), as of observed_at; unavailable carries no numbers and reason says why. */
+ WebSearchQuota: {
+ /** @enum {string} */
+ from: "provider" | "last_response" | "unavailable";
+ remaining?: number;
+ /** @description Absent when the provider reports no cap. */
+ limit?: number;
+ /** @enum {string} */
+ unit?: "credits" | "usd" | "requests";
+ plan?: string;
+ resets_at?: components["schemas"]["Timestamp"];
+ observed_at?: components["schemas"]["Timestamp"];
+ /**
+ * @description no_key: no key is saved; not_reported: there is no usage endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet; key_rejected: the provider refused the saved key; provider_unavailable: the usage endpoint did not answer in time.
+ * @enum {string}
+ */
+ reason?:
+ | "no_key"
+ | "not_reported"
+ | "not_observed"
+ | "key_rejected"
+ | "provider_unavailable";
+ };
+ /** @description One backend with the static text a client shows for it and its live state. status is ready when a call would run now: direct always, You.com also without a key, the others with a key that is not rejected. */
+ WebSearchBackend: {
+ id: components["schemas"]["WebSearchBackendId"];
+ name: string;
+ /**
+ * @description How a call to the backend runs now. key: with an API key saved in the product (or one it still needs); free_trial: You.com without a key, a limited trial with lower quality results that TeamHub does not count; none: direct, which needs no account.
+ * @enum {string}
+ */
+ tier: "key" | "free_trial" | "none";
+ /** @description A short display line for the tier, set for free_trial. */
+ tier_text?: string;
+ commands: components["schemas"]["WebSearchCommand"][];
+ /** @description The search filters the backend honors; any other is refused before a call. */
+ filters: components["schemas"]["WebSearchFilter"][];
+ /** @description The most results one search returns; 0 for a backend without search. */
+ max_limit: number;
+ /** @description How many sites one search may name; 0 when it takes no site filter. */
+ max_sites: number;
+ /** @description Whether the backend works without a saved key. */
+ keyless: boolean;
+ /** @description Whether the provider has an official endpoint TeamHub checks a key with before saving it. Without one the key is saved unverified and proven by its first call. */
+ official_key_check: boolean;
+ /** @description The provider's free allowance, for display. */
+ free_tier?: string;
+ /**
+ * Format: uri
+ * @description Where the Human gets a key.
+ */
+ key_url?: string;
+ /** @enum {string} */
+ status: "ready" | "key_required" | "key_rejected";
+ /** @enum {string} */
+ key_state: "none" | "verified" | "unverified" | "rejected";
+ quota: components["schemas"]["WebSearchQuota"];
+ };
+ /** @description Every backend in TeamHub's default order. default_search is the backend a search without one uses now: the default a Human saved (chosen_default_search) even when its key stopped working, else the first ready backend in that order. */
+ WebSearchBackendList: {
+ default_search: components["schemas"]["WebSearchKeyBackend"];
+ chosen_default_search?: components["schemas"]["WebSearchKeyBackend"];
+ /** @constant */
+ default_open: "direct";
+ /** @description False when the deployment has no TEAMHUB_SECRET_ENCRYPTION_KEY to seal keys with. */
+ can_save_keys: boolean;
+ backends: components["schemas"]["WebSearchBackend"][];
+ };
+ WebConnectRequest: {
+ backend: components["schemas"]["WebSearchKeyBackend"];
+ };
+ WebConnectResponse: {
+ /** @enum {string} */
+ status: "ready" | "connection_requested";
+ /** @description The backend's state when it is ready. */
+ backend?: components["schemas"]["WebSearchBackend"];
+ room_id?: string;
+ message_id?: string;
+ interaction_id?: string;
+ };
/**
* @description The app macOS grants the permission to. linger is the Linger desktop app, which owns shell commands such as screencapture; computer_use is CuaDriver, which owns the computer-use tools.
* @enum {string}
@@ -4322,6 +4560,184 @@ export interface operations {
default: components["responses"]["InternalError"];
};
};
+ searchAgentWeb: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["WebSearchRequest"];
+ };
+ };
+ responses: {
+ /** @description The results, best first. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebSearchResponse"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ /** @description search_quota_exhausted: the backend's account has no credit or quota left; details lists the other ready backends. */
+ 402: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ 403: components["responses"]["Forbidden"];
+ /** @description search_key_requested: a card asking the Human for a web search key is in the chat. */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ /** @description provider_rate_limited: the backend is rate limiting; details carries retry_after_seconds when known and the other ready backends. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ 503: components["responses"]["ServiceUnavailable"];
+ default: components["responses"]["InternalError"];
+ };
+ };
+ openAgentWebPage: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["WebOpenRequest"];
+ };
+ };
+ responses: {
+ /** @description The page. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebOpenResponse"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ /** @description search_quota_exhausted: the backend's account has no credit or quota left. */
+ 402: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ 403: components["responses"]["Forbidden"];
+ /** @description search_key_requested: a card asking the Human for a web search key is in the chat. */
+ 409: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ /** @description tool_execution_failed: the provider could not read this page. */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ /** @description provider_rate_limited: the backend is rate limiting. */
+ 429: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["AgentApiErrorEnvelope"];
+ };
+ };
+ 503: components["responses"]["ServiceUnavailable"];
+ default: components["responses"]["InternalError"];
+ };
+ };
+ listAgentWebBackends: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["WebBackendsQuery"];
+ };
+ };
+ responses: {
+ /** @description The backends in TeamHub's default order. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebSearchBackendList"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["Forbidden"];
+ default: components["responses"]["InternalError"];
+ };
+ };
+ connectAgentWebBackend: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["WebConnectRequest"];
+ };
+ };
+ responses: {
+ /** @description The backend is ready, or the card that asks for its key. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebConnectResponse"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["Forbidden"];
+ 503: components["responses"]["ServiceUnavailable"];
+ default: components["responses"]["InternalError"];
+ };
+ };
requestAgentBrowserConnection: {
parameters: {
query?: never;
diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
index f0fbb7ce..d44b579c 100644
--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
@@ -2509,6 +2509,73 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/v0/web-search/backends": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * List the web search backends with their display text, state and live quota.
+ * @description Every backend in TeamHub's default order, with what a client needs to render one row each: name, commands, filters, free tier text, where to get a key, the key state and live quota. Quota is read from each provider's official usage endpoint for this request, in parallel and briefly.
+ */
+ get: operations["listWebSearchBackends"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v0/web-search/backends/{backend}/key": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ backend: components["schemas"]["WebSearchKeyBackend"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ /**
+ * Save the deployment's API key for one web search backend.
+ * @description From a search_key card (decision_id, its decision owner only), TeamHub first runs the search or page open the card was posted for against this backend with the new key. A provider refusing the key leaves it unsaved and the card open (400 WEB_SEARCH_KEY_REJECTED). Any other outcome saves the key, verified once the provider proved it, and answers the card configured with this backend and that call's results or error code, so the Agent need not run it again. Otherwise TeamHub checks the key with the provider's official endpoint when it has one (Tavily usage, You.com account balance, Firecrawl credit usage); a Brave key is saved unverified and its first call proves it. Keys are stored encrypted with TEAMHUB_SECRET_ENCRYPTION_KEY and never returned; any signed-in Human may save one. Saving answers every other open search_key card configured with this backend and wakes the waiting Agents. 400 carries INVALID_REQUEST or WEB_SEARCH_KEY_REJECTED, 403 FORBIDDEN, 404 NOT_FOUND for a card the caller cannot see, 503 WEB_SEARCH_KEY_STORAGE_UNAVAILABLE or WEB_SEARCH_PROVIDER_UNAVAILABLE.
+ */
+ put: operations["saveWebSearchKey"];
+ post?: never;
+ /**
+ * Remove the saved API key of one web search backend.
+ * @description The backend also stops being the chosen default, so searches without a backend fall back to TeamHub's order. Removing a key that is not saved succeeds.
+ */
+ delete: operations["deleteWebSearchKey"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v0/web-search/default": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ /**
+ * Choose the backend a search without one uses.
+ * @description The backend must be ready (409 WEB_SEARCH_KEY_REQUIRED otherwise). Any signed-in Human may choose it; it applies to the whole deployment.
+ */
+ put: operations["setWebSearchDefault"];
+ post?: never;
+ /** Return searches without a backend to TeamHub's order. */
+ delete: operations["clearWebSearchDefault"];
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v0/work-items/{workItemId}/documents/uploads": {
parameters: {
query?: never;
@@ -5487,9 +5554,10 @@ export interface components {
| "provider_key"
| "browser_connection"
| "room_creation"
- | "computer_permission";
+ | "computer_permission"
+ | "search_key";
/**
- * @description For connector_write and agent_change, approved and executing mean TeamHub is running the approved request, and unknown means a run stopped midway and may have taken effect; TeamHub does not run it again. A question or AnotherMe setup card ends answered. An approved runtime_permission lets the Agent retry that one call until expires_at, and ends consumed once it does. An approved connection_auth is authorizing until the OAuth it started completes (succeeded), fails, or expires. A provider_key ends answered when someone saves a Composio key, denied when its Human declines. A browser_connection ends answered when its owner connects, denied when they decline. A room_creation ends succeeded with its Room created, or denied. A computer_permission ends answered once every permission it asks for is granted, denied when its owner declines.
+ * @description For connector_write and agent_change, approved and executing mean TeamHub is running the approved request, and unknown means a run stopped midway and may have taken effect; TeamHub does not run it again. A question or AnotherMe setup card ends answered. An approved runtime_permission lets the Agent retry that one call until expires_at, and ends consumed once it does. An approved connection_auth is authorizing until the OAuth it started completes (succeeded), fails, or expires. A provider_key ends answered when someone saves a Composio key, denied when its Human declines. A browser_connection ends answered when its owner connects, denied when they decline. A room_creation ends succeeded with its Room created, or denied. A computer_permission ends answered once every permission it asks for is granted, denied when its owner declines. A search_key ends answered when someone saves any web search key, denied when its Human declines.
* @enum {string}
*/
DecisionStatus:
@@ -5504,13 +5572,18 @@ export interface components {
| "answered"
| "consumed"
| "authorizing";
+ /**
+ * @description A backend that takes an API key saved in the product.
+ * @enum {string}
+ */
+ WebSearchKeyBackend: "tavily" | "brave" | "firecrawl" | "you";
/** @description A radio or checkbox answer names option ids. Any other value is the Human's own written answer, which every option question accepts, so a checkbox answer holds up to 20 options and one written answer. */
DecisionAnswerValue: string | string[];
/** @description Service-signed upload credential. It names the uploading Human, the Room, and the stored file, and it expires at the upload's expires_at; clients must not construct or parse it. */
AttachmentUploadToken: string;
DecisionAnswer: {
/**
- * @description approve or deny for connector_write, agent_change, runtime_permission, connection_auth and room_creation; deny or connected (recorded by TeamHub once the owner connects Chrome) for browser_connection; deny or configured (recorded by TeamHub once a Composio key is saved) for provider_key; deny or granted (recorded by TeamHub once the Computer reports every permission granted) for computer_permission; submit for question; connected or skipped for profile_setup_apps; done or skipped for profile_setup_sources.
+ * @description approve or deny for connector_write, agent_change, runtime_permission, connection_auth and room_creation; deny or connected (recorded by TeamHub once the owner connects Chrome) for browser_connection; deny or configured (recorded by TeamHub once a Composio key is saved) for provider_key and search_key (with the backend whose key was saved); deny or granted (recorded by TeamHub once the Computer reports every permission granted) for computer_permission; submit for question; connected or skipped for profile_setup_apps; done or skipped for profile_setup_sources.
* @enum {string}
*/
decision:
@@ -5526,6 +5599,8 @@ export interface components {
comment?: string;
/** @description The Connection a connection_auth approval chose. */
connection_id?: components["schemas"]["Id"];
+ /** @description The web search backend whose key was saved, on a configured search_key answer; it may differ from the backend the card showed. */
+ backend?: components["schemas"]["WebSearchKeyBackend"];
/** @description Map of question id to the Human's answer; only with submit. */
answers?: {
[key: string]: components["schemas"]["DecisionAnswerValue"];
@@ -5683,6 +5758,14 @@ export interface components {
permissions: components["schemas"]["ComputerPermissionId"][];
reason?: string;
};
+ /** @description The view of a search_key decision: the web search backend the card shows. origin is requested when the Agent's command named it, and suggested when the command named none and nothing was usable, so TeamHub picked the first backend in its order that still needs a key. reason says why: no key is saved (missing), the provider refused the saved one (rejected), or the keyless You.com searches are used up (free_limit). The Human may add a key for any other backend instead; saving any web search key answers the card configured with that backend. */
+ SearchKeyDecisionView: {
+ backend: components["schemas"]["WebSearchKeyBackend"];
+ /** @enum {string} */
+ origin: "requested" | "suggested";
+ /** @enum {string} */
+ reason: "missing" | "rejected" | "free_limit";
+ };
/** @description A request waiting on one Human's decision. TeamHub runs what the decision approves and reports the result to the requesting Agent. Exactly the view property named by kind is present; both AnotherMe setup kinds use profile_setup. */
DecisionRequestedMessageCard: {
/** @constant */
@@ -5718,6 +5801,7 @@ export interface components {
browser_connection?: components["schemas"]["BrowserConnectionDecisionView"];
room_creation?: components["schemas"]["RoomCreationDecisionView"];
computer_permission?: components["schemas"]["ComputerPermissionDecisionView"];
+ search_key?: components["schemas"]["SearchKeyDecisionView"];
};
/** @description The Message author, an Agent, created this General Agent. Without approved_by it was created here and joined this Room; with approved_by it was created after that Human approved the confirmation card and joined no Room. */
AgentCreatedNotice: {
@@ -7319,6 +7403,95 @@ export interface components {
/** Format: binary */
content: string;
};
+ /**
+ * @description A web search backend. direct opens pages only and is fetched by the Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+ * @enum {string}
+ */
+ WebSearchBackendId: "tavily" | "brave" | "firecrawl" | "you" | "direct";
+ /** @enum {string} */
+ WebSearchCommand: "search" | "open";
+ /** @enum {string} */
+ WebSearchFilter: "recency" | "site";
+ /** @description What is left on the backend's account. from says where the numbers came from: provider is the provider's official usage endpoint read for this response; last_response is the rate-limit headers of the last call (Brave), as of observed_at; unavailable carries no numbers and reason says why. */
+ WebSearchQuota: {
+ /** @enum {string} */
+ from: "provider" | "last_response" | "unavailable";
+ remaining?: number;
+ /** @description Absent when the provider reports no cap. */
+ limit?: number;
+ /** @enum {string} */
+ unit?: "credits" | "usd" | "requests";
+ plan?: string;
+ resets_at?: components["schemas"]["Timestamp"];
+ observed_at?: components["schemas"]["Timestamp"];
+ /**
+ * @description no_key: no key is saved; not_reported: there is no usage endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet; key_rejected: the provider refused the saved key; provider_unavailable: the usage endpoint did not answer in time.
+ * @enum {string}
+ */
+ reason?:
+ | "no_key"
+ | "not_reported"
+ | "not_observed"
+ | "key_rejected"
+ | "provider_unavailable";
+ };
+ /** @description One backend with the static text a client shows for it and its live state. status is ready when a call would run now: direct always, You.com also without a key, the others with a key that is not rejected. */
+ WebSearchBackend: {
+ id: components["schemas"]["WebSearchBackendId"];
+ name: string;
+ /**
+ * @description How a call to the backend runs now. key: with an API key saved in the product (or one it still needs); free_trial: You.com without a key, a limited trial with lower quality results that TeamHub does not count; none: direct, which needs no account.
+ * @enum {string}
+ */
+ tier: "key" | "free_trial" | "none";
+ /** @description A short display line for the tier, set for free_trial. */
+ tier_text?: string;
+ commands: components["schemas"]["WebSearchCommand"][];
+ /** @description The search filters the backend honors; any other is refused before a call. */
+ filters: components["schemas"]["WebSearchFilter"][];
+ /** @description The most results one search returns; 0 for a backend without search. */
+ max_limit: number;
+ /** @description How many sites one search may name; 0 when it takes no site filter. */
+ max_sites: number;
+ /** @description Whether the backend works without a saved key. */
+ keyless: boolean;
+ /** @description Whether the provider has an official endpoint TeamHub checks a key with before saving it. Without one the key is saved unverified and proven by its first call. */
+ official_key_check: boolean;
+ /** @description The provider's free allowance, for display. */
+ free_tier?: string;
+ /**
+ * Format: uri
+ * @description Where the Human gets a key.
+ */
+ key_url?: string;
+ /** @enum {string} */
+ status: "ready" | "key_required" | "key_rejected";
+ /** @enum {string} */
+ key_state: "none" | "verified" | "unverified" | "rejected";
+ quota: components["schemas"]["WebSearchQuota"];
+ };
+ /** @description Every backend in TeamHub's default order. default_search is the backend a search without one uses now: the default a Human saved (chosen_default_search) even when its key stopped working, else the first ready backend in that order. */
+ WebSearchBackendList: {
+ default_search: components["schemas"]["WebSearchKeyBackend"];
+ chosen_default_search?: components["schemas"]["WebSearchKeyBackend"];
+ /** @constant */
+ default_open: "direct";
+ /** @description False when the deployment has no TEAMHUB_SECRET_ENCRYPTION_KEY to seal keys with. */
+ can_save_keys: boolean;
+ backends: components["schemas"]["WebSearchBackend"][];
+ };
+ SaveWebSearchKeyRequest: {
+ api_key: string;
+ /** @description The search_key card the key is added from. TeamHub then runs the search or page open that card was posted for against this backend with the new key before saving it, and answers the card with what that call returned. Without it, or for a card posted by a connect request, the key gets the official check. */
+ decision_id?: string;
+ };
+ SetWebSearchDefaultRequest: {
+ backend: components["schemas"]["WebSearchKeyBackend"];
+ };
+ WebSearchDefault: {
+ default_search: components["schemas"]["WebSearchKeyBackend"];
+ chosen_default_search?: components["schemas"]["WebSearchKeyBackend"];
+ };
DocumentMetadataUpdateRequest: {
title: string;
};
@@ -12511,6 +12684,128 @@ export interface operations {
503: components["responses"]["ServiceUnavailable"];
};
};
+ listWebSearchBackends: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The backends. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebSearchBackendList"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ };
+ };
+ saveWebSearchKey: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ backend: components["schemas"]["WebSearchKeyBackend"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["SaveWebSearchKeyRequest"];
+ };
+ };
+ responses: {
+ /** @description The backend after saving. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebSearchBackend"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["Forbidden"];
+ 404: components["responses"]["NotFound"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
+ deleteWebSearchKey: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ backend: components["schemas"]["WebSearchKeyBackend"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The key is gone. */
+ 204: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ };
+ };
+ setWebSearchDefault: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["SetWebSearchDefaultRequest"];
+ };
+ };
+ responses: {
+ /** @description The default now in effect. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebSearchDefault"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 409: components["responses"]["Conflict"];
+ };
+ };
+ clearWebSearchDefault: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description The default now in effect. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["WebSearchDefault"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ };
+ };
uploadWorkItemDocument: {
parameters: {
query?: never;
diff --git a/contracts/openapi/components/agent-api-errors.yaml b/contracts/openapi/components/agent-api-errors.yaml
index 1067a599..aa8cede7 100644
--- a/contracts/openapi/components/agent-api-errors.yaml
+++ b/contracts/openapi/components/agent-api-errors.yaml
@@ -30,6 +30,8 @@ components:
- connection_not_active
- app_not_connected
- provider_key_required
+ - search_key_requested
+ - search_quota_exhausted
- tool_not_found
- invalid_tool_arguments
- provider_auth_failed
@@ -88,6 +90,58 @@ components:
maxItems: 100
items:
$ref: "#/components/schemas/AgentApiErrorIssue"
+ details:
+ $ref: "#/components/schemas/AgentApiErrorDetails"
+ AgentApiErrorDetails:
+ type: object
+ description: >-
+ Machine-readable facts a failure carries for the CLI to act on. A
+ search_key_requested failure names the card it posted and the backend
+ it shows; a quota or rate limit names the backend and the other
+ backends ready now.
+ additionalProperties: false
+ properties:
+ backend:
+ type: string
+ maxLength: 64
+ origin:
+ type: string
+ enum: [requested, suggested]
+ x-enum-varnames:
+ [
+ AgentApiErrorDetailsOriginRequested,
+ AgentApiErrorDetailsOriginSuggested,
+ ]
+ description: >-
+ requested when the command named the backend the card shows;
+ suggested when it named none and TeamHub picked one.
+ reason:
+ type: string
+ enum: [missing, rejected, free_limit]
+ x-enum-varnames:
+ [
+ AgentApiErrorDetailsReasonMissing,
+ AgentApiErrorDetailsReasonRejected,
+ AgentApiErrorDetailsReasonFreeLimit,
+ ]
+ room_id:
+ type: string
+ maxLength: 128
+ message_id:
+ type: string
+ maxLength: 128
+ interaction_id:
+ type: string
+ maxLength: 128
+ ready_backends:
+ type: array
+ maxItems: 10
+ items:
+ type: string
+ maxLength: 64
+ retry_after_seconds:
+ type: integer
+ minimum: 0
AgentApiErrorEnvelope:
type: object
description: Standard failure envelope for every TeamHub Agent API operation.
diff --git a/contracts/openapi/components/message-cards.yaml b/contracts/openapi/components/message-cards.yaml
index 0afee9ca..d19e0dbb 100644
--- a/contracts/openapi/components/message-cards.yaml
+++ b/contracts/openapi/components/message-cards.yaml
@@ -444,6 +444,40 @@ components:
type: string
minLength: 1
maxLength: 120
+ SearchKeyDecisionView:
+ type: object
+ additionalProperties: false
+ description: >-
+ The view of a search_key decision: the web search backend the card
+ shows. origin is requested when the Agent's command named it, and
+ suggested when the command named none and nothing was usable, so
+ TeamHub picked the first backend in its order that still needs a key.
+ reason says why: no key is saved (missing), the provider refused the
+ saved one (rejected), or the keyless You.com searches are used up
+ (free_limit). The Human may add a key for any other backend instead;
+ saving any web search key answers the card configured with that
+ backend.
+ required: [backend, origin, reason]
+ properties:
+ backend:
+ $ref: "./web-search.yaml#/components/schemas/WebSearchKeyBackend"
+ origin:
+ type: string
+ enum: [requested, suggested]
+ x-enum-varnames:
+ [
+ SearchKeyDecisionViewOriginRequested,
+ SearchKeyDecisionViewOriginSuggested,
+ ]
+ reason:
+ type: string
+ enum: [missing, rejected, free_limit]
+ x-enum-varnames:
+ [
+ SearchKeyDecisionViewReasonMissing,
+ SearchKeyDecisionViewReasonRejected,
+ SearchKeyDecisionViewReasonFreeLimit,
+ ]
BrowserConnectionDecisionView:
type: object
additionalProperties: false
@@ -507,6 +541,7 @@ components:
browser_connection,
room_creation,
computer_permission,
+ search_key,
]
x-enum-varnames:
[
@@ -521,6 +556,7 @@ components:
DecisionKindBrowserConnection,
DecisionKindRoomCreation,
DecisionKindComputerPermission,
+ DecisionKindSearchKey,
]
description: >-
profile_setup_apps and profile_setup_sources are the AnotherMe setup
@@ -569,7 +605,8 @@ components:
they decline. A room_creation
ends succeeded with its Room created, or denied. A computer_permission
ends answered once every permission it asks for is granted, denied when
- its owner declines.
+ its owner declines. A search_key ends answered when someone saves any
+ web search key, denied when its Human declines.
DecisionAnswer:
type: object
additionalProperties: false
@@ -604,7 +641,8 @@ components:
runtime_permission, connection_auth and room_creation; deny or
connected (recorded by TeamHub once the owner connects Chrome) for
browser_connection; deny or configured (recorded by TeamHub once
- a Composio key is saved) for provider_key; deny or granted (recorded by TeamHub once
+ a Composio key is saved) for provider_key and search_key (with the
+ backend whose key was saved); deny or granted (recorded by TeamHub once
the Computer reports every permission granted) for
computer_permission; submit for question; connected or skipped for profile_setup_apps;
done or skipped for profile_setup_sources.
@@ -616,6 +654,11 @@ components:
connection_id:
$ref: "./common.yaml#/components/schemas/Id"
description: The Connection a connection_auth approval chose.
+ backend:
+ $ref: "./web-search.yaml#/components/schemas/WebSearchKeyBackend"
+ description: >-
+ The web search backend whose key was saved, on a configured
+ search_key answer; it may differ from the backend the card showed.
answers:
type: object
additionalProperties:
@@ -724,6 +767,8 @@ components:
$ref: "#/components/schemas/RoomCreationDecisionView"
computer_permission:
$ref: "#/components/schemas/ComputerPermissionDecisionView"
+ search_key:
+ $ref: "#/components/schemas/SearchKeyDecisionView"
DecisionRequest:
type: object
additionalProperties: false
diff --git a/contracts/openapi/components/web-search.yaml b/contracts/openapi/components/web-search.yaml
new file mode 100644
index 00000000..b9403196
--- /dev/null
+++ b/contracts/openapi/components/web-search.yaml
@@ -0,0 +1,402 @@
+components:
+ schemas:
+ WebSearchBackendId:
+ type: string
+ description: >-
+ A web search backend. direct opens pages only and is fetched by the
+ Agent CLI on the Agent's computer; TeamHub never fetches a page itself.
+ enum: [tavily, brave, firecrawl, you, direct]
+ x-enum-varnames:
+ [
+ WebSearchBackendIdTavily,
+ WebSearchBackendIdBrave,
+ WebSearchBackendIdFirecrawl,
+ WebSearchBackendIdYou,
+ WebSearchBackendIdDirect,
+ ]
+ WebSearchKeyBackend:
+ type: string
+ description: A backend that takes an API key saved in the product.
+ enum: [tavily, brave, firecrawl, you]
+ x-enum-varnames:
+ [
+ WebSearchKeyBackendTavily,
+ WebSearchKeyBackendBrave,
+ WebSearchKeyBackendFirecrawl,
+ WebSearchKeyBackendYou,
+ ]
+ WebSearchCommand:
+ type: string
+ enum: [search, open]
+ x-enum-varnames: [WebSearchCommandSearch, WebSearchCommandOpen]
+ WebSearchFilter:
+ type: string
+ enum: [recency, site]
+ x-enum-varnames: [WebSearchFilterRecency, WebSearchFilterSite]
+ WebSearchRecency:
+ type: string
+ enum: [day, week, month, year]
+ x-enum-varnames:
+ [
+ WebSearchRecencyDay,
+ WebSearchRecencyWeek,
+ WebSearchRecencyMonth,
+ WebSearchRecencyYear,
+ ]
+ WebSearchQuota:
+ type: object
+ additionalProperties: false
+ description: >-
+ What is left on the backend's account. from says where the numbers
+ came from: provider is the provider's official usage endpoint read for
+ this response; last_response is the rate-limit headers of the last
+ call (Brave), as of observed_at; unavailable carries no numbers and
+ reason says why.
+ required: [from]
+ properties:
+ from:
+ type: string
+ enum: [provider, last_response, unavailable]
+ x-enum-varnames:
+ [
+ WebSearchQuotaFromProvider,
+ WebSearchQuotaFromLastResponse,
+ WebSearchQuotaFromUnavailable,
+ ]
+ remaining:
+ type: number
+ minimum: 0
+ limit:
+ type: number
+ minimum: 0
+ description: Absent when the provider reports no cap.
+ unit:
+ type: string
+ enum: [credits, usd, requests]
+ x-enum-varnames:
+ [
+ WebSearchQuotaUnitCredits,
+ WebSearchQuotaUnitUsd,
+ WebSearchQuotaUnitRequests,
+ ]
+ plan:
+ type: string
+ maxLength: 200
+ resets_at:
+ $ref: "./common.yaml#/components/schemas/Timestamp"
+ observed_at:
+ $ref: "./common.yaml#/components/schemas/Timestamp"
+ reason:
+ type: string
+ enum:
+ [
+ no_key,
+ not_reported,
+ not_observed,
+ key_rejected,
+ provider_unavailable,
+ ]
+ x-enum-varnames:
+ [
+ WebSearchQuotaReasonNoKey,
+ WebSearchQuotaReasonNotReported,
+ WebSearchQuotaReasonNotObserved,
+ WebSearchQuotaReasonKeyRejected,
+ WebSearchQuotaReasonProviderUnavailable,
+ ]
+ description: >-
+ no_key: no key is saved; not_reported: there is no usage
+ endpoint to read (keyless You.com, direct); not_observed: Brave has answered no call yet;
+ key_rejected: the provider refused the saved key;
+ provider_unavailable: the usage endpoint did not answer in time.
+ WebSearchBackend:
+ type: object
+ additionalProperties: false
+ description: >-
+ One backend with the static text a client shows for it and its live
+ state. status is ready when a call would run now: direct always, You.com
+ also without a key, the others with a key that is not rejected.
+ required:
+ [
+ id,
+ name,
+ tier,
+ commands,
+ filters,
+ max_limit,
+ max_sites,
+ keyless,
+ official_key_check,
+ status,
+ key_state,
+ quota,
+ ]
+ properties:
+ id:
+ $ref: "#/components/schemas/WebSearchBackendId"
+ name:
+ type: string
+ minLength: 1
+ maxLength: 80
+ tier:
+ type: string
+ enum: [key, free_trial, none]
+ x-enum-varnames:
+ [
+ WebSearchBackendTierKey,
+ WebSearchBackendTierFreeTrial,
+ WebSearchBackendTierNone,
+ ]
+ description: >-
+ How a call to the backend runs now. key: with an API key saved in
+ the product (or one it still needs); free_trial: You.com without a
+ key, a limited trial with lower quality results that TeamHub does
+ not count; none: direct, which needs no account.
+ tier_text:
+ type: string
+ maxLength: 300
+ description: A short display line for the tier, set for free_trial.
+ commands:
+ type: array
+ minItems: 1
+ uniqueItems: true
+ items:
+ $ref: "#/components/schemas/WebSearchCommand"
+ filters:
+ type: array
+ uniqueItems: true
+ items:
+ $ref: "#/components/schemas/WebSearchFilter"
+ description: The search filters the backend honors; any other is refused before a call.
+ max_limit:
+ type: integer
+ minimum: 0
+ maximum: 20
+ description: The most results one search returns; 0 for a backend without search.
+ max_sites:
+ type: integer
+ minimum: 0
+ maximum: 10
+ description: How many sites one search may name; 0 when it takes no site filter.
+ keyless:
+ type: boolean
+ description: Whether the backend works without a saved key.
+ official_key_check:
+ type: boolean
+ description: >-
+ Whether the provider has an official endpoint TeamHub checks a key
+ with before saving it. Without one the key is saved unverified and
+ proven by its first call.
+ free_tier:
+ type: string
+ maxLength: 300
+ description: The provider's free allowance, for display.
+ key_url:
+ type: string
+ format: uri
+ description: Where the Human gets a key.
+ status:
+ type: string
+ enum: [ready, key_required, key_rejected]
+ x-enum-varnames:
+ [
+ WebSearchBackendStatusReady,
+ WebSearchBackendStatusKeyRequired,
+ WebSearchBackendStatusKeyRejected,
+ ]
+ key_state:
+ type: string
+ enum: [none, verified, unverified, rejected]
+ x-enum-varnames:
+ [
+ WebSearchBackendKeyStateNone,
+ WebSearchBackendKeyStateVerified,
+ WebSearchBackendKeyStateUnverified,
+ WebSearchBackendKeyStateRejected,
+ ]
+ quota:
+ $ref: "#/components/schemas/WebSearchQuota"
+ WebSearchBackendList:
+ type: object
+ additionalProperties: false
+ description: >-
+ Every backend in TeamHub's default order. default_search is the
+ backend a search without one uses now: the default a Human saved
+ (chosen_default_search) even when its key stopped working, else the
+ first ready backend in that order.
+ required: [default_search, default_open, can_save_keys, backends]
+ properties:
+ default_search:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ chosen_default_search:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ default_open:
+ type: string
+ const: direct
+ can_save_keys:
+ type: boolean
+ description: False when the deployment has no TEAMHUB_SECRET_ENCRYPTION_KEY to seal keys with.
+ backends:
+ type: array
+ items:
+ $ref: "#/components/schemas/WebSearchBackend"
+ SaveWebSearchKeyRequest:
+ type: object
+ additionalProperties: false
+ required: [api_key]
+ properties:
+ api_key:
+ type: string
+ minLength: 1
+ maxLength: 512
+ decision_id:
+ type: string
+ minLength: 1
+ maxLength: 128
+ description: >-
+ The search_key card the key is added from. TeamHub then runs the
+ search or page open that card was posted for against this backend
+ with the new key before saving it, and answers the card with what
+ that call returned. Without it, or for a card posted by a connect
+ request, the key gets the official check.
+ SetWebSearchDefaultRequest:
+ type: object
+ additionalProperties: false
+ required: [backend]
+ properties:
+ backend:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ WebSearchDefault:
+ type: object
+ additionalProperties: false
+ required: [default_search]
+ properties:
+ default_search:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ chosen_default_search:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ WebSearchRequest:
+ type: object
+ additionalProperties: false
+ required: [query]
+ properties:
+ query:
+ type: string
+ minLength: 1
+ maxLength: 400
+ backend:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ limit:
+ type: integer
+ minimum: 1
+ maximum: 20
+ description: Defaults to 10.
+ recency:
+ $ref: "#/components/schemas/WebSearchRecency"
+ sites:
+ type: array
+ maxItems: 10
+ uniqueItems: true
+ items:
+ type: string
+ minLength: 3
+ maxLength: 253
+ description: Hostnames to search within, up to the backend's max_sites.
+ WebSearchResult:
+ type: object
+ additionalProperties: false
+ required: [title, url, snippet]
+ properties:
+ title:
+ type: string
+ maxLength: 300
+ url:
+ type: string
+ format: uri
+ snippet:
+ type: string
+ maxLength: 500
+ published_at:
+ type: string
+ maxLength: 64
+ description: The page date as the provider reports it.
+ WebSearchResponse:
+ type: object
+ additionalProperties: false
+ required: [results]
+ properties:
+ results:
+ type: array
+ maxItems: 20
+ items:
+ $ref: "#/components/schemas/WebSearchResult"
+ WebOpenRequest:
+ type: object
+ additionalProperties: false
+ required: [url, backend]
+ properties:
+ url:
+ type: string
+ format: uri
+ minLength: 1
+ maxLength: 2048
+ backend:
+ type: string
+ enum: [tavily, firecrawl, you]
+ x-enum-varnames:
+ [
+ WebOpenRequestBackendTavily,
+ WebOpenRequestBackendFirecrawl,
+ WebOpenRequestBackendYou,
+ ]
+ description: A backend that opens pages; direct is fetched by the CLI.
+ WebOpenResponse:
+ type: object
+ additionalProperties: false
+ required: [url, markdown, truncated]
+ properties:
+ url:
+ type: string
+ format: uri
+ description: The page's final URL when the provider reports one.
+ title:
+ type: string
+ maxLength: 300
+ markdown:
+ type: string
+ maxLength: 20000
+ truncated:
+ type: boolean
+ description: True when the page was longer than the 20,000 characters returned.
+ WebBackendsQuery:
+ type: object
+ additionalProperties: false
+ properties:
+ backend:
+ $ref: "#/components/schemas/WebSearchBackendId"
+ WebConnectRequest:
+ type: object
+ additionalProperties: false
+ required: [backend]
+ properties:
+ backend:
+ $ref: "#/components/schemas/WebSearchKeyBackend"
+ WebConnectResponse:
+ type: object
+ additionalProperties: false
+ required: [status]
+ properties:
+ status:
+ type: string
+ enum: [ready, connection_requested]
+ x-enum-varnames:
+ [
+ WebConnectResponseStatusReady,
+ WebConnectResponseStatusConnectionRequested,
+ ]
+ backend:
+ $ref: "#/components/schemas/WebSearchBackend"
+ description: The backend's state when it is ready.
+ room_id: { type: string }
+ message_id: { type: string }
+ interaction_id: { type: string }
diff --git a/contracts/openapi/paths/agent-web-search.yaml b/contracts/openapi/paths/agent-web-search.yaml
new file mode 100644
index 00000000..81d52434
--- /dev/null
+++ b/contracts/openapi/paths/agent-web-search.yaml
@@ -0,0 +1,183 @@
+search:
+ post:
+ operationId: searchAgentWeb
+ tags: [Agent Business API]
+ security: [{ agentBearer: [] }]
+ summary: Search the web through one backend with the deployment's saved key.
+ description: >-
+ Without backend, TeamHub uses the default a Human chose exactly as if
+ the request named it, even when its key stopped working; without a
+ chosen default it uses the first ready backend in the order tavily,
+ brave, firecrawl, you (with a key), then You.com's keyless free tier,
+ and details.origin is suggested. A filter the backend cannot honor is
+ refused before any call. There is no automatic fallback to another
+ backend. When the backend needs a key the deployment lacks, or the
+ provider refused the saved one, or the keyless You.com searches are used
+ up, TeamHub posts (or reuses) a search_key card in the chat and answers
+ 409 search_key_requested; details names the card and the backend it
+ shows. Saving any web search key answers the card and wakes the Agent
+ with the backend to use.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchRequest"
+ responses:
+ "200":
+ description: The results, best first.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchResponse"
+ "400":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Unauthenticated"
+ "402":
+ description: "search_quota_exhausted: the backend's account has no credit or quota left; details lists the other ready backends."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "403":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Forbidden"
+ "409":
+ description: "search_key_requested: a card asking the Human for a web search key is in the chat."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "429":
+ description: "provider_rate_limited: the backend is rate limiting; details carries retry_after_seconds when known and the other ready backends."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "503":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/ServiceUnavailable"
+ default:
+ $ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
+open:
+ post:
+ operationId: openAgentWebPage
+ tags: [Agent Business API]
+ security: [{ agentBearer: [] }]
+ summary: Read one web page as Markdown through a provider backend.
+ description: >-
+ Only provider backends open pages here; the CLI fetches direct itself,
+ so TeamHub never requests the page URL. The Markdown is cut at 20,000
+ characters. Key failures post a search_key card as search does.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebOpenRequest"
+ responses:
+ "200":
+ description: The page.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebOpenResponse"
+ "400":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Unauthenticated"
+ "402":
+ description: "search_quota_exhausted: the backend's account has no credit or quota left."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "403":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Forbidden"
+ "409":
+ description: "search_key_requested: a card asking the Human for a web search key is in the chat."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "422":
+ description: "tool_execution_failed: the provider could not read this page."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "429":
+ description: "provider_rate_limited: the backend is rate limiting."
+ content:
+ application/json:
+ schema:
+ $ref: "../components/agent-api-errors.yaml#/components/schemas/AgentApiErrorEnvelope"
+ "503":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/ServiceUnavailable"
+ default:
+ $ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
+backends:
+ post:
+ operationId: listAgentWebBackends
+ tags: [Agent Business API]
+ security: [{ agentBearer: [] }]
+ summary: List the web search backends with their state and live quota.
+ description: >-
+ Quota is read from each provider's official usage endpoint for this
+ request, in parallel and briefly; a provider that does not answer in
+ time reports quota from=unavailable. backend narrows the list to one.
+ requestBody:
+ required: false
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebBackendsQuery"
+ responses:
+ "200":
+ description: The backends in TeamHub's default order.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchBackendList"
+ "400":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Unauthenticated"
+ "403":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Forbidden"
+ default:
+ $ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
+connect:
+ post:
+ operationId: connectAgentWebBackend
+ tags: [Agent Business API]
+ security: [{ agentBearer: [] }]
+ summary: Make one web search backend usable, asking the Human for its key through a chat card.
+ description: >-
+ A ready backend answers ready with its state and live quota. A backend
+ without a usable key gets a search_key card in the chat (an open one is
+ reused) and answers connection_requested. Saving any web search key
+ answers the card and wakes the Agent with the backend that was
+ configured.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebConnectRequest"
+ responses:
+ "200":
+ description: The backend is ready, or the card that asks for its key.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebConnectResponse"
+ "400":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Unauthenticated"
+ "403":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/Forbidden"
+ "503":
+ $ref: "../components/agent-api-errors.yaml#/components/responses/ServiceUnavailable"
+ default:
+ $ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
diff --git a/contracts/openapi/paths/teamhub-public-web-search.yaml b/contracts/openapi/paths/teamhub-public-web-search.yaml
new file mode 100644
index 00000000..0ecea717
--- /dev/null
+++ b/contracts/openapi/paths/teamhub-public-web-search.yaml
@@ -0,0 +1,120 @@
+backends:
+ get:
+ tags: [External Sources]
+ operationId: listWebSearchBackends
+ summary: List the web search backends with their display text, state and live quota.
+ description: >-
+ Every backend in TeamHub's default order, with what a client needs to
+ render one row each: name, commands, filters, free tier text, where to
+ get a key, the key state and live quota. Quota is read from each
+ provider's official usage endpoint for this request, in parallel and
+ briefly.
+ responses:
+ "200":
+ description: The backends.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchBackendList"
+ "401":
+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"
+backendKey:
+ put:
+ tags: [External Sources]
+ operationId: saveWebSearchKey
+ summary: Save the deployment's API key for one web search backend.
+ description: >-
+ From a search_key card (decision_id, its decision owner only), TeamHub
+ first runs the search or page open the card was posted for against this
+ backend with the new key. A provider refusing the key leaves it unsaved
+ and the card open (400 WEB_SEARCH_KEY_REJECTED). Any other outcome saves
+ the key, verified once the provider proved it, and answers the card
+ configured with this backend and that call's results or error code, so
+ the Agent need not run it again. Otherwise TeamHub checks the key with
+ the provider's official endpoint when it has one (Tavily usage, You.com
+ account balance, Firecrawl credit usage); a Brave key is saved
+ unverified and its first call proves it. Keys are stored encrypted with
+ TEAMHUB_SECRET_ENCRYPTION_KEY and never returned; any signed-in Human
+ may save one. Saving answers every other open search_key card
+ configured with this backend and wakes the waiting Agents. 400 carries
+ INVALID_REQUEST or WEB_SEARCH_KEY_REJECTED, 403 FORBIDDEN, 404
+ NOT_FOUND for a card the caller cannot see, 503
+ WEB_SEARCH_KEY_STORAGE_UNAVAILABLE or WEB_SEARCH_PROVIDER_UNAVAILABLE.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/SaveWebSearchKeyRequest"
+ responses:
+ "200":
+ description: The backend after saving.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchBackend"
+ "400":
+ $ref: "../components/common.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"
+ "403":
+ $ref: "../components/common.yaml#/components/responses/Forbidden"
+ "404":
+ $ref: "../components/common.yaml#/components/responses/NotFound"
+ "503":
+ $ref: "../components/common.yaml#/components/responses/ServiceUnavailable"
+ delete:
+ tags: [External Sources]
+ operationId: deleteWebSearchKey
+ summary: Remove the saved API key of one web search backend.
+ description: >-
+ The backend also stops being the chosen default, so searches without a
+ backend fall back to TeamHub's order. Removing a key that is not saved
+ succeeds.
+ responses:
+ "204":
+ description: The key is gone.
+ "400":
+ $ref: "../components/common.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"
+default:
+ put:
+ tags: [External Sources]
+ operationId: setWebSearchDefault
+ summary: Choose the backend a search without one uses.
+ description: >-
+ The backend must be ready (409 WEB_SEARCH_KEY_REQUIRED otherwise). Any
+ signed-in Human may choose it; it applies to the whole deployment.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/SetWebSearchDefaultRequest"
+ responses:
+ "200":
+ description: The default now in effect.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchDefault"
+ "400":
+ $ref: "../components/common.yaml#/components/responses/BadRequest"
+ "401":
+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"
+ "409":
+ $ref: "../components/common.yaml#/components/responses/Conflict"
+ delete:
+ tags: [External Sources]
+ operationId: clearWebSearchDefault
+ summary: Return searches without a backend to TeamHub's order.
+ responses:
+ "200":
+ description: The default now in effect.
+ content:
+ application/json:
+ schema:
+ $ref: "../components/web-search.yaml#/components/schemas/WebSearchDefault"
+ "401":
+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"
diff --git a/contracts/openapi/teamhub-agent-api/openapi.yaml b/contracts/openapi/teamhub-agent-api/openapi.yaml
index 759f7c8c..af3921d7 100644
--- a/contracts/openapi/teamhub-agent-api/openapi.yaml
+++ b/contracts/openapi/teamhub-agent-api/openapi.yaml
@@ -1115,6 +1115,14 @@ paths:
$ref: "../components/agent-api-errors.yaml#/components/responses/ServiceUnavailable"
default:
$ref: "../components/agent-api-errors.yaml#/components/responses/InternalError"
+ /api/agent/v1/web/search:
+ $ref: "../paths/agent-web-search.yaml#/search"
+ /api/agent/v1/web/open:
+ $ref: "../paths/agent-web-search.yaml#/open"
+ /api/agent/v1/web/backends/query:
+ $ref: "../paths/agent-web-search.yaml#/backends"
+ /api/agent/v1/web/connect:
+ $ref: "../paths/agent-web-search.yaml#/connect"
/api/agent/v1/computer/browser-connection:
$ref: "../paths/agent-browser-connection.yaml#/request"
/api/agent/v1/computer/permissions/status:
diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
index 52ee9899..93a1c69b 100644
--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
@@ -3264,6 +3264,18 @@ paths:
$ref: '../components/common.yaml#/components/responses/PayloadTooLarge'
'503':
$ref: '../components/common.yaml#/components/responses/ServiceUnavailable'
+ /v0/web-search/backends:
+ $ref: '../paths/teamhub-public-web-search.yaml#/backends'
+ /v0/web-search/backends/{backend}/key:
+ parameters:
+ - name: backend
+ in: path
+ required: true
+ schema:
+ $ref: '../components/web-search.yaml#/components/schemas/WebSearchKeyBackend'
+ $ref: '../paths/teamhub-public-web-search.yaml#/backendKey'
+ /v0/web-search/default:
+ $ref: '../paths/teamhub-public-web-search.yaml#/default'
/v0/work-items/{workItemId}/documents/uploads:
parameters:
- $ref: '#/components/parameters/WorkItemId'