commit 657fe90fd3aa63c62a02551f1a7fc9ec06d0e791 Author: catShark <1716967236@qq.com> Date: Mon Nov 16 18:17:49 2026 +0800 feat: commandcode-pi 0.1.0 — Command Code Go provider over /alpha/generate 从 ~/.pi/agent/extensions/ 的本地实验文件收编为独立 pi 包: - extensions/commandcode-go.ts:provider commandcode-go,只走 CLI 内部端点 POST /alpha/generate;启动拉 /provider/v1/models 并过滤出 Go 套餐可用的 DeepSeek 模型;凭据按 env → ~/.commandcode/auth.json → pi auth.json 顺序验活 - extensions/commandcode-transient-retry.ts:把网关签名明确的偶发 400 改写为 可重试,复用 pi 内置退避重试 - 文档:README(安装/凭据/模型/风险/排查)、docs/protocol.md(线协议)、 LICENSE(MIT + 上游署名) diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d290d16 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +node_modules/ +package-lock.json + +# 运行时缓存与凭据:由 pi / 扩展在 ~/.pi/agent 下生成,绝不入库 +*.log +.env +.env.* +auth.json +commandcode-go-catalog.json diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..af8ca1a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# Changelog + +## [0.1.0] - 2026-11-16 + +首个版本,从 `~/.pi/agent/extensions/` 的本地实验文件收编为独立项目。 + +- `extensions/commandcode-go.ts`:`commandcode-go` provider,只走 CLI 内部端点 `POST /alpha/generate`;启动拉 `/provider/v1/models?view=client` 并过滤出 Go 套餐可用的 DeepSeek 模型;凭据按 env → `~/.commandcode/auth.json` → `~/.pi/agent/auth.json` 顺序验活;`/commandcode-go-status` 查看状态。 +- `extensions/commandcode-transient-retry.ts`:把 Command Code 网关签名明确的偶发 400 改写成可重试,复用 pi 内置退避重试。 +- 文档:`README.md`(安装/凭据/模型/风险/排查)、`docs/protocol.md`(线协议要点)、`LICENSE`(MIT + 上游署名)。 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f859eb5 --- /dev/null +++ b/LICENSE @@ -0,0 +1,42 @@ +MIT License + +Copyright (c) 2026 cat-shark + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +--- + +## Third-party attribution + +The `/alpha/generate` transport in `extensions/commandcode-go.ts` is a port of +earlier MIT-licensed work. The original copyright notices belong to their +respective authors: + +- `patlux/pi-commandcode-provider` (MIT) — `src/core.ts`, `src/converters.ts` + were the base for the request serializer, event-stream decoder, reasoning + replay, tool-call pairing and tool-call id shortening logic. The last version + of that project to still ship the `/alpha/generate` client was 0.7.12. +- `Mars-Sea/dsh-commandcode-provider` (MIT) — `docs/agent-reference/adapter-protocol.md` + and the `buildCliBody()` / `handleCliEvent()` implementations documented the + wire protocol as observed in `command-code@1.88.5`. + +`extensions/commandcode-transient-retry.ts` is original to this project. + +Command Code and DeepSeek are trademarks of their respective owners. This +project is not affiliated with or endorsed by Command Code. diff --git a/README.md b/README.md new file mode 100644 index 0000000..fead992 --- /dev/null +++ b/README.md @@ -0,0 +1,149 @@ +# commandcode-pi + +让 **Command Code「Go」套餐**能在 [pi](https://pi.dev) 里当 API 用:注册 DeepSeek 模型,并用官方 CLI 的内部端点 `POST /alpha/generate` 流式对话。 + +> 非官方实现。它模拟官方 CLI 的请求头与线协议,属于对厂商内部接口的逆向复用,见 [风险与合规](#风险与合规)。 + +## 为什么需要它 + +Command Code 把「订阅套餐」和「Provider API」拆成了两种权限: + +| 通道 | 端点 | Go 套餐可用 | +|---|---|---| +| Provider API(OpenAI 兼容) | `/provider/v1/responses`、`/provider/v1/chat/completions` | ❌ 一律 `403 upgrade_required` | +| 官方 CLI 内部端点 | `/alpha/generate` | ✅ 唯一可用通道 | + +现成的两个 pi 插件都用不了:`@commandcode/pi-commandcode-provider`(官方)只走 Provider API;`pi-commandcode-provider`(社区)自 0.8.0 起主动删掉了 `/alpha/generate` 兜底(最后带兜底的是 0.7.12)。因此这里自建一个只走该端点的最小 provider。 + +## 安装 + +```bash +# 从本仓库安装(跟踪 main,改完 push 后 pi update --extensions 生效) +pi install ssh://git@git.cat-shark.xyz:2222/cat-shark/commandcode-pi.git + +# 需要锁版本时 +pi install ssh://git@git.cat-shark.xyz:2222/cat-shark/commandcode-pi.git@v0.1.0 +``` + +安装后由 pi 管理到 `~/.pi/agent/git/git.cat-shark.xyz/cat-shark/commandcode-pi`。 + +不想用包管理时,也可以直接把两个文件拷进全局扩展目录(pi 启动即自动发现): + +```bash +cp extensions/*.ts ~/.pi/agent/extensions/ +``` + +> 两种方式**只选一种**。同时存在会造成 provider id `commandcode-go` 被注册两次。 + +本包 `package.json` 的 `pi.extensions` 同时声明了两个文件: + +| 文件 | 作用 | 可否省略 | +|---|---|---| +| `extensions/commandcode-go.ts` | provider 本体 | 必需 | +| `extensions/commandcode-transient-retry.ts` | 把 Command Code 网关偶发 400 改写成可重试,复用 pi 内置退避重试 | 可选,省略后偶发 400 需手工重发 | + +## 凭据 + +按可信度顺序自动挑选,启动时逐个 `GET /alpha/whoami` 验活,过期的自动跳过: + +1. 环境变量:`COMMAND_CODE_GO_API_KEY` → `COMMAND_CODE_API_KEY` → `COMMANDCODE_API_KEY` +2. `~/.commandcode/auth.json`(`cmd login` 写入的官方 CLI 凭据) +3. `~/.pi/agent/auth.json`(pi 的 `/login` 写入的凭据,条目 id 依次尝试 `commandcode-go`、`commandcode`、`command-code`) + +全部失效时留占位符,`/login` 选 `commandcode-go` 粘贴新 key 即可写入 `auth.json`。 + +```bash +# 换 key 后确认拿到了哪一把(只显示前 8 位) +/commandcode-go-status +``` + +## 用法 + +启动时拉取 `GET /provider/v1/models?view=client` 生成模型列表,缓存到 `~/.pi/agent/commandcode-go-catalog.json`(命中缓存不刷新,要最新目录就删掉该文件)。 + +过滤规则(在 `toModelConfig()` 里): + +- 只保留 `id` 以 `deepseek/` 开头的模型 +- 只保留 `minimumPlan` 为空或 `individual-go` 的模型(其它档位选到就是 `MODEL_NOT_IN_PLAN`) + +典型注册结果(全部 Go 套餐可用): + +| 模型 | 上下文 | 图片 | 思考档位 | +|---|---|---|---| +| `deepseek/deepseek-v4-pro` | 1M | ✗ | off/high/max | +| `deepseek/deepseek-v4-flash` | 1M | ✗ | off/high/max | +| `deepseek/deepseek-v4-flash-fast` | 1M | ✗ | low/high/max | +| `deepseek/deepseek-v4-flash-vision-exp` | 1M | ✓ | off/high/max | +| `deepseek/deepseek-v4.1-flash` | 1M | ✓ | off/low/high/max | +| `deepseek/deepseek-v4.1-flash-fast` | 1M | ✓ | off/low/high/max | + +设为默认(`enabledModels` 首项会抢占 `defaultProvider`,两处都要对齐): + +```json +"defaultProvider": "commandcode-go", +"defaultModel": "deepseek/deepseek-v4.1-flash", +"enabledModels": ["commandcode-go/deepseek/deepseek-v4.1-flash", "..."] +``` + +## 配置 + +| 环境变量 | 默认 | 说明 | +|---|---|---| +| `COMMAND_CODE_GO_API_KEY` / `COMMAND_CODE_API_KEY` / `COMMANDCODE_API_KEY` | — | 最高优先级凭据来源 | +| `COMMANDCODE_API_BASE` | `https://api.commandcode.ai` | 换网关/镜像时用 | + +代码内常量:`CLI_VERSION = "1.88.5"`(请求头伪装的官方 CLI 版本)、`MAX_OUTPUT_TOKENS = 131072`(服务端实际上限约 200K,按官方 CLI 取值压低)、`TOOL_CALL_ID_LIMIT = 64`(网关拒绝更长的 tool-call id)。 + +## 验证 + +```bash +# 1. 模型注册(应为 6 个,且无 provider warning) +pi --list-models | grep -c commandcode-go + +# 2. 纯文本 +pi -p "用三个词回答:你好" --model commandcode-go/deepseek/deepseek-v4.1-flash + +# 3. 工具循环(验证工具调用、结果回传、历史回放) +pi -p "用 bash 工具执行 uname -a,然后只回答内核版本" + +# 4. 失败分类:选一个 Go 套餐没有的模型,应报 403 MODEL_NOT_IN_PLAN 并带中文提示 +``` + +## 错误码 + +| 网关返回 | 扩展给的提示 | +|---|---| +| `MODEL_NOT_IN_PLAN` | 该模型不在 Go 套餐内,换一个模型 | +| `UNAUTHORIZED` | key 无效/过期,走 `/login` 或换 env | +| `upgrade_required` | Go 套餐没有 Provider API 权限,本扩展只走 `/alpha/generate` | + +## 风险与合规 + +1. **非官方通道**:`/alpha/generate` 是官方 CLI 的内部端点,未公开承诺稳定;上游改协议或封禁即失效,且需要同步升级 `CLI_VERSION`。 +2. **服务条款冲突风险**:伪装 `User-Agent`、`x-command-code-version` 模拟官方客户端,与 Command Code 服务条款存在冲突,账号自负风险。 +3. **无自动重试**(provider 本体):依赖 pi 内置重试;`commandcode-transient-retry.ts` 只覆盖网关签名特征明确的 400。 +4. **成本为估算**:价格取自上游目录,`maxTokens` 统一按 131 072 注册(目录未给 `maxOutputTokens`),不影响计费但会高估可用输出上限。 +5. **缓存陈旧**:`~/.pi/agent/commandcode-go-catalog.json` 命中即不刷新。 + +## 故障排查 + +| 现象 | 排查 | +|---|---| +| `/model` 里没有 `commandcode-go` | `pi list` 看包是否装了;`pi --list-models` 是否有 warning;两个来源是否重复加载 | +| 一直 401 | key 过期:`/commandcode-go-status` 看凭据前缀,`curl -H "Authorization: Bearer $KEY" https://api.commandcode.ai/alpha/whoami` | +| 403 `MODEL_NOT_IN_PLAN` | 选了 Go 套餐不含的模型,见上方模型表 | +| 偶发 `invalid request error trace_id` 400 | 网关瞬态故障;确认 `commandcode-transient-retry.ts` 已加载,然后重发 | +| 模型列表少了新模型 | 删掉 `~/.pi/agent/commandcode-go-catalog.json` 后重启 | + +## 开发 + +```bash +git clone ssh://git@git.cat-shark.xyz:2222/cat-shark/commandcode-pi.git +cd commandcode-pi +# 本包无 runtime 依赖,扩展直接由 pi 加载(pi 提供 @earendil-works/* 模块映射) + +# 改完提交并推送,让 pi 管理的副本跟上 +git push && pi update --extensions +``` + +版本号写在 `package.json`,变更写 `CHANGELOG.md`(pi 会按版本号在下次启动的 "Extension Updates" 里展示)。线协议细节见 [`docs/protocol.md`](docs/protocol.md)。 diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..4d92a2d --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,80 @@ +# `/alpha/generate` 线协议要点 + +Command Code 官方 CLI 自己走的内网端点。它**不是** OpenAI / Anthropic 兼容协议,`models.json` 无法表达,只能用 provider 扩展实现。以下事实来自逆向复验(`command-code@1.88.5`)与 MIT 许可的上游实现。 + +## 请求 + +``` +POST https://api.commandcode.ai/alpha/generate +``` + +请求头: + +| 头 | 值 | +|---|---| +| `Authorization` | `Bearer user_...` | +| `Content-Type` | `application/json` | +| `x-command-code-version` | `1.88.5`(伪装官方 CLI 版本) | +| `x-cli-environment` | `production` | +| `x-project-slug` | 项目名 | +| `x-taste-learning` | `false` | +| `x-co-flag` | `false` | +| `User-Agent` | `cli` | +| `x-session-id` | 会话 id | +| `x-cmd-zdr` | `1`(可选,零数据留存) | + +请求体: + +```jsonc +{ + "config": { "workingDir": "...", "date": "...", "environment": {...}, "structure": "...", "isGitRepo": true }, + "memory": "", "taste": "", "skills": [], + "permissionMode": "standard", + "params": { + "model": "deepseek/deepseek-v4.1-flash", + "messages": [...], // system 可用数组形式并带 cache_control + "tools": [...], + "system": [...], + "max_tokens": 131072, + "temperature": 0.2, // 可选 + "stream": true, + "reasoning_effort": "high" // 可选,取值随模型目录的 reasoningEfforts + }, + "threadId": "..." +} +``` + +约束: + +- 工具参数 schema 必须是**对象根**(`type: "object"`)。 +- `max_tokens` 服务端上限约 200K(实测 200 704 起 400),官方 CLI 取 131 072。 +- `tool-call id` 上限 64 字符;超长需确定性缩短,且调用与结果共用同一映射。 +- 历史 assistant 的 `thinking` 必须回放为 `{ "type": "reasoning", "text": ... }`,否则 DeepSeek 思考模式的工具循环会被拒。 + +## 响应事件流 + +| 事件 | 含义 | +|---|---| +| `reasoning-start` / `reasoning-delta` / `reasoning-end` | 思考块 | +| `text-start` / `text-delta` / `text-end` | 正文 | +| `tool-input-start` / `tool-input-delta` | 工具参数增量 | +| `tool-call` | 完整工具调用 | +| `cache-write-tokens` | 缓存写入计数 | +| `finish` | 结束,带 `totalUsage` | +| `error` | 错误,带 `code`(`MODEL_NOT_IN_PLAN` / `UNAUTHORIZED` / `upgrade_required` 等) | +| `abort` | 中断 | + +## 相关端点 + +| 端点 | 鉴权 | 用途 | +|---|---|---| +| `GET /alpha/whoami` | 需要 | 验活 key(启动时逐把探测,5s 超时) | +| `GET /provider/v1/models?view=client` | 不需要 | 能力元数据:`minimumPlan`、`pricing`、`reasoningEfforts`、`context_length`、`inputModalities` | +| `POST /provider/v1/*` | 需要(且套餐要含 API 权限) | Go 套餐一律 `403 upgrade_required` | + +## 上游来源 + +- `Mars-Sea/dsh-commandcode-provider`(MIT):`docs/agent-reference/adapter-protocol.md`、`buildCliBody()` / `handleCliEvent()`。 +- `patlux/pi-commandcode-provider`(MIT):0.7.12 的 `src/core.ts` / `src/converters.ts`(序列化器、事件解码、reasoning 回放、tool-call 配对与 id 缩短)。 + +本项目是在这两份实现基础上裁剪出「只服务 Go 套餐」的单链路版本。 diff --git a/extensions/commandcode-go.ts b/extensions/commandcode-go.ts new file mode 100644 index 0000000..b3cccbe --- /dev/null +++ b/extensions/commandcode-go.ts @@ -0,0 +1,1000 @@ +/** + * Command Code — Go 套餐专用 provider(只走 CLI `/alpha/generate` 传输) + * + * 为什么需要它:Command Code 的 Go 套餐没有官方 Provider API 权限, + * `/provider/v1/*` 一律回 `403 upgrade_required`。官方 CLI 自己走内部端点 + * `POST /alpha/generate`,本扩展把那套线协议搬到 pi 里:同一把 `user_...` key, + * 换传输而已。 + * + * 协议来源:dsh-commandcode-provider 的 generate 适配器 + * (docs/agent-reference/adapter-protocol.md,command-code@1.88.5 复验), + * 与 pi-commandcode-provider@0.7.12 的 core/converters(MIT)同源。 + * + * 只实现一件事:注册 commandcode-go 模型 + `/alpha/generate` 流式对话。 + * 不做配额面板、多账号轮换、Provider API 兜底、图片卸载。 + * + * 触发词:commandcode go、Go 套餐当 API、alpha/generate、upgrade_required + */ + +import { createHash, randomUUID } from "node:crypto" +import { mkdirSync, readFileSync, writeFileSync } from "node:fs" +import { homedir } from "node:os" +import { join } from "node:path" + +import { + type Api, + type AssistantMessage, + type AssistantMessageEventStream, + createAssistantMessageEventStream, + getCurrentSystemPrompt, + getCurrentTools, + type Model, + type SimpleStreamOptions, + type StopReason, + type ThinkingLevelMap, + type TranscriptContext, + type Usage, +} from "@earendil-works/pi-ai/compat" +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent" + +// ============================================================================= +// Constants +// ============================================================================= + +const PROVIDER_ID = "commandcode-go" +const PROVIDER_NAME = "Command Code (Go / CLI generate)" + +const API_BASE = (process.env.COMMANDCODE_API_BASE ?? "https://api.commandcode.ai").replace(/\/+$/, "") +/** 请求头里伪装的官方 CLI 版本;1.88.5 是 dsh 侧最后复验过的值。 */ +const CLI_VERSION = "1.88.5" +/** `/alpha/generate` 的服务端上限(实测 200 704 起 400),这里按官方 CLI 的取值压到 131 072。 */ +const MAX_OUTPUT_TOKENS = 131072 +/** 网关拒绝超过 64 字符的 tool-call id。 */ +const TOOL_CALL_ID_LIMIT = 64 + +const MODELS_URL = `${API_BASE}/provider/v1/models?view=client` +const AGENT_DIR = join(homedir(), ".pi", "agent") +const CATALOG_CACHE = join(AGENT_DIR, "commandcode-go-catalog.json") +const THREAD_NAMESPACE = "pi-commandcode-go" + +// ============================================================================= +// Small helpers +// ============================================================================= + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value) +} + +function stringValue(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined +} + +function numberValue(value: unknown): number | undefined { + return typeof value === "number" && Number.isFinite(value) ? value : undefined +} + +function recordArray(value: unknown): readonly Record[] { + return Array.isArray(value) ? value.filter(isRecord) : [] +} + +function recordOrEmpty(value: unknown): Record { + if (isRecord(value)) return value + if (typeof value === "string") { + try { + const parsed: unknown = JSON.parse(value) + if (isRecord(parsed)) return parsed + } catch { + // 模型可能只吐出半截 JSON。 + } + } + return {} +} + +function defaultUsage(): Usage { + return { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + } +} + +function redact(message: string): string { + return message.replace(/\b(user_[A-Za-z0-9_-]{6,})/g, "[redacted]").slice(0, 500) +} + +// ============================================================================= +// Credentials +// ============================================================================= + +function usableKey(value: string | undefined): string | undefined { + const trimmed = value?.trim() + if (!trimmed) return undefined + if (/^\$?[A-Z0-9_]+$/.test(trimmed)) return undefined // 未解析的占位符 + return trimmed +} + +function keyFromAuthValue(value: unknown): string | undefined { + if (typeof value === "string") return usableKey(value) + if (!isRecord(value)) return undefined + return ( + usableKey(stringValue(value.key)) ?? + usableKey(stringValue(value.apiKey)) ?? + usableKey(stringValue(value.access)) + ) +} + +function readJson(path: string): unknown { + try { + return JSON.parse(readFileSync(path, "utf8")) as unknown + } catch { + return undefined + } +} + +/** + * 候选 key,按可信度排序:环境变量 → 官方 CLI 的 auth.json → pi 的 auth.json。 + * pi 里可能同时存在多把(不同 provider id),所以启动时会逐个验活。 + */ +function keyCandidates(): string[] { + const found: string[] = [] + const push = (key: string | undefined) => { + if (key && !found.includes(key)) found.push(key) + } + + for (const name of ["COMMAND_CODE_GO_API_KEY", "COMMAND_CODE_API_KEY", "COMMANDCODE_API_KEY"]) { + push(usableKey(process.env[name])) + } + + const cliAuth = readJson(join(homedir(), ".commandcode", "auth.json")) + if (isRecord(cliAuth)) { + for (const id of ["commandcode", "command-code"]) push(keyFromAuthValue(cliAuth[id])) + push(keyFromAuthValue(cliAuth)) + } + + const piAuth = readJson(join(AGENT_DIR, "auth.json")) + if (isRecord(piAuth)) { + for (const id of [PROVIDER_ID, "commandcode", "command-code"]) push(keyFromAuthValue(piAuth[id])) + } + + return found +} + +let resolvedKey: string | undefined + +function rememberedKey(): string | undefined { + resolvedKey = resolvedKey ?? keyCandidates()[0] + return resolvedKey +} + +/** 一次 whoami 判断 key 是否还活着(过期 key 会让整轮对话 401)。 */ +async function keyIsAlive(key: string): Promise { + try { + const response = await fetch(`${API_BASE}/alpha/whoami`, { + headers: { Authorization: `Bearer ${key}` }, + signal: AbortSignal.timeout(5000), + }) + return response.ok + } catch { + // 离线时不要卡住启动:当作可用,交给请求时报错。 + return true + } +} + +/** 启动时挑一把真的能用的 key;全都失效时返回 undefined,让 /login 接管。 */ +async function resolveStartupKey(): Promise { + for (const key of keyCandidates()) { + if (await keyIsAlive(key)) { + resolvedKey = key + return key + } + } + return undefined +} + +// ============================================================================= +// Model catalog +// ============================================================================= + +const PI_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const + +interface CatalogEntry { + id: string + name?: string + minimumPlan?: string | null + display?: { label?: string; group?: string } + context_length?: number + maxOutputTokens?: number | null + inputModalities?: string[] + reasoningEfforts?: string[] | null + pricing?: { + inputCost?: number + outputCost?: number + cacheReadCost?: number + cacheWriteCost?: number + } +} + +interface ChatModelConfig { + id: string + name: string + reasoning: boolean + thinkingLevelMap?: ThinkingLevelMap + input: ("text" | "image")[] + cost: { input: number; output: number; cacheRead: number; cacheWrite: number } + contextWindow: number + maxTokens: number +} + +function thinkingLevelMapFor(efforts: readonly string[]): ThinkingLevelMap | undefined { + if (efforts.length === 0) return undefined + const available = new Set(efforts) + const map: Record = {} + for (const level of PI_LEVELS) { + // 只声明上游真的接受的档位;其余置 null 让 pi 夹到最近的合法档位。 + map[level] = level !== "minimal" && available.has(level) ? level : null + } + return map as ThinkingLevelMap +} + +function toModelConfig(entry: CatalogEntry): ChatModelConfig | undefined { + if (!entry.id) return undefined + // 只保留 DeepSeek 系模型。 + if (!entry.id.startsWith("deepseek/")) return undefined + // 本扩展只为 Go 套餐而存在:上游明确标了其它档位的模型直接不注册, + // 否则选中就是 MODEL_NOT_IN_PLAN。 + if (entry.minimumPlan && entry.minimumPlan !== "individual-go") return undefined + const efforts = Array.isArray(entry.reasoningEfforts) ? entry.reasoningEfforts : [] + const contextWindow = entry.context_length && entry.context_length > 0 ? entry.context_length : 200_000 + const input = (entry.inputModalities ?? ["text"]).filter( + (m): m is "text" | "image" => m === "text" || m === "image", + ) + const pricing = entry.pricing ?? {} + + return { + id: entry.id, + name: entry.display?.label ?? entry.name ?? entry.id, + reasoning: efforts.length > 0, + ...(efforts.length > 0 ? { thinkingLevelMap: thinkingLevelMapFor(efforts) } : {}), + input: input.length > 0 ? input : ["text"], + cost: { + input: pricing.inputCost ?? 0, + output: pricing.outputCost ?? 0, + cacheRead: pricing.cacheReadCost ?? 0, + cacheWrite: pricing.cacheWriteCost ?? 0, + }, + contextWindow, + maxTokens: Math.min(entry.maxOutputTokens ?? MAX_OUTPUT_TOKENS, contextWindow, MAX_OUTPUT_TOKENS), + } +} + +function entriesToModels(entries: readonly CatalogEntry[]): ChatModelConfig[] { + const seen = new Set() + const models: ChatModelConfig[] = [] + for (const entry of entries) { + const model = toModelConfig(entry) + if (!model || seen.has(model.id)) continue + seen.add(model.id) + models.push(model) + } + return models +} + +/** 无网络、无缓存时的最小可用集,保证 `/model` 里不是空的。 */ +const FALLBACK_CATALOG: CatalogEntry[] = [ + { + id: "deepseek/deepseek-v4-flash", + name: "DeepSeek V4 Flash", + context_length: 1_000_000, + inputModalities: ["text"], + reasoningEfforts: ["off", "high", "max"], + pricing: { inputCost: 0.15, outputCost: 0.6, cacheReadCost: 0.003 }, + }, + { + id: "deepseek/deepseek-v4.1-flash-fast", + name: "DeepSeek V4.1 Flash Fast", + context_length: 1_000_000, + inputModalities: ["text", "image"], + reasoningEfforts: ["high", "max"], + pricing: { inputCost: 0.16, outputCost: 0.58 }, + }, +] + +async function loadCatalog(): Promise<{ models: ChatModelConfig[]; source: string }> { + const cached = readJson(CATALOG_CACHE) + if (Array.isArray((cached as { data?: unknown })?.data)) { + const models = entriesToModels((cached as { data: CatalogEntry[] }).data) + if (models.length > 0) return { models, source: "cache" } + } + + try { + const response = await fetch(MODELS_URL, { + headers: { "x-command-code-version": CLI_VERSION }, + signal: AbortSignal.timeout(10_000), + }) + if (!response.ok) throw new Error(`HTTP ${response.status}`) + const body = (await response.json()) as { data?: CatalogEntry[] } + const entries = Array.isArray(body.data) ? body.data : [] + const models = entriesToModels(entries) + if (models.length === 0) throw new Error("empty catalog") + persistCatalog(entries) + return { models, source: "live" } + } catch { + return { models: entriesToModels(FALLBACK_CATALOG), source: "fallback" } + } +} + +function persistCatalog(entries: readonly CatalogEntry[]): void { + try { + mkdirSync(AGENT_DIR, { recursive: true }) + writeFileSync(CATALOG_CACHE, JSON.stringify({ fetchedAt: new Date().toISOString(), data: entries }), "utf8") + } catch { + // 只读环境忽略。 + } +} + +// ============================================================================= +// Wire conversion (pi transcript → /alpha/generate) +// ============================================================================= + +function imageToCli(part: Record): Record { + const data = stringValue(part.data) + const mimeType = stringValue(part.mimeType) + if (!data || !mimeType) throw new Error("Invalid image content: expected base64 data and mimeType") + return { type: "image", image: `data:${mimeType};base64,${data}`, mimeType } +} + +function textOf(message: { content?: unknown }): string { + if (typeof message.content === "string") return message.content + return recordArray(message.content) + .filter((part) => part.type === "text") + .map((part) => stringValue(part.text) ?? "") + .join("\n") +} + +function imageParts(value: unknown): readonly Record[] { + return recordArray(value).filter((part) => part.type === "image") +} + +/** 映射 tool-call id:短 id 原样,超长 id 确定性缩短且保持配对。 */ +function toolCallIdMap(messages: readonly { role: string; content?: unknown; toolCallId?: string }[]) { + const referenced = new Set() + for (const message of messages) { + if (message.role === "assistant") { + for (const part of recordArray(message.content)) { + const id = stringValue(part.id) + if (part.type === "toolCall" && id) referenced.add(id) + } + } else if (message.role === "toolResult" && message.toolCallId) { + referenced.add(message.toolCallId) + } + } + + const used = new Set() + const mapped = new Map() + for (const id of referenced) { + if (id.length <= TOOL_CALL_ID_LIMIT) { + mapped.set(id, id) + used.add(id) + } + } + for (const id of referenced) { + if (mapped.has(id)) continue + const hash = createHash("sha256").update(id, "utf8").digest("hex").slice(0, 8) + let candidate = `${id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, TOOL_CALL_ID_LIMIT - 9)}_${hash}` + let attempt = 0 + while (used.has(candidate)) { + attempt += 1 + const suffix = createHash("sha256").update(`${id}#${attempt}`, "utf8").digest("hex").slice(0, 8) + candidate = `${id.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, TOOL_CALL_ID_LIMIT - 9)}_${suffix}` + } + mapped.set(id, candidate) + used.add(candidate) + } + return mapped +} + +type MessageLike = { + role: string + content?: unknown + toolCallId?: string + toolName?: string + isError?: boolean +} + +function messagesToCli(messages: readonly MessageLike[], allowImages: boolean): unknown[] { + const out: unknown[] = [] + const callIds = new Set() + const resultIds = new Set() + for (const message of messages) { + if (message.role === "assistant") { + for (const part of recordArray(message.content)) { + const id = stringValue(part.id) + if (part.type === "toolCall" && id) callIds.add(id) + } + } else if (message.role === "toolResult" && message.toolCallId) { + resultIds.add(message.toolCallId) + } + } + const wireIds = toolCallIdMap(messages) + const wireId = (id: string) => wireIds.get(id) ?? id + + for (let i = 0; i < messages.length; i++) { + const message = messages[i] + + if (message.role === "system") continue + + // developer(OMP 等宿主的插入消息)降级为 user,位置和内容不变。 + if (message.role === "user" || message.role === "developer") { + const parts = recordArray(message.content).flatMap((part) => { + if (part.type === "text") return [{ type: "text", text: stringValue(part.text) ?? "" }] + if (part.type === "image") { + if (!allowImages) throw new Error("Selected Command Code model does not support image input") + return [imageToCli(part)] + } + return [] + }) + out.push({ role: "user", content: parts }) + continue + } + + if (message.role === "assistant") { + const parts: unknown[] = [] + const missingResults: unknown[] = [] + for (const part of recordArray(message.content)) { + if (part.type === "text") { + parts.push({ type: "text", text: stringValue(part.text) ?? "" }) + } else if (part.type === "thinking") { + // 官方 CLI 的 toWireMessages 会把历史思考回放成 reasoning 块; + // 丢掉它,DeepSeek 思考模式下的工具循环会被服务端拒绝。 + parts.push({ type: "reasoning", text: stringValue(part.thinking) ?? "" }) + } else if (part.type === "toolCall") { + const rawId = stringValue(part.id) + if (!rawId) continue + const id = wireId(rawId) + const toolName = stringValue(part.name) ?? "" + parts.push({ type: "tool-call", toolCallId: id, toolName, input: recordOrEmpty(part.arguments) }) + if (!resultIds.has(rawId)) { + missingResults.push({ + type: "tool-result", + toolCallId: id, + toolName, + output: { type: "error-text", value: "No result — the tool call did not complete." }, + }) + } + } + } + if (parts.length > 0) out.push({ role: "assistant", content: parts }) + if (missingResults.length > 0) out.push({ role: "tool", content: missingResults }) + continue + } + + if (message.role === "toolResult") { + const pendingImages: Record[] = [] + let j = i + for (; j < messages.length && messages[j].role === "toolResult"; j++) { + const result = messages[j] + if (!result.toolCallId || !callIds.has(result.toolCallId)) continue + const images = imageParts(result.content) + const text = textOf(result) + const outputText = + text || (images.length > 0 && !allowImages ? "[Image omitted: model takes text only]" : "") + out.push({ + role: "tool", + content: [ + { + type: "tool-result", + toolCallId: wireId(result.toolCallId), + toolName: result.toolName, + output: result.isError + ? { type: "error-text", value: outputText } + : { type: "text", value: outputText }, + }, + ], + }) + if (images.length > 0 && allowImages) pendingImages.push(...images.map(imageToCli)) + } + i = j - 1 + if (pendingImages.length > 0) out.push({ role: "user", content: pendingImages }) + } + } + return out +} + +/** 工具参数 schema 必须对象根,否则服务端整轮 400。 */ +function normalizeToolSchema(parameters: unknown): Record { + if (!isRecord(parameters)) return { type: "object", properties: {}, additionalProperties: true } + const schema = parameters as Record + const type = schema.type + if (type === "object") return schema + if (Array.isArray(type) && type.includes("object")) return { ...schema, type: "object" } + if (type === undefined || type === null) { + if (schema.properties !== undefined || schema.required !== undefined) return { ...schema, type: "object" } + return { type: "object", properties: {}, additionalProperties: true } + } + return { type: "object", properties: {}, additionalProperties: true } +} + +function toolsToCli(tools: readonly { name: string; description?: string; parameters?: unknown }[]): unknown[] { + return tools.map((tool) => ({ + type: "function", + name: tool.name, + description: tool.description, + input_schema: normalizeToolSchema(tool.parameters), + })) +} + +// ============================================================================= +// Request shape +// ============================================================================= + +function projectSlug(pathName: string): string { + const slug = pathName + .toLowerCase() + .replace(/^[a-z]:/i, "") + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + return slug || "project" +} + +function threadIdFor(sessionId: string | undefined): string { + const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + if (!sessionId) return randomUUID() + if (uuid.test(sessionId)) return sessionId + const digest = createHash("sha1").update(THREAD_NAMESPACE).update("/session/").update(sessionId).digest() + digest[6] = ((digest[6] ?? 0) & 0x0f) | 0x80 + digest[8] = ((digest[8] ?? 0) & 0x3f) | 0x80 + const hex = digest.toString("hex", 0, 16) + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` +} + +function effortFor(model: Model, options: SimpleStreamOptions | undefined): string | undefined { + const level = options?.reasoning + if (!level || level === "off" || !model.reasoning) return undefined + const mapped = (model.thinkingLevelMap as Record | undefined)?.[level] + return typeof mapped === "string" && mapped !== "off" ? mapped : undefined +} + +// ============================================================================= +// Cost +// ============================================================================= + +const DEEPSEEK_V4_TIME_PRICED = new Set([ + "deepseek/deepseek-v4-pro", + "deepseek/deepseek-v4-flash", + "deepseek/deepseek-v4-flash-vision-exp", + "deepseek/deepseek-v4.1-flash", + "deepseek/deepseek-v4.1-flash-fast", +]) + +/** DeepSeek V4 工作日 01:00-04:00 / 06:00-10:00 UTC 是 2 倍峰时价。 */ +function isPeak(atMs: number): boolean { + const at = new Date(atMs) + const day = at.getUTCDay() + if (day === 0 || day === 6) return false + const hour = at.getUTCHours() + return (hour >= 1 && hour < 4) || (hour >= 6 && hour < 10) +} + +function applyCost(model: Model, usage: Usage, atMs: number): void { + let rates = model.cost + if (DEEPSEEK_V4_TIME_PRICED.has(model.id) && isPeak(atMs)) { + rates = { + ...rates, + input: rates.input * 2, + output: rates.output * 2, + cacheRead: rates.cacheRead * 2, + cacheWrite: rates.cacheWrite * 2, + } + } + usage.cost.input = (rates.input / 1_000_000) * usage.input + usage.cost.output = (rates.output / 1_000_000) * usage.output + usage.cost.cacheRead = (rates.cacheRead / 1_000_000) * usage.cacheRead + usage.cost.cacheWrite = (rates.cacheWrite / 1_000_000) * usage.cacheWrite + usage.cost.total = usage.cost.input + usage.cost.output + usage.cost.cacheRead + usage.cost.cacheWrite +} + +// ============================================================================= +// Stream +// ============================================================================= + +function mapFinishReason(reason: string | undefined): StopReason { + if (reason === "tool-calls" || reason === "tool_calls") return "toolUse" + if (reason === "length" || reason === "max_tokens" || reason === "max_tokens_reached") return "length" + return "stop" +} + +function parseStreamLine(line: string): unknown | undefined { + let trimmed = line.trim() + if (!trimmed || trimmed.startsWith(":") || trimmed.startsWith("event:")) return undefined + if (trimmed.startsWith("data:")) trimmed = trimmed.slice(5).trim() + if (!trimmed || trimmed === "[DONE]") return undefined + try { + return JSON.parse(trimmed) as unknown + } catch { + return undefined + } +} + +interface ToolCallContent { + type: "toolCall" + id: string + name: string + arguments: Record +} + +function streamGenerate( + model: Model, + context: TranscriptContext, + options?: SimpleStreamOptions, +): AssistantMessageEventStream { + const stream = createAssistantMessageEventStream() + + void (async () => { + const apiKey = usableKey(options?.apiKey) ?? rememberedKey() + const output: AssistantMessage = { + role: "assistant", + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: defaultUsage(), + stopReason: "pending", + timestamp: Date.now(), + } + + if (!apiKey) { + output.stopReason = "error" + output.errorMessage = + "No Command Code API key. Run /login (provider commandcode-go), set COMMAND_CODE_API_KEY, or configure ~/.commandcode/auth.json" + stream.push({ type: "error", reason: "error", error: output }) + stream.end() + return + } + + const controller = new AbortController() + const signal = options?.signal + const onAbort = () => controller.abort() + if (signal?.aborted) controller.abort() + else signal?.addEventListener("abort", onAbort, { once: true }) + + let textIndex = -1 + let textBuffer = "" + let thinkingIndex = -1 + let finished = false + let cacheWriteTokens: number | undefined + const streamingToolCalls = new Map() + + const endText = () => { + if (textIndex < 0) return + stream.push({ type: "text_end", contentIndex: textIndex, content: textBuffer, partial: output }) + textIndex = -1 + textBuffer = "" + } + + const endThinking = () => { + if (thinkingIndex < 0) return + const block = output.content[thinkingIndex] + if (block?.type === "thinking") { + stream.push({ + type: "thinking_end", + contentIndex: thinkingIndex, + content: block.thinking, + partial: output, + }) + } + thinkingIndex = -1 + } + + const handle = (event: unknown) => { + if (!isRecord(event)) return + switch (event.type) { + case "text-delta": { + endThinking() + const delta = stringValue(event.text) ?? "" + if (textIndex < 0) { + output.content.push({ type: "text", text: "" }) + textIndex = output.content.length - 1 + stream.push({ type: "text_start", contentIndex: textIndex, partial: output }) + } + textBuffer += delta + const block = output.content[textIndex] + if (block?.type === "text") block.text = textBuffer + stream.push({ type: "text_delta", contentIndex: textIndex, delta, partial: output }) + break + } + case "reasoning-start": { + endText() + break + } + case "reasoning-delta": { + endText() + const delta = stringValue(event.text) ?? "" + if (thinkingIndex < 0) { + output.content.push({ type: "thinking", thinking: "" }) + thinkingIndex = output.content.length - 1 + stream.push({ type: "thinking_start", contentIndex: thinkingIndex, partial: output }) + } + const block = output.content[thinkingIndex] + if (block?.type === "thinking") block.thinking += delta + stream.push({ type: "thinking_delta", contentIndex: thinkingIndex, delta, partial: output }) + break + } + case "reasoning-end": { + endThinking() + break + } + case "tool-input-start": { + endText() + endThinking() + const id = stringValue(event.id) + if (!id || streamingToolCalls.has(id)) break + const toolCall: ToolCallContent = { + type: "toolCall", + id, + name: stringValue(event.toolName) ?? "", + arguments: {}, + } + output.content.push(toolCall) + streamingToolCalls.set(id, { + contentIndex: output.content.length - 1, + toolCall, + args: "", + }) + stream.push({ type: "toolcall_start", contentIndex: output.content.length - 1, partial: output }) + break + } + case "tool-input-delta": { + const id = stringValue(event.id) + const delta = stringValue(event.delta) + const active = id ? streamingToolCalls.get(id) : undefined + if (!active || delta === undefined) break + active.args += delta + active.toolCall.arguments = recordOrEmpty(active.args) + stream.push({ + type: "toolcall_delta", + contentIndex: active.contentIndex, + delta, + partial: output, + }) + break + } + case "tool-call": { + endText() + endThinking() + const id = stringValue(event.toolCallId) ?? randomUUID() + const active = streamingToolCalls.get(id) + const toolCall: ToolCallContent = active?.toolCall ?? { + type: "toolCall", + id, + name: stringValue(event.toolName) ?? "", + arguments: {}, + } + toolCall.name = stringValue(event.toolName) ?? toolCall.name + toolCall.arguments = recordOrEmpty(event.input ?? event.args ?? event.arguments) + let contentIndex: number + if (active) { + contentIndex = active.contentIndex + streamingToolCalls.delete(id) + } else { + output.content.push(toolCall) + contentIndex = output.content.length - 1 + stream.push({ type: "toolcall_start", contentIndex, partial: output }) + } + stream.push({ type: "toolcall_end", contentIndex, toolCall, partial: output }) + break + } + case "cache-write-tokens": { + const value = numberValue(event.cacheWriteTokens) + if (value !== undefined && value >= 0) cacheWriteTokens = value + break + } + case "finish": { + endText() + endThinking() + const usage = isRecord(event.totalUsage) ? event.totalUsage : undefined + const details = usage && isRecord(usage.inputTokenDetails) ? usage.inputTokenDetails : undefined + const totalInput = numberValue(usage?.inputTokens) ?? 0 + const cacheRead = numberValue(details?.cacheReadTokens) ?? 0 + const reportedWrite = numberValue(details?.cacheWriteTokens) ?? 0 + const cacheWrite = reportedWrite === 0 && cacheWriteTokens !== undefined ? cacheWriteTokens : reportedWrite + output.usage.input = + numberValue(details?.noCacheTokens) ?? Math.max(0, totalInput - cacheRead - cacheWrite) + output.usage.output = numberValue(usage?.outputTokens) ?? 0 + output.usage.cacheRead = cacheRead + output.usage.cacheWrite = cacheWrite + output.usage.totalTokens = + output.usage.input + output.usage.output + output.usage.cacheRead + output.usage.cacheWrite + const reasoning = numberValue( + (isRecord(usage?.outputTokenDetails) ? usage?.outputTokenDetails.reasoningTokens : undefined) ?? + usage?.reasoningTokens, + ) + if (reasoning !== undefined) output.usage.reasoning = reasoning + applyCost(model, output.usage, output.timestamp) + output.stopReason = mapFinishReason(stringValue(event.finishReason)) + finished = true + break + } + case "error": { + const message = + stringValue((isRecord(event.error) ? event.error.message : undefined) ?? undefined) ?? + stringValue(event.message) ?? + "Stream error" + throw new Error(message) + } + case "abort": { + throw Object.assign(new Error("Request aborted"), { name: "AbortError" }) + } + default: + break + } + } + + try { + stream.push({ type: "start", partial: output }) + + const systemText = getCurrentSystemPrompt(context.messages) + const tools = getCurrentTools(context.messages) + const allowImages = model.input?.includes("image") ?? false + + const body = { + config: { + workingDir: process.cwd(), + date: new Date().toISOString().split("T")[0], + environment: `${process.platform}-${process.arch}, Node.js ${process.version}`, + structure: [], + isGitRepo: false, + currentBranch: "", + mainBranch: "", + gitStatus: "", + recentCommits: [], + }, + memory: null, + taste: null, + skills: null, + permissionMode: "standard", + params: { + model: model.id, + messages: messagesToCli(context.messages as readonly MessageLike[], allowImages), + tools: toolsToCli(tools), + system: systemText ? [{ type: "text", text: systemText, cache_control: { type: "ephemeral" } }] : "", + max_tokens: Math.min(options?.maxTokens ?? model.maxTokens, model.maxTokens, MAX_OUTPUT_TOKENS), + ...(options?.temperature !== undefined ? { temperature: options.temperature } : {}), + stream: true, + ...(() => { + const effort = effortFor(model, options) + return effort ? { reasoning_effort: effort } : {} + })(), + }, + threadId: threadIdFor(options?.sessionId), + } + + const zdr = process.env.CMD_ZDR === "1" || process.env.COMMANDCODE_ZDR === "1" + const headers: Record = { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + "x-command-code-version": CLI_VERSION, + "x-cli-environment": "production", + "x-project-slug": projectSlug(process.cwd()), + "x-taste-learning": "false", + "x-co-flag": "false", + "User-Agent": "cli", + ...(options?.sessionId ? { "x-session-id": options.sessionId } : {}), + ...(zdr ? { "x-cmd-zdr": "1" } : {}), + } + + const response = await fetch(`${API_BASE}/alpha/generate`, { + method: "POST", + headers, + body: JSON.stringify(body), + signal: controller.signal, + }) + + await options?.onResponse?.({ status: response.status, headers: Object.fromEntries(response.headers) }, model) + + if (!response.ok) { + const raw = await response.text().catch(() => "") + let detail = raw + let code: string | undefined + try { + const parsed: unknown = JSON.parse(raw) + if (isRecord(parsed)) { + detail = stringValue(parsed.message) ?? raw + const error = isRecord(parsed.error) ? parsed.error : parsed + code = stringValue(error.code) + detail = stringValue(error.message) ?? detail + } + } catch { + // 纯文本错误体原样保留。 + } + const hint = + code === "MODEL_NOT_IN_PLAN" + ? " (该模型不在 Go 套餐内,换一个模型)" + : code === "UNAUTHORIZED" + ? " (key 已过期,运行 cmd login 或 /login 重新获取)" + : code === "upgrade_required" + ? " (Go 套餐无 Provider API 权限,本扩展应只走 /alpha/generate)" + : "" + throw new Error(`Command Code API error ${response.status}${hint}: ${redact(detail)}`) + } + + const reader = response.body?.getReader() + if (!reader) throw new Error("No response body") + const decoder = new TextDecoder() + let buffer = "" + readLoop: for (;;) { + if (controller.signal.aborted) throw Object.assign(new Error("Request aborted"), { name: "AbortError" }) + const { done, value } = await reader.read() + if (done) { + if (buffer.trim()) handle(parseStreamLine(buffer)) + if (!finished) throw new Error("Stream ended unexpectedly before completion (no finish event)") + break + } + buffer += decoder.decode(value, { stream: true }) + const lines = buffer.split("\n") + buffer = lines.pop() ?? "" + for (const line of lines) { + handle(parseStreamLine(line)) + if (finished) break readLoop + } + } + + if (!finished) throw new Error("Stream ended unexpectedly before completion (no finish event)") + endText() + endThinking() + + const reason = output.stopReason + if (reason === "error" || reason === "aborted" || reason === "pending") output.stopReason = "stop" + stream.push({ + type: "done", + reason: output.stopReason as "stop" | "length" | "toolUse" | "deferred", + message: output, + }) + stream.end() + } catch (error) { + const aborted = controller.signal.aborted || (error instanceof Error && error.name === "AbortError") + output.stopReason = aborted ? "aborted" : "error" + output.errorMessage = aborted + ? "Request aborted" + : redact(error instanceof Error ? error.message : String(error)) + stream.push({ type: "error", reason: aborted ? "aborted" : "error", error: output }) + stream.end() + } finally { + signal?.removeEventListener("abort", onAbort) + } + })() + + return stream +} + +// ============================================================================= +// Extension entry point +// ============================================================================= + +export default async function (pi: ExtensionAPI) { + const [{ models }, startupKey] = await Promise.all([loadCatalog(), resolveStartupKey()]) + + pi.registerProvider(PROVIDER_ID, { + name: PROVIDER_NAME, + baseUrl: API_BASE, + // 验活过的 key 直接内联;全失效时留占位符,让 /login 的 + // “Enter API key” 提示把新 key 存进 auth.json。 + apiKey: startupKey ?? "$COMMAND_CODE_GO_API_KEY", + api: "commandcode-generate", + models, + streamSimple: streamGenerate, + }) + + pi.registerCommand("commandcode-go-status", { + description: "显示 Command Code Go provider 的模型数量与凭据来源", + handler: async (_args, ctx) => { + const key = rememberedKey() + ctx.ui.notify( + `${PROVIDER_NAME}\n模型 ${models.length} 个\n端点 ${API_BASE}/alpha/generate\n凭据 ${key ? `${key.slice(0, 8)}…` : "未找到"}`, + "info", + ) + }, + }) +} diff --git a/extensions/commandcode-transient-retry.ts b/extensions/commandcode-transient-retry.ts new file mode 100644 index 0000000..8fa2e37 --- /dev/null +++ b/extensions/commandcode-transient-retry.ts @@ -0,0 +1,56 @@ +/** + * Auto-retry Command Code's transient HTTP 400s. + * + * Command Code's gateway occasionally rejects an otherwise valid request with + * a generic, server-side 400 — on the native Provider API + * (`/provider/v1/responses`) and on the `/alpha/generate` fallback alike: + * + * commandcode API error (400): {"message":"{\"type\":\"invalid_request_error\", + * \"code\":\"\",\"message\":\"invalid request error trace_id: \"}\n", + * "type":"invalid_request_error"} + * + * The request is well formed and the identical payload succeeds on replay, so + * this is a transient upstream failure, not a client error. Pi only retries + * assistant errors whose message matches its transient-error classifier + * (`isRetryableAssistantError`), and a bare 400 does not match. Rewriting the + * finalized message to carry the classifier's "server error" marker lets Pi's + * built-in auto-retry (settings.retry: 3 attempts with backoff) handle it + * transparently. + * + * Scope is deliberately narrow — provider `commandcode` + HTTP 400 + the + * gateway's `invalid_request_error` signature — so genuine client-side 400s + * are not blanket-retried. + */ + +import type { ExtensionAPI } from "@earendil-works/pi-coding-agent" + +const COMMAND_CODE_ERROR = /\bcommand[ -]?code API error\b/i +const COMMAND_CODE_PROVIDERS = new Set(["commandcode", "command-code", "commandcode-go"]) +const HTTP_400 = /\b400\b/ +const TRANSIENT_SIGNATURE = /invalid request error trace_id|"type"\s*:\s*"invalid_request_error"/i +// Already matches one of Pi's retryable patterns: leave the message untouched. +const ALREADY_RETRYABLE = + /server.?error|internal.?error|overloaded|rate.?limit|too many requests|\b(?:408|409|429|5\d\d)\b/i +const RETRY_MARKER = + " [transient Command Code gateway error; treated as server error, auto-retrying]" + +export default function (pi: ExtensionAPI) { + pi.on("message_end", async (event, ctx) => { + const message = event.message + if (!message || message.role !== "assistant") return + if (message.stopReason !== "error") return + if ( + !COMMAND_CODE_PROVIDERS.has(message.provider ?? "") && + !COMMAND_CODE_PROVIDERS.has(ctx.model?.provider ?? "") + ) + return + + const errorMessage = message.errorMessage + if (typeof errorMessage !== "string" || errorMessage.length === 0) return + if (!COMMAND_CODE_ERROR.test(errorMessage) || !HTTP_400.test(errorMessage)) return + if (!TRANSIENT_SIGNATURE.test(errorMessage)) return + if (ALREADY_RETRYABLE.test(errorMessage) || errorMessage.includes(RETRY_MARKER)) return + + return { message: { ...message, errorMessage: errorMessage + RETRY_MARKER } } + }) +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..fcd62c6 --- /dev/null +++ b/package.json @@ -0,0 +1,32 @@ +{ + "name": "commandcode-pi", + "version": "0.1.0", + "description": "pi provider for the Command Code Go plan: registers DeepSeek models and streams over the CLI /alpha/generate transport", + "type": "module", + "keywords": [ + "pi-package", + "pi-extension", + "commandcode", + "provider", + "deepseek" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+ssh://git@git.cat-shark.xyz:2222/cat-shark/commandcode-pi.git" + }, + "pi": { + "extensions": [ + "./extensions/commandcode-go.ts", + "./extensions/commandcode-transient-retry.ts" + ], + "changelogPath": "./CHANGELOG.md" + }, + "peerDependencies": { + "@earendil-works/pi-ai": "*", + "@earendil-works/pi-coding-agent": "*" + }, + "engines": { + "node": ">=20" + } +}