@chosengeneration/light-code 0.203.0 → 0.207.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 +478 -72
  2. package/dist/server.cjs +475 -69
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -39918,6 +39918,16 @@ var mcpServersSchema = external_exports.record(external_exports.string(), mcpSer
39918
39918
  function isStdioServer(config2) {
39919
39919
  return "command" in config2;
39920
39920
  }
39921
+ function isJoinedLine(line) {
39922
+ const trimmed = line.trim();
39923
+ return /\s/.test(trimmed) && !/["'\\]/.test(trimmed) && /(^|\s)--?[A-Za-z]/.test(trimmed);
39924
+ }
39925
+ function stdioCommandLine(config2) {
39926
+ const words2 = (line) => line.trim().split(/\s+/);
39927
+ const head = isJoinedLine(config2.command) ? words2(config2.command) : [config2.command];
39928
+ const args = (config2.args ?? []).flatMap((arg) => isJoinedLine(arg) ? words2(arg) : [arg]).filter((arg) => arg.length > 0);
39929
+ return { command: head[0] ?? config2.command, args: [...head.slice(1), ...args] };
39930
+ }
39921
39931
  function resolveToolPermission(toolName, namespacedName, disabledTools, alwaysAllowedTools) {
39922
39932
  if (disabledTools?.includes(toolName) === true)
39923
39933
  return "never";
@@ -60368,9 +60378,10 @@ async function interpolateSecrets(values, secrets, options = {}) {
60368
60378
  async function buildTransport(config2, secrets, options) {
60369
60379
  if (isStdioServer(config2)) {
60370
60380
  const configuredEnv = await interpolateSecrets(config2.env, secrets, options);
60381
+ const line = stdioCommandLine(config2);
60371
60382
  return new StdioClientTransport({
60372
- command: config2.command,
60373
- ...config2.args !== void 0 ? { args: config2.args } : {},
60383
+ command: line.command,
60384
+ ...line.args.length > 0 ? { args: line.args } : {},
60374
60385
  ...config2.cwd !== void 0 ? { cwd: config2.cwd } : {},
60375
60386
  // Passing `env` *replaces* the SDK's default rather than merging, so a server given
60376
60387
  // any env var at all would otherwise lose PATH and fail to spawn. The SDK's default
@@ -67148,9 +67159,7 @@ function chromeServerProblems(config2) {
67148
67159
  if (typeof record2.url === "string" || typeof record2.command !== "string")
67149
67160
  return ["The Chrome DevTools MCP server must run on this PC (a command), not as a remote server at a URL."];
67150
67161
  const problems = [];
67151
- const words2 = commandWords([record2.command, ...record2.args ?? []].join(" "));
67152
- const command = words2[0] ?? record2.command;
67153
- const args = words2.slice(1);
67162
+ const { command, args } = stdioCommandLine({ command: record2.command, args: record2.args ?? [] });
67154
67163
  const runner = command.split(/[\\/]/).pop()?.toLowerCase() ?? "";
67155
67164
  if (runner === "npx" || runner === "npx.cmd") {
67156
67165
  const spec = npxPackage(args);
@@ -67179,11 +67188,56 @@ function chromeServerProblems(config2) {
67179
67188
  }
67180
67189
  return problems;
67181
67190
  }
67182
- function commandWords(line) {
67183
- const words2 = [];
67184
- for (const match of line.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g))
67185
- words2.push(match[1] ?? match[2] ?? match[3] ?? "");
67186
- return words2;
67191
+ var TESTED_CHROME_MCP = "chrome-devtools-mcp@1.13.0";
67192
+ function fixChromeServer(config2) {
67193
+ if (config2 === void 0)
67194
+ return void 0;
67195
+ const record2 = config2;
67196
+ if (typeof record2.url === "string" || typeof record2.command !== "string")
67197
+ return void 0;
67198
+ const line = stdioCommandLine({ command: record2.command, args: record2.args ?? [] });
67199
+ const args = [...line.args];
67200
+ const runner = line.command.split(/[\\/]/).pop()?.toLowerCase() ?? "";
67201
+ if (runner === "npx" || runner === "npx.cmd") {
67202
+ const spec = npxPackage(args);
67203
+ if (spec === void 0)
67204
+ return void 0;
67205
+ if (!isPinned(spec)) {
67206
+ if (!/^chrome-devtools-mcp(@[^@]*)?$/.test(spec))
67207
+ return void 0;
67208
+ args[args.indexOf(spec)] = TESTED_CHROME_MCP;
67209
+ }
67210
+ if (!args.includes("-y") && !args.includes("--yes"))
67211
+ args.unshift("-y");
67212
+ } else if (isPackageRunnerCommand(line.command)) {
67213
+ return void 0;
67214
+ }
67215
+ for (const flag of REQUIRED_CHROME_FLAGS)
67216
+ if (!args.includes(flag))
67217
+ args.push(flag);
67218
+ const fixed = { ...config2, command: line.command, args };
67219
+ return chromeServerProblems(fixed).length === 0 ? fixed : void 0;
67220
+ }
67221
+ var AUTO_CONNECT = /^--?(autoConnect|auto-connect)(=true)?$/;
67222
+ var NAMES_CHROME = /^--?(browserUrl|browser-url|u|wsEndpoint|ws-endpoint|w)(=|$)/;
67223
+ function chromeMode(config2) {
67224
+ const record2 = config2;
67225
+ if (record2 === void 0 || typeof record2.command !== "string")
67226
+ return void 0;
67227
+ const { args } = stdioCommandLine({ command: record2.command, args: record2.args ?? [] });
67228
+ if (args.some((arg) => NAMES_CHROME.test(arg)))
67229
+ return "address";
67230
+ return args.some((arg) => AUTO_CONNECT.test(arg)) ? "own" : "started";
67231
+ }
67232
+ function withChromeMode(config2, mode) {
67233
+ const record2 = config2;
67234
+ if (typeof record2.command !== "string" || chromeMode(config2) === "address")
67235
+ return void 0;
67236
+ const line = stdioCommandLine({ command: record2.command, args: record2.args ?? [] });
67237
+ const args = line.args.filter((arg) => !AUTO_CONNECT.test(arg));
67238
+ if (mode === "own")
67239
+ args.push("--autoConnect");
67240
+ return { ...config2, command: line.command, args };
67187
67241
  }
67188
67242
  function isLoopback2(host) {
67189
67243
  return host === "localhost" || host === "::1" || /^127\./.test(host);
@@ -67239,36 +67293,74 @@ function sseEvents(text2) {
67239
67293
  }
67240
67294
  return events;
67241
67295
  }
67242
- function findAnswer(responseText, contentType2, exclude) {
67243
- const notQuestion = (text2) => text2.trim().length > 0 && text2.split(exclude).join("").replace(/[\s"'`.,:;!?()[\]{}-]/g, "").length >= 3;
67244
- const events = (contentType2 ?? "").includes("event-stream") || /^data:/m.test(responseText) ? sseEvents(responseText) : void 0;
67245
- if (events !== void 0 && events.length > 0) {
67246
- const byPath = /* @__PURE__ */ new Map();
67247
- for (const event of events) {
67248
- const found2 = [];
67249
- leaves(event, [], found2);
67250
- for (const leaf of found2) {
67251
- const entry = byPath.get(keyOf(leaf.path)) ?? { path: leaf.path, values: [] };
67252
- entry.values.push(leaf.text);
67253
- byPath.set(keyOf(leaf.path), entry);
67254
- }
67296
+ var nameLike = (text2) => /^[A-Za-z0-9_.:/#@+-]*$/.test(text2);
67297
+ function labelsEvents(values, eventCount) {
67298
+ if (values.length < 2 || values.length < eventCount * 0.8)
67299
+ return false;
67300
+ return values.every(nameLike) && new Set(values).size > 1;
67301
+ }
67302
+ function combine(values, mode) {
67303
+ if (mode === "cumulative")
67304
+ return values.at(-1) ?? "";
67305
+ if (values.length > 1) {
67306
+ const before = values.slice(0, -1).join("");
67307
+ const last = values.at(-1) ?? "";
67308
+ if (before.trim().length > 0 && last.trim() === before.trim())
67309
+ return last;
67310
+ }
67311
+ return values.join("");
67312
+ }
67313
+ function sseFields(events) {
67314
+ const byPath = /* @__PURE__ */ new Map();
67315
+ for (const event of events) {
67316
+ const found2 = [];
67317
+ leaves(event, [], found2);
67318
+ for (const leaf of found2) {
67319
+ const entry = byPath.get(keyOf(leaf.path)) ?? { path: leaf.path, values: [] };
67320
+ entry.values.push(leaf.text);
67321
+ byPath.set(keyOf(leaf.path), entry);
67255
67322
  }
67256
- let best;
67257
- for (const entry of byPath.values()) {
67258
- const cumulative = entry.values.length > 1 && entry.values.every((value, i) => i === 0 || value.startsWith(entry.values[i - 1] ?? ""));
67259
- const answer = cumulative ? entry.values.at(-1) ?? "" : entry.values.join("");
67260
- if (!notQuestion(answer))
67261
- continue;
67262
- if (best === void 0 || answer.length > best.answer.length)
67263
- best = { spec: { kind: "sse", path: entry.path, mode: cumulative ? "cumulative" : "delta" }, answer };
67323
+ }
67324
+ return [...byPath.values()];
67325
+ }
67326
+ var isProse = (text2) => /\s/.test(text2.trim());
67327
+ function answerRank(text2, path70) {
67328
+ const key4 = String(path70.filter((part) => typeof part === "string").at(-1) ?? "");
67329
+ if (/(^|_|-)id$|Id$|^uuid$/i.test(key4))
67330
+ return 0;
67331
+ if (isProse(text2))
67332
+ return 2;
67333
+ if (/\d/.test(text2) && /^[A-Za-z0-9_-]+$/.test(text2.trim()))
67334
+ return 0;
67335
+ return 1;
67336
+ }
67337
+ function bestSse(events, accept) {
67338
+ let best;
67339
+ for (const entry of sseFields(events)) {
67340
+ if (labelsEvents(entry.values, events.length))
67341
+ continue;
67342
+ const cumulative = entry.values.length > 1 && entry.values.every((value, i) => i === 0 || value.startsWith(entry.values[i - 1] ?? ""));
67343
+ const mode = cumulative ? "cumulative" : "delta";
67344
+ const answer = combine(entry.values, mode);
67345
+ if (!accept(answer))
67346
+ continue;
67347
+ const rank4 = answerRank(answer, entry.path);
67348
+ if (best === void 0 || rank4 > best.rank || rank4 === best.rank && answer.length > best.answer.length) {
67349
+ best = { spec: { kind: "sse", path: entry.path, mode }, answer, rank: rank4 };
67264
67350
  }
67265
- return best;
67266
67351
  }
67352
+ return best === void 0 ? void 0 : { spec: best.spec, answer: best.answer };
67353
+ }
67354
+ function findAnswer(responseText, contentType2, exclude) {
67355
+ const notQuestion = (text2) => text2.trim().length > 0 && text2.split(exclude).join("").replace(/[\s"'`.,:;!?()[\]{}-]/g, "").length >= 3;
67356
+ const events = (contentType2 ?? "").includes("event-stream") || /^data:/m.test(responseText) ? sseEvents(responseText) : void 0;
67357
+ if (events !== void 0 && events.length > 0)
67358
+ return bestSse(events, notQuestion);
67267
67359
  try {
67268
67360
  const document = JSON.parse(responseText);
67269
67361
  const found2 = [];
67270
67362
  leaves(document, [], found2);
67271
- const best = found2.filter((leaf) => notQuestion(leaf.text)).sort((a, b) => b.text.length - a.text.length)[0];
67363
+ const best = found2.filter((leaf) => notQuestion(leaf.text)).sort((a, b) => answerRank(b.text, b.path) - answerRank(a.text, a.path) || b.text.length - a.text.length)[0];
67272
67364
  return best === void 0 ? void 0 : { spec: { kind: "json", path: best.path }, answer: best.text };
67273
67365
  } catch {
67274
67366
  return notQuestion(responseText) ? { spec: { kind: "text" }, answer: responseText } : void 0;
@@ -67287,26 +67379,62 @@ function readAnswer(responseText, spec) {
67287
67379
  }
67288
67380
  const events = sseEvents(responseText) ?? [];
67289
67381
  const values = events.map((event) => at(event, spec.path ?? [])).filter((value) => typeof value === "string");
67382
+ if (labelsEvents(values, events.length))
67383
+ return bestSse(events, (text2) => text2.trim().length > 0)?.answer;
67290
67384
  if (values.length === 0)
67291
67385
  return void 0;
67292
- return spec.mode === "cumulative" ? values.at(-1) : values.join("");
67386
+ return combine(values, spec.mode === "cumulative" ? "cumulative" : "delta");
67387
+ }
67388
+ function replyShape(responseText) {
67389
+ const events = /^data:/m.test(responseText) ? sseEvents(responseText) : void 0;
67390
+ if (events !== void 0 && events.length > 0) {
67391
+ const fields = sseFields(events).map((entry) => {
67392
+ const chars = entry.values.reduce((sum, value) => sum + value.length, 0);
67393
+ return `${entry.path.join(".")} \xD7${String(entry.values.length)} (${String(chars)} chars${labelsEvents(entry.values, events.length) ? ", event labels" : ""})`;
67394
+ });
67395
+ return `${String(events.length)} events; fields: ${fields.join(", ")}`;
67396
+ }
67397
+ try {
67398
+ const found2 = [];
67399
+ leaves(JSON.parse(responseText), [], found2);
67400
+ return `JSON; text fields: ${found2.map((leaf) => `${leaf.path.join(".")} (${String(leaf.text.length)} chars)`).join(", ")}`;
67401
+ } catch {
67402
+ return `plain text, ${String(responseText.length)} chars`;
67403
+ }
67293
67404
  }
67294
67405
 
67295
67406
  // ../../packages/core/dist/webchat/inpage.js
67296
- function watchScript(origin, marker) {
67407
+ function watchScript(origin, marker, backendUrl) {
67297
67408
  return `async () => {
67298
67409
  const ORIGIN = ${JSON.stringify(origin)}
67299
67410
  if (location.origin !== ORIGIN) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67300
67411
  const w = window
67301
- w.__lcWebChat = w.__lcWebChat || { found: [], headers: {}, ws: false, marker: undefined }
67412
+ w.__lcWebChat = w.__lcWebChat || { found: [], headers: {}, ws: false, marker: undefined, replies: [] }
67302
67413
  const state = w.__lcWebChat
67414
+ state.replies = state.replies || []
67415
+ ${backendUrl !== void 0 ? `state.watchUrl = ${JSON.stringify(backendUrl)}; state.replies = []; state.ws = false` : ""}
67303
67416
  ${marker !== void 0 ? `state.marker = ${JSON.stringify(marker)}; state.found = []; state.ws = false` : ""}
67304
67417
  if (state.installed) return { ok: true }
67305
67418
  state.installed = true
67306
67419
  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
67420
+ // The chat window method: the page's own requests to the approved backend, with their replies, wherever it is.
67421
+ const toBackend = (u) => {
67422
+ if (!state.watchUrl) return false
67423
+ // Same site, same path segment by segment - except a segment that is plainly an id (a long number, long hex, a UUID),
67424
+ // which a chat app changes per conversation.
67425
+ 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)
67426
+ try {
67427
+ const a = new URL(u, location.href), b = new URL(state.watchUrl)
67428
+ if (a.origin !== b.origin) return false
67429
+ const p = a.pathname.split('/'), q = b.pathname.split('/')
67430
+ return p.length === q.length && p.every((part, i) => part === q[i] || (id(part) && id(q[i])))
67431
+ } catch { return false }
67432
+ }
67433
+ // The page's sign-in headers, from its requests to its own site or to the approved backend (which may be another site).
67434
+ const keep = (headers) => { for (const [k, v] of Object.entries(headers)) if (secret.test(k)) state.headers[k.toLowerCase()] = v }
67307
67435
  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
67436
+ try { if (new URL(url, location.href).origin !== ORIGIN && !toBackend(url)) return } catch { return }
67437
+ keep(headers)
67310
67438
  }
67311
67439
  const plain = (h) => {
67312
67440
  const out = {}
@@ -67322,14 +67450,21 @@ function watchScript(origin, marker) {
67322
67450
  let method = (init && init.method) || (input instanceof Request ? input.method : 'GET')
67323
67451
  let headers = plain((init && init.headers) || (input instanceof Request ? input.headers : undefined))
67324
67452
  let body = init && typeof init.body === 'string' ? init.body : undefined
67453
+ const credentials = (init && init.credentials) || (input instanceof Request ? input.credentials : 'same-origin')
67325
67454
  if (body === undefined && input instanceof Request) { try { body = await input.clone().text() } catch {} }
67326
67455
  note(url, headers)
67327
67456
  const response = await origFetch.apply(this, arguments)
67328
67457
  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') || '' }
67458
+ 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
67459
  state.found.push(entry)
67460
+ keep(headers)
67331
67461
  response.clone().text().then((t) => { entry.response = t.slice(0, 2000000) }).catch(() => {})
67332
67462
  }
67463
+ if (toBackend(url)) {
67464
+ const reply = { url: new URL(url, location.href).href, status: response.status, contentType: response.headers.get('content-type') || '', at: Date.now() }
67465
+ state.replies.push(reply)
67466
+ response.clone().text().then((t) => { reply.response = t.slice(0, 2000000) }).catch(() => { reply.response = '' })
67467
+ }
67333
67468
  return response
67334
67469
  }
67335
67470
  const X = XMLHttpRequest.prototype
@@ -67341,15 +67476,21 @@ function watchScript(origin, marker) {
67341
67476
  if (info) {
67342
67477
  note(info.url, info.headers)
67343
67478
  if (state.marker && typeof body === 'string' && body.includes(state.marker)) {
67344
- const entry = { url: info.url, method: info.method, headers: info.headers, body }
67479
+ const entry = { url: info.url, method: info.method, headers: info.headers, body, credentials: this.withCredentials ? 'include' : 'same-origin' }
67345
67480
  state.found.push(entry)
67481
+ keep(info.headers)
67346
67482
  this.addEventListener('loadend', () => { entry.status = this.status; entry.contentType = this.getResponseHeader('content-type') || ''; entry.response = String(this.responseText || '').slice(0, 2000000) })
67347
67483
  }
67484
+ if (toBackend(info.url)) {
67485
+ const reply = { url: info.url, at: Date.now() }
67486
+ state.replies.push(reply)
67487
+ this.addEventListener('loadend', () => { reply.status = this.status; reply.contentType = this.getResponseHeader('content-type') || ''; reply.response = String(this.responseText || '').slice(0, 2000000) })
67488
+ }
67348
67489
  }
67349
67490
  return send.apply(this, arguments)
67350
67491
  }
67351
67492
  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) }
67493
+ 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
67494
  return { ok: true }
67354
67495
  }`;
67355
67496
  }
@@ -67366,8 +67507,9 @@ function askScript(setup, question) {
67366
67507
  return `async () => {
67367
67508
  const ORIGIN = ${JSON.stringify(origin)}
67368
67509
  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.' }
67510
+ // The exact backend address the user approved - on the chat page's site or another (an api. address) - and no other.
67511
+ const url = new URL(${JSON.stringify(setup.backendUrl ?? new URL(setup.request.path, origin).href)})
67512
+ ${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
67513
  const state = window.__lcWebChat || { headers: {} }
67372
67514
  const headers = Object.assign({}, ${JSON.stringify(setup.request.headers)})
67373
67515
  const missing = []
@@ -67378,16 +67520,20 @@ function askScript(setup, question) {
67378
67520
  if (missing.length > 0) return { ok: false, needsActivity: missing }
67379
67521
  let response
67380
67522
  try {
67381
- response = await fetch(url.href, { method: ${JSON.stringify(setup.request.method)}, headers, body: ${JSON.stringify(fillBody(setup, question))}, credentials: 'include', redirect: 'error' })
67523
+ // Cookies or not, as the page's own request did: a cross-site API answers its page's way and no other.
67524
+ 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
67525
  } catch (e) {
67383
67526
  return { ok: false, error: 'The request failed in the page: ' + (e && e.message ? e.message : String(e)) }
67384
67527
  }
67385
- if (response.url && new URL(response.url).origin !== ORIGIN) return { ok: false, error: 'The reply came from another site; it was not used.' }
67528
+ 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
67529
  const text = await response.text()
67387
67530
  return { ok: true, status: response.status, contentType: response.headers.get('content-type') || '', text: text.slice(0, 2000000) }
67388
67531
  }`;
67389
67532
  }
67390
67533
  function typePhraseScript(origin, marker) {
67534
+ return typeTextScript(origin, marker);
67535
+ }
67536
+ function typeTextScript(origin, text2) {
67391
67537
  return `async () => {
67392
67538
  if (location.origin !== ${JSON.stringify(origin)}) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67393
67539
  const visible = (el) => el.offsetParent !== null
@@ -67395,14 +67541,27 @@ function typePhraseScript(origin, marker) {
67395
67541
  const box = boxes.sort((a, b) => b.getBoundingClientRect().width - a.getBoundingClientRect().width)[0]
67396
67542
  if (!box) return { ok: false, error: 'No message box found on the page - paste the phrase by hand.' }
67397
67543
  box.focus()
67398
- const text = ${JSON.stringify(marker)}
67399
- if (box.isContentEditable) { document.execCommand('insertText', false, text) }
67544
+ const text = ${JSON.stringify(text2)}
67545
+ if (box.isContentEditable) { document.execCommand('selectAll', false); document.execCommand('insertText', false, text) }
67400
67546
  else {
67401
67547
  const setter = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(box), 'value')?.set
67402
67548
  if (setter) setter.call(box, text); else box.value = text
67403
67549
  box.dispatchEvent(new Event('input', { bubbles: true }))
67404
67550
  }
67405
67551
  box.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', keyCode: 13, which: 13, bubbles: true }))
67552
+ await new Promise((r) => setTimeout(r, 400))
67553
+ const still = box.isContentEditable ? (box.innerText || '').trim().length > 0 : String(box.value || '').trim().length > 0
67554
+ if (still) {
67555
+ let scope = box.parentElement
67556
+ let button
67557
+ for (let i = 0; i < 6 && scope && !button; i += 1, scope = scope.parentElement) {
67558
+ const buttons = [...scope.querySelectorAll('button, [role="button"], input[type="submit"]')].filter((b) => b.offsetParent !== null && !b.disabled)
67559
+ 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)
67560
+ }
67561
+ // An app that keeps the text after sending looks the same as one that did not send: without a button to press, carry
67562
+ // on - the wait for the reply (or for the capture) says whether it went.
67563
+ if (button) button.click()
67564
+ }
67406
67565
  return { ok: true }
67407
67566
  }`;
67408
67567
  }
@@ -67424,6 +67583,21 @@ function scriptResult(text2) {
67424
67583
  return void 0;
67425
67584
  }
67426
67585
  }
67586
+ function readRepliesScript(origin) {
67587
+ return `async () => {
67588
+ if (location.origin !== ${JSON.stringify(origin)}) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67589
+ const state = window.__lcWebChat
67590
+ if (!state) return { ok: true, replies: [], pending: 0, ws: false }
67591
+ const replies = state.replies || []
67592
+ return { ok: true, replies: replies.filter((r) => r.response !== undefined), pending: replies.filter((r) => r.response === undefined).length, ws: state.wsSent === true }
67593
+ }`;
67594
+ }
67595
+ function pageTextScript(origin) {
67596
+ return `async () => {
67597
+ if (location.origin !== ${JSON.stringify(origin)}) return { ok: false, error: 'The selected page is ' + location.origin + ', not the web chat.' }
67598
+ return { ok: true, text: String(document.body ? document.body.innerText : '').slice(0, 400000) }
67599
+ }`;
67600
+ }
67427
67601
 
67428
67602
  // ../../packages/core/dist/webchat/chrome.js
67429
67603
  function isChromeDevToolsServer(toolNames) {
@@ -67455,9 +67629,25 @@ function sameOrigin(url2, origin) {
67455
67629
  return false;
67456
67630
  }
67457
67631
  }
67632
+ function explainChromeError(text2) {
67633
+ const clipped = text2.slice(0, 300);
67634
+ if (/already running for/i.test(text2)) {
67635
+ return `${clipped}
67636
+
67637
+ Another copy of the Chrome DevTools MCP server (in VS Code, Fire Code or another chat) has already started its own Chrome with that profile, and only one can. In Settings \u2192 Agents \u2192 Web chat, set "Which Chrome" to "Your own Chrome" (and switch remote debugging on once in your Chrome at chrome://inspect/#remote-debugging): every copy then uses your own Chrome, where you are signed in to the web chat. Or close the other one.`;
67638
+ }
67639
+ if (/DevToolsActivePort|Could not connect to Chrome/i.test(text2)) {
67640
+ return `${clipped}
67641
+
67642
+ The server is set to use your own Chrome, and your Chrome is not accepting it. Either: open chrome://inspect/#remote-debugging in your Chrome and switch remote debugging on (Chrome 144 or newer; your organisation may block it), then try again - or, in Settings \u2192 Agents \u2192 Web chat, set "Which Chrome" to "A Chrome it starts": the server opens a Chrome of its own (sign in to the web chat there once; it remembers) - only one app at a time can use that one.`;
67643
+ }
67644
+ return clipped;
67645
+ }
67458
67646
  async function selectWebChatPage(chrome, pageUrl) {
67459
67647
  const origin = new URL(pageUrl).origin;
67460
67648
  const listed = await chrome.call("list_pages", {});
67649
+ if (listed.isError && /already running for/i.test(listed.text))
67650
+ throw new Error(`Chrome could not start: ${explainChromeError(listed.text)}`);
67461
67651
  const existing = listed.isError ? [] : pagesIn(listed.text).filter((page) => sameOrigin(page.url, origin));
67462
67652
  const chosen = existing.find((page) => page.selected) ?? existing[0];
67463
67653
  if (chosen !== void 0) {
@@ -67466,13 +67656,13 @@ async function selectWebChatPage(chrome, pageUrl) {
67466
67656
  const key4 = names.includes("pageId") ? "pageId" : names.find((name) => /idx|index|id/i.test(name)) ?? "pageId";
67467
67657
  const selected = await chrome.call("select_page", { [key4]: chosen.id });
67468
67658
  if (selected.isError)
67469
- throw new Error(`Chrome could not select the web chat tab: ${selected.text.slice(0, 300)}`);
67659
+ throw new Error(`Chrome could not select the web chat tab: ${explainChromeError(selected.text)}`);
67470
67660
  }
67471
67661
  return chosen.id;
67472
67662
  }
67473
67663
  const opened = await chrome.call("new_page", { url: pageUrl });
67474
67664
  if (opened.isError)
67475
- throw new Error(`Chrome could not open ${pageUrl}: ${opened.text.slice(0, 300)}`);
67665
+ throw new Error(`Chrome could not open ${pageUrl}: ${explainChromeError(opened.text)}`);
67476
67666
  const now = pagesIn(opened.text).filter((page) => sameOrigin(page.url, origin));
67477
67667
  const fresh = now.find((page) => page.selected) ?? now.at(-1);
67478
67668
  if (fresh !== void 0)
@@ -67494,16 +67684,16 @@ async function runScript(chrome, source, pageId) {
67494
67684
  args["waitForStableDom"] = false;
67495
67685
  const result = await chrome.call("evaluate_script", args);
67496
67686
  if (result.isError)
67497
- throw new Error(`Chrome could not run the script: ${result.text.slice(0, 400)}`);
67687
+ throw new Error(`Chrome could not run the script: ${explainChromeError(result.text)}`);
67498
67688
  const value = result.structured ?? scriptResult(result.text);
67499
67689
  if (value === null || typeof value !== "object")
67500
67690
  throw new Error(`Chrome returned something unexpected: ${result.text.slice(0, 300)}`);
67501
67691
  return value;
67502
67692
  }
67503
- async function askWebChat(chrome, setup, question) {
67693
+ async function askWebChat(chrome, setup, question, options = {}) {
67504
67694
  const origin = new URL(setup.pageUrl).origin;
67505
67695
  const pageId = await selectWebChatPage(chrome, setup.pageUrl);
67506
- const watched = await runScript(chrome, watchScript(origin, void 0), pageId);
67696
+ const watched = await runScript(chrome, watchScript(origin, void 0, setup.backendUrl ?? new URL(setup.request.path, origin).href), pageId);
67507
67697
  if (watched["ok"] !== true)
67508
67698
  throw new Error(String(watched["error"] ?? "The web chat page could not be prepared."));
67509
67699
  const sent = await runScript(chrome, askScript(setup, question), pageId);
@@ -67517,12 +67707,72 @@ async function askWebChat(chrome, setup, question) {
67517
67707
  throw new Error(`The web chat answered HTTP ${String(status2)}: sign in to it again in Chrome, then ask again.`);
67518
67708
  if (status2 >= 400)
67519
67709
  throw new Error(`The web chat answered HTTP ${String(status2)}: ${String(sent["text"] ?? "").slice(0, 300)}`);
67710
+ options.onReply?.(String(sent["text"] ?? ""));
67520
67711
  const answer = readAnswer(String(sent["text"] ?? ""), setup.response);
67521
67712
  if (answer === void 0 || answer.trim().length === 0) {
67522
67713
  throw new Error("The answer was not where the capture found it - the web chat may have changed how it replies. Capture again in Settings \u2192 Agents \u2192 Web chat.");
67523
67714
  }
67524
67715
  return answer;
67525
67716
  }
67717
+ async function askThroughWindow(chrome, setup, question, options = {}) {
67718
+ const sleep3 = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
67719
+ const timeout = options.timeoutMs ?? 3e5;
67720
+ const origin = new URL(setup.pageUrl).origin;
67721
+ const backend = setup.backendUrl ?? new URL(setup.request.path, origin).href;
67722
+ const pageId = await selectWebChatPage(chrome, setup.pageUrl);
67723
+ const before = String((await runScript(chrome, pageTextScript(origin), pageId))["text"] ?? "");
67724
+ const watched = await runScript(chrome, watchScript(origin, void 0, backend), pageId);
67725
+ if (watched["ok"] !== true)
67726
+ throw new Error(String(watched["error"] ?? "The web chat page could not be prepared."));
67727
+ const typed = await runScript(chrome, typeTextScript(origin, question), pageId);
67728
+ if (typed["ok"] !== true)
67729
+ throw new Error(String(typed["error"] ?? "The question could not be typed into the web chat."));
67730
+ const started = Date.now();
67731
+ let lastText = "";
67732
+ let stableSince = Date.now();
67733
+ while (Date.now() - started < timeout) {
67734
+ await sleep3(1e3);
67735
+ const read = await runScript(chrome, readRepliesScript(origin), pageId);
67736
+ const replies = Array.isArray(read["replies"]) ? read["replies"] : [];
67737
+ const reply = replies.at(-1);
67738
+ if (reply !== void 0) {
67739
+ const status2 = Number(reply.status ?? 0);
67740
+ if (status2 === 401 || status2 === 403)
67741
+ throw new Error(`The web chat answered HTTP ${String(status2)}: sign in to it again in Chrome, then ask again.`);
67742
+ if (status2 >= 400)
67743
+ throw new Error(`The web chat answered HTTP ${String(status2)}: ${String(reply.response ?? "").slice(0, 300)}`);
67744
+ options.onReply?.(String(reply.response ?? ""));
67745
+ const answer = readAnswer(String(reply.response ?? ""), setup.response);
67746
+ if (answer !== void 0 && answer.trim().length > 0)
67747
+ return { answer, from: "reply" };
67748
+ 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.");
67749
+ }
67750
+ const waitingForRequest = Number(read["pending"] ?? 0) > 0;
67751
+ if (!waitingForRequest && Date.now() - started > 5e3) {
67752
+ const now = String((await runScript(chrome, pageTextScript(origin), pageId))["text"] ?? "");
67753
+ if (now !== lastText) {
67754
+ lastText = now;
67755
+ stableSince = Date.now();
67756
+ } else if (Date.now() - stableSince >= (options.quietMs ?? 4e3)) {
67757
+ const added = newText(before, now, question);
67758
+ if (added.length > 0)
67759
+ return { answer: added, from: "screen" };
67760
+ }
67761
+ }
67762
+ }
67763
+ throw new Error(`No answer from the web chat within ${String(Math.round(timeout / 1e3))} seconds. Look at the web chat tab in Chrome.`);
67764
+ }
67765
+ function newText(before, after, question) {
67766
+ let start = 0;
67767
+ while (start < before.length && start < after.length && before[start] === after[start])
67768
+ start += 1;
67769
+ let added = after.slice(start);
67770
+ const q = question.trim();
67771
+ const at2 = q.length > 0 ? added.indexOf(q) : -1;
67772
+ if (at2 >= 0)
67773
+ added = added.slice(at2 + q.length);
67774
+ return added.trim();
67775
+ }
67526
67776
 
67527
67777
  // ../../packages/core/dist/webchat/capture.js
67528
67778
  function capturePhrase(random2 = Math.random) {
@@ -67540,10 +67790,7 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67540
67790
  refused.push(`${entry.url}: not an address.`);
67541
67791
  continue;
67542
67792
  }
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
- }
67793
+ const window = url2.origin !== origin;
67547
67794
  const contentType2 = Object.entries(entry.headers).find(([name]) => name.toLowerCase() === "content-type")?.[1];
67548
67795
  const template = bodyTemplate(entry.body, marker, contentType2);
67549
67796
  if (template === void 0)
@@ -67558,10 +67805,22 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67558
67805
  const setup = {
67559
67806
  version: 1,
67560
67807
  pageUrl,
67561
- request: { path: `${url2.pathname}${url2.search}`, method: entry.method.toUpperCase(), headers: plain, fromPage, body: template.body, encoding: template.encoding },
67808
+ request: {
67809
+ path: `${url2.pathname}${url2.search}`,
67810
+ method: entry.method.toUpperCase(),
67811
+ headers: plain,
67812
+ fromPage,
67813
+ body: template.body,
67814
+ encoding: template.encoding,
67815
+ ...entry.credentials === "include" || entry.credentials === "same-origin" || entry.credentials === "omit" ? { credentials: entry.credentials } : {}
67816
+ },
67562
67817
  response: answer.spec,
67563
67818
  ...model !== void 0 ? { model } : {},
67564
- capturedAt: now.toISOString()
67819
+ capturedAt: now.toISOString(),
67820
+ // Sent directly to the approved address even on another site (asked for: "even if the api site is different, it
67821
+ // should work if I approved it"); the chat window is the fallback when the backend refuses it.
67822
+ method: "replay",
67823
+ backendUrl: `${url2.origin}${url2.pathname}${url2.search}`
67565
67824
  };
67566
67825
  candidates.push({
67567
67826
  backend: `${url2.origin}${url2.pathname}${url2.search}`,
@@ -67569,6 +67828,7 @@ function candidatesFrom(found2, pageUrl, marker, now = /* @__PURE__ */ new Date(
67569
67828
  ...model !== void 0 ? { model } : {},
67570
67829
  answerPreview: answer.answer.slice(0, 300),
67571
67830
  fromPage,
67831
+ window,
67572
67832
  setup
67573
67833
  });
67574
67834
  }
@@ -67590,7 +67850,12 @@ function createAskWebChatTool(deps) {
67590
67850
  const where = destination === void 0 ? "the web chat (not set up yet)" : `${destination.backend}${destination.model !== void 0 ? ` (model ${destination.model})` : ""}`;
67591
67851
  return {
67592
67852
  kind: "text",
67593
- text: `Sent through your Chrome, signed in as you, to the web chat's approved backend address only:
67853
+ 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:
67854
+ ${where}
67855
+
67856
+ The exact text typed:
67857
+
67858
+ ${params3.question}` : `Sent through your Chrome, signed in as you, to the web chat's approved backend address only:
67594
67859
  ${where}
67595
67860
 
67596
67861
  The exact text sent:
@@ -91371,9 +91636,9 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91371
91636
  const setup = cachedWebChat ?? await loadWebChat();
91372
91637
  if (setup === void 0)
91373
91638
  return void 0;
91374
- const backend = new URL(setup.request.path, new URL(setup.pageUrl).origin).href;
91639
+ const backend = setup.backendUrl ?? new URL(setup.request.path, new URL(setup.pageUrl).origin).href;
91375
91640
  const model = setup.modelOverride ?? setup.model;
91376
- return { backend, ...model !== void 0 ? { model } : {} };
91641
+ return { backend, method: setup.method ?? "replay", ...model !== void 0 ? { model } : {} };
91377
91642
  },
91378
91643
  problem: async () => {
91379
91644
  const setup = cachedWebChat ?? await loadWebChat();
@@ -91384,9 +91649,73 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91384
91649
  const server = webChatServer();
91385
91650
  if (setup === void 0 || server === void 0)
91386
91651
  throw new Error("The web chat or its Chrome DevTools MCP server is not available.");
91387
- return askWebChat(chromeAccess(server), setup, question);
91652
+ const throughWindow = async (why) => {
91653
+ const read = await askThroughWindow(chromeAccess(server), setup, question);
91654
+ const how = why === void 0 ? "" : `
91655
+
91656
+ (Sent through the chat window: the direct request did not work - ${why})`;
91657
+ return read.from === "screen" ? `${read.answer}
91658
+
91659
+ (Read off the web chat's screen: no reply from its backend was seen.)${how}` : `${read.answer}${how}`;
91660
+ };
91661
+ if (setup.method === "window")
91662
+ return throughWindow();
91663
+ try {
91664
+ return await askWebChat(chromeAccess(server), setup, question);
91665
+ } catch (error51) {
91666
+ const message6 = error51 instanceof Error ? error51.message : String(error51);
91667
+ if (/HTTP 40[13]/.test(message6) || /not where the capture found it/.test(message6))
91668
+ throw error51;
91669
+ logger.info(`web chat: the direct request did not work (${message6}); trying the chat window`);
91670
+ return throughWindow(message6);
91671
+ }
91388
91672
  }
91389
91673
  };
91674
+ let webChatTesting = false;
91675
+ async function testWebChat() {
91676
+ if (webChatTesting)
91677
+ return;
91678
+ webChatTesting = true;
91679
+ try {
91680
+ const setup = cachedWebChat ?? await loadWebChat();
91681
+ const server = webChatServer();
91682
+ const results = [];
91683
+ const fail = (text2) => {
91684
+ post({ type: "webChatTest", results: [{ way: "direct", ok: false, text: text2, ms: 0 }, { way: "window", ok: false, text: text2, ms: 0 }] });
91685
+ };
91686
+ if (setup === void 0)
91687
+ return fail("The web chat is not set up.");
91688
+ if (server === void 0)
91689
+ return fail("The Chrome DevTools MCP server chosen for the web chat is not connected.");
91690
+ const problem = await webChatProblem(setup.pageUrl, server);
91691
+ if (problem !== void 0 && problem.length > 0)
91692
+ return fail(problem);
91693
+ const question = "Reply with the single word: ready";
91694
+ const clip3 = (text2) => text2.length > 300 ? `${text2.slice(0, 300)}\u2026` : text2;
91695
+ post({ type: "webChatTest", running: "direct" });
91696
+ let started = Date.now();
91697
+ let reply;
91698
+ const shape = () => reply === void 0 ? {} : { shape: replyShape(reply) };
91699
+ try {
91700
+ const answer = await askWebChat(chromeAccess(server), setup, question, { onReply: (text2) => reply = text2 });
91701
+ results.push({ way: "direct", ok: true, text: clip3(answer), ms: Date.now() - started, ...shape() });
91702
+ } catch (error51) {
91703
+ results.push({ way: "direct", ok: false, text: error51 instanceof Error ? error51.message : String(error51), ms: Date.now() - started, ...shape() });
91704
+ }
91705
+ post({ type: "webChatTest", results, running: "window" });
91706
+ started = Date.now();
91707
+ reply = void 0;
91708
+ try {
91709
+ const read = await askThroughWindow(chromeAccess(server), setup, question, { onReply: (text2) => reply = text2 });
91710
+ results.push({ way: "window", ok: true, text: clip3(read.answer), ms: Date.now() - started, from: read.from, ...shape() });
91711
+ } catch (error51) {
91712
+ results.push({ way: "window", ok: false, text: error51 instanceof Error ? error51.message : String(error51), ms: Date.now() - started, ...shape() });
91713
+ }
91714
+ post({ type: "webChatTest", results });
91715
+ } finally {
91716
+ webChatTesting = false;
91717
+ }
91718
+ }
91390
91719
  async function postWebChat(message6) {
91391
91720
  const setup = await loadWebChat();
91392
91721
  const servers = chromeServers();
@@ -91396,7 +91725,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91396
91725
  ...setup !== void 0 ? {
91397
91726
  setup: {
91398
91727
  pageUrl: setup.pageUrl,
91399
- backend: new URL(setup.request.path, new URL(setup.pageUrl).origin).href,
91728
+ backend: setup.backendUrl ?? new URL(setup.request.path, new URL(setup.pageUrl).origin).href,
91729
+ via: setup.method ?? "replay",
91400
91730
  method: setup.request.method,
91401
91731
  ...setup.model !== void 0 ? { model: setup.model } : {},
91402
91732
  ...setup.modelOverride !== void 0 ? { modelOverride: setup.modelOverride } : {},
@@ -91405,13 +91735,37 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91405
91735
  }
91406
91736
  } : {},
91407
91737
  chrome: {
91408
- servers: await Promise.all(servers.map(async (name) => ({ name, problems: await chromeProblems(name), ...await npxRegistryFor(name) }))),
91738
+ servers: await Promise.all(servers.map(async (name) => {
91739
+ const problems = await chromeProblems(name);
91740
+ const mode = chromeMode(mcp.serverConfig(name));
91741
+ return { name, problems, fixable: problems.length > 0 && fixChromeServer(mcp.serverConfig(name)) !== void 0, ...mode !== void 0 ? { mode } : {}, ...await npxRegistryFor(name) };
91742
+ })),
91409
91743
  ...setup?.server !== void 0 ? { chosen: setup.server } : {}
91410
91744
  },
91411
91745
  ...setup !== void 0 ? { hostProblem: await hostProblem(setup.pageUrl).catch((error51) => String(error51)) ?? "" } : {},
91412
91746
  ...message6 !== void 0 ? { message: message6 } : {}
91413
91747
  });
91414
91748
  }
91749
+ async function fixWebChatServer(server) {
91750
+ const fixed = fixChromeServer(mcp.serverConfig(server));
91751
+ if (fixed === void 0) {
91752
+ await postWebChat(`"${server}" cannot be fixed automatically - change it in Settings \u2192 MCP.`);
91753
+ return;
91754
+ }
91755
+ await handleSaveMcpServer(server, server, fixed);
91756
+ const args = fixed.args ?? [];
91757
+ await postWebChat(`Fixed "${server}": ${fixed.command} ${args.join(" ")}. It is restarting with these options.`);
91758
+ }
91759
+ async function setWebChatChrome(server, mode) {
91760
+ const config2 = mcp.serverConfig(server);
91761
+ const changed = config2 === void 0 ? void 0 : withChromeMode(config2, mode);
91762
+ if (changed === void 0) {
91763
+ await postWebChat(`"${server}" names a Chrome by address - change it in Settings \u2192 MCP.`);
91764
+ return;
91765
+ }
91766
+ await handleSaveMcpServer(server, server, changed);
91767
+ await postWebChat(mode === "own" ? `"${server}" now uses your own Chrome. Switch remote debugging on once at chrome://inspect/#remote-debugging in that Chrome (Chrome 144 or newer).` : `"${server}" now opens a Chrome of its own. Sign in to the web chat in that Chrome once; it remembers. Only one app at a time can use it.`);
91768
+ }
91415
91769
  function stopWebChatCapture() {
91416
91770
  if (webChatCapture?.timer !== void 0)
91417
91771
  clearInterval(webChatCapture.timer);
@@ -91482,7 +91836,8 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
91482
91836
  method: candidate.method,
91483
91837
  ...candidate.model !== void 0 ? { model: candidate.model } : {},
91484
91838
  answerPreview: candidate.answerPreview,
91485
- fromPage: candidate.fromPage
91839
+ fromPage: candidate.fromPage,
91840
+ window: candidate.window
91486
91841
  })),
91487
91842
  refused
91488
91843
  });
@@ -99747,6 +100102,12 @@ ${answer.slice(0, 16e3)}` } }, (d) => d.best !== void 0 && d.best.probability >=
99747
100102
  await writeWebChatSetup(webChatFile, next);
99748
100103
  await postWebChat("Saved.");
99749
100104
  })();
100105
+ } else if (message6.type === "testWebChat") {
100106
+ reportFailure("testWebChat", testWebChat());
100107
+ } else if (message6.type === "setWebChatChrome") {
100108
+ reportFailure("setWebChatChrome", setWebChatChrome(message6.server, message6.mode));
100109
+ } else if (message6.type === "fixWebChatServer") {
100110
+ reportFailure("fixWebChatServer", fixWebChatServer(message6.server));
99750
100111
  } else if (message6.type === "clearWebChat") {
99751
100112
  stopWebChatCapture();
99752
100113
  if (webChatFile !== void 0)
@@ -106055,9 +106416,25 @@ transcript was written.
106055
106416
  "second opinion",
106056
106417
  "capture",
106057
106418
  "backend address",
106058
- "bank",
106419
+ "chat window",
106420
+ "another site",
106421
+ "on another site",
106422
+ "test both ways",
106423
+ "backup way",
106424
+ "primary way",
106425
+ "fix it for me",
106426
+ "cannot be used yet",
106427
+ "must include",
106428
+ "which chrome",
106429
+ "devtoolsactiveport",
106430
+ "could not connect to chrome",
106431
+ "remote debugging",
106432
+ "already running",
106433
+ "isolated",
106434
+ "wrong answer",
106435
+ "answer extraction",
106059
106436
  "inside the network",
106060
- "outside the bank"
106437
+ "outside the organisation"
106061
106438
  ],
106062
106439
  body: `
106063
106440
  **\`ask_web_chat\` consults the model behind your organisation's internal web chat** - for when a model (Gemini, say) is
@@ -106069,8 +106446,18 @@ DevTools MCP server is connected, and never on a shared server.
106069
106446
  1. **Give the web chat a Chrome DevTools MCP server of its own** - a second entry in Settings \u2192 MCP under its own name
106070
106447
  (e.g. chrome-webchat), so any Chrome server you already use is left exactly as it is - and choose it in the Web chat
106071
106448
  panel. Add it with \`--autoConnect\`, \`--no-usage-statistics\` and
106072
- \`--no-performance-crux\` (the panel shows the entry to paste), and allow it in Chrome at
106073
- chrome://inspect/#remote-debugging. Either installed once (\`npm i -g chrome-devtools-mcp\`), or run with **npx**
106449
+ \`--no-performance-crux\`. Typed on one line, or the whole command line typed into Command, they are split into
106450
+ separate arguments when the server starts (a line with quotes or a backslash is left as typed). When the panel says
106451
+ the server **cannot be used yet**, press **Fix it for me**: it adds what is missing to that server's entry (each
106452
+ option on its own line, npx pinned to the tested version) and restarts it. The panel shows the entry to paste.
106453
+ **Which Chrome** (in the panel, once a server is chosen):
106454
+ - **Your own Chrome** (\`--autoConnect\`): the Chrome you have open, already signed in; VS Code and Fire Code can
106455
+ both use it. Needs Chrome 144 or newer with remote debugging switched on once at chrome://inspect/#remote-debugging
106456
+ - otherwise it fails with "Could not connect to Chrome ... DevToolsActivePort". Your organisation may block it.
106457
+ - **A Chrome it starts**: the server opens a Chrome with a profile of its own - sign in to the web chat there once
106458
+ and it remembers. Only one app at a time can have it ("The browser is already running ... Use --isolated" means
106459
+ another app has it).
106460
+ Either installed once (\`npm i -g chrome-devtools-mcp\`), or run with **npx**
106074
106461
  and a pinned version (\`chrome-devtools-mcp@1.13.0\`, not \`@latest\`); the panel shows where npx downloads it from
106075
106462
  (\`npm config get registry\` - it should be your organisation's registry).
106076
106463
  2. Type the web chat page's address and press **Capture**. In the tab Light Code selects, start a new chat, choose the
@@ -106078,6 +106465,25 @@ DevTools MCP server is connected, and never on a shared server.
106078
106465
  3. Light Code shows the request that carried it: **the backend address**, the model, and the start of the answer it read.
106079
106466
  **Use this** approves it - only that backend address is ever used afterwards. **Capture again** to change it.
106080
106467
 
106468
+ **Two ways a question is sent, wherever the backend is (its own site or another, such as an \`api.\` address):**
106469
+ - **Directly (the primary way):** Light Code sends the approved request itself, from inside the chat page, signed in as
106470
+ you, to exactly the approved address - with cookies or without, as the page's own request was.
106471
+ - **Through the chat window (the backup):** when the direct request is refused or fails, the question is typed into the
106472
+ chat and sent, as you would, and the answer is read from the page's own reply from the approved backend. A path part
106473
+ that is plainly an id (a conversation id) may differ; anything else must match. When no such reply is seen (a chat
106474
+ over a WebSocket), the answer is read off the screen once it stops changing, and the result says so. A sign-in
106475
+ refusal (401/403) is not retried this way - sign in to the web chat in Chrome.
106476
+ - **Test both ways** (beside Capture again) asks one short question each way and shows which works here, how long
106477
+ each took, the answer, and what the reply was made of (its fields and sizes, never its text) - send that line if the
106478
+ answer looks wrong.
106479
+
106480
+ **If the answer is wrong** (a run of words like \`chat_idprogresscompletion\u2026\`): the answer was read from the field that
106481
+ labels each event. Since 0.229.0 such fields are never taken, ids rank below words, and a capture saved earlier is read
106482
+ afresh - no need to capture again. **"The browser is already running \u2026 Use --isolated"**: this copy of the Chrome
106483
+ DevTools server is starting a Chrome of its own while another copy (VS Code's, another chat's) already has - give it
106484
+ \`--autoConnect\` on its own line so every copy uses your own Chrome. \`--isolated\` would start a Chrome that is not
106485
+ signed in to the web chat.
106486
+
106081
106487
  **It cannot go outside the organisation, by rule - each checked before every consultation, and nothing is sent when one fails:**
106082
106488
  - Light Code opens no connection itself: the request runs inside the chat page, in your Chrome, to the approved
106083
106489
  backend address on the chat's own site only, with redirects refused; a reply from another site is not used. Your session