@chosengeneration/light-code 0.202.0 → 0.204.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.cjs +332 -79
  2. package/dist/server.cjs +329 -76
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -3278,7 +3278,7 @@ var require_util2 = __commonJS({
3278
3278
  }
3279
3279
  break;
3280
3280
  case "same-origin":
3281
- if (!sameOrigin(request2, requestCurrentURL(request2))) {
3281
+ if (!sameOrigin2(request2, requestCurrentURL(request2))) {
3282
3282
  serializedOrigin = null;
3283
3283
  }
3284
3284
  break;
@@ -3335,7 +3335,7 @@ var require_util2 = __commonJS({
3335
3335
  if (referrerURL.toString().length > 4096) {
3336
3336
  referrerURL = referrerOrigin;
3337
3337
  }
3338
- const areSameOrigin = sameOrigin(request2, referrerURL);
3338
+ const areSameOrigin = sameOrigin2(request2, referrerURL);
3339
3339
  const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(request2.url);
3340
3340
  switch (policy) {
3341
3341
  case "origin":
@@ -3348,7 +3348,7 @@ var require_util2 = __commonJS({
3348
3348
  return areSameOrigin ? referrerURL : referrerOrigin;
3349
3349
  case "strict-origin-when-cross-origin": {
3350
3350
  const currentURL = requestCurrentURL(request2);
3351
- if (sameOrigin(referrerURL, currentURL)) {
3351
+ if (sameOrigin2(referrerURL, currentURL)) {
3352
3352
  return referrerURL;
3353
3353
  }
3354
3354
  if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) {
@@ -3509,7 +3509,7 @@ var require_util2 = __commonJS({
3509
3509
  }
3510
3510
  function tryUpgradeRequestToAPotentiallyTrustworthyURL(request2) {
3511
3511
  }
3512
- function sameOrigin(A, B) {
3512
+ function sameOrigin2(A, B) {
3513
3513
  if (A.origin === B.origin && A.origin === "null") {
3514
3514
  return true;
3515
3515
  }
@@ -3712,7 +3712,7 @@ var require_util2 = __commonJS({
3712
3712
  isBlobLike,
3713
3713
  isURLPotentiallyTrustworthy,
3714
3714
  isValidReasonPhrase,
3715
- sameOrigin,
3715
+ sameOrigin: sameOrigin2,
3716
3716
  normalizeMethod,
3717
3717
  serializeJavascriptValueToJSONString,
3718
3718
  makeIterator,
@@ -11822,7 +11822,7 @@ var require_request2 = __commonJS({
11822
11822
  var util = require_util();
11823
11823
  var {
11824
11824
  isValidHTTPToken,
11825
- sameOrigin,
11825
+ sameOrigin: sameOrigin2,
11826
11826
  normalizeMethod,
11827
11827
  makePolicyContainer,
11828
11828
  normalizeMethodRecord
@@ -11893,7 +11893,7 @@ var require_request2 = __commonJS({
11893
11893
  }
11894
11894
  const origin = this[kRealm].settingsObject.origin;
11895
11895
  let window = "client";
11896
- if (request2.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin(request2.window, origin)) {
11896
+ if (request2.window?.constructor?.name === "EnvironmentSettingsObject" && sameOrigin2(request2.window, origin)) {
11897
11897
  window = request2.window;
11898
11898
  }
11899
11899
  if (init.window != null) {
@@ -11969,7 +11969,7 @@ var require_request2 = __commonJS({
11969
11969
  } catch (err) {
11970
11970
  throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err });
11971
11971
  }
11972
- if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) {
11972
+ if (parsedReferrer.protocol === "about:" && parsedReferrer.hostname === "client" || origin && !sameOrigin2(parsedReferrer, this[kRealm].settingsObject.baseUrl)) {
11973
11973
  request2.referrer = "client";
11974
11974
  } else {
11975
11975
  request2.referrer = parsedReferrer;
@@ -12484,7 +12484,7 @@ var require_fetch = __commonJS({
12484
12484
  coarsenedSharedCurrentTime,
12485
12485
  createDeferredPromise,
12486
12486
  isBlobLike,
12487
- sameOrigin,
12487
+ sameOrigin: sameOrigin2,
12488
12488
  isCancelled,
12489
12489
  isAborted,
12490
12490
  isErrorLike,
@@ -12763,7 +12763,7 @@ var require_fetch = __commonJS({
12763
12763
  if (
12764
12764
  // - request’s current URL’s origin is same origin with request’s origin,
12765
12765
  // and request’s response tainting is "basic"
12766
- sameOrigin(currentURL, request2.url) && request2.responseTainting === "basic" || // request’s current URL’s scheme is "data"
12766
+ sameOrigin2(currentURL, request2.url) && request2.responseTainting === "basic" || // request’s current URL’s scheme is "data"
12767
12767
  currentURL.protocol === "data:" || // - request’s mode is "navigate" or "websocket"
12768
12768
  (request2.mode === "navigate" || request2.mode === "websocket")
12769
12769
  ) {
@@ -13022,7 +13022,7 @@ var require_fetch = __commonJS({
13022
13022
  return Promise.resolve(makeNetworkError("redirect count exceeded"));
13023
13023
  }
13024
13024
  request2.redirectCount += 1;
13025
- if (request2.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin(request2, locationURL)) {
13025
+ if (request2.mode === "cors" && (locationURL.username || locationURL.password) && !sameOrigin2(request2, locationURL)) {
13026
13026
  return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"'));
13027
13027
  }
13028
13028
  if (request2.responseTainting === "cors" && (locationURL.username || locationURL.password)) {
@@ -13040,7 +13040,7 @@ var require_fetch = __commonJS({
13040
13040
  request2.headersList.delete(headerName);
13041
13041
  }
13042
13042
  }
13043
- if (!sameOrigin(requestCurrentURL(request2), locationURL)) {
13043
+ if (!sameOrigin2(requestCurrentURL(request2), locationURL)) {
13044
13044
  request2.headersList.delete("authorization");
13045
13045
  request2.headersList.delete("proxy-authorization", true);
13046
13046
  request2.headersList.delete("cookie");
@@ -67240,7 +67240,7 @@ function sseEvents(text2) {
67240
67240
  return events;
67241
67241
  }
67242
67242
  function findAnswer(responseText, contentType2, exclude) {
67243
- const notQuestion = (text2) => text2.trim().length > 0 && !text2.includes(exclude);
67243
+ const notQuestion = (text2) => text2.trim().length > 0 && text2.split(exclude).join("").replace(/[\s"'`.,:;!?()[\]{}-]/g, "").length >= 3;
67244
67244
  const events = (contentType2 ?? "").includes("event-stream") || /^data:/m.test(responseText) ? sseEvents(responseText) : void 0;
67245
67245
  if (events !== void 0 && events.length > 0) {
67246
67246
  const byPath = /* @__PURE__ */ new Map();
@@ -67293,20 +67293,37 @@ function readAnswer(responseText, spec) {
67293
67293
  }
67294
67294
 
67295
67295
  // ../../packages/core/dist/webchat/inpage.js
67296
- function watchScript(origin, marker) {
67296
+ function watchScript(origin, marker, backendUrl) {
67297
67297
  return `async () => {
67298
67298
  const ORIGIN = ${JSON.stringify(origin)}
67299
67299
  if (location.origin !== ORIGIN) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67300
67300
  const w = window
67301
- w.__lcWebChat = w.__lcWebChat || { found: [], headers: {}, ws: false, marker: undefined }
67301
+ w.__lcWebChat = w.__lcWebChat || { found: [], headers: {}, ws: false, marker: undefined, replies: [] }
67302
67302
  const state = w.__lcWebChat
67303
+ state.replies = state.replies || []
67304
+ ${backendUrl !== void 0 ? `state.watchUrl = ${JSON.stringify(backendUrl)}; state.replies = []; state.ws = false` : ""}
67303
67305
  ${marker !== void 0 ? `state.marker = ${JSON.stringify(marker)}; state.found = []; state.ws = false` : ""}
67304
67306
  if (state.installed) return { ok: true }
67305
67307
  state.installed = true
67306
67308
  const secret = /^(authorization|proxy-authorization|x-csrf-token|x-xsrf-token|csrf-token|x-auth-token|x-api-key|api-key|x-access-token|x-id-token)$|token|secret|session|auth/i
67309
+ // The chat window method: the page's own requests to the approved backend, with their replies, wherever it is.
67310
+ const toBackend = (u) => {
67311
+ if (!state.watchUrl) return false
67312
+ // Same site, same path segment by segment - except a segment that is plainly an id (a long number, long hex, a UUID),
67313
+ // which a chat app changes per conversation.
67314
+ const id = (x) => /^\\d{3,}$/.test(x) || /^[0-9a-f]{12,}$/i.test(x) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(x)
67315
+ try {
67316
+ const a = new URL(u, location.href), b = new URL(state.watchUrl)
67317
+ if (a.origin !== b.origin) return false
67318
+ const p = a.pathname.split('/'), q = b.pathname.split('/')
67319
+ return p.length === q.length && p.every((part, i) => part === q[i] || (id(part) && id(q[i])))
67320
+ } catch { return false }
67321
+ }
67322
+ // The page's sign-in headers, from its requests to its own site or to the approved backend (which may be another site).
67323
+ const keep = (headers) => { for (const [k, v] of Object.entries(headers)) if (secret.test(k)) state.headers[k.toLowerCase()] = v }
67307
67324
  const note = (url, headers) => {
67308
- try { if (new URL(url, location.href).origin !== ORIGIN) return } catch { return }
67309
- for (const [k, v] of Object.entries(headers)) if (secret.test(k)) state.headers[k.toLowerCase()] = v
67325
+ try { if (new URL(url, location.href).origin !== ORIGIN && !toBackend(url)) return } catch { return }
67326
+ keep(headers)
67310
67327
  }
67311
67328
  const plain = (h) => {
67312
67329
  const out = {}
@@ -67322,14 +67339,21 @@ function watchScript(origin, marker) {
67322
67339
  let method = (init && init.method) || (input instanceof Request ? input.method : 'GET')
67323
67340
  let headers = plain((init && init.headers) || (input instanceof Request ? input.headers : undefined))
67324
67341
  let body = init && typeof init.body === 'string' ? init.body : undefined
67342
+ const credentials = (init && init.credentials) || (input instanceof Request ? input.credentials : 'same-origin')
67325
67343
  if (body === undefined && input instanceof Request) { try { body = await input.clone().text() } catch {} }
67326
67344
  note(url, headers)
67327
67345
  const response = await origFetch.apply(this, arguments)
67328
67346
  if (state.marker && body && body.includes(state.marker)) {
67329
- const entry = { url: new URL(url, location.href).href, method: method.toUpperCase(), headers, body, status: response.status, contentType: response.headers.get('content-type') || '' }
67347
+ const entry = { url: new URL(url, location.href).href, method: method.toUpperCase(), headers, body, credentials, status: response.status, contentType: response.headers.get('content-type') || '' }
67330
67348
  state.found.push(entry)
67349
+ keep(headers)
67331
67350
  response.clone().text().then((t) => { entry.response = t.slice(0, 2000000) }).catch(() => {})
67332
67351
  }
67352
+ if (toBackend(url)) {
67353
+ const reply = { url: new URL(url, location.href).href, status: response.status, contentType: response.headers.get('content-type') || '', at: Date.now() }
67354
+ state.replies.push(reply)
67355
+ response.clone().text().then((t) => { reply.response = t.slice(0, 2000000) }).catch(() => { reply.response = '' })
67356
+ }
67333
67357
  return response
67334
67358
  }
67335
67359
  const X = XMLHttpRequest.prototype
@@ -67341,15 +67365,21 @@ function watchScript(origin, marker) {
67341
67365
  if (info) {
67342
67366
  note(info.url, info.headers)
67343
67367
  if (state.marker && typeof body === 'string' && body.includes(state.marker)) {
67344
- const entry = { url: info.url, method: info.method, headers: info.headers, body }
67368
+ const entry = { url: info.url, method: info.method, headers: info.headers, body, credentials: this.withCredentials ? 'include' : 'same-origin' }
67345
67369
  state.found.push(entry)
67370
+ keep(info.headers)
67346
67371
  this.addEventListener('loadend', () => { entry.status = this.status; entry.contentType = this.getResponseHeader('content-type') || ''; entry.response = String(this.responseText || '').slice(0, 2000000) })
67347
67372
  }
67373
+ if (toBackend(info.url)) {
67374
+ const reply = { url: info.url, at: Date.now() }
67375
+ state.replies.push(reply)
67376
+ this.addEventListener('loadend', () => { reply.status = this.status; reply.contentType = this.getResponseHeader('content-type') || ''; reply.response = String(this.responseText || '').slice(0, 2000000) })
67377
+ }
67348
67378
  }
67349
67379
  return send.apply(this, arguments)
67350
67380
  }
67351
67381
  const wsSend = WebSocket.prototype.send
67352
- WebSocket.prototype.send = function (data) { if (state.marker && typeof data === 'string' && data.includes(state.marker)) state.ws = true; return wsSend.apply(this, arguments) }
67382
+ WebSocket.prototype.send = function (data) { if (state.marker && typeof data === 'string' && data.includes(state.marker)) state.ws = true; if (state.watchUrl) state.wsSent = true; return wsSend.apply(this, arguments) }
67353
67383
  return { ok: true }
67354
67384
  }`;
67355
67385
  }
@@ -67366,8 +67396,9 @@ function askScript(setup, question) {
67366
67396
  return `async () => {
67367
67397
  const ORIGIN = ${JSON.stringify(origin)}
67368
67398
  if (location.origin !== ORIGIN) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67369
- const url = new URL(${JSON.stringify(setup.request.path)}, ORIGIN)
67370
- if (url.origin !== ORIGIN) return { ok: false, error: 'The saved backend address is not on the web chat site; nothing was sent.' }
67399
+ // The exact backend address the user approved - on the chat page's site or another (an api. address) - and no other.
67400
+ const url = new URL(${JSON.stringify(setup.backendUrl ?? new URL(setup.request.path, origin).href)})
67401
+ ${setup.backendUrl === void 0 ? "if (url.origin !== ORIGIN) return { ok: false, error: 'The saved backend address is not on the web chat site; nothing was sent.' }" : ""}
67371
67402
  const state = window.__lcWebChat || { headers: {} }
67372
67403
  const headers = Object.assign({}, ${JSON.stringify(setup.request.headers)})
67373
67404
  const missing = []
@@ -67378,16 +67409,20 @@ function askScript(setup, question) {
67378
67409
  if (missing.length > 0) return { ok: false, needsActivity: missing }
67379
67410
  let response
67380
67411
  try {
67381
- response = await fetch(url.href, { method: ${JSON.stringify(setup.request.method)}, headers, body: ${JSON.stringify(fillBody(setup, question))}, credentials: 'include', redirect: 'error' })
67412
+ // Cookies or not, as the page's own request did: a cross-site API answers its page's way and no other.
67413
+ response = await fetch(url.href, { method: ${JSON.stringify(setup.request.method)}, headers, body: ${JSON.stringify(fillBody(setup, question))}, credentials: ${JSON.stringify(setup.request.credentials ?? "include")}, redirect: 'error' })
67382
67414
  } catch (e) {
67383
67415
  return { ok: false, error: 'The request failed in the page: ' + (e && e.message ? e.message : String(e)) }
67384
67416
  }
67385
- if (response.url && new URL(response.url).origin !== ORIGIN) return { ok: false, error: 'The reply came from another site; it was not used.' }
67417
+ if (response.url && new URL(response.url).origin !== url.origin) return { ok: false, error: 'The reply came from another site than the approved backend; it was not used.' }
67386
67418
  const text = await response.text()
67387
67419
  return { ok: true, status: response.status, contentType: response.headers.get('content-type') || '', text: text.slice(0, 2000000) }
67388
67420
  }`;
67389
67421
  }
67390
67422
  function typePhraseScript(origin, marker) {
67423
+ return typeTextScript(origin, marker);
67424
+ }
67425
+ function typeTextScript(origin, text2) {
67391
67426
  return `async () => {
67392
67427
  if (location.origin !== ${JSON.stringify(origin)}) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67393
67428
  const visible = (el) => el.offsetParent !== null
@@ -67395,14 +67430,27 @@ function typePhraseScript(origin, marker) {
67395
67430
  const box = boxes.sort((a, b) => b.getBoundingClientRect().width - a.getBoundingClientRect().width)[0]
67396
67431
  if (!box) return { ok: false, error: 'No message box found on the page - paste the phrase by hand.' }
67397
67432
  box.focus()
67398
- const text = ${JSON.stringify(marker)}
67399
- if (box.isContentEditable) { document.execCommand('insertText', false, text) }
67433
+ const text = ${JSON.stringify(text2)}
67434
+ if (box.isContentEditable) { document.execCommand('selectAll', false); document.execCommand('insertText', false, text) }
67400
67435
  else {
67401
67436
  const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(box), 'value')?.set
67402
67437
  if (setter) setter.call(box, text); else box.value = text
67403
67438
  box.dispatchEvent(new Event('input', { bubbles: true }))
67404
67439
  }
67405
67440
  box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }))
67441
+ await new Promise((r) => setTimeout(r, 400))
67442
+ const still = box.isContentEditable ? (box.innerText || '').trim().length > 0 : String(box.value || '').trim().length > 0
67443
+ if (still) {
67444
+ let scope = box.parentElement
67445
+ let button
67446
+ for (let i = 0; i < 6 && scope && !button; i += 1, scope = scope.parentElement) {
67447
+ const buttons = [...scope.querySelectorAll('button, [role="button"], input[type="submit"]')].filter((b) => b.offsetParent !== null && !b.disabled)
67448
+ button = buttons.find((b) => /send|submit|ask/i.test((b.getAttribute('aria-label') || '') + ' ' + (b.title || '') + ' ' + (b.textContent || '') + ' ' + (b.type || ''))) || (buttons.length === 1 ? buttons[0] : undefined)
67449
+ }
67450
+ // An app that keeps the text after sending looks the same as one that did not send: without a button to press, carry
67451
+ // on - the wait for the reply (or for the capture) says whether it went.
67452
+ if (button) button.click()
67453
+ }
67406
67454
  return { ok: true }
67407
67455
  }`;
67408
67456
  }
@@ -67424,6 +67472,21 @@ function scriptResult(text2) {
67424
67472
  return void 0;
67425
67473
  }
67426
67474
  }
67475
+ function readRepliesScript(origin) {
67476
+ return `async () => {
67477
+ if (location.origin !== ${JSON.stringify(origin)}) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67478
+ const state = window.__lcWebChat
67479
+ if (!state) return { ok: true, replies: [], pending: 0, ws: false }
67480
+ const replies = state.replies || []
67481
+ return { ok: true, replies: replies.filter((r) => r.response !== undefined), pending: replies.filter((r) => r.response === undefined).length, ws: state.wsSent === true }
67482
+ }`;
67483
+ }
67484
+ function pageTextScript(origin) {
67485
+ return `async () => {
67486
+ if (location.origin !== ${JSON.stringify(origin)}) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67487
+ return { ok: true, text: String(document.body ? document.body.innerText : '').slice(0, 400000) }
67488
+ }`;
67489
+ }
67427
67490
 
67428
67491
  // ../../packages/core/dist/webchat/chrome.js
67429
67492
  function isChromeDevToolsServer(toolNames) {
@@ -67433,52 +67496,80 @@ function propertyNames(schema13) {
67433
67496
  const properties = schema13?.["properties"];
67434
67497
  return properties !== null && typeof properties === "object" ? Object.keys(properties) : [];
67435
67498
  }
67436
- async function runScript(chrome, source) {
67437
- const names = propertyNames(chrome.schema("evaluate_script"));
67438
- const key4 = names.includes("function") ? "function" : names.includes("expression") ? "expression" : names[0] ?? "function";
67439
- const result = await chrome.call("evaluate_script", { [key4]: source });
67440
- if (result.isError)
67441
- throw new Error(`Chrome could not run the script: ${result.text.slice(0, 400)}`);
67442
- const value = result.structured ?? scriptResult(result.text);
67443
- if (value === null || typeof value !== "object")
67444
- throw new Error(`Chrome returned something unexpected: ${result.text.slice(0, 300)}`);
67445
- return value;
67499
+ function pagesIn(text2) {
67500
+ const pages = [];
67501
+ for (const line of text2.split(/\r?\n/)) {
67502
+ const match = /^\s*(\d+)\s*:\s*(.+?)\s*$/.exec(line);
67503
+ if (match === null)
67504
+ continue;
67505
+ const rest = match[2] ?? "";
67506
+ const inBrackets = [...rest.matchAll(/\((https?:\/\/[^\s)]+)\)/g)].at(-1)?.[1];
67507
+ const url2 = inBrackets ?? /^(https?:\/\/\S+)/.exec(rest)?.[1];
67508
+ if (url2 === void 0)
67509
+ continue;
67510
+ pages.push({ id: Number(match[1]), url: url2, selected: /\[selected\]/i.test(rest) });
67511
+ }
67512
+ return pages;
67513
+ }
67514
+ function sameOrigin(url2, origin) {
67515
+ try {
67516
+ return new URL(url2).origin === origin;
67517
+ } catch {
67518
+ return false;
67519
+ }
67446
67520
  }
67447
67521
  async function selectWebChatPage(chrome, pageUrl) {
67448
67522
  const origin = new URL(pageUrl).origin;
67449
67523
  const listed = await chrome.call("list_pages", {});
67450
- if (!listed.isError) {
67451
- for (const line of listed.text.split(/\r?\n/)) {
67452
- const match = /^\s*(\d+)\s*[:.)]\s*(\S+)/.exec(line);
67453
- if (match === null)
67454
- continue;
67455
- try {
67456
- if (new URL(match[2] ?? "").origin !== origin)
67457
- continue;
67458
- } catch {
67459
- continue;
67460
- }
67461
- if (/\[selected\]/i.test(line))
67462
- return;
67524
+ const existing = listed.isError ? [] : pagesIn(listed.text).filter((page) => sameOrigin(page.url, origin));
67525
+ const chosen = existing.find((page) => page.selected) ?? existing[0];
67526
+ if (chosen !== void 0) {
67527
+ if (!chosen.selected && chrome.schema("select_page") !== void 0) {
67463
67528
  const names = propertyNames(chrome.schema("select_page"));
67464
- const key4 = names.find((name) => /idx|index|id/i.test(name)) ?? "pageIdx";
67465
- const selected = await chrome.call("select_page", { [key4]: Number(match[1]) });
67529
+ const key4 = names.includes("pageId") ? "pageId" : names.find((name) => /idx|index|id/i.test(name)) ?? "pageId";
67530
+ const selected = await chrome.call("select_page", { [key4]: chosen.id });
67466
67531
  if (selected.isError)
67467
67532
  throw new Error(`Chrome could not select the web chat tab: ${selected.text.slice(0, 300)}`);
67468
- return;
67469
67533
  }
67534
+ return chosen.id;
67470
67535
  }
67471
67536
  const opened = await chrome.call("new_page", { url: pageUrl });
67472
67537
  if (opened.isError)
67473
67538
  throw new Error(`Chrome could not open ${pageUrl}: ${opened.text.slice(0, 300)}`);
67539
+ const now = pagesIn(opened.text).filter((page) => sameOrigin(page.url, origin));
67540
+ const fresh = now.find((page) => page.selected) ?? now.at(-1);
67541
+ if (fresh !== void 0)
67542
+ return fresh.id;
67543
+ const again = await chrome.call("list_pages", {});
67544
+ const found2 = again.isError ? [] : pagesIn(again.text).filter((page) => sameOrigin(page.url, origin));
67545
+ return (found2.find((page) => page.selected) ?? found2.at(-1))?.id;
67546
+ }
67547
+ async function runScript(chrome, source, pageId) {
67548
+ const names = propertyNames(chrome.schema("evaluate_script"));
67549
+ const key4 = names.includes("function") ? "function" : names.includes("expression") ? "expression" : names[0] ?? "function";
67550
+ const args = { [key4]: source };
67551
+ if (names.includes("pageId")) {
67552
+ if (pageId === void 0)
67553
+ throw new Error("Chrome needs the web chat tab's id, and none was found in its list of tabs.");
67554
+ args["pageId"] = pageId;
67555
+ }
67556
+ if (names.includes("waitForStableDom"))
67557
+ args["waitForStableDom"] = false;
67558
+ const result = await chrome.call("evaluate_script", args);
67559
+ if (result.isError)
67560
+ throw new Error(`Chrome could not run the script: ${result.text.slice(0, 400)}`);
67561
+ const value = result.structured ?? scriptResult(result.text);
67562
+ if (value === null || typeof value !== "object")
67563
+ throw new Error(`Chrome returned something unexpected: ${result.text.slice(0, 300)}`);
67564
+ return value;
67474
67565
  }
67475
67566
  async function askWebChat(chrome, setup, question) {
67476
67567
  const origin = new URL(setup.pageUrl).origin;
67477
- await selectWebChatPage(chrome, setup.pageUrl);
67478
- const watched = await runScript(chrome, watchScript(origin, void 0));
67568
+ const pageId = await selectWebChatPage(chrome, setup.pageUrl);
67569
+ const watched = await runScript(chrome, watchScript(origin, void 0, setup.backendUrl ?? new URL(setup.request.path, origin).href), pageId);
67479
67570
  if (watched["ok"] !== true)
67480
67571
  throw new Error(String(watched["error"] ?? "The web chat page could not be prepared."));
67481
- const sent = await runScript(chrome, askScript(setup, question));
67572
+ const sent = await runScript(chrome, askScript(setup, question), pageId);
67482
67573
  if (Array.isArray(sent["needsActivity"])) {
67483
67574
  throw new Error(`The web chat signs its requests with ${sent["needsActivity"].join(", ")}, which Light Code takes from the page and never stores. Send any message in the web chat tab once (or reload it), then ask again.`);
67484
67575
  }
@@ -67495,6 +67586,64 @@ async function askWebChat(chrome, setup, question) {
67495
67586
  }
67496
67587
  return answer;
67497
67588
  }
67589
+ async function askThroughWindow(chrome, setup, question, options = {}) {
67590
+ const sleep3 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
67591
+ const timeout = options.timeoutMs ?? 3e5;
67592
+ const origin = new URL(setup.pageUrl).origin;
67593
+ const backend = setup.backendUrl ?? new URL(setup.request.path, origin).href;
67594
+ const pageId = await selectWebChatPage(chrome, setup.pageUrl);
67595
+ const before = String((await runScript(chrome, pageTextScript(origin), pageId))["text"] ?? "");
67596
+ const watched = await runScript(chrome, watchScript(origin, void 0, backend), pageId);
67597
+ if (watched["ok"] !== true)
67598
+ throw new Error(String(watched["error"] ?? "The web chat page could not be prepared."));
67599
+ const typed = await runScript(chrome, typeTextScript(origin, question), pageId);
67600
+ if (typed["ok"] !== true)
67601
+ throw new Error(String(typed["error"] ?? "The question could not be typed into the web chat."));
67602
+ const started = Date.now();
67603
+ let lastText = "";
67604
+ let stableSince = Date.now();
67605
+ while (Date.now() - started < timeout) {
67606
+ await sleep3(1e3);
67607
+ const read = await runScript(chrome, readRepliesScript(origin), pageId);
67608
+ const replies = Array.isArray(read["replies"]) ? read["replies"] : [];
67609
+ const reply = replies.at(-1);
67610
+ if (reply !== void 0) {
67611
+ const status2 = Number(reply.status ?? 0);
67612
+ if (status2 === 401 || status2 === 403)
67613
+ throw new Error(`The web chat answered HTTP ${String(status2)}: sign in to it again in Chrome, then ask again.`);
67614
+ if (status2 >= 400)
67615
+ throw new Error(`The web chat answered HTTP ${String(status2)}: ${String(reply.response ?? "").slice(0, 300)}`);
67616
+ const answer = readAnswer(String(reply.response ?? ""), setup.response);
67617
+ if (answer !== void 0 && answer.trim().length > 0)
67618
+ return { answer, from: "reply" };
67619
+ throw new Error("The web chat replied, but not in the shape the capture found - it may have changed how it replies. Capture again in Settings \u2192 Agents \u2192 Web chat.");
67620
+ }
67621
+ const waitingForRequest = Number(read["pending"] ?? 0) > 0;
67622
+ if (!waitingForRequest && Date.now() - started > 5e3) {
67623
+ const now = String((await runScript(chrome, pageTextScript(origin), pageId))["text"] ?? "");
67624
+ if (now !== lastText) {
67625
+ lastText = now;
67626
+ stableSince = Date.now();
67627
+ } else if (Date.now() - stableSince >= (options.quietMs ?? 4e3)) {
67628
+ const added = newText(before, now, question);
67629
+ if (added.length > 0)
67630
+ return { answer: added, from: "screen" };
67631
+ }
67632
+ }
67633
+ }
67634
+ throw new Error(`No answer from the web chat within ${String(Math.round(timeout / 1e3))} seconds. Look at the web chat tab in Chrome.`);
67635
+ }
67636
+ function newText(before, after, question) {
67637
+ let start = 0;
67638
+ while (start < before.length && start < after.length && before[start] === after[start])
67639
+ start += 1;
67640
+ let added = after.slice(start);
67641
+ const q = question.trim();
67642
+ const at2 = q.length > 0 ? added.indexOf(q) : -1;
67643
+ if (at2 >= 0)
67644
+ added = added.slice(at2 + q.length);
67645
+ return added.trim();
67646
+ }
67498
67647
 
67499
67648
  // ../../packages/core/dist/webchat/capture.js
67500
67649
  function capturePhrase(random2 = Math.random) {
@@ -67512,10 +67661,7 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67512
67661
  refused.push(`${entry.url}: not an address.`);
67513
67662
  continue;
67514
67663
  }
67515
- if (url2.origin !== origin) {
67516
- refused.push(`${entry.method} ${entry.url}: on another site than the web chat (${origin}), so it is not used.`);
67517
- continue;
67518
- }
67664
+ const window = url2.origin !== origin;
67519
67665
  const contentType2 = Object.entries(entry.headers).find(([name]) => name.toLowerCase() === "content-type")?.[1];
67520
67666
  const template = bodyTemplate(entry.body, marker, contentType2);
67521
67667
  if (template === void 0)
@@ -67530,10 +67676,22 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67530
67676
  const setup = {
67531
67677
  version: 1,
67532
67678
  pageUrl,
67533
- request: { path: `${url2.pathname}${url2.search}`, method: entry.method.toUpperCase(), headers: plain, fromPage, body: template.body, encoding: template.encoding },
67679
+ request: {
67680
+ path: `${url2.pathname}${url2.search}`,
67681
+ method: entry.method.toUpperCase(),
67682
+ headers: plain,
67683
+ fromPage,
67684
+ body: template.body,
67685
+ encoding: template.encoding,
67686
+ ...entry.credentials === "include" || entry.credentials === "same-origin" || entry.credentials === "omit" ? { credentials: entry.credentials } : {}
67687
+ },
67534
67688
  response: answer.spec,
67535
67689
  ...model !== void 0 ? { model } : {},
67536
- capturedAt: now.toISOString()
67690
+ capturedAt: now.toISOString(),
67691
+ // Sent directly to the approved address even on another site (asked for: "even if the api site is different, it
67692
+ // should work if I approved it"); the chat window is the fallback when the backend refuses it.
67693
+ method: "replay",
67694
+ backendUrl: `${url2.origin}${url2.pathname}${url2.search}`
67537
67695
  };
67538
67696
  candidates.push({
67539
67697
  backend: `${url2.origin}${url2.pathname}${url2.search}`,
@@ -67541,6 +67699,7 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67541
67699
  ...model !== void 0 ? { model } : {},
67542
67700
  answerPreview: answer.answer.slice(0, 300),
67543
67701
  fromPage,
67702
+ window,
67544
67703
  setup
67545
67704
  });
67546
67705
  }
@@ -67562,7 +67721,12 @@ function createAskWebChatTool(deps) {
67562
67721
  const where = destination === void 0 ? "the web chat (not set up yet)" : `${destination.backend}${destination.model !== void 0 ? ` (model ${destination.model})` : ""}`;
67563
67722
  return {
67564
67723
  kind: "text",
67565
- text: `Sent through your Chrome, signed in as you, to the web chat's approved backend address only:
67724
+ text: destination?.method === "window" ? `Typed into the web chat window in your Chrome and sent, as you would; the answer is read from its reply from the approved backend address only:
67725
+ ${where}
67726
+
67727
+ The exact text typed:
67728
+
67729
+ ${params3.question}` : `Sent through your Chrome, signed in as you, to the web chat's approved backend address only:
67566
67730
  ${where}
67567
67731
 
67568
67732
  The exact text sent:
@@ -91343,9 +91507,9 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91343
91507
  const setup = cachedWebChat ?? await loadWebChat();
91344
91508
  if (setup === void 0)
91345
91509
  return void 0;
91346
- const backend = new URL(setup.request.path, new URL(setup.pageUrl).origin).href;
91510
+ const backend = setup.backendUrl ?? new URL(setup.request.path, new URL(setup.pageUrl).origin).href;
91347
91511
  const model = setup.modelOverride ?? setup.model;
91348
- return { backend, ...model !== void 0 ? { model } : {} };
91512
+ return { backend, method: setup.method ?? "replay", ...model !== void 0 ? { model } : {} };
91349
91513
  },
91350
91514
  problem: async () => {
91351
91515
  const setup = cachedWebChat ?? await loadWebChat();
@@ -91356,9 +91520,70 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91356
91520
  const server = webChatServer();
91357
91521
  if (setup === void 0 || server === void 0)
91358
91522
  throw new Error("The web chat or its Chrome DevTools MCP server is not available.");
91359
- return askWebChat(chromeAccess(server), setup, question);
91523
+ const throughWindow = async (why) => {
91524
+ const read = await askThroughWindow(chromeAccess(server), setup, question);
91525
+ const how = why === void 0 ? "" : `
91526
+
91527
+ (Sent through the chat window: the direct request did not work - ${why})`;
91528
+ return read.from === "screen" ? `${read.answer}
91529
+
91530
+ (Read off the web chat's screen: no reply from its backend was seen.)${how}` : `${read.answer}${how}`;
91531
+ };
91532
+ if (setup.method === "window")
91533
+ return throughWindow();
91534
+ try {
91535
+ return await askWebChat(chromeAccess(server), setup, question);
91536
+ } catch (error51) {
91537
+ const message6 = error51 instanceof Error ? error51.message : String(error51);
91538
+ if (/HTTP 40[13]/.test(message6) || /not where the capture found it/.test(message6))
91539
+ throw error51;
91540
+ logger.info(`web chat: the direct request did not work (${message6}); trying the chat window`);
91541
+ return throughWindow(message6);
91542
+ }
91360
91543
  }
91361
91544
  };
91545
+ let webChatTesting = false;
91546
+ async function testWebChat() {
91547
+ if (webChatTesting)
91548
+ return;
91549
+ webChatTesting = true;
91550
+ try {
91551
+ const setup = cachedWebChat ?? await loadWebChat();
91552
+ const server = webChatServer();
91553
+ const results = [];
91554
+ const fail = (text2) => {
91555
+ post({ type: "webChatTest", results: [{ way: "direct", ok: false, text: text2, ms: 0 }, { way: "window", ok: false, text: text2, ms: 0 }] });
91556
+ };
91557
+ if (setup === void 0)
91558
+ return fail("The web chat is not set up.");
91559
+ if (server === void 0)
91560
+ return fail("The Chrome DevTools MCP server chosen for the web chat is not connected.");
91561
+ const problem = await webChatProblem(setup.pageUrl, server);
91562
+ if (problem !== void 0 && problem.length > 0)
91563
+ return fail(problem);
91564
+ const question = "Reply with the single word: ready";
91565
+ const clip3 = (text2) => text2.length > 300 ? `${text2.slice(0, 300)}\u2026` : text2;
91566
+ post({ type: "webChatTest", running: "direct" });
91567
+ let started = Date.now();
91568
+ try {
91569
+ const answer = await askWebChat(chromeAccess(server), setup, question);
91570
+ results.push({ way: "direct", ok: true, text: clip3(answer), ms: Date.now() - started });
91571
+ } catch (error51) {
91572
+ results.push({ way: "direct", ok: false, text: error51 instanceof Error ? error51.message : String(error51), ms: Date.now() - started });
91573
+ }
91574
+ post({ type: "webChatTest", results, running: "window" });
91575
+ started = Date.now();
91576
+ try {
91577
+ const read = await askThroughWindow(chromeAccess(server), setup, question);
91578
+ results.push({ way: "window", ok: true, text: clip3(read.answer), ms: Date.now() - started, from: read.from });
91579
+ } catch (error51) {
91580
+ results.push({ way: "window", ok: false, text: error51 instanceof Error ? error51.message : String(error51), ms: Date.now() - started });
91581
+ }
91582
+ post({ type: "webChatTest", results });
91583
+ } finally {
91584
+ webChatTesting = false;
91585
+ }
91586
+ }
91362
91587
  async function postWebChat(message6) {
91363
91588
  const setup = await loadWebChat();
91364
91589
  const servers = chromeServers();
@@ -91368,7 +91593,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91368
91593
  ...setup !== void 0 ? {
91369
91594
  setup: {
91370
91595
  pageUrl: setup.pageUrl,
91371
- backend: new URL(setup.request.path, new URL(setup.pageUrl).origin).href,
91596
+ backend: setup.backendUrl ?? new URL(setup.request.path, new URL(setup.pageUrl).origin).href,
91597
+ via: setup.method ?? "replay",
91372
91598
  method: setup.request.method,
91373
91599
  ...setup.model !== void 0 ? { model: setup.model } : {},
91374
91600
  ...setup.modelOverride !== void 0 ? { modelOverride: setup.modelOverride } : {},
@@ -91401,16 +91627,17 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91401
91627
  const origin = new URL(pageUrl).origin;
91402
91628
  const phrase = capturePhrase();
91403
91629
  mcp.reserve([server]);
91404
- await selectWebChatPage(chrome, pageUrl);
91405
- const installed = await runScript(chrome, watchScript(origin, phrase));
91630
+ const pageId = await selectWebChatPage(chrome, pageUrl);
91631
+ const installed = await runScript(chrome, watchScript(origin, phrase), pageId);
91406
91632
  if (installed["ok"] !== true) {
91407
91633
  post({ type: "webChatCapture", phase: "failed", message: String(installed["error"] ?? "The page could not be watched.") });
91408
91634
  return;
91409
91635
  }
91410
- webChatCapture = { pageUrl, server, phrase, startedAt: Date.now(), candidates: [] };
91636
+ webChatCapture = { pageUrl, server, pageId, phrase, startedAt: Date.now(), candidates: [] };
91411
91637
  post({ type: "webChatCapture", phase: "waiting", phrase });
91412
91638
  const capture = webChatCapture;
91413
91639
  let polling = false;
91640
+ let failures = 0;
91414
91641
  capture.timer = setInterval(() => {
91415
91642
  if (polling || webChatCapture !== capture)
91416
91643
  return;
@@ -91422,9 +91649,10 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91422
91649
  post({ type: "webChatCapture", phase: "failed", message: "Nothing carrying the phrase was seen in three minutes. Send it in the web chat tab Light Code opened (a new chat), then capture again." });
91423
91650
  return;
91424
91651
  }
91425
- const read = await runScript(chrome, readCaptureScript(origin));
91652
+ const read = await runScript(chrome, readCaptureScript(origin), capture.pageId);
91653
+ failures = 0;
91426
91654
  if (read["ok"] !== true) {
91427
- await selectWebChatPage(chrome, pageUrl);
91655
+ capture.pageId = await selectWebChatPage(chrome, pageUrl);
91428
91656
  return;
91429
91657
  }
91430
91658
  if (read["ws"] === true) {
@@ -91452,12 +91680,19 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91452
91680
  method: candidate.method,
91453
91681
  ...candidate.model !== void 0 ? { model: candidate.model } : {},
91454
91682
  answerPreview: candidate.answerPreview,
91455
- fromPage: candidate.fromPage
91683
+ fromPage: candidate.fromPage,
91684
+ window: candidate.window
91456
91685
  })),
91457
91686
  refused
91458
91687
  });
91459
91688
  } catch (error51) {
91460
- logger.warn(`web chat capture: ${error51 instanceof Error ? error51.message : String(error51)}`);
91689
+ const message6 = error51 instanceof Error ? error51.message : String(error51);
91690
+ logger.warn(`web chat capture: ${message6}`);
91691
+ failures += 1;
91692
+ if (failures >= 3 && webChatCapture === capture) {
91693
+ stopWebChatCapture();
91694
+ post({ type: "webChatCapture", phase: "failed", message: message6 });
91695
+ }
91461
91696
  } finally {
91462
91697
  polling = false;
91463
91698
  }
@@ -99672,7 +99907,7 @@ ${answer.slice(0, 16e3)}` } }, (d) => d.best !== void 0 && d.best.probability >=
99672
99907
  const capture = webChatCapture;
99673
99908
  const server = capture?.server;
99674
99909
  if (capture !== void 0 && server !== void 0) {
99675
- void runScript(chromeAccess(server), typePhraseScript(new URL(capture.pageUrl).origin, capture.phrase)).then((done) => {
99910
+ void runScript(chromeAccess(server), typePhraseScript(new URL(capture.pageUrl).origin, capture.phrase), capture.pageId).then((done) => {
99676
99911
  if (done["ok"] !== true)
99677
99912
  post({ type: "webChatCapture", phase: "waiting", phrase: capture.phrase, message: String(done["error"] ?? "It could not be typed - paste it by hand.") });
99678
99913
  }).catch((error51) => post({ type: "webChatCapture", phase: "waiting", phrase: capture.phrase, message: error51 instanceof Error ? error51.message : String(error51) }));
@@ -99711,6 +99946,8 @@ ${answer.slice(0, 16e3)}` } }, (d) => d.best !== void 0 && d.best.probability >=
99711
99946
  await writeWebChatSetup(webChatFile, next);
99712
99947
  await postWebChat("Saved.");
99713
99948
  })();
99949
+ } else if (message6.type === "testWebChat") {
99950
+ reportFailure("testWebChat", testWebChat());
99714
99951
  } else if (message6.type === "clearWebChat") {
99715
99952
  stopWebChatCapture();
99716
99953
  if (webChatFile !== void 0)
@@ -106019,9 +106256,14 @@ transcript was written.
106019
106256
  "second opinion",
106020
106257
  "capture",
106021
106258
  "backend address",
106022
- "bank",
106259
+ "chat window",
106260
+ "another site",
106261
+ "on another site",
106262
+ "test both ways",
106263
+ "backup way",
106264
+ "primary way",
106023
106265
  "inside the network",
106024
- "outside the bank"
106266
+ "outside the organisation"
106025
106267
  ],
106026
106268
  body: `
106027
106269
  **\`ask_web_chat\` consults the model behind your organisation's internal web chat** - for when a model (Gemini, say) is
@@ -106042,6 +106284,17 @@ DevTools MCP server is connected, and never on a shared server.
106042
106284
  3. Light Code shows the request that carried it: **the backend address**, the model, and the start of the answer it read.
106043
106285
  **Use this** approves it - only that backend address is ever used afterwards. **Capture again** to change it.
106044
106286
 
106287
+ **Two ways a question is sent, wherever the backend is (its own site or another, such as an \`api.\` address):**
106288
+ - **Directly (the primary way):** Light Code sends the approved request itself, from inside the chat page, signed in as
106289
+ you, to exactly the approved address - with cookies or without, as the page's own request was.
106290
+ - **Through the chat window (the backup):** when the direct request is refused or fails, the question is typed into the
106291
+ chat and sent, as you would, and the answer is read from the page's own reply from the approved backend. A path part
106292
+ that is plainly an id (a conversation id) may differ; anything else must match. When no such reply is seen (a chat
106293
+ over a WebSocket), the answer is read off the screen once it stops changing, and the result says so. A sign-in
106294
+ refusal (401/403) is not retried this way - sign in to the web chat in Chrome.
106295
+ - **Test both ways** (beside Capture again) asks one short question each way and shows which works here, and how long
106296
+ each took.
106297
+
106045
106298
  **It cannot go outside the organisation, by rule - each checked before every consultation, and nothing is sent when one fails:**
106046
106299
  - Light Code opens no connection itself: the request runs inside the chat page, in your Chrome, to the approved
106047
106300
  backend address on the chat's own site only, with redirects refused; a reply from another site is not used. Your session