从 ~/.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 + 上游署名)
1001 lines
34 KiB
TypeScript
1001 lines
34 KiB
TypeScript
/**
|
||
* 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<string, unknown> {
|
||
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<string, unknown>[] {
|
||
return Array.isArray(value) ? value.filter(isRecord) : []
|
||
}
|
||
|
||
function recordOrEmpty(value: unknown): Record<string, unknown> {
|
||
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<boolean> {
|
||
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<string | undefined> {
|
||
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<string, string | null> = {}
|
||
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<string>()
|
||
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<string, unknown>): Record<string, string> {
|
||
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<string, unknown>[] {
|
||
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<string>()
|
||
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<string>()
|
||
const mapped = new Map<string, string>()
|
||
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<string>()
|
||
const resultIds = new Set<string>()
|
||
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<string, string>[] = []
|
||
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<string, unknown> {
|
||
if (!isRecord(parameters)) return { type: "object", properties: {}, additionalProperties: true }
|
||
const schema = parameters as Record<string, unknown>
|
||
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<Api>, options: SimpleStreamOptions | undefined): string | undefined {
|
||
const level = options?.reasoning
|
||
if (!level || level === "off" || !model.reasoning) return undefined
|
||
const mapped = (model.thinkingLevelMap as Record<string, string | null> | 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<Api>, 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<string, unknown>
|
||
}
|
||
|
||
function streamGenerate(
|
||
model: Model<Api>,
|
||
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<string, { contentIndex: number; toolCall: ToolCallContent; args: string }>()
|
||
|
||
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<string, string> = {
|
||
"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",
|
||
)
|
||
},
|
||
})
|
||
}
|