@chosengeneration/light-code 0.203.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 +248 -31
  2. package/dist/server.cjs +245 -28
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -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) {
@@ -67503,7 +67566,7 @@ async function runScript(chrome, source, pageId) {
67503
67566
  async function askWebChat(chrome, setup, question) {
67504
67567
  const origin = new URL(setup.pageUrl).origin;
67505
67568
  const pageId = await selectWebChatPage(chrome, setup.pageUrl);
67506
- const watched = await runScript(chrome, watchScript(origin, void 0), pageId);
67569
+ const watched = await runScript(chrome, watchScript(origin, void 0, setup.backendUrl ?? new URL(setup.request.path, origin).href), pageId);
67507
67570
  if (watched["ok"] !== true)
67508
67571
  throw new Error(String(watched["error"] ?? "The web chat page could not be prepared."));
67509
67572
  const sent = await runScript(chrome, askScript(setup, question), pageId);
@@ -67523,6 +67586,64 @@ async function askWebChat(chrome, setup, question) {
67523
67586
  }
67524
67587
  return answer;
67525
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
+ }
67526
67647
 
67527
67648
  // ../../packages/core/dist/webchat/capture.js
67528
67649
  function capturePhrase(random2 = Math.random) {
@@ -67540,10 +67661,7 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67540
67661
  refused.push(`${entry.url}: not an address.`);
67541
67662
  continue;
67542
67663
  }
67543
- if (url2.origin !== origin) {
67544
- refused.push(`${entry.method} ${entry.url}: on another site than the web chat (${origin}), so it is not used.`);
67545
- continue;
67546
- }
67664
+ const window = url2.origin !== origin;
67547
67665
  const contentType2 = Object.entries(entry.headers).find(([name]) => name.toLowerCase() === "content-type")?.[1];
67548
67666
  const template = bodyTemplate(entry.body, marker, contentType2);
67549
67667
  if (template === void 0)
@@ -67558,10 +67676,22 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67558
67676
  const setup = {
67559
67677
  version: 1,
67560
67678
  pageUrl,
67561
- 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
+ },
67562
67688
  response: answer.spec,
67563
67689
  ...model !== void 0 ? { model } : {},
67564
- 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}`
67565
67695
  };
67566
67696
  candidates.push({
67567
67697
  backend: `${url2.origin}${url2.pathname}${url2.search}`,
@@ -67569,6 +67699,7 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67569
67699
  ...model !== void 0 ? { model } : {},
67570
67700
  answerPreview: answer.answer.slice(0, 300),
67571
67701
  fromPage,
67702
+ window,
67572
67703
  setup
67573
67704
  });
67574
67705
  }
@@ -67590,7 +67721,12 @@ function createAskWebChatTool(deps) {
67590
67721
  const where = destination === void 0 ? "the web chat (not set up yet)" : `${destination.backend}${destination.model !== void 0 ? ` (model ${destination.model})` : ""}`;
67591
67722
  return {
67592
67723
  kind: "text",
67593
- 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:
67594
67730
  ${where}
67595
67731
 
67596
67732
  The exact text sent:
@@ -91371,9 +91507,9 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91371
91507
  const setup = cachedWebChat ?? await loadWebChat();
91372
91508
  if (setup === void 0)
91373
91509
  return void 0;
91374
- 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;
91375
91511
  const model = setup.modelOverride ?? setup.model;
91376
- return { backend, ...model !== void 0 ? { model } : {} };
91512
+ return { backend, method: setup.method ?? "replay", ...model !== void 0 ? { model } : {} };
91377
91513
  },
91378
91514
  problem: async () => {
91379
91515
  const setup = cachedWebChat ?? await loadWebChat();
@@ -91384,9 +91520,70 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91384
91520
  const server = webChatServer();
91385
91521
  if (setup === void 0 || server === void 0)
91386
91522
  throw new Error("The web chat or its Chrome DevTools MCP server is not available.");
91387
- 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
+ }
91388
91543
  }
91389
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
+ }
91390
91587
  async function postWebChat(message6) {
91391
91588
  const setup = await loadWebChat();
91392
91589
  const servers = chromeServers();
@@ -91396,7 +91593,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91396
91593
  ...setup !== void 0 ? {
91397
91594
  setup: {
91398
91595
  pageUrl: setup.pageUrl,
91399
- 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",
91400
91598
  method: setup.request.method,
91401
91599
  ...setup.model !== void 0 ? { model: setup.model } : {},
91402
91600
  ...setup.modelOverride !== void 0 ? { modelOverride: setup.modelOverride } : {},
@@ -91482,7 +91680,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91482
91680
  method: candidate.method,
91483
91681
  ...candidate.model !== void 0 ? { model: candidate.model } : {},
91484
91682
  answerPreview: candidate.answerPreview,
91485
- fromPage: candidate.fromPage
91683
+ fromPage: candidate.fromPage,
91684
+ window: candidate.window
91486
91685
  })),
91487
91686
  refused
91488
91687
  });
@@ -99747,6 +99946,8 @@ ${answer.slice(0, 16e3)}` } }, (d) => d.best !== void 0 && d.best.probability >=
99747
99946
  await writeWebChatSetup(webChatFile, next);
99748
99947
  await postWebChat("Saved.");
99749
99948
  })();
99949
+ } else if (message6.type === "testWebChat") {
99950
+ reportFailure("testWebChat", testWebChat());
99750
99951
  } else if (message6.type === "clearWebChat") {
99751
99952
  stopWebChatCapture();
99752
99953
  if (webChatFile !== void 0)
@@ -106055,9 +106256,14 @@ transcript was written.
106055
106256
  "second opinion",
106056
106257
  "capture",
106057
106258
  "backend address",
106058
- "bank",
106259
+ "chat window",
106260
+ "another site",
106261
+ "on another site",
106262
+ "test both ways",
106263
+ "backup way",
106264
+ "primary way",
106059
106265
  "inside the network",
106060
- "outside the bank"
106266
+ "outside the organisation"
106061
106267
  ],
106062
106268
  body: `
106063
106269
  **\`ask_web_chat\` consults the model behind your organisation's internal web chat** - for when a model (Gemini, say) is
@@ -106078,6 +106284,17 @@ DevTools MCP server is connected, and never on a shared server.
106078
106284
  3. Light Code shows the request that carried it: **the backend address**, the model, and the start of the answer it read.
106079
106285
  **Use this** approves it - only that backend address is ever used afterwards. **Capture again** to change it.
106080
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
+
106081
106298
  **It cannot go outside the organisation, by rule - each checked before every consultation, and nothing is sent when one fails:**
106082
106299
  - Light Code opens no connection itself: the request runs inside the chat page, in your Chrome, to the approved
106083
106300
  backend address on the chat's own site only, with redirects refused; a reply from another site is not used. Your session
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chosengeneration/light-code",
3
- "version": "0.203.0",
3
+ "version": "0.204.0",
4
4
  "description": "A minimal agentic coding assistant, served to your browser from a local Node server",
5
5
  "license": "MIT",
6
6
  "type": "module",