@chosengeneration/light-code 0.202.0 → 0.203.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.
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();
@@ -67433,52 +67433,80 @@ function propertyNames(schema13) {
67433
67433
  const properties = schema13?.["properties"];
67434
67434
  return properties !== null && typeof properties === "object" ? Object.keys(properties) : [];
67435
67435
  }
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;
67436
+ function pagesIn(text2) {
67437
+ const pages = [];
67438
+ for (const line of text2.split(/\r?\n/)) {
67439
+ const match = /^\s*(\d+)\s*:\s*(.+?)\s*$/.exec(line);
67440
+ if (match === null)
67441
+ continue;
67442
+ const rest = match[2] ?? "";
67443
+ const inBrackets = [...rest.matchAll(/\((https?:\/\/[^\s)]+)\)/g)].at(-1)?.[1];
67444
+ const url2 = inBrackets ?? /^(https?:\/\/\S+)/.exec(rest)?.[1];
67445
+ if (url2 === void 0)
67446
+ continue;
67447
+ pages.push({ id: Number(match[1]), url: url2, selected: /\[selected\]/i.test(rest) });
67448
+ }
67449
+ return pages;
67450
+ }
67451
+ function sameOrigin(url2, origin) {
67452
+ try {
67453
+ return new URL(url2).origin === origin;
67454
+ } catch {
67455
+ return false;
67456
+ }
67446
67457
  }
67447
67458
  async function selectWebChatPage(chrome, pageUrl) {
67448
67459
  const origin = new URL(pageUrl).origin;
67449
67460
  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;
67461
+ const existing = listed.isError ? [] : pagesIn(listed.text).filter((page) => sameOrigin(page.url, origin));
67462
+ const chosen = existing.find((page) => page.selected) ?? existing[0];
67463
+ if (chosen !== void 0) {
67464
+ if (!chosen.selected && chrome.schema("select_page") !== void 0) {
67463
67465
  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]) });
67466
+ const key4 = names.includes("pageId") ? "pageId" : names.find((name) => /idx|index|id/i.test(name)) ?? "pageId";
67467
+ const selected = await chrome.call("select_page", { [key4]: chosen.id });
67466
67468
  if (selected.isError)
67467
67469
  throw new Error(`Chrome could not select the web chat tab: ${selected.text.slice(0, 300)}`);
67468
- return;
67469
67470
  }
67471
+ return chosen.id;
67470
67472
  }
67471
67473
  const opened = await chrome.call("new_page", { url: pageUrl });
67472
67474
  if (opened.isError)
67473
67475
  throw new Error(`Chrome could not open ${pageUrl}: ${opened.text.slice(0, 300)}`);
67476
+ const now = pagesIn(opened.text).filter((page) => sameOrigin(page.url, origin));
67477
+ const fresh = now.find((page) => page.selected) ?? now.at(-1);
67478
+ if (fresh !== void 0)
67479
+ return fresh.id;
67480
+ const again = await chrome.call("list_pages", {});
67481
+ const found2 = again.isError ? [] : pagesIn(again.text).filter((page) => sameOrigin(page.url, origin));
67482
+ return (found2.find((page) => page.selected) ?? found2.at(-1))?.id;
67483
+ }
67484
+ async function runScript(chrome, source, pageId) {
67485
+ const names = propertyNames(chrome.schema("evaluate_script"));
67486
+ const key4 = names.includes("function") ? "function" : names.includes("expression") ? "expression" : names[0] ?? "function";
67487
+ const args = { [key4]: source };
67488
+ if (names.includes("pageId")) {
67489
+ if (pageId === void 0)
67490
+ throw new Error("Chrome needs the web chat tab's id, and none was found in its list of tabs.");
67491
+ args["pageId"] = pageId;
67492
+ }
67493
+ if (names.includes("waitForStableDom"))
67494
+ args["waitForStableDom"] = false;
67495
+ const result = await chrome.call("evaluate_script", args);
67496
+ if (result.isError)
67497
+ throw new Error(`Chrome could not run the script: ${result.text.slice(0, 400)}`);
67498
+ const value = result.structured ?? scriptResult(result.text);
67499
+ if (value === null || typeof value !== "object")
67500
+ throw new Error(`Chrome returned something unexpected: ${result.text.slice(0, 300)}`);
67501
+ return value;
67474
67502
  }
67475
67503
  async function askWebChat(chrome, setup, question) {
67476
67504
  const origin = new URL(setup.pageUrl).origin;
67477
- await selectWebChatPage(chrome, setup.pageUrl);
67478
- const watched = await runScript(chrome, watchScript(origin, void 0));
67505
+ const pageId = await selectWebChatPage(chrome, setup.pageUrl);
67506
+ const watched = await runScript(chrome, watchScript(origin, void 0), pageId);
67479
67507
  if (watched["ok"] !== true)
67480
67508
  throw new Error(String(watched["error"] ?? "The web chat page could not be prepared."));
67481
- const sent = await runScript(chrome, askScript(setup, question));
67509
+ const sent = await runScript(chrome, askScript(setup, question), pageId);
67482
67510
  if (Array.isArray(sent["needsActivity"])) {
67483
67511
  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
67512
  }
@@ -91401,16 +91429,17 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91401
91429
  const origin = new URL(pageUrl).origin;
91402
91430
  const phrase = capturePhrase();
91403
91431
  mcp.reserve([server]);
91404
- await selectWebChatPage(chrome, pageUrl);
91405
- const installed = await runScript(chrome, watchScript(origin, phrase));
91432
+ const pageId = await selectWebChatPage(chrome, pageUrl);
91433
+ const installed = await runScript(chrome, watchScript(origin, phrase), pageId);
91406
91434
  if (installed["ok"] !== true) {
91407
91435
  post({ type: "webChatCapture", phase: "failed", message: String(installed["error"] ?? "The page could not be watched.") });
91408
91436
  return;
91409
91437
  }
91410
- webChatCapture = { pageUrl, server, phrase, startedAt: Date.now(), candidates: [] };
91438
+ webChatCapture = { pageUrl, server, pageId, phrase, startedAt: Date.now(), candidates: [] };
91411
91439
  post({ type: "webChatCapture", phase: "waiting", phrase });
91412
91440
  const capture = webChatCapture;
91413
91441
  let polling = false;
91442
+ let failures = 0;
91414
91443
  capture.timer = setInterval(() => {
91415
91444
  if (polling || webChatCapture !== capture)
91416
91445
  return;
@@ -91422,9 +91451,10 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91422
91451
  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
91452
  return;
91424
91453
  }
91425
- const read = await runScript(chrome, readCaptureScript(origin));
91454
+ const read = await runScript(chrome, readCaptureScript(origin), capture.pageId);
91455
+ failures = 0;
91426
91456
  if (read["ok"] !== true) {
91427
- await selectWebChatPage(chrome, pageUrl);
91457
+ capture.pageId = await selectWebChatPage(chrome, pageUrl);
91428
91458
  return;
91429
91459
  }
91430
91460
  if (read["ws"] === true) {
@@ -91457,7 +91487,13 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91457
91487
  refused
91458
91488
  });
91459
91489
  } catch (error51) {
91460
- logger.warn(`web chat capture: ${error51 instanceof Error ? error51.message : String(error51)}`);
91490
+ const message6 = error51 instanceof Error ? error51.message : String(error51);
91491
+ logger.warn(`web chat capture: ${message6}`);
91492
+ failures += 1;
91493
+ if (failures >= 3 && webChatCapture === capture) {
91494
+ stopWebChatCapture();
91495
+ post({ type: "webChatCapture", phase: "failed", message: message6 });
91496
+ }
91461
91497
  } finally {
91462
91498
  polling = false;
91463
91499
  }
@@ -99672,7 +99708,7 @@ ${answer.slice(0, 16e3)}` } }, (d) => d.best !== void 0 && d.best.probability >=
99672
99708
  const capture = webChatCapture;
99673
99709
  const server = capture?.server;
99674
99710
  if (capture !== void 0 && server !== void 0) {
99675
- void runScript(chromeAccess(server), typePhraseScript(new URL(capture.pageUrl).origin, capture.phrase)).then((done) => {
99711
+ void runScript(chromeAccess(server), typePhraseScript(new URL(capture.pageUrl).origin, capture.phrase), capture.pageId).then((done) => {
99676
99712
  if (done["ok"] !== true)
99677
99713
  post({ type: "webChatCapture", phase: "waiting", phrase: capture.phrase, message: String(done["error"] ?? "It could not be typed - paste it by hand.") });
99678
99714
  }).catch((error51) => post({ type: "webChatCapture", phase: "waiting", phrase: capture.phrase, message: error51 instanceof Error ? error51.message : String(error51) }));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chosengeneration/light-code",
3
- "version": "0.202.0",
3
+ "version": "0.203.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",