# Harbor Agent SDK — C# `Harbor.Agent.Sdk` (.NET 10, pure BCL: `HttpListener` + `System.Net.WebSockets`) — build a Harbor agent in C#. See [`../SPEC.md`](../SPEC.md) / [`../SPEC-highlevel.md`](../SPEC-highlevel.md). ```bash dotnet nuget add source -n harbor-local # the .nupkg from https://ai.nti56.com/dev/harbor/sdk// dotnet add package Harbor.Agent.Sdk -v ``` Install details: [`../README.md`](../README.md) (section 「获取与安装」). ## Quick start ```csharp using Harbor.Agent.Sdk; class EchoHandler : AgentHandlerBase { private readonly Dedup _dedup = new(); public override async Task OnDeliverMessageAsync(AgentConnection conn, DeliverMessage m, CancellationToken ct) { var client = new AgentClient(conn); if (!_dedup.Begin(m.ContextId, m.ChangeSeq)) { await client.AckDeliveryAsync(m.ContextId, m.ChangeSeq, ct); return; } await client.SendTextAsync(m.ContextId, "echo: " + m.Text, m.OriginatingPrincipal.Id, ct); await _dedup.AckProcessedAsync(client, m.ContextId, m.ChangeSeq, ct); } } var agent = new HarborAgent(new HarborAgentOptions { Token = "shared-secret", // static-token; "" = accept any (dev) Path = "/agent", Host = "+", Port = 7501, Manifest = new Manifest { DisplayName = "小李", Version = 1, IsMentionable = true }, Handler = new EchoHandler(), }); await agent.RunAsync(); ``` ## 成员生命周期 / 重连对账 `AgentHandlerBase` 另有两个回调(基类 no-op,旧 handler 不改即兼容): ```csharp class MyHandler : AgentHandlerBase { // #22:context 成员增量(join / leave / context-closed);在线直投、离线重连补投 public override async Task OnContextLifecycleAsync(AgentConnection conn, ContextLifecycle e, CancellationToken ct) { if (e.Event == "context-closed") { _cache.DropContext(e.ContextId); return; } if (e.Event == "participant-left") { _cache.DropParticipant(e.ContextId, e.ParticipantId); return; } // participant-joined if (e.IsSelf) // 自身被加入 → 拉一次全员名册 await new AgentClient(conn).GetParticipantsAsync(e.ContextId, ct); } // #23:(重)连接后下发当前在场 context 列表 → 对账,清理本地记着但不在列表的 public override Task OnResyncAsync(AgentConnection conn, ResyncContexts r, CancellationToken ct) { _cache.ReconcileContexts(r.Contexts.Select(c => c.ContextId)); return Task.CompletedTask; } } ``` ## 回复语言:跟着这场对话说话(`ReplyLanguage`,SDK 0.51.0) 每条投递都带 `ReplyLanguage`(BCP-47,如 `en-US`;**`null` = 未锁定** ⇒ 用你自己的默认,别自己去检测用户语言) 与 `ReplyLanguageSource`(`ReplyLanguageSources.Explicit` = 用户亲口选的、尤其要尊重; `ReplyLanguageSources.Detected` = Harbor 按前几条用户消息检测的,同样要跟随)。 🔴 **Harbor 的主模型就是按这一位回话的** —— 你不跟,用户看到的就是同一场对话里两种语言并排。 它是**对话级的锁**,不是「这条消息用什么语言写的」;Harbor 内部「仅此一轮」的临时切换不出现在这一位上。 ```csharp class MyHandler : AgentHandlerBase { private readonly ConcurrentDictionary _lang = new(); // contextId → 当前语言锁 public override async Task OnDeliverMessageAsync(AgentConnection conn, DeliverMessage m, CancellationToken ct) { var client = new AgentClient(conn); var lang = m.ReplyLanguage ?? "zh-CN"; // null ⇒ 回落到你自己的默认 var sys = $"Reply in {lang}."; if (m.ReplyLanguageSource == ReplyLanguageSources.Explicit) sys += " The user picked this language explicitly."; var r = await client.InvokeModelFullAsync(new InvokeModelParams { ModelRef = _modelRef, // 从 ListModelsAsync 里挑,别写死模型名 ContextId = m.ContextId, System = sys, Messages = [new { role = "user", content = m.Text }], EstimatedOutputTokens = 300, MaxTokens = 800, }, ct); await client.SendTextAsync(m.ContextId, r.Text, m.OriginatingPrincipal.Id, ct); await client.AckDeliveryAsync(m.ContextId, m.ChangeSeq, ct); } // 语言变更在线推这一帧(角色风格 + 回复语言的**全量快照**,不是 patch)⇒ 整体覆盖你的缓存 public override Task OnContextStyleAsync(AgentConnection conn, NotifyContextStyle s, CancellationToken ct) { _lang[s.ContextId] = s.ReplyLanguage; // null = 语言锁解开,回你自己的默认语言 return Task.CompletedTask; } // 离线期间的变更不排队 ⇒ 重连时以 resync 的快照为准对账 public override Task OnResyncAsync(AgentConnection conn, ResyncContexts r, CancellationToken ct) { foreach (var c in r.Contexts) _lang[c.ContextId] = c.ReplyLanguage; return Task.CompletedTask; } } ``` 按需查同样有:`(await client.GetParticipantsAsync(cid, ct)).ReplyLanguage`;跨对话行动前 `ListMyContextsAsync()` 每项也带 `ReplyLanguage` —— 别拿 A 对话的语言去回 B 对话。 不读这两个键的老 handler 行为逐字不变(只是仍会说错语言)。 ## 调模型:思考不是正文(SDK 0.51.0) 开了思维档的模型产出**思考**与**正文**两样东西,它们在同一次调用里回来。 ```csharp // 非流式:Text 只含正文,思考另走 Thinking(null = 这次没思考) var r = await client.InvokeModelFullAsync(p, ct); if (r.Finish == "incomplete") // 被 MaxTokens 截断 —— 空的 / 半截的 Text 是**合法返回**: { // 🔴 不得当成功答案落库,按你的策略续写 / 重试 / 明说没答完 await HandleTruncatedAsync(r, ct); return; } _log.Debug("thinking: {T}", r.Thinking); // 想看模型怎么想的读这里;常含被推翻的中间结论,别拼进答案 Use(r.Text); _log.Debug("reasoning tokens: {N}", r.Usage?.Reasoning); // 已含在 Usage.Output 内、不参与计费;本地路径是估算值 // 流式:聚合器只收 Phase != Reasoning 的 delta;要思考就用 Full 变体 var (text, thinking) = await client.InvokeModelStreamFullAsync(p, c => { if (c.Phase == ChunkPhases.Reasoning) ShowThinkingBadge(c.Delta); // 回调仍收到**每一格** else if (!string.IsNullOrEmpty(c.Delta)) Append(c.Delta); // 空 / 认不出的 Phase 按正文处理 if (c.IsFinal) _log.Debug("reasoning tokens: {N}", c.Usage?.Reasoning); // 0.51.0 起流式终止帧也带 }, ct); ``` - 只要正文就用 `InvokeModelStreamTextAsync`(= `InvokeModelStreamFullAsync(...).Text`)。 - 🔴 **自己遍历 `StreamInvokeModelAsync` 拼字符串的必须自己按 `Phase` 分流** —— 不分的后果不是「多点噪声」: 高思维档的思考链会逐字复述提示词里的 JSON 模板,按「首个完整 JSON」解析就会截到模板占位符。 - 流式的截断判据同样是终止 chunk 的 `Finish`,不是「Text 空不空」。 ## 图像生成通道(SDK 0.55.0) `ListImageModelsAsync()` / `GenerateImageAsync(modelRef, JsonElement body, Guid? contextId = null)` / `EditImageAsync(modelRef, ImageEditRequest req, Guid? contextId = null)` —— gateway gpt-image 系的**纯透传**(2026-09-12,[skill §5.9](../../skills/harbor-agent-dev.skill.md))。 ```csharp var models = await client.ListImageModelsAsync(); // 先看 Rates:medium 1024² ≈ 210 万计费量(r=200) var body = JsonSerializer.SerializeToElement(new { prompt = "一只红狐", n = 1, size = "1024x1024", quality = "low", output_format = "jpeg" }); // output_format 还可为 gif(+ frame_count / frame_duration_ms,只在 generations)或 svg(n=1)——取决于上游模型是否支持;响应的 output_format 以上游为准,先核再用。 var r = await client.GenerateImageAsync(models[0].ModelRef, body, contextId: ctxId); var png = Convert.FromBase64String(r.B64Images[0]); // r.Response = 上游 JSON 原样;r.Usage.Charged = 记进预算的量 var e = await client.EditImageAsync(models[0].ModelRef, new ImageEditRequest( new Dictionary { ["prompt"] = "换成海边背景", ["input_fidelity"] = "high" }, [ImagePart.FromBytes("image/png", png, "in.png")]), contextId: ctxId); ``` - `body` 原样透传:**别放 `model`**(Harbor 也会删)、`stream:true` ⇒ `image_stream_not_supported`、`n` > 4(缺省)⇒ `invalid_args`;其余由上游 4xx 报 ⇒ `image_generation_failed`。 - 🔴 **Harbor 不存图**:b64 只在响应里,要给用户看就自己写文件区(`Files`)再发 `image` 块。 - 新错误字段:`HarborAgentException.UpstreamStatus`(`int?`)/ `UpstreamError`(`JsonElement?`,上游 `{message,type,code,param}` 原样)/ `ModerationDetails`(`JsonElement?`);其余码恒 `null`。 - C# 收侧本就无帧上限(8 KB 循环累积),无需改传输层。 ## 工具失败带 `errorMessage`(SDK 0.54.0) `ExecuteToolAsync` 回 `tool_invoke_timeout` / `agent_tool_timeout` 等工具失败时,Harbor 随码附一句模型面的话(哪件工具、等了多久、别假装执行过)。 `HarborAgentException.ErrorMessage`(`string?`)承载它,与 `AvailableModels` 同一条解码路径;`ex.Message` 文本不变(匹配靠 `Code`,这句只是话术)。 ⚠️ **只有 Harbor 2026-09-12 之后的构建才发这个键**,老 Harbor 缺键 ⇒ `null` = 没给,不是「没有错误」。 ## High-level - `MessageBuilder` — `b.Text("hi ").Mention(id, "张三")` → `client.SendBuiltAsync(cid, b)`. - `client.SetStatusAsync / ClearStatusAsync` — progress badge (extension methods). - `ToolpackRouter : AgentHandlerBase` — `Register(def, fn)`; subclass for business; `ManifestTools()`. **SDK 0.53.0**:交给你的 `InvokeProvidedToolRequest` 上挂着 Harbor 的响应窗口(默认 15s;帧带 `timeoutSec` 则按帧)—— `t.CancellationToken`(Harbor 放弃等待即取消;`OnInvokeProvidedToolAsync` 的 `ct` 参数仍是连接级的)、`t.Deadline`、`t.EffectiveTimeout`。 窗口内的一切 I/O 都传 `t.CancellationToken`;处理器一返回 SDK 就取消它(长任务仍走「秒回已受理 + 后台 `SendMessage`」,后台用自己的 token)。 **SDK 0.54.0**:C# 这里没变 —— 窗口 CTS 本就 link 了连接级 `ct`(连接掉了窗口同时取消);本版是 Go 补齐到同样行为(`conn.Context()`),三语言对齐。 - `ChoiceBroker` — `await broker.AskAsync(...)`; call `broker.TryHandle(m)` at the top of `OnDeliverMessageAsync`. Choice 失效规则(SDK 0.52.0:`selectMode` / `reentrant`)走 `AskAsync(..., selectMode: "single"|"multi", reentrant: false|true)` 的可选参数 —— 既有调用逐字不变。Go 的拼法是新方法 `AskWith(..., ChoiceMode{SelectMode, Reentrant})`,Python 是 `ask(..., select_mode=, reentrant=)`;三语言能力等价、只是形态不同。 ⚠️ `multi` 要等前端支持后才能用(在役前端见到 `selectMode != "single"` 会把整块静默丢掉)。 - `FileHandlerAgent : ToolpackRouter` — file-handler contract (§10). - `client.OpenPythonSessionAsync/OpenPgSessionAsync/OpenFileSessionAsync(contextId, ...)` — **Session** entity: hides the key, direct-connects to the component keyed port. `s.ExecAsync(code)` / `s.InstallAsync(pkgs)` / `s.RunFileAsync(path)` (python), `s.PyenvListAsync/CreateAsync/...` (preset mgmt), `s.QueryAsync(sql, params, mode)` (pg); file bytes are **streaming-first**: `s.OpenReadStreamAsync(relpath)` / `s.OpenWriteStreamAsync(relpath)` → `Stream` (juicefs-bytes plane), with `s.DownloadAsync(relpath)` (read-side byte convenience, capped at `s.MaxInMemoryBytes` default 8MB) / `s.UploadAsync(relpath, bytes)` (write-side: **no size cap** — sends the caller-held bytes directly; use `OpenWriteStreamAsync` for large files); `s.RenewAsync/RevokeAsync`, `s.ExpiresAt`. - `client.Files(contextId)` — **unified file facade**: `ListAsync/DeleteAsync/StatAsync/MoveAsync` (context area metadata, builtin `context.file.*`); file **content** is streaming-first over the harbor-agent WS **Binary stream primitive** (`ContextFileRead`/`ContextFileWrite` control frames on the same connection, no HTTP byte plane) — `OpenReadStreamAsync(name)` / `OpenWriteStreamAsync(name, mimeType?)` → `Stream`, with `ReadAsync/WriteAsync(name, byte[])` as byte convenience wrappers; plus `FetchAsync/MkdirAsync/CompressAsync/ExtractAsync/CrossCopyAsync/...` + `AgentToolAsync(name,args)` (files-agent). See SPEC-highlevel §9. - `client.OpenUserViewAsync(contextId, title, url, "self", style, dur)` — ui.url.open. ### 大文件:优先流式,别整块 base64 `Files`/`Session` 的**读侧**字节便利包装(`ReadAsync`/`DownloadAsync`)内部先流式收取、再在内存里攒成 `byte[]`——超过 `MaxInMemoryBytes`(默认 **8 MB**)会抛 `HarborAgentException("file_too_large_use_stream")`,**不会静默截断**。**写侧**便利包装(`WriteAsync`/`UploadAsync`)**不校大小**——调用方已持有全量 bytes,直接流式发送、无此上限。大文件(尤其是写)请直接用流式 API: ```csharp // context 区大文件:流式写(本地文件 → context 文件区,任意大小、不整体驻内存) await using (var src = File.OpenRead("local-large.bin")) await using (var dst = await client.Files(contextId).OpenWriteStreamAsync("large.bin", "application/octet-stream")) await src.CopyToAsync(dst); // dst 在 await using 结束时 Dispose → 完成 PUT,HTTP 失败会在此处抛出 // context 区大文件:流式读 await using var rs = await client.Files(contextId).OpenReadStreamAsync("large.bin"); await using var localOut = File.Create("downloaded.bin"); await rs.CopyToAsync(localOut); // session 区(juicefs-bytes)同款:OpenWriteStreamAsync / OpenReadStreamAsync var session = await client.OpenFileSessionAsync(contextId); await using var sessRead = await session.OpenReadStreamAsync("some/relpath.bin"); ``` 调大 `MaxInMemoryBytes`(如 `client.Files(contextId).MaxInMemoryBytes = 32 * 1024 * 1024`)只是放宽**读侧**便利包装的上限;写侧便利本就无上限,流式路径本身也没有大小限制。 The `.nupkg` ships the library only (no example project). The Quick start above is a complete echo agent; fuller runnable examples (echo / file handler / context file streaming / permission gate) are in the `examples/` directory of the Go source package and serve as a reference — or ask the Harbor team for the C# `EchoAgent` sample.