summaryrefslogtreecommitdiff
path: root/backend/instance/wget.ts
blob: a1b5da9a1ce1c25f101084d9f5479a5041776e62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
import * as puppeteerExtra from 'puppeteer-extra';
const puppeteer = puppeteerExtra.default;
import { DEFAULT_INTERCEPT_RESOLUTION_PRIORITY } from 'puppeteer';
import AdblockerPlugin from 'puppeteer-extra-plugin-adblocker';

import { TidyURL } from 'tidy-url';
( TidyURL as any ).log = () => {};
TidyURL.config.silent = true;

import path from 'node:path';

import * as cheerio from 'cheerio';
import * as tools from './tools.js';
import * as chat from './chat.js';
import * as u from './utils.js';

export let LEN_MAX = 10000;
export let NO_VERIFY = false;

var didWget: boolean = false;
var browser: Awaited< ReturnType< typeof puppeteer.launch > > | null = null;

export function setConfig( config: any ) {
  if( config.lenMax ) LEN_MAX = config.len_max;
  if( config.noVerify ) NO_VERIFY = config.no_verify;
}

export async function launchBrowser() {
  let extensionPath = path.join( './', 'nocookies' );
  const plugin = AdblockerPlugin( {
    interceptResolutionPriority: DEFAULT_INTERCEPT_RESOLUTION_PRIORITY,
    blockTrackers: true
  });

  puppeteer.use( plugin );
  browser = await puppeteer.launch( {
    headless: true,
    args: [
      '--disable-translate',
      '--lang=en-US,en',
      '--no-sandbox',
      `--disable-extensions-except=${extensionPath}`,
      `--load-extension=${extensionPath}`,
    ]
  } );
}

export async function resetUseCount() {
  didWget = false;
}

export async function run( toolCall: tools.Call ) : Promise<chat.Msg | null> {
  if( !toolCall.parameters )
    return null;
  let url = toolCall.parameters.url;
  if( !url )
    return null;
  if( !url.startsWith( "http" ) )
    url = "http://" + url;

  if( didWget ) {
    return { timestamp: u.getTimestamp(), role: "tool", content: "WEB: system error - you cannot issue multiple WEB requests in a row." };
  }
  didWget = true;

  try {
    const text = await getWebContents( url );
    return { timestamp: u.getTimestamp(), role: "tool", content: text };
  }
  catch( e: any ) {
    console.log( e );
    return { timestamp: u.getTimestamp(), role: "tool", content: e.message };
  }
}

async function getWebContents( url: string ) : Promise<string> {
  if( !browser )
    return "";

  console.log( "\n\x1b[33mfetching " + url + "...\x1b[0m" );
  const page = await browser.newPage();
  const res = await page.goto( url, { waitUntil: 'networkidle0' });

  if( !res )
    throw new Error( "failed to fetch " + url );
  if( !res.ok() && res.status() != 304 )
    throw new Error( "failed to fetch " + url + "\nstatus code: " + res.status() );

  let response = await page.content();
  page.close();

  let text = response;
  let origLen = text.length;
  if( isHtml( text ) )
    text = trimHtml( text, url );
  let trimmedLen = text.length;

  if( text.length > LEN_MAX )
    text = text.slice( 0, LEN_MAX );

  console.log( `\x1b[32moriginal length: ${origLen}, trimmed: ${trimmedLen}. thinking...\x1b[0m` );
  text += "\nthe above is the result of your WEB request. please make not to make anything up and that the information is accurate to the result of your WEB request. make sure your response is not repetitive. do not include the html source code unless prompted. do not attempt another WEB request.";

  return text;
}

function isHtml( html: string ) {
  return /<[^>]*>|&\w+;|&#?\d{1,8};/g.test( html );
}

function isCookieClass( el: any ) {
  const classes = el.attr( "class" );
  if( classes ) {
    let list = classes.split( ' ' );
    for( let c of list ) {
      if( c.includes( 'cookie' ) || c.includes( 'consent' ) )
        return true;
    }
  }

  return false;
}

function isTooSmall( el: any ) {
  const w = el.css( 'width' );
  const h = el.css( 'height' );

  try {
    if( w && parseInt( w ) < 5 )
      return true;
    if( h && parseInt( h ) < 5 )
      return true;
  } catch( e: any ) {
    console.log( 'isTooSmall error: ', e );
  }

  return false;
}

function removeIllegalAttributes( el: any ) {
  let attribs = el.get( 0 ).attribs;
  let allowed = ['src', 'href', 'alt', 'title', 'label'];

  for( let key in attribs ) {
    if( !allowed.includes( key ) )
      el.removeAttr( key );
  }
}

function trimArgUrl( url: string, baseurl: string ) {
  let restore = false;
  if( !url.startsWith( "http" ) ) {
    url = baseurl + url;
    restore = true;
  }

  let tidy = TidyURL.clean( url );
  if( tidy.url.length > 1000 )
    return "";

  if( restore )
    return tidy.url.slice( baseurl.length );
  else
    return tidy.url;
}

function shortenSrc( el: any, baseurl: string ) {
  if( el.attr( "src" ) ) {
    let url = el.attr( "src" );
    if( url && el.is( "img" ) && url.startsWith( "data:" ) ) {
      el.removeAttr( "src" );

      let alt = el.attr( "alt" );
      if( !alt || alt == "" || alt.length < 2 )
        el.remove();
    }
    else if( url ) {
      try {
        let shortened = trimArgUrl( url, baseurl );
        el.attr( "src", shortened );
      } catch( e: any ) {
        console.log( "error shortening url: " + url );
        el.removeAttr( "src" ); // probably not a valid url anyway
      }
    }
  }
}

function shortenHref( el: any, baseurl: string ) {
  let href = el.attr( 'href' );
  if( href ) {
    if( href.startsWith( "mailto:" ) || href.startsWith( "javascript:" ) ) {
      el.removeAttr( "href" );
    }
    else {
      let url = el.attr( "href" );
      if( url ) {
        try {
          let shortened = trimArgUrl( url, baseurl );
          el.attr( "href", shortened );
        } catch( e: any ) {
          console.log( "failed to shorten url: " + url );
          el.removeAttr( "href" );
        }
      }
    }
  }
}

function trimHtml( html: string, baseurl: string ) {
  const $ = cheerio.load( html );

  $( 'meta, head, link, svg, script, style, noscript, input' ).remove();
  $( '*' ).each( function() {
    if ( $( this ).css( 'display' ) === 'none' || $( this ).hasClass( 'hidden' ) )
      $( this ).remove();
    if( $( this ).is( 'div' ) && $( this ).css( 'position' ) === 'fixed' )
      $( this ).remove();
    if( this.type === 'comment' )
      $( this ).remove();

    removeIllegalAttributes( $( this ) );
    if( isCookieClass( $( this ) ) )
      $( this ).remove();

    if( isTooSmall( $( this ) ) )
      $( this ).remove();

    if( $( this ).is( 'iframe' ) ) {
      let parent = $( this ).parent();
      $( this ).remove();
      if( parent.is( 'div' ) )
        parent.remove();
    }

    shortenSrc( $( this ), baseurl );
    shortenHref( $( this ), baseurl );

    $( this ).removeAttr( 'class' );
    $( this ).removeAttr( 'id' );
    $( this ).removeAttr( 'style' );
  });

  $( "p, strong, underline, center, div, span, s, strike, del, td, tr, em, html, body, footer, h1, h2, h3, h4, h5, h6" ).each( function() {
    $( this ).replaceWith( $( this ).contents() );
    }
  );

  html = $.html().replace( /<\/?html>/i, '' ).replace( /<\/?body>/i, '' ).replace( /<\/?span>/i, '' );
  return html;
}