@chosengeneration/light-code 0.35.0 → 0.39.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(" ");
@@ -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,171 @@ 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
+ var WRAPPER_KEYS = ["records", "items", "data", "results", "rows"];
38975
+ var TEXT_KEYS = ["text", "content", "body", "description", "summary"];
38976
+ function toMilliseconds(value) {
38977
+ if (typeof value === "string") {
38978
+ const parsed = Date.parse(value);
38979
+ return Number.isNaN(parsed) ? void 0 : parsed;
38980
+ }
38981
+ if (typeof value !== "number" || !Number.isFinite(value))
38982
+ return void 0;
38983
+ return value > 0 && value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
38984
+ }
38985
+ function normaliseRecord(value) {
38986
+ if (value === null || typeof value !== "object" || Array.isArray(value))
38987
+ return void 0;
38988
+ const row = value;
38989
+ const id = row["id"] ?? row["key"] ?? row["_id"];
38990
+ const textKey = TEXT_KEYS.find((key) => typeof row[key] === "string" && row[key].length > 0);
38991
+ const record2 = {
38992
+ ...typeof id === "string" || typeof id === "number" ? { id: String(id) } : {},
38993
+ ...textKey !== void 0 ? { text: row[textKey] } : {},
38994
+ ...typeof row["title"] === "string" ? { title: row["title"] } : {},
38995
+ ...typeof row["url"] === "string" ? { url: row["url"] } : {}
38996
+ };
38997
+ const at = toMilliseconds(row["timestamp"] ?? row["updated"] ?? row["updated_at"] ?? row["date"]);
38998
+ if (at !== void 0)
38999
+ record2["timestamp"] = at;
39000
+ if (row["tags"] !== null && typeof row["tags"] === "object" && !Array.isArray(row["tags"])) {
39001
+ const tags = {};
39002
+ for (const [key, tagValue] of Object.entries(row["tags"])) {
39003
+ if (tagValue === null || tagValue === void 0)
39004
+ continue;
39005
+ if (typeof tagValue === "object")
39006
+ continue;
39007
+ tags[key] = String(tagValue);
39008
+ }
39009
+ if (Object.keys(tags).length > 0)
39010
+ record2["tags"] = tags;
39011
+ }
39012
+ return record2;
39013
+ }
39014
+ function parseDatasetPayload(value) {
39015
+ let candidate = value;
39016
+ if (typeof candidate === "string") {
39017
+ try {
39018
+ candidate = JSON.parse(candidate);
39019
+ } catch {
39020
+ return {
39021
+ error: `The collector tool returned text rather than records. It must return a list of {"id": ..., "text": ...} dicts. It returned: ${String(value).slice(0, 200)}`
39022
+ };
39023
+ }
39024
+ }
39025
+ if (candidate !== null && typeof candidate === "object" && !Array.isArray(candidate)) {
39026
+ const wrapper = WRAPPER_KEYS.find((key) => Array.isArray(candidate[key]));
39027
+ candidate = wrapper === void 0 ? [candidate] : candidate[wrapper];
39028
+ }
39029
+ if (!Array.isArray(candidate)) {
39030
+ return {
39031
+ error: `The collector tool did not return a list of records. Return a list of {"id": ..., "text": ...} dicts, or a dict with them under "records". It returned: ${JSON.stringify(value).slice(0, 200)}`
39032
+ };
39033
+ }
39034
+ const normalised = candidate.map((entry) => normaliseRecord(entry) ?? entry);
39035
+ const parsed = external_exports.array(datasetRecordSchema).safeParse(normalised);
39036
+ if (parsed.success)
39037
+ return { records: parsed.data };
39038
+ const first = parsed.error.issues[0];
39039
+ const index = typeof first?.path[0] === "number" ? first.path[0] : 0;
39040
+ const offending = candidate[index];
39041
+ const keys = offending !== null && typeof offending === "object" ? Object.keys(offending).join(", ") : "none";
39042
+ return {
39043
+ error: `The collector tool returned ${String(candidate.length)} item(s), and item ${String(index + 1)} is not a usable record. Each needs a stable \`id\` (the source's own identifier, so a re-sync updates rather than duplicates) and a \`text\` to index. That item had these keys: ${keys}. ` + parsed.error.issues.slice(0, 3).map((issue2) => `${issue2.path.join(".")}: ${issue2.message}`).join("; ")
39044
+ };
39045
+ }
39046
+ var datasetConfigSchema = external_exports.object({
39047
+ id: external_exports.string().min(1),
39048
+ name: external_exports.string().min(1, "Give it a name"),
39049
+ /** The Python tool that produces the records, by its bare name. */
39050
+ toolName: external_exports.string().min(1, "Choose a collector tool"),
39051
+ /** Passed to the tool as its arguments, so one tool can serve several datasets. */
39052
+ arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
39053
+ enabled: external_exports.boolean().optional(),
39054
+ /** How often to re-run the collector. Zero or absent means only when asked. */
39055
+ syncMinutes: external_exports.number().int().min(0).optional(),
39056
+ /** Drop records older than this. Absent means keep everything. */
39057
+ retentionDays: external_exports.number().int().positive().optional(),
39058
+ /** Which vector store to write to. Falls back to the one named for `data`, then the active one. */
39059
+ storeId: external_exports.string().optional()
39060
+ });
39061
+ var COLLECTOR_EXAMPLE = `def run(since: int | None = None) -> list[dict]:
39062
+ """Tickets assigned to the team.
39063
+
39064
+ Args:
39065
+ since: Epoch milliseconds of the last successful sync, or None on the first run.
39066
+ """
39067
+ rows = my_internal_lib.search(updated_after=since)
39068
+ return [
39069
+ {
39070
+ "id": row.key, # stable: the source's own identifier
39071
+ "title": row.summary,
39072
+ "text": f"{row.summary}\\n\\n{row.description}", # what gets embedded
39073
+ "url": row.browse_url,
39074
+ "timestamp": int(row.updated.timestamp() * 1000), # epoch MILLIseconds
39075
+ "tags": {"status": row.status, "team": row.team}, # flat, strings only
39076
+ }
39077
+ for row in rows
39078
+ ]`;
39079
+ var COLLECTOR_TOOL_GUIDANCE = [
39080
+ "Writing a collector for a custom dataset:",
39081
+ "- A collector is an ordinary Python tool. Its `run` returns a list of records, each a dict",
39082
+ " with `id` and `text`, and optionally `title`, `url`, `timestamp` (epoch milliseconds) and",
39083
+ " `tags` (a flat dict of strings).",
39084
+ "- **`id` must be stable across runs.** Use the source's own identifier \u2014 a ticket key, a row",
39085
+ " id, a file path. A generated or time-based id makes every sync duplicate the whole corpus",
39086
+ " instead of updating it, which is not obvious until the results are full of near-copies.",
39087
+ "- **`text` is what gets embedded and what a search shows.** Put the meaning in it: a subject",
39088
+ " and a body, not an id and a status code. Roughly a paragraph to a page each works best.",
39089
+ '- Set `timestamp` wherever the source has one. Retention and any "what changed recently"',
39090
+ " question both need it, and it cannot be recovered later.",
39091
+ "- The tool is called with whatever arguments the dataset configures, plus `since` \u2014 epoch",
39092
+ " milliseconds of the last successful sync, or absent on the first. Use it to fetch only what",
39093
+ " changed if the source allows; returning everything each time is correct but slower.",
39094
+ "- Return `[]` when there is nothing new. That is a successful sync, not an error.",
39095
+ "- Keep credentials out of the tool: read them from the environment or from a file the user",
39096
+ " already has. A tool file lives in the workspace and lands in git.",
39097
+ "",
39098
+ "**Return a list of dicts. Not a string, not a dict of rows, not a formatted report.** The",
39099
+ "common mistake is returning something a person would read; a collector returns something a",
39100
+ "search can index, and anything else is refused when it runs. If the source gives you one",
39101
+ "object, return a one-element list.",
39102
+ "",
39103
+ "A collector looks like this:",
39104
+ "",
39105
+ "```python",
39106
+ COLLECTOR_EXAMPLE,
39107
+ "```"
39108
+ ].join("\n");
39109
+
38945
39110
  // ../../packages/core/dist/mcp/types.js
38946
39111
  var stdioServerSchema = external_exports.object({
38947
39112
  command: external_exports.string().min(1),
@@ -39213,6 +39378,20 @@ var authSchema = external_exports.discriminatedUnion("type", [
39213
39378
  */
39214
39379
  external_exports.object({ type: external_exports.literal("apiKey"), apiKeyRef: external_exports.string().min(1) }),
39215
39380
  external_exports.object({ type: external_exports.literal("tokenCommand"), tokenCommand: tokenCommandSchema }),
39381
+ /**
39382
+ * A fixed header the gateway expects, with no API key involved.
39383
+ *
39384
+ * Each value is a *reference* — a secret-store key, or `env:NAME` — never a literal, because
39385
+ * the profile lives in the config file and §15 is explicit that a credential never does.
39386
+ */
39387
+ external_exports.object({
39388
+ type: external_exports.literal("header"),
39389
+ headers: external_exports.array(external_exports.object({
39390
+ name: external_exports.string().min(1, "Give the header name"),
39391
+ valueRef: external_exports.string().min(1, "Give the value, or env:NAME"),
39392
+ prefix: external_exports.string().optional()
39393
+ })).min(1, "Add at least one header")
39394
+ }),
39216
39395
  external_exports.object({
39217
39396
  type: external_exports.literal("apigeeMtls"),
39218
39397
  certs: certConfigSchema,
@@ -39256,6 +39435,7 @@ var providerProfileSchema = external_exports.object({
39256
39435
  });
39257
39436
 
39258
39437
  // ../../packages/core/dist/config/schema.js
39438
+ var datasetsConfigSchema = external_exports.array(datasetConfigSchema);
39259
39439
  var pythonConfigSchema = external_exports.object({
39260
39440
  /**
39261
39441
  * Off by default and explicitly three-state. This is the sharpest surface in the
@@ -39545,7 +39725,15 @@ var retrievalConfigSchema = external_exports.object({
39545
39725
  /** Indexed mail. Usually local, and deliberately easy to keep separate. */
39546
39726
  mail: external_exports.string().min(1),
39547
39727
  /** The team's shared skills. Often the same cluster as the code. */
39548
- skills: external_exports.string().min(1)
39728
+ skills: external_exports.string().min(1),
39729
+ /**
39730
+ * Corpora the user collects themselves.
39731
+ *
39732
+ * Routed separately for the same reason mail is: somebody's own collected data —
39733
+ * tickets, extracts from an internal system — is frequently the thing they most want
39734
+ * kept off a cluster their team shares.
39735
+ */
39736
+ data: external_exports.string().min(1)
39549
39737
  }).partial()
39550
39738
  }).partial();
39551
39739
  function storeIdFor(purpose, config2) {
@@ -39733,6 +39921,7 @@ var configSchema = external_exports.object({
39733
39921
  programmingProfileId: external_exports.string(),
39734
39922
  certDir: external_exports.string(),
39735
39923
  python: pythonConfigSchema,
39924
+ datasets: datasetsConfigSchema,
39736
39925
  /**
39737
39926
  * Keyed by workspace path. Per-workspace in *behaviour* (§8) but stored user-side and
39738
39927
  * user-scope-only (invariant 5) — a repo must not be able to ship its own
@@ -40204,6 +40393,19 @@ var GUIDE_STEPS = [
40204
40393
  "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."
40205
40394
  ]
40206
40395
  },
40396
+ {
40397
+ id: "customData",
40398
+ title: "Custom data - bring your own corpus",
40399
+ tab: "customData",
40400
+ completionEvents: ["onStepSelected"],
40401
+ 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.",
40402
+ body: [
40403
+ "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.",
40404
+ "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.",
40405
+ "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.",
40406
+ "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."
40407
+ ]
40408
+ },
40207
40409
  {
40208
40410
  id: "search",
40209
40411
  title: "Search - find things by meaning",
@@ -40306,6 +40508,9 @@ var USER_SCOPE_ONLY_KEYS = [
40306
40508
  // Added for Phase 8b, and the sharpest entries on this list. A workspace able to name a
40307
40509
  // cluster, or repoint the embedder at a profile of its choosing, would exfiltrate
40308
40510
  // whatever gets indexed — and what gets indexed is the source code.
40511
+ // A dataset names a program to run *and* a store to write what it produced into — the `python`
40512
+ // threat and the `embedder` threat in one key, on a timer.
40513
+ "datasets",
40309
40514
  "vectorStores",
40310
40515
  "activeVectorStoreId",
40311
40516
  "embedder",
@@ -40868,6 +41073,27 @@ var NoAuthStrategy = class {
40868
41073
  }
40869
41074
  };
40870
41075
 
41076
+ // ../../packages/core/dist/providers/auth/header.js
41077
+ var HeaderAuthStrategy = class {
41078
+ secrets;
41079
+ credentials;
41080
+ constructor(secrets, credentials) {
41081
+ this.secrets = secrets;
41082
+ this.credentials = credentials;
41083
+ }
41084
+ async resolveHeaders() {
41085
+ const headers = {};
41086
+ for (const credential of this.credentials) {
41087
+ const value = await resolveSecretRef(credential.valueRef, { secrets: this.secrets });
41088
+ if (value === void 0) {
41089
+ throw new Error(`${describeMissingSecret(credential.valueRef, `the value for header "${credential.name}"`)}`);
41090
+ }
41091
+ headers[credential.name] = `${credential.prefix ?? ""}${value}`;
41092
+ }
41093
+ return headers;
41094
+ }
41095
+ };
41096
+
40871
41097
  // ../../packages/core/dist/providers/auth/tokenCommand.js
40872
41098
  import { spawn } from "node:child_process";
40873
41099
  function readPath(source, dotted) {
@@ -41413,6 +41639,8 @@ function createBaseAuthStrategy(auth2, context) {
41413
41639
  headerPrefix: auth2.tokenCommand.headerPrefix ?? context.apiKeyHeaderPrefix ?? derived.prefix
41414
41640
  });
41415
41641
  }
41642
+ case "header":
41643
+ return new HeaderAuthStrategy(context.secrets, auth2.headers);
41416
41644
  case "none":
41417
41645
  return new NoAuthStrategy();
41418
41646
  case "apigeeMtls": {
@@ -42391,8 +42619,8 @@ var SUPERSEDED_MARKER = "[Superseded: this file was read again later in the conv
42391
42619
  function readFilePath(argumentsJson) {
42392
42620
  try {
42393
42621
  const parsed = JSON.parse(argumentsJson.length > 0 ? argumentsJson : "{}");
42394
- const path30 = parsed.path;
42395
- return typeof path30 === "string" && path30.length > 0 ? path30 : void 0;
42622
+ const path31 = parsed.path;
42623
+ return typeof path31 === "string" && path31.length > 0 ? path31 : void 0;
42396
42624
  } catch {
42397
42625
  return void 0;
42398
42626
  }
@@ -42405,8 +42633,8 @@ function dropSupersededReads(messages) {
42405
42633
  for (const toolCall of message3.toolCalls ?? []) {
42406
42634
  if (toolCall.name !== "read_file")
42407
42635
  continue;
42408
- const path30 = readFilePath(toolCall.arguments);
42409
- if (path30 === void 0)
42636
+ const path31 = readFilePath(toolCall.arguments);
42637
+ if (path31 === void 0)
42410
42638
  continue;
42411
42639
  keyByCallId.set(toolCall.id, toolCall.arguments);
42412
42640
  }
@@ -42841,6 +43069,18 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
42841
43069
  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.");
42842
43070
  }
42843
43071
  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.");
43072
+ if (options.canWriteCollectors === true && (options.datasets ?? []).length === 0) {
43073
+ lines.push("", "Custom datasets:", "- None are configured yet. The user sets one up in Settings, Custom data, by pointing at a", " tool that returns records \u2014 and can ask you to write that tool. If they do, it is an", " ordinary Python tool and the contract is below. Follow it exactly: a collector returning", " the wrong shape is refused when it runs, not when it is written.", "", COLLECTOR_TOOL_GUIDANCE);
43074
+ }
43075
+ if (options.datasets !== void 0 && options.datasets.length > 0) {
43076
+ 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 ? [
43077
+ "- If they want a dataset you cannot find, you can write the collector: it is an",
43078
+ " ordinary Python tool returning records. Offer, do not assume \u2014 then they configure",
43079
+ " it in Settings, Custom data. The contract is below.",
43080
+ "",
43081
+ COLLECTOR_TOOL_GUIDANCE
43082
+ ] : []);
43083
+ }
42844
43084
  if (options.mailIndexed === true) {
42845
43085
  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.");
42846
43086
  }
@@ -43480,13 +43720,13 @@ var OpenSearchClient = class {
43480
43720
  * `_bulk`, `_delete_by_query`, index creation — is refused here rather than merely
43481
43721
  * unused, so no future edit or crafted argument can turn a read client into a writer.
43482
43722
  */
43483
- async request(path30, options = {}) {
43723
+ async request(path31, options = {}) {
43484
43724
  const method = options.method ?? "GET";
43485
- const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path30);
43725
+ const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path31);
43486
43726
  if (method !== "GET" && !isSearchPost) {
43487
- throw new OpenSearchError(`Refusing ${method} ${path30}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
43727
+ throw new OpenSearchError(`Refusing ${method} ${path31}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
43488
43728
  }
43489
- const url2 = `${this.base}${path30}`;
43729
+ const url2 = `${this.base}${path31}`;
43490
43730
  const request = {
43491
43731
  method,
43492
43732
  headers: this.headers()
@@ -43649,11 +43889,11 @@ function collectFields(properties, prefix, out) {
43649
43889
  return;
43650
43890
  for (const [name, raw] of Object.entries(properties)) {
43651
43891
  const field = raw;
43652
- const path30 = prefix.length > 0 ? `${prefix}.${name}` : name;
43892
+ const path31 = prefix.length > 0 ? `${prefix}.${name}` : name;
43653
43893
  if (typeof field.type === "string")
43654
- out[path30] = field.type;
43894
+ out[path31] = field.type;
43655
43895
  if (field.properties !== void 0)
43656
- collectFields(field.properties, path30, out);
43896
+ collectFields(field.properties, path31, out);
43657
43897
  }
43658
43898
  }
43659
43899
  function describeStatus(status, url2, body) {
@@ -43672,23 +43912,23 @@ function describeStatus(status, url2, body) {
43672
43912
  var TEXT_TYPES = /* @__PURE__ */ new Set(["text", "match_only_text", "search_as_you_type", "wildcard"]);
43673
43913
  var KEYWORD_TYPES = /* @__PURE__ */ new Set(["keyword", "constant_keyword"]);
43674
43914
  var NOISE_FIELDS = /* @__PURE__ */ new Set(["@version", "ecs", "tags", "stream", "input", "agent", "host", "event"]);
43675
- function leafName(path30) {
43676
- const parts = path30.split(".");
43677
- return parts[parts.length - 1] ?? path30;
43915
+ function leafName(path31) {
43916
+ const parts = path31.split(".");
43917
+ return parts[parts.length - 1] ?? path31;
43678
43918
  }
43679
43919
  function selectQueryFields(mapping, limit = 25) {
43680
43920
  const text = [];
43681
43921
  const keyword = [];
43682
- for (const [path30, type] of Object.entries(mapping)) {
43683
- if (NOISE_FIELDS.has(leafName(path30)) || NOISE_FIELDS.has(path30.split(".")[0] ?? ""))
43922
+ for (const [path31, type] of Object.entries(mapping)) {
43923
+ if (NOISE_FIELDS.has(leafName(path31)) || NOISE_FIELDS.has(path31.split(".")[0] ?? ""))
43684
43924
  continue;
43685
43925
  if (TEXT_TYPES.has(type)) {
43686
- text.push(path30);
43926
+ text.push(path31);
43687
43927
  } else if (KEYWORD_TYPES.has(type)) {
43688
- const parent = path30.replace(/\.keyword$/, "");
43689
- if (path30.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
43928
+ const parent = path31.replace(/\.keyword$/, "");
43929
+ if (path31.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
43690
43930
  continue;
43691
- keyword.push(path30);
43931
+ keyword.push(path31);
43692
43932
  }
43693
43933
  }
43694
43934
  const byDepth = (a, b) => a.split(".").length - b.split(".").length || a.localeCompare(b);
@@ -43830,8 +44070,8 @@ var OpenSearchIndexWriter = class {
43830
44070
  }
43831
44071
  return headers;
43832
44072
  }
43833
- async request(path30, method, body, signal) {
43834
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path30}`;
44073
+ async request(path31, method, body, signal) {
44074
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path31}`;
43835
44075
  const request = { method, headers: this.headers() };
43836
44076
  if (body !== void 0) {
43837
44077
  if (typeof body === "string") {
@@ -44045,13 +44285,13 @@ var OpenSearchIndexWriter = class {
44045
44285
  for (const hit of hits) {
44046
44286
  const source = hit._source ?? {};
44047
44287
  const vector = source.vector;
44048
- const path30 = source.path;
44049
- if (typeof path30 !== "string" || !Array.isArray(vector))
44288
+ const path31 = source.path;
44289
+ if (typeof path31 !== "string" || !Array.isArray(vector))
44050
44290
  continue;
44051
44291
  documents.push({
44052
44292
  id: hit._id ?? "",
44053
44293
  text: typeof source.text === "string" ? source.text : "",
44054
- path: path30,
44294
+ path: path31,
44055
44295
  startLine: typeof source.startLine === "number" ? source.startLine : 1,
44056
44296
  endLine: typeof source.endLine === "number" ? source.endLine : 1,
44057
44297
  vector
@@ -44125,8 +44365,8 @@ var RestTransport = class {
44125
44365
  * threw would push every caller into catching and re-inspecting an error to find out
44126
44366
  * whether it was really an error. `expectOk` is there for the cases that are.
44127
44367
  */
44128
- async send(path30, method, body, signal) {
44129
- const url2 = `${this.connection.url.replace(/\/+$/, "")}${path30}`;
44368
+ async send(path31, method, body, signal) {
44369
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}${path31}`;
44130
44370
  const request = { method, headers: this.headers() };
44131
44371
  if (body !== void 0)
44132
44372
  request.body = JSON.stringify(body);
@@ -44152,11 +44392,11 @@ var RestTransport = class {
44152
44392
  return { status: response.status, body: parsed };
44153
44393
  }
44154
44394
  /** Sends, and throws unless the status is 2xx. */
44155
- async expectOk(path30, method, body, signal) {
44156
- const result = await this.send(path30, method, body, signal);
44395
+ async expectOk(path31, method, body, signal) {
44396
+ const result = await this.send(path31, method, body, signal);
44157
44397
  if (result.status < 200 || result.status >= 300) {
44158
44398
  const detail = typeof result.body === "string" ? result.body : JSON.stringify(result.body ?? "");
44159
- throw new VectorStoreError(`${method} ${path30} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
44399
+ throw new VectorStoreError(`${method} ${path31} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
44160
44400
  }
44161
44401
  return result.body;
44162
44402
  }
@@ -44257,10 +44497,10 @@ var ChromaSearcher = class extends ChromaBase {
44257
44497
  const matches = [];
44258
44498
  for (let index = 0; index < ids.length; index++) {
44259
44499
  const metadata = metadatas[index] ?? {};
44260
- const path30 = typeof metadata.path === "string" ? metadata.path : void 0;
44261
- if (path30 === void 0)
44500
+ const path31 = typeof metadata.path === "string" ? metadata.path : void 0;
44501
+ if (path31 === void 0)
44262
44502
  continue;
44263
- if (filtering && !path30.startsWith(prefix))
44503
+ if (filtering && !path31.startsWith(prefix))
44264
44504
  continue;
44265
44505
  const distance = distances[index];
44266
44506
  const match = {
@@ -44272,7 +44512,7 @@ var ChromaSearcher = class extends ChromaBase {
44272
44512
  */
44273
44513
  score: typeof distance === "number" ? 1 / (1 + Math.max(0, distance)) : 0,
44274
44514
  text: documents[index] ?? (typeof metadata.text === "string" ? metadata.text : ""),
44275
- path: path30
44515
+ path: path31
44276
44516
  };
44277
44517
  if (typeof metadata.startLine === "number")
44278
44518
  match.startLine = metadata.startLine;
@@ -44383,13 +44623,13 @@ var ChromaIndexWriter = class extends ChromaBase {
44383
44623
  for (let index = 0; index < ids.length; index++) {
44384
44624
  const metadata = result.metadatas?.[index] ?? {};
44385
44625
  const vector = result.embeddings?.[index];
44386
- const path30 = typeof metadata.path === "string" ? metadata.path : void 0;
44387
- if (path30 === void 0 || !Array.isArray(vector))
44626
+ const path31 = typeof metadata.path === "string" ? metadata.path : void 0;
44627
+ if (path31 === void 0 || !Array.isArray(vector))
44388
44628
  continue;
44389
44629
  documents.push({
44390
44630
  id: ids[index] ?? "",
44391
44631
  text: result.documents?.[index] ?? "",
44392
- path: path30,
44632
+ path: path31,
44393
44633
  startLine: typeof metadata.startLine === "number" ? metadata.startLine : 1,
44394
44634
  endLine: typeof metadata.endLine === "number" ? metadata.endLine : 1,
44395
44635
  vector
@@ -44406,9 +44646,9 @@ var ChromaIndexWriter = class extends ChromaBase {
44406
44646
  const result = await this.rest.expectOk(`${this.base}/collections/${found.id}/get`, "POST", { include: ["metadatas"], limit }, options.signal);
44407
44647
  const paths = /* @__PURE__ */ new Set();
44408
44648
  for (const metadata of result.metadatas ?? []) {
44409
- const path30 = metadata?.path;
44410
- if (typeof path30 === "string")
44411
- paths.add(path30);
44649
+ const path31 = metadata?.path;
44650
+ if (typeof path31 === "string")
44651
+ paths.add(path31);
44412
44652
  }
44413
44653
  return [...paths];
44414
44654
  }
@@ -44435,14 +44675,14 @@ var MARKER_ID = "5f6d2a41-0000-5000-8000-6c69676874c0";
44435
44675
  var MARKER_MARK = "light-code";
44436
44676
  function toMatch(point) {
44437
44677
  const payload = point.payload ?? {};
44438
- const path30 = typeof payload.path === "string" ? payload.path : void 0;
44439
- if (path30 === void 0)
44678
+ const path31 = typeof payload.path === "string" ? payload.path : void 0;
44679
+ if (path31 === void 0)
44440
44680
  return void 0;
44441
44681
  const match = {
44442
44682
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
44443
44683
  score: typeof point.score === "number" ? point.score : 0,
44444
44684
  text: typeof payload.text === "string" ? payload.text : "",
44445
- path: path30
44685
+ path: path31
44446
44686
  };
44447
44687
  if (typeof payload.startLine === "number")
44448
44688
  match.startLine = payload.startLine;
@@ -44620,13 +44860,13 @@ var QdrantIndexWriter = class extends QdrantBase {
44620
44860
  const documents = [];
44621
44861
  for (const point of result.body.result?.points ?? []) {
44622
44862
  const payload = point.payload ?? {};
44623
- const path30 = typeof payload.path === "string" ? payload.path : void 0;
44624
- if (path30 === void 0 || !Array.isArray(point.vector))
44863
+ const path31 = typeof payload.path === "string" ? payload.path : void 0;
44864
+ if (path31 === void 0 || !Array.isArray(point.vector))
44625
44865
  continue;
44626
44866
  documents.push({
44627
44867
  id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
44628
44868
  text: typeof payload.text === "string" ? payload.text : "",
44629
- path: path30,
44869
+ path: path31,
44630
44870
  startLine: typeof payload.startLine === "number" ? payload.startLine : 1,
44631
44871
  endLine: typeof payload.endLine === "number" ? payload.endLine : 1,
44632
44872
  vector: point.vector
@@ -44653,9 +44893,9 @@ var QdrantIndexWriter = class extends QdrantBase {
44653
44893
  throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).`, result.status);
44654
44894
  }
44655
44895
  for (const point of result.body.result?.points ?? []) {
44656
- const path30 = point.payload?.path;
44657
- if (typeof path30 === "string")
44658
- paths.add(path30);
44896
+ const path31 = point.payload?.path;
44897
+ if (typeof path31 === "string")
44898
+ paths.add(path31);
44659
44899
  }
44660
44900
  offset = result.body.result?.next_page_offset;
44661
44901
  if (offset === void 0 || offset === null)
@@ -45069,8 +45309,8 @@ function teamSkillDocument(skill, body, vector, attribution) {
45069
45309
  vector
45070
45310
  };
45071
45311
  }
45072
- function nameFromPath(path30) {
45073
- return path30.startsWith("skill:") ? path30.slice("skill:".length) : path30;
45312
+ function nameFromPath(path31) {
45313
+ return path31.startsWith("skill:") ? path31.slice("skill:".length) : path31;
45074
45314
  }
45075
45315
  function toHit(match, self) {
45076
45316
  return {
@@ -46456,8 +46696,8 @@ function createMailCoverageTool(options) {
46456
46696
  }
46457
46697
  };
46458
46698
  }
46459
- function normaliseFolder(path30) {
46460
- return path30.toLowerCase().replace(/[\\/]+/g, "\\");
46699
+ function normaliseFolder(path31) {
46700
+ return path31.toLowerCase().replace(/[\\/]+/g, "\\");
46461
46701
  }
46462
46702
  function haystackOf(record2) {
46463
46703
  return `${record2.subject}
@@ -46915,7 +47155,7 @@ async function refreshMail(options) {
46915
47155
  const limit = options.batchLimit ?? 2e3;
46916
47156
  const previewChars = options.previewChars ?? 400;
46917
47157
  const sinceMs = Date.now() - options.days * 24 * 60 * 60 * 1e3;
46918
- const harvested = await options.harvest(options.folders.map((path30) => ({ path: path30, sinceMs })), { limit, previewChars });
47158
+ const harvested = await options.harvest(options.folders.map((path31) => ({ path: path31, sinceMs })), { limit, previewChars });
46919
47159
  const fetched = harvested.messages.map(toRecord);
46920
47160
  if (fetched.length === 0) {
46921
47161
  return { added: 0, more: false, total: known.length, embedded: 0, backfilled: 0, complete: [] };
@@ -46956,9 +47196,9 @@ async function syncMail(options) {
46956
47196
  const backfillDone = await options.store.loadBackfillState();
46957
47197
  const limit = options.batchLimit ?? 500;
46958
47198
  const previewChars = options.previewChars ?? 400;
46959
- const forwardRequests = options.folders.map((path30) => {
46960
- const mark = marks.get(path30);
46961
- return mark === void 0 ? { path: path30 } : { path: path30, sinceMs: mark.newest - 1e3 };
47199
+ const forwardRequests = options.folders.map((path31) => {
47200
+ const mark = marks.get(path31);
47201
+ return mark === void 0 ? { path: path31 } : { path: path31, sinceMs: mark.newest - 1e3 };
46962
47202
  });
46963
47203
  const forward = await options.harvest(forwardRequests, { limit, previewChars });
46964
47204
  let candidates = forward.messages.map(toRecord);
@@ -46967,15 +47207,15 @@ async function syncMail(options) {
46967
47207
  let more = forward.truncated;
46968
47208
  const remaining = limit - candidates.length;
46969
47209
  const floor = options.retentionMonths === void 0 ? void 0 : monthsBefore(options.now ?? Date.now(), options.retentionMonths);
46970
- const outstanding = options.folders.filter((path30) => marks.has(path30) && backfillDone[path30] !== true);
46971
- const atFloor = floor === void 0 ? [] : outstanding.filter((path30) => marks.get(path30).oldest <= floor);
46972
- const behind = outstanding.filter((path30) => !atFloor.includes(path30));
47210
+ const outstanding = options.folders.filter((path31) => marks.has(path31) && backfillDone[path31] !== true);
47211
+ const atFloor = floor === void 0 ? [] : outstanding.filter((path31) => marks.get(path31).oldest <= floor);
47212
+ const behind = outstanding.filter((path31) => !atFloor.includes(path31));
46973
47213
  completed.push(...atFloor);
46974
47214
  if (remaining > 0 && behind.length > 0 && options.signal?.aborted !== true) {
46975
- const backRequests = behind.map((path30) => ({
46976
- path: path30,
47215
+ const backRequests = behind.map((path31) => ({
47216
+ path: path31,
46977
47217
  // Strictly older, so the oldest held message is not fetched again every pass.
46978
- beforeMs: marks.get(path30).oldest,
47218
+ beforeMs: marks.get(path31).oldest,
46979
47219
  // And no older than retention wants. The harvest ANDs the two into one window.
46980
47220
  ...floor === void 0 ? {} : { sinceMs: floor }
46981
47221
  }));
@@ -46983,9 +47223,9 @@ async function syncMail(options) {
46983
47223
  backfilled = backward.messages.length;
46984
47224
  candidates = [...candidates, ...backward.messages.map(toRecord)];
46985
47225
  const returnedFor = new Set(backward.messages.map((message3) => message3.folder));
46986
- for (const path30 of behind) {
46987
- if (!returnedFor.has(path30))
46988
- completed.push(path30);
47226
+ for (const path31 of behind) {
47227
+ if (!returnedFor.has(path31))
47228
+ completed.push(path31);
46989
47229
  }
46990
47230
  if (backward.truncated || backfilled > 0)
46991
47231
  more = true;
@@ -46993,7 +47233,7 @@ async function syncMail(options) {
46993
47233
  if (completed.length > 0) {
46994
47234
  await options.store.saveBackfillState({
46995
47235
  ...backfillDone,
46996
- ...Object.fromEntries(completed.map((path30) => [path30, true]))
47236
+ ...Object.fromEntries(completed.map((path31) => [path31, true]))
46997
47237
  });
46998
47238
  }
46999
47239
  const fresh = withoutKnown(candidates, known);
@@ -47911,14 +48151,14 @@ function formatBytes(size) {
47911
48151
  return `${(size / (1 << 10)).toFixed(1)}KB`;
47912
48152
  return `${String(size)}B`;
47913
48153
  }
47914
- async function readTail(fs24, path30, size, count) {
48154
+ async function readTail(fs25, path31, size, count) {
47915
48155
  let span = Math.min(size, CHUNK);
47916
48156
  let text;
47917
48157
  let start;
47918
48158
  for (; ; ) {
47919
48159
  start = Math.max(0, size - span);
47920
48160
  const decoder = new StringDecoder("utf8");
47921
- text = decoder.write(await fs24.readBytesSlice(path30, start, size)) + decoder.end();
48161
+ text = decoder.write(await fs25.readBytesSlice(path31, start, size)) + decoder.end();
47922
48162
  const enough = text.split("\n").length > count;
47923
48163
  if (enough || start === 0 || span >= size)
47924
48164
  break;
@@ -47936,7 +48176,7 @@ async function readTail(fs24, path30, size, count) {
47936
48176
  hasMoreAfter: false
47937
48177
  };
47938
48178
  }
47939
- async function readLineWindow(fs24, path30, size, from, count) {
48179
+ async function readLineWindow(fs25, path31, size, from, count) {
47940
48180
  const decoder = new StringDecoder("utf8");
47941
48181
  const lines = [];
47942
48182
  let pending = "";
@@ -47951,7 +48191,7 @@ async function readLineWindow(fs24, path30, size, from, count) {
47951
48191
  };
47952
48192
  scan: while (position < size) {
47953
48193
  const end = Math.min(size, position + CHUNK);
47954
- pending += decoder.write(await fs24.readBytesSlice(path30, position, end));
48194
+ pending += decoder.write(await fs25.readBytesSlice(path31, position, end));
47955
48195
  position = end;
47956
48196
  const parts = pending.split(/\r\n|\r|\n/);
47957
48197
  pending = parts.pop() ?? "";
@@ -47974,13 +48214,13 @@ async function readLineWindow(fs24, path30, size, from, count) {
47974
48214
  hasMoreAfter: !reachedEnd || lineNumber > from + lines.length
47975
48215
  };
47976
48216
  }
47977
- async function countLines(fs24, path30, size) {
48217
+ async function countLines(fs25, path31, size) {
47978
48218
  let newlines = 0;
47979
48219
  let position = 0;
47980
48220
  let lastByte = -1;
47981
48221
  while (position < size) {
47982
48222
  const end = Math.min(size, position + CHUNK);
47983
- const buffer = await fs24.readBytesSlice(path30, position, end);
48223
+ const buffer = await fs25.readBytesSlice(path31, position, end);
47984
48224
  for (const byte of buffer)
47985
48225
  if (byte === 10)
47986
48226
  newlines += 1;
@@ -54107,6 +54347,10 @@ var PythonWorker = class {
54107
54347
  this.options.logger.debug("python worker output", line);
54108
54348
  return;
54109
54349
  }
54350
+ if (typeof frame.callback === "string") {
54351
+ void this.serveCallback(frame.callback, frame.name, frame.arguments, frame.caller);
54352
+ return;
54353
+ }
54110
54354
  if (typeof frame.id !== "number")
54111
54355
  return;
54112
54356
  const entry = this.pending.get(frame.id);
@@ -54120,6 +54364,40 @@ var PythonWorker = class {
54120
54364
  entry.reject(new PythonWorkerError(typeof frame.error === "string" ? frame.error : "The Python tool failed.", typeof frame.traceback === "string" ? frame.traceback : void 0));
54121
54365
  }
54122
54366
  }
54367
+ /**
54368
+ * Runs a tool on a Python tool's behalf and writes the answer back.
54369
+ *
54370
+ * The rules live in `options.callTool`, which the host supplies — this only carries the
54371
+ * message. Refusing here would put a policy decision in the transport, where nothing can see
54372
+ * the registry, the approval gate or whether anybody is present to answer.
54373
+ */
54374
+ async serveCallback(token, name, args, caller) {
54375
+ const reply = (payload) => {
54376
+ try {
54377
+ this.child?.stdin?.write(`${JSON.stringify({ callback: token, ...payload })}
54378
+ `);
54379
+ } catch {
54380
+ this.options.logger.debug("python worker: could not answer a callback");
54381
+ }
54382
+ };
54383
+ if (this.options.callTool === void 0) {
54384
+ reply({
54385
+ ok: false,
54386
+ error: "This session cannot call other tools from a Python tool. That is the case during an unattended scheduled run, where nobody is present to approve one."
54387
+ });
54388
+ return;
54389
+ }
54390
+ if (typeof name !== "string") {
54391
+ reply({ ok: false, error: "call_tool needs the name of a tool." });
54392
+ return;
54393
+ }
54394
+ try {
54395
+ const value = await this.options.callTool(name, args ?? {}, typeof caller === "string" ? caller : "a Python tool");
54396
+ reply({ ok: true, value });
54397
+ } catch (error51) {
54398
+ reply({ ok: false, error: error51 instanceof Error ? error51.message : String(error51) });
54399
+ }
54400
+ }
54123
54401
  request(method, params, timeoutMs) {
54124
54402
  if (this.disposed)
54125
54403
  return Promise.reject(new PythonWorkerError("The Python worker has been shut down."));
@@ -54763,7 +55041,7 @@ function createCreatePythonTool(context) {
54763
55041
  * script that nothing can call. Both tools write Python to a file; only this one registers
54764
55042
  * it, and the description has to make that the obvious reading.
54765
55043
  */
54766
- description: 'THE way to create a tool when the user asks for one. Writes a Python tool and registers it, so it becomes callable as py__<name> from the next message onwards. Use this \u2014 not write_to_file \u2014 for anything described as a "tool", and for work awkward in shell commands: parsing, data transformation, anything needing a library. Define a `run` function with type hints; the schema and description are derived from the code, so there is no metadata to keep in sync. The user must approve the source before it is saved.'
55044
+ description: 'THE way to create a tool when the user asks for one. Writes a Python tool and registers it, so it becomes callable as py__<name> from the next message onwards. Use this \u2014 not write_to_file \u2014 for anything described as a "tool", and for work awkward in shell commands: parsing, data transformation, anything needing a library. Define a `run` function with type hints; the schema and description are derived from the code, so there is no metadata to keep in sync. The user must approve the source before it is saved. A tool can call other tools: `import light_code` then `light_code.call_tool("py__other", x=1)` or `light_code.call_tool("server__tool", ...)`. Only other Python tools and MCP tools can be reached that way \u2014 running commands, editing files and creating tools are deliberately out of reach from inside a tool body. The user approves each nested call as they would any other, so use it for composing work rather than for slipping past a prompt.'
54767
55045
  });
54768
55046
  }
54769
55047
  function createUpdatePythonTool(context) {
@@ -54839,7 +55117,7 @@ ${traceback}` : message3, isError: true };
54839
55117
  }
54840
55118
 
54841
55119
  // ../../packages/core/dist/python/workerSource.js
54842
- var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\n\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\nTypeScript side cannot do for itself:\n\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\n and therefore never drifts from the code (CLAUDE.md \xA713);\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\n restarting;\n* running the tool.\n\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\nthem as the tool\'s own output rather than corrupting the channel.\n"""\n\nfrom __future__ import annotations\n\nimport importlib.util\nimport inspect\nimport io\nimport json\nimport re\nimport sys\nimport traceback\nfrom contextlib import redirect_stdout\nfrom pathlib import Path\nfrom typing import Any\n\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\n_MODULES: dict[str, Any] = {}\n\n\ndef _respond(payload: dict[str, Any]) -> None:\n """Write one frame.\n\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\n """\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\n _REAL_STDOUT.flush()\n\n\n_REAL_STDOUT = sys.stdout\n\n\ndef _load(name: str, path: str) -> Any:\n """Imports a tool module from an explicit path, replacing any previous version."""\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\n if spec is None or spec.loader is None:\n raise ImportError(f"could not load {path}")\n module = importlib.util.module_from_spec(spec)\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\n # land in the middle of the JSON-RPC stream.\n with redirect_stdout(io.StringIO()):\n spec.loader.exec_module(module)\n if not hasattr(module, "run"):\n raise AttributeError(f"{path} defines no `run` function")\n _MODULES[name] = module\n return module\n\n\ndef _google_arg_docs(doc: str) -> dict[str, str]:\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\n\n Best-effort by design. A missing description costs the model a hint; a parser that threw\n would cost it the whole tool.\n """\n docs: dict[str, str] = {}\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\n if not match:\n return docs\n for line in match.group(1).splitlines():\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\n if entry:\n docs[entry.group(1)] = entry.group(2).strip()\n return docs\n\n\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\n#: which is lossy but callable.\n_PRIMITIVE_TYPES: dict[Any, str] = {\n str: "string",\n bool: "boolean",\n int: "integer",\n float: "number",\n list: "array",\n dict: "object",\n}\n\n\ndef _fallback_schema(run: Any) -> dict[str, Any]:\n """Derives a schema from bare annotations, for when pydantic is not installed.\n\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\n which is truthy for every value including ``"false"``. Silent, and wrong.\n """\n signature = inspect.signature(run)\n properties: dict[str, Any] = {}\n required: list[str] = []\n\n for name, parameter in signature.parameters.items():\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\n continue\n annotation = parameter.annotation\n # A string annotation appears under `from __future__ import annotations`; resolving\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\n if isinstance(annotation, str):\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\n if parameter.default is parameter.empty:\n required.append(name)\n\n return {"type": "object", "properties": properties, "required": required}\n\n\ndef _schema_for(module: Any) -> dict[str, Any]:\n """Derives the parameter schema from ``run``\'s type hints.\n\n pydantic when available, because it handles unions, defaults, nested models and\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\n """\n run = module.run\n try:\n from pydantic import TypeAdapter\n\n schema = TypeAdapter(run).json_schema()\n properties = schema.get("properties", {})\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\n schema = _fallback_schema(run)\n properties = schema["properties"]\n\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\n for name, description in _google_arg_docs(doc).items():\n if name in properties:\n properties[name]["description"] = description\n\n schema.setdefault("type", "object")\n schema["properties"] = properties\n return schema\n\n\ndef _describe(name: str, path: str) -> dict[str, Any]:\n module = _load(name, path)\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\n # usually documents the parameters.\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\n return {"name": name, "description": description, "schema": _schema_for(module)}\n\n\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\n method = request.get("method")\n params = request.get("params") or {}\n\n if method == "ping":\n return {"ok": True, "python": sys.version}\n\n if method == "describe":\n return _describe(params["name"], params["path"])\n\n if method == "validate":\n # Parsed before importing, so a syntax error is reported as one rather than as\n # whatever the import machinery happens to raise.\n source = Path(params["path"]).read_text(encoding="utf-8")\n compile(source, params["path"], "exec")\n return _describe(params["name"], params["path"])\n\n if method == "call":\n name = params["name"]\n module = _MODULES.get(name)\n if module is None:\n module = _load(name, params["path"])\n # Reloaded when the caller says the file changed, so an edit mid-session takes\n # effect without a restart.\n if params.get("reload"):\n module = _load(name, params["path"])\n\n captured = io.StringIO()\n with redirect_stdout(captured):\n result = module.run(**(params.get("arguments") or {}))\n printed = captured.getvalue()\n return {\n "result": result,\n # Returned rather than discarded: a print is how people debug, and swallowing it\n # makes a misbehaving tool impossible to diagnose from the chat.\n "stdout": printed,\n }\n\n raise ValueError(f"unknown method: {method}")\n\n\ndef main() -> None:\n for line in sys.stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n continue\n\n request_id = request.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\n _respond(\n {\n "id": request_id,\n "ok": False,\n "error": f"{type(error).__name__}: {error}",\n "traceback": traceback.format_exc(),\n }\n )\n\n\nif __name__ == "__main__":\n main()\n';
55120
+ var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\r\n\r\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\r\nTypeScript side cannot do for itself:\r\n\r\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\r\n and therefore never drifts from the code (CLAUDE.md \xA713);\r\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\r\n restarting;\r\n* running the tool.\r\n\r\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\r\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\r\nthem as the tool\'s own output rather than corrupting the channel.\r\n"""\r\n\r\nfrom __future__ import annotations\r\n\r\nimport importlib.util\r\nimport inspect\r\nimport io\r\nimport json\r\nimport re\r\nimport sys\r\nimport traceback\r\nimport types\r\nfrom contextlib import redirect_stdout\r\nfrom pathlib import Path\r\nfrom typing import Any\r\n\r\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\r\n_MODULES: dict[str, Any] = {}\r\n\r\n\r\ndef _respond(payload: dict[str, Any]) -> None:\r\n """Write one frame.\r\n\r\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\r\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\r\n """\r\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\r\n _REAL_STDOUT.flush()\r\n\r\n\r\n_REAL_STDOUT = sys.stdout\r\n_REAL_STDIN = sys.stdin\r\n\r\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\r\n_CALL_DEPTH = 0\r\n_MAX_DEPTH = 4\r\n_CURRENT_TOOL = ""\r\n_CALL_SEQ = 0\r\n\r\n\r\nclass ToolError(RuntimeError):\r\n """A tool this one called came back with a failure."""\r\n\r\n\r\ndef call_tool(name: str, **arguments: Any) -> Any:\r\n """Calls another tool and returns its result.\r\n\r\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\r\n tools can be reached; see the host for why.\r\n\r\n This blocks the worker, which is correct: the tool asked for something and cannot\r\n continue without it. The host may prompt the user before running it, so it can take as\r\n long as a person takes to answer.\r\n """\r\n global _CALL_DEPTH\r\n if _CALL_DEPTH >= _MAX_DEPTH:\r\n raise ToolError(\r\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\r\n "a tool calling itself, or two calling each other"\r\n )\r\n\r\n global _CALL_SEQ\r\n _CALL_SEQ += 1\r\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\r\n # two calls in a row could be handed the same token.\r\n token = f"cb{_CALL_SEQ}"\r\n _CALL_DEPTH += 1\r\n try:\r\n _respond(\r\n {\r\n "callback": token,\r\n "method": "call_tool",\r\n "name": name,\r\n "arguments": arguments,\r\n "caller": _CURRENT_TOOL,\r\n }\r\n )\r\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\r\n # protocol error rather than something to skip, so it is reported rather than ignored.\r\n while True:\r\n line = _REAL_STDIN.readline()\r\n if not line:\r\n raise ToolError("the host closed the connection while waiting for " + name)\r\n line = line.strip()\r\n if not line:\r\n continue\r\n frame = json.loads(line)\r\n\r\n if frame.get("callback") == token:\r\n if frame.get("ok"):\r\n return frame.get("value")\r\n raise ToolError(frame.get("error") or f"{name} failed")\r\n\r\n # An ordinary request, arriving while this tool is blocked.\r\n #\r\n # It happens for real: the tool this one called is *another Python tool*, so the host\r\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\r\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\r\n # out-of-order answer, which the first version did, fails every nested call between\r\n # two Python tools. So it is served here and the wait resumes.\r\n if "method" in frame:\r\n request_id = frame.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n continue\r\n\r\n raise ToolError(\r\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\r\n )\r\n finally:\r\n _CALL_DEPTH -= 1\r\n\r\n\r\ndef _install_helper_module() -> None:\r\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\r\n\r\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\r\n an ordinary Python file that must also be readable, lintable and runnable on its own\r\n terms, and magic names appearing from nowhere break every one of those.\r\n """\r\n if "light_code" in sys.modules:\r\n return\r\n module = types.ModuleType("light_code")\r\n module.call_tool = call_tool # type: ignore[attr-defined]\r\n module.ToolError = ToolError # type: ignore[attr-defined]\r\n sys.modules["light_code"] = module\r\n\r\n\r\ndef _load(name: str, path: str) -> Any:\r\n """Imports a tool module from an explicit path, replacing any previous version."""\r\n _install_helper_module()\r\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\r\n if spec is None or spec.loader is None:\r\n raise ImportError(f"could not load {path}")\r\n module = importlib.util.module_from_spec(spec)\r\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\r\n # land in the middle of the JSON-RPC stream.\r\n with redirect_stdout(io.StringIO()):\r\n spec.loader.exec_module(module)\r\n if not hasattr(module, "run"):\r\n raise AttributeError(f"{path} defines no `run` function")\r\n _MODULES[name] = module\r\n return module\r\n\r\n\r\ndef _google_arg_docs(doc: str) -> dict[str, str]:\r\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\r\n\r\n Best-effort by design. A missing description costs the model a hint; a parser that threw\r\n would cost it the whole tool.\r\n """\r\n docs: dict[str, str] = {}\r\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\r\n if not match:\r\n return docs\r\n for line in match.group(1).splitlines():\r\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\r\n if entry:\r\n docs[entry.group(1)] = entry.group(2).strip()\r\n return docs\r\n\r\n\r\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\r\n#: which is lossy but callable.\r\n_PRIMITIVE_TYPES: dict[Any, str] = {\r\n str: "string",\r\n bool: "boolean",\r\n int: "integer",\r\n float: "number",\r\n list: "array",\r\n dict: "object",\r\n}\r\n\r\n\r\ndef _fallback_schema(run: Any) -> dict[str, Any]:\r\n """Derives a schema from bare annotations, for when pydantic is not installed.\r\n\r\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\r\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\r\n which is truthy for every value including ``"false"``. Silent, and wrong.\r\n """\r\n signature = inspect.signature(run)\r\n properties: dict[str, Any] = {}\r\n required: list[str] = []\r\n\r\n for name, parameter in signature.parameters.items():\r\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\r\n continue\r\n annotation = parameter.annotation\r\n # A string annotation appears under `from __future__ import annotations`; resolving\r\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\r\n if isinstance(annotation, str):\r\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\r\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\r\n if parameter.default is parameter.empty:\r\n required.append(name)\r\n\r\n return {"type": "object", "properties": properties, "required": required}\r\n\r\n\r\ndef _schema_for(module: Any) -> dict[str, Any]:\r\n """Derives the parameter schema from ``run``\'s type hints.\r\n\r\n pydantic when available, because it handles unions, defaults, nested models and\r\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\r\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\r\n """\r\n run = module.run\r\n try:\r\n from pydantic import TypeAdapter\r\n\r\n schema = TypeAdapter(run).json_schema()\r\n properties = schema.get("properties", {})\r\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\r\n schema = _fallback_schema(run)\r\n properties = schema["properties"]\r\n\r\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\r\n for name, description in _google_arg_docs(doc).items():\r\n if name in properties:\r\n properties[name]["description"] = description\r\n\r\n schema.setdefault("type", "object")\r\n schema["properties"] = properties\r\n return schema\r\n\r\n\r\ndef _describe(name: str, path: str) -> dict[str, Any]:\r\n module = _load(name, path)\r\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\r\n # usually documents the parameters.\r\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\r\n return {"name": name, "description": description, "schema": _schema_for(module)}\r\n\r\n\r\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\r\n method = request.get("method")\r\n params = request.get("params") or {}\r\n\r\n if method == "ping":\r\n return {"ok": True, "python": sys.version}\r\n\r\n if method == "describe":\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "validate":\r\n # Parsed before importing, so a syntax error is reported as one rather than as\r\n # whatever the import machinery happens to raise.\r\n source = Path(params["path"]).read_text(encoding="utf-8")\r\n compile(source, params["path"], "exec")\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "call":\r\n name = params["name"]\r\n # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\r\n # callee is the prompt people click through.\r\n global _CURRENT_TOOL\r\n _CURRENT_TOOL = name\r\n module = _MODULES.get(name)\r\n if module is None:\r\n module = _load(name, params["path"])\r\n # Reloaded when the caller says the file changed, so an edit mid-session takes\r\n # effect without a restart.\r\n if params.get("reload"):\r\n module = _load(name, params["path"])\r\n\r\n captured = io.StringIO()\r\n with redirect_stdout(captured):\r\n result = module.run(**(params.get("arguments") or {}))\r\n printed = captured.getvalue()\r\n return {\r\n "result": result,\r\n # Returned rather than discarded: a print is how people debug, and swallowing it\r\n # makes a misbehaving tool impossible to diagnose from the chat.\r\n "stdout": printed,\r\n }\r\n\r\n raise ValueError(f"unknown method: {method}")\r\n\r\n\r\ndef main() -> None:\r\n for line in sys.stdin:\r\n line = line.strip()\r\n if not line:\r\n continue\r\n try:\r\n request = json.loads(line)\r\n except json.JSONDecodeError:\r\n continue\r\n\r\n request_id = request.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\r\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n\r\n\r\nif __name__ == "__main__":\r\n main()\r\n';
54843
55121
 
54844
55122
  // ../../packages/core/dist/python/manager.js
54845
55123
  var PythonManager = class {
@@ -54928,7 +55206,15 @@ var PythonManager = class {
54928
55206
  cwd: this.options.workspaceRoot,
54929
55207
  env: env2,
54930
55208
  logger: this.options.logger,
54931
- timeoutMs: this.timeoutMs
55209
+ timeoutMs: this.timeoutMs,
55210
+ /*
55211
+ * Passed through rather than resolved here.
55212
+ *
55213
+ * The manager has no registry and no approval gate; the host has both. Threading the
55214
+ * function means the rules are decided once, where the information is, instead of this
55215
+ * file growing an opinion about which tools a tool may call.
55216
+ */
55217
+ ...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
54932
55218
  });
54933
55219
  await this.refresh();
54934
55220
  this.ready = true;
@@ -55094,7 +55380,15 @@ var PythonManager = class {
55094
55380
  cwd: workspaceRoot,
55095
55381
  env: env2,
55096
55382
  logger: this.options.logger,
55097
- timeoutMs: this.timeoutMs
55383
+ timeoutMs: this.timeoutMs,
55384
+ /*
55385
+ * Passed through rather than resolved here.
55386
+ *
55387
+ * The manager has no registry and no approval gate; the host has both. Threading the
55388
+ * function means the rules are decided once, where the information is, instead of this
55389
+ * file growing an opinion about which tools a tool may call.
55390
+ */
55391
+ ...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
55098
55392
  });
55099
55393
  await this.refresh();
55100
55394
  this.ready = true;
@@ -58488,17 +58782,17 @@ var WebviewApprovalGate = class {
58488
58782
  // ../../packages/core/dist/platform/node/filesystem.js
58489
58783
  import fs16 from "node:fs/promises";
58490
58784
  var NodeFileSystem = class {
58491
- async readFile(path30) {
58492
- return fs16.readFile(path30, "utf8");
58785
+ async readFile(path31) {
58786
+ return fs16.readFile(path31, "utf8");
58493
58787
  }
58494
- async readBytes(path30) {
58495
- return fs16.readFile(path30);
58788
+ async readBytes(path31) {
58789
+ return fs16.readFile(path31);
58496
58790
  }
58497
- async readBytesSlice(path30, start, end) {
58791
+ async readBytesSlice(path31, start, end) {
58498
58792
  const length = Math.max(0, end - start);
58499
58793
  if (length === 0)
58500
58794
  return Buffer.alloc(0);
58501
- const handle = await fs16.open(path30, "r");
58795
+ const handle = await fs16.open(path31, "r");
58502
58796
  try {
58503
58797
  const buffer = Buffer.alloc(length);
58504
58798
  const { bytesRead } = await handle.read(buffer, 0, length, start);
@@ -58507,11 +58801,11 @@ var NodeFileSystem = class {
58507
58801
  await handle.close();
58508
58802
  }
58509
58803
  }
58510
- async writeFile(path30, contents) {
58511
- await fs16.writeFile(path30, contents, "utf8");
58804
+ async writeFile(path31, contents) {
58805
+ await fs16.writeFile(path31, contents, "utf8");
58512
58806
  }
58513
- async stat(path30) {
58514
- const stat = await fs16.lstat(path30);
58807
+ async stat(path31) {
58808
+ const stat = await fs16.lstat(path31);
58515
58809
  return {
58516
58810
  size: stat.size,
58517
58811
  mtimeMs: stat.mtimeMs,
@@ -58520,8 +58814,8 @@ var NodeFileSystem = class {
58520
58814
  isSymbolicLink: stat.isSymbolicLink()
58521
58815
  };
58522
58816
  }
58523
- async readdir(path30) {
58524
- const entries = await fs16.readdir(path30, { withFileTypes: true });
58817
+ async readdir(path31) {
58818
+ const entries = await fs16.readdir(path31, { withFileTypes: true });
58525
58819
  return entries.map((entry) => ({
58526
58820
  name: entry.name,
58527
58821
  isFile: entry.isFile(),
@@ -58529,16 +58823,16 @@ var NodeFileSystem = class {
58529
58823
  isSymbolicLink: entry.isSymbolicLink()
58530
58824
  }));
58531
58825
  }
58532
- async exists(path30) {
58826
+ async exists(path31) {
58533
58827
  try {
58534
- await fs16.access(path30);
58828
+ await fs16.access(path31);
58535
58829
  return true;
58536
58830
  } catch {
58537
58831
  return false;
58538
58832
  }
58539
58833
  }
58540
- async mkdir(path30) {
58541
- await fs16.mkdir(path30, { recursive: true });
58834
+ async mkdir(path31) {
58835
+ await fs16.mkdir(path31, { recursive: true });
58542
58836
  }
58543
58837
  };
58544
58838
 
@@ -58783,6 +59077,8 @@ async function toSummary(profile, secrets) {
58783
59077
  ...profile.auth.type === "apiKey" && describeSecretRef(profile.auth.apiKeyRef).kind === "env" ? { apiKeyEnvVar: describeSecretRef(profile.auth.apiKeyRef).envVar } : {},
58784
59078
  // Not a secret: a command describes how to *get* a credential. The token it produces never
58785
59079
  // crosses the bridge, and a form cannot edit what it is never shown.
59080
+ // References only — a store key or a variable name, never the credential (invariant 7).
59081
+ ...profile.auth.type === "header" ? { authHeaders: profile.auth.headers } : {},
58786
59082
  ...profile.auth.type === "tokenCommand" ? {
58787
59083
  /*
58788
59084
  * `env` is dropped on the way out, deliberately.
@@ -58840,6 +59136,62 @@ function wireChatBridge(services) {
58840
59136
  workspaceRoot,
58841
59137
  storageDir,
58842
59138
  logger,
59139
+ /*
59140
+ * Lets one Python tool call another, or an MCP tool.
59141
+ *
59142
+ * Here rather than in the Python package because this is the only place that can see all
59143
+ * three things the decision needs: the registry, the approval gate, and whether there is
59144
+ * anybody present to answer a prompt. `callPolicy.ts` holds the rule and the reasoning.
59145
+ */
59146
+ callTool: async (name, args, caller) => {
59147
+ if (!pythonNestedCallsAllowed) {
59148
+ throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
59149
+ }
59150
+ const registry2 = currentToolRegistry();
59151
+ const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
59152
+ if (tool === void 0) {
59153
+ throw new Error(`There is no tool called "${name}". Settings \u2192 Tools lists everything callable; an MCP tool is named with its server, like \`filesystem__read_file\`.`);
59154
+ }
59155
+ if (!mayPythonToolCall(tool.name, tool.group))
59156
+ throw new Error(PYTHON_CALL_DENIED);
59157
+ const context = pythonNestedContext;
59158
+ if (context === void 0) {
59159
+ throw new Error("No turn is in progress, so there is nothing to run this against.");
59160
+ }
59161
+ let preview;
59162
+ try {
59163
+ preview = await tool.preview?.(args, context) ?? {
59164
+ kind: "text",
59165
+ text: `${tool.name}(${JSON.stringify(args, null, 2)})`
59166
+ };
59167
+ } catch (error51) {
59168
+ preview = {
59169
+ kind: "text",
59170
+ text: `${tool.name}(${JSON.stringify(args, null, 2)})
59171
+
59172
+ Could not preview this: ${error51 instanceof Error ? error51.message : String(error51)}`
59173
+ };
59174
+ }
59175
+ const decision = await approvalGate.requestApproval({
59176
+ id: `py-nested-${String(Date.now())}-${tool.name}`,
59177
+ toolName: tool.name,
59178
+ group: tool.group,
59179
+ preview: {
59180
+ ...preview,
59181
+ // Says who is asking. "Allow filesystem__write_file?" with no indication of who wants
59182
+ // it is exactly the prompt people click through.
59183
+ ...preview.kind === "text" ? { text: `${describeNestedCall(caller, tool.name)}
59184
+
59185
+ ${preview.text}` } : {}
59186
+ }
59187
+ });
59188
+ if (decision !== "approve")
59189
+ throw new Error(`The user did not allow "${tool.name}" to run.`);
59190
+ const result = await tool.execute(args, context);
59191
+ if (result.isError === true)
59192
+ throw new Error(String(result.content));
59193
+ return result.content;
59194
+ },
58843
59195
  // Read at worker spawn, so a changed variable applies to the next worker rather than being
58844
59196
  // frozen at construction. Added to the allowlist in minimalPythonEnv, never a way past it.
58845
59197
  ...services.sessionEnv !== void 0 ? { sessionEnv: services.sessionEnv } : {},
@@ -58859,6 +59211,7 @@ function wireChatBridge(services) {
58859
59211
  void postPython();
58860
59212
  void postSchedules();
58861
59213
  void postTools();
59214
+ void postDatasetStatus();
58862
59215
  }
58863
59216
  });
58864
59217
  const defaultSkillsDir = workspaceRoot !== void 0 ? path23.join(workspaceRoot, ".lightcode", "skills") : void 0;
@@ -59078,6 +59431,8 @@ function wireChatBridge(services) {
59078
59431
  let backgroundRun = false;
59079
59432
  let userTurnRunning = false;
59080
59433
  let scheduledRunInFlight;
59434
+ let pythonNestedContext;
59435
+ let pythonNestedCallsAllowed = false;
59081
59436
  const MENTION_SCAN_LIMIT = 2e3;
59082
59437
  const MENTION_RESULT_LIMIT = 30;
59083
59438
  let scheduleToolAccess;
@@ -59310,6 +59665,9 @@ function wireChatBridge(services) {
59310
59665
  let cachedProgrammingProfileId;
59311
59666
  let cachedOffice = {};
59312
59667
  let cachedMail = {};
59668
+ let cachedDatasets = [];
59669
+ let datasetSummaryForPrompt = [];
59670
+ let cachedPythonEnabled = false;
59313
59671
  const mailStore = new MailStore(storageDir);
59314
59672
  let mailBusy = false;
59315
59673
  let mailTimer;
@@ -59342,6 +59700,12 @@ function wireChatBridge(services) {
59342
59700
  cachedProgrammingProfileId = config2.programmingProfileId;
59343
59701
  cachedOffice = config2.office ?? {};
59344
59702
  cachedMail = config2.mail ?? {};
59703
+ cachedDatasets = config2.datasets ?? [];
59704
+ cachedPythonEnabled = config2.python?.dynamicTools === "on";
59705
+ datasetSummaryForPrompt = await Promise.all(cachedDatasets.map(async (dataset) => ({
59706
+ name: dataset.name,
59707
+ records: (await new DatasetStore(storageDir, dataset.id).load()).length
59708
+ })));
59345
59709
  cachedModeId = config2.modeId;
59346
59710
  cachedMaxIterations = config2.maxIterations ?? 25;
59347
59711
  cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
@@ -59425,6 +59789,7 @@ function wireChatBridge(services) {
59425
59789
  postMcp();
59426
59790
  void postSchedules();
59427
59791
  void postTools();
59792
+ void postDatasetStatus();
59428
59793
  scheduleDocsReindex("MCP tools changed");
59429
59794
  }
59430
59795
  }, logger, () => cachedApprovals.allowedTools ?? [], () => cachedToolTimeoutSeconds);
@@ -59442,7 +59807,7 @@ function wireChatBridge(services) {
59442
59807
  platform: process.platform === "win32" ? "win32" : "posix"
59443
59808
  });
59444
59809
  }
59445
- function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic) {
59810
+ function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic, datasetSemanticForTools) {
59446
59811
  const combined = new ToolRegistry();
59447
59812
  for (const tool of builtinTools.list())
59448
59813
  combined.register(tool);
@@ -59529,6 +59894,16 @@ function wireChatBridge(services) {
59529
59894
  if (codebase !== void 0) {
59530
59895
  combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
59531
59896
  }
59897
+ if (cachedDatasets.length > 0) {
59898
+ combined.register(createSearchDataTool({
59899
+ load: async () => Promise.all(cachedDatasets.map(async (dataset) => ({
59900
+ id: dataset.id,
59901
+ name: dataset.name,
59902
+ records: await new DatasetStore(storageDir, dataset.id).load()
59903
+ }))),
59904
+ ...datasetSemanticForTools !== void 0 ? { semantic: datasetSemanticForTools } : {}
59905
+ }));
59906
+ }
59532
59907
  if (officeSupported() && (cachedOffice.excel === true || cachedOffice.outlook === true)) {
59533
59908
  const officeOptions = { bridge: office() };
59534
59909
  if (cachedOffice.excel === true) {
@@ -59804,6 +60179,9 @@ function wireChatBridge(services) {
59804
60179
  expertAvailable: expertCliInfo !== void 0,
59805
60180
  // Named only when there is an index to prefer.
59806
60181
  mailIndexed: cachedMail.enabled === true && cachedOffice.outlook === true,
60182
+ // Counted here rather than in the prompt builder, which has no filesystem.
60183
+ datasets: datasetSummaryForPrompt,
60184
+ canWriteCollectors: cachedPythonEnabled,
59807
60185
  /*
59808
60186
  * Either the whole list or a count and an instruction to search — never both, and
59809
60187
  * never neither. `renderSkillsHintForPrompt` explains why the count stays.
@@ -59873,6 +60251,8 @@ function wireChatBridge(services) {
59873
60251
  // lives in the VSIX, so resolving it is a host concern (§4).
59874
60252
  ...ripgrepPath !== void 0 ? { ripgrepPath } : {}
59875
60253
  };
60254
+ pythonNestedContext = toolContext;
60255
+ pythonNestedCallsAllowed = schedule === void 0;
59876
60256
  const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
59877
60257
  const messageText = attachMentions(text, mentions);
59878
60258
  const turnOptions = {
@@ -59954,7 +60334,17 @@ function wireChatBridge(services) {
59954
60334
  * is frequently a local Qdrant while the code goes to a shared cluster — mail is the
59955
60335
  * corpus people most want kept off a team's infrastructure.
59956
60336
  */
59957
- mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0
60337
+ mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0,
60338
+ /*
60339
+ * Datasets share one collection, resolved against whichever store `retrieval.stores.data`
60340
+ * names — the same per-corpus routing §12e added, for the same reason: somebody's own
60341
+ * collected data is frequently the corpus they most want kept off a shared cluster.
60342
+ */
60343
+ await (async () => {
60344
+ const collection = datasetCollectionName(config2);
60345
+ const search2 = await resolveDatasetSearch(config2);
60346
+ return collection !== void 0 && search2 !== void 0 && embedder !== void 0 ? { searcher: search2.searcher, embedder, collection } : void 0;
60347
+ })()
59958
60348
  );
59959
60349
  const turnRegistry = schedule !== void 0 ? registryForSchedule(fullRegistry.list(), schedule) : fullRegistry;
59960
60350
  turnOptions.timeoutForTool = toolTimeout;
@@ -60074,6 +60464,21 @@ function wireChatBridge(services) {
60074
60464
  }
60075
60465
  };
60076
60466
  }
60467
+ if (input.authType === "header") {
60468
+ const headers = (input.authHeaders ?? []).map((header) => ({
60469
+ name: header.name.trim(),
60470
+ valueRef: header.valueRef.trim(),
60471
+ ...header.prefix !== void 0 && header.prefix.length > 0 ? { prefix: header.prefix } : {}
60472
+ })).filter((header) => header.name.length > 0 && header.valueRef.length > 0);
60473
+ const stored = await Promise.all(headers.map(async (header, index) => {
60474
+ if (describeSecretRef(header.valueRef).kind === "env")
60475
+ return header;
60476
+ const ref = `profile:${id}:header:${String(index)}`;
60477
+ await secrets.set(ref, header.valueRef);
60478
+ return { ...header, valueRef: ref };
60479
+ }));
60480
+ return stored.length > 0 ? { type: "header", headers: stored } : { type: "none" };
60481
+ }
60077
60482
  if (input.authType === "tokenCommand") {
60078
60483
  if (services.executableAuthRefusal !== void 0)
60079
60484
  throw new Error(services.executableAuthRefusal);
@@ -60699,8 +61104,8 @@ function wireChatBridge(services) {
60699
61104
  limit: limits.limit,
60700
61105
  previewChars: limits.previewChars
60701
61106
  });
60702
- for (const path30 of answer.skipped ?? [])
60703
- skipped.add(path30);
61107
+ for (const path31 of answer.skipped ?? [])
61108
+ skipped.add(path31);
60704
61109
  return { messages: answer.messages, truncated: answer.truncated };
60705
61110
  },
60706
61111
  ...embedder !== void 0 && search !== void 0 && collection !== void 0 ? {
@@ -60732,6 +61137,209 @@ function wireChatBridge(services) {
60732
61137
  endIndexing("mail");
60733
61138
  }
60734
61139
  }
61140
+ const datasetTimers = /* @__PURE__ */ new Map();
61141
+ const datasetBusy = /* @__PURE__ */ new Set();
61142
+ const datasetResults = /* @__PURE__ */ new Map();
61143
+ function datasetStoreFor(id) {
61144
+ return new DatasetStore(storageDir, id);
61145
+ }
61146
+ function datasetCollectionName(config2) {
61147
+ const base = codebaseIndexName(config2);
61148
+ return base === void 0 ? void 0 : `${base}-data`;
61149
+ }
61150
+ async function resolveDatasetSearch(config2, dataset) {
61151
+ const wanted = dataset?.storeId ?? storeIdFor("data", config2);
61152
+ return resolveSearch(config2, wanted);
61153
+ }
61154
+ async function datasetSemantic(config2, dataset) {
61155
+ const collection = datasetCollectionName(config2);
61156
+ const search = await resolveDatasetSearch(config2, dataset);
61157
+ const embedder = await resolveEmbedder(config2);
61158
+ if (collection === void 0 || search === void 0 || embedder === void 0)
61159
+ return void 0;
61160
+ return {
61161
+ embedder,
61162
+ collection,
61163
+ writer: createVectorIndexWriter(httpClient, search.store, await vectorStoreConnectionFor(search.store, search.id)),
61164
+ searcher: search.searcher
61165
+ };
61166
+ }
61167
+ async function runDatasetSync(id, reason) {
61168
+ if (datasetBusy.has(id))
61169
+ return;
61170
+ const config2 = await loadSettings();
61171
+ const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
61172
+ if (dataset === void 0)
61173
+ return;
61174
+ datasetBusy.add(id);
61175
+ const signal = beginIndexing(`dataset:${id}`);
61176
+ reportIndexing("dataset", `Syncing ${dataset.name}`, { detail: `via ${dataset.toolName}` });
61177
+ try {
61178
+ const semantic = await datasetSemantic(config2, dataset);
61179
+ const result = await syncDataset({
61180
+ datasetId: id,
61181
+ store: datasetStoreFor(id),
61182
+ signal,
61183
+ onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
61184
+ ...dataset.retentionDays !== void 0 ? { retentionDays: dataset.retentionDays } : {},
61185
+ ...semantic !== void 0 ? { semantic: { embedder: semantic.embedder, writer: semantic.writer, collection: semantic.collection } } : {},
61186
+ /*
61187
+ * The collector runs through the ordinary Python tool path, so it is the same code that
61188
+ * validated it, the same worker, the same timeout. A second execution path would be a
61189
+ * second thing to keep in step with tool approval.
61190
+ */
61191
+ collect: async (since2) => {
61192
+ const registry2 = currentToolRegistry();
61193
+ const tool = registry2.get(dataset.toolName) ?? registry2.get(`py__${dataset.toolName}`);
61194
+ if (tool === void 0) {
61195
+ 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.`);
61196
+ }
61197
+ const args = { ...dataset.arguments ?? {}, ...since2 === void 0 ? {} : { since: since2 } };
61198
+ const output = await tool.execute(args, { signal });
61199
+ if (output.isError === true)
61200
+ throw new Error(String(output.content));
61201
+ try {
61202
+ return JSON.parse(typeof output.content === "string" ? output.content : JSON.stringify(output.content));
61203
+ } catch {
61204
+ 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.");
61205
+ }
61206
+ }
61207
+ });
61208
+ 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.`;
61209
+ datasetResults.set(id, { detail, failed: false, at: Date.now() });
61210
+ reportIndexing("dataset", "Finished", { detail, running: false });
61211
+ } catch (error51) {
61212
+ const stopped = signal.aborted;
61213
+ const detail = stopped ? "Stopped." : error51 instanceof Error ? error51.message : String(error51);
61214
+ datasetResults.set(id, { detail, failed: !stopped, at: Date.now() });
61215
+ if (!stopped)
61216
+ logger.warn(`dataset "${dataset.name}" sync failed: ${detail}`);
61217
+ reportIndexing("dataset", stopped ? "Stopped" : "Failed", { detail, running: false });
61218
+ } finally {
61219
+ datasetBusy.delete(id);
61220
+ endIndexing(`dataset:${id}`);
61221
+ await postDatasetStatus();
61222
+ }
61223
+ }
61224
+ async function handleClearDataset(id, resync) {
61225
+ if (datasetBusy.has(id))
61226
+ return;
61227
+ const config2 = await loadSettings();
61228
+ const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
61229
+ if (dataset === void 0)
61230
+ return;
61231
+ datasetBusy.add(id);
61232
+ const signal = beginIndexing(`dataset:${id}`);
61233
+ reportIndexing("dataset", `Clearing ${dataset.name}`);
61234
+ try {
61235
+ const semantic = await datasetSemantic(config2, dataset);
61236
+ const { removed } = await clearDataset({
61237
+ datasetId: id,
61238
+ store: datasetStoreFor(id),
61239
+ signal,
61240
+ onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
61241
+ ...semantic !== void 0 ? { semantic: { writer: semantic.writer, collection: semantic.collection } } : {}
61242
+ });
61243
+ const detail = `Cleared ${String(removed)} record(s).`;
61244
+ datasetResults.set(id, { detail, failed: false, at: Date.now() });
61245
+ reportIndexing("dataset", "Finished", { detail, running: false });
61246
+ } catch (error51) {
61247
+ const detail = error51 instanceof Error ? error51.message : String(error51);
61248
+ datasetResults.set(id, { detail, failed: true, at: Date.now() });
61249
+ logger.warn(`dataset clear failed: ${detail}`);
61250
+ reportIndexing("dataset", "Failed", { detail, running: false });
61251
+ } finally {
61252
+ datasetBusy.delete(id);
61253
+ endIndexing(`dataset:${id}`);
61254
+ await postDatasetStatus();
61255
+ }
61256
+ if (resync)
61257
+ await runDatasetSync(id, "rebuild");
61258
+ }
61259
+ function reconcileDatasetTimers(config2) {
61260
+ for (const timer of datasetTimers.values())
61261
+ clearInterval(timer);
61262
+ datasetTimers.clear();
61263
+ for (const dataset of config2.datasets ?? []) {
61264
+ const minutes = dataset.syncMinutes ?? 0;
61265
+ if (dataset.enabled === false || minutes <= 0)
61266
+ continue;
61267
+ const timer = setInterval(() => void runDatasetSync(dataset.id, "scheduled"), minutes * 60 * 1e3);
61268
+ timer.unref?.();
61269
+ datasetTimers.set(dataset.id, timer);
61270
+ }
61271
+ }
61272
+ async function postDatasetStatus() {
61273
+ const config2 = (await configManager.load()).config;
61274
+ const datasets = config2.datasets ?? [];
61275
+ const collection = datasetCollectionName(config2);
61276
+ const embedder = await resolveEmbedder(config2).catch(() => void 0);
61277
+ const entries = await Promise.all(datasets.map(async (dataset) => {
61278
+ const store = datasetStoreFor(dataset.id);
61279
+ const records = await store.load();
61280
+ const times = records.map((record2) => record2.timestamp).filter((at) => at !== void 0);
61281
+ const search = await resolveDatasetSearch(config2, dataset).catch(() => void 0);
61282
+ return {
61283
+ ...dataset,
61284
+ records: records.length,
61285
+ sizeBytes: await store.sizeBytes(),
61286
+ ...times.length > 0 ? { oldest: Math.min(...times), newest: Math.max(...times) } : {},
61287
+ ...await store.lastSyncedAt() !== void 0 ? { lastSyncedAt: await store.lastSyncedAt() } : {},
61288
+ busy: datasetBusy.has(dataset.id),
61289
+ ...datasetResults.get(dataset.id) !== void 0 ? {
61290
+ lastResult: datasetResults.get(dataset.id).detail,
61291
+ lastFailed: datasetResults.get(dataset.id).failed,
61292
+ lastAttemptAt: datasetResults.get(dataset.id).at
61293
+ } : {},
61294
+ storeLabel: search?.store.label ?? "none"
61295
+ };
61296
+ }));
61297
+ post({
61298
+ type: "datasetStatus",
61299
+ datasets: entries,
61300
+ // Said plainly, because a dataset with no embedder still syncs and still searches — on words
61301
+ // rather than meaning — and someone seeing results would otherwise assume it is semantic.
61302
+ semantic: collection !== void 0 && embedder !== void 0,
61303
+ /*
61304
+ * Python tools and MCP tools, selected by what they *are* rather than by group.
61305
+ *
61306
+ * Filtering on `group` was wrong and showed only the built-ins: a Python tool is registered
61307
+ * as `command`, because it runs code, and an MCP tool as `mcp`. Those two groups also hold
61308
+ * `execute_command` and the tool-authoring tools, which are not data sources — so the test
61309
+ * is the `py__` prefix and the mcp group, not a permission category. Reported as the picker
61310
+ * listing only built-in tools.
61311
+ */
61312
+ stores: Object.entries(config2.vectorStores ?? {}).map(([id, store]) => ({ id, label: store.label })),
61313
+ // Resolved here, where the fallback chain lives. See the note on the message.
61314
+ defaultStoreLabel: (await resolveDatasetSearch(config2).catch(() => void 0))?.store.label ?? "none",
61315
+ tools: currentToolRegistry().list().filter((tool) => tool.name.startsWith("py__") || tool.group === "mcp").map((tool) => ({
61316
+ name: tool.name,
61317
+ description: tool.description,
61318
+ // Grouped in the picker, because "which of these is mine?" is the first question with
61319
+ // forty MCP tools in the list.
61320
+ kind: tool.name.startsWith("py__") ? "python" : "mcp"
61321
+ })),
61322
+ guidance: COLLECTOR_TOOL_GUIDANCE
61323
+ });
61324
+ }
61325
+ async function handleSaveDataset(dataset) {
61326
+ const { config: config2 } = await configManager.load();
61327
+ const existing = config2.datasets ?? [];
61328
+ const next = existing.some((entry) => entry.id === dataset.id) ? existing.map((entry) => entry.id === dataset.id ? dataset : entry) : [...existing, dataset];
61329
+ await configManager.save("user", { datasets: next });
61330
+ reconcileDatasetTimers((await configManager.load()).config);
61331
+ await postDatasetStatus();
61332
+ }
61333
+ async function handleDeleteDataset(id) {
61334
+ const { config: config2 } = await configManager.load();
61335
+ await handleClearDataset(id, false);
61336
+ await configManager.save("user", {
61337
+ datasets: (config2.datasets ?? []).filter((entry) => entry.id !== id)
61338
+ });
61339
+ datasetResults.delete(id);
61340
+ reconcileDatasetTimers((await configManager.load()).config);
61341
+ await postDatasetStatus();
61342
+ }
60735
61343
  function reconcileMailTimer(config2) {
60736
61344
  if (mailTimer !== void 0) {
60737
61345
  clearInterval(mailTimer);
@@ -60781,9 +61389,9 @@ function wireChatBridge(services) {
60781
61389
  });
60782
61390
  const all = result.folders.map((entry) => entry.path);
60783
61391
  const wanted = new Set(chosen);
60784
- for (const path30 of all) {
60785
- if (chosen.some((root) => path30 === root || path30.startsWith(`${root}\\`)))
60786
- wanted.add(path30);
61392
+ for (const path31 of all) {
61393
+ if (chosen.some((root) => path31 === root || path31.startsWith(`${root}\\`)))
61394
+ wanted.add(path31);
60787
61395
  }
60788
61396
  return [...wanted];
60789
61397
  } catch {
@@ -61000,6 +61608,7 @@ function wireChatBridge(services) {
61000
61608
  });
61001
61609
  const config2 = await loadSettings();
61002
61610
  reconcileMailTimer(config2);
61611
+ reconcileDatasetTimers(config2);
61003
61612
  await postMailStatus();
61004
61613
  if (config2.mail?.enabled === true)
61005
61614
  void runMailSync("just enabled");
@@ -61278,6 +61887,28 @@ function wireChatBridge(services) {
61278
61887
  const { config: config2 } = await configManager.load();
61279
61888
  const search = await resolveSearch(config2);
61280
61889
  const embedder = await resolveEmbedder(config2);
61890
+ if (target === "data") {
61891
+ const datasets = config2.datasets ?? [];
61892
+ const collection = datasetCollectionName(config2);
61893
+ const dataSearch = await resolveDatasetSearch(config2);
61894
+ const tool2 = createSearchDataTool({
61895
+ load: async () => Promise.all(datasets.map(async (dataset) => ({
61896
+ id: dataset.id,
61897
+ name: dataset.name,
61898
+ records: await new DatasetStore(storageDir, dataset.id).load()
61899
+ }))),
61900
+ ...collection !== void 0 && dataSearch !== void 0 && embedder !== void 0 ? { semantic: { searcher: dataSearch.searcher, embedder, collection } } : {}
61901
+ });
61902
+ const result2 = await tool2.execute({ query, limit: 25 }, {});
61903
+ post({
61904
+ type: "searchProbe",
61905
+ target,
61906
+ query,
61907
+ text: result2.content,
61908
+ ...result2.isError === true ? { error: "The search failed." } : {}
61909
+ });
61910
+ return;
61911
+ }
61281
61912
  if (target === "mail") {
61282
61913
  const collection = mailCollectionName(config2);
61283
61914
  const mailSearch = await resolveMailSearch(config2);
@@ -61586,6 +62217,9 @@ function wireChatBridge(services) {
61586
62217
  ...saved.uvPath !== void 0 ? { uvPath: saved.uvPath } : {},
61587
62218
  ...saved.toolsDir !== void 0 ? { toolsDir: saved.toolsDir } : {},
61588
62219
  ...saved.venvPath !== void 0 ? { venvPath: saved.venvPath } : {},
62220
+ ...saved.interpreterPath !== void 0 ? { interpreterPath: saved.interpreterPath } : {},
62221
+ // Sent so nothing the form cannot edit is invisible *and* silently rewritten.
62222
+ ...saved.extraIndexUrls !== void 0 ? { extraIndexUrls: saved.extraIndexUrls } : {},
61589
62223
  ...saved.indexUrl !== void 0 ? { indexUrl: saved.indexUrl } : {},
61590
62224
  ...saved.offline !== void 0 ? { offline: saved.offline } : {},
61591
62225
  ...saved.timeoutSeconds !== void 0 ? { timeoutSeconds: saved.timeoutSeconds } : {},
@@ -61597,16 +62231,26 @@ function wireChatBridge(services) {
61597
62231
  }
61598
62232
  async function handleSetPython(input) {
61599
62233
  try {
62234
+ const existing = (await configManager.load()).config.python ?? {};
61600
62235
  await configManager.save("user", {
61601
62236
  python: {
62237
+ ...existing,
61602
62238
  dynamicTools: input.dynamicTools,
61603
- ...input.uvPath !== void 0 && input.uvPath.length > 0 ? { uvPath: input.uvPath } : {},
62239
+ ...input.uvPath !== void 0 ? input.uvPath.length > 0 ? { uvPath: input.uvPath } : { uvPath: void 0 } : {},
61604
62240
  // Absent rather than empty when cleared, so the manager falls back to
61605
62241
  // `.lightcode/tools` instead of resolving an empty string against the workspace.
61606
- ...input.toolsDir !== void 0 && input.toolsDir.trim().length > 0 ? { toolsDir: input.toolsDir.trim() } : {},
61607
- ...input.venvPath !== void 0 && input.venvPath.trim().length > 0 ? { venvPath: input.venvPath.trim() } : {},
62242
+ ...input.toolsDir !== void 0 ? input.toolsDir.trim().length > 0 ? { toolsDir: input.toolsDir.trim() } : { toolsDir: void 0 } : {},
62243
+ /*
62244
+ * Cleared means cleared, which is why each of these deletes rather than omitting.
62245
+ *
62246
+ * With the spread of `existing` above, omitting a blank field would *keep* the old
62247
+ * value — so emptying the box would appear to do nothing. The three-way distinction
62248
+ * matters: a field the form did not send is kept, a field it sent empty is removed.
62249
+ */
62250
+ ...input.venvPath !== void 0 ? input.venvPath.trim().length > 0 ? { venvPath: input.venvPath.trim() } : { venvPath: void 0 } : {},
62251
+ ...input.interpreterPath !== void 0 ? input.interpreterPath.trim().length > 0 ? { interpreterPath: input.interpreterPath.trim() } : { interpreterPath: void 0 } : {},
61608
62252
  ...input.timeoutSeconds !== void 0 ? { timeoutSeconds: input.timeoutSeconds } : {},
61609
- ...input.indexUrl !== void 0 && input.indexUrl.length > 0 ? { indexUrl: input.indexUrl } : {},
62253
+ ...input.indexUrl !== void 0 ? input.indexUrl.length > 0 ? { indexUrl: input.indexUrl } : { indexUrl: void 0 } : {},
61610
62254
  ...input.offline !== void 0 ? { offline: input.offline } : {}
61611
62255
  }
61612
62256
  });
@@ -62469,6 +63113,7 @@ function wireChatBridge(services) {
62469
63113
  } else if (message3.type === "requestMailStatus") {
62470
63114
  void loadSettings().then((config2) => {
62471
63115
  reconcileMailTimer(config2);
63116
+ reconcileDatasetTimers(config2);
62472
63117
  return postMailStatus();
62473
63118
  });
62474
63119
  } else if (message3.type === "saveMailSettings") {
@@ -62484,6 +63129,16 @@ function wireChatBridge(services) {
62484
63129
  void handleClearTeamSkills();
62485
63130
  } else if (message3.type === "refreshMail") {
62486
63131
  void handleRefreshMail(message3.days);
63132
+ } else if (message3.type === "requestDatasetStatus") {
63133
+ void postDatasetStatus();
63134
+ } else if (message3.type === "saveDataset") {
63135
+ void handleSaveDataset(message3.dataset);
63136
+ } else if (message3.type === "deleteDataset") {
63137
+ void handleDeleteDataset(message3.id);
63138
+ } else if (message3.type === "syncDataset") {
63139
+ void runDatasetSync(message3.id, "manual");
63140
+ } else if (message3.type === "clearDataset") {
63141
+ void handleClearDataset(message3.id, message3.resync === true);
62487
63142
  } else if (message3.type === "clearMailIndex") {
62488
63143
  void handleClearMailIndex(message3.resync === true);
62489
63144
  } else if (message3.type === "saveSkillsAlias") {
@@ -63888,10 +64543,10 @@ function readSmall(raw, params) {
63888
64543
  const end = params.limit !== void 0 ? start + params.limit : lines.length;
63889
64544
  return number4(lines.slice(start, end), start + 1);
63890
64545
  }
63891
- async function readLarge(fs24, realPath, params, size) {
64546
+ async function readLarge(fs25, realPath, params, size) {
63892
64547
  const human = formatBytes(size);
63893
64548
  if (params.tail !== void 0) {
63894
- const part = await readTail(fs24, realPath, size, params.tail);
64549
+ const part = await readTail(fs25, realPath, size, params.tail);
63895
64550
  return [
63896
64551
  `${human} file \u2014 last ${String(part.lines.length)} lines.`,
63897
64552
  /*
@@ -63906,7 +64561,7 @@ async function readLarge(fs24, realPath, params, size) {
63906
64561
  }
63907
64562
  if (params.offset !== void 0) {
63908
64563
  const limit = params.limit ?? DEFAULT_LARGE_LIMIT;
63909
- const part = await readLineWindow(fs24, realPath, size, params.offset, limit);
64564
+ const part = await readLineWindow(fs25, realPath, size, params.offset, limit);
63910
64565
  const shown = part.lines.length;
63911
64566
  return [
63912
64567
  `${human} file \u2014 lines ${String(params.offset)}\u2013${String(params.offset + shown - 1)}${part.hasMoreAfter ? ", more follows" : " (end of file)"}.`,
@@ -63914,7 +64569,7 @@ async function readLarge(fs24, realPath, params, size) {
63914
64569
  number4(part.lines, params.offset)
63915
64570
  ].join("\n");
63916
64571
  }
63917
- const total = await countLines(fs24, realPath, size);
64572
+ const total = await countLines(fs25, realPath, size);
63918
64573
  return [
63919
64574
  `${realPathName(realPath)} is ${human} (${total.toLocaleString()} lines) \u2014 too large to read at once.`,
63920
64575
  "",
@@ -64113,6 +64768,345 @@ function createDefaultToolRegistry() {
64113
64768
  return registry2;
64114
64769
  }
64115
64770
 
64771
+ // ../../packages/core/dist/dataset/store.js
64772
+ import fs19 from "node:fs/promises";
64773
+ import path25 from "node:path";
64774
+ var DatasetStore = class {
64775
+ filePath;
64776
+ statePath;
64777
+ constructor(storageDir, datasetId) {
64778
+ const safe = datasetId.replace(/[^A-Za-z0-9._-]/g, "_");
64779
+ this.filePath = path25.join(storageDir, "datasets", `${safe}.jsonl`);
64780
+ this.statePath = path25.join(storageDir, "datasets", `${safe}.state.json`);
64781
+ }
64782
+ /** Every record. A malformed line is skipped — one bad line costs one record, not the corpus. */
64783
+ async load() {
64784
+ let raw;
64785
+ try {
64786
+ raw = await fs19.readFile(this.filePath, "utf8");
64787
+ } catch {
64788
+ return [];
64789
+ }
64790
+ const byId = /* @__PURE__ */ new Map();
64791
+ for (const line of raw.split("\n")) {
64792
+ const trimmed = line.trim();
64793
+ if (trimmed.length === 0)
64794
+ continue;
64795
+ try {
64796
+ const parsed = JSON.parse(trimmed);
64797
+ if (typeof parsed.id === "string" && typeof parsed.text === "string")
64798
+ byId.set(parsed.id, parsed);
64799
+ } catch {
64800
+ }
64801
+ }
64802
+ return [...byId.values()];
64803
+ }
64804
+ /** Appends. Re-appending an existing id is how an update is recorded — see `load`. */
64805
+ async append(records) {
64806
+ if (records.length === 0)
64807
+ return;
64808
+ await fs19.mkdir(path25.dirname(this.filePath), { recursive: true });
64809
+ await fs19.writeFile(this.filePath, "", { flag: "a" });
64810
+ const lines = records.map((record2) => JSON.stringify(record2)).join("\n");
64811
+ await fs19.appendFile(this.filePath, `${lines}
64812
+ `, "utf8");
64813
+ }
64814
+ /** Rewrites with exactly these. Temp-and-rename, so an interrupted prune leaves the old file. */
64815
+ async replace(records) {
64816
+ await fs19.mkdir(path25.dirname(this.filePath), { recursive: true });
64817
+ const temporary = `${this.filePath}.tmp`;
64818
+ const body = records.map((record2) => JSON.stringify(record2)).join("\n");
64819
+ await fs19.writeFile(temporary, records.length === 0 ? "" : `${body}
64820
+ `, "utf8");
64821
+ await fs19.rename(temporary, this.filePath);
64822
+ }
64823
+ /**
64824
+ * Rewrites the file with the duplicates collapsed.
64825
+ *
64826
+ * Append-as-upsert means a record updated every hour adds a line every hour, so the file grows
64827
+ * with the *number of syncs* rather than the size of the corpus. Compaction is cheap and only
64828
+ * worth doing when it would actually shrink anything, which the caller decides.
64829
+ */
64830
+ async compact() {
64831
+ let before;
64832
+ try {
64833
+ before = (await fs19.readFile(this.filePath, "utf8")).split("\n").filter((line) => line.trim().length > 0).length;
64834
+ } catch {
64835
+ return { before: 0, after: 0 };
64836
+ }
64837
+ const records = await this.load();
64838
+ if (records.length === before)
64839
+ return { before, after: before };
64840
+ await this.replace(records);
64841
+ return { before, after: records.length };
64842
+ }
64843
+ async clear() {
64844
+ await fs19.rm(this.filePath, { force: true });
64845
+ await fs19.rm(this.statePath, { force: true });
64846
+ }
64847
+ async sizeBytes() {
64848
+ try {
64849
+ return (await fs19.stat(this.filePath)).size;
64850
+ } catch {
64851
+ return 0;
64852
+ }
64853
+ }
64854
+ /**
64855
+ * When the last successful sync finished, passed to the collector as `since`.
64856
+ *
64857
+ * Written only on success, deliberately: after a failed run the next one must ask for the same
64858
+ * window again, or whatever the source produced while it was broken is skipped for ever with
64859
+ * nothing anywhere recording the gap.
64860
+ */
64861
+ async lastSyncedAt() {
64862
+ try {
64863
+ const parsed = JSON.parse(await fs19.readFile(this.statePath, "utf8"));
64864
+ return typeof parsed.lastSyncedAt === "number" ? parsed.lastSyncedAt : void 0;
64865
+ } catch {
64866
+ return void 0;
64867
+ }
64868
+ }
64869
+ async recordSync(at) {
64870
+ await fs19.mkdir(path25.dirname(this.statePath), { recursive: true });
64871
+ const temporary = `${this.statePath}.tmp`;
64872
+ await fs19.writeFile(temporary, JSON.stringify({ lastSyncedAt: at }), "utf8");
64873
+ await fs19.rename(temporary, this.statePath);
64874
+ }
64875
+ };
64876
+ function partitionByAge(records, cutoff) {
64877
+ const kept = [];
64878
+ const removed = [];
64879
+ for (const record2 of records) {
64880
+ if (record2.timestamp !== void 0 && record2.timestamp < cutoff)
64881
+ removed.push(record2);
64882
+ else
64883
+ kept.push(record2);
64884
+ }
64885
+ return { kept, removed };
64886
+ }
64887
+
64888
+ // ../../packages/core/dist/dataset/sync.js
64889
+ function datasetEmbedText(record2) {
64890
+ return [record2.title, record2.text].filter((part) => part !== void 0 && part.length > 0).join("\n");
64891
+ }
64892
+ function datasetVectorId(datasetId, recordId) {
64893
+ return `data:${datasetId}:${recordId}`;
64894
+ }
64895
+ async function syncDataset(options) {
64896
+ const now = options.now ?? Date.now();
64897
+ const held = await options.store.load();
64898
+ const heldById = new Map(held.map((record2) => [record2.id, record2]));
64899
+ options.onProgress?.(0, 0, "Running the collector");
64900
+ const since2 = await options.store.lastSyncedAt();
64901
+ const payload = await options.collect(since2);
64902
+ const parsed = parseDatasetPayload(payload);
64903
+ if ("error" in parsed)
64904
+ throw new Error(parsed.error);
64905
+ const collected = parsed.records;
64906
+ const changed = collected.filter((record2) => {
64907
+ const existing = heldById.get(record2.id);
64908
+ return existing === void 0 || JSON.stringify(existing) !== JSON.stringify(record2);
64909
+ });
64910
+ let embedded = 0;
64911
+ if (options.semantic !== void 0 && changed.length > 0) {
64912
+ const { embedder, writer, collection } = options.semantic;
64913
+ await writer.ensureCollection(collection, embedder.dimensions, options.signal);
64914
+ const documents = [];
64915
+ for (const record2 of changed) {
64916
+ if (options.signal?.aborted === true)
64917
+ throw new Error("Stopped.");
64918
+ options.onProgress?.(documents.length, changed.length, "Embedding new and changed records");
64919
+ const existing = heldById.get(record2.id);
64920
+ if (existing !== void 0 && datasetEmbedText(existing) === datasetEmbedText(record2))
64921
+ continue;
64922
+ const text = datasetEmbedText(record2);
64923
+ if (text.trim().length === 0)
64924
+ continue;
64925
+ documents.push({
64926
+ id: datasetVectorId(options.datasetId, record2.id),
64927
+ text,
64928
+ // The id travels in `path`, which is how a hit is joined back to its record.
64929
+ path: datasetVectorId(options.datasetId, record2.id),
64930
+ startLine: 1,
64931
+ endLine: 1,
64932
+ vector: await embedder.embed(text)
64933
+ });
64934
+ }
64935
+ if (documents.length > 0) {
64936
+ await writer.upsert(collection, documents, options.signal);
64937
+ embedded = documents.length;
64938
+ }
64939
+ }
64940
+ if (changed.length > 0)
64941
+ await options.store.append(changed);
64942
+ let removed = 0;
64943
+ if (options.retentionDays !== void 0) {
64944
+ const cutoff = now - options.retentionDays * 24 * 60 * 60 * 1e3;
64945
+ const after = await options.store.load();
64946
+ const { kept, removed: old } = partitionByAge(after, cutoff);
64947
+ if (old.length > 0) {
64948
+ options.onProgress?.(0, old.length, "Removing records past retention");
64949
+ if (options.semantic !== void 0) {
64950
+ await options.semantic.writer.deleteByPaths(options.semantic.collection, old.map((record2) => datasetVectorId(options.datasetId, record2.id)), options.signal);
64951
+ }
64952
+ await options.store.replace(kept);
64953
+ removed = old.length;
64954
+ }
64955
+ }
64956
+ await options.store.compact();
64957
+ await options.store.recordSync(now);
64958
+ const total = (await options.store.load()).length;
64959
+ return { collected: collected.length, updated: changed.length, embedded, removed, total };
64960
+ }
64961
+ async function clearDataset(options) {
64962
+ const held = await options.store.load();
64963
+ if (options.semantic !== void 0 && held.length > 0) {
64964
+ const size = 500;
64965
+ const paths = held.map((record2) => datasetVectorId(options.datasetId, record2.id));
64966
+ for (let start = 0; start < paths.length; start += size) {
64967
+ if (options.signal?.aborted === true)
64968
+ throw new Error("Stopped.");
64969
+ options.onProgress?.(Math.min(start + size, paths.length), paths.length, "Removing vectors");
64970
+ await options.semantic.writer.deleteByPaths(options.semantic.collection, paths.slice(start, start + size), options.signal);
64971
+ }
64972
+ }
64973
+ await options.store.clear();
64974
+ return { removed: held.length };
64975
+ }
64976
+
64977
+ // ../../packages/core/dist/tools/searchData.js
64978
+ var searchSchema3 = external_exports.object({
64979
+ dataset: external_exports.string().optional().describe("Which dataset to search, by name. Omit to search all of them."),
64980
+ query: external_exports.string().optional().describe("Rank by meaning. Omit to get the most recent records in the window."),
64981
+ withinDays: external_exports.number().min(0.01).optional().describe("Only records with a timestamp this recent. Records with no timestamp are excluded."),
64982
+ contains: external_exports.string().optional().describe("Only records whose title or text contains this text. Exact, case-insensitive."),
64983
+ tag: external_exports.string().optional().describe("Filter on a tag, as `name=value`. Exact."),
64984
+ limit: external_exports.number().int().min(1).max(50).optional().describe("How many to return. Default 15.")
64985
+ });
64986
+ function describe4(record2, dataset) {
64987
+ const when = record2.timestamp === void 0 ? "" : `${new Date(record2.timestamp).toLocaleString()} `;
64988
+ const heading = record2.title ?? record2.text.trim().split("\n")[0]?.slice(0, 100) ?? record2.id;
64989
+ const body = record2.text.trim().slice(0, 400);
64990
+ return `${when}[${dataset}] ${heading}
64991
+ id: ${record2.id}${record2.url === void 0 ? "" : ` ${record2.url}`}
64992
+ ${body}`;
64993
+ }
64994
+ function createSearchDataTool(options) {
64995
+ return {
64996
+ name: "search_data",
64997
+ group: "read",
64998
+ 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.",
64999
+ parametersSchema: searchSchema3,
65000
+ execute: async (params) => {
65001
+ try {
65002
+ const datasets = await options.load();
65003
+ if (datasets.length === 0) {
65004
+ return {
65005
+ 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."
65006
+ };
65007
+ }
65008
+ const wanted = params.dataset === void 0 ? datasets : datasets.filter((entry) => entry.name.toLowerCase() === params.dataset?.toLowerCase());
65009
+ if (wanted.length === 0) {
65010
+ return {
65011
+ content: `There is no dataset called "${params.dataset ?? ""}". Configured: ${datasets.map((entry) => entry.name).join(", ")}.`,
65012
+ isError: true
65013
+ };
65014
+ }
65015
+ let candidates = wanted.flatMap((entry) => entry.records.map((record2) => ({ dataset: entry.name, datasetId: entry.id, record: record2 })));
65016
+ const narrowed = [];
65017
+ if (params.withinDays !== void 0) {
65018
+ const cutoff = Date.now() - params.withinDays * 24 * 60 * 60 * 1e3;
65019
+ candidates = candidates.filter((entry) => entry.record.timestamp !== void 0 && entry.record.timestamp >= cutoff);
65020
+ narrowed.push(`in the last ${String(params.withinDays)} day(s)`);
65021
+ }
65022
+ if (params.tag !== void 0) {
65023
+ const [name, value] = params.tag.split("=");
65024
+ candidates = candidates.filter((entry) => value === void 0 ? entry.record.tags?.[name ?? ""] !== void 0 : entry.record.tags?.[name ?? ""] === value);
65025
+ narrowed.push(`tagged ${params.tag}`);
65026
+ }
65027
+ if (params.contains !== void 0) {
65028
+ const needle = params.contains.toLowerCase();
65029
+ candidates = candidates.filter((entry) => `${entry.record.title ?? ""}
65030
+ ${entry.record.text}`.toLowerCase().includes(needle));
65031
+ narrowed.push(`containing "${params.contains}"`);
65032
+ }
65033
+ const criteria = narrowed.length === 0 ? "" : `, ${narrowed.join(", ")}`;
65034
+ if (candidates.length === 0) {
65035
+ return {
65036
+ 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.`
65037
+ };
65038
+ }
65039
+ const limit = params.limit ?? 15;
65040
+ let ordered = candidates.sort((a, b) => (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0));
65041
+ let how = "";
65042
+ const asked = params.query?.trim() ?? "";
65043
+ if (asked.length > 0 && options.semantic === void 0) {
65044
+ const words = asked.toLowerCase().split(/\s+/).filter((word) => word.length > 2);
65045
+ const needle = asked.toLowerCase();
65046
+ candidates = candidates.filter((entry) => {
65047
+ const haystack = `${entry.record.title ?? ""}
65048
+ ${entry.record.text}`.toLowerCase();
65049
+ return words.length === 0 ? haystack.includes(needle) : words.some((word) => haystack.includes(word));
65050
+ });
65051
+ if (candidates.length === 0) {
65052
+ return {
65053
+ 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.`
65054
+ };
65055
+ }
65056
+ ordered = candidates;
65057
+ how = " matched on words, not meaning \u2014 no embedding model is configured";
65058
+ }
65059
+ if (asked.length > 0 && options.semantic !== void 0) {
65060
+ const vector = await options.semantic.embedder.embed(asked);
65061
+ const hits = await options.semantic.searcher.searchByVector(options.semantic.collection, vector, {
65062
+ size: Math.min(100, Math.max(limit * 4, 40))
65063
+ });
65064
+ const rank2 = /* @__PURE__ */ new Map();
65065
+ hits.forEach((hit, position) => {
65066
+ if (!rank2.has(hit.path))
65067
+ rank2.set(hit.path, position);
65068
+ });
65069
+ ordered = [...candidates].sort((a, b) => {
65070
+ const left = rank2.get(`data:${a.datasetId}:${a.record.id}`);
65071
+ const right = rank2.get(`data:${b.datasetId}:${b.record.id}`);
65072
+ if (left !== void 0 && right !== void 0)
65073
+ return left - right;
65074
+ if (left !== void 0)
65075
+ return -1;
65076
+ if (right !== void 0)
65077
+ return 1;
65078
+ return (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0);
65079
+ });
65080
+ how = " ranked by meaning";
65081
+ }
65082
+ const shown = ordered.slice(0, limit);
65083
+ return {
65084
+ content: [
65085
+ `${String(candidates.length)} record(s) in ${wanted.map((entry) => entry.name).join(", ")}${criteria}${how}${candidates.length > shown.length ? `, showing ${String(shown.length)}` : ""}:`,
65086
+ "",
65087
+ ...shown.map((entry) => describe4(entry.record, entry.dataset)),
65088
+ "",
65089
+ "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."
65090
+ ].join("\n")
65091
+ };
65092
+ } catch (error51) {
65093
+ return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
65094
+ }
65095
+ }
65096
+ };
65097
+ }
65098
+
65099
+ // ../../packages/core/dist/python/callPolicy.js
65100
+ var PYTHON_CALL_DENIED = "A Python tool may only call other Python tools and MCP tools. Built-in tools \u2014 running commands, editing files, creating tools or writing skills \u2014 are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.";
65101
+ function mayPythonToolCall(name, group) {
65102
+ if (name.startsWith("py__"))
65103
+ return true;
65104
+ return group === "mcp";
65105
+ }
65106
+ function describeNestedCall(caller, callee) {
65107
+ return `The Python tool "${caller}" is asking to call "${callee}".`;
65108
+ }
65109
+
64116
65110
  // src/identity.ts
64117
65111
  import crypto5 from "node:crypto";
64118
65112
  var SingleUserIdentity = class _SingleUserIdentity {
@@ -64123,13 +65117,36 @@ var SingleUserIdentity = class _SingleUserIdentity {
64123
65117
  /**
64124
65118
  * Single-use and short-lived, because it travels in the launch URL's fragment where it
64125
65119
  * can end up in shell history or a terminal scrollback (§14).
65120
+ *
65121
+ * Ten seconds is right when the browser opens itself, and far too short when a person has to
65122
+ * move the URL by hand — into another application, a remote session, a phone. `--handoff-seconds`
65123
+ * raises it, and what that costs is stated where it is set: a longer window is a longer time in
65124
+ * which somebody reading that scrollback can use it before you do.
64126
65125
  */
64127
65126
  handoffToken = crypto5.randomBytes(32).toString("base64url");
64128
- handoffExpiresAt = Date.now() + 1e4;
65127
+ handoffExpiresAt;
65128
+ handoffSeconds;
65129
+ constructor(handoffSeconds = 10) {
65130
+ this.handoffSeconds = handoffSeconds;
65131
+ this.handoffExpiresAt = Date.now() + handoffSeconds * 1e3;
65132
+ }
64129
65133
  get launchToken() {
64130
65134
  if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
64131
65135
  return this.handoffToken;
64132
65136
  }
65137
+ /**
65138
+ * Mints a fresh handoff token, replacing any outstanding one.
65139
+ *
65140
+ * For the case the old design had no answer to: the token expired unused, and the only way back
65141
+ * was to stop the server and start it again — losing the session, the conversation and anything
65142
+ * running. A new token grants exactly what the first one did, to whoever can read the terminal,
65143
+ * which is the same person it was printed to in the first place.
65144
+ */
65145
+ remintHandoff() {
65146
+ this.handoffToken = crypto5.randomBytes(32).toString("base64url");
65147
+ this.handoffExpiresAt = Date.now() + this.handoffSeconds * 1e3;
65148
+ return this.handoffToken;
65149
+ }
64133
65150
  /**
64134
65151
  * Exchanges the handoff token for the session token, once.
64135
65152
  *
@@ -64137,11 +65154,23 @@ var SingleUserIdentity = class _SingleUserIdentity {
64137
65154
  * or an attack, and in both cases the right answer is that this token is now spent.
64138
65155
  */
64139
65156
  redeemHandoff(presented) {
65157
+ return this.redeem(presented).token;
65158
+ }
65159
+ /**
65160
+ * The same exchange, saying *why* it failed.
65161
+ *
65162
+ * The reasons need different handling and only one of them is anybody's fault. An expired token
65163
+ * is an ordinary mishap — the browser was slow, the URL was pasted late — and the right response
65164
+ * is to offer another. A token that does not match is either a bug or an attack, and the right
65165
+ * response there is nothing at all.
65166
+ */
65167
+ redeem(presented) {
64140
65168
  const expected = this.handoffToken;
64141
65169
  const expiresAt = this.handoffExpiresAt;
64142
65170
  this.handoffToken = void 0;
64143
- if (expected === void 0 || Date.now() > expiresAt) return void 0;
64144
- return timingSafeEquals(presented, expected) ? this.sessionToken : void 0;
65171
+ if (expected === void 0) return { reason: "spent" };
65172
+ if (Date.now() > expiresAt) return { reason: "expired" };
65173
+ return timingSafeEquals(presented, expected) ? { token: this.sessionToken } : { reason: "mismatch" };
64145
65174
  }
64146
65175
  async authenticate(request) {
64147
65176
  const header = request.headers.authorization;
@@ -64158,6 +65187,13 @@ function timingSafeEquals(a, b) {
64158
65187
  function storageKeyFor(principal) {
64159
65188
  return crypto5.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
64160
65189
  }
65190
+ var OpenIdentity = class _OpenIdentity {
65191
+ describe = "single user, no token (--no-token)";
65192
+ static PRINCIPAL = { id: "local", displayName: "Local user" };
65193
+ async authenticate() {
65194
+ return _OpenIdentity.PRINCIPAL;
65195
+ }
65196
+ };
64161
65197
 
64162
65198
  // src/roles.ts
64163
65199
  var ADMIN_ONLY_MESSAGES = [
@@ -64353,8 +65389,8 @@ async function readJsonBody(request, maxBytes = 32 * 1024 * 1024) {
64353
65389
  }
64354
65390
 
64355
65391
  // src/fileSecretStore.ts
64356
- import fs19 from "node:fs/promises";
64357
- import path25 from "node:path";
65392
+ import fs20 from "node:fs/promises";
65393
+ import path26 from "node:path";
64358
65394
  var FileSecretStore = class {
64359
65395
  constructor(filePath) {
64360
65396
  this.filePath = filePath;
@@ -64366,7 +65402,7 @@ var FileSecretStore = class {
64366
65402
  async load() {
64367
65403
  if (this.cache !== void 0) return this.cache;
64368
65404
  try {
64369
- const raw = await fs19.readFile(this.filePath, "utf8");
65405
+ const raw = await fs20.readFile(this.filePath, "utf8");
64370
65406
  const parsed = JSON.parse(raw);
64371
65407
  this.cache = typeof parsed === "object" && parsed !== null ? parsed : {};
64372
65408
  } catch {
@@ -64378,10 +65414,10 @@ var FileSecretStore = class {
64378
65414
  this.queue = this.queue.then(async () => {
64379
65415
  const secrets = await this.load();
64380
65416
  mutate(secrets);
64381
- await fs19.mkdir(path25.dirname(this.filePath), { recursive: true });
65417
+ await fs20.mkdir(path26.dirname(this.filePath), { recursive: true });
64382
65418
  const temp = `${this.filePath}.${process.pid}.tmp`;
64383
- await fs19.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
64384
- await fs19.rename(temp, this.filePath);
65419
+ await fs20.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
65420
+ await fs20.rename(temp, this.filePath);
64385
65421
  });
64386
65422
  return this.queue;
64387
65423
  }
@@ -64412,8 +65448,8 @@ var FileSecretStore = class {
64412
65448
 
64413
65449
  // src/reviewQueue.ts
64414
65450
  import crypto6 from "node:crypto";
64415
- import fs20 from "node:fs/promises";
64416
- import path26 from "node:path";
65451
+ import fs21 from "node:fs/promises";
65452
+ import path27 from "node:path";
64417
65453
  var ReviewQueue = class {
64418
65454
  constructor(filePath) {
64419
65455
  this.filePath = filePath;
@@ -64423,7 +65459,7 @@ var ReviewQueue = class {
64423
65459
  async load() {
64424
65460
  if (this.cache !== void 0) return this.cache;
64425
65461
  try {
64426
- const parsed = JSON.parse(await fs20.readFile(this.filePath, "utf8"));
65462
+ const parsed = JSON.parse(await fs21.readFile(this.filePath, "utf8"));
64427
65463
  this.cache = Array.isArray(parsed) ? parsed : [];
64428
65464
  } catch {
64429
65465
  this.cache = [];
@@ -64432,10 +65468,10 @@ var ReviewQueue = class {
64432
65468
  }
64433
65469
  async persist(items) {
64434
65470
  this.cache = items;
64435
- await fs20.mkdir(path26.dirname(this.filePath), { recursive: true });
65471
+ await fs21.mkdir(path27.dirname(this.filePath), { recursive: true });
64436
65472
  const temporary = `${this.filePath}.tmp`;
64437
- await fs20.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
64438
- await fs20.rename(temporary, this.filePath);
65473
+ await fs21.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
65474
+ await fs21.rename(temporary, this.filePath);
64439
65475
  }
64440
65476
  async list() {
64441
65477
  return [...await this.load()];
@@ -64590,9 +65626,9 @@ var RoutedSecretStore = class {
64590
65626
  };
64591
65627
 
64592
65628
  // src/userVariables.ts
64593
- import fs21 from "node:fs/promises";
65629
+ import fs22 from "node:fs/promises";
64594
65630
  import { readFileSync } from "node:fs";
64595
- import path27 from "node:path";
65631
+ import path28 from "node:path";
64596
65632
  var UserVariableStore = class {
64597
65633
  constructor(filePath) {
64598
65634
  this.filePath = filePath;
@@ -64607,21 +65643,21 @@ var UserVariableStore = class {
64607
65643
  }
64608
65644
  async save(variables) {
64609
65645
  const parsed = sessionVariablesSchema.parse(variables);
64610
- await fs21.mkdir(path27.dirname(this.filePath), { recursive: true });
65646
+ await fs22.mkdir(path28.dirname(this.filePath), { recursive: true });
64611
65647
  const temporary = `${this.filePath}.tmp`;
64612
- await fs21.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
65648
+ await fs22.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
64613
65649
  encoding: "utf8",
64614
65650
  mode: 384
64615
65651
  });
64616
- await fs21.rename(temporary, this.filePath);
65652
+ await fs22.rename(temporary, this.filePath);
64617
65653
  return parsed;
64618
65654
  }
64619
65655
  };
64620
65656
  function userVariableStoreFor(dataDir, principal) {
64621
- return new UserVariableStore(userVariablesPath(path27.join(dataDir, "users", storageKeyFor(principal))));
65657
+ return new UserVariableStore(userVariablesPath(path28.join(dataDir, "users", storageKeyFor(principal))));
64622
65658
  }
64623
65659
  function userVariablesPath(userDir) {
64624
- return path27.join(userDir, "variables.json");
65660
+ return path28.join(userDir, "variables.json");
64625
65661
  }
64626
65662
  function readVariablesFile(filePath) {
64627
65663
  try {
@@ -64635,8 +65671,8 @@ function readVariablesFile(filePath) {
64635
65671
 
64636
65672
  // src/session.ts
64637
65673
  import { watch as fsWatch } from "node:fs";
64638
- import fs22 from "node:fs/promises";
64639
- import path28 from "node:path";
65674
+ import fs23 from "node:fs/promises";
65675
+ import path29 from "node:path";
64640
65676
  var FileConfigStore = class {
64641
65677
  constructor(userConfigPath, workspaceRoot) {
64642
65678
  this.userConfigPath = userConfigPath;
@@ -64652,7 +65688,7 @@ var FileConfigStore = class {
64652
65688
  const filePath = this.pathFor(scope);
64653
65689
  if (filePath === void 0) return void 0;
64654
65690
  try {
64655
- return await fs22.readFile(filePath, "utf8");
65691
+ return await fs23.readFile(filePath, "utf8");
64656
65692
  } catch (error51) {
64657
65693
  if (error51.code === "ENOENT") return void 0;
64658
65694
  throw error51;
@@ -64662,14 +65698,14 @@ var FileConfigStore = class {
64662
65698
  async write(scope, contents) {
64663
65699
  const filePath = this.pathFor(scope);
64664
65700
  if (filePath === void 0) throw new Error(`Cannot write ${scope} config: no workspace is open`);
64665
- await fs22.mkdir(path28.dirname(filePath), { recursive: true });
65701
+ await fs23.mkdir(path29.dirname(filePath), { recursive: true });
64666
65702
  const temporary = `${filePath}.${process.pid.toString(36)}.tmp`;
64667
- await fs22.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
64668
- await fs22.rename(temporary, filePath);
65703
+ await fs23.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
65704
+ await fs23.rename(temporary, filePath);
64669
65705
  try {
64670
65706
  const backupTemp = `${configBackupPath(filePath)}.tmp`;
64671
- await fs22.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
64672
- await fs22.rename(backupTemp, configBackupPath(filePath));
65707
+ await fs23.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
65708
+ await fs23.rename(backupTemp, configBackupPath(filePath));
64673
65709
  } catch {
64674
65710
  }
64675
65711
  }
@@ -64677,7 +65713,7 @@ var FileConfigStore = class {
64677
65713
  const filePath = this.pathFor(scope);
64678
65714
  if (filePath === void 0) return void 0;
64679
65715
  try {
64680
- return await fs22.readFile(configBackupPath(filePath), "utf8");
65716
+ return await fs23.readFile(configBackupPath(filePath), "utf8");
64681
65717
  } catch {
64682
65718
  return void 0;
64683
65719
  }
@@ -64687,7 +65723,7 @@ var FileConfigStore = class {
64687
65723
  if (filePath === void 0) return void 0;
64688
65724
  const target = `${filePath}.corrupt-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
64689
65725
  try {
64690
- await fs22.rename(filePath, target);
65726
+ await fs23.rename(filePath, target);
64691
65727
  return target;
64692
65728
  } catch {
64693
65729
  return void 0;
@@ -64699,8 +65735,8 @@ var FileConfigStore = class {
64699
65735
  };
64700
65736
  let watcher;
64701
65737
  try {
64702
- watcher = fsWatch(path28.dirname(filePath), (_event, filename) => {
64703
- if (filename === path28.basename(filePath)) onChange();
65738
+ watcher = fsWatch(path29.dirname(filePath), (_event, filename) => {
65739
+ if (filename === path29.basename(filePath)) onChange();
64704
65740
  });
64705
65741
  } catch {
64706
65742
  }
@@ -64715,7 +65751,7 @@ var FileWorkspaceState = class {
64715
65751
  values = {};
64716
65752
  async load() {
64717
65753
  try {
64718
- const parsed = JSON.parse(await fs22.readFile(this.filePath, "utf8"));
65754
+ const parsed = JSON.parse(await fs23.readFile(this.filePath, "utf8"));
64719
65755
  if (typeof parsed === "object" && parsed !== null) this.values = parsed;
64720
65756
  } catch {
64721
65757
  this.values = {};
@@ -64727,8 +65763,8 @@ var FileWorkspaceState = class {
64727
65763
  async set(key, value) {
64728
65764
  if (value === void 0) delete this.values[key];
64729
65765
  else this.values[key] = value;
64730
- await fs22.mkdir(path28.dirname(this.filePath), { recursive: true });
64731
- await fs22.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
65766
+ await fs23.mkdir(path29.dirname(this.filePath), { recursive: true });
65767
+ await fs23.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
64732
65768
  }
64733
65769
  };
64734
65770
  function createBrowserUi(workspaceRoot, post) {
@@ -64766,7 +65802,7 @@ function createBrowserUi(workspaceRoot, post) {
64766
65802
  */
64767
65803
  openFile: async (filePath) => {
64768
65804
  try {
64769
- post([`[info] ${path28.basename(filePath)}`, "", await fs22.readFile(filePath, "utf8")].join("\n"));
65805
+ post([`[info] ${path29.basename(filePath)}`, "", await fs23.readFile(filePath, "utf8")].join("\n"));
64770
65806
  } catch (error51) {
64771
65807
  post(`[warning] Could not read ${filePath}: ${String(error51)}`);
64772
65808
  }
@@ -64784,14 +65820,14 @@ function createBrowserUi(workspaceRoot, post) {
64784
65820
  if (found.length >= limit || depth > 12) return;
64785
65821
  let entries;
64786
65822
  try {
64787
- entries = await fs22.readdir(dir, { withFileTypes: true });
65823
+ entries = await fs23.readdir(dir, { withFileTypes: true });
64788
65824
  } catch {
64789
65825
  return;
64790
65826
  }
64791
65827
  for (const entry of entries) {
64792
65828
  if (found.length >= limit) return;
64793
65829
  if (entry.name.startsWith(".") && entry.name !== ".env") continue;
64794
- const full = path28.join(dir, entry.name);
65830
+ const full = path29.join(dir, entry.name);
64795
65831
  if (entry.isDirectory()) {
64796
65832
  if (!skip.has(entry.name)) await walk(full, depth + 1);
64797
65833
  } else if (needle.length === 0 || entry.name.toLowerCase().includes(needle)) {
@@ -64805,11 +65841,11 @@ function createBrowserUi(workspaceRoot, post) {
64805
65841
  };
64806
65842
  }
64807
65843
  async function createSession(options) {
64808
- const userDir = path28.join(options.dataDir, "users", storageKeyFor(options.principal));
64809
- await fs22.mkdir(userDir, { recursive: true, mode: 448 });
65844
+ const userDir = path29.join(options.dataDir, "users", storageKeyFor(options.principal));
65845
+ await fs23.mkdir(userDir, { recursive: true, mode: 448 });
64810
65846
  const variableStore = new UserVariableStore(userVariablesPath(userDir));
64811
65847
  const userVariables = () => variableStore.read();
64812
- const workspaceState = new FileWorkspaceState(path28.join(userDir, "workspace-state.json"));
65848
+ const workspaceState = new FileWorkspaceState(path29.join(userDir, "workspace-state.json"));
64813
65849
  await workspaceState.load();
64814
65850
  const services = {
64815
65851
  transport: options.transport,
@@ -64817,9 +65853,9 @@ async function createSession(options) {
64817
65853
  * A shared profile's API key belongs to the administrator and lives beside the shared config;
64818
65854
  * everything else is this user's. Routed by the reference, which is all a secret store gets.
64819
65855
  */
64820
- secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path28.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path28.join(userDir, "secrets.json")), options.sharedSecrets),
64821
- configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path28.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
64822
- new FileConfigStore(path28.join(userDir, "config.json"), options.workspaceRoot),
65856
+ secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path29.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path29.join(userDir, "secrets.json")), options.sharedSecrets),
65857
+ configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path29.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
65858
+ new FileConfigStore(path29.join(userDir, "config.json"), options.workspaceRoot),
64823
65859
  options.sharedProfiles
64824
65860
  ),
64825
65861
  workspaceState,
@@ -64904,11 +65940,11 @@ var CONTENT_TYPES = {
64904
65940
  async function startServer(options) {
64905
65941
  const log = options.logSink ?? ((line) => process.stderr.write(`${line}
64906
65942
  `));
64907
- const identity = options.identity ?? new SingleUserIdentity();
65943
+ const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : new SingleUserIdentity(options.handoffSeconds));
64908
65944
  const roles = options.roles ?? SINGLE_USER_POLICY;
64909
65945
  const sharedStore = options.sharedConfig;
64910
- const sharedSecretStore = new FileSecretStore(path29.join(options.dataDir, "shared-secrets.json"));
64911
- const reviews = new ReviewQueue(path29.join(options.dataDir, "reviews.json"));
65946
+ const sharedSecretStore = new FileSecretStore(path30.join(options.dataDir, "shared-secrets.json"));
65947
+ const reviews = new ReviewQueue(path30.join(options.dataDir, "reviews.json"));
64912
65948
  let sharedCache = { variables: [], adminIds: [], profiles: [] };
64913
65949
  const bindAddress = options.bindAddress ?? "127.0.0.1";
64914
65950
  if (sharedStore !== void 0) sharedCache = await sharedStore.load();
@@ -65015,18 +66051,26 @@ async function startServer(options) {
65015
66051
  return;
65016
66052
  }
65017
66053
  if (url2.pathname === "/api/session" && request.method === "POST") {
66054
+ if (identity instanceof OpenIdentity) {
66055
+ respondJson(response, 200, { token: "" });
66056
+ return;
66057
+ }
65018
66058
  if (!(identity instanceof SingleUserIdentity)) {
65019
66059
  reject(response, { status: 404, reason: "Handoff is only used in single-user mode." });
65020
66060
  return;
65021
66061
  }
65022
66062
  const body = await readJsonBody(request);
65023
66063
  const handoff = typeof body?.handoff === "string" ? body.handoff : "";
65024
- const token = identity.redeemHandoff(handoff);
65025
- if (token === void 0) {
65026
- reject(response, { status: 401, reason: "Handoff token invalid or expired. Restart light-code." });
66064
+ const outcome = identity.redeem(handoff);
66065
+ if (outcome.token === void 0) {
66066
+ if (outcome.reason === "expired" || outcome.reason === "spent") options.onHandoffLapsed?.(outcome.reason);
66067
+ reject(response, {
66068
+ status: 401,
66069
+ 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."
66070
+ });
65027
66071
  return;
65028
66072
  }
65029
- respondJson(response, 200, { token });
66073
+ respondJson(response, 200, { token: outcome.token });
65030
66074
  return;
65031
66075
  }
65032
66076
  const principal = await identity.authenticate(request);
@@ -65119,14 +66163,14 @@ async function startServer(options) {
65119
66163
  if (options.workspaceRoot === void 0) return "No workspace is open, so there is nowhere to write it.";
65120
66164
  try {
65121
66165
  if (item.kind === "skill") {
65122
- const dir2 = path29.join(options.workspaceRoot, ".lightcode", "skills");
65123
- await fs23.mkdir(dir2, { recursive: true });
65124
- await fs23.writeFile(path29.join(dir2, `${item.name}.md`), item.content, "utf8");
66166
+ const dir2 = path30.join(options.workspaceRoot, ".lightcode", "skills");
66167
+ await fs24.mkdir(dir2, { recursive: true });
66168
+ await fs24.writeFile(path30.join(dir2, `${item.name}.md`), item.content, "utf8");
65125
66169
  return void 0;
65126
66170
  }
65127
- const dir = path29.join(options.workspaceRoot, ".lightcode", "tools");
65128
- await fs23.mkdir(dir, { recursive: true });
65129
- await fs23.writeFile(path29.join(dir, `${item.name}.py`), item.content, "utf8");
66171
+ const dir = path30.join(options.workspaceRoot, ".lightcode", "tools");
66172
+ await fs24.mkdir(dir, { recursive: true });
66173
+ await fs24.writeFile(path30.join(dir, `${item.name}.py`), item.content, "utf8");
65130
66174
  return void 0;
65131
66175
  } catch (error51) {
65132
66176
  return error51 instanceof Error ? error51.message : String(error51);
@@ -65227,9 +66271,9 @@ async function startServer(options) {
65227
66271
  return;
65228
66272
  }
65229
66273
  try {
65230
- const body = await fs23.readFile(path29.join(options.clientDir, asset));
66274
+ const body = await fs24.readFile(path30.join(options.clientDir, asset));
65231
66275
  response.writeHead(200, {
65232
- "Content-Type": CONTENT_TYPES[path29.extname(asset)] ?? "application/octet-stream",
66276
+ "Content-Type": CONTENT_TYPES[path30.extname(asset)] ?? "application/octet-stream",
65233
66277
  ...securityHeaders()
65234
66278
  });
65235
66279
  response.end(body);
@@ -65245,6 +66289,7 @@ async function startServer(options) {
65245
66289
  return {
65246
66290
  url: `http://${authority}`,
65247
66291
  launchToken: identity instanceof SingleUserIdentity ? identity.launchToken : void 0,
66292
+ newLaunchUrl: identity instanceof SingleUserIdentity ? () => `http://${authority}/#t=${identity.remintHandoff()}` : void 0,
65248
66293
  close: () => new Promise((resolve) => {
65249
66294
  for (const connection of connections.values()) connection.dispose();
65250
66295
  connections.clear();