# Harbor Agent SDK — Go `package harboragent` — build a Harbor agent in Go. See [`../SPEC.md`](../SPEC.md) / [`../SPEC-highlevel.md`](../SPEC-highlevel.md). ```bash # inside the unpacked source package (harbor-agent-sdk-go-src.tar.gz from https://ai.nti56.com/dev/harbor/sdk//) go test ./... # unit + end-to-end (mock Harbor) go run ./examples/echo # run the echo agent on :7501 ``` Install details: [`../README.md`](../README.md) (section 「获取与安装」). ## Quick start ```go package main import ( "context" "net/http" hb "github.com/NTI56-AI/harbor-agent-sdk-go" ) type handler struct { hb.BaseHandler dedup *hb.Dedup } func (h handler) OnDeliverMessage(c *hb.Conn, m hb.DeliverMessage) error { cl := hb.NewClient(c) ctx := context.Background() if !h.dedup.Begin(m.ContextID, m.ChangeSeq) { // replay → ack & skip return cl.AckDelivery(ctx, m.ContextID, m.ChangeSeq) } _, _ = cl.SendText(ctx, m.ContextID, "echo: "+m.Text, m.OriginatingPrincipal.ID) return h.dedup.AckProcessed(ctx, cl, m.ContextID, m.ChangeSeq) } func main() { a := hb.New(hb.Options{ Token: "shared-secret", // static-token; "" = accept any (dev) Path: "/agent", Manifest: hb.Manifest{DisplayName: "小李", Version: 1, IsMentionable: true}, Handler: handler{dedup: hb.NewDedup()}, }) http.ListenAndServe(":7501", a.Mux()) } ``` ## 成员生命周期 / 重连对账 `BaseHandler` 另有两个回调(基类 no-op,旧 handler 不改即兼容): ```go // #22:context 成员增量(join / leave / context-closed);在线直投、离线重连补投 func (h handler) OnContextLifecycle(c *hb.Conn, e hb.ContextLifecycle) error { switch e.Event { case "context-closed": h.cache.DropContext(e.ContextID) case "participant-left": h.cache.DropParticipant(e.ContextID, e.ParticipantID) case "participant-joined": if e.IsSelf { // 自身被加入 → 拉一次全员名册 _, _ = hb.NewClient(c).GetParticipants(context.Background(), e.ContextID) } } return nil } // #23:(重)连接后下发当前在场 context 列表 → 对账,清理本地记着但不在列表的 func (h handler) OnResync(c *hb.Conn, r hb.ResyncContexts) error { h.cache.ReconcileContexts(r.Contexts) // 据 r.Contexts[].ContextID 对账 return nil } ``` ## Reply language: answer in the conversation's language (`ReplyLanguage`, SDK 0.51.0) 每条投递都带 `ReplyLanguage *string`(BCP-47,如 `en-US`;**`nil` = 未锁定** ⇒ 用你自己的默认,别自己去检测) 与 `ReplyLanguageSource *string`(`hb.ReplyLanguageSourceExplicit` = 用户亲口选的、尤其要尊重; `hb.ReplyLanguageSourceDetected` = Harbor 按前几条用户消息检测的,同样要跟随)。 🔴 **Harbor 的主模型就是按这一位回话的** —— 你不跟,用户看到的就是同一场对话里两种语言并排。 它是**对话级的锁**,不是「这条消息用什么语言写的」;Harbor 内部「仅此一轮」的临时切换不出现在这一位上。 ```go func (h handler) OnDeliverMessage(c *hb.Conn, m hb.DeliverMessage) error { cl, ctx := hb.NewClient(c), context.Background() lang := "zh-CN" // 你自己的默认 if m.ReplyLanguage != nil { lang = *m.ReplyLanguage // Harbor 锁了语言 ⇒ 用它 } sys := "Reply in " + lang + "." if m.ReplyLanguageSource != nil && *m.ReplyLanguageSource == hb.ReplyLanguageSourceExplicit { sys += " The user picked this language explicitly." } out, err := cl.InvokeModelFull(ctx, hb.InvokeParams{ ModelRef: h.modelRef, // 从 ListModels 里挑,别写死模型名 ContextID: m.ContextID, System: sys, Messages: []any{map[string]any{"role": "user", "content": m.Text}}, MaxTokens: 800, EstimatedOutputTokens: 300, }) if err != nil { return err } if _, err := cl.SendText(ctx, m.ContextID, out.Text, m.OriginatingPrincipal.ID); err != nil { return err } return cl.AckDelivery(ctx, m.ContextID, m.ChangeSeq) } // 语言变更在线推 NotifyContextStyle(角色风格 + 回复语言的**全量快照**,不是 patch)⇒ 整体覆盖缓存 func (h handler) OnContextStyle(c *hb.Conn, s hb.NotifyContextStyle) error { h.lang.Store(s.ContextID, s.ReplyLanguage) // nil = 语言锁解开,回你自己的默认语言 return nil } // 离线期间的变更不排队 ⇒ 重连时以 resync 的快照为准对账 func (h handler) OnResync(c *hb.Conn, r hb.ResyncContexts) error { for _, it := range r.Contexts { h.lang.Store(it.ContextID, it.ReplyLanguage) } return nil } ``` 按需查同样有:`cl.GetParticipants(ctx, contextID)` 的 `ReplyLanguage`;跨对话行动前 `cl.ListMyContexts(ctx, "")` 每项也带 `ReplyLanguage` —— 别拿 A 对话的语言去回 B 对话。 不读这两个字段的老 handler 行为逐字不变(只是仍会说错语言)。 ## Thinking is not the answer (SDK 0.51.0) 开了思维档的模型产出**思考**与**正文**两样东西,它们在同一次调用里回来。 ```go // 非流式:Text 只含正文,思考另走 Thinking(空 = 这次没思考) out, err := cl.InvokeModelFull(ctx, p) if err != nil { return err } if out.Finish == "incomplete" { // 被 MaxTokens 截断 —— 空的 / 半截的 Text 是**合法返回**: return h.handleTruncated(out) // 🔴 不得当成功答案落库,按你的策略续写 / 重试 / 明说没答完 } log.Printf("thinking: %s", out.Thinking) // 想看模型怎么想的读这里;常含被推翻的中间结论,别拼进答案 if out.Usage != nil && out.Usage.Reasoning != nil { log.Printf("reasoning tokens: %d", *out.Usage.Reasoning) // 已含在 Usage.Output 内、不参与计费;本地路径是估算值 } // 流式:聚合器只收 Phase != ChunkPhaseReasoning 的 delta;要思考就用 Full 变体 so, err := cl.StreamInvokeModelFull(ctx, p, func(ch hb.InvokeModelChunk) { switch ch.Phase { case hb.ChunkPhaseReasoning: showThinking(ch.Delta) // 回调仍收到**每一格**,包括 reasoning default: appendText(ch.Delta) // 空 / 认不出的 Phase 按正文处理 } if ch.IsFinal { if ch.Usage != nil && ch.Usage.Reasoning != nil { log.Printf("reasoning tokens: %d", *ch.Usage.Reasoning) // 0.51.0 起流式终止帧也带 } if ch.Finish == "incomplete" { /* 流式的截断判据同样是 Finish,不是「Text 空不空」*/ } } }) if err != nil { return err } // so.Text 只含正文;so.Thinking 是聚合起来的思考(空 = 这次没思考) ``` - 只要正文就用 `cl.StreamInvokeModel(ctx, p, onChunk)`(= `StreamInvokeModelFull(...).Text`)。 - 🔴 **在 `onChunk` 里自己拼字符串的必须自己按 `Phase` 分流** —— 不分的后果不是「多点噪声」: 高思维档的思考链会逐字复述提示词里的 JSON 模板,按「首个完整 JSON」解析就会截到模板占位符。 ## Image generation channel (SDK 0.55.0) `ListImageModels(ctx)` / `GenerateImage(ctx, modelRef, body map[string]any, contextID)` / `EditImage(ctx, modelRef, ImageEditRequest, contextID)` — a **pure passthrough** to the gateway's gpt-image models (by design, [skill §5.9](../../skills/harbor-agent-dev.skill.md)). ```go models, _ := c.ListImageModels(ctx) // read Rates first: medium 1024² ≈ 2.1M charged at r=200 r, err := c.GenerateImage(ctx, models[0].ModelRef, map[string]any{"prompt": "a red fox", "n": 1, "size": "1024x1024", "quality": "low", "output_format": "jpeg"}, contextID) // output_format 还可为 gif(+ frame_count / frame_duration_ms,只在 generations)或 svg(n=1)——取决于上游模型是否支持;响应的 output_format 以上游为准,先核再用。 png, _ := base64.StdEncoding.DecodeString(r.B64Images()[0]) // r.Response = upstream JSON verbatim; r.Usage.Charged = what the budget was debited e, err := c.EditImage(ctx, models[0].ModelRef, harboragent.ImageEditRequest{ Fields: map[string]string{"prompt": "put it on a beach", "input_fidelity": "high"}, Images: []harboragent.ImagePart{harboragent.ImagePartFromBytes("image/png", png, "in.png")}}, contextID) ``` - `body` goes through verbatim: **do not set `model`** (Harbor strips it anyway), `stream:true` ⇒ `image_stream_not_supported`, `n` > 4 (default cap) ⇒ `invalid_args`; everything else is validated upstream ⇒ `image_generation_failed`. - 🔴 **Harbor does not store the image**: the b64 lives only in this response — write it to the context file area yourself (`Files`) and send an `image` block. - New error fields: `(*Error).UpstreamStatus` (`*int`) / `UpstreamError` (`json.RawMessage`, upstream `{message,type,code,param}` verbatim) / `ModerationDetails` (`json.RawMessage`); nil on every other code. - Go's receive side (gorilla, no `SetReadLimit`) has no frame cap; nothing to change in the transport. ## Tool failures carry `errorMessage` (SDK 0.54.0) When `ExecuteTool` fails with `tool_invoke_timeout` / `agent_tool_timeout` (and other tool failures), Harbor now attaches a model-facing sentence next to the code — which tool, how long it waited, "don't pretend it ran". `(*Error).ErrorMessage` carries it (decoded on the same path as `AvailableModels`); `err.Error()` text is unchanged (match on `Code`, the sentence is just wording). Only Harbor builds from the 2026-09-12 review-fix round 2 onward send the key — older Harbors omit it, so `""` means "not given", never "no error". ## High-level - `MessageBuilder` — `b.Text("hi ").Mention(id, "张三")` → `cl.SendBuilt(ctx, cid, &b, "self")`. - `cl.SetStatus/ClearStatus` — progress badge. - `NewToolpackRouter()` — `r.Register(def, fn)`; embed in your handler; put `r.ManifestTools()` into the manifest. **SDK 0.53.0**: the `InvokeProvidedTool` you get carries Harbor's response window (15s by default; a frame `timeoutSec` overrides) — `t.Context()` is Done when Harbor stops waiting, `t.Deadline()` is the absolute cut-off. Pass `t.Context()` to every I/O you do inside the call; the SDK cancels it as soon as your handler returns (long jobs still go "ack now, `SendMessage` later" on your own context). **SDK 0.54.0**: that window's parent is now the connection's lifetime context (new `conn.Context()`, Done when the connection closes) instead of `context.Background()` — if Harbor drops the connection your handler is cancelled at once rather than running out the full 15s with nobody left to receive the result. Same as C#, which links the connection-level `ct` into its window CTS. - `NewChoiceBroker()` — `broker.Ask(...)`; call `broker.TryHandle(m)` at the top of `OnDeliverMessage`. Choice invalidation rules (SDK 0.52.0: `selectMode` / `reentrant`) are declared with `broker.AskWith(..., ChoiceMode{SelectMode, Reentrant})` — `Ask` keeps its old signature. This is the Go spelling of what C# exposes as optional parameters on `AskAsync(..., selectMode:, reentrant:)` and Python on `ask(..., select_mode=, reentrant=)`; the three are capability-equivalent, only the shape differs. - `NewFileHandlerAgent(cfg)` — file-handler contract (§10): declares `summarize`, parses `aside.fileRef`, auto-leaves. - `cl.OpenPythonSession/OpenPgSession/OpenFileSession(ctx, contextID, ...)` — **Session** entity: hides the key, direct-connects to the component keyed port. `s.Exec(code)` / `s.Install(pkgs...)` / `s.RunFile(path)` (python), `s.PyenvList/Create/...` (preset mgmt), `s.Query(sql, params, mode)` (pg); file bytes are **streaming-first**: `s.OpenRead(ctx, relpath) io.ReadCloser` / `s.OpenWrite(ctx, relpath) io.WriteCloser` (juicefs-bytes plane), with `s.Download(relpath)` (read-side byte convenience, capped at `s.MaxInMemoryBytes` default 8MB) / `s.Upload(relpath, data)` (write-side: **no size cap** — sends the caller-held bytes directly; use `OpenWrite` for large files); `s.Renew/Revoke/Close`, `s.ExpiresAt`. - `cl.Files(contextID, "self")` — **unified file facade** (context area metadata + files-agent `file.*`): `List/Delete/Stat/Move` (context, builtin `context.file.*`); file **content** is streaming-first over the harbor-agent WS **Binary stream primitive** (`ContextFileRead`/`ContextFileWrite` control frames on the same connection) — `f.OpenRead(ctx, name) io.ReadCloser` / `f.OpenWrite(ctx, name, mimeType) io.WriteCloser`, with `f.Read/Write(name, data)` as byte convenience wrappers; plus `Fetch/Mkdir/Compress/Extract/CrossCopy/...` + `AgentTool(name,args)` (files-agent). See SPEC-highlevel §9. - `cl.OpenUserView(ctx, contextID, title, url, "self", style, dur)` — ui.url.open (`proxyAgentId="self"`). ### Large files: prefer streaming, don't buffer whole blobs The **read-side** byte-convenience wrappers (`Files.Read` / `Session.Download`) stream internally but buffer the result in memory, capped at `MaxInMemoryBytes` (default **8 MB**; `<=0` falls back to the default). Exceeding it returns an `*Error{Code: "file_too_large_use_stream"}` — it **never silently truncates**. The **write-side** wrappers (`Files.Write` / `Session.Upload`) have **no size cap** — the caller already holds the full `[]byte`, so they just stream it out. For large files (especially writes) use the streaming API directly: ```go // context area: stream a local file up (any size, never buffered whole) f := cl.Files(contextID, "self") src, _ := os.Open("local-large.bin") defer src.Close() wc, err := f.OpenWrite(ctx, "large.bin", "application/octet-stream") if err != nil { /* ... */ } if _, err := io.Copy(wc, src); err != nil { _ = wc.Close(); /* ... */ } if err := wc.Close(); err != nil { /* Close() surfaces the ContextFileWrite control frame's outcome */ } // context area: stream a read rc, err := f.OpenRead(ctx, "large.bin") if err != nil { /* ... */ } defer rc.Close() io.Copy(localOut, rc) // session area (juicefs-bytes) — same shape on Session sess, _ := cl.OpenFileSession(ctx, contextID, "") rc2, _ := sess.OpenRead(ctx, "some/relpath.bin") defer rc2.Close() ``` Raise `f.MaxInMemoryBytes` / `sess.MaxInMemoryBytes` only to relax the **read-side** convenience cap; write-side convenience has no cap and streaming itself has no size limit. Runnable examples ship inside the Go source package under `examples/` (`echo`, `filehandler`, `ctxfilestream`, `permgate`).