Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

moonshot.test.ts

189 lines6.9 KB

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