@chosengeneration/light-code 0.37.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 +291 -18
- package/dist/client/client.js +57 -57
- package/dist/server.js +263 -14
- package/package.json +1 -1
package/dist/server.js
CHANGED
|
@@ -38971,13 +38971,76 @@ var datasetPayloadSchema = external_exports.union([
|
|
|
38971
38971
|
external_exports.object({ records: external_exports.array(datasetRecordSchema) }),
|
|
38972
38972
|
external_exports.array(datasetRecordSchema)
|
|
38973
38973
|
]);
|
|
38974
|
+
var WRAPPER_KEYS = ["records", "items", "data", "results", "rows"];
|
|
38975
|
+
var TEXT_KEYS = ["text", "content", "body", "description", "summary"];
|
|
38976
|
+
function toMilliseconds(value) {
|
|
38977
|
+
if (typeof value === "string") {
|
|
38978
|
+
const parsed = Date.parse(value);
|
|
38979
|
+
return Number.isNaN(parsed) ? void 0 : parsed;
|
|
38980
|
+
}
|
|
38981
|
+
if (typeof value !== "number" || !Number.isFinite(value))
|
|
38982
|
+
return void 0;
|
|
38983
|
+
return value > 0 && value < 1e11 ? Math.round(value * 1e3) : Math.round(value);
|
|
38984
|
+
}
|
|
38985
|
+
function normaliseRecord(value) {
|
|
38986
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
38987
|
+
return void 0;
|
|
38988
|
+
const row = value;
|
|
38989
|
+
const id = row["id"] ?? row["key"] ?? row["_id"];
|
|
38990
|
+
const textKey = TEXT_KEYS.find((key) => typeof row[key] === "string" && row[key].length > 0);
|
|
38991
|
+
const record2 = {
|
|
38992
|
+
...typeof id === "string" || typeof id === "number" ? { id: String(id) } : {},
|
|
38993
|
+
...textKey !== void 0 ? { text: row[textKey] } : {},
|
|
38994
|
+
...typeof row["title"] === "string" ? { title: row["title"] } : {},
|
|
38995
|
+
...typeof row["url"] === "string" ? { url: row["url"] } : {}
|
|
38996
|
+
};
|
|
38997
|
+
const at = toMilliseconds(row["timestamp"] ?? row["updated"] ?? row["updated_at"] ?? row["date"]);
|
|
38998
|
+
if (at !== void 0)
|
|
38999
|
+
record2["timestamp"] = at;
|
|
39000
|
+
if (row["tags"] !== null && typeof row["tags"] === "object" && !Array.isArray(row["tags"])) {
|
|
39001
|
+
const tags = {};
|
|
39002
|
+
for (const [key, tagValue] of Object.entries(row["tags"])) {
|
|
39003
|
+
if (tagValue === null || tagValue === void 0)
|
|
39004
|
+
continue;
|
|
39005
|
+
if (typeof tagValue === "object")
|
|
39006
|
+
continue;
|
|
39007
|
+
tags[key] = String(tagValue);
|
|
39008
|
+
}
|
|
39009
|
+
if (Object.keys(tags).length > 0)
|
|
39010
|
+
record2["tags"] = tags;
|
|
39011
|
+
}
|
|
39012
|
+
return record2;
|
|
39013
|
+
}
|
|
38974
39014
|
function parseDatasetPayload(value) {
|
|
38975
|
-
|
|
38976
|
-
if (
|
|
38977
|
-
|
|
39015
|
+
let candidate = value;
|
|
39016
|
+
if (typeof candidate === "string") {
|
|
39017
|
+
try {
|
|
39018
|
+
candidate = JSON.parse(candidate);
|
|
39019
|
+
} catch {
|
|
39020
|
+
return {
|
|
39021
|
+
error: `The collector tool returned text rather than records. It must return a list of {"id": ..., "text": ...} dicts. It returned: ${String(value).slice(0, 200)}`
|
|
39022
|
+
};
|
|
39023
|
+
}
|
|
39024
|
+
}
|
|
39025
|
+
if (candidate !== null && typeof candidate === "object" && !Array.isArray(candidate)) {
|
|
39026
|
+
const wrapper = WRAPPER_KEYS.find((key) => Array.isArray(candidate[key]));
|
|
39027
|
+
candidate = wrapper === void 0 ? [candidate] : candidate[wrapper];
|
|
39028
|
+
}
|
|
39029
|
+
if (!Array.isArray(candidate)) {
|
|
39030
|
+
return {
|
|
39031
|
+
error: `The collector tool did not return a list of records. Return a list of {"id": ..., "text": ...} dicts, or a dict with them under "records". It returned: ${JSON.stringify(value).slice(0, 200)}`
|
|
39032
|
+
};
|
|
38978
39033
|
}
|
|
39034
|
+
const normalised = candidate.map((entry) => normaliseRecord(entry) ?? entry);
|
|
39035
|
+
const parsed = external_exports.array(datasetRecordSchema).safeParse(normalised);
|
|
39036
|
+
if (parsed.success)
|
|
39037
|
+
return { records: parsed.data };
|
|
39038
|
+
const first = parsed.error.issues[0];
|
|
39039
|
+
const index = typeof first?.path[0] === "number" ? first.path[0] : 0;
|
|
39040
|
+
const offending = candidate[index];
|
|
39041
|
+
const keys = offending !== null && typeof offending === "object" ? Object.keys(offending).join(", ") : "none";
|
|
38979
39042
|
return {
|
|
38980
|
-
error:
|
|
39043
|
+
error: `The collector tool returned ${String(candidate.length)} item(s), and item ${String(index + 1)} is not a usable record. Each needs a stable \`id\` (the source's own identifier, so a re-sync updates rather than duplicates) and a \`text\` to index. That item had these keys: ${keys}. ` + parsed.error.issues.slice(0, 3).map((issue2) => `${issue2.path.join(".")}: ${issue2.message}`).join("; ")
|
|
38981
39044
|
};
|
|
38982
39045
|
}
|
|
38983
39046
|
var datasetConfigSchema = external_exports.object({
|
|
@@ -38995,6 +39058,24 @@ var datasetConfigSchema = external_exports.object({
|
|
|
38995
39058
|
/** Which vector store to write to. Falls back to the one named for `data`, then the active one. */
|
|
38996
39059
|
storeId: external_exports.string().optional()
|
|
38997
39060
|
});
|
|
39061
|
+
var COLLECTOR_EXAMPLE = `def run(since: int | None = None) -> list[dict]:
|
|
39062
|
+
"""Tickets assigned to the team.
|
|
39063
|
+
|
|
39064
|
+
Args:
|
|
39065
|
+
since: Epoch milliseconds of the last successful sync, or None on the first run.
|
|
39066
|
+
"""
|
|
39067
|
+
rows = my_internal_lib.search(updated_after=since)
|
|
39068
|
+
return [
|
|
39069
|
+
{
|
|
39070
|
+
"id": row.key, # stable: the source's own identifier
|
|
39071
|
+
"title": row.summary,
|
|
39072
|
+
"text": f"{row.summary}\\n\\n{row.description}", # what gets embedded
|
|
39073
|
+
"url": row.browse_url,
|
|
39074
|
+
"timestamp": int(row.updated.timestamp() * 1000), # epoch MILLIseconds
|
|
39075
|
+
"tags": {"status": row.status, "team": row.team}, # flat, strings only
|
|
39076
|
+
}
|
|
39077
|
+
for row in rows
|
|
39078
|
+
]`;
|
|
38998
39079
|
var COLLECTOR_TOOL_GUIDANCE = [
|
|
38999
39080
|
"Writing a collector for a custom dataset:",
|
|
39000
39081
|
"- A collector is an ordinary Python tool. Its `run` returns a list of records, each a dict",
|
|
@@ -39012,7 +39093,18 @@ var COLLECTOR_TOOL_GUIDANCE = [
|
|
|
39012
39093
|
" changed if the source allows; returning everything each time is correct but slower.",
|
|
39013
39094
|
"- Return `[]` when there is nothing new. That is a successful sync, not an error.",
|
|
39014
39095
|
"- Keep credentials out of the tool: read them from the environment or from a file the user",
|
|
39015
|
-
" already has. A tool file lives in the workspace and lands in git."
|
|
39096
|
+
" already has. A tool file lives in the workspace and lands in git.",
|
|
39097
|
+
"",
|
|
39098
|
+
"**Return a list of dicts. Not a string, not a dict of rows, not a formatted report.** The",
|
|
39099
|
+
"common mistake is returning something a person would read; a collector returns something a",
|
|
39100
|
+
"search can index, and anything else is refused when it runs. If the source gives you one",
|
|
39101
|
+
"object, return a one-element list.",
|
|
39102
|
+
"",
|
|
39103
|
+
"A collector looks like this:",
|
|
39104
|
+
"",
|
|
39105
|
+
"```python",
|
|
39106
|
+
COLLECTOR_EXAMPLE,
|
|
39107
|
+
"```"
|
|
39016
39108
|
].join("\n");
|
|
39017
39109
|
|
|
39018
39110
|
// ../../packages/core/dist/mcp/types.js
|
|
@@ -42977,6 +43069,9 @@ function buildSystemPrompt(workspaceRoot, options = {}) {
|
|
|
42977
43069
|
lines.push("", "Recording what you learn:", "- When the user explains something durable about their environment \u2014 an internal", " library and how to use it, a house convention, the shape of an in-house API, a", " gotcha specific to this codebase \u2014 offer to record it with write_skill. Ask first;", " do not write one unprompted.", '- "Durable" means it would be true again next week and useful to a future', " conversation. A one-off instruction for the current task is not a skill.", options.skillsSearchable === true ? "- Before writing a new skill, search for one with search_docs: if a note already covers the subject, read it and update that instead of creating a near-duplicate." : "- Before writing a new skill, check the list above: if one already covers the subject, read it and update that instead of creating a near-duplicate.", "- When you learn something *corrects* an existing skill, say so and offer to update", " it. A stale skill is worse than a missing one, because it is trusted.", "- Write for a reader who has none of this conversation: name the package, the import", ' path, the function, and show a short example. Avoid "as discussed" and "the usual".', options.skillsSearchable === true ? "- The description line is what search matches on, so make it say what subject the skill covers in the words someone would search for \u2014 it is a trigger, not a summary." : "- The description line is the only part always in context, so make it say what subject the skill covers \u2014 it is a trigger for reading, not a summary.");
|
|
42978
43070
|
}
|
|
42979
43071
|
lines.push("", "Charts:", "- **Draw one whenever numbers are easier seen than read** \u2014 a count per folder or per day, a", " value trending over time, a breakdown of a total. Use show_chart; do not print a table of", " figures where a chart would answer the question faster.", "- **Always fill in `detail`** when the numbers count things that can be named \u2014 the subjects,", ' the files, the ids. A bar reading 14 is only useful if "which fourteen?" has an answer, and', " the detail is what lets the user open the bar instead of asking you to search again.", "- Say in `note` where the numbers came from and what they exclude. A chart is believed", " without being checked, so its limits have to travel with it.", "- Series must have exactly one value per category. A mismatch is refused rather than padded,", " because a chart drawn from misaligned data looks correct and is not.", "- After drawing, describe what it shows. Do not recite the numbers again \u2014 they are on screen.", "- **A Python tool can produce the data.** Have it return JSON shaped", ' `{"categories": [...], "series": [{"name": ..., "values": [...], "detail": [[...], ...]}]}`', " and pass that straight to show_chart. That is the intended way to chart anything you have", " analysed in Python \u2014 the tool does the arithmetic, show_chart draws it, and the numbers are", " never retyped by you in between.");
|
|
43072
|
+
if (options.canWriteCollectors === true && (options.datasets ?? []).length === 0) {
|
|
43073
|
+
lines.push("", "Custom datasets:", "- None are configured yet. The user sets one up in Settings, Custom data, by pointing at a", " tool that returns records \u2014 and can ask you to write that tool. If they do, it is an", " ordinary Python tool and the contract is below. Follow it exactly: a collector returning", " the wrong shape is refused when it runs, not when it is written.", "", COLLECTOR_TOOL_GUIDANCE);
|
|
43074
|
+
}
|
|
42980
43075
|
if (options.datasets !== void 0 && options.datasets.length > 0) {
|
|
42981
43076
|
lines.push("", "Custom datasets:", `- The user collects these themselves: ${options.datasets.map((dataset) => `${dataset.name} (${String(dataset.records)} records)`).join(", ")}.`, "- **Use search_data for anything about data the organisation collects itself** \u2014 tickets,", " wiki pages, rows from an internal system. It is the only way to reach these; they are not", " in the codebase and not in the mail index.", "- It searches what has been **synced**, not the live source. If the answer turns on", " something very recent, say when the dataset was last synced rather than implying it is", " current. Do not offer to refresh it yourself \u2014 syncing is triggered by the user.", ...options.canWriteCollectors === true ? [
|
|
42982
43077
|
"- If they want a dataset you cannot find, you can write the collector: it is an",
|
|
@@ -54252,6 +54347,10 @@ var PythonWorker = class {
|
|
|
54252
54347
|
this.options.logger.debug("python worker output", line);
|
|
54253
54348
|
return;
|
|
54254
54349
|
}
|
|
54350
|
+
if (typeof frame.callback === "string") {
|
|
54351
|
+
void this.serveCallback(frame.callback, frame.name, frame.arguments, frame.caller);
|
|
54352
|
+
return;
|
|
54353
|
+
}
|
|
54255
54354
|
if (typeof frame.id !== "number")
|
|
54256
54355
|
return;
|
|
54257
54356
|
const entry = this.pending.get(frame.id);
|
|
@@ -54265,6 +54364,40 @@ var PythonWorker = class {
|
|
|
54265
54364
|
entry.reject(new PythonWorkerError(typeof frame.error === "string" ? frame.error : "The Python tool failed.", typeof frame.traceback === "string" ? frame.traceback : void 0));
|
|
54266
54365
|
}
|
|
54267
54366
|
}
|
|
54367
|
+
/**
|
|
54368
|
+
* Runs a tool on a Python tool's behalf and writes the answer back.
|
|
54369
|
+
*
|
|
54370
|
+
* The rules live in `options.callTool`, which the host supplies — this only carries the
|
|
54371
|
+
* message. Refusing here would put a policy decision in the transport, where nothing can see
|
|
54372
|
+
* the registry, the approval gate or whether anybody is present to answer.
|
|
54373
|
+
*/
|
|
54374
|
+
async serveCallback(token, name, args, caller) {
|
|
54375
|
+
const reply = (payload) => {
|
|
54376
|
+
try {
|
|
54377
|
+
this.child?.stdin?.write(`${JSON.stringify({ callback: token, ...payload })}
|
|
54378
|
+
`);
|
|
54379
|
+
} catch {
|
|
54380
|
+
this.options.logger.debug("python worker: could not answer a callback");
|
|
54381
|
+
}
|
|
54382
|
+
};
|
|
54383
|
+
if (this.options.callTool === void 0) {
|
|
54384
|
+
reply({
|
|
54385
|
+
ok: false,
|
|
54386
|
+
error: "This session cannot call other tools from a Python tool. That is the case during an unattended scheduled run, where nobody is present to approve one."
|
|
54387
|
+
});
|
|
54388
|
+
return;
|
|
54389
|
+
}
|
|
54390
|
+
if (typeof name !== "string") {
|
|
54391
|
+
reply({ ok: false, error: "call_tool needs the name of a tool." });
|
|
54392
|
+
return;
|
|
54393
|
+
}
|
|
54394
|
+
try {
|
|
54395
|
+
const value = await this.options.callTool(name, args ?? {}, typeof caller === "string" ? caller : "a Python tool");
|
|
54396
|
+
reply({ ok: true, value });
|
|
54397
|
+
} catch (error51) {
|
|
54398
|
+
reply({ ok: false, error: error51 instanceof Error ? error51.message : String(error51) });
|
|
54399
|
+
}
|
|
54400
|
+
}
|
|
54268
54401
|
request(method, params, timeoutMs) {
|
|
54269
54402
|
if (this.disposed)
|
|
54270
54403
|
return Promise.reject(new PythonWorkerError("The Python worker has been shut down."));
|
|
@@ -54908,7 +55041,7 @@ function createCreatePythonTool(context) {
|
|
|
54908
55041
|
* script that nothing can call. Both tools write Python to a file; only this one registers
|
|
54909
55042
|
* it, and the description has to make that the obvious reading.
|
|
54910
55043
|
*/
|
|
54911
|
-
description: 'THE way to create a tool when the user asks for one. Writes a Python tool and registers it, so it becomes callable as py__<name> from the next message onwards. Use this \u2014 not write_to_file \u2014 for anything described as a "tool", and for work awkward in shell commands: parsing, data transformation, anything needing a library. Define a `run` function with type hints; the schema and description are derived from the code, so there is no metadata to keep in sync. The user must approve the source before it is saved.'
|
|
55044
|
+
description: 'THE way to create a tool when the user asks for one. Writes a Python tool and registers it, so it becomes callable as py__<name> from the next message onwards. Use this \u2014 not write_to_file \u2014 for anything described as a "tool", and for work awkward in shell commands: parsing, data transformation, anything needing a library. Define a `run` function with type hints; the schema and description are derived from the code, so there is no metadata to keep in sync. The user must approve the source before it is saved. A tool can call other tools: `import light_code` then `light_code.call_tool("py__other", x=1)` or `light_code.call_tool("server__tool", ...)`. Only other Python tools and MCP tools can be reached that way \u2014 running commands, editing files and creating tools are deliberately out of reach from inside a tool body. The user approves each nested call as they would any other, so use it for composing work rather than for slipping past a prompt.'
|
|
54912
55045
|
});
|
|
54913
55046
|
}
|
|
54914
55047
|
function createUpdatePythonTool(context) {
|
|
@@ -54984,7 +55117,7 @@ ${traceback}` : message3, isError: true };
|
|
|
54984
55117
|
}
|
|
54985
55118
|
|
|
54986
55119
|
// ../../packages/core/dist/python/workerSource.js
|
|
54987
|
-
var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\n\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\nTypeScript side cannot do for itself:\n\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\n and therefore never drifts from the code (CLAUDE.md \xA713);\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\n restarting;\n* running the tool.\n\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\nthem as the tool\'s own output rather than corrupting the channel.\n"""\n\nfrom __future__ import annotations\n\nimport importlib.util\nimport inspect\nimport io\nimport json\nimport re\nimport sys\nimport traceback\nfrom contextlib import redirect_stdout\nfrom pathlib import Path\nfrom typing import Any\n\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\n_MODULES: dict[str, Any] = {}\n\n\ndef _respond(payload: dict[str, Any]) -> None:\n """Write one frame.\n\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\n """\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\n _REAL_STDOUT.flush()\n\n\n_REAL_STDOUT = sys.stdout\n\n\ndef _load(name: str, path: str) -> Any:\n """Imports a tool module from an explicit path, replacing any previous version."""\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\n if spec is None or spec.loader is None:\n raise ImportError(f"could not load {path}")\n module = importlib.util.module_from_spec(spec)\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\n # land in the middle of the JSON-RPC stream.\n with redirect_stdout(io.StringIO()):\n spec.loader.exec_module(module)\n if not hasattr(module, "run"):\n raise AttributeError(f"{path} defines no `run` function")\n _MODULES[name] = module\n return module\n\n\ndef _google_arg_docs(doc: str) -> dict[str, str]:\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\n\n Best-effort by design. A missing description costs the model a hint; a parser that threw\n would cost it the whole tool.\n """\n docs: dict[str, str] = {}\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\n if not match:\n return docs\n for line in match.group(1).splitlines():\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\n if entry:\n docs[entry.group(1)] = entry.group(2).strip()\n return docs\n\n\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\n#: which is lossy but callable.\n_PRIMITIVE_TYPES: dict[Any, str] = {\n str: "string",\n bool: "boolean",\n int: "integer",\n float: "number",\n list: "array",\n dict: "object",\n}\n\n\ndef _fallback_schema(run: Any) -> dict[str, Any]:\n """Derives a schema from bare annotations, for when pydantic is not installed.\n\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\n which is truthy for every value including ``"false"``. Silent, and wrong.\n """\n signature = inspect.signature(run)\n properties: dict[str, Any] = {}\n required: list[str] = []\n\n for name, parameter in signature.parameters.items():\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\n continue\n annotation = parameter.annotation\n # A string annotation appears under `from __future__ import annotations`; resolving\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\n if isinstance(annotation, str):\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\n if parameter.default is parameter.empty:\n required.append(name)\n\n return {"type": "object", "properties": properties, "required": required}\n\n\ndef _schema_for(module: Any) -> dict[str, Any]:\n """Derives the parameter schema from ``run``\'s type hints.\n\n pydantic when available, because it handles unions, defaults, nested models and\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\n """\n run = module.run\n try:\n from pydantic import TypeAdapter\n\n schema = TypeAdapter(run).json_schema()\n properties = schema.get("properties", {})\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\n schema = _fallback_schema(run)\n properties = schema["properties"]\n\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\n for name, description in _google_arg_docs(doc).items():\n if name in properties:\n properties[name]["description"] = description\n\n schema.setdefault("type", "object")\n schema["properties"] = properties\n return schema\n\n\ndef _describe(name: str, path: str) -> dict[str, Any]:\n module = _load(name, path)\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\n # usually documents the parameters.\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\n return {"name": name, "description": description, "schema": _schema_for(module)}\n\n\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\n method = request.get("method")\n params = request.get("params") or {}\n\n if method == "ping":\n return {"ok": True, "python": sys.version}\n\n if method == "describe":\n return _describe(params["name"], params["path"])\n\n if method == "validate":\n # Parsed before importing, so a syntax error is reported as one rather than as\n # whatever the import machinery happens to raise.\n source = Path(params["path"]).read_text(encoding="utf-8")\n compile(source, params["path"], "exec")\n return _describe(params["name"], params["path"])\n\n if method == "call":\n name = params["name"]\n module = _MODULES.get(name)\n if module is None:\n module = _load(name, params["path"])\n # Reloaded when the caller says the file changed, so an edit mid-session takes\n # effect without a restart.\n if params.get("reload"):\n module = _load(name, params["path"])\n\n captured = io.StringIO()\n with redirect_stdout(captured):\n result = module.run(**(params.get("arguments") or {}))\n printed = captured.getvalue()\n return {\n "result": result,\n # Returned rather than discarded: a print is how people debug, and swallowing it\n # makes a misbehaving tool impossible to diagnose from the chat.\n "stdout": printed,\n }\n\n raise ValueError(f"unknown method: {method}")\n\n\ndef main() -> None:\n for line in sys.stdin:\n line = line.strip()\n if not line:\n continue\n try:\n request = json.loads(line)\n except json.JSONDecodeError:\n continue\n\n request_id = request.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\n _respond(\n {\n "id": request_id,\n "ok": False,\n "error": f"{type(error).__name__}: {error}",\n "traceback": traceback.format_exc(),\n }\n )\n\n\nif __name__ == "__main__":\n main()\n';
|
|
55120
|
+
var PYTHON_WORKER_SOURCE = '"""Light Code\'s Python tool worker.\r\n\r\nOne long-lived process per workspace, speaking JSON-RPC over stdio. It owns three jobs the\r\nTypeScript side cannot do for itself:\r\n\r\n* deriving a JSON Schema from ``run``\'s type hints, so tool metadata is never hand-written\r\n and therefore never drifts from the code (CLAUDE.md \xA713);\r\n* importing and reloading tool modules, so a tool edited mid-session takes effect without\r\n restarting;\r\n* running the tool.\r\n\r\nFraming is one JSON object per line. Length-prefixing would be sturdier, but a tool that\r\nprints to stdout is *common* \u2014 so the reader tolerates unparseable lines instead, treating\r\nthem as the tool\'s own output rather than corrupting the channel.\r\n"""\r\n\r\nfrom __future__ import annotations\r\n\r\nimport importlib.util\r\nimport inspect\r\nimport io\r\nimport json\r\nimport re\r\nimport sys\r\nimport traceback\r\nimport types\r\nfrom contextlib import redirect_stdout\r\nfrom pathlib import Path\r\nfrom typing import Any\r\n\r\n# Loaded modules, keyed by tool name, so a reload replaces rather than shadows.\r\n_MODULES: dict[str, Any] = {}\r\n\r\n\r\ndef _respond(payload: dict[str, Any]) -> None:\r\n """Write one frame.\r\n\r\n Always to the real stdout, captured at import time \u2014 a tool that reassigns\r\n ``sys.stdout`` would otherwise silently swallow every subsequent reply.\r\n """\r\n _REAL_STDOUT.write(json.dumps(payload) + "\\n")\r\n _REAL_STDOUT.flush()\r\n\r\n\r\n_REAL_STDOUT = sys.stdout\r\n_REAL_STDIN = sys.stdin\r\n\r\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\r\n_CALL_DEPTH = 0\r\n_MAX_DEPTH = 4\r\n_CURRENT_TOOL = ""\r\n_CALL_SEQ = 0\r\n\r\n\r\nclass ToolError(RuntimeError):\r\n """A tool this one called came back with a failure."""\r\n\r\n\r\ndef call_tool(name: str, **arguments: Any) -> Any:\r\n """Calls another tool and returns its result.\r\n\r\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\r\n tools can be reached; see the host for why.\r\n\r\n This blocks the worker, which is correct: the tool asked for something and cannot\r\n continue without it. The host may prompt the user before running it, so it can take as\r\n long as a person takes to answer.\r\n """\r\n global _CALL_DEPTH\r\n if _CALL_DEPTH >= _MAX_DEPTH:\r\n raise ToolError(\r\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\r\n "a tool calling itself, or two calling each other"\r\n )\r\n\r\n global _CALL_SEQ\r\n _CALL_SEQ += 1\r\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\r\n # two calls in a row could be handed the same token.\r\n token = f"cb{_CALL_SEQ}"\r\n _CALL_DEPTH += 1\r\n try:\r\n _respond(\r\n {\r\n "callback": token,\r\n "method": "call_tool",\r\n "name": name,\r\n "arguments": arguments,\r\n "caller": _CURRENT_TOOL,\r\n }\r\n )\r\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\r\n # protocol error rather than something to skip, so it is reported rather than ignored.\r\n while True:\r\n line = _REAL_STDIN.readline()\r\n if not line:\r\n raise ToolError("the host closed the connection while waiting for " + name)\r\n line = line.strip()\r\n if not line:\r\n continue\r\n frame = json.loads(line)\r\n\r\n if frame.get("callback") == token:\r\n if frame.get("ok"):\r\n return frame.get("value")\r\n raise ToolError(frame.get("error") or f"{name} failed")\r\n\r\n # An ordinary request, arriving while this tool is blocked.\r\n #\r\n # It happens for real: the tool this one called is *another Python tool*, so the host\r\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\r\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\r\n # out-of-order answer, which the first version did, fails every nested call between\r\n # two Python tools. So it is served here and the wait resumes.\r\n if "method" in frame:\r\n request_id = frame.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n continue\r\n\r\n raise ToolError(\r\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\r\n )\r\n finally:\r\n _CALL_DEPTH -= 1\r\n\r\n\r\ndef _install_helper_module() -> None:\r\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\r\n\r\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\r\n an ordinary Python file that must also be readable, lintable and runnable on its own\r\n terms, and magic names appearing from nowhere break every one of those.\r\n """\r\n if "light_code" in sys.modules:\r\n return\r\n module = types.ModuleType("light_code")\r\n module.call_tool = call_tool # type: ignore[attr-defined]\r\n module.ToolError = ToolError # type: ignore[attr-defined]\r\n sys.modules["light_code"] = module\r\n\r\n\r\ndef _load(name: str, path: str) -> Any:\r\n """Imports a tool module from an explicit path, replacing any previous version."""\r\n _install_helper_module()\r\n spec = importlib.util.spec_from_file_location(f"light_code_tool_{name}", path)\r\n if spec is None or spec.loader is None:\r\n raise ImportError(f"could not load {path}")\r\n module = importlib.util.module_from_spec(spec)\r\n # Executed with the tool\'s own stdout captured: a print at import time would otherwise\r\n # land in the middle of the JSON-RPC stream.\r\n with redirect_stdout(io.StringIO()):\r\n spec.loader.exec_module(module)\r\n if not hasattr(module, "run"):\r\n raise AttributeError(f"{path} defines no `run` function")\r\n _MODULES[name] = module\r\n return module\r\n\r\n\r\ndef _google_arg_docs(doc: str) -> dict[str, str]:\r\n """Pulls parameter descriptions out of a Google-style ``Args:`` block.\r\n\r\n Best-effort by design. A missing description costs the model a hint; a parser that threw\r\n would cost it the whole tool.\r\n """\r\n docs: dict[str, str] = {}\r\n match = re.search(r"^\\s*Args:\\s*$(.*?)(?=^\\s*\\w+:\\s*$|\\Z)", doc, re.MULTILINE | re.DOTALL)\r\n if not match:\r\n return docs\r\n for line in match.group(1).splitlines():\r\n entry = re.match(r"\\s*(\\w+)\\s*(?:\\([^)]*\\))?\\s*:\\s*(.+)", line)\r\n if entry:\r\n docs[entry.group(1)] = entry.group(2).strip()\r\n return docs\r\n\r\n\r\n#: Annotations the fallback can map without pydantic. Anything else becomes a string,\r\n#: which is lossy but callable.\r\n_PRIMITIVE_TYPES: dict[Any, str] = {\r\n str: "string",\r\n bool: "boolean",\r\n int: "integer",\r\n float: "number",\r\n list: "array",\r\n dict: "object",\r\n}\r\n\r\n\r\ndef _fallback_schema(run: Any) -> dict[str, Any]:\r\n """Derives a schema from bare annotations, for when pydantic is not installed.\r\n\r\n Worth doing properly rather than declaring everything a string: a ``bool`` advertised as\r\n a string means the model sends ``"true"`` and the tool receives the string ``"true"``,\r\n which is truthy for every value including ``"false"``. Silent, and wrong.\r\n """\r\n signature = inspect.signature(run)\r\n properties: dict[str, Any] = {}\r\n required: list[str] = []\r\n\r\n for name, parameter in signature.parameters.items():\r\n if parameter.kind in (parameter.VAR_POSITIONAL, parameter.VAR_KEYWORD):\r\n continue\r\n annotation = parameter.annotation\r\n # A string annotation appears under `from __future__ import annotations`; resolving\r\n # it properly needs typing.get_type_hints, which can itself fail on a forward ref.\r\n if isinstance(annotation, str):\r\n annotation = {"str": str, "bool": bool, "int": int, "float": float}.get(annotation, inspect.Parameter.empty)\r\n properties[name] = {"type": _PRIMITIVE_TYPES.get(annotation, "string")}\r\n if parameter.default is parameter.empty:\r\n required.append(name)\r\n\r\n return {"type": "object", "properties": properties, "required": required}\r\n\r\n\r\ndef _schema_for(module: Any) -> dict[str, Any]:\r\n """Derives the parameter schema from ``run``\'s type hints.\r\n\r\n pydantic when available, because it handles unions, defaults, nested models and\r\n ``Optional`` correctly. The fallback treats every parameter as a string, which is worse\r\n but still callable \u2014 better than refusing to register a tool because pydantic is missing.\r\n """\r\n run = module.run\r\n try:\r\n from pydantic import TypeAdapter\r\n\r\n schema = TypeAdapter(run).json_schema()\r\n properties = schema.get("properties", {})\r\n except Exception: # noqa: BLE001 - any pydantic failure falls back rather than failing\r\n schema = _fallback_schema(run)\r\n properties = schema["properties"]\r\n\r\n doc = inspect.getdoc(run) or inspect.getdoc(module) or ""\r\n for name, description in _google_arg_docs(doc).items():\r\n if name in properties:\r\n properties[name]["description"] = description\r\n\r\n schema.setdefault("type", "object")\r\n schema["properties"] = properties\r\n return schema\r\n\r\n\r\ndef _describe(name: str, path: str) -> dict[str, Any]:\r\n module = _load(name, path)\r\n # The module docstring, not run\'s: it describes the tool, whereas run\'s docstring\r\n # usually documents the parameters.\r\n description = (inspect.getdoc(module) or inspect.getdoc(module.run) or "").strip()\r\n return {"name": name, "description": description, "schema": _schema_for(module)}\r\n\r\n\r\ndef _handle(request: dict[str, Any]) -> dict[str, Any]:\r\n method = request.get("method")\r\n params = request.get("params") or {}\r\n\r\n if method == "ping":\r\n return {"ok": True, "python": sys.version}\r\n\r\n if method == "describe":\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "validate":\r\n # Parsed before importing, so a syntax error is reported as one rather than as\r\n # whatever the import machinery happens to raise.\r\n source = Path(params["path"]).read_text(encoding="utf-8")\r\n compile(source, params["path"], "exec")\r\n return _describe(params["name"], params["path"])\r\n\r\n if method == "call":\r\n name = params["name"]\r\n # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\r\n # callee is the prompt people click through.\r\n global _CURRENT_TOOL\r\n _CURRENT_TOOL = name\r\n module = _MODULES.get(name)\r\n if module is None:\r\n module = _load(name, params["path"])\r\n # Reloaded when the caller says the file changed, so an edit mid-session takes\r\n # effect without a restart.\r\n if params.get("reload"):\r\n module = _load(name, params["path"])\r\n\r\n captured = io.StringIO()\r\n with redirect_stdout(captured):\r\n result = module.run(**(params.get("arguments") or {}))\r\n printed = captured.getvalue()\r\n return {\r\n "result": result,\r\n # Returned rather than discarded: a print is how people debug, and swallowing it\r\n # makes a misbehaving tool impossible to diagnose from the chat.\r\n "stdout": printed,\r\n }\r\n\r\n raise ValueError(f"unknown method: {method}")\r\n\r\n\r\ndef main() -> None:\r\n for line in sys.stdin:\r\n line = line.strip()\r\n if not line:\r\n continue\r\n try:\r\n request = json.loads(line)\r\n except json.JSONDecodeError:\r\n continue\r\n\r\n request_id = request.get("id")\r\n try:\r\n _respond({"id": request_id, "ok": True, "value": _handle(request)})\r\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\r\n # The traceback is the payload: \xA713 requires a failed tool to return it to the\r\n # model so it can fix its own code, rather than a one-line summary it cannot act on.\r\n _respond(\r\n {\r\n "id": request_id,\r\n "ok": False,\r\n "error": f"{type(error).__name__}: {error}",\r\n "traceback": traceback.format_exc(),\r\n }\r\n )\r\n\r\n\r\nif __name__ == "__main__":\r\n main()\r\n';
|
|
54988
55121
|
|
|
54989
55122
|
// ../../packages/core/dist/python/manager.js
|
|
54990
55123
|
var PythonManager = class {
|
|
@@ -55073,7 +55206,15 @@ var PythonManager = class {
|
|
|
55073
55206
|
cwd: this.options.workspaceRoot,
|
|
55074
55207
|
env: env2,
|
|
55075
55208
|
logger: this.options.logger,
|
|
55076
|
-
timeoutMs: this.timeoutMs
|
|
55209
|
+
timeoutMs: this.timeoutMs,
|
|
55210
|
+
/*
|
|
55211
|
+
* Passed through rather than resolved here.
|
|
55212
|
+
*
|
|
55213
|
+
* The manager has no registry and no approval gate; the host has both. Threading the
|
|
55214
|
+
* function means the rules are decided once, where the information is, instead of this
|
|
55215
|
+
* file growing an opinion about which tools a tool may call.
|
|
55216
|
+
*/
|
|
55217
|
+
...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
|
|
55077
55218
|
});
|
|
55078
55219
|
await this.refresh();
|
|
55079
55220
|
this.ready = true;
|
|
@@ -55239,7 +55380,15 @@ var PythonManager = class {
|
|
|
55239
55380
|
cwd: workspaceRoot,
|
|
55240
55381
|
env: env2,
|
|
55241
55382
|
logger: this.options.logger,
|
|
55242
|
-
timeoutMs: this.timeoutMs
|
|
55383
|
+
timeoutMs: this.timeoutMs,
|
|
55384
|
+
/*
|
|
55385
|
+
* Passed through rather than resolved here.
|
|
55386
|
+
*
|
|
55387
|
+
* The manager has no registry and no approval gate; the host has both. Threading the
|
|
55388
|
+
* function means the rules are decided once, where the information is, instead of this
|
|
55389
|
+
* file growing an opinion about which tools a tool may call.
|
|
55390
|
+
*/
|
|
55391
|
+
...this.options.callTool !== void 0 ? { callTool: this.options.callTool } : {}
|
|
55243
55392
|
});
|
|
55244
55393
|
await this.refresh();
|
|
55245
55394
|
this.ready = true;
|
|
@@ -58987,6 +59136,62 @@ function wireChatBridge(services) {
|
|
|
58987
59136
|
workspaceRoot,
|
|
58988
59137
|
storageDir,
|
|
58989
59138
|
logger,
|
|
59139
|
+
/*
|
|
59140
|
+
* Lets one Python tool call another, or an MCP tool.
|
|
59141
|
+
*
|
|
59142
|
+
* Here rather than in the Python package because this is the only place that can see all
|
|
59143
|
+
* three things the decision needs: the registry, the approval gate, and whether there is
|
|
59144
|
+
* anybody present to answer a prompt. `callPolicy.ts` holds the rule and the reasoning.
|
|
59145
|
+
*/
|
|
59146
|
+
callTool: async (name, args, caller) => {
|
|
59147
|
+
if (!pythonNestedCallsAllowed) {
|
|
59148
|
+
throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
|
|
59149
|
+
}
|
|
59150
|
+
const registry2 = currentToolRegistry();
|
|
59151
|
+
const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
|
|
59152
|
+
if (tool === void 0) {
|
|
59153
|
+
throw new Error(`There is no tool called "${name}". Settings \u2192 Tools lists everything callable; an MCP tool is named with its server, like \`filesystem__read_file\`.`);
|
|
59154
|
+
}
|
|
59155
|
+
if (!mayPythonToolCall(tool.name, tool.group))
|
|
59156
|
+
throw new Error(PYTHON_CALL_DENIED);
|
|
59157
|
+
const context = pythonNestedContext;
|
|
59158
|
+
if (context === void 0) {
|
|
59159
|
+
throw new Error("No turn is in progress, so there is nothing to run this against.");
|
|
59160
|
+
}
|
|
59161
|
+
let preview;
|
|
59162
|
+
try {
|
|
59163
|
+
preview = await tool.preview?.(args, context) ?? {
|
|
59164
|
+
kind: "text",
|
|
59165
|
+
text: `${tool.name}(${JSON.stringify(args, null, 2)})`
|
|
59166
|
+
};
|
|
59167
|
+
} catch (error51) {
|
|
59168
|
+
preview = {
|
|
59169
|
+
kind: "text",
|
|
59170
|
+
text: `${tool.name}(${JSON.stringify(args, null, 2)})
|
|
59171
|
+
|
|
59172
|
+
Could not preview this: ${error51 instanceof Error ? error51.message : String(error51)}`
|
|
59173
|
+
};
|
|
59174
|
+
}
|
|
59175
|
+
const decision = await approvalGate.requestApproval({
|
|
59176
|
+
id: `py-nested-${String(Date.now())}-${tool.name}`,
|
|
59177
|
+
toolName: tool.name,
|
|
59178
|
+
group: tool.group,
|
|
59179
|
+
preview: {
|
|
59180
|
+
...preview,
|
|
59181
|
+
// Says who is asking. "Allow filesystem__write_file?" with no indication of who wants
|
|
59182
|
+
// it is exactly the prompt people click through.
|
|
59183
|
+
...preview.kind === "text" ? { text: `${describeNestedCall(caller, tool.name)}
|
|
59184
|
+
|
|
59185
|
+
${preview.text}` } : {}
|
|
59186
|
+
}
|
|
59187
|
+
});
|
|
59188
|
+
if (decision !== "approve")
|
|
59189
|
+
throw new Error(`The user did not allow "${tool.name}" to run.`);
|
|
59190
|
+
const result = await tool.execute(args, context);
|
|
59191
|
+
if (result.isError === true)
|
|
59192
|
+
throw new Error(String(result.content));
|
|
59193
|
+
return result.content;
|
|
59194
|
+
},
|
|
58990
59195
|
// Read at worker spawn, so a changed variable applies to the next worker rather than being
|
|
58991
59196
|
// frozen at construction. Added to the allowlist in minimalPythonEnv, never a way past it.
|
|
58992
59197
|
...services.sessionEnv !== void 0 ? { sessionEnv: services.sessionEnv } : {},
|
|
@@ -59006,6 +59211,7 @@ function wireChatBridge(services) {
|
|
|
59006
59211
|
void postPython();
|
|
59007
59212
|
void postSchedules();
|
|
59008
59213
|
void postTools();
|
|
59214
|
+
void postDatasetStatus();
|
|
59009
59215
|
}
|
|
59010
59216
|
});
|
|
59011
59217
|
const defaultSkillsDir = workspaceRoot !== void 0 ? path23.join(workspaceRoot, ".lightcode", "skills") : void 0;
|
|
@@ -59225,6 +59431,8 @@ function wireChatBridge(services) {
|
|
|
59225
59431
|
let backgroundRun = false;
|
|
59226
59432
|
let userTurnRunning = false;
|
|
59227
59433
|
let scheduledRunInFlight;
|
|
59434
|
+
let pythonNestedContext;
|
|
59435
|
+
let pythonNestedCallsAllowed = false;
|
|
59228
59436
|
const MENTION_SCAN_LIMIT = 2e3;
|
|
59229
59437
|
const MENTION_RESULT_LIMIT = 30;
|
|
59230
59438
|
let scheduleToolAccess;
|
|
@@ -59581,6 +59789,7 @@ function wireChatBridge(services) {
|
|
|
59581
59789
|
postMcp();
|
|
59582
59790
|
void postSchedules();
|
|
59583
59791
|
void postTools();
|
|
59792
|
+
void postDatasetStatus();
|
|
59584
59793
|
scheduleDocsReindex("MCP tools changed");
|
|
59585
59794
|
}
|
|
59586
59795
|
}, logger, () => cachedApprovals.allowedTools ?? [], () => cachedToolTimeoutSeconds);
|
|
@@ -60042,6 +60251,8 @@ function wireChatBridge(services) {
|
|
|
60042
60251
|
// lives in the VSIX, so resolving it is a host concern (§4).
|
|
60043
60252
|
...ripgrepPath !== void 0 ? { ripgrepPath } : {}
|
|
60044
60253
|
};
|
|
60254
|
+
pythonNestedContext = toolContext;
|
|
60255
|
+
pythonNestedCallsAllowed = schedule === void 0;
|
|
60045
60256
|
const mentions = await resolveMentions(text, { fs: toolContext.fs, workspaceRoot, denylist });
|
|
60046
60257
|
const messageText = attachMentions(text, mentions);
|
|
60047
60258
|
const turnOptions = {
|
|
@@ -61098,6 +61309,9 @@ function wireChatBridge(services) {
|
|
|
61098
61309
|
* is the `py__` prefix and the mcp group, not a permission category. Reported as the picker
|
|
61099
61310
|
* listing only built-in tools.
|
|
61100
61311
|
*/
|
|
61312
|
+
stores: Object.entries(config2.vectorStores ?? {}).map(([id, store]) => ({ id, label: store.label })),
|
|
61313
|
+
// Resolved here, where the fallback chain lives. See the note on the message.
|
|
61314
|
+
defaultStoreLabel: (await resolveDatasetSearch(config2).catch(() => void 0))?.store.label ?? "none",
|
|
61101
61315
|
tools: currentToolRegistry().list().filter((tool) => tool.name.startsWith("py__") || tool.group === "mcp").map((tool) => ({
|
|
61102
61316
|
name: tool.name,
|
|
61103
61317
|
description: tool.description,
|
|
@@ -62003,6 +62217,9 @@ function wireChatBridge(services) {
|
|
|
62003
62217
|
...saved.uvPath !== void 0 ? { uvPath: saved.uvPath } : {},
|
|
62004
62218
|
...saved.toolsDir !== void 0 ? { toolsDir: saved.toolsDir } : {},
|
|
62005
62219
|
...saved.venvPath !== void 0 ? { venvPath: saved.venvPath } : {},
|
|
62220
|
+
...saved.interpreterPath !== void 0 ? { interpreterPath: saved.interpreterPath } : {},
|
|
62221
|
+
// Sent so nothing the form cannot edit is invisible *and* silently rewritten.
|
|
62222
|
+
...saved.extraIndexUrls !== void 0 ? { extraIndexUrls: saved.extraIndexUrls } : {},
|
|
62006
62223
|
...saved.indexUrl !== void 0 ? { indexUrl: saved.indexUrl } : {},
|
|
62007
62224
|
...saved.offline !== void 0 ? { offline: saved.offline } : {},
|
|
62008
62225
|
...saved.timeoutSeconds !== void 0 ? { timeoutSeconds: saved.timeoutSeconds } : {},
|
|
@@ -62014,16 +62231,26 @@ function wireChatBridge(services) {
|
|
|
62014
62231
|
}
|
|
62015
62232
|
async function handleSetPython(input) {
|
|
62016
62233
|
try {
|
|
62234
|
+
const existing = (await configManager.load()).config.python ?? {};
|
|
62017
62235
|
await configManager.save("user", {
|
|
62018
62236
|
python: {
|
|
62237
|
+
...existing,
|
|
62019
62238
|
dynamicTools: input.dynamicTools,
|
|
62020
|
-
...input.uvPath !== void 0
|
|
62239
|
+
...input.uvPath !== void 0 ? input.uvPath.length > 0 ? { uvPath: input.uvPath } : { uvPath: void 0 } : {},
|
|
62021
62240
|
// Absent rather than empty when cleared, so the manager falls back to
|
|
62022
62241
|
// `.lightcode/tools` instead of resolving an empty string against the workspace.
|
|
62023
|
-
...input.toolsDir !== void 0
|
|
62024
|
-
|
|
62242
|
+
...input.toolsDir !== void 0 ? input.toolsDir.trim().length > 0 ? { toolsDir: input.toolsDir.trim() } : { toolsDir: void 0 } : {},
|
|
62243
|
+
/*
|
|
62244
|
+
* Cleared means cleared, which is why each of these deletes rather than omitting.
|
|
62245
|
+
*
|
|
62246
|
+
* With the spread of `existing` above, omitting a blank field would *keep* the old
|
|
62247
|
+
* value — so emptying the box would appear to do nothing. The three-way distinction
|
|
62248
|
+
* matters: a field the form did not send is kept, a field it sent empty is removed.
|
|
62249
|
+
*/
|
|
62250
|
+
...input.venvPath !== void 0 ? input.venvPath.trim().length > 0 ? { venvPath: input.venvPath.trim() } : { venvPath: void 0 } : {},
|
|
62251
|
+
...input.interpreterPath !== void 0 ? input.interpreterPath.trim().length > 0 ? { interpreterPath: input.interpreterPath.trim() } : { interpreterPath: void 0 } : {},
|
|
62025
62252
|
...input.timeoutSeconds !== void 0 ? { timeoutSeconds: input.timeoutSeconds } : {},
|
|
62026
|
-
...input.indexUrl !== void 0
|
|
62253
|
+
...input.indexUrl !== void 0 ? input.indexUrl.length > 0 ? { indexUrl: input.indexUrl } : { indexUrl: void 0 } : {},
|
|
62027
62254
|
...input.offline !== void 0 ? { offline: input.offline } : {}
|
|
62028
62255
|
}
|
|
62029
62256
|
});
|
|
@@ -64869,6 +65096,17 @@ ${entry.record.text}`.toLowerCase();
|
|
|
64869
65096
|
};
|
|
64870
65097
|
}
|
|
64871
65098
|
|
|
65099
|
+
// ../../packages/core/dist/python/callPolicy.js
|
|
65100
|
+
var PYTHON_CALL_DENIED = "A Python tool may only call other Python tools and MCP tools. Built-in tools \u2014 running commands, editing files, creating tools or writing skills \u2014 are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.";
|
|
65101
|
+
function mayPythonToolCall(name, group) {
|
|
65102
|
+
if (name.startsWith("py__"))
|
|
65103
|
+
return true;
|
|
65104
|
+
return group === "mcp";
|
|
65105
|
+
}
|
|
65106
|
+
function describeNestedCall(caller, callee) {
|
|
65107
|
+
return `The Python tool "${caller}" is asking to call "${callee}".`;
|
|
65108
|
+
}
|
|
65109
|
+
|
|
64872
65110
|
// src/identity.ts
|
|
64873
65111
|
import crypto5 from "node:crypto";
|
|
64874
65112
|
var SingleUserIdentity = class _SingleUserIdentity {
|
|
@@ -64949,6 +65187,13 @@ function timingSafeEquals(a, b) {
|
|
|
64949
65187
|
function storageKeyFor(principal) {
|
|
64950
65188
|
return crypto5.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
|
|
64951
65189
|
}
|
|
65190
|
+
var OpenIdentity = class _OpenIdentity {
|
|
65191
|
+
describe = "single user, no token (--no-token)";
|
|
65192
|
+
static PRINCIPAL = { id: "local", displayName: "Local user" };
|
|
65193
|
+
async authenticate() {
|
|
65194
|
+
return _OpenIdentity.PRINCIPAL;
|
|
65195
|
+
}
|
|
65196
|
+
};
|
|
64952
65197
|
|
|
64953
65198
|
// src/roles.ts
|
|
64954
65199
|
var ADMIN_ONLY_MESSAGES = [
|
|
@@ -65695,7 +65940,7 @@ var CONTENT_TYPES = {
|
|
|
65695
65940
|
async function startServer(options) {
|
|
65696
65941
|
const log = options.logSink ?? ((line) => process.stderr.write(`${line}
|
|
65697
65942
|
`));
|
|
65698
|
-
const identity = options.identity ?? new SingleUserIdentity(options.handoffSeconds);
|
|
65943
|
+
const identity = options.identity ?? (options.noToken === true ? new OpenIdentity() : new SingleUserIdentity(options.handoffSeconds));
|
|
65699
65944
|
const roles = options.roles ?? SINGLE_USER_POLICY;
|
|
65700
65945
|
const sharedStore = options.sharedConfig;
|
|
65701
65946
|
const sharedSecretStore = new FileSecretStore(path30.join(options.dataDir, "shared-secrets.json"));
|
|
@@ -65806,6 +66051,10 @@ async function startServer(options) {
|
|
|
65806
66051
|
return;
|
|
65807
66052
|
}
|
|
65808
66053
|
if (url2.pathname === "/api/session" && request.method === "POST") {
|
|
66054
|
+
if (identity instanceof OpenIdentity) {
|
|
66055
|
+
respondJson(response, 200, { token: "" });
|
|
66056
|
+
return;
|
|
66057
|
+
}
|
|
65809
66058
|
if (!(identity instanceof SingleUserIdentity)) {
|
|
65810
66059
|
reject(response, { status: 404, reason: "Handoff is only used in single-user mode." });
|
|
65811
66060
|
return;
|