@volter/twin-moonshot
v0.1.37
Published
Local Moonshot (Kimi) twin — a faithful, stateful local Moonshot Platform API your real `openai` / `anthropic` SDKs (swapped base URL) talk to unmodified. The model is stubbed (deterministic), but the protocol envelope across three inference protocols (Op
Readme
@volter/twin-moonshot
A local, faithful Moonshot (Kimi) Platform API twin your real openai / anthropic SDKs talk
to unmodified — Moonshot ships no SDK of its own, and its documented integration path is the
standard SDKs with a swapped base URL (platform.kimi.ai/docs/overview, read 2026-09-16). Point the
client at the twin and chat completions, Responses, the Anthropic-compatible Messages surface,
streaming, models, files, batches, the account balance, token counting and signature verify
all work. Built on the shared @volter/world-core kernel (durable event/action log + projection);
no parallel side store.
import OpenAI from 'openai';
import { createMoonshotTwinServer } from '@volter/twin-moonshot';
const { port } = createMoonshotTwinServer({});
// Moonshot's base URL carries the version segment — the SDK builds every URL as
// `${baseURL}/chat/completions`.
const client = new OpenAI({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}/v1` });
const res = await client.chat.completions.create({
model: 'kimi-k3',
messages: [{ role: 'user', content: 'hello' }],
});
// res.choices[0].message.content starts with "[twin-stub:kimi-k3]" — a deterministic stub,
// clearly labeled. res.usage carries Moonshot's FLAT cache split: usage.cached_tokens, not
// OpenAI's nested prompt_tokens_details.cached_tokens.The Anthropic-compatible surface is a base-URL suffix, exactly as on the real vendor:
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}/anthropic` });Moonshot is not OpenAI — the differences this twin models
Moonshot exposes an OpenAI-compatible surface, and treating "compatible" as "identical" is how a Moonshot twin gets built wrong. The load-bearing differences, each grounded in Moonshot's own OpenAPI 3.1.0 document (platform.kimi.ai/docs/openapi.json) and platform.kimi.ai/docs/{overview,api-reference,errors,models,pricing/limits,guides/context-caching}, all read 2026-09-16:
| | Moonshot | OpenAI |
|---|---|---|
| base path | https://api.moonshot.ai/v1/… (version segment in the base) | https://api.openai.com/v1/… |
| second surface | /anthropic/v1/messages — the Anthropic-compatible Messages protocol on the SAME host | — |
| usage cache split | FLAT usage.cached_tokens | nested prompt_tokens_details.cached_tokens |
| streaming usage | the usage tail chunk (empty choices[], whole usage object), then data: [DONE] — unconditional, per the OpenAPI's ChatCompletionChunk.usage ("Object in the final chunk with usage, null in ordinary chunks"); the prose chat doc mentions the chunk under stream_options.include_usage, so the two first-party sources disagree and the OpenAPI governs | opt-in extra chunk via stream_options.include_usage |
| response signing | Msh-Request-Timestamp + Msh-Request-Signature (reqsigv1_…) headers on STREAMED model calls that carry X-Msh-Request-Nonce (a nonce-less call proceeds unsigned), verifiable at POST /v1/signatures/verify | — |
| retired models | moonshot-v1-*, kimi-latest, kimi-k2 are gone from the catalog — a stale client 400s/404s here like it does at the vendor | old ids keep serving |
| thinking | thinking object per-model: kimi-k2.6 takes {type:'enabled'\|'disabled', keep}; kimi-k2.7-code refuses 'disabled'; kimi-k3 has no thinking parameter | — |
| reasoning | reasoning_content on the assistant message (and its own delta before content when streaming) | reasoning (Responses only) |
| reasoning_effort | kimi-k3-only, closed set 'low'\|'high'\|'max' | all reasoning models |
| dynamic tools | kimi-k3 accepts a system message carrying tools and no content (dynamic tool loading); any other role is a 400 | — |
| error envelope | { error: { message, type, … } } with Moonshot's own type names (invalid_authentication_error, rate_limit_reached_error, server_unavailable, …) | { error: { message, type, param, code } } |
| balance | GET /v1/users/me/balance — its own envelope {code, data:{cash_balance,voucher_balance,…}, scode, status} | — |
| token counting | POST /v1/tokenizers/estimate-token-count — a first-class endpoint, one tokenizer shared with chat's prompt_tokens | — |
| statuses | 429 rate_limit_reached_error with the documented X-RateLimit-* header family; 503 server_unavailable | different type names |
The twin serves /v1/… and /anthropic/v1/…. A request to the bare root (no version segment)
404s, because Moonshot does not serve it either.
The generative-stub design (be honest)
The twin cannot run the model — there are no weights here. So all three inference endpoints
(POST /v1/chat/completions, POST /v1/responses, POST /anthropic/v1/messages) return a
deterministic STUB completion that is unmistakably a twin stub (it carries a
[twin-stub:<model>] marker and echoes your prompt), and the web-search tool endpoints return
deterministic labeled results. They never pretend to be real model output.
What is faithful is the entire protocol envelope:
- chat response shape —
{ id:'chatcmpl-twin-…', object:'chat.completion', created, model, choices:[{index, message:{role:'assistant', content, reasoning_content?}, finish_reason}], usage:{prompt_tokens, completion_tokens, total_tokens, cached_tokens} } - streaming via SSE — role delta →
reasoning_contentdelta → content deltas → tool-call deltas → finish_reason chunk → Moonshot's empty-choices usage tail →data: [DONE](driven through an injected sink — no real sockets in the handler) - Responses — the Responses envelope (object
response, output items,usage.input_tokens_details.cached_tokens),reasoning.effort,max_output_tokens→incomplete, and its own SSE grammar (response.created→output_item.added/done→response.completed,sequence_numberfrom 0) - Messages (Anthropic-compatible) —
{type:'message', content blocks, stop_reason, usage}with a thinking block first, top-levelsystem,stop_sequences(≤5, ≤32 bytes), and the Anthropic SSE grammar (message_start→ thinking/text deltas →message_delta→message_stop, no[DONE]sentinel); kimi-k2.x refused with the Messages error envelope, never the/v1shape - tool / function calling —
tool_calls+finish_reason:'tool_calls',tool_choice(none/named), schema-shaped JSON arguments, tool-result turns, tool-name regex^[a-zA-Z_][a-zA-Z0-9-_]{0,127}$ - structured outputs —
response_formatjson_object/json_schema(name + schema required) yield JSON stub content max_completion_tokens/max_tokens(→finish_reason:'length'; 0 is a 400),stop(earliest hit, ≤5 entries ≤32 bytes),logprobs/top_logprobs(accepted 0..20;top_logprobswithoutlogprobs:trueis a 400),prompt_cache_key, multi-turn history, system messages counted intoprompt_tokens, vision gating (image parts on kimi-k3/kimi-k2.6, refused on kimi-k2.7-code), context-window overflow as a 400- deterministic usage — an identical request replays byte-identically
The genuinely stateful + static surface is real, not a stub:
GET /v1/models(+/models/:id) — the static catalog (kimi-k3, kimi-k2.7-code, kimi-k2.7-code-highspeed, kimi-k2.6); retired ids are NOT served- Files —
POST/GET/DELETE /v1/files(+/content), kernel-backed, purpose closed set, and a dirty-state proof that a deleted id is never re-minted.POST /v1/filesis multipart on the real vendor and the server accepts the real multipart form (binary uploads travel base64 under the server's privatebinary_contentmarker andGET /contentdecodes before serving; text files round-trip byte for byte); a form with nofilepart is refused, and a pulled file's content read answers 501 — the vendor's list endpoint returns no content, so the twin honestly holds none - Batches —
POST/GET /v1/batches(+ retrieve + cancel →cancelling,cancelling_atset, double cancel refused), input validated against an existing batch-purpose file,endpointandcompletion_windowclosed sets - Balance —
GET /v1/users/me/balancein Moonshot's own envelope shape - Token counting —
POST /v1/tokenizers/estimate-token-count→{data:{total_tokens}}, and the estimate equals chat'sprompt_tokensfor the same input (one tokenizer, two doors) - Signature verify —
POST /v1/signatures/verifyrecomputes the tuple; the server signs streamed model calls withMsh-Request-Timestamp/Msh-Request-Signature - Web search tools —
POST /v1/tools/search(limit 1..20),/v1/tools/search_pro(sites ≤5,time_windowvalidated),/v1/tools/fetch(http(s) URLs only)
Vendor-shaped errors throughout: 400 / 401 / 404 / 405 (read-only guard) / 429 / 500 /
503. Every /v1 envelope carries message + type and only keys Moonshot's own error table
declares; the Messages surface answers {type:'error', error:{type,message}}.
Connector (pull / push)
syncMoonshotFromReal pulls real models / files / batches / balance into the twin;
pushPendingMoonshotActions pushes pending local writes (create / cancel / delete) to the real API
and confirms them. All vendor I/O is over an injected client (liveMoonshotExecute(apiKey)
live; a fake in tests) — the pack holds no key and imports no SDK at runtime. Every live call is
charged against the shared kernel RateBudget before it goes out, and the executor refuses any
path outside /v1/ and /anthropic/v1/ before the budget is even charged.
The rate budget's declaration is grounded in Moonshot's published tier table
(platform.kimi.ai/docs/pricing/limits, read 2026-09-16): the LOWEST published row (Tier 0: RPM 3)
is an order of magnitude under the kernel's 30-calls/minute fallback, so the ceiling is pinned AT
the fallback and spent downward — the three inference endpoints and the three web-search endpoints
(Moonshot meters the latter on their own QPS pool) price at 6 units each, reads at 2. A real 429's
X-RateLimit-* headers arm a persisted cooldown that makes later calls fail fast without touching
the vendor.
Coverage
Partial and honest. The capability manifest is the real Moonshot Platform API surface as the
denominator — enumerated from Moonshot's own OpenAPI 3.1.0 document (19 operations) reconciled
against the prose docs, with the spec census
(moonshot-spec-census.json) holding the exact bijection — not a list of what was built. The
measurement lives in the repo-root coverage table (README.md /
../../../docs/contributing/conformance.md, regenerated by
bun scripts/twin-capabilities.ts --write-docs moonshot); run
bun scripts/manifest-baseline-one.ts moonshot for this pack alone.
The remaining todos are real surface: per-request response ids (the twin derives id from a hash
of the request, so two identical calls share one id), the asynchronous cancelling → cancelled
batch settlement (settling on a READ would break the read-only contract), the multipart file-create
push (the JSON executor cannot express a multipart body — the push is REFUSED rather than faked),
and the unpushable-action drain (a permanently-unpushable action can never be acknowledged, so
pendingActions never reaches empty).
No UI mirror
Moonshot is an API-first vendor: an integrator POSTs /v1/chat/completions from code, and
platform.kimi.ai is a keys/billing/usage console — incidental tooling, not where the work happens.
So this pack ships no client/ mirror and declares no UI capabilities. This matches the sibling
generative packs (openai, anthropic, deepseek, groq, xai).
Scenario scripting (twin-only)
The three inference endpoints can be scripted by MSW-shaped handlers in a world dir's
handlers/moonshot.json, run by the ONE kernel scenario engine with this pack's adapter:
{ "handlers": [
{ "on": { "userTextIncludes": "summarize", "hasTool": "search_docs" },
"respond": { "text": "Scripted summary.", "reasoning": "scripted reasoning_content" }, "once": true },
{ "on": { "thinkingTypeEquals": "disabled" }, "respond": { "error": { "type": "rate_limit_reached_error" } } }
] }Load it with createMoonshotTwinServer({ scenarioPath }) / TWIN_MOONSHOT_SCENARIO. The read
doors GET /twin and GET /twin/scenario explain and inspect it. A malformed file throws at
load, never a silent fall-back. Scenario support is twin-only scaffolding for eval worlds, not
vendor surface — it is kept OUT of the capability manifest (the coverage count above excludes
it) and gated by src/moonshot-scenario.test.ts, including the kernel's fault grammar.
CLI
world-moonshot serve [--port N] [--root DIR] [--read-only] [--scenario FILE]
world-moonshot conformanceBoth read their state root from VOLTER_STATE_DIR (--root overrides).
