@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/server.js CHANGED
@@ -499,14 +499,14 @@ var require_util = __commonJS({
499
499
  }
500
500
  const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
501
501
  let origin = url2.origin != null ? url2.origin : `${url2.protocol}//${url2.hostname}:${port}`;
502
- let path30 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
502
+ let path31 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
503
503
  if (origin.endsWith("/")) {
504
504
  origin = origin.substring(0, origin.length - 1);
505
505
  }
506
- if (path30 && !path30.startsWith("/")) {
507
- path30 = `/${path30}`;
506
+ if (path31 && !path31.startsWith("/")) {
507
+ path31 = `/${path31}`;
508
508
  }
509
- url2 = new URL(origin + path30);
509
+ url2 = new URL(origin + path31);
510
510
  }
511
511
  return url2;
512
512
  }
@@ -2120,20 +2120,20 @@ var require_parseParams = __commonJS({
2120
2120
  var require_basename = __commonJS({
2121
2121
  "../../node_modules/.pnpm/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/basename.js"(exports, module) {
2122
2122
  "use strict";
2123
- module.exports = function basename(path30) {
2124
- if (typeof path30 !== "string") {
2123
+ module.exports = function basename(path31) {
2124
+ if (typeof path31 !== "string") {
2125
2125
  return "";
2126
2126
  }
2127
- for (var i = path30.length - 1; i >= 0; --i) {
2128
- switch (path30.charCodeAt(i)) {
2127
+ for (var i = path31.length - 1; i >= 0; --i) {
2128
+ switch (path31.charCodeAt(i)) {
2129
2129
  case 47:
2130
2130
  // '/'
2131
2131
  case 92:
2132
- path30 = path30.slice(i + 1);
2133
- return path30 === ".." || path30 === "." ? "" : path30;
2132
+ path31 = path31.slice(i + 1);
2133
+ return path31 === ".." || path31 === "." ? "" : path31;
2134
2134
  }
2135
2135
  }
2136
- return path30 === ".." || path30 === "." ? "" : path30;
2136
+ return path31 === ".." || path31 === "." ? "" : path31;
2137
2137
  };
2138
2138
  }
2139
2139
  });
@@ -5163,7 +5163,7 @@ var require_request = __commonJS({
5163
5163
  }
5164
5164
  var Request = class _Request {
5165
5165
  constructor(origin, {
5166
- path: path30,
5166
+ path: path31,
5167
5167
  method,
5168
5168
  body,
5169
5169
  headers,
@@ -5177,11 +5177,11 @@ var require_request = __commonJS({
5177
5177
  throwOnError,
5178
5178
  expectContinue
5179
5179
  }, handler) {
5180
- if (typeof path30 !== "string") {
5180
+ if (typeof path31 !== "string") {
5181
5181
  throw new InvalidArgumentError("path must be a string");
5182
- } else if (path30[0] !== "/" && !(path30.startsWith("http://") || path30.startsWith("https://")) && method !== "CONNECT") {
5182
+ } else if (path31[0] !== "/" && !(path31.startsWith("http://") || path31.startsWith("https://")) && method !== "CONNECT") {
5183
5183
  throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
5184
- } else if (invalidPathRegex.exec(path30) !== null) {
5184
+ } else if (invalidPathRegex.exec(path31) !== null) {
5185
5185
  throw new InvalidArgumentError("invalid request path");
5186
5186
  }
5187
5187
  if (typeof method !== "string") {
@@ -5244,7 +5244,7 @@ var require_request = __commonJS({
5244
5244
  this.completed = false;
5245
5245
  this.aborted = false;
5246
5246
  this.upgrade = upgrade || null;
5247
- this.path = query ? util.buildURL(path30, query) : path30;
5247
+ this.path = query ? util.buildURL(path31, query) : path31;
5248
5248
  this.origin = origin;
5249
5249
  this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
5250
5250
  this.blocking = blocking == null ? false : blocking;
@@ -6252,9 +6252,9 @@ var require_RedirectHandler = __commonJS({
6252
6252
  return this.handler.onHeaders(statusCode, headers, resume, statusText);
6253
6253
  }
6254
6254
  const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
6255
- const path30 = search ? `${pathname}${search}` : pathname;
6255
+ const path31 = search ? `${pathname}${search}` : pathname;
6256
6256
  this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
6257
- this.opts.path = path30;
6257
+ this.opts.path = path31;
6258
6258
  this.opts.origin = origin;
6259
6259
  this.opts.maxRedirections = 0;
6260
6260
  this.opts.query = null;
@@ -7494,7 +7494,7 @@ var require_client = __commonJS({
7494
7494
  writeH2(client, client[kHTTP2Session], request);
7495
7495
  return;
7496
7496
  }
7497
- const { body, method, path: path30, host, upgrade, headers, blocking, reset } = request;
7497
+ const { body, method, path: path31, host, upgrade, headers, blocking, reset } = request;
7498
7498
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
7499
7499
  if (body && typeof body.read === "function") {
7500
7500
  body.read(0);
@@ -7544,7 +7544,7 @@ var require_client = __commonJS({
7544
7544
  if (blocking) {
7545
7545
  socket[kBlocking] = true;
7546
7546
  }
7547
- let header = `${method} ${path30} HTTP/1.1\r
7547
+ let header = `${method} ${path31} HTTP/1.1\r
7548
7548
  `;
7549
7549
  if (typeof host === "string") {
7550
7550
  header += `host: ${host}\r
@@ -7607,7 +7607,7 @@ upgrade: ${upgrade}\r
7607
7607
  return true;
7608
7608
  }
7609
7609
  function writeH2(client, session, request) {
7610
- const { body, method, path: path30, host, upgrade, expectContinue, signal, headers: reqHeaders } = request;
7610
+ const { body, method, path: path31, host, upgrade, expectContinue, signal, headers: reqHeaders } = request;
7611
7611
  let headers;
7612
7612
  if (typeof reqHeaders === "string") headers = Request[kHTTP2CopyHeaders](reqHeaders.trim());
7613
7613
  else headers = reqHeaders;
@@ -7650,7 +7650,7 @@ upgrade: ${upgrade}\r
7650
7650
  });
7651
7651
  return true;
7652
7652
  }
7653
- headers[HTTP2_HEADER_PATH] = path30;
7653
+ headers[HTTP2_HEADER_PATH] = path31;
7654
7654
  headers[HTTP2_HEADER_SCHEME] = "https";
7655
7655
  const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
7656
7656
  if (body && typeof body.read === "function") {
@@ -9890,20 +9890,20 @@ var require_mock_utils = __commonJS({
9890
9890
  }
9891
9891
  return true;
9892
9892
  }
9893
- function safeUrl(path30) {
9894
- if (typeof path30 !== "string") {
9895
- return path30;
9893
+ function safeUrl(path31) {
9894
+ if (typeof path31 !== "string") {
9895
+ return path31;
9896
9896
  }
9897
- const pathSegments = path30.split("?");
9897
+ const pathSegments = path31.split("?");
9898
9898
  if (pathSegments.length !== 2) {
9899
- return path30;
9899
+ return path31;
9900
9900
  }
9901
9901
  const qp = new URLSearchParams(pathSegments.pop());
9902
9902
  qp.sort();
9903
9903
  return [...pathSegments, qp.toString()].join("?");
9904
9904
  }
9905
- function matchKey(mockDispatch2, { path: path30, method, body, headers }) {
9906
- const pathMatch = matchValue(mockDispatch2.path, path30);
9905
+ function matchKey(mockDispatch2, { path: path31, method, body, headers }) {
9906
+ const pathMatch = matchValue(mockDispatch2.path, path31);
9907
9907
  const methodMatch = matchValue(mockDispatch2.method, method);
9908
9908
  const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
9909
9909
  const headersMatch = matchHeaders(mockDispatch2, headers);
@@ -9921,7 +9921,7 @@ var require_mock_utils = __commonJS({
9921
9921
  function getMockDispatch(mockDispatches, key) {
9922
9922
  const basePath = key.query ? buildURL(key.path, key.query) : key.path;
9923
9923
  const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
9924
- let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path30 }) => matchValue(safeUrl(path30), resolvedPath));
9924
+ let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path31 }) => matchValue(safeUrl(path31), resolvedPath));
9925
9925
  if (matchedMockDispatches.length === 0) {
9926
9926
  throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
9927
9927
  }
@@ -9958,9 +9958,9 @@ var require_mock_utils = __commonJS({
9958
9958
  }
9959
9959
  }
9960
9960
  function buildKey(opts) {
9961
- const { path: path30, method, body, headers, query } = opts;
9961
+ const { path: path31, method, body, headers, query } = opts;
9962
9962
  return {
9963
- path: path30,
9963
+ path: path31,
9964
9964
  method,
9965
9965
  body,
9966
9966
  headers,
@@ -10409,10 +10409,10 @@ var require_pending_interceptors_formatter = __commonJS({
10409
10409
  }
10410
10410
  format(pendingInterceptors) {
10411
10411
  const withPrettyHeaders = pendingInterceptors.map(
10412
- ({ method, path: path30, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
10412
+ ({ method, path: path31, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
10413
10413
  Method: method,
10414
10414
  Origin: origin,
10415
- Path: path30,
10415
+ Path: path31,
10416
10416
  "Status code": statusCode,
10417
10417
  Persistent: persist ? "\u2705" : "\u274C",
10418
10418
  Invocations: timesInvoked,
@@ -15032,8 +15032,8 @@ var require_util6 = __commonJS({
15032
15032
  }
15033
15033
  }
15034
15034
  }
15035
- function validateCookiePath(path30) {
15036
- for (const char of path30) {
15035
+ function validateCookiePath(path31) {
15036
+ for (const char of path31) {
15037
15037
  const code = char.charCodeAt(0);
15038
15038
  if (code < 33 || char === ";") {
15039
15039
  throw new Error("Invalid cookie path");
@@ -16713,11 +16713,11 @@ var require_undici = __commonJS({
16713
16713
  if (typeof opts.path !== "string") {
16714
16714
  throw new InvalidArgumentError("invalid opts.path");
16715
16715
  }
16716
- let path30 = opts.path;
16716
+ let path31 = opts.path;
16717
16717
  if (!opts.path.startsWith("/")) {
16718
- path30 = `/${path30}`;
16718
+ path31 = `/${path31}`;
16719
16719
  }
16720
- url2 = new URL(util.parseOrigin(url2).origin + path30);
16720
+ url2 = new URL(util.parseOrigin(url2).origin + path31);
16721
16721
  } else {
16722
16722
  if (!opts) {
16723
16723
  opts = typeof url2 === "object" ? url2 : {};
@@ -19988,8 +19988,8 @@ var require_utils2 = __commonJS({
19988
19988
  }
19989
19989
  return ind;
19990
19990
  }
19991
- function removeDotSegments(path30) {
19992
- let input = path30;
19991
+ function removeDotSegments(path31) {
19992
+ let input = path31;
19993
19993
  const output = [];
19994
19994
  let nextSlash = -1;
19995
19995
  let len = 0;
@@ -20241,8 +20241,8 @@ var require_schemes = __commonJS({
20241
20241
  wsComponent.secure = void 0;
20242
20242
  }
20243
20243
  if (wsComponent.resourceName) {
20244
- const [path30, query] = wsComponent.resourceName.split("?");
20245
- wsComponent.path = path30 && path30 !== "/" ? path30 : void 0;
20244
+ const [path31, query] = wsComponent.resourceName.split("?");
20245
+ wsComponent.path = path31 && path31 !== "/" ? path31 : void 0;
20246
20246
  wsComponent.query = query;
20247
20247
  wsComponent.resourceName = void 0;
20248
20248
  }
@@ -23641,12 +23641,12 @@ var require_dist = __commonJS({
23641
23641
  throw new Error(`Unknown format "${name}"`);
23642
23642
  return f;
23643
23643
  };
23644
- function addFormats(ajv, list, fs24, exportName) {
23644
+ function addFormats(ajv, list, fs25, exportName) {
23645
23645
  var _a3;
23646
23646
  var _b;
23647
23647
  (_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
23648
23648
  for (const f of list)
23649
- ajv.addFormat(f, fs24[f]);
23649
+ ajv.addFormat(f, fs25[f]);
23650
23650
  }
23651
23651
  module.exports = exports = formatsPlugin;
23652
23652
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -23659,8 +23659,8 @@ var require_windows = __commonJS({
23659
23659
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
23660
23660
  module.exports = isexe;
23661
23661
  isexe.sync = sync;
23662
- var fs24 = __require("fs");
23663
- function checkPathExt(path30, options) {
23662
+ var fs25 = __require("fs");
23663
+ function checkPathExt(path31, options) {
23664
23664
  var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
23665
23665
  if (!pathext) {
23666
23666
  return true;
@@ -23671,25 +23671,25 @@ var require_windows = __commonJS({
23671
23671
  }
23672
23672
  for (var i = 0; i < pathext.length; i++) {
23673
23673
  var p = pathext[i].toLowerCase();
23674
- if (p && path30.substr(-p.length).toLowerCase() === p) {
23674
+ if (p && path31.substr(-p.length).toLowerCase() === p) {
23675
23675
  return true;
23676
23676
  }
23677
23677
  }
23678
23678
  return false;
23679
23679
  }
23680
- function checkStat(stat, path30, options) {
23680
+ function checkStat(stat, path31, options) {
23681
23681
  if (!stat.isSymbolicLink() && !stat.isFile()) {
23682
23682
  return false;
23683
23683
  }
23684
- return checkPathExt(path30, options);
23684
+ return checkPathExt(path31, options);
23685
23685
  }
23686
- function isexe(path30, options, cb) {
23687
- fs24.stat(path30, function(er, stat) {
23688
- cb(er, er ? false : checkStat(stat, path30, options));
23686
+ function isexe(path31, options, cb) {
23687
+ fs25.stat(path31, function(er, stat) {
23688
+ cb(er, er ? false : checkStat(stat, path31, options));
23689
23689
  });
23690
23690
  }
23691
- function sync(path30, options) {
23692
- return checkStat(fs24.statSync(path30), path30, options);
23691
+ function sync(path31, options) {
23692
+ return checkStat(fs25.statSync(path31), path31, options);
23693
23693
  }
23694
23694
  }
23695
23695
  });
@@ -23699,14 +23699,14 @@ var require_mode = __commonJS({
23699
23699
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
23700
23700
  module.exports = isexe;
23701
23701
  isexe.sync = sync;
23702
- var fs24 = __require("fs");
23703
- function isexe(path30, options, cb) {
23704
- fs24.stat(path30, function(er, stat) {
23702
+ var fs25 = __require("fs");
23703
+ function isexe(path31, options, cb) {
23704
+ fs25.stat(path31, function(er, stat) {
23705
23705
  cb(er, er ? false : checkStat(stat, options));
23706
23706
  });
23707
23707
  }
23708
- function sync(path30, options) {
23709
- return checkStat(fs24.statSync(path30), options);
23708
+ function sync(path31, options) {
23709
+ return checkStat(fs25.statSync(path31), options);
23710
23710
  }
23711
23711
  function checkStat(stat, options) {
23712
23712
  return stat.isFile() && checkMode(stat, options);
@@ -23730,7 +23730,7 @@ var require_mode = __commonJS({
23730
23730
  // ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
23731
23731
  var require_isexe = __commonJS({
23732
23732
  "../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
23733
- var fs24 = __require("fs");
23733
+ var fs25 = __require("fs");
23734
23734
  var core;
23735
23735
  if (process.platform === "win32" || global.TESTING_WINDOWS) {
23736
23736
  core = require_windows();
@@ -23739,7 +23739,7 @@ var require_isexe = __commonJS({
23739
23739
  }
23740
23740
  module.exports = isexe;
23741
23741
  isexe.sync = sync;
23742
- function isexe(path30, options, cb) {
23742
+ function isexe(path31, options, cb) {
23743
23743
  if (typeof options === "function") {
23744
23744
  cb = options;
23745
23745
  options = {};
@@ -23749,7 +23749,7 @@ var require_isexe = __commonJS({
23749
23749
  throw new TypeError("callback not provided");
23750
23750
  }
23751
23751
  return new Promise(function(resolve, reject2) {
23752
- isexe(path30, options || {}, function(er, is) {
23752
+ isexe(path31, options || {}, function(er, is) {
23753
23753
  if (er) {
23754
23754
  reject2(er);
23755
23755
  } else {
@@ -23758,7 +23758,7 @@ var require_isexe = __commonJS({
23758
23758
  });
23759
23759
  });
23760
23760
  }
23761
- core(path30, options || {}, function(er, is) {
23761
+ core(path31, options || {}, function(er, is) {
23762
23762
  if (er) {
23763
23763
  if (er.code === "EACCES" || options && options.ignoreErrors) {
23764
23764
  er = null;
@@ -23768,9 +23768,9 @@ var require_isexe = __commonJS({
23768
23768
  cb(er, is);
23769
23769
  });
23770
23770
  }
23771
- function sync(path30, options) {
23771
+ function sync(path31, options) {
23772
23772
  try {
23773
- return core.sync(path30, options || {});
23773
+ return core.sync(path31, options || {});
23774
23774
  } catch (er) {
23775
23775
  if (options && options.ignoreErrors || er.code === "EACCES") {
23776
23776
  return false;
@@ -23786,7 +23786,7 @@ var require_isexe = __commonJS({
23786
23786
  var require_which = __commonJS({
23787
23787
  "../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
23788
23788
  var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
23789
- var path30 = __require("path");
23789
+ var path31 = __require("path");
23790
23790
  var COLON = isWindows ? ";" : ":";
23791
23791
  var isexe = require_isexe();
23792
23792
  var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
@@ -23824,7 +23824,7 @@ var require_which = __commonJS({
23824
23824
  return opt.all && found.length ? resolve(found) : reject2(getNotFoundError(cmd));
23825
23825
  const ppRaw = pathEnv[i];
23826
23826
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
23827
- const pCmd = path30.join(pathPart, cmd);
23827
+ const pCmd = path31.join(pathPart, cmd);
23828
23828
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
23829
23829
  resolve(subStep(p, i, 0));
23830
23830
  });
@@ -23851,7 +23851,7 @@ var require_which = __commonJS({
23851
23851
  for (let i = 0; i < pathEnv.length; i++) {
23852
23852
  const ppRaw = pathEnv[i];
23853
23853
  const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
23854
- const pCmd = path30.join(pathPart, cmd);
23854
+ const pCmd = path31.join(pathPart, cmd);
23855
23855
  const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
23856
23856
  for (let j = 0; j < pathExt.length; j++) {
23857
23857
  const cur = p + pathExt[j];
@@ -23899,7 +23899,7 @@ var require_path_key = __commonJS({
23899
23899
  var require_resolveCommand = __commonJS({
23900
23900
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
23901
23901
  "use strict";
23902
- var path30 = __require("path");
23902
+ var path31 = __require("path");
23903
23903
  var which = require_which();
23904
23904
  var getPathKey = require_path_key();
23905
23905
  function resolveCommandAttempt(parsed, withoutPathExt) {
@@ -23917,7 +23917,7 @@ var require_resolveCommand = __commonJS({
23917
23917
  try {
23918
23918
  resolved = which.sync(parsed.command, {
23919
23919
  path: env2[getPathKey({ env: env2 })],
23920
- pathExt: withoutPathExt ? path30.delimiter : void 0
23920
+ pathExt: withoutPathExt ? path31.delimiter : void 0
23921
23921
  });
23922
23922
  } catch (e) {
23923
23923
  } finally {
@@ -23926,7 +23926,7 @@ var require_resolveCommand = __commonJS({
23926
23926
  }
23927
23927
  }
23928
23928
  if (resolved) {
23929
- resolved = path30.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
23929
+ resolved = path31.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
23930
23930
  }
23931
23931
  return resolved;
23932
23932
  }
@@ -23980,8 +23980,8 @@ var require_shebang_command = __commonJS({
23980
23980
  if (!match) {
23981
23981
  return null;
23982
23982
  }
23983
- const [path30, argument] = match[0].replace(/#! ?/, "").split(" ");
23984
- const binary = path30.split("/").pop();
23983
+ const [path31, argument] = match[0].replace(/#! ?/, "").split(" ");
23984
+ const binary = path31.split("/").pop();
23985
23985
  if (binary === "env") {
23986
23986
  return argument;
23987
23987
  }
@@ -23994,16 +23994,16 @@ var require_shebang_command = __commonJS({
23994
23994
  var require_readShebang = __commonJS({
23995
23995
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
23996
23996
  "use strict";
23997
- var fs24 = __require("fs");
23997
+ var fs25 = __require("fs");
23998
23998
  var shebangCommand = require_shebang_command();
23999
23999
  function readShebang(command) {
24000
24000
  const size = 150;
24001
24001
  const buffer = Buffer.alloc(size);
24002
24002
  let fd;
24003
24003
  try {
24004
- fd = fs24.openSync(command, "r");
24005
- fs24.readSync(fd, buffer, 0, size, 0);
24006
- fs24.closeSync(fd);
24004
+ fd = fs25.openSync(command, "r");
24005
+ fs25.readSync(fd, buffer, 0, size, 0);
24006
+ fs25.closeSync(fd);
24007
24007
  } catch (e) {
24008
24008
  }
24009
24009
  return shebangCommand(buffer.toString());
@@ -24016,7 +24016,7 @@ var require_readShebang = __commonJS({
24016
24016
  var require_parse2 = __commonJS({
24017
24017
  "../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
24018
24018
  "use strict";
24019
- var path30 = __require("path");
24019
+ var path31 = __require("path");
24020
24020
  var resolveCommand = require_resolveCommand();
24021
24021
  var escape2 = require_escape();
24022
24022
  var readShebang = require_readShebang();
@@ -24041,7 +24041,7 @@ var require_parse2 = __commonJS({
24041
24041
  const needsShell = !isExecutableRegExp.test(commandFile);
24042
24042
  if (parsed.options.forceShell || needsShell) {
24043
24043
  const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
24044
- parsed.command = path30.normalize(parsed.command);
24044
+ parsed.command = path31.normalize(parsed.command);
24045
24045
  parsed.command = escape2.command(parsed.command);
24046
24046
  parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
24047
24047
  const shellCommand = [parsed.command].concat(parsed.args).join(" ");
@@ -24131,7 +24131,7 @@ var require_cross_spawn = __commonJS({
24131
24131
  var cp = __require("child_process");
24132
24132
  var parse3 = require_parse2();
24133
24133
  var enoent = require_enoent();
24134
- function spawn6(command, args, options) {
24134
+ function spawn7(command, args, options) {
24135
24135
  const parsed = parse3(command, args, options);
24136
24136
  const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
24137
24137
  enoent.hookChildProcess(spawned, parsed);
@@ -24143,8 +24143,8 @@ var require_cross_spawn = __commonJS({
24143
24143
  result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
24144
24144
  return result;
24145
24145
  }
24146
- module.exports = spawn6;
24147
- module.exports.spawn = spawn6;
24146
+ module.exports = spawn7;
24147
+ module.exports.spawn = spawn7;
24148
24148
  module.exports.sync = spawnSync;
24149
24149
  module.exports._parse = parse3;
24150
24150
  module.exports._enoent = enoent;
@@ -24256,11 +24256,11 @@ var require_content_type = __commonJS({
24256
24256
  });
24257
24257
 
24258
24258
  // src/server.ts
24259
- import fs23 from "node:fs/promises";
24259
+ import fs24 from "node:fs/promises";
24260
24260
  import {
24261
24261
  createServer
24262
24262
  } from "node:http";
24263
- import path29 from "node:path";
24263
+ import path30 from "node:path";
24264
24264
 
24265
24265
  // ../../packages/core/dist/platform/http.js
24266
24266
  var import_undici = __toESM(require_undici(), 1);
@@ -25194,10 +25194,10 @@ function mergeDefs(...defs) {
25194
25194
  function cloneDef(schema) {
25195
25195
  return mergeDefs(schema._zod.def);
25196
25196
  }
25197
- function getElementAtPath(obj, path30) {
25198
- if (!path30)
25197
+ function getElementAtPath(obj, path31) {
25198
+ if (!path31)
25199
25199
  return obj;
25200
- return path30.reduce((acc, key) => acc?.[key], obj);
25200
+ return path31.reduce((acc, key) => acc?.[key], obj);
25201
25201
  }
25202
25202
  function promiseAllObject(promisesObj) {
25203
25203
  const keys = Object.keys(promisesObj);
@@ -25606,11 +25606,11 @@ function explicitlyAborted(x, startIndex = 0) {
25606
25606
  }
25607
25607
  return false;
25608
25608
  }
25609
- function prefixIssues(path30, issues) {
25609
+ function prefixIssues(path31, issues) {
25610
25610
  return issues.map((iss) => {
25611
25611
  var _a3;
25612
25612
  (_a3 = iss).path ?? (_a3.path = []);
25613
- iss.path.unshift(path30);
25613
+ iss.path.unshift(path31);
25614
25614
  return iss;
25615
25615
  });
25616
25616
  }
@@ -25757,16 +25757,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
25757
25757
  }
25758
25758
  function formatError(error51, mapper = (issue2) => issue2.message) {
25759
25759
  const fieldErrors = { _errors: [] };
25760
- const processError = (error52, path30 = []) => {
25760
+ const processError = (error52, path31 = []) => {
25761
25761
  for (const issue2 of error52.issues) {
25762
25762
  if (issue2.code === "invalid_union" && issue2.errors.length) {
25763
- issue2.errors.map((issues) => processError({ issues }, [...path30, ...issue2.path]));
25763
+ issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
25764
25764
  } else if (issue2.code === "invalid_key") {
25765
- processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
25765
+ processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
25766
25766
  } else if (issue2.code === "invalid_element") {
25767
- processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
25767
+ processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
25768
25768
  } else {
25769
- const fullpath = [...path30, ...issue2.path];
25769
+ const fullpath = [...path31, ...issue2.path];
25770
25770
  if (fullpath.length === 0) {
25771
25771
  fieldErrors._errors.push(mapper(issue2));
25772
25772
  } else {
@@ -25793,17 +25793,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
25793
25793
  }
25794
25794
  function treeifyError(error51, mapper = (issue2) => issue2.message) {
25795
25795
  const result = { errors: [] };
25796
- const processError = (error52, path30 = []) => {
25796
+ const processError = (error52, path31 = []) => {
25797
25797
  var _a3, _b;
25798
25798
  for (const issue2 of error52.issues) {
25799
25799
  if (issue2.code === "invalid_union" && issue2.errors.length) {
25800
- issue2.errors.map((issues) => processError({ issues }, [...path30, ...issue2.path]));
25800
+ issue2.errors.map((issues) => processError({ issues }, [...path31, ...issue2.path]));
25801
25801
  } else if (issue2.code === "invalid_key") {
25802
- processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
25802
+ processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
25803
25803
  } else if (issue2.code === "invalid_element") {
25804
- processError({ issues: issue2.issues }, [...path30, ...issue2.path]);
25804
+ processError({ issues: issue2.issues }, [...path31, ...issue2.path]);
25805
25805
  } else {
25806
- const fullpath = [...path30, ...issue2.path];
25806
+ const fullpath = [...path31, ...issue2.path];
25807
25807
  if (fullpath.length === 0) {
25808
25808
  result.errors.push(mapper(issue2));
25809
25809
  continue;
@@ -25835,8 +25835,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
25835
25835
  }
25836
25836
  function toDotPath(_path) {
25837
25837
  const segs = [];
25838
- const path30 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
25839
- for (const seg of path30) {
25838
+ const path31 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
25839
+ for (const seg of path31) {
25840
25840
  if (typeof seg === "number")
25841
25841
  segs.push(`[${seg}]`);
25842
25842
  else if (typeof seg === "symbol")
@@ -38528,13 +38528,13 @@ function resolveRef(ref, ctx) {
38528
38528
  if (!ref.startsWith("#")) {
38529
38529
  throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
38530
38530
  }
38531
- const path30 = ref.slice(1).split("/").filter(Boolean);
38532
- if (path30.length === 0) {
38531
+ const path31 = ref.slice(1).split("/").filter(Boolean);
38532
+ if (path31.length === 0) {
38533
38533
  return ctx.rootSchema;
38534
38534
  }
38535
38535
  const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
38536
- if (path30[0] === defsKey) {
38537
- const key = path30[1];
38536
+ if (path31[0] === defsKey) {
38537
+ const key = path31[1];
38538
38538
  if (!key || !ctx.defs[key]) {
38539
38539
  throw new Error(`Reference not found: ${ref}`);
38540
38540
  }
@@ -38942,6 +38942,79 @@ function date4(params) {
38942
38942
  // ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
38943
38943
  config(en_default());
38944
38944
 
38945
+ // ../../packages/core/dist/dataset/types.js
38946
+ var datasetRecordSchema = external_exports.object({
38947
+ /**
38948
+ * Stable across syncs. The same record from the source must come back with the same id, or a
38949
+ * re-sync duplicates it rather than replacing it — which is the failure that turns a useful
38950
+ * corpus into noise a few runs in.
38951
+ */
38952
+ id: external_exports.string().min(1),
38953
+ /** What gets embedded and what a search returns. */
38954
+ text: external_exports.string().min(1),
38955
+ /** A heading for the search result. Falls back to the opening of `text`. */
38956
+ title: external_exports.string().optional(),
38957
+ /** Where it came from — a ticket URL, a file path. Shown so a hit can be followed up. */
38958
+ url: external_exports.string().optional(),
38959
+ /**
38960
+ * Epoch milliseconds. Retention and "what changed this week" both need it.
38961
+ *
38962
+ * Absent is allowed and means "no age", which retention then cannot remove. Defaulting it to
38963
+ * *now* would be worse: every record would age from whenever it was last synced, so nothing
38964
+ * would ever look old and retention would silently never fire.
38965
+ */
38966
+ timestamp: external_exports.number().optional(),
38967
+ /** Anything else the tool wants to keep. Filterable exactly, never embedded. */
38968
+ tags: external_exports.record(external_exports.string(), external_exports.string()).optional()
38969
+ });
38970
+ var datasetPayloadSchema = external_exports.union([
38971
+ external_exports.object({ records: external_exports.array(datasetRecordSchema) }),
38972
+ external_exports.array(datasetRecordSchema)
38973
+ ]);
38974
+ function parseDatasetPayload(value) {
38975
+ const parsed = datasetPayloadSchema.safeParse(value);
38976
+ if (parsed.success) {
38977
+ return { records: Array.isArray(parsed.data) ? parsed.data : parsed.data.records };
38978
+ }
38979
+ return {
38980
+ 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("; ")
38981
+ };
38982
+ }
38983
+ var datasetConfigSchema = external_exports.object({
38984
+ id: external_exports.string().min(1),
38985
+ name: external_exports.string().min(1, "Give it a name"),
38986
+ /** The Python tool that produces the records, by its bare name. */
38987
+ toolName: external_exports.string().min(1, "Choose a collector tool"),
38988
+ /** Passed to the tool as its arguments, so one tool can serve several datasets. */
38989
+ arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
38990
+ enabled: external_exports.boolean().optional(),
38991
+ /** How often to re-run the collector. Zero or absent means only when asked. */
38992
+ syncMinutes: external_exports.number().int().min(0).optional(),
38993
+ /** Drop records older than this. Absent means keep everything. */
38994
+ retentionDays: external_exports.number().int().positive().optional(),
38995
+ /** Which vector store to write to. Falls back to the one named for `data`, then the active one. */
38996
+ storeId: external_exports.string().optional()
38997
+ });
38998
+ var COLLECTOR_TOOL_GUIDANCE = [
38999
+ "Writing a collector for a custom dataset:",
39000
+ "- A collector is an ordinary Python tool. Its `run` returns a list of records, each a dict",
39001
+ " with `id` and `text`, and optionally `title`, `url`, `timestamp` (epoch milliseconds) and",
39002
+ " `tags` (a flat dict of strings).",
39003
+ "- **`id` must be stable across runs.** Use the source's own identifier \u2014 a ticket key, a row",
39004
+ " id, a file path. A generated or time-based id makes every sync duplicate the whole corpus",
39005
+ " instead of updating it, which is not obvious until the results are full of near-copies.",
39006
+ "- **`text` is what gets embedded and what a search shows.** Put the meaning in it: a subject",
39007
+ " and a body, not an id and a status code. Roughly a paragraph to a page each works best.",
39008
+ '- Set `timestamp` wherever the source has one. Retention and any "what changed recently"',
39009
+ " question both need it, and it cannot be recovered later.",
39010
+ "- The tool is called with whatever arguments the dataset configures, plus `since` \u2014 epoch",
39011
+ " milliseconds of the last successful sync, or absent on the first. Use it to fetch only what",
39012
+ " changed if the source allows; returning everything each time is correct but slower.",
39013
+ "- Return `[]` when there is nothing new. That is a successful sync, not an error.",
39014
+ "- Keep credentials out of the tool: read them from the environment or from a file the user",
39015
+ " already has. A tool file lives in the workspace and lands in git."
39016
+ ].join("\n");
39017
+
38945
39018
  // ../../packages/core/dist/mcp/types.js
38946
39019
  var stdioServerSchema = external_exports.object({
38947
39020
  command: external_exports.string().min(1),
@@ -39191,9 +39264,42 @@ var apigeeMtlsSettingsSchema = external_exports.object({
39191
39264
  refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39192
39265
  extraHeaders: external_exports.record(external_exports.string(), external_exports.string()).optional()
39193
39266
  });
39267
+ var tokenCommandSchema = external_exports.object({
39268
+ 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."),
39269
+ cwd: external_exports.string().optional(),
39270
+ tokenPath: external_exports.string().optional(),
39271
+ expiresInPath: external_exports.string().optional(),
39272
+ fallbackExpirySeconds: external_exports.number().int().positive().optional(),
39273
+ refreshSkewSeconds: external_exports.number().int().nonnegative().optional(),
39274
+ timeoutSeconds: external_exports.number().int().positive().optional(),
39275
+ headerName: external_exports.string().optional(),
39276
+ headerPrefix: external_exports.string().optional(),
39277
+ env: external_exports.record(external_exports.string(), external_exports.string()).optional()
39278
+ });
39194
39279
  var authSchema = external_exports.discriminatedUnion("type", [
39195
39280
  external_exports.object({ type: external_exports.literal("none") }),
39281
+ /**
39282
+ * `apiKeyRef` may name the environment as well as the secret store.
39283
+ *
39284
+ * `env:API_TOKEN` reads it from the process environment — see `auth/secretRef.ts`. Anything
39285
+ * else is a key into `SecretStore`, which is what the UI writes.
39286
+ */
39196
39287
  external_exports.object({ type: external_exports.literal("apiKey"), apiKeyRef: external_exports.string().min(1) }),
39288
+ external_exports.object({ type: external_exports.literal("tokenCommand"), tokenCommand: tokenCommandSchema }),
39289
+ /**
39290
+ * A fixed header the gateway expects, with no API key involved.
39291
+ *
39292
+ * Each value is a *reference* — a secret-store key, or `env:NAME` — never a literal, because
39293
+ * the profile lives in the config file and §15 is explicit that a credential never does.
39294
+ */
39295
+ external_exports.object({
39296
+ type: external_exports.literal("header"),
39297
+ headers: external_exports.array(external_exports.object({
39298
+ name: external_exports.string().min(1, "Give the header name"),
39299
+ valueRef: external_exports.string().min(1, "Give the value, or env:NAME"),
39300
+ prefix: external_exports.string().optional()
39301
+ })).min(1, "Add at least one header")
39302
+ }),
39197
39303
  external_exports.object({
39198
39304
  type: external_exports.literal("apigeeMtls"),
39199
39305
  certs: certConfigSchema,
@@ -39237,6 +39343,7 @@ var providerProfileSchema = external_exports.object({
39237
39343
  });
39238
39344
 
39239
39345
  // ../../packages/core/dist/config/schema.js
39346
+ var datasetsConfigSchema = external_exports.array(datasetConfigSchema);
39240
39347
  var pythonConfigSchema = external_exports.object({
39241
39348
  /**
39242
39349
  * Off by default and explicitly three-state. This is the sharpest surface in the
@@ -39256,6 +39363,17 @@ var pythonConfigSchema = external_exports.object({
39256
39363
  * user storage is the fallback.
39257
39364
  */
39258
39365
  venvPath: external_exports.string(),
39366
+ /**
39367
+ * A Python interpreter to use directly, with no virtualenv and no uv.
39368
+ *
39369
+ * For an environment somebody else already built — a Streamlit app, a container, a conda env
39370
+ * — where the interpreter has the internal libraries the tools need and installing a package
39371
+ * manager to reach it makes no sense. Left unset, uv is preferred and this is the fallback:
39372
+ * `python3`, then `python`, from PATH.
39373
+ *
39374
+ * User-scope only for the same reason as `uvPath`: it names a program that gets run.
39375
+ */
39376
+ interpreterPath: external_exports.string(),
39259
39377
  /**
39260
39378
  * Package index for tool dependencies. §3 treats `uv` resolving PyPI as *our* egress
39261
39379
  * rather than the user's, so pointing it at an internal mirror is the expected
@@ -39515,7 +39633,15 @@ var retrievalConfigSchema = external_exports.object({
39515
39633
  /** Indexed mail. Usually local, and deliberately easy to keep separate. */
39516
39634
  mail: external_exports.string().min(1),
39517
39635
  /** The team's shared skills. Often the same cluster as the code. */
39518
- skills: external_exports.string().min(1)
39636
+ skills: external_exports.string().min(1),
39637
+ /**
39638
+ * Corpora the user collects themselves.
39639
+ *
39640
+ * Routed separately for the same reason mail is: somebody's own collected data —
39641
+ * tickets, extracts from an internal system — is frequently the thing they most want
39642
+ * kept off a cluster their team shares.
39643
+ */
39644
+ data: external_exports.string().min(1)
39519
39645
  }).partial()
39520
39646
  }).partial();
39521
39647
  function storeIdFor(purpose, config2) {
@@ -39703,6 +39829,7 @@ var configSchema = external_exports.object({
39703
39829
  programmingProfileId: external_exports.string(),
39704
39830
  certDir: external_exports.string(),
39705
39831
  python: pythonConfigSchema,
39832
+ datasets: datasetsConfigSchema,
39706
39833
  /**
39707
39834
  * Keyed by workspace path. Per-workspace in *behaviour* (§8) but stored user-side and
39708
39835
  * user-scope-only (invariant 5) — a repo must not be able to ship its own
@@ -40174,6 +40301,19 @@ var GUIDE_STEPS = [
40174
40301
  "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."
40175
40302
  ]
40176
40303
  },
40304
+ {
40305
+ id: "customData",
40306
+ title: "Custom data - bring your own corpus",
40307
+ tab: "customData",
40308
+ completionEvents: ["onStepSelected"],
40309
+ 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.",
40310
+ body: [
40311
+ "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.",
40312
+ "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.",
40313
+ "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.",
40314
+ "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."
40315
+ ]
40316
+ },
40177
40317
  {
40178
40318
  id: "search",
40179
40319
  title: "Search - find things by meaning",
@@ -40276,6 +40416,9 @@ var USER_SCOPE_ONLY_KEYS = [
40276
40416
  // Added for Phase 8b, and the sharpest entries on this list. A workspace able to name a
40277
40417
  // cluster, or repoint the embedder at a profile of its choosing, would exfiltrate
40278
40418
  // whatever gets indexed — and what gets indexed is the source code.
40419
+ // A dataset names a program to run *and* a store to write what it produced into — the `python`
40420
+ // threat and the `embedder` threat in one key, on a timer.
40421
+ "datasets",
40279
40422
  "vectorStores",
40280
40423
  "activeVectorStoreId",
40281
40424
  "embedder",
@@ -40780,6 +40923,30 @@ function resolveActiveProfile(config2) {
40780
40923
  return found;
40781
40924
  }
40782
40925
 
40926
+ // ../../packages/core/dist/providers/auth/secretRef.js
40927
+ var ENV_REF_PREFIX = "env:";
40928
+ function describeSecretRef(ref) {
40929
+ if (!ref.startsWith(ENV_REF_PREFIX))
40930
+ return { kind: "store" };
40931
+ const envVar = ref.slice(ENV_REF_PREFIX.length).trim();
40932
+ return envVar.length === 0 ? { kind: "store" } : { kind: "env", envVar };
40933
+ }
40934
+ async function resolveSecretRef(ref, options) {
40935
+ const described = describeSecretRef(ref);
40936
+ if (described.kind === "env") {
40937
+ const value = (options.env ?? process.env)[described.envVar];
40938
+ return value === void 0 || value.trim().length === 0 ? void 0 : value;
40939
+ }
40940
+ return options.secrets.get(ref);
40941
+ }
40942
+ function describeMissingSecret(ref, what = "API key") {
40943
+ const described = describeSecretRef(ref);
40944
+ if (described.kind === "env") {
40945
+ 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.`;
40946
+ }
40947
+ 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.`;
40948
+ }
40949
+
40783
40950
  // ../../packages/core/dist/providers/auth/apiKey.js
40784
40951
  function defaultApiKeyHeader(wireFormat) {
40785
40952
  switch (wireFormat) {
@@ -40801,9 +40968,9 @@ var ApiKeyAuthStrategy = class {
40801
40968
  this.header = header;
40802
40969
  }
40803
40970
  async resolveHeaders() {
40804
- const key = await this.secrets.get(this.apiKeyRef);
40971
+ const key = await resolveSecretRef(this.apiKeyRef, { secrets: this.secrets });
40805
40972
  if (key === void 0) {
40806
- 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.");
40973
+ throw new Error(describeMissingSecret(this.apiKeyRef));
40807
40974
  }
40808
40975
  return { [this.header.name]: `${this.header.prefix}${key}` };
40809
40976
  }
@@ -40814,6 +40981,162 @@ var NoAuthStrategy = class {
40814
40981
  }
40815
40982
  };
40816
40983
 
40984
+ // ../../packages/core/dist/providers/auth/header.js
40985
+ var HeaderAuthStrategy = class {
40986
+ secrets;
40987
+ credentials;
40988
+ constructor(secrets, credentials) {
40989
+ this.secrets = secrets;
40990
+ this.credentials = credentials;
40991
+ }
40992
+ async resolveHeaders() {
40993
+ const headers = {};
40994
+ for (const credential of this.credentials) {
40995
+ const value = await resolveSecretRef(credential.valueRef, { secrets: this.secrets });
40996
+ if (value === void 0) {
40997
+ throw new Error(`${describeMissingSecret(credential.valueRef, `the value for header "${credential.name}"`)}`);
40998
+ }
40999
+ headers[credential.name] = `${credential.prefix ?? ""}${value}`;
41000
+ }
41001
+ return headers;
41002
+ }
41003
+ };
41004
+
41005
+ // ../../packages/core/dist/providers/auth/tokenCommand.js
41006
+ import { spawn } from "node:child_process";
41007
+ function readPath(source, dotted) {
41008
+ let current = source;
41009
+ for (const part of dotted.split(".")) {
41010
+ if (current === null || typeof current !== "object")
41011
+ return void 0;
41012
+ current = current[part];
41013
+ }
41014
+ return current;
41015
+ }
41016
+ var TokenCommandAuthStrategy = class {
41017
+ settings;
41018
+ held;
41019
+ inFlight;
41020
+ constructor(settings) {
41021
+ this.settings = settings;
41022
+ if (settings.command.length === 0) {
41023
+ throw new Error("The token command is empty. Give the program and its arguments.");
41024
+ }
41025
+ }
41026
+ async resolveHeaders() {
41027
+ const token = await this.token();
41028
+ const name = this.settings.headerName ?? "Authorization";
41029
+ const prefix = this.settings.headerPrefix ?? "Bearer ";
41030
+ return { [name]: `${prefix}${token.value}` };
41031
+ }
41032
+ /**
41033
+ * Checked before a stream opens, with margin for a long generation.
41034
+ *
41035
+ * The same reasoning as the Apigee strategy: a token that expires halfway through a response
41036
+ * cannot be recovered from without discarding what has already been written.
41037
+ */
41038
+ async ensureTokenForStream(marginSeconds = 120) {
41039
+ const deadline = Date.now() + marginSeconds * 1e3;
41040
+ if (this.held === void 0 || this.held.expiresAt <= deadline) {
41041
+ this.held = void 0;
41042
+ await this.token();
41043
+ }
41044
+ }
41045
+ /** Drops the held token, so the next request fetches a new one. For a 401 retry. */
41046
+ invalidate() {
41047
+ this.held = void 0;
41048
+ }
41049
+ async token() {
41050
+ const skew = (this.settings.refreshSkewSeconds ?? 60) * 1e3;
41051
+ if (this.held !== void 0 && this.held.expiresAt - skew > Date.now())
41052
+ return this.held;
41053
+ this.inFlight ??= this.fetch().then((token) => {
41054
+ this.held = token;
41055
+ return token;
41056
+ }).finally(() => {
41057
+ this.inFlight = void 0;
41058
+ });
41059
+ return this.inFlight;
41060
+ }
41061
+ async fetch() {
41062
+ const [program, ...args] = this.settings.command;
41063
+ const timeout = (this.settings.timeoutSeconds ?? 30) * 1e3;
41064
+ const output = await new Promise((resolve, reject2) => {
41065
+ const child = spawn(program, args, {
41066
+ // Never `shell: true`. See the note at the top of this file.
41067
+ shell: false,
41068
+ ...this.settings.cwd === void 0 ? {} : { cwd: this.settings.cwd },
41069
+ env: { ...process.env, ...this.settings.env ?? {} }
41070
+ });
41071
+ let stdout = "";
41072
+ let stderr = "";
41073
+ let settled = false;
41074
+ const timer = setTimeout(() => {
41075
+ if (settled)
41076
+ return;
41077
+ settled = true;
41078
+ child.kill();
41079
+ 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.`));
41080
+ }, timeout);
41081
+ child.stdout.on("data", (chunk) => stdout += chunk.toString());
41082
+ child.stderr.on("data", (chunk) => stderr += chunk.toString());
41083
+ child.on("error", (error51) => {
41084
+ if (settled)
41085
+ return;
41086
+ settled = true;
41087
+ clearTimeout(timer);
41088
+ 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}`));
41089
+ });
41090
+ child.on("close", (code) => {
41091
+ if (settled)
41092
+ return;
41093
+ settled = true;
41094
+ clearTimeout(timer);
41095
+ if (code === 0) {
41096
+ resolve(stdout);
41097
+ return;
41098
+ }
41099
+ const detail = stderr.trim().length > 0 ? stderr.trim() : stdout.trim();
41100
+ reject2(new Error(`The token command exited with code ${String(code ?? -1)}.` + (detail.length > 0 ? `
41101
+ ${detail.slice(0, 2e3)}` : " It printed nothing.")));
41102
+ });
41103
+ });
41104
+ return this.parse(output);
41105
+ }
41106
+ parse(stdout) {
41107
+ const fallback = (this.settings.fallbackExpirySeconds ?? 3600) * 1e3;
41108
+ if (this.settings.tokenPath === void 0) {
41109
+ const value2 = stdout.trim();
41110
+ if (value2.length === 0) {
41111
+ throw new Error("The token command succeeded but printed nothing. It must write the token to stdout, or name `tokenPath` if it prints JSON.");
41112
+ }
41113
+ if (/\s/.test(value2)) {
41114
+ 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`.");
41115
+ }
41116
+ return { value: value2, expiresAt: Date.now() + fallback };
41117
+ }
41118
+ let parsed;
41119
+ try {
41120
+ parsed = JSON.parse(stdout);
41121
+ } catch {
41122
+ 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)}`);
41123
+ }
41124
+ const value = readPath(parsed, this.settings.tokenPath);
41125
+ if (typeof value !== "string" || value.trim().length === 0) {
41126
+ throw new Error(`The token command's JSON has nothing usable at "${this.settings.tokenPath}". It printed: ${stdout.trim().slice(0, 200)}`);
41127
+ }
41128
+ let lifetime = fallback;
41129
+ if (this.settings.expiresInPath !== void 0) {
41130
+ const reported = readPath(parsed, this.settings.expiresInPath);
41131
+ const seconds = typeof reported === "string" ? Number(reported) : reported;
41132
+ if (typeof seconds === "number" && Number.isFinite(seconds) && seconds > 0) {
41133
+ lifetime = seconds * 1e3;
41134
+ }
41135
+ }
41136
+ return { value: value.trim(), expiresAt: Date.now() + lifetime };
41137
+ }
41138
+ };
41139
+
40817
41140
  // ../../packages/core/dist/providers/auth/apigeeMtls.js
40818
41141
  var DEFAULTS = {
40819
41142
  grantType: "client_credentials",
@@ -40832,7 +41155,7 @@ function defaultTokenUrl(baseUrl) {
40832
41155
  return "";
40833
41156
  }
40834
41157
  }
40835
- function readPath(source, dottedPath) {
41158
+ function readPath2(source, dottedPath) {
40836
41159
  return dottedPath.split(".").reduce((current, segment) => {
40837
41160
  if (typeof current !== "object" || current === null)
40838
41161
  return void 0;
@@ -40951,11 +41274,11 @@ var ApigeeMtlsAuthStrategy = class {
40951
41274
  throw new ApigeeAuthError(`The token endpoint at ${tokenUrl} did not return JSON.`);
40952
41275
  }
40953
41276
  const tokenPath = this.settings.tokenPath ?? DEFAULTS.tokenPath;
40954
- const value = readPath(payload, tokenPath);
41277
+ const value = readPath2(payload, tokenPath);
40955
41278
  if (typeof value !== "string" || value.length === 0) {
40956
41279
  throw new ApigeeAuthError(`The token endpoint response has no token at "${tokenPath}". Set tokenPath if your gateway nests it elsewhere.`);
40957
41280
  }
40958
- const rawExpiry = readPath(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
41281
+ const rawExpiry = readPath2(payload, this.settings.expiresInPath ?? DEFAULTS.expiresInPath);
40959
41282
  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;
40960
41283
  const skew = this.settings.refreshSkewSeconds ?? DEFAULTS.refreshSkewSeconds;
40961
41284
  const issuedAt = this.now();
@@ -41216,6 +41539,16 @@ function createBaseAuthStrategy(auth2, context) {
41216
41539
  prefix: context.apiKeyHeaderPrefix ?? derived.prefix
41217
41540
  });
41218
41541
  }
41542
+ case "tokenCommand": {
41543
+ const derived = defaultApiKeyHeader(context.wireFormat ?? "openai");
41544
+ return new TokenCommandAuthStrategy({
41545
+ ...auth2.tokenCommand,
41546
+ headerName: auth2.tokenCommand.headerName ?? context.apiKeyHeaderName ?? derived.name,
41547
+ headerPrefix: auth2.tokenCommand.headerPrefix ?? context.apiKeyHeaderPrefix ?? derived.prefix
41548
+ });
41549
+ }
41550
+ case "header":
41551
+ return new HeaderAuthStrategy(context.secrets, auth2.headers);
41219
41552
  case "none":
41220
41553
  return new NoAuthStrategy();
41221
41554
  case "apigeeMtls": {
@@ -41407,7 +41740,11 @@ async function testConnection(profile, context, http, signal) {
41407
41740
  } else {
41408
41741
  try {
41409
41742
  await auth2.resolveHeaders();
41410
- steps.push({ step: "token", status: "ok", detail: "Credential resolved from secure storage." });
41743
+ steps.push({
41744
+ step: "token",
41745
+ status: "ok",
41746
+ 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."
41747
+ });
41411
41748
  } catch (error51) {
41412
41749
  steps.push({ step: "token", status: "failed", detail: messageOf(error51) });
41413
41750
  steps.push({ step: "models", status: "skipped", detail: "Not attempted \u2014 no credential." });
@@ -42190,8 +42527,8 @@ var SUPERSEDED_MARKER = "[Superseded: this file was read again later in the conv
42190
42527
  function readFilePath(argumentsJson) {
42191
42528
  try {
42192
42529
  const parsed = JSON.parse(argumentsJson.length > 0 ? argumentsJson : "{}");
42193
- const path30 = parsed.path;
42194
- return typeof path30 === "string" && path30.length > 0 ? path30 : void 0;
42530
+ const path31 = parsed.path;
42531
+ return typeof path31 === "string" && path31.length > 0 ? path31 : void 0;
42195
42532
  } catch {
42196
42533
  return void 0;
42197
42534
  }
@@ -42204,8 +42541,8 @@ function dropSupersededReads(messages) {
42204
42541
  for (const toolCall of message3.toolCalls ?? []) {
42205
42542
  if (toolCall.name !== "read_file")
42206
42543
  continue;
42207
- const path30 = readFilePath(toolCall.arguments);
42208
- if (path30 === void 0)
42544
+ const path31 = readFilePath(toolCall.arguments);
42545
+ if (path31 === void 0)
42209
42546
  continue;
42210
42547
  keyByCallId.set(toolCall.id, toolCall.arguments);
42211
42548
  }
@@ -42639,8 +42976,18 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
42639
42976
  if (options.canWriteSkills === true) {
42640
42977
  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.");
42641
42978
  }
42979
+ 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.");
42980
+ if (options.datasets !== void 0 && options.datasets.length > 0) {
42981
+ 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 ? [
42982
+ "- If they want a dataset you cannot find, you can write the collector: it is an",
42983
+ " ordinary Python tool returning records. Offer, do not assume \u2014 then they configure",
42984
+ " it in Settings, Custom data. The contract is below.",
42985
+ "",
42986
+ COLLECTOR_TOOL_GUIDANCE
42987
+ ] : []);
42988
+ }
42642
42989
  if (options.mailIndexed === true) {
42643
- 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.");
42990
+ 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.");
42644
42991
  }
42645
42992
  if (options.expertAvailable === true) {
42646
42993
  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.");
@@ -42687,7 +43034,7 @@ function fallbackLocations(name) {
42687
43034
  if (path8.isAbsolute(name))
42688
43035
  return [];
42689
43036
  const candidates = [];
42690
- const push = (dir) => {
43037
+ const push2 = (dir) => {
42691
43038
  if (dir === void 0 || dir.length === 0)
42692
43039
  return;
42693
43040
  if (process.platform === "win32")
@@ -42695,12 +43042,12 @@ function fallbackLocations(name) {
42695
43042
  candidates.push(path8.join(dir, name));
42696
43043
  };
42697
43044
  if (process.platform === "win32") {
42698
- push(process.env.APPDATA !== void 0 ? path8.join(process.env.APPDATA, "npm") : void 0);
43045
+ push2(process.env.APPDATA !== void 0 ? path8.join(process.env.APPDATA, "npm") : void 0);
42699
43046
  } else {
42700
- push("/usr/local/bin");
42701
- push("/opt/homebrew/bin");
42702
- push(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".npm-global", "bin") : void 0);
42703
- push(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".local", "bin") : void 0);
43047
+ push2("/usr/local/bin");
43048
+ push2("/opt/homebrew/bin");
43049
+ push2(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".npm-global", "bin") : void 0);
43050
+ push2(process.env.HOME !== void 0 ? path8.join(process.env.HOME, ".local", "bin") : void 0);
42704
43051
  }
42705
43052
  return candidates;
42706
43053
  }
@@ -43278,13 +43625,13 @@ var OpenSearchClient = class {
43278
43625
  * `_bulk`, `_delete_by_query`, index creation — is refused here rather than merely
43279
43626
  * unused, so no future edit or crafted argument can turn a read client into a writer.
43280
43627
  */
43281
- async request(path30, options = {}) {
43628
+ async request(path31, options = {}) {
43282
43629
  const method = options.method ?? "GET";
43283
- const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path30);
43630
+ const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path31);
43284
43631
  if (method !== "GET" && !isSearchPost) {
43285
- throw new OpenSearchError(`Refusing ${method} ${path30}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
43632
+ throw new OpenSearchError(`Refusing ${method} ${path31}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
43286
43633
  }
43287
- const url2 = `${this.base}${path30}`;
43634
+ const url2 = `${this.base}${path31}`;
43288
43635
  const request = {
43289
43636
  method,
43290
43637
  headers: this.headers()
@@ -43447,11 +43794,11 @@ function collectFields(properties, prefix, out) {
43447
43794
  return;
43448
43795
  for (const [name, raw] of Object.entries(properties)) {
43449
43796
  const field = raw;
43450
- const path30 = prefix.length > 0 ? `${prefix}.${name}` : name;
43797
+ const path31 = prefix.length > 0 ? `${prefix}.${name}` : name;
43451
43798
  if (typeof field.type === "string")
43452
- out[path30] = field.type;
43799
+ out[path31] = field.type;
43453
43800
  if (field.properties !== void 0)
43454
- collectFields(field.properties, path30, out);
43801
+ collectFields(field.properties, path31, out);
43455
43802
  }
43456
43803
  }
43457
43804
  function describeStatus(status, url2, body) {
@@ -43470,23 +43817,23 @@ function describeStatus(status, url2, body) {
43470
43817
  var TEXT_TYPES = /* @__PURE__ */ new Set(["text", "match_only_text", "search_as_you_type", "wildcard"]);
43471
43818
  var KEYWORD_TYPES = /* @__PURE__ */ new Set(["keyword", "constant_keyword"]);
43472
43819
  var NOISE_FIELDS = /* @__PURE__ */ new Set(["@version", "ecs", "tags", "stream", "input", "agent", "host", "event"]);
43473
- function leafName(path30) {
43474
- const parts = path30.split(".");
43475
- return parts[parts.length - 1] ?? path30;
43820
+ function leafName(path31) {
43821
+ const parts = path31.split(".");
43822
+ return parts[parts.length - 1] ?? path31;
43476
43823
  }
43477
43824
  function selectQueryFields(mapping, limit = 25) {
43478
43825
  const text = [];
43479
43826
  const keyword = [];
43480
- for (const [path30, type] of Object.entries(mapping)) {
43481
- if (NOISE_FIELDS.has(leafName(path30)) || NOISE_FIELDS.has(path30.split(".")[0] ?? ""))
43827
+ for (const [path31, type] of Object.entries(mapping)) {
43828
+ if (NOISE_FIELDS.has(leafName(path31)) || NOISE_FIELDS.has(path31.split(".")[0] ?? ""))
43482
43829
  continue;
43483
43830
  if (TEXT_TYPES.has(type)) {
43484
- text.push(path30);
43831
+ text.push(path31);
43485
43832
  } else if (KEYWORD_TYPES.has(type)) {
43486
- const parent = path30.replace(/\.keyword$/, "");
43487
- if (path30.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
43833
+ const parent = path31.replace(/\.keyword$/, "");
43834
+ if (path31.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
43488
43835
  continue;
43489
- keyword.push(path30);
43836
+ keyword.push(path31);
43490
43837
  }
43491
43838
  }
43492
43839
  const byDepth = (a, b) => a.split(".").length - b.split(".").length || a.localeCompare(b);
@@ -43628,8 +43975,8 @@ var OpenSearchIndexWriter = class {
43628
43975
  }
43629
43976
  return headers;
43630
43977
  }
43631
- async request(path30, method, body, signal) {
43632
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path30}`;
43978
+ async request(path31, method, body, signal) {
43979
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path31}`;
43633
43980
  const request = { method, headers: this.headers() };
43634
43981
  if (body !== void 0) {
43635
43982
  if (typeof body === "string") {
@@ -43843,13 +44190,13 @@ var OpenSearchIndexWriter = class {
43843
44190
  for (const hit of hits) {
43844
44191
  const source = hit._source ?? {};
43845
44192
  const vector = source.vector;
43846
- const path30 = source.path;
43847
- if (typeof path30 !== "string" || !Array.isArray(vector))
44193
+ const path31 = source.path;
44194
+ if (typeof path31 !== "string" || !Array.isArray(vector))
43848
44195
  continue;
43849
44196
  documents.push({
43850
44197
  id: hit._id ?? "",
43851
44198
  text: typeof source.text === "string" ? source.text : "",
43852
- path: path30,
44199
+ path: path31,
43853
44200
  startLine: typeof source.startLine === "number" ? source.startLine : 1,
43854
44201
  endLine: typeof source.endLine === "number" ? source.endLine : 1,
43855
44202
  vector
@@ -43923,8 +44270,8 @@ var RestTransport = class {
43923
44270
  * threw would push every caller into catching and re-inspecting an error to find out
43924
44271
  * whether it was really an error. `expectOk` is there for the cases that are.
43925
44272
  */
43926
- async send(path30, method, body, signal) {
43927
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path30}`;
44273
+ async send(path31, method, body, signal) {
44274
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path31}`;
43928
44275
  const request = { method, headers: this.headers() };
43929
44276
  if (body !== void 0)
43930
44277
  request.body = JSON.stringify(body);
@@ -43950,11 +44297,11 @@ var RestTransport = class {
43950
44297
  return { status: response.status, body: parsed };
43951
44298
  }
43952
44299
  /** Sends, and throws unless the status is 2xx. */
43953
- async expectOk(path30, method, body, signal) {
43954
- const result = await this.send(path30, method, body, signal);
44300
+ async expectOk(path31, method, body, signal) {
44301
+ const result = await this.send(path31, method, body, signal);
43955
44302
  if (result.status < 200 || result.status >= 300) {
43956
44303
  const detail = typeof result.body === "string" ? result.body : JSON.stringify(result.body ?? "");
43957
- throw new VectorStoreError(`${method} ${path30} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
44304
+ throw new VectorStoreError(`${method} ${path31} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
43958
44305
  }
43959
44306
  return result.body;
43960
44307
  }
@@ -44055,10 +44402,10 @@ var ChromaSearcher = class extends ChromaBase {
44055
44402
  const matches = [];
44056
44403
  for (let index = 0; index < ids.length; index++) {
44057
44404
  const metadata = metadatas[index] ?? {};
44058
- const path30 = typeof metadata.path === "string" ? metadata.path : void 0;
44059
- if (path30 === void 0)
44405
+ const path31 = typeof metadata.path === "string" ? metadata.path : void 0;
44406
+ if (path31 === void 0)
44060
44407
  continue;
44061
- if (filtering && !path30.startsWith(prefix))
44408
+ if (filtering && !path31.startsWith(prefix))
44062
44409
  continue;
44063
44410
  const distance = distances[index];
44064
44411
  const match = {
@@ -44070,7 +44417,7 @@ var ChromaSearcher = class extends ChromaBase {
44070
44417
  */
44071
44418
  score: typeof distance === "number" ? 1 / (1 + Math.max(0, distance)) : 0,
44072
44419
  text: documents[index] ?? (typeof metadata.text === "string" ? metadata.text : ""),
44073
- path: path30
44420
+ path: path31
44074
44421
  };
44075
44422
  if (typeof metadata.startLine === "number")
44076
44423
  match.startLine = metadata.startLine;
@@ -44181,13 +44528,13 @@ var ChromaIndexWriter = class extends ChromaBase {
44181
44528
  for (let index = 0; index < ids.length; index++) {
44182
44529
  const metadata = result.metadatas?.[index] ?? {};
44183
44530
  const vector = result.embeddings?.[index];
44184
- const path30 = typeof metadata.path === "string" ? metadata.path : void 0;
44185
- if (path30 === void 0 || !Array.isArray(vector))
44531
+ const path31 = typeof metadata.path === "string" ? metadata.path : void 0;
44532
+ if (path31 === void 0 || !Array.isArray(vector))
44186
44533
  continue;
44187
44534
  documents.push({
44188
44535
  id: ids[index] ?? "",
44189
44536
  text: result.documents?.[index] ?? "",
44190
- path: path30,
44537
+ path: path31,
44191
44538
  startLine: typeof metadata.startLine === "number" ? metadata.startLine : 1,
44192
44539
  endLine: typeof metadata.endLine === "number" ? metadata.endLine : 1,
44193
44540
  vector
@@ -44204,9 +44551,9 @@ var ChromaIndexWriter = class extends ChromaBase {
44204
44551
  const result = await this.rest.expectOk(`${this.base}/collections/${found.id}/get`, "POST", { include: ["metadatas"], limit }, options.signal);
44205
44552
  const paths = /* @__PURE__ */ new Set();
44206
44553
  for (const metadata of result.metadatas ?? []) {
44207
- const path30 = metadata?.path;
44208
- if (typeof path30 === "string")
44209
- paths.add(path30);
44554
+ const path31 = metadata?.path;
44555
+ if (typeof path31 === "string")
44556
+ paths.add(path31);
44210
44557
  }
44211
44558
  return [...paths];
44212
44559
  }
@@ -44233,14 +44580,14 @@ var MARKER_ID = "5f6d2a41-0000-5000-8000-6c69676874c0";
44233
44580
  var MARKER_MARK = "light-code";
44234
44581
  function toMatch(point) {
44235
44582
  const payload = point.payload ?? {};
44236
- const path30 = typeof payload.path === "string" ? payload.path : void 0;
44237
- if (path30 === void 0)
44583
+ const path31 = typeof payload.path === "string" ? payload.path : void 0;
44584
+ if (path31 === void 0)
44238
44585
  return void 0;
44239
44586
  const match = {
44240
44587
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
44241
44588
  score: typeof point.score === "number" ? point.score : 0,
44242
44589
  text: typeof payload.text === "string" ? payload.text : "",
44243
- path: path30
44590
+ path: path31
44244
44591
  };
44245
44592
  if (typeof payload.startLine === "number")
44246
44593
  match.startLine = payload.startLine;
@@ -44418,13 +44765,13 @@ var QdrantIndexWriter = class extends QdrantBase {
44418
44765
  const documents = [];
44419
44766
  for (const point of result.body.result?.points ?? []) {
44420
44767
  const payload = point.payload ?? {};
44421
- const path30 = typeof payload.path === "string" ? payload.path : void 0;
44422
- if (path30 === void 0 || !Array.isArray(point.vector))
44768
+ const path31 = typeof payload.path === "string" ? payload.path : void 0;
44769
+ if (path31 === void 0 || !Array.isArray(point.vector))
44423
44770
  continue;
44424
44771
  documents.push({
44425
44772
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
44426
44773
  text: typeof payload.text === "string" ? payload.text : "",
44427
- path: path30,
44774
+ path: path31,
44428
44775
  startLine: typeof payload.startLine === "number" ? payload.startLine : 1,
44429
44776
  endLine: typeof payload.endLine === "number" ? payload.endLine : 1,
44430
44777
  vector: point.vector
@@ -44451,9 +44798,9 @@ var QdrantIndexWriter = class extends QdrantBase {
44451
44798
  throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).`, result.status);
44452
44799
  }
44453
44800
  for (const point of result.body.result?.points ?? []) {
44454
- const path30 = point.payload?.path;
44455
- if (typeof path30 === "string")
44456
- paths.add(path30);
44801
+ const path31 = point.payload?.path;
44802
+ if (typeof path31 === "string")
44803
+ paths.add(path31);
44457
44804
  }
44458
44805
  offset = result.body.result?.next_page_offset;
44459
44806
  if (offset === void 0 || offset === null)
@@ -44867,8 +45214,8 @@ function teamSkillDocument(skill, body, vector, attribution) {
44867
45214
  vector
44868
45215
  };
44869
45216
  }
44870
- function nameFromPath(path30) {
44871
- return path30.startsWith("skill:") ? path30.slice("skill:".length) : path30;
45217
+ function nameFromPath(path31) {
45218
+ return path31.startsWith("skill:") ? path31.slice("skill:".length) : path31;
44872
45219
  }
44873
45220
  function toHit(match, self) {
44874
45221
  return {
@@ -45669,6 +46016,125 @@ function message(error51) {
45669
46016
  return error51 instanceof Error ? error51.message : String(error51);
45670
46017
  }
45671
46018
 
46019
+ // ../../packages/core/dist/office/mailStats.js
46020
+ var DETAIL_CAP = 50;
46021
+ function push(buckets, label, record2) {
46022
+ const existing = buckets.get(label);
46023
+ const line = `${new Date(record2.receivedAt).toLocaleString()} \u2014 ${record2.subject}`;
46024
+ if (existing === void 0) {
46025
+ buckets.set(label, { label, count: 1, detail: [line] });
46026
+ return;
46027
+ }
46028
+ existing.count += 1;
46029
+ if (existing.detail.length < DETAIL_CAP)
46030
+ existing.detail.push(line);
46031
+ }
46032
+ function dayKey(at) {
46033
+ const date5 = new Date(at);
46034
+ const month = String(date5.getMonth() + 1).padStart(2, "0");
46035
+ const day = String(date5.getDate()).padStart(2, "0");
46036
+ return `${String(date5.getFullYear())}-${month}-${day}`;
46037
+ }
46038
+ function hourKey(at) {
46039
+ return String(new Date(at).getHours()).padStart(2, "0");
46040
+ }
46041
+ function groupKey(record2, by) {
46042
+ switch (by) {
46043
+ case "folder":
46044
+ return record2.folder;
46045
+ case "day":
46046
+ return dayKey(record2.receivedAt);
46047
+ case "hour":
46048
+ return hourKey(record2.receivedAt);
46049
+ case "sender":
46050
+ return record2.sender;
46051
+ case "status":
46052
+ return record2.status ?? "none";
46053
+ }
46054
+ }
46055
+ function countBy(records, by, options = {}) {
46056
+ const buckets = /* @__PURE__ */ new Map();
46057
+ for (const record2 of records)
46058
+ push(buckets, groupKey(record2, by), record2);
46059
+ if (by === "day" && options.fillDays === true && records.length > 0) {
46060
+ const times = records.map((record2) => record2.receivedAt);
46061
+ const from = new Date(Math.min(...times));
46062
+ const to = new Date(Math.max(...times));
46063
+ from.setHours(0, 0, 0, 0);
46064
+ for (let day = from; day <= to; day = new Date(day.getTime() + 864e5)) {
46065
+ const key = dayKey(day.getTime());
46066
+ if (!buckets.has(key))
46067
+ buckets.set(key, { label: key, count: 0, detail: [] });
46068
+ }
46069
+ }
46070
+ if (by === "hour") {
46071
+ for (let hour = 0; hour < 24; hour++) {
46072
+ const key = String(hour).padStart(2, "0");
46073
+ if (!buckets.has(key))
46074
+ buckets.set(key, { label: key, count: 0, detail: [] });
46075
+ }
46076
+ }
46077
+ const rows = [...buckets.values()];
46078
+ 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));
46079
+ }
46080
+ function crossTab(records, by, splitBy) {
46081
+ const categories = countBy(records, by, { fillDays: true }).map((bucket) => bucket.label);
46082
+ const splits = [...new Set(records.map((record2) => groupKey(record2, splitBy)))].sort();
46083
+ const index = /* @__PURE__ */ new Map();
46084
+ for (const record2 of records) {
46085
+ const key = `${groupKey(record2, by)}\0${groupKey(record2, splitBy)}`;
46086
+ push(index, key, record2);
46087
+ }
46088
+ return {
46089
+ categories,
46090
+ series: splits.map((split) => ({
46091
+ name: split,
46092
+ values: categories.map((category) => index.get(`${category}\0${split}`)?.count ?? 0),
46093
+ detail: categories.map((category) => index.get(`${category}\0${split}`)?.detail ?? null)
46094
+ }))
46095
+ };
46096
+ }
46097
+ function extractNumber(record2, label) {
46098
+ const haystack = `${record2.subject}
46099
+ ${record2.preview}`;
46100
+ const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
46101
+ const pattern = new RegExp(`${escaped}[^0-9+-]{0,12}([+-]?[0-9][0-9,]*(?:\\.[0-9]+)?)`, "i");
46102
+ const match = pattern.exec(haystack);
46103
+ if (match?.[1] === void 0)
46104
+ return void 0;
46105
+ const value = Number(match[1].replace(/,/g, ""));
46106
+ return Number.isFinite(value) ? value : void 0;
46107
+ }
46108
+ function numberOverTime(records, label, how = "last") {
46109
+ const byDay = /* @__PURE__ */ new Map();
46110
+ let matched = 0;
46111
+ for (const record2 of [...records].sort((a, b) => a.receivedAt - b.receivedAt)) {
46112
+ const value = extractNumber(record2, label);
46113
+ if (value === void 0)
46114
+ continue;
46115
+ matched += 1;
46116
+ const key = dayKey(record2.receivedAt);
46117
+ const entry = byDay.get(key) ?? { values: [], detail: [] };
46118
+ entry.values.push(value);
46119
+ if (entry.detail.length < DETAIL_CAP) {
46120
+ entry.detail.push(`${new Date(record2.receivedAt).toLocaleTimeString()} \u2014 ${String(value)} \u2014 ${record2.subject}`);
46121
+ }
46122
+ byDay.set(key, entry);
46123
+ }
46124
+ const points = [...byDay.entries()].sort((a, b) => a[0].localeCompare(b[0])).map(([day, entry]) => ({
46125
+ label: day,
46126
+ 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],
46127
+ detail: entry.detail
46128
+ }));
46129
+ return { points, matched, skipped: records.length - matched };
46130
+ }
46131
+ function dailyChange(points) {
46132
+ return points.map((point, index) => ({
46133
+ label: point.label,
46134
+ change: index === 0 ? void 0 : point.value - points[index - 1].value
46135
+ }));
46136
+ }
46137
+
45672
46138
  // ../../packages/core/dist/office/mailIndex.js
45673
46139
  function parseStatusTag(subject) {
45674
46140
  if (/\[\s*alert\s*\]/i.test(subject))
@@ -46135,14 +46601,123 @@ function createMailCoverageTool(options) {
46135
46601
  }
46136
46602
  };
46137
46603
  }
46138
- function normaliseFolder(path30) {
46139
- return path30.toLowerCase().replace(/[\\/]+/g, "\\");
46604
+ function normaliseFolder(path31) {
46605
+ return path31.toLowerCase().replace(/[\\/]+/g, "\\");
46140
46606
  }
46141
46607
  function haystackOf(record2) {
46142
46608
  return `${record2.subject}
46143
46609
  ${record2.sender}
46144
46610
  ${record2.preview}`.toLowerCase();
46145
46611
  }
46612
+ var statsSchema = external_exports.object({
46613
+ by: external_exports.enum(["folder", "day", "hour", "sender", "status"]).describe("What each bar or point represents. `day` and `hour` are in local time."),
46614
+ 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."),
46615
+ withinHours: external_exports.number().min(0.1).max(24 * 365).optional().describe("Only mail received in this many hours."),
46616
+ status: external_exports.enum(["alert", "ok"]).optional().describe("Narrow to [ALERT] or [OK] messages first."),
46617
+ folder: external_exports.string().optional().describe("Narrow to a folder path first."),
46618
+ within: external_exports.array(external_exports.string().min(1)).max(500).optional().describe("Count only these message ids, from an earlier search_mail result."),
46619
+ 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.'),
46620
+ combine: external_exports.enum(["last", "max", "sum", "average"]).optional().describe("With numberLabel: what several messages in one day mean. Default last."),
46621
+ change: external_exports.boolean().optional().describe("With numberLabel: report the day-on-day movement rather than the value itself.")
46622
+ });
46623
+ function createMailStatsTool(options) {
46624
+ return {
46625
+ name: "mail_stats",
46626
+ group: "read",
46627
+ 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.',
46628
+ parametersSchema: statsSchema,
46629
+ execute: async (params) => {
46630
+ try {
46631
+ const all = await options.loadRecords();
46632
+ if (all.length === 0) {
46633
+ return {
46634
+ 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."
46635
+ };
46636
+ }
46637
+ let records = params.withinHours === void 0 ? [...all] : since(all, params.withinHours);
46638
+ if (params.status !== void 0)
46639
+ records = records.filter((r) => r.status === params.status);
46640
+ if (params.folder !== void 0) {
46641
+ const wanted = normaliseFolder(params.folder);
46642
+ records = records.filter((r) => normaliseFolder(r.folder).startsWith(wanted));
46643
+ }
46644
+ if (params.within !== void 0 && params.within.length > 0) {
46645
+ const keep = new Set(params.within);
46646
+ records = records.filter((r) => keep.has(r.id));
46647
+ }
46648
+ if (records.length === 0) {
46649
+ return { content: "No indexed messages match those filters, so there is nothing to count." };
46650
+ }
46651
+ if (params.numberLabel !== void 0) {
46652
+ const { points, matched, skipped } = numberOverTime(records, params.numberLabel, params.combine ?? "last");
46653
+ if (points.length === 0) {
46654
+ return {
46655
+ 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.`
46656
+ };
46657
+ }
46658
+ const rows = params.change === true ? dailyChange(points).map((entry) => ({
46659
+ label: entry.label,
46660
+ value: entry.change,
46661
+ detail: null
46662
+ })) : points.map((point) => ({ label: point.label, value: point.value, detail: point.detail }));
46663
+ const usable = rows.filter((row) => row.value !== void 0);
46664
+ return {
46665
+ content: [
46666
+ `${String(matched)} message(s) carried a number labelled "${params.numberLabel}"${skipped > 0 ? `, ${String(skipped)} did not and were left out` : ""}.`,
46667
+ 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.`,
46668
+ "",
46669
+ JSON.stringify({
46670
+ categories: usable.map((row) => row.label),
46671
+ series: [
46672
+ {
46673
+ name: params.change === true ? `${params.numberLabel} change` : params.numberLabel,
46674
+ values: usable.map((row) => row.value),
46675
+ ...params.change === true ? {} : { detail: usable.map((row) => row.detail) }
46676
+ }
46677
+ ]
46678
+ }),
46679
+ "",
46680
+ "Pass this to show_chart as a line chart. Keep `detail` on the series so the user can open a point."
46681
+ ].join("\n")
46682
+ };
46683
+ }
46684
+ if (params.splitBy !== void 0) {
46685
+ const table = crossTab(records, params.by, params.splitBy);
46686
+ return {
46687
+ content: [
46688
+ `${String(records.length)} message(s), by ${params.by} and ${params.splitBy}.`,
46689
+ "",
46690
+ JSON.stringify(table),
46691
+ "",
46692
+ "Pass this to show_chart as stackedBar or groupedBar. `detail` is already aligned."
46693
+ ].join("\n")
46694
+ };
46695
+ }
46696
+ const buckets = countBy(records, params.by, { fillDays: true });
46697
+ return {
46698
+ content: [
46699
+ `${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." : ""),
46700
+ "",
46701
+ JSON.stringify({
46702
+ categories: buckets.map((bucket) => bucket.label),
46703
+ series: [
46704
+ {
46705
+ name: params.status === void 0 ? "Messages" : params.status.toUpperCase(),
46706
+ values: buckets.map((bucket) => bucket.count),
46707
+ detail: buckets.map((bucket) => bucket.detail.length === 0 ? null : bucket.detail)
46708
+ }
46709
+ ]
46710
+ }),
46711
+ "",
46712
+ "Pass this to show_chart. Keep `detail` so the user can open a bar and see what is in it."
46713
+ ].join("\n")
46714
+ };
46715
+ } catch (error51) {
46716
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
46717
+ }
46718
+ }
46719
+ };
46720
+ }
46146
46721
 
46147
46722
  // ../../packages/core/dist/office/mailStore.js
46148
46723
  import fs5 from "node:fs/promises";
@@ -46485,7 +47060,7 @@ async function refreshMail(options) {
46485
47060
  const limit = options.batchLimit ?? 2e3;
46486
47061
  const previewChars = options.previewChars ?? 400;
46487
47062
  const sinceMs = Date.now() - options.days * 24 * 60 * 60 * 1e3;
46488
- const harvested = await options.harvest(options.folders.map((path30) => ({ path: path30, sinceMs })), { limit, previewChars });
47063
+ const harvested = await options.harvest(options.folders.map((path31) => ({ path: path31, sinceMs })), { limit, previewChars });
46489
47064
  const fetched = harvested.messages.map(toRecord);
46490
47065
  if (fetched.length === 0) {
46491
47066
  return { added: 0, more: false, total: known.length, embedded: 0, backfilled: 0, complete: [] };
@@ -46526,9 +47101,9 @@ async function syncMail(options) {
46526
47101
  const backfillDone = await options.store.loadBackfillState();
46527
47102
  const limit = options.batchLimit ?? 500;
46528
47103
  const previewChars = options.previewChars ?? 400;
46529
- const forwardRequests = options.folders.map((path30) => {
46530
- const mark = marks.get(path30);
46531
- return mark === void 0 ? { path: path30 } : { path: path30, sinceMs: mark.newest - 1e3 };
47104
+ const forwardRequests = options.folders.map((path31) => {
47105
+ const mark = marks.get(path31);
47106
+ return mark === void 0 ? { path: path31 } : { path: path31, sinceMs: mark.newest - 1e3 };
46532
47107
  });
46533
47108
  const forward = await options.harvest(forwardRequests, { limit, previewChars });
46534
47109
  let candidates = forward.messages.map(toRecord);
@@ -46537,15 +47112,15 @@ async function syncMail(options) {
46537
47112
  let more = forward.truncated;
46538
47113
  const remaining = limit - candidates.length;
46539
47114
  const floor = options.retentionMonths === void 0 ? void 0 : monthsBefore(options.now ?? Date.now(), options.retentionMonths);
46540
- const outstanding = options.folders.filter((path30) => marks.has(path30) && backfillDone[path30] !== true);
46541
- const atFloor = floor === void 0 ? [] : outstanding.filter((path30) => marks.get(path30).oldest <= floor);
46542
- const behind = outstanding.filter((path30) => !atFloor.includes(path30));
47115
+ const outstanding = options.folders.filter((path31) => marks.has(path31) && backfillDone[path31] !== true);
47116
+ const atFloor = floor === void 0 ? [] : outstanding.filter((path31) => marks.get(path31).oldest <= floor);
47117
+ const behind = outstanding.filter((path31) => !atFloor.includes(path31));
46543
47118
  completed.push(...atFloor);
46544
47119
  if (remaining > 0 && behind.length > 0 && options.signal?.aborted !== true) {
46545
- const backRequests = behind.map((path30) => ({
46546
- path: path30,
47120
+ const backRequests = behind.map((path31) => ({
47121
+ path: path31,
46547
47122
  // Strictly older, so the oldest held message is not fetched again every pass.
46548
- beforeMs: marks.get(path30).oldest,
47123
+ beforeMs: marks.get(path31).oldest,
46549
47124
  // And no older than retention wants. The harvest ANDs the two into one window.
46550
47125
  ...floor === void 0 ? {} : { sinceMs: floor }
46551
47126
  }));
@@ -46553,9 +47128,9 @@ async function syncMail(options) {
46553
47128
  backfilled = backward.messages.length;
46554
47129
  candidates = [...candidates, ...backward.messages.map(toRecord)];
46555
47130
  const returnedFor = new Set(backward.messages.map((message3) => message3.folder));
46556
- for (const path30 of behind) {
46557
- if (!returnedFor.has(path30))
46558
- completed.push(path30);
47131
+ for (const path31 of behind) {
47132
+ if (!returnedFor.has(path31))
47133
+ completed.push(path31);
46559
47134
  }
46560
47135
  if (backward.truncated || backfilled > 0)
46561
47136
  more = true;
@@ -46563,7 +47138,7 @@ async function syncMail(options) {
46563
47138
  if (completed.length > 0) {
46564
47139
  await options.store.saveBackfillState({
46565
47140
  ...backfillDone,
46566
- ...Object.fromEntries(completed.map((path30) => [path30, true]))
47141
+ ...Object.fromEntries(completed.map((path31) => [path31, true]))
46567
47142
  });
46568
47143
  }
46569
47144
  const fresh = withoutKnown(candidates, known);
@@ -47481,14 +48056,14 @@ function formatBytes(size) {
47481
48056
  return `${(size / (1 << 10)).toFixed(1)}KB`;
47482
48057
  return `${String(size)}B`;
47483
48058
  }
47484
- async function readTail(fs24, path30, size, count) {
48059
+ async function readTail(fs25, path31, size, count) {
47485
48060
  let span = Math.min(size, CHUNK);
47486
48061
  let text;
47487
48062
  let start;
47488
48063
  for (; ; ) {
47489
48064
  start = Math.max(0, size - span);
47490
48065
  const decoder = new StringDecoder("utf8");
47491
- text = decoder.write(await fs24.readBytesSlice(path30, start, size)) + decoder.end();
48066
+ text = decoder.write(await fs25.readBytesSlice(path31, start, size)) + decoder.end();
47492
48067
  const enough = text.split("\n").length > count;
47493
48068
  if (enough || start === 0 || span >= size)
47494
48069
  break;
@@ -47506,7 +48081,7 @@ async function readTail(fs24, path30, size, count) {
47506
48081
  hasMoreAfter: false
47507
48082
  };
47508
48083
  }
47509
- async function readLineWindow(fs24, path30, size, from, count) {
48084
+ async function readLineWindow(fs25, path31, size, from, count) {
47510
48085
  const decoder = new StringDecoder("utf8");
47511
48086
  const lines = [];
47512
48087
  let pending = "";
@@ -47521,7 +48096,7 @@ async function readLineWindow(fs24, path30, size, from, count) {
47521
48096
  };
47522
48097
  scan: while (position < size) {
47523
48098
  const end = Math.min(size, position + CHUNK);
47524
- pending += decoder.write(await fs24.readBytesSlice(path30, position, end));
48099
+ pending += decoder.write(await fs25.readBytesSlice(path31, position, end));
47525
48100
  position = end;
47526
48101
  const parts = pending.split(/\r\n|\r|\n/);
47527
48102
  pending = parts.pop() ?? "";
@@ -47544,13 +48119,13 @@ async function readLineWindow(fs24, path30, size, from, count) {
47544
48119
  hasMoreAfter: !reachedEnd || lineNumber > from + lines.length
47545
48120
  };
47546
48121
  }
47547
- async function countLines(fs24, path30, size) {
48122
+ async function countLines(fs25, path31, size) {
47548
48123
  let newlines = 0;
47549
48124
  let position = 0;
47550
48125
  let lastByte = -1;
47551
48126
  while (position < size) {
47552
48127
  const end = Math.min(size, position + CHUNK);
47553
- const buffer = await fs24.readBytesSlice(path30, position, end);
48128
+ const buffer = await fs25.readBytesSlice(path31, position, end);
47554
48129
  for (const byte of buffer)
47555
48130
  if (byte === 10)
47556
48131
  newlines += 1;
@@ -53562,25 +54137,64 @@ async function discoverWorkspaceVenv(workspaceRoot) {
53562
54137
  continue;
53563
54138
  }
53564
54139
  let uvManaged = false;
53565
- let pythonVersion;
54140
+ let pythonVersion2;
53566
54141
  try {
53567
54142
  const config2 = await fs8.readFile(path14.join(candidate, "pyvenv.cfg"), "utf8");
53568
54143
  uvManaged = /^\s*uv\s*=/m.test(config2);
53569
- pythonVersion = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
54144
+ pythonVersion2 = /^\s*version(?:_info)?\s*=\s*(.+)$/m.exec(config2)?.[1]?.trim();
53570
54145
  } catch {
53571
54146
  }
53572
54147
  return {
53573
54148
  path: candidate,
53574
54149
  interpreter,
53575
54150
  uvManaged,
53576
- ...pythonVersion !== void 0 ? { pythonVersion } : {}
54151
+ ...pythonVersion2 !== void 0 ? { pythonVersion: pythonVersion2 } : {}
53577
54152
  };
53578
54153
  }
53579
54154
  return void 0;
53580
54155
  }
54156
+ var BARE_PYTHON_CANDIDATES = ["python3", "python"];
54157
+ async function detectBareInterpreter(configuredPath) {
54158
+ const candidates = configuredPath !== void 0 && configuredPath.trim().length > 0 ? [configuredPath.trim()] : [...BARE_PYTHON_CANDIDATES];
54159
+ for (const candidate of candidates) {
54160
+ try {
54161
+ const version2 = await pythonVersion(candidate);
54162
+ if (version2 !== void 0)
54163
+ return { path: candidate, version: version2 };
54164
+ } catch {
54165
+ }
54166
+ }
54167
+ return void 0;
54168
+ }
54169
+ async function pythonVersion(program) {
54170
+ const { spawn: spawn7 } = await import("node:child_process");
54171
+ return new Promise((resolve) => {
54172
+ const child = spawn7(program, ["-c", 'import sys; print("%d.%d.%d" % sys.version_info[:3])'], {
54173
+ shell: false,
54174
+ env: minimalPythonEnv()
54175
+ });
54176
+ let out = "";
54177
+ child.stdout.on("data", (chunk) => out += chunk.toString());
54178
+ child.on("error", () => resolve(void 0));
54179
+ const timer = setTimeout(() => {
54180
+ child.kill();
54181
+ resolve(void 0);
54182
+ }, 1e4);
54183
+ child.on("close", (code) => {
54184
+ clearTimeout(timer);
54185
+ const version2 = out.trim();
54186
+ if (code !== 0 || !/^\d+\.\d+\.\d+$/.test(version2)) {
54187
+ resolve(void 0);
54188
+ return;
54189
+ }
54190
+ const major = Number(version2.split(".")[0]);
54191
+ resolve(major >= 3 ? version2 : void 0);
54192
+ });
54193
+ });
54194
+ }
53581
54195
 
53582
54196
  // ../../packages/core/dist/python/worker.js
53583
- import { execFile as execFile4, spawn as spawn2 } from "node:child_process";
54197
+ import { execFile as execFile4, spawn as spawn3 } from "node:child_process";
53584
54198
  import { createInterface } from "node:readline";
53585
54199
  var PythonWorkerError = class extends Error {
53586
54200
  traceback;
@@ -53604,7 +54218,7 @@ var PythonWorker = class {
53604
54218
  start() {
53605
54219
  if (this.child !== void 0 && this.child.exitCode === null && !this.child.killed)
53606
54220
  return this.child;
53607
- const child = spawn2(this.options.pythonPath, [this.options.workerScript], {
54221
+ const child = spawn3(this.options.pythonPath, [this.options.workerScript], {
53608
54222
  cwd: this.options.cwd,
53609
54223
  env: this.options.env,
53610
54224
  windowsHide: true,
@@ -54245,7 +54859,7 @@ function makeWriteTool(context, options) {
54245
54859
  if (context.installDeps === void 0) {
54246
54860
  await restore();
54247
54861
  return {
54248
- 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.`,
54862
+ 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.",
54249
54863
  isError: true
54250
54864
  };
54251
54865
  }
@@ -54427,8 +55041,7 @@ var PythonManager = class {
54427
55041
  if (this.uv === void 0)
54428
55042
  this.uv = await detectUv(config2.uvPath);
54429
55043
  if (this.uv === void 0) {
54430
- this.ready = false;
54431
- this.detail = "uv was not found. Install it and set the path in Settings \u2192 Python, or add it to PATH.";
55044
+ await this.startWithoutUv(config2, this.options.workspaceRoot);
54432
55045
  return;
54433
55046
  }
54434
55047
  try {
@@ -54576,6 +55189,16 @@ var PythonManager = class {
54576
55189
  ...generated !== void 0 ? { generateSource: generated } : {},
54577
55190
  worker,
54578
55191
  onChanged: () => this.refresh(),
55192
+ /*
55193
+ * No installing against an interpreter we do not own.
55194
+ *
55195
+ * Absent rather than failing, so the refusal happens before a file is written and names the
55196
+ * package. The reason travels with it because the advice differs: install uv, versus
55197
+ * install the package into the environment you already have.
55198
+ */
55199
+ ...this.venvSource === "interpreter" ? {
55200
+ 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.`
55201
+ } : {},
54579
55202
  ...uv !== void 0 ? {
54580
55203
  installDeps: (packages) => installDependencies({
54581
55204
  uv,
@@ -54589,6 +55212,44 @@ var PythonManager = class {
54589
55212
  } : {}
54590
55213
  };
54591
55214
  }
55215
+ /**
55216
+ * Starts against an interpreter we did not create and do not own.
55217
+ *
55218
+ * Deliberately parallel to the uv path rather than folded into it: the two differ on the one
55219
+ * decision that matters — whether installing a package is allowed — and a single path with a
55220
+ * flag threaded through it is how that decision ends up being made in the wrong place.
55221
+ */
55222
+ async startWithoutUv(config2, workspaceRoot) {
55223
+ const bare = await detectBareInterpreter(config2.interpreterPath);
55224
+ if (bare === void 0) {
55225
+ this.ready = false;
55226
+ 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.";
55227
+ return;
55228
+ }
55229
+ try {
55230
+ const env2 = minimalPythonEnv(this.options.sessionEnv?.() ?? {});
55231
+ this.interpreter = bare.path;
55232
+ this.venvPath = "";
55233
+ this.venvSource = "interpreter";
55234
+ this.venvIsUvManaged = false;
55235
+ const workerScript = await this.writeWorkerScript();
55236
+ this.worker ??= new PythonWorker({
55237
+ pythonPath: bare.path,
55238
+ workerScript,
55239
+ cwd: workspaceRoot,
55240
+ env: env2,
55241
+ logger: this.options.logger,
55242
+ timeoutMs: this.timeoutMs
55243
+ });
55244
+ await this.refresh();
55245
+ this.ready = true;
55246
+ 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.`;
55247
+ } catch (error51) {
55248
+ this.ready = false;
55249
+ this.detail = error51 instanceof Error ? error51.message : String(error51);
55250
+ this.options.logger.warn("python environment failed to start", this.detail);
55251
+ }
55252
+ }
54592
55253
  status() {
54593
55254
  return {
54594
55255
  enabled: this.enabled,
@@ -55390,13 +56051,13 @@ async function runAgentTurn(provider, conversation, userMessage, toolRegistry, t
55390
56051
  // ../../packages/core/dist/host/bridge.js
55391
56052
  import { createHash as createHash3, randomUUID as randomUUID3 } from "node:crypto";
55392
56053
  import { watch as watchPath } from "node:fs";
55393
- import { spawn as spawn5 } from "node:child_process";
56054
+ import { spawn as spawn6 } from "node:child_process";
55394
56055
  import fs18 from "node:fs/promises";
55395
56056
  import os2 from "node:os";
55396
56057
  import path23 from "node:path";
55397
56058
 
55398
56059
  // ../../packages/core/dist/office/bridge.js
55399
- import { spawn as spawn3 } from "node:child_process";
56060
+ import { spawn as spawn4 } from "node:child_process";
55400
56061
  import fs15 from "node:fs/promises";
55401
56062
  import path21 from "node:path";
55402
56063
 
@@ -57379,7 +58040,7 @@ var OfficeBridge = class {
57379
58040
  const BOM = "\uFEFF";
57380
58041
  await fs15.writeFile(target, `${BOM}${OFFICE_WORKER_SOURCE}`, "utf8");
57381
58042
  this.scriptPath = target;
57382
- const child = spawn3("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
58043
+ const child = spawn4("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", target], { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
57383
58044
  this.child = child;
57384
58045
  this.buffer = "";
57385
58046
  child.stdout?.setEncoding("utf8");
@@ -57972,17 +58633,17 @@ var WebviewApprovalGate = class {
57972
58633
  // ../../packages/core/dist/platform/node/filesystem.js
57973
58634
  import fs16 from "node:fs/promises";
57974
58635
  var NodeFileSystem = class {
57975
- async readFile(path30) {
57976
- return fs16.readFile(path30, "utf8");
58636
+ async readFile(path31) {
58637
+ return fs16.readFile(path31, "utf8");
57977
58638
  }
57978
- async readBytes(path30) {
57979
- return fs16.readFile(path30);
58639
+ async readBytes(path31) {
58640
+ return fs16.readFile(path31);
57980
58641
  }
57981
- async readBytesSlice(path30, start, end) {
58642
+ async readBytesSlice(path31, start, end) {
57982
58643
  const length = Math.max(0, end - start);
57983
58644
  if (length === 0)
57984
58645
  return Buffer.alloc(0);
57985
- const handle = await fs16.open(path30, "r");
58646
+ const handle = await fs16.open(path31, "r");
57986
58647
  try {
57987
58648
  const buffer = Buffer.alloc(length);
57988
58649
  const { bytesRead } = await handle.read(buffer, 0, length, start);
@@ -57991,11 +58652,11 @@ var NodeFileSystem = class {
57991
58652
  await handle.close();
57992
58653
  }
57993
58654
  }
57994
- async writeFile(path30, contents) {
57995
- await fs16.writeFile(path30, contents, "utf8");
58655
+ async writeFile(path31, contents) {
58656
+ await fs16.writeFile(path31, contents, "utf8");
57996
58657
  }
57997
- async stat(path30) {
57998
- const stat = await fs16.lstat(path30);
58658
+ async stat(path31) {
58659
+ const stat = await fs16.lstat(path31);
57999
58660
  return {
58000
58661
  size: stat.size,
58001
58662
  mtimeMs: stat.mtimeMs,
@@ -58004,8 +58665,8 @@ var NodeFileSystem = class {
58004
58665
  isSymbolicLink: stat.isSymbolicLink()
58005
58666
  };
58006
58667
  }
58007
- async readdir(path30) {
58008
- const entries = await fs16.readdir(path30, { withFileTypes: true });
58668
+ async readdir(path31) {
58669
+ const entries = await fs16.readdir(path31, { withFileTypes: true });
58009
58670
  return entries.map((entry) => ({
58010
58671
  name: entry.name,
58011
58672
  isFile: entry.isFile(),
@@ -58013,21 +58674,21 @@ var NodeFileSystem = class {
58013
58674
  isSymbolicLink: entry.isSymbolicLink()
58014
58675
  }));
58015
58676
  }
58016
- async exists(path30) {
58677
+ async exists(path31) {
58017
58678
  try {
58018
- await fs16.access(path30);
58679
+ await fs16.access(path31);
58019
58680
  return true;
58020
58681
  } catch {
58021
58682
  return false;
58022
58683
  }
58023
58684
  }
58024
- async mkdir(path30) {
58025
- await fs16.mkdir(path30, { recursive: true });
58685
+ async mkdir(path31) {
58686
+ await fs16.mkdir(path31, { recursive: true });
58026
58687
  }
58027
58688
  };
58028
58689
 
58029
58690
  // ../../packages/core/dist/platform/node/terminal.js
58030
- import { execFile as execFile6, spawn as spawn4 } from "node:child_process";
58691
+ import { execFile as execFile6, spawn as spawn5 } from "node:child_process";
58031
58692
  var NodeTerminalProcess = class {
58032
58693
  child;
58033
58694
  dataListeners = [];
@@ -58078,7 +58739,7 @@ var NodeTerminalProcess = class {
58078
58739
  };
58079
58740
  var NodeTerminal = class {
58080
58741
  run(command, options = {}) {
58081
- const child = spawn4(command, {
58742
+ const child = spawn5(command, {
58082
58743
  cwd: options.cwd,
58083
58744
  env: options.env ? { ...process.env, ...options.env } : process.env,
58084
58745
  shell: true,
@@ -58256,7 +58917,33 @@ async function toSummary(profile, secrets) {
58256
58917
  baseUrl: profile.baseUrl,
58257
58918
  model: profile.model,
58258
58919
  authType: profile.auth.type,
58259
- hasApiKey: profile.auth.type === "apiKey" && await secrets.get(profile.auth.apiKeyRef) !== void 0,
58920
+ hasApiKey: profile.auth.type === "apiKey" && await resolveSecretRef(profile.auth.apiKeyRef, { secrets }) !== void 0,
58921
+ /*
58922
+ * The reference itself, when it names the environment.
58923
+ *
58924
+ * Sending it is not a secret leak (invariant 7) — a variable *name* is not its value, and the
58925
+ * user typed it. It is what lets the panel show "from $API_TOKEN" instead of an empty box that
58926
+ * reads as an unconfigured profile.
58927
+ */
58928
+ ...profile.auth.type === "apiKey" && describeSecretRef(profile.auth.apiKeyRef).kind === "env" ? { apiKeyEnvVar: describeSecretRef(profile.auth.apiKeyRef).envVar } : {},
58929
+ // Not a secret: a command describes how to *get* a credential. The token it produces never
58930
+ // crosses the bridge, and a form cannot edit what it is never shown.
58931
+ // References only — a store key or a variable name, never the credential (invariant 7).
58932
+ ...profile.auth.type === "header" ? { authHeaders: profile.auth.headers } : {},
58933
+ ...profile.auth.type === "tokenCommand" ? {
58934
+ /*
58935
+ * `env` is dropped on the way out, deliberately.
58936
+ *
58937
+ * It is the one field here somebody might have put a credential in, and the panel has no
58938
+ * business rendering it. Dropping it from the summary rather than from the schema means a
58939
+ * hand-written one keeps working; the form simply never sees it, and never sends it back.
58940
+ */
58941
+ tokenCommand: ((whole) => {
58942
+ const { env: env2, ...rest } = whole;
58943
+ void env2;
58944
+ return rest;
58945
+ })(profile.auth.tokenCommand)
58946
+ } : {},
58260
58947
  hasClientSecret: false,
58261
58948
  hasCertPassphrase: false
58262
58949
  };
@@ -58770,6 +59457,9 @@ function wireChatBridge(services) {
58770
59457
  let cachedProgrammingProfileId;
58771
59458
  let cachedOffice = {};
58772
59459
  let cachedMail = {};
59460
+ let cachedDatasets = [];
59461
+ let datasetSummaryForPrompt = [];
59462
+ let cachedPythonEnabled = false;
58773
59463
  const mailStore = new MailStore(storageDir);
58774
59464
  let mailBusy = false;
58775
59465
  let mailTimer;
@@ -58802,6 +59492,12 @@ function wireChatBridge(services) {
58802
59492
  cachedProgrammingProfileId = config2.programmingProfileId;
58803
59493
  cachedOffice = config2.office ?? {};
58804
59494
  cachedMail = config2.mail ?? {};
59495
+ cachedDatasets = config2.datasets ?? [];
59496
+ cachedPythonEnabled = config2.python?.dynamicTools === "on";
59497
+ datasetSummaryForPrompt = await Promise.all(cachedDatasets.map(async (dataset) => ({
59498
+ name: dataset.name,
59499
+ records: (await new DatasetStore(storageDir, dataset.id).load()).length
59500
+ })));
58805
59501
  cachedModeId = config2.modeId;
58806
59502
  cachedMaxIterations = config2.maxIterations ?? 25;
58807
59503
  cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
@@ -58902,7 +59598,7 @@ function wireChatBridge(services) {
58902
59598
  platform: process.platform === "win32" ? "win32" : "posix"
58903
59599
  });
58904
59600
  }
58905
- function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic) {
59601
+ function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic, datasetSemanticForTools) {
58906
59602
  const combined = new ToolRegistry();
58907
59603
  for (const tool of builtinTools.list())
58908
59604
  combined.register(tool);
@@ -58989,6 +59685,16 @@ function wireChatBridge(services) {
58989
59685
  if (codebase !== void 0) {
58990
59686
  combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
58991
59687
  }
59688
+ if (cachedDatasets.length > 0) {
59689
+ combined.register(createSearchDataTool({
59690
+ load: async () => Promise.all(cachedDatasets.map(async (dataset) => ({
59691
+ id: dataset.id,
59692
+ name: dataset.name,
59693
+ records: await new DatasetStore(storageDir, dataset.id).load()
59694
+ }))),
59695
+ ...datasetSemanticForTools !== void 0 ? { semantic: datasetSemanticForTools } : {}
59696
+ }));
59697
+ }
58992
59698
  if (officeSupported() && (cachedOffice.excel === true || cachedOffice.outlook === true)) {
58993
59699
  const officeOptions = { bridge: office() };
58994
59700
  if (cachedOffice.excel === true) {
@@ -59016,6 +59722,7 @@ function wireChatBridge(services) {
59016
59722
  combined.register(createSearchMailTool(mailToolOptions));
59017
59723
  combined.register(createMailPatternsTool(mailToolOptions));
59018
59724
  combined.register(createMailCoverageTool(mailToolOptions));
59725
+ combined.register(createMailStatsTool(mailToolOptions));
59019
59726
  combined.register(createOpenEmailTool({
59020
59727
  display: async (id) => office().request({ op: "outlook.display", id })
59021
59728
  }));
@@ -59138,7 +59845,8 @@ function wireChatBridge(services) {
59138
59845
  try {
59139
59846
  const { config: config2 } = await configManager.load();
59140
59847
  const refs = (config2.profiles ?? []).flatMap((profile) => SECRET_REFS_PER_PROFILE.map((refFor) => refFor(profile.id)));
59141
- const values = await Promise.all(refs.map((ref) => secrets.get(ref)));
59848
+ const named = (config2.profiles ?? []).map((profile) => profile.auth.type === "apiKey" ? profile.auth.apiKeyRef : void 0).filter((ref) => ref !== void 0);
59849
+ const values = await Promise.all([.../* @__PURE__ */ new Set([...refs, ...named])].map((ref) => resolveSecretRef(ref, { secrets })));
59142
59850
  cachedSecretValues = values.filter((value) => value !== void 0 && value.length > 0);
59143
59851
  return [...cachedSecretValues];
59144
59852
  } catch (error51) {
@@ -59262,6 +59970,9 @@ function wireChatBridge(services) {
59262
59970
  expertAvailable: expertCliInfo !== void 0,
59263
59971
  // Named only when there is an index to prefer.
59264
59972
  mailIndexed: cachedMail.enabled === true && cachedOffice.outlook === true,
59973
+ // Counted here rather than in the prompt builder, which has no filesystem.
59974
+ datasets: datasetSummaryForPrompt,
59975
+ canWriteCollectors: cachedPythonEnabled,
59265
59976
  /*
59266
59977
  * Either the whole list or a count and an instruction to search — never both, and
59267
59978
  * never neither. `renderSkillsHintForPrompt` explains why the count stays.
@@ -59412,7 +60123,17 @@ function wireChatBridge(services) {
59412
60123
  * is frequently a local Qdrant while the code goes to a shared cluster — mail is the
59413
60124
  * corpus people most want kept off a team's infrastructure.
59414
60125
  */
59415
- mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0
60126
+ mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0,
60127
+ /*
60128
+ * Datasets share one collection, resolved against whichever store `retrieval.stores.data`
60129
+ * names — the same per-corpus routing §12e added, for the same reason: somebody's own
60130
+ * collected data is frequently the corpus they most want kept off a shared cluster.
60131
+ */
60132
+ await (async () => {
60133
+ const collection = datasetCollectionName(config2);
60134
+ const search2 = await resolveDatasetSearch(config2);
60135
+ return collection !== void 0 && search2 !== void 0 && embedder !== void 0 ? { searcher: search2.searcher, embedder, collection } : void 0;
60136
+ })()
59416
60137
  );
59417
60138
  const turnRegistry = schedule !== void 0 ? registryForSchedule(fullRegistry.list(), schedule) : fullRegistry;
59418
60139
  turnOptions.timeoutForTool = toolTimeout;
@@ -59448,6 +60169,8 @@ function wireChatBridge(services) {
59448
60169
  expertInformed = true;
59449
60170
  if (CONTROL_TOOLS.has(toolCall.name))
59450
60171
  return;
60172
+ if (chartFromToolCall(toolCall.name, toolCall.arguments) !== void 0)
60173
+ return;
59451
60174
  const summary = {
59452
60175
  id: toolCall.id,
59453
60176
  name: toolCall.name,
@@ -59461,6 +60184,11 @@ function wireChatBridge(services) {
59461
60184
  post({ type: "textChunk", text: result.content });
59462
60185
  return;
59463
60186
  }
60187
+ const chart = chartFromToolCall(toolCall.name, toolCall.arguments);
60188
+ if (chart !== void 0) {
60189
+ post(chart.kind === "chart" ? { type: "chart", chart: chart.chart, ...expertInformed ? { expertInformed } : {} } : { type: "chartError", message: chart.message });
60190
+ return;
60191
+ }
59464
60192
  const summary = {
59465
60193
  id: toolCall.id,
59466
60194
  name: toolCall.name,
@@ -59500,8 +60228,8 @@ function wireChatBridge(services) {
59500
60228
  }
59501
60229
  }
59502
60230
  async function buildAuthFromInput(input, id) {
59503
- async function persistSecret(ref, typed) {
59504
- const value = typed?.trim() ?? "";
60231
+ async function persistSecret(ref, typed2) {
60232
+ const value = typed2?.trim() ?? "";
59505
60233
  if (value.length > 0) {
59506
60234
  await secrets.set(ref, value);
59507
60235
  return true;
@@ -59525,8 +60253,47 @@ function wireChatBridge(services) {
59525
60253
  }
59526
60254
  };
59527
60255
  }
60256
+ if (input.authType === "header") {
60257
+ const headers = (input.authHeaders ?? []).map((header) => ({
60258
+ name: header.name.trim(),
60259
+ valueRef: header.valueRef.trim(),
60260
+ ...header.prefix !== void 0 && header.prefix.length > 0 ? { prefix: header.prefix } : {}
60261
+ })).filter((header) => header.name.length > 0 && header.valueRef.length > 0);
60262
+ const stored = await Promise.all(headers.map(async (header, index) => {
60263
+ if (describeSecretRef(header.valueRef).kind === "env")
60264
+ return header;
60265
+ const ref = `profile:${id}:header:${String(index)}`;
60266
+ await secrets.set(ref, header.valueRef);
60267
+ return { ...header, valueRef: ref };
60268
+ }));
60269
+ return stored.length > 0 ? { type: "header", headers: stored } : { type: "none" };
60270
+ }
60271
+ if (input.authType === "tokenCommand") {
60272
+ if (services.executableAuthRefusal !== void 0)
60273
+ throw new Error(services.executableAuthRefusal);
60274
+ const existing2 = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60275
+ if (input.tokenCommand === void 0 || input.tokenCommand.command.length === 0) {
60276
+ return existing2?.auth.type === "tokenCommand" ? existing2.auth : { type: "none" };
60277
+ }
60278
+ return {
60279
+ type: "tokenCommand",
60280
+ tokenCommand: {
60281
+ ...input.tokenCommand,
60282
+ command: input.tokenCommand.command.filter((part) => part.trim().length > 0)
60283
+ }
60284
+ };
60285
+ }
59528
60286
  if (input.authType === "none")
59529
60287
  return { type: "none" };
60288
+ const typed = input.apiKey.trim();
60289
+ if (describeSecretRef(typed).kind === "env") {
60290
+ await secrets.delete(apiKeyRefFor(id));
60291
+ return { type: "apiKey", apiKeyRef: typed };
60292
+ }
60293
+ const existing = (await configManager.load()).config.profiles?.find((profile) => profile.id === id);
60294
+ if (typed.length === 0 && existing?.auth.type === "apiKey" && describeSecretRef(existing.auth.apiKeyRef).kind === "env") {
60295
+ return existing.auth;
60296
+ }
59530
60297
  const apiKeyRef = apiKeyRefFor(id);
59531
60298
  if (await persistSecret(apiKeyRef, input.apiKey)) {
59532
60299
  return { type: "apiKey", apiKeyRef };
@@ -60126,8 +60893,8 @@ function wireChatBridge(services) {
60126
60893
  limit: limits.limit,
60127
60894
  previewChars: limits.previewChars
60128
60895
  });
60129
- for (const path30 of answer.skipped ?? [])
60130
- skipped.add(path30);
60896
+ for (const path31 of answer.skipped ?? [])
60897
+ skipped.add(path31);
60131
60898
  return { messages: answer.messages, truncated: answer.truncated };
60132
60899
  },
60133
60900
  ...embedder !== void 0 && search !== void 0 && collection !== void 0 ? {
@@ -60159,6 +60926,206 @@ function wireChatBridge(services) {
60159
60926
  endIndexing("mail");
60160
60927
  }
60161
60928
  }
60929
+ const datasetTimers = /* @__PURE__ */ new Map();
60930
+ const datasetBusy = /* @__PURE__ */ new Set();
60931
+ const datasetResults = /* @__PURE__ */ new Map();
60932
+ function datasetStoreFor(id) {
60933
+ return new DatasetStore(storageDir, id);
60934
+ }
60935
+ function datasetCollectionName(config2) {
60936
+ const base = codebaseIndexName(config2);
60937
+ return base === void 0 ? void 0 : `${base}-data`;
60938
+ }
60939
+ async function resolveDatasetSearch(config2, dataset) {
60940
+ const wanted = dataset?.storeId ?? storeIdFor("data", config2);
60941
+ return resolveSearch(config2, wanted);
60942
+ }
60943
+ async function datasetSemantic(config2, dataset) {
60944
+ const collection = datasetCollectionName(config2);
60945
+ const search = await resolveDatasetSearch(config2, dataset);
60946
+ const embedder = await resolveEmbedder(config2);
60947
+ if (collection === void 0 || search === void 0 || embedder === void 0)
60948
+ return void 0;
60949
+ return {
60950
+ embedder,
60951
+ collection,
60952
+ writer: createVectorIndexWriter(httpClient, search.store, await vectorStoreConnectionFor(search.store, search.id)),
60953
+ searcher: search.searcher
60954
+ };
60955
+ }
60956
+ async function runDatasetSync(id, reason) {
60957
+ if (datasetBusy.has(id))
60958
+ return;
60959
+ const config2 = await loadSettings();
60960
+ const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
60961
+ if (dataset === void 0)
60962
+ return;
60963
+ datasetBusy.add(id);
60964
+ const signal = beginIndexing(`dataset:${id}`);
60965
+ reportIndexing("dataset", `Syncing ${dataset.name}`, { detail: `via ${dataset.toolName}` });
60966
+ try {
60967
+ const semantic = await datasetSemantic(config2, dataset);
60968
+ const result = await syncDataset({
60969
+ datasetId: id,
60970
+ store: datasetStoreFor(id),
60971
+ signal,
60972
+ onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
60973
+ ...dataset.retentionDays !== void 0 ? { retentionDays: dataset.retentionDays } : {},
60974
+ ...semantic !== void 0 ? { semantic: { embedder: semantic.embedder, writer: semantic.writer, collection: semantic.collection } } : {},
60975
+ /*
60976
+ * The collector runs through the ordinary Python tool path, so it is the same code that
60977
+ * validated it, the same worker, the same timeout. A second execution path would be a
60978
+ * second thing to keep in step with tool approval.
60979
+ */
60980
+ collect: async (since2) => {
60981
+ const registry2 = currentToolRegistry();
60982
+ const tool = registry2.get(dataset.toolName) ?? registry2.get(`py__${dataset.toolName}`);
60983
+ if (tool === void 0) {
60984
+ 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.`);
60985
+ }
60986
+ const args = { ...dataset.arguments ?? {}, ...since2 === void 0 ? {} : { since: since2 } };
60987
+ const output = await tool.execute(args, { signal });
60988
+ if (output.isError === true)
60989
+ throw new Error(String(output.content));
60990
+ try {
60991
+ return JSON.parse(typeof output.content === "string" ? output.content : JSON.stringify(output.content));
60992
+ } catch {
60993
+ 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.");
60994
+ }
60995
+ }
60996
+ });
60997
+ 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.`;
60998
+ datasetResults.set(id, { detail, failed: false, at: Date.now() });
60999
+ reportIndexing("dataset", "Finished", { detail, running: false });
61000
+ } catch (error51) {
61001
+ const stopped = signal.aborted;
61002
+ const detail = stopped ? "Stopped." : error51 instanceof Error ? error51.message : String(error51);
61003
+ datasetResults.set(id, { detail, failed: !stopped, at: Date.now() });
61004
+ if (!stopped)
61005
+ logger.warn(`dataset "${dataset.name}" sync failed: ${detail}`);
61006
+ reportIndexing("dataset", stopped ? "Stopped" : "Failed", { detail, running: false });
61007
+ } finally {
61008
+ datasetBusy.delete(id);
61009
+ endIndexing(`dataset:${id}`);
61010
+ await postDatasetStatus();
61011
+ }
61012
+ }
61013
+ async function handleClearDataset(id, resync) {
61014
+ if (datasetBusy.has(id))
61015
+ return;
61016
+ const config2 = await loadSettings();
61017
+ const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
61018
+ if (dataset === void 0)
61019
+ return;
61020
+ datasetBusy.add(id);
61021
+ const signal = beginIndexing(`dataset:${id}`);
61022
+ reportIndexing("dataset", `Clearing ${dataset.name}`);
61023
+ try {
61024
+ const semantic = await datasetSemantic(config2, dataset);
61025
+ const { removed } = await clearDataset({
61026
+ datasetId: id,
61027
+ store: datasetStoreFor(id),
61028
+ signal,
61029
+ onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
61030
+ ...semantic !== void 0 ? { semantic: { writer: semantic.writer, collection: semantic.collection } } : {}
61031
+ });
61032
+ const detail = `Cleared ${String(removed)} record(s).`;
61033
+ datasetResults.set(id, { detail, failed: false, at: Date.now() });
61034
+ reportIndexing("dataset", "Finished", { detail, running: false });
61035
+ } catch (error51) {
61036
+ const detail = error51 instanceof Error ? error51.message : String(error51);
61037
+ datasetResults.set(id, { detail, failed: true, at: Date.now() });
61038
+ logger.warn(`dataset clear failed: ${detail}`);
61039
+ reportIndexing("dataset", "Failed", { detail, running: false });
61040
+ } finally {
61041
+ datasetBusy.delete(id);
61042
+ endIndexing(`dataset:${id}`);
61043
+ await postDatasetStatus();
61044
+ }
61045
+ if (resync)
61046
+ await runDatasetSync(id, "rebuild");
61047
+ }
61048
+ function reconcileDatasetTimers(config2) {
61049
+ for (const timer of datasetTimers.values())
61050
+ clearInterval(timer);
61051
+ datasetTimers.clear();
61052
+ for (const dataset of config2.datasets ?? []) {
61053
+ const minutes = dataset.syncMinutes ?? 0;
61054
+ if (dataset.enabled === false || minutes <= 0)
61055
+ continue;
61056
+ const timer = setInterval(() => void runDatasetSync(dataset.id, "scheduled"), minutes * 60 * 1e3);
61057
+ timer.unref?.();
61058
+ datasetTimers.set(dataset.id, timer);
61059
+ }
61060
+ }
61061
+ async function postDatasetStatus() {
61062
+ const config2 = (await configManager.load()).config;
61063
+ const datasets = config2.datasets ?? [];
61064
+ const collection = datasetCollectionName(config2);
61065
+ const embedder = await resolveEmbedder(config2).catch(() => void 0);
61066
+ const entries = await Promise.all(datasets.map(async (dataset) => {
61067
+ const store = datasetStoreFor(dataset.id);
61068
+ const records = await store.load();
61069
+ const times = records.map((record2) => record2.timestamp).filter((at) => at !== void 0);
61070
+ const search = await resolveDatasetSearch(config2, dataset).catch(() => void 0);
61071
+ return {
61072
+ ...dataset,
61073
+ records: records.length,
61074
+ sizeBytes: await store.sizeBytes(),
61075
+ ...times.length > 0 ? { oldest: Math.min(...times), newest: Math.max(...times) } : {},
61076
+ ...await store.lastSyncedAt() !== void 0 ? { lastSyncedAt: await store.lastSyncedAt() } : {},
61077
+ busy: datasetBusy.has(dataset.id),
61078
+ ...datasetResults.get(dataset.id) !== void 0 ? {
61079
+ lastResult: datasetResults.get(dataset.id).detail,
61080
+ lastFailed: datasetResults.get(dataset.id).failed,
61081
+ lastAttemptAt: datasetResults.get(dataset.id).at
61082
+ } : {},
61083
+ storeLabel: search?.store.label ?? "none"
61084
+ };
61085
+ }));
61086
+ post({
61087
+ type: "datasetStatus",
61088
+ datasets: entries,
61089
+ // Said plainly, because a dataset with no embedder still syncs and still searches — on words
61090
+ // rather than meaning — and someone seeing results would otherwise assume it is semantic.
61091
+ semantic: collection !== void 0 && embedder !== void 0,
61092
+ /*
61093
+ * Python tools and MCP tools, selected by what they *are* rather than by group.
61094
+ *
61095
+ * Filtering on `group` was wrong and showed only the built-ins: a Python tool is registered
61096
+ * as `command`, because it runs code, and an MCP tool as `mcp`. Those two groups also hold
61097
+ * `execute_command` and the tool-authoring tools, which are not data sources — so the test
61098
+ * is the `py__` prefix and the mcp group, not a permission category. Reported as the picker
61099
+ * listing only built-in tools.
61100
+ */
61101
+ tools: currentToolRegistry().list().filter((tool) => tool.name.startsWith("py__") || tool.group === "mcp").map((tool) => ({
61102
+ name: tool.name,
61103
+ description: tool.description,
61104
+ // Grouped in the picker, because "which of these is mine?" is the first question with
61105
+ // forty MCP tools in the list.
61106
+ kind: tool.name.startsWith("py__") ? "python" : "mcp"
61107
+ })),
61108
+ guidance: COLLECTOR_TOOL_GUIDANCE
61109
+ });
61110
+ }
61111
+ async function handleSaveDataset(dataset) {
61112
+ const { config: config2 } = await configManager.load();
61113
+ const existing = config2.datasets ?? [];
61114
+ const next = existing.some((entry) => entry.id === dataset.id) ? existing.map((entry) => entry.id === dataset.id ? dataset : entry) : [...existing, dataset];
61115
+ await configManager.save("user", { datasets: next });
61116
+ reconcileDatasetTimers((await configManager.load()).config);
61117
+ await postDatasetStatus();
61118
+ }
61119
+ async function handleDeleteDataset(id) {
61120
+ const { config: config2 } = await configManager.load();
61121
+ await handleClearDataset(id, false);
61122
+ await configManager.save("user", {
61123
+ datasets: (config2.datasets ?? []).filter((entry) => entry.id !== id)
61124
+ });
61125
+ datasetResults.delete(id);
61126
+ reconcileDatasetTimers((await configManager.load()).config);
61127
+ await postDatasetStatus();
61128
+ }
60162
61129
  function reconcileMailTimer(config2) {
60163
61130
  if (mailTimer !== void 0) {
60164
61131
  clearInterval(mailTimer);
@@ -60208,9 +61175,9 @@ function wireChatBridge(services) {
60208
61175
  });
60209
61176
  const all = result.folders.map((entry) => entry.path);
60210
61177
  const wanted = new Set(chosen);
60211
- for (const path30 of all) {
60212
- if (chosen.some((root) => path30 === root || path30.startsWith(`${root}\\`)))
60213
- wanted.add(path30);
61178
+ for (const path31 of all) {
61179
+ if (chosen.some((root) => path31 === root || path31.startsWith(`${root}\\`)))
61180
+ wanted.add(path31);
60214
61181
  }
60215
61182
  return [...wanted];
60216
61183
  } catch {
@@ -60427,6 +61394,7 @@ function wireChatBridge(services) {
60427
61394
  });
60428
61395
  const config2 = await loadSettings();
60429
61396
  reconcileMailTimer(config2);
61397
+ reconcileDatasetTimers(config2);
60430
61398
  await postMailStatus();
60431
61399
  if (config2.mail?.enabled === true)
60432
61400
  void runMailSync("just enabled");
@@ -60591,7 +61559,7 @@ function wireChatBridge(services) {
60591
61559
  return void 0;
60592
61560
  try {
60593
61561
  const listed = await new Promise((resolve, reject2) => {
60594
- const child = spawn5(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
61562
+ const child = spawn6(ripgrepPath, ["--files", "--hidden", "--glob", "!.git"], { cwd: workspaceRoot });
60595
61563
  let out = "";
60596
61564
  child.stdout.on("data", (chunk) => out += chunk.toString("utf8"));
60597
61565
  child.on("error", reject2);
@@ -60705,6 +61673,28 @@ function wireChatBridge(services) {
60705
61673
  const { config: config2 } = await configManager.load();
60706
61674
  const search = await resolveSearch(config2);
60707
61675
  const embedder = await resolveEmbedder(config2);
61676
+ if (target === "data") {
61677
+ const datasets = config2.datasets ?? [];
61678
+ const collection = datasetCollectionName(config2);
61679
+ const dataSearch = await resolveDatasetSearch(config2);
61680
+ const tool2 = createSearchDataTool({
61681
+ load: async () => Promise.all(datasets.map(async (dataset) => ({
61682
+ id: dataset.id,
61683
+ name: dataset.name,
61684
+ records: await new DatasetStore(storageDir, dataset.id).load()
61685
+ }))),
61686
+ ...collection !== void 0 && dataSearch !== void 0 && embedder !== void 0 ? { semantic: { searcher: dataSearch.searcher, embedder, collection } } : {}
61687
+ });
61688
+ const result2 = await tool2.execute({ query, limit: 25 }, {});
61689
+ post({
61690
+ type: "searchProbe",
61691
+ target,
61692
+ query,
61693
+ text: result2.content,
61694
+ ...result2.isError === true ? { error: "The search failed." } : {}
61695
+ });
61696
+ return;
61697
+ }
60708
61698
  if (target === "mail") {
60709
61699
  const collection = mailCollectionName(config2);
60710
61700
  const mailSearch = await resolveMailSearch(config2);
@@ -61896,6 +62886,7 @@ function wireChatBridge(services) {
61896
62886
  } else if (message3.type === "requestMailStatus") {
61897
62887
  void loadSettings().then((config2) => {
61898
62888
  reconcileMailTimer(config2);
62889
+ reconcileDatasetTimers(config2);
61899
62890
  return postMailStatus();
61900
62891
  });
61901
62892
  } else if (message3.type === "saveMailSettings") {
@@ -61911,6 +62902,16 @@ function wireChatBridge(services) {
61911
62902
  void handleClearTeamSkills();
61912
62903
  } else if (message3.type === "refreshMail") {
61913
62904
  void handleRefreshMail(message3.days);
62905
+ } else if (message3.type === "requestDatasetStatus") {
62906
+ void postDatasetStatus();
62907
+ } else if (message3.type === "saveDataset") {
62908
+ void handleSaveDataset(message3.dataset);
62909
+ } else if (message3.type === "deleteDataset") {
62910
+ void handleDeleteDataset(message3.id);
62911
+ } else if (message3.type === "syncDataset") {
62912
+ void runDatasetSync(message3.id, "manual");
62913
+ } else if (message3.type === "clearDataset") {
62914
+ void handleClearDataset(message3.id, message3.resync === true);
61914
62915
  } else if (message3.type === "clearMailIndex") {
61915
62916
  void handleClearMailIndex(message3.resync === true);
61916
62917
  } else if (message3.type === "saveSkillsAlias") {
@@ -62090,6 +63091,21 @@ ${entry.content}`);
62090
63091
  lines.push(`## Thinking
62091
63092
 
62092
63093
  ${entry.content}`);
63094
+ } else if (entry.kind === "chart") {
63095
+ const chart = entry.chart;
63096
+ const header = ["", ...chart.series.map((series) => series.name)];
63097
+ lines.push([
63098
+ `## ${chart.title ?? "Chart"}`,
63099
+ "",
63100
+ `| ${header.join(" | ")} |`,
63101
+ `| ${header.map(() => "---").join(" | ")} |`,
63102
+ ...chart.categories.map((category, index) => `| ${category} | ${chart.series.map((series) => String(series.values[index] ?? "")).join(" | ")} |`),
63103
+ ...chart.note === void 0 ? [] : ["", chart.note]
63104
+ ].join("\n"));
63105
+ } else if (entry.kind === "chartError") {
63106
+ lines.push(`## Chart
63107
+
63108
+ Could not be drawn: ${entry.message}`);
62093
63109
  } else {
62094
63110
  const call = entry.toolCall;
62095
63111
  lines.push([
@@ -62590,6 +63606,89 @@ function deriveTitle(messages) {
62590
63606
  return `${cut.trimEnd()}\u2026`;
62591
63607
  }
62592
63608
 
63609
+ // ../../packages/core/dist/charts/types.js
63610
+ var CHART_TYPES = ["bar", "stackedBar", "groupedBar", "line", "multiLine", "pie"];
63611
+ var MAX_CATEGORIES = 200;
63612
+ var MAX_SERIES = 12;
63613
+ var finiteNumber = external_exports.number().refine((value) => Number.isFinite(value), { message: "must be a finite number" });
63614
+ var chartSeriesSchema = external_exports.object({
63615
+ name: external_exports.string().min(1).describe('What this series is, e.g. "Alerts" or "Inbox". Shown in the legend.'),
63616
+ values: external_exports.array(finiteNumber).min(1).max(MAX_CATEGORIES).describe("One number per category, in the same order as `categories`."),
63617
+ /**
63618
+ * What each number is made of, for the reader who asks "which ones?".
63619
+ *
63620
+ * Aligned with `values` by index, and any entry may be omitted. This is the drill-down: a bar
63621
+ * showing 14 alerts can list the fourteen subjects, so the chart is a way *into* the data rather
63622
+ * than a summary that replaces it.
63623
+ */
63624
+ 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.")
63625
+ });
63626
+ var chartSpecSchema = external_exports.object({
63627
+ type: external_exports.enum(CHART_TYPES).describe("bar, stackedBar, groupedBar, line, multiLine or pie."),
63628
+ title: external_exports.string().max(200).optional(),
63629
+ 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."),
63630
+ series: external_exports.array(chartSeriesSchema).min(1).max(MAX_SERIES),
63631
+ xLabel: external_exports.string().max(80).optional(),
63632
+ yLabel: external_exports.string().max(80).optional(),
63633
+ note: external_exports.string().max(500).optional().describe("A line under the chart. Say where the numbers came from, and what they exclude.")
63634
+ }).superRefine((spec, context) => {
63635
+ for (const [index, series] of spec.series.entries()) {
63636
+ if (series.values.length !== spec.categories.length) {
63637
+ context.addIssue({
63638
+ code: "custom",
63639
+ path: ["series", index, "values"],
63640
+ /*
63641
+ * Refused rather than padded, and the message says the counts.
63642
+ *
63643
+ * A silently padded series draws a chart that is the right shape and the wrong answer,
63644
+ * and nobody checks a chart against its data — that is what a chart is for. Being told
63645
+ * the two numbers is also what lets the model fix it in one turn.
63646
+ */
63647
+ 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.`
63648
+ });
63649
+ }
63650
+ if (series.detail !== void 0 && series.detail.length > series.values.length) {
63651
+ context.addIssue({
63652
+ code: "custom",
63653
+ path: ["series", index, "detail"],
63654
+ message: `series "${series.name}" has more detail entries than values.`
63655
+ });
63656
+ }
63657
+ }
63658
+ if (spec.type === "pie") {
63659
+ if (spec.series.length !== 1) {
63660
+ context.addIssue({
63661
+ code: "custom",
63662
+ path: ["series"],
63663
+ message: "a pie chart takes exactly one series \u2014 use stackedBar or groupedBar for several."
63664
+ });
63665
+ }
63666
+ if (spec.series.some((series) => series.values.some((value) => value < 0))) {
63667
+ context.addIssue({
63668
+ code: "custom",
63669
+ path: ["series"],
63670
+ // A negative slice has no meaning: it cannot be drawn, and drawing its absolute value
63671
+ // would misreport the total every other slice is measured against.
63672
+ message: "a pie chart cannot show negative values."
63673
+ });
63674
+ }
63675
+ }
63676
+ if (spec.type === "stackedBar" && spec.series.some((series) => series.values.some((value) => value < 0))) {
63677
+ context.addIssue({
63678
+ code: "custom",
63679
+ path: ["series"],
63680
+ message: "a stacked bar cannot show negative values \u2014 the segments would overlap rather than stack."
63681
+ });
63682
+ }
63683
+ });
63684
+ function chartTotals(spec) {
63685
+ const series = spec.series.map((entry) => ({
63686
+ name: entry.name,
63687
+ total: entry.values.reduce((sum, value) => sum + value, 0)
63688
+ }));
63689
+ return { series, grand: series.reduce((sum, entry) => sum + entry.total, 0) };
63690
+ }
63691
+
62593
63692
  // ../../packages/core/dist/history/transcript.js
62594
63693
  var CONTROL_TOOLS = /* @__PURE__ */ new Set(["attempt_completion", "ask_followup_question"]);
62595
63694
  function formatToolArguments(raw) {
@@ -62636,6 +63735,11 @@ function toTranscript(messages) {
62636
63735
  }
62637
63736
  for (const toolCall of message3.toolCalls ?? []) {
62638
63737
  const result = resultsByCallId.get(toolCall.id);
63738
+ const asChart = chartFromToolCall(toolCall.name, toolCall.arguments);
63739
+ if (asChart !== void 0) {
63740
+ entries.push(asChart.kind === "chart" ? { kind: "chart", chart: asChart.chart, ...expertInformed ? { expertInformed: true } : {} } : asChart);
63741
+ continue;
63742
+ }
62639
63743
  if (CONTROL_TOOLS.has(toolCall.name)) {
62640
63744
  if (result !== void 0)
62641
63745
  entries.push({ kind: "text", role: "assistant", content: result });
@@ -62661,6 +63765,19 @@ function toTranscript(messages) {
62661
63765
  }
62662
63766
  return entries;
62663
63767
  }
63768
+ function chartFromToolCall(name, rawArguments) {
63769
+ if (name !== "show_chart")
63770
+ return void 0;
63771
+ const parsed = chartSpecSchema.safeParse(decodeArguments(rawArguments));
63772
+ return parsed.success ? { kind: "chart", chart: parsed.data } : { kind: "chartError", message: parsed.error.issues.map((issue2) => issue2.message).join("; ") };
63773
+ }
63774
+ function decodeArguments(raw) {
63775
+ try {
63776
+ return JSON.parse(raw.length > 0 ? raw : "{}");
63777
+ } catch {
63778
+ return raw;
63779
+ }
63780
+ }
62664
63781
 
62665
63782
  // ../../packages/core/dist/history/redactTask.js
62666
63783
  function redactMessage(message3, knownSecrets) {
@@ -62688,6 +63805,29 @@ function redactTask(task, knownSecrets) {
62688
63805
  };
62689
63806
  }
62690
63807
 
63808
+ // ../../packages/core/dist/tools/showChart.js
63809
+ function createShowChartTool() {
63810
+ return {
63811
+ name: "show_chart",
63812
+ // A control tool: it presents, it does not act. Never filtered out by a mode, never gated.
63813
+ group: "always",
63814
+ 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.",
63815
+ parametersSchema: chartSpecSchema,
63816
+ async execute(params) {
63817
+ const totals = chartTotals(params);
63818
+ const detailed = params.series.filter((series) => series.detail !== void 0).length;
63819
+ return {
63820
+ content: [
63821
+ `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.`,
63822
+ ...totals.series.map((entry) => ` ${entry.name}: total ${String(entry.total)}`),
63823
+ 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.`,
63824
+ "The chart is now in the conversation. Describe what it shows rather than reciting the numbers again \u2014 they are on screen."
63825
+ ].join("\n")
63826
+ };
63827
+ }
63828
+ };
63829
+ }
63830
+
62691
63831
  // ../../packages/core/dist/tools/applyDiff/eol.js
62692
63832
  function detectEol(text) {
62693
63833
  const crlfCount = (text.match(/\r\n/g) ?? []).length;
@@ -63176,10 +64316,10 @@ function readSmall(raw, params) {
63176
64316
  const end = params.limit !== void 0 ? start + params.limit : lines.length;
63177
64317
  return number4(lines.slice(start, end), start + 1);
63178
64318
  }
63179
- async function readLarge(fs24, realPath, params, size) {
64319
+ async function readLarge(fs25, realPath, params, size) {
63180
64320
  const human = formatBytes(size);
63181
64321
  if (params.tail !== void 0) {
63182
- const part = await readTail(fs24, realPath, size, params.tail);
64322
+ const part = await readTail(fs25, realPath, size, params.tail);
63183
64323
  return [
63184
64324
  `${human} file \u2014 last ${String(part.lines.length)} lines.`,
63185
64325
  /*
@@ -63194,7 +64334,7 @@ async function readLarge(fs24, realPath, params, size) {
63194
64334
  }
63195
64335
  if (params.offset !== void 0) {
63196
64336
  const limit = params.limit ?? DEFAULT_LARGE_LIMIT;
63197
- const part = await readLineWindow(fs24, realPath, size, params.offset, limit);
64337
+ const part = await readLineWindow(fs25, realPath, size, params.offset, limit);
63198
64338
  const shown = part.lines.length;
63199
64339
  return [
63200
64340
  `${human} file \u2014 lines ${String(params.offset)}\u2013${String(params.offset + shown - 1)}${part.hasMoreAfter ? ", more follows" : " (end of file)"}.`,
@@ -63202,7 +64342,7 @@ async function readLarge(fs24, realPath, params, size) {
63202
64342
  number4(part.lines, params.offset)
63203
64343
  ].join("\n");
63204
64344
  }
63205
- const total = await countLines(fs24, realPath, size);
64345
+ const total = await countLines(fs25, realPath, size);
63206
64346
  return [
63207
64347
  `${realPathName(realPath)} is ${human} (${total.toLocaleString()} lines) \u2014 too large to read at once.`,
63208
64348
  "",
@@ -63396,10 +64536,339 @@ function createDefaultToolRegistry() {
63396
64536
  registry2.register(executeCommandTool);
63397
64537
  registry2.register(askFollowupQuestionTool);
63398
64538
  registry2.register(createAskUserFormTool());
64539
+ registry2.register(createShowChartTool());
63399
64540
  registry2.register(attemptCompletionTool);
63400
64541
  return registry2;
63401
64542
  }
63402
64543
 
64544
+ // ../../packages/core/dist/dataset/store.js
64545
+ import fs19 from "node:fs/promises";
64546
+ import path25 from "node:path";
64547
+ var DatasetStore = class {
64548
+ filePath;
64549
+ statePath;
64550
+ constructor(storageDir, datasetId) {
64551
+ const safe = datasetId.replace(/[^A-Za-z0-9._-]/g, "_");
64552
+ this.filePath = path25.join(storageDir, "datasets", `${safe}.jsonl`);
64553
+ this.statePath = path25.join(storageDir, "datasets", `${safe}.state.json`);
64554
+ }
64555
+ /** Every record. A malformed line is skipped — one bad line costs one record, not the corpus. */
64556
+ async load() {
64557
+ let raw;
64558
+ try {
64559
+ raw = await fs19.readFile(this.filePath, "utf8");
64560
+ } catch {
64561
+ return [];
64562
+ }
64563
+ const byId = /* @__PURE__ */ new Map();
64564
+ for (const line of raw.split("\n")) {
64565
+ const trimmed = line.trim();
64566
+ if (trimmed.length === 0)
64567
+ continue;
64568
+ try {
64569
+ const parsed = JSON.parse(trimmed);
64570
+ if (typeof parsed.id === "string" && typeof parsed.text === "string")
64571
+ byId.set(parsed.id, parsed);
64572
+ } catch {
64573
+ }
64574
+ }
64575
+ return [...byId.values()];
64576
+ }
64577
+ /** Appends. Re-appending an existing id is how an update is recorded — see `load`. */
64578
+ async append(records) {
64579
+ if (records.length === 0)
64580
+ return;
64581
+ await fs19.mkdir(path25.dirname(this.filePath), { recursive: true });
64582
+ await fs19.writeFile(this.filePath, "", { flag: "a" });
64583
+ const lines = records.map((record2) => JSON.stringify(record2)).join("\n");
64584
+ await fs19.appendFile(this.filePath, `${lines}
64585
+ `, "utf8");
64586
+ }
64587
+ /** Rewrites with exactly these. Temp-and-rename, so an interrupted prune leaves the old file. */
64588
+ async replace(records) {
64589
+ await fs19.mkdir(path25.dirname(this.filePath), { recursive: true });
64590
+ const temporary = `${this.filePath}.tmp`;
64591
+ const body = records.map((record2) => JSON.stringify(record2)).join("\n");
64592
+ await fs19.writeFile(temporary, records.length === 0 ? "" : `${body}
64593
+ `, "utf8");
64594
+ await fs19.rename(temporary, this.filePath);
64595
+ }
64596
+ /**
64597
+ * Rewrites the file with the duplicates collapsed.
64598
+ *
64599
+ * Append-as-upsert means a record updated every hour adds a line every hour, so the file grows
64600
+ * with the *number of syncs* rather than the size of the corpus. Compaction is cheap and only
64601
+ * worth doing when it would actually shrink anything, which the caller decides.
64602
+ */
64603
+ async compact() {
64604
+ let before;
64605
+ try {
64606
+ before = (await fs19.readFile(this.filePath, "utf8")).split("\n").filter((line) => line.trim().length > 0).length;
64607
+ } catch {
64608
+ return { before: 0, after: 0 };
64609
+ }
64610
+ const records = await this.load();
64611
+ if (records.length === before)
64612
+ return { before, after: before };
64613
+ await this.replace(records);
64614
+ return { before, after: records.length };
64615
+ }
64616
+ async clear() {
64617
+ await fs19.rm(this.filePath, { force: true });
64618
+ await fs19.rm(this.statePath, { force: true });
64619
+ }
64620
+ async sizeBytes() {
64621
+ try {
64622
+ return (await fs19.stat(this.filePath)).size;
64623
+ } catch {
64624
+ return 0;
64625
+ }
64626
+ }
64627
+ /**
64628
+ * When the last successful sync finished, passed to the collector as `since`.
64629
+ *
64630
+ * Written only on success, deliberately: after a failed run the next one must ask for the same
64631
+ * window again, or whatever the source produced while it was broken is skipped for ever with
64632
+ * nothing anywhere recording the gap.
64633
+ */
64634
+ async lastSyncedAt() {
64635
+ try {
64636
+ const parsed = JSON.parse(await fs19.readFile(this.statePath, "utf8"));
64637
+ return typeof parsed.lastSyncedAt === "number" ? parsed.lastSyncedAt : void 0;
64638
+ } catch {
64639
+ return void 0;
64640
+ }
64641
+ }
64642
+ async recordSync(at) {
64643
+ await fs19.mkdir(path25.dirname(this.statePath), { recursive: true });
64644
+ const temporary = `${this.statePath}.tmp`;
64645
+ await fs19.writeFile(temporary, JSON.stringify({ lastSyncedAt: at }), "utf8");
64646
+ await fs19.rename(temporary, this.statePath);
64647
+ }
64648
+ };
64649
+ function partitionByAge(records, cutoff) {
64650
+ const kept = [];
64651
+ const removed = [];
64652
+ for (const record2 of records) {
64653
+ if (record2.timestamp !== void 0 && record2.timestamp < cutoff)
64654
+ removed.push(record2);
64655
+ else
64656
+ kept.push(record2);
64657
+ }
64658
+ return { kept, removed };
64659
+ }
64660
+
64661
+ // ../../packages/core/dist/dataset/sync.js
64662
+ function datasetEmbedText(record2) {
64663
+ return [record2.title, record2.text].filter((part) => part !== void 0 && part.length > 0).join("\n");
64664
+ }
64665
+ function datasetVectorId(datasetId, recordId) {
64666
+ return `data:${datasetId}:${recordId}`;
64667
+ }
64668
+ async function syncDataset(options) {
64669
+ const now = options.now ?? Date.now();
64670
+ const held = await options.store.load();
64671
+ const heldById = new Map(held.map((record2) => [record2.id, record2]));
64672
+ options.onProgress?.(0, 0, "Running the collector");
64673
+ const since2 = await options.store.lastSyncedAt();
64674
+ const payload = await options.collect(since2);
64675
+ const parsed = parseDatasetPayload(payload);
64676
+ if ("error" in parsed)
64677
+ throw new Error(parsed.error);
64678
+ const collected = parsed.records;
64679
+ const changed = collected.filter((record2) => {
64680
+ const existing = heldById.get(record2.id);
64681
+ return existing === void 0 || JSON.stringify(existing) !== JSON.stringify(record2);
64682
+ });
64683
+ let embedded = 0;
64684
+ if (options.semantic !== void 0 && changed.length > 0) {
64685
+ const { embedder, writer, collection } = options.semantic;
64686
+ await writer.ensureCollection(collection, embedder.dimensions, options.signal);
64687
+ const documents = [];
64688
+ for (const record2 of changed) {
64689
+ if (options.signal?.aborted === true)
64690
+ throw new Error("Stopped.");
64691
+ options.onProgress?.(documents.length, changed.length, "Embedding new and changed records");
64692
+ const existing = heldById.get(record2.id);
64693
+ if (existing !== void 0 && datasetEmbedText(existing) === datasetEmbedText(record2))
64694
+ continue;
64695
+ const text = datasetEmbedText(record2);
64696
+ if (text.trim().length === 0)
64697
+ continue;
64698
+ documents.push({
64699
+ id: datasetVectorId(options.datasetId, record2.id),
64700
+ text,
64701
+ // The id travels in `path`, which is how a hit is joined back to its record.
64702
+ path: datasetVectorId(options.datasetId, record2.id),
64703
+ startLine: 1,
64704
+ endLine: 1,
64705
+ vector: await embedder.embed(text)
64706
+ });
64707
+ }
64708
+ if (documents.length > 0) {
64709
+ await writer.upsert(collection, documents, options.signal);
64710
+ embedded = documents.length;
64711
+ }
64712
+ }
64713
+ if (changed.length > 0)
64714
+ await options.store.append(changed);
64715
+ let removed = 0;
64716
+ if (options.retentionDays !== void 0) {
64717
+ const cutoff = now - options.retentionDays * 24 * 60 * 60 * 1e3;
64718
+ const after = await options.store.load();
64719
+ const { kept, removed: old } = partitionByAge(after, cutoff);
64720
+ if (old.length > 0) {
64721
+ options.onProgress?.(0, old.length, "Removing records past retention");
64722
+ if (options.semantic !== void 0) {
64723
+ await options.semantic.writer.deleteByPaths(options.semantic.collection, old.map((record2) => datasetVectorId(options.datasetId, record2.id)), options.signal);
64724
+ }
64725
+ await options.store.replace(kept);
64726
+ removed = old.length;
64727
+ }
64728
+ }
64729
+ await options.store.compact();
64730
+ await options.store.recordSync(now);
64731
+ const total = (await options.store.load()).length;
64732
+ return { collected: collected.length, updated: changed.length, embedded, removed, total };
64733
+ }
64734
+ async function clearDataset(options) {
64735
+ const held = await options.store.load();
64736
+ if (options.semantic !== void 0 && held.length > 0) {
64737
+ const size = 500;
64738
+ const paths = held.map((record2) => datasetVectorId(options.datasetId, record2.id));
64739
+ for (let start = 0; start < paths.length; start += size) {
64740
+ if (options.signal?.aborted === true)
64741
+ throw new Error("Stopped.");
64742
+ options.onProgress?.(Math.min(start + size, paths.length), paths.length, "Removing vectors");
64743
+ await options.semantic.writer.deleteByPaths(options.semantic.collection, paths.slice(start, start + size), options.signal);
64744
+ }
64745
+ }
64746
+ await options.store.clear();
64747
+ return { removed: held.length };
64748
+ }
64749
+
64750
+ // ../../packages/core/dist/tools/searchData.js
64751
+ var searchSchema3 = external_exports.object({
64752
+ dataset: external_exports.string().optional().describe("Which dataset to search, by name. Omit to search all of them."),
64753
+ query: external_exports.string().optional().describe("Rank by meaning. Omit to get the most recent records in the window."),
64754
+ withinDays: external_exports.number().min(0.01).optional().describe("Only records with a timestamp this recent. Records with no timestamp are excluded."),
64755
+ contains: external_exports.string().optional().describe("Only records whose title or text contains this text. Exact, case-insensitive."),
64756
+ tag: external_exports.string().optional().describe("Filter on a tag, as `name=value`. Exact."),
64757
+ limit: external_exports.number().int().min(1).max(50).optional().describe("How many to return. Default 15.")
64758
+ });
64759
+ function describe4(record2, dataset) {
64760
+ const when = record2.timestamp === void 0 ? "" : `${new Date(record2.timestamp).toLocaleString()} `;
64761
+ const heading = record2.title ?? record2.text.trim().split("\n")[0]?.slice(0, 100) ?? record2.id;
64762
+ const body = record2.text.trim().slice(0, 400);
64763
+ return `${when}[${dataset}] ${heading}
64764
+ id: ${record2.id}${record2.url === void 0 ? "" : ` ${record2.url}`}
64765
+ ${body}`;
64766
+ }
64767
+ function createSearchDataTool(options) {
64768
+ return {
64769
+ name: "search_data",
64770
+ group: "read",
64771
+ 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.",
64772
+ parametersSchema: searchSchema3,
64773
+ execute: async (params) => {
64774
+ try {
64775
+ const datasets = await options.load();
64776
+ if (datasets.length === 0) {
64777
+ return {
64778
+ 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."
64779
+ };
64780
+ }
64781
+ const wanted = params.dataset === void 0 ? datasets : datasets.filter((entry) => entry.name.toLowerCase() === params.dataset?.toLowerCase());
64782
+ if (wanted.length === 0) {
64783
+ return {
64784
+ content: `There is no dataset called "${params.dataset ?? ""}". Configured: ${datasets.map((entry) => entry.name).join(", ")}.`,
64785
+ isError: true
64786
+ };
64787
+ }
64788
+ let candidates = wanted.flatMap((entry) => entry.records.map((record2) => ({ dataset: entry.name, datasetId: entry.id, record: record2 })));
64789
+ const narrowed = [];
64790
+ if (params.withinDays !== void 0) {
64791
+ const cutoff = Date.now() - params.withinDays * 24 * 60 * 60 * 1e3;
64792
+ candidates = candidates.filter((entry) => entry.record.timestamp !== void 0 && entry.record.timestamp >= cutoff);
64793
+ narrowed.push(`in the last ${String(params.withinDays)} day(s)`);
64794
+ }
64795
+ if (params.tag !== void 0) {
64796
+ const [name, value] = params.tag.split("=");
64797
+ candidates = candidates.filter((entry) => value === void 0 ? entry.record.tags?.[name ?? ""] !== void 0 : entry.record.tags?.[name ?? ""] === value);
64798
+ narrowed.push(`tagged ${params.tag}`);
64799
+ }
64800
+ if (params.contains !== void 0) {
64801
+ const needle = params.contains.toLowerCase();
64802
+ candidates = candidates.filter((entry) => `${entry.record.title ?? ""}
64803
+ ${entry.record.text}`.toLowerCase().includes(needle));
64804
+ narrowed.push(`containing "${params.contains}"`);
64805
+ }
64806
+ const criteria = narrowed.length === 0 ? "" : `, ${narrowed.join(", ")}`;
64807
+ if (candidates.length === 0) {
64808
+ return {
64809
+ 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.`
64810
+ };
64811
+ }
64812
+ const limit = params.limit ?? 15;
64813
+ let ordered = candidates.sort((a, b) => (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0));
64814
+ let how = "";
64815
+ const asked = params.query?.trim() ?? "";
64816
+ if (asked.length > 0 && options.semantic === void 0) {
64817
+ const words = asked.toLowerCase().split(/\s+/).filter((word) => word.length > 2);
64818
+ const needle = asked.toLowerCase();
64819
+ candidates = candidates.filter((entry) => {
64820
+ const haystack = `${entry.record.title ?? ""}
64821
+ ${entry.record.text}`.toLowerCase();
64822
+ return words.length === 0 ? haystack.includes(needle) : words.some((word) => haystack.includes(word));
64823
+ });
64824
+ if (candidates.length === 0) {
64825
+ return {
64826
+ 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.`
64827
+ };
64828
+ }
64829
+ ordered = candidates;
64830
+ how = " matched on words, not meaning \u2014 no embedding model is configured";
64831
+ }
64832
+ if (asked.length > 0 && options.semantic !== void 0) {
64833
+ const vector = await options.semantic.embedder.embed(asked);
64834
+ const hits = await options.semantic.searcher.searchByVector(options.semantic.collection, vector, {
64835
+ size: Math.min(100, Math.max(limit * 4, 40))
64836
+ });
64837
+ const rank2 = /* @__PURE__ */ new Map();
64838
+ hits.forEach((hit, position) => {
64839
+ if (!rank2.has(hit.path))
64840
+ rank2.set(hit.path, position);
64841
+ });
64842
+ ordered = [...candidates].sort((a, b) => {
64843
+ const left = rank2.get(`data:${a.datasetId}:${a.record.id}`);
64844
+ const right = rank2.get(`data:${b.datasetId}:${b.record.id}`);
64845
+ if (left !== void 0 && right !== void 0)
64846
+ return left - right;
64847
+ if (left !== void 0)
64848
+ return -1;
64849
+ if (right !== void 0)
64850
+ return 1;
64851
+ return (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0);
64852
+ });
64853
+ how = " ranked by meaning";
64854
+ }
64855
+ const shown = ordered.slice(0, limit);
64856
+ return {
64857
+ content: [
64858
+ `${String(candidates.length)} record(s) in ${wanted.map((entry) => entry.name).join(", ")}${criteria}${how}${candidates.length > shown.length ? `, showing ${String(shown.length)}` : ""}:`,
64859
+ "",
64860
+ ...shown.map((entry) => describe4(entry.record, entry.dataset)),
64861
+ "",
64862
+ "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."
64863
+ ].join("\n")
64864
+ };
64865
+ } catch (error51) {
64866
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
64867
+ }
64868
+ }
64869
+ };
64870
+ }
64871
+
63403
64872
  // src/identity.ts
63404
64873
  import crypto5 from "node:crypto";
63405
64874
  var SingleUserIdentity = class _SingleUserIdentity {
@@ -63410,13 +64879,36 @@ var SingleUserIdentity = class _SingleUserIdentity {
63410
64879
  /**
63411
64880
  * Single-use and short-lived, because it travels in the launch URL's fragment where it
63412
64881
  * can end up in shell history or a terminal scrollback (§14).
64882
+ *
64883
+ * Ten seconds is right when the browser opens itself, and far too short when a person has to
64884
+ * move the URL by hand — into another application, a remote session, a phone. `--handoff-seconds`
64885
+ * raises it, and what that costs is stated where it is set: a longer window is a longer time in
64886
+ * which somebody reading that scrollback can use it before you do.
63413
64887
  */
63414
64888
  handoffToken = crypto5.randomBytes(32).toString("base64url");
63415
- handoffExpiresAt = Date.now() + 1e4;
64889
+ handoffExpiresAt;
64890
+ handoffSeconds;
64891
+ constructor(handoffSeconds = 10) {
64892
+ this.handoffSeconds = handoffSeconds;
64893
+ this.handoffExpiresAt = Date.now() + handoffSeconds * 1e3;
64894
+ }
63416
64895
  get launchToken() {
63417
64896
  if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
63418
64897
  return this.handoffToken;
63419
64898
  }
64899
+ /**
64900
+ * Mints a fresh handoff token, replacing any outstanding one.
64901
+ *
64902
+ * For the case the old design had no answer to: the token expired unused, and the only way back
64903
+ * was to stop the server and start it again — losing the session, the conversation and anything
64904
+ * running. A new token grants exactly what the first one did, to whoever can read the terminal,
64905
+ * which is the same person it was printed to in the first place.
64906
+ */
64907
+ remintHandoff() {
64908
+ this.handoffToken = crypto5.randomBytes(32).toString("base64url");
64909
+ this.handoffExpiresAt = Date.now() + this.handoffSeconds * 1e3;
64910
+ return this.handoffToken;
64911
+ }
63420
64912
  /**
63421
64913
  * Exchanges the handoff token for the session token, once.
63422
64914
  *
@@ -63424,11 +64916,23 @@ var SingleUserIdentity = class _SingleUserIdentity {
63424
64916
  * or an attack, and in both cases the right answer is that this token is now spent.
63425
64917
  */
63426
64918
  redeemHandoff(presented) {
64919
+ return this.redeem(presented).token;
64920
+ }
64921
+ /**
64922
+ * The same exchange, saying *why* it failed.
64923
+ *
64924
+ * The reasons need different handling and only one of them is anybody's fault. An expired token
64925
+ * is an ordinary mishap — the browser was slow, the URL was pasted late — and the right response
64926
+ * is to offer another. A token that does not match is either a bug or an attack, and the right
64927
+ * response there is nothing at all.
64928
+ */
64929
+ redeem(presented) {
63427
64930
  const expected = this.handoffToken;
63428
64931
  const expiresAt = this.handoffExpiresAt;
63429
64932
  this.handoffToken = void 0;
63430
- if (expected === void 0 || Date.now() > expiresAt) return void 0;
63431
- return timingSafeEquals(presented, expected) ? this.sessionToken : void 0;
64933
+ if (expected === void 0) return { reason: "spent" };
64934
+ if (Date.now() > expiresAt) return { reason: "expired" };
64935
+ return timingSafeEquals(presented, expected) ? { token: this.sessionToken } : { reason: "mismatch" };
63432
64936
  }
63433
64937
  async authenticate(request) {
63434
64938
  const header = request.headers.authorization;
@@ -63640,8 +65144,8 @@ async function readJsonBody(request, maxBytes = 32 * 1024 * 1024) {
63640
65144
  }
63641
65145
 
63642
65146
  // src/fileSecretStore.ts
63643
- import fs19 from "node:fs/promises";
63644
- import path25 from "node:path";
65147
+ import fs20 from "node:fs/promises";
65148
+ import path26 from "node:path";
63645
65149
  var FileSecretStore = class {
63646
65150
  constructor(filePath) {
63647
65151
  this.filePath = filePath;
@@ -63653,7 +65157,7 @@ var FileSecretStore = class {
63653
65157
  async load() {
63654
65158
  if (this.cache !== void 0) return this.cache;
63655
65159
  try {
63656
- const raw = await fs19.readFile(this.filePath, "utf8");
65160
+ const raw = await fs20.readFile(this.filePath, "utf8");
63657
65161
  const parsed = JSON.parse(raw);
63658
65162
  this.cache = typeof parsed === "object" && parsed !== null ? parsed : {};
63659
65163
  } catch {
@@ -63665,10 +65169,10 @@ var FileSecretStore = class {
63665
65169
  this.queue = this.queue.then(async () => {
63666
65170
  const secrets = await this.load();
63667
65171
  mutate(secrets);
63668
- await fs19.mkdir(path25.dirname(this.filePath), { recursive: true });
65172
+ await fs20.mkdir(path26.dirname(this.filePath), { recursive: true });
63669
65173
  const temp = `${this.filePath}.${process.pid}.tmp`;
63670
- await fs19.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
63671
- await fs19.rename(temp, this.filePath);
65174
+ await fs20.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
65175
+ await fs20.rename(temp, this.filePath);
63672
65176
  });
63673
65177
  return this.queue;
63674
65178
  }
@@ -63699,8 +65203,8 @@ var FileSecretStore = class {
63699
65203
 
63700
65204
  // src/reviewQueue.ts
63701
65205
  import crypto6 from "node:crypto";
63702
- import fs20 from "node:fs/promises";
63703
- import path26 from "node:path";
65206
+ import fs21 from "node:fs/promises";
65207
+ import path27 from "node:path";
63704
65208
  var ReviewQueue = class {
63705
65209
  constructor(filePath) {
63706
65210
  this.filePath = filePath;
@@ -63710,7 +65214,7 @@ var ReviewQueue = class {
63710
65214
  async load() {
63711
65215
  if (this.cache !== void 0) return this.cache;
63712
65216
  try {
63713
- const parsed = JSON.parse(await fs20.readFile(this.filePath, "utf8"));
65217
+ const parsed = JSON.parse(await fs21.readFile(this.filePath, "utf8"));
63714
65218
  this.cache = Array.isArray(parsed) ? parsed : [];
63715
65219
  } catch {
63716
65220
  this.cache = [];
@@ -63719,10 +65223,10 @@ var ReviewQueue = class {
63719
65223
  }
63720
65224
  async persist(items) {
63721
65225
  this.cache = items;
63722
- await fs20.mkdir(path26.dirname(this.filePath), { recursive: true });
65226
+ await fs21.mkdir(path27.dirname(this.filePath), { recursive: true });
63723
65227
  const temporary = `${this.filePath}.tmp`;
63724
- await fs20.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
63725
- await fs20.rename(temporary, this.filePath);
65228
+ await fs21.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
65229
+ await fs21.rename(temporary, this.filePath);
63726
65230
  }
63727
65231
  async list() {
63728
65232
  return [...await this.load()];
@@ -63877,9 +65381,9 @@ var RoutedSecretStore = class {
63877
65381
  };
63878
65382
 
63879
65383
  // src/userVariables.ts
63880
- import fs21 from "node:fs/promises";
65384
+ import fs22 from "node:fs/promises";
63881
65385
  import { readFileSync } from "node:fs";
63882
- import path27 from "node:path";
65386
+ import path28 from "node:path";
63883
65387
  var UserVariableStore = class {
63884
65388
  constructor(filePath) {
63885
65389
  this.filePath = filePath;
@@ -63894,21 +65398,21 @@ var UserVariableStore = class {
63894
65398
  }
63895
65399
  async save(variables) {
63896
65400
  const parsed = sessionVariablesSchema.parse(variables);
63897
- await fs21.mkdir(path27.dirname(this.filePath), { recursive: true });
65401
+ await fs22.mkdir(path28.dirname(this.filePath), { recursive: true });
63898
65402
  const temporary = `${this.filePath}.tmp`;
63899
- await fs21.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
65403
+ await fs22.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
63900
65404
  encoding: "utf8",
63901
65405
  mode: 384
63902
65406
  });
63903
- await fs21.rename(temporary, this.filePath);
65407
+ await fs22.rename(temporary, this.filePath);
63904
65408
  return parsed;
63905
65409
  }
63906
65410
  };
63907
65411
  function userVariableStoreFor(dataDir, principal) {
63908
- return new UserVariableStore(userVariablesPath(path27.join(dataDir, "users", storageKeyFor(principal))));
65412
+ return new UserVariableStore(userVariablesPath(path28.join(dataDir, "users", storageKeyFor(principal))));
63909
65413
  }
63910
65414
  function userVariablesPath(userDir) {
63911
- return path27.join(userDir, "variables.json");
65415
+ return path28.join(userDir, "variables.json");
63912
65416
  }
63913
65417
  function readVariablesFile(filePath) {
63914
65418
  try {
@@ -63922,8 +65426,8 @@ function readVariablesFile(filePath) {
63922
65426
 
63923
65427
  // src/session.ts
63924
65428
  import { watch as fsWatch } from "node:fs";
63925
- import fs22 from "node:fs/promises";
63926
- import path28 from "node:path";
65429
+ import fs23 from "node:fs/promises";
65430
+ import path29 from "node:path";
63927
65431
  var FileConfigStore = class {
63928
65432
  constructor(userConfigPath, workspaceRoot) {
63929
65433
  this.userConfigPath = userConfigPath;
@@ -63939,7 +65443,7 @@ var FileConfigStore = class {
63939
65443
  const filePath = this.pathFor(scope);
63940
65444
  if (filePath === void 0) return void 0;
63941
65445
  try {
63942
- return await fs22.readFile(filePath, "utf8");
65446
+ return await fs23.readFile(filePath, "utf8");
63943
65447
  } catch (error51) {
63944
65448
  if (error51.code === "ENOENT") return void 0;
63945
65449
  throw error51;
@@ -63949,14 +65453,14 @@ var FileConfigStore = class {
63949
65453
  async write(scope, contents) {
63950
65454
  const filePath = this.pathFor(scope);
63951
65455
  if (filePath === void 0) throw new Error(`Cannot write ${scope} config: no workspace is open`);
63952
- await fs22.mkdir(path28.dirname(filePath), { recursive: true });
65456
+ await fs23.mkdir(path29.dirname(filePath), { recursive: true });
63953
65457
  const temporary = `${filePath}.${process.pid.toString(36)}.tmp`;
63954
- await fs22.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
63955
- await fs22.rename(temporary, filePath);
65458
+ await fs23.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
65459
+ await fs23.rename(temporary, filePath);
63956
65460
  try {
63957
65461
  const backupTemp = `${configBackupPath(filePath)}.tmp`;
63958
- await fs22.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
63959
- await fs22.rename(backupTemp, configBackupPath(filePath));
65462
+ await fs23.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
65463
+ await fs23.rename(backupTemp, configBackupPath(filePath));
63960
65464
  } catch {
63961
65465
  }
63962
65466
  }
@@ -63964,7 +65468,7 @@ var FileConfigStore = class {
63964
65468
  const filePath = this.pathFor(scope);
63965
65469
  if (filePath === void 0) return void 0;
63966
65470
  try {
63967
- return await fs22.readFile(configBackupPath(filePath), "utf8");
65471
+ return await fs23.readFile(configBackupPath(filePath), "utf8");
63968
65472
  } catch {
63969
65473
  return void 0;
63970
65474
  }
@@ -63974,7 +65478,7 @@ var FileConfigStore = class {
63974
65478
  if (filePath === void 0) return void 0;
63975
65479
  const target = `${filePath}.corrupt-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
63976
65480
  try {
63977
- await fs22.rename(filePath, target);
65481
+ await fs23.rename(filePath, target);
63978
65482
  return target;
63979
65483
  } catch {
63980
65484
  return void 0;
@@ -63986,8 +65490,8 @@ var FileConfigStore = class {
63986
65490
  };
63987
65491
  let watcher;
63988
65492
  try {
63989
- watcher = fsWatch(path28.dirname(filePath), (_event, filename) => {
63990
- if (filename === path28.basename(filePath)) onChange();
65493
+ watcher = fsWatch(path29.dirname(filePath), (_event, filename) => {
65494
+ if (filename === path29.basename(filePath)) onChange();
63991
65495
  });
63992
65496
  } catch {
63993
65497
  }
@@ -64002,7 +65506,7 @@ var FileWorkspaceState = class {
64002
65506
  values = {};
64003
65507
  async load() {
64004
65508
  try {
64005
- const parsed = JSON.parse(await fs22.readFile(this.filePath, "utf8"));
65509
+ const parsed = JSON.parse(await fs23.readFile(this.filePath, "utf8"));
64006
65510
  if (typeof parsed === "object" && parsed !== null) this.values = parsed;
64007
65511
  } catch {
64008
65512
  this.values = {};
@@ -64014,8 +65518,8 @@ var FileWorkspaceState = class {
64014
65518
  async set(key, value) {
64015
65519
  if (value === void 0) delete this.values[key];
64016
65520
  else this.values[key] = value;
64017
- await fs22.mkdir(path28.dirname(this.filePath), { recursive: true });
64018
- await fs22.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
65521
+ await fs23.mkdir(path29.dirname(this.filePath), { recursive: true });
65522
+ await fs23.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
64019
65523
  }
64020
65524
  };
64021
65525
  function createBrowserUi(workspaceRoot, post) {
@@ -64053,7 +65557,7 @@ function createBrowserUi(workspaceRoot, post) {
64053
65557
  */
64054
65558
  openFile: async (filePath) => {
64055
65559
  try {
64056
- post([`[info] ${path28.basename(filePath)}`, "", await fs22.readFile(filePath, "utf8")].join("\n"));
65560
+ post([`[info] ${path29.basename(filePath)}`, "", await fs23.readFile(filePath, "utf8")].join("\n"));
64057
65561
  } catch (error51) {
64058
65562
  post(`[warning] Could not read ${filePath}: ${String(error51)}`);
64059
65563
  }
@@ -64071,14 +65575,14 @@ function createBrowserUi(workspaceRoot, post) {
64071
65575
  if (found.length >= limit || depth > 12) return;
64072
65576
  let entries;
64073
65577
  try {
64074
- entries = await fs22.readdir(dir, { withFileTypes: true });
65578
+ entries = await fs23.readdir(dir, { withFileTypes: true });
64075
65579
  } catch {
64076
65580
  return;
64077
65581
  }
64078
65582
  for (const entry of entries) {
64079
65583
  if (found.length >= limit) return;
64080
65584
  if (entry.name.startsWith(".") && entry.name !== ".env") continue;
64081
- const full = path28.join(dir, entry.name);
65585
+ const full = path29.join(dir, entry.name);
64082
65586
  if (entry.isDirectory()) {
64083
65587
  if (!skip.has(entry.name)) await walk(full, depth + 1);
64084
65588
  } else if (needle.length === 0 || entry.name.toLowerCase().includes(needle)) {
@@ -64092,11 +65596,11 @@ function createBrowserUi(workspaceRoot, post) {
64092
65596
  };
64093
65597
  }
64094
65598
  async function createSession(options) {
64095
- const userDir = path28.join(options.dataDir, "users", storageKeyFor(options.principal));
64096
- await fs22.mkdir(userDir, { recursive: true, mode: 448 });
65599
+ const userDir = path29.join(options.dataDir, "users", storageKeyFor(options.principal));
65600
+ await fs23.mkdir(userDir, { recursive: true, mode: 448 });
64097
65601
  const variableStore = new UserVariableStore(userVariablesPath(userDir));
64098
65602
  const userVariables = () => variableStore.read();
64099
- const workspaceState = new FileWorkspaceState(path28.join(userDir, "workspace-state.json"));
65603
+ const workspaceState = new FileWorkspaceState(path29.join(userDir, "workspace-state.json"));
64100
65604
  await workspaceState.load();
64101
65605
  const services = {
64102
65606
  transport: options.transport,
@@ -64104,9 +65608,9 @@ async function createSession(options) {
64104
65608
  * A shared profile's API key belongs to the administrator and lives beside the shared config;
64105
65609
  * everything else is this user's. Routed by the reference, which is all a secret store gets.
64106
65610
  */
64107
- secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path28.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path28.join(userDir, "secrets.json")), options.sharedSecrets),
64108
- configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path28.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
64109
- new FileConfigStore(path28.join(userDir, "config.json"), options.workspaceRoot),
65611
+ secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path29.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path29.join(userDir, "secrets.json")), options.sharedSecrets),
65612
+ configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path29.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
65613
+ new FileConfigStore(path29.join(userDir, "config.json"), options.workspaceRoot),
64110
65614
  options.sharedProfiles
64111
65615
  ),
64112
65616
  workspaceState,
@@ -64191,11 +65695,11 @@ var CONTENT_TYPES = {
64191
65695
  async function startServer(options) {
64192
65696
  const log = options.logSink ?? ((line) => process.stderr.write(`${line}
64193
65697
  `));
64194
- const identity = options.identity ?? new SingleUserIdentity();
65698
+ const identity = options.identity ?? new SingleUserIdentity(options.handoffSeconds);
64195
65699
  const roles = options.roles ?? SINGLE_USER_POLICY;
64196
65700
  const sharedStore = options.sharedConfig;
64197
- const sharedSecretStore = new FileSecretStore(path29.join(options.dataDir, "shared-secrets.json"));
64198
- const reviews = new ReviewQueue(path29.join(options.dataDir, "reviews.json"));
65701
+ const sharedSecretStore = new FileSecretStore(path30.join(options.dataDir, "shared-secrets.json"));
65702
+ const reviews = new ReviewQueue(path30.join(options.dataDir, "reviews.json"));
64199
65703
  let sharedCache = { variables: [], adminIds: [], profiles: [] };
64200
65704
  const bindAddress = options.bindAddress ?? "127.0.0.1";
64201
65705
  if (sharedStore !== void 0) sharedCache = await sharedStore.load();
@@ -64245,6 +65749,15 @@ async function startServer(options) {
64245
65749
  * absent for them rather than a queue they would have to visit to approve themselves.
64246
65750
  */
64247
65751
  ...roles.shared && !isAdminSession(principal) ? {
65752
+ /*
65753
+ * A personal profile may not run a program to fetch its token.
65754
+ *
65755
+ * That would be arbitrary execution as the service account, which §14 says plainly is
65756
+ * the thing locking down configuration does *not* buy you. An administrator can still
65757
+ * set one up as a shared profile, which is where a credential belonging to the server
65758
+ * belongs anyway.
65759
+ */
65760
+ 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.",
64248
65761
  submitForReview: async (request) => {
64249
65762
  const queued = await reviews.submit({ ...request, authorId: principal.id, authorName: principal.displayName });
64250
65763
  log(`${principal.displayName} submitted ${request.kind} "${request.name}" for review`);
@@ -64299,12 +65812,16 @@ async function startServer(options) {
64299
65812
  }
64300
65813
  const body = await readJsonBody(request);
64301
65814
  const handoff = typeof body?.handoff === "string" ? body.handoff : "";
64302
- const token = identity.redeemHandoff(handoff);
64303
- if (token === void 0) {
64304
- reject(response, { status: 401, reason: "Handoff token invalid or expired. Restart light-code." });
65815
+ const outcome = identity.redeem(handoff);
65816
+ if (outcome.token === void 0) {
65817
+ if (outcome.reason === "expired" || outcome.reason === "spent") options.onHandoffLapsed?.(outcome.reason);
65818
+ reject(response, {
65819
+ status: 401,
65820
+ 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."
65821
+ });
64305
65822
  return;
64306
65823
  }
64307
- respondJson(response, 200, { token });
65824
+ respondJson(response, 200, { token: outcome.token });
64308
65825
  return;
64309
65826
  }
64310
65827
  const principal = await identity.authenticate(request);
@@ -64397,14 +65914,14 @@ async function startServer(options) {
64397
65914
  if (options.workspaceRoot === void 0) return "No workspace is open, so there is nowhere to write it.";
64398
65915
  try {
64399
65916
  if (item.kind === "skill") {
64400
- const dir2 = path29.join(options.workspaceRoot, ".lightcode", "skills");
64401
- await fs23.mkdir(dir2, { recursive: true });
64402
- await fs23.writeFile(path29.join(dir2, `${item.name}.md`), item.content, "utf8");
65917
+ const dir2 = path30.join(options.workspaceRoot, ".lightcode", "skills");
65918
+ await fs24.mkdir(dir2, { recursive: true });
65919
+ await fs24.writeFile(path30.join(dir2, `${item.name}.md`), item.content, "utf8");
64403
65920
  return void 0;
64404
65921
  }
64405
- const dir = path29.join(options.workspaceRoot, ".lightcode", "tools");
64406
- await fs23.mkdir(dir, { recursive: true });
64407
- await fs23.writeFile(path29.join(dir, `${item.name}.py`), item.content, "utf8");
65922
+ const dir = path30.join(options.workspaceRoot, ".lightcode", "tools");
65923
+ await fs24.mkdir(dir, { recursive: true });
65924
+ await fs24.writeFile(path30.join(dir, `${item.name}.py`), item.content, "utf8");
64408
65925
  return void 0;
64409
65926
  } catch (error51) {
64410
65927
  return error51 instanceof Error ? error51.message : String(error51);
@@ -64505,9 +66022,9 @@ async function startServer(options) {
64505
66022
  return;
64506
66023
  }
64507
66024
  try {
64508
- const body = await fs23.readFile(path29.join(options.clientDir, asset));
66025
+ const body = await fs24.readFile(path30.join(options.clientDir, asset));
64509
66026
  response.writeHead(200, {
64510
- "Content-Type": CONTENT_TYPES[path29.extname(asset)] ?? "application/octet-stream",
66027
+ "Content-Type": CONTENT_TYPES[path30.extname(asset)] ?? "application/octet-stream",
64511
66028
  ...securityHeaders()
64512
66029
  });
64513
66030
  response.end(body);
@@ -64523,6 +66040,7 @@ async function startServer(options) {
64523
66040
  return {
64524
66041
  url: `http://${authority}`,
64525
66042
  launchToken: identity instanceof SingleUserIdentity ? identity.launchToken : void 0,
66043
+ newLaunchUrl: identity instanceof SingleUserIdentity ? () => `http://${authority}/#t=${identity.remintHandoff()}` : void 0,
64526
66044
  close: () => new Promise((resolve) => {
64527
66045
  for (const connection of connections.values()) connection.dispose();
64528
66046
  connections.clear();