Files
pi-commandcode-provider/index.ts
T
Omar Iqbal Naru 1e0dd1189c fix(core): register custom api under non-reserved name for omp 17.4.0
omp 17.4.0's host registry rejects registerCustomApi calls under
built-in api names ("Cannot register custom API '<name>': built-in
API names are reserved"). The provider and its models registered
under "openai-completions", so the extension failed to load.

Register under "commandcode-custom" instead (matches the published
npm build) and restore the real wire api via apiForModelId before
dispatching to the native compat stream inside the transport router.

The host's model registry also stores provider-supplied compat under
model.compatConfig internally, only copying it back to model.compat
inside its own dispatch-time patches. Since the transport router calls
the native compat stream directly, it must read compatConfig itself or
requests crash with 'baseCompat is undefined' before any network call.

Verified against a local mock Provider API server with the extension
linked into omp 17.4.0: model discovery lists all Command Code models,
and a streamed chat completion sends the resolved x-cmd-zdr header and
Authorization header end to end.
2026-08-21 19:41:54 +05:00

142 lines
4.6 KiB
TypeScript

/**
* Command Code provider for pi.
*
* Uses Command Code's documented Provider API:
* https://api.commandcode.ai/provider/v1
*/
import { AssistantMessageEventStream } from "@earendil-works/pi-ai"
import { streamSimple as streamNativeProvider } from "@earendil-works/pi-ai/compat"
import {
getAgentDir,
type ExtensionAPI,
type ExtensionCommandContext,
type ProviderConfig,
} from "@earendil-works/pi-coding-agent"
import { join } from "node:path"
import { getConfiguredApiKey } from "./src/api-key.ts"
import { createStreamCommandCode } from "./src/core.ts"
import { calculateCommandCodeCost } from "./src/cost.ts"
import {
apiForModelId,
baseUrlForModel,
DEFAULT_MODELS_URL,
DEFAULT_PROVIDER_API_BASE,
getModelsTimeoutMs,
inputModalitiesForModel,
loadCommandCodeModels,
thinkingMetadataForModel,
type CommandCodeModel,
} from "./src/models.ts"
import { getApiKey as getOAuthApiKey, login, refreshToken } from "./src/oauth.ts"
import { normalizeCommandCodeMessage } from "./src/overflow.ts"
import { MODEL_COSTS, ZERO_MODEL_COST } from "./src/pricing.ts"
import { createCommandCodeRuntime } from "./src/runtime.ts"
import { createCommandCodeTransportRouter } from "./src/transport.ts"
function commandCodeHeaders(): Record<string, string> | undefined {
if (process.env.COMMANDCODE_ZDR === "1") {
return { "x-cmd-zdr": "1" }
}
return undefined
}
function createProviderConfig(
models: readonly CommandCodeModel[],
apiBase: string,
streamCommandCode: ProviderConfig["streamSimple"],
): ProviderConfig {
const headers = commandCodeHeaders()
return {
name: "Command Code",
baseUrl: apiBase,
apiKey: getConfiguredApiKey() ?? "$COMMANDCODE_API_KEY",
api: "commandcode-custom",
streamSimple: streamCommandCode,
headers,
oauth: {
name: "Command Code",
login,
refreshToken,
getApiKey: getOAuthApiKey,
},
models: models.map((model) => ({
id: model.id,
name: model.name,
api: "commandcode-custom",
baseUrl: baseUrlForModel(apiBase, model.api),
reasoning: model.reasoning,
...(thinkingMetadataForModel(model.id) ?? {}),
input: [...inputModalitiesForModel(model.id)],
cost: MODEL_COSTS[model.id] ?? ZERO_MODEL_COST,
contextWindow: model.contextWindow,
maxTokens: model.maxTokens,
headers,
compat:
model.api === "openai-completions"
? {
supportsStore: false,
supportsDeveloperRole: false,
supportsReasoningEffort: true,
maxTokensField: "max_tokens",
}
: {
supportsEagerToolInputStreaming: false,
supportsLongCacheRetention: false,
supportsCacheControlOnTools: false,
supportsToolReferences: false,
...(model.reasoning ? { forceAdaptiveThinking: true } : {}),
},
})),
}
}
function legacyApiBase(providerApiBase: string): string {
return providerApiBase.replace(/\/provider\/v1\/?$/, "")
}
export default async function (pi: ExtensionAPI) {
const apiBase = process.env.COMMANDCODE_API_BASE ?? DEFAULT_PROVIDER_API_BASE
const modelsUrl = process.env.COMMANDCODE_MODELS_URL ?? DEFAULT_MODELS_URL
const modelsTimeoutMs = getModelsTimeoutMs()
const modelsCachePath =
process.env.COMMANDCODE_MODELS_CACHE ?? join(getAgentDir(), "commandcode-models.json")
const streamGenerate = createStreamCommandCode({
createStream: () => new AssistantMessageEventStream(),
calculateCost: calculateCommandCodeCost,
apiBase: legacyApiBase(apiBase),
})
const transport = createCommandCodeTransportRouter({
createStream: () => new AssistantMessageEventStream(),
streamProvider: (model, context, options) =>
streamNativeProvider(
{ ...model, api: apiForModelId(model.id), compat: model.compatConfig ?? model.compat },
context,
options,
),
streamGenerate,
})
pi.on("message_end", async (event, ctx) => {
if (event.message.role !== "assistant") return
const normalized = normalizeCommandCodeMessage(event.message, ctx.model?.provider)
return normalized ? { message: normalized.message } : undefined
})
const runtime = createCommandCodeRuntime<ProviderConfig, ExtensionCommandContext>(pi, {
endpoint: modelsUrl,
cachePath: modelsCachePath,
loadModels: () =>
loadCommandCodeModels({
url: modelsUrl,
cachePath: modelsCachePath,
timeoutMs: modelsTimeoutMs,
}),
createProviderConfig: (models) => createProviderConfig(models, apiBase, transport.stream),
getTransport: transport.getTransport,
})
await runtime.initialize()
}