{"id":50336952,"url":"https://github.com/studyzy/codebuddy-sdk-go","last_synced_at":"2026-05-29T14:01:30.361Z","repository":{"id":358512583,"uuid":"1241610896","full_name":"studyzy/codebuddy-sdk-go","owner":"studyzy","description":"CodeBuddy Code Golang SDK, based on https://www.codebuddy.cn/docs/cli/sdk","archived":false,"fork":false,"pushed_at":"2026-05-17T18:28:18.000Z","size":165,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-17T19:49:34.935Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/studyzy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2026-05-17T15:50:57.000Z","updated_at":"2026-05-17T18:28:22.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/studyzy/codebuddy-sdk-go","commit_stats":null,"previous_names":["studyzy/codebuddy-sdk-go"],"tags_count":null,"template":false,"template_full_name":null,"purl":"pkg:github/studyzy/codebuddy-sdk-go","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/studyzy%2Fcodebuddy-sdk-go","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/studyzy%2Fcodebuddy-sdk-go/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/studyzy%2Fcodebuddy-sdk-go/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/studyzy%2Fcodebuddy-sdk-go/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/studyzy","download_url":"https://codeload.github.com/studyzy/codebuddy-sdk-go/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/studyzy%2Fcodebuddy-sdk-go/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33655441,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-05-29T02:00:06.066Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-05-29T14:01:29.187Z","updated_at":"2026-05-29T14:01:30.350Z","avatar_url":"https://github.com/studyzy.png","language":"Go","funding_links":[],"categories":[],"sub_categories":[],"readme":"# CodeBuddy Golang SDK\n\nCodeBuddy Golang SDK 允许您在 Go 应用程序中集成 CodeBuddy 的 AI 能力。通过此 SDK，您可以轻松实现单次查询、管理多轮对话、配置自定义权限钩子 (Hooks) 以及扩展进程内 MCP 服务器。\n\n## 设计原则\n\n本项目遵循以下核心设计原则，确保代码质量和长期可维护性：\n\n### Golang 规范优先\n\n- 代码必须通过 `go vet` 和 `golangci-lint` 检查，零警告\n- 所有导出符号必须有符合 godoc 规范的注释（第一行以符号名称开头）\n- 错误处理使用 Go 惯用模式：显式返回 error，不使用 panic 处理业务逻辑\n- 代码格式统一使用 `gofmt` / `goimports`\n- 接口遵循\"小接口\"原则，优先定义在消费方\n- 并发代码正确使用 context、goroutine 和 channel\n\n### 测试要求\n\n- 所有新增或修改的公共函数/方法必须编写对应的单元测试\n- 测试覆盖率必须达到 60% 以上\n- 使用标准 `testing` 库 + table-driven tests 模式\n- Mock 对象通过接口注入实现\n- 集成测试使用 `//go:build integration` 构建标签隔离\n\n### 简洁与可维护性\n\n- YAGNI：不为假设的未来需求增加复杂度\n- 公共 API 表面积最小化，只暴露用户真正需要的功能\n- 避免过度抽象，依赖最小化，优先使用标准库\n\n## 架构概览\n\n```text\n┌───────────────────────────────────────────────────┐\n│                 Public API Layer                   │\n│                                                    │\n│  Query()          Client          Session          │\n│  (一次性查询)    (遗留入口)     (推荐多轮对话)      │\n│                     │               │              │\n│                     └───┬───────────┘              │\n│                         │ embeds                   │\n│                         ▼                          │\n│                    connCore                        │\n│              (共享连接核心逻辑)                      │\n│                         │                          │\n│                         ▼                          │\n│                   Transport                        │\n│                   (接口层)                          │\n│                    ╱       ╲                       │\n│        Subprocess        HTTP/ACP                  │\n│        Transport         Transport                 │\n│       (CLI 子进程)     (HTTP 通信)                  │\n└───────────────────────────────────────────────────┘\n```\n\n### 核心模块\n\n| 模块 | 文件 | 职责 |\n|:-----|:-----|:-----|\n| 包入口 | `codebuddy.go` | `Query()` 一次性查询 |\n| 客户端 | `client.go` | Client 工厂和遗留 API |\n| 会话 | `session.go` | Session 多轮对话管理 |\n| 连接核心 | `conn_core.go` | Client/Session 共享的连接管理逻辑 |\n| 传输层 | `transport.go`, `transport_subprocess.go`, `transport_http.go` | Transport 接口及实现 |\n| 消息类型 | `types_message.go` | Message/ContentBlock 类型定义 |\n| 配置选项 | `types_options.go` | Options/SessionOptions 等 |\n| MCP | `mcp.go`, `types_mcp.go` | 进程内 MCP Server |\n| Hooks | `types_hooks.go` | 事件钩子类型 |\n| 认证 | `auth.go` | 两阶段认证流程 |\n| 协议 | `protocol.go`, `message_parser.go` | 控制协议和消息解析 |\n| 错误 | `errors.go` | 错误类型定义 |\n\n## 安装\n\n在您的 Go 项目中，使用 `go get` 安装 SDK：\n\n```bash\ngo get github.com/studyzy/codebuddy-sdk-go\n```\n\n\u003e **注意**：确保您的环境中已安装 CodeBuddy CLI 可执行文件，SDK 将通过子进程与之通信。\n\n## 快速开始\n\n以下是一个简单的单次查询示例：\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log\"\n\n\t\"github.com/studyzy/codebuddy-sdk-go\"\n)\n\nfunc main() {\n\tctx := context.Background()\n\n\t// 发起单次查询\n\tmsgCh, err := codebuddy.Query(ctx, \"帮我写一个 Go 语言的 Hello World\", nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\t// 处理返回的消息流\n\tfor msg := range msgCh {\n\t\tswitch m := msg.(type) {\n\t\tcase *codebuddy.AssistantMessage:\n\t\t\tfor _, block := range m.Content {\n\t\t\t\tif tb, ok := block.(*codebuddy.TextBlock); ok {\n\t\t\t\t\tfmt.Print(tb.Text) // 打印 AI 生成的内容\n\t\t\t\t}\n\t\t\t}\n\t\tcase *codebuddy.ResultMessage:\n\t\t\tfmt.Printf(\"\\n[查询完成] 耗时: %dms\\n\", m.DurationMs)\n\t\tcase *codebuddy.ErrorMessage:\n\t\t\tlog.Fatalf(\"发生错误: %s\", m.Error)\n\t\t}\n\t}\n}\n```\n\n## 身份认证\n\nSDK 支持两阶段认证流程：获取登录 URL 并等待用户授权。\n\n```go\nfunc handleAuth(ctx context.Context) {\n\t// 启动认证流程\n\tflow, err := codebuddy.Authenticate(ctx, \u0026codebuddy.AuthOptions{\n\t\tTimeout: 300, // 等待用户登录的超时时间（秒）\n\t})\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tif flow.AuthURL != \"\" {\n\t\tfmt.Printf(\"请访问以下链接完成登录: %s\\n\", flow.AuthURL)\n\t}\n\n\t// 阻塞等待认证结果\n\tresult, err := flow.Wait(ctx)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n\n\tfmt.Printf(\"登录成功，用户: %s\\n\", result.UserInfo.UserName)\n}\n\n// 登出\nfunc handleLogout(ctx context.Context) {\n\terr := codebuddy.Logout(ctx, nil)\n\tif err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n```\n\n## 多轮对话 (Client)\n\n使用 `Client` 可以精细化管理连接生命周期，支持保持上下文的连续对话。\n\n```go\nfunc multiTurnConversation(ctx context.Context) {\n\tclient := codebuddy.NewClient(nil)\n\tif err := client.Connect(ctx, nil); err != nil {\n\t\tlog.Fatal(err)\n\t}\n\tdefer client.Close()\n\n\t// 第一轮\n\tclient.Send(ctx, \"谁是世界上最伟大的程序员？\")\n\t// ... 接收消息 (参考快速开始中的消息循环)\n\n\t// 第二轮（基于上下文）\n\tclient.Send(ctx, \"他有哪些著名的贡献？\")\n\t// ... 接收消息\n}\n```\n\n## 高级配置 (Options)\n\n`codebuddy.Options` 结构体提供了丰富的配置项，用于控制 CLI 行为：\n\n| 字段 | 类型 | 说明 |\n| :--- | :--- | :--- |\n| `Model` | `*string` | 指定主模型名称。 |\n| `CLIPath` | `*string` | CLI 可执行文件的绝对路径。 |\n| `SystemPrompt` | `*SystemPromptConfig` | 覆盖或追加全局系统提示词。 |\n| `Agents` | `map[string]AgentDefinition` | 定义子 Agent 及其能力。 |\n| `MCPServers` | `any` | 配置 MCP 服务器（支持 stdio, http, sse, sdk 等）。 |\n| `PermissionMode` | `*PermissionMode` | 权限模式：`default`, `acceptEdits`, `bypassPermissions` 等。 |\n| `CanUseTool` | `CanUseToolFunc` | 自定义工具执行权限控制回调。 |\n| `Hooks` | `map[HookEvent][]HookMatcher` | 注册事件钩子（如工具调用前后的干预）。 |\n\n### 权限控制回调 (CanUseTool)\n\n您可以拦截工具调用并决定是否允许：\n\n```go\nopts := \u0026codebuddy.Options{\n    CanUseTool: func(ctx context.Context, toolName string, input map[string]any, opts codebuddy.CanUseToolOptions) (codebuddy.PermissionResult, error) {\n        if toolName == \"Bash\" \u0026\u0026 strings.Contains(input[\"command\"].(string), \"rm\") {\n            return \u0026codebuddy.PermissionResultDeny{Message: \"禁止执行删除命令\"}, nil\n        }\n        return \u0026codebuddy.PermissionResultAllow{}, nil\n    },\n}\n```\n\n### 钩子 (Hooks)\n\nHook 允许您在特定事件发生时执行自定义逻辑：\n\n```go\nopts := \u0026codebuddy.Options{\n    Hooks: map[codebuddy.HookEvent][]codebuddy.HookMatcher{\n        codebuddy.HookPreToolUse: {{\n            Matcher: nil, // 匹配所有工具\n            Hooks: []codebuddy.HookCallback{\n                func(ctx context.Context, input map[string]any, id *string) (codebuddy.HookJSONOutput, error) {\n                    fmt.Println(\"准备执行工具...\")\n                    return codebuddy.HookJSONOutput{}, nil\n                },\n            },\n        }},\n    },\n}\n```\n\n## 核心类型参考\n\n### 消息类型 (Message)\n\n所有消息均实现 `Message` 接口。常见类型包括：\n- `*AssistantMessage`: 包含 AI 生成的内容块（`ContentBlock`）。\n- `*ResultMessage`: 包含会话最终状态、统计信息及结果字符串。\n- `*ErrorMessage`: 包含错误描述。\n- `*UserMessage`: 表示用户输入的消息。\n\n### 内容块 (ContentBlock)\n\n`AssistantMessage` 中的 `Content` 字段由多个块组成：\n- `*TextBlock`: 纯文本。\n- `*ThinkingBlock`: 模型的思考过程。\n- `*ToolUseBlock`: AI 发起的工具调用请求。\n- `*ToolResultBlock`: 工具执行后的结果反馈。\n\n## 开发指南\n\n### 构建与测试\n\n```bash\n# 编译\nmake build\n\n# 运行测试\nmake test\n\n# 覆盖率报告\nmake cover\n\n# 静态分析\nmake vet\nmake lint\n```\n\n### 提交规范\n\n提交信息遵循 [Conventional Commits](https://www.conventionalcommits.org/) 规范：\n\n- `feat:` 新功能\n- `fix:` Bug 修复\n- `docs:` 文档更新\n- `test:` 测试相关\n- `refactor:` 代码重构\n\n### 质量门禁\n\n所有提交必须满足：\n\n1. `go vet ./...` 零警告\n2. `golangci-lint run ./...` 零警告\n3. `go test ./...` 全部通过\n4. 测试覆盖率 \u003e= 60%\n\n---\n\n更多详细示例，请参阅项目中的 `examples/` 目录。\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstudyzy%2Fcodebuddy-sdk-go","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fstudyzy%2Fcodebuddy-sdk-go","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fstudyzy%2Fcodebuddy-sdk-go/lists"}