-
Notifications
You must be signed in to change notification settings - Fork 35
/
server.js
1487 lines (1153 loc) · 43.6 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
////////////////////////////////////////////////////////////////////////////////
// init
const MongoClient = require('mongodb').MongoClient
const MONGODB_URI = process.env.MONGODB_URI
let client, bookdb, poscoll, movecoll
if(MONGODB_URI){
MongoClient.connect(MONGODB_URI, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, setClient) {
if(err){
console.log("MongoDb connection failed.")
}else{
console.log("MongoDb connected. Version", mongoVersion, ".")
client = setClient
let coll
if(mongoVersion == 1){
bookdb = client.db("book")
poscoll = bookdb.collection("positions")
coll = poscoll
}else if(mongoVersion == 2){
bookdb = client.db("book2")
movecoll = bookdb.collection("moves")
coll = movecoll
}
if(coll){
let index = {
variant: 1,
key: 1
}
console.log(`creating index ${JSON.stringify(index)}`)
coll.createIndex(index).then(result => {
console.log(`index creation result ${result}`)
})
}
}
})
}
const fooVersion = '1.0.43'
const lichessBotName = process.env.BOT_NAME || "bot"
const { isEnvTrue, formatTime, formatName, SECOND, MINUTE } = require('@easychessanimations/tinyutils')
let envKeys = []
const useStockfish14_1 = isEnvTrue('USE_STOCKFISH_14_1')
envKeys.push('USE_STOCKFISH_14_1')
const useStockfish14 = isEnvTrue('USE_STOCKFISH_14')
envKeys.push('USE_STOCKFISH_14')
const useStockfish13 = isEnvTrue('USE_STOCKFISH_13')
envKeys.push('USE_STOCKFISH_13')
const useStockfish12 = isEnvTrue('USE_STOCKFISH_12')
envKeys.push('USE_STOCKFISH_12')
const disableLogs = isEnvTrue('DISABLE_LOGS')
envKeys.push('DISABLE_LOGS')
const calcFen = (!(isEnvTrue('SKIP_FEN')))
envKeys.push('SKIP_FEN')
const incrementalUpdate = isEnvTrue('INCREMENTAL_UPDATE')
envKeys.push('INCREMENTAL_UPDATE')
const skipAfterFailed = parseInt(process.env.SKIP_AFTER_FAILED || "0")
envKeys.push('SKIP_AFTER_FAILED')
const appName = process.env.APP_NAME || "lichess-bot"
envKeys.push('APP_NAME')
const generalTimeout = parseInt(process.env.GENERAL_TIMEOUT || "15")
envKeys.push('GENERAL_TIMEOUT')
const engineThreads = process.env.ENGINE_THREADS || "1"
envKeys.push('ENGINE_THREADS')
const engineSkillLevel = process.env.ENGINE_SKILL_LEVEL || "20"
envKeys.push('ENGINE_SKILL_LEVEL')
const engineHash = process.env.ENGINE_HASH || "16"
envKeys.push('ENGINE_HASH')
const engineMoveOverhead = process.env.ENGINE_MOVE_OVERHEAD || "500"
envKeys.push('ENGINE_MOVE_OVERHEAD')
const allowPonder = isEnvTrue('ALLOW_PONDER')
envKeys.push('ALLOW_PONDER')
const useBook = isEnvTrue('USE_BOOK')
envKeys.push('USE_BOOK')
const useMongoBook = isEnvTrue('USE_MONGO_BOOK')
envKeys.push('USE_MONGO_BOOK')
const disableEngineForMongo = isEnvTrue('DISABLE_ENGINE_FOR_MONGO')
envKeys.push('DISABLE_ENGINE_FOR_MONGO')
const mongoVersion = parseInt(process.env.MONGO_VERSION || "1")
envKeys.push('MONGO_VERSION')
const ignoreMongoPercent = parseInt(process.env.IGNORE_MONGO_PERCENT || "20")
envKeys.push('IGNORE_MONGO_PERCENT')
const mongoFilter = parseInt(process.env.MONGO_FILTER || "30")
envKeys.push('MONGO_FILTER')
const bookDepth = parseInt(process.env.BOOK_DEPTH || "20")
envKeys.push('BOOK_DEPTH')
const bookSpread = parseInt(process.env.BOOK_SPREAD || "4")
envKeys.push('BOOK_SPREAD')
const bookRatings = (process.env.BOOK_RATINGS || "2200,2500").split(",")
envKeys.push('BOOK_RATINGS')
const bookSpeeds = (process.env.BOOK_SPEEDS || "blitz,rapid").split(",")
envKeys.push('BOOK_SPEEDS')
const logApi = isEnvTrue('LOG_API')
envKeys.push('LOG_API')
const challengeInterval = parseInt(process.env.CHALLENGE_INTERVAL || "15")
envKeys.push('CHALLENGE_INTERVAL')
const challengeTimeout = parseInt(process.env.CHALLENGE_TIMEOUT || "30")
envKeys.push('CHALLENGE_TIMEOUT')
const urlArray = (name,items) => items.map(item=>`${name}[]=${item}`).join("&")
const useScalachess = isEnvTrue('USE_SCALACHESS')
envKeys.push('USE_SCALACHESS')
const acceptVariants = (process.env.ACCEPT_VARIANTS || "standard").split(" ")
envKeys.push('ACCEPT_VARIANTS')
const acceptSpeeds = (process.env.ACCEPT_SPEEDS || "bullet blitz rapid classical").split(" ")
envKeys.push('ACCEPT_SPEEDS')
const gameStartDelay = parseInt(process.env.GAME_START_DELAY || "2")
envKeys.push('GAME_START_DELAY')
const disableRated = isEnvTrue('DISABLE_RATED')
envKeys.push('DISABLE_RATED')
const disableCasual = isEnvTrue('DISABLE_CASUAL')
envKeys.push('DISABLE_CASUAL')
const disableBot = isEnvTrue('DISABLE_BOT')
envKeys.push('DISABLE_BOT')
const disableHuman = isEnvTrue('DISABLE_HUMAN')
envKeys.push('DISABLE_HUMAN')
const usePolyglot = isEnvTrue('USE_POLYGLOT')
envKeys.push('USE_POLYGLOT')
const useSolution = isEnvTrue('USE_SOLUTION')
envKeys.push('USE_SOLUTION')
const welcomeMessage = process.env.WELCOME_MESSAGE || `coded by @YohaanSethNathan`
envKeys.push('WELCOME_MESSAGE')
const goodLuckMessage = process.env.GOOD_LUCK_MESSAGE || `Good luck!`
envKeys.push('GOOD_LUCK_MESSAGE')
const goodGameMessage = process.env.GOOD_GAME_MESSAGE || `Good game!`
envKeys.push('GOOD_GAME_MESSAGE')
let disableSyzygy = isEnvTrue('DISABLE_SYZYGY')
envKeys.push('DISABLE_SYZYGY')
const filterThresoldPlays = parseInt(process.env.FILTER_THRESOLD_PLAYS, "10")
envKeys.push('FILTER_THRESOLD_PLAYS')
const bookForgiveness = parseInt(process.env.BOOK_FORGIVENESS, "20")
envKeys.push('BOOK_FORGIVENESS')
const alwaysOn = isEnvTrue('ALWAYS_ON')
envKeys.push('ALWAYS_ON')
const abortAfter = parseInt(process.env.ABORT_AFTER || "120")
envKeys.push('ABORT_AFTER')
const allowCorrespondence = isEnvTrue('ALLOW_CORRESPONDENCE')
envKeys.push('ALLOW_CORRESPONDENCE')
const correspondenceThinkingTime = parseInt(process.env.CORRESPONDENCE_THINKING_TIME || "120")
envKeys.push('CORRESPONDENCE_THINKING_TIME')
const declineHard = isEnvTrue('DECLINE_HARD')
envKeys.push('DECLINE_HARD')
const disableChallengeRandom = isEnvTrue('DISABLE_CHALLENGE_RANDOM')
envKeys.push('DISABLE_CHALLENGE_RANDOM')
const fs = require('fs')
const syzygyPath = "/syzygy"
console.log(`finding syzygy path ${syzygyPath}`)
if(fs.existsSync(syzygyPath)){
console.log(`syzygy path exists`)
if(fs.statSync(syzygyPath).isDirectory()){
console.log(`syzygy path is a directory`)
}else{
console.log(`syzygy path is not a directory`)
disableSyzygy = true
}
}else{
console.log(`syzygy path does not exist`)
disableSyzygy = true
}
console.log(`syzygy tablebases ${disableSyzygy ? "disabled" : "enabled"}`)
let lastPlayedAt = 0
const { Section, EnvVars } = require('@easychessanimations/foo/lib/smartmd.js')
const startFen = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
const polyglotBookName = "elo-3300.bin"
const Polyglot = require('@easychessanimations/polyglot')
const book = new Polyglot()
if(usePolyglot) book.loadThen(polyglotBookName)
let config = {}
for (let envKey of envKeys){
let value = process.env[envKey]
if(value) config[envKey] = value
}
const path = require('path')
const express = require('express')
const app = express()
const port = process.env.PORT || 3000
const cors = require('cors')
app.use(cors())
const fetch = require('node-fetch')
let docs = null
fetch(`https://raw.githubusercontent.com/TheYoBots/easyherokubot/docs/docs.json`).then(response=>response.text().then(content=>{
try{
docs = JSON.parse(content)
}catch(err){console.log(err)}
}))
const lichessUtils = require("@easychessanimations/lichessutils")
const { streamNdjson } = require('@easychessanimations/fetchutils')
const { makeUciMoves } = require("@easychessanimations/scalachess/lib/outopt.js")
const { UciEngine, setLogEngine, AnalyzeJob } = require('@easychessanimations/uci')
let stockfishPath = useScalachess ? 'stockfishm_dev' : 'stockfishdev'
if(useStockfish12){
stockfishPath = useScalachess ? 'stockfish12m' : 'stockfish12'
console.log(`using Stockfish 12 ( ${stockfishPath} )`)
}
if(useStockfish13){
stockfishPath = useScalachess ? 'stockfish13m' : 'stockfish13'
console.log(`using Stockfish 13 ( ${stockfishPath} )`)
}
if(useStockfish14){
stockfishPath = useScalachess ? 'stockfish14m' : 'stockfish14'
console.log(`using Stockfish 14 ( ${stockfishPath} )`)
}
if(useStockfish14_1){
stockfishPath = useScalachess ? 'stockfish14_1m' : 'stockfish14_1'
console.log(`using Stockfish 14.1 ( ${stockfishPath} )`)
}
const engine = new UciEngine(path.join(__dirname, stockfishPath))
const corrEngine = allowCorrespondence ? new UciEngine(path.join(__dirname, stockfishPath)) : null
const { Chess } = require('chess.js')
let playingGameId = null
const { sseMiddleware, setupStream, ssesend, TICK_INTERVAL } = require('@easychessanimations/sse')
app.use(sseMiddleware)
setupStream(app)
const logStream = isEnvTrue("LOG_FILE") ? fs.createWriteStream("log.txt", {flags: "a"}) : null
let logFileT0 = new Date().getTime()
function logFile(content){
if(logStream){
let time = new Date().getTime()
let elapsed = time - logFileT0
logFileT0 = time
logStream.write(`${elapsed} > ${content}\n`)
}
}
function logPage(content){
if(disableLogs){
return
}
console.log(content)
ssesend({
kind: "logPage",
content: content
})
}
setLogEngine(logPage)
const KEEP_ALIVE_URL = process.env.KEEP_ALIVE_URL
const KEEP_ALIVE_INTERVAL = parseInt(process.env.KEEP_ALIVE_INTERVAL || "5")
const possibleOpeningMoves = ["e2e4", "d2d4", "c2c4", "g1f3", "e2e3"]
const possibleOpeningResponses = {
"e2e4": ["e7e6", "e7e5", "c7c5", "c7c6", "g8f6", "g7g6", "b7b6", "d7d5"],
"d2d4": ["e7e6", "e7e5", "c7c5", "c7c6", "g8f6", "d7d5"],
"c2c4": ["e7e6", "e7e5", "c7c5", "c7c6", "g8f6"],
"g1f3": ["d7d5", "d7d6", "c7c5", "g8f6"],
"e2e3": ["e7e5", "d7d6", "c7c5", "g8f6"]
}
// end init
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// bot
function requestBook(state){
return new Promise(resolve=>{
if(!state.fen){
resolve(null)
return
}
if(useSolution && (state.variant == "antichess")){
if(state.movesArray.length){
let url = `http://magma.maths.usyd.edu.au/~watkins/LOSING_CHESS/WEB/browse.php?${state.movesArray.join("+")}`
console.log("getting solution", url)
let timedOut = false
let solutionTimeout = setTimeout(_=>{
console.log("antichess solution timed out")
timedOut = true
resolve(null)
return
}, 5000)
fetch(url).then(response => response.text().then(content => {
clearTimeout(solutionTimeout)
if(timedOut){
return
}
let m = content.match(/<tr class="oddRow"><td><a href="browse.php?[^"]+">([^<]+)/)
if(m){
let san = m[1]
console.log("antichess solution move", san)
let result = makeUciMoves("antichess", state.fen, [])
let legalMovesUcis = result.legalMovesUcis
let uci = null
console.log("legal ucis", legalMovesUcis)
for(let test of legalMovesUcis){
let result = makeUciMoves("antichess", state.fen, [test])
let sanMoves = result.sanMoves
//console.log("convert", test, sanMoves[0])
if(sanMoves[0] == san){
console.log("solution move", test)
resolve({
source: "solution",
moves: [{
white: 1,
draws: 0,
black: 0,
uci: test
}]
})
}
}
resolve(null)
return
}else{
resolve(null)
return
}
}))
}else{
resolve({
source: "solution",
moves: [{
white: 1,
draws: 0,
black: 0,
uci: "e2e3"
}]
})
return
}
return
}
if(usePolyglot && lichessUtils.isStandard(state.variant)){
if(!book.loaded){
console.log("polyglot book not yet loaded")
resolve(null)
return
}
let entries = book.find(state.fen)
if((!entries) || (!entries.length)){
resolve(null)
return
}
resolve({
source: "polyglot",
moves: entries.map(entry => ({
white: 0,
draws: entry.weight,
black: 0,
uci: entry.algebraic_move
}))
})
return
}
let coll = (mongoVersion == 1) ? poscoll : movecoll
if( useMongoBook && coll ){
if(!disableEngineForMongo){
if((Math.random() * 100) < ignoreMongoPercent){
resolve(null)
return
}
}
let key = state.fen.split(" ").slice(0, 4).join(" ")
getBook(state.variant, key).then(result => {
if(result.length){
let moves = result.map(item => ({
uci: item.uci,
plays: item.plays,
score: Math.floor(item.score * 100)
}))
let filteredMoves = moves
if(!disableEngineForMongo){
filteredMoves = moves.filter(move => {
let perf = move.score / move.plays
if(move.plays < filterThresoldPlays) return true
if((Math.random() * 100) < bookForgiveness) return true
if(perf < mongoFilter) return false
return true
})
}
if(!filteredMoves.length){
resolve(null)
return
}
let blob = {
source: "mongo",
moves: filteredMoves.map(move => ({
uci: move.uci,
white: 0,
draws: move.score,
black: 0
}))
}
resolve(blob)
return
}else{
resolve(null)
}
})
return
}
if(!useBook){
resolve(null)
return
}
let reqUrl = `https://explorer.lichess.ovh/lichess?fen=${state.fen}&${urlArray("ratings", bookRatings)}&${urlArray("speeds", bookSpeeds)}&moves=${bookSpread}&variant=${state.variant}`
if(logApi) console.log(reqUrl)
fetch(reqUrl).then(response=>response.text().then(content=>{
try{
let blob = JSON.parse(content)
blob.source = "lichess"
resolve(blob)
}catch(err){resolve(null)}
}))
})
}
function getUseBook(moves, failedLookups){
if(skipAfterFailed){
if(failedLookups.count >= skipAfterFailed){
logFile(`skip use book after ${failedLookups.count} failed lookups`)
return false
}
}
return (useBook || useMongoBook || usePolyglot || useSolution) && (moves.length <= bookDepth)
}
async function makeMove(gameId, state, moves, analyzejob, actualengine, failedLookups){
logFile(`makeMove ${gameId} ${state} ${moves} ${analyzejob} ${actualengine}`)
if(state.realtime && playingGameId && (gameId != playingGameId)){
logPage(`refused to make move for real time game ${gameId} ( already playing real time : ${playingGameId} )`)
return
}
logPage(`making move for game ${gameId}, variant ${state.variant}, fen ${state.fen}, moves ${moves}`)
engine.logProcessLine = false
let enginePromise
if(state.variant == "standard"){
if(moves.length == 0){
let randomOpeningMove = possibleOpeningMoves[Math.floor(Math.random() * possibleOpeningMoves.length)]
enginePromise = Promise.resolve({
bestmove: randomOpeningMove,
source: "own book"
})
}
if(moves.length == 1){
let responses = possibleOpeningResponses[moves[0]]
if(responses){
let randomOpeningResponse = responses[Math.floor(Math.random() * responses.length)]
enginePromise = Promise.resolve({
bestmove: randomOpeningResponse,
source: "own book"
})
}
}
}
let bookalgeb = null
let bookSource = null
if(getUseBook(moves, failedLookups)){
let blob = await requestBook(state)
if(blob){
let bmoves = blob.moves
if(bmoves && bmoves.length){
let grandTotal = 0
for(let bmove of bmoves){
bmove.total = bmove.white + bmove.draws + bmove.black
grandTotal += bmove.total
}
let rand = Math.round(Math.random() * grandTotal)
let currentTotal = 0
for(let bmove of bmoves){
currentTotal += bmove.total
if(currentTotal >= rand){
bookalgeb = bmove.uci
bookSource = blob.source
break
}
}
}
}
}
if(bookalgeb){
logPage(`${bookSource} book move found ${bookalgeb}`)
enginePromise = Promise.resolve({
bestmove: bookalgeb,
source: bookSource + " book"
})
}else{
failedLookups.count++
logFile(`failed lookups ${failedLookups.count}`)
}
if(!enginePromise){
logFile(`making engine move`)
let doPonder = ( ( state.botTime > ( 15 * SECOND ) ) || isEnvTrue("ALLOW_LATE_PONDER") ) && allowPonder
if(isEnvTrue('REDUCE_LATE_TIME')){
if(state.botTime < ( 30 * SECOND ) ) state.botTime = Math.floor(state.botTime * 0.75)
if(state.botTime < ( 15 * SECOND ) ) state.botTime = Math.floor(state.botTime * 0.75)
}
logPage(`engine time ${state.botTime} ponder ${doPonder} thinking with ${engineThreads} thread(s) at skill level ${engineSkillLevel} using ${engineHash} hash and overhead ${engineMoveOverhead}`)
analyzejob.position(`fen ${state.initialFen}`, moves)
let timecontrol = state.realtime ? {
wtime: state.botWhite ? state.botTime : state.wtime, winc: state.winc,
btime: state.botWhite ? state.btime : state.botTime, binc: state.binc,
ponderAfter: allowPonder
}
:
{
wtime: correspondenceThinkingTime * SECOND, winc: 0,
btime: correspondenceThinkingTime * SECOND, binc: 0
}
analyzejob.setTimecontrol(timecontrol)
analyzejob.processing = false
analyzejob.waiting = true
enginePromise = actualengine.enqueueJob(analyzejob)
}else{
if(state.realtime) engine.stop()
}
logFile(`launching search`)
enginePromise.then(result => {
let bestmove = result.bestmove
let ponder = result.ponder
let score = {unit: "none", value: "none"}
try{
scoreTemp = result.depthInfos[result.depthInfos.length - 1].score
if(scoreTemp) score = scoreTemp
}catch(err){/*console.log(err)*/}
let logMsg = `bestmove: ${bestmove}, ponder: ${ponder || "none"}, source: ${result.source || "engine"}, score unit: ${score.unit}, score value: ${score.value}`
logPage(logMsg)
logFile(`bestmove ${bestmove} ponder ${ponder} score ${score}`)
lichessUtils.postApi({
url: lichessUtils.makeBotMoveUrl(gameId, bestmove), log: logApi, token: process.env.TOKEN,
callback: content => {
logFile(`make move response ${content}`)
if(logApi) logPage(`move ack: ${content}`)
if(content.match(/error/)){
if(state.realtime && playingGameId && (gameId == playingGameId)){
logPage(`retry move for ${gameId} ${bestmove}`)
engine.spawn() // restart engine for retry move
setTimeout(_ => makeMove(gameId, state, moves, analyzejob, actualengine, failedLookups), 10 * SECOND)
}
}
}
})
})
}
function abortGame(gameId){
console.log(`aborting game ${gameId}`)
lichessUtils.postApi({
url: lichessUtils.abortGameUrl(gameId), log: logApi, token: process.env.TOKEN,
callback: content => logPage(`abort game response: ${content}`)
})
}
function enqueueGame(gameId){
if(playQueue.find(id => id == gameId)){
logFile(`game already in queue ${gameId}`)
return
}
playQueue.push(gameId)
logFile(`enqueued game ${gameId} , queue ${playQueue}`)
}
function playGame(gameId){
let abortGameTimeout = null
logPage(`playing game: ${gameId}`)
let actualengine, analyzejob, speed, correspondence, realtime, botWhite, variant, initialFen, whiteName, blackName, whiteTitle, blackTitle, whiteRating, blackRating, rated, mode
let playgame = true
let playgameTimeout = null
let duration = null
let storedChess = null
let storedMoves = null
let failedLookups = {
count: 0
}
streamNdjson({url: lichessUtils.streamBotGameUrl(gameId), token: process.env.TOKEN, timeout: generalTimeout, log: logApi, timeoutCallback: _=>{
logPage(`game ${gameId} timed out ( playing : ${playingGameId} )`)
if( (gameId == playingGameId) || correspondence ){
playGame(gameId)
}
}, callback: async function(blob){
logFile(`game event ${JSON.stringify(blob)}`)
if(!playgame) return
lastPlayedAt = new Date().getTime()
if(blob.type == "gameFull"){
speed = blob.speed
correspondence = ( speed == "correspondence" )
realtime = !correspondence
if(realtime && playingGameId && ( gameId != playingGameId )){
playgame = false
logPage(`can't start new game ${gameId}, already playing ${playingGameId}`)
return
}
if(realtime){
playingGameId = gameId
setTimeout(_=>lichessUtils.gameChat(gameId, "all", welcomeMessage), 2 * SECOND)
setTimeout(_=>lichessUtils.gameChat(gameId, "all", goodLuckMessage), 4 * SECOND)
engine.spawn()
engine
.setoption("Threads", engineThreads)
.setoption("Skill Level", engineSkillLevel)
.setoption("Hash", engineHash)
.setoption("Move Overhead", engineMoveOverhead)
actualengine = engine
if(blob.clock){
const clock = blob.clock
console.log("clock", clock)
const initial = clock.initial || 0
const increment = clock.increment || 0
duration = initial + lichessUtils.AVERAGE_GAME_LENGTH * increment
}else{
duration = ( 180 * MINUTE ) + ( lichessUtils.AVERAGE_GAME_LENGTH * 180 * SECOND )
}
console.log("duration", duration)
}else{
actualengine = corrEngine
}
//console.log("actual engine", actualengine)
abortGameTimeout = setTimeout(_ => {
console.log(`opponent failed to make their opening move for ${abortAfter} seconds`)
abortGame(gameId)
}, abortAfter * SECOND)
whiteName = blob.white.name
whiteTitle = blob.white.title
whiteRating = blob.white.rating
blackName = blob.black.name
blackTitle = blob.black.title
blackRating = blob.black.rating
botWhite = whiteName == lichessBotName
variant = blob.variant.key
initialFen = blob.initialFen
rated = blob.rated
mode = rated ? "rated" : "casual"
if(initialFen == 'startpos') initialFen = startFen
analyzejob = new AnalyzeJob()
analyzejob.setoption("UCI_Chess960", variant == "chess960" ? "true" : "false")
if(useScalachess){
let uciVariant = ( variant == "threeCheck" ? "3check" : variant.toLowerCase() )
if(lichessUtils.isStandard(variant)) uciVariant = "chess"
analyzejob.setoption("UCI_Variant", uciVariant)
if(uciVariant != "chess" && uciVariant != "chess960"){
analyzejob.setoption("EvalFile", "3check-313cc226a173.nnue:atomic-4ecb2067c716.nnue:crazyhouse-ca0dab479c68.nnue:horde-28173ddccabe.nnue:kingofthehill-2103ec0a1135.nnue:racingkings-8ede8541e245.nnue:")
}
}
analyzejob.setoption("Use NNUE", "true");
analyzejob.setoption("SyzygyPath", ( (!disableSyzygy) && lichessUtils.isStandard(variant) ) ? syzygyPath : "<empty>")
}
if(blob.type != "chatLine"){
if(playgameTimeout){
clearTimeout(playgameTimeout)
}
playgameTimeout = setTimeout(_ => {
if(playingGameId && (gameId == playingGameId)){
console.log("playing game timed out, shutting down", gameId)
playingGameId = null
}
}, duration)
let moves = []
let state = blob.type == "gameFull" ? blob.state : blob
state.variant = variant
state.initialFen = initialFen
state.fen = initialFen
state.movesArray = []
state.whiteTitle = whiteTitle
state.blackTitle = blackTitle
state.rated = rated
state.mode = mode
state.correspondence = correspondence
state.realtime = realtime
if(state.moves){
logFile(`setting up fen from moves`)
moves = state.moves.split(" ")
state.movesArray = moves
if(getUseBook(moves, failedLookups) || calcFen){
if(useScalachess && (state.variant != "standard")){
let result = makeUciMoves(state.variant, state.initialFen, moves)
state.fen = result.fen
}else{
if(useScalachess) logPage(`switched to chess.js for variant standard`)
let chess = new Chess()
let updateDone = false
if(storedMoves && ( (moves.length - storedMoves.split(" ").length) == 1 ) && incrementalUpdate ){
if(state.moves.substring(0, storedMoves.length) == storedMoves){
chess = storedChess
const lastMove = moves[moves.length - 1]
chess.move(lastMove, {sloppy:true})
updateDone = true
logFile(`updated chess incrementally with move ${lastMove} , stored was ${storedMoves} , update was ${state.moves}`)
}
}
if(!updateDone){
for(let move of moves) chess.move(move, {sloppy:true})
}
state.fen = chess.fen()
storedMoves = state.moves
storedChess = chess
}
logFile(`setting up fen from moves done`)
}else{
logFile(`skipping setting up fen`)
}
}
if( abortGameTimeout && ( (botWhite && (state.movesArray.length > 1)) || ((!botWhite) && (state.movesArray.length > 0)) ) ){
clearTimeout(abortGameTimeout)
abortGameTimeout = null
}
state.botWhite = botWhite
state.botTime = botWhite ? state.wtime : state.btime
state.orientation = botWhite ? "w" : "b"
state.title = `${formatName(whiteName, whiteTitle)} ( ${whiteRating} ) ${formatTime(state.wtime)} - ${formatName(blackName, blackTitle)} ( ${blackRating} ) ${formatTime(state.btime)} ${state.variant} ${state.mode}`
state.lastmove = null
if(state.movesArray.length) state.lastmove = state.movesArray.slice().pop()
if(realtime && (!disableLogs)) ssesend({
kind: "refreshGame",
gameId: gameId,
fen: state.fen,
orientation: state.orientation,
title: state.title,
lastmove: state.lastmove
})
let whiteMoves = (moves.length % 2) == 0
let botTurn = (whiteMoves && botWhite) || ((!whiteMoves) && (!botWhite))
if(logApi) logPage(`bot turn: ${botTurn}`)
if(botTurn){
try{
makeMove(gameId, state, moves, analyzejob, actualengine, failedLookups)
}catch(err){
console.log(err)
}
}
}
}})
}
function decline(challengeId, reason){
console.log("ignoring challenge", challengeId, "reason", reason)
if(declineHard){
console.log("declining challenge", challengeId, "reason", reason)
lichessUtils.postApi({
contentType: "application/x-www-form-urlencoded",
url: lichessUtils.declineChallengeUrl(challengeId), log: this.logApi, token: process.env.TOKEN,
body: `reason=${reason}`,
callback: content => console.log(`decline challenge response: ${content}`)
})
}
}
function streamEvents(){
streamNdjson({url: lichessUtils.streamEventsUrl, token: process.env.TOKEN, timeout: generalTimeout, log: logApi, timeoutCallback: _=>{
logPage(`event stream timed out`)
streamEvents()
}, callback: blob => {
if(blob.type == "challenge"){
let challenge = blob.challenge
let challengeId = challenge.id
let rated = challenge.rated
let challenger = challenge.challenger
let challengerTitle = challenger.title
let variant = challenge.variant.key
let speed = challenge.speed
let correspondence = speed == "correspondence"
let realtime = !correspondence
let speedok = acceptSpeeds.includes(speed)
if(correspondence && allowCorrespondence) speedok = true
if( (realtime && playingGameId) || playQueue.length ){
decline(challengeId, `later`)
}else if(!acceptVariants.includes(variant)){
decline(challengeId, `variant`)
}else if(!speedok){
decline(challengeId, `timeControl`)
}else if(rated && disableRated){
decline(challengeId, `casual`)
}else if((!rated) && disableCasual){
decline(challengeId, `rated`)
}else if((challengerTitle == "BOT") && disableBot){
decline(challengeId, `noBot`)
}else if((challengerTitle != "BOT") && disableHuman){
decline(challengeId, `onlyBot`)
}else{
lichessUtils.postApi({
url: lichessUtils.acceptChallengeUrl(challengeId), log: logApi, token: process.env.TOKEN,
callback: content => logPage(`accept response: ${content}`)