diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..e1e887e --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,179 @@ +# Installing Trader's Agent: instructions for AI agents + +**If you are an AI agent and your user gave you this repository's link to install, follow this file.** +It is written for you: every command is exact, and each step says what success looks like. A human can +read it too. The README holds the same facts, written for people. + +Trader's Agent is a chart-first trading desk: +- a local console on `127.0.0.1` (a Vela chart, the LuxAlgo Library, a paper broker); +- a `traders-chart` MCP server with 56 tools, so you can drive that chart; +- a skill that teaches you to use those tools; +- in Hermes Desktop, a sidebar pane that shows the chart beside the chat. + +## Rules + +1. **Tell your user what you are about to do, in one short message, before you run anything.** For + example: "I'll clone it to ~/tradersagent-plugin and run its installer. That sets up a Python + environment, installs the console as a login service, and registers the chart tools with me. No + sudo; about a minute." Then proceed unless they object. +2. **Never use `sudo`**, and never edit system files. Everything installs into the user's home folder. +3. **Run only the commands below.** Do not add optional extras (`--with-edge`, `--with-prop`, + `--with-backtest`) unless the user asks for them. They are large and need Node 20+. +4. **If a step fails, stop.** Show the user the exact error and the matching row under + [If something fails](#if-something-fails). Do not improvise workarounds. +5. **Keep the clone where you put it.** The console service runs from that folder, so never clone into a + temporary directory. + +## 1. Check the machine + +```bash +uname -s # Linux or Darwin (macOS). Windows: stop, it is not supported. +git --version # required +command -v uv || python3 --version # uv, OR a Python 3.11+ (one of the two is enough) +curl --version | head -1 # required +``` + +Then work out which agent host you are running in: + +| Signal | You are in | Go to | +|---|---|---| +| `$HERMES_HOME` is set, or `~/.hermes` exists, or `hermes` is on PATH | Hermes Agent / Hermes Desktop | step 3A | +| `dsh` is on PATH, or your user says DeepSeek Harness | DeepSeek Harness | step 3B | +| neither | another agent | step 3C | + +## 2. Get the code + +```bash +if [ -d ~/tradersagent-plugin/.git ]; then + git -C ~/tradersagent-plugin pull --ff-only +else + git clone --depth 1 https://github.com/godzillacode0000/tradersagent-plugin ~/tradersagent-plugin +fi +cd ~/tradersagent-plugin +``` + +## 3A. Hermes Agent / Hermes Desktop + +```bash +./install.sh --all +``` + +This one command: +1. finds or builds a Python with the `mcp` client (uses `uv` when present); +2. installs the plugin and the desk skill into `$HERMES_HOME` (default `~/.hermes`); +3. installs the console as a login service on port 8787; +4. registers the `traders-chart` MCP server with Hermes; +5. waits until the console answers. + +It is safe to run again: it updates in place. + +**Success:** it ends with `Done in Ns. The console is answering on http://127.0.0.1:8787.` + +Two lines you may also see: +- **`register-mcp.sh: no 'hermes' on PATH — run this once in a terminal where it is:`** followed by a + `hermes mcp add traders-chart ...` command. If you can run `hermes`, run that exact command. + Otherwise give it to your user to paste. +- **`note: no systemd user session here — starting the console detached`** means the console is + running now but will not start again after a reboot. Tell your user. + +Then go to step 4. + +## 3B. DeepSeek Harness (dsh) + +dsh gets a desk of its own: a separate console on port 8788, with its own chart, paper account and +token. It is never linked to a Hermes desk on the same machine. + +First find the JSON file where this dsh lists its MCP servers. Check dsh's docs or config folder. If +you cannot find it, ask your user. Do not guess. + +```bash +./adapters/dsh/install-dsh.sh --mcp-file /path/to/dsh/mcp.json # skill + MCP entry (other servers kept, backup made) +./adapters/dsh/install-dsh.sh --service # dsh's own console, starts at login +``` + +If you could not find the MCP file, run `./adapters/dsh/install-dsh.sh` with no flags. It prints the +JSON entry, which your user can paste into dsh's config themselves. + +**Success:** `install-dsh.sh` prints `dsh gets a desk of its own ('dsh' on port 8788)`, and `--service` +prints `ok console running ... on port 8788`. + +Then go to step 4. + +## 3C. Another MCP-capable agent + +There is no ready adapter for your host, and this path is untested. Tell your user so. If they want to +try anyway, use the dsh adapter: it writes a standard stdio MCP entry and runs an isolated desk. + +```bash +./adapters/dsh/install-dsh.sh --skills-dir /your/skills/folder # prints a standard {"mcpServers": {...}} entry +./adapters/dsh/install-dsh.sh --service # the console it points at, on port 8788 +``` + +Add the printed entry to your MCP configuration. + +## 4. Verify + +| Host | Command | Must end with | +|---|---|---| +| Hermes | `./install.sh --doctor` | no `FAIL` lines | +| dsh, or another agent | `./adapters/dsh/install-dsh.sh --doctor` | `all checks passed` | + +Lines starting with `--` are optional parts that are not installed. They are not failures. + +Then check that the console answers: + +```bash +curl -fsS http://127.0.0.1:8787/api/health # Hermes desk +curl -fsS http://127.0.0.1:8788/api/health # dsh desk +``` + +The `instance` field must say `default` for the Hermes desk and `dsh` for the dsh desk. + +## 5. Tell your user what is left + +You cannot click inside their app, so finish with these steps for them. + +**Hermes Desktop:** +1. Press Cmd/Ctrl+K and choose "Reload desktop plugins". +2. Click "Trader's Agent" in the left sidebar. The chart opens beside the chat. +3. If the row is missing: Settings → Plugins → "Trader's Agent" → on. +4. Start a new agent session so it gets the chart tools, then ask: "what is on my chart?" + +**DeepSeek Harness:** +1. Restart dsh, or reload its MCP servers and skills. +2. Open http://127.0.0.1:8788/ in a browser to watch the chart. +3. Ask: "what is on my chart?" + +## If something fails + +| You see | Do this | +|---|---| +| `no python with the 'mcp' client found` | `./bin/setup-python.sh`, then repeat your step 3 command | +| `no uv and no python 3.11+ on PATH` | ask your user to install `uv` (https://docs.astral.sh/uv/) or Python 3.12, then retry | +| `cannot listen on 127.0.0.1:8787` / port in use | another program uses the port. Run `./install.sh --doctor` and show your user the result. Do not kill processes you did not start | +| `console not answering` after install | read the last 30 lines of the log the installer printed (`console.log`, or `journalctl --user -u traders-agent.service -n 30`) and show them | +| `the console on ... is the 'default' desk, not 'dsh'` | dsh's port is taken by the Hermes desk. Run `./adapters/dsh/install-dsh.sh --service` | +| the chart pane says the console is not running | `./console/service-linux.sh status` (Linux) or `./console/service-macos.sh status` (macOS) | +| anything else | stop, and show your user the full error | + +## Update and uninstall + +```bash +cd ~/tradersagent-plugin && git pull --ff-only && ./install.sh --all # Hermes: update in place +./install.sh --uninstall # Hermes: remove plugin and skill (prints what else to undo) +./adapters/dsh/install-dsh.sh --uninstall --mcp-file /path/to/dsh/mcp.json # dsh: remove skill, entry and dsh's service +``` + +The user's paper account and settings are left in `~/.local/state/traders-agent/` on purpose. +Uninstalling never deletes them. + +## Working on this repository instead? + +If you were asked to change this code rather than install it, this file is not your guide. Start with +[`docs/HANDOFF.md`](docs/HANDOFF.md). Run the tests with: + +```bash +python3 -m unittest discover -s console/backend/tests +``` + +Then run the checks in `.github/workflows/ci.yml` before you push. diff --git a/CHANGELOG.md b/CHANGELOG.md index eca6351..3ac3c3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,8 +4,43 @@ All notable changes to this project are documented here. Format: [Keep a Changel ## [Unreleased] +### Added + +- **`AGENTS.md`: give an agent the repo link and it installs the plugin** (30 Oct). A file written for AI agents + and signposted at the top of the README ("If you are an AI agent ..."). It covers: + - telling the user what will happen, before running anything; + - checking the machine and working out the host (Hermes, DeepSeek Harness, other); + - the exact install commands for each host, and the line that means success; + - the two warnings an install can print (no `hermes` on PATH, no systemd) and what to do about each; + - verifying with the doctor and `/api/health`; + - what to tell the user at the end, since an agent cannot click inside their app; + - a troubleshooting table that quotes the real error lines; + - update and uninstall. + + Its rules: no sudo, no optional extras unless asked, stop on failure. `test_agents_guide.py` fails if a flag it + runs or a message it waits for stops existing in the scripts. A fresh-home dry run of the guide took 7 s to a + console answering on 8787 (Hermes) and 8788 (dsh, doctor: all checks passed). + ### Changed +- **The DeepSeek Harness gets a desk of its own** (30 Oct). The operator: a desk opened in dsh "should stay in + DeepSeek Harness only — not linked or connected" to the Hermes one. + - **Before:** the dsh adapter pointed its MCP server at the Hermes console on 8787. Both agents shared one chart, + one paper account, one write token and one set of studies, and dsh's in-app study chat ran through the Hermes CLI. + - **Now:** `TRADERS_AGENT_INSTANCE=NAME` (`console/backend/instance.py`) gives a console its own token, paper + account, chart and study files under `~/.local/state/traders-agent/instances/NAME/`. It also gets its own Edge + Stats workspace and engine on the console's port + 2, and no Hermes chat unless `HERMES_CLI` is set. + - A named desk runs on its own port, and the browser keeps per origin, so saved scripts, layout and theme are + separate too. + - `install-dsh.sh` defaults to desk `dsh` on 8788. New options: `--console` runs that desk, and `--service` + installs it as its own service (`traders-agent-dsh.service` / `com.traders-agent.console.dsh`). `--doctor` + fails if the console on dsh's port is another desk. `--shared` is the explicit way back to one desk. + - Unset, nothing changes for Hermes. + - Market data stays shared on purpose. + - Pinned by `test_instances.py`, which runs two real consoles side by side: different tokens, a token refused + across desks, a chart command that never reaches the other chart, and the chat refused on the dsh desk. Also + pinned by adapter and service tests. + - **The replay strip is a glass capsule** (30 Oct), the operator's pick of two designs. One frosted pill, about 430 px: the scrubber is its top edge (white playhead, the range's first and last bar fade in on hover), Play is the one bright control and turns into Pause, back-to-start and next-bar flank @@ -20,6 +55,11 @@ All notable changes to this project are documented here. Format: [Keep a Changel ### Fixed +- **`./install.sh --doctor` failed a working install.** The install started the console with the Python that has + the `mcp` client, but the doctor checked the first Python 3.11+ on PATH, a 3.14 without it, and said FAIL. It + now prefers an interpreter with `mcp`, the same order as the service and `bin/setup-python.sh`. Found by + following `AGENTS.md` on a fresh home. + - **The chart sprang back to its right edge after a drag, in replay and out** (30 Oct). Two faults in `nudgeChart()` (app.js): its repaint dispatched a window `resize`, and the resize handler called `nudgeChart()` again — an endless loop, measured at 140 view resets in 10 idle seconds; and each diff --git a/README.md b/README.md index fef5b54..7b2b88f 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,11 @@ +> [!IMPORTANT] +> **If you are an AI agent asked to install this for your user, follow [`AGENTS.md`](AGENTS.md).** It covers +> Hermes, DeepSeek Harness and other agents: exact commands, what success looks like, how to verify, and what to +> tell your user at the end. + A sidebar entry that docks a full trading console **beside your conversation**: **Vela**-rendered candlesticks and the **LuxAlgo Library** (800+ concepts and indicators, served live by LuxAlgo's own MCP server) in one local web app — your chat session is left exactly where it was. @@ -53,6 +58,9 @@ MCP server) in one local web app — your chat session is left exactly where it ## Install +**Let your agent do it:** give Hermes (or DeepSeek Harness) this repository's link and ask it to install it. It +reads [`AGENTS.md`](AGENTS.md) and runs the steps below, then tells you the two clicks left in the app. + **One command** (Linux and macOS; about a minute with [uv](https://docs.astral.sh/uv/), a few without it): ```bash @@ -414,22 +422,54 @@ is still not a headless renderer: with no view attached, commands fail fast and ### Using it from the DeepSeek Harness (dsh) -The chart pane is Hermes-only, but the desk is not: the same MCP server (56 tools) and the same skill work from dsh, -and the agent drives the console's chart exactly as it does from Hermes. Open `http://127.0.0.1:8787/` in a browser tab -to watch it. +The chart pane is Hermes-only, but the desk is not: the same MCP server (56 tools) and the same skill work from dsh. +**dsh gets a desk of its own.** It runs a second console on `127.0.0.1:8788` (`TRADERS_AGENT_INSTANCE=dsh`, see +`console/backend/instance.py`). Nothing the dsh agent does reaches the Hermes desk on 8787, and nothing Hermes does +reaches dsh's desk. ```bash -./console/start.sh # the console must be running ./adapters/dsh/install-dsh.sh --mcp-file PATH # PATH: the JSON file where your dsh lists MCP servers -./adapters/dsh/install-dsh.sh --doctor # skill, launcher, a real MCP handshake, the console +./adapters/dsh/install-dsh.sh --console # run dsh's console (or --service: start it at login) +./adapters/dsh/install-dsh.sh --doctor # skill, launcher, a real MCP handshake, and that 8788 is dsh's desk ``` -It copies the skill to `~/.agents/skills/trader-desk` (`--skills-dir` or `DSH_SKILLS_DIR` to change it) and writes a -stdio entry into the file you name (it runs `console/mcp/server.py` with `PY`, the repo's `.venv` or a python that has the `mcp` client, same order as `bin/register-mcp.sh`; else `uvx fastmcp run`; `--venv` forces a private venv), -keeping your other servers and a `.bak-traders` copy. Without `--mcp-file` it prints the entry for you to paste. -`PORT=9000` points the entry at a console on another port. It reads nothing from dsh itself and writes nowhere else, so -check your dsh's own docs for the config path. Not verified against a real dsh install yet: the handshake is tested with -the MCP client, and dsh's skill and config locations are as reported by third-party dsh plugins. +Open `http://127.0.0.1:8788/` in a browser tab to watch the dsh agent drive its chart. + +| | Hermes desk | dsh desk | +|---|---|---| +| console | `127.0.0.1:8787` | `127.0.0.1:8788` | +| chart and agent commands | its own | its own | +| write token | its own | its own | +| paper account | its own | its own | +| studies | its own | its own | +| saved scripts, layout, theme | its own | its own | +| Edge Stats engine and workspace | `8789` | `8790` | +| in-app study chat | the Hermes CLI | off (the dsh agent talks through its MCP tools) | +| service | `traders-agent.service` / `com.traders-agent.console` | `traders-agent-dsh.service` / `com.traders-agent.console.dsh` | +| state | `~/.local/state/traders-agent/` | `~/.local/state/traders-agent/instances/dsh/` | +| market data | shared | shared | + +Market data is shared on purpose: the tick store, candle caches, downloaded data, thumbnails and the prop-firm +simulator describe the market, not a desk. + +The doctor fails if the console on dsh's port turns out to be another desk. `--shared` is the explicit way back to one +desk: the entry points at the Hermes console on 8787, the same chart and paper account. + +The installer copies the skill to `~/.agents/skills/trader-desk` (`--skills-dir` or `DSH_SKILLS_DIR` to change it). It +writes a stdio entry into the file you name. That entry runs `console/mcp/server.py` with the first of these that +works: +1. `PY`, the repo's `.venv`, or a python that has the `mcp` client (the same order as `bin/register-mcp.sh`); +2. `uvx fastmcp run`. + +`--venv` forces a private venv instead. Your other servers are kept, and a `.bak-traders` copy is saved. Without +`--mcp-file` the installer prints the entry for you to paste. + +`PORT=9000` moves dsh's console to another port. `--uninstall` removes the skill and dsh's service. It never touches +the Hermes console and keeps dsh's desk state. + +The installer reads nothing from dsh itself and writes nowhere else, so check your dsh's own docs for the config path. +This is not verified against a real dsh install yet. The handshake is tested with the MCP client, and the two desks +are tested side by side as real consoles. dsh's skill and config locations are as reported by third-party dsh plugins. ## Screenshots @@ -486,6 +526,7 @@ bin/ register-mcp.sh (the MCP registration on its own) · is-enabl | `TRADER_CONSOLE_TOKEN_FILE` | `~/.local/state/traders-agent/console.token` | the POST token the console mints and the MCP server and CLI read | | `TRADERS_AGENT_WORKDIR` | `~/Projects/luxalgo-web` if it exists, else `console/agents` | the folder the in-app study bridge runs the agent CLI in (never taken from a request) | | `TRADERS_AGENT_ALLOW_LAN` | unset | with `--host 0.0.0.0`, let peers that reach the console **from their own address** receive the POST token; without it they get a read-only console. It does **not** govern a caller arriving through a local reverse proxy — see the row below | +| `TRADERS_AGENT_INSTANCE` | unset | runs a separate desk: its own token, paper account, chart and study files under `~/.local/state/traders-agent/instances/NAME/`, its own Edge Stats engine (the console's port + 2), and no Hermes study chat unless `HERMES_CLI` is set. Unset is the Hermes desk. The dsh adapter uses `dsh` | | `TRADERS_AGENT_ALLOWED_HOSTS` | unset | comma-separated extra `Host` names this console answers to, for a local reverse proxy that forwards the public name (`tailscale serve` does). **Every name you add here is a full-trust door:** the proxy terminates on this machine, so the caller arrives on loopback, is handed the POST token and can write — approve paper orders, drive the chart, run Pine — with `ALLOW_LAN` unset. Only add names that resolve to this machine inside an access-controlled network, and read it as “everyone on that tailnet is me”. Any other name is still refused | | `TRADER_PAPER_FILE` | `~/.local/state/traders-agent/paper.json` | the paper account (use another path for a second test console) | | `LUXALGO_AGENTS_DIR` | `console/agents` | runtime state: chart bridge files, study threads, shots | diff --git a/adapters/dsh/install-dsh.sh b/adapters/dsh/install-dsh.sh index 1dc8a3d..fe627a8 100755 --- a/adapters/dsh/install-dsh.sh +++ b/adapters/dsh/install-dsh.sh @@ -5,15 +5,21 @@ # ./adapters/dsh/install-dsh.sh --mcp-file PATH also merge the entry into that JSON file ({"mcpServers": {...}}); a backup is kept # ./adapters/dsh/install-dsh.sh --skills-dir DIR skill folder (default $DSH_SKILLS_DIR, else ~/.agents/skills) # ./adapters/dsh/install-dsh.sh --venv always use a private venv with fastmcp (default: PY, .venv or a python with `mcp`, else uvx) -# ./adapters/dsh/install-dsh.sh --doctor check skill, launcher, a real MCP handshake and the console -# ./adapters/dsh/install-dsh.sh --uninstall remove the skill (and the entry from --mcp-file) +# ./adapters/dsh/install-dsh.sh --console run dsh's own console in the foreground (Ctrl-C stops it) +# ./adapters/dsh/install-dsh.sh --service install dsh's own console as a login service (systemd / launchd) +# ./adapters/dsh/install-dsh.sh --doctor check skill, launcher, a real MCP handshake and dsh's console +# ./adapters/dsh/install-dsh.sh --uninstall remove the skill, dsh's console service (and the entry from --mcp-file) +# ./adapters/dsh/install-dsh.sh --shared use the Hermes desk's console (8787) instead of dsh's own # ./adapters/dsh/install-dsh.sh --help this text -# PORT=9000 ./adapters/dsh/install-dsh.sh the console is not on 8787 (written into the MCP entry as LUXALGO_CONSOLE) +# PORT=9000 ./adapters/dsh/install-dsh.sh dsh's console on another port (default 8788) # -# What dsh gets: the `trader-desk` skill and the 56-tool `traders-chart` MCP server. What it does not -# get: the Hermes sidebar pane (plugin/plugin.js is Hermes Desktop only). In dsh, open the console in a -# browser tab at http://127.0.0.1:$PORT/ and the agent drives that same chart through the tools. -# The console itself must be running: ./console/start.sh +# What dsh gets: the `trader-desk` skill and the 56-tool `traders-chart` MCP server, talking to a desk +# of its OWN — a separate console on 127.0.0.1:8788 (TRADERS_AGENT_INSTANCE=dsh, see +# console/backend/instance.py): its own chart, paper account, write token, studies and saved scripts, +# its own Edge Stats engine, and no Hermes study chat. Nothing the dsh agent does reaches the Hermes +# desk on 8787, and the reverse. Market data (tick store, candle caches) stays shared on purpose. +# What dsh does not get: the Hermes sidebar pane (traders-desk/desktop/plugin.js is Hermes Desktop +# only) — open http://127.0.0.1:8788/ in a browser tab and the dsh agent drives that chart. # # dsh's config locations are not read from dsh itself, so nothing is written outside --skills-dir and # --mcp-file. If your dsh keeps MCP servers elsewhere, use the printed entry as-is. @@ -25,27 +31,48 @@ REPO="$(cd "$HERE/../.." && pwd)" SERVER="$REPO/console/mcp/server.py" SKILL_SRC="$REPO/skills/trader-desk/SKILL.md" SKILLS_DIR="${DSH_SKILLS_DIR:-$HOME/.agents/skills}" -PORT="${PORT:-8787}" -CONSOLE_URL="${LUXALGO_CONSOLE:-http://127.0.0.1:$PORT}" +INSTANCE="${DSH_INSTANCE:-dsh}" # the desk name; --shared clears it VENV="${TRADERS_MCP_VENV:-$HOME/.local/share/traders-agent/mcp-venv}" NAME="traders-chart" usage() { awk 'NR>1 && /^set -euo/{exit} NR>1{sub(/^# ?/,""); print}' "$0"; } -DOCTOR=0 UNINSTALL=0 USE_VENV=0 MCP_FILE="" +DOCTOR=0 UNINSTALL=0 USE_VENV=0 MCP_FILE="" SHARED=0 RUN_CONSOLE=0 SERVICE=0 while [[ $# -gt 0 ]]; do case "$1" in -h|--help) usage; exit 0 ;; --doctor) DOCTOR=1 ;; --uninstall) UNINSTALL=1 ;; --venv) USE_VENV=1 ;; + --shared) SHARED=1 ;; + --console) RUN_CONSOLE=1 ;; + --service) SERVICE=1 ;; --skills-dir) [[ $# -ge 2 ]] || { echo "install-dsh: --skills-dir needs a folder" >&2; exit 2; }; SKILLS_DIR="$2"; shift ;; --mcp-file) [[ $# -ge 2 ]] || { echo "install-dsh: --mcp-file needs a path" >&2; exit 2; }; MCP_FILE="$2"; shift ;; *) echo "install-dsh: unknown option '$1'" >&2; usage >&2; exit 2 ;; esac shift done +if [[ $SHARED -eq 1 ]]; then + INSTANCE=""; PORT="${PORT:-8787}" + [[ $RUN_CONSOLE -eq 0 && $SERVICE -eq 0 ]] || { echo "install-dsh: --shared uses the Hermes desk's console; start that one with ./console/start.sh or ./install.sh --service" >&2; exit 2; } +else + PORT="${PORT:-8788}" + [[ "$INSTANCE" =~ ^[a-z0-9][a-z0-9-]{0,31}$ ]] || { echo "install-dsh: DSH_INSTANCE must be 1-32 lowercase letters, digits or dashes, got '$INSTANCE'" >&2; exit 2; } +fi [[ "$PORT" =~ ^[0-9]{1,5}$ ]] || { echo "install-dsh: PORT must be a number, got '$PORT'" >&2; exit 2; } +CONSOLE_URL="${LUXALGO_CONSOLE:-http://127.0.0.1:$PORT}" +WANT_DESK="${INSTANCE:-default}" +if [[ "$(uname -s)" == "Darwin" ]]; then SERVICE_SH="$REPO/console/service-macos.sh"; else SERVICE_SH="$REPO/console/service-linux.sh"; fi + +# dsh's own console: the same server, a desk of its own (instance.py) on its own port. +if [[ $RUN_CONSOLE -eq 1 ]]; then + echo "dsh's console (desk '$INSTANCE') -> http://127.0.0.1:$PORT/ (Ctrl-C stops it)" + exec env TRADERS_AGENT_INSTANCE="$INSTANCE" PORT="$PORT" bash "$REPO/console/start.sh" +fi +if [[ $SERVICE -eq 1 ]]; then + exec env TRADERS_AGENT_INSTANCE="$INSTANCE" PORT="$PORT" bash "$SERVICE_SH" install --port "$PORT" +fi SKILL_DST="$SKILLS_DIR/trader-desk" # PYTHONPATH/PYTHONHOME are scrubbed for the probe: an agent session can export one that shadows the probe's own packages. @@ -136,7 +163,13 @@ PY if [[ $UNINSTALL -eq 1 ]]; then rm -rf "$SKILL_DST"; echo "removed $SKILL_DST" if [[ -n "$MCP_FILE" ]]; then remove_entry "$MCP_FILE"; fi - echo "still yours: the MCP entry if you added it by hand, $VENV, ~/.local/state/traders-agent/" + # Only dsh's own service: the Hermes desk's console is never touched from here. + if [[ -n "$INSTANCE" ]]; then + env TRADERS_AGENT_INSTANCE="$INSTANCE" bash "$SERVICE_SH" uninstall 2>/dev/null || true + echo "still yours: the MCP entry if you added it by hand, $VENV, dsh's desk state in ~/.local/state/traders-agent/instances/$INSTANCE/" + else + echo "still yours: the MCP entry if you added it by hand, $VENV" + fi exit 0 fi @@ -174,7 +207,16 @@ PY ''|*[!0-9]*) if [[ "$n" == "noclient" ]]; then echo " -- python 'mcp' client not installed here; handshake skipped"; else bad "MCP handshake failed: run the launcher by hand to see the error"; fi ;; *) ok "MCP handshake: $n tools" ;; esac - if curl -fsS --max-time 3 "$CONSOLE_URL/api/health" >/dev/null 2>&1; then ok "console answering on $CONSOLE_URL"; else bad "console not answering on $CONSOLE_URL (./console/start.sh)"; fi + # Answering is not enough: it must be THIS desk, or the dsh agent would be driving another host's chart. + health="$(curl -fsS --max-time 3 "$CONSOLE_URL/api/health" 2>/dev/null || true)" + if [[ -z "$health" ]]; then + if [[ -n "$INSTANCE" ]]; then bad "dsh's console not answering on $CONSOLE_URL (./adapters/dsh/install-dsh.sh --console, or --service)" + else bad "console not answering on $CONSOLE_URL (./console/start.sh)"; fi + else + desk="$(printf '%s' "$health" | python3 -c 'import json,sys; print((json.load(sys.stdin).get("data") or {}).get("instance") or "default")' 2>/dev/null || echo "?")" + if [[ "$desk" == "$WANT_DESK" ]]; then ok "console answering on $CONSOLE_URL (desk: $desk)" + else bad "the console on $CONSOLE_URL is the '$desk' desk, not '$WANT_DESK' — another host's chart; start dsh's own with --console"; fi + fi [[ $fail -eq 0 ]] && { echo "all checks passed"; exit 0; } || { echo "one or more checks failed"; exit 1; } fi @@ -189,11 +231,23 @@ if [[ -n "$MCP_FILE" ]]; then else echo; echo "Add this to your dsh MCP servers (or re-run with --mcp-file PATH):"; entry_json print fi +if [[ -n "$INSTANCE" ]]; then cat < dict: def home() -> Path: - return Path(os.environ.get("TRADERS_EDGE_HOME") - or Path.home() / ".local" / "share" / "traders-agent" / "edge") + # per desk (instance.py): two consoles must not share one engine's workspace + return Path(os.environ.get("TRADERS_EDGE_HOME") or instance.share_dir() / "edge") def engine_dir() -> Path: diff --git a/console/backend/instance.py b/console/backend/instance.py new file mode 100644 index 0000000..fce19a2 --- /dev/null +++ b/console/backend/instance.py @@ -0,0 +1,64 @@ +"""Which desk this console is — so two agent hosts on one machine never share one. + +Unset (or `default`), the console is the desk Hermes has always had: state under +~/.local/state/traders-agent, chart files in console/agents, the in-app study chat through the Hermes +CLI, the Edge Stats engine on 8789. `TRADERS_AGENT_INSTANCE=` (lowercase letters, digits, +dashes) gives a console a desk of its own — 30 Oct, the operator: a desk opened in the DeepSeek +Harness "should stay in DeepSeek Harness only, not linked or connected": + +* its token, paper account and chart/study files under ~/.local/state/traders-agent/instances// +* its Edge Stats workspace under ~/.local/share/traders-agent/instances//edge, and its engine on + the console's port + 2 (8788 -> 8790), so two consoles never fight over one sidecar; +* no Hermes study chat unless HERMES_CLI names a CLI on purpose. + +The browser keeps layout, theme and saved scripts per origin, and a named desk runs on its own port, +so those are separate too. Market data and installed tools stay shared on purpose — the tick store, +candle caches, downloaded data, thumbnails and the prop-firm simulator describe the market, not a +desk. Every explicit path variable (TRADER_PAPER_FILE, LUXALGO_AGENTS_DIR, ...) still wins. +""" + +from __future__ import annotations + +import os +import re +from pathlib import Path + +ENV = "TRADERS_AGENT_INSTANCE" +_NAME = re.compile(r"[a-z0-9][a-z0-9-]{0,31}") +DEFAULT_EDGE_PORT = 8789 + + +class InstanceError(ValueError): + """The instance name cannot be used as a folder name.""" + + +def name() -> str: + """'' for the default desk, else the validated instance name.""" + raw = (os.environ.get(ENV) or "").strip() + if raw in ("", "default"): + return "" + if not _NAME.fullmatch(raw): + raise InstanceError(f"{ENV}={raw!r} is not a desk name: use 1-32 lowercase letters, digits or dashes " + "(not starting with a dash), e.g. dsh") + return raw + + +def label() -> str: + return name() or "default" + + +def state_dir() -> Path: + """Token, paper account, pid and log — per desk.""" + base = Path.home() / ".local" / "state" / "traders-agent" + return base / "instances" / name() if name() else base + + +def share_dir() -> Path: + """Per-desk data that is NOT market data (the Edge Stats workspace).""" + base = Path.home() / ".local" / "share" / "traders-agent" + return base / "instances" / name() if name() else base + + +def edge_port(console_port: int) -> int: + """The Edge Stats engine: 8789 for the default desk, the console's port + 2 for a named one.""" + return console_port + 2 if name() else DEFAULT_EDGE_PORT diff --git a/console/backend/server.py b/console/backend/server.py index be547d6..ba31c3f 100755 --- a/console/backend/server.py +++ b/console/backend/server.py @@ -52,6 +52,17 @@ from pathlib import Path from urllib.parse import parse_qs, unquote, urlparse +import instance + +# Which desk this is (instance.py): unset is the Hermes desk as it always was; a named desk keeps its +# token, paper account, chart and study files apart and does not call Hermes. A bad name stops here, +# before any module below (edgestats registers an exit hook) reads a path from it. +try: + instance.name() +except instance.InstanceError as _exc: + sys.stderr.write(f"server.py: {_exc}\n") + raise SystemExit(2) from None + import library_thumbs # -------------------------------------------------------------------------- @@ -103,9 +114,10 @@ def _repo_version() -> str: AGENTS_ROOT = os.path.abspath(os.environ.get( "LUXALGO_AGENTS_DIR", - os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "agents"))) -CHAT_CLI = os.environ.get("HERMES_CLI") or os.path.expanduser( - "~/.hermes/hermes-agent/venv/bin/hermes") + str(instance.state_dir() / "agents") if instance.name() + else os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "agents"))) +CHAT_CLI = os.environ.get("HERMES_CLI") or ("" if instance.name() else os.path.expanduser( + "~/.hermes/hermes-agent/venv/bin/hermes")) DEFAULT_PORT = 8787 DEFAULT_HOST = "127.0.0.1" DEFAULT_FRONTEND = "../frontend" @@ -648,6 +660,7 @@ def ep_health(params: dict) -> dict: data = { "status": "ok" if BRIDGE.connected else "degraded", "version": SERVER_VERSION, + "instance": instance.label(), "mcp": BRIDGE.stats(), "cache": CACHE.stats(), "endpoints": sorted(ROUTES.keys()), @@ -1655,8 +1668,7 @@ def get_broker() -> PaperBroker: global _BROKER with _BROKER_LOCK: if _BROKER is None: - path = os.environ.get("TRADER_PAPER_FILE") or str( - Path(os.path.expanduser("~")) / ".local/state/traders-agent/paper.json") + path = os.environ.get("TRADER_PAPER_FILE") or str(instance.state_dir() / "paper.json") _BROKER = PaperBroker(path, broker_price) return _BROKER @@ -2044,7 +2056,7 @@ def cors_origin(origin: str | None, host: str | None) -> str | None: # The token lives beside the runtime state at mode 0600; delete the file to mint a new one. TOKEN_PATH = Path(os.environ.get( "TRADER_CONSOLE_TOKEN_FILE", - str(Path(os.path.expanduser("~")) / ".local/state/traders-agent/console.token"), + str(instance.state_dir() / "console.token"), )) @@ -2435,6 +2447,11 @@ def _chat(self, payload: dict): detail={"available": ids}) return agent = load_study(AGENTS_ROOT, agent_id) + if not CHAT_CLI: + self._fail(f"the study chat is off on the '{instance.label()}' desk: it would run through the Hermes CLI, " + "and this desk is kept apart from Hermes. Talk to this desk's agent through its MCP tools, " + "or set HERMES_CLI to a CLI on purpose.", HTTPStatus.SERVICE_UNAVAILABLE, "chat_unavailable") + return # `fresh` starts the study over: the CLI is called WITHOUT --resume, and the new session id # replaces the stored one (the reply path below already persists a changed session). @@ -2861,6 +2878,8 @@ def _agent_workdir() -> str: env = os.environ.get("TRADERS_AGENT_WORKDIR") if env: return env + if instance.name(): + return str(AGENTS_ROOT) legacy = os.path.expanduser("~/Projects/luxalgo-web") return legacy if os.path.isdir(legacy) else str(AGENTS_ROOT) @@ -2875,6 +2894,9 @@ def _env_int(name: str, default: int) -> int: def main(argv=None) -> int: args = build_parser().parse_args(argv) + # A named desk runs its own Edge Stats engine beside its own console (port + 2), never the default's. + if instance.name(): + os.environ.setdefault("TRADERS_EDGE_PORT", str(instance.edge_port(args.port))) frontend_root = os.path.abspath( args.frontend if os.path.isabs(args.frontend) else os.path.join(os.getcwd(), args.frontend) @@ -2898,7 +2920,7 @@ def main(argv=None) -> int: except (OSError, OverflowError) as exc: log(f"cannot listen on {args.host}:{args.port}: {exc}") return 2 - log(f"listening on http://{args.host}:{args.port} (Ctrl-C to stop)") + log(f"listening on http://{args.host}:{args.port} (Ctrl-C to stop) · desk: {instance.label()}") if args.no_mcp: log("starting WITHOUT an MCP session (--no-mcp)") diff --git a/console/backend/tests/test_agents_guide.py b/console/backend/tests/test_agents_guide.py new file mode 100644 index 0000000..75cf347 --- /dev/null +++ b/console/backend/tests/test_agents_guide.py @@ -0,0 +1,87 @@ +"""AGENTS.md — the install guide an AI agent follows when its user hands it this repository's link. + +An agent follows it literally, so every flag it runs must exist and every message it is told to look +for must be one the scripts really print. These tests read the guide and the scripts side by side, so +a renamed flag or a reworded message fails here instead of stranding an agent mid-install. +""" + +import re +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[3] +GUIDE = (ROOT / "AGENTS.md").read_text(encoding="utf-8") +README = (ROOT / "README.md").read_text(encoding="utf-8") +INSTALL = (ROOT / "install.sh").read_text(encoding="utf-8") +DSH = (ROOT / "adapters" / "dsh" / "install-dsh.sh").read_text(encoding="utf-8") +SOURCES = "\n".join(p.read_text(encoding="utf-8") for p in [ + ROOT / "install.sh", ROOT / "adapters/dsh/install-dsh.sh", ROOT / "bin/register-mcp.sh", + ROOT / "bin/setup-python.sh", ROOT / "console/service-linux.sh", ROOT / "console/service-macos.sh", + ROOT / "console/backend/server.py"]) + + +def flags(script: str) -> set: + """The options a script's case statement accepts.""" + return set(re.findall(r"^\s+(--[a-z][a-z-]*)\)", script, re.M)) | set(re.findall(r"\|(--[a-z][a-z-]*)\)", script)) + + +class TheGuideIsFoundFirst(unittest.TestCase): + def test_the_readme_points_agents_at_it_near_the_top(self): + head = "\n".join(README.splitlines()[:30]) + self.assertIn("If you are an AI agent", head) + self.assertIn("(AGENTS.md)", head) + + def test_the_guide_says_who_it_is_for(self): + self.assertIn("If you are an AI agent", GUIDE.splitlines()[2]) + + +class EveryCommandExists(unittest.TestCase): + def test_install_sh_flags(self): + used = set(re.findall(r"\./install\.sh ((?:--[a-z-]+ ?)+)", GUIDE)) + used = {f for group in used for f in group.split()} + self.assertTrue(used, "the guide runs install.sh") + self.assertLessEqual(used, flags(INSTALL), used - flags(INSTALL)) + + def test_install_dsh_flags(self): + used = {f for group in re.findall(r"install-dsh\.sh((?: --[a-z-]+(?: /\S+)?)+)", GUIDE) + for f in re.findall(r"--[a-z-]+", group)} + self.assertTrue(used) + self.assertLessEqual(used, flags(DSH), used - flags(DSH)) + + def test_the_scripts_it_names_are_in_the_repo(self): + for rel in ("bin/setup-python.sh", "console/service-linux.sh", "console/service-macos.sh", + "adapters/dsh/install-dsh.sh", "install.sh"): + self.assertIn(rel.split("/")[-1], GUIDE) + self.assertTrue((ROOT / rel).is_file(), rel) + + +class EveryMessageItWaitsForIsReal(unittest.TestCase): + def test_success_and_trouble_lines_are_printed_by_the_scripts(self): + for msg in ("Done in", "The console is", "register-mcp.sh: no 'hermes' on PATH", + "note: no systemd user session here", "dsh gets a desk of its own", + "all checks passed", "no python with the 'mcp' client found", + "no uv and no python 3.11+ on PATH", "cannot listen on", "desk, not '", + "Reload desktop plugins"): + self.assertIn(msg, GUIDE, f"the guide no longer mentions {msg!r}") + self.assertIn(msg, SOURCES, f"the guide waits for {msg!r}, which no script prints") + + +class ItIsSafeToFollowLiterally(unittest.TestCase): + def test_no_sudo_in_any_command(self): + blocks = re.findall(r"```bash\n(.*?)```", GUIDE, re.S) + self.assertTrue(blocks) + for b in blocks: + self.assertNotRegex(b, r"\bsudo\b") + + def test_it_asks_the_agent_to_tell_the_user_first_and_stop_on_failure(self): + self.assertIn("Tell your user what you are about to do", GUIDE) + self.assertIn("If a step fails, stop", GUIDE) + + def test_optional_extras_are_opt_in(self): + self.assertIn("unless the user asks", GUIDE) + for block in re.findall(r"```bash\n(.*?)```", GUIDE, re.S): + self.assertNotIn("--with-", block, "the guide must not install the large extras by default") + + +if __name__ == "__main__": + unittest.main() diff --git a/console/backend/tests/test_dsh_adapter.py b/console/backend/tests/test_dsh_adapter.py index 522b9d5..181f133 100644 --- a/console/backend/tests/test_dsh_adapter.py +++ b/console/backend/tests/test_dsh_adapter.py @@ -1,12 +1,21 @@ -"""adapters/dsh/install-dsh.sh: skill copy, MCP entry merge (other servers kept, backup made), uninstall, bad JSON refused.""" +"""adapters/dsh/install-dsh.sh: skill copy, MCP entry merge (other servers kept, backup made), uninstall, bad JSON refused. + +30 Oct: dsh gets a desk of its OWN by default (TRADERS_AGENT_INSTANCE=dsh on port 8788), so nothing the +dsh agent does reaches the Hermes desk on 8787 — `--shared` is the explicit way back to one desk. +""" import json import os +import socket import subprocess +import sys import tempfile +import time import unittest +import urllib.request from pathlib import Path SCRIPT = Path(__file__).resolve().parents[3] / "adapters" / "dsh" / "install-dsh.sh" +BACKEND = Path(__file__).resolve().parents[1] _STUB = tempfile.mkdtemp() @@ -17,8 +26,9 @@ def run(*args, **env): # A stub uvx on PATH: the installer picks it and never tries to build a venv (no network in tests). - e = {k: v for k, v in os.environ.items() if k not in ("LUXALGO_CONSOLE", "PY", "PORT")} # other tests set these - e.update(TRADERS_MCP_VENV="/nonexistent/venv", PATH=_STUB + os.pathsep + e["PATH"], **env) + e = {k: v for k, v in os.environ.items() + if k not in ("LUXALGO_CONSOLE", "PY", "PORT", "TRADERS_AGENT_INSTANCE", "DSH_INSTANCE")} # other tests set these + e.update(TRADERS_MCP_VENV="/nonexistent/venv", PATH=_STUB + os.pathsep + e["PATH"], HOME=_STUB, **env) return subprocess.run(["bash", str(SCRIPT), *args], capture_output=True, text=True, env=e, timeout=60) @@ -68,6 +78,85 @@ def test_invalid_json_is_not_overwritten(self): def test_bad_port_refused(self): self.assertEqual(run("--skills-dir", str(self.t / "s"), PORT="abc").returncode, 2) + def entry(self, *args, **env): + cfg = self.t / "e.json" + r = run("--skills-dir", str(self.t / "skills"), "--mcp-file", str(cfg), *args, **env) + self.assertEqual(r.returncode, 0, r.stderr) + return json.loads(cfg.read_text())["mcpServers"]["traders-chart"], r.stdout + + def test_dsh_gets_its_own_desk_by_default(self): + e, out = self.entry() + self.assertEqual(e["env"]["LUXALGO_CONSOLE"], "http://127.0.0.1:8788", + "the dsh agent must talk to dsh's console, not the Hermes one on 8787") + self.assertIn("desk of its own", out) + self.assertIn("--console", out) + + def test_shared_is_the_explicit_way_back_to_the_hermes_console(self): + e, out = self.entry("--shared") + self.assertEqual(e["env"]["LUXALGO_CONSOLE"], "http://127.0.0.1:8787") + self.assertIn("same chart and paper account", out) + + def test_shared_cannot_start_or_install_a_console(self): + self.assertEqual(run("--shared", "--console").returncode, 2) + self.assertEqual(run("--shared", "--service").returncode, 2) + + def test_a_bad_desk_name_is_refused(self): + self.assertEqual(run("--skills-dir", str(self.t / "s"), DSH_INSTANCE="../hermes").returncode, 2) + + def test_console_and_service_start_dshs_own_desk(self): + src = SCRIPT.read_text() + self.assertIn('exec env TRADERS_AGENT_INSTANCE="$INSTANCE" PORT="$PORT" bash "$REPO/console/start.sh"', src) + self.assertIn('exec env TRADERS_AGENT_INSTANCE="$INSTANCE" PORT="$PORT" bash "$SERVICE_SH" install', src) + + def test_uninstall_only_touches_dshs_own_service(self): + src = SCRIPT.read_text() + self.assertIn('env TRADERS_AGENT_INSTANCE="$INSTANCE" bash "$SERVICE_SH" uninstall', src) + self.assertIn('if [[ -n "$INSTANCE" ]]; then\n env TRADERS_AGENT_INSTANCE', src) + + +def _free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class TheDoctorKnowsWhichDeskItFound(unittest.TestCase): + """Answering is not enough: a console on dsh's port that is the HERMES desk would mean the dsh + agent drives the Hermes chart. The doctor reads /api/health's `instance` and says so.""" + + def console(self, home, instance): + port = _free_port() + env = {k: v for k, v in os.environ.items() if k not in ("PYTHONPATH", "PYTHONHOME", "TRADERS_AGENT_INSTANCE")} + env.update(HOME=home, LUXALGO_AGENTS_DIR=os.path.join(home, "agents-" + (instance or "default"))) + if instance: + env["TRADERS_AGENT_INSTANCE"] = instance + p = subprocess.Popen([sys.executable, str(BACKEND / "server.py"), "--port", str(port), "--no-mcp", + "--frontend", str(BACKEND.parent / "frontend")], cwd=str(BACKEND), env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + self.addCleanup(lambda: (p.terminate(), p.wait(10))) + for _ in range(100): + try: + urllib.request.urlopen(f"http://127.0.0.1:{port}/api/health", timeout=1).read() + return port + except OSError: + time.sleep(0.1) + self.fail("console did not start") + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def test_the_hermes_desk_on_dshs_port_is_a_failure(self): + port = self.console(self.tmp.name, None) + r = run("--doctor", PORT=str(port)) + self.assertIn("is the 'default' desk, not 'dsh'", r.stdout) + self.assertEqual(r.returncode, 1) + + def test_dshs_own_desk_passes_that_check(self): + port = self.console(self.tmp.name, "dsh") + r = run("--doctor", PORT=str(port)) + self.assertIn("(desk: dsh)", r.stdout) + if __name__ == "__main__": unittest.main() diff --git a/console/backend/tests/test_fast_install.py b/console/backend/tests/test_fast_install.py index 5d9ba03..c0a8671 100644 --- a/console/backend/tests/test_fast_install.py +++ b/console/backend/tests/test_fast_install.py @@ -104,6 +104,23 @@ def test_unit_text(self): 'ExecStart=/bin/bash "%s"' % (ROOT / "console" / "start.sh")): self.assertIn(needle, r.stdout) + def test_a_named_desk_gets_its_own_unit_and_state(self): + # 30 Oct: dsh's console runs beside the Hermes one, never replacing its unit or its pid file + r = subprocess.run(["bash", str(SERVICE), "print", "--port", "8788", "--instance", "dsh"], + capture_output=True, text=True, timeout=30) + self.assertEqual(r.returncode, 0, r.stderr) + self.assertIn('Environment="TRADERS_AGENT_INSTANCE=dsh"', r.stdout) + st = subprocess.run(["bash", str(SERVICE), "status", "--port", "1", "--instance", "dsh"], + capture_output=True, text=True, timeout=30) + self.assertIn("traders-agent-dsh.service", st.stdout) + self.assertIn("instances/dsh/console.log", st.stdout) + bad = subprocess.run(["bash", str(SERVICE), "print", "--instance", "../x"], capture_output=True, text=True) + self.assertEqual(bad.returncode, 2) + + def test_the_default_unit_is_unchanged(self): + st = subprocess.run(["bash", str(SERVICE), "status", "--port", "1"], capture_output=True, text=True, timeout=30) + self.assertIn("journalctl --user -u traders-agent.service", st.stdout) + def test_bad_port_and_unknown_command(self): self.assertEqual(subprocess.run(["bash", str(SERVICE), "print", "--port", "abc"], capture_output=True, text=True).returncode, 2) self.assertEqual(subprocess.run(["bash", str(SERVICE), "frobnicate"], capture_output=True, text=True).returncode, 2) @@ -115,6 +132,24 @@ def test_detached_start_does_not_hold_the_callers_pipe(self): self.assertIn('echo $! > "$PIDFILE"', src) +class TheDoctorChecksTheInterpreterTheInstallUsed(unittest.TestCase): + """30 Oct, a fresh-home run of `./install.sh --all` then `--doctor`: the install started the console with the + python that HAS the mcp client (3.11), the doctor checked the first 3.11+ on PATH (a 3.14 without it) and + reported FAIL on a working install — the first thing an agent following AGENTS.md would chase.""" + + @unittest.skipIf((ROOT / ".venv").exists(), "a repo .venv wins over PATH; this pins the PATH order") + def test_a_python_with_mcp_beats_a_newer_one_without(self): + with tempfile.TemporaryDirectory() as d: + stub = Path(d) + (stub / "python3.14").write_text('#!/bin/sh\ncase "$*" in *"import mcp"*) exit 1;; esac\nexit 0\n') + (stub / "python3.11").write_text("#!/bin/sh\nexit 0\n") + for f in stub.iterdir(): + f.chmod(0o755) + env = {"HOME": d, "PATH": f"{stub}:/usr/bin:/bin", "TERM": "dumb", "PORT": "1"} + r = subprocess.run(["bash", str(INSTALL), "--doctor"], capture_output=True, text=True, env=env, timeout=60) + self.assertIn(f"console python: {stub}/python3.11", r.stdout, r.stdout) + + class InstallAllFlag(unittest.TestCase): def test_help_lists_the_one_command_install(self): r = subprocess.run(["bash", str(INSTALL), "--help"], capture_output=True, text=True, timeout=30) diff --git a/console/backend/tests/test_instances.py b/console/backend/tests/test_instances.py new file mode 100644 index 0000000..c54d6b0 --- /dev/null +++ b/console/backend/tests/test_instances.py @@ -0,0 +1,228 @@ +"""One machine, two agent hosts, two desks that never touch. + +30 Oct, the operator: "if this plugin opened in DeepSeek Harness, it should stay in DeepSeek Harness +only — not linked or connected" to the Hermes one. Before this, the dsh adapter pointed its MCP +server at the SAME console as Hermes (127.0.0.1:8787): one chart, one paper account, one token, one +set of studies, and the in-app study chat shelled out to Hermes. `TRADERS_AGENT_INSTANCE=` +gives a console its own state; the default (unset) is exactly what Hermes has always had. + +Shared on purpose: market data and installed tools (tick store, candle caches, downloaded data, +thumbnails, the prop-firm simulator) — they describe the market, not a desk. +""" + +import json +import os +import socket +import subprocess +import sys +import tempfile +import time +import unittest +import urllib.request +from pathlib import Path + +BACKEND = Path(__file__).resolve().parents[1] + + +def probe(code: str, home: str, **env) -> dict: + """Import the console in a fresh interpreter (paths are resolved at import) and print JSON.""" + e = {k: v for k, v in os.environ.items() + if k not in ("PYTHONPATH", "PYTHONHOME", "TRADERS_AGENT_INSTANCE", "LUXALGO_AGENTS_DIR", + "TRADER_PAPER_FILE", "TRADER_CONSOLE_TOKEN_FILE", "HERMES_CLI", + "TRADERS_EDGE_HOME", "TRADERS_EDGE_PORT", "TRADERS_AGENT_WORKDIR")} + e["HOME"] = home + e.update(env) + done = subprocess.run([sys.executable, "-c", f"import sys, json; sys.path.insert(0, r'{BACKEND}'); {code}"], + capture_output=True, text=True, env=e, timeout=60) + if done.returncode != 0: + return {"_rc": done.returncode, "_err": done.stderr} + return json.loads(done.stdout.strip().splitlines()[-1]) + + +PATHS = ("import server, edgestats; b = server.get_broker(); " + "print(json.dumps({'agents': server.AGENTS_ROOT, 'token': str(server.TOKEN_PATH), " + "'paper': str(b.path), 'chat': server.CHAT_CLI, 'edge': str(edgestats.home()), " + "'workdir': server._agent_workdir(), 'instance': server.instance.label()}))") + + +class WhereADeskKeepsItsState(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.home = self.tmp.name + + def test_unset_is_the_desk_hermes_has_always_had(self): + p = probe(PATHS, self.home) + self.assertNotIn("_err", p, p.get("_err")) + state = Path(self.home) / ".local/state/traders-agent" + self.assertEqual(p["instance"], "default") + self.assertEqual(p["token"], str(state / "console.token")) + self.assertEqual(p["paper"], str(state / "paper.json")) + self.assertEqual(Path(p["agents"]), (BACKEND.parent / "agents").resolve()) + self.assertTrue(p["chat"].endswith("hermes"), "the default desk still talks to Hermes") + self.assertEqual(p["edge"], str(Path(self.home) / ".local/share/traders-agent/edge")) + + def test_a_named_desk_keeps_everything_of_its_own(self): + p = probe(PATHS, self.home, TRADERS_AGENT_INSTANCE="dsh") + self.assertNotIn("_err", p, p.get("_err")) + mine = Path(self.home) / ".local/state/traders-agent/instances/dsh" + self.assertEqual(p["instance"], "dsh") + self.assertEqual(p["token"], str(mine / "console.token")) + self.assertEqual(p["paper"], str(mine / "paper.json")) + self.assertEqual(p["agents"], str(mine / "agents")) + self.assertEqual(p["workdir"], str(mine / "agents")) + self.assertEqual(p["edge"], str(Path(self.home) / ".local/share/traders-agent/instances/dsh/edge")) + + def test_a_named_desk_does_not_call_hermes(self): + p = probe(PATHS, self.home, TRADERS_AGENT_INSTANCE="dsh") + self.assertEqual(p["chat"], "", "the dsh desk must not shell out to the Hermes CLI") + + def test_an_explicit_cli_or_path_still_wins(self): + p = probe(PATHS, self.home, TRADERS_AGENT_INSTANCE="dsh", HERMES_CLI="/opt/x/agent", + TRADER_PAPER_FILE=self.home + "/p.json") + self.assertEqual(p["chat"], "/opt/x/agent") + self.assertEqual(p["paper"], self.home + "/p.json") + + def test_a_bad_name_stops_the_console_with_a_sentence(self): + for bad in ("../hermes", "Has Space", "x" * 40, "-lead"): + p = probe(PATHS, self.home, TRADERS_AGENT_INSTANCE=bad) + self.assertIn("_rc", p, f"{bad!r} was accepted") + self.assertIn("TRADERS_AGENT_INSTANCE", p["_err"]) + self.assertNotIn("Traceback", p["_err"]) + + def test_default_is_a_spelling_of_unset(self): + self.assertEqual(probe(PATHS, self.home, TRADERS_AGENT_INSTANCE="default")["instance"], "default") + + def test_the_edge_engine_port_follows_the_console_port(self): + code = "import instance; print(json.dumps([instance.edge_port(8787), instance.edge_port(8788)]))" + self.assertEqual(probe(code, self.home), [8789, 8789]) + self.assertEqual(probe(code, self.home, TRADERS_AGENT_INSTANCE="dsh"), [8789, 8790]) + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +class TwoDesksOnOneMachine(unittest.TestCase): + """Two real consoles, as the operator runs them: Hermes's (unset) and dsh's. Nothing one desk + does may show up in the other.""" + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory() + cls.procs = [] + cls.ports = {} + for name in ("default", "dsh"): + port = free_port() + env = {k: v for k, v in os.environ.items() + if k not in ("PYTHONPATH", "PYTHONHOME", "TRADERS_AGENT_INSTANCE", "LUXALGO_AGENTS_DIR", + "TRADER_PAPER_FILE", "TRADER_CONSOLE_TOKEN_FILE")} + env["HOME"] = cls.tmp.name + if name != "default": + env["TRADERS_AGENT_INSTANCE"] = name + else: # keep the default desk's chart files out of the repo's own agents/ folder + env["LUXALGO_AGENTS_DIR"] = str(Path(cls.tmp.name) / "hermes-agents") + p = subprocess.Popen([sys.executable, str(BACKEND / "server.py"), "--port", str(port), "--no-mcp", + "--frontend", str(BACKEND.parent / "frontend")], + cwd=str(BACKEND), env=env, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE) + cls.procs.append(p) + cls.ports[name] = port + for name, port in cls.ports.items(): + for _ in range(100): + try: + cls.get(name, "/api/health") + break + except OSError: + time.sleep(0.1) + else: + raise RuntimeError(f"{name} console did not start") + + @classmethod + def tearDownClass(cls): + for p in cls.procs: + p.terminate() + p.wait(10) + if p.stderr: + p.stderr.close() + cls.tmp.cleanup() + + @classmethod + def get(cls, name, path): + with urllib.request.urlopen(f"http://127.0.0.1:{cls.ports[name]}{path}", timeout=5) as r: + return json.loads(r.read()) + + @classmethod + def post(cls, name, path, body, token): + req = urllib.request.Request(f"http://127.0.0.1:{cls.ports[name]}{path}", data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", "X-Trader-Token": token}) + with urllib.request.urlopen(req, timeout=10) as r: + return json.loads(r.read()) + + def token(self, name): + return self.get(name, "/api/session")["data"]["token"] + + def test_each_console_says_which_desk_it_is(self): + self.assertEqual(self.get("default", "/api/health")["data"]["instance"], "default") + self.assertEqual(self.get("dsh", "/api/health")["data"]["instance"], "dsh") + + def test_the_write_tokens_differ(self): + a, b = self.token("default"), self.token("dsh") + self.assertTrue(a and b) + self.assertNotEqual(a, b, "one token would let either agent write to the other's desk") + + def test_a_token_from_one_desk_is_refused_by_the_other(self): + req = urllib.request.Request(f"http://127.0.0.1:{self.ports['default']}/api/chart/command", + data=json.dumps({"action": "market", "symbol": "ETHUSDT"}).encode(), + headers={"Content-Type": "application/json", "X-Trader-Token": self.token("dsh")}) + with self.assertRaises(urllib.error.HTTPError) as ctx: + urllib.request.urlopen(req, timeout=5) + self.assertIn(ctx.exception.code, (401, 403)) + + def test_a_chart_command_to_dsh_never_reaches_the_hermes_chart(self): + sent = self.post("dsh", "/api/chart/command", {"action": "market", "symbol": "ETHUSDT", "wait": 0}, + self.token("dsh")) + self.assertTrue(sent.get("ok"), sent) + dsh_pending = self.get("dsh", "/api/chart/commands?since=0") + hermes_pending = self.get("default", "/api/chart/commands?since=0") + self.assertIn("ETHUSDT", json.dumps(dsh_pending)) + self.assertNotIn("ETHUSDT", json.dumps(hermes_pending)) + + def test_each_desk_wrote_its_own_token_file(self): + root = Path(self.tmp.name) / ".local/state/traders-agent" + a, b = self.token("default"), self.token("dsh") + self.assertEqual((root / "console.token").read_text().strip(), a) + self.assertEqual((root / "instances/dsh/console.token").read_text().strip(), b) + + def test_the_dsh_desk_refuses_the_hermes_study_chat(self): + sys.path.insert(0, str(BACKEND)) + import agents_store # noqa: PLC0415 + agents_store.upsert(str(Path(self.tmp.name) / ".local/state/traders-agent/instances/dsh/agents"), + {"id": "trend-study", "name": "Trend study", "instruction": "Read the trend."}) + req = urllib.request.Request(f"http://127.0.0.1:{self.ports['dsh']}/api/chat", + data=json.dumps({"agent_id": "trend-study", "message": "hi"}).encode(), + headers={"Content-Type": "application/json", "X-Trader-Token": self.token("dsh")}) + with self.assertRaises(urllib.error.HTTPError) as ctx: + urllib.request.urlopen(req, timeout=5) + self.assertEqual(ctx.exception.code, 503) + body = json.loads(ctx.exception.read()) + self.assertEqual(body.get("code") or (body.get("error") or {}).get("code"), "chat_unavailable", body) + +if __name__ == "__main__": + unittest.main() + + +class TheMacServiceIsPerDeskToo(unittest.TestCase): + """launchd cannot run here, so the source is pinned: a named desk gets its own label, plist and logs.""" + + src = (BACKEND.parent / "service-macos.sh").read_text() + + def test_label_and_state_follow_the_instance(self): + self.assertIn('LABEL="$LABEL.$INSTANCE"', self.src) + self.assertIn('STATE_DIR="$STATE_DIR/instances/$INSTANCE"', self.src) + self.assertLess(self.src.index('LABEL="$LABEL.$INSTANCE"'), self.src.index('PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"'), + "the plist path must be derived after the label") + + def test_the_plist_carries_the_instance(self): + self.assertIn("TRADERS_AGENT_INSTANCE", self.src) diff --git a/console/service-linux.sh b/console/service-linux.sh index cfa435f..42cb3ad 100755 --- a/console/service-linux.sh +++ b/console/service-linux.sh @@ -5,12 +5,14 @@ # ./console/service-linux.sh uninstall stop it and remove the unit (or stop the detached console) # ./console/service-linux.sh status unit state, is the console answering, where are the logs # ./console/service-linux.sh print print the unit file and change nothing +# ... --instance NAME a separate desk (TRADERS_AGENT_INSTANCE, see backend/instance.py): +# its own unit traders-agent-NAME.service, state, pid and log # # Unit: ~/.config/systemd/user/traders-agent.service (the same name the README documents). # Without a systemd user session (a container, WSL without systemd, an SSH-less box) it starts the # console detached instead (nohup, pid file in the state dir) and says plainly that this does NOT # survive a reboot. A console that is already answering and that this script did not start is left alone. -# Logs: ~/.local/state/traders-agent/console.log +# Logs: ~/.local/state/traders-agent/console.log (a named desk: .../traders-agent/instances/NAME/console.log) # # Bash 3.2 safe: no arrays, no mapfile. set -euo pipefail @@ -26,6 +28,7 @@ STATE_DIR="$HOME/.local/state/traders-agent" PIDFILE="$STATE_DIR/console.pid" LOG="$STATE_DIR/console.log" PORT="${PORT:-8787}" +INSTANCE="${TRADERS_AGENT_INSTANCE:-}" # Environment baked into the unit: a systemd user service gets a minimal PATH, but the console shells # out (`node` drives the Edge Stats sidecar, `hermes` starts the in-app study bridge). @@ -71,6 +74,7 @@ After=network-online.target [Service] Environment="PORT=$PORT" +Environment="TRADERS_AGENT_INSTANCE=$INSTANCE" Environment="PY=$(unit_escape "$1")" Environment="PATH=$(unit_escape "$SVC_PATH")" WorkingDirectory=$(unit_escape "$ROOT") @@ -128,7 +132,7 @@ cmd_install() { echo "note: no systemd user session here — starting the console detached (it will NOT survive a reboot)" # exec inside the subshell: the recorded pid is the console itself (not a wrapper), and nothing keeps # the caller's stdout open (a lingering wrapper made `./install.sh --all | tee log` hang until the console died). - ( cd "$ROOT" && exec env PORT="$PORT" PY="$PYR" PATH="$SVC_PATH:$PATH" nohup bash "$ROOT/console/start.sh" >>"$LOG" 2>&1 < /dev/null ) & + ( cd "$ROOT" && exec env PORT="$PORT" TRADERS_AGENT_INSTANCE="$INSTANCE" PY="$PYR" PATH="$SVC_PATH:$PATH" nohup bash "$ROOT/console/start.sh" >>"$LOG" 2>&1 < /dev/null ) & echo $! > "$PIDFILE" if wait_health; then echo "ok console running detached on port $PORT (pid $(cat "$PIDFILE"); logs: $LOG)" @@ -167,11 +171,22 @@ cmd="${1:-}"; [[ $# -gt 0 ]] && shift || true while [[ $# -gt 0 ]]; do case "$1" in --port) [[ $# -ge 2 ]] || { echo "service-linux.sh: --port needs a number" >&2; exit 2; }; PORT="$2"; shift ;; + --instance) [[ $# -ge 2 ]] || { echo "service-linux.sh: --instance needs a name" >&2; exit 2; }; INSTANCE="$2"; shift ;; *) echo "service-linux.sh: unknown option '$1'" >&2; exit 2 ;; esac shift done [[ "$PORT" =~ ^[0-9]{1,5}$ ]] || { echo "service-linux.sh: PORT must be a number, got '$PORT'" >&2; exit 2; } +# A named desk gets its own unit, state, pid and log, so it never stops or replaces the default one. +[[ "$INSTANCE" == "default" ]] && INSTANCE="" +if [[ -n "$INSTANCE" ]]; then + [[ "$INSTANCE" =~ ^[a-z0-9][a-z0-9-]{0,31}$ ]] || { echo "service-linux.sh: instance must be 1-32 lowercase letters, digits or dashes, got '$INSTANCE'" >&2; exit 2; } + UNIT_NAME="traders-agent-$INSTANCE.service" + UNIT="$UNIT_DIR/$UNIT_NAME" + STATE_DIR="$STATE_DIR/instances/$INSTANCE" + PIDFILE="$STATE_DIR/console.pid" + LOG="$STATE_DIR/console.log" +fi case "$cmd" in install) cmd_install ;; diff --git a/console/service-macos.sh b/console/service-macos.sh index 2f627fb..e0b8ea6 100755 --- a/console/service-macos.sh +++ b/console/service-macos.sh @@ -9,6 +9,9 @@ # (launchd KeepAlive ≈ systemd Restart=always). Label: com.traders-agent.console # Plist: ~/Library/LaunchAgents/com.traders-agent.console.plist # Logs: ~/.local/state/traders-agent/console.out.log / console.err.log +# +# TRADERS_AGENT_INSTANCE=NAME (backend/instance.py) runs a separate desk beside the default one: label +# com.traders-agent.console.NAME, its own plist and logs under ~/.local/state/traders-agent/instances/NAME/. set -euo pipefail [[ "$(uname -s)" == "Darwin" ]] || { echo "service-macos.sh: macOS only (Linux uses the systemd unit in the README)" >&2; exit 2; } @@ -16,9 +19,16 @@ set -euo pipefail HERE="$(cd "$(dirname "$0")" && pwd)" ROOT="$(cd "$HERE/.." && pwd)" LABEL="com.traders-agent.console" -PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" STATE_DIR="$HOME/.local/state/traders-agent" PORT="${PORT:-8787}" +INSTANCE="${TRADERS_AGENT_INSTANCE:-}" +[[ "$INSTANCE" == "default" ]] && INSTANCE="" +if [[ -n "$INSTANCE" ]]; then + [[ "$INSTANCE" =~ ^[a-z0-9][a-z0-9-]{0,31}$ ]] || { echo "service-macos.sh: TRADERS_AGENT_INSTANCE must be 1-32 lowercase letters, digits or dashes, got '$INSTANCE'" >&2; exit 2; } + LABEL="$LABEL.$INSTANCE" + STATE_DIR="$STATE_DIR/instances/$INSTANCE" +fi +PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" # launchd services get a minimal PATH, but the console shells out: `node` drives the Edge Stats # sidecar, and `hermes` is what the in-app study bridge starts. Bake the node directory (and the @@ -102,6 +112,8 @@ cmd_install() { PORT $PORT + TRADERS_AGENT_INSTANCE + $(xml_escape "$INSTANCE") PY $(xml_escape "$PY_RESOLVED") TRADERS_AGENT_ALLOWED_HOSTS diff --git a/install.sh b/install.sh index 8c671ca..5675a75 100755 --- a/install.sh +++ b/install.sh @@ -71,22 +71,26 @@ for arg in "$@"; do done if ! [[ "$PORT" =~ ^[0-9]{1,5}$ ]]; then echo "install.sh: PORT must be a number, got '$PORT'" >&2; exit 2; fi -# Resolve the console's interpreter the same way start.sh does: PY wins, then the repo's .venv, -# then the first python3.11+ on PATH. macOS ships python3 as 3.9, so checking the bare name -# "python3" would fail a healthy install there. +# Resolve the console's interpreter the way the service and bin/setup-python.sh do: PY wins, then the +# repo's .venv, then the first python3.11+ on PATH that HAS the mcp client, and only then the first +# 3.11+ without it (so the doctor can say what is missing). Checking a newer python without mcp +# while the service ran an older one with it made `--doctor` FAIL a working install (30 Oct). +# macOS ships python3 as 3.9, so checking the bare name "python3" would fail a healthy install there. resolve_py() { # Probes run with PYTHONPATH/PYTHONHOME scrubbed: an agent session can export a PYTHONPATH that # points at a DIFFERENT interpreter's site-packages, shadowing the probe's own packages (on # macOS this made a healthy venv report "no mcp"). PY= still wins. if [[ -n "${PY:-}" ]]; then echo "$PY"; return 0; fi if [[ -x "$HERE/.venv/bin/python" ]]; then echo "$HERE/.venv/bin/python"; return 0; fi - local cand + local cand first="" for cand in python3.14 python3.13 python3.12 python3.11 python3; do if command -v "$cand" >/dev/null 2>&1 \ && env -u PYTHONPATH -u PYTHONHOME "$cand" -c 'import sys; sys.exit(0 if sys.version_info >= (3, 11) else 1)' >/dev/null 2>&1; then - command -v "$cand"; return 0 + if env -u PYTHONPATH -u PYTHONHOME "$cand" -c 'import mcp' >/dev/null 2>&1; then command -v "$cand"; return 0; fi + [[ -n "$first" ]] || first="$(command -v "$cand")" fi done + [[ -n "$first" ]] && { echo "$first"; return 0; } return 1 } diff --git a/tools/sync-live.sh b/tools/sync-live.sh index c8015f8..f6fc582 100755 --- a/tools/sync-live.sh +++ b/tools/sync-live.sh @@ -39,7 +39,7 @@ done rm -rf "$LIVE/frontend/extra" mkdir -p "$LIVE/frontend/extra" cp -r "$HERE/console/frontend/extra/." "$LIVE/frontend/extra/" -cp "$HERE"/console/backend/{server.py,chart_bridge.py,chart_stream.py,agents_store.py,chat.py,backtest_service.py,library_thumbs.py,broker.py,edgestats.py,propfirmsim.py,fxdata.py,fxticks.py} \ +cp "$HERE"/console/backend/{server.py,chart_bridge.py,chart_stream.py,agents_store.py,chat.py,backtest_service.py,library_thumbs.py,broker.py,edgestats.py,propfirmsim.py,fxdata.py,fxticks.py,instance.py} \ "$LIVE/backend/" cp "$HERE"/console/bin/trader-chart "$LIVE/bin/trader-chart" # `trader-chart edge …` prints through the same renderer the MCP tools use. The live tree has no mcp/