Compare commits
637 commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41e6fd78ef | ||
|
|
5ca8270db9 | ||
|
|
66ac7d0af1 | ||
|
|
dcdb501f16 | ||
|
|
9067bae1ce | ||
|
|
efe4405ea4 | ||
|
|
6f0c080875 | ||
|
|
7967a29083 | ||
|
|
08eb349d87 | ||
|
|
9c26d03952 | ||
|
|
99b16f6184 | ||
|
|
727c8f8500 | ||
|
|
2b8bd1c402 | ||
|
|
c52e7c7747 | ||
|
|
e2b3615a19 | ||
|
|
e27e9e3066 | ||
|
|
c137d3552d | ||
|
|
1ccdda171b | ||
|
|
79426f7a00 | ||
|
|
b892dcd923 | ||
|
|
dc696c72f2 | ||
|
|
102298a9ed | ||
|
|
e8cbb9b440 | ||
|
|
12ce66b33a | ||
|
|
d42fc5b68e | ||
|
|
d2e642adb9 | ||
|
|
1cf8d547bf | ||
|
|
a98e34711b | ||
|
|
870227100d | ||
|
|
69cdb3e372 | ||
|
|
d8223bad04 | ||
|
|
32b0b282f8 | ||
|
|
e51510a115 | ||
|
|
d086fcbd92 | ||
|
|
80baa970e7 | ||
|
|
36629195cc | ||
|
|
9601345201 | ||
|
|
9496c26a25 | ||
|
|
417160f383 | ||
|
|
02b6c24d7b | ||
|
|
286ae48207 | ||
|
|
1f76639b8f | ||
|
|
ae78e82ddb | ||
|
|
2dc8274f34 | ||
|
|
7930d332f1 | ||
|
|
27ffa33d7c | ||
|
|
8068a45abd | ||
|
|
3e30621684 | ||
|
|
77f4035853 | ||
|
|
9597d89079 | ||
|
|
3b8c331556 | ||
|
|
72f31e809b | ||
|
|
c5c7ea9508 | ||
|
|
065c922287 | ||
|
|
61e31c53d3 | ||
|
|
e0671c02be | ||
|
|
1579f3743b | ||
|
|
b087d4b4e5 | ||
|
|
4630ba99af | ||
|
|
6a44da4017 | ||
|
|
f00bc733d0 | ||
|
|
d6b08dded3 | ||
|
|
249ad4d478 | ||
|
|
d98b11a1f7 | ||
|
|
36b9b170c5 | ||
|
|
3dbeaeeeb7 | ||
|
|
3554e9f700 | ||
|
|
93d7c87dc7 | ||
|
|
5d76d3afc8 | ||
|
|
afd71a0899 | ||
|
|
ef6bd750ea | ||
|
|
1e15c61e3d | ||
|
|
9cdab7235b | ||
|
|
71e7dcec59 | ||
|
|
d971ded259 | ||
|
|
4292cd4c74 | ||
|
|
a1c0afbbbf | ||
|
|
44116103be | ||
|
|
1edf0abb54 | ||
|
|
b9d6319302 | ||
|
|
d03dde6fcd | ||
|
|
91b2afe706 | ||
|
|
2f738dceda | ||
|
|
e6b5464352 | ||
|
|
fcb7264570 | ||
|
|
e8808f605d | ||
|
|
4b922aba02 | ||
|
|
4e6f780c81 | ||
|
|
d1e127da67 | ||
|
|
03523cb16b | ||
|
|
0342d90657 | ||
|
|
e25f843526 | ||
|
|
69328ce257 | ||
|
|
3bc1641a46 | ||
|
|
fbae6fc3ed | ||
|
|
7a6eb29013 | ||
|
|
032470f486 | ||
|
|
040e25faab | ||
|
|
b533f3baa8 | ||
|
|
e1ae8e0164 | ||
|
|
8e1f2d66a5 | ||
|
|
eac0604300 | ||
|
|
2cd6b71198 | ||
|
|
95aa9b6532 | ||
|
|
2b48a6ad65 | ||
|
|
52e740cdae | ||
|
|
410eb81544 | ||
|
|
ed0cac9974 | ||
|
|
c96f9e7644 | ||
|
|
74e8611f8e | ||
|
|
d7aad7d965 | ||
|
|
f317b25bc5 | ||
|
|
647e302f1c | ||
|
|
1e7638c4b9 | ||
|
|
f3df5e5d23 | ||
|
|
3c45d7dca1 | ||
|
|
9d64aa0144 | ||
|
|
9a5522bbb1 | ||
|
|
2243280aff | ||
|
|
9d74873edb | ||
|
|
176a6995b1 | ||
|
|
95f3851557 | ||
|
|
7001174d79 | ||
|
|
267f9efc72 | ||
|
|
b3153c020f | ||
|
|
b4a7576251 | ||
|
|
8b92adcaa8 | ||
|
|
1de0723c35 | ||
|
|
46ba4e04d2 | ||
|
|
d7d5d21372 | ||
|
|
48d2cedbee | ||
|
|
ff0276f325 | ||
|
|
940ce0df10 | ||
|
|
4ad080cb91 | ||
|
|
df6e0e0964 | ||
|
|
ad8d036913 | ||
|
|
52c31d94b5 | ||
|
|
6812638a5b | ||
|
|
80bddc8694 | ||
|
|
8035fc03cc | ||
|
|
727541a9d8 | ||
|
|
112450d158 | ||
|
|
d3174600e7 | ||
|
|
c860a128e4 | ||
|
|
2729779501 | ||
|
|
7fb7be305d | ||
|
|
d2c7294ed3 | ||
|
|
50e0119497 | ||
|
|
934a83588a | ||
|
|
f303f29f22 | ||
|
|
7c65b9e7ed | ||
|
|
85701dbb82 | ||
|
|
4ec3fb4a1a | ||
|
|
efd7a42edd | ||
|
|
7f3b742451 | ||
|
|
fca11b39d2 | ||
|
|
dd6e4f4f8a | ||
|
|
e7729d0a1e | ||
|
|
1a6c63e920 | ||
|
|
b5fba00e0b | ||
|
|
bf6090f413 | ||
|
|
478e767c83 | ||
|
|
7c0f1b3b05 | ||
|
|
131e2f7b9c | ||
|
|
8d3db207be | ||
|
|
8ebd1fd425 | ||
|
|
aa444c2d94 | ||
|
|
98735eb769 | ||
|
|
9c8cda44c1 | ||
|
|
908f2e0de9 | ||
|
|
107b0b825a | ||
|
|
d7fb2a9617 | ||
|
|
8c96fa5bc1 | ||
|
|
f19b337d7b | ||
|
|
eb294e9b14 | ||
|
|
151b7786ed | ||
|
|
02d3709944 | ||
|
|
aef744af50 | ||
|
|
7f4fdf6043 | ||
|
|
f9c85ab0c3 | ||
|
|
57c0594a90 | ||
|
|
c1d726c105 | ||
|
|
e62e4c7c98 | ||
|
|
13768c61cb | ||
|
|
939aaeea59 | ||
|
|
27c4977412 | ||
|
|
b9860edc77 | ||
|
|
5259e93034 | ||
|
|
0cdbef97fe | ||
|
|
8841fdacb9 | ||
|
|
b8d313b029 | ||
|
|
45ffdba8ae | ||
|
|
28e732448e | ||
|
|
72f4bb54f3 | ||
|
|
c3e1dd9348 | ||
|
|
8c2000f6b1 | ||
|
|
32f330b1c3 | ||
|
|
c652bce7d2 | ||
|
|
b7a9ec3e3c | ||
|
|
351b3aa522 | ||
|
|
57546ea18e | ||
|
|
d57b3ae10f | ||
|
|
10ef838e87 | ||
|
|
123b3d00ea | ||
|
|
fe109cff84 | ||
|
|
b03bec267c | ||
|
|
cdc7c6d1eb | ||
|
|
52c8aaffd6 | ||
|
|
fb76a1e6fd | ||
|
|
87b153db6f | ||
|
|
3482142ae5 | ||
|
|
eeeccc60d4 | ||
|
|
2ff634a0ed | ||
|
|
39941c257e | ||
|
|
1e9b1d458b | ||
|
|
8491b1a8f6 | ||
|
|
cf9ab5e774 | ||
|
|
7aa6506e70 | ||
|
|
29af343739 | ||
|
|
b2dddf8f06 | ||
|
|
96062ed114 | ||
|
|
253927f10c | ||
|
|
bac645ed5b | ||
|
|
6906a333b3 | ||
|
|
e23a0e2c90 | ||
|
|
5b24282224 | ||
|
|
6da0449ae9 | ||
|
|
cfbe1afdcd | ||
|
|
39fb61fd31 | ||
|
|
7295064167 | ||
|
|
0d72311911 | ||
|
|
8d709d7fb9 | ||
|
|
ea59443748 | ||
|
|
97e7cb17bd | ||
|
|
eae0b3d127 | ||
|
|
0d8d5df472 | ||
|
|
82f3833d8f | ||
|
|
034a5de66e | ||
|
|
08bf22cfec | ||
|
|
4b554f2ecb | ||
|
|
3fd44908af | ||
|
|
ae70e8e750 | ||
|
|
6c0342ad1f | ||
|
|
ac5ce7fa05 | ||
|
|
0ad36c2178 | ||
|
|
b6d89847bb | ||
|
|
b405bf78fc | ||
|
|
f9d24699c1 | ||
|
|
80f671953a | ||
|
|
47799d7e47 | ||
|
|
95fd50b0bb | ||
|
|
ad9aabb265 | ||
|
|
8b0e198c03 | ||
|
|
c7fd54b067 | ||
|
|
b74fe1bda6 | ||
|
|
24d865aa57 | ||
|
|
c358b715c7 | ||
|
|
2d9d4177be | ||
|
|
4ce7331c6a | ||
|
|
3250d95d38 | ||
|
|
c04fbe88b8 | ||
|
|
35854ee253 | ||
|
|
b57c022860 | ||
|
|
81e4fbd215 | ||
|
|
2d88a04584 | ||
|
|
ba835c0604 | ||
|
|
7438fd1065 | ||
|
|
2526dd458d | ||
|
|
5b76685e5c | ||
|
|
b2366ed260 | ||
|
|
b4cfa2b320 | ||
|
|
894307a35c | ||
|
|
296392fb96 | ||
|
|
c5c0d853ae | ||
|
|
017eba4ca2 | ||
|
|
44c587221a | ||
|
|
62c242c9a7 | ||
|
|
41d5bc8b21 | ||
|
|
d1a2504104 | ||
|
|
48ba0048da | ||
|
|
9cf90d0ad0 | ||
|
|
c5c5aac970 | ||
|
|
3192f42b5a | ||
|
|
b7e5f193b4 | ||
|
|
daec638bfc | ||
|
|
a0acb27c7a | ||
|
|
823e4188be | ||
|
|
2680f3d82b | ||
|
|
4d609d996f | ||
|
|
2a503b223e | ||
|
|
83740911e8 | ||
|
|
d88684d86e | ||
|
|
a031b81d4d | ||
|
|
186e4c65d1 | ||
|
|
23eeddf44f | ||
|
|
1c498734b4 | ||
|
|
366c9a2542 | ||
|
|
3048c18b14 | ||
|
|
a47fc0735f | ||
|
|
4a66bbf998 | ||
|
|
09f205e458 | ||
|
|
de4a750cdd | ||
|
|
3e57b41e13 | ||
|
|
a72cb7d760 | ||
|
|
da1a4e2f3c | ||
|
|
1a4a62d0f2 | ||
|
|
15dc5741d4 | ||
|
|
295908f859 | ||
|
|
add3d67e48 | ||
|
|
640b65ce9a | ||
|
|
8b0c624b21 | ||
|
|
204af83bff | ||
|
|
0dad03727f | ||
|
|
d93d598d01 | ||
|
|
37def9dd6b | ||
|
|
2122db8cc4 | ||
|
|
85e62f6392 | ||
|
|
a428ed817f | ||
|
|
3501a642a2 | ||
|
|
25a43e22df | ||
|
|
935c08839f | ||
|
|
de9b56befe | ||
|
|
167e2a715b | ||
|
|
fde4279633 | ||
|
|
18db953818 | ||
|
|
bc5539c632 | ||
|
|
b6c2fe677b | ||
|
|
9bdc2b70e1 | ||
|
|
88c37d1b48 | ||
|
|
0eba165bed | ||
|
|
89fc8b8d03 | ||
|
|
0355eb4e38 | ||
|
|
dd10a6c19c | ||
|
|
fda5607238 | ||
|
|
54f40221d5 | ||
|
|
19b546f5ab | ||
|
|
597cc40aef | ||
|
|
5e27f9e787 | ||
|
|
0bf27a66c7 | ||
|
|
66aaaec5f1 | ||
|
|
620253b57b | ||
|
|
a77eef8ce7 | ||
|
|
96e2c2f537 | ||
|
|
1fa5566d66 | ||
|
|
7202441716 | ||
|
|
6b8791c605 | ||
|
|
533532ba32 | ||
|
|
5d7b626519 | ||
|
|
999aaca0e8 | ||
|
|
38fdf9b4d8 | ||
|
|
bd6ba6bfd7 | ||
|
|
31e1951376 | ||
|
|
eb78d7104e | ||
|
|
b8845413d3 | ||
|
|
061acfe9f1 | ||
|
|
b9183f1178 | ||
|
|
c3b253925d | ||
|
|
f0d0675bad | ||
|
|
29a5859354 | ||
|
|
a469844f61 | ||
|
|
20c70f16e6 | ||
|
|
d2ee430b7d | ||
|
|
2decbdf69c | ||
|
|
2cb22ad3c4 | ||
|
|
bdbb8b4393 | ||
|
|
a8fa75411c | ||
|
|
2d1f48f3e6 | ||
|
|
63a332947b | ||
|
|
7756d89d41 | ||
|
|
9dc8aac45a | ||
|
|
0402cf5845 | ||
|
|
d50fc201bb | ||
|
|
318db6bed0 | ||
|
|
48356c0179 | ||
|
|
d9868a3757 | ||
|
|
31af9e3ff5 | ||
|
|
3e7bbdffad | ||
|
|
72fb233af7 | ||
|
|
296de1d946 | ||
|
|
f5f56d29c0 | ||
|
|
cb90e735fd | ||
|
|
e1a6a582fa | ||
|
|
64d71adc35 | ||
|
|
251baf5894 | ||
|
|
99c18bdf7a | ||
|
|
73f0a4af72 | ||
|
|
662fd98d69 | ||
|
|
43938083d4 | ||
|
|
70676d7bfb | ||
|
|
664dd24bbd | ||
|
|
2c60af18cc | ||
|
|
e7518507ae | ||
|
|
11d6d195e7 | ||
|
|
59928d6f8c | ||
|
|
caa979a671 | ||
|
|
3aab9f1d73 | ||
|
|
2b31bd5632 | ||
|
|
dc89369c2a | ||
|
|
d9f3cede11 | ||
|
|
4edd760ff6 | ||
|
|
6021439fe6 | ||
|
|
2d61c09219 | ||
|
|
928d6f0111 | ||
|
|
8c2dd05d0b | ||
|
|
59757c2256 | ||
|
|
198c636442 | ||
|
|
2d7aff4956 | ||
|
|
816de9b5ec | ||
|
|
7de22c2180 | ||
|
|
41e1a62983 | ||
|
|
a4aa48c401 | ||
|
|
97c328dce6 | ||
|
|
5f2dd38d2d | ||
|
|
51ed64d789 | ||
|
|
91481b1d6b | ||
|
|
abd55c0846 | ||
|
|
dbd2fa7b55 | ||
|
|
78d2b7c8c9 | ||
|
|
73e11349dc | ||
|
|
5f478dd318 | ||
|
|
4e6e8294d2 | ||
|
|
601f7028bd | ||
|
|
7672db1992 | ||
|
|
dbc801169c | ||
|
|
dc4c0f07d5 | ||
|
|
9fc38fa4f4 | ||
|
|
cbcb242d90 | ||
|
|
5216a66db3 | ||
|
|
cbb7ca8772 | ||
|
|
87364af55d | ||
|
|
b04e1e22c1 | ||
|
|
170914b05e | ||
|
|
f4486ee955 | ||
|
|
c8113d9043 | ||
|
|
4701cefbfd | ||
|
|
b3351fb7d9 | ||
|
|
ab05c80d68 | ||
|
|
eeac6ebcf4 | ||
|
|
1d3d8eb2ef | ||
|
|
235ff2f9b5 | ||
|
|
644e6174d9 | ||
|
|
807e981a4d | ||
|
|
d69ab9f3f9 | ||
|
|
5bc12832e5 | ||
|
|
cb7d5912d2 | ||
|
|
870a2eba95 | ||
|
|
55a62d32b2 | ||
|
|
2b6a28203a | ||
|
|
becbd3de8f | ||
|
|
d0d97e068e | ||
|
|
bb9a474923 | ||
|
|
8501458101 | ||
|
|
90d4073d17 | ||
|
|
039fe743d2 | ||
|
|
101ced4482 | ||
|
|
92536606dd | ||
|
|
b6213344ce | ||
|
|
9ba7f197f1 | ||
|
|
4ebe8418a0 | ||
|
|
81ad85cb03 | ||
|
|
3de3e545e1 | ||
|
|
62d6ece5dc | ||
|
|
1b5bce7ba5 | ||
|
|
47c3674e8c | ||
|
|
b008b3a652 | ||
|
|
8c7b7d3c6b | ||
|
|
79616ead03 | ||
|
|
c09e293939 | ||
|
|
271c562205 | ||
|
|
d309b70e0e | ||
|
|
97223e9d12 | ||
|
|
6ae5cd30dc | ||
|
|
0ca9ad8a95 | ||
|
|
b79eb73fbf | ||
|
|
68bea796f6 | ||
|
|
826ccbef46 | ||
|
|
1065630d29 | ||
|
|
1fcfb58751 | ||
|
|
c40e30234a | ||
|
|
d6856591b4 | ||
|
|
4e17728a20 | ||
|
|
71f459c4e9 | ||
|
|
d48fdbf2e5 | ||
|
|
2699634e0f | ||
|
|
8ccf84cf4a | ||
|
|
a98a0f7154 | ||
|
|
be63e3df67 | ||
|
|
2604a9c74c | ||
|
|
3dbd508b64 | ||
|
|
0ece48a79d | ||
|
|
d8df1e37f6 | ||
|
|
da7f4e6927 | ||
|
|
f24abe8fc7 | ||
|
|
2eb22d1df3 | ||
|
|
ac5928d41d | ||
|
|
e880dc69c1 | ||
|
|
40019c46ae | ||
|
|
0ad1ef6435 | ||
|
|
b640ab9814 | ||
|
|
12ef18f9e6 | ||
|
|
69689f18f4 | ||
|
|
e90f5f675e | ||
|
|
a93eb3e8fd | ||
|
|
cc89a266f3 | ||
|
|
7cbe0ec09b | ||
|
|
77ec31d1a0 | ||
|
|
e17ddc247b | ||
|
|
9b7b1c150c | ||
|
|
efb14680cc | ||
|
|
5dc7bebfb6 | ||
|
|
d2f6ac1d5b | ||
|
|
9fe5f124c6 | ||
|
|
08e88d53a8 | ||
|
|
5f412f72d8 | ||
|
|
c5142046ed | ||
|
|
31e44440e8 | ||
|
|
5f09111a95 | ||
|
|
06da3f7456 | ||
|
|
2b8b641216 | ||
|
|
7e068fde98 | ||
|
|
94488bf8f7 | ||
|
|
871b340910 | ||
|
|
df8edddfe6 | ||
|
|
732c329844 | ||
|
|
cd46128c09 | ||
|
|
4bb5e07c28 | ||
|
|
1692217549 | ||
|
|
13376ceb97 | ||
|
|
537ec4efd0 | ||
|
|
5c2b3a4758 | ||
|
|
adc312f27b | ||
|
|
8d72259500 | ||
|
|
b9b55f1deb | ||
|
|
2223a4b044 | ||
|
|
f4c8400df1 | ||
|
|
023114103d | ||
|
|
d56039695c | ||
|
|
2011311084 | ||
|
|
da8150b7c4 | ||
|
|
faac3427f3 | ||
|
|
587d50decf | ||
|
|
2ac9143db9 | ||
|
|
372893ec75 | ||
|
|
34b72f6d44 | ||
|
|
94b27eadf3 | ||
|
|
ec1cf7d3b5 | ||
|
|
9a0fb48aa3 | ||
|
|
94e71beb16 | ||
|
|
0788b98729 | ||
|
|
e56659f949 | ||
|
|
b485b54d20 | ||
|
|
b5cba3e591 | ||
|
|
ef700a3480 | ||
|
|
f13b0d40af | ||
|
|
23634241c0 | ||
|
|
e80fd0e453 | ||
|
|
4c0d535369 | ||
|
|
e7554f66ea | ||
|
|
9dbbfbe1b8 | ||
|
|
40e4c79139 | ||
|
|
7b7d3ea1b3 | ||
|
|
25e3e6db33 | ||
|
|
675c63d561 | ||
|
|
d69e340f9a | ||
|
|
a0a492f19e | ||
|
|
ad07bfeada | ||
|
|
3fa3b3e579 | ||
|
|
6d839102b5 | ||
|
|
f4980dc098 | ||
|
|
0c4d9c0869 | ||
|
|
2a5a26a831 | ||
|
|
28743698a3 | ||
|
|
9902599a23 | ||
|
|
499862b140 | ||
|
|
ed4d029ba1 | ||
|
|
837c56c13e | ||
|
|
66652576e5 | ||
|
|
d3f550cc3e | ||
|
|
e3534cad4b | ||
|
|
e0a02276a2 | ||
|
|
843811956b | ||
|
|
19a9c60fd5 | ||
|
|
9279908f7d | ||
|
|
db429b1d74 | ||
|
|
cc898ea282 | ||
|
|
6693d734e6 | ||
|
|
92d276bdc5 | ||
|
|
f69a0a526f | ||
|
|
2873ee3435 | ||
|
|
462e783599 | ||
|
|
7def8113f4 | ||
|
|
2d12a20e34 | ||
|
|
1f182b0df9 | ||
|
|
de8ce0a6c3 | ||
|
|
946da17c8b | ||
|
|
47fbd1c124 | ||
|
|
d0fbbed96a | ||
|
|
829d3a4ba6 | ||
|
|
c3c25fe565 | ||
|
|
08413b53a3 | ||
|
|
4717bc0f75 | ||
|
|
7c8fa68659 | ||
|
|
39ef7c13bb | ||
|
|
6489db146e | ||
|
|
8df1b82a2e | ||
|
|
78100bd158 | ||
|
|
7fc8d0f080 | ||
|
|
fa4e30692e | ||
|
|
33c84964fa | ||
|
|
66e13d2fc3 | ||
|
|
531f90f107 | ||
|
|
370ac536f6 | ||
|
|
35fb35103f | ||
|
|
96463577b9 | ||
|
|
327749e0cf | ||
|
|
624f12bfd4 | ||
|
|
1b12a2c014 | ||
|
|
a6829b3d66 | ||
|
|
0fb3d3ab96 | ||
|
|
39063acce7 | ||
|
|
ce83c01f83 | ||
|
|
0f1db884c2 | ||
|
|
2f5a924d6a | ||
|
|
9a01b3d415 | ||
|
|
dd82737af8 | ||
|
|
abe92fe3b1 | ||
|
|
4932b3f93a | ||
|
|
66ae4be72d | ||
|
|
e7ae3b18bf | ||
|
|
330dbd5935 | ||
|
|
925e7c1798 | ||
|
|
744b769000 | ||
|
|
5914711f2c | ||
|
|
8a25ebdb95 | ||
|
|
6de56f79eb | ||
|
|
af155f27bb | ||
|
|
13a29c2c2a |
577 changed files with 71423 additions and 4299 deletions
|
|
@ -14,6 +14,7 @@ load, so splitting code across files costs nothing at runtime. Why it works this
|
|||
src/index.html the shell: <head>, static markup, `<!-- @include styles -->`, `<!-- @include game -->`
|
||||
src/styles/NN-*.css CSS, in order (phones last)
|
||||
src/game/NN-area/NN-*.js the game script, in order (see the map in docs/ARCHITECTURE.md)
|
||||
src/agent/NN-*.js the agent facade the MCP server drives: in the development page only
|
||||
site/ static files copied as they are (dictionaries, icons, service worker)
|
||||
```
|
||||
|
||||
|
|
@ -34,7 +35,8 @@ npm test -- tests/peering.test.js # one suite
|
|||
```
|
||||
|
||||
A browser error points at a line of the assembled page; the dev server prints the `src/` file and line
|
||||
next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you want to look at it.
|
||||
next to it. `npm run page -- -o /tmp/page.html` writes the page players get if you want to look at it;
|
||||
`npm run page -- --source --dev -o /tmp/page.html` the development page `npm run dev` serves.
|
||||
|
||||
## Where new code goes
|
||||
|
||||
|
|
@ -47,7 +49,17 @@ next to it. `npm run page -- -o /tmp/page.html` writes the assembled page if you
|
|||
anything runs after boot. When in doubt, put constants in an earlier file and logic in functions.
|
||||
- **Actions:** add `name:(args)=>{…},` to the matching `src/game/90-actions/*.js`. Only
|
||||
`10-interface.js` declares `const ACT={`; the others are `Object.assign(ACT,{ … });`. A new area can get
|
||||
a new `NN-area.js` file of that second form.
|
||||
a new `NN-area.js` file of that second form. The MCP server types every action: a new one also gets
|
||||
an entry in `src/agent/20-commands.js` (a game command with its argument domains, a view, a draft,
|
||||
a session action, or `API_DENY`); `tests/mcp-commands.test.js` fails until it has one.
|
||||
- **Agent code** (`src/agent/`, the facade the MCP server plays through) is assembled into the
|
||||
development page only (`<!-- @include-dev agent -->`): players never download it. Its top-level names
|
||||
start with `api`/`API_`, and **nothing in `src/game/` may name them**: that would work in `npm run dev`
|
||||
and break for players (`tests/build.test.js` checks). Tests load the players' page; a test of the
|
||||
facade asks for `load({ agent: true })`. Where agent code must change what the game does (agent mode
|
||||
locks the clock, adds a Settings section and a HUD badge), the game calls `HOOKS.x?.()` and reads
|
||||
`UI.clockLocked` (`50-state.js`), and agent code fills them in: add a hook there rather than an `if` for
|
||||
the agent in a game file. See docs/adr/0004-dev-only-code.md.
|
||||
- **Panels and modals:** `93-ui/` (HUD, side panels), `94-dashboard/` (NOC dashboard, bank), `95-modals/`.
|
||||
- **Styles:** the matching `src/styles/*.css`; phone rules go in `60-phone.css`.
|
||||
- **Data tables** (cities, cables, networks): one entry per line, and keep id-keyed objects such as
|
||||
|
|
|
|||
102
.claude/skills/gameplay-rules/SKILL.md
Normal file
102
.claude/skills/gameplay-rules/SKILL.md
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
---
|
||||
name: gameplay-rules
|
||||
description: The design rules of Series of Tubes, each with an id and the test that enforces it. Use whenever you add or change cities, countries, networks (NETS, upstreams, traffic shares, presence), cables, exchanges, data centers, customers, scenarios, puzzles, presets or rules, balance numbers or progression, and before committing any such change.
|
||||
---
|
||||
|
||||
# Gameplay rules
|
||||
|
||||
These are what the game promises, held up by `tests/gameplay-rules.test.js` (one `test()` per id, on the live
|
||||
`CITIES`, `NETS`, `CABLES`, `SCN`, `PZ`, `PRESETS`…). Each rule is true of the intended design.
|
||||
|
||||
## Procedure
|
||||
|
||||
1. Changing anything above? Run `npm test -- tests/gameplay-rules.test.js` (under a minute) before committing.
|
||||
Changing orbit prices, crusts, incidents or orbit customers? Also run `npm test -- tests/pie-balance.test.js` (O7's
|
||||
game-loop half, about a minute).
|
||||
2. A failure names what breaks the rule and how to fix it. Fix the data or the code.
|
||||
3. Only when real life really is different, add an entry to `EXCEPTIONS` in the test (keyed by rule id, sorted, with
|
||||
its reason in plain words). Never delete or loosen a check to make it pass. A stale exception fails too.
|
||||
4. A new rule gets an id in the right section here, one line, a why, and its own `test('ID: …')`.
|
||||
|
||||
## World
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| W1 | Every city has a country code (`cc`, ISO 3166-1 alpha-2; territories have their own: PR, GU, RE, MQ, CW…), a region, a landmass and coordinates. | Borders, prices and the eyeball rule all hang off the country. |
|
||||
| W2 | Every country on the map has at least two consumer networks of its own: an eyeball network, or a Tier 1 or Tier 2 incumbent that sells to homes, whose home markets (`cc` on the network) include that country and which has a PoP there. | Real countries have competing local ISPs, and peering locally is half the game. Add real operators in `src/game/30-networks/32-homegrown-eyeballs.js`. |
|
||||
| W3 | Every city can buy transit from someone, or is a documented exception (Pitcairn: land your own cable, reach it through a pie dish, or rent a satellite circuit from a teleport; Stuttgart: peering only). | A start or an expansion must never be a dead end by accident. |
|
||||
| W4 | Cable pairs join two distinct real cities, have a length, and cable ids are unique. | Broken landings break routing and the own-cable planner. |
|
||||
| W5 | A city alone on its landmass has a cable or a beach to land one. | Islands are reachable. |
|
||||
| W6 | Every island Wi-Fi zone (`WISP`, #83) hangs off a satellite city (`satRemote`) within 1,000 km of it, seen together with it by a GEO bird; its pool is 3 to 12 G of homes; its spur is at most 1,500 km, or there is none (`km:0`); ids are sorted. | A zone is the outer islands of the city they look to, reachable from the first teleport; smaller ones never pay, and pie terminals serve them. |
|
||||
|
||||
## Networks
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| N1 | Network ids and ASNs are unique; ASNs are public (the real one for real-world networks). | Saves key on ids; players look ASNs up. |
|
||||
| N2 | Names are puns: no network, cable, exchange, data center, router, optic, satellite or satellite operator, cable ship or maintenance club is called by a real name (blocklist `REAL_NAMES` in the test), and no lazy "-ish" names. | CLAUDE.md. Add the real name to the blocklist whenever you add its pun. |
|
||||
| N3 | Every non-Tier-1, non-content network is in a founding Tier 1's customer cone (`up`), or is a documented island (transit-free incumbents, China, Korea, Australia…). Upstreams exist and are never content. | Tier 1 by customer cone (#85): a new network outside the cones makes Tier 1 harder for every save, old ones included. |
|
||||
| N4 | No upstream cycles. | Cones must be trees, not loops. |
|
||||
| N5 | Traffic shares are positive and below 20%; `NSH` and the regional tables sum to 1; content carries at least 30%. | Shares drive every flow; eyeballs mostly ask for traffic. |
|
||||
| N6 | Every network has a type, a peering policy (selective ones state `minIx`/`minPni`), a colour and a translated blurb; carriers have a price. | Panels and the peering rules read them. |
|
||||
| N7 | PoPs are real, distinct cities; exchange ports only where the city has an exchange and the network has a PoP. | Presence follows PeeringDB-style reality. |
|
||||
| N8 | A POP's traffic to the networks that sell to homes (`cc`) goes mostly to those whose users live near it: at home above the world share, on other continents below (`locSh()`, `45-home-markets.js`). Only that split moves: a city's total and every network without home markets keep their shares. | People mostly talk to people near them, and peering with an eyeball where its users are must beat hauling its traffic to two cities (#48). |
|
||||
|
||||
## Modes and rules
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| M1 | On-call is the classic game: it equals `RULE_DEF`, and a save without rules loads as On-call. The seeded suites (`tests/game.test.js`, `tests/rules.test.js`) are its behaviour. | Old saves never change under them. |
|
||||
| M2 | Presets are ordered: Best Effort never harsher than Change Freeze, Change Freeze never harsher than On-call, BGP at 3 a.m. never gentler (chaos, lead times, market; and a seeded year of incidents). Only Best Effort mends sea cuts without ships, skips conferences, rescues instead of game over, has patient customers and instant PNIs. | The names promise it. |
|
||||
| M3 | Every subsystem that can annoy the player reads a rule: outages and events (`chaos`), DDoS, sold-out routes, de-peering and hardware prices (`market`), lead times (`lead`), the clock, cable ships (`sea`), conferences (`confs`), going broke (`broke`), customer patience (`moods`), PNI delivery (`pnis`), scarce IPv4, CGNAT and IPv6-only homes behind NAT64 (`ip4`, On-call and BGP at 3 a.m. only; scenarios opt in), and the day's toasts (quiet notifications). A quiet ruleset gives a quiet year. | Rules are presets of flags, not separate code. |
|
||||
| M4 | Scenarios and the weekly challenge always run On-call plus their own `S.scn.rules`. | Fair scores. |
|
||||
| M5 | Sandbox has no locked feature: open gates, every level, own cables, endless money. | It is a sandbox. |
|
||||
| M6 | A Normal game picks its charter once, when it starts (sandbox, puzzles and scenarios never do). A charter changes what you set out to do, never what things cost: the Cable broker gets glass (fiber, line systems, optics, own subsea cables and the routers to light them) from day one at the prices everyone pays at the top level, and everything else by level. | Same prices and rules for every charter (#300). |
|
||||
|
||||
## Content
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| C1 | Every scenario has a name, a goal, an `ok()` its progress card (`SCN_PROG`) shows, and cannot be won on day 0; so does every committed weekly scenario (`site/scenarios/weekly/`, its goal type's card in `WS_GOALS`). | A goal must need play. |
|
||||
| C2 | Every puzzle has a 1-star and a 3-star reference solution in `REF` of `tests/puzzles.test.js`, which builds and scores them. | Every puzzle is solvable and every star reachable. |
|
||||
| C3 | Every player-facing string is translated in every language (`node scripts/i18n-check.js`: 0 missing, 0 unused, 0 broken). | CLAUDE.md; see `add-strings`. |
|
||||
| C4 | Every Architect run, handmade (`REF` in `tests/architect.test.js`) or weekly (`ref` in its file, `scripts/weekly-architect.js --check`), has a reference build that passes every brief's chaos monkey review and earns three stars; every weekly brief takes at least one change (a tube, a bigger tube, a move), and later briefs' cities stay hidden until they come. | A run you cannot finish, or a brief that asks for nothing, is not a puzzle; knowing the next brief makes it a chore. |
|
||||
|
||||
## Fun and fairness
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| F1 | A new network gets a gentle start (counted from the network's own first day; hardware prices hold for the calendar's first 180 days, see F11): no outage before day 45, no event before day 40 and only good news before day 50, nothing sold out for 90 days, hardware prices hold for 180, and a new customer loses no mood for 15 days. Its first IPv4 block covers the start: no home behind CGNAT, no IPv4 bill and no IPv4 warning before day 50, even signing every offer that fits. | New players learn before they get punished. |
|
||||
| F2 | On On-call, a simple build in a start city (broadband, the cheapest 100G transit, an exchange port with the route server) makes money within 3 months, in Frankfurt, New York, Singapore and Johannesburg. | Seeded today it turns a profit in month 1 or 2; a balance change that breaks this makes the start too hard. |
|
||||
| F3 | A specialist path (#187) only brings a customer type in below its level when the network can already serve it, or nearly: the spotted cities have POPs, the latency is met, the fiber carries at least three quarters of the smallest order. | Capability, not luck: an offer you cannot fulfil with a reasonable build is a trap. |
|
||||
| F4 | The chaos monkey visits only On-call and BGP at 3 a.m. (never Change Freeze, Sandbox, puzzles or scenarios), not before day 180, for 120 to 240 days; while it is here its snips replace the ordinary failures, each snip heals within a week, and it goes after tubes with no other way round first. | A test of resilience you can prepare for, not a pile-on: the reward goes to networks built with a second path. |
|
||||
| F5 | Capacity you rent to other carriers never outgrows the route's market: the capacity market sells a listing over time as carriers between the two cities want it, never past what they want that day (both cities' eyeballs, a landing town counting the big city it serves, grown about 15% a year up to 8 times, and at most 2.5 times its usual size on its hottest day), and a random offer never past what the eyeballs alone support. | Rent that scales with your own glass and not with demand is a money machine (#203); a market that never moves or grows makes no decisions. |
|
||||
| F6 | An alien wave rents for at most 30% of what its fiber costs a month (lease plus amplifiers), each wave sold between two cities is never dearer than the one before, and a route sold out to its market earns less than eight times that cost. | A buyer would lease the fiber rather than pay many times its price; the old price made one wave worth the whole fiber and a full route 11 to 35 times its lease (#203). |
|
||||
| F7 | Extra crews cut a build on land to half its planned time at most. | Permits, rights of way and trenching set the pace; a 1,000-day build finishing tomorrow made lead times meaningless (#203). |
|
||||
| F8 | In the capacity market (Lambda Bazaar), a managed wave comes out of capacity you lit yourself (your own traffic gets that much less, and the customer suffers when your optics cannot carry it), rides one channel (an 800G or 1.6T wave needs an optic that big), and is priced against its fiber: a 400G wave 2.7 times a 100G one on land and 3.8 times on subsea, each bigger size cheaper per bit. Spectrum lists at 30% of the fiber's monthly cost, and heat moves any price by at most −30% to +35%. | Selling lit capacity must cost capacity, or every fiber sells twice; the ratios are 2025 market prices (TeleGeography), so bigger waves win on volume, not on price per bit. |
|
||||
| F9 | A strict latency contract (`BIZ_T.lowlat`, #137) comes only from customer level 7, is 1.6T or 3.2T and never grows past 3.2T, has a latency limit something you can build meets (`latMaxOf`, as trading links), pays more per Gbps than any other big circuit on the same route even with all their extras, and once its 15-day grace is over credits a day's fee and loses patience faster for every day over its limit. | Real low-latency routes sell at a premium for guaranteed milliseconds and pay service credits when they miss; the cap keeps one contract from carrying a level. |
|
||||
| F10 | Growth goes sideways, plus one paid way up: a PNI bundles eight members per router at its POP, up to 32 (`pniLagMax()`); transit, exchange and fabric LAGs stay at eight (`LAG_MAX`). Giant AI circuits land at campuses (`MEGA`) in at least 30 metros, no metro more than two, picked less often where giant circuits already crowd the city. | Raising caps only moves the wall; a fatter PNI costs a router (its price and its port slots), and the late game's demand spreads over many metros as real AI and cloud campuses do (#61, #323). |
|
||||
| F11 | A network that joins a server session after its first 180 days starts on the session's date with F1's gentle start, the charter and the tutorial counted from its own first day, a starting-cash top-up as large as the rise in hardware prices (START_CASH × (hwTrend − 1), at most $60k), and its first 365 days of home broadband income matched (after wholesale cuts, outside investors' share); the market stays on the session's date. | One market for everyone, and a friend who joins late still gets a fair start. |
|
||||
| F12 | Island Wi-Fi (#83), on a zone's own books at full take-up in era 1 (its homes at island prices less the towers' upkeep and the backhaul rent; the teleport, tracking antennas and a Starblink gateway are shared and left out), makes money on at least one way in; a spur earns more than any satellite option, MEO at least as much as GEO and LEO at least as much as MEO where both reach; spurs up to 250 km pay back within 5 years against the best GEO or MEO stage, up to 1,000 km within 10. | The ladder (GEO, then MEO or LEO, then your own cable) must be worth climbing, and its first rung must not lose money; the longest spurs are a choice, not a given. |
|
||||
|
||||
## DDoS
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| D1 | Attack sizes come from the world, never from your network: a heavy tail (median near 9 G, one in a hundred over 650 G) scaled by the era, capped at the era's record, and for the first 180 days (or with one POP) never more than twice your biggest port. Ten times the subscribers means the same attacks. | Sizes that grew with the network made every late-game flood larger than the internet's record (#242). |
|
||||
| D2 | A flood enters on every port the internet reaches you on, by each network's share, and a port carries only what fits: everyone on a full port loses the same share. | Real floods are spread by geography; one fat port at a single POP is the weak spot (#242). |
|
||||
| D3 | Only upstream tools (RTBH, clean pipe) and an engaged scrubbing center keep a flood off your ports. Flowspec acts on the ingress router, after the port, within that router's own rule budget. | Flowspec protects customers, not the external connections; TCAM is finite. |
|
||||
| D4 | RTBH costs only the target: it goes dark (and its mood drops once), everyone else is saved, and the attack counts as sacrificed, not held. | RTBH is the tool that saves the network and is bad for that one customer, so it must be a real choice. |
|
||||
|
||||
## Orbit (Pie in the Sky, `docs/plans/pie-in-the-sky.md`)
|
||||
|
||||
| Id | Rule | Why |
|
||||
| --- | --- | --- |
|
||||
| O1 | The rocket company unlocks only on the Tier 1 win of a save started on its version (`S.pieV>=1`, set by `newGame()`; a save without it loads as 0), or from day 0 with open gates (sandbox). Never in puzzles, the Architect or scenarios. Losing Tier 1 keeps everything flying but builds nothing new. | An endgame for people who earned it; old won saves must not change under their players. |
|
||||
| O2 | A crust under 40% coverage carries nothing; from 40% a half-baked crust carries a share that grows to all of its capacity at 60% (a slope, not a cliff), and orbit never carries more than the pie dishes' antennas (x rain, jamming): terminals and sky paths share each dish. | Satellites are not magic bandwidth; the ground segment is the bottleneck, as in real life. |
|
||||
| O3 | A cut-off pie dish (its POP on an island the backbone does not reach) carries only its own POP's traffic (backhaul, to a landing dish on the backbone) and local terminals, never transit between other cities: no POP on the backbone routes through it. Backhaul is small (the dish's antennas, the landing dish's and the crust's room) and pays the orbit's latency. | Orbit extends your network to a town no cable reaches; it does not replace building one, and laying fiber stays the real fix. |
|
||||
| O4 | Through space with lasers, light travels at c in vacuum (about 1.47 times glass), up and down at the shell's height; orbit never carries traffic between cities under 3,000 km apart and only latency-routed circuits fly: IP traffic, bulk and scenic circuits stay on fiber. | Real constellations win only on long routes, and their capacity is small. |
|
||||
| O5 | Launches fail only with chaos on (`rule('chaos')`), and never in the first 90 days after the unlock; heavy test flights explode by design, not by chance. Orbit incidents and geopolitical spats (`pieChaos()`) follow the same rule. | Like F1: learn the thing before it punishes you. |
|
||||
| O7 | A fresh Tier 1 cannot afford a full Shortcrust from its first year's money: even a big network's yearly profit plus the largest loan a bank would offer (and the Ex-Im Pie Bank's most) stays below the cheapest full build (`pieFullCost('short')`). And a full lasered Shortcrust, played through the game loop on the big-network save by a sensible policy (reusable rockets, two pads, no launches past the crust's size except replacements, safe mode in storms, dishes grown with demand at well-served POPs, every orbit offer signed), pays back on its own books (`S.pie.book`: every launch, replacement, dish, licence and running cost against orbit income) in 5 to 10 years, never sooner; government money (the Rural Digital Pie Fund, Pitcairn's satellite grant) brings that forward by at most two years, never under four (`tests/pie-balance.test.js`; `PIE_BALANCE_YEARS=10` prints the long run). | Obscenely expensive is the joke and the goal; a constellation in year one would be a cheat code. |
|
||||
| O8 | Rented LEO (Starblink, #83) reaches only within `SAT_ORB.leo.km` of a gateway under its shell (`SAT_ORB.leo.lat`) at a POP on your fiber (the mainland, or an island with a lit wired link or transit); once a crust of your own carries traffic it sells nothing new (no gateway, circuit or growth), while circuits already rented keep running; and every size costs more per Gbps than any subsea wave over its whole reach. | A bent pipe is regional; the rented tier must not undercut your own constellation; and a cable stays the better buy wherever one can go. |
|
||||
|
||||
|
|
@ -31,6 +31,13 @@ one, redesign the feature.
|
|||
- **Limits:** about 1 GB for the whole site, 100 MB per file.
|
||||
- **Paths:** the site lives at the domain root (`site/CNAME`), so `/` paths are fine; unknown paths get
|
||||
`404.html`.
|
||||
- **Local tools are not hosting.** `npm run dev` and the MCP server (`npm run mcp`, also over `--http`)
|
||||
run on a developer's own machine against a checkout; nothing they serve is deployed, and the game
|
||||
never depends on them. Their code stays out of `_site/` (`src/agent/` is development-only, see
|
||||
`docs/adr/0004-dev-only-code.md`).
|
||||
- **The container image is a tool too.** `docker/` packages those tools; `docker.yml` publishes it to GHCR for releases
|
||||
(version tags only, no `latest`) and never to Pages. Someone may run its development server where they like; that is
|
||||
not a host of the game, and the game never depends on it.
|
||||
|
||||
## How it deploys
|
||||
|
||||
|
|
@ -40,6 +47,17 @@ publishes the GitHub release and starts `release.yml`: test, `REQUIRE_NOTES=1 np
|
|||
`pages: write`. Pushes to `main` and pull requests build but never deploy. The `release` skill has the
|
||||
steps.
|
||||
|
||||
**The one exception: the weekly puzzle.** Every Sunday at 03:37 UTC `weekly-puzzle.yml` commits the new
|
||||
`site/puzzles/weekly/<key>.json` to `main` (data only, no version bump) and starts `release.yml` for the **live
|
||||
release tag** with `weekly=true`. That run rebuilds exactly the live release, with every weekly file from `main`
|
||||
added, checks them with `scripts/weekly-puzzle.js --check`, and deploys it in the same `pages` concurrency group.
|
||||
Players get no update banner (the version does not change). Every release build also copies all weekly files from
|
||||
`main`, so a release never drops a published week, and regenerates (in the build, deterministically) any week
|
||||
not over yet that the release's prices no longer fit. Weekly files are plain JSON the game fetches only when the
|
||||
Puzzles list opens and never trusts; the service worker serves them network-first. The weekly scenario rides along in
|
||||
the same run: `scripts/weekly-scenario.js` writes `site/scenarios/weekly/<key>.json` (fetched when the Scenarios list
|
||||
opens), committed and deployed with the puzzle, never by a second workflow. See `docs/ARCHITECTURE.md`.
|
||||
|
||||
## Before you hand back a change that touches the build, deploy or loading
|
||||
|
||||
```bash
|
||||
|
|
|
|||
|
|
@ -5,13 +5,34 @@ description: Cut and ship a Series of Tubes release (patch or minor) from main v
|
|||
|
||||
# Releasing Series of Tubes
|
||||
|
||||
Bumping `version` in `package.json` on `main` is the release button. The
|
||||
`auto-release.yml` workflow tests, tags `v<version>`, publishes a GitHub release with
|
||||
Bumping `version` in `package.json` on `main` is the release button. CI tests the push
|
||||
as usual; when it passes, `auto-release.yml` (which runs after every CI on `main`) sees
|
||||
the new version, tags `v<version>` on the commit CI tested, publishes a GitHub release with
|
||||
that version's CHANGELOG section as notes, and dispatches `release.yml`, which builds
|
||||
`_site/` (`npm run build`: the page assembled from `src/` plus `site/`) and deploys it
|
||||
to GitHub Pages (https://seriesoftub.es). GitHub Pages is the only host, ever: see the
|
||||
`github-pages` skill.
|
||||
|
||||
## Weekly puzzles are not releases
|
||||
|
||||
`weekly-puzzle.yml` publishes a new puzzle every Sunday morning without a release: it commits the JSON under
|
||||
`site/puzzles/weekly/` to `main` and redeploys the live tag through `release.yml` (`weekly=true`). Never bump the
|
||||
version for a weekly puzzle. To publish or fix one by hand: `node scripts/weekly-puzzle.js --key 2026-W45 --force`,
|
||||
`node scripts/weekly-puzzle.js --check`, commit to `main`, then run the "Weekly puzzle" workflow (or
|
||||
`gh workflow run release.yml --ref <live tag> -f tag=<live tag> -f weekly=true`). A release includes every weekly
|
||||
file on `main` when it builds.
|
||||
|
||||
The weekly scenario (`site/scenarios/weekly/`, `scripts/weekly-scenario.js`) ships in the same run and the same way:
|
||||
`--key`, `--force` and `--check` work alike. Its `--check` replays each week not over yet with the reference plan in
|
||||
the file; a new par is just written, a week the reference no longer wins is regenerated with `rev` + 1.
|
||||
|
||||
**Prices change, weeks follow.** `--check` re-solves every week not over yet with the game it runs; a week whose
|
||||
budget no longer verifies is regenerated deterministically (the same puzzle with a new budget if that works, else a
|
||||
fresh one for the same key) with `rev` + 1, which resets players' stars for that week only. Past weeks are left alone
|
||||
unless the game rejects them. `release.yml` runs it before the tests on every deploy and fails only if a week cannot be
|
||||
regenerated. A change to prices, cables or cities fails `npm test` until you run `node scripts/weekly-puzzle.js --check`
|
||||
and commit the regenerated files with it (and `node scripts/weekly-scenario.js --check` for the scenarios).
|
||||
|
||||
## Only release when Frederic says so
|
||||
|
||||
Never bump the version on your own. Finished work is committed and pushed with its
|
||||
|
|
@ -45,24 +66,23 @@ gh api repos/fjaeckel/seriesoftubes/releases/latest --jq '.tag_name+" "+.publish
|
|||
|
||||
## Steps
|
||||
|
||||
1. Make sure `main` is green: `npm test` and `node scripts/i18n-check.js`
|
||||
("0 missing, 0 unused, 0 broken").
|
||||
1. Don't run the test suite, the game or benchmarks before a release: CI tests the
|
||||
version bump (a red CI releases nothing), and the Performance workflow benchmarks it. Just
|
||||
check that the latest CI run on `main` is green (`gh run list --repo fjaeckel/seriesoftubes --limit 4`).
|
||||
2. In `CHANGELOG.md`, move the bullets from `## [Unreleased]` into a new section
|
||||
right below it: `## [x.y.z] — YYYY-MM-DD` (em dash, today's date). Keep an empty
|
||||
`## [Unreleased]` heading above it. The build fails if the section has no bullets.
|
||||
3. Bump the version in **both** files:
|
||||
- `package.json` → `"version"`
|
||||
- `package-lock.json` → top-level `"version"` and `packages[""].version`
|
||||
4. `npm test` once more.
|
||||
Then compare performance with the previous release and mention anything notable to Frederic:
|
||||
`npm run perf -- --base-ref v<last>`.
|
||||
4. (Nothing to run here: the workflow tests the release before it tags it.)
|
||||
5. Commit on `main` as Frederic, with no attribution trailers:
|
||||
```bash
|
||||
git -c user.name="Frederic Jung" -c user.email="frederic@jc-ix.net" commit \
|
||||
--author="Frederic Jung <frederic@jc-ix.net>" -m "Short summary (x.y.z)"
|
||||
git push origin main
|
||||
```
|
||||
6. Watch the workflows until both finish:
|
||||
6. Watch the workflows until all three finish (CI, then Auto-release, then Release to GitHub Pages):
|
||||
```bash
|
||||
gh run list --repo fjaeckel/seriesoftubes --limit 4
|
||||
gh run watch <id> --repo fjaeckel/seriesoftubes
|
||||
|
|
|
|||
|
|
@ -7,7 +7,8 @@ description: Write deterministic jsdom tests for Series of Tubes features and fi
|
|||
|
||||
Tests use `node:test` and `tests/harness.js`, which assembles the game page from `src/`
|
||||
(once per test file) and loads it in jsdom with the animation loop off, a seeded `Math.random` and a recording fake canvas.
|
||||
Code runs inside the page through `ev()`.
|
||||
Code runs inside the page through `ev()`. `load()` is the page players get; tests of the agent facade
|
||||
(`src/agent/`, `window.TUBES`) ask for the development page with `load({ agent: true })`.
|
||||
|
||||
## Pattern
|
||||
|
||||
|
|
@ -44,12 +45,27 @@ pull requests collide. Run one file with `npm test -- tests/route-servers.test.j
|
|||
or set state directly (`S.day=…`, `S.ev.x=…`).
|
||||
- **Force a specific random failure or event** by patching the picker:
|
||||
```js
|
||||
ev("eval('('+fireFailure.toString().replace('const e=pick(opts);',\"const e='crash';\")+')')()");
|
||||
ev("runNow(eval('('+failureRun.toString().replace('if(only)type=only;',\"type='crash';\")+')')())");
|
||||
```
|
||||
Check the current source for the exact `pick` line first (`grep -rn "function fireFailure" src/game`); it may differ.
|
||||
`failureRun()` is a generator (its yield is the routing): play it with `runNow()`. Check the current source for the
|
||||
exact line first (`grep -rn "function\* failureRun" src/game`); it may differ. Or simply `fireFailure('crash')`.
|
||||
- **Drive the game through `ACT`** like a player would, then `compute()` or `dayTick()`.
|
||||
- **Saves:** for persistence changes, round-trip `JSON.stringify(S)` through
|
||||
`parseSave()`/`migrate()`, and test that an *old* save without the new field still loads.
|
||||
- **UI:** render with `renderAll()` and query `dom.window.document`; check phone
|
||||
layouts by setting `window.innerWidth = 390` before rendering.
|
||||
- Run `npm test`; the whole suite must pass, not just the new test.
|
||||
|
||||
## Servers, sockets and anything async
|
||||
|
||||
CI runs four parts at once, each with its files in parallel, so a test can wait seconds for things that take
|
||||
milliseconds on your machine. Never sleep a fixed time and then assert: wait for the state with `tests/net.js`.
|
||||
|
||||
- `until(() => condition)` resolves true as soon as it holds (false after 20 s); assert on its result.
|
||||
- `freePort()` asks the OS for a free port; never a fixed or random one.
|
||||
- `kill(child)` stops a spawned server and resolves once it is gone.
|
||||
- Listen and connect on `127.0.0.1`, not `localhost` (it can resolve to `::1` only on a CI runner).
|
||||
- For HTTP to a test server, pass `agent: false`: a kept-alive socket can be reset by the server's idle timer.
|
||||
- A fixed wait is fine only to prove that something does *not* happen.
|
||||
|
||||
Hunt a suspected flake before pushing: `npm test -- --stress 8 tests/x.test.js` runs 8 copies at once, busier than CI.
|
||||
|
|
|
|||
10
.dockerignore
Normal file
10
.dockerignore
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
# The image takes only what docker/Dockerfile copies; everything else (git history, tests, docs, local saves,
|
||||
# node_modules, _site) stays out of the build context.
|
||||
*
|
||||
!package.json
|
||||
!package-lock.json
|
||||
!src/
|
||||
!site/
|
||||
!scripts/
|
||||
!tests/harness.js
|
||||
!docker/docker-entrypoint.sh
|
||||
39
.github/dependabot.yml
vendored
Normal file
39
.github/dependabot.yml
vendored
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
# Keeps what the workflows and the container image pin up to date: every GitHub Action is pinned to a commit SHA
|
||||
# (Dependabot moves the SHA and its version comment together), the image's Node base to a digest, and the npm tools
|
||||
# to the lockfile. Updates come as pull requests, one group per ecosystem, once a week.
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
groups:
|
||||
actions:
|
||||
patterns: ["*"]
|
||||
commit-message:
|
||||
prefix: "CI"
|
||||
|
||||
- package-ecosystem: docker
|
||||
directory: /docker
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
# The image runs the Node major CI tests on (ci.yml); a new major comes with CI, by hand.
|
||||
ignore:
|
||||
- dependency-name: node
|
||||
update-types: ["version-update:semver-major"]
|
||||
commit-message:
|
||||
prefix: "Container"
|
||||
|
||||
- package-ecosystem: npm
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
day: monday
|
||||
groups:
|
||||
tools:
|
||||
patterns: ["*"]
|
||||
update-types: [minor, patch]
|
||||
commit-message:
|
||||
prefix: "Tools"
|
||||
78
.github/workflows/auto-release.yml
vendored
78
.github/workflows/auto-release.yml
vendored
|
|
@ -5,10 +5,15 @@ name: Auto-release
|
|||
# as notes, and starts the deploy. Releases created with the workflow token do
|
||||
# not fire the "released" event, so the deploy is started explicitly, from the
|
||||
# tag, which keeps the github-pages environment's v* tag rule happy.
|
||||
#
|
||||
# It runs when CI finishes on main, so a release never repeats the push's tests:
|
||||
# CI green on the commit that bumped the version is the go. A red CI releases
|
||||
# nothing. Started by hand, it has no CI result to go by, so it tests first.
|
||||
on:
|
||||
push:
|
||||
workflow_run:
|
||||
workflows: [CI]
|
||||
types: [completed]
|
||||
branches: [main]
|
||||
paths: [package.json]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
|
|
@ -20,18 +25,26 @@ concurrency:
|
|||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
check:
|
||||
# After CI: only a green run of a push to main (not a PR's run, not a release's own call).
|
||||
if: >-
|
||||
github.event_name == 'workflow_dispatch' ||
|
||||
(github.event.workflow_run.conclusion == 'success' && github.event.workflow_run.event == 'push')
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
outputs:
|
||||
skip: ${{ steps.v.outputs.skip }}
|
||||
ver: ${{ steps.v.outputs.ver }}
|
||||
tag: ${{ steps.v.outputs.tag }}
|
||||
pre: ${{ steps.v.outputs.pre }}
|
||||
# The commit CI tested (main may have moved on since); by hand, main as it is now.
|
||||
sha: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-node@v7
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
||||
- name: Work out the version and whether it is new
|
||||
id: v
|
||||
|
|
@ -57,19 +70,48 @@ jobs:
|
|||
case "$ver" in *-*) echo "pre=true" >> "$GITHUB_OUTPUT";; *) echo "pre=false" >> "$GITHUB_OUTPUT";; esac
|
||||
echo "skip=false" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Test before releasing
|
||||
if: steps.v.outputs.skip == 'false'
|
||||
run: npm ci && npm test
|
||||
# Only when started by hand: after a push, CI has already tested this commit. By hand the commit is main as it is
|
||||
# (github.sha, what check.outputs.sha is then), named directly so CI never checks out a ref a workflow_run handed over.
|
||||
tests:
|
||||
needs: check
|
||||
if: needs.check.outputs.skip == 'false' && github.event_name == 'workflow_dispatch'
|
||||
uses: ./.github/workflows/ci.yml
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
|
||||
release:
|
||||
needs: [check, tests]
|
||||
if: >-
|
||||
always() && needs.check.result == 'success' && needs.check.outputs.skip == 'false' &&
|
||||
(needs.tests.result == 'success' || needs.tests.result == 'skipped')
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ needs.check.outputs.tag }}
|
||||
VER: ${{ needs.check.outputs.ver }}
|
||||
PRE: ${{ needs.check.outputs.pre }}
|
||||
SHA: ${{ needs.check.outputs.sha }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ needs.check.outputs.sha }}
|
||||
|
||||
- name: Publish the release
|
||||
if: steps.v.outputs.skip == 'false'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
pre=(); [ "${{ steps.v.outputs.pre }}" = "true" ] && pre=(--prerelease)
|
||||
gh release create "${{ steps.v.outputs.tag }}" --repo "$GITHUB_REPOSITORY" \
|
||||
--target "$GITHUB_SHA" --title "${{ steps.v.outputs.ver }}" --notes-file notes.md "${pre[@]}"
|
||||
awk -v v="$VER" 'index($0,"## ["v"]")==1{f=1;next} /^## \[/{f=0} f' CHANGELOG.md | sed -e '/./,$!d' > notes.md
|
||||
pre=(); [ "$PRE" = "true" ] && pre=(--prerelease)
|
||||
gh release create "$TAG" --repo "$GITHUB_REPOSITORY" \
|
||||
--target "$SHA" --title "$VER" --notes-file notes.md "${pre[@]}"
|
||||
|
||||
- name: Deploy it
|
||||
# Pre-releases are for testing and never go live.
|
||||
if: steps.v.outputs.skip == 'false' && steps.v.outputs.pre == 'false'
|
||||
run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "${{ steps.v.outputs.tag }}" -f tag="${{ steps.v.outputs.tag }}"
|
||||
# Pre-releases are for testing and never go live. CI (or the tests above) already passed on this commit,
|
||||
# so the deploy does not test it again (tested=true).
|
||||
if: env.PRE == 'false'
|
||||
run: gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG" -f tested=true
|
||||
|
||||
- name: Publish the Docker image
|
||||
# Same pattern as the deploy above: the image is built and pushed from the
|
||||
# release tag by docker.yml. Pre-releases get one too: an image tag is
|
||||
# pulled on purpose, so a test image costs nothing.
|
||||
run: gh workflow run docker.yml --repo "$GITHUB_REPOSITORY" --ref "$TAG" -f tag="$TAG"
|
||||
|
|
|
|||
119
.github/workflows/ci.yml
vendored
119
.github/workflows/ci.yml
vendored
|
|
@ -1,35 +1,142 @@
|
|||
name: CI
|
||||
|
||||
# Every push and PR, and the releases too (auto-release.yml and release.yml call this workflow), so the tests run
|
||||
# one way, split over several runners, everywhere.
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
workflow_call:
|
||||
inputs:
|
||||
ref:
|
||||
description: The commit or tag to test (a release tag); the caller's commit when empty
|
||||
type: string
|
||||
default: ''
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
# A newer push to the same pull request makes the older run pointless: cancel it instead of queueing behind it.
|
||||
# Runs on main always finish. A release's call gets a group of its own, so it never waits behind main's push run.
|
||||
concurrency:
|
||||
group: ci-${{ github.event_name == 'pull_request' && github.ref || github.run_id }}${{ inputs.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
env:
|
||||
# Runners for the tests. Standard GitHub-hosted runners (4 cores each) are the only free ones for a public repo,
|
||||
# and a run may use up to 20 at once, so more parts is how the tests get faster. Each part costs ~30 s of setup.
|
||||
PARTS: 6
|
||||
|
||||
jobs:
|
||||
test:
|
||||
# Splits the test files into parts of about equal time, once, so every part works from the same plan. The times
|
||||
# come from the last run on main (the cache, see "timings" below), else from the committed tests/durations.json.
|
||||
plan:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
parts: ${{ steps.plan.outputs.parts }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.ref }}
|
||||
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: tests/durations.json
|
||||
key: test-durations-${{ github.run_id }}
|
||||
restore-keys: test-durations-
|
||||
- id: plan
|
||||
run: echo "parts=$(node scripts/test.js --plan "$PARTS")" >> "$GITHUB_OUTPUT"
|
||||
|
||||
part:
|
||||
name: part ${{ strategy.job-index }}
|
||||
needs: plan
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
files: ${{ fromJSON(needs.plan.outputs.parts) }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.ref }}
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Tests
|
||||
env:
|
||||
FILES: ${{ matrix.files }}
|
||||
# Word splitting on purpose: FILES is a space-separated list of tests/*.test.js paths.
|
||||
run: npm test -- --timings "$RUNNER_TEMP/timings.json" $FILES
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: always()
|
||||
with:
|
||||
name: timings-${{ strategy.job-index }}
|
||||
path: ${{ runner.temp }}/timings.json
|
||||
retention-days: 1
|
||||
if-no-files-found: ignore
|
||||
|
||||
build:
|
||||
name: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.ref }}
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
- name: Build (not deployed — only releases deploy)
|
||||
run: npm run build
|
||||
|
||||
translations:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.ref }}
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- name: Translation coverage
|
||||
run: node scripts/i18n-check.js --summary "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# The one check to look at: green only when the plan, every part, the build and the translations are.
|
||||
test:
|
||||
needs: [plan, part, build, translations]
|
||||
if: always()
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Everything passed
|
||||
run: |
|
||||
echo "plan: ${{ needs.plan.result }}, parts: ${{ needs.part.result }}, build: ${{ needs.build.result }}, translations: ${{ needs.translations.result }}"
|
||||
test "${{ needs.plan.result }}" = success && test "${{ needs.part.result }}" = success
|
||||
test "${{ needs.build.result }}" = success && test "${{ needs.translations.result }}" = success
|
||||
|
||||
# After a run on main: each file's time from this run goes into the cache, so the next run (main or a PR) splits
|
||||
# its parts by today's tests. Nobody has to remember to refresh tests/durations.json.
|
||||
timings:
|
||||
needs: part
|
||||
if: always() && github.event_name == 'push' && github.ref == 'refs/heads/main' && needs.part.result != 'skipped'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: tests/durations.json
|
||||
key: test-durations-${{ github.run_id }}
|
||||
restore-keys: test-durations-
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
pattern: timings-*
|
||||
path: ${{ runner.temp }}/timings
|
||||
- run: node scripts/test-timings.js --merge "$RUNNER_TEMP/timings"
|
||||
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
|
||||
with:
|
||||
path: tests/durations.json
|
||||
key: test-durations-${{ github.run_id }}
|
||||
|
|
|
|||
4
.github/workflows/claude.yml
vendored
4
.github/workflows/claude.yml
vendored
|
|
@ -27,9 +27,9 @@ jobs:
|
|||
id-token: write
|
||||
actions: read
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
fetch-depth: 1
|
||||
- uses: anthropics/claude-code-action@v1
|
||||
- uses: anthropics/claude-code-action@61a9c274fa7110a66dfafc1bbbced03833eb25fe # v1.0.269
|
||||
with:
|
||||
claude_code_oauth_token: ${{ secrets.CLAUDE_CODE_OAUTH_TOKEN }}
|
||||
|
|
|
|||
187
.github/workflows/docker.yml
vendored
Normal file
187
.github/workflows/docker.yml
vendored
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
name: Container image
|
||||
|
||||
# Publishes ghcr.io/<owner>/<repo>:<version> for releases, and nothing else: auto-release.yml dispatches this workflow
|
||||
# with the new tag (pre-releases too). There is no :latest and no image per commit. Pushes and pull requests that change
|
||||
# what goes into the image only build it and try both modes; they never publish. The image packages the MCP server and
|
||||
# the development server; the game itself is hosted on GitHub Pages only (docs/adr/0001-github-pages-only.md).
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag:
|
||||
description: Release tag to build and publish (e.g. v2.10.1)
|
||||
required: true
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- docker/**
|
||||
- .dockerignore
|
||||
- package.json
|
||||
- package-lock.json
|
||||
- scripts/**
|
||||
- tests/harness.js
|
||||
- .github/workflows/docker.yml
|
||||
pull_request:
|
||||
paths:
|
||||
- docker/**
|
||||
- .dockerignore
|
||||
- package.json
|
||||
- package-lock.json
|
||||
- scripts/**
|
||||
- tests/harness.js
|
||||
- .github/workflows/docker.yml
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: docker-${{ github.event_name }}-${{ inputs.tag || github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
|
||||
|
||||
jobs:
|
||||
# A push that bumps the version is a release on its way: once CI passes, auto-release.yml starts this workflow for
|
||||
# the tag, which tests the same code before it publishes. Testing the push too would be the same run twice.
|
||||
gate:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
run: ${{ steps.g.outputs.run }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.tag || '' }}
|
||||
persist-credentials: false
|
||||
- id: g
|
||||
run: |
|
||||
tag="v$(jq -r .version package.json)"
|
||||
if [ "$GITHUB_EVENT_NAME" = push ] && ! git ls-remote --exit-code --tags origin "refs/tags/$tag" >/dev/null; then
|
||||
echo "$tag is not tagged yet: the release will test this commit when it publishes."
|
||||
echo "run=false" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "run=true" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
test:
|
||||
needs: gate
|
||||
if: needs.gate.outputs.run == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.tag || '' }}
|
||||
persist-credentials: false
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- name: Build for this runner
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: .
|
||||
file: docker/Dockerfile
|
||||
platforms: linux/amd64
|
||||
load: true
|
||||
push: false
|
||||
tags: sot:test
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
|
||||
- name: Try both modes
|
||||
run: |
|
||||
set -euo pipefail
|
||||
init='{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"ci","version":"1"}}}'
|
||||
mcp() { curl -sS -o /tmp/out -w '%{http_code}' -X POST http://127.0.0.1:7777/mcp \
|
||||
-H 'content-type: application/json' -H 'accept: application/json, text/event-stream' "$@" -d "$init"; }
|
||||
until_up() { for i in $(seq 1 60); do curl -s -o /dev/null "$1" && return 0; sleep 1; done; docker logs "$2"; exit 1; }
|
||||
|
||||
# Headless, with a token: refused without it, answered with it.
|
||||
docker run -d --name sot-h -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=ci-token sot:test
|
||||
until_up http://127.0.0.1:7777/ sot-h
|
||||
test "$(mcp)" = 401
|
||||
test "$(mcp -H 'authorization: Bearer ci-token')" = 200
|
||||
grep -q serverInfo /tmp/out
|
||||
docker rm -f sot-h
|
||||
|
||||
# No token given: the container makes one, says so, and wants it.
|
||||
docker run -d --name sot-t -p 127.0.0.1:7777:7777 -e MCP_MODE=headless sot:test
|
||||
until_up http://127.0.0.1:7777/ sot-t
|
||||
test "$(mcp)" = 401
|
||||
tok=$(docker logs sot-t 2>&1 | sed -n "s/.*this run's token is //p" | head -1)
|
||||
test -n "$tok"
|
||||
test "$(mcp -H "authorization: Bearer $tok")" = 200
|
||||
docker rm -f sot-t
|
||||
|
||||
# Browser mode: the development page and the MCP server.
|
||||
docker run -d --name sot-b -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 -e SOT_MCP_TOKEN=ci-token sot:test
|
||||
until_up http://127.0.0.1:8080/ sot-b
|
||||
test "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8080/)" = 200
|
||||
until_up http://127.0.0.1:7777/ sot-b
|
||||
test "$(mcp -H 'authorization: Bearer ci-token')" = 200
|
||||
docker rm -f sot-b
|
||||
|
||||
# The server runs as node, not root.
|
||||
test "$(docker run --rm --entrypoint id sot:test -u)" != 0
|
||||
|
||||
publish:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 45
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
steps:
|
||||
- name: Check the tag
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
[[ "$TAG" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "::error::Not a release tag: $TAG"; exit 1; }
|
||||
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ inputs.tag }}
|
||||
persist-credentials: false
|
||||
|
||||
- name: Work out the image name and version
|
||||
id: meta
|
||||
env:
|
||||
TAG: ${{ inputs.tag }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
want="v$(jq -r .version package.json)"
|
||||
if [ "$TAG" != "$want" ]; then echo "::error::Release tag $TAG does not match package.json ($want)"; exit 1; fi
|
||||
# Named after this repository (ghcr.io/<owner>/<repo>, lowercased), so forks publish their own.
|
||||
echo "image=ghcr.io/${GITHUB_REPOSITORY,,}" >> "$GITHUB_OUTPUT"
|
||||
echo "version=${TAG#v}" >> "$GITHUB_OUTPUT"
|
||||
echo "revision=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
|
||||
echo "created=$(git log -1 --format=%cI)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Build and push the release's version
|
||||
uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0
|
||||
with:
|
||||
context: .
|
||||
file: docker/Dockerfile
|
||||
platforms: linux/amd64,linux/arm64
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.image }}:${{ steps.meta.outputs.version }}
|
||||
labels: |
|
||||
org.opencontainers.image.title=Series of Tubes MCP server
|
||||
org.opencontainers.image.description=The Series of Tubes MCP server and development server, so an AI client can play the game.
|
||||
org.opencontainers.image.source=${{ github.server_url }}/${{ github.repository }}
|
||||
org.opencontainers.image.documentation=${{ github.server_url }}/${{ github.repository }}/blob/${{ inputs.tag }}/docs/MCP.md
|
||||
org.opencontainers.image.version=${{ steps.meta.outputs.version }}
|
||||
org.opencontainers.image.revision=${{ steps.meta.outputs.revision }}
|
||||
org.opencontainers.image.created=${{ steps.meta.outputs.created }}
|
||||
org.opencontainers.image.licenses=MIT
|
||||
provenance: mode=max
|
||||
sbom: true
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
5
.github/workflows/perf-comment.yml
vendored
5
.github/workflows/perf-comment.yml
vendored
|
|
@ -17,9 +17,11 @@ jobs:
|
|||
if: github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
|
||||
with:
|
||||
name: perf
|
||||
# Outside the workspace: the files come from a PR's run and are only ever read as text.
|
||||
path: ${{ runner.temp }}/perf
|
||||
run-id: ${{ github.event.workflow_run.id }}
|
||||
github-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Post or update the comment
|
||||
|
|
@ -28,6 +30,7 @@ jobs:
|
|||
REPO: ${{ github.repository }}
|
||||
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
|
||||
run: |
|
||||
cd "$RUNNER_TEMP/perf"
|
||||
pr=$(tr -cd '0-9' < pr-number.txt)
|
||||
[ -n "$pr" ] || { echo "no PR number"; exit 0; }
|
||||
# Trust the number only if that PR's head is the commit that was benchmarked.
|
||||
|
|
|
|||
6
.github/workflows/perf.yml
vendored
6
.github/workflows/perf.yml
vendored
|
|
@ -22,8 +22,8 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
|
@ -48,7 +48,7 @@ jobs:
|
|||
env:
|
||||
PR: ${{ github.event.pull_request.number }}
|
||||
run: echo "$PR" > pr-number.txt
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
if: github.event_name == 'pull_request'
|
||||
with:
|
||||
name: perf
|
||||
|
|
|
|||
74
.github/workflows/release.yml
vendored
74
.github/workflows/release.yml
vendored
|
|
@ -4,7 +4,8 @@ name: Release to GitHub Pages
|
|||
# Pushes to main run CI but never deploy. To ship: bump "version" in
|
||||
# package.json and date its CHANGELOG section; auto-release.yml then tags,
|
||||
# publishes the release and starts this workflow from the tag. Publishing a
|
||||
# release by hand works too.
|
||||
# release by hand works too. Every Sunday weekly-puzzle.yml redeploys the live
|
||||
# release from its tag with the new weekly puzzle added (input weekly).
|
||||
on:
|
||||
release:
|
||||
# "released" also fires when a pre-release is promoted to a full release.
|
||||
|
|
@ -18,6 +19,14 @@ on:
|
|||
description: Allow deploying a version older than what is live (rollback)
|
||||
type: boolean
|
||||
default: false
|
||||
weekly:
|
||||
description: Only the weekly puzzles changed (weekly-puzzle.yml); the release itself was tested when it shipped
|
||||
type: boolean
|
||||
default: false
|
||||
tested:
|
||||
description: The tag's tests already passed (auto-release.yml tests it before tagging)
|
||||
type: boolean
|
||||
default: false
|
||||
|
||||
# Least privilege: only the deploy job can write to Pages.
|
||||
permissions:
|
||||
|
|
@ -28,19 +37,28 @@ concurrency:
|
|||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
# The release's tests, split over several runners like every push (ci.yml). Skipped when auto-release.yml has just
|
||||
# run them on this tag, and for a weekly redeploy (the build step below tests the weekly files against the tag).
|
||||
tests:
|
||||
if: ${{ (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && !inputs.weekly && !inputs.tested }}
|
||||
uses: ./.github/workflows/ci.yml
|
||||
with:
|
||||
ref: ${{ github.event.release.tag_name || inputs.tag }}
|
||||
|
||||
build:
|
||||
needs: tests
|
||||
# Pre-releases are for testing and never go live.
|
||||
if: ${{ github.event_name == 'workflow_dispatch' || !github.event.release.prerelease }}
|
||||
if: ${{ always() && (github.event_name == 'workflow_dispatch' || !github.event.release.prerelease) && (needs.tests.result == 'success' || needs.tests.result == 'skipped') }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
TAG: ${{ github.event.release.tag_name || inputs.tag }}
|
||||
ALLOW_OLDER: ${{ inputs.allow_older || false }}
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ env.TAG }}
|
||||
- uses: actions/setup-node@v7
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
|
|
@ -63,16 +81,55 @@ jobs:
|
|||
if [ "$ALLOW_OLDER" != "true" ] && [ "$(printf '%s\n%s\n' "$live" "$new" | sort -V | tail -n1)" != "$new" ]; then
|
||||
echo "::error::$new is older than the live $live. Re-run with allow_older to roll back on purpose."; exit 1
|
||||
fi
|
||||
# Weekly puzzles are published on main between releases (weekly-puzzle.yml). Every deploy ships all of them,
|
||||
# so neither a release nor a weekly redeploy ever drops a week that is already out.
|
||||
- name: Weekly puzzles and scenarios from main
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git fetch --no-tags --depth=1 origin main
|
||||
for d in site/puzzles/weekly site/scenarios/weekly site/architect/weekly; do
|
||||
if git cat-file -e "FETCH_HEAD:$d" 2>/dev/null; then
|
||||
rm -rf "$d"
|
||||
git checkout FETCH_HEAD -- "$d"
|
||||
echo "$d: $(ls "$d" | grep -c '^[0-9].*\.json$')"
|
||||
fi
|
||||
done
|
||||
- run: npm ci
|
||||
- run: npm test
|
||||
# This release's prices may no longer fit a week already published: --check regenerates every week not over
|
||||
# yet whose budget no longer verifies (deterministically, so main's next weekly run commits the same files),
|
||||
# and fails the deploy only if that fails. Before the tests, which check the weeks too.
|
||||
- name: Fit the weekly puzzles to this release
|
||||
run: |
|
||||
set -euo pipefail
|
||||
# A release from before the weekly puzzles ships the files without reading them: nothing to check.
|
||||
if [ ! -f scripts/weekly-puzzle.js ]; then echo "This release does not read weekly puzzles yet."; exit 0; fi
|
||||
node scripts/weekly-puzzle.js --check
|
||||
if [ -f scripts/weekly-scenario.js ]; then node scripts/weekly-scenario.js --check; fi
|
||||
if [ -f scripts/weekly-architect.js ]; then node scripts/weekly-architect.js --check; fi
|
||||
# The weekly files come from main, not the tag. When they (after fitting) are the tag's own, CI already tested
|
||||
# them with it; otherwise (a newer week, a refitted one) they are tested against this release here.
|
||||
- name: Are the weekly files the tag's own?
|
||||
id: weekly
|
||||
run: |
|
||||
if [ -z "$(git status --porcelain -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly)" ]; then
|
||||
echo "Same weekly files as the tag: tested with it already."; echo "same=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
git status --short -- site/puzzles/weekly site/scenarios/weekly site/architect/weekly; echo "same=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
- name: Test the weekly puzzles against this release
|
||||
if: ${{ hashFiles('scripts/weekly-puzzle.js') != '' && (steps.weekly.outputs.same != 'true' || !(inputs.tested || needs.tests.result == 'success')) }}
|
||||
run: npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js $(ls tests/weekly-scenario.test.js tests/weekly-architect.test.js 2>/dev/null)
|
||||
- name: Build site
|
||||
run: VERSION="${TAG#v}" REQUIRE_NOTES=1 npm run build
|
||||
- uses: actions/upload-pages-artifact@v5
|
||||
- uses: actions/upload-pages-artifact@fc324d3547104276b827a68afc52ff2a11cc49c9 # v5.0.0
|
||||
with:
|
||||
path: ./_site
|
||||
|
||||
# A skipped job skips everything that needs it, even through build (which runs anyway): without always() here, a
|
||||
# release whose tests auto-release.yml already ran built and never deployed (v3.2.0).
|
||||
deploy:
|
||||
needs: build
|
||||
if: ${{ always() && needs.build.result == 'success' }}
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
pages: write
|
||||
|
|
@ -82,12 +139,11 @@ jobs:
|
|||
url: ${{ steps.deployment.outputs.page_url }}
|
||||
steps:
|
||||
- id: deployment
|
||||
uses: actions/deploy-pages@v5
|
||||
|
||||
# Tell IndexNow (Bing, Yandex, Seznam, …) about the new version, only after
|
||||
uses: actions/deploy-pages@368f82528645a54fb793d4d04e342629a3f51346 # v5.0.1
|
||||
# the site is live.
|
||||
indexnow:
|
||||
needs: deploy
|
||||
if: ${{ always() && needs.deploy.result == 'success' && !inputs.weekly }}
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
# IndexNow keys are public by design (also served at /<key>.txt).
|
||||
|
|
|
|||
88
.github/workflows/weekly-puzzle.yml
vendored
Normal file
88
.github/workflows/weekly-puzzle.yml
vendored
Normal file
|
|
@ -0,0 +1,88 @@
|
|||
name: Weekly puzzle
|
||||
|
||||
# Every Sunday morning: make this week's puzzle (scripts/weekly-puzzle.js), scenario (scripts/weekly-scenario.js) and
|
||||
# Architect run (scripts/weekly-architect.js),
|
||||
# commit them to main as a data-only change, and redeploy the live release with them, once. Weeks start Sunday
|
||||
# 06:00 Berlin time; 03:37 UTC is 04:37 in winter and 05:37 in summer, so the files are live before the week starts.
|
||||
#
|
||||
# No version bump, so no release: auto-release.yml only runs when package.json changes (and pushes made with
|
||||
# the workflow token start no workflows at all). The deploy itself is release.yml, still the only workflow
|
||||
# that can write to Pages, started from the live release's tag with weekly=true: it rebuilds exactly that
|
||||
# release with every weekly puzzle from main added, in the same "pages" concurrency group as any release.
|
||||
on:
|
||||
schedule:
|
||||
- cron: '37 3 * * 0'
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
key:
|
||||
description: Week to make, e.g. 2026-W45 (default the week starting this Sunday)
|
||||
required: false
|
||||
deploy:
|
||||
description: Redeploy the live release with it
|
||||
type: boolean
|
||||
default: true
|
||||
|
||||
permissions:
|
||||
contents: write # commit the puzzle to main
|
||||
actions: write # start release.yml
|
||||
|
||||
concurrency:
|
||||
group: weekly-puzzle
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
puzzle:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
KEY: ${{ inputs.key }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: main
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
# Weeks already out that main's prices no longer fit are regenerated first, so the new week's history is current.
|
||||
- name: Fit the published weeks to main
|
||||
run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check
|
||||
- name: Make the puzzle and the scenario
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [ -n "$KEY" ]; then
|
||||
[[ "$KEY" =~ ^[0-9]{4}-W[0-9]{2}$ ]] || { echo "::error::$KEY is not a week key"; exit 1; }
|
||||
node scripts/weekly-puzzle.js --key "$KEY"
|
||||
node scripts/weekly-scenario.js --key "$KEY"
|
||||
node scripts/weekly-architect.js --key "$KEY"
|
||||
else
|
||||
node scripts/weekly-puzzle.js
|
||||
node scripts/weekly-scenario.js
|
||||
node scripts/weekly-architect.js
|
||||
fi
|
||||
- name: Check every weekly puzzle
|
||||
run: node scripts/weekly-puzzle.js --check && node scripts/weekly-scenario.js --check && node scripts/weekly-architect.js --check && npm test -- tests/weekly-puzzle.test.js tests/puzzles.test.js tests/weekly-scenario.test.js tests/weekly-architect.test.js
|
||||
- name: Commit it to main
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git add site/puzzles/weekly site/scenarios/weekly site/architect/weekly
|
||||
# Data only: anything else changed means something is wrong.
|
||||
if git status --porcelain | grep -v -e ' site/puzzles/weekly/' -e ' site/scenarios/weekly/' -e ' site/architect/weekly/' | grep -q .; then git status --porcelain; echo "::error::unexpected changes"; exit 1; fi
|
||||
if git diff --cached --quiet; then echo "Nothing new to commit."; exit 0; fi
|
||||
git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \
|
||||
commit -m "Weekly puzzle and scenario $(git diff --cached --name-only | grep -o '[0-9]\{4\}-W[0-9]\{2\}' | sort -u | paste -sd ' ')"
|
||||
git push origin HEAD:main
|
||||
- name: Redeploy the live release with it
|
||||
if: github.event_name == 'schedule' || inputs.deploy
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tag=$(gh release list --repo "$GITHUB_REPOSITORY" --exclude-pre-releases --exclude-drafts --limit 1 --json tagName -q '.[0].tagName')
|
||||
[ -n "$tag" ] || { echo "::error::no release to redeploy"; exit 1; }
|
||||
# Releases from before the weekly puzzles cannot take them (and their game would not read them).
|
||||
if ! git fetch --no-tags --depth=1 origin "refs/tags/$tag" || ! git show FETCH_HEAD:.github/workflows/release.yml | grep -q '^ weekly:'; then
|
||||
echo "::notice::$tag predates weekly puzzles; the puzzle is on main and ships with the next release."; exit 0
|
||||
fi
|
||||
gh workflow run release.yml --repo "$GITHUB_REPOSITORY" --ref "$tag" -f tag="$tag" -f weekly=true
|
||||
echo "Redeploying $tag with the weekly puzzles."
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
|
|
@ -1,3 +1,4 @@
|
|||
node_modules/
|
||||
_site/
|
||||
.DS_Store
|
||||
mp-data/
|
||||
|
|
|
|||
363
CHANGELOG.md
363
CHANGELOG.md
|
|
@ -6,6 +6,367 @@ All notable changes to this project are documented here. The project follows
|
|||
|
||||
## [Unreleased]
|
||||
|
||||
- Investors on a revenue share now take their cut of your IPv4 lease income too, as they already did of fiber pairs you lease out (#150). Selling a block is still a one-off that is all yours, like the up-front price of a fiber pair, and the NOC dashboard's Investor revenue share row now includes the leases.
|
||||
- Island Wi-Fi: bring the internet to 18 groups of outer islands, over satellite capacity first and your own spur cable later (#83). Each group looks to an island city, like Vanua Levu to Suva or Abaco and Eleuthera to Nassau: open a POP there and its Customers tab lists them. Rent capacity at the city's teleport and about a third of the islanders sign up over GEO, three quarters over MEO and nine in ten over Starblink from a gateway there; from level 3 a spur cable from the city lets everyone sign up, with upkeep but no rent. Islanders pay island prices, their homes are IPv6-only from day one, and their traffic rides the city's routers and links. A spur can be cut and the repair ship takes weeks: a satellite circuit kept beside it carries the islands meanwhile. Investors on a revenue share take their cut of what the islands pay.
|
||||
- Rent low-orbit satellite capacity from Starblink from level 5: islands near your fiber get circuits at about 30 ms round trip (#83). Host a Starblink gateway at a teleport on your fiber, then rent 5 to 50 Gbps to small islands and remote towns within 1,200 km of it. Users hardly notice the lag, and selective networks peer over it as over a cable; next to a cable it waits on standby, and a GEO or MEO circuit to the same island waits on standby beside it. Every island behind a gateway leans on that POP's routers, fiber and transit, which its teleport section now shows, and a rare solar storm puts the circuits in safe mode for a day or two. Once your own constellation carries traffic, Starblink sells you nothing new.
|
||||
- A POP you mark as a micro POP, medium POP or regional hub now keeps that kind's routers when you also have a build standard (#315). Its router model and count come from its kind: "Bring everything up now" and your intern no longer swap its routers or add more to meet the build standard, while the standard's other targets still apply there. The POP's router section says so.
|
||||
- Send to another device now gives a multiplayer network its session link, on copies of the game you host yourself (#263). The link carries on with the network in the session on the other device, and pasting it under From another device opens it there too; the save file stays a copy that plays on alone.
|
||||
- Buy it and sign no longer spends money on an offer your IPv4 space cannot take (#150). The button only shows once the deal's address block fits.
|
||||
- Linking to an island or remote town where no subsea cable lands, like Iqaluit or Adamstown, now says that a satellite can get there too. The window has a button to the order sheet from your teleports that reach it, up to four of them; without one, it says where a teleport would have to go (#83).
|
||||
- IPv4 notices in the NOC's notifications now have an Open button to the bank's Address space (#150). Notices like "Your IPv4 is full" already had that button when they popped up; now they keep it.
|
||||
- Red warning text and the capacity market's Hot and Cool tags now read well in dark mode (#80). The red is a lighter one on the dark panels, and the tags take the night colours instead of staying bright pastel chips.
|
||||
- The build standard can now take every broadband city IPv6-only while IPv4 is scarce (#150). Its new target, Broadband: IPv6-only, swaps the home routers of every city still on dual stack for 464XLAT ones, the cities with the most dual-stack homes first. "Bring everything up now" and your intern's Keep to the build standard order start a city's swap only with all of it to spare, and the intern counts it against the order's monthly budget. What the swaps under way still owe is set aside: the button's other jobs and every one of your intern's standing orders leave it alone, above the cash floor.
|
||||
- "Bring everything up now" in the build standard no longer takes a fiber dark for a day while a customer's alien or managed wave rides it. Such a fiber keeps its line system and the sheet says why; the upgrade button on the fiber itself still does it when you choose. Your intern waits for those fibers too, but no longer skips fibers that only carry leased pairs or IRUs, which a line system swap never touches.
|
||||
- Broadband cities can now go IPv6-only with 464XLAT, a second way to save IPv4 next to CGNAT. Start it from a city's Home broadband, which also says what it does to your monthly IPv4 bill: its home routers are swapped over a month or more, paid as each one goes in (new homes there get one too, at the same price), and the homes then need no IPv4 address of their own, only a share of a NAT64 pool at up to 256 homes per address, with fewer refunds than CGNAT at the same ratio. The bank's Address space section shows your homes as public, behind CGNAT and IPv6-only, with the NAT64 ratio next to the CGNAT one, and says which of the two to stretch when space runs out.
|
||||
- CGNAT gets a little cheaper every year as the world moves to IPv6. About two points less of your homes' traffic needs IPv4 each year, so the CGNAT and NAT64 boxes carry less of it.
|
||||
- The router model and the line system your intern standardizes on are now picked in one place, the build standard. Keep routers ahead and Upgrade optical transport take them from there and say so, with a button to the sheet. With a model or line system in the standard, both orders bring everything up to it and stop there (Upgrade optical transport on every fiber, even at POPs that Keep to the build standard skips); "Keep as is" leaves them to the next one up when busy. A model or line system you had picked in an order that was running moves into your standard, so new POPs get that model too.
|
||||
- Your intern no longer takes a fiber dark for the build standard just because it looks quiet. Like the optical upgrade order, it first checks that every gigabit, circuit and express gets around the fiber for the day. The two orders share one line system swap a night (two for Kevin), never work on the same fiber in one shift, and a wave the standard just upgraded is no longer handed back the same day.
|
||||
- Copies of the game you host yourself can now have multiplayer, with friends building their networks next to yours in the same world. They join your session with a six-character code, and the session has a leaderboard, a feed with chat, saves kept on your server and a link to carry a network to another device. It needs the small session server that comes with the source code, so the game at seriesoftub.es stays single-player.
|
||||
- Dark mode: pick Light, Dark or Auto (follows your device) under Settings › Theme. The panels, the NOC dashboard and the map all go dark, with a night-time sea and land, and the setting is kept on your device (#80).
|
||||
- Express lightpaths: light a wave straight through the cities between your own dark fibers, without touching the routers there. Wherever two or more of your ROADM fibers on land meet, a fiber's panel lists where an express can go and the link window gets an Express tab; it uses ports only at its two ends, saves a hop of latency and takes one channel slot on every fiber it rides, and the light has to reach all the way between regen sites. A cut or a line system swap on any of those fibers darkens it, and a fiber can only be given up once no express rides it. (#58)
|
||||
- Teleports bring satellites to small islands and remote towns, long before you have a cable there or a rocket company (#83). Build one at a POP from level 2 and rent GEO circuits (about 600 ms round trip, and users notice) or, with tracking antennas from level 3, MEO circuits (about 130 ms) to any island or town its satellites see. Next to an island's only cable a circuit waits on standby (whether the cable or the circuit came first) and carries the island when the cable is cut, and a city with no cable at all gets a POP and a circuit in one order.
|
||||
- Set a build standard for your whole network: what every POP, connection and fiber should have, all in one sheet. It covers routers, a second building and a generator at every POP, LAGs, exchange ports and PNIs, line systems, optics and wave sizes. New POPs get the POP part the day they open, the sheet shows what is below the standard and what fixing it costs, one tap brings everything up, and the new "Keep to the build standard" order has your intern do it a few jobs a day with money to spare. Find it in the menu, the Standing orders sheet and every POP's router section.
|
||||
- IPv4 is scarce now: business customers need public address blocks, and the homes that do not fit share addresses behind CGNAT. A new network starts with a /21 from its registry, enough for its first months; buy, lease or sell blocks from /24 to /16 on the transfer market in the bank's new Address space section, or lease spare ones out for a monthly income. An offer you have no addresses for says so and waits, a customer that wants to grow at renewal stays at its size until you have the addresses, CGNAT costs a little and annoys some gamers, and you pick how many homes share an address. IPv6 stays free for everyone. This is part of On-call and BGP at 3 a.m.; the gentler rules, Sandbox, puzzles and scenarios keep IPv4 plentiful, and saved games get the addresses they already use plus room to grow (#150).
|
||||
- Express lightpaths now pay their share when you add a regen site, and a dirty connector on a fiber dims the expresses riding it too (#58). A regen site added to a fiber that already carries expresses needs a regen card for each of their channels, just as for the fiber's own, and the price on the fiber's button includes them. A dirty connector dims every wave in that fiber, and the express's panel says which fiber it is; an MTU mismatch, microbursts or a marginal optic stay with that fiber's own routers and optics, which an express passes by.
|
||||
- Many selective networks now refuse to peer where a satellite circuit is your only way out (#83). On an island or in a remote town that only a satellite joins to the rest of your network, they would hand you traffic for your whole network to haul through orbit, so more of them turn down a GEO hop (about 600 ms there and back) than a MEO one (about 130 ms), and each says why on the exchange and PNI lists. Once a wave, fiber or cable to the island is lit they peer again. An exchange session you already had there pauses until then; a PNI you already have and the members of an exchange you run yourself keep peering.
|
||||
|
||||
## [3.5.0] — 2026-11-11
|
||||
|
||||
- Alien waves you list on a fiber yourself now stay listed. With the capacity market selling for you, the broker used to cut your listing down to what its settings allowed the next day, or take it off altogether when the route's demand was below your minimum. Your own listing now stays put, and the broker adds what its settings allow on top (#340).
|
||||
- The Connections list in the NOC dashboard no longer stays blank when you sort it by load or show only NNI ports while a fabric port runs at 400G. A 400G fabric port is the fastest there is, so the list now offers it one more LAG member instead of a faster port that does not exist. (#342)
|
||||
- You can now start a link by typing where it goes: open one of your POPs, go to Infra and tap Link to a city, then type a city, country or exchange and pick it. You get the same link window as dragging between the two on the map, which is much easier on a crowded phone screen (#343).
|
||||
- The Connections tab of the NOC dashboard can now shrink connections as well as grow them. Next to the upgrades, transit ports, PNIs and exchange ports get a downgrade to the next smaller port and a button to drop one LAG member, and a PNI that is still on order can be chased from the list, just like from the POP panel (#336).
|
||||
- Once you have made Tier 1, conferences stop sending notifications. No more 30-day reminders, reports from the hallway track or notes from your sales engineer about bookings; you can still register and sponsor from the Deals tab, and everything a conference does works as before (#101).
|
||||
|
||||
## [3.4.0] — 2026-11-10
|
||||
|
||||
- A PNI can now grow past eight ports: each router at the POP takes eight members of a PNI, up to 32, so a busier interconnect costs another router and its ports. Saves keep every LAG they have, and a router a PNI still needs stays until the PNI shrinks (#323).
|
||||
- Your traffic to home internet providers now starts where their customers live: a New York POP talks a lot to Comecast and little to Doitsche Telekomm, Frankfurt the other way round. Peering with a big eyeball network in the cities its users are in now takes that traffic off your backbone, while peering in only two cities means hauling it there from everywhere else (#48).
|
||||
- Giant AI circuits now come from campuses in more than 30 metros, from Oregon and Wyoming to Atlanta, Querétaro and Québec, and less often from cities already crowded with them. Ashburn stays a little busier than the rest, but no longer has to carry the whole late game with four other cities (#61).
|
||||
- RouteScript can spill early onto detours within a latency budget: `spill at 80% within 10 ms` keeps a hot link at 80% and moves the rest onto the fastest detour that adds at most 10 ms and is itself under 80%. Stack them (`spill at 90% within 20 ms`) to spill further as links get hotter (#136).
|
||||
- You can now send a network to another device straight from the game: open the menu, pick Send to another device, and send the save file with AirDrop, Quick Share, a chat with yourself or email, then open it there with Import a save. You can also copy a link that carries the whole network and paste it on the other device under From another device. Nothing is uploaded anywhere (#263).
|
||||
- From customer level 7, low-latency wholesale routes call: 1.6 or 3.2 Tbps between two of your cities with a strict latency limit, paying about three times what a hyperscaler pays per Gbps on the same route. Every day over the limit (after the first 15) you pay back a day's fee as an SLA credit and they lose patience twice as fast as a trading link over its limit, so keep a fast path and a fast backup. They never grow past 3.2 Tbps, so one contract cannot carry a whole level (#137).
|
||||
- From customer level 2, you can save up to three POP standards (micro POP, medium POP, regional hub), each a router model and a number of routers, and mark which POP is which. One button in a POP's Infra tab brings it up to its standard, and Utilities brings every POP of a kind up at once with the price shown first. A POP is never stepped down to a smaller model, and a busy POP with one router gets its second router before the swap, so the upgrade rolls instead of taking the POP down (#315).
|
||||
- Utilities can now install the redundancy kit at every POP still missing part of it in one go, at one price shown on the button, from customer level 2. With a NOC intern you can also put the kit in the intern's new-POP template from there (#317).
|
||||
- A customer asking for a backup generator, a second router or a second site at POPs you already have now shows what is missing and what it costs, with a button that buys exactly that and signs the deal. Nothing is bought unless you press it (#241).
|
||||
- The NOC intern's "Light more fiber" order can now leave new fiber dark, so a fiber handed over in the night no longer pulls in traffic before you are ready for it. Fiber you light yourself still gets more optics when it runs hot (#316).
|
||||
- The Transit and Peering tabs of a POP have a search box for a network's name or AS number and a "Connected only" switch, so you can find the one network you need in a long list, on phones too (#199).
|
||||
- Decommissioning one of several links between the same two cities keeps the link panel open on the next one, so you can hand back a row of waves without reopening it each time (#119).
|
||||
- A link that a closed border has taken down, like Doha to Dubai or Abu Dhabi while the neighbours have fallen out, now says so in its panel, with the days until it comes back, instead of showing nothing wrong. Leasing a new wave or fiber pair across that border during the spat warns you first that it will stay dark (#329).
|
||||
- A customer asking for a discount at renewal now shows how much traffic they book and get, the price per Gbps now and asked, and any latency limit or path terms they signed for, each ticked or crossed as your network stands today (#292).
|
||||
- The two city names at the top of a wave, dark fiber or virtual circuit panel now open that city, for example to upgrade the router there before a bigger link (#196).
|
||||
|
||||
## [3.3.0] — 2026-11-09
|
||||
|
||||
- You can now move a customer to another path between the same two POPs, with the most diverse options listed first. Waves and leased fiber pairs move to another fiber with room for them, leaving alone what you keep back for your own traffic, and circuits can be pinned to a path of your choice, falling back to normal routing while a link on it is down.
|
||||
- Routing a big network's day takes about half the work, with exactly the same results: on a network of 390 POPs with Auto-TE, a day's routing went from about 0.7 to 0.3 seconds on a computer.
|
||||
- Big networks no longer freeze for a moment at every new game day, above all with a NOC intern on duty. The intern now plans cache boxes, router ports and PNIs for every POP in one pass. On a network of 190 POPs the intern's shift held the page for about a tenth of a second on a computer and half a second on a phone; it now takes a few thousandths, and a whole day holds the page a quarter as long. The game plays exactly as before.
|
||||
- At ×8 a big network's autosave no longer holds the page: the game is packed, turned into text and compressed in the background, and less of each day's routing has to travel back to the page. The game plays exactly as before.
|
||||
- While nothing moves on the map but its animations (packets, waves, clouds), it is drawn 30 times a second instead of at the screen's full rate, half the work on most screens and a quarter on 120 Hz phones. Moving the map, pointing at something or anything changing on the network still gets every frame, and the animations keep their speed.
|
||||
- Linking to a coast where no subsea cable lands yet, like Iqaluit, now says how you can get there (overland, or with a cable of your own) instead of listing no cities to hop through (#321).
|
||||
- A delay while your own subsea cable is being laid now holds the lay ship where it is, instead of sending it back to port and starting the laying over. The cable already on the seabed stays there, the build simply finishes later, and there is nothing to pay twice (#322).
|
||||
- A paused game no longer rewrites its save every 5 seconds when nothing has changed. On a big network each of those writes held the page for 20 to 30 milliseconds.
|
||||
- A low-latency boutique with a lot of its own fiber no longer stalls every day while it times its finance routes. On a big fiber network that check held the page for about a third of a second and now takes a few hundredths; checking customers who want a path without subsea or under a latency limit got quicker too. The game plays exactly as before.
|
||||
- The NOC intern no longer holds a big network for more than half a second each time it weighs taking out a spare wave. Before it decides, it checks every customer promised diverse paths, no subsea or a latency limit, and on a network of 390 POPs that check now takes a few hundredths of a second. Spotting new sovereign cloud and trading offers is about ten times quicker too, and the game plays exactly as before.
|
||||
|
||||
## [3.2.0] — 2026-11-07
|
||||
|
||||
- New badges for traffic: serve 1 Tbps and 10 Tbps on the way to the 100 Tbps and petabit ones, and carry a petabyte, 100 petabytes, an exabyte and a zettabyte in one game. The dashboard shows how much traffic your network has carried so far, and only the top step of each ladder is legendary: Hundred Terabits is now epic.
|
||||
- Lambda Bazaar, a capacity market for your dark fiber, is a new tab in the NOC dashboard. Sell spectrum, managed 100G, 400G, 800G and 1.6T waves, and dark pair IRUs on every route you hold fiber on, and choose how much to keep back for your own traffic, from what demand the broker lists, and the price it never sells below. What each route wants moves all the time and grows every year: hot routes pay more, a fiber cut next door or a hyperscaler breaking ground sends demand up, buyers move from 100G to bigger waves over the years, and carriers already on your glass ask to move up a size. Short, straight routes earn more for fast waves. A Cable broker pays the broker 3% instead of 10%, and sees where each route is heading and which routes between its POPs are worth building.
|
||||
|
||||
## [3.1.0] — 2026-11-07
|
||||
|
||||
- Whoever runs sales can now answer renewal haggles for you, each in their own way: switch it on at the sales desk. The engineer keeps nerdy customers at the market price and gives everyone else their discount, the shark refuses discounts and some customers walk, and the CEO settles it on the golf course, for better or worse.
|
||||
- The three interns now each have something they are best at: Anycast Annie peers every day and orders PNIs twice a week, Kevin from the night shift swaps two line systems a night and never fat-fingers anything, and Tracy Route buys capacity as if traffic were already 10% higher. They run the same orders at the same salary.
|
||||
- Your intern can upgrade optical transport: a new standing order moves full, busy fiber to a bigger line system, or trades its smallest channels for bigger optics. Pick a line system, and every fiber on a smaller one is moved up to it. A line system swap takes the fiber down for a day, so the intern only does it where the traffic gets around it and no customer rides it, one a night.
|
||||
- Your intern can standardize your routers on a model you choose: pick it in Keep routers ahead, and every POP on a smaller model is swapped to it, the busiest first, within the monthly budget. Every setting in the Standing orders sheet is now a list to pick from instead of a button to tap through.
|
||||
- France gets seven more cities: Lyon, Toulouse, Lille, Bordeaux, Strasbourg, Rennes and Nantes, all but Nantes with an exchange of their own (#288). SF-Error Telecom and Boy-Egg Telecom bring home broadband and mobile, Ov-Hatch Cloud and Scale-Away bring French clouds, Tangerine Telecom and Free as in Beer reach the new cities, Cogentle reaches Toulouse, Lille, Bordeaux and Strasbourg, and Andorable Telecom comes up to Toulouse. The Atlantic cables now come ashore where they really do: Ami-Tea at Bordeaux and Dunno-ant at Nantes, and Dunno-ant starts at Virginia Beach.
|
||||
- Big networks at ×8 no longer stop for a moment when a day reroutes, after a failure, an event, the intern's shift or the sales desk's signing. Every routing a day needs now runs in the background like the day's own, a long day lets the map draw between its steps, and the check for customers afraid of sharks no longer walks every land fiber for each of them. Quiet notifications now also apply while the game is running.
|
||||
|
||||
## [3.0.0] — 2026-11-06
|
||||
|
||||
**Series of Tubes 3.0: Pie in the Sky.** You have wired up the planet with fiber, cables and routers. Now take your network to orbit: start your own rocket company, fill the sky with satellites (we call them pies) and sell internet to everyone your cables will never reach.
|
||||
|
||||
**How to get there.** Become Tier 1 in a game started with 3.0, whatever your charter, and Pie Control opens from the NOC tab, right next to the NOC dashboard. Want to look around first? In Sandbox the rocket company is yours from day one. Games you started before 3.0 keep the rules they began with.
|
||||
|
||||
**Rockets, pies and crusts.** Build a pie factory and a launch pad on the coast (the closer to the equator, the cheaper each launch), then fly rockets that carry pies into four orbital shells, the crusts. Once a crust is 40% full it starts carrying traffic: pie dishes at your POPs land it on your backbone, and homes and boats in the remotest places, airlines, cruise lines and even a Mars mission sign up. A town no cable reaches can join your network through orbit. You watch it all on a spinning cartoon globe, launches and fireballs included.
|
||||
|
||||
**Space is not quiet.** Solar storms, food fights in orbit, failed launches and spats with governments over landing rights keep you busy, and the Founder of your rocket company does something daft every few months, so the markets get the jitters until it wears off. Governments pay for space too, in a new Government money section of the bank. Run it well and a full constellation pays for itself in about seven years.
|
||||
|
||||
**Three charters.** A new game now starts by asking what you are building. **Global backbone** is the classic game: grow everywhere and become Tier 1. **Low-latency boutique** lives on speed: trading firms call more often and pay more, and you win Speed of Light by beating the fastest leased latency on finance routes with your own glass. **Cable broker** is new: lay fiber on land and cables under the sea from day one, light them and sell the capacity to other carriers, and win Glass Baron when your own cables land on five continents while carriers pay you $1M a month. Every charter can still become Tier 1, and so reach orbit.
|
||||
|
||||
**Sales runs the deals.** Your salesperson can now sign deals for you, orbit customers included, each in their own style, while the NOC intern sticks to running the network.
|
||||
|
||||
- Pie in the Sky: become Tier 1 and you can start your own rocket company, putting your network in orbit. Win Tier 1 in a game started from this version (any charter), and Pie Control opens from the NOC tab, next to the NOC dashboard; in Sandbox it is there from day one. Build a pie factory and a launch pad on the coast (near the equator, launches are cheaper), fly rockets that carry satellites ("pies") into four orbital shells ("crusts"), and watch it all on a spinning cartoon globe with a night side, laser links between pies and launches that either spill their pies into orbit or end in a fireball.
|
||||
- A new game now starts by asking what you are building, with three charters to choose from (#300). Global backbone is the classic game: grow everywhere and become Tier 1. Low-latency boutique: trading firms and other latency customers call more often and pay more, and you win Speed of Light by beating the fastest leased latency on finance routes with your own glass. Cable broker is new: lay fiber on land and cables under the sea from day one, light them and sell the capacity to other carriers, with ten goals of its own and the Glass Baron win when your own cables land on five continents while carriers pay you $1M a month. Every charter can still become Tier 1, and with it reach Pie in the Sky.
|
||||
- Your pies carry real traffic and earn money once a crust is 40% full. Pie dishes (ground stations) at your POPs land the traffic on your backbone, with landing rights bought country by country. Homes and boats in the remotest places (Pitcairn, the Arctic, the outer islands), airlines, cruise lines and even a Mars mission sign up, and a town no cable reaches can join your network through orbit. Before a crust carries anything, buoys and sensors that live with gaps in the sky pay a little; when it starts carrying traffic, a grand opening brings a month of daily calls.
|
||||
- Space is not quiet, and neither is your Founder. Solar storms, food fights in orbit, rain over tropical dishes, failed launches and geopolitical spats over data and landing rights keep you busy, and the Founder of your rocket company does something daft every few months, so markets get the jitters until it wears off. A full constellation pays for itself in about seven years if you run it well.
|
||||
- Deals belong to Sales now: your salesperson can sign deals for you, orbit customers included. The NOC intern sticks to the network. The engineer, the shark and the CEO each sign in their own style, and each sells orbit their own way, from careful deals where a pie dish has room to Mars missions agreed with the Founder on the golf course.
|
||||
- Governments pay for space too, in a new Government money section of the bank (Cash · Bank): the Rural Digital Pie Fund auctions support for remote towns only your satellites reach, the Export-Import Pie Bank lends against launches with strings attached, and the UK pays a grant when Pitcairn is served from orbit.
|
||||
- Pie Control helps you plan: the Launch tab says how long each crust takes to fill at your current pace and points to a better pad when your pads are the bottleneck, the Dishes tab tells you when dishes are worth building, and the Traffic tab shows who rides your satellites, how full each crust and dish is, and why a sky is still empty. Traceroute follows packets through orbit too.
|
||||
- The NOC tab is tidier: Pie Control sits in its top row next to the NOC dashboard, traceroute moved into Routing & DDoS, and All connections lives in the NOC dashboard.
|
||||
- From customer level 9 you can lay your own subsea cable without being Tier 1 first (#300).
|
||||
- Traffic now leaves your network at the nearest peering, so a PNI in London no longer pulls New York's traffic across the Atlantic when the New York IX reaches the same network (#298). Where a PNI and an IX port reach a network in the same city, the PNI still goes first, and RouteScript's `prefer pni` still hauls everything to your PNIs.
|
||||
- Fabric (NNI) ports now grow like your other ports: buy them at 10G, 100G or 400G (as fast as your router takes), and bundle up to eight into a LAG when one is not enough (#140). A fabric customer is no longer accepted, by hand or automatically, when its bandwidth would not fit on the port as well (#307).
|
||||
- Pressing Space to play again after a pause now picks up at the speed you were playing, not always at 1× (#299).
|
||||
- Your own subsea cables now land right on the city's dot, also in Fujairah, Dubai, Karachi, Barcelona, Osaka and other cities the map shifts slightly so they do not overlap (#305).
|
||||
- Starting a new network no longer leaves the last one's "New POP!" and money pop-ups frozen all over the map until a reload.
|
||||
|
||||
## [2.10.1] — 2026-11-05
|
||||
|
||||
- "Meet halfway" on a renewal now offers the price halfway between what the customer pays and what they ask, and the button shows it before you press (#293).
|
||||
- Fujairah sits on the UAE's east coast again, where its cables land, instead of on top of Muscat (#295).
|
||||
- Puzzles on phones no longer scroll. A bar at the top shows the stars, the money and the one thing to do next, with a chip for every flow that turns green once it all arrives; tap a chip to jump to its city. A city or a link opens a short card at the bottom, split into tabs (links, router, traffic; size, traffic, routing), so every button is on screen at once. Architect runs get the same bar, and Reset is in the ☰ menu on phones.
|
||||
|
||||
## [2.10.0] — 2026-11-05
|
||||
|
||||
**The map now runs on your graphics card.** Panning, zooming and fast play stay smooth even on huge networks. If something looks wrong or your phone gets warm, switch back to the old map in **Settings › Map drawing › Always 2D**. Older browsers stay in 2D on their own, and Settings › Diagnostic info shows which one you have.
|
||||
|
||||
**Customers sign contracts now.** When one ends they renew, grow, haggle or leave, and bandwidth gets cheaper every year. To bring in more deals, hire someone to run sales: an engineer who goes to every NOG, a shark who oversells, or the CEO, who thinks he sells best.
|
||||
|
||||
**Also new:** a "No POP yet" tab on the dashboard, clearer puzzles on phones, Gothenburg, Malmö, Haparanda and Bilbao on the map, and tooltips on the NOC charts.
|
||||
|
||||
- The map is now drawn by your graphics card, so panning, zooming and fast play stay smooth on big networks (#281). If it looks wrong or your device runs hot, go back to the old drawing in Settings › Map drawing › Always 2D. Browsers without WebGL2 stay in 2D on their own, and Settings › Diagnostic info shows which one you are on.
|
||||
- Customers sign contracts, and when one ends they renew, grow, haggle or leave (#178). Bandwidth prices fall over the years and rise when hardware is short, and the dashboard shows who you won and lost each month.
|
||||
- You can hire one person to run sales: an engineer, a shark or the CEO himself. Each brings different deals and leaves their mark on the customers they sign.
|
||||
- The NOC dashboard has a "No POP yet" tab listing every city you could still expand to.
|
||||
- Puzzles explain their goals in plain words, with a Show me button and marks on the map, and fit phones better.
|
||||
- Sweden gets Gothenburg, Malmö and Haparanda (#206).
|
||||
- Bilbao joins the map, where the transatlantic cables really land; Columbus III-and-a-half now lands near Cádiz.
|
||||
- NOC charts have tooltips, and their legend can hide a series.
|
||||
- Leasing dark fiber costs more, alien waves are priced against the fiber, and extra crews can only halve a land build (#203).
|
||||
- Clean traffic sent back by a scrubbing center no longer shows as DDoS junk on your links (#289).
|
||||
- In Firefox on a computer, the 2D map is up to three times as fast when zoomed in.
|
||||
- Fixes: a link ordered by the AI tools can no longer end in a city the map does not show, and names from a save file always show as plain text.
|
||||
|
||||
## [2.9.1] — 2026-11-04
|
||||
|
||||
- Jokes in the game now poke fun at networks, cables and routers, never at people, countries or beliefs. A few networks have new names (Atlas Hold-the-Line Telecom, Star-Blink, Telekom Malay-tency, Oh Yas Sénégal, Afghan Tele-Pass, Island-Hop Micronesia, Tel-One-derful, Tango Two-Step), so do three of the names for your own cables, and about forty descriptions of networks, cities, cables and events were rewritten.
|
||||
- A network operators' meeting that hires you for its event network now meets only where it really does: NANOG in the United States, APRICOT in Asia Pacific and Oceania (not mainland China or Hong Kong), DENOG in Germany, UKNOF in the UK, RIPE in Europe, the Middle East and Africa, and DKNOG in Copenhagen.
|
||||
- North Korea now moves well under 1 Gbps, and no customer of any kind calls from there.
|
||||
|
||||
## [2.9.0] — 2026-11-04
|
||||
|
||||
- In Architect runs, a diverse second tube now takes the cheapest other route, as a new tube does, so the Euro Run's plain plan fits its budget again. A failed review also says that every site still connected after a cut needs room for its traffic, not only the mission-critical ones (#282).
|
||||
- A new button next to the speed controls opens a NOC screen in a window of its own, to keep on a second display beside the map. It is a dark wallboard with a live world map of your links and POPs, traffic and money graphs, alarms, and your hottest ports with their upgrade buttons, which work on the running game; click a POP to see its ports. Details has the full dashboard, and Full screen fills the display. The new window only shows and sends clicks: your network is still played and saved in the game window. Phones do not show the button.
|
||||
- Cities of one country on one piece of land can be joined by fiber over land, even where there is no road: Pevek to Anadyr or Moscow, Juneau to Seattle, Nuuk to Sisimiut. Inside one country, crossing from Europe into Asia (Moscow–Vladivostok, Istanbul–Ankara) is no longer priced as a crossing between continents.
|
||||
- No circuit of any kind can be built between North and South Korea, and nothing leaves South Korea over land: every way out is a subsea cable.
|
||||
- The map zooms in twice as far, for crowded regions like New England or around Washington.
|
||||
- Cable ships at anchor sit a little further out from their port, and a tap on a city picks the city even with a ship close by.
|
||||
- With a credit rating of AA or better you can now call a bank from the Bank window and ask for the amount you need. The better your rating, the lower the rate and the more they will lend, up to a limit based on your revenue and what you already owe, but weird conditions always apply. (#251)
|
||||
- Agents playing through the Agent API can no longer start a link in a city where you have no POP, just as on the map. Before, an agent could sign a dark fiber IRU, lease a wave or lay a cable from such a city; now it is told why, and so is its dry run.
|
||||
- Build POP in a small city that is off the map now says why it can't, and names a city nearby to build in instead. Founding your own exchange where you can't (mainland China, a city that already has one, a city with no POP) says why too. Before, both did nothing without a word, and an agent's dry run quoted a price.
|
||||
|
||||
## [2.8.0] — 2026-11-04
|
||||
|
||||
- Every capital of the world is now on the map, with Africa's 33 capitals completing the set. They run from Porto-Novo, Bamako and Niamey to Khartoum, Juba, Mogadishu, Brazzaville, Tripoli, Rabat and Pretoria. Each country brings its real telcos, Nigeria gets its wholesale backbone up to Abuja, and the island capitals of the Comoros, São Tomé and Equatorial Guinea sit on their real cables.
|
||||
- The NOC intern has a new order, Keep peering headroom, that adds capacity to your PNI and IX ports before they fill up (#234). A single port at a POP with several routers gets a second port in a LAG; any other port moves up to the smallest size that fits. It has the same Headroom and Budget dials as the transit order, and it waits out DDoS floods, link faults and PNI augments already on order. The monthly figure in the intern's log now counts IX ports too.
|
||||
- An exchange port, a transit port or a PNI can now be stepped down one size from its panel, so shrinking a port no longer means leaving and rejoining (a PNI cannot while an augment is on order).
|
||||
- The traceroute can follow the metrics, the lowest latency or the quietest links, like a customer circuit.
|
||||
- Money now shows billions ($1.20B) and bandwidth shows petabits (1.00 Pbps) instead of running on in millions and terabits, including on the NOC graph and the fiber labels on the map.
|
||||
- Latency customers only ask for a ceiling something you can build meets. Before, a Mars ground station could ask for 4.3 ms between Pevek and Anadyr, where the only sea route takes 7.7 ms at best. (#273)
|
||||
- DE-Kicks ports stop getting dearer once they cost four times the list price. Before, the yearly price harmonisation kept compounding, so a long game ended up paying $100k a month for one port at Frankfurt or Mumbai.
|
||||
- Your own subsea cable from Buenos Aires to Santiago now earns The Long Way Round, like a wave leased on the old ring round Cape Horn. (#272)
|
||||
- Every capital in South, East and Southeast Asia and the Pacific is on the map: Thimphu, Kathmandu, Bandar Seri Begawan, Phnom Penh, Vientiane, Ulaanbaatar, Naypyidaw, Pyongyang, Dili, Hanoi and Wellington, with the island capitals Tarawa, Palikir, Yaren, Funafuti and Port Vila. Each country brings its real telcos, North Korea reaches the world only through China and Russia, and the islands hang on their real cables.
|
||||
- Every capital in the Middle East, the Caucasus and Central Asia is on the map, from Yerevan and Baku to Kabul, Tehran, Baghdad, Jerusalem, Amman, Kuwait City, Beirut, Damascus, Sanaa and Manama, with Ankara and Islamabad. Each country brings its real telcos, and Bahrain is an island on the Gulf's cables.
|
||||
- Every capital in Europe is on the map: Tirana, Andorra la Vella, Minsk, Sarajevo, Zagreb, Nicosia, Vaduz, Vilnius, Valletta, Chișinău, Monaco, Podgorica, Skopje, San Marino, Bratislava, Ljubljana and Bern. Each country brings its real telcos, exchanges sit only where real ones do, and Malta and Cyprus are islands on the real PEACE, MedNautilus and Blue cables.
|
||||
- Every capital in the Americas is on the map: the eastern Caribbean islands, Central America, Haiti, Guyana, Suriname and Bolivia's constitutional capital Sucre. The islands land the real cables (ECFS and Southern Caribbean Fiber), Flow and Digicel serve all of them, and Belize, Guyana, Suriname and Haiti get their own national telcos.
|
||||
- Every US state capital and Washington, DC are on the map, with every Canadian provincial and territorial capital and Greenland. Greenland's capital Nuuk and three towns up the coast hang on the real Greenland Connect cables; Iqaluit has only satellites, so land your own cable there. New carriers sell transit in the north and the Canadian provinces, and exchanges sit only where real ones do.
|
||||
- If you run the game on your own computer, an AI agent can now play it in your browser while you watch. Turn the Agent API on in Settings (the section only appears in a copy of the game you run with npm run dev, never on seriesoftub.es) and point an AI client at the game's MCP server: every move happens live on your screen, and docs/MCP.md in the repository explains the setup. You choose the clock: a pace from one simulated day every 30 seconds to 5 minutes, which nobody can pause and which waits while no agent is connected, or the agent moves time itself. Your game, your settings and the windows you open stay yours.
|
||||
## [2.7.0] — 2026-11-03
|
||||
|
||||
- Three new cities in northern Australia: Port Hedland, Townsville and Alice Springs (#255). Port Hedland lands a new cable up the coast to Darwin and a branch of Darwin's cable out to Singapore; Alice Springs has no sea at all. In the wet season, November to April, fiber cuts in the tropical north, Darwin included, take twice as long to reach.
|
||||
- New keyboard shortcuts: the arrow keys and W A S D move the map, [ and ] step through your POPs, $ through the open offers, - and = zoom out and in, n opens the NOC dashboard, and ? lists every shortcut. A letter right after n opens one of the dashboard's tabs, such as n c for Connections, and Help links to the list too.
|
||||
- You can pay to hurry the survey, permits and factory of your own subsea cable, 30 days at a time (#258). Money only goes so far: the cable still has to be made, about two months plus a day for every 80 km, before the lay ships sail.
|
||||
- Traceroute no longer shows an "embedded cache in your rack" hop on paths that leave over transit, an exchange or a PNI. Only traffic that really ends at one of your cache boxes shows it now.
|
||||
|
||||
## [2.6.0] — 2026-11-03
|
||||
|
||||
- New Best Effort mode, the gentlest way to play: rare outages, no DDoS, no chaos monkey, no conferences and no cable ships, with sea cuts that mend on their own. PNIs are up the moment you order them, customers are more patient, a rescue loan from the Ministry of Tubes replaces game over, builds take days and prices never spike. A new Quiet notifications setting, on by default in Best Effort and available in every mode, only pops up trouble and milestones; everything else goes into the NOC log.
|
||||
- Backbone, Auto-TE and DDoS settings now open from a Routing & DDoS button at the top of the NOC tab. They used to sit at the very bottom, below every notification; a red dot on the button says when Auto-TE is paused.
|
||||
- The Build POP button now shows the whole price of a new POP, including the routers of your standard POP (#261). Before, it showed only the site, although the standard routers were paid for on top; a note under the button now lists them, and the intern's one-tap template prices them in as well. POPs that come with a new wave, dark fiber, your own subsea cable or a consortium seat now get the standard routers too, and those offers show the price with them.
|
||||
- The intern's "Light more fiber" order has a new Optics setting: light new fiber with the biggest optic it can afford, to save channels for later (#262). Once a fiber is lit, the intern still adds more of the same optic and never swaps what is in there.
|
||||
- Networks you reach through an exchange's route server now stay "via RS" (#265). With an Open peering policy, the peering desk used to turn some of them into separate sessions of their own.
|
||||
- The tabs above the left panel no longer run off its edge on smaller screens and tablets. Counts such as finished goals now sit on the corner of their tab.
|
||||
- Gaming customers no longer warn that they attract attacks in modes without DDoS attacks, such as Change Freeze.
|
||||
|
||||
## [2.5.0] — 2026-11-02
|
||||
|
||||
**Mostly a performance release.** Big networks route their traffic on about half the processor time, days no longer freeze the game, and clicks that change nothing about your traffic answer at once, so phones last longer. Same routes, same results, just faster.
|
||||
|
||||
- Big networks use about half the battery they did: each day's routing takes half the processor time, and reuses what it worked out the day before when only demand has changed. Where traffic goes does not change.
|
||||
- The game no longer freezes while it routes each day's traffic on big networks. A background thread of the game does the routing, so the map, panels and buttons keep responding while days go by; what the day brings is exactly what it was before. Clicks that change your network still route right away.
|
||||
- On big networks, clicks that change nothing about your traffic now answer at once: dismissing an offer or renaming your network no longer works out every route again, which also saves battery on phones.
|
||||
- The calendar is real now: months have 28 to 31 days and every fourth year has a 29 February (#257). Monthly prices, loan statements, the intern's budget and paydays follow calendar months, and conferences fall on the 10th of their month.
|
||||
- Cache boxes are sized for the traffic each city really sends (#260): Russian and Chinese cities get boxes for the networks people there actually use, and none for networks they cannot reach. Boxes already installed stay; remove idle ones from the POP.
|
||||
- A 1.6T transponder on routers with 800G ports now takes two ports at each end, one for each 800G it hands over, and the optics list says so (#256). Before, a full 1.6T fit into a single 800G port. On 1.6T routers it still takes one.
|
||||
- A plug-in optic that is too short for your subsea cable no longer sends you to submarine terminals and optical engineering, which cannot stretch it (#253). The hint now names the optics that do reach, such as the Sienna WaveMagic 1.6T for Perth to Cape Town. Optics the upgrades can stretch still get the advice.
|
||||
|
||||
## [2.4.0] — 2026-11-01
|
||||
|
||||
- Cable ships now sail out to fix your subsea cables, and you can watch them on the map. A cut at sea calls the nearest free ship of its region's repair club, from ports such as Cornwall, Curaçao, Cape Town, Marseille, Vancouver, Tokyo, Manila and Singapore. The cut lasts while the ship sails out (about 500 km a day), splices for 3 to 5 days in shallow water or a week or two in the deep, and in some countries waits weeks for a repair permit. A ship is busy until it is home again.
|
||||
- Doitsche Telekomm and Tangerine Telecom are now Tier 1s, as in real life (#194). In new games, going transit-free means a PNI with both of them too; games you already started keep the Tier 1s they were playing for. Doitsche now sells transit at the highest price in Europe and still charges for peering, and like the other Tier 1s, Tangerine now starts its PNIs at 100G.
|
||||
- Cache boxes now share router ports through an aggregation switch: one port carries as many 100G boxes as its speed holds, so 32 fit on a 3.2T port (#252). Each site gets its own.
|
||||
- Pick a standard POP: in any POP's Infra tab, make its routers the standard, and every new POP gets that model and number of routers right away, while it is still empty (#240).
|
||||
- Big networks run faster: the map skips links off screen without working out their shape, and the Networks tab and the zoomed-in map draw faster. Where traffic goes does not change.
|
||||
- A network the game once failed to load is no longer stuck as damaged: the next version of the game tries it again, and its menu has a Try again button. Before, it could only be exported or deleted, even after the cause was fixed.
|
||||
- Save files of very large networks import again: the limit went from 8 MB to 64 MB.
|
||||
- 400G cache boxes: a POP whose routers have 400G or faster ports now gets 400G boxes, at $1,000 a month instead of $400 for 100G, so big caches need fewer boxes and cost less per Gbps. Boxes you already have stay as they are.
|
||||
- Clarovision now peers only over paid PNIs, like the real carrier, and free only with networks at customer level 11 or above (#213). A PNI you already have with it starts paying the fee.
|
||||
- Opening a link from a list now moves the map to it, zoomed so the whole line fits beside the open panel.
|
||||
- Traffic for a carrier now leaves through that carrier's own transit port at the same POP, instead of being shared with every other transit port there. Networks that buy transit from the carrier get the same treatment, and a new switch on each transit port, Carry here, pulls that traffic across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win, and Prefer only does so at the POP where you set it.
|
||||
- When every ship of a region's club is out, a subsea cut waits for the first one back. A private charter of the quickest free ship anywhere jumps the queue for $1M plus $200 per km it sails; the NOC intern's rush-repair order can pay it within its budget.
|
||||
- Building your own subsea cable now shows the survey, permits and cable factory first, then a lay ship laying about 150 km a day. Crews can no longer speed up a cable at sea: book a second lay ship before laying starts instead, for $3M plus $150k a day, and it lays from the other end to halve that part.
|
||||
- Tap a cable ship on the map to see its name, its club and what it is doing.
|
||||
|
||||
## [2.3.0] — 2026-10-31
|
||||
|
||||
- Clicking a city without a POP works again while the intern's transit order is set to Already connected (#249). Before, the city panel failed to open and the map stuck to the mouse.
|
||||
- The intern's Accept free caches order, and the Request caches button, now add more cache boxes as demand to a network outgrows the ones you have (#248). Before, they stopped at one box per site.
|
||||
- Manila gets real exchanges: GotchaFIX Manila, the free community Bayanihan-IX and In-Vitro-IX, run by PLDTea Time. Diverge, Smarty Pants, Ditto and RISE & Shine join as Philippine networks, and PLDTea Time and Globe-Trotter Telecom now sell transit.
|
||||
- Cebu joins the map on its own island, with GotchaFIX Cebu and two domestic cables from Manila: the Pan de Sal Cable Network and the Philippines Long Distance Relationship. PLDTea Time, Globe-Trotter Telecom, Diverge and RISE & Shine reach Cebu, and typhoons can hit it too.
|
||||
- Davao joins the map on Mindanao, with GotchaFIX Davao. Bi-Frosted and SEA-US Later now land in Davao, as the real cables do, instead of Manila; a link you already run on their old Manila landings keeps working as a plain subsea link. Three domestic cables reach Davao from Cebu: the Pan de Sal Cable Network, the Philippines Long Distance Relationship and the new Diverge VisMin Express. RISE & Shine peers at GotchaFIX Davao. The Pan de Sal Cable Network also runs straight from Manila to Davao.
|
||||
- Transit in the Philippines now costs about twice the Asian rate, as it really does, and Philippine homes pay less for broadband. GotchaFIX ports cost what the real exchange charges, about $700 a month for 10G and $2,800 for 100G. In-Vitro-IX charges about double that.
|
||||
- Waves between Philippine islands now cost more than waves out of the country: Manila to Cebu costs about twice Manila to Hong Kong.
|
||||
- Manila, Cebu and Davao have more people online, in line with their real populations.
|
||||
- Cable names on the map no longer pile on top of each other when you zoom in. Where short cables crowd together, a name that would cover another is left out, and selecting a city shows the names of all its cables.
|
||||
|
||||
## [2.2.0] — 2026-10-31
|
||||
|
||||
- DDoS attacks are realistic now: most are small, the big ones are rare, and their size no longer grows with your network, so a big network is no longer hit by floods larger than the internet's record. Attacks go after one customer (gamers and hosting attract the most) or one city's subscribers, last one to three days, and On-call sees about one a month (#242).
|
||||
- A flood now arrives on every port the internet reaches you on, so more POPs and more exits spread it thinner, and a port it fills slows every customer on it. Flowspec and scrubbing behind a full port can no longer empty it (#242).
|
||||
- RTBH now blackholes only the customer under attack, upstream at your transits, most exchanges and about half your private peers: everyone else is saved and the target goes dark until you withdraw it. The IX blackhole button is part of RTBH now, and RouteScript's `blackhole ddos` does the same.
|
||||
- Find any city with the new 🔍 button in the top bar, or press / on a keyboard (#218). Type a city, a country (in your language or in English) or an exchange, and the map jumps there.
|
||||
- Cities on the map now show how big they are: zoomed out, bigger cities are bigger dots and megacities glow; zoomed in, a city's skyline grows from a hut to a megacity's towers. When cities crowd together, the smaller ones step back to a dot until you zoom in, so the map stays readable, and exchanges you haven't joined are quieter tags.
|
||||
- An engaged scrubbing center now pulls the whole flood onto its own ingress and cleans up to its size, so your ports stay clear and only the target suffers if the center is too small. On-demand scrubbing takes half the flood on its first day instead of nothing for two days.
|
||||
- Each router holds a limited number of Flowspec rules, shown in its POP: every attack takes one rule on each router it enters (a carpet bomb takes four), and when they run out, junk passes that router unfiltered. Bigger routers hold more.
|
||||
- The NOC's attack card reads like the flood's path: who is hit, which ports are full, what Flowspec and scrubbing do, the result and the one thing to do now. Optional Auto-RTBH and auto-engaged scrubbing switches sit in the NOC, full ports pulse on the map, and Sandbox can send a test flood.
|
||||
- Flood Season starts at customer level 4, so a 10T scrubbing center is within reach for the terabit floods; a flood you blackhole to save everyone else no longer counts as held.
|
||||
- The intern's transit order has a new provider choice, Already connected: it only grows the transit you already buy at each POP, the smallest port first, and never signs a new provider, so several upstreams grow together and no customer's "no Cogentle" gets a surprise (#227).
|
||||
- The intern's PNI order now counts the traffic the PNI list shows at each POP, so it no longer orders a PNI where a network's own cache boxes already serve most of its traffic (#244).
|
||||
## [2.1.0] — 2026-10-31
|
||||
|
||||
- Your backbone now runs a technology you choose: plain IGP, LDP/MPLS, RSVP-TE, SR-MPLS or SRv6. Each step up costs plenty and uses less router CPU: label switching makes traffic that only passes through a POP cheaper for its router, and Auto-TE and RouteScript now need RSVP-TE or higher. Routers only run what they support, so a POP with an older router stays outside the backbone, and mixing vendors at the very top of what their routers can do brings interop failures. Networks that already have Auto-TE keep it exactly as it is.
|
||||
- An upgraded backbone brings new customers: L3VPNs for enterprises from LDP/MPLS, flex-algo low-latency links from SR-MPLS and network slices from SRv6.
|
||||
- A seat on a consortium cable can be lit with the optics you have: add regen sites in the landing stations along the cable. Before, a seat bought at level 2 or 3 stayed dark until long-haul transponders arrived at level 4.
|
||||
- List spare capacity with a capacity broker as a standing listing: pick how many alien waves (or your spare pair) to sell, and the broker sells them off over time as carriers on that route want capacity. Each route's market is sized by the eyeballs at both ends, and a busy route sells in days while a road to nowhere sells maybe once, so renting out long empty fibers is no longer a money machine (#203).
|
||||
- Two new routers for RSVP-TE backbones: the refurbished Brocadabra MLX-16 with 400G ports, and the Extremely Networks SLX 9740 with 1.6T ports.
|
||||
- From RSVP-TE up, fast reroute has backup paths ready, so customers lose only half as much happiness while a link is cut.
|
||||
- An interop lab in the NOC tests your vendors against each other first and cuts interop incidents by 60%.
|
||||
- Four new badges for your backbone: Label switcher, Bleeding edge, Single-vendor shop and Vendor zoo.
|
||||
- The chaos monkey's notice in the NOC no longer has an Open button that did nothing; the monkey's own card is right above it (#226).
|
||||
- The puzzle list counts each section's own stars: architect runs show theirs next to their title, and the pack total now sits right above the packs, the stars that unlock the next one (#231).
|
||||
- The intern's notes now name the exchanges it peered at: a city's first exchange showed as the city, so "Apfelwein-IX, London" really meant Apfelwein-IX and LYNX (#228).
|
||||
- Cancelling an IRU, giving up your own fiber or decommissioning a POP now puts the optics on its fibers back on the spares shelf, instead of throwing them away (#229).
|
||||
- Big networks freeze for less on every game day and every click: working out where traffic goes skips exits whose route is already full, so a game day takes about 40% less time (#210). Traffic goes exactly where it went before.
|
||||
- Premium submarine terminals and Optical engineering can no longer be bought on a cable where they would change nothing (#198). The button now says so, and an upgrade that only helps together with the other one stays available.
|
||||
- A wave size that is sold out on a route can no longer be reached by upgrading a smaller wave on it (#201). The upgrade button says how long it is sold out, just like when buying.
|
||||
- Choosing Both for a PNI with one member now really splits it: the second member arrives in the other building when the augment lands, instead of joining the first (#219).
|
||||
- The Open button next to your intern's weekly shift report in the NOC now opens the Standing orders sheet, where the whole week is laid out (#226). Before, it did nothing.
|
||||
|
||||
## [2.0.0] — 2026-10-30
|
||||
|
||||
**Series of Tubes 2.0: one game, four doors.** Some of you wanted a calmer game, some a harder one, some a quick puzzle over coffee and some a playground where nothing can go wrong. So now every network starts behind a door, and the rules you pick stay with that network for good. Your saved games carry on exactly as they were.
|
||||
|
||||
**Normal** comes in three flavours. Change Freeze is the calm one: a third of the outages, no DDoS floods, and deliveries in days instead of months. On-call is the game you know. BGP at 3 a.m. is for people whose pager is a personality: more outages, longer ones, more attacks, and fiery badges to prove you survived. In your first month you also pick a charter: a global backbone, or a low-latency boutique racing the speed of light.
|
||||
|
||||
**Sandbox** is a real sandbox now: everything unlocked from day one, money that never runs out, and a chaos dial from nothing ever breaks to spicy.
|
||||
|
||||
**Puzzles** are small networks that carry real traffic, routed exactly like the big game. Deliver every flow for the first star, stay on budget for the second, and survive any single cut for the third. When your build earns a star, the chaos monkey runs round the map snipping every trench and cable to prove it. A new puzzle arrives every Sunday morning, the same for everyone.
|
||||
|
||||
**Architect runs** grow one network brief by brief. New sites sign up, some become mission-critical, a city closes, traffic outgrows its tubes, and the chaos monkey reviews every brief before the next customer signs. Three handmade runs to start, and a fresh one every Sunday with its HQ somewhere new.
|
||||
|
||||
**Scenarios** are themed crises against the clock: a cut cable, a peering spat, a flood week, a race for low latency. A new one comes out every Sunday too.
|
||||
|
||||
And in On-call and BGP at 3 a.m., a **chaos monkey** sometimes moves into your network for a few months and snips tubes on purpose, the ones without a backup path first. Outlast it without a customer noticing and it pays; throw it a banana if you have had enough.
|
||||
|
||||
**Also new:** Tier 1 works like the real thing, so peering with the big club brings their customers along. A NOC intern carries out your standing orders. Customers call when your network can serve them, not only when your level says so. You can buy a seat on a consortium subsea cable, see at a glance whether a PNI is worth it, keep several networks and play two side by side, and every router model has its own face.
|
||||
|
||||
### One game, four doors
|
||||
|
||||
- A new start screen with four doors: Puzzles, Sandbox, Normal, and Scenarios & weekly. Every network now picks its rules when it starts, and they stay locked for that network; your saved games carry on exactly as before.
|
||||
- Normal comes in three flavours. Change Freeze has a third of the outages and no DDoS floods, delivers PNIs, cross-connects and builds in days instead of months (#151), and skips hardware shortages, sold-out routes and de-peering at exchanges. On-call is the classic game. BGP at 3 a.m. brings almost twice the outages, lasting half as long again, and twice the DDoS. The HUD and the share card show which one you picked.
|
||||
- Sandbox is a real sandbox now (#188): everything is unlocked from day one, your own subsea cable included, money never runs out, deliveries are quick, and you pick how much chaos you want, from none to spicy.
|
||||
- Pick a charter in your first month of a Normal game: Global backbone (the game as you know it, and the default) or Low-latency boutique (#187). The boutique gets more trading firms, pays them 40% more and has its own win, Speed of Light: beat the fastest leased latency on three finance routes with your own glass while two latency customers pay you. It comes with a badge and shows on your share card.
|
||||
- Badges now come in variants: games under the Change Freeze rules earn frosted Freeze-dried badges, and games under BGP at 3 a.m. earn fiery ones worth bragging about. Earning a badge under harder rules than before upgrades it in your collection on this device, and the badge list counts how many of each kind you have. On-call games earn the standard badges; Sandbox and puzzles earn none.
|
||||
- Keep several networks on one device, and play two of them side by side in two browser windows. The title screen lists your networks, newest first, with their day, tier, cash and when you last played; tap one to continue it, or use ⋯ to export or delete it. Starting a scenario, the weekly challenge or a new network, or importing a save, now adds a network instead of replacing the one you have, and you can rename a network from the menu. Each window remembers its own network when you reload it. If a network is already open in another window, you can switch to it or take it over, and the other window steps aside instead of both saving over each other. Your existing save carries on as your first network.
|
||||
- A tidier start screen: language first, then your network's name, the doors, three compact difficulty buttons with the chosen one explained below, and one drop-down for your home city with the five suggested homes at the top.
|
||||
- Pick your own AS number next to your network's name when you start (#135). Leave it empty and the game picks one, and the round green arrow in the name box suggests another name.
|
||||
|
||||
### Puzzles
|
||||
|
||||
- Puzzles: small networks that carry real traffic, routed exactly like the main game (#190). Each puzzle has flows to deliver (eyeballs pulling from a content origin, circuits between two cities with a latency cap, best-effort traffic that may drop), and the map shows every link's load as it fills. Earn up to three stars: everything delivered, under budget, and still delivered when any single trench or cable is cut. Build with the real tools: link sizes from 10G to 800G, parallel links in the same trench or on a diverse route (also from the link panel), routers with real ports and limits, routing metrics, standby, lowest-latency paths for circuits, and the redundancy check. The whole world is open: any city can get a POP if it helps. Parallel links show their count and sizes, and selecting a city lights up every path it has. Eighteen puzzles in five packs, each teaching one idea: Fat Pipes, Router Rodeo, Traffic Cops, N-1 Club and Grand Tour. No clock, no bills, nothing breaks, and your main game is never touched.
|
||||
- A new weekly puzzle every Sunday morning, the same for everyone: a themed puzzle with its own traffic, such as an ocean crossing, a ring, a latency sprint, island hopping or a detour around a busy hub, with its own name and a budget tuned so three stars take a smart design. The Puzzles door says "New this Sunday!" until you have played it, the list counts down to the next one, and your streak and share line use the week's name. A new puzzle week starts on Sunday at 06:00 Berlin time; offline, the game still has a weekly puzzle of its own.
|
||||
- Every puzzle now has the chaos monkey: when your build earns a new star, it runs round the map snipping each trench and cable in turn, and the cities that lose traffic say how much. Let it loose again whenever you like, or skip straight to the stars.
|
||||
- In puzzles, the map now shows whether the tubes between two cities share one trench or take separate paths, at any zoom: one trench is drawn as a bundle with a "2× one trench" tag, separate paths bow apart with a "2 paths" tag.
|
||||
- When a new release changes prices so that this week's or a coming week's puzzle no longer adds up, that puzzle gets a fair new budget, and only its stars start again. Weeks that are over keep theirs.
|
||||
|
||||
### Architect runs
|
||||
|
||||
- Architect runs, under Puzzles: grow one network brief by brief, from a single tube to a ring that shrugs off any cut. Your build carries over between briefs, mission-critical sites must survive any single trench or cable cut with room on the detour, and a chaos monkey runs round the map snipping tubes before the next customer signs. Three runs to start: Euro Run, Coast to Coast and Pacific Rim.
|
||||
- A new Architect run every week: every Sunday a fresh HQ somewhere in the world and six or seven briefs, each built around the network you already have, with its own stars. Sites can outgrow their tubes, so some briefs are about making room. Later briefs stay a surprise in every Architect run: their cities only appear when they come.
|
||||
|
||||
### Scenarios
|
||||
|
||||
- A new weekly scenario every Sunday morning too, the same for everyone: a themed crisis such as a cut cable, a peering spat, a big event, a flood week, island hopping, a race for low latency, a push across a continent or a shoestring budget, in about a year of game days. It sits at the top of Scenarios & weekly with a countdown and a "New this Sunday!" badge, has its own goal and progress card, a par to beat, a weekly streak and a result line to share. Offline, the classic weekly challenge stands in.
|
||||
- Scenario tuning: every handmade scenario now asks for what its story is about, with shorter clocks where it was won in a tenth of the time. Mind the Gap, Cape to Cairo and Order and Progress count cities and IX.brrr ports only when your network joins them up; Fibre to the Basement also wants 500 Gbps served; in Anchors Away nobody sells transit in Tallinn and ships really do drag their anchors over the Baltic links, while the Great Firewall's losses no longer break your 99.5% streak; in the Cogentle Spat, Goggle wants a lot more of your traffic before it peers; Flood Season's terabit floods count when your scrubbing or Flowspec took them; Stepping Stones and Mid-Atlantic Accent start with 5M, enough to light the whole 1.6T chain. Gangnam Style Peering is now really about sender pays: Seoul transit carries a fee on every Gbps, the three incumbents only peer over a paid PNI, and Korean users notice every millisecond, so you win by hauling cheap Tokyo transit while keeping Seoul fast and in profit.
|
||||
|
||||
### The chaos monkey
|
||||
|
||||
- A chaos monkey now and then moves into your network in On-call and BGP at 3 a.m., and snips a tube every couple of weeks for 120 to 240 days, tubes with no backup path first. Its snips replace the usual random outages while it is here; get through the visit without a customer noticing for a resilience bonus and a new badge, or throw it a banana to send it home early. The "Met the Backhoe" badge is now "Met the Chaos Monkey", earned on its first visit; badges you already have stay yours.
|
||||
|
||||
### Build your network your way
|
||||
|
||||
- Customers now call when your network can already serve them, not only when your level says so (#187). A fast path between two finance cities brings trading firms, lit dark fiber brings AI interconnects, two diverse paths in one country bring sovereign clouds and broadband in a big city brings cloud gaming, each at its smallest size and with a note on what they spotted; your level still makes them bigger and more frequent.
|
||||
- Routers, line systems and optics one level above yours can be had early as a vendor demo unit (#187). Ask the vendor, wait about two weeks, then pay 60% over list until your level catches up; and you can dig your own dark fiber from level 2 as a pioneer, at 60% more than the level 3 price.
|
||||
- Take a seat on a new consortium subsea cable (#173). Capacity conferences offer them, and now and then a consortium calls from level 2: pay your share of the build, wait for the ship, then own one, two or four fiber pairs and light them with your own optics, your way onto your own subsea glass before Tier 1. A cut on that cable cuts your pairs too.
|
||||
- Hire a NOC intern and give them standing orders: from customer level 2, Kevin from the night shift, Anycast Annie or Tracy Route runs your rules once a game day and pays exactly what your own clicks would. Keep transit above a multiple of its peak, add or swap routers above a load, take free caches, peer at every IX and PNI with the big networks every week, sign ready customers and decline tiny ones, rush repairs, light more fiber and retire small parallel waves. Each order has a pause switch, its own settings, a monthly budget and per-POP exceptions, never breaks a customer's or a bank's transit requirement, and shows what it adds to your monthly bill. The Ops sheet opens with the intern's mood and a weekly shift report, which is also the one notice a week the intern leaves in the NOC (#98, #100, #102, #181, #185, #192, #177).
|
||||
- The intern only signs a customer after a trial run shows the network can carry them without hurting anyone else, and rushes every repair that has a price, while the budget lasts (#185). The bulk peering and PNI batches live in the Ops sheet, next to the orders that repeat them (#181, #192).
|
||||
- Open a new city from a template in one tap: POP, broadband, transit, an IX port and the redundancy kit, priced up front, with your standing orders taking it from there (#98, #192).
|
||||
- Utilities join route servers and request eligible peers across every joined IX, install missing PoP redundancy hardware and balance caches between sites, and request a cache from each eligible provider at each site. A POP's Infra tab shows the redundancy kit as one line with its price, above the rows it fills in.
|
||||
- Order PNIs with one network or every network at all shared POPs from the Ops sheet: choose a port size, review the total cost, and add missing connections or upgrade smaller ones in one go. Each network keeps its own smallest PNI size and delivery time.
|
||||
- Set the number of each optic model directly on land and subsea fiber links. Apply a whole change at once, with its total price shown before buying; removed optics return to the spares shelf.
|
||||
- Every router model has its own picture: open one of your POPs and its router sits next to the city's name.
|
||||
|
||||
### Peering and Tier 1
|
||||
|
||||
- Tier 1 now works like the real thing: peer with the Tier 1 club and their customers come along for free (#85). A PNI or an exchange session reaches the networks you peer with and everyone who buys transit from them, so you no longer chase every tiny ISP for the win; only networks that buy transit from nobody, like the content giants and the big incumbents, still need peering of their own. Small networks and more real eyeball ISPs now buy transit from real-world upstreams, a peer's customers are tried after your direct peers and before transit (so peering widely still pays), the traceroute shows the hand-off, and the Road to Tier 1 card counts who already comes along. Games already won stay won.
|
||||
- The peering inbox is gone: your peering policy now answers every peering request for you. Open accepts everyone, Selective accepts small networks on the exchange and newcomers with an up-to-date PeeringDB and quietly declines the rest, and Closed declines them all; once a week the NOC log sums it up, like "Peering desk: 7 new sessions at DE-KICKS and HAMS-IX, 3 declined (Selective)". Max-prefix alerts, the button that raised every limit at once, max-prefix outages at exchanges, your peering reputation and the Large Peering Model are gone too. The policy picker sits in the Networks tab, saved games keep their policy, and a game that hired the AI simply stops paying for it.
|
||||
- Every network in a POP's PNI list now shows how you reach it today and whether a PNI there is worth the cross-connect (#175, #172). A chip says PNI here (with size and load), PNI elsewhere, which exchanges you peer at, whose customer cone carries it, transit only or not reached; a value line shows how much of its traffic leaves from that POP over transit, exchanges or other PNIs, and what a PNI there would save or cost a month. The best candidates get a ⭐ Worth it tag, the list sorts them first, filters to All, Via transit, Worth it or Already PNI, and groups networks by type, with idle groups folded. The same chip shows in the Networks tab and in the bulk PNI preview.
|
||||
- Only Spätzle-IX now asks for 50% reach instead of 45%, since peering with the Tier 1 club brings their customers along. Two Tier 1 PNIs and the exchange are no longer quite enough (#114).
|
||||
- Every country on the map now has at least two homegrown eyeball networks. Sixty-three real consumer ISPs and mobile operators join, from Angola and Bangladesh to Iceland, Japan and Zimbabwe, each with its real AS number and a pun name. They buy transit from the big carriers, so peering with the Tier 1 club reaches them too, and saved games get the usual courtesy route to them for their first 60 days.
|
||||
- Palau's and the Marshall Islands' main networks now show their real AS numbers instead of ones borrowed from networks elsewhere.
|
||||
|
||||
### Prices, routing and money
|
||||
|
||||
- Prices now follow how connected each city really is, based on public peering and routing data. Every city on the map now has it, from Düsseldorf and Riga to Malé, the Caribbean and the Russian Arctic. Transit costs up to 1.8× more in cities where few networks are present, a POP costs 1.25× to 1.5× where there is little or no carrier-neutral data center, and countries with thousands of networks, like Brazil and the US, bring more ISP customers. Big hubs such as Frankfurt, Amsterdam, New York and São Paulo keep their prices.
|
||||
- Every city now knows its country. Long-distance waves cost double only where they cross a border inside Africa, as they always meant to; a few northern routes, such as Kristiansand to Esbjerg and Anchorage to Halifax, lose a surcharge they picked up by mistake.
|
||||
- Transit bills no longer change when you click something later in the day. After each day, the 95th percentile counted that day twice and dropped the oldest day, so building or changing anything could nudge your transit bill (and the bank's view of it) until the next day came round.
|
||||
- Links can now use a custom routing metric, set either as a multiplier or as an exact cost. Pick Custom under Routing metric to fine-tune where your traffic goes; it explains how a link's cost is worked out and what each preset comes to on that link.
|
||||
- Check a selected link’s redundancy against current demand: see disconnected endpoints, additional service loss and full fallback links without changing the live network.
|
||||
|
||||
### Attacks
|
||||
|
||||
- Attacks are more varied: sizes and lengths change from one attack to the next, and several can hit at once, each with its own controls in the NOC. Hosting game servers or cloud gaming makes attacks more frequent, as it does in real life (#153).
|
||||
- Hosting game servers or cloud gaming brings RackNet and TeamSpooked attacks. Both bypass Flowspec and require dedicated mitigation (#153).
|
||||
- Attacks can now use Memcached amplification or an ACK flood. Flowspec catches the former; the latter need mitigation (#153).
|
||||
- Game server and cloud gaming customers now carry a “Gaming attracts attacks” note on their offers and customer lists, so you can see the DDoS risk before signing them (#153).
|
||||
- Each live attack in the NOC now shows incoming bandwidth, upstream scrubbing, edge filtering, scrubbing-center use and any traffic still leaking through (#153).
|
||||
- DDoS bandwidth now adds up: upstream scrubbing, edge filters and scrubbing centers work in sequence. The NOC uses the same figures as traffic routing, including floods that cannot reach a remote center (#153).
|
||||
- Live attacks now show how much traffic Flowspec actually drops. Routers without TCAM no longer claim to filter attacks, and Flowspec drops are counted separately from other edge filters (#153).
|
||||
- Live attacks now show one scrubbing detour from the attacked city to its nearest active scrubbing center, using the links' one-way latency (#153).
|
||||
- The link traffic breakdown now shows the correct source city for scrubbing traffic. Cities using the same center no longer overwrite each other's labels (#153).
|
||||
- Flood Season keeps sending ever larger attacks when you keep playing after winning or running out of time. Finishing the challenge no longer switches the floods off (#153).
|
||||
- Flood Season escalates again: ordinary floods mixed with terabit monsters, all growing through the year, and floods go for the POPs that serve customers, so empty POPs no longer hold them for free.
|
||||
|
||||
### Smoother and safer
|
||||
|
||||
- Big networks load faster: on a phone, the map of a late-game network now appears about a second and a half sooner.
|
||||
- The Networks list shows 100 networks at a time, with a button for the rest, so it opens quickly now that every country has its own networks.
|
||||
- When your browser's storage is full, the warning now lists your other networks by size so you can export or delete one to make room. Closing the tab in the middle of a puzzle no longer loses recent progress on the network you set aside.
|
||||
- The China licence follows quick lead times: about 5 days instead of 45 under Change Freeze and in Sandbox.
|
||||
- Imported saves can no longer change a network's rules or slip HTML into a Flood Season attacker's name.
|
||||
|
||||
## [1.37.0] — 2026-10-28
|
||||
|
||||
- Series of Tubes now speaks German. The game follows your browser's language the first time, and you can switch to German under Settings or on the title screen. Networking terms like Peering and Transit stay in English, the way network engineers say them.
|
||||
|
|
@ -114,7 +475,7 @@ All notable changes to this project are documented here. The project follows
|
|||
- Come chat with other players in the new Series of Tubes Signal group. It's linked from the title screen, the menu and How to play: share screenshots, report bugs and argue about peering policy.
|
||||
- RouteScript speaks more BGP. `prefer transit` and `avoid transit` set which upstream goes first, like local-pref, `prepend transit PROVIDER 1-3` moves part of an upstream's traffic away, the way AS-path prepending nudges the rest of the internet, and `protect customers` routes business traffic first when links are congested, so home users take the hit instead of your SLAs. A new Optimize button drafts a script from live traffic and points out networks you could reach over an IX or a PNI instead of transit.
|
||||
- Twelve more Latin American cities: Montevideo, Asunción, Córdoba, La Paz, Quito, Medellín, Caracas, Guatemala City, San José, Querétaro, Monterrey and Guadalajara. Moviestar, Liberty Latte America, Antelope and Tiger Mobile join them, and Salvador and Montevideo get cable landings.
|
||||
- Seven new cables around Africa (ACE of Spades, SAT-3-Legged Stool, MainOne-Track Mind, Mint Tea West Africa, Set SAIL, Sea-Comedy Hour and Dare-Devil-1), and the existing ones now stop in the new cities. Set SAIL and SACS-y Cable link Brazil to Cameroon and Angola, and Sea-Comedy Hour links Djibouti to Mumbai. Liquid Lunch Networks, Sea-Comedy Networks, Angle-a Cables, Djibouti Calling, Empty-N, Air-Tell Africa, Ethio-Tele-Calm and Atlas Shrugged Telecom join the networks.
|
||||
- Seven new cables around Africa (ACE of Spades, SAT-3-Legged Stool, MainOne-Track Mind, Mint Tea West Africa, Set SAIL, Sea-Comedy Hour and Dare-Devil-1), and the existing ones now stop in the new cities. Set SAIL and SACS-y Cable link Brazil to Cameroon and Angola, and Sea-Comedy Hour links Djibouti to Mumbai. Liquid Lunch Networks, Sea-Comedy Networks, Angle-a Cables, Djibouti Calling, Empty-N, Air-Tell Africa, Ethio-Tele-Calm and Atlas Hold-the-Line Telecom join the networks.
|
||||
- Hamburg and Munich join the map, with the Moin-IX and the Brezn-IX. Stuttgart and Frankfurt are back where they belong on the map, with Stuttgart between Frankfurt and Zurich instead of halfway to Prague.
|
||||
- Swapping router models now sells the old ones on eBuy for 30% of their price, and removing a router does too (#82). A POP takes one swap a day, so a double click no longer buys two upgrades, and optics and waves now say which port speed they need instead of naming one model.
|
||||
- Fiber between nearby cities bends gently again instead of looping wide around the neighbourhood, so dense regions like Toronto, Ottawa and Montreal stay readable.
|
||||
|
|
|
|||
|
|
@ -5,7 +5,8 @@ https://seriesoftub.es, hosted on GitHub Pages. The game is one static page with
|
|||
Its source is many small files in `src/` (`src/styles/*.css`, `src/game/**/*.js`, the shell
|
||||
`src/index.html`); the build pastes them together, in path order, into a single `index.html`, the
|
||||
same one-file page players have always loaded. Static files (dictionaries, icons, service worker)
|
||||
live in `site/`.
|
||||
live in `site/`. `src/agent/` (the facade the MCP server plays through) goes into the development page only,
|
||||
never into the page players get, and nothing in `src/game/` may use it (`docs/adr/0004-dev-only-code.md`).
|
||||
|
||||
Read these before larger changes:
|
||||
|
||||
|
|
@ -13,12 +14,14 @@ Read these before larger changes:
|
|||
- `docs/adr/`: decisions that are settled (GitHub Pages only; one page assembled at build).
|
||||
- `.claude/skills/`: step-by-step procedures (`edit-the-game`, `github-pages`, release,
|
||||
translations, tests, performance).
|
||||
- `.claude/skills/gameplay-rules/`: the game's design rules (W1, N3, F2…), each enforced by
|
||||
`tests/gameplay-rules.test.js`; run it before changing cities, networks, cables, modes or balance.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
npm ci # once: installs jsdom for the tests
|
||||
npm run dev # play while developing: http://localhost:8080, reloads on save
|
||||
npm run dev # play while developing: http://localhost:8080, reloads on save (--host to share)
|
||||
npm test # node:test + jsdom, every tests/*.test.js, must stay green
|
||||
node scripts/i18n-check.js # must report "0 missing, 0 unused, 0 broken" (and sorted dictionaries)
|
||||
node scripts/i18n-add.js FILE.json # add/change/remove translations (see `add-strings`)
|
||||
|
|
@ -26,6 +29,7 @@ npm run build # builds _site/ for GitHub Pages (assembles src/, s
|
|||
npm run serve # build and serve the production site locally
|
||||
npm run perf -- --base-ref origin/main # big-network benchmark vs main (see `performance`)
|
||||
npm run perf -- --base-ref origin/main --browser # the same, also in real Chromium (desktop and phone)
|
||||
npm run mcp # the game as a local MCP server for AI clients, stdio or --http (docs/MCP.md)
|
||||
```
|
||||
|
||||
## Hard rules
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ project, online or at a conference bar after NANOG.
|
|||
- **Own your mistakes.** We all fat-finger a config now and then. Apologise, fix it,
|
||||
move on.
|
||||
- **Keep the jokes kind.** This game runs on puns. The target of a joke is a network,
|
||||
a cable or a backhoe, never a person or a group of people.
|
||||
a cable or a router, never a person or a group of people.
|
||||
|
||||
## What we don't accept
|
||||
|
||||
|
|
|
|||
|
|
@ -52,10 +52,11 @@ and remembers the one you pick under Settings or on the title screen.
|
|||
|
||||
```sh
|
||||
npm ci
|
||||
npm run dev # development server: assembles src/ on every request, reloads on save
|
||||
npm run dev # development server on localhost (--host to share): assembles src/ on every request, reloads on save
|
||||
npm test # headless tests: boot, geography, a year of play, every incident, every panel
|
||||
npm run build # writes the site for GitHub Pages to _site/, with version and date stamped in
|
||||
npm run i18n:check # lists text missing from (or stale in) the translations
|
||||
npm run mcp # the game as an MCP server, so an AI client can play and debug it, headless or in your tab (docs/MCP.md)
|
||||
```
|
||||
|
||||
## Community
|
||||
|
|
|
|||
28
docker/Dockerfile
Normal file
28
docker/Dockerfile
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# The MCP server and the development server in one image (docs/MCP.md, "In a container"). docker.yml builds it and
|
||||
# publishes it to GHCR for releases only; nothing here is ever deployed to GitHub Pages (docs/adr/0001-github-pages-only.md).
|
||||
# The base is pinned by digest and kept current by Dependabot (.github/dependabot.yml); CI tests on the same Node major.
|
||||
FROM node:24-slim@sha256:01d566e8d94d8c619591d78652babfccd3c6992a3dffa9ed5ab39e11cf6c70e9
|
||||
|
||||
WORKDIR /series-of-tubes
|
||||
|
||||
# Dependencies first, exactly as locked, so a change to the code reuses this layer. Every dependency is a dev one (the
|
||||
# game has none), and the servers need them all. No install scripts run.
|
||||
COPY package.json package-lock.json ./
|
||||
RUN npm ci --no-audit --no-fund --ignore-scripts && npm cache clean --force
|
||||
|
||||
# Only what the servers read: the game's source and static files, the scripts, and the harness the MCP server plays
|
||||
# through. Owned by root and read-only to the server, which runs as node.
|
||||
COPY src ./src
|
||||
COPY site ./site
|
||||
COPY scripts ./scripts
|
||||
COPY tests/harness.js ./tests/harness.js
|
||||
COPY --chmod=0755 docker/docker-entrypoint.sh /usr/local/bin/docker-entrypoint.sh
|
||||
|
||||
# --save-dir /saves needs somewhere the server may write: a volume mounted here takes this ownership.
|
||||
RUN mkdir /saves && chown node:node /saves
|
||||
VOLUME /saves
|
||||
|
||||
USER node
|
||||
ENV NPM_CONFIG_UPDATE_NOTIFIER=false
|
||||
EXPOSE 8080 7777
|
||||
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]
|
||||
55
docker/docker-entrypoint.sh
Normal file
55
docker/docker-entrypoint.sh
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
#!/usr/bin/env bash
|
||||
# Starts the container's servers (docker/Dockerfile, docs/MCP.md "In a container").
|
||||
# MCP_MODE=browser (default): the development server on :8080, with the relay a player's tab dials, and the MCP server
|
||||
# on :7777 driving that tab.
|
||||
# MCP_MODE=headless: only the MCP server, with a game of its own.
|
||||
# Everything after the image name goes to scripts/mcp.js (node scripts/mcp.js --help lists the options).
|
||||
set -uo pipefail
|
||||
cd /series-of-tubes
|
||||
|
||||
mode=${MCP_MODE:-browser}
|
||||
case "$mode" in
|
||||
browser|headless) ;;
|
||||
*) echo "[entrypoint] MCP_MODE must be browser or headless, not '$mode'" >&2; exit 1 ;;
|
||||
esac
|
||||
|
||||
extra=("$@")
|
||||
has() { local a; for a in "${extra[@]}"; do [ "$a" = "$1" ] && return 0; done; return 1; }
|
||||
|
||||
# A container must listen beyond loopback to be reachable at all; --http in the arguments overrides it.
|
||||
http=(--http 0.0.0.0:7777)
|
||||
has --http && http=()
|
||||
|
||||
# Listening beyond loopback, the MCP server would take orders from anyone who reaches the port (its Host check stops
|
||||
# browsers, not other clients), so it gets a token. None given (SOT_MCP_TOKEN or --token-file): this run makes one and
|
||||
# prints it. MCP_NO_TOKEN=1 turns that off, for a port published to 127.0.0.1 only.
|
||||
if [ -z "${SOT_MCP_TOKEN:-}" ] && ! has --token-file && [ "${MCP_NO_TOKEN:-}" != 1 ]; then
|
||||
SOT_MCP_TOKEN=$(node -e "process.stdout.write(require('node:crypto').randomBytes(24).toString('base64url'))")
|
||||
export SOT_MCP_TOKEN
|
||||
echo "[entrypoint] No SOT_MCP_TOKEN given: this run's token is $SOT_MCP_TOKEN" >&2
|
||||
echo "[entrypoint] claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header \"Authorization: Bearer $SOT_MCP_TOKEN\"" >&2
|
||||
fi
|
||||
|
||||
pids=()
|
||||
start() { "$@" & pids+=("$!"); }
|
||||
shutdown() {
|
||||
trap '' TERM INT
|
||||
kill -TERM "${pids[@]}" 2>/dev/null || true
|
||||
wait "${pids[@]}" 2>/dev/null || true
|
||||
exit "${1:-0}"
|
||||
}
|
||||
trap shutdown TERM INT
|
||||
|
||||
# node directly, not npm run: one process less, and signals reach the server.
|
||||
if [ "$mode" = browser ]; then
|
||||
start node scripts/dev.js --host 0.0.0.0 --port 8080
|
||||
start node scripts/mcp.js --browser "${http[@]}" "${extra[@]}"
|
||||
else
|
||||
start node scripts/mcp.js "${http[@]}" "${extra[@]}"
|
||||
fi
|
||||
|
||||
# One server stopping stops the container, with its status, so a restart policy can bring both back.
|
||||
status=0
|
||||
wait -n || status=$?
|
||||
echo "[entrypoint] a server exited with status $status; stopping the container" >&2
|
||||
shutdown "$status"
|
||||
|
|
@ -11,8 +11,13 @@ src/ the game page, in pieces
|
|||
i18n/en.js the English for every label → inlined at the top of the page's <script>
|
||||
styles/NN-*.css → pasted into the page's <style>, in path order
|
||||
game/NN-area/NN-*.js → pasted into the page's <script>, in path order
|
||||
agent/NN-*.js → the agent facade the MCP server drives: development page only (@include-dev)
|
||||
game/98-server-play/, styles/43-server-play.css
|
||||
→ server-run play: only in a multiplayer build's page (MP_API, assemble({mp}))
|
||||
site/ static files copied to the build as they are (dictionaries, icons, sw.js…)
|
||||
scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted
|
||||
scripts/lib/page.js the assembler: <!-- @include DIR --> → every file under src/DIR, sorted;
|
||||
<!-- @include-dev DIR --> the same, in the development page only;
|
||||
mp: true adds the multiplayer-only files (MP_ONLY), simId() is their build id
|
||||
scripts/build.js _site/ = site/ + the assembled page, version-stamped, release notes baked in
|
||||
```
|
||||
|
||||
|
|
@ -27,29 +32,36 @@ hoisted across files, and top-level statements run in path order. Find code by n
|
|||
| `10-catalog/` | Prices and gear: POP and port costs, routers (`RG`), supply chain, port slots, dark fiber systems and optics (`OPT`), reach and subsea upgrades |
|
||||
| `20-world/` | Map projection, landmasses, coastline, city coordinates (`CITY_LL`), `CITIES`, `CABLES` |
|
||||
| `30-networks/` | Other ASes (`NETS`), rival exchanges (`XIX`), the long tail, traffic shares (`NSH`) |
|
||||
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS` |
|
||||
| `40-progress/` | Customer types (`BIZ_T`), `LEVELS` and their requirements, `GOALS`; the per-save ruleset (`S.rules`, `rule()`, `PRESETS`, `chaosMul()`, `leadDays()`) |
|
||||
| `50-state.js` | The globals `S`, `R`, `UI`; `emptyR()` |
|
||||
| `60-features/` | Banks and loans, scenarios and the weekly challenge, conferences, the tutorial, traceroute, the share card, `newGame()` |
|
||||
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering inbox, peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
|
||||
| `80-simulation/` | Dijkstra, RouteScript, `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, geography pricing and latency, second sites and service |
|
||||
| `85-incidents/` | `addInc()`, DDoS and scrubbing, `fireFailure()`, `clearInc()`, `fireEvent()` |
|
||||
| `60-features/` | Moving a customer to another path (`37-customer-paths.js`), banks and loans, scenarios and the weekly challenge, puzzles and the published weekly puzzle, conferences, the tutorial, traceroute, the share card, `newGame()`, the offer trial (`autoOffer()`), standing orders (`S.ops`, `opsDay()`, run from `dayTick()`), the sales desk (`S.sales`, `salesDay()`, `salesShape()` on new offers, orbit ones through `pieSlShape()`; signing for you: `S.slAuto`, `slAutoDay()`; renewal haggles: `S.slAuto.ren`, `slRenDay()`) |
|
||||
| `70-rules/` | Formatting helpers and market rules: exchanges, PNIs, the peering desk (requests answered by policy), peering policy and snubs, DE-KICKS, sold-out routes, hot ports and the Tier 1/2/3 rank |
|
||||
| `80-simulation/` | Dijkstra, RouteScript, where a DDoS flood goes (`ddosLoad()`/`ddosAfter()`, called by `compute()`), `compute()`, monthly prices, `sanitize()`/`migrate()`, customer requirements, events, the customer lifecycle (contracts, renewals, the bandwidth market, why customers leave), geography pricing and latency, second sites and service |
|
||||
| `85-incidents/` | `addInc()`, DDoS attacks (targets, sizes, scoring, the NOC card) and scrubbing, `failureRun()`/`fireFailure()`, `clearInc()`, `fireEvent()`, the chaos monkey, cable ships (`50-cable-ships.js`: a subsea cut sends a club ship from its port along the cable routes; voyages in `S.fleet`, drawn by `96-map/88-cable-ships.js`) |
|
||||
| `88-days/` | `dayTick()`, new offers, badges, `checkGoals()` |
|
||||
| `90-actions/` | The `ACT` map, one file per area (`const ACT` in `10-interface.js`, `Object.assign(ACT,…)` in the rest), and their helpers |
|
||||
| `91-save.js`, `92-audio.js` | Save, export and import; sound effects |
|
||||
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
|
||||
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, lease swaps, the NOC dashboard, the bank, hints |
|
||||
| `93-ui/` | DOM helpers (`$`, `btn`, `morph`), the theme (light, dark or Auto: `15-theme.js`), the phone tab bar, install pitch, HUD, left panel, city and link panels, decommissioning |
|
||||
| `94-dashboard/` | Scenario and level progress, where to meet a network, customers and connections overviews, cities with no POP yet, lease swaps, the NOC dashboard and its own window for a second display (`90-noc-window.js`: this page at `?noc=<slot>`, a read-only copy of `S` and `R` over a BroadcastChannel, clicks sent back to the game; `91-noc-wall.js`: its wallboard), the bank, hints |
|
||||
| `95-modals/` | Toasts, notifications, modals, title screen, what's new, help, the link and own-cable modals |
|
||||
| `96-map/` | The canvas: resize, land and clouds, settings, level of detail, link geometry, `draw()`, the world layer, cities, input and click delegation |
|
||||
| `96-map/` | The canvas: resize, the map's colours per theme (`15-palette.js`), land and clouds, settings, level of detail, link geometry, how each tube looks, the WebGL map (the default, 2D as fallback: context, background, tubes, and the sprite atlas cities, labels and markers are drawn from, in 2D too), `draw()`, the world layer, cities, input and click delegation |
|
||||
| `99-loop.js` | `frame()` and `boot()` |
|
||||
|
||||
`src/styles/` holds the CSS the same way: base, HUD, drawers, toasts, modal, tablet, then phone.
|
||||
`src/styles/` holds the CSS the same way: base, the dark theme's colours (`05-theme.css`), HUD, drawers, toasts, modal, tablet, then phone.
|
||||
|
||||
`src/agent/` is the agent facade (`window.TUBES`): the typed commands, reads and screens the MCP server plays
|
||||
through. It is assembled into the **development page** only (`npm run dev`, the MCP server, tests that ask for it);
|
||||
the page players get never has it ([ADR 0004](adr/0004-dev-only-code.md)). Its top-level names all start with
|
||||
`api`/`API_`, and nothing outside `src/agent/` may use them. Where it must reach into the game (agent mode in the
|
||||
player's tab locks the clock and draws its badge and Settings section), the game offers `HOOKS` and the flag
|
||||
`UI.clockLocked` (`50-state.js`), empty and false in the page players get, and `runClock(dt)` (`99-loop.js`).
|
||||
|
||||
Rules for the source (checked by `tests/build.test.js` and the assembler): files are named
|
||||
`NN-lower-case.js`/`.css`, end with a newline and never close their `<script>`/`<style>`; top-level code
|
||||
may only use top-level values from earlier files; tables people add to have one entry per line, the
|
||||
id-keyed ones sorted. New features get their own file in the right folder (`edit-the-game` skill).
|
||||
Development runs on `npm run dev` (assembles on every request, reloads on save);
|
||||
`npm run page -- -o FILE` writes the assembled page.
|
||||
Development runs on `npm run dev` (assembles the development page on every request, reloads on save);
|
||||
`npm run page -- -o FILE` writes the page players get, `npm run page -- --source --dev -o FILE` the development page.
|
||||
|
||||
## Other files
|
||||
|
||||
|
|
@ -62,23 +74,54 @@ Development runs on `npm run dev` (assembles on every request, reloads on save);
|
|||
| `scripts/lib/page.js` | Assembles the page from `src/` (also from a git ref with `--ref`, for performance baselines) |
|
||||
| `scripts/lib/compile-labels.js` | Shrinks labels to short ids in the shipped page and dictionaries |
|
||||
| `scripts/build.js` | Builds `_site/` for GitHub Pages: copies `site/`, writes the page, stamps `__VERSION__`/`__BUILD_DATE__`, bakes release notes, writes `version.json` |
|
||||
| `scripts/dev.js` | `npm run dev`: development server, no dependencies |
|
||||
| `scripts/dev.js` | `npm run dev`: development server (loopback unless `--host`), serving the development page and hosting the agent relay |
|
||||
| `scripts/test.js` | `npm test`: runs every `tests/*.test.js` |
|
||||
| `scripts/release-notes.js` | Extracts a version's CHANGELOG bullets |
|
||||
| `scripts/perf-bench.js`, `perf-browser.js`, `perf-stats.js`, `perf-fixture.js` | Big-network benchmark, base vs head, headless and in Chromium as a desktop and a throttled phone, with a significance test per row (posted on every PR by `perf.yml` + `perf-comment.yml`), and the generator of its save, `tests/fixtures/big-network.json` |
|
||||
| `scripts/gpu-bench.js`, `scripts/lib/gpu-bench-client.js` | `npm run bench:gpu -- --save FILE`: the map in your own browser on your own graphics card, 2D against WebGL, scenario by scenario; the table shows in the page and in the terminal |
|
||||
| `scripts/mcp.js`, `scripts/lib/mcp-game.js`, `scripts/lib/mcp-headless.js`, `src/agent/` | The game as a local MCP server, on the official SDK over stdio or HTTP: typed tools to play, inspect and debug it from an AI client, headless or in the player's own tab ([MCP.md](MCP.md)) |
|
||||
| `scripts/agent/relay.js`, `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js` | The agent relay `npm run dev` hosts at `/agent`, and the MCP server's side of it: how a tool reaches the game in the player's tab |
|
||||
| `scripts/i18n-check.js`, `scripts/i18n-add.js`, `scripts/lib/dict.js` | Translation coverage and dictionary order; adding, renaming and removing entries |
|
||||
| `scripts/legacy/` | The splitter that made `src/` from the old `site/index.html` (and gave its text labels), and `port-branch.js`, which carries older branches over |
|
||||
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas |
|
||||
| `.github/workflows/ci.yml` | Tests and build on every push and PR |
|
||||
| `.github/workflows/auto-release.yml` | On a `package.json` version bump on `main`: test, tag, GitHub release from the CHANGELOG, start the deploy |
|
||||
| `tests/harness.js` | Loads the assembled page in jsdom with a seeded `Math.random` and a fake canvas: the players' page, or the development page with `{agent: true}`. The page's scripts run straight in the window (jsdom's parser is slow on 2 MB of script) |
|
||||
| `scripts/test.js`, `tests/durations.json` | Runs the tests, every file in its own process; splits them into parts of equal time for CI (`--plan`, `--shard`) by each file's seconds, which CI refreshes after every run on `main` |
|
||||
| `.github/workflows/ci.yml` | Tests (split over 6 runners), build and translations on every push and PR; the releases call it too, so the tests run one way everywhere |
|
||||
| `.github/workflows/auto-release.yml` | After every green CI on `main`: if `package.json` has a new version, tag the commit CI tested, publish the GitHub release from the CHANGELOG, start the deploy (`tested=true`, so it does not test again) |
|
||||
| `.github/workflows/release.yml` | Builds and deploys to GitHub Pages, the only workflow that can |
|
||||
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003) |
|
||||
| `.github/workflows/weekly-puzzle.yml` | Sunday 03:37 UTC: makes the week's puzzle, commits it to `main` (data only, no release) and starts `release.yml` for the live release tag with `weekly=true` |
|
||||
| `scripts/weekly-puzzle.js`, `site/puzzles/weekly/` | The weekly puzzle generator and its output, one `<key>.json` per week plus `index.json` (see below) |
|
||||
| `scripts/weekly-scenario.js`, `scripts/lib/scenario-bot.js`, `site/scenarios/weekly/` | The weekly scenario generator, its reference player and its output (see below) |
|
||||
| `docs/adr/` | Decisions: GitHub Pages only (0001), one page assembled at build (0002), translations by label (0003), development-only code (0004) |
|
||||
|
||||
## This fork's own files
|
||||
|
||||
This copy adds features upstream does not have. They follow the same rules as the rest of `src/`, and are listed here
|
||||
apart so that upstream's tables above merge cleanly. The multiplayer server is for self-hosted copies only: a plain
|
||||
build stays the static page described above.
|
||||
|
||||
| Path | What it is |
|
||||
| --- | --- |
|
||||
| `src/game/60-features/96-pop-standard.js` (grown from upstream's POP standard), `src/game/90-actions/88-build-standard.js`, `src/game/93-ui/59-build-standard.js` | The build standard: one target for every POP, port and fiber (`BSTD`, saved sparse in `S.popStd`), what is below it and what bringing it up costs (`bstdPlan()`, `bstdQuote()`), the sheet, "Bring everything up now" (`bstdApply`) and the intern's "Keep to the build standard" order (`std`, in `95-standing-orders.js`). The router model and the line system are picked here and nowhere else |
|
||||
| `src/game/93-ui/15-theme.js`, `src/styles/05-theme.css`, `src/game/96-map/15-palette.js` | Dark mode (#80): Light, Dark or Auto per device (`sot-theme`), set on `<html data-theme>` before the first paint; the panels' dark colours as CSS custom properties; the map's colours per theme |
|
||||
| `src/game/60-features/33-address-space.js`, `src/game/90-actions/54-address-space.js`, `src/game/94-dashboard/72-address-space.js` | IPv4 address space (#150): blocks held, bought, leased in and leased out (`S.ip4`), customers' blocks, CGNAT and its ratio; the bank's Address space section |
|
||||
| `src/game/60-features/34-ipv6-only.js`, `src/game/90-actions/55-ipv6-only.js` | IPv6-only broadband: a city's home routers swapped for 464XLAT, and the NAT64 pool next to CGNAT; the build standard's `v6` row rolls it out (`ip6Todo()`, `ip6Owed()`) |
|
||||
| `src/game/80-simulation/65-express.js`, `src/game/90-actions/87-express.js`, `src/game/93-ui/72-express.js`, `src/game/96-map/51-express-geometry.js` | Express lightpaths (#58): a link of kind `xp` from A to C over a chain of ROADM fibers, passing the cities between as light; its rules, actions, panels, the link window's Express tab, and how the map draws it |
|
||||
| `src/game/10-catalog/75-satellites.js`, `src/game/60-features/45-teleports.js`, `src/game/90-actions/87-teleports.js`, `src/game/93-ui/72-teleport-panels.js` | Satellites (#83): teleports at POPs (`p.tele`) and rented GEO and MEO circuits (links of kind `sat`): the birds and their reach, the rules and money, the actions and the panels |
|
||||
| `src/game/10-catalog/76-wisp-zones.js`, `src/game/60-features/46-wisp-zones.js`, `src/game/90-actions/87-wisp-zones.js`, `src/game/93-ui/73-wisp-panels.js` | Island Wi-Fi (#83): zones of outer islands (`WISP`), each a pool of homes at its city's POP (`p.wisp`) whose Gbps join the city's demand; their backhaul from the city's teleport (GEO, MEO, Starblink LEO) or a spur cable, the spur cut (incident `wspur`), the money, the actions and the panels |
|
||||
| `src/game/60-features/89-multiplayer.js`, `src/game/95-modals/48-multiplayer.js`, `src/game/90-actions/92-multiplayer.js`, `src/styles/41-multiplayer.css` | Multiplayer, only in a copy built with `MP_API` ([MULTIPLAYER.md](MULTIPLAYER.md)): `S.mp`, saves and cards sent to the session server, the `#mp=` link; the title screen's door, the session panel and the HUD chip; `srvOn()`, false until server-run play is switched on |
|
||||
| `src/game/60-features/81-late-joiners.js` | Late joiners of a server session: a network begins on the session's date (`S.day0`; `netAge()` counts its first-days rules from there), with a hardware top-up and a year of home broadband matched (`R.rev.late`); the Goals card, the bank section and the city pitch. Dormant until the host passes a start day (T3) |
|
||||
| `src/game/98-server-play/`, `src/styles/43-server-play.css` | The page's side of server-run play (T4), only in a multiplayer build's page; a comment so far ([plans/server-run.md](plans/server-run.md)) |
|
||||
| `scripts/mp-server.js`, `scripts/lib/mp.js` | The multiplayer session server: the command line and the built site, and the API with its storage. `npm run dev -- --mp` mounts the API in the development server |
|
||||
| `scripts/lib/mp-sim-acts.js` | Server-run play's act tables (SEND, ASK, VOTE, LOCAL, CONFIRM, DRAFTS, TEXT, WINDOWS…) and the envelope check every request passes |
|
||||
| `scripts/lib/mp-sim-engine.js`, `scripts/lib/mp-sim-worker.js`, `scripts/lib/mp-sim-realm.js` | The server-run engine (merged, not wired in yet): worker threads, each holding a vm realm per network that runs the plain page's game, behind the promise API the session host will use ([plans/server-run.md](plans/server-run.md)) |
|
||||
| `tests/lib/mp-sim-*.js`, `tests/fixtures/mp-sim/` | Server-run play's contracts for the tests: the shape checker, the fake engine, the fixtures and their generator, the button crawl, and the player that plays a realm against a page |
|
||||
| `docs/plans/next-session.md`, `server-run.md`, `multiplayer-phase2.md` | What is left and what waits for a decision; the server-run design and its status; the phase 2 design (on hold) |
|
||||
|
||||
## Globals
|
||||
|
||||
- **`S`**: the whole saved game (one JSON object). Cash, day, POPs, links, transit,
|
||||
IX ports, PNIs, caches, customers (`biz`), offers, incidents (`inc`), live events
|
||||
(`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1`.
|
||||
(`ev`), stats, settings. Saved to `localStorage` key `sot-save-v1:<slot>` (one per network, see below).
|
||||
- **`R`**: results of the last `compute()`: per-link load, per-exit use, served and
|
||||
demanded traffic, reach, costs and revenue. Never saved; always rebuilt.
|
||||
- **`UI`**: view state (selection, open tabs, speed, confirmations). Not game state.
|
||||
|
|
@ -88,17 +131,44 @@ Lookup tables built at load: `CITY[id]`, `NET[id]`, `CABLE`, `FAB`, `BIZ_T`, `RE
|
|||
|
||||
## The life of a day
|
||||
|
||||
`frame()` (requestAnimationFrame) accumulates time; every `DAY_MS × speed` it calls
|
||||
`dayTick()`, at most four times per frame, each inside a try/catch so one bad tick
|
||||
never freezes the game.
|
||||
`frame()` (requestAnimationFrame) accumulates time (`runClock()`); every `DAY_MS × speed` it starts a day, inside a
|
||||
try/catch so one bad tick never freezes the game. In play the day runs with the route worker (below), one day in flight
|
||||
at a time: the clock waits for the day, never the other way round, so a machine that cannot keep up at ×8 plays slower
|
||||
instead of freezing to catch up. Without a worker it calls `dayTick()`, at most four times per frame.
|
||||
|
||||
`dayTick()`:
|
||||
A day is a generator, `dayRun()` (`src/game/88-days/10-day-tick.js`): `dayPreRun()` (the world moves on), then
|
||||
`dayPost()`, and the intern's shift (`opsRun()`) and the sales desk's (`slAutoRun()`) inside it are generators too. Each
|
||||
`yield` is a `compute()` the day needs before it goes on: the day's own routing, then a recompute after failures and
|
||||
events, and after the intern's jobs. `dayTick()` (tests, the fallback) answers each one with `compute()` on the spot
|
||||
(`dayGo()`); in play the route worker answers them. `yield DAY_REST` is not a routing, only a place where a long day may
|
||||
let a frame through. Same steps, same random numbers either way: routing draws none. Nothing of a day routes on the page:
|
||||
a failure (`failureRun()`; `fireFailure()` plays one at once through `runNow()`), a DDoS and Auto-RTBH (`ddosNewsRun()`),
|
||||
the chaos monkey's snip (`mkSnipRun()`), an event's cut (`eventRun()`: its routing is deferred to the next yield) and the
|
||||
sales desk's trials (a `{trial}` yield the worker answers with yes or no, `offerTrial()`) are all steps. The intern's
|
||||
orders are generators too, with a rest after each job. `UI.tick` (what the day itself announces, which quiet
|
||||
notifications may keep to the NOC log) is set around every step (`dayStep()`), on both sides of the worker.
|
||||
A big autosave is packed, turned into text and compressed in the worker (`rwSave()`), the page only writes it. The
|
||||
diverse-paths map and the latency floors new offers need are worked out a millisecond a frame ahead (`diversityWarm()`,
|
||||
`latWarm()`). A rest waits for the next frame only when none was drawn just now (`rwLater()`).
|
||||
|
||||
The daily mood check asks "a path without subsea" for each customer that wants one: during that loop the land-connected
|
||||
islands are worked out once (`TERR`, `terrIslands()`), and two cities have a land path when they share one.
|
||||
|
||||
The day:
|
||||
|
||||
1. Advances `S.day`, runs scheduled world events (conferences, IX price wars, licences).
|
||||
2. Runs `compute()` to route today's traffic.
|
||||
3. Records history for 95th-percentile billing, stats and streaks.
|
||||
4. Rolls failures (`fireFailure()`) and events (`fireEvent()`) when their timers run out,
|
||||
4. Rolls failures (`failureRun()`) and events (`fireEvent()`) when their timers run out,
|
||||
and expires incidents.
|
||||
Then the NOC intern's standing orders (`opsRun()`, or `opsDay()` in one go), if one is hired: each order clicks the
|
||||
same `ACT` actions a player would, muted, within its monthly budget, and the shift routes again (a yield) before
|
||||
decommissioning, which reads today's loads, and at the end, each only if a job changed the network. An order that
|
||||
throws is paused; the day goes on. The NOC gets one notice a week. The orders plan for every POP each day, so what
|
||||
they count is counted for all POPs in one pass (`portsAt()`, `cachePlan()`, `pniFlows()`, `pniBatch()`), never one
|
||||
pass over the network per POP.
|
||||
Then the sales desk (`slAutoDay()`), if someone runs sales and the player lets them sign: deals are Sales', never
|
||||
the intern's. Each salesperson signs in their own style (a routing trial a day, or the shark's sign-everything).
|
||||
5. Updates customer mood, churn and new offers; IX members join; loans tick.
|
||||
6. Every 30 days: bills the month (revenue minus costs) and checks for bankruptcy.
|
||||
7. Checks goals, level, badges and scenario end conditions.
|
||||
|
|
@ -110,15 +180,24 @@ never freezes the game.
|
|||
(`S.pairMet`) and sets the edge's weight; Dijkstra gives shortest paths from each POP.
|
||||
Links on standby (`l.standby`) add their capacity to the edge, but when loads are
|
||||
handed back to links the active ones fill first and standby links take the rest.
|
||||
2. Builds the exit list `E`: embedded caches (rank 0), PNIs (1), IX ports (2),
|
||||
2. Builds the exit list `E`: embedded caches (rank 0), PNIs and IX ports (2, both peering),
|
||||
transit (3). Each exit has a capacity, the networks it can reach (`ok(net)`) and an
|
||||
egress preference (`high`, `normal`, `low` = backup only).
|
||||
egress preference (`high`, `normal`, `low` = backup only). A transit port can also be set to
|
||||
carry (`t.carry`): see step 4.
|
||||
3. Builds flows: for every POP, its demand (eyeballs and customers) split across
|
||||
destination networks by their traffic share (`NSH`, with regional variants for
|
||||
China, Russia and Korea). Incidents can add junk flows or scale demand.
|
||||
4. Routes flows rank by rank: the nearest usable exit first, ECMP across equal exits,
|
||||
consuming link, router (`nodeCap`) and exit capacity. With Auto-TE, overflow spills
|
||||
onto alternate paths; RouteScript rules (`teRules()`) can prefer, avoid, cap, drain
|
||||
China, Russia and Korea), localised per city: the networks that sell to homes split their part by where their users
|
||||
live (`locSh()`, `30-networks/45-home-markets.js`, #48). Incidents can add junk flows or scale demand.
|
||||
4. Routes flows rank by rank: the nearest usable exit first, ECMP across equal exits (a PNI goes before an
|
||||
IX port at the same distance: `PNI_TIE`, #298),
|
||||
consuming link, router (`nodeCap`) and exit capacity. A carrier's own transit port also
|
||||
goes first, before plain transit, for traffic bound for that carrier or for a network that buys
|
||||
transit from it (`25-direct-egress.js`: the shorter AS path): always at its own POP, and from every
|
||||
POP when the port is set to carry. Such a port is still an ordinary transit exit for the other
|
||||
POPs. Backup, RouteScript and Auto-TE rules keep their say, and so does a Prefer-marked port at its own POP (the other
|
||||
POPs keep the rule). With Auto-TE, overflow spills
|
||||
onto alternate paths (spill tiers, `spill at 80% within 10 ms`, first try the fastest detour under the line within
|
||||
that budget: `tiers()` in `29-route-core.js`); RouteScript rules (`teRules()`) can prefer, avoid, cap, drain
|
||||
or blackhole.
|
||||
5. Layer-2 customers (L2VPN, SD-WAN, waves) are carved out of link capacity first.
|
||||
6. Totals costs (`R.cost`) and revenue (`R.rev`) per month.
|
||||
|
|
@ -127,8 +206,64 @@ It runs every day and after every action, so it is built for big networks: the g
|
|||
indices (`CIDX`), each exit is asked once per network what it can reach, and `R.ef` (what crosses each
|
||||
link) is only put together for a link when something reads it.
|
||||
|
||||
What follows from the network's shape alone is kept from one call to the next (`29-route-cache.js`): the shortest
|
||||
paths from every POP, and who reaches whom with each network's exit lists. Each has a key made of everything it is
|
||||
built from (the live graph with its weights; every exit with what it reaches and how it is preferred, RouteScript and
|
||||
the events that move routes), so most days, when only demand changes, they are reused, and any other change rebuilds
|
||||
them. Only indices are kept: exits, lists and paths are made fresh every call, because routing writes on them.
|
||||
`tests/route-cache.test.js` checks the keys, and the equivalence tests route with and without the kept tables.
|
||||
`scripts/route-fuzz.js` plays hundreds of random seeded games on main's page and this checkout's at once, comparing all
|
||||
of R and S after every move and day, with the kept tables and without (`tests/route-fuzz.test.js` plays a few).
|
||||
|
||||
Each loop of `compute()` runs in a function of its own (the money is `computeMoney()`). V8 optimises a small function
|
||||
quickly and keeps it; `compute()` as one 33 KB function never stayed optimised: it ran in baseline code, boxing every
|
||||
number, and was compiled again and again in the background only to be thrown away, which cost more CPU than the routing
|
||||
itself. Keep it that way: a new loop goes in a function.
|
||||
|
||||
The routing core, the loops that place every flow on an exit (`rankPass`, `directPass`, `sendGroup`, `send`, `push`,
|
||||
`carry`, `altPath`), lives in `ROUTE` (`29-route-core.js`), made once at load: `compute()` hands it the day's state
|
||||
(`ROUTE.nodes()`, `ROUTE.run()`). Made inside `compute()`, as they were, they were new functions every call, and V8 threw
|
||||
away the code it had compiled for the old ones. The core reads exits by number from typed columns (`USED`, `CAPX`, `CIX`,
|
||||
`HPX`, `VISX`), and each list as an object of one shape (`lx()`). For each list and source city, the route cache also
|
||||
keeps the list in the order routing tries it (`xOrder()`: by preference, then distance, a stable sort): on a day the cache
|
||||
is used, a flow's first group is where that order starts, past the exits that filled up, instead of a scan of the whole
|
||||
list, and what is left needs no sort. Auto-TE marks the pairs that have no detour (`TEF`), the answer to most of its
|
||||
asks. `tests/day-steps.test.js` and the routing equivalence tests hold all this to the same results.
|
||||
|
||||
Served share per city (`sfOf`) drives eyeball revenue and customer mood.
|
||||
|
||||
## Routing in a worker
|
||||
|
||||
During play, each day's `compute()` runs off the main thread (`src/game/80-simulation/28-route-worker.js`), so a big
|
||||
network does not freeze the page once a day.
|
||||
|
||||
- **Built from the page itself.** The worker is the page's own inline game script (`document.currentScript.textContent`)
|
||||
run again from a Blob URL, after a short prelude of inert stand-ins for `document`, storage and the other DOM globals,
|
||||
and the player's dictionary. Nothing is fetched: GitHub Pages still serves one page, and a release cannot mismatch.
|
||||
In the worker `RW_IN` is true and `boot()` never runs; the catalogs are rebuilt by the same top-level code.
|
||||
- **The day in steps.** In play, `frame()` calls `rwDay()`, which runs `dayRun()` (see "The life of a day") with
|
||||
`rwGo()`: the steps run on the page up to a yield, then S and what routing reads of yesterday's R (`R.load`,
|
||||
`R.l2route`, `R.efg`) are posted, and the day goes on in `rwDone()` when R comes back. The next day waits until the
|
||||
last step has run. So a day sees exactly the routing it would have had in one go: same results, same random numbers.
|
||||
At a `DAY_REST`, a day that has run `RW.budget` ms (half a frame: 3 to 8, or up to 32 on a device slower than 50 frames a second) already goes on after the next frame
|
||||
(`RW.later`, `rwLater()`), so a phone gets its frames between the steps of a big network's day. Half a day is never
|
||||
saved; nothing else starts meanwhile. `tests/day-steps.test.js` plays a second page as the worker and compares every
|
||||
day with `dayTick()`.
|
||||
- **What crosses.** `R.ef` and `R.fl` are lazy getters; their pieces (`R.efp`, `R.flc`) travel instead, typed arrays
|
||||
transferred, and `efBuild()`/`flDefine()` (in `30-compute.js`) rebuild the same lazy R on the page. What crossed each
|
||||
link (`R.efp.L`) crosses as typed arrays with each exit key once (`rwLOut()`), and the page decodes a link only when
|
||||
something reads it (`rwLIn()`). Two parts are not sent again when they would be the same: `R.egDesc` comes back as 0
|
||||
when it is the last one key for key (the page keeps `RW.desc`), and `R.efg` is not posted back while R is the worker's
|
||||
own last answer (`RW.wR`; the worker keeps it in `RW.last`). Both sides read every message in order, so they always
|
||||
hold the same last one; `tests/day-steps.test.js` plays a second page as the worker and checks it all.
|
||||
- **Actions mid-day.** Every `compute()` bumps `RW.gen`. If an action routed while a day was in flight, the worker's
|
||||
answer is stale: it is dropped and the day ends with the action's R.
|
||||
- **Fallbacks.** Tests (`__TUBES_TEST__`, and jsdom has no Worker), `window.__TUBES_SYNC__`, a browser without workers, a
|
||||
post that fails or a worker that errors take the synchronous path (`rwKill()` routes the day in flight on the page).
|
||||
- **Still on the main thread**, because the caller reads R right away: actions (`after()`), loading a game, failures and
|
||||
RouteScript what-ifs and the link panel's cut check. Everything a day routes (failures, events, DDoS, the chaos monkey,
|
||||
the intern's shift, the sales desk's trials) is a yield of the day, so it goes to the worker.
|
||||
|
||||
## Actions and rendering
|
||||
|
||||
- Player actions live in `ACT`. Buttons render as `btn(label, act, args, cls, disabled)`
|
||||
|
|
@ -141,14 +276,67 @@ Served share per city (`sfOf`) drives eyeball revenue and customer mood.
|
|||
controlled by `renderTabbar()`.
|
||||
- These panels and the dashboard are rebuilt as HTML every tick and written with `morph()`, which
|
||||
patches only what changed. Buttons whose action changed are replaced, so taps stay safe (#44).
|
||||
- The map is a canvas drawn every frame by `draw()`. Zoomed out (`lodFar()`) it uses
|
||||
a simplified style; parallel waves are grouped by `linkGroups()`.
|
||||
- The map is a canvas drawn by `draw()` from `frame()`. Zoomed out (`lodFar()`) it uses
|
||||
a simplified style; parallel waves are grouped by `linkGroups()`. `mapStill()` decides whether a frame is drawn:
|
||||
when nothing changed (paused, animations off) it is not, except once a second; when only the animation clock moved
|
||||
(packets, waves, clouds, floaters) the map is ambient and drawn at most 30 times a second; anything else that moves
|
||||
(camera, pointer, selection, the network) gets every frame (`tests/frame-pacing.test.js`).
|
||||
|
||||
## The weekly puzzle
|
||||
|
||||
A puzzle week runs from Sunday 06:00 Berlin time to the next Sunday 06:00, and is named after the ISO week of
|
||||
its Monday (the week starting Sunday 1 November 2026 is `2026-W45`); `pzWeekKey()` and `pzWeekStart()` in
|
||||
`src/game/60-features/93-puzzles-weekly.js` handle summer time and the year boundary.
|
||||
|
||||
Every Sunday `weekly-puzzle.yml` runs `scripts/weekly-puzzle.js`, which loads the real game headless, picks a
|
||||
theme the last three weeks did not have (region tour, ring, detour around a hub, ocean crossing, island hopping,
|
||||
latency sprint) and cities the last four weeks did not use, gives them traffic (content in the first city, eyeballs
|
||||
in the others, a circuit with a latency cap for a sprint), searches for the cheapest topology that connects them and
|
||||
the cheapest one that survives any single cut (a whole cable, or a trench), then sizes both with the game's own
|
||||
routing (`scripts/lib/puzzle-solver.js`: links and routers big enough for every flow, after any cut too, then as
|
||||
small as they go). The budget sits just above that N-1 build. Both references are judged by the game's own star
|
||||
code and must earn one and three stars, or the puzzle is thrown away. The file holds only ids, numbers and
|
||||
translation labels with their fill-ins
|
||||
(`{"v":2,"key","theme","cities","src","dem","via","avoid","budget","twist","name":{"l","p"},"joke":{"l","p"},"ref","rev"?}`).
|
||||
`--check` re-validates every file the way the game does.
|
||||
|
||||
The game fetches `puzzles/weekly/<key>.json` (relative, same origin) only when the Puzzles list opens, and checks
|
||||
it field by field (`pzWkValid()`): known fields, playable cities, labels from the theme's own list, sane numbers.
|
||||
When it is missing, offline or wrong, the seeded weekly (`pzWeekly()`) stands in, so the weekly puzzle always
|
||||
works. The service worker fetches these files network-first and keeps a copy for offline play.
|
||||
|
||||
The weekly ships without a release: the workflow commits only `site/puzzles/weekly/` to `main` (no version bump,
|
||||
so `auto-release.yml` stays quiet) and starts `release.yml` from the live release's tag with `weekly=true`, which
|
||||
rebuilds that exact release with every weekly file from `main` and deploys it. Every release build takes the
|
||||
weekly files from `main` too, so no deploy ever drops a published week.
|
||||
|
||||
The weekly scenario is its twin, in the same weeks and the same workflow run: `scripts/weekly-scenario.js` writes
|
||||
`site/scenarios/weekly/<key>.json`. A template (plain data in the script) picks a theme, a home city, rules from the
|
||||
scenario vocabulary (`scnRule` keys, `WEEK_MODS`) and a goal type with parameters; each goal type (`WS_GOALS` in
|
||||
`src/game/60-features/94-scenarios-weekly.js`) is implemented once in the game, with its progress card. A reference
|
||||
player (`scripts/lib/scenario-bot.js`) plays it through `ACT`, seeded with the scenario's seed; the goal's number is
|
||||
calibrated from that run, the scenario must not be won on day 0, the reference must win with a tenth of the days to
|
||||
spare, and its finishing day is the par. The file keeps the reference plan (`ref`), which `--check` replays. The game
|
||||
fetches the file when the Scenarios list opens, checks it with `wsValid()` (again in `sanitize()` on load), and falls
|
||||
back to the in-browser `weekly()`.
|
||||
|
||||
## Saves, imports and migration
|
||||
|
||||
- `save()` writes `S` to localStorage every few seconds and after actions.
|
||||
- `save()` writes `S` to localStorage every few seconds and after actions, into this window's slot
|
||||
(`UI.slot`, `src/game/91-slots.js`): `sot-save-v1:<id>`, plain JSON or `gz:`-compressed above a million
|
||||
characters, with a stamp `sv:{seq,at}` appended. Then the index `sot-slots` (name, ASN, preset, day, tier,
|
||||
cash, last played, size, seq) is updated; the title screen lists networks from the index alone. A save whose text is
|
||||
the one the slot already holds (`SLOT.txt`: a paused game, nothing changed) is not written again, unless the page is
|
||||
closing: on a big network the storage write costs more than making the text.
|
||||
- Each tab keeps its slot in `sessionStorage['sot-slot']`. One window per slot: a Web Lock
|
||||
(`sot-slot:<id>`) where supported, plus a heartbeat `sot-open:<id>`; BroadcastChannel `sot-slots` asks
|
||||
another window to hand over, and the `storage` event stops a window whose slot was saved newer elsewhere
|
||||
(higher seq) or deleted. A window never writes a slot whose index seq is newer than its own.
|
||||
- The single save of older versions (`sot-save-v1`) is copied to slot `main` and read back before the
|
||||
index lists it; the old key is removed only by that slot's next successful save.
|
||||
- `boot()` loads the save through `migrate()` → `sanitize()`. If loading throws, the
|
||||
damaged save is kept under `sot-save-broken` and the player starts fresh.
|
||||
slot is kept and marked damaged in the index (it can still be exported or deleted).
|
||||
- Puzzles never write a slot; while one runs, `save()` writes the network set aside (`UI.pzKeep`).
|
||||
- `sanitize(s)` is the gate for all untrusted state (saves and imported files): it
|
||||
drops unknown ids, clamps numbers, repairs references and fills defaults. Every new
|
||||
field in `S` needs a line there.
|
||||
|
|
@ -182,5 +370,5 @@ assert.deepEqual(errors, []);
|
|||
```
|
||||
|
||||
`ev()` runs code inside the page. To force a specific random failure, patch the
|
||||
picker, e.g. evaluate `fireFailure` with `.replace('const e=pick(opts);', "const e='x';")`.
|
||||
picker, e.g. evaluate `failureRun` with a `.replace(…)` and play it with `runNow(…)` (it is a generator).
|
||||
Use `window.__reseed(n)` to reset the random sequence mid-test.
|
||||
|
|
|
|||
238
docs/MCP.md
Normal file
238
docs/MCP.md
Normal file
|
|
@ -0,0 +1,238 @@
|
|||
# Series of Tubes as an MCP server
|
||||
|
||||
`scripts/mcp.js` lets an AI client (Claude Code, Claude Desktop, any MCP client) play, inspect and debug the game
|
||||
through typed tools, over stdio or HTTP, in one of two sessions:
|
||||
|
||||
- **Headless** (`node scripts/mcp.js`): a game of its own, loaded from this checkout's `src/` the way the tests load
|
||||
it: one page in jsdom, seeded, with no animation loop. For playing and debugging when nobody is watching: fresh
|
||||
starts, bug-report saves, scenarios and puzzles, and fast-forwarding time.
|
||||
- **Browser** (`node scripts/mcp.js --browser`): the game in your own browser tab, through a local relay, so you can
|
||||
watch and take part. Toasts fire, panels open, the map moves. The game, its saves, its settings and any window you
|
||||
open stay yours.
|
||||
|
||||
Both run the same tools on the same code: the agent facade in the game page (`src/agent/`, `window.TUBES`), which does
|
||||
nothing until a tool calls it. It is part of the development page only, never of the page players get
|
||||
([ADR 0004](adr/0004-dev-only-code.md)). Nothing is hosted, so this stays within
|
||||
[ADR 0001](adr/0001-github-pages-only.md): it is a local tool, like `npm run dev`. On the public site there is no relay
|
||||
and no agent mode. The protocol is the official SDK's (`@modelcontextprotocol/server`, a dev dependency).
|
||||
|
||||
## Set it up
|
||||
|
||||
### Headless
|
||||
|
||||
```sh
|
||||
npm ci
|
||||
claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
|
||||
```
|
||||
|
||||
Other clients take the same command (`node /path/to/seriesoftubes/scripts/mcp.js`) in their MCP server settings.
|
||||
Use `node` directly: `npm run` prints a line of its own to stdout, which is the protocol channel.
|
||||
|
||||
A game is always loaded: a fresh On-call game in Frankfurt until you start or load another. Every game is seeded, so
|
||||
the same seed and the same moves give the same game. `--seed N` sets the first game's seed.
|
||||
|
||||
### Browser
|
||||
|
||||
1. `npm run dev`. It hosts the agent relay on its own port, at `/agent`.
|
||||
2. Open the game at `http://localhost:8080`, start or load the game you want the agent to play, and turn on
|
||||
**Settings → Agent API → "Let an AI agent drive this game"**. That connects the page to the relay; there are no
|
||||
tokens and no ports to configure. The section only exists while the page is served over plain `http://` to an
|
||||
address (`localhost`, `127.0.0.1`, or the IP the dev server is bound to).
|
||||
3. Point your MCP client at `node /path/to/seriesoftubes/scripts/mcp.js --browser` (add `--relay-port N` if the dev
|
||||
server runs on another port, `--relay-host ADDR` if it is bound elsewhere).
|
||||
|
||||
The order does not matter. The server answers the MCP handshake at once, then waits up to 90 s (`--page-wait-ms`) for
|
||||
a page on the relay. When one connects it checks that the page was built from the code on disk, and over stdio stops
|
||||
with a message if the tab is older (reload it). A call the page has not answered after 30 s comes back as an error
|
||||
(`--call-ms`); a page that goes away answers its calls at once. One tab drives the relay at a time: the newest one wins.
|
||||
|
||||
`npm run dev` binds loopback by default. `npm run dev -- --host 0.0.0.0` (to try the game on a phone, say) binds every
|
||||
interface, the relay with it, and says so: then anything that can reach the address can drive a game whose player
|
||||
turned agent mode on. Whatever the bind address, the relay only takes connections made to an IP address or
|
||||
`localhost`, and refuses a page from another site, so a website in your browser cannot reach it.
|
||||
|
||||
### Over HTTP
|
||||
|
||||
For a client that connects to a running server instead of starting one (another process, a container, another
|
||||
machine), serve Streamable HTTP:
|
||||
|
||||
```sh
|
||||
node scripts/mcp.js --http 7777 # http://127.0.0.1:7777/mcp, this machine only
|
||||
claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp
|
||||
```
|
||||
|
||||
- **Where it listens is your choice.** `--http 7777` binds loopback. `--http 0.0.0.0:7777` (or one address) lets
|
||||
other machines in, and then anyone who can reach it can play; the server says so when it starts.
|
||||
- **Token (optional).** With `SOT_MCP_TOKEN=…` or `--token-file FILE`, every request needs
|
||||
`Authorization: Bearer <token>` (`claude mcp add … --header "Authorization: Bearer …"`). Without a token, a server
|
||||
bound beyond loopback warns. There is no TLS: beyond a network you trust, use `ssh -L 7777:127.0.0.1:7777` or a
|
||||
TLS proxy in front.
|
||||
- **Always checked, wherever it listens:** the `Host` must be an address of this machine (or a name given with
|
||||
`--allow-host`), which stops DNS rebinding, and a request from a web page (an `Origin` other than localhost) is
|
||||
refused, so no website can drive the game through your browser.
|
||||
- **Files:** over HTTP, `load_save` and `export_save` take and give JSON only. `--save-dir DIR` lets them read and
|
||||
write files under `DIR` and nowhere else (symbolic links that lead out are refused).
|
||||
- **One game for every client.** Calls run one at a time, in the order they arrive; `new_game` or `load_save` from
|
||||
any client replaces the game for all of them.
|
||||
- **Either session.** `--http` works headless and with `--browser` alike: then a client elsewhere drives the game
|
||||
in the player's tab, while the relay stays where `npm run dev` put it.
|
||||
|
||||
### In a container
|
||||
|
||||
Every release publishes a multi-arch (amd64/arm64) image at `ghcr.io/fjaeckel/seriesoftubes:<version>`
|
||||
(`docker.yml`, dispatched by the release; pre-releases too). There is no `latest` and no image per commit: pick a
|
||||
version from the [releases](https://github.com/fjaeckel/seriesoftubes/releases). It holds the MCP server and the
|
||||
development server, nothing else from the repository, and runs as `node`, not root. It is published to GHCR only; the
|
||||
game itself is served from GitHub Pages and nowhere else.
|
||||
|
||||
- **`MCP_MODE=browser`** (the default) serves the development page on 8080, with the relay, and runs the MCP server on
|
||||
7777 driving that tab. **`MCP_MODE=headless`** runs only the MCP server, with a game of its own.
|
||||
- **Options** go after the image name, to `scripts/mcp.js` (`node scripts/mcp.js --help`). The MCP server listens on
|
||||
`0.0.0.0:7777` inside the container, since loopback there is unreachable; pass your own `--http` to change it.
|
||||
- **A token, always.** The Host check stops browsers, not other clients, so a published port without a token is open to
|
||||
anyone who reaches it. Give one with `-e SOT_MCP_TOKEN=…` (or `--token-file`); without one the container makes a
|
||||
token for this run and prints it, with the `claude mcp add` line to use it. `MCP_NO_TOKEN=1` turns that off.
|
||||
- **Publish the ports to loopback** (`-p 127.0.0.1:7777:7777`), as below. A bare `-p 7777:7777` listens on every
|
||||
interface of the host, and Docker's rules go around ufw and firewalld. To reach it from elsewhere, keep the token,
|
||||
add `--allow-host NAME` for the name or address clients use (requests naming the host's address are refused
|
||||
otherwise, since that is not an address inside the container), and put TLS in front.
|
||||
- **The relay has no token** (as with `npm run dev -- --host`): in browser mode, anyone who reaches port 8080 can drive
|
||||
a game whose player turned agent mode on. Publish it to loopback too.
|
||||
|
||||
```sh
|
||||
V=2.10.1 # a release
|
||||
|
||||
# Headless, with your own token
|
||||
docker run -d --name sot -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret \
|
||||
ghcr.io/fjaeckel/seriesoftubes:$V --clock realtime --pace 60000
|
||||
claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp --header "Authorization: Bearer secret"
|
||||
|
||||
# The browser session: open http://localhost:8080, then Settings → Agent API. The token is in `docker logs sot`.
|
||||
docker run -d --name sot -p 127.0.0.1:8080:8080 -p 127.0.0.1:7777:7777 ghcr.io/fjaeckel/seriesoftubes:$V
|
||||
```
|
||||
|
||||
`load_save` and `export_save` take JSON only unless the server runs with `--save-dir`; the image has `/saves` for it,
|
||||
owned by the server's user, so mount a volume there:
|
||||
|
||||
```sh
|
||||
docker run -d -p 127.0.0.1:7777:7777 -e MCP_MODE=headless -e SOT_MCP_TOKEN=secret -v sot-saves:/saves \
|
||||
ghcr.io/fjaeckel/seriesoftubes:$V --save-dir /saves
|
||||
```
|
||||
|
||||
The image's Node base is pinned by digest, its dependencies by the lockfile, and every workflow action by commit;
|
||||
Dependabot (`.github/dependabot.yml`) keeps them current. Pull requests that touch the image build it and try both modes
|
||||
without publishing.
|
||||
|
||||
## The clock
|
||||
|
||||
Every session has one of two clocks, and `schema` (section `mode`) says which:
|
||||
|
||||
- **The agent's clock**: nothing happens between calls. `advance {days}` runs the days, one `dayTick()` each, as the
|
||||
game loop runs them, and stops early when a window asks a question or the network goes bankrupt. Headless, this is
|
||||
the default. In the browser the player picks it in Settings ("The agent moves it"), and the days run on screen.
|
||||
- **A running clock**: one simulated day passes every so often whatever the agent does, and nothing can stop it, not
|
||||
even an open window. The agent decides while it runs, and `wait {days}` returns once that many days have passed (or
|
||||
earlier, when a window asks a question). Headless: `--clock realtime --pace MS` (default 60000 ms a day). In the
|
||||
browser the player picks a pace from 30 s to 5 min a day; the clock holds while no tool is connected.
|
||||
|
||||
`advance` with a running clock and `wait` with the agent's are errors that say which one to use.
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | What it does |
|
||||
|---|---|
|
||||
| `new_game` | Headless only. Start a network in any home city with a preset (`soft` for Best Effort, `freeze`, `oncall`, `bgp`, `sandbox`), a seed, your own ASN, and the sandbox's chaos dial |
|
||||
| `load_save`, `export_save` | Headless only. Load an exported save (a path or JSON text, migrated as the game does) or write one the real game can import |
|
||||
| `status` | Date, cash, revenue and costs by kind, level, tier and why it is not Tier 1, the goal, traffic, reach, POPs, incidents |
|
||||
| `advance`, `wait` | Move time with the agent's clock, or let it pass with a running one. They return the log, new incidents and cash; `advance` also the time each day took |
|
||||
| `network`, `city`, `find` | The world: policies and what a network asks for, its PoPs, cone and price; a city's exchanges, transit sellers, cables; search by name, id or ASN |
|
||||
| `traceroute` | The looking glass: which exit wins to a network and why, with the AS path |
|
||||
| `peering_check` | Would this network peer with you over a PNI or at an exchange, and the game's reason if not |
|
||||
| `hot_spots` | The fullest links, transit ports and PNIs, the transit bill by carrier, and the biggest traffic still on transit with the way off it |
|
||||
| `schema` | The typed contract: the session (`mode`: headless or browser, the clock, what is held back), every action with its arguments, their domains and what it does; what is not available and why; a field-by-field reference of `state` and `results` |
|
||||
| `catalog` | The reference tables the arguments point at (cities, networks, ports, optics, interns…), plus the conference calendar with its keys and the RouteScript recipes with their scripts |
|
||||
| `state`, `results`, `ui` | The saved game itself (`S`), the last traffic computation (`R`) and the view state, as JSON, whole or by path (`pops.fra`, `loanOffers`, `links.<id>`) |
|
||||
| `actions`, `act` | Every action with its arguments, and running one |
|
||||
| `screen`, `panel`, `click`, `open_link` | The game's own windows, panels, left drawer, NOC dashboard, bank and puzzle box as text with numbered buttons; press one; open a link's build window |
|
||||
|
||||
## Acting
|
||||
|
||||
`act` checks the arguments against `schema` first: a wrong id or value is an error that says what would fit, and
|
||||
nothing runs. The action then runs as the game runs it, with what a player would type and pick filled in: a rename,
|
||||
a RouteScript, a custom metric, the route and size of a link, the source and line system of dark fiber, the design
|
||||
of a cable, the POPs to close. Confirmations are given, so `rmLink` removes the link in one call. The result says
|
||||
what happened:
|
||||
|
||||
| `outcome` | Meaning |
|
||||
|---|---|
|
||||
| `applied` | Something changed. `charged` is what the game's money gate took; `cashChange` also counts goal rewards |
|
||||
| `rejected` | The game said no; `toasts` has its words |
|
||||
| `no_effect` | Nothing changed and nothing was said: usually a wrong id or a precondition |
|
||||
| `shown` | A view or a draft: only the screen changed |
|
||||
| `decision` | A window asks a question (a De-Kicks quote, a retention offer). Answer with one of `decision.options` or `closeModal`; other game commands wait until then |
|
||||
| `quote` | With `dryRun`: `{setup, monthly, days, blocked}`, priced with the game's own helpers. Nothing happens, and no dice are rolled |
|
||||
| `stopped` | The network is bankrupt |
|
||||
|
||||
`click` presses a button as a player's click does, with the button's own arguments, so a confirmation arms first
|
||||
and windows step on as they do in the game. Lists the game acts on when they change are listed with their options
|
||||
and clicked with a value. Neither tool reaches files, save slots, settings, the title screen or the game speed.
|
||||
There is no tool that evaluates code in the page, and nothing but tool names and JSON arguments crosses the relay.
|
||||
|
||||
## In the player's browser
|
||||
|
||||
The browser mode plays by the player's rules on top of the headless ones:
|
||||
|
||||
- **The game is the player's.** There is no `new_game`, `load_save` or `export_save`, and the actions that start,
|
||||
retry or leave a scenario, puzzle or architect run are refused. Whichever tab is connected is the game.
|
||||
- **So is the clock**, set in Settings (see above). There is no tool for it.
|
||||
- **And their windows.** A window the player opened (Settings, the menu, a sheet) is never a question, never closed
|
||||
and never replaced: the agent plays behind it. `screen` shows it with `playerWindow`, and its buttons are the
|
||||
player's to press. A sheet the agent opens meanwhile is shown to it and closed again. Only a question the game asks
|
||||
in answer to the agent's own move takes the screen, as it would after a click.
|
||||
- **And their settings**: no preference can be changed.
|
||||
- **The dice stay hidden**: `state` never returns the seed or the days of the next failure, event or scripted attack;
|
||||
`schema` marks them `withheld`, with the reason.
|
||||
|
||||
## Looking into a bug report
|
||||
|
||||
1. `load_save` (headless) with the save attached to the issue.
|
||||
2. `status` and `hot_spots` for the picture, `traceroute` and `peering_check` for one network's traffic, `state`
|
||||
and `results` for the numbers behind them.
|
||||
3. `advance` a few days and read `timing.slowestDays` for lag, or the log for what went wrong.
|
||||
|
||||
## Troubleshooting the browser mode
|
||||
|
||||
- **"no game page answered"**: the tab is not connected. Settings → Agent API → on. No Agent API section in Settings?
|
||||
The page is not the development page served locally: open it from `npm run dev`, at an address such as
|
||||
`http://localhost:8080` or `http://127.0.0.1:8080`, not under a DNS name, which the relay refuses.
|
||||
- **"the game page in the browser disagrees with the code on disk"**: the tab is older than the checkout (perhaps
|
||||
after a `git pull`). Reload it: `npm run dev` assembles the page on every request.
|
||||
- **A second tab took over**: one page per relay; the newest tab wins and the old one stops dialing.
|
||||
|
||||
## Code
|
||||
|
||||
- `scripts/mcp.js`: the server on the SDK: the tools registered from `TOOLS` for the session's mode, stdio or
|
||||
Streamable HTTP, the Host, Origin and token checks, the one-at-a-time queue, and the options.
|
||||
- `scripts/lib/mcp-game.js`: the headless session (one game page) and the tool list, each tool with its input schema
|
||||
and the modes it works in.
|
||||
- `scripts/lib/mcp-headless.js`: runs inside the headless page only: starting, loading and exporting games, and the
|
||||
server's clock.
|
||||
- `scripts/lib/mcp-browser.js`, `scripts/lib/relay-client.js`: the browser session: the relay's tool side, the wait
|
||||
for a page and the check that it serves this checkout's contract.
|
||||
- `scripts/agent/relay.js`: the relay, hosted by `scripts/dev.js` on its own port.
|
||||
- `src/agent/`: the facade in the page, in the development page only: every action's class, arguments, domains,
|
||||
price and description (`20-commands.js`), the `state`/`results` field reference and what is withheld
|
||||
(`30-docs.js`), the reads, the screens, dispatch and the clocks (`70-time.js`); agent mode's switch, clock and
|
||||
Settings (`75-mode.js`), the page's side of the relay (`80-relay.js`) and the clock where frames do not run
|
||||
(`85-ticker.js`). The game itself only offers `HOOKS` and `UI.clockLocked` (`src/game/50-state.js`).
|
||||
- `tests/mcp.test.js`: the protocol over stdio, a game played through the tools, determinism, saves, both clocks, and
|
||||
what stays out of reach. `tests/mcp-http.test.js`: the HTTP transport, its checks, the token and the save directory.
|
||||
`tests/mcp-commands.test.js`: every action classified and its arguments real, outcomes, quotes, typed text,
|
||||
multi-step builds, confirmations, the reads and the screens. `tests/agent-api.test.js`: the facade is inert until
|
||||
called, and the page players get has none of it. `tests/agent-relay.test.js`, `tests/agent-settings.test.js`: the
|
||||
relay, the browser mode and its rules, and the Settings. `tests/mcp-parity.test.js`: one scripted session gives the
|
||||
same outcomes headless and through the relay.
|
||||
|
||||
The tools read the game's internals (`S`, `R`, `ACT`, `NETS`…), which are not a stable API: a refactor in `src/` can
|
||||
break a tool, and the tests are there to catch that in CI. A new action in `ACT` needs an entry in
|
||||
`src/agent/20-commands.js` (a class, or `API_DENY`), or `tests/mcp-commands.test.js` fails.
|
||||
222
docs/MULTIPLAYER.md
Normal file
222
docs/MULTIPLAYER.md
Normal file
|
|
@ -0,0 +1,222 @@
|
|||
# Multiplayer (self-hosted copies)
|
||||
|
||||
The game at [seriesoftub.es](https://seriesoftub.es) is hosted on GitHub Pages and nowhere else
|
||||
([ADR 0001](adr/0001-github-pages-only.md)), so it has no server and no multiplayer. This page is for a copy you host
|
||||
yourself: there, a small session server that ships with the source (`scripts/mp-server.js`) lets players build their
|
||||
networks side by side.
|
||||
|
||||
A plain `npm run build` is unchanged: the page has no multiplayer door, no chip and makes no request for it. Multiplayer
|
||||
is switched on only when the build is told where the session server lives.
|
||||
|
||||
## What it does (phase 1)
|
||||
|
||||
- **Sessions by code.** One player starts a session from the title screen (Multiplayer: their network's name, home city
|
||||
and rules preset, optionally a session name) and gets a six-character code such as `K7Q-2XD`. Friends join with that
|
||||
code. Codes use Crockford's base32 (no I, L, O or U); they are case-insensitive, and the dash is optional.
|
||||
- **One world.** Everyone in a session plays a Normal game with the creator's rules preset (Best Effort, Change Freeze,
|
||||
On-call or BGP at 3 a.m.) and the session's random seed, so day 0 is the same world for all. The session hands each
|
||||
player an AS number from 200000–214999 that nobody else in the session and no network on the map uses. Each network
|
||||
is still simulated in its own player's browser; from the first different click on, the worlds drift apart.
|
||||
- **Saves on the server.** Each network's save goes to the server on a new game day, at most every 15 seconds (gzipped
|
||||
when it is big), and when the page is hidden or closed if anything changed since the last push (a paused game's
|
||||
building too). Opening the network on any device fetches the server's save first and loads it if another device
|
||||
played on.
|
||||
- **Seeing each other.** Every push carries a small public *card*: day, tier, POPs, links between them (with capacity),
|
||||
exchanges, transit providers, peering policy, reach, peak and served traffic, customers, revenue per month, cash as an
|
||||
order of magnitude, and a score. The session panel (the 🌐 chip in the top bar, or the menu) shows the leaderboard
|
||||
(Tier 1 first, then Tier 2, then traffic served), a feed (joins, leaves, Tier 2, Tier 1 and who got there first) and a
|
||||
chat. While the panel is open it refreshes every 5 seconds; otherwise the roster rides along with each push.
|
||||
- **Moving to another device.** The panel's "Move to another device" holds a link `https://your.host/#mp=CODE.pid.token`.
|
||||
The part after `#` never reaches any server. Opening it (or copying the link) first sends this device's latest save,
|
||||
and opening the link loads the network into that browser. Treat it like a password: anyone with it can play as you.
|
||||
A browser keeps the link's token only once the server has accepted it, so a wrong or mistyped link never replaces the
|
||||
one it already has; when the server cannot be reached, the link stays in the address bar for a reload to try again.
|
||||
- **Offline.** The game never waits for the server. When it cannot be reached, the game says so once, keeps playing and
|
||||
tries again later (30 s, then 1, 2, 4, at most 5 minutes apart; the open session panel keeps looking every 5 seconds
|
||||
without stretching that wait).
|
||||
|
||||
Not yet (phase 2): peering, transit and competition between players inside the simulation. The card already carries
|
||||
what that will need (POPs, links, exchanges, transit, peering policy, reach).
|
||||
|
||||
## Being built: the server runs the game
|
||||
|
||||
Work has started on server-run play. In a multiplayer build, the session server will run every network's days, so all
|
||||
players of a session share one calendar and one speed, and the page will only show the network and send the player's
|
||||
clicks. The engine that runs networks on the server is in the source (`scripts/lib/mp-sim-*.js`), but nothing uses it
|
||||
yet and it is not switched on: sessions work exactly as this page describes, with each network simulated in its own
|
||||
player's browser. The design and how far it has got are in [plans/server-run.md](plans/server-run.md).
|
||||
|
||||
## Build
|
||||
|
||||
```bash
|
||||
MP_API=/api/mp npm run build # _site/ with multiplayer on; the page talks to /api/mp on its own origin
|
||||
```
|
||||
|
||||
`MP_API` must be a path on the same origin (letters, digits, `/`, `_`, `-`; no trailing slash, and not starting with
|
||||
`//`, which a browser reads as another host). Anything else fails the build. Without it, or empty, the build is the
|
||||
plain one.
|
||||
|
||||
## Run the server
|
||||
|
||||
```bash
|
||||
node scripts/mp-server.js --site _site --data /var/lib/tubes-mp --port 8090
|
||||
# or: npm run mp -- --site _site --data /var/lib/tubes-mp
|
||||
```
|
||||
|
||||
One process serves the API under `/api/mp` and, with `--site`, the built game too (like GitHub Pages would: `/` is
|
||||
`index.html`, a missing file gets `404.html`, nothing outside the folder is ever served). It binds `127.0.0.1` by default:
|
||||
put a reverse proxy with HTTPS in front. Plain `node:http`, no dependencies beyond Node 20 or newer.
|
||||
|
||||
| Option | Default | |
|
||||
|---|---|---|
|
||||
| `--port N` | 8090 (or `$PORT`) | port to listen on |
|
||||
| `--host H` | 127.0.0.1 | address to bind |
|
||||
| `--data DIR` | `./mp-data` | sessions and saves; created if missing |
|
||||
| `--site DIR` | none | also serve the built game from DIR |
|
||||
| `--base PATH` | `/api/mp` | the API's path; must match `MP_API` |
|
||||
| `--prune-days N` | 60 | sessions nobody touched for N days are deleted, at startup and daily |
|
||||
| `--max-sessions N` | 1000 | sessions on this server |
|
||||
| `--max-players N` | 12 | players per session (at most 12) |
|
||||
| `--create-per-hour N` | 10 | new sessions one address may start per hour |
|
||||
| `--sessions-per-hour N` | 100 | new sessions per hour on the whole server, from all addresses together |
|
||||
| `--trust-proxy` | off | take the client's address from `X-Forwarded-For` (only behind your own proxy) |
|
||||
| `--verbose` | off | one log line per API request (never tokens) |
|
||||
|
||||
Behind a reverse proxy every request comes from the proxy's address, so the per-address limits only mean something with
|
||||
`--trust-proxy` (the server then uses the last address in `X-Forwarded-For`, the one your proxy added); without it, all
|
||||
players share one address's limits, such as 4 save uploads at once. An IPv6 address counts as its /64, since one phone
|
||||
or home usually has a whole /64 to itself.
|
||||
|
||||
To try it locally without a build: `npm run dev -- --mp` runs the API inside the dev server (sessions in `mp-data/`) and
|
||||
turns multiplayer on in the dev page. Open a second window (a private one counts as another browser) to be the second
|
||||
player.
|
||||
|
||||
### nginx
|
||||
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl http2;
|
||||
server_name tubes.example.org;
|
||||
ssl_certificate /etc/letsencrypt/live/tubes.example.org/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/tubes.example.org/privkey.pem;
|
||||
|
||||
client_max_body_size 5m; # a save is at most 4 MB
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8090; # the game and /api/mp, from the one process
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Run the server with `--site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy`.
|
||||
|
||||
### Caddy
|
||||
|
||||
```caddy
|
||||
tubes.example.org {
|
||||
request_body {
|
||||
max_size 5MB
|
||||
}
|
||||
reverse_proxy 127.0.0.1:8090
|
||||
}
|
||||
```
|
||||
|
||||
Caddy sets `X-Forwarded-For` itself and gets the certificate on its own; run the server with `--trust-proxy` as above.
|
||||
|
||||
### systemd
|
||||
|
||||
```ini
|
||||
[Unit]
|
||||
Description=Series of Tubes multiplayer
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/bin/node /srv/tubes/scripts/mp-server.js --site /srv/tubes/_site --data /var/lib/tubes-mp --trust-proxy
|
||||
User=tubes
|
||||
Restart=on-failure
|
||||
StateDirectory=tubes-mp
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
## Backups
|
||||
|
||||
Everything is in the data folder: `<CODE>.json` per session (settings, players, cards, feed, and each save's number) and
|
||||
`<CODE>.<pid>.save` per player's save (its text exactly as the game sent it). Every write goes to a temporary file that is then renamed over the old one, so a
|
||||
copy of the folder (`rsync`, a snapshot, `tar`) taken while the server runs holds whole files. Restore by stopping the
|
||||
server, putting the files back and starting it again. A player's token is stored only as its SHA-256, so a backup cannot
|
||||
be used to play as anyone.
|
||||
|
||||
## Limits
|
||||
|
||||
- 12 players per session, 1000 sessions per server (configurable).
|
||||
- A save is at most 4 MB of text (the game gzips anything over 32 kB: the big test network, 236 kB of JSON, goes as about 50 kB). Other
|
||||
requests are at most 16 kB.
|
||||
- Chat lines: at most 200 characters, one a second and six per 30 seconds per player. The feed keeps the last 100 lines.
|
||||
- Per address and hour (an IPv6 address counts as its /64): 10 new sessions, 60 joins, 120 wrong codes (after that,
|
||||
every code is refused for a while from there, so guessing codes gets nowhere; a player who sends their own session's
|
||||
code with its token is never refused for it). At most 100 new sessions an hour on the whole server.
|
||||
- Saves and cards: one save upload at a time per player (another one meanwhile gets 429), at most 4 at once from one
|
||||
address and 16 on the whole server (503 with `busy: true` beyond that; the game then tries again a little later,
|
||||
quietly), and per player at most 20 saves and 60 cards a minute (the game sends one every 15 seconds at most). A
|
||||
save's body must arrive within two minutes. A card alone is written to disk within two seconds, together with any
|
||||
others that came in meanwhile.
|
||||
- Network names: at most 32 characters; control characters, `<`, `>`, `&`, quotes and backticks are removed. The page
|
||||
escapes everything other players wrote anyway.
|
||||
- A page that is being hidden or closed can only send 64 KiB (the browser's limit for such requests, counted in bytes),
|
||||
so a network whose save does not fit sends its card alone then; its save goes with the next push from that device.
|
||||
|
||||
## How saves stay in order
|
||||
|
||||
Each network in a session carries a save number (`S.mp.seq`). When a save is due to go to the server, the game picks
|
||||
the next number before it writes the save, so the save kept in the browser and the one sent carry the same number;
|
||||
reopening the network then finds nothing newer on the server unless another device pushed one. The server refuses a
|
||||
number that is not newer than its own (HTTP 409, with its number), and only counts a save once it is on disk. Then the
|
||||
player is told once that the network moved on elsewhere and chooses: load the newer save from the server (only one at
|
||||
least as new as the server said it had: never an older one), or keep this one (at the end of the current game day it
|
||||
goes with `force` and a number past the server's).
|
||||
|
||||
The token is never part of the save: it lives in the browser's storage under `sot-mp:<code>:<pid>`. An exported or
|
||||
imported save keeps its session but cannot talk to the server without the token (the game says it is no longer in its
|
||||
session and plays on alone).
|
||||
|
||||
## API
|
||||
|
||||
JSON in and out, same origin, no cookies, no CORS headers. Every call but starting and joining needs
|
||||
`Authorization: Bearer <pid>.<token>`. Errors are `{"error": "…"}` with a fitting status (400, 401, 404, 405, 409, 413,
|
||||
415, 429, 503).
|
||||
|
||||
| Call | Body | Answer |
|
||||
|---|---|---|
|
||||
| `POST /api/mp/sessions` | `{net:{name,home}, preset, title?, avoid?}` | `201 {code, pid, token, seed, asn, preset, color, title}` |
|
||||
| `POST /api/mp/sessions/:code/join` | `{net:{name,home}, avoid?}` | the same, for the joiner (`409 {full:true}` when full) |
|
||||
| `GET /api/mp/sessions/:code` | | `{code, title, preset, seed, created, players:[{pid, name, asn, color, card, seen, joined}], feed}` |
|
||||
| `PUT /api/mp/sessions/:code/card` | `{card}` | the roster |
|
||||
| `PUT /api/mp/sessions/:code/save` | `{seq, at, data, card?, force?}` | `{ok, seq, at, roster}`, or `409 {seq, at}`; `429` while another one is on its way, `503` when the server is busy |
|
||||
| `GET /api/mp/sessions/:code/save` | | `{seq, at, data}` (your own save only) |
|
||||
| `POST /api/mp/sessions/:code/feed` | `{text}` | the roster |
|
||||
| `DELETE /api/mp/sessions/:code/me` | | `{ok}`; the session goes when its last player leaves |
|
||||
|
||||
`avoid` lists AS numbers the server must not hand out (the game sends the map's own networks in that range). `preset` is
|
||||
one of `soft`, `freeze`, `oncall`, `bgp`. `data` is the save as the game writes it: JSON text, or `gz:` and base64.
|
||||
|
||||
The card, as the server keeps it (unknown fields are dropped, numbers clamped, ids checked for shape; the page checks
|
||||
the ids against its own catalogs again): `day`, `tier` (`t1`, `t2`, `t3`), `t1`, `lvl`, `pops` (city ids), `links`
|
||||
(`[a, b, Gbps]`, up to 300), `ix`, `transit` (network ids), `ppol` (`open`, `selective`, `closed`), `reach` (0–1),
|
||||
`peak`, `served` (Gbps), `cust`, `rev` (per month), `cashB` (−1 in debt, else the power of ten of the cash), `score`.
|
||||
Cards are what each player's browser says: nothing on the server checks that a network really is that big.
|
||||
|
||||
## Code
|
||||
|
||||
- Server: `scripts/lib/mp.js` (the API and storage), `scripts/mp-server.js` (the command line and the static site).
|
||||
- Game: `src/game/60-features/89-multiplayer.js` (state, sync, the card, the `#mp=` link),
|
||||
`src/game/95-modals/48-multiplayer.js` (door, sheets, panel, chip), `src/game/90-actions/92-multiplayer.js`
|
||||
(actions), `src/styles/41-multiplayer.css`. The build stamps `MP_API` into `src/game/00-core/20-analytics.js`.
|
||||
- Tests: `tests/mp-server.test.js`, `tests/multiplayer.test.js`.
|
||||
- Server-run play (being built, not switched on): the act tables `scripts/lib/mp-sim-acts.js`, the engine
|
||||
`scripts/lib/mp-sim-engine.js`, `mp-sim-worker.js` and `mp-sim-realm.js`, the page's side `src/game/98-server-play/`
|
||||
(a comment so far), and the tests `tests/mp-sim-*.test.js` and `tests/server-sim-prereqs.test.js`.
|
||||
|
|
@ -41,6 +41,9 @@ Anything that needs data at runtime fetches it from the same origin as a static
|
|||
what is cached for offline play, versioned by the release.
|
||||
- **Deploys only come from releases.** `release.yml` is the only workflow with `pages: write`. Pushes to
|
||||
`main` never deploy.
|
||||
- **Tools are not hosting.** `npm run dev`, the MCP server and the container image that packages them
|
||||
(`docker/`, published to GHCR for releases) are tools. What someone serves with them is theirs; seriesoftub.es is
|
||||
the game, and nothing is ever deployed anywhere but GitHub Pages.
|
||||
- **Tests guard it.** `tests/pages.test.js` checks that a build is plain static files that GitHub
|
||||
Pages can serve as they are: no server or host configuration files, every local reference resolving
|
||||
inside `_site/`, nothing over the size limits, `CNAME` and `404.html` in place, and the deploy going
|
||||
|
|
|
|||
|
|
@ -35,7 +35,7 @@ fell back to English. Long sentences as keys made dictionary diffs hard to read
|
|||
- **`npm run i18n:check`** verifies that every label used in `src/` is defined in English, every
|
||||
English label is used, every translation keeps its English's placeholders, HTML tags and plural forms,
|
||||
and every dictionary is sorted.
|
||||
- **Saves:** a few things in a save hold text to show later (the peering inbox log, sold-out reasons,
|
||||
- **Saves:** a few things in a save hold text to show later (sold-out reasons,
|
||||
attack names). New saves hold labels. Saves from before labels (1.34 and older) hold the English text; `tr()` maps it
|
||||
back to its label the first time it sees one, so old saves still show the player's language.
|
||||
- **Translators** read `src/i18n/en.js` next to their file; both are sorted by the same labels, so the
|
||||
|
|
|
|||
46
docs/adr/0004-dev-only-code.md
Normal file
46
docs/adr/0004-dev-only-code.md
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
# ADR 0004: Development-only code, assembled into the development page only
|
||||
|
||||
- Status: accepted
|
||||
- Date: 2026-11-03
|
||||
|
||||
## Context
|
||||
|
||||
The MCP server (`npm run mcp`, [MCP.md](../MCP.md)) plays the game through a facade of typed commands, reads and
|
||||
screens. That facade has to run inside the game page, in its top-level scope: it reads `S`, `R`, `ACT` and the
|
||||
catalogs directly, and a page in the player's own browser can only run code it was served (nothing may be sent to
|
||||
it as code). So it belongs in `src/`, next to the game.
|
||||
|
||||
But it is about 110 KB of JavaScript (some 40 KB gzipped) that no player can use: seriesoftub.es has no way to
|
||||
reach it. Shipping it would make every player, most of them on phones, download and parse it on every load,
|
||||
against the rule that structure costs nothing at runtime ([ADR 0002](0002-one-page-assembled-at-build.md)).
|
||||
|
||||
## Decision
|
||||
|
||||
- Code only tools use lives in `src/agent/` (and later folders like it), named and ordered like `src/game/`.
|
||||
- `src/index.html` includes it with `<!-- @include-dev agent -->`, right after `<!-- @include game -->`, inside the
|
||||
same script, so it shares the game's top-level scope.
|
||||
- `scripts/lib/page.js` expands an `@include-dev` line only when asked (`assemble({ dev: true })`, `--source --dev`).
|
||||
Otherwise the line is dropped whole, so the page players get is byte for byte what it would be without the
|
||||
feature.
|
||||
- The **development page** (with `src/agent/`) is what `npm run dev` serves, what the MCP server loads and what
|
||||
`i18n-check` reads. The **players' page** (without it) is what `npm run build` and `npm run serve` ship, what
|
||||
`npm run perf` measures and what the tests load unless a test asks for `load({ agent: true })`.
|
||||
|
||||
## Rules that come with it
|
||||
|
||||
- **The game never names agent code.** Nothing in `src/game/`, `src/styles/` or `src/index.html` may refer to
|
||||
anything `src/agent/` defines: it would work in development and break for players. Every top-level name in
|
||||
`src/agent/` starts with `api` or `API_` (the facade itself is `window.TUBES`), and `tests/build.test.js` fails on
|
||||
any use of those names outside `src/agent/`.
|
||||
- **Agent code runs after the game.** Its files come after `99-loop.js`, so its top level may use anything the game
|
||||
defines, and must not assume `boot()` has or has not run yet. In practice it only defines tables and functions.
|
||||
- **Tests load the players' page by default.** So a core change that quietly leans on agent code fails the suite
|
||||
instead of the release. `tests/pages.test.js` checks that the built page carries no agent code and still plays.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Players pay nothing for the facade: the build is unchanged by it, and the performance benchmark measures exactly
|
||||
what ships.
|
||||
- `npm run serve` stays what it says: the built site as GitHub Pages serves it, without the agent.
|
||||
- The development page and the players' page differ, by design and only by what `@include-dev` adds. Anything that
|
||||
must behave like production (perf, the release build test) uses the players' page.
|
||||
408
docs/plans/multiplayer-phase2.md
Normal file
408
docs/plans/multiplayer-phase2.md
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
# Multiplayer phase 2: players inside each other's simulations
|
||||
|
||||
Status: design only, not built. Phase 1 (sessions, server-side saves, leaderboard) is in `docs/MULTIPLAYER.md`.
|
||||
|
||||
Clock: this design assumes each player's game keeps its own time. A shared session clock is proposed in
|
||||
`docs/plans/next-session.md` (item 3). If it is adopted, the parts timed in real minutes or on each player's own clock
|
||||
(tenders, `idle`, notice, the soak test) move to game days.
|
||||
|
||||
**Conventions:**
|
||||
- Line numbers are `main` at `1e7638c`.
|
||||
- Phase 1 (multiplayer sessions, merged on `main`) provides `S.mp`, `MP`, `mpCard`/`mpCardOk`, and `cleanCard` in `scripts/lib/mp.js`.
|
||||
- Everything runs only when `MP_API` is stamped and `S.mpx` is not null. The plain GitHub Pages build is unchanged (`pages.test.js`, `build.test.js`).
|
||||
|
||||
## 1. Starting point and grafts
|
||||
|
||||
**Base: "contracts".** It had the best totals in two of the three scorings, and the best feasibility and risk.
|
||||
- Players are pseudo carriers `mp:<pid>`, registered only in `NET` with single-entry `CONE`/`CONE_S`/`DOWN`/`ANC`.
|
||||
- `NETS`, `NET_IDS`, `NSH`, `t1Need()`, seen/grace and the gameplay-rules tests never see a player.
|
||||
- No catalog id contains `:`, and nothing iterates `NET`.
|
||||
|
||||
**I checked this on big-network** (a throwaway probe, not committed): a buyer row on `mp:p1` in `S.transit` plus a player PNI, through `compute`, 5 day ticks, the intern, every panel and tab, traceroute, `t1Why`/`isTier1` and a `migrate` round trip.
|
||||
|
||||
Results:
|
||||
- No errors anywhere.
|
||||
- The rows were kept while registered and dropped once unregistered.
|
||||
- Warm compute went from 32.3 to 33.2 ms (median of 25 alternating runs).
|
||||
- `R.sessions` rose by 1. That confirms the exploit fixed below.
|
||||
|
||||
**How each fatal flaw the judges found is removed:**
|
||||
|
||||
| Judged flaw | Fix |
|
||||
|---|---|
|
||||
| The seller's `S.biz` row is exposed to dropBiz, decommission, ddosTargets, Pie moods and the mood loop | The seller side is a deal entry read in exactly two places, demand and money (nets) |
|
||||
| Peering is cosmetic, yet player PNIs count toward `isTier2`/`t1Club` | Player traffic ships with peering (§2.3). Player sessions never enter `R.sessions` |
|
||||
| Health is all or nothing, and bought transit reaches every network | A capacity factor (`t.mpf`) and a `miss` id list, from day one |
|
||||
| A↔B transit loops | The server refuses with 409; clients drop loop links in a fixed pid order (nets) |
|
||||
| A stale or alt buyer keeps paying the commit forever | The seller earns, and carries load, only while the buyer's clock runs. Prices are capped against the catalog |
|
||||
| A bought wave can be upgraded past its agreed price | `upLink`/`rmLink`/`setStandby` refuse it (gameplay) |
|
||||
| "An active deal with no row" is ambiguous | A per-deal `made` flag (§5) |
|
||||
| `NKN` flips inside `compute()` | It is always `NN+4` |
|
||||
|
||||
**Grafted from the other designs:**
|
||||
- From nets: the two-sided route-server rule; cones through players; PNI lead from `hstr`, with capacity set by the smaller side; the Tier 1 clique star.
|
||||
- From gameplay: waves, tenders, poaching, consortium seats, notice on each player's own clock, and the LOA handshake.
|
||||
|
||||
**Rejected:** players as `NETS` entries (a mutable catalog, a rescaled `NSH`), reach bitmaps (they break between builds), a Tier 1 that depends on other players, automatic ratio strikes, and own-day timers that end a deal (they fire within seconds at 8×; own-day notice only paces each side's own teardown).
|
||||
|
||||
## 2. Mechanics
|
||||
|
||||
### 2.1 Pseudo carriers (`src/game/30-networks/45-player-carriers.js`, new)
|
||||
|
||||
`mpBind(s)` does three things:
|
||||
1. deletes every `mp:*` key;
|
||||
2. registers `{id:'mp:'+pid, name, asn, type:'t2', pol:'open', share:0, price:1, pops:[], up:[], ix:[], cc:'', col, blurb:tr('mp.another_player'), mp:1}` for each `s.mpx.who` entry;
|
||||
3. sets `MPB.k`.
|
||||
|
||||
It runs at the start of every `sanitize` and every `compute()` (`if(MPB.k!==(S.mpx?S.mpx.k:''))mpBind(S)`). That covers the route worker, slot switches, imports, the failed-load rollback (`91-slots.js:105`) and puzzles. `nocWinState` (`94-dashboard/90-noc-window.js:45`) calls it too.
|
||||
|
||||
Because the carrier has `pops:[]` and is not in `NETS`, no catalog list ever offers a player:
|
||||
- `sellsAt` and `buyTransit`;
|
||||
- the intern's providers, `peerAll` and `pniAll`;
|
||||
- the peering desk and own-exchange joins.
|
||||
|
||||
The `peer` action returns at `ixMembers(city).includes(net)` (`40-sites-peering-caches.js:14`).
|
||||
|
||||
### 2.2 Transit between players (the Tier 1 endgame)
|
||||
|
||||
**Who can sell:** a player publishes `tp` ($/Gbps/month) while `R.reach >= 0.99` and they have at least one POP.
|
||||
|
||||
**Buying:** "Buy transit from X here" posts a `t` deal (city, tier, LAG). The server makes it `live` at once (a price list is a standing offer) when all of these hold:
|
||||
- the seller's card has `tp`;
|
||||
- both cards list the city;
|
||||
- there is no cycle;
|
||||
- the limits hold.
|
||||
|
||||
**Price:** `min(tp, mpCap(city))`, where `mpCap = 2 × the cheapest catalog transitPerG(n,city,false)` there, or the catalog median if nobody sells there.
|
||||
- Both sides compute it from the static catalog, ignoring each save's own `priceMul`.
|
||||
- Both clamp again when they receive the deal.
|
||||
|
||||
**Buyer side: an ordinary `S.transit` row** `{id:'mt-'+deal, net:'mp:'+seller, city, tier, n, mp:deal, mpp:price}`.
|
||||
- **Comes free:** the router port (`40-ports.js:20`), p95 history (`10-day-tick.js:37`), hot ports, traceroute, incidents, the panels, and `isTier1()===false`.
|
||||
- **Billing:** `transitMo` (`40-billing.js:9`) uses `t.mpp` instead of `transitPerG(...)*S.priceMul`. The commit floor, `PORT.tmo` and `krFee` still apply.
|
||||
- **Capacity:** `30-compute.js:53` multiplies by `t.mpf` = min(1, the seller's `sv[city]`/0.95), in 0.05 steps.
|
||||
- **Reach:** `:54`'s `ok` also needs `!mm.has(n)` (the seller's `miss`).
|
||||
- **Route cache:** the hash of every miss set joins the flags at `:70` (`+(S.mpx?S.mpx.xk:'')`), so `rcExitKey` rebuilds when a seller's reach changes.
|
||||
- **Outage:** `t.down=S.day+1` when the seller's POP is down or the seller has left.
|
||||
|
||||
**Seller side: a `sell` entry in `S.mpx.deals`, never in `S.biz`.**
|
||||
- **Load:** `mpDem(bizBw)` after the biz loop (`:95`) adds `u`, the buyer's reported use. It leaves by catalog share over the seller's own backbone, peering and upstreams; a Tier 1 carries it settlement-free.
|
||||
- **Money:** `V.mp = Σ price × max(q, 20% of port) × min(1, sfOf(R2,city)/0.95)`. `q` is the buyer's p95; the last factor is the business customers' SLA credit. `V.mp` is added to `revMo` (`:382`) and to the revshare base (`:380`).
|
||||
- **Port:** the seller's port counts in `portsUsed` (`10-catalog/40-ports.js`, after `:21`).
|
||||
- **Idle buyer:** if the buyer's roster `idle` is ≥ 300 s (no newer game day reached the server), load and revenue are 0.
|
||||
- A paused or closed buyer has no traffic to bill, and a fast seller cannot bill a frozen buyer.
|
||||
- An alt account has to keep playing, and still pays at most the capped price.
|
||||
|
||||
**Loops:**
|
||||
- The server returns 409 `loop` if the seller already buys from the buyer, directly or through others (a search over at most 12 players).
|
||||
- Clients build the player-transit graph from `who[].pt` and add edges sorted by (buyer pid, seller pid), dropping any that closes a cycle, so every client drops the same edge.
|
||||
- So reach passes down a reseller chain one push per hop, never settling at a false 1.
|
||||
|
||||
**Tier 1 stays defined by the built-in networks.**
|
||||
- `R.reach` only sums `NSH`, so neither `isTier1` (`80-hot-ports-and-rank.js:20`) nor the mood check `R.reach>0.99` (`10-day-tick.js:51`) can depend on players.
|
||||
- Buying player transit costs Tier 1, and `t1Why` already says so. Selling never does.
|
||||
- Refusing to peer blocks nobody's win.
|
||||
|
||||
### 2.3 Peering between players, carrying traffic
|
||||
|
||||
**PNI (`pni` deal, always accepted by hand).** Each side adds `S.pni` `{id:'mn-'+deal, net:'mp:'+other, city, tier, n, mp:deal, ready:S.day+lead}`.
|
||||
- **Lead time:** `lead = pniNow() ? 0 : leadDays(14 + hstr(deal+myPid) % 29)`, with no random numbers.
|
||||
- **Cost:** each side pays its own `pniMo`.
|
||||
- **Capacity:** the smaller of the two sides (theirs comes from `dl[].g`). It is 0 until both cards report `ok`: the LOA and cross-connect handshake.
|
||||
|
||||
**IX (`ix` deal).** The server makes it `live` if the responder's policy is open, `no` if closed, and `offer` if selective. Once live, both sides set `S.peers['mp:P@x']`.
|
||||
|
||||
**Route server:** no deal. P peers with me at `x` when both `S.rs[x]` and `P.rs ∋ x` hold and both policies are open. That is the same rule on both clients.
|
||||
|
||||
**Sessions:**
|
||||
- `mpIx(x)` lists the player peers at an exchange. `ixSessions` (`20-exchanges.js:29`) stays catalog-only.
|
||||
- At `30-compute.js:61`, player PNIs skip `R2.sessions++` (`if(!p.mp)`) and count in `R.mpSess` instead.
|
||||
- So friends can never inflate `isTier2`/`t1Club`.
|
||||
|
||||
**Player traffic** (new `src/game/80-simulation/36-mp-traffic.js`). `compute.js:343` calls `mpTraffic({E,SPP,NRES,HAS,R2,carry,NN})` once, after `citySrv` (`:341-342`). The parts are handed in the way `ddosLoad` gets them (`:188`).
|
||||
- **Demand:** each POP sends `cityEye[c]·w_P` to each active player P.
|
||||
- `w_P = min(0.02, (biz_P + 0.3·eye_P)/75000)`, and `Σw ≤ 0.1`.
|
||||
- **Exits that reach P:**
|
||||
- rank 2: a ready PNI with P, or an IX exit with `mpIx(x) ∋ P`;
|
||||
- rank 2.5: the same exits toward Q when P buys from Q, which gives cones through players;
|
||||
- rank 3: player transit from Q when `P===Q` or `Q.mr ∋ P`, and catalog transit when `P.on`;
|
||||
- `pref:'low'` moves an exit to rank 4.
|
||||
- **Pushing:** exits are sorted by distance once per POP. Traffic goes along `walkI(SPP[c],ci,e.ci)` and is limited by `l.res`, `NRES` and `e.cap-e.used`.
|
||||
- **Recording:** each push calls `carry(l,e.ek,NN+3,…)`. `NKN` is always `NN+4` (`:130`), and that column is named `'players'` at `:16`.
|
||||
- **Effects:**
|
||||
- Transit p95, hot ports and link loads include player traffic, so peering saves transit money.
|
||||
- `R2.mp={dem,srv,peer,lost,full,by}` records the totals.
|
||||
- The pass runs after every catalog flow, so `R.served`, `R.demand`, moods, levels, `peerShare` and Tier 1 never change.
|
||||
|
||||
**Cost of a de-peering war:**
|
||||
- `computeMoney` applies `V.eyeballs *= 1 - mp.lost/(demand+mp.dem)`, where `lost` is traffic with no route at all.
|
||||
- Two transit-free Tier 1 players who won't peer cannot reach each other: catalog Tier 1s don't pass on routes they learn from peers. Each loses up to 2% of eyeball revenue, which is real Level 3 vs Cogent drama at a bounded cost. Neither loses Tier 1.
|
||||
- Two eyeball players who don't peer pay transit p95 for each other's traffic.
|
||||
|
||||
**Clique star (cosmetic):** card `cq=1` when you are Tier 1 and reach every player whose card says `t1` by your own PNI or IX session. The leaderboard sorts the star first.
|
||||
|
||||
**De-peering:** `end` the deal. Each side removes its rows 7 own days after it first sees the end.
|
||||
|
||||
### 2.4 Competition
|
||||
|
||||
**Overlap:** `clComp` (`75-customer-lifecycle.js:30`) also counts rival players whose card POPs cover the customer's cities. The rolls stay hash-stable (`clR`).
|
||||
|
||||
**Poaching:**
|
||||
- `clLeave` (`:64`), for "cheap" or "multi" with a rival POP in the city, posts the customer to `/lost`.
|
||||
- The server gives it to one rival, chosen by `hstr`, as a gift.
|
||||
- The rival checks it with `okBiz`, `BIZ_T` and `rate ≤ catalog×mkt()×1.2`, then puts it in `S.offers` with `ref` set to the loser's name.
|
||||
|
||||
**Tenders:**
|
||||
- **Issue:** while at least two players are active (`idle` < 300 s), the server issues `{n, city}` every 5 real minutes. The city is seeded from the active players' POPs.
|
||||
- **Content:** derived from `hstr(seed|n)` and the `BIZ_T` lists, so every client sees the same tender.
|
||||
- **Bids:** a ratio r from 0.6 to 1.0. You can bid while paused, and an optional standing auto-bid covers your cities.
|
||||
- **Closing:** after 10 real minutes, or once every active player has bid. Wall-clock time, because no game clock is shared.
|
||||
- **Winner:** the best `(1.2-r)·sq`, where `sq` is served share. The tender goes into `S.offers` with `mp:1`, expiring in 10 own days, and is signed with the normal `accept`.
|
||||
|
||||
### 2.5 Shared fiber
|
||||
|
||||
**Waves and IRUs (`wave`/`iru` deals):**
|
||||
- **Seller side:** books spectrum or pairs via `+mpSold(l.id)` in the three counters (`60-requirements.js:72,75`, `37-fiber-broker.js:16`). It earns `V.mp += rate×(fiberOk?1:0)`.
|
||||
- **Buyer side:** an `S.links` row `{kind:'wave'|'df', own:false, mo:price, mp:deal}`, which copies cut/eqDown/ready from `dl`.
|
||||
|
||||
**Consortium seats:** built like `seatBuy` (`86-specialist.js:4`), at `ownCabCost(km)×myPairs/totalPairs` (`36-specialist.js:54`).
|
||||
|
||||
**Deferred:**
|
||||
- Joint exchanges, which need an id namespace (`isIx`, `50-sanitize.js:2`).
|
||||
- An opt-in "Tier 1 must reach every Tier 1 player" rule.
|
||||
|
||||
## 3. Server (`scripts/lib/mp-deals.js`, pure logic, with routes in phase 1's `scripts/lib/mp.js`)
|
||||
|
||||
**The deal record** is public to the session, like PeeringDB. The session keeps a counter `dv`, bumped on every change.
|
||||
|
||||
```
|
||||
{id:'d'+base36, k:'t'|'pni'|'ix'|'wave'|'iru', a, b, s (seller), at (city|ix|'a|b'), tier, n, price, slots, st, rev, t0, tl, te, by, why}
|
||||
```
|
||||
|
||||
| from | event | to | allowed for |
|
||||
|---|---|---|---|
|
||||
| – | create `t` | `live`, or 409 `not_selling`/`no_pop`/`loop`/`dup`/`limit` | the buyer |
|
||||
| – | create `ix` | `live` (b open and present) / `no` (b closed) / `offer` | a |
|
||||
| – | create `pni`/`wave`/`iru` | `offer` | a |
|
||||
| `offer` | accept / decline / withdraw / 7 days pass | `live` / `no` / `gone` / `gone` | b / b / a / server |
|
||||
| `live` | end | `end` (`quit`) | a or b |
|
||||
| `live` | a side's card never reports `ok` within 7 days | `end` (`unbuilt`) | server |
|
||||
| `live` | no card from a party for 14 days | `end` (`idle`) | server |
|
||||
| any open deal | a party leaves or is pruned | `end` (`left`) | server |
|
||||
| `no`/`gone`/`end` | 7 days pass | deleted | server |
|
||||
|
||||
**Errors:** every write sends `rev`. A stale `rev` or an illegal transition gets 409, and the wrong party gets 403.
|
||||
|
||||
**Limits:**
|
||||
- one open deal per (pair, kind, place);
|
||||
- 10 open offers and 24 live deals per player;
|
||||
- 300 deals per session;
|
||||
- price 0.05–50, tier 0–15, n 1–8;
|
||||
- 30 writes per minute per player.
|
||||
|
||||
**Feed:** the server writes a line for each transition ("X sells transit to Y in Frankfurt", "X de-peered Y").
|
||||
|
||||
**Endpoints:**
|
||||
- `POST /api/mp/sessions/:code/deals {k,to,at,tier,n,price?,slots?}` returns 201 `{deal,dv}`.
|
||||
- `POST …/deals/:id {op,rev}` with `op` one of accept, decline, withdraw or end.
|
||||
- `POST …/lost` reports a lost customer; `POST …/tenders/:n/bid {r}`; `PUT …/autobid`.
|
||||
- The roster responses (`GET` the session, and `PUT` the card or save) add:
|
||||
- `deals[]` (my deals, any state) and `dv`. Other players' links come from their cards' `pt`;
|
||||
- `tenders[]` and my `gifts[]`;
|
||||
- each player's `idle`: seconds since their card last carried a newer day.
|
||||
|
||||
So nothing needs extra polling.
|
||||
|
||||
## 4. Card fields beyond phase 1
|
||||
|
||||
Every field below is added to both `cleanCard` and `mpCardOk`. Phase 1's `transit` field stays catalog-only, because `NET_RE` would silently drop `mp:` ids.
|
||||
|
||||
| field | content |
|
||||
|---|---|
|
||||
| `nv` | build version |
|
||||
| `pt` | pids I buy transit from |
|
||||
| `rs` | exchanges with my route server on |
|
||||
| `tp` | my transit price, or null |
|
||||
| `miss` | catalog ids I can't reach, biggest share first, ≤160 (a reach of 0.99 can still miss 72) |
|
||||
| `on` | 1 if the internet of built-in networks can reach me: catalog transit, PNIs with every `t1Need()` network, or a seller with `on` |
|
||||
| `mr` | pids I reach |
|
||||
| `eye`, `biz` | Gbps, 2 significant digits |
|
||||
| `sq` | served share |
|
||||
| `sv` | `{city: delivered share}` where I sell, ≤64, in 0.05 steps |
|
||||
| `dl` | `[{id,u,q,g,ok,up,cut,eq,rdy}]`, one per live deal, ≤64 |
|
||||
| `cq` | clique star |
|
||||
|
||||
The card grows by about 4 KB at most. ASNs need nothing new: phase 1 already sends the catalog ASNs to avoid (`mpAvoid`, `mp.js:238`).
|
||||
|
||||
## 5. Client day flow (`src/game/60-features/89-player-deals.js`, new)
|
||||
|
||||
Phase 1's `mpRosterOk` is extended to whitelist `deals`, `dv`, `tenders`, `gifts` and `idle` (plus new `MP_FEED` kinds). The validated roster stays in `MP.roster`, never in S. `mpDay(d)` runs first in `dayPre`, right after `S.day++` (`10-day-tick.js:10`):
|
||||
|
||||
1. **Copy changes in.** If `dv`, `idle` or any card changed, rebuild `S.mpx.who` and `S.mpx.deals` from the validated data, with values in steps. Then recompute `k`/`xk` and call `mpBind(S)`.
|
||||
2. **Reconcile each deal:**
|
||||
- **live, not `made`:** create my row (`S.pops[at]`, `portOk`, `portGate`, `spend(setup)`) and set `made`. If that fails, the deal waits under a "waiting on you" badge, with no client timer; the server ends it as `unbuilt`.
|
||||
- **live, `made`, but the row is gone** (for example after a decommission, which `decomImpact` warns about): post `end` with `why:'gone'`. Decommissioning a city where I sell also ends those sell deals.
|
||||
- **ended** (or missing from the server's list): set `until=d+notice` (14 own days for transit, 7 for the rest) and remove the rows when it passes.
|
||||
3. **Copy the coupling values onto the rows:**
|
||||
- on transit rows: `t.mpf` and `t.down`;
|
||||
- on PNI rows: their side's capacity and whether it is ready;
|
||||
- on link rows: cut, eqDown and ready;
|
||||
- on my seller entries: `u`, `q` and whether the buyer is active.
|
||||
4. `compute()` runs (worker or not), then `dayPost`, then phase 1's push carries the new fields. `dl` comes from yesterday's R.
|
||||
|
||||
**My own clicks** (`mpOffer`, `mpAnswer`, `mpEnd`, `mpSell`, `mpBid`) apply as soon as the server answers, with `mpApply();after()`. If `RW.job` is set, they apply at the next `dayPre` instead.
|
||||
|
||||
Multiplayer code never calls `Math.random`.
|
||||
|
||||
## 6. Saves and sanitize
|
||||
|
||||
**New field:** `S.mpx = null | {k, xk, dv, who:[≤11], deals:[≤64]}`. `deals` holds only my own deals. Cones, `on` and who-buys-from-whom come from `who[].pt`.
|
||||
- `mpx:null` is the default in `newGame` (`80-new-game.js:4`), so old saves get null.
|
||||
|
||||
**Order in `sanitize`:** move phase 1's `mpSanitize(s)` from `50-sanitize.js:113` up to `:21`, then call `mpxSanitize(s)`. Both now run before `opsSanitize` (`:22`) and every `isNet` filter (`:34-35, :54-55`).
|
||||
|
||||
**`mpxSanitize`:**
|
||||
- **When it is null:** unless `MP_API` is stamped and `s.mp` is valid in normal mode. An imported multiplayer save then just loses its player rows.
|
||||
- **Players (`who`):** pids checked against the regex, unique, never my own.
|
||||
- **Names:** stripped like the phase 1 server does (control characters and `<>&"'\``, at most 32). They are not escaped, because `labOf`/`hotPorts` print catalog names unescaped too.
|
||||
- **Ids:** pass `isCity`/`isIx`. `miss` must be catalog ids, and `pt`/`mr` must be pids in `who`.
|
||||
- **Numbers:** clamped and stepped.
|
||||
- **Deals:** kinds from a whitelist, the other party present, `at` checked, `tier` within `PORT`, the price at most `mpCap`.
|
||||
- **Loops:** `pt` edges are dropped in (buyer, seller) pid order.
|
||||
- **Keys:** `k`/`xk` are recomputed, never trusted.
|
||||
- **Last step:** it ends with `mpBind(s)`.
|
||||
|
||||
**`mpOrphans(s)`** runs right after `:113`:
|
||||
- it drops tagged `transit`/`pni`/`links`/`peers` entries that have no deal;
|
||||
- it drops untagged rows on `mp:` networks;
|
||||
- it strips `mp`/`mpp`/`mpf` from untagged rows, so a forged `mpp:0` gives no free transit.
|
||||
|
||||
**`RK_SKIP`:** `mpx` stays off it, because `compute` reads it. Phase 1's `mp` stays on, because `compute` must never read it; the `route-skip.test.js` proxy enforces both.
|
||||
|
||||
**Size:** at most +15 KB per save.
|
||||
|
||||
## 7. Ordered steps
|
||||
|
||||
Each step ends with `npm test` green, the i18n check clean, MCP classification, a CHANGELOG bullet and perf numbers.
|
||||
|
||||
**1. Dormant core (no server, no UI).**
|
||||
- `45-player-carriers.js`.
|
||||
- `80-new-game.js:4`; `50-sanitize.js:21`/`:113`.
|
||||
- `30-compute.js`:
|
||||
- `:28` bind check;
|
||||
- `:53-54` `mpf` and `miss`;
|
||||
- `:61` `if(!p.mp)`;
|
||||
- `:62` `*(p.mp?mpPniF(p):1)`;
|
||||
- `:70` `xk`;
|
||||
- `:95` `mpDem`;
|
||||
- `:130`/`:16` the players column;
|
||||
- `:375-382` `V.mp`.
|
||||
- `40-billing.js:9`; `40-ports.js:21`.
|
||||
- **Guards:**
|
||||
- `lagT`/`lagP`/`cancelTransit` (`20-pops-transit-ix.js:6,7,11`), `unpeer`/`cancelPni` (`40-sites-peering-caches.js:16,30`) and `downT` (`21-ix-downgrade.js:6`) route to `mpEnd` or a renegotiation offer;
|
||||
- `cleanPipe` (`80-security-and-china.js:8`) refuses `mp` rows;
|
||||
- `trExits` (`50-traceroute.js:20`) applies `miss`, and `hotPorts` (`80-hot-ports-and-rank.js:4`) applies `mpf`;
|
||||
- `connUp` (`40-connections.js:18`) shows no upgrade for these rows;
|
||||
- the intern (`95-standing-orders.js:155,180,250`) skips `mp` rows;
|
||||
- `upLink`/`rmLink`/`setStandby` (`60-links.js:2,6`).
|
||||
- `src/agent/30-docs.js`.
|
||||
- **Tests:** `mp-sanitize`, and `mp-transit` with `S.mpx` injected.
|
||||
|
||||
**2. Deals and transit, end to end.**
|
||||
- `scripts/lib/mp-deals.js` and the `mp.js` routes and timers.
|
||||
- The card fields.
|
||||
- `89-player-deals.js`, called from `10-day-tick.js:10`.
|
||||
- `90-actions/92-player-deals.js`, classified in `src/agent/20-commands.js`.
|
||||
- `95-modals/49-player-deals.js`: a Deals tab in the session sheet, a bottom sheet at 360 px.
|
||||
- `90-noc-window.js:45`; `decomImpact`; all six languages.
|
||||
- **Tests:** `mp-deals-server`, and `mp-transit` with `fetch` mocked.
|
||||
|
||||
**3. Peering and player traffic.**
|
||||
- `pni`/`ix` deals, `mpIx`, and `36-mp-traffic.js` with its hook at `:343`.
|
||||
- The `V.eyeballs` factor, `R.mpSess` and the star.
|
||||
- Player Gbps in the PNI list and the connections list.
|
||||
- **Test:** `mp-peering`.
|
||||
|
||||
**4. Competition:** `clComp`, poaching, tenders.
|
||||
|
||||
**5. Shared fiber:** waves, IRUs, seats.
|
||||
|
||||
**6. `scripts/mp-soak.js`:** opt-in, never part of `npm test`.
|
||||
|
||||
## 8. Performance budget
|
||||
|
||||
**Single-player.** Each `compute()` costs one string comparison, one property read per transit and PNI row, and one more `ACN` column per edge.
|
||||
- `npm run perf -- --base-ref origin/main` must stay within noise (≤1%).
|
||||
- `emptyR()` gains no keys; `R.mp`, `R.mpSess` and `V.mp` exist only when `S.mpx` is set.
|
||||
|
||||
**Multiplayer.** The carrier mechanics are measured above: 32.3 → 33.2 ms. A new `big-network-mp` workload (the fixture plus 11 players and 20 deals, built by `scripts/perf-mp-fixture.js`) must meet:
|
||||
- `mpTraffic` ≤ 1.5 ms (one exit sort per POP, then O(players×exits), with paths cached for each pair of cities);
|
||||
- `mpBind` ≤ 0.1 ms;
|
||||
- warm `compute` ≤ +5% compared with the same fixture without players.
|
||||
|
||||
A cold route happens only when `xk` changes, at most once a game day. Report jsdom and `--browser` numbers.
|
||||
|
||||
## 9. Test plan
|
||||
|
||||
**`mp-deals-server`** (spawned server, temporary directory):
|
||||
- every transition and who may make it (403/409);
|
||||
- the policy outcomes for `ix` (live, no, offer);
|
||||
- 409 `loop` on A→B→C→A;
|
||||
- the limits;
|
||||
- the `unbuilt`, `idle` and `left` ends, and expiry, with an injected clock;
|
||||
- card validation;
|
||||
- restart persistence.
|
||||
|
||||
**`mp-transit`:**
|
||||
- the buyer's exit and label, `transitMo` using `mpp`, `isTier1` false;
|
||||
- `mpf` scales capacity, and `miss` blocks reach and changes `xk`;
|
||||
- the seller's demand rises by `u`, `V.mp` follows the formula, and the seller keeps Tier 1;
|
||||
- an idle buyer gives zero load and revenue;
|
||||
- a forged `mpp` is stripped;
|
||||
- worker parity (the `route-worker.test.js` pattern);
|
||||
- no `Math.random` calls;
|
||||
- the inbox is never applied mid-day.
|
||||
|
||||
**`mp-peering`:**
|
||||
- a PNI carries traffic only once both ends are ready;
|
||||
- de-peering raises transit p95;
|
||||
- two unpeered Tier 1 players lose revenue, and both stay Tier 1;
|
||||
- 24 player PNIs leave `R.sessions` unchanged;
|
||||
- C reaches B through A's cone;
|
||||
- the route-server rule is two-sided;
|
||||
- the PNI lead time is stable.
|
||||
|
||||
**`mp-sanitize`:**
|
||||
- fuzzing does not throw and stays bounded: 1,000 entries, HTML in names, loops, unknown ids, `mp:` rows in a single-player save;
|
||||
- old saves load;
|
||||
- a multiplayer-to-single-player slot switch clears every `mp:*`;
|
||||
- `<img onerror>` stays text in the panels and the Deals sheet at 360 px.
|
||||
|
||||
**`mp-competition` and `mp-fiber`:**
|
||||
- rival players raise `clComp`;
|
||||
- gifts are validated;
|
||||
- every client derives the same tender;
|
||||
- cuts are copied;
|
||||
- a bought wave can't be upgraded.
|
||||
|
||||
**Existing gates:**
|
||||
- `route-skip` (same digest with `S.mpx` null or empty), `compute-idempotent`, `routing-reference`, `route-cache`;
|
||||
- `gameplay-rules`, plus a check that no `mp:` id is in `NETS`/`NSH`;
|
||||
- `persist`, `save-size`, `save-text`, `mcp-commands`, `i18n`, `pages`, `build`, `multiplayer`, `mp-server`.
|
||||
|
||||
**Soak test (the "hardcore" local run):**
|
||||
- The server plus 12 seeded jsdom players in `worker_threads` (about 0.5 GB each, with `--jobs` capped).
|
||||
- Each plays about 2,000 days at its own speed, with a random agent making, answering and ending deals.
|
||||
- During the run: server restarts, reloads through `migrate`, a player leaving, tampered cards and a burst of 409s.
|
||||
- It checks: no errors or NaN, an acyclic deal graph, each seller's `V.mp` matching the buyer's bill, every save reloading, and a single-player control game keeping `main`'s digest.
|
||||
|
||||
## 10. Failure modes
|
||||
|
||||
| Case | Handling |
|
||||
|---|---|
|
||||
| The other player is paused or offline | Their last card stands: an idle buyer brings no load or money, and a buyer keeps the seller's last values. After 14 days the server ends the deal (`idle`) |
|
||||
| A player leaves | The deal ends (`left`) and each side tears down after notice. `mpBind` drops the carrier on the next sanitize |
|
||||
| Server down | Play goes on with the frozen `S.mpx`. New deals fail with one toast |
|
||||
| Two devices | Phase 1's seq/409 picks the save; `made` settles the rows |
|
||||
| Version skew | Unknown `miss` ids are dropped; networks the seller's build lacks count as reachable |
|
||||
| Tampered card or save | Whitelists, clamps, steps, local price caps, orphan stripping. Money comes only from local formulas |
|
||||
179
docs/plans/next-session.md
Normal file
179
docs/plans/next-session.md
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
# What is left (as of 2026-11-09)
|
||||
|
||||
Work in this fork, pushed to the `vanvik` Forgejo remote (never to `origin`). Written on top of 3e30621, with the
|
||||
batch of fixes below ("Built in the batch of 2026-11-09"). Nothing below is switched on or built unless it says so.
|
||||
|
||||
## Built so far
|
||||
|
||||
On top of upstream, merged up to 3.3.0 (61e31c5 "Merge upstream: Lambda Bazaar, traffic badges, moving customers and
|
||||
faster routing (3.3.0)"; earlier merges 032470f and 4b922ab):
|
||||
- **Build standard**: 2b48a6a "A build standard for the whole network, kept by the intern", and fbae6fc "The build
|
||||
standard owns the router model and the line system; one owner per fiber" (the router model and line system are
|
||||
picked in the sheet only; the `routers` and `optup` orders read them from there).
|
||||
- **Multiplayer phase 1** for self-hosted copies: 95aa9b6 "Multiplayer for self-hosted copies: sessions, server-side
|
||||
saves, a leaderboard" (`docs/MULTIPLAYER.md`).
|
||||
- **Dark mode (#80)**: 2cd6b71 "Dark mode: Light, Dark or Auto under Settings › Theme".
|
||||
- **IPv4 address space (#150)**: eac0604 "IPv4 address space: scarce, bought, leased, leased out; IPv6 is free", and
|
||||
69328ce "IPv6-only broadband: 464XLAT city by city, a NAT64 pool next to CGNAT".
|
||||
- **Express fiber (#58)**: 8e1f2d6 "Express fiber: light a wave through a city without its router".
|
||||
- **Satellite teleports (#83)**: e1ae8e0 "Satellite teleports: GEO and MEO circuits for islands and remote towns".
|
||||
- A fix after the 3.1.0 merge: e8808f6 "The connections list no longer breaks on a 400G fabric port".
|
||||
- **Server-run play, parts 1 and 2** (merged, not switched on): T1 is d1e127d "Server-run play, part 1: game
|
||||
prerequisites and shared contracts". T2 is 065c922 "Server-run play, part 2: the engine" with its fixes c5c7ea9,
|
||||
72f31e8, 3b8c331, 9597d89, 77f4035 and 3e30621. The design, its status and what building T2 changed in it are in
|
||||
`docs/plans/server-run.md`.
|
||||
|
||||
### Built in the batch of 2026-11-09
|
||||
|
||||
Nine commits after 3e30621, the one that wrote this list and "Review fixes for the small-fix batch" (folded into
|
||||
the entries below); every code change comes with its test:
|
||||
- 8068a45 "Plans: the server-run design in the repo, what is left now, and the fork's files" (this file,
|
||||
`server-run.md`, the fork's files in `ARCHITECTURE.md`, a note in `MULTIPLAYER.md`).
|
||||
- **Dark mode (#80)**, 27ffa33: red text is `--tx-red` (a lighter red at night) everywhere it is text, in the styles
|
||||
and in 19 game files; fills, borders and bars that carry white letters keep `--bad`. The market's Hot and Cool tags
|
||||
take `--tint-o`/`--tx-amber` and `--tint-b`/`--tx-blue`. `tests/dark-mode.test.js` fails on any new
|
||||
`color:var(--bad)`. Decided not to: light mode's `--bad` on white (3.24, under AA) stays as upstream has it.
|
||||
- **IPv4 (#150)**, 7930d33: IPv4 notices in the notification log open the Address space (log target `{a:'ip4'}`,
|
||||
`ip4Open` in `NOC_GO`); with IPv4 off since, they open the bank.
|
||||
- **Satellites (#83)**, 2dc8274: the "no subsea cable lands here" hint (#321) names a satellite circuit where one can
|
||||
reach the city, with a "From X" button per teleport (up to four) to the order sheet (`satNoCable()`), or where a teleport would
|
||||
have to go. It covers only the city the hint names.
|
||||
- **Express fiber (#58)**, ae78e82: a regen site added later charges a regen card per express channel on its fiber
|
||||
(`regenAddCost()`, used by the action, the button's price and the MCP quote); a dirty connector (loss with
|
||||
`glass:true`) dims every express on the fiber (`xpGlassF()`), and the express panel names the fiber. Decided not to:
|
||||
an MTU mismatch, microbursts and a marginal optic's CRC errors stay with the fiber's own routers and optics, which an
|
||||
express passes by (as an optic failure already did, while amp-hut and ROADM incidents darken expresses).
|
||||
- **Satellites (#83)**, 1f76639: selective networks refuse to peer where a satellite circuit is the island's or
|
||||
town's only way out (`satOnly()`: a fiber or cable with no optics of its own does not count): 60 in 100 refuse a
|
||||
GEO hop, 15 in 100 a MEO one, each network's answer fixed; a session already there stops carrying until a wave or
|
||||
cable is lit. Decided not to: a worse traffic ratio for MEO,
|
||||
refusals at exchanges you run, and any effect on PNIs already there.
|
||||
- **Build standard**, 286ae48: "Bring everything up now" and the intern follow one rule: a fiber a customer's alien or
|
||||
managed wave rides keeps its line system (`dfWaveCust()`), and the sheet says why (`bstd.held_wave`); leased pairs
|
||||
and IRUs no longer hold a fiber for the intern. Left as it was: the fiber panel's own upgrade button (`ACT.upSys`)
|
||||
still swaps under a sold wave, with its warning toast.
|
||||
- **Standing orders**, 02b6c24: the shift's log keeps at most three broken orders, the week's tally no longer makes an
|
||||
empty list of places, and `opsTidy()` is gone (`tests/canonical-state.test.js` passes without it).
|
||||
- **IPv6-only broadband (#150)**, 417160f: the build standard's "Broadband: IPv6-only" row (`BSTD` `v6`, shown only
|
||||
while `ip4On()`). `bstdPlan()` makes one job per dual-stack broadband city (`ip6Todo()`), the most dual-stack homes
|
||||
first, priced as the whole swap (`ip6Cost()`); the button and the `std` order start one only with all of it above
|
||||
the floor on top of what running swaps still owe (`ip6Owed()`), and the order counts it against its month's budget.
|
||||
What running swaps owe, whoever started them, is set aside for every later job: the button's, and every standing
|
||||
order's (`X.ow` in `opsShift()`, refreshed when the `std` order starts a swap). Decided not to: a separate hold in
|
||||
`ip6Day()` at the cash floor; with the money set aside, the swaps pay down to the floor at most.
|
||||
|
||||
## The user's answers (2026-11-09)
|
||||
|
||||
The four questions of the server-run design:
|
||||
1. A player who joins an old session starts on the **session's date**: one shared calendar. The game's day-0 rules
|
||||
then have to count from each network's own start (`server-run.md`, "What Q1 changes").
|
||||
2. Single player in a multiplayer build runs **on the server** by default; "this device" stays an option.
|
||||
3. An empty session that wakes runs at **1×**.
|
||||
4. Phase-1 sessions **start fresh**: nothing is migrated.
|
||||
|
||||
## On hold until the user says go
|
||||
|
||||
- **#97 co-op companies** (several players run one network, with roles, budgets and approvals).
|
||||
- **Multiplayer phase 2** (players as carriers in each other's simulations: transit, peering, PNIs, shared fiber):
|
||||
design in `docs/plans/multiplayer-phase2.md`. When it restarts, that design needs rework for the shared server clock:
|
||||
it assumes each player's own clock, and tenders and notice timed in real minutes.
|
||||
- **#144 directional traffic**, last and on its own: keep the totals, split them by traffic profile, utilization is the
|
||||
busier direction. It comes after #58 because both touch link capacity (express channels count too).
|
||||
|
||||
## Open questions waiting for the user
|
||||
|
||||
Asked on 2026-11-09, not answered yet:
|
||||
1. ~~**Late joiners' prices and beginner grace.**~~ *Answered 2026-11-11 ("late joiners get a late joiners bonus and a
|
||||
year of double income per Gbps of FTTP sold/provided") and built: the day-0 rules count from the network's own start
|
||||
(`S.day0`, `netAge()`), and a network that joins after day 180 gets a hardware top-up and its first year of home
|
||||
broadband matched (`60-features/81-late-joiners.js`, gameplay rule F11). Dormant until T3 passes a start day.*
|
||||
2. **Other players' POPs on the map.** Draw other players' POPs and links on your map (from their cards) as part of
|
||||
the server-run work, or wait for phase 2?
|
||||
3. **The other modes in a multiplayer build.** Sandbox, scenarios, puzzles and the weekly keep running on the device.
|
||||
Fine, or should sandbox (or all of them) also run on the server?
|
||||
4. **Dark mode and the build standard upstream.** Upstream contributors have said they will open pull requests for a
|
||||
dark mode (#80) and a bulk redundancy kit (#317), and a three-tier router standard sits on another contributor's
|
||||
branch (#315). Offer the fork's dark mode and build standard upstream before those land, or keep them fork-only and
|
||||
settle the clash at the next merge?
|
||||
5. **#58 whole-fiber splicing.** Is the express lightpath enough, or should a whole fiber pair also splice through a
|
||||
city (one dark fiber A–C through B, with no ROADM at B)? The issue asks for "waves and/or entire fibers".
|
||||
6. ~~**#83 WISP zones and a rented LEO tier.**~~ *Answered 2026-11-11 ("wisp and leo please") and built: Starblink
|
||||
LEO circuits from a gateway at a teleport on your fiber (level 5), and Island Wi-Fi for 18 zones of outer islands
|
||||
over GEO, MEO or Starblink and a spur cable (`60-features/45-teleports.js`, `60-features/46-wisp-zones.js`, gameplay
|
||||
rules O8, W6 and F12).*
|
||||
7. ~~**Investors' cut of IPv4 lease income.**~~ *Answered 2026-11-11 (yes) and built: investors on a revenue share
|
||||
take their cut of IPv4 lease income, as of fiber pairs leased out; a sale stays all the player's.*
|
||||
8. **Founding an exchange on a basic router.** Founding your own exchange gives a 400G port even where the POP's router
|
||||
only takes 100G, though the shop would not sell that port. Document it as a limitation, block founding until the
|
||||
router takes 400G, or found at the router's largest port size? (`tests/server-sim-prereqs.test.js` asserts today's
|
||||
behaviour.)
|
||||
9. **The six old wip worktrees.** They hold nothing `main` lacks. Delete them and their branches?
|
||||
|
||||
## Next
|
||||
|
||||
- **After the user's go:** T3 (host and protocol), T4 (the browser client) and the integration of server-run play,
|
||||
as `docs/plans/server-run.md` describes them, with the corrections at its top. The game's side of the Q1 work is
|
||||
built (`S.day0`, the day-0 rules, `begin.day`, `CLOCK.off` gone, the late joiner's head start); T3 sends the start
|
||||
day, checks every network's day after each tick and replaces the line-up of 4.7 ("What Q1 changes").
|
||||
|
||||
## Known limitations of what shipped
|
||||
|
||||
- **Multiplayer (phase 1):** each browser runs its own clock, so the players' worlds drift apart (server-run play fixes
|
||||
this for new sessions only); other players' POPs are not drawn on the map (open question 2); cards are what each
|
||||
browser reports, and the server does not check them; a save over ~60 KB sends only the card when the tab closes, and
|
||||
the save goes with that device's next push; a session network still makes its save on the page, so it misses 3.3.0's
|
||||
smoother saves in the worker; the capacity market and path moves are each player's own, with no market shared
|
||||
between players; the HUD chip in phone landscape wider than 760 px has not been checked by eye (worth doing when T4
|
||||
changes the chip). Behind a reverse proxy, run the server with `--trust-proxy`, or every player shares one address's
|
||||
rate limits.
|
||||
- **Server-run engine (merged, not switched on):** a checkpoint is over its size budget, and so are a snapshot, a big
|
||||
realm's memory and a small network's day; a checkpoint written before c5c7ea9 restores close to exact, not exact; the
|
||||
engine has no per-call deadline of its own; a worker of its own whose session's loads all fail stays idle until the
|
||||
next unload; the path window would read routes the page never gets (`server-run.md`, "Corrections from building
|
||||
T2").
|
||||
- **Build standard:** the game menu's last row of tiles is not full (7 tiles, or 8 in a multiplayer game, in rows of
|
||||
3). The sheet's quote and "Bring everything up now" judge a line-system swap without routing (`bstdDarkOk()`: a
|
||||
quiet fiber, under 10% of its capacity, or a parallel link with room; any express with traffic holds its fibers,
|
||||
`bstdXpBusy()`), so the quote is the bill; only the intern routes to test. A quiet fiber with no way around can
|
||||
still go dark from the button for a day. A fiber a customer's alien or managed wave rides keeps its line system for
|
||||
both the button and the intern (`dfWaveCust()`); the fiber panel's own upgrade button still swaps it, with only a
|
||||
toast to warn. `bstdSet` accepts the `v6` target while IPv4 is plentiful: it is saved, hidden and never planned. An
|
||||
old save's `routers.model` moved into the standard (only from a running
|
||||
order with an intern hired; a paused one's is dropped) also becomes what new POPs get. A model or line system in the
|
||||
standard is a ceiling for the `routers` and `optup` orders (their next-one-up rule only applies with "keep"), as an
|
||||
order's own model was before; `optup` has no per-POP exceptions, so it moves fiber at POPs excepted from `std` too.
|
||||
- **Dark mode (#80):** the share card PNG and the web manifest stay light; the WebGL map was checked by tests only, not
|
||||
by eye in a real GPU browser.
|
||||
- **IPv4 (#150):** the intern does not manage addresses (optional in the issue); transfers are instant (real ones take
|
||||
weeks); blocks granted to old saves can be sold after two years (a one-off windfall); CGNAT annoyance costs refunds
|
||||
but does not slow broadband growth.
|
||||
- **IPv6-only broadband:** no one-off grumble while a city's home routers are swapped; a new home in an IPv6-only city
|
||||
pays its router even when cash is short (a running cost, so a finished city never looks like a stopped swap). The
|
||||
NAT64 ratio is not in the build standard (the swap is), and the standard starts a swap only with the whole of it to
|
||||
spare, stricter than the city panel's button (the first day's routers).
|
||||
- **Express fiber (#58):** a whole fiber pair does not splice through a city (every fiber end is a POP; expresses
|
||||
cover the need; open question 5). Of a fiber's own incidents only the dirty connector dims its expresses; MTU,
|
||||
microbursts and a marginal optic stay with its routers and optics.
|
||||
- **Island Wi-Fi (#83):** a zone's traffic enters at its own city's POP, so Starblink serves it only from a gateway in
|
||||
that city (16 of the 18 zones; a gateway anywhere in reach would serve the same 16): Nunavut and Southeast Alaska lie
|
||||
beyond the 56° shell and MEO's ring, so they stay on GEO (Southeast Alaska keeps its spur). One circuit, one move
|
||||
and one spur per zone; a standby satellite pays full rent; no standing order for island backhaul, no zones on the
|
||||
map or the multiplayer card, no rain fade. The spurs follow real domestic cables: Tahiti to the Tuamotus and
|
||||
Marquesas (Natitua), Tonga's domestic cable (cut by the Hunga Tonga eruption in 2022), Papua New Guinea's Kumul,
|
||||
the Solomons' and the Maldives' domestic networks, the Bahamas' and Cape Verde's inter-island cables, and Southeast
|
||||
Alaska's.
|
||||
- **Satellites (#83):** the rented GEO and MEO circuits never
|
||||
fail (no rain fade or sun outage; Pie in the Sky has its own); no island volcano or Caribbean and Pacific hurricane
|
||||
events; no "Island Hopper" scenario; no footprints on the map; no satellite tab in the drag-to-link window (ordering
|
||||
is from the city panel; the no-cable hint offers a teleport's order sheet only for the city it names); selective
|
||||
networks judge a satellite-only island by fixed shares (60 in 100 refuse GEO, 15 in 100 MEO), not by its traffic;
|
||||
GEO/MEO losses and prices are design numbers; well-cabled islands (Wellington, Hobart) also count as "can be
|
||||
served"; MEO needs 5° elevation (10° would drop 416 pairs); Pitcairn's $120k satellite grant stays Pie-only.
|
||||
|
||||
## Housekeeping
|
||||
|
||||
- `npm run perf -- --browser` runs with `PERF_CHROME=/usr/bin/chromium`.
|
||||
- The phase-1 playtest on port 8090 runs from its own checkout outside the repo, with its data in
|
||||
`mp-data/playtest`: leave it alone unless the user asks. Its one session can go once a server-run build replaces it
|
||||
(answer 4).
|
||||
- The six old wip worktrees under `.claude/worktrees/` wait for the user's answer (open question 9).
|
||||
123
docs/plans/pie-in-the-sky.md
Normal file
123
docs/plans/pie-in-the-sky.md
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
# Pie in the Sky (implementation spec)
|
||||
|
||||
Local branch `pie-in-the-sky`. Never push. Commit as `Frederic Jung <frederic@jc-ix.net>`, no attribution
|
||||
trailers (CLAUDE.md). Full design doc lives in Claude Docs; this file is the contract for the code.
|
||||
|
||||
## What it is
|
||||
|
||||
The endgame for players who just became Tier 1 in a save started on this version (and sandbox from day 0):
|
||||
found a rocket company, launch thousands of satellites ("pies") into shells ("crusts"), build dedicated
|
||||
base stations ("pie dishes") everywhere, and connect them with your own backbone. Obscenely expensive.
|
||||
Satirical tone: a cartoon Founder (no real person) who breaks every promise by a year; a press office that
|
||||
calls every failure a success. All names are puns (rule N2); add each real name riffed on to `REAL_NAMES`.
|
||||
|
||||
## Gate (rule O1)
|
||||
|
||||
- `newGame()` sets `pieV:1, pie:null`. `sanitize()`: missing `pieV` -> 0, so old saves never get it.
|
||||
- Unlock fires only on the transition in `checkGoals()` where `g.win&&!S.won` flips `S.won`, when `S.pieV>=1`.
|
||||
- Sandbox (`gatesOpen()` / open gates): available from day 0, real prices, `book.wouldHave` shame counter.
|
||||
- Losing Tier 1 (`!(S.won&&isTier1())`): everything keeps working; no new launches, dishes, factory orders.
|
||||
- Never in puzzles, Architect, scenarios, weekly challenge.
|
||||
|
||||
## State
|
||||
|
||||
```
|
||||
S.pieV
|
||||
S.pie = null | {born, co:{name}, fac:bool, rd:{reuse:bool,heavy:bool,heavyTests:int},
|
||||
pads:[{city,next,boosters:[{id,flights}]}],
|
||||
crusts:{short|frozen|upper|flaky:{cohorts:[{n,day,las}], queued}},
|
||||
dishes:[{id,city,ant,down}], lic:{[cc]:{state,until}}, q:[launches],
|
||||
founder:{posts:[...last 20], promises, broken, due, jit, next, kid, bill, nerv, hype, leak, mars}, (antics: 60-features/99-pie-jitters.js) book:{spent,earned,wouldHave},
|
||||
spat:{...active geopolitical spats}, safe:bool}
|
||||
```
|
||||
Pies are cohorts, never one object per satellite. `sanitize()` clamps all of it.
|
||||
|
||||
## Catalog (`src/game/10-catalog/70-pie.js`), all prices x `PIE_MUL` x `hwMul()`
|
||||
|
||||
| Item | One-off | Running |
|
||||
| --- | --- | --- |
|
||||
| Found company | $250M | $5M/mo |
|
||||
| Pie factory | $1B | $8M/mo, 120 pies/mo |
|
||||
| Pie | $0.5M (+$0.25M lasers) | - |
|
||||
| Launch pad (coastal/beach city with a POP) | $400M | $2M/mo, equatorial -15% per launch |
|
||||
| Falcon Punch launch | $60M, 20 pies | - |
|
||||
| Reuse R&D (Falcon Punch Again) | $500M; launch $30M; booster lost $40M | - |
|
||||
| Heavy R&D (Starshipping & Handling) | $3B; $100M/launch, 100 pies, first 3 test flights explode | - |
|
||||
| Insurance | 8% of launch, optional | - |
|
||||
| Pie dish (city with a POP) | $25M + $2M per antenna | $300k/mo |
|
||||
| Landing rights | $10M-$100M per country by market size | yearly |
|
||||
| LEO-IX port | $50M | $1M/mo |
|
||||
| Founder launch party | $2M per launch, automatic | - |
|
||||
|
||||
Crusts: short 550 km / 1584 full / |lat|<=53; frozen 560 km / 520 / polar; upper 1100 km / 1200 / |lat|<=60;
|
||||
flaky 340 km / 2500 / dense cities, life 3y. Life 5y otherwise. Coverage < 60% = half-baked: carries 0 under 40%, then a share growing to all of it at 60% (pieCarry). Pies wear out over the last 30% of their life, a few a day (pieAlive), not a whole launch month at once.
|
||||
|
||||
## Routing (rules O2-O4)
|
||||
|
||||
Crust > 40% = virtual hub (capacity pieCap = g x coverage x carry). Live, licensed, connected dish <-> hub edge: latency (alt up+down)/c + 2 ms.
|
||||
With lasers: hub-to-hub along great circle at c (vacuum). Capacity = min(crust cap x coverage,
|
||||
antennas x Gbps x rain). Orbit never beats fiber under ~3000 km. Graph grows by dishes + crusts only.
|
||||
Dishes with no path to the backbone carry no transit (O3), but backhaul their own POP: all its traffic (eyeballs, customers,
|
||||
circuits) goes up its dish and down at a landing dish on the backbone (bent pipe <= 1,000 km, lasers past that). Capacity =
|
||||
min(cut-off dish's room after terminals, landing dish's room, crust's room); latency = the orbit path. Spats, safe mode, a
|
||||
down crust, landing rights or a backhoe cut it. Must not slow `compute()` for saves without pies.
|
||||
|
||||
## Customers
|
||||
|
||||
`pizza` (homes/boats), `flywifi` (airlines, latency), `boat` (cruise). `mars` gets an orbit option only
|
||||
in `pieV` saves. Remote cities (Pitcairn, Arctic) servable from orbit.
|
||||
|
||||
## Incidents (`rule('chaos')`, quiet 90 days after unlock)
|
||||
|
||||
Rapid Unscheduled Disassembly, booster falls over, solar storm (safe mode), food fight (debris, rare,
|
||||
Space Roomba fix), rain fade, backhoe at the dish, astronomers (VisorSat), Founder posts at 3 a.m.,
|
||||
chaos monkey snips a laser link.
|
||||
A solar storm also puts Starblink, the rented LEO tier at your teleports (#83), in safe mode for a day or two.
|
||||
|
||||
## Geopolitical spats (cartoon, even-handed, countries as data, never real leaders)
|
||||
|
||||
Reuse the existing sanctions / sovereign-drill / China licence machinery where it fits.
|
||||
- Landing rights: each country licenses separately; big markets cost most; some refuse for a while.
|
||||
- Data stays home: a country requires an in-country pie dish for its customers.
|
||||
- Spectrum squabble: two neighbours both want the same band; pick a side, the other closes for 180 days.
|
||||
- Kill switch, please: a government wants an off switch during "national exam week"; comply (customer
|
||||
mood drop) or refuse (licence suspended 90 days).
|
||||
- Orbital land grab: a rival constellation's home regulator files first; your next crust costs more.
|
||||
- Jamming near a border: capacity over a region drops for some days.
|
||||
- Launch diplomacy: a country offers a subsidised pad if you build 3 dishes there.
|
||||
- Not over my airspace: two countries each demand their traffic avoid the other's dishes.
|
||||
Each spat is a notification with 2 choices; outcomes deterministic per seed.
|
||||
|
||||
## Government money (`60-features/99-pie-subsidies.js`, a section of the bank)
|
||||
|
||||
- Rural Digital Pie Fund: reverse auctions for towns only orbit reaches (a cut-off POP on backhaul, or a small town of
|
||||
your terminal customers). You ask 90%, 70% or 50% of the reserve; a rival asks 40-100%; the lower ask wins and is paid
|
||||
monthly for 5 years. From a 90-day deadline the town's service, averaged per month, must stay at 70%, or the award is
|
||||
revoked and half of what it paid is clawed back. Counts in `book.earned`.
|
||||
- Ex-Im Pie Bank: a BANKS loan (never offered by the usual banks) of half the value of the pies flying and booked, at most
|
||||
20% of a full Shortcrust (O7 counts it), 1.5-2.5% over 60 months. Covenants: launch n pies in a year, keep a dish in the
|
||||
lending country. A breach: the bank's penalty, +3 points, the launch deadline moved, and with chaos a spat there
|
||||
(`home` or `lic`). Off the books: financing, not orbit income.
|
||||
- Pitcairn: served from orbit (its POP on backhaul, or home terminals there) at 90% of its demand, latency forgiven, the UK
|
||||
pays `GRANT_SKY_MO` instead of `GRANT_MO`. Counts in `book.earned`.
|
||||
|
||||
## Visualisation: a separate animated 3D globe
|
||||
|
||||
Satellites are NEVER drawn on the existing map (no cost there). The map only gets static pie dish icons
|
||||
at POPs, drawn with the existing city layer. Satellites live on an animated 3D globe (orthographic
|
||||
projection on a 2D canvas, no WebGL, no library) inside the Pie Control panel, rendered only while it is
|
||||
open, paused when hidden, capped frame budget, fewer dots on phones. Final look is chosen from mockups.
|
||||
|
||||
## Rules O1-O7 (`gameplay-rules` skill + tests)
|
||||
|
||||
O1 gate, O2 half-baked carries nothing / capacity <= dishes, O3 disconnected dish no transit, O4 vacuum
|
||||
latency, never beats fiber < 3000 km, O5 chaos + 90 quiet days, O6 rideshare <= demand,
|
||||
O7 fresh Tier 1 cannot afford a full Shortcrust in year 1; full constellation never pays back < 5 years.
|
||||
O8 (the rented LEO tier, #83): Starblink sells no new gateway, circuit or growth once a crust of yours carries
|
||||
traffic; circuits already rented keep running, billed with the teleports, never on `S.pie.book`.
|
||||
|
||||
## Every change
|
||||
|
||||
Translated strings via `scripts/i18n-add.js` (0/0/0), sanitize, phones first, a seeded test
|
||||
(`tests/pie-in-the-sky.test.js` and friends), perf vs `main` (`npm run perf -- --base-ref main`) must not
|
||||
get worse, CHANGELOG bullet under `## [Unreleased]`.
|
||||
1433
docs/plans/server-run.md
Normal file
1433
docs/plans/server-run.md
Normal file
File diff suppressed because it is too large
Load diff
893
package-lock.json
generated
893
package-lock.json
generated
File diff suppressed because it is too large
Load diff
16
package.json
16
package.json
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "seriesoftubes",
|
||||
"version": "1.37.0",
|
||||
"version": "3.5.0",
|
||||
"description": "A cartoon browser game about building the internet.",
|
||||
"private": true,
|
||||
"license": "MIT",
|
||||
|
|
@ -11,19 +11,27 @@
|
|||
},
|
||||
"scripts": {
|
||||
"test": "node scripts/test.js",
|
||||
"test:timings": "node scripts/test-timings.js",
|
||||
"build": "node scripts/build.js",
|
||||
"i18n:check": "node scripts/i18n-check.js",
|
||||
"i18n:fix": "node scripts/i18n-check.js --fix",
|
||||
"dev": "node scripts/dev.js",
|
||||
"page": "node scripts/lib/page.js",
|
||||
"serve": "npm run build && npx --yes serve@14.2.4 _site",
|
||||
"perf": "node scripts/perf-bench.js"
|
||||
"perf": "node scripts/perf-bench.js",
|
||||
"bench:gpu": "node scripts/gpu-bench.js",
|
||||
"mcp": "node scripts/mcp.js",
|
||||
"mcp:browser": "node scripts/mcp.js --browser",
|
||||
"mp": "node scripts/mp-server.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"devDependencies": {
|
||||
"jsdom": "24.1.3",
|
||||
"playwright-core": "1.56.0"
|
||||
"@modelcontextprotocol/node": "2.1.2",
|
||||
"@modelcontextprotocol/server": "2.4.0",
|
||||
"jsdom": "31.0.0",
|
||||
"playwright-core": "1.65.0",
|
||||
"ws": "8.22.1"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
115
scripts/agent/relay.js
Normal file
115
scripts/agent/relay.js
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
#!/usr/bin/env node
|
||||
// The agent relay: a WebSocket router between the game page and tool clients. The page (src/agent/80-relay.js, agent
|
||||
// mode in Settings) connects as the one "page"; tools (the MCP server, a script) connect as "tool" peers and send
|
||||
// {kind:'call', id, tool, args}, which the relay routes to the page and back as {kind:'result', id, ...}. It holds no
|
||||
// game state and knows no game logic: a dumb router (every client states its role; there is no token), so the whole
|
||||
// player/operator boundary stays in the page's facade and in the driver.
|
||||
//
|
||||
// The relay rides the page's own HTTP server, on the same port, at the path AGENT_PATH: there is no second port, and
|
||||
// the page infers its endpoint from where it was loaded (location.host). `npm run dev` hosts it in-process
|
||||
// (scripts/dev.js); `createRelay({ server })` is the whole file, shared by the dev server and the tests.
|
||||
//
|
||||
// Security: no token. The bind address is the dev server's --host, loopback unless the operator chooses otherwise;
|
||||
// what can reach that address may drive a game whose player turned agent mode on. What no bind address opens up: a
|
||||
// website in the player's browser dialing the relay. Browsers send Origin on every WebSocket handshake and Node
|
||||
// clients do not, and an Origin that does not name this very host (the page's own server) is refused below.
|
||||
// Same-origin alone would let DNS rebinding through (evil.example re-pointed at 127.0.0.1 is "same-origin" with
|
||||
// itself), so the Host must also be an address, never a name: an IP literal, localhost or *.localhost. Every client
|
||||
// still states its role before anything routes, and one page at a time: a new page replaces the old one (a reload).
|
||||
const { WebSocketServer } = require('ws');
|
||||
|
||||
const AUTH_MS = 5000; // a client must state its role within this, or the socket closes
|
||||
const AGENT_PATH = '/agent'; // the relay's path on the page's own HTTP port
|
||||
|
||||
// `server`: the http.Server that serves the game page. The WebSocket rides it, same port.
|
||||
// Host header → whether it names this machine by address (IP literal, localhost) rather than by a
|
||||
// DNS name someone else controls.
|
||||
function hostOk(h) {
|
||||
if (typeof h !== 'string' || !h) return false;
|
||||
let name;
|
||||
try { name = new URL(`http://${h}`).hostname.toLowerCase(); } catch { return false; }
|
||||
return name === 'localhost' || name.endsWith('.localhost') || /^\[[0-9a-f:.]+\]$/.test(name) || /^\d{1,3}(\.\d{1,3}){3}$/.test(name);
|
||||
}
|
||||
|
||||
function createRelay({ server } = {}) {
|
||||
if (!server) throw new Error('createRelay needs the http.Server that serves the page');
|
||||
const wss = new WebSocketServer({ server, path: AGENT_PATH });
|
||||
let page = null; // the one connected game page
|
||||
const tools = new Set(); // connected tool clients
|
||||
const pending = new Map(); // relay-scoped call id → {tool, id, page}
|
||||
let seq = 0;
|
||||
|
||||
const send = (ws, o) => { if (ws.readyState === 1) ws.send(JSON.stringify(o)); };
|
||||
// Presence goes both ways: tools learn whether a page is connected, the page learns how many
|
||||
// tools are — agent mode holds the game's clock while none are (src/agent/80-relay.js).
|
||||
const presence = () => {
|
||||
const p = !!(page && page.readyState === 1);
|
||||
const n = [...tools].filter((t) => t.readyState === 1).length;
|
||||
for (const t of tools) send(t, { kind: 'presence', page: p });
|
||||
if (page) send(page, { kind: 'presence', tools: n });
|
||||
};
|
||||
|
||||
wss.on('connection', (ws, req) => {
|
||||
// Browsers send Origin on every WebSocket handshake, Node clients (our tools) never do.
|
||||
// Same-origin only, host against Host: a foreign site must not dial the loopback relay
|
||||
// and drive (or replace) the game — this closes that hole at no cost to either side.
|
||||
if (!hostOk(req.headers.host)) { ws.close(4004, 'bad host'); return; }
|
||||
const origin = req.headers.origin;
|
||||
if (origin) {
|
||||
let host = null;
|
||||
try { host = new URL(origin).host; } catch { host = null; }
|
||||
if (!host || host !== req.headers.host) { ws.close(4004, 'bad origin'); return; }
|
||||
}
|
||||
let role = null;
|
||||
const authTimer = setTimeout(() => { if (!role) ws.close(4003, 'no auth'); }, AUTH_MS);
|
||||
const dead = () => {
|
||||
clearTimeout(authTimer);
|
||||
if (ws === page) {
|
||||
page = null;
|
||||
// Answer the calls this page was sent with, so no tool waits out its timeout: the
|
||||
// call is lost (reload, tab closed, replaced), not pending — say so, at once.
|
||||
for (const [id, p] of [...pending]) if (p.page === ws) {
|
||||
pending.delete(id);
|
||||
send(p.tool, { kind: 'result', id: p.id, error: 'the game page disconnected before answering (reload or another tab took over)' });
|
||||
}
|
||||
}
|
||||
tools.delete(ws);
|
||||
for (const [id, p] of [...pending]) if (p.tool === ws) pending.delete(id);
|
||||
presence(); // tools left: the page must know, to hold its clock
|
||||
};
|
||||
ws.on('message', (data) => {
|
||||
let m; try { m = JSON.parse(String(data)); } catch { return; }
|
||||
if (!m || typeof m !== 'object') return;
|
||||
if (!role) {
|
||||
if (m.kind !== 'auth' || (m.role !== 'page' && m.role !== 'tool')) { ws.close(4001, 'bad role'); return; }
|
||||
role = m.role; clearTimeout(authTimer);
|
||||
if (role === 'page') { if (page && page.readyState === 1) page.close(4000, 'replaced'); page = ws; presence(); }
|
||||
else { tools.add(ws); presence(); }
|
||||
return;
|
||||
}
|
||||
if (role === 'tool' && m.kind === 'call' && m.id !== undefined && typeof m.tool === 'string') {
|
||||
if (!page || page.readyState !== 1) { send(ws, { kind: 'result', id: m.id, error: 'no game page connected: open the game in a browser with the relay on in Settings' }); return; }
|
||||
const id = 'r' + (++seq);
|
||||
pending.set(id, { tool: ws, id: m.id, page });
|
||||
send(page, { kind: 'call', id, tool: m.tool, args: m.args || {} });
|
||||
return;
|
||||
}
|
||||
if (role === 'page' && m.kind === 'result' && m.id !== undefined) {
|
||||
const p = pending.get(m.id); if (!p) return;
|
||||
pending.delete(m.id);
|
||||
send(p.tool, { kind: 'result', id: p.id, dayBefore: m.dayBefore, dayAfter: m.dayAfter, value: m.value, error: m.error });
|
||||
}
|
||||
});
|
||||
ws.on('close', dead);
|
||||
ws.on('error', () => dead());
|
||||
});
|
||||
|
||||
return {
|
||||
wss, path: AGENT_PATH,
|
||||
// What the relay holds right now, so tests wait for a state instead of sleeping.
|
||||
status: () => ({ page: !!(page && page.readyState === 1), tools: [...tools].filter((t) => t.readyState === 1).length, calls: pending.size }),
|
||||
close() { for (const c of [page, ...tools]) { try { c.close(4002, 'relay shutdown'); } catch {} } try { wss.close(); } catch {} },
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createRelay };
|
||||
|
|
@ -6,10 +6,13 @@
|
|||
//
|
||||
// npm run build VERSION, BUILD_DATE and OUT can be set in the environment
|
||||
// REQUIRE_NOTES=1 npm run build fail when CHANGELOG.md has no bullets for this version
|
||||
// MP_API=/api/mp npm run build a self-hosted copy with multiplayer (docs/MULTIPLAYER.md): the
|
||||
// page talks to scripts/mp-server.js at that path, same origin, and
|
||||
// has the server-run play (src/game/98-server-play/) and its SIM_ID
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { execFileSync } = require('node:child_process');
|
||||
const { shipped, ROOT } = require('./lib/page');
|
||||
const { shipped, simId, assemble, ROOT } = require('./lib/page');
|
||||
|
||||
const VERSION = process.env.VERSION || require(path.join(ROOT, 'package.json')).version;
|
||||
const BUILD_DATE = process.env.BUILD_DATE || new Date().toISOString().slice(0, 10);
|
||||
|
|
@ -19,13 +22,19 @@ const die = (msg) => { console.error(`error: ${msg}`); process.exit(1); };
|
|||
if (!/^[0-9]+\.[0-9]+\.[0-9]+([-.+][0-9A-Za-z.-]+)?$/.test(VERSION)) die(`VERSION '${VERSION}' is not a semantic version`);
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(BUILD_DATE)) die(`BUILD_DATE '${BUILD_DATE}' is not YYYY-MM-DD`);
|
||||
if (OUT === ROOT || OUT === path.join(ROOT, 'site') || OUT === path.join(ROOT, 'src')) die(`refusing to build into ${OUT}`);
|
||||
// Multiplayer is off unless MP_API names the session server's path on the page's own origin ("//host/x" would be
|
||||
// another host, and the player's token would go there).
|
||||
const MP_API = process.env.MP_API || '';
|
||||
if (MP_API && !/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(MP_API)) die(`MP_API '${MP_API}' must be a path on the same origin, like /api/mp`);
|
||||
|
||||
fs.rmSync(OUT, { recursive: true, force: true });
|
||||
fs.cpSync(path.join(ROOT, 'site'), OUT, { recursive: true });
|
||||
if (fs.existsSync(path.join(OUT, 'index.html'))) die('site/index.html must not exist: the page is assembled from src/');
|
||||
// The page and the translations ship with labels shrunk to short ids (docs/adr/0003-translations-by-label.md).
|
||||
const D = require('./lib/dict');
|
||||
const { html: page0, dicts } = shipped(Object.fromEntries(D.langs().map((l) => [l, D.read(l).dict])));
|
||||
const { html: page0, dicts } = shipped(Object.fromEntries(D.langs().map((l) => [l, D.read(l).dict])), { mp: !!MP_API });
|
||||
// Server-run play's build id: only a multiplayer build has one (scripts/lib/page.js simId()).
|
||||
const SIM_ID = MP_API ? simId(assemble({ mp: true }).html) : '';
|
||||
fs.writeFileSync(path.join(OUT, 'index.html'), page0);
|
||||
for (const [lang, dict] of Object.entries(dicts)) fs.writeFileSync(path.join(OUT, 'i18n', `${lang}.js`), D.format(lang, '', dict));
|
||||
|
||||
|
|
@ -41,8 +50,16 @@ if (process.env.REQUIRE_NOTES === '1' && notes === '[]') die(`CHANGELOG.md has n
|
|||
const page = path.join(OUT, 'index.html'), PH = '/*__RELEASE_NOTES__*/[]', html = fs.readFileSync(page, 'utf8');
|
||||
if (!html.includes(PH)) die('release-notes placeholder missing from the page');
|
||||
// Function replacer: no $& / $$ expansion. Escape "<" so a note can never close the <script>.
|
||||
fs.writeFileSync(page, html.replace(PH, () => notes.replace(/</g, '\\u003c')));
|
||||
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes) }, null, 2) + '\n');
|
||||
// A release can also open with a story (prose before its first bullet), shown in full in "What's new".
|
||||
const story = execFileSync(process.execPath, [path.join(__dirname, 'release-notes.js'), VERSION, '--story'], { encoding: 'utf8' }), PS = '/*__RELEASE_STORY__*/[]';
|
||||
if (!html.includes(PS)) die('release-story placeholder missing from the page');
|
||||
const PM = "/*__MP_API__*/''", PI = "/*__SIM_ID__*/''";
|
||||
if (!html.includes(PM)) die('multiplayer placeholder missing from the page');
|
||||
if (!html.includes(PI)) die('server-play build id placeholder missing from the page');
|
||||
let out = html.replace(PH, () => notes.replace(/</g, '\\u003c')).replace(PS, () => story.replace(/</g, '\\u003c')).replace(PM, () => `'${MP_API}'`);
|
||||
if (SIM_ID) out = out.replace(PI, () => `'${SIM_ID}'`);
|
||||
fs.writeFileSync(page, out);
|
||||
fs.writeFileSync(path.join(OUT, 'version.json'), JSON.stringify({ version: VERSION, date: BUILD_DATE, notes: JSON.parse(notes), story: JSON.parse(story), ...(SIM_ID ? { simId: SIM_ID } : {}) }, null, 2) + '\n');
|
||||
|
||||
// Nothing may ship half-stamped.
|
||||
const left = [];
|
||||
|
|
|
|||
|
|
@ -1,30 +1,43 @@
|
|||
#!/usr/bin/env node
|
||||
// Development server: http://localhost:8080 (PORT=… to change). The page is assembled from src/ on every
|
||||
// request, static files come straight from site/, and the browser reloads itself when you save a file.
|
||||
// The page is not version-stamped, so the game runs in dev mode (IS_DEV) like a local copy always has.
|
||||
// No dependencies: plain node:http. For the production build as GitHub Pages will serve it: npm run serve.
|
||||
// Development server: http://127.0.0.1:8080 (--host/--port, or HOST=/PORT=, to change). The page is assembled from
|
||||
// src/ on every request, static files come straight from site/, and the browser reloads itself when you save a file.
|
||||
// The page is not version-stamped, so the game runs in dev mode (IS_DEV) like a local copy always has, and it is
|
||||
// the development page: with the agent facade (src/agent/, window.TUBES) that the page players get has not.
|
||||
// The agent relay rides this same server, same port, path /agent: agent mode in the game's Settings dials it, and
|
||||
// tools (node scripts/mcp.js --browser) drive the page this server serves.
|
||||
// Binds loopback by default; --host binds wherever the operator chooses, the relay with it. Plain node:http and the
|
||||
// relay's ws. For the production build as GitHub Pages will serve it: npm run serve.
|
||||
// --mp also runs the multiplayer API (docs/MULTIPLAYER.md) at /api/mp, sessions kept in mp-data/, and turns multiplayer
|
||||
// on in the page: two browser windows (or a private one) can then play one session locally.
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
const { createRelay } = require('./agent/relay');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const PORT = +process.env.PORT || 8080;
|
||||
// --host/--port; a bare --host binds loopback (never undefined, which would listen on every interface).
|
||||
const argOf = (k) => { const i = process.argv.indexOf(k); return i >= 0 && process.argv[i + 1] && !process.argv[i + 1].startsWith('--') ? process.argv[i + 1] : null; };
|
||||
const HOST = argOf('--host') || process.env.HOST || '127.0.0.1';
|
||||
const PORT = (() => { const p = +argOf('--port'); return Number.isInteger(p) && p > 0 && p < 65536 ? p : (+process.env.PORT || 8080); })();
|
||||
const SITE = path.join(ROOT, 'site');
|
||||
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
|
||||
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
|
||||
'.webmanifest': 'application/manifest+json' };
|
||||
const RELOAD = '<script>new EventSource("/__dev").onmessage=()=>location.reload()</script>';
|
||||
const MP = process.argv.includes('--mp') ? require('./lib/mp').createMp({ dir: path.join(ROOT, 'mp-data'), createPerHour: 1000, joinPerHour: 1000, log: (s) => console.error(s) }) : null;
|
||||
const clients = new Set();
|
||||
|
||||
function page() {
|
||||
const { html, map } = assemble();
|
||||
const { html, map } = assemble({ dev: true });
|
||||
// Errors report a line of the assembled page; the console also says which file under src/ that is.
|
||||
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${JSON.stringify(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
|
||||
return html.replace('</body>', `${hint}${RELOAD}</body>`);
|
||||
const hint = `<script>addEventListener('error',e=>{const n=e.lineno,m=n&&(${lit(map)}).find(m=>n>=m.from&&n<=m.to);if(m)console.warn('↑ src/'+m.file+':'+(n-m.from+1))});</script>`;
|
||||
return (MP ? html.replace("/*__MP_API__*/''", () => "'/api/mp'") : html).replace('</body>', `${hint}${RELOAD}</body>`);
|
||||
}
|
||||
|
||||
http.createServer((req, res) => {
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
if (MP && MP.handle(req, res)) return;
|
||||
if (url.pathname === '/__dev') {
|
||||
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store' });
|
||||
res.write(': hi\n\n');
|
||||
|
|
@ -45,10 +58,26 @@ http.createServer((req, res) => {
|
|||
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
|
||||
fs.createReadStream(file).pipe(res);
|
||||
} catch (e) {
|
||||
// The stack goes to the terminal running the server, never into the response.
|
||||
console.error(e);
|
||||
res.writeHead(500, { 'content-type': 'text/plain; charset=utf-8' });
|
||||
res.end(String(e && e.stack || e));
|
||||
res.end('Could not build the page: see the terminal running npm run dev.');
|
||||
}
|
||||
}).listen(PORT, () => console.log(`Series of Tubes (dev): http://localhost:${PORT}/ — edits in src/ and site/ reload the page`));
|
||||
});
|
||||
const relay = createRelay({ server });
|
||||
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
|
||||
server.listen(PORT, HOST, () => {
|
||||
// The banner reports the socket's real address, not the flag it was asked for.
|
||||
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
|
||||
const local = /^(127\.|::1$|localhost$)/.test(ad.address);
|
||||
console.log(`Series of Tubes (dev): http://${at}/ — edits in src/ and site/ reload the page`);
|
||||
console.error(`[series-of-tubes] agent relay on ws://${at}${relay.path} (no token)${local ? '' : `: bound to ${ad.address}, so anything that can reach this address can drive a game whose player turned agent mode on`}`);
|
||||
console.error('[series-of-tubes] to let an agent play: Settings → Agent API in the game, then node scripts/mcp.js --browser');
|
||||
if (MP) console.error(`[series-of-tubes] multiplayer on: API at http://${at}/api/mp, sessions in ${path.relative(ROOT, MP.dir) || MP.dir}/`);
|
||||
});
|
||||
const shutdown = () => { relay.close(); process.exit(0); };
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
|
||||
let timer = null;
|
||||
for (const dir of ['src', 'site']) {
|
||||
|
|
|
|||
76
scripts/gpu-bench.js
Normal file
76
scripts/gpu-bench.js
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
#!/usr/bin/env node
|
||||
// The map's speed on your own graphics card, 2D against WebGL, in the browser you play in:
|
||||
//
|
||||
// npm run bench:gpu -- --save path/to/save.json (an exported save, or a plain one; default: the perf fixture)
|
||||
//
|
||||
// then open the printed address in Chrome, Edge or Firefox and press Start. Headless benchmarks (npm run perf) draw the
|
||||
// canvas in software, so they cannot say what a GPU does; this one runs where the GPU is. Each scenario plays a few
|
||||
// seconds with the 2D map and with the WebGL tubes, the table shows in the page, and the server prints it here when the
|
||||
// run ends. Options: --port N (8090), --secs N per scenario (6), --host 0.0.0.0 to open it from a phone on your network,
|
||||
// --out FILE to also write the table there. Under WSL, the Windows browser reaches http://localhost:PORT as it is.
|
||||
// In the address: ?only=gl or ?only=2d (one renderer), ?scen=x1-mid,pan (some scenarios), ?dpr=2 (a 4K screen's
|
||||
// pixels on a smaller one), ?auto (start at once). The game's clock keeps running: incidents do not pause it.
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { assemble, ROOT } = require('./lib/page');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k, d) => { const i = args.indexOf('--' + k); return i >= 0 ? args[i + 1] : d; };
|
||||
const PORT = +opt('port', 8090), HOST = opt('host', 'localhost'), SECS = +opt('secs', 6), OUT = opt('out', null);
|
||||
const SAVE = path.resolve(opt('save', path.join(ROOT, 'tests', 'fixtures', 'big-network.json')));
|
||||
const SITE = path.join(ROOT, 'site');
|
||||
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css', '.json': 'application/json',
|
||||
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json' };
|
||||
|
||||
// An exported save is {app, version, S}; a plain one is S itself.
|
||||
const save = (() => { const d = JSON.parse(fs.readFileSync(SAVE, 'utf8')); return JSON.stringify({ S: d && d.S && d.S.pops ? d.S : d }); })();
|
||||
const client = fs.readFileSync(path.join(__dirname, 'lib', 'gpu-bench-client.js'), 'utf8');
|
||||
const page = () => assemble().html.replace('</body>', `<script>window.__BENCH__=${lit({ secs: SECS })};</script><script>${client}</script></body>`);
|
||||
|
||||
/* Only the page this server hands out may talk to it. Any other site open in the same browser could otherwise
|
||||
POST results (printed to this terminal, written to --out) or, through DNS rebinding, read the save. So the Host
|
||||
header must name this server, and a POST must come from its own origin. */
|
||||
const HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', HOST.includes(':') ? `[${HOST}]` : HOST]);
|
||||
if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4') HOSTS.add(l.address);
|
||||
const hostOk = (h) => { const m = /^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/.exec(h || ''); return !!m && HOSTS.has(m[1].toLowerCase()) && (m[2] ? +m[2] : 80) === PORT; };
|
||||
const MAX_BODY = 2 * 1048576;
|
||||
// What the page sends is printed and written as text: no terminal escape sequences or other control characters.
|
||||
const plain = (s) => String(s ?? '').replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F\u2028\u2029]/g, '');
|
||||
|
||||
http.createServer((req, res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
try {
|
||||
if (!hostOk(req.headers.host)) { res.writeHead(421); return res.end(); }
|
||||
if (url.pathname === '/' || url.pathname === '/index.html') { res.writeHead(200, { 'content-type': TYPES['.html'], 'cache-control': 'no-store' }); return res.end(page()); }
|
||||
if (url.pathname === '/__bench/save.json') { res.writeHead(200, { 'content-type': TYPES['.json'], 'cache-control': 'no-store' }); return res.end(save); }
|
||||
if (url.pathname === '/__bench/results' && req.method === 'POST') {
|
||||
if (req.headers.origin !== `http://${req.headers.host}`) { res.writeHead(403); return res.end(); }
|
||||
let body = '', size = 0, over = false;
|
||||
req.on('data', (c) => { size += c.length; if (size > MAX_BODY) { over = true; req.destroy(); return; } body += c; });
|
||||
req.on('end', () => {
|
||||
if (over) return;
|
||||
try { const r = JSON.parse(body), md = plain(r && r.md); console.log('\n' + md + '\n'); if (OUT) { fs.writeFileSync(OUT, md + '\n\n```json\n' + plain(JSON.stringify(r, null, 1)) + '\n```\n'); console.log(`(also written to ${OUT})`); } } catch (e) { console.error('bad results:', e.message); }
|
||||
res.writeHead(204); res.end(); });
|
||||
return;
|
||||
}
|
||||
// The service worker would cache this page over the real one: none here.
|
||||
if (url.pathname === '/sw.js') { res.writeHead(404); return res.end(); }
|
||||
const file = path.join(SITE, path.normalize(decodeURIComponent(url.pathname)).replace(/^([/\\]|\.\.)+/, ''));
|
||||
if (!file.startsWith(SITE + path.sep) || !fs.statSync(file, { throwIfNoEntry: false })?.isFile()) { res.writeHead(404); return res.end(); }
|
||||
res.writeHead(200, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': 'no-store' });
|
||||
fs.createReadStream(file).pipe(res);
|
||||
} catch (e) {
|
||||
// A malformed address (decodeURIComponent) or a missing file: the details stay in this terminal.
|
||||
console.error('bench server:', e && e.message || e);
|
||||
res.writeHead(e instanceof URIError ? 400 : 500); res.end();
|
||||
}
|
||||
}).listen(PORT, HOST, () => {
|
||||
const s = JSON.parse(save).S;
|
||||
console.log(`GPU benchmark: ${path.basename(SAVE)} (${Object.keys(s.pops || {}).length} POPs, ${(s.links || []).length} links), ${SECS}s per scenario`);
|
||||
console.log(`Open http://localhost:${PORT}/ in your browser, press Start and keep the tab in front.`);
|
||||
if (HOST === '0.0.0.0') for (const l of Object.values(os.networkInterfaces()).flat()) if (l && l.family === 'IPv4' && !l.internal) console.log(` from another device: http://${l.address}:${PORT}/`);
|
||||
console.log('Ctrl+C to stop.');
|
||||
});
|
||||
|
|
@ -36,7 +36,7 @@ if (args[0] === '--rename') {
|
|||
for (const f of listFiles(src)) {
|
||||
if (f === 'i18n/en.js') continue;
|
||||
const p = path.join(src, f), t = fs.readFileSync(p, 'utf8');
|
||||
const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/\./g, '\\.')}\1`, 'g'), (m, q) => { n++; return q + to + q; });
|
||||
const u = t.replace(new RegExp(String.raw`(['"\x60])${from.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\1`, 'g'), (m, q) => { n++; return q + to + q; });
|
||||
if (u !== t) fs.writeFileSync(p, u);
|
||||
}
|
||||
console.log(`renamed ${from} → ${to} in every dictionary and ${n} place(s) in src/`);
|
||||
|
|
|
|||
|
|
@ -16,13 +16,26 @@ const D = require('./lib/dict');
|
|||
const { CALL } = require('./legacy/labels');
|
||||
|
||||
const SITE = path.join(__dirname, '..', 'site');
|
||||
const page = () => require('./lib/page').assemble().html;
|
||||
// The development page of a multiplayer build: it has every label, the agent's (src/agent/) and the server-play
|
||||
// client's (src/game/98-server-play/, only in MP builds) too. src: another source tree (tests).
|
||||
const page = (src) => require('./lib/page').assemble({ src, dev: true, mp: true }).html;
|
||||
const LABEL = /^[a-z0-9_]+(\.[a-z0-9_]+)+$/;
|
||||
|
||||
// The bodies of the page's bare <script> tags. Our own assembled page, so a plain search is enough.
|
||||
function inlineScripts(html) {
|
||||
const out = [];
|
||||
for (let i = html.indexOf('<script>'); i >= 0; i = html.indexOf('<script>', i)) {
|
||||
const end = html.indexOf('</script>', i += 8);
|
||||
if (end < 0) break;
|
||||
out.push(html.slice(i, end)); i = end;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// The labels the game uses, with problems in how they are used.
|
||||
function sourceLabels(html) {
|
||||
const labels = new Set(), problems = [];
|
||||
const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => m[1]).join('\n');
|
||||
const scripts = inlineScripts(html).join('\n');
|
||||
for (const m of scripts.matchAll(CALL)) {
|
||||
const l = m[2].slice(1, -1);
|
||||
if (!LABEL.test(l)) problems.push(`${m[1]}(${m[2].slice(0, 60)}…): not a label like 'area.some_words'`);
|
||||
|
|
@ -95,14 +108,14 @@ function checkEnglish(src, en) {
|
|||
return out;
|
||||
}
|
||||
|
||||
module.exports = { loadDict, brokenEntries, sourceLabels };
|
||||
module.exports = { loadDict, brokenEntries, sourceLabels, page };
|
||||
|
||||
// A language file only works if the game offers it and the offline cache keeps it.
|
||||
function registration(lang, html) {
|
||||
const sw = fs.readFileSync(path.join(SITE, 'sw.js'), 'utf8');
|
||||
const out = [];
|
||||
const m = html.match(/SOT_LANGS=\{([^}]*)\}/);
|
||||
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)');
|
||||
if (!m || !new RegExp(String.raw`(^|[,{\s])${lang.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\s*:`).test(m[1])) out.push('not in the language list (SOT_LANGS in src/index.html)');
|
||||
if (!sw.includes(`/i18n/${lang}.js`)) out.push('not cached for offline play (CORE in site/sw.js)');
|
||||
if (!D.tidy(lang)) out.push('not sorted one entry per line: run npm run i18n:fix');
|
||||
return out;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@
|
|||
// static markup, in the inlined English and in every translation file, and the page ends up about the
|
||||
// size it was when the English text itself was the key.
|
||||
//
|
||||
// Labels passed to N_() are kept whole: those are the ones the game stores (in saves, in the inbox log)
|
||||
// Labels passed to N_() are kept whole: those are the ones the game stores (in saves)
|
||||
// and shows later, and an id would mean something else in the next release.
|
||||
const { CALL } = require('../legacy/labels');
|
||||
const D = require('./dict');
|
||||
|
|
|
|||
216
scripts/lib/fuzz-page.js
Normal file
216
scripts/lib/fuzz-page.js
Normal file
|
|
@ -0,0 +1,216 @@
|
|||
// Runs inside a game page (scripts/route-fuzz.js loads two: main's and this checkout's).
|
||||
// The driver picks every move with its own seeded random numbers and sends the same calls to both pages, so the pages
|
||||
// stay in lockstep; this file only offers what a player could do now (buttons on screen, POPs, cities) and digests what
|
||||
// routing gave, as strings the driver compares.
|
||||
(() => {
|
||||
const DENY = new Set(['animSet', 'cont', 'exportSave', 'importGo', 'importPick', 'install', 'langSet', 'mapSet', 'menu', 'mute', 'newgame', 'phonePlay', 'phoneSpeed',
|
||||
'prefSet', 'pzShare', 'resetAsk', 'settings', 'settingsClose', 'share', 'shareDl', 'shareGo', 'slotBack', 'slotDel', 'slotDelGo', 'slotExport', 'slotMenu',
|
||||
'slotRetry', 'slotSpace', 'slotSwitch', 'slotTake', 'soundSet', 'speed', 'start', 'toTitle', 'traceCopy', 'updateLater', 'updateNow', 'vpSet', 'wsShare',
|
||||
// Leave the game or open what is not this game: the title screen, menus of other modes, AI helpers that fetch.
|
||||
'closePanel', 'puzzleMenu', 'puzzleDoor', 'scnMenu', 'startScn', 'startWeekly', 'pzStart', 'pzArStart', 'arMenu', 'teSlop', 'help', 'helpClose', 'keepPlaying',
|
||||
'logOpen', 'pitchSkip', 'pitchGo', 'feedback', 'tutSkip', 'tutNext']);
|
||||
const sig = (b) => b.act + ' ' + JSON.stringify(b.args);
|
||||
const btns = (root) => (root ? [...root.querySelectorAll('[data-act]')] : []).filter((b) => !b.disabled && !DENY.has(b.dataset.act) && typeof ACT[b.dataset.act] === 'function')
|
||||
.map((b) => { let args = {}; try { args = JSON.parse(b.dataset.args || '{}'); } catch (e) {} return { act: b.dataset.act, args }; });
|
||||
const modalOpen = () => !$('modal').hidden;
|
||||
const errs = [];
|
||||
const call = (act, args) => {
|
||||
try { const r = ACT[act](args || {}); if (r && typeof r.then === 'function') r.catch((e) => errs.push(act + ': ' + e.message)); return ''; } catch (e) { return act + ': ' + (e && e.message); }
|
||||
};
|
||||
const fixClock = (t) => { Date.now = () => t; };
|
||||
|
||||
// ---------- starts ----------
|
||||
const homes = () => CITIES.filter((c) => homeOk(c.id)).map((c) => c.id);
|
||||
// Home cities with rules of their own: China, Korea, Russia, Australia, the Philippines, islands and far places.
|
||||
const special = () => CITIES.filter((c) => homeOk(c.id) && (c.cn || c.kr || c.ru || ['AU', 'PH', 'NZ', 'JP', 'ID', 'IS', 'FJ', 'PF', 'MU', 'MV', 'CL', 'ZA', 'BR', 'IN', 'SG', 'HK', 'TW', 'KR', 'CN'].includes(c.cc))).map((c) => c.id);
|
||||
const lists = () => ({ homes: homes(), special: special(), scn: SCN.map((s) => s.id), pz: PZ.map((p) => p.id), ar: AR_RUNS.map((r) => r.id) });
|
||||
const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); if (S && !pzOn()) compute(); renderAll(); };
|
||||
const start = ({ kind, id, city, preset, seed, name }) => {
|
||||
if (window.__reseed) window.__reseed(seed);
|
||||
fixClock(1.7e12 + seed * 1000);
|
||||
UI.pitched = true; UI.pendGame = null;
|
||||
if (pzOn()) pzLeave();
|
||||
if (kind === 'normal') beginGame(name, city, { mode: 'normal', preset });
|
||||
else if (kind === 'sandbox') beginGame(name, city, { mode: 'sandbox', rules: { chaos: preset } });
|
||||
else if (kind === 'scenario') { const sc = SCN.find((x) => x.id === id); beginGame(name, sc.city, { scn: sc }); }
|
||||
else if (kind === 'weekly') { const wk = weekly(); beginGame(name, wk.city, { scn: wk, seed: wk.seed }); }
|
||||
else if (kind === 'puzzle') pzBegin(pzDef(id));
|
||||
else if (kind === 'architect') arBegin(arRunDef(id));
|
||||
// A saved network (the big fixture): loaded and migrated as an import is, with its incidents and events still on.
|
||||
else if (kind === 'save') { S = migrate(JSON.parse(window.__fzSave)); }
|
||||
settle();
|
||||
return { mode: S.mode, home: S.home, puzzle: pzOn() };
|
||||
};
|
||||
|
||||
// ---------- what a player could do now ----------
|
||||
// The nearest cities, and those a cable lands from here (subsea seats, IRUs and own cables start there).
|
||||
const near = (c, n) => CITIES.filter((x) => x.id !== c).map((x) => [x.id, kmBetween(c, x.id)]).sort((a, b) => a[1] - b[1]).slice(0, n).map((x) => x[0])
|
||||
.concat(CABLE_PAIRS.filter((p) => p.a === c || p.b === c).slice(0, 4).map((p) => (p.a === c ? p.b : p.a)));
|
||||
const state = () => {
|
||||
const pops = Object.keys(S.pops), nb = new Set();
|
||||
for (const p of pops.slice(0, 12)) for (const c of near(p, 8)) if (!S.pops[c]) nb.add(c);
|
||||
return { pops, near: [...nb], cities: CITIES.length, links: S.links.map((l) => l.id), day: S.day, puzzle: pzOn(), modal: modalOpen(), lost: !!S.lost,
|
||||
clock: !!rule('clock'), core: S.core ? S.core.lv : 0, nets: NET_IDS.length, transit: S.transit.map((t) => t.id), pni: S.pni.map((p) => p.id), biz: S.biz.map((b) => b.id), offers: (S.offers || []).map((o) => o.id) };
|
||||
};
|
||||
// The buttons of one place on screen, after opening it.
|
||||
const screen = (w) => {
|
||||
if (w.where === 'modal') return btns($('modal'));
|
||||
if (w.where === 'city') { UI.sel = { type: 'city', id: w.city }; UI.tab = w.tab; renderAll(); return btns($('panel')); }
|
||||
// The city names in a link panel's header open the city (#196); older pages have plain text there. They only change
|
||||
// the view, so neither page offers them, and both stay in lockstep.
|
||||
if (w.where === 'link') { if (!S.links.some((l) => l.id === w.id)) return []; UI.sel = { type: 'link', id: w.id }; renderAll(); const P = $('panel'); for (const h of P.querySelectorAll('.ph h2 [data-act]')) h.removeAttribute('data-act'); return btns(P); }
|
||||
if (w.where === 'dash') { $('dash').hidden = false; UI.dtab = w.tab; renderDash(); const b = btns($('dash')); return b; }
|
||||
if (w.where === 'left') {
|
||||
UI.left = w.tab; UI.leftOpen = true; renderLeft(); let b = btns($('leftBody'));
|
||||
if (w.tab !== 'noc') return b;
|
||||
// The backbone, Auto-TE and DDoS settings moved from the NOC tab into the Routing & DDoS modal: offer them here on
|
||||
// both pages, in one order, so main's page (settings in the tab) and this one (behind the button) stay in lockstep.
|
||||
if (typeof routingBody === 'function' && b.some((x) => x.act === 'routingOpen')) { const d = document.createElement('div'); d.innerHTML = routingBody(); b = b.filter((x) => x.act !== 'routingOpen').concat(btns(d)); }
|
||||
// The traceroute moved into that modal too, and Connections left the tab (it is in the dashboard): drop it on both pages.
|
||||
b = b.filter((x) => x.act !== 'connOpen');
|
||||
return b.sort((x, y) => (sig(x) < sig(y) ? -1 : sig(x) > sig(y) ? 1 : 0));
|
||||
}
|
||||
if (w.where === 'openLink') { if (!S.pops[w.a]) return []; openLinkModal(w.a, w.b); return modalOpen() ? btns($('modal')) : []; }
|
||||
return [];
|
||||
};
|
||||
const press = (b) => { const e = call(b.act, b.args); return e; };
|
||||
const close = () => { if (modalOpen()) closeModal(); $('dash').hidden = true; };
|
||||
|
||||
// ---------- things a player does with no button handy here ----------
|
||||
const RS = ['spill at 80%', 'spill at 60%', 'protect customers', 'blackhole ddos'];
|
||||
const script = (rules) => {
|
||||
const L = [];
|
||||
for (const r of rules) {
|
||||
const [k, a, b] = r;
|
||||
const net = NETS[a % NETS.length], t = S.transit.length ? NET[S.transit[a % S.transit.length].net] : net;
|
||||
const pops = Object.keys(S.pops), l = S.links.length ? S.links[a % S.links.length] : null;
|
||||
if (k === 0) L.push(RS[a % RS.length]);
|
||||
else if (k === 1) L.push(`${b % 2 ? 'prefer' : 'avoid'} ${['pni', 'ix', 'transit'][b % 3]} for ${net.name.toLowerCase()}`);
|
||||
else if (k === 2) L.push(`cap transit ${t.name.toLowerCase()} at ${10 + (b % 50)} gbps`);
|
||||
else if (k === 3) L.push(`${b % 2 ? 'prefer' : 'avoid'} transit ${t.name.toLowerCase()}`);
|
||||
else if (k === 4) L.push(`prepend transit ${t.name.toLowerCase()} ${1 + (b % 3)}`);
|
||||
else if (k === 5 && pops.length) L.push(`drain ${CITY[pops[a % pops.length]].name.toLowerCase()}`);
|
||||
else if (k === 6 && l) L.push(`avoid link ${CITY[l.a].name.toLowerCase()}-${CITY[l.b].name.toLowerCase()}`);
|
||||
}
|
||||
return L.join('\n');
|
||||
};
|
||||
const poke = (p) => {
|
||||
const [k, a, b] = p;
|
||||
if (k === 'te') { if (!S.te) return 'no te'; S.te.script = script(a); S.te.on = !!b; S.core = S.core || { lv: 0, run: 0 }; after(); return S.te.script; }
|
||||
if (k === 'teOff') { if (S.te) { S.te.on = false; after(); } return ''; }
|
||||
if (k === 'core') { if (S.core) { const v = a % (S.core.lv + 1); return call('coreSet', { v }); } return ''; }
|
||||
if (k === 'fail') { S.nextFail = S.day + 1; return ''; }
|
||||
if (k === 'event') { S.nextEvent = S.day + 1; return ''; }
|
||||
if (k === 'cash') { S.cash += a; after(); return ''; }
|
||||
// One level up from the level the game reads (lvl(): S.lvl, or 1 when a page never wrote it down).
|
||||
if (k === 'lvl') { S.lvl = Math.min(LEVELS.length, (S.lvl || 1) + 1); after(); return ''; }
|
||||
// Events that move routes, as the game's own events set them.
|
||||
if (k === 'ev') {
|
||||
const n = NETS[a % NETS.length].id;
|
||||
if (b === 0) S.ev.leak = { net: n, until: S.day + 3 };
|
||||
else if (b === 1) S.ev.rpki = { nets: [n, NETS[(a * 7) % NETS.length].id], until: S.day + 3 };
|
||||
else if (b === 2) S.ev.depeer = S.day + 3;
|
||||
else if (b === 3) { const x = Object.keys(S.ixp); if (x.length) { S.ev.ixdown = S.ev.ixdown || {}; S.ev.ixdown[x[a % x.length]] = S.day + 2; } }
|
||||
else if (b === 4 && S.links.length) S.links[a % S.links.length].cut = S.day + 2;
|
||||
else if (b === 5 && S.transit.length) S.transit[a % S.transit.length].down = S.day + 2;
|
||||
// After an update brings networks: the courtesy route to them (sanitize() sets it on load).
|
||||
else if (b === 7) S.grace = { until: S.day + 4, nets: [n, NETS[(a * 13) % NETS.length].id, NETS[(a * 31) % NETS.length].id], fresh: 0 };
|
||||
else if (b === 8) S.krExit = S.day + 2;
|
||||
else if (b === 6) { const p = Object.keys(S.pops); if (p.length > 1) S.pops[p[1 + (a % (p.length - 1))]].down = S.day + 2; }
|
||||
after(); return '';
|
||||
}
|
||||
return 'unknown poke';
|
||||
};
|
||||
|
||||
/* Actions on what the network already has, with arguments a button somewhere would give (some sit in collapsed
|
||||
lists, or on screens the walker rarely reaches): one list of calls, the driver picks one. */
|
||||
const direct = () => {
|
||||
const o = [], add = (act, args) => { if (typeof ACT[act] === 'function') o.push({ act, args }); };
|
||||
const pops = Object.keys(S.pops), PR = ['high', 'low', 'normal'];
|
||||
for (const t of S.transit) { add('setPref', { kind: 't', id: t.id, v: PR[(t.id.length + S.day) % 3] }); add('setCarry', { id: t.id, on: !t.carry }); add('lagT', { id: t.id, d: (S.day % 3) ? 1 : -1 }); add('cancelTransit', { id: t.id, ok: true }); add('togglePrem', { id: t.id }); add('cleanPipe', { id: t.id }); }
|
||||
for (const p of S.pni) { add('setPref', { kind: 'p', id: p.id, v: PR[(p.id.length + S.day) % 3] }); add('lagP', { id: p.id, d: (S.day % 3) ? 1 : -1 }); add('cancelPni', { id: p.id, ok: true }); add('sacrif', { id: p.id }); }
|
||||
for (const x of Object.keys(S.ixp)) { add('setPref', { kind: 'ix', id: x, v: PR[(x.length + S.day) % 3] }); add('lagIx', { city: x, d: (S.day % 3) ? 1 : -1 }); add('peerAll', { city: x }); add('rs', { city: x }); add('cancelIx', { city: x, sure: true, ok: true });
|
||||
for (const n of ixMembers(x).slice(0, 30)) add(ixSessions(x).has(n) ? 'unpeer' : 'peer', { city: x, net: n }); }
|
||||
for (const c of pops) {
|
||||
for (const x of ixIdsIn(c)) if (S.ixp[x] === undefined) add('buyIx', { city: x, tier: S.day % 3 });
|
||||
for (const n of NETS) if (n.pops.includes(c)) { if (S.day % 2 === 0 || n.cache) add('pni', { city: c, net: n.id, tier: n.id.length % 3 }); if (n.cache) add('cache', { city: c, net: n.id }); }
|
||||
for (const n of NETS) if (sellsAt(n, c) && (n.id.length + S.day) % 4 === 0) add('buyTransit', { city: c, net: n.id, tier: (S.day >> 2) % 3 });
|
||||
add('addRouter', { city: c }); add('upRouter', { city: c, g: 1 + (S.day % 4) }); if (!ixName(c) && !CITY[c].cn) add('foundIx', { city: c }); add('launchBB', { city: c }); add('addSite', { city: c });
|
||||
}
|
||||
for (const c of S.caches) add('rmCache', { id: c.id });
|
||||
for (const l of S.links) { add('setStandby', { id: l.id, on: !l.standby }); add('setMetric', { id: l.id, v: ['backup', 'avoid', 'prefer', 'normal'][(l.id.length + S.day) % 4] }); add('upLink', { id: l.id, tier: (S.day % 4) }); add('rmLink', { id: l.id }); add('addParallel', { id: l.id }); }
|
||||
for (const b of S.offers || []) add('accept', { id: b.id });
|
||||
for (const b of S.biz) add('dropBiz', { id: b.id });
|
||||
for (const l of S.loanOffers || []) add('takeLoan', { id: l.id });
|
||||
for (const l of S.loans || []) add('repayLoan', { id: l.id });
|
||||
return o;
|
||||
};
|
||||
|
||||
// ---------- time ----------
|
||||
const day = () => { if (S.lost || !rule('clock')) return 'no clock'; if (modalOpen()) closeModal(); try { dayTick(); } catch (e) { return 'dayTick: ' + e.message; } return ''; };
|
||||
|
||||
// ---------- digests ----------
|
||||
// Everything routing produced: R in full (with every link's R.ef), the flows (R.fl), and what the PNI lists read.
|
||||
// An attack's record names its attack by id (as rwPack does): the attack itself is game state, compared with S.
|
||||
const rj = (v) => JSON.stringify(v, (k, x) => (k === 'attack' && x && typeof x === 'object' ? x.id : x));
|
||||
const routing = () => {
|
||||
if (!R) return 'noR';
|
||||
const r = rj(R), fl = R.fl ? JSON.stringify(R.fl) : '';
|
||||
let pf = '';
|
||||
if (typeof pniFlows === 'function' && S && !pzOn()) for (const c of Object.keys(S.pops).slice(0, 4)) try { pf += c + JSON.stringify(pniFlows(c)); } catch (e) { pf += c + 'E' + e.message; }
|
||||
return r + '\n' + fl + '\n' + pf;
|
||||
};
|
||||
const parts = () => { const o = {}; if (!R) return o; for (const k of Object.keys(R)) o[k] = rj(R[k]); o.fl = R.fl ? JSON.stringify(R.fl) : ''; return o; };
|
||||
// A field only this checkout's game has (a new feature's state, on S or on its customers and offers) cannot match main
|
||||
// yet: the driver passes those (drop) and they are left out; every field both games have must still match.
|
||||
// The intern's state two levels deep (ops.on.sales, ops.wk.rev): a standing order one game has and the other retired.
|
||||
// Compared as a reload makes it (migrate(), keys in order): the same game, whichever way each version writes the
|
||||
// fields it fills in anyway (main may create a record without the defaults a reload gives it, in another order).
|
||||
// One reload judges both: the driver passes the base page's live state (sLive) through this checkout's migrate()
|
||||
// (sDigest(drop, json)), so a repair only one version's reload makes (main's re-aimed an attack whose customer left
|
||||
// during the day) is no divergence. That reload runs with this page's own S in scope (sanitize reads S.rules through
|
||||
// rule()): pages in lockstep have the same, and a difference in the rules shows up in the fields they decide. A POP without a router model plays the basic one (RG[p.rgen||0]): that is written
|
||||
// down first, so the reload does not guess one from its ports (a free upgrade a page from before canonical state got).
|
||||
// Puzzles are never saved: as they are. The rules stay as they are too: both pages may have set them alike (noIp4),
|
||||
// and a base that does not know a rule would drop it on the way.
|
||||
const sortK = (v) => (Array.isArray(v) ? v.map(sortK) : v && typeof v === 'object' ? Object.keys(v).sort().reduce((o, k) => ((o[k] = sortK(v[k])), o), {}) : v);
|
||||
const sLive = () => JSON.stringify(S === undefined ? null : S);
|
||||
const sOf = (json) => { const live = JSON.parse(json); if (!live || !S || pzOn() || live.mode === 'puzzle') return live; const u0 = uidN, r0 = S.rng;
|
||||
try {
|
||||
for (const c of Object.keys(live.pops || {})) if (live.pops[c] && live.pops[c].rgen === undefined) live.pops[c].rgen = 0;
|
||||
const rules = live.rules === undefined ? undefined : JSON.parse(JSON.stringify(live.rules));
|
||||
const s = migrate(live); s.rules = rules; return sortK(s);
|
||||
} finally { uidN = u0; S.rng = r0; } };
|
||||
const sNow = () => sOf(sLive());
|
||||
const opsPaths = (s = sNow()) => { const O = s.ops, out = []; if (!O || typeof O !== 'object') return out;
|
||||
for (const k of Object.keys(O)) { out.push(k); const v = O[k]; if (v && typeof v === 'object' && !Array.isArray(v)) for (const j of Object.keys(v)) out.push(k + '.' + j); } return out; };
|
||||
const sKeys = () => { const s = sNow(); return { top: Object.keys(s), items: [...new Set([...(s.biz || []), ...(s.offers || [])].flatMap((x) => Object.keys(x)))], ops: opsPaths(s), orders: typeof OPSK === 'object' ? Object.keys(OPSK) : [] }; };
|
||||
const opsDrop = (s, ops) => { const o = {}; for (const k of Object.keys(s.ops)) { if (ops.includes(k)) continue; const v = s.ops[k];
|
||||
if (v && typeof v === 'object' && !Array.isArray(v)) { const w = {}; for (const j of Object.keys(v)) if (!ops.includes(k + '.' + j)) w[j] = v[j]; o[k] = w; } else o[k] = v; } return o; };
|
||||
// json: a live state to judge (the other page's, from sLive); without it, this page's own.
|
||||
const sDrop = (drop, json) => { const s = json === undefined ? sNow() : sOf(json); if (!s || typeof s !== 'object' || !drop || (!drop.top.length && !drop.items.length && !(drop.ops || []).length)) return s; const o = {};
|
||||
for (const k of Object.keys(s)) if (!drop.top.includes(k)) o[k] = k === 'ops' && s.ops && (drop.ops || []).length ? opsDrop(s, drop.ops) : s[k];
|
||||
for (const k of ['biz', 'offers']) if (Array.isArray(o[k])) o[k] = o[k].map((x) => { const y = {}; for (const f of Object.keys(x)) if (!drop.items.includes(f)) y[f] = x[f]; return y; });
|
||||
return o; };
|
||||
const sDigest = (drop, json) => JSON.stringify(sDrop(drop, json));
|
||||
const sParts = (drop, json) => { const s = sDrop(drop, json), o = {}; if (s && typeof s === 'object') for (const k of Object.keys(s)) o[k] = JSON.stringify(s[k]); return o; };
|
||||
/* After a move: what the move routed (a), routing again from the same state (b: on this checkout's page the kept
|
||||
tables are used), and routing from that state with the cache off (c: RC.on=false where there is an RC). b and c
|
||||
route from the same previous R; c's R is kept, as a plain compute would. */
|
||||
const check = () => {
|
||||
if (!S || pzOn() && !R) return { a: routing() };
|
||||
const a = routing(), prior = R, keep = UI.rkR === prior;
|
||||
compute(); const b = routing();
|
||||
R = prior; const rc = typeof RC !== 'undefined';
|
||||
if (rc) RC.on = false;
|
||||
try { compute(); } finally { if (rc) RC.on = true; }
|
||||
const c = routing();
|
||||
if (keep) UI.rkR = R;
|
||||
return { a, b, c };
|
||||
};
|
||||
const acts = () => Object.keys(ACT);
|
||||
// Scarce IPv4 off (#150, rule ip4), the same rules object with its keys in the same order on both pages: the driver calls
|
||||
// it only while the base has no such rule, so the pages play the same game until it lands.
|
||||
const noIp4 = () => { if (S && S.rules) { const { ip4, mods, ...r } = S.rules; S.rules = { ...r, ip4: false, mods }; } };
|
||||
window.__fz = { acts, direct, lists, start, state, screen, press, close, poke, day, routing, parts, sKeys, sLive, sDigest, sParts, check, errs, modalOpen, noIp4 };
|
||||
})();
|
||||
155
scripts/lib/gpu-bench-client.js
Normal file
155
scripts/lib/gpu-bench-client.js
Normal file
|
|
@ -0,0 +1,155 @@
|
|||
// The benchmark panel that scripts/gpu-bench.js adds to the game page. It runs in your own browser, so it measures your
|
||||
// graphics card: the save is loaded, then each scenario plays for a few seconds with the 2D map and with the WebGL
|
||||
// tubes, and the frames are timed as they really reach the screen (requestAnimationFrame). Results show in the panel
|
||||
// and go back to the terminal that started the server. Nothing is saved: the page's save() is switched off.
|
||||
// What each number is: the frame rate and p95 frame are the cadence of requestAnimationFrame (what you see); draw() is
|
||||
// the main thread's time to build and submit a frame (CPU only: the card may still be drawing when it returns); GPU is
|
||||
// the card's own time for a WebGL frame, from EXT_disjoint_timer_query_webgl2 where the browser offers it (read back
|
||||
// frames later, never waited for, and thrown away when the card says its timing was disturbed).
|
||||
(() => {
|
||||
const CFG = window.__BENCH__ || {}, QS = new URLSearchParams(location.search);
|
||||
const SECS = CFG.secs || 6, WARM = CFG.warm ?? 1500, SETTLE = CFG.settleMs || 5000, SEED = CFG.seed || 777;
|
||||
const SCEN = [
|
||||
{ id: 'x1-far', label: 'Map at x1, zoomed out (0.6)', speed: 1, z: 0.6 },
|
||||
{ id: 'x1-mid', label: 'Map at x1 (zoom 1.4)', speed: 1, z: 1.4 },
|
||||
{ id: 'x1-near', label: 'Map at x1, zoomed in (3.2)', speed: 1, z: 3.2 },
|
||||
{ id: 'pan', label: 'Panning at x1 (zoom 1.4)', speed: 1, z: 1.4, pan: true },
|
||||
{ id: 'x8', label: 'Game at x8 (zoom 1.4)', speed: 8, z: 1.4 },
|
||||
];
|
||||
// ?only=gl or ?only=2d runs one renderer; ?scen=x1-mid,pan runs only those scenarios; ?reps=3 runs each one three
|
||||
// times (the renderers take turns going first, and the table shows the medians); ?dpr=2 below.
|
||||
const ONLY = QS.get('only'), PICK = QS.get('scen'), REPS = Math.max(1, Math.min(9, +QS.get('reps') || CFG.reps || 1));
|
||||
if (PICK) SCEN.splice(0, SCEN.length, ...SCEN.filter((s) => PICK.split(',').includes(s.id)));
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
const box = document.createElement('div');
|
||||
box.style.cssText = 'position:fixed;top:8px;left:50%;transform:translateX(-50%);z-index:100000;background:rgba(30,38,64,.94);color:#fff;font:13px/1.4 system-ui,sans-serif;padding:12px 14px;border-radius:12px;max-width:94vw;max-height:80vh;overflow:auto;box-shadow:0 6px 24px rgba(0,0,0,.35)';
|
||||
box.innerHTML = '<b>Series of Tubes · GPU benchmark</b><div id="bst" style="margin:6px 0">Loading…</div><button id="bgo" disabled style="font:inherit;padding:6px 12px;border-radius:8px;border:0;background:#22C47A;color:#fff;font-weight:700;cursor:pointer">Start</button> <button id="bcp" hidden style="font:inherit;padding:6px 12px;border-radius:8px;border:0;background:#FF4F9A;color:#fff;font-weight:700;cursor:pointer">Copy results</button><div id="bout"></div>';
|
||||
const st = (t) => { box.querySelector('#bst').textContent = t; };
|
||||
let SAVE = null, MD = '', TRIAL = 0;
|
||||
|
||||
// Ends what the last trial left running before the next one starts, so nothing of one lands on the other: the clock
|
||||
// stops, its frame callback is cancelled (measure() does that, and TRIAL turns away one already queued), and a day
|
||||
// still being routed in the worker is waited for. Its answer runs dayPost() on the old save; one that never comes is
|
||||
// dropped (rwDone() ignores an answer to no job). Then the clock's leftovers are cleared.
|
||||
async function settle() {
|
||||
UI.speed = 0; TRIAL++;
|
||||
const t0 = performance.now();
|
||||
while (RW.job && performance.now() - t0 < SETTLE) await sleep(10);
|
||||
if (RW.job) { console.warn('[bench] the route worker did not answer: its day is dropped'); RW.job = null; }
|
||||
acc = 0; animT = 0;
|
||||
}
|
||||
// The save again, with the same random numbers every time (S.rng makes Math.random() follow it, as in a scenario).
|
||||
function fresh() {
|
||||
S = migrate(JSON.parse(SAVE)); S.rng = SEED; UI.started = true; UI.pitched = true; UI.sel = null; UI.anim = 'on'; applyAnim();
|
||||
closeModal(); compute(); renderAll();
|
||||
const h = CITY[S.home] || CITIES[0]; cam.x = h.x; cam.y = h.y;
|
||||
}
|
||||
async function reset() { await settle(); fresh(); }
|
||||
const q = (s, x) => (s.length ? s[Math.min(s.length - 1, Math.floor(s.length * x))] : 0);
|
||||
async function measure(sc, hz, r) {
|
||||
await reset(); cam.z = sc.z; UI.speed = sc.speed; WL.key = null;
|
||||
const trial = TRIAL;
|
||||
await sleep(WARM);
|
||||
const fr = [], dr = [], gpu = [], pend = [], day0 = S.day; let last = 0, stop = false, hidden = false, long = 0, panX = cam.x, raf = 0, glF = 0, flatF = 0, disjoint = 0;
|
||||
// The card's own time, where the browser lets us read it: a timer around each WebGL draw(), read when it is ready.
|
||||
const gl = r === 'gl' ? GLX.gl : null; let tq = null; try { tq = gl && gl.getExtension('EXT_disjoint_timer_query_webgl2'); } catch (e) { /* none */ }
|
||||
const poll = () => { while (pend.length) { const x = pend[0]; if (!gl.getQueryParameter(x, gl.QUERY_RESULT_AVAILABLE)) break; pend.shift();
|
||||
const ns = gl.getQueryParameter(x, gl.QUERY_RESULT); gl.deleteQuery(x); if (gl.getParameter(tq.GPU_DISJOINT_EXT)) disjoint++; else gpu.push(ns / 1e6); } };
|
||||
const D0 = draw;
|
||||
draw = function (t) { let x = null; if (tq && GLX.gl === gl && pend.length < 16) { x = gl.createQuery(); gl.beginQuery(tq.TIME_ELAPSED_EXT, x); }
|
||||
const a = performance.now();
|
||||
try { return D0(t); } finally { dr.push(performance.now() - a); if (x) { gl.endQuery(tq.TIME_ELAPSED_EXT); pend.push(x); } if (GLX.shown) glF++; else flatF++; } };
|
||||
let po = null; try { po = new PerformanceObserver((l) => { long += l.getEntries().length; }); po.observe({ type: 'longtask' }); } catch (e) { /* not in this browser */ }
|
||||
// Frames slower than three refreshes, with the day they fell on and their draw(): where the stutters are.
|
||||
const t00 = performance.now(), slow = [];
|
||||
const tick = (t) => { if (stop || trial !== TRIAL) return;
|
||||
if (last) { fr.push(t - last); if (t - last > 50) slow.push({ at: Math.round(t - t00), ms: Math.round(t - last), day: S.day, draw: +(dr[dr.length - 1] || 0).toFixed(1) }); } last = t; if (document.hidden) hidden = true;
|
||||
if (sc.pan) { panX += 0.18 * (t - (tick.p || t)) / cam.z; cam.x = panX; tick.p = t; }
|
||||
if (tq) poll();
|
||||
raf = requestAnimationFrame(tick); };
|
||||
raf = requestAnimationFrame(tick);
|
||||
const t0 = performance.now(); await sleep(SECS * 1000); stop = true; cancelAnimationFrame(raf); const T = (performance.now() - t0) / 1000;
|
||||
draw = D0; if (po) po.disconnect(); UI.speed = 0;
|
||||
if (tq) { poll(); for (const x of pend) gl.deleteQuery(x); }
|
||||
const s = fr.slice().sort((a, b) => a - b), d = dr.slice().sort((a, b) => a - b), g = gpu.slice().sort((a, b) => a - b), budget = 1000 / hz;
|
||||
return { fps: +(fr.length / T).toFixed(1), p50: +q(s, 0.5).toFixed(1), p95: +q(s, 0.95).toFixed(1), p99: +q(s, 0.99).toFixed(1), max: +q(s, 1).toFixed(1),
|
||||
dropped: +(100 * fr.filter((x) => x > budget * 1.5).length / Math.max(1, fr.length)).toFixed(1),
|
||||
drawMs: +(d.reduce((a, x) => a + x, 0) / Math.max(1, d.length)).toFixed(2), drawP95: +q(d, 0.95).toFixed(2),
|
||||
gpuMs: g.length ? +(g.reduce((a, x) => a + x, 0) / g.length).toFixed(2) : null, gpuP95: g.length ? +q(g, 0.95).toFixed(2) : null, gpuN: g.length, disjoint,
|
||||
// Which map really drew the frames: a WebGL run that fell back to 2D (or a 2D run on the card) is not what it says.
|
||||
drawn: glF && flatF ? 'mixed' : glF ? 'gl' : flatF ? '2d' : 'none', glFrames: glF, flatFrames: flatF,
|
||||
daysPerSec: +((S.day - day0) / T).toFixed(2), longTasks: long, hidden, drawMax: +q(d, 1).toFixed(1), slow };
|
||||
}
|
||||
// Several runs of one scenario: the median of each number; the flags and the stutters of all of them.
|
||||
function merge(ms) {
|
||||
if (ms.length === 1) return ms[0];
|
||||
const o = {}, med = (a) => { const s = a.slice().sort((x, y) => x - y); return s[(s.length - 1) >> 1]; };
|
||||
for (const k of Object.keys(ms[0])) {
|
||||
const v = ms.map((m) => m[k]);
|
||||
o[k] = k === 'slow' ? v.flat() : k === 'drawn' ? [...new Set(v)].join('+') : typeof v[0] === 'boolean' ? v.some(Boolean) : v.every((x) => typeof x === 'number') ? med(v) : v[0];
|
||||
}
|
||||
o.runs = ms.length; return o;
|
||||
}
|
||||
async function refresh() {
|
||||
const a = []; let l = 0; await new Promise((r) => { const f = (t) => { if (l) a.push(t - l); l = t; if (a.length < 90) requestAnimationFrame(f); else r(); }; requestAnimationFrame(f); });
|
||||
a.sort((x, y) => x - y); return Math.round(1000 / a[a.length >> 1]);
|
||||
}
|
||||
function table(res, env) {
|
||||
const gpu = res.gl && SCEN.some((sc) => res.gl[sc.id] && res.gl[sc.id].gpuMs != null);
|
||||
const rows = SCEN.map((sc) => { const a = res['2d'] && res['2d'][sc.id], b = res.gl && res.gl[sc.id];
|
||||
const f = (m, k, u = '') => (m && m[k] != null ? `${m[k]}${u}` : '-');
|
||||
return `| ${sc.label} | ${f(a, 'fps')} | ${f(b, 'fps')} | ${f(a, 'p95', ' ms')} | ${f(b, 'p95', ' ms')} | ${f(a, 'drawMs', ' ms')} | ${f(b, 'drawMs', ' ms')} |${gpu ? ` ${f(b, 'gpuMs', ' ms')} |` : ''}`; });
|
||||
// A run is only what it says if its frames were drawn by the map it names.
|
||||
const off = []; for (const [r, want] of [['2d', '2d'], ['gl', 'gl']]) for (const sc of SCEN) { const m = res[r] && res[r][sc.id]; if (m && m.drawn !== want && m.drawn !== 'none') off.push(`${sc.label} (${r === 'gl' ? 'WebGL' : '2D'}: ${m.flatFrames} frames in 2D, ${m.glFrames} on the card)`); }
|
||||
return [`**${env.gpu || 'unknown GPU'}** · ${env.ua}`, `${env.w}×${env.h} at ${env.dpr}× · ${env.hz} Hz screen · ${env.cores} threads · ${env.save}${env.reps > 1 ? ` · median of ${env.reps} runs` : ''}`, '',
|
||||
`| Scenario | 2D fps | WebGL fps | 2D p95 frame | WebGL p95 frame | 2D draw() | WebGL draw() |${gpu ? ' WebGL GPU |' : ''}`,
|
||||
`|---|--:|--:|--:|--:|--:|--:|${gpu ? '--:|' : ''}`, ...rows,
|
||||
'', `<sub>fps and p95 frame: requestAnimationFrame's cadence (p95: the slowest 5% of frames). draw(): CPU time on the main thread to build and submit a frame; the card may still be working when it returns, so it is not the cost of drawing.${gpu ? ' WebGL GPU: the card\'s own time per frame (EXT_disjoint_timer_query_webgl2).' : ' No GPU timer in this browser: the card\'s own time is not measured.'}${env.invalid ? ' ⚠️ The tab was hidden during a run: those numbers are not valid.' : ''}</sub>`,
|
||||
...(off.length ? ['', `⚠️ Not drawn by the map they name: ${off.join('; ')}.`] : [])].join('\n');
|
||||
}
|
||||
async function run() {
|
||||
const go = box.querySelector('#bgo'); go.disabled = true;
|
||||
save = () => {};
|
||||
// An incident pauses the game (autoPause): the clock must keep running for the timings to mean anything.
|
||||
autoPause = () => false;
|
||||
await reset(); st('Measuring the screen refresh…'); await sleep(500);
|
||||
const hz = await refresh();
|
||||
const want0 = GLX.want, glOk = mapGl(true, false) && glInit(); const env = { gpu: GLX.gpu, ua: navigator.userAgent.replace(/^Mozilla\/5\.0 /, ''), w: innerWidth, h: innerHeight, dpr: devicePixelRatio, hz, cores: navigator.hardwareConcurrency, save: `${Object.keys(S.pops).length} POPs · ${S.links.length} links`, reps: REPS };
|
||||
mapGl(false, false);
|
||||
const rends = (glOk ? ['2d', 'gl'] : ['2d']).filter((x) => !ONLY || x === ONLY), all = {};
|
||||
// Scenario by scenario, both renderers in turn, the first one changing every time: neither always runs on a cold or
|
||||
// a tired browser.
|
||||
let n = 0;
|
||||
for (let rep = 0; rep < REPS; rep++) for (const [i, sc] of SCEN.entries()) for (const r of (rep + i) % 2 ? rends.slice().reverse() : rends) {
|
||||
mapGl(r === 'gl', false); n++;
|
||||
st(`${r === 'gl' ? 'WebGL' : '2D'} · ${sc.label}${REPS > 1 ? ` · run ${rep + 1}/${REPS}` : ''} (${SECS}s, ${n}/${REPS * SCEN.length * rends.length})… keep this tab in front`);
|
||||
const m = await measure(sc, hz, r); ((all[r] = all[r] || {})[sc.id] = all[r][sc.id] || []).push(m); if (m.hidden) env.invalid = true;
|
||||
}
|
||||
const res = { '2d': null, gl: null };
|
||||
for (const r of Object.keys(all)) { res[r] = {}; for (const id of Object.keys(all[r])) res[r][id] = merge(all[r][id]); }
|
||||
mapGl(want0, false); await reset();
|
||||
MD = table(res, env);
|
||||
st(glOk ? 'Done. The results are also in the terminal.' : 'Done (no WebGL2 here: 2D only).');
|
||||
box.querySelector('#bout').innerHTML = '<pre style="white-space:pre-wrap;font:11px/1.35 ui-monospace,monospace;margin:8px 0 0">' + MD.replace(/<\/?sub>/g, '').replace(/&/g, '&').replace(/</g, '<') + '</pre>';
|
||||
box.querySelector('#bcp').hidden = false; go.disabled = false; go.textContent = 'Run again';
|
||||
try { await fetch('/__bench/results', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ env, res, md: MD }) }); } catch (e) { /* the panel has them */ }
|
||||
}
|
||||
// tests/gpu-bench.test.js drives the pieces without the panel.
|
||||
if (CFG.expose) { window.__bench = { settle, reset, measure, merge, table, setSave: (s) => { SAVE = s; } }; return; }
|
||||
addEventListener('load', async () => {
|
||||
document.body.appendChild(box);
|
||||
while (typeof migrate !== 'function' || typeof GLX === 'undefined') await sleep(50);
|
||||
// A software renderer is measured too here (the game itself keeps the 2D map on one); the table names the renderer.
|
||||
GLX.soft = true;
|
||||
// ?dpr=2 draws the map as a screen of that density would (a 4K screen's pixels, measured on a smaller one).
|
||||
const DPRQ = +QS.get('dpr'); if (DPRQ > 0) { Object.defineProperty(window, 'devicePixelRatio', { get: () => DPRQ }); resize(); WL.key = null; }
|
||||
await sleep(800);
|
||||
try { SAVE = JSON.stringify((await (await fetch('/__bench/save.json')).json()).S || null); } catch (e) { st('Could not load the save: ' + e); return; }
|
||||
if (SAVE === 'null') { st('The save file has no game in it.'); return; }
|
||||
const runs = SCEN.length * (ONLY ? 1 : 2) * REPS;
|
||||
st(`Ready: ${SCEN.length} scenarios × ${ONLY ? 1 : 2} renderers${REPS > 1 ? ` × ${REPS}` : ''}, about ${Math.ceil(runs * (SECS + 3) / 60)} minutes. Keep this tab in front and do not touch the map.`);
|
||||
const go = box.querySelector('#bgo'); go.disabled = false; go.onclick = () => run().catch((e) => st('Failed: ' + (e && e.stack || e)));
|
||||
box.querySelector('#bcp').onclick = () => navigator.clipboard.writeText(MD).then(() => st('Copied.'), () => st('Copy failed: select the table instead.'));
|
||||
if (/[?&]auto\b/.test(location.search)) go.onclick();
|
||||
});
|
||||
})();
|
||||
5
scripts/lib/js-literal.js
Normal file
5
scripts/lib/js-literal.js
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
// A value as a JavaScript literal, safe to paste into code that is eval'd or into an inline <script>: JSON, with the
|
||||
// characters that could end a script tag or break a string (<, >, /, U+2028, U+2029) written as \u escapes.
|
||||
const ESC = /[<>\/\u2028\u2029]/g;
|
||||
const lit = (v) => { const s = JSON.stringify(v); return s === undefined ? 'undefined' : s.replace(ESC, (c) => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0')); };
|
||||
module.exports = { lit };
|
||||
64
scripts/lib/mcp-browser.js
Normal file
64
scripts/lib/mcp-browser.js
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
// The MCP server's browser session: the game in the player's tab, over the agent relay (scripts/lib/relay-client.js),
|
||||
// never a game of this process. The page owns the game (start, saves, seed), the clock (its Settings) and its windows;
|
||||
// the tools are the page's own facade (src/agent/, TUBES.call), called with ctx.relay, so the same tools play
|
||||
// the same way as the headless session (scripts/lib/mcp-game.js), with the player's rules on top.
|
||||
const { load } = require('../../tests/harness');
|
||||
const { pageCall } = require('./mcp-game');
|
||||
const { createRelaySession } = require('./relay-client');
|
||||
|
||||
// Days the player watches take their time: an advance may run for minutes on a big network.
|
||||
const ADVANCE_MS = 10 * 60 * 1000;
|
||||
// The sections of the contract a tab and this checkout must agree on. mode and clock are the live session's own.
|
||||
const CONTRACT = ['commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
|
||||
|
||||
// This checkout's contract, as a tab built from it would serve it over the relay.
|
||||
let LOCAL = null;
|
||||
function localSchema() {
|
||||
if (LOCAL) return LOCAL;
|
||||
const g = load({ agent: true });
|
||||
LOCAL = pageCall(g, 'schema', {}, { relay: true });
|
||||
if (g.errors.length) throw new Error(`the page assembled from src/ reported errors: ${g.errors.join('; ')}`);
|
||||
g.dom.window.close();
|
||||
return LOCAL;
|
||||
}
|
||||
// The sections in which a live tab's contract differs from this checkout's: a stale tab keeps names but may have
|
||||
// changed arguments, domains or docs, so the comparison is deep.
|
||||
const drift = (live, local = localSchema()) => CONTRACT.filter((k) => JSON.stringify(live && live[k]) !== JSON.stringify(local[k]));
|
||||
|
||||
function createBrowserSession(opts = {}) {
|
||||
const relay = createRelaySession(opts);
|
||||
const session = {
|
||||
mode: 'browser', relay,
|
||||
async tool(name, args = {}) {
|
||||
const r = await relay.call(name, args, { ms: name === 'advance' ? Math.max(relay.config.callMs, ADVANCE_MS) : undefined });
|
||||
if (r.refused) throw new Error(r.refused);
|
||||
return r.value;
|
||||
},
|
||||
call(name, args) { return session.tool(name, args); },
|
||||
headless() { throw new Error('Not in the player\'s browser: the game there is the player\'s to start, load and save.'); },
|
||||
loadSave() { return session.headless(); },
|
||||
info() { return { transport: 'relay', relay: relay.url }; },
|
||||
errors() { return []; },
|
||||
close() { return relay.close(); },
|
||||
// Wait for a page on the relay (up to waitMs), then check that it serves this checkout's contract.
|
||||
// Resolves {ok:true}, or {ok:false, why} for the server to say and stop on.
|
||||
async ready({ waitMs = 90000, onWait } = {}) {
|
||||
const deadline = Date.now() + waitMs;
|
||||
let said = false, why = 'no answer';
|
||||
for (;;) {
|
||||
const r = await relay.call('schema', {});
|
||||
if (!r.refused && r.value) {
|
||||
const d = drift(r.value);
|
||||
return d.length ? { ok: false, stale: d, why: `the game page in the browser disagrees with the code on disk (${d.join(', ')})` } : { ok: true };
|
||||
}
|
||||
why = r.refused || why;
|
||||
if (Date.now() >= deadline) return { ok: false, why: `no game page answered on the relay (${relay.url}): ${why}` };
|
||||
if (!said && onWait) { said = true; onWait(); }
|
||||
await new Promise((res) => setTimeout(res, 1000));
|
||||
}
|
||||
},
|
||||
};
|
||||
return session;
|
||||
}
|
||||
|
||||
module.exports = { createBrowserSession, drift, localSchema, CONTRACT };
|
||||
283
scripts/lib/mcp-game.js
Normal file
283
scripts/lib/mcp-game.js
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
// The game behind the MCP server (scripts/mcp.js), in one of two places. Headless (createSession): one game page of its
|
||||
// own, the development page from src/ (with the agent facade, src/agent/), loaded in jsdom as the tests load it
|
||||
// (tests/harness.js: seeded, no animation loop), with scripts/lib/mcp-headless.js added to start, load and export games.
|
||||
// In the browser (scripts/lib/mcp-browser.js): the game in the player's tab, over the agent relay. Either way every
|
||||
// other tool is the page's own facade (TUBES.call), so both play the same game the same way.
|
||||
//
|
||||
// TOOLS is the list the server offers; each says which sessions it works in (modes), and run() gets the session and
|
||||
// the tool's arguments and returns JSON, or a promise of it (the browser answers over a socket).
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../../tests/harness');
|
||||
|
||||
const HEADLESS_JS = fs.readFileSync(path.join(__dirname, 'mcp-headless.js'), 'utf8');
|
||||
const ACT_DIRS = ['90-actions', '94-dashboard', '96-map'].map((d) => path.join(__dirname, '..', '..', 'src', 'game', d));
|
||||
|
||||
// The arguments of the actions the command tables do not type (the drafts), read from their source
|
||||
// (`dfSrc:({v})=>`): in the page the actions are wrapped for puzzle mode, so their own parameter lists are not visible.
|
||||
let ACT_ARGS = null;
|
||||
function actArgs() {
|
||||
if (ACT_ARGS) return ACT_ARGS;
|
||||
ACT_ARGS = {};
|
||||
const re = /(?:^|[\s,{])([A-Za-z]\w*):\s*(?:async\s*)?\(\s*\{([^}]*)\}\s*(?:=\s*\{\s*\}\s*)?\)\s*=>/g;
|
||||
for (const [dir, f] of ACT_DIRS.flatMap((d) => fs.readdirSync(d).filter((f) => f.endsWith('.js')).sort().map((f) => [d, f]))) {
|
||||
const src = fs.readFileSync(path.join(dir, f), 'utf8');
|
||||
for (const m of src.matchAll(re)) if (!ACT_ARGS[m[1]]) ACT_ARGS[m[1]] = m[2].split(',').map((a) => a.split('=')[0].trim()).filter(Boolean);
|
||||
}
|
||||
return ACT_ARGS;
|
||||
}
|
||||
const MAX_INLINE_SAVE = 200000;
|
||||
const CLOCKS = ['agent', 'realtime'];
|
||||
const DEFAULT_PACE_MS = 60000;
|
||||
|
||||
|
||||
// One call into a jsdom page's facade, as JSON both ways: nothing but plain data crosses.
|
||||
function pageCall(g, tool, args = {}, ctx) {
|
||||
const w = g.dom.window;
|
||||
w.__mcpTool = tool; w.__mcpArgs = JSON.parse(JSON.stringify(args)); w.__mcpCtx = ctx || null;
|
||||
return JSON.parse(g.ev('JSON.stringify(TUBES.call(__mcpTool,__mcpArgs,__mcpCtx))') || 'null');
|
||||
}
|
||||
|
||||
// Where load_save and export_save may touch files. stdio (saveDir undefined): anywhere, as the operator's own client
|
||||
// asks. Over HTTP the client may be another machine: nowhere (null), or only under one directory, symlinks included.
|
||||
function savePath(s, p, write) {
|
||||
if (s.saveDir === undefined) return path.resolve(p);
|
||||
if (s.saveDir === null) throw new Error('This server takes saves as JSON only: give json instead of path (the server can allow a directory with --save-dir).');
|
||||
const root = s.saveDir, full = path.resolve(root, String(p));
|
||||
let real;
|
||||
try { real = write ? path.join(fs.realpathSync(path.dirname(full)), path.basename(full)) : fs.realpathSync(full); } catch (e) { throw new Error(`${p}: no such file or directory under the save directory`); }
|
||||
if (!real.startsWith(root + path.sep)) throw new Error(`${p} is outside the save directory.`);
|
||||
if (write && fs.existsSync(real) && fs.lstatSync(real).isSymbolicLink()) throw new Error(`${p} is a symbolic link: write to a plain file.`);
|
||||
return real;
|
||||
}
|
||||
|
||||
// opts.clock: 'agent' (time moves with advance) or 'realtime' (the session runs a day every opts.paceMs, and tools can
|
||||
// only wait). opts.seed, opts.file as tests/harness.js takes them (a file must be a development page: it carries the
|
||||
// facade). opts.saveDir: see savePath.
|
||||
function createSession(opts = {}) {
|
||||
const clock = CLOCKS.includes(opts.clock) ? opts.clock : 'agent';
|
||||
const paceMs = Math.max(10, Math.floor(+opts.paceMs) || DEFAULT_PACE_MS);
|
||||
let game = null, timer = null;
|
||||
const boot = () => {
|
||||
const g = load({ seed: opts.seed || 12345, file: opts.file, agent: true });
|
||||
g.ev(HEADLESS_JS);
|
||||
g.headless = (fn, ...args) => { g.dom.window.__mcpArgs = JSON.parse(JSON.stringify(args)); return JSON.parse(g.ev(`JSON.stringify(__mcpHeadless.${fn}(...window.__mcpArgs))`) || 'null'); };
|
||||
g.headless('setClock', clock, paceMs, clock === 'realtime');
|
||||
g.headless('newGame', { city: 'fra', name: 'Scratch Networks', preset: 'oncall' });
|
||||
// A running clock: the server keeps the time, one day per pace, whatever the tools do (as the player's tab does).
|
||||
if (clock === 'realtime') {
|
||||
timer = setInterval(() => { try { g.ev('apiTick()'); } catch (e) { g.errors.push(String(e && e.message || e)); } }, paceMs);
|
||||
if (timer.unref) timer.unref();
|
||||
}
|
||||
return g;
|
||||
};
|
||||
const session = {
|
||||
mode: 'headless', clock, paceMs: clock === 'realtime' ? paceMs : 0, saveDir: opts.saveDir,
|
||||
get game() { return game || (game = boot()); },
|
||||
// The page's own tools (TUBES.call), answered at once.
|
||||
tool(name, args) { return pageCall(session.game, name, args); },
|
||||
call(name, args) { return session.tool(name, args); },
|
||||
headless(fn, ...args) { return session.game.headless(fn, ...args); },
|
||||
// Text into the page without building a giant eval string (saves run to megabytes).
|
||||
loadSave(txt) { session.game.dom.window.__mcpSave = txt; return JSON.parse(session.game.ev('JSON.stringify(__mcpHeadless.loadSave(window.__mcpSave))')); },
|
||||
info() { return { transport: 'jsdom', clock, ...(clock === 'realtime' ? { paceMs } : {}) }; },
|
||||
errors() { return game ? game.errors.slice() : []; },
|
||||
close() { if (timer) clearInterval(timer); timer = null; },
|
||||
};
|
||||
return session;
|
||||
}
|
||||
|
||||
// A value or a promise of one, the same way: headless tools answer at once, the browser's over a socket.
|
||||
const then = (v, f) => (v && typeof v.then === 'function' ? v.then(f) : f(v));
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
const str = (description, extra = {}) => ({ type: 'string', description, ...extra });
|
||||
const num = (description, extra = {}) => ({ type: 'number', description, ...extra });
|
||||
const bool = (description) => ({ type: 'boolean', description });
|
||||
const obj = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
||||
const SECTIONS = ['mode', 'clock', 'commands', 'view', 'session', 'drafts', 'denied', 'domains', 'state', 'results'];
|
||||
const WHERE = ['modal', 'bank', 'dash', 'panel', 'left', 'puzzle'];
|
||||
const BOTH = ['headless', 'browser'], HEADLESS = ['headless'];
|
||||
// A page tool, passed straight through: the MCP tool's arguments are the facade's.
|
||||
const page = (name) => (s, a) => s.tool(name, a);
|
||||
|
||||
// wait: a running clock's days, read off the page until enough have passed (or something needs an answer).
|
||||
async function waitDays(s, a) {
|
||||
const days = Math.max(1, Math.min(365, Math.floor(+a.days) || 1)), maxMs = Math.max(1, Math.min(600, +a.maxSeconds || 120)) * 1000;
|
||||
const c0 = await s.tool('clock', {});
|
||||
if (c0.mode !== 'realtime') throw new Error('The clock here is yours and stands still between calls: use advance to move it.');
|
||||
const t0 = Date.now(), poll = Math.max(10, Math.min(250, (c0.paceMs || 1000) / 4));
|
||||
let c = c0, stop = null;
|
||||
if (!c0.running) stop = 'the clock is not running (no game, a puzzle, or the network is bankrupt)';
|
||||
while (!stop) {
|
||||
await sleep(poll);
|
||||
c = await s.tool('clock', {});
|
||||
if (c.day >= c0.day + days) break;
|
||||
if (c.lost) stop = 'bankrupt';
|
||||
else if (c.question && !c0.question) stop = 'a window opened';
|
||||
else if (Date.now() - t0 >= maxMs) stop = 'maxSeconds passed';
|
||||
}
|
||||
const since = await s.tool('since', { day: c0.day, cash: c0.cash, inc: c0.incidents });
|
||||
return { ...since, daysAsked: days, stoppedBecause: stop, waitedSeconds: Math.round((Date.now() - t0) / 100) / 10 };
|
||||
}
|
||||
|
||||
const TOOLS = [
|
||||
{
|
||||
name: 'new_game', modes: HEADLESS,
|
||||
description: 'Start a new network, replacing the current one. Presets: soft (Best Effort, the gentlest: no DDoS, no cable ships, no conferences, instant PNIs, patient customers, a rescue loan instead of game over), freeze (Change Freeze, gentle), oncall (On-call, the classic game), bgp (BGP at 3 a.m., harsh), sandbox (endless money, every level; chaos sets how often things break, default none). Seeded, so the same seed and the same moves give the same game. Scenarios, puzzles and architect runs start with act (startScn, pzStart, pzArStart).',
|
||||
inputSchema: obj({ city: str('Home city: id (fra) or name (Frankfurt). Default Frankfurt.'), name: str('Network name (24 characters at most). Default: a random pun.'),
|
||||
preset: str('Rules preset', { enum: ['soft', 'freeze', 'oncall', 'bgp', 'sandbox'] }), seed: num('Random seed, default 12345.'),
|
||||
asn: num('Your own AS number, as the title screen takes it. Default: a free one.'), chaos: str('Sandbox only: how often things break. Default none.', { enum: ['none', 'calm', 'normal', 'spicy'] }) }),
|
||||
run: (s, a) => s.headless('newGame', a),
|
||||
},
|
||||
{
|
||||
name: 'load_save', modes: HEADLESS,
|
||||
description: 'Load a saved game: a file exported from the game (Menu → Export save, the series-of-tubes-*.json from a bug report) or a raw save, as a path or as JSON text. Old saves are migrated exactly as the game does.',
|
||||
inputSchema: obj({ path: str('Path to a .json save file.'), json: str('The save itself, as JSON text.') }),
|
||||
run: (s, a) => {
|
||||
if (!a.path === !a.json) throw new Error('Give either path or json.');
|
||||
const txt = a.path ? fs.readFileSync(savePath(s, a.path, false), 'utf8') : a.json;
|
||||
return s.loadSave(txt);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'export_save', modes: HEADLESS,
|
||||
description: 'Export the current game as a save file the real game can import (Menu → Import save). Writes it to path, or returns it when it is small.',
|
||||
inputSchema: obj({ path: str('Where to write the .json file.') }),
|
||||
run: (s, a) => {
|
||||
const txt = s.headless('exportSave', require('../../package.json').version);
|
||||
if (a.path) { const f = savePath(s, a.path, true); fs.writeFileSync(f, txt); return { wrote: f, bytes: Buffer.byteLength(txt) }; }
|
||||
if (txt.length > MAX_INLINE_SAVE) throw new Error(`The save is ${txt.length} characters; give a path to write it to.`);
|
||||
return JSON.parse(txt);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'status', modes: BOTH,
|
||||
description: 'The network at a glance: date, cash, monthly revenue and costs by kind, level, tier and why it is not Tier 1 yet, the current goal, traffic, reach, counts, POPs and open incidents.',
|
||||
inputSchema: obj(),
|
||||
run: page('status'),
|
||||
},
|
||||
{
|
||||
name: 'advance', modes: BOTH,
|
||||
description: 'With the agent\'s clock (schema mode.clock "agent"): run the game forward day by day, as the game loop does. Stops early when a window opens (then read it with screen and answer it with click or act; decision says when it is a question with options) or the network goes bankrupt. Returns what happened: log, toasts, new incidents, cash, and how long each simulated day took. With a running clock it is an error: use wait.',
|
||||
inputSchema: obj({ days: num('Days to run, 1 to 3650. Default 1.') }),
|
||||
run: page('advance'),
|
||||
},
|
||||
{
|
||||
name: 'wait', modes: BOTH,
|
||||
description: 'With a running clock (schema mode.clock "realtime"): days pass on their own at a fixed pace and nobody can stop them. wait returns once that many have passed, or earlier when a window asks a question, the network goes bankrupt or maxSeconds of real time are up. Returns what happened meanwhile: log, new incidents, cash. With the agent\'s clock it is an error: use advance.',
|
||||
inputSchema: obj({ days: num('Days to wait for, 1 to 365. Default 1.'), maxSeconds: num('Give up after this much real time, 1 to 600. Default 120.') }),
|
||||
run: (s, a) => waitDays(s, a),
|
||||
},
|
||||
{
|
||||
name: 'network', modes: BOTH,
|
||||
description: 'Everything about one network (a carrier, eyeball network, CDN…): type, peering policy and what it asks for, traffic share, transit price, PoPs, exchanges, upstreams and customer cone, whether Tier 1 needs it, and for you: demand, how its traffic leaves you (egress by kind), your PNIs and sessions with it, and how to move it to peering.',
|
||||
inputSchema: obj({ network: str('Id (dtk), name (Doitsche Telekomm) or ASN.') }, ['network']),
|
||||
run: page('network'),
|
||||
},
|
||||
{
|
||||
name: 'city', modes: BOTH,
|
||||
description: 'One city: country, exchanges and their member counts, data center, who sells transit there and at what price, the networks present, the cables that land there, and your POP if you have one.',
|
||||
inputSchema: obj({ city: str('Id (fra) or name (Frankfurt).') }, ['city']),
|
||||
run: page('city'),
|
||||
},
|
||||
{
|
||||
name: 'find', modes: BOTH,
|
||||
description: 'Search cities, networks, cables and exchanges by name, id or ASN. Use it to get the ids other tools and actions take.',
|
||||
inputSchema: obj({ query: str('Part of a name, an id or an ASN.'), kind: str('Only this kind', { enum: ['city', 'network', 'cable', 'exchange'] }) }, ['query']),
|
||||
run: page('find'),
|
||||
},
|
||||
{
|
||||
name: 'traceroute', modes: BOTH,
|
||||
description: 'The game\'s looking glass: the path traffic takes from one of your POPs to a network (which exit wins and why, with the AS path) or to another of your POPs (prefix it city:).',
|
||||
inputSchema: obj({ from: str('One of your POPs: id or name.'), to: str('A network (id, name or ASN), or city:<one of your POPs>.') }, ['from', 'to']),
|
||||
run: page('traceroute'),
|
||||
},
|
||||
{
|
||||
name: 'peering_check', modes: BOTH,
|
||||
description: 'Would this network peer with you, and if not, why not? Checks a PNI at each of your POPs where it is, and a session at each exchange you are on where it is a member, with the game\'s own reasons (traffic it wants, paid peering, the Tier 1 club…).',
|
||||
inputSchema: obj({ network: str('Id, name or ASN.'), city: str('Only this city.'), via: str('Only this way', { enum: ['pni', 'ix'] }) }, ['network']),
|
||||
run: page('peering_check'),
|
||||
},
|
||||
{
|
||||
name: 'hot_spots', modes: BOTH,
|
||||
description: 'Where it hurts: the fullest links, transit ports and PNIs, the transit bill by carrier, and the networks with the most traffic still over transit, each with the cheapest way to peer with it.',
|
||||
inputSchema: obj({ limit: num('How many of each, default 10.') }),
|
||||
run: page('hot_spots'),
|
||||
},
|
||||
{
|
||||
name: 'schema', modes: BOTH,
|
||||
description: 'The typed contract act checks against: which session this is (mode: headless or the player\'s browser, and whose clock), every game command with its arguments, their domains and a description, which ones dry-run, decide or confirm; view commands; session actions (scenarios, puzzles, runs); drafts (inputs another command reads); what is not available and why; the argument domains; and a field-by-field reference of state and results. Give section for one part.',
|
||||
inputSchema: obj({ section: str('One part only', { enum: SECTIONS }) }),
|
||||
run: (s, a) => then(s.tool('schema', a), (v) => (!a.section ? { ...v, mode: { ...v.mode, ...s.info() } } : a.section === 'mode' ? { ...v, ...s.info() } : v)),
|
||||
},
|
||||
{
|
||||
name: 'catalog', modes: BOTH,
|
||||
description: 'The game\'s reference tables, which the argument domains point at: CITIES, NETS, CABLES, PORT, LT, OPT, DF_SYS, FAB, INTERNS, OPSK, CHARTERS, SCN, BANKS… plus three made for you: conferences (the upcoming calendar with the keys confGo and confSponsor take), TE_RECIPES (each RouteScript recipe with its script, ready for teDeploy) and BADGES (as the badge wall shows them). Omit name for the list of tables with their sizes.',
|
||||
inputSchema: obj({ name: str('One table; omit for the list.') }),
|
||||
run: page('catalog'),
|
||||
},
|
||||
{
|
||||
name: 'state', modes: BOTH,
|
||||
description: 'The saved game itself as JSON, the same object the game saves: offers, loan offers, links, ports, PNIs, customers, the intern, events… with their ids. schema section "state" documents each field; in the player\'s browser the dice (the seed, the days of the next failure and event) are held back. Give a path (pops.fra, links, loanOffers, biz.3, links.<id>): the whole state of a big network is hundreds of KB.',
|
||||
inputSchema: obj({ path: str('Dotted path: a key, an array index or an entity id per step.') }),
|
||||
run: page('state'),
|
||||
},
|
||||
{
|
||||
name: 'results', modes: BOTH,
|
||||
description: 'The game\'s last traffic computation (R), rebuilt after every action and every day: load per link, use per port, demand and served per city, egress per network, monthly cost and revenue by kind, latency, reach. schema section "results" documents each field. Give a path (load, cost, netEg.ggl).',
|
||||
inputSchema: obj({ path: str('Dotted path.') }),
|
||||
run: page('results'),
|
||||
},
|
||||
{
|
||||
name: 'ui', modes: BOTH,
|
||||
description: 'The view state actions read and write (the selection, the pending link pair, the drafts of the link, fiber and cable windows, the RouteScript draft, confirmations), without render caches. For working out why an action did what it did.',
|
||||
inputSchema: obj(),
|
||||
run: page('ui'),
|
||||
},
|
||||
{
|
||||
name: 'actions', modes: BOTH,
|
||||
description: 'Every action act can run, with its arguments (? marks an optional one), e.g. buildPop(city), buyTransit(city,net,tier), buildLink(a,b,tier,cable?,route?,premiumCrossing?). Port tiers: 0 = 10G, 1 = 100G, 2 = 400G, 3 = 800G. Exchanges are given as city=<exchange id>. schema has each one\'s argument domains and what it does.',
|
||||
inputSchema: obj(),
|
||||
run: (s) => then(s.tool('actions', {}), ({ typed, drafts }) => {
|
||||
const a = actArgs();
|
||||
return [...Object.entries(typed).map(([k, sig]) => `${k}(${sig})`), ...drafts.map((k) => (a[k] ? `${k}(${a[k].join(',')})` : k))].sort();
|
||||
}),
|
||||
},
|
||||
{
|
||||
name: 'act', modes: BOTH,
|
||||
description: 'Do something in the game: run one action with its arguments (see actions and schema). Arguments are checked first (a wrong id or value is an error that lists what fits); the action then runs as the game runs it: windows that take typed text are filled in (renameGo, teDeploy, teCheck, metricSet), multi-step builds take their choices as arguments (buildLink, orderDf, orderCable, decomGo), and confirmations are given (rmLink, cancelTransit…). outcome says what happened: applied (something changed), rejected (the game said no, see toasts), no_effect (nothing changed and nothing was said), shown (a view or draft: only the screen changed), decision (a window asks a question: answer with one of decision.options or closeModal; other game commands wait), quote (dryRun), stopped (bankrupt). charged is what the money gate took; cashChange also counts goal rewards. With dryRun, a game command is priced with the game\'s own helpers and nothing happens. In the player\'s browser, a window the player opened stays theirs: you play behind it.',
|
||||
inputSchema: obj({ action: str('Action name, e.g. buildPop (view. prefixes are accepted).'), command: str('Same as action.'), args: { type: 'object', description: 'Its arguments, e.g. {"city":"ams"}.' },
|
||||
dryRun: bool('Price it and check it can be done: {setup, monthly, days, blocked}. Nothing happens.') }),
|
||||
run: page('act'),
|
||||
},
|
||||
{
|
||||
name: 'screen', modes: BOTH,
|
||||
description: 'What the player sees, as text with numbered buttons for click: the open window, else the bank or the NOC dashboard when open, else the side panel, else the puzzle box. where picks one: modal, bank, dash, panel, left (the left drawer: goals, deals, noc or nets) or puzzle. open lists what is showing. Long text comes in pages: textMore says the offset of the next one. Lists the game acts on when they change come with their options; click them with a value.',
|
||||
inputSchema: obj({ where: str('Which surface', { enum: WHERE }), offset: num('Start the text here (from textMore).') }),
|
||||
run: page('screen'),
|
||||
},
|
||||
{
|
||||
name: 'panel', modes: BOTH,
|
||||
description: 'Open the side panel of a city or a link, a network in the network list, or a tab of the left drawer (goals, deals: offers and loans, noc, nets), optionally on a tab (a city has cust, up, peer, infra…), and show it as text with numbered buttons.',
|
||||
inputSchema: obj({ city: str('City id or name.'), link: str('Link id (from status, hot_spots or state links).'), network: str('Network id or name.'), tab: str('Tab id, as the tab buttons name it.'),
|
||||
left: str('A tab of the left drawer', { enum: ['goals', 'deals', 'noc', 'nets'] }) }),
|
||||
run: page('panel'),
|
||||
},
|
||||
{
|
||||
name: 'click', modes: BOTH,
|
||||
description: 'Press a numbered button from the last screen, panel or act result, as a player\'s click does: with the button\'s own arguments, so confirmations arm first and windows step on as in the game. For a list (it has options), give value.',
|
||||
inputSchema: obj({ button: num('The button\'s n.'), value: str('For a list: the option to pick.') }, ['button']),
|
||||
run: page('click'),
|
||||
},
|
||||
{
|
||||
name: 'open_link', modes: BOTH,
|
||||
description: 'Open the build window for a link (a leased wave, dark fiber or your own cable) from one of your POPs to any city, to compare the routes and sizes it offers; then click through it. act buildLink, orderDf and orderCable do the same in one call.',
|
||||
inputSchema: obj({ from: str('One of your POPs.'), to: str('Any city.') }, ['from', 'to']),
|
||||
run: page('open_link'),
|
||||
},
|
||||
];
|
||||
|
||||
const toolsFor = (mode) => TOOLS.filter((t) => t.modes.includes(mode));
|
||||
|
||||
module.exports = { createSession, TOOLS, toolsFor, actArgs, pageCall, savePath, CLOCKS, DEFAULT_PACE_MS };
|
||||
36
scripts/lib/mcp-headless.js
Normal file
36
scripts/lib/mcp-headless.js
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// Runs inside the MCP server's own game page (scripts/lib/mcp-game.js), in the game's global scope, after the page has
|
||||
// loaded: the half of a session only that page has. It starts, loads and exports games, which in a player's browser
|
||||
// are the player's alone, so it is not part of any page. Everything else a tool does goes through the page's own
|
||||
// facade (window.TUBES, src/agent/).
|
||||
(() => {
|
||||
// Out of the way of the game: no sheet of a previous game, no title screen or pitch, the clock left to the server.
|
||||
const settle = () => { UI.started = true; UI.pitched = true; UI.speed = 0; if (UI.pendGame) ACT.pitchSkip(); closeModal(); API_SHEET = null; compute(); renderAll(); };
|
||||
const newGame = ({ city = 'fra', name, preset = 'oncall', seed, asn, chaos } = {}) => {
|
||||
const c = apiCityOf(city).id;
|
||||
if (!homeOk(c)) apiFail(`${apiCityName(c)} cannot be a home city.`);
|
||||
if (!['soft', 'freeze', 'oncall', 'bgp', 'sandbox'].includes(preset)) apiFail('preset is one of soft, freeze, oncall, bgp, sandbox');
|
||||
if (asn !== undefined && !asnOk(+asn)) apiFail(`AS${asn} cannot be yours: it is reserved, private or another network's. Leave asn out for a free one.`);
|
||||
if (chaos !== undefined && preset !== 'sandbox') apiFail('chaos is the sandbox\'s dial: give preset "sandbox" with it.');
|
||||
if (chaos !== undefined && !own(CHAOS, chaos)) apiFail(`chaos is one of ${Object.keys(CHAOS).join(', ')}.`);
|
||||
if (seed !== undefined && window.__reseed) window.__reseed(Math.max(1, Math.floor(+seed) || 1));
|
||||
if (UI.pendGame) UI.pendGame = null;
|
||||
UI.pitched = true;
|
||||
const nm = String(name || randomNetworkName()).slice(0, 24), was = UI.asnTxt;
|
||||
// beginGame takes the ASN typed on the title screen.
|
||||
UI.asnTxt = asn !== undefined ? String(+asn) : '';
|
||||
try { beginGame(nm, c, preset === 'sandbox' ? { mode: 'sandbox', rules: { chaos: chaos || 'none' } } : { mode: 'normal', preset }); } finally { UI.asnTxt = was; }
|
||||
settle();
|
||||
return apiStatus();
|
||||
};
|
||||
const loadSave = (txt) => {
|
||||
const r = parseSave(txt);
|
||||
if (r.err) apiFail(apiText(r.err));
|
||||
S = migrate(JSON.parse(JSON.stringify(r.s)));
|
||||
settle();
|
||||
return { savedBy: r.ver, ...apiStatus() };
|
||||
};
|
||||
const exportSave = (version) => JSON.stringify({ app: 'series-of-tubes', version: /^\d/.test(APP_VERSION) ? APP_VERSION : version, exported: new Date().toISOString(), S: packSave(S) });
|
||||
// The server's clock: the agent's (advance), or a running one it ticks itself (apiTick) at paceMs.
|
||||
const setClock = (mode, paceMs, running) => { API_CLK = { mode, paceMs: mode === 'realtime' ? paceMs : 0, running: !!running }; };
|
||||
window.__mcpHeadless = { newGame, loadSave, exportSave, setClock };
|
||||
})();
|
||||
650
scripts/lib/mp-sim-acts.js
Normal file
650
scripts/lib/mp-sim-acts.js
Normal file
|
|
@ -0,0 +1,650 @@
|
|||
// What a page of a server-run network may ask the session server to do, as plain data, and the envelope check every
|
||||
// request body passes before anything reaches a game (docs: the server-sim design, sections 5.8-5.9 and 10).
|
||||
// Shared by the realm (scripts/lib/mp-sim-realm.js), the host (scripts/lib/mp-sim.js) and the page's own copies
|
||||
// (src/game/98-server-play/40-acts.js), which tests hold equal to these tables. Plain data only: no game code here,
|
||||
// and nothing here is ever evaluated.
|
||||
//
|
||||
// Every ACT is in exactly one of SEND, ASK, VOTE, LOCAL or PUZZLE (tests/mp-sim-contract.test.js names the act and this
|
||||
// file when one is not). SEND is the agent's API_CMD minus the pz* acts and teCheck, traceRun, closeModal, plus
|
||||
// connCancel, pieRename and tutSkip: a test derives it again, so nobody counts it by hand.
|
||||
'use strict';
|
||||
|
||||
// Acts that change the game: the page sends them, the server runs them as a click (ACT[act](args)).
|
||||
const SEND = [
|
||||
'accept',
|
||||
'acceptFix',
|
||||
'ad',
|
||||
'addCh',
|
||||
'addGen',
|
||||
'addPair',
|
||||
'addRouter',
|
||||
'addSite',
|
||||
'applyCn',
|
||||
'bstdApply',
|
||||
'bstdSet',
|
||||
'buildLink',
|
||||
'buildPop',
|
||||
'buildScrub',
|
||||
'buyIx',
|
||||
'buyNni',
|
||||
'buySat',
|
||||
'buySpare',
|
||||
'buyTE',
|
||||
'buyTransit',
|
||||
'buyVxc',
|
||||
'cache',
|
||||
'cacheSite',
|
||||
'callBank',
|
||||
'cancelIx',
|
||||
'cancelPni',
|
||||
'cancelTransit',
|
||||
'cancelVxc',
|
||||
'charter',
|
||||
'cleanPipe',
|
||||
'confGo',
|
||||
'confSponsor',
|
||||
'connCancel',
|
||||
'coreLab',
|
||||
'coreSet',
|
||||
'coreUp',
|
||||
'crews',
|
||||
'ddosAuto',
|
||||
'ddosEngage',
|
||||
'ddosTest',
|
||||
'decline',
|
||||
'declineLoan',
|
||||
'decomGo',
|
||||
'demoAsk',
|
||||
'dkAccept',
|
||||
'dkHaggle',
|
||||
'dkOptOut',
|
||||
'dkStay',
|
||||
'dkWalk',
|
||||
'downIx',
|
||||
'downP',
|
||||
'downT',
|
||||
'dropBiz',
|
||||
'fixInc',
|
||||
'foundIx',
|
||||
'hackback',
|
||||
'hwLock',
|
||||
'ip4Back',
|
||||
'ip4Buy',
|
||||
'ip4Lease',
|
||||
'ip4Nat',
|
||||
'ip4Nat64',
|
||||
'ip4Out',
|
||||
'ip4Return',
|
||||
'ip4Sell',
|
||||
'ip6Go',
|
||||
'ip6Stop',
|
||||
'lagIx',
|
||||
'lagNni',
|
||||
'lagP',
|
||||
'lagT',
|
||||
'launchBB',
|
||||
'layShip',
|
||||
'listFiber',
|
||||
'metricMode',
|
||||
'metricSet',
|
||||
'mkBanana',
|
||||
'mktCfg',
|
||||
'mktHold',
|
||||
'mktRoute',
|
||||
'myIxUp',
|
||||
'opsCap',
|
||||
'opsFire',
|
||||
'opsFloor',
|
||||
'opsHire',
|
||||
'opsNewPop',
|
||||
'opsParam',
|
||||
'opsPop',
|
||||
'opsToggle',
|
||||
'opsTpl',
|
||||
'orderCable',
|
||||
'orderDf',
|
||||
'pathAuto',
|
||||
'pathMove',
|
||||
'pathPin',
|
||||
'peer',
|
||||
'peerAll',
|
||||
'peerPol',
|
||||
'pieAnt',
|
||||
'pieBid',
|
||||
'pieDish',
|
||||
'pieExim',
|
||||
'pieFactory',
|
||||
'pieFound',
|
||||
'pieLaunch',
|
||||
'pieLic',
|
||||
'pieName',
|
||||
'piePad',
|
||||
'pieRd',
|
||||
'pieRename',
|
||||
'pieSafe',
|
||||
'pieSpatPick',
|
||||
'pni',
|
||||
'pniAll',
|
||||
'pniChase',
|
||||
'popStdClear',
|
||||
'popStdSet',
|
||||
'ptAll',
|
||||
'ptApply',
|
||||
'ptSave',
|
||||
'regen',
|
||||
'renameGo',
|
||||
'renewLet',
|
||||
'renewMatch',
|
||||
'renewMeet',
|
||||
'repayLoan',
|
||||
'rmCache',
|
||||
'rmCh',
|
||||
'rmLink',
|
||||
'rmNni',
|
||||
'rmRouter',
|
||||
'rmScrub',
|
||||
'rmSite',
|
||||
'rs',
|
||||
'rtbh',
|
||||
'sacrif',
|
||||
'salesAuto',
|
||||
'salesFire',
|
||||
'salesHire',
|
||||
'salesMin',
|
||||
'salesRen',
|
||||
'salesVp',
|
||||
'satSize',
|
||||
'scrubMode',
|
||||
'scrubUp',
|
||||
'seaRush',
|
||||
'seatBuy',
|
||||
'seatNo',
|
||||
'sellSpare',
|
||||
'setCarry',
|
||||
'setChCount',
|
||||
'setMetric',
|
||||
'setPref',
|
||||
'setRoute',
|
||||
'setStandby',
|
||||
'siteSet',
|
||||
'spares',
|
||||
'subUpgrade',
|
||||
'takeLoan',
|
||||
'teClear',
|
||||
'teDeploy',
|
||||
'teToggle',
|
||||
'teleBuild',
|
||||
'teleLeo',
|
||||
'teleLeoRm',
|
||||
'teleRm',
|
||||
'teleTrk',
|
||||
'togglePrem',
|
||||
'tutSkip',
|
||||
'unlistFiber',
|
||||
'unpeer',
|
||||
'unrtbh',
|
||||
'upLink',
|
||||
'upRouter',
|
||||
'upSys',
|
||||
'upVxc',
|
||||
'utilityCaches',
|
||||
'utilityKit',
|
||||
'utilityKitAll',
|
||||
'utilityKitNew',
|
||||
'utilityPeers',
|
||||
'utilityRouteServers',
|
||||
'wispRm',
|
||||
'wispSat',
|
||||
'wispSatRm',
|
||||
'wispSatSize',
|
||||
'wispSpur',
|
||||
'xpBuild',
|
||||
'xpCh',
|
||||
];
|
||||
// What-ifs the server answers with the window they open, putting the game back as it was (5.9).
|
||||
const ASK = ['linkCheck', 'teCheck', 'teSlop'];
|
||||
// The clock's buttons: on a server network they are a vote for the session's speed (4.5).
|
||||
const VOTE = ['phonePlay', 'phoneSpeed', 'speed'];
|
||||
// The page runs these itself: views, drafts, settings, slots, session acts, teOpt.
|
||||
const LOCAL = [
|
||||
'addParallel',
|
||||
'animSet',
|
||||
'bank',
|
||||
'bankClose',
|
||||
'bstdOpen',
|
||||
'chaosSet',
|
||||
'chartToggle',
|
||||
'closeModal',
|
||||
'closePanel',
|
||||
'cnPrem',
|
||||
'connCity',
|
||||
'connF',
|
||||
'connFor',
|
||||
'connNet',
|
||||
'connOpen',
|
||||
'connSort',
|
||||
'cont',
|
||||
'custCity',
|
||||
'custF',
|
||||
'custGo',
|
||||
'custOpen',
|
||||
'custSort',
|
||||
'dash',
|
||||
'dashClose',
|
||||
'dashLink',
|
||||
'dashSort',
|
||||
'dashTab',
|
||||
'decomOpen',
|
||||
'decomToggle',
|
||||
'dfMode',
|
||||
'dfSrc',
|
||||
'dfSys',
|
||||
'exportSave',
|
||||
'findGo',
|
||||
'findLink',
|
||||
'findOpen',
|
||||
'focusCity',
|
||||
'goConn',
|
||||
'goEgress',
|
||||
'help',
|
||||
'helpClose',
|
||||
'importGo',
|
||||
'importPick',
|
||||
'install',
|
||||
'ip4Open',
|
||||
'ip4Pick',
|
||||
'keepPlaying',
|
||||
'keys',
|
||||
'langSet',
|
||||
'leaseSwap',
|
||||
'leftTab',
|
||||
'linkTo',
|
||||
'listMore',
|
||||
'logAll',
|
||||
'logOpen',
|
||||
'mapSet',
|
||||
'marketOpen',
|
||||
'meetGo',
|
||||
'menu',
|
||||
'modeSet',
|
||||
'models',
|
||||
'mpBack',
|
||||
'mpChat',
|
||||
'mpCopyLink',
|
||||
'mpDoor',
|
||||
'mpJoin',
|
||||
'mpKeep',
|
||||
'mpLeave',
|
||||
'mpLeaveAsk',
|
||||
'mpNewer',
|
||||
'mpOpen',
|
||||
'mpShare',
|
||||
'mpStart',
|
||||
'mute',
|
||||
'netClear',
|
||||
'netFilter',
|
||||
'netFind',
|
||||
'netFocus',
|
||||
'netOnly',
|
||||
'newgame',
|
||||
'nocWindow',
|
||||
'offerStep',
|
||||
'openVxc',
|
||||
'opsCity',
|
||||
'opsOpen',
|
||||
'ownCab',
|
||||
'pathOpen',
|
||||
'phoneTab',
|
||||
'pickHome',
|
||||
'pickStart',
|
||||
'pieCity',
|
||||
'pieGlobeNight',
|
||||
'pieGovOpen',
|
||||
'pieHi',
|
||||
'pieIns',
|
||||
'pieLas',
|
||||
'pieOpen',
|
||||
'pieSpatOpen',
|
||||
'pieTab',
|
||||
'pitchSkip',
|
||||
'pniAllOpen',
|
||||
'pniAllSize',
|
||||
'pniFilter',
|
||||
'pniGrp',
|
||||
'pniSort',
|
||||
'popGo',
|
||||
'popStep',
|
||||
'popsReg',
|
||||
'popsSort',
|
||||
'prefSet',
|
||||
'presetSet',
|
||||
'puzzleDoor',
|
||||
'puzzleMenu',
|
||||
'randomName',
|
||||
'rename',
|
||||
'resetAsk',
|
||||
'route',
|
||||
'routingOpen',
|
||||
'salesOpen',
|
||||
'satOpen',
|
||||
'scenarios',
|
||||
'seaDesign',
|
||||
'seaPackage',
|
||||
'selLink',
|
||||
'settings',
|
||||
'settingsClose',
|
||||
'share',
|
||||
'shareDl',
|
||||
'shareGo',
|
||||
'slotBack',
|
||||
'slotDel',
|
||||
'slotDelGo',
|
||||
'slotExport',
|
||||
'slotMenu',
|
||||
'slotRetry',
|
||||
'slotSpace',
|
||||
'slotSwitch',
|
||||
'slotTake',
|
||||
'soundSet',
|
||||
'start',
|
||||
'startScn',
|
||||
'startWeekly',
|
||||
'tab',
|
||||
'tailTog',
|
||||
'teBack',
|
||||
'teClose',
|
||||
'teEdit',
|
||||
'teExample',
|
||||
'teHelp',
|
||||
'teOpt',
|
||||
'teRecipe',
|
||||
'themeSet',
|
||||
'toTitle',
|
||||
'toggleLeft',
|
||||
'trace',
|
||||
'traceCopy',
|
||||
'traceMode',
|
||||
'traceRun',
|
||||
'updateLater',
|
||||
'updateNow',
|
||||
'utilities',
|
||||
'utilityPick',
|
||||
'via',
|
||||
'vpSet',
|
||||
'whatsNewShow',
|
||||
'wispOpen',
|
||||
'wsShare',
|
||||
'xfer',
|
||||
'xferFile',
|
||||
'xferLink',
|
||||
'xferPaste',
|
||||
'xferRecv',
|
||||
'xferShare',
|
||||
'xpOpen',
|
||||
'zoomStep',
|
||||
];
|
||||
// Puzzles never run on the server: they stay on the device, like everything that starts with pz.
|
||||
const PUZZLE = [
|
||||
'pzAddPar',
|
||||
'pzArAll',
|
||||
'pzArGo',
|
||||
'pzArNext',
|
||||
'pzArSkip',
|
||||
'pzArStart',
|
||||
'pzCity',
|
||||
'pzDiv',
|
||||
'pzFinish',
|
||||
'pzLeave',
|
||||
'pzLink',
|
||||
'pzLinkTo',
|
||||
'pzLook',
|
||||
'pzMkSkip',
|
||||
'pzMonkey',
|
||||
'pzPop',
|
||||
'pzReset',
|
||||
'pzRetry',
|
||||
'pzRmLink',
|
||||
'pzRmPop',
|
||||
'pzRoute',
|
||||
'pzRtAdd',
|
||||
'pzRtModel',
|
||||
'pzRtRm',
|
||||
'pzShare',
|
||||
'pzStart',
|
||||
'pzTab',
|
||||
'pzTier',
|
||||
'pzUndo',
|
||||
'pzVia',
|
||||
'pzWeekly',
|
||||
];
|
||||
|
||||
/* Two-click buttons: the first click arms the button on the page (a view change), only the second is sent, with
|
||||
confirmed:true. 'arg': the act takes ok:1 and runs at once. Anything else: the key the first click writes to
|
||||
UI.confirm, as a template over the act's args ({id} is String(args.id)); the server sets UI.confirm to it and runs the
|
||||
act once. */
|
||||
const CONFIRM = {
|
||||
cancelIx: 'arg',
|
||||
cancelPni: 'arg',
|
||||
cancelTransit: 'arg',
|
||||
cancelVxc: '{id}',
|
||||
connCancel: 'cc:{k}:{id}',
|
||||
dkOptOut: 'dk{city}{n}',
|
||||
dropBiz: '{id}',
|
||||
ip4Sell: '{id}',
|
||||
opsFire: 'opsFire',
|
||||
repayLoan: '{id}',
|
||||
rmLink: '{id}',
|
||||
rmScrub: 'scrub:{city}',
|
||||
rmSite: 'site{city}',
|
||||
salesFire: 'salesFire',
|
||||
teleLeoRm: 'leo:{city}',
|
||||
teleRm: 'tele:{city}',
|
||||
wispRm: 'wz:{z}',
|
||||
wispSatRm: 'wsat:{z}',
|
||||
};
|
||||
// The UI.confirm key a preset act's first click writes (null for 'arg' acts and acts that do not confirm).
|
||||
const SRV_ARM = Object.fromEntries(Object.entries(CONFIRM).filter(([, v]) => v !== 'arg'));
|
||||
function armKey(act, args) {
|
||||
const t = Object.prototype.hasOwnProperty.call(SRV_ARM, act) ? SRV_ARM[act] : null;
|
||||
return t === null ? null : t.replace(/\{(\w+)\}/g, (m, k) => String(args && args[k] !== undefined ? args[k] : ''));
|
||||
}
|
||||
|
||||
/* The UI drafts an act reads, and the only UI keys a request may set (its ui object). Types are checked here; the realm
|
||||
checks the values against the game's catalogs (cities, CABLES, DF_SYS, SEA_DESIGNS, the route picker's values). */
|
||||
const DRAFTS = {
|
||||
buildLink: ['pending', 'route', 'via', 'cnPrem'],
|
||||
decomGo: ['decom'],
|
||||
orderCable: ['pending', 'seaDesign', 'seaterminal', 'seaengineering'],
|
||||
orderDf: ['pending', 'dfSrc', 'dfSys'],
|
||||
pieLaunch: ['pieIns', 'pieLas'],
|
||||
teDeploy: ['slop'],
|
||||
};
|
||||
// pair: {a, b}, two different city-like ids; id: a short id string; ids: an array of at most 200 of them (a Set in the game).
|
||||
const DRAFT_TYPES = {
|
||||
cnPrem: 'boolean',
|
||||
decom: 'ids',
|
||||
dfSrc: ['lease', 'build', 'cable'],
|
||||
dfSys: 'id',
|
||||
pending: 'pair',
|
||||
pieIns: 'boolean',
|
||||
pieLas: 'boolean',
|
||||
route: 'string',
|
||||
seaDesign: 'id',
|
||||
seaengineering: 'boolean',
|
||||
seaterminal: 'boolean',
|
||||
slop: 'boolean',
|
||||
via: 'string',
|
||||
};
|
||||
|
||||
// Args longer than the envelope's 64 characters: their own cap (the game cuts the texts shorter itself).
|
||||
const TEXT = {
|
||||
metricSet: { v: 16 },
|
||||
// A pinned path's cities, comma-separated: a long path is longer than 64 characters.
|
||||
pathPin: { via: 1024 },
|
||||
pieRename: { name: 64 },
|
||||
renameGo: { name: 64 },
|
||||
teCheck: { script: 4000 },
|
||||
teDeploy: { script: 4000 },
|
||||
utilityCaches: { quote: 1024 },
|
||||
// An express's spans, as link ids joined by ',' (up to XP_HOPS = 6 ids of about 10 characters).
|
||||
xpBuild: { via: 256 },
|
||||
};
|
||||
|
||||
/* Acts that charge a total the player saw in a window, planned again at the click: the arg that carries what the window
|
||||
showed. The game refuses a different one ("The quote changed"); the server also refuses a request without it.
|
||||
'quote' is the plan's key (a string), any other name the total (a number). pniAll: the exact total (fixed prices, so
|
||||
the total names the plan). bstdApply: the plan's key, plus its total q, which may drift 1% (hardware prices move
|
||||
daily under the market rule). utilityKit, utilityKitAll, acceptFix, ptApply, ptAll: the total, within 1% (each prices
|
||||
routers, so a day's drift moves it; ptApply's "Mark it" sends 0). utilityCaches: the list of boxes. */
|
||||
const QUOTE = {
|
||||
acceptFix: 'cost',
|
||||
bstdApply: 'quote',
|
||||
pniAll: 'q',
|
||||
ptAll: 'cost',
|
||||
ptApply: 'cost',
|
||||
utilityCaches: 'quote',
|
||||
utilityKit: 'cost',
|
||||
utilityKitAll: 'cost',
|
||||
};
|
||||
|
||||
/* The windows a request's ctx.win may name: the one the page has open when the click came from inside it. The game asks
|
||||
which window is open by its class and by a marker inside it (pieRe: class 'pie'; bstdShown: [data-sheet="bstd"];
|
||||
routingRefresh: [data-routing]; charter), so the realm's stand-in has to be that window, or a redraw on the server
|
||||
opens another one. c: its class (#modal's className); sel: the marker inside #modalCard, if it has one; ui: the view
|
||||
state it draws from that only the page holds (set by LOCAL acts: the intern window's POP, the pie window's tab and
|
||||
POP), each checked against the game in the realm. The page names the first entry, in this order, whose c is the open
|
||||
window's class and whose sel (when it has one) matches inside it; a window none names is sent as ctx.modal alone. */
|
||||
const WINDOWS = {
|
||||
bstd: { c: 'ops', sel: '[data-sheet="bstd"]' },
|
||||
routing: { c: '', sel: '[data-routing]' },
|
||||
charter: { c: 'charter' },
|
||||
ops: { c: 'ops', ui: ['opsCity'] },
|
||||
pie: { c: 'pie', ui: ['pieCity', 'pieTab'] },
|
||||
};
|
||||
|
||||
const ID_RE = /^[a-z0-9]{8,16}$/, SIM_RE = /^[0-9a-f]{12}$/, KEY_RE = /^[A-Za-z][A-Za-z0-9]{0,15}$/, VIEW_RE = /^[a-z0-9]{1,16}$/, SHORT_RE = /^[A-Za-z0-9_.:|~-]{1,40}$/;
|
||||
const SPEEDS = [0, 0.5, 1, 2, 4, 8];
|
||||
// The viewport a request's ctx may set on the realm, in CSS pixels: checkEnvelope clamps ctx.w and ctx.h into it.
|
||||
const VIEW_MIN = 200, VIEW_MAX = 4000;
|
||||
const PREFS = ['pauseFurious', 'pauseIncident', 'warnUnhappy'];
|
||||
const SETS = { SEND: new Set(SEND), ASK: new Set(ASK), CONFIRM: new Set(Object.keys(CONFIRM)) };
|
||||
const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
|
||||
const plain = (o) => !!o && typeof o === 'object' && !Array.isArray(o) && (Object.getPrototypeOf(o) === Object.prototype || Object.getPrototypeOf(o) === null);
|
||||
const prim = (v, cap) => v === null || typeof v === 'boolean' || (typeof v === 'number' && Number.isFinite(v)) || (typeof v === 'string' && v.length <= cap);
|
||||
// Keys a request object may never carry, whatever the regex says; nor values, where a value names something: written
|
||||
// through as a key (S.pops[city]), they reach a prototype, and any name Object.prototype has ('toString', 'valueOf')
|
||||
// reads as something there. Free text (TEXT) may say them.
|
||||
const BAD_KEY = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
const badVal = (v) => (typeof v === 'string' ? BAD_KEY.has(v) || v in Object.prototype : Array.isArray(v) ? v.some(badVal) : !!v && typeof v === 'object' && Object.keys(v).some((k) => BAD_KEY.has(k) || badVal(v[k])));
|
||||
|
||||
function bad(error, code = 400, extra = {}) { return { ok: false, code, error, ...extra }; }
|
||||
|
||||
function checkArgs(act, args) {
|
||||
if (!plain(args)) return 'args must be an object';
|
||||
const keys = Object.keys(args);
|
||||
if (keys.length > 12) return 'too many args';
|
||||
const caps = own(TEXT, act) ? TEXT[act] : {};
|
||||
for (const k of keys) {
|
||||
if (!KEY_RE.test(k) || BAD_KEY.has(k)) return `bad arg name ${JSON.stringify(k).slice(0, 40)}`;
|
||||
const v = args[k], cap = own(caps, k) ? caps[k] : 64;
|
||||
if (!own(caps, k) && badVal(v)) return `bad arg ${k}`;
|
||||
if (Array.isArray(v)) { if (v.length > 64 || !v.every((x) => prim(x, 64))) return `bad arg ${k}`; continue; }
|
||||
if (!prim(v, cap)) return `bad arg ${k}`;
|
||||
}
|
||||
if (own(QUOTE, act)) { const q = args[QUOTE[act]]; if (QUOTE[act] === 'quote' ? typeof q !== 'string' : !(typeof q === 'number' && Number.isFinite(q))) return `${act} needs the quoted ${QUOTE[act]}`; }
|
||||
return null;
|
||||
}
|
||||
function checkDraft(k, v) {
|
||||
const t = DRAFT_TYPES[k];
|
||||
if (badVal(v)) return false;
|
||||
if (Array.isArray(t)) return t.includes(v);
|
||||
if (t === 'boolean') return typeof v === 'boolean';
|
||||
if (t === 'string') return typeof v === 'string' && v.length <= 64;
|
||||
if (t === 'id') return typeof v === 'string' && SHORT_RE.test(v);
|
||||
// Two different places: the game's own drag never opens a link from a city to itself.
|
||||
if (t === 'pair') return plain(v) && Object.keys(v).length === 2 && typeof v.a === 'string' && typeof v.b === 'string' && SHORT_RE.test(v.a) && SHORT_RE.test(v.b) && v.a !== v.b;
|
||||
if (t === 'ids') return Array.isArray(v) && v.length <= 200 && v.every((x) => typeof x === 'string' && SHORT_RE.test(x));
|
||||
return false;
|
||||
}
|
||||
function checkCtx(c) {
|
||||
if (!plain(c)) return 'ctx must be an object';
|
||||
for (const k of Object.keys(c)) {
|
||||
const v = c[k];
|
||||
if (k === 'sel') { if (v !== null && !(plain(v) && Object.keys(v).length === 2 && (v.type === 'city' || v.type === 'link') && typeof v.id === 'string' && SHORT_RE.test(v.id))) return 'bad ctx.sel'; }
|
||||
else if (k === 'tab' || k === 'left') { if (v !== null && !(typeof v === 'string' && VIEW_RE.test(v))) return `bad ctx.${k}`; }
|
||||
else if (k === 'modal' || k === 'coarse') { if (typeof v !== 'boolean') return `bad ctx.${k}`; }
|
||||
// The page sends its innerWidth/innerHeight as they are: a 5120-px monitor, or a desktop zoomed out, is wider than
|
||||
// anything the layout tells apart (isPhone() and the like only ask whether it is under about 760). Clamped, not refused.
|
||||
else if (k === 'w' || k === 'h') { if (!(typeof v === 'number' && Number.isFinite(v) && v > 0 && v <= 1e5)) return `bad ctx.${k}`; c[k] = Math.min(VIEW_MAX, Math.max(VIEW_MIN, v)); }
|
||||
// The open window, by name, with its view state (WINDOWS): {k, ui?}.
|
||||
else if (k === 'win') {
|
||||
const W = plain(v) && typeof v.k === 'string' && own(WINDOWS, v.k) ? WINDOWS[v.k] : null;
|
||||
if (!W || !Object.keys(v).every((x) => x === 'k' || x === 'ui')) return 'bad ctx.win';
|
||||
if (v.ui !== undefined && !(plain(v.ui) && Object.keys(v.ui).every((u) => (W.ui || []).includes(u) && (v.ui[u] === null || (typeof v.ui[u] === 'string' && SHORT_RE.test(v.ui[u]) && !badVal(v.ui[u])))))) return 'bad ctx.win.ui';
|
||||
}
|
||||
else return `unknown ctx.${String(k).slice(0, 20)}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const bool = (v) => v === undefined || typeof v === 'boolean';
|
||||
|
||||
/* The envelope of one request body, before anything reaches a game. kind: 'act' | 'ask' | 'vote' | 'here' | 'prefs'.
|
||||
opts.sim: the server's build id; a request built by another one answers 409 {old:true}. Returns {ok:true} or
|
||||
{ok:false, code (400 or 409), error, old?}. Only shapes are checked here; what the ids name is the realm's to check.
|
||||
One repair, in place: ctx.w and ctx.h (any finite width up to 100000) are clamped into VIEW_MIN–VIEW_MAX, so the
|
||||
realm only ever sees a viewport in that range. */
|
||||
function checkEnvelope(kind, body, opts = {}) {
|
||||
if (!plain(body)) return bad('the body must be a JSON object');
|
||||
const keys = Object.keys(body);
|
||||
const only = (allowed) => { for (const k of keys) if (!allowed.includes(k)) return `unknown field ${JSON.stringify(k).slice(0, 40)}`; return null; };
|
||||
const simOk = () => {
|
||||
if (typeof body.sim !== 'string' || !SIM_RE.test(body.sim)) return bad('sim must be the page\'s build id');
|
||||
if (opts.sim && body.sim !== opts.sim) return bad('this page is from another build', 409, { old: true });
|
||||
return null;
|
||||
};
|
||||
if (kind === 'act' || kind === 'ask') {
|
||||
const e = only(kind === 'act' ? ['rid', 'dev', 'sim', 'act', 'args', 'ui', 'confirmed', 'ctx'] : ['rid', 'dev', 'sim', 'act', 'args', 'ctx']);
|
||||
if (e) return bad(e);
|
||||
if (typeof body.rid !== 'string' || !ID_RE.test(body.rid)) return bad('bad rid');
|
||||
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
|
||||
const s = simOk(); if (s) return s;
|
||||
if (typeof body.act !== 'string' || !(kind === 'act' ? SETS.SEND : SETS.ASK).has(body.act)) return bad(`${kind} ${JSON.stringify(String(body.act).slice(0, 40))} is not one the server runs`);
|
||||
const a = checkArgs(body.act, body.args === undefined ? {} : body.args); if (a) return bad(a);
|
||||
if (body.ui !== undefined) {
|
||||
if (kind !== 'act' || !plain(body.ui)) return bad('bad ui');
|
||||
const allowed = own(DRAFTS, body.act) ? DRAFTS[body.act] : [];
|
||||
for (const k of Object.keys(body.ui)) if (!allowed.includes(k) || !checkDraft(k, body.ui[k])) return bad(`bad ui.${String(k).slice(0, 20)}`);
|
||||
}
|
||||
if (body.confirmed !== undefined && (body.confirmed !== true || !SETS.CONFIRM.has(body.act))) return bad('confirmed only goes with a two-click act');
|
||||
if (body.ctx !== undefined) { const c = checkCtx(body.ctx); if (c) return bad(c); }
|
||||
return { ok: true };
|
||||
}
|
||||
if (kind === 'vote') {
|
||||
const e = only(['speed', 'sim']); if (e) return bad(e);
|
||||
const s = simOk(); if (s) return s;
|
||||
if (body.speed !== null && !SPEEDS.includes(body.speed)) return bad('bad speed');
|
||||
return { ok: true };
|
||||
}
|
||||
if (kind === 'here') {
|
||||
const e = only(['dev', 'hidden', 'hold', 'idle', 'away', 'view']); if (e) return bad(e);
|
||||
if (typeof body.dev !== 'string' || !ID_RE.test(body.dev)) return bad('bad dev');
|
||||
if (!['hidden', 'hold', 'idle', 'away'].every((k) => bool(body[k]))) return bad('bad flag');
|
||||
if (body.view !== undefined) {
|
||||
const v = body.view;
|
||||
if (v !== null && !(plain(v) && Object.keys(v).every((k) => (k === 'link' || k === 'peer') && (v[k] === null || (typeof v[k] === 'string' && SHORT_RE.test(v[k])))))) return bad('bad view');
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
if (kind === 'prefs') {
|
||||
const e = only(['prefs', 'lang']); if (e) return bad(e);
|
||||
if (body.prefs !== undefined && !(plain(body.prefs) && Object.keys(body.prefs).every((k) => PREFS.includes(k) && typeof body.prefs[k] === 'boolean'))) return bad('bad prefs');
|
||||
if (body.lang !== undefined && !(typeof body.lang === 'string' && /^[a-z]{2}(-[A-Za-z]{2,4})?$/.test(body.lang))) return bad('bad lang');
|
||||
return { ok: true };
|
||||
}
|
||||
return bad(`unknown kind ${String(kind).slice(0, 20)}`);
|
||||
}
|
||||
|
||||
// Body size caps per kind, in bytes (section 10), for the host's readJson.
|
||||
const BODY_MAX = { act: 16384, ask: 8192, here: 2048, prefs: 1024, vote: 256 };
|
||||
|
||||
module.exports = { SEND, ASK, VOTE, LOCAL, PUZZLE, CONFIRM, SRV_ARM, armKey, DRAFTS, DRAFT_TYPES, TEXT, QUOTE, WINDOWS, SPEEDS, PREFS, VIEW_MIN, VIEW_MAX, BODY_MAX, checkEnvelope };
|
||||
271
scripts/lib/mp-sim-engine.js
Normal file
271
scripts/lib/mp-sim-engine.js
Normal file
|
|
@ -0,0 +1,271 @@
|
|||
// The server-run engine (the server-sim design, sections 4.2-4.3): a small pool of worker threads (mp-sim-worker.js),
|
||||
// each holding the vm realms (mp-sim-realm.js) of the sessions placed on it, behind a promise API. The session host
|
||||
// (scripts/lib/mp-sim.js) keeps the clock, presence and votes, and asks this for days, actions, what-ifs and pulls.
|
||||
// tests/lib/mp-sim-fake-engine.js has the same API with canned answers.
|
||||
//
|
||||
// const engine = createEngine({workers: 2, heapMb: 1536, root, log, maxOwn: 4, onLost});
|
||||
// engine.load(code, [{nid, env?, begin?, lang, prefs, rng?}]) → [{t:'loaded', nid, epoch, day, lost, saved?} |
|
||||
// {t:'loaded', nid, err}], one per network, in order. env: the checkpoint envelope {s, uidN, rt, last,
|
||||
// day} (s: the save text; rt: what the realm needs besides it to play on exactly as before, opaque
|
||||
// here: route memory, R's routing point, key order, the sales desk's memory); begin: {name, home,
|
||||
// preset, asn, mp, tut, day?} builds a new network, checkpointed at once (saved); day is the
|
||||
// session's date, where it begins (absent or 0: the session's first day). A network that comes
|
||||
// without a save, whose save does not load, or that cannot begin answers err: broken (4.7), and
|
||||
// the others load. A load of a network that is loaded replaces its realm (a failed one leaves none).
|
||||
// engine.day(code, {d, speed, last, alone:[nid], nets:[nid], mute}) → {t:'dayDone', code, d, nets:{[nid]: {day, lost,
|
||||
// pause?, err?, retried?, ms}}}. Each network in sorted order; one that failed twice answers err and
|
||||
// its day as it was, and is broken from then on (no more days; actions answer 'stopped'). One
|
||||
// calendar for the session: the host (T3) checks that every network's day here is d, lost and
|
||||
// broken networks excepted; the engine does not.
|
||||
// engine.act(code, nid, msg) → {t:'actDone', nid, epoch, rid, outcome, why?, v, upd, ms} (upd: the update with the
|
||||
// result, version v; null when stopped) | {t:'err', code, nid, rid, what:'timeout'|'throw', msg}
|
||||
// engine.ask(code, nid, msg) → {t:'askDone', nid, rid, modal?, ui?, err?, ms} (neither modal nor err: the what-if
|
||||
// opened nothing) | {t:'err', …}
|
||||
// engine.pull(code, nid, {snap, views}) → {t:'pulled', nid, epoch, v, upd?, snap?, subs?, ms}. snap is the realm's
|
||||
// half of a snapshot: snapWith(snap, {clock, roster, since}) makes the stream event.
|
||||
// ms: the worker's time for the call (the mark, the realm, the update), without the wait behind other calls: what
|
||||
// the host's rate limit of worker time counts (section 10).
|
||||
// engine.sub(code, nid, {views}) → {t:'subbed', nid, epoch, v, subs}; engine.greet(code, nid) → a pulled
|
||||
// engine.prefs(code, nid, {prefs}) → undefined (or the {t:'err'} of a realm that failed);
|
||||
// engine.save(code, nid) → {t:'saved', nid, txt, uidN, rt, day, lost}; engine.card(code, nid) → {t:'card', nid, card}
|
||||
// engine.unload(code, nid?) → {t:'unloaded', code, nid?}; engine.has(code, nid) → whether that network has a realm
|
||||
// engine.stats() → {workers, realms, sessions} (not a promise); engine.mem() → each pool worker's heap and rss
|
||||
// engine.close() → stops the workers
|
||||
// engine.simId the build id this engine's game belongs to (SIM_ID of the multiplayer page from the same src/). The
|
||||
// game text is read once, here: every worker, also one started after an exit, runs that game, and
|
||||
// a src/ that does not compile makes createEngine throw.
|
||||
//
|
||||
// Rejections: a call for a network that is not loaded (code 'NO_REALM'), a malformed call (code 'ERR': a load that
|
||||
// names no network, or one twice, changes nothing), every call pending on a worker that exits (out of memory, a crash):
|
||||
// Error('worker exited'), code 'EXIT', and every call while no worker can start (code 'SIM_DOWN', 503 for the host).
|
||||
// Every call is answered or rejected; none waits for ever.
|
||||
// Lost networks. A worker that exits takes the realms of every session on it, also of those with no call pending, and
|
||||
// the worker drops a network whose realm cannot be built again after a failure. Such a network answers NO_REALM: for a
|
||||
// network the host believes loaded, NO_REALM means "load it again from its checkpoint" (4.7). opts.onLost(code, nids,
|
||||
// why) says it as it happens ('exit', or the worker's reason).
|
||||
// Blame. An exit counts against the session the worker was running (a call or a step that crashed or overflowed it),
|
||||
// else against those whose load was under way, else against every session it held; a worker that never started
|
||||
// blames nobody. A session with two exits against it within an hour gets a worker of its own (at most opts.maxOwn of
|
||||
// them, 4 by default: past that it is given up); when that one exits too, its loads reject with code 'GAVE_UP' until
|
||||
// the engine is made again (the server restarts). A worker that exits before it is ready is started again after a
|
||||
// pause that doubles; after 5 such starts in a row the engine is down (SIM_DOWN). A session stays on its worker while
|
||||
// a load of it is under way, so an unload and a load sent back to back (a language change) land on the same worker.
|
||||
// Epochs: every realm load mints one (a load, a begin, the fresh realm after a timeout); loaded, pulled, actDone and
|
||||
// subbed carry the realm's current one. Versions are the realm's: only a pull (or an action's own pull) makes one.
|
||||
//
|
||||
// Tests only, with createEngine({test: {seed, now, step} | true}): engine.eval(code, nid, src) runs code in a realm
|
||||
// ({value} | {error} | {timeout, epoch}); engine.kill(i) ends pool worker i, engine.killOf(code) the worker of that
|
||||
// session; engine.workerOf(code) is its pool index (-1: none, or its own), engine.dedicated(code) whether it has a
|
||||
// worker of its own, engine.running(i) the session pool worker i is running as far as the engine knows.
|
||||
// opts.test.startFail: no worker starts; opts.startBackoffMs: the first pause before starting one again (1000).
|
||||
'use strict';
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { Worker } = require('node:worker_threads');
|
||||
const page = require('./page');
|
||||
const { gameSource } = require('./mp-sim-realm');
|
||||
|
||||
const FILE = path.join(__dirname, 'mp-sim-worker.js');
|
||||
const HOUR = 3600e3;
|
||||
|
||||
/* The stream event of a snapshot: the realm's half (S, r, keep, epoch, v, now) with the host's (clock, roster,
|
||||
since), joined as text: the realm's 270 KB are never parsed again. */
|
||||
function snapWith(snap, { clock, roster, since }) {
|
||||
if (typeof snap !== 'string' || !snap.endsWith('}')) throw new Error('snapWith: not a snapshot');
|
||||
return snap.slice(0, -1) + ',"clock":' + JSON.stringify(clock) + ',"roster":' + JSON.stringify(roster) + ',"since":' + JSON.stringify(since) + '}';
|
||||
}
|
||||
|
||||
function createEngine(opts = {}) {
|
||||
if (!vm.constants || vm.constants.DONT_CONTEXTIFY === undefined) {
|
||||
throw new Error(`server-run play needs Node 22.8 or newer (vm.constants.DONT_CONTEXTIFY); this is ${process.version}`);
|
||||
}
|
||||
const N = Math.max(1, Math.floor(+opts.workers || 2));
|
||||
const heapMb = Math.max(64, Math.floor(+opts.heapMb || 1536));
|
||||
const maxOwn = Math.max(0, Math.floor(opts.maxOwn !== undefined ? +opts.maxOwn || 0 : 4));
|
||||
const backoff = Math.max(1, +opts.startBackoffMs || 1000);
|
||||
const log = typeof opts.log === 'function' ? opts.log : () => {};
|
||||
const lostTo = (code, nids, why) => { if (typeof opts.onLost === 'function' && nids.length) try { opts.onLost(code, nids, why); } catch (e) { log('error', 'mp-sim: onLost threw: ' + (e && e.message)); } };
|
||||
const test = opts.test || null;
|
||||
// The game, read once, here: a src/ that does not compile throws now, and every worker runs the game simId names.
|
||||
const root = opts.root || page.ROOT, src = gameSource({ root, page: opts.page });
|
||||
try { new vm.Script(src, { filename: 'game.js' }); } catch (e) { throw new Error(`mp-sim: the game in ${path.join(root, 'src')} does not compile: ${e.message}`); }
|
||||
const simId = page.simId(page.assemble({ src: path.join(root, 'src'), mp: true }).html);
|
||||
const W = { root: opts.root, page: opts.page, src, simId, test, strict: opts.strict !== undefined ? !!opts.strict : process.env.SIM_STRICT === '1', timeouts: opts.timeouts };
|
||||
let seq = 0, closed = false, down = null, fails = 0;
|
||||
const DOWN = () => Object.assign(new Error(`server-run play is down: ${down}`), { code: 'SIM_DOWN' });
|
||||
const CLOSED = () => Object.assign(new Error('engine closed'), { code: 'CLOSED' });
|
||||
// Why no call can go out now: closed, or down (else null).
|
||||
const shut = () => (closed ? CLOSED() : down ? DOWN() : null);
|
||||
const pool = [], own = new Map(), placed = new Map(), exits = new Map(), gaveUp = new Set();
|
||||
// A worker's realms (sessions: code → its loaded nids), and for placement the networks of its loads under way too
|
||||
// (loading: code → how many).
|
||||
const size = (w) => [...w.sessions.values()].reduce((a, b) => a + b.size, 0);
|
||||
const count = (w) => size(w) + [...w.loading.values()].reduce((a, b) => a + b, 0);
|
||||
|
||||
function spawn(dedicated = false) {
|
||||
const w = { worker: null, pending: new Map(), sessions: new Map(), loading: new Map(), dedicated, dead: false, ready: false, fatal: null, running: null };
|
||||
w.worker = new Worker(FILE, { workerData: { mpSim: W }, resourceLimits: { maxOldGenerationSizeMb: heapMb } });
|
||||
w.worker.on('message', (m) => {
|
||||
if (m.log) { log(m.log[0], m.log[1]); return; }
|
||||
if (m.fatal) { w.fatal = String(m.fatal).split('\n')[0].slice(0, 300); return; }
|
||||
if (m.ready) { w.ready = true; fails = 0; return; }
|
||||
// The session it runs from now until its next reply: whose doing an exit then is.
|
||||
if ('run' in m) { w.running = m.run; return; }
|
||||
if (m.lost) { const s = w.sessions.get(m.lost.code); if (s) s.delete(m.lost.nid); lostTo(m.lost.code, [m.lost.nid], m.lost.why); return; }
|
||||
w.running = null;
|
||||
const p = w.pending.get(m.id);
|
||||
if (!p) return;
|
||||
w.pending.delete(m.id);
|
||||
// An idle worker does not keep the process alive; one with calls pending does.
|
||||
if (!w.pending.size) w.worker.unref();
|
||||
if (m.ok) p.ok(m.reply);
|
||||
else p.no(Object.assign(new Error(m.error.message), { code: m.error.code }));
|
||||
});
|
||||
w.worker.on('error', (e) => log('error', 'mp-sim worker failed: ' + (e && e.message)));
|
||||
w.worker.on('exit', (c) => died(w, c));
|
||||
w.worker.unref();
|
||||
return w;
|
||||
}
|
||||
function died(w, c) {
|
||||
if (w.dead) return;
|
||||
w.dead = true;
|
||||
// Whose exit it is: the session it was running (a call or a step that crashed or overflowed it), else those whose
|
||||
// load was under way, else every session it held; nobody's when it never started. The others lose their realms
|
||||
// (the host loads them again) without an exit against them.
|
||||
const held = new Set([...w.sessions.keys(), ...w.loading.keys()]);
|
||||
const blamed = new Set(!w.ready ? [] : w.running && held.has(w.running) ? [w.running] : w.loading.size ? w.loading.keys() : held);
|
||||
const e = Object.assign(new Error('worker exited'), { code: 'EXIT', exitCode: c });
|
||||
for (const p of w.pending.values()) p.no(e);
|
||||
w.pending.clear();
|
||||
const t = Date.now();
|
||||
for (const code of held) {
|
||||
if (placed.get(code) === w) placed.delete(code);
|
||||
lostTo(code, [...(w.sessions.get(code) || [])], 'exit');
|
||||
if (!blamed.has(code)) continue;
|
||||
if (w.dedicated) { gaveUp.add(code); own.delete(code); log('error', `mp-sim: session ${code} took down its own worker too; not loading it again until a restart`); continue; }
|
||||
exits.set(code, (exits.get(code) || []).filter((x) => t - x < HOUR).concat(t));
|
||||
}
|
||||
w.sessions.clear(); w.loading.clear();
|
||||
for (const [k, x] of own) if (x === w) own.delete(k);
|
||||
if (closed) return;
|
||||
const i = pool.indexOf(w);
|
||||
if (!w.ready) {
|
||||
// It never started (the game does not run in a worker): not again at once, but after a pause that doubles; after
|
||||
// 5 such starts in a row, server-run play is down until the engine is made again.
|
||||
if (++fails >= 5) { if (!down) { down = w.fatal || `a worker exited before it started (code ${c})`; log('error', `mp-sim: no worker can start (${down}); server-run play is down until a restart`); } return; }
|
||||
log('warn', `mp-sim: a worker could not start (${w.fatal || 'code ' + c}); trying again in ${backoff * 2 ** (fails - 1)} ms`);
|
||||
if (i >= 0) setTimeout(() => { if (!closed && !down && pool[i] === w) pool[i] = spawn(); }, backoff * 2 ** (fails - 1)).unref();
|
||||
return;
|
||||
}
|
||||
log('warn', `mp-sim: a worker exited (code ${c}); its sessions load again from their checkpoints`);
|
||||
if (i >= 0) pool[i] = spawn();
|
||||
}
|
||||
for (let i = 0; i < N; i++) pool.push(spawn());
|
||||
|
||||
// The worker of a session: where it is, else the pool's least loaded one (or one of its own, after two exits).
|
||||
function workerOf(code, create) {
|
||||
let w = placed.get(code);
|
||||
if (w && !w.dead) return w;
|
||||
if (!create) return null;
|
||||
if (down) throw DOWN();
|
||||
if (gaveUp.has(code)) throw Object.assign(new Error(`session ${code} kept failing its worker`), { code: 'GAVE_UP' });
|
||||
if ((exits.get(code) || []).filter((x) => Date.now() - x < HOUR).length >= 2) {
|
||||
if (own.size >= maxOwn) {
|
||||
gaveUp.add(code);
|
||||
log('error', `mp-sim: session ${code} keeps failing its worker, and ${own.size} sessions have workers of their own already; not loading it again until a restart`);
|
||||
throw Object.assign(new Error(`session ${code} kept failing its worker`), { code: 'GAVE_UP' });
|
||||
}
|
||||
w = spawn(true); own.set(code, w);
|
||||
} else {
|
||||
const live = pool.filter((x) => !x.dead);
|
||||
if (!live.length) throw Object.assign(new Error('no worker is up yet: try again'), { code: 'SIM_DOWN' });
|
||||
w = live.reduce((a, b) => (count(b) < count(a) ? b : a));
|
||||
}
|
||||
placed.set(code, w);
|
||||
return w;
|
||||
}
|
||||
function send(w, m) {
|
||||
if (closed) return Promise.reject(CLOSED());
|
||||
if (!w || w.dead) return Promise.reject(Object.assign(new Error('worker exited'), { code: 'EXIT' }));
|
||||
const id = ++seq;
|
||||
return new Promise((ok, no) => {
|
||||
if (!w.pending.size) w.worker.ref();
|
||||
w.pending.set(id, { ok, no });
|
||||
// A message that cannot be sent (not cloneable) is a malformed call, and nothing waits for its answer.
|
||||
try { w.worker.postMessage({ id, ...m }); } catch (e) { w.pending.delete(id); if (!w.pending.size) w.worker.unref(); no(Object.assign(new Error(String((e && e.message) || e)), { code: 'ERR' })); }
|
||||
});
|
||||
}
|
||||
const noRealm = (code, nid) => Promise.reject(Object.assign(new Error(`no realm ${code}/${nid}`), { code: 'NO_REALM' }));
|
||||
const to = (code, nid, m) => { const x = shut(); if (x) return Promise.reject(x); const w = workerOf(code, false); return w ? send(w, { code, nid, ...m }) : noRealm(code, nid); };
|
||||
const mine = (w, code) => { let s = w.sessions.get(code); if (!s) w.sessions.set(code, s = new Set()); return s; };
|
||||
|
||||
const engine = {
|
||||
simId,
|
||||
load(code, nets) {
|
||||
{ const x = shut(); if (x) return Promise.reject(x); }
|
||||
if (!Array.isArray(nets) || !nets.length) return Promise.reject(Object.assign(new Error('load: give the networks to load'), { code: 'ERR' }));
|
||||
let w;
|
||||
try { w = workerOf(code, true); } catch (e) { return Promise.reject(e); }
|
||||
// Under way: the session is on this worker from now (an exit meanwhile counts against it, and its placement holds).
|
||||
const n = nets.length, done = () => { const k = (w.loading.get(code) || 0) - n; if (k > 0) w.loading.set(code, k); else w.loading.delete(code); };
|
||||
w.loading.set(code, (w.loading.get(code) || 0) + n);
|
||||
return send(w, { t: 'load', code, nets }).then((r) => {
|
||||
done();
|
||||
const s = mine(w, code);
|
||||
for (const l of r) if (!l.err) s.add(l.nid); else s.delete(l.nid);
|
||||
return r;
|
||||
}, (e) => { done(); throw e; });
|
||||
},
|
||||
day(code, { d, speed = 1, last = 1, alone = [], nets = [], mute = false } = {}) {
|
||||
{ const x = shut(); if (x) return Promise.reject(x); }
|
||||
const w = workerOf(code, false);
|
||||
if (!w) return Promise.reject(Object.assign(new Error(`no session ${code} here`), { code: 'NO_REALM' }));
|
||||
return send(w, { t: 'day', code, d, speed, last, alone, nets, mute });
|
||||
},
|
||||
act(code, nid, msg) { return to(code, nid, { t: 'act', msg }); },
|
||||
ask(code, nid, msg) { return to(code, nid, { t: 'ask', msg }); },
|
||||
pull(code, nid, { snap = false, views } = {}) { return to(code, nid, { t: 'pull', snap: !!snap, ...(views ? { views } : {}) }); },
|
||||
sub(code, nid, { views = [] } = {}) { return to(code, nid, { t: 'sub', views }); },
|
||||
prefs(code, nid, { prefs } = {}) { return to(code, nid, { t: 'prefs', prefs }).then((r) => (r && r.t === 'err' ? r : undefined)); },
|
||||
greet(code, nid) { return to(code, nid, { t: 'greet' }); },
|
||||
save(code, nid) { return to(code, nid, { t: 'save' }); },
|
||||
card(code, nid) { return to(code, nid, { t: 'card' }); },
|
||||
unload(code, nid) {
|
||||
if (closed) return Promise.reject(CLOSED());
|
||||
const w = workerOf(code, false);
|
||||
if (!w) return Promise.resolve({ t: 'unloaded', code, ...(nid !== undefined ? { nid } : {}) });
|
||||
return send(w, { t: 'unload', code, ...(nid !== undefined ? { nid } : {}) }).then((r) => {
|
||||
const s = w.sessions.get(code);
|
||||
if (s) { if (nid === undefined) s.clear(); else s.delete(nid); }
|
||||
// Gone from here, unless a load of it sent after this unload is under way.
|
||||
if ((!s || !s.size) && !w.loading.has(code)) { w.sessions.delete(code); if (placed.get(code) === w) placed.delete(code); }
|
||||
// A worker of its own with nothing on it and nothing pending is done (with a call pending it would never answer).
|
||||
if (w.dedicated && !w.dead && !w.sessions.size && !w.loading.size && !w.pending.size) { if (own.get(code) === w) own.delete(code); w.dead = true; w.worker.terminate(); }
|
||||
return r;
|
||||
});
|
||||
},
|
||||
has(code, nid) { const w = placed.get(code), s = w && !w.dead && w.sessions.get(code); return !!(s && s.has(nid)); },
|
||||
mem() { return Promise.all(pool.filter((w) => !w.dead).map((w) => send(w, { t: 'mem' }))); },
|
||||
stats() {
|
||||
const ws = [...pool, ...own.values()].filter((w) => !w.dead);
|
||||
return { workers: ws.length, realms: ws.reduce((a, w) => a + size(w), 0), sessions: ws.reduce((a, w) => a + w.sessions.size, 0) };
|
||||
},
|
||||
close() {
|
||||
closed = true;
|
||||
const ws = [...pool, ...own.values()];
|
||||
return Promise.all(ws.map((w) => (w.dead ? null : w.worker.terminate()))).then(() => undefined);
|
||||
},
|
||||
snapWith,
|
||||
};
|
||||
if (test) {
|
||||
engine.eval = (code, nid, src, ms) => to(code, nid, { t: 'eval', src: String(src), ...(ms ? { ms } : {}) });
|
||||
engine.kill = (i = 0) => { const w = pool[i]; if (w && !w.dead) w.worker.terminate(); };
|
||||
engine.killOf = (code) => { const w = placed.get(code); if (w && !w.dead) w.worker.terminate(); };
|
||||
engine.workerOf = (code) => pool.indexOf(placed.get(code));
|
||||
engine.dedicated = (code) => !!(placed.get(code) && placed.get(code).dedicated);
|
||||
engine.running = (i = 0) => (pool[i] ? pool[i].running : null);
|
||||
}
|
||||
return engine;
|
||||
}
|
||||
|
||||
module.exports = { createEngine, snapWith };
|
||||
565
scripts/lib/mp-sim-realm.js
Normal file
565
scripts/lib/mp-sim-realm.js
Normal file
|
|
@ -0,0 +1,565 @@
|
|||
// One network of a server session, run by the game's own code in a vm realm (the server-sim design, section 4.1).
|
||||
// The realm is a vm context made with DONT_CONTEXTIFY, so it has its own intrinsics (a prototype polluted in one realm
|
||||
// stays there) and runs at full speed. Into it go, in order: the prelude below (DOM stand-ins that record what the
|
||||
// game writes and reads back, no-op timers that count, the network's language), the network's dictionary
|
||||
// (site/i18n/<lang>.js, not English), the game script, and the epilogue (the srv… functions: what the server asks of a
|
||||
// network, and the rebinds that turn toasts, sounds, windows and the like into effects, "fx", for the page).
|
||||
//
|
||||
// The worker (mp-sim-worker.js) calls into a realm only through call()/raw(): the input goes in as one JSON string
|
||||
// (globalThis.__in), the answer comes back as one string, and no object crosses between host and realm. An answer is
|
||||
// a JSON header, optionally followed by more parts, each on its own line (JSON text never holds a raw newline):
|
||||
// srvPull answers `{"v":3,"parts":["upd","snap"]}\n<upd JSON>\n<snap JSON>`, ready to write to a stream.
|
||||
// A call that throws inside the realm answers {"srvErr": stack}; a call after which the realm's built-ins are not what
|
||||
// they were at load (a prototype written through) answers {"srvErr", "polluted":1}, and the realm must not be used for
|
||||
// play again; a call that runs over its time limit throws ERR_SCRIPT_EXECUTION_TIMEOUT here, and the realm must not be
|
||||
// used for play again either (a timeout skips finally blocks).
|
||||
//
|
||||
// gameSource({root, page}) the game script (the largest inline <script> of the assembled page)
|
||||
// dictSource(lang, root) the source dictionary of a language, or null for English
|
||||
// prelude(opts), EPILOGUE the realm's own code around the game, as plain strings
|
||||
// compileCode({root, page, src, simId}) {game, epilogue, simId} as vm.Scripts, once per process (a worker); src and
|
||||
// simId: the game text and build id the engine read once (every worker runs the same)
|
||||
// new Realm({code, lang, dict, test, log, nid}) a realm, the game loaded; .call(name, input, ms), .raw(...)
|
||||
// parts(text) [header, ...parts] of an answer
|
||||
'use strict';
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const vm = require('node:vm');
|
||||
const { assemble, simId, ROOT } = require('./page');
|
||||
const ACTS = require('./mp-sim-acts');
|
||||
|
||||
/* The page whose game a realm runs: the plain one (design 4.1), never a multiplayer build's page. That one also holds
|
||||
the server-play client (src/game/98-server-play/), whose rebinds of after, toast and save are for a page that shows
|
||||
a server's network; inside the server's own realm they would have to be switched off one by one. The build id
|
||||
(SIM_ID) still names the multiplayer page, which holds this game and its client both. */
|
||||
const REALM_PAGE = Object.freeze({ dev: false, mp: false });
|
||||
|
||||
function gameSource({ root = ROOT, page = REALM_PAGE } = {}) {
|
||||
const html = assemble({ src: path.join(root, 'src'), dev: !!page.dev, mp: !!page.mp }).html;
|
||||
let best = '';
|
||||
html.replace(/<script>([\s\S]*?)<\/script>/g, (m, s) => { if (s.length > best.length) best = s; return m; });
|
||||
if (!best.includes('function dayTick')) throw new Error('mp-sim-realm: no game script in the assembled page');
|
||||
return best;
|
||||
}
|
||||
|
||||
const LANG_RE = /^[a-z]{2}$/;
|
||||
function dictSource(lang, root = ROOT) {
|
||||
if (!lang || lang === 'en') return null;
|
||||
if (!LANG_RE.test(lang)) throw new Error(`mp-sim-realm: bad language ${JSON.stringify(String(lang).slice(0, 20))}`);
|
||||
const f = path.join(root, 'site', 'i18n', lang + '.js');
|
||||
if (!fs.existsSync(f)) throw new Error(`mp-sim-realm: no dictionary for ${lang}`);
|
||||
return fs.readFileSync(f, 'utf8');
|
||||
}
|
||||
|
||||
/* The realm's stand-ins (start: probe/srv-engine/common.js prelude({mode:'record'}), which kept S byte-identical to
|
||||
jsdom over 30 big-network days). opts.seed: a test's seeded Math.random under the game's own seeded wrapper (the
|
||||
harness's generator, so a realm and a test page draw the same numbers); opts.now: a test's pinned Date.now, moved on
|
||||
by opts.step at every day. Without them the realm has its own Math.random and the real clock. */
|
||||
function prelude({ lang = 'en', seed = null, now = null, step = 2500, test = false } = {}) {
|
||||
const L = JSON.stringify(LANG_RE.test(lang) ? lang : 'en');
|
||||
return `'use strict';
|
||||
globalThis.self=globalThis;self.window=self;self.__TUBES_WORKER__=1;self.__TUBES_TEST__=true;
|
||||
{const hn=__hostNow;self.performance={now:()=>hn(),mark(){},measure(){},timeOrigin:0};}
|
||||
{const hl=__hostLog,f=l=>(...a)=>{try{hl(l,a.map(x=>x&&x.stack?x.stack:String(x)).join(' '));}catch(e){}};self.console={log:f('log'),info:f('info'),warn:f('warn'),error:f('error'),debug:f('debug'),trace:f('debug')};}
|
||||
// No timers in a realm: nothing may run outside the worker's handling of a message. Calls are counted (the timer audit).
|
||||
self.__SRV_T={n:0,at:${test ? '[]' : 'null'}};
|
||||
{const t=k=>function(){__SRV_T.n++;if(__SRV_T.at&&__SRV_T.at.length<50)__SRV_T.at.push(k+': '+String(new Error().stack).split('\\n').slice(2,7).join(' < '));return 0;};
|
||||
for(const k of ['setTimeout','setInterval','requestAnimationFrame','queueMicrotask','setImmediate','requestIdleCallback'])self[k]=t(k);
|
||||
for(const k of ['clearTimeout','clearInterval','cancelAnimationFrame','clearImmediate','cancelIdleCallback'])self[k]=()=>{};}
|
||||
${seed == null ? '' : `{let r=${(+seed | 0) || 12345};Math.random=()=>{r=(r*16807)%2147483647;return r/2147483647;};}`}
|
||||
${now == null ? '' : `{let t=${+now};Date.now=()=>t;self.__srvClock=v=>{if(typeof v==='number')t=v;return t;};self.__srvStep=${+step || 0};}`}
|
||||
const _n=new Proxy(function(){},{get:(t,k)=>k===Symbol.toPrimitive?()=>0:k==='then'?undefined:_n,apply:()=>_n,construct:()=>_n,set:()=>true});
|
||||
const _store=()=>{const m=new Map();return {getItem:k=>m.has(String(k))?m.get(String(k)):null,setItem(k,v){m.set(String(k),String(v));},removeItem(k){m.delete(String(k));},clear(){m.clear();},key:i=>[...m.keys()][i]??null,get length(){return m.size;}};};
|
||||
const _ent={amp:'&',lt:'<',gt:'>',quot:'"',apos:"'",nbsp:'\\u00a0',middot:'\\u00b7',times:'\\u00d7',rarr:'\\u2192',larr:'\\u2190',hellip:'\\u2026',mdash:'\\u2014',ndash:'\\u2013',bull:'\\u2022',deg:'\\u00b0',euro:'\\u20ac',thinsp:'\\u2009'};
|
||||
const _txt=h=>String(h).replace(/<[^>]*>/g,'').replace(/&(#x[0-9a-f]+|#\\d+|[a-z]+);/gi,(m,e)=>e[0]==='#'?String.fromCodePoint(e[1]==='x'||e[1]==='X'?parseInt(e.slice(2),16):+e.slice(1)):(e in _ent?_ent[e]:m));
|
||||
// Elements keep innerHTML, hidden and value, and answer textContent and firstElementChild from what was written; they
|
||||
// have no children (morphKids would loop for ever on the inert proxy's endless nextSibling).
|
||||
const _el=(tag,init)=>{const t={tagName:String(tag||'div').toUpperCase(),_h:'',hidden:true,value:'',firstChild:null,lastChild:null,nextSibling:null,previousSibling:null,parentNode:null,children:[],childNodes:[],attributes:[],...init};
|
||||
return new Proxy(t,{get(o,k){if(k==='innerHTML')return o._h;if(k==='textContent')return _txt(o._h);
|
||||
if(k==='firstElementChild'){const m=/^\\s*<([a-zA-Z][a-zA-Z0-9]*)\\b[^>]*>([\\s\\S]*?)<\\/\\1>/.exec(o._h);return m?_el(m[1],{_h:m[2]}):null;}
|
||||
if(k==='querySelector'||k==='querySelectorAll')return s=>_q(o._h,s,k==='querySelectorAll');if(k==='classList')return _cls(o);
|
||||
if(k in o)return o[k];return _n;},
|
||||
set(o,k,v){if(k==='innerHTML')o._h=String(v);else if(k==='textContent')o._h=String(v).replace(/[&<>]/g,c=>({'&':'&','<':'<','>':'>'})[c]);else o[k]=v;return true;}});};
|
||||
// Which window is open, as the game asks it (pieRe, bstdShown, routingRefresh, the sea survey: a class, or a [data-x] /
|
||||
// [data-x="v"] marker inside the card), is answered from what was written, never with the inert proxy, which would say
|
||||
// every window is open. Other selectors match nothing; matches carry their data-* attributes. (closest() stays inert:
|
||||
// a stand-in has no ancestors, and the page's own start asks one for its chip.)
|
||||
const _cls=o=>{const g=()=>String(o.className||'').split(/\\s+/).filter(Boolean),p=a=>{o.className=a.join(' ');};
|
||||
return new Proxy({contains:c=>g().includes(String(c)),add:(...c)=>p([...new Set([...g(),...c.map(String)])]),remove:(...c)=>{const x=c.map(String);p(g().filter(y=>!x.includes(y)));},
|
||||
toggle:(c,f)=>{c=String(c);const on=f===undefined?!g().includes(c):!!f;p(on?[...new Set([...g(),c])]:g().filter(y=>y!==c));return on;}},{get:(t,k)=>k in t?t[k]:_n});};
|
||||
const _cc=x=>x.replace(/-([a-z])/g,(q,c)=>c.toUpperCase());
|
||||
const _ds=a=>{const d=Object.create(null);a.replace(/\\sdata-([a-z0-9-]+)(?:\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'>]+)))?/gi,(m,k,x,y,z)=>{d[_cc(k.toLowerCase())]=_txt(x??y??z??'');return m;});return d;};
|
||||
const _q=(h,sel,all)=>{const m=/^\\[data-([a-z0-9-]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\\]"']*)))?\\]$/i.exec(String(sel).trim()),out=[];
|
||||
if(m){const k=_cc(m[1].toLowerCase()),v=m[2]??m[3]??m[4],re=/<([a-zA-Z][a-zA-Z0-9]*)(\\s[^>]*)?>/g;let t;
|
||||
while((t=re.exec(h))){const d=_ds(t[2]||'');if(Object.hasOwn(d,k)&&(v===undefined||d[k]===v)){out.push(_el(t[1],{dataset:d}));if(!all)break;}}}
|
||||
return all?out:out[0]||null;};
|
||||
const _byId=new Map();
|
||||
const _doc=new Proxy({},{get(o,k){if(k==='createElement')return tag=>_el(tag);if(k==='getElementById')return id=>{if(!_byId.has(id))_byId.set(id,_el('div',{id}));return _byId.get(id);};return _n;},set:()=>true});
|
||||
self.__srvEl=_byId;self.__srvCoarse=false;
|
||||
for(const [k,v] of Object.entries({document:_doc,localStorage:_store(),sessionStorage:_store(),innerWidth:1024,innerHeight:768,devicePixelRatio:1,
|
||||
matchMedia:q=>({matches:/pointer:\\s*coarse/.test(String(q))?!!self.__srvCoarse:false,addEventListener(){},removeEventListener(){},addListener(){},removeListener(){}}),
|
||||
Image:_n,Audio:_n,AudioContext:undefined,webkitAudioContext:undefined,screen:_n,visualViewport:_n,history:_n,getComputedStyle:_n,ResizeObserver:_n,MutationObserver:_n,IntersectionObserver:_n,Path2D:_n,scrollTo(){},
|
||||
SOT_LANG:${L},SOT_LANGS:{en:'English',it:'Italiano',pt:'Português',fr:'Français',es:'Español',de:'Deutsch'},I18N:{},
|
||||
location:{href:'https://server.invalid/',protocol:'https:',hostname:'server.invalid',host:'server.invalid',origin:'https://server.invalid',search:'',hash:'',pathname:'/',reload(){},replace(){},assign(){}},
|
||||
addEventListener(){},removeEventListener(){},dispatchEvent(){return true;},
|
||||
// Nothing reaches out of a realm: no channels, sockets or requests (fetch never settles), no workers.
|
||||
BroadcastChannel:undefined,WebSocket:undefined,EventSource:undefined,Worker:undefined,fetch:()=>new Promise(()=>{}),
|
||||
navigator:{language:${L},languages:[${L}],userAgent:'tubes-server',onLine:true,maxTouchPoints:0,hardwareConcurrency:1,vibrate:()=>false}}))
|
||||
Object.defineProperty(self,k,{value:v,writable:true,configurable:true,enumerable:true});
|
||||
`;
|
||||
}
|
||||
|
||||
/* The epilogue: the server's side of a network, in the game's global scope. It only uses the game's own functions and
|
||||
the tables of mp-sim-acts.js, written in as data. Everything a page needs to know comes out as fx or in the answers. */
|
||||
const TABLES = JSON.stringify({ SEND: ACTS.SEND, ASK: ACTS.ASK, CONFIRM: ACTS.CONFIRM, DRAFTS: ACTS.DRAFTS, DRAFT_TYPES: ACTS.DRAFT_TYPES, PREFS: ACTS.PREFS, TEXT: ACTS.TEXT, WINDOWS: ACTS.WINDOWS });
|
||||
const EPILOGUE = `'use strict';
|
||||
const SIMT=${TABLES},SIM_SEND=new Set(SIMT.SEND),SIM_ASK=new Set(SIMT.ASK),SIM_KEEP=new Set(['badge','modal']);
|
||||
const SIM_RNEVER=new Set(['ef','fl','efp','flc','efg','egDesc','l2route','bbF','peered','cityBlocked']);
|
||||
const SIM_DRAFT=Object.keys(SIMT.DRAFT_TYPES);
|
||||
// The realm's own memory: epoch and version of what it sent (5.10), the last keys sent, the fx and actions since the
|
||||
// last pull, the marks, and what the running call saw (a window opened or closed, a refusal toast, an auto-pause).
|
||||
const SIMR={epoch:'',v:0,seen:false,base:null,rSent:null,fx:[],acts:[],floats:0,alone:false,last:1,pause:false,modal:null,closed:false,bad:false,
|
||||
mark:null,markK:null,markRt:null,strict:false};
|
||||
const srvOwn=(o,k)=>Object.prototype.hasOwnProperty.call(o,k);
|
||||
const srvOut=(h,...p)=>[JSON.stringify(h),...p].join('\\n');
|
||||
function srvLog(t){console.warn(String(t).slice(0,600));}
|
||||
/* The realm's built-ins as the game left them at load. A click that writes through a prototype (a city named
|
||||
__proto__ or constructor) changes them, and every for…in, the game's and this file's, would carry that from then on.
|
||||
The trampoline checks after every call; a realm whose built-ins changed is replaced like one that timed out. */
|
||||
const srvFp=(()=>{const n=Object.getOwnPropertyNames,L=[Object,Object.prototype,Array,Array.prototype,Function.prototype,String.prototype,Number.prototype,Boolean.prototype,Map.prototype,Set.prototype];
|
||||
return ()=>{for(const k in {})return 'Object.prototype.'+k;for(const k in [])return 'Array.prototype.'+k;return L.map(o=>n(o).length).join(',');};})();
|
||||
const SIM_FP0=srvFp();
|
||||
function srvDirty(){const f=srvFp();return f===SIM_FP0?'':/^(Object|Array)\\./.test(f)?f:'a built-in has a new property';}
|
||||
// Strings no arg names: written through as a key, they reach a prototype. Free text (TEXT) may say them.
|
||||
const SIM_BADV=new Set(['__proto__','constructor','prototype']);
|
||||
const srvBadV=v=>typeof v==='string'?SIM_BADV.has(v):Array.isArray(v)?v.some(srvBadV):!!v&&typeof v==='object'&&Object.keys(v).some(k=>SIM_BADV.has(k)||srvBadV(v[k]));
|
||||
const srvBadArgs=(act,a)=>{const t=srvOwn(SIMT.TEXT,act)?SIMT.TEXT[act]:{};return Object.keys(a).some(k=>SIM_BADV.has(k)||(!srvOwn(t,k)&&srvBadV(a[k])));};
|
||||
|
||||
/* fx: a ring of 200; when it overflows, the oldest go first, but badges and windows (win, lose) stay, at most 32. */
|
||||
function srvFx(f){const q=SIMR.fx;q.push(f);
|
||||
if(q.length>200){const i=q.findIndex(x=>!SIM_KEEP.has(x[0]));q.splice(i>=0?i:0,1);}
|
||||
if(SIM_KEEP.has(f[0])){let n=0;for(const x of q)if(SIM_KEEP.has(x[0]))n++;if(n>32)q.splice(q.findIndex(x=>SIM_KEEP.has(x[0])),1);}}
|
||||
// At most 60 in one update: floaters go first, then sounds and the like, then the oldest toasts; windows, badges,
|
||||
// pauses and the chaos monkey's last word stay.
|
||||
function srvCap(fx){if(fx.length<=60)return fx;let out=fx;
|
||||
for(const k of ['floater','sfx','haptic','track','mk','told','toast']){let over=out.length-60;if(over<=0)break;
|
||||
out=out.filter(f=>{if(over>0&&f[0]===k&&!(k==='mk'&&f[1]&&f[1].e==='end')){over--;return false;}return true;});}
|
||||
return out.length>60?out.slice(-60):out;}
|
||||
|
||||
/* ---- capture: what the page shows, as fx (design 4.1's table) ---- */
|
||||
toast=function(h,k='',a=[],o=null){if(S)logNote(h,k,a,o);if(k==='bad')SIMR.bad=true;srvFx(['toast',{h:String(h),k:String(k),a:Array.isArray(a)?a:[],o:o||null,tick:!!UI.tick}]);};
|
||||
sfx=function(n){srvFx(['sfx',String(n)]);};
|
||||
haptic=function(n){srvFx(['haptic',+n||12]);};
|
||||
floater=function(x,y,t,c){if(SIMR.floats>=40)return;SIMR.floats++;srvFx(['floater',[+x||0,+y||0,String(t),String(c)]]);};
|
||||
track=function(n,once){srvFx(['track',[String(n),!!once]]);};
|
||||
// Alone, an auto-pause pauses the world (the host stops the clock after the day) and its toast's Resume votes for the
|
||||
// speed it ran at; with others it does not pause, and the page offers a vote instead.
|
||||
// Alone it stops this realm's clock too, as the page's does: a second auto-pause that day finds it paused (srvDay sets
|
||||
// the speed again before the next day).
|
||||
autoPause=function(){if(!S||!UI.speed)return false;SIMR.pause=true;srvFx(['pause',1]);if(!SIMR.alone)return false;UI.resumeSpeed=UI.lastSpeed=SIMR.last;UI.speed=0;return true;};
|
||||
openModal=function(h,c=''){SIMR.modal={h:String(h),c:String(c||'')};const m=$('modal');m.className=String(c||'');m.hidden=false;$('modalCard').innerHTML=String(h);};
|
||||
{const c0=closeModal;closeModal=function(){c0();SIMR.closed=true;};}
|
||||
showWin=function(){srvFx(['modal','win']);};
|
||||
showLose=function(){srvFx(['modal','lose']);};
|
||||
showBaronWin=function(){srvFx(['modal','baron']);};
|
||||
{const s0=mkStart,r0=mkRun,e0=mkEnd;
|
||||
mkStart=function(c){s0(c);srvFx(['mk',{e:'start',c:String(c)}]);};
|
||||
mkRun=function(l,dur,bad){r0(l,dur,bad);srvFx(['mk',{e:'run',link:l&&l.id!==undefined?String(l.id):null,felt:!!bad}]);};
|
||||
mkEnd=function(ok,bye){e0(ok,bye);srvFx(['mk',{e:'end',ok:!!ok,bye:!!bye}]);};}
|
||||
{const b0=checkBadges;checkBadges=function(){const a0=S&&S.ach?{...S.ach}:{},p0=S&&S.achP?{...S.achP}:{};b0();
|
||||
if(S&&S.achP)for(const id of Object.keys(S.achP))if(a0[id]===undefined||p0[id]!==S.achP[id])srvFx(['badge',{id,v:String(S.achP[id])}]);};}
|
||||
// Never shown here, and linkPanel would drop a selection it cannot find; the page keeps its own.
|
||||
renderPanel=function(){};renderLeft=function(){};
|
||||
// Checkpoints are the engine's (UI.slot is null anyway).
|
||||
save=function(){};
|
||||
// This realm is the server: a server network is never shown here.
|
||||
srvOn=function(){return false;};
|
||||
UI.clockLocked=true;UI.started=true;UI.pitched=true;UI.speed=1;
|
||||
|
||||
/* ---- S as top-level keys, R as the page gets it ---- */
|
||||
function srvKeyJson(){const o=Object.create(null);for(const k of Object.keys(S)){const j=JSON.stringify(S[k]);if(j!==undefined)o[k]=j;}return o;}
|
||||
function srvJoin(K){let t='{',f=true;for(const k in K){t+=(f?'':',')+JSON.stringify(k)+':'+K[k];f=false;}return t+'}';}
|
||||
// Slim R (5.5): rwPack's view without the flow tables, routing's own inputs and what goes on demand; the top 4 networks
|
||||
// per transit port, the top 8 over all of them, numbers to 6 significant digits. Packed once per R object.
|
||||
const srvR6=(k,v)=>typeof v==='number'&&!Number.isInteger(v)&&Number.isFinite(v)?+v.toPrecision(6):v;
|
||||
function srvSlimR(){const c=SIM_RTXT.get(R);if(c)return c;const o={};
|
||||
for(const k in R){if(SIM_RNEVER.has(k))continue;o[k]=k==='ddos'?R.ddos.map(m=>({...m,attack:m.attack?m.attack.id:null,ports:null})):R[k];}
|
||||
const tn={};for(const id in o.tNet)tn[id]=Object.fromEntries(Object.entries(o.tNet[id]).sort((a,b)=>b[1]-a[1]).slice(0,4));o.tNet=tn;
|
||||
o.tTop8=transitTop(S.transit.map(t=>t.id),8);
|
||||
const t=JSON.stringify(o,srvR6);SIM_RTXT.set(R,t);return t;}
|
||||
const SIM_RTXT=new WeakMap();
|
||||
|
||||
/* ---- rt (4.1, 4.6): what a fresh realm needs besides the save to go on exactly as this one ---- */
|
||||
// The route memory: what compute() reads of the R before it (R.load, R.l2route, R.efg cut to the scenic circuits' keys).
|
||||
function srvRtOut(r){const efg={},E=r&&r.efg;
|
||||
if(E)for(const id in E){const t=E[id]&&E[id].t;if(!t||!t.g)continue;const g=[],v=[];for(const [k,s] of t.g)if(String(k).startsWith('l2:')){g.push([k,v.length]);v.push(+t.v[s]);}if(g.length)efg[id]={g,v};}
|
||||
return {load:(r&&r.load)||{},l2route:(r&&r.l2route)||{},efg};}
|
||||
function srvRtIn(rt){const r=emptyR();if(!rt||typeof rt!=='object')return r;
|
||||
if(rt.load&&typeof rt.load==='object')r.load=rt.load;if(rt.l2route&&typeof rt.l2route==='object')r.l2route=rt.l2route;
|
||||
if(rt.efg&&typeof rt.efg==='object'){const o={};for(const id of Object.keys(rt.efg)){const t=rt.efg[id];if(t&&Array.isArray(t.g)&&Array.isArray(t.v))o[id]={g:new Map(t.g),v:t.v};}
|
||||
Object.defineProperty(r,'efg',{value:rwEfgIn(o)});}
|
||||
return r;}
|
||||
/* The routing point. R after a day is the R of the day's last routing, which ran before the day's end changed S (bills,
|
||||
moods, customers who left or signed) and started from the memory of the R before it. compute() of the saved S, even
|
||||
from R's own memory, gives another R, and the next day reads it (eyeball growth, the peering share): a network
|
||||
restored that way drifts from its first day on. So every compute() keeps, for the R it makes, S as it routed it (one
|
||||
JSON per top-level key, 0.8 ms big) and the memory it started from. rt carries that point (pt: the memory, at: the
|
||||
keys that changed since, gone: the keys S did not have then), and a fresh realm routes that S again from that memory:
|
||||
the same R (srvReroute). Trials route and put R back: their points go with their R. */
|
||||
const SIM_RIN=new WeakMap();
|
||||
{const c0=compute;compute=function(){const k=S?srvKeyJson():null,rt=JSON.stringify(srvRtOut(R)),v=c0.apply(this,arguments);if(k)SIM_RIN.set(R,{k,rt});return v;};}
|
||||
// The sales desk's memory (39-sales-auto.js): the offers it tried, which wait a week before it tries them again. It is
|
||||
// not in S; rt carries the entries of offers still on the table (no other can count again).
|
||||
function srvSlOut(){const t=UI.slTried;if(!t||t.s!==S||!t.m)return [];const ids=new Set(S.offers.map(o=>o.id));return [...t.m].filter(e=>ids.has(e[0]));}
|
||||
function srvSlIn(sl){const m=new Map();if(Array.isArray(sl))for(const e of sl.slice(0,1000))if(Array.isArray(e)&&typeof e[0]==='string'&&Number.isInteger(e[1]))m.set(e[0],e[1]);UI.slTried=m.size?{s:S,m}:null;}
|
||||
/* Key order: a reload gives some keys back with their keys in another order (a customer's defaults go last, the intern's
|
||||
week tally comes back in its own order, and the week's report lists it in that order). At a checkpoint rt carries the
|
||||
live text of each such key (ord, srvGate's round trip: ≈ 8 ms big, once per checkpoint), and a fresh realm takes it
|
||||
only where it holds what sanitize() made of the save (srvSame): only the order comes from it. */
|
||||
function srvOrdOut(txt,K){const u0=uidN,r0=S.rng;let B;
|
||||
try{B=migrate(JSON.parse(txt));}catch(e){srvLog('checkpoint: the save does not load: '+String(e&&e.message||e));return '{}';}finally{uidN=u0;S.rng=r0;}
|
||||
const o=[];for(const k in K)if(srvOwn(B,k)&&JSON.stringify(B[k])!==K[k])o.push(JSON.stringify(k)+':'+K[k]);return '{'+o.join(',')+'}';}
|
||||
function srvOrdIn(o){if(!o||typeof o!=='object'||Array.isArray(o))return;for(const k of Object.keys(o))if(srvOwn(S,k)&&srvSame(o[k],S[k]))S[k]=o[k];}
|
||||
// rt as JSON text: R's own route memory, its routing point against S as K holds it (when R was routed here), ord when
|
||||
// given, and the desk's memory sl.
|
||||
function srvRtText(r,K,ord,sl,rk){const p=K&&SIM_RIN.get(r);let t=JSON.stringify(srvRtOut(r)).slice(0,-1);
|
||||
if(p){const at=[],gone=[];for(const k in p.k)if(K[k]!==p.k[k])at.push(JSON.stringify(k)+':'+p.k[k]);for(const k in K)if(!srvOwn(p.k,k))gone.push(k);
|
||||
t+=',"pt":'+p.rt.slice(0,-1)+',"at":{'+at.join(',')+'},"gone":'+JSON.stringify(gone)+'}';}
|
||||
return t+(ord?',"ord":'+ord:'')+(rk?',"rk":true':'')+',"sl":'+JSON.stringify(sl||[])+'}';}
|
||||
// rk: R is the routing of S as it is (routeIfChanged's memory, UI.rk and UI.rkR, against K: routeKey() is the join of
|
||||
// K without RK_SKIP). A fresh realm given it skips the routing of a click that changes nothing routing reads, as this
|
||||
// one would; without it that click routes again, and compute() is not always a fixed point.
|
||||
const srvRkOk=(r,K,rk,rkR)=>{if(!K||rkR!==r||typeof rk!=='string')return false;let t='{',f=true;for(const k in K){if(RK_SKIP.has(k))continue;t+=(f?'':',')+JSON.stringify(k)+':'+K[k];f=false;}return t+'}'===rk;};
|
||||
const srvKeysOf=s=>{const o=JSON.parse(s),K=Object.create(null);for(const k of Object.keys(o)){const j=JSON.stringify(o[k]);if(j!==undefined)K[k]=j;}return K;};
|
||||
// The S of a routing point (pt), one JSON per key: the loaded S with the keys of at put back and those of gone left out.
|
||||
function srvAtK(pt){if(!pt||typeof pt!=='object'||!pt.at||typeof pt.at!=='object'||Array.isArray(pt.at)||!Array.isArray(pt.gone))return null;
|
||||
const K=srvKeyJson();for(const k of Object.keys(pt.at))K[k]=JSON.stringify(pt.at[k]);for(const k of pt.gone)if(typeof k==='string')delete K[k];return K;}
|
||||
// R as the routing point gives it: that S routed from that memory, then the loaded S again (R's attacks found in it).
|
||||
function srvReroute(pt){const K=srvAtK(pt);if(!K)return false;const S1=S,u0=uidN;
|
||||
try{S=JSON.parse(srvJoin(K));R=srvRtIn(pt);compute();}
|
||||
catch(e){srvLog('routing the checkpoint again failed: '+String(e&&e.stack||e));return false;}
|
||||
finally{S=S1;uidN=u0;}
|
||||
srvAttacks();return true;}
|
||||
// R with its point, when it came whole (rpack): a checkpoint before its next routing still carries the point.
|
||||
function srvPointIn(r,pt){const K=srvAtK(pt);if(K)SIM_RIN.set(r,{k:K,rt:JSON.stringify({load:pt.load||{},l2route:pt.l2route||{},efg:pt.efg||{}})});}
|
||||
// R's attacks are its only references into S (rwPack): looked up again in a new S.
|
||||
function srvAttacks(){if(!R||!Array.isArray(R.ddos))return;const as=ddosAll(S,false);for(const x of R.ddos)if(x.attack)x.attack=as.find(a=>a.id===x.attack.id)||null;}
|
||||
// mark: rt of the marked R against the marked S (a day's mark has it at once); else of R against S now.
|
||||
function srvRt(inp){const m=inp?JSON.parse(inp):{},k=SIMR.mark;
|
||||
if(!m.mark){const K=srvKeyJson();return srvRtText(R,K,'',srvSlOut(),srvRkOk(R,K,UI.rk,UI.rkR));}
|
||||
if(SIMR.markRt)return SIMR.markRt;
|
||||
if(!k)return srvRtText(R,null,'',[]);
|
||||
const K=SIMR.markK||srvKeysOf(k.s);return srvRtText(k.R,K,'',k.sl,srvRkOk(k.R,K,k.ui.rk,k.ui.rkR));}
|
||||
/* R itself, whole, for the fresh realm that replaces this one after a timeout (routing it again from its point costs a
|
||||
routing; the old realm still answers), the way the route worker sends it (rwPack/rwUnpack), as text: Maps, Sets, typed
|
||||
arrays and non-finite numbers tagged. A checkpoint carries the point instead: 20 KB gzip, where R is 375 KB. */
|
||||
const SIM_TA=new Set(['Float64Array','Float32Array','Int32Array','Uint32Array','Int16Array','Uint16Array','Int8Array','Uint8Array','Uint8ClampedArray']);
|
||||
const srvEnc=(k,v)=>typeof v==='number'&&!Number.isFinite(v)?{__n:String(v)}:v instanceof Map?{__m:[...v]}:v instanceof Set?{__s:[...v]}:ArrayBuffer.isView(v)&&SIM_TA.has(v.constructor.name)?{__t:v.constructor.name,a:Array.from(v)}:v;
|
||||
const srvDec=(k,v)=>!v||typeof v!=='object'||Array.isArray(v)?v:'__n' in v?Number(v.__n):'__m' in v?new Map(v.__m):'__s' in v?new Set(v.__s):'__t' in v&&SIM_TA.has(v.__t)?new self[v.__t](v.a):v;
|
||||
function srvRPack(inp){const m=inp?JSON.parse(inp):{},r=m.mark&&SIMR.mark?SIMR.mark.R:R;if(!r||!r.efp||!r.flc)return '';const {o,p}=rwPack(r);return JSON.stringify({o,p},srvEnc);}
|
||||
|
||||
function srvSetPrefs(p){if(!p||typeof p!=='object')return;for(const k of SIMT.PREFS)if(typeof p[k]==='boolean')PREFS[k]=p[k];}
|
||||
/* The window the page has open (ctx.modal; ctx.win names it, mp-sim-acts.js WINDOWS): the stand-in #modal is that
|
||||
window as the game asks it (its class, its marker), with the view state it draws from (checked here). No win: no
|
||||
window, or one nothing asks about. The view state of an earlier request never stays. */
|
||||
const SIM_WINUI=[...new Set(Object.values(SIMT.WINDOWS).flatMap(w=>w.ui||[]))];
|
||||
const SIM_WINOK={opsCity:v=>srvOwn(S.pops,v),pieCity:v=>srvOwn(S.pops,v),pieTab:v=>PIE_TABS.includes(v)};
|
||||
function srvWin(c){const w=c&&c.win&&typeof c.win==='object'?c.win:null,W=w&&typeof w.k==='string'&&srvOwn(SIMT.WINDOWS,w.k)?SIMT.WINDOWS[w.k]:null,m=$('modal');
|
||||
for(const k of SIM_WINUI)delete UI[k];
|
||||
m.hidden=!((c&&c.modal===true)||W);m.className=W?W.c:'';$('modalCard').innerHTML=W&&W.sel?'<div '+W.sel.slice(1,-1)+'></div>':'';
|
||||
if(W&&W.ui&&w.ui&&typeof w.ui==='object')for(const k of W.ui){const v=w.ui[k];if(typeof v==='string'&&srvOwn(SIM_WINOK,k)&&SIM_WINOK[k](v))UI[k]=v;}}
|
||||
function srvWinOff(){const m=$('modal');m.hidden=true;m.className='';$('modalCard').innerHTML='';}
|
||||
function srvFresh(epoch){SIMR.epoch=String(epoch||'');SIMR.v=0;SIMR.seen=false;SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.rSent=new WeakRef(R);SIMR.base=srvKeyJson();SIMR.mark=null;SIMR.markK=null;SIMR.markRt=null;
|
||||
UI.sel=null;UI.confirm=null;UI.pending=null;UI.started=true;UI.pitched=true;UI.clockLocked=true;srvWinOff();}
|
||||
|
||||
/* srvLoad: a network from its save (a checkpoint, or the mark of a realm that timed out) and its rt: S in its live key
|
||||
order, R routed again from its routing point, the desk's memory; then the days to come are the ones the old realm
|
||||
had. A realm that replaces one that timed out gets the old realm's R itself when it could still pack it (rpack); live:
|
||||
the save is the old realm's own S as text (a mark), key order and all. An rt without a point (an older checkpoint)
|
||||
seeds R with its memory before compute(), the way the route worker does: close, not always the same. A damaged rt
|
||||
never breaks a save that loads: R is routed from nothing then (close, logged). fx: the fx a fresh realm takes over
|
||||
from the one it replaces (srvFxOut). Only a server network loads: a Normal game with the session's marks (S.mp.sim;
|
||||
a local save is stamped on its way in, 5.2), else the load fails with the reason. */
|
||||
function srvLoad(inp){const m=JSON.parse(inp),rt=m.rt&&typeof m.rt==='object'?m.rt:{};SIMR.strict=!!m.strict;
|
||||
S=migrate(JSON.parse(m.save));
|
||||
{const no=S.mode!=='normal'||S.scn?'server networks are Normal games':!S.mp||S.mp.sim!==1?'not a server network (S.mp.sim)':'';if(no)throw new Error('srvLoad: '+no);}
|
||||
if(typeof S.rng!=='number')S.rng=(m.rng|0)||1;
|
||||
if(Number.isInteger(m.uidN)&&m.uidN>0)uidN=m.uidN;
|
||||
srvSetPrefs(m.prefs);
|
||||
// A test's pinned clock goes on where the realm this one replaces had it.
|
||||
if(self.__srvClock&&typeof m.clock==='number')__srvClock(m.clock);
|
||||
srvOrdIn(m.live?JSON.parse(m.save):rt.ord);
|
||||
if(typeof m.rpack==='string'&&m.rpack){const x=JSON.parse(m.rpack,srvDec);R=rwUnpack(x.o,x.p);UI.hotMap=hotByCity();srvPointIn(R,rt.pt);}
|
||||
else if(!srvReroute(rt.pt)){try{R=srvRtIn(rt);compute();}catch(e){srvLog('the route memory does not load ('+String(e&&e.message||e).slice(0,200)+'): routed from nothing');R=emptyR();compute();}}
|
||||
if(rt.rk===true){UI.rk=routeKey();UI.rkR=R;}
|
||||
srvSlIn(rt.sl);
|
||||
srvFresh(m.epoch);
|
||||
if(m.fx&&typeof m.fx==='object'&&Array.isArray(m.fx.fx)){SIMR.fx=m.fx.fx.filter(f=>Array.isArray(f)&&typeof f[0]==='string').slice(-200);SIMR.floats=Math.min(40,Math.max(0,m.fx.floats|0));}
|
||||
// Whatever a loaded network says before its first snapshot (days nobody watched) is older than that snapshot: the
|
||||
// first pull handles it like any (5.11). Only a new network's welcome waits for its first page (srvBegin).
|
||||
SIMR.seen=true;
|
||||
return JSON.stringify({day:S.day,lost:!!S.lost});}
|
||||
const srvClockNow=()=>self.__srvClock?{clock:__srvClock()}:{};
|
||||
// srvBegin: a new network of a server session (T1's beginState, then the server's own marks and the welcome). b.day: the
|
||||
// session's date, where the network begins (one calendar for the session; 0 or none: its first day).
|
||||
function srvBegin(inp){const m=JSON.parse(inp),b=m.begin||{};SIMR.strict=!!m.strict;
|
||||
if(typeof b.home!=='string'||!homeOk(b.home))throw new Error('srvBegin: '+String(b.home).slice(0,20)+' cannot be a home city');
|
||||
if(!b.mp||typeof b.mp!=='object')throw new Error('srvBegin: no session');
|
||||
const D=b.day===undefined?0:b.day;
|
||||
if(!Number.isInteger(D)||D<0||D>1e7)throw new Error('srvBegin: '+String(b.day).slice(0,20)+' is no start day');
|
||||
srvSetPrefs(m.prefs);UI.pitched=true;
|
||||
beginState(String(b.name||'').slice(0,24)||randomNetworkName(),b.home,{mode:'normal',preset:b.preset,mp:b.mp,asn:Number(b.asn),day:D});
|
||||
if(!S.mp)throw new Error('srvBegin: the session did not take');
|
||||
S.mp.sim=1;S.tut=b.tut?0:null;compute();srvFresh(m.epoch);
|
||||
// The welcome: in S.log, and an fx that waits for the first update after the first snapshot (srvPullParts).
|
||||
beginHello();
|
||||
return JSON.stringify({day:S.day,lost:!!S.lost});}
|
||||
function srvPrefs(inp){const m=JSON.parse(inp);srvSetPrefs(m.prefs);return '{}';}
|
||||
|
||||
/* srvMark: the restore point of the next day (day) or action (keys: one JSON per top-level key, whose join is the same
|
||||
string, kept for the action's own comparison). The worker keeps the string, uidN and a day's rt too, to build a fresh
|
||||
realm if this one times out. */
|
||||
function srvMark(inp){const m=inp?JSON.parse(inp):{};let s,K=null;
|
||||
if(m.keys||m.day){K=srvKeyJson();s=srvJoin(K);}else s=JSON.stringify(S);
|
||||
SIMR.markK=m.keys?K:null;const sl=srvSlOut();
|
||||
SIMR.mark={s,uidN,rng:S.rng,R,sl,...srvClockNow(),fx:SIMR.fx.slice(),floats:SIMR.floats,ui:{sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm,pending:UI.pending,rk:UI.rk,rkR:UI.rkR}};
|
||||
// As text: nothing the day does reaches it.
|
||||
const rtJ=m.day?srvRtText(R,K,'',sl,srvRkOk(R,K,UI.rk,UI.rkR)):'';SIMR.markRt=rtJ||null;const h=JSON.stringify({uidN,day:S.day,...srvClockNow()});
|
||||
return (rtJ?h.slice(0,-1)+',"rt":'+rtJ+'}':h)+'\\n'+s;}
|
||||
/* srvRestore: back to the mark, in place (after a throw: the finally blocks ran). S is parsed back only when it
|
||||
changed, so the S object stays on every normal path; R is the marked object, its attacks looked up again in a parsed
|
||||
S; the sales desk's memory is the marked one (a failed day may have added to it). (The design rebuilt R from route
|
||||
memory after a failed day; that R is close, not the same: tests/mp-sim-determinism.) */
|
||||
function srvRestore(inp){const k=SIMR.mark;if(!k)return '{"none":1}';
|
||||
let parsed=false;if(JSON.stringify(S)!==k.s){S=JSON.parse(k.s);parsed=true;}
|
||||
uidN=k.uidN;S.rng=k.rng;if(self.__srvClock&&typeof k.clock==='number')__srvClock(k.clock);
|
||||
// R: the marked object. A day or an action routes into a new R (compute() never writes to the one it starts from),
|
||||
// so the marked one is still the R the network had: route memory and compute() would only give one close to it.
|
||||
R=k.R;if(parsed)srvAttacks();
|
||||
UI.hotMap=hotByCity();UI.slTried=k.sl.length?{s:S,m:new Map(k.sl)}:null;
|
||||
Object.assign(UI,k.ui);SIMR.fx=k.fx.slice();SIMR.floats=k.floats;SIMR.modal=null;SIMR.closed=false;srvWinOff();
|
||||
return JSON.stringify({parsed});}
|
||||
// The fx a fresh realm takes over from this one: the mark's after a failed call (its own fx are dropped, 4.3), else
|
||||
// (a read that ran out of time) all of them. Badges and windows wait for a page for days; a timeout does not lose them.
|
||||
function srvFxOut(inp){const m=inp?JSON.parse(inp):{},k=SIMR.mark;return JSON.stringify(m.mark&&k?{fx:k.fx,floats:k.floats}:{fx:SIMR.fx,floats:SIMR.floats});}
|
||||
|
||||
/* srvDay: one day of this network, as the page runs it (dayTick, then the day's end render), then the tutorial. mute:
|
||||
a catch-up day, whose fx are dropped (badges and windows stay). */
|
||||
function srvDay(inp){const m=inp?JSON.parse(inp):{};
|
||||
if(!S||S.lost)return JSON.stringify({day:S?S.day:0,lost:true});
|
||||
SIMR.alone=!!m.alone;SIMR.last=[0.5,1,2,4,8].includes(m.last)?m.last:1;SIMR.pause=false;
|
||||
UI.speed=[0.5,1,2,4,8].includes(m.speed)?m.speed:1;UI.clockLocked=true;UI.started=true;
|
||||
if(self.__srvClock&&self.__srvStep)__srvClock(__srvClock()+__srvStep);
|
||||
const n0=SIMR.fx.length;
|
||||
dayTick();UI.ticking=true;try{renderHUD();}finally{UI.ticking=false;}
|
||||
tutAdvance();
|
||||
if(m.mute)SIMR.fx=SIMR.fx.slice(0,n0).concat(SIMR.fx.slice(n0).filter(f=>SIM_KEEP.has(f[0])));
|
||||
// Tests (SIM_STRICT): live S after a day is what a reload makes of it, every key (T1's canonical state).
|
||||
if(SIMR.strict){const bad=srvGate(null).bad;if(bad.length)throw new Error('sanitize would repair day '+S.day+': '+bad.join(', '));}
|
||||
// Done: the marked R (and its flow tables) need not stay alive until the next mark.
|
||||
SIMR.mark=null;
|
||||
return JSON.stringify({day:S.day,lost:!!S.lost,...(SIMR.pause?{pause:true}:{})});}
|
||||
|
||||
/* The sanitize gate (5.8 step 6): the keys an action changed must come through the save path as they are. Never adopts
|
||||
the repaired copy (a new S without compute() would leave R's attacks pointing into the old one). keys null: all. */
|
||||
const srvSortK=v=>Array.isArray(v)?v.map(srvSortK):v&&typeof v==='object'?Object.keys(v).sort().reduce((o,k)=>(v[k]!==undefined&&(o[k]=srvSortK(v[k])),o),Object.create(null)):v;
|
||||
const srvSame=(a,b)=>{const x=JSON.stringify(a),y=JSON.stringify(b);return x===y||JSON.stringify(srvSortK(a))===JSON.stringify(srvSortK(b));};
|
||||
function srvGate(keys){const u0=uidN,r0=S.rng;
|
||||
try{const txt=JSON.stringify(packSave(S)),a=JSON.parse(txt),b=JSON.parse(JSON.stringify(packSave(migrate(JSON.parse(txt)))));
|
||||
const ks=keys||[...new Set([...Object.keys(a),...Object.keys(b)])];return {bad:ks.filter(k=>!srvSame(a[k],b[k])),len:txt.length};}
|
||||
finally{uidN=u0;S.rng=r0;}}
|
||||
|
||||
/* ---- actions (5.8) ---- */
|
||||
const srvSel=v=>v&&typeof v==='object'&&typeof v.id==='string'&&(v.type==='city'?isCity(v.id):v.type==='link'?S.links.some(l=>l.id===v.id):false)?{type:v.type,id:v.id}:null;
|
||||
function srvView(c){c=c&&typeof c==='object'?c:{};
|
||||
innerWidth=Number.isFinite(c.w)?c.w:1024;innerHeight=Number.isFinite(c.h)?c.h:768;self.__srvCoarse=!!c.coarse;}
|
||||
function srvArm(act,args){const t=SIMT.CONFIRM[act];return t.replace(/\\{(\\w+)\\}/g,(m,k)=>String(args&&args[k]!==undefined?args[k]:''));}
|
||||
// The drafts an act reads, from the request, each checked against the game's catalogs; anything else is wiped first, so
|
||||
// nothing of an earlier request leaks into this one. A bad one: the reason; the act does not run.
|
||||
function srvDrafts(act,ui,args){for(const k of SIM_DRAFT){if(k==='pending')UI.pending=null;else delete UI[k];}
|
||||
const allowed=SIMT.DRAFTS[act]||[];
|
||||
for(const k of Object.keys(ui||{})){if(!allowed.includes(k))return 'draft '+k+' is not '+act+'\\'s';const v=ui[k];
|
||||
if(k==='pending'){if(!v||typeof v!=='object'||!isCity(v.a)||!isCity(v.b)||v.a===v.b)return 'pending names no two places';UI.pending={a:v.a,b:v.b};}
|
||||
else if(k==='route'){if(typeof v!=='string'||!/^(|same|diverse|t:[A-Za-z0-9_.:|~-]{1,40})$/.test(v))return 'bad route';UI.route=v;}
|
||||
else if(k==='via'){if(!(v===''||v==='land'||(typeof v==='string'&&CABLES.some(c=>c.id===v))))return 'bad via';UI.via=v;}
|
||||
else if(k==='dfSrc'){if(!['lease','build','cable'].includes(v))return 'bad dfSrc';UI.dfSrc=v;}
|
||||
else if(k==='dfSys'){if(typeof v!=='string'||!srvOwn(DF_SYS,v))return 'bad dfSys';UI.dfSys=v;}
|
||||
else if(k==='seaDesign'){if(typeof v!=='string'||!srvOwn(SEA_DESIGNS,v))return 'bad seaDesign';UI.seaDesign=v;}
|
||||
else if(k==='decom'){if(!Array.isArray(v))return 'bad decom';UI.decom=new Set(v.filter(isCity).slice(0,200));}
|
||||
else if(k==='slop'){if(typeof v!=='boolean')return 'bad slop';if(v&&typeof args.script==='string')UI.slop=args.script.slice(0,4000);}
|
||||
else{if(typeof v!=='boolean')return 'bad '+k;UI[k]=v;}}
|
||||
return null;}
|
||||
function srvAct(inp){const m=JSON.parse(inp),act=String(m.act),ent={rid:String(m.rid),dev:String(m.dev),ui:{}};
|
||||
if(!S||S.lost)return srvOut({outcome:'stopped',v:SIMR.v});
|
||||
const args=m.args&&typeof m.args==='object'&&!Array.isArray(m.args)?m.args:{};
|
||||
let outcome,why;const K0=SIMR.markK;
|
||||
const done=(o,w)=>{outcome=o;why=w;};
|
||||
if(!SIM_SEND.has(act)||!srvOwn(ACT,act)||typeof ACT[act]!=='function')done('rejected','not an act the server runs');
|
||||
else if(srvBadArgs(act,args)||srvBadV(m.ui))done('rejected','an arg names a built-in');
|
||||
else{const w=srvDrafts(act,m.ui,args);
|
||||
if(w)done('rejected',w);
|
||||
else{const c=m.ctx&&typeof m.ctx==='object'?m.ctx:{};
|
||||
UI.sel=srvSel(c.sel);if(typeof c.tab==='string')UI.tab=c.tab;if(typeof c.left==='string')UI.left=c.left;srvView(c);srvWin(c);
|
||||
let a2=args;UI.confirm=null;
|
||||
if(m.confirmed===true&&srvOwn(SIMT.CONFIRM,act)){if(SIMT.CONFIRM[act]==='arg')a2={...args,ok:1};else UI.confirm=srvArm(act,args);}
|
||||
const sent={sel:UI.sel,tab:UI.tab,left:UI.left,confirm:UI.confirm};
|
||||
SIMR.modal=null;SIMR.closed=false;SIMR.bad=false;
|
||||
let err=null;try{ACT[act](a2);tutAdvance();}catch(e){err=e;}
|
||||
if(err){srvRestore('{}');srvLog('act '+act+' threw: '+String(err&&err.stack||err));done('error','the game threw: '+String(err&&err.message||err).slice(0,200));}
|
||||
else{const K=srvKeyJson(),ch=[];for(const k in K)if(!K0||K0[k]!==K[k])ch.push(k);if(K0)for(const k in K0)if(!(k in K))ch.push(k);
|
||||
if(!ch.length)done(SIMR.bad?'rejected':'no_effect');
|
||||
else if(SIMR.bad&&ch.every(k=>k==='log'))done('rejected');
|
||||
else{const g=srvGate(ch);let len=0,len0=0;for(const k in K)len+=K[k].length;if(K0)for(const k in K0)len0+=K0[k].length;
|
||||
if(g.bad.length){srvRestore('{}');srvLog('sanitize would repair '+act+': '+g.bad.join(', '));done('error','sanitize would repair '+act+': '+g.bad.join(', '));}
|
||||
else if(g.len>4194304||len-len0>262144){srvRestore('{}');srvLog('size guard: '+act);done('error','the network would grow too big');}
|
||||
else done('applied');}
|
||||
if(outcome!=='error'){for(const k of ['sel','tab','left','confirm'])if(JSON.stringify(UI[k]??null)!==JSON.stringify(sent[k]??null))ent.ui[k]=UI[k]??null;
|
||||
if(SIMR.closed)ent.ui.closed=1;if(SIMR.modal)ent.ui.modal=SIMR.modal;}}}}
|
||||
srvWinOff();SIMR.mark=null;SIMR.markK=null;SIMR.acts.push(ent);
|
||||
const p=srvPullParts({});
|
||||
return srvOut({outcome,...(why?{why}:{}),v:SIMR.v},p.upd);}
|
||||
|
||||
/* ---- asks (5.9): what-ifs that open a window and put everything back ---- */
|
||||
function srvAsk(inp){const m=JSON.parse(inp),k=SIMR.mark,act=String(m.act),out={};
|
||||
if(!SIM_ASK.has(act)||!srvOwn(ACT,act))return JSON.stringify({err:'not a what-if the server answers'});
|
||||
const args=m.args&&typeof m.args==='object'&&!Array.isArray(m.args)?m.args:{},td=UI.teDraft,sl=UI.slop,fx0=SIMR.fx.slice(),fl=SIMR.floats,hot=UI.hotMap;
|
||||
if(srvBadArgs(act,args))return JSON.stringify({err:'an arg names a built-in'});
|
||||
srvView(m.ctx);srvWin(m.ctx);SIMR.modal=null;
|
||||
try{ACT[act](args);}catch(e){out.err='the game threw: '+String(e&&e.message||e).slice(0,200);srvLog('ask '+act+' threw: '+String(e&&e.stack||e));}
|
||||
if(SIMR.modal)out.modal=SIMR.modal;
|
||||
if(act==='teCheck'||act==='teSlop'){out.ui={teDraft:typeof UI.teDraft==='string'?UI.teDraft:null};if(act==='teSlop')out.ui.slop=typeof UI.slop==='string'?UI.slop:null;}
|
||||
R=k.R;UI.hotMap=hot;uidN=k.uidN;S.rng=k.rng;
|
||||
if(JSON.stringify(S)!==k.s){srvLog('ask '+act+' changed the game: put back');srvRestore('{}');}
|
||||
else Object.assign(UI,k.ui);
|
||||
SIMR.mark=null;UI.teDraft=td;UI.slop=sl;SIMR.fx=fx0;SIMR.floats=fl;SIMR.modal=null;srvWinOff();
|
||||
return JSON.stringify(out);}
|
||||
|
||||
/* ---- pulls (5.3-5.6, 5.10): the only place the version moves ---- */
|
||||
function srvSubs(views){const o={};if(!Array.isArray(views))return o;
|
||||
for(const w of views.slice(0,16)){if(!w||typeof w!=='object')continue;
|
||||
if(typeof w.link==='string'){const l=S.links.find(x=>x.id===w.link),ef={},egd={};
|
||||
if(l){const k=edgeKey(l),rec=R.ef&&R.ef[k];if(rec){ef[k]=rec;for(const e in rec.eg||{})if(R.egDesc&&R.egDesc[e])egd[e]=R.egDesc[e];}}
|
||||
o['link:'+w.link]={ef,egd};}
|
||||
if(typeof w.peer==='string'&&isCity(w.peer))o['peer:'+w.peer]={pf:{[w.peer]:S.pops[w.peer]?pniFlows(w.peer):{}}};}
|
||||
return o;}
|
||||
function srvPullParts(m,K){K=K||srvKeyJson();const now=Date.now();
|
||||
// The first snapshot of an epoch, before any update: nobody holds anything of this realm yet, so there is no update to
|
||||
// make; what happened meanwhile (a new network's welcome) waits for the first one, which that page will get.
|
||||
if(m.snap&&!SIMR.seen){SIMR.seen=true;SIMR.base=K;SIMR.rSent=new WeakRef(R);
|
||||
return {upd:'',snap:'{"t":"snap","epoch":'+JSON.stringify(SIMR.epoch)+',"v":'+SIMR.v+',"now":'+now+',"S":'+srvJoin(K)+',"r":'+srvSlimR()+',"keep":[]}',subs:m.views?srvSubs(m.views):null};}
|
||||
const B=SIMR.base||Object.create(null),s=[],del=[];
|
||||
for(const k in K)if(B[k]!==K[k])s.push(k);for(const k in B)if(!(k in K))del.push(k);
|
||||
const rNew=!SIMR.rSent||SIMR.rSent.deref()!==R,fx=SIMR.fx,acts=SIMR.acts;let upd='';
|
||||
if(s.length||del.length||rNew||fx.length||acts.length){const from=SIMR.v,v=++SIMR.v;
|
||||
let t='{"t":"upd","from":'+from+',"v":'+v+',"now":'+now+',"day":'+S.day+',"s":{'+s.map(k=>JSON.stringify(k)+':'+K[k]).join(',')+'}';
|
||||
if(del.length)t+=',"del":'+JSON.stringify(del);
|
||||
if(rNew)t+=',"r":'+srvSlimR();
|
||||
const cf=srvCap(fx);if(cf.length)t+=',"fx":'+JSON.stringify(cf);
|
||||
if(acts.length)t+=',"acts":'+JSON.stringify(acts);
|
||||
upd=t+'}';SIMR.base=K;SIMR.rSent=new WeakRef(R);SIMR.fx=[];SIMR.acts=[];SIMR.floats=0;SIMR.seen=true;}
|
||||
let snap='';
|
||||
// A snapshot at the same version: what the host adds (clock, roster, since) it adds to this text itself.
|
||||
if(m.snap){const keep=fx.filter(f=>SIM_KEEP.has(f[0])).slice(-32);
|
||||
snap='{"t":"snap","epoch":'+JSON.stringify(SIMR.epoch)+',"v":'+SIMR.v+',"now":'+now+',"S":'+srvJoin(K)+',"r":'+srvSlimR()+',"keep":'+JSON.stringify(keep)+'}';
|
||||
SIMR.base=K;SIMR.rSent=new WeakRef(R);}
|
||||
return {upd,snap,subs:m.views?srvSubs(m.views):null};}
|
||||
function srvPull(inp){const m=inp?JSON.parse(inp):{},p=srvPullParts(m),parts=[],h={v:SIMR.v,parts};
|
||||
if(p.upd)parts.push('upd');if(p.snap)parts.push('snap');if(p.subs)h.subs=p.subs;
|
||||
return srvOut(h,...(p.upd?[p.upd]:[]),...(p.snap?[p.snap]:[]));}
|
||||
function srvSub(inp){const m=inp?JSON.parse(inp):{};return JSON.stringify({v:SIMR.v,subs:srvSubs(m.views)});}
|
||||
// The one-shots a page says when a network opens (the courtesy route, Australia's prices): they change S, so the
|
||||
// server says them, as fx of the next update.
|
||||
function srvGreet(inp){bootNotes();return srvPull(inp);}
|
||||
// A checkpoint: the save and its rt, ord included.
|
||||
function srvSave(){const txt=JSON.stringify(packSave(S)),K=srvKeyJson(),h=JSON.stringify({uidN,day:S.day,lost:!!S.lost,...srvClockNow()});
|
||||
return h.slice(0,-1)+',"rt":'+srvRtText(R,K,srvOrdOut(txt,K),srvSlOut(),srvRkOk(R,K,UI.rk,UI.rkR))+'}\\n'+txt;}
|
||||
function srvCard(){return JSON.stringify({card:mpCard()});}
|
||||
`;
|
||||
|
||||
// The realm API: one precompiled trampoline per name. Input in __in, a string out; a throw comes back as {srvErr}, and
|
||||
// changed built-ins as {srvErr, polluted}. The unchecked ones only read what a fresh realm needs from one that is done
|
||||
// (its save, rt, R and fx): the worker's recovery after a timeout or a pollution.
|
||||
const API = ['srvLoad', 'srvBegin', 'srvPrefs', 'srvMark', 'srvRestore', 'srvRt', 'srvRPack', 'srvFxOut', 'srvDay', 'srvAct', 'srvAsk', 'srvPull', 'srvSub', 'srvGreet', 'srvSave', 'srvCard'];
|
||||
const PEEK = ['srvRt', 'srvRPack', 'srvFxOut', 'srvSave'];
|
||||
let TRAMP = null, TRAMP0 = null;
|
||||
const tramp = (n, check) => new vm.Script(`(()=>{let r;try{r=${n}(globalThis.__in);}catch(e){r=JSON.stringify({srvErr:String(e&&e.stack||e).slice(0,4000)});}`
|
||||
+ (check ? `const d=srvDirty();return d?JSON.stringify({srvErr:'the built-ins of the realm changed: '+d,polluted:1}):r;})()` : 'return r;})()'), { filename: `srv-${n}.js` });
|
||||
const tramps = (check = true) => (check ? TRAMP || (TRAMP = Object.fromEntries(API.map((n) => [n, tramp(n, true)])))
|
||||
: TRAMP0 || (TRAMP0 = Object.fromEntries(PEEK.map((n) => [n, tramp(n, false)]))));
|
||||
// Tests only (createEngine({test})): run a piece of code in a realm, answer its value as JSON.
|
||||
const EVAL = new vm.Script('(()=>{const f=new Function(globalThis.__in);const v=f();return v===undefined?"null":JSON.stringify(v);})()', { filename: 'srv-test-eval.js' });
|
||||
|
||||
/* The game, the epilogue and the build id, compiled once per process. The engine passes the game text and its build
|
||||
id (read once, in the main thread), so a worker started later runs the game the engine names, whatever src/ holds by
|
||||
then; without them they are read from root. */
|
||||
function compileCode({ root = ROOT, page = REALM_PAGE, src = null, simId: id = null } = {}) {
|
||||
if (!vm.constants || vm.constants.DONT_CONTEXTIFY === undefined) {
|
||||
throw new Error(`server-run play needs Node 22.8 or newer (vm.constants.DONT_CONTEXTIFY); this is ${process.version}`);
|
||||
}
|
||||
const game = typeof src === 'string' && src ? src : gameSource({ root, page });
|
||||
return {
|
||||
game: new vm.Script(game, { filename: 'game.js' }),
|
||||
epilogue: new vm.Script(EPILOGUE, { filename: 'srv-epilogue.js' }),
|
||||
simId: id || simId(assemble({ src: path.join(root, 'src'), mp: true }).html),
|
||||
root,
|
||||
};
|
||||
}
|
||||
|
||||
const DICTS = new Map();
|
||||
function dictScript(lang, root) {
|
||||
const k = root + '|' + lang;
|
||||
if (!DICTS.has(k)) { const s = dictSource(lang, root); DICTS.set(k, s ? new vm.Script(s, { filename: `i18n-${lang}.js` }) : null); }
|
||||
return DICTS.get(k);
|
||||
}
|
||||
|
||||
class Realm {
|
||||
/* code: compileCode()'s; lang: the network's language; test: {seed, now, step} for tests; log(level, text). */
|
||||
constructor({ code, lang = 'en', test = null, log = () => {}, loadMs = 30000 }) {
|
||||
const t0 = performance.now();
|
||||
const ctx = vm.createContext(vm.constants.DONT_CONTEXTIFY);
|
||||
ctx.__hostNow = () => performance.now();
|
||||
let n = 0, w0 = 0;
|
||||
// The realm's console, rate-limited: 20 lines, then one a second.
|
||||
ctx.__hostLog = (lvl, txt) => { const t = Date.now(); if (n > 20 && t - w0 < 1000) return; if (t - w0 >= 1000) { w0 = t; n = Math.min(n, 20); } n++; log(lvl, String(txt).slice(0, 2000)); };
|
||||
// A language this server has no dictionary for plays in English (the page falls back the same way), not broken.
|
||||
let d = null;
|
||||
if (LANG_RE.test(lang) && lang !== 'en') { try { d = dictScript(lang, code.root); } catch (e) { log('warn', `no dictionary for ${lang}: English`); } }
|
||||
this.lang = d ? lang : 'en';
|
||||
new vm.Script(prelude({ lang: this.lang, test: !!test, ...(test || {}) }), { filename: 'srv-prelude.js' }).runInContext(ctx, { timeout: loadMs });
|
||||
if (d) d.runInContext(ctx, { timeout: loadMs });
|
||||
code.game.runInContext(ctx, { timeout: loadMs });
|
||||
code.epilogue.runInContext(ctx, { timeout: loadMs });
|
||||
// The no-op timers the page's own start called (two canvas resizes) are not a simulation's.
|
||||
new vm.Script('__SRV_T.n=0;if(__SRV_T.at)__SRV_T.at.length=0;').runInContext(ctx);
|
||||
this.ctx = ctx;
|
||||
this.ms = performance.now() - t0;
|
||||
}
|
||||
// The answer as the realm gave it (a string). Throws ERR_SCRIPT_EXECUTION_TIMEOUT past ms. check false: one of PEEK,
|
||||
// whatever the built-ins are now (recovery only).
|
||||
raw(name, input, ms = 1000, check = true) {
|
||||
const s = tramps(check)[name];
|
||||
if (!s) throw new Error(`mp-sim-realm: no realm call ${name}`);
|
||||
this.ctx.__in = input === undefined ? '' : JSON.stringify(input);
|
||||
try { const r = s.runInContext(this.ctx, { timeout: ms }); return typeof r === 'string' ? r : ''; } finally { this.ctx.__in = ''; }
|
||||
}
|
||||
// The header parsed, plus the parts that follow it.
|
||||
call(name, input, ms) { return parts(this.raw(name, input, ms)); }
|
||||
// Tests only.
|
||||
eval(src, ms = 5000) {
|
||||
this.ctx.__in = String(src);
|
||||
try { const r = EVAL.runInContext(this.ctx, { timeout: ms }); return JSON.parse(r); } finally { this.ctx.__in = ''; }
|
||||
}
|
||||
}
|
||||
|
||||
// [header (parsed), ...parts (strings)] of a realm's answer.
|
||||
function parts(text) {
|
||||
const t = String(text);
|
||||
const i = t.indexOf('\n');
|
||||
if (i < 0) return [JSON.parse(t || '{}')];
|
||||
const rest = t.slice(i + 1).split('\n');
|
||||
return [JSON.parse(t.slice(0, i)), ...rest];
|
||||
}
|
||||
|
||||
const isTimeout = (e) => !!e && e.code === 'ERR_SCRIPT_EXECUTION_TIMEOUT';
|
||||
|
||||
module.exports = { REALM_PAGE, gameSource, dictSource, prelude, EPILOGUE, API, compileCode, Realm, parts, isTimeout };
|
||||
408
scripts/lib/mp-sim-worker.js
Normal file
408
scripts/lib/mp-sim-worker.js
Normal file
|
|
@ -0,0 +1,408 @@
|
|||
// A worker thread of the server-run engine (the server-sim design, section 4.2): it compiles the game once, holds the
|
||||
// realms of the sessions placed on it (every network of a session in one worker), and answers the host's messages.
|
||||
//
|
||||
// Order. Messages run one at a time, in arrival order per network. A session's day is one task per network, in sorted
|
||||
// network order, with a turn for other messages between two networks: an action for network X lands between days of
|
||||
// other networks, never inside X's own day. The networks of a day are fixed when it starts. Loads, new networks and
|
||||
// unloads of a session wait for its day; actions for a network that is still loading wait for it. Every message is
|
||||
// answered: a load that names no network (or one twice), or a day whose lists are not lists, is refused whole and
|
||||
// changes nothing; a network in a load that has no save, or whose save does not load, answers err (broken) and the
|
||||
// others load. Nothing a message holds, and nothing a step throws, takes the worker down.
|
||||
//
|
||||
// Failures. Every realm call has a time limit (a day 2 s, an action 1 s, a what-if 3 s, a pull or a save 1 s). Before
|
||||
// a day or an action the realm is marked (its S as text, uidN, the dice, and for a day its rt: route memory and routing
|
||||
// point), and the worker keeps the mark. A mark changes nothing: one that fails leaves the realm as it was, and one
|
||||
// that runs out of time has the realm built again from its own save, never from an older mark (that would undo what
|
||||
// came after it). A call that throws has run its finally blocks: the realm goes back to the mark in place. A call that
|
||||
// times out has not (vm skips them), and one after which the realm's built-ins changed (a prototype written through)
|
||||
// left them changed: such a realm is never called again for play. A fresh one is built from the mark, with a new
|
||||
// epoch, and takes over the fx the mark held. A failed day runs once more; failing again, the network is broken at its
|
||||
// state before the day. When not even a fresh realm can be built, the network is dropped: its calls answer NO_REALM,
|
||||
// and the engine is told ({lost}), so the host loads it again from its checkpoint (4.7).
|
||||
//
|
||||
// The worker → host replies are the shapes of tests/lib/mp-sim-shape.js checkWorker(), sent as {id, ok, reply} (or
|
||||
// {id, ok:false, error}) for the engine to match its promises; logs go up as {log:[level, text]}, a dropped network as
|
||||
// {lost:{code, nid, why}}, and before each job or step that runs a realm {run: code}, the session it runs (the engine
|
||||
// forgets it at the next reply): a worker that dies then is that session's doing.
|
||||
'use strict';
|
||||
const { isMainThread, parentPort, workerData } = require('node:worker_threads');
|
||||
const crypto = require('node:crypto');
|
||||
const v8 = require('node:v8');
|
||||
const { compileCode, Realm, isTimeout, parts } = require('./mp-sim-realm');
|
||||
|
||||
const TIMEOUTS = { day: 2000, act: 1000, ask: 3000, pull: 1000, save: 1000, mark: 1000, small: 1000, load: 30000 };
|
||||
const now = () => performance.now();
|
||||
const MSG = (e) => String((e && (e.stack || e.message)) || e).slice(0, 2000);
|
||||
const LINE = (e) => String((e && e.message) || e).split('\n')[0].slice(0, 300);
|
||||
const msOf = (t0) => +(now() - t0).toFixed(2);
|
||||
|
||||
/* opts: {root, page, src, simId, test: {seed, now, step} | true | null, strict, timeouts, log(level, text), post(message)}. */
|
||||
function createCore(opts = {}) {
|
||||
const code = compileCode({ root: opts.root, page: opts.page, src: opts.src, simId: opts.simId });
|
||||
const T = { ...TIMEOUTS, ...(opts.timeouts || {}) };
|
||||
const test = opts.test ? (typeof opts.test === 'object' ? opts.test : {}) : null;
|
||||
const log = opts.log || (() => {});
|
||||
const post = opts.post || (() => {});
|
||||
const realms = new Map(), sessions = new Map(), jobs = [];
|
||||
let epochN = 0, pumping = false, turn = 0;
|
||||
const key = (c, n) => c + '/' + n;
|
||||
const epochOf = () => crypto.randomBytes(4).toString('hex') + (++epochN).toString(36);
|
||||
const session = (c) => { let s = sessions.get(c); if (!s) sessions.set(c, s = { code: c, day: null, load: null }); return s; };
|
||||
const running = (c) => post({ run: c });
|
||||
|
||||
/* ---- realms ---- */
|
||||
function build(nid, lang) {
|
||||
return new Realm({ code, lang, test: test && { seed: test.seed, now: test.now, step: test.step }, loadMs: T.load,
|
||||
log: (lvl, txt) => log(lvl === 'log' || lvl === 'info' || lvl === 'debug' ? 'info' : 'warn', `[${nid}] ${txt}`) });
|
||||
}
|
||||
// A realm call: [header, ...parts]; a throw inside the realm comes back as {srvErr}, a timeout throws. A realm whose
|
||||
// built-ins changed is marked polluted: the caller replaces it.
|
||||
const call = (e, name, input, ms) => { const r = e.realm.call(name, input, ms); if (r[0] && r[0].polluted) e.polluted = true; return r; };
|
||||
// What a fresh realm takes from one that is done (its save, rt, R, fx), whatever its built-ins are now.
|
||||
const peek = (e, name, input, ms) => (e.realm ? parts(e.realm.raw(name, input, ms, false)) : [{ srvErr: 'gone' }]);
|
||||
/* A fresh realm in place of one that is done (timed out, polluted, or could not go back in place), from {s, uidN, rt,
|
||||
live}: same network, new epoch, versions from 0, the fx the old one held (the mark's, or after a read all of them).
|
||||
R comes from the old realm, which still answers after a timeout: the marked R (mark) or its current one, packed
|
||||
whole; when it cannot (or is polluted), or that R does not load, R is routed again from rt's routing point. The old
|
||||
realm is never called again, even when this throws. */
|
||||
function rebuild(e, from, mark = true) {
|
||||
if (!from || typeof from.s !== 'string') { e.realm = null; throw new Error('rebuilding the realm failed: nothing to build from'); }
|
||||
let rpack = null, fx = null;
|
||||
if (!e.polluted) try { const s = e.realm && e.realm.raw('srvRPack', { mark }, T.load, false); if (typeof s === 'string' && s.startsWith('{"o"')) rpack = s; } catch (x) { /* gone */ }
|
||||
try { const [h] = peek(e, 'srvFxOut', { mark }, T.small); if (h && Array.isArray(h.fx)) fx = h; } catch (x) { /* gone */ }
|
||||
e.realm = null;
|
||||
const epoch = epochOf();
|
||||
const load = (rp) => {
|
||||
const r = build(e.nid, e.lang);
|
||||
const [h] = r.call('srvLoad', { save: from.s, uidN: from.uidN, rt: from.rt, rpack: rp, fx, live: !!from.live, prefs: e.prefs, epoch, strict: !!opts.strict, clock: from.clock }, T.load);
|
||||
if (h.srvErr) throw new Error(h.srvErr);
|
||||
return [r, h];
|
||||
};
|
||||
let r, h;
|
||||
try { [r, h] = load(rpack); } catch (x) {
|
||||
if (!rpack) throw new Error('rebuilding the realm failed: ' + LINE(x));
|
||||
log('warn', `[${e.nid}] R as it was did not load (${LINE(x)}): routed again`);
|
||||
rpack = null;
|
||||
try { [r, h] = load(null); } catch (y) { throw new Error('rebuilding the realm failed: ' + LINE(y)); }
|
||||
}
|
||||
e.realm = r; e.polluted = false; e.epoch = epoch; e.v = 0; e.day = h.day; e.lost = h.lost;
|
||||
log('warn', `[${e.nid}] realm rebuilt (epoch ${epoch}${rpack ? '' : ', R routed again'})`);
|
||||
}
|
||||
// The network cannot go on: dropped (later calls answer NO_REALM), and the engine tells the host (4.7).
|
||||
function lose(e, why) {
|
||||
e.realm = null; e.broken = true;
|
||||
if (realms.get(key(e.code, e.nid)) === e) realms.delete(key(e.code, e.nid));
|
||||
log('error', `[${e.nid}] dropped, its realm could not be built again: ${why}`);
|
||||
post({ lost: { code: e.code, nid: e.nid, why: String(why).slice(0, 300) } });
|
||||
}
|
||||
// A recovery: true when the network has a realm to play on again, else it is dropped.
|
||||
const recover = (e, f) => { try { f(); return true; } catch (x) { lose(e, LINE(x)); return false; } };
|
||||
const gone = (e) => (e.realm ? '' : '; the network was dropped: load it again');
|
||||
// The rt of the old realm's mark, if it still answers; else the last day's, whose routing point belongs to that day's
|
||||
// S: with another mark only its route memory counts (a close R).
|
||||
function markRt(e) {
|
||||
try { const [h] = peek(e, 'srvRt', { mark: true }, 200); if (h && !h.srvErr && h.load) return h; } catch (x) { /* gone */ }
|
||||
return e.dayMark ? (e.dayMark === e.mark ? e.dayMark.rt : { ...e.dayMark.rt, pt: undefined, rk: undefined }) : null;
|
||||
}
|
||||
// The restore point of the next day or action. A failed mark throws {mark:true} and changed nothing applied; one that
|
||||
// ran out of time has the realm built again from its own save first (or the network dropped).
|
||||
function mark(e, input) {
|
||||
e.mark = null;
|
||||
if (input.day) e.dayMark = null;
|
||||
let h, s;
|
||||
try { [h, s] = call(e, 'srvMark', input, T.mark); } catch (x) {
|
||||
if (!isTimeout(x)) throw x;
|
||||
recover(e, () => rebuildAfterRead(e));
|
||||
throw Object.assign(new Error(`marking the network took longer than ${T.mark} ms`), { mark: true, timeout: true });
|
||||
}
|
||||
if (h.srvErr) {
|
||||
if (e.polluted) recover(e, () => rebuildAfterRead(e));
|
||||
throw Object.assign(new Error('marking the network failed: ' + LINE(h.srvErr)), { mark: true });
|
||||
}
|
||||
const m = { s, uidN: h.uidN, rt: h.rt || null, day: h.day, clock: h.clock, live: true };
|
||||
if (input.day) e.dayMark = m;
|
||||
e.mark = m;
|
||||
return m;
|
||||
}
|
||||
// After a throw: back to the mark in place; if even that fails (or the realm is polluted), a fresh realm from the mark.
|
||||
function restore(e, input) {
|
||||
if (!e.polluted) {
|
||||
try { const [h] = call(e, 'srvRestore', input, T.small); if (!h.srvErr) return; log('warn', `[${e.nid}] restore failed: ${h.srvErr}`); }
|
||||
catch (x) { log('warn', `[${e.nid}] restore failed: ${LINE(x)}`); }
|
||||
}
|
||||
rebuild(e, { ...e.mark, rt: input.day ? e.mark.rt : markRt(e) });
|
||||
}
|
||||
// A call that changed nothing applied and timed out (or left the realm polluted): the fresh realm starts from the
|
||||
// realm's own save. When even that cannot be read, this throws: never an older mark.
|
||||
function rebuildAfterRead(e) {
|
||||
let from = null;
|
||||
try { const [h, txt] = peek(e, 'srvSave', undefined, T.save); if (!h.srvErr && typeof txt === 'string') from = { s: txt, uidN: h.uidN, rt: h.rt, clock: h.clock }; } catch (x) { /* gone */ }
|
||||
if (!from) { e.realm = null; throw new Error('rebuilding the realm failed: its save could not be read'); }
|
||||
rebuild(e, from, false);
|
||||
}
|
||||
|
||||
/* ---- the handlers: each returns the reply (or throws, which the engine turns into a rejection) ---- */
|
||||
const errReply = (m, what, msg) => ({ t: 'err', code: m.code, nid: m.nid, ...(m.msg && m.msg.rid ? { rid: m.msg.rid } : {}), what, msg: String(msg).slice(0, 500) });
|
||||
function loadOne(c, n) {
|
||||
const e = realms.get(key(c, n.nid));
|
||||
try {
|
||||
if (!n.begin && !(n.env && typeof n.env === 'object' && typeof n.env.s === 'string')) throw new Error('no save to load');
|
||||
e.realm = build(n.nid, n.lang);
|
||||
e.lang = e.realm.lang;
|
||||
const epoch = epochOf();
|
||||
// begin: {name, home, preset, asn, mp, tut, day?}, passed on untouched (srvBegin checks it; day: the session's date).
|
||||
const [h] = n.begin
|
||||
? call(e, 'srvBegin', { begin: n.begin, prefs: n.prefs, epoch, strict: !!opts.strict }, T.load)
|
||||
: call(e, 'srvLoad', { save: n.env.s, uidN: n.env.uidN, rt: n.env.rt, prefs: n.prefs, rng: n.rng, epoch, strict: !!opts.strict }, T.load);
|
||||
if (h.srvErr) throw new Error(h.srvErr);
|
||||
Object.assign(e, { epoch, v: 0, day: h.day, lost: h.lost, loading: false });
|
||||
const out = { t: 'loaded', nid: n.nid, epoch, day: h.day, lost: h.lost };
|
||||
if (n.begin) out.saved = saved(e);
|
||||
return out;
|
||||
} catch (x) {
|
||||
if (realms.get(key(c, n.nid)) === e) realms.delete(key(c, n.nid));
|
||||
log('warn', `[${n.nid}] did not load: ${MSG(x)}`);
|
||||
return { t: 'loaded', nid: n.nid, err: isTimeout(x) ? 'the network took too long to load' : LINE(x) };
|
||||
}
|
||||
}
|
||||
function saved(e) {
|
||||
const [h, txt] = call(e, 'srvSave', undefined, T.save);
|
||||
if (h.srvErr) { if (e.polluted) recover(e, () => rebuildAfterRead(e)); throw new Error(h.srvErr); }
|
||||
return { t: 'saved', nid: e.nid, txt, uidN: h.uidN, rt: h.rt, day: h.day, lost: h.lost };
|
||||
}
|
||||
// One network's day, with its mark, one retry, and broken after a second failure.
|
||||
function dayOne(e, m) {
|
||||
const t0 = now(), d0 = e.day;
|
||||
const input = { speed: m.speed, last: m.last, alone: m.alone.includes(e.nid), mute: !!m.mute };
|
||||
let err = null;
|
||||
for (let i = 0; i < 2 && e.realm; i++) {
|
||||
try {
|
||||
mark(e, { day: true });
|
||||
const [h] = call(e, 'srvDay', input, T.day);
|
||||
if (h.srvErr) throw new Error(h.srvErr);
|
||||
e.day = h.day; e.lost = h.lost;
|
||||
return { day: h.day, lost: h.lost, ...(h.pause ? { pause: true } : {}), ...(i ? { retried: true } : {}), ms: msOf(t0) };
|
||||
} catch (x) {
|
||||
err = x;
|
||||
log('warn', `[${e.nid}] day ${d0 + 1} failed (${x.mark ? 'mark' : isTimeout(x) ? 'timeout' : e.polluted ? 'polluted' : 'throw'}${i ? ', again' : ''}): ${MSG(x)}`);
|
||||
// A failed mark changed nothing (the realm is as it was, built again from its own save, or dropped). Else back
|
||||
// to this attempt's mark: in place after a throw, a fresh realm after a timeout or a pollution.
|
||||
if (!x.mark && !recover(e, () => { if (isTimeout(x) || e.polluted) rebuild(e, e.dayMark); else restore(e, { day: true }); })) break;
|
||||
}
|
||||
}
|
||||
e.broken = true;
|
||||
return { day: e.day, lost: !!e.lost, err: (isTimeout(err) ? 'timeout: ' : '') + LINE(err) + gone(e), retried: true, ms: msOf(t0) };
|
||||
}
|
||||
// An action or a what-if: its mark, the call, and the way back when it fails.
|
||||
function marked(m, e, name, input, ms, what) {
|
||||
try { mark(e, input); } catch (x) { if (!x.mark) throw x; return [errReply(m, x.timeout ? 'timeout' : 'throw', x.message + gone(e))]; }
|
||||
let r;
|
||||
try { r = call(e, name, m.msg, ms); } catch (x) {
|
||||
if (!isTimeout(x)) throw x;
|
||||
recover(e, () => rebuild(e, { ...e.mark, rt: markRt(e) }));
|
||||
return [errReply(m, 'timeout', `the ${what} took longer than ${ms} ms` + gone(e))];
|
||||
}
|
||||
if (r[0].srvErr) { recover(e, () => (e.polluted ? rebuild(e, { ...e.mark, rt: markRt(e) }) : restore(e, {}))); return [errReply(m, 'throw', r[0].srvErr + gone(e))]; }
|
||||
return r;
|
||||
}
|
||||
const H = {
|
||||
act(m, e) {
|
||||
if (e.broken || e.lost) return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: 'stopped', v: e.v, upd: null };
|
||||
const t0 = now(), [h, upd] = marked(m, e, 'srvAct', { keys: true }, T.act, 'action');
|
||||
if (h.t === 'err') return h;
|
||||
e.v = h.v;
|
||||
if (h.outcome === 'stopped') e.lost = true;
|
||||
return { t: 'actDone', nid: m.nid, epoch: e.epoch, rid: m.msg.rid, outcome: h.outcome, ...(h.why ? { why: h.why } : {}), v: h.v, upd: upd || null, ms: msOf(t0) };
|
||||
},
|
||||
ask(m, e) {
|
||||
if (e.broken || e.lost) return { t: 'askDone', nid: m.nid, rid: m.msg.rid, err: 'stopped' };
|
||||
const t0 = now(), [h] = marked(m, e, 'srvAsk', {}, T.ask, 'what-if');
|
||||
if (h.t === 'err') return h;
|
||||
return { t: 'askDone', nid: m.nid, rid: m.msg.rid, ...h, ms: msOf(t0) };
|
||||
},
|
||||
pull(m, e) { return pulled(m, e, 'srvPull', { snap: !!m.snap, views: m.views }); },
|
||||
greet(m, e) { return pulled(m, e, 'srvGreet', {}); },
|
||||
sub(m, e) {
|
||||
return guarded(m, e, () => { const [h] = call(e, 'srvSub', { views: m.views || [] }, T.pull); if (h.srvErr) return errReply(m, 'throw', h.srvErr); return { t: 'subbed', nid: m.nid, epoch: e.epoch, v: h.v, subs: h.subs }; });
|
||||
},
|
||||
save(m, e) { return guarded(m, e, () => saved(e)); },
|
||||
card(m, e) { return guarded(m, e, () => { const [h] = call(e, 'srvCard', undefined, T.small); if (h.srvErr) return errReply(m, 'throw', h.srvErr); return { t: 'card', nid: m.nid, card: h.card || null }; }); },
|
||||
prefs(m, e) { if (m.prefs) e.prefs = { ...e.prefs, ...m.prefs }; return guarded(m, e, () => { const [h] = call(e, 'srvPrefs', { prefs: m.prefs }, T.small); return h.srvErr ? errReply(m, 'throw', h.srvErr) : null; }); },
|
||||
// Tests only: a piece of code in the realm, its value back.
|
||||
eval(m, e) {
|
||||
if (!test) throw new Error('eval is for tests');
|
||||
try { return { value: e.realm.eval(m.src, m.ms || 5000) }; }
|
||||
catch (x) { if (isTimeout(x)) { recover(e, () => rebuildAfterRead(e)); return { timeout: true, epoch: e.epoch }; } return { error: MSG(x) }; }
|
||||
},
|
||||
};
|
||||
function pulled(m, e, name, input) {
|
||||
return guarded(m, e, () => {
|
||||
const t0 = now(), [h, ...p] = call(e, name, input, T.pull);
|
||||
if (h.srvErr) return errReply(m, 'throw', h.srvErr);
|
||||
e.v = h.v;
|
||||
const o = { t: 'pulled', nid: m.nid, epoch: e.epoch, v: h.v };
|
||||
(h.parts || []).forEach((k, i) => { o[k] = p[i]; });
|
||||
if (h.subs) o.subs = h.subs;
|
||||
o.ms = msOf(t0);
|
||||
return o;
|
||||
});
|
||||
}
|
||||
// A call that changes nothing applied: after a timeout (or a pollution) the realm is built again from its own save.
|
||||
function guarded(m, e, f) {
|
||||
let r;
|
||||
try { r = f(); } catch (x) {
|
||||
if (!isTimeout(x)) { if (e.polluted && e.realm) recover(e, () => rebuildAfterRead(e)); throw x; }
|
||||
recover(e, () => rebuildAfterRead(e));
|
||||
return errReply(m, 'timeout', `${m.t} took too long` + gone(e));
|
||||
}
|
||||
if (e.polluted && e.realm) recover(e, () => rebuildAfterRead(e));
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ---- the queue ---- */
|
||||
const SESSION_OPS = new Set(['load', 'unload', 'day']);
|
||||
function runnable(j, i) {
|
||||
const s = sessions.get(j.code);
|
||||
if (SESSION_OPS.has(j.t)) {
|
||||
if (s && (s.day || s.load)) return false;
|
||||
for (let k = 0; k < i; k++) if (jobs[k].code === j.code) return false;
|
||||
return true;
|
||||
}
|
||||
for (let k = 0; k < i; k++) if (jobs[k].code === j.code && SESSION_OPS.has(jobs[k].t) && jobs[k].t !== 'day') return false;
|
||||
// A network that is loading waits for its load; one marked loading with no load under way (none can be: a guard)
|
||||
// waits for nothing, so start() answers NO_REALM.
|
||||
const e = realms.get(key(j.code, j.nid));
|
||||
return !e || !e.loading || !(s && s.load);
|
||||
}
|
||||
function reply(j, r) { post({ id: j.id, ok: true, reply: r === undefined ? null : r }); }
|
||||
function fail(j, x) { post({ id: j.id, ok: false, error: { message: String((x && x.message) || x), code: (x && x.code) || 'ERR' } }); }
|
||||
function runJob() {
|
||||
for (let i = 0; i < jobs.length; i++) {
|
||||
const j = jobs[i];
|
||||
if (!runnable(j, i)) continue;
|
||||
jobs.splice(i, 1);
|
||||
try { start(j); } catch (x) { fail(j, x); }
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const strings = (a) => [...new Set(a.filter((n) => typeof n === 'string'))];
|
||||
function start(j) {
|
||||
if (j.t === 'mem') { const h = v8.getHeapStatistics(), mu = process.memoryUsage(); return reply(j, { heapUsed: h.used_heap_size, heapTotal: h.total_heap_size, external: h.external_memory, rss: mu.rss, realms: realms.size }); }
|
||||
if (j.t === 'load') {
|
||||
// The whole call first, with no side effects: a malformed one is refused and leaves every realm as it was. A
|
||||
// network without a save to load (or a begin) is only that network's problem: loadOne answers it broken.
|
||||
const nets = Array.isArray(j.nets) ? j.nets : [], seen = new Set();
|
||||
if (!nets.length) throw new Error('load: give the networks to load');
|
||||
for (const n of nets) {
|
||||
if (!n || typeof n !== 'object' || typeof n.nid !== 'string' || !n.nid) throw new Error('load: each network needs a nid');
|
||||
if (seen.has(n.nid)) throw new Error(`load: ${n.nid.slice(0, 40)} is there twice`);
|
||||
seen.add(n.nid);
|
||||
}
|
||||
const s = session(j.code);
|
||||
for (const n of nets) realms.set(key(j.code, n.nid), { code: j.code, nid: n.nid, lang: n.lang || 'en', prefs: n.prefs || {}, loading: true, realm: null, epoch: '', v: 0, day: 0, lost: false, broken: false, polluted: false, mark: null, dayMark: null });
|
||||
s.load = { j, i: 0, out: [] };
|
||||
return;
|
||||
}
|
||||
if (j.t === 'day') {
|
||||
// The lists as lists (of network ids), or the day is refused whole; speed and last the realm checks itself.
|
||||
for (const k of ['nets', 'alone']) if (j[k] !== undefined && !Array.isArray(j[k])) throw new Error(`day: ${k} must be a list`);
|
||||
j.alone = strings(j.alone || []);
|
||||
const s = session(j.code);
|
||||
const order = strings(j.nets || []).sort().filter((n) => { const e = realms.get(key(j.code, n)); return e && !e.loading && !e.broken && !e.lost; });
|
||||
s.day = { j, order, i: 0, out: {} };
|
||||
return;
|
||||
}
|
||||
if (j.t === 'unload') {
|
||||
for (const [k, e] of [...realms]) if (e.code === j.code && (j.nid === undefined || e.nid === j.nid)) realms.delete(k);
|
||||
if (![...realms.values()].some((e) => e.code === j.code)) sessions.delete(j.code);
|
||||
return reply(j, { t: 'unloaded', code: j.code, ...(j.nid !== undefined ? { nid: j.nid } : {}) });
|
||||
}
|
||||
const e = realms.get(key(j.code, j.nid));
|
||||
if (e && e.loading) { realms.delete(key(j.code, j.nid)); log('error', `[${j.nid}] marked loading with no load under way: dropped`); }
|
||||
if (!e || e.loading || !e.realm) throw Object.assign(new Error(`no realm ${key(j.code, j.nid)}`), { code: 'NO_REALM' });
|
||||
const h = H[j.t];
|
||||
if (!h) throw new Error(`unknown message ${j.t}`);
|
||||
running(j.code);
|
||||
return reply(j, h(j, e));
|
||||
}
|
||||
// One step of a session's load (one network) or day (one network). A throw answers the whole call, never the worker.
|
||||
function runStep() {
|
||||
const ss = [...sessions.values()].filter((s) => s.load || s.day);
|
||||
if (!ss.length) return false;
|
||||
const s = ss[turn++ % ss.length];
|
||||
if (s.load) {
|
||||
const L = s.load;
|
||||
try {
|
||||
const n = L.j.nets[L.i++];
|
||||
if (n) { running(s.code); L.out.push(loadOne(L.j.code, n)); }
|
||||
if (L.i >= L.j.nets.length) { s.load = null; reply(L.j, L.out); }
|
||||
} catch (x) {
|
||||
s.load = null;
|
||||
for (const n of L.j.nets.slice(L.i)) { const e = n && realms.get(key(L.j.code, n.nid)); if (e && e.loading) realms.delete(key(L.j.code, n.nid)); }
|
||||
log('error', `mp-sim worker: a load of ${s.code} failed: ${MSG(x)}`);
|
||||
fail(L.j, x);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const D = s.day;
|
||||
try {
|
||||
const nid = D.order[D.i++];
|
||||
const e = nid && realms.get(key(D.j.code, nid));
|
||||
if (e && !e.broken && !e.lost && e.realm) {
|
||||
running(s.code);
|
||||
try { D.out[nid] = dayOne(e, D.j); } catch (x) {
|
||||
e.broken = true;
|
||||
log('error', `[${nid}] the day could not run: ${MSG(x)}`);
|
||||
D.out[nid] = { day: e.day, lost: !!e.lost, err: 'the day could not run: ' + LINE(x), retried: false, ms: 0 };
|
||||
}
|
||||
}
|
||||
if (D.i >= D.order.length) { s.day = null; reply(D.j, { t: 'dayDone', code: D.j.code, d: D.j.d, nets: D.out }); }
|
||||
} catch (x) {
|
||||
s.day = null;
|
||||
log('error', `mp-sim worker: a day of ${s.code} failed: ${MSG(x)}`);
|
||||
fail(D.j, x);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
/* Turns: a message and a step of a session's load or day, in alternation. The worker goes on only while something ran:
|
||||
what a job waits for (a load, a day, an earlier job of its session) is itself a job or a step that runs, so a pass
|
||||
where nothing could run means nothing will until a message comes (handle() kicks). If a job were still waiting
|
||||
then, nothing could ever free it: it is answered, not left pending, and the worker does not spin on it. */
|
||||
let flip = false;
|
||||
function pump() {
|
||||
pumping = false;
|
||||
flip = !flip;
|
||||
try {
|
||||
if (flip ? runJob() || runStep() : runStep() || runJob()) return kick();
|
||||
if (!jobs.length) return;
|
||||
const j = jobs.shift();
|
||||
log('error', `mp-sim worker: ${j.t} for ${key(j.code, j.nid)} waited for nothing that could come; answered`);
|
||||
fail(j, new Error(`${j.t} could not run`));
|
||||
} catch (x) { log('error', `mp-sim worker: ${MSG(x)}`); }
|
||||
kick();
|
||||
}
|
||||
function kick() { if (!pumping) { pumping = true; setImmediate(pump); } }
|
||||
return {
|
||||
handle(m) { jobs.push(m); kick(); },
|
||||
stats: () => ({ realms: realms.size, sessions: sessions.size, jobs: jobs.length }),
|
||||
simId: code.simId,
|
||||
};
|
||||
}
|
||||
|
||||
if (!isMainThread && workerData && workerData.mpSim) {
|
||||
const W = workerData.mpSim;
|
||||
const post = (m) => parentPort.postMessage(m);
|
||||
const log = (level, text) => post({ log: [level, text] });
|
||||
process.on('unhandledRejection', (e) => log('warn', 'unhandled rejection in a realm: ' + MSG(e)));
|
||||
let core;
|
||||
try {
|
||||
// Tests only: a worker that cannot start (the engine backs off, then stops trying).
|
||||
if (W.test && W.test.startFail) throw new Error('injected: the game does not start');
|
||||
core = createCore({ ...W, log, post });
|
||||
} catch (e) { post({ fatal: MSG(e) }); process.exit(1); }
|
||||
parentPort.on('message', (m) => core.handle(m));
|
||||
post({ ready: true, simId: core.simId });
|
||||
}
|
||||
|
||||
module.exports = { createCore, TIMEOUTS };
|
||||
448
scripts/lib/mp.js
Normal file
448
scripts/lib/mp.js
Normal file
|
|
@ -0,0 +1,448 @@
|
|||
// The multiplayer API (docs/MULTIPLAYER.md): sessions players share by a short code, each player's save kept on the
|
||||
// server, and a small public card per player for the session's leaderboard and feed. Plain node:http, no dependencies.
|
||||
// scripts/mp-server.js runs it on its own (optionally serving the built site too); npm run dev -- --mp mounts it in the
|
||||
// dev server. It is never part of the page or of site/: the page only talks to it when the build stamped MP_API.
|
||||
//
|
||||
// Storage: one JSON file per session (DIR/<CODE>.json: settings, players, cards, feed) and one file per player's save
|
||||
// (DIR/<CODE>.<pid>.save), kept apart so a card push never rewrites a dozen saves. Writes go to a temporary file and are
|
||||
// renamed into place, one session at a time, in order. A session code is checked against CODE_RE before it ever becomes
|
||||
// part of a file name, and so is a player id.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const net = require('node:net');
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
// Crockford's base32 (no I, L, O or U): codes read aloud or typed from a phone do not get mixed up.
|
||||
const ALPHA = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
|
||||
const CODE_RE = /^[0-9A-HJKMNP-TV-Z]{6}$/;
|
||||
const PID_RE = /^[a-z0-9]{8}$/;
|
||||
const TOKEN_RE = /^[0-9a-f]{64}$/;
|
||||
const PRESETS = ['soft', 'freeze', 'oncall', 'bgp'];
|
||||
const PPOL = ['open', 'selective', 'closed'];
|
||||
const TIERS = ['t1', 't2', 't3'];
|
||||
const ASN_LO = 200000, ASN_HI = 214999;
|
||||
const COLORS = ['#ff4f9a', '#3a86ff', '#ffbe0b', '#2ec4b6', '#8338ec', '#fb5607', '#06d6a0', '#e63946', '#118ab2', '#8ac926', '#b5179e', '#6c757d'];
|
||||
const MAX_SAVE = 4 * 1024 * 1024; // characters of save text ('gz:'+base64 or JSON)
|
||||
const LIMIT = { small: 16 * 1024, save: MAX_SAVE + 64 * 1024 };
|
||||
const SAVE_MS = 120000; // a save's body must arrive within this, or the upload is cut (it holds one of few places)
|
||||
const FEED_MAX = 100, CHAT_MAX = 200;
|
||||
const DAY = 86400000;
|
||||
|
||||
// "k7q-2xd", "K7Q 2XD", even "k7q2xo": the code itself, or null. I, L and O are read as 1, 1 and 0, as Crockford meant.
|
||||
function normCode(s) {
|
||||
if (typeof s !== 'string' || s.length > 20) return null;
|
||||
const c = s.toUpperCase().replace(/[\s-]/g, '').replace(/[IL]/g, '1').replace(/O/g, '0');
|
||||
return CODE_RE.test(c) ? c : null;
|
||||
}
|
||||
const showCode = (c) => c.slice(0, 3) + '-' + c.slice(3);
|
||||
const randCode = () => { const b = crypto.randomBytes(6); let s = ''; for (const x of b) s += ALPHA[x & 31]; return s; };
|
||||
const randPid = () => crypto.randomBytes(4).toString('hex');
|
||||
const sha = (t) => crypto.createHash('sha256').update(t).digest();
|
||||
|
||||
// Text from players: no control or bidi-override characters, none of <>&"'` (the page escapes everything anyway), one
|
||||
// space between words, at most max characters (whole characters, never half an emoji).
|
||||
function cleanText(v, max) {
|
||||
if (typeof v !== 'string') return '';
|
||||
const s = v.replace(/[\u0000-\u001f\u007f-\u009f--<>&"'`]/g, '').replace(/\s+/g, ' ').trim();
|
||||
return Array.from(s).slice(0, max).join('').trim();
|
||||
}
|
||||
const cleanChat = (v) => {
|
||||
if (typeof v !== 'string') return '';
|
||||
const s = v.replace(/[\u0000-\u001f\u007f-\u009f--]/g, ' ').replace(/\s+/g, ' ').trim();
|
||||
return Array.from(s).slice(0, CHAT_MAX).join('').trim();
|
||||
};
|
||||
const num = (v, lo, hi, d = 0) => { v = +v; if (!Number.isFinite(v)) return d; return Math.min(hi, Math.max(lo, v)); };
|
||||
const int = (v, lo, hi, d = 0) => Math.round(num(v, lo, hi, d));
|
||||
// Only the first few times max entries are even looked at: a card padded with copies costs no more than an honest one.
|
||||
const ids = (v, re, max) => {
|
||||
if (!Array.isArray(v)) return [];
|
||||
const out = new Set();
|
||||
for (const x of v.slice(0, max * 4)) { if (typeof x === 'string' && re.test(x)) out.add(x); if (out.size >= max) break; }
|
||||
return [...out];
|
||||
};
|
||||
const CITY_RE = /^[a-z0-9]{2,8}$/, IX_RE = /^[a-z0-9~_-]{1,16}$/, NET_RE = /^[a-z0-9]{1,12}$/;
|
||||
|
||||
/* A player's public card: only these fields, numbers clamped, ids only in their shape (the page checks them against its
|
||||
catalogs again: this is other players' data there). Name and AS number come from the server, never from the card. */
|
||||
function cleanCard(c) {
|
||||
if (!c || typeof c !== 'object' || Array.isArray(c)) return null;
|
||||
const links = [];
|
||||
if (Array.isArray(c.links)) for (const l of c.links.slice(0, 1200)) {
|
||||
if (!Array.isArray(l) || typeof l[0] !== 'string' || typeof l[1] !== 'string' || !CITY_RE.test(l[0]) || !CITY_RE.test(l[1]) || l[0] === l[1]) continue;
|
||||
links.push([l[0], l[1], num(l[2], 0, 1e7)]);
|
||||
if (links.length >= 300) break;
|
||||
}
|
||||
return {
|
||||
day: int(c.day, 0, 1e7), tier: TIERS.includes(c.tier) ? c.tier : 't3', t1: c.t1 === true, lvl: int(c.lvl, 0, 99),
|
||||
pops: ids(c.pops, CITY_RE, 500), links, ix: ids(c.ix, IX_RE, 500), transit: ids(c.transit, NET_RE, 64),
|
||||
ppol: PPOL.includes(c.ppol) ? c.ppol : 'open', reach: num(c.reach, 0, 1), peak: num(c.peak, 0, 1e9), served: num(c.served, 0, 1e9),
|
||||
cust: int(c.cust, 0, 1e7), rev: num(c.rev, -1e13, 1e13), cashB: int(c.cashB, -1, 20), score: num(c.score, 0, 1e15),
|
||||
};
|
||||
}
|
||||
|
||||
/* Small in-memory rate limits: at most n events per window for one key (an address, a player). Keys are kept in the
|
||||
order they were last seen, so the ones nobody used for a whole window go from the front, a few at a time, and above
|
||||
cap keys the oldest go too: memory stays bounded and no call ever walks the whole map. */
|
||||
function limiter(n, ms, cap = 20000) {
|
||||
const m = new Map();
|
||||
const live = (k, now) => { const a = m.get(k); return a ? a.filter((t) => now - t < ms) : []; };
|
||||
return {
|
||||
// Counts one more, unless the key is already at its limit.
|
||||
ok(k, now) {
|
||||
const a = live(k, now), ok = a.length < n;
|
||||
if (ok) a.push(now);
|
||||
m.delete(k); m.set(k, a);
|
||||
for (const [x, v] of m) { if (m.size > cap || !v.length || now - v[v.length - 1] >= ms) m.delete(x); else break; }
|
||||
return ok;
|
||||
},
|
||||
full: (k, now) => live(k, now).length >= n,
|
||||
size: () => m.size,
|
||||
};
|
||||
}
|
||||
|
||||
/* The address a limit counts against. One IPv6 customer (a phone, a home, a server) usually holds a whole /64, so an
|
||||
IPv6 address counts as its /64; an IPv4 address mapped into IPv6 counts as itself. null: not an address. */
|
||||
function addrKey(a) {
|
||||
a = String(a || '').trim();
|
||||
if (a.startsWith('[')) a = a.slice(1, a.indexOf(']') >>> 0);
|
||||
const z = a.indexOf('%'); if (z >= 0) a = a.slice(0, z);
|
||||
const m4 = /^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(a); if (m4) a = m4[1];
|
||||
const v = net.isIP(a);
|
||||
if (v === 4) return a;
|
||||
if (v !== 6) return null;
|
||||
const [h, t] = a.toLowerCase().split('::'), head = h ? h.split(':') : [], tail = t ? t.split(':') : [];
|
||||
// The groups :: stands for (a dotted IPv4 at the end is two of them).
|
||||
const n = head.length + tail.length + (tail.length && tail[tail.length - 1].includes('.') ? 1 : 0);
|
||||
const g = t === undefined ? head : [...head, ...Array(8 - n).fill('0'), ...tail];
|
||||
return g.slice(0, 4).map((x) => parseInt(x, 16).toString(16)).join(':') + '::/64';
|
||||
}
|
||||
|
||||
class HttpError extends Error { constructor(status, msg, extra) { super(msg); this.status = status; this.extra = extra; } }
|
||||
const fail = (status, msg, extra) => { throw new HttpError(status, msg, extra); };
|
||||
|
||||
// The request body as JSON, refusing it as soon as it is longer than max bytes (never buffered beyond that). A body that
|
||||
// has not arrived within ms is cut off: it would hold its place (and its memory) for as long as the sender likes.
|
||||
function readJson(req, max, ms = 30000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const ct = String(req.headers['content-type'] || '');
|
||||
if (!/^application\/json\b/i.test(ct)) { req.resume(); return reject(new HttpError(415, 'send JSON (content-type: application/json)')); }
|
||||
const len = +req.headers['content-length'];
|
||||
if (len > max) { req.resume(); return reject(new HttpError(413, 'too large')); }
|
||||
let parts = [], n = 0, done = false;
|
||||
const stop = (e) => { if (done) return; done = true; clearTimeout(tm); parts = null; reject(e); };
|
||||
const tm = setTimeout(() => { stop(new HttpError(408, 'too slow')); req.destroy(); }, ms);
|
||||
req.on('data', (b) => {
|
||||
if (done) return;
|
||||
n += b.length;
|
||||
if (n > max) { stop(new HttpError(413, 'too large')); req.resume(); return; }
|
||||
parts.push(b);
|
||||
});
|
||||
req.on('end', () => {
|
||||
if (done) return; done = true; clearTimeout(tm);
|
||||
let j;
|
||||
try { const t = Buffer.concat(parts).toString('utf8'); parts = null; j = JSON.parse(t); } catch (e) { return reject(new HttpError(400, 'bad JSON')); }
|
||||
if (!j || typeof j !== 'object' || Array.isArray(j)) return reject(new HttpError(400, 'expected a JSON object'));
|
||||
resolve(j);
|
||||
});
|
||||
req.on('error', () => stop(new HttpError(400, 'request failed')));
|
||||
req.on('close', () => { if (!req.complete) stop(new HttpError(400, 'request failed')); });
|
||||
});
|
||||
}
|
||||
|
||||
function send(res, status, body) {
|
||||
if (res.headersSent) { try { res.end(); } catch (e) { /* gone */ } return; }
|
||||
const txt = JSON.stringify(body);
|
||||
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', 'content-length': Buffer.byteLength(txt) });
|
||||
res.end(txt);
|
||||
}
|
||||
|
||||
/* createMp({dir, base, maxSessions, maxPlayers, pruneDays, trustProxy, verbose, log, now, ...limits}): the API.
|
||||
handle(req, res) answers anything under base (default /api/mp) and returns true, or returns false for everything else. */
|
||||
function createMp(o = {}) {
|
||||
const dir = path.resolve(o.dir || 'mp-data');
|
||||
const base = (o.base || '/api/mp').replace(/\/+$/, '');
|
||||
const maxSessions = o.maxSessions || 1000, maxPlayers = o.maxPlayers || 12, pruneDays = o.pruneDays || 60;
|
||||
const now = o.now || Date.now, log = o.log || ((s) => console.log(s));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const file = (code) => path.join(dir, code + '.json');
|
||||
const saveFile = (code, pid) => path.join(dir, `${code}.${pid}.save`);
|
||||
const cache = new Map(), chains = new Map(), soon = new Map();
|
||||
let codes = new Set(), tmpN = 0;
|
||||
const HOUR = 3600000, MIN = 60000;
|
||||
const createRate = limiter(o.createPerHour || 10, HOUR), joinRate = limiter(o.joinPerHour || 60, HOUR);
|
||||
// However many addresses ask, the server fills up slowly: a full server takes days, not minutes.
|
||||
const createAll = limiter(o.sessionsPerHour || 100, HOUR);
|
||||
const chatRate = limiter(6, 30000), chatGap = limiter(1, 1000);
|
||||
// Wrong codes, counted per address: guessing codes runs out long before it finds one.
|
||||
const missRate = limiter(o.missesPerHour || 120, HOUR);
|
||||
// A player's pushes. The game sends a save at most every 15 seconds and a card with it, so these never touch it; they
|
||||
// stop one player from keeping the disk busy rewriting their session.
|
||||
const saveRate = limiter(o.savesPerMinute || 20, MIN), cardRate = limiter(o.cardsPerMinute || 60, MIN);
|
||||
// Saves being uploaded: one per player, a few per address, a few more on the whole server. Each can hold megabytes.
|
||||
const up = new Set(), upAddr = new Map(), maxUploads = o.maxUploads || 16, maxUploadsAddr = o.maxUploadsPerAddress || 4;
|
||||
|
||||
// Atomic: write a temporary file next to it, then rename over the old one.
|
||||
const writeAtomic = async (f, txt) => {
|
||||
const tmp = `${f}.${process.pid}.${++tmpN}.tmp`;
|
||||
await fs.promises.writeFile(tmp, txt);
|
||||
await fs.promises.rename(tmp, f);
|
||||
};
|
||||
// One session's writes happen one after another, in the order they were asked for.
|
||||
const queue = (code, job) => {
|
||||
const p = (chains.get(code) || Promise.resolve()).then(job, job);
|
||||
const q = p.catch((e) => { log(`[mp] writing ${code} failed: ${e.message}`); });
|
||||
chains.set(code, q);
|
||||
q.then(() => { if (chains.get(code) === q) chains.delete(code); });
|
||||
return p;
|
||||
};
|
||||
// A session that is gone (its last player left) is never written again, whatever was still on its way.
|
||||
const persist = (s) => {
|
||||
const tm = soon.get(s.code); if (tm) { clearTimeout(tm); soon.delete(s.code); }
|
||||
s.touched = now();
|
||||
if (s.dead) return Promise.resolve();
|
||||
return queue(s.code, () => s.dead ? null : writeAtomic(file(s.code), JSON.stringify(s)));
|
||||
};
|
||||
// Cards change often and matter little: their session is written a moment later, once for all of that moment's.
|
||||
const persistSoon = (s) => {
|
||||
s.touched = now();
|
||||
if (s.dead || soon.has(s.code)) return;
|
||||
const tm = setTimeout(() => { soon.delete(s.code); persist(s); }, o.persistMs ?? 2000);
|
||||
if (tm.unref) tm.unref();
|
||||
soon.set(s.code, tm);
|
||||
};
|
||||
|
||||
function scan() { codes = new Set(); for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.json$/.exec(f); if (m && CODE_RE.test(m[1])) codes.add(m[1]); } }
|
||||
// Sessions nobody touched for pruneDays go, with their saves; so do leftovers of interrupted writes.
|
||||
function prune() {
|
||||
const cut = now() - pruneDays * DAY; let n = 0;
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
const p = path.join(dir, f);
|
||||
let st; try { st = fs.statSync(p); } catch (e) { continue; }
|
||||
if (!st.isFile()) continue;
|
||||
if (f.endsWith('.tmp') && st.mtimeMs < now() - 3600000) { fs.rmSync(p, { force: true }); continue; }
|
||||
const m = /^([0-9A-Z]{6})\.json$/.exec(f);
|
||||
const live = m && cache.get(m[1]);
|
||||
if (m && CODE_RE.test(m[1]) && st.mtimeMs < cut && !(live && live.touched >= cut)) { drop(m[1]); n++; }
|
||||
}
|
||||
for (const f of fs.readdirSync(dir)) { const m = /^([0-9A-Z]{6})\.[a-z0-9]{8}\.save$/.exec(f); if (m && !fs.existsSync(file(m[1]))) fs.rmSync(path.join(dir, f), { force: true }); }
|
||||
scan();
|
||||
return n;
|
||||
}
|
||||
function drop(code) {
|
||||
const s = cache.get(code); if (s) s.dead = true;
|
||||
const tm = soon.get(code); if (tm) { clearTimeout(tm); soon.delete(code); }
|
||||
for (const f of fs.readdirSync(dir)) if (f === code + '.json' || (f.startsWith(code + '.') && f.endsWith('.save'))) fs.rmSync(path.join(dir, f), { force: true });
|
||||
cache.delete(code); codes.delete(code);
|
||||
}
|
||||
function load(code) {
|
||||
if (!CODE_RE.test(code)) return null;
|
||||
if (cache.has(code)) return cache.get(code);
|
||||
if (!codes.has(code)) return null;
|
||||
let s = null;
|
||||
try { s = JSON.parse(fs.readFileSync(file(code), 'utf8')); } catch (e) { return null; }
|
||||
if (!s || s.code !== code || !Array.isArray(s.players)) return null;
|
||||
// A hand-edited or damaged file: players without an id or a token hash cannot be anyone.
|
||||
s.players = s.players.filter((p) => p && typeof p === 'object' && PID_RE.test(p.pid) && typeof p.th === 'string');
|
||||
for (const p of s.players) if (!p.hit || typeof p.hit !== 'object') p.hit = { t1: !!(p.card && p.card.t1), t2: !!(p.card && (p.card.t1 || p.card.tier !== 't3')) };
|
||||
if (!Array.isArray(s.feed)) s.feed = [];
|
||||
cache.set(code, s);
|
||||
return s;
|
||||
}
|
||||
prune();
|
||||
|
||||
// The client's address, as the limits count it (see addrKey); behind your own proxy, the one it added last.
|
||||
const ipOf = (req) => {
|
||||
if (o.trustProxy) { const x = String(req.headers['x-forwarded-for'] || '').split(',').map((v) => v.trim()).filter(Boolean); const k = x.length && addrKey(x[x.length - 1]); if (k) return k; }
|
||||
return addrKey(req.socket.remoteAddress) || '?';
|
||||
};
|
||||
// The player this request's token belongs to, or null. Compares hashes of the same length, in constant time, even for
|
||||
// a player who is not there.
|
||||
function player(req, s) {
|
||||
const m = /^Bearer ([a-z0-9]{8})\.([0-9a-f]{64})$/.exec(String(req.headers.authorization || ''));
|
||||
if (!m) return null;
|
||||
const p = s.players.find((x) => x.pid === m[1]);
|
||||
const want = p && /^[0-9a-f]{64}$/.test(p.th) ? Buffer.from(p.th, 'hex') : Buffer.alloc(32), got = sha(m[2]);
|
||||
return crypto.timingSafeEqual(want, got) && p ? p : null;
|
||||
}
|
||||
const authed = (p) => { if (!p) fail(401, 'unauthorized'); p.seen = now(); return p; };
|
||||
// Still there after waiting for a body or a write: the player may have left meanwhile, or the session gone with them.
|
||||
const still = (s, p) => !s.dead && cache.get(s.code) === s && (!p || s.players.includes(p));
|
||||
const event = (s, k, p, extra) => { s.feed.push({ k, pid: p.pid, name: p.name, at: now(), ...extra }); if (s.feed.length > FEED_MAX) s.feed.splice(0, s.feed.length - FEED_MAX); };
|
||||
const roster = (s) => ({
|
||||
code: s.code, title: s.title, preset: s.preset, seed: s.seed, created: s.created,
|
||||
players: s.players.map((p) => ({ pid: p.pid, name: p.name, asn: p.asn, color: p.color, card: p.card, seen: p.seen, joined: p.joined })),
|
||||
feed: s.feed,
|
||||
});
|
||||
// A card can tell the feed something, once per player: reaching Tier 2, and Tier 1 (the first one in the session gets
|
||||
// the headline). A network that drops out and comes back is not news again.
|
||||
function applyCard(s, p, c) {
|
||||
const hit = p.hit || (p.hit = {});
|
||||
if (c.t1 && !hit.t1) { hit.t1 = hit.t2 = true; if (!s.first) { s.first = p.pid; event(s, 't1first', p); } else event(s, 't1', p); }
|
||||
else if (c.tier === 't2' && !hit.t2) { hit.t2 = true; event(s, 't2', p); }
|
||||
p.card = c;
|
||||
}
|
||||
function newPlayer(s, body, ip) {
|
||||
const net = body.net && typeof body.net === 'object' ? body.net : {};
|
||||
const name = cleanText(net.name, 32);
|
||||
if (!name) fail(400, 'name your network');
|
||||
const home = typeof net.home === 'string' && CITY_RE.test(net.home) ? net.home : null;
|
||||
if (!home) fail(400, 'pick a home city');
|
||||
let pid; do pid = randPid(); while (s.players.some((p) => p.pid === pid));
|
||||
const token = crypto.randomBytes(32).toString('hex');
|
||||
const avoid = new Set((Array.isArray(body.avoid) ? body.avoid.slice(0, 64) : []).filter((a) => Number.isInteger(a)));
|
||||
for (const p of s.players) avoid.add(p.asn);
|
||||
let asn; do asn = ASN_LO + crypto.randomInt(ASN_HI - ASN_LO + 1); while (avoid.has(asn));
|
||||
const color = COLORS.find((c) => !s.players.some((p) => p.color === c)) || COLORS[s.players.length % COLORS.length];
|
||||
const p = { pid, name, home, asn, color, th: sha(token).toString('hex'), joined: now(), seen: now(), card: null, sv: null, hit: {} };
|
||||
s.players.push(p);
|
||||
event(s, 'join', p);
|
||||
return { code: s.code, pid, token, seed: s.seed, asn, preset: s.preset, color, title: s.title };
|
||||
}
|
||||
// The save as stored: its text alone (the number and time are in the session). Files from before that were wrapped.
|
||||
const readSave = async (code, pid) => {
|
||||
const t = await fs.promises.readFile(saveFile(code, pid), 'utf8');
|
||||
if (t.startsWith('{"seq":')) { try { const j = JSON.parse(t); if (typeof j.data === 'string') return j.data; } catch (e) { /* a save after all */ } }
|
||||
return t;
|
||||
};
|
||||
// A save upload holds a place until it is done: one per player, a few per address and on the whole server.
|
||||
function upTake(key, ip) {
|
||||
if (up.has(key)) fail(429, 'a save of yours is still on its way');
|
||||
if (up.size >= maxUploads || (upAddr.get(ip) || 0) >= maxUploadsAddr) fail(503, 'busy: try again in a moment', { busy: true });
|
||||
up.add(key); upAddr.set(ip, (upAddr.get(ip) || 0) + 1);
|
||||
return () => { up.delete(key); const n = (upAddr.get(ip) || 1) - 1; if (n > 0) upAddr.set(ip, n); else upAddr.delete(ip); };
|
||||
}
|
||||
|
||||
async function route(req, res, url) {
|
||||
const rest = url.pathname.slice(base.length);
|
||||
const t = now(), ip = ipOf(req), M = req.method;
|
||||
if (rest === '/sessions') {
|
||||
if (M !== 'POST') fail(405, 'method not allowed');
|
||||
const body = await readJson(req, LIMIT.small);
|
||||
if (codes.size >= maxSessions) fail(503, 'the server is full: no new sessions for now');
|
||||
if (!createRate.ok(ip, t)) fail(429, 'too many new sessions from here: try again later');
|
||||
if (!createAll.ok('*', t)) fail(503, 'the server is full: no new sessions for now');
|
||||
const preset = PRESETS.includes(body.preset) ? body.preset : null;
|
||||
if (!preset) fail(400, 'unknown rules preset');
|
||||
let code; do code = randCode(); while (codes.has(code));
|
||||
const s = { v: 1, code, title: cleanText(body.title, 40), preset, seed: crypto.randomBytes(4).readInt32LE(0), created: t, touched: t, first: null, players: [], feed: [] };
|
||||
const out = newPlayer(s, body, ip);
|
||||
codes.add(code); cache.set(code, s);
|
||||
await persist(s);
|
||||
return send(res, 201, out);
|
||||
}
|
||||
const m = /^\/sessions\/([^/]{1,32})(\/[a-z]+)?$/.exec(rest);
|
||||
if (!m) fail(404, 'not found');
|
||||
const sub = m[2] || '';
|
||||
let raw = ''; try { raw = decodeURIComponent(m[1]); } catch (e) { /* not a code */ }
|
||||
const code = normCode(raw), s = code && load(code);
|
||||
// A player of this very session, with their token, is never held up by somebody else's wrong codes from the same
|
||||
// address. Everyone else is: a wrong code and a wrong token get the same answer then, so it says nothing either.
|
||||
const me = s ? player(req, s) : null;
|
||||
if (!me && missRate.full(ip, t)) fail(429, 'too many wrong codes from here: try again later');
|
||||
if (sub === '/join' && M === 'POST' && !joinRate.ok(ip, t)) fail(429, 'too many joins from here: try again later');
|
||||
if (!s) { missRate.ok(ip, t); fail(404, 'no such session'); }
|
||||
if (sub === '/join') {
|
||||
if (M !== 'POST') fail(405, 'method not allowed');
|
||||
const body = await readJson(req, LIMIT.small);
|
||||
if (!still(s)) fail(404, 'no such session');
|
||||
if (s.players.length >= maxPlayers) fail(409, 'this session is full', { full: true });
|
||||
const out = newPlayer(s, body, ip);
|
||||
await persist(s);
|
||||
return send(res, 200, out);
|
||||
}
|
||||
if (sub === '') {
|
||||
if (M !== 'GET') fail(405, 'method not allowed');
|
||||
authed(me);
|
||||
return send(res, 200, roster(s));
|
||||
}
|
||||
if (sub === '/card') {
|
||||
if (M !== 'PUT') fail(405, 'method not allowed');
|
||||
const p = authed(me);
|
||||
if (!cardRate.ok(code + '.' + p.pid, t)) fail(429, 'too many cards: slow down');
|
||||
const body = await readJson(req, LIMIT.small);
|
||||
if (!still(s, p)) fail(401, 'unauthorized');
|
||||
const c = cleanCard(body.card);
|
||||
if (!c) fail(400, 'bad card');
|
||||
applyCard(s, p, c);
|
||||
persistSoon(s);
|
||||
return send(res, 200, roster(s));
|
||||
}
|
||||
if (sub === '/save') {
|
||||
if (M === 'GET') {
|
||||
const p = authed(me);
|
||||
if (!p.sv) fail(404, 'no save yet');
|
||||
let data; try { data = await readSave(code, p.pid); } catch (e) { fail(404, 'no save yet'); }
|
||||
return send(res, 200, { seq: p.sv.seq, at: p.sv.at, data });
|
||||
}
|
||||
if (M !== 'PUT') fail(405, 'method not allowed');
|
||||
const p = authed(me), key = code + '.' + p.pid;
|
||||
const free = upTake(key, ip);
|
||||
try {
|
||||
if (!saveRate.ok(key, t)) fail(429, 'too many saves: slow down');
|
||||
const body = await readJson(req, LIMIT.save, o.saveMs || SAVE_MS);
|
||||
if (!still(s, p)) fail(401, 'unauthorized');
|
||||
const seq = body.seq, data = body.data;
|
||||
if (!Number.isSafeInteger(seq) || seq < 1) fail(400, 'seq must be a positive integer');
|
||||
if (typeof data !== 'string' || !data.length) fail(400, 'no save data');
|
||||
if (data.length > MAX_SAVE) fail(413, 'save too large');
|
||||
if (!(data.startsWith('gz:') || data.startsWith('{'))) fail(400, 'not a save');
|
||||
const card = body.card === undefined ? undefined : cleanCard(body.card);
|
||||
if (card === null) fail(400, 'bad card');
|
||||
const old = p.sv;
|
||||
// Another device of the same player saved a newer game: never overwrite it unless the player says so.
|
||||
if (old && seq <= old.seq && body.force !== true) fail(409, 'a newer save is on the server', { seq: old.seq, at: old.at });
|
||||
const at = num(body.at, 0, 1e15, t), sq = old && seq <= old.seq ? old.seq + 1 : seq;
|
||||
// The session says it has this save only once the save is on disk.
|
||||
await queue(code, () => writeAtomic(saveFile(code, p.pid), data));
|
||||
if (!still(s, p)) fail(401, 'unauthorized');
|
||||
p.sv = { seq: sq, at, size: data.length };
|
||||
if (card) applyCard(s, p, card);
|
||||
await persist(s);
|
||||
return send(res, 200, { ok: true, seq: sq, at, roster: roster(s) });
|
||||
} finally { free(); }
|
||||
}
|
||||
if (sub === '/feed') {
|
||||
if (M !== 'POST') fail(405, 'method not allowed');
|
||||
const p = authed(me), body = await readJson(req, LIMIT.small);
|
||||
if (!still(s, p)) fail(401, 'unauthorized');
|
||||
const text = cleanChat(body.text);
|
||||
if (!text) fail(400, 'say something');
|
||||
if (!chatGap.ok(code + p.pid, t) || !chatRate.ok(code + p.pid, t)) fail(429, 'slow down a little');
|
||||
event(s, 'chat', p, { text });
|
||||
await persist(s);
|
||||
return send(res, 200, roster(s));
|
||||
}
|
||||
if (sub === '/me') {
|
||||
if (M !== 'DELETE') fail(405, 'method not allowed');
|
||||
const p = authed(me);
|
||||
s.players = s.players.filter((x) => x !== p);
|
||||
await queue(code, () => fs.promises.rm(saveFile(code, p.pid), { force: true }));
|
||||
if (!s.players.length) { s.dead = true; await queue(code, async () => drop(code)); return send(res, 200, { ok: true }); }
|
||||
event(s, 'leave', p);
|
||||
await persist(s);
|
||||
return send(res, 200, { ok: true });
|
||||
}
|
||||
fail(404, 'not found');
|
||||
}
|
||||
|
||||
function handle(req, res) {
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://x'); } catch (e) { return false; }
|
||||
if (url.pathname !== base && !url.pathname.startsWith(base + '/')) return false;
|
||||
const t0 = Date.now();
|
||||
res.on('finish', () => { if (o.verbose) log(`${new Date().toISOString()} ${ipOf(req)} ${req.method} ${url.pathname} ${res.statusCode} ${Date.now() - t0}ms`); });
|
||||
route(req, res, url).catch((e) => {
|
||||
// A body nobody read (refused before it was needed) is drained, so the client still gets its answer.
|
||||
if (!req.complete && !req.destroyed) req.resume();
|
||||
if (e instanceof HttpError) return send(res, e.status, { error: e.message, ...(e.extra || {}) });
|
||||
log(`[mp] ${req.method} ${url.pathname}: ${e && e.stack || e}`);
|
||||
send(res, 500, { error: 'server error' });
|
||||
});
|
||||
return true;
|
||||
}
|
||||
// Everything written before the process goes, sessions waiting for their moment too.
|
||||
const flush = () => { for (const code of [...soon.keys()]) { const s = cache.get(code); if (s) persist(s); else { clearTimeout(soon.get(code)); soon.delete(code); } } return Promise.all([...chains.values()]); };
|
||||
return { handle, prune, flush, dir, base, sessions: () => codes.size, uploads: () => up.size };
|
||||
}
|
||||
|
||||
module.exports = { createMp, cleanCard, cleanText, normCode, showCode, addrKey, limiter, CODE_RE, PRESETS, MAX_SAVE };
|
||||
|
|
@ -3,8 +3,19 @@
|
|||
// The result is the same single, self-contained index.html the game has always shipped: one request,
|
||||
// no module loader, no runtime cost. See docs/ARCHITECTURE.md ("Source layout") and docs/adr/.
|
||||
//
|
||||
// A line `<!-- @include-dev DIR -->` is the same, but only in the development page (dev: true): the
|
||||
// tools' side of the game (src/agent/, the agent facade the MCP server drives) for npm run dev, the
|
||||
// MCP server's own page and the tests that ask for it. Everywhere else the line is dropped whole, so
|
||||
// the page players get is exactly what it would be without it (docs/adr/0004-dev-only-code.md).
|
||||
//
|
||||
// The server-run play of a multiplayer build (src/game/98-server-play/ and src/styles/43-server-play.css) is only in a
|
||||
// page assembled with mp: true, which MP_API=… npm run build asks for; every other page, the one players get on
|
||||
// GitHub Pages included, has none of it.
|
||||
//
|
||||
// node scripts/lib/page.js [-o FILE] the page as it ships (stdout by default)
|
||||
// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests and npm run dev use)
|
||||
// node scripts/lib/page.js --source [-o FILE] assembled only, labels as in src/ (what tests use)
|
||||
// node scripts/lib/page.js --source --dev [-o FILE] the development page: with src/agent/ (what npm run dev serves)
|
||||
// node scripts/lib/page.js --mp [--source] [-o FILE] a multiplayer build's page: with the server-play client
|
||||
// node scripts/lib/page.js --ref origin/main -o FILE the page as it ships at a git ref
|
||||
//
|
||||
// --ref uses that commit's own assembler, so it keeps working when this file changes; refs from before
|
||||
|
|
@ -15,7 +26,10 @@ const path = require('node:path');
|
|||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
const ROOT = path.join(__dirname, '..', '..');
|
||||
const INCLUDE = /^<!-- @include ([\w./-]+) -->$/;
|
||||
const INCLUDE = /^<!-- @include(-dev)? ([\w./-]+) -->$/;
|
||||
// Parts of src/ only a multiplayer build's page has (paths as the line map names them; a trailing / is a folder).
|
||||
const MP_ONLY = ['game/98-server-play/', 'styles/43-server-play.css'];
|
||||
const mpOnly = (f) => MP_ONLY.some((p) => (p.endsWith('/') ? f.startsWith(p) : f === p));
|
||||
|
||||
// Every file under dir, as paths relative to dir with '/' separators, in a stable order
|
||||
// (plain code-unit comparison, so the order never depends on the machine's locale).
|
||||
|
|
@ -30,11 +44,11 @@ function listFiles(dir, rel = '') {
|
|||
return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
||||
}
|
||||
|
||||
// The partials that make up one include, in order: [{file, text}].
|
||||
function partials(src, dir) {
|
||||
// The partials that make up one include, in order: [{file, text}]. Without mp, the multiplayer-only ones are left out.
|
||||
function partials(src, dir, mp = true) {
|
||||
const base = path.join(src, dir);
|
||||
if (!fs.existsSync(base)) throw new Error(`@include ${dir}: no such directory under ${path.relative(ROOT, src) || '.'}`);
|
||||
return listFiles(base).map((r) => {
|
||||
return listFiles(base).filter((r) => mp || !mpOnly(dir + '/' + r)).map((r) => {
|
||||
const file = path.join(base, r);
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
if (text.includes('\r')) throw new Error(`${path.relative(ROOT, file)}: use LF line endings`);
|
||||
|
|
@ -45,7 +59,9 @@ function partials(src, dir) {
|
|||
}
|
||||
|
||||
// The assembled page as a string, plus a map of which output line came from which source file.
|
||||
function assemble({ src = path.join(ROOT, 'src') } = {}) {
|
||||
// dev: also the @include-dev parts (the development page); without it, their lines are left out entirely.
|
||||
// mp: also the multiplayer-only parts (MP_ONLY); without it, those files are left out entirely.
|
||||
function assemble({ src = path.join(ROOT, 'src'), dev = false, mp = false } = {}) {
|
||||
const shell = fs.readFileSync(path.join(src, 'index.html'), 'utf8');
|
||||
const out = [], map = [];
|
||||
let line = 1;
|
||||
|
|
@ -57,7 +73,8 @@ function assemble({ src = path.join(ROOT, 'src') } = {}) {
|
|||
line++;
|
||||
return;
|
||||
}
|
||||
for (const p of partials(src, m[1])) {
|
||||
if (m[1] && !dev) return;
|
||||
for (const p of partials(src, m[2], mp)) {
|
||||
const n = p.text.split('\n').length - 1;
|
||||
map.push({ file: p.file, from: line, to: line + n - 1 });
|
||||
out.push(p.text);
|
||||
|
|
@ -87,10 +104,17 @@ function assembleRef(ref, cwd = ROOT) {
|
|||
}
|
||||
|
||||
// The page as it ships: assembled, with labels shrunk to short ids (compile-labels.js). Not version-stamped.
|
||||
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids.
|
||||
function shipped(dicts = {}) {
|
||||
// `dicts` ({lang: label-keyed dictionary}) come back with the same ids. mp: a multiplayer build's page.
|
||||
function shipped(dicts = {}, { mp = false } = {}) {
|
||||
const D = require('./dict');
|
||||
return require('./compile-labels').compile(assemble().html, D.read('en').dict, dicts);
|
||||
return require('./compile-labels').compile(assemble({ mp }).html, D.read('en').dict, dicts);
|
||||
}
|
||||
|
||||
/* The build id of server-run play (SIM_ID): the first 12 hex digits of sha256 of the multiplayer page as assembled from
|
||||
src/, labels as written (game and server-play client together, so a change to either is a new id). The build stamps
|
||||
it into MP pages and version.json; the session server works it out from its own src/ and refuses pages of another. */
|
||||
function simId(html = assemble({ mp: true }).html) {
|
||||
return require('node:crypto').createHash('sha256').update(html).digest('hex').slice(0, 12);
|
||||
}
|
||||
|
||||
// The shipped page written to a file, for tools that need a path (perf in a real browser, base vs head).
|
||||
|
|
@ -99,12 +123,13 @@ function pageFile(file = path.join(os.tmpdir(), `tubes-page-${process.pid}.html`
|
|||
return file;
|
||||
}
|
||||
|
||||
module.exports = { assemble, assembleRef, shipped, pageFile, locate, listFiles, ROOT };
|
||||
module.exports = { assemble, assembleRef, shipped, simId, pageFile, locate, listFiles, MP_ONLY, ROOT };
|
||||
|
||||
if (require.main === module) {
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : null; };
|
||||
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble().html : shipped().html;
|
||||
const mp = args.includes('--mp');
|
||||
const html = opt('--ref') ? assembleRef(opt('--ref')) : args.includes('--source') ? assemble({ dev: args.includes('--dev'), mp }).html : shipped({}, { mp }).html;
|
||||
const out = opt('-o');
|
||||
if (out) { fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true }); fs.writeFileSync(out, html); }
|
||||
else process.stdout.write(html);
|
||||
|
|
|
|||
89
scripts/lib/puzzle-solver.js
Normal file
89
scripts/lib/puzzle-solver.js
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
// Puzzle tools (the weekly generator, the puzzle tests): build a puzzle network straight into a headless game, judge
|
||||
// it with the game's own star code, and search for the cheapest build that earns three stars.
|
||||
//
|
||||
// A build is a list of links [a, b, via, tier, same]: via is 'land' or a cable id, tier an index into LT, and `same`
|
||||
// (k > 0) puts an overland link in the k-th trench already on that pair (otherwise a further one takes a diverse
|
||||
// route, +40%). Routers
|
||||
// are not part of the search: each POP gets the cheapest models that carry its busiest moment (across every single
|
||||
// cut), its ports and its biggest wave, which is what any sensible player would buy for that build.
|
||||
|
||||
// Runs inside the page.
|
||||
function page() {
|
||||
window.pzsReset = () => { S.pops = {}; S.links = []; S.pairMet = {}; for (const b of S.biz) b.route = 'normal'; UI.pzEv = null; };
|
||||
window.pzsLink = (a, b, via, tier, same) => {
|
||||
const r = pzRoutes(a, b).find((x) => x.via === via); if (!r) throw new Error(`no route ${via} for ${a}-${b}`);
|
||||
for (const c of [a, b]) if (!S.pops[c]) S.pops[c] = pzNewPop(c);
|
||||
// `same` k > 0: in the k-th overland trench on this pair; 0: a trench of its own (diverse, unless it is the first).
|
||||
const tr = !r.sub ? [...new Set(S.links.filter((l) => edgeKey(l) === edgeKey({ a, b }) && !l.cable).map((l) => l.trench))] : [], sm = same && tr[same - 1], div = !!(tr.length && sm !== tr[0]), id = uid();
|
||||
S.links.push({ id, a, b, kind: 'wave', border: false, premium: false, tier, km: r.km, sub: r.sub, cable: r.cab, mo: pzMo(r, tier, div), mult: r.f * (div ? DIVERSE : 1), trench: r.cab ? 'cab:' + r.cab : sm || id, cut: 0, day: 0 });
|
||||
};
|
||||
// The cheapest routers for POP c: enough ports, a model that lights its biggest wave, and capacity for its peak.
|
||||
window.pzsRouters = (c, peak) => {
|
||||
const used = portsUsed(c), lt = Math.max(0, ...S.links.filter((l) => l.a === c || l.b === c).map((l) => l.tier)); let best = null;
|
||||
for (const g of PZ_RG) for (let rt = 1; rt <= 6; rt++) { const M = RG[g]; if (M.maxLT < lt || M.ports * rt < used - 1e-9 || M.cap * rt < peak - 1e-6) continue;
|
||||
const cost = pzRtCost(g, rt); if (!best || cost < best.cost) best = { g, rt, cost }; }
|
||||
return best;
|
||||
};
|
||||
// Judge the build on routers big enough for anything, then price the routers it really needs. With those, routing
|
||||
// is the same (no router is ever full), so the stars are too.
|
||||
window.pzsJudge = () => {
|
||||
const BIG = RG.findIndex((r) => r.n === 'Arrrhipster 7800R'), keep = {};
|
||||
for (const c in S.pops) { keep[c] = [S.pops[c].rgen, S.pops[c].routers]; S.pops[c].rgen = BIG; S.pops[c].routers = 1; }
|
||||
UI.pzEv = null; const b0 = S.pz.budget; S.pz.budget = 0; const e = pzEval(); S.pz.budget = b0; UI.pzEv = null;
|
||||
const rt = {}; let spend = 0, bad = false;
|
||||
for (const c in S.pops) { const r = pzsRouters(c, e.peak[c] || 0); if (!r) { bad = true; continue; } rt[c] = [r.g, r.rt]; spend += r.cost + pzPopCost(c); S.pops[c].rgen = keep[c][0]; S.pops[c].routers = keep[c][1]; }
|
||||
for (const l of S.links) spend += l.mo * PZ_YEAR;
|
||||
return { one: e.goal && !bad, three: e.goal && e.n1 && !bad, spend, rt };
|
||||
};
|
||||
window.pzsApplyRt = (rt) => { for (const c in rt) { S.pops[c].rgen = rt[c][0]; S.pops[c].routers = rt[c][1]; } UI.pzEv = null; };
|
||||
}
|
||||
const install = (ev) => { if (ev("typeof pzsJudge!=='function'")) ev(`(${page.toString()})()`); };
|
||||
|
||||
const key = (L) => JSON.stringify(L);
|
||||
// Steps that are not links set what a player sets in the panels: ['@route', flow, 'fast'] a circuit's path,
|
||||
// ['@met', a, b, 'avoid'] a pair's metric. The search keeps them as they are.
|
||||
const step = ([a, b, v, t, s]) => a === '@route' ? `S.biz.find(x=>x.id===pzFlowId(${b})).route='${v}';` : a === '@met' ? `(S.pairMet=S.pairMet||{})[edgeKey({a:'${b}',b:'${v}'})]='${t}';`
|
||||
: `pzsLink('${a}','${b}','${v}',${t},${s || 0});`;
|
||||
function judge(ev, L) {
|
||||
return JSON.parse(ev(`pzsReset();${L.map(step).join('')}JSON.stringify(pzsJudge())`));
|
||||
}
|
||||
// Every link option between the given cities: each route, at tiers up to maxTier.
|
||||
function options(ev, cities, maxTier, noSub) {
|
||||
const out = [];
|
||||
for (let i = 0; i < cities.length; i++) for (let j = i + 1; j < cities.length; j++) {
|
||||
const [a, b] = [cities[i], cities[j]];
|
||||
const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>({via:r.via,sub:r.sub,ok:[0,1,2,3].map(t=>!subWaveWhy(t,r.km,r.sub))})))`));
|
||||
for (const r of rs) { if (noSub && r.sub) continue; for (let t = 0; t <= maxTier; t++) if (r.ok[t]) { out.push([a, b, r.via, t, 0]); if (!r.sub) { out.push([a, b, r.via, t, 1]); out.push([a, b, r.via, t, 2]); } } }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Local search from a 3-star build: drop a link, shrink one, move one to another route, put it in the first trench
|
||||
// or out of it, or swap one link for another option, while it is cheaper and still three stars.
|
||||
function improve(ev, start, opts = {}) {
|
||||
const memo = new Map(), J = (L) => { const k = key(L); if (!memo.has(k)) memo.set(k, judge(ev, L)); return memo.get(k); };
|
||||
let cur = start.map((x) => x.slice()), cj = J(cur);
|
||||
if (!cj.three) throw new Error('the starting build does not earn three stars');
|
||||
const routes = {}, via = (a, b) => { const k = a < b ? a + '|' + b : b + '|' + a; if (!routes[k]) routes[k] = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').map(r=>r.via))`)); return routes[k]; };
|
||||
const opt = opts.options || [];
|
||||
for (let round = 0; round < 60; round++) {
|
||||
const nb = [];
|
||||
for (let i = 0; i < cur.length; i++) {
|
||||
const w = (x) => { const L = cur.slice(); L[i] = x; return L; }, [a, b, v, t, s] = cur[i];
|
||||
if (a[0] === '@') continue;
|
||||
nb.push(cur.filter((_, k) => k !== i));
|
||||
if (t > 0) nb.push(w([a, b, v, t - 1, s]));
|
||||
for (const v2 of via(a, b)) if (v2 !== v) nb.push(w([a, b, v2, t, 0]));
|
||||
if (v === 'land') for (const s2 of [0, 1, 2]) if (s2 !== (s || 0)) nb.push(w([a, b, v, t, s2]));
|
||||
}
|
||||
if (opts.swap) for (const o of opt) for (let i = 0; i < cur.length; i++) { if (cur[i][0][0] === '@') continue; const L = cur.slice(); L[i] = o; nb.push(L); }
|
||||
let best = null;
|
||||
for (const L of nb) { const j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; }
|
||||
if (!best && opts.add) for (const o of opt) for (let i = 0; i < cur.length; i++) for (let k = i + 1; k < cur.length; k++) {
|
||||
if (cur[i][0][0] === '@' || cur[k][0][0] === '@') continue;
|
||||
const L = [...cur.filter((_, x) => x !== i && x !== k), o], j = J(L); if (j.three && j.spend < cj.spend - 1 && (!best || j.spend < best.j.spend)) best = { L, j }; }
|
||||
if (!best) break;
|
||||
cur = best.L; cj = best.j;
|
||||
}
|
||||
return { links: cur, ...cj };
|
||||
}
|
||||
module.exports = { install, judge, options, improve };
|
||||
72
scripts/lib/relay-client.js
Normal file
72
scripts/lib/relay-client.js
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
// The tool side of the agent relay (scripts/agent/relay.js), for the MCP server's browser session
|
||||
// (scripts/lib/mcp-browser.js). The game runs in the player's browser, never in this process, connected to the relay
|
||||
// from Settings. The relay rides the server that serves the page, same port, path /agent (npm run dev, 8080 unless
|
||||
// told otherwise), so host and port say where the page is served, nothing else. A call travels
|
||||
// tool → relay → page → TUBES.call and back.
|
||||
const WebSocket = require('ws');
|
||||
|
||||
// A healthy page answers in milliseconds, and a page that goes away has its calls answered at once (by the relay, or
|
||||
// by the close handler below), so this only catches a page that hangs. Days the player watches take longer: a call
|
||||
// can ask for more time of its own.
|
||||
const CALL_MS = 30000;
|
||||
|
||||
function createRelaySession(opts = {}) {
|
||||
const cfg = {
|
||||
host: typeof opts.host === 'string' && opts.host ? opts.host : '127.0.0.1',
|
||||
port: +opts.port || 8080, // the port the game page is served on: the relay rides it
|
||||
callMs: +opts.callMs > 0 ? +opts.callMs : CALL_MS,
|
||||
};
|
||||
const url = `ws://${cfg.host.includes(':') && !cfg.host.startsWith('[') ? `[${cfg.host}]` : cfg.host}:${cfg.port}/agent`;
|
||||
|
||||
let ws = null, connecting = null, id = 0, page = false;
|
||||
const pending = new Map();
|
||||
|
||||
function connect() {
|
||||
if (ws && ws.readyState === 1) return Promise.resolve();
|
||||
if (connecting) return connecting;
|
||||
connecting = new Promise((res, rej) => {
|
||||
const w = new WebSocket(url);
|
||||
let done = false;
|
||||
const finish = (e) => { if (done) return; done = true; connecting = null; e ? rej(e) : res(); };
|
||||
w.on('open', () => { w.send(JSON.stringify({ kind: 'auth', role: 'tool' })); finish(); });
|
||||
w.on('error', (e) => finish(new Error(`relay ${url}: ${e.message}`)));
|
||||
w.on('close', () => {
|
||||
if (ws === w) { ws = null; page = false; }
|
||||
// The socket died with calls in flight: answer them here too, so no tool waits out its timeout on a
|
||||
// connection that is already gone (the relay answers for a dead page).
|
||||
for (const [k, p] of [...pending]) { pending.delete(k); clearTimeout(p.t); p.res({ error: `relay ${url}: connection closed before the game page answered` }); }
|
||||
if (!done) finish(new Error(`relay ${url}: connection closed`));
|
||||
});
|
||||
w.on('message', (d) => {
|
||||
let m; try { m = JSON.parse(String(d)); } catch { return; }
|
||||
if (!m || typeof m !== 'object') return;
|
||||
if (m.kind === 'presence') { page = !!m.page; return; }
|
||||
if (m.kind === 'result' && m.id !== undefined) { const p = pending.get(m.id); if (p) { pending.delete(m.id); clearTimeout(p.t); p.res(m); } }
|
||||
});
|
||||
ws = w;
|
||||
});
|
||||
return connecting;
|
||||
}
|
||||
|
||||
// One call: {refused} when it could not be answered (no relay, no page, a timeout) or the page's tool threw,
|
||||
// else {value}. dayBefore/dayAfter: the game day the page saw around it.
|
||||
async function call(tool, args = {}, o = {}) {
|
||||
try { await connect(); } catch (e) { return { refused: e.message, value: null }; }
|
||||
const k = 't' + (++id), ms = +o.ms > 0 ? +o.ms : cfg.callMs;
|
||||
const m = await new Promise((res) => {
|
||||
const t = setTimeout(() => { pending.delete(k); res({ error: `no answer from the game page in ${ms / 1000} s (is the tab stuck?)` }); }, ms);
|
||||
pending.set(k, { res, t });
|
||||
ws.send(JSON.stringify({ kind: 'call', id: k, tool, args }));
|
||||
});
|
||||
if (m.error) return { refused: m.error, value: null, dayBefore: m.dayBefore, dayAfter: m.dayAfter };
|
||||
return { refused: null, value: m.value === undefined ? null : m.value, dayBefore: m.dayBefore, dayAfter: m.dayAfter };
|
||||
}
|
||||
|
||||
return {
|
||||
config: cfg, url, call, connect,
|
||||
get page() { return page; },
|
||||
async close() { try { ws && ws.close(1000); } catch {} },
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { createRelaySession, CALL_MS };
|
||||
217
scripts/lib/route-fuzz.js
Normal file
217
scripts/lib/route-fuzz.js
Normal file
|
|
@ -0,0 +1,217 @@
|
|||
// Differential games (scripts/route-fuzz.js, tests/route-fuzz.test.js): two game pages in one process, a base page
|
||||
// (main's) and this checkout's, play the same seeded game move for move. After every move and every day both must
|
||||
// have routed identically (all of R, R.fl, R.ef, the PNI lists), and this checkout must route the same with the
|
||||
// routing cache (RC) on and off. The whole game state S must match too, so the two games stay in lockstep.
|
||||
// Every move is picked here, from what the base page offers right now, with the game's seed: the seed alone
|
||||
// replays a game.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { load } = require('../../tests/harness');
|
||||
|
||||
const FUZZ_JS = fs.readFileSync(path.join(__dirname, 'fuzz-page.js'), 'utf8');
|
||||
|
||||
function openPage(file, label) {
|
||||
const g = load({ seed: 1, file });
|
||||
g.ev(FUZZ_JS);
|
||||
g.label = label;
|
||||
g.call = (fn, ...args) => {
|
||||
g.dom.window.__fzA = JSON.parse(JSON.stringify(args));
|
||||
const out = g.ev(`JSON.stringify(__fz.${fn}(...window.__fzA))`);
|
||||
return out === undefined ? undefined : JSON.parse(out);
|
||||
};
|
||||
return g;
|
||||
}
|
||||
|
||||
// mulberry32: the driver's own numbers, apart from the pages' Math.random.
|
||||
function rng(seed) {
|
||||
let a = seed >>> 0;
|
||||
const f = () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
|
||||
f.int = (n) => Math.floor(f() * n);
|
||||
f.pick = (a) => a[f.int(a.length)];
|
||||
// A button by its action's weight (w), then any button of that action: 38 transit sellers count as one choice.
|
||||
f.wp = (a, w) => { const g = new Map(); for (const x of a) { const l = g.get(x.act); if (l) l.push(x); else g.set(x.act, [x]); }
|
||||
const ks = [...g.keys()]; let s = 0; for (const k of ks) s += w(g.get(k)[0]); let t = f() * s;
|
||||
for (const k of ks) { t -= w(g.get(k)[0]); if (t < 0) return f.pick(g.get(k)); } return f.pick(g.get(ks[ks.length - 1])); };
|
||||
f.w = (o) => { let s = 0; for (const k in o) s += o[k]; let x = f() * s; for (const k in o) { x -= o[k]; if (x < 0) return k; } return Object.keys(o)[0]; };
|
||||
return f;
|
||||
}
|
||||
|
||||
// The first key of two {key: json} maps that differs, with a short look at where.
|
||||
function firstDiff(A, B) {
|
||||
const keys = [...new Set([...Object.keys(A), ...Object.keys(B)])];
|
||||
const out = [];
|
||||
for (const k of keys) {
|
||||
if (A[k] === B[k]) continue;
|
||||
const a = A[k] || '', b = B[k] || '';
|
||||
let i = 0; while (i < a.length && a[i] === b[i]) i++;
|
||||
out.push({ key: k, at: i, base: a.slice(Math.max(0, i - 80), i + 120), head: b.slice(Math.max(0, i - 80), i + 120) });
|
||||
if (out.length >= 4) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const DTABS = ['overview', 'cust', 'conn', 'traffic', 'infra', 'lease'];
|
||||
const TABS = ['cust', 'up', 'peer', 'links'];
|
||||
const LEFT = ['nets', 'noc', 'deals', 'goals'];
|
||||
const PRESETS = ['freeze', 'oncall', 'bgp'];
|
||||
// How often a button is pressed against the others on screen: what changes the network often, looking around rarely.
|
||||
const BUILD = /^(buy\w*|pni\w*All|pni|peer|peerAll|unpeer|cache|cacheSite|rmCache|buildLink|buildPop|launchBB|accept|decline|dropBiz|pathMove|pathPin|pathAuto|takeLoan|repayLoan|lag[TPI]x?|setPref|setCarry|setStandby|setMetric|togglePrem|cleanPipe|sacrif|rs|foundIx|myIxUp|addRouter|rmRouter|upRouter|addSite|rmSite|siteSet|decomToggle|rmLink|upLink|addParallel|cancel\w*|upVxc|buyNni|rmNni|buildScrub|scrubUp|rmScrub|addGen|regen|addCh|rmCh|addPair|upSys|spares|layShip|crews|fixInc|seaPackage|subUpgrade|orderCable|orderDf|ownCab|opsHire|opsToggle|opsParam|opsCap|opsPop|opsTpl|opsNewPop|popStdSet|coreSet|teRecipe|dkOptOut|dkStay|utility\w*|listFiber|unlistFiber|leaseSwap|custGo|confGo|confSponsor|seatBuy|charter|cnPrem|applyCn|ad|ddosAuto|pz(Pop|RmPop|Link|AddPar|Tier|RmLink|RtAdd|RtRm|RtModel|Route|Via|Div)|setRoute|route|via|metricSet)$/;
|
||||
const UIACT = /^(tab|dashTab|leftTab|\w*Sort|\w*Filter|pniGrp|trace\w*|focusCity|findGo|selLink|dashLink|logAll|tailTog|listMore|netFocus|netFilter|meetGo|phoneTab|dashClose|connF|connCity|connNet|connFor|custF|custCity|popGo|popsReg|opsOpen|decomOpen|linkCheck|pathOpen)$/;
|
||||
const DW = { launchBB: 4, accept: 4, buyTransit: 3, pni: 3, buyIx: 3, setPref: 4, cache: 2, peerAll: 2, setCarry: 2, takeLoan: 2 };
|
||||
const weight = (b) => (BUILD.test(b.act) ? 8 : UIACT.test(b.act) ? 0.3 : 1);
|
||||
|
||||
/* One game. pages: {base, head}. Returns {seed, start, moves, days, log, div} where div is the first divergence (or null).
|
||||
opts: moves (count, default 50 to 200 by seed), maxDays per day-move, onMove(i, move) */
|
||||
function playGame(pages, seed, opts = {}) {
|
||||
const { base, head } = pages;
|
||||
// A badge only this checkout has would unlock in its game alone, and an unlock writes a log line, which shifts every
|
||||
// id made after it: the comparison is about routing, so the new badges are taken off this checkout's page.
|
||||
if (!pages.badges && base !== head) {
|
||||
const ids = base.ev('JSON.stringify(BADGES.map((b)=>b.id))');
|
||||
head.ev(`{const keep=new Set(${ids});for(let i=BADGES.length-1;i>=0;i--)if(!keep.has(BADGES[i].id))BADGES.splice(i,1);}`);
|
||||
pages.badges = true;
|
||||
}
|
||||
const r = rng(seed * 2654435761);
|
||||
const both = (fn, ...a) => [base.call(fn, ...a), head.call(fn, ...a)];
|
||||
const L = base.call('lists');
|
||||
const log = [], acts = {};
|
||||
let div = null, days = 0;
|
||||
const note = (m) => { log.push(m); };
|
||||
const fail = (where, info) => { if (!div) div = { seed, where, move: log.length, last: log.slice(-6), ...info }; };
|
||||
const same = (where, a, b) => { if (JSON.stringify(a) !== JSON.stringify(b)) fail(where, { base: a, head: b }); };
|
||||
|
||||
// Compare everything: routing on both pages (a: the move's, b: again, c: cache off) and the game state.
|
||||
const compare = (where) => {
|
||||
const [x, y] = both('check');
|
||||
for (const k of ['a', 'b', 'c']) if (x[k] !== y[k]) { fail(where + ': routing (' + k + ') base vs head', { diff: firstDiff(base.call('parts'), head.call('parts')) }); return false; }
|
||||
if (y.b !== y.c) { fail(where + ': head cached vs uncached', { diff: 'R from the kept tables differs from a fresh route' }); return false; }
|
||||
// Fields only this checkout's game has are left out on both sides (see sKeys in fuzz-page.js), and so is the state of a
|
||||
// standing order only one of them has (one this checkout retired, or added).
|
||||
const [k1, k2] = both('sKeys'), drop = { top: k2.top.filter((k) => !k1.top.includes(k)), items: k2.items.filter((k) => !k1.items.includes(k)),
|
||||
ops: [...k1.ops.filter((k) => !k2.ops.includes(k)), ...k2.ops.filter((k) => !k1.ops.includes(k))] };
|
||||
// Both states as this checkout's reload makes them (see sLive in fuzz-page.js).
|
||||
const [j1, j2] = both('sLive'), s1 = head.call('sDigest', drop, j1), s2 = head.call('sDigest', drop, j2);
|
||||
if (s1 !== s2) { fail(where + ': game state S', { diff: firstDiff(head.call('sParts', drop, j1), head.call('sParts', drop, j2)) }); return false; }
|
||||
return true;
|
||||
};
|
||||
|
||||
// The start.
|
||||
const kind = opts.save ? 'save' : r.w({ normal: 44, sandbox: 14, scenario: 20, weekly: 3, puzzle: 11, architect: 8 });
|
||||
if (opts.save) for (const p of [base, head]) p.dom.window.__fzSave = opts.save;
|
||||
const home = r() < 0.4 ? r.pick(L.special) : r.pick(L.homes);
|
||||
const st = { kind, seed: (seed % 2147483646) + 1, name: 'Fuzz ' + seed, city: home,
|
||||
preset: kind === 'sandbox' ? r.pick(['none', 'calm', 'normal', 'spicy']) : r.pick(PRESETS),
|
||||
id: kind === 'scenario' ? r.pick(L.scn) : kind === 'puzzle' ? r.pick(L.pz) : kind === 'architect' ? r.pick(L.ar) : undefined };
|
||||
const [s0, s1] = both('start', st);
|
||||
// A base without scarce IPv4 (#150) plays the classic game: both pages switch the rule off. Once it is on main, both play it.
|
||||
if (!base.call('acts').includes('ip4Buy')) both('noIp4');
|
||||
same('start', s0, s1);
|
||||
note('start ' + JSON.stringify(st));
|
||||
// A normal game signs its charter first: a popup on newer pages (which seeded pages skip), a card on older ones. Both
|
||||
// sign the classic one at once, so neither shows charter buttons the other has not, and the game plays as it did.
|
||||
if (kind === 'normal') { const [c0, c1] = both('press', { act: 'charter', args: { k: 'global' } }); same('charter', c0, c1); }
|
||||
if (!div) compare('start');
|
||||
|
||||
// A screen's buttons on both pages; the same list or a divergence.
|
||||
// Buttons for actions main's page does not have (a new feature's) are left out: the driver only presses what both have.
|
||||
// So are the switches and dials of a standing order this checkout retired (main's sheet still shows them), and a
|
||||
// dashboard tab main's page does not have yet.
|
||||
let baseActs = null, retired = null, baseTabs = null;
|
||||
const screen = (w) => { const [a0, b0] = both('screen', w); baseActs = baseActs || new Set(base.call('acts'));
|
||||
if (!retired) { const [o1, o2] = both('sKeys'); retired = new Set(o1.orders.filter((k) => !o2.orders.includes(k))); }
|
||||
const a = Array.isArray(a0) ? a0.filter((x) => !(/^ops/.test(x.act) && retired.has(x.args && x.args.k))) : a0;
|
||||
// Args only this checkout's buttons carry (the total or plan a window shows: pniAll's q, bstdApply's quote) are left
|
||||
// out as well: the driver presses the base's button, which both pages take as before.
|
||||
if (!baseTabs) baseTabs = new Set(JSON.parse(base.ev('JSON.stringify(DTABS)')));
|
||||
const b = Array.isArray(b0) ? b0.filter((x) => baseActs.has(x.act) && !(x.act === 'dashTab' && x.args && !baseTabs.has(x.args.k))).map((x, i) => { const y = Array.isArray(a) && a[i] && a[i].act === x.act ? a[i].args : null;
|
||||
return y && x.args && typeof x.args === 'object' && typeof y === 'object' ? { act: x.act, args: Object.fromEntries(Object.entries(x.args).filter(([k]) => k in y)) } : x; }) : b0;
|
||||
same('buttons of ' + JSON.stringify(w), a, b); return a || []; };
|
||||
const press = (b, where) => { acts[b.act] = (acts[b.act] || 0) + 1; const [e1, e2] = both('press', b); same('press ' + where, e1, e2); note(where + ' ' + b.act + JSON.stringify(b.args) + (e1 ? ' !' + e1 : '')); };
|
||||
// Answer whatever window opened, a few levels deep, then close it.
|
||||
const modal = (bias) => {
|
||||
for (let k = 0; k < 4 && !div; k++) {
|
||||
if (!base.call('modalOpen')) return;
|
||||
let bs = screen({ where: 'modal' });
|
||||
if (bias) { const pref = bs.filter((b) => bias.test(b.act)); if (pref.length && r() < 0.7) bs = pref; }
|
||||
const real = bs.filter((b) => !/^(closeModal|x)$/.test(b.act));
|
||||
if (!real.length || r() < 0.12) break;
|
||||
press(r.wp(real, weight), ' modal');
|
||||
if (!div) compare('modal button');
|
||||
}
|
||||
both('close');
|
||||
};
|
||||
|
||||
const N = opts.moves || 50 + (seed % 151);
|
||||
for (let i = 0; i < N && !div; i++) {
|
||||
const s = base.call('state');
|
||||
if (s.lost) { note('bankrupt'); break; }
|
||||
const mv = r.w(s.puzzle ? { city: 40, openLink: 30, link: 15, modal: 5 } : { city: 22, direct: 22, openLink: 13, link: 5, dash: 5, left: 3, poke: 8, day: s.clock ? 20 : 0, build: 4 });
|
||||
if (opts.onMove) opts.onMove(i, mv);
|
||||
if (mv === 'city' || mv === 'build') {
|
||||
const city = mv === 'build' || !s.pops.length || r() < 0.3 ? (s.near.length ? r.pick(s.near) : r.pick(L.homes)) : r.pick(s.pops);
|
||||
const tab = r.pick(TABS);
|
||||
let bs = screen({ where: 'city', city, tab });
|
||||
if (mv === 'build') { const p = bs.filter((b) => /^(buildPop|launchBB|opsNewPop|popStdSet)$/.test(b.act)); if (p.length) bs = p; }
|
||||
if (bs.length) press(r.wp(bs, weight), `city ${city}/${tab}`);
|
||||
if (!div) compare('city button');
|
||||
modal();
|
||||
} else if (mv === 'openLink') {
|
||||
if (!s.pops.length) continue;
|
||||
const a = r.pick(s.pops), b = r() < 0.75 && s.near.length ? r.pick(s.near) : r() < 0.5 && s.pops.length > 1 ? r.pick(s.pops) : r.pick(L.homes);
|
||||
const bs = screen({ where: 'openLink', a, b });
|
||||
note(`openLink ${a}-${b} (${bs.length})`);
|
||||
if (bs.length) {
|
||||
// Pick a route or a kind first sometimes (dark fiber, subsea seat, own cable...), then build.
|
||||
const opt = bs.filter((x) => !/^(buildLink|closeModal)$/.test(x.act));
|
||||
if (opt.length && r() < 0.4) { press(r.pick(opt), ' link option'); if (!div) compare('link option'); }
|
||||
modal(/^(buildLink|pzLink|seaPackage|layShip|buyVxc|dfSys|seaDesign)$/);
|
||||
} else both('close');
|
||||
if (!div) compare('openLink');
|
||||
} else if (mv === 'link') {
|
||||
if (!s.links.length) continue;
|
||||
const id = r.pick(s.links);
|
||||
const bs = screen({ where: 'link', id });
|
||||
if (bs.length) press(r.wp(bs, weight), 'link ' + id);
|
||||
if (!div) compare('link button');
|
||||
modal();
|
||||
} else if (mv === 'dash' || mv === 'left') {
|
||||
const w = mv === 'dash' ? { where: 'dash', tab: r.pick(DTABS) } : { where: 'left', tab: r.pick(LEFT) };
|
||||
const bs = screen(w);
|
||||
if (bs.length) press(r.wp(bs, weight), mv + ' ' + w.tab);
|
||||
both('close');
|
||||
if (!div) compare(mv + ' button');
|
||||
modal();
|
||||
} else if (mv === 'direct') {
|
||||
const [a, b] = both('direct');
|
||||
same('direct calls', a, b);
|
||||
if (a.length) press(r.wp(a, (x) => DW[x.act] || (/^(cancel|rm|drop|unpeer)/.test(x.act) ? 0.4 : 1)), 'direct');
|
||||
if (!div) compare('direct');
|
||||
modal();
|
||||
} else if (mv === 'modal') {
|
||||
modal();
|
||||
} else if (mv === 'poke') {
|
||||
const k = r.w({ te: 3, teOff: 1, core: 2, fail: 2, event: 3, cash: 3, lvl: 2, ev: 4 });
|
||||
let p;
|
||||
if (k === 'te') { const rules = []; for (let j = 0, n = 1 + r.int(4); j < n; j++) rules.push([r.int(7), r.int(1000), r.int(1000)]); p = [k, rules, r() < 0.85]; }
|
||||
else p = [k, k === 'cash' ? r.int(3e7) : r.int(1e6), r.int(9)];
|
||||
const [e1, e2] = both('poke', p);
|
||||
same('poke', e1, e2);
|
||||
note('poke ' + JSON.stringify(p));
|
||||
if (!div) compare('poke ' + k);
|
||||
} else if (mv === 'day') {
|
||||
const n = 1 + r.int(opts.maxDays || 12);
|
||||
note('days ' + n);
|
||||
for (let d = 0; d < n && !div; d++) {
|
||||
const [e1, e2] = both('day');
|
||||
same('day', e1, e2);
|
||||
days++;
|
||||
if (!div) compare('day ' + d);
|
||||
// A window that opened over the day (an offer, a loan, a crisis) gets an answer.
|
||||
if (!div && base.call('modalOpen')) modal();
|
||||
}
|
||||
}
|
||||
}
|
||||
return { seed, start: st, moves: log.length, days, log, div, acts, errors: [...base.errors, ...head.errors] };
|
||||
}
|
||||
|
||||
module.exports = { openPage, playGame, rng };
|
||||
54
scripts/lib/scenario-bot.js
Normal file
54
scripts/lib/scenario-bot.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
// The reference player for weekly scenarios (scripts/weekly-scenario.js). It plays inside the real game, headless,
|
||||
// through the game's own actions (ACT.*, openLinkModal + buildLink), as a careful human would: broadband, transit and
|
||||
// an exchange port at home on day 0, a NOC intern on standing orders for transit and routers, then the generator's
|
||||
// plan one step at a time whenever the bank allows it, upgrading any wave that runs hot. It never reads the goal, so the
|
||||
// same seed and plan always play the same game, and the generator can calibrate a goal from what it reached.
|
||||
const { lit } = require('./js-literal');
|
||||
const BOT = String.raw`(()=>{
|
||||
const B=window.__wsBot={};
|
||||
const cheapNet=(c,avoid)=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!avoid.includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
|
||||
const reserve=()=>Math.max(60000,1.5*(R.costMo||0));
|
||||
const can=x=>S.cash>=x+reserve();
|
||||
const quiet=f=>{const t=window.toast;window.toast=()=>{};try{f();}finally{window.toast=t;}};
|
||||
function link(a,b,tier,via){UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.some(l=>(l.a===a&&l.b===b)||(l.a===b&&l.b===a));}
|
||||
function ix(c){if(!S.pops[c])return;for(const x of (B.plan&&B.plan.allIx?ixIdsIn(c):[c])){if(!ixName(x)||S.ixp[x]!==undefined)continue;ACT.buyIx({city:x,tier:1,signed:true});if(S.ixp[x]!==undefined&&!S.rs[x])ACT.rs({city:x});}}
|
||||
// Before a big event: transit enough for the event on top of the usual peak, and routers that can take it.
|
||||
function prep(E){const c=E.city,need=(S.stats.peak||R.served||0)*1.2+E.g*1.15;let cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0);
|
||||
for(let k=0;k<12&&cap()<need;k++){const t=S.transit.filter(t=>t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap();
|
||||
if(t.tier<PORT.length-1&&PORT[t.tier+1].g>=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1});if(cap()===c0)break;}
|
||||
for(let k=0;k<4;k++){const p=S.pops[c];if(!p||(p.routers||1)>=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}}
|
||||
B.start=(plan)=>{B.plan=plan;B.i=0;const c=S.scn.home||plan.home;quiet(()=>{
|
||||
ACT.launchBB({city:c});
|
||||
if(!scnRule('noTransit')){const n=cheapNet(c,plan.avoid||[]);if(n)ACT.buyTransit({city:c,net:n.id,tier:1});if(plan.tr2){const m=cheapNet(c,plan.avoid||[]);if(m)ACT.buyTransit({city:c,net:m.id,tier:1});}}
|
||||
ix(c);if(plan.scrub)ACT.buildScrub({city:c,tier:plan.scrub});});};
|
||||
B.day=()=>{const P=B.plan,d=S.day;if(!P)return;quiet(()=>{
|
||||
// A month in, with the first bills paid: the intern keeps transit and routers ahead of the traffic.
|
||||
if(d===30&&opsCanHire()&&!opsHired()&&rule('clock')){ACT.opsHire({id:'kevin'});closeModal();if(opsHired())for(const k of ['transit','routers','repair'])if(!S.ops.on[k])ACT.opsToggle({k});closeModal();}
|
||||
if(d%7===0)for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||(R.load[l.id]||0)<LT[l.tier].g*0.7)continue;const nm=Math.round(waveMo(l.km,l.sub,l.tier+1)*(l.mult||1));if(can(nm))ACT.upLink({id:l.id,tier:l.tier+1});}
|
||||
if(P.event&&d>=P.event.day-21&&d<P.event.day&&d%7===0)prep(P.event);
|
||||
const s=P.steps[B.i];if(!s)return;
|
||||
if(s.k==='hop'){const [a,b,t,via]=s.v;if(!S.pops[a])return;const est=(S.pops[b]?0:popCost(b))+waveMo(kmBetween(a,b),isSub(a,b),t)*2+(P.bb?bbCost(b):0);if(!can(est))return;
|
||||
// Big waves need big routers at both ends: the POP first, then the routers, then the wave.
|
||||
if(!waveOk(a,b,t)){if(!S.pops[b])ACT.buildPop({city:b});for(const c of [a,b])for(let k=0;k<4&&S.pops[c]&&!waveOk(a,b,t);k++){const g0=S.pops[c].rgen||0;ACT.upRouter({city:c});if((S.pops[c].rgen||0)===g0)break;}}
|
||||
if(!link(a,b,t,via)){B.i++;return;}if(P.bb&&!S.pops[b].bb)ACT.launchBB({city:b});if(P.ix)ix(b);B.i++;}
|
||||
else if(s.k==='ix'){if(can(30000)){ix(s.v);B.i++;}}
|
||||
else if(s.k==='tr'){if(can(40000)&&!scnRule('noTransit')){const n=cheapNet(s.v,P.avoid||[]);if(n)ACT.buyTransit({city:s.v,net:n.id,tier:1});B.i++;}}
|
||||
else B.i++;});};
|
||||
})()`;
|
||||
|
||||
const install = (ev) => { if (!ev('!!window.__wsBot')) ev(BOT); };
|
||||
|
||||
// Plays a weekly scenario file from day 0: the plan steps once a day, until the goal is met (when stop) or the days
|
||||
// run out. Returns the day the goal was first met (or null), what the goal measure read each day, and the end state.
|
||||
function play(ev, file, plan, { days, stop = true, measure = 'wsMeasure()' } = {}) {
|
||||
install(ev);
|
||||
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${lit(file)},'Ref');if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
|
||||
if (ev('!!(S.scn&&S.scn.wk)') !== true) throw new Error('the game would not start this scenario');
|
||||
ev(`__wsBot.start(${lit(plan)})`);
|
||||
const won0 = ev('wsOk()'), n = days || ev('S.scn.days');
|
||||
// Each day: the bot moves, the day ticks (scnTick records a win), and we note the measure.
|
||||
const out = JSON.parse(ev(`(()=>{const m=[];let won=null;for(let i=0;i<${n};i++){__wsBot.day();dayTick();closeModal();m.push(+(${measure}).toFixed(3));if(won===null&&S.scn.done)won=S.scn.done;if(won!==null&&${stop})break;if(S.lost)break;}return JSON.stringify({won,m,lost:!!S.lost,day:S.day,cash:Math.round(S.cash)});})()`));
|
||||
return { won0, ...out };
|
||||
}
|
||||
|
||||
module.exports = { BOT, install, play };
|
||||
77
scripts/lib/scenario-ref.js
Normal file
77
scripts/lib/scenario-ref.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// The reference player for the handmade scenarios (tests/scenarios-playtest.test.js), the sibling of scenario-bot.js
|
||||
// (which plays the weekly ones). It plays inside the real game, headless, through the game's own actions, one plan
|
||||
// step at a time whenever the bank allows it, plus the upkeep a careful human does every week: hot waves a size up, hot
|
||||
// transit and exchange ports a LAG member, new peers at every exchange, routers before they fill.
|
||||
//
|
||||
// A plan is a list of steps, each [op, ...args]:
|
||||
// ['bb', c] POP and broadband ['tr', c, tier] the cheapest transit there ['ix', c, tier] every exchange
|
||||
// ['pop', c] a POP only ['link', a, b, tier, cable] a wave (routers upgraded first, a swap a day)
|
||||
// ['hire', orders, params] the NOC intern on standing orders, as soon as the level allows ('sales': the CEO signs deals)
|
||||
// ['wait', day] until that day ['served', g] until g Gbps are served ['prep', c, g] capacity for an event
|
||||
// ['scrub', c, tier] a scrubbing center ['pnis'] a PNI with every unreached network that takes one
|
||||
// ['pni', c, net, tier] one PNI with that network there ['last', c] transit there only as a last resort
|
||||
// ['loans'] take every loan the banks offer, from now on (the cheese plans)
|
||||
const { lit } = require('./js-literal');
|
||||
const REF = String.raw`(()=>{
|
||||
const Q=window.__ref={log:[]};
|
||||
const quiet=f=>{const t=window.toast;window.toast=()=>{};try{return f();}finally{window.toast=t;}};
|
||||
Q.reserve=()=>Math.max(40000,1.3*(R.costMo||0));
|
||||
Q.can=x=>S.cash>=x+Q.reserve();
|
||||
Q.cheap=c=>NETS.filter(n=>n.price&&sellsAt(n,c)&&!(Q.avoid||[]).includes(n.id)&&!S.transit.some(t=>t.city===c&&t.net===n.id)).sort((a,b)=>a.price*netMult(a,c)-b.price*netMult(b,c))[0];
|
||||
Q.pop=c=>{if(!S.pops[c])ACT.buildPop({city:c});return !!S.pops[c];};
|
||||
Q.bb=c=>{Q.pop(c);if(S.pops[c]&&!S.pops[c].bb)ACT.launchBB({city:c});return !!(S.pops[c]&&S.pops[c].bb);};
|
||||
Q.tr=(c,tier=1)=>{Q.pop(c);const n=Q.cheap(c);if(!n)return true;ACT.buyTransit({city:c,net:n.id,tier});return true;};
|
||||
Q.last=c=>{for(const t of S.transit)if(t.city===c)ACT.setPref({kind:'t',id:t.id,v:'low'});return true;};
|
||||
Q.ix=(c,tier=1)=>{if(!S.pops[c])return false;for(const x of ixIdsIn(c)){if(!ixName(x))continue;if(S.ixp[x]===undefined)ACT.buyIx({city:x,tier,signed:true});if(S.ixp[x]===undefined)continue;if(!S.rs[x])ACT.rs({city:x});ACT.peerAll({city:x});}return true;};
|
||||
// A wave: big waves need big routers at both ends, and a router swap takes a day, so the step waits (null) until they fit.
|
||||
Q.link=(a,b,tier=1,via)=>{for(const c of [a,b])Q.pop(c);if(!S.pops[a]||!S.pops[b])return false;
|
||||
for(const c of [a,b])for(let k=0;k<4&&!waveOk(a,b,tier);k++){const g0=S.pops[c].rgen||0;ACT.upRouter({city:c});if((S.pops[c].rgen||0)===g0)break;}
|
||||
if(!waveOk(a,b,tier))return null;const n0=S.links.length;UI.via=via||null;UI.route=null;openLinkModal(a,b);ACT.buildLink({tier});closeModal();return S.links.length>n0;};
|
||||
Q.hire=(orders,par)=>{Q.wantHire=[orders||['transit','routers','repair'],par||{}];return true;};
|
||||
Q.hire0=(orders,par)=>{if(!opsCanHire()||!Q.can(20000))return false;if(!opsHired()){ACT.opsHire({id:'kevin'});closeModal();}if(!opsHired())return false;
|
||||
// Deals are the sales desk's: 'sales' puts the CEO there (free, and he signs what the old sales order signed) and lets him sign.
|
||||
for(const k of orders)if(k==='sales'){if(!slP()&&salesCanHire())ACT.salesHire({id:'ceo'});if(slP()&&!S.slAuto.on)ACT.salesAuto();}else if(!S.ops.on[k])ACT.opsToggle({k});for(const k in par)for(const [p,v] of Object.entries(par[k]))for(let i=0;i<8&&opsP(k,p)!==v;i++)ACT.opsParam({k,p});closeModal();return true;};
|
||||
Q.pnis=(tier=0)=>{for(const n of NETS.filter(n=>!R.reachable[n.id]).sort((a,b)=>NSH[b.id]-NSH[a.id])){const b=pniBatch(n.id,tier);if(!b||!b.orders.length||!Q.can(b.cost))continue;ACT.pniAll({net:n.id,tier});}return true;};
|
||||
Q.pni=(c,net,tier=0)=>{if(!S.pni.some(p=>p.city===c&&p.net===net))ACT.pni({city:c,net,tier});closeModal();return S.pni.some(p=>p.city===c&&p.net===net);};
|
||||
Q.scrub=(c,tier=0)=>{ACT.buildScrub({city:c,tier});return true;};
|
||||
Q.loans=()=>{Q.loan=true;return true;};
|
||||
Q.served=g=>R.served>=g||null;
|
||||
Q.wait=d=>S.day>=d||null;
|
||||
// Before an event: transit for the event on top of the usual peak, and routers that can take it.
|
||||
Q.prep=(c,g)=>{const need=(S.stats.peak||R.served||0)*1.2+g*1.15,cap=()=>S.transit.filter(t=>t.city===c).reduce((a,t)=>a+PORT[t.tier].g*(t.n||1),0);
|
||||
for(let k=0;k<12&&cap()<need;k++){const t=S.transit.filter(t=>t.city===c).sort((a,b)=>PORT[a.tier].g*(a.n||1)-PORT[b.tier].g*(b.n||1))[0];if(!t)break;const c0=cap();
|
||||
if(t.tier<PORT.length-1&&PORT[t.tier+1].g>=need/4&&portOk(c,t.tier+1))ACT.buyTransit({city:c,net:t.net,tier:t.tier+1});else ACT.lagT({id:t.id,d:1});
|
||||
if(cap()===c0){if(t.tier<PORT.length-1&&!portOk(c,t.tier+1))ACT.upRouter({city:c});else break;}}
|
||||
for(let k=0;k<4;k++){const p=S.pops[c];if(!p||(p.routers||1)>=RMAX)break;const r0=p.routers||1;ACT.addRouter({city:c});if((p.routers||1)===r0)break;}return true;};
|
||||
Q.est={pop:c=>S.pops[c]?0:popCost(c),bb:c=>(S.pops[c]?0:popCost(c))+bbCost(c),tr:()=>20000,pni:()=>20000,ix:()=>25000,hire:()=>0,scrub:(c,t)=>SCRUB_TIERS[t||0].cost,
|
||||
link:(a,b,t)=>(S.pops[a]?0:popCost(a))+(S.pops[b]?0:popCost(b))+waveMo(kmBetween(a,b),isSub(a,b),t)*2+20000};
|
||||
Q.upkeep=()=>{
|
||||
for(const l of S.links){if(l.kind!=='wave'||l.tier>=LT.length-1||linkDown(l)||(R.load[l.id]||0)<LT[l.tier].g*0.75)continue;
|
||||
if(!waveOk(l.a,l.b,l.tier+1))for(const c of [l.a,l.b])if(!waveOk(l.a,l.b,l.tier+1)&&Q.can(80000))ACT.upRouter({city:c});
|
||||
if(Q.can(Math.round(waveMo(l.km,l.sub,l.tier+1)*(l.mult||1))*2))ACT.upLink({id:l.id,tier:l.tier+1});}
|
||||
for(const x in S.ixp)if(!(S.myIx&&S.myIx[x]))ACT.peerAll({city:x});
|
||||
if(!(opsHired()&&S.ops.on.transit))for(const t of S.transit.slice()){const u=(R.useT&&R.useT[t.id])||0,cap=lagCap(PORT[t.tier].g,t.n);if(u<cap*0.75)continue;
|
||||
if((t.n||1)<2||t.tier>=PORT.length-1||!portOk(t.city,t.tier+1)){if(Q.can(PORT[t.tier].setup+20000))ACT.lagT({id:t.id,d:1});if(lagCap(PORT[t.tier].g,t.n)===cap&&Q.can(80000))ACT.upRouter({city:t.city});}
|
||||
else if(Q.can(PORT[t.tier+1].setup+30000))ACT.buyTransit({city:t.city,net:t.net,tier:t.tier+1});}
|
||||
for(const x in S.ixp){if(S.myIx&&S.myIx[x])continue;const u=(R.useIx&&R.useIx[x])||0;if(u>=lagCap(PORT[S.ixp[x]].g,(S.ixn||{})[x])*0.75&&Q.can(30000))ACT.lagIx({city:x,d:1});}
|
||||
if(!(opsHired()&&S.ops.on.routers))for(const c in S.pops){if((R.nodeLoad[c]||0)/(R.nodeCap[c]||nodeCap(c)||1)>0.8&&Q.can(80000)){if((S.pops[c].routers||1)<2)ACT.addRouter({city:c});else ACT.upRouter({city:c});}}};
|
||||
Q.step=()=>{for(let k=0;k<6;k++){const s=Q.steps[Q.i];if(!s)return;const [op,...a]=s;
|
||||
if(Q.est[op]&&!Q.can(Q.est[op](...a)))return;const ok=Q[op](...a);if(ok===null)return;Q.log.push(S.day+' '+op+' '+a.join(',')+(ok?'':' (failed)'));Q.i++;}};
|
||||
Q.day=()=>quiet(()=>{if(Q.wantHire&&Q.hire0(...Q.wantHire)){Q.log.push(S.day+' hired');Q.wantHire=null;}
|
||||
if(Q.loan)for(const o of (S.loanOffers||[]).slice())ACT.takeLoan({id:o.id});closeModal();
|
||||
Q.step();if(S.day%7===0)Q.upkeep();});
|
||||
Q.start=(steps,o={})=>quiet(()=>{Q.steps=steps;Q.i=0;Q.avoid=o.avoid||[];Q.step();});
|
||||
})()`;
|
||||
|
||||
// Starts scenario `id` (with `seed`, or its own), plays `plan` for up to `days` days (default: the scenario's), and
|
||||
// returns the day it was won (or null), whether the network went broke, and the end state.
|
||||
function play(ev, id, plan, { seed, days, avoid } = {}) {
|
||||
ev(`localStorage.removeItem('sot-scn');beginGame('Ref',SCN.find(x=>x.id==='${id}').city,{scn:SCN.find(x=>x.id==='${id}')${seed ? ',seed:' + seed : ''}});if(UI.pendGame)ACT.pitchSkip();UI.speed=0;closeModal()`);
|
||||
if (ev('typeof __ref') === 'undefined') ev(REF);
|
||||
ev(`__ref.start(${lit(plan)},${lit({ avoid })})`);
|
||||
const n = days || ev('S.scn.days');
|
||||
return JSON.parse(ev(`(()=>{let won=null;for(let i=0;i<${n};i++){__ref.day();dayTick();closeModal();if(S.scn.done){won=S.scn.done;break;}if(S.lost||S.scn.failed)break;}
|
||||
return JSON.stringify({won,lost:!!S.lost,day:S.day,limit:S.scn.days,cash:Math.round(S.cash),served:Math.round(R.served)});})()`));
|
||||
}
|
||||
|
||||
module.exports = { REF, play };
|
||||
18
scripts/lib/timings-reporter.js
Normal file
18
scripts/lib/timings-reporter.js
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
// A node:test reporter that writes how long each test file took, as JSON {"tests/x.test.js": seconds}, to its
|
||||
// destination. scripts/test.js adds it next to the usual output with --timings FILE; CI merges the parts' files
|
||||
// into tests/durations.json, which the next run splits its parts by.
|
||||
const path = require('node:path');
|
||||
|
||||
module.exports = async function* timings(source) {
|
||||
const sec = {};
|
||||
for await (const { type, data } of source) {
|
||||
// Top-level tests only: their durations include their subtests.
|
||||
if ((type === 'test:pass' || type === 'test:fail') && data.nesting === 0 && data.file && data.details) {
|
||||
const f = path.relative(process.cwd(), data.file).split(path.sep).join('/');
|
||||
sec[f] = (sec[f] || 0) + (data.details.duration_ms || 0) / 1000;
|
||||
}
|
||||
}
|
||||
const out = {};
|
||||
for (const f of Object.keys(sec).sort()) out[f] = Math.round(sec[f] * 10) / 10;
|
||||
yield JSON.stringify(out, null, 1) + '\n';
|
||||
};
|
||||
240
scripts/mcp.js
Normal file
240
scripts/mcp.js
Normal file
|
|
@ -0,0 +1,240 @@
|
|||
#!/usr/bin/env node
|
||||
// Series of Tubes as an MCP server: an AI client can play, inspect and debug the game through typed tools, in one of
|
||||
// two sessions: headless, a game of its own loaded from this checkout's src/ (scripts/lib/mcp-game.js), or the game in
|
||||
// the player's browser tab over the agent relay (scripts/lib/mcp-browser.js). It speaks MCP through the official SDK
|
||||
// (@modelcontextprotocol/server), over stdio or over HTTP. Nothing is hosted: this is a local tool, like npm run dev,
|
||||
// and the game page players get does not change.
|
||||
//
|
||||
// node scripts/mcp.js # stdio, headless, the agent's clock (advance)
|
||||
// node scripts/mcp.js --clock realtime # a clock that runs on its own (--pace ms per day; wait)
|
||||
// node scripts/mcp.js --browser # the player's tab, through the relay npm run dev hosts
|
||||
// node scripts/mcp.js --http 7777 # Streamable HTTP on http://127.0.0.1:7777/mcp (with any of the above)
|
||||
// node scripts/mcp.js --http 0.0.0.0:7777 # the same on every interface: anyone who can reach it can play
|
||||
//
|
||||
// claude mcp add seriesoftubes -- node /path/to/seriesoftubes/scripts/mcp.js
|
||||
// claude mcp add --transport http seriesoftubes http://127.0.0.1:7777/mcp
|
||||
//
|
||||
// stdout carries only protocol messages in stdio mode; anything else goes to stderr.
|
||||
const crypto = require('node:crypto');
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { McpServer, fromJsonSchema, createMcpHandler, validateHostHeader, validateOriginHeader, localhostAllowedHostnames, localhostAllowedOrigins } = require('@modelcontextprotocol/server');
|
||||
const { createSession, toolsFor, CLOCKS, DEFAULT_PACE_MS } = require('./lib/mcp-game');
|
||||
const { version } = require('../package.json');
|
||||
|
||||
const READ = 'Read with status, network, city, find, traceroute, peering_check and hot_spots, or raw with state, results and catalog; schema is the typed contract of every action, and its mode section says which session this is. Change things with act (arguments are checked, outcome says what happened, dryRun prices a move first), or with screen, panel and click, which show the game\'s own panels and windows as text with numbered buttons.';
|
||||
const CLOCK = {
|
||||
agent: 'Time moves only with advance.',
|
||||
realtime: 'The clock runs on its own, a day at a fixed pace, and you cannot stop it: decide while it runs, and use wait to let days pass.',
|
||||
};
|
||||
const instructions = (mode, clock) => mode === 'browser'
|
||||
? `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. You are playing the game in the player's own browser tab while they watch: the game, its saves and its settings are theirs, and so is any window they open (you play behind it). ${READ} The player picks the clock in Settings: either it runs on its own at a pace and you use wait, or it is yours and you use advance (schema mode.clock says which).`
|
||||
: `Series of Tubes is a cartoon game about building an internet backbone: POPs in cities, links between them, transit, exchanges, PNIs, customers. A game is always loaded (a fresh On-call game in Frankfurt until you start or load another). ${READ} ${CLOCK[clock]} Games are seeded: the same seed and moves give the same game.
|
||||
To look into a bug report: load_save with the attached save, then status, hot_spots, and advance with timings.`;
|
||||
const INSTRUCTIONS = instructions('headless', 'agent');
|
||||
const MCP_PATH = '/mcp';
|
||||
|
||||
const usage = () => `Usage: node scripts/mcp.js [options]
|
||||
|
||||
(no options) headless over stdio: a game of its own, from this checkout's src/; the client starts this process
|
||||
--clock agent|realtime headless: who moves time (default agent: advance; realtime: a day every --pace ms, and wait)
|
||||
--pace MS headless, realtime clock: real milliseconds per simulated day (default ${DEFAULT_PACE_MS})
|
||||
--seed N headless: the random seed of the first game (default 12345)
|
||||
--browser the game in the player's browser instead, over the agent relay (Settings → Agent API)
|
||||
--relay-host HOST browser: where npm run dev serves the page; the relay rides it (default 127.0.0.1)
|
||||
--relay-port N browser: the port it serves the page on (default 8080)
|
||||
--page-wait-ms N browser: how long to wait for a game page to connect (default 90000)
|
||||
--call-ms N browser: how long one tool call may wait for the page (default 30000)
|
||||
--http [HOST:]PORT Streamable HTTP at http://HOST:PORT${MCP_PATH} instead (HOST defaults to 127.0.0.1)
|
||||
--token-file FILE HTTP: require "Authorization: Bearer <the file's contents>" (or set SOT_MCP_TOKEN)
|
||||
--allow-host NAME HTTP: also accept this Host name (repeatable), e.g. for a tunnel or a LAN name
|
||||
--save-dir DIR HTTP: load_save and export_save may read and write files under DIR (otherwise no files)
|
||||
--help`;
|
||||
|
||||
// Valueless flags are true; repeated ones collect; --kebab-case becomes camelCase.
|
||||
function parseArgs(argv) {
|
||||
const out = {};
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (!a.startsWith('--')) continue;
|
||||
const k = a.slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase()), v = argv[i + 1];
|
||||
const val = v === undefined || v.startsWith('--') ? true : (i++, v);
|
||||
out[k] = k in out ? [].concat(out[k], val) : val;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Tool calls run one at a time, in the order they arrived, from every client: one game, one move at a time.
|
||||
function serial() {
|
||||
let chain = Promise.resolve();
|
||||
return (f) => { const p = chain.then(f); chain = p.catch(() => {}); return p; };
|
||||
}
|
||||
|
||||
// One MCP server definition over the game session: the SDK asks for a fresh one per connection (stdio) or per request
|
||||
// (HTTP); they all share the session and its queue.
|
||||
function serverFactory(session) {
|
||||
const queue = serial(), tools = toolsFor(session.mode || 'headless'), text = instructions(session.mode || 'headless', session.clock || 'agent');
|
||||
const schemas = new Map(tools.map((t) => [t.name, fromJsonSchema(t.inputSchema)]));
|
||||
return () => {
|
||||
const server = new McpServer({ name: 'seriesoftubes', title: 'Series of Tubes', version }, { capabilities: { tools: {} }, instructions: text });
|
||||
for (const tool of tools) {
|
||||
server.registerTool(tool.name, { description: tool.description, inputSchema: schemas.get(tool.name) }, (args) => queue(async () => {
|
||||
try {
|
||||
const out = await tool.run(session, args || {});
|
||||
const errs = session.errors();
|
||||
return { content: [{ type: 'text', text: JSON.stringify(out, null, 1) }], ...(errs.length ? { _meta: { pageErrors: errs.slice(-5) } } : {}) };
|
||||
} catch (e) {
|
||||
return { content: [{ type: 'text', text: String(e && e.message || e) }], isError: true };
|
||||
}
|
||||
}));
|
||||
}
|
||||
return server;
|
||||
};
|
||||
}
|
||||
|
||||
// --http [HOST:]PORT, with IPv6 hosts in brackets ([::1]:7777).
|
||||
function parseListen(v) {
|
||||
const s = String(v === true ? '' : v);
|
||||
const m = /^(?:\[([^\]]+)\]|([^:]+)):(\d+)$/.exec(s) || /^()()(\d+)$/.exec(s);
|
||||
// Port 0 picks a free one (the banner says which).
|
||||
if (!m || +m[3] > 65535) throw new Error(`--http takes [HOST:]PORT, e.g. 7777 or 0.0.0.0:7777, not "${s}"`);
|
||||
return { host: m[1] || m[2] || '127.0.0.1', port: +m[3] };
|
||||
}
|
||||
const isLoopback = (h) => h === 'localhost' || h === '::1' || /^127\.\d+\.\d+\.\d+$/.test(h);
|
||||
const isWildcard = (h) => h === '0.0.0.0' || h === '::';
|
||||
const bracket = (h) => (h.includes(':') && !h.startsWith('[') ? `[${h}]` : h);
|
||||
|
||||
// The names a request's Host may carry: this machine by loopback, the address the server is bound to (every local
|
||||
// address when bound to all of them), and names the operator allowed. Anything else is a name someone else's DNS
|
||||
// points here (DNS rebinding) and is refused.
|
||||
function allowedHosts(host, extra = []) {
|
||||
const out = new Set([...localhostAllowedHostnames(), ...extra.map(String)]);
|
||||
if (isWildcard(host)) for (const list of Object.values(os.networkInterfaces())) for (const a of list || []) out.add(bracket(a.address.split('%')[0]));
|
||||
else out.add(bracket(host));
|
||||
return [...out];
|
||||
}
|
||||
|
||||
// Constant-time token check (hashing first makes the lengths equal, so the length does not leak either).
|
||||
const sameToken = (a, b) => crypto.timingSafeEqual(crypto.createHash('sha256').update(String(a)).digest(), crypto.createHash('sha256').update(String(b)).digest());
|
||||
|
||||
// The HTTP side: Host and Origin checked on every request (browsers cannot be talked into driving the game from a
|
||||
// website), the token when there is one, then the SDK's Streamable HTTP handler.
|
||||
function createHttpServer(factory, { host, allow = [], token = null } = {}) {
|
||||
const { toNodeHandler } = require('@modelcontextprotocol/node');
|
||||
const handle = toNodeHandler(createMcpHandler(factory));
|
||||
const hosts = allowedHosts(host, allow), origins = localhostAllowedOrigins();
|
||||
const deny = (res, code, message, headers = {}) => {
|
||||
res.writeHead(code, { 'content-type': 'application/json', ...headers });
|
||||
res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32000, message } }));
|
||||
};
|
||||
const server = http.createServer((req, res) => {
|
||||
const url = new URL(req.url, 'http://localhost');
|
||||
if (url.pathname !== MCP_PATH) return deny(res, 404, `The MCP endpoint is ${MCP_PATH}.`);
|
||||
const h = validateHostHeader(req.headers.host, hosts);
|
||||
if (!h.ok) return deny(res, 403, `Host not allowed: ${h.message}. Use an address of this machine, or start the server with --allow-host.`);
|
||||
const o = validateOriginHeader(req.headers.origin, origins);
|
||||
if (!o.ok) return deny(res, 403, 'Origin not allowed: a web page may not drive this server.');
|
||||
if (token) {
|
||||
const auth = String(req.headers.authorization || '').trim(), sp = auth.search(/\s/);
|
||||
const given = sp > 0 && auth.slice(0, sp).toLowerCase() === 'bearer' ? auth.slice(sp + 1).trim() : '';
|
||||
if (!given || !sameToken(given, token)) return deny(res, 401, 'A bearer token is required.', { 'www-authenticate': 'Bearer realm="seriesoftubes"' });
|
||||
}
|
||||
handle(req, res);
|
||||
});
|
||||
// advance over thousands of days on a big network takes minutes; Node's default would cut it off at five.
|
||||
server.requestTimeout = 30 * 60 * 1000;
|
||||
return server;
|
||||
}
|
||||
|
||||
function readToken(args) {
|
||||
if (args.tokenFile) {
|
||||
const t = fs.readFileSync(path.resolve(String(args.tokenFile)), 'utf8').trim();
|
||||
if (!t) throw new Error(`${args.tokenFile} is empty`);
|
||||
return t;
|
||||
}
|
||||
return process.env.SOT_MCP_TOKEN ? String(process.env.SOT_MCP_TOKEN).trim() || null : null;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
if (args.help) { console.error(usage()); process.exit(0); }
|
||||
const say = (m) => console.error(`[series-of-tubes] ${m}`);
|
||||
const die = (m) => { console.error(`error: ${m}`); process.exit(1); };
|
||||
// The game page logs nothing to stdout, but a stray console.log anywhere must not break the stdio protocol.
|
||||
console.log = console.info = (...a) => console.error(...a);
|
||||
const flag = (k) => `--${k.replace(/[A-Z]/g, (c) => '-' + c.toLowerCase())}`;
|
||||
if (!args.http) for (const k of ['tokenFile', 'allowHost', 'saveDir']) if (args[k] !== undefined) die(`${flag(k)} is an --http option`);
|
||||
if (args.browser) {
|
||||
for (const k of ['clock', 'pace', 'seed', 'saveDir']) if (args[k] !== undefined) die(`${flag(k)} is the headless session's: in the browser the player owns the game and sets the clock in Settings`);
|
||||
} else {
|
||||
for (const k of ['relayHost', 'relayPort', 'pageWaitMs', 'callMs']) if (args[k] !== undefined) die(`${flag(k)} is a --browser option`);
|
||||
if (args.clock !== undefined && !CLOCKS.includes(args.clock)) die(`--clock is one of ${CLOCKS.join(', ')}`);
|
||||
}
|
||||
if (!args.http) {
|
||||
const { serveStdio } = require('@modelcontextprotocol/server/stdio');
|
||||
const session = open(args);
|
||||
serveStdio(serverFactory(session));
|
||||
const shutdown = () => { try { session.close(); } catch {} process.exit(0); };
|
||||
process.stdin.on('close', shutdown);
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
// stdio has one client, which needs the page: without one, it is better told by the server stopping.
|
||||
started(session, args, say, true);
|
||||
return;
|
||||
}
|
||||
let listen, token;
|
||||
try { listen = parseListen(args.http); token = readToken(args); } catch (e) { die(e.message); }
|
||||
// Over HTTP the client may be another machine: files only under --save-dir, never anywhere on this one.
|
||||
let saveDir = null;
|
||||
if (args.saveDir !== undefined) {
|
||||
try { saveDir = fs.realpathSync(path.resolve(String(args.saveDir))); } catch (e) { die(`--save-dir ${args.saveDir}: ${e.message}`); }
|
||||
if (!fs.statSync(saveDir).isDirectory()) die(`--save-dir ${args.saveDir} is not a directory`);
|
||||
}
|
||||
const session = open(args, { saveDir });
|
||||
const server = createHttpServer(serverFactory(session), { host: listen.host, allow: [].concat(args.allowHost || []), token });
|
||||
server.on('error', (e) => die(`could not listen on ${bracket(listen.host)}:${listen.port}: ${e.message}`));
|
||||
server.listen(listen.port, listen.host, () => {
|
||||
const ad = server.address(), at = `${bracket(ad.address)}:${ad.port}`;
|
||||
say(`MCP server ${version} on http://${at}${MCP_PATH} (one game, shared by every client; calls run one at a time)`);
|
||||
say(token ? 'a bearer token is required' : 'no token: anything that can reach this address may play');
|
||||
if (!isLoopback(listen.host) && !token) say(`WARNING: bound to ${listen.host}, beyond this machine, without a token. Set SOT_MCP_TOKEN or --token-file to require one.`);
|
||||
if (session.mode === 'headless') say(saveDir ? `load_save and export_save files: under ${saveDir}` : 'load_save and export_save take JSON only (no files: --save-dir DIR allows some)');
|
||||
started(session, args, say, false);
|
||||
});
|
||||
const shutdown = () => { try { session.close(); } catch {} server.close(() => process.exit(0)); };
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
}
|
||||
|
||||
// The session the flags ask for: headless (with its clock), or the player's browser over the relay.
|
||||
function open(args, extra = {}) {
|
||||
if (args.browser) {
|
||||
const { createBrowserSession } = require('./lib/mcp-browser');
|
||||
return createBrowserSession({ host: args.relayHost, port: args.relayPort, callMs: args.callMs });
|
||||
}
|
||||
return createSession({ clock: args.clock, paceMs: args.pace, seed: +args.seed || undefined, ...extra });
|
||||
}
|
||||
|
||||
// What the session is, said once it is up. In the browser the handshake is answered at once; the page may arrive
|
||||
// later, and must be built from this checkout. Over stdio a missing or stale page stops the server (its one client
|
||||
// is better told so); over HTTP the server stays up and says why its tools fail.
|
||||
function started(session, args, say, stopOnFail) {
|
||||
if (session.mode !== 'browser') {
|
||||
say(`MCP server ${version}: headless, ${session.clock === 'realtime' ? `a running clock, a day every ${session.paceMs} ms` : 'the agent\'s clock'}`);
|
||||
return;
|
||||
}
|
||||
say(`MCP server ${version}: the player's browser, over the relay ${session.relay.url}`);
|
||||
session.ready({ waitMs: +args.pageWaitMs || 90000, onWait: () => say(`waiting for the game page on the relay (${session.relay.url})...`) }).then((r) => {
|
||||
if (r.ok) { say('the game page serves this checkout\'s contract: ready'); return; }
|
||||
say(r.why);
|
||||
if (r.stale) say('Its tab is older than this checkout: reload the page in the browser (npm run dev assembles it from src/ on every request).');
|
||||
else say('Turn agent mode on in the game (Settings → Agent API), which connects it to the relay. The page must come from npm run dev, which hosts the relay (the deployed seriesoftub.es has none), opened by address (http://localhost or http://127.0.0.1, or the IP it is bound to), not a DNS name, which the relay refuses.');
|
||||
if (stopOnFail) process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
if (require.main === module) main();
|
||||
|
||||
module.exports = { serverFactory, createHttpServer, serial, parseArgs, parseListen, allowedHosts, instructions, INSTRUCTIONS, MCP_PATH };
|
||||
117
scripts/mp-server.js
Normal file
117
scripts/mp-server.js
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
#!/usr/bin/env node
|
||||
// The multiplayer server for a self-hosted Series of Tubes (docs/MULTIPLAYER.md). The public game at seriesoftub.es
|
||||
// is GitHub Pages only and has no multiplayer: this is for your own copy, built with MP_API=/api/mp npm run build.
|
||||
// Plain node:http, no dependencies. It answers the API under /api/mp and, with --site, serves the built game too, so
|
||||
// one process can sit behind a reverse proxy.
|
||||
const fs = require('node:fs');
|
||||
const http = require('node:http');
|
||||
const path = require('node:path');
|
||||
const { createMp } = require('./lib/mp');
|
||||
|
||||
const HELP = `Series of Tubes multiplayer server
|
||||
|
||||
node scripts/mp-server.js [options] (npm run mp -- [options])
|
||||
|
||||
--port N port to listen on (default 8090, or $PORT)
|
||||
--host H address to bind (default 127.0.0.1: put a reverse proxy in front)
|
||||
--data DIR where sessions and saves are kept (default ./mp-data, created if missing)
|
||||
--site DIR also serve the built game from DIR (e.g. _site from MP_API=/api/mp npm run build)
|
||||
--base PATH the API's path (default /api/mp; the page's MP_API must match)
|
||||
--prune-days N sessions nobody touched for N days are deleted at startup and daily (default 60)
|
||||
--max-sessions N at most N sessions on this server (default 1000)
|
||||
--max-players N at most N players per session (default 12, at most 12)
|
||||
--create-per-hour N new sessions one address may start per hour (default 10; an IPv6 address counts as its /64)
|
||||
--sessions-per-hour N new sessions on the whole server per hour (default 100)
|
||||
--trust-proxy take the client's address from X-Forwarded-For (only behind your own reverse proxy)
|
||||
--verbose log one line per API request (never tokens)
|
||||
--help this text
|
||||
|
||||
Storage: DIR/<CODE>.json per session and DIR/<CODE>.<pid>.save per player's save. Back up DIR.
|
||||
API (JSON; every call but create and join needs Authorization: Bearer <pid>.<token>):
|
||||
POST /api/mp/sessions {net:{name,home},preset,title?} start a session
|
||||
POST /api/mp/sessions/:code/join {net:{name,home}} join one
|
||||
GET /api/mp/sessions/:code roster, cards and feed
|
||||
PUT /api/mp/sessions/:code/card {card} your public card
|
||||
PUT /api/mp/sessions/:code/save {seq,at,data,card?,force?} your save (409 when the server has a newer one)
|
||||
GET /api/mp/sessions/:code/save your save
|
||||
POST /api/mp/sessions/:code/feed {text} a chat line
|
||||
DELETE /api/mp/sessions/:code/me leave
|
||||
`;
|
||||
|
||||
const argv = process.argv.slice(2);
|
||||
if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP); process.exit(0); }
|
||||
const die = (m) => { console.error(`error: ${m}`); process.exit(2); };
|
||||
const KNOWN = new Set(['--port', '--host', '--data', '--site', '--base', '--prune-days', '--max-sessions', '--max-players', '--create-per-hour', '--sessions-per-hour', '--trust-proxy', '--verbose', '--help', '-h']);
|
||||
for (const a of argv) if (a.startsWith('-') && !KNOWN.has(a)) die(`unknown option ${a} (see --help)`);
|
||||
const opt = (k) => { const i = argv.indexOf(k); if (i < 0) return null; const v = argv[i + 1]; if (v === undefined || v.startsWith('--')) die(`${k} needs a value`); return v; };
|
||||
const pos = (k, d, max = 1e9) => { const v = opt(k); if (v === null) return d; const n = +v; if (!Number.isInteger(n) || n < 1 || n > max) die(`${k} wants a whole number from 1 to ${max}`); return n; };
|
||||
|
||||
const PORT = pos('--port', +process.env.PORT || 8090, 65535);
|
||||
const HOST = opt('--host') || '127.0.0.1';
|
||||
const DATA = path.resolve(opt('--data') || 'mp-data');
|
||||
const SITE = opt('--site') ? path.resolve(opt('--site')) : null;
|
||||
const BASE = opt('--base') || '/api/mp';
|
||||
// A path, never "//host/..." (which a browser reads as another host).
|
||||
if (!/^\/(?!\/)[A-Za-z0-9/_-]*[A-Za-z0-9_-]$/.test(BASE)) die('--base must be a path like /api/mp');
|
||||
if (SITE && !fs.statSync(SITE, { throwIfNoEntry: false })?.isDirectory()) die(`--site ${SITE} is not a directory`);
|
||||
if (SITE && !fs.existsSync(path.join(SITE, 'index.html'))) die(`--site ${SITE} has no index.html (run npm run build first)`);
|
||||
|
||||
const mp = createMp({
|
||||
dir: DATA, base: BASE, pruneDays: pos('--prune-days', 60), maxSessions: pos('--max-sessions', 1000),
|
||||
maxPlayers: pos('--max-players', 12, 12), createPerHour: pos('--create-per-hour', 10), sessionsPerHour: pos('--sessions-per-hour', 100),
|
||||
trustProxy: argv.includes('--trust-proxy'), verbose: argv.includes('--verbose'),
|
||||
});
|
||||
|
||||
const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json',
|
||||
'.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml',
|
||||
'.webmanifest': 'application/manifest+json', '.woff2': 'font/woff2', '.jpg': 'image/jpeg', '.webp': 'image/webp' };
|
||||
// The page, the service worker and the files that change between releases are always checked; the rest may be cached.
|
||||
const FRESH = /(^|\/)(index\.html|404\.html|sw\.js|version\.json)$|\/weekly\//;
|
||||
|
||||
// What is at p, or null: a path the file system cannot even look at (too long, a loop of links...) is not there either.
|
||||
const stat = (p) => { try { return fs.statSync(p, { throwIfNoEntry: false }) || null; } catch (e) { return null; } };
|
||||
const isFile = (p) => { const st = stat(p); return !!(st && st.isFile()); };
|
||||
|
||||
// The built site, like GitHub Pages serves it: / is index.html, a missing file is 404.html, nothing outside SITE.
|
||||
function serveSite(req, res) {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { allow: 'GET, HEAD' }); return res.end(); }
|
||||
let rel;
|
||||
try { rel = decodeURIComponent(new URL(req.url, 'http://x').pathname); } catch (e) { rel = null; }
|
||||
let file = null;
|
||||
if (rel !== null && !rel.includes('\0')) {
|
||||
if (rel.endsWith('/')) rel += 'index.html';
|
||||
const p = path.resolve(SITE, '.' + path.posix.normalize('/' + rel));
|
||||
if (p.startsWith(SITE + path.sep)) { const st = stat(p); if (st && st.isFile()) file = p; else if (st && st.isDirectory() && isFile(path.join(p, 'index.html'))) file = path.join(p, 'index.html'); }
|
||||
}
|
||||
const status = file ? 200 : 404;
|
||||
if (!file) file = path.join(SITE, '404.html');
|
||||
if (!isFile(file)) { res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' }); return res.end('Not found'); }
|
||||
const r = path.relative(SITE, file).split(path.sep).join('/');
|
||||
res.writeHead(status, { 'content-type': TYPES[path.extname(file)] || 'application/octet-stream', 'cache-control': FRESH.test('/' + r) ? 'no-cache' : 'public, max-age=3600', 'x-content-type-options': 'nosniff' });
|
||||
if (req.method === 'HEAD') return res.end();
|
||||
fs.createReadStream(file).on('error', () => res.destroy()).pipe(res);
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
try {
|
||||
if (mp.handle(req, res)) return;
|
||||
if (SITE) return serveSite(req, res);
|
||||
res.writeHead(404, { 'content-type': 'application/json; charset=utf-8' });
|
||||
res.end('{"error":"not found"}');
|
||||
} catch (e) {
|
||||
// One line, never a stack: whatever went wrong, a request should not be able to fill the log.
|
||||
console.error(`[mp] ${req.method} ${String(req.url).slice(0, 200)}: ${e && e.message}`);
|
||||
if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json; charset=utf-8' });
|
||||
res.end('{"error":"server error"}');
|
||||
}
|
||||
});
|
||||
server.on('clientError', (e, socket) => { try { socket.end('HTTP/1.1 400 Bad Request\r\n\r\n'); } catch (_) { /* gone */ } });
|
||||
server.on('error', (e) => { console.error(`error: could not listen on ${HOST}:${PORT}: ${e.message}`); process.exit(1); });
|
||||
server.listen(PORT, HOST, () => {
|
||||
const ad = server.address(), at = `${ad.family === 'IPv6' ? `[${ad.address}]` : ad.address}:${ad.port}`;
|
||||
console.log(`Series of Tubes multiplayer: http://${at}${BASE} (data in ${DATA}, ${mp.sessions()} sessions${SITE ? `, serving ${SITE}` : ''})`);
|
||||
});
|
||||
setInterval(() => { try { mp.prune(); } catch (e) { console.error(`[mp] pruning failed: ${e.message}`); } }, 86400000).unref();
|
||||
const shutdown = () => { server.close(); mp.flush().finally(() => process.exit(0)); setTimeout(() => process.exit(0), 3000).unref(); };
|
||||
process.on('SIGINT', shutdown);
|
||||
process.on('SIGTERM', shutdown);
|
||||
|
|
@ -21,6 +21,7 @@ const args = process.argv.slice(2);
|
|||
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const page = require('./lib/page');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
// Pages as files: the browser run opens them from disk.
|
||||
const HEAD = opt('--head', null) || page.pageFile();
|
||||
const BASE = opt('--base', null) || (opt('--base-ref', null) && (() => {
|
||||
|
|
@ -42,11 +43,16 @@ const METRICS = [
|
|||
['panels', 'Side panel and left list', "for(const f of [true,false]){UI.sel={type:'city',id:f?'fra':'ams'};UI.tab=f?'peer':'up';UI.left=f?'nets':'noc';UI.leftOpen=true;renderPanel();renderLeft();}"],
|
||||
['dash', 'NOC dashboard tabs', "$('dash').hidden=false;for(const k of ['overview','conn','traffic','infra','cust']){UI.dtab=k;renderDash();}$('dash').hidden=true"],
|
||||
['map', 'Map at three zoom levels', "for(const z of [1,3.2,7]){cam.x=CITY.fra.x;cam.y=CITY.fra.y;cam.z=z;draw(0);}"],
|
||||
// The NOC intern runs every order, every day: one shift, its recomputes included (hired here if the save has none).
|
||||
['ops', "The NOC intern's shift: opsDay()", "if(!S.ops.intern){S.ops.intern='tracy';S.ops.hired=S.day;for(const k in S.ops.on)S.ops.on[k]=true;S.ops.floor=0;for(const k in S.ops.cap)S.ops.cap[k]=0;}S.cash=1e9;opsDay(S.day)"],
|
||||
// A day as it is played: its routing in the route worker, and only the time it holds the page counted (what a player
|
||||
// feels as a hitch). Chromium only: jsdom has no Worker. See perf-browser.js.
|
||||
['play', 'One game day in play: page time only', null, { play: true }],
|
||||
];
|
||||
|
||||
function open(file) {
|
||||
const { ev, errors } = load({ file, seed: 777 });
|
||||
ev(`S=migrate(JSON.parse(${JSON.stringify(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();renderAll();`);
|
||||
ev(`S=migrate(JSON.parse(${lit(SAVE)}));UI.started=true;UI.pitched=true;UI.speed=0;closeModal();compute();renderAll();`);
|
||||
const time = (body) => ev(`(()=>{const t=performance.now();${body};return performance.now()-t;})()`);
|
||||
// What the network carries, to tell a pure speed-up from a change in how traffic is routed.
|
||||
const outcome = () => ev(`(()=>{compute();const r=[R.served,R.demand,R.reach,R.peered,JSON.stringify(R.egT),...Object.keys(R.citySrv).sort().map(c=>R.citySrv[c]),...S.links.map(l=>R.load[l.id]||0)];
|
||||
|
|
@ -56,13 +62,14 @@ function open(file) {
|
|||
}
|
||||
|
||||
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2; };
|
||||
const ms = (x) => x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2);
|
||||
const ms = (x) => x == null ? '–' : x >= 100 ? x.toFixed(0) : x >= 10 ? x.toFixed(1) : x.toFixed(2);
|
||||
|
||||
(async () => {
|
||||
const head = open(HEAD), base = BASE ? open(BASE) : null;
|
||||
const sameOutcome = base ? base.outcome() === head.outcome() : null;
|
||||
const res = {};
|
||||
for (const [k, , body] of METRICS) {
|
||||
for (const [k, , body, o] of METRICS) {
|
||||
if (o && o.play) { res[k] = { head: null, base: null, samples: null }; continue; }
|
||||
const h = [], b = [];
|
||||
for (const v of [head, base].filter(Boolean)) { v.time(body); v.time(body); } // warm up
|
||||
for (let i = 0; i < RUNS; i++) {
|
||||
|
|
@ -77,7 +84,7 @@ const browser = args.includes('--browser') ? await require('./perf-browser').run
|
|||
const { mannWhitneyP } = require('./perf-stats');
|
||||
const pOf = (r) => (r.samples && r.samples.base ? mannWhitneyP(r.samples.head, r.samples.base) : 1);
|
||||
const verdict = (r, noise = 2) => {
|
||||
if (r.base == null) return '';
|
||||
if (r.base == null || r.head == null) return '';
|
||||
const ratio = r.head / (r.base || 1e-9);
|
||||
if (Math.abs(r.head - r.base) < noise || pOf(r) >= 0.01) return '≈';
|
||||
if (ratio >= 1.5) return '🔴 slower';
|
||||
|
|
@ -85,8 +92,8 @@ const verdict = (r, noise = 2) => {
|
|||
if (ratio <= 0.85) return '🟢 faster';
|
||||
return '≈';
|
||||
};
|
||||
const pct = (r) => r.base == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`;
|
||||
const pTxt = (r) => { const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); };
|
||||
const pct = (r) => r.base == null || r.head == null ? '' : `${r.head >= r.base ? '+' : ''}${(((r.head - r.base) / (r.base || 1e-9)) * 100).toFixed(0)}%`;
|
||||
const pTxt = (r) => { if (r.base == null || r.head == null) return ''; const p = pOf(r); return p < 0.001 ? '<0.001' : p.toFixed(p < 0.1 ? 3 : 2); };
|
||||
// One table per environment, all the same shape. `noise` is the absolute floor below which nothing counts.
|
||||
const table = (res, noise) => (base ? '| What | Base | This PR | Change | p | |\n|---|--:|--:|--:|--:|---|\n' : '| What | Time |\n|---|--:|\n') +
|
||||
METRICS.map(([k, label]) => { const r = res[k]; return base ? `| ${label} | ${ms(r.base)} | ${ms(r.head)} | ${pct(r)} | ${pTxt(r)} | ${verdict(r, noise)} |` : `| ${label} | ${ms(r.head)} |`; }).join('\n') + '\n';
|
||||
|
|
@ -94,11 +101,14 @@ const slowIn = (res, noise) => METRICS.filter(([k]) => /slower/.test(verdict(res
|
|||
|
||||
const s = head.size;
|
||||
let md = `## Performance on a big network\n\n${s.pops} POPs · ${s.links} links · ${s.pni} PNIs · ${s.caches} cache boxes · ${s.ix} IX ports · ${s.customers} customers. Median of ${RUNS} runs, in milliseconds.\n\n`;
|
||||
md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here.\n\n` + table(res, 2);
|
||||
md += `### Headless (jsdom)\n\nOur JavaScript only: jsdom has no layout and its DOM is far slower than a browser's, so trust the routing rows most here. It has no Worker either: a day in play is timed in Chromium only.\n\n` + table(res, 2);
|
||||
const slow = base ? slowIn(res, 2) : [];
|
||||
const { PROFILES } = browser ? require('./perf-browser') : { PROFILES: [] };
|
||||
for (const p of PROFILES) {
|
||||
md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.\n\n` + table(browser.profiles[p.key], 2 * p.rate);
|
||||
// The map row is the whole frame, up to a pixel read back from the surface that drew it; say which one that was.
|
||||
const mp = browser.profiles[p.key].maps, mapName = (m) => (!m || !m.length ? 'no map' : m.map((x) => (x === 'gl' ? 'WebGL' : '2D canvas')).join(' then '));
|
||||
const drew = mp ? ` The map was drawn with ${base ? `${mapName(mp.base)} (base) and ${mapName(mp.head)} (this PR)` : mapName(mp.head)}; its row waits for that surface to finish.` : '';
|
||||
md += `\n### Chromium ${browser.version}: ${p.key === 'phone' ? 'phone' : 'desktop'}\n\n${p.key === 'phone' ? 'A 390×844 screen at 3× pixel density, with the CPU slowed down 4× like a mid-range Android.' : 'A 1280×800 window at full speed.'} Real DOM, layout and canvas.${drew}\n\n` + table(browser.profiles[p.key], 2 * p.rate);
|
||||
if (base) slow.push(...slowIn(browser.profiles[p.key], 2 * p.rate).map((l) => `${l} (Chromium ${p.key})`));
|
||||
}
|
||||
if (base) {
|
||||
|
|
|
|||
|
|
@ -36,11 +36,32 @@ async function openPage(browser, profile, file, save, errors) {
|
|||
// One run of a workload, timed inside the page so the round trip to Node does not count. Garbage is collected
|
||||
// first, so a run never pays for the one before it (its own garbage still costs it, as in the game).
|
||||
// The browser leaves layout and canvas drawing for the next frame, so code that changes the DOM or draws the map
|
||||
// would look free: each run ends by forcing both (reading a size, and one pixel back from the map canvas).
|
||||
// would look free: each run ends by forcing both (reading a size, and one pixel back from the surface the map was
|
||||
// last drawn on: the WebGL canvas when the card drew it, which waits for the card to finish, else the 2D canvas).
|
||||
// A run also says which map drew (gl, 2d, or none when it drew nothing).
|
||||
const time = async (k, body) => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(([k, body]) => {
|
||||
const F = window.__fx || (window.__fx = {}); const f = F[k] || (F[k] = new Function(body)); const map = document.getElementById('map').getContext('2d');
|
||||
const t = performance.now(); f(); void document.documentElement.offsetHeight; map.getImageData(0, 0, 1, 1); return performance.now() - t; }, [k, body]); };
|
||||
return { ctx, time };
|
||||
const G = typeof GLX === 'object' ? GLX : null, px = window.__px || (window.__px = new Uint8Array(4));
|
||||
const t = performance.now(); f(); void document.documentElement.offsetHeight;
|
||||
const gl = G && G.shown && G.gl; if (gl) gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, px); else map.getImageData(0, 0, 1, 1);
|
||||
return { ms: performance.now() - t, map: G && G.shown ? 'gl' : '2d' }; }, [k, body]); };
|
||||
// One game day as it is played: its steps on the page, its routing in the route worker (built from the page itself,
|
||||
// see 28-route-worker.js). Only the time it holds the page counts: starting the day, each answer from the worker and
|
||||
// each step that waited for a frame. Waiting for the worker does not count; the page is free meanwhile.
|
||||
// null when this page has no worker to play with.
|
||||
const play = async () => { await cdp.send('HeapProfiler.collectGarbage'); return page.evaluate(async () => {
|
||||
window.__TUBES_TEST__ = false;
|
||||
try {
|
||||
const w = typeof rwOn === 'function' && rwOn() && rwStart(); if (!w) return null;
|
||||
let busy = 0; const wrap = (f) => function (...a) { const t = performance.now(); try { return f.apply(this, a); } finally { busy += performance.now() - t; } };
|
||||
const om = w.onmessage, later = RW.later; w.onmessage = wrap(om); if (later) RW.later = (f) => later(wrap(f));
|
||||
S.nextFail = S.nextEvent = S.day + 99;
|
||||
try { const t = performance.now(); rwDay(); busy += performance.now() - t; while (RW.job) await new Promise((r) => setTimeout(r, 1)); }
|
||||
finally { w.onmessage = om; if (later) RW.later = later; }
|
||||
return RW.dead ? null : busy;
|
||||
} finally { window.__TUBES_TEST__ = true; }
|
||||
}); };
|
||||
return { ctx, time, play };
|
||||
}
|
||||
|
||||
// Returns {version, profiles: {desktop: {compute: {head, base}, ...}, phone: {...}}, errors}.
|
||||
|
|
@ -54,15 +75,21 @@ async function runBrowser({ head, base, save, metrics, runs, exe }) {
|
|||
for (const p of PROFILES) {
|
||||
const h = await openPage(hb, p, head, save, errors), b = base ? await openPage(bb, p, base, save, errors) : null;
|
||||
const res = out.profiles[p.key] = {};
|
||||
for (const [k, , body] of metrics) {
|
||||
const H = [], B = [];
|
||||
for (const v of [h, b].filter(Boolean)) { await v.time(k, body); await v.time(k, body); } // warm up
|
||||
// Which map each version drew with, over all the runs that drew one (a version falling back mid-run shows both).
|
||||
const maps = res.maps = { head: new Set(), base: new Set() };
|
||||
for (const [k, , body, o] of metrics) {
|
||||
const H = [], B = [], run = (v) => (o && o.play ? v.play() : v.time(k, body));
|
||||
const go = async (v, into, m) => { const r = await run(v); if (o && o.play) into.push(r); else { into.push(r.ms); if (k === 'map') m.add(r.map); } };
|
||||
for (const v of [h, b].filter(Boolean)) { await run(v); await run(v); } // warm up (and the worker starts)
|
||||
for (let i = 0; i < runs; i++) {
|
||||
// Alternate who goes first, like the jsdom runs.
|
||||
if (b && i % 2) { B.push(await b.time(k, body)); H.push(await h.time(k, body)); } else { H.push(await h.time(k, body)); if (b) B.push(await b.time(k, body)); }
|
||||
if (b && i % 2) { await go(b, B, maps.base); await go(h, H, maps.head); } else { await go(h, H, maps.head); if (b) await go(b, B, maps.base); }
|
||||
}
|
||||
res[k] = { head: median(H), base: b ? median(B) : null, samples: { head: H.map((x) => +x.toFixed(1)), base: b ? B.map((x) => +x.toFixed(1)) : null } };
|
||||
// A version without a worker gives nothing to compare.
|
||||
const ok = (a) => a.every((x) => x != null);
|
||||
res[k] = { head: ok(H) ? median(H) : null, base: b && ok(B) ? median(B) : null, samples: { head: ok(H) ? H.map((x) => +x.toFixed(1)) : null, base: b && ok(B) ? B.map((x) => +x.toFixed(1)) : null } };
|
||||
}
|
||||
res.maps = { head: [...maps.head], base: b ? [...maps.base] : null };
|
||||
await h.ctx.close(); if (b) await b.ctx.close();
|
||||
}
|
||||
} finally { await hb.close(); if (bb) await bb.close(); }
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
#!/usr/bin/env node
|
||||
// Prints the CHANGELOG.md bullets for one version as a JSON array of strings.
|
||||
// Usage: node scripts/release-notes.js 1.2.0
|
||||
// node scripts/release-notes.js 2.0.0 --story the release's story instead: the paragraphs of prose between
|
||||
// its heading and its first bullet or ### heading (often none)
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const version = process.argv[2];
|
||||
const version = process.argv[2], story = process.argv.includes('--story');
|
||||
const text = fs.readFileSync(path.join(__dirname, '..', 'CHANGELOG.md'), 'utf8');
|
||||
const lines = text.split('\n');
|
||||
const start = lines.findIndex((l) => l.startsWith(`## [${version}]`));
|
||||
|
|
@ -16,4 +18,15 @@ if (start >= 0) {
|
|||
else if (/^\s{2,}\S/.test(l) && notes.length) notes[notes.length - 1] += ' ' + l.trim();
|
||||
}
|
||||
}
|
||||
process.stdout.write(JSON.stringify(notes));
|
||||
if (story) {
|
||||
const paras = [];
|
||||
if (start >= 0) {
|
||||
let cur = [];
|
||||
for (let i = start + 1; i < lines.length && !lines[i].startsWith('## [') && !/^\s*-\s+/.test(lines[i]) && !lines[i].startsWith('###'); i++) {
|
||||
const l = lines[i].trim();
|
||||
if (l) cur.push(l); else if (cur.length) { paras.push(cur.join(' ')); cur = []; }
|
||||
}
|
||||
if (cur.length) paras.push(cur.join(' '));
|
||||
}
|
||||
process.stdout.write(JSON.stringify(paras));
|
||||
} else process.stdout.write(JSON.stringify(notes));
|
||||
|
|
|
|||
84
scripts/route-fuzz.js
Normal file
84
scripts/route-fuzz.js
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
#!/usr/bin/env node
|
||||
// Many random games, played move for move on main's page and on this checkout's, compared after every move and day
|
||||
// (scripts/lib/route-fuzz.js). For refactors that promise identical routing.
|
||||
//
|
||||
// node scripts/route-fuzz.js 300 games against origin/main
|
||||
// node scripts/route-fuzz.js --games 50 --from 1000 games with seeds 1000..1049
|
||||
// node scripts/route-fuzz.js --seed 1234 -v one game, every move printed (to replay a divergence)
|
||||
// node scripts/route-fuzz.js --save tests/fixtures/big-network.json --games 10 --moves 30 from a big network
|
||||
// node scripts/route-fuzz.js --jobs 2 --base OLD.html --out fuzz.json
|
||||
// Exit code 1 when any game diverged; each divergence is printed with its seed and its last moves.
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { fork } = require('node:child_process');
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const opt = (k, d) => { const i = args.indexOf(k); return i >= 0 ? args[i + 1] : d; };
|
||||
const has = (k) => args.includes(k);
|
||||
|
||||
function child() {
|
||||
const { openPage, playGame } = require('./lib/route-fuzz');
|
||||
const base = openPage(opt('--base'), 'base'), head = openPage(opt('--head'), 'head');
|
||||
process.on('message', (m) => {
|
||||
if (m.stop) process.exit(0);
|
||||
const t = Date.now();
|
||||
let res;
|
||||
try { res = playGame({ base, head }, m.seed, { moves: m.moves, save: m.save }); } catch (e) { res = { seed: m.seed, div: { where: 'driver crashed', error: String(e.stack || e) }, log: [] }; }
|
||||
process.send({ seed: m.seed, ms: Date.now() - t, start: res.start, moves: res.moves, days: res.days, div: res.div, acts: res.acts, log: m.verbose || res.div ? res.log : null, errors: res.errors });
|
||||
});
|
||||
process.send({ ready: true });
|
||||
}
|
||||
|
||||
function parent() {
|
||||
const page = require('./lib/page');
|
||||
const tmp = (n) => path.join(os.tmpdir(), `tubes-fuzz-${process.pid}-${n}.html`);
|
||||
const BASE = opt('--base', null) || (() => { const f = tmp('base'); fs.writeFileSync(f, page.assembleRef(opt('--base-ref', 'origin/main'))); return f; })();
|
||||
const HEAD = opt('--head', null) || (() => { const f = tmp('head'); fs.writeFileSync(f, page.assemble().html); return f; })();
|
||||
const one = opt('--seed', null);
|
||||
const from = +opt('--from', 1), games = one ? 1 : +opt('--games', 300);
|
||||
const seeds = one ? [+one] : Array.from({ length: games }, (_, i) => from + i);
|
||||
const jobs = Math.max(1, Math.min(+opt('--jobs', Math.max(1, os.cpus().length)), seeds.length));
|
||||
const verbose = has('-v');
|
||||
const moves = opt('--moves', null) ? +opt('--moves') : undefined;
|
||||
// --save FILE: every game starts from this save (a plain one, or an export from the menu) instead of a new network.
|
||||
const RAW = opt('--save', null) ? JSON.parse(fs.readFileSync(opt('--save'), 'utf8')) : null;
|
||||
const save = RAW ? JSON.stringify(RAW.app === 'series-of-tubes' && RAW.S ? RAW.S : RAW) : undefined;
|
||||
const results = [];
|
||||
let next = 0, live = 0;
|
||||
const t0 = Date.now();
|
||||
const done = () => {
|
||||
const div = results.filter((r) => r.div), tot = (k) => results.reduce((a, r) => a + (r[k] || 0), 0);
|
||||
const kinds = {};
|
||||
for (const r of results) if (r.start) { const k = r.start.kind + (r.start.kind === 'normal' || r.start.kind === 'sandbox' ? ':' + r.start.preset : ''); kinds[k] = (kinds[k] || 0) + 1; }
|
||||
console.log(`\n${results.length} games, ${tot('moves')} moves, ${tot('days')} days in ${((Date.now() - t0) / 1000).toFixed(0)} s. Starts: ${JSON.stringify(kinds)}`);
|
||||
const acts = {};for (const r of results) for (const k in r.acts || {}) acts[k] = (acts[k] || 0) + r.acts[k];
|
||||
if (has('--acts')) console.log('Actions pressed: ' + Object.entries(acts).sort((a, b) => b[1] - a[1]).map(([k, n]) => k + ' ' + n).join(', '));
|
||||
const errs = [...new Set(results.flatMap((r) => r.errors || []))];
|
||||
if (errs.length) console.log('Page errors:\n' + errs.slice(0, 10).map((e) => ' ' + e.slice(0, 200)).join('\n'));
|
||||
if (div.length) {
|
||||
console.log(`\n${div.length} games diverged:`);
|
||||
for (const r of div) console.log(JSON.stringify({ seed: r.seed, start: r.start, ...r.div }, null, 1).slice(0, 4000));
|
||||
} else console.log('No divergence: identical routing and game state in every game, cached and uncached.');
|
||||
const out = opt('--out', null);
|
||||
if (out) fs.writeFileSync(out, JSON.stringify(results, null, 1));
|
||||
process.exit(div.length ? 1 : 0);
|
||||
};
|
||||
for (let j = 0; j < jobs; j++) {
|
||||
const c = fork(__filename, ['--child', '--base', BASE, '--head', HEAD], { stdio: ['ignore', 'inherit', 'inherit', 'ipc'] });
|
||||
live++;
|
||||
const feed = () => { if (next < seeds.length) c.send({ seed: seeds[next++], moves, verbose, save }); else c.send({ stop: true }); };
|
||||
c.on('message', (m) => {
|
||||
if (!m.ready) {
|
||||
results.push(m);
|
||||
const tag = m.div ? 'DIVERGED at ' + m.div.where : 'ok';
|
||||
console.log(`seed ${m.seed} ${m.start ? m.start.kind + ' ' + (m.start.id || m.start.preset) + ' ' + m.start.city : ''}: ${m.moves} moves, ${m.days} days, ${(m.ms / 1000).toFixed(1)} s, ${tag}`);
|
||||
if (verbose && m.log) console.log(m.log.map((l) => ' ' + l).join('\n'));
|
||||
}
|
||||
feed();
|
||||
});
|
||||
c.on('exit', () => { if (--live === 0) done(); });
|
||||
}
|
||||
}
|
||||
|
||||
if (has('--child')) child(); else parent();
|
||||
58
scripts/test-timings.js
Normal file
58
scripts/test-timings.js
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
#!/usr/bin/env node
|
||||
// Times each tests/*.test.js on its own and writes tests/durations.json (seconds per file), which
|
||||
// `npm test -- --shard i/n` uses to split the files into parts of about equal time.
|
||||
// Run it after adding or growing slow tests; it takes a few minutes. Files run as many at once as the
|
||||
// machine has cores, so absolute numbers vary, but their sizes relative to each other are what count.
|
||||
//
|
||||
// npm run test:timings
|
||||
// node scripts/test-timings.js --merge DIR (CI) fold the parts' --timings files into it
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawn } = require('node:child_process');
|
||||
|
||||
const root = path.join(__dirname, '..');
|
||||
const dir = path.join(root, 'tests');
|
||||
|
||||
// --merge DIR: fold the timings CI's parts wrote (scripts/test.js --timings) into tests/durations.json. Files that are
|
||||
// gone drop out; files no part ran keep their old time.
|
||||
const mi = process.argv.indexOf('--merge');
|
||||
if (mi >= 0) {
|
||||
const from = process.argv[mi + 1], dur = path.join(dir, 'durations.json');
|
||||
let out = {};
|
||||
try { out = JSON.parse(fs.readFileSync(dur, 'utf8')); } catch (e) { /* none yet */ }
|
||||
let n = 0;
|
||||
for (const f of fs.readdirSync(from, { recursive: true }).filter((f) => String(f).endsWith('.json'))) {
|
||||
for (const [k, v] of Object.entries(JSON.parse(fs.readFileSync(path.join(from, String(f)), 'utf8')))) if (v > 0) { out[k] = v; n++; }
|
||||
}
|
||||
const have = new Set(fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).map((f) => 'tests/' + f));
|
||||
const sorted = Object.fromEntries(Object.keys(out).filter((k) => have.has(k)).sort().map((k) => [k, out[k]]));
|
||||
fs.writeFileSync(dur, JSON.stringify(sorted, null, 1) + '\n');
|
||||
console.log(`merged ${n} timings; tests/durations.json has ${Object.keys(sorted).length} of ${have.size} files`);
|
||||
process.exit(0);
|
||||
}
|
||||
const files = fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => 'tests/' + f);
|
||||
const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism());
|
||||
const out = {};
|
||||
let next = 0, failed = 0;
|
||||
|
||||
function run() {
|
||||
if (next >= files.length) return Promise.resolve();
|
||||
const f = files[next++], t = performance.now();
|
||||
return new Promise((res) => {
|
||||
const p = spawn(process.execPath, ['--test', f], { cwd: root, stdio: 'ignore' });
|
||||
p.on('close', (code) => {
|
||||
out[f] = Math.round((performance.now() - t) / 100) / 10;
|
||||
if (code) { failed++; console.log(`✗ ${f} failed (timed anyway)`); }
|
||||
console.log(`${String(out[f]).padStart(6)}s ${f}`);
|
||||
res();
|
||||
});
|
||||
}).then(run);
|
||||
}
|
||||
|
||||
Promise.all(Array.from({ length: jobs }, run)).then(() => {
|
||||
const sorted = Object.fromEntries(Object.keys(out).sort().map((k) => [k, out[k]]));
|
||||
fs.writeFileSync(path.join(dir, 'durations.json'), JSON.stringify(sorted, null, 1) + '\n');
|
||||
const sum = Object.values(out).reduce((a, b) => a + b, 0);
|
||||
console.log(`${files.length} files, ${Math.round(sum)} s in all; wrote tests/durations.json${failed ? ` (${failed} failed)` : ''}`);
|
||||
});
|
||||
100
scripts/test.js
100
scripts/test.js
|
|
@ -1,16 +1,104 @@
|
|||
#!/usr/bin/env node
|
||||
// Runs every tests/*.test.js, one file at a time. New test files are picked up on their own, so adding
|
||||
// one never touches package.json (and never conflicts with someone else adding theirs).
|
||||
// Runs every tests/*.test.js, each file in its own process, as many at once as the machine has cores. New test
|
||||
// files are picked up on their own, so adding one never touches package.json (and never conflicts with someone
|
||||
// else adding theirs).
|
||||
//
|
||||
// npm test everything
|
||||
// npm test -- tests/peering.test.js just these files (other arguments go to node --test)
|
||||
// npm test -- --shard 2/4 one of four parts of about equal time
|
||||
// npm test -- --shard 2/4 --list which files that part holds, without running them
|
||||
// node scripts/test.js --plan 6 the split into 6 parts as JSON (CI's plan job: one list per runner)
|
||||
// npm test -- --timings out.json also write each file's seconds to out.json (CI merges these into
|
||||
// the durations the next run splits by)
|
||||
// TEST_JOBS=1 npm test one file at a time, as it used to be
|
||||
// npm test -- --stress 8 tests/x.test.js hunt a flaky test: 8 copies of these files at once, on a machine kept
|
||||
// busier than CI ever is, and how many runs failed (and why)
|
||||
//
|
||||
// Parts are balanced by tests/durations.json, each file's typical seconds. CI keeps it fresh in its cache from every
|
||||
// run on main (.github/workflows/ci.yml); npm run test:timings rewrites the committed copy. A file missing from it
|
||||
// counts as a typical one, so a stale list only makes the parts a little uneven.
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { spawnSync } = require('node:child_process');
|
||||
const { spawn, spawnSync } = require('node:child_process');
|
||||
|
||||
const dir = path.join(__dirname, '..', 'tests');
|
||||
const root = path.join(__dirname, '..');
|
||||
const dir = path.join(root, 'tests');
|
||||
const args = process.argv.slice(2);
|
||||
const files = args.some((a) => a.endsWith('.test.js')) ? [] :
|
||||
|
||||
const list = args.includes('--list');
|
||||
if (list) args.splice(args.indexOf('--list'), 1);
|
||||
let stress = 0;
|
||||
const ti = args.indexOf('--stress');
|
||||
if (ti >= 0) {
|
||||
stress = parseInt(args[ti + 1], 10);
|
||||
if (!(stress >= 1)) { console.error('--stress wants a count, like --stress 8'); process.exit(2); }
|
||||
args.splice(ti, 2);
|
||||
}
|
||||
let timings = null;
|
||||
const tmi = args.indexOf('--timings');
|
||||
if (tmi >= 0) { timings = args[tmi + 1]; args.splice(tmi, 2); if (!timings) { console.error('--timings wants a file'); process.exit(2); } }
|
||||
let plan = 0;
|
||||
const pi = args.indexOf('--plan');
|
||||
if (pi >= 0) { plan = parseInt(args[pi + 1], 10); args.splice(pi, 2); if (!(plan >= 1)) { console.error('--plan wants a count, like --plan 6'); process.exit(2); } }
|
||||
let shard = null;
|
||||
const si = args.indexOf('--shard');
|
||||
if (si >= 0) {
|
||||
const m = /^(\d+)\/(\d+)$/.exec(args[si + 1] || '');
|
||||
if (!m || +m[1] < 1 || +m[1] > +m[2]) { console.error('--shard wants i/n, like 2/4'); process.exit(2); }
|
||||
shard = [+m[1], +m[2]];
|
||||
args.splice(si, 2);
|
||||
}
|
||||
|
||||
let files = args.some((a) => a.endsWith('.test.js')) ? [] :
|
||||
fs.readdirSync(dir).filter((f) => f.endsWith('.test.js')).sort().map((f) => path.join('tests', f));
|
||||
const r = spawnSync(process.execPath, ['--test', '--test-concurrency=1', ...args, ...files], { stdio: 'inherit', cwd: path.join(__dirname, '..') });
|
||||
|
||||
// Longest first, each onto the part with the least so far: parts within a file's length of each other.
|
||||
function part(list, i, n) {
|
||||
let dur = {};
|
||||
try { dur = JSON.parse(fs.readFileSync(path.join(dir, 'durations.json'), 'utf8')); } catch (e) { /* none yet: by count */ }
|
||||
const known = list.map((f) => dur[f.replace(/\\/g, '/')]).filter((s) => s > 0).sort((a, b) => a - b);
|
||||
const typical = known.length ? known[known.length >> 1] : 1;
|
||||
const w = (f) => dur[f.replace(/\\/g, '/')] > 0 ? dur[f.replace(/\\/g, '/')] : typical;
|
||||
const load = Array(n).fill(0), out = Array.from({ length: n }, () => []);
|
||||
for (const f of list.slice().sort((a, b) => w(b) - w(a) || a.localeCompare(b))) {
|
||||
let k = 0;
|
||||
for (let j = 1; j < n; j++) if (load[j] < load[k]) k = j;
|
||||
load[k] += w(f); out[k].push(f);
|
||||
}
|
||||
return out[i - 1].sort();
|
||||
}
|
||||
if (plan) {
|
||||
console.log(JSON.stringify(Array.from({ length: plan }, (_, i) => part(files, i + 1, plan).join(' '))));
|
||||
process.exit(0);
|
||||
}
|
||||
if (shard && files.length) {
|
||||
files = part(files, shard[0], shard[1]);
|
||||
console.log(`# part ${shard[0]}/${shard[1]}: ${files.length} files`);
|
||||
if (list) { for (const f of files) console.log(f); process.exit(0); }
|
||||
// node --test with no files would run every test it can find: an empty part has nothing to do.
|
||||
if (!files.length) process.exit(0);
|
||||
}
|
||||
|
||||
const jobs = Math.max(1, parseInt(process.env.TEST_JOBS, 10) || os.availableParallelism());
|
||||
// Stress: N runs of the same files at once, each its own node --test, so they fight for the CPU the way the four
|
||||
// CI parts and their own parallel files do (and worse). A test that only passes on a quiet machine fails here.
|
||||
if (stress) {
|
||||
if (!args.some((a) => a.endsWith('.test.js'))) { console.error('--stress wants the test files to run, like tests/agent-relay.test.js'); process.exit(2); }
|
||||
const runs = Array.from({ length: stress }, (_, i) => new Promise((res) => {
|
||||
const c = spawn(process.execPath, ['--test', '--test-reporter=dot', ...args], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let out = ''; c.stdout.on('data', (d) => { out += d; }); c.stderr.on('data', (d) => { out += d; });
|
||||
c.on('close', (code) => res({ i: i + 1, code, out }));
|
||||
}));
|
||||
Promise.all(runs).then((rs) => {
|
||||
const bad = rs.filter((r) => r.code !== 0);
|
||||
for (const r of bad) console.log(`\n--- run ${r.i} failed ---\n${r.out.slice(-4000)}`);
|
||||
console.log(`\n# stress: ${rs.length - bad.length} of ${rs.length} runs passed, ${stress} at once on ${os.availableParallelism()} cores`);
|
||||
process.exit(bad.length ? 1 : 0);
|
||||
});
|
||||
return;
|
||||
}
|
||||
const rep = timings ? ['--test-reporter=spec', '--test-reporter-destination=stdout',
|
||||
`--test-reporter=${path.join(__dirname, 'lib', 'timings-reporter.js')}`, `--test-reporter-destination=${timings}`] : [];
|
||||
const r = spawnSync(process.execPath, ['--test', `--test-concurrency=${jobs}`, ...rep, ...args, ...files], { stdio: 'inherit', cwd: root });
|
||||
process.exit(r.status ?? 1);
|
||||
|
|
|
|||
242
scripts/weekly-architect.js
Normal file
242
scripts/weekly-architect.js
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
#!/usr/bin/env node
|
||||
// The weekly Architect run generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml
|
||||
// runs it to publish site/architect/weekly/<key>.json, which the game fetches when Puzzles opens
|
||||
// (src/game/60-features/98-architect-weekly.js). It plays the real game headless, so the briefs are judged by the game's
|
||||
// own checklist and chaos monkey review.
|
||||
//
|
||||
// node scripts/weekly-architect.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
|
||||
// node scripts/weekly-architect.js --key 2026-W45 that week (--force replaces an existing file)
|
||||
// node scripts/weekly-architect.js --next 3 this week and the next two
|
||||
// node scripts/weekly-architect.js --check re-play every week not over yet; one whose reference no longer
|
||||
// earns three stars is regenerated with rev + 1; then validate every file
|
||||
// --page FILE / --dir DIR another build of the game / where the files live
|
||||
//
|
||||
// How a run is made: an HQ in a region the last weeks did not have, and its nearest cities as the sites to come. Then a
|
||||
// reference architect plays it brief by brief, and each brief is designed against the network it has built so far, so
|
||||
// every brief asks for something new: a site to connect, a site that one cut would strand made mission-critical, a ring
|
||||
// it does not have yet, a latency cap its paths miss, a site that closes. The reference builds the cheapest fix it finds
|
||||
// (connect to the nearest POP; for a site a cut strands, the cheapest tube from the stranded side to the rest on another
|
||||
// trench or cable) until the game's review passes. Its tube count is the brief's plan, its spend plus a little the
|
||||
// budget, and the whole run is then replayed from the file and must earn three stars.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { game, world } = require('./weekly-puzzle');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SCHEMA = 1, HISTORY = 4, ATTEMPTS = 40, DEM_MAX = 380;
|
||||
const NAMES = ['architect_weekly.name_all_roads_lead_to_hq', 'architect_weekly.name_the_hq_job', 'architect_weekly.name_hq_and_friends'];
|
||||
const JOKES = ['architect_weekly.joke_hq_signed_the_lease', 'architect_weekly.joke_one_network_a_handful'];
|
||||
|
||||
const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
|
||||
function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
|
||||
const pick = (r, a) => a[Math.floor(r() * a.length)];
|
||||
const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
|
||||
const ceil10k = (x) => Math.ceil(x / 10000) * 10000;
|
||||
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
|
||||
const J = (ev, code) => JSON.parse(ev(`JSON.stringify(${code})`));
|
||||
|
||||
// ---------- playing the game ----------
|
||||
// Load a run definition into the page as this week's, with the briefs known so far.
|
||||
function stage(ev, key, hq, briefs) {
|
||||
ev(`UI.arWk={key:'${key}',def:{id:arWkId('${key}'),key:'${key}',wk:true,n:'',j:'',hq:'${hq}',via:[],budget:2e7,briefs:${lit(briefs)},rev:1},at:Date.now()}`);
|
||||
}
|
||||
// Lay one tube the way a player does: a diverse trench when the pair already has one overland. The size is what all
|
||||
// the traffic needs (100G, or 400G once there is more than 100G), smaller where a long cable cannot take it.
|
||||
const tierFor = (ev) => (ev('S.pz.cities.reduce((a,c)=>a+(c===S.ar.hq?0:arDem(c)),0)') > 100 ? 2 : 1);
|
||||
function lay(ev, a, b, via, tier) {
|
||||
if (!ev(`!!S.pops['${a}']`)) [a, b] = [b, a];
|
||||
const n = ev('S.links.length');
|
||||
for (let t = tier == null ? tierFor(ev) : tier; t >= 0; t--) {
|
||||
ev(`ACT.pzLinkTo({a:'${a}',b:'${b}'});ACT.pzVia({v:'${via}'});ACT.pzDiv({v:1});ACT.pzLink({tier:${t}});closeModal()`);
|
||||
if (ev('S.links.length') === n + 1) return [a, b, via, t];
|
||||
if (tier != null) break;
|
||||
}
|
||||
throw new Error(`could not lay ${a}-${b} ${via}`);
|
||||
}
|
||||
// One step of a reference, as the file keeps it: a tube [a, b, route, size], ['@rm', city] closing a POP, or
|
||||
// ['@tier', n, size] resizing the n-th tube.
|
||||
function step(ev, s) {
|
||||
if (s[0] === '@rm') { ev(`ACT.pzRmPop({city:'${s[1]}'})`); return; }
|
||||
if (s[0] === '@tier') { const n = ev(`(()=>{const l=S.links[${s[1]}];ACT.pzTier({id:l.id,tier:${s[2]}});return S.links[${s[1]}].tier;})()`); if (n !== s[2]) throw new Error(`could not resize tube ${s[1]}`); return; }
|
||||
lay(ev, s[0], s[1], s[2], s[3]);
|
||||
}
|
||||
// Room for the traffic: upsize the busiest tube that is not cut (or, when it cannot grow, lay a second one beside it).
|
||||
function makeRoom(ev, W, steps, cut) {
|
||||
const ls = J(ev, `(()=>{${cut ? `for(const l of S.links)if(pzUnit(l)===${lit(cut)})l.cut=1;` : ''}compute();const o=S.links.map((l,i)=>({i,a:l.a,b:l.b,cut:!!l.cut,tier:l.tier,u:(R.load[l.id]||0)/capOf(l)})).filter(x=>!x.cut).sort((x,y)=>y.u-x.u);for(const l of S.links)l.cut=0;compute();return o;})()`);
|
||||
for (const l of ls.slice(0, 3)) {
|
||||
if (l.tier < 2) { const t = ev(`(()=>{const l=S.links[${l.i}];ACT.pzTier({id:l.id,tier:${l.tier + 1}});return S.links[${l.i}].tier;})()`); if (t === l.tier + 1) { steps.push(['@tier', l.i, t]); return; } }
|
||||
const o = W.opts(l.a, l.b).filter((x) => !x.second).sort((x, y) => x.cost - y.cost)[0];
|
||||
if (o) { try { steps.push(lay(ev, o.a, o.b, o.via)); return; } catch (e) { /* try the next tube */ } }
|
||||
}
|
||||
throw new Error('no room to be made');
|
||||
}
|
||||
// What the review would say: the first cut that strands a mission-critical site or leaves a site short.
|
||||
const reviewFail = (ev) => J(ev, `(()=>{let f=null;for(const u of [...new Set(S.links.map(pzUnit))]){const x=arCut(u);for(const l of x.ls)l.cut=0;if(x.gold.length||x.short.length){f={u,gold:x.gold,short:x.short,dark:x.dark};break;}}compute();return f;})()`);
|
||||
const passes = (ev) => ev('arShowStart();arShowSkip();S.ar.passed===pzSig()');
|
||||
|
||||
// The reference architect: fix what the checklist and the review find, cheapest first, until the brief passes.
|
||||
function solveBrief(ev, W, steps) {
|
||||
for (let guard = 0; guard < 24; guard++) {
|
||||
for (const c of J(ev, 'S.pz.avoid.filter(c=>S.pops[c])')) { ev(`ACT.pzRmPop({city:'${c}'})`); steps.push(['@rm', c]); }
|
||||
const e = J(ev, '(()=>{const e=arEval(),r=[...arReach(S.ar.hq,arAdj())];return {conn:e.conn,lat:e.lat,rings:e.rings,ready:e.ready,why:e.why,r,miss:e.sites.filter(s=>!s.ok).map(s=>s.c)};})()');
|
||||
const best = (from, to, skip) => { let o = null; for (const a of from) for (const b of to) if (a !== b) for (const x of W.opts(a, b)) if (!x.second && x.unit !== skip && (!o || x.cost < o.cost)) o = x; return o; };
|
||||
if (!e.conn) { const c = e.miss[0], o = best([c], e.r); if (!o) throw new Error(`no way to ${c}`); steps.push(lay(ev, o.a, o.b, o.via)); continue; }
|
||||
if (e.lat && !e.lat.ok) { const os = W.opts(e.lat.a, e.lat.b).filter((x) => !x.second && x.ms <= e.lat.cap).sort((x, y) => x.cost - y.cost); if (!os.length) throw new Error('latency cap out of reach'); steps.push(lay(ev, os[0].a, os[0].b, os[0].via)); continue; }
|
||||
const rg = e.rings.find((x) => !x.ok);
|
||||
if (rg) { const cs = rg.cs, has = J(ev, 'S.links.map(l=>edgeKey(l))'); let done = false;
|
||||
for (let i = 0; i < cs.length && !done; i++) { const a = cs[i], b = cs[(i + 1) % cs.length]; if (has.includes(ev(`edgeKey({a:'${a}',b:'${b}'})`))) continue; const o = best([a], [b]); if (o) { steps.push(lay(ev, o.a, o.b, o.via)); done = true; } }
|
||||
if (!done) throw new Error('ring out of reach'); continue; }
|
||||
if (!e.ready) { if (/thin/i.test(e.why) || J(ev, 'arEval().sites.some(s=>!s.full)')) { makeRoom(ev, W, steps, null); continue; } throw new Error(`not ready: ${e.why}`); }
|
||||
const f = reviewFail(ev); if (!f) return;
|
||||
if (f.short.length && !f.gold.length) { makeRoom(ev, W, steps, f.u); continue; }
|
||||
// A cut strands a mission-critical site: join the stranded side to the rest another way.
|
||||
const rest = J(ev, `Object.keys(S.pops).filter(c=>!${lit(f.dark)}.includes(c))`), o = best(f.dark, rest, f.u);
|
||||
if (!o) throw new Error('no second way'); steps.push(lay(ev, o.a, o.b, o.via));
|
||||
}
|
||||
throw new Error('the brief would not pass');
|
||||
}
|
||||
|
||||
// ---------- designing a run ----------
|
||||
// The brief kinds after the first two. Each is designed against the reference network as it stands, or refused (null).
|
||||
function design(kind, ev, W, r, s) {
|
||||
const pops = J(ev, 'S.pz.cities'), gold = J(ev, 'S.ar.gold'), hq = s.hq, next = () => s.todo.shift(), dem = (c) => { const g = Math.min(s.room, pick(r, [10, 20, 20, 30])); s.room -= g; return { [c]: g }; };
|
||||
const weak = J(ev, `S.pz.cities.filter(c=>c!==S.ar.hq&&!S.ar.gold.includes(c)&&[...new Set(S.links.map(pzUnit))].some(u=>arDark(u).includes(c)))`);
|
||||
if (kind === 'gold') { if (!weak.length) return null; const c = weak.sort((a, b) => W.km(hq, b) - W.km(hq, a))[0]; return { gold: [c] }; }
|
||||
if (kind === 'addgold') { if (!s.todo.length || s.room < 10) return null; const c = next(); return { add: [c], dem: dem(c), gold: [c] }; }
|
||||
if (kind === 'move') { const c = pops.filter((x) => x !== hq && !gold.includes(x) && !(s.lat || []).includes(x)).sort((a, b) => W.km(hq, b) - W.km(hq, a))[0];
|
||||
if (!c || !s.todo.length || s.room < 10) return null; const n = next(); return { drop: [c], add: [n], dem: dem(n), gold: [n] }; }
|
||||
if (kind === 'lat') { let bestP = null;
|
||||
for (const a of pops) for (const b of pops) { if (a >= b) continue; const cur = J(ev, `arLat('${a}','${b}')`), os = W.opts(a, b).filter((x) => !x.second); if (cur == null || !os.length) continue;
|
||||
const ms = Math.min(...os.map((x) => x.ms)), cap = Math.ceil(ms * 1.12 * 10) / 10; if (cap < 2 || cap >= cur * 0.85) continue;
|
||||
if (!bestP || cur / cap > bestP.k) bestP = { a, b, cap, k: cur / cap }; }
|
||||
if (!bestP) return null; s.lat = [bestP.a, bestP.b]; return { lat: [bestP.a, bestP.b, bestP.cap] }; }
|
||||
if (kind === 'grow') { const cs = pops.filter((c) => c !== hq).map((c) => [c, ev(`arDem('${c}')`)]).sort((x, y) => y[1] - x[1]); if (!cs.length || s.room < 60) return null;
|
||||
const [c, d] = cs[0], g = d + Math.min(s.room, pick(r, [60, 90, 120])); s.room -= g - d; return { dem: { [c]: g } }; }
|
||||
if (kind === 'ring') { const cs = pops.filter((c) => c !== hq).sort((a, b) => W.km(hq, a) - W.km(hq, b)).slice(0, 2); if (cs.length < 2) return null;
|
||||
const ring = [hq, ...cs]; if (ev(`arRingOk(${lit(ring)})`)) return null; return { ring }; }
|
||||
return null;
|
||||
}
|
||||
|
||||
// Play a run from scratch: stage, start, then brief by brief design (when designing) or follow the file, solve, review, next.
|
||||
function play(g, W, key, hq, plan, r, sites) {
|
||||
const { ev } = g, briefs = [], steps = [], s = { hq, todo: sites.slice(), room: DEM_MAX, lat: null };
|
||||
const first = () => { const c = s.todo.shift(), g0 = Math.min(s.room, pick(r, [20, 30, 40])); s.room -= g0; return { add: [c], dem: { [c]: g0 } }; };
|
||||
for (let i = 0; i < plan.length; i++) {
|
||||
let b = null;
|
||||
if (plan[i] === 'add1') b = first();
|
||||
else if (plan[i] === 'add2') { if (s.todo.length < 2) throw new Error('not enough sites'); const a = s.todo.shift(), c = s.todo.shift(), ga = Math.min(s.room, 20); s.room -= ga; const gc = Math.min(s.room, pick(r, [10, 20])); s.room -= gc; b = { add: [a, c], dem: { [a]: ga, [c]: gc } }; }
|
||||
// A kind that cannot be made here gives way to one the run has not had yet, then to a new mission-critical site.
|
||||
else for (const k of [plan[i], ...['lat', 'ring', 'move', 'grow', 'gold'].filter((x) => !plan.slice(0, i).includes(x) && x !== plan[i]), 'addgold']) { b = design(k, ev, W, r, s); if (b) { plan[i] = k; break; } }
|
||||
if (!b) throw new Error(`brief ${i + 1}: nothing left to ask`);
|
||||
b.tubes = 9; briefs.push(b); stage(ev, key, hq, briefs.map((x) => Object.assign({ t: '' }, x)));
|
||||
if (i === 0) ev(`ACT.pzArStart({id:arWkId('${key}')})`); else ev('ACT.pzArNext()');
|
||||
if (ev('S.ar.bi') !== i) throw new Error(`brief ${i + 1} did not start`);
|
||||
const st = []; solveBrief(ev, W, st); steps.push(st);
|
||||
b.tubes = ev('S.links.filter(l=>(l.br|0)===S.ar.bi).length');
|
||||
if (!st.length) throw new Error(`brief ${i + 1} asks for nothing new`);
|
||||
ev(`UI.arWk.def.briefs[${i}].tubes=${b.tubes}`);
|
||||
if (!passes(ev)) throw new Error(`brief ${i + 1}: the review does not pass`);
|
||||
}
|
||||
return { briefs, steps, spend: ev('arSpend()') };
|
||||
}
|
||||
|
||||
// Replay a file the way a player would, from its own reference: it must pass every brief and earn three stars.
|
||||
function verify(g, j, key) {
|
||||
const { ev } = g, def = J(ev, `arWkValid(${lit(j)},'${key}')`);
|
||||
if (!def) return { ok: false, why: 'the game rejects it' };
|
||||
if (!j.ref || !Array.isArray(j.ref.steps) || j.ref.steps.length !== def.briefs.length) return { ok: false, why: 'no reference' };
|
||||
try {
|
||||
ev(`UI.arWk={key:'${key}',def:arWkValid(${lit(j)},'${key}'),at:Date.now()}`);
|
||||
ev(`ACT.pzArStart({id:arWkId('${key}')})`);
|
||||
for (let i = 0; i < def.briefs.length; i++) {
|
||||
for (const st of j.ref.steps[i]) step(ev, st);
|
||||
if (!passes(ev)) return { ok: false, why: `brief ${i + 1} does not pass` };
|
||||
if (i < def.briefs.length - 1) ev('ACT.pzArNext()');
|
||||
}
|
||||
const sp = ev('arSpend()'), stars = ev(`arStars(${sp})`);
|
||||
ev('arStop(true)');
|
||||
return stars === 3 ? { ok: true, spend: sp } : { ok: false, why: `the reference earns ${stars} stars (spend ${sp}, budget ${j.budget})` };
|
||||
} catch (e) { return { ok: false, why: e.message }; }
|
||||
}
|
||||
|
||||
function generate(g, key, dir) {
|
||||
const { ev } = g, W = world(ev);
|
||||
// The regions of the last weeks, so the HQ moves around the world.
|
||||
const past = list(dir).filter((k) => k < key).map((k) => { try { return JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')).hq; } catch (e) { return null; } });
|
||||
const recent = past.slice(-HISTORY).map((c) => W.C[c] && W.C[c].reg), used = past.slice(-12);
|
||||
for (let attempt = 0; attempt < ATTEMPTS; attempt++) {
|
||||
const r = rng(hash(`architect|${key}|${attempt}`));
|
||||
const hqs = W.cities.filter((c) => !used.includes(c.id) && (!recent.includes(c.reg) || attempt >= ATTEMPTS / 2));
|
||||
const hq = pick(r, hqs).id;
|
||||
const near = W.cities.filter((c) => c.id !== hq && c.reg === W.C[hq].reg && W.km(hq, c.id) < 2500).sort((a, b) => W.km(hq, a.id) - W.km(hq, b.id)).slice(0, 8).map((c) => c.id);
|
||||
if (near.length < 6) continue;
|
||||
const mid = shuffle(r, ['lat', 'ring', 'move', 'addgold', 'grow']).slice(0, r() < 0.5 ? 2 : 3);
|
||||
const plan = ['add1', 'add2', 'gold', ...mid, 'gold'];
|
||||
const sites = [...near.slice(0, 3), ...shuffle(r, near.slice(3))];
|
||||
try {
|
||||
const run = play(g, W, key, hq, plan, r, sites);
|
||||
const jk = pick(r, JOKES), j = { v: SCHEMA, key, hq, budget: ceil10k(run.spend * 1.06), name: { l: pick(r, NAMES), p: { hq } }, joke: { l: jk, p: jk === JOKES[0] ? { hq } : {} }, briefs: run.briefs, ref: { spend: run.spend, steps: run.steps } };
|
||||
const v = verify(g, j, key);
|
||||
if (!v.ok) { if (process.env.DEBUG) console.warn(`${key} #${attempt}: ${v.why}`); continue; }
|
||||
return j;
|
||||
} catch (e) { if (process.env.DEBUG) console.warn(`${key} #${attempt} (${hq}): ${e.message}`); }
|
||||
}
|
||||
throw new Error(`${key}: no run survived verification`);
|
||||
}
|
||||
|
||||
// --check: every file is what the game accepts, under its own name, and the weeks still to come earn three stars.
|
||||
function check(g, dir, now = Date.now()) {
|
||||
const { ev } = g, bad = [], keys = list(dir);
|
||||
for (const k of keys) {
|
||||
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
|
||||
if (!ev(`!!arWkValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
|
||||
}
|
||||
if (keys.length) {
|
||||
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ }
|
||||
if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files');
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
// A release can change prices under weeks already out: a week not over yet whose reference no longer earns three stars
|
||||
// is regenerated with its rev up, so players' stars for that week (only that week) start again. Past weeks stay.
|
||||
function refresh(g, dir, now = Date.now()) {
|
||||
const { ev } = g, fixed = [], bad = [];
|
||||
for (const k of list(dir)) {
|
||||
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated below */ }
|
||||
const valid = !!j && ev(`!!arWkValid(${lit(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
if (valid && (!live || verify(g, j, k).ok)) continue;
|
||||
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
|
||||
try { writeWeek(dir, Object.assign(generate(g, k, dir), { rev })); fixed.push(`${k}: regenerated as rev ${rev}`); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); }
|
||||
}
|
||||
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
|
||||
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
|
||||
return { fixed, bad };
|
||||
}
|
||||
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
|
||||
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
|
||||
const say = (j) => `${j.key}: HQ ${j.hq}, ${j.briefs.length} briefs (${j.briefs.map((b) => Object.keys(b).filter((k) => k !== 'tubes' && (k !== 'dem' || !b.add)).map((k) => (k === 'dem' ? 'grow' : k)).join('+')).join(', ')}), budget ${j.budget}, reference ${j.ref.spend}`;
|
||||
|
||||
module.exports = { generate, verify, check, refresh, writeWeek, writeIndex, list, say, step };
|
||||
|
||||
if (require.main === module) {
|
||||
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
|
||||
const dir = path.resolve(ROOT, opt('--dir', 'site/architect/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
|
||||
if (!g.ev("typeof arWkValid==='function'")) { console.log('This game has no weekly Architect runs yet.'); process.exit(0); }
|
||||
if (args.includes('--check')) {
|
||||
const r = refresh(g, dir);
|
||||
for (const x of r.fixed) console.log(`fixed: ${x}`);
|
||||
const bad = [...r.bad, ...check(g, dir)];
|
||||
for (const b of bad) console.error(`error: ${b}`);
|
||||
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly Architect run(s) OK`);
|
||||
process.exit(bad.length ? 1 : 0);
|
||||
}
|
||||
const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const key = g.ev(`pzKeyAdd('${first}',${i})`);
|
||||
if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); }
|
||||
if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; }
|
||||
const j = generate(g, key, dir); writeWeek(dir, j); console.log(say(j));
|
||||
}
|
||||
}
|
||||
413
scripts/weekly-puzzle.js
Normal file
413
scripts/weekly-puzzle.js
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
#!/usr/bin/env node
|
||||
// The weekly puzzle generator. Every Sunday .github/workflows/weekly-puzzle.yml runs it to publish that week's
|
||||
// puzzle as a static file, site/puzzles/weekly/<key>.json, which the game fetches when Puzzles opens
|
||||
// (src/game/60-features/93-puzzles-weekly.js). It loads the real game headless (tests/harness.js), so it uses the
|
||||
// game's own cities, cables, prices, week keys, file validator and star code.
|
||||
//
|
||||
// node scripts/weekly-puzzle.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
|
||||
// node scripts/weekly-puzzle.js --key 2026-W45 that week (--force replaces an existing file)
|
||||
// node scripts/weekly-puzzle.js --next 3 this week and the next two
|
||||
// node scripts/weekly-puzzle.js --check regenerate weeks not over yet whose budget this game no longer verifies
|
||||
// (see refresh()), then validate every file; fails only if that fails
|
||||
// --page FILE play another build of the game (the live release), see the workflow
|
||||
// --dir DIR where the files live (default site/puzzles/weekly)
|
||||
//
|
||||
// How a puzzle is made: pick a theme the last weeks did not have, choose 4-6 cities for it (avoiding last weeks'
|
||||
// cities) and the traffic they carry (content in the first city, eyeballs in the others; a latency sprint adds a
|
||||
// circuit with a latency cap). Search for the cheapest topology that connects them and the cheapest one that survives
|
||||
// any single cut (a whole cable or a trench), then size each with the game's own routing (scripts/lib/puzzle-solver.js):
|
||||
// links and routers big enough for every flow, after any single cut too, then as small as they can be. The budget is
|
||||
// that N-1 build plus a little. Both reference builds are judged by the game's own star code and must earn their
|
||||
// stars, or the candidate is thrown away and another one tried.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SV = require('./lib/puzzle-solver');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
const SCHEMA = 2, HISTORY = 4, THEME_GAP = 3, REG_GAP = 2, ATTEMPTS = 40, KEEP = 6;
|
||||
const THEMES = ['tour', 'ring', 'detour', 'ocean', 'islands', 'sprint'];
|
||||
|
||||
// ---------- the game, headless ----------
|
||||
function game(file) {
|
||||
const { load } = require('../tests/harness');
|
||||
let g = load(file ? { file } : {});
|
||||
if (file && !g.ev("typeof pzWkValid==='function'")) {
|
||||
console.warn(`warning: ${file} has no published weekly puzzles yet; using src/ instead`);
|
||||
g = load();
|
||||
}
|
||||
SV.install(g.ev);
|
||||
// N-1 counts a whole cable as one failure (every segment of a cable shares its risk), as the solver does.
|
||||
if (g.ev("pzUnit({cable:'x',a:'a',b:'b'})") !== 'cab:x') throw new Error('this game counts cable segments separately; the solver would not match its N-1 check');
|
||||
return g;
|
||||
}
|
||||
|
||||
// ---------- small helpers ----------
|
||||
const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
|
||||
function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
|
||||
const pick = (r, a) => a[Math.floor(r() * a.length)];
|
||||
const shuffle = (r, a) => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(r() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
|
||||
const ceil10k = (x) => Math.ceil(x / 10000) * 10000;
|
||||
function perms(a) { if (a.length <= 1) return [a]; const out = []; a.forEach((x, i) => { for (const p of perms([...a.slice(0, i), ...a.slice(i + 1)])) out.push([x, ...p]); }); return out; }
|
||||
function subsets(a) { const out = []; for (let m = 0; m < 1 << a.length; m++) out.push(a.filter((_, i) => m >> i & 1)); return out; }
|
||||
|
||||
// ---------- the world, as the game prices it ----------
|
||||
function world(ev) {
|
||||
const cities = JSON.parse(ev("JSON.stringify(Object.values(CITY).filter(c=>!c.off&&!c.cn).map(c=>({id:c.id,name:c.name,lands:lands(c),reg:c.reg,P:c.P,lon:c.lon,lat:c.lat,pop:pzPopCost(c.id)})))"));
|
||||
const C = Object.fromEntries(cities.map((c) => [c.id, c]));
|
||||
const cablePairs = JSON.parse(ev('JSON.stringify(CABLE_PAIRS.map(p=>[p.cid,p.a,p.b]))')).filter(([, a, b]) => C[a] && C[b]);
|
||||
const cabs = {}; for (const [cid, a, b] of cablePairs) { (cabs[a] = cabs[a] || new Set()).add(cid); (cabs[b] = cabs[b] || new Set()).add(cid); }
|
||||
const memo = new Map();
|
||||
// Every way to join a and b: overland (first wave, and a second one on a diverse route) and each cable.
|
||||
const opts = (a, b) => {
|
||||
const k = a < b ? a + '|' + b : b + '|' + a; if (memo.has(k)) return memo.get(k);
|
||||
const rs = JSON.parse(ev(`JSON.stringify(pzRoutes('${a}','${b}').filter(r=>!subWaveWhy(0,r.km,r.sub)).map(r=>({via:r.via,cab:r.cab,sub:r.sub,ms:r.ms,c:pzLinkCost(r,0,false),c2:r.sub?0:pzLinkCost(r,0,true)})))`));
|
||||
const out = [];
|
||||
for (const r of rs) {
|
||||
if (r.cab) out.push({ a, b, via: r.via, sub: true, ms: r.ms, cost: r.c, unit: 'cab:' + r.cab });
|
||||
else { out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c, unit: `land:${k}:1` }); out.push({ a, b, via: 'land', sub: false, ms: r.ms, cost: r.c2, unit: `land:${k}:2`, second: true }); }
|
||||
}
|
||||
out.sort((x, y) => x.cost - y.cost || (x.unit < y.unit ? -1 : 1));
|
||||
memo.set(k, out); return out;
|
||||
};
|
||||
const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); };
|
||||
return { cities, C, cablePairs, cabs, opts, km };
|
||||
}
|
||||
|
||||
// ---------- judging a build (the game has the last word; this steers the search) ----------
|
||||
function judge(W, P, links) {
|
||||
const nodes = new Set(); for (const l of links) { nodes.add(l.a); nodes.add(l.b); }
|
||||
// A second overland wave on a pair needs the first one.
|
||||
for (const l of links) if (l.second && !links.some((x) => x !== l && !x.second && x.via === 'land' && x.unit === l.unit.replace(/2$/, '1'))) return null;
|
||||
if (new Set(links.map((l) => l.unit)).size !== links.length) return null;
|
||||
const cost = [...nodes].reduce((s, c) => s + W.C[c].pop, 0) + links.reduce((s, l) => s + l.cost, 0);
|
||||
const comp = (skip) => { const adj = {}; for (const l of links) if (l.unit !== skip) { (adj[l.a] = adj[l.a] || []).push(l.b); (adj[l.b] = adj[l.b] || []).push(l.a); }
|
||||
const seen = new Set([P.cities[0]]), q = [P.cities[0]]; while (q.length) { const u = q.pop(); for (const v of adj[u] || []) if (!seen.has(v)) { seen.add(v); q.push(v); } } return seen; };
|
||||
const all = comp(null);
|
||||
if (!P.cities.every((c) => all.has(c))) return { ok: false, cost };
|
||||
if (P.avoid.some((c) => nodes.has(c))) return { ok: false, cost };
|
||||
if (P.noSub && links.some((l) => l.sub)) return { ok: false, cost };
|
||||
if (P.ring) { const nb = {}; for (const l of links) { (nb[l.a] = nb[l.a] || new Set()).add(l.b); (nb[l.b] = nb[l.b] || new Set()).add(l.a); }
|
||||
if (links.length !== nodes.size || ![...nodes].every((c) => nb[c].size === 2)) return { ok: false, cost }; }
|
||||
if (P.lat) { const [a, b, ms] = P.lat, d = { [a]: 0 }, done = new Set();
|
||||
for (;;) { let u = null; for (const k in d) if (!done.has(k) && (u === null || d[k] < d[u])) u = k; if (u === null || u === b) break; done.add(u);
|
||||
for (const l of links) { const v = l.a === u ? l.b : l.b === u ? l.a : null; if (v && !(d[v] <= d[u] + l.ms)) d[v] = d[u] + l.ms; } }
|
||||
if (!(d[b] <= ms)) return { ok: false, cost }; }
|
||||
const weak = [...new Set(links.map((l) => l.unit))].filter((u) => { const g = comp(u); return !P.cities.every((c) => g.has(c)); });
|
||||
return { ok: true, cost, n1: weak.length === 0, weak };
|
||||
}
|
||||
|
||||
// ---------- the solver ----------
|
||||
// Cheapest tree over a node set (Kruskal on each pair's cheapest way), with some links forced in.
|
||||
function tree(W, nodes, forced = []) {
|
||||
const par = Object.fromEntries(nodes.map((n) => [n, n])), f = (x) => (par[x] === x ? x : (par[x] = f(par[x])));
|
||||
const out = [];
|
||||
for (const l of forced) { par[f(l.a)] = f(l.b); out.push(l); }
|
||||
const es = [];
|
||||
for (let i = 0; i < nodes.length; i++) for (let j = i + 1; j < nodes.length; j++) { const o = W.opts(nodes[i], nodes[j]).filter((x) => !x.second); if (o.length) es.push(o[0]); }
|
||||
es.sort((x, y) => x.cost - y.cost);
|
||||
for (const e of es) if (f(e.a) !== f(e.b)) { par[f(e.a)] = f(e.b); out.push(e); }
|
||||
return out.length - forced.length === nodes.length - 1 - forced.length ? out : null;
|
||||
}
|
||||
// Add the link that removes the most single points of failure per dollar, until none are left.
|
||||
function harden(W, P, nodes, links) {
|
||||
links = links.slice();
|
||||
for (let guard = 0; guard < 12; guard++) {
|
||||
const j = judge(W, P, links); if (!j || !j.ok) return null; if (j.n1) return links;
|
||||
let best = null;
|
||||
for (let i = 0; i < nodes.length; i++) for (let k = i + 1; k < nodes.length; k++) for (const o of W.opts(nodes[i], nodes[k])) {
|
||||
if (links.some((l) => l.unit === o.unit)) continue;
|
||||
const jj = judge(W, P, [...links, o]); if (!jj || !jj.ok) continue;
|
||||
const gain = j.weak.length - jj.weak.length; if (gain <= 0) continue;
|
||||
const score = gain / o.cost; if (!best || score > best.score) best = { score, o };
|
||||
}
|
||||
if (!best) return null; links.push(best.o);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// Every simple cycle through the node set, each hop by one of its three cheapest ways, cheapest first.
|
||||
function cycles(W, P, nodes, bound) {
|
||||
let best = null; const [h, ...rest] = nodes;
|
||||
if (nodes.length < 3) return null;
|
||||
for (const p of perms(rest)) {
|
||||
if (p[0] > p[p.length - 1]) continue; // each cycle once
|
||||
const ring = [h, ...p], hops = ring.map((x, i) => W.opts(x, ring[(i + 1) % ring.length]).filter((o) => !o.second).slice(0, 3));
|
||||
if (hops.some((o) => !o.length)) continue;
|
||||
const pop = ring.reduce((s, c) => s + W.C[c].pop, 0);
|
||||
const go = (i, acc, cost) => {
|
||||
if (cost >= Math.min(bound, best ? best.cost : Infinity)) return;
|
||||
if (i === hops.length) { const j = judge(W, P, acc); if (j && j.ok && j.n1) best = { cost: j.cost, links: acc.slice() }; return; }
|
||||
for (const o of hops[i]) { if (acc.some((l) => l.unit === o.unit)) continue; acc.push(o); go(i + 1, acc, cost + o.cost); acc.pop(); }
|
||||
};
|
||||
go(0, [], pop);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
function solve(W, P) {
|
||||
const vias = P.via.filter((c) => !P.avoid.includes(c));
|
||||
let one = null, three = null, naive = null;
|
||||
const keep = (cur, links) => { if (!links) return cur; const j = judge(W, P, links); if (!j || !j.ok) return cur; return !cur || j.cost < cur.cost ? { cost: j.cost, links, n1: j.n1 } : cur; };
|
||||
for (const sub of subsets(vias)) {
|
||||
const nodes = [...P.cities, ...sub];
|
||||
const forced = P.lat ? [W.opts(P.lat[0], P.lat[1]).filter((o) => !o.second).sort((x, y) => x.ms - y.ms)[0]].filter(Boolean) : [];
|
||||
const ts = [tree(W, nodes), forced.length ? tree(W, nodes, forced) : null].filter(Boolean)
|
||||
// A via city left as a leaf is money for nothing.
|
||||
.filter((t) => sub.every((v) => t.filter((l) => l.a === v || l.b === v).length >= 2));
|
||||
if (!P.ring) for (const t of ts) {
|
||||
one = keep(one, t);
|
||||
// The obvious way to survive a cut: a second, different way along every hop of the tree.
|
||||
const dbl = t.slice(); let okd = true;
|
||||
for (const l of t) { const alt = W.opts(l.a, l.b).find((o) => o.unit !== l.unit && !dbl.some((x) => x.unit === o.unit)); if (!alt) { okd = false; break; } dbl.push(alt); }
|
||||
if (okd) { const j = judge(W, P, dbl); if (j && j.ok && j.n1 && (!naive || j.cost < naive.cost)) naive = { cost: j.cost, links: dbl }; if (j && j.ok && j.n1) three = keep(three, dbl); }
|
||||
const hd = harden(W, P, nodes, t); if (hd) three = keep(three, hd);
|
||||
}
|
||||
if (nodes.length <= 7) { const c = cycles(W, P, nodes, three ? three.cost : Infinity); if (c) { three = keep(three, c.links); if (P.ring) one = keep(one, c.links); } }
|
||||
}
|
||||
return { one, three, naive };
|
||||
}
|
||||
|
||||
// ---------- themes: which cities, which twist ----------
|
||||
function pools(W) {
|
||||
const byLand = {};
|
||||
for (const c of W.cities) { const k = c.lands[0] + '/' + c.reg; (byLand[k] = byLand[k] || []).push(c.id); }
|
||||
const big = Object.values(byLand).map((g) => g.filter((c) => W.C[c].P >= 100)).filter((g) => g.length >= 6);
|
||||
const isl = W.cities.filter((c) => byLand[c.lands[0] + '/' + c.reg].length === 1 && c.lands.length === 1 && (W.cabs[c.id] || new Set()).size >= 2).map((c) => c.id);
|
||||
return { big, isl };
|
||||
}
|
||||
const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n);
|
||||
function draft(W, theme, r, banned) {
|
||||
const { big, isl } = pools(W), free = (c) => !banned.has(c);
|
||||
const P = { theme, cities: [], via: [], avoid: [], noSub: false, ring: false, lat: null };
|
||||
if (theme === 'tour' || theme === 'ring' || theme === 'detour') {
|
||||
const g = pick(r, big).filter(free);
|
||||
if (g.length < 6) return null;
|
||||
if (theme === 'detour') {
|
||||
const hub = pick(r, g.slice().sort((a, b) => W.C[b].P - W.C[a].P).slice(0, 4)), around = near(W, hub, g, 8);
|
||||
if (around.length < 6) return null;
|
||||
const sh = shuffle(r, around); P.cities = sh.slice(0, 4); P.via = sh.slice(4, 6); P.avoid = [hub];
|
||||
} else {
|
||||
const seed = pick(r, g), n = theme === 'ring' ? 4 + Math.floor(r() * 2) : 4 + Math.floor(r() * 3);
|
||||
P.cities = [seed, ...shuffle(r, near(W, seed, g, n + 2)).slice(0, n - 1)];
|
||||
if (theme === 'tour') P.via = near(W, seed, g, n + 4).filter((c) => !P.cities.includes(c)).slice(0, 1);
|
||||
P.ring = theme === 'ring';
|
||||
}
|
||||
} else if (theme === 'ocean') {
|
||||
const land = (c) => W.C[c].lands[0], ok = W.cablePairs.filter(([, a, b]) => land(a) !== land(b) && free(a) && free(b) && big.some((g) => g.includes(a)) && big.some((g) => g.includes(b)));
|
||||
if (!ok.length) return null;
|
||||
const [, a, b] = pick(r, ok), ga = big.find((g) => g.includes(a)).filter(free), gb = big.find((g) => g.includes(b)).filter(free);
|
||||
const a2 = pick(r, near(W, a, ga, 3)), b2 = pick(r, near(W, b, gb, 3));
|
||||
if (!a2 || !b2) return null;
|
||||
P.cities = [a, a2, b, b2];
|
||||
// Other landing points on either shore that cross the same ocean: the stepping stones to a second crossing.
|
||||
const shores = W.cablePairs.filter(([, x, y]) => (land(x) === land(a) && land(y) === land(b)) || (land(x) === land(b) && land(y) === land(a))).flatMap(([, x, y]) => [x, y]);
|
||||
P.via = shuffle(r, [...new Set(shores)].filter((c) => free(c) && !P.cities.includes(c))).slice(0, 2);
|
||||
} else if (theme === 'islands') {
|
||||
const i0 = pick(r, isl.filter(free)); if (!i0) return null;
|
||||
const hops = W.cablePairs.filter(([, x, y]) => x === i0 || y === i0).map(([, x, y]) => (x === i0 ? y : x));
|
||||
const islN = near(W, i0, isl.filter((c) => free(c) && W.km(i0, c) < 4500), 3), main = near(W, i0, [...new Set(hops)].filter((c) => free(c) && !isl.includes(c)), 2);
|
||||
if (!islN.length || !main.length) return null;
|
||||
P.cities = [i0, ...shuffle(r, islN).slice(0, 1 + Math.floor(r() * 2)), main[0]];
|
||||
P.via = [...new Set([...islN, ...main, ...hops])].filter((c) => !P.cities.includes(c) && free(c)).sort((x, y) => W.km(i0, x) - W.km(i0, y)).slice(0, 3);
|
||||
} else if (theme === 'sprint') {
|
||||
const ok = [];
|
||||
for (const [, a, b] of W.cablePairs) { if (!free(a) || !free(b) || W.C[a].P < 100 || W.C[b].P < 100) continue;
|
||||
const o = W.opts(a, b).filter((x) => !x.second); if (o.length < 2) continue;
|
||||
const fast = o.slice().sort((x, y) => x.ms - y.ms)[0], cheap = o[0];
|
||||
if (fast.unit !== cheap.unit && fast.ms < cheap.ms * 0.94 && fast.ms >= 5) ok.push([a, b, fast.ms, cheap.ms]); }
|
||||
if (!ok.length) return null;
|
||||
const [a, b, fms, cms] = pick(r, ok.sort((x, y) => (x[0] + x[1] < y[0] + y[1] ? -1 : 1)));
|
||||
const ms = Math.ceil(fms * 1.04 + 0.5); if (ms >= cms) return null;
|
||||
const ga = big.find((g) => g.includes(a)) || [], gb = big.find((g) => g.includes(b)) || [];
|
||||
const extra = [...near(W, a, ga.filter(free), 2), ...near(W, b, gb.filter(free), 2)];
|
||||
P.cities = [a, b, ...shuffle(r, extra).slice(0, 1 + Math.floor(r() * 2))];
|
||||
P.via = W.cablePairs.filter(([, x, y]) => [x, y].includes(a) || [x, y].includes(b)).flatMap(([, x, y]) => [x, y]).filter((c, i, s) => s.indexOf(c) === i && free(c) && !P.cities.includes(c)).sort((x, y) => W.km(a, x) - W.km(a, y)).slice(0, 2);
|
||||
P.lat = [a, b, ms];
|
||||
}
|
||||
if (new Set([...P.cities, ...P.via, ...P.avoid]).size !== P.cities.length + P.via.length + P.avoid.length) return null;
|
||||
if (P.cities.length < 3 || P.cities.length > 6) return null;
|
||||
// The traffic: content in the first city, eyeballs in the others (less across an ocean, where waves are dear), and
|
||||
// for a sprint a circuit between its two cities under the latency cap.
|
||||
const far = theme === 'ocean' || theme === 'islands', sizes = far ? [5, 8, 10, 15] : [10, 20, 30, 40, 60];
|
||||
P.src = [P.cities[0]];
|
||||
P.dem = P.cities.slice(1).map((c) => ({ t: 'eye', a: c, g: pick(r, sizes) }));
|
||||
if (P.lat) P.dem.unshift({ t: 'l2', a: P.lat[0], b: P.lat[1], g: 10, ms: P.lat[2] });
|
||||
return P;
|
||||
}
|
||||
|
||||
// ---------- names and jokes: labels and their fill-ins ----------
|
||||
function words(ev, W, P, r) {
|
||||
const T = JSON.parse(ev(`JSON.stringify(PZ_WK_THEMES['${P.theme}'])`)), c = P.cities, last = c[c.length - 1];
|
||||
const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], p = {};
|
||||
for (const k of need) p[k] = k === 'hub' ? P.avoid[0] : k === 'reg' ? W.C[c[0]].reg : k === 'ms' ? P.lat[2] : k === 'n' ? c.length : k === 'a' ? (P.lat ? P.lat[0] : P.theme === 'tour' ? last : c[0]) : k === 'b' ? (P.lat ? P.lat[1] : c[2] || last) : null;
|
||||
return { l, p }; };
|
||||
return { name: fill(pick(r, T.names)), joke: fill(pick(r, T.jokes)) };
|
||||
}
|
||||
|
||||
// ---------- one week ----------
|
||||
function history(dir, key) {
|
||||
const keys = list(dir).filter((k) => k < key).slice(-HISTORY);
|
||||
const files = keys.map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')));
|
||||
return { cities: new Set(files.flatMap((f) => [...(f.cities || []), ...(f.via || []), ...(f.avoid || [])])), themes: files.slice(-THEME_GAP).map((f) => f.theme),
|
||||
regs: files.slice(-REG_GAP).map((f) => f.cities && f.cities[0]).filter(Boolean) };
|
||||
}
|
||||
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
|
||||
|
||||
// A topology's links, sized for the traffic: every wave at the smallest size that carries it all (after any single cut
|
||||
// too, for the N-1 build), as the game routes it, with the cheapest routers that fit.
|
||||
const TIER_G = [10, 100, 400];
|
||||
function size(ev, def, links, n1) {
|
||||
ev(`pzBegin(${lit(def)})`);
|
||||
const tot = def.dem.reduce((a, f) => a + f.g, 0), t0 = Math.max(0, TIER_G.findIndex((g) => g >= tot));
|
||||
for (let t = t0; t < TIER_G.length; t++) {
|
||||
const L = [...links.map((l) => [l.a, l.b, l.via, t, 0]), ...def.dem.map((f, i) => f.ms ? ['@route', i, 'fast'] : null).filter(Boolean)], j = SV.judge(ev, L);
|
||||
if (n1 ? j.three : j.one) { const r = n1 ? SV.improve(ev, L) : { links: L, ...j }; return r; }
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// Plays a sized build (links and routers) in the game and returns the stars it earns.
|
||||
function play(ev, def, b) {
|
||||
ev(`localStorage.removeItem('sot-puzzles');pzBegin(${lit(def)})`);
|
||||
SV.judge(ev, b.links); ev(`pzsApplyRt(${lit(b.rt)})`);
|
||||
return JSON.parse(ev('JSON.stringify((({stars,spend,goal,n1,cheap})=>({stars,spend,goal,n1,cheap}))(pzEval()))'));
|
||||
}
|
||||
const fileOf = (key, P, budget, w, sol) => ({ v: SCHEMA, key, theme: P.theme, cities: P.cities, src: P.src, dem: P.dem, via: P.via, avoid: P.avoid, budget,
|
||||
twist: Object.assign({}, P.ring ? { ring: true } : {}, P.noSub ? { noSub: true } : {}),
|
||||
name: w.name, joke: w.joke, ref: { one: sol.one.cost, three: sol.three.cost } });
|
||||
// The topology search reads a sprint's latency cap from its circuit.
|
||||
const shape = (def) => { const l2 = def.dem.find((f) => f.t === 'l2' && f.ms); return { theme: def.theme, cities: def.cities, via: def.via, avoid: def.avoid, noSub: def.noSub, ring: def.ring, lat: l2 ? [l2.a, l2.b, l2.ms] : null }; };
|
||||
// Topology, then sizes: the 1-star and 3-star references with their prices.
|
||||
function sized(g, W, P, def) {
|
||||
const sol = solve(W, P); if (!sol.one || !sol.three) return null;
|
||||
const one = size(g.ev, def, sol.one.links, false), three = size(g.ev, def, sol.three.links, true);
|
||||
if (!one || !three) return null;
|
||||
// The three-star build delivers too: when it is the cheaper one (a ring, sized down), it is the one-star reference.
|
||||
const o = one.spend <= three.spend ? one : three;
|
||||
return { one: { cost: Math.round(o.spend), b: o }, three: { cost: Math.round(three.spend), b: three } };
|
||||
}
|
||||
// The game's own validator decides what a puzzle is; then both references must earn their stars.
|
||||
function verify(g, W, j, key, known) {
|
||||
const { ev } = g, def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(j)},'${key}'))`));
|
||||
if (!def) return { ok: false, why: 'the game rejects the file' };
|
||||
const P = shape(def), sol = known || sized(g, W, P, def);
|
||||
if (!sol) return { ok: false, why: 'no build delivers the traffic and survives a cut' };
|
||||
if (sol.three.cost > def.budget) return { ok: false, why: `the cheapest N-1 build found costs ${sol.three.cost}, over the budget ${def.budget}` };
|
||||
const s1 = play(ev, def, sol.one.b), s3 = play(ev, def, sol.three.b);
|
||||
if (s1.stars < 1) return { ok: false, why: `the one-star reference earns ${s1.stars} stars` };
|
||||
if (s3.stars !== 3) return { ok: false, why: `the three-star reference earns ${s3.stars} stars (${JSON.stringify(s3)})` };
|
||||
return { ok: true, sol, s1, s3 };
|
||||
}
|
||||
|
||||
// Three stars need the smart design: the budget sits just above the cheapest N-1 build found, sized for its traffic.
|
||||
const budgetOf = (sol) => Math.max(50000, ceil10k(sol.three.cost * 1.05));
|
||||
|
||||
function generate(g, key, dir) {
|
||||
const { ev } = g, W = world(ev);
|
||||
if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`);
|
||||
// Themes take turns (none of the last weeks' again); the week's own theme first, the others only if it finds nothing.
|
||||
const hist = history(dir, key), free = THEMES.filter((t) => !hist.themes.includes(t)), h = hash(key);
|
||||
const order = free.map((_, i) => free[(h + i) % free.length]);
|
||||
for (const theme of order) {
|
||||
const cands = [];
|
||||
for (let at = 0; at < ATTEMPTS && cands.length < KEEP; at++) {
|
||||
const r = rng(hash(`${key}|${theme}|${at}`)), P = draft(W, theme, r, hist.cities);
|
||||
// Not the same part of the world as the last two weeks.
|
||||
if (!P || hist.regs.some((c) => W.C[c] && W.C[c].reg === W.C[P.cities[0]].reg && W.C[c].lands[0] === W.C[P.cities[0]].lands[0])) continue;
|
||||
const sol = solve(W, P);
|
||||
if (!sol.one || !sol.three) continue;
|
||||
// Prefer puzzles where surviving a cut takes real thought: the obvious "double everything" costs a lot more.
|
||||
const smart = sol.naive ? sol.naive.cost / sol.three.cost : 1.05, slack = sol.three.cost / sol.one.cost;
|
||||
const score = Math.min(smart, 1.6) + Math.min(slack, 2) * 0.2 + r() * 0.05;
|
||||
cands.push({ P, score, w: words(ev, W, P, r) });
|
||||
}
|
||||
cands.sort((a, b) => b.score - a.score);
|
||||
for (const c of cands) {
|
||||
// Sized with the traffic: the budget sits just above the cheapest N-1 build found.
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(fileOf(key, c.P, 1e6, c.w, { one: { cost: 0 }, three: { cost: 0 } }))},'${key}'))`));
|
||||
const sol = def && sized(g, W, c.P, def);
|
||||
if (!sol) { console.warn(`${key}: rejected a ${theme} puzzle: no build carries its traffic`); continue; }
|
||||
const j = fileOf(key, c.P, budgetOf(sol), c.w, sol), v = verify(g, W, j, key, sol);
|
||||
if (v.ok) return j;
|
||||
console.warn(`${key}: rejected a ${theme} puzzle: ${v.why}`);
|
||||
}
|
||||
}
|
||||
throw new Error(`${key}: no puzzle survived verification`);
|
||||
}
|
||||
|
||||
// --check: every file is what the game accepts, under its own name, and the weeks still to come are solvable.
|
||||
function check(g, dir, now = Date.now()) {
|
||||
const { ev } = g, W = world(ev), bad = [], keys = list(dir);
|
||||
for (const k of keys) {
|
||||
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
|
||||
if (!ev(`!!pzWkValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!j.ref || !Number.isInteger(j.ref.one) || !Number.isInteger(j.ref.three) || j.ref.one > j.ref.three || j.ref.three > j.budget) { bad.push(`${k}: bad ref`); continue; }
|
||||
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, W, j, k); if (!v.ok) bad.push(`${k}: ${v.why}`); }
|
||||
}
|
||||
const ip = path.join(dir, 'index.json');
|
||||
if (keys.length) {
|
||||
let idx = null; try { idx = JSON.parse(fs.readFileSync(ip, 'utf8')); } catch (e) { /* reported below */ }
|
||||
if (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys)) bad.push('index.json does not list exactly the weekly files');
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
/* --check, first part: a release can change prices, cables or cities under weeks that are already published. Every
|
||||
week not over yet is re-solved with this game; when its budget no longer verifies it is regenerated, deterministically:
|
||||
the same puzzle (theme, cities, twist, name) with a new budget when that still works, else a fresh puzzle for the
|
||||
same key. Its rev goes up, so players' stars for that week (and only that week) start again; new references alone
|
||||
keep the rev. Past weeks can no longer be played, so they keep their stars and are only replaced when the game
|
||||
rejects them outright. Returns what changed and what could not be fixed. */
|
||||
function refresh(g, dir, now = Date.now()) {
|
||||
const { ev } = g, W = world(ev), fixed = [], bad = [];
|
||||
for (const k of list(dir)) {
|
||||
const f = path.join(dir, k + '.json');
|
||||
let j = null; try { j = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { /* regenerated below */ }
|
||||
const valid = !!j && ev(`!!pzWkValid(${lit(j)},'${k}')`), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
if (valid && !live) continue;
|
||||
const v = valid ? verify(g, W, j, k) : null;
|
||||
if (v && v.ok) {
|
||||
if (j.ref && j.ref.one === v.sol.one.cost && j.ref.three === v.sol.three.cost) continue;
|
||||
j.ref = { one: v.sol.one.cost, three: v.sol.three.cost }; writeWeek(dir, j); fixed.push(`${k}: new references`); continue;
|
||||
}
|
||||
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
|
||||
let n = null;
|
||||
if (valid) {
|
||||
const def = JSON.parse(ev(`JSON.stringify(pzWkValid(${lit(j)},'${k}'))`));
|
||||
const sol = sized(g, W, shape(def), def);
|
||||
if (sol) {
|
||||
const c = Object.assign({}, j, { budget: budgetOf(sol), ref: { one: sol.one.cost, three: sol.three.cost }, rev });
|
||||
if (verify(g, W, c, k, sol).ok) n = c;
|
||||
}
|
||||
}
|
||||
if (!n) { try { n = Object.assign(generate(g, k, dir), { rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; } }
|
||||
writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}${n.theme === (j && j.theme) && JSON.stringify(n.cities) === JSON.stringify(j.cities) ? ', same puzzle, new budget ' + n.budget : ', a new ' + n.theme + ' puzzle'}`);
|
||||
}
|
||||
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
|
||||
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
|
||||
return { fixed, bad };
|
||||
}
|
||||
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
|
||||
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
|
||||
|
||||
module.exports = { game, generate, check, refresh, solve, sized, shape, world, writeWeek, writeIndex, list };
|
||||
|
||||
if (require.main === module) {
|
||||
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
|
||||
const dir = path.resolve(ROOT, opt('--dir', 'site/puzzles/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
|
||||
if (args.includes('--check')) {
|
||||
// Fix what a release's new prices broke, then check everything; only what could not be fixed fails.
|
||||
const r = refresh(g, dir);
|
||||
for (const x of r.fixed) console.log(`fixed: ${x}`);
|
||||
const bad = [...r.bad, ...check(g, dir)];
|
||||
for (const b of bad) console.error(`error: ${b}`);
|
||||
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly puzzle(s) OK`);
|
||||
process.exit(bad.length ? 1 : 0);
|
||||
}
|
||||
// By default the week that holds "12 hours from now": run early on Sunday, that is the week starting that morning.
|
||||
const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const key = g.ev(`pzKeyAdd('${first}',${i})`);
|
||||
if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); }
|
||||
if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; }
|
||||
const j = generate(g, key, dir); writeWeek(dir, j);
|
||||
console.log(`${key}: ${j.theme}, ${j.cities.join(' ')}${j.via.length ? ' via ' + j.via.join(' ') : ''}${j.avoid.length ? ' avoid ' + j.avoid.join(' ') : ''}, budget ${j.budget} (1★ ${j.ref.one}, 3★ ${j.ref.three})`);
|
||||
}
|
||||
}
|
||||
298
scripts/weekly-scenario.js
Normal file
298
scripts/weekly-scenario.js
Normal file
|
|
@ -0,0 +1,298 @@
|
|||
#!/usr/bin/env node
|
||||
// The weekly scenario generator, the twin of scripts/weekly-puzzle.js. Every Sunday .github/workflows/weekly-puzzle.yml
|
||||
// runs both; this one publishes site/scenarios/weekly/<key>.json, which the game fetches when the Scenarios list opens
|
||||
// (src/game/60-features/94-scenarios-weekly.js). It loads the real game headless, so it uses the game's own cities,
|
||||
// cables, prices, week keys, file validator and goal code.
|
||||
//
|
||||
// node scripts/weekly-scenario.js the week starting on the coming (or current) Sunday 06:00 Berlin, if missing
|
||||
// node scripts/weekly-scenario.js --key 2026-W45 that week (--force replaces an existing file)
|
||||
// node scripts/weekly-scenario.js --next 3 this week and the next two
|
||||
// node scripts/weekly-scenario.js --check re-play every week not over yet with this game; a week its reference
|
||||
// no longer wins is regenerated with rev + 1 (see refresh()); then
|
||||
// validate every file. Fails only if that fails.
|
||||
// --page FILE / --dir DIR another build of the game / where the files live
|
||||
//
|
||||
// How a scenario is made: pick a theme the last weeks did not have (TEMPLATES, plain data), a home city from another part
|
||||
// of the world than the last weeks', its rules and the reference plan (which links to build, in order). Then the
|
||||
// reference player (scripts/lib/scenario-bot.js) plays it through the game's own actions with the scenario's seed. The
|
||||
// goal's number is calibrated from that run (what the reference reached about three quarters of the way in), and the
|
||||
// scenario is verified: not won on day 0, won by the reference with time to spare. Its finishing day is the par.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const BOT = require('./lib/scenario-bot');
|
||||
const { lit } = require('./lib/js-literal');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const SCHEMA = 1, HISTORY = 4, THEME_GAP = 4, REG_GAP = 3, ATTEMPTS = 12, AT = 0.8, MARGIN = 0.9;
|
||||
|
||||
// ---------- the templates: data only. `home` names a city pool, `goal` a goal type of the game, `plan` a planner ----------
|
||||
const TEMPLATES = {
|
||||
budget: { goal: 'served', home: 'big', days: [240, 300], cash: [150000, 250000], lvl: 2, mods: ['pricey'], plan: 'spread', hops: 4 },
|
||||
spat: { goal: 'reach', home: 'big', days: [240, 300], cash: [500000, 800000], lvl: 2, rules: { spat: true }, plan: 'spread', hops: 3, tr2: true, avoid: ['cog'] },
|
||||
region: { goal: 'ix', home: 'ixrich', days: [270, 365], cash: [200000, 350000], lvl: 2, plan: 'exchanges', hops: 14 },
|
||||
event: { goal: 'event', home: 'big', days: [180, 240], cash: [500000, 900000], lvl: 2, plan: 'spread', hops: 2, sizes: [1600, 800, 400, 200] },
|
||||
flood: { goal: 'floods', home: 'big', days: [240, 300], cash: [1500000, 2500000], lvl: 4, rules: { ddos: true }, plan: 'spread', hops: 2, scrub: 2 },
|
||||
island: { goal: 'pops', home: 'island', days: [240, 365], cash: [250000, 500000], lvl: 3, plan: 'islands', hops: 3 },
|
||||
cable: { goal: 'path', home: 'landing', days: [270, 365], cash: [200000, 400000], lvl: 3, plan: 'detour', g: [400, 800], n: 45 },
|
||||
latency: { goal: 'lat', home: 'fast', days: [180, 270], cash: [300000, 600000], lvl: 3, plan: 'fast', n: 60 },
|
||||
};
|
||||
|
||||
// ---------- the game, headless ----------
|
||||
function game(file) {
|
||||
const { load } = require('../tests/harness');
|
||||
let g = load(file ? { file } : {});
|
||||
if (file && !g.ev("typeof wsValid==='function'")) { console.warn(`warning: ${file} has no weekly scenarios yet; using src/ instead`); g = load(); }
|
||||
return g;
|
||||
}
|
||||
const J = (ev, s) => JSON.parse(ev(`JSON.stringify(${s})`));
|
||||
|
||||
// ---------- small helpers ----------
|
||||
const hash = (s) => { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; };
|
||||
function rng(seed) { let a = seed >>> 0 || 1; return () => { a = (a + 0x6D2B79F5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; }
|
||||
const pick = (r, a) => a[Math.floor(r() * a.length)];
|
||||
const between = (r, [lo, hi], step) => lo + Math.floor(r() * ((hi - lo) / step + 1)) * step;
|
||||
// A goal number players can read: two significant digits, rounded down.
|
||||
const nice = (x) => { if (x < 10) return Math.max(1, Math.floor(x)); const p = 10 ** (Math.floor(Math.log10(x)) - 1); return Math.floor(x / p) * p; };
|
||||
|
||||
// ---------- the world, as the game sees it ----------
|
||||
function world(ev) {
|
||||
const cities = J(ev, `Object.values(CITY).filter(c=>pzCityOk(c.id)).map(c=>({id:c.id,reg:c.reg,P:c.P,land:lands(c)[0],nl:lands(c).length,ix:ixIdsIn(c.id).length,lon:c.lon,lat:c.lat}))`);
|
||||
const C = Object.fromEntries(cities.map((c) => [c.id, c]));
|
||||
const pairs = J(ev, 'CABLE_PAIRS.map(p=>[p.cid,p.a,p.b])').filter(([, a, b]) => C[a] && C[b]);
|
||||
const byLand = {}; for (const c of cities) (byLand[c.land] = byLand[c.land] || []).push(c.id);
|
||||
const km = (a, b) => { const A = C[a], B = C[b], r = Math.PI / 180, h = Math.sin((B.lat - A.lat) * r / 2) ** 2 + Math.cos(A.lat * r) * Math.cos(B.lat * r) * Math.sin((B.lon - A.lon) * r / 2) ** 2; return 12742 * Math.asin(Math.sqrt(h)); };
|
||||
const cabs = (c) => pairs.filter(([, a, b]) => a === c || b === c);
|
||||
const pools = {
|
||||
big: cities.filter((c) => c.P >= 150 && byLand[c.land].length >= 5).map((c) => c.id),
|
||||
ixrich: cities.filter((c) => c.ix && cities.filter((x) => x.reg === c.reg && x.land === c.land && x.ix && km(c.id, x.id) < 2500).length >= 9).map((c) => c.id),
|
||||
island: cities.filter((c) => byLand[c.land].length <= 2 && c.nl === 1 && cabs(c.id).length >= 2).map((c) => c.id),
|
||||
landing: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 3).map((c) => c.id),
|
||||
fast: cities.filter((c) => c.P >= 100 && cabs(c.id).length >= 2).map((c) => c.id),
|
||||
};
|
||||
return { cities, C, pairs, byLand, km, cabs, pools };
|
||||
}
|
||||
const near = (W, c, from, n) => from.filter((x) => x !== c).sort((a, b) => W.km(c, a) - W.km(c, b)).slice(0, n);
|
||||
|
||||
// ---------- drafts: a template, a home, rules, the goal's fixed parameters and the reference plan ----------
|
||||
// Plans are lists of steps for the reference player: {k:'hop',v:[a,b,tier,via]} lights a wave a-b (a new POP at b).
|
||||
function draft(g, W, theme, r, hist) {
|
||||
const T = TEMPLATES[theme], free = (c) => !hist.cities.has(c) && !hist.regs.includes(W.C[c].reg);
|
||||
const homes = W.pools[T.home].filter(free); if (!homes.length) return null;
|
||||
const home = pick(r, homes), H = W.C[home];
|
||||
const f = { theme, city: home, cash: between(r, T.cash, 50000), days: between(r, T.days, 10), lvl: T.lvl, rules: { ...(T.rules || {}) }, mods: (T.mods || []).slice() };
|
||||
const plan = { home, bb: true, ix: true, steps: [], avoid: T.avoid || [], tr2: !!T.tr2, scrub: T.scrub || 0 };
|
||||
const hop = (a, b, t = 1, via = null) => plan.steps.push({ k: 'hop', v: [a, b, t, via] });
|
||||
const land = W.byLand[H.land].filter((c) => c !== home && W.km(home, c) < 1500);
|
||||
let goal = null, words = {};
|
||||
if (T.plan === 'spread') {
|
||||
// Overland to the nearest big cities, each from the closest POP already built.
|
||||
const to = near(W, home, land.filter((c) => W.C[c].P >= 60), T.hops); if (to.length < Math.min(2, T.hops)) return null;
|
||||
const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); }
|
||||
if (theme === 'budget') goal = { t: 'served', p: { g: 0 } };
|
||||
if (theme === 'spat') goal = { t: 'reach', p: { r: 99, g: 0 } };
|
||||
if (theme === 'flood') goal = { t: 'floods', p: { n: 0, big: 0 } };
|
||||
if (theme === 'event') { const day = Math.round(f.days * (0.6 + r() * 0.15)); goal = { t: 'event', p: { city: home, g: 0, day, dur: 3 + Math.floor(r() * 3) } }; plan.event = { city: home, day }; words = { day }; }
|
||||
} else if (T.plan === 'exchanges') {
|
||||
const to = near(W, home, W.cities.filter((c) => c.reg === H.reg && c.land === H.land && c.ix).map((c) => c.id), T.hops); if (to.length < T.hops) return null;
|
||||
const built = [home]; for (const c of to) { hop(near(W, c, built, 1)[0], c); built.push(c); }
|
||||
plan.allIx = true; goal = { t: 'ix', p: { reg: H.reg, n: 0 } }; words = { reg: H.reg };
|
||||
} else {
|
||||
// Cable work: plan inside the game, which knows each pair's cables under this scenario's rules.
|
||||
let a = home, b = null, cs = null;
|
||||
if (theme === 'cable') {
|
||||
// Cut one cable everywhere it lands; the goal is its far end, the long way round.
|
||||
const mine = W.cabs(home).filter(([, x, y]) => W.C[x].land !== W.C[y].land && W.C[x === home ? y : x].P >= 60);
|
||||
if (!mine.length) return null;
|
||||
const [cid, x, y] = pick(r, mine); b = x === home ? y : x;
|
||||
// The whole cable, and every other cable straight from home to its far end: the corridor is closed.
|
||||
const cut = new Set([cid, ...W.pairs.filter(([, p, q]) => (p === home && q === b) || (p === b && q === home)).map(([c]) => c)]);
|
||||
f.rules.banPairs = W.pairs.filter(([c, p, q]) => c === cid || (cut.has(c) && [p, q].includes(home) && [p, q].includes(b))).map(([c, p, q]) => `${c}:${p}-${q}`);
|
||||
if (f.rules.banPairs.length > 40) return null;
|
||||
const gb = pick(r, T.g); plan.tier = J(g.ev, `LT.findIndex(x=>x.g>=${gb})`);
|
||||
goal = { t: 'path', p: { a, b, g: gb, n: T.n } }; words = { cab: cid, a, b };
|
||||
} else if (theme === 'island') {
|
||||
const hops = W.cabs(home).map(([, x, y]) => (x === home ? y : x)).filter((c, i, s) => s.indexOf(c) === i && W.km(home, c) < 6000);
|
||||
if (hops.length < 2) return null;
|
||||
// The nearest islands a cable away, and one more island further out.
|
||||
const isl = W.pools.island.filter((c) => c !== home && W.km(home, c) < 9000 && !hops.includes(c));
|
||||
cs = [...near(W, home, hops, 2), ...near(W, home, isl, 1 + Math.floor(r() * 2))];
|
||||
if (cs.length < 3) return null;
|
||||
goal = { t: 'pops', p: { cs } };
|
||||
} else if (theme === 'latency') {
|
||||
// Far enough that the fast way takes more than one cable.
|
||||
const ok = W.cities.filter((c) => c.P >= 100 && c.land !== H.land && W.km(home, c.id) > 5000 && W.km(home, c.id) < 11000 && W.cabs(c.id).length >= 2).map((c) => c.id);
|
||||
if (!ok.length) return null; b = pick(r, ok); goal = { t: 'lat', p: { a, b, ms: 0, n: T.n } }; words = { a, b };
|
||||
}
|
||||
plan.targets = cs || [b]; plan.fast = theme === 'latency';
|
||||
f.goal = goal;
|
||||
return { f, plan, words, T };
|
||||
}
|
||||
f.goal = goal;
|
||||
return { f, plan, words, T };
|
||||
}
|
||||
|
||||
// ---------- names and descriptions: labels and their fill-ins ----------
|
||||
function texts(ev, d, r) {
|
||||
const T = J(ev, `WS_THEMES['${d.f.theme}']`), p = d.f.goal.p;
|
||||
const fill = (l) => { const need = [...new Set([...ev(`EN['${l}']`).matchAll(/\{(\w+)\}/g)].map((m) => m[1]))], o = {};
|
||||
for (const k of need) o[k] = k === 'city' ? d.f.city : k === 'ms' ? p.ms : k === 'g' ? p.g : k === 'n' ? p.n : d.words[k];
|
||||
return { l, p: o }; };
|
||||
return { name: fill(pick(r, T.names)), desc: fill(pick(r, T.descs)) };
|
||||
}
|
||||
|
||||
// ---------- playing a draft ----------
|
||||
const fileOf = (key, d, seed, extra) => ({ v: SCHEMA, key, theme: d.f.theme, city: d.f.city, cash: d.f.cash, days: d.f.days, lvl: d.f.lvl, rules: d.f.rules, mods: d.f.mods, goal: d.f.goal, ...extra, seed, ref: d.plan });
|
||||
// Cable plans are made in the game, once the scenario's rules are in force: the shortest chain of POPs to each target.
|
||||
function cablePlan(ev, plan) {
|
||||
if (!plan.targets) return plan;
|
||||
const steps = J(ev, `(()=>{const home=S.scn.home,T=${lit(plan.targets)},fast=${!!plan.fast},out=[],have=new Set([home]);
|
||||
const ok=c=>pzCityOk(c)&&cityOn(c)&&!cnCity(c);
|
||||
const edges=u=>{const o=[];for(const p of CABLE_PAIRS){const v=p.a===u?p.b:p.b===u?p.a:null;if(!v||!ok(v))continue;const cs=cablesOk(u,v);if(!cs.length)continue;
|
||||
const c=cs.slice().sort((x,y)=>x.km*(CAB[x.cid].lat||1)-y.km*(CAB[y.cid].lat||1))[0];o.push([v,c.km*(CAB[c.cid].lat||1)/200,c.cid]);}
|
||||
for(const c of CITIES)if(c.id!==u&&ok(c.id)&&!isSub(u,c.id)&&kmBetween(u,c.id)<(fast?4000:1800))o.push([c.id,kmBetween(u,c.id)*1.3/200,null]);return o;};
|
||||
for(const t of T){if(have.has(t))continue;const d={},pv={},done=new Set();for(const h of have)d[h]=0;
|
||||
for(;;){let u=null;for(const k in d)if(!done.has(k)&&(u===null||d[k]<d[u]))u=k;if(u===null||u===t)break;done.add(u);for(const [v,w,cid] of edges(u)){const nd=d[u]+(fast?w:1+w/1000);if(!(d[v]<=nd)){d[v]=nd;pv[v]=[u,cid];}}}
|
||||
if(d[t]===undefined)return null;const chain=[];for(let v=t;!have.has(v);v=pv[v][0])chain.unshift([pv[v][0],v,${plan.tier || 1},pv[v][1]]);for(const h of chain){out.push({k:'hop',v:h});have.add(h[1]);}}
|
||||
return out;})()`);
|
||||
return steps ? { ...plan, steps } : null;
|
||||
}
|
||||
// Starts the draft in the game (so its rules apply), finishes the plan, and plays it with the reference player.
|
||||
function run(g, file, plan, days) {
|
||||
const { ev } = g;
|
||||
ev(`localStorage.removeItem('sot-wkscn');wsBegin(${lit(file)},'Ref');if(UI.pendGame)ACT.pitchSkip()`);
|
||||
const p = cablePlan(ev, plan); if (!p || (plan.targets && p.steps.length < 2)) return null;
|
||||
return { plan: p, res: BOT.play(ev, { ...file, ref: p }, p, { days, stop: false }) };
|
||||
}
|
||||
|
||||
// The goal's number, from the reference run: what it held about three quarters of the way in.
|
||||
function calibrate(g, d, key, seed) {
|
||||
const { f } = d, p = f.goal.p, t = f.goal.t, at = Math.round(f.days * AT);
|
||||
// The validator wants a complete goal: start from placeholders the game accepts.
|
||||
const probe = JSON.parse(JSON.stringify(f.goal));
|
||||
if (t === 'served') probe.p.g = 50000; if (t === 'reach') probe.p.g = 50000; if (t === 'ix') probe.p.n = 60; if (t === 'floods') probe.p.n = 60;
|
||||
if (t === 'event') probe.p.g = 10; if (t === 'lat') probe.p.ms = 400;
|
||||
// Probed with placeholder numbers; the real name and text are filled in once the numbers are known.
|
||||
const tmp = { ...d, f: { ...f, goal: probe } }, file = fileOf(key, tmp, seed, { ...texts(g.ev, tmp, rng(1)), par: 1 });
|
||||
if (t === 'event') {
|
||||
// The biggest event the reference delivers in full.
|
||||
for (const size of d.T.sizes) { probe.p.g = size; file.goal = probe; const o = run(g, { ...file }, { ...d.plan, event: { ...d.plan.event, g: size } }, p.day + p.dur + 1); if (o && g.ev('(S.stats.evFull||0)>=1')) { p.g = size; return { plan: o.plan }; } }
|
||||
return null;
|
||||
}
|
||||
if (t === 'lat') {
|
||||
const o = run(g, file, d.plan, at); if (!o) return null;
|
||||
const best = g.ev(`bestLat('${p.a}','${p.b}')`); if (!isFinite(best)) return null;
|
||||
p.ms = Math.ceil(best * 1.03 + 0.5); return { plan: o.plan };
|
||||
}
|
||||
const o = run(g, file, d.plan, at); if (!o) return null;
|
||||
const m = o.res.m, v = m[m.length - 1];
|
||||
if (t === 'served') p.g = nice(Math.min(...m.slice(-14)));
|
||||
if (t === 'reach') { if (g.ev('R.reach') < 0.99) return null; p.g = nice(Math.min(...m.slice(-14))); }
|
||||
if (t === 'ix') p.n = Math.floor(v);
|
||||
if (t === 'floods') { p.n = Math.floor(v); p.big = Math.min(5, g.ev('S.stats.ddosOkBig||0')); }
|
||||
if ((p.g !== undefined && p.g < 5) || (p.n !== undefined && p.n < 2)) return null;
|
||||
return { plan: o.plan };
|
||||
}
|
||||
|
||||
// The game's validator decides what a scenario is; then it must need play, and the reference must win with time to spare.
|
||||
function verify(g, j) {
|
||||
const { ev } = g;
|
||||
if (!ev(`!!wsValid(${lit(j)},'${j.key}')`)) return { ok: false, why: 'the game rejects the file' };
|
||||
// Played with the longest clock the game allows, so a late win still shows its day (the days change nothing else).
|
||||
const res = BOT.play(ev, { ...j, days: 400 }, j.ref, { stop: true });
|
||||
if (res.won0) return { ok: false, why: 'won on day 0' };
|
||||
if (!res.won) return { ok: false, why: `the reference does not win in ${j.days} days` };
|
||||
if (res.won > j.days * MARGIN) return { ok: false, late: res.won, why: `the reference wins only on day ${res.won} of ${j.days}` };
|
||||
if (res.won < 40) return { ok: false, why: `the reference wins already on day ${res.won} of ${j.days}` };
|
||||
return { ok: true, par: res.won };
|
||||
}
|
||||
|
||||
// ---------- one week ----------
|
||||
const list = (dir) => (fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => /^\d{4}-W\d{2}\.json$/.test(f)).map((f) => f.slice(0, -5)).sort() : []);
|
||||
function history(W, dir, key) {
|
||||
const files = list(dir).filter((k) => k < key).slice(-HISTORY).map((k) => JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')));
|
||||
return { themes: files.slice(-THEME_GAP).map((f) => f.theme), regs: files.slice(-REG_GAP).map((f) => W.C[f.city] && W.C[f.city].reg).filter(Boolean), cities: new Set(files.map((f) => f.city)) };
|
||||
}
|
||||
function generate(g, key, dir) {
|
||||
const { ev } = g, W = world(ev);
|
||||
if (ev(`pzWeekStart('${key}')`) == null) throw new Error(`${key} is not a week`);
|
||||
const hist = history(W, dir, key), free = Object.keys(TEMPLATES).sort().filter((t) => !hist.themes.includes(t)), h = hash('scn|' + key);
|
||||
const order = free.map((_, i) => free[(h + i) % free.length]);
|
||||
for (const theme of order) {
|
||||
for (let at = 0; at < ATTEMPTS; at++) {
|
||||
const r = rng(hash(`${key}|${theme}|${at}`)), d = draft(g, W, theme, r, hist);
|
||||
if (!d) continue;
|
||||
const seed = 1 + (hash(`${key}|seed|${at}`) % 2147483646), c = calibrate(g, d, key, seed);
|
||||
if (!c) { console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: no goal to calibrate`); continue; }
|
||||
d.plan = c.plan;
|
||||
const w = texts(ev, d, r), j = fileOf(key, d, seed, { name: w.name, desc: w.desc, par: 1 });
|
||||
let v = verify(g, j);
|
||||
// A goal with a fixed bar (a path, a set of POPs, a latency) gets the days the reference needed, and a third more.
|
||||
const day = v.ok ? v.par : v.late;
|
||||
if (day && ['path', 'pops', 'lat'].includes(j.goal.t)) { j.days = Math.min(365, Math.max(180, Math.ceil(day / 0.7 / 10) * 10)); v = verify(g, j); }
|
||||
if (v.ok) { j.par = v.par; return order0(j); }
|
||||
console.warn(`${key}: rejected a ${theme} scenario in ${d.f.city}: ${v.why}`);
|
||||
}
|
||||
}
|
||||
throw new Error(`${key}: no scenario survived verification`);
|
||||
}
|
||||
// Fields in a fixed order, so files diff well.
|
||||
const order0 = (j) => { const o = {}; for (const k of ['v', 'key', 'rev', 'theme', 'city', 'cash', 'days', 'lvl', 'rules', 'mods', 'goal', 'name', 'desc', 'seed', 'par', 'ref']) if (j[k] !== undefined) o[k] = j[k]; return o; };
|
||||
|
||||
// --check: every file is what the game accepts, under its own name, listed in the index; weeks not over yet still verify.
|
||||
function check(g, dir, now = Date.now()) {
|
||||
const { ev } = g, bad = [], keys = list(dir);
|
||||
for (const k of keys) {
|
||||
let j; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { bad.push(`${k}: not JSON`); continue; }
|
||||
if (!ev(`!!wsValid(${lit(j)},'${k}')`)) { bad.push(`${k}: the game rejects it`); continue; }
|
||||
if (!j.ref || !Array.isArray(j.ref.steps)) { bad.push(`${k}: no reference plan`); continue; }
|
||||
if (ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now) { const v = verify(g, j); if (!v.ok) bad.push(`${k}: ${v.why}`); else if (v.par !== j.par) bad.push(`${k}: par is ${j.par}, the reference wins on day ${v.par}`); }
|
||||
}
|
||||
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* reported below */ }
|
||||
if (keys.length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(keys))) bad.push('index.json does not list exactly the weekly files');
|
||||
return bad;
|
||||
}
|
||||
/* --check, first part: a release can change prices, cables or the simulation under weeks already published. Every week
|
||||
not over yet is re-played with this game. Still won with time to spare: only its par follows. Not any more: it is
|
||||
regenerated for the same key, deterministically, with rev + 1, so last week's wins for it no longer show. Past weeks
|
||||
are only replaced when the game rejects them outright. */
|
||||
function refresh(g, dir, now = Date.now()) {
|
||||
const { ev } = g, fixed = [], bad = [];
|
||||
for (const k of list(dir)) {
|
||||
let j = null; try { j = JSON.parse(fs.readFileSync(path.join(dir, k + '.json'), 'utf8')); } catch (e) { /* regenerated */ }
|
||||
const valid = !!j && ev(`!!wsValid(${lit(j)},'${k}')`) && j.ref && Array.isArray(j.ref.steps), live = ev(`pzWeekStart('${k}')`) + 7 * 864e5 > now;
|
||||
if (valid && !live) continue;
|
||||
const v = valid ? verify(g, j) : null;
|
||||
if (v && v.ok) { if (v.par !== j.par) { j.par = v.par; writeWeek(dir, j); fixed.push(`${k}: new par ${v.par}`); } continue; }
|
||||
const rev = (j && Number.isInteger(j.rev) && j.rev >= 2 ? j.rev : 1) + 1;
|
||||
let n; try { n = order0({ ...generate(g, k, dir), rev }); } catch (e) { bad.push(`${k}: could not regenerate (${e.message})`); continue; }
|
||||
writeWeek(dir, n); fixed.push(`${k}: regenerated as rev ${rev}, a ${n.theme} scenario in ${n.city}`);
|
||||
}
|
||||
let idx = null; try { idx = JSON.parse(fs.readFileSync(path.join(dir, 'index.json'), 'utf8')); } catch (e) { /* rewritten */ }
|
||||
if (list(dir).length && (!idx || idx.v !== SCHEMA || JSON.stringify(idx.weeks) !== JSON.stringify(list(dir)))) { writeIndex(dir); fixed.push('index.json rewritten'); }
|
||||
return { fixed, bad };
|
||||
}
|
||||
const writeIndex = (dir) => fs.writeFileSync(path.join(dir, 'index.json'), JSON.stringify({ v: SCHEMA, weeks: list(dir) }) + '\n');
|
||||
const writeWeek = (dir, j) => { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, j.key + '.json'), JSON.stringify(j) + '\n'); writeIndex(dir); };
|
||||
|
||||
module.exports = { game, generate, verify, check, refresh, list, writeWeek, TEMPLATES };
|
||||
|
||||
if (require.main === module) {
|
||||
const args = process.argv.slice(2), opt = (n, d) => { const i = args.indexOf(n); return i >= 0 ? args[i + 1] : d; };
|
||||
const dir = path.resolve(ROOT, opt('--dir', 'site/scenarios/weekly')), g = game(opt('--page') && path.resolve(opt('--page')));
|
||||
if (args.includes('--check')) {
|
||||
const r = refresh(g, dir);
|
||||
for (const x of r.fixed) console.log(`fixed: ${x}`);
|
||||
const bad = [...r.bad, ...check(g, dir)];
|
||||
for (const b of bad) console.error(`error: ${b}`);
|
||||
console.log(bad.length ? `${bad.length} problem(s)` : `${list(dir).length} weekly scenario(s) OK`);
|
||||
process.exit(bad.length ? 1 : 0);
|
||||
}
|
||||
const first = opt('--key') || g.ev(`pzWeekKey(Date.now()+12*3600e3)`), n = +opt('--next', 1);
|
||||
for (let i = 0; i < n; i++) {
|
||||
const key = g.ev(`pzKeyAdd('${first}',${i})`);
|
||||
if (!key) { console.error(`error: ${first} is not a week`); process.exit(1); }
|
||||
if (fs.existsSync(path.join(dir, key + '.json')) && !args.includes('--force')) { console.log(`${key}: already there`); continue; }
|
||||
const j = generate(g, key, dir); writeWeek(dir, j);
|
||||
console.log(`${key}: ${j.theme} in ${j.city}, ${j.days} days, goal ${j.goal.t} ${JSON.stringify(j.goal.p)}, par ${j.par}`);
|
||||
}
|
||||
}
|
||||
1
site/architect/weekly/2026-W44.json
Normal file
1
site/architect/weekly/2026-W44.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"key":"2026-W44","hq":"cor","budget":1580000,"name":{"l":"architect_weekly.name_all_roads_lead_to_hq","p":{"hq":"cor"}},"joke":{"l":"architect_weekly.joke_hq_signed_the_lease","p":{"hq":"cor"}},"briefs":[{"add":["bue"],"dem":{"bue":40},"tubes":1},{"add":["scl","mvd"],"dem":{"scl":20,"mvd":20},"tubes":2},{"gold":["mvd"],"tubes":2},{"drop":["scl"],"add":["ldb"],"dem":{"ldb":10},"gold":["ldb"],"tubes":2},{"lat":["ldb","mvd",10.1],"tubes":1},{"dem":{"bue":100},"tubes":0},{"add":["cgr"],"dem":{"cgr":10},"gold":["cgr"],"tubes":2}],"ref":{"spend":1489176,"steps":[[["cor","bue","land",1]],[["cor","scl","land",1],["bue","mvd","land",1]],[["bue","cor","land",1],["mvd","bue","land",1]],[["@rm","scl"],["cor","ldb","land",1],["ldb","cor","land",1]],[["ldb","mvd","land",1]],[["@tier",2,2],["@tier",0,2]],[["ldb","cgr","land",2],["cgr","ldb","land",2]]]}}
|
||||
1
site/architect/weekly/2026-W45.json
Normal file
1
site/architect/weekly/2026-W45.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"key":"2026-W45","hq":"maa","budget":930000,"name":{"l":"architect_weekly.name_hq_and_friends","p":{"hq":"maa"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["blr"],"dem":{"blr":30},"tubes":1},{"add":["hyd","cbo"],"dem":{"hyd":20,"cbo":20},"tubes":2},{"gold":["cbo"],"tubes":1},{"ring":["maa","blr","hyd"],"tubes":1},{"drop":["hyd"],"add":["dac"],"dem":{"dac":20},"gold":["dac"],"tubes":2},{"gold":["blr"],"tubes":1}],"ref":{"spend":869628,"steps":[[["maa","blr","land",1]],[["blr","hyd","land",1],["maa","cbo","smw6",1]],[["cbo","maa","smw4",1]],[["hyd","maa","land",1]],[["@rm","hyd"],["maa","dac","land",1],["dac","maa","land",1]],[["blr","maa","land",1]]]}}
|
||||
1
site/architect/weekly/2026-W46.json
Normal file
1
site/architect/weekly/2026-W46.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"key":"2026-W46","hq":"svg","budget":610000,"name":{"l":"architect_weekly.name_the_hq_job","p":{"hq":"svg"}},"joke":{"l":"architect_weekly.joke_one_network_a_handful","p":{}},"briefs":[{"add":["krs"],"dem":{"krs":30},"tubes":1},{"add":["osl","ebj"],"dem":{"osl":20,"ebj":20},"tubes":2},{"gold":["ebj"],"tubes":2},{"lat":["osl","svg",2.2],"tubes":1},{"drop":["krs"],"add":["cph"],"dem":{"cph":20},"gold":["cph"],"tubes":3},{"dem":{"osl":140},"tubes":0}],"ref":{"spend":567292,"steps":[[["svg","krs","land",1]],[["krs","osl","land",1],["krs","ebj","land",1]],[["krs","svg","land",1],["ebj","krs","land",1]],[["osl","svg","land",1]],[["@rm","krs"],["ebj","svg","land",1],["ebj","cph","land",1],["cph","osl","land",1]],[["@tier",0,2],["@tier",1,2],["@tier",2,2],["@tier",3,2]]]}}
|
||||
1
site/architect/weekly/index.json
Normal file
1
site/architect/weekly/index.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]}
|
||||
2709
site/i18n/de.js
2709
site/i18n/de.js
File diff suppressed because it is too large
Load diff
2711
site/i18n/es.js
2711
site/i18n/es.js
File diff suppressed because it is too large
Load diff
2711
site/i18n/fr.js
2711
site/i18n/fr.js
File diff suppressed because it is too large
Load diff
2711
site/i18n/it.js
2711
site/i18n/it.js
File diff suppressed because it is too large
Load diff
2711
site/i18n/pt.js
2711
site/i18n/pt.js
File diff suppressed because it is too large
Load diff
1
site/puzzles/weekly/2026-W44.json
Normal file
1
site/puzzles/weekly/2026-W44.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":2,"key":"2026-W44","theme":"ring","cities":["ham","fra","bru","dus"],"src":["ham"],"dem":[{"t":"eye","a":"fra","g":30},{"t":"eye","a":"bru","g":60},{"t":"eye","a":"dus","g":60}],"via":[],"avoid":[],"budget":360000,"twist":{"ring":true},"name":{"l":"puzzles_weekly.name_one_ring_to_rule_reg","p":{"reg":"EU"}},"joke":{"l":"puzzles_weekly.joke_a_ring_survives_one_cut","p":{}},"ref":{"one":341708,"three":341708}}
|
||||
1
site/puzzles/weekly/2026-W45.json
Normal file
1
site/puzzles/weekly/2026-W45.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":2,"key":"2026-W45","theme":"tour","cities":["abj","fih","acc","dkr"],"src":["abj"],"dem":[{"t":"eye","a":"fih","g":20},{"t":"eye","a":"acc","g":10},{"t":"eye","a":"dkr","g":30}],"via":["lag"],"avoid":[],"budget":1750000,"twist":{},"name":{"l":"puzzles_weekly.name_tour_de_reg","p":{"reg":"AF"}},"joke":{"l":"puzzles_weekly.joke_a_road_trip_for_photons","p":{}},"ref":{"one":989200,"three":1657240}}
|
||||
1
site/puzzles/weekly/2026-W46.json
Normal file
1
site/puzzles/weekly/2026-W46.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":2,"key":"2026-W46","theme":"ocean","cities":["for","ssa","lad","lun"],"src":["for"],"dem":[{"t":"eye","a":"ssa","g":8},{"t":"eye","a":"lad","g":5},{"t":"eye","a":"lun","g":8}],"via":["sao","dla"],"avoid":[],"budget":4520000,"twist":{},"name":{"l":"puzzles_weekly.name_sea_you_in_b","p":{"b":"lad"}},"joke":{"l":"puzzles_weekly.joke_somewhere_between_a_and_b","p":{"a":"for","b":"lad"}},"ref":{"one":2368700,"three":4296628}}
|
||||
1
site/puzzles/weekly/index.json
Normal file
1
site/puzzles/weekly/index.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":2,"weeks":["2026-W44","2026-W45","2026-W46"]}
|
||||
1
site/scenarios/weekly/2026-W44.json
Normal file
1
site/scenarios/weekly/2026-W44.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"key":"2026-W44","rev":3,"theme":"flood","city":"sto","cash":2050000,"days":250,"lvl":4,"rules":{"ddos":true},"mods":[],"goal":{"t":"floods","p":{"n":28,"big":5}},"name":{"l":"wkscn.name_packet_monsoon","p":{}},"desc":{"l":"wkscn.desc_city_hosts_the_internets_favourite","p":{"city":"sto"}},"seed":1559294845,"par":185,"ref":{"home":"sto","bb":true,"ix":true,"steps":[{"k":"hop","v":["sto","tll",1,null]},{"k":"hop","v":["tll","hel",1,null]}],"avoid":[],"tr2":false,"scrub":2}}
|
||||
1
site/scenarios/weekly/2026-W45.json
Normal file
1
site/scenarios/weekly/2026-W45.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"key":"2026-W45","theme":"event","city":"bog","cash":900000,"days":230,"lvl":2,"rules":{},"mods":[],"goal":{"t":"event","p":{"city":"bog","g":400,"day":159,"dur":3}},"name":{"l":"wkscn.name_party_like_its_1999","p":{}},"desc":{"l":"wkscn.desc_the_whole_city_is_watching","p":{"day":159,"city":"bog","g":400}},"seed":169037385,"par":162,"ref":{"home":"bog","bb":true,"ix":true,"steps":[{"k":"hop","v":["bog","mde",1,null]},{"k":"hop","v":["bog","uio",1,null]}],"avoid":[],"tr2":false,"scrub":0,"event":{"city":"bog","day":159,"g":400}}}
|
||||
1
site/scenarios/weekly/2026-W46.json
Normal file
1
site/scenarios/weekly/2026-W46.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"key":"2026-W46","theme":"spat","city":"fih","cash":750000,"days":250,"lvl":2,"rules":{"spat":true},"mods":[],"goal":{"t":"reach","p":{"r":99,"g":370}},"name":{"l":"wkscn.name_not_on_speaking_terms","p":{}},"desc":{"l":"wkscn.desc_two_giants_de_peered_over","p":{"city":"fih"}},"seed":61791269,"par":170,"ref":{"home":"fih","bb":true,"ix":true,"steps":[{"k":"hop","v":["fih","lad",1,null]},{"k":"hop","v":["fih","dla",1,null]}],"avoid":["cog"],"tr2":true,"scrub":0}}
|
||||
1
site/scenarios/weekly/index.json
Normal file
1
site/scenarios/weekly/index.json
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"v":1,"weeks":["2026-W44","2026-W45","2026-W46"]}
|
||||
|
|
@ -15,6 +15,8 @@ self.addEventListener('activate', (e) => {
|
|||
self.addEventListener('fetch', (e) => {
|
||||
const req = e.request;
|
||||
if (req.method !== 'GET') return;
|
||||
// Calls with a player's credentials, or that ask not to be cached (a self-hosted copy's multiplayer server), are never cached.
|
||||
if (req.cache === 'no-store' || req.headers.has('authorization')) return;
|
||||
const url = new URL(req.url);
|
||||
// The update check must always ask the network.
|
||||
if (url.origin === location.origin && url.pathname === '/version.json') return;
|
||||
|
|
@ -25,6 +27,12 @@ self.addEventListener('fetch', (e) => {
|
|||
}
|
||||
const local = url.origin === location.origin, fonts = /fonts\.(googleapis|gstatic)\.com$/.test(url.hostname);
|
||||
if (!local && !fonts) return;
|
||||
// Weekly puzzles, scenarios and Architect runs are published between releases: ask the network first, and keep a copy for offline.
|
||||
if (local && (url.pathname.startsWith('/puzzles/weekly/') || url.pathname.startsWith('/scenarios/weekly/') || url.pathname.startsWith('/architect/weekly/'))) {
|
||||
e.respondWith(fetch(req).then((r) => { if (r.ok) { const copy = r.clone(); caches.open(CACHE).then((c) => c.put(req, copy)); } return r; })
|
||||
.catch(() => caches.match(req).then((r) => r || Response.error())));
|
||||
return;
|
||||
}
|
||||
e.respondWith(caches.open(CACHE).then((c) => c.match(req).then((hit) => {
|
||||
const net = fetch(req).then((r) => { if (r && (r.ok || r.type === 'opaque')) c.put(req, r.clone()); return r; }).catch(() => hit);
|
||||
return hit || net;
|
||||
|
|
|
|||
130
src/agent/10-domains.js
Normal file
130
src/agent/10-domains.js
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
/* ================= AGENT API: argument domains =================
|
||||
The agent facade (window.TUBES, this folder) is how tools play the game: the MCP server (scripts/mcp.js) calls it in
|
||||
its own jsdom page, or in the player's tab through the agent relay (80-relay.js). It is part of the development page
|
||||
only (<!-- @include-dev agent -->): the page players get has none of it, so nothing in src/game/ may name anything
|
||||
defined here; the game offers HOOKS instead. Nothing here runs until a tool calls it or the player switches agent
|
||||
mode on: these files define tables and functions, and 99-start.js wires agent mode in.
|
||||
A domain is what an argument may be: an id in a catalog table, a key, an index, a small fixed list, or a check. */
|
||||
const API_DOMAINS={
|
||||
// Tables from the catalog: an id in a list, a key in an object, or an index into a list.
|
||||
cityId:{table:'CITIES',kind:'id'},
|
||||
netId:{table:'NETS',kind:'id'},
|
||||
cableId:{table:'CABLES',kind:'id'},
|
||||
fabId:{table:'FAB',kind:'key'},
|
||||
opticId:{table:'OPT',kind:'key'},
|
||||
systemId:{table:'DF_SYS',kind:'key'},
|
||||
designId:{table:'SEA_DESIGNS',kind:'key'},
|
||||
upgradeId:{table:'SUB_UPGRADES',kind:'key'},
|
||||
bizTypeId:{table:'BIZ_T',kind:'key'},
|
||||
portTier:{table:'PORT',kind:'index'},
|
||||
linkTier:{table:'LT',kind:'index'},
|
||||
nniTier:{table:'NNI',kind:'index'},
|
||||
vxcTier:{table:'VXC',kind:'index'},
|
||||
routerModel:{table:'RG',kind:'index'},
|
||||
scrubTier:{table:'SCRUB_TIERS',kind:'index'},
|
||||
satBird:{table:'SATS',kind:'key'},
|
||||
wispZone:{table:'WISP',kind:'key'},
|
||||
satG:{kind:'enum',values:()=>[...new Set(Object.values(SAT_ORB).flatMap(o=>o.g))].sort((a,b)=>a-b)},
|
||||
// Small fixed vocabularies the game itself checks by list membership.
|
||||
// The link metric presets, plus "custom" for a hand-tuned number (ACT.setMetric).
|
||||
metric:{kind:'enum',values:()=>[...Object.keys(MET),'custom']},
|
||||
egress:{table:'PREF',kind:'key'},
|
||||
routeMode:{table:'RT',kind:'key'},
|
||||
salesPersona:{table:'SALES',kind:'key'},
|
||||
site:{kind:'enum',values:['a','b','ab']},
|
||||
step:{kind:'enum',values:[1,-1]},
|
||||
connKind:{kind:'enum',values:['t','p','ix','c','nni']},
|
||||
egressKind:{kind:'enum',values:['t','p','ix','c','nni','l2']},
|
||||
peerPolicy:{table:'PPOL',kind:'enum'},
|
||||
// The intern, their orders and the new-POP template (opsHire, opsToggle, opsParam…).
|
||||
internId:{table:'INTERNS',kind:'key'},
|
||||
opsKey:{table:'OPSK',kind:'key'},
|
||||
opsPopKind:{kind:'enum',values:()=>OPS_POP.slice()},
|
||||
opsTplKey:{kind:'enum',values:()=>OPS_TPL.slice()},
|
||||
// The build standard's targets (bstdSet).
|
||||
bstdKey:{kind:'enum',values:()=>BSTD.map(x=>x.k)},
|
||||
// The three POP standards (#315).
|
||||
popTier:{kind:'enum',values:()=>POP_TIERS.slice()},
|
||||
// The specialist's offers: a seat on a consortium cable, the charter, a vendor demo.
|
||||
seatPairs:{kind:'enum',values:()=>SEAT_N.slice()},
|
||||
callAmount:{kind:'enum',values:()=>CALL_AMTS.slice()},
|
||||
charterKey:{table:'CHARTERS',kind:'key'},
|
||||
// The link metric editor: a factor or an exact weight (metricMode, metricSet).
|
||||
metricKind:{kind:'enum',values:['f','w']},
|
||||
// The NOC's auto-mitigation switches (ddosAuto).
|
||||
ddosKey:{kind:'enum',values:['rtbh','scrub']},
|
||||
// Puzzle and architect builds: the tiers a puzzle may light, the router models it offers.
|
||||
pztTier:{kind:'fn',ok:v=>PZ_TIERS.includes(+v)||AR_TIERS.includes(+v)},
|
||||
pzRouterModel:{table:'PZ_RG',kind:'index'},
|
||||
pzRouteMode:{kind:'enum',values:['normal','fast']},
|
||||
// The bulk PNI order takes one network or null for every network at every shared POP (ACT.pniAll).
|
||||
pniAllNet:{kind:'fn',ok:v=>v===null||(typeof v==='string'&&!!NET[v])},
|
||||
// The total a sheet showed (pniAll, bstdApply carry it as q): the game refuses a different one (bstdApply: more than 1% away).
|
||||
shownTotal:{kind:'fn',ok:v=>typeof v==='number'&&Number.isFinite(v)},
|
||||
dashTab:{kind:'enum',values:()=>DTABS.slice()},
|
||||
dashSortKey:{kind:'enum',values:['name','asn','type','traffic','cost','lost']},
|
||||
leftTab:{kind:'enum',values:['goals','deals','noc','nets']},
|
||||
netFilter:{kind:'enum',values:['all','out']},
|
||||
pniFilter:{kind:'enum',values:['all','t','worth','pni']},
|
||||
listPage:{kind:'enum',values:['conn','cust','nets','pni','pops']},
|
||||
popsSortKey:{kind:'enum',values:['eye','cost','name']},
|
||||
custSortKey:{kind:'enum',values:['mood','mo','name','city']},
|
||||
connFilter:{kind:'enum',values:['all','k']},
|
||||
connSortKey:{kind:'enum',values:['k','city','name','use','mo']},
|
||||
dfSource:{kind:'enum',values:['lease','build','cable']},
|
||||
cityIdArray:{kind:'array',of:'cityId'},
|
||||
// Anything a panel can reach: an exchange city, a rival exchange id, one of your own exchanges.
|
||||
ixId:{kind:'fn',ok:v=>isIx(v)},
|
||||
// A PNI also takes tier:-1, the 1G courtesy port a network may offer (ACT.pni).
|
||||
pniTier:{kind:'fn',ok:v=>v===-1||(Number.isInteger(v)&&v>=0&&v<PORT.length)},
|
||||
// Keys are built at render time by confKey(), so they can only be resolved against the calendar.
|
||||
confKey:{kind:'fn',ok:v=>typeof v==='string'&&upcomingConfs(75).some(c=>c.key===v)},
|
||||
// traceroute goes to your own POPs and to networks; traceModal parses a net:/city: prefix.
|
||||
traceTo:{kind:'fn',ok:v=>typeof v==='string'&&(NET[v]||isCity(v))},
|
||||
// Entity ids (uid()) cannot be validated against a table: shape only. A wrong id is the game's
|
||||
// to answer, honestly, with no_effect — never a refusal invented on this side of the wall.
|
||||
entityId:{kind:'string'},
|
||||
// Pie in the Sky (the rocket company, unlocked by a Tier 1 win in a new game or from day 0 in a sandbox).
|
||||
rocketId:{table:'ROCKETS',kind:'key'},
|
||||
crustId:{table:'CRUSTS',kind:'key'},
|
||||
pieRdId:{table:'PIE_RD',kind:'key'},
|
||||
pieTab:{kind:'enum',values:()=>PIE_TABS.slice()},
|
||||
pieBidShare:{kind:'enum',values:()=>PIE_RDF_BIDS.slice()},
|
||||
pieSpatId:{table:'PIE_SPAT_DEF',kind:'key'},
|
||||
pieSpatChoice:{kind:'enum',values:[0,1]},
|
||||
countryCode:{kind:'enum',values:()=>[...new Set(CITIES.map(c=>c.cc))].sort()},
|
||||
// Address space: an IPv4 prefix length the market sells, and the CGNAT and NAT64 ratios.
|
||||
ip4Len:{kind:'enum',values:()=>Array.from({length:IP4_MAX-IP4_MIN+1},(_,i)=>IP4_MIN+i)},
|
||||
ip4Ratio:{kind:'enum',values:()=>IP4_NAT.slice()},
|
||||
ip4Ratio64:{kind:'enum',values:()=>IP4_N64.slice()},
|
||||
scnId:{table:'SCN',kind:'id'},
|
||||
// A traceroute target in the modal's own terms.
|
||||
};
|
||||
|
||||
/* Type names an arg can take instead of a domain: 'string' | 'boolean' | 'integer'. */
|
||||
|
||||
function apiDomCheck(dom,v){
|
||||
const d=API_DOMAINS[dom];
|
||||
// The game's own buttons ship truthiness as 0 and 1 (custOpen's {"sad":0}); accept the game's dialect.
|
||||
if(dom==='boolean')return {ok:v===true||v===false||v===0||v===1};
|
||||
if(!d)return {ok:dom==='integer'?Number.isInteger(v):typeof v===dom}; // 'string' | 'integer'
|
||||
if(d.kind==='array')return {ok:Array.isArray(v)&&v.every(x=>apiDomCheck(d.of,x).ok)};
|
||||
const t=d.table?API_CATALOG_TABLE(d.table):null;
|
||||
if(d.kind==='id')return {ok:!!t&&t.some(x=>x&&x.id===v)};
|
||||
if(d.kind==='string')return {ok:typeof v==='string'};
|
||||
if(d.kind==='key'||d.kind==='enum'){
|
||||
const vs=d.kind==='key'?Object.keys(t||{}):(t||(typeof d.values==='function'?d.values():d.values)||[]);
|
||||
return {ok:vs.includes(v)};}
|
||||
if(d.kind==='index')return {ok:Number.isInteger(v)&&v>=0&&v<(t?t.length:0)};
|
||||
return {ok:!!d.ok&&d.ok(v)};
|
||||
}
|
||||
function apiDomValues(dom){
|
||||
const d=API_DOMAINS[dom];if(!d)return null;
|
||||
const t=d.table?API_CATALOG_TABLE(d.table):null;
|
||||
if(d.kind==='array')return {of:d.of};
|
||||
if(d.kind==='id')return t?t.map(x=>x.id):[];
|
||||
if(d.kind==='key')return t?Object.keys(t):[];
|
||||
if(d.kind==='enum')return t||(typeof d.values==='function'?d.values():d.values)||[];
|
||||
if(d.kind==='index')return {from:0,to:(t?t.length:1)-1};
|
||||
return null;
|
||||
}
|
||||
730
src/agent/20-commands.js
Normal file
730
src/agent/20-commands.js
Normal file
|
|
@ -0,0 +1,730 @@
|
|||
/* ================= AGENT API: the command tables =================
|
||||
Every action in ACT is in exactly one class (tests/mcp-commands.test.js fails otherwise, so a new action forces a
|
||||
decision): API_CMD, a game command with typed arguments; API_VIEW, which changes only what is on screen; API_BOUND,
|
||||
which only drafts an input another command reads; API_SESSION, which starts, retries or leaves a game or dismisses a
|
||||
coaching screen; or API_DENY, never run by a tool. CMD fields: args [name, domain|'string'|'boolean'|'integer',
|
||||
required]; bind(args) writes the UI a panel would set (bindsUI: the UI keys it touches, restored after a dry run);
|
||||
open/dom: the window an input lives in and the fields that must exist before dispatch; pass(args) reshapes the args
|
||||
for the action (confirmations); confirm 'arg' (passed through) or 'double' (the game arms a button first); decides
|
||||
(may end in a question); reads 'modal' (the window's text is the report); watch (extra fingerprint paths, #name
|
||||
filled from args); quote (the dry run, priced with the game's own helpers); doc. */
|
||||
const API_CMD={
|
||||
/* ---------- Pie in the Sky: the rocket company (Tier 1 in a new game, or a sandbox) ---------- */
|
||||
pieFound:{args:[],watch:['pie'],quote:a=>({setup:piePrice(PIE_CO),monthly:PIE_CO_MO}),doc:'Found the rocket company. Needs Tier 1 (or a sandbox).'},
|
||||
pieFactory:{args:[],watch:['pie'],quote:a=>({setup:piePrice(PIE_FAC)}),doc:'Build the pie factory: it bakes the satellites ("pies") that rockets carry.'},
|
||||
piePad:{args:[['city','cityId']],watch:['pie'],doc:'Build a launch pad in a city. Pads near the equator lift more.'},
|
||||
pieRd:{args:[['k','pieRdId']],watch:['pie'],quote:a=>({setup:piePrice(PIE_RD[a.k].cost)}),doc:'Fund rocket R&D: reuse (reusable boosters, cheaper launches) or heavy (a bigger rocket, after test flights).'},
|
||||
pieLaunch:{args:[['rk','rocketId'],['cr','crustId']],watch:['pie'],doc:'Queue a launch of a rocket into a crust (an orbital shell). Insurance and lasers follow the Launch tab toggles (pieIns, pieLas).'},
|
||||
pieDish:{args:[['city','cityId']],watch:['pie'],doc:'Build a pie dish (ground station) at one of your POPs. Needs landing rights in its country.'},
|
||||
pieAnt:{args:[['id','entityId']],watch:['pie'],quote:a=>({setup:piePrice(PIE_ANT)}),doc:'Add an antenna to a pie dish (20 Gbps each, 16 at most).'},
|
||||
pieLic:{args:[['cc','countryCode']],watch:['pie'],doc:'Buy or renew landing rights in a country, for its dishes and orbit customers.'},
|
||||
pieSafe:{args:[],watch:['pie'],doc:'Toggle safe mode: pies ride out solar storms, carrying nothing meanwhile.'},
|
||||
pieName:{args:[],watch:['pie'],doc:'Rename the rocket company to the next name on the list.'},
|
||||
pieBid:{args:[['id','entityId'],['f','pieBidShare']],watch:['pie'],doc:'Bid in a Rural Digital Pie Fund auction, asking this share of the reserve. The lower ask wins.'},
|
||||
pieExim:{args:[],watch:['pie','loans'],doc:'Take the Export-Import Pie Bank loan, with its space covenants.'},
|
||||
pieSpatPick:{args:[['id','pieSpatId'],['c','pieSpatChoice']],watch:['pie'],doc:'Answer a geopolitical spat over orbit: choice 0 or 1, as its sheet offers.'},
|
||||
downIx:{args:[['city','ixId']],watch:['ixp'],doc:'Step an exchange port down one size.'},
|
||||
downT:{args:[['id','entityId']],watch:['transit.#id'],doc:'Step a transit port down one size (a LAG steps down together).'},
|
||||
downP:{args:[['id','entityId']],watch:['pni.#id'],doc:'Step a PNI down one size. Not while an augment is on order.'},
|
||||
/* ---------- footprint: buildings, routers, POPs ---------- */
|
||||
buildPop:{args:[['city','cityId']],
|
||||
quote:a=>({setup:popCost(a.city),blocked:[cityOn(a.city)?'':popOffWhy(a.city),cnCity(a.city)&&!cnOk()?tr('pops_transit_ix.you_need_a_license_first_foreign'):''].filter(Boolean)}),
|
||||
doc:'Open a POP in a city you do not have one in. Costs popCost(city). Not in a retired small city (off the map in new games).'},
|
||||
launchBB:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>({setup:bbCost(a.city)}),
|
||||
doc:'Launch broadband to the eyeballs of a city you have a POP in. The core revenue source; one per POP.'},
|
||||
ad:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>({setup:8000}),
|
||||
doc:'A 30-day ad campaign that boosts eyeball growth in a broadband city.'},
|
||||
addRouter:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>{const p=S.pops[a.city];return {setup:p?routerCost(p.rgen||0,p.routers||1):0};},
|
||||
doc:'Add a router to a POP, up to RMAX. Cost rises with the model and the count.'},
|
||||
rmRouter:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>{const p=S.pops[a.city];return {setup:-((p&&tradeIn(p.rgen||0,1))||0),blocked:p&&portsUsed(a.city)>portsMax(a.city,undefined,p.routers-1)?[tr('routing_and_routers.unplug_something_first_used_ports',{used:fmtPorts(portsUsed(a.city)),max:portsMax(a.city,undefined,p.routers-1)})]:[]};},
|
||||
doc:'Remove a router and sell it on eBuy for a trade-in. Refused while the rest cannot carry the ports.'},
|
||||
upRouter:{args:[['city','cityId'],['g','routerModel',false]],watch:['pops.#city'],
|
||||
quote:a=>{const p=S.pops[a.city];if(!p)return {};const g=a.g===undefined?mainRG(RG[p.rgen||0].cls+1):+a.g;
|
||||
return {setup:swapCost(a.city,g),blocked:[(!RG[g]||g===(p.rgen||0))?'no such model':modelFits(a.city,g)||''].filter(Boolean)};},
|
||||
doc:'Swap every router in a city for another model. Omit g for the next class up. One swap per day per city.'},
|
||||
addGen:{args:[['city','cityId']],watch:['pops.#city'],quote:a=>({setup:GEN_COST,monthly:GEN_MO}),
|
||||
doc:'Install a generator, so a power cut does not take the POP out.'},
|
||||
addSite:{args:[['city','cityId']],watch:['pops.#city'],quote:a=>({setup:SITE2_COST,monthly:SITE2_MO}),
|
||||
doc:'Add a second building in the city, so one dark data centre does not take everything down.'},
|
||||
rmSite:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'],
|
||||
doc:'Remove the second building. Every port, PNI and cache there moves back to site A.'},
|
||||
decomGo:{args:[['cities','cityIdArray']],bindsUI:['decom'],bind:a=>{UI.decom=new Set((a.cities||[]).filter(c=>S.pops[c]));},
|
||||
doc:'Close POPs: cancels their ports, links, peerings and customers. Refuses to close every POP you have. Irreversible.'},
|
||||
/* ---------- upstream (transit) ---------- */
|
||||
buyTransit:{args:[['city','cityId'],['net','netId'],['tier','portTier']],
|
||||
quote:a=>({setup:PORT[a.tier].setup,monthly:PORT[a.tier].tmo}),
|
||||
doc:'Order a transit port from a network that sells in that city. Billed monthly on the 95th percentile. A higher tier on an existing port upgrades it.'},
|
||||
lagT:{args:[['id','entityId'],['d','step']],watch:['transit.#id'],
|
||||
quote:a=>{const t=S.transit.find(x=>x.id===a.id);return {setup:a.d>0&&t?PORT[t.tier].setup:0};},
|
||||
doc:'Add or remove one LAG member on a transit port, up to LAG_MAX. Adding charges another port setup.'},
|
||||
cancelTransit:{args:[['id','entityId']],confirm:'arg',pass:a=>({id:a.id,ok:1}),
|
||||
doc:'Cancel a transit port.'},
|
||||
togglePrem:{args:[['id','entityId']],watch:['transit.#id'],
|
||||
doc:'Turn the premium upstream product on or off, where the network sells one in that city.'},
|
||||
cleanPipe:{args:[['id','entityId']],watch:['transit.#id'],
|
||||
quote:a=>{const t=S.transit.find(x=>x.id===a.id);return t?{monthly:cleanMo(t)}:{};},
|
||||
doc:'Add or remove the upstream DDoS-scrubbing add-on. Monthly.'},
|
||||
/* ---------- exchanges ---------- */
|
||||
buyIx:{args:[['city','ixId'],['tier','portTier'],['signed','boolean',false]],decides:true,
|
||||
quote:a=>({setup:ixPortMo(a.city,a.tier),monthly:ixPortMo(a.city,a.tier),blocked:[portOk(ixCity(a.city),a.tier)?'':tr('actions.your_router_can_t_take_a',{port:PORT[a.tier].n})].filter(Boolean)}),
|
||||
doc:'Take a port on an internet exchange. Monthly. At a De-Kicks exchange the first order returns a personalised quote to answer. A remote port (no POP) is possible at 10G over a fabric.'},
|
||||
lagIx:{args:[['city','ixId'],['d','step']],watch:['ixn'],
|
||||
doc:'Add or remove one LAG member on an IX port. Not on your own exchange.'},
|
||||
cancelIx:{args:[['city','ixId']],confirm:'arg',pass:a=>({city:a.city,ok:1}),decides:true,
|
||||
doc:'Leave an exchange; drops every peering session there. De-Kicks may answer with a retention offer.'},
|
||||
rs:{args:[['city','ixId']],watch:['rs'],
|
||||
doc:'Toggle the route-server session, which peers you with everyone on the server at once.'},
|
||||
foundIx:{args:[['city','cityId']],watch:['myIx.#city'],quote:a=>({setup:MYIX_COST,monthly:MYIX_MO,blocked:[foundIxWhy(a.city)].filter(Boolean)}),
|
||||
doc:'Found your own exchange in a city with no IX where you have a POP. Not in mainland China. Networks join over the following days.'},
|
||||
myIxUp:{args:[['city','cityId']],watch:['myIx.#city'],
|
||||
quote:a=>{const m=S.myIx[a.city];const f=m?(m.fab|0)+1:0,N=f<MYIX_FAB.length?MYIX_FAB[f]:null;return N?{setup:N.cost,monthly:N.mo}:{};},
|
||||
doc:'Upgrade your own exchange\'s switch fabric. Each step has a level gate.'},
|
||||
/* ---------- peering and PNIs ---------- */
|
||||
peer:{args:[['city','ixId'],['net','netId']],
|
||||
doc:'Ask one network at an exchange for a session. Rejected with the network\'s own reason if its policy says no.'},
|
||||
unpeer:{args:[['city','ixId'],['net','netId']],
|
||||
doc:'Drop a peering session.'},
|
||||
peerAll:{args:[['city','ixId']],
|
||||
doc:'Ask everyone at that exchange who would say yes. No effect if there is nobody new.'},
|
||||
pni:{args:[['city','cityId'],['net','netId'],['tier','pniTier']],
|
||||
quote:a=>{const t=a.tier===-1?0:a.tier,ex=S.pni.find(p=>p.city===a.city&&p.net===a.net),r=peerOk(a.net,'pni',a.city);
|
||||
return {setup:a.tier===-1?PNI_G1_COST:(1500+PORT[t].setup/2)*((ex&&ex.n)||1),monthly:(a.tier===-1?Math.round(PORT[0].pni/2):PORT[t].pni)*((ex&&ex.n)||1),days:pniLead(a.net),
|
||||
blocked:[r.ok?'':r.why,portOk(a.city,t)?'':tr('actions.your_router_can_t_take_a',{port:PORT[t].n}),
|
||||
a.tier!==-1&&a.tier<pniMin(a.net)?tr('sites_peering_caches.net_does_not_do_port_pnis',{net:NET[a.net].name,port:PORT[t].n}):''].filter(Boolean)};},
|
||||
doc:'Order a private interconnect. tier:-1 asks for the 1G courtesy PNI where a network offers one. Takes weeks to months; an existing PNI is augmented instead.'},
|
||||
pniChase:{args:[['id','entityId']],watch:['pni.#id'],
|
||||
doc:'Chase the provisioning ticket. 15% pulls the date in by 30 days; otherwise an excuse.'},
|
||||
cancelPni:{args:[['id','entityId']],confirm:'arg',pass:a=>({id:a.id,ok:1}),
|
||||
doc:'Cancel a PNI or its pending augment.'},
|
||||
lagP:{args:[['id','entityId'],['d','step']],watch:['pni.#id'],
|
||||
doc:'Add or remove a LAG member on a PNI, up to 8 per router at the POP (pniLagMax, at most PNI_LAG_MAX). Adding is an augment with a lead time.'},
|
||||
sacrif:{args:[['id','entityId']],watch:['pni.#id'],
|
||||
doc:'Mark a PNI sacrificial, so attack traffic is steered into it.'},
|
||||
peerPol:{args:[['p','peerPolicy']],watch:['ppol'],
|
||||
doc:'Set your published peering policy: open, selective or closed. It answers every peering request for you: open accepts everyone, selective takes small networks on the exchange and newcomers with an up-to-date PeeringDB, closed declines them all. The NOC log sums the week up.'},
|
||||
/* ---------- caches ---------- */
|
||||
cache:{args:[['city','cityId'],['net','netId']],
|
||||
quote:a=>{const n=NET[a.net];return {monthly:n&&n.cache?CACHE_MO:0,
|
||||
blocked:n&&n.cache&&(R.demTo[a.net]||0)<n.cache.min?[tr('sites_peering_caches.net_says_not_yet_send_them',{net:n.name,min:n.cache.min})]:[]};},
|
||||
doc:'Ask a CDN to ship you a cache. Monthly. Rejected until you send that network enough traffic.'},
|
||||
rmCache:{args:[['id','entityId']],
|
||||
doc:'Send a cache box back.'},
|
||||
cacheSite:{args:[['city','cityId'],['net','netId'],['s','site']],watch:['caches'],
|
||||
doc:'Move one of that CDN\'s boxes to the other building.'},
|
||||
/* ---------- backbone links ---------- */
|
||||
buildLink:{args:[['a','cityId'],['b','cityId'],['tier','linkTier'],['cable','cableId',false],['route','string',false],['premiumCrossing','boolean',false]],
|
||||
bindsUI:['pending','route','via','cnPrem'],
|
||||
bind:a=>{UI.pending={a:a.a,b:a.b};UI.route=a.route||'';UI.via=a.cable||'';UI.cnPrem=!!a.premiumCrossing;},
|
||||
pass:a=>({tier:a.tier}),
|
||||
quote:a=>{const A=a.a,B=a.b,tier=a.tier;
|
||||
if(!S.pops[A])return {blocked:[linkFromWhy(A)]};
|
||||
if(!waveOk(A,B,tier))return {blocked:[tr('links.a_wave_wave_needs_need_at',{wave:LT[tier].n,need:waveNeed(tier)})]};
|
||||
const sib=pairLinks(A,B).filter(l=>l.kind!=='vxc'&&l.kind!=='xp'&&l.kind!=='sat'),jn=sib.length?routeJoin(A,B):null,border=cnCity(A)!==cnCity(B);
|
||||
const mult=(sib.length&&!(jn&&jn.k===(landTrenches(A,B)[0]||{}).k)?DIVERSE:1)*(border?3*((a.premiumCrossing&&(A==='hkg'||B==='hkg'))?1.6:1):1);
|
||||
const wr=waveRoute(A,B,mult,border);if(!wr)return {blocked:[tr('links.no_cable_available_for_that_route')]};
|
||||
const blocked=[],so=soldOut(A,B,tier,wr.cab);
|
||||
if(so)blocked.push(tr('links.no_wave_capacity_on_this_route',{wave:LT[tier].n,why:tr(so.why),n:Math.max(1,so.until-S.day)}));
|
||||
const w=subWaveWhy(tier,wr.km,wr.sub);if(w)blocked.push(tr('links.no_wave_waves_on_this_cable',{wave:LT[tier].n,why:w}));
|
||||
return {setup:Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm)+(S.pops[B]?0:popCost(B)),monthly:Math.round(waveMo(wr.km,wr.sub,tier)*wr.wm),blocked};},
|
||||
doc:'Lease a wave from one of your POPs (a) to any city; opens a POP in b if there is none. A second wave on a pair costs 1.4x unless it joins an existing trench; cross-border into mainland China costs 3x. premiumCrossing applies only via Hong Kong.'},
|
||||
upLink:{args:[['id','entityId'],['tier','linkTier']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};
|
||||
const blocked=[waveOk(l.a,l.b,a.tier)?'':tr('links.a_wave_wave_needs_need_at',{wave:LT[a.tier].n,need:waveNeed(a.tier)})];
|
||||
const w=subWaveWhy(a.tier,l.km,l.sub);if(w)blocked.push(tr('links.no_wave_waves_on_this_cable',{wave:LT[a.tier].n,why:w}));
|
||||
return {monthly:Math.round(waveMo(l.km,l.sub,a.tier)*(l.mult||1)),blocked:blocked.filter(Boolean)};},
|
||||
doc:'Upgrade a leased wave in place. Upward only, and only if the span and cable support it.'},
|
||||
rmLink:{args:[['id','entityId']],confirm:'double',
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return {setup:-((l&&cabBack(l))||0)};},
|
||||
doc:'Decommission a link. A cancelled own-cable build refunds part of the money. Irreversible.'},
|
||||
setMetric:{args:[['id','entityId'],['v','metric']],watch:['pairMet'],
|
||||
doc:'Routing preference for the city pair this link belongs to (not the link): prefer, normal, avoid, backup, or custom (then metricMode and metricSet tune the number).'},
|
||||
setCarry:{args:[['id','entityId'],['on','boolean']],watch:['transit.#id'],
|
||||
doc:'Turn a transit port\'s Carry here on or off: it pulls that carrier\'s traffic (and its customers\') across your network from POPs that have no port of that carrier. Prefer, Backup only and RouteScript still win.'},
|
||||
setStandby:{args:[['id','entityId'],['on','boolean']],watch:['links.#id'],
|
||||
doc:'Hold a link in reserve: its capacity fills last.'},
|
||||
/* ---------- fabrics and VXCs ---------- */
|
||||
buyNni:{args:[['city','cityId'],['prov','fabId'],['tier','nniTier']],
|
||||
quote:a=>{const ex=nniPort(a.city,a.prov),n=ex?(ex.n||1):1,m=NNI[a.tier]?NNI[a.tier].mo*n:undefined;return {setup:m,monthly:m};},
|
||||
doc:'Take a port on an interconnection fabric, at any port speed the router takes. Monthly, the first month up front. A higher tier upgrades every member of the port.'},
|
||||
lagNni:{args:[['city','cityId'],['prov','fabId'],['d','step']],watch:['nni'],
|
||||
quote:a=>{const pt=nniPort(a.city,a.prov),m=pt&&a.d>0&&NNI[pt.tier]?NNI[pt.tier].mo:0;return {setup:m,monthly:m};},
|
||||
doc:'Add (d:1) or remove (d:-1) a member of the fabric port\'s LAG: same speed, one more router port, up to 8. Removing is rejected while the circuits would not fit.'},
|
||||
rmNni:{args:[['city','cityId'],['prov','fabId']],
|
||||
doc:'Give the fabric port back. Rejected while circuits still use it.'},
|
||||
buyVxc:{args:[['a','cityId'],['b','cityId'],['prov','fabId'],['t','vxcTier']],
|
||||
quote:a=>({monthly:vxcMo(kmBetween(a.a,a.b),isSub(a.a,a.b),a.t)}),
|
||||
doc:'Buy a virtual circuit between two fabric ports. Up in 59 seconds, which is the joke.'},
|
||||
upVxc:{args:[['id','entityId'],['t','vxcTier']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l&&l.kind==='vxc'?{monthly:vxcMo(l.km,l.sub,a.t)}:{};},
|
||||
doc:'Grow a circuit. Needs headroom at both ends.'},
|
||||
cancelVxc:{args:[['id','entityId']],confirm:'double',
|
||||
doc:'Cancel a circuit; any remote IX ports it reached go with it.'},
|
||||
setPref:{args:[['kind','connKind'],['id','entityId'],['v','egress']],watch:['transit.#id','pni.#id'],
|
||||
doc:'Egress preference for one exit: high sends more traffic that way, low keeps it for backup.'},
|
||||
siteSet:{args:[['k','connKind'],['id','entityId'],['s','site']],watch:['transit.#id','pni.#id'],
|
||||
doc:'Put a transit port, PNI or IX port in building A, B or both. Choosing both with a single member adds a LAG member first, and charges for it.'},
|
||||
/* ---------- teleports and satellite capacity (#83) ---------- */
|
||||
teleBuild:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>({setup:TPORT_COST,monthly:TPORT_MO,blocked:[teleOf(a.city)?'there is a teleport here already':teleWhy(a.city)].filter(Boolean)}),
|
||||
doc:'Build a teleport (a satellite gateway) at one of your POPs: it rents circuits on GEO birds to small islands and remote towns in their footprint. Refused where no satellite on sale at your level sees the city.'},
|
||||
teleTrk:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>({setup:TRK_COST,monthly:TRK_MO,blocked:[teleOf(a.city)===2?'this teleport has tracking antennas already':trkWhy(a.city)].filter(Boolean)}),
|
||||
doc:'Add tracking antennas to a teleport, so it can work the MEO ring (about 130 ms round trip instead of GEO\'s 600). Only within 50 degrees of the equator, where the ring is in view.'},
|
||||
teleRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'],
|
||||
doc:'Close a teleport (and its LEO gateway). Refused while circuits still start there.'},
|
||||
teleLeo:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>({setup:LEO_GW_COST,monthly:LEO_GW_MO,blocked:[leoGw(a.city)?'there is a LEO gateway here already':leoGwWhy(a.city)].filter(Boolean)}),
|
||||
doc:'Host a Starblink LEO gateway at your teleport (level 5, a POP on your fiber or with transit, within 56 degrees of the equator): LEO circuits from it reach small islands and remote towns within 1,200 km, about 30 ms round trip. Refused once your own constellation carries traffic.'},
|
||||
teleLeoRm:{args:[['city','cityId']],confirm:'double',watch:['pops.#city'],
|
||||
doc:'Close a LEO gateway. Refused while LEO circuits still start there.'},
|
||||
buySat:{args:[['a','cityId'],['b','cityId'],['bird','satBird'],['g','satG']],
|
||||
quote:a=>{const ok=own(SATS,a.bird),mo=ok?satMo(a.bird,+a.g):0;return {setup:mo+(S.pops[a.b]||!CITY[a.b]?0:popCost(a.b)),monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[satWhy(a.a,a.b,a.bird,+a.g)].filter(Boolean)};},
|
||||
doc:'Rent a satellite circuit from your teleport in a to b (a small island or a remote town) on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas, LEO 5-50 from a LEO gateway within 1,200 km (about 30 ms round trip; it puts GEO and MEO circuits on the same pair on standby, and one ordered beside it waits on standby). The first month up front; builds a POP at b if there is none. Next to an existing link between the two it goes on standby, as backup; a link built later between the two puts it on standby too. Cancel with rmLink.'},
|
||||
satSize:{args:[['id','entityId'],['g','satG']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id&&x.kind==='sat'),g=+a.g,ok=!!l&&g!==l.g&&SAT_ORB[SATS[l.bird].orb].g.includes(g),mo=ok?satMo(l.bird,g):0;
|
||||
return {setup:ok&&g>l.g?mo:0,monthly:mo,blocked:!l?['not a satellite circuit']:ok?[g>l.g&&leoLink(l)?leoGrowWhy(l):''].filter(Boolean):[tr('satellites.no_such_circuit')]};},
|
||||
doc:'Resize a satellite circuit on the same bird. A bigger one pays its new month up front; a LEO circuit grows only while its gateway is on your fiber and your own constellation carries nothing.'},
|
||||
wispSat:{args:[['z','wispZone'],['bird','satBird'],['g','satG']],watch:['pops'],
|
||||
quote:a=>{const ok=own(WISP,a.z)&&own(SATS,a.bird),mo=ok?wispSatMo(a.bird,+a.g):0;return {setup:ok?mo+(wispZ(a.z)?0:wispKit(a.z)):0,monthly:mo,days:ok?leadDays(SAT_ORB[SATS[a.bird].orb].days):0,blocked:[wispSatWhy(a.z,a.bird,+a.g)].filter(Boolean)};},
|
||||
doc:'Island Wi-Fi: rent satellite capacity for an island zone (catalog WISP; its city is c) from your teleport in that city, on a bird that sees both: GEO 1-10 Gbps, MEO 2-20 with tracking antennas, LEO 5-50 from a Starblink gateway there. A contended share, 60% of a circuit\'s price. The first order of a zone also pays the island kit (towers, solar, home radios). How many homes sign up follows the link: about 35% of the pool over GEO, 75% over MEO, 90% over LEO, all over a spur. With a circuit running, one on another bird is a move: the old one carries until the new one is commissioned. The zone\'s homes join the city\'s demand.'},
|
||||
wispSatSize:{args:[['z','wispZone'],['g','satG']],watch:['pops'],
|
||||
quote:a=>{const Z=own(WISP,a.z)?wispZ(a.z):null,o=Z&&Z.sat,g=+a.g,ok=!!o&&g!==o.g&&SAT_ORB[wispOrb(o)].g.includes(g),mo=ok?wispSatMo(o.bird,g):0;
|
||||
return {setup:ok&&g>o.g?mo:0,monthly:mo,blocked:!o?['no circuit for that zone']:ok?[g>o.g&&wispOrb(o)==='leo'?leoGrowWhy({a:WISP[a.z].c}):''].filter(Boolean):[tr('satellites.no_such_circuit')]};},
|
||||
doc:'Resize an island zone\'s satellite circuit on the same bird. A bigger one pays its new month up front.'},
|
||||
wispSatRm:{args:[['z','wispZone']],confirm:'double',watch:['pops'],
|
||||
doc:'Cancel an island zone\'s satellite circuit (and a move being commissioned). With no spur lit, its homes go offline and leave.'},
|
||||
wispSpur:{args:[['z','wispZone']],watch:['pops'],
|
||||
quote:a=>{const ok=own(WISP,a.z);return {setup:ok?wispSpurCost(a.z)+(wispZ(a.z)?0:wispKit(a.z)):0,monthly:ok?wispSpurMo(a.z):0,days:ok?wispSpurDays(a.z):0,blocked:[wispSpurWhy(a.z)].filter(Boolean)};},
|
||||
doc:'Island Wi-Fi: lay a spur cable from the zone\'s city (level 3; not every zone can have one). Every home there may sign up once it is lit, and nothing is rented. A spur can be cut (weeks to mend, or a $250k repair ship): a satellite circuit kept beside it carries the islands meanwhile. A zone may start with a spur alone (with the island kit).'},
|
||||
wispRm:{args:[['z','wispZone']],confirm:'double',watch:['pops'],
|
||||
doc:'Close an island Wi-Fi zone: its circuits, spur and homes go.'},
|
||||
/* ---------- dark fiber and own cable ---------- */
|
||||
orderDf:{args:[['a','cityId'],['b','cityId'],['source','dfSource'],['system','systemId']],
|
||||
bindsUI:['pending','dfSrc','dfSys'],bind:a=>{UI.pending={a:a.a,b:a.b};UI.dfSrc=a.source;UI.dfSys=a.system;},
|
||||
quote:a=>{const A=a.a,B=a.b,sc=isSub(A,B)?subDfCable(A,B):null,km=sc?sc.km:kmBetween(A,B);
|
||||
const building=a.source==='build'&&glassLvl()>=3&&!sc,sys=DF_SYS[a.system]&&DF_SYS[a.system].lvl<=glassLvl()?a.system:'lite';
|
||||
const amps=ampCount(km),blocked=[];
|
||||
if(!S.pops[A])blocked.push(linkFromWhy(A));
|
||||
if(isSub(A,B)&&!sc)blocked.push(tr('fiber_modals.nobody_sells_dark_fiber_on_a'));
|
||||
else if(uaePair(A,B))blocked.push(tr('fiber_modals.no_dark_fiber_inside_the_uae'));
|
||||
else if(landX(A,B)&&cnCity(A)===cnCity(B))blocked.push(tr('fiber_modals.nobody_sells_one_fiber_pair_across'));
|
||||
else if(!dfAllowed(A,B))blocked.push(tr('fiber_modals.dark_fiber_across_the_chinese_border'));
|
||||
if(glassLvl()<2)blocked.push(tr('fiber_modals.dark_fiber_unlocks_at_customer_level'));
|
||||
return {setup:(building?dfBuildCost(km):0)+DF_SYS[sys].cost+amps*AMP_COST+(S.pops[B]?0:popCost(B)),
|
||||
monthly:(building?Math.round(km*0.15):dfLeaseMo(km))+amps*AMP_MO,days:building?dfBuildDays(km):30,blocked};},
|
||||
doc:'Get dark fiber from one of your POPs (a): lease an IRU, dig your own (level 3+), or take a pair on a subsea cable; opens a POP in b if there is none. Then light it with a line system.'},
|
||||
orderCable:{args:[['a','cityId'],['b','cityId'],['design','designId',false],['terminal','boolean',false],['engineering','boolean',false]],
|
||||
bindsUI:['pending','seaDesign','seaterminal','seaengineering'],
|
||||
bind:a=>{UI.pending={a:a.a,b:a.b};UI.seaDesign=a.design||'standard';UI.seaterminal=!!a.terminal;UI.seaengineering=!!a.engineering;},
|
||||
quote:a=>{const why=linkFromWhy(a.a)||ownCabWhy(a.a,a.b);if(why)return {blocked:[why]};
|
||||
const design=own(SEA_DESIGNS,a.design)?a.design:'standard',up={terminal:!!a.terminal,engineering:!!a.engineering};
|
||||
const q=seaQuote(a.a,a.b,design,up),lack=seaLack(q.km,up);
|
||||
return {setup:q.cost+(S.pops[a.b]?0:popCost(a.b)),monthly:ownCabMo(q.km),days:q.days,
|
||||
blocked:lack.map(k=>k==='design'?tr('own_cable.this_design_s_route_is_km',{km:q.km.toLocaleString()})
|
||||
:tr('own_cable.km_km_is_too_far_for',{km:q.km.toLocaleString(),what:lack.length>1?tr('own_cable.a_and_b',{a:tr(SUB_UPGRADES[lack[0]].n),b:tr(SUB_UPGRADES[lack[1]].n)}):tr(SUB_UPGRADES[lack[0]].n)}))};},
|
||||
doc:'Commission your own submarine cable. A ship sails; it takes months. The most expensive thing in the game.'},
|
||||
subUpgrade:{args:[['id','entityId'],['k','upgradeId']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:subUpgradeCost(l,a.k),days:SUB_UPGRADES[a.k].days}:{};},
|
||||
doc:'Add premium submarine terminals or extra optical engineering to your own subsea cable. Level 4+, once each.'},
|
||||
crews:{args:[['id','entityId'],['all','boolean',false]],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const n=a.all?crewSteps(l):Math.min(1,crewSteps(l));return {setup:n*crewCost(l),days:n?l.ready-Math.max(crewFloor(l),l.ready-30*n):0};},
|
||||
doc:'Pay for more crews on a cable build: 30 days off per step, down to half of the planned build at most.'},
|
||||
addCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:chCost(l,a.o),blocked:[chWhy(l,a.o)].filter(Boolean)}:{};},
|
||||
doc:'Light one channel on a dark-fiber span with a given optic; uses a spare from the shelf if you have one.'},
|
||||
rmCh:{args:[['id','entityId'],['o','opticId']],watch:['links.#id'],
|
||||
doc:'Unplug a channel; the optic goes on the spares shelf.'},
|
||||
addPair:{args:[['id','entityId']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:pairCost(l)}:{};},
|
||||
doc:'Light another fiber pair on your own cable. ROADM system, finished construction, current pair full.'},
|
||||
upSys:{args:[['id','entityId']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:sysUpCost(l)}:{};},
|
||||
doc:'Upgrade the line system: Rainbow to ROADMaster to C+L. Every channel goes down for a day.'},
|
||||
regen:{args:[['id','entityId'],['d','step']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l&&a.d>0?{setup:regenAddCost(l)}:{setup:0};},
|
||||
doc:'Add or remove a regeneration site on a terrestrial span, up to REGEN_MAX. Removing is refused if the optics then cannot reach.'},
|
||||
spares:{args:[['id','entityId']],watch:['links.#id'],
|
||||
doc:'Toggle keeping spare optics on site for this span, so a card failure is fixed in hours instead of days.'},
|
||||
/* ---------- hardware ---------- */
|
||||
hwLock:{args:[],quote:a=>({setup:hwLockCost()}),
|
||||
doc:'Lock router, optic and build prices for a year, shortages included. Costs twice as much while a shortage runs.'},
|
||||
buySpare:{args:[['o','opticId']],
|
||||
quote:a=>({setup:optCost(a.o),blocked:[OPT[a.o]&&OPT[a.o].lvl>glassLvl()?tr('action_helpers.unlocks_at_customer_level_n',{n:OPT[a.o].lvl}):''].filter(Boolean)}),
|
||||
doc:'Buy a spare optic for the shelf, up to 64 of a kind. The next channel of that type is then free of optic cost.'},
|
||||
sellSpare:{args:[['o','opticId']],quote:a=>({setup:-spareValue(a.o)}),
|
||||
doc:'Sell a spare on eBuy for 40% of list.'},
|
||||
/* ---------- capacity broker ---------- */
|
||||
listFiber:{args:[['id','entityId'],['w','integer'],['p','integer',false]],watch:['links.#id'],
|
||||
doc:'List spare capacity on a dark-fiber span with a capacity broker as a standing listing: w alien waves, and p (own cables only) your spare fiber pair. The broker sells them off over time as carriers on that route want capacity; a busy route sells in days, a road to nowhere maybe once.'},
|
||||
mktHold:{args:[['v','integer']],watch:['cm'],
|
||||
doc:'Capacity market (Lambda Bazaar): the share of every fiber (0, 10, 25 or 50%) the broker never sells, kept for your own traffic.'},
|
||||
mktCfg:{args:[['p','string'],['k','string'],['v','integer']],watch:['cm'],
|
||||
doc:'Capacity market: for product p (spec = alien-wave spectrum, w100/w400 = managed 100G/400G waves carved from your lit capacity, iru = dark pairs on fiber you dug), set k: on (v 1 or 0: the broker lists it on every route by your thresholds), min (list only while the route wants at least v units; spec/w400 1,2,4,8, w100 1,4,8,16, iru 1,2) or floor (never sell below v% of list: 60, 80, 100, 120). Demand and prices move every day.'},
|
||||
mktRoute:{args:[['k','string']],watch:['cm'],
|
||||
doc:'Capacity market: toggle whether the broker trades on a route (k = the two city ids sorted and joined by |, e.g. ams|fra).'},
|
||||
unlistFiber:{args:[['id','entityId']],watch:['links.#id'],
|
||||
doc:'Take the listing down. What the broker already sold stays sold.'},
|
||||
setChCount:{args:[['id','entityId'],['o','opticId'],['n','integer']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);return l?{setup:opticCountCost(l,a.o,a.n)}:{};},
|
||||
doc:'Set how many channels of one optic model a dark-fiber span carries, in one change. Added optics come from the spares shelf when you have them (regen cards still cost their share); removed ones go back to the shelf.'},
|
||||
xpBuild:{args:[['a','cityId'],['b','cityId'],['via','string'],['o','opticId']],
|
||||
quote:a=>{const sp=xpParse(a.a,a.b,a.via);if(!sp||!OPT[a.o])return {setup:0,blocked:[tr('express.no_such_path')]};const old=xpFind(a.a,a.b,sp.map(s=>s.id));
|
||||
return {setup:xpCost(sp,a.o,!old),blocked:[xpWhy(a.a,a.b,sp,a.o)].filter(Boolean)};},
|
||||
doc:'Light an express lightpath from a to b straight through the ROADMs of the cities between: via is the ids of your ROADM dark fibers (land, own or IRU) in order from a, comma-separated, 2 to 6 of them. One optic, one channel slot on every fiber, ports only at a and b, and the light must reach the whole run between regen sites. The same path again adds a channel to that express. Give one up with rmLink.'},
|
||||
xpCh:{args:[['id','entityId'],['o','opticId'],['d','step']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id),sp=l&&l.kind==='xp'&&xpSpans(l);if(!sp||!OPT[a.o]||a.d<0)return {setup:0};return {setup:xpCost(sp,a.o,false),blocked:[xpWhy(l.a,l.b,sp,a.o)].filter(Boolean)};},
|
||||
doc:'Add (d:1) or unplug (d:-1) one channel of an optic on an express lightpath; unplugged optics go on the spares shelf. The last channel stays: rmLink gives the express up.'},
|
||||
/* ---------- customers ---------- */
|
||||
accept:{args:[['id','entityId']],
|
||||
doc:'Sign a pending offer. Rejected without a POP in every city it needs, without the IPv4 addresses it needs (rule ip4: see the bank\'s Address space), without free channels for a wave sale, or after an event\'s start date. Extra waves for a carrier you already serve grow that contract.'},
|
||||
acceptFix:{args:[['id','entityId'],['cost','integer',false]],watch:['pops','biz','offers'],
|
||||
quote:a=>{const q=S?reqFix(S.offers.find(x=>x.id===a.id)):null;return q?{setup:q.cost,monthly:q.mo}:{setup:0};},
|
||||
pass:a=>({id:a.id,cost:a.cost??((reqFix(S.offers.find(x=>x.id===a.id))||{}).cost)}),
|
||||
doc:'Buy what an offer asks for at POPs you already have (backup generator, a second router, a second site), then sign it. Pass the quoted setup as cost; the game checks it still matches (within 1%: hardware prices drift by the day).'},
|
||||
decline:{args:[['id','entityId']],
|
||||
doc:'Throw an offer away.'},
|
||||
salesHire:{args:[['id','salesPersona']],
|
||||
doc:'Put one salesperson at the sales desk: eng (engineer turned salesdroid: books every NOG at the usual ticket price, more small and mid deals, never the huge ones, customers stay longer), shark (bigger deals at higher prices plus a month of commission, oversells promises, no nerdy customers, peering desks want more traffic) or ceo (free, signs huge discounted deals on the golf course, sometimes signs what you declined, cannot be fired). One at a time; from customer level 2.'},
|
||||
salesFire:{args:[],confirm:'double',
|
||||
doc:'Let the salesperson go (not the CEO: ask the board for a VP of Sales instead).'},
|
||||
salesVp:{args:[],
|
||||
doc:'With the CEO running sales: pay for a board meeting that brings a VP of Sales, who frees the desk a month later.'},
|
||||
salesAuto:{args:[],watch:['slAuto'],
|
||||
doc:'With someone at the sales desk: switch automatic signing on or off. Once a game day they sign the offers that fit, in their own style: eng and ceo after a routing trial (one a day; an offer that did not fit waits a week), shark every offer whose POPs are up, promises and all, while the cash covers the commission. Orbit offers sign where the landing dish has room (the shark ignores that). Nobody at the desk: nothing is signed for you.'},
|
||||
salesRen:{args:[],watch:['slAuto'],
|
||||
doc:'Switch whether the sales desk answers renewal haggles for you, 3 days after each opens (only while someone runs sales). The engineer gives business customers their discount and keeps nerdy ones at the market price; the shark holds the old price (sometimes with a new promise, billing a month of the saving) but some walk; the CEO gives 10% more off for a double term, says yes, or picks a fight and loses them.'},
|
||||
salesMin:{args:[],watch:['slAuto'],
|
||||
doc:'Step the minimum monthly value under which the sales desk declines offers: never, 2k, 5k, 10k, 25k, 50k. With the CEO, about one decline in three is signed anyway.'},
|
||||
renewMatch:{args:[['id','entityId']],watch:['biz.#id'],
|
||||
doc:'Answer a renewal haggle (a customer with hag): renew at the price they asked. Unanswered, this happens on its own when the term ends.'},
|
||||
renewMeet:{args:[['id','entityId']],watch:['biz.#id'],
|
||||
doc:'Answer a renewal haggle by meeting halfway between their price and today\'s market price. They accept about two times in three; otherwise they leave.'},
|
||||
renewLet:{args:[['id','entityId']],
|
||||
doc:'Answer a renewal haggle by letting the customer go now.'},
|
||||
dropBiz:{args:[['id','entityId']],confirm:'double',
|
||||
doc:'Terminate a signed customer. Rejected once an event contract\'s event has started.'},
|
||||
setRoute:{args:[['id','entityId'],['m','routeMode']],watch:['biz.#id'],
|
||||
doc:'How a customer\'s traffic is routed: normal follows metrics, fast takes the lowest latency, scenic the quietest links. Clears a pinned path.'},
|
||||
pathMove:{args:[['id','entityId'],['link','entityId']],watch:['biz.#id'],
|
||||
doc:'Move a fiber customer (alien wave, dark fiber pair, fiber pairs) to another working fiber between the same two cities. Free. Rejected if that fiber has no room for it.'},
|
||||
pathPin:{args:[['id','entityId'],['via','string']],watch:['biz.#id'],
|
||||
doc:'Pin a circuit to a path: via is its city ids in order, comma-separated, from the customer\'s city to its city2, every hop a working link. Free. While a link on it is down the circuit follows routing.'},
|
||||
pathAuto:{args:[['id','entityId']],watch:['biz.#id'],
|
||||
doc:'Unpin a circuit, so routing chooses its path again.'},
|
||||
/* ---------- traffic engineering ---------- */
|
||||
buyTE:{args:[],quote:a=>({setup:TE_COST,monthly:TE_MO,blocked:coreTE()||(S&&S.te)?[]:[tr('core.auto_te_needs_an_rsvp_te_or')]}),
|
||||
doc:'Buy the Auto-TE controller, which spills overflow onto alternate paths. Level 3+, and it needs an RSVP-TE-or-higher backbone.'},
|
||||
teToggle:{args:[],watch:['te'],
|
||||
doc:'Turn Auto-TE on or off.'},
|
||||
teCheck:{args:[['script','string']],open:'teEdit',dom:['teSrc'],reads:'modal',
|
||||
bind:a=>{$('teSrc').value=String(a.script);},
|
||||
doc:'Parse and dry-run a RouteScript without deploying it. The parse errors, or served traffic and transit cost before and after, come back as the report. No state change.'},
|
||||
teDeploy:{args:[['script','string']],open:'teEdit',dom:['teSrc'],watch:['te'],
|
||||
bind:a=>{$('teSrc').value=String(a.script).slice(0,4000);},
|
||||
quote:a=>({setup:0}),
|
||||
doc:'Deploy a RouteScript, up to 4000 characters. Rejected with the parse errors. A deploy that cuts traffic by more than 10% says so in messages.'},
|
||||
teClear:{args:[],watch:['te'],
|
||||
doc:'Delete the script and fall back to plain Auto-TE.'},
|
||||
traceRun:{args:[['from','cityId'],['to','traceTo']],open:'trace',dom:['trFrom','trTo'],reads:'modal',
|
||||
bind:a=>{$('trFrom').value=a.from;$('trTo').value=(NET[a.to]?'net:':'city:')+a.to;},
|
||||
doc:'Run a traceroute to a network or one of your own POPs. The hops come back as report text; they are not stored in the game state.'},
|
||||
/* ---------- money ---------- */
|
||||
takeLoan:{args:[['id','entityId']],
|
||||
doc:'Accept a loan offer. Terms vary wildly by bank; the crypto one pays out 55-135% of face value. Equity banks take a share of the company.'},
|
||||
callBank:{args:[['amount','callAmount']],watch:['loanOffers'],
|
||||
doc:'Call a bank for a loan offer of this size, with a credit rating of AA or better (weird conditions apply). The terms follow from the rating, and the amount must fit the limit of a few months of revenue less current debt. Nothing is borrowed until you take the offer.'},
|
||||
declineLoan:{args:[['id','entityId']],
|
||||
doc:'Throw a loan offer away.'},
|
||||
repayLoan:{args:[['id','entityId']],confirm:'double',
|
||||
quote:a=>{const l=S.loans.find(x=>x.id===a.id);return l?{setup:repayCost(l,BANKS[l.bank])}:{};},
|
||||
doc:'Repay a loan early, or buy an equity investor out.'},
|
||||
/* ---------- address space (IPv4, rule ip4: On-call and BGP at 3 a.m.) ---------- */
|
||||
ip4Buy:{args:[['len','ip4Len']],watch:['ip4'],
|
||||
quote:a=>({setup:ip4Cost(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}),
|
||||
doc:'Buy an IPv4 block of this prefix length (24 = 256 addresses up to 16 = 65,536) on the transfer market at today\'s price. It can be sold again two years after this transfer. A network holds at most 256 blocks, bought, leased in and from the registry together.'},
|
||||
ip4Lease:{args:[['len','ip4Len']],watch:['ip4'],
|
||||
quote:a=>({setup:0,monthly:ip4InMo(Number(a.len)),blocked:[ip4On()?'':tr('ip4.off'),ip4On()&&ip4Full()?tr('ip4.too_many',{n:IP4_BLK}):''].filter(Boolean)}),
|
||||
doc:'Lease an IPv4 block of this prefix length by the month, at today\'s rate (fixed for the lease). Hand it back with ip4Return. Refused at 256 blocks, like ip4Buy.'},
|
||||
ip4Sell:{args:[['id','entityId']],confirm:'double',watch:['ip4'],
|
||||
doc:'Sell an owned block (not leased out) for 92% of the market price. Refused within two years of its last transfer, or when the customers signed would no longer fit with every dual-stack home behind CGNAT and the IPv6-only homes in the NAT64 pool.'},
|
||||
ip4Out:{args:[['id','entityId']],watch:['ip4'],
|
||||
doc:'Lease an owned block out through a broker for a monthly income, while your own customers still fit without it.'},
|
||||
ip4Back:{args:[['id','entityId']],watch:['ip4'],
|
||||
doc:'End the lease of a block you leased out; its addresses are yours to use again.'},
|
||||
ip4Return:{args:[['id','entityId']],watch:['ip4'],
|
||||
doc:'Hand a leased-in block back, ending its monthly fee, when your customers still fit without it.'},
|
||||
ip4Nat:{args:[['v','ip4Ratio']],watch:['ip4'],
|
||||
doc:'Set how many broadband homes share one IPv4 address behind CGNAT (8, 16, 32 or 64). More frees space for business customers but more gamers ask for refunds; fewer is refused when the customers signed would not fit.'},
|
||||
ip4Nat64:{args:[['v','ip4Ratio64']],watch:['ip4'],
|
||||
doc:'Set how many IPv6-only homes share one IPv4 address in the NAT64 pool (64, 128 or 256). Their refunds are well under CGNAT\'s at the same ratio and shrink as the world moves to IPv6; fewer is refused when the customers signed would not fit.'},
|
||||
ip6Go:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>({setup:ip6Cost(a.city),days:ip6Days(a.city),monthly:Math.round(ip6Mo(a.city,ip4Eye())),blocked:[ip6Why(a.city)].filter(Boolean)}),
|
||||
doc:'Take a broadband city IPv6-only (464XLAT): swap its dual-stack home routers for ones with a CLAT over the quoted days, paid day by day as they go in (setup is the whole swap; starting needs only the first day\'s share on hand, and it waits while cash is short). Those homes then need no IPv4 of their own, only a share of the NAT64 pool; new homes there get the new router too, at the swap\'s price a router, paid the day they join (even short of cash: a new home needs it). monthly is what it does to the IPv4 bill (NAT64 gateways and refunds against the CGNAT it saves; negative saves). Frees what the city panel says for new customers.'},
|
||||
ip6Stop:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
doc:'Stop a city\'s swap to IPv6-only. The homes already swapped stay IPv6-only (their routers are paid for, nothing comes back); new homes come dual stack again. ip6Go resumes it for the rest.'},
|
||||
/* ---------- security, China, incidents ---------- */
|
||||
buildScrub:{args:[['city','cityId'],['tier','scrubTier',false]],watch:['scrubs'],
|
||||
quote:a=>{const T=SCRUB_TIERS[a.tier||0];return {setup:T?T.cost:undefined,monthly:T?T.mo:undefined};},
|
||||
doc:'Build a scrubbing centre: 100G, 1T, 10T or 100T. Level-gated per tier; one per city.'},
|
||||
scrubUp:{args:[['city','cityId'],['tier','scrubTier']],watch:['scrubs'],
|
||||
quote:a=>({setup:Math.round(SCRUB_TIERS[a.tier].cost*0.6)}),
|
||||
doc:'Upgrade a scrubbing centre, at 60% of the tier price. Upward only.'},
|
||||
rmScrub:{args:[['city','cityId']],confirm:'double',watch:['scrubs'],
|
||||
doc:'Tear a scrubbing centre down.'},
|
||||
scrubMode:{args:[],watch:['scrubMode'],
|
||||
doc:'Switch scrubbing between always-on and on-demand.'},
|
||||
rtbh:{args:[['id','entityId',false]],watch:['ev'],
|
||||
doc:'Announce a remote-triggered blackhole for the target under attack: it goes dark at your transits, most exchanges and about half your private peers, and everyone else is saved. Withdraw with unrtbh.'},
|
||||
unrtbh:{args:[['id','entityId',false]],watch:['ev'],
|
||||
doc:'Withdraw the blackhole.'},
|
||||
ddosEngage:{args:[['id','entityId',false]],watch:['ev'],
|
||||
doc:'Engage on-demand scrubbing now: start the diversion to the nearest active scrubbing centre instead of waiting for it to engage by itself.'},
|
||||
ddosAuto:{args:[['k','ddosKey']],watch:['ddosAuto'],
|
||||
doc:'Flip a NOC auto-mitigation switch: rtbh blackholes the target of a flood on its own, scrub engages on-demand scrubbing.'},
|
||||
ddosTest:{args:[],watch:['ev'],
|
||||
doc:'Sandbox only: send yourself a test flood, to try the tools on.'},
|
||||
hackback:{args:[['id','entityId',false]],watch:['ev'],quote:a=>({setup:20000}),
|
||||
doc:'Fire the Hackback 3000(tm) at the botnet. 35% it ends the attack; otherwise a fine and a story.'},
|
||||
applyCn:{args:[],watch:['cnLic'],quote:a=>({setup:CN_LIC,days:45}),
|
||||
doc:'File for a mainland China licence through a local partner. Required before a POP in mainland China. 45 days.'},
|
||||
fixInc:{args:[['id','entityId']],watch:['inc'],
|
||||
quote:a=>{const i=S.inc.find(x=>x.id===a.id);return i&&i.cost>0?{setup:i.cost}:{};},
|
||||
doc:'Pay to rush a repair. A slow router reboot is cut to one day; anything else clears immediately.'},
|
||||
/* ---------- conferences ---------- */
|
||||
confGo:{args:[['key','confKey']],watch:['confReg'],
|
||||
quote:a=>{const cf=upcomingConfs(75).find(x=>x.key===a.key);return cf?{setup:confCost(cf)}:{};},
|
||||
doc:'Register for an upcoming conference. Keys come from catalog(\'conferences\'). Peering gets easier in that region for 45 days. Capacity conferences need level 3.'},
|
||||
confSponsor:{args:[['key','confKey']],watch:['confReg'],
|
||||
quote:a=>{const cf=upcomingConfs(75).find(x=>x.key===a.key);return cf&&confSp(cf)?{setup:CONF_SP-(S.confReg&&S.confReg[a.key]?CONF_COST:0)}:{};},
|
||||
doc:'Sponsor it instead: your logo on every lanyard, a bigger effect, a bigger bill. Only where sponsorships are offered; upgrades an existing registration for the difference.'},
|
||||
/* ---------- the NOC intern (standing orders) ---------- */
|
||||
opsHire:{args:[['id','internId']],quote:a=>({setup:INTERN_MO}),watch:['ops'],
|
||||
doc:'Hire the NOC intern. They run your standing orders once a game day and cost a salary a month. Level 2+, and only in a game with a clock.'},
|
||||
opsFire:{args:[],confirm:'double',watch:['ops'],
|
||||
doc:'Let the intern go. The standing orders stop; the rest of the month\'s salary is lost.'},
|
||||
opsToggle:{args:[['k','opsKey']],watch:['ops'],
|
||||
doc:'Pause or resume one standing order. Keys come from catalog(\'OPSK\'); the sheet in the game shows what each one does.'},
|
||||
opsParam:{args:[['k','opsKey'],['p','string'],['v','string',false]],watch:['ops'],
|
||||
// The routers order's model and the optup order's line system were settings once: they are the build standard's now.
|
||||
pass:a=>{const b={routers:{model:'g'},optup:{sys:'sys'}}[a.k],t=b&&b[a.p];
|
||||
if(t)throw new Error(`the ${a.k} order takes its ${t==='g'?'router model':'line system'} from the build standard: set it with bstdSet (k "${t}")`);return a;},
|
||||
doc:'Step one of a standing order\'s settings to its next value (the provider to prefer, the port size to order, the load ceiling…). With v (a position in the list the sheet shows, 0 first) it picks that value instead. The routers order\'s model and the optup order\'s line system are not settings: both orders take them from the build standard (bstdSet k "g" and k "sys"; "keep" leaves them to the next model or line system up, when needed).'},
|
||||
opsCap:{args:[['k','opsKey'],['v','string',false]],watch:['ops'],
|
||||
doc:'Step the monthly budget of an order that has one: 10k, 50k, 250k, 1M, 5M, no limit (for caches, a cap on the rent it adds: 1k, 2.5k, 5k, 10k, 25k, no limit). With v (a position in that list, 0 first) it picks that one.'},
|
||||
opsFloor:{args:[['v','string',false]],watch:['ops'],
|
||||
doc:'Step the floor under your cash that the intern keeps clear when paying for jobs: 0, 50k, 250k, 1M, 5M. With v (a position in that list, 0 first) it picks that one.'},
|
||||
opsPop:{args:[['k','opsPopKind'],['city','cityId']],watch:['ops'],
|
||||
doc:'Add or remove one POP as an exception to an order: the intern never touches the POPs you except.'},
|
||||
opsTpl:{args:[['k','opsTplKey']],watch:['ops'],
|
||||
doc:'Toggle a piece of the one-tap new-POP template: broadband, a transit port, an IX port, the redundancy kit.'},
|
||||
opsNewPop:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
quote:a=>{const q=S&&S.ops?opsTplQuote(a.city):null;return q?{setup:q.cost}:{};},
|
||||
doc:'Open a city from the template in one go: the POP, then broadband, transit, an IX port and the redundancy kit as the template says — all or nothing on the price.'},
|
||||
/* ---------- the bulk PNI order ---------- */
|
||||
pniAll:{args:[['net','pniAllNet'],['tier','pniTier'],['q','shownTotal',false]],
|
||||
quote:a=>{const b=pniBatch(a.net,a.tier);return b?{setup:b.cost,monthly:b.mo,blocked:(b.blocked||[]).map(q=>q.why).filter(Boolean)}:{};},
|
||||
watch:['pni'],
|
||||
doc:'Order PNIs with one network (net) or every network (net:null) at all shared POPs: missing connections are added, smaller ones upgraded, each at its own minimum size. The quote is the batch total, lead times as for one PNI. q (optional): the total you were shown; a different one now is refused and the sheet shown again.'},
|
||||
/* ---------- backbone technology ---------- */
|
||||
coreUp:{args:[],watch:['core'],
|
||||
quote:a=>{const n=S&&S.core?S.core.lv+1:1;return n<=4?{setup:CORE_COST[n],blocked:[(lvl()||1)<CORE_REQ[n]?tr('core.needs_customer_level_n',{n:CORE_REQ[n]}):''].filter(Boolean)}:{};},
|
||||
doc:'Buy the next backbone technology: IGP, LDP/MPLS, RSVP-TE, SR-MPLS, SRv6. One step at a time, level-gated; each step passes transit through a POP cheaper and RSVP-TE or higher unlocks Auto-TE.'},
|
||||
coreLab:{args:[],watch:['core'],quote:a=>({setup:CORE_LAB}),
|
||||
doc:'Build the interop lab in the NOC: it tests your vendors against each other first and cuts interop incidents by 60%.'},
|
||||
coreSet:{args:[['v','integer']],watch:['core'],
|
||||
doc:'Run the backbone at any level already paid for, 0 up to the highest bought.'},
|
||||
/* ---------- the specialist's offers ---------- */
|
||||
demoAsk:{args:[['k','string'],['id','string']],watch:['demo'],
|
||||
doc:'Ask a vendor for a demo unit: a router, line system or optic one level above yours, delivered in about two weeks, at 60% over list until your level catches up. k and id name the thing (as the game\'s buttons pass them).'},
|
||||
seatBuy:{args:[['n','seatPairs']],decides:true,watch:['seatOff','links'],
|
||||
quote:a=>{const o=S&&S.seatOff;if(!o||!SEAT_N.includes(a.n))return {};const miss=[o.a,o.b].filter(c=>!S.pops[c]);
|
||||
return {setup:seatCost(o.km,a.n)+miss.reduce((x,c)=>x+popCost(c),0),days:seatDays(o.km)};},
|
||||
doc:'Take the consortium cable offer: own 1, 2 or 4 fiber pairs on a new subsea cable for your share of the build, and light them with your own optics. POPs open at both landings if you have none.'},
|
||||
seatNo:{args:[],watch:['seatOff'],
|
||||
doc:'Decline the consortium cable offer.'},
|
||||
charter:{args:[['k','charterKey']],watch:['charter'],
|
||||
doc:'Sign the charter a new normal game asks for before anything else (the player sees a popup until it is signed): global backbone (the classic game), low-latency boutique (trading firms pay 40% more, and it has its own win) or broker (dark fiber, line systems, optics and own subsea cables from day one at the usual prices, its own goals and its own win, Glass Baron). One choice per network, normal games only.'},
|
||||
mkBanana:{args:[],watch:['monkey'],
|
||||
quote:a=>({setup:mkBananaCost()}),
|
||||
doc:'Throw the chaos monkey a banana and it leaves early. Only while it is in your network; the price scales with your revenue.'},
|
||||
/* ---------- link tools ---------- */
|
||||
metricMode:{args:[['id','entityId'],['k','metricKind']],watch:['pairMet'],
|
||||
doc:'Set the custom routing metric of a link\'s city pair as a factor (k:"f", the preset way) or an exact cost weight (k:"w"). Starts from the current preset\'s value; edit the number with metricSet.'},
|
||||
metricSet:{args:[['id','entityId'],['v','string']],dom:['metIn'],watch:['pairMet'],
|
||||
bind:a=>{$('metIn').value=String(a.v);},
|
||||
doc:'Write the custom metric\'s number for the link\'s city pair, in the mode metricMode set. Select the link first (view.selLink), so the panel is showing the input.'},
|
||||
seaRush:{args:[['id','entityId'],['all','boolean',false]],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id);if(!l)return {};const k=prepSteps(l),n=a.all?k:Math.min(1,k);return {setup:n*prepCost(l),days:Math.min(n*PREP_STEP,Math.max(0,l.ready-prepFloor(l)))};},
|
||||
doc:'Hurry the survey, permits and factory of your own subsea cable before laying starts: 30 days sooner per step (all: as fast as money goes), never sooner than the factory can make the cable.'},
|
||||
layShip:{args:[['id','entityId']],watch:['links.#id'],
|
||||
quote:a=>{const l=S.links.find(x=>x.id===a.id),q=l&&layQuote(l);return q?{setup:q.cost}:{};},
|
||||
doc:'Book a second lay ship on your own cable before laying starts: it lays from the other end and halves that part of the build.'},
|
||||
/* ---------- the build standard ---------- */
|
||||
popStdSet:{args:[['city','cityId']],watch:['popStd'],
|
||||
doc:'Make a POP\'s build the standard\'s POP part: its router model, router count, second building and generator. New POPs start with them at once; the other targets are kept.'},
|
||||
popStdClear:{args:[],watch:['popStd'],
|
||||
doc:'Clear the whole build standard; new POPs go back to one basic router.'},
|
||||
bstdSet:{args:[['k','bstdKey'],['v','string',false]],watch:['popStd'],
|
||||
doc:'Set one target of the build standard: g router model, rt routers, site2 second building, gen generator, v6 every broadband city IPv6-only (ip6Go, only while IPv4 is scarce: rule ip4), lag LAG members on transit, IX and PNI ports, split LAGs across both buildings, ix an IX port wherever the city has an exchange, pni PNIs per network in at least that many cities, sys line system, opt fastest optics, wv waves at least that size. g and sys are also what the intern\'s routers and optup orders standardize on. Without v it steps to the next value; with v (a position in the list the sheet shows, 0 first, "keep" first) it picks that one.'},
|
||||
bstdApply:{args:[['quote','string',false],['q','shownTotal',false]],watch:['pops','transit','pni','ixp','ixn','ixSite','links','spares'],
|
||||
quote:a=>{const q=bstdQuote(false),nm=w=>w.split('|').map(c=>CITY[c].name).join('–');return {setup:q.cost,monthly:q.mo,key:bstdPlanKey(bstdPlan(false)),
|
||||
blocked:[...q.wait.map(w=>nm(w)+': its line system waits until the fiber is quiet or a parallel link can carry its load for the day it goes dark'),
|
||||
...q.wv.map(w=>nm(w)+': its line system waits: a customer\'s wave rides it and would go dark with it for the day (upSys on the fiber still swaps it)')]};},
|
||||
doc:'Bring everything up to the build standard now, the busiest first, while cash lasts: routers, buildings, generators, IPv6-only swaps (the cities with the most dual-stack homes first; each priced as its whole swap, paid as the routers go in, and started only with that much cash on top of what the swaps under way still owe), LAG members, IX ports, PNIs, line systems, optics and waves. A line-system swap waits unless the fiber is quiet or a parallel link carries its load, and while a customer\'s alien or managed wave rides the fiber (leased pairs and IRUs do not count: they are glass): such a fiber gets the best optics its line system takes, and the quote lists it under blocked. The quote is the whole bill. quote and q (optional): the plan\'s key and the total you were shown; another plan, or a total more than 1% away, is refused and the sheet shown again.'},
|
||||
/* ---------- utilities ---------- */
|
||||
utilityRouteServers:{args:[['city','cityId',false]],watch:['rs'],
|
||||
doc:'Join the route server at every IX you have a port at. One call does what the button does.'},
|
||||
utilityKit:{args:[['city','cityId'],['cost','integer',false]],watch:['pops.#city','caches'],
|
||||
quote:a=>{const q=S?utilityKit(a.city):null;return q?{setup:q.cost,monthly:q.mo}:{};},
|
||||
pass:a=>({city:a.city,cost:a.cost??((utilityKit(a.city)||{}).cost)}),
|
||||
doc:'Install the POP redundancy kit in one go: generator, second building, a second router, and the cache boxes balanced between sites. Pass the quoted setup as cost; the game checks it still matches (within 1%: hardware prices drift by the day). Nothing to do reads as no_effect.'},
|
||||
utilityKitAll:{args:[['cost','integer',false],['city','cityId',false]],watch:['pops','caches'],
|
||||
quote:a=>{const q=S?utilityKitAll():null;return q?{setup:q.cost,monthly:q.mo}:{setup:0};},
|
||||
pass:a=>({city:a.city,cost:a.cost??((utilityKitAll()||{}).cost)}),
|
||||
doc:'Install the redundancy kit at every POP still missing part of it, at one quoted price. From customer level 2. Pass the quoted setup as cost; the game checks it still matches (within 1%).'},
|
||||
utilityKitNew:{args:[['city','cityId',false]],watch:['ops'],
|
||||
doc:'Put the redundancy kit in the intern\'s new-POP template, or take it out (the same switch as in the Ops sheet).'},
|
||||
ptSave:{args:[['city','cityId'],['k','popTier']],watch:['popTiers'],
|
||||
doc:'Save a POP\'s routers (model and count) as one of three POP standards: micro, medium or hub. The POP is marked as that kind. From customer level 2.'},
|
||||
ptApply:{args:[['city','cityId'],['k','popTier'],['cost','integer',false]],watch:['pops.#city','popTiers'],
|
||||
quote:a=>{const q=S?ptPlan(a.city,a.k):null;return q?{setup:q.cost,monthly:q.mo,blocked:q.why?[q.why]:[]}:{setup:0};},
|
||||
pass:a=>({city:a.city,k:a.k,cost:a.cost??((S&&ptPlan(a.city,a.k))||{cost:0}).cost}),
|
||||
doc:'Mark a POP as one kind and bring its routers up to that standard: add routers, swap to the standard\'s model if it is bigger. Never a step down. Pass the quoted setup as cost; the game checks it still matches (within 1%), and 0 only marks a POP that already meets it.'},
|
||||
ptAll:{args:[['k','popTier'],['cost','integer',false],['city','cityId',false]],watch:['pops','popTiers'],
|
||||
quote:a=>{const A=S?ptAll(a.k):null;return A?{setup:A.cost}:{setup:0};},
|
||||
pass:a=>({k:a.k,city:a.city,cost:a.cost??(ptAll(a.k)||{}).cost}),
|
||||
doc:'Bring every POP marked as one kind up to that standard, at one quoted price. Pass the quoted setup as cost; the game checks it still matches (within 1%).'},
|
||||
utilityCaches:{args:[['city','cityId'],['quote','string',false]],watch:['caches'],
|
||||
quote:a=>{const q=S?utilityCaches(a.city):null;return q?{key:q.key}:{};},
|
||||
pass:a=>({city:a.city,quote:a.quote??((utilityCaches(a.city)||{}).key)}),
|
||||
doc:'Request a cache from each eligible provider at each site of the city, as many as demand asks for. Pass the quote\'s key back; the game checks the list has not moved under it.'},
|
||||
utilityPeers:{args:[['city','cityId',false]],watch:['peers'],
|
||||
doc:'Request peering with every eligible peer across every IX you have joined.'},
|
||||
/* ---------- renaming ---------- */
|
||||
renameGo:{args:[['name','string']],open:'rename',dom:['rnIn'],watch:['name'],
|
||||
bind:a=>{$('rnIn').value=String(a.name).slice(0,24);},
|
||||
doc:'Rename your network. act opens the menu\'s rename sheet and types the name in; it is trimmed to 24 characters.'},
|
||||
/* ---------- puzzles and architect runs ---------- */
|
||||
pzLinkTo:{args:[['a','cityId'],['b','cityId']],bindsUI:['pending'],decides:true,watch:['links'],
|
||||
bind:a=>{UI.pending={a:a.a,b:a.b};},
|
||||
doc:'Puzzles only: open the link picker between two cities. Answer the decision with pzLink.'},
|
||||
pzLink:{args:[['tier','pztTier']],watch:['links'],
|
||||
doc:'Puzzles only: light the pending link (from pzLinkTo) at a tier, on the picked route, in the picked trench.'},
|
||||
pzTier:{args:[['id','entityId'],['tier','pztTier']],watch:['links.#id'],
|
||||
doc:'Puzzles only: change a link\'s wave size.'},
|
||||
pzRmLink:{args:[['id','entityId']],watch:['links.#id'],
|
||||
doc:'Puzzles only: tear a link down.'},
|
||||
pzPop:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
doc:'Puzzles only: open a POP in a puzzle city.'},
|
||||
pzRmPop:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
doc:'Puzzles only: close a POP and the links that reach it.'},
|
||||
pzRtAdd:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
doc:'Puzzles only: add a router to a POP, up to RMAX.'},
|
||||
pzRtRm:{args:[['city','cityId']],watch:['pops.#city'],
|
||||
doc:'Puzzles only: remove a router, if the ports still fit.'},
|
||||
pzRtModel:{args:[['city','cityId'],['g','pzRouterModel']],watch:['pops.#city'],
|
||||
doc:'Puzzles only: swap every router in a POP for another model.'},
|
||||
pzRoute:{args:[['i','integer'],['m','pzRouteMode']],watch:['biz'],
|
||||
doc:'Puzzles only: send one flow (index i, as state(\'biz\') lists them) along the metrics or the lowest-latency path.'},
|
||||
pzUndo:{args:[],watch:['pops','links','pairMet'],
|
||||
doc:'Puzzles only: undo the last build step, up to sixty of them.'},
|
||||
pzReset:{args:[],watch:['pops','links','pairMet'],
|
||||
doc:'Puzzles only: clear the whole build and start the puzzle over.'},
|
||||
pzArGo:{args:[],watch:['ar'],
|
||||
doc:'Architect runs only: run the chaos monkey\'s review of this brief, every tube snipped in turn.'},
|
||||
pzArSkip:{args:[],watch:['ar'],
|
||||
doc:'Architect runs only: fast-forward the review to the first cut that hurts.'},
|
||||
pzArNext:{args:[],watch:['ar'],
|
||||
doc:'Architect runs only: pass the review and sign the next brief. Rejected while the current one does not pass.'},
|
||||
|
||||
/* ---------- answering decisions ---------- */
|
||||
dkAccept:{args:[],watch:['dk'],
|
||||
doc:'Take the De-Kicks quote as offered and order the port.'},
|
||||
dkHaggle:{args:[],watch:['dk'],
|
||||
doc:'Haggle. 45% a better price, 30% a worse one, 25% sales stops returning your calls for a few days. Three attempts.'},
|
||||
dkWalk:{args:[],watch:['dk'],
|
||||
doc:'Walk away; the quote is remembered for 90 days.'},
|
||||
dkStay:{args:[['city','ixId']],watch:['dk'],
|
||||
doc:'Take the retention discount instead of leaving: 40% off for six months.'},
|
||||
dkOptOut:{args:[['city','ixId'],['n','string']],confirm:'double',watch:['dk'],
|
||||
doc:'Opt out of an add-on De-Kicks slipped onto the bill.'},
|
||||
closeModal:{args:[],
|
||||
doc:'Close the open window, answering nothing. Always available, so you are never stuck in front of one.'},
|
||||
};
|
||||
|
||||
const API_VIEW={
|
||||
pieOpen:{args:[],doc:'Open Pie Control, the rocket company\'s panel.'},
|
||||
ip4Open:{args:[],doc:'Open the bank at its Address space section: your IPv4 blocks, who uses them, CGNAT, the NAT64 pool and the transfer market.'},
|
||||
ip4Pick:{args:[['v','ip4Len']],doc:'Pick the block size the Address space market quotes (a prefix length, 24 to 16).'},
|
||||
pieGovOpen:{args:[],doc:'Open the bank at its Government money section: the rocket company\'s fund auctions, the Pitcairn grant and the Ex-Im Pie Bank (it used to be Pie Control\'s Gov tab).'},
|
||||
pieTab:{args:[['t','pieTab']],doc:'Switch the Pie Control tab: traffic, co (the company, its books and the Founder\'s posts), fly (launches) or dish.'},
|
||||
pieCity:{args:[['v','cityId']],doc:'Pick the POP the Dishes tab works on.'},
|
||||
pieHi:{args:[['id','string']],doc:'Highlight one orbit flow on the Pie Control globe.'},
|
||||
pieIns:{args:[],doc:'Toggle launch insurance for the next launches.'},
|
||||
pieLas:{args:[],doc:'Toggle lasers (inter-satellite links) for the next launches.'},
|
||||
pieGlobeNight:{args:[],doc:'Flip the Pie Control globe between day and night.'},
|
||||
pieSpatOpen:{args:[['id','pieSpatId']],doc:'Open the sheet of a geopolitical spat over orbit.'},
|
||||
traceMode:{args:[['m','string']],doc:'Redo the open traceroute in a routing mode: normal, fast or scenic.'},
|
||||
chartToggle:{args:[['c','string'],['k','string']],doc:'Hide or show one series of a dashboard chart (a legend click); hiding every series shows them all again.'},
|
||||
help:{args:[],doc:'Open the how-to-play modal.'},
|
||||
dash:{args:[],doc:'Open the NOC dashboard.'},
|
||||
dashClose:{args:[],doc:'Close the NOC dashboard.'},
|
||||
nocWindow:{args:[],doc:'Open the NOC dashboard in a window of its own, for a second display.'},
|
||||
dashTab:{args:[['k','dashTab']],doc:'Switch the NOC dashboard tab.'},
|
||||
marketOpen:{args:[],doc:'Open the NOC dashboard at the capacity market (Lambda Bazaar).'},
|
||||
dashSort:{args:[['k','dashSortKey']],doc:'Flip a dashboard column\'s sort.'},
|
||||
dashLink:{args:[['id','entityId']],doc:'Jump from the dashboard to a link\'s panel.'},
|
||||
bank:{args:[],doc:'Open the bank.'},
|
||||
bankClose:{args:[],doc:'Close the bank.'},
|
||||
closePanel:{args:[],doc:'Close the selection panel.'},
|
||||
tab:{args:[['t','string']],doc:'Switch the city panel\'s tab.'},
|
||||
pzCity:{args:[['c','cityId']],doc:'Puzzles on a phone: open a city\'s card from its flow chip.'},
|
||||
pzTab:{args:[['k','string'],['t','string']],doc:'Puzzles on a phone: switch the city (k:"city") or link (k:"link") card\'s tab.'},
|
||||
leftTab:{args:[['t','leftTab']],doc:'Switch the left drawer and open it.'},
|
||||
toggleLeft:{args:[],doc:'Open or close the left drawer.'},
|
||||
netFocus:{args:[['id','netId']],doc:'Focus one network in the left drawer.'},
|
||||
netFilter:{args:[['f','netFilter']],doc:'All networks, or only the out-of-reach ones.'},
|
||||
meetGo:{args:[['city','cityId']],doc:'Go to a city and open where to meet networks there.'},
|
||||
phoneTab:{args:[['t','leftTab']],doc:'Phone tab bar: switch bottom-sheet tab.'},
|
||||
logOpen:{args:[['id','entityId']],doc:'Open the thing a notification refers to.'},
|
||||
logAll:{args:[],doc:'Show every notification in the drawer.'},
|
||||
focusCity:{args:[['city','cityId']],doc:'Select and centre a city.'},
|
||||
selLink:{args:[['id','entityId']],doc:'Select a link.'},
|
||||
custGo:{args:[['id','entityId']],doc:'Jump from the dashboard to a customer.'},
|
||||
pathOpen:{args:[['id','entityId']],doc:'Open the window listing the other paths a customer can move to: fibers for a fiber customer, routes for a circuit. pathMove and pathPin make the move.'},
|
||||
listMore:{args:[['k','listPage']],doc:'Show another page of the dashboard list.'},
|
||||
custF:{args:[['v','string']],doc:'Filter the customers list.'},
|
||||
custCity:{args:[['v','string']],doc:'Filter the customers list by city.'},
|
||||
custSort:{args:[['k','custSortKey']],doc:'Flip the customers list sort.'},
|
||||
custOpen:{args:[['sad','boolean',false]],doc:'Open the customers dashboard tab.'},
|
||||
popGo:{args:[['city','cityId']],doc:'Jump from the dashboard to a city with no POP yet.'},
|
||||
popsReg:{args:[['v','string']],doc:'Filter the list of cities with no POP by region.'},
|
||||
popsSort:{args:[['k','popsSortKey']],doc:'Flip the sort of the list of cities with no POP.'},
|
||||
goConn:{args:[['city','cityId'],['k','connKind']],doc:'Open a city\'s connections tab.'},
|
||||
goEgress:{args:[['city','cityId'],['k','egressKind']],doc:'Open a city\'s connections tab (l2 for the customer list).'},
|
||||
connOpen:{args:[],doc:'Open the connections tab of the NOC dashboard (also the Peering tab\'s "All connections" button).'},
|
||||
connF:{args:[['f','connFilter'],['v','string',false]],doc:'Filter the connections list.'},
|
||||
connCity:{args:[['v','string']],doc:'Filter the connections list by city.'},
|
||||
connNet:{args:[['v','string']],doc:'Filter the connections list by network.'},
|
||||
connSort:{args:[['k','connSortKey']],doc:'Flip the connections list sort.'},
|
||||
connFor:{args:[['net','netId']],doc:'Open the connections of one network.'},
|
||||
linkCheck:{args:[['id','entityId']],doc:'Open the redundancy check for a link: what a single cut would drop, without changing anything.'},
|
||||
findOpen:{args:[],doc:'Open the city finder (the 🔍 in the top bar).'},
|
||||
findGo:{args:[['city','cityId']],doc:'Close the finder and jump to a city.'},
|
||||
findLink:{args:[['city','cityId']],doc:'Open the city finder to pick where a new link from this POP goes (the "Link to a city" button in its panel).'},
|
||||
linkTo:{args:[['a','cityId'],['b','cityId']],doc:'From the link finder: open the new-link window from POP a to city b, as dragging between them would.'},
|
||||
popStep:{args:[['d','integer']],doc:'Select and centre the previous (d<0) or next (d>0) of your POPs, by name: the [ and ] keys.'},
|
||||
offerStep:{args:[],doc:'Select the next open offer (soonest to expire first), centre its city and mark it under Offers here: the $ key.'},
|
||||
zoomStep:{args:[['d','integer']],doc:'Zoom the map out (d<0) or in (d>0) around its middle: the - and = keys.'},
|
||||
keys:{args:[],doc:'Open the list of keyboard shortcuts (the ? key).'},
|
||||
routingOpen:{args:[],doc:'Open the Routing & DDoS window: the traceroute, backbone, Auto-TE and DDoS settings (the button at the top of the NOC tab).'},
|
||||
opsOpen:{args:[],doc:'Open the Ops sheet: the NOC intern\'s mood, weekly shift report and standing orders.'},
|
||||
bstdOpen:{args:[],doc:'Open the build standard sheet: every target, how many POPs, ports and links are below it, what bringing them up costs, and the intern\'s order that keeps them there.'},
|
||||
salesOpen:{args:[],doc:'Open the sales desk sheet: the three kinds of salesperson, who is at the desk and what they cost.'},
|
||||
opsCity:{args:[['v','cityId',false]],doc:'Show one POP\'s standing-order exceptions in the Ops sheet.'},
|
||||
utilities:{args:[['city','cityId',false]],doc:'Open the utilities sheet: route servers, the redundancy kit, caches and bulk peering, for one city or the whole network.'},
|
||||
pniAllOpen:{args:[['net','pniAllNet']],doc:'Open the bulk PNI order sheet for one network (or every network with null).'},
|
||||
pniFilter:{args:[['f','pniFilter']],doc:'Filter the PNI list: all, via transit, worth it, already PNI.'},
|
||||
pniGrp:{args:[['g','string'],['o','boolean',false]],doc:'Fold or unfold one group of the PNI list.'},
|
||||
pniSort:{args:[],doc:'Flip the PNI list sort between A-Z and worth-it-first.'},
|
||||
netFind:{args:[['q','string']],doc:'Filter a POP\'s transit, exchange, PNI and cache lists by network name or AS number.'},
|
||||
netOnly:{args:[],doc:'Show only the networks you are connected to in a POP\'s lists, or all of them again.'},
|
||||
netClear:{args:[],doc:'Clear the network search and the connected-only switch.'},
|
||||
puzzleMenu:{args:[],doc:'Open the puzzle list.'},
|
||||
puzzleDoor:{args:[],doc:'From the title screen: open the puzzle list (keeps the typed name).'},
|
||||
pzFinish:{args:[],doc:'Puzzles only: run the star count and show the results sheet.'},
|
||||
pzMonkey:{args:[],doc:'Puzzles only: send the chaos monkey round the build to prove the N-1 star.'},
|
||||
pzMkSkip:{args:[],doc:'Puzzles only: skip the monkey\'s tour to the verdict.'},
|
||||
pzLook:{args:[['c','cityId',false],['u','string',false]],doc:'Puzzles only: move the map to the city (c) or the cut (u, a link unit) that the sheet\'s next line names.'},
|
||||
pzArAll:{args:[],doc:'Architect runs only: show every city on the map, not just the run\'s own.'},
|
||||
tailTog:{args:[],doc:'Show or hide the long tail of small networks.'},
|
||||
teEdit:{args:[],doc:'Open the RouteScript editor.'},
|
||||
teClose:{args:[],doc:'Close the RouteScript editor.'},
|
||||
teHelp:{args:[],doc:'Open the RouteScript reference.'},
|
||||
teBack:{args:[],doc:'Back to the RouteScript editor.'},
|
||||
models:{args:[],doc:'Open the router catalogue.'},
|
||||
decomOpen:{args:[['city','cityId',false]],doc:'Open the decommissioning sheet.'},
|
||||
scenarios:{args:[],doc:'Open the scenario picker. Start one with startScn.'},
|
||||
helpClose:{args:[],doc:'Close the help modal.'},
|
||||
whatsNewShow:{args:[],doc:'Open the release notes.'},
|
||||
};
|
||||
|
||||
const API_BOUND={
|
||||
pieRename:{command:'pieName',note:'the typed company name'},
|
||||
leaseSwap:{command:'orderDf',note:'presets the dark-fiber modal on a leased pair'},
|
||||
teOpt:{command:'teDeploy',arg:'script',note:'the optimiser drafts a script'},
|
||||
teSlop:{command:'teDeploy',arg:'script',note:'the AI drafts a script'},
|
||||
teExample:{command:'teDeploy',arg:'script',note:'the worked example'},
|
||||
teRecipe:{command:'teDeploy',arg:'script',note:'a recipe from catalog(\'TE_RECIPES\')'},
|
||||
trace:{command:'traceRun',arg:'from'},
|
||||
decomToggle:{command:'decomGo',arg:'cities'},
|
||||
satOpen:{command:'buySat',note:'opens the satellite order sheet from a teleport (a) or for a city (b); buySat takes a, b, bird and g itself'},
|
||||
wispOpen:{command:'wispSat',note:'opens an island Wi-Fi zone in its city\'s Customers tab; wispSat, wispSpur and the rest take z themselves'},
|
||||
openVxc:{command:'buyVxc',note:'opens the circuit picker from a fabric port ({from, prov}); buyVxc takes a, b, prov and t itself'},
|
||||
connCancel:{command:'cancelTransit',note:'the connections list\'s cancel button: it arms, then dispatches cancelTransit, cancelPni, cancelIx, rmCache or rmNni'},
|
||||
cnPrem:{command:'buildLink',arg:'premiumCrossing'},
|
||||
addParallel:{command:'buildLink',note:'opens the link modal on the same pair',arg:'a/b'},
|
||||
via:{command:'buildLink',arg:'cable'},
|
||||
route:{command:'buildLink',arg:'route'},
|
||||
dfMode:{command:'orderDf',note:'opens the dark-fiber modal',arg:'a/b'},
|
||||
xpOpen:{command:'xpBuild',note:'opens the link window on its Express tab: the ways your ROADM fibers chain from a to b (via, fiber ids comma-separated, puts that path first)',arg:'a/b/via'},
|
||||
dfSrc:{command:'orderDf',arg:'source'},
|
||||
dfSys:{command:'orderDf',arg:'system'},
|
||||
seaDesign:{command:'orderCable',arg:'design'},
|
||||
seaPackage:{command:'orderCable',arg:'terminal/engineering'},
|
||||
ownCab:{command:'orderCable',note:'presets the own-cable flow'},
|
||||
randomName:{command:'start',note:'drafts the title-screen name; new_game starts games'},
|
||||
pickStart:{command:'start',note:'drafts the home city; new_game starts games'},
|
||||
pickHome:{command:'start',note:'drafts the home city; new_game starts games'},
|
||||
modeSet:{command:'start',note:'drafts the game mode; new_game starts games'},
|
||||
presetSet:{command:'start',note:'drafts the difficulty preset; new_game starts games'},
|
||||
chaosSet:{command:'start',note:'drafts the sandbox chaos dial; new_game starts games'},
|
||||
rename:{command:'renameGo',note:'opens the rename sheet; renameGo opens it itself'},
|
||||
pniAllSize:{command:'pniAll',arg:'tier',note:'steps the port size in the bulk sheet'},
|
||||
utilityPick:{command:'utilities',note:'the sheet\'s city picker; pass city to utilities itself'},
|
||||
pzAddPar:{command:'pzLink',note:'opens the puzzle picker on the same pair',arg:'tier'},
|
||||
pzVia:{command:'pzLink',note:'picks the route (cable or land) for the pending link'},
|
||||
pzDiv:{command:'pzLink',note:'same trench or a diverse one for the pending link'},
|
||||
};
|
||||
|
||||
/* Starting, retrying and leaving scenarios, puzzles and architect runs, and the screens a player dismisses. They run
|
||||
as their buttons run them; new_game, load_save and export_save are the other half of the session, and exist only in
|
||||
the MCP server's own page (scripts/lib/mcp-headless.js). In the player's tab the player owns the game, so the ones
|
||||
that replace or leave it are refused there (API_PLAYER_OWNS). */
|
||||
const API_SESSION={
|
||||
startScn:{args:[['id','scnId']],doc:'Start a scenario (ids from catalog SCN), replacing the current game.'},
|
||||
startWeekly:{args:[],doc:'Start this week\'s weekly scenario, replacing the current game. The week follows the real date.'},
|
||||
pzStart:{args:[['id','string']],doc:'Start a puzzle by id (the puzzle list, view.puzzleMenu, shows them), replacing the current game.'},
|
||||
pzWeekly:{args:[],doc:'Start this week\'s weekly puzzle, replacing the current game.'},
|
||||
pzArStart:{args:[['id','string']],doc:'Start an architect run by id (view.puzzleMenu lists them), replacing the current game.'},
|
||||
pzRetry:{args:[],doc:'Puzzles and architect runs: start the same one over from scratch.'},
|
||||
pzLeave:{args:[],doc:'Leave the running puzzle or architect run.'},
|
||||
keepPlaying:{args:[],doc:'Dismiss the win screen and keep playing.'},
|
||||
pitchSkip:{args:[],doc:'Skip the opening pitch; a game waiting behind it starts.'},
|
||||
tutSkip:{args:[],doc:'Skip the tutorial coaching.'},
|
||||
};
|
||||
// Session actions that would replace or leave the game in the player's tab: refused over the relay.
|
||||
const API_OWN_WHY='the game in this tab is the player\'s: only the player starts, loads or leaves one';
|
||||
const API_PLAYER_OWNS={startScn:1,startWeekly:1,pzStart:1,pzWeekly:1,pzArStart:1,pzRetry:1,pzLeave:1};
|
||||
|
||||
/* Actions no tool runs, by reason: files, storage slots, settings and the title screen are not the game's, and time
|
||||
moves only through advance (or the page's own clock). */
|
||||
const API_WHY={
|
||||
time:'use advance to move time, or wait when the clock runs on its own',start:'use new_game',files:'use load_save or export_save',
|
||||
slots:'saved networks in browser storage are not part of this game',prefs:'device and player settings are not part of the game',
|
||||
browser:'it needs the browser itself (a share sheet, the clipboard, an install prompt or a reload)',
|
||||
mp:'multiplayer talks to a session server for the player: only the player starts, joins, chats in or leaves a session',
|
||||
};
|
||||
const API_DENY={
|
||||
speed:'time',phonePlay:'time',phoneSpeed:'time',
|
||||
start:'start',newgame:'start',cont:'start',toTitle:'start',resetAsk:'start',
|
||||
exportSave:'files',importGo:'files',importPick:'files',slotExport:'files',xfer:'files',xferFile:'files',xferPaste:'files',xferRecv:'files',
|
||||
slotBack:'slots',slotDel:'slots',slotDelGo:'slots',slotMenu:'slots',slotRetry:'slots',slotSpace:'slots',slotSwitch:'slots',slotTake:'slots',
|
||||
animSet:'prefs',langSet:'prefs',mapSet:'prefs',menu:'prefs',mute:'prefs',prefSet:'prefs',settings:'prefs',settingsClose:'prefs',soundSet:'prefs',themeSet:'prefs',vpSet:'prefs',
|
||||
mpDoor:'mp',mpBack:'mp',mpStart:'mp',mpJoin:'mp',mpOpen:'mp',mpShare:'mp',mpCopyLink:'mp',mpChat:'mp',mpLeaveAsk:'mp',mpLeave:'mp',mpNewer:'mp',mpKeep:'mp',
|
||||
install:'browser',share:'browser',shareDl:'browser',shareGo:'browser',traceCopy:'browser',updateLater:'browser',updateNow:'browser',wsShare:'browser',pzShare:'browser',xferLink:'browser',xferShare:'browser',
|
||||
};
|
||||
171
src/agent/30-docs.js
Normal file
171
src/agent/30-docs.js
Normal file
|
|
@ -0,0 +1,171 @@
|
|||
/* ================= AGENT API: what the state and the results hold =================
|
||||
One line per field of S and of R (tests/mcp-commands.test.js fails on a field without one). */
|
||||
const API_STATE_DOC={
|
||||
v:{type:'integer',doc:'Save format version.'},
|
||||
name:{type:'string',doc:'Your network\'s name.'},
|
||||
asn:{type:'integer',doc:'Your AS number.'},
|
||||
home:{type:'string',doc:'The city you started in.'},
|
||||
day:{type:'integer',doc:'The calendar day (shared by every network of a server session); day − day0 is the network\'s age.'},
|
||||
day0:{type:'integer',doc:'The calendar day this network began: 0, or the session\'s date for a network that joined a server session late.'},
|
||||
cash:{type:'number',doc:'Cash on hand. Goes negative into the red; -100k is bankruptcy.'},
|
||||
priceMul:{type:'number',doc:'Multiplier on transit prices (weekly modifier).'},
|
||||
mode:{type:'string',doc:'normal | sandbox | scenario | puzzle.'},
|
||||
rules:{type:'map',doc:'The rules this network locked in at its door: preset (soft, freeze, oncall, bgp, sandbox or puzzle), the chaos dial, lead times, the market, and the later rules (sea, confs, broke, moods, pnis, and ip4 for scarce IPv4, off outside On-call and BGP at 3 a.m.), which are only written where they differ from the classic game. They stay for the network\'s whole life.'},
|
||||
charter:{type:'string',doc:'The charter a normal game signed when it started: global | boutique | broker. chartSet is false until one is signed.'},
|
||||
baronWon:{type:'number',doc:'The day a broker won Glass Baron, or 0.'},
|
||||
chartSet:{type:'boolean',doc:'The charter has been picked; false while the choice is still open.'},
|
||||
solWon:{type:'integer',doc:'The day the Speed of Light win landed (boutique charter), or 0.'},
|
||||
lvl:{type:'integer',doc:'Customer level (unlocks customer types).'},
|
||||
ltv:{type:'integer',doc:'Level at which Tier 1 vendors were visible (title-screen pick).'},
|
||||
t1v:{type:'integer',doc:'Level at which Tier 1 transit was offered.'},
|
||||
auV:{type:'integer',doc:'Australia content level gate.'},
|
||||
seen:{type:'array',doc:'Network ids the deals panel has already shown. Vestigial: written by newGame, read nowhere.'},
|
||||
pops:{type:'map',doc:'Your POPs by city id: day opened, broadband (bb: d, its demand in Gbps; v6, the share of its homes that are IPv6-only behind NAT64, absent for dual stack; v6e, the day a swap to IPv6-only finishes, while it runs), ad boost, downtime, routers, generator, second site, teleport (tele: 1 GEO dishes, 2 with MEO tracking antennas), a Starblink LEO gateway on it (leo: 1), island Wi-Fi zones (wisp: by zone id, {day, d: the homes\' Gbps signed up, sat: the circuit {bird, g, mo, day, ready}, nxt: a move to another bird being commissioned, sp: the spur cable {day, ready}}).'},
|
||||
links:{type:'array',doc:'Your links: waves, dark fiber (df), own cables, fabric circuits (vxc), express lightpaths (xp: via lists the dark fibers it rides from a, ch its optics) and rented satellite circuits (sat: bird, g Gbps, km of radio path, ready day), each with an entity id.'},
|
||||
transit:{type:'array',doc:'Transit ports: city, net, tier, LAG members, port history for 95th-percentile billing.'},
|
||||
ixp:{type:'map',doc:'IX ports by exchange city; tier per port (may exceed 1 with LAG members in ixn).'},
|
||||
rs:{type:'map',doc:'Route-server sessions by exchange city.'},
|
||||
ixn:{type:'map',doc:'LAG members on IX ports by exchange city.'},
|
||||
ixSite:{type:'map',doc:'Which building each IX port sits in (a, b or ab).'},
|
||||
ixPref:{type:'map',doc:'Egress preference per IX port.'},
|
||||
myIx:{type:'map',doc:'Exchanges you founded: name, members, join schedule, fabric step.'},
|
||||
peers:{type:'map',doc:'Peering sessions, keyed "net@ix".'},
|
||||
pairMet:{type:'map',doc:'Routing metric per city pair (prefer/avoid/backup/normal), keyed by pair.'},
|
||||
pni:{type:'array',doc:'Private interconnects: city, net, tier, ready day, augments (up), LAG, sacrificial flag.'},
|
||||
caches:{type:'array',doc:'CDN cache boxes: city, net, building.'},
|
||||
nni:{type:'array',doc:'Fabric ports: city, provider, tier.'},
|
||||
biz:{type:'array',doc:'Signed customers: type, cities, bandwidth, rate, mood, contract dates (te: the day the term ends, mk: the bandwidth market it was priced in, hag: an open renewal haggle {rate, until}).'},
|
||||
offers:{type:'array',doc:'Pending customer offers, each expiring on a day (mk: the bandwidth market they were priced in; refN: the customer who referred them).'},
|
||||
sales:{type:'map',doc:'The sales desk: p (eng, shark, ceo or null), hired (day), vp (the day a VP of Sales takes over from the CEO), golf and say (the CEO\'s next golf deal and opinion). Offers and customers carry by: who brought or signed them, orbit ones too (the shark\'s may carry the skyfull promise).'},
|
||||
slAuto:{type:'map',doc:'Deals the sales desk signs for you (only while someone runs sales): on (sign offers that fit), min (decline offers paying less a month; 0 never), ren (answer renewal haggles), wk (this week: w, p who was at the desk, n signed, rev their monthly revenue, x declined, y declined but signed anyway by the CEO) and rep (last week, the same).'},
|
||||
cl:{type:'map',doc:'Customer lifecycle (#178): odd (the day of the last unusual departure) and mo, one entry a month of customers won, renewed, grown, haggling and lost by reason.'},
|
||||
done:{type:'map',doc:'Goals landed, by goal id → day.'},
|
||||
ach:{type:'map',doc:'Badges earned this game, by badge id → day.'},
|
||||
inc:{type:'array',doc:'Open incidents: type, what they hit, until when, optional rush-repair price.'},
|
||||
ddosStarts:{type:'array',doc:'The days the attacks of the last week started; at most 14 a week.'},
|
||||
ev:{type:'map',doc:'Live world events: the running DDoS, route leaks, fabric failures, price shocks, a solar storm (sky: the day LEO circuits leave safe mode).'},
|
||||
stats:{type:'map',doc:'Counters: incidents survived, loans taken, sharks, conferences attended, peak traffic…'},
|
||||
log:{type:'array',doc:'The NOC notification feed, newest first, capped at 60; identical notices within a minute fold with a count.'},
|
||||
nextFail:{type:'integer',doc:'The day the next failure fires.'},
|
||||
nextEvent:{type:'integer',doc:'The day the next world event fires.'},
|
||||
rng:{type:'integer',doc:'The scenario seed; it predicts every future random draw.'},
|
||||
usedNames:{type:'array',doc:'Customer names already handed out.'},
|
||||
spares:{type:'map',doc:'Spare optics on the shelf, by optic id.'},
|
||||
scrubs:{type:'array',doc:'Scrubbing centres: city and tier.'},
|
||||
scrubMode:{type:'string',doc:'always | ondemand.'},
|
||||
cnLic:{type:'map',doc:'Mainland China licence: none | pending (with ready day) | ok.'},
|
||||
pieV:{type:'number',doc:'Pie in the Sky version stamp: 1 in games started since it shipped (only those unlock it, on a Tier 1 win).'},
|
||||
pie:{type:'map',doc:'The rocket company (Pie in the Sky), or null: company, factory, stock, pads, crusts (cohorts of pies by launch day), dishes, landing rights (lic), launch queue (q), R&D, spats, the founder (posts, promises made and broken with their due days, and his antics: jit, the market jitters 0..1 that fade over 30 days and lower orbit offer odds and happiness; next, the day of the next antic; kid, 1 + the index of PIE_KIDS once he has named his son; bill, the day orbit billing comes back (no orbit income until then); nerv, hype, leak: days a posting spree, Mars hype and a leaked launch date (dearer launch insurance) last until; mars, the due day of the Mars promise, whose slip loses a few orbit customers; all only with chaos on), books, and government money (gov: auctions, awards, Ex-Im).'},
|
||||
ppol:{type:'string',doc:'Your published peering policy: open | selective | closed.'},
|
||||
pdesk:{type:'map',doc:'This week\'s peering desk summary: sessions accepted and declined at which exchanges.'},
|
||||
pdeskRep:{type:'map',doc:'Last week\'s peering desk summary, as the NOC log reported it.'},
|
||||
ops:{type:'map',doc:'The NOC intern: who is hired, each standing order\'s on/off switch and settings (network work only: deals belong to the sales desk, slAuto), the monthly budget and what it spent, per-POP exceptions, the new-POP template and the weekly log.'},
|
||||
core:{type:'map',doc:'Your backbone technology: lv bought, the level it runs at, the interop lab.'},
|
||||
ddosAuto:{type:'map',doc:'The NOC\'s auto-mitigation switches: rtbh and scrub.'},
|
||||
ip4:{type:'map',doc:'IPv4 address space (rule ip4): b, the blocks, at most 256 (len: prefix length 16-24, k: rir from the registry, buy bought, in leased in; d: the day it last moved, out: leased out, mo: the monthly fee or income), nat: homes per address behind CGNAT, n64: IPv6-only homes per address in the NAT64 pool, w: which warnings were shown. What customers use is derived from their kind and size.'},
|
||||
popStd:{type:'map',doc:'The build standard, or null for none. g router model (an RG index), rt routers, then only the targets that are set: site2, gen, v6 (true; v6: every broadband city goes IPv6-only, only while rule ip4 is on), lag (2 or 4 members), split, ix (true), pni (2 or 3 cities per network), sys (roadm, cl), opt (fast), wv (an LT index). New POPs get g, rt, site2 and gen at once; the std standing order and bstdApply bring the rest up (v6 with ip6Go, city by city). g and sys are also the model the routers order and the line system the optup order standardize on.'},
|
||||
popTiers:{type:'map',doc:'POP standards by kind: def.micro|medium|hub is {g: router model, rt: routers} or null; at maps a POP city to its kind.'},
|
||||
mp:{type:'map',doc:'Multiplayer, only in a self-hosted copy with a session server: the session code, your player id, the AS number and seed the session gave you, its rules preset, your colour, its title and the last save number the server holds; null in every other game.'},
|
||||
demo:{type:'map',doc:'Vendor demo units on order, by "kind:id" → ready day.'},
|
||||
seatOff:{type:'map',doc:'The pending consortium-cable seat offer: landings, km, name, expiry day.'},
|
||||
monkey:{type:'map',doc:'The chaos monkey: next visit day, whether it is in your network now, days left, whether anyone noticed.'},
|
||||
fleet:{type:'map',doc:'Cable-ship voyages by ship id: the cut it sails to, when it arrives, splices and comes home.'},
|
||||
achP:{type:'map',doc:'Which rule set each badge was earned under (oncall, freeze, bgp), by badge id.'},
|
||||
calV:{type:'integer',doc:'Calendar save-format marker: 1 once the real calendar (28-31-day months) applies.'},
|
||||
pz:{type:'map',doc:'The running puzzle: its id, cities, flows to deliver, budget and stars.'},
|
||||
ar:{type:'map',doc:'The running architect run: its HQ, brief index, gold sites, spend and the build it started from.'},
|
||||
loans:{type:'array',doc:'Active loans: bank, balance, APR, term, share (equity banks).'},
|
||||
loanOffers:{type:'array',doc:'Pending loan offers.'},
|
||||
loanStrikes:{type:'integer',doc:'How many loan offers you have let lapse.'},
|
||||
confReg:{type:'map',doc:'Conferences registered for, by key; "sp" when sponsoring.'},
|
||||
hw:{type:'map',doc:'Hardware market: price shocks and any price lock.'},
|
||||
capDeal:{type:'map',doc:'The pending capacity deal from a capacity conference.'},
|
||||
cm:{type:'map',doc:'The capacity market (Lambda Bazaar): hold (% of every fiber never sold, kept for your own traffic), p (per product spec/w100/w400/w800/w1600/iru: on, min demand, floor % of list), off (routes the broker leaves alone, by "a|b"), sh (market shocks: why, from, until, m multiplier, on a route k, a city c or every subsea route), news (the latest market news), seen (incident ids already turned into news).'},
|
||||
cam:{type:'map',doc:'Map camera position. View state that save() happens to store inside S.'},
|
||||
uiSpeed:{type:'number',doc:'The speed you left the game at. View state that save() stores inside S.'},
|
||||
won:{type:'boolean',doc:'You reached Tier 1.'},
|
||||
t1Now:{type:'boolean',doc:'Tier 1 right now, as of the last day; falling out of it is announced.'},
|
||||
lost:{type:'boolean',doc:'The bank repossessed the routers.'},
|
||||
neg:{type:'integer',doc:'Days in the red in a row.'},
|
||||
hist:{type:'array',doc:'Daily history for the graphs: demand, served, exit split, revenue, cost, cash.'},
|
||||
vol:{type:'number',doc:'Traffic carried in this game, in petabytes (each day adds a day of what was served); badges at 1 PB, 100 PB, 1 EB and 1 ZB.'},
|
||||
scn:{type:'map',doc:'The running scenario: id, rules, day limit, done/failed, and the day of the next scripted attack (nextDdos).'},
|
||||
dk:{type:'map',doc:'De-Kicks state: per-exchange multipliers, add-ons, retention, the live quote (q) and the remembered one (lastQ).'},
|
||||
grace:{type:'map',doc:'Courtesy transit after a merger wave, until a day.'},
|
||||
merged:{type:'map',doc:'Networks merged into others this game.'},
|
||||
tut:{type:'map',doc:'Tutorial progress.'},
|
||||
conf:{type:'map',doc:'The conference glow: region and until when; sp when you sponsored.'},
|
||||
phpDone:{type:'boolean',doc:'One-shot flag.'},
|
||||
krExit:{type:'map',doc:'Korea exit state.'},
|
||||
auNews:{type:'boolean',doc:'One-shot flag: the Australia news toast.'},
|
||||
richTold:{type:'boolean',doc:'One-shot flag: the cash milestone toast.'},
|
||||
};
|
||||
|
||||
const API_RESULTS_DOC={
|
||||
pie:{type:'map',doc:'Orbit this compute (only with a rocket company): revenue (rev; 0 while the founder has orbit billing down, with billOff what it would have been; including patchy: {mo, cr} from patchy-sky customers who pay from 10% coverage, before a crust carries anything, and fade out between 40% and 60%), service per orbit customer, landing dishes, flows through the sky, backhaul for cut-off POPs (bh), crust and dish load, government money (gov).'},
|
||||
nt:{type:'map',doc:'Traffic per network through transit, by net id.'},
|
||||
tNet:{type:'map',doc:'Traffic per network you hand to each upstream, by "net@upstream".'},
|
||||
reachNT:{type:'number',doc:'Networks reachable without transit.'},
|
||||
teBlack:{type:'number',doc:'Traffic blackholed by RouteScript rules.'},
|
||||
teMoved:{type:'number',doc:'Traffic Auto-TE spilled onto alternate paths.'},
|
||||
egT:{type:'map',doc:'Egress split by exit kind (c/p/ix/t/l2) in Gbps.'},
|
||||
egDesc:{type:'map',doc:'RouteScript drains per exit.'},
|
||||
netEg:{type:'map',doc:'Per-network egress split: which exit carries which network.'},
|
||||
ef:{type:'map',doc:'LAZY per-link exit breakdown: what crosses each link, per network, built only when a panel asks. What is in here depends on which panels have rendered.'},
|
||||
l2:{type:'map',doc:'Layer-2 traffic per customer (L2VPN, SD-WAN, waves).'},
|
||||
l2lat:{type:'map',doc:'Latency per L2 customer.'},
|
||||
l2route:{type:'map',doc:'Which path an L2 customer\'s traffic takes.'},
|
||||
l2split:{type:'map',doc:'L2 traffic split per path.'},
|
||||
nodeLoad:{type:'map',doc:'Router forwarding load per city.'},
|
||||
nodeCap:{type:'map',doc:'Router forwarding capacity per city.'},
|
||||
div:{type:'map',doc:'Traffic diversity per customer (how split their paths are).'},
|
||||
gfwLost:{type:'number',doc:'Traffic lost to the Great Firewall.'},
|
||||
gfwCross:{type:'number',doc:'Traffic crossing into mainland China.'},
|
||||
p95:{type:'map',doc:'95th-percentile transit readings per port.'},
|
||||
peered:{type:'number',doc:'Share of traffic that stays on peering.'},
|
||||
peerShare:{type:'number',doc:'Fraction of traffic served by peers (mood driver).'},
|
||||
load:{type:'map',doc:'Load per link in Gbps.'},
|
||||
useT:{type:'map',doc:'Transit use per port id.'},
|
||||
useIx:{type:'map',doc:'IX use per exchange city.'},
|
||||
usePni:{type:'map',doc:'PNI use per port id.'},
|
||||
useCache:{type:'map',doc:'Cache use per box id.'},
|
||||
cityDem:{type:'map',doc:'Eyeball + customer demand per city.'},
|
||||
citySrv:{type:'map',doc:'Traffic served per city.'},
|
||||
cityEye:{type:'map',doc:'Eyeballs online per city.'},
|
||||
cityWisp:{type:'map',doc:'Island Wi-Fi: the Gbps of island homes each city carries for its zones (already in cityDem; never in cityEye). Only there while you run a zone.'},
|
||||
wisp:{type:'map',doc:'Island Wi-Fi zones by zone id (catalog WISP): d, the homes\' Gbps wanted; car, what their backhaul carried; sf, how well they were served (0..1); k, how many may sign up over today\'s link (the take-up cap). Only there while you run a zone.'},
|
||||
wispL:{type:'array',doc:'Island Wi-Fi zones in this compute: z, its city c, zd wanted and car carried, in Gbps. Only there while you run a zone.'},
|
||||
latF:{type:'map',doc:'Fraction of each city\'s traffic that goes far (over a threshold latency).'},
|
||||
latFar:{type:'map',doc:'The far exit each slow city sends traffic through.'},
|
||||
satU:{type:'map',doc:'Of each city\'s served traffic, the Gbps that rode a rented satellite circuit (its users notice the orbit\'s latency on that share). Only there while you have a satellite circuit up.'},
|
||||
demTo:{type:'map',doc:'Your traffic destined to each network, in Gbps. The number CDN caches ask about.'},
|
||||
served:{type:'number',doc:'Total traffic served, in Gbps.'},
|
||||
demand:{type:'number',doc:'Total traffic demanded, in Gbps.'},
|
||||
reach:{type:'number',doc:'Fraction of the internet you can reach (0..1).'},
|
||||
sessions:{type:'number',doc:'Peering sessions up.'},
|
||||
revMo:{type:'number',doc:'Revenue per month.'},
|
||||
costMo:{type:'number',doc:'Cost per month.'},
|
||||
cost:{type:'map',doc:'Monthly cost by category (transit, pni, ix, links…).'},
|
||||
rev:{type:'map',doc:'Monthly revenue by source (late: a late joiner\'s first-year match of what its homes pay).'},
|
||||
reachable:{type:'map',doc:'Networks reachable per net id.'},
|
||||
cone:{type:'map',doc:'Which peer\'s customer cone carries each network you reach without transit of your own, by net id.'},
|
||||
ddos:{type:'array',doc:'Per live attack: the target, its size, which ports it fills, what Flowspec and each scrubbing centre cleaned, and what reaches the target.'},
|
||||
haul:{type:'array',doc:'Scrubbing detours: from the attacked city to each centre, one-way latency and how much they carry.'},
|
||||
tgtF:{type:'map',doc:'The share of a targeted customer\'s traffic that survives the attack, by customer id.'},
|
||||
bbF:{type:'map',doc:'The share of a city\'s broadband subscribers that survive an attack on them, by city id.'},
|
||||
fsUse:{type:'map',doc:'Flowspec rules in use per city: used of the routers\' rule capacity.'},
|
||||
bizDem:{type:'map',doc:'Business customers\' share of each city\'s demand, in Gbps (what RouteScript\'s protect customers serves first).'},
|
||||
bizSrv:{type:'map',doc:'Of that business demand, what was served, per city.'},
|
||||
graceNets:{type:'number',doc:'Networks reached over the courtesy route after a merger wave.'},
|
||||
cityBlocked:{type:'map',doc:'Set up per city by the traffic computation; nothing fills it at present.'},
|
||||
ddosHot:{type:'map',doc:'Cities whose ports a flood is filling, for the map\'s pulse. Keyed by city id.'},
|
||||
};
|
||||
|
||||
/* The dice rather than the board: in the player's tab (over the relay) state never returns these, and schema says why.
|
||||
The MCP server's own page returns them, for debugging. */
|
||||
const API_WITHHELD={
|
||||
rng:'the seed: it predicts every future random draw',
|
||||
nextFail:'the day the next failure fires',
|
||||
nextEvent:'the day the next world event fires',
|
||||
'scn.nextDdos':'the day of the next scripted attack in a scenario',
|
||||
};
|
||||
230
src/agent/40-read.js
Normal file
230
src/agent/40-read.js
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
/* ================= AGENT API: reading the game =================
|
||||
Every function takes and returns plain JSON and only reads the game. */
|
||||
/* Dotted subtrees, no wildcards. An array walks by index (`biz.3`) or by entity id (`links[#id]`). */
|
||||
function apiPath(o,p){
|
||||
if(p===undefined||p===null||p==='')return o;
|
||||
let v=o;
|
||||
for(const k of String(p).split('.')){
|
||||
if(v==null)return undefined;
|
||||
if(Array.isArray(v)){const i=Number(k);
|
||||
v=(Number.isInteger(i)&&String(i)===k&&i>=0&&i<v.length)?v[i]:v.find(x=>x&&typeof x==='object'&&x.id===k);}
|
||||
else if(v instanceof Set)v=[...v];
|
||||
else if(v instanceof Map)v=Object.fromEntries(v);
|
||||
else if(typeof v==='object')v=v[k];
|
||||
else return undefined;}
|
||||
return v;}
|
||||
|
||||
function apiJson(v){
|
||||
if(v instanceof Set)return [...v].map(apiJson);
|
||||
if(v instanceof Map)return apiJson(Object.fromEntries(v));
|
||||
if(v&&typeof v==='object')return Array.isArray(v)?v.map(apiJson):Object.fromEntries(Object.entries(v).map(([k,x])=>[k,apiJson(x)]));
|
||||
if(typeof v==='function')return undefined;
|
||||
return v;}
|
||||
|
||||
/* The tables the argument domains point at. Everything is a static reference except three,
|
||||
each computed for a reason: BADGES hides unearned secrets like the badge wall; conferences
|
||||
carries the keys confGo/confSponsor need, which exist in no field of S; TE_RECIPES renders
|
||||
each recipe's script, because the source is a function and some read the live network. The
|
||||
recipes' relevance score is not exposed: judging which one fits is the agent's job. */
|
||||
const API_TABLES={ROCKETS,CRUSTS,PIE_RD,PIE_SPAT_DEF,SATS,SAT_ORB,SAT_PROV,WISP,SALES,CITIES,NETS,CABLES,XIX,PORT,LT,NNI,VXC,RG,OPT,DF_SYS,FAB,SCRUB_TIERS,BIZ_T,LEVELS,GOALS,BROKER_GOALS,SCN,BANKS,REQS,NSH,MET,PREF,RT,PPOL,CONFS,LAG_MAX,PNI_LAG_MAX,PNI_LAG_RT,RMAX,REGEN_MAX,START_CASH,CONF_COST,CONF_SP,CAP_COST,CAP_LV,CONF_DAYS,SUB_UPGRADES,SEA_DESIGNS,TE_COST,TE_MO,MYIX_COST,CN_LIC,SITE2_COST,MYIX_FAB,INTERNS,OPSK,CHARTERS,SEAT_N,CORE_LV,CORE_COST,CORE_REQ,CORE_LAB,INTERN_MO,PZ_TIERS,AR_TIERS,PZ_RG};
|
||||
const API_MADE={
|
||||
BADGES:()=>!S?[]:BADGES.map(b=>{const on=S.ach&&S.ach[b.id]!==undefined,ever=!!hof()[b.id];
|
||||
return b.secret&&!on&&!ever?{id:b.id,i:'❔',t:'???',d:tr('badges.a_secret_badge'),r:b.r,secret:true}:{...b,ever};}),
|
||||
conferences:()=>!S?[]:upcomingConfs(75).map(cf=>({key:cf.key,name:cf.n,city:cf.c,day:cf.day,capacity:!!cf.cap,cost:confCost(cf),sponsorCost:confSp(cf)?CONF_SP:null})),
|
||||
TE_RECIPES:()=>!S?[]:TE_RECIPES.map(r=>({id:r.id,name:tr(r.n),description:tr(r.d),script:r.src().join('\n')})),
|
||||
};
|
||||
function API_CATALOG_TABLE(name){return name in API_MADE?API_MADE[name]():API_TABLES[name];}
|
||||
|
||||
/* UI minus the render caches and pointer scratch, which are inputs to nothing.
|
||||
Everything a command binds (pending, route, via, dfSrc, dfSys, seaDesign, cnPrem, decom,
|
||||
teDraft, confirm) stays, so an agent can see what it was given. */
|
||||
const API_UI_HIDDEN={_lh:1,_ph:1,_tb:1,_layer:1,layerAt:1,hover:1,drag:1,snap:1};
|
||||
|
||||
/* ---------- text as a player reads it ---------- */
|
||||
const API_BLOCK=/^(DIV|P|H1|H2|H3|H4|SECTION|LI|UL|OL|TR|TABLE|NAV|HEADER|FOOTER|BUTTON|LABEL|DETAILS|SUMMARY)$/,API_MAX_TEXT=8000;
|
||||
// One line per block, no runs of spaces. jsdom has no innerText, so this walks the nodes itself.
|
||||
function apiFullText(x){
|
||||
let el=x;
|
||||
if(typeof x==='string'){el=document.createElement('div');el.innerHTML=x;}
|
||||
if(!el)return '';
|
||||
const out=[];
|
||||
const walk=n=>{
|
||||
if(n.nodeType===3){out.push(n.nodeValue);return;}
|
||||
if(n.nodeType!==1||n.hidden||/^(SCRIPT|STYLE|SVG|CANVAS)$/i.test(n.tagName))return;
|
||||
if(n.tagName==='BR'){out.push('\n');return;}
|
||||
// A dropdown reads as its choice: hundreds of options would crowd out the rest (the catalog lists them).
|
||||
if(n.tagName==='SELECT'){const o=n.options[n.selectedIndex];out.push(' ',o?o.text:'',' ');return;}
|
||||
// Blocks get their own line; inline tags a space, so "Revenue<b>$2k</b>" does not read as one word.
|
||||
const sep=API_BLOCK.test(n.tagName)?'\n':' ';
|
||||
out.push(sep);for(const c of n.childNodes)walk(c);out.push(sep);};
|
||||
walk(el);
|
||||
return out.join('').split('\n').map(l=>l.replace(/\s+/g,' ').replace(/ ([.,;:!?)])/g,'$1').replace(/\( /g,'(').trim()).filter(Boolean).join('\n');}
|
||||
const apiText=(x,max=API_MAX_TEXT)=>{const s=apiFullText(x);return s.length>max?s.slice(0,max)+'\n…':s;};
|
||||
const apiR1=v=>typeof v==='number'&&isFinite(v)?Math.round(v*10)/10:v;
|
||||
const apiFail=msg=>{throw new Error(msg);};
|
||||
const apiNorm=s=>String(s||'').toLowerCase().normalize('NFD').replace(/[\u0300-\u036f]/g,'').trim();
|
||||
const apiParse=s=>{try{return JSON.parse(s||'{}');}catch(e){return {};}};
|
||||
|
||||
/* ---------- finding things by id or by name ---------- */
|
||||
function apiBest(list,q,keys){const n=apiNorm(q);if(!n)return null;
|
||||
for(const test of [v=>v===n,v=>v.startsWith(n),v=>v.includes(n)]){const hit=list.find(x=>keys(x).some(k=>test(apiNorm(k))));if(hit)return hit;}
|
||||
return null;}
|
||||
const apiNetOf=q=>NET[q]||apiBest(NETS,q,n=>[n.id,n.name,'as'+n.asn,String(n.asn)])||apiFail(`No network matches "${q}". Try find.`);
|
||||
const apiCityOf=q=>CITY[q]||apiBest(CITIES,q,c=>[c.id,c.name])||apiFail(`No city matches "${q}". Try find.`);
|
||||
function apiAllIx(){const o=[];for(const c of CITIES)for(const x of ixStatic(c.id))o.push(x);for(const c of Object.keys(S.myIx||{}))if(!o.includes(c))o.push(c);return o;}
|
||||
const apiCityName=c=>CITY[c]?CITY[c].name:c;
|
||||
const apiIncText=i=>apiText(i.msg||incTitle(i),400);
|
||||
const apiMyPops=()=>Object.keys(S.pops).map(apiCityName).join(', ');
|
||||
|
||||
/* ---------- the network at a glance, and the world ---------- */
|
||||
function apiStatus(){
|
||||
const goal=goals().find(g=>S.done[g.id]===undefined),t1=isTier1(),k=o=>Object.fromEntries(Object.entries(o||{}).map(([a,v])=>[a,Math.round(v)]).filter(([,v])=>v));
|
||||
return {
|
||||
name:S.name,asn:S.asn,home:apiCityName(S.home),mode:S.mode,rules:S.rules&&S.rules.preset,
|
||||
day:S.day,age:netAge(),date:dateStr(S.day),cash:Math.round(S.cash),level:S.lvl||0,
|
||||
tier:tierLabel(),whyNotTier1:t1?null:apiText(t1Why()),
|
||||
goal:goal?{title:apiText(goal.t),what:apiText(goal.d)}:null,
|
||||
monthly:{revenue:Math.round(R.revMo),cost:Math.round(R.costMo),profit:Math.round(R.revMo-R.costMo),revenueBy:k(R.rev),costBy:k(R.cost)},
|
||||
traffic:{demandGbps:apiR1(R.demand),servedGbps:apiR1(R.served),reach:apiR1((R.reach||0)*100)+'%',peeringSessions:R.sessions},
|
||||
counts:{pops:Object.keys(S.pops).length,links:S.links.length,transitPorts:S.transit.length,exchangePorts:Object.keys(S.ixp).length,
|
||||
pnis:S.pni.length,cacheBoxes:S.caches.length,customers:S.biz.length,offers:S.offers.length},
|
||||
pops:Object.keys(S.pops).map(apiCityName),
|
||||
incidents:S.inc.map(i=>({id:i.id,type:i.type,what:apiIncText(i),until:i.until!==undefined?dateStr(i.until):undefined,rushRepairCost:i.cost||undefined})),
|
||||
lost:!!S.lost,won:!!S.won,
|
||||
};}
|
||||
|
||||
function apiNetwork(q){
|
||||
const n=apiNetOf(q),id=n.id,eg=R.netEg&&R.netEg[id];
|
||||
return {
|
||||
id,name:n.name,asn:n.asn,type:TYPE_L[n.type],policy:n.pol,
|
||||
requirements:{minIxGbps:n.minIx,minPniGbps:n.minPni,paidFeePerMonth:n.paidFee,freeFromLevel:n.freeLv},
|
||||
trafficShare:apiR1(NSH[id]*100)+'%',transitPerGbps:n.price?apiR1(n.price*S.priceMul):null,
|
||||
homeMarkets:n.cc?[].concat(n.cc):[],pops:n.pops.map(apiCityName),
|
||||
exchanges:n.ix==='ALL'?'most exchanges where it has a PoP':(n.ix||[]).map(x=>ixName(x)),
|
||||
upstreams:(n.up||[]).map(u=>NET[u]?NET[u].name:u),customerCone:(DOWN[id]||[]).length,
|
||||
neededForTier1:t1Need().some(x=>x.id===id),mergedInto:merged(id)?(MERGERS.find(m=>m.id===id)||{}).into:undefined,
|
||||
about:apiText(n.blurb),
|
||||
you:{
|
||||
reachable:!!(R.reachable&&R.reachable[id]),demandGbps:apiR1((R.demTo&&R.demTo[id])||0),
|
||||
egressGbps:eg?Object.fromEntries(Object.entries(eg).map(([k,v])=>[k,apiR1(v)])):null,
|
||||
pnis:S.pni.filter(p=>p.net===id).map(p=>({id:p.id,city:apiCityName(p.city),port:pniPN(p),count:p.n||1,ready:pniOn(p)})),
|
||||
exchangeSessions:Object.keys(S.ixp).filter(x=>ixSessions(x).has(id)).map(ixName),
|
||||
howToPeer:apiText(offTransitHint(id,S.home)),
|
||||
},
|
||||
};}
|
||||
|
||||
function apiCity(q){
|
||||
const C=apiCityOf(q),c=C.id,P=S.pops[c];
|
||||
const cab=CABLE_PAIRS.filter(p=>p.a===c||p.b===c).map(p=>({cable:CAB[p.cid]?CAB[p.cid].name:p.cid,to:apiCityName(p.a===c?p.b:p.a),km:p.km}));
|
||||
const here=NETS.filter(n=>n.pops.includes(c)&&!n.tail).sort((a,b)=>b.share-a.share);
|
||||
return {
|
||||
id:c,name:C.name,country:C.cc,region:C.reg,about:C.note?apiText(C.note):undefined,dataCenter:C.dc,
|
||||
canBeHome:homeOk(c),
|
||||
exchanges:ixIdsIn(c).map(x=>({id:x,name:ixName(x),members:ixMembers(x).length,yourPort:S.ixp[x]!==undefined})),
|
||||
transit:NETS.filter(n=>sellsAt(n,c)).map(n=>({id:n.id,name:n.name,type:TYPE_L[n.type],perGbps:apiR1(transitPerG(n,c,false)*S.priceMul)})).sort((a,b)=>a.perGbps-b.perGbps),
|
||||
networksHere:here.length,biggestNetworksHere:here.slice(0,15).map(n=>n.name),cables:cab,
|
||||
you:P?{demandGbps:apiR1((R.cityDem||{})[c]||0),servedGbps:apiR1((R.citySrv||{})[c]||0),routers:P.routers,down:P.down>S.day?dateStr(P.down):false,
|
||||
broadband:!!P.bb,links:S.links.filter(l=>l.a===c||l.b===c).length}:null,
|
||||
};}
|
||||
|
||||
function apiFind(q,kind){
|
||||
const n=apiNorm(q),hit=(...k)=>k.some(v=>apiNorm(v).includes(n)),out={};
|
||||
if(!n)apiFail('Give a word to search for.');
|
||||
if(!kind||kind==='city')out.cities=CITIES.filter(c=>hit(c.id,c.name)).slice(0,20).map(c=>({id:c.id,name:c.name,country:c.cc}));
|
||||
if(!kind||kind==='network')out.networks=NETS.filter(x=>hit(x.id,x.name,String(x.asn))).slice(0,20).map(x=>({id:x.id,name:x.name,asn:x.asn,type:TYPE_L[x.type]}));
|
||||
if(!kind||kind==='cable')out.cables=Object.values(CAB).filter(x=>hit(x.id,x.name)).slice(0,20).map(x=>({id:x.id,name:x.name,lands:[...new Set(x.pairs.flatMap(p=>[p[0],p[1]]))].map(apiCityName)}));
|
||||
if(!kind||kind==='exchange')out.exchanges=apiAllIx().filter(x=>hit(x,ixName(x))).slice(0,20).map(x=>({id:x,name:ixName(x),city:apiCityName(ixCity(x))}));
|
||||
return out;}
|
||||
|
||||
function apiTrace(from,to){
|
||||
const src=apiCityOf(from).id;
|
||||
if(!S.pops[src])apiFail(`You have no POP in ${apiCityName(src)}. Yours: ${apiMyPops()}.`);
|
||||
let target=null;
|
||||
if(typeof to==='string'&&/^city:/i.test(to))target={city:apiCityOf(to.slice(5)).id};
|
||||
else{try{target={net:apiNetOf(to).id};}catch(e){target={city:apiCityOf(to).id};}}
|
||||
if(target.city&&!S.pops[target.city])apiFail(`A traceroute to a city goes to one of your POPs: ${apiMyPops()}.`);
|
||||
const r=traceroute(src,target);
|
||||
return {text:r.text,why:apiText(r.why||''),asPath:r.asPath||null};}
|
||||
|
||||
function apiPeering(q,where,via){
|
||||
const n=apiNetOf(q),id=n.id,out=[];
|
||||
if(!via||via==='pni')for(const c of (where?[apiCityOf(where).id]:Object.keys(S.pops).filter(c=>n.pops.includes(c)))){
|
||||
const r=peerOk(id,'pni',c);
|
||||
out.push({via:'pni',city:apiCityName(c),ok:!!r.ok,why:r.why?apiText(r.why):undefined,feePerMonth:r.fee,free:r.free,minimumPort:PORT[pniMin(id)].n});}
|
||||
if(!via||via==='ix')for(const x of Object.keys(S.ixp).filter(x=>ixMembers(x).includes(id)&&(!where||ixCity(x)===apiCityOf(where).id))){
|
||||
const r=peerOk(id,'ix',x);
|
||||
out.push({via:'ix',exchange:ixName(x),ok:!!r.ok,why:r.why?apiText(r.why):undefined,session:ixSessions(x).has(id)});}
|
||||
return {network:n.name,policy:n.pol,hint:apiText(offTransitHint(id,where?apiCityOf(where).id:S.home)),
|
||||
checks:out,note:out.length?undefined:'No POP or exchange port of yours is where this network is. Build one first: see network.'};}
|
||||
|
||||
function apiHotSpots(limit=10){
|
||||
const top=a=>a.sort((x,y)=>y.util-x.util).slice(0,limit),pct=(u,c)=>c>0?apiR1((u/c)*100):null;
|
||||
const links=S.links.map(l=>{const cap=capOf(l),u=(R.load||{})[l.id]||0;return {id:l.id,between:apiCityName(l.a)+' – '+apiCityName(l.b),kind:l.kind,capacity:capName(l),usedGbps:apiR1(u),util:pct(u,cap),down:linkDown(l)};});
|
||||
const transit=S.transit.map(t=>{const cap=lagCap(PORT[t.tier].g,t.n),u=(R.useT||{})[t.id]||0,q=(R.p95&&R.p95[t.id])||u;
|
||||
return {id:t.id,city:apiCityName(t.city),carrier:NET[t.net].name,port:lagName(t.tier,t.n),usedGbps:apiR1(u),util:pct(u,cap),billPerMonth:Math.round(transitMo(t,q))};});
|
||||
const pnis=S.pni.filter(pniOn).map(p=>{const cap=pniG(p)*(p.n||1),u=(R.usePni||{})[p.id]||0;return {id:p.id,network:NET[p.net].name,city:apiCityName(p.city),port:pniPN(p),usedGbps:apiR1(u),util:pct(u,cap)};});
|
||||
const viaTransit=NETS.filter(n=>R.netEg&&R.netEg[n.id]&&R.netEg[n.id].t>0.05).sort((a,b)=>R.netEg[b.id].t-R.netEg[a.id].t).slice(0,limit)
|
||||
.map(n=>({id:n.id,network:n.name,overTransitGbps:apiR1(R.netEg[n.id].t),howToPeer:apiText(offTransitHint(n.id,S.home))}));
|
||||
const bill={};for(const t of transit)bill[t.carrier]=(bill[t.carrier]||0)+t.billPerMonth;
|
||||
return {links:top(links),transitPorts:top(transit),pnis:top(pnis),transitBillByCarrier:bill,biggestTrafficStillOnTransit:viaTransit};}
|
||||
|
||||
/* ---------- the contract: commands, arguments, reference tables, raw state ---------- */
|
||||
const apiDenied=name=>own(API_DENY,name)?API_WHY[API_DENY[name]]:null;
|
||||
const apiKind=name=>API_CMD[name]?'game':API_VIEW[name]?'view':API_BOUND[name]?'draft':API_SESSION[name]?'session':null;
|
||||
const apiSpec=name=>API_CMD[name]||API_VIEW[name]||API_SESSION[name]||null;
|
||||
const apiClasses=()=>({game:Object.keys(API_CMD),view:Object.keys(API_VIEW),draft:Object.keys(API_BOUND),session:Object.keys(API_SESSION),denied:Object.keys(API_DENY)});
|
||||
|
||||
// One argument as the schema states it. Table domains name their catalog table rather than list every id.
|
||||
function apiArgDoc([name,dom,req]){
|
||||
const a={name,required:req!==false},d=API_DOMAINS[dom];
|
||||
if(!d){a.type=dom;return a;}
|
||||
a.domain=dom;
|
||||
if(d.table)a.from=d.table;
|
||||
else{const v=apiDomValues(dom);if(Array.isArray(v))a.values=v;else if(v&&v.from!==undefined)a.range=v;}
|
||||
return a;}
|
||||
function apiSchema(section){
|
||||
const cmd=s=>({args:(s.args||[]).map(apiArgDoc),doc:s.doc}),relay=API_CTX.relay;
|
||||
const doc={
|
||||
mode:apiMode(),
|
||||
clock:apiClockDoc(),
|
||||
commands:Object.fromEntries(Object.entries(API_CMD).map(([n,s])=>[n,{...cmd(s),dryRun:!!s.quote,
|
||||
...(s.decides?{decides:true}:{}),...(s.confirm?{confirm:s.confirm}:{}),...(s.open?{opens:s.open}:{}),...(s.reads?{report:true}:{})}])),
|
||||
view:Object.fromEntries(Object.entries(API_VIEW).map(([n,s])=>[n,cmd(s)])),
|
||||
session:Object.fromEntries(Object.entries(API_SESSION).map(([n,s])=>[n,{...cmd(s),...(relay&&API_PLAYER_OWNS[n]?{refused:API_OWN_WHY}:{})}])),
|
||||
drafts:API_BOUND,
|
||||
denied:Object.fromEntries(Object.keys(API_DENY).sort().map(n=>[n,apiDenied(n)])),
|
||||
domains:Object.fromEntries(Object.entries(API_DOMAINS).map(([n,d])=>{const v=apiDomValues(n);
|
||||
return [n,{kind:d.kind==='fn'?'custom':d.kind,...(d.table?{from:d.table}:{}),
|
||||
...(!d.table&&Array.isArray(v)?{values:v}:v&&v.from!==undefined?{range:v}:v&&v.of?{of:v.of}:{})}];})),
|
||||
state:relay?Object.fromEntries(Object.entries(API_STATE_DOC).map(([k,d])=>[k,API_WITHHELD[k]?{...d,withheld:API_WITHHELD[k]}:d])):API_STATE_DOC,
|
||||
results:API_RESULTS_DOC,
|
||||
};
|
||||
if(section===undefined||section===null||section==='')return doc;
|
||||
if(!(section in doc))apiFail(`No section "${section}". Sections: ${Object.keys(doc).join(', ')}.`);
|
||||
return doc[section];}
|
||||
function apiCatalog(name){
|
||||
if(name===undefined||name===null||name===''){
|
||||
return {tables:[...Object.keys(API_TABLES),...Object.keys(API_MADE)].sort().map(k=>{const t=k in API_MADE?API_MADE[k]():API_TABLES[k];
|
||||
return {name:k,n:Array.isArray(t)?t.length:t&&typeof t==='object'?Object.keys(t).length:1};})};}
|
||||
if(name in API_MADE)return apiJson(API_MADE[name]());
|
||||
if(name in API_TABLES)return apiJson(API_TABLES[name]);
|
||||
apiFail(`No table "${name}". Call catalog without a name for the list.`);}
|
||||
// In the player's tab the dice are held back: a withheld field, or one inside the subtree asked for, is left out.
|
||||
function apiState(path){
|
||||
if(!S)return null;
|
||||
const p=path===undefined||path===null?'':String(path),v=apiJson(apiPath(S,p));
|
||||
if(v===undefined)return null;
|
||||
if(!API_CTX.relay)return v;
|
||||
for(const w of Object.keys(API_WITHHELD)){
|
||||
if(w===p||p.startsWith(w+'.'))return null;
|
||||
if(p&&!w.startsWith(p+'.'))continue;
|
||||
const ks=(p?w.slice(p.length+1):w).split('.');let o=v;
|
||||
for(let i=0;i<ks.length-1&&o&&typeof o==='object';i++)o=o[ks[i]];
|
||||
if(o&&typeof o==='object')delete o[ks[ks.length-1]];}
|
||||
return v;}
|
||||
function apiResults(path){const v=apiJson(apiPath(R,path));return v===undefined?null:v;}
|
||||
function apiUi(){const o={};for(const k of Object.keys(UI))if(!API_UI_HIDDEN[k])o[k]=apiJson(UI[k]);return o;}
|
||||
function apiActions(){
|
||||
const sig=s=>(s.args||[]).map(a=>a[0]+(a[2]===false?'?':'')).join(','),typed={};
|
||||
for(const t of [API_CMD,API_VIEW,API_SESSION])for(const [n,s] of Object.entries(t))typed[n]=sig(s);
|
||||
return {typed,drafts:Object.keys(API_BOUND)};}
|
||||
79
src/agent/50-screen.js
Normal file
79
src/agent/50-screen.js
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
/* ================= AGENT API: what is on screen =================
|
||||
The surfaces a player can read, as text with numbered buttons, by the name screen takes. The left drawer has tabs
|
||||
(goals, deals, noc, nets). */
|
||||
const API_ROOT={modal:'modal',bank:'bankBox',dash:'dash',panel:'panel',left:'leftBody',puzzle:'pzBox'};
|
||||
const apiShown=w=>{const el=$(API_ROOT[w]);return !!el&&!el.hidden;};
|
||||
const apiModalOpen=()=>apiShown('modal');
|
||||
// A window the player opened by hand (API_MODAL.hand, 75-mode.js) is theirs: a tool reads it but never answers,
|
||||
// closes or replaces it, and it is never a question the game is waiting on.
|
||||
const apiPlayerWin=()=>apiModalOpen()&&API_MODAL.hand;
|
||||
// The buttons of the last screen a tool read, for click. Set by apiScreen.
|
||||
let API_LAST=[];
|
||||
function apiControls(root,player){
|
||||
const out=[];
|
||||
for(const b of root.querySelectorAll('[data-act],select[data-chg]')){
|
||||
const o=b.dataset.act?{label:apiText(b,200).replace(/\n/g,' ')||b.getAttribute('aria-label')||b.dataset.act,act:b.dataset.act,args:apiParse(b.dataset.args),disabled:!!b.disabled}
|
||||
// A list the game acts on when its value changes (the change handler in 96-map/95-clicks.js): click it with a value.
|
||||
:{label:b.getAttribute('aria-label')||(b.closest('label')&&apiText(b.closest('label'),120).split('\n')[0])||b.dataset.chg,
|
||||
select:b.dataset.chg,args:apiParse(b.dataset.args),value:b.value,options:[...b.options].map(o=>({value:o.value,label:o.textContent.trim()})),disabled:!!b.disabled};
|
||||
if(player)o.player=true;
|
||||
out.push(o);}
|
||||
return out;}
|
||||
function apiScreen(where,offset=0){
|
||||
if(where===null)where=undefined;
|
||||
if(where!==undefined&&!API_ROOT[where])apiFail(`where is one of ${Object.keys(API_ROOT).join(', ')}.`);
|
||||
const open=Object.keys(API_ROOT).filter(w=>w!=='left'&&apiShown(w));
|
||||
const w=where||['modal','bank','dash','panel','puzzle'].find(apiShown)||'panel';
|
||||
const root=$(API_ROOT[w]),player=w==='modal'&&apiPlayerWin();
|
||||
API_LAST=root?apiControls(root,player):[];
|
||||
const all=root?apiFullText(root):'',from=Math.max(0,Math.floor(+offset)||0),more=all.length-from-API_MAX_TEXT;
|
||||
const out={where:w,open,selected:UI.sel,tab:UI.tab};
|
||||
if(w==='left')out.leftTab=UI.left||'goals';
|
||||
if(w==='modal'){out.question=!!apiDecision();if(player)out.playerWindow='the player opened this window: read it, but its buttons are theirs to press';}
|
||||
out.text=all.slice(from,from+API_MAX_TEXT);
|
||||
if(from)out.textFrom=from;
|
||||
if(more>0)out.textMore=`${more} more characters: call screen with where "${w}" and offset ${from+API_MAX_TEXT}`;
|
||||
out.buttons=API_LAST.map((b,i)=>({n:i,...b}));
|
||||
return out;}
|
||||
|
||||
/* ---------- windows: the tool's own sheets, and the game's questions ----------
|
||||
A window the tool opened itself (a view, a draft, the link window, a sheet it clicked inside) is something to read
|
||||
and click through. A window the game opened in answer to a game command, or during a day, is a question when one
|
||||
of its buttons runs a game command other than closeModal (a De-Kicks quote, a retention offer); then other game
|
||||
commands wait until it is answered or closed, as clicks outside an open window do in the game. */
|
||||
let API_SHEET=null;
|
||||
const apiCard=()=>$('modalCard').firstChild;
|
||||
const apiMarkSheet=()=>{API_SHEET=apiModalOpen()&&!apiPlayerWin()?apiCard():null;};
|
||||
const apiIsSheet=()=>apiModalOpen()&&!!API_SHEET&&apiCard()===API_SHEET;
|
||||
function apiDecision(){
|
||||
if(!apiModalOpen()||apiIsSheet()||apiPlayerWin())return null;
|
||||
const b=[...$('modal').querySelectorAll('[data-act]')].filter(x=>x.dataset.act!=='closeModal'&&API_CMD[x.dataset.act]);
|
||||
if(!b.length)return null;
|
||||
return {text:apiText($('modal'),1500),options:b.map(x=>({command:x.dataset.act,args:apiParse(x.dataset.args),label:apiText(x,120).replace(/\n/g,' ')}))};}
|
||||
|
||||
/* A player's window stays where it is: its very nodes are set aside while a tool's command runs, and put back after,
|
||||
so typed text survives. Only a question the game asks in answer to the tool's move takes the screen, as it would
|
||||
after a click. */
|
||||
function apiHold(){const m=$('modal'),c=$('modalCard');
|
||||
return {nodes:[...c.childNodes],cls:m.className,aria:c.getAttribute('aria-modal'),setOpen:UI.setOpen,pending:UI.pending};}
|
||||
function apiRestore(h){const m=$('modal'),c=$('modalCard');
|
||||
if(!m.hidden&&m.className===h.cls&&c.childNodes.length===h.nodes.length&&h.nodes.every((n,i)=>c.childNodes[i]===n)){API_MODAL.hand=true;return;}
|
||||
m.className=h.cls;if(h.aria!==null)c.setAttribute('aria-modal',h.aria);c.replaceChildren(...h.nodes);
|
||||
if(m.hidden)markLayer();m.hidden=false;UI.setOpen=h.setOpen;UI.pending=h.pending;API_MODAL.hand=true;API_SHEET=null;}
|
||||
|
||||
function apiPanel({city:c,link,network:q,tab,left}={}){
|
||||
if(left!==undefined){if(!['goals','deals','noc','nets'].includes(left))apiFail('left is one of goals, deals, noc, nets.');ACT.leftTab({t:left});return apiScreen('left');}
|
||||
if(c)UI.sel={type:'city',id:apiCityOf(c).id};
|
||||
else if(link){if(!S.links.some(l=>l.id===link))apiFail(`No link ${link}. See status or hot_spots for link ids.`);UI.sel={type:'link',id:link};}
|
||||
else if(q)ACT.netFocus({id:apiNetOf(q).id});
|
||||
if(tab)UI.tab=tab;
|
||||
renderAll();
|
||||
return apiScreen(q?'left':'panel');}
|
||||
function apiOpenLink(a,b){
|
||||
const x=apiCityOf(a).id,y=apiCityOf(b).id;
|
||||
if(!S.pops[x])apiFail(`A link starts at one of your POPs: ${apiMyPops()}.`);
|
||||
if(apiPlayerWin())apiFail('The player has a window open, and the link window would replace it. Use act buildLink, orderDf or orderCable, or wait until it is closed.');
|
||||
apiTake();
|
||||
openLinkModal(x,y);
|
||||
apiMarkSheet();
|
||||
return {toasts:apiToastLines(apiTake()),screen:apiScreen()};}
|
||||
123
src/agent/60-dispatch.js
Normal file
123
src/agent/60-dispatch.js
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
/* ================= AGENT API: doing things =================
|
||||
One action, run as the game runs it, and reported through the game's own channels: what it said (toast), what it
|
||||
charged at the money gate (spend) and whether anything changed (a fingerprint of S). The API checks shape and domain
|
||||
only; whether a move is allowed is the game's to answer. */
|
||||
|
||||
// Arguments: shape and domain only. Anything beyond that is the game's to answer.
|
||||
function apiValidate(spec,args){
|
||||
const problems=[],out={};
|
||||
for(const [name,dom,req] of spec.args||[]){
|
||||
const v=args[name];
|
||||
if(v===undefined){if(req!==false)problems.push(`${name} is required`);continue;}
|
||||
if(apiDomCheck(dom,v).ok){out[name]=v;continue;}
|
||||
const vs=apiDomValues(dom),d=API_DOMAINS[dom];
|
||||
problems.push(`${name}: ${JSON.stringify(v)} is not a ${dom}${d&&d.table&&d.kind==='id'?` (see catalog ${d.table} or find)`:Array.isArray(vs)?` (one of ${vs.slice(0,12).join(', ')}${vs.length>12?'…':''})`:vs&&typeof vs==='object'&&vs.from!==undefined?` (${vs.from}..${vs.to})`:''}`);}
|
||||
for(const k of Object.keys(args))if(!(spec.args||[]).some(a=>a[0]===k))problems.push(`${k} is not an argument of this action`);
|
||||
return {ok:!problems.length,problems,args:out};}
|
||||
|
||||
// The fingerprint tells "did nothing" from "did something quietly": cash, day, the entity counts, the small settings
|
||||
// maps, and the paths a command declares in watch. R is left out: it is rebuilt after every action.
|
||||
const API_FP_LEN=['links','transit','pni','caches','biz','offers','nni','loans','loanOffers','inc','scrubs'];
|
||||
const API_FP_KEYS=['pops','ixp','peers','myIx','done','ach','merged','confReg'];
|
||||
const API_FP_JSON=['name','pairMet','rs','ixn','ixSite','ixPref','spares','te','cnLic','hw','scrubMode','ppol','ops','core','ddosAuto','popStd','popTiers','demo','charter','monkey','seatOff','pz','ar','dk','ev'];
|
||||
function apiFp(watch,args){
|
||||
if(!S)return null;
|
||||
const f={cash:S.cash,day:S.day,lvl:S.lvl||1,won:!!S.won,lost:!!S.lost};
|
||||
for(const k of API_FP_LEN)f[k]=(S[k]||[]).length;
|
||||
for(const k of API_FP_KEYS)f[k]=Object.keys(S[k]||{}).length;
|
||||
for(const k of API_FP_JSON)f[k]=JSON.stringify(apiJson(S[k])??null);
|
||||
for(const p of watch||[])f['@'+p]=JSON.stringify(apiJson(apiPath(S,String(p).replace(/#(\w+)/g,(m,k)=>args&&args[k]!==undefined?args[k]:m)))??null);
|
||||
return JSON.stringify(f);}
|
||||
// spend() is the game's money gate and a top-level function, so every action reaches it by its global name.
|
||||
function apiMeter(){const real=window.spend;let paid=0;window.spend=c=>{const ok=real(c);if(ok)paid+=c;return ok;};return ()=>{window.spend=real;return paid;};}
|
||||
|
||||
/* typed: through the command table (bind the UI, type into fields, pass the confirmation); otherwise as a button click
|
||||
does it, with the button's own arguments. */
|
||||
function apiDispatch(name,kind,spec,args,typed){
|
||||
const mine=apiIsSheet()||(typed&&kind==='game'&&!!spec.open),held=apiPlayerWin()?apiHold():null;
|
||||
apiTake();
|
||||
const ref=S,cash=S?S.cash:0,f0=apiFp(spec&&spec.watch,args),paid=apiMeter();
|
||||
let threw=null,report;
|
||||
try{
|
||||
if(typed&&kind==='game'){
|
||||
if(spec.open){ACT[spec.open]({});apiMarkSheet();}
|
||||
// The custom metric's field lives in the link's panel.
|
||||
if(name==='metricSet'&&!$('metIn')){UI.sel={type:'link',id:args.id};renderAll();}
|
||||
const gone=(spec.dom||[]).filter(f=>!$(f));
|
||||
if(gone.length)throw new Error(`the field it types into (${gone.join(', ')}) is not on screen${name==='metricSet'?': set the link\'s metric to custom first (setMetric v "custom")':''}`);
|
||||
if(spec.bind)spec.bind(args);
|
||||
const a=spec.pass?spec.pass(args):args;
|
||||
ACT[name](a);
|
||||
if(spec.confirm==='double')ACT[name](a);
|
||||
if(spec.reads==='modal'&&apiModalOpen()&&!apiPlayerWin()){report=apiText($('modal'));closeModal();}
|
||||
}else ACT[name](args);
|
||||
}catch(e){threw=e;}
|
||||
const charged=paid();
|
||||
if(held&&(threw||!apiDecision())){
|
||||
// The tool's own sheet is read before the player's window goes back over it.
|
||||
const shot=!threw&&apiModalOpen()&&!apiPlayerWin()?apiScreen('modal'):null;
|
||||
apiRestore(held);
|
||||
if(shot)shot.note='The player has a window open, so this one was shown to you and closed again.';
|
||||
held.shot=shot;}
|
||||
if(threw){apiTake();apiFail(`${name} failed: ${threw&&threw.message||threw}`);}
|
||||
if(!apiModalOpen()||apiPlayerWin())API_SHEET=null;
|
||||
else if(mine||kind!=='game')apiMarkSheet();
|
||||
else API_SHEET=null;
|
||||
const said=apiTake(),d=apiDecision();
|
||||
const outcome=d?'decision':S!==ref||apiFp(spec&&spec.watch,args)!==f0||report!==undefined?'applied'
|
||||
:said.some(t=>t.kind==='bad')?'rejected':kind==='view'||kind==='draft'?'shown':'no_effect';
|
||||
return {action:name,outcome,toasts:apiToastLines(said),charged,cashChange:Math.round((S?S.cash:0)-cash),
|
||||
...(report!==undefined?{report}:{}),...(d?{decision:d}:{}),screen:held&&held.shot||apiScreen()};}
|
||||
// While the game waits for an answer, game commands other than its options report the question instead.
|
||||
function apiWaiting(name){
|
||||
const d=apiDecision();
|
||||
return d&&name!=='closeModal'&&!d.options.some(o=>o.command===name)
|
||||
?{action:name,outcome:'decision',reason:'A window is waiting for an answer: run one of its options, or closeModal.',decision:d,screen:apiScreen()}:null;}
|
||||
function apiQuote(name,spec,args){
|
||||
const ui0={};
|
||||
for(const k of spec.bindsUI||[])ui0[k]=UI[k];
|
||||
const f0=apiFp(spec.watch,args);
|
||||
// A dry run must not use up the dice: some helpers draw (a PNI's lead time), and a draw here would move the seeded
|
||||
// game. They get the middle of the range instead, so a drawn figure in a quote is a typical one.
|
||||
const dice=Math.random;
|
||||
Math.random=()=>0.5;
|
||||
let q={};
|
||||
try{
|
||||
if(spec.bind&&!spec.dom)spec.bind(args);
|
||||
if(spec.quote)q=spec.quote(args)||{};
|
||||
}catch(e){apiFail(`${name}: the price could not be worked out: ${e&&e.message||e}`);}finally{Math.random=dice;for(const k of Object.keys(ui0))UI[k]=ui0[k];}
|
||||
return {action:name,outcome:'quote',quote:{setup:0,monthly:0,...q,blocked:(q.blocked||[]).map(b=>apiText(String(b),400))},consistent:apiFp(spec.watch,args)===f0,
|
||||
...(spec.quote?{}:{note:'This command has no price of its own: it costs nothing up front.'})};}
|
||||
// Checks shared by act and click: what no tool runs, and what only the player runs in their own tab.
|
||||
function apiAllowed(name,what){
|
||||
const no=apiDenied(name);
|
||||
if(no)apiFail(`${name} is not available here: ${no}.`);
|
||||
if(API_CTX.relay&&API_PLAYER_OWNS[name])apiFail(`${name} is not available here: ${API_OWN_WHY}.`);
|
||||
const kind=apiKind(name);
|
||||
if(!kind||typeof ACT[name]!=='function')apiFail(what);
|
||||
return kind;}
|
||||
function apiRun(name,args,opts={}){
|
||||
name=String(name||'');
|
||||
if(name.startsWith('view.'))name=name.slice(5);
|
||||
const kind=apiAllowed(name,`There is no action "${name}". See actions or schema.`);
|
||||
args=args&&typeof args==='object'&&!Array.isArray(args)?args:{};
|
||||
const spec=apiSpec(name);
|
||||
if(spec){const v=apiValidate(spec,args);if(!v.ok)apiFail(`${name}: ${v.problems.join('; ')}. See schema for its arguments.`);args=v.args;}
|
||||
if(kind==='game'){
|
||||
if(S&&S.lost&&name!=='closeModal')return {action:name,outcome:'stopped',reason:'The network went bankrupt: start or load another game.'};
|
||||
const w=apiWaiting(name);
|
||||
if(w)return w;
|
||||
if(opts.dryRun)return apiQuote(name,spec,args);
|
||||
}else if(opts.dryRun)apiFail(`${name} has no price: only game commands (see schema commands) dry-run.`);
|
||||
return apiDispatch(name,kind,spec,args,true);}
|
||||
function apiClick(n,value){
|
||||
const b=API_LAST[n];
|
||||
if(!b)apiFail(`No button ${n} on the last screen. Call screen first.`);
|
||||
if(b.disabled)apiFail(`"${b.label}" is greyed out.`);
|
||||
if(b.player&&apiPlayerWin())apiFail(`"${b.label}" is in a window the player opened: it is theirs to press.`);
|
||||
// A list sends its own arguments with the value picked, as the page's change handler does (96-map/95-clicks.js).
|
||||
const name=b.select||b.act,args=b.select?{...(b.args||{}),v:value===undefined?undefined:String(value)}:b.args;
|
||||
if(b.select&&!b.options.some(o=>o.value===args.v))apiFail(`"${b.label}" is a list: click it with a value, one of ${b.options.map(o=>JSON.stringify(o.value)).join(', ')}.`);
|
||||
const kind=apiAllowed(name,`"${b.label}" runs ${name}, which is not an action.`);
|
||||
if(kind==='game'){const w=apiWaiting(name);if(w)return {clicked:b.label,...w};}
|
||||
return {clicked:b.label,...apiDispatch(name,kind,apiSpec(name),args,false)};}
|
||||
67
src/agent/70-time.js
Normal file
67
src/agent/70-time.js
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
/* ================= AGENT API: time =================
|
||||
Two clocks, in the MCP server's own page and in the player's tab alike. The agent's clock: nothing moves until a tool
|
||||
asks for days with advance. A running clock: days pass at a fixed pace whatever the tool does, and the tool can only
|
||||
wait and react. In the player's tab the player picks one in Settings (apiAgentMs(), 0 for the agent's clock); the MCP
|
||||
server's own page is told by the server (API_CLK). */
|
||||
let API_CLK={mode:'agent',paceMs:0,running:false};
|
||||
const apiClockNow=()=>API_CTX.relay?(apiAgentMs()>0?{mode:'realtime',paceMs:apiAgentMs(),running:!!UI.speed}:{mode:'agent',paceMs:0,running:false}):API_CLK;
|
||||
function apiMode(){const c=apiClockNow();
|
||||
return {backend:API_CTX.relay?'browser':'headless',clock:c.mode,...(c.mode==='realtime'?{paceMs:c.paceMs}:{}),
|
||||
...(API_CTX.relay?{withheld:API_WITHHELD,playerOwns:Object.keys(API_PLAYER_OWNS)}:{})};}
|
||||
function apiClockDoc(){const c=apiClockNow();
|
||||
return c.mode==='agent'?'Time moves only with advance: one dayTick() per simulated day, as the game loop runs it. Nothing runs between calls.'
|
||||
:`The clock runs on its own: one simulated day every ${apiR1(c.paceMs/1000)} s of real time, behind open windows too, and no tool can stop it${API_CTX.relay?' (it holds while no tool is connected)':''}. advance is not available; wait returns once days have passed.`;}
|
||||
function apiClock(){const c=apiClockNow();
|
||||
return {mode:c.mode,paceMs:c.paceMs||undefined,running:c.mode==='realtime'?!!c.running:false,
|
||||
day:S?S.day:null,date:S?dateStr(S.day):null,cash:S?S.cash:null,lost:!!(S&&S.lost),incidents:S?S.inc.map(i=>i.id):[],question:!!apiDecision()};}
|
||||
|
||||
// What happened since a moment (the start of an advance, or a clock reading before wait): the log, new incidents, cash.
|
||||
// The log keeps what mattered; toasts that only repeat a log line are left out.
|
||||
function apiSince({day=0,cash=0,inc=[]}={},toasts=[]){
|
||||
const seen=new Set(inc),entries=(S.log||[]).filter(e=>e.d>day).slice(-60),logged=entries.map(e=>apiNorm(apiText(e.t,400)));
|
||||
const d=apiDecision();
|
||||
return {from:dateStr(day),to:dateStr(S.day),daysRun:S.day-day,cash:Math.round(S.cash),cashChange:Math.round(S.cash-cash),
|
||||
newIncidents:S.inc.filter(i=>!seen.has(i.id)).map(apiIncText),
|
||||
log:entries.map(e=>`${dateStr(e.d)}: ${apiText(e.t,400)}`),
|
||||
toasts:[...new Set(apiToastLines(toasts))].filter(t=>{const f=apiNorm(t.replace(/^\w+: /,'').split('\n')[0]);return !logged.some(l=>l.startsWith(f));}).slice(-40),
|
||||
...(d?{decision:d,screen:apiScreen()}:{})};}
|
||||
|
||||
function apiAdvanceStart(days){
|
||||
if(!S)apiFail('No game is running.');
|
||||
const c=apiClockNow();
|
||||
if(c.mode!=='agent')apiFail(`The clock runs on its own here, one day every ${apiR1(c.paceMs/1000)} s: use wait to let days pass.`);
|
||||
if(apiModalOpen()&&!apiPlayerWin())apiFail('A window is open. Answer it first (screen, click, or act closeModal), the game does not run days behind it.');
|
||||
API_SHEET=null;
|
||||
apiTake();
|
||||
return {days:Math.max(1,Math.min(3650,Math.floor(+days)||1)),start:S.day,cash:S.cash,inc:S.inc.map(i=>i.id),times:[],ran:0,stop:null};}
|
||||
// One day of the run; false once it is over.
|
||||
function apiAdvanceDay(a){
|
||||
if(a.ran>=a.days)return false;
|
||||
if(S.lost){a.stop='bankrupt';return false;}
|
||||
const t=performance.now();
|
||||
dayTick();
|
||||
a.times.push({day:S.day,ms:apiR1(performance.now()-t)});a.ran++;
|
||||
if(apiModalOpen()&&!apiPlayerWin()){a.stop='a window opened';return false;}
|
||||
return a.ran<a.days;}
|
||||
function apiAdvanceEnd(a){
|
||||
renderAll();
|
||||
const total=a.times.reduce((x,t)=>x+t.ms,0),out=apiSince({day:a.start,cash:a.cash,inc:a.inc},apiTake());
|
||||
if(a.stop!=='a window opened'){delete out.decision;delete out.screen;}
|
||||
return {from:out.from,to:out.to,daysRun:a.ran,stoppedBecause:a.stop,cash:out.cash,cashChange:out.cashChange,newIncidents:out.newIncidents,log:out.log,toasts:out.toasts,
|
||||
timing:{totalMs:apiR1(total),perDayMs:apiR1(total/(a.ran||1)),slowestDays:a.times.slice().sort((x,y)=>y.ms-x.ms).slice(0,5).map(x=>({date:dateStr(x.day),ms:x.ms}))},
|
||||
...(out.decision?{decision:out.decision,screen:out.screen}:{})};}
|
||||
function apiAdvance(days){const a=apiAdvanceStart(days);while(apiAdvanceDay(a));return apiAdvanceEnd(a);}
|
||||
/* In the player's tab the days run where the player can watch them: a frame's worth of days, then the page draws.
|
||||
A hidden tab draws nothing (and its timers are throttled), so there they run straight through. A day the route
|
||||
worker is still routing finishes first. */
|
||||
const apiSleep=ms=>new Promise(r=>setTimeout(r,ms));
|
||||
async function apiAdvanceLive(days){
|
||||
const a=apiAdvanceStart(days);let t=performance.now();
|
||||
for(;;){
|
||||
while(RW.job)await apiSleep(20);
|
||||
if(!apiAdvanceDay(a))break;
|
||||
if(document.visibilityState!=='hidden'&&performance.now()-t>30){renderHUD();UI.panelsDue=true;await apiSleep(0);t=performance.now();}}
|
||||
return apiAdvanceEnd(a);}
|
||||
|
||||
// One day of a running clock in the MCP server's own page (the server keeps the time); the player's tab runs its own loop.
|
||||
function apiTick(){if(!S||S.lost||pzOn()||!rule('clock'))return false;dayTick();renderAll();return true;}
|
||||
86
src/agent/75-mode.js
Normal file
86
src/agent/75-mode.js
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
/* ================= AGENT MODE: the player's switch and clock =================
|
||||
In the player's own tab (the development page, served locally), the player can let an agent drive: the page dials
|
||||
the agent relay (80-relay.js) and answers tool calls through TUBES.call. While it does, the clock is not the
|
||||
player's (UI.clockLocked): either a fixed pace, one simulated day every 30 s to 5 min, that nobody can pause and
|
||||
that holds while no tool is connected; or the agent's clock, which stands still until the agent asks for days.
|
||||
The game itself knows none of this: it calls HOOKS (50-state.js), which this file fills in, and reads
|
||||
UI.clockLocked. Settings of its own, in their own storage key, so the game's preferences stay as they are. */
|
||||
const API_AGENT_MS=[0,30000,60000,120000,300000],API_AGENT_KEY='sot-agent';
|
||||
const API_AGENT_PREFS=(()=>{let j={};try{j=JSON.parse(localStorage.getItem(API_AGENT_KEY)||'{}')||{};}catch(e){}
|
||||
return {on:j.on===true,ms:API_AGENT_MS.includes(j.ms)?j.ms:60000};})();
|
||||
/* Only where a relay can be: plain http (an https page cannot open ws://) to an address, never a DNS name, which the
|
||||
relay refuses (DNS rebinding). The public site is https and a name, so it never shows the switch. The test
|
||||
harness's made-up origin opts in, and a test page loaded from the public address does not. */
|
||||
const apiAgentLocal=(p,h)=>p==='http:'&&(h==='localhost'||/\.localhost$/.test(h)||/^\[[0-9a-f:.]+\]$/i.test(h)||/^\d{1,3}(\.\d{1,3}){3}$/.test(h));
|
||||
const API_AGENT_OK=apiAgentLocal(location.protocol,location.hostname)||!!window.__TUBES_TEST__&&location.hostname==='tests.invalid';
|
||||
const apiAgentMs=()=>API_AGENT_PREFS.ms;
|
||||
const apiMsLabel=ms=>ms>=60000?tr('settings.n_min',{n:Math.round(ms/60000)}):tr('settings.n_sec',{n:Math.round(ms/1000)});
|
||||
const apiAgentMsLabel=()=>apiAgentMs()>0?apiMsLabel(apiAgentMs()):tr('settings.agent_s_clock');
|
||||
|
||||
/* The speed a locked clock runs at: the pace while a tool is connected, else held (0); always 0 on the agent's clock,
|
||||
where only advance moves days; and only in a game with a clock (the rule the pause buttons follow). */
|
||||
function apiAgentSpeed(){const r=API_RELAY;return r.on&&r.tools>0&&apiAgentMs()>0&&S&&rule('clock')?DAY_MS/apiAgentMs():0;}
|
||||
|
||||
// k: 'on' (true/false) or 'ms' (one of API_AGENT_MS). Anything else is ignored, never coerced.
|
||||
function apiAgentSet(k,v){
|
||||
if(k==='on')API_AGENT_PREFS.on=v===true||v==='1'||v===1;
|
||||
else if(k==='ms'){if(!API_AGENT_MS.includes(+v))return;API_AGENT_PREFS.ms=+v;}
|
||||
else return;
|
||||
try{localStorage.setItem(API_AGENT_KEY,JSON.stringify(API_AGENT_PREFS));}catch(e){}
|
||||
apiAgentSync();}
|
||||
|
||||
/* Locks or frees the clock to match the switch, and keeps the speed where it belongs. Switching on leaves the save's
|
||||
speed alone (save() does not overwrite it while the clock is locked), so switching off puts back the one the player
|
||||
left the game at. Safe to run any number of times. */
|
||||
function apiAgentSync(){
|
||||
const on=!RW_IN&&API_AGENT_OK&&API_AGENT_PREFS.on;
|
||||
if(on!==UI.clockLocked){
|
||||
if(on&&S&&[0,0.5,1,2,4,8].includes(UI.speed))S.uiSpeed=UI.speed;
|
||||
UI.clockLocked=on;
|
||||
if(!on)UI.speed=S&&[0,0.5,1,2,4,8].includes(S.uiSpeed)?S.uiSpeed:(UI.lastSpeed||1);}
|
||||
if(on)UI.speed=apiAgentSpeed();
|
||||
apiRelaySync();
|
||||
apiTickerSync();
|
||||
renderHUD();renderTabbar();}
|
||||
|
||||
/* What the game draws for a locked clock: the badge in the HUD in place of the speed buttons, and on phones the two
|
||||
tab bar slots of play and speed, disabled, the second one reading the pace. */
|
||||
function apiAgentHud(){
|
||||
const p=$('spPace');if(!p)return;
|
||||
p.hidden=!UI.clockLocked;
|
||||
if(UI.clockLocked)p.textContent=apiAgentMs()>0?tr('settings.pace_t_per_day',{t:apiAgentMsLabel()}):apiAgentMsLabel();}
|
||||
function apiAgentTabbar(){
|
||||
return `<button class="play${UI.speed?'':' paused'}" disabled aria-label="${UI.speed?tr('common.pause'):tr('common.play')}"><span class="ic" aria-hidden="true">${UI.speed?'❚❚':'▶'}</span>${UI.speed?tr('common.pause'):tr('common.play')}</button>`+
|
||||
`<button class="pace" disabled aria-label="${tr('common.game_speed')}"><span class="ic" aria-hidden="true">${apiAgentMs()>0?apiAgentMsLabel():'🤖'}</span>${tr('common.speed')}</button>`;}
|
||||
|
||||
/* The Settings section. Its buttons are the agent's own (data-agent-set, answered below), not game actions, so no
|
||||
tool can find them on a screen and switch the agent off, or on. */
|
||||
function apiAgentSettings(){
|
||||
if(!API_AGENT_OK)return '';
|
||||
const b=(v,l,on)=>`<button class="b ${on?'pink sm':'ghost sm'}" data-agent-set="${v}">${l}</button>`;
|
||||
const line=(lab,btns,note)=>`<div class="setline"><span>${lab}</span><div class="seg">${btns}</div></div><p class="meta" style="margin:0 0 6px">${note}</p>`;
|
||||
return `<h3 class="sub4">${tr('settings.agent_api')}</h3>`+
|
||||
line(tr('settings.let_an_ai_agent_drive_this_game'),b('on:1',tr('common.on'),API_AGENT_PREFS.on)+b('on:0',tr('common.off'),!API_AGENT_PREFS.on),tr('settings.while_agent_mode_is_on_the'))+
|
||||
line(tr('settings.the_clock_while_an_agent_plays'),API_AGENT_MS.map(m=>b('ms:'+m,m?apiMsLabel(m):tr('settings.the_agent_moves_it'),apiAgentMs()===m)).join(''),tr('settings.a_pace_runs_one_simulated_day'));}
|
||||
function apiAgentClick(e){
|
||||
const el=e.target&&e.target.closest&&e.target.closest('[data-agent-set]');if(!el||el.disabled)return;
|
||||
const [k,v]=String(el.dataset.agentSet).split(':');
|
||||
apiAgentSet(k,k==='on'?v==='1':v);sfx('click');refreshSettings();}
|
||||
|
||||
/* Who opened the window on screen: the player (a click, a key, a picker: window.event is the input being handled), or
|
||||
the game itself (a day, a tool's call inside a relay message). A tool leaves the player's windows alone. */
|
||||
const API_MODAL={hand:false};
|
||||
const apiByHand=()=>{const e=window.event;return !!e&&/^(click|keydown|keyup|pointerup|touchend|change|input|submit)$/.test(e.type);};
|
||||
|
||||
// Wires agent mode into the page: the hooks, the badge and its style, the Settings buttons. Once, at load.
|
||||
function apiAgentStart(){
|
||||
if(RW_IN)return;
|
||||
Object.assign(HOOKS,{speed:apiAgentSpeed,hud:apiAgentHud,tabbar:apiAgentTabbar,settings:apiAgentSettings,modal:open=>{API_MODAL.hand=open&&apiByHand();}});
|
||||
const sp8=$('sp8');
|
||||
if(sp8&&!$('spPace')){const p=document.createElement('span');p.id='spPace';p.hidden=true;sp8.after(p);}
|
||||
const st=document.createElement('style');
|
||||
st.textContent='.speed #spPace[hidden]{display:none}#spPace{border:2.5px solid var(--ink);background:var(--sun);border-radius:9px;height:32px;padding:0 8px;display:flex;align-items:center;font-family:var(--display);font-weight:800;font-size:12.5px;white-space:nowrap}'+
|
||||
'#tabbar button.pace .ic{font-size:13px;line-height:1.25}';
|
||||
document.head.appendChild(st);
|
||||
document.addEventListener('click',apiAgentClick);
|
||||
apiAgentSync();}
|
||||
77
src/agent/80-relay.js
Normal file
77
src/agent/80-relay.js
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
/* ================= AGENT RELAY: the in-page transport =================
|
||||
With agent mode on (75-mode.js), the page dials the agent relay (scripts/agent/relay.js, which npm run dev hosts on
|
||||
its own port) and answers tool calls from connected tools (the MCP server, node scripts/mcp.js --browser) through
|
||||
TUBES.call, so a human follows along on the real UI: toasts fire, panels render, the map moves.
|
||||
|
||||
No endpoint to configure and no token: the relay rides the server that served the page, same port, path
|
||||
API_RELAY_PATH, so the endpoint is where the page already is. The relay refuses a page from any other origin and a
|
||||
Host that is a name, so no website can reach it through the player's browser; who else can reach it is the
|
||||
operator's choice of bind address. No eval ever: a message is JSON with a tool name from TUBES.tools, a fixed list,
|
||||
answered as the relay (ctx.relay): the player's game, clock, windows and settings stay theirs, and the dice stay
|
||||
hidden. Nothing dials or polls while the switch is off.
|
||||
|
||||
API_RELAY_HOST is a var because tests point it at their relay (under __TUBES_TEST__ nothing dials unless the test
|
||||
opts in with __AGENT_RELAY_TEST__): a jsdom page is not loaded from the relay's server. */
|
||||
var API_RELAY_HOST=''; // tests: '127.0.0.1:<port>'; live pages use their own host
|
||||
const API_RELAY={ws:null,on:false,timer:null,tries:0,said:false,tools:0,host:null,queue:null};
|
||||
const API_RELAY_PATH='/agent';
|
||||
const apiRelayUrl=()=>`ws://${API_RELAY_HOST||location.host}${API_RELAY_PATH}`;
|
||||
|
||||
/* The relay reports tool presence on every connect and disconnect: the clock holds while no tool is connected and
|
||||
runs again the moment one arrives. A missing relay (dial failed, retry backoff) holds it too. */
|
||||
function apiRelayPresence(tools){
|
||||
API_RELAY.tools=tools|0;
|
||||
if(!UI.clockLocked||!API_RELAY.on)return;
|
||||
const run=apiAgentSpeed();
|
||||
if(run!==UI.speed){UI.speed=run;renderHUD();}}
|
||||
|
||||
function apiRelaySync(){
|
||||
const want=!RW_IN&&UI.clockLocked&&(!window.__TUBES_TEST__||!!window.__AGENT_RELAY_TEST__);
|
||||
// Nothing to do when the switch and the endpoint stand: tearing a healthy dial down for nothing drops the calls in
|
||||
// flight and holds the clock for no reason.
|
||||
if(API_RELAY_HOST===API_RELAY.host&&API_RELAY.on===want&&(want?!!(API_RELAY.ws||API_RELAY.timer):true))return;
|
||||
clearTimeout(API_RELAY.timer);API_RELAY.timer=null;API_RELAY.tries=0;
|
||||
if(API_RELAY.ws){const w=API_RELAY.ws;API_RELAY.ws=null;try{w.close();}catch(e){}}
|
||||
API_RELAY.on=want;API_RELAY.host=API_RELAY_HOST;
|
||||
apiRelayPresence(0); // off the relay: nobody driving, the clock holds
|
||||
if(want)apiRelayDial();}
|
||||
|
||||
// Dev reloads and relay restarts heal on their own, without a spinning reconnect.
|
||||
function apiRelayRetry(){
|
||||
if(!API_RELAY.on)return;
|
||||
const wait=Math.min(15000,500*Math.pow(2,Math.min(API_RELAY.tries++,5)));
|
||||
API_RELAY.timer=setTimeout(()=>{API_RELAY.timer=null;apiRelayDial();},wait);}
|
||||
|
||||
/* One call, answered in order: calls queue behind each other, so a move sent while days are still running waits for
|
||||
them, as the tool sent it. A promise (days the player watches) is awaited; a throw is the tool's error. */
|
||||
function apiRelayAnswer(ws,m){
|
||||
const dayBefore=S?S.day:null,send=o=>{if(API_RELAY.ws===ws)ws.send(JSON.stringify({kind:'result',id:m.id,dayBefore,dayAfter:S?S.day:null,...o}));};
|
||||
const run=()=>Promise.resolve().then(()=>TUBES.call(m.tool,m.args||{},{relay:true}))
|
||||
.then(value=>send({value}),er=>send({error:String(er&&er.message||er)}));
|
||||
API_RELAY.queue=(API_RELAY.queue||Promise.resolve()).then(run);}
|
||||
|
||||
function apiRelayDial(){
|
||||
if(!API_RELAY.on)return;
|
||||
let ws;
|
||||
try{ws=new WebSocket(apiRelayUrl());}catch(e){return apiRelayRetry();}
|
||||
API_RELAY.ws=ws;
|
||||
ws.onopen=()=>{
|
||||
if(API_RELAY.ws!==ws)return;
|
||||
ws.send(JSON.stringify({kind:'auth',role:'page'}));
|
||||
API_RELAY.tries=0;
|
||||
if(!API_RELAY.said){API_RELAY.said=true;toast(tr('settings.agent_relay_connected'),'good');}};
|
||||
ws.onmessage=e=>{
|
||||
if(API_RELAY.ws!==ws)return;
|
||||
let m;try{m=JSON.parse(e.data);}catch(_){return;}
|
||||
if(!m||typeof m!=='object')return;
|
||||
if(m.kind==='presence'){apiRelayPresence(m.tools);return;}
|
||||
if(m.kind!=='call'||m.id===undefined)return;
|
||||
// A call this page cannot make sense of is answered, never ignored: a silent drop would hang the tool that sent it.
|
||||
if(typeof m.tool!=='string'||!TUBES.tools.includes(m.tool)){ws.send(JSON.stringify({kind:'result',id:m.id,error:`no tool "${m.tool}" here`}));return;}
|
||||
apiRelayAnswer(ws,m);};
|
||||
// Replaced (4000): another tab took the relay, so this one yields instead of fighting it: redialing would just
|
||||
// replace the new tab back, forever. Toggling agent mode dials again.
|
||||
ws.onclose=e=>{if(API_RELAY.ws!==ws)return;API_RELAY.ws=null;
|
||||
apiRelayPresence(0); // off the relay: the clock holds
|
||||
if(e&&e.code===4000)API_RELAY.on=false;else apiRelayRetry();};
|
||||
ws.onerror=()=>{};}
|
||||
24
src/agent/85-ticker.js
Normal file
24
src/agent/85-ticker.js
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
/* ================= AGENT MODE: the clock where frames do not run =================
|
||||
A paced clock runs through the game's own loop (UI.speed is the pace, runClock() the days), but frames stop in a
|
||||
hidden tab, and the frame runs no days behind an open window. Agent mode keeps time in both: a hidden tab is the
|
||||
normal place for an agent to drive while the player does something else, and an agent that deliberates over a
|
||||
window pays for it in days. This ticker covers exactly those moments, under the frame's other conditions, and
|
||||
leaves every other moment to the frame. Hidden-tab timers are throttled (to 1 Hz, after five minutes to once a
|
||||
minute in Chrome), so an unthrottled worker posts the ticks; a plain interval is the fallback without Worker.
|
||||
The agent's clock (pace 0) needs no ticks: its days run when the agent asks. Never under __TUBES_TEST__: tests call
|
||||
apiAgentTick() by hand. */
|
||||
const API_TICKER={on:false,worker:null,interval:null,last:0};
|
||||
// Days for the time since the last tick, if the frame is not running them now.
|
||||
function apiAgentTick(now=performance.now()){
|
||||
const dt=API_TICKER.last?Math.max(0,Math.min(1000,now-API_TICKER.last)):0;API_TICKER.last=now;
|
||||
const behind=document.visibilityState==='hidden'||!$('modal').hidden;
|
||||
if(behind&&UI.clockLocked&&S&&!S.lost&&UI.speed&&!pzOn())runClock(dt);}
|
||||
function apiTickerSync(){
|
||||
const want=UI.clockLocked&&apiAgentMs()>0&&!window.__TUBES_TEST__;
|
||||
if(want===API_TICKER.on)return;API_TICKER.on=want;API_TICKER.last=0;
|
||||
if(!want){if(API_TICKER.worker){try{API_TICKER.worker.terminate();}catch(e){}API_TICKER.worker=null;}
|
||||
if(API_TICKER.interval){clearInterval(API_TICKER.interval);API_TICKER.interval=null;}return;}
|
||||
try{const url=URL.createObjectURL(new Blob(['setInterval(()=>postMessage(0),250)'],{type:'text/javascript'}));
|
||||
API_TICKER.worker=new Worker(url);URL.revokeObjectURL(url);
|
||||
API_TICKER.worker.onmessage=()=>apiAgentTick();}
|
||||
catch(e){API_TICKER.interval=setInterval(()=>apiAgentTick(),250);}}
|
||||
54
src/agent/90-facade.js
Normal file
54
src/agent/90-facade.js
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
/* ================= AGENT API: the facade =================
|
||||
window.TUBES.call(tool, args) is the whole surface: one tool from API_TOOLS by name, with the MCP tool's own
|
||||
arguments, answered as plain JSON (or a promise of it, for days that run where the player can watch). Nothing here
|
||||
listens, polls or runs on the day loop: toast() is only listened to while a call runs.
|
||||
ctx.relay: the call came over the relay into the player's tab (80-relay.js), where the player owns the game, its
|
||||
clock and their windows, and the dice stay hidden. */
|
||||
let API_CTX={relay:false};
|
||||
const API_TOASTS={depth:0,list:[],real:null};
|
||||
function apiTake(){const t=API_TOASTS.list;API_TOASTS.list=[];return t;}
|
||||
const apiToastLines=t=>t.map(x=>(x.kind?x.kind+': ':'')+x.text);
|
||||
// toast() is a top-level function, so the game reaches it by its global name and this stands in for it.
|
||||
function apiListen(on){
|
||||
if(on){if(API_TOASTS.depth++)return;const real=API_TOASTS.real=window.toast;API_TOASTS.list=[];
|
||||
window.toast=function(h,kind){API_TOASTS.list.push({kind:kind||'',text:apiText(String(h),600)});return real.apply(this,arguments);};}
|
||||
else if(!--API_TOASTS.depth){window.toast=API_TOASTS.real;API_TOASTS.real=null;API_TOASTS.list=[];}}
|
||||
|
||||
const API_TOOLS={
|
||||
status:()=>apiStatus(),
|
||||
network:a=>apiNetwork(a.network),
|
||||
city:a=>apiCity(a.city),
|
||||
find:a=>apiFind(a.query,a.kind),
|
||||
traceroute:a=>apiTrace(a.from,a.to),
|
||||
peering_check:a=>apiPeering(a.network,a.city,a.via),
|
||||
hot_spots:a=>apiHotSpots(a.limit||10),
|
||||
schema:a=>apiSchema(a.section),
|
||||
catalog:a=>apiCatalog(a.name),
|
||||
state:a=>apiState(a.path),
|
||||
results:a=>apiResults(a.path),
|
||||
ui:()=>apiUi(),
|
||||
actions:()=>apiActions(),
|
||||
classes:()=>apiClasses(),
|
||||
act:a=>{const name=a.action||a.command;if(!name)apiFail('Give action, e.g. {"action":"buildPop","args":{"city":"ams"}}.');
|
||||
return apiRun(name,a.args||{},{dryRun:!!a.dryRun});},
|
||||
screen:a=>apiScreen(a.where,a.offset),
|
||||
panel:a=>apiPanel(a),
|
||||
click:a=>apiClick(a.button,a.value),
|
||||
open_link:a=>apiOpenLink(a.from,a.to),
|
||||
advance:a=>API_CTX.relay?apiAdvanceLive(a.days):apiAdvance(a.days),
|
||||
clock:()=>apiClock(),
|
||||
since:a=>apiSince(a),
|
||||
};
|
||||
function apiCall(tool,args,ctx){
|
||||
if(typeof tool!=='string'||!own(API_TOOLS,tool))apiFail(`No tool "${tool}".`);
|
||||
if(!S&&!['schema','catalog','classes','actions','clock'].includes(tool))apiFail('No game is running.');
|
||||
const was=API_CTX;API_CTX={relay:!!(ctx&&ctx.relay)};
|
||||
apiListen(true);
|
||||
let out;
|
||||
try{out=API_TOOLS[tool](args&&typeof args==='object'&&!Array.isArray(args)?args:{});}
|
||||
catch(e){apiListen(false);throw e;}
|
||||
finally{API_CTX=was;}
|
||||
if(out&&typeof out.then==='function')return out.finally(()=>apiListen(false));
|
||||
apiListen(false);
|
||||
return out;}
|
||||
window.TUBES={version:1,tools:Object.keys(API_TOOLS),call:apiCall};
|
||||
4
src/agent/99-start.js
Normal file
4
src/agent/99-start.js
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
/* ================= AGENT API: start =================
|
||||
Last, once every file of the facade has loaded: agent mode wires itself in (75-mode.js). Everything before this only
|
||||
defines tables and functions. */
|
||||
apiAgentStart();
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue