Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
feat: add page agent with tool-calling AI assistant (#19629)
p0ny406b154fd157
diff --git a/.github/workflows/frontend-tests.yml b/.github/workflows/frontend-tests.ymlindex 7e47be8924..24ced2f291 100644--- a/.github/workflows/frontend-tests.yml+++ b/.github/workflows/frontend-tests.yml@@ -53,9 +53,6 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfileworking-directory: frontend- - name: Copy config files- run: pnpm run copy:config-files- working-directory: frontend- name: Run unit testsrun: pnpm testworking-directory: frontenddiff --git a/backend/api/mcp/gen/openapi.yaml b/backend/api/mcp/gen/openapi.yamlindex 6ff110b2e7..2bce36141b 100644--- a/backend/api/mcp/gen/openapi.yaml+++ b/backend/api/mcp/gen/openapi.yaml@@ -1,6 +1,44 @@openapi: 3.1.0info: {}paths:+ /bytebase.v1.AIService/Chat:+ post:+ tags:+ - bytebase.v1.AIService+ summary: Chat+ description: |-+ Chat sends a conversation with tool definitions to the configured AI provider+ and returns the AI response.+ operationId: bytebase.v1.AIService.Chat+ parameters:+ - name: Connect-Protocol-Version+ in: header+ required: true+ schema:+ $ref: '#/components/schemas/connect-protocol-version'+ - name: Connect-Timeout-Ms+ in: header+ schema:+ $ref: '#/components/schemas/connect-timeout-header'+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.AIChatRequest'+ required: true+ responses:+ default:+ description: Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/connect.error'+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.AIChatResponse'/bytebase.v1.AccessGrantService/ActivateAccessGrant:post:tags:@@ -6866,6 +6904,124 @@ paths:$ref: '#/components/schemas/bytebase.v1.IamPolicy'components:schemas:+ bytebase.v1.AIChatMessage:+ type: object+ properties:+ role:+ title: role+ description: The role of the message sender.+ $ref: '#/components/schemas/bytebase.v1.AIChatMessageRole'+ content:+ type:+ - string+ - "null"+ title: content+ description: The text content of the message. Optional for assistant messages that only contain tool calls.+ toolCalls:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatToolCall'+ title: tool_calls+ description: Tool calls made by the assistant. Only present in assistant messages.+ toolCallId:+ type:+ - string+ - "null"+ title: tool_call_id+ description: The ID of the tool call this message is responding to. Only present in tool messages.+ title: AIChatMessage+ additionalProperties: false+ description: A single message in the conversation.+ bytebase.v1.AIChatMessageRole:+ type: string+ title: AIChatMessageRole+ enum:+ - AI_CHAT_MESSAGE_ROLE_UNSPECIFIED+ - AI_CHAT_MESSAGE_ROLE_SYSTEM+ - AI_CHAT_MESSAGE_ROLE_USER+ - AI_CHAT_MESSAGE_ROLE_ASSISTANT+ - AI_CHAT_MESSAGE_ROLE_TOOL+ description: Role of a chat message.+ bytebase.v1.AIChatRequest:+ type: object+ properties:+ messages:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatMessage'+ title: messages+ description: The conversation messages.+ toolDefinitions:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatToolDefinition'+ title: tool_definitions+ description: The tool definitions available to the AI.+ title: AIChatRequest+ additionalProperties: false+ description: Request message for AIService.Chat.+ bytebase.v1.AIChatResponse:+ type: object+ properties:+ content:+ type:+ - string+ - "null"+ title: content+ description: The text content of the AI response. Optional when the response only contains tool calls.+ toolCalls:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatToolCall'+ title: tool_calls+ description: Tool calls the AI wants to make.+ title: AIChatResponse+ additionalProperties: false+ description: Response message for AIService.Chat.+ bytebase.v1.AIChatToolCall:+ type: object+ properties:+ id:+ type: string+ title: id+ description: The unique ID of this tool call.+ name:+ type: string+ title: name+ description: The name of the tool to call.+ arguments:+ type: string+ title: arguments+ description: The JSON-encoded arguments to pass to the tool.+ metadata:+ type:+ - string+ - "null"+ title: metadata+ description: |-+ Opaque provider-specific metadata (e.g., Gemini thought_signature).+ Frontend must echo this back unchanged when sending tool results.+ title: AIChatToolCall+ additionalProperties: false+ description: A tool call made by the AI.+ bytebase.v1.AIChatToolDefinition:+ type: object+ properties:+ name:+ type: string+ title: name+ description: The name of the tool.+ description:+ type: string+ title: description+ description: A description of what the tool does.+ parametersSchema:+ type: string+ title: parameters_schema+ description: The JSON Schema describing the tool's parameters.+ title: AIChatToolDefinition+ additionalProperties: false+ description: A tool definition that the AI can invoke.bytebase.v1.AICompletionRequest:type: objectproperties:@@ -20210,6 +20366,8 @@ tags:description: SettingService manages workspace-level settings and configurations.- name: bytebase.v1.ActuatorServicedescription: ActuatorService manages system health and operational information.+ - name: bytebase.v1.AIService+ description: AIService provides AI chat capabilities for the page agent.- name: bytebase.v1.AuditLogServicedescription: AuditLogService manages audit logs for system activities and API calls.- name: bytebase.v1.UserServicediff --git a/backend/api/mcp/tool_search.go b/backend/api/mcp/tool_search.goindex 6091cad394..44b50ed92b 100644--- a/backend/api/mcp/tool_search.go+++ b/backend/api/mcp/tool_search.go@@ -18,14 +18,9 @@ type SearchInput struct {// Schema gets the definition of a message type.// Examples: "bytebase.v1.Instance", "Instance", "Engine"Schema string `json:"schema,omitempty"`- // Query is a free-text search query to find relevant API endpoints.- // Examples: "create database", "execute sql", "list projects"- Query string `json:"query,omitempty"`// Service filters results to a specific service.// Examples: "SQLService", "DatabaseService", "ProjectService"Service string `json:"service,omitempty"`- // Limit is the maximum number of results to return (default: 5, max: 50).- Limit int `json:"limit,omitempty"`}// searchAPIDescription is the description for the search_api tool.@@ -35,12 +30,10 @@ const searchAPIDescription = `Discover Bytebase API endpoints. **Always call bef|------|------------|--------|| List | (none) | All services || Browse | service="SQLService" | All endpoints in service |-| Search | query="database" | Matching endpoints |-| Filter | service+query | Search within service || Details | operationId="SQLService/Query" | Request/response schema || Schema | schema="Instance" | Message type definition |-**Workflow:** search_api() → search_api(operationId="...") → call_api(...)`+**Workflow:** search_api() → search_api(service="...") → search_api(operationId="...") → call_api(...)`func (s *Server) registerSearchTool() {mcp.AddTool(s.mcpServer, &mcp.Tool{@@ -61,21 +54,11 @@ func (s *Server) handleSearchAPI(_ context.Context, _ *mcp.CallToolRequest, inpu// Schema lookup mode: get properties of a message typetext = s.formatSchemaDetail(input.Schema)- case input.Query == "" && input.Service == "":+ case input.Service == "":// List all servicestext = s.formatServiceList()- case input.Service != "" && input.Query != "":- // Search within a service- endpoints := s.openAPIIndex.SearchInService(input.Query, input.Service)- if len(endpoints) == 0 {- text = fmt.Sprintf("No endpoints found for query %q in service %s\n\nTry:\n- Different keywords\n- Browsing the service with search_api(service=\"%s\")",- input.Query, input.Service, input.Service)- } else {- text = s.formatEndpoints(endpoints, s.getLimit(input.Limit))- }-- case input.Service != "":+ default:// List all endpoints in a service (no limit)endpoints := s.openAPIIndex.GetServiceEndpoints(input.Service)if len(endpoints) == 0 {@@ -84,15 +67,6 @@ func (s *Server) handleSearchAPI(_ context.Context, _ *mcp.CallToolRequest, inpu} else {text = s.formatEndpoints(endpoints, 0)}-- default:- // Search by query- endpoints := s.openAPIIndex.Search(input.Query)- if len(endpoints) == 0 {- text = fmt.Sprintf("No endpoints found for query: %q\n\nTry:\n- Different keywords\n- Listing services with search_api() (no parameters)\n- Browsing a service with search_api(service=\"ServiceName\")", input.Query)- } else {- text = s.formatEndpoints(endpoints, s.getLimit(input.Limit))- }}return &mcp.CallToolResult{@@ -100,16 +74,6 @@ func (s *Server) handleSearchAPI(_ context.Context, _ *mcp.CallToolRequest, inpu}, nil, nil}-func (*Server) getLimit(limit int) int {- if limit <= 0 {- return 5- }- if limit > 50 {- return 50- }- return limit-}-func (s *Server) formatServiceList() string {services := s.openAPIIndex.Services()var sb strings.Builder@@ -152,7 +116,7 @@ func (*Server) formatEndpoints(endpoints []*EndpointInfo, limit int) string {func (s *Server) formatEndpointDetail(operationID string) string {ep, ok := s.openAPIIndex.GetEndpoint(operationID)if !ok {- return fmt.Sprintf("Unknown operationId: %s\n\nUse search_api(query=\"...\") to find valid operations.", operationID)+ return fmt.Sprintf("Unknown operationId: %s\n\nUse search_api(service=\"...\") to browse endpoints.", operationID)}var sb strings.Builderdiff --git a/backend/api/mcp/tool_search_test.go b/backend/api/mcp/tool_search_test.goindex 6b530a412a..94b9179d75 100644--- a/backend/api/mcp/tool_search_test.go+++ b/backend/api/mcp/tool_search_test.go@@ -30,50 +30,6 @@ func TestSearchAPIListServices(t *testing.T) {require.Contains(t, text, "ProjectService")}-func TestSearchAPIByQuery(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := NewServer(nil, profile, "test-secret")- require.NoError(t, err)-- tests := []struct {- name string- query string- expectContain []string- }{- {- name: "search for sql",- query: "sql",- expectContain: []string{"SQL"},- },- {- name: "search for database",- query: "database",- expectContain: []string{"Database"},- },- {- name: "search for project",- query: "project",- expectContain: []string{"Project"},- },- }-- for _, tc := range tests {- t.Run(tc.name, func(t *testing.T) {- result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{- Query: tc.query,- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- for _, expected := range tc.expectContain {- require.Contains(t, text, expected, "expected %q in result for query %q", expected, tc.query)- }- })- }-}-func TestSearchAPIByService(t *testing.T) {profile := &config.Profile{Mode: common.ReleaseModeDev}s, err := NewServer(nil, profile, "test-secret")@@ -184,83 +140,6 @@ func TestSearchAPIDetailModeNotFound(t *testing.T) {require.Contains(t, text, "Unknown operationId")}-func TestSearchAPILimit(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := NewServer(nil, profile, "test-secret")- require.NoError(t, err)-- // Test with custom limit- result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{- Service: "DatabaseService",- Limit: 2,- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- // Should show "Showing X of Y results" if limited- if strings.Contains(text, "Showing") {- require.Contains(t, text, "Showing 2 of")- }-}--func TestSearchAPIDefaultLimit(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := NewServer(nil, profile, "test-secret")- require.NoError(t, err)-- // Test default limit (should be 5)- result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{- Query: "list",- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- // Count how many "###" headers (each endpoint starts with ###)- count := strings.Count(text, "### ")- require.LessOrEqual(t, count, 5, "default limit should be 5")-}--func TestSearchAPIMaxLimit(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := NewServer(nil, profile, "test-secret")- require.NoError(t, err)-- // Test max limit enforcement (should cap at 50)- result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{- Query: "list",- Limit: 100, // Should be capped to 50- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- count := strings.Count(text, "### ")- require.LessOrEqual(t, count, 50, "max limit should be 50")-}--func TestSearchAPINoResults(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := NewServer(nil, profile, "test-secret")- require.NoError(t, err)-- // Test query with no results - use a query that truly won't match anything- result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{- Query: "zzzzqqqq",- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "No endpoints found")- require.Contains(t, text, "Try:")-}-func TestSearchAPIServiceShowsAll(t *testing.T) {profile := &config.Profile{Mode: common.ReleaseModeDev}s, err := NewServer(nil, profile, "test-secret")@@ -280,26 +159,6 @@ func TestSearchAPIServiceShowsAll(t *testing.T) {require.NotContains(t, text, "Showing")}-func TestSearchAPIQueryWithService(t *testing.T) {- profile := &config.Profile{Mode: common.ReleaseModeDev}- s, err := NewServer(nil, profile, "test-secret")- require.NoError(t, err)-- // Test query within a specific service- result, _, err := s.handleSearchAPI(context.Background(), nil, SearchInput{- Service: "SQLService",- Query: "query",- })- require.NoError(t, err)- require.NotNil(t, result)- require.Len(t, result.Content, 1)-- text := result.Content[0].(*mcpsdk.TextContent).Text- require.Contains(t, text, "SQLService/")- // Should only return SQLService endpoints- require.NotContains(t, text, "DatabaseService/")-}-func TestSearchAPISchemaLookup(t *testing.T) {profile := &config.Profile{Mode: common.ReleaseModeDev}s, err := NewServer(nil, profile, "test-secret")diff --git a/backend/api/v1/ai_service.go b/backend/api/v1/ai_service.gonew file mode 100644index 0000000000..ea5cd12977--- /dev/null+++ b/backend/api/v1/ai_service.go@@ -0,0 +1,604 @@+package v1++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "net/url"++ "connectrpc.com/connect"+ "github.com/pkg/errors"++ storepb "github.com/bytebase/bytebase/backend/generated-go/store"+ v1pb "github.com/bytebase/bytebase/backend/generated-go/v1"+ "github.com/bytebase/bytebase/backend/generated-go/v1/v1connect"+ "github.com/bytebase/bytebase/backend/store"+)++// AIService implements the AI chat service with tool-calling support.+type AIService struct {+ v1connect.UnimplementedAIServiceHandler+ store *store.Store+}++// NewAIService creates a new AIService.+func NewAIService(store *store.Store) *AIService {+ return &AIService{+ store: store,+ }+}++// Chat sends a conversation with tool definitions to the configured AI provider and returns the response.+func (s *AIService) Chat(ctx context.Context, req *connect.Request[v1pb.AIChatRequest]) (*connect.Response[v1pb.AIChatResponse], error) {+ aiSetting, err := s.store.GetAISetting(ctx)+ if err != nil {+ return nil, err+ }+ if !aiSetting.Enabled {+ return nil, connect.NewError(connect.CodeFailedPrecondition, errors.New("AI is not enabled"))+ }++ switch aiSetting.Provider {+ case storepb.AISetting_OPEN_AI, storepb.AISetting_AZURE_OPENAI:+ return s.chatOpenAI(ctx, aiSetting, req.Msg)+ case storepb.AISetting_GEMINI:+ return s.chatGemini(ctx, aiSetting, req.Msg)+ case storepb.AISetting_CLAUDE:+ return s.chatClaude(ctx, aiSetting, req.Msg)+ default:+ return nil, connect.NewError(connect.CodeInvalidArgument, errors.Errorf("unsupported AI provider %s", aiSetting.Provider))+ }+}++// OpenAI chat types with tool-calling support.++type chatOpenAIRequest struct {+ Model string `json:"model"`+ Messages []chatOpenAIMessage `json:"messages"`+ Tools []chatOpenAITool `json:"tools,omitempty"`+}++type chatOpenAIMessage struct {+ Role string `json:"role"`+ Content *string `json:"content"`+ ToolCalls []json.RawMessage `json:"tool_calls,omitempty"`+ ToolCallID string `json:"tool_call_id,omitempty"`+}++type chatOpenAITool struct {+ Type string `json:"type"`+ Function chatOpenAIFunction `json:"function"`+}++type chatOpenAIFunction struct {+ Name string `json:"name"`+ Description string `json:"description"`+ Parameters any `json:"parameters"`+}++type chatOpenAIToolUse struct {+ ID string `json:"id"`+ Type string `json:"type"`+ Function chatOpenAIFunctionCallRef `json:"function"`+}++type chatOpenAIFunctionCallRef struct {+ Name string `json:"name"`+ Arguments string `json:"arguments"`+}++type chatOpenAIResponse struct {+ Choices []struct {+ Message struct {+ Role string `json:"role"`+ Content *string `json:"content"`+ ToolCalls []json.RawMessage `json:"tool_calls"`+ } `json:"message"`+ } `json:"choices"`+}++// chatOpenAIToolCallParsed extracts the fields we need from a raw tool call JSON.+type chatOpenAIToolCallParsed struct {+ ID string `json:"id"`+ Function struct {+ Name string `json:"name"`+ Arguments string `json:"arguments"`+ } `json:"function"`+}++func (*AIService) chatOpenAI(ctx context.Context, aiSetting *storepb.AISetting, request *v1pb.AIChatRequest) (*connect.Response[v1pb.AIChatResponse], error) {+ payload := chatOpenAIRequest{+ Model: aiSetting.Model,+ }++ for _, m := range request.Messages {+ msg := chatOpenAIMessage{+ Role: chatMessageRoleToOpenAI(m.Role),+ }+ if m.Content != nil {+ msg.Content = m.Content+ }+ if m.ToolCallId != nil {+ msg.ToolCallID = *m.ToolCallId+ }+ for _, tc := range m.ToolCalls {+ if tc.Metadata != nil && *tc.Metadata != "" {+ // Replay the raw tool call JSON exactly as received from the provider.+ // This preserves provider-specific fields like Gemini's thought_signature.+ msg.ToolCalls = append(msg.ToolCalls, json.RawMessage(*tc.Metadata))+ } else {+ // Construct a standard OpenAI tool call.+ raw, _ := json.Marshal(chatOpenAIToolUse{+ ID: tc.Id,+ Type: "function",+ Function: chatOpenAIFunctionCallRef{+ Name: tc.Name,+ Arguments: tc.Arguments,+ },+ })+ msg.ToolCalls = append(msg.ToolCalls, json.RawMessage(raw))+ }+ }+ payload.Messages = append(payload.Messages, msg)+ }++ for _, td := range request.ToolDefinitions {+ var params any+ if err := json.Unmarshal([]byte(td.ParametersSchema), ¶ms); err != nil {+ return nil, errors.Errorf("failed to parse parameters schema for tool %s: %s", td.Name, err)+ }+ payload.Tools = append(payload.Tools, chatOpenAITool{+ Type: "function",+ Function: chatOpenAIFunction{+ Name: td.Name,+ Description: td.Description,+ Parameters: params,+ },+ })+ }++ payloadBytes, err := json.Marshal(payload)+ if err != nil {+ return nil, errors.Errorf("failed to marshal OpenAI request: %s", err)+ }++ httpReq, err := http.NewRequestWithContext(ctx, "POST", aiSetting.Endpoint, bytes.NewBuffer(payloadBytes))+ if err != nil {+ return nil, errors.Errorf("failed to create HTTP request: %s", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")+ if aiSetting.Provider == storepb.AISetting_AZURE_OPENAI {+ httpReq.Header.Set("api-key", aiSetting.ApiKey)+ } else {+ httpReq.Header.Set("Authorization", fmt.Sprintf("Bearer %s", aiSetting.ApiKey))+ }++ body, err := doHTTPRequest(ctx, httpReq, "OpenAI")+ if err != nil {+ return nil, err+ }++ var resp chatOpenAIResponse+ if err := json.Unmarshal(body, &resp); err != nil {+ return nil, errors.Errorf("failed to unmarshal OpenAI response: %s", err)+ }++ result := &v1pb.AIChatResponse{}+ if len(resp.Choices) > 0 {+ msg := resp.Choices[0].Message+ result.Content = msg.Content+ for _, rawTC := range msg.ToolCalls {+ var parsed chatOpenAIToolCallParsed+ if err := json.Unmarshal(rawTC, &parsed); err != nil {+ return nil, errors.Errorf("failed to parse tool call: %s", err)+ }+ // Store the entire raw JSON as metadata so we can replay it exactly,+ // preserving any provider-specific fields (e.g., Gemini thought_signature).+ rawStr := string(rawTC)+ toolCall := &v1pb.AIChatToolCall{+ Id: parsed.ID,+ Name: parsed.Function.Name,+ Arguments: parsed.Function.Arguments,+ Metadata: &rawStr,+ }+ result.ToolCalls = append(result.ToolCalls, toolCall)+ }+ }+ return connect.NewResponse(result), nil+}++// Claude chat types with tool-calling support.++type chatClaudeRequest struct {+ Model string `json:"model"`+ System string `json:"system,omitempty"`+ Messages []chatClaudeMsg `json:"messages"`+ Tools []chatClaudeTool `json:"tools,omitempty"`+ MaxTokens int `json:"max_tokens"`+}++type chatClaudeMsg struct {+ Role string `json:"role"`+ Content any `json:"content"`+}++type chatClaudeTool struct {+ Name string `json:"name"`+ Description string `json:"description"`+ InputSchema any `json:"input_schema"`+}++type chatClaudeContentBlock struct {+ Type string `json:"type"`+ Text string `json:"text,omitempty"`+ ID string `json:"id,omitempty"`+ Name string `json:"name,omitempty"`+ Input any `json:"input,omitempty"`+ ToolUseID string `json:"tool_use_id,omitempty"`+ Content string `json:"content,omitempty"`+}++type chatClaudeResponse struct {+ Content []chatClaudeContentBlock `json:"content"`+}++func (*AIService) chatClaude(ctx context.Context, aiSetting *storepb.AISetting, request *v1pb.AIChatRequest) (*connect.Response[v1pb.AIChatResponse], error) {+ payload := chatClaudeRequest{+ Model: aiSetting.Model,+ MaxTokens: 4096,+ }++ for _, m := range request.Messages {+ switch m.Role {+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_SYSTEM:+ payload.System = m.GetContent()+ continue+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_USER:+ payload.Messages = append(payload.Messages, chatClaudeMsg{+ Role: "user",+ Content: m.GetContent(),+ })+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_ASSISTANT:+ var contentBlocks []chatClaudeContentBlock+ if m.Content != nil && *m.Content != "" {+ contentBlocks = append(contentBlocks, chatClaudeContentBlock{+ Type: "text",+ Text: *m.Content,+ })+ }+ for _, tc := range m.ToolCalls {+ var input any+ if err := json.Unmarshal([]byte(tc.Arguments), &input); err != nil {+ input = tc.Arguments+ }+ contentBlocks = append(contentBlocks, chatClaudeContentBlock{+ Type: "tool_use",+ ID: tc.Id,+ Name: tc.Name,+ Input: input,+ })+ }+ payload.Messages = append(payload.Messages, chatClaudeMsg{+ Role: "assistant",+ Content: contentBlocks,+ })+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_TOOL:+ // Claude uses "user" role with tool_result content block.+ payload.Messages = append(payload.Messages, chatClaudeMsg{+ Role: "user",+ Content: []chatClaudeContentBlock{+ {+ Type: "tool_result",+ ToolUseID: m.GetToolCallId(),+ Content: m.GetContent(),+ },+ },+ })+ default:+ continue+ }+ }++ for _, td := range request.ToolDefinitions {+ var schema any+ if err := json.Unmarshal([]byte(td.ParametersSchema), &schema); err != nil {+ return nil, errors.Errorf("failed to parse parameters schema for tool %s: %s", td.Name, err)+ }+ payload.Tools = append(payload.Tools, chatClaudeTool{+ Name: td.Name,+ Description: td.Description,+ InputSchema: schema,+ })+ }++ payloadBytes, err := json.Marshal(payload)+ if err != nil {+ return nil, errors.Errorf("failed to marshal Claude request: %s", err)+ }++ httpReq, err := http.NewRequestWithContext(ctx, "POST", aiSetting.Endpoint, bytes.NewBuffer(payloadBytes))+ if err != nil {+ return nil, errors.Errorf("failed to create HTTP request: %s", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")+ httpReq.Header.Set("x-api-key", aiSetting.ApiKey)+ if aiSetting.Version != "" {+ httpReq.Header.Set("anthropic-version", aiSetting.Version)+ } else {+ httpReq.Header.Set("anthropic-version", "2023-06-01")+ }++ body, err := doHTTPRequest(ctx, httpReq, "Claude")+ if err != nil {+ return nil, err+ }++ var resp chatClaudeResponse+ if err := json.Unmarshal(body, &resp); err != nil {+ return nil, errors.Errorf("failed to unmarshal Claude response: %s", err)+ }++ result := &v1pb.AIChatResponse{}+ var textContent string+ for _, block := range resp.Content {+ switch block.Type {+ case "text":+ textContent += block.Text+ case "tool_use":+ args, err := json.Marshal(block.Input)+ if err != nil {+ return nil, errors.Errorf("failed to marshal tool call input: %s", err)+ }+ result.ToolCalls = append(result.ToolCalls, &v1pb.AIChatToolCall{+ Id: block.ID,+ Name: block.Name,+ Arguments: string(args),+ })+ default:+ }+ }+ if textContent != "" {+ result.Content = &textContent+ }+ return connect.NewResponse(result), nil+}++// Gemini chat types with tool-calling support.++type chatGeminiRequest struct {+ Contents []chatGeminiContent `json:"contents"`+ Tools []chatGeminiTool `json:"tools,omitempty"`+}++type chatGeminiContent struct {+ Role string `json:"role"`+ Parts []chatGeminiPart `json:"parts"`+}++type chatGeminiPart struct {+ Text string `json:"text,omitempty"`+ FunctionCall *chatGeminiFunctionCall `json:"functionCall,omitempty"`+ FunctionResponse *chatGeminiFunctionResult `json:"functionResponse,omitempty"`+}++type chatGeminiFunctionCall struct {+ Name string `json:"name"`+ Args any `json:"args"`+ ThoughtSignature string `json:"thoughtSignature,omitempty"`+}++type chatGeminiFunctionResult struct {+ Name string `json:"name"`+ Response any `json:"response"`+}++type chatGeminiTool struct {+ FunctionDeclarations []chatGeminiFunctionDecl `json:"functionDeclarations"`+}++type chatGeminiFunctionDecl struct {+ Name string `json:"name"`+ Description string `json:"description"`+ Parameters any `json:"parameters"`+}++type chatGeminiResponse struct {+ Candidates []struct {+ Content struct {+ Parts []chatGeminiResponsePart `json:"parts"`+ } `json:"content"`+ } `json:"candidates"`+}++type chatGeminiResponsePart struct {+ Text string `json:"text,omitempty"`+ FunctionCall *chatGeminiFunctionCall `json:"functionCall,omitempty"`+}++func (*AIService) chatGemini(ctx context.Context, aiSetting *storepb.AISetting, request *v1pb.AIChatRequest) (*connect.Response[v1pb.AIChatResponse], error) {+ payload := chatGeminiRequest{}++ for _, m := range request.Messages {+ switch m.Role {+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_SYSTEM:+ // Gemini handles system messages as the first user message.+ payload.Contents = append(payload.Contents, chatGeminiContent{+ Role: "user",+ Parts: []chatGeminiPart{{Text: m.GetContent()}},+ })+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_USER:+ payload.Contents = append(payload.Contents, chatGeminiContent{+ Role: "user",+ Parts: []chatGeminiPart{{Text: m.GetContent()}},+ })+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_ASSISTANT:+ var parts []chatGeminiPart+ if m.Content != nil && *m.Content != "" {+ parts = append(parts, chatGeminiPart{Text: *m.Content})+ }+ for _, tc := range m.ToolCalls {+ var args any+ if err := json.Unmarshal([]byte(tc.Arguments), &args); err != nil {+ args = tc.Arguments+ }+ fc := &chatGeminiFunctionCall{+ Name: tc.Name,+ Args: args,+ }+ if tc.Metadata != nil {+ fc.ThoughtSignature = *tc.Metadata+ }+ parts = append(parts, chatGeminiPart{+ FunctionCall: fc,+ })+ }+ payload.Contents = append(payload.Contents, chatGeminiContent{+ Role: "model",+ Parts: parts,+ })+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_TOOL:+ // Gemini uses functionResponse parts in a "user" role message.+ // We need the tool name; get it from the tool call ID by searching prior messages.+ toolName := getToolNameFromMessages(request.Messages, m.GetToolCallId())+ var resultData any+ if err := json.Unmarshal([]byte(m.GetContent()), &resultData); err != nil {+ resultData = map[string]string{"result": m.GetContent()}+ }+ payload.Contents = append(payload.Contents, chatGeminiContent{+ Role: "user",+ Parts: []chatGeminiPart{+ {+ FunctionResponse: &chatGeminiFunctionResult{+ Name: toolName,+ Response: resultData,+ },+ },+ },+ })+ default:+ }+ }++ if len(request.ToolDefinitions) > 0 {+ var decls []chatGeminiFunctionDecl+ for _, td := range request.ToolDefinitions {+ var params any+ if err := json.Unmarshal([]byte(td.ParametersSchema), ¶ms); err != nil {+ return nil, errors.Errorf("failed to parse parameters schema for tool %s: %s", td.Name, err)+ }+ decls = append(decls, chatGeminiFunctionDecl{+ Name: td.Name,+ Description: td.Description,+ Parameters: params,+ })+ }+ payload.Tools = []chatGeminiTool{{FunctionDeclarations: decls}}+ }++ payloadBytes, err := json.Marshal(payload)+ if err != nil {+ return nil, errors.Errorf("failed to marshal Gemini request: %s", err)+ }++ requestURL, err := url.JoinPath(aiSetting.Endpoint, "models", aiSetting.Model+":generateContent")+ if err != nil {+ return nil, errors.Wrap(err, "failed to build Gemini request URL")+ }+ httpReq, err := http.NewRequestWithContext(ctx, "POST", requestURL, bytes.NewBuffer(payloadBytes))+ if err != nil {+ return nil, errors.Errorf("failed to create HTTP request: %s", err)+ }+ httpReq.Header.Set("Content-Type", "application/json")+ httpReq.Header.Set("x-goog-api-key", aiSetting.ApiKey)++ body, err := doHTTPRequest(ctx, httpReq, "Gemini")+ if err != nil {+ return nil, err+ }++ var resp chatGeminiResponse+ if err := json.Unmarshal(body, &resp); err != nil {+ return nil, errors.Errorf("failed to unmarshal Gemini response: %s", err)+ }++ result := &v1pb.AIChatResponse{}+ if len(resp.Candidates) > 0 {+ var textContent string+ for _, part := range resp.Candidates[0].Content.Parts {+ if part.Text != "" {+ textContent += part.Text+ }+ if part.FunctionCall != nil {+ args, err := json.Marshal(part.FunctionCall.Args)+ if err != nil {+ return nil, errors.Errorf("failed to marshal function call args: %s", err)+ }+ tc := &v1pb.AIChatToolCall{+ Id: fmt.Sprintf("call_%s", part.FunctionCall.Name),+ Name: part.FunctionCall.Name,+ Arguments: string(args),+ }+ if part.FunctionCall.ThoughtSignature != "" {+ tc.Metadata = &part.FunctionCall.ThoughtSignature+ }+ result.ToolCalls = append(result.ToolCalls, tc)+ }+ }+ if textContent != "" {+ result.Content = &textContent+ }+ }+ return connect.NewResponse(result), nil+}++// doHTTPRequest executes an HTTP request and returns the response body.+func doHTTPRequest(_ context.Context, httpReq *http.Request, provider string) ([]byte, error) {+ client := &http.Client{}+ httpResp, err := client.Do(httpReq)+ if err != nil {+ return nil, errors.Errorf("failed to send HTTP request to %s: %s", provider, err)+ }+ defer httpResp.Body.Close()++ body, err := io.ReadAll(httpResp.Body)+ if err != nil {+ return nil, errors.Errorf("failed to read %s response body: %s", provider, err)+ }++ if httpResp.StatusCode != http.StatusOK {+ return nil, errors.Errorf("%s API returned status %d: %s", provider, httpResp.StatusCode, string(body))+ }++ return body, nil+}++// chatMessageRoleToOpenAI converts a proto role enum to OpenAI role string.+func chatMessageRoleToOpenAI(role v1pb.AIChatMessageRole) string {+ switch role {+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_SYSTEM:+ return "system"+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_USER:+ return "user"+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_ASSISTANT:+ return "assistant"+ case v1pb.AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_TOOL:+ return "tool"+ default:+ return "user"+ }+}++// getToolNameFromMessages finds the tool name for a given tool call ID by searching assistant messages.+func getToolNameFromMessages(messages []*v1pb.AIChatMessage, toolCallID string) string {+ for _, m := range messages {+ for _, tc := range m.ToolCalls {+ if tc.Id == toolCallID {+ return tc.Name+ }+ }+ }+ return toolCallID+}diff --git a/backend/api/v1/sql_service_ai.go b/backend/api/v1/sql_service_ai.goindex bf455c41ae..caaa5cd372 100644--- a/backend/api/v1/sql_service_ai.go+++ b/backend/api/v1/sql_service_ai.go@@ -7,6 +7,7 @@ import ("fmt""io""net/http"+ "net/url""strings""connectrpc.com/connect"@@ -223,15 +224,19 @@ func callGemini(ctx context.Context, aiSetting *storepb.AISetting, request *v1pbreturn nil, errors.Errorf("failed to marshal Gemini request payload: %s", err)}- // Gemini API endpoint format: https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent?key={apiKey}- url := fmt.Sprintf("%s/models/%s:generateContent?key=%s", aiSetting.Endpoint, aiSetting.Model, aiSetting.ApiKey)+ // Gemini API endpoint format: https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent+ requestURL, err := url.JoinPath(aiSetting.Endpoint, "models", aiSetting.Model+":generateContent")+ if err != nil {+ return nil, errors.Wrap(err, "failed to build Gemini request URL")+ }- httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(payloadBytes))+ httpReq, err := http.NewRequestWithContext(ctx, "POST", requestURL, bytes.NewBuffer(payloadBytes))if err != nil {return nil, errors.Errorf("failed to create HTTP request: %s", err)}httpReq.Header.Set("Content-Type", "application/json")+ httpReq.Header.Set("x-goog-api-key", aiSetting.ApiKey)client := &http.Client{}httpResp, err := client.Do(httpReq)diff --git a/backend/generated-go/v1/ai_service.pb.go b/backend/generated-go/v1/ai_service.pb.gonew file mode 100644index 0000000000..2d70c757be--- /dev/null+++ b/backend/generated-go/v1/ai_service.pb.go@@ -0,0 +1,515 @@+// Code generated by protoc-gen-go. DO NOT EDIT.+// versions:+// protoc-gen-go v1.36.11+// protoc (unknown)+// source: v1/ai_service.proto++package v1++import (+ _ "google.golang.org/genproto/googleapis/api/annotations"+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"+ reflect "reflect"+ sync "sync"+ unsafe "unsafe"+)++const (+ // Verify that this generated code is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)+ // Verify that runtime/protoimpl is sufficiently up-to-date.+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)+)++// Role of a chat message.+type AIChatMessageRole int32++const (+ // Unspecified role.+ AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_UNSPECIFIED AIChatMessageRole = 0+ // System message providing instructions.+ AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_SYSTEM AIChatMessageRole = 1+ // User message.+ AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_USER AIChatMessageRole = 2+ // Assistant (AI) message.+ AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_ASSISTANT AIChatMessageRole = 3+ // Tool result message.+ AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_TOOL AIChatMessageRole = 4+)++// Enum value maps for AIChatMessageRole.+var (+ AIChatMessageRole_name = map[int32]string{+ 0: "AI_CHAT_MESSAGE_ROLE_UNSPECIFIED",+ 1: "AI_CHAT_MESSAGE_ROLE_SYSTEM",+ 2: "AI_CHAT_MESSAGE_ROLE_USER",+ 3: "AI_CHAT_MESSAGE_ROLE_ASSISTANT",+ 4: "AI_CHAT_MESSAGE_ROLE_TOOL",+ }+ AIChatMessageRole_value = map[string]int32{+ "AI_CHAT_MESSAGE_ROLE_UNSPECIFIED": 0,+ "AI_CHAT_MESSAGE_ROLE_SYSTEM": 1,+ "AI_CHAT_MESSAGE_ROLE_USER": 2,+ "AI_CHAT_MESSAGE_ROLE_ASSISTANT": 3,+ "AI_CHAT_MESSAGE_ROLE_TOOL": 4,+ }+)++func (x AIChatMessageRole) Enum() *AIChatMessageRole {+ p := new(AIChatMessageRole)+ *p = x+ return p+}++func (x AIChatMessageRole) String() string {+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))+}++func (AIChatMessageRole) Descriptor() protoreflect.EnumDescriptor {+ return file_v1_ai_service_proto_enumTypes[0].Descriptor()+}++func (AIChatMessageRole) Type() protoreflect.EnumType {+ return &file_v1_ai_service_proto_enumTypes[0]+}++func (x AIChatMessageRole) Number() protoreflect.EnumNumber {+ return protoreflect.EnumNumber(x)+}++// Deprecated: Use AIChatMessageRole.Descriptor instead.+func (AIChatMessageRole) EnumDescriptor() ([]byte, []int) {+ return file_v1_ai_service_proto_rawDescGZIP(), []int{0}+}++// A single message in the conversation.+type AIChatMessage struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // The role of the message sender.+ Role AIChatMessageRole `protobuf:"varint,1,opt,name=role,proto3,enum=bytebase.v1.AIChatMessageRole" json:"role,omitempty"`+ // The text content of the message. Optional for assistant messages that only contain tool calls.+ Content *string `protobuf:"bytes,2,opt,name=content,proto3,oneof" json:"content,omitempty"`+ // Tool calls made by the assistant. Only present in assistant messages.+ ToolCalls []*AIChatToolCall `protobuf:"bytes,3,rep,name=tool_calls,json=toolCalls,proto3" json:"tool_calls,omitempty"`+ // The ID of the tool call this message is responding to. Only present in tool messages.+ ToolCallId *string `protobuf:"bytes,4,opt,name=tool_call_id,json=toolCallId,proto3,oneof" json:"tool_call_id,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *AIChatMessage) Reset() {+ *x = AIChatMessage{}+ mi := &file_v1_ai_service_proto_msgTypes[0]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *AIChatMessage) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*AIChatMessage) ProtoMessage() {}++func (x *AIChatMessage) ProtoReflect() protoreflect.Message {+ mi := &file_v1_ai_service_proto_msgTypes[0]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use AIChatMessage.ProtoReflect.Descriptor instead.+func (*AIChatMessage) Descriptor() ([]byte, []int) {+ return file_v1_ai_service_proto_rawDescGZIP(), []int{0}+}++func (x *AIChatMessage) GetRole() AIChatMessageRole {+ if x != nil {+ return x.Role+ }+ return AIChatMessageRole_AI_CHAT_MESSAGE_ROLE_UNSPECIFIED+}++func (x *AIChatMessage) GetContent() string {+ if x != nil && x.Content != nil {+ return *x.Content+ }+ return ""+}++func (x *AIChatMessage) GetToolCalls() []*AIChatToolCall {+ if x != nil {+ return x.ToolCalls+ }+ return nil+}++func (x *AIChatMessage) GetToolCallId() string {+ if x != nil && x.ToolCallId != nil {+ return *x.ToolCallId+ }+ return ""+}++// A tool definition that the AI can invoke.+type AIChatToolDefinition struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // The name of the tool.+ Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`+ // A description of what the tool does.+ Description string `protobuf:"bytes,2,opt,name=description,proto3" json:"description,omitempty"`+ // The JSON Schema describing the tool's parameters.+ ParametersSchema string `protobuf:"bytes,3,opt,name=parameters_schema,json=parametersSchema,proto3" json:"parameters_schema,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *AIChatToolDefinition) Reset() {+ *x = AIChatToolDefinition{}+ mi := &file_v1_ai_service_proto_msgTypes[1]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *AIChatToolDefinition) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*AIChatToolDefinition) ProtoMessage() {}++func (x *AIChatToolDefinition) ProtoReflect() protoreflect.Message {+ mi := &file_v1_ai_service_proto_msgTypes[1]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use AIChatToolDefinition.ProtoReflect.Descriptor instead.+func (*AIChatToolDefinition) Descriptor() ([]byte, []int) {+ return file_v1_ai_service_proto_rawDescGZIP(), []int{1}+}++func (x *AIChatToolDefinition) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *AIChatToolDefinition) GetDescription() string {+ if x != nil {+ return x.Description+ }+ return ""+}++func (x *AIChatToolDefinition) GetParametersSchema() string {+ if x != nil {+ return x.ParametersSchema+ }+ return ""+}++// A tool call made by the AI.+type AIChatToolCall struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // The unique ID of this tool call.+ Id string `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`+ // The name of the tool to call.+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"`+ // The JSON-encoded arguments to pass to the tool.+ Arguments string `protobuf:"bytes,3,opt,name=arguments,proto3" json:"arguments,omitempty"`+ // Opaque provider-specific metadata (e.g., Gemini thought_signature).+ // Frontend must echo this back unchanged when sending tool results.+ Metadata *string `protobuf:"bytes,4,opt,name=metadata,proto3,oneof" json:"metadata,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *AIChatToolCall) Reset() {+ *x = AIChatToolCall{}+ mi := &file_v1_ai_service_proto_msgTypes[2]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *AIChatToolCall) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*AIChatToolCall) ProtoMessage() {}++func (x *AIChatToolCall) ProtoReflect() protoreflect.Message {+ mi := &file_v1_ai_service_proto_msgTypes[2]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use AIChatToolCall.ProtoReflect.Descriptor instead.+func (*AIChatToolCall) Descriptor() ([]byte, []int) {+ return file_v1_ai_service_proto_rawDescGZIP(), []int{2}+}++func (x *AIChatToolCall) GetId() string {+ if x != nil {+ return x.Id+ }+ return ""+}++func (x *AIChatToolCall) GetName() string {+ if x != nil {+ return x.Name+ }+ return ""+}++func (x *AIChatToolCall) GetArguments() string {+ if x != nil {+ return x.Arguments+ }+ return ""+}++func (x *AIChatToolCall) GetMetadata() string {+ if x != nil && x.Metadata != nil {+ return *x.Metadata+ }+ return ""+}++// Request message for AIService.Chat.+type AIChatRequest struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // The conversation messages.+ Messages []*AIChatMessage `protobuf:"bytes,1,rep,name=messages,proto3" json:"messages,omitempty"`+ // The tool definitions available to the AI.+ ToolDefinitions []*AIChatToolDefinition `protobuf:"bytes,2,rep,name=tool_definitions,json=toolDefinitions,proto3" json:"tool_definitions,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *AIChatRequest) Reset() {+ *x = AIChatRequest{}+ mi := &file_v1_ai_service_proto_msgTypes[3]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *AIChatRequest) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*AIChatRequest) ProtoMessage() {}++func (x *AIChatRequest) ProtoReflect() protoreflect.Message {+ mi := &file_v1_ai_service_proto_msgTypes[3]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use AIChatRequest.ProtoReflect.Descriptor instead.+func (*AIChatRequest) Descriptor() ([]byte, []int) {+ return file_v1_ai_service_proto_rawDescGZIP(), []int{3}+}++func (x *AIChatRequest) GetMessages() []*AIChatMessage {+ if x != nil {+ return x.Messages+ }+ return nil+}++func (x *AIChatRequest) GetToolDefinitions() []*AIChatToolDefinition {+ if x != nil {+ return x.ToolDefinitions+ }+ return nil+}++// Response message for AIService.Chat.+type AIChatResponse struct {+ state protoimpl.MessageState `protogen:"open.v1"`+ // The text content of the AI response. Optional when the response only contains tool calls.+ Content *string `protobuf:"bytes,1,opt,name=content,proto3,oneof" json:"content,omitempty"`+ // Tool calls the AI wants to make.+ ToolCalls []*AIChatToolCall `protobuf:"bytes,2,rep,name=tool_calls,json=toolCalls,proto3" json:"tool_calls,omitempty"`+ unknownFields protoimpl.UnknownFields+ sizeCache protoimpl.SizeCache+}++func (x *AIChatResponse) Reset() {+ *x = AIChatResponse{}+ mi := &file_v1_ai_service_proto_msgTypes[4]+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ ms.StoreMessageInfo(mi)+}++func (x *AIChatResponse) String() string {+ return protoimpl.X.MessageStringOf(x)+}++func (*AIChatResponse) ProtoMessage() {}++func (x *AIChatResponse) ProtoReflect() protoreflect.Message {+ mi := &file_v1_ai_service_proto_msgTypes[4]+ if x != nil {+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))+ if ms.LoadMessageInfo() == nil {+ ms.StoreMessageInfo(mi)+ }+ return ms+ }+ return mi.MessageOf(x)+}++// Deprecated: Use AIChatResponse.ProtoReflect.Descriptor instead.+func (*AIChatResponse) Descriptor() ([]byte, []int) {+ return file_v1_ai_service_proto_rawDescGZIP(), []int{4}+}++func (x *AIChatResponse) GetContent() string {+ if x != nil && x.Content != nil {+ return *x.Content+ }+ return ""+}++func (x *AIChatResponse) GetToolCalls() []*AIChatToolCall {+ if x != nil {+ return x.ToolCalls+ }+ return nil+}++var File_v1_ai_service_proto protoreflect.FileDescriptor++const file_v1_ai_service_proto_rawDesc = "" ++ "\n" ++ "\x13v1/ai_service.proto\x12\vbytebase.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x13v1/annotation.proto\"\xe2\x01\n" ++ "\rAIChatMessage\x122\n" ++ "\x04role\x18\x01 \x01(\x0e2\x1e.bytebase.v1.AIChatMessageRoleR\x04role\x12\x1d\n" ++ "\acontent\x18\x02 \x01(\tH\x00R\acontent\x88\x01\x01\x12:\n" ++ "\n" ++ "tool_calls\x18\x03 \x03(\v2\x1b.bytebase.v1.AIChatToolCallR\ttoolCalls\x12%\n" ++ "\ftool_call_id\x18\x04 \x01(\tH\x01R\n" ++ "toolCallId\x88\x01\x01B\n" ++ "\n" ++ "\b_contentB\x0f\n" ++ "\r_tool_call_id\"y\n" ++ "\x14AIChatToolDefinition\x12\x12\n" ++ "\x04name\x18\x01 \x01(\tR\x04name\x12 \n" ++ "\vdescription\x18\x02 \x01(\tR\vdescription\x12+\n" ++ "\x11parameters_schema\x18\x03 \x01(\tR\x10parametersSchema\"\x80\x01\n" ++ "\x0eAIChatToolCall\x12\x0e\n" ++ "\x02id\x18\x01 \x01(\tR\x02id\x12\x12\n" ++ "\x04name\x18\x02 \x01(\tR\x04name\x12\x1c\n" ++ "\targuments\x18\x03 \x01(\tR\targuments\x12\x1f\n" ++ "\bmetadata\x18\x04 \x01(\tH\x00R\bmetadata\x88\x01\x01B\v\n" ++ "\t_metadata\"\x95\x01\n" ++ "\rAIChatRequest\x126\n" ++ "\bmessages\x18\x01 \x03(\v2\x1a.bytebase.v1.AIChatMessageR\bmessages\x12L\n" ++ "\x10tool_definitions\x18\x02 \x03(\v2!.bytebase.v1.AIChatToolDefinitionR\x0ftoolDefinitions\"w\n" ++ "\x0eAIChatResponse\x12\x1d\n" ++ "\acontent\x18\x01 \x01(\tH\x00R\acontent\x88\x01\x01\x12:\n" ++ "\n" ++ "tool_calls\x18\x02 \x03(\v2\x1b.bytebase.v1.AIChatToolCallR\ttoolCallsB\n" ++ "\n" ++ "\b_content*\xbc\x01\n" ++ "\x11AIChatMessageRole\x12$\n" ++ " AI_CHAT_MESSAGE_ROLE_UNSPECIFIED\x10\x00\x12\x1f\n" ++ "\x1bAI_CHAT_MESSAGE_ROLE_SYSTEM\x10\x01\x12\x1d\n" ++ "\x19AI_CHAT_MESSAGE_ROLE_USER\x10\x02\x12\"\n" ++ "\x1eAI_CHAT_MESSAGE_ROLE_ASSISTANT\x10\x03\x12\x1d\n" ++ "\x19AI_CHAT_MESSAGE_ROLE_TOOL\x10\x042h\n" ++ "\tAIService\x12[\n" ++ "\x04Chat\x12\x1a.bytebase.v1.AIChatRequest\x1a\x1b.bytebase.v1.AIChatResponse\"\x1a\x90\xea0\x02\x82\xd3\xe4\x93\x02\x10:\x01*\"\v/v1/ai/chatB\xa4\x01\n" ++ "\x0fcom.bytebase.v1B\x0eAiServiceProtoP\x01Z4github.com/bytebase/bytebase/backend/generated-go/v1\xa2\x02\x03BXX\xaa\x02\vBytebase.V1\xca\x02\vBytebase\\V1\xe2\x02\x17Bytebase\\V1\\GPBMetadata\xea\x02\fBytebase::V1b\x06proto3"++var (+ file_v1_ai_service_proto_rawDescOnce sync.Once+ file_v1_ai_service_proto_rawDescData []byte+)++func file_v1_ai_service_proto_rawDescGZIP() []byte {+ file_v1_ai_service_proto_rawDescOnce.Do(func() {+ file_v1_ai_service_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_v1_ai_service_proto_rawDesc), len(file_v1_ai_service_proto_rawDesc)))+ })+ return file_v1_ai_service_proto_rawDescData+}++var file_v1_ai_service_proto_enumTypes = make([]protoimpl.EnumInfo, 1)+var file_v1_ai_service_proto_msgTypes = make([]protoimpl.MessageInfo, 5)+var file_v1_ai_service_proto_goTypes = []any{+ (AIChatMessageRole)(0), // 0: bytebase.v1.AIChatMessageRole+ (*AIChatMessage)(nil), // 1: bytebase.v1.AIChatMessage+ (*AIChatToolDefinition)(nil), // 2: bytebase.v1.AIChatToolDefinition+ (*AIChatToolCall)(nil), // 3: bytebase.v1.AIChatToolCall+ (*AIChatRequest)(nil), // 4: bytebase.v1.AIChatRequest+ (*AIChatResponse)(nil), // 5: bytebase.v1.AIChatResponse+}+var file_v1_ai_service_proto_depIdxs = []int32{+ 0, // 0: bytebase.v1.AIChatMessage.role:type_name -> bytebase.v1.AIChatMessageRole+ 3, // 1: bytebase.v1.AIChatMessage.tool_calls:type_name -> bytebase.v1.AIChatToolCall+ 1, // 2: bytebase.v1.AIChatRequest.messages:type_name -> bytebase.v1.AIChatMessage+ 2, // 3: bytebase.v1.AIChatRequest.tool_definitions:type_name -> bytebase.v1.AIChatToolDefinition+ 3, // 4: bytebase.v1.AIChatResponse.tool_calls:type_name -> bytebase.v1.AIChatToolCall+ 4, // 5: bytebase.v1.AIService.Chat:input_type -> bytebase.v1.AIChatRequest+ 5, // 6: bytebase.v1.AIService.Chat:output_type -> bytebase.v1.AIChatResponse+ 6, // [6:7] is the sub-list for method output_type+ 5, // [5:6] is the sub-list for method input_type+ 5, // [5:5] is the sub-list for extension type_name+ 5, // [5:5] is the sub-list for extension extendee+ 0, // [0:5] is the sub-list for field type_name+}++func init() { file_v1_ai_service_proto_init() }+func file_v1_ai_service_proto_init() {+ if File_v1_ai_service_proto != nil {+ return+ }+ file_v1_annotation_proto_init()+ file_v1_ai_service_proto_msgTypes[0].OneofWrappers = []any{}+ file_v1_ai_service_proto_msgTypes[2].OneofWrappers = []any{}+ file_v1_ai_service_proto_msgTypes[4].OneofWrappers = []any{}+ type x struct{}+ out := protoimpl.TypeBuilder{+ File: protoimpl.DescBuilder{+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_v1_ai_service_proto_rawDesc), len(file_v1_ai_service_proto_rawDesc)),+ NumEnums: 1,+ NumMessages: 5,+ NumExtensions: 0,+ NumServices: 1,+ },+ GoTypes: file_v1_ai_service_proto_goTypes,+ DependencyIndexes: file_v1_ai_service_proto_depIdxs,+ EnumInfos: file_v1_ai_service_proto_enumTypes,+ MessageInfos: file_v1_ai_service_proto_msgTypes,+ }.Build()+ File_v1_ai_service_proto = out.File+ file_v1_ai_service_proto_goTypes = nil+ file_v1_ai_service_proto_depIdxs = nil+}diff --git a/backend/generated-go/v1/ai_service.pb.gw.go b/backend/generated-go/v1/ai_service.pb.gw.gonew file mode 100644index 0000000000..fa8b06b75d--- /dev/null+++ b/backend/generated-go/v1/ai_service.pb.gw.go@@ -0,0 +1,157 @@+// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.+// source: v1/ai_service.proto++/*+Package v1 is a reverse proxy.++It translates gRPC into RESTful JSON APIs.+*/+package v1++import (+ "context"+ "errors"+ "io"+ "net/http"++ "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"+ "github.com/grpc-ecosystem/grpc-gateway/v2/utilities"+ "google.golang.org/grpc"+ "google.golang.org/grpc/codes"+ "google.golang.org/grpc/grpclog"+ "google.golang.org/grpc/metadata"+ "google.golang.org/grpc/status"+ "google.golang.org/protobuf/proto"+)++// Suppress "imported and not used" errors+var (+ _ codes.Code+ _ io.Reader+ _ status.Status+ _ = errors.New+ _ = runtime.String+ _ = utilities.NewDoubleArray+ _ = metadata.Join+)++func request_AIService_Chat_0(ctx context.Context, marshaler runtime.Marshaler, client AIServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq AIChatRequest+ metadata runtime.ServerMetadata+ )+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }+ if req.Body != nil {+ _, _ = io.Copy(io.Discard, req.Body)+ }+ msg, err := client.Chat(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))+ return msg, metadata, err+}++func local_request_AIService_Chat_0(ctx context.Context, marshaler runtime.Marshaler, server AIServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {+ var (+ protoReq AIChatRequest+ metadata runtime.ServerMetadata+ )+ if err := marshaler.NewDecoder(req.Body).Decode(&protoReq); err != nil && !errors.Is(err, io.EOF) {+ return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)+ }+ msg, err := server.Chat(ctx, &protoReq)+ return msg, metadata, err+}++// RegisterAIServiceHandlerServer registers the http handlers for service AIService to "mux".+// UnaryRPC :call AIServiceServer directly.+// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.+// Note that using this registration option will cause many gRPC library features to stop working. Consider using RegisterAIServiceHandlerFromEndpoint instead.+// GRPC interceptors will not work for this type of registration. To use interceptors, you must use the "runtime.WithMiddlewares" option in the "runtime.NewServeMux" call.+func RegisterAIServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server AIServiceServer) error {+ mux.Handle(http.MethodPost, pattern_AIService_Chat_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ var stream runtime.ServerTransportStream+ ctx = grpc.NewContextWithServerTransportStream(ctx, &stream)+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateIncomingContext(ctx, mux, req, "/bytebase.v1.AIService/Chat", runtime.WithHTTPPathPattern("/v1/ai/chat"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := local_request_AIService_Chat_0(annotatedContext, inboundMarshaler, server, req, pathParams)+ md.HeaderMD, md.TrailerMD = metadata.Join(md.HeaderMD, stream.Header()), metadata.Join(md.TrailerMD, stream.Trailer())+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_AIService_Chat_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })++ return nil+}++// RegisterAIServiceHandlerFromEndpoint is same as RegisterAIServiceHandler but+// automatically dials to "endpoint" and closes the connection when "ctx" gets done.+func RegisterAIServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {+ conn, err := grpc.NewClient(endpoint, opts...)+ if err != nil {+ return err+ }+ defer func() {+ if err != nil {+ if cerr := conn.Close(); cerr != nil {+ grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr)+ }+ return+ }+ go func() {+ <-ctx.Done()+ if cerr := conn.Close(); cerr != nil {+ grpclog.Errorf("Failed to close conn to %s: %v", endpoint, cerr)+ }+ }()+ }()+ return RegisterAIServiceHandler(ctx, mux, conn)+}++// RegisterAIServiceHandler registers the http handlers for service AIService to "mux".+// The handlers forward requests to the grpc endpoint over "conn".+func RegisterAIServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {+ return RegisterAIServiceHandlerClient(ctx, mux, NewAIServiceClient(conn))+}++// RegisterAIServiceHandlerClient registers the http handlers for service AIService+// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "AIServiceClient".+// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "AIServiceClient"+// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in+// "AIServiceClient" to call the correct interceptors. This client ignores the HTTP middlewares.+func RegisterAIServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client AIServiceClient) error {+ mux.Handle(http.MethodPost, pattern_AIService_Chat_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {+ ctx, cancel := context.WithCancel(req.Context())+ defer cancel()+ inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)+ annotatedContext, err := runtime.AnnotateContext(ctx, mux, req, "/bytebase.v1.AIService/Chat", runtime.WithHTTPPathPattern("/v1/ai/chat"))+ if err != nil {+ runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)+ return+ }+ resp, md, err := request_AIService_Chat_0(annotatedContext, inboundMarshaler, client, req, pathParams)+ annotatedContext = runtime.NewServerMetadataContext(annotatedContext, md)+ if err != nil {+ runtime.HTTPError(annotatedContext, mux, outboundMarshaler, w, req, err)+ return+ }+ forward_AIService_Chat_0(annotatedContext, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)+ })+ return nil+}++var (+ pattern_AIService_Chat_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2}, []string{"v1", "ai", "chat"}, ""))+)++var (+ forward_AIService_Chat_0 = runtime.ForwardResponseMessage+)diff --git a/backend/generated-go/v1/ai_service_equal.pb.go b/backend/generated-go/v1/ai_service_equal.pb.gonew file mode 100644index 0000000000..6e7a24606d--- /dev/null+++ b/backend/generated-go/v1/ai_service_equal.pb.go@@ -0,0 +1,119 @@+// Code generated by protoc-gen-equal-go. DO NOT EDIT.+// source: v1/ai_service.proto++package v1++func (x *AIChatMessage) Equal(y *AIChatMessage) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Role != y.Role {+ return false+ }+ if p, q := x.Content, y.Content; (p == nil && q != nil) || (p != nil && (q == nil || *p != *q)) {+ return false+ }+ if len(x.ToolCalls) != len(y.ToolCalls) {+ return false+ }+ for i := 0; i < len(x.ToolCalls); i++ {+ if !x.ToolCalls[i].Equal(y.ToolCalls[i]) {+ return false+ }+ }+ if p, q := x.ToolCallId, y.ToolCallId; (p == nil && q != nil) || (p != nil && (q == nil || *p != *q)) {+ return false+ }+ return true+}++func (x *AIChatToolDefinition) Equal(y *AIChatToolDefinition) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Name != y.Name {+ return false+ }+ if x.Description != y.Description {+ return false+ }+ if x.ParametersSchema != y.ParametersSchema {+ return false+ }+ return true+}++func (x *AIChatToolCall) Equal(y *AIChatToolCall) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if x.Id != y.Id {+ return false+ }+ if x.Name != y.Name {+ return false+ }+ if x.Arguments != y.Arguments {+ return false+ }+ if p, q := x.Metadata, y.Metadata; (p == nil && q != nil) || (p != nil && (q == nil || *p != *q)) {+ return false+ }+ return true+}++func (x *AIChatRequest) Equal(y *AIChatRequest) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if len(x.Messages) != len(y.Messages) {+ return false+ }+ for i := 0; i < len(x.Messages); i++ {+ if !x.Messages[i].Equal(y.Messages[i]) {+ return false+ }+ }+ if len(x.ToolDefinitions) != len(y.ToolDefinitions) {+ return false+ }+ for i := 0; i < len(x.ToolDefinitions); i++ {+ if !x.ToolDefinitions[i].Equal(y.ToolDefinitions[i]) {+ return false+ }+ }+ return true+}++func (x *AIChatResponse) Equal(y *AIChatResponse) bool {+ if x == y {+ return true+ }+ if x == nil || y == nil {+ return x == nil && y == nil+ }+ if p, q := x.Content, y.Content; (p == nil && q != nil) || (p != nil && (q == nil || *p != *q)) {+ return false+ }+ if len(x.ToolCalls) != len(y.ToolCalls) {+ return false+ }+ for i := 0; i < len(x.ToolCalls); i++ {+ if !x.ToolCalls[i].Equal(y.ToolCalls[i]) {+ return false+ }+ }+ return true+}diff --git a/backend/generated-go/v1/ai_service_grpc.pb.go b/backend/generated-go/v1/ai_service_grpc.pb.gonew file mode 100644index 0000000000..f302cae12c--- /dev/null+++ b/backend/generated-go/v1/ai_service_grpc.pb.go@@ -0,0 +1,129 @@+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.+// versions:+// - protoc-gen-go-grpc v1.6.1+// - protoc (unknown)+// source: v1/ai_service.proto++package v1++import (+ context "context"+ grpc "google.golang.org/grpc"+ codes "google.golang.org/grpc/codes"+ status "google.golang.org/grpc/status"+)++// This is a compile-time assertion to ensure that this generated file+// is compatible with the grpc package it is being compiled against.+// Requires gRPC-Go v1.64.0 or later.+const _ = grpc.SupportPackageIsVersion9++const (+ AIService_Chat_FullMethodName = "/bytebase.v1.AIService/Chat"+)++// AIServiceClient is the client API for AIService service.+//+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.+//+// AIService provides AI chat capabilities for the page agent.+type AIServiceClient interface {+ // Chat sends a conversation with tool definitions to the configured AI provider+ // and returns the AI response.+ Chat(ctx context.Context, in *AIChatRequest, opts ...grpc.CallOption) (*AIChatResponse, error)+}++type aIServiceClient struct {+ cc grpc.ClientConnInterface+}++func NewAIServiceClient(cc grpc.ClientConnInterface) AIServiceClient {+ return &aIServiceClient{cc}+}++func (c *aIServiceClient) Chat(ctx context.Context, in *AIChatRequest, opts ...grpc.CallOption) (*AIChatResponse, error) {+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)+ out := new(AIChatResponse)+ err := c.cc.Invoke(ctx, AIService_Chat_FullMethodName, in, out, cOpts...)+ if err != nil {+ return nil, err+ }+ return out, nil+}++// AIServiceServer is the server API for AIService service.+// All implementations must embed UnimplementedAIServiceServer+// for forward compatibility.+//+// AIService provides AI chat capabilities for the page agent.+type AIServiceServer interface {+ // Chat sends a conversation with tool definitions to the configured AI provider+ // and returns the AI response.+ Chat(context.Context, *AIChatRequest) (*AIChatResponse, error)+ mustEmbedUnimplementedAIServiceServer()+}++// UnimplementedAIServiceServer must be embedded to have+// forward compatible implementations.+//+// NOTE: this should be embedded by value instead of pointer to avoid a nil+// pointer dereference when methods are called.+type UnimplementedAIServiceServer struct{}++func (UnimplementedAIServiceServer) Chat(context.Context, *AIChatRequest) (*AIChatResponse, error) {+ return nil, status.Error(codes.Unimplemented, "method Chat not implemented")+}+func (UnimplementedAIServiceServer) mustEmbedUnimplementedAIServiceServer() {}+func (UnimplementedAIServiceServer) testEmbeddedByValue() {}++// UnsafeAIServiceServer may be embedded to opt out of forward compatibility for this service.+// Use of this interface is not recommended, as added methods to AIServiceServer will+// result in compilation errors.+type UnsafeAIServiceServer interface {+ mustEmbedUnimplementedAIServiceServer()+}++func RegisterAIServiceServer(s grpc.ServiceRegistrar, srv AIServiceServer) {+ // If the following call panics, it indicates UnimplementedAIServiceServer was+ // embedded by pointer and is nil. This will cause panics if an+ // unimplemented method is ever invoked, so we test this at initialization+ // time to prevent it from happening at runtime later due to I/O.+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {+ t.testEmbeddedByValue()+ }+ s.RegisterService(&AIService_ServiceDesc, srv)+}++func _AIService_Chat_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {+ in := new(AIChatRequest)+ if err := dec(in); err != nil {+ return nil, err+ }+ if interceptor == nil {+ return srv.(AIServiceServer).Chat(ctx, in)+ }+ info := &grpc.UnaryServerInfo{+ Server: srv,+ FullMethod: AIService_Chat_FullMethodName,+ }+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {+ return srv.(AIServiceServer).Chat(ctx, req.(*AIChatRequest))+ }+ return interceptor(ctx, in, info, handler)+}++// AIService_ServiceDesc is the grpc.ServiceDesc for AIService service.+// It's only intended for direct use with grpc.RegisterService,+// and not to be introspected or modified (even as a copy)+var AIService_ServiceDesc = grpc.ServiceDesc{+ ServiceName: "bytebase.v1.AIService",+ HandlerType: (*AIServiceServer)(nil),+ Methods: []grpc.MethodDesc{+ {+ MethodName: "Chat",+ Handler: _AIService_Chat_Handler,+ },+ },+ Streams: []grpc.StreamDesc{},+ Metadata: "v1/ai_service.proto",+}diff --git a/backend/generated-go/v1/v1connect/ai_service.connect.go b/backend/generated-go/v1/v1connect/ai_service.connect.gonew file mode 100644index 0000000000..ad6fc9543c--- /dev/null+++ b/backend/generated-go/v1/v1connect/ai_service.connect.go@@ -0,0 +1,112 @@+// Code generated by protoc-gen-connect-go. DO NOT EDIT.+//+// Source: v1/ai_service.proto++package v1connect++import (+ connect "connectrpc.com/connect"+ context "context"+ errors "errors"+ v1 "github.com/bytebase/bytebase/backend/generated-go/v1"+ http "net/http"+ strings "strings"+)++// This is a compile-time assertion to ensure that this generated file and the connect package are+// compatible. If you get a compiler error that this constant is not defined, this code was+// generated with a version of connect newer than the one compiled into your binary. You can fix the+// problem by either regenerating this code with an older version of connect or updating the connect+// version compiled into your binary.+const _ = connect.IsAtLeastVersion1_13_0++const (+ // AIServiceName is the fully-qualified name of the AIService service.+ AIServiceName = "bytebase.v1.AIService"+)++// These constants are the fully-qualified names of the RPCs defined in this package. They're+// exposed at runtime as Spec.Procedure and as the final two segments of the HTTP route.+//+// Note that these are different from the fully-qualified method names used by+// google.golang.org/protobuf/reflect/protoreflect. To convert from these constants to+// reflection-formatted method names, remove the leading slash and convert the remaining slash to a+// period.+const (+ // AIServiceChatProcedure is the fully-qualified name of the AIService's Chat RPC.+ AIServiceChatProcedure = "/bytebase.v1.AIService/Chat"+)++// AIServiceClient is a client for the bytebase.v1.AIService service.+type AIServiceClient interface {+ // Chat sends a conversation with tool definitions to the configured AI provider+ // and returns the AI response.+ Chat(context.Context, *connect.Request[v1.AIChatRequest]) (*connect.Response[v1.AIChatResponse], error)+}++// NewAIServiceClient constructs a client for the bytebase.v1.AIService service. By default, it uses+// the Connect protocol with the binary Protobuf Codec, asks for gzipped responses, and sends+// uncompressed requests. To use the gRPC or gRPC-Web protocols, supply the connect.WithGRPC() or+// connect.WithGRPCWeb() options.+//+// The URL supplied here should be the base URL for the Connect or gRPC server (for example,+// http://api.acme.com or https://acme.com/grpc).+func NewAIServiceClient(httpClient connect.HTTPClient, baseURL string, opts ...connect.ClientOption) AIServiceClient {+ baseURL = strings.TrimRight(baseURL, "/")+ aIServiceMethods := v1.File_v1_ai_service_proto.Services().ByName("AIService").Methods()+ return &aIServiceClient{+ chat: connect.NewClient[v1.AIChatRequest, v1.AIChatResponse](+ httpClient,+ baseURL+AIServiceChatProcedure,+ connect.WithSchema(aIServiceMethods.ByName("Chat")),+ connect.WithClientOptions(opts...),+ ),+ }+}++// aIServiceClient implements AIServiceClient.+type aIServiceClient struct {+ chat *connect.Client[v1.AIChatRequest, v1.AIChatResponse]+}++// Chat calls bytebase.v1.AIService.Chat.+func (c *aIServiceClient) Chat(ctx context.Context, req *connect.Request[v1.AIChatRequest]) (*connect.Response[v1.AIChatResponse], error) {+ return c.chat.CallUnary(ctx, req)+}++// AIServiceHandler is an implementation of the bytebase.v1.AIService service.+type AIServiceHandler interface {+ // Chat sends a conversation with tool definitions to the configured AI provider+ // and returns the AI response.+ Chat(context.Context, *connect.Request[v1.AIChatRequest]) (*connect.Response[v1.AIChatResponse], error)+}++// NewAIServiceHandler builds an HTTP handler from the service implementation. It returns the path+// on which to mount the handler and the handler itself.+//+// By default, handlers support the Connect, gRPC, and gRPC-Web protocols with the binary Protobuf+// and JSON codecs. They also support gzip compression.+func NewAIServiceHandler(svc AIServiceHandler, opts ...connect.HandlerOption) (string, http.Handler) {+ aIServiceMethods := v1.File_v1_ai_service_proto.Services().ByName("AIService").Methods()+ aIServiceChatHandler := connect.NewUnaryHandler(+ AIServiceChatProcedure,+ svc.Chat,+ connect.WithSchema(aIServiceMethods.ByName("Chat")),+ connect.WithHandlerOptions(opts...),+ )+ return "/bytebase.v1.AIService/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case AIServiceChatProcedure:+ aIServiceChatHandler.ServeHTTP(w, r)+ default:+ http.NotFound(w, r)+ }+ })+}++// UnimplementedAIServiceHandler returns CodeUnimplemented from all methods.+type UnimplementedAIServiceHandler struct{}++func (UnimplementedAIServiceHandler) Chat(context.Context, *connect.Request[v1.AIChatRequest]) (*connect.Response[v1.AIChatResponse], error) {+ return nil, connect.NewError(connect.CodeUnimplemented, errors.New("bytebase.v1.AIService.Chat is not implemented"))+}diff --git a/backend/server/grpc_routes.go b/backend/server/grpc_routes.goindex f9a63d817f..5ab114d358 100644--- a/backend/server/grpc_routes.go+++ b/backend/server/grpc_routes.go@@ -87,6 +87,7 @@ func configureGrpcRouters(grpcruntime.DefaultHTTPErrorHandler(ctx, sm, m, w, r, err)}),)+ aiService := apiv1.NewAIService(stores)accessGrantService := apiv1.NewAccessGrantService(stores, licenseService, webhookManager, bus)actuatorService := apiv1.NewActuatorService(stores, profile, schemaSyncer, licenseService, sampleInstanceManager)auditLogService := apiv1.NewAuditLogService(stores, licenseService)@@ -140,6 +141,9 @@ func configureGrpcRouters(connectHandlers := make(map[string]http.Handler)+ aiPath, aiHandler := v1connect.NewAIServiceHandler(aiService, handlerOpts)+ connectHandlers[aiPath] = aiHandler+accessGrantPath, accessGrantHandler := v1connect.NewAccessGrantServiceHandler(accessGrantService, handlerOpts)connectHandlers[accessGrantPath] = accessGrantHandler@@ -232,6 +236,7 @@ func configureGrpcRouters(// grpc reflection handlers.reflector := grpcreflect.NewStaticReflector(+ v1connect.AIServiceName,v1connect.AccessGrantServiceName,v1connect.ActuatorServiceName,v1connect.AuditLogServiceName,@@ -282,6 +287,9 @@ func configureGrpcRouters(return err}+ if err := v1pb.RegisterAIServiceHandler(ctx, mux, grpcConn); err != nil {+ return err+ }if err := v1pb.RegisterAccessGrantServiceHandler(ctx, mux, grpcConn); err != nil {return err}diff --git a/docs/plans/2026-03-12-page-agent-design.md b/docs/plans/2026-03-12-page-agent-design.mdnew file mode 100644index 0000000000..f465921d62--- /dev/null+++ b/docs/plans/2026-03-12-page-agent-design.md@@ -0,0 +1,202 @@+# Bytebase Page Agent Design++This document describes the page agent as currently implemented. It is the durable design reference for the in-page agent and intentionally omits earlier phase-by-phase implementation planning.++## Goal++Provide an app-wide AI assistant inside the Bytebase console that can:++- understand the current page,+- navigate the product,+- use Bytebase APIs,+- interact with the DOM when page-local UI state matters, and+- load reusable workflow guidance for common tasks.++The page agent complements the existing SQL-editor AI experience; it does not replace it.++## Non-goals++- controlling non-Bytebase pages,+- relying on a browser extension or external page controller,+- changing production behavior independently of the normal UI and API contracts.++## Architecture++The implementation has four main parts.++### 1. App-wide UI surface++The floating agent window is mounted from `frontend/src/layouts/BodyLayout.vue`, so it is available across the dashboard instead of being tied to a single page.++Entry points:++- `frontend/src/layouts/BodyLayout.vue` mounts `AgentWindow` and registers the keyboard shortcut.+- `frontend/src/views/DashboardHeader.vue` exposes the header toggle button.+- `frontend/src/plugins/agent/index.ts` defines the `Ctrl/Cmd + Shift + A` shortcut.+- `frontend/src/plugins/agent/store/agent.ts` stores UI state and conversation state.++The Pinia store persists the conversation history plus the window layout state used by the floating window (position and size) in `localStorage`.++### 2. Frontend agent runtime++The agent loop runs in the frontend in `frontend/src/plugins/agent/logic/agentLoop.ts`.++High-level flow:++1. Build the system prompt.+2. Send conversation messages plus tool definitions to `AIService.Chat`.+3. Receive assistant text and/or tool calls.+4. Execute tool calls locally in the browser.+5. Append tool results to the conversation.+6. Repeat until the model returns a final text response.++This keeps page-aware operations in the frontend while the backend remains the provider-facing proxy.++### 3. Tool layer++The implemented tool set is six tools:++1. `search_api`+2. `call_api`+3. `navigate`+4. `get_page_state`+5. `dom_action`+6. `get_skill`++Tool definitions live in `frontend/src/plugins/agent/logic/tools/index.ts`, and tool execution is local to the page agent runtime.++### 4. Backend AI proxy++The backend contract is defined in `proto/v1/v1/ai_service.proto`, with backend handling in `backend/api/v1/ai_service.go`.++The backend is the source of truth for provider integration and normalizes tool-calling responses from supported AI providers. The frontend never talks directly to model providers.++## Tool model++### `search_api`++`search_api` is a structured OpenAPI index browser, not a free-text keyword search tool.++Current modes:++- list available services,+- browse endpoints for a service,+- inspect an endpoint by `operationId`,+- inspect a schema by name.++The implementation is backed by the generated OpenAPI index used by the frontend tool code. The expected workflow is:++1. identify a service from the API directory in the prompt,+2. call `search_api(service="...")`,+3. call `search_api(operationId="...")`,+4. then call `call_api(...)`.++### `call_api`++`call_api` executes a Bytebase API operation by `operationId` with an optional JSON body. It is the direct bridge from the agent to Bytebase APIs already available to the current signed-in user.++### `navigate`++`navigate` uses Vue Router to either:++- navigate to a concrete path, or+- list known route patterns with `list=true`.++The prompt instructs the model to list routes first when unsure instead of guessing paths.++### `get_page_state`++`get_page_state` is the read tool for current-page context.++Current modes:++- default `semantic` mode returns route information plus structured context when available,+- `mode: "dom"` returns the same base page state plus indexed DOM information.++There is no standalone `get_dom_tree` tool. DOM inspection is part of `get_page_state(mode="dom")`.++In semantic mode the implementation currently extracts a narrow context set:++- `user`+- `project`+- `database`+- `issue`++Those values are populated from route-aware store lookups in `frontend/src/plugins/agent/logic/context.ts`.++### `dom_action`++`dom_action` is the browser-side UI interaction tool. It supports the implemented action types used by the agent runtime, including reading indexed DOM elements and performing interactions such as click, input, select, and scroll.++The intended workflow is:++1. call `get_page_state(mode="dom")`,+2. inspect element indices,+3. call `dom_action(...)`.++### `get_skill`++`get_skill` loads reusable workflow guidance shipped with the page agent.++Current skills are:++- `query`+- `database-change`+- `grant-permission`++This keeps step-by-step workflow guidance out of the main prompt until it is needed.++## Prompt and context model++Prompt construction lives in `frontend/src/plugins/agent/logic/prompt.ts`.++The current system prompt includes:++- assistant identity and safety/usage rules,+- an API service directory,+- compact Bytebase domain concepts,+- dynamic page information including current path, page title, and role when available.++Important current behavior:++- dynamic route/page context is folded into the system prompt,+- it is not appended as a separate user message,+- the prompt tells the model to call `get_page_state` first,+- the prompt tells the model to use `get_skill` before common multi-step workflows,+- tool choice is context-sensitive rather than universally API-first.++The implemented guidance prefers DOM interaction on pages with unsaved or in-progress UI state, and prefers API access for persisted data, cross-resource lookup, or bulk operations.++## AI service contract++`proto/v1/v1/ai_service.proto` is the source of truth.++At a high level:++- `AIService.Chat` accepts conversation `messages` and `tool_definitions`.+- Message roles use the `AIChatMessageRole` enum rather than raw role strings.+- Assistant messages can carry `tool_calls`.+- Tool result messages carry `tool_call_id`.+- Tool calls include opaque provider metadata, which the frontend preserves when echoing tool results back through the loop.++This contract is what the frontend agent loop serializes to in `agentLoop.ts`.++## Durable implementation map++Primary implementation files:++- `frontend/src/layouts/BodyLayout.vue`+- `frontend/src/views/DashboardHeader.vue`+- `frontend/src/plugins/agent/index.ts`+- `frontend/src/plugins/agent/store/agent.ts`+- `frontend/src/plugins/agent/logic/agentLoop.ts`+- `frontend/src/plugins/agent/logic/prompt.ts`+- `frontend/src/plugins/agent/logic/context.ts`+- `frontend/src/plugins/agent/logic/tools/index.ts`+- `frontend/src/plugins/agent/logic/tools/searchApi.ts`+- `frontend/src/plugins/agent/logic/tools/pageState.ts`+- `proto/v1/v1/ai_service.proto`++## Notes on scope++This document intentionally excludes older phase plans, handoff notes, and exploratory design alternatives that were useful during implementation but are no longer the durable source of truth.diff --git a/frontend/package.json b/frontend/package.jsonindex 7e01e8146f..7b26632858 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -3,18 +3,23 @@"license": "SEE LICENSE IN LICENSE","scripts": {"copy:config-files": "sh ./scripts/copy_config_files.sh",- "copy:all": "pnpm run copy:config-files",- "dev": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run copy:all && vite --mode dev-local",- "release": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run copy:all && vite build --mode release --outDir=../backend/server/dist --emptyOutDir",- "release-docker": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run copy:all && vite build --mode release",- "release-aws": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run copy:all && vite build --mode release-aws",+ "prepare:artifacts": "pnpm run copy:config-files && pnpm run generate:openapi-index",+ "dev": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run prepare:artifacts && vite --mode dev-local",+ "release": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run prepare:artifacts && vite build --mode release --outDir=../backend/server/dist --emptyOutDir",+ "release-docker": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run prepare:artifacts && vite build --mode release",+ "release-aws": "export NODE_OPTIONS=--max_old_space_size=8000 && pnpm run prepare:artifacts && vite build --mode release-aws",+ "precheck": "pnpm run prepare:artifacts","check": "eslint --cache src && biome ci .","fix": "eslint --cache --fix src && biome check --write .","bundle-visualize": "export NODE_OPTIONS=--max_old_space_size=80000 && vite-bundle-visualizer -c vite.config.ts",+ "pretype-check": "pnpm run prepare:artifacts","type-check": "export NODE_OPTIONS=--max_old_space_size=8000 && vue-tsc --build --force",+ "pretest": "pnpm run prepare:artifacts","test": "vitest run --passWithNoTests",+ "precoverage": "pnpm run prepare:artifacts","coverage": "vitest --coverage",- "i18n": "TS_NODE_PROJECT='./tsconfig.i18n.json' ts-node i18n.ts && pnpm fix"+ "i18n": "TS_NODE_PROJECT='./tsconfig.i18n.json' ts-node i18n.ts && pnpm fix",+ "generate:openapi-index": "node scripts/generate_openapi_index.js"},"dependencies": {"@buf/googleapis_googleapis.bufbuild_es": "2.10.2-20251126203132-004180b77378.1",diff --git a/frontend/scripts/generate_openapi_index.js b/frontend/scripts/generate_openapi_index.jsnew file mode 100644index 0000000000..3a02a3dda3--- /dev/null+++ b/frontend/scripts/generate_openapi_index.js@@ -0,0 +1,262 @@+#!/usr/bin/env node++// Generates a compact TypeScript index from the OpenAPI spec.+// Run: pnpm --dir frontend run generate:openapi-index++const fs = require("fs");+const path = require("path");+const yaml = require("js-yaml");++const YAML_FILE = path.join(+ __dirname,+ "../../backend/api/mcp/gen/openapi.yaml"+);+const OUTPUT_FILE = path.join(+ __dirname,+ "../src/plugins/agent/logic/tools/gen/openapi-index.ts"+);++// --- Helpers ---++// Extract the last segment of a $ref string.+// "#/components/schemas/bytebase.v1.Foo" -> "bytebase.v1.Foo"+function refName(ref) {+ if (!ref) return "";+ const parts = ref.split("/");+ return parts[parts.length - 1];+}++// Extract property type and description from a schema property object.+function extractPropertyTypeAndDesc(prop) {+ if (!prop) return { type: "object", description: "" };++ // If the property itself is a $ref+ if (prop.$ref) {+ return { type: refName(prop.$ref), description: prop.description || "" };+ }++ let propType = "object";+ const rawType = Array.isArray(prop.type)+ ? prop.type.find((t) => t !== "null")+ : prop.type;+ if (rawType) propType = rawType;++ // For arrays, get the item type+ if (propType === "array" && prop.items) {+ if (prop.items.$ref) {+ propType = `array<${refName(prop.items.$ref)}>`;+ } else if (prop.items.type) {+ const itemType = Array.isArray(prop.items.type)+ ? prop.items.type.find((t) => t !== "null")+ : prop.items.type;+ if (itemType) propType = `array<${itemType}>`;+ }+ }++ return { type: propType, description: prop.description || "" };+}++// --- Main ---++const yamlContent = fs.readFileSync(YAML_FILE, "utf8");+const spec = yaml.load(yamlContent);++// 1. Extract endpoints+const endpoints = [];+const paths = spec.paths || {};++for (const [pathStr, pathItem] of Object.entries(paths)) {+ const op = pathItem && pathItem.post;+ if (!op) continue;++ // /bytebase.v1.SQLService/Query -> service=SQLService, method=Query+ const trimmed = pathStr.replace(/^\/bytebase\.v1\./, "");+ const slashIdx = trimmed.indexOf("/");+ if (slashIdx < 0) continue;++ const service = trimmed.slice(0, slashIdx);+ const method = trimmed.slice(slashIdx + 1);++ let requestSchemaRef = "";+ const reqBody = op.requestBody;+ if (+ reqBody &&+ reqBody.content &&+ reqBody.content["application/json"] &&+ reqBody.content["application/json"].schema &&+ reqBody.content["application/json"].schema.$ref+ ) {+ requestSchemaRef = reqBody.content["application/json"].schema.$ref;+ }++ let responseSchemaRef = "";+ const resp200 =+ op.responses && (op.responses["200"] || op.responses[200]);+ if (+ resp200 &&+ resp200.content &&+ resp200.content["application/json"] &&+ resp200.content["application/json"].schema &&+ resp200.content["application/json"].schema.$ref+ ) {+ responseSchemaRef = resp200.content["application/json"].schema.$ref;+ }++ endpoints.push({+ operationId: op.operationId || "",+ path: pathStr,+ service,+ method,+ summary: op.summary || "",+ description: op.description || "",+ requestSchemaRef,+ responseSchemaRef,+ });+}++// 2. Extract schemas (only bytebase.v1.* component schemas)+const schemas = {};+const componentSchemas =+ (spec.components && spec.components.schemas) || {};++for (const [schemaName, schemaDef] of Object.entries(componentSchemas)) {+ if (!schemaName.startsWith("bytebase.v1.")) continue;+ if (!schemaDef) continue;++ // Handle enum types+ if (schemaDef.enum && Array.isArray(schemaDef.enum)) {+ schemas[schemaName] = {+ type: "enum",+ values: schemaDef.enum.filter((v) => v != null && v !== ""),+ description: schemaDef.description || "",+ };+ continue;+ }++ // Merge allOf properties into a flat properties object+ let mergedProperties = schemaDef.properties;+ let mergedRequired = schemaDef.required || [];+ if (schemaDef.allOf && Array.isArray(schemaDef.allOf)) {+ mergedProperties = {};+ for (const part of schemaDef.allOf) {+ if (part.properties) {+ Object.assign(mergedProperties, part.properties);+ }+ if (part.required) {+ mergedRequired = mergedRequired.concat(part.required);+ }+ }+ }++ // Handle object types with properties+ if (!mergedProperties || Object.keys(mergedProperties).length === 0) continue;++ const requiredSet = new Set(mergedRequired);+ const properties = [];++ for (const [propName, propDef] of Object.entries(mergedProperties)) {+ const { type, description } = extractPropertyTypeAndDesc(propDef);+ const prop = { name: propName, type };+ if (description) prop.description = description;+ if (requiredSet.has(propName)) prop.required = true;+ properties.push(prop);+ }++ // Sort properties by name for consistent output+ properties.sort((a, b) => a.name.localeCompare(b.name));++ schemas[schemaName] = {+ type: "object",+ properties,+ description: schemaDef.description || "",+ };+}++// 3. Generate TypeScript output+const lines = [];+lines.push(+ "// Auto-generated from openapi.yaml. DO NOT EDIT manually.",+ "// Run 'pnpm --dir frontend run generate:openapi-index' to regenerate.",+ ""+);++// Interfaces+lines.push(+ "export interface EndpointInfo {",+ " operationId: string;",+ " path: string;",+ " service: string;",+ " method: string;",+ " summary: string;",+ " description: string;",+ " requestSchemaRef: string;",+ " responseSchemaRef: string;",+ "}",+ "",+ "export interface PropertyInfo {",+ " name: string;",+ " type: string;",+ " description?: string;",+ " required?: boolean;",+ "}",+ "",+ "export interface SchemaInfo {",+ " type: \"object\" | \"enum\";",+ " description: string;",+ " properties?: PropertyInfo[];",+ " values?: string[];",+ "}",+ ""+);++// Endpoints array+lines.push(+ `export const endpoints: EndpointInfo[] = ${JSON.stringify(endpoints, null, 2)};`,+ ""+);++// Schemas record+lines.push(+ `export const schemas: Record<string, SchemaInfo> = ${JSON.stringify(schemas, null, 2)};`,+ ""+);++fs.writeFileSync(OUTPUT_FILE, lines.join("\n"), "utf8");++const schemaCount = Object.keys(schemas).length;+const enumCount = Object.values(schemas).filter(+ (s) => s.type === "enum"+).length;+const objectCount = schemaCount - enumCount;++console.log(`Generated ${OUTPUT_FILE}`);+console.log(+ ` Endpoints: ${endpoints.length}, Schemas: ${schemaCount} (${objectCount} objects, ${enumCount} enums)`+);++// Validate service directory coverage in the prompt+const PROMPT_FILE = path.join(__dirname, "../src/plugins/agent/logic/prompt.ts");+if (fs.existsSync(PROMPT_FILE)) {+ const promptContent = fs.readFileSync(PROMPT_FILE, "utf8");+ const specServices = new Set(endpoints.map((ep) => ep.service));+ const missing = [];+ for (const svc of specServices) {+ if (!promptContent.includes(svc)) {+ missing.push(svc);+ }+ }+ if (missing.length > 0) {+ console.warn(+ ` ⚠ Services not reflected in prompt.ts serviceDirectory: ${missing.join(", ")}`+ );+ console.warn(+ " Review frontend/src/plugins/agent/AGENT.md and manually update the serviceDirectory block in prompt.ts"+ );+ } else {+ console.log(` ✓ Prompt service directory covers all ${specServices.size} services`);+ }+} else {+ console.warn(+ " ⚠ No prompt.ts found. Review frontend/src/plugins/agent/AGENT.md and restore or recreate the serviceDirectory block"+ );+}diff --git a/frontend/src/connect/index.ts b/frontend/src/connect/index.tsindex 1f2307dac2..b4df293f4b 100644--- a/frontend/src/connect/index.ts+++ b/frontend/src/connect/index.ts@@ -1,6 +1,7 @@import { createClient } from "@connectrpc/connect";import { createConnectTransport } from "@connectrpc/connect-web";import { createRegistry } from "@bufbuild/protobuf";+import { AIService } from "@/types/proto-es/v1/ai_service_pb";import { AccessGrantService } from "@/types/proto-es/v1/access_grant_service_pb";import { ActuatorService } from "@/types/proto-es/v1/actuator_service_pb";import {@@ -63,6 +64,8 @@ const transport = createConnectTransport({},});+export const aiServiceClientConnect = createClient(AIService, transport);+export const accessGrantServiceClientConnect = createClient(AccessGrantService,transportdiff --git a/frontend/src/layouts/BodyLayout.vue b/frontend/src/layouts/BodyLayout.vueindex cb7be68511..a479973c16 100644--- a/frontend/src/layouts/BodyLayout.vue+++ b/frontend/src/layouts/BodyLayout.vue@@ -74,6 +74,8 @@<Quickstart /></div>+ <AgentWindow />+<ReleaseRemindModalv-if="state.showReleaseModal && route.name !== WORKSPACE_ROOT_MODULE"@cancel="state.showReleaseModal = false"@@ -87,6 +89,7 @@ import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";import { useRoute, useRouter } from "vue-router";import RoutePermissionGuard from "@/components/Permission/RoutePermissionGuard.vue";import ReleaseRemindModal from "@/components/ReleaseRemindModal.vue";+import { AgentWindow, useAgentShortcut } from "@/plugins/agent";import { t } from "@/plugins/i18n";import environmentV1Routes from "@/router/dashboard/environmentV1";import instanceRoutes from "@/router/dashboard/instance";@@ -188,6 +191,8 @@ onUnmounted(() => {}});+useAgentShortcut();+provideBodyLayoutContext({mainContainerRef,});diff --git a/frontend/src/locales/en-US.json b/frontend/src/locales/en-US.jsonindex 30126f7c29..b989c82cd0 100644--- a/frontend/src/locales/en-US.json+++ b/frontend/src/locales/en-US.json@@ -1088,8 +1088,8 @@"batch-transition": {"not-allowed-tips": "Some of selected issues cannot be {operation}","open-cannot-reopen": "Open issues cannot be reopened",- "done-cannot-reopen": "Approved issues cannot be reopened",- "done-cannot-close": "Approved issues cannot be closed",+ "done-cannot-reopen": "Done issues cannot be reopened",+ "done-cannot-close": "Done issues cannot be closed","canceled-cannot-close": "Canceled issues cannot be closed","reopen": "Reopen","reopened": "reopened",@@ -1137,7 +1137,7 @@"error": {"statement-cannot-be-modified": "Statement cannot be modified after the issue is created"},- "unfinished-resolved-issue-tips": "This issue is marked as \"Approved\" but some of its tasks are not executed successfully.",+ "unfinished-resolved-issue-tips": "This issue is marked as \"Done\" but some of its tasks are not executed successfully.","data-export": {"options": "Options","limits": "Limits",@@ -2963,5 +2963,17 @@},"help-drawer": {"dont-show-again": "Don't show these tips again"+ },+ "agent": {+ "assistant-title": "Bytebase Assistant",+ "new-chat": "New chat",+ "minimize": "Minimize",+ "close": "Close",+ "input-placeholder": "Ask anything...",+ "send": "Send",+ "args": "Args:",+ "result": "Result:",+ "stop": "Stop",+ "interrupted": "Interrupted"}}diff --git a/frontend/src/locales/es-ES.json b/frontend/src/locales/es-ES.jsonindex e8ba9ed155..230c07c5b5 100644--- a/frontend/src/locales/es-ES.json+++ b/frontend/src/locales/es-ES.json@@ -2473,6 +2473,18 @@},"tooltip-for-resource": "También es configurable a nivel {scope}. Bytebase dará prioridad a la configuración a nivel de entorno."},+ "agent": {+ "assistant-title": "Bytebase Assistant",+ "new-chat": "New chat",+ "minimize": "Minimize",+ "close": "Close",+ "input-placeholder": "Ask anything...",+ "send": "Send",+ "args": "Args:",+ "result": "Result:",+ "stop": "Stop",+ "interrupted": "Interrupted"+ },"audit-log": {"export-finished": "Exportación finalizada","export-tooltip": "Debe seleccionar la hora de inicio y la hora de finalización dentro de los 30 días",diff --git a/frontend/src/locales/ja-JP.json b/frontend/src/locales/ja-JP.jsonindex 7e87ebfc1a..948502efbe 100644--- a/frontend/src/locales/ja-JP.json+++ b/frontend/src/locales/ja-JP.json@@ -2473,6 +2473,18 @@},"tooltip-for-resource": "{scope} レベルでも設定可能です。Bytebase は環境レベルの設定を優先します。"},+ "agent": {+ "assistant-title": "Bytebase Assistant",+ "new-chat": "New chat",+ "minimize": "Minimize",+ "close": "Close",+ "input-placeholder": "Ask anything...",+ "send": "Send",+ "args": "Args:",+ "result": "Result:",+ "stop": "Stop",+ "interrupted": "Interrupted"+ },"audit-log": {"export-finished": "エクスポートが完了しました","export-tooltip": "30日以内に開始時間と終了時間を選択する必要があります",diff --git a/frontend/src/locales/vi-VN.json b/frontend/src/locales/vi-VN.jsonindex 1584adcdf7..b74ae97b15 100644--- a/frontend/src/locales/vi-VN.json+++ b/frontend/src/locales/vi-VN.json@@ -2473,6 +2473,18 @@},"tooltip-for-resource": "Bạn cũng có thể cấu hình ở cấp độ {scope}. Bytebase sẽ ưu tiên cấu hình ở cấp độ môi trường."},+ "agent": {+ "assistant-title": "Bytebase Assistant",+ "new-chat": "New chat",+ "minimize": "Minimize",+ "close": "Close",+ "input-placeholder": "Ask anything...",+ "send": "Send",+ "args": "Args:",+ "result": "Result:",+ "stop": "Stop",+ "interrupted": "Interrupted"+ },"audit-log": {"export-finished": "Xuất hoàn tất","export-tooltip": "Phải chọn thời gian bắt đầu và thời gian kết thúc trong vòng 30 ngày",diff --git a/frontend/src/locales/zh-CN.json b/frontend/src/locales/zh-CN.jsonindex aeabdd8894..b6d551a93b 100644--- a/frontend/src/locales/zh-CN.json+++ b/frontend/src/locales/zh-CN.json@@ -1088,8 +1088,8 @@"batch-transition": {"not-allowed-tips": "部分选中的工单无法被{operation}","open-cannot-reopen": "打开中的工单无法重开",- "done-cannot-reopen": "已批准的工单无法重开",- "done-cannot-close": "已批准的工单无法关闭",+ "done-cannot-reopen": "已完成的工单无法重开",+ "done-cannot-close": "已完成的工单无法关闭","canceled-cannot-close": "已取消的工单无法关闭","reopen": "重开","reopened": "重开",@@ -1137,7 +1137,7 @@"error": {"statement-cannot-be-modified": "工单创建后,语句将无法修改"},- "unfinished-resolved-issue-tips": "该工单被标记为「已批准」,但其中部分任务并未成功执行。",+ "unfinished-resolved-issue-tips": "该工单被标记为「已完成」,但其中部分任务并未成功执行。","data-export": {"options": "配置项","limits": "限制",@@ -2963,5 +2963,17 @@},"help-drawer": {"dont-show-again": "不再显示这些提示"+ },+ "agent": {+ "assistant-title": "Bytebase 助手",+ "new-chat": "新对话",+ "minimize": "最小化",+ "close": "关闭",+ "input-placeholder": "输入任何问题...",+ "send": "发送",+ "args": "参数:",+ "result": "结果:",+ "stop": "停止",+ "interrupted": "已中断"}}diff --git a/frontend/src/plugins/agent/AGENT.md b/frontend/src/plugins/agent/AGENT.mdnew file mode 100644index 0000000000..ae16f0e3ca--- /dev/null+++ b/frontend/src/plugins/agent/AGENT.md@@ -0,0 +1,103 @@+# Page Agent — Maintenance Guide++This document explains how the page agent works and how to maintain it. It is intended for both humans and LLMs.++## Architecture++```+frontend/src/plugins/agent/+├── components/ # Vue UI (AgentWindow, message rendering)+├── dom/ # DOM interaction layer+│ ├── actions.ts # Execute DOM actions (click, input, select, scroll)+│ └── domTree.ts # Extract and index interactive DOM elements+├── logic/+│ ├── agentLoop.ts # Main agent loop: tool calls, retries, message history+│ ├── context.ts # Extract page context from Pinia stores+│ ├── prompt.ts # System prompt construction+│ ├── types.ts # Shared types+│ ├── skills/ # On-demand workflow guides+│ │ ├── index.ts # Skill registry and get_skill handler+│ │ ├── query.ts+│ │ ├── databaseChange.ts+│ │ └── grantPermission.ts+│ └── tools/ # Tool implementations+│ ├── index.ts # Tool definitions and executor dispatcher+│ ├── callApi.ts # Execute API endpoints+│ ├── searchApi.ts # API discovery with search + alias map+│ ├── navigate.ts # Router navigation + route listing+│ ├── pageState.ts # Page context (semantic or DOM)+│ ├── domAction.ts # DOM action wrapper+│ └── gen/ # Generated API discovery artifacts+│ └── openapi-index.ts # Generated API endpoint and schema index+└── store/ # Pinia store for agent state+```++## Tools Available to the Agent++| Tool | Purpose |+|------|---------|+| `search_api` | Discover API endpoints, browse services, get request/response schemas |+| `call_api` | Execute a Bytebase API endpoint |+| `navigate` | Navigate to a page or list available routes |+| `get_page_state` | Get current page context (route, stores, or DOM tree) |+| `dom_action` | Interact with DOM elements (click, input, select, read, scroll) |+| `get_skill` | Load step-by-step workflow guides for multi-step tasks |++## Tool Selection Philosophy++The agent chooses between DOM and API based on page context:+- **DOM-first** on form/preview/editor/creation pages — these have unsaved state that only exists in the UI+- **API-first** for data queries, bulk operations, or when the relevant page is not open+- **Either** for mutations on persisted resources — DOM if the user benefits from seeing it, API for speed++## Maintaining the Service Directory++**What:** A compact, feature-grouped summary of API services. It is embedded directly in `logic/prompt.ts` so the agent can choose the right service quickly before using `search_api` for exact endpoint details.++**Where:** `logic/prompt.ts` (`serviceDirectory` constant)++**Source of truth:**+- The `serviceDirectory` string in `logic/prompt.ts` is a **checked-in, manually maintained** prompt aid.+- `openapi-index.ts` and `search_api` remain the actual API discovery source of truth.++**When to update:**+- After adding or removing an API service+- After major endpoint additions that materially change what a service covers+- When `pnpm --dir frontend run generate:openapi-index` warns about uncovered services+- When the page agent consistently picks the wrong service because the descriptions are stale or missing key synonyms++**How to update:**+1. Run `pnpm --dir frontend run generate:openapi-index`.+2. If the script warns about missing services, edit the `serviceDirectory` block in `logic/prompt.ts` manually.+3. Keep each service description to one line.+4. Use user-facing feature names and useful synonyms, not raw method lists.+5. Keep the category structure compact and stable; do not try to enumerate every endpoint.+6. Preserve the surrounding prompt structure and the `serviceDirectory` constant name.+7. Review the resulting prompt text and commit the file.++## Maintaining Search Hints++When users repeatedly search for a feature using terms that do not map cleanly to the right service, update the search heuristics in `logic/tools/searchApi.ts` so the agent can discover the relevant APIs more reliably.++## Maintaining Skills++**What:** Step-by-step workflow guides for multi-step tasks (e.g., running a query, creating a schema change).++**Where:** `logic/skills/`++**How to add a new skill:**+1. Create `logic/skills/mySkill.ts` exporting `{ name, description, content }`+2. Register it in `logic/skills/index.ts`+3. Update the `get_skill` tool description in `logic/tools/index.ts` to list the new skill++## Maintaining Route List++**What:** The `navigate` tool supports `list=true` which returns all valid route patterns from Vue Router at runtime. No maintenance needed — it reads directly from the router instance.++## Regenerating the OpenAPI Index++```bash+pnpm --dir frontend run generate:openapi-index+```++This reads `backend/api/mcp/gen/openapi.yaml` and produces `gen/openapi-index.ts` with all endpoint definitions and schemas. Run after proto changes that affect the API.diff --git a/frontend/src/plugins/agent/components/AgentChat.vue b/frontend/src/plugins/agent/components/AgentChat.vuenew file mode 100644index 0000000000..daf908a065--- /dev/null+++ b/frontend/src/plugins/agent/components/AgentChat.vue@@ -0,0 +1,154 @@+<script setup lang="ts">+import remarkGfm from "remark-gfm";+import remarkParse from "remark-parse";+import { unified } from "unified";+import { computed, nextTick, ref, watch } from "vue";+import AstToMarkdown from "@/plugins/ai/components/ChatView/Markdown/AstToVNode.vue";+import { useAgentStore } from "../store/agent";+import ToolCallCard from "./ToolCallCard.vue";++const markdownProcessor = unified().use(remarkParse).use(remarkGfm);++const parseMarkdown = (content: string) => {+ return markdownProcessor.parse(content ?? "");+};++const agentStore = useAgentStore();+const chatContainer = ref<HTMLElement | null>(null);++const displayMessages = computed(() =>+ agentStore.messages.filter(+ (msg) => msg.role === "user" || msg.role === "assistant"+ )+);++function getToolResult(+ displayIndex: number,+ toolCallId: string+): string | undefined {+ // Map display index back to the full messages array+ const msg = displayMessages.value[displayIndex];+ if (!msg) return undefined;++ const fullIndex = agentStore.messages.indexOf(msg);+ if (fullIndex < 0) return undefined;++ // Look forward in the full messages array for the tool result+ for (let i = fullIndex + 1; i < agentStore.messages.length; i++) {+ const m = agentStore.messages[i];+ if (m.role === "tool" && m.toolCallId === toolCallId) {+ return m.content;+ }+ // Stop if we hit another assistant message (new turn)+ if (m.role === "assistant" && m.content && !m.toolCalls?.length) {+ break;+ }+ }+ return undefined;+}++watch(+ () => agentStore.messages.length,+ async () => {+ await nextTick();+ if (chatContainer.value) {+ const el = chatContainer.value;+ el.scrollTop = el.scrollHeight;+ }+ }+);+</script>++<template>+ <div ref="chatContainer" class="overflow-y-auto p-3 space-y-3">+ <template v-for="(msg, i) in displayMessages" :key="i">+ <!-- User message -->+ <div v-if="msg.role === 'user'" class="flex justify-end">+ <div class="max-w-[80%] rounded-lg px-3 py-2 bg-blue-50 text-sm">+ {{ msg.content }}+ </div>+ </div>+ <!-- Assistant message -->+ <div v-else-if="msg.role === 'assistant'" class="flex flex-col gap-y-2">+ <div+ v-if="msg.content"+ class="max-w-[80%] rounded-lg px-3 py-2 bg-gray-50 text-sm markdown-content"+ >+ <AstToMarkdown :ast="parseMarkdown(msg.content)" />+ </div>+ <ToolCallCard+ v-for="tc in msg.toolCalls"+ :key="tc.id"+ :tool-call="tc"+ :result="getToolResult(i, tc.id)"+ />+ </div>+ </template>+ <!-- Loading -->+ <div+ v-if="agentStore.loading"+ class="flex items-center gap-x-2 text-sm text-gray-400"+ >+ <span class="animate-pulse">●</span> {{ $t("common.loading") }}+ </div>+ <!-- Error -->+ <div+ v-if="agentStore.error"+ class="rounded-lg bg-red-50 px-3 py-2 text-sm text-red-600"+ >+ {{ agentStore.error }}+ </div>+ </div>+</template>++<style scoped lang="postcss">+.markdown-content :deep(p) {+ @apply my-1;+}+.markdown-content :deep(p:first-child) {+ @apply mt-0;+}+.markdown-content :deep(p:last-child) {+ @apply mb-0;+}+.markdown-content :deep(pre) {+ @apply my-1 p-2 bg-gray-100 rounded text-xs overflow-x-auto;+}+.markdown-content :deep(code) {+ @apply bg-gray-200 px-1 rounded text-xs;+}+.markdown-content :deep(pre code) {+ @apply bg-transparent px-0;+}+.markdown-content :deep(ul),+.markdown-content :deep(ol) {+ @apply my-1 pl-5;+}+.markdown-content :deep(ul) {+ @apply list-disc;+}+.markdown-content :deep(ol) {+ @apply list-decimal;+}+.markdown-content :deep(li) {+ @apply my-0.5;+}+.markdown-content :deep(h1),+.markdown-content :deep(h2),+.markdown-content :deep(h3) {+ @apply font-semibold my-1;+}+.markdown-content :deep(a) {+ @apply text-blue-600 underline;+}+.markdown-content :deep(blockquote) {+ @apply border-l-2 border-gray-300 pl-2 my-1 text-gray-600;+}+.markdown-content :deep(table) {+ @apply my-1 border-collapse text-xs;+}+.markdown-content :deep(th),+.markdown-content :deep(td) {+ @apply border border-gray-300 px-2 py-1;+}+</style>diff --git a/frontend/src/plugins/agent/components/AgentInput.vue b/frontend/src/plugins/agent/components/AgentInput.vuenew file mode 100644index 0000000000..629353752a--- /dev/null+++ b/frontend/src/plugins/agent/components/AgentInput.vue@@ -0,0 +1,137 @@+<script setup lang="ts">+import { ref } from "vue";+import { useI18n } from "vue-i18n";+import { useRoute, useRouter } from "vue-router";+import { runAgentLoop } from "../logic/agentLoop";+import { buildSystemPrompt } from "../logic/prompt";+import { createToolExecutor, getToolDefinitions } from "../logic/tools";+import type { Message } from "../logic/types";+import { useAgentStore } from "../store/agent";++const { t } = useI18n();+const router = useRouter();+const route = useRoute();+const agentStore = useAgentStore();+const input = ref("");++async function send() {+ const text = input.value.trim();+ if (!text || agentStore.loading) return;+ agentStore.clearError();+ input.value = "";++ agentStore.addMessage({ role: "user", content: text });+ agentStore.loading = true;++ const controller = new AbortController();+ agentStore.abortController = controller;++ const systemPrompt = buildSystemPrompt({+ path: route.fullPath,+ title: document.title,+ });++ const allMessages: Message[] = [+ { role: "system", content: systemPrompt },+ ...agentStore.messages,+ ];++ const tools = getToolDefinitions();+ const executor = createToolExecutor(router);++ try {+ await runAgentLoop(+ allMessages,+ tools,+ executor,+ {+ onToolCall: (tc) => {+ // The agent loop calls onToolCall for each tool call in an assistant+ // turn. All tool calls from the same turn arrive before any+ // onToolResult. We batch them into one assistant message.+ const lastMsg = agentStore.messages[agentStore.messages.length - 1];+ if (+ lastMsg?.role === "assistant" &&+ lastMsg.toolCalls &&+ !agentStore.messages.some(+ (m) =>+ m.role === "tool" &&+ lastMsg.toolCalls!.some((t) => t.id === m.toolCallId)+ )+ ) {+ // Same turn — append to existing assistant message+ lastMsg.toolCalls.push(tc);+ } else {+ agentStore.addMessage({+ role: "assistant",+ toolCalls: [tc],+ });+ }+ },+ onToolResult: (toolCallId, result) => {+ agentStore.addMessage({+ role: "tool",+ toolCallId,+ content: result,+ });+ },+ onText: (text) => {+ agentStore.addMessage({+ role: "assistant",+ content: text,+ });+ },+ },+ controller.signal+ );+ } catch (err) {+ const error = err instanceof Error ? err : new Error(String(err));+ // AbortError from DOMException or ConnectError with "[canceled]"+ const isAbort =+ error.name === "AbortError" || error.message.includes("[canceled]");+ if (isAbort) {+ agentStore.addMessage({+ role: "assistant",+ content: `_${t("agent.interrupted")}_`,+ });+ } else {+ agentStore.addMessage({+ role: "assistant",+ content: `Error: ${error.message}`,+ });+ }+ } finally {+ agentStore.loading = false;+ agentStore.abortController = null;+ }+}+</script>++<template>+ <div class="border-t p-3">+ <div class="flex items-end gap-x-2">+ <textarea+ v-model="input"+ rows="1"+ :placeholder="$t('agent.input-placeholder')"+ class="flex-1 resize-none rounded-md border px-3 py-2 text-sm focus:outline-none focus:ring-1 focus:ring-blue-500"+ @keydown.enter.exact.prevent="send"+ />+ <button+ v-if="agentStore.loading"+ class="rounded-md bg-red-500 px-3 py-2 text-sm text-white hover:bg-red-600"+ @click="agentStore.cancel()"+ >+ {{ $t("agent.stop") }}+ </button>+ <button+ v-else+ class="rounded-md bg-blue-500 px-3 py-2 text-sm text-white hover:bg-blue-600 disabled:opacity-50"+ :disabled="!input.trim()"+ @click="send"+ >+ {{ $t("agent.send") }}+ </button>+ </div>+ </div>+</template>diff --git a/frontend/src/plugins/agent/components/AgentWindow.vue b/frontend/src/plugins/agent/components/AgentWindow.vuenew file mode 100644index 0000000000..e1d43f4b6a--- /dev/null+++ b/frontend/src/plugins/agent/components/AgentWindow.vue@@ -0,0 +1,176 @@+<script setup lang="ts">+import { computed, onMounted, ref } from "vue";+import { useAgentStore } from "../store/agent";+import AgentChat from "./AgentChat.vue";+import AgentInput from "./AgentInput.vue";++const agentStore = useAgentStore();++const MIN_WIDTH = 300;+const MIN_HEIGHT = 400;+const MAX_WIDTH = 800;+const MAX_HEIGHT = 800;++const windowStyle = computed(() => ({+ left: `${agentStore.position.x}px`,+ top: `${agentStore.position.y}px`,+ width: `${agentStore.size.width}px`,+ height: `${agentStore.size.height}px`,+}));++// Drag logic+const isDragging = ref(false);+const dragOffset = ref({ x: 0, y: 0 });++function startDrag(e: MouseEvent) {+ isDragging.value = true;+ dragOffset.value = {+ x: e.clientX - agentStore.position.x,+ y: e.clientY - agentStore.position.y,+ };+ document.addEventListener("mousemove", onDrag);+ document.addEventListener("mouseup", stopDrag);+}++function onDrag(e: MouseEvent) {+ if (!isDragging.value) return;+ agentStore.position.x = e.clientX - dragOffset.value.x;+ agentStore.position.y = e.clientY - dragOffset.value.y;+}++function stopDrag() {+ isDragging.value = false;+ document.removeEventListener("mousemove", onDrag);+ document.removeEventListener("mouseup", stopDrag);+ agentStore.saveWindowState();+}++// Resize logic+const isResizing = ref(false);+const resizeStart = ref({ x: 0, y: 0, w: 0, h: 0 });++function startResize(e: MouseEvent) {+ e.preventDefault();+ isResizing.value = true;+ resizeStart.value = {+ x: e.clientX,+ y: e.clientY,+ w: agentStore.size.width,+ h: agentStore.size.height,+ };+ document.addEventListener("mousemove", onResize);+ document.addEventListener("mouseup", stopResize);+}++function onResize(e: MouseEvent) {+ if (!isResizing.value) return;+ const dx = e.clientX - resizeStart.value.x;+ const dy = e.clientY - resizeStart.value.y;+ agentStore.size.width = Math.min(+ MAX_WIDTH,+ Math.max(MIN_WIDTH, resizeStart.value.w + dx)+ );+ agentStore.size.height = Math.min(+ MAX_HEIGHT,+ Math.max(MIN_HEIGHT, resizeStart.value.h + dy)+ );+}++function stopResize() {+ isResizing.value = false;+ document.removeEventListener("mousemove", onResize);+ document.removeEventListener("mouseup", stopResize);+ agentStore.saveWindowState();+}++onMounted(() => {+ agentStore.loadWindowState();+});+</script>++<template>+ <Teleport to="body">+ <!-- Minimized button -->+ <div+ v-if="agentStore.visible && agentStore.minimized"+ data-agent-window+ class="fixed z-[1999] bottom-4 right-4 flex h-10 w-10 cursor-pointer items-center justify-center rounded-full bg-blue-500 text-white shadow-lg hover:bg-blue-600"+ @click="agentStore.restore()"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ class="h-5 w-5"+ viewBox="0 0 20 20"+ fill="currentColor"+ >+ <path+ fill-rule="evenodd"+ d="M18 10c0 3.866-3.582 7-8 7a8.841 8.841 0 01-4.083-.98L2 17l1.338-3.123C2.493 12.767 2 11.434 2 10c0-3.866 3.582-7 8-7s8 3.134 8 7zM7 9H5v2h2V9zm8 0h-2v2h2V9zm-4 0H9v2h2V9z"+ clip-rule="evenodd"+ />+ </svg>+ </div>++ <!-- Full window -->+ <div+ v-if="agentStore.visible && !agentStore.minimized"+ data-agent-window+ class="fixed z-[1999] flex flex-col rounded-lg border border-gray-200 shadow-xl bg-white overflow-hidden"+ :style="windowStyle"+ >+ <!-- Title bar -->+ <div+ class="flex items-center justify-between px-3 py-2 border-b bg-gray-50 cursor-move select-none"+ @mousedown="startDrag"+ >+ <span class="text-sm font-medium">{{ $t("agent.assistant-title") }}</span>+ <div class="flex items-center gap-x-1">+ <button+ class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"+ :title="$t('agent.new-chat')"+ @click.stop="agentStore.clearMessages()"+ >+ <svg+ xmlns="http://www.w3.org/2000/svg"+ class="h-3.5 w-3.5"+ viewBox="0 0 20 20"+ fill="currentColor"+ >+ <path+ fill-rule="evenodd"+ d="M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z"+ clip-rule="evenodd"+ />+ </svg>+ </button>+ <button+ class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"+ :title="$t('agent.minimize')"+ @click.stop="agentStore.minimize()"+ >+ −+ </button>+ <button+ class="flex h-5 w-5 items-center justify-center rounded text-gray-400 hover:bg-gray-200 hover:text-gray-600"+ :title="$t('agent.close')"+ @click.stop="agentStore.toggle()"+ >+ ✕+ </button>+ </div>+ </div>++ <!-- Chat -->+ <AgentChat class="flex-1 min-h-0" />++ <!-- Input -->+ <AgentInput />++ <!-- Resize handle -->+ <div+ class="absolute bottom-0 right-0 w-3 h-3 cursor-se-resize"+ @mousedown="startResize"+ />+ </div>+ </Teleport>+</template>diff --git a/frontend/src/plugins/agent/components/ToolCallCard.vue b/frontend/src/plugins/agent/components/ToolCallCard.vuenew file mode 100644index 0000000000..7948782f98--- /dev/null+++ b/frontend/src/plugins/agent/components/ToolCallCard.vue@@ -0,0 +1,46 @@+<script setup lang="ts">+import { ref } from "vue";+import type { ToolCall } from "../logic/types";++defineProps<{+ toolCall: ToolCall;+ result?: string;+}>();++const expanded = ref(false);++function formatJson(value: string): string {+ try {+ return JSON.stringify(JSON.parse(value), null, 2);+ } catch {+ return value;+ }+}+</script>++<template>+ <div class="rounded border bg-gray-50 text-xs">+ <div+ class="flex items-center gap-x-2 px-2 py-1.5 cursor-pointer"+ @click="expanded = !expanded"+ >+ <span class="font-mono text-gray-600">{{ toolCall.name }}</span>+ <span v-if="result" class="text-green-500">✓</span>+ <span v-else class="animate-pulse text-gray-400">●</span>+ <span class="ml-auto text-gray-400">{{ expanded ? "\u25BE" : "\u25B8" }}</span>+ </div>+ <div v-if="expanded" class="border-t px-2 py-1.5 space-y-1">+ <div class="text-gray-500">{{ $t("agent.args") }}</div>+ <pre class="text-gray-700 whitespace-pre-wrap break-all">{{+ formatJson(toolCall.arguments)+ }}</pre>+ <template v-if="result">+ <div class="text-gray-500">{{ $t("agent.result") }}</div>+ <pre+ class="text-gray-700 whitespace-pre-wrap break-all max-h-32 overflow-y-auto"+ >{{ formatJson(result) }}</pre+ >+ </template>+ </div>+ </div>+</template>diff --git a/frontend/src/plugins/agent/dom/actions.ts b/frontend/src/plugins/agent/dom/actions.tsnew file mode 100644index 0000000000..a5a09f766f--- /dev/null+++ b/frontend/src/plugins/agent/dom/actions.ts@@ -0,0 +1,236 @@+export { extractDomTree, getElementByIndex } from "./domTree";++export type DomActionType = "click" | "input" | "select" | "scroll" | "read";++export interface DomActionParams {+ type: DomActionType;+ index: number;+ value?: string;+}++export interface DomActionResult {+ success: boolean;+ message: string;+}++function getCenter(el: Element): { x: number; y: number } {+ const rect = el.getBoundingClientRect();+ return {+ x: rect.left + rect.width / 2,+ y: rect.top + rect.height / 2,+ };+}++function dispatchClick(el: Element): void {+ const { x, y } = getCenter(el);+ const shared: MouseEventInit = {+ bubbles: true,+ cancelable: true,+ clientX: x,+ clientY: y,+ view: window,+ };+ el.dispatchEvent(new MouseEvent("mousedown", shared));+ el.dispatchEvent(new MouseEvent("mouseup", shared));+ el.dispatchEvent(new MouseEvent("click", shared));+}++function setNativeValue(+ el: HTMLInputElement | HTMLTextAreaElement,+ value: string+): void {+ const proto =+ el instanceof HTMLTextAreaElement+ ? HTMLTextAreaElement.prototype+ : HTMLInputElement.prototype;+ const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;+ if (setter) {+ setter.call(el, value);+ } else {+ el.value = value;+ }+ el.dispatchEvent(new Event("input", { bubbles: true }));+ el.dispatchEvent(new Event("change", { bubbles: true }));+}++function normalizeMultilineValue(value: string): string {+ if (!value.includes("\\")) {+ return value;+ }++ return value+ .replace(/\\r\\n/g, "\n")+ .replace(/\\n/g, "\n")+ .replace(/\\r/g, "\r")+ .replace(/\\t/g, "\t");+}++function findInnerInput(+ el: Element+): HTMLInputElement | HTMLTextAreaElement | null {+ return el.querySelector<HTMLInputElement | HTMLTextAreaElement>(+ "input, textarea"+ );+}++async function findMonacoEditor(+ el: Element+): Promise<{ getValue(): string; setValue(v: string): void } | null> {+ try {+ const { isMonacoLoaded, getMonacoEditor } = await import(+ "@/components/MonacoEditor/lazy-editor"+ );+ if (!isMonacoLoaded()) return null;+ const monaco = await getMonacoEditor();+ const monacoRoot = el.closest(".monaco-editor");+ for (const editor of monaco.editor.getEditors()) {+ const domNode = editor.getDomNode();+ if (!domNode) {+ continue;+ }+ if (+ el === domNode ||+ el.contains(domNode) ||+ domNode.contains(el) ||+ monacoRoot === domNode+ ) {+ return editor;+ }+ }+ } catch {+ // Monaco not available+ }+ return null;+}++async function handleClick(el: Element): Promise<DomActionResult> {+ dispatchClick(el);+ return { success: true, message: `Clicked ${el.tagName.toLowerCase()}` };+}++async function handleInput(+ el: Element,+ value: string+): Promise<DomActionResult> {+ // Monaco editor+ const monacoEditor = await findMonacoEditor(el);+ if (monacoEditor) {+ const normalizedValue = normalizeMultilineValue(value);+ monacoEditor.setValue(normalizedValue);+ return {+ success: true,+ message: `Set editor content (${normalizedValue.length} chars)`,+ };+ }++ let target: HTMLInputElement | HTMLTextAreaElement | null = null;++ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {+ target = el;+ } else {+ // Naive UI wraps inputs — find the inner element+ target = findInnerInput(el);+ }++ if (!target) {+ return {+ success: false,+ message: `No input element found within [${el.tagName.toLowerCase()}]`,+ };+ }++ target.focus();+ const normalizedValue =+ target instanceof HTMLTextAreaElement+ ? normalizeMultilineValue(value)+ : value;+ setNativeValue(target, normalizedValue);+ return { success: true, message: `Set value to "${normalizedValue}"` };+}++async function handleSelect(+ el: Element,+ value: string+): Promise<DomActionResult> {+ // Native <select>+ if (el instanceof HTMLSelectElement) {+ el.value = value;+ el.dispatchEvent(new Event("change", { bubbles: true }));+ return { success: true, message: `Selected "${value}"` };+ }++ // Naive UI select — click to open, then pick option+ dispatchClick(el);++ return new Promise<DomActionResult>((resolve) => {+ setTimeout(() => {+ const options = document.querySelectorAll(".n-base-select-option");+ for (const opt of Array.from(options)) {+ const text = opt.textContent?.trim();+ if (text === value) {+ dispatchClick(opt);+ resolve({ success: true, message: `Selected "${value}"` });+ return;+ }+ }+ resolve({+ success: false,+ message: `Option "${value}" not found. Available options: ${Array.from(+ options+ )+ .map((o) => o.textContent?.trim())+ .filter(Boolean)+ .join(", ")}`,+ });+ }, 200);+ });+}++async function handleRead(el: Element): Promise<DomActionResult> {+ // Monaco editor — read full content via API+ const monacoEditor = await findMonacoEditor(el);+ if (monacoEditor) {+ return { success: true, message: monacoEditor.getValue() };+ }++ // Standard inputs+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {+ return { success: true, message: el.value };+ }++ const inner = findInnerInput(el);+ if (inner) {+ return { success: true, message: inner.value };+ }++ // Fallback: text content+ return { success: true, message: el.textContent?.trim() ?? "" };+}++async function handleScroll(el: Element): Promise<DomActionResult> {+ el.scrollIntoView({ behavior: "smooth", block: "center" });+ return { success: true, message: "Scrolled element into view" };+}++export async function executeDomAction(+ params: DomActionParams,+ element: Element+): Promise<DomActionResult> {+ switch (params.type) {+ case "click":+ return handleClick(element);+ case "input":+ return handleInput(element, params.value ?? "");+ case "select":+ return handleSelect(element, params.value ?? "");+ case "read":+ return handleRead(element);+ case "scroll":+ return handleScroll(element);+ default:+ return {+ success: false,+ message: `Unknown action type: ${params.type}`,+ };+ }+}diff --git a/frontend/src/plugins/agent/dom/domTree.ts b/frontend/src/plugins/agent/dom/domTree.tsnew file mode 100644index 0000000000..4a137a11a1--- /dev/null+++ b/frontend/src/plugins/agent/dom/domTree.ts@@ -0,0 +1,247 @@+export interface IndexedElement {+ index: number;+ tag: string;+ role?: string;+ label: string;+ value?: string;+ element: Element;+}++const INTERACTIVE_TAGS = new Set([+ "A",+ "BUTTON",+ "INPUT",+ "SELECT",+ "TEXTAREA",+ "DETAILS",+ "SUMMARY",+]);++const INTERACTIVE_ROLES = new Set([+ "button",+ "link",+ "textbox",+ "combobox",+ "listbox",+ "option",+ "menuitem",+ "tab",+ "checkbox",+ "radio",+ "switch",+ "slider",+]);++const NAIVE_INTERACTIVE_CLASSES = ["n-button", "n-switch", "n-checkbox"];++const SKIP_TAGS = new Set(["SCRIPT", "STYLE", "NOSCRIPT", "SVG", "PATH"]);++const LANDMARK_TAGS = new Set([+ "NAV",+ "MAIN",+ "HEADER",+ "FOOTER",+ "ASIDE",+ "SECTION",+ "ARTICLE",+ "FORM",+ "TABLE",+ "THEAD",+ "TBODY",+ "TR",+ "UL",+ "OL",+ "LI",+ "DIALOG",+]);++function isLandmark(el: Element): boolean {+ if (LANDMARK_TAGS.has(el.tagName)) return true;+ if (el.getAttribute("role")) return true;+ if (el.getAttribute("aria-label")) return true;+ return false;+}++let elementRegistry: IndexedElement[] = [];++export function getElementByIndex(index: number): IndexedElement | undefined {+ return elementRegistry[index];+}++function isVisible(el: Element): boolean {+ const style = window.getComputedStyle(el);+ return (+ style.display !== "none" &&+ style.visibility !== "hidden" &&+ style.opacity !== "0"+ );+}++function isMonacoEditor(el: Element): boolean {+ return el.classList.contains("monaco-editor");+}++function getMonacoContent(el: Element): string | undefined {+ // Read content directly from Monaco's rendered DOM lines+ const viewLines = el.querySelector(".view-lines");+ if (!viewLines) return undefined;+ const lines: string[] = [];+ for (const line of Array.from(viewLines.querySelectorAll(".view-line"))) {+ lines.push(line.textContent ?? "");+ }+ const content = lines.join("\n").trim();+ return content || undefined;+}++function isInteractive(el: Element): boolean {+ if (INTERACTIVE_TAGS.has(el.tagName)) return true;++ const role = el.getAttribute("role");+ if (role && INTERACTIVE_ROLES.has(role)) return true;++ for (const cls of NAIVE_INTERACTIVE_CLASSES) {+ if (el.classList.contains(cls)) return true;+ }++ return false;+}++function extractLabel(el: Element): string {+ // aria-label+ const ariaLabel = el.getAttribute("aria-label");+ if (ariaLabel) return ariaLabel.trim();++ // aria-labelledby+ const labelledBy = el.getAttribute("aria-labelledby");+ if (labelledBy) {+ const parts = labelledBy+ .split(/\s+/)+ .map((id) => document.getElementById(id)?.textContent?.trim())+ .filter(Boolean);+ if (parts.length > 0) return parts.join(" ");+ }++ // placeholder+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {+ if (el.placeholder) return el.placeholder.trim();+ }++ // Naive UI form-item label+ const formItem = el.closest(".n-form-item");+ if (formItem) {+ const labelEl = formItem.querySelector(".n-form-item-label__text");+ if (labelEl?.textContent) return labelEl.textContent.trim();+ }++ // title+ const title = el.getAttribute("title");+ if (title) return title.trim();++ // text content (truncated)+ const text = (el.textContent ?? "").trim().replace(/\s+/g, " ");+ if (text.length > 80) return text.slice(0, 80) + "...";+ return text;+}++function extractValue(el: Element): string | undefined {+ if (el instanceof HTMLInputElement) {+ if (el.type === "checkbox" || el.type === "radio") {+ return el.checked ? "checked" : "unchecked";+ }+ return el.value || undefined;+ }+ if (el instanceof HTMLTextAreaElement) {+ return el.value || undefined;+ }+ if (el instanceof HTMLSelectElement) {+ return el.options[el.selectedIndex]?.text || el.value || undefined;+ }++ // Naive UI select+ if (el.classList.contains("n-base-selection")) {+ const label = el.querySelector(".n-base-selection-label");+ const text = label?.textContent?.trim();+ if (text) return text;+ }++ // Naive UI checkbox/switch+ if (+ el.classList.contains("n-checkbox") ||+ el.classList.contains("n-switch")+ ) {+ const isChecked =+ el.classList.contains("n-checkbox--checked") ||+ el.classList.contains("n-switch--active");+ return isChecked ? "checked" : "unchecked";+ }++ return undefined;+}++function walkDom(node: Element, depth: number, lines: string[]): void {+ if (SKIP_TAGS.has(node.tagName)) return;+ if (node.hasAttribute("data-agent-window")) return;+ if (!isVisible(node)) return;++ // Monaco editor — register as a single interactive element+ if (isMonacoEditor(node)) {+ const index = elementRegistry.length;+ const content = getMonacoContent(node) ?? "";+ const preview =+ content.length > 200 ? content.slice(0, 200) + "..." : content;+ const label = content ? `SQL: ${preview}` : "empty editor";++ elementRegistry.push({+ index,+ tag: "editor",+ label,+ value: content,+ element: node,+ });++ const indent = " ".repeat(depth);+ lines.push(`${indent}[${index}]<editor>${label}</editor>`);+ return;+ }++ if (isInteractive(node)) {+ const index = elementRegistry.length;+ const tag = node.tagName.toLowerCase();+ const label = extractLabel(node);+ const value = extractValue(node);+ const role = node.getAttribute("role") ?? undefined;++ elementRegistry.push({ index, tag, role, label, value, element: node });++ const indent = " ".repeat(depth);+ const valueAttr = value ? ` value="${value}"` : "";+ lines.push(`${indent}[${index}]<${tag}${valueAttr}>${label}</${tag}>`);++ // Don't recurse into interactive elements+ return;+ }++ // Only increment depth at landmark/semantic containers+ const childDepth = isLandmark(node) ? depth + 1 : depth;+ for (const child of Array.from(node.children)) {+ walkDom(child, childDepth, lines);+ }+}++export function extractDomTree(root?: Element): {+ tree: string;+ count: number;+} {+ elementRegistry = [];+ const lines: string[] = [];+ const rootEl = root ?? document.body;++ for (const child of Array.from(rootEl.children)) {+ walkDom(child, 0, lines);+ }++ return {+ tree: lines.join("\n"),+ count: elementRegistry.length,+ };+}diff --git a/frontend/src/plugins/agent/dom/index.ts b/frontend/src/plugins/agent/dom/index.tsnew file mode 100644index 0000000000..ee5e17377d--- /dev/null+++ b/frontend/src/plugins/agent/dom/index.ts@@ -0,0 +1,67 @@+import type { Router } from "vue-router";+import type { DomActionParams, DomActionResult } from "./actions";++// Single dynamic import path. actions.ts re-exports extractDomTree and+// getElementByIndex from domTree.ts, ensuring one module instance so the+// element registry populated by extractDomTree is readable by getElementByIndex.+let module: typeof import("./actions") | undefined;++async function ensureLoaded(): Promise<typeof import("./actions")> {+ if (module) return module;+ module = await import("./actions");+ return module;+}++export async function lazyExtractDomTree(): Promise<{+ tree: string;+ count: number;+}> {+ const m = await ensureLoaded();+ return m.extractDomTree();+}++function isSameOriginLink(el: Element): string | undefined {+ if (!(el instanceof HTMLAnchorElement)) return undefined;+ const href = el.getAttribute("href");+ if (!href) return undefined;+ // Relative paths or same-origin absolute URLs+ if (href.startsWith("/")) return href;+ try {+ const url = new URL(href);+ if (url.origin === window.location.origin)+ return url.pathname + url.search + url.hash;+ } catch {+ // Not a valid URL+ }+ return undefined;+}++export async function lazyExecuteDomAction(+ params: DomActionParams,+ router?: Router+): Promise<DomActionResult> {+ const m = await ensureLoaded();+ const entry = m.getElementByIndex(params.index);+ if (!entry) {+ return {+ success: false,+ message: `Element [${params.index}] not found. Run get_page_state(mode="dom") to refresh the DOM tree.`,+ };+ }++ // For <a> clicks, use Vue Router to avoid full page reload+ if (params.type === "click" && router) {+ const path = isSameOriginLink(entry.element);+ if (path) {+ await router.push(path);+ return {+ success: true,+ message: `Navigated to ${path}`,+ };+ }+ }++ return m.executeDomAction(params, entry.element);+}++export type { DomActionParams, DomActionResult };diff --git a/frontend/src/plugins/agent/index.ts b/frontend/src/plugins/agent/index.tsnew file mode 100644index 0000000000..d55d89e50e--- /dev/null+++ b/frontend/src/plugins/agent/index.ts@@ -0,0 +1,24 @@+import { onMounted, onUnmounted } from "vue";+import { useAgentStore } from "./store/agent";++export { default as AgentWindow } from "./components/AgentWindow.vue";+export { useAgentStore } from "./store/agent";++export function useAgentShortcut() {+ const store = useAgentStore();++ function handleKeydown(e: KeyboardEvent) {+ if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key === "A") {+ e.preventDefault();+ store.toggle();+ }+ }++ onMounted(() => {+ window.addEventListener("keydown", handleKeydown);+ });++ onUnmounted(() => {+ window.removeEventListener("keydown", handleKeydown);+ });+}diff --git a/frontend/src/plugins/agent/logic/agentLoop.ts b/frontend/src/plugins/agent/logic/agentLoop.tsnew file mode 100644index 0000000000..c33a0a2077--- /dev/null+++ b/frontend/src/plugins/agent/logic/agentLoop.ts@@ -0,0 +1,171 @@+import { create } from "@bufbuild/protobuf";+import { createContextValues } from "@connectrpc/connect";+import { aiServiceClientConnect } from "@/connect";+import { silentContextKey } from "@/connect/context-key";+import type {+ AIChatMessage,+ AIChatToolDefinition,+} from "@/types/proto-es/v1/ai_service_pb";+import {+ AIChatMessageRole,+ AIChatMessageSchema,+ AIChatToolDefinitionSchema,+} from "@/types/proto-es/v1/ai_service_pb";+import type { Message, ToolCall, ToolDefinition, ToolExecutor } from "./types";++const MAX_ITERATIONS = 50;+const MAX_RETRIES = 2;+const RETRY_DELAY_MS = 1000;++async function callWithRetry<T>(+ fn: () => Promise<T>,+ signal?: AbortSignal+): Promise<T> {+ let lastError: Error | undefined;+ for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {+ if (signal?.aborted) {+ throw new DOMException("Agent loop aborted", "AbortError");+ }+ try {+ return await fn();+ } catch (err) {+ lastError = err instanceof Error ? err : new Error(String(err));+ if (lastError.name === "AbortError") throw lastError;+ const msg = lastError.message.toLowerCase();+ if (+ msg.includes("400") ||+ msg.includes("401") ||+ msg.includes("403") ||+ msg.includes("404")+ ) {+ throw lastError;+ }+ if (attempt < MAX_RETRIES) {+ await new Promise((r) => setTimeout(r, RETRY_DELAY_MS * (attempt + 1)));+ }+ }+ }+ throw lastError!;+}++const ROLE_MAP: Record<Message["role"], AIChatMessageRole> = {+ system: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_SYSTEM,+ user: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_USER,+ assistant: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_ASSISTANT,+ tool: AIChatMessageRole.AI_CHAT_MESSAGE_ROLE_TOOL,+};++function roleToProto(role: Message["role"]): AIChatMessageRole {+ return ROLE_MAP[role];+}++function messageToProto(msg: Message): AIChatMessage {+ const proto = create(AIChatMessageSchema);+ proto.role = roleToProto(msg.role);+ proto.content = msg.content;+ proto.toolCallId = msg.toolCallId;+ if (msg.toolCalls) {+ proto.toolCalls = msg.toolCalls.map((tc) => ({+ $typeName: "bytebase.v1.AIChatToolCall" as const,+ id: tc.id,+ name: tc.name,+ arguments: tc.arguments,+ metadata: tc.metadata,+ }));+ }+ return proto;+}++function toolDefToProto(tool: ToolDefinition): AIChatToolDefinition {+ const proto = create(AIChatToolDefinitionSchema);+ proto.name = tool.name;+ proto.description = tool.description;+ proto.parametersSchema = JSON.stringify(tool.parametersSchema);+ return proto;+}++export interface AgentCallbacks {+ onToolCall?: (toolCall: ToolCall) => void;+ onToolResult?: (toolCallId: string, result: string) => void;+ onText?: (text: string) => void;+ onError?: (error: Error) => void;+}++export async function runAgentLoop(+ messages: Message[],+ tools: ToolDefinition[],+ executeTool: ToolExecutor,+ callbacks?: AgentCallbacks,+ signal?: AbortSignal+): Promise<string> {+ const conversation: Message[] = [...messages];+ const protoTools = tools.map(toolDefToProto);++ for (let i = 0; i < MAX_ITERATIONS; i++) {+ if (signal?.aborted) {+ throw new DOMException("Agent loop aborted", "AbortError");+ }++ const protoMessages = conversation.map(messageToProto);++ const response = await callWithRetry(+ () =>+ aiServiceClientConnect.chat(+ { messages: protoMessages, toolDefinitions: protoTools },+ {+ signal,+ contextValues: createContextValues().set(silentContextKey, true),+ }+ ),+ signal+ );++ if (response.toolCalls.length > 0) {+ const toolCalls: ToolCall[] = response.toolCalls.map((tc) => ({+ id: tc.id,+ name: tc.name,+ arguments: tc.arguments,+ metadata: tc.metadata,+ }));++ // Append assistant message with tool calls+ conversation.push({+ role: "assistant",+ content: response.content,+ toolCalls,+ });++ // Execute each tool call and append results+ for (const tc of toolCalls) {+ callbacks?.onToolCall?.(tc);++ let result: string;+ try {+ const args = JSON.parse(tc.arguments) as Record<string, unknown>;+ result = await executeTool(tc.name, args);+ } catch (err) {+ const error = err instanceof Error ? err : new Error(String(err));+ callbacks?.onError?.(error);+ result = `Error: ${error.message}`;+ }++ callbacks?.onToolResult?.(tc.id, result);++ conversation.push({+ role: "tool",+ content: result,+ toolCallId: tc.id,+ });+ }++ continue;+ }++ // Text-only response — return final answer+ const text = response.content ?? "";+ callbacks?.onText?.(text);+ return text;+ }++ throw new Error("Agent loop exceeded maximum iterations");+}diff --git a/frontend/src/plugins/agent/logic/context.ts b/frontend/src/plugins/agent/logic/context.tsnew file mode 100644index 0000000000..6e605e4b93--- /dev/null+++ b/frontend/src/plugins/agent/logic/context.ts@@ -0,0 +1,99 @@+import type { RouteLocationNormalizedLoaded } from "vue-router";+import { useCurrentUserV1 } from "@/store";+import { Engine, State } from "@/types/proto-es/v1/common_pb";+import { Issue_Type, IssueStatus } from "@/types/proto-es/v1/issue_service_pb";++interface PageContext {+ user?: { name: string; email: string; title: string };+ project?: { name: string; title: string; state: string };+ database?: { name: string; engine: string; environment: string };+ issue?: { name: string; title: string; status: string; type: string };+ [key: string]: unknown;+}++export async function extractRouteContext(+ route: RouteLocationNormalizedLoaded+): Promise<PageContext> {+ const ctx: PageContext = {};++ // Current user — always available+ try {+ const user = useCurrentUserV1();+ if (user.value?.name) {+ ctx.user = {+ name: user.value.name,+ email: user.value.email,+ title: user.value.title,+ };+ }+ } catch {+ // Store not initialized+ }++ const { projectId, databaseName, instanceId, issueId } =+ route.params as Record<string, string>;++ // Project context+ if (projectId) {+ try {+ const { useProjectV1Store } = await import("@/store");+ const store = useProjectV1Store();+ const project = store.getProjectByName(`projects/${projectId}`);+ if (project?.name) {+ ctx.project = {+ name: project.name,+ title: project.title,+ state: State[project.state] ?? "",+ };+ }+ } catch {+ // Store not available+ }+ }++ // Database context+ if (instanceId && databaseName) {+ try {+ const { useDatabaseV1Store } = await import("@/store");+ const store = useDatabaseV1Store();+ const db = store.getDatabaseByName(+ `instances/${instanceId}/databases/${databaseName}`+ );+ if (db?.name) {+ ctx.database = {+ name: db.name,+ engine: db.instanceResource+ ? (Engine[db.instanceResource.engine] ?? "")+ : "",+ environment: db.effectiveEnvironment ?? "",+ };+ }+ } catch {+ // Store not available+ }+ }++ // Issue context+ if (projectId && issueId) {+ try {+ const { useIssueV1Store } = await import("@/store");+ const store = useIssueV1Store();+ const issue = await store.fetchIssueByName(+ `projects/${projectId}/issues/${issueId}`,+ true+ );+ if (issue?.name) {+ ctx.issue = {+ name: issue.name,+ title: issue.title,+ status: IssueStatus[issue.status] ?? "",+ type: Issue_Type[issue.type] ?? "",+ };+ }+ } catch {+ // Store not available or fetch failed+ }+ }++ return ctx;+}diff --git a/frontend/src/plugins/agent/logic/prompt.ts b/frontend/src/plugins/agent/logic/prompt.tsnew file mode 100644index 0000000000..9cc7c10ea7--- /dev/null+++ b/frontend/src/plugins/agent/logic/prompt.ts@@ -0,0 +1,90 @@+const serviceDirectory = `API Directory — use search_api(service="...") to browse endpoints, search_api(operationId="...") for schemas.++Database Management:+- DatabaseService: CRUD databases, list schemas/tables/columns, metadata, secrets, changelogs, slow queries, backups+- DatabaseCatalogService: semantic types, column masking config, data classification+- DatabaseGroupService: database groups, matching databases by expression++SQL & Queries:+- SQLService: execute SQL queries, export query results, SQL check/lint, parse SQL, differencing+- SheetService: internal saved SQL sheets (system use)+- WorksheetService: user-facing saved SQL worksheets++Change Management:+- PlanService: create/update database change plans, plan checks, spec management+- IssueService: change tickets (issues), approval flow, issue status, comments, subscribers+- RolloutService: rollout stages, tasks, task runs, batch rollout execution+- RevisionService: schema revision snapshots+- ReleaseService: release bundles grouping multiple changes++Access & Identity:+- AuthService: login, logout, password management, OAuth/OIDC+- UserService: user CRUD, list users+- GroupService: user groups+- ServiceAccountService: service account CRUD+- WorkloadIdentityService: workload identity federation+- RoleService: custom RBAC role definitions+- IdentityProviderService: SSO/IdP config (OIDC, OAuth2, LDAP)+- AccessGrantService: time-limited data access grants, approval++Infrastructure:+- InstanceService: database server instances, connections, SSL config+- InstanceRoleService: database roles/users on instances+- EnvironmentService: environments (dev, staging, prod)++Policy & Compliance:+- OrgPolicyService: organization policies (masking, access control, backup, SQL review)+- ReviewConfigService: SQL review rule configuration+- RiskService: risk rules for custom approval routing++Workspace:+- ProjectService: projects, webhooks, Git/VCS connectors, IAM bindings, project search+- SettingService: workspace-level settings (branding, approval, classification, mail, etc.)+- WorkspaceService: workspace metadata+- SubscriptionService: license and subscription info+- ActuatorService: server health, version, debug info+- AuditLogService: workspace audit logs++Utility:+- CelService: parse/format CEL expressions (Common Expression Language)+- AIService: internal AI chat endpoint (system use)+`;++export function buildSystemPrompt(pageContext: {+ path: string;+ title: string;+ role?: string;+}): string {+ return `You are Bytebase Assistant, an AI agent embedded in the Bytebase console.+You help DBAs and developers manage databases, write SQL, review changes,+and navigate the platform.++Rules:+- Always call get_page_state first to understand the current page context.+- Use navigate for "show me" / "go to" requests. Call navigate(list=true) first if unsure about the path — never guess routes.+- Use get_skill to load step-by-step workflow guides before multi-step tasks (SQL queries, schema changes, permission grants).+- Always confirm destructive actions (drop database, delete project) before executing.++Tool selection — choose based on context, not a fixed preference:+- DOM-first when the user is on a form, preview, editor, or creation page. These pages have unsaved/in-progress state that only exists in the UI — APIs cannot access it. Read from and write to visible elements directly.+- API-first when fetching data not visible on the current page, querying across resources, or performing bulk operations on persisted resources.+- Either works for mutations on persisted resources. Use DOM if the user is already on the relevant page and would benefit from seeing the interaction. Use API for speed or when the relevant page is not open.++DOM interaction workflow: get_page_state(mode="dom") → read element indices → dom_action(type, index, value).+API interaction workflow: Use the API Directory below to choose the right service first. Browse with search_api(service="..."), inspect the exact endpoint with search_api(operationId="..."), then call call_api(...). Do not guess operationIds or request body fields.++${serviceDirectory}++Core concepts:+- Workspace: top-level container. One workspace per deployment.+- Project: groups databases and members. All changes happen within a project.+- Database: belongs to a project, hosted on an instance.+- Instance: a database server (MySQL, PostgreSQL, etc.) in an environment.+- Environment: dev, staging, prod. Controls approval policies.+- Change ticket (Issue): the review workflow for schema/data changes.+ Flow: create → review → approve → roll out.+- SQL Editor: interactive query tool with access control.++Current page: ${pageContext.path}+Page title: ${pageContext.title}${pageContext.role ? `\nYour role: ${pageContext.role}` : ""}`;+}diff --git a/frontend/src/plugins/agent/logic/skills/databaseChange.ts b/frontend/src/plugins/agent/logic/skills/databaseChange.tsnew file mode 100644index 0000000000..c241621bc3--- /dev/null+++ b/frontend/src/plugins/agent/logic/skills/databaseChange.ts@@ -0,0 +1,151 @@+export const skill = {+ name: "database-change",+ description:+ "Use when making schema changes (DDL), data migrations, ALTER TABLE, CREATE TABLE, or deploying SQL changes through review workflow",+ content: `# Database Change++## Overview++Create database changes (DDL/DML) through Bytebase's review workflow. Supports single database or batch changes across multiple databases.++## Prerequisites++- Have \`bb.plans.create\`, \`bb.issues.create\`, \`bb.rollouts.create\` permissions+- Know the target database(s)++## Workflow++### Step 1: Create sheet(s) with SQL++SQL content must be **base64 encoded**. Engine field is **required**.++\`\`\`+search_api(operationId="SheetService/CreateSheet")+\`\`\`+\`\`\`+call_api(operationId="SheetService/CreateSheet", body={+ "parent": "projects/{project-id}",+ "sheet": {+ "title": "Add users table",+ "engine": "POSTGRES",+ "content": "Q1JFQVRFIFRBQkxFIHVzZXJzIChpZCBJTlQgUFJJTUFSWSBLRVkpOw=="+ }+})+\`\`\`++Note: \`Q1JFQVRFIFRBQkxFIHVzZXJzIChpZCBJTlQgUFJJTUFSWSBLRVkpOw==\` decodes to \`CREATE TABLE users (id INT PRIMARY KEY);\`++Use \`search_api(schema="Engine")\` to discover valid engine values.++### Step 2: Create a plan++Plan contains \`specs\` directly (not wrapped in "steps").++**Single database:**+\`\`\`+search_api(operationId="PlanService/CreatePlan")+\`\`\`+\`\`\`+call_api(operationId="PlanService/CreatePlan", body={+ "parent": "projects/{project-id}",+ "plan": {+ "title": "Add users table",+ "specs": [{+ "id": "spec-1",+ "changeDatabaseConfig": {+ "targets": ["instances/{instance-id}/databases/{database-name}"],+ "sheet": "projects/{project-id}/sheets/{sheet-id}",+ "type": "MIGRATE"+ }+ }]+ }+})+\`\`\`++**Batch change (multiple databases):**+\`\`\`+call_api(operationId="PlanService/CreatePlan", body={+ "parent": "projects/{project-id}",+ "plan": {+ "title": "Add users table to all databases",+ "specs": [+ {+ "id": "spec-dev",+ "changeDatabaseConfig": {+ "targets": ["instances/dev-pg/databases/mydb"],+ "sheet": "projects/{project-id}/sheets/{sheet-id}",+ "type": "MIGRATE"+ }+ },+ {+ "id": "spec-prod",+ "changeDatabaseConfig": {+ "targets": ["instances/prod-pg/databases/mydb"],+ "sheet": "projects/{project-id}/sheets/{sheet-id}",+ "type": "MIGRATE"+ }+ }+ ]+ }+})+\`\`\`++**Key concepts:**+- \`specs\` is a flat array directly on the plan (no "steps" wrapper)+- Each \`spec\` has a unique \`id\` (any string, used for identification)+- \`targets\` is an **array** (even for single database)+- Specs are executed based on rollout policy (can be sequential or parallel)++**Using database groups:**+\`\`\`+"targets": ["projects/{project-id}/databaseGroups/{group-name}"]+\`\`\`++### Step 3: Create an issue++\`\`\`+search_api(operationId="IssueService/CreateIssue")+\`\`\`+\`\`\`+call_api(operationId="IssueService/CreateIssue", body={+ "parent": "projects/{project-id}",+ "issue": {+ "title": "Add users table",+ "type": "DATABASE_CHANGE",+ "plan": "projects/{project-id}/plans/{plan-id}"+ }+})+\`\`\`++### Step 4: Create a rollout++\`\`\`+search_api(operationId="RolloutService/CreateRollout")+\`\`\`+\`\`\`+call_api(operationId="RolloutService/CreateRollout", body={+ "parent": "projects/{project-id}",+ "rollout": {+ "plan": "projects/{project-id}/plans/{plan-id}"+ }+})+\`\`\`++## Change Types++| Type | Use Case |+|------|----------|+| \`MIGRATE\` | Imperative schema/data changes (DDL and DML) |+| \`SDL\` | State-based declarative schema migration |++## Common Errors++| Error | Cause | Fix |+|-------|-------|-----|+| database not found | Wrong database reference | Verify \`instances/{id}/databases/{name}\` format |+| sheet not found | Sheet doesn't exist | Create sheet first (Step 1) |+| missing engine | Sheet without engine field | Add \`engine\` field to sheet |+| plan not found | Plan doesn't exist | Create plan before issue |+| invalid base64 | SQL not encoded | Base64 encode the SQL content |+| targets must be array | Using string instead of array | Wrap target in array: \`["..."]\` |`,+} as const;diff --git a/frontend/src/plugins/agent/logic/skills/grantPermission.ts b/frontend/src/plugins/agent/logic/skills/grantPermission.tsnew file mode 100644index 0000000000..c09d3939ca--- /dev/null+++ b/frontend/src/plugins/agent/logic/skills/grantPermission.ts@@ -0,0 +1,174 @@+export const skill = {+ name: "grant-permission",+ description:+ "Use when granting roles, managing access control, adding users to projects, or setting up RBAC permissions",+ content: `# Grant Permission++## Overview++Grant roles to users or groups using Bytebase's RBAC system. Permissions can be set at workspace level (global) or project level (scoped).++## Prerequisites++- Have \`bb.workspaces.setIamPolicy\` for workspace-level grants+- Have \`bb.projects.setIamPolicy\` for project-level grants++## Permission Levels++| Level | Scope | Use Case |+|-------|-------|----------|+| **Workspace** | All projects | Admins, DBAs, global viewers |+| **Project** | Single project | Developers, project owners |++## Workflow++### Step 1: List Available Roles++\`\`\`+search_api(operationId="RoleService/ListRoles")+\`\`\`+\`\`\`+call_api(operationId="RoleService/ListRoles", body={})+\`\`\`++**Built-in roles:**++| Role | Description |+|------|-------------|+| \`roles/workspaceAdmin\` | Full workspace access |+| \`roles/workspaceDBA\` | Database administration |+| \`roles/workspaceMember\` | Basic workspace access |+| \`roles/projectOwner\` | Full project access |+| \`roles/projectDeveloper\` | Development access (create issues, plans) |+| \`roles/projectReleaser\` | Execute rollouts |+| \`roles/sqlEditorUser\` | SQL Editor access only |+| \`roles/projectViewer\` | Read-only access |+| \`roles/gitopsServiceAgent\` | GitOps automation |++### Step 2: Get Current IAM Policy++Always fetch current policy first to avoid overwriting existing bindings.++**Workspace level:**+\`\`\`+search_api(operationId="WorkspaceService/GetIamPolicy")+\`\`\`+\`\`\`+call_api(operationId="WorkspaceService/GetIamPolicy", body={+ "resource": "workspaces/{id}"+})+\`\`\`++**Project level:**+\`\`\`+search_api(operationId="ProjectService/GetIamPolicy")+\`\`\`+\`\`\`+call_api(operationId="ProjectService/GetIamPolicy", body={+ "resource": "projects/{project-id}"+})+\`\`\`++Save the returned \`etag\` for the update.++### Step 3: Set IAM Policy++Add new bindings while preserving existing ones.++**Workspace level:**+\`\`\`+search_api(operationId="WorkspaceService/SetIamPolicy")+\`\`\`+\`\`\`+call_api(operationId="WorkspaceService/SetIamPolicy", body={+ "resource": "workspaces/{id}",+ "etag": "{etag-from-get}",+ "policy": {+ "bindings": [+ {+ "role": "roles/workspaceDBA",+ "members": ["user:[email protected]"]+ },+ {+ "role": "roles/workspaceMember",+ "members": [+ "user:[email protected]",+ "user:[email protected]",+ "group:[email protected]"+ ]+ }+ ]+ }+})+\`\`\`++**Project level:**+\`\`\`+call_api(operationId="ProjectService/SetIamPolicy", body={+ "resource": "projects/{project-id}",+ "etag": "{etag-from-get}",+ "policy": {+ "bindings": [+ {+ "role": "roles/projectOwner",+ "members": ["user:[email protected]"]+ },+ {+ "role": "roles/projectDeveloper",+ "members": ["group:[email protected]"]+ }+ ]+ }+})+\`\`\`++## Member Format++| Type | Format | Example |+|------|--------|---------|+| User | \`user:{email}\` | \`user:[email protected]\` |+| Group | \`group:{email}\` | \`group:[email protected]\` |+| All users | \`allUsers\` | \`allUsers\` |++## Time-Limited Access (CEL Expressions)++Grant temporary access using CEL conditions.++\`\`\`+call_api(operationId="ProjectService/SetIamPolicy", body={+ "resource": "projects/{project-id}",+ "etag": "{etag}",+ "policy": {+ "bindings": [{+ "role": "roles/projectDeveloper",+ "members": ["user:[email protected]"],+ "condition": {+ "expression": "request.time < timestamp('2024-12-31T23:59:59Z')",+ "title": "Temporary access",+ "description": "Access expires end of 2024"+ }+ }]+ }+})+\`\`\`++**CEL variables for sqlEditorUser:**+- \`resource.database\`: Database name (\`instances/{id}/databases/{name}\`)+- \`resource.schema_name\`: Schema name+- \`resource.table_name\`: Table name+- \`request.time\`: For expiration++**CEL examples:**+- Expire at date: \`request.time < timestamp('2024-12-31T23:59:59Z')\`+- Limit to database: \`resource.database == "instances/prod/databases/main"\`++## Common Errors++| Error | Cause | Fix |+|-------|-------|-----|+| etag mismatch | Policy changed | Re-fetch policy and retry |+| role not found | Invalid role name | List roles first, use \`roles/{name}\` format |+| invalid member | Wrong format | Use \`user:email\` or \`group:email\` format |+| permission denied | Missing setIamPolicy | Check workspace/project admin access |+| invalid CEL | Bad expression syntax | Validate CEL expression format |`,+} as const;diff --git a/frontend/src/plugins/agent/logic/skills/index.ts b/frontend/src/plugins/agent/logic/skills/index.tsnew file mode 100644index 0000000000..87779d08ee--- /dev/null+++ b/frontend/src/plugins/agent/logic/skills/index.ts@@ -0,0 +1,34 @@+import { skill as databaseChangeSkill } from "./databaseChange";+import { skill as grantPermissionSkill } from "./grantPermission";+import { skill as querySkill } from "./query";++interface Skill {+ name: string;+ description: string;+ content: string;+}++const skills: Skill[] = [querySkill, databaseChangeSkill, grantPermissionSkill];++const skillMap = new Map(skills.map((s) => [s.name, s]));++export interface GetSkillArgs {+ name?: string;+}++export function getSkill(args: GetSkillArgs): string {+ if (!args.name) {+ const list = skills+ .map((s) => `- **${s.name}**: ${s.description}`)+ .join("\n");+ return `Available skills:\n${list}\n\nCall get_skill(name="skill-name") to load a specific skill.`;+ }++ const skill = skillMap.get(args.name);+ if (!skill) {+ const names = skills.map((s) => s.name).join(", ");+ return `Skill "${args.name}" not found. Available skills: ${names}`;+ }++ return skill.content;+}diff --git a/frontend/src/plugins/agent/logic/skills/query.ts b/frontend/src/plugins/agent/logic/skills/query.tsnew file mode 100644index 0000000000..2816b38aa0--- /dev/null+++ b/frontend/src/plugins/agent/logic/skills/query.ts@@ -0,0 +1,66 @@+export const skill = {+ name: "query",+ description:+ "Use when running SQL queries, executing SELECT/INSERT/UPDATE/DELETE statements, or fetching data from databases",+ content: `# Execute SQL++## Overview++Run SQL queries against databases managed by Bytebase.++## Prerequisites++- Know the instance and database name+- Have \`bb.sql.query\` permission++## Workflow++1. **Get the schema**:+ \`\`\`+ search_api(operationId="SQLService/Query")+ \`\`\`++2. **List databases** (if needed):+ \`\`\`+ call_api(operationId="DatabaseService/ListDatabases", body={+ "parent": "workspaces/{id}",+ "filter": "name.matches(\\"db_name\\")"+ })+ \`\`\`++ Filter examples:+ - \`name.matches("employee")\` - database name contains "employee"+ - \`project == "projects/{project-id}"\` - databases in a project+ - \`instance == "instances/{instance-id}"\` - databases in an instance+ - \`engine == "MYSQL"\` - MySQL databases only+ - \`environment == "environments/prod" && name.matches("user")\` - combine filters++ **Extract \`dataSourceId\`** from \`instanceResource.dataSources\` in the response. Prefer \`type: "READ_ONLY"\` over \`type: "ADMIN"\` when available.++3. **Execute SQL**:+ \`\`\`+ call_api(operationId="SQLService/Query", body={+ "name": "instances/{instance-id}/databases/{database-name}",+ "dataSourceId": "{data-source-id}",+ "statement": "SELECT * FROM users LIMIT 10"+ })+ \`\`\`++ \`dataSourceId\` is **required**.++## Notes++- Query results may contain masked values due to data masking policies. Do not remove or modify masked values.+ - Full mask: \`******\`+ - Partial mask: \`**rn**\` (only "rn" visible)+- **Displaying partial masks:** Use backticks or code blocks when presenting results. Without escaping, markdown interprets \`**text**\` as bold formatting.++## Common Errors++| Error | Cause | Fix |+|-------|-------|-----|+| data source id is required | Missing dataSourceId field | Get dataSourceId from instanceResource.dataSources in database listing |+| database not found | Wrong instance/database name | List databases first |+| permission denied | Missing bb.sql.query | Check user permissions |+| syntax error | Invalid SQL | Check SQL syntax for the database engine |`,+} as const;diff --git a/frontend/src/plugins/agent/logic/tools/callApi.ts b/frontend/src/plugins/agent/logic/tools/callApi.tsnew file mode 100644index 0000000000..24a360ead3--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/callApi.ts@@ -0,0 +1,75 @@+import { getEndpointPath } from "./searchApi";++const baseAddress = import.meta.env.BB_GRPC_LOCAL || window.location.origin;++export interface CallApiArgs {+ operationId: string;+ body?: Record<string, unknown>;+}++export async function callApi(args: CallApiArgs): Promise<string> {+ if (!args.operationId) {+ return JSON.stringify({+ error:+ "operationId is required. Use search_api to find valid operations.",+ });+ }++ const path = getEndpointPath(args.operationId);+ if (!path) {+ return JSON.stringify({+ error: `Unknown operation: ${args.operationId}. Use search_api to find valid operations.`,+ });+ }++ const controller = new AbortController();+ const timeoutId = setTimeout(() => controller.abort(), 30_000);++ try {+ const response = await fetch(`${baseAddress}${path}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Connect-Protocol-Version": "1",+ },+ credentials: "include",+ body: JSON.stringify(args.body ?? {}),+ signal: controller.signal,+ });++ let respJSON: unknown = null;+ try {+ respJSON = await response.json();+ } catch {+ // Not valid JSON — leave as null.+ }++ if (response.status >= 400) {+ let error = `HTTP ${response.status}`;+ if (respJSON && typeof respJSON === "object") {+ const errMap = respJSON as Record<string, unknown>;+ if (typeof errMap.message === "string") {+ error = errMap.message;+ } else if (typeof errMap.code === "string") {+ error = errMap.code;+ }+ }+ return JSON.stringify({+ status: response.status,+ error,+ response: respJSON,+ });+ }++ return JSON.stringify({+ status: response.status,+ response: respJSON,+ });+ } catch (err) {+ return JSON.stringify({+ error: `Failed to call ${args.operationId}: ${err instanceof Error ? err.message : String(err)}`,+ });+ } finally {+ clearTimeout(timeoutId);+ }+}diff --git a/frontend/src/plugins/agent/logic/tools/domAction.ts b/frontend/src/plugins/agent/logic/tools/domAction.tsnew file mode 100644index 0000000000..87be421e6e--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/domAction.ts@@ -0,0 +1,15 @@+import type { Router } from "vue-router";+import { lazyExecuteDomAction } from "../../dom";++export interface DomActionArgs {+ type: "click" | "input" | "select" | "scroll";+ index: number;+ value?: string;+}++export function createDomActionTool(router: Router) {+ return async (args: DomActionArgs): Promise<string> => {+ const result = await lazyExecuteDomAction(args, router);+ return JSON.stringify(result);+ };+}diff --git a/frontend/src/plugins/agent/logic/tools/gen/.gitignore b/frontend/src/plugins/agent/logic/tools/gen/.gitignorenew file mode 100644index 0000000000..14e1e2ca87--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/gen/.gitignore@@ -0,0 +1,2 @@+# Generated by scripts/generate_openapi_index.js+openapi-index.tsdiff --git a/frontend/src/plugins/agent/logic/tools/index.ts b/frontend/src/plugins/agent/logic/tools/index.tsnew file mode 100644index 0000000000..4465166306--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/index.ts@@ -0,0 +1,208 @@+import type { Router } from "vue-router";+import type { ToolDefinition, ToolExecutor } from "../types";+import { getSkill, type GetSkillArgs } from "../skills";+import { callApi, type CallApiArgs } from "./callApi";+import { createDomActionTool, type DomActionArgs } from "./domAction";+import { createNavigateTool } from "./navigate";+import { createPageStateTool, type PageStateArgs } from "./pageState";+import { searchApi, type SearchApiArgs } from "./searchApi";++export function getToolDefinitions(): ToolDefinition[] {+ return [+ {+ name: "search_api",+ description: `Browse API endpoints and get request/response schemas. Use the API Directory in the system prompt to identify the right service first.++| Mode | Parameters | Result |+|------|------------|--------|+| List | (none) | All services |+| Browse | service="SQLService" | All endpoints in a service |+| Details | operationId="SQLService/Query" | Request/response schema |+| Schema | schema="Instance" | Message type definition |++**Typical workflow:** Read API Directory → search_api(service="...") → search_api(operationId="...") → call_api(...)`,+ parametersSchema: {+ type: "object",+ properties: {+ operationId: {+ type: "string",+ description:+ 'Get detailed schema for a specific endpoint. Supports short format: "SQLService/Query"',+ },+ schema: {+ type: "string",+ description:+ 'Get the definition of a message type. Examples: "Instance", "Engine", "bytebase.v1.Instance"',+ },+ service: {+ type: "string",+ description:+ 'Filter to a specific service. Examples: "SQLService", "DatabaseService"',+ },+ },+ },+ },+ {+ name: "call_api",+ description: `Execute a Bytebase API endpoint. **Use search_api first to get operationId and schema.**++| Parameter | Required | Description |+|-----------|----------|-------------|+| operationId | Yes | e.g., "SQLService/Query" |+| body | No | JSON request body |++**Resource names:** projects/my-project, instances/prod/databases/main++**Example:**+call_api(operationId="SQLService/Query", body={"name": "instances/i/databases/db", "statement": "SELECT 1"})`,+ parametersSchema: {+ type: "object",+ properties: {+ operationId: {+ type: "string",+ description:+ 'The operation ID from search_api results. Supports short format: "SQLService/Query"',+ },+ body: {+ type: "object",+ description:+ "JSON request body. Structure depends on the endpoint — use search_api with operationId to see the expected format.",+ },+ },+ required: ["operationId"],+ },+ },+ {+ name: "navigate",+ description: `Navigate to a page in Bytebase, or list all available routes.++| Mode | Parameters | Result |+|------|------------|--------|+| Navigate | path="/projects" | Navigates to the page |+| List | list=true | Returns all valid route patterns |++**Always call with list=true first if you are unsure about the exact path.** Do not guess paths — a wrong path causes a 404.`,+ parametersSchema: {+ type: "object",+ properties: {+ path: {+ type: "string",+ description:+ "URL path to navigate to. Supports param placeholders like /projects/:projectId.",+ },+ list: {+ type: "boolean",+ description:+ "Set to true to list all available route patterns instead of navigating.",+ },+ },+ },+ },+ {+ name: "get_page_state",+ description: `Get information about the current page.++| Mode | Result |+|------|--------|+| semantic (default) | Route path, params, title + context from Pinia stores (project, database, issue, user info when available) |+| dom | Above + indexed DOM tree of interactive elements |++Use mode="dom" before dom_action to get element indices. Use semantic mode (default) to understand the current page context.`,+ parametersSchema: {+ type: "object",+ properties: {+ mode: {+ type: "string",+ enum: ["semantic", "dom"],+ description:+ 'Default "semantic" returns route info + store context. "dom" adds an indexed tree of interactive elements for use with dom_action.',+ },+ },+ },+ },+ {+ name: "dom_action",+ description: `Last-resort DOM interaction — use only when no API endpoint covers the action.+**Always call get_page_state(mode="dom") first** to get the element index.++| Action | When to use | value param |+|--------|-------------|-------------|+| click | Buttons, links, tabs, checkboxes | not needed |+| input | Text fields, textareas, code editors | required — the text to enter |+| select | Dropdowns | required — the option text to select |+| read | Get full content of an element (editor, input) | not needed |+| scroll | Bring element into viewport | not needed |`,+ parametersSchema: {+ type: "object",+ properties: {+ type: {+ type: "string",+ enum: ["click", "input", "select", "read", "scroll"],+ description: "The action to perform",+ },+ index: {+ type: "number",+ description:+ "Element index from DOM tree (from get_page_state with mode='dom')",+ },+ value: {+ type: "string",+ description: "Value for input/select actions",+ },+ },+ required: ["type", "index"],+ },+ },+ {+ name: "get_skill",+ description: `Get step-by-step workflow guides for common Bytebase tasks. Load a skill before performing multi-step operations.++| Mode | Parameters | Result |+|------|------------|--------|+| List | (none) | All available skills |+| Load | name="query" | Step-by-step workflow guide |++**Available skills:** query, database-change, grant-permission++**Workflow:** get_skill() → get_skill(name="...") → follow the guide using search_api + call_api`,+ parametersSchema: {+ type: "object",+ properties: {+ name: {+ type: "string",+ description:+ 'Skill name to load. Omit to list all skills. Examples: "query", "database-change", "grant-permission"',+ },+ },+ },+ },+ ];+}++export function createToolExecutor(router: Router): ToolExecutor {+ const navigateTool = createNavigateTool(router);+ const pageStateTool = createPageStateTool(router);+ const domActionTool = createDomActionTool(router);++ return async (+ name: string,+ args: Record<string, unknown>+ ): Promise<string> => {+ switch (name) {+ case "search_api":+ return searchApi(args as SearchApiArgs);+ case "call_api":+ return callApi(args as unknown as CallApiArgs);+ case "navigate":+ return navigateTool(args as { path?: string; list?: boolean });+ case "get_page_state":+ return pageStateTool(args as PageStateArgs);+ case "dom_action":+ return domActionTool(args as unknown as DomActionArgs);+ case "get_skill":+ return getSkill(args as GetSkillArgs);+ default:+ return JSON.stringify({ error: `Unknown tool: ${name}` });+ }+ };+}diff --git a/frontend/src/plugins/agent/logic/tools/navigate.ts b/frontend/src/plugins/agent/logic/tools/navigate.tsnew file mode 100644index 0000000000..a3d487503b--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/navigate.ts@@ -0,0 +1,51 @@+import type { Router } from "vue-router";++function getRouteMap(router: Router): string[] {+ const routes = router.getRoutes();+ const paths = new Set<string>();++ for (const route of routes) {+ const path = route.path;+ // Skip empty, auth-only, and error routes+ if (+ !path ||+ path.startsWith("/auth") ||+ path === "/setup" ||+ path === "/403" ||+ path === "/404"+ ) {+ continue;+ }+ // Skip internal layout-only routes (no name, have children)+ if (!route.name && route.children.length > 0) continue;++ paths.add(path);+ }++ return [...paths].sort();+}++export function createNavigateTool(router: Router) {+ return async (args: { path?: string; list?: boolean }): Promise<string> => {+ if (args.list) {+ const routes = getRouteMap(router);+ return JSON.stringify({ routes });+ }++ if (!args.path) {+ return JSON.stringify({ error: "path is required when list is not set" });+ }++ try {+ await router.push(args.path);+ return JSON.stringify({+ navigated: true,+ currentPath: router.currentRoute.value.fullPath,+ });+ } catch (err) {+ return JSON.stringify({+ error: `Navigation failed: ${err instanceof Error ? err.message : String(err)}`,+ });+ }+ };+}diff --git a/frontend/src/plugins/agent/logic/tools/pageState.ts b/frontend/src/plugins/agent/logic/tools/pageState.tsnew file mode 100644index 0000000000..ab01609d4d--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/pageState.ts@@ -0,0 +1,37 @@+import type { Router } from "vue-router";+import { lazyExtractDomTree } from "../../dom";+import { extractRouteContext } from "../context";++export interface PageStateArgs {+ mode?: "semantic" | "dom";+}++export function createPageStateTool(router: Router) {+ return async (args?: PageStateArgs): Promise<string> => {+ const route = router.currentRoute.value;+ const base: Record<string, unknown> = {+ path: route.fullPath,+ name: String(route.name ?? ""),+ params: route.params,+ query: route.query,+ title: document.title,+ };++ // Enrich with Pinia store data+ const ctx = await extractRouteContext(route);+ if (Object.keys(ctx).length > 0) {+ base.context = ctx;+ }++ if (args?.mode === "dom") {+ const { tree, count } = await lazyExtractDomTree();+ return JSON.stringify({+ ...base,+ interactiveElements: count,+ domTree: tree,+ });+ }++ return JSON.stringify(base);+ };+}diff --git a/frontend/src/plugins/agent/logic/tools/searchApi.ts b/frontend/src/plugins/agent/logic/tools/searchApi.tsnew file mode 100644index 0000000000..0db2718051--- /dev/null+++ b/frontend/src/plugins/agent/logic/tools/searchApi.ts@@ -0,0 +1,249 @@+// Multi-mode search for Bytebase API endpoints.+// Ported from backend/api/mcp/openapi_index.go and tool_search.go.++import {+ type EndpointInfo,+ endpoints,+ type PropertyInfo,+ type SchemaInfo,+ schemas,+} from "./gen/openapi-index";++export interface SearchApiArgs {+ operationId?: string;+ schema?: string;+ service?: string;+}++const TYPE_DESCRIPTIONS: Record<string, string> = {+ "google.protobuf.Timestamp": 'ISO 8601 format, e.g. "2024-01-15T01:30:15Z"',+ "google.protobuf.Duration": 'e.g. "3.5s" or "1h30m"',+ "google.protobuf.FieldMask": 'e.g. "title,engine"',+ "google.protobuf.Empty": "empty message",+ "google.protobuf.Any": "any JSON value",+ "google.protobuf.Struct": "JSON object",+ "google.protobuf.Value": "any JSON value",+};++// Singleton index built at import time.+class OpenAPIIndex {+ readonly byOperation: Map<string, EndpointInfo>;+ readonly byService: Map<string, EndpointInfo[]>;+ readonly services: string[];++ constructor() {+ this.byOperation = new Map();+ this.byService = new Map();++ const serviceSet = new Set<string>();++ for (const ep of endpoints) {+ this.byOperation.set(ep.operationId, ep);++ const list = this.byService.get(ep.service);+ if (list) {+ list.push(ep);+ } else {+ this.byService.set(ep.service, [ep]);+ }+ serviceSet.add(ep.service);+ }++ this.services = Array.from(serviceSet).sort();+ }++ // Resolve operationId, supporting short format "SQLService/Query".+ getEndpoint(operationId: string): EndpointInfo | undefined {+ const ep = this.byOperation.get(operationId);+ if (ep) return ep;++ // Short format: Service/Method -> bytebase.v1.Service.Method+ const parts = operationId.split("/");+ if (parts.length === 2) {+ const fullId = `bytebase.v1.${parts[0]}.${parts[1]}`;+ return this.byOperation.get(fullId);+ }+ return undefined;+ }++ getServiceEndpoints(service: string): EndpointInfo[] {+ return this.byService.get(service) ?? [];+ }+}++const index = new OpenAPIIndex();++// Resolve operationId to HTTP path (used by callApi).+export function getEndpointPath(operationId: string): string | undefined {+ return index.getEndpoint(operationId)?.path;+}++// --- Formatting helpers (matching Go tool_search.go) ---++function truncate(s: string, max: number): string {+ if (s.length <= max) return s;+ return s.slice(0, max) + "...";+}++function formatProperty(prop: PropertyInfo): string {+ const required = prop.required ? " (required)" : "";++ let desc = "";+ const shortDesc = TYPE_DESCRIPTIONS[prop.type];+ if (shortDesc) {+ desc = ` // ${shortDesc}`;+ } else if (prop.description) {+ const clean = prop.description.replace(/[\n\r]/g, " ");+ desc = ` // ${truncate(clean, 97)}`;+ }++ return ` "${prop.name}": ${prop.type}${required}${desc}`;+}++function formatServiceList(): string {+ const lines: string[] = [];+ lines.push("## Available Services\n");+ lines.push(+ 'Use `search_api(service="ServiceName")` to list endpoints in a service.\n'+ );++ for (const svc of index.services) {+ const eps = index.getServiceEndpoints(svc);+ lines.push(`- **${svc}** (${eps.length} endpoints)`);+ }++ lines.push(`\nTotal: ${index.services.length} services`);+ return lines.join("\n");+}++function formatEndpoints(eps: EndpointInfo[], limit: number): string {+ const lines: string[] = [];++ if (limit > 0 && eps.length > limit) {+ lines.push(`Showing ${limit} of ${eps.length} results:\n`);+ eps = eps.slice(0, limit);+ } else {+ lines.push(`Found ${eps.length} endpoints:\n`);+ }++ for (let i = 0; i < eps.length; i++) {+ const ep = eps[i];+ lines.push(`### ${i + 1}. ${ep.service}/${ep.method}`);+ lines.push(ep.summary);+ lines.push("");+ }++ return lines.join("\n");+}++function getSchemaProps(schemaRef: string): PropertyInfo[] | undefined {+ // Extract name from ref: "#/components/schemas/bytebase.v1.QueryRequest"+ const parts = schemaRef.split("/");+ const name = parts[parts.length - 1];+ const info = schemas[name];+ if (!info) return undefined;+ return info.properties;+}++function formatEndpointDetail(operationId: string): string {+ const ep = index.getEndpoint(operationId);+ if (!ep) {+ return `Unknown operationId: ${operationId}\n\nUse search_api(service="...") to browse endpoints.`;+ }++ const lines: string[] = [];+ lines.push(`## ${ep.service}/${ep.method}\n`);+ lines.push(`${ep.summary}\n`);++ // Request schema+ if (ep.requestSchemaRef) {+ const props = getSchemaProps(ep.requestSchemaRef);+ if (props && props.length > 0) {+ lines.push("### Request Body");+ lines.push("```json");+ lines.push("{");+ for (const prop of props) {+ lines.push(formatProperty(prop));+ }+ lines.push("}");+ lines.push("```\n");+ }+ }++ // Response schema+ if (ep.responseSchemaRef) {+ const props = getSchemaProps(ep.responseSchemaRef);+ if (props && props.length > 0) {+ lines.push("### Response Body");+ lines.push("```json");+ lines.push("{");+ for (const prop of props) {+ lines.push(formatProperty(prop));+ }+ lines.push("}");+ lines.push("```");+ }+ }++ return lines.join("\n");+}++function formatSchemaDetail(schemaName: string): string {+ // Try exact, then with prefix+ let info: SchemaInfo | undefined = schemas[schemaName];+ let displayName = schemaName;+ if (!info && !schemaName.startsWith("bytebase.v1.")) {+ const fullName = "bytebase.v1." + schemaName;+ info = schemas[fullName];+ displayName = fullName;+ }+ if (!info) {+ return `Unknown schema: ${schemaName}\n\nUse search_api(operationId="...") to see schemas in request/response bodies.`;+ }+ if (!displayName.startsWith("bytebase.v1.")) {+ displayName = "bytebase.v1." + displayName;+ }++ const lines: string[] = [];+ lines.push(`## ${displayName}\n`);++ if (info.type === "enum" && info.values) {+ lines.push(`**Enum values:** ${info.values.join(", ")}`);+ return lines.join("\n");+ }++ if (info.properties) {+ for (const prop of info.properties) {+ lines.push(formatProperty(prop));+ }+ }++ return lines.join("\n");+}++// --- Main search_api handler ---++export async function searchApi(args: SearchApiArgs): Promise<string> {+ const { operationId, schema, service } = args;++ if (operationId) {+ return formatEndpointDetail(operationId);+ }++ if (schema) {+ return formatSchemaDetail(schema);+ }++ if (!service) {+ return formatServiceList();+ }++ if (service) {+ const eps = index.getServiceEndpoints(service);+ if (eps.length === 0) {+ return `No endpoints found for service: ${service}\n\nAvailable services:\n${formatServiceList()}`;+ }+ return formatEndpoints(eps, 0); // no limit for service browse+ }+ return formatServiceList();+}diff --git a/frontend/src/plugins/agent/logic/types.ts b/frontend/src/plugins/agent/logic/types.tsnew file mode 100644index 0000000000..989e76cea5--- /dev/null+++ b/frontend/src/plugins/agent/logic/types.ts@@ -0,0 +1,24 @@+export interface ToolDefinition {+ name: string;+ description: string;+ parametersSchema: Record<string, unknown>;+}++export interface ToolCall {+ id: string;+ name: string;+ arguments: string; // JSON-encoded+ metadata?: string; // Opaque provider-specific data (e.g., Gemini thought_signature)+}++export interface Message {+ role: "system" | "user" | "assistant" | "tool";+ content?: string;+ toolCalls?: ToolCall[];+ toolCallId?: string;+}++export type ToolExecutor = (+ name: string,+ args: Record<string, unknown>+) => Promise<string>;diff --git a/frontend/src/plugins/agent/store/agent.ts b/frontend/src/plugins/agent/store/agent.tsnew file mode 100644index 0000000000..980c4669f0--- /dev/null+++ b/frontend/src/plugins/agent/store/agent.ts@@ -0,0 +1,121 @@+import { defineStore } from "pinia";+import { ref, watch } from "vue";+import type { Message } from "../logic/types";++const MESSAGES_KEY = "bb-agent-messages";++export const useAgentStore = defineStore("agent", () => {+ // Window state+ const visible = ref(false);+ const position = ref({+ x: window.innerWidth - 420,+ y: window.innerHeight - 520,+ });+ const size = ref({ width: 400, height: 500 });+ const minimized = ref(false);++ // Conversation+ const messages = ref<Message[]>([]);+ const loading = ref(false);+ const error = ref<string | null>(null);+ const abortController = ref<AbortController | null>(null);++ function toggle() {+ visible.value = !visible.value;+ if (visible.value) minimized.value = false;+ }++ function minimize() {+ minimized.value = true;+ }++ function restore() {+ minimized.value = false;+ }++ function addMessage(message: Message) {+ messages.value.push(message);+ }++ function clearMessages() {+ messages.value = [];+ localStorage.removeItem(MESSAGES_KEY);+ }++ function clearConversation() {+ clearMessages();+ cancel();+ }++ function clearError() {+ error.value = null;+ }++ function cancel() {+ abortController.value?.abort();+ abortController.value = null;+ loading.value = false;+ }++ function saveWindowState() {+ localStorage.setItem(+ "bb-agent-window",+ JSON.stringify({ position: position.value, size: size.value })+ );+ }++ function saveMessages() {+ localStorage.setItem(MESSAGES_KEY, JSON.stringify(messages.value));+ }++ function loadMessages() {+ const saved = localStorage.getItem(MESSAGES_KEY);+ if (saved) {+ try {+ const parsed = JSON.parse(saved);+ if (Array.isArray(parsed)) {+ messages.value = parsed;+ }+ } catch {+ // Ignore corrupted data+ localStorage.removeItem(MESSAGES_KEY);+ }+ }+ }++ function loadWindowState() {+ const saved = localStorage.getItem("bb-agent-window");+ if (saved) {+ const state = JSON.parse(saved);+ if (state.position) position.value = state.position;+ if (state.size) size.value = state.size;+ }+ }++ // Persist messages on every change+ watch(messages, saveMessages, { deep: true });++ // Load persisted messages on init+ loadMessages();++ return {+ visible,+ position,+ size,+ minimized,+ messages,+ loading,+ error,+ abortController,+ toggle,+ minimize,+ restore,+ addMessage,+ clearMessages,+ clearConversation,+ clearError,+ cancel,+ saveWindowState,+ loadWindowState,+ };+});diff --git a/frontend/src/types/proto-es/v1/ai_service_pb.d.ts b/frontend/src/types/proto-es/v1/ai_service_pb.d.tsnew file mode 100644index 0000000000..42090dca63--- /dev/null+++ b/frontend/src/types/proto-es/v1/ai_service_pb.d.ts@@ -0,0 +1,249 @@+// @generated by protoc-gen-es v2.5.2+// @generated from file v1/ai_service.proto (package bytebase.v1, syntax proto3)+/* eslint-disable */++import type { GenEnum, GenFile, GenMessage, GenService } from "@bufbuild/protobuf/codegenv2";+import type { Message } from "@bufbuild/protobuf";++/**+ * Describes the file v1/ai_service.proto.+ */+export declare const file_v1_ai_service: GenFile;++/**+ * A single message in the conversation.+ *+ * @generated from message bytebase.v1.AIChatMessage+ */+export declare type AIChatMessage = Message<"bytebase.v1.AIChatMessage"> & {+ /**+ * The role of the message sender.+ *+ * @generated from field: bytebase.v1.AIChatMessageRole role = 1;+ */+ role: AIChatMessageRole;++ /**+ * The text content of the message. Optional for assistant messages that only contain tool calls.+ *+ * @generated from field: optional string content = 2;+ */+ content?: string;++ /**+ * Tool calls made by the assistant. Only present in assistant messages.+ *+ * @generated from field: repeated bytebase.v1.AIChatToolCall tool_calls = 3;+ */+ toolCalls: AIChatToolCall[];++ /**+ * The ID of the tool call this message is responding to. Only present in tool messages.+ *+ * @generated from field: optional string tool_call_id = 4;+ */+ toolCallId?: string;+};++/**+ * Describes the message bytebase.v1.AIChatMessage.+ * Use `create(AIChatMessageSchema)` to create a new message.+ */+export declare const AIChatMessageSchema: GenMessage<AIChatMessage>;++/**+ * A tool definition that the AI can invoke.+ *+ * @generated from message bytebase.v1.AIChatToolDefinition+ */+export declare type AIChatToolDefinition = Message<"bytebase.v1.AIChatToolDefinition"> & {+ /**+ * The name of the tool.+ *+ * @generated from field: string name = 1;+ */+ name: string;++ /**+ * A description of what the tool does.+ *+ * @generated from field: string description = 2;+ */+ description: string;++ /**+ * The JSON Schema describing the tool's parameters.+ *+ * @generated from field: string parameters_schema = 3;+ */+ parametersSchema: string;+};++/**+ * Describes the message bytebase.v1.AIChatToolDefinition.+ * Use `create(AIChatToolDefinitionSchema)` to create a new message.+ */+export declare const AIChatToolDefinitionSchema: GenMessage<AIChatToolDefinition>;++/**+ * A tool call made by the AI.+ *+ * @generated from message bytebase.v1.AIChatToolCall+ */+export declare type AIChatToolCall = Message<"bytebase.v1.AIChatToolCall"> & {+ /**+ * The unique ID of this tool call.+ *+ * @generated from field: string id = 1;+ */+ id: string;++ /**+ * The name of the tool to call.+ *+ * @generated from field: string name = 2;+ */+ name: string;++ /**+ * The JSON-encoded arguments to pass to the tool.+ *+ * @generated from field: string arguments = 3;+ */+ arguments: string;++ /**+ * Opaque provider-specific metadata (e.g., Gemini thought_signature).+ * Frontend must echo this back unchanged when sending tool results.+ *+ * @generated from field: optional string metadata = 4;+ */+ metadata?: string;+};++/**+ * Describes the message bytebase.v1.AIChatToolCall.+ * Use `create(AIChatToolCallSchema)` to create a new message.+ */+export declare const AIChatToolCallSchema: GenMessage<AIChatToolCall>;++/**+ * Request message for AIService.Chat.+ *+ * @generated from message bytebase.v1.AIChatRequest+ */+export declare type AIChatRequest = Message<"bytebase.v1.AIChatRequest"> & {+ /**+ * The conversation messages.+ *+ * @generated from field: repeated bytebase.v1.AIChatMessage messages = 1;+ */+ messages: AIChatMessage[];++ /**+ * The tool definitions available to the AI.+ *+ * @generated from field: repeated bytebase.v1.AIChatToolDefinition tool_definitions = 2;+ */+ toolDefinitions: AIChatToolDefinition[];+};++/**+ * Describes the message bytebase.v1.AIChatRequest.+ * Use `create(AIChatRequestSchema)` to create a new message.+ */+export declare const AIChatRequestSchema: GenMessage<AIChatRequest>;++/**+ * Response message for AIService.Chat.+ *+ * @generated from message bytebase.v1.AIChatResponse+ */+export declare type AIChatResponse = Message<"bytebase.v1.AIChatResponse"> & {+ /**+ * The text content of the AI response. Optional when the response only contains tool calls.+ *+ * @generated from field: optional string content = 1;+ */+ content?: string;++ /**+ * Tool calls the AI wants to make.+ *+ * @generated from field: repeated bytebase.v1.AIChatToolCall tool_calls = 2;+ */+ toolCalls: AIChatToolCall[];+};++/**+ * Describes the message bytebase.v1.AIChatResponse.+ * Use `create(AIChatResponseSchema)` to create a new message.+ */+export declare const AIChatResponseSchema: GenMessage<AIChatResponse>;++/**+ * Role of a chat message.+ *+ * @generated from enum bytebase.v1.AIChatMessageRole+ */+export enum AIChatMessageRole {+ /**+ * Unspecified role.+ *+ * @generated from enum value: AI_CHAT_MESSAGE_ROLE_UNSPECIFIED = 0;+ */+ AI_CHAT_MESSAGE_ROLE_UNSPECIFIED = 0,++ /**+ * System message providing instructions.+ *+ * @generated from enum value: AI_CHAT_MESSAGE_ROLE_SYSTEM = 1;+ */+ AI_CHAT_MESSAGE_ROLE_SYSTEM = 1,++ /**+ * User message.+ *+ * @generated from enum value: AI_CHAT_MESSAGE_ROLE_USER = 2;+ */+ AI_CHAT_MESSAGE_ROLE_USER = 2,++ /**+ * Assistant (AI) message.+ *+ * @generated from enum value: AI_CHAT_MESSAGE_ROLE_ASSISTANT = 3;+ */+ AI_CHAT_MESSAGE_ROLE_ASSISTANT = 3,++ /**+ * Tool result message.+ *+ * @generated from enum value: AI_CHAT_MESSAGE_ROLE_TOOL = 4;+ */+ AI_CHAT_MESSAGE_ROLE_TOOL = 4,+}++/**+ * Describes the enum bytebase.v1.AIChatMessageRole.+ */+export declare const AIChatMessageRoleSchema: GenEnum<AIChatMessageRole>;++/**+ * AIService provides AI chat capabilities for the page agent.+ *+ * @generated from service bytebase.v1.AIService+ */+export declare const AIService: GenService<{+ /**+ * Chat sends a conversation with tool definitions to the configured AI provider+ * and returns the AI response.+ *+ * @generated from rpc bytebase.v1.AIService.Chat+ */+ chat: {+ methodKind: "unary";+ input: typeof AIChatRequestSchema;+ output: typeof AIChatResponseSchema;+ },+}>;+diff --git a/frontend/src/types/proto-es/v1/ai_service_pb.js b/frontend/src/types/proto-es/v1/ai_service_pb.jsnew file mode 100644index 0000000000..7e80684338--- /dev/null+++ b/frontend/src/types/proto-es/v1/ai_service_pb.js@@ -0,0 +1,71 @@+// @generated by protoc-gen-es v2.5.2+// @generated from file v1/ai_service.proto (package bytebase.v1, syntax proto3)+/* eslint-disable */++import { enumDesc, fileDesc, messageDesc, serviceDesc, tsEnum } from "@bufbuild/protobuf/codegenv2";+import { file_google_api_annotations } from "../google/api/annotations_pb";+import { file_v1_annotation } from "./annotation_pb";++/**+ * Describes the file v1/ai_service.proto.+ */+export const file_v1_ai_service = /*@__PURE__*/+ fileDesc("ChN2MS9haV9zZXJ2aWNlLnByb3RvEgtieXRlYmFzZS52MSK8AQoNQUlDaGF0TWVzc2FnZRIsCgRyb2xlGAEgASgOMh4uYnl0ZWJhc2UudjEuQUlDaGF0TWVzc2FnZVJvbGUSFAoHY29udGVudBgCIAEoCUgAiAEBEi8KCnRvb2xfY2FsbHMYAyADKAsyGy5ieXRlYmFzZS52MS5BSUNoYXRUb29sQ2FsbBIZCgx0b29sX2NhbGxfaWQYBCABKAlIAYgBAUIKCghfY29udGVudEIPCg1fdG9vbF9jYWxsX2lkIlQKFEFJQ2hhdFRvb2xEZWZpbml0aW9uEgwKBG5hbWUYASABKAkSEwoLZGVzY3JpcHRpb24YAiABKAkSGQoRcGFyYW1ldGVyc19zY2hlbWEYAyABKAkiYQoOQUlDaGF0VG9vbENhbGwSCgoCaWQYASABKAkSDAoEbmFtZRgCIAEoCRIRCglhcmd1bWVudHMYAyABKAkSFQoIbWV0YWRhdGEYBCABKAlIAIgBAUILCglfbWV0YWRhdGEiegoNQUlDaGF0UmVxdWVzdBIsCghtZXNzYWdlcxgBIAMoCzIaLmJ5dGViYXNlLnYxLkFJQ2hhdE1lc3NhZ2USOwoQdG9vbF9kZWZpbml0aW9ucxgCIAMoCzIhLmJ5dGViYXNlLnYxLkFJQ2hhdFRvb2xEZWZpbml0aW9uImMKDkFJQ2hhdFJlc3BvbnNlEhQKB2NvbnRlbnQYASABKAlIAIgBARIvCgp0b29sX2NhbGxzGAIgAygLMhsuYnl0ZWJhc2UudjEuQUlDaGF0VG9vbENhbGxCCgoIX2NvbnRlbnQqvAEKEUFJQ2hhdE1lc3NhZ2VSb2xlEiQKIEFJX0NIQVRfTUVTU0FHRV9ST0xFX1VOU1BFQ0lGSUVEEAASHwobQUlfQ0hBVF9NRVNTQUdFX1JPTEVfU1lTVEVNEAESHQoZQUlfQ0hBVF9NRVNTQUdFX1JPTEVfVVNFUhACEiIKHkFJX0NIQVRfTUVTU0FHRV9ST0xFX0FTU0lTVEFOVBADEh0KGUFJX0NIQVRfTUVTU0FHRV9ST0xFX1RPT0wQBDJoCglBSVNlcnZpY2USWwoEQ2hhdBIaLmJ5dGViYXNlLnYxLkFJQ2hhdFJlcXVlc3QaGy5ieXRlYmFzZS52MS5BSUNoYXRSZXNwb25zZSIakOowAoLT5JMCEDoBKiILL3YxL2FpL2NoYXRCpAEKD2NvbS5ieXRlYmFzZS52MUIOQWlTZXJ2aWNlUHJvdG9QAVo0Z2l0aHViLmNvbS9ieXRlYmFzZS9ieXRlYmFzZS9iYWNrZW5kL2dlbmVyYXRlZC1nby92MaICA0JYWKoCC0J5dGViYXNlLlYxygILQnl0ZWJhc2VcVjHiAhdCeXRlYmFzZVxWMVxHUEJNZXRhZGF0YeoCDEJ5dGViYXNlOjpWMWIGcHJvdG8z", [file_google_api_annotations, file_v1_annotation]);++/**+ * Describes the message bytebase.v1.AIChatMessage.+ * Use `create(AIChatMessageSchema)` to create a new message.+ */+export const AIChatMessageSchema = /*@__PURE__*/+ messageDesc(file_v1_ai_service, 0);++/**+ * Describes the message bytebase.v1.AIChatToolDefinition.+ * Use `create(AIChatToolDefinitionSchema)` to create a new message.+ */+export const AIChatToolDefinitionSchema = /*@__PURE__*/+ messageDesc(file_v1_ai_service, 1);++/**+ * Describes the message bytebase.v1.AIChatToolCall.+ * Use `create(AIChatToolCallSchema)` to create a new message.+ */+export const AIChatToolCallSchema = /*@__PURE__*/+ messageDesc(file_v1_ai_service, 2);++/**+ * Describes the message bytebase.v1.AIChatRequest.+ * Use `create(AIChatRequestSchema)` to create a new message.+ */+export const AIChatRequestSchema = /*@__PURE__*/+ messageDesc(file_v1_ai_service, 3);++/**+ * Describes the message bytebase.v1.AIChatResponse.+ * Use `create(AIChatResponseSchema)` to create a new message.+ */+export const AIChatResponseSchema = /*@__PURE__*/+ messageDesc(file_v1_ai_service, 4);++/**+ * Describes the enum bytebase.v1.AIChatMessageRole.+ */+export const AIChatMessageRoleSchema = /*@__PURE__*/+ enumDesc(file_v1_ai_service, 0);++/**+ * Role of a chat message.+ *+ * @generated from enum bytebase.v1.AIChatMessageRole+ */+export const AIChatMessageRole = /*@__PURE__*/+ tsEnum(AIChatMessageRoleSchema);++/**+ * AIService provides AI chat capabilities for the page agent.+ *+ * @generated from service bytebase.v1.AIService+ */+export const AIService = /*@__PURE__*/+ serviceDesc(file_v1_ai_service, 0);+diff --git a/frontend/src/views/DashboardHeader.vue b/frontend/src/views/DashboardHeader.vueindex fc5b8fa1de..2d93234f88 100644--- a/frontend/src/views/DashboardHeader.vue+++ b/frontend/src/views/DashboardHeader.vue@@ -53,6 +53,13 @@</NButton></router-link>+ <NButton size="small" @click="agentStore.toggle()">+ <template #icon>+ <BotIcon class="w-4 h-4" />+ </template>+ <span v-if="windowWidth >= 640">Agent</span>+ </NButton>+<ProfileBrandingLogo><ProfileDropdown :link="true" /></ProfileBrandingLogo>@@ -69,6 +76,7 @@<script lang="ts" setup>import { computedAsync, useLocalStorage, useWindowSize } from "@vueuse/core";import {+ BotIcon,CircleDotIcon,MenuIcon,MessagesSquareIcon,@@ -81,6 +89,7 @@ import { computed, reactive } from "vue";import { useRoute, useRouter } from "vue-router";import ProjectSwitchPopover from "@/components/Project/ProjectSwitch/ProjectSwitchPopover.vue";import WeChatQRModal from "@/components/WeChatQRModal.vue";+import { useAgentStore } from "@/plugins/agent";import {WORKSPACE_ROUTE_LANDING,WORKSPACE_ROUTE_MY_ISSUES,@@ -128,6 +137,7 @@ interface LocalState {showProjectModal: boolean;}+const agentStore = useAgentStore();const subscriptionStore = useSubscriptionV1Store();const route = useRoute();const router = useRouter();diff --git a/proto/gen/grpc-doc/openapi.yaml b/proto/gen/grpc-doc/openapi.yamlindex 66c1219dac..c51e58dab2 100644--- a/proto/gen/grpc-doc/openapi.yaml+++ b/proto/gen/grpc-doc/openapi.yaml@@ -65,6 +65,28 @@ paths:application/json:schema:$ref: '#/components/schemas/google.protobuf.Empty'+ /v1/ai/chat:+ post:+ tags:+ - AIService+ summary: Chat+ description: |-+ Chat sends a conversation with tool definitions to the configured AI provider+ and returns the AI response.+ operationId: AIService_Chat+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.AIChatRequest'+ required: true+ responses:+ "200":+ description: Success+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/bytebase.v1.AIChatResponse'/v1/auditLogs:export:post:tags:@@ -15963,6 +15985,124 @@ paths:$ref: '#/components/schemas/bytebase.v1.AdminExecuteResponse'components:schemas:+ bytebase.v1.AIChatMessage:+ type: object+ properties:+ role:+ title: role+ description: The role of the message sender.+ $ref: '#/components/schemas/bytebase.v1.AIChatMessageRole'+ content:+ type:+ - string+ - "null"+ title: content+ description: The text content of the message. Optional for assistant messages that only contain tool calls.+ toolCalls:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatToolCall'+ title: tool_calls+ description: Tool calls made by the assistant. Only present in assistant messages.+ toolCallId:+ type:+ - string+ - "null"+ title: tool_call_id+ description: The ID of the tool call this message is responding to. Only present in tool messages.+ title: AIChatMessage+ additionalProperties: false+ description: A single message in the conversation.+ bytebase.v1.AIChatMessageRole:+ type: string+ title: AIChatMessageRole+ enum:+ - AI_CHAT_MESSAGE_ROLE_UNSPECIFIED+ - AI_CHAT_MESSAGE_ROLE_SYSTEM+ - AI_CHAT_MESSAGE_ROLE_USER+ - AI_CHAT_MESSAGE_ROLE_ASSISTANT+ - AI_CHAT_MESSAGE_ROLE_TOOL+ description: Role of a chat message.+ bytebase.v1.AIChatRequest:+ type: object+ properties:+ messages:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatMessage'+ title: messages+ description: The conversation messages.+ toolDefinitions:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatToolDefinition'+ title: tool_definitions+ description: The tool definitions available to the AI.+ title: AIChatRequest+ additionalProperties: false+ description: Request message for AIService.Chat.+ bytebase.v1.AIChatResponse:+ type: object+ properties:+ content:+ type:+ - string+ - "null"+ title: content+ description: The text content of the AI response. Optional when the response only contains tool calls.+ toolCalls:+ type: array+ items:+ $ref: '#/components/schemas/bytebase.v1.AIChatToolCall'+ title: tool_calls+ description: Tool calls the AI wants to make.+ title: AIChatResponse+ additionalProperties: false+ description: Response message for AIService.Chat.+ bytebase.v1.AIChatToolCall:+ type: object+ properties:+ id:+ type: string+ title: id+ description: The unique ID of this tool call.+ name:+ type: string+ title: name+ description: The name of the tool to call.+ arguments:+ type: string+ title: arguments+ description: The JSON-encoded arguments to pass to the tool.+ metadata:+ type:+ - string+ - "null"+ title: metadata+ description: |-+ Opaque provider-specific metadata (e.g., Gemini thought_signature).+ Frontend must echo this back unchanged when sending tool results.+ title: AIChatToolCall+ additionalProperties: false+ description: A tool call made by the AI.+ bytebase.v1.AIChatToolDefinition:+ type: object+ properties:+ name:+ type: string+ title: name+ description: The name of the tool.+ description:+ type: string+ title: description+ description: A description of what the tool does.+ parametersSchema:+ type: string+ title: parameters_schema+ description: The JSON Schema describing the tool's parameters.+ title: AIChatToolDefinition+ additionalProperties: false+ description: A tool definition that the AI can invoke.bytebase.v1.AICompletionRequest:type: objectproperties:@@ -29760,6 +29900,8 @@ tags:description: SettingService manages workspace-level settings and configurations.- name: ActuatorServicedescription: ActuatorService manages system health and operational information.+ - name: AIService+ description: AIService provides AI chat capabilities for the page agent.- name: AuditLogServicedescription: AuditLogService manages audit logs for system activities and API calls.- name: UserServicediff --git a/proto/gen/grpc-doc/v1/README.md b/proto/gen/grpc-doc/v1/README.mdindex a2e3c84af3..196b279e27 100644--- a/proto/gen/grpc-doc/v1/README.md+++ b/proto/gen/grpc-doc/v1/README.md@@ -133,6 +133,17 @@- [ActuatorService](#bytebase-v1-ActuatorService)+- [v1/ai_service.proto](#v1_ai_service-proto)+ - [AIChatMessage](#bytebase-v1-AIChatMessage)+ - [AIChatRequest](#bytebase-v1-AIChatRequest)+ - [AIChatResponse](#bytebase-v1-AIChatResponse)+ - [AIChatToolCall](#bytebase-v1-AIChatToolCall)+ - [AIChatToolDefinition](#bytebase-v1-AIChatToolDefinition)++ - [AIChatMessageRole](#bytebase-v1-AIChatMessageRole)++ - [AIService](#bytebase-v1-AIService)+- [v1/iam_policy.proto](#v1_iam_policy-proto)- [Binding](#bytebase-v1-Binding)- [BindingDelta](#bytebase-v1-BindingDelta)@@ -2648,6 +2659,132 @@ ActuatorService manages system health and operational information.+<a name="v1_ai_service-proto"></a>+<p align="right"><a href="#top">Top</a></p>++## v1/ai_service.proto++++<a name="bytebase-v1-AIChatMessage"></a>++### AIChatMessage+A single message in the conversation.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| role | [AIChatMessageRole](#bytebase-v1-AIChatMessageRole) | | The role of the message sender. |+| content | [string](#string) | optional | The text content of the message. Optional for assistant messages that only contain tool calls. |+| tool_calls | [AIChatToolCall](#bytebase-v1-AIChatToolCall) | repeated | Tool calls made by the assistant. Only present in assistant messages. |+| tool_call_id | [string](#string) | optional | The ID of the tool call this message is responding to. Only present in tool messages. |+++++++<a name="bytebase-v1-AIChatRequest"></a>++### AIChatRequest+Request message for AIService.Chat.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| messages | [AIChatMessage](#bytebase-v1-AIChatMessage) | repeated | The conversation messages. |+| tool_definitions | [AIChatToolDefinition](#bytebase-v1-AIChatToolDefinition) | repeated | The tool definitions available to the AI. |+++++++<a name="bytebase-v1-AIChatResponse"></a>++### AIChatResponse+Response message for AIService.Chat.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| content | [string](#string) | optional | The text content of the AI response. Optional when the response only contains tool calls. |+| tool_calls | [AIChatToolCall](#bytebase-v1-AIChatToolCall) | repeated | Tool calls the AI wants to make. |+++++++<a name="bytebase-v1-AIChatToolCall"></a>++### AIChatToolCall+A tool call made by the AI.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| id | [string](#string) | | The unique ID of this tool call. |+| name | [string](#string) | | The name of the tool to call. |+| arguments | [string](#string) | | The JSON-encoded arguments to pass to the tool. |+| metadata | [string](#string) | optional | Opaque provider-specific metadata (e.g., Gemini thought_signature). Frontend must echo this back unchanged when sending tool results. |+++++++<a name="bytebase-v1-AIChatToolDefinition"></a>++### AIChatToolDefinition+A tool definition that the AI can invoke.+++| Field | Type | Label | Description |+| ----- | ---- | ----- | ----------- |+| name | [string](#string) | | The name of the tool. |+| description | [string](#string) | | A description of what the tool does. |+| parameters_schema | [string](#string) | | The JSON Schema describing the tool's parameters. |+++++++++<a name="bytebase-v1-AIChatMessageRole"></a>++### AIChatMessageRole+Role of a chat message.++| Name | Number | Description |+| ---- | ------ | ----------- |+| AI_CHAT_MESSAGE_ROLE_UNSPECIFIED | 0 | Unspecified role. |+| AI_CHAT_MESSAGE_ROLE_SYSTEM | 1 | System message providing instructions. |+| AI_CHAT_MESSAGE_ROLE_USER | 2 | User message. |+| AI_CHAT_MESSAGE_ROLE_ASSISTANT | 3 | Assistant (AI) message. |+| AI_CHAT_MESSAGE_ROLE_TOOL | 4 | Tool result message. |++++++++<a name="bytebase-v1-AIService"></a>++### AIService+AIService provides AI chat capabilities for the page agent.++| Method Name | Request Type | Response Type | Description |+| ----------- | ------------ | ------------- | ------------|+| Chat | [AIChatRequest](#bytebase-v1-AIChatRequest) | [AIChatResponse](#bytebase-v1-AIChatResponse) | Chat sends a conversation with tool definitions to the configured AI provider and returns the AI response. |+++++<a name="v1_iam_policy-proto"></a><p align="right"><a href="#top">Top</a></p>diff --git a/proto/gen/grpc-doc/v1/index.html b/proto/gen/grpc-doc/v1/index.htmlindex 3a70cad59b..ea0240ae8b 100644--- a/proto/gen/grpc-doc/v1/index.html+++ b/proto/gen/grpc-doc/v1/index.html@@ -676,6 +676,45 @@</li>+ <li>+ <a href="#v1%2fai_service.proto">v1/ai_service.proto</a>+ <ul>++ <li>+ <a href="#bytebase.v1.AIChatMessage"><span class="badge">M</span>AIChatMessage</a>+ </li>++ <li>+ <a href="#bytebase.v1.AIChatRequest"><span class="badge">M</span>AIChatRequest</a>+ </li>++ <li>+ <a href="#bytebase.v1.AIChatResponse"><span class="badge">M</span>AIChatResponse</a>+ </li>++ <li>+ <a href="#bytebase.v1.AIChatToolCall"><span class="badge">M</span>AIChatToolCall</a>+ </li>++ <li>+ <a href="#bytebase.v1.AIChatToolDefinition"><span class="badge">M</span>AIChatToolDefinition</a>+ </li>+++ <li>+ <a href="#bytebase.v1.AIChatMessageRole"><span class="badge">E</span>AIChatMessageRole</a>+ </li>++++ <li>+ <a href="#bytebase.v1.AIService"><span class="badge">S</span>AIService</a>+ </li>++ </ul>+ </li>++<li><a href="#v1%2fiam_policy.proto">v1/iam_policy.proto</a><ul>@@ -8087,6 +8126,300 @@ Permissions required: None</p></td>+ <div class="file-heading">+ <h2 id="v1/ai_service.proto">v1/ai_service.proto</h2><a href="#title">Top</a>+ </div>+ <p></p>+++ <h3 id="bytebase.v1.AIChatMessage">AIChatMessage</h3>+ <p>A single message in the conversation.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>role</td>+ <td><a href="#bytebase.v1.AIChatMessageRole">AIChatMessageRole</a></td>+ <td></td>+ <td><p>The role of the message sender. </p></td>+ </tr>++ <tr>+ <td>content</td>+ <td><a href="#string">string</a></td>+ <td>optional</td>+ <td><p>The text content of the message. Optional for assistant messages that only contain tool calls. </p></td>+ </tr>++ <tr>+ <td>tool_calls</td>+ <td><a href="#bytebase.v1.AIChatToolCall">AIChatToolCall</a></td>+ <td>repeated</td>+ <td><p>Tool calls made by the assistant. Only present in assistant messages. </p></td>+ </tr>++ <tr>+ <td>tool_call_id</td>+ <td><a href="#string">string</a></td>+ <td>optional</td>+ <td><p>The ID of the tool call this message is responding to. Only present in tool messages. </p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.AIChatRequest">AIChatRequest</h3>+ <p>Request message for AIService.Chat.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>messages</td>+ <td><a href="#bytebase.v1.AIChatMessage">AIChatMessage</a></td>+ <td>repeated</td>+ <td><p>The conversation messages. </p></td>+ </tr>++ <tr>+ <td>tool_definitions</td>+ <td><a href="#bytebase.v1.AIChatToolDefinition">AIChatToolDefinition</a></td>+ <td>repeated</td>+ <td><p>The tool definitions available to the AI. </p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.AIChatResponse">AIChatResponse</h3>+ <p>Response message for AIService.Chat.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>content</td>+ <td><a href="#string">string</a></td>+ <td>optional</td>+ <td><p>The text content of the AI response. Optional when the response only contains tool calls. </p></td>+ </tr>++ <tr>+ <td>tool_calls</td>+ <td><a href="#bytebase.v1.AIChatToolCall">AIChatToolCall</a></td>+ <td>repeated</td>+ <td><p>Tool calls the AI wants to make. </p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.AIChatToolCall">AIChatToolCall</h3>+ <p>A tool call made by the AI.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>id</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The unique ID of this tool call. </p></td>+ </tr>++ <tr>+ <td>name</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The name of the tool to call. </p></td>+ </tr>++ <tr>+ <td>arguments</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The JSON-encoded arguments to pass to the tool. </p></td>+ </tr>++ <tr>+ <td>metadata</td>+ <td><a href="#string">string</a></td>+ <td>optional</td>+ <td><p>Opaque provider-specific metadata (e.g., Gemini thought_signature).+Frontend must echo this back unchanged when sending tool results. </p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.AIChatToolDefinition">AIChatToolDefinition</h3>+ <p>A tool definition that the AI can invoke.</p>+++ <table class="field-table">+ <thead>+ <tr><td>Field</td><td>Type</td><td>Label</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>name</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The name of the tool. </p></td>+ </tr>++ <tr>+ <td>description</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>A description of what the tool does. </p></td>+ </tr>++ <tr>+ <td>parameters_schema</td>+ <td><a href="#string">string</a></td>+ <td></td>+ <td><p>The JSON Schema describing the tool's parameters. </p></td>+ </tr>++ </tbody>+ </table>++++++++ <h3 id="bytebase.v1.AIChatMessageRole">AIChatMessageRole</h3>+ <p>Role of a chat message.</p>+ <table class="enum-table">+ <thead>+ <tr><td>Name</td><td>Number</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>AI_CHAT_MESSAGE_ROLE_UNSPECIFIED</td>+ <td>0</td>+ <td><p>Unspecified role.</p></td>+ </tr>++ <tr>+ <td>AI_CHAT_MESSAGE_ROLE_SYSTEM</td>+ <td>1</td>+ <td><p>System message providing instructions.</p></td>+ </tr>++ <tr>+ <td>AI_CHAT_MESSAGE_ROLE_USER</td>+ <td>2</td>+ <td><p>User message.</p></td>+ </tr>++ <tr>+ <td>AI_CHAT_MESSAGE_ROLE_ASSISTANT</td>+ <td>3</td>+ <td><p>Assistant (AI) message.</p></td>+ </tr>++ <tr>+ <td>AI_CHAT_MESSAGE_ROLE_TOOL</td>+ <td>4</td>+ <td><p>Tool result message.</p></td>+ </tr>++ </tbody>+ </table>++++++ <h3 id="bytebase.v1.AIService">AIService</h3>+ <p>AIService provides AI chat capabilities for the page agent.</p>+ <table class="enum-table">+ <thead>+ <tr><td>Method Name</td><td>Request Type</td><td>Response Type</td><td>Description</td></tr>+ </thead>+ <tbody>++ <tr>+ <td>Chat</td>+ <td><a href="#bytebase.v1.AIChatRequest">AIChatRequest</a></td>+ <td><a href="#bytebase.v1.AIChatResponse">AIChatResponse</a></td>+ <td><p>Chat sends a conversation with tool definitions to the configured AI provider+and returns the AI response.</p></td>+ </tr>++ </tbody>+ </table>+++++ <h4>Methods with HTTP bindings</h4>+ <table>+ <thead>+ <tr>+ <td>Method Name</td>+ <td>Method</td>+ <td>Pattern</td>+ <td>Body</td>+ </tr>+ </thead>+ <tbody>++++ <tr>+ <td>Chat</td>+ <td>POST</td>+ <td>/v1/ai/chat</td>+ <td>*</td>+ </tr>+++ </tbody>+ </table>++++<div class="file-heading"><h2 id="v1/iam_policy.proto">v1/iam_policy.proto</h2><a href="#title">Top</a></div>diff --git a/proto/v1/v1/ai_service.proto b/proto/v1/v1/ai_service.protonew file mode 100644index 0000000000..c4c0a36e16--- /dev/null+++ b/proto/v1/v1/ai_service.proto@@ -0,0 +1,96 @@+syntax = "proto3";++package bytebase.v1;++import "google/api/annotations.proto";+import "v1/annotation.proto";++option go_package = "github.com/bytebase/bytebase/backend/generated-go/v1";++// AIService provides AI chat capabilities for the page agent.+service AIService {+ // Chat sends a conversation with tool definitions to the configured AI provider+ // and returns the AI response.+ rpc Chat(AIChatRequest) returns (AIChatResponse) {+ option (google.api.http) = {+ post: "/v1/ai/chat"+ body: "*"+ };+ option (bytebase.v1.auth_method) = CUSTOM;+ }+}++// Role of a chat message.+enum AIChatMessageRole {+ // Unspecified role.+ AI_CHAT_MESSAGE_ROLE_UNSPECIFIED = 0;+ // System message providing instructions.+ AI_CHAT_MESSAGE_ROLE_SYSTEM = 1;+ // User message.+ AI_CHAT_MESSAGE_ROLE_USER = 2;+ // Assistant (AI) message.+ AI_CHAT_MESSAGE_ROLE_ASSISTANT = 3;+ // Tool result message.+ AI_CHAT_MESSAGE_ROLE_TOOL = 4;+}++// A single message in the conversation.+message AIChatMessage {+ // The role of the message sender.+ AIChatMessageRole role = 1;++ // The text content of the message. Optional for assistant messages that only contain tool calls.+ optional string content = 2;++ // Tool calls made by the assistant. Only present in assistant messages.+ repeated AIChatToolCall tool_calls = 3;++ // The ID of the tool call this message is responding to. Only present in tool messages.+ optional string tool_call_id = 4;+}++// A tool definition that the AI can invoke.+message AIChatToolDefinition {+ // The name of the tool.+ string name = 1;++ // A description of what the tool does.+ string description = 2;++ // The JSON Schema describing the tool's parameters.+ string parameters_schema = 3;+}++// A tool call made by the AI.+message AIChatToolCall {+ // The unique ID of this tool call.+ string id = 1;++ // The name of the tool to call.+ string name = 2;++ // The JSON-encoded arguments to pass to the tool.+ string arguments = 3;++ // Opaque provider-specific metadata (e.g., Gemini thought_signature).+ // Frontend must echo this back unchanged when sending tool results.+ optional string metadata = 4;+}++// Request message for AIService.Chat.+message AIChatRequest {+ // The conversation messages.+ repeated AIChatMessage messages = 1;++ // The tool definitions available to the AI.+ repeated AIChatToolDefinition tool_definitions = 2;+}++// Response message for AIService.Chat.+message AIChatResponse {+ // The text content of the AI response. Optional when the response only contains tool calls.+ optional string content = 1;++ // Tool calls the AI wants to make.+ repeated AIChatToolCall tool_calls = 2;+}