@volter/twin-moonshot 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +164 -0
  3. package/dist/src/cli.d.ts +2 -0
  4. package/dist/src/cli.js +25 -0
  5. package/dist/src/index.d.ts +14 -0
  6. package/dist/src/index.js +86 -0
  7. package/dist/src/moonshot-budget.d.ts +57 -0
  8. package/dist/src/moonshot-budget.js +142 -0
  9. package/dist/src/moonshot-capabilities.d.ts +4 -0
  10. package/dist/src/moonshot-capabilities.js +1200 -0
  11. package/dist/src/moonshot-conformance.d.ts +14 -0
  12. package/dist/src/moonshot-conformance.js +405 -0
  13. package/dist/src/moonshot-connector.d.ts +168 -0
  14. package/dist/src/moonshot-connector.js +416 -0
  15. package/dist/src/moonshot-models.d.ts +36 -0
  16. package/dist/src/moonshot-models.js +37 -0
  17. package/dist/src/moonshot-scenario.d.ts +54 -0
  18. package/dist/src/moonshot-scenario.js +175 -0
  19. package/dist/src/moonshot-server.d.ts +13 -0
  20. package/dist/src/moonshot-server.js +202 -0
  21. package/dist/src/moonshot-stub.d.ts +70 -0
  22. package/dist/src/moonshot-stub.js +222 -0
  23. package/dist/src/moonshot-twin.d.ts +144 -0
  24. package/dist/src/moonshot-twin.js +1647 -0
  25. package/dist/src/moonshot-types.d.ts +251 -0
  26. package/dist/src/moonshot-types.js +19 -0
  27. package/package.json +53 -0
  28. package/src/cli.ts +25 -0
  29. package/src/index.ts +129 -0
  30. package/src/moonshot-budget.ts +163 -0
  31. package/src/moonshot-capabilities.ts +1220 -0
  32. package/src/moonshot-conformance.ts +416 -0
  33. package/src/moonshot-connector.ts +465 -0
  34. package/src/moonshot-models.ts +89 -0
  35. package/src/moonshot-scenario.ts +194 -0
  36. package/src/moonshot-server.ts +220 -0
  37. package/src/moonshot-stub.ts +230 -0
  38. package/src/moonshot-twin.ts +1670 -0
  39. package/src/moonshot-types.ts +225 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,164 @@
1
+ # @volter/twin-moonshot
2
+
3
+ A local, faithful **Moonshot (Kimi) Platform API** twin your real `openai` / `anthropic` SDKs talk
4
+ to **unmodified** — Moonshot ships no SDK of its own, and its documented integration path is the
5
+ standard SDKs with a swapped base URL (platform.kimi.ai/docs/overview, read 2026-09-16). Point the
6
+ client at the twin and chat completions, Responses, the Anthropic-compatible Messages surface,
7
+ streaming, `models`, `files`, `batches`, the account balance, token counting and signature verify
8
+ all work. Built on the shared `@volter/world-core` kernel (durable event/action log + projection);
9
+ no parallel side store.
10
+
11
+ ```ts
12
+ import OpenAI from 'openai';
13
+ import { createMoonshotTwinServer } from '@volter/twin-moonshot';
14
+
15
+ const { port } = createMoonshotTwinServer({});
16
+ // Moonshot's base URL carries the version segment — the SDK builds every URL as
17
+ // `${baseURL}/chat/completions`.
18
+ const client = new OpenAI({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}/v1` });
19
+ const res = await client.chat.completions.create({
20
+ model: 'kimi-k3',
21
+ messages: [{ role: 'user', content: 'hello' }],
22
+ });
23
+ // res.choices[0].message.content starts with "[twin-stub:kimi-k3]" — a deterministic stub,
24
+ // clearly labeled. res.usage carries Moonshot's FLAT cache split: usage.cached_tokens, not
25
+ // OpenAI's nested prompt_tokens_details.cached_tokens.
26
+ ```
27
+
28
+ The Anthropic-compatible surface is a base-URL suffix, exactly as on the real vendor:
29
+
30
+ ```ts
31
+ import Anthropic from '@anthropic-ai/sdk';
32
+ const anthropic = new Anthropic({ apiKey: 'sk-twin', baseURL: `http://127.0.0.1:${port}/anthropic` });
33
+ ```
34
+
35
+ ## Moonshot is not OpenAI — the differences this twin models
36
+
37
+ Moonshot exposes an *OpenAI-compatible* surface, and treating "compatible" as "identical" is how a
38
+ Moonshot twin gets built wrong. The load-bearing differences, each grounded in Moonshot's own
39
+ OpenAPI 3.1.0 document (platform.kimi.ai/docs/openapi.json) and
40
+ platform.kimi.ai/docs/{overview,api-reference,errors,models,pricing/limits,guides/context-caching},
41
+ all read 2026-09-16:
42
+
43
+ | | Moonshot | OpenAI |
44
+ |---|---|---|
45
+ | base path | **`https://api.moonshot.ai/v1/…`** (version segment in the base) | `https://api.openai.com/v1/…` |
46
+ | second surface | **`/anthropic/v1/messages`** — the Anthropic-compatible Messages protocol on the SAME host | — |
47
+ | `usage` cache split | **FLAT `usage.cached_tokens`** | nested `prompt_tokens_details.cached_tokens` |
48
+ | 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` |
49
+ | 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` | — |
50
+ | 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 |
51
+ | 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 | — |
52
+ | reasoning | `reasoning_content` on the assistant message (and its own delta before content when streaming) | `reasoning` (Responses only) |
53
+ | `reasoning_effort` | kimi-k3-only, closed set `'low'\|'high'\|'max'` | all reasoning models |
54
+ | dynamic tools | kimi-k3 accepts a **system message carrying `tools` and no content** (dynamic tool loading); any other role is a 400 | — |
55
+ | 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 } }` |
56
+ | balance | **`GET /v1/users/me/balance`** — its own envelope `{code, data:{cash_balance,voucher_balance,…}, scode, status}` | — |
57
+ | token counting | **`POST /v1/tokenizers/estimate-token-count`** — a first-class endpoint, one tokenizer shared with chat's `prompt_tokens` | — |
58
+ | statuses | 429 `rate_limit_reached_error` with the documented `X-RateLimit-*` header family; 503 `server_unavailable` | different type names |
59
+
60
+ The twin serves `/v1/…` and `/anthropic/v1/…`. A request to the bare root (no version segment)
61
+ 404s, because Moonshot does not serve it either.
62
+
63
+ ## The generative-stub design (be honest)
64
+
65
+ The twin **cannot run the model** — there are no weights here. So all three inference endpoints
66
+ (`POST /v1/chat/completions`, `POST /v1/responses`, `POST /anthropic/v1/messages`) return a
67
+ **deterministic STUB completion** that is unmistakably a twin stub (it carries a
68
+ `[twin-stub:<model>]` marker and echoes your prompt), and the web-search tool endpoints return
69
+ **deterministic labeled results**. They **never** pretend to be real model output.
70
+
71
+ What **is** faithful is the **entire protocol envelope**:
72
+
73
+ - 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} }`
74
+ - **streaming** via SSE — role delta → `reasoning_content` delta → 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)
75
+ - **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_number` from 0)
76
+ - **Messages (Anthropic-compatible)** — `{type:'message', content blocks, stop_reason, usage}` with a thinking block first, top-level `system`, `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 `/v1` shape
77
+ - **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}$`
78
+ - **structured outputs** — `response_format` `json_object` / `json_schema` (name + schema required) yield JSON stub content
79
+ - `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_logprobs` without `logprobs:true` is a 400), `prompt_cache_key`, multi-turn history, system messages counted into `prompt_tokens`, vision gating (image parts on kimi-k3/kimi-k2.6, refused on kimi-k2.7-code), context-window overflow as a 400
80
+ - **deterministic usage** — an identical request replays byte-identically
81
+
82
+ The genuinely **stateful + static** surface is real, not a stub:
83
+
84
+ - `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
85
+ - **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/files` is multipart on the real vendor and the server accepts the real multipart form (binary uploads travel base64 under the server's private `binary_content` marker and `GET /content` decodes before serving; text files round-trip byte for byte); a form with no `file` part 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
86
+ - **Batches** — `POST/GET /v1/batches` (+ retrieve + cancel → `cancelling`, `cancelling_at` set, double cancel refused), input validated against an existing batch-purpose file, `endpoint` and `completion_window` closed sets
87
+ - **Balance** — `GET /v1/users/me/balance` in Moonshot's own envelope shape
88
+ - **Token counting** — `POST /v1/tokenizers/estimate-token-count` → `{data:{total_tokens}}`, and the estimate **equals** chat's `prompt_tokens` for the same input (one tokenizer, two doors)
89
+ - **Signature verify** — `POST /v1/signatures/verify` recomputes the tuple; the server signs streamed model calls with `Msh-Request-Timestamp`/`Msh-Request-Signature`
90
+ - **Web search tools** — `POST /v1/tools/search` (limit 1..20), `/v1/tools/search_pro` (sites ≤5, `time_window` validated), `/v1/tools/fetch` (http(s) URLs only)
91
+
92
+ Vendor-shaped errors throughout: `400` / `401` / `404` / `405` (read-only guard) / `429` / `500` /
93
+ `503`. Every `/v1` envelope carries `message` + `type` and only keys Moonshot's own error table
94
+ declares; the Messages surface answers `{type:'error', error:{type,message}}`.
95
+
96
+ ## Connector (pull / push)
97
+
98
+ `syncMoonshotFromReal` pulls real models / files / batches / balance into the twin;
99
+ `pushPendingMoonshotActions` pushes pending local writes (create / cancel / delete) to the real API
100
+ and confirms them. All vendor I/O is over an **injected client** (`liveMoonshotExecute(apiKey)`
101
+ live; a fake in tests) — the pack holds no key and imports no SDK at runtime. Every live call is
102
+ charged against the shared kernel `RateBudget` **before** it goes out, and the executor refuses any
103
+ path outside `/v1/` and `/anthropic/v1/` before the budget is even charged.
104
+
105
+ The rate budget's declaration is grounded in Moonshot's published tier table
106
+ (platform.kimi.ai/docs/pricing/limits, read 2026-09-16): the LOWEST published row (Tier 0: RPM 3)
107
+ is an order of magnitude under the kernel's 30-calls/minute fallback, so the ceiling is pinned AT
108
+ the fallback and spent downward — the three inference endpoints and the three web-search endpoints
109
+ (Moonshot meters the latter on their own QPS pool) price at 6 units each, reads at 2. A real 429's
110
+ `X-RateLimit-*` headers arm a persisted cooldown that makes later calls fail fast without touching
111
+ the vendor.
112
+
113
+ ## Coverage
114
+
115
+ **Partial and honest.** The capability manifest is the *real Moonshot Platform API surface* as the
116
+ denominator — enumerated from Moonshot's own OpenAPI 3.1.0 document (19 operations) reconciled
117
+ against the prose docs, with the spec census
118
+ (`moonshot-spec-census.json`) holding the exact bijection — not a list of what was built. The
119
+ measurement lives in the repo-root coverage table (README.md /
120
+ ../../../docs/contributing/conformance.md, regenerated by
121
+ `bun scripts/twin-capabilities.ts --write-docs moonshot`); run
122
+ `bun scripts/manifest-baseline-one.ts moonshot` for this pack alone.
123
+
124
+ The remaining `todo`s are real surface: per-request response ids (the twin derives `id` from a hash
125
+ of the request, so two identical calls share one id), the asynchronous `cancelling` → `cancelled`
126
+ batch settlement (settling on a READ would break the read-only contract), the multipart file-create
127
+ push (the JSON executor cannot express a multipart body — the push is REFUSED rather than faked),
128
+ and the unpushable-action drain (a permanently-unpushable action can never be acknowledged, so
129
+ `pendingActions` never reaches empty).
130
+
131
+ ### No UI mirror
132
+
133
+ Moonshot is an API-first vendor: an integrator POSTs `/v1/chat/completions` from code, and
134
+ platform.kimi.ai is a keys/billing/usage console — incidental tooling, not where the work happens.
135
+ So this pack ships no `client/` mirror and declares no UI capabilities. This matches the sibling
136
+ generative packs (`openai`, `anthropic`, `deepseek`, `groq`, `xai`).
137
+
138
+ ## Scenario scripting (twin-only)
139
+
140
+ The three inference endpoints can be scripted by MSW-shaped handlers in a world dir's
141
+ `handlers/moonshot.json`, run by the ONE kernel scenario engine with this pack's adapter:
142
+
143
+ ```json
144
+ { "handlers": [
145
+ { "on": { "userTextIncludes": "summarize", "hasTool": "search_docs" },
146
+ "respond": { "text": "Scripted summary.", "reasoning": "scripted reasoning_content" }, "once": true },
147
+ { "on": { "thinkingTypeEquals": "disabled" }, "respond": { "error": { "type": "rate_limit_reached_error" } } }
148
+ ] }
149
+ ```
150
+
151
+ Load it with `createMoonshotTwinServer({ scenarioPath })` / `TWIN_MOONSHOT_SCENARIO`. The read
152
+ doors `GET /twin` and `GET /twin/scenario` explain and inspect it. A malformed file throws **at
153
+ load**, never a silent fall-back. Scenario support is twin-only scaffolding for eval worlds, not
154
+ vendor surface — it is kept OUT of the capability manifest (the coverage count above excludes
155
+ it) and gated by `src/moonshot-scenario.test.ts`, including the kernel's fault grammar.
156
+
157
+ ## CLI
158
+
159
+ ```
160
+ world-moonshot serve [--port N] [--root DIR] [--read-only] [--scenario FILE]
161
+ world-moonshot conformance
162
+ ```
163
+
164
+ Both read their state root from `VOLTER_STATE_DIR` (`--root` overrides).
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { hasFlag, optionValue } from '@volter/world-core/args';
3
+ import { createMoonshotTwinServer } from "./moonshot-server.js";
4
+ const [cmd, ...rest] = process.argv.slice(2);
5
+ if (cmd === 'serve') {
6
+ const root = optionValue(rest, '--root') || process.env.VOLTER_STATE_DIR;
7
+ const port = Number(optionValue(rest, '--port') || 0) || undefined;
8
+ const readOnly = hasFlag(rest, '--read-only'); // a twin accepts writes unless started read-only
9
+ const scenario = optionValue(rest, '--scenario') || undefined; // scripted completions (JSON file)
10
+ const server = await createMoonshotTwinServer({
11
+ ...(root ? { root } : {}), ...(port ? { port } : {}), readOnly, ...(scenario ? { scenarioPath: scenario } : {}),
12
+ });
13
+ process.stdout.write(`moonshot twin (Moonshot Platform API at /v1 and /anthropic/v1; model output is a deterministic stub)${readOnly ? ' [read-only]' : ''}${scenario ? ` [scenario: ${scenario}]` : ''} at http://127.0.0.1:${server.port}\n`);
14
+ }
15
+ else if (cmd === 'conformance') {
16
+ // Lazy — the conformance module is DEV-ONLY and must not be reachable from the runtime
17
+ // entrypoints (recipe §3/§4, enforced by scripts/architecture.test.ts).
18
+ const { checkMoonshotConformance } = await import("./moonshot-conformance.js");
19
+ const report = await checkMoonshotConformance({ root: process.env.VOLTER_STATE_DIR });
20
+ console.log(JSON.stringify(report, null, 2));
21
+ process.exit(report.ok ? 0 : 1);
22
+ }
23
+ else {
24
+ console.log('usage: world-moonshot serve [--port N] [--root DIR] [--read-only] [--scenario FILE] | conformance');
25
+ }
@@ -0,0 +1,14 @@
1
+ export { handleMoonshotTwinRequest, streamChat, streamMessages, streamResponses, buildChatCompletion, buildMessagesResponse, buildResponsesResponse, MOONSHOT_API_PREFIX, MESSAGES_PREFIX, messagesSignature } from './moonshot-twin.js';
2
+ export type { MoonshotRequest, MoonshotResponseEnvelope, MessagesSseSink } from './moonshot-twin.js';
3
+ export { createMoonshotTwinFetch, createMoonshotTwinServer, type MoonshotTwinFetchOptions } from './moonshot-server.js';
4
+ export { MOONSHOT_MODELS, findModel, BATCH_MODELS, REASONING_EFFORTS, K26_THINKING_TYPES, K27_THINKING_TYPES } from './moonshot-models.js';
5
+ export { buildChatUsage, contentToText, countPromptTokens, estimateTokens, fnv1a, lastUserText, stubAssistantText, stubCachedTokens, stubFetchedMarkdown, stubJsonObject, stubReasoningContent, stubSearchResults, stubSignature, stubToolArguments, stubToolCall, } from './moonshot-stub.js';
6
+ export type { MoonshotAssistantMessage, MoonshotBatch, MoonshotChatChunk, MoonshotChatCompletion, MoonshotChoice, MoonshotError, MoonshotFile, MoonshotMessageParam, MoonshotMessagesBlock, MoonshotMessagesResponse, MoonshotModelObject, MoonshotResponsesOutputItem, MoonshotResponsesResponse, MoonshotResponsesUsage, MoonshotToolCall, MoonshotUsage, SseEvent, SseSink, MessagesSseEvent, } from './moonshot-types.js';
7
+ export { createMoonshotScenarioEngine, moonshotScenarioAdapter, loadMoonshotScenarioDocument, realizeMoonshotRespond } from './moonshot-scenario.js';
8
+ export type { MoonshotScenarioEngine, MoonshotScenarioRequest, MoonshotScenarioRespond, ScenarioToolCall, ScriptedResult } from './moonshot-scenario.js';
9
+ export { fullSyncMoonshot, externalIdFor, liveMoonshotExecute, mapBalance, mapBatch, mapFile, mapModel, moonshotExecuteOver, moonshotRequestForAction, performMoonshotAction, pullMoonshotState, pushMoonshotAction, pushPendingMoonshotActions, syncMoonshotFromReal, syncMoonshotFromRemote, unpushableReason, } from './moonshot-connector.js';
10
+ export type { MoonshotExecute, LiveMoonshotOptions } from './moonshot-connector.js';
11
+ export { MOONSHOT_BUDGET_CEILING, MOONSHOT_BUDGET_MAX_RETRY_AFTER_S, MOONSHOT_BUDGET_WINDOW_MS, MOONSHOT_CALL_WEIGHTS, MOONSHOT_RATE_BUDGET, MoonshotBudget, MoonshotBudgetError, moonshotBudgetPath, moonshotCallWeight, } from './moonshot-budget.js';
12
+ export type { MoonshotBudgetErrorKind, MoonshotBudgetOptions, MoonshotBudgetReservation, MoonshotBudgetSnapshot } from './moonshot-budget.js';
13
+ import { type TwinPack } from '@volter/world-core';
14
+ export declare const pack: TwinPack;
@@ -0,0 +1,86 @@
1
+ // @volter/twin-moonshot — the Moonshot (Kimi) twin (one vendor, one package), built on the shared
2
+ // @volter/world-core kernel. The Moonshot Platform API: a vendor-faithful protocol envelope on
3
+ // THREE inference protocols (OpenAI-compatible /v1/chat/completions + /v1/responses, and the
4
+ // Anthropic-compatible /anthropic/v1/messages), a static models catalog, STATEFUL files +
5
+ // batches + account balance, and the deterministic stateless helpers (token counting, signature
6
+ // verify, web-search tools) — over an event/action log.
7
+ //
8
+ // THE DETERMINISTIC STUB IS THE ANSWER: the twin runs no model, so the three inference endpoints
9
+ // return a DETERMINISTIC STUB completion (clearly labeled), never pretending to be real
10
+ // inference. Everything around them — the wire protocol, the rejections, the stateful objects —
11
+ // is faithful.
12
+ //
13
+ // MOONSHOT SHIPS NO SDK OF ITS OWN: its documented integration path is the standard `openai` /
14
+ // `anthropic` SDKs with a swapped base URL (platform.kimi.ai/docs/overview, read 2026-09-16), so
15
+ // the pack claims no vendor SDK in `adoption.sdks` and the fidelity test drives the real
16
+ // `openai` SDK at the twin. (Conformance + capability tooling live in @volter/world-tooling, a
17
+ // dev dependency — NOT re-exported here, per E2.)
18
+ export { handleMoonshotTwinRequest, streamChat, streamMessages, streamResponses, buildChatCompletion, buildMessagesResponse, buildResponsesResponse, MOONSHOT_API_PREFIX, MESSAGES_PREFIX, messagesSignature } from "./moonshot-twin.js";
19
+ export { createMoonshotTwinFetch, createMoonshotTwinServer } from "./moonshot-server.js";
20
+ export { MOONSHOT_MODELS, findModel, BATCH_MODELS, REASONING_EFFORTS, K26_THINKING_TYPES, K27_THINKING_TYPES } from "./moonshot-models.js";
21
+ export { buildChatUsage, contentToText, countPromptTokens, estimateTokens, fnv1a, lastUserText, stubAssistantText, stubCachedTokens, stubFetchedMarkdown, stubJsonObject, stubReasoningContent, stubSearchResults, stubSignature, stubToolArguments, stubToolCall, } from "./moonshot-stub.js";
22
+ export { createMoonshotScenarioEngine, moonshotScenarioAdapter, loadMoonshotScenarioDocument, realizeMoonshotRespond } from "./moonshot-scenario.js";
23
+ export { fullSyncMoonshot, externalIdFor, liveMoonshotExecute, mapBalance, mapBatch, mapFile, mapModel, moonshotExecuteOver, moonshotRequestForAction, performMoonshotAction, pullMoonshotState, pushMoonshotAction, pushPendingMoonshotActions, syncMoonshotFromReal, syncMoonshotFromRemote, unpushableReason, } from "./moonshot-connector.js";
24
+ // The client-side rate budget — the fail-closed backstop `liveMoonshotExecute` routes every live
25
+ // request through. The MECHANISM is the kernel's shared, vendor-agnostic `RateBudget`; what lives
26
+ // here is Moonshot's DECLARATION (window/ceiling/per-endpoint weights) plus the vendor-bound
27
+ // bindings. Exported so an operator can inspect spend (`snapshot`) and so a caller can catch
28
+ // `MoonshotBudgetError` by type; there is deliberately no export that disables the guard.
29
+ export { MOONSHOT_BUDGET_CEILING, MOONSHOT_BUDGET_MAX_RETRY_AFTER_S, MOONSHOT_BUDGET_WINDOW_MS, MOONSHOT_CALL_WEIGHTS, MOONSHOT_RATE_BUDGET, MoonshotBudget, MoonshotBudgetError, moonshotBudgetPath, moonshotCallWeight, } from "./moonshot-budget.js";
30
+ // Registry descriptor: the pack self-describes so tooling can discover it.
31
+ import { registerPack } from '@volter/world-core';
32
+ import { MOONSHOT_RATE_BUDGET as RATE_BUDGET } from "./moonshot-budget.js";
33
+ import { performMoonshotAction, syncMoonshotFromRemote } from "./moonshot-connector.js";
34
+ export const pack = {
35
+ vendor: 'moonshot',
36
+ // PROTOCOL 2 (docs/contributing/architecture.md#protocol-2-the-pack-is-a-plugin): the pack is a plugin — its wire, its tree, and its half of
37
+ // the real state system: perform one entry against Moonshot, refresh the root from it.
38
+ protocol: '2',
39
+ refresh: { every: '5m', onDemand: { atMost: '30s' } },
40
+ stateSystem: { perform: performMoonshotAction, refresh: syncMoonshotFromRemote },
41
+ // the round trip: a file — the one thing this API mints an id for and keeps, and a fresh id each
42
+ // time, so it repeats cleanly on a branch. (A batch needs a seeded input file; a completion is
43
+ // answered, not kept.)
44
+ roundTrip: { method: 'POST', path: '/v1/files', body: { purpose: 'batch', filename: 'round-trip.jsonl', content: 'x' }, headers: { authorization: 'Bearer sk-round-trip' } },
45
+ // The SAME object moonshot-budget.ts declares at module load — one source of truth, so
46
+ // registering the pack and importing the connector can never arm two different ceilings.
47
+ rateBudget: RATE_BUDGET,
48
+ transport: 'rest',
49
+ archetype: 'generative',
50
+ bin: 'world-moonshot',
51
+ // R2 adopted-as-debt, legibly: declared types no replay can create, each with its reason.
52
+ resourcesUnreachable: {
53
+ 'model': 'the vendor catalog',
54
+ 'balance': 'the account ledger the vendor keeps; read-only',
55
+ },
56
+ resources: ['file', 'batch', 'balance', 'model'],
57
+ specSource: 'Moonshot Platform API — enumerated from Moonshot\'s own OpenAPI 3.1.0 document (https://platform.kimi.ai/docs/openapi.json, read 2026-09-16; 19 operations) + platform.kimi.ai/docs/{overview,api-reference,errors,models,pricing/limits,guides/context-caching} (read 2026-09-16). Envelope-faithful across the OpenAI-compatible /v1 and Anthropic-compatible /anthropic/v1 surfaces; model output is a labeled deterministic stub.',
58
+ description: 'Moonshot (Kimi) API twin — faithful protocol envelope across three inference protocols (OpenAI chat completions, Responses, Anthropic-compatible Messages) with streaming grammars, tool calls and cache-split usage; models catalog; stateful files/batches/balance; deterministic token counting, signature verify and web-search tool stubs; Moonshot\'s own documented rejections.',
59
+ // Moonshot serves BOTH surfaces on one host. browserRouting points the browser lane at the
60
+ // OpenAI-compatible prefix, which is the dominant client form.
61
+ browserRouting: { apiPathPrefix: '/v1/', loaderHost: 'https://api.moonshot.ai' },
62
+ // ADOPTION (adding-a-twin.md §3): how an app repo betrays that it talks to Moonshot. Declared
63
+ // HERE, not in world-runtime's central SDK_TWINS/ENV_STEM_VENDORS maps — declaring in both
64
+ // throws. Moonshot ships NO SDK of its own: its documented clients are the standard `openai`
65
+ // and `anthropic` SDKs with a swapped base URL, and BOTH of those npm names belong to their
66
+ // own vendors' packs (openai → @volter/twin-openai, anthropic → @volter/twin-anthropic) — a
67
+ // repo depending on `openai` is an OpenAI repo unless its base URL says otherwise. What
68
+ // betrays Moonshot specifically is the ENV STEM (`MOONSHOT_API_KEY` / `MOONSHOT_BASE_URL`)
69
+ // and the deepseek precedent: no sdk claim, envStems only.
70
+ adoption: {
71
+ // No official Moonshot PyPI client is documented (the docs name the OpenAI Python SDK).
72
+ pypi: [],
73
+ sdks: [], envStems: ['MOONSHOT'],
74
+ },
75
+ // INTERCEPTION: the ONE host both documented clients address (the openai SDK pointed at
76
+ // https://api.moonshot.ai/v1 and the anthropic SDK pointed at https://api.moonshot.ai/anthropic).
77
+ hosts: [{ host: 'api.moonshot.ai' }],
78
+ // No app-read endpoint env, deliberately. Moonshot documents no MOONSHOT_BASE_URL-style env
79
+ // var: the standard SDKs take their base URL as a CONSTRUCTOR option (`new OpenAI({
80
+ // baseURL })`), not from the environment, so an app-read var would cover only env-configured
81
+ // callers while disabling the interception that covers all of them (the deepseek/groq
82
+ // precedent). Emitting both would quietly forgo interception (`init.test.ts`, "the app-read
83
+ // endpoint table cannot go stale behind the injector").
84
+ endpointEnvNone: 'Moonshot ships no SDK of its own; its documented clients (the standard openai/anthropic SDKs) take their base URL as a constructor option and read no MOONSHOT_BASE_URL env, so an app-read var would cover only env-configured callers while disabling the api.moonshot.ai interception that covers all traffic.',
85
+ };
86
+ registerPack(pack);
@@ -0,0 +1,57 @@
1
+ import { RateBudget, type RateBudgetDeclaration, type RateBudgetOptions, type RateBudgetReservation, type RateBudgetSnapshot } from '@volter/world-core';
2
+ /** Rolling window, in ms. Spend older than this is pruned. */
3
+ export declare const MOONSHOT_BUDGET_WINDOW_MS = 60000;
4
+ /**
5
+ * Weighted units allowed inside one window. 60/60s at `defaultWeight` 2 = 30 calls a minute —
6
+ * EXACTLY the kernel's undeclared fallback. Moonshot DOES publish an RPM scalar (3 at Tier 0),
7
+ * but it is a CALL ceiling, not a weight-unit ceiling; pricing every call 2 keeps the fallback
8
+ * shape and lets the inference rules spend the allowance where the vendor actually meters it.
9
+ */
10
+ export declare const MOONSHOT_BUDGET_CEILING = 60;
11
+ /** Seconds. A `retry-after` above this means the key is throttled hard — fail loudly, don't sleep. */
12
+ export declare const MOONSHOT_BUDGET_MAX_RETRY_AFTER_S = 300;
13
+ /** Per-call cost, keyed by `"<METHOD> <path>"`. See the header for what is documented vs. judged. */
14
+ export declare const MOONSHOT_CALL_WEIGHTS: {
15
+ /** Model-facing inference: /v1/chat/completions, /v1/responses, /anthropic/v1/messages.
16
+ * At 60/6 that is at most 10 inference calls a window — inside Tier 0's RPM 3×window shape
17
+ * for a single burst while leaving room for the interleaved reads a real client issues. */
18
+ readonly inference: 6;
19
+ /** The web-search tool endpoints — Moonshot meters them on their OWN QPS (1 at Tier 0),
20
+ * independent of inference RPM. Priced like inference so a sweep cannot ride the read weight. */
21
+ readonly webSearch: 6;
22
+ /** Everything else: models, files, batches, balance, token counting, signature verify. */
23
+ readonly other: 2;
24
+ };
25
+ /** THE PACK'S DECLARATION — pure data, the only Moonshot-specific thing in the whole budget. */
26
+ export declare const MOONSHOT_RATE_BUDGET: RateBudgetDeclaration;
27
+ /**
28
+ * Price one call. The key is `"<METHOD> <path>"` with the query string split off, so a rule can
29
+ * price by method (a write is not a read) without the kernel knowing anything about Moonshot. An
30
+ * unclassified endpoint still costs `defaultWeight` — nothing is ever free.
31
+ */
32
+ export declare function moonshotCallWeight(method: string, path: string): number;
33
+ /** Where Moonshot's ledger lives. Token-keyed and cwd-independent by default (Moonshot's limits
34
+ * are per ACCOUNT, so a cwd-scoped ledger would hand the same key a fresh allowance in every
35
+ * checkout, worktree and CI matrix leg); pass `root` for world-scoped accounting. */
36
+ export declare function moonshotBudgetPath(opts?: {
37
+ root?: string;
38
+ token?: string;
39
+ } | string): string;
40
+ /** Construction options for Moonshot's budget. The vendor is fixed; everything else may only TIGHTEN. */
41
+ export type MoonshotBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
42
+ /**
43
+ * Moonshot's budget — the shared kernel guard bound to this vendor's declaration. A real
44
+ * subclass, not an alias, so `budget instanceof MoonshotBudget` in `liveMoonshotExecute` means
45
+ * "a budget that accounts against MOONSHOT's ledger under MOONSHOT's ceiling".
46
+ */
47
+ export declare class MoonshotBudget extends RateBudget {
48
+ constructor(opts?: MoonshotBudgetOptions);
49
+ }
50
+ /** The typed refusal. One error class shared with every other vendor's budget; `err.vendor` says
51
+ * which one refused, and `err.kind` says why. */
52
+ export { RateBudgetError as MoonshotBudgetError } from '@volter/world-core';
53
+ export type { RateBudgetErrorKind as MoonshotBudgetErrorKind } from '@volter/world-core';
54
+ /** Re-exported so a caller can age a window out against the DECLARED window, not a hard-coded 60_000. */
55
+ export { MOONSHOT_BUDGET_WINDOW_MS as MOONSHOT_RATE_BUDGET_WINDOW_MS };
56
+ export type MoonshotBudgetReservation = RateBudgetReservation;
57
+ export type MoonshotBudgetSnapshot = RateBudgetSnapshot;