Metadata-Version: 2.4
Name: rustygate
Version: 0.1.53
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: Implementation :: CPython
Requires-Dist: fastws-cli>=0.0.39 ; extra == 'dev'
Requires-Dist: fastcore>=2.2.41 ; extra == 'dev'
Requires-Dist: pytest ; extra == 'dev'
Requires-Dist: pytest-asyncio ; extra == 'dev'
Requires-Dist: pytest-timeout ; extra == 'dev'
Requires-Dist: pytest-xdist ; extra == 'dev'
Requires-Dist: httpx ; extra == 'dev'
Requires-Dist: websockets ; extra == 'dev'
Requires-Dist: jupyter-client ; extra == 'dev'
Requires-Dist: jupywire>=0.1.14 ; extra == 'dev'
Requires-Dist: jupyasyncclient>=0.2.32 ; extra == 'dev'
Requires-Dist: ipymini>=0.1.26 ; extra == 'dev'
Requires-Dist: basedpl ; extra == 'dev'
Requires-Dist: aihist>=0.1.5 ; extra == 'dev'
Requires-Dist: nbformat ; extra == 'dev'
Provides-Extra: dev
Summary: Jupyter kernel gateway with terminals, files, and cells APIs, as a single binary
Author: Jeremy Howard
Maintainer-email: "fast.ai" <infos@fast.ai>
License-Expression: LicenseRef-Proprietary
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/AnswerDotAI/rustygate
Project-URL: Issues, https://github.com/AnswerDotAI/rustygate/issues
Project-URL: Repository, https://github.com/AnswerDotAI/rustygate

# rustygate

A Jupyter kernel gateway as one binary: kernels, terminals, files, search, and per-cell notebook operations, over the same REST and websocket API shapes `jupyter_server` uses.

## Running

    rustygate [--host H] [--port N] [--token T | --token-file PATH] [--trust-loopback] [--root DIR] [--settings-file PATH] [--tls] [--exec-allow CMDS] [--autorun DIR] [--cull-idle SECONDS] [--exit-with-parent]

The defaults are 127.0.0.1, port 8787, no auth, and the working directory as the files root. With a token set, requests carry `Authorization: Bearer T`; Jupyter's `Authorization: token T` form and `?token=T` are also accepted. `--token-file` reads the token without putting it in the process arguments. `--trust-loopback` lets clients whose actual TCP peer is loopback omit the token. Do not use it behind an untrusted same-host reverse proxy, since the proxy is the TCP peer. Forwarded headers never affect authentication. `--tls` serves https and wss from a self-signed certificate generated at startup; clients opt out of verification (jupyasyncclient's `verify=False`).

The Python helper `jupyasyncclient.start_gateway(('rustygate',))` starts a background gateway with inherited stdout and stderr. Gateway and kernel startup errors appear in the calling process's console. It passes `--exit-with-parent`. With that flag the gateway shuts down as it does on SIGINT once the process that started it exits, even when that process is killed.

`GET /` returns JSON with the gateway build `version` and effective working root `cwd`, under normal gateway auth. A 200 means the gateway is serving HTTP, not that its kernels or models are ready. Human-readable API notes live in [docs/routes.md](docs/routes.md); the gateway does not serve HTTP OpenAPI or help/index pages.

`SOLVELP_URL` (default `https://solve.it.com`) configures the single Responses server at startup. The gateway reads `AAI_USER_KEY` once at startup and removes it from the process environment before spawning threads or children. The Solve-LP key in `X-API-Token` selects settings by its `<user-id>:<signature>` form. The instance owner, identified by the startup `AAI_USER_KEY`, uses the base `solveit_settings.json` file in the launch directory. Requests without a caller key use that same file and fall back to the startup owner key for Responses-server calls. `--settings-file PATH` selects its location, independently of `--root`. Other users have separate preferences and secrets in `solveit_settings/<user-id>.json` beside it. Guest files never fall back to the base file. See [docs/routes.md](docs/routes.md) for the settings/secrets API.

New and restarted kernels read the creating user's saved secrets; new terminals read the initiating user's saved secrets. Existing processes keep their environment. Everyone sharing a kernel can read its environment and state; personal files do not isolate a shared kernel.

Reply usage blocks are off by default. Add `LLM_USAGE` with value `1` in Solveit's Secrets UI to enable them for your replies. The gateway reads the prompting user's value for each reply.

Dialog settings support custom assistants: `mode: "bare"` omits the built-in teaching material, `sysp` supplies literal system instructions, and `prefixpaths` names notebooks of worked examples and startup code. Prefix messages are marked as examples rather than user conversation. Their nonprompt code cells run with CRAFT code on startup and restart. Paths beginning with `/` use the served root; other paths use the dialog's folder.

Prompt requests can select `mode: "chat"` for built-in file-task framing or override with `bare`, `learning` or `concise` without changing notebook settings. Shell executes use metadata; the kernel prompt HTTP route uses a body field. Same-kernel prompts invoked by a model tool inherit its mode when omitted. Shell and HTTP prompts share tool/expression defaults; pass `[]` to disable automatic additions. See [docs/routes.md](docs/routes.md#prompts-srcturnrs).

The gateway formats its current UTC time and data root directly into each prompt's turn instructions, without changing system instructions.

### Working directories

Notebook-bound kernels default to the notebook's parent directory under the served root. A dialog's terminal, bound to its notebook, defaults to the same folder. Explicit `cwd` overrides either default; relative values use the served root. Restart recomputes a kernel's default cwd from its current binding. See [DEV.md](DEV.md#kernel-lifecycle) for unbound processes and path rules.

### Notebook state and connections

Clients sharing a notebook share its kernel and authoritative notebook state. Accepted edits broadcast to every subscriber, including their author. Saving runs on a 500ms poll tick; contents reads, copies, search and command execution first save pending changes in their file or directory scope, then operate on disk normally.

`POST /api/kernels` with a `path` returns its existing non-dead kernel unchanged (200), apart from `dialog`'s settings, or starts a new kernel (201). A concurrent creation still starting waits for it and returns 200 with its model. Without a path, each request starts a new kernel. `unique: true` always binds a new notebook, at the first free `_n` name beside `path` when it's taken. A `dialog` object sets the dialog up: a missing notebook starts from the inherited `TEMPLATE.ipynb` files, its settings are completed, and inherited CRAFT code runs once a client connects. `GET /api/models` returns the caller's cached model catalog (loading on a cache miss, or force-refreshing with `?refresh=true`); `POST /api/models` force-refreshes and can also settle a dialog's settings. See [DEV.md](DEV.md#kernel-lifecycle) for both.

A kernel id identifies the logical kernel across rename and restart. A failed restart removes the kernel entry. `GET/POST /api/kernels/{kid}/cells` operates on its current notebook binding. `PATCH /api/kernels/{kid}` with `{"path":"new.ipynb"}` renames that notebook. Deletion and new creation produce a new id. Path-addressed file and cell operations remain available for unopened notebooks.

`init_git: true` on kernel creation ensures an independent repository in the notebook's parent directory. It does not change TEMPLATE/CRAFT handling or exclude the notebook. Notebook metadata `solveit.auto_commit: true` commits that folder's changes after saved prompt turns with local tool calls, including partial changes after interruption. Plain replies do not commit. Automatic commits run best-effort after saving the reply and skip on lock contention without blocking renames or overlapping turns; see [docs/routes.md](docs/routes.md#automatic-commits).

Cell reads support `section=ID` for a heading and its descendants, `ancestors=ID` for enclosing headings, and `before=ID` or `after=ID` for every cell on one side of a cell. All use ordinary cell IDs and ignore collapse flags. `fields=id` returns IDs in cell dictionaries; `fields=id,source` returns IDs and sources. Omit `fields` for full cells without attachments, or use `fields=*` for all cell fields including attachments. `fields=*,meta` also returns notebook metadata. See [DEV.md](DEV.md#cells-api) for heading detection and selector composition.

`max_tokens=N` keeps the newest cells whose approximate token counts total at most `N`. See [DEV.md](DEV.md#cells-api) for the token estimate.

Notebook settings use the same ordered ops: `{"ops":[{"op":"meta","metadata":{"solveit":{"mode":"learn"}}}]}` merge-patches notebook metadata without transferring or replacing cells and outputs. Accepted metadata broadcasts carry the resulting metadata, so subscribers need no follow-up read.

File and cell edits use last-accepted-edit-wins semantics, without hashes or stale-write checks. File writes and copies can require a new destination with `overwrite=false`; renames never overwrite. The watcher reloads valid external changes when disk changes, 3-way merging non-overlapping cell edits against the last synced version when unsaved gateway edits exist and saving conflicting external bytes to a sibling conflict copy.

Kernel traffic uses bounded queues with backpressure before notebook updates. A slow frontend's full queue closes its whole connection rather than silently dropping individual messages. Disconnected messages are not replayed: reconnecting clients load current notebook state. Kernel execution and persistence continue without connected clients.

### Startup notebooks

`--autorun AUTORUN` runs the direct `*.ipynb` children of `AUTORUN` under the files root once per gateway startup. Each notebook gets its own path-bound kernel, with its parent directory as the working directory. Nonempty code cells run in notebook order; outputs persist normally. Other cell types and CRAFT inheritance are not processed. Shared initialization belongs in explicit imports in the notebook.

Startup notebooks receive the `AAI_USER_KEY` captured at gateway startup for their preferences, secrets, and API calls.

Notebooks run independently in the background, without delaying HTTP readiness. A cell error stops the remaining cells in that notebook; errors are logged and its kernel remains available for inspection. Other notebooks and the gateway keep running. A missing directory is empty; unreadable directories or malformed notebooks produce an error. Attaching a client or restarting an individual kernel does not rerun AUTORUN. Omit the flag to disable it. `rustygate service install` accepts the same flag.

Kernels bound to these direct-child notebook paths are exempt from idle culling, including kernels created later through the API. Moving a notebook into or out of this directory changes that protection without running it. Kernel models and notebook views include a read-only `autorun` flag for the current path.

## Running as a service

`rustygate service` installs and controls a user service using launchd on macOS and systemd on Linux:

    rustygate service install --root ~/git --workdir ~/git/project
    rustygate service status
    rustygate service restart
    rustygate service stop
    rustygate service start
    rustygate service uninstall

`install` starts the service immediately; running it again replaces the configuration. Add `--host 0.0.0.0` for direct network access, `--token-file ~/.config/rustygate/token` for authentication, `--trust-loopback` when same-host clients should not need that token, and `--tls` when wanted. A missing token file is generated with user-only permissions. `--env-file` sources environment variables inherited by kernels. The service PATH is the rustygate binary's own directory (the venv bin, under a pip install) plus the standard system directories, so kernels find `python` despite the minimal launchd and systemd defaults. The default loopback service can instead be reached remotely through an SSH tunnel.

## Kernels

`POST /api/kernels` starts the kernel that `name` selects from installed Jupyter kernelspecs. `pip install ipymini` installs the `py` kernelspec (Python/IPython). Without `name` or `argv`, the bound notebook's kernelspec chooses, where `python3`, `python` and `py` all mean `py`. `py` is also the default without a notebook. `pip install basedpl` installs `bpl`. A `name` cannot be combined with a custom `argv`. An unknown name returns 400 with the available names.

`GET /api/kernelspecs` lists the available names with their `kernel.json` contents, in `jupyter_server`'s format. `GET /api/kernelspecs/{name}` returns one. The gateway reads the kernelspec directories on each request. A kernel installed while the gateway runs needs no gateway restart.

The gateway searches the directories that `jupyter kernelspec list` searches, in the same order, then `~/.ipython/kernels`. The first kernelspec of a name wins. The environment directories are `share/jupyter` beside the `bin/` that holds the `rustygate` binary, then under `$VIRTUAL_ENV`, then under `$CONDA_PREFIX`. A binary outside any Python environment finds an activated environment's kernels that way. An interrupt follows the kernelspec's `interrupt_mode`. The gateway sends SIGINT, or a control-channel `interrupt_request` when the mode is `message`.

A kernel can advertise `interrupt requires restart` in `kernel_info_reply.supported_features` when its language cannot safely cancel running native code. Stop then restarts the process, losing live variables but preserving the notebook, kernel id and connected clients. A parked AI turn with ordinary code queued behind it still interrupts normally.

See [DEV.md](DEV.md#kernelspecs) for the search order and the `kernel.json` fields the gateway uses.

## MCP

Choose a kernel, then execute code in it:

```python
create(kernel="bpl")
exec(code="avg←+/÷≢ ⋄ avg 2 4 9")
```

`kernel` takes the names `POST /api/kernels` takes: installed kernelspecs such as `py` (Python/IPython, installed by `ipymini`) and `bpl` (installed by `basedpl`). The `create` tool's schema lists the names found when the client lists the tools. `create(kernel=...)` creates an unbound kernel. `exec` never creates or switches kernels. Use `list_kernels` and `use_kernel(kernel=...)` to attach to an existing dialog kernel.

Creation and selection return kernel-specific guidance. Creation, selection, and listing report both the implementation and the language from `kernel_info_reply`. Python startup/inspectors run only for Python kernels, including on restart. Clikernel forwards the tools and arguments directly, including creation on named gateways.

`POST /mcp` is a stateful Streamable HTTP MCP server for Claude Code and other MCP clients. Its tools are `list_kernels`, `create`, `use_kernel`, `delete_kernel`, `exec`, `restart`, and `interrupt`. Code runs exactly as written; Python/IPython magics such as `%%bash` work in Python kernels. The MCP session remembers its current kernel, so no id is needed between calls. Call `create` or `use_kernel` before executing. Ending the session (`DELETE /mcp`) stops every kernel it created with autoclose, enabled by default; `autoclose=false` keeps a new kernel. Selecting an existing kernel never claims ownership. Clients may send creation defaults (cwd, env, Python startup code, quiet) in initialize params; see [DEV.md](DEV.md#mcp-api).

Kernels actually spawned through MCP receive `JUPYGATE_LAUNCHER=mcp`, available during their startup profiles and preserved across restart. Selecting or attaching to a kernel that was already running does not alter its environment. Subagent isolation (`JUPYGATE_AGENT`, per-agent sessions, and 30-minute idle eviction) is owned by `clikernel`. See [DEV.md](DEV.md#mcp-api) for the tool and execution contract.

