### Install LSP Servers and Run Integration Tests Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TEST_SUMMARY.md Commands to install required LSP servers for Go, Python, and TypeScript, verify their installation, and execute the full integration test suite. ```bash # Go go install golang.org/x/tools/gopls@latest # Python pip install pyright # TypeScript npm install -g typescript-language-server typescript # Verify installation gopls version pyright-langserver --version typescript-language-server --version # Run full test suite cd core/sdk make test-integration-all ``` -------------------------------- ### Install CodeGen SDK Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/README.md Install the SDK package using the Go toolchain. ```bash go get github.com/zeroroot-ai/sdk/codegen ``` -------------------------------- ### Install and Verify gopls Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Install the Go language server and verify the installation. ```bash go install golang.org/x/tools/gopls@latest gopls version ``` -------------------------------- ### Install Git Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Install or verify Git installation to resolve path-related errors. ```bash # Ubuntu/Debian sudo apt-get install git # macOS brew install git # Verify git --version ``` -------------------------------- ### Install and Verify pyright Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Install the Python language server via npm and verify the installation. ```bash npm install -g pyright pyright-langserver --version ``` -------------------------------- ### Install language server binaries Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/lsp/README.md Commands to install required language server binaries for the SDK. ```bash go install golang.org/x/tools/gopls@latest ``` -------------------------------- ### Install and Verify TypeScript Language Server Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Install the TypeScript/JavaScript language server and verify the installation. ```bash npm install -g typescript-language-server typescript typescript-language-server --version ``` -------------------------------- ### Configure gRPC Services Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Examples for initializing agents, tools, and plugins with specific ports and configurations. ```go serve.Agent(agent, serve.WithPort(50051), serve.WithHealthPort(8080), // K8s probes: /healthz, /readyz serve.WithTLS(certFile, keyFile), serve.WithLogger(logger), ) serve.Tool(tool, serve.WithPort(50052)) serve.Plugin(plugin, serve.WithPort(50053)) ``` -------------------------------- ### Implement a Plugin Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Example implementation of a GitLab plugin including method definitions and server initialization. ```go package main import ( "context" "github.com/zeroroot-ai/sdk/plugin" "github.com/zeroroot-ai/sdk/schema" "github.com/zeroroot-ai/sdk/serve" ) type GitLabPlugin struct { client *gitlab.Client } func (p *GitLabPlugin) Name() string { return "gitlab" } func (p *GitLabPlugin) Version() string { return "1.0.0" } func (p *GitLabPlugin) Description() string { return "GitLab integration" } func (p *GitLabPlugin) Methods() []plugin.MethodDescriptor { return []plugin.MethodDescriptor{ { Name: "list_projects", Description: "List accessible GitLab projects", InputSchema: schema.Object(). Property("group", schema.String().Description("Filter by group")). Property("limit", schema.Integer().Default(100)), OutputSchema: schema.Object(). Property("projects", schema.Array().Items(schema.Object())), }, { Name: "get_vulnerabilities", Description: "Get vulnerabilities for a project", InputSchema: schema.Object(). Property("project_id", schema.Integer().Required()). Property("severity", schema.Enum("critical", "high", "medium", "low")), }, } } func (p *GitLabPlugin) Initialize(ctx context.Context, config map[string]any) error { token := config["token"].(string) p.client = gitlab.NewClient(token) return nil } func (p *GitLabPlugin) Invoke(ctx context.Context, method string, input map[string]any) (map[string]any, error) { switch method { case "list_projects": return p.listProjects(ctx, input) case "get_vulnerabilities": return p.getVulnerabilities(ctx, input) default: return nil, fmt.Errorf("unknown method: %s", method) } } func main() { serve.Plugin(&GitLabPlugin{}, serve.WithPort(50053)) } ``` -------------------------------- ### Initialize Framework Interface Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Create a framework instance using a configuration file and manage its lifecycle with Start and Shutdown methods. ```go import "github.com/zeroroot-ai/sdk" // Create framework instance fw, err := sdk.NewFramework(ctx, sdk.Config{ ConfigPath: "~/.gibson/config.yaml", }) // Access framework services missions := fw.Missions() registry := fw.Registry() findings := fw.Findings() // Lifecycle management fw.Start(ctx) defer fw.Shutdown(ctx) ``` -------------------------------- ### Install Gibson SDK Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Use the Go toolchain to fetch the latest version of the Gibson SDK. ```bash go get github.com/zeroroot-ai/sdk@latest ``` -------------------------------- ### Reference Example Tests Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/README.md Locations for finding example test implementations within the codebase. ```go // See example_test.go files in each package: // - editor/example_test.go // - lsp/example_test.go // - integration_test.go ``` -------------------------------- ### Implement a Custom Tool Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Example implementation of a tool using the SDK, including metadata methods, proto message mapping, and execution logic. ```go package main import ( "context" "github.com/zeroroot-ai/sdk/tool" "github.com/zeroroot-ai/sdk/serve" pb "github.com/zeroroot-ai/tools/mytool-c/proto" ) type HTTPXTool struct{} func (t *HTTPXTool) Name() string { return "mytool-c" } func (t *HTTPXTool) Version() string { return "1.0.0" } func (t *HTTPXTool) Description() string { return "HTTP probing and analysis" } func (t *HTTPXTool) Tags() []string { return []string{"http", "recon", "web"} } func (t *HTTPXTool) InputMessageType() proto.Message { return &pb.ProbeRequest{} } func (t *HTTPXTool) OutputMessageType() proto.Message { return &pb.ProbeResponse{} } func (t *HTTPXTool) Execute(ctx context.Context, input proto.Message) (proto.Message, error) { req := input.(*pb.ProbeRequest) // Execute mytool-c probe result, err := runHTTPXProbe(ctx, req) if err != nil { return nil, err } return &pb.ProbeResponse{ StatusCode: result.StatusCode, ContentType: result.ContentType, Headers: result.Headers, Body: result.Body, }, nil } func main() { serve.Tool(&HTTPXTool{}, serve.WithPort(50052)) } ``` -------------------------------- ### GET /readyz Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Checks the readiness of the Gibson daemon and its dependencies. ```APIDOC ## GET /readyz ### Description Returns the readiness status of the Gibson daemon, confirming that all dependencies (Redis, Neo4j, etcd) are healthy. ### Method GET ### Endpoint /readyz ``` -------------------------------- ### Install Language Servers Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Install required language servers to resolve LSP-related test skips. ```bash # For Go go install golang.org/x/tools/gopls@latest # For Python pip install pyright # For TypeScript npm install -g typescript-language-server typescript ``` -------------------------------- ### Manage Tools Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Commands to list, show details, install, and view logs for tools. ```bash # List registered tools gibson tool list # Show tool details gibson tool show mytool-c # Install tool gibson tool install https://github.com/zeroroot-ai/tool-mytool-c # View tool logs gibson tool logs mytool-c ``` -------------------------------- ### Implement a Custom Agent Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md A complete example of an agent implementation, including LLM slot definitions, execution logic, and server registration. ```go package main import ( "context" "github.com/zeroroot-ai/sdk/agent" "github.com/zeroroot-ai/sdk/llm" "github.com/zeroroot-ai/sdk/serve" ) type APIScanner struct { config map[string]any } func (a *APIScanner) Name() string { return "api-scanner" } func (a *APIScanner) Version() string { return "1.0.0" } func (a *APIScanner) Description() string { return "Scans APIs for vulnerabilities" } func (a *APIScanner) LLMSlots() []agent.SlotDefinition { return []agent.SlotDefinition{ agent.NewSlotDefinition("primary", "Main reasoning LLM", true). WithConstraints(agent.SlotConstraints{ MinContextWindow: 8000, RequiredFeatures: []string{agent.FeatureToolUse}, }), agent.NewSlotDefinition("fast", "Quick classification", false). WithPreferredModels([]string{"claude-3-haiku"}), } } func (a *APIScanner) Execute(ctx context.Context, task agent.Task, h agent.Harness) (agent.Result, error) { // Use LLM for reasoning resp, err := h.Complete(ctx, "primary", []llm.Message{ llm.NewSystemMessage("You are an API security expert..."), llm.NewUserMessage(task.Goal), }) if err != nil { return agent.NewFailedResult(err), nil } // Execute tools scanResult, err := h.CallToolProto(ctx, "mytool-c", &mytool-c.ScanRequest{ Url: task.Target.URL, }) if err != nil { return agent.NewFailedResult(err), nil } // Submit findings if vuln := analyzeResponse(scanResult); vuln != nil { h.SubmitFinding(ctx, vuln) } // Store in memory for other agents h.Memory().Mission().Set(ctx, "scan_results", scanResult) return agent.NewSuccessResult(map[string]any{ "endpoints_scanned": len(scanResult.Endpoints), "vulnerabilities": len(scanResult.Vulnerabilities), }), nil } func main() { serve.Agent(&APIScanner{}, serve.WithPort(50051)) } ``` -------------------------------- ### Serve the Agent Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Initializes and starts the agent server with specific ports for service and health checks. ```go func main() { agent := &myagent.MyAgent{} serve.Agent(agent, serve.WithPort(50051), serve.WithHealthPort(8080), // K8s probes ) } ``` -------------------------------- ### Verify Git Installation Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Check the installed version of Git to ensure compatibility with integration tests. ```bash git --version ``` -------------------------------- ### Serve Agents, Tools, and Plugins Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Configures and starts gRPC servers for agents, tools, and plugins with optional TLS and worker modes. ```go serve.Agent(&MyAgent{}, serve.WithPort(50051), serve.WithHealthPort(8080), serve.WithGracefulShutdown(30*time.Second), serve.WithTLS("cert.pem", "key.pem"), ) serve.Tool(&MyTool{}, serve.WithPort(50052), serve.WithWorkerMode(serve.WorkerConfig{ RedisURL: "redis://localhost:6379", Concurrency: 10, }), ) serve.Plugin(&MyPlugin{}, serve.WithPort(50053), ) ``` -------------------------------- ### Apply and Validate Changes with LSP Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/lsp/INTEGRATION.md Demonstrates the full lifecycle of applying patches, starting the LSP manager, collecting diagnostics, and performing rollback on validation failure. ```go func ApplyAndValidateChanges(ctx context.Context, workspace string, patches []Patch) error { // 1. Apply patches for _, patch := range patches { if err := applyPatch(patch); err != nil { return fmt.Errorf("failed to apply patch: %w", err) } } // 2. Start LSP validation config := lsp.DefaultLSPConfig() config.ValidationTimeout = 15 * time.Second manager := lsp.NewLSPManager(config, slog.Default()) if err := manager.Start(ctx, workspace); err != nil { return fmt.Errorf("failed to start LSP manager: %w", err) } defer manager.Stop(ctx) if err := manager.WaitForReady(ctx); err != nil { return fmt.Errorf("LSP manager not ready: %w", err) } // 3. Validate all modified files allDiagnostics := []codegen.Diagnostic{} hasErrors := false for _, patch := range patches { diagnostics, err := manager.GetDiagnostics(ctx, patch.FilePath) if err != nil { return fmt.Errorf("failed to get diagnostics: %w", err) } allDiagnostics = append(allDiagnostics, diagnostics...) for _, d := range diagnostics { if d.IsError() { hasErrors = true slog.Error("validation error", "file", d.Path, "line", d.Line, "message", d.Message) } } } // 4. Decide on outcome if hasErrors { // Rollback changes for _, patch := range patches { rollbackPatch(patch) } return fmt.Errorf("validation failed with %d errors", countErrors(allDiagnostics)) } // 5. Success - commit or store changeset slog.Info("validation passed", "diagnostics", len(allDiagnostics)) return nil } ``` -------------------------------- ### Implement RPC Handler in Daemon Source: https://github.com/zeroroot-ai/sdk/blob/main/docs/how-to-add-a-rpc.md Example implementation of the RPC handler in the daemon, ensuring proper tenant context handling. ```go // internal/daemon/api/server.go (or a server_.go split file) func (s *Server) ListMyDrafts(ctx context.Context, req *daemonpb.ListMyDraftsRequest) (*daemonpb.ListMyDraftsResponse, error) { tenant, ok := auth.TenantFromContext(ctx) if !ok { return nil, status.Error(codes.PermissionDenied, "no tenant on context") } conn, err := s.pool.For(ctx, tenant) // data-plane spec if err != nil { /* ... */ } defer conn.Release() drafts, next, err := conn.MissionDrafts().List(ctx, req.PageSize, req.PageToken) if err != nil { return nil, status.Errorf(codes.Internal, "list drafts: %v", err) } return &daemonpb.ListMyDraftsResponse{Drafts: drafts, NextToken: next}, nil } ``` -------------------------------- ### GET /readyz Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Readiness probe endpoint for checking if the server is ready to accept traffic. ```APIDOC ## GET /readyz ### Description Readiness probe used to determine if the server is ready to accept incoming requests. ### Method GET ### Endpoint /readyz ``` -------------------------------- ### Kubernetes Deployment Configuration Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Example Kubernetes deployment manifest for running the tool in platform mode. ```yaml apiVersion: apps/v1 kind: Deployment metadata: name: my-nmap-tool spec: replicas: 5 # Scale horizontally template: spec: containers: - name: tool image: ghcr.io/you/my-nmap-tool:v0.1.0 env: - name: PLATFORM_URL value: gibson:50002 - name: BOOTSTRAP_TOKEN valueFrom: secretKeyRef: name: gibson-bootstrap key: token ``` -------------------------------- ### Execute Cypher Query and Map Results Source: https://github.com/zeroroot-ai/sdk/blob/main/graphrag/query/README.md A complete example showing how to build a Cypher query, execute it against Neo4j, and map the results to proto messages. ```go package main import ( "context" "fmt" "github.com/zeroroot-ai/sdk/api/gen/taxonomypb" "github.com/zeroroot-ai/sdk/graphrag/query" ) func main() { // Build a Cypher query cypher := query.BuildMatch("h", "host") + " " + query.BuildWhere("h", []query.Predicate{ {Field: "ip", Op: query.Eq, Value: "192.168.1.1"}, }) + " " + query.BuildReturn("h", nil) // Execute query (assuming you have a Neo4j client) rows, err := client.Query(ctx, cypher, nil) if err != nil { panic(err) } // Map results to proto messages hosts, err := query.MapRowsToProtos(rows, func() *taxonomypb.Host { return &taxonomypb.Host{} }) if err != nil { panic(err) } // Use the results for _, host := range hosts { fmt.Printf("Host: %s (%s)\n", host.GetHostname(), host.GetIp()) } } ``` -------------------------------- ### Implement a Kubernetes Troubleshooter Agent Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Example implementation of an agent that defines LLM slots and executes tools to diagnose cluster issues. ```go package main import ( "context" "github.com/zeroroot-ai/sdk/agent" "github.com/zeroroot-ai/sdk/llm" "github.com/zeroroot-ai/sdk/serve" ) type K8sTroubleshooter struct{} func (a *K8sTroubleshooter) Name() string { return "k8s-troubleshooter" } func (a *K8sTroubleshooter) Version() string { return "1.0.0" } func (a *K8sTroubleshooter) Description() string { return "Troubleshoots Kubernetes cluster issues" } func (a *K8sTroubleshooter) LLMSlots() []agent.SlotDefinition { return []agent.SlotDefinition{ agent.NewSlotDefinition("primary", "Main reasoning LLM", true). WithConstraints(agent.SlotConstraints{ MinContextWindow: 8000, RequiredFeatures: []string{agent.FeatureToolUse}, }), } } func (a *K8sTroubleshooter) Execute(ctx context.Context, task agent.Task, h agent.Harness) (agent.Result, error) { // Use LLM to reason about the issue messages := []llm.Message{ llm.NewSystemMessage("You are a Kubernetes expert. Diagnose cluster issues."), llm.NewUserMessage(task.Goal), } resp, err := h.Complete(ctx, "primary", messages) if err != nil { return agent.NewFailedResult(err), err } // Execute kubectl via tool output, err := h.ExecuteTool(ctx, "kubectl", &pb.KubectlRequest{ Command: "get pods -A --field-selector=status.phase!=Running", }) // Store findings in memory h.Memory().Mission().Set(ctx, "diagnosis", resp.Content) return agent.NewSuccessResult(map[string]any{ "diagnosis": resp.Content, "pods": output, }), nil } func main() { serve.Agent(&K8sTroubleshooter{}, serve.WithPort(50051)) } ``` -------------------------------- ### Common Entity Patterns Source: https://github.com/zeroroot-ai/sdk/blob/main/api/proto/DISCOVERY_RESULT.md Examples of initializing various graph entities including Hosts, Ports, Services, Endpoints, Vulnerabilities, and K8s Pods. ```go // Host {Ip: "192.168.1.100", Hostname: "server01", State: "up", Os: "Linux"} // Port (links to host via host_id) {HostId: "192.168.1.100", Number: 443, Protocol: "tcp", State: "open"} // Service (links to port via port_id) {PortId: "192.168.1.100:443:tcp", Name: "https", Version: "nginx 1.18"} // Endpoint {Url: "https://api.example.com/users", Method: "GET", StatusCode: 200} // Vulnerability {Id: "CVE-2024-1234", Name: "Buffer Overflow", CvssScore: 9.8} // K8s Pod {NamespaceId: "prod:default", Name: "webapp-abc123", Phase: "Running"} ``` -------------------------------- ### Configure GitHub Actions for Integration Tests Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Defines a workflow to set up Go and Node.js environments, install necessary LSP servers, and execute integration tests. ```yaml name: Integration Tests on: [push, pull_request] jobs: integration: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-go@v4 with: go-version: '1.21' - name: Install gopls run: go install golang.org/x/tools/gopls@latest - name: Install Node.js uses: actions/setup-node@v3 with: node-version: '18' - name: Install LSP servers run: | npm install -g pyright typescript-language-server typescript - name: Run integration tests run: | cd core/sdk/codegen go test -v -tags=integration -timeout=10m ``` -------------------------------- ### Query and export findings via CLI Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Command-line interface examples for filtering and exporting security findings. ```bash # All critical findings from last 7 days gibson finding list --severity critical --since 7d # Findings by category gibson finding list --category prompt_injection # Export for specific mission gibson finding export --mission m-abc123 --format sarif ``` -------------------------------- ### CI/CD Remote Daemon Integration Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Examples for connecting to a long-running Gibson deployment within CI/CD pipelines. ```yaml # .gitlab-ci.yml variables: GIBSON_DAEMON_ADDRESS: "gibson.internal.example.com:50002" security-scan: stage: test image: ghcr.io/zeroroot-ai/gibson:latest script: - gibson status - gibson attack --target $CI_PROJECT_NAME --agent api-scanner - gibson finding export --format sarif > gl-sast-report.json artifacts: reports: sast: gl-sast-report.json ``` ```yaml # GitHub Actions name: Security Scan on: [push] env: GIBSON_DAEMON_ADDRESS: gibson.internal.example.com:50002 jobs: scan: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - name: Run Gibson Scan run: | gibson attack --target ${{ github.repository }} --agent api-scanner gibson finding export --format sarif > results.sarif - name: Upload SARIF uses: github/codeql-action/upload-sarif@v3 with: sarif_file: results.sarif ``` -------------------------------- ### Unit Test Discovery Scan Source: https://github.com/zeroroot-ai/sdk/blob/main/api/proto/DISCOVERY_RESULT.md Example unit test verifying that the discovery scan request correctly populates host and port information in the response. ```go func TestMyTool_Discovery(t *testing.T) { tool := New() req := &pb.ScanRequest{ Target: "192.168.1.0/24", } resp, err := tool.ExecuteProto(context.Background(), req) require.NoError(t, err) scanResp := resp.(*pb.ScanResponse) // Verify discovery populated require.NotNil(t, scanResp.Discovery) assert.NotEmpty(t, scanResp.Discovery.Hosts) assert.NotEmpty(t, scanResp.Discovery.Ports) // Verify host details host := scanResp.Discovery.Hosts[0] assert.NotEmpty(t, host.Ip) assert.Equal(t, "up", host.State) // Verify port relationships port := scanResp.Discovery.Ports[0] assert.Equal(t, host.Ip, port.HostId) // Foreign key set correctly assert.Greater(t, port.Number, int32(0)) } ``` -------------------------------- ### Initialize and use LSP Manager in Go Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/lsp/README.md Demonstrates the full lifecycle of the LSP manager, including configuration, server startup, and diagnostic retrieval. ```go package main import ( "context" "log/slog" "time" "github.com/zeroroot-ai/sdk/codegen/lsp" ) func main() { // Create LSP manager with default config config := lsp.DefaultLSPConfig() config.ValidationTimeout = 15 * time.Second manager := lsp.NewLSPManager(config, slog.Default()) ctx := context.Background() // Start language servers for workspace if err := manager.Start(ctx, "/path/to/workspace"); err != nil { panic(err) } defer manager.Stop(ctx) // Wait for servers to be ready if err := manager.WaitForReady(ctx); err != nil { panic(err) } // Get diagnostics for a file diagnostics, err := manager.GetDiagnostics(ctx, "main.go") if err != nil { panic(err) } // Check for errors for _, d := range diagnostics { if d.IsError() { log.Printf("Error at line %d: %s", d.Line, d.Message) } } } ``` -------------------------------- ### Bootstrap a new tool project Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Initialize a new tool repository using the provided template. ```bash gh repo create my-nmap-tool --template zeroroot-ai/component-skeleton --public cd my-nmap-tool # You get: main.go, Dockerfile, Makefile, component.yaml, CLAUDE.md ``` -------------------------------- ### Initialize Agent with Platform Environment Source: https://github.com/zeroroot-ai/sdk/blob/main/docs/auth.md Use this method to automatically configure the agent with both Capability Grant and SPIFFE settings from environment variables. ```go err := serve.Agent(myAgent, serve.WithPlatformFromEnv()) ``` -------------------------------- ### Basic Discovery Pattern in Go Source: https://github.com/zeroroot-ai/sdk/blob/main/api/proto/DISCOVERY_RESULT.md Demonstrates the standard workflow for importing the discovery package, initializing a DiscoveryResult, and attaching it to a tool response. ```go // 1. Import import graphragpb "github.com/zeroroot-ai/sdk/api/gen/graphragpb" // 2. Create discovery result discovery := &graphragpb.DiscoveryResult{ Hosts: []*graphragpb.Host{ {Ip: "192.168.1.100", Hostname: "web01", State: "up"}, }, Ports: []*graphragpb.Port{ {HostId: "192.168.1.100", Number: 80, Protocol: "tcp"}, }, } // 3. Return in response (field 100) return &pb.MyToolResponse{ Discovery: discovery, } ``` -------------------------------- ### Integration Testing with Real LSP Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/lsp/INTEGRATION.md Demonstrates setting up a real LSP manager for integration tests, including workspace cleanup and availability checks. ```go func TestAgentWithRealLSP(t *testing.T) { if testing.Short() { t.Skip("skipping integration test") } workspace := setupTestWorkspace(t) defer cleanupWorkspace(workspace) manager := lsp.NewLSPManager(lsp.DefaultLSPConfig(), slog.Default()) if err := manager.Start(context.Background(), workspace); err != nil { t.Skipf("LSP not available: %v", err) } defer manager.Stop(context.Background()) // Test agent with real LSP validation } ``` -------------------------------- ### Configure LSP Manager settings Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/lsp/README.md Shows how to define custom paths for language server binaries and toggle language support. ```go config := lsp.LSPConfig{ // Language server binary paths (empty = search in PATH) GoplsPath: "/usr/local/bin/gopls", PyrightPath: "", TypeScriptServerPath: "", // Timeouts InitTimeout: 30 * time.Second, ValidationTimeout: 10 * time.Second, // Enable/disable specific languages EnableGo: true, EnablePython: true, EnableTypeScript: true, } manager := lsp.NewLSPManager(config, slog.Default()) ``` -------------------------------- ### GET /healthz Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Checks the liveness of the Gibson daemon process. ```APIDOC ## GET /healthz ### Description Returns the liveness status of the Gibson daemon process to ensure it is alive and responsive. ### Method GET ### Endpoint /healthz ``` -------------------------------- ### GET /healthz Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Liveness probe endpoint for checking if the server is running. ```APIDOC ## GET /healthz ### Description Liveness probe used to determine if the server process is currently running. ### Method GET ### Endpoint /healthz ``` -------------------------------- ### Structured Log Entry Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Example of a JSON log entry with trace correlation. ```json { "timestamp": "2024-01-15T10:30:00.000Z", "level": "INFO", "message": "Agent execution completed", "trace_id": "abc123def456", "span_id": "789xyz", "component": "orchestrator", "mission_id": "m-abc123", "agent": "api-scanner", "duration_ms": 45000, "findings": 3 } ``` -------------------------------- ### TypeScript Code Fixtures Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TEST_SUMMARY.md Examples demonstrating XSS vulnerabilities and their corrected versions. ```typescript // XSS vulnerability return "
Welcome " + username + "!
"; // Fixed version const escaped = username.replace(/[&<>"']/g, (char) => escapeMap[char]); return "
Welcome " + escaped + "!
"; ``` -------------------------------- ### Initialize default configuration Source: https://github.com/zeroroot-ai/sdk/blob/main/protoresolver/README.md Retrieve the default configuration settings for the resolver. ```go config := protoresolver.DefaultConfig() // Returns: // ProtoResolverConfig{ // CacheMaxEntries: 100, // CacheTTL: time.Hour, // StrictMode: true, // LogFallbacks: true, // } ``` -------------------------------- ### Manage Agents Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Commands to list, install, remove, and view logs for registered agents. ```bash # List registered agents gibson agent list # Show agent details gibson agent show api-scanner # Install agent from URL gibson agent install https://github.com/zeroroot-ai/agent-api-scanner # View agent logs gibson agent logs api-scanner # Stream agent logs gibson agent logs api-scanner --follow # Remove agent gibson agent remove api-scanner ``` -------------------------------- ### Attack Result Output Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Example JSON output representing the results of an attack mission. ```json { "status": "findings", "duration": "3m 45s", "turns": 12, "tokens_used": 15000, "findings": 3, "findings_by_severity": { "critical": 1, "high": 1, "medium": 1 } } ``` -------------------------------- ### Export findings to SARIF format Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Example of a SARIF-compliant JSON output for a security finding. ```json { "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json", "version": "2.1.0", "runs": [{ "tool": { "driver": { "name": "Gibson", "version": "1.0.0", "informationUri": "https://github.com/zeroroot-ai/gibson" } }, "results": [{ "ruleId": "sql-injection", "level": "error", "message": { "text": "SQL Injection in Login Endpoint" }, "locations": [{ "physicalLocation": { "artifactLocation": { "uri": "https://api.example.com/auth/login" } } }] }] }] } ``` -------------------------------- ### Python Code Fixtures Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TEST_SUMMARY.md Examples demonstrating SQL injection vulnerabilities and their corrected versions. ```python # SQL injection vulnerability query = "SELECT * FROM users WHERE username = '" + username + "'" cursor.execute(query) # Fixed version query = "SELECT * FROM users WHERE username = ?" cursor.execute(query, (username,)) ``` -------------------------------- ### Configure LSP Settings in Go Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/README.md Initialize the LSP configuration struct to define binary paths, timeouts, and enabled language servers. ```go config := lsp.LSPConfig{ // Specify custom binary paths (optional) GoplsPath: "/usr/local/bin/gopls", PyrightPath: "/usr/local/bin/pyright-langserver", TypeScriptServerPath: "/usr/local/bin/typescript-language-server", // Configure timeouts InitTimeout: 30 * time.Second, ValidationTimeout: 10 * time.Second, // Enable specific languages EnableGo: true, EnablePython: true, EnableTypeScript: true, } ``` -------------------------------- ### Expected LSP Integration Tests Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TEST_SUMMARY.md Lists the additional tests expected when LSP servers are installed. ```text Expected additional tests: - TestGoCodeWithLSP (~5s) - TestPythonCodeWithLSP (~5s) - TestTypeScriptCodeWithLSP (~5s) - TestLSPValidationIntegration (~5s) Total duration with LSP: ~25s ``` -------------------------------- ### Initialize ProtoResolver Source: https://github.com/zeroroot-ai/sdk/blob/main/protoresolver/README.md Create a resolver instance using either default settings or a custom configuration struct. ```go import ( "github.com/zeroroot-ai/sdk/protoresolver" ) // Create resolver with default configuration resolver := protoresolver.NewDefaultProtoResolver(protoresolver.DefaultConfig()) // Or customize configuration config := protoresolver.ProtoResolverConfig{ CacheMaxEntries: 200, // Max FileDescriptorSets to cache CacheTTL: 2 * time.Hour, // Cache entry lifetime StrictMode: true, // Fail if type not found LogFallbacks: true, // Log when falling back to FileDescriptorSet } resolver := protoresolver.NewDefaultProtoResolver(config) ``` -------------------------------- ### Implement an Nmap Tool with ZeroRoot SDK Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md A complete implementation of a tool that executes nmap, parses XML output, and populates a knowledge graph via DiscoveryResult. ```go package main import ( "context" "encoding/xml" "fmt" "os/exec" nmappb "github.com/you/my-nmap-tool/api/gen/nmap/v1" graphragpb "github.com/zeroroot-ai/sdk/api/gen/gibson/graphrag/v1" "github.com/zeroroot-ai/sdk/serve" "google.golang.org/protobuf/proto" ) type NmapTool struct{} func (t *NmapTool) Name() string { return "my-nmap-tool" } func (t *NmapTool) Version() string { return "v0.1.0" } func (t *NmapTool) InputMessageType() string { return "mytool.nmap.v1.NmapRequest" } func (t *NmapTool) OutputMessageType() string { return "mytool.nmap.v1.NmapResponse" } // Execute is the tool's main entrypoint. SDK serves it over gRPC. func (t *NmapTool) Execute(ctx context.Context, in proto.Message) (proto.Message, error) { req := in.(*nmappb.NmapRequest) // 1. Run nmap. args := []string{"-sV", "-oX", "-"} if req.ScanType != "" { args = append(args, "-s"+req.ScanType[:1]) } args = append(args, req.Targets...) out, err := exec.CommandContext(ctx, "nmap", args...).Output() if err != nil { return nil, err } // 2. Parse nmap's XML output (use a parser library — omitted here). var parsed nmapXML xml.Unmarshal(out, &parsed) // 3. Translate parsed XML → DiscoveryResult. // THIS is the part that lights up the knowledge graph. discovery := &graphragpb.DiscoveryResult{} for _, h := range parsed.Hosts { discovery.Hosts = append(discovery.Hosts, &graphragpb.Host{ Ip: h.Address, Hostname: ptr(h.Hostname), }) for _, p := range h.Ports { discovery.Ports = append(discovery.Ports, &graphragpb.Port{ Number: int32(p.Number), Protocol: p.Protocol, State: ptr(p.State), HostId: h.Address, // ← edge: Port BELONGS_TO Host }) if p.Service != "" { discovery.Services = append(discovery.Services, &graphragpb.Service{ Name: p.Service, PortId: fmt.Sprintf("%s:%d", h.Address, p.Number), // ← edge: Service RUNS_ON Port Version: p.Version, }) } } } // 4. Return the response with discovery in field 100. return &nmappb.NmapResponse{ RawXml: string(out), HostsScanned: int32(len(parsed.Hosts)), ScanDurationSeconds: parsed.Duration, Discovery: discovery, // ← the magic field }, nil } func ptr[T any](v T) *T { return &v } func main() { // serve.Tool handles all gRPC plumbing, FileDescriptorSet registration // with gibson, mode selection (local vs platform), health probes, OTel. if err := serve.Tool(&NmapTool{}); err != nil { panic(err) } } ``` -------------------------------- ### Memory Management Operations Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Examples of interacting with the three-tier memory system provided by the Harness interface. ```APIDOC ## Memory Operations ### Working Memory (Ephemeral) - `h.Memory().Working().Set(ctx, key, value)` - `h.Memory().Working().Get(ctx, key)` ### Mission Memory (Persistent/Redis) - `h.Memory().Mission().Set(ctx, key, data, metadata)` - `h.Memory().Mission().Search(ctx, query, limit)` ### Long-Term Memory (Vector Embeddings) - `h.Memory().LongTerm().Store(ctx, data, metadata)` - `h.Memory().LongTerm().Search(ctx, query, limit)` ``` -------------------------------- ### Initialize and use ProtoMetricsCollector in Go Source: https://github.com/zeroroot-ai/sdk/blob/main/protoresolver/README.md Demonstrates creating a collector, recording resolution attempts and cache operations, and retrieving statistics. ```go import "github.com/zeroroot-ai/sdk/protoresolver" // Create metrics collector collector := protoresolver.NewProtoMetricsCollector() // Record resolution attempts collector.RecordResolution( protoresolver.StrategyGlobalTypes, protoresolver.StatusSuccess, 1.5, // duration in milliseconds ) // Record cache operations collector.RecordCacheHit() collector.RecordCacheMiss() collector.RecordCacheEviction() // Get statistics stats := collector.Stats() fmt.Printf("Global types success: %d\n", stats.GlobalTypesSuccess) fmt.Printf("FileDescriptorSet success: %d\n", stats.FDSSuccess) fmt.Printf("Cache hit rate: %.2f%%\n", float64(stats.CacheHits) / float64(stats.CacheHits + stats.CacheMisses) * 100) fmt.Printf("P95 resolution time: %.2fms\n", stats.P95DurationMs) ``` -------------------------------- ### Manage Daemon Operations Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Commands to start, stop, restart, and check the status of the Gibson daemon. ```bash # Start daemon in foreground gibson daemon start # Start daemon in background gibson daemon start --background # Stop daemon gracefully gibson daemon stop # Check daemon status gibson daemon status # Restart daemon gibson daemon restart ``` -------------------------------- ### Implement Graceful Degradation for LSP Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/lsp/INTEGRATION.md Fallback to non-validated operations if the LSP manager fails to start. ```go manager := lsp.NewLSPManager(config, logger) if err := manager.Start(ctx, workspace); err != nil { logger.Warn("LSP validation unavailable, skipping", "error", err) // Continue without validation return applyPatchesWithoutValidation(patches) } defer manager.Stop(ctx) // Normal validation flow... ``` -------------------------------- ### View Package Structure Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md The SDK is organized into functional modules for agents, tools, memory, and more. ```text github.com/zeroroot-ai/sdk/ ├── agent/ # Agent interface and utilities ├── tool/ # Tool interface and workers ├── plugin/ # Plugin interface ├── llm/ # LLM abstraction layer ├── memory/ # Three-tier memory system ├── graphrag/ # Knowledge graph client ├── finding/ # Finding management ├── serve/ # gRPC serving utilities ├── schema/ # JSON Schema helpers ├── input/ # Type-safe input extraction └── types/ # Common types and errors ``` -------------------------------- ### Run sdk-bump command Source: https://github.com/zeroroot-ai/sdk/blob/main/cmd/sdk-bump/README.md General usage syntax for the sdk-bump CLI tool. ```bash sdk-bump --to vX.Y.Z [--dry-run] [--repos repo1,repo2] [--workdir /tmp/sdk-bump] [--json] [--ci-delay 30s] ``` -------------------------------- ### Log Orchestrator Decision Events Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Example JSON structure for logging decisions made by the orchestrator during mission execution. ```json { "event": "orchestrator_decision", "timestamp": "2024-01-15T10:30:00Z", "mission_id": "m-abc123", "decision": "invoke_agent", "reasoning": "Target reconnaissance complete, proceeding to vulnerability scan", "agent": "vuln-scanner", "confidence": 0.92 } ``` -------------------------------- ### Go Code Fixtures Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TEST_SUMMARY.md Examples of buggy and broken Go code used for testing workflows and LSP validation. ```go // Buggy calculator (TestFullWorkflow) func calculate(x int) int { return x * 2 // Bug: should be * 3 } // Syntax error (TestGoCodeWithLSP) func broken() { fmt.Println("Missing closing brace" // Missing } ``` -------------------------------- ### Execute Nmap Tool via SDK Source: https://github.com/zeroroot-ai/sdk/blob/main/README.md Demonstrates how to invoke a tool using the SDK's CallToolProto method within an agent's reasoning loop. ```go import ( nmappb "github.com/you/my-nmap-tool/api/gen/nmap/v1" // ← agent imports the tool's Go bindings ) // Inside the agent's reasoning loop: req := &nmappb.NmapRequest{ Targets: []string{"10.0.0.0/24"}, ScanType: "syn", Ports: []string{"1-1024"}, } resp := &nmappb.NmapResponse{} if err := h.CallToolProto(ctx, "my-nmap-tool", req, resp); err != nil { return err } slog.Info("nmap done", "hosts", resp.HostsScanned, "duration", resp.ScanDurationSeconds) ``` -------------------------------- ### Execute All Integration Tests Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Run the full suite of integration tests using make or go test commands. ```bash # From the SDK root make test-integration # Or directly with go test cd core/sdk/codegen go test -v -tags=integration -timeout=10m ``` -------------------------------- ### Perform Checkpoint Recovery in Go Source: https://github.com/zeroroot-ai/sdk/blob/main/FEATURES.md Demonstrates how to programmatically pause and resume missions using the daemon interface. ```go // Automatic checkpoint on pause daemon.PauseMission(ctx, missionID) // State persisted to Redis: missions:{id}:checkpoints:{timestamp} // Resume from latest checkpoint daemon.ResumeMission(ctx, missionID) // State restored, execution continues from checkpoint ``` -------------------------------- ### Configure GitLab CI for Integration Tests Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/INTEGRATION_TESTS.md Defines a CI job to install dependencies and run integration tests within a Go-based container. ```yaml integration: image: golang:1.21 before_script: - apt-get update && apt-get install -y nodejs npm - go install golang.org/x/tools/gopls@latest - npm install -g pyright typescript-language-server typescript script: - cd core/sdk/codegen - go test -v -tags=integration -timeout=10m ``` -------------------------------- ### LSPConfig Structure Definition Source: https://github.com/zeroroot-ai/sdk/blob/main/codegen/README.md Configuration settings for initializing LSP servers. ```go type LSPConfig struct { GoplsPath string PyrightPath string TypeScriptServerPath string InitTimeout time.Duration ValidationTimeout time.Duration EnableGo bool EnablePython bool EnableTypeScript bool } ```