dsh-codebuddy-sdk 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Alexandre@AI
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,71 @@
1
- # Temporary Holding Version
1
+ <p align="center">
2
+ <img src="assets/readme/hero.svg" alt="dsh-codebuddy-sdk — CodeBuddy as a DeepSeek Harness LLM provider" width="100%">
3
+ </p>
2
4
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
5
+ # dsh-codebuddy-sdk
6
+
7
+ Registers **CodeBuddy** (Tencent Agent SDK) as an LLM provider adapter for DeepSeek Harness (`ctx.llm`), so the Harness can run a CodeBuddy model while keeping its own tools, session, and UI.
8
+
9
+ > Port of [pi-codebuddy-sdk](https://github.com/RetiredPhysicist/pi-plugins/tree/main/packages/pi-codebuddy-sdk).
10
+
11
+ [English](README.md) · [中文](README.zh.md)
12
+
13
+ ## What it does
14
+
15
+ - Advertises the CLI's own model catalog on the `codebuddy` provider route
16
+ - Streams text, reasoning, and tool calls into the Harness `StreamChunk` protocol
17
+ - Bridges Harness tools to CodeBuddy through an in-process SDK MCP server, so the Harness still executes every tool
18
+ - Re-imports the Harness history into a CodeBuddy session file and resumes it per step, which is what makes multi-turn context survive the per-step CLI lifetime
19
+ - Reaps the CLI child process on every completion path, including model discovery and aborts
20
+
21
+ ## Quick start
22
+
23
+ ```sh
24
+ dsh plugin add dsh-codebuddy-sdk
25
+ ```
26
+
27
+ Requires the `codebuddy` CLI on `PATH`, signed in (`codebuddy` works standalone).
28
+
29
+ ```yaml
30
+ - id: codebuddy
31
+ name: dsh-codebuddy-sdk
32
+ config:
33
+ provider: codebuddy # provider route (default codebuddy)
34
+ model: hy3-preview-agent-ioa # default model id (default: CLI's own default)
35
+ # pathToCodebuddyCode: /opt/homebrew/bin/codebuddy
36
+ # permissionMode: bypassPermissions
37
+ ```
38
+
39
+ Pick the model with the Harness model selector; `codebuddy/<id>` routes through this adapter.
40
+
41
+ ## Configuration
42
+
43
+ | key | default | meaning |
44
+ |---|---|---|
45
+ | `provider` | `codebuddy` | provider route registered with `ctx.llm` |
46
+ | `model` | CLI default | model id sent when the request names none |
47
+ | `pathToCodebuddyCode` | `PATH` lookup | explicit CLI path |
48
+ | `cwd` | process cwd | working directory for the CLI |
49
+ | `permissionMode` | `bypassPermissions` | CLI permission mode; the Harness owns tool approval |
50
+ | `contextWindow` | estimated | context window override for every model |
51
+ | `maxTokens` | estimated | output cap override for every model |
52
+
53
+ ## Privacy
54
+
55
+ - Talks to the local `codebuddy` CLI only; no extra network hop.
56
+ - No credentials are read or stored; the CLI's own auth is reused.
57
+ - Tool arguments and results pass between the Harness and the CLI over the local control protocol.
58
+
59
+ ## Development
60
+
61
+ ```bash
62
+ npm install
63
+ npm run typecheck
64
+ npm run test:ci # unit tests, no CLI or credentials needed
65
+ npm run test:integration # opt-in, needs a signed-in codebuddy CLI
66
+ npm run build
67
+ ```
68
+
69
+ ## License
70
+
71
+ MIT
package/README.zh.md ADDED
@@ -0,0 +1,71 @@
1
+ <p align="center">
2
+ <img src="assets/readme/hero.zh.svg" alt="dsh-codebuddy-sdk —— 把 CodeBuddy 接进 DeepSeek Harness" width="100%">
3
+ </p>
4
+
5
+ # dsh-codebuddy-sdk
6
+
7
+ 把 **CodeBuddy**(腾讯 Agent SDK)注册为 DeepSeek Harness 的 LLM provider 适配器(`ctx.llm`):模型走 CodeBuddy,工具、会话、界面仍由 Harness 掌管。
8
+
9
+ > 由 [pi-codebuddy-sdk](https://github.com/RetiredPhysicist/pi-plugins/tree/main/packages/pi-codebuddy-sdk) 移植。
10
+
11
+ [English](README.md) · [中文](README.zh.md)
12
+
13
+ ## 功能
14
+
15
+ - 在 `codebuddy` 路由上暴露 CLI 自己的模型目录
16
+ - 把文本、思维链、工具调用转成 Harness 的 `StreamChunk` 协议
17
+ - 通过进程内 SDK MCP server 把 Harness 工具桥接给 CodeBuddy,工具仍由 Harness 执行
18
+ - 每步把 Harness 历史写入 CodeBuddy 会话文件并 resume,因此多轮上下文能在 CLI 的「每步一个进程」模型下保留
19
+ - 所有结束路径(包括模型发现与中断)都会回收 CLI 子进程
20
+
21
+ ## 快速开始
22
+
23
+ ```sh
24
+ dsh plugin add dsh-codebuddy-sdk
25
+ ```
26
+
27
+ 需要 `codebuddy` CLI 在 `PATH` 上且已登录(即终端里 `codebuddy` 能正常用)。
28
+
29
+ ```yaml
30
+ - id: codebuddy
31
+ name: dsh-codebuddy-sdk
32
+ config:
33
+ provider: codebuddy # provider 路由(默认 codebuddy)
34
+ model: hy3-preview-agent-ioa # 默认模型 ID(默认用 CLI 自带默认值)
35
+ # pathToCodebuddyCode: /opt/homebrew/bin/codebuddy
36
+ # permissionMode: bypassPermissions
37
+ ```
38
+
39
+ 在 Harness 的模型选择器里选 `codebuddy/<id>` 即可走这个适配器。
40
+
41
+ ## 配置
42
+
43
+ | 键 | 默认 | 说明 |
44
+ |---|---|---|
45
+ | `provider` | `codebuddy` | 注册到 `ctx.llm` 的路由名 |
46
+ | `model` | CLI 默认 | 请求未指定模型时发送的模型 ID |
47
+ | `pathToCodebuddyCode` | 从 `PATH` 查找 | 显式指定 CLI 路径 |
48
+ | `cwd` | 进程 cwd | CLI 工作目录 |
49
+ | `permissionMode` | `bypassPermissions` | CLI 权限模式;工具审批由 Harness 负责 |
50
+ | `contextWindow` | 估算值 | 覆盖所有模型的上下文窗口 |
51
+ | `maxTokens` | 估算值 | 覆盖所有模型的输出上限 |
52
+
53
+ ## 隐私
54
+
55
+ - 只与本地 `codebuddy` CLI 通信,不额外发网络请求
56
+ - 不读取、不存储任何凭据(复用 CLI 自身认证)
57
+ - 工具参数与结果只在 Harness 与 CLI 的本地控制协议之间传递
58
+
59
+ ## 开发
60
+
61
+ ```bash
62
+ npm install
63
+ npm run typecheck
64
+ npm run test:ci # 单元测试,不需要 CLI 或凭据
65
+ npm run test:integration # 可选,需要已登录的 codebuddy CLI
66
+ npm run build
67
+ ```
68
+
69
+ ## License
70
+
71
+ MIT
@@ -0,0 +1,7 @@
1
+ # Plugin bundle for dsh-codebuddy-sdk.
2
+ # Registers the CodeBuddy provider adapter into ctx.llm.
3
+ # Multi-turn history, tool calls, and streaming are implemented; the CLI is
4
+ # invoked per Harness step and resumed from an imported session file.
5
+ - insert:
6
+ - id: codebuddy
7
+ name: 'dsh-codebuddy-sdk'
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Harness → CodeBuddy conversion.
3
+ *
4
+ * The Harness keeps tool arguments as raw JSON strings and tool results as
5
+ * first-class `tool`-role messages; CodeBuddy expects Anthropic-shaped
6
+ * `tool_use`/`tool_result` blocks in `user`/`assistant` turns.
7
+ */
8
+ import type { GenerateOptions, ToolSchema } from '@deepseek-ai/dsh-llm';
9
+ type RequestMessage = GenerateOptions['messages'][number];
10
+ export declare const PROVIDER_ID = "codebuddy";
11
+ export declare const MCP_SERVER_NAME = "custom_tools";
12
+ export declare const MCP_TOOL_PREFIX = "mcp__custom_tools__";
13
+ export type AnthropicContentBlock = {
14
+ type: 'text';
15
+ text: string;
16
+ } | {
17
+ type: 'thinking';
18
+ thinking: string;
19
+ signature: string;
20
+ } | {
21
+ type: 'tool_use';
22
+ id: string;
23
+ name: string;
24
+ input: unknown;
25
+ } | {
26
+ type: 'tool_result';
27
+ tool_use_id: string;
28
+ content: string;
29
+ is_error?: boolean;
30
+ } | {
31
+ type: 'image';
32
+ source: {
33
+ type: 'base64';
34
+ media_type: string;
35
+ data: string;
36
+ };
37
+ };
38
+ export interface AnthropicMessage {
39
+ role: 'user' | 'assistant';
40
+ content: string | AnthropicContentBlock[];
41
+ }
42
+ export declare function sanitizeToolId(id: string, cache: Map<string, string>): string;
43
+ export declare function mapHarnessToolNameToSdk(name: string, custom?: Map<string, string>): string;
44
+ /**
45
+ * Convert one request history into the Anthropic-shaped message array the
46
+ * CodeBuddy CLI accepts for session import.
47
+ */
48
+ export declare function convertMessages(messages: readonly RequestMessage[], customToolNames?: Map<string, string>): {
49
+ messages: AnthropicMessage[];
50
+ sanitizedIds: Map<string, string>;
51
+ };
52
+ export declare function lastUserText(messages: readonly RequestMessage[]): string;
53
+ export declare function toolSchemasToNames(tools: readonly ToolSchema[] | undefined): string[];
54
+ export {};
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Harness → CodeBuddy conversion.
3
+ *
4
+ * The Harness keeps tool arguments as raw JSON strings and tool results as
5
+ * first-class `tool`-role messages; CodeBuddy expects Anthropic-shaped
6
+ * `tool_use`/`tool_result` blocks in `user`/`assistant` turns.
7
+ */
8
+ import { pascalCase } from 'change-case';
9
+ export const PROVIDER_ID = 'codebuddy';
10
+ export const MCP_SERVER_NAME = 'custom_tools';
11
+ export const MCP_TOOL_PREFIX = `mcp__${MCP_SERVER_NAME}__`;
12
+ const HARNESS_TO_SDK_TOOL_NAME = {
13
+ read: 'Read',
14
+ write: 'Write',
15
+ edit: 'Edit',
16
+ bash: 'Bash',
17
+ };
18
+ export function sanitizeToolId(id, cache) {
19
+ const existing = cache.get(id);
20
+ if (existing)
21
+ return existing;
22
+ const clean = id.replace(/[^a-zA-Z0-9_-]/g, '_');
23
+ cache.set(id, clean);
24
+ return clean;
25
+ }
26
+ export function mapHarnessToolNameToSdk(name, custom) {
27
+ if (!name)
28
+ return '';
29
+ const normalized = name.toLowerCase();
30
+ const mapped = custom?.get(name) ?? custom?.get(normalized);
31
+ if (mapped)
32
+ return mapped;
33
+ if (HARNESS_TO_SDK_TOOL_NAME[normalized])
34
+ return HARNESS_TO_SDK_TOOL_NAME[normalized];
35
+ return pascalCase(name);
36
+ }
37
+ function blocksOf(content) {
38
+ const out = [];
39
+ for (const block of content) {
40
+ switch (block.type) {
41
+ case 'text':
42
+ if (block.text)
43
+ out.push({ type: 'text', text: block.text });
44
+ break;
45
+ case 'reasoning':
46
+ break;
47
+ case 'image':
48
+ break;
49
+ case 'tool-call':
50
+ out.push({ type: 'tool_use', id: block.id, name: block.name, input: parseArguments(block.arguments) });
51
+ break;
52
+ default:
53
+ break;
54
+ }
55
+ }
56
+ return out;
57
+ }
58
+ function parseArguments(raw) {
59
+ if (!raw)
60
+ return {};
61
+ try {
62
+ return JSON.parse(raw);
63
+ }
64
+ catch {
65
+ return {};
66
+ }
67
+ }
68
+ /**
69
+ * Convert one request history into the Anthropic-shaped message array the
70
+ * CodeBuddy CLI accepts for session import.
71
+ */
72
+ export function convertMessages(messages, customToolNames) {
73
+ const out = [];
74
+ const sanitizedIds = new Map();
75
+ const pendingToolUse = new Set();
76
+ const toolNames = new Map();
77
+ for (const message of messages) {
78
+ if (message.role === 'system')
79
+ continue;
80
+ if (message.role === 'user') {
81
+ const content = blocksOf(message.content).filter((block) => block.type === 'text' || block.type === 'image');
82
+ if (content.length > 0)
83
+ out.push({ role: 'user', content });
84
+ continue;
85
+ }
86
+ if (message.role === 'assistant') {
87
+ const content = blocksOf(message.content).map((block) => {
88
+ if (block.type !== 'tool_use')
89
+ return block;
90
+ const id = sanitizeToolId(block.id, sanitizedIds);
91
+ toolNames.set(id, block.name);
92
+ pendingToolUse.add(id);
93
+ return { ...block, id, name: mapHarnessToolNameToSdk(block.name, customToolNames) };
94
+ });
95
+ if (content.length > 0)
96
+ out.push({ role: 'assistant', content });
97
+ continue;
98
+ }
99
+ if (message.role === 'tool') {
100
+ const callId = message.source.kind === 'tool' ? message.source.callId : '';
101
+ const id = sanitizeToolId(callId, sanitizedIds);
102
+ pendingToolUse.delete(id);
103
+ const text = message.content
104
+ .filter((block) => block.type === 'text')
105
+ .map((block) => block.text)
106
+ .join('\n');
107
+ const result = {
108
+ type: 'tool_result',
109
+ tool_use_id: id,
110
+ content: text,
111
+ ...message.isError === true ? { is_error: true } : {},
112
+ };
113
+ const previous = out.at(-1);
114
+ if (previous?.role === 'user' && Array.isArray(previous.content))
115
+ previous.content.push(result);
116
+ else
117
+ out.push({ role: 'user', content: [result] });
118
+ }
119
+ }
120
+ // A history cut between a tool call and its result cannot be replayed by the
121
+ // CLI; synthesize the missing results so the request stays valid.
122
+ if (pendingToolUse.size > 0) {
123
+ const results = [...pendingToolUse].map((id) => ({
124
+ type: 'tool_result',
125
+ tool_use_id: id,
126
+ content: '[no tool result recorded]',
127
+ is_error: true,
128
+ }));
129
+ const previous = out.at(-1);
130
+ if (previous?.role === 'user' && Array.isArray(previous.content))
131
+ previous.content.push(...results);
132
+ else
133
+ out.push({ role: 'user', content: results });
134
+ }
135
+ return { messages: out, sanitizedIds };
136
+ }
137
+ export function lastUserText(messages) {
138
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
139
+ const message = messages[index];
140
+ if (message?.role !== 'user')
141
+ continue;
142
+ const text = message.content
143
+ .filter((block) => block.type === 'text')
144
+ .map((block) => block.text)
145
+ .join('\n');
146
+ if (text)
147
+ return text;
148
+ }
149
+ return '';
150
+ }
151
+ export function toolSchemasToNames(tools) {
152
+ return (tools ?? []).map((tool) => tool.name);
153
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * CodeBuddy (Tencent Agent SDK) as a DeepSeek Harness LLM provider.
3
+ *
4
+ * The Harness owns tool execution, so one conversation is driven one step at a
5
+ * time: a `stream()` call that ends on a tool call returns `tool-calls`, the
6
+ * Harness runs the tool, and the next `stream()` call delivers the result.
7
+ *
8
+ * One CodeBuddy CLI query spans the whole conversation. The MCP handlers it
9
+ * invokes stay pending across steps; the next step resolves them with the
10
+ * Harness's real tool results, which lets the CLI continue the same turn. Only
11
+ * the first step sends a prompt — later steps are continuations of it.
12
+ */
13
+ import type { Context } from '@deepseek-ai/cordis';
14
+ import z from '@deepseek-ai/schemastery';
15
+ export interface Config {
16
+ /** Provider route advertised to the harness (default `codebuddy`). */
17
+ provider?: string;
18
+ /** Default model id (default `codebuddy`). */
19
+ model?: string;
20
+ /** Path to the CodeBuddy CLI when it is not on `PATH`. */
21
+ pathToCodebuddyCode?: string;
22
+ /** Working directory for the CLI; defaults to the process cwd. */
23
+ cwd?: string;
24
+ /** Permission mode handed to the CLI. Defaults to `bypassPermissions`. */
25
+ permissionMode?: string;
26
+ /** Context window override for every model. */
27
+ contextWindow?: number;
28
+ /** Max output tokens override for every model. */
29
+ maxTokens?: number;
30
+ }
31
+ export declare const Config: z<Config>;
32
+ export declare const name = "codebuddy";
33
+ export declare const inject: string[];
34
+ export declare function apply(ctx: Context, config: Config): void;
package/dist/index.js ADDED
@@ -0,0 +1,220 @@
1
+ /**
2
+ * CodeBuddy (Tencent Agent SDK) as a DeepSeek Harness LLM provider.
3
+ *
4
+ * The Harness owns tool execution, so one conversation is driven one step at a
5
+ * time: a `stream()` call that ends on a tool call returns `tool-calls`, the
6
+ * Harness runs the tool, and the next `stream()` call delivers the result.
7
+ *
8
+ * One CodeBuddy CLI query spans the whole conversation. The MCP handlers it
9
+ * invokes stay pending across steps; the next step resolves them with the
10
+ * Harness's real tool results, which lets the CLI continue the same turn. Only
11
+ * the first step sends a prompt — later steps are continuations of it.
12
+ */
13
+ import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
14
+ import { query } from '@tencent-ai/agent-sdk';
15
+ import z from '@deepseek-ai/schemastery';
16
+ import { PROVIDER_ID, lastUserText } from './convert.js';
17
+ import { FALLBACK_MODELS, modelsFromSdk, resolveModel } from './models.js';
18
+ import { translateStep } from './stream.js';
19
+ import { CodeBuddyToolBridge } from './tool-bridge.js';
20
+ import { QueryReaper } from './teardown.js';
21
+ export const Config = z.object({
22
+ provider: z.string().description('Provider route (default codebuddy)'),
23
+ model: z.string().description('Default model id (default codebuddy)'),
24
+ pathToCodebuddyCode: z.string().description('Path to the CodeBuddy CLI'),
25
+ cwd: z.string().description('Working directory for the CLI'),
26
+ permissionMode: z.string().description('Permission mode passed to the CLI'),
27
+ contextWindow: z.number().description('Context window override for every model'),
28
+ maxTokens: z.number().description('Max output tokens override for every model'),
29
+ });
30
+ export const name = 'codebuddy';
31
+ export const inject = ['llm'];
32
+ function errorMessage(error) {
33
+ if (error instanceof Error)
34
+ return error.message;
35
+ if (error && typeof error === 'object' && 'message' in error)
36
+ return String(error.message);
37
+ return String(error);
38
+ }
39
+ /** Results the Harness appended for the calls the previous step advertised. */
40
+ function toolResultsFrom(options, awaiting) {
41
+ const wanted = new Set(awaiting);
42
+ const results = new Map();
43
+ for (const candidate of options.messages) {
44
+ if (candidate.role !== 'tool')
45
+ continue;
46
+ const callId = candidate.source.callId;
47
+ if (callId === undefined || !wanted.has(callId))
48
+ continue;
49
+ const content = candidate.content
50
+ .map((block) => block.type === 'text' ? block.text ?? '' : `[${block.type}]`)
51
+ .filter(Boolean)
52
+ .join('\n');
53
+ results.set(callId, { content, ...candidate.isError === true ? { isError: true } : {} });
54
+ }
55
+ return results;
56
+ }
57
+ class CodeBuddyAdapter extends LlmAdapter {
58
+ config;
59
+ models = [...FALLBACK_MODELS];
60
+ discovered = false;
61
+ conversations = new Map();
62
+ constructor(config) {
63
+ super();
64
+ this.config = config;
65
+ }
66
+ providerInfo(provider) {
67
+ return { id: provider, name: 'CodeBuddy' };
68
+ }
69
+ /** Adopt the CLI's own catalog once; discovery costs a CLI start. */
70
+ async refreshModels() {
71
+ if (this.discovered)
72
+ return;
73
+ this.discovered = true;
74
+ const discovery = query({ prompt: '', options: { tools: [] } });
75
+ const reaper = new QueryReaper(discovery, 'discover');
76
+ try {
77
+ const supported = await discovery.supportedModels();
78
+ const mapped = modelsFromSdk(supported);
79
+ if (mapped.length > 0)
80
+ this.models = mapped;
81
+ }
82
+ catch {
83
+ // Best-effort: the fallback catalog keeps the route usable and the CLI
84
+ // reports the real model error on the first request.
85
+ }
86
+ finally {
87
+ await reaper.close();
88
+ }
89
+ }
90
+ async listModels(provider) {
91
+ await this.refreshModels();
92
+ return this.models.map((model) => ({
93
+ provider,
94
+ id: model.id,
95
+ name: model.name,
96
+ inputModalities: [...model.input],
97
+ }));
98
+ }
99
+ async resolveModel(provider, model) {
100
+ await this.refreshModels();
101
+ const resolved = resolveModel(this.models, model) ?? this.models.find((candidate) => candidate.id === model) ?? {
102
+ id: model,
103
+ name: model,
104
+ reasoning: false,
105
+ input: ['text'],
106
+ contextWindow: this.config.contextWindow ?? 131_072,
107
+ maxTokens: this.config.maxTokens ?? 8192,
108
+ };
109
+ return {
110
+ provider,
111
+ id: resolved.id,
112
+ name: resolved.name,
113
+ inputModalities: [...resolved.input],
114
+ context: { contextWindow: this.config.contextWindow ?? resolved.contextWindow },
115
+ defaultMaxTokens: this.config.maxTokens ?? resolved.maxTokens,
116
+ };
117
+ }
118
+ startConversation(options, model) {
119
+ const bridge = new CodeBuddyToolBridge(options.tools ?? []);
120
+ const controller = new AbortController();
121
+ if (options.signal?.aborted)
122
+ controller.abort();
123
+ else
124
+ options.signal?.addEventListener('abort', () => controller.abort(), { once: true });
125
+ const child = query({
126
+ prompt: lastUserText(options.messages) || '[continue]',
127
+ options: {
128
+ cwd: this.config.cwd ?? process.cwd(),
129
+ abortController: controller,
130
+ tools: [],
131
+ permissionMode: (this.config.permissionMode ?? 'bypassPermissions'),
132
+ includePartialMessages: true,
133
+ systemPrompt: options.system,
134
+ model,
135
+ ...this.config.pathToCodebuddyCode === undefined
136
+ ? {}
137
+ : { pathToCodebuddyCode: this.config.pathToCodebuddyCode },
138
+ ...(options.tools ?? []).length === 0
139
+ ? {}
140
+ : { mcpServers: { [bridge.server.name]: bridge.server } },
141
+ },
142
+ });
143
+ return {
144
+ iterator: child[Symbol.asyncIterator](),
145
+ bridge,
146
+ reaper: new QueryReaper(child, `conversation:${model}`),
147
+ awaiting: [],
148
+ controller,
149
+ };
150
+ }
151
+ async *stream(options) {
152
+ const provider = options.provider || this.config.provider || PROVIDER_ID;
153
+ const model = options.model || this.config.model || FALLBACK_MODELS[0].id;
154
+ // Keyed by session so concurrent subagents each own an independent CLI and
155
+ // do not resolve one another's pending tool calls.
156
+ const key = options.sessionId ?? '__default__';
157
+ let conversation = this.conversations.get(key);
158
+ if (conversation === undefined) {
159
+ conversation = this.startConversation(options, model);
160
+ this.conversations.set(key, conversation);
161
+ }
162
+ // Resolve the handlers the previous step left waiting. The CLI continues
163
+ // the same turn as soon as the Harness's real result arrives.
164
+ const results = toolResultsFrom(options, conversation.awaiting);
165
+ for (const callId of conversation.awaiting) {
166
+ const result = results.get(callId);
167
+ if (result === undefined)
168
+ continue;
169
+ conversation.bridge.deliver(callId, {
170
+ content: [{ type: 'text', text: result.content }],
171
+ ...result.isError === true ? { isError: true } : {},
172
+ });
173
+ }
174
+ conversation.awaiting = [];
175
+ try {
176
+ const step = translateStep(conversation.iterator, conversation.bridge, options.signal);
177
+ while (true) {
178
+ const next = await step.next();
179
+ if (next.done) {
180
+ if (next.value.ended)
181
+ await this.finishConversation(key);
182
+ break;
183
+ }
184
+ const value = next.value;
185
+ if (!('type' in value))
186
+ break;
187
+ const chunk = value;
188
+ if (chunk.type === 'block-end' && chunk.block.type === 'tool-call') {
189
+ conversation.awaiting.push(chunk.block.id);
190
+ }
191
+ yield chunk;
192
+ }
193
+ }
194
+ catch (error) {
195
+ conversation.bridge.failAll(`CodeBuddy provider "${provider}" failed: ${errorMessage(error)}`);
196
+ await this.finishConversation(key);
197
+ throw new LlmError(`CodeBuddy provider "${provider}" failed: ${errorMessage(error)}`, 'CODEBUDDY_ERROR', {
198
+ cause: error instanceof Error ? error : undefined,
199
+ });
200
+ }
201
+ }
202
+ async finishConversation(key) {
203
+ const conversation = this.conversations.get(key);
204
+ if (conversation === undefined)
205
+ return;
206
+ this.conversations.delete(key);
207
+ conversation.bridge.failAll('conversation ended');
208
+ await conversation.reaper.close();
209
+ }
210
+ /** Release every CLI when the plugin is disposed. */
211
+ async dispose() {
212
+ await Promise.all([...this.conversations.keys()].map((key) => this.finishConversation(key)));
213
+ }
214
+ }
215
+ export function apply(ctx, config) {
216
+ const provider = config.provider ?? PROVIDER_ID;
217
+ const adapter = new CodeBuddyAdapter(config);
218
+ ctx.llm.registerAdapter([provider], adapter);
219
+ ctx.effect(() => () => { void adapter.dispose(); });
220
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * CodeBuddy model catalog and capability estimation.
3
+ *
4
+ * The CLI reports the available model ids but little else, so capacity is
5
+ * estimated from the id with the same rules the Pi adapter uses.
6
+ */
7
+ import type { ModelInfo } from '@tencent-ai/agent-sdk';
8
+ export interface CodeBuddyModel {
9
+ id: string;
10
+ name: string;
11
+ reasoning: boolean;
12
+ input: Array<'text' | 'image'>;
13
+ contextWindow: number;
14
+ maxTokens: number;
15
+ }
16
+ export declare const FALLBACK_MODELS: CodeBuddyModel[];
17
+ export declare function modelsFromSdk(supported: readonly ModelInfo[]): CodeBuddyModel[];
18
+ export declare function resolveModel(models: readonly CodeBuddyModel[], input: string): CodeBuddyModel | undefined;
package/dist/models.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * CodeBuddy model catalog and capability estimation.
3
+ *
4
+ * The CLI reports the available model ids but little else, so capacity is
5
+ * estimated from the id with the same rules the Pi adapter uses.
6
+ */
7
+ const DEFAULT_CONTEXT = 131_072;
8
+ const DEFAULT_MAX_TOKENS = 8192;
9
+ function detectThinking(id) {
10
+ return /claude|gemini|gpt-5|hy3|deepseek|glm/i.test(id);
11
+ }
12
+ function detectImages(id) {
13
+ return /claude|gemini|gpt/i.test(id);
14
+ }
15
+ function estimateContext(id) {
16
+ const lower = id.toLowerCase();
17
+ if (lower.includes('gemini'))
18
+ return 1_048_576;
19
+ if (lower.includes('claude') || lower.includes('gpt'))
20
+ return 200_000;
21
+ return DEFAULT_CONTEXT;
22
+ }
23
+ function estimateMaxTokens(id) {
24
+ return id.toLowerCase().includes('gpt') ? 16_384 : DEFAULT_MAX_TOKENS;
25
+ }
26
+ export const FALLBACK_MODELS = [{
27
+ id: 'hy3-preview-agent-ioa',
28
+ name: 'Hunyuan 3 Preview',
29
+ reasoning: true,
30
+ input: ['text'],
31
+ contextWindow: DEFAULT_CONTEXT,
32
+ maxTokens: DEFAULT_MAX_TOKENS,
33
+ }];
34
+ export function modelsFromSdk(supported) {
35
+ return supported
36
+ // The published `.d.ts` describes `value`/`displayName`, while the CLI in
37
+ // the wild returns `id`/`name`; accept both rather than dropping the
38
+ // catalog on one of them.
39
+ .map((model) => {
40
+ const raw = model;
41
+ const id = raw.id ?? raw.value ?? '';
42
+ const name = raw.name ?? raw.displayName ?? id;
43
+ return { id, name };
44
+ })
45
+ .filter((model) => model.id)
46
+ .map((model) => ({
47
+ id: model.id,
48
+ name: model.name,
49
+ reasoning: detectThinking(model.id),
50
+ input: detectImages(model.id) ? ['text', 'image'] : ['text'],
51
+ contextWindow: estimateContext(model.id),
52
+ maxTokens: estimateMaxTokens(model.id),
53
+ }));
54
+ }
55
+ export function resolveModel(models, input) {
56
+ const lower = input.toLowerCase();
57
+ return models.find((model) => model.id.toLowerCase() === lower)
58
+ ?? models.find((model) => model.id.toLowerCase().includes(lower));
59
+ }
@@ -0,0 +1,30 @@
1
+ /**
2
+ * CodeBuddy message-stream translation into the Harness streaming protocol.
3
+ *
4
+ * CodeBuddy reports Anthropic-shaped `content_block_*` events plus a final
5
+ * `assistant`/`result` message. The Harness vocabulary keeps tool arguments as
6
+ * raw JSON strings and ends a step at the first tool call so its own loop can
7
+ * execute the tool, so one call to {@link translateStep} consumes exactly one
8
+ * CodeBuddy turn and stops at that boundary.
9
+ */
10
+ import type { StreamChunk } from '@deepseek-ai/dsh-llm';
11
+ import type { Message as CodeBuddyMessage } from '@tencent-ai/agent-sdk';
12
+ import type { CodeBuddyToolBridge } from './tool-bridge.js';
13
+ export interface StepStatus {
14
+ /** True when this step ended on a tool call and the loop must run it. */
15
+ awaitingTool: boolean;
16
+ /** True when the conversation reached a terminal result and can be released. */
17
+ ended: boolean;
18
+ }
19
+ /**
20
+ * Consume one CodeBuddy turn and yield Harness chunks.
21
+ *
22
+ * A turn that calls a tool ends the iteration after yielding its `finish`
23
+ * chunk: the next step's `translateStep()` call resumes the same query, at
24
+ * which point the still-pending MCP handlers receive their results.
25
+ *
26
+ * The iterator is advanced with an explicit `next()` rather than `for await`:
27
+ * a `for await` that returns early would call `iterator.return()`, which tears
28
+ * down the CLI the next step still needs.
29
+ */
30
+ export declare function translateStep(source: AsyncIterator<CodeBuddyMessage>, bridge: CodeBuddyToolBridge, callerSignal?: AbortSignal): AsyncGenerator<StreamChunk, StepStatus, void>;
package/dist/stream.js ADDED
@@ -0,0 +1,164 @@
1
+ /**
2
+ * CodeBuddy message-stream translation into the Harness streaming protocol.
3
+ *
4
+ * CodeBuddy reports Anthropic-shaped `content_block_*` events plus a final
5
+ * `assistant`/`result` message. The Harness vocabulary keeps tool arguments as
6
+ * raw JSON strings and ends a step at the first tool call so its own loop can
7
+ * execute the tool, so one call to {@link translateStep} consumes exactly one
8
+ * CodeBuddy turn and stops at that boundary.
9
+ */
10
+ function toolCallId(value) {
11
+ return value;
12
+ }
13
+ function mapUsage(usage) {
14
+ return {
15
+ inputTokens: usage?.input_tokens ?? 0,
16
+ outputTokens: usage?.output_tokens ?? 0,
17
+ ...(usage?.cache_read_input_tokens ?? 0) > 0 ? { cacheReadTokens: usage.cache_read_input_tokens } : {},
18
+ ...(usage?.cache_creation_input_tokens ?? 0) > 0 ? { cacheWriteTokens: usage.cache_creation_input_tokens } : {},
19
+ };
20
+ }
21
+ function mapStopReason(reason) {
22
+ switch (reason) {
23
+ case 'tool_use':
24
+ return { kind: 'tool-calls' };
25
+ case 'max_tokens':
26
+ return { kind: 'max-tokens' };
27
+ case 'refusal':
28
+ return { kind: 'error', failure: { message: 'CodeBuddy refused the request', code: 'REFUSAL' } };
29
+ default:
30
+ return { kind: 'stop' };
31
+ }
32
+ }
33
+ /**
34
+ * Consume one CodeBuddy turn and yield Harness chunks.
35
+ *
36
+ * A turn that calls a tool ends the iteration after yielding its `finish`
37
+ * chunk: the next step's `translateStep()` call resumes the same query, at
38
+ * which point the still-pending MCP handlers receive their results.
39
+ *
40
+ * The iterator is advanced with an explicit `next()` rather than `for await`:
41
+ * a `for await` that returns early would call `iterator.return()`, which tears
42
+ * down the CLI the next step still needs.
43
+ */
44
+ export async function* translateStep(source, bridge, callerSignal) {
45
+ let sawToolCall = false;
46
+ const toolIndex = new Map();
47
+ const argumentBuffers = new Map();
48
+ while (true) {
49
+ const next = await source.next();
50
+ if (next.done)
51
+ break;
52
+ const message = next.value;
53
+ if (message.type === 'stream_event') {
54
+ const event = message.event;
55
+ switch (event.type) {
56
+ case 'content_block_start': {
57
+ if (event.content_block.type === 'text') {
58
+ yield { type: 'block-start', index: event.index, blockType: 'text' };
59
+ }
60
+ else if (event.content_block.type === 'thinking') {
61
+ yield { type: 'block-start', index: event.index, blockType: 'reasoning' };
62
+ }
63
+ else if (event.content_block.type === 'tool_use') {
64
+ toolIndex.set(event.index, { id: event.content_block.id, name: event.content_block.name });
65
+ argumentBuffers.set(event.index, '');
66
+ yield { type: 'block-start', index: event.index, blockType: 'tool-call' };
67
+ }
68
+ break;
69
+ }
70
+ case 'content_block_delta': {
71
+ const delta = event.delta;
72
+ if (delta.type === 'text_delta') {
73
+ yield { type: 'text-delta', index: event.index, text: delta.text };
74
+ }
75
+ else if (delta.type === 'thinking_delta') {
76
+ yield { type: 'reasoning-delta', index: event.index, text: delta.thinking };
77
+ }
78
+ else if (delta.type === 'input_json_delta') {
79
+ const known = toolIndex.get(event.index);
80
+ argumentBuffers.set(event.index, (argumentBuffers.get(event.index) ?? '') + delta.partial_json);
81
+ yield {
82
+ type: 'tool-call-delta',
83
+ index: event.index,
84
+ id: toolCallId(known?.id ?? ''),
85
+ ...known?.name === undefined ? {} : { name: known.name },
86
+ argumentsDelta: delta.partial_json,
87
+ };
88
+ }
89
+ break;
90
+ }
91
+ case 'content_block_stop': {
92
+ // The assembled assistant message below is authoritative and is the
93
+ // only place a `block-end` is emitted, so the Harness's
94
+ // first-close-wins rule cannot drop the real arguments.
95
+ if (toolIndex.has(event.index))
96
+ sawToolCall = true;
97
+ break;
98
+ }
99
+ default:
100
+ break;
101
+ }
102
+ continue;
103
+ }
104
+ if (message.type === 'assistant') {
105
+ if (message.error) {
106
+ yield { type: 'finish', reason: { kind: 'error', failure: { message: message.error, code: 'CODEBUDDY_ERROR' } } };
107
+ return { awaitingTool: false, ended: true };
108
+ }
109
+ for (const [index, block] of message.message.content.entries()) {
110
+ if (block.type === 'text') {
111
+ yield { type: 'block-end', index, block: { type: 'text', text: block.text } };
112
+ }
113
+ else if (block.type === 'thinking') {
114
+ yield { type: 'block-end', index, block: { type: 'reasoning', text: block.thinking } };
115
+ }
116
+ else if (block.type === 'tool_use') {
117
+ sawToolCall = true;
118
+ bridge.noteToolCall(block.id);
119
+ yield {
120
+ type: 'block-end',
121
+ index,
122
+ block: {
123
+ type: 'tool-call',
124
+ id: toolCallId(block.id),
125
+ name: block.name,
126
+ arguments: argumentBuffers.get(index) || JSON.stringify(block.input ?? {}),
127
+ },
128
+ };
129
+ }
130
+ }
131
+ if (!sawToolCall && message.message.stop_reason === 'tool_use')
132
+ sawToolCall = true;
133
+ // A tool-call turn ends here: control returns to the Harness loop, which
134
+ // executes the tools and calls again with their results.
135
+ if (sawToolCall) {
136
+ yield { type: 'finish', reason: { kind: 'tool-calls' } };
137
+ return { awaitingTool: true, ended: false };
138
+ }
139
+ continue;
140
+ }
141
+ if (message.type === 'result') {
142
+ yield { type: 'usage', usage: mapUsage(message.usage) };
143
+ if (message.is_error || message.subtype !== 'success') {
144
+ const detail = message.subtype === 'success'
145
+ ? 'CodeBuddy reported an error'
146
+ : message.errors?.join('; ') ?? message.subtype;
147
+ yield { type: 'finish', reason: { kind: 'error', failure: { message: detail, code: 'CODEBUDDY_ERROR' } } };
148
+ }
149
+ else {
150
+ yield { type: 'finish', reason: mapStopReason(sawToolCall ? 'tool_use' : 'end_turn') };
151
+ }
152
+ return { awaitingTool: sawToolCall, ended: true };
153
+ }
154
+ }
155
+ yield {
156
+ type: 'finish',
157
+ reason: callerSignal?.aborted
158
+ ? { kind: 'aborted', failure: { message: 'CodeBuddy query aborted', code: 'ABORTED' } }
159
+ : sawToolCall
160
+ ? { kind: 'tool-calls' }
161
+ : { kind: 'error', failure: { message: 'CodeBuddy query ended without a result', code: 'STREAM_CLOSED' } },
162
+ };
163
+ return { awaitingTool: sawToolCall, ended: true };
164
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Guarantee the CodeBuddy CLI child process is reaped.
3
+ *
4
+ * `@tencent-ai/agent-sdk`'s `query()` closes its transport only when its
5
+ * iterator reaches the terminal message. Paths that abandon the iterator
6
+ * (model discovery, canceled turns) would otherwise leak a child process for
7
+ * the lifetime of the host, so every completion path calls this.
8
+ */
9
+ export interface TeardownOptions {
10
+ forceKillAfterMs?: number;
11
+ log?: (message: string) => void;
12
+ }
13
+ export declare function closeQueryTransport(query: unknown, label: string, options?: TeardownOptions): void;
14
+ export declare function endQuery(query: unknown, label: string, options?: TeardownOptions): void;
15
+ /**
16
+ * Idempotent teardown for one query. `close()` on the underlying transport is
17
+ * idempotent too, so repeated calls (a completed turn plus fiber disposal) are
18
+ * safe.
19
+ */
20
+ export declare class QueryReaper {
21
+ private readonly query;
22
+ private readonly label;
23
+ private readonly options;
24
+ private closed;
25
+ constructor(query: unknown, label: string, options?: TeardownOptions);
26
+ /** Stop the turn (if any) and release the child process. */
27
+ close(): Promise<void>;
28
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Guarantee the CodeBuddy CLI child process is reaped.
3
+ *
4
+ * `@tencent-ai/agent-sdk`'s `query()` closes its transport only when its
5
+ * iterator reaches the terminal message. Paths that abandon the iterator
6
+ * (model discovery, canceled turns) would otherwise leak a child process for
7
+ * the lifetime of the host, so every completion path calls this.
8
+ */
9
+ export function closeQueryTransport(query, label, options = {}) {
10
+ const transport = query?.transport;
11
+ if (!transport || typeof transport.close !== 'function')
12
+ return;
13
+ const pid = typeof transport.process?.pid === 'number' ? transport.process.pid : undefined;
14
+ try {
15
+ transport.close();
16
+ options.log?.(`teardown(${label}): transport closed${pid === undefined ? '' : ` (pid ${pid})`}`);
17
+ }
18
+ catch (error) {
19
+ options.log?.(`teardown(${label}): transport close failed: ${error instanceof Error ? error.message : String(error)}`);
20
+ }
21
+ if (pid === undefined)
22
+ return;
23
+ const timer = setTimeout(() => {
24
+ try {
25
+ process.kill(pid, 0);
26
+ }
27
+ catch {
28
+ return;
29
+ }
30
+ try {
31
+ process.kill(pid, 'SIGKILL');
32
+ options.log?.(`teardown(${label}): pid ${pid} survived close, sent SIGKILL`);
33
+ }
34
+ catch {
35
+ // Raced with exit.
36
+ }
37
+ }, options.forceKillAfterMs ?? 2000);
38
+ timer.unref?.();
39
+ }
40
+ export function endQuery(query, label, options = {}) {
41
+ try {
42
+ void query?.interrupt?.()?.catch?.(() => { });
43
+ }
44
+ catch {
45
+ // Expected on a half-dead transport.
46
+ }
47
+ closeQueryTransport(query, label, options);
48
+ }
49
+ /**
50
+ * Idempotent teardown for one query. `close()` on the underlying transport is
51
+ * idempotent too, so repeated calls (a completed turn plus fiber disposal) are
52
+ * safe.
53
+ */
54
+ export class QueryReaper {
55
+ query;
56
+ label;
57
+ options;
58
+ closed = false;
59
+ constructor(query, label, options = {}) {
60
+ this.query = query;
61
+ this.label = label;
62
+ this.options = options;
63
+ }
64
+ /** Stop the turn (if any) and release the child process. */
65
+ async close() {
66
+ if (this.closed)
67
+ return;
68
+ this.closed = true;
69
+ endQuery(this.query, this.label, this.options);
70
+ }
71
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Bridge the Harness tool declarations to CodeBuddy through an in-process SDK
3
+ * MCP server.
4
+ *
5
+ * The Harness owns tool execution: a `stream()` call ends at the tool call,
6
+ * its loop runs the tool, and the next `stream()` call carries the result.
7
+ * The MCP handler therefore blocks on a promise that the *next* step resolves
8
+ * by matching the tool call id against the result the Harness just appended.
9
+ * Returning eagerly instead would let CodeBuddy fabricate a result and
10
+ * continue the conversation unobserved by the Harness loop.
11
+ */
12
+ import { type SdkMcpServerResult } from '@tencent-ai/agent-sdk';
13
+ import type { ToolSchema } from '@deepseek-ai/dsh-llm';
14
+ export interface ToolResult {
15
+ content: Array<{
16
+ type: 'text';
17
+ text: string;
18
+ } | {
19
+ type: 'image';
20
+ data: string;
21
+ mimeType: string;
22
+ }>;
23
+ isError?: boolean;
24
+ }
25
+ export interface ToolBridge {
26
+ server: SdkMcpServerResult;
27
+ /** Tool call ids this turn advertised, in call order. */
28
+ readonly toolCallIds: string[];
29
+ /** Resolve every waiting handler; used on abort and query teardown. */
30
+ failAll(message: string): void;
31
+ }
32
+ /**
33
+ * One bridge per CodeBuddy query. The same instance must span the step that
34
+ * advertises the tools and the step that delivers their results.
35
+ */
36
+ export declare class CodeBuddyToolBridge {
37
+ private readonly pending;
38
+ private readonly results;
39
+ private readonly ids;
40
+ private index;
41
+ readonly server: SdkMcpServerResult;
42
+ constructor(tools: readonly ToolSchema[]);
43
+ /** Record a tool-call id as it streams, preserving call order. */
44
+ noteToolCall(id: string): void;
45
+ /** Resolve a waiting handler, or queue the result for one that has not arrived. */
46
+ deliver(id: string, result: ToolResult): boolean;
47
+ /** Unblock every waiting handler so a torn-down query can exit. */
48
+ failAll(message: string): void;
49
+ get waiting(): number;
50
+ }
51
+ /** Build a bridge; kept as a function for call sites that only need the server. */
52
+ export declare function createToolBridge(tools: readonly ToolSchema[]): CodeBuddyToolBridge;
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Bridge the Harness tool declarations to CodeBuddy through an in-process SDK
3
+ * MCP server.
4
+ *
5
+ * The Harness owns tool execution: a `stream()` call ends at the tool call,
6
+ * its loop runs the tool, and the next `stream()` call carries the result.
7
+ * The MCP handler therefore blocks on a promise that the *next* step resolves
8
+ * by matching the tool call id against the result the Harness just appended.
9
+ * Returning eagerly instead would let CodeBuddy fabricate a result and
10
+ * continue the conversation unobserved by the Harness loop.
11
+ */
12
+ import { createSdkMcpServer, tool } from '@tencent-ai/agent-sdk';
13
+ import { MCP_SERVER_NAME } from './convert.js';
14
+ import { jsonSchemaToZodShape } from './zod-shape.js';
15
+ function toCallToolResult(result) {
16
+ const content = result.content.map((block) => block.type === 'text'
17
+ ? { type: 'text', text: block.text }
18
+ : {
19
+ type: 'image',
20
+ data: block.data,
21
+ mimeType: block.mimeType,
22
+ });
23
+ return { content, ...result.isError === true ? { isError: true } : {} };
24
+ }
25
+ /**
26
+ * One bridge per CodeBuddy query. The same instance must span the step that
27
+ * advertises the tools and the step that delivers their results.
28
+ */
29
+ export class CodeBuddyToolBridge {
30
+ pending = new Map();
31
+ results = new Map();
32
+ ids = [];
33
+ index = 0;
34
+ server;
35
+ constructor(tools) {
36
+ this.server = createSdkMcpServer({
37
+ name: MCP_SERVER_NAME,
38
+ version: '1.0.0',
39
+ tools: tools.map((schema) => tool(schema.name, schema.description, jsonSchemaToZodShape(schema.parameters), async () => {
40
+ // The control protocol does not expose the model's tool-call id to
41
+ // the handler, so ids are matched positionally within the turn: the
42
+ // Harness emits them in the same order the MCP server receives them.
43
+ const id = this.ids[this.index];
44
+ this.index += 1;
45
+ if (id === undefined)
46
+ return toCallToolResult({ content: [{ type: 'text', text: 'tool call could not be matched' }], isError: true });
47
+ const queued = this.results.get(id);
48
+ if (queued !== undefined) {
49
+ this.results.delete(id);
50
+ return toCallToolResult(queued);
51
+ }
52
+ return await new Promise((resolve) => {
53
+ this.pending.set(id, {
54
+ name: schema.name,
55
+ resolve: (result) => resolve(toCallToolResult(result)),
56
+ });
57
+ });
58
+ })),
59
+ });
60
+ }
61
+ /** Record a tool-call id as it streams, preserving call order. */
62
+ noteToolCall(id) {
63
+ this.ids.push(id);
64
+ }
65
+ /** Resolve a waiting handler, or queue the result for one that has not arrived. */
66
+ deliver(id, result) {
67
+ const pending = this.pending.get(id);
68
+ if (pending !== undefined) {
69
+ this.pending.delete(id);
70
+ pending.resolve(result);
71
+ return true;
72
+ }
73
+ this.results.set(id, result);
74
+ return false;
75
+ }
76
+ /** Unblock every waiting handler so a torn-down query can exit. */
77
+ failAll(message) {
78
+ for (const pending of this.pending.values()) {
79
+ pending.resolve({ content: [{ type: 'text', text: message }], isError: true });
80
+ }
81
+ this.pending.clear();
82
+ }
83
+ get waiting() {
84
+ return this.pending.size;
85
+ }
86
+ }
87
+ /** Build a bridge; kept as a function for call sites that only need the server. */
88
+ export function createToolBridge(tools) {
89
+ return new CodeBuddyToolBridge(tools);
90
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * JSON Schema → Zod raw shape for the SDK MCP server.
3
+ *
4
+ * `createSdkMcpServer()` silently degrades an unrecognized schema to an empty
5
+ * object, which leaves the model with no parameter information. The Harness
6
+ * declares tool parameters as JSON Schema, so they are translated here.
7
+ */
8
+ import { type ZodTypeAny } from 'zod';
9
+ export declare function jsonSchemaToZodShape(schema: unknown): Record<string, ZodTypeAny>;
@@ -0,0 +1,49 @@
1
+ /**
2
+ * JSON Schema → Zod raw shape for the SDK MCP server.
3
+ *
4
+ * `createSdkMcpServer()` silently degrades an unrecognized schema to an empty
5
+ * object, which leaves the model with no parameter information. The Harness
6
+ * declares tool parameters as JSON Schema, so they are translated here.
7
+ */
8
+ import { z } from 'zod';
9
+ function propertyToZod(property) {
10
+ if (Array.isArray(property.enum))
11
+ return z.enum(property.enum);
12
+ let base;
13
+ switch (property.type) {
14
+ case 'string':
15
+ base = z.string();
16
+ break;
17
+ case 'number':
18
+ case 'integer':
19
+ base = z.number();
20
+ break;
21
+ case 'boolean':
22
+ base = z.boolean();
23
+ break;
24
+ case 'array':
25
+ base = property.items
26
+ ? z.array(propertyToZod(property.items))
27
+ : z.array(z.unknown());
28
+ break;
29
+ case 'object':
30
+ base = z.record(z.string(), z.unknown());
31
+ break;
32
+ default:
33
+ base = z.unknown();
34
+ }
35
+ return typeof property.description === 'string' ? base.describe(property.description) : base;
36
+ }
37
+ export function jsonSchemaToZodShape(schema) {
38
+ const object = schema;
39
+ if (!object || object.type !== 'object' || !object.properties)
40
+ return {};
41
+ const properties = object.properties;
42
+ const required = new Set(Array.isArray(object.required) ? object.required : []);
43
+ const shape = {};
44
+ for (const [key, property] of Object.entries(properties)) {
45
+ const zodProperty = propertyToZod(property);
46
+ shape[key] = required.has(key) ? zodProperty : zodProperty.optional();
47
+ }
48
+ return shape;
49
+ }
package/package.json CHANGED
@@ -1,6 +1,59 @@
1
1
  {
2
2
  "name": "dsh-codebuddy-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "DeepSeek Harness plugin: CodeBuddy (Tencent Agent SDK) as an LLM provider adapter (ctx.llm). WIP — port of pi-codebuddy-sdk.",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "exports": {
8
+ ".": "./dist/index.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "cordis.patch.yml",
13
+ "README.md",
14
+ "LICENSE"
15
+ ],
16
+ "scripts": {
17
+ "build": "tsc -p tsconfig.json",
18
+ "test:ci": "node --import tsx --test tests/smoke.test.mjs tests/unit-*.mjs",
19
+ "test:integration": "CODEBUDDY_SDK_INTEGRATION=1 node --import tsx --test tests/integration-cli.test.mjs",
20
+ "test": "node --import tsx --test tests/*.mjs",
21
+ "typecheck": "tsc --noEmit",
22
+ "clean": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\"",
23
+ "prepack": "npm run clean && npm run build",
24
+ "prepublishOnly": "npm run clean && npm run build"
25
+ },
26
+ "keywords": [
27
+ "dsh",
28
+ "dsh-plugin",
29
+ "deepseek-harness",
30
+ "cordis",
31
+ "codebuddy",
32
+ "llm"
33
+ ],
34
+ "license": "MIT",
35
+ "dependencies": {
36
+ "@deepseek-ai/cordis": "^4.0.1",
37
+ "@deepseek-ai/dsh-credentials": "^0.0.1-rc.1",
38
+ "@deepseek-ai/dsh-llm": "^0.0.1-rc.1",
39
+ "@deepseek-ai/schemastery": "^3.18.0",
40
+ "@tencent-ai/agent-sdk": "^0.3.267",
41
+ "change-case": "^5.4.4",
42
+ "zod": "^4.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "^22.0.0",
46
+ "tsx": "^4.19.0",
47
+ "typescript": "^5.5.0"
48
+ },
49
+ "dsh": {
50
+ "bundle": {
51
+ "patch": "./cordis.patch.yml"
52
+ }
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/RetiredPhysicist/dsh-plugins.git",
57
+ "directory": "packages/dsh-codebuddy-sdk"
58
+ }
59
+ }