Open History to see the last commit
1import { KIMI_THINKING_URL } from '../provider-replay.ts'
2import { KIMI_REPLAY_FIXTURE } from '../fixtures/provider-replay.ts'
3import { describe, expect, it } from 'vitest'
4
5import specFixture from '../fixtures/moonshotai-cn-openapi.json' with { type: 'json' }
6import { provider } from './moonshot.ts'
7
8const SPEC_URL = 'https://platform.kimi.ai/docs/openapi.json'
9/** One compiled-MDX DocTable row, as the HTML pricing page embeds it. */
10const OTHER_PRICES =
11 '_jsx(DocTable,{columns:[{title:`Model`},{title:`Input`},{title:`Output`},{title:`Cached Input`}],rows:[[`kimi-other`,`$0.2 / MTok`,`$0.3 / MTok`,`$0.1 / MTok`]]})_provideComponents()'
12
13const FIXTURE_SPEC = {
14 openapi: '3.1.0',
15 info: { title: 'Moonshot AI API', version: '1.0.0' },
16 servers: [{ url: 'https://api.moonshot.ai' }],
17 paths: {
18 '/v1/chat/completions': { post: { summary: 'Create Chat Completion' } },
19 '/v1/files': { post: { summary: 'Upload File' } },
20 },
21}
22
23describe('moonshot adapter', () => {
24 it('exports seed metadata for the international host', () => {
25 expect(provider.id).toBe('moonshot')
26 expect(provider.displayName).toBe('Moonshot')
27 expect(provider.authEnvVar).toBe('MOONSHOT_API_KEY')
28 expect(provider.defaultDerivation).toBe('upstream-spec')
29 expect(provider.specSourceUrl).toBe(SPEC_URL)
30 expect(provider.modelsEndpoint).toBe('https://api.moonshot.ai/v1/models')
31 })
32
33 it('classifies chat completions and drops platform paths', () => {
34 expect(provider.classify('/v1/chat/completions', {})).toBe('chat')
35 expect(provider.classify('/chat/completions', {})).toBe('chat')
36 expect(provider.classify('/v1/files', {})).toBeNull()
37 expect(provider.classify('/v1/batches', {})).toBeNull()
38 expect(provider.classify('/v1/models', {})).toBeNull()
39 expect(provider.classify('/v1/users/me/balance', {})).toBeNull()
40 expect(
41 provider.classify('/v1/tokenizers/estimate-token-count', {}),
42 ).toBeNull()
43 })
44
45 it('skips listModels when the secret is absent', async () => {
46 const result = await provider.listModels({})
47 expect(result.models).toMatchObject([])
48 expect(result.skipped).toBe('moonshot: MOONSHOT_API_KEY not set — skipped')
49 })
50
51 it('lists models from api.moonshot.ai, not the CN host', async () => {
52 const original = globalThis.fetch
53 const urls: Array<string> = []
54 globalThis.fetch = ((url: string) => {
55 urls.push(String(url))
56 if (String(url) === KIMI_THINKING_URL)
57 return Promise.resolve(new Response(KIMI_REPLAY_FIXTURE))
58 if (String(url).includes('platform.kimi.ai')) {
59 return Promise.resolve(new Response(OTHER_PRICES))
60 }
61 return Promise.resolve(
62 new Response(
63 JSON.stringify({
64 data: [{ id: 'kimi-k2.7-code', created: 1_786_418_420 }],
65 }),
66 ),
67 )
68 }) as typeof fetch
69 try {
70 const result = await provider.listModels({
71 MOONSHOT_API_KEY: 'test-key',
72 })
73 expect(urls[0]).toBe('https://api.moonshot.ai/v1/models')
74 expect(result.skipped).toBeUndefined()
75 // The stub's spec is not a spec: the stored reasoning is kept.
76 expect(result.models).toMatchObject([
77 {
78 rawId: 'kimi-k2.7-code',
79 releasedAt: null,
80 activity: 'chat',
81 absent: { reasoning: 'unavailable', releasedAt: 'cleared' },
82 },
83 ])
84 expect(result.docsFailures).toMatchObject({
85 failed: 1,
86 first: [{ source: SPEC_URL }],
87 })
88 } finally {
89 globalThis.fetch = original
90 }
91 })
92
93 it('reads each K2 model’s thinking switch from its own spec branch', async () => {
94 // The international spec has the China spec's shape and names its own
95 // server; the fixture is the China document with that one line changed.
96 const spec = (server: string) =>
97 JSON.stringify({ ...specFixture, servers: [{ url: server }] })
98 const list = async (body: string) => {
99 const original = globalThis.fetch
100 globalThis.fetch = ((url: string) =>
101 Promise.resolve(
102 new Response(
103 String(url) === KIMI_THINKING_URL
104 ? KIMI_REPLAY_FIXTURE
105 : String(url) === SPEC_URL
106 ? body
107 : String(url).includes('platform.kimi.ai')
108 ? OTHER_PRICES
109 : JSON.stringify({
110 data: [
111 { id: 'kimi-k3' },
112 { id: 'kimi-k2.7-code' },
113 { id: 'kimi-k2.6' },
114 { id: 'moonshot-v1-8k' },
115 ],
116 }),
117 ),
118 )) as typeof fetch
119 try {
120 return await provider.listModels({ MOONSHOT_API_KEY: 'test-key' })
121 } finally {
122 globalThis.fetch = original
123 }
124 }
125
126 const listed = await list(spec('https://api.moonshot.ai'))
127 const byId = new Map(listed.models.map((model) => [model.rawId, model]))
128 expect(listed.docsFailures).toMatchObject({ failed: 0 })
129 expect(byId.get('kimi-k2.6')?.reasoning).toEqual({
130 mode: 'toggle',
131 mandatory: false,
132 })
133 expect(byId.get('kimi-k2.7-code')?.reasoning).toEqual({
134 mode: 'toggle',
135 mandatory: true,
136 })
137 expect(byId.get('kimi-k2.6')?.factSources).toMatchObject({
138 reasoning: {
139 derivation: 'upstream-spec',
140 sourceUrl: SPEC_URL,
141 sourceHash: expect.stringMatching(/^[0-9a-f]{64}$/) as string,
142 path: 'thinking.type',
143 },
144 })
145 // Only the switch is taken from the spec; an effort row and an id the
146 // spec does not map are left as the listing gave them.
147 for (const id of ['kimi-k3', 'moonshot-v1-8k']) {
148 expect(byId.get(id)).not.toHaveProperty('reasoning')
149 expect(byId.get(id)?.factSources?.reasoning).toBeUndefined()
150 expect(byId.get(id)?.absent).toEqual({ releasedAt: 'cleared' })
151 }
152
153 // The China host's document is not this provider's, and neither is a
154 // 200 web page: every row keeps what is stored.
155 for (const body of [
156 spec('https://api.moonshot.cn'),
157 '<!DOCTYPE html><html><body>Not found</body></html>',
158 ]) {
159 const failed = await list(body)
160 expect(failed.docsFailures).toMatchObject({ failed: 1 })
161 for (const model of failed.models) {
162 expect(model.absent).toEqual({
163 reasoning: 'unavailable',
164 releasedAt: 'cleared',
165 })
166 expect(model).not.toHaveProperty('reasoning')
167 }
168 }
169 })
170
171 it('fetches the published spec without a key', async () => {
172 const original = globalThis.fetch
173 const urls: Array<string> = []
174 globalThis.fetch = ((url: string) => {
175 urls.push(String(url))
176 return Promise.resolve(new Response(JSON.stringify(FIXTURE_SPEC)))
177 }) as typeof fetch
178 try {
179 const fetched = await provider.fetchSpec({})
180 expect(urls).toEqual([SPEC_URL])
181 expect(fetched.outputStrategy).toBe('post-200')
182 expect(fetched.sources).toHaveLength(1)
183 expect(fetched.sources[0]?.url).toBe(SPEC_URL)
184 expect(fetched.sources[0]?.hash).toMatch(/^[0-9a-f]{64}$/)
185 expect(fetched.specs[0]?.info?.title).toBe('Moonshot AI API')
186 } finally {
187 globalThis.fetch = original
188 }
189 })
190})