@chosengeneration/light-code 0.164.0 → 0.165.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.cjs +59 -19
- package/dist/server.cjs +57 -17
- package/package.json +1 -1
package/dist/server.cjs
CHANGED
|
@@ -61783,7 +61783,7 @@ The module "${module2}" is not installed in the tools' Python environment, and L
|
|
|
61783
61783
|
}
|
|
61784
61784
|
|
|
61785
61785
|
// ../../packages/core/dist/python/workerSource.js
|
|
61786
|
-
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 ast\nimport importlib.util\nimport inspect\nimport io\nimport json\nimport os\nimport re\nimport sys\nimport time\nimport traceback\nimport types\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_REAL_STDIN = sys.stdin\n\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\n_CALL_DEPTH = 0\n_MAX_DEPTH = 4\n_CURRENT_TOOL = ""\n_CALL_SEQ = 0\n\n\nclass ToolError(RuntimeError):\n """A tool this one called came back with a failure."""\n\n\ndef call_tool(name: str, **arguments: Any) -> Any:\n """Calls another tool and returns its result.\n\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\n tools can be reached; see the host for why.\n\n This blocks the worker, which is correct: the tool asked for something and cannot\n continue without it. The host may prompt the user before running it, so it can take as\n long as a person takes to answer.\n """\n global _CALL_DEPTH\n if _CALL_DEPTH >= _MAX_DEPTH:\n raise ToolError(\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\n "a tool calling itself, or two calling each other"\n )\n\n _CALL_DEPTH += 1\n try:\n return _ask_host({"method": "call_tool", "name": name, "arguments": arguments}, name)\n finally:\n _CALL_DEPTH -= 1\n\n\ndef credential(name: str) -> Any:\n """A saved credential from Fire Code\'s credential manager, by its name.\n\n Returns the value as a string, or ``{"username": ..., "password": ...}`` for a login.\n\n Only credentials this tool declares are given, in a module-level list::\n\n __credentials__ = ["Corp LDAP", "Jira token"]\n\n That line is part of the code you approved, so adding a credential means approving the tool\n again. Nothing is put in the environment, and any value handed out is blanked from what the\n tool returns before the model sees it. Raises ToolError with the reason when refused.\n """\n return _ask_host({"method": "credential", "name": name}, f"credential {name!r}")\n\n\ndef _ask_host(payload: dict, name: str) -> Any:\n """Sends one request up to the host and waits for its answer, serving nested requests."""\n global _CALL_SEQ\n _CALL_SEQ += 1\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\n # two calls in a row could be handed the same token.\n token = f"cb{_CALL_SEQ}"\n _respond({"callback": token, "caller": _CURRENT_TOOL, **payload})\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\n # protocol error rather than something to skip, so it is reported rather than ignored.\n while True:\n line = _REAL_STDIN.readline()\n if not line:\n raise ToolError("the host closed the connection while waiting for " + name)\n line = line.strip()\n if not line:\n continue\n frame = json.loads(line)\n\n if frame.get("callback") == token:\n if frame.get("ok"):\n return frame.get("value")\n raise ToolError(frame.get("error") or f"{name} failed")\n\n # An ordinary request, arriving while this tool is blocked.\n #\n # It happens for real: the tool this one called is *another Python tool*, so the host\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\n # out-of-order answer, which the first version did, fails every nested call between\n # two Python tools. So it is served here and the wait resumes.\n if "method" in frame:\n request_id = frame.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\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 continue\n\n raise ToolError(\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\n )\n\n\ndef _install_helper_module() -> None:\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\n\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\n an ordinary Python file that must also be readable, lintable and runnable on its own\n terms, and magic names appearing from nowhere break every one of those.\n """\n if "light_code" in sys.modules:\n return\n module = types.ModuleType("light_code")\n module.call_tool = call_tool # type: ignore[attr-defined]\n module.credential = credential # type: ignore[attr-defined]\n module.ToolError = ToolError # type: ignore[attr-defined]\n sys.modules["light_code"] = module\n\n\n# --- running in somebody\'s live Jupyter kernel ---------------------------------------------\n#\n# Requested so that a notebook can drive Light Code and have its tools see the session\'s own\n# state - the dataframe that is already loaded, the model that took ten minutes to fit.\n#\n# ## Why the kernel is named to us rather than discovered by us\n#\n# A kernel knows its own connection file (``ipykernel.get_connection_file()``); nothing outside\n# it does. From another process all you can do is list ``<runtime-dir>/kernel-*.json`` and\n# guess, and with more than one kernel running - the ordinary case for anybody who uses\n# Jupyter - a guess means running somebody\'s tool inside the wrong notebook. That is the same\n# refusal the Excel tools make about attaching: answering "the session I have open" with a\n# different one is worse than asking.\n#\n# So the connection file arrives in ``LIGHT_CODE_JUPYTER_CONNECTION_FILE``, and the host has a\n# discovery helper that only ever *offers* candidates.\n#\n# ## Why the result comes back behind a marker\n#\n# The same reason the identity and credential wrappers do it (CLAUDE.md section 14): a kernel\n# is full of libraries that print. Licence banners, deprecation warnings and progress bars all\n# arrive on the same channel as the answer, and reading "the output" would hand back a log line\n# while looking like it had worked.\n\n_KERNEL_MARKER = "__LIGHT_CODE_RESULT__"\n_kernel_client: Any = None\n\n\ndef _kernel_connection_file() -> str:\n return (os.environ.get("LIGHT_CODE_JUPYTER_CONNECTION_FILE") or "").strip()\n\n\ndef _kernel() -> Any:\n """The client for the configured kernel, connected once and kept.\n\n Reconnecting per call would pay the handshake every time and, worse, would lose the\n channel\'s message ordering guarantees mid-conversation.\n """\n global _kernel_client\n if _kernel_client is not None:\n return _kernel_client\n\n connection_file = _kernel_connection_file()\n if not connection_file:\n raise RuntimeError("no Jupyter kernel is configured for this session")\n if not Path(connection_file).exists():\n raise RuntimeError(\n f"the kernel connection file is gone: {connection_file}. The kernel it described "\n "has probably been shut down or restarted - restart the notebook\'s Light Code "\n "session so it picks up the new one."\n )\n\n try:\n from jupyter_client import BlockingKernelClient\n except ImportError as error:\n raise RuntimeError(\n "running tools in a Jupyter kernel needs jupyter_client, which is not importable "\n "from this interpreter. It ships with Jupyter, so install it into the same "\n "environment the kernel runs in: pip install jupyter_client"\n ) from error\n\n client = BlockingKernelClient()\n client.load_connection_file(connection_file)\n client.start_channels()\n try:\n # Proves the kernel is actually there before any tool is run. Without it the first\n # failure is a silent timeout in the middle of somebody\'s tool, which reads as the tool\n # hanging rather than as the kernel being gone.\n client.wait_for_ready(timeout=20)\n except RuntimeError as error:\n client.stop_channels()\n raise RuntimeError(\n f"connected to the kernel described by {connection_file} but it never became "\n "ready. It may be busy running a cell, or it may have died."\n ) from error\n\n _kernel_client = client\n # Sent here, on the one path that produces a connected client.\n #\n # The first version defined `_kernel_preamble` and never called it, so every tool call\n # arrived at a kernel that had never heard of `_lc_json` and failed with a NameError on\n # line 1. Nothing in the TypeScript, the schema or the wiring was wrong, and no test of\n # any of them could have seen it - it took starting a real kernel and asking it. That is\n # the same shape as `s3.tools` shipping with nothing on the other end.\n _kernel_run(client, _kernel_preamble(), timeout=30)\n return client\n\n\ndef _kernel_preamble() -> str:\n """Code run in the kernel before any tool is, exactly once.\n\n Everything it defines is prefixed and kept in one dict, because this is *somebody\'s\n notebook*: a bare ``json`` or ``run`` left in their globals would shadow their own name and\n break a cell they wrote, a long way from anything they would connect to us.\n\n ## It also installs ``light_code`` in the kernel, and that is not optional\n\n A tool written against ``light_code.call_tool`` imports that module. The worker registers\n it in *its own* ``sys.modules``, which the kernel has never heard of - so without this,\n moving a tool into a kernel turns a working tool into an ImportError whose message points\n at the tool rather than at the move. Found by running it, not by reading it.\n\n ``call_tool`` raises there rather than working, and says why: the callback rides on this\n worker\'s stdio and the kernel has no route back to the host. An honest refusal beats a\n name that exists and hangs.\n\n ``session`` is the point of the whole feature - it *is* the notebook\'s namespace, so a\n tool can read the dataframe that is already loaded.\n """\n return (\n "import json as _lc_json, io as _lc_io, pathlib as _lc_path, sys as _lc_sys, "\n "types as _lc_types, traceback as _lc_tb\\n"\n "from contextlib import redirect_stdout as _lc_redirect\\n"\n "_lc_tools = globals().setdefault(\'_lc_tools\', {})\\n"\n "if \'light_code\' not in _lc_sys.modules:\\n"\n " _lc_helper = _lc_types.ModuleType(\'light_code\')\\n"\n " _lc_helper.session = globals()\\n"\n " class _LcToolError(RuntimeError):\\n"\n " pass\\n"\n " def _lc_no_call(*_a, **_k):\\n"\n " raise _LcToolError(\'call_tool is not available to a tool running inside "\n "a Jupyter kernel: the callback channel belongs to the Light Code worker, and the "\n "kernel has no route back to the host.\')\\n"\n " _lc_helper.call_tool = _lc_no_call\\n"\n " def _lc_no_credential(*_a, **_k):\\n"\n " raise _LcToolError(\'credential() is not available to a tool running inside a "\n "Jupyter kernel: the request would have no route back to the host.\')\\n"\n " _lc_helper.credential = _lc_no_credential\\n"\n " _lc_helper.ToolError = _LcToolError\\n"\n " _lc_sys.modules[\'light_code\'] = _lc_helper\\n"\n )\n\n\ndef _kernel_call_code(name: str, path: str, arguments: dict[str, Any], reload: bool) -> str:\n """The code sent to the kernel for one tool call.\n\n The tool\'s source is executed **in the kernel**, so its imports resolve against the\n kernel\'s environment and its ``run`` sees the kernel\'s globals if it asks for them. The\n module is cached there between calls, and reloaded on the same signal the local path uses.\n """\n payload = json.dumps(\n {"name": name, "path": path, "arguments": arguments, "reload": bool(reload)}\n )\n # A single JSON literal rather than interpolated values: every one of these is\n # model-supplied, and building source by concatenation is how a quote in an argument\n # becomes a syntax error at best (CLAUDE.md section 16\'s rule, applied to code rather than\n # to a command line).\n return (\n f"_lc_req = _lc_json.loads({payload!r})\\n"\n "_lc_out = _lc_io.StringIO()\\n"\n "try:\\n"\n " if _lc_req[\'reload\'] or _lc_req[\'name\'] not in _lc_tools:\\n"\n " _lc_mod = _lc_types.ModuleType(\'light_code_tool_\' + _lc_req[\'name\'])\\n"\n " _lc_mod.__file__ = _lc_req[\'path\']\\n"\n # The notebook\'s own namespace, as a module-level name, so the simplest possible\n # tool - `session[\'df\']` - needs no import at all. This is the whole feature.\n " _lc_mod.session = globals()\\n"\n " _lc_src = _lc_path.Path(_lc_req[\'path\']).read_text(encoding=\'utf-8\')\\n"\n " with _lc_redirect(_lc_out):\\n"\n " exec(compile(_lc_src, _lc_req[\'path\'], \'exec\'), _lc_mod.__dict__)\\n"\n " if not hasattr(_lc_mod, \'run\'):\\n"\n " raise AttributeError(_lc_req[\'path\'] + \' defines no `run` function\')\\n"\n " _lc_tools[_lc_req[\'name\']] = _lc_mod\\n"\n " with _lc_redirect(_lc_out):\\n"\n " _lc_value = _lc_tools[_lc_req[\'name\']].run(**_lc_req[\'arguments\'])\\n"\n " try:\\n"\n " _lc_json.dumps(_lc_value)\\n"\n " _lc_payload = {\'ok\': True, \'result\': _lc_value, "\n "\'stdout\': _lc_out.getvalue()}\\n"\n " except TypeError:\\n"\n # A DataFrame, a model, a connection - returned rather than refused. `repr` is what a\n # notebook would have shown, and losing the answer because it does not serialise would\n # be the worst outcome of a feature whose point is reaching live objects.\n " _lc_payload = {\'ok\': True, \'result\': repr(_lc_value), \'repr\': True, "\n "\'stdout\': _lc_out.getvalue()}\\n"\n "except Exception as _lc_err:\\n"\n " _lc_payload = {\'ok\': False, \'error\': type(_lc_err).__name__ + \': \' + str(_lc_err), "\n "\'traceback\': _lc_tb.format_exc(), \'stdout\': _lc_out.getvalue()}\\n"\n f"print({_KERNEL_MARKER!r} + _lc_json.dumps(_lc_payload))\\n"\n )\n\n\ndef _kernel_execute(code: str, timeout: float) -> dict[str, Any]:\n """Runs code in the kernel and reads back the marked result.\n\n Output that is not the marker is the kernel\'s own chatter and is kept separately, so a\n library\'s banner is never mistaken for the answer.\n """\n return _kernel_run(_kernel(), code, timeout)\n\n\ndef _kernel_run(client: Any, code: str, timeout: float) -> dict[str, Any]:\n """The same, against a client already in hand.\n\n Split out so the preamble can be sent from inside ``_kernel`` - going through\n ``_kernel_execute`` there would call back into ``_kernel`` before it had returned.\n """\n msg_id = client.execute(code, store_history=False)\n\n answer: dict[str, Any] | None = None\n chatter: list[str] = []\n deadline = time.monotonic() + timeout\n\n while True:\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\n "the kernel did not answer in time. It is probably busy running a cell - a "\n "kernel runs one thing at a time, so a tool waits for whatever is already going."\n )\n try:\n message = client.get_iopub_msg(timeout=min(remaining, 1.0))\n except Exception: # noqa: BLE001 - an empty queue is the ordinary case, so poll again\n continue\n\n if message.get("parent_header", {}).get("msg_id") != msg_id:\n # Somebody else\'s cell. Ignored rather than read: this is a shared kernel and the\n # user is still using it.\n continue\n\n kind = message.get("msg_type")\n content = message.get("content", {})\n if kind == "stream":\n for line in content.get("text", "").splitlines():\n if line.startswith(_KERNEL_MARKER):\n answer = json.loads(line[len(_KERNEL_MARKER):])\n else:\n chatter.append(line)\n elif kind == "error":\n # Raised *before* the tool\'s own code could print the marker: a bad compile, or the\n # kernel dying. The tool\'s own exceptions come back inside the payload instead.\n raise RuntimeError(\n "the kernel refused the call: " + "\\n".join(content.get("traceback", []))\n )\n elif kind == "status" and content.get("execution_state") == "idle":\n break\n\n if answer is None:\n if _KERNEL_MARKER not in code:\n # Setup rather than a call: it is not meant to print anything.\n return {}\n raise RuntimeError(\n "the kernel finished without returning a result. If it was restarted mid-call, "\n "reconnect the notebook\'s Light Code session."\n )\n if chatter:\n answer["stdout"] = (answer.get("stdout") or "") + "\\n".join(chatter)\n return answer\n\n\ndef _banned() -> list[str]:\n """The calls no tool may use, set in Settings -> Python (python.bannedCalls)."""\n try:\n listed = json.loads(os.environ.get("LIGHT_CODE_BANNED_CALLS", "[]"))\n except ValueError:\n return []\n return [str(entry).strip() for entry in listed if str(entry).strip()]\n\n\ndef banned_uses(source: str, banned: list[str]) -> list[str]:\n """Where a tool\'s code uses a banned function or module, as \'line N: name\' - empty when it does not.\n\n Read with Python\'s own parser, so comments and strings never count and aliases are followed:\n ``import certainLib as c`` then ``c.certainFunction(...)``, ``from certainLib import\n certainFunction as f``, a reference passed along without being called, ``getattr(c, "name")``,\n and ``importlib.import_module("certainLib")``. An entry naming a module bans all of it.\n """\n if not banned:\n return []\n tree = ast.parse(source)\n aliases: dict[str, str] = {}\n found: list[str] = []\n\n def hit(dotted: str) -> str | None:\n for entry in banned:\n if dotted == entry or dotted.startswith(entry + "."):\n return entry\n return None\n\n def report(node: ast.AST, dotted: str) -> None:\n entry = hit(dotted)\n if entry is not None:\n found.append(f"line {getattr(node, \'lineno\', \'?\')}: {dotted}" + (f" (banned: {entry})" if entry != dotted else ""))\n\n for node in ast.walk(tree):\n if isinstance(node, ast.Import):\n for name in node.names:\n aliases[name.asname or name.name.split(".")[0]] = name.name if name.asname else name.name.split(".")[0]\n report(node, name.name)\n elif isinstance(node, ast.ImportFrom) and node.module:\n for name in node.names:\n if name.name == "*":\n if any(entry.startswith(node.module + ".") for entry in banned):\n found.append(f"line {node.lineno}: from {node.module} import * (could reach a banned name)")\n continue\n aliases[name.asname or name.name] = f"{node.module}.{name.name}"\n report(node, f"{node.module}.{name.name}")\n\n def dotted_of(node: ast.AST) -> str | None:\n if isinstance(node, ast.Name):\n return aliases.get(node.id, node.id)\n if isinstance(node, ast.Attribute):\n base = dotted_of(node.value)\n return f"{base}.{node.attr}" if base is not None else None\n return None\n\n for node in ast.walk(tree):\n if isinstance(node, ast.Attribute) or (isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)):\n dotted = dotted_of(node)\n # Only the outermost attribute of a chain is reported, so c.f.g is one finding, not three.\n if dotted is not None and not isinstance(getattr(node, "_lc_parent", None), ast.Attribute):\n report(node, dotted)\n # A module imported by name at run time: importlib.import_module("x"), __import__("x").\n if (\n isinstance(node, ast.Call)\n and dotted_of(node.func) in ("importlib.import_module", "__import__")\n and node.args\n and isinstance(node.args[0], ast.Constant)\n and isinstance(node.args[0].value, str)\n ):\n report(node, node.args[0].value)\n # An attribute fetched by name: getattr(c, "certainFunction").\n if isinstance(node, ast.Call) and dotted_of(node.func) == "getattr" and len(node.args) > 1:\n base = dotted_of(node.args[0])\n attr = node.args[1]\n if base is not None and isinstance(attr, ast.Constant) and isinstance(attr.value, str):\n report(node, f"{base}.{attr.value}")\n for child in ast.iter_child_nodes(node):\n child._lc_parent = node # type: ignore[attr-defined]\n # One line each, in source order, without repeats.\n return sorted(set(found), key=lambda line: int(line.split()[1].rstrip(":")) if line.split()[1].rstrip(":").isdigit() else 0)\n\n\ndef _check_banned(path: str) -> None:\n """Refuses a tool whose code uses a banned call, naming each use."""\n banned = _banned()\n if not banned:\n return\n uses = banned_uses(Path(path).read_text(encoding="utf-8"), banned)\n if uses:\n raise PermissionError(\n "This tool uses calls that are banned in Settings -> Python (Banned calls), so it is not loaded: "\n + "; ".join(uses)\n + ". Rewrite it without them."\n )\n\n\ndef _load(name: str, path: str) -> Any:\n """Imports a tool module from an explicit path, replacing any previous version."""\n _check_banned(path)\n _install_helper_module()\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 connection_file = _kernel_connection_file()\n # Reported rather than merely configured, so the Python tab can say *which* kernel\n # tools run in. "It is using my notebook" is not something anybody should have to\n # infer from a tool seeing a variable it should not have.\n return {\n "ok": True,\n "python": sys.version,\n **({"jupyterConnectionFile": connection_file} if connection_file else {}),\n }\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 # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\n # callee is the prompt people click through.\n global _CURRENT_TOOL\n _CURRENT_TOOL = name\n\n # Before either place it could run: a banned call is refused in a kernel as much as here.\n _check_banned(params["path"])\n if _kernel_connection_file():\n """Run it where the user\'s own session is.\n\n The whole call goes over, source and all, so the tool\'s imports resolve against\n the kernel\'s environment rather than this one - which is the point: the notebook\n has the libraries and the loaded data, and this process has neither.\n\n The registry is unchanged by this. A tool still had to be approved here, with its\n source shown, before it could ever be called - so running it elsewhere widens\n where the code runs and not who may run it.\n """\n answer = _kernel_execute(\n _kernel_call_code(\n name,\n params["path"],\n params.get("arguments") or {},\n bool(params.get("reload")),\n ),\n # Generous, and bounded anyway by the host\'s own per-tool timeout. A kernel\n # runs one thing at a time, so a tool legitimately waits behind whatever cell\n # the user just ran.\n timeout=float(params.get("timeoutSeconds") or 600),\n )\n if not answer.get("ok"):\n # Re-raised rather than returned, so it reaches the model as a failure with a\n # traceback exactly as a local one does. Section 13 wants the traceback: it is\n # what lets the model fix its own code.\n error = RuntimeError(answer.get("error") or "the tool failed in the kernel")\n error.kernel_traceback = answer.get("traceback") # type: ignore[attr-defined]\n raise error\n return {\n "result": answer.get("result"),\n "stdout": answer.get("stdout") or "",\n "ranInKernel": True,\n # Said out loud when the value could not be JSON, so nobody reads a repr as\n # the structure it is a picture of.\n **({"resultIsRepr": True} if answer.get("repr") else {}),\n }\n\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 # The kernel\'s own traceback when the failure happened there. Ours would\n # be a stack through this file, which says nothing about the tool and is\n # the one thing section 13 wants the model to be able to act on.\n "traceback": getattr(error, "kernel_traceback", None)\n or traceback.format_exc(),\n }\n )\n\n\nif __name__ == "__main__":\n main()\n';
|
|
61786
|
+
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 ast\nimport importlib.util\nimport inspect\nimport io\nimport json\nimport os\nimport re\nimport sys\nimport time\nimport traceback\nimport types\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_REAL_STDIN = sys.stdin\n\n# Counts nested calls out to the host, so a loop is stopped rather than left to fill the pipe.\n_CALL_DEPTH = 0\n_MAX_DEPTH = 4\n_CURRENT_TOOL = ""\n_CALL_SEQ = 0\n\n\nclass ToolError(RuntimeError):\n """A tool this one called came back with a failure."""\n\n\ndef call_tool(name: str, **arguments: Any) -> Any:\n """Calls another tool and returns its result.\n\n Available to every tool as ``light_code.call_tool``. Only other Python tools and MCP\n tools can be reached; see the host for why.\n\n This blocks the worker, which is correct: the tool asked for something and cannot\n continue without it. The host may prompt the user before running it, so it can take as\n long as a person takes to answer.\n """\n global _CALL_DEPTH\n if _CALL_DEPTH >= _MAX_DEPTH:\n raise ToolError(\n f"tool calls are nested {_MAX_DEPTH} deep, which is almost certainly a loop - "\n "a tool calling itself, or two calling each other"\n )\n\n _CALL_DEPTH += 1\n try:\n return _ask_host({"method": "call_tool", "name": name, "arguments": arguments}, name)\n finally:\n _CALL_DEPTH -= 1\n\n\ndef credential(name: str) -> Any:\n """A saved credential from Fire Code\'s credential manager, by its name.\n\n Returns the value as a string, or ``{"username": ..., "password": ...}`` for a login.\n\n Only credentials this tool declares are given, in a module-level list::\n\n __credentials__ = ["Corp LDAP", "Jira token"]\n\n That line is part of the code you approved, so adding a credential means approving the tool\n again. Nothing is put in the environment, and any value handed out is blanked from what the\n tool returns before the model sees it. Raises ToolError with the reason when refused.\n """\n return _ask_host({"method": "credential", "name": name}, f"credential {name!r}")\n\n\ndef _ask_host(payload: dict, name: str) -> Any:\n """Sends one request up to the host and waits for its answer, serving nested requests."""\n global _CALL_SEQ\n _CALL_SEQ += 1\n # A counter, not ``id()``: CPython reuses an address the moment the object is collected, so\n # two calls in a row could be handed the same token.\n token = f"cb{_CALL_SEQ}"\n _respond({"callback": token, "caller": _CURRENT_TOOL, **payload})\n # Read until the answer to *this* call arrives. Anything else on the stream would be a\n # protocol error rather than something to skip, so it is reported rather than ignored.\n while True:\n line = _REAL_STDIN.readline()\n if not line:\n raise ToolError("the host closed the connection while waiting for " + name)\n line = line.strip()\n if not line:\n continue\n frame = json.loads(line)\n\n if frame.get("callback") == token:\n if frame.get("ok"):\n return frame.get("value")\n raise ToolError(frame.get("error") or f"{name} failed")\n\n # An ordinary request, arriving while this tool is blocked.\n #\n # It happens for real: the tool this one called is *another Python tool*, so the host\n # sends it down the same pipe while we are still waiting. Skipping it would deadlock \u2014\n # the host waits for a reply that nobody is reading for \u2014 and treating it as an\n # out-of-order answer, which the first version did, fails every nested call between\n # two Python tools. So it is served here and the wait resumes.\n if "method" in frame:\n request_id = frame.get("id")\n try:\n _respond({"id": request_id, "ok": True, "value": _handle(frame)})\n except Exception as error: # noqa: BLE001 - every failure goes back as a result\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 continue\n\n raise ToolError(\n "unexpected frame while waiting for " + name + "; this is a bug in Light Code"\n )\n\n\ndef _install_helper_module() -> None:\n """Publishes ``light_code`` so a tool can ``import light_code`` and call other tools.\n\n A real module in ``sys.modules`` rather than a builtin or an injected global: a tool is\n an ordinary Python file that must also be readable, lintable and runnable on its own\n terms, and magic names appearing from nowhere break every one of those.\n """\n if "light_code" in sys.modules:\n return\n module = types.ModuleType("light_code")\n module.call_tool = call_tool # type: ignore[attr-defined]\n module.credential = credential # type: ignore[attr-defined]\n module.ToolError = ToolError # type: ignore[attr-defined]\n sys.modules["light_code"] = module\n\n\n# --- running in somebody\'s live Jupyter kernel ---------------------------------------------\n#\n# Requested so that a notebook can drive Light Code and have its tools see the session\'s own\n# state - the dataframe that is already loaded, the model that took ten minutes to fit.\n#\n# ## Why the kernel is named to us rather than discovered by us\n#\n# A kernel knows its own connection file (``ipykernel.get_connection_file()``); nothing outside\n# it does. From another process all you can do is list ``<runtime-dir>/kernel-*.json`` and\n# guess, and with more than one kernel running - the ordinary case for anybody who uses\n# Jupyter - a guess means running somebody\'s tool inside the wrong notebook. That is the same\n# refusal the Excel tools make about attaching: answering "the session I have open" with a\n# different one is worse than asking.\n#\n# So the connection file arrives in ``LIGHT_CODE_JUPYTER_CONNECTION_FILE``, and the host has a\n# discovery helper that only ever *offers* candidates.\n#\n# ## Why the result comes back behind a marker\n#\n# The same reason the identity and credential wrappers do it (CLAUDE.md section 14): a kernel\n# is full of libraries that print. Licence banners, deprecation warnings and progress bars all\n# arrive on the same channel as the answer, and reading "the output" would hand back a log line\n# while looking like it had worked.\n\n_KERNEL_MARKER = "__LIGHT_CODE_RESULT__"\n_kernel_client: Any = None\n\n\ndef _kernel_connection_file() -> str:\n return (os.environ.get("LIGHT_CODE_JUPYTER_CONNECTION_FILE") or "").strip()\n\n\ndef _kernel() -> Any:\n """The client for the configured kernel, connected once and kept.\n\n Reconnecting per call would pay the handshake every time and, worse, would lose the\n channel\'s message ordering guarantees mid-conversation.\n """\n global _kernel_client\n if _kernel_client is not None:\n return _kernel_client\n\n connection_file = _kernel_connection_file()\n if not connection_file:\n raise RuntimeError("no Jupyter kernel is configured for this session")\n if not Path(connection_file).exists():\n raise RuntimeError(\n f"the kernel connection file is gone: {connection_file}. The kernel it described "\n "has probably been shut down or restarted - restart the notebook\'s Light Code "\n "session so it picks up the new one."\n )\n\n try:\n from jupyter_client import BlockingKernelClient\n except ImportError as error:\n raise RuntimeError(\n "running tools in a Jupyter kernel needs jupyter_client, which is not importable "\n "from this interpreter. It ships with Jupyter, so install it into the same "\n "environment the kernel runs in: pip install jupyter_client"\n ) from error\n\n client = BlockingKernelClient()\n client.load_connection_file(connection_file)\n client.start_channels()\n try:\n # Proves the kernel is actually there before any tool is run. Without it the first\n # failure is a silent timeout in the middle of somebody\'s tool, which reads as the tool\n # hanging rather than as the kernel being gone.\n client.wait_for_ready(timeout=20)\n except RuntimeError as error:\n client.stop_channels()\n raise RuntimeError(\n f"connected to the kernel described by {connection_file} but it never became "\n "ready. It may be busy running a cell, or it may have died."\n ) from error\n\n _kernel_client = client\n # Sent here, on the one path that produces a connected client.\n #\n # The first version defined `_kernel_preamble` and never called it, so every tool call\n # arrived at a kernel that had never heard of `_lc_json` and failed with a NameError on\n # line 1. Nothing in the TypeScript, the schema or the wiring was wrong, and no test of\n # any of them could have seen it - it took starting a real kernel and asking it. That is\n # the same shape as `s3.tools` shipping with nothing on the other end.\n _kernel_run(client, _kernel_preamble(), timeout=30)\n return client\n\n\ndef _kernel_preamble() -> str:\n """Code run in the kernel before any tool is, exactly once.\n\n Everything it defines is prefixed and kept in one dict, because this is *somebody\'s\n notebook*: a bare ``json`` or ``run`` left in their globals would shadow their own name and\n break a cell they wrote, a long way from anything they would connect to us.\n\n ## It also installs ``light_code`` in the kernel, and that is not optional\n\n A tool written against ``light_code.call_tool`` imports that module. The worker registers\n it in *its own* ``sys.modules``, which the kernel has never heard of - so without this,\n moving a tool into a kernel turns a working tool into an ImportError whose message points\n at the tool rather than at the move. Found by running it, not by reading it.\n\n ``call_tool`` raises there rather than working, and says why: the callback rides on this\n worker\'s stdio and the kernel has no route back to the host. An honest refusal beats a\n name that exists and hangs.\n\n ``session`` is the point of the whole feature - it *is* the notebook\'s namespace, so a\n tool can read the dataframe that is already loaded.\n """\n return (\n "import json as _lc_json, io as _lc_io, pathlib as _lc_path, sys as _lc_sys, "\n "types as _lc_types, traceback as _lc_tb\\n"\n "from contextlib import redirect_stdout as _lc_redirect\\n"\n "_lc_tools = globals().setdefault(\'_lc_tools\', {})\\n"\n "if \'light_code\' not in _lc_sys.modules:\\n"\n " _lc_helper = _lc_types.ModuleType(\'light_code\')\\n"\n " _lc_helper.session = globals()\\n"\n " class _LcToolError(RuntimeError):\\n"\n " pass\\n"\n " def _lc_no_call(*_a, **_k):\\n"\n " raise _LcToolError(\'call_tool is not available to a tool running inside "\n "a Jupyter kernel: the callback channel belongs to the Light Code worker, and the "\n "kernel has no route back to the host.\')\\n"\n " _lc_helper.call_tool = _lc_no_call\\n"\n " def _lc_no_credential(*_a, **_k):\\n"\n " raise _LcToolError(\'credential() is not available to a tool running inside a "\n "Jupyter kernel: the request would have no route back to the host.\')\\n"\n " _lc_helper.credential = _lc_no_credential\\n"\n " _lc_helper.ToolError = _LcToolError\\n"\n " _lc_sys.modules[\'light_code\'] = _lc_helper\\n"\n )\n\n\ndef _kernel_call_code(name: str, path: str, arguments: dict[str, Any], reload: bool) -> str:\n """The code sent to the kernel for one tool call.\n\n The tool\'s source is executed **in the kernel**, so its imports resolve against the\n kernel\'s environment and its ``run`` sees the kernel\'s globals if it asks for them. The\n module is cached there between calls, and reloaded on the same signal the local path uses.\n """\n payload = json.dumps(\n {"name": name, "path": path, "arguments": arguments, "reload": bool(reload)}\n )\n # A single JSON literal rather than interpolated values: every one of these is\n # model-supplied, and building source by concatenation is how a quote in an argument\n # becomes a syntax error at best (CLAUDE.md section 16\'s rule, applied to code rather than\n # to a command line).\n return (\n f"_lc_req = _lc_json.loads({payload!r})\\n"\n "_lc_out = _lc_io.StringIO()\\n"\n "try:\\n"\n " if _lc_req[\'reload\'] or _lc_req[\'name\'] not in _lc_tools:\\n"\n " _lc_mod = _lc_types.ModuleType(\'light_code_tool_\' + _lc_req[\'name\'])\\n"\n " _lc_mod.__file__ = _lc_req[\'path\']\\n"\n # The notebook\'s own namespace, as a module-level name, so the simplest possible\n # tool - `session[\'df\']` - needs no import at all. This is the whole feature.\n " _lc_mod.session = globals()\\n"\n " _lc_src = _lc_path.Path(_lc_req[\'path\']).read_text(encoding=\'utf-8\')\\n"\n " with _lc_redirect(_lc_out):\\n"\n " exec(compile(_lc_src, _lc_req[\'path\'], \'exec\'), _lc_mod.__dict__)\\n"\n " if not hasattr(_lc_mod, \'run\'):\\n"\n " raise AttributeError(_lc_req[\'path\'] + \' defines no `run` function\')\\n"\n " _lc_tools[_lc_req[\'name\']] = _lc_mod\\n"\n " with _lc_redirect(_lc_out):\\n"\n " _lc_value = _lc_tools[_lc_req[\'name\']].run(**_lc_req[\'arguments\'])\\n"\n " try:\\n"\n " _lc_json.dumps(_lc_value)\\n"\n " _lc_payload = {\'ok\': True, \'result\': _lc_value, "\n "\'stdout\': _lc_out.getvalue()}\\n"\n " except TypeError:\\n"\n # A DataFrame, a model, a connection - returned rather than refused. `repr` is what a\n # notebook would have shown, and losing the answer because it does not serialise would\n # be the worst outcome of a feature whose point is reaching live objects.\n " _lc_payload = {\'ok\': True, \'result\': repr(_lc_value), \'repr\': True, "\n "\'stdout\': _lc_out.getvalue()}\\n"\n "except Exception as _lc_err:\\n"\n " _lc_payload = {\'ok\': False, \'error\': type(_lc_err).__name__ + \': \' + str(_lc_err), "\n "\'traceback\': _lc_tb.format_exc(), \'stdout\': _lc_out.getvalue()}\\n"\n f"print({_KERNEL_MARKER!r} + _lc_json.dumps(_lc_payload))\\n"\n )\n\n\ndef _kernel_execute(code: str, timeout: float) -> dict[str, Any]:\n """Runs code in the kernel and reads back the marked result.\n\n Output that is not the marker is the kernel\'s own chatter and is kept separately, so a\n library\'s banner is never mistaken for the answer.\n """\n return _kernel_run(_kernel(), code, timeout)\n\n\ndef _kernel_run(client: Any, code: str, timeout: float) -> dict[str, Any]:\n """The same, against a client already in hand.\n\n Split out so the preamble can be sent from inside ``_kernel`` - going through\n ``_kernel_execute`` there would call back into ``_kernel`` before it had returned.\n """\n msg_id = client.execute(code, store_history=False)\n\n answer: dict[str, Any] | None = None\n chatter: list[str] = []\n deadline = time.monotonic() + timeout\n\n while True:\n remaining = deadline - time.monotonic()\n if remaining <= 0:\n raise TimeoutError(\n "the kernel did not answer in time. It is probably busy running a cell - a "\n "kernel runs one thing at a time, so a tool waits for whatever is already going."\n )\n try:\n message = client.get_iopub_msg(timeout=min(remaining, 1.0))\n except Exception: # noqa: BLE001 - an empty queue is the ordinary case, so poll again\n continue\n\n if message.get("parent_header", {}).get("msg_id") != msg_id:\n # Somebody else\'s cell. Ignored rather than read: this is a shared kernel and the\n # user is still using it.\n continue\n\n kind = message.get("msg_type")\n content = message.get("content", {})\n if kind == "stream":\n for line in content.get("text", "").splitlines():\n if line.startswith(_KERNEL_MARKER):\n answer = json.loads(line[len(_KERNEL_MARKER):])\n else:\n chatter.append(line)\n elif kind == "error":\n # Raised *before* the tool\'s own code could print the marker: a bad compile, or the\n # kernel dying. The tool\'s own exceptions come back inside the payload instead.\n raise RuntimeError(\n "the kernel refused the call: " + "\\n".join(content.get("traceback", []))\n )\n elif kind == "status" and content.get("execution_state") == "idle":\n break\n\n if answer is None:\n if _KERNEL_MARKER not in code:\n # Setup rather than a call: it is not meant to print anything.\n return {}\n raise RuntimeError(\n "the kernel finished without returning a result. If it was restarted mid-call, "\n "reconnect the notebook\'s Light Code session."\n )\n if chatter:\n answer["stdout"] = (answer.get("stdout") or "") + "\\n".join(chatter)\n return answer\n\n\ndef _banned() -> list[str]:\n """The calls no tool may use, set in Settings -> Python (python.bannedCalls)."""\n try:\n listed = json.loads(os.environ.get("LIGHT_CODE_BANNED_CALLS", "[]"))\n except ValueError:\n return []\n return [str(entry).strip() for entry in listed if str(entry).strip()]\n\n\ndef banned_uses(source: str, banned: list[str]) -> list[str]:\n """Where a tool\'s code uses a banned function or module, as \'line N: name\' - empty when it does not.\n\n Read with Python\'s own parser, so comments and strings never count and aliases are followed:\n ``import certainLib as c`` then ``c.certainFunction(...)``, ``from certainLib import\n certainFunction as f``, a reference passed along without being called, ``getattr(c, "name")``,\n and ``importlib.import_module("certainLib")``. An entry naming a module bans all of it.\n """\n if not banned:\n return []\n tree = ast.parse(source)\n aliases: dict[str, str] = {}\n found: list[str] = []\n\n def hit(dotted: str) -> str | None:\n for entry in banned:\n if dotted == entry or dotted.startswith(entry + "."):\n return entry\n return None\n\n def report(node: ast.AST, dotted: str) -> None:\n entry = hit(dotted)\n if entry is not None:\n found.append(f"line {getattr(node, \'lineno\', \'?\')}: {dotted}" + (f" (banned: {entry})" if entry != dotted else ""))\n\n for node in ast.walk(tree):\n if isinstance(node, ast.Import):\n for name in node.names:\n aliases[name.asname or name.name.split(".")[0]] = name.name if name.asname else name.name.split(".")[0]\n report(node, name.name)\n elif isinstance(node, ast.ImportFrom) and node.module:\n for name in node.names:\n if name.name == "*":\n if any(entry.startswith(node.module + ".") for entry in banned):\n found.append(f"line {node.lineno}: from {node.module} import * (could reach a banned name)")\n continue\n aliases[name.asname or name.name] = f"{node.module}.{name.name}"\n report(node, f"{node.module}.{name.name}")\n\n def dotted_of(node: ast.AST) -> str | None:\n if isinstance(node, ast.Name):\n return aliases.get(node.id, node.id)\n if isinstance(node, ast.Attribute):\n base = dotted_of(node.value)\n return f"{base}.{node.attr}" if base is not None else None\n return None\n\n for node in ast.walk(tree):\n if isinstance(node, ast.Attribute) or (isinstance(node, ast.Name) and isinstance(node.ctx, ast.Load)):\n dotted = dotted_of(node)\n # Only the outermost attribute of a chain is reported, so c.f.g is one finding, not three.\n if dotted is not None and not isinstance(getattr(node, "_lc_parent", None), ast.Attribute):\n report(node, dotted)\n # A module imported by name at run time: importlib.import_module("x"), __import__("x").\n if (\n isinstance(node, ast.Call)\n and dotted_of(node.func) in ("importlib.import_module", "__import__")\n and node.args\n and isinstance(node.args[0], ast.Constant)\n and isinstance(node.args[0].value, str)\n ):\n report(node, node.args[0].value)\n # An attribute fetched by name: getattr(c, "certainFunction").\n if isinstance(node, ast.Call) and dotted_of(node.func) == "getattr" and len(node.args) > 1:\n base = dotted_of(node.args[0])\n attr = node.args[1]\n if base is not None and isinstance(attr, ast.Constant) and isinstance(attr.value, str):\n report(node, f"{base}.{attr.value}")\n for child in ast.iter_child_nodes(node):\n child._lc_parent = node # type: ignore[attr-defined]\n # One line each, in source order, without repeats.\n return sorted(set(found), key=lambda line: int(line.split()[1].rstrip(":")) if line.split()[1].rstrip(":").isdigit() else 0)\n\n\ndef _check_banned(path: str) -> None:\n """Refuses a tool whose code uses a banned call, naming each use."""\n banned = _banned()\n if not banned:\n return\n uses = banned_uses(Path(path).read_text(encoding="utf-8"), banned)\n if uses:\n raise PermissionError(\n "This tool uses calls that are banned in Settings -> Python (Banned calls), so it is not loaded: "\n + "; ".join(uses)\n + ". Rewrite it without them."\n )\n\n\ndef _load(name: str, path: str) -> Any:\n """Imports a tool module from an explicit path, replacing any previous version."""\n _check_banned(path)\n _install_helper_module()\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 """Serves one request, putting back which tool is running when it ends.\n\n A tool that calls another Python tool has that call served here while it waits (see\n ``_ask_host``), and the call records the *callee* as the running tool. Without putting the\n caller back, every later ``call_tool`` from the caller was sent as if the callee asked - so\n it was judged against the callee\'s ``__tool_calls__``, which declares nothing, and a\n monitor\'s check failed on its second call. The first call always worked, which is what made\n it look like an approval problem rather than a bookkeeping one.\n """\n global _CURRENT_TOOL\n previous = _CURRENT_TOOL\n try:\n return _serve(request)\n finally:\n _CURRENT_TOOL = previous\n\n\ndef _serve(request: dict[str, Any]) -> dict[str, Any]:\n method = request.get("method")\n params = request.get("params") or {}\n\n if method == "ping":\n connection_file = _kernel_connection_file()\n # Reported rather than merely configured, so the Python tab can say *which* kernel\n # tools run in. "It is using my notebook" is not something anybody should have to\n # infer from a tool seeing a variable it should not have.\n return {\n "ok": True,\n "python": sys.version,\n **({"jupyterConnectionFile": connection_file} if connection_file else {}),\n }\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 # Recorded so a nested call can say *who* is asking. An approval prompt naming only the\n # callee is the prompt people click through.\n global _CURRENT_TOOL\n _CURRENT_TOOL = name\n\n # Before either place it could run: a banned call is refused in a kernel as much as here.\n _check_banned(params["path"])\n if _kernel_connection_file():\n """Run it where the user\'s own session is.\n\n The whole call goes over, source and all, so the tool\'s imports resolve against\n the kernel\'s environment rather than this one - which is the point: the notebook\n has the libraries and the loaded data, and this process has neither.\n\n The registry is unchanged by this. A tool still had to be approved here, with its\n source shown, before it could ever be called - so running it elsewhere widens\n where the code runs and not who may run it.\n """\n answer = _kernel_execute(\n _kernel_call_code(\n name,\n params["path"],\n params.get("arguments") or {},\n bool(params.get("reload")),\n ),\n # Generous, and bounded anyway by the host\'s own per-tool timeout. A kernel\n # runs one thing at a time, so a tool legitimately waits behind whatever cell\n # the user just ran.\n timeout=float(params.get("timeoutSeconds") or 600),\n )\n if not answer.get("ok"):\n # Re-raised rather than returned, so it reaches the model as a failure with a\n # traceback exactly as a local one does. Section 13 wants the traceback: it is\n # what lets the model fix its own code.\n error = RuntimeError(answer.get("error") or "the tool failed in the kernel")\n error.kernel_traceback = answer.get("traceback") # type: ignore[attr-defined]\n raise error\n return {\n "result": answer.get("result"),\n "stdout": answer.get("stdout") or "",\n "ranInKernel": True,\n # Said out loud when the value could not be JSON, so nobody reads a repr as\n # the structure it is a picture of.\n **({"resultIsRepr": True} if answer.get("repr") else {}),\n }\n\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 # The kernel\'s own traceback when the failure happened there. Ours would\n # be a stack through this file, which says nothing about the tool and is\n # the one thing section 13 wants the model to be able to act on.\n "traceback": getattr(error, "kernel_traceback", None)\n or traceback.format_exc(),\n }\n )\n\n\nif __name__ == "__main__":\n main()\n';
|
|
61787
61787
|
|
|
61788
61788
|
// ../../packages/core/dist/python/manager.js
|
|
61789
61789
|
function labelFields(labels) {
|
|
@@ -75978,7 +75978,7 @@ var createSchema2 = external_exports.object({
|
|
|
75978
75978
|
name: external_exports.string().describe('kebab-case, e.g. "overnight-batch" - the monitor and its skill file.'),
|
|
75979
75979
|
title: external_exports.string().describe('What the tile says, a few words: "Overnight batch".'),
|
|
75980
75980
|
summary: external_exports.string().describe("One sentence shown on hover: what it watches and what an alert means."),
|
|
75981
|
-
audience: external_exports.enum(["me", "team"]).optional().describe(
|
|
75981
|
+
audience: external_exports.enum(["me", "team"]).optional().describe(`"me": a Personal monitor, only on this computer - always possible. "team": shown under Team alerts and shared where the team shares skills; needs the team's OpenSearch history (Settings \u2192 Monitoring). Left out: team when that history is set up, otherwise personal. Use "me" when the user says it is just for them.`),
|
|
75982
75982
|
every: external_exports.union([external_exports.string(), external_exports.number()]).optional().describe('How often to check: "5m", "15m", "1h", "1d" (one minute at least). Leave out when "at" gives the times instead; both together check at the times and in between.'),
|
|
75983
75983
|
at: external_exports.union([external_exports.string(), external_exports.array(external_exports.string())]).optional().describe('Exact times of day: "07:30" for once a day, or ["07:30", "12:00", "18:00"]. Run on the "days" given, whatever activeHours says.'),
|
|
75984
75984
|
activeHours: external_exports.string().optional().describe('A run window for "every": "07:00-19:00" (past midnight is allowed), "09:00-" for not before nine, "-17:00" for until five.'),
|
|
@@ -76040,12 +76040,26 @@ function describeEvaluation(e) {
|
|
|
76040
76040
|
}
|
|
76041
76041
|
var message2 = (error51) => error51 instanceof Error ? error51.message : String(error51);
|
|
76042
76042
|
function createMonitorCreateTool(options) {
|
|
76043
|
-
const skillParams = (params3, block2) => ({
|
|
76043
|
+
const skillParams = (params3, block2, audience) => ({
|
|
76044
76044
|
name: params3.name,
|
|
76045
76045
|
description: `Monitor: ${params3.summary.replace(/\s+/g, " ").trim()}`,
|
|
76046
76046
|
body: monitorSkillBody(params3, block2),
|
|
76047
|
-
|
|
76047
|
+
audience
|
|
76048
76048
|
});
|
|
76049
|
+
const audienceFor = async (params3) => {
|
|
76050
|
+
if (params3.audience !== void 0)
|
|
76051
|
+
return { audience: params3.audience };
|
|
76052
|
+
try {
|
|
76053
|
+
const listed = await options.channel.request("list");
|
|
76054
|
+
if (listed.teamReady === true)
|
|
76055
|
+
return { audience: "team" };
|
|
76056
|
+
} catch {
|
|
76057
|
+
}
|
|
76058
|
+
return {
|
|
76059
|
+
audience: "me",
|
|
76060
|
+
note: "Personal (only on this computer): team monitors need the team's OpenSearch history, which is not set up in Fire Code \u2192 Settings \u2192 Monitoring."
|
|
76061
|
+
};
|
|
76062
|
+
};
|
|
76049
76063
|
const tryIt = async (block2, team = false) => {
|
|
76050
76064
|
try {
|
|
76051
76065
|
if (team) {
|
|
@@ -76069,7 +76083,7 @@ ${describeEvaluation(tried)}` };
|
|
|
76069
76083
|
return {
|
|
76070
76084
|
name: "monitor_create",
|
|
76071
76085
|
group: "edit",
|
|
76072
|
-
description: `Create or replace a Fire Code monitor: a check that runs on a schedule and shows on the Monitoring dashboard as a coloured tile, with a data grid whose cells or rows are coloured by alert rules, and Windows notifications at the levels the user chose. Before creating one: find an existing tool that returns the data (search_docs, or the tools you have) and reuse it; if none does, write a Python tool with create_python_tool from the template in monitor_check_tool, and run monitor_check_tool until it says PASS - then use the columns and key it gives. A SQLite database or CSV/Excel file needs no tool. Rules are judged by Fire Code itself on every check - no model is involved - so make them exact. ASK THE AUTHOR (ask_user_form, one field per rule plus a general one) what each alert means and what to do about it, unless they already said, and put it in each rule's "advice" and in "runbook": that is what an agent tells whoever meets the alert later. A team monitor needs the team's OpenSearch history set in Fire Code \u2192 Settings \u2192 Monitoring; without it
|
|
76086
|
+
description: `Create or replace a Fire Code monitor: a check that runs on a schedule and shows on the Monitoring dashboard as a coloured tile, with a data grid whose cells or rows are coloured by alert rules, and Windows notifications at the levels the user chose. Before creating one: find an existing tool that returns the data (search_docs, or the tools you have) and reuse it; if none does, write a Python tool with create_python_tool from the template in monitor_check_tool, and run monitor_check_tool until it says PASS - then use the columns and key it gives. A SQLite database or CSV/Excel file needs no tool. Rules are judged by Fire Code itself on every check - no model is involved - so make them exact. ASK THE AUTHOR (ask_user_form, one field per rule plus a general one) what each alert means and what to do about it, unless they already said, and put it in each rule's "advice" and in "runbook": that is what an agent tells whoever meets the alert later. A team monitor needs the team's OpenSearch history set in Fire Code \u2192 Settings \u2192 Monitoring; without it the monitor is created personal (only on this computer), which always works - say so to the user.The user approves the skill file; the result shows what the first check found. ` + MONITOR_TOOL_FORMAT,
|
|
76073
76087
|
parametersSchema: createSchema2,
|
|
76074
76088
|
async preview(params3, context) {
|
|
76075
76089
|
const block2 = monitorBlock(params3);
|
|
@@ -76081,23 +76095,23 @@ ${describeEvaluation(tried)}` };
|
|
|
76081
76095
|
${"tool" in params3.source ? `Run ${params3.source.tool}(${JSON.stringify(params3.source.args ?? {})})` : `Read ${JSON.stringify(params3.source)}`}`
|
|
76082
76096
|
};
|
|
76083
76097
|
}
|
|
76084
|
-
const
|
|
76098
|
+
const { audience, note: forWhom } = await audienceFor(params3);
|
|
76099
|
+
const tried = await tryIt(block2, audience === "team");
|
|
76085
76100
|
if (!tried.ok) {
|
|
76086
76101
|
return { kind: "text", text: `This monitor cannot be created as written - nothing will be saved:
|
|
76087
76102
|
|
|
76088
76103
|
${tried.error}` };
|
|
76089
76104
|
}
|
|
76090
|
-
const written = options.writeSkill.preview !== void 0 ? await options.writeSkill.preview(skillParams(params3, block2), context) : void 0;
|
|
76105
|
+
const written = options.writeSkill.preview !== void 0 ? await options.writeSkill.preview(skillParams(params3, block2, audience), context) : void 0;
|
|
76091
76106
|
if (written?.kind === "diff") {
|
|
76092
|
-
return { ...written, note: [written.note, tried.note, "Approving this also lets it run on this computer."].filter((n) => n !== void 0 && n.length > 0).join("\n\n") };
|
|
76107
|
+
return { ...written, note: [forWhom, written.note, tried.note, "Approving this also lets it run on this computer."].filter((n) => n !== void 0 && n.length > 0).join("\n\n") };
|
|
76093
76108
|
}
|
|
76094
|
-
return { kind: "text", text:
|
|
76095
|
-
|
|
76096
|
-
${tried.note}` };
|
|
76109
|
+
return { kind: "text", text: [forWhom, monitorSkillBody(params3, block2), tried.note].filter((n) => n !== void 0).join("\n\n") };
|
|
76097
76110
|
},
|
|
76098
76111
|
async execute(params3, context) {
|
|
76099
76112
|
const block2 = monitorBlock(params3);
|
|
76100
|
-
const
|
|
76113
|
+
const { audience, note: forWhom } = params3.tryOnly === true ? { audience: "me", note: void 0 } : await audienceFor(params3);
|
|
76114
|
+
const tried = await tryIt(block2, audience === "team");
|
|
76101
76115
|
if (!tried.ok)
|
|
76102
76116
|
return { content: `Not created: ${tried.error}`, isError: true };
|
|
76103
76117
|
if (params3.tryOnly === true) {
|
|
@@ -76122,10 +76136,10 @@ ${describeRowsCheck(checkMonitorRows(result.content))}` };
|
|
|
76122
76136
|
${MONITOR_TOOL_FORMAT}`, isError: true };
|
|
76123
76137
|
}
|
|
76124
76138
|
}
|
|
76125
|
-
const written = await options.writeSkill.execute(skillParams(params3, block2), context);
|
|
76139
|
+
const written = await options.writeSkill.execute(skillParams(params3, block2, audience), context);
|
|
76126
76140
|
if (written.isError === true)
|
|
76127
76141
|
return written;
|
|
76128
|
-
const lines2 = [written.content];
|
|
76142
|
+
const lines2 = [written.content, ...forWhom !== void 0 ? [forWhom] : []];
|
|
76129
76143
|
try {
|
|
76130
76144
|
await options.channel.request("approve", { name: params3.name, block: block2 });
|
|
76131
76145
|
} catch (error51) {
|
|
@@ -81115,7 +81129,7 @@ function wireChatBridge(services) {
|
|
|
81115
81129
|
}
|
|
81116
81130
|
const declared = await declaredCallsOf(caller);
|
|
81117
81131
|
const isDeclared = declared.some((d) => d === tool.name || `py__${d}` === tool.name);
|
|
81118
|
-
if (
|
|
81132
|
+
if (monitorRunContext !== void 0) {
|
|
81119
81133
|
if (!isDeclared) {
|
|
81120
81134
|
throw new Error(`${caller} calls "${tool.name}" without declaring it. Add it to the tool's __tool_calls__ list (e.g. __tool_calls__ = [${[...declared, tool.name].map((d) => JSON.stringify(d)).join(", ")}]); the tool is then approved again.`);
|
|
81121
81135
|
}
|
|
@@ -94490,7 +94504,18 @@ edits made outside the agent (in VS Code, say) are saved with \`hub_sync\` "push
|
|
|
94490
94504
|
"cleanup",
|
|
94491
94505
|
"opensearch history",
|
|
94492
94506
|
"explain alert",
|
|
94493
|
-
"tool_calls"
|
|
94507
|
+
"tool_calls",
|
|
94508
|
+
"edit schedule",
|
|
94509
|
+
"change schedule",
|
|
94510
|
+
"delete monitor",
|
|
94511
|
+
"delete check",
|
|
94512
|
+
"remove monitor",
|
|
94513
|
+
"personal monitor",
|
|
94514
|
+
"personal check",
|
|
94515
|
+
"monitor schedule",
|
|
94516
|
+
"schedule of a monitor",
|
|
94517
|
+
"monitor check",
|
|
94518
|
+
"monitoring check"
|
|
94494
94519
|
],
|
|
94495
94520
|
body: `
|
|
94496
94521
|
**Fire Code only.** Settings \u2192 Monitoring switches it on; a Monitoring button then appears at the top of the
|
|
@@ -94537,6 +94562,19 @@ before nine, "-17:00" for until five); \`at\` for exact times of day ("07:30" -
|
|
|
94537
94562
|
"18:00"]); \`days\` for the days of the week, for both. A time missed while Fire Code was closed is not made up the
|
|
94538
94563
|
next day.
|
|
94539
94564
|
|
|
94565
|
+
**Change when it runs**: in its grid window, **Schedule** (or right-click a tile \u2192 Edit schedule\u2026): every N minutes
|
|
94566
|
+
or hours, only between two times (either may be empty), at set times of day, on chosen days. Saving writes only those
|
|
94567
|
+
fields into the skill file and keeps an approved monitor approved. An agent can change it too ("run the batch check
|
|
94568
|
+
every 10 minutes on weekdays"); you approve the change as a diff.
|
|
94569
|
+
|
|
94570
|
+
**Delete a monitor for good**: right-click its tile \u2192 Delete this monitor\u2026 (or \u22EF \u2192 Delete in its window). Its skill
|
|
94571
|
+
file, its results and history here, and your own checks in the team history go; Pause stops it for a while instead.
|
|
94572
|
+
A copy synced from the team's bucket or repository cannot be changed or deleted from the dashboard - the next sync
|
|
94573
|
+
would put it back - so ask the agent, or delete it for everyone in Settings \u2192 Skills.
|
|
94574
|
+
|
|
94575
|
+
**Personal monitors need nothing set up.** Ask for "a personal check" (or just a check, before team history exists)
|
|
94576
|
+
and the agent makes one only on this computer.
|
|
94577
|
+
|
|
94540
94578
|
**Team monitors need OpenSearch** (Settings \u2192 Monitoring \u2192 Team history): choose an OpenSearch connection from the
|
|
94541
94579
|
codebase monitoring runs with, and an index name the whole team shares. Without it a team monitor stays grey
|
|
94542
94580
|
("Needs team history"); personal monitors keep their history on this computer. Every member's Fire Code may run a
|
|
@@ -94557,7 +94595,9 @@ default), with what is known already in the message box - press Enter to send it
|
|
|
94557
94595
|
|
|
94558
94596
|
**Tools can call tools**: a Python tool lists what it calls in \`__tool_calls__ = ["server__query", "autosys_status"]\`
|
|
94559
94597
|
- MCP tools, other Python tools and Fire Code's reading tools. That line is part of the approved code; in a
|
|
94560
|
-
monitor's check those calls run without asking
|
|
94598
|
+
monitor's check those calls run without asking - the same when the agent tries the monitor in a chat - and nothing
|
|
94599
|
+
that edits or runs commands is reachable. A tool calling another Python tool several times works (before Fire Code
|
|
94600
|
+
0.61.0 only the first call did, which read as an approval problem).
|
|
94561
94601
|
|
|
94562
94602
|
**Agents can**: \`monitor_history\` (an alert's history: new, ongoing, recurring), \`monitor_check_tool\` (run a tool once and check its answer strictly: PASS or FAIL with what
|
|
94563
94603
|
to change, and the columns and key for the monitor - an agent writing a Python tool for a monitor works until
|