Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions development/examples/share-local-model/SCRIPT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
# Share a local model: refused, then granted by name

A two-minute recording on one machine. Node A serves a model that runs on
its own loopback. Node B, another member of the mesh, asks for it and is
refused, because nothing is reachable by default. The operator grants that
one service by name, and the same request goes through. Two agents on node B
then find the model through node B's MCP server.

`record.sh` produces it with [VHS](https://github.com/charmbracelet/vhs). The
scenes below are what it types; the captions are in `captions.txt`.

## Before recording

```bash
make build # ./bin/agentmesh-one and ./bin/agentmesh-node
ollama pull gemma3:1b # Ollama listening on 127.0.0.1:11434
```

Tools: `vhs`, `ttyd`, `ffmpeg`, `tmux`, `jq`, `python3`, `curl`, and the
DejaVu Sans Mono font.

Scenes 9 and 10 use two agent CLIs, Antigravity CLI and OpenCode, configured
with node B's MCP server:

- URL: `http://127.0.0.1:8080/mcp`
- Header: `X-Mesh-Authentication: Bearer <token>`, where the token is the
content of `$WORK_DIR/api-token` (`record.sh` creates it on the first run)

Both commands must work in the recording's shells. If they are not on `PATH`
(for example Windows binaries called from WSL), put wrapper functions in a
file and pass it as `AGENTS_RC`. To record without them, set `AGENTS=0`; the
video then ends after step 8.

## Scenes

The panes: control plane (top left), node A (bottom left), node B (top right)
and the operator, then the agents on node B (bottom right). Every node's log
goes through `audit.py`, which prints one line per authorization decision
(`ALLOW`, `DENY`) and a line when the node loads a changed policy.

### 1. The policy

```bash
cat mesh-policy.json
```

Members hold the role `mesh:role:node`. They may publish `inference://*` but
may call only `system://mesh.catalog`.

### 2. One command starts the mesh

```bash
agentmesh-one --data-dir ~/data/one --port 9000 --policy-file mesh-policy.json \
--admin-token-path ~/data/admin-token --no-join-token --enroll-qr=false --log-level warn
```

The admin token comes from a file, so the banner does not print it, and there
is no standing join token.

### 3. One enrollment token per node

```bash
umask 077; for n in node-a node-b; do agentmesh-one token create --server $URL \
--admin-token-path ~/data/admin-token --description $n | awk '/^Token:/ {print $2}' > ~/data/$n.token; done
stat -c '%A %s bytes %n' data/*.token
```

### 4. Node A publishes its model

```bash
cat node-a.yaml
agentmesh-node run --control-plane $URL --bootstrap-token-path ~/data/node-a.token \
--config node-a.yaml --data-dir ~/data/node-a --bind-addr= --allow-loopback \
--listen /ip4/127.0.0.1/tcp/0 --control-plane-sync-interval 5s 2>&1 | python3 audit.py
```

### 5. Node B joins

```bash
agentmesh-node run --control-plane $URL --bootstrap-token-path ~/data/node-b.token \
--data-dir ~/data/node-b --bind-addr 127.0.0.1:8080 --api-token-path api-token \
--allow-loopback --listen /ip4/127.0.0.1/tcp/0 --control-plane-sync-interval 5s 2>&1 | python3 audit.py
```

### 6. Refused

```bash
cat hello.json
curl -s --unix-socket ~/data/node-b/agentmesh.sock localhost/v1/chat/completions \
-d @hello.json | jq -r '.choices[0].message.content // .error.message'
```

Node B answers that no provider serves the model. Node A's pane shows `DENY`.

### 7. Grant one service by name

```bash
./grant.sh inference://laptop-llm
```

`grant.sh` reads the policy from `GET /admin/policy`, adds the service to
`mesh:role:node` and posts it to `POST /policies`. Both node panes show the
policy update within seconds.

### 8. The same request is allowed

The same `curl`: node A's pane shows `ALLOW` and the model answers.

### 9. An agent: Antigravity CLI

```bash
antigravity -p "Using the agentmesh tools, which AI models are on my mesh and which node serves them? Answer in two short lines of plain text, no markdown."
```

### 10. A second agent: OpenCode

```bash
opencode run "Using the agentmesh tools, list the services on my mesh and the node that serves each. Two short lines of plain text, no markdown."
```

## Notes

- The nodes pull from the control plane every 5 seconds in this demo
(`--control-plane-sync-interval 5s`; the default is 15 minutes), and a
policy event brings the pull forward, so the grant lands within seconds.
- The model's answer is different every take.

## Recording

```bash
./record.sh # all ten steps
AGENTS=0 ./record.sh # steps 1 to 8
AGENTS_RC=~/agents.sh ./record.sh # agent wrappers from a file
PUBLISH=0 ./record.sh # do not copy the video to site/static
AGENTMESH_BIN=/usr/local/bin ./record.sh # installed binaries instead of ./bin
```

The work directory is `$WORK_DIR` (default `~/agentmesh-share-local-model`).
The video is written to `out/demo.mp4` there and, unless `PUBLISH=0`, copied
to `site/static/demo-share-local-model.mp4`; `out/thumbnail.png` is a frame
from step 8.
83 changes: 83 additions & 0 deletions development/examples/share-local-model/audit.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Reads an agentmesh-node log on stdin and prints the lines a viewer needs:
what the node serves, one line per authorization decision, and policy updates.

agentmesh-node run ... 2>&1 | python3 audit.py

Adapted from ../sandboxed-agent/audit.py. Decisions on the internal
system://mesh.catalog lookups are not shown (they are routine allows that
would crowd the pane), and a line is printed when the node loads a changed
policy. On a terminal, ALLOW, DENY and policy updates are colored.
Set AUDIT_RAW=<file> to keep the unfiltered log as well.
"""

import json
import os
import re
import sys
from contextlib import nullcontext

AUDIT = re.compile(r"Audit Traceability\s+(\{.*\})\s*$")
KEEP = re.compile(r"Agent Mesh Node Online|PeerID:|Mesh policy changed|peer banned")
COLOR = {
"ALLOW": "\033[1;38;2;74;222;128m", # green
"DENY": "\033[1;38;2;248;113;113m", # red
"POLICY": "\033[1;38;2;250;204;21m", # yellow
}
RESET = "\033[0m"
# Colors only on a terminal, so a log written to a file stays plain text.
TTY = sys.stdout.isatty()


def paint(kind, text):
return f"{COLOR[kind]}{text}{RESET}" if TTY else text


def verdict(line):
m = AUDIT.search(line)
if m:
try:
d = json.loads(m.group(1))
except json.JSONDecodeError:
return None
target = d.get("target", "")
if target.startswith("system://"):
return None
who = f"{d.get('role') or '-'} {d.get('peer_id', '')[:12]}…"
what = " ".join(x for x in (d.get("method"), d.get("path")) if x) or d.get("protocol", "")
decision = d.get("decision", "?").upper()
word = paint(decision, f"{decision:<5}") if decision in COLOR else f"{decision:<5}"
return f"{word} {who:<28} {what:<26} {target}"
Comment on lines +56 to +63

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Several fields extracted from the parsed JSON (such as target, peer_id, and decision) can potentially be null (None in Python) or of unexpected types. Directly calling string methods like .startswith(), .upper(), or slicing ([:12]) on None will raise AttributeError or TypeError and crash the log filtering script. Providing robust fallback defaults ensures the script handles any malformed or incomplete audit log entries gracefully.

Suggested change
target = d.get("target", "")
if target.startswith("system://"):
return None
who = f"{d.get('role') or '-'} {d.get('peer_id', '')[:12]}…"
what = " ".join(x for x in (d.get("method"), d.get("path")) if x) or d.get("protocol", "")
decision = d.get("decision", "?").upper()
word = paint(decision, f"{decision:<5}") if decision in COLOR else f"{decision:<5}"
return f"{word} {who:<28} {what:<26} {target}"
target = d.get("target")
if not isinstance(target, str):
target = ""
if target.startswith("system://"):
return None
role = d.get("role") or "-"
peer_id = d.get("peer_id") or ""
who = f"{role} {peer_id[:12]}…"
method = d.get("method") or ""
path = d.get("path") or ""
protocol = d.get("protocol") or ""
what = " ".join(x for x in (method, path) if x) or protocol
decision = (d.get("decision") or "?").upper()
word = paint(decision, f"{decision:<5}") if decision in COLOR else f"{decision:<5}"
return f"{word} {who:<28} {what:<26} {target}"

if "Mesh policy changed" in line:
return paint("POLICY", "Policy updated by the control plane")
if "peer banned" in line:
peer = re.search(r'"peer":\s*"([^"]+)"', line)
return f"BANNED {peer.group(1) if peer else ''}: the control plane cut this member off"
if KEEP.search(line):
# Drop the timestamp and logger columns; keep the message.
return (line.split("\t")[-1] if "\t" in line else line).strip()
return None


raw_path = os.environ.get("AUDIT_RAW")
with (open(raw_path, "a") if raw_path else nullcontext()) as raw:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When opening files in Python 3, it is a best practice to explicitly specify the encoding parameter (e.g., encoding="utf-8") to prevent platform-dependent encoding issues, especially when running on environments with different default locales.

Suggested change
with (open(raw_path, "a") if raw_path else nullcontext()) as raw:
with (open(raw_path, "a", encoding="utf-8") if raw_path else nullcontext()) as raw:

for raw_line in sys.stdin:
if raw:
raw.write(raw_line)
raw.flush()
out = verdict(raw_line.rstrip("\n"))
if out:
print(out, flush=True)
58 changes: 58 additions & 0 deletions development/examples/share-local-model/caption.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Caption pane for the recording: shows the text in a file, typed at reading
speed, and redraws whenever the file changes.

python3 caption.py <caption-file> <columns> <characters-per-second>

Adapted from the caption pane in ../multi-tier-guardrails/record.sh. A
caption that starts with "Step n/m · " draws that label in an accent color.
"""

import sys
import textwrap
import time

path, cols, cps = sys.argv[1], int(sys.argv[2]), float(sys.argv[3])
sys.stdout.write("\033[?25l") # no cursor in the caption pane
last = None
while True:
try:
with open(path, encoding="utf-8") as f:
text = f.read().strip()
except FileNotFoundError:
text = ""
if text != last:
last = text
time.sleep(0.4) # let the recording show the pane before typing starts
sys.stdout.write("\033[2J\033[H\n")
label, sep, body = text.partition(" · ")
if not (sep and label.startswith("Step ")):
label, body = "", text
width = cols - 6 - (len(label) + 3 if label else 0)
first = True
for line in textwrap.wrap(body, width)[:3]:
sys.stdout.write(" ")
if first and label:
sys.stdout.write(f"\033[1;38;2;34;211;238m{label}\033[0m\033[38;2;148;163;184m · \033[0m")
first = False
sys.stdout.write("\033[1m")
for ch in line:
sys.stdout.write(ch)
sys.stdout.flush()
time.sleep(1 / cps)
sys.stdout.write("\033[0m\n")
sys.stdout.flush()
time.sleep(0.1)
12 changes: 12 additions & 0 deletions development/examples/share-local-model/captions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
Agent Mesh connects AI agents, tools and models by service name. Nothing is reachable until a policy allows it. In this demo, node B asks to use a model that node A serves.
Step 1/10 · The mesh policy. Members may publish models, but may not call them. Deny by default.
Step 2/10 · One command starts the control plane, a router and the web console. The admin token is read from a file, so it is never printed.
Step 3/10 · The operator mints one single-use enrollment token per node. The tokens are written to files, not to the screen.
Step 4/10 · Node A publishes its local Ollama model as the service laptop-llm. Ollama stays on 127.0.0.1. Node A's pane shows every authorization decision.
Step 5/10 · Node B joins with its own identity. It offers the agents on its machine an OpenAI-compatible API and an MCP server.
Step 6/10 · Node B asks for the model. Node A checks node B's credential against the policy and refuses the call: DENY.
Step 7/10 · The operator grants one service, by name. No restart, no new credentials. Both nodes load the new policy within seconds.
Step 8/10 · The same request now reaches the model on node A over an authenticated peer-to-peer link: ALLOW.
Step 9/10 · An AI agent uses the mesh through node B's MCP server. Antigravity CLI finds the model and the node that serves it.
Step 10/10 · A second agent, OpenCode, uses the same MCP server. Its project config allows the agentmesh tools and nothing else.
Agent Mesh: an identity per node, policy on service names, deny by default. github.com/google/agentmesh · google.github.io/agentmesh
28 changes: 28 additions & 0 deletions development/examples/share-local-model/ctl.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
#!/usr/bin/env bash
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Off-camera controls that demo.tape calls through tmux run-shell:
# ctl.sh go <cp|na|nb|op> focus a pane (layout.sh stores the pane ids)
# ctl.sh cap <n> show line n of captions.txt in the caption pane

set -o errexit
set -o nounset
set -o pipefail

case "${1:-}" in
go) tmux select-pane -t "$(tmux show -gv "@${2:?pane name}")" ;;
cap) sed -n "${2:?caption number}p" "$(tmux show -gv @captions)" > "$(tmux show -gv @caption_file)" ;;
*) echo "usage: ctl.sh go <pane> | cap <n>" >&2; exit 2 ;;
esac
40 changes: 40 additions & 0 deletions development/examples/share-local-model/demo-bashrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# Shell for every pane of the recording. layout.sh starts it as:
# env DEMO_HOME=<dir> DEMO_HOST=<role> bash --rcfile demo-bashrc
# Every Agent Mesh command in the video is typed as shown; nothing here wraps them.

KIT=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
# AGENTMESH_BIN and AGENTS_RC, written by record.sh.
# shellcheck source=/dev/null
source "$KIT/paths.env"
export PATH="$AGENTMESH_BIN:$PATH"
export URL="http://127.0.0.1:9000"

# The demo home is the home of these shells, so the prompt reads ~ and the
# files the video uses are right there.
export HOME="${DEMO_HOME:?DEMO_HOME is not set}"
export HISTFILE="$HOME/.bash_history"
export PS1="\[\e[1;32m\]\u@${DEMO_HOST:-demo}\[\e[0m\]:\[\e[1;34m\]\w\[\e[0m\]\\$ "
unset PROMPT_COMMAND

# Optional: wrappers that make antigravity and opencode callable (see SCRIPT.md).
if [[ -n "${AGENTS_RC:-}" && -r "$AGENTS_RC" ]]; then
# shellcheck source=/dev/null
source "$AGENTS_RC"
fi

cd ~ || return
clear
Loading
Loading