@chosengeneration/light-code 0.164.0 → 0.169.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.
Files changed (3) hide show
  1. package/dist/cli.cjs +474 -55
  2. package/dist/server.cjs +463 -51
  3. 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) {
@@ -62015,6 +62015,47 @@ var PythonManager = class {
62015
62015
  findTool(name) {
62016
62016
  return this.registered.find((tool) => tool.name === name);
62017
62017
  }
62018
+ /**
62019
+ * Which of these modules the tools' environment has, without importing any (`importlib.util.find_spec`).
62020
+ * Undefined when Python is not running, so nobody is told a module is missing that was never looked for.
62021
+ */
62022
+ async hasModules(modules) {
62023
+ if (!this.ready || this.interpreter.length === 0 || modules.length === 0)
62024
+ return void 0;
62025
+ try {
62026
+ const answer = await interpreterCheck(this.interpreter, await this.childEnv())({ modules: [...modules], distributions: [] });
62027
+ return Object.fromEntries(modules.map((module2) => [module2, !answer.missingModules.includes(module2)]));
62028
+ } catch {
62029
+ return void 0;
62030
+ }
62031
+ }
62032
+ /**
62033
+ * What the Python tab can show at once, before Python starts: the tools already approved in each folder,
62034
+ * from its `.registry.json` (no interpreter, no import). Reported as slow on a managed machine, where
62035
+ * starting uv and Python costs seconds and the tab used to stay empty until both had.
62036
+ *
62037
+ * Issues are left out on purpose: deciding that a tool needs approval may take adopting an approval
62038
+ * made elsewhere on this machine, which loads the tool in the worker - so a guess here would flash an
62039
+ * approval request for something already approved.
62040
+ */
62041
+ async previewStatus(folders) {
62042
+ const current = this.status();
62043
+ if (current.ready || this.options.workspaceRoot === void 0)
62044
+ return current;
62045
+ const toolsDir = folders.toolsDir ?? defaultPythonToolsDir(this.options.workspaceRoot);
62046
+ const dirs = [toolsDir, ...folders.extraToolDirs ?? []].filter((dir) => dir.length > 0);
62047
+ const loaded = await loadRegistries(dirs, void 0, this.options.logger, this.declinedTools, void 0);
62048
+ return {
62049
+ ...current,
62050
+ enabled: true,
62051
+ ready: false,
62052
+ starting: true,
62053
+ toolsDir,
62054
+ detail: "Starting Python\u2026 the tools below were approved before; anything new to review is listed once it is running.",
62055
+ tools: loaded.tools.map((tool) => ({ name: tool.name, description: tool.description, filePath: tool.filePath, sourceDir: tool.sourceDir })),
62056
+ issues: []
62057
+ };
62058
+ }
62018
62059
  async refresh() {
62019
62060
  if (!this.enabled || this.toolsDir.length === 0)
62020
62061
  return;
@@ -66429,6 +66470,15 @@ var toMs = (value) => {
66429
66470
  const ms = Date.parse(value);
66430
66471
  return Number.isNaN(ms) ? void 0 : ms;
66431
66472
  };
66473
+ var RECORDS = external_exports.boolean().optional().describe("Answer as a JSON list of records (one per file, hit or row; numbers as numbers, times as ISO) - for a Fire Code monitor's source or for dataframe. Default: text for reading.");
66474
+ function asRecords(records, answer) {
66475
+ if (answer.timedOut === true)
66476
+ return { content: "Stopped at the time limit, so the answer is partial - narrow the folders, names or dates.", isError: true };
66477
+ return { content: JSON.stringify(records) };
66478
+ }
66479
+ var iso = (ms) => typeof ms === "number" && Number.isFinite(ms) ? new Date(ms).toISOString() : null;
66480
+ var ageMinutes = (ms) => typeof ms === "number" && Number.isFinite(ms) ? Math.max(0, Math.round((Date.now() - ms) / 6e4)) : null;
66481
+ var keyed = (columns, rows) => rows.map((row) => Object.fromEntries(columns.map((c2, i) => [c2, row[i] ?? null])));
66432
66482
  var grepSchema = external_exports.object({
66433
66483
  pattern: external_exports.string().min(1).describe("A regular expression (or plain text with literal: true). Case-insensitive unless it has a capital letter."),
66434
66484
  roots: external_exports.array(external_exports.string().min(1)).min(1).max(20).describe("Folders or files to search: workspace-relative, absolute, another drive, or shares like \\\\server\\share\\folder - several at once."),
@@ -66709,7 +66759,7 @@ function allFastFsTools(exe, options = {}) {
66709
66759
  name: "find_files",
66710
66760
  group: "read",
66711
66761
  description: 'Find files fast across whole folders, drives and network shares, using every CPU core: by name pattern, extension, size and modified date (action "find"); summarise a folder tree \u2014 total size, size by file type, largest and newest files ("summary"); or find identical files by content ("duplicates"). Read-only. Prefer this to list_files for anything larger than one folder.',
66712
- parametersSchema: findSchema,
66762
+ parametersSchema: findSchema.extend({ records: RECORDS }),
66713
66763
  async execute(input, context) {
66714
66764
  const params3 = { ...input, action: input.action ?? "find" };
66715
66765
  const roots = [];
@@ -66742,6 +66792,9 @@ ${(answer.unreadablePaths ?? []).map((u) => ` ${u}`).join("\n")}` : ".");
66742
66792
  if (params3.action === "find") {
66743
66793
  const matches = answer.matches ?? [];
66744
66794
  const keep = await allowedResults(context, matches.map((m) => m.path));
66795
+ if (params3.records === true) {
66796
+ return asRecords(matches.filter((m) => keep.has(m.path)).map((m) => ({ path: m.path, name: m.path.split(/[\\/]/).pop() ?? m.path, folder: m.directory, sizeBytes: m.directory ? null : m.size, modified: iso(m.modified), ageMinutes: ageMinutes(m.modified) })), answer);
66797
+ }
66745
66798
  const lines2 = matches.filter((m) => keep.has(m.path)).map((m) => `${m.path} ${m.directory ? "folder" : formatBytes(m.size)} ${when(m.modified)}`);
66746
66799
  return { content: `${lines2.length === 0 ? "Nothing matched." : lines2.join("\n")}
66747
66800
 
@@ -66817,7 +66870,7 @@ ${refused.join("\n")}`] : []].join("\n\n") };
66817
66870
  name: "big_file",
66818
66871
  group: "read",
66819
66872
  description: 'Work through a large file \u2014 a log, a data export, a CSV of millions of rows \u2014 without loading it: "inspect" gives size, line count, the first lines and (for CSV/Excel) the columns and types; "lines" reads any window; "tail" reads the end; "search" runs a regular expression over the whole file on every CPU core and returns matching lines with numbers and context. Start with inspect, then read or search part by part.',
66820
- parametersSchema: bigFileSchema,
66873
+ parametersSchema: bigFileSchema.extend({ records: RECORDS }),
66821
66874
  async execute(params3, context) {
66822
66875
  const r = await readable(context, params3.path);
66823
66876
  if (!r.ok)
@@ -66845,6 +66898,8 @@ ${refused.join("\n")}`] : []].join("\n\n") };
66845
66898
  }
66846
66899
  if (params3.action === "search") {
66847
66900
  const matches = answer.matches ?? [];
66901
+ if (params3.records === true)
66902
+ return { ...asRecords(matches.map((m) => ({ line: m.line, text: m.text })), answer), path: params3.path };
66848
66903
  const text2 = matches.map((m) => [...m.before.map((b, i) => `${String(m.line - m.before.length + i).padStart(8)} ${b}`), `${String(m.line).padStart(8)}> ${m.text}`, ...m.after.map((a, i) => `${String(m.line + 1 + i).padStart(8)} ${a}`)].join("\n")).join("\n--\n");
66849
66904
  return { content: `${matches.length === 0 ? "No matches." : text2}
66850
66905
 
@@ -66865,8 +66920,9 @@ ${answer.limitReached === true ? `At least ${String(answer.matchCount)} matches`
66865
66920
  name: "query_table",
66866
66921
  group: "read",
66867
66922
  description: "Query a CSV/TSV file or an Excel sheet of any size without reading it all: choose columns, filter rows, group with count/sum/avg/min/max/distinct, sort, and page with offset/limit. Runs on every CPU core and returns only the small result. Use big_file inspect first to learn the column names.",
66868
- parametersSchema: tableSchema,
66869
- async execute(params3, context) {
66923
+ parametersSchema: tableSchema.extend({ records: RECORDS }),
66924
+ async execute(input, context) {
66925
+ const { records: asJson, ...params3 } = input;
66870
66926
  const r = await readable(context, params3.path);
66871
66927
  if (!r.ok)
66872
66928
  return { content: r.message, isError: true, path: params3.path };
@@ -66875,6 +66931,8 @@ ${answer.limitReached === true ? `At least ${String(answer.matchCount)} matches`
66875
66931
  return { content: answer.error ?? "The query failed.", isError: true, path: params3.path };
66876
66932
  const columns = answer.columns ?? [];
66877
66933
  const rows = answer.rows ?? [];
66934
+ if (asJson === true)
66935
+ return { ...asRecords(keyed(columns, rows), answer), path: params3.path };
66878
66936
  const cell = (v) => v === null || v === void 0 ? "" : typeof v === "number" ? String(Math.round(v * 1e6) / 1e6) : String(v).replace(/\|/g, "\\|");
66879
66937
  const table = [`| ${columns.join(" | ")} |`, `|${columns.map(() => " --- ").join("|")}|`, ...rows.map((row) => `| ${row.map(cell).join(" | ")} |`)].join("\n");
66880
66938
  const offset = answer.offset ?? 0;
@@ -66890,7 +66948,7 @@ Rows ${String(offset + 1)}\u2013${String(offset + rows.length)} of ${String(answ
66890
66948
  name: "grep_files",
66891
66949
  group: "read",
66892
66950
  description: "Search the contents of files for text or a regular expression across several folders, drives and network shares at once, on every CPU core - filtered by file name, extension and date first. Reads UTF-16 files too, and names every file or folder it could not read and why. Use for searching outside the workspace or across many roots; search_files is fine inside the workspace.",
66893
- parametersSchema: grepSchema,
66951
+ parametersSchema: grepSchema.extend({ records: RECORDS }),
66894
66952
  async execute(params3, context) {
66895
66953
  const roots = [];
66896
66954
  for (const root of params3.roots) {
@@ -66920,21 +66978,32 @@ Rows ${String(offset + 1)}\u2013${String(offset + rows.length)} of ${String(answ
66920
66978
  }, context.signal);
66921
66979
  if (answer.ok !== true)
66922
66980
  return { content: answer.error ?? "The search failed.", isError: true };
66923
- return { content: formatGrepAnswer(answer, await allowedResults(context, (answer.files ?? []).map((f) => f.path))) };
66981
+ const allowed = await allowedResults(context, (answer.files ?? []).map((f) => f.path));
66982
+ if (params3.records === true) {
66983
+ const files = (answer.files ?? []).filter((f) => allowed.has(f.path));
66984
+ return asRecords(files.flatMap((f) => f.hits.length === 0 ? [{ path: f.path, matches: f.matches }] : f.hits.map((h) => ({ path: f.path, line: h.line, text: h.text, matches: f.matches }))), answer);
66985
+ }
66986
+ return { content: formatGrepAnswer(answer, allowed) };
66924
66987
  }
66925
66988
  };
66926
66989
  const sqliteTool = {
66927
66990
  name: "query_sqlite",
66928
66991
  group: "read",
66929
66992
  description: "Read a SQLite database without creating it and without blocking the program that uses it: schema (tables, columns, indexes, row counts), query (one read-only SQL statement), scan (filter/group/sort a big table on every CPU core), search (text anywhere in the database). Use instead of python or a sqlite3 shell. A missing file is reported, never created; writes are refused.",
66930
- parametersSchema: sqliteSchema,
66931
- async execute(params3, context) {
66993
+ parametersSchema: sqliteSchema.extend({ records: RECORDS }),
66994
+ async execute(input, context) {
66995
+ const { records: asJson, ...params3 } = input;
66932
66996
  const r = await readable(context, params3.path);
66933
66997
  if (!r.ok)
66934
66998
  return { content: r.message, isError: true, path: params3.path };
66935
66999
  const answer = await runHelper(exe, { op: "sqlite", ...params3, path: r.path }, context.signal);
66936
67000
  if (answer.ok !== true)
66937
67001
  return { content: answer.error ?? "The SQLite read failed.", isError: true, path: params3.path };
67002
+ if (asJson === true && (params3.action === "query" || params3.action === "scan")) {
67003
+ if (answer.consistent === false)
67004
+ return { content: "The database was being written throughout the read; check again.", isError: true, path: params3.path };
67005
+ return { ...asRecords(keyed(answer.columns ?? [], answer.rows ?? []), answer), path: params3.path };
67006
+ }
66938
67007
  return { content: formatSqliteAnswer(params3, answer), path: params3.path };
66939
67008
  }
66940
67009
  };
@@ -66942,8 +67011,9 @@ Rows ${String(offset + 1)}\u2013${String(offset + rows.length)} of ${String(answ
66942
67011
  name: "dataframe",
66943
67012
  group: "read",
66944
67013
  description: "Data analysis with Polars (Rust, every CPU core) over CSV/delimited files, Excel sheets, the clipboard, JSON files, SQLite tables or queries, and records you already have (`rows`: e.g. results from another tool) - name each source and query them together with SQL: joins across sources, GROUP BY, window functions - and pivot. Reading is forgiving: every value is kept, and a column becomes numbers or dates only when all of it converts (the answer says which columns stayed text and why). Use instead of writing pandas or opening Excel.",
66945
- parametersSchema: dataframeSchema,
66946
- async execute(params3, context) {
67014
+ parametersSchema: dataframeSchema.extend({ records: RECORDS }),
67015
+ async execute(input, context) {
67016
+ const { records: asJson, ...params3 } = input;
66947
67017
  const sources = [];
66948
67018
  for (const source of params3.sources) {
66949
67019
  if (source.path !== void 0) {
@@ -66968,6 +67038,10 @@ Rows ${String(offset + 1)}\u2013${String(offset + rows.length)} of ${String(answ
66968
67038
  const answer = await runHelper(exe, { op: "dataframe", ...params3, sources }, context.signal);
66969
67039
  if (answer.ok !== true)
66970
67040
  return { content: answer.error ?? "The dataframe operation failed.", isError: true };
67041
+ if (asJson === true && params3.action !== "describe") {
67042
+ const columns = (answer.columns ?? []).map((c2) => c2.name);
67043
+ return asRecords(keyed(columns, answer.rows ?? []), answer);
67044
+ }
66971
67045
  return { content: formatDataframeAnswer(params3.action, answer) };
66972
67046
  }
66973
67047
  };
@@ -71518,13 +71592,13 @@ function order(spec, ranks, back) {
71518
71592
  const above = byRank[depth - 1] ?? [];
71519
71593
  const positions = new Map(above.map((id, index) => [id, index]));
71520
71594
  const row = byRank[depth] ?? [];
71521
- const keyed = row.map((id, index) => {
71595
+ const keyed2 = row.map((id, index) => {
71522
71596
  const known = (parents.get(id) ?? []).map((parent) => positions.get(parent)).filter((value) => value !== void 0);
71523
71597
  const barycentre = known.length === 0 ? index : known.reduce((a, b) => a + b, 0) / known.length;
71524
71598
  return { id, barycentre, index };
71525
71599
  });
71526
- keyed.sort((a, b) => a.barycentre - b.barycentre || a.index - b.index);
71527
- byRank[depth] = keyed.map((entry) => entry.id);
71600
+ keyed2.sort((a, b) => a.barycentre - b.barycentre || a.index - b.index);
71601
+ byRank[depth] = keyed2.map((entry) => entry.id);
71528
71602
  }
71529
71603
  return byRank;
71530
71604
  }
@@ -73928,10 +74002,10 @@ function calendarDates(records) {
73928
74002
  const visit = (value) => {
73929
74003
  if (typeof value === "string" || typeof value === "number") {
73930
74004
  const text2 = String(value).trim();
73931
- const iso = /^(\d{4})-(\d{2})-(\d{2})/.exec(text2);
74005
+ const iso2 = /^(\d{4})-(\d{2})-(\d{2})/.exec(text2);
73932
74006
  const us = /^(\d{1,2})\/(\d{1,2})\/(\d{4})/.exec(text2);
73933
- if (iso !== null)
73934
- found2.add(`${iso[1] ?? ""}-${iso[2] ?? ""}-${iso[3] ?? ""}`);
74007
+ if (iso2 !== null)
74008
+ found2.add(`${iso2[1] ?? ""}-${iso2[2] ?? ""}-${iso2[3] ?? ""}`);
73935
74009
  else if (us !== null)
73936
74010
  found2.add(`${us[3] ?? ""}-${(us[1] ?? "").padStart(2, "0")}-${(us[2] ?? "").padStart(2, "0")}`);
73937
74011
  } else if (Array.isArray(value))
@@ -75626,6 +75700,8 @@ var MAPPING = {
75626
75700
  level: { type: "keyword" },
75627
75701
  alertIds: { type: "keyword" },
75628
75702
  alertKeys: { type: "keyword" },
75703
+ /** A shared grid's content hash (Fire Code 0.65.0). */
75704
+ hash: { type: "keyword" },
75629
75705
  payload: { type: "object", enabled: false }
75630
75706
  }
75631
75707
  }
@@ -75694,9 +75770,46 @@ var MonitorHistoryStore = class {
75694
75770
  const type = json2["error"]?.type;
75695
75771
  if (status2 >= 300 && type !== "resource_already_exists_exception")
75696
75772
  this.fail("creating the monitoring index", status2, json2);
75773
+ if (type === "resource_already_exists_exception") {
75774
+ const added = await this.send("PUT", "/_mapping", { properties: { hash: MAPPING.mappings.properties.hash } });
75775
+ if (added.status >= 300)
75776
+ this.fail("updating the monitoring index", added.status, added.json);
75777
+ }
75697
75778
  this.ensured = true;
75698
75779
  }
75699
75780
  /** True when this Fire Code may run `monitor` for interval `slot`; false when a team member already is. */
75781
+ /**
75782
+ * A check's whole grid, shared once per distinct grid and day (asked: every member must see the same rows, not
75783
+ * only the alerted ones). Named by the grid's content hash, so unchanged data adds nothing; created once - a
75784
+ * second writer the same day gets "already there", which is success.
75785
+ */
75786
+ async writeGrid(monitor, hash3, evaluation) {
75787
+ await this.ensureIndex();
75788
+ const day = Math.floor(Date.now() / 864e5);
75789
+ const { status: status2, json: json2 } = await this.send("PUT", `/_create/${encodeURIComponent(docId("grid", monitor, hash3, day))}`, {
75790
+ kind: "grid",
75791
+ monitor,
75792
+ by: this.by,
75793
+ at: Math.floor(Date.now() / 1e3),
75794
+ hash: hash3,
75795
+ payload: { evaluation }
75796
+ });
75797
+ if (status2 === 409)
75798
+ return;
75799
+ if (status2 >= 300)
75800
+ this.fail(`sharing the grid of ${monitor}`, status2, json2);
75801
+ }
75802
+ /** A shared grid by its hash: the newest copy, or undefined when no member shared it (or it was cleaned up). */
75803
+ async grid(monitor, hash3) {
75804
+ const json2 = await this.search({
75805
+ size: 1,
75806
+ sort: [{ at: "desc" }],
75807
+ _source: ["payload"],
75808
+ query: { bool: { filter: [{ term: { kind: "grid" } }, { term: { monitor } }, { term: { hash: hash3 } }] } }
75809
+ });
75810
+ const hits = json2["hits"]?.hits ?? [];
75811
+ return hits[0]?._source.payload.evaluation;
75812
+ }
75700
75813
  async claim(monitor, slot) {
75701
75814
  await this.ensureIndex();
75702
75815
  const { status: status2, json: json2 } = await this.send("PUT", `/_create/${encodeURIComponent(docId("claim", monitor, slot))}`, {
@@ -75755,16 +75868,26 @@ var MonitorHistoryStore = class {
75755
75868
  return out;
75756
75869
  }
75757
75870
  /** A monitor's checks since `since` (epoch seconds), newest first, by anyone. */
75758
- async history(monitor, since2, limit = 500) {
75871
+ /** Checks from `since`, newest first; with `until`, only before then (one day's, from the History view). */
75872
+ async history(monitor, since2, limit = 500, until) {
75759
75873
  const json2 = await this.search({
75760
75874
  size: Math.min(Math.max(limit, 1), 2e3),
75761
75875
  sort: [{ at: "desc" }],
75762
75876
  _source: ["payload"],
75763
- query: { bool: { filter: [{ term: { kind: "check" } }, { term: { monitor } }, { range: { at: { gte: since2 } } }] } }
75877
+ query: { bool: { filter: [{ term: { kind: "check" } }, { term: { monitor } }, { range: { at: { gte: since2, ...until !== void 0 ? { lt: until } : {} } } }] } }
75764
75878
  });
75765
75879
  const hits = json2["hits"]?.hits ?? [];
75766
75880
  return hits.map((h) => h._source.payload);
75767
75881
  }
75882
+ /** Removes one check of this person's - the History view's "Delete this check". A colleague's stays theirs. */
75883
+ async deleteCheck(monitor, at) {
75884
+ await this.ensureIndex();
75885
+ const filter = [{ term: { kind: "check" } }, { term: { monitor } }, { term: { at } }, { term: { by: this.by } }];
75886
+ const { status: status2, json: json2 } = await this.send("POST", "/_delete_by_query?conflicts=proceed", { query: { bool: { filter } } });
75887
+ if (status2 >= 300)
75888
+ this.fail("deleting a check", status2, json2);
75889
+ return Number(json2["deleted"] ?? 0);
75890
+ }
75768
75891
  /** Removes this person's checks and claims older than `before` - only theirs. How many went. */
75769
75892
  async prune(before, monitor) {
75770
75893
  await this.ensureIndex();
@@ -75932,6 +76055,12 @@ from datetime import datetime, timezone
75932
76055
 
75933
76056
  import light_code
75934
76057
 
76058
+ # Big or tabular data: use Polars when it is installed (monitor_check_tool says whether it is) - filter and
76059
+ # aggregate there and return df.to_dicts(). Fall back to plain Python (or pandas) only when it is not:
76060
+ # import polars as pl
76061
+ # df = pl.read_csv(path).filter(pl.col("status") != "OK").select(["job", "status", "minutes"])
76062
+ # return df.to_dicts()
76063
+
75935
76064
  # Tools this one calls with light_code.call_tool - MCP tools, other Python tools, and Fire Code's
75936
76065
  # reading tools (autosys_status, jira_search, ...). Reviewed with the tool; in a monitor they run unasked.
75937
76066
  __tool_calls__ = ["server__query_jobs"]
@@ -75947,7 +76076,8 @@ def run(pattern: str = "PAY_*") -> list[dict]:
75947
76076
  """
75948
76077
  # Either read the source directly, or call an existing tool (its answer is text - json.loads it
75949
76078
  # when the tool answers JSON). Let it RAISE when the data cannot be read - the tile turns purple.
75950
- items = json.loads(light_code.call_tool("server__query_jobs", {"pattern": pattern}))
76079
+ # Arguments are keywords: call_tool("server__query_jobs", pattern=pattern) - never a dict.
76080
+ items = json.loads(light_code.call_tool("server__query_jobs", pattern=pattern))
75951
76081
  rows = []
75952
76082
  for item in items:
75953
76083
  rows.append({
@@ -75961,7 +76091,7 @@ def run(pattern: str = "PAY_*") -> list[dict]:
75961
76091
  `.trim();
75962
76092
 
75963
76093
  // ../../packages/core/dist/monitoring/tools.js
75964
- var MONITOR_TOOL_FORMAT = `FORMAT a monitor reads: make the Python tool's run() return a LIST OF DICTS - one dict per thing watched (a job, a host, a feed), the same keys in each; flat values (str, int, float, bool or None - a nested dict is read with a dotted key such as "owner.name"); numbers as numbers, never "1,250" or "84 min" strings; timestamps as ISO 8601 ("2026-10-25T14:05:00Z") or epoch seconds, so olderThan/newerThan rules work; one key that names the row (job, host) for the monitor's "key"; a status as a short fixed word (FAILURE, OK) rules can match. Return [] when there is nothing to report - never a message saying so. RAISE an exception when the data cannot be read, so the tile turns purple (cannot tell) instead of green. Keep it fast (seconds) and read-only. {"rows": [...]} and {"columns": [...], "rows": [[...]]} are read too. Try it with monitor_create tryOnly: true before saving.`;
76094
+ var MONITOR_TOOL_FORMAT = `FORMAT a monitor reads: make the Python tool's run() return a LIST OF DICTS - one dict per thing watched (a job, a host, a feed), the same keys in each; flat values (str, int, float, bool or None - a nested dict is read with a dotted key such as "owner.name"); numbers as numbers, never "1,250" or "84 min" strings; timestamps as ISO 8601 ("2026-10-25T14:05:00Z") or epoch seconds, so olderThan/newerThan rules work; one key that names the row (job, host) for the monitor's "key"; a status as a short fixed word (FAILURE, OK) rules can match. Return [] when there is nothing to report - never a message saying so. RAISE an exception when the data cannot be read, so the tile turns purple (cannot tell) instead of green. Keep it fast (seconds) and read-only. {"rows": [...]} and {"columns": [...], "rows": [[...]]} are read too. Try it with monitor_create tryOnly: true before saving. FOR SPEED: when Polars is installed in the tools' environment (monitor_check_tool says), use it rather than pandas - read, filter and aggregate in Polars (lazy scans for big files) and return df.to_dicts(); return only the rows and fields the rules need. light_code.call_tool takes keyword arguments: call_tool("name", job="X"), never a dict.`;
75965
76095
  var condition = external_exports.lazy(() => external_exports.union([
75966
76096
  external_exports.object({ all: external_exports.array(condition) }),
75967
76097
  external_exports.object({ any: external_exports.array(condition) }),
@@ -75973,12 +76103,12 @@ var sourceSchema = external_exports.union([
75973
76103
  external_exports.object({ tool: external_exports.string(), args: external_exports.record(external_exports.string(), external_exports.unknown()).optional() }),
75974
76104
  external_exports.object({ sqlite: external_exports.string(), sql: external_exports.string() }),
75975
76105
  external_exports.object({ files: external_exports.union([external_exports.string(), external_exports.array(external_exports.union([external_exports.string(), external_exports.object({ name: external_exports.string().optional(), path: external_exports.string() })]))]), sql: external_exports.string() })
75976
- ]).describe('Where the rows come from. {"tool": "py__name", "args": {...}}: a Python tool (returning a list of records), an MCP tool or a read tool - runs in the background with the settings Fire Code monitoring uses. {"sqlite": "C:\\\\full\\\\path.db", "sql": "select ..."}: read by Fire Code itself, never locked. {"files": ["C:\\\\full\\\\path.csv"], "sql": "select ... from data"}: CSV, TSV, Excel or JSON, queried with SQL (the first file is the table "data", the second "data2").');
76106
+ ]).describe(`Where the rows come from - PREFER, IN THIS ORDER: (1) {"sqlite": ...} or {"files": ...} when the data is a database or a file - Fire Code reads it itself; (2) one of Fire Code's Rust tools with "records": true in its args, for files, folders, logs and tables - Rust collects and judges, no Python: find_files (a feed file late or missing: ageMinutes, sizeBytes), grep_files (ERROR lines across logs or shares: path, line, text), big_file action "search" (one huge log: line, text), query_table (a CSV or Excel sheet, filtered and grouped), query_sqlite (action "query"), dataframe (SQL across several files) - e.g. {"tool": "find_files", "args": {"roots": ["//fileserver/feeds"], "names": ["prices_*.csv"], "records": true}}; (3) an existing Python or MCP tool that already returns records; (4) only then a new Python tool - for an API or logic the others cannot do, calling the Rust tools for the heavy lifting. {"tool": "py__name", "args": {...}}: a Python tool (returning a list of records), an MCP tool or a read tool - runs in the background with the settings Fire Code monitoring uses. {"sqlite": "C:\\\\full\\\\path.db", "sql": "select ..."}: read by Fire Code itself, never locked. {"files": ["C:\\\\full\\\\path.csv"], "sql": "select ... from data"}: CSV, TSV, Excel or JSON, queried with SQL (the first file is the table "data", the second "data2").`);
75977
76107
  var createSchema2 = external_exports.object({
75978
76108
  name: external_exports.string().describe('kebab-case, e.g. "overnight-batch" - the monitor and its skill file.'),
75979
76109
  title: external_exports.string().describe('What the tile says, a few words: "Overnight batch".'),
75980
76110
  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('"team" (the default): shown under Team alerts and shared where the team shares skills. "me": a Personal monitor only on this computer. Use "me" when the user says it is just for them.'),
76111
+ 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
76112
  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
76113
  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
76114
  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 +76170,26 @@ function describeEvaluation(e) {
76040
76170
  }
76041
76171
  var message2 = (error51) => error51 instanceof Error ? error51.message : String(error51);
76042
76172
  function createMonitorCreateTool(options) {
76043
- const skillParams = (params3, block2) => ({
76173
+ const skillParams = (params3, block2, audience) => ({
76044
76174
  name: params3.name,
76045
76175
  description: `Monitor: ${params3.summary.replace(/\s+/g, " ").trim()}`,
76046
76176
  body: monitorSkillBody(params3, block2),
76047
- ...params3.audience !== void 0 ? { audience: params3.audience } : {}
76177
+ audience
76048
76178
  });
76179
+ const audienceFor = async (params3) => {
76180
+ if (params3.audience !== void 0)
76181
+ return { audience: params3.audience };
76182
+ try {
76183
+ const listed = await options.channel.request("list");
76184
+ if (listed.teamReady === true)
76185
+ return { audience: "team" };
76186
+ } catch {
76187
+ }
76188
+ return {
76189
+ audience: "me",
76190
+ 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."
76191
+ };
76192
+ };
76049
76193
  const tryIt = async (block2, team = false) => {
76050
76194
  try {
76051
76195
  if (team) {
@@ -76069,7 +76213,7 @@ ${describeEvaluation(tried)}` };
76069
76213
  return {
76070
76214
  name: "monitor_create",
76071
76215
  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 make a personal one ("me") or tell the user. The user approves the skill file; the result shows what the first check found. ` + MONITOR_TOOL_FORMAT,
76216
+ 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
76217
  parametersSchema: createSchema2,
76074
76218
  async preview(params3, context) {
76075
76219
  const block2 = monitorBlock(params3);
@@ -76081,23 +76225,23 @@ ${describeEvaluation(tried)}` };
76081
76225
  ${"tool" in params3.source ? `Run ${params3.source.tool}(${JSON.stringify(params3.source.args ?? {})})` : `Read ${JSON.stringify(params3.source)}`}`
76082
76226
  };
76083
76227
  }
76084
- const tried = await tryIt(block2, params3.audience !== "me");
76228
+ const { audience, note: forWhom } = await audienceFor(params3);
76229
+ const tried = await tryIt(block2, audience === "team");
76085
76230
  if (!tried.ok) {
76086
76231
  return { kind: "text", text: `This monitor cannot be created as written - nothing will be saved:
76087
76232
 
76088
76233
  ${tried.error}` };
76089
76234
  }
76090
- const written = options.writeSkill.preview !== void 0 ? await options.writeSkill.preview(skillParams(params3, block2), context) : void 0;
76235
+ const written = options.writeSkill.preview !== void 0 ? await options.writeSkill.preview(skillParams(params3, block2, audience), context) : void 0;
76091
76236
  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") };
76237
+ 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
76238
  }
76094
- return { kind: "text", text: `${monitorSkillBody(params3, block2)}
76095
-
76096
- ${tried.note}` };
76239
+ return { kind: "text", text: [forWhom, monitorSkillBody(params3, block2), tried.note].filter((n) => n !== void 0).join("\n\n") };
76097
76240
  },
76098
76241
  async execute(params3, context) {
76099
76242
  const block2 = monitorBlock(params3);
76100
- const tried = await tryIt(block2, params3.audience !== "me" && params3.tryOnly !== true);
76243
+ const { audience, note: forWhom } = params3.tryOnly === true ? { audience: "me", note: void 0 } : await audienceFor(params3);
76244
+ const tried = await tryIt(block2, audience === "team");
76101
76245
  if (!tried.ok)
76102
76246
  return { content: `Not created: ${tried.error}`, isError: true };
76103
76247
  if (params3.tryOnly === true) {
@@ -76122,10 +76266,10 @@ ${describeRowsCheck(checkMonitorRows(result.content))}` };
76122
76266
  ${MONITOR_TOOL_FORMAT}`, isError: true };
76123
76267
  }
76124
76268
  }
76125
- const written = await options.writeSkill.execute(skillParams(params3, block2), context);
76269
+ const written = await options.writeSkill.execute(skillParams(params3, block2, audience), context);
76126
76270
  if (written.isError === true)
76127
76271
  return written;
76128
- const lines2 = [written.content];
76272
+ const lines2 = [written.content, ...forWhom !== void 0 ? [forWhom] : []];
76129
76273
  try {
76130
76274
  await options.channel.request("approve", { name: params3.name, block: block2 });
76131
76275
  } catch (error51) {
@@ -76163,7 +76307,7 @@ function createMonitorCheckToolTool(options) {
76163
76307
  return {
76164
76308
  name: "monitor_check_tool",
76165
76309
  group: "command",
76166
- description: 'Run a tool once and check its answer is what a Fire Code monitor needs: a list of records with one type per field, numbers as numbers, ISO timestamps, a field naming each row, failures raised rather than returned. Says PASS or FAIL with what to change, the fields it found, and the "columns" and "key" to give monitor_create. HOW TO MAKE A MONITORING TOOL: (1) reuse a tool that already returns the data if one passes this check; (2) otherwise write a Python tool with create_python_tool (audience "team" for a team monitor, "me" for a personal one) starting from this template, reading the real source - use light_code.credential("name") for a saved credential, never a password in the code:\n' + MONITOR_TOOL_TEMPLATE + '\n(3) call monitor_check_tool and fix the tool until it says PASS; (4) only then call monitor_create with the "columns" and "key" it suggests.',
76310
+ description: 'Run a tool once and check its answer is what a Fire Code monitor needs: a list of records with one type per field, numbers as numbers, ISO timestamps, a field naming each row, failures raised rather than returned. Says PASS or FAIL with what to change, the fields it found, and the "columns" and "key" to give monitor_create. FIRST consider no new tool at all: a SQLite or file source, or a Rust tool with "records": true (find_files, grep_files, big_file search, query_table, query_sqlite, dataframe) - check those with this tool too. HOW TO MAKE A MONITORING TOOL when one is needed: (1) reuse a tool that already returns the data if one passes this check - it must only read, since a monitor runs it unattended; (2) otherwise write a Python tool with create_python_tool (audience "team" for a team monitor, "me" for a personal one) starting from this template, reading the real source - use light_code.credential("name") for a saved credential, never a password in the code:\n' + MONITOR_TOOL_TEMPLATE + '\n(3) call monitor_check_tool and fix the tool until it says PASS; (4) only then call monitor_create with the "columns" and "key" it suggests.',
76167
76311
  parametersSchema: checkToolSchema,
76168
76312
  async preview(params3) {
76169
76313
  return { kind: "text", text: `Run ${params3.tool}(${JSON.stringify(params3.args ?? {}, null, 2)}) once and check what it returns.` };
@@ -76179,10 +76323,20 @@ That is what a monitor shows as purple (cannot tell). Fix the tool and check aga
76179
76323
  isError: true
76180
76324
  };
76181
76325
  }
76182
- return { content: describeRowsCheck(checkMonitorRows(result.content)) };
76326
+ return { content: `${describeRowsCheck(checkMonitorRows(result.content))}
76327
+
76328
+ ${await polarsNote(options)}` };
76183
76329
  }
76184
76330
  };
76185
76331
  }
76332
+ async function polarsNote(options) {
76333
+ const has2 = await options.hasModule?.("polars").catch(() => void 0);
76334
+ if (has2 === true)
76335
+ return "Polars is installed in the tools' environment: use it rather than pandas for reading, filtering and aggregating (return df.to_dicts()).";
76336
+ if (has2 === false)
76337
+ return "Polars is not installed in the tools' environment: plain Python (or pandas, if installed) it is. If the data is big, ask the user whether to install polars (install_python_packages).";
76338
+ return "Could not tell whether Polars is installed; if `import polars` works, prefer it to pandas.";
76339
+ }
76186
76340
  var statusSchema2 = external_exports.object({
76187
76341
  name: external_exports.string().optional().describe("One monitor, for its alerts and rows. Omit for every monitor."),
76188
76342
  rows: external_exports.number().int().min(0).max(1e3).optional().describe("How many rows of one monitor to include. Default 50."),
@@ -81115,7 +81269,7 @@ function wireChatBridge(services) {
81115
81269
  }
81116
81270
  const declared = await declaredCallsOf(caller);
81117
81271
  const isDeclared = declared.some((d) => d === tool.name || `py__${d}` === tool.name);
81118
- if (!pythonNestedCallsAllowed && monitorRunContext !== void 0) {
81272
+ if (monitorRunContext !== void 0) {
81119
81273
  if (!isDeclared) {
81120
81274
  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
81275
  }
@@ -82859,7 +83013,8 @@ ${preview.text}` } : {}
82859
83013
  const monitorOptions = {
82860
83014
  channel: services.monitoring,
82861
83015
  writeSkill,
82862
- runTool: (name, args, toolContext) => executeForMonitor(name, args, toolContext)
83016
+ runTool: (name, args, toolContext) => executeForMonitor(name, args, toolContext),
83017
+ hasModule: async (module2) => (await python.hasModules([module2]))?.[module2]
82863
83018
  };
82864
83019
  combined.register(createMonitorCreateTool(monitorOptions));
82865
83020
  combined.register(createMonitorStatusTool(monitorOptions));
@@ -85941,7 +86096,7 @@ ${redact(shown2, cachedSecretValues)}` }
85941
86096
  return [];
85942
86097
  }
85943
86098
  }
85944
- async function executeForMonitor(name, args, given, signal) {
86099
+ async function monitorToolHere(name) {
85945
86100
  const { config: config2 } = await configManager.load();
85946
86101
  if (!monitorSettingsLoaded) {
85947
86102
  monitorSettingsLoaded = true;
@@ -85952,9 +86107,22 @@ ${redact(shown2, cachedSecretValues)}` }
85952
86107
  await python.configure({ ...config2.python ?? {}, ...pythonFolders(config2) });
85953
86108
  const registry2 = currentToolRegistry();
85954
86109
  const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
86110
+ if (tool === void 0) {
86111
+ const bare = name.replace(/^py__/, "");
86112
+ const waiting = python.status().issues.find((issue2) => issue2.name === bare);
86113
+ if (waiting !== void 0)
86114
+ return { refusal: `${name} is on this computer but not loaded: ${waiting.detail}` };
86115
+ }
85955
86116
  const refusal = monitorToolRefusal(tool, name);
85956
86117
  if (refusal !== void 0 || tool === void 0)
85957
- return { content: refusal ?? `No tool called "${name}".`, isError: true };
86118
+ return { refusal: refusal ?? `No tool called "${name}".` };
86119
+ return { tool };
86120
+ }
86121
+ async function executeForMonitor(name, args, given, signal) {
86122
+ const here = await monitorToolHere(name);
86123
+ if ("refusal" in here)
86124
+ return { content: here.refusal, isError: true };
86125
+ const tool = here.tool;
85958
86126
  const parsed = tool.parametersSchema.safeParse(args);
85959
86127
  if (!parsed.success)
85960
86128
  return { content: `The arguments do not fit ${tool.name}: ${parsed.error.message}`, isError: true };
@@ -86011,12 +86179,19 @@ ${redact(shown2, cachedSecretValues)}` }
86011
86179
  case "write":
86012
86180
  await store.write(args["record"]);
86013
86181
  return { by: store.by };
86182
+ case "writeGrid":
86183
+ await store.writeGrid(monitor, String(args["hash"] ?? ""), args["evaluation"]);
86184
+ return { by: store.by };
86185
+ case "grid":
86186
+ return await store.grid(monitor, String(args["hash"] ?? "")) ?? null;
86014
86187
  case "latest":
86015
86188
  return store.latest(Array.isArray(args["monitors"]) ? args["monitors"] : []);
86016
86189
  case "history":
86017
- return store.history(monitor, Number(args["since"] ?? 0), Number(args["limit"] ?? 500));
86190
+ return store.history(monitor, Number(args["since"] ?? 0), Number(args["limit"] ?? 500), typeof args["until"] === "number" ? args["until"] : void 0);
86018
86191
  case "prune":
86019
86192
  return { deleted: await store.prune(Number(args["before"] ?? 0), monitor.length > 0 ? monitor : void 0) };
86193
+ case "deleteCheck":
86194
+ return { deleted: await store.deleteCheck(monitor, Number(args["at"] ?? 0)) };
86020
86195
  case "test":
86021
86196
  await store.ensureIndex();
86022
86197
  return { index: store.index, by: store.by };
@@ -86050,6 +86225,14 @@ ${redact(shown2, cachedSecretValues)}` }
86050
86225
  return { ok: true, data: await answerMonitorStore(request.op, await monitorStore(request.storeId, request.index), request.args) };
86051
86226
  case "explain":
86052
86227
  return { ok: true, data: await explainForMonitor(request.context) };
86228
+ case "probe": {
86229
+ const here = await monitorToolHere(request.tool);
86230
+ return { ok: true, data: "refusal" in here ? { ready: false, reason: here.refusal } : { ready: true } };
86231
+ }
86232
+ case "skill": {
86233
+ const done = request.op === "write" ? await writeTeamMonitorSkill(request.file, request.content ?? "") : await deleteEverywhere(await planDeleteEverywhere("skill", request.name));
86234
+ return done.ok ? { ok: true, data: done.message } : { ok: false, error: done.message };
86235
+ }
86053
86236
  }
86054
86237
  } catch (error51) {
86055
86238
  return { ok: false, error: error51 instanceof Error ? error51.message : String(error51) };
@@ -86526,7 +86709,17 @@ ${redact(shown2, cachedSecretValues)}` }
86526
86709
  }
86527
86710
  async function handleDeleteEverywhere(requested2) {
86528
86711
  const { kind, name } = requested2;
86529
- const done = (ok, message5) => post({ type: "deleteEverywhereDone", kind, name, ok, message: message5 });
86712
+ const result = await deleteEverywhere(requested2);
86713
+ post({ type: "deleteEverywhereDone", kind, name, ok: result.ok, message: result.message });
86714
+ }
86715
+ async function deleteEverywhere(requested2) {
86716
+ const { kind, name } = requested2;
86717
+ if (requested2.error !== void 0)
86718
+ return { ok: false, message: requested2.error };
86719
+ let answer = { ok: false, message: "Nothing was done." };
86720
+ const done = (ok, message5) => {
86721
+ answer = { ok, message: message5 };
86722
+ };
86530
86723
  try {
86531
86724
  const config2 = await loadSettings();
86532
86725
  const team = teamRepoPlan(config2);
@@ -86548,7 +86741,7 @@ ${redact(shown2, cachedSecretValues)}` }
86548
86741
  });
86549
86742
  if (result.failed !== void 0) {
86550
86743
  done(false, `Not deleted: the repository refused ${result.failed.path} (${result.failed.problem}). Nothing else was removed, so it stays consistent - try again.`);
86551
- return;
86744
+ return answer;
86552
86745
  }
86553
86746
  parts.push(`Marked deleted in the team repository ${fresh.repoLabel ?? ""} (${String(result.done.length)} file(s)); colleagues' copies go at their next sync.`);
86554
86747
  }
@@ -86592,6 +86785,64 @@ ${redact(shown2, cachedSecretValues)}` }
86592
86785
  } catch (error51) {
86593
86786
  done(false, error51 instanceof Error ? error51.message : String(error51));
86594
86787
  }
86788
+ return answer;
86789
+ }
86790
+ async function writeTeamMonitorSkill(file2, content) {
86791
+ const config2 = await loadSettings();
86792
+ const norm2 = (value) => process.platform === "win32" ? import_node_path52.default.resolve(value).toLowerCase() : import_node_path52.default.resolve(value);
86793
+ const inside = (dir) => {
86794
+ const target = norm2(file2);
86795
+ const root = norm2(dir);
86796
+ return target.startsWith(root + import_node_path52.default.sep) ? import_node_path52.default.relative(import_node_path52.default.resolve(dir), import_node_path52.default.resolve(file2)) : void 0;
86797
+ };
86798
+ const saveIn = async (dir, relative) => {
86799
+ const destination = import_node_path52.default.join(dir, relative);
86800
+ const enabled = cachedSkillMirrors.filter((each) => each.enabled === true);
86801
+ const mirror = enabled.find((_, i) => samePath(mirroredSkillsDirs[i], dir));
86802
+ const target = mirror !== void 0 ? targetById(cachedS3, mirror.connectionId) : void 0;
86803
+ if (mirror !== void 0 && (target === void 0 || target.readOnly === true)) {
86804
+ throw new Error(`${target?.label ?? mirror.connectionId} is read-only here, so this team monitor cannot be changed from this computer - ask whoever owns that bucket.`);
86805
+ }
86806
+ await import_promises29.default.mkdir(import_node_path52.default.dirname(destination), { recursive: true });
86807
+ await writeFileAtomically(destination, content);
86808
+ if (mirror !== void 0 && target !== void 0) {
86809
+ await uploadToS3({ target, ...mirror.prefix !== void 0 ? { prefix: mirror.prefix } : {}, relative: relative.split(import_node_path52.default.sep).join("/"), contents: Buffer.from(content, "utf8") });
86810
+ return `uploaded to the bucket ${target.label}`;
86811
+ }
86812
+ return `saved in ${dir}`;
86813
+ };
86814
+ try {
86815
+ for (const dir of mirroredSkillsDirs) {
86816
+ const relative = inside(dir);
86817
+ if (relative !== void 0) {
86818
+ const where = await saveIn(dir, relative);
86819
+ await refreshSkills();
86820
+ return { ok: true, message: `Saved and ${where}; colleagues get it at their next sync and approve it once.` };
86821
+ }
86822
+ }
86823
+ const team = teamRepoPlan(config2);
86824
+ if ("dirs" in team) {
86825
+ const relative = inside(team.dirs.skills);
86826
+ if (relative !== void 0) {
86827
+ if (skillsDir === void 0)
86828
+ throw new Error("There is no folder to save skills in, so the change cannot reach the team repository.");
86829
+ const where = await saveIn(skillsDir, relative);
86830
+ await handleTeamRepoSync("a monitor changed on the dashboard");
86831
+ const problem = teamRepoStatus?.error ?? teamRepoStatus?.conflicts.find((c2) => c2.path.endsWith(relative.split(import_node_path52.default.sep).join("/")))?.reason;
86832
+ if (problem !== void 0) {
86833
+ return { ok: false, message: `Saved here (${where}), but not committed to the team repository: ${problem}. Nothing was overwritten - see Settings \u2192 DevOps \u2192 Team repository.` };
86834
+ }
86835
+ await refreshSkills();
86836
+ return { ok: true, message: `Saved and committed to the team repository ${cachedTeamRepoLabel ?? ""}; colleagues get it at their next sync and approve it once.` };
86837
+ }
86838
+ }
86839
+ return {
86840
+ ok: false,
86841
+ message: `${file2} is not in a bucket folder or the team repository that the settings monitoring runs with know about. Choose the codebase that has them in Fire Code \u2192 Settings \u2192 Monitoring ("Run tools with the settings of").`
86842
+ };
86843
+ } catch (error51) {
86844
+ return { ok: false, message: error51 instanceof Error ? error51.message : String(error51) };
86845
+ }
86595
86846
  }
86596
86847
  let cachedTeamRepoLabel;
86597
86848
  function sharedWith(kind) {
@@ -88303,6 +88554,45 @@ ${last}` : ""}`);
88303
88554
  };
88304
88555
  }
88305
88556
  }
88557
+ async function showPythonTab() {
88558
+ if (!python.status().ready && !userTurnRunning && runningScheduleId === void 0) {
88559
+ const config2 = await loadSettings();
88560
+ if (config2.python?.dynamicTools === "on")
88561
+ await postPython(await python.previewStatus(pythonFolders(config2)));
88562
+ }
88563
+ await configurePythonFromSettings();
88564
+ await postPython();
88565
+ }
88566
+ async function handleCheckTeamTools() {
88567
+ const { config: config2 } = await configManager.load();
88568
+ const bucket = (config2.s3?.tools ?? []).some((mirror) => mirror.enabled === true);
88569
+ const repo = config2.teamRepo?.enabled === true;
88570
+ if (!bucket && !repo) {
88571
+ post({ type: "teamToolsChecked", ok: false, message: "No team bucket folder for tools (Settings \u2192 S3) and no team repository (Settings \u2192 DevOps) is set up here, so there is nothing to pull." });
88572
+ return;
88573
+ }
88574
+ const waitingBefore = new Set(python.status().issues.filter((issue2) => issue2.recoverable).map((issue2) => issue2.filePath));
88575
+ const notes = [];
88576
+ if (bucket) {
88577
+ await handleSyncS3("tools");
88578
+ if (lastSync.tools !== void 0)
88579
+ notes.push(lastSync.tools);
88580
+ }
88581
+ if (repo) {
88582
+ await handleTeamRepoSync("checked by hand");
88583
+ if (teamRepoStatus?.error !== void 0)
88584
+ notes.push(`Team repository: ${teamRepoStatus.error}`);
88585
+ else if (teamRepoStatus !== void 0)
88586
+ notes.push(`Team repository: ${String(teamRepoStatus.pulled.length)} file(s) came down.`);
88587
+ }
88588
+ await configurePythonFromSettings();
88589
+ await python.refresh();
88590
+ await postPython();
88591
+ const waiting = python.status().issues.filter((issue2) => issue2.recoverable);
88592
+ const fresh = waiting.filter((issue2) => !waitingBefore.has(issue2.filePath));
88593
+ const summary = fresh.length > 0 ? `${String(fresh.length)} new tool(s) to review: ${fresh.map((issue2) => issue2.name).join(", ")}.` : waiting.length > 0 ? `Nothing new; ${String(waiting.length)} tool(s) still waiting for your approval.` : "No new tools waiting for approval.";
88594
+ post({ type: "teamToolsChecked", ok: true, message: [summary, ...notes].join(" ") });
88595
+ }
88306
88596
  async function configurePythonFromSettings() {
88307
88597
  if (userTurnRunning || runningScheduleId !== void 0)
88308
88598
  return;
@@ -88862,11 +89152,11 @@ ${last}` : ""}`);
88862
89152
  if (usageCollecting())
88863
89153
  void pushUsageNow();
88864
89154
  }
88865
- async function postPython() {
89155
+ async function postPython(preview) {
88866
89156
  const saved = await configManager.load().then((loaded) => loaded.config.python, () => void 0) ?? {};
88867
89157
  post({
88868
89158
  type: "python",
88869
- status: python.status(),
89159
+ status: preview ?? python.status(),
88870
89160
  settings: {
88871
89161
  dynamicTools: saved.dynamicTools ?? "off",
88872
89162
  ...saved.uvPath !== void 0 ? { uvPath: saved.uvPath } : {},
@@ -90595,7 +90885,9 @@ ${last}` : ""}`);
90595
90885
  } else if (message5.type === "deleteSkillFile") {
90596
90886
  reportFailure("handleDeleteSkillFile", handleDeleteSkillFile(message5.name));
90597
90887
  } else if (message5.type === "requestPython") {
90598
- reportFailure("postPython", configurePythonFromSettings().then(postPython));
90888
+ reportFailure("postPython", showPythonTab());
90889
+ } else if (message5.type === "checkTeamTools") {
90890
+ reportFailure("handleCheckTeamTools", handleCheckTeamTools());
90599
90891
  } else if (message5.type === "setPython") {
90600
90892
  reportFailure("handleSetPython", handleSetPython(message5));
90601
90893
  } else if (message5.type === "requestUsage") {
@@ -92896,6 +93188,11 @@ git is the main defence.
92896
93188
  "dynamic",
92897
93189
  "registry",
92898
93190
  "missing package",
93191
+ "new team tools",
93192
+ "check for new tools",
93193
+ "pull tools",
93194
+ "tools not showing for approval",
93195
+ "python tab slow",
92899
93196
  "install package",
92900
93197
  "module not found",
92901
93198
  "library",
@@ -92936,6 +93233,12 @@ installed or removed: that environment belongs to whatever built it.
92936
93233
  as an ImportError from inside the worker. config:python.indexUrl points at an internal mirror and
92937
93234
  config:python.offline refuses the network.
92938
93235
 
93236
+ **A colleague's new tool, now**: Settings \u2192 Python \u2192 **Check for new team tools** pulls the team's bucket tool
93237
+ folders and the team repository straight away (instead of at the next sync, every 15 minutes by default) and
93238
+ says what came down; anything new appears above the chat for approval. The Python tab shows the tools already
93239
+ approved at once, marked "Starting Python\u2026", and fills in the rest once Python is running - starting uv and
93240
+ Python can take seconds on a managed machine.
93241
+
92939
93242
  **Missing packages are spotted before they fail.** Tools arriving from a bucket often need packages
92940
93243
  this machine's environment lacks. Light Code checks every tool's declared dependencies and imports
92941
93244
  against the environment; a tool that needs something missing says so in its description, the
@@ -94252,7 +94555,9 @@ the Windows VS Code package carries a slim one with every tool below except \`da
94252
94555
 
94253
94556
  To see whether they are on right now, look at the tool list in Settings \u2192 Tools, or ask "which tools do
94254
94557
  you have?" - the assistant answers from the tools it was actually given.
94255
- `
94558
+
94559
+
94560
+ **For a monitor**: find_files, grep_files, big_file (search), query_table, query_sqlite and dataframe take \`"records": true\` and answer as a JSON list of records, so a Fire Code monitor can use them as its source directly - Rust collects, Rust judges, no Python in between. See the Monitoring topic.`
94256
94561
  },
94257
94562
  {
94258
94563
  id: "confluence",
@@ -94490,7 +94795,49 @@ edits made outside the agent (in VS Code, say) are saved with \`hub_sync\` "push
94490
94795
  "cleanup",
94491
94796
  "opensearch history",
94492
94797
  "explain alert",
94493
- "tool_calls"
94798
+ "tool_calls",
94799
+ "edit schedule",
94800
+ "change schedule",
94801
+ "delete monitor",
94802
+ "delete check",
94803
+ "remove monitor",
94804
+ "personal monitor",
94805
+ "personal check",
94806
+ "monitor schedule",
94807
+ "schedule of a monitor",
94808
+ "monitor check",
94809
+ "monitoring check",
94810
+ "snooze until",
94811
+ "snooze row",
94812
+ "review all",
94813
+ "approve several monitors",
94814
+ "run history",
94815
+ "past failures",
94816
+ "polars",
94817
+ "team monitors",
94818
+ "approve monitors",
94819
+ "approve the team monitors",
94820
+ "offline",
94821
+ "runs elsewhere",
94822
+ "claim",
94823
+ "who runs the check",
94824
+ "not shared",
94825
+ "team checks",
94826
+ "my checks",
94827
+ "checks offline",
94828
+ "past failure",
94829
+ "specific date",
94830
+ "grid as it was",
94831
+ "delete a check",
94832
+ "delete one check",
94833
+ "rust tools",
94834
+ "find_files",
94835
+ "grep_files",
94836
+ "records",
94837
+ "only alerted rows",
94838
+ "all rows",
94839
+ "lazy load",
94840
+ "many rows"
94494
94841
  ],
94495
94842
  body: `
94496
94843
  **Fire Code only.** Settings \u2192 Monitoring switches it on; a Monitoring button then appears at the top of the
@@ -94532,11 +94879,66 @@ while it stays red or amber, a quiet word when it clears, and quiet hours when o
94532
94879
  Each monitor can override it (right-click \u2192 How this one notifies), and its own \`notify\` sets the least
94533
94880
  severe level that notifies. Notifications have Open, Acknowledge and Snooze buttons.
94534
94881
 
94535
- **When checks run**: \`every\` ("15m") for an interval, kept to \`activeHours\` ("07:00-19:00", or "09:00-" for not
94882
+ **When checks run**: \`every\` ("15m") for an interval - once in each window of the clock (every 10 minutes is
94883
+ 10:00, 10:10, 10:20 ..., windows counted from UTC so a team across time zones agrees), whoever joined when, kept to \`activeHours\` ("07:00-19:00", or "09:00-" for not
94536
94884
  before nine, "-17:00" for until five); \`at\` for exact times of day ("07:30" - once a day - or ["07:30", "12:00",
94537
94885
  "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
94886
  next day.
94539
94887
 
94888
+ **Change when it runs**: in its grid window, **Schedule** (or right-click a tile \u2192 Edit schedule\u2026): every N minutes
94889
+ or hours, only between two times (either may be empty), at set times of day, on chosen days. Saving writes only those
94890
+ fields into the skill file and keeps an approved monitor approved. An agent can change it too ("run the batch check
94891
+ every 10 minutes on weekdays"); you approve the change as a diff.
94892
+
94893
+ **Delete a monitor for good**: right-click its tile \u2192 Delete this monitor\u2026 (or \u22EF \u2192 Delete in its window). Its skill
94894
+ file, its results and history here, and your own checks in the team history go; Pause stops it for a while instead.
94895
+ A copy synced from the team's bucket or repository is changed or deleted **where the team keeps it** - uploaded
94896
+ to the bucket or committed to the repository (a deletion goes from the repository, the bucket and this computer,
94897
+ like Delete everywhere in Settings \u2192 Skills) - so the next sync does not put the old one back. Colleagues get the
94898
+ change at their next sync and approve it once. This uses the bucket and repository of the codebase chosen under
94899
+ Settings \u2192 Monitoring ("Run tools with the settings of").
94900
+
94901
+ **Snooze**: right-click a tile \u2192 Snooze 1 hour / until tomorrow / **Snooze until\u2026** (a date and time, up to 30 days),
94902
+ or the Snooze button in its window. **One row**: right-click the row in the grid (or **Snooze row** in its details)
94903
+ \u2192 1 hour, 4 hours, until tomorrow 09:00, or until a date and time - its alerts stop counting until then, unless one
94904
+ gets worse, which counts again at once.
94905
+
94906
+ **Reviewing a colleague's monitors**: a blue banner on the dashboard says how many wait for your review; **Review
94907
+ all\u2026** lists each with its definition and a tick box - approve the ones you ticked (Select all ticks every one).
94908
+
94909
+ **Run history**: the wide button across the bottom of each tile shows the last checks as bars, oldest on the left.
94910
+ Press it for the monitor's History - every check kept, earlier days too (24 hours to 90 days, or **On** a chosen
94911
+ date); press one bar to open on that check. Choosing a check shows, under the bars: its time, result, who ran it,
94912
+ rows read, how long it took, and **its whole grid as it was** - every row, coloured as it was - straight away;
94913
+ **Open in grid view** for filters and sorting, read-only, with **Back to now**. Whole grids are kept from Fire Code
94914
+ 0.64.0 on, once per distinct grid, for as long as its history; a **team** check's grid is also shared in the team
94915
+ index (from 0.65.0), so **every member sees every row** of the newest check and of past ones, whoever ran it. A grid
94916
+ over 5,000 rows or about 2 MB is not shared - members then see its alerted rows, and an older check says why.
94917
+
94918
+ **Big grids** are drawn as you scroll: the first 200 rows at once, more as the bottom comes near - filters, search,
94919
+ sorting and counts cover every row. **Delete this check**
94920
+ removes one check: here, and your own record of it in the team history.
94921
+
94922
+ **A team check is collected once, not once per person**: each scheduled run is claimed in the team index first, so
94923
+ one member's Fire Code runs it and everyone sees that result ("checked by \u2026"); **Run now** claims a two-minute slot, so
94924
+ people pressing it together get one check. The full history is stored once, in the team index; each computer keeps
94925
+ only the newest 200 checks of a team monitor, for its tile.
94926
+
94927
+ **Only a computer that can run it claims it.** Before claiming, Fire Code checks the monitor can run here: a SQLite
94928
+ or file source's path is reachable, a tool exists, is approved here and is allowed for monitors (checked without
94929
+ running it, re-checked every 10 minutes). A computer that cannot leaves it to colleagues, and its tile says **Runs
94930
+ elsewhere** with the reason on hover. A check that **failed** here (a credential, a network route) makes this computer
94931
+ step back for three windows (at least 30 minutes) while a colleague's runs succeed - unless nobody has checked it for
94932
+ a window, when it tries again rather than leave it unrun.
94933
+
94934
+ **Offline**: when the team history cannot be reached, a team monitor still runs on this computer - its tile, colours
94935
+ and notifications stay current - and the tile says **Offline \xB7 N not shared**. Once the history answers again, each
94936
+ offline check claims its window: written if nobody had it, dropped if a colleague already checked that window. At
94937
+ most 50 per monitor are kept for this, on disk.
94938
+
94939
+ **Personal monitors need nothing set up.** Ask for "a personal check" (or just a check, before team history exists)
94940
+ and the agent makes one only on this computer.
94941
+
94540
94942
  **Team monitors need OpenSearch** (Settings \u2192 Monitoring \u2192 Team history): choose an OpenSearch connection from the
94541
94943
  codebase monitoring runs with, and an index name the whole team shares. Without it a team monitor stays grey
94542
94944
  ("Needs team history"); personal monitors keep their history on this computer. Every member's Fire Code may run a
@@ -94555,9 +94957,19 @@ the monitor is created), then **the agent's explanation** - what is wrong, wheth
94555
94957
  history, what to do. **Start a chat** opens a chat named after the alert in the codebase you pick (the first by
94556
94958
  default), with what is known already in the message box - press Enter to send it.
94557
94959
 
94960
+ **Fast data collection**: a monitor that reads SQLite or a CSV/Excel/JSON file is read by Fire Code's Rust helper
94961
+ (Polars) - no Python at all. Fire Code's Rust tools can be a monitor's source too, with \`"records": true\` (a JSON list
94962
+ of records): find_files (a feed file late or missing - ageMinutes, sizeBytes), grep_files (ERROR lines across logs or
94963
+ shares), big_file search (one huge log), query_table, query_sqlite and dataframe. Prefer, in order: a SQLite or file
94964
+ source, a Rust tool, an existing Python or MCP tool that returns records, and only then a new Python tool. Reusing an
94965
+ existing Python tool is fine when it only reads and is approved on each member's computer. A Python tool source is Python: the agent is told whether Polars is installed in the tools'
94966
+ environment and to prefer it to pandas (filter and aggregate there, return df.to_dicts()). Rust then judges the rows.
94967
+
94558
94968
  **Tools can call tools**: a Python tool lists what it calls in \`__tool_calls__ = ["server__query", "autosys_status"]\`
94559
94969
  - 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, and nothing that edits or runs commands is reachable.
94970
+ monitor's check those calls run without asking - the same when the agent tries the monitor in a chat - and nothing
94971
+ that edits or runs commands is reachable. A tool calling another Python tool several times works (before Fire Code
94972
+ 0.61.0 only the first call did, which read as an approval problem).
94561
94973
 
94562
94974
  **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
94975
  to change, and the columns and key for the monitor - an agent writing a Python tool for a monitor works until