@chosengeneration/light-code 0.163.0 → 0.165.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/cli.cjs +623 -103
  2. package/dist/server.cjs +612 -94
  3. package/package.json +1 -1
package/dist/server.cjs CHANGED
@@ -57384,8 +57384,8 @@ async function random(size) {
57384
57384
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
57385
57385
  let result = "";
57386
57386
  while (result.length < size) {
57387
- const randomBytes4 = await getRandomValues(size - result.length);
57388
- for (const randomByte of randomBytes4) {
57387
+ const randomBytes5 = await getRandomValues(size - result.length);
57388
+ for (const randomByte of randomBytes5) {
57389
57389
  if (randomByte < evenDistCutoff) {
57390
57390
  result += mask[randomByte % mask.length];
57391
57391
  }
@@ -61221,12 +61221,18 @@ var import_promises13 = __toESM(require("node:fs/promises"), 1);
61221
61221
  function declaresAlwaysAsk(source) {
61222
61222
  return /^__always_ask__\s*(?::[^=\n]*)?=\s*True\b/m.test(source);
61223
61223
  }
61224
- function declaredCredentials(source) {
61225
- const match = /^__credentials__\s*(?::[^=\n]*)?=\s*[[(]([\s\S]*?)[\])]/m.exec(source);
61224
+ function declaredList(source, name) {
61225
+ const match = new RegExp(`^${name}\\s*(?::[^=\\n]*)?=\\s*[[(]([\\s\\S]*?)[\\])]`, "m").exec(source);
61226
61226
  if (match === null)
61227
61227
  return [];
61228
61228
  return [...(match[1] ?? "").matchAll(/(["'])((?:(?!\1)[^\\\n]|\\.)*)\1/g)].map((m) => m[2] ?? "").filter((s) => s.length > 0);
61229
61229
  }
61230
+ function declaredCredentials(source) {
61231
+ return declaredList(source, "__credentials__");
61232
+ }
61233
+ function declaredToolCalls(source) {
61234
+ return declaredList(source, "__tool_calls__");
61235
+ }
61230
61236
 
61231
61237
  // ../../packages/core/dist/python/tools.js
61232
61238
  var import_node_path26 = __toESM(require("node:path"), 1);
@@ -61500,6 +61506,7 @@ function makeWriteTool(context, options) {
61500
61506
  const notes = [
61501
61507
  ...producedBy !== void 0 ? [`Written by ${producedBy}`] : [],
61502
61508
  ...reads.length > 0 ? [`Reads saved credentials: ${reads.join(", ")}`] : [],
61509
+ ...declaredToolCalls(source).length > 0 ? [`Calls tools: ${declaredToolCalls(source).join(", ")}`] : [],
61503
61510
  ...declaresAlwaysAsk(source) ? ["Always asks before every run, for everyone who has this tool (__always_ask__ = True)"] : [],
61504
61511
  ...[toolAudienceNote(context, target.personal)].filter((note) => note !== void 0)
61505
61512
  ];
@@ -61776,7 +61783,7 @@ The module "${module2}" is not installed in the tools' Python environment, and L
61776
61783
  }
61777
61784
 
61778
61785
  // ../../packages/core/dist/python/workerSource.js
61779
- 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';
61780
61787
 
61781
61788
  // ../../packages/core/dist/python/manager.js
61782
61789
  function labelFields(labels) {
@@ -63266,7 +63273,7 @@ The conversation is longer than this model accepts, and it could not be shortene
63266
63273
  }
63267
63274
 
63268
63275
  // ../../packages/core/dist/host/bridge.js
63269
- var import_node_crypto16 = require("node:crypto");
63276
+ var import_node_crypto17 = require("node:crypto");
63270
63277
 
63271
63278
  // ../../packages/core/dist/atlassian/autosysGateway.js
63272
63279
  function withBasicCredentials(auth2, headerName, username, password) {
@@ -74106,6 +74113,16 @@ function asList(value) {
74106
74113
  }
74107
74114
  return [];
74108
74115
  }
74116
+ function pagingNote(value, returned, what) {
74117
+ if (value === null || typeof value !== "object" || Array.isArray(value))
74118
+ return void 0;
74119
+ const o = value;
74120
+ const total = ["total", "totalCount", "totalRecords", "totalResults", "totalSize", "numFound", "count", "size"].map((k) => Number(o[k])).find((n) => Number.isFinite(n) && n > returned);
74121
+ const next = ["next", "nextPage", "nextLink", "hasMore", "more", "moreResults"].some((k) => o[k] === true || typeof o[k] === "string" && o[k].length > 0);
74122
+ if (total === void 0 && !next)
74123
+ return void 0;
74124
+ return `AutoSys answered ${String(returned)} ${what}${total !== void 0 ? ` of ${String(total)}` : ""} - it pages its answers, so some are missing. Add its page-size parameter to the address (config:autosys paths, e.g. "/job-run-info?filter={filter:name}&limit=1000" - the name of the parameter is in the server's API documentation or the office wiki); autosys_check_addresses shows what each address answers.`;
74125
+ }
74109
74126
  function field(record2, ...names) {
74110
74127
  for (const name of names) {
74111
74128
  const value = record2[name];
@@ -74183,6 +74200,11 @@ var AutosysClient = class _AutosysClient {
74183
74200
  get base() {
74184
74201
  return this.rest.base;
74185
74202
  }
74203
+ /** What the last calls found worth saying - an answer that pages - for the tool to pass on, once. */
74204
+ notes = [];
74205
+ takeNotes() {
74206
+ return [...new Set(this.notes.splice(0))];
74207
+ }
74186
74208
  /** The address templates in use, defaults included. */
74187
74209
  get addresses() {
74188
74210
  return { ...this.paths };
@@ -74230,7 +74252,12 @@ var AutosysClient = class _AutosysClient {
74230
74252
  async findJobs(pattern, signal) {
74231
74253
  if (!isAutosysName(pattern, true))
74232
74254
  throw new AtlassianError(`"${pattern}" is not a job name or pattern \u2014 letters, digits, . _ - # and * only.`);
74233
- return asList(await this.rest.json("finding jobs", fill(this.paths.jobs, { pattern }), { method: "GET" }, signal));
74255
+ const answer = await this.rest.json("finding jobs", fill(this.paths.jobs, { pattern }), { method: "GET" }, signal);
74256
+ const list2 = asList(answer);
74257
+ const note = pagingNote(answer, list2.length, `jobs for ${pattern}`);
74258
+ if (note !== void 0)
74259
+ this.notes.push(note);
74260
+ return list2;
74234
74261
  }
74235
74262
  async job(name, signal) {
74236
74263
  if (!isAutosysName(name))
@@ -74259,7 +74286,12 @@ var AutosysClient = class _AutosysClient {
74259
74286
  if (!pattern.includes("*"))
74260
74287
  return this.oneRun(pattern, signal);
74261
74288
  try {
74262
- return asList(await this.rest.json(`reading the status of ${pattern}`, fill(this.paths.runInfo, { pattern }), { method: "GET" }, signal)).map(toRun);
74289
+ const answer = await this.rest.json(`reading the status of ${pattern}`, fill(this.paths.runInfo, { pattern }), { method: "GET" }, signal);
74290
+ const list2 = asList(answer);
74291
+ const note = pagingNote(answer, list2.length, `statuses for ${pattern}`);
74292
+ if (note !== void 0)
74293
+ this.notes.push(note);
74294
+ return list2.map(toRun);
74263
74295
  } catch (error51) {
74264
74296
  if (!(error51 instanceof AtlassianError && error51.status === 404))
74265
74297
  throw error51;
@@ -74434,11 +74466,13 @@ function createAutosysFindJobsTool(options) {
74434
74466
  async execute(params3) {
74435
74467
  try {
74436
74468
  const pattern = params3.pattern ?? options.defaultPattern ?? "*";
74437
- const all = await (await options.client()).findJobs(pattern);
74469
+ const client = await options.client();
74470
+ const all = await client.findJobs(pattern);
74471
+ const notes = client.takeNotes();
74438
74472
  const jobs = all.filter((job) => definitionMatches(job, params3));
74439
74473
  if (jobs.length === 0) {
74440
74474
  return {
74441
- content: all.length === 0 ? `No AutoSys jobs match ${pattern}.` : `None of the ${String(all.length)} job(s) matching ${pattern} pass those filters.`
74475
+ content: [all.length === 0 ? `No AutoSys jobs match ${pattern}.` : `None of the ${String(all.length)} job(s) matching ${pattern} pass those filters.`, ...notes].join("\n\n")
74442
74476
  };
74443
74477
  }
74444
74478
  const shown2 = jobs.slice(0, params3.limit ?? 50);
@@ -74451,7 +74485,8 @@ function createAutosysFindJobsTool(options) {
74451
74485
  const machine = field(job, "machine");
74452
74486
  const owner = field(job, "owner");
74453
74487
  return `- ${field(job, "name", "jobName") ?? "?"} (${field(job, "jobType", "job_type", "type") ?? "?"}${box !== void 0 ? `, in box ${box}` : ""}${machine !== void 0 ? `, on ${machine}` : ""}${owner !== void 0 ? `, owner ${owner}` : ""})`;
74454
- })
74488
+ }),
74489
+ ...notes.length > 0 ? ["", ...notes] : []
74455
74490
  ].join("\n")
74456
74491
  };
74457
74492
  } catch (error51) {
@@ -74671,7 +74706,8 @@ function createAutosysStatusTool(options) {
74671
74706
  };
74672
74707
  }
74673
74708
  const asked = wanted.join(", ");
74674
- const unreadable = problems.length > 0 ? ["", "Could not read:", ...problems.map((problem) => `- ${problem}`)] : [];
74709
+ const paging = client.takeNotes();
74710
+ const unreadable = [...problems.length > 0 ? ["", "Could not read:", ...problems.map((problem) => `- ${problem}`)] : [], ...paging.length > 0 ? ["", ...paging] : []];
74675
74711
  if (runs.length === 0) {
74676
74712
  return {
74677
74713
  content: [
@@ -75576,6 +75612,193 @@ function monitorToolRefusal(tool, name) {
75576
75612
  return void 0;
75577
75613
  }
75578
75614
 
75615
+ // ../../packages/core/dist/monitoring/history.js
75616
+ var import_node_crypto15 = require("node:crypto");
75617
+ var MAPPING = {
75618
+ mappings: {
75619
+ dynamic: false,
75620
+ properties: {
75621
+ kind: { type: "keyword" },
75622
+ monitor: { type: "keyword" },
75623
+ by: { type: "keyword" },
75624
+ at: { type: "long" },
75625
+ slot: { type: "long" },
75626
+ level: { type: "keyword" },
75627
+ alertIds: { type: "keyword" },
75628
+ alertKeys: { type: "keyword" },
75629
+ payload: { type: "object", enabled: false }
75630
+ }
75631
+ }
75632
+ };
75633
+ var MonitorHistoryError = class extends Error {
75634
+ status;
75635
+ constructor(message5, status2) {
75636
+ super(message5);
75637
+ this.status = status2;
75638
+ this.name = "MonitorHistoryError";
75639
+ }
75640
+ };
75641
+ function docId(...parts) {
75642
+ return parts.map((p) => String(p)).map((p) => /^[A-Za-z0-9._-]{1,80}$/.test(p) ? p : (0, import_node_crypto15.createHash)("sha256").update(p).digest("hex").slice(0, 16)).join(":");
75643
+ }
75644
+ var MonitorHistoryStore = class {
75645
+ http;
75646
+ connection;
75647
+ index;
75648
+ by;
75649
+ ensured = false;
75650
+ constructor(http, connection, index, by) {
75651
+ this.http = http;
75652
+ this.connection = connection;
75653
+ this.index = index;
75654
+ this.by = by;
75655
+ if (!isSafeIndexName(index))
75656
+ throw new MonitorHistoryError(`"${index}" is not a usable index name (lowercase letters, digits, - and _).`);
75657
+ }
75658
+ async send(method, path63, body) {
75659
+ const headers = { "Content-Type": "application/json" };
75660
+ const { username, password } = this.connection;
75661
+ if (username !== void 0 && username.length > 0) {
75662
+ headers.Authorization = `Basic ${Buffer.from(`${username}:${password ?? ""}`).toString("base64")}`;
75663
+ }
75664
+ const url2 = `${this.connection.url.replace(/\/+$/, "")}/${encodeURIComponent(this.index)}${path63}`;
75665
+ const request = { method, headers };
75666
+ if (body !== void 0)
75667
+ request.body = JSON.stringify(body);
75668
+ if (this.connection.tls !== void 0)
75669
+ request.tls = this.connection.tls;
75670
+ let response;
75671
+ try {
75672
+ response = await this.http.request(url2, request);
75673
+ } catch (error51) {
75674
+ throw new MonitorHistoryError(`Could not reach ${this.connection.url}: ${describeTlsError(error51)}`);
75675
+ }
75676
+ const text2 = await response.text().catch(() => "");
75677
+ let json2 = {};
75678
+ try {
75679
+ json2 = text2.length > 0 ? JSON.parse(text2) : {};
75680
+ } catch {
75681
+ }
75682
+ return { status: response.status, json: json2 };
75683
+ }
75684
+ fail(doing, status2, json2) {
75685
+ const reason = json2["error"]?.reason ?? JSON.stringify(json2).slice(0, 300);
75686
+ const hint = status2 === 401 ? " - the sign-in was refused" : status2 === 403 ? " - this account may not write to that index; ask whoever runs the cluster" : "";
75687
+ throw new MonitorHistoryError(`OpenSearch refused ${doing} (${String(status2)}${hint}): ${reason}`, status2);
75688
+ }
75689
+ /** Creates the index with its mapping, once; "already exists" - another member won - is success. */
75690
+ async ensureIndex() {
75691
+ if (this.ensured)
75692
+ return;
75693
+ const { status: status2, json: json2 } = await this.send("PUT", "", MAPPING);
75694
+ const type = json2["error"]?.type;
75695
+ if (status2 >= 300 && type !== "resource_already_exists_exception")
75696
+ this.fail("creating the monitoring index", status2, json2);
75697
+ this.ensured = true;
75698
+ }
75699
+ /** True when this Fire Code may run `monitor` for interval `slot`; false when a team member already is. */
75700
+ async claim(monitor, slot) {
75701
+ await this.ensureIndex();
75702
+ const { status: status2, json: json2 } = await this.send("PUT", `/_create/${encodeURIComponent(docId("claim", monitor, slot))}`, {
75703
+ kind: "claim",
75704
+ monitor,
75705
+ slot,
75706
+ by: this.by,
75707
+ at: Math.floor(Date.now() / 1e3)
75708
+ });
75709
+ if (status2 === 409)
75710
+ return false;
75711
+ if (status2 >= 300)
75712
+ this.fail(`claiming ${monitor}`, status2, json2);
75713
+ return true;
75714
+ }
75715
+ async write(check2) {
75716
+ await this.ensureIndex();
75717
+ const record2 = { ...check2, by: this.by };
75718
+ const id = docId("check", record2.monitor, record2.by, record2.at, (0, import_node_crypto15.randomBytes)(4).toString("hex"));
75719
+ const { status: status2, json: json2 } = await this.send("PUT", `/_create/${encodeURIComponent(id)}`, {
75720
+ kind: "check",
75721
+ monitor: record2.monitor,
75722
+ by: record2.by,
75723
+ at: record2.at,
75724
+ level: record2.level,
75725
+ alertIds: (record2.found ?? []).map((a) => a.id),
75726
+ alertKeys: [...new Set((record2.found ?? []).map((a) => a.key))],
75727
+ payload: record2
75728
+ });
75729
+ if (status2 >= 300)
75730
+ this.fail(`recording a check of ${record2.monitor}`, status2, json2);
75731
+ }
75732
+ async search(body) {
75733
+ await this.ensureIndex();
75734
+ const { status: status2, json: json2 } = await this.send("POST", "/_search", body);
75735
+ if (status2 >= 300)
75736
+ this.fail("reading monitoring history", status2, json2);
75737
+ return json2;
75738
+ }
75739
+ /** The newest check of each monitor, by anyone. */
75740
+ async latest(monitors) {
75741
+ if (monitors.length === 0)
75742
+ return {};
75743
+ const json2 = await this.search({
75744
+ size: 0,
75745
+ query: { bool: { filter: [{ term: { kind: "check" } }, { terms: { monitor: monitors } }] } },
75746
+ aggs: { m: { terms: { field: "monitor", size: monitors.length }, aggs: { top: { top_hits: { size: 1, sort: [{ at: "desc" }], _source: ["payload"] } } } } }
75747
+ });
75748
+ const out = {};
75749
+ const buckets = json2["aggregations"]?.m?.buckets ?? [];
75750
+ for (const bucket of buckets) {
75751
+ const hit = bucket.top.hits.hits[0]?._source.payload;
75752
+ if (hit !== void 0)
75753
+ out[bucket.key] = hit;
75754
+ }
75755
+ return out;
75756
+ }
75757
+ /** A monitor's checks since `since` (epoch seconds), newest first, by anyone. */
75758
+ async history(monitor, since2, limit = 500) {
75759
+ const json2 = await this.search({
75760
+ size: Math.min(Math.max(limit, 1), 2e3),
75761
+ sort: [{ at: "desc" }],
75762
+ _source: ["payload"],
75763
+ query: { bool: { filter: [{ term: { kind: "check" } }, { term: { monitor } }, { range: { at: { gte: since2 } } }] } }
75764
+ });
75765
+ const hits = json2["hits"]?.hits ?? [];
75766
+ return hits.map((h) => h._source.payload);
75767
+ }
75768
+ /** Removes this person's checks and claims older than `before` - only theirs. How many went. */
75769
+ async prune(before, monitor) {
75770
+ await this.ensureIndex();
75771
+ const filter = [{ term: { by: this.by } }, { range: { at: { lt: before } } }];
75772
+ if (monitor !== void 0)
75773
+ filter.push({ term: { monitor } });
75774
+ const { status: status2, json: json2 } = await this.send("POST", "/_delete_by_query?conflicts=proceed", { query: { bool: { filter } } });
75775
+ if (status2 >= 300)
75776
+ this.fail("cleaning up monitoring history", status2, json2);
75777
+ return Number(json2["deleted"] ?? 0);
75778
+ }
75779
+ };
75780
+
75781
+ // ../../packages/core/dist/monitoring/explain.js
75782
+ var EXPLAIN_SYSTEM = [
75783
+ "You explain a monitoring alert to the person responsible for it, in Fire Code.",
75784
+ "You get the monitor, the author's advice for the rules that fired, the row the alert fired on, and each",
75785
+ "alert's history worked out from past checks. Write Markdown, at most about 200 words:",
75786
+ "1. **What is wrong** - one or two sentences, in plain words, naming the thing (job, host, feed).",
75787
+ "2. **New or known** - from the history: new today, ongoing since when, or recurring (how often, at what",
75788
+ " time). Say it exactly as the history shows; never guess a pattern it does not show.",
75789
+ "3. **What to do** - the author's advice first, as given. Then, only if it helps, up to three concrete next",
75790
+ " steps of your own, marked as suggestions. If there is no advice, say so and suggest checks to start with.",
75791
+ "No preamble, no repeating the input back, no code fences unless quoting a command from the advice."
75792
+ ].join("\n");
75793
+ function explainMessages(context) {
75794
+ return [
75795
+ { role: "system", content: EXPLAIN_SYSTEM },
75796
+ { role: "user", content: `The alert, as Fire Code recorded it:
75797
+
75798
+ ${JSON.stringify(context, null, 2).slice(0, 24e3)}` }
75799
+ ];
75800
+ }
75801
+
75579
75802
  // ../../packages/core/dist/monitoring/rowsCheck.js
75580
75803
  var NUMERIC_TEXT = /^\s*[-+(]?[\d,]+(\.\d+)?\)?\s*(%|ms|s|sec|min|mins|h|hrs|kb|mb|gb|tb)?\s*$/i;
75581
75804
  var ISO = /^\d{4}-\d{2}-\d{2}([T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
@@ -75704,8 +75927,17 @@ function describeRowsCheck(check2) {
75704
75927
  }
75705
75928
  var MONITOR_TOOL_TEMPLATE = `
75706
75929
  """<What it reads>, for monitoring: one record per <job | host | feed>."""
75930
+ import json
75707
75931
  from datetime import datetime, timezone
75708
75932
 
75933
+ import light_code
75934
+
75935
+ # Tools this one calls with light_code.call_tool - MCP tools, other Python tools, and Fire Code's
75936
+ # reading tools (autosys_status, jira_search, ...). Reviewed with the tool; in a monitor they run unasked.
75937
+ __tool_calls__ = ["server__query_jobs"]
75938
+ # Saved credentials it reads with light_code.credential("name"), if any - never a password in the code.
75939
+ __credentials__ = []
75940
+
75709
75941
 
75710
75942
  def run(pattern: str = "PAY_*") -> list[dict]:
75711
75943
  """<One line>.
@@ -75713,15 +75945,17 @@ def run(pattern: str = "PAY_*") -> list[dict]:
75713
75945
  Args:
75714
75946
  pattern: <what narrows it>.
75715
75947
  """
75716
- items = read_source(pattern) # let it RAISE when the source cannot be read - the tile turns purple
75948
+ # Either read the source directly, or call an existing tool (its answer is text - json.loads it
75949
+ # 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}))
75717
75951
  rows = []
75718
75952
  for item in items:
75719
75953
  rows.append({
75720
- "job": item.name, # names the row: the monitor's "key"
75721
- "status": item.status.upper(), # a short fixed word rules can match
75722
- "minutes": int(item.minutes), # numbers as numbers - no units, no commas
75723
- "lastStart": item.start.astimezone(timezone.utc).isoformat(), # ISO 8601, with a zone
75724
- "machine": item.machine or None, # None, not "", when there is no value
75954
+ "job": item["name"], # names the row: the monitor's "key"
75955
+ "status": str(item["status"]).upper(), # a short fixed word rules can match
75956
+ "minutes": int(item["minutes"]), # numbers as numbers - no units, no commas
75957
+ "lastStart": datetime.fromisoformat(item["start"]).astimezone(timezone.utc).isoformat(), # ISO 8601, with a zone
75958
+ "machine": item.get("machine") or None, # None, not "", when there is no value
75725
75959
  })
75726
75960
  return rows # [] when there is nothing to report - never a message
75727
75961
  `.trim();
@@ -75744,10 +75978,11 @@ var createSchema2 = external_exports.object({
75744
75978
  name: external_exports.string().describe('kebab-case, e.g. "overnight-batch" - the monitor and its skill file.'),
75745
75979
  title: external_exports.string().describe('What the tile says, a few words: "Overnight batch".'),
75746
75980
  summary: external_exports.string().describe("One sentence shown on hover: what it watches and what an alert means."),
75747
- 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.'),
75748
- every: external_exports.union([external_exports.string(), external_exports.number()]).describe('How often to check: "5m", "15m", "1h", "1d" (one minute at least).'),
75749
- activeHours: external_exports.string().optional().describe('Only check between these times, e.g. "07:00-19:00" (a window past midnight is allowed).'),
75750
- days: external_exports.array(external_exports.string()).optional().describe('Only on these days, e.g. ["mon","tue","wed","thu","fri"].'),
75981
+ audience: external_exports.enum(["me", "team"]).optional().describe(`"me": a Personal monitor, only on this computer - always possible. "team": shown under Team alerts and shared where the team shares skills; needs the team's OpenSearch history (Settings \u2192 Monitoring). Left out: team when that history is set up, otherwise personal. Use "me" when the user says it is just for them.`),
75982
+ 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
+ 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
+ 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.'),
75985
+ days: external_exports.array(external_exports.string()).optional().describe('Only on these days, e.g. ["mon","tue","wed","thu","fri"]; for both "every" and "at".'),
75751
75986
  source: sourceSchema,
75752
75987
  rows: external_exports.string().optional().describe('Where the list of rows is in the answer, as a dotted path ("data.jobs"), when it is not found by itself.'),
75753
75988
  columns: external_exports.array(external_exports.object({ key: external_exports.string(), label: external_exports.string().optional(), format: external_exports.enum(["text", "number", "percent", "datetime", "duration", "bytes"]).optional(), width: external_exports.number().optional() })).optional().describe("The grid columns, in order. Omit to show every field. A dotted key reads inside a nested object."),
@@ -75757,19 +75992,21 @@ var createSchema2 = external_exports.object({
75757
75992
  when: condition.describe('{"column", "op", "value"} with op ==, !=, >, >=, <, <=, contains, notContains, startsWith, endsWith, matches (regex), in, notIn (value a list), empty, notEmpty, olderThan / newerThan (value "30m", "2h", for a timestamp column); or {"all": [...]}, {"any": [...]}, {"not": {...}}.'),
75758
75993
  highlight: external_exports.enum(["row", "cell"]).optional().describe("Colour the whole row, or just the cell (the default when the rule is about one column)."),
75759
75994
  column: external_exports.string().optional().describe("Which cell to colour, when not the rule's own column."),
75760
- message: external_exports.string().optional().describe('The alert text, filled from the row: "{name} failed at {lastEnd}".')
75995
+ message: external_exports.string().optional().describe('The alert text, filled from the row: "{name} failed at {lastEnd}".'),
75996
+ advice: external_exports.string().optional().describe("The author's own words for this alert: what it means and what to do (who to call, what to rerun, what to check). Shown and used when the alert is explained.")
75761
75997
  })).describe("Alert rules, tried on every row. red = failure / needs attention, amber = warning, blue = information, purple = no data or cannot tell."),
75762
75998
  whenEmpty: level.optional().describe("The level when there are no rows. Default green."),
75763
75999
  whenClear: level.optional().describe("The level when there are rows and no rule fires. Default green."),
75764
76000
  notify: level.optional().describe("The least severe level that sends a Windows notification for this monitor. Default amber. How each level notifies is the user's setting."),
75765
76001
  details: sourceSchema.optional().describe(`The breakdown shown when the user double-clicks a row: a source whose args or SQL take {column} values from that row, e.g. {"tool": "py__job_runs", "args": {"job": "{name}"}}. Omit to show the row's own fields.`),
75766
76002
  timeoutSeconds: external_exports.number().int().min(5).max(900).optional().describe("How long one check may take. Default 120."),
76003
+ runbook: external_exports.string().optional().describe("The author's general advice for this monitor: who owns it, where to look first, known false alarms. Used with each rule's advice when an alert is explained."),
75767
76004
  notes: external_exports.string().optional().describe("Markdown for the skill body: what this watches, why, and what to do about each alert."),
75768
76005
  tryOnly: external_exports.boolean().optional().describe("Run the source once and show what Fire Code makes of it - columns, rows, alerts - without saving anything. Use it while writing or fixing the tool.")
75769
76006
  });
75770
76007
  function monitorBlock(params3) {
75771
- const spec = { title: params3.title, summary: params3.summary, every: params3.every };
75772
- for (const key2 of ["activeHours", "days", "source", "rows", "columns", "key", "rules", "whenEmpty", "whenClear", "notify", "details", "timeoutSeconds"]) {
76008
+ const spec = { title: params3.title, summary: params3.summary, ...params3.every !== void 0 ? { every: params3.every } : {} };
76009
+ for (const key2 of ["at", "activeHours", "days", "source", "rows", "columns", "key", "rules", "whenEmpty", "whenClear", "notify", "details", "timeoutSeconds", "runbook"]) {
75773
76010
  if (params3[key2] !== void 0)
75774
76011
  spec[key2] = params3[key2];
75775
76012
  }
@@ -75782,7 +76019,7 @@ function monitorSkillBody(params3, block2) {
75782
76019
  params3.summary,
75783
76020
  "",
75784
76021
  ...params3.notes !== void 0 && params3.notes.trim().length > 0 ? [params3.notes.trim(), ""] : [],
75785
- `This skill is a **Fire Code monitor**: Fire Code checks it every ${String(params3.every)} and shows it on the Monitoring dashboard. The block below is its definition. Change it with monitor_create under the same name, so the change is approved again; an edit by hand is reviewed on the dashboard before it runs.`,
76022
+ `This skill is a **Fire Code monitor**: Fire Code checks it ${params3.every !== void 0 ? `every ${String(params3.every)}` : ""}${params3.every !== void 0 && params3.at !== void 0 ? " and " : ""}${params3.at !== void 0 ? `at ${[params3.at].flat().join(", ")}` : ""} and shows it on the Monitoring dashboard. The block below is its definition. Change it with monitor_create under the same name, so the change is approved again; an edit by hand is reviewed on the dashboard before it runs.`,
75786
76023
  "",
75787
76024
  "```monitor",
75788
76025
  block2,
@@ -75803,14 +76040,34 @@ function describeEvaluation(e) {
75803
76040
  }
75804
76041
  var message2 = (error51) => error51 instanceof Error ? error51.message : String(error51);
75805
76042
  function createMonitorCreateTool(options) {
75806
- const skillParams = (params3, block2) => ({
76043
+ const skillParams = (params3, block2, audience) => ({
75807
76044
  name: params3.name,
75808
76045
  description: `Monitor: ${params3.summary.replace(/\s+/g, " ").trim()}`,
75809
76046
  body: monitorSkillBody(params3, block2),
75810
- ...params3.audience !== void 0 ? { audience: params3.audience } : {}
76047
+ audience
75811
76048
  });
75812
- const tryIt = async (block2) => {
76049
+ const audienceFor = async (params3) => {
76050
+ if (params3.audience !== void 0)
76051
+ return { audience: params3.audience };
76052
+ try {
76053
+ const listed = await options.channel.request("list");
76054
+ if (listed.teamReady === true)
76055
+ return { audience: "team" };
76056
+ } catch {
76057
+ }
76058
+ return {
76059
+ audience: "me",
76060
+ note: "Personal (only on this computer): team monitors need the team's OpenSearch history, which is not set up in Fire Code \u2192 Settings \u2192 Monitoring."
76061
+ };
76062
+ };
76063
+ const tryIt = async (block2, team = false) => {
75813
76064
  try {
76065
+ if (team) {
76066
+ const listed = await options.channel.request("list");
76067
+ if (listed.teamReady !== true) {
76068
+ return { ok: false, error: `A team monitor keeps its history in the team's OpenSearch index, and that is not set up: ${listed.teamProblem ?? "Fire Code \u2192 Settings \u2192 Monitoring \u2192 Team history"}. Make it personal (audience "me"), or ask the user to set it up.` };
76069
+ }
76070
+ }
75814
76071
  const checked = await options.channel.request("evaluate", { block: block2 });
75815
76072
  if (checked.sourceKind === "tool") {
75816
76073
  return { ok: true, native: false, note: "After it is saved, its tool is run once here to show what the first check finds." };
@@ -75826,7 +76083,7 @@ ${describeEvaluation(tried)}` };
75826
76083
  return {
75827
76084
  name: "monitor_create",
75828
76085
  group: "edit",
75829
- 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. The user approves the skill file; the result shows what the first check found. " + MONITOR_TOOL_FORMAT,
76086
+ description: `Create or replace a Fire Code monitor: a check that runs on a schedule and shows on the Monitoring dashboard as a coloured tile, with a data grid whose cells or rows are coloured by alert rules, and Windows notifications at the levels the user chose. Before creating one: find an existing tool that returns the data (search_docs, or the tools you have) and reuse it; if none does, write a Python tool with create_python_tool from the template in monitor_check_tool, and run monitor_check_tool until it says PASS - then use the columns and key it gives. A SQLite database or CSV/Excel file needs no tool. Rules are judged by Fire Code itself on every check - no model is involved - so make them exact. ASK THE AUTHOR (ask_user_form, one field per rule plus a general one) what each alert means and what to do about it, unless they already said, and put it in each rule's "advice" and in "runbook": that is what an agent tells whoever meets the alert later. A team monitor needs the team's OpenSearch history set in Fire Code \u2192 Settings \u2192 Monitoring; without it the monitor is created personal (only on this computer), which always works - say so to the user.The user approves the skill file; the result shows what the first check found. ` + MONITOR_TOOL_FORMAT,
75830
76087
  parametersSchema: createSchema2,
75831
76088
  async preview(params3, context) {
75832
76089
  const block2 = monitorBlock(params3);
@@ -75838,23 +76095,23 @@ ${describeEvaluation(tried)}` };
75838
76095
  ${"tool" in params3.source ? `Run ${params3.source.tool}(${JSON.stringify(params3.source.args ?? {})})` : `Read ${JSON.stringify(params3.source)}`}`
75839
76096
  };
75840
76097
  }
75841
- const tried = await tryIt(block2);
76098
+ const { audience, note: forWhom } = await audienceFor(params3);
76099
+ const tried = await tryIt(block2, audience === "team");
75842
76100
  if (!tried.ok) {
75843
76101
  return { kind: "text", text: `This monitor cannot be created as written - nothing will be saved:
75844
76102
 
75845
76103
  ${tried.error}` };
75846
76104
  }
75847
- const written = options.writeSkill.preview !== void 0 ? await options.writeSkill.preview(skillParams(params3, block2), context) : void 0;
76105
+ const written = options.writeSkill.preview !== void 0 ? await options.writeSkill.preview(skillParams(params3, block2, audience), context) : void 0;
75848
76106
  if (written?.kind === "diff") {
75849
- return { ...written, note: [written.note, tried.note, "Approving this also lets it run on this computer."].filter((n) => n !== void 0 && n.length > 0).join("\n\n") };
76107
+ return { ...written, note: [forWhom, written.note, tried.note, "Approving this also lets it run on this computer."].filter((n) => n !== void 0 && n.length > 0).join("\n\n") };
75850
76108
  }
75851
- return { kind: "text", text: `${monitorSkillBody(params3, block2)}
75852
-
75853
- ${tried.note}` };
76109
+ return { kind: "text", text: [forWhom, monitorSkillBody(params3, block2), tried.note].filter((n) => n !== void 0).join("\n\n") };
75854
76110
  },
75855
76111
  async execute(params3, context) {
75856
76112
  const block2 = monitorBlock(params3);
75857
- const tried = await tryIt(block2);
76113
+ const { audience, note: forWhom } = params3.tryOnly === true ? { audience: "me", note: void 0 } : await audienceFor(params3);
76114
+ const tried = await tryIt(block2, audience === "team");
75858
76115
  if (!tried.ok)
75859
76116
  return { content: `Not created: ${tried.error}`, isError: true };
75860
76117
  if (params3.tryOnly === true) {
@@ -75879,10 +76136,10 @@ ${describeRowsCheck(checkMonitorRows(result.content))}` };
75879
76136
  ${MONITOR_TOOL_FORMAT}`, isError: true };
75880
76137
  }
75881
76138
  }
75882
- const written = await options.writeSkill.execute(skillParams(params3, block2), context);
76139
+ const written = await options.writeSkill.execute(skillParams(params3, block2, audience), context);
75883
76140
  if (written.isError === true)
75884
76141
  return written;
75885
- const lines2 = [written.content];
76142
+ const lines2 = [written.content, ...forWhom !== void 0 ? [forWhom] : []];
75886
76143
  try {
75887
76144
  await options.channel.request("approve", { name: params3.name, block: block2 });
75888
76145
  } catch (error51) {
@@ -75991,6 +76248,44 @@ function createMonitorStatusTool(options) {
75991
76248
  }
75992
76249
  };
75993
76250
  }
76251
+ var historySchema = external_exports.object({
76252
+ name: external_exports.string().describe("The monitor."),
76253
+ key: external_exports.string().optional().describe("One row: its key value (a job name, a host) - its alerts' history only."),
76254
+ alert: external_exports.string().optional().describe("One alert, by the id monitor_status shows."),
76255
+ days: external_exports.number().int().min(1).max(366).optional().describe("How far back. Default 14.")
76256
+ });
76257
+ function createMonitorHistoryTool(options) {
76258
+ return {
76259
+ name: "monitor_history",
76260
+ group: "read",
76261
+ description: "A monitor's past checks and, for each alert, whether it is new, ongoing (since when, how many checks in a row), recurring (on how many days, usually at what time) or intermittent - worked out by Fire Code from the stored checks (the team's, for a team monitor). Use it before saying whether an alert is new or known, and when investigating one.",
76262
+ parametersSchema: historySchema,
76263
+ async execute(params3) {
76264
+ try {
76265
+ const got = await options.channel.request("history", {
76266
+ name: params3.name,
76267
+ days: params3.days ?? 14,
76268
+ ...params3.key !== void 0 ? { key: params3.key } : {},
76269
+ ...params3.alert !== void 0 ? { alert: params3.alert } : {}
76270
+ });
76271
+ const changes = got.checks.filter((c2, i, all) => i === all.length - 1 || all[i + 1]?.level !== c2.level);
76272
+ return {
76273
+ content: [
76274
+ `${params3.name}: ${String(got.checks.length)} check(s) in the last ${String(got.days)} day(s).`,
76275
+ "",
76276
+ "Alerts:",
76277
+ ...got.patterns.length === 0 ? ["- none in this period"] : got.patterns.map((p) => `- [${p.id}] ${p.level} ${p.key}: ${p.verdict.toUpperCase()} - ${p.summary}` + (p.days.length > 0 ? ` (by day: ${p.days.map((d) => `${d.date} ${String(d.count)}`).join(", ")})` : "")),
76278
+ "",
76279
+ "Level changes, newest first:",
76280
+ ...changes.slice(0, 30).map((c2) => `- ${when3(c2.at)} ${c2.level}${c2.by ? ` (checked by ${c2.by})` : ""} - ${c2.headline}`)
76281
+ ].join("\n")
76282
+ };
76283
+ } catch (error51) {
76284
+ return { content: message2(error51), isError: true };
76285
+ }
76286
+ }
76287
+ };
76288
+ }
75994
76289
  var showSchema = external_exports.object({
75995
76290
  action: external_exports.enum(["run", "open", "dashboard"]).describe("run: check now. open: the monitor's grid window. dashboard: the Monitoring dashboard."),
75996
76291
  name: external_exports.string().optional().describe("The monitor, for run and open.")
@@ -76200,7 +76495,7 @@ async function copySetupFiles(mainCheckout, folder, names) {
76200
76495
  }
76201
76496
 
76202
76497
  // ../../packages/core/dist/teamrepo/sync.js
76203
- var import_node_crypto15 = require("node:crypto");
76498
+ var import_node_crypto16 = require("node:crypto");
76204
76499
  var import_promises26 = __toESM(require("node:fs/promises"), 1);
76205
76500
  var import_node_path46 = __toESM(require("node:path"), 1);
76206
76501
  var TOMBSTONE_PREFIX = "LIGHT-CODE-DELETED:";
@@ -76223,13 +76518,13 @@ function contentHash(bytes) {
76223
76518
  text2 = void 0;
76224
76519
  }
76225
76520
  }
76226
- const digest = (0, import_node_crypto15.createHash)("sha256");
76521
+ const digest = (0, import_node_crypto16.createHash)("sha256");
76227
76522
  if (text2 === void 0)
76228
76523
  return digest.update(bytes).digest("hex");
76229
76524
  return digest.update(text2.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").replace(/\s+$/, "")).digest("hex");
76230
76525
  }
76231
76526
  var hash2 = contentHash;
76232
- var rawHash = (bytes) => (0, import_node_crypto15.createHash)("sha256").update(bytes).digest("hex");
76527
+ var rawHash = (bytes) => (0, import_node_crypto16.createHash)("sha256").update(bytes).digest("hex");
76233
76528
  function repoPathFor(folder, kind, relative) {
76234
76529
  const base = folder.replace(/\\/g, "/").replace(/^\/+|\/+$/g, "");
76235
76530
  return [base, kind, relative.replace(/\\/g, "/")].filter((part) => part.length > 0).join("/");
@@ -76712,11 +77007,63 @@ function tracingHttpClient(inner, entries, knownSecrets = []) {
76712
77007
  ...inner.openWebSocket !== void 0 ? { openWebSocket: inner.openWebSocket.bind(inner) } : {}
76713
77008
  };
76714
77009
  }
77010
+ function explainStep(entry) {
77011
+ const error51 = (entry.error ?? "").toLowerCase();
77012
+ const status2 = entry.status;
77013
+ const body = (entry.responseBody ?? "").trimStart().toLowerCase();
77014
+ const header2 = (name) => Object.entries(entry.responseHeaders ?? {}).find(([k]) => k.toLowerCase() === name)?.[1];
77015
+ if (entry.error !== void 0) {
77016
+ if (/enotfound|getaddrinfo|eai_again/.test(error51))
77017
+ return "The server name does not resolve here: check the site address, or that this machine is on the network or VPN that can see it.";
77018
+ if (/econnrefused/.test(error51))
77019
+ return "Nothing is listening at that address and port: check the port in the site address, or whether the service is up.";
77020
+ if (/etimedout|timeout|timed out|aborted/.test(error51))
77021
+ return "No answer: a firewall or proxy may be dropping the connection. Check the address, and whether this network needs a proxy (Settings \u2192 Network).";
77022
+ if (/certificate|self.signed|unable to verify|cert_|ssl|tls/.test(error51))
77023
+ return "TLS: the server's certificate is not trusted here. Add your company's CA in Settings \u2192 Network (or the connection's own CA file).";
77024
+ if (/econnreset|socket hang up/.test(error51))
77025
+ return "The connection was cut: often a proxy or TLS inspection, or plain http sent to an https port (or the other way round).";
77026
+ return void 0;
77027
+ }
77028
+ if (status2 === void 0)
77029
+ return void 0;
77030
+ if (status2 >= 300 && status2 < 400) {
77031
+ const to = header2("location");
77032
+ return `Redirected${to !== void 0 ? ` to ${to}` : ""}: the address may need https, a context path (/jira, /confluence, /AEWS), or it leads to a login page - use the server's own address.`;
77033
+ }
77034
+ if (status2 >= 200 && status2 < 300 && (body.startsWith("<!doctype html") || body.startsWith("<html"))) {
77035
+ return "A web page came back where data was expected: usually a single sign-on login page, which means the token is not accepted at this address. Use the server's REST address, not a portal link.";
77036
+ }
77037
+ if (status2 === 400)
77038
+ return "The server did not understand the request: often a wrong context path or API version in the site address, or a field it does not accept.";
77039
+ if (status2 === 401)
77040
+ return "Not signed in: the token or password was refused, or not sent the way this server expects (Bearer token vs user name and password; an expired token).";
77041
+ if (status2 === 403)
77042
+ return "Signed in, but this account may not do this: check its permissions on the server, the token's scopes, or an IP allow-list on a gateway.";
77043
+ if (status2 === 404)
77044
+ return "Nothing at this address: the site address (its context path, such as /jira, /confluence or /AEWS) or the API path differs on this server. Compare with the address that works in a browser or Postman.";
77045
+ if (status2 === 405)
77046
+ return "This address does not accept this kind of request: it probably points at a different service than the one named.";
77047
+ if (status2 === 407)
77048
+ return "The proxy wants a sign-in: set the proxy's user name and password in Settings \u2192 Network.";
77049
+ if (status2 === 429)
77050
+ return "Too many requests: the server or gateway is limiting calls. Wait a little and try again.";
77051
+ if (status2 >= 500)
77052
+ return "The server (or a gateway in front of it) failed: the body may say why. A 502/503/504 usually means the gateway could not reach the service behind it.";
77053
+ return void 0;
77054
+ }
76715
77055
  function renderTrace(entries) {
76716
77056
  if (entries.length === 0)
76717
77057
  return "No request was sent - the test stopped before reaching the network (see the message above).";
76718
- return entries.map((entry, index) => {
77058
+ const failed2 = entries.findIndex((e) => e.error !== void 0 || e.status !== void 0 && (e.status >= 300 || explainStep(e) !== void 0));
77059
+ const first = failed2 === -1 ? void 0 : entries[failed2];
77060
+ const reading = first === void 0 ? void 0 : explainStep(first);
77061
+ const summary = first !== void 0 && reading !== void 0 ? [`Likely cause (step #${String(failed2 + 1)}): ${reading}`] : [];
77062
+ return [...summary, ...entries.map((entry, index) => {
76719
77063
  const lines2 = [`#${String(index + 1)} ${entry.method} ${entry.url}`];
77064
+ const meaning = explainStep(entry);
77065
+ if (meaning !== void 0)
77066
+ lines2.push(`What this usually means: ${meaning}`);
76720
77067
  const headers = Object.entries(entry.requestHeaders);
76721
77068
  if (headers.length > 0)
76722
77069
  lines2.push("Request headers:", ...headers.map(([name, value]) => ` ${name}: ${value}`));
@@ -76732,7 +77079,7 @@ function renderTrace(entries) {
76732
77079
  lines2.push("Response body:", entry.responseBody !== void 0 && entry.responseBody.length > 0 ? indent(entry.responseBody) : " (empty)");
76733
77080
  }
76734
77081
  return lines2.join("\n");
76735
- }).join("\n\n");
77082
+ })].join("\n\n");
76736
77083
  }
76737
77084
  function indent(text2) {
76738
77085
  return text2.split("\n").map((line) => ` ${line}`).join("\n");
@@ -80710,7 +81057,7 @@ function wireChatBridge(services) {
80710
81057
  let cachedSecretValues = [];
80711
81058
  const droppedFilesRoot2 = droppedFilesRoot();
80712
81059
  const mailAttachmentsRoot2 = mailAttachmentsRoot();
80713
- const droppedFilesDir = import_node_path52.default.join(droppedFilesRoot2, (0, import_node_crypto16.randomUUID)().slice(0, 8));
81060
+ const droppedFilesDir = import_node_path52.default.join(droppedFilesRoot2, (0, import_node_crypto17.randomUUID)().slice(0, 8));
80714
81061
  const truncationStore = new RecordingTruncationStore(new DiskTruncationStore(import_node_path52.default.join(storageDir, "tool-results"), () => cachedSecretValues));
80715
81062
  const taskStore = new JsonTaskStore(storageDir, truncationStore, logger);
80716
81063
  const manifestsRoot = services.codebaseDir ?? storageDir;
@@ -80775,15 +81122,29 @@ function wireChatBridge(services) {
80775
81122
  * anybody present to answer a prompt. `callPolicy.ts` holds the rule and the reasoning.
80776
81123
  */
80777
81124
  callTool: async (name, args, caller) => {
80778
- if (!pythonNestedCallsAllowed) {
80779
- throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
80780
- }
80781
81125
  const registry2 = currentToolRegistry();
80782
81126
  const tool = registry2.get(name) ?? registry2.get(`py__${name}`);
80783
81127
  if (tool === void 0) {
80784
81128
  throw new Error(`There is no tool called "${name}". Settings \u2192 Tools lists everything callable; an MCP tool is named with its server, like \`filesystem__read_file\`.`);
80785
81129
  }
80786
- if (!mayPythonToolCall(tool.name, tool.group))
81130
+ const declared = await declaredCallsOf(caller);
81131
+ const isDeclared = declared.some((d) => d === tool.name || `py__${d}` === tool.name);
81132
+ if (monitorRunContext !== void 0) {
81133
+ if (!isDeclared) {
81134
+ throw new Error(`${caller} calls "${tool.name}" without declaring it. Add it to the tool's __tool_calls__ list (e.g. __tool_calls__ = [${[...declared, tool.name].map((d) => JSON.stringify(d)).join(", ")}]); the tool is then approved again.`);
81135
+ }
81136
+ const refusal = monitorToolRefusal(tool, tool.name);
81137
+ if (refusal !== void 0)
81138
+ throw new Error(refusal);
81139
+ const result2 = await tool.execute(args, monitorRunContext);
81140
+ if (result2.isError === true)
81141
+ throw new Error(String(result2.content));
81142
+ return result2.content;
81143
+ }
81144
+ if (!pythonNestedCallsAllowed) {
81145
+ throw new Error("This run cannot call other tools from a Python tool: it is unattended, so nobody is here to approve one.");
81146
+ }
81147
+ if (!mayPythonToolCall(tool.name, tool.group, isDeclared))
80787
81148
  throw new Error(PYTHON_CALL_DENIED);
80788
81149
  const context = pythonNestedContext;
80789
81150
  if (context === void 0) {
@@ -82518,6 +82879,7 @@ ${preview.text}` } : {}
82518
82879
  combined.register(createMonitorStatusTool(monitorOptions));
82519
82880
  combined.register(createMonitorShowTool(monitorOptions));
82520
82881
  combined.register(createMonitorCheckToolTool(monitorOptions));
82882
+ combined.register(createMonitorHistoryTool(monitorOptions));
82521
82883
  combined.register(createMonitorControlTool(monitorOptions));
82522
82884
  }
82523
82885
  combined.register(createDeleteSkillTool(context));
@@ -82892,7 +83254,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
82892
83254
  if (id === void 0) {
82893
83255
  if (records.length >= (spec.max ?? 500))
82894
83256
  return postAddonPage(message5.package, { error: `No more than ${String(spec.max ?? 500)} ${spec.noun}s.` });
82895
- id = (0, import_node_crypto16.randomBytes)(6).toString("hex");
83257
+ id = (0, import_node_crypto17.randomBytes)(6).toString("hex");
82896
83258
  records.push({ id, values: cleaned.values });
82897
83259
  } else {
82898
83260
  const at = records.findIndex((record2) => record2.id === id);
@@ -83129,7 +83491,7 @@ ${error51.stack.split("\n").slice(1, 6).join("\n")}`;
83129
83491
  if (workspaceRoot === void 0 || conversation.isEmpty())
83130
83492
  return;
83131
83493
  if (activeTaskId === void 0) {
83132
- await setActiveTaskId((0, import_node_crypto16.randomUUID)());
83494
+ await setActiveTaskId((0, import_node_crypto17.randomUUID)());
83133
83495
  activeTaskCreatedAt = Date.now();
83134
83496
  truncationStore.startTask();
83135
83497
  }
@@ -83915,7 +84277,7 @@ ${direction}` : attachMentions(text2, mentions);
83915
84277
  try {
83916
84278
  const { config: config2 } = await configManager.load();
83917
84279
  const profiles = config2.profiles ?? [];
83918
- const id = input.id ?? (0, import_node_crypto16.randomUUID)();
84280
+ const id = input.id ?? (0, import_node_crypto17.randomUUID)();
83919
84281
  const existing = profiles.find((p) => p.id === id);
83920
84282
  const auth2 = await buildAuthFromInput(input, id);
83921
84283
  const saved = {
@@ -83953,7 +84315,7 @@ ${direction}` : attachMentions(text2, mentions);
83953
84315
  post({ type: "error", message: `Profile "${id}" no longer exists.` });
83954
84316
  return;
83955
84317
  }
83956
- const newId = (0, import_node_crypto16.randomUUID)();
84318
+ const newId = (0, import_node_crypto17.randomUUID)();
83957
84319
  async function copySecret(fromRef, toRef) {
83958
84320
  if (fromRef === void 0)
83959
84321
  return false;
@@ -85448,7 +85810,7 @@ ${redact(shown2, cachedSecretValues)}` }
85448
85810
  if (auth2.clientId === void 0 || auth2.clientSecretRef === void 0) {
85449
85811
  throw new AtlassianError("AutoSys uses the API gateway but the client id or secret is missing. Settings \u2192 DevOps \u2192 AutoSys \u2192 API gateway: enter both and save.");
85450
85812
  }
85451
- const key2 = JSON.stringify({ auth: auth2, baseUrl: config2.autosys?.baseUrl, tls: tls2 === void 0 ? 0 : (0, import_node_crypto16.createHash)("sha256").update(JSON.stringify(tls2)).digest("hex") });
85813
+ const key2 = JSON.stringify({ auth: auth2, baseUrl: config2.autosys?.baseUrl, tls: tls2 === void 0 ? 0 : (0, import_node_crypto17.createHash)("sha256").update(JSON.stringify(tls2)).digest("hex") });
85452
85814
  const testing = http !== httpClient;
85453
85815
  if (!testing && autosysGateway?.key === key2)
85454
85816
  return autosysGateway.strategy;
@@ -85580,6 +85942,19 @@ ${redact(shown2, cachedSecretValues)}` }
85580
85942
  return new AutosysClient(http, await atlassianConnection("autosys", http), paths);
85581
85943
  }
85582
85944
  let monitorSettingsLoaded = false;
85945
+ let monitorRunContext;
85946
+ let monitorRuns = 0;
85947
+ async function declaredCallsOf(caller) {
85948
+ const found2 = python.findTool(caller);
85949
+ if (found2 === void 0)
85950
+ return [];
85951
+ try {
85952
+ const source = await import_promises29.default.readFile(found2.filePath, "utf8");
85953
+ return hashSource(source) === found2.hash ? declaredToolCalls(source) : [];
85954
+ } catch {
85955
+ return [];
85956
+ }
85957
+ }
85583
85958
  async function executeForMonitor(name, args, given, signal) {
85584
85959
  const { config: config2 } = await configManager.load();
85585
85960
  if (!monitorSettingsLoaded) {
@@ -85611,12 +85986,85 @@ ${redact(shown2, cachedSecretValues)}` }
85611
85986
  return resolved !== void 0 ? { ripgrepPath: resolved } : {};
85612
85987
  })()
85613
85988
  };
85614
- return tool.execute(parsed.data, context);
85989
+ monitorRuns += 1;
85990
+ monitorRunContext = context;
85991
+ try {
85992
+ return await tool.execute(parsed.data, context);
85993
+ } finally {
85994
+ monitorRuns -= 1;
85995
+ if (monitorRuns === 0)
85996
+ monitorRunContext = void 0;
85997
+ }
85615
85998
  }
85616
- services.monitorExecutor?.serve(async (fetch2) => {
85999
+ const monitorStores = /* @__PURE__ */ new Map();
86000
+ async function monitorStore(storeId, index) {
86001
+ const key2 = `${storeId}\0${index}`;
86002
+ const cached2 = monitorStores.get(key2);
86003
+ if (cached2 !== void 0)
86004
+ return cached2;
86005
+ const { config: config2 } = await configManager.load();
86006
+ const store = config2.vectorStores?.[storeId];
86007
+ if (store === void 0)
86008
+ throw new Error(`There is no search connection "${storeId}" in the settings monitoring runs with.`);
86009
+ if (store.kind !== "opensearch")
86010
+ throw new Error(`"${store.label || storeId}" is not an OpenSearch connection; team monitoring keeps its history in OpenSearch.`);
86011
+ if (!monitorSettingsLoaded) {
86012
+ monitorSettingsLoaded = true;
86013
+ await loadSettings();
86014
+ }
86015
+ const by = cachedAttribution.author ?? import_node_os6.default.userInfo().username;
86016
+ const made = new MonitorHistoryStore(httpClient, await vectorStoreConnectionFor(store, storeId), index, by);
86017
+ monitorStores.set(key2, made);
86018
+ return made;
86019
+ }
86020
+ async function answerMonitorStore(op, store, args) {
86021
+ const monitor = typeof args["monitor"] === "string" ? args["monitor"] : "";
86022
+ switch (op) {
86023
+ case "claim":
86024
+ return store.claim(monitor, Number(args["slot"] ?? 0));
86025
+ case "write":
86026
+ await store.write(args["record"]);
86027
+ return { by: store.by };
86028
+ case "latest":
86029
+ return store.latest(Array.isArray(args["monitors"]) ? args["monitors"] : []);
86030
+ case "history":
86031
+ return store.history(monitor, Number(args["since"] ?? 0), Number(args["limit"] ?? 500));
86032
+ case "prune":
86033
+ return { deleted: await store.prune(Number(args["before"] ?? 0), monitor.length > 0 ? monitor : void 0) };
86034
+ case "test":
86035
+ await store.ensureIndex();
86036
+ return { index: store.index, by: store.by };
86037
+ default:
86038
+ throw new Error(`"${op}" is not a monitoring history operation.`);
86039
+ }
86040
+ }
86041
+ async function explainForMonitor(context) {
86042
+ const config2 = await loadSettings();
86043
+ const profile = resolveActiveProfile(config2);
86044
+ const provider = createChatProvider(profile, httpClient, authStrategyFor(config2, profile), logger, services.languageModels);
86045
+ let text2 = "";
86046
+ for await (const chunk of provider.streamChat(explainMessages(JSON.parse(redact(JSON.stringify(context), cachedSecretValues))))) {
86047
+ if (chunk.type === "text")
86048
+ text2 += chunk.text;
86049
+ if (chunk.type === "error")
86050
+ throw new Error(chunk.error);
86051
+ }
86052
+ if (text2.trim().length === 0)
86053
+ throw new Error("The model replied with nothing.");
86054
+ return text2.trim();
86055
+ }
86056
+ services.monitorExecutor?.serve(async (request) => {
85617
86057
  try {
85618
- const result = await executeForMonitor(fetch2.tool, fetch2.args, void 0, AbortSignal.timeout(Math.max(5e3, fetch2.timeoutMs)));
85619
- return result.isError === true ? { ok: false, error: result.content.slice(0, 4e3) } : { ok: true, text: result.content };
86058
+ switch (request.kind) {
86059
+ case "fetch": {
86060
+ const result = await executeForMonitor(request.tool, request.args, void 0, AbortSignal.timeout(Math.max(5e3, request.timeoutMs)));
86061
+ return result.isError === true ? { ok: false, error: result.content.slice(0, 4e3) } : { ok: true, data: result.content };
86062
+ }
86063
+ case "store":
86064
+ return { ok: true, data: await answerMonitorStore(request.op, await monitorStore(request.storeId, request.index), request.args) };
86065
+ case "explain":
86066
+ return { ok: true, data: await explainForMonitor(request.context) };
86067
+ }
85620
86068
  } catch (error51) {
85621
86069
  return { ok: false, error: error51 instanceof Error ? error51.message : String(error51) };
85622
86070
  }
@@ -85978,7 +86426,7 @@ ${redact(shown2, cachedSecretValues)}` }
85978
86426
  return { reason: "Off." };
85979
86427
  if (!isSafeSegment(settings.project) || !isSafeSegment(settings.repo))
85980
86428
  return { reason: "Enter the project key and repository slug." };
85981
- const digest = (0, import_node_crypto16.createHash)("sha256").update(JSON.stringify([bitbucket.baseUrl, settings.project, settings.repo, settings.branch, settings.folder]).toLowerCase()).digest("hex").slice(0, 12);
86429
+ const digest = (0, import_node_crypto17.createHash)("sha256").update(JSON.stringify([bitbucket.baseUrl, settings.project, settings.repo, settings.branch, settings.folder]).toLowerCase()).digest("hex").slice(0, 12);
85982
86430
  const root = import_node_path52.default.join(mirrorRoot, "teamrepo", `${settings.project}-${settings.repo}-${digest}`.toLowerCase());
85983
86431
  return {
85984
86432
  dirs: { skills: import_node_path52.default.join(root, "skills"), tools: import_node_path52.default.join(root, "tools") },
@@ -87000,7 +87448,7 @@ ${last}` : ""}`);
87000
87448
  });
87001
87449
  const wanted = options.kind;
87002
87450
  const entries = wanted === void 0 ? all : all.filter((entry) => entry.kind === wanted);
87003
- const fingerprint = (0, import_node_crypto16.createHash)("sha256").update(`${wanted ?? "all"}:${embedder.model}:${String(embedder.dimensions)}`).update(entries.map((entry) => `${entry.id}\0${entry.text}`).join("")).digest("hex");
87451
+ const fingerprint = (0, import_node_crypto17.createHash)("sha256").update(`${wanted ?? "all"}:${embedder.model}:${String(embedder.dimensions)}`).update(entries.map((entry) => `${entry.id}\0${entry.text}`).join("")).digest("hex");
87004
87452
  if (!options.force && fingerprint === await readDocsFingerprint(index, search.id, wanted)) {
87005
87453
  return { unchanged: true, index, indexed: entries.length };
87006
87454
  }
@@ -88113,7 +88561,7 @@ ${last}` : ""}`);
88113
88561
  try {
88114
88562
  const text2 = (await import_promises29.default.readFile(file2, "utf8")).replace(/\r\n/g, "\n");
88115
88563
  const meaningful = text2.split("\n").filter((line) => !/^(author|project|version|updated)\s*:/i.test(line) && !/^__(author|project|version|updated)__\s*=/.test(line)).join("\n").trim();
88116
- return (0, import_node_crypto16.createHash)("sha256").update(meaningful).digest("hex").slice(0, 16);
88564
+ return (0, import_node_crypto17.createHash)("sha256").update(meaningful).digest("hex").slice(0, 16);
88117
88565
  } catch {
88118
88566
  return void 0;
88119
88567
  }
@@ -88802,7 +89250,7 @@ ${last}` : ""}`);
88802
89250
  return;
88803
89251
  }
88804
89252
  const { config: config2 } = await configManager.load();
88805
- const id = input.id ?? (0, import_node_crypto16.randomUUID)();
89253
+ const id = input.id ?? (0, import_node_crypto17.randomUUID)();
88806
89254
  if (input.username !== void 0 && input.username.length > 0)
88807
89255
  await secrets.set(searchUserRefFor(id), input.username);
88808
89256
  if (input.password !== void 0 && input.password.length > 0)
@@ -90553,7 +91001,7 @@ ${contents}
90553
91001
  async function handleSaveSchedule(schedule) {
90554
91002
  try {
90555
91003
  const schedules = await loadSchedules();
90556
- const id = schedule.id.length > 0 ? schedule.id : (0, import_node_crypto16.createHash)("sha256").update(`${schedule.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
91004
+ const id = schedule.id.length > 0 ? schedule.id : (0, import_node_crypto17.createHash)("sha256").update(`${schedule.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
90557
91005
  const armed = { ...schedule, id, nextRunAt: nextFireTime(schedule, Date.now()) };
90558
91006
  await saveSchedules({ ...schedules, [id]: armed });
90559
91007
  } catch (error51) {
@@ -90562,7 +91010,7 @@ ${contents}
90562
91010
  }
90563
91011
  async function createScheduleFromProposal(proposal) {
90564
91012
  const schedules = await loadSchedules();
90565
- const id = (0, import_node_crypto16.createHash)("sha256").update(`${proposal.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
91013
+ const id = (0, import_node_crypto17.createHash)("sha256").update(`${proposal.name}:${String(Date.now())}`).digest("hex").slice(0, 12);
90566
91014
  const schedule = {
90567
91015
  id,
90568
91016
  name: proposal.name,
@@ -93033,7 +93481,12 @@ signs in without listing any jobs; with **Job to check in Test connection** fill
93033
93481
  \`<site>/job/<name>\` in Postman, so the two answers can be compared. Under its result, **Details** shows every request it made and what
93034
93482
  came back - the address, HTTP status, response headers and the start of the body, the gateway's token
93035
93483
  request first - with passwords, tokens and secrets masked; open by default when the test failed, with a
93036
- **Copy details** button for whoever runs the service. Error messages name the HTTP status (401 not signed
93484
+ **Copy details** button for whoever runs the service. Details begin with **Likely cause**, the first step that failed
93485
+ read in plain words (a name that does not resolve, a certificate not trusted, a redirect to a login page, what a
93486
+ 401, 403 or 404 usually means there), and each step says the same - for Confluence, Jira, Bitbucket and Jenkins too.
93487
+ **A pattern finds only some jobs?** Many servers answer a page at a time; when an answer says it has more (a total,
93488
+ a "next" link), the status and find tools say how many came back of how many, and to add the server's page-size
93489
+ parameter to the address in config:autosys (paths) - autosys_check_addresses shows what each address answers. Error messages name the HTTP status (401 not signed
93037
93490
  in, 403 forbidden - signed in but that account is not allowed) so they can be compared with Postman.
93038
93491
 
93039
93492
  **Read-only access?** Tick **My access is read-only** in the panel. The tools that change things
@@ -94041,7 +94494,28 @@ edits made outside the agent (in VS Code, say) are saved with \`hub_sync\` "push
94041
94494
  "team alerts",
94042
94495
  "personal alerts",
94043
94496
  "monitor_create",
94044
- "quiet hours"
94497
+ "quiet hours",
94498
+ "run window",
94499
+ "specific time",
94500
+ "once a day",
94501
+ "history of alert",
94502
+ "recurring alert",
94503
+ "retention",
94504
+ "cleanup",
94505
+ "opensearch history",
94506
+ "explain alert",
94507
+ "tool_calls",
94508
+ "edit schedule",
94509
+ "change schedule",
94510
+ "delete monitor",
94511
+ "delete check",
94512
+ "remove monitor",
94513
+ "personal monitor",
94514
+ "personal check",
94515
+ "monitor schedule",
94516
+ "schedule of a monitor",
94517
+ "monitor check",
94518
+ "monitoring check"
94045
94519
  ],
94046
94520
  body: `
94047
94521
  **Fire Code only.** Settings \u2192 Monitoring switches it on; a Monitoring button then appears at the top of the
@@ -94083,7 +94557,49 @@ while it stays red or amber, a quiet word when it clears, and quiet hours when o
94083
94557
  Each monitor can override it (right-click \u2192 How this one notifies), and its own \`notify\` sets the least
94084
94558
  severe level that notifies. Notifications have Open, Acknowledge and Snooze buttons.
94085
94559
 
94086
- **Agents can**: \`monitor_check_tool\` (run a tool once and check its answer strictly: PASS or FAIL with what
94560
+ **When checks run**: \`every\` ("15m") for an interval, kept to \`activeHours\` ("07:00-19:00", or "09:00-" for not
94561
+ before nine, "-17:00" for until five); \`at\` for exact times of day ("07:30" - once a day - or ["07:30", "12:00",
94562
+ "18:00"]); \`days\` for the days of the week, for both. A time missed while Fire Code was closed is not made up the
94563
+ next day.
94564
+
94565
+ **Change when it runs**: in its grid window, **Schedule** (or right-click a tile \u2192 Edit schedule\u2026): every N minutes
94566
+ or hours, only between two times (either may be empty), at set times of day, on chosen days. Saving writes only those
94567
+ fields into the skill file and keeps an approved monitor approved. An agent can change it too ("run the batch check
94568
+ every 10 minutes on weekdays"); you approve the change as a diff.
94569
+
94570
+ **Delete a monitor for good**: right-click its tile \u2192 Delete this monitor\u2026 (or \u22EF \u2192 Delete in its window). Its skill
94571
+ file, its results and history here, and your own checks in the team history go; Pause stops it for a while instead.
94572
+ A copy synced from the team's bucket or repository cannot be changed or deleted from the dashboard - the next sync
94573
+ would put it back - so ask the agent, or delete it for everyone in Settings \u2192 Skills.
94574
+
94575
+ **Personal monitors need nothing set up.** Ask for "a personal check" (or just a check, before team history exists)
94576
+ and the agent makes one only on this computer.
94577
+
94578
+ **Team monitors need OpenSearch** (Settings \u2192 Monitoring \u2192 Team history): choose an OpenSearch connection from the
94579
+ codebase monitoring runs with, and an index name the whole team shares. Without it a team monitor stays grey
94580
+ ("Needs team history"); personal monitors keep their history on this computer. Every member's Fire Code may run a
94581
+ team monitor, but each slot is **claimed** first, so it runs once across the team, and everyone's dashboard shows
94582
+ the newest check, saying who ran it. Writes never overwrite each other, and cleanup removes only your own checks.
94583
+
94584
+ **History** (the grid's History view): a bar per check in its colour, its height how many alerts it had; each
94585
+ alert's pattern - **new** today, **ongoing** since when, **recurring** on several days ("usually starting around
94586
+ 02:00"), comes and goes, or cleared; and any past check's alerted rows. A check keeps its colour, headline and the
94587
+ rows that had an alert. **Kept 90 days** by default (30 days to a year), cleaned every few hours; **Clean up now** in
94588
+ Settings \u2192 Monitoring, and **Delete its history** on a tile's right-click menu. A snoozed or paused monitor keeps its
94589
+ colour on its tile but no longer colours the Monitoring button.
94590
+
94591
+ **An alert explained**: double-click a coloured row. The author's advice for that rule comes first (asked for when
94592
+ the monitor is created), then **the agent's explanation** - what is wrong, whether it is new or known from the
94593
+ history, what to do. **Start a chat** opens a chat named after the alert in the codebase you pick (the first by
94594
+ default), with what is known already in the message box - press Enter to send it.
94595
+
94596
+ **Tools can call tools**: a Python tool lists what it calls in \`__tool_calls__ = ["server__query", "autosys_status"]\`
94597
+ - MCP tools, other Python tools and Fire Code's reading tools. That line is part of the approved code; in a
94598
+ monitor's check those calls run without asking - the same when the agent tries the monitor in a chat - and nothing
94599
+ that edits or runs commands is reachable. A tool calling another Python tool several times works (before Fire Code
94600
+ 0.61.0 only the first call did, which read as an approval problem).
94601
+
94602
+ **Agents can**: \`monitor_history\` (an alert's history: new, ongoing, recurring), \`monitor_check_tool\` (run a tool once and check its answer strictly: PASS or FAIL with what
94087
94603
  to change, and the columns and key for the monitor - an agent writing a Python tool for a monitor works until
94088
94604
  it passes), \`monitor_status\` (every monitor, or one monitor's alerts and rows), \`monitor_show\` (check
94089
94605
  now, open a grid or the dashboard), \`monitor_control\` (pause, snooze, acknowledge, notification level -
@@ -96135,11 +96651,13 @@ ${entry.record.text}`.toLowerCase();
96135
96651
  }
96136
96652
 
96137
96653
  // ../../packages/core/dist/python/callPolicy.js
96138
- var PYTHON_CALL_DENIED = "A Python tool may only call other Python tools and MCP tools. Built-in tools \u2014 running commands, editing files, creating tools or writing skills \u2014 are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.";
96139
- function mayPythonToolCall(name, group) {
96654
+ var PYTHON_CALL_DENIED = 'A Python tool may call other Python tools, MCP tools, and the built-in reading tools it declares in __tool_calls__ = ["name", ...]. Built-in tools that run commands, edit files, create tools or write skills are deliberately out of reach: a tool body is model-authored, and approving one must not silently grant the rest.';
96655
+ function mayPythonToolCall(name, group, declared = false) {
96140
96656
  if (name.startsWith("py__"))
96141
96657
  return true;
96142
- return group === "mcp";
96658
+ if (group === "mcp")
96659
+ return true;
96660
+ return declared && group === "read";
96143
96661
  }
96144
96662
  function describeNestedCall(caller, callee) {
96145
96663
  return `The Python tool "${caller}" is asking to call "${callee}".`;
@@ -96242,8 +96760,8 @@ That is a fault in the tool itself, or the source is unreachable from here. Fix
96242
96760
  }
96243
96761
 
96244
96762
  // ../../packages/core/dist/s3/sigv4.js
96245
- var import_node_crypto17 = require("node:crypto");
96246
- var EMPTY_PAYLOAD_SHA256 = (0, import_node_crypto17.createHash)("sha256").update("").digest("hex");
96763
+ var import_node_crypto18 = require("node:crypto");
96764
+ var EMPTY_PAYLOAD_SHA256 = (0, import_node_crypto18.createHash)("sha256").update("").digest("hex");
96247
96765
  function encodeSegment(segment) {
96248
96766
  return encodeURIComponent(segment).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
96249
96767
  }
@@ -96267,10 +96785,10 @@ function amzDate(now) {
96267
96785
  return `${now.toISOString().replace(/[-:]/g, "").slice(0, 15)}Z`;
96268
96786
  }
96269
96787
  function signingKey(secretAccessKey, date5, region, service) {
96270
- const dateKey = (0, import_node_crypto17.createHmac)("sha256", `AWS4${secretAccessKey}`).update(date5).digest();
96271
- const regionKey = (0, import_node_crypto17.createHmac)("sha256", dateKey).update(region).digest();
96272
- const serviceKey = (0, import_node_crypto17.createHmac)("sha256", regionKey).update(service).digest();
96273
- return (0, import_node_crypto17.createHmac)("sha256", serviceKey).update("aws4_request").digest();
96788
+ const dateKey = (0, import_node_crypto18.createHmac)("sha256", `AWS4${secretAccessKey}`).update(date5).digest();
96789
+ const regionKey = (0, import_node_crypto18.createHmac)("sha256", dateKey).update(region).digest();
96790
+ const serviceKey = (0, import_node_crypto18.createHmac)("sha256", regionKey).update(service).digest();
96791
+ return (0, import_node_crypto18.createHmac)("sha256", serviceKey).update("aws4_request").digest();
96274
96792
  }
96275
96793
  function signRequest(input) {
96276
96794
  const service = input.service ?? "s3";
@@ -96279,7 +96797,7 @@ function signRequest(input) {
96279
96797
  const date5 = timestamp.slice(0, 8);
96280
96798
  const url2 = new URL(input.url);
96281
96799
  const body = input.body ?? Buffer.alloc(0);
96282
- const payloadHash = (0, import_node_crypto17.createHash)("sha256").update(body).digest("hex");
96800
+ const payloadHash = (0, import_node_crypto18.createHash)("sha256").update(body).digest("hex");
96283
96801
  const headers = {
96284
96802
  ...input.headers,
96285
96803
  host: url2.host,
@@ -96303,9 +96821,9 @@ function signRequest(input) {
96303
96821
  "AWS4-HMAC-SHA256",
96304
96822
  timestamp,
96305
96823
  scope,
96306
- (0, import_node_crypto17.createHash)("sha256").update(canonicalRequest).digest("hex")
96824
+ (0, import_node_crypto18.createHash)("sha256").update(canonicalRequest).digest("hex")
96307
96825
  ].join("\n");
96308
- const signature = (0, import_node_crypto17.createHmac)("sha256", signingKey(input.secretAccessKey, date5, input.region, service)).update(stringToSign).digest("hex");
96826
+ const signature = (0, import_node_crypto18.createHmac)("sha256", signingKey(input.secretAccessKey, date5, input.region, service)).update(stringToSign).digest("hex");
96309
96827
  return {
96310
96828
  headers: {
96311
96829
  ...headers,
@@ -96826,15 +97344,15 @@ function createS3Tools(targets) {
96826
97344
  }
96827
97345
 
96828
97346
  // ../../packages/core/dist/s3/localFolder.js
96829
- var import_node_crypto18 = require("node:crypto");
97347
+ var import_node_crypto19 = require("node:crypto");
96830
97348
  function mirrorFolder(options) {
96831
97349
  const connection = safeSegment(options.connectionId);
96832
- const digest = (0, import_node_crypto18.createHash)("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
97350
+ const digest = (0, import_node_crypto19.createHash)("sha256").update((options.prefix ?? "").trim().toLowerCase()).digest("hex").slice(0, 8);
96833
97351
  return join2(options.storageDir, "s3", connection, `${options.kind}-${digest}`);
96834
97352
  }
96835
97353
  function safeSegment(id) {
96836
97354
  const cleaned = id.replace(/[^a-zA-Z0-9._-]/g, "-").replace(/-+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, 40);
96837
- const suffix = (0, import_node_crypto18.createHash)("sha256").update(id).digest("hex").slice(0, 6);
97355
+ const suffix = (0, import_node_crypto19.createHash)("sha256").update(id).digest("hex").slice(0, 6);
96838
97356
  return `${cleaned === "" ? "connection" : cleaned}-${suffix}`;
96839
97357
  }
96840
97358
  function join2(...parts) {
@@ -96951,13 +97469,13 @@ function reachableOrigins(hosts, extra = []) {
96951
97469
  }
96952
97470
 
96953
97471
  // src/identity.ts
96954
- var import_node_crypto19 = __toESM(require("node:crypto"), 1);
97472
+ var import_node_crypto20 = __toESM(require("node:crypto"), 1);
96955
97473
  var SingleUserIdentity = class _SingleUserIdentity {
96956
97474
  describe;
96957
97475
  static PRINCIPAL = { id: "local", displayName: "Local user" };
96958
97476
  principal;
96959
97477
  /** Long-lived, minted per server run, only ever sent in an `Authorization` header. */
96960
- sessionToken = import_node_crypto19.default.randomBytes(32).toString("base64url");
97478
+ sessionToken = import_node_crypto20.default.randomBytes(32).toString("base64url");
96961
97479
  /**
96962
97480
  * Single-use and short-lived, because it travels in the launch URL's fragment where it
96963
97481
  * can end up in shell history or a terminal scrollback (§14).
@@ -96967,7 +97485,7 @@ var SingleUserIdentity = class _SingleUserIdentity {
96967
97485
  * raises it, and what that costs is stated where it is set: a longer window is a longer time in
96968
97486
  * which somebody reading that scrollback can use it before you do.
96969
97487
  */
96970
- handoffToken = import_node_crypto19.default.randomBytes(32).toString("base64url");
97488
+ handoffToken = import_node_crypto20.default.randomBytes(32).toString("base64url");
96971
97489
  handoffExpiresAt;
96972
97490
  handoffSeconds;
96973
97491
  /**
@@ -97001,7 +97519,7 @@ var SingleUserIdentity = class _SingleUserIdentity {
97001
97519
  * which is the same person it was printed to in the first place.
97002
97520
  */
97003
97521
  remintHandoff() {
97004
- this.handoffToken = import_node_crypto19.default.randomBytes(32).toString("base64url");
97522
+ this.handoffToken = import_node_crypto20.default.randomBytes(32).toString("base64url");
97005
97523
  this.handoffExpiresAt = Date.now() + this.handoffSeconds * 1e3;
97006
97524
  return this.handoffToken;
97007
97525
  }
@@ -97040,10 +97558,10 @@ function timingSafeEquals(a, b) {
97040
97558
  const left = Buffer.from(a);
97041
97559
  const right = Buffer.from(b);
97042
97560
  if (left.length !== right.length) return false;
97043
- return import_node_crypto19.default.timingSafeEqual(left, right);
97561
+ return import_node_crypto20.default.timingSafeEqual(left, right);
97044
97562
  }
97045
97563
  function storageKeyFor(principal) {
97046
- return import_node_crypto19.default.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
97564
+ return import_node_crypto20.default.createHash("sha256").update(principal.id).digest("hex").slice(0, 32);
97047
97565
  }
97048
97566
  var OpenIdentity = class _OpenIdentity {
97049
97567
  describe = "single user, no token (--no-token)";
@@ -97317,19 +97835,19 @@ var import_promises32 = __toESM(require("node:fs/promises"), 1);
97317
97835
  var import_node_path58 = __toESM(require("node:path"), 1);
97318
97836
 
97319
97837
  // src/vaultCrypto.ts
97320
- var import_node_crypto20 = require("node:crypto");
97838
+ var import_node_crypto21 = require("node:crypto");
97321
97839
  function isVaultEnvelope(value) {
97322
97840
  const v = value;
97323
97841
  return typeof v === "object" && v !== null && v.sunVault === 1 && typeof v.iv === "string" && typeof v.tag === "string" && typeof v.data === "string";
97324
97842
  }
97325
97843
  function sealSecrets(secrets, key2) {
97326
- const iv = (0, import_node_crypto20.randomBytes)(12);
97327
- const cipher = (0, import_node_crypto20.createCipheriv)("aes-256-gcm", key2, iv);
97844
+ const iv = (0, import_node_crypto21.randomBytes)(12);
97845
+ const cipher = (0, import_node_crypto21.createCipheriv)("aes-256-gcm", key2, iv);
97328
97846
  const data = Buffer.concat([cipher.update(JSON.stringify(secrets), "utf8"), cipher.final()]);
97329
97847
  return { sunVault: 1, iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), data: data.toString("base64") };
97330
97848
  }
97331
97849
  function openSecrets(envelope, key2) {
97332
- const decipher = (0, import_node_crypto20.createDecipheriv)("aes-256-gcm", key2, Buffer.from(envelope.iv, "base64"));
97850
+ const decipher = (0, import_node_crypto21.createDecipheriv)("aes-256-gcm", key2, Buffer.from(envelope.iv, "base64"));
97333
97851
  decipher.setAuthTag(Buffer.from(envelope.tag, "base64"));
97334
97852
  const plain = Buffer.concat([decipher.update(Buffer.from(envelope.data, "base64")), decipher.final()]);
97335
97853
  const parsed = JSON.parse(plain.toString("utf8"));
@@ -97447,7 +97965,7 @@ var FileSecretStore = class {
97447
97965
  };
97448
97966
 
97449
97967
  // src/reviewQueue.ts
97450
- var import_node_crypto21 = __toESM(require("node:crypto"), 1);
97968
+ var import_node_crypto22 = __toESM(require("node:crypto"), 1);
97451
97969
  var import_promises33 = __toESM(require("node:fs/promises"), 1);
97452
97970
  var import_node_path59 = __toESM(require("node:path"), 1);
97453
97971
  var ReviewQueue = class {
@@ -97486,7 +98004,7 @@ var ReviewQueue = class {
97486
98004
  );
97487
98005
  const queued = {
97488
98006
  ...request,
97489
- id: import_node_crypto21.default.randomUUID(),
98007
+ id: import_node_crypto22.default.randomUUID(),
97490
98008
  submittedAt: Date.now(),
97491
98009
  status: "pending"
97492
98010
  };