Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sdk: native JavaScript and Python SDKs, milestone 1
Antonio Ojeabbc62908178b
diff --git a/.github/dependabot.yml b/.github/dependabot.ymlindex 72b58ab1..7953b4f7 100644--- a/.github/dependabot.yml+++ b/.github/dependabot.yml@@ -38,6 +38,7 @@ updates:- package-ecosystem: "npm"directories:- "/tests/ui"+ - "/sdk/js"schedule:interval: "weekly"cooldown:@@ -45,6 +46,7 @@ updates:- package-ecosystem: "pip"directories:+ - "/sdk/python"- "/cmd/chaos-agent"- "/tests/e2e/docker/*"- "/development/examples/*"diff --git a/.github/workflows/sdk.yml b/.github/workflows/sdk.ymlnew file mode 100644index 00000000..5cce6691--- /dev/null+++ b/.github/workflows/sdk.yml@@ -0,0 +1,80 @@+# 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.++# Native SDKs (sdk/): unit tests per language, then both SDKs enrolling+# against a real control plane through tests/integration/sdk_enroll_test.go.+# api/sam.proto is a trigger because the SDKs ship bindings generated from it.+name: SDK++on:+ push:+ branches: [main]+ paths:+ - 'sdk/**'+ - 'api/sam.proto'+ - 'hack/gen-sdk-proto.sh'+ - 'tests/integration/sdk_*_test.go'+ - '.github/workflows/sdk.yml'+ pull_request:+ branches: [main]+ paths:+ - 'sdk/**'+ - 'api/sam.proto'+ - 'hack/gen-sdk-proto.sh'+ - 'tests/integration/sdk_*_test.go'+ - '.github/workflows/sdk.yml'++permissions:+ contents: read++env:+ GO_VERSION: "1.26"++jobs:+ sdk:+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false++ - uses: actions/setup-go@40f1582b2485089dde7abd97c1529aa768e1baff # v5+ with:+ go-version: ${{ env.GO_VERSION }}+ cache: false++ - uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0+ with:+ node-version: "22"+ cache: npm+ cache-dependency-path: sdk/js/package-lock.json++ - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"++ - name: Install protoc+ run: sudo apt-get update && sudo apt-get install -y protobuf-compiler++ - name: JavaScript SDK+ run: make sdk-js++ - name: Python SDK+ run: make sdk-python++ - name: Generated bindings are current+ run: ./hack/verify-sdk-generated.sh++ - name: Both SDKs against a real control plane+ run: go test ./tests/integration -run TestNativeSDKs -count=1 -vdiff --git a/Makefile b/Makefileindex 868f922d..b6c5c78c 100644--- a/Makefile+++ b/Makefile@@ -159,6 +159,24 @@ test:e2e-test: build docker-buildbats -j 10 --verbose-run $(if $(WHAT),--filter "$(WHAT)") tests/e2e/+# Native SDKs under sdk/. sdk-js and sdk-python run each SDK's own unit+# tests and leave it installed, which is what TestNativeSDKs needs to run+# both against a real control plane instead of skipping.+.PHONY: sdk-js sdk-python sdk-proto sdk-test+sdk-js:+ cd sdk/js && npm ci --no-fund --no-audit && npm test && npm run build++sdk-python:+ python3 -m venv sdk/python/.venv+ ./sdk/python/.venv/bin/pip install -q -e './sdk/python[test]'+ ./sdk/python/.venv/bin/python -m pytest -q sdk/python/tests++sdk-proto:+ ./hack/gen-sdk-proto.sh++sdk-test: sdk-js sdk-python+ go test ./tests/integration -run TestNativeSDKs -count=1 -v+.PHONY: ui-testui-test: buildchmod +x ./tests/ui/run.shdiff --git a/hack/gen-sdk-proto.sh b/hack/gen-sdk-proto.shnew file mode 100755index 00000000..a51f768d--- /dev/null+++ b/hack/gen-sdk-proto.sh@@ -0,0 +1,51 @@+#!/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.++# Regenerates the protobuf bindings the native SDKs under sdk/ ship for+# api/sam.proto. The Go bindings are gen-proto.sh's job. Requires protoc+# and, for JavaScript, an `npm install` in sdk/js (protoc-gen-es).++set -o errexit+set -o nounset+set -o pipefail++REPO_ROOT=$(git rev-parse --show-toplevel)+cd "${REPO_ROOT}"++JS_GEN_DIR="sdk/js/src/gen"+PY_GEN_DIR="sdk/python/src/agent_mesh/_proto"+PROTOC_GEN_ES="sdk/js/node_modules/.bin/protoc-gen-es"++if [[ ! -x "${PROTOC_GEN_ES}" ]]; then+ echo "missing ${PROTOC_GEN_ES}: run 'npm install' in sdk/js first" >&2+ exit 1+fi++echo "Generating JavaScript protobuf code..."+mkdir -p "${JS_GEN_DIR}"+protoc -I api \+ --plugin="protoc-gen-es=${PROTOC_GEN_ES}" \+ --es_out="${JS_GEN_DIR}" \+ --es_opt=target=ts \+ api/sam.proto++echo "Generating Python protobuf code..."+mkdir -p "${PY_GEN_DIR}"+protoc -I api \+ --python_out="${PY_GEN_DIR}" \+ --pyi_out="${PY_GEN_DIR}" \+ api/sam.proto++echo "SDK protobuf generation complete."diff --git a/hack/verify-sdk-generated.sh b/hack/verify-sdk-generated.shnew file mode 100755index 00000000..24763980--- /dev/null+++ b/hack/verify-sdk-generated.sh@@ -0,0 +1,35 @@+#!/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.++# Fails when the protobuf bindings the SDKs ship are stale relative to+# api/sam.proto. Regenerates in place, so run it on a clean checkout.++set -o errexit+set -o nounset+set -o pipefail++REPO_ROOT=$(git rev-parse --show-toplevel)+cd "${REPO_ROOT}"++GENERATED=(sdk/js/src/gen sdk/python/src/agent_mesh/_proto)++./hack/gen-sdk-proto.sh++if ! git diff --exit-code -- "${GENERATED[@]}"; then+ echo "ERROR: SDK protobuf bindings are not up to date."+ echo "Run ./hack/gen-sdk-proto.sh and commit the result."+ exit 1+fi+echo "SDK protobuf bindings are up to date."diff --git a/sdk/README.md b/sdk/README.mdnew file mode 100644index 00000000..60723cd3--- /dev/null+++ b/sdk/README.md@@ -0,0 +1,253 @@+# Native SDKs++This directory holds the SDKs that let an agent join a SAM mesh from inside+its own process, without a `sam-node` sidecar. Two languages are in scope:++- [`js/`](js/) — `@agent-mesh/sdk`, TypeScript for Node.js, built on+ [js-libp2p](https://github.com/libp2p/js-libp2p).+- [`python/`](python/) — `agent-mesh` (import `agent_mesh`), built on+ [py-libp2p](https://github.com/libp2p/py-libp2p).++The motivation is [issue #480](https://github.com/google/sam/issues/480). The+sidecar works, but it makes every agent deployment manage a second process,+a local port and a token, which does not fit serverless platforms and splits+tracing between the agent and the network layer. An earlier attempt at a+Python package (`sam-mcp-python`) only wrapped the sidecar's HTTP API and was+removed in favour of this work.++Both SDKs speak the mesh protocol directly. There is no SDK-specific+endpoint anywhere in the mesh; a node built with an SDK is, to every other+node and to the control plane, a `sam-node`.++## What exists today++Milestone 1 is implemented and tested in both languages:++| Capability | JS | Python |+| --- | --- | --- |+| ed25519 identity, libp2p key encodings, peer ID | yes | yes |+| Enrollment with a bootstrap token (`POST /enroll`, `GET /enroll/status` polling) | yes | yes |+| Enrollment with an OIDC token (`POST /register`) | yes | yes |+| Credential refresh (`POST /refresh`) | yes | yes |+| Signed key-set sync (`GET /keys`) | yes | yes |+| Persisted state (identity and credential, owner-only files) | yes | yes |+| `AuthFrame` encoding | yes | yes |++A member built this way holds a valid mesh credential bound to its peer ID+and knows the router addresses. It cannot yet open a libp2p connection.++## Wire contract++Everything below is what the Go implementation does today, with the source+file that defines it. The SDKs must match it byte for byte; when a Go change+alters one of these, the SDKs change with it.++### Identity++- The identity is an ed25519 key pair. The public key travels in the libp2p+ protobuf encoding `PublicKey{Type: Ed25519, Data: <32 bytes>}`, which is+ the bytes `08 01 12 20` followed by the key. Private keys persist as+ `PrivateKey{Type: Ed25519, Data: <seed || public>}`, bytes `08 01 12 40`+ followed by 64 bytes; this is what `sam-node` writes to its store.+- The peer ID is the identity multihash (`00 24`) of the public key encoding,+ written in base58btc. The control plane refuses an enrollment whose+ `peer_id` is not derived from `public_key`+ (`internal/controlplane/server.go`, `pID.MatchesPublicKey`).++### Control plane (protobuf over HTTP)++All requests and responses are `application/x-protobuf` bodies of the+messages in `api/sam.proto`. Bodies are capped at 1 MiB on both sides.++| Endpoint | Request | Response | Proof of possession |+| --- | --- | --- | --- |+| `GET /info` | — | `ControlPlaneInfoResponse` | none |+| `POST /enroll` | `BootstrapEnrollRequest` | `BootstrapEnrollResponse` | sign `sam:enroll:<peer_id>:<ts>` |+| `GET /enroll/status?peer_id=` | headers `X-Sam-Challenge-Ts`, `X-Sam-Challenge-Sig` (base64url, unpadded) | `BootstrapEnrollResponse` | sign `sam:enroll-status:<peer_id>:<ts>` |+| `POST /register` | `EnrollRequest` | `EnrollResponse` | sign `sam:register:<peer_id>:<ts>` |+| `POST /refresh` | `TokenRefreshRequest`, header `Authorization: Bearer <base64 biscuit>` | `TokenRefreshResponse` | sign `sam:refresh:<peer_id>:<ts>` |+| `GET /keys` | — | `KeysResponse` | none; see below |++- `<ts>` is unix milliseconds and must be within 5 minutes of the control+ plane's clock (`challengeMaxAge`). Challenges are defined in+ `api/network.go`.+- A bootstrap enrollment answers `PENDING` until an operator approves it,+ unless the control plane runs with auto-approval. The client polls+ `/enroll/status` at the returned `poll_interval_seconds`.+- `/refresh` redeems only the last biscuit the control plane issued for the+ peer. A client must persist the new biscuit before using it; losing it+ means re-enrolling.+- `/keys` signatures cover the deterministic protobuf encoding of+ `KeysResponse{public_keys, timestamp}` with `signatures` cleared, one+ signature per key by that key. The receiver accepts the set when a key it+ already trusts (the enrollment key) vouches for it and the timestamp is+ within 5 minutes (`api/trust.go`). Rotation keeps several keys valid, so+ a member must trust the whole set to verify peers enrolled under a+ retiring key.+- A plaintext `http://` control plane URL is accepted only for a loopback+ host (`api.ValidateControlPlaneTransport`). The SDKs expose the same+ explicit opt-in (`allowInsecure` / `allow_insecure`).+- Bootstrap tokens are secrets. The SDKs read them from a file or a value the+ caller already holds; the conformance runners take a path in the+ environment. Nothing takes a token as a command-line argument.++### libp2p host (`internal/node/node.go`)++- Transports: `libp2p.DefaultTransports` (TCP, QUIC, WebSocket).+- Security: **TLS only** (`libp2p.Security(libp2ptls.ID, libp2ptls.New)`).+ There is no Noise on `sam-node` or `sam-router`. js-libp2p has TLS;+ py-libp2p gained it in+ [libp2p/py-libp2p#831](https://github.com/libp2p/py-libp2p/pull/831) and+ has passed the libp2p transport interoperability suite against the other+ implementations since+ [libp2p/test-plans#798](https://github.com/libp2p/test-plans/pull/798).+- Muxer: yamux (libp2p default).+- Relay: circuit relay v2, with the routers as static relays; hole punching+ is on. A node behind NAT is reached through a router.+- DHT: Kademlia with protocol prefix `/sam`, mode auto.++### Streams++Two protocols, both starting with a length-prefixed protobuf frame. Framing+is the go-msgio varint style (unsigned varint byte length, then the bytes),+with a 64 KiB cap on the first frame.++- `/sam/auth/1.0.0` (`HandleAuthHandshake`, and the router's equivalent).+ Client sends `AuthFrame{biscuit}`; server verifies the biscuit against the+ control plane keys, checks it is bound to the connection's peer ID and not+ revoked, and answers `AuthResponse{success, biscuit}` with its own+ credential. The client verifies that credential the same way and, for a+ router, requires the router role. This is how a member joins: connect to a+ router, run this handshake, and the router admits it to the relay and+ gossip.+- `/sam/mcp/1.0.0` (`WithBiscuitAuth` then `HandleMCPStream`). Client sends+ `AuthFrame{biscuit, target_service: "mcp://<service>", agent}`; server+ authorizes the request with the Biscuit authorizer described below and+ answers `AuthResponse`. The stream then carries MCP JSON-RPC messages, each+ one varint-length-prefixed (`StreamTransport` in `internal/node/gate.go`).+ An empty `target_service` selects the node's own catalog tools.++### Discovery (`internal/node/service.go`)++A provider announces a service as a DHT provider record for+`cidv1(raw, sha256("sam:service:<type>[:<name>]"))`, once for the type and+once for the name (`<type>` is `mcp`, `inference` or `a2a`). A consumer+looks up providers for the same CID, dials one and opens `/sam/mcp/1.0.0`.+Gossip topics under `/sam/discovery/v1/...` carry `ServiceAnnounce` for+interest-scoped updates; the DHT is the source of truth.++### Authorization on the provider side (`internal/node/middleware.go`)++A node that serves a tool evaluates the caller's biscuit with an authorizer+that has, in this order: the biscuit's own authority facts (`node`, `role`,+`label`, `agent`), injected facts `service(<type>, <name>)`,+`connection_peer_id(<peer>)` and optionally `agent(<claim>)`, the baseline+checks, rules and policies from `api/datalog.go`, the facts from the+provider's own biscuit, and the mesh policy rules the control plane+publishes (`BuildPolicyRules` over `PolicyConfigGetResponse`). Deny by+default.++## Plan++Each milestone lands in both languages with its tests before the next one+starts. Where a milestone needs a Go change, the Go change lands first.++### Milestone 1 — identity and enrollment (done)++Described above. Tested by unit tests in each SDK against a fake control+plane and by `tests/integration/sdk_enroll_test.go`, which runs each SDK's+conformance runner against a real control plane in manual-approval mode,+approves the request through `/admin`, and checks the biscuits the SDK+holds against the control plane's records.++### Milestone 2 — join the mesh++- libp2p host per SDK: TCP, TLS, yamux, identify, circuit relay v2 client,+ Kademlia client with prefix `/sam`, dial-through-relay to peers.+ JS: `libp2p`, `@libp2p/tcp`, `@libp2p/tls`, `@chainsafe/libp2p-yamux`,+ `@libp2p/circuit-relay-v2`, `@libp2p/kad-dht`, `@libp2p/identify`.+ Python: `libp2p>=0.7` (`security.tls`, `stream_muxer.yamux`,+ `relay.circuit_v2`, `kad_dht`); it is trio-based, so the Python SDK's+ networking API is `anyio`-compatible async.+- Biscuit verification of the peer's `AuthResponse`: signature under a+ trusted control plane key, expiry, authority binding to the connection+ peer ID, and the router role for routers. JS:+ `@biscuit-auth/biscuit-wasm`; Python: `biscuit-python`.+- `/sam/auth/1.0.0` client handshake with a router; the router addresses come+ from the credential.+- Background credential refresh, driven by the biscuit's expiration as+ `StartRenewalLoop` does.+- Test: a Go integration test starts a real router (`startRouter`) and+ checks, through the control plane's lease report, that the SDK member is+ among the router's authenticated peers.++### Milestone 3 — call tools++- DHT lookup by service type and name; `/sam/mcp/1.0.0` client: send the+ `AuthFrame`, verify the provider's biscuit, then run an MCP client over+ the varint-framed stream. JS: a `Transport` for+ `@modelcontextprotocol/sdk`; Python: a read/write stream pair for `mcp`.+- Caller-side label requirements (`checkPeerLabels`) on the provider's+ biscuit.+- Public API: `mesh.discover(type, name)`, `mesh.callTool("mcp://svc/tool",+ args)`, `mesh.listTools(peer, service)`.+- Test: the SDK calls a tool served by a `sam-node` started with+ `startBackgroundNode` and a registered MCP backend, through a real router.++### Milestone 4 — serve tools++- `/sam/mcp/1.0.0` server: read the `AuthFrame`, run the authorizer, answer,+ then hand the stream to an in-process MCP server.+- The authorizer needs the baseline Datalog from `api/datalog.go` and the+ mesh policy from `GET /policies`. Before this milestone the baseline+ Datalog moves out of Go string constants into a language-neutral artifact+ that the Go build and both SDKs embed, so it is written once.+- DHT provide for each registered service, reprovided on the node's+ interval; `POST /nodes/catalog` self-report.+- Test: a `sam-node` calls a tool served by the SDK member, and a denied+ caller is refused at the `AuthResponse`.++### Milestone 5 — parity and release++- Control plane sync loop (`/keys`, bans, router addresses, policy) and+ gossip event handling for bans and key rotation.+- Inference and A2A egress over libp2p HTTP (`libp2phttp`), following the+ sidecar's `/sam/<peer>/<type>/<name>/` proxy.+- Publishing: `@agent-mesh/sdk` to npm and `agent-mesh` to PyPI from the+ release workflow, versioned with the repository.+- Docs: a guide under `site/content/docs/guides/` and the connector+ interface for platforms (issue #480).++### Non-goals++- Rewriting the control plane, router or sandbox components; they stay Go.+- A browser build. Node.js only until the transport story for browsers+ (WebTransport or WebRTC to routers) is designed.+- Any SDK-only wire protocol. If an SDK needs something the Go node does not+ speak, the Go node learns it first.++## Working on the SDKs++```bash+# Regenerate protobuf bindings after editing api/sam.proto+./hack/gen-sdk-proto.sh++# JavaScript+cd sdk/js && npm ci && npm test && npm run build++# Python+python3 -m venv sdk/python/.venv+sdk/python/.venv/bin/pip install -e 'sdk/python[test]'+sdk/python/.venv/bin/pytest sdk/python/tests++# Both against a real control plane+go test ./tests/integration -run TestNativeSDKs -v+```++`make sdk-test` runs all of the above. The integration test skips an SDK+whose toolchain is missing, and CI (`.github/workflows/sdk.yml`) installs+both so nothing skips there.++Interoperability facts that the tests pin: `sdk/testdata/identity_vectors.json`+holds key encodings, peer IDs and challenge signatures produced with+go-libp2p, and every SDK's identity tests reproduce them.diff --git a/sdk/js/.gitignore b/sdk/js/.gitignorenew file mode 100644index 00000000..d93463d4--- /dev/null+++ b/sdk/js/.gitignore@@ -0,0 +1,3 @@+node_modules/+dist/+build/diff --git a/sdk/js/README.md b/sdk/js/README.mdnew file mode 100644index 00000000..b198f653--- /dev/null+++ b/sdk/js/README.md@@ -0,0 +1,63 @@+# @agent-mesh/sdk++Native JavaScript SDK for joining a SAM agent mesh from inside the agent+process. It replaces the `sam-node` sidecar for agents written for Node.js.++Status: **milestone 1** (identity, enrollment, credential refresh). The+libp2p transport, service discovery and MCP over the mesh are the next+milestones; see [../README.md](../README.md) for the plan.++## Install++```bash+cd sdk/js && npm ci && npm run build+```++Requires Node.js 22.18 or later. The only runtime dependency is+`@bufbuild/protobuf`.++## Use++```ts+import { AgentMesh } from "@agent-mesh/sdk";++const mesh = await AgentMesh.enroll({+ controlPlaneUrl: "https://hub.sam-mesh.dev",+ bootstrapTokenPath: "/run/secrets/sam-bootstrap-token",+ stateDir: `${process.env.HOME}/.config/sam-mesh/agent`,+});+console.log(mesh.peerId); // 12D3Koo...+await mesh.refresh(); // trades the biscuit for a fresh one++// Later, in a new process:+const resumed = await AgentMesh.load({ controlPlaneUrl: "https://hub.sam-mesh.dev", stateDir: "..." });+const frame = resumed.authFrame("mcp://calculator"); // first frame on a mesh stream+```++`enroll` takes exactly one of `bootstrapTokenPath`, `bootstrapToken` or+`jwt`. Read tokens from a file or the environment; do not put them on a+command line.++A plaintext `http://` control plane is accepted only on loopback. Pass+`allowInsecure: true` for a network you trust.++## Layout++- `src/identity.ts`: ed25519 key pair, libp2p key encodings, peer ID.+- `src/controlplane.ts`: `/info`, `/keys`, `/enroll`, `/enroll/status`,+ `/register`, `/refresh`, with the proof-of-possession challenges from+ `api/network.go`.+- `src/credential.ts`: what a member holds, `AuthFrame` encoding.+- `src/mesh.ts`: `AgentMesh`, persistence under a state directory+ (`identity.key` in the libp2p private key encoding, `credential.json`).+- `src/gen/`: generated from `api/sam.proto` by `hack/gen-sdk-proto.sh`.++## Test++```bash+npm test # unit tests, fake control plane+go test ./tests/integration -run TestNativeSDKs # against a real control plane+```++The integration test runs `dist/conformance.js`, so build first. It skips+when `dist/` or `node_modules/` is missing.diff --git a/sdk/js/package-lock.json b/sdk/js/package-lock.jsonnew file mode 100644index 00000000..ebebc5ed--- /dev/null+++ b/sdk/js/package-lock.json@@ -0,0 +1,150 @@+{+ "name": "@agent-mesh/sdk",+ "version": "0.1.0",+ "lockfileVersion": 3,+ "requires": true,+ "packages": {+ "": {+ "name": "@agent-mesh/sdk",+ "version": "0.1.0",+ "license": "Apache-2.0",+ "dependencies": {+ "@bufbuild/protobuf": "^2.15.0"+ },+ "devDependencies": {+ "@bufbuild/protoc-gen-es": "^2.15.0",+ "@types/node": "^22.19.0",+ "typescript": "^5.9.3"+ },+ "engines": {+ "node": ">=22.18"+ }+ },+ "node_modules/@bufbuild/protobuf": {+ "version": "2.15.0",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@bufbuild/protobuf/-/protobuf-2.15.0.tgz",+ "integrity": "sha512-DAheWUkVr/SJTWCc+lg9dhY0eN4SaWlf4+bG1KzHeXbnqt0AfB/NX0Z+VunGlM1ki1B4zVvye27MpKh/svySUA==",+ "license": "(Apache-2.0 AND BSD-3-Clause)"+ },+ "node_modules/@bufbuild/protoc-gen-es": {+ "version": "2.15.0",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@bufbuild/protoc-gen-es/-/protoc-gen-es-2.15.0.tgz",+ "integrity": "sha512-FRhNTAZEXW6arWx2JxgtpuazhmewYctXugu5SfXGpXpLLCInDT1005fSKDzEM/70Es2oIn07PM4RvpwvDvR/fg==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@bufbuild/protobuf": "2.15.0",+ "@bufbuild/protoplugin": "2.15.0"+ },+ "bin": {+ "protoc-gen-es": "bin/protoc-gen-es"+ },+ "engines": {+ "node": ">=22"+ },+ "peerDependencies": {+ "@bufbuild/protobuf": "2.15.0"+ },+ "peerDependenciesMeta": {+ "@bufbuild/protobuf": {+ "optional": true+ }+ }+ },+ "node_modules/@bufbuild/protoplugin": {+ "version": "2.15.0",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@bufbuild/protoplugin/-/protoplugin-2.15.0.tgz",+ "integrity": "sha512-vZhRoqB/jTHATqItRvJQf1zbxdrGRRhiusGty4+lKcfEFODG0PMXky2Ezv4WHHS6oSxq+5qShITuE7K1/82SuQ==",+ "dev": true,+ "license": "Apache-2.0",+ "dependencies": {+ "@bufbuild/protobuf": "2.15.0",+ "@typescript/vfs": "^1.6.2",+ "typescript": "5.4.5"+ }+ },+ "node_modules/@bufbuild/protoplugin/node_modules/typescript": {+ "version": "5.4.5",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/typescript/-/typescript-5.4.5.tgz",+ "integrity": "sha512-vcI4UpRgg81oIRUFwR0WSIHKt11nJ7SAVlYNIu+QpqeyXP+gpQJy/Z4+F0aGxSE4MqwjyXvW/TzgkLAx2AGHwQ==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/@types/node": {+ "version": "22.20.4",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@types/node/-/node-22.20.4.tgz",+ "integrity": "sha512-zJRE40jpHtKqE/C4fgHrAKQLJuSpzEnP9ff9Y7YtoR3Wd2pwqzlekDeEuUQXjRd+QCYnVnNwuJYmhdk9XV8gvA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "undici-types": "~6.21.0"+ }+ },+ "node_modules/@typescript/vfs": {+ "version": "1.6.5",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/@typescript/vfs/-/vfs-1.6.5.tgz",+ "integrity": "sha512-gobLHQLmvQGJInFk31NvgMd1uYzRXsd8qgnOssyLD055R2QPnw1ubRbBQ4+T+5qC7IQVuYXdvNDE2G7tMDVHgw==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "debug": "^4.4.3"+ },+ "peerDependencies": {+ "typescript": "*"+ }+ },+ "node_modules/debug": {+ "version": "4.4.3",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/debug/-/debug-4.4.3.tgz",+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "ms": "^2.1.3"+ },+ "engines": {+ "node": ">=6.0"+ },+ "peerDependenciesMeta": {+ "supports-color": {+ "optional": true+ }+ }+ },+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",+ "dev": true,+ "license": "MIT"+ },+ "node_modules/typescript": {+ "version": "5.9.3",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/typescript/-/typescript-5.9.3.tgz",+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",+ "dev": true,+ "license": "Apache-2.0",+ "bin": {+ "tsc": "bin/tsc",+ "tsserver": "bin/tsserver"+ },+ "engines": {+ "node": ">=14.17"+ }+ },+ "node_modules/undici-types": {+ "version": "6.21.0",+ "resolved": "http://airlock-proxy.uplink.goog:999/npm/artifact-foundry-prod/ah-3p-staging-npm/undici-types/-/undici-types-6.21.0.tgz",+ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",+ "dev": true,+ "license": "MIT"+ }+ }+}diff --git a/sdk/js/package.json b/sdk/js/package.jsonnew file mode 100644index 00000000..bdb16c85--- /dev/null+++ b/sdk/js/package.json@@ -0,0 +1,39 @@+{+ "name": "@agent-mesh/sdk",+ "version": "0.1.0",+ "description": "Native SDK for joining a SAM agent mesh from inside a Node.js agent process",+ "license": "Apache-2.0",+ "repository": {+ "type": "git",+ "url": "https://github.com/google/sam.git",+ "directory": "sdk/js"+ },+ "type": "module",+ "engines": {+ "node": ">=22.18"+ },+ "exports": {+ ".": {+ "types": "./dist/index.d.ts",+ "default": "./dist/index.js"+ }+ },+ "files": [+ "dist",+ "README.md"+ ],+ "scripts": {+ "build": "tsc -p tsconfig.build.json",+ "typecheck": "tsc -p tsconfig.json --noEmit",+ "pretest": "tsc -p tsconfig.test.json",+ "test": "node --test 'build/**/*.test.js'"+ },+ "dependencies": {+ "@bufbuild/protobuf": "^2.15.0"+ },+ "devDependencies": {+ "@bufbuild/protoc-gen-es": "^2.15.0",+ "@types/node": "^22.19.0",+ "typescript": "^5.9.3"+ }+}diff --git a/sdk/js/src/base58.ts b/sdk/js/src/base58.tsnew file mode 100644index 00000000..fcff39ec--- /dev/null+++ b/sdk/js/src/base58.ts@@ -0,0 +1,62 @@+// 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.++// base58btc, the alphabet libp2p peer IDs are written in.++const ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";+const BASE = BigInt(ALPHABET.length);++const INDEX = new Map<string, number>();+for (let i = 0; i < ALPHABET.length; i++) {+ INDEX.set(ALPHABET.charAt(i), i);+}++export function encodeBase58(bytes: Uint8Array): string {+ let zeros = 0;+ while (zeros < bytes.length && bytes[zeros] === 0) {+ zeros++;+ }+ let n = 0n;+ for (const b of bytes) {+ n = (n << 8n) | BigInt(b);+ }+ let out = "";+ while (n > 0n) {+ const digit = Number(n % BASE);+ out = ALPHABET.charAt(digit) + out;+ n /= BASE;+ }+ return "1".repeat(zeros) + out;+}++export function decodeBase58(text: string): Uint8Array {+ let zeros = 0;+ while (zeros < text.length && text.charAt(zeros) === "1") {+ zeros++;+ }+ let n = 0n;+ for (const ch of text) {+ const digit = INDEX.get(ch);+ if (digit === undefined) {+ throw new Error(`invalid base58 character ${JSON.stringify(ch)}`);+ }+ n = n * BASE + BigInt(digit);+ }+ const body: number[] = [];+ while (n > 0n) {+ body.unshift(Number(n & 0xffn));+ n >>= 8n;+ }+ return new Uint8Array([...new Array<number>(zeros).fill(0), ...body]);+}diff --git a/sdk/js/src/challenges.ts b/sdk/js/src/challenges.tsnew file mode 100644index 00000000..becccd32--- /dev/null+++ b/sdk/js/src/challenges.ts@@ -0,0 +1,46 @@+// 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.++// Proof-of-possession challenges on the control plane's enrollment surface.+// Each payload names the peer and the endpoint, so a captured signature+// verifies nowhere else. Mirrors api/network.go; ts is unix milliseconds.++const encoder = new TextEncoder();++function challenge(domain: string, peerId: string, ts: number): Uint8Array {+ if (!Number.isSafeInteger(ts) || ts <= 0) {+ throw new Error(`challenge timestamp must be a positive integer, got ${ts}`);+ }+ return encoder.encode(`sam:${domain}:${peerId}:${ts}`);+}++/** Signed at POST /enroll (bootstrap token enrollment). */+export function enrollChallenge(peerId: string, ts: number): Uint8Array {+ return challenge("enroll", peerId, ts);+}++/** Signed at GET /enroll/status while a bootstrap enrollment is pending. */+export function enrollStatusChallenge(peerId: string, ts: number): Uint8Array {+ return challenge("enroll-status", peerId, ts);+}++/** Signed at POST /register (OIDC enrollment). */+export function registerChallenge(peerId: string, ts: number): Uint8Array {+ return challenge("register", peerId, ts);+}++/** Signed at POST /refresh. */+export function refreshChallenge(peerId: string, ts: number): Uint8Array {+ return challenge("refresh", peerId, ts);+}diff --git a/sdk/js/src/conformance.ts b/sdk/js/src/conformance.tsnew file mode 100644index 00000000..12f47d67--- /dev/null+++ b/sdk/js/src/conformance.ts@@ -0,0 +1,71 @@+// 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.++// Conformance runner driven by tests/integration/sdk_enroll_test.go: enrolls+// against a real control plane, refreshes, reloads from disk and reports+// what it holds as JSON on stdout for the Go side to verify. The Python SDK+// ships the same runner (python -m agent_mesh.conformance) with the same+// environment and output, so one Go test checks both.+//+// SAM_CONTROL_PLANE_URL base URL of the control plane+// SAM_BOOTSTRAP_TOKEN_PATH file holding a bootstrap token+// SAM_SDK_STATE_DIR directory for identity and credential+// SAM_INSECURE_CONTROL_PLANE "1" to accept plaintext http:// off loopback++import { AgentMesh } from "./mesh.ts";++const hex = (b: Uint8Array) => Buffer.from(b).toString("hex");+const b64 = (b: Uint8Array) => Buffer.from(b).toString("base64");++function requireEnv(name: string): string {+ const v = process.env[name];+ if (!v) {+ throw new Error(`${name} is required`);+ }+ return v;+}++async function main(): Promise<void> {+ const controlPlaneUrl = requireEnv("SAM_CONTROL_PLANE_URL");+ const bootstrapTokenPath = requireEnv("SAM_BOOTSTRAP_TOKEN_PATH");+ const stateDir = requireEnv("SAM_SDK_STATE_DIR");+ const allowInsecure = process.env.SAM_INSECURE_CONTROL_PLANE === "1";++ const mesh = await AgentMesh.enroll({ controlPlaneUrl, allowInsecure, stateDir, bootstrapTokenPath, pollIntervalMs: 200 });+ const enrolled = mesh.credential;++ const reloaded = await AgentMesh.load({ controlPlaneUrl, allowInsecure, stateDir });+ const refreshed = await reloaded.refresh();++ process.stdout.write(+ JSON.stringify({+ sdk: "js",+ peer_id: mesh.peerId,+ public_key: hex(mesh.identity.publicKeyRaw),+ biscuit: b64(enrolled.biscuit),+ expiration: enrolled.expiration,+ control_plane_keys: enrolled.controlPlaneKeys.map(hex),+ router_addresses: enrolled.routerAddresses,+ reloaded_peer_id: reloaded.peerId,+ refreshed_biscuit: b64(refreshed.biscuit),+ refreshed_expiration: refreshed.expiration,+ auth_frame: b64(reloaded.authFrame("mcp://echo", "agent:example.test:conformance")),+ }) + "\n",+ );+}++main().catch((err: unknown) => {+ process.stderr.write(`${err instanceof Error ? err.stack ?? err.message : String(err)}\n`);+ process.exit(1);+});diff --git a/sdk/js/src/controlplane.test.ts b/sdk/js/src/controlplane.test.tsnew file mode 100644index 00000000..6a2efb5f--- /dev/null+++ b/sdk/js/src/controlplane.test.ts@@ -0,0 +1,258 @@+// 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.++// A fake control plane behind an injected fetch: enough of /enroll,+// /enroll/status, /register, /refresh and /keys to check what the client+// sends and how it treats every answer. The real one is exercised by+// tests/integration/sdk_enroll_test.go.++import { create, fromBinary, toBinary } from "@bufbuild/protobuf";+import assert from "node:assert/strict";+import { test } from "node:test";+import { enrollChallenge, enrollStatusChallenge, refreshChallenge, registerChallenge } from "./challenges.ts";+import {+ ControlPlaneClient,+ ControlPlaneError,+ EnrollmentRejectedError,+ HEADER_CHALLENGE_SIGNATURE,+ HEADER_CHALLENGE_TIMESTAMP,+ InsecureControlPlaneURLError,+ KEYS_RESPONSE_FRESHNESS_MS,+ ROLE_NODE,+ validateControlPlaneURL,+ verifyKeysResponse,+} from "./controlplane.ts";+import {+ BootstrapEnrollRequestSchema,+ BootstrapEnrollResponseSchema,+ EnrollRequestSchema,+ EnrollResponseSchema,+ EnrollmentStatus,+ KeysResponseSchema,+ TokenRefreshRequestSchema,+ TokenRefreshResponseSchema,+ type KeysResponse,+} from "./gen/sam_pb.ts";+import { Identity, verifyEd25519 } from "./identity.ts";++type Handler = (req: Request, body: Uint8Array) => Response | Promise<Response>;++function proto(bytes: Uint8Array, status = 200): Response {+ return new Response(Buffer.from(bytes), { status, headers: { "Content-Type": "application/x-protobuf" } });+}++function fakeFetch(routes: Record<string, Handler>): typeof fetch {+ return (async (input: Parameters<typeof fetch>[0], init?: RequestInit) => {+ const req = new Request(input, init);+ const path = new URL(req.url).pathname;+ const handler = routes[`${req.method} ${path}`];+ if (!handler) {+ return new Response(`no route for ${req.method} ${path}`, { status: 404 });+ }+ return handler(req, new Uint8Array(await req.arrayBuffer()));+ }) as typeof fetch;+}++/** Signs a KeysResponse the way api.SignKeysResponse does. */+function signedKeys(signers: Identity[], timestamp = Date.now()): KeysResponse {+ const unsigned = create(KeysResponseSchema, { publicKeys: signers.map((s) => s.publicKeyRaw), timestamp: BigInt(timestamp) });+ const payload = toBinary(KeysResponseSchema, unsigned);+ return create(KeysResponseSchema, { ...unsigned, signatures: signers.map((s) => s.sign(payload)) });+}++const cpKey = Identity.generate();+const biscuit = new TextEncoder().encode("not-really-a-biscuit");++test("validateControlPlaneURL: https always, http only to loopback unless allowed", () => {+ assert.equal(validateControlPlaneURL("https://hub.example").hostname, "hub.example");+ assert.equal(validateControlPlaneURL("http://127.0.0.1:8080").port, "8080");+ assert.equal(validateControlPlaneURL("http://localhost").hostname, "localhost");+ assert.equal(validateControlPlaneURL("http://[::1]:9").hostname, "[::1]");+ assert.throws(() => validateControlPlaneURL("http://hub.example"), InsecureControlPlaneURLError);+ assert.equal(validateControlPlaneURL("http://hub.example", true).hostname, "hub.example");+ assert.throws(() => validateControlPlaneURL("ftp://hub.example"), /must use http/);+ assert.throws(() => validateControlPlaneURL("not a url"), /invalid control plane URL/);+});++test("enrollBootstrap sends a bound proof of possession and polls until approved", async () => {+ const id = Identity.generate();+ const seen: string[] = [];+ const routerAddrs = ["/ip4/10.0.0.1/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"];+ const fetch = fakeFetch({+ "POST /enroll": (req, body) => {+ assert.equal(req.headers.get("content-type"), "application/x-protobuf");+ const r = fromBinary(BootstrapEnrollRequestSchema, body);+ assert.equal(r.bootstrapToken, "sbt_secret");+ assert.equal(r.peerId, id.peerId);+ assert.deepEqual(r.publicKey, id.libp2pPublicKey);+ assert.equal(r.requestedRole, ROLE_NODE);+ assert.deepEqual(r.labels, { region: "eu" });+ assert.ok(Math.abs(Number(r.timestamp) - Date.now()) < 5000);+ assert.ok(verifyEd25519(id.publicKeyRaw, enrollChallenge(r.peerId, Number(r.timestamp)), r.challengeSignature));+ seen.push("enroll");+ return proto(toBinary(BootstrapEnrollResponseSchema, create(BootstrapEnrollResponseSchema, { status: EnrollmentStatus.PENDING, pollIntervalSeconds: 30 })));+ },+ "GET /enroll/status": (req) => {+ const url = new URL(req.url);+ assert.equal(url.searchParams.get("peer_id"), id.peerId);+ const ts = Number(req.headers.get(HEADER_CHALLENGE_TIMESTAMP));+ const sig = new Uint8Array(Buffer.from(req.headers.get(HEADER_CHALLENGE_SIGNATURE) ?? "", "base64url"));+ assert.ok(verifyEd25519(id.publicKeyRaw, enrollStatusChallenge(id.peerId, ts), sig));+ seen.push("status");+ // Still pending once, then approved.+ const approved = seen.filter((s) => s === "status").length > 1;+ return proto(+ toBinary(+ BootstrapEnrollResponseSchema,+ approved+ ? create(BootstrapEnrollResponseSchema, {+ status: EnrollmentStatus.APPROVED,+ biscuitToken: biscuit,+ controlPlanePublicKey: cpKey.publicKeyRaw,+ routerAddresses: routerAddrs,+ expiration: 1_800_000_000n,+ })+ : create(BootstrapEnrollResponseSchema, { status: EnrollmentStatus.PENDING, pollIntervalSeconds: 30 }),+ ),+ );+ },+ });++ const client = new ControlPlaneClient({ url: "http://127.0.0.1:1", fetch });+ const enrollment = await client.enrollBootstrap({ identity: id, bootstrapToken: "sbt_secret", labels: { region: "eu" }, pollIntervalMs: 1 });+ assert.deepEqual(seen, ["enroll", "status", "status"]);+ assert.deepEqual(enrollment.biscuit, biscuit);+ assert.deepEqual(enrollment.controlPlanePublicKey, cpKey.publicKeyRaw);+ assert.deepEqual(enrollment.routerAddresses, routerAddrs);+ assert.equal(enrollment.expiration, 1_800_000_000);+});++test("enrollBootstrap surfaces a rejection and an HTTP error distinctly", async () => {+ const id = Identity.generate();+ const rejected = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({+ "POST /enroll": () => proto(toBinary(BootstrapEnrollResponseSchema, create(BootstrapEnrollResponseSchema, { status: EnrollmentStatus.REJECTED, errorMessage: "Bootstrap token expired, revoked or exhausted" }))),+ }),+ });+ await assert.rejects(rejected.enrollBootstrap({ identity: id, bootstrapToken: "x" }), (err: unknown) => err instanceof EnrollmentRejectedError && /exhausted/.test(err.message));++ const limited = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({ "POST /enroll": () => new Response("Rate limit exceeded", { status: 429 }) }),+ });+ await assert.rejects(limited.enrollBootstrap({ identity: id, bootstrapToken: "x" }), (err: unknown) => err instanceof ControlPlaneError && err.status === 429 && /Rate limit/.test(err.message));++ const empty = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({+ "POST /enroll": () => proto(toBinary(BootstrapEnrollResponseSchema, create(BootstrapEnrollResponseSchema, { status: EnrollmentStatus.APPROVED, controlPlanePublicKey: cpKey.publicKeyRaw }))),+ }),+ });+ await assert.rejects(empty.enrollBootstrap({ identity: id, bootstrapToken: "x" }), /empty biscuit/);+});++test("enrollBootstrap stops polling when the caller aborts", async () => {+ const id = Identity.generate();+ const client = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({+ "POST /enroll": () => proto(toBinary(BootstrapEnrollResponseSchema, create(BootstrapEnrollResponseSchema, { status: EnrollmentStatus.PENDING, pollIntervalSeconds: 30 }))),+ }),+ });+ const controller = new AbortController();+ const pending = client.enrollBootstrap({ identity: id, bootstrapToken: "x", signal: controller.signal });+ controller.abort(new Error("operator never came"));+ await assert.rejects(pending, /operator never came/);+});++test("register carries the JWT and the register-bound challenge", async () => {+ const id = Identity.generate();+ const client = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({+ "POST /register": (_req, body) => {+ const r = fromBinary(EnrollRequestSchema, body);+ assert.equal(r.jwt, "eyJ.fake.jwt");+ assert.equal(r.peerId, id.peerId);+ assert.equal(r.requestedRole, "sam:role:custom");+ assert.ok(verifyEd25519(id.publicKeyRaw, registerChallenge(r.peerId, Number(r.timestamp)), r.challengeSignature));+ return proto(toBinary(EnrollResponseSchema, create(EnrollResponseSchema, { biscuitToken: biscuit, controlPlanePublicKey: cpKey.publicKeyRaw, expiration: 7n })));+ },+ }),+ });+ const e = await client.register({ identity: id, jwt: "eyJ.fake.jwt", role: "sam:role:custom" });+ assert.deepEqual(e.biscuit, biscuit);+ assert.equal(e.expiration, 7);++ const denied = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({ "POST /register": () => proto(toBinary(EnrollResponseSchema, create(EnrollResponseSchema, { errorMessage: "role not bound" }))) }),+ });+ await assert.rejects(denied.register({ identity: id, jwt: "j" }), EnrollmentRejectedError);+});++test("refresh presents the biscuit as a bearer and signs the refresh challenge", async () => {+ const id = Identity.generate();+ const fresh = new TextEncoder().encode("fresher-biscuit");+ const client = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({+ "POST /refresh": (req, body) => {+ assert.equal(req.headers.get("authorization"), `Bearer ${Buffer.from(biscuit).toString("base64")}`);+ const r = fromBinary(TokenRefreshRequestSchema, body);+ assert.equal(r.peerId, id.peerId);+ assert.ok(verifyEd25519(id.publicKeyRaw, refreshChallenge(id.peerId, Number(r.timestamp)), r.challengeSignature));+ return proto(toBinary(TokenRefreshResponseSchema, create(TokenRefreshResponseSchema, { biscuitToken: fresh, expiresAt: 99n })));+ },+ }),+ });+ const result = await client.refresh({ identity: id, biscuit });+ assert.deepEqual(result.biscuit, fresh);+ assert.equal(result.expiration, 99);++ const replayed = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({ "POST /refresh": () => new Response("Biscuit already rotated", { status: 401 }) }),+ });+ await assert.rejects(replayed.refresh({ identity: id, biscuit }), (err: unknown) => err instanceof ControlPlaneError && err.status === 401);+});++test("verifyKeysResponse accepts a set vouched for by a trusted key and nothing else", () => {+ const retiring = Identity.generate();+ const resp = signedKeys([cpKey, retiring]);++ // Trusting either key yields the whole set.+ assert.deepEqual(verifyKeysResponse(resp, [cpKey.publicKeyRaw]), [cpKey.publicKeyRaw, retiring.publicKeyRaw]);+ assert.deepEqual(verifyKeysResponse(resp, [retiring.publicKeyRaw]), [cpKey.publicKeyRaw, retiring.publicKeyRaw]);++ assert.throws(() => verifyKeysResponse(resp, []), /no trusted control plane key/);+ assert.throws(() => verifyKeysResponse(resp, [Identity.generate().publicKeyRaw]), /not signed by any trusted/);+ assert.throws(() => verifyKeysResponse(resp, [cpKey.publicKeyRaw], Date.now() + KEYS_RESPONSE_FRESHNESS_MS + 1000), /freshness window/);++ const forged = create(KeysResponseSchema, { ...resp, publicKeys: [Identity.generate().publicKeyRaw, retiring.publicKeyRaw] });+ assert.throws(() => verifyKeysResponse(forged, [retiring.publicKeyRaw]), /not signed by any trusted/);++ const unsigned = create(KeysResponseSchema, { publicKeys: resp.publicKeys, timestamp: resp.timestamp });+ assert.throws(() => verifyKeysResponse(unsigned, [cpKey.publicKeyRaw]), /carries 0 signatures for 2 keys/);+});++test("keys() fetches and verifies against the enrollment key", async () => {+ const client = new ControlPlaneClient({+ url: "http://127.0.0.1:1",+ fetch: fakeFetch({ "GET /keys": () => proto(toBinary(KeysResponseSchema, signedKeys([cpKey]))) }),+ });+ assert.deepEqual(await client.keys([cpKey.publicKeyRaw]), [cpKey.publicKeyRaw]);+ await assert.rejects(client.keys([Identity.generate().publicKeyRaw]), /not signed by any trusted/);+});diff --git a/sdk/js/src/controlplane.ts b/sdk/js/src/controlplane.tsnew file mode 100644index 00000000..14dffc10--- /dev/null+++ b/sdk/js/src/controlplane.ts@@ -0,0 +1,385 @@+// 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.++// Client for the control plane's mesh-protocol surface: protobuf over HTTP+// (api/sam.proto). The operator plane (/admin/*, JSON) is out of scope.++import { create, fromBinary, toBinary } from "@bufbuild/protobuf";+import { enrollChallenge, enrollStatusChallenge, refreshChallenge, registerChallenge } from "./challenges.ts";+import {+ BootstrapEnrollRequestSchema,+ BootstrapEnrollResponseSchema,+ ControlPlaneInfoResponseSchema,+ EnrollRequestSchema,+ EnrollResponseSchema,+ EnrollmentStatus,+ KeysResponseSchema,+ TokenRefreshRequestSchema,+ TokenRefreshResponseSchema,+ type BootstrapEnrollResponse,+ type ControlPlaneInfoResponse,+ type KeysResponse,+} from "./gen/sam_pb.ts";+import type { Identity } from "./identity.ts";+import { verifyEd25519 } from "./identity.ts";++export const PROTOBUF_CONTENT_TYPE = "application/x-protobuf";+export const HEADER_CHALLENGE_TIMESTAMP = "X-Sam-Challenge-Ts";+export const HEADER_CHALLENGE_SIGNATURE = "X-Sam-Challenge-Sig";++/** The role a plain mesh member enrolls with (api.RoleNode). */+export const ROLE_NODE = "sam:role:node";++/** How far a signed /keys response's timestamp may drift from our clock. */+export const KEYS_RESPONSE_FRESHNESS_MS = 5 * 60 * 1000;++const ED25519_PUBLIC_KEY_SIZE = 32;+const MAX_RESPONSE_BYTES = 1024 * 1024;++/** A non-2xx answer from the control plane. */+export class ControlPlaneError extends Error {+ readonly status: number;+ readonly body: string;++ constructor(path: string, status: number, body: string) {+ super(`control plane ${path}: HTTP ${status}${body ? `: ${body.trim()}` : ""}`);+ this.name = "ControlPlaneError";+ this.status = status;+ this.body = body;+ }+}++/** The control plane answered, and the answer is a refusal. */+export class EnrollmentRejectedError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "EnrollmentRejectedError";+ }+}++/** Plaintext http:// to a host that is not loopback; see api.ValidateControlPlaneTransport. */+export class InsecureControlPlaneURLError extends Error {+ constructor(url: string) {+ super(`plaintext http:// control plane URL to a non-loopback host: ${url} (use https://, or set allowInsecure for a network you trust)`);+ this.name = "InsecureControlPlaneURLError";+ }+}++export interface ControlPlaneClientOptions {+ /** Base URL, e.g. https://hub.sam-mesh.dev. */+ url: string;+ /** Accept plaintext http:// to a non-loopback host. Off by default. */+ allowInsecure?: boolean;+ /** Per-request timeout. */+ timeoutMs?: number;+ /** Injection point for tests. Defaults to the global fetch. */+ fetch?: typeof fetch;+}++/** What an approved enrollment hands the caller. */+export interface Enrollment {+ biscuit: Uint8Array;+ /** Unix seconds at which the biscuit expires. */+ expiration: number;+ controlPlanePublicKey: Uint8Array;+ routerAddresses: string[];+}++export interface EnrollBootstrapParams {+ identity: Identity;+ bootstrapToken: string;+ /** Must equal the role the bootstrap token was minted for. Defaults to ROLE_NODE. */+ role?: string;+ labels?: Record<string, string>;+ /** Overrides the control plane's suggested poll interval while pending. */+ pollIntervalMs?: number;+ /** Bounds the wait for an operator to approve a pending enrollment. */+ signal?: AbortSignal;+}++export interface RegisterParams {+ identity: Identity;+ jwt: string;+ role?: string;+ labels?: Record<string, string>;+}++export interface RefreshParams {+ identity: Identity;+ /** The biscuit currently held; only the last one issued is redeemable. */+ biscuit: Uint8Array;+}++export interface RefreshResult {+ biscuit: Uint8Array;+ /** Unix seconds. */+ expiration: number;+}++function isLoopbackHost(host: string): boolean {+ const h = host.replace(/^\[|\]$/g, "");+ return h.toLowerCase() === "localhost" || h === "127.0.0.1" || h === "::1" || /^127\.\d+\.\d+\.\d+$/.test(h);+}++/** Mirrors api.ValidateControlPlaneTransport: https, or http to loopback only. */+export function validateControlPlaneURL(rawUrl: string, allowInsecure = false): URL {+ let u: URL;+ try {+ u = new URL(rawUrl);+ } catch {+ throw new Error(`invalid control plane URL ${JSON.stringify(rawUrl)}`);+ }+ if (u.protocol === "https:") {+ return u;+ }+ if (u.protocol === "http:") {+ if (allowInsecure || isLoopbackHost(u.hostname)) {+ return u;+ }+ throw new InsecureControlPlaneURLError(rawUrl);+ }+ throw new Error(`control plane URL ${JSON.stringify(rawUrl)} must use http:// or https://`);+}++function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {+ return a.length === b.length && a.every((v, i) => v === b[i]);+}++/**+ * Returns the key set if it is fresh and at least one listed key is already+ * trusted and its signature verifies. Mirrors api.VerifyKeysResponse.+ */+export function verifyKeysResponse(resp: KeysResponse, trusted: Uint8Array[], nowMs = Date.now()): Uint8Array[] {+ if (trusted.length === 0) {+ throw new Error("no trusted control plane key to verify /keys against");+ }+ if (resp.signatures.length !== resp.publicKeys.length) {+ throw new Error(`keys response carries ${resp.signatures.length} signatures for ${resp.publicKeys.length} keys`);+ }+ const issued = Number(resp.timestamp);+ if (Math.abs(nowMs - issued) > KEYS_RESPONSE_FRESHNESS_MS) {+ throw new Error(`keys response timestamp ${new Date(issued).toISOString()} is outside the freshness window`);+ }+ // Each signature covers the set and the timestamp, deterministically+ // encoded with the signatures cleared.+ const payload = toBinary(KeysResponseSchema, create(KeysResponseSchema, { publicKeys: resp.publicKeys, timestamp: resp.timestamp }));+ const keys: Uint8Array[] = [];+ let verified = false;+ resp.publicKeys.forEach((pub, i) => {+ if (pub.length !== ED25519_PUBLIC_KEY_SIZE) {+ return;+ }+ keys.push(pub);+ if (verified) {+ return;+ }+ const sig = resp.signatures[i];+ if (sig && trusted.some((t) => bytesEqual(t, pub)) && verifyEd25519(pub, payload, sig)) {+ verified = true;+ }+ });+ if (!verified) {+ throw new Error("keys response is not signed by any trusted control plane key");+ }+ return keys;+}++function abortError(signal: AbortSignal): Error {+ return signal.reason instanceof Error ? signal.reason : new Error("aborted");+}++function sleep(ms: number, signal?: AbortSignal): Promise<void> {+ return new Promise((resolve, reject) => {+ if (signal?.aborted) {+ reject(abortError(signal));+ return;+ }+ const timer = setTimeout(() => {+ signal?.removeEventListener("abort", onAbort);+ resolve();+ }, ms);+ const onAbort = () => {+ clearTimeout(timer);+ reject(abortError(signal as AbortSignal));+ };+ signal?.addEventListener("abort", onAbort, { once: true });+ });+}++export class ControlPlaneClient {+ readonly url: URL;+ readonly #fetch: typeof fetch;+ readonly #timeoutMs: number;++ constructor(options: ControlPlaneClientOptions) {+ this.url = validateControlPlaneURL(options.url, options.allowInsecure ?? false);+ this.#fetch = options.fetch ?? globalThis.fetch;+ this.#timeoutMs = options.timeoutMs ?? 30_000;+ }++ /** GET /info: OIDC settings, router addresses and the ban list. Unauthenticated. */+ async info(): Promise<ControlPlaneInfoResponse> {+ const body = await this.#request("GET", "/info");+ return fromBinary(ControlPlaneInfoResponseSchema, body);+ }++ /**+ * GET /keys: every signing key the control plane currently trusts,+ * verified against a key the caller already trusts (the enrollment key).+ */+ async keys(trusted: Uint8Array[]): Promise<Uint8Array[]> {+ const body = await this.#request("GET", "/keys");+ return verifyKeysResponse(fromBinary(KeysResponseSchema, body), trusted);+ }++ /**+ * POST /enroll with a bootstrap token, then GET /enroll/status until an+ * operator approves the request if the mesh is not on auto-approve.+ */+ async enrollBootstrap(params: EnrollBootstrapParams): Promise<Enrollment> {+ const { identity, signal } = params;+ const role = params.role ?? ROLE_NODE;+ const ts = Date.now();+ const req = create(BootstrapEnrollRequestSchema, {+ bootstrapToken: params.bootstrapToken,+ peerId: identity.peerId,+ publicKey: identity.libp2pPublicKey,+ requestedRole: role,+ labels: params.labels ?? {},+ timestamp: BigInt(ts),+ challengeSignature: identity.sign(enrollChallenge(identity.peerId, ts)),+ });+ let resp = fromBinary(BootstrapEnrollResponseSchema, await this.#request("POST", "/enroll", toBinary(BootstrapEnrollRequestSchema, req)));++ while (resp.status === EnrollmentStatus.PENDING) {+ const waitMs = params.pollIntervalMs ?? Math.max(1, resp.pollIntervalSeconds) * 1000;+ await sleep(waitMs, signal);+ resp = await this.#enrollStatus(identity);+ }+ return enrollmentFromBootstrapResponse(resp);+ }++ async #enrollStatus(identity: Identity): Promise<BootstrapEnrollResponse> {+ const ts = Date.now();+ const sig = identity.sign(enrollStatusChallenge(identity.peerId, ts));+ const body = await this.#request("GET", `/enroll/status?peer_id=${encodeURIComponent(identity.peerId)}`, undefined, {+ [HEADER_CHALLENGE_TIMESTAMP]: String(ts),+ [HEADER_CHALLENGE_SIGNATURE]: Buffer.from(sig).toString("base64url"),+ });+ return fromBinary(BootstrapEnrollResponseSchema, body);+ }++ /** POST /register with an OIDC ID token. */+ async register(params: RegisterParams): Promise<Enrollment> {+ const { identity } = params;+ const ts = Date.now();+ const req = create(EnrollRequestSchema, {+ jwt: params.jwt,+ peerId: identity.peerId,+ publicKey: identity.libp2pPublicKey,+ requestedRole: params.role ?? ROLE_NODE,+ labels: params.labels ?? {},+ timestamp: BigInt(ts),+ challengeSignature: identity.sign(registerChallenge(identity.peerId, ts)),+ });+ const resp = fromBinary(EnrollResponseSchema, await this.#request("POST", "/register", toBinary(EnrollRequestSchema, req)));+ if (resp.errorMessage) {+ throw new EnrollmentRejectedError(`enrollment failed: ${resp.errorMessage}`);+ }+ return checkedEnrollment({+ biscuit: resp.biscuitToken,+ expiration: Number(resp.expiration),+ controlPlanePublicKey: resp.controlPlanePublicKey,+ routerAddresses: resp.routerAddresses,+ });+ }++ /**+ * POST /refresh: trades the biscuit for a fresh one. The old one is+ * spent by this call; callers must persist the result before using it.+ */+ async refresh(params: RefreshParams): Promise<RefreshResult> {+ const { identity } = params;+ const ts = Date.now();+ const req = create(TokenRefreshRequestSchema, {+ timestamp: BigInt(ts),+ challengeSignature: identity.sign(refreshChallenge(identity.peerId, ts)),+ peerId: identity.peerId,+ });+ const body = await this.#request("POST", "/refresh", toBinary(TokenRefreshRequestSchema, req), {+ Authorization: `Bearer ${Buffer.from(params.biscuit).toString("base64")}`,+ });+ const resp = fromBinary(TokenRefreshResponseSchema, body);+ if (resp.errorMessage) {+ throw new EnrollmentRejectedError(`refresh failed: ${resp.errorMessage}`);+ }+ if (resp.biscuitToken.length === 0) {+ throw new Error("refresh returned an empty biscuit");+ }+ return { biscuit: resp.biscuitToken, expiration: Number(resp.expiresAt) };+ }++ async #request(method: "GET" | "POST", path: string, body?: Uint8Array, headers: Record<string, string> = {}): Promise<Uint8Array> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(new Error(`control plane ${path}: timed out after ${this.#timeoutMs}ms`)), this.#timeoutMs);+ try {+ const init: RequestInit = {+ method,+ headers: { Accept: PROTOBUF_CONTENT_TYPE, ...headers },+ signal: controller.signal,+ };+ if (body !== undefined) {+ init.body = Buffer.from(body);+ init.headers = { ...init.headers, "Content-Type": PROTOBUF_CONTENT_TYPE };+ }+ const resp = await this.#fetch(new URL(path, this.url), init);+ const buf = new Uint8Array(await resp.arrayBuffer());+ if (buf.length > MAX_RESPONSE_BYTES) {+ throw new Error(`control plane ${path}: response of ${buf.length} bytes exceeds the ${MAX_RESPONSE_BYTES} byte limit`);+ }+ if (!resp.ok) {+ throw new ControlPlaneError(path, resp.status, new TextDecoder().decode(buf));+ }+ return buf;+ } finally {+ clearTimeout(timer);+ }+ }+}++function enrollmentFromBootstrapResponse(resp: BootstrapEnrollResponse): Enrollment {+ switch (resp.status) {+ case EnrollmentStatus.APPROVED:+ return checkedEnrollment({+ biscuit: resp.biscuitToken,+ expiration: Number(resp.expiration),+ controlPlanePublicKey: resp.controlPlanePublicKey,+ routerAddresses: resp.routerAddresses,+ });+ case EnrollmentStatus.REJECTED:+ throw new EnrollmentRejectedError(`enrollment rejected: ${resp.errorMessage || "no reason given"}`);+ default:+ throw new Error(`unexpected enrollment status ${resp.status}: ${resp.errorMessage}`);+ }+}++function checkedEnrollment(e: Enrollment): Enrollment {+ if (e.biscuit.length === 0) {+ throw new Error("received empty biscuit token");+ }+ if (e.controlPlanePublicKey.length !== ED25519_PUBLIC_KEY_SIZE) {+ throw new Error(`received invalid control plane public key size: ${e.controlPlanePublicKey.length} bytes (expected ${ED25519_PUBLIC_KEY_SIZE})`);+ }+ return e;+}diff --git a/sdk/js/src/credential.ts b/sdk/js/src/credential.tsnew file mode 100644index 00000000..0ed94fb6--- /dev/null+++ b/sdk/js/src/credential.ts@@ -0,0 +1,81 @@+// 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.++import { create, fromBinary, toBinary } from "@bufbuild/protobuf";+import { AuthFrameSchema, AuthResponseSchema, type AuthResponse } from "./gen/sam_pb.ts";++/** What a member holds after enrolling: its biscuit and what it trusts. */+export interface MeshCredential {+ controlPlaneUrl: string;+ /** The biscuit the control plane minted for this identity. */+ biscuit: Uint8Array;+ /** Unix seconds at which the biscuit expires. */+ expiration: number;+ /** Every control plane signing key currently trusted (rotation keeps several valid). */+ controlPlaneKeys: Uint8Array[];+ /** Router multiaddrs, `/p2p/<peer id>` suffixed, as handed out at enrollment. */+ routerAddresses: string[];+}++/** Seconds of validity left on the biscuit; negative once expired. */+export function credentialTimeToLiveSeconds(c: MeshCredential, nowMs = Date.now()): number {+ return c.expiration - Math.floor(nowMs / 1000);+}++/**+ * The first frame on every mesh stream (/sam/auth/1.0.0, /sam/mcp/1.0.0):+ * the caller's biscuit, the service it wants and the agent it speaks for.+ * Framing (varint length prefix) is the transport's job.+ */+export function encodeAuthFrame(biscuit: Uint8Array, targetService = "", agent = ""): Uint8Array {+ return toBinary(AuthFrameSchema, create(AuthFrameSchema, { biscuit, targetService, agent }));+}++/** The peer's answer to an AuthFrame, carrying its own biscuit on success. */+export function decodeAuthResponse(bytes: Uint8Array): AuthResponse {+ return fromBinary(AuthResponseSchema, bytes);+}++interface CredentialJSON {+ control_plane_url: string;+ biscuit: string;+ expiration: number;+ control_plane_keys: string[];+ router_addresses: string[];+}++export function credentialToJSON(c: MeshCredential): string {+ const out: CredentialJSON = {+ control_plane_url: c.controlPlaneUrl,+ biscuit: Buffer.from(c.biscuit).toString("base64"),+ expiration: c.expiration,+ control_plane_keys: c.controlPlaneKeys.map((k) => Buffer.from(k).toString("base64")),+ router_addresses: c.routerAddresses,+ };+ return JSON.stringify(out, null, 2) + "\n";+}++export function credentialFromJSON(text: string): MeshCredential {+ const raw = JSON.parse(text) as Partial<CredentialJSON>;+ if (typeof raw.control_plane_url !== "string" || typeof raw.biscuit !== "string" || typeof raw.expiration !== "number") {+ throw new Error("malformed credential file");+ }+ return {+ controlPlaneUrl: raw.control_plane_url,+ biscuit: new Uint8Array(Buffer.from(raw.biscuit, "base64")),+ expiration: raw.expiration,+ controlPlaneKeys: (raw.control_plane_keys ?? []).map((k) => new Uint8Array(Buffer.from(k, "base64"))),+ routerAddresses: raw.router_addresses ?? [],+ };+}diff --git a/sdk/js/src/gen/sam_pb.ts b/sdk/js/src/gen/sam_pb.tsnew file mode 100644index 00000000..62354e6c--- /dev/null+++ b/sdk/js/src/gen/sam_pb.ts@@ -0,0 +1,1535 @@+// 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.++// @generated by protoc-gen-es v2.15.0 with parameter "target=ts"+// @generated from file sam.proto (package sam.v1, syntax proto3)+/* eslint-disable */++import type { GenEnum, GenFile, GenMessage } from "@bufbuild/protobuf/codegenv2";+import { enumDesc, fileDesc, messageDesc } from "@bufbuild/protobuf/codegenv2";+import type { Message } from "@bufbuild/protobuf";++/**+ * Describes the file sam.proto.+ */+export const file_sam: GenFile = /*@__PURE__*/+ fileDesc("CglzYW0ucHJvdG8SBnNhbS52MSJDCglBdXRoRnJhbWUSDwoHYmlzY3VpdBgBIAEoDBIWCg50YXJnZXRfc2VydmljZRgCIAEoCRINCgVhZ2VudBgDIAEoCSI/CgxBdXRoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRIPCgdiaXNjdWl0GAMgASgMIrkBCglNZXNoRXZlbnQSJAoEdHlwZRgBIAEoDjIWLnNhbS52MS5NZXNoRXZlbnQuVHlwZRIPCgdwZWVyX2lkGAIgASgJEhEKCXRpbWVzdGFtcBgDIAEoAxIWCg5uZXdfcHVibGljX2tleRgEIAEoDBIRCglzaWduYXR1cmUYBSABKAwiNwoEVHlwZRIKCgZCQU5ORUQQABIQCgxLRVlfUk9UQVRJT04QARIRCg1QT0xJQ1lfVVBEQVRFEAIi6wEKDUVucm9sbFJlcXVlc3QSCwoDand0GAEgASgJEg8KB3BlZXJfaWQYAiABKAkSEgoKcHVibGljX2tleRgDIAEoDBIWCg5yZXF1ZXN0ZWRfcm9sZRgEIAEoCRIxCgZsYWJlbHMYBSADKAsyIS5zYW0udjEuRW5yb2xsUmVxdWVzdC5MYWJlbHNFbnRyeRIRCgl0aW1lc3RhbXAYBiABKAMSGwoTY2hhbGxlbmdlX3NpZ25hdHVyZRgHIAEoDBotCgtMYWJlbHNFbnRyeRILCgNrZXkYASABKAkSDQoFdmFsdWUYAiABKAk6AjgBIo4BCg5FbnJvbGxSZXNwb25zZRIVCg1iaXNjdWl0X3Rva2VuGAEgASgMEhUKDWVycm9yX21lc3NhZ2UYAiABKAkSIAoYY29udHJvbF9wbGFuZV9wdWJsaWNfa2V5GAMgASgMEhgKEHJvdXRlcl9hZGRyZXNzZXMYBCADKAkSEgoKZXhwaXJhdGlvbhgFIAEoAyKJAgoWQm9vdHN0cmFwRW5yb2xsUmVxdWVzdBIXCg9ib290c3RyYXBfdG9rZW4YASABKAkSDwoHcGVlcl9pZBgCIAEoCRISCgpwdWJsaWNfa2V5GAMgASgMEhYKDnJlcXVlc3RlZF9yb2xlGAQgASgJEjoKBmxhYmVscxgFIAMoCzIqLnNhbS52MS5Cb290c3RyYXBFbnJvbGxSZXF1ZXN0LkxhYmVsc0VudHJ5EhEKCXRpbWVzdGFtcBgGIAEoAxIbChNjaGFsbGVuZ2Vfc2lnbmF0dXJlGAcgASgMGi0KC0xhYmVsc0VudHJ5EgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCToCOAEi4AEKF0Jvb3RzdHJhcEVucm9sbFJlc3BvbnNlEigKBnN0YXR1cxgBIAEoDjIYLnNhbS52MS5FbnJvbGxtZW50U3RhdHVzEhUKDWJpc2N1aXRfdG9rZW4YAiABKAwSHQoVcG9sbF9pbnRlcnZhbF9zZWNvbmRzGAMgASgFEhUKDWVycm9yX21lc3NhZ2UYBCABKAkSIAoYY29udHJvbF9wbGFuZV9wdWJsaWNfa2V5GAUgASgMEhgKEHJvdXRlcl9hZGRyZXNzZXMYBiADKAkSEgoKZXhwaXJhdGlvbhgHIAEoAyJTCgtTZXJ2aWNlSW5mbxIhCgR0eXBlGAEgASgOMhMuc2FtLnYxLlNlcnZpY2VUeXBlEgwKBG5hbWUYAiABKAkSEwoLZGVzY3JpcHRpb24YAyABKAkiewoOQ29tbWFuZEJhY2tlbmQSDwoHY29tbWFuZBgBIAMoCRIsCgNlbnYYAiADKAsyHy5zYW0udjEuQ29tbWFuZEJhY2tlbmQuRW52RW50cnkaKgoIRW52RW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASKKAQoWUmVnaXN0ZXJTZXJ2aWNlUmVxdWVzdBIkCgdzZXJ2aWNlGAEgASgLMhMuc2FtLnYxLlNlcnZpY2VJbmZvEhQKCnRhcmdldF91cmwYAiABKAlIABIpCgdjb21tYW5kGAMgASgLMhYuc2FtLnYxLkNvbW1hbmRCYWNrZW5kSABCCQoHYmFja2VuZCJpChJEaXNjb3ZlcmVkUHJvdmlkZXISDwoHcGVlcl9pZBgBIAEoCRIXCg9sb2NhbF9wcm94eV91cmwYAiABKAkSEAoIc3J2X25hbWUYAyABKAkSFwoPc3J2X2Rlc2NyaXB0aW9uGAQgASgJIpICCg9TZXJ2aWNlQW5ub3VuY2USDwoHcGVlcl9pZBgBIAEoCRIhCgR0eXBlGAIgASgOMhMuc2FtLnYxLlNlcnZpY2VUeXBlEhQKDHNlcnZpY2VfbmFtZRgDIAEoCRIMCgRrZXlzGAQgAygJEjMKBmxhYmVscxgFIAMoCzIjLnNhbS52MS5TZXJ2aWNlQW5ub3VuY2UuTGFiZWxzRW50cnkSFwoPYWN0aXZlX3JlcXVlc3RzGAYgASgNEhcKD2xhdGVuY3lfZXdtYV9tcxgHIAEoARIRCgl0aW1lc3RhbXAYCCABKAMaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASKHAQoYQ29udHJvbFBsYW5lSW5mb1Jlc3BvbnNlEhMKC29pZGNfaXNzdWVyGAEgASgJEhEKCWNsaWVudF9pZBgCIAEoCRIQCghhdWRpZW5jZRgDIAEoCRIYChByb3V0ZXJfYWRkcmVzc2VzGAQgAygJEhcKD2Jhbm5lZF9wZWVyX2lkcxgFIAMoCSKkAQoSUm91dGVyTGVhc2VSZXF1ZXN0Eg8KB3BlZXJfaWQYASABKAkSEQoJYWRkcmVzc2VzGAIgAygJEg8KB2Jpc2N1aXQYAyABKAwSFwoPY29ubmVjdGVkX3BlZXJzGAQgAygJEhAKCGRodF9zaXplGAUgASgFEhEKCXRpbWVzdGFtcBgGIAEoAxIbChNjaGFsbGVuZ2Vfc2lnbmF0dXJlGAcgASgMIkkKE1JvdXRlckxlYXNlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRISCgpleHBpcmVzX2F0GAMgASgDIpUBCgpQb2xpY3lSb2xlEgwKBG5hbWUYASABKAkSFwoPYWxsb3dlZF90YXJnZXRzGAIgAygJEhgKEGFsbG93ZWRfc2VydmljZXMYAyADKAkSFgoOY3VzdG9tX2RhdGFsb2cYBCADKAkSFgoOYWxsb3dlZF9hZ2VudHMYBSADKAkSFgoOYWxsb3dlZF9sYWJlbHMYBiADKAkiLgoNUG9saWN5QmluZGluZxIMCgRyb2xlGAEgASgJEg8KB21lbWJlcnMYAiADKAkiGAoWUG9saWN5Q29uZmlnR2V0UmVxdWVzdCJlChdQb2xpY3lDb25maWdHZXRSZXNwb25zZRIhCgVyb2xlcxgBIAMoCzISLnNhbS52MS5Qb2xpY3lSb2xlEicKCGJpbmRpbmdzGAIgAygLMhUuc2FtLnYxLlBvbGljeUJpbmRpbmciZwoZUG9saWN5Q29uZmlnVXBkYXRlUmVxdWVzdBIhCgVyb2xlcxgBIAMoCzISLnNhbS52MS5Qb2xpY3lSb2xlEicKCGJpbmRpbmdzGAIgAygLMhUuc2FtLnYxLlBvbGljeUJpbmRpbmciPAoaUG9saWN5Q29uZmlnVXBkYXRlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCSJKCgxLZXlzUmVzcG9uc2USEwoLcHVibGljX2tleXMYASADKAwSEQoJdGltZXN0YW1wGAIgASgDEhIKCnNpZ25hdHVyZXMYAyADKAwiVgoTVG9rZW5SZWZyZXNoUmVxdWVzdBIbChNjaGFsbGVuZ2Vfc2lnbmF0dXJlGAEgASgMEhEKCXRpbWVzdGFtcBgCIAEoAxIPCgdwZWVyX2lkGAMgASgJIlgKFFRva2VuUmVmcmVzaFJlc3BvbnNlEhUKDWJpc2N1aXRfdG9rZW4YASABKAwSEgoKZXhwaXJlc19hdBgCIAEoAxIVCg1lcnJvcl9tZXNzYWdlGAMgASgJIjoKEU5vZGVDYXRhbG9nUmVwb3J0EiUKCHNlcnZpY2VzGAEgAygLMhMuc2FtLnYxLlNlcnZpY2VJbmZvIiUKElRva2VuUmV2b2tlUmVxdWVzdBIPCgdwZWVyX2lkGAEgASgJIjUKE1Rva2VuUmV2b2tlUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCSJSCgtBZ2VudFNlY3JldBIMCgRob3N0GAEgASgJEgwKBGtpbmQYAiABKAkSEwoLaGVhZGVyX25hbWUYAyABKAkSEgoKdmFsdWVfcGF0aBgEIAEoCSJCCgtBZ2VudEVncmVzcxINCgVhbGxvdxgBIAMoCRIkCgdzZWNyZXRzGAIgAygLMhMuc2FtLnYxLkFnZW50U2VjcmV0ImIKDEFnZW50SW5ncmVzcxIhCgR0eXBlGAEgASgOMhMuc2FtLnYxLlNlcnZpY2VUeXBlEgwKBG5hbWUYAiABKAkSDAoEcG9ydBgDIAEoDRITCgtkZXNjcmlwdGlvbhgEIAEoCSKqAQoLQWdlbnRCdW5kbGUSDwoHdmVyc2lvbhgBIAEoCRIQCghhZ2VudF9pZBgCIAEoCRITCgtleHRlcm5hbF9pZBgDIAEoCRIXCg9jcmVkZW50aWFsX3BhdGgYBCABKAkSIwoGZWdyZXNzGAUgASgLMhMuc2FtLnYxLkFnZW50RWdyZXNzEiUKB2luZ3Jlc3MYBiADKAsyFC5zYW0udjEuQWdlbnRJbmdyZXNzIjkKEkFnZW50QXR0YWNoUmVxdWVzdBIjCgZidW5kbGUYASABKAsyEy5zYW0udjEuQWdlbnRCdW5kbGUiUwoTQWdlbnRBdHRhY2hSZXNwb25zZRIVCg1lZ3Jlc3Nfc29ja2V0GAEgASgJEhYKDmluZ3Jlc3Nfc29ja2V0GAIgASgJEg0KBWVycm9yGAMgASgJIiYKEkFnZW50RGV0YWNoUmVxdWVzdBIQCghhZ2VudF9pZBgBIAEoCSI1ChNBZ2VudERldGFjaFJlc3BvbnNlEg8KB3N1Y2Nlc3MYASABKAgSDQoFZXJyb3IYAiABKAkiQAoTQWdlbnRSZWZyZXNoUmVxdWVzdBIQCghhZ2VudF9pZBgBIAEoCRIXCg9jcmVkZW50aWFsX3BhdGgYAiABKAkiSgoUQWdlbnRSZWZyZXNoUmVzcG9uc2USDwoHc3VjY2VzcxgBIAEoCBINCgVlcnJvchgCIAEoCRISCgpleHBpcmVzX2F0GAMgASgDIiYKEkFnZW50U3RhdHVzUmVxdWVzdBIQCghhZ2VudF9pZBgBIAEoCSJ3CgtBZ2VudFN0YXR1cxIQCghhZ2VudF9pZBgBIAEoCRIQCghhdHRhY2hlZBgCIAEoCBIlCgdpbmdyZXNzGAMgAygLMhQuc2FtLnYxLkFnZW50SW5ncmVzcxIdChVjcmVkZW50aWFsX2V4cGlyZXNfYXQYBCABKAMiSQoTQWdlbnRTdGF0dXNSZXNwb25zZRIjCgZhZ2VudHMYASADKAsyEy5zYW0udjEuQWdlbnRTdGF0dXMSDQoFZXJyb3IYAiABKAkiqwEKGElkZW50aXR5RXZpZGVuY2VSZXNwb25zZRIPCgdwZWVyX2lkGAEgASgJEg8KB2Jpc2N1aXQYAiABKAwSGgoSYmlzY3VpdF9leHBpcmVzX2F0GAMgASgDEhkKEWNvbnRyb2xfcGxhbmVfdXJsGAQgASgJEiIKGnRydXN0ZWRfY29udHJvbF9wbGFuZV9rZXlzGAUgAygMEhIKCmNoZWNrZWRfYXQYBiABKAMihwIKFFBlZXJFdmlkZW5jZVJlc3BvbnNlEg8KB3BlZXJfaWQYASABKAkSDwoHYmlzY3VpdBgCIAEoDBIVCg12ZXJpZnlpbmdfa2V5GAMgASgMEg0KBXJvbGVzGAQgAygJEjgKBmxhYmVscxgFIAMoCzIoLnNhbS52MS5QZWVyRXZpZGVuY2VSZXNwb25zZS5MYWJlbHNFbnRyeRISCgpleHBpcmF0aW9uGAYgASgDEhYKDnJldm9jYXRpb25faWRzGAcgAygJEhIKCmNoZWNrZWRfYXQYCCABKAMaLQoLTGFiZWxzRW50cnkSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgJOgI4ASqUAQoQRW5yb2xsbWVudFN0YXR1cxIhCh1FTlJPTExNRU5UX1NUQVRVU19VTlNQRUNJRklFRBAAEh0KGUVOUk9MTE1FTlRfU1RBVFVTX1BFTkRJTkcQARIeChpFTlJPTExNRU5UX1NUQVRVU19BUFBST1ZFRBACEh4KGkVOUk9MTE1FTlRfU1RBVFVTX1JFSkVDVEVEEAMqcwoLU2VydmljZVR5cGUSHAoYU0VSVklDRV9UWVBFX1VOU1BFQ0lGSUVEEAASFAoQU0VSVklDRV9UWVBFX01DUBABEhoKFlNFUlZJQ0VfVFlQRV9JTkZFUkVOQ0UQAhIUChBTRVJWSUNFX1RZUEVfQTJBEANCG1oZZ2l0aHViLmNvbS9nb29nbGUvc2FtL2FwaWIGcHJvdG8z");++/**+ * @generated from message sam.v1.AuthFrame+ */+export type AuthFrame = Message<"sam.v1.AuthFrame"> & {+ /**+ * @generated from field: bytes biscuit = 1;+ */+ biscuit: Uint8Array;++ /**+ * Optional: specific service requested+ *+ * @generated from field: string target_service = 2;+ */+ targetService: string;++ /**+ * The agent this request is made for, as a canonical agent identifier (see+ * api/agent.go). It is the calling node's claim, carried beside the token+ * because Biscuit hides an appended block's facts from the authorizer; the+ * HTTP datapath carries the same claim in HeaderSamAgent.+ *+ * @generated from field: string agent = 3;+ */+ agent: string;+};++/**+ * Describes the message sam.v1.AuthFrame.+ * Use `create(AuthFrameSchema)` to create a new message.+ */+export const AuthFrameSchema: GenMessage<AuthFrame> = /*@__PURE__*/+ messageDesc(file_sam, 0);++/**+ * @generated from message sam.v1.AuthResponse+ */+export type AuthResponse = Message<"sam.v1.AuthResponse"> & {+ /**+ * @generated from field: bool success = 1;+ */+ success: boolean;++ /**+ * populated only if success is false+ *+ * @generated from field: string error = 2;+ */+ error: string;++ /**+ * The server's own Biscuit token (for mutual auth)+ *+ * @generated from field: bytes biscuit = 3;+ */+ biscuit: Uint8Array;+};++/**+ * Describes the message sam.v1.AuthResponse.+ * Use `create(AuthResponseSchema)` to create a new message.+ */+export const AuthResponseSchema: GenMessage<AuthResponse> = /*@__PURE__*/+ messageDesc(file_sam, 1);++/**+ * @generated from message sam.v1.MeshEvent+ */+export type MeshEvent = Message<"sam.v1.MeshEvent"> & {+ /**+ * @generated from field: sam.v1.MeshEvent.Type type = 1;+ */+ type: MeshEvent_Type;++ /**+ * @generated from field: string peer_id = 2;+ */+ peerId: string;++ /**+ * @generated from field: int64 timestamp = 3;+ */+ timestamp: bigint;++ /**+ * @generated from field: bytes new_public_key = 4;+ */+ newPublicKey: Uint8Array;++ /**+ * @generated from field: bytes signature = 5;+ */+ signature: Uint8Array;+};++/**+ * Describes the message sam.v1.MeshEvent.+ * Use `create(MeshEventSchema)` to create a new message.+ */+export const MeshEventSchema: GenMessage<MeshEvent> = /*@__PURE__*/+ messageDesc(file_sam, 2);++/**+ * @generated from enum sam.v1.MeshEvent.Type+ */+export enum MeshEvent_Type {+ /**+ * @generated from enum value: BANNED = 0;+ */+ BANNED = 0,++ /**+ * @generated from enum value: KEY_ROTATION = 1;+ */+ KEY_ROTATION = 1,++ /**+ * @generated from enum value: POLICY_UPDATE = 2;+ */+ POLICY_UPDATE = 2,+}++/**+ * Describes the enum sam.v1.MeshEvent.Type.+ */+export const MeshEvent_TypeSchema: GenEnum<MeshEvent_Type> = /*@__PURE__*/+ enumDesc(file_sam, 2, 0);++/**+ * @generated from message sam.v1.EnrollRequest+ */+export type EnrollRequest = Message<"sam.v1.EnrollRequest"> & {+ /**+ * @generated from field: string jwt = 1;+ */+ jwt: string;++ /**+ * @generated from field: string peer_id = 2;+ */+ peerId: string;++ /**+ * @generated from field: bytes public_key = 3;+ */+ publicKey: Uint8Array;++ /**+ * @generated from field: string requested_role = 4;+ */+ requestedRole: string;++ /**+ * Operator-declared labels (e.g. key "region", see api/labels.go).+ * Validated fail-closed by the control plane and, once attested by the+ * enrollment flow's gates, minted as signed label() facts in the+ * biscuit. Empty means no claims.+ *+ * @generated from field: map<string, string> labels = 5;+ */+ labels: { [key: string]: string };++ /**+ * Proof of possession of public_key's private half: timestamp is unix+ * milliseconds and challenge_signature signs the UTF-8 bytes of+ * "sam:register:<peer_id>:<timestamp>". Required, and peer_id must be+ * derived from public_key. The JWT proves who is asking; this proves+ * they hold the key they are asking to bind, so an identity cannot+ * register (and overwrite) another node's peer_id.+ *+ * @generated from field: int64 timestamp = 6;+ */+ timestamp: bigint;++ /**+ * @generated from field: bytes challenge_signature = 7;+ */+ challengeSignature: Uint8Array;+};++/**+ * Describes the message sam.v1.EnrollRequest.+ * Use `create(EnrollRequestSchema)` to create a new message.+ */+export const EnrollRequestSchema: GenMessage<EnrollRequest> = /*@__PURE__*/+ messageDesc(file_sam, 3);++/**+ * @generated from message sam.v1.EnrollResponse+ */+export type EnrollResponse = Message<"sam.v1.EnrollResponse"> & {+ /**+ * @generated from field: bytes biscuit_token = 1;+ */+ biscuitToken: Uint8Array;++ /**+ * @generated from field: string error_message = 2;+ */+ errorMessage: string;++ /**+ * @generated from field: bytes control_plane_public_key = 3;+ */+ controlPlanePublicKey: Uint8Array;++ /**+ * @generated from field: repeated string router_addresses = 4;+ */+ routerAddresses: string[];++ /**+ * @generated from field: int64 expiration = 5;+ */+ expiration: bigint;+};++/**+ * Describes the message sam.v1.EnrollResponse.+ * Use `create(EnrollResponseSchema)` to create a new message.+ */+export const EnrollResponseSchema: GenMessage<EnrollResponse> = /*@__PURE__*/+ messageDesc(file_sam, 4);++/**+ * @generated from message sam.v1.BootstrapEnrollRequest+ */+export type BootstrapEnrollRequest = Message<"sam.v1.BootstrapEnrollRequest"> & {+ /**+ * @generated from field: string bootstrap_token = 1;+ */+ bootstrapToken: string;++ /**+ * @generated from field: string peer_id = 2;+ */+ peerId: string;++ /**+ * @generated from field: bytes public_key = 3;+ */+ publicKey: Uint8Array;++ /**+ * @generated from field: string requested_role = 4;+ */+ requestedRole: string;++ /**+ * Operator-declared labels; the admin approving the enrollment attests+ * them (see EnrollRequest.labels).+ *+ * @generated from field: map<string, string> labels = 5;+ */+ labels: { [key: string]: string };++ /**+ * Proof of possession of public_key's private half: timestamp is unix+ * milliseconds and challenge_signature signs the UTF-8 bytes of+ * "sam:enroll:<peer_id>:<timestamp>". Required, and peer_id must be+ * derived from public_key: this is what entitles a repeated POST /enroll+ * to re-fetch an existing enrollment's biscuit, so a bootstrap token+ * alone must never satisfy it.+ *+ * @generated from field: int64 timestamp = 6;+ */+ timestamp: bigint;++ /**+ * @generated from field: bytes challenge_signature = 7;+ */+ challengeSignature: Uint8Array;+};++/**+ * Describes the message sam.v1.BootstrapEnrollRequest.+ * Use `create(BootstrapEnrollRequestSchema)` to create a new message.+ */+export const BootstrapEnrollRequestSchema: GenMessage<BootstrapEnrollRequest> = /*@__PURE__*/+ messageDesc(file_sam, 5);++/**+ * BootstrapEnrollResponse answers POST /enroll and GET /enroll/status.+ * Polling GET /enroll/status requires proof of possession of the key+ * submitted at /enroll: alongside the `peer_id` query parameter, the caller+ * sends the X-Sam-Challenge-Ts header (unix milliseconds) and the+ * X-Sam-Challenge-Sig header (unpadded base64url signature over the UTF-8+ * bytes of "sam:enroll-status:<peer_id>:<ts>").+ *+ * @generated from message sam.v1.BootstrapEnrollResponse+ */+export type BootstrapEnrollResponse = Message<"sam.v1.BootstrapEnrollResponse"> & {+ /**+ * @generated from field: sam.v1.EnrollmentStatus status = 1;+ */+ status: EnrollmentStatus;++ /**+ * Populated only if APPROVED+ *+ * @generated from field: bytes biscuit_token = 2;+ */+ biscuitToken: Uint8Array;++ /**+ * Recommended polling wait time+ *+ * @generated from field: int32 poll_interval_seconds = 3;+ */+ pollIntervalSeconds: number;++ /**+ * @generated from field: string error_message = 4;+ */+ errorMessage: string;++ /**+ * Populated only if APPROVED+ *+ * @generated from field: bytes control_plane_public_key = 5;+ */+ controlPlanePublicKey: Uint8Array;++ /**+ * Populated only if APPROVED+ *+ * @generated from field: repeated string router_addresses = 6;+ */+ routerAddresses: string[];++ /**+ * Populated only if APPROVED+ *+ * @generated from field: int64 expiration = 7;+ */+ expiration: bigint;+};++/**+ * Describes the message sam.v1.BootstrapEnrollResponse.+ * Use `create(BootstrapEnrollResponseSchema)` to create a new message.+ */+export const BootstrapEnrollResponseSchema: GenMessage<BootstrapEnrollResponse> = /*@__PURE__*/+ messageDesc(file_sam, 6);++/**+ * @generated from message sam.v1.ServiceInfo+ */+export type ServiceInfo = Message<"sam.v1.ServiceInfo"> & {+ /**+ * @generated from field: sam.v1.ServiceType type = 1;+ */+ type: ServiceType;++ /**+ * @generated from field: string name = 2;+ */+ name: string;++ /**+ * @generated from field: string description = 3;+ */+ description: string;+};++/**+ * Describes the message sam.v1.ServiceInfo.+ * Use `create(ServiceInfoSchema)` to create a new message.+ */+export const ServiceInfoSchema: GenMessage<ServiceInfo> = /*@__PURE__*/+ messageDesc(file_sam, 7);++/**+ * @generated from message sam.v1.CommandBackend+ */+export type CommandBackend = Message<"sam.v1.CommandBackend"> & {+ /**+ * @generated from field: repeated string command = 1;+ */+ command: string[];++ /**+ * @generated from field: map<string, string> env = 2;+ */+ env: { [key: string]: string };+};++/**+ * Describes the message sam.v1.CommandBackend.+ * Use `create(CommandBackendSchema)` to create a new message.+ */+export const CommandBackendSchema: GenMessage<CommandBackend> = /*@__PURE__*/+ messageDesc(file_sam, 8);++/**+ * @generated from message sam.v1.RegisterServiceRequest+ */+export type RegisterServiceRequest = Message<"sam.v1.RegisterServiceRequest"> & {+ /**+ * @generated from field: sam.v1.ServiceInfo service = 1;+ */+ service?: ServiceInfo | undefined;++ /**+ * @generated from oneof sam.v1.RegisterServiceRequest.backend+ */+ backend: {+ /**+ * @generated from field: string target_url = 2;+ */+ value: string;+ case: "targetUrl";+ } | {+ /**+ * @generated from field: sam.v1.CommandBackend command = 3;+ */+ value: CommandBackend;+ case: "command";+ } | { case: undefined; value?: undefined };+};++/**+ * Describes the message sam.v1.RegisterServiceRequest.+ * Use `create(RegisterServiceRequestSchema)` to create a new message.+ */+export const RegisterServiceRequestSchema: GenMessage<RegisterServiceRequest> = /*@__PURE__*/+ messageDesc(file_sam, 9);++/**+ * @generated from message sam.v1.DiscoveredProvider+ */+export type DiscoveredProvider = Message<"sam.v1.DiscoveredProvider"> & {+ /**+ * @generated from field: string peer_id = 1;+ */+ peerId: string;++ /**+ * @generated from field: string local_proxy_url = 2;+ */+ localProxyUrl: string;++ /**+ * @generated from field: string srv_name = 3;+ */+ srvName: string;++ /**+ * @generated from field: string srv_description = 4;+ */+ srvDescription: string;+};++/**+ * Describes the message sam.v1.DiscoveredProvider.+ * Use `create(DiscoveredProviderSchema)` to create a new message.+ */+export const DiscoveredProviderSchema: GenMessage<DiscoveredProvider> = /*@__PURE__*/+ messageDesc(file_sam, 10);++/**+ * ServiceAnnounce is gossiped by a node on per-key topics (see+ * DiscoveryTopic) while those topics have subscribers. It is a routing+ * hint signed at the pubsub layer by the announcing peer: consumers use+ * it for freshness and load awareness, never for authorization.+ *+ * @generated from message sam.v1.ServiceAnnounce+ */+export type ServiceAnnounce = Message<"sam.v1.ServiceAnnounce"> & {+ /**+ * @generated from field: string peer_id = 1;+ */+ peerId: string;++ /**+ * @generated from field: sam.v1.ServiceType type = 2;+ */+ type: ServiceType;++ /**+ * @generated from field: string service_name = 3;+ */+ serviceName: string;++ /**+ * Routing keys served by this service: model IDs for inference,+ * tool names for MCP.+ *+ * @generated from field: repeated string keys = 4;+ */+ keys: string[];++ /**+ * Operator-declared labels (e.g. "region"). Operator claims always+ * take precedence over runtime-derived values.+ *+ * @generated from field: map<string, string> labels = 5;+ */+ labels: { [key: string]: string };++ /**+ * Runtime load hints; zero values mean unknown.+ *+ * @generated from field: uint32 active_requests = 6;+ */+ activeRequests: number;++ /**+ * @generated from field: double latency_ewma_ms = 7;+ */+ latencyEwmaMs: number;++ /**+ * @generated from field: int64 timestamp = 8;+ */+ timestamp: bigint;+};++/**+ * Describes the message sam.v1.ServiceAnnounce.+ * Use `create(ServiceAnnounceSchema)` to create a new message.+ */+export const ServiceAnnounceSchema: GenMessage<ServiceAnnounce> = /*@__PURE__*/+ messageDesc(file_sam, 11);++/**+ * @generated from message sam.v1.ControlPlaneInfoResponse+ */+export type ControlPlaneInfoResponse = Message<"sam.v1.ControlPlaneInfoResponse"> & {+ /**+ * @generated from field: string oidc_issuer = 1;+ */+ oidcIssuer: string;++ /**+ * @generated from field: string client_id = 2;+ */+ clientId: string;++ /**+ * @generated from field: string audience = 3;+ */+ audience: string;++ /**+ * @generated from field: repeated string router_addresses = 4;+ */+ routerAddresses: string[];++ /**+ * The complete set of currently banned peer IDs. Consumers reconcile their+ * local blocklist against this list rather than merging into it, so that a+ * peer the control plane no longer bans is unbanned everywhere without+ * needing an event of its own. MeshEvent_BANNED stays the fast path for+ * sub-second eviction; this is how a node that restarted or was offline+ * when the event was published catches up.+ *+ * @generated from field: repeated string banned_peer_ids = 5;+ */+ bannedPeerIds: string[];+};++/**+ * Describes the message sam.v1.ControlPlaneInfoResponse.+ * Use `create(ControlPlaneInfoResponseSchema)` to create a new message.+ */+export const ControlPlaneInfoResponseSchema: GenMessage<ControlPlaneInfoResponse> = /*@__PURE__*/+ messageDesc(file_sam, 12);++/**+ * @generated from message sam.v1.RouterLeaseRequest+ */+export type RouterLeaseRequest = Message<"sam.v1.RouterLeaseRequest"> & {+ /**+ * @generated from field: string peer_id = 1;+ */+ peerId: string;++ /**+ * @generated from field: repeated string addresses = 2;+ */+ addresses: string[];++ /**+ * @generated from field: bytes biscuit = 3;+ */+ biscuit: Uint8Array;++ /**+ * @generated from field: repeated string connected_peers = 4;+ */+ connectedPeers: string[];++ /**+ * @generated from field: int32 dht_size = 5;+ */+ dhtSize: number;++ /**+ * Proof of possession of the router's enrolled key: timestamp is unix+ * milliseconds and challenge_signature signs the UTF-8 bytes of+ * "sam:routers-lease:<peer_id>:<timestamp>" with the key the router+ * enrolled with. Required. The biscuit alone is not proof: routers hand+ * theirs to every peer they authenticate.+ *+ * @generated from field: int64 timestamp = 6;+ */+ timestamp: bigint;++ /**+ * @generated from field: bytes challenge_signature = 7;+ */+ challengeSignature: Uint8Array;+};++/**+ * Describes the message sam.v1.RouterLeaseRequest.+ * Use `create(RouterLeaseRequestSchema)` to create a new message.+ */+export const RouterLeaseRequestSchema: GenMessage<RouterLeaseRequest> = /*@__PURE__*/+ messageDesc(file_sam, 13);++/**+ * @generated from message sam.v1.RouterLeaseResponse+ */+export type RouterLeaseResponse = Message<"sam.v1.RouterLeaseResponse"> & {+ /**+ * @generated from field: bool success = 1;+ */+ success: boolean;++ /**+ * @generated from field: string error = 2;+ */+ error: string;++ /**+ * @generated from field: int64 expires_at = 3;+ */+ expiresAt: bigint;+};++/**+ * Describes the message sam.v1.RouterLeaseResponse.+ * Use `create(RouterLeaseResponseSchema)` to create a new message.+ */+export const RouterLeaseResponseSchema: GenMessage<RouterLeaseResponse> = /*@__PURE__*/+ messageDesc(file_sam, 14);++/**+ * @generated from message sam.v1.PolicyRole+ */+export type PolicyRole = Message<"sam.v1.PolicyRole"> & {+ /**+ * @generated from field: string name = 1;+ */+ name: string;++ /**+ * @generated from field: repeated string allowed_targets = 2;+ */+ allowedTargets: string[];++ /**+ * @generated from field: repeated string allowed_services = 3;+ */+ allowedServices: string[];++ /**+ * @generated from field: repeated string custom_datalog = 4;+ */+ customDatalog: string[];++ /**+ * Agent namespaces the holder may speak for, e.g. "*.prod.acme.example".+ * An agent claim is the calling node's word, so it is only worth what the+ * control plane attested about that node. Distinct from allowed_targets:+ * being allowed to call an agent is not being allowed to impersonate it.+ *+ * @generated from field: repeated string allowed_agents = 5;+ */+ allowedAgents: string[];++ /**+ * Labels a node with this role may declare at enrollment, as "*", "key=*"+ * or "key=value". A node declares its own labels, so this is what turns a+ * declaration into something the control plane is willing to sign.+ *+ * @generated from field: repeated string allowed_labels = 6;+ */+ allowedLabels: string[];+};++/**+ * Describes the message sam.v1.PolicyRole.+ * Use `create(PolicyRoleSchema)` to create a new message.+ */+export const PolicyRoleSchema: GenMessage<PolicyRole> = /*@__PURE__*/+ messageDesc(file_sam, 15);++/**+ * @generated from message sam.v1.PolicyBinding+ */+export type PolicyBinding = Message<"sam.v1.PolicyBinding"> & {+ /**+ * @generated from field: string role = 1;+ */+ role: string;++ /**+ * @generated from field: repeated string members = 2;+ */+ members: string[];+};++/**+ * Describes the message sam.v1.PolicyBinding.+ * Use `create(PolicyBindingSchema)` to create a new message.+ */+export const PolicyBindingSchema: GenMessage<PolicyBinding> = /*@__PURE__*/+ messageDesc(file_sam, 16);++/**+ * @generated from message sam.v1.PolicyConfigGetRequest+ */+export type PolicyConfigGetRequest = Message<"sam.v1.PolicyConfigGetRequest"> & {+};++/**+ * Describes the message sam.v1.PolicyConfigGetRequest.+ * Use `create(PolicyConfigGetRequestSchema)` to create a new message.+ */+export const PolicyConfigGetRequestSchema: GenMessage<PolicyConfigGetRequest> = /*@__PURE__*/+ messageDesc(file_sam, 17);++/**+ * @generated from message sam.v1.PolicyConfigGetResponse+ */+export type PolicyConfigGetResponse = Message<"sam.v1.PolicyConfigGetResponse"> & {+ /**+ * @generated from field: repeated sam.v1.PolicyRole roles = 1;+ */+ roles: PolicyRole[];++ /**+ * @generated from field: repeated sam.v1.PolicyBinding bindings = 2;+ */+ bindings: PolicyBinding[];+};++/**+ * Describes the message sam.v1.PolicyConfigGetResponse.+ * Use `create(PolicyConfigGetResponseSchema)` to create a new message.+ */+export const PolicyConfigGetResponseSchema: GenMessage<PolicyConfigGetResponse> = /*@__PURE__*/+ messageDesc(file_sam, 18);++/**+ * @generated from message sam.v1.PolicyConfigUpdateRequest+ */+export type PolicyConfigUpdateRequest = Message<"sam.v1.PolicyConfigUpdateRequest"> & {+ /**+ * @generated from field: repeated sam.v1.PolicyRole roles = 1;+ */+ roles: PolicyRole[];++ /**+ * @generated from field: repeated sam.v1.PolicyBinding bindings = 2;+ */+ bindings: PolicyBinding[];+};++/**+ * Describes the message sam.v1.PolicyConfigUpdateRequest.+ * Use `create(PolicyConfigUpdateRequestSchema)` to create a new message.+ */+export const PolicyConfigUpdateRequestSchema: GenMessage<PolicyConfigUpdateRequest> = /*@__PURE__*/+ messageDesc(file_sam, 19);++/**+ * @generated from message sam.v1.PolicyConfigUpdateResponse+ */+export type PolicyConfigUpdateResponse = Message<"sam.v1.PolicyConfigUpdateResponse"> & {+ /**+ * @generated from field: bool success = 1;+ */+ success: boolean;++ /**+ * @generated from field: string error = 2;+ */+ error: string;+};++/**+ * Describes the message sam.v1.PolicyConfigUpdateResponse.+ * Use `create(PolicyConfigUpdateResponseSchema)` to create a new message.+ */+export const PolicyConfigUpdateResponseSchema: GenMessage<PolicyConfigUpdateResponse> = /*@__PURE__*/+ messageDesc(file_sam, 20);++/**+ * @generated from message sam.v1.KeysResponse+ */+export type KeysResponse = Message<"sam.v1.KeysResponse"> & {+ /**+ * @generated from field: repeated bytes public_keys = 1;+ */+ publicKeys: Uint8Array[];++ /**+ * Unix milliseconds at which the set was signed; receivers reject responses+ * outside a short freshness window so a captured set cannot be replayed.+ *+ * @generated from field: int64 timestamp = 2;+ */+ timestamp: bigint;++ /**+ * One ed25519 signature per entry of public_keys, by that key, over the+ * deterministic encoding of this message with signatures cleared. A+ * receiver trusting any key still valid on the control plane can verify+ * the whole set (see api.VerifyKeysResponse).+ *+ * @generated from field: repeated bytes signatures = 3;+ */+ signatures: Uint8Array[];+};++/**+ * Describes the message sam.v1.KeysResponse.+ * Use `create(KeysResponseSchema)` to create a new message.+ */+export const KeysResponseSchema: GenMessage<KeysResponse> = /*@__PURE__*/+ messageDesc(file_sam, 21);++/**+ * @generated from message sam.v1.TokenRefreshRequest+ */+export type TokenRefreshRequest = Message<"sam.v1.TokenRefreshRequest"> & {+ /**+ * Signature with the node key over the UTF-8 bytes of+ * "sam:refresh:<peer_id>:<timestamp>", where peer_id is the one bound in+ * the presented biscuit. Peer- and endpoint-bound so a captured signature+ * verifies nowhere else.+ *+ * @generated from field: bytes challenge_signature = 1;+ */+ challengeSignature: Uint8Array;++ /**+ * Unix milliseconds. Must be within the control plane's freshness window.+ *+ * @generated from field: int64 timestamp = 2;+ */+ timestamp: bigint;++ /**+ * The caller's peer ID. Optional: the control plane normally reads it+ * from the verified biscuit. It is consulted only when the biscuit's+ * signing key has been retired, so the biscuit cannot be verified: the+ * control plane then looks up the enrolled node record by this ID and,+ * if the node was opted in to autonomous recovery, accepts the request+ * when the presented biscuit is byte-identical to the last one it+ * issued and the challenge verifies against the stored public key.+ *+ * @generated from field: string peer_id = 3;+ */+ peerId: string;+};++/**+ * Describes the message sam.v1.TokenRefreshRequest.+ * Use `create(TokenRefreshRequestSchema)` to create a new message.+ */+export const TokenRefreshRequestSchema: GenMessage<TokenRefreshRequest> = /*@__PURE__*/+ messageDesc(file_sam, 22);++/**+ * @generated from message sam.v1.TokenRefreshResponse+ */+export type TokenRefreshResponse = Message<"sam.v1.TokenRefreshResponse"> & {+ /**+ * @generated from field: bytes biscuit_token = 1;+ */+ biscuitToken: Uint8Array;++ /**+ * @generated from field: int64 expires_at = 2;+ */+ expiresAt: bigint;++ /**+ * @generated from field: string error_message = 3;+ */+ errorMessage: string;+};++/**+ * Describes the message sam.v1.TokenRefreshResponse.+ * Use `create(TokenRefreshResponseSchema)` to create a new message.+ */+export const TokenRefreshResponseSchema: GenMessage<TokenRefreshResponse> = /*@__PURE__*/+ messageDesc(file_sam, 23);++/**+ * NodeCatalogReport is the body of POST /nodes/catalog: a node's+ * self-reported list of locally registered services. The reporting peer is+ * taken from the presented biscuit, never from the body, so a node can only+ * ever describe itself. Display-only; carries no authorization weight.+ *+ * @generated from message sam.v1.NodeCatalogReport+ */+export type NodeCatalogReport = Message<"sam.v1.NodeCatalogReport"> & {+ /**+ * @generated from field: repeated sam.v1.ServiceInfo services = 1;+ */+ services: ServiceInfo[];+};++/**+ * Describes the message sam.v1.NodeCatalogReport.+ * Use `create(NodeCatalogReportSchema)` to create a new message.+ */+export const NodeCatalogReportSchema: GenMessage<NodeCatalogReport> = /*@__PURE__*/+ messageDesc(file_sam, 24);++/**+ * @generated from message sam.v1.TokenRevokeRequest+ */+export type TokenRevokeRequest = Message<"sam.v1.TokenRevokeRequest"> & {+ /**+ * @generated from field: string peer_id = 1;+ */+ peerId: string;+};++/**+ * Describes the message sam.v1.TokenRevokeRequest.+ * Use `create(TokenRevokeRequestSchema)` to create a new message.+ */+export const TokenRevokeRequestSchema: GenMessage<TokenRevokeRequest> = /*@__PURE__*/+ messageDesc(file_sam, 25);++/**+ * @generated from message sam.v1.TokenRevokeResponse+ */+export type TokenRevokeResponse = Message<"sam.v1.TokenRevokeResponse"> & {+ /**+ * @generated from field: bool success = 1;+ */+ success: boolean;++ /**+ * @generated from field: string error = 2;+ */+ error: string;+};++/**+ * Describes the message sam.v1.TokenRevokeResponse.+ * Use `create(TokenRevokeResponseSchema)` to create a new message.+ */+export const TokenRevokeResponseSchema: GenMessage<TokenRevokeResponse> = /*@__PURE__*/+ messageDesc(file_sam, 26);++/**+ * AgentSecret configures credential injection for one destination. It carries+ * a path, never a value: secret material must not travel through this API.+ *+ * @generated from message sam.v1.AgentSecret+ */+export type AgentSecret = Message<"sam.v1.AgentSecret"> & {+ /**+ * @generated from field: string host = 1;+ */+ host: string;++ /**+ * bearer | basicauth | customheader+ *+ * @generated from field: string kind = 2;+ */+ kind: string;++ /**+ * customheader only+ *+ * @generated from field: string header_name = 3;+ */+ headerName: string;++ /**+ * @generated from field: string value_path = 4;+ */+ valuePath: string;+};++/**+ * Describes the message sam.v1.AgentSecret.+ * Use `create(AgentSecretSchema)` to create a new message.+ */+export const AgentSecretSchema: GenMessage<AgentSecret> = /*@__PURE__*/+ messageDesc(file_sam, 27);++/**+ * AgentEgress is deny-by-default. Patterns are matched against the destination+ * name taken from the sandbox boundary, never against a resolved address.+ *+ * @generated from message sam.v1.AgentEgress+ */+export type AgentEgress = Message<"sam.v1.AgentEgress"> & {+ /**+ * @generated from field: repeated string allow = 1;+ */+ allow: string[];++ /**+ * @generated from field: repeated sam.v1.AgentSecret secrets = 2;+ */+ secrets: AgentSecret[];+};++/**+ * Describes the message sam.v1.AgentEgress.+ * Use `create(AgentEgressSchema)` to create a new message.+ */+export const AgentEgressSchema: GenMessage<AgentEgress> = /*@__PURE__*/+ messageDesc(file_sam, 28);++/**+ * AgentIngress declares that the agent serves a mesh service. The name is the+ * service half of the mesh host the rest of the mesh dials (see api/names.go);+ * port is where the agent listens inside its sandbox.+ *+ * @generated from message sam.v1.AgentIngress+ */+export type AgentIngress = Message<"sam.v1.AgentIngress"> & {+ /**+ * @generated from field: sam.v1.ServiceType type = 1;+ */+ type: ServiceType;++ /**+ * @generated from field: string name = 2;+ */+ name: string;++ /**+ * @generated from field: uint32 port = 3;+ */+ port: number;++ /**+ * @generated from field: string description = 4;+ */+ description: string;+};++/**+ * Describes the message sam.v1.AgentIngress.+ * Use `create(AgentIngressSchema)` to create a new message.+ */+export const AgentIngressSchema: GenMessage<AgentIngress> = /*@__PURE__*/+ messageDesc(file_sam, 29);++/**+ * AgentBundle is everything the platform declares about one agent. Its+ * canonical form is a YAML file in the agent's own state directory, so that a+ * suspend/resume onto another host carries it with no extra machinery; this+ * message is the transport mirror of that file.+ *+ * @generated from message sam.v1.AgentBundle+ */+export type AgentBundle = Message<"sam.v1.AgentBundle"> & {+ /**+ * @generated from field: string version = 1;+ */+ version: string;++ /**+ * Canonical mesh identifier, without the "agent:" prefix. Dot-separated and+ * DNS-shaped; see api/agent.go for the rules and why they exist.+ *+ * @generated from field: string agent_id = 2;+ */+ agentId: string;++ /**+ * The platform's own identifier, verbatim, kept for audit because the+ * translation into agent_id is not always reversible.+ *+ * @generated from field: string external_id = 3;+ */+ externalId: string;++ /**+ * Path to the workload credential the platform already issues: a projected+ * Kubernetes service-account token, a pod certificate, or an SVID. It is+ * verified at admission against the platform's issuer and then translated+ * into agent facts, the same way OIDC claims are translated at node+ * enrollment. The scheduler needs no mesh credential of its own.+ *+ * @generated from field: string credential_path = 4;+ */+ credentialPath: string;++ /**+ * @generated from field: sam.v1.AgentEgress egress = 5;+ */+ egress?: AgentEgress | undefined;++ /**+ * @generated from field: repeated sam.v1.AgentIngress ingress = 6;+ */+ ingress: AgentIngress[];+};++/**+ * Describes the message sam.v1.AgentBundle.+ * Use `create(AgentBundleSchema)` to create a new message.+ */+export const AgentBundleSchema: GenMessage<AgentBundle> = /*@__PURE__*/+ messageDesc(file_sam, 30);++/**+ * AgentAttachRequest admits an agent. It is idempotent on agent_id: resuming+ * after a crash or a migration is another Attach, not a distinct operation.+ *+ * @generated from message sam.v1.AgentAttachRequest+ */+export type AgentAttachRequest = Message<"sam.v1.AgentAttachRequest"> & {+ /**+ * @generated from field: sam.v1.AgentBundle bundle = 1;+ */+ bundle?: AgentBundle | undefined;+};++/**+ * Describes the message sam.v1.AgentAttachRequest.+ * Use `create(AgentAttachRequestSchema)` to create a new message.+ */+export const AgentAttachRequestSchema: GenMessage<AgentAttachRequest> = /*@__PURE__*/+ messageDesc(file_sam, 31);++/**+ * @generated from message sam.v1.AgentAttachResponse+ */+export type AgentAttachResponse = Message<"sam.v1.AgentAttachResponse"> & {+ /**+ * Sandbox boundary endpoints to wire into the sandbox: named HTTP tunnels+ * (CONNECT, connect-udp) for guest to host, and a reverse channel for host+ * to guest that is empty when the bundle declares no ingress.+ *+ * @generated from field: string egress_socket = 1;+ */+ egressSocket: string;++ /**+ * @generated from field: string ingress_socket = 2;+ */+ ingressSocket: string;++ /**+ * @generated from field: string error = 3;+ */+ error: string;+};++/**+ * Describes the message sam.v1.AgentAttachResponse.+ * Use `create(AgentAttachResponseSchema)` to create a new message.+ */+export const AgentAttachResponseSchema: GenMessage<AgentAttachResponse> = /*@__PURE__*/+ messageDesc(file_sam, 32);++/**+ * AgentDetachRequest stops an agent: ingress is unregistered, channels are+ * closed and credentials dropped. It must leave no residual advertisement.+ *+ * @generated from message sam.v1.AgentDetachRequest+ */+export type AgentDetachRequest = Message<"sam.v1.AgentDetachRequest"> & {+ /**+ * @generated from field: string agent_id = 1;+ */+ agentId: string;+};++/**+ * Describes the message sam.v1.AgentDetachRequest.+ * Use `create(AgentDetachRequestSchema)` to create a new message.+ */+export const AgentDetachRequestSchema: GenMessage<AgentDetachRequest> = /*@__PURE__*/+ messageDesc(file_sam, 33);++/**+ * @generated from message sam.v1.AgentDetachResponse+ */+export type AgentDetachResponse = Message<"sam.v1.AgentDetachResponse"> & {+ /**+ * @generated from field: bool success = 1;+ */+ success: boolean;++ /**+ * @generated from field: string error = 2;+ */+ error: string;+};++/**+ * Describes the message sam.v1.AgentDetachResponse.+ * Use `create(AgentDetachResponseSchema)` to create a new message.+ */+export const AgentDetachResponseSchema: GenMessage<AgentDetachResponse> = /*@__PURE__*/+ messageDesc(file_sam, 34);++/**+ * AgentRefreshRequest hands in a rotated workload credential. Platforms rotate+ * these on their own schedule, which is what bounds how long a stale admission+ * stays usable.+ *+ * @generated from message sam.v1.AgentRefreshRequest+ */+export type AgentRefreshRequest = Message<"sam.v1.AgentRefreshRequest"> & {+ /**+ * @generated from field: string agent_id = 1;+ */+ agentId: string;++ /**+ * @generated from field: string credential_path = 2;+ */+ credentialPath: string;+};++/**+ * Describes the message sam.v1.AgentRefreshRequest.+ * Use `create(AgentRefreshRequestSchema)` to create a new message.+ */+export const AgentRefreshRequestSchema: GenMessage<AgentRefreshRequest> = /*@__PURE__*/+ messageDesc(file_sam, 35);++/**+ * @generated from message sam.v1.AgentRefreshResponse+ */+export type AgentRefreshResponse = Message<"sam.v1.AgentRefreshResponse"> & {+ /**+ * @generated from field: bool success = 1;+ */+ success: boolean;++ /**+ * @generated from field: string error = 2;+ */+ error: string;++ /**+ * @generated from field: int64 expires_at = 3;+ */+ expiresAt: bigint;+};++/**+ * Describes the message sam.v1.AgentRefreshResponse.+ * Use `create(AgentRefreshResponseSchema)` to create a new message.+ */+export const AgentRefreshResponseSchema: GenMessage<AgentRefreshResponse> = /*@__PURE__*/+ messageDesc(file_sam, 36);++/**+ * AgentStatusRequest reports on one agent, or on all of them when agent_id is+ * empty, for a scheduler's reconcile loop.+ *+ * @generated from message sam.v1.AgentStatusRequest+ */+export type AgentStatusRequest = Message<"sam.v1.AgentStatusRequest"> & {+ /**+ * @generated from field: string agent_id = 1;+ */+ agentId: string;+};++/**+ * Describes the message sam.v1.AgentStatusRequest.+ * Use `create(AgentStatusRequestSchema)` to create a new message.+ */+export const AgentStatusRequestSchema: GenMessage<AgentStatusRequest> = /*@__PURE__*/+ messageDesc(file_sam, 37);++/**+ * @generated from message sam.v1.AgentStatus+ */+export type AgentStatus = Message<"sam.v1.AgentStatus"> & {+ /**+ * @generated from field: string agent_id = 1;+ */+ agentId: string;++ /**+ * @generated from field: bool attached = 2;+ */+ attached: boolean;++ /**+ * @generated from field: repeated sam.v1.AgentIngress ingress = 3;+ */+ ingress: AgentIngress[];++ /**+ * @generated from field: int64 credential_expires_at = 4;+ */+ credentialExpiresAt: bigint;+};++/**+ * Describes the message sam.v1.AgentStatus.+ * Use `create(AgentStatusSchema)` to create a new message.+ */+export const AgentStatusSchema: GenMessage<AgentStatus> = /*@__PURE__*/+ messageDesc(file_sam, 38);++/**+ * @generated from message sam.v1.AgentStatusResponse+ */+export type AgentStatusResponse = Message<"sam.v1.AgentStatusResponse"> & {+ /**+ * @generated from field: repeated sam.v1.AgentStatus agents = 1;+ */+ agents: AgentStatus[];++ /**+ * @generated from field: string error = 2;+ */+ error: string;+};++/**+ * Describes the message sam.v1.AgentStatusResponse.+ * Use `create(AgentStatusResponseSchema)` to create a new message.+ */+export const AgentStatusResponseSchema: GenMessage<AgentStatusResponse> = /*@__PURE__*/+ messageDesc(file_sam, 39);++/**+ * @generated from message sam.v1.IdentityEvidenceResponse+ */+export type IdentityEvidenceResponse = Message<"sam.v1.IdentityEvidenceResponse"> & {+ /**+ * @generated from field: string peer_id = 1;+ */+ peerId: string;++ /**+ * @generated from field: bytes biscuit = 2;+ */+ biscuit: Uint8Array;++ /**+ * @generated from field: int64 biscuit_expires_at = 3;+ */+ biscuitExpiresAt: bigint;++ /**+ * @generated from field: string control_plane_url = 4;+ */+ controlPlaneUrl: string;++ /**+ * Ed25519 SPKI DER+ *+ * @generated from field: repeated bytes trusted_control_plane_keys = 5;+ */+ trustedControlPlaneKeys: Uint8Array[];++ /**+ * @generated from field: int64 checked_at = 6;+ */+ checkedAt: bigint;+};++/**+ * Describes the message sam.v1.IdentityEvidenceResponse.+ * Use `create(IdentityEvidenceResponseSchema)` to create a new message.+ */+export const IdentityEvidenceResponseSchema: GenMessage<IdentityEvidenceResponse> = /*@__PURE__*/+ messageDesc(file_sam, 40);++/**+ * @generated from message sam.v1.PeerEvidenceResponse+ */+export type PeerEvidenceResponse = Message<"sam.v1.PeerEvidenceResponse"> & {+ /**+ * @generated from field: string peer_id = 1;+ */+ peerId: string;++ /**+ * @generated from field: bytes biscuit = 2;+ */+ biscuit: Uint8Array;++ /**+ * Ed25519 SPKI DER, member of the trusted set+ *+ * @generated from field: bytes verifying_key = 3;+ */+ verifyingKey: Uint8Array;++ /**+ * @generated from field: repeated string roles = 4;+ */+ roles: string[];++ /**+ * @generated from field: map<string, string> labels = 5;+ */+ labels: { [key: string]: string };++ /**+ * @generated from field: int64 expiration = 6;+ */+ expiration: bigint;++ /**+ * hex+ *+ * @generated from field: repeated string revocation_ids = 7;+ */+ revocationIds: string[];++ /**+ * @generated from field: int64 checked_at = 8;+ */+ checkedAt: bigint;+};++/**+ * Describes the message sam.v1.PeerEvidenceResponse.+ * Use `create(PeerEvidenceResponseSchema)` to create a new message.+ */+export const PeerEvidenceResponseSchema: GenMessage<PeerEvidenceResponse> = /*@__PURE__*/+ messageDesc(file_sam, 41);++/**+ * @generated from enum sam.v1.EnrollmentStatus+ */+export enum EnrollmentStatus {+ /**+ * @generated from enum value: ENROLLMENT_STATUS_UNSPECIFIED = 0;+ */+ UNSPECIFIED = 0,++ /**+ * @generated from enum value: ENROLLMENT_STATUS_PENDING = 1;+ */+ PENDING = 1,++ /**+ * @generated from enum value: ENROLLMENT_STATUS_APPROVED = 2;+ */+ APPROVED = 2,++ /**+ * @generated from enum value: ENROLLMENT_STATUS_REJECTED = 3;+ */+ REJECTED = 3,+}++/**+ * Describes the enum sam.v1.EnrollmentStatus.+ */+export const EnrollmentStatusSchema: GenEnum<EnrollmentStatus> = /*@__PURE__*/+ enumDesc(file_sam, 0);++/**+ * @generated from enum sam.v1.ServiceType+ */+export enum ServiceType {+ /**+ * @generated from enum value: SERVICE_TYPE_UNSPECIFIED = 0;+ */+ UNSPECIFIED = 0,++ /**+ * @generated from enum value: SERVICE_TYPE_MCP = 1;+ */+ MCP = 1,++ /**+ * @generated from enum value: SERVICE_TYPE_INFERENCE = 2;+ */+ INFERENCE = 2,++ /**+ * @generated from enum value: SERVICE_TYPE_A2A = 3;+ */+ A2A = 3,+}++/**+ * Describes the enum sam.v1.ServiceType.+ */+export const ServiceTypeSchema: GenEnum<ServiceType> = /*@__PURE__*/+ enumDesc(file_sam, 1);+diff --git a/sdk/js/src/identity.test.ts b/sdk/js/src/identity.test.tsnew file mode 100644index 00000000..dbd6ed4e--- /dev/null+++ b/sdk/js/src/identity.test.ts@@ -0,0 +1,84 @@+// 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.++import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { test } from "node:test";+import { decodeBase58, encodeBase58 } from "./base58.ts";+import { enrollChallenge } from "./challenges.ts";+import { Identity, libp2pPublicKey, peerIdFromPublicKey, verifyEd25519 } from "./identity.ts";++interface Vector {+ seed: string;+ public_key: string;+ peer_id: string;+ libp2p_private_key: string;+ libp2p_public_key: string;+ challenge: string;+ signature: string;+}++const vectors = (JSON.parse(readFileSync(new URL("../../testdata/identity_vectors.json", import.meta.url), "utf8")) as { vectors: Vector[] }).vectors;+const hex = (s: string) => new Uint8Array(Buffer.from(s, "hex"));+const toHex = (b: Uint8Array) => Buffer.from(b).toString("hex");++test("identity matches go-libp2p for every vector", () => {+ for (const v of vectors) {+ const id = Identity.fromSeed(hex(v.seed));+ assert.equal(toHex(id.publicKeyRaw), v.public_key);+ assert.equal(id.peerId, v.peer_id);+ assert.equal(toHex(id.libp2pPublicKey), v.libp2p_public_key);+ assert.equal(toHex(id.toLibp2pPrivateKey()), v.libp2p_private_key);+ assert.equal(peerIdFromPublicKey(hex(v.public_key)), v.peer_id);+ // ed25519 signatures are deterministic, so the Go signature is reproducible.+ const [, , peer, ts] = v.challenge.split(":");+ assert.equal(toHex(id.sign(enrollChallenge(peer as string, Number(ts)))), v.signature);+ assert.ok(verifyEd25519(id.publicKeyRaw, new TextEncoder().encode(v.challenge), hex(v.signature)));+ }+});++test("libp2p private key round-trips and rejects a mismatched public half", () => {+ const id = Identity.generate();+ const again = Identity.fromLibp2pPrivateKey(id.toLibp2pPrivateKey());+ assert.equal(again.peerId, id.peerId);++ const tampered = id.toLibp2pPrivateKey();+ tampered[tampered.length - 1] = (tampered[tampered.length - 1] ?? 0) ^ 0xff;+ assert.throws(() => Identity.fromLibp2pPrivateKey(tampered), /public half does not match/);+ assert.throws(() => Identity.fromLibp2pPrivateKey(tampered.subarray(1)), /not a libp2p ed25519 private key/);+});++test("generated identities are distinct and self-verify", () => {+ const a = Identity.generate();+ const b = Identity.generate();+ assert.notEqual(a.peerId, b.peerId);+ const msg = new TextEncoder().encode("hello");+ const sig = a.sign(msg);+ assert.ok(a.verify(msg, sig));+ assert.ok(!b.verify(msg, sig));+ assert.ok(!verifyEd25519(new Uint8Array(31), msg, sig));+});++test("libp2pPublicKey refuses the wrong size", () => {+ assert.throws(() => libp2pPublicKey(new Uint8Array(33)), /32 bytes/);+});++test("base58btc round-trips and keeps leading zeros", () => {+ const cases: Uint8Array[] = [new Uint8Array(0), Uint8Array.of(0), Uint8Array.of(0, 0, 1, 2), hex("00ff"), hex("deadbeef")];+ for (const c of cases) {+ assert.deepEqual(decodeBase58(encodeBase58(c)), c);+ }+ assert.equal(encodeBase58(new TextEncoder().encode("Hello World!")), "2NEpo7TZRRrLZSi2U");+ assert.throws(() => decodeBase58("0OIl"), /invalid base58 character/);+});diff --git a/sdk/js/src/identity.ts b/sdk/js/src/identity.tsnew file mode 100644index 00000000..b7ea122f--- /dev/null+++ b/sdk/js/src/identity.ts@@ -0,0 +1,145 @@+// 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.++// A mesh identity is an ed25519 key pair. Its peer ID is the one libp2p+// derives, so the same key works in the SDK, in sam-node and on the wire.++import { createPrivateKey, createPublicKey, sign, verify, type KeyObject } from "node:crypto";+import { encodeBase58 } from "./base58.ts";++const PUBLIC_KEY_SIZE = 32;+const SEED_SIZE = 32;++// libp2p crypto.proto PublicKey{Type: Ed25519 (1), Data: <32 bytes>}.+const LIBP2P_PUBLIC_KEY_PREFIX = Uint8Array.of(0x08, 0x01, 0x12, 0x20);+// libp2p crypto.proto PrivateKey{Type: Ed25519 (1), Data: <seed || public>}.+const LIBP2P_PRIVATE_KEY_PREFIX = Uint8Array.of(0x08, 0x01, 0x12, 0x40);+// multihash: identity function (0x00), digest length 36.+const IDENTITY_MULTIHASH_PREFIX = Uint8Array.of(0x00, 0x24);++// PKCS#8 wrapper for a raw ed25519 seed (RFC 8410): what node:crypto imports.+const PKCS8_ED25519_PREFIX = Uint8Array.of(+ 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,+);+// SubjectPublicKeyInfo wrapper for a raw ed25519 public key (RFC 8410).+const SPKI_ED25519_PREFIX = Uint8Array.of(0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00);++function concat(...parts: Uint8Array[]): Uint8Array {+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));+ let offset = 0;+ for (const p of parts) {+ out.set(p, offset);+ offset += p.length;+ }+ return out;+}++function startsWith(bytes: Uint8Array, prefix: Uint8Array): boolean {+ return prefix.every((b, i) => bytes[i] === b);+}++function publicKeyObject(publicKeyRaw: Uint8Array): KeyObject {+ return createPublicKey({ key: Buffer.from(concat(SPKI_ED25519_PREFIX, publicKeyRaw)), format: "der", type: "spki" });+}++/** The libp2p protobuf encoding of an ed25519 public key. */+export function libp2pPublicKey(publicKeyRaw: Uint8Array): Uint8Array {+ if (publicKeyRaw.length !== PUBLIC_KEY_SIZE) {+ throw new Error(`ed25519 public key must be ${PUBLIC_KEY_SIZE} bytes, got ${publicKeyRaw.length}`);+ }+ return concat(LIBP2P_PUBLIC_KEY_PREFIX, publicKeyRaw);+}++/** The peer ID libp2p derives from an ed25519 public key (base58btc, "12D3Koo..."). */+export function peerIdFromPublicKey(publicKeyRaw: Uint8Array): string {+ return encodeBase58(concat(IDENTITY_MULTIHASH_PREFIX, libp2pPublicKey(publicKeyRaw)));+}++export class Identity {+ readonly #privateKey: KeyObject;+ readonly #publicKey: KeyObject;+ readonly #seed: Uint8Array;+ /** Raw 32-byte ed25519 public key. */+ readonly publicKeyRaw: Uint8Array;+ readonly peerId: string;++ private constructor(seed: Uint8Array) {+ if (seed.length !== SEED_SIZE) {+ throw new Error(`ed25519 seed must be ${SEED_SIZE} bytes, got ${seed.length}`);+ }+ this.#seed = new Uint8Array(seed);+ this.#privateKey = createPrivateKey({+ key: Buffer.from(concat(PKCS8_ED25519_PREFIX, this.#seed)),+ format: "der",+ type: "pkcs8",+ });+ this.#publicKey = createPublicKey(this.#privateKey);+ const spki = new Uint8Array(this.#publicKey.export({ format: "der", type: "spki" }));+ if (spki.length !== SPKI_ED25519_PREFIX.length + PUBLIC_KEY_SIZE || !startsWith(spki, SPKI_ED25519_PREFIX)) {+ throw new Error("unexpected ed25519 public key encoding");+ }+ this.publicKeyRaw = spki.slice(SPKI_ED25519_PREFIX.length);+ this.peerId = peerIdFromPublicKey(this.publicKeyRaw);+ }++ static generate(): Identity {+ const seed = new Uint8Array(SEED_SIZE);+ crypto.getRandomValues(seed);+ return new Identity(seed);+ }++ static fromSeed(seed: Uint8Array): Identity {+ return new Identity(seed);+ }++ /** Loads the libp2p protobuf private key encoding, the format sam-node persists. */+ static fromLibp2pPrivateKey(bytes: Uint8Array): Identity {+ if (bytes.length !== LIBP2P_PRIVATE_KEY_PREFIX.length + 64 || !startsWith(bytes, LIBP2P_PRIVATE_KEY_PREFIX)) {+ throw new Error("not a libp2p ed25519 private key");+ }+ const seed = bytes.subarray(LIBP2P_PRIVATE_KEY_PREFIX.length, LIBP2P_PRIVATE_KEY_PREFIX.length + SEED_SIZE);+ const pub = bytes.subarray(LIBP2P_PRIVATE_KEY_PREFIX.length + SEED_SIZE);+ const id = new Identity(seed);+ if (!pub.every((b, i) => id.publicKeyRaw[i] === b)) {+ throw new Error("libp2p private key: public half does not match the seed");+ }+ return id;+ }++ /** The libp2p protobuf private key encoding (seed || public key). */+ toLibp2pPrivateKey(): Uint8Array {+ return concat(LIBP2P_PRIVATE_KEY_PREFIX, this.#seed, this.publicKeyRaw);+ }++ /** The libp2p protobuf public key encoding, what the control plane stores. */+ get libp2pPublicKey(): Uint8Array {+ return libp2pPublicKey(this.publicKeyRaw);+ }++ sign(data: Uint8Array): Uint8Array {+ return new Uint8Array(sign(null, data, this.#privateKey));+ }++ verify(data: Uint8Array, signature: Uint8Array): boolean {+ return verify(null, data, this.#publicKey, signature);+ }+}++/** Verifies an ed25519 signature with a raw 32-byte public key. */+export function verifyEd25519(publicKeyRaw: Uint8Array, data: Uint8Array, signature: Uint8Array): boolean {+ if (publicKeyRaw.length !== PUBLIC_KEY_SIZE) {+ return false;+ }+ return verify(null, data, publicKeyObject(publicKeyRaw), signature);+}diff --git a/sdk/js/src/index.ts b/sdk/js/src/index.tsnew file mode 100644index 00000000..d66a0002--- /dev/null+++ b/sdk/js/src/index.ts@@ -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.++export { AgentMesh, type AgentMeshOptions, type EnrollOptions } from "./mesh.ts";+export { Identity, peerIdFromPublicKey, libp2pPublicKey, verifyEd25519 } from "./identity.ts";+export {+ ControlPlaneClient,+ ControlPlaneError,+ EnrollmentRejectedError,+ InsecureControlPlaneURLError,+ ROLE_NODE,+ validateControlPlaneURL,+ verifyKeysResponse,+ type ControlPlaneClientOptions,+ type Enrollment,+ type EnrollBootstrapParams,+ type RegisterParams,+ type RefreshParams,+ type RefreshResult,+} from "./controlplane.ts";+export {+ credentialFromJSON,+ credentialTimeToLiveSeconds,+ credentialToJSON,+ decodeAuthResponse,+ encodeAuthFrame,+ type MeshCredential,+} from "./credential.ts";+export { enrollChallenge, enrollStatusChallenge, refreshChallenge, registerChallenge } from "./challenges.ts";diff --git a/sdk/js/src/mesh.test.ts b/sdk/js/src/mesh.test.tsnew file mode 100644index 00000000..2675e7e8--- /dev/null+++ b/sdk/js/src/mesh.test.ts@@ -0,0 +1,146 @@+// 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.++import { create, fromBinary, toBinary } from "@bufbuild/protobuf";+import assert from "node:assert/strict";+import { mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { test } from "node:test";+import { credentialTimeToLiveSeconds, decodeAuthResponse } from "./credential.ts";+import {+ AuthFrameSchema,+ AuthResponseSchema,+ BootstrapEnrollResponseSchema,+ EnrollmentStatus,+ KeysResponseSchema,+ TokenRefreshResponseSchema,+} from "./gen/sam_pb.ts";+import { Identity } from "./identity.ts";+import { AgentMesh } from "./mesh.ts";++const cpKey = Identity.generate();+const text = (s: string) => new TextEncoder().encode(s);++function proto(bytes: Uint8Array): Response {+ return new Response(Buffer.from(bytes), { status: 200, headers: { "Content-Type": "application/x-protobuf" } });+}++/** A control plane that approves everything and hands out numbered biscuits. */+function fakeControlPlane(keysOk = true): { fetch: typeof fetch; issued: number } {+ const state = { issued: 0 };+ const signedKeys = () => {+ const unsigned = create(KeysResponseSchema, { publicKeys: [cpKey.publicKeyRaw], timestamp: BigInt(Date.now()) });+ return create(KeysResponseSchema, { ...unsigned, signatures: [cpKey.sign(toBinary(KeysResponseSchema, unsigned))] });+ };+ const fetch: typeof globalThis.fetch = (async (input: Parameters<typeof globalThis.fetch>[0], init?: RequestInit) => {+ const req = new Request(input, init);+ const path = new URL(req.url).pathname;+ switch (`${req.method} ${path}`) {+ case "POST /enroll":+ state.issued++;+ return proto(+ toBinary(+ BootstrapEnrollResponseSchema,+ create(BootstrapEnrollResponseSchema, {+ status: EnrollmentStatus.APPROVED,+ biscuitToken: text(`biscuit-${state.issued}`),+ controlPlanePublicKey: cpKey.publicKeyRaw,+ routerAddresses: ["/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"],+ expiration: BigInt(Math.floor(Date.now() / 1000) + 3600),+ }),+ ),+ );+ case "POST /refresh":+ state.issued++;+ return proto(toBinary(TokenRefreshResponseSchema, create(TokenRefreshResponseSchema, { biscuitToken: text(`biscuit-${state.issued}`), expiresAt: BigInt(Math.floor(Date.now() / 1000) + 7200) })));+ case "GET /keys":+ return keysOk ? proto(toBinary(KeysResponseSchema, signedKeys())) : new Response("boom", { status: 500 });+ default:+ return new Response(`no route for ${req.method} ${path}`, { status: 404 });+ }+ }) as typeof globalThis.fetch;+ return {+ fetch,+ get issued() {+ return state.issued;+ },+ };+}++test("enroll persists identity and credential, load resumes them, refresh rotates", async () => {+ const dir = await mkdtemp(join(tmpdir(), "sam-sdk-"));+ try {+ const cp = fakeControlPlane();+ const tokenPath = join(dir, "bootstrap.token");+ await writeFile(tokenPath, "sbt_secret\n");++ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir: join(dir, "state"), bootstrapTokenPath: tokenPath, fetch: cp.fetch });+ assert.deepEqual(mesh.credential.biscuit, text("biscuit-1"));+ assert.deepEqual(mesh.credential.controlPlaneKeys, [cpKey.publicKeyRaw]);+ assert.equal(mesh.credential.routerAddresses.length, 1);+ assert.ok(credentialTimeToLiveSeconds(mesh.credential) > 3500);++ // Secrets on disk are owner-only.+ for (const f of ["identity.key", "credential.json"]) {+ assert.equal((await stat(join(dir, "state", f))).mode & 0o777, 0o600, f);+ }+ assert.equal((await stat(join(dir, "state"))).mode & 0o777, 0o700);++ const resumed = await AgentMesh.load({ controlPlaneUrl: "ignored://", stateDir: join(dir, "state"), fetch: cp.fetch });+ assert.equal(resumed.peerId, mesh.peerId);+ assert.deepEqual(resumed.credential.biscuit, text("biscuit-1"));+ assert.equal(resumed.controlPlane.url.toString(), "http://127.0.0.1:1/");++ await resumed.refresh();+ assert.deepEqual(resumed.credential.biscuit, text("biscuit-2"));+ const onDisk = JSON.parse(await readFile(join(dir, "state", "credential.json"), "utf8")) as { biscuit: string };+ assert.equal(Buffer.from(onDisk.biscuit, "base64").toString(), "biscuit-2");++ // Re-enrolling from the same directory keeps the identity.+ const again = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", stateDir: join(dir, "state"), bootstrapToken: "sbt_secret", fetch: cp.fetch });+ assert.equal(again.peerId, mesh.peerId);+ } finally {+ await rm(dir, { recursive: true, force: true });+ }+});++test("enroll works without a state directory and keeps the enrollment key when /keys fails", async () => {+ const cp = fakeControlPlane(false);+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt_secret", fetch: cp.fetch });+ assert.deepEqual(mesh.credential.controlPlaneKeys, [cpKey.publicKeyRaw]);+ await mesh.save();+ await mesh.refresh();+ assert.deepEqual(mesh.credential.biscuit, text("biscuit-2"));+});++test("enroll refuses ambiguous credentials", async () => {+ const cp = fakeControlPlane();+ await assert.rejects(AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", fetch: cp.fetch }), /exactly one of/);+ await assert.rejects(AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "a", jwt: "b", fetch: cp.fetch }), /exactly one of/);+ assert.equal(cp.issued, 0);+});++test("authFrame is the AuthFrame protobuf with this member's biscuit", async () => {+ const cp = fakeControlPlane();+ const mesh = await AgentMesh.enroll({ controlPlaneUrl: "http://127.0.0.1:1", bootstrapToken: "sbt_secret", fetch: cp.fetch });+ const frame = fromBinary(AuthFrameSchema, mesh.authFrame("mcp://calculator", "agent:acme.example:bot"));+ assert.deepEqual(frame.biscuit, text("biscuit-1"));+ assert.equal(frame.targetService, "mcp://calculator");+ assert.equal(frame.agent, "agent:acme.example:bot");++ const resp = decodeAuthResponse(toBinary(AuthResponseSchema, create(AuthResponseSchema, { success: false, error: "denied" })));+ assert.equal(resp.success, false);+ assert.equal(resp.error, "denied");+});diff --git a/sdk/js/src/mesh.ts b/sdk/js/src/mesh.tsnew file mode 100644index 00000000..c614ff47--- /dev/null+++ b/sdk/js/src/mesh.ts@@ -0,0 +1,216 @@+// 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.++import { mkdir, readFile, rename, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { ControlPlaneClient, ROLE_NODE, type Enrollment } from "./controlplane.ts";+import { credentialFromJSON, credentialToJSON, encodeAuthFrame, type MeshCredential } from "./credential.ts";+import { Identity } from "./identity.ts";++const IDENTITY_FILE = "identity.key";+const CREDENTIAL_FILE = "credential.json";++export interface AgentMeshOptions {+ /** Base URL of the control plane, e.g. https://hub.sam-mesh.dev. */+ controlPlaneUrl: string;+ /** Accept plaintext http:// to a non-loopback control plane. Off by default. */+ allowInsecure?: boolean;+ /**+ * Directory that keeps the identity key and the credential across+ * restarts. Without it the identity lives only in this process.+ */+ stateDir?: string;+ /** Use this identity instead of the persisted or a freshly generated one. */+ identity?: Identity;+ /** Role to enroll as. Defaults to ROLE_NODE. */+ role?: string;+ /** Operator-declared labels, e.g. { region: "eu" }. */+ labels?: Record<string, string>;+ /** Injection point for tests. */+ fetch?: typeof fetch;+}++export interface EnrollOptions extends AgentMeshOptions {+ /** A bootstrap token value, when the caller already holds it in memory. */+ bootstrapToken?: string;+ /** Path of a file holding the bootstrap token. Preferred over a value. */+ bootstrapTokenPath?: string;+ /** An OIDC ID token, for meshes that enroll identities interactively. */+ jwt?: string;+ /** Bounds the wait for an operator to approve a pending enrollment. */+ signal?: AbortSignal;+ /** Overrides the control plane's suggested poll interval while pending. */+ pollIntervalMs?: number;+}++/**+ * A member of the mesh: an identity, the credential the control plane minted+ * for it, and the client that keeps that credential fresh.+ *+ * This is the enrollment half of the SDK. Joining the mesh over libp2p and+ * serving or calling MCP tools build on top of it (see sdk/README.md).+ */+export class AgentMesh {+ readonly identity: Identity;+ readonly controlPlane: ControlPlaneClient;+ #credential: MeshCredential;+ readonly #stateDir: string | undefined;++ private constructor(identity: Identity, controlPlane: ControlPlaneClient, credential: MeshCredential, stateDir: string | undefined) {+ this.identity = identity;+ this.controlPlane = controlPlane;+ this.#credential = credential;+ this.#stateDir = stateDir;+ }++ get peerId(): string {+ return this.identity.peerId;+ }++ get credential(): MeshCredential {+ return this.#credential;+ }++ /**+ * Enrolls with the control plane and returns a member holding a credential.+ * Exactly one of bootstrapToken, bootstrapTokenPath or jwt must be given.+ */+ static async enroll(options: EnrollOptions): Promise<AgentMesh> {+ const given = [options.bootstrapToken, options.bootstrapTokenPath, options.jwt].filter((v) => v !== undefined).length;+ if (given !== 1) {+ throw new Error("exactly one of bootstrapToken, bootstrapTokenPath or jwt is required");+ }+ const identity = options.identity ?? (await loadIdentity(options.stateDir)) ?? Identity.generate();+ const controlPlane = newClient(options);+ const role = options.role ?? ROLE_NODE;++ let enrollment: Enrollment;+ if (options.jwt !== undefined) {+ enrollment = await controlPlane.register({ identity, jwt: options.jwt, role, ...labelsOf(options) });+ } else {+ const bootstrapToken = options.bootstrapTokenPath !== undefined ? (await readFile(options.bootstrapTokenPath, "utf8")).trim() : (options.bootstrapToken as string);+ enrollment = await controlPlane.enrollBootstrap({+ identity,+ bootstrapToken,+ role,+ ...labelsOf(options),+ ...(options.pollIntervalMs !== undefined ? { pollIntervalMs: options.pollIntervalMs } : {}),+ ...(options.signal !== undefined ? { signal: options.signal } : {}),+ });+ }++ // Widen trust from the one key the enrollment carries to every key the+ // control plane currently signs with, so peers holding credentials from+ // a retiring key still verify. Best effort, as in sam-node.+ let controlPlaneKeys = [enrollment.controlPlanePublicKey];+ try {+ controlPlaneKeys = await controlPlane.keys(controlPlaneKeys);+ } catch {+ // The enrollment key alone still works until the next sync.+ }++ const mesh = new AgentMesh(+ identity,+ controlPlane,+ {+ controlPlaneUrl: controlPlane.url.toString(),+ biscuit: enrollment.biscuit,+ expiration: enrollment.expiration,+ controlPlaneKeys,+ routerAddresses: enrollment.routerAddresses,+ },+ options.stateDir,+ );+ await mesh.save();+ return mesh;+ }++ /** Resumes a member from a state directory written by an earlier enroll(). */+ static async load(options: AgentMeshOptions & { stateDir: string }): Promise<AgentMesh> {+ const identity = options.identity ?? (await loadIdentity(options.stateDir));+ if (!identity) {+ throw new Error(`no identity in ${options.stateDir}; enroll first`);+ }+ const credential = credentialFromJSON(await readFile(join(options.stateDir, CREDENTIAL_FILE), "utf8"));+ return new AgentMesh(identity, newClient({ ...options, controlPlaneUrl: credential.controlPlaneUrl }), credential, options.stateDir);+ }++ /**+ * Trades the current biscuit for a fresh one and persists it. The control+ * plane redeems only the last biscuit it issued, so a lost refresh result+ * means re-enrolling; persisting before returning keeps that rare.+ */+ async refresh(): Promise<MeshCredential> {+ const result = await this.controlPlane.refresh({ identity: this.identity, biscuit: this.#credential.biscuit });+ let controlPlaneKeys = this.#credential.controlPlaneKeys;+ try {+ controlPlaneKeys = await this.controlPlane.keys(controlPlaneKeys);+ } catch {+ // Keep the previous set; a failed /keys sync must not cost the new biscuit.+ }+ this.#credential = { ...this.#credential, biscuit: result.biscuit, expiration: result.expiration, controlPlaneKeys };+ await this.save();+ return this.#credential;+ }++ /**+ * The frame that opens every stream to a peer: this member's biscuit plus+ * the service it wants (e.g. "mcp://calculator") and the agent it speaks for.+ */+ authFrame(targetService = "", agent = ""): Uint8Array {+ return encodeAuthFrame(this.#credential.biscuit, targetService, agent);+ }++ /** Writes identity and credential to the state directory, if one is configured. */+ async save(): Promise<void> {+ if (this.#stateDir === undefined) {+ return;+ }+ await mkdir(this.#stateDir, { recursive: true, mode: 0o700 });+ await writeAtomic(join(this.#stateDir, IDENTITY_FILE), this.identity.toLibp2pPrivateKey(), 0o600);+ await writeAtomic(join(this.#stateDir, CREDENTIAL_FILE), credentialToJSON(this.#credential), 0o600);+ }+}++function newClient(options: AgentMeshOptions): ControlPlaneClient {+ return new ControlPlaneClient({+ url: options.controlPlaneUrl,+ allowInsecure: options.allowInsecure ?? false,+ ...(options.fetch !== undefined ? { fetch: options.fetch } : {}),+ });+}++function labelsOf(options: AgentMeshOptions): { labels?: Record<string, string> } {+ return options.labels !== undefined ? { labels: options.labels } : {};+}++async function loadIdentity(stateDir: string | undefined): Promise<Identity | undefined> {+ if (stateDir === undefined) {+ return undefined;+ }+ try {+ return Identity.fromLibp2pPrivateKey(new Uint8Array(await readFile(join(stateDir, IDENTITY_FILE))));+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {+ return undefined;+ }+ throw err;+ }+}++async function writeAtomic(path: string, data: Uint8Array | string, mode: number): Promise<void> {+ const tmp = `${path}.tmp`;+ await writeFile(tmp, data, { mode });+ await rename(tmp, path);+}diff --git a/sdk/js/tsconfig.build.json b/sdk/js/tsconfig.build.jsonnew file mode 100644index 00000000..dca5799d--- /dev/null+++ b/sdk/js/tsconfig.build.json@@ -0,0 +1,11 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": false,+ "declaration": true,+ "outDir": "dist",+ "rootDir": "src"+ },+ "include": ["src/**/*.ts"],+ "exclude": ["src/**/*.test.ts"]+}diff --git a/sdk/js/tsconfig.json b/sdk/js/tsconfig.jsonnew file mode 100644index 00000000..70811de8--- /dev/null+++ b/sdk/js/tsconfig.json@@ -0,0 +1,19 @@+{+ "compilerOptions": {+ "target": "es2022",+ "module": "nodenext",+ "moduleResolution": "nodenext",+ "lib": ["es2022"],+ "types": ["node"],+ "strict": true,+ "noUncheckedIndexedAccess": true,+ "exactOptionalPropertyTypes": true,+ "verbatimModuleSyntax": true,+ "allowImportingTsExtensions": true,+ "rewriteRelativeImportExtensions": true,+ "isolatedModules": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["src/**/*.ts"]+}diff --git a/sdk/js/tsconfig.test.json b/sdk/js/tsconfig.test.jsonnew file mode 100644index 00000000..8df4e2ea--- /dev/null+++ b/sdk/js/tsconfig.test.json@@ -0,0 +1,9 @@+{+ "extends": "./tsconfig.json",+ "compilerOptions": {+ "noEmit": false,+ "outDir": "build",+ "rootDir": "src"+ },+ "include": ["src/**/*.ts"]+}diff --git a/sdk/python/README.md b/sdk/python/README.mdnew file mode 100644index 00000000..b853843e--- /dev/null+++ b/sdk/python/README.md@@ -0,0 +1,64 @@+# agent-mesh (Python)++Native Python SDK for joining a SAM agent mesh from inside the agent+process. It replaces the `sam-node` sidecar for agents written in Python.+Import it as `agent_mesh`.++Status: **milestone 1** (identity, enrollment, credential refresh). The+libp2p transport, service discovery and MCP over the mesh are the next+milestones; see [../README.md](../README.md) for the plan.++## Install++```bash+pip install -e 'sdk/python[test]'+```++Runtime dependencies are `cryptography` (ed25519) and `protobuf`.++## Use++```python+from agent_mesh import AgentMesh++mesh = AgentMesh.enroll(+ "https://hub.sam-mesh.dev",+ bootstrap_token_path="/run/secrets/sam-bootstrap-token",+ state_dir="~/.config/sam-mesh/agent",+)+print(mesh.peer_id) # 12D3Koo...+print(mesh.credential.time_to_live_seconds())+mesh.refresh() # trades the biscuit for a fresh one++# Later, in a new process:+mesh = AgentMesh.load("~/.config/sam-mesh/agent")+frame = mesh.auth_frame("mcp://calculator") # first frame on a mesh stream+```++`enroll` takes exactly one of `bootstrap_token_path`, `bootstrap_token` or+`jwt`. Read tokens from a file or the environment; do not put them on a+command line.++A plaintext `http://` control plane is accepted only on loopback. Pass+`allow_insecure=True` for a network you trust.++## Layout++- `agent_mesh.identity`: ed25519 key pair, libp2p key encodings, peer ID.+- `agent_mesh.controlplane`: `/info`, `/keys`, `/enroll`, `/enroll/status`,+ `/register`, `/refresh`, with the proof-of-possession challenges from+ `api/network.go`.+- `agent_mesh.credential`: what a member holds, `AuthFrame` encoding.+- `agent_mesh.mesh`: `AgentMesh`, persistence under a state directory+ (`identity.key` in the libp2p private key encoding, `credential.json`).+- `agent_mesh._proto`: generated from `api/sam.proto` by+ `hack/gen-sdk-proto.sh`.++## Test++```bash+pytest sdk/python/tests # unit tests, fake control plane+go test ./tests/integration -run TestNativeSDKs # against a real control plane+```++The integration test skips unless `agent_mesh` imports in `python3`.diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlnew file mode 100644index 00000000..dd906665--- /dev/null+++ b/sdk/python/pyproject.toml@@ -0,0 +1,31 @@+[build-system]+requires = ["hatchling>=1.25"]+build-backend = "hatchling.build"++[project]+name = "agent-mesh"+version = "0.1.0"+description = "Native SDK for joining a SAM agent mesh from inside a Python agent process"+readme = "README.md"+license = "Apache-2.0"+requires-python = ">=3.10"+dependencies = [+ "cryptography>=42",+ # py-libp2p (the next milestone) requires protobuf<7; stay co-installable.+ "protobuf>=4.25,<7",+]++[project.optional-dependencies]+test = [+ "pytest>=8",+]++[project.urls]+Homepage = "https://github.com/google/sam"+Source = "https://github.com/google/sam/tree/main/sdk/python"++[tool.hatch.build.targets.wheel]+packages = ["src/agent_mesh"]++[tool.pytest.ini_options]+testpaths = ["tests"]diff --git a/sdk/python/src/agent_mesh/__init__.py b/sdk/python/src/agent_mesh/__init__.pynew file mode 100644index 00000000..cfb10ebf--- /dev/null+++ b/sdk/python/src/agent_mesh/__init__.py@@ -0,0 +1,57 @@+# 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.++"""Native SDK for joining a SAM agent mesh from inside a Python process."""++from .challenges import enroll_challenge, enroll_status_challenge, refresh_challenge, register_challenge+from .controlplane import (+ ROLE_NODE,+ ControlPlaneClient,+ ControlPlaneError,+ Enrollment,+ EnrollmentRejectedError,+ InsecureControlPlaneURLError,+ RefreshResult,+ validate_control_plane_url,+ verify_keys_response,+)+from .credential import MeshCredential, decode_auth_response, encode_auth_frame+from .identity import Identity, libp2p_public_key, peer_id_from_public_key, verify_ed25519+from .mesh import AgentMesh++__version__ = "0.1.0"++__all__ = [+ "AgentMesh",+ "ControlPlaneClient",+ "ControlPlaneError",+ "Enrollment",+ "EnrollmentRejectedError",+ "Identity",+ "InsecureControlPlaneURLError",+ "MeshCredential",+ "ROLE_NODE",+ "RefreshResult",+ "decode_auth_response",+ "encode_auth_frame",+ "enroll_challenge",+ "enroll_status_challenge",+ "libp2p_public_key",+ "peer_id_from_public_key",+ "refresh_challenge",+ "register_challenge",+ "validate_control_plane_url",+ "verify_ed25519",+ "verify_keys_response",+]diff --git a/sdk/python/src/agent_mesh/_proto/__init__.py b/sdk/python/src/agent_mesh/_proto/__init__.pynew file mode 100644index 00000000..6d8dc108--- /dev/null+++ b/sdk/python/src/agent_mesh/_proto/__init__.py@@ -0,0 +1 @@+# Generated protobuf bindings for api/sam.proto; regenerate with hack/gen-sdk-proto.sh.diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.py b/sdk/python/src/agent_mesh/_proto/sam_pb2.pynew file mode 100644index 00000000..450b8e74--- /dev/null+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.py@@ -0,0 +1,134 @@+# -*- coding: utf-8 -*-+# Generated by the protocol buffer compiler. DO NOT EDIT!+# source: sam.proto+"""Generated protocol buffer code."""+from google.protobuf.internal import builder as _builder+from google.protobuf import descriptor as _descriptor+from google.protobuf import descriptor_pool as _descriptor_pool+from google.protobuf import symbol_database as _symbol_database+# @@protoc_insertion_point(imports)++_sym_db = _symbol_database.Default()+++++DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\tsam.proto\x12\x06sam.v1\"C\n\tAuthFrame\x12\x0f\n\x07\x62iscuit\x18\x01 \x01(\x0c\x12\x16\n\x0etarget_service\x18\x02 \x01(\t\x12\r\n\x05\x61gent\x18\x03 \x01(\t\"?\n\x0c\x41uthResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\"\xb9\x01\n\tMeshEvent\x12$\n\x04type\x18\x01 \x01(\x0e\x32\x16.sam.v1.MeshEvent.Type\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x11\n\ttimestamp\x18\x03 \x01(\x03\x12\x16\n\x0enew_public_key\x18\x04 \x01(\x0c\x12\x11\n\tsignature\x18\x05 \x01(\x0c\"7\n\x04Type\x12\n\n\x06\x42\x41NNED\x10\x00\x12\x10\n\x0cKEY_ROTATION\x10\x01\x12\x11\n\rPOLICY_UPDATE\x10\x02\"\xeb\x01\n\rEnrollRequest\x12\x0b\n\x03jwt\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12\x31\n\x06labels\x18\x05 \x03(\x0b\x32!.sam.v1.EnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8e\x01\n\x0e\x45nrollResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x15\n\rerror_message\x18\x02 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x03 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x12\n\nexpiration\x18\x05 \x01(\x03\"\x89\x02\n\x16\x42ootstrapEnrollRequest\x12\x17\n\x0f\x62ootstrap_token\x18\x01 \x01(\t\x12\x0f\n\x07peer_id\x18\x02 \x01(\t\x12\x12\n\npublic_key\x18\x03 \x01(\x0c\x12\x16\n\x0erequested_role\x18\x04 \x01(\t\x12:\n\x06labels\x18\x05 \x03(\x0b\x32*.sam.v1.BootstrapEnrollRequest.LabelsEntry\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe0\x01\n\x17\x42ootstrapEnrollResponse\x12(\n\x06status\x18\x01 \x01(\x0e\x32\x18.sam.v1.EnrollmentStatus\x12\x15\n\rbiscuit_token\x18\x02 \x01(\x0c\x12\x1d\n\x15poll_interval_seconds\x18\x03 \x01(\x05\x12\x15\n\rerror_message\x18\x04 \x01(\t\x12 \n\x18\x63ontrol_plane_public_key\x18\x05 \x01(\x0c\x12\x18\n\x10router_addresses\x18\x06 \x03(\t\x12\x12\n\nexpiration\x18\x07 \x01(\x03\"S\n\x0bServiceInfo\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x13\n\x0b\x64\x65scription\x18\x03 \x01(\t\"{\n\x0e\x43ommandBackend\x12\x0f\n\x07\x63ommand\x18\x01 \x03(\t\x12,\n\x03\x65nv\x18\x02 \x03(\x0b\x32\x1f.sam.v1.CommandBackend.EnvEntry\x1a*\n\x08\x45nvEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x8a\x01\n\x16RegisterServiceRequest\x12$\n\x07service\x18\x01 \x01(\x0b\x32\x13.sam.v1.ServiceInfo\x12\x14\n\ntarget_url\x18\x02 \x01(\tH\x00\x12)\n\x07\x63ommand\x18\x03 \x01(\x0b\x32\x16.sam.v1.CommandBackendH\x00\x42\t\n\x07\x62\x61\x63kend\"i\n\x12\x44iscoveredProvider\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x17\n\x0flocal_proxy_url\x18\x02 \x01(\t\x12\x10\n\x08srv_name\x18\x03 \x01(\t\x12\x17\n\x0fsrv_description\x18\x04 \x01(\t\"\x92\x02\n\x0fServiceAnnounce\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12!\n\x04type\x18\x02 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x14\n\x0cservice_name\x18\x03 \x01(\t\x12\x0c\n\x04keys\x18\x04 \x03(\t\x12\x33\n\x06labels\x18\x05 \x03(\x0b\x32#.sam.v1.ServiceAnnounce.LabelsEntry\x12\x17\n\x0f\x61\x63tive_requests\x18\x06 \x01(\r\x12\x17\n\x0flatency_ewma_ms\x18\x07 \x01(\x01\x12\x11\n\ttimestamp\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\x87\x01\n\x18\x43ontrolPlaneInfoResponse\x12\x13\n\x0boidc_issuer\x18\x01 \x01(\t\x12\x11\n\tclient_id\x18\x02 \x01(\t\x12\x10\n\x08\x61udience\x18\x03 \x01(\t\x12\x18\n\x10router_addresses\x18\x04 \x03(\t\x12\x17\n\x0f\x62\x61nned_peer_ids\x18\x05 \x03(\t\"\xa4\x01\n\x12RouterLeaseRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x11\n\taddresses\x18\x02 \x03(\t\x12\x0f\n\x07\x62iscuit\x18\x03 \x01(\x0c\x12\x17\n\x0f\x63onnected_peers\x18\x04 \x03(\t\x12\x10\n\x08\x64ht_size\x18\x05 \x01(\x05\x12\x11\n\ttimestamp\x18\x06 \x01(\x03\x12\x1b\n\x13\x63hallenge_signature\x18\x07 \x01(\x0c\"I\n\x13RouterLeaseResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"\x95\x01\n\nPolicyRole\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x17\n\x0f\x61llowed_targets\x18\x02 \x03(\t\x12\x18\n\x10\x61llowed_services\x18\x03 \x03(\t\x12\x16\n\x0e\x63ustom_datalog\x18\x04 \x03(\t\x12\x16\n\x0e\x61llowed_agents\x18\x05 \x03(\t\x12\x16\n\x0e\x61llowed_labels\x18\x06 \x03(\t\".\n\rPolicyBinding\x12\x0c\n\x04role\x18\x01 \x01(\t\x12\x0f\n\x07members\x18\x02 \x03(\t\"\x18\n\x16PolicyConfigGetRequest\"e\n\x17PolicyConfigGetResponse\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"g\n\x19PolicyConfigUpdateRequest\x12!\n\x05roles\x18\x01 \x03(\x0b\x32\x12.sam.v1.PolicyRole\x12\'\n\x08\x62indings\x18\x02 \x03(\x0b\x32\x15.sam.v1.PolicyBinding\"<\n\x1aPolicyConfigUpdateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"J\n\x0cKeysResponse\x12\x13\n\x0bpublic_keys\x18\x01 \x03(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x12\n\nsignatures\x18\x03 \x03(\x0c\"V\n\x13TokenRefreshRequest\x12\x1b\n\x13\x63hallenge_signature\x18\x01 \x01(\x0c\x12\x11\n\ttimestamp\x18\x02 \x01(\x03\x12\x0f\n\x07peer_id\x18\x03 \x01(\t\"X\n\x14TokenRefreshResponse\x12\x15\n\rbiscuit_token\x18\x01 \x01(\x0c\x12\x12\n\nexpires_at\x18\x02 \x01(\x03\x12\x15\n\rerror_message\x18\x03 \x01(\t\":\n\x11NodeCatalogReport\x12%\n\x08services\x18\x01 \x03(\x0b\x32\x13.sam.v1.ServiceInfo\"%\n\x12TokenRevokeRequest\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\"5\n\x13TokenRevokeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"R\n\x0b\x41gentSecret\x12\x0c\n\x04host\x18\x01 \x01(\t\x12\x0c\n\x04kind\x18\x02 \x01(\t\x12\x13\n\x0bheader_name\x18\x03 \x01(\t\x12\x12\n\nvalue_path\x18\x04 \x01(\t\"B\n\x0b\x41gentEgress\x12\r\n\x05\x61llow\x18\x01 \x03(\t\x12$\n\x07secrets\x18\x02 \x03(\x0b\x32\x13.sam.v1.AgentSecret\"b\n\x0c\x41gentIngress\x12!\n\x04type\x18\x01 \x01(\x0e\x32\x13.sam.v1.ServiceType\x12\x0c\n\x04name\x18\x02 \x01(\t\x12\x0c\n\x04port\x18\x03 \x01(\r\x12\x13\n\x0b\x64\x65scription\x18\x04 \x01(\t\"\xaa\x01\n\x0b\x41gentBundle\x12\x0f\n\x07version\x18\x01 \x01(\t\x12\x10\n\x08\x61gent_id\x18\x02 \x01(\t\x12\x13\n\x0b\x65xternal_id\x18\x03 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x04 \x01(\t\x12#\n\x06\x65gress\x18\x05 \x01(\x0b\x32\x13.sam.v1.AgentEgress\x12%\n\x07ingress\x18\x06 \x03(\x0b\x32\x14.sam.v1.AgentIngress\"9\n\x12\x41gentAttachRequest\x12#\n\x06\x62undle\x18\x01 \x01(\x0b\x32\x13.sam.v1.AgentBundle\"S\n\x13\x41gentAttachResponse\x12\x15\n\regress_socket\x18\x01 \x01(\t\x12\x16\n\x0eingress_socket\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\"&\n\x12\x41gentDetachRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"5\n\x13\x41gentDetachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"@\n\x13\x41gentRefreshRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x17\n\x0f\x63redential_path\x18\x02 \x01(\t\"J\n\x14\x41gentRefreshResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\r\n\x05\x65rror\x18\x02 \x01(\t\x12\x12\n\nexpires_at\x18\x03 \x01(\x03\"&\n\x12\x41gentStatusRequest\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\"w\n\x0b\x41gentStatus\x12\x10\n\x08\x61gent_id\x18\x01 \x01(\t\x12\x10\n\x08\x61ttached\x18\x02 \x01(\x08\x12%\n\x07ingress\x18\x03 \x03(\x0b\x32\x14.sam.v1.AgentIngress\x12\x1d\n\x15\x63redential_expires_at\x18\x04 \x01(\x03\"I\n\x13\x41gentStatusResponse\x12#\n\x06\x61gents\x18\x01 \x03(\x0b\x32\x13.sam.v1.AgentStatus\x12\r\n\x05\x65rror\x18\x02 \x01(\t\"\xab\x01\n\x18IdentityEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x1a\n\x12\x62iscuit_expires_at\x18\x03 \x01(\x03\x12\x19\n\x11\x63ontrol_plane_url\x18\x04 \x01(\t\x12\"\n\x1atrusted_control_plane_keys\x18\x05 \x03(\x0c\x12\x12\n\nchecked_at\x18\x06 \x01(\x03\"\x87\x02\n\x14PeerEvidenceResponse\x12\x0f\n\x07peer_id\x18\x01 \x01(\t\x12\x0f\n\x07\x62iscuit\x18\x02 \x01(\x0c\x12\x15\n\rverifying_key\x18\x03 \x01(\x0c\x12\r\n\x05roles\x18\x04 \x03(\t\x12\x38\n\x06labels\x18\x05 \x03(\x0b\x32(.sam.v1.PeerEvidenceResponse.LabelsEntry\x12\x12\n\nexpiration\x18\x06 \x01(\x03\x12\x16\n\x0erevocation_ids\x18\x07 \x03(\t\x12\x12\n\nchecked_at\x18\x08 \x01(\x03\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01*\x94\x01\n\x10\x45nrollmentStatus\x12!\n\x1d\x45NROLLMENT_STATUS_UNSPECIFIED\x10\x00\x12\x1d\n\x19\x45NROLLMENT_STATUS_PENDING\x10\x01\x12\x1e\n\x1a\x45NROLLMENT_STATUS_APPROVED\x10\x02\x12\x1e\n\x1a\x45NROLLMENT_STATUS_REJECTED\x10\x03*s\n\x0bServiceType\x12\x1c\n\x18SERVICE_TYPE_UNSPECIFIED\x10\x00\x12\x14\n\x10SERVICE_TYPE_MCP\x10\x01\x12\x1a\n\x16SERVICE_TYPE_INFERENCE\x10\x02\x12\x14\n\x10SERVICE_TYPE_A2A\x10\x03\x42\x1bZ\x19github.com/google/sam/apib\x06proto3')++_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, globals())+_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'sam_pb2', globals())+if _descriptor._USE_C_DESCRIPTORS == False:++ DESCRIPTOR._options = None+ DESCRIPTOR._serialized_options = b'Z\031github.com/google/sam/api'+ _ENROLLREQUEST_LABELSENTRY._options = None+ _ENROLLREQUEST_LABELSENTRY._serialized_options = b'8\001'+ _BOOTSTRAPENROLLREQUEST_LABELSENTRY._options = None+ _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_options = b'8\001'+ _COMMANDBACKEND_ENVENTRY._options = None+ _COMMANDBACKEND_ENVENTRY._serialized_options = b'8\001'+ _SERVICEANNOUNCE_LABELSENTRY._options = None+ _SERVICEANNOUNCE_LABELSENTRY._serialized_options = b'8\001'+ _PEEREVIDENCERESPONSE_LABELSENTRY._options = None+ _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_options = b'8\001'+ _ENROLLMENTSTATUS._serialized_start=4723+ _ENROLLMENTSTATUS._serialized_end=4871+ _SERVICETYPE._serialized_start=4873+ _SERVICETYPE._serialized_end=4988+ _AUTHFRAME._serialized_start=21+ _AUTHFRAME._serialized_end=88+ _AUTHRESPONSE._serialized_start=90+ _AUTHRESPONSE._serialized_end=153+ _MESHEVENT._serialized_start=156+ _MESHEVENT._serialized_end=341+ _MESHEVENT_TYPE._serialized_start=286+ _MESHEVENT_TYPE._serialized_end=341+ _ENROLLREQUEST._serialized_start=344+ _ENROLLREQUEST._serialized_end=579+ _ENROLLREQUEST_LABELSENTRY._serialized_start=534+ _ENROLLREQUEST_LABELSENTRY._serialized_end=579+ _ENROLLRESPONSE._serialized_start=582+ _ENROLLRESPONSE._serialized_end=724+ _BOOTSTRAPENROLLREQUEST._serialized_start=727+ _BOOTSTRAPENROLLREQUEST._serialized_end=992+ _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_start=534+ _BOOTSTRAPENROLLREQUEST_LABELSENTRY._serialized_end=579+ _BOOTSTRAPENROLLRESPONSE._serialized_start=995+ _BOOTSTRAPENROLLRESPONSE._serialized_end=1219+ _SERVICEINFO._serialized_start=1221+ _SERVICEINFO._serialized_end=1304+ _COMMANDBACKEND._serialized_start=1306+ _COMMANDBACKEND._serialized_end=1429+ _COMMANDBACKEND_ENVENTRY._serialized_start=1387+ _COMMANDBACKEND_ENVENTRY._serialized_end=1429+ _REGISTERSERVICEREQUEST._serialized_start=1432+ _REGISTERSERVICEREQUEST._serialized_end=1570+ _DISCOVEREDPROVIDER._serialized_start=1572+ _DISCOVEREDPROVIDER._serialized_end=1677+ _SERVICEANNOUNCE._serialized_start=1680+ _SERVICEANNOUNCE._serialized_end=1954+ _SERVICEANNOUNCE_LABELSENTRY._serialized_start=534+ _SERVICEANNOUNCE_LABELSENTRY._serialized_end=579+ _CONTROLPLANEINFORESPONSE._serialized_start=1957+ _CONTROLPLANEINFORESPONSE._serialized_end=2092+ _ROUTERLEASEREQUEST._serialized_start=2095+ _ROUTERLEASEREQUEST._serialized_end=2259+ _ROUTERLEASERESPONSE._serialized_start=2261+ _ROUTERLEASERESPONSE._serialized_end=2334+ _POLICYROLE._serialized_start=2337+ _POLICYROLE._serialized_end=2486+ _POLICYBINDING._serialized_start=2488+ _POLICYBINDING._serialized_end=2534+ _POLICYCONFIGGETREQUEST._serialized_start=2536+ _POLICYCONFIGGETREQUEST._serialized_end=2560+ _POLICYCONFIGGETRESPONSE._serialized_start=2562+ _POLICYCONFIGGETRESPONSE._serialized_end=2663+ _POLICYCONFIGUPDATEREQUEST._serialized_start=2665+ _POLICYCONFIGUPDATEREQUEST._serialized_end=2768+ _POLICYCONFIGUPDATERESPONSE._serialized_start=2770+ _POLICYCONFIGUPDATERESPONSE._serialized_end=2830+ _KEYSRESPONSE._serialized_start=2832+ _KEYSRESPONSE._serialized_end=2906+ _TOKENREFRESHREQUEST._serialized_start=2908+ _TOKENREFRESHREQUEST._serialized_end=2994+ _TOKENREFRESHRESPONSE._serialized_start=2996+ _TOKENREFRESHRESPONSE._serialized_end=3084+ _NODECATALOGREPORT._serialized_start=3086+ _NODECATALOGREPORT._serialized_end=3144+ _TOKENREVOKEREQUEST._serialized_start=3146+ _TOKENREVOKEREQUEST._serialized_end=3183+ _TOKENREVOKERESPONSE._serialized_start=3185+ _TOKENREVOKERESPONSE._serialized_end=3238+ _AGENTSECRET._serialized_start=3240+ _AGENTSECRET._serialized_end=3322+ _AGENTEGRESS._serialized_start=3324+ _AGENTEGRESS._serialized_end=3390+ _AGENTINGRESS._serialized_start=3392+ _AGENTINGRESS._serialized_end=3490+ _AGENTBUNDLE._serialized_start=3493+ _AGENTBUNDLE._serialized_end=3663+ _AGENTATTACHREQUEST._serialized_start=3665+ _AGENTATTACHREQUEST._serialized_end=3722+ _AGENTATTACHRESPONSE._serialized_start=3724+ _AGENTATTACHRESPONSE._serialized_end=3807+ _AGENTDETACHREQUEST._serialized_start=3809+ _AGENTDETACHREQUEST._serialized_end=3847+ _AGENTDETACHRESPONSE._serialized_start=3849+ _AGENTDETACHRESPONSE._serialized_end=3902+ _AGENTREFRESHREQUEST._serialized_start=3904+ _AGENTREFRESHREQUEST._serialized_end=3968+ _AGENTREFRESHRESPONSE._serialized_start=3970+ _AGENTREFRESHRESPONSE._serialized_end=4044+ _AGENTSTATUSREQUEST._serialized_start=4046+ _AGENTSTATUSREQUEST._serialized_end=4084+ _AGENTSTATUS._serialized_start=4086+ _AGENTSTATUS._serialized_end=4205+ _AGENTSTATUSRESPONSE._serialized_start=4207+ _AGENTSTATUSRESPONSE._serialized_end=4280+ _IDENTITYEVIDENCERESPONSE._serialized_start=4283+ _IDENTITYEVIDENCERESPONSE._serialized_end=4454+ _PEEREVIDENCERESPONSE._serialized_start=4457+ _PEEREVIDENCERESPONSE._serialized_end=4720+ _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_start=534+ _PEEREVIDENCERESPONSE_LABELSENTRY._serialized_end=579+# @@protoc_insertion_point(module_scope)diff --git a/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyinew file mode 100644index 00000000..a3a8d51e--- /dev/null+++ b/sdk/python/src/agent_mesh/_proto/sam_pb2.pyi@@ -0,0 +1,525 @@+from google.protobuf.internal import containers as _containers+from google.protobuf.internal import enum_type_wrapper as _enum_type_wrapper+from google.protobuf import descriptor as _descriptor+from google.protobuf import message as _message+from typing import ClassVar as _ClassVar, Iterable as _Iterable, Mapping as _Mapping, Optional as _Optional, Union as _Union++DESCRIPTOR: _descriptor.FileDescriptor+ENROLLMENT_STATUS_APPROVED: EnrollmentStatus+ENROLLMENT_STATUS_PENDING: EnrollmentStatus+ENROLLMENT_STATUS_REJECTED: EnrollmentStatus+ENROLLMENT_STATUS_UNSPECIFIED: EnrollmentStatus+SERVICE_TYPE_A2A: ServiceType+SERVICE_TYPE_INFERENCE: ServiceType+SERVICE_TYPE_MCP: ServiceType+SERVICE_TYPE_UNSPECIFIED: ServiceType++class AgentAttachRequest(_message.Message):+ __slots__ = ["bundle"]+ BUNDLE_FIELD_NUMBER: _ClassVar[int]+ bundle: AgentBundle+ def __init__(self, bundle: _Optional[_Union[AgentBundle, _Mapping]] = ...) -> None: ...++class AgentAttachResponse(_message.Message):+ __slots__ = ["egress_socket", "error", "ingress_socket"]+ EGRESS_SOCKET_FIELD_NUMBER: _ClassVar[int]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ INGRESS_SOCKET_FIELD_NUMBER: _ClassVar[int]+ egress_socket: str+ error: str+ ingress_socket: str+ def __init__(self, egress_socket: _Optional[str] = ..., ingress_socket: _Optional[str] = ..., error: _Optional[str] = ...) -> None: ...++class AgentBundle(_message.Message):+ __slots__ = ["agent_id", "credential_path", "egress", "external_id", "ingress", "version"]+ AGENT_ID_FIELD_NUMBER: _ClassVar[int]+ CREDENTIAL_PATH_FIELD_NUMBER: _ClassVar[int]+ EGRESS_FIELD_NUMBER: _ClassVar[int]+ EXTERNAL_ID_FIELD_NUMBER: _ClassVar[int]+ INGRESS_FIELD_NUMBER: _ClassVar[int]+ VERSION_FIELD_NUMBER: _ClassVar[int]+ agent_id: str+ credential_path: str+ egress: AgentEgress+ external_id: str+ ingress: _containers.RepeatedCompositeFieldContainer[AgentIngress]+ version: str+ def __init__(self, version: _Optional[str] = ..., agent_id: _Optional[str] = ..., external_id: _Optional[str] = ..., credential_path: _Optional[str] = ..., egress: _Optional[_Union[AgentEgress, _Mapping]] = ..., ingress: _Optional[_Iterable[_Union[AgentIngress, _Mapping]]] = ...) -> None: ...++class AgentDetachRequest(_message.Message):+ __slots__ = ["agent_id"]+ AGENT_ID_FIELD_NUMBER: _ClassVar[int]+ agent_id: str+ def __init__(self, agent_id: _Optional[str] = ...) -> None: ...++class AgentDetachResponse(_message.Message):+ __slots__ = ["error", "success"]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ SUCCESS_FIELD_NUMBER: _ClassVar[int]+ error: str+ success: bool+ def __init__(self, success: bool = ..., error: _Optional[str] = ...) -> None: ...++class AgentEgress(_message.Message):+ __slots__ = ["allow", "secrets"]+ ALLOW_FIELD_NUMBER: _ClassVar[int]+ SECRETS_FIELD_NUMBER: _ClassVar[int]+ allow: _containers.RepeatedScalarFieldContainer[str]+ secrets: _containers.RepeatedCompositeFieldContainer[AgentSecret]+ def __init__(self, allow: _Optional[_Iterable[str]] = ..., secrets: _Optional[_Iterable[_Union[AgentSecret, _Mapping]]] = ...) -> None: ...++class AgentIngress(_message.Message):+ __slots__ = ["description", "name", "port", "type"]+ DESCRIPTION_FIELD_NUMBER: _ClassVar[int]+ NAME_FIELD_NUMBER: _ClassVar[int]+ PORT_FIELD_NUMBER: _ClassVar[int]+ TYPE_FIELD_NUMBER: _ClassVar[int]+ description: str+ name: str+ port: int+ type: ServiceType+ def __init__(self, type: _Optional[_Union[ServiceType, str]] = ..., name: _Optional[str] = ..., port: _Optional[int] = ..., description: _Optional[str] = ...) -> None: ...++class AgentRefreshRequest(_message.Message):+ __slots__ = ["agent_id", "credential_path"]+ AGENT_ID_FIELD_NUMBER: _ClassVar[int]+ CREDENTIAL_PATH_FIELD_NUMBER: _ClassVar[int]+ agent_id: str+ credential_path: str+ def __init__(self, agent_id: _Optional[str] = ..., credential_path: _Optional[str] = ...) -> None: ...++class AgentRefreshResponse(_message.Message):+ __slots__ = ["error", "expires_at", "success"]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ EXPIRES_AT_FIELD_NUMBER: _ClassVar[int]+ SUCCESS_FIELD_NUMBER: _ClassVar[int]+ error: str+ expires_at: int+ success: bool+ def __init__(self, success: bool = ..., error: _Optional[str] = ..., expires_at: _Optional[int] = ...) -> None: ...++class AgentSecret(_message.Message):+ __slots__ = ["header_name", "host", "kind", "value_path"]+ HEADER_NAME_FIELD_NUMBER: _ClassVar[int]+ HOST_FIELD_NUMBER: _ClassVar[int]+ KIND_FIELD_NUMBER: _ClassVar[int]+ VALUE_PATH_FIELD_NUMBER: _ClassVar[int]+ header_name: str+ host: str+ kind: str+ value_path: str+ def __init__(self, host: _Optional[str] = ..., kind: _Optional[str] = ..., header_name: _Optional[str] = ..., value_path: _Optional[str] = ...) -> None: ...++class AgentStatus(_message.Message):+ __slots__ = ["agent_id", "attached", "credential_expires_at", "ingress"]+ AGENT_ID_FIELD_NUMBER: _ClassVar[int]+ ATTACHED_FIELD_NUMBER: _ClassVar[int]+ CREDENTIAL_EXPIRES_AT_FIELD_NUMBER: _ClassVar[int]+ INGRESS_FIELD_NUMBER: _ClassVar[int]+ agent_id: str+ attached: bool+ credential_expires_at: int+ ingress: _containers.RepeatedCompositeFieldContainer[AgentIngress]+ def __init__(self, agent_id: _Optional[str] = ..., attached: bool = ..., ingress: _Optional[_Iterable[_Union[AgentIngress, _Mapping]]] = ..., credential_expires_at: _Optional[int] = ...) -> None: ...++class AgentStatusRequest(_message.Message):+ __slots__ = ["agent_id"]+ AGENT_ID_FIELD_NUMBER: _ClassVar[int]+ agent_id: str+ def __init__(self, agent_id: _Optional[str] = ...) -> None: ...++class AgentStatusResponse(_message.Message):+ __slots__ = ["agents", "error"]+ AGENTS_FIELD_NUMBER: _ClassVar[int]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ agents: _containers.RepeatedCompositeFieldContainer[AgentStatus]+ error: str+ def __init__(self, agents: _Optional[_Iterable[_Union[AgentStatus, _Mapping]]] = ..., error: _Optional[str] = ...) -> None: ...++class AuthFrame(_message.Message):+ __slots__ = ["agent", "biscuit", "target_service"]+ AGENT_FIELD_NUMBER: _ClassVar[int]+ BISCUIT_FIELD_NUMBER: _ClassVar[int]+ TARGET_SERVICE_FIELD_NUMBER: _ClassVar[int]+ agent: str+ biscuit: bytes+ target_service: str+ def __init__(self, biscuit: _Optional[bytes] = ..., target_service: _Optional[str] = ..., agent: _Optional[str] = ...) -> None: ...++class AuthResponse(_message.Message):+ __slots__ = ["biscuit", "error", "success"]+ BISCUIT_FIELD_NUMBER: _ClassVar[int]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ SUCCESS_FIELD_NUMBER: _ClassVar[int]+ biscuit: bytes+ error: str+ success: bool+ def __init__(self, success: bool = ..., error: _Optional[str] = ..., biscuit: _Optional[bytes] = ...) -> None: ...++class BootstrapEnrollRequest(_message.Message):+ __slots__ = ["bootstrap_token", "challenge_signature", "labels", "peer_id", "public_key", "requested_role", "timestamp"]+ class LabelsEntry(_message.Message):+ __slots__ = ["key", "value"]+ KEY_FIELD_NUMBER: _ClassVar[int]+ VALUE_FIELD_NUMBER: _ClassVar[int]+ key: str+ value: str+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...+ BOOTSTRAP_TOKEN_FIELD_NUMBER: _ClassVar[int]+ CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]+ LABELS_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int]+ REQUESTED_ROLE_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ bootstrap_token: str+ challenge_signature: bytes+ labels: _containers.ScalarMap[str, str]+ peer_id: str+ public_key: bytes+ requested_role: str+ timestamp: int+ def __init__(self, bootstrap_token: _Optional[str] = ..., peer_id: _Optional[str] = ..., public_key: _Optional[bytes] = ..., requested_role: _Optional[str] = ..., labels: _Optional[_Mapping[str, str]] = ..., timestamp: _Optional[int] = ..., challenge_signature: _Optional[bytes] = ...) -> None: ...++class BootstrapEnrollResponse(_message.Message):+ __slots__ = ["biscuit_token", "control_plane_public_key", "error_message", "expiration", "poll_interval_seconds", "router_addresses", "status"]+ BISCUIT_TOKEN_FIELD_NUMBER: _ClassVar[int]+ CONTROL_PLANE_PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int]+ ERROR_MESSAGE_FIELD_NUMBER: _ClassVar[int]+ EXPIRATION_FIELD_NUMBER: _ClassVar[int]+ POLL_INTERVAL_SECONDS_FIELD_NUMBER: _ClassVar[int]+ ROUTER_ADDRESSES_FIELD_NUMBER: _ClassVar[int]+ STATUS_FIELD_NUMBER: _ClassVar[int]+ biscuit_token: bytes+ control_plane_public_key: bytes+ error_message: str+ expiration: int+ poll_interval_seconds: int+ router_addresses: _containers.RepeatedScalarFieldContainer[str]+ status: EnrollmentStatus+ def __init__(self, status: _Optional[_Union[EnrollmentStatus, str]] = ..., biscuit_token: _Optional[bytes] = ..., poll_interval_seconds: _Optional[int] = ..., error_message: _Optional[str] = ..., control_plane_public_key: _Optional[bytes] = ..., router_addresses: _Optional[_Iterable[str]] = ..., expiration: _Optional[int] = ...) -> None: ...++class CommandBackend(_message.Message):+ __slots__ = ["command", "env"]+ class EnvEntry(_message.Message):+ __slots__ = ["key", "value"]+ KEY_FIELD_NUMBER: _ClassVar[int]+ VALUE_FIELD_NUMBER: _ClassVar[int]+ key: str+ value: str+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...+ COMMAND_FIELD_NUMBER: _ClassVar[int]+ ENV_FIELD_NUMBER: _ClassVar[int]+ command: _containers.RepeatedScalarFieldContainer[str]+ env: _containers.ScalarMap[str, str]+ def __init__(self, command: _Optional[_Iterable[str]] = ..., env: _Optional[_Mapping[str, str]] = ...) -> None: ...++class ControlPlaneInfoResponse(_message.Message):+ __slots__ = ["audience", "banned_peer_ids", "client_id", "oidc_issuer", "router_addresses"]+ AUDIENCE_FIELD_NUMBER: _ClassVar[int]+ BANNED_PEER_IDS_FIELD_NUMBER: _ClassVar[int]+ CLIENT_ID_FIELD_NUMBER: _ClassVar[int]+ OIDC_ISSUER_FIELD_NUMBER: _ClassVar[int]+ ROUTER_ADDRESSES_FIELD_NUMBER: _ClassVar[int]+ audience: str+ banned_peer_ids: _containers.RepeatedScalarFieldContainer[str]+ client_id: str+ oidc_issuer: str+ router_addresses: _containers.RepeatedScalarFieldContainer[str]+ def __init__(self, oidc_issuer: _Optional[str] = ..., client_id: _Optional[str] = ..., audience: _Optional[str] = ..., router_addresses: _Optional[_Iterable[str]] = ..., banned_peer_ids: _Optional[_Iterable[str]] = ...) -> None: ...++class DiscoveredProvider(_message.Message):+ __slots__ = ["local_proxy_url", "peer_id", "srv_description", "srv_name"]+ LOCAL_PROXY_URL_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ SRV_DESCRIPTION_FIELD_NUMBER: _ClassVar[int]+ SRV_NAME_FIELD_NUMBER: _ClassVar[int]+ local_proxy_url: str+ peer_id: str+ srv_description: str+ srv_name: str+ def __init__(self, peer_id: _Optional[str] = ..., local_proxy_url: _Optional[str] = ..., srv_name: _Optional[str] = ..., srv_description: _Optional[str] = ...) -> None: ...++class EnrollRequest(_message.Message):+ __slots__ = ["challenge_signature", "jwt", "labels", "peer_id", "public_key", "requested_role", "timestamp"]+ class LabelsEntry(_message.Message):+ __slots__ = ["key", "value"]+ KEY_FIELD_NUMBER: _ClassVar[int]+ VALUE_FIELD_NUMBER: _ClassVar[int]+ key: str+ value: str+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...+ CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]+ JWT_FIELD_NUMBER: _ClassVar[int]+ LABELS_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int]+ REQUESTED_ROLE_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ challenge_signature: bytes+ jwt: str+ labels: _containers.ScalarMap[str, str]+ peer_id: str+ public_key: bytes+ requested_role: str+ timestamp: int+ def __init__(self, jwt: _Optional[str] = ..., peer_id: _Optional[str] = ..., public_key: _Optional[bytes] = ..., requested_role: _Optional[str] = ..., labels: _Optional[_Mapping[str, str]] = ..., timestamp: _Optional[int] = ..., challenge_signature: _Optional[bytes] = ...) -> None: ...++class EnrollResponse(_message.Message):+ __slots__ = ["biscuit_token", "control_plane_public_key", "error_message", "expiration", "router_addresses"]+ BISCUIT_TOKEN_FIELD_NUMBER: _ClassVar[int]+ CONTROL_PLANE_PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int]+ ERROR_MESSAGE_FIELD_NUMBER: _ClassVar[int]+ EXPIRATION_FIELD_NUMBER: _ClassVar[int]+ ROUTER_ADDRESSES_FIELD_NUMBER: _ClassVar[int]+ biscuit_token: bytes+ control_plane_public_key: bytes+ error_message: str+ expiration: int+ router_addresses: _containers.RepeatedScalarFieldContainer[str]+ def __init__(self, biscuit_token: _Optional[bytes] = ..., error_message: _Optional[str] = ..., control_plane_public_key: _Optional[bytes] = ..., router_addresses: _Optional[_Iterable[str]] = ..., expiration: _Optional[int] = ...) -> None: ...++class IdentityEvidenceResponse(_message.Message):+ __slots__ = ["biscuit", "biscuit_expires_at", "checked_at", "control_plane_url", "peer_id", "trusted_control_plane_keys"]+ BISCUIT_EXPIRES_AT_FIELD_NUMBER: _ClassVar[int]+ BISCUIT_FIELD_NUMBER: _ClassVar[int]+ CHECKED_AT_FIELD_NUMBER: _ClassVar[int]+ CONTROL_PLANE_URL_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ TRUSTED_CONTROL_PLANE_KEYS_FIELD_NUMBER: _ClassVar[int]+ biscuit: bytes+ biscuit_expires_at: int+ checked_at: int+ control_plane_url: str+ peer_id: str+ trusted_control_plane_keys: _containers.RepeatedScalarFieldContainer[bytes]+ def __init__(self, peer_id: _Optional[str] = ..., biscuit: _Optional[bytes] = ..., biscuit_expires_at: _Optional[int] = ..., control_plane_url: _Optional[str] = ..., trusted_control_plane_keys: _Optional[_Iterable[bytes]] = ..., checked_at: _Optional[int] = ...) -> None: ...++class KeysResponse(_message.Message):+ __slots__ = ["public_keys", "signatures", "timestamp"]+ PUBLIC_KEYS_FIELD_NUMBER: _ClassVar[int]+ SIGNATURES_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ public_keys: _containers.RepeatedScalarFieldContainer[bytes]+ signatures: _containers.RepeatedScalarFieldContainer[bytes]+ timestamp: int+ def __init__(self, public_keys: _Optional[_Iterable[bytes]] = ..., timestamp: _Optional[int] = ..., signatures: _Optional[_Iterable[bytes]] = ...) -> None: ...++class MeshEvent(_message.Message):+ __slots__ = ["new_public_key", "peer_id", "signature", "timestamp", "type"]+ class Type(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):+ __slots__ = []+ BANNED: MeshEvent.Type+ KEY_ROTATION: MeshEvent.Type+ NEW_PUBLIC_KEY_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ POLICY_UPDATE: MeshEvent.Type+ SIGNATURE_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ TYPE_FIELD_NUMBER: _ClassVar[int]+ new_public_key: bytes+ peer_id: str+ signature: bytes+ timestamp: int+ type: MeshEvent.Type+ def __init__(self, type: _Optional[_Union[MeshEvent.Type, str]] = ..., peer_id: _Optional[str] = ..., timestamp: _Optional[int] = ..., new_public_key: _Optional[bytes] = ..., signature: _Optional[bytes] = ...) -> None: ...++class NodeCatalogReport(_message.Message):+ __slots__ = ["services"]+ SERVICES_FIELD_NUMBER: _ClassVar[int]+ services: _containers.RepeatedCompositeFieldContainer[ServiceInfo]+ def __init__(self, services: _Optional[_Iterable[_Union[ServiceInfo, _Mapping]]] = ...) -> None: ...++class PeerEvidenceResponse(_message.Message):+ __slots__ = ["biscuit", "checked_at", "expiration", "labels", "peer_id", "revocation_ids", "roles", "verifying_key"]+ class LabelsEntry(_message.Message):+ __slots__ = ["key", "value"]+ KEY_FIELD_NUMBER: _ClassVar[int]+ VALUE_FIELD_NUMBER: _ClassVar[int]+ key: str+ value: str+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...+ BISCUIT_FIELD_NUMBER: _ClassVar[int]+ CHECKED_AT_FIELD_NUMBER: _ClassVar[int]+ EXPIRATION_FIELD_NUMBER: _ClassVar[int]+ LABELS_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ REVOCATION_IDS_FIELD_NUMBER: _ClassVar[int]+ ROLES_FIELD_NUMBER: _ClassVar[int]+ VERIFYING_KEY_FIELD_NUMBER: _ClassVar[int]+ biscuit: bytes+ checked_at: int+ expiration: int+ labels: _containers.ScalarMap[str, str]+ peer_id: str+ revocation_ids: _containers.RepeatedScalarFieldContainer[str]+ roles: _containers.RepeatedScalarFieldContainer[str]+ verifying_key: bytes+ def __init__(self, peer_id: _Optional[str] = ..., biscuit: _Optional[bytes] = ..., verifying_key: _Optional[bytes] = ..., roles: _Optional[_Iterable[str]] = ..., labels: _Optional[_Mapping[str, str]] = ..., expiration: _Optional[int] = ..., revocation_ids: _Optional[_Iterable[str]] = ..., checked_at: _Optional[int] = ...) -> None: ...++class PolicyBinding(_message.Message):+ __slots__ = ["members", "role"]+ MEMBERS_FIELD_NUMBER: _ClassVar[int]+ ROLE_FIELD_NUMBER: _ClassVar[int]+ members: _containers.RepeatedScalarFieldContainer[str]+ role: str+ def __init__(self, role: _Optional[str] = ..., members: _Optional[_Iterable[str]] = ...) -> None: ...++class PolicyConfigGetRequest(_message.Message):+ __slots__ = []+ def __init__(self) -> None: ...++class PolicyConfigGetResponse(_message.Message):+ __slots__ = ["bindings", "roles"]+ BINDINGS_FIELD_NUMBER: _ClassVar[int]+ ROLES_FIELD_NUMBER: _ClassVar[int]+ bindings: _containers.RepeatedCompositeFieldContainer[PolicyBinding]+ roles: _containers.RepeatedCompositeFieldContainer[PolicyRole]+ def __init__(self, roles: _Optional[_Iterable[_Union[PolicyRole, _Mapping]]] = ..., bindings: _Optional[_Iterable[_Union[PolicyBinding, _Mapping]]] = ...) -> None: ...++class PolicyConfigUpdateRequest(_message.Message):+ __slots__ = ["bindings", "roles"]+ BINDINGS_FIELD_NUMBER: _ClassVar[int]+ ROLES_FIELD_NUMBER: _ClassVar[int]+ bindings: _containers.RepeatedCompositeFieldContainer[PolicyBinding]+ roles: _containers.RepeatedCompositeFieldContainer[PolicyRole]+ def __init__(self, roles: _Optional[_Iterable[_Union[PolicyRole, _Mapping]]] = ..., bindings: _Optional[_Iterable[_Union[PolicyBinding, _Mapping]]] = ...) -> None: ...++class PolicyConfigUpdateResponse(_message.Message):+ __slots__ = ["error", "success"]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ SUCCESS_FIELD_NUMBER: _ClassVar[int]+ error: str+ success: bool+ def __init__(self, success: bool = ..., error: _Optional[str] = ...) -> None: ...++class PolicyRole(_message.Message):+ __slots__ = ["allowed_agents", "allowed_labels", "allowed_services", "allowed_targets", "custom_datalog", "name"]+ ALLOWED_AGENTS_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_LABELS_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_SERVICES_FIELD_NUMBER: _ClassVar[int]+ ALLOWED_TARGETS_FIELD_NUMBER: _ClassVar[int]+ CUSTOM_DATALOG_FIELD_NUMBER: _ClassVar[int]+ NAME_FIELD_NUMBER: _ClassVar[int]+ allowed_agents: _containers.RepeatedScalarFieldContainer[str]+ allowed_labels: _containers.RepeatedScalarFieldContainer[str]+ allowed_services: _containers.RepeatedScalarFieldContainer[str]+ allowed_targets: _containers.RepeatedScalarFieldContainer[str]+ custom_datalog: _containers.RepeatedScalarFieldContainer[str]+ name: str+ def __init__(self, name: _Optional[str] = ..., allowed_targets: _Optional[_Iterable[str]] = ..., allowed_services: _Optional[_Iterable[str]] = ..., custom_datalog: _Optional[_Iterable[str]] = ..., allowed_agents: _Optional[_Iterable[str]] = ..., allowed_labels: _Optional[_Iterable[str]] = ...) -> None: ...++class RegisterServiceRequest(_message.Message):+ __slots__ = ["command", "service", "target_url"]+ COMMAND_FIELD_NUMBER: _ClassVar[int]+ SERVICE_FIELD_NUMBER: _ClassVar[int]+ TARGET_URL_FIELD_NUMBER: _ClassVar[int]+ command: CommandBackend+ service: ServiceInfo+ target_url: str+ def __init__(self, service: _Optional[_Union[ServiceInfo, _Mapping]] = ..., target_url: _Optional[str] = ..., command: _Optional[_Union[CommandBackend, _Mapping]] = ...) -> None: ...++class RouterLeaseRequest(_message.Message):+ __slots__ = ["addresses", "biscuit", "challenge_signature", "connected_peers", "dht_size", "peer_id", "timestamp"]+ ADDRESSES_FIELD_NUMBER: _ClassVar[int]+ BISCUIT_FIELD_NUMBER: _ClassVar[int]+ CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]+ CONNECTED_PEERS_FIELD_NUMBER: _ClassVar[int]+ DHT_SIZE_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ addresses: _containers.RepeatedScalarFieldContainer[str]+ biscuit: bytes+ challenge_signature: bytes+ connected_peers: _containers.RepeatedScalarFieldContainer[str]+ dht_size: int+ peer_id: str+ timestamp: int+ def __init__(self, peer_id: _Optional[str] = ..., addresses: _Optional[_Iterable[str]] = ..., biscuit: _Optional[bytes] = ..., connected_peers: _Optional[_Iterable[str]] = ..., dht_size: _Optional[int] = ..., timestamp: _Optional[int] = ..., challenge_signature: _Optional[bytes] = ...) -> None: ...++class RouterLeaseResponse(_message.Message):+ __slots__ = ["error", "expires_at", "success"]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ EXPIRES_AT_FIELD_NUMBER: _ClassVar[int]+ SUCCESS_FIELD_NUMBER: _ClassVar[int]+ error: str+ expires_at: int+ success: bool+ def __init__(self, success: bool = ..., error: _Optional[str] = ..., expires_at: _Optional[int] = ...) -> None: ...++class ServiceAnnounce(_message.Message):+ __slots__ = ["active_requests", "keys", "labels", "latency_ewma_ms", "peer_id", "service_name", "timestamp", "type"]+ class LabelsEntry(_message.Message):+ __slots__ = ["key", "value"]+ KEY_FIELD_NUMBER: _ClassVar[int]+ VALUE_FIELD_NUMBER: _ClassVar[int]+ key: str+ value: str+ def __init__(self, key: _Optional[str] = ..., value: _Optional[str] = ...) -> None: ...+ ACTIVE_REQUESTS_FIELD_NUMBER: _ClassVar[int]+ KEYS_FIELD_NUMBER: _ClassVar[int]+ LABELS_FIELD_NUMBER: _ClassVar[int]+ LATENCY_EWMA_MS_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ SERVICE_NAME_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ TYPE_FIELD_NUMBER: _ClassVar[int]+ active_requests: int+ keys: _containers.RepeatedScalarFieldContainer[str]+ labels: _containers.ScalarMap[str, str]+ latency_ewma_ms: float+ peer_id: str+ service_name: str+ timestamp: int+ type: ServiceType+ def __init__(self, peer_id: _Optional[str] = ..., type: _Optional[_Union[ServiceType, str]] = ..., service_name: _Optional[str] = ..., keys: _Optional[_Iterable[str]] = ..., labels: _Optional[_Mapping[str, str]] = ..., active_requests: _Optional[int] = ..., latency_ewma_ms: _Optional[float] = ..., timestamp: _Optional[int] = ...) -> None: ...++class ServiceInfo(_message.Message):+ __slots__ = ["description", "name", "type"]+ DESCRIPTION_FIELD_NUMBER: _ClassVar[int]+ NAME_FIELD_NUMBER: _ClassVar[int]+ TYPE_FIELD_NUMBER: _ClassVar[int]+ description: str+ name: str+ type: ServiceType+ def __init__(self, type: _Optional[_Union[ServiceType, str]] = ..., name: _Optional[str] = ..., description: _Optional[str] = ...) -> None: ...++class TokenRefreshRequest(_message.Message):+ __slots__ = ["challenge_signature", "peer_id", "timestamp"]+ CHALLENGE_SIGNATURE_FIELD_NUMBER: _ClassVar[int]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ TIMESTAMP_FIELD_NUMBER: _ClassVar[int]+ challenge_signature: bytes+ peer_id: str+ timestamp: int+ def __init__(self, challenge_signature: _Optional[bytes] = ..., timestamp: _Optional[int] = ..., peer_id: _Optional[str] = ...) -> None: ...++class TokenRefreshResponse(_message.Message):+ __slots__ = ["biscuit_token", "error_message", "expires_at"]+ BISCUIT_TOKEN_FIELD_NUMBER: _ClassVar[int]+ ERROR_MESSAGE_FIELD_NUMBER: _ClassVar[int]+ EXPIRES_AT_FIELD_NUMBER: _ClassVar[int]+ biscuit_token: bytes+ error_message: str+ expires_at: int+ def __init__(self, biscuit_token: _Optional[bytes] = ..., expires_at: _Optional[int] = ..., error_message: _Optional[str] = ...) -> None: ...++class TokenRevokeRequest(_message.Message):+ __slots__ = ["peer_id"]+ PEER_ID_FIELD_NUMBER: _ClassVar[int]+ peer_id: str+ def __init__(self, peer_id: _Optional[str] = ...) -> None: ...++class TokenRevokeResponse(_message.Message):+ __slots__ = ["error", "success"]+ ERROR_FIELD_NUMBER: _ClassVar[int]+ SUCCESS_FIELD_NUMBER: _ClassVar[int]+ error: str+ success: bool+ def __init__(self, success: bool = ..., error: _Optional[str] = ...) -> None: ...++class EnrollmentStatus(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):+ __slots__ = []++class ServiceType(int, metaclass=_enum_type_wrapper.EnumTypeWrapper):+ __slots__ = []diff --git a/sdk/python/src/agent_mesh/base58.py b/sdk/python/src/agent_mesh/base58.pynew file mode 100644index 00000000..5285b0a3--- /dev/null+++ b/sdk/python/src/agent_mesh/base58.py@@ -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.++"""base58btc, the alphabet libp2p peer IDs are written in."""++_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"+_INDEX = {c: i for i, c in enumerate(_ALPHABET)}+++def encode(data: bytes) -> str:+ zeros = len(data) - len(data.lstrip(b"\x00"))+ n = int.from_bytes(data, "big")+ out = []+ while n > 0:+ n, digit = divmod(n, 58)+ out.append(_ALPHABET[digit])+ return "1" * zeros + "".join(reversed(out))+++def decode(text: str) -> bytes:+ zeros = len(text) - len(text.lstrip("1"))+ n = 0+ for ch in text:+ try:+ n = n * 58 + _INDEX[ch]+ except KeyError:+ raise ValueError(f"invalid base58 character {ch!r}") from None+ body = n.to_bytes((n.bit_length() + 7) // 8, "big") if n else b""+ return b"\x00" * zeros + bodydiff --git a/sdk/python/src/agent_mesh/challenges.py b/sdk/python/src/agent_mesh/challenges.pynew file mode 100644index 00000000..ff03477f--- /dev/null+++ b/sdk/python/src/agent_mesh/challenges.py@@ -0,0 +1,43 @@+# 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.++"""Proof-of-possession challenges on the control plane's enrollment surface.+Each payload names the peer and the endpoint, so a captured signature+verifies nowhere else. Mirrors api/network.go; ts is unix milliseconds."""+++def _challenge(domain: str, peer_id: str, ts: int) -> bytes:+ if not isinstance(ts, int) or ts <= 0:+ raise ValueError(f"challenge timestamp must be a positive integer, got {ts!r}")+ return f"sam:{domain}:{peer_id}:{ts}".encode()+++def enroll_challenge(peer_id: str, ts: int) -> bytes:+ """Signed at POST /enroll (bootstrap token enrollment)."""+ return _challenge("enroll", peer_id, ts)+++def enroll_status_challenge(peer_id: str, ts: int) -> bytes:+ """Signed at GET /enroll/status while a bootstrap enrollment is pending."""+ return _challenge("enroll-status", peer_id, ts)+++def register_challenge(peer_id: str, ts: int) -> bytes:+ """Signed at POST /register (OIDC enrollment)."""+ return _challenge("register", peer_id, ts)+++def refresh_challenge(peer_id: str, ts: int) -> bytes:+ """Signed at POST /refresh."""+ return _challenge("refresh", peer_id, ts)diff --git a/sdk/python/src/agent_mesh/conformance.py b/sdk/python/src/agent_mesh/conformance.pynew file mode 100644index 00000000..8c829578--- /dev/null+++ b/sdk/python/src/agent_mesh/conformance.py@@ -0,0 +1,81 @@+# 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.++"""Conformance runner driven by tests/integration/sdk_enroll_test.go: enrolls+against a real control plane, refreshes, reloads from disk and reports what it+holds as JSON on stdout for the Go side to verify. The JavaScript SDK ships the+same runner (dist/conformance.js) with the same environment and output, so one+Go test checks both.++ SAM_CONTROL_PLANE_URL base URL of the control plane+ SAM_BOOTSTRAP_TOKEN_PATH file holding a bootstrap token+ SAM_SDK_STATE_DIR directory for identity and credential+ SAM_INSECURE_CONTROL_PLANE "1" to accept plaintext http:// off loopback+"""++import base64+import json+import os+import sys++from .mesh import AgentMesh+++def _require_env(name: str) -> str:+ value = os.environ.get(name)+ if not value:+ raise SystemExit(f"{name} is required")+ return value+++def main() -> None:+ control_plane_url = _require_env("SAM_CONTROL_PLANE_URL")+ bootstrap_token_path = _require_env("SAM_BOOTSTRAP_TOKEN_PATH")+ state_dir = _require_env("SAM_SDK_STATE_DIR")+ allow_insecure = os.environ.get("SAM_INSECURE_CONTROL_PLANE") == "1"++ mesh = AgentMesh.enroll(+ control_plane_url,+ bootstrap_token_path=bootstrap_token_path,+ state_dir=state_dir,+ allow_insecure=allow_insecure,+ poll_interval=0.2,+ )+ enrolled = mesh.credential++ reloaded = AgentMesh.load(state_dir, allow_insecure=allow_insecure)+ refreshed = reloaded.refresh()++ b64 = lambda b: base64.b64encode(b).decode() # noqa: E731+ json.dump(+ {+ "sdk": "python",+ "peer_id": mesh.peer_id,+ "public_key": mesh.identity.public_key_raw.hex(),+ "biscuit": b64(enrolled.biscuit),+ "expiration": enrolled.expiration,+ "control_plane_keys": [k.hex() for k in enrolled.control_plane_keys],+ "router_addresses": list(enrolled.router_addresses),+ "reloaded_peer_id": reloaded.peer_id,+ "refreshed_biscuit": b64(refreshed.biscuit),+ "refreshed_expiration": refreshed.expiration,+ "auth_frame": b64(reloaded.auth_frame("mcp://echo", "agent:example.test:conformance")),+ },+ sys.stdout,+ )+ sys.stdout.write("\n")+++if __name__ == "__main__":+ main()diff --git a/sdk/python/src/agent_mesh/controlplane.py b/sdk/python/src/agent_mesh/controlplane.pynew file mode 100644index 00000000..931ee93e--- /dev/null+++ b/sdk/python/src/agent_mesh/controlplane.py@@ -0,0 +1,313 @@+# 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.++"""Client for the control plane's mesh-protocol surface: protobuf over HTTP+(api/sam.proto). The operator plane (/admin/*, JSON) is out of scope."""++from __future__ import annotations++import base64+import ipaddress+import threading+import time+import urllib.error+import urllib.parse+import urllib.request+from dataclasses import dataclass, field+from typing import Callable, Mapping, Optional, Sequence++from . import challenges+from ._proto import sam_pb2 as pb+from .identity import PUBLIC_KEY_SIZE, Identity, verify_ed25519++PROTOBUF_CONTENT_TYPE = "application/x-protobuf"+HEADER_CHALLENGE_TIMESTAMP = "X-Sam-Challenge-Ts"+HEADER_CHALLENGE_SIGNATURE = "X-Sam-Challenge-Sig"++# The role a plain mesh member enrolls with (api.RoleNode).+ROLE_NODE = "sam:role:node"++# How far a signed /keys response's timestamp may drift from our clock.+KEYS_RESPONSE_FRESHNESS_MS = 5 * 60 * 1000++_MAX_RESPONSE_BYTES = 1024 * 1024++# (method, url, headers, body) -> (status, body). Injection point for tests.+Transport = Callable[[str, str, Mapping[str, str], Optional[bytes]], "tuple[int, bytes]"]+++class ControlPlaneError(Exception):+ """A non-2xx answer from the control plane."""++ def __init__(self, path: str, status: int, body: bytes):+ text = body.decode("utf-8", "replace").strip()+ super().__init__(f"control plane {path}: HTTP {status}" + (f": {text}" if text else ""))+ self.path = path+ self.status = status+ self.body = text+++class EnrollmentRejectedError(Exception):+ """The control plane answered, and the answer is a refusal."""+++class InsecureControlPlaneURLError(Exception):+ """Plaintext http:// to a host that is not loopback; see api.ValidateControlPlaneTransport."""++ def __init__(self, url: str):+ super().__init__(+ f"plaintext http:// control plane URL to a non-loopback host: {url} "+ "(use https://, or set allow_insecure for a network you trust)"+ )+++@dataclass(frozen=True)+class Enrollment:+ """What an approved enrollment hands the caller."""++ biscuit: bytes+ # Unix seconds at which the biscuit expires.+ expiration: int+ control_plane_public_key: bytes+ router_addresses: list[str] = field(default_factory=list)+++@dataclass(frozen=True)+class RefreshResult:+ biscuit: bytes+ # Unix seconds.+ expiration: int+++def _is_loopback_host(host: str) -> bool:+ if host.lower() == "localhost":+ return True+ try:+ return ipaddress.ip_address(host.strip("[]")).is_loopback+ except ValueError:+ return False+++def validate_control_plane_url(raw_url: str, allow_insecure: bool = False) -> str:+ """Mirrors api.ValidateControlPlaneTransport: https, or http to loopback only."""+ parts = urllib.parse.urlsplit(raw_url)+ if parts.scheme == "https" and parts.hostname:+ return raw_url.rstrip("/")+ if parts.scheme == "http" and parts.hostname:+ if allow_insecure or _is_loopback_host(parts.hostname):+ return raw_url.rstrip("/")+ raise InsecureControlPlaneURLError(raw_url)+ if parts.scheme in ("http", "https"):+ raise ValueError(f"invalid control plane URL {raw_url!r}")+ raise ValueError(f"control plane URL {raw_url!r} must use http:// or https://")+++def verify_keys_response(resp: pb.KeysResponse, trusted: Sequence[bytes], now_ms: Optional[int] = None) -> list[bytes]:+ """Returns the key set if it is fresh and at least one listed key is already+ trusted and its signature verifies. Mirrors api.VerifyKeysResponse."""+ if not trusted:+ raise ValueError("no trusted control plane key to verify /keys against")+ if len(resp.signatures) != len(resp.public_keys):+ raise ValueError(f"keys response carries {len(resp.signatures)} signatures for {len(resp.public_keys)} keys")+ now_ms = int(time.time() * 1000) if now_ms is None else now_ms+ if abs(now_ms - resp.timestamp) > KEYS_RESPONSE_FRESHNESS_MS:+ raise ValueError(f"keys response timestamp {resp.timestamp} is outside the freshness window")+ # Each signature covers the set and the timestamp, deterministically+ # encoded with the signatures cleared.+ payload = pb.KeysResponse(public_keys=list(resp.public_keys), timestamp=resp.timestamp).SerializeToString(deterministic=True)+ keys: list[bytes] = []+ verified = False+ for pub, sig in zip(resp.public_keys, resp.signatures):+ if len(pub) != PUBLIC_KEY_SIZE:+ continue+ keys.append(bytes(pub))+ if not verified and any(t == pub for t in trusted) and verify_ed25519(pub, payload, sig):+ verified = True+ if not verified:+ raise ValueError("keys response is not signed by any trusted control plane key")+ return keys+++def _urllib_transport(timeout: float) -> Transport:+ def send(method: str, url: str, headers: Mapping[str, str], body: Optional[bytes]) -> tuple[int, bytes]:+ req = urllib.request.Request(url, data=body, method=method, headers=dict(headers))+ try:+ with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - scheme validated by the client+ return resp.status, resp.read(_MAX_RESPONSE_BYTES + 1)+ except urllib.error.HTTPError as err:+ return err.code, err.read(_MAX_RESPONSE_BYTES + 1)++ return send+++class ControlPlaneClient:+ def __init__(+ self,+ url: str,+ *,+ allow_insecure: bool = False,+ timeout: float = 30.0,+ transport: Optional[Transport] = None,+ ):+ self.url = validate_control_plane_url(url, allow_insecure)+ self._transport = transport or _urllib_transport(timeout)++ def info(self) -> pb.ControlPlaneInfoResponse:+ """GET /info: OIDC settings, router addresses and the ban list. Unauthenticated."""+ return pb.ControlPlaneInfoResponse.FromString(self._request("GET", "/info"))++ def keys(self, trusted: Sequence[bytes]) -> list[bytes]:+ """GET /keys: every signing key the control plane currently trusts,+ verified against a key the caller already trusts (the enrollment key)."""+ return verify_keys_response(pb.KeysResponse.FromString(self._request("GET", "/keys")), trusted)++ def enroll_bootstrap(+ self,+ identity: Identity,+ bootstrap_token: str,+ *,+ role: str = ROLE_NODE,+ labels: Optional[Mapping[str, str]] = None,+ poll_interval: Optional[float] = None,+ cancel: Optional[threading.Event] = None,+ ) -> Enrollment:+ """POST /enroll with a bootstrap token, then GET /enroll/status until an+ operator approves the request if the mesh is not on auto-approve.+ `cancel` bounds that wait; set it to stop polling."""+ ts = _now_ms()+ req = pb.BootstrapEnrollRequest(+ bootstrap_token=bootstrap_token,+ peer_id=identity.peer_id,+ public_key=identity.libp2p_public_key,+ requested_role=role,+ labels=dict(labels or {}),+ timestamp=ts,+ challenge_signature=identity.sign(challenges.enroll_challenge(identity.peer_id, ts)),+ )+ resp = pb.BootstrapEnrollResponse.FromString(self._request("POST", "/enroll", req.SerializeToString()))+ while resp.status == pb.ENROLLMENT_STATUS_PENDING:+ wait = poll_interval if poll_interval is not None else max(1, resp.poll_interval_seconds)+ if cancel is not None:+ if cancel.wait(wait):+ raise TimeoutError("enrollment cancelled while pending approval")+ else:+ time.sleep(wait)+ resp = self._enroll_status(identity)+ return _enrollment_from_bootstrap_response(resp)++ def _enroll_status(self, identity: Identity) -> pb.BootstrapEnrollResponse:+ ts = _now_ms()+ sig = identity.sign(challenges.enroll_status_challenge(identity.peer_id, ts))+ body = self._request(+ "GET",+ "/enroll/status?" + urllib.parse.urlencode({"peer_id": identity.peer_id}),+ headers={+ HEADER_CHALLENGE_TIMESTAMP: str(ts),+ HEADER_CHALLENGE_SIGNATURE: base64.urlsafe_b64encode(sig).rstrip(b"=").decode(),+ },+ )+ return pb.BootstrapEnrollResponse.FromString(body)++ def register(+ self,+ identity: Identity,+ jwt: str,+ *,+ role: str = ROLE_NODE,+ labels: Optional[Mapping[str, str]] = None,+ ) -> Enrollment:+ """POST /register with an OIDC ID token."""+ ts = _now_ms()+ req = pb.EnrollRequest(+ jwt=jwt,+ peer_id=identity.peer_id,+ public_key=identity.libp2p_public_key,+ requested_role=role,+ labels=dict(labels or {}),+ timestamp=ts,+ challenge_signature=identity.sign(challenges.register_challenge(identity.peer_id, ts)),+ )+ resp = pb.EnrollResponse.FromString(self._request("POST", "/register", req.SerializeToString()))+ if resp.error_message:+ raise EnrollmentRejectedError(f"enrollment failed: {resp.error_message}")+ return _checked_enrollment(+ Enrollment(+ biscuit=resp.biscuit_token,+ expiration=resp.expiration,+ control_plane_public_key=resp.control_plane_public_key,+ router_addresses=list(resp.router_addresses),+ )+ )++ def refresh(self, identity: Identity, biscuit: bytes) -> RefreshResult:+ """POST /refresh: trades the biscuit for a fresh one. The old one is+ spent by this call; callers must persist the result before using it."""+ ts = _now_ms()+ req = pb.TokenRefreshRequest(+ timestamp=ts,+ challenge_signature=identity.sign(challenges.refresh_challenge(identity.peer_id, ts)),+ peer_id=identity.peer_id,+ )+ body = self._request(+ "POST",+ "/refresh",+ req.SerializeToString(),+ headers={"Authorization": "Bearer " + base64.b64encode(biscuit).decode()},+ )+ resp = pb.TokenRefreshResponse.FromString(body)+ if resp.error_message:+ raise EnrollmentRejectedError(f"refresh failed: {resp.error_message}")+ if not resp.biscuit_token:+ raise ValueError("refresh returned an empty biscuit")+ return RefreshResult(biscuit=resp.biscuit_token, expiration=resp.expires_at)++ def _request(self, method: str, path: str, body: Optional[bytes] = None, headers: Optional[Mapping[str, str]] = None) -> bytes:+ all_headers = {"Accept": PROTOBUF_CONTENT_TYPE, **(headers or {})}+ if body is not None:+ all_headers["Content-Type"] = PROTOBUF_CONTENT_TYPE+ status, data = self._transport(method, self.url + path, all_headers, body)+ if len(data) > _MAX_RESPONSE_BYTES:+ raise ValueError(f"control plane {path}: response of {len(data)} bytes exceeds the {_MAX_RESPONSE_BYTES} byte limit")+ if not 200 <= status < 300:+ raise ControlPlaneError(path, status, data)+ return data+++def _now_ms() -> int:+ return int(time.time() * 1000)+++def _enrollment_from_bootstrap_response(resp: pb.BootstrapEnrollResponse) -> Enrollment:+ if resp.status == pb.ENROLLMENT_STATUS_APPROVED:+ return _checked_enrollment(+ Enrollment(+ biscuit=resp.biscuit_token,+ expiration=resp.expiration,+ control_plane_public_key=resp.control_plane_public_key,+ router_addresses=list(resp.router_addresses),+ )+ )+ if resp.status == pb.ENROLLMENT_STATUS_REJECTED:+ raise EnrollmentRejectedError(f"enrollment rejected: {resp.error_message or 'no reason given'}")+ raise ValueError(f"unexpected enrollment status {resp.status}: {resp.error_message}")+++def _checked_enrollment(e: Enrollment) -> Enrollment:+ if not e.biscuit:+ raise ValueError("received empty biscuit token")+ if len(e.control_plane_public_key) != PUBLIC_KEY_SIZE:+ raise ValueError(+ f"received invalid control plane public key size: {len(e.control_plane_public_key)} bytes (expected {PUBLIC_KEY_SIZE})"+ )+ return ediff --git a/sdk/python/src/agent_mesh/credential.py b/sdk/python/src/agent_mesh/credential.pynew file mode 100644index 00000000..f192e902--- /dev/null+++ b/sdk/python/src/agent_mesh/credential.py@@ -0,0 +1,79 @@+# 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.++from __future__ import annotations++import base64+import json+import time+from dataclasses import dataclass, field++from ._proto import sam_pb2 as pb+++@dataclass(frozen=True)+class MeshCredential:+ """What a member holds after enrolling: its biscuit and what it trusts."""++ control_plane_url: str+ # The biscuit the control plane minted for this identity.+ biscuit: bytes+ # Unix seconds at which the biscuit expires.+ expiration: int+ # Every control plane signing key currently trusted (rotation keeps several valid).+ control_plane_keys: list[bytes] = field(default_factory=list)+ # Router multiaddrs, `/p2p/<peer id>` suffixed, as handed out at enrollment.+ router_addresses: list[str] = field(default_factory=list)++ def time_to_live_seconds(self, now: float | None = None) -> int:+ """Seconds of validity left on the biscuit; negative once expired."""+ return self.expiration - int(time.time() if now is None else now)++ def to_json(self) -> str:+ return json.dumps(+ {+ "control_plane_url": self.control_plane_url,+ "biscuit": base64.b64encode(self.biscuit).decode(),+ "expiration": self.expiration,+ "control_plane_keys": [base64.b64encode(k).decode() for k in self.control_plane_keys],+ "router_addresses": list(self.router_addresses),+ },+ indent=2,+ ) + "\n"++ @classmethod+ def from_json(cls, text: str) -> "MeshCredential":+ raw = json.loads(text)+ try:+ return cls(+ control_plane_url=str(raw["control_plane_url"]),+ biscuit=base64.b64decode(raw["biscuit"]),+ expiration=int(raw["expiration"]),+ control_plane_keys=[base64.b64decode(k) for k in raw.get("control_plane_keys", [])],+ router_addresses=[str(a) for a in raw.get("router_addresses", [])],+ )+ except (KeyError, TypeError, ValueError) as err:+ raise ValueError("malformed credential file") from err+++def encode_auth_frame(biscuit: bytes, target_service: str = "", agent: str = "") -> bytes:+ """The first frame on every mesh stream (/sam/auth/1.0.0, /sam/mcp/1.0.0):+ the caller's biscuit, the service it wants and the agent it speaks for.+ Framing (varint length prefix) is the transport's job."""+ return pb.AuthFrame(biscuit=biscuit, target_service=target_service, agent=agent).SerializeToString()+++def decode_auth_response(data: bytes) -> pb.AuthResponse:+ """The peer's answer to an AuthFrame, carrying its own biscuit on success."""+ return pb.AuthResponse.FromString(data)diff --git a/sdk/python/src/agent_mesh/identity.py b/sdk/python/src/agent_mesh/identity.pynew file mode 100644index 00000000..efbe448a--- /dev/null+++ b/sdk/python/src/agent_mesh/identity.py@@ -0,0 +1,112 @@+# 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.++"""A mesh identity is an ed25519 key pair. Its peer ID is the one libp2p+derives, so the same key works in the SDK, in sam-node and on the wire."""++from __future__ import annotations++import os++from cryptography.exceptions import InvalidSignature+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey++from . import base58++PUBLIC_KEY_SIZE = 32+SEED_SIZE = 32++# libp2p crypto.proto PublicKey{Type: Ed25519 (1), Data: <32 bytes>}.+_LIBP2P_PUBLIC_KEY_PREFIX = bytes([0x08, 0x01, 0x12, 0x20])+# libp2p crypto.proto PrivateKey{Type: Ed25519 (1), Data: <seed || public>}.+_LIBP2P_PRIVATE_KEY_PREFIX = bytes([0x08, 0x01, 0x12, 0x40])+# multihash: identity function (0x00), digest length 36.+_IDENTITY_MULTIHASH_PREFIX = bytes([0x00, 0x24])+++def libp2p_public_key(public_key_raw: bytes) -> bytes:+ """The libp2p protobuf encoding of an ed25519 public key."""+ if len(public_key_raw) != PUBLIC_KEY_SIZE:+ raise ValueError(f"ed25519 public key must be {PUBLIC_KEY_SIZE} bytes, got {len(public_key_raw)}")+ return _LIBP2P_PUBLIC_KEY_PREFIX + public_key_raw+++def peer_id_from_public_key(public_key_raw: bytes) -> str:+ """The peer ID libp2p derives from an ed25519 public key (base58btc, "12D3Koo...")."""+ return base58.encode(_IDENTITY_MULTIHASH_PREFIX + libp2p_public_key(public_key_raw))+++def verify_ed25519(public_key_raw: bytes, data: bytes, signature: bytes) -> bool:+ """Verifies an ed25519 signature with a raw 32-byte public key."""+ if len(public_key_raw) != PUBLIC_KEY_SIZE:+ return False+ try:+ Ed25519PublicKey.from_public_bytes(public_key_raw).verify(signature, data)+ except (InvalidSignature, ValueError):+ return False+ return True+++class Identity:+ """An ed25519 key pair and the libp2p peer ID it maps to."""++ __slots__ = ("_private", "_seed", "public_key_raw", "peer_id")++ def __init__(self, seed: bytes):+ if len(seed) != SEED_SIZE:+ raise ValueError(f"ed25519 seed must be {SEED_SIZE} bytes, got {len(seed)}")+ self._seed = bytes(seed)+ self._private = Ed25519PrivateKey.from_private_bytes(self._seed)+ self.public_key_raw: bytes = self._private.public_key().public_bytes(+ serialization.Encoding.Raw, serialization.PublicFormat.Raw+ )+ self.peer_id: str = peer_id_from_public_key(self.public_key_raw)++ @classmethod+ def generate(cls) -> "Identity":+ return cls(os.urandom(SEED_SIZE))++ @classmethod+ def from_seed(cls, seed: bytes) -> "Identity":+ return cls(seed)++ @classmethod+ def from_libp2p_private_key(cls, data: bytes) -> "Identity":+ """Loads the libp2p protobuf private key encoding, the format sam-node persists."""+ prefix = len(_LIBP2P_PRIVATE_KEY_PREFIX)+ if len(data) != prefix + 64 or not data.startswith(_LIBP2P_PRIVATE_KEY_PREFIX):+ raise ValueError("not a libp2p ed25519 private key")+ identity = cls(data[prefix : prefix + SEED_SIZE])+ if data[prefix + SEED_SIZE :] != identity.public_key_raw:+ raise ValueError("libp2p private key: public half does not match the seed")+ return identity++ def to_libp2p_private_key(self) -> bytes:+ """The libp2p protobuf private key encoding (seed || public key)."""+ return _LIBP2P_PRIVATE_KEY_PREFIX + self._seed + self.public_key_raw++ @property+ def libp2p_public_key(self) -> bytes:+ """The libp2p protobuf public key encoding, what the control plane stores."""+ return libp2p_public_key(self.public_key_raw)++ def sign(self, data: bytes) -> bytes:+ return self._private.sign(data)++ def verify(self, data: bytes, signature: bytes) -> bool:+ return verify_ed25519(self.public_key_raw, data, signature)++ def __repr__(self) -> str:+ return f"Identity({self.peer_id})"diff --git a/sdk/python/src/agent_mesh/mesh.py b/sdk/python/src/agent_mesh/mesh.pynew file mode 100644index 00000000..84d2ccbd--- /dev/null+++ b/sdk/python/src/agent_mesh/mesh.py@@ -0,0 +1,176 @@+# 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.++from __future__ import annotations++import os+import threading+from dataclasses import replace+from pathlib import Path+from typing import Mapping, Optional++from .controlplane import ROLE_NODE, ControlPlaneClient, Enrollment, Transport+from .credential import MeshCredential, encode_auth_frame+from .identity import Identity++_IDENTITY_FILE = "identity.key"+_CREDENTIAL_FILE = "credential.json"+++class AgentMesh:+ """A member of the mesh: an identity, the credential the control plane+ minted for it, and the client that keeps that credential fresh.++ This is the enrollment half of the SDK. Joining the mesh over libp2p and+ serving or calling MCP tools build on top of it (see sdk/README.md)."""++ def __init__(self, identity: Identity, control_plane: ControlPlaneClient, credential: MeshCredential, state_dir: Optional[Path]):+ self.identity = identity+ self.control_plane = control_plane+ self._credential = credential+ self._state_dir = state_dir++ @property+ def peer_id(self) -> str:+ return self.identity.peer_id++ @property+ def credential(self) -> MeshCredential:+ return self._credential++ @classmethod+ def enroll(+ cls,+ control_plane_url: str,+ *,+ bootstrap_token: Optional[str] = None,+ bootstrap_token_path: Optional[str | os.PathLike[str]] = None,+ jwt: Optional[str] = None,+ state_dir: Optional[str | os.PathLike[str]] = None,+ identity: Optional[Identity] = None,+ role: str = ROLE_NODE,+ labels: Optional[Mapping[str, str]] = None,+ allow_insecure: bool = False,+ poll_interval: Optional[float] = None,+ cancel: Optional[threading.Event] = None,+ transport: Optional[Transport] = None,+ ) -> "AgentMesh":+ """Enrolls with the control plane and returns a member holding a credential.+ Exactly one of bootstrap_token, bootstrap_token_path or jwt must be given.+ A bootstrap token is better read from a file than passed as a value."""+ given = sum(v is not None for v in (bootstrap_token, bootstrap_token_path, jwt))+ if given != 1:+ raise ValueError("exactly one of bootstrap_token, bootstrap_token_path or jwt is required")+ state = Path(state_dir) if state_dir is not None else None+ identity = identity or _load_identity(state) or Identity.generate()+ control_plane = ControlPlaneClient(control_plane_url, allow_insecure=allow_insecure, transport=transport)++ enrollment: Enrollment+ if jwt is not None:+ enrollment = control_plane.register(identity, jwt, role=role, labels=labels)+ else:+ if bootstrap_token_path is not None:+ bootstrap_token = Path(bootstrap_token_path).read_text().strip()+ assert bootstrap_token is not None+ enrollment = control_plane.enroll_bootstrap(+ identity, bootstrap_token, role=role, labels=labels, poll_interval=poll_interval, cancel=cancel+ )++ # Widen trust from the one key the enrollment carries to every key the+ # control plane currently signs with, so peers holding credentials from+ # a retiring key still verify. Best effort, as in sam-node.+ control_plane_keys = [enrollment.control_plane_public_key]+ try:+ control_plane_keys = control_plane.keys(control_plane_keys)+ except Exception: # noqa: BLE001 - the enrollment key alone still works until the next sync+ pass++ mesh = cls(+ identity,+ control_plane,+ MeshCredential(+ control_plane_url=control_plane.url,+ biscuit=enrollment.biscuit,+ expiration=enrollment.expiration,+ control_plane_keys=control_plane_keys,+ router_addresses=list(enrollment.router_addresses),+ ),+ state,+ )+ mesh.save()+ return mesh++ @classmethod+ def load(+ cls,+ state_dir: str | os.PathLike[str],+ *,+ identity: Optional[Identity] = None,+ allow_insecure: bool = False,+ transport: Optional[Transport] = None,+ ) -> "AgentMesh":+ """Resumes a member from a state directory written by an earlier enroll()."""+ state = Path(state_dir)+ identity = identity or _load_identity(state)+ if identity is None:+ raise FileNotFoundError(f"no identity in {state}; enroll first")+ credential = MeshCredential.from_json((state / _CREDENTIAL_FILE).read_text())+ control_plane = ControlPlaneClient(credential.control_plane_url, allow_insecure=allow_insecure, transport=transport)+ return cls(identity, control_plane, credential, state)++ def refresh(self) -> MeshCredential:+ """Trades the current biscuit for a fresh one and persists it. The control+ plane redeems only the last biscuit it issued, so a lost refresh result+ means re-enrolling; persisting before returning keeps that rare."""+ result = self.control_plane.refresh(self.identity, self._credential.biscuit)+ control_plane_keys = self._credential.control_plane_keys+ try:+ control_plane_keys = self.control_plane.keys(control_plane_keys)+ except Exception: # noqa: BLE001 - a failed /keys sync must not cost the new biscuit+ pass+ self._credential = replace(+ self._credential, biscuit=result.biscuit, expiration=result.expiration, control_plane_keys=control_plane_keys+ )+ self.save()+ return self._credential++ def auth_frame(self, target_service: str = "", agent: str = "") -> bytes:+ """The frame that opens every stream to a peer: this member's biscuit plus+ the service it wants (e.g. "mcp://calculator") and the agent it speaks for."""+ return encode_auth_frame(self._credential.biscuit, target_service, agent)++ def save(self) -> None:+ """Writes identity and credential to the state directory, if one is configured."""+ if self._state_dir is None:+ return+ self._state_dir.mkdir(parents=True, exist_ok=True, mode=0o700)+ _write_atomic(self._state_dir / _IDENTITY_FILE, self.identity.to_libp2p_private_key())+ _write_atomic(self._state_dir / _CREDENTIAL_FILE, self._credential.to_json().encode())+++def _load_identity(state: Optional[Path]) -> Optional[Identity]:+ if state is None:+ return None+ try:+ return Identity.from_libp2p_private_key((state / _IDENTITY_FILE).read_bytes())+ except FileNotFoundError:+ return None+++def _write_atomic(path: Path, data: bytes) -> None:+ tmp = path.with_name(path.name + ".tmp")+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "wb") as f:+ f.write(data)+ os.replace(tmp, path)diff --git a/sdk/python/tests/test_controlplane.py b/sdk/python/tests/test_controlplane.pynew file mode 100644index 00000000..530654cb--- /dev/null+++ b/sdk/python/tests/test_controlplane.py@@ -0,0 +1,233 @@+# 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.++"""A fake control plane behind an injected transport: enough of /enroll,+/enroll/status, /register, /refresh and /keys to check what the client sends+and how it treats every answer. The real one is exercised by+tests/integration/sdk_enroll_test.go."""++import base64+import threading+import time+import urllib.parse++import pytest++from agent_mesh import challenges+from agent_mesh._proto import sam_pb2 as pb+from agent_mesh.controlplane import (+ HEADER_CHALLENGE_SIGNATURE,+ HEADER_CHALLENGE_TIMESTAMP,+ KEYS_RESPONSE_FRESHNESS_MS,+ ROLE_NODE,+ ControlPlaneClient,+ ControlPlaneError,+ EnrollmentRejectedError,+ InsecureControlPlaneURLError,+ validate_control_plane_url,+ verify_keys_response,+)+from agent_mesh.identity import Identity, verify_ed25519++CP_KEY = Identity.generate()+BISCUIT = b"not-really-a-biscuit"+++def fake_transport(routes):+ """routes: {"METHOD /path": handler(url_parts, headers, body) -> (status, bytes)}"""++ def send(method, url, headers, body):+ parts = urllib.parse.urlsplit(url)+ handler = routes.get(f"{method} {parts.path}")+ if handler is None:+ return 404, f"no route for {method} {parts.path}".encode()+ return handler(parts, headers, body)++ return send+++def signed_keys(signers, timestamp=None):+ """Signs a KeysResponse the way api.SignKeysResponse does."""+ ts = int(time.time() * 1000) if timestamp is None else timestamp+ unsigned = pb.KeysResponse(public_keys=[s.public_key_raw for s in signers], timestamp=ts)+ payload = unsigned.SerializeToString(deterministic=True)+ return pb.KeysResponse(public_keys=list(unsigned.public_keys), timestamp=ts, signatures=[s.sign(payload) for s in signers])+++def test_validate_control_plane_url():+ assert validate_control_plane_url("https://hub.example/") == "https://hub.example"+ assert validate_control_plane_url("http://127.0.0.1:8080") == "http://127.0.0.1:8080"+ assert validate_control_plane_url("http://localhost") == "http://localhost"+ assert validate_control_plane_url("http://[::1]:9") == "http://[::1]:9"+ with pytest.raises(InsecureControlPlaneURLError):+ validate_control_plane_url("http://hub.example")+ assert validate_control_plane_url("http://hub.example", allow_insecure=True) == "http://hub.example"+ with pytest.raises(ValueError, match="must use http"):+ validate_control_plane_url("ftp://hub.example")+ with pytest.raises(ValueError, match="invalid control plane URL"):+ validate_control_plane_url("http://")+++def test_enroll_bootstrap_sends_bound_proof_and_polls_until_approved():+ identity = Identity.generate()+ seen = []+ router_addrs = ["/ip4/10.0.0.1/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"]++ def enroll(parts, headers, body):+ assert headers["Content-Type"] == "application/x-protobuf"+ r = pb.BootstrapEnrollRequest.FromString(body)+ assert r.bootstrap_token == "sbt_secret"+ assert r.peer_id == identity.peer_id+ assert r.public_key == identity.libp2p_public_key+ assert r.requested_role == ROLE_NODE+ assert dict(r.labels) == {"region": "eu"}+ assert abs(r.timestamp - time.time() * 1000) < 5000+ assert verify_ed25519(identity.public_key_raw, challenges.enroll_challenge(r.peer_id, r.timestamp), r.challenge_signature)+ seen.append("enroll")+ return 200, pb.BootstrapEnrollResponse(status=pb.ENROLLMENT_STATUS_PENDING, poll_interval_seconds=30).SerializeToString()++ def status(parts, headers, body):+ assert urllib.parse.parse_qs(parts.query)["peer_id"] == [identity.peer_id]+ ts = int(headers[HEADER_CHALLENGE_TIMESTAMP])+ sig = base64.urlsafe_b64decode(headers[HEADER_CHALLENGE_SIGNATURE] + "==")+ assert verify_ed25519(identity.public_key_raw, challenges.enroll_status_challenge(identity.peer_id, ts), sig)+ seen.append("status")+ if seen.count("status") < 2:+ return 200, pb.BootstrapEnrollResponse(status=pb.ENROLLMENT_STATUS_PENDING, poll_interval_seconds=30).SerializeToString()+ return 200, pb.BootstrapEnrollResponse(+ status=pb.ENROLLMENT_STATUS_APPROVED,+ biscuit_token=BISCUIT,+ control_plane_public_key=CP_KEY.public_key_raw,+ router_addresses=router_addrs,+ expiration=1_800_000_000,+ ).SerializeToString()++ client = ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /enroll": enroll, "GET /enroll/status": status}))+ enrollment = client.enroll_bootstrap(identity, "sbt_secret", labels={"region": "eu"}, poll_interval=0.001)+ assert seen == ["enroll", "status", "status"]+ assert enrollment.biscuit == BISCUIT+ assert enrollment.control_plane_public_key == CP_KEY.public_key_raw+ assert enrollment.router_addresses == router_addrs+ assert enrollment.expiration == 1_800_000_000+++def test_enroll_bootstrap_surfaces_rejection_http_error_and_empty_biscuit():+ identity = Identity.generate()++ def rejected(parts, headers, body):+ return 200, pb.BootstrapEnrollResponse(+ status=pb.ENROLLMENT_STATUS_REJECTED, error_message="Bootstrap token expired, revoked or exhausted"+ ).SerializeToString()++ with pytest.raises(EnrollmentRejectedError, match="exhausted"):+ ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /enroll": rejected})).enroll_bootstrap(identity, "x")++ with pytest.raises(ControlPlaneError, match="429.*Rate limit") as excinfo:+ ControlPlaneClient(+ "http://127.0.0.1:1", transport=fake_transport({"POST /enroll": lambda *a: (429, b"Rate limit exceeded")})+ ).enroll_bootstrap(identity, "x")+ assert excinfo.value.status == 429++ def empty(parts, headers, body):+ return 200, pb.BootstrapEnrollResponse(+ status=pb.ENROLLMENT_STATUS_APPROVED, control_plane_public_key=CP_KEY.public_key_raw+ ).SerializeToString()++ with pytest.raises(ValueError, match="empty biscuit"):+ ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /enroll": empty})).enroll_bootstrap(identity, "x")+++def test_enroll_bootstrap_stops_polling_when_cancelled():+ identity = Identity.generate()+ pending = lambda *a: (200, pb.BootstrapEnrollResponse(status=pb.ENROLLMENT_STATUS_PENDING, poll_interval_seconds=30).SerializeToString()) # noqa: E731+ client = ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /enroll": pending}))+ cancel = threading.Event()+ cancel.set()+ with pytest.raises(TimeoutError, match="cancelled"):+ client.enroll_bootstrap(identity, "x", cancel=cancel)+++def test_register_carries_jwt_and_register_bound_challenge():+ identity = Identity.generate()++ def register(parts, headers, body):+ r = pb.EnrollRequest.FromString(body)+ assert r.jwt == "eyJ.fake.jwt"+ assert r.peer_id == identity.peer_id+ assert r.requested_role == "sam:role:custom"+ assert verify_ed25519(identity.public_key_raw, challenges.register_challenge(r.peer_id, r.timestamp), r.challenge_signature)+ return 200, pb.EnrollResponse(biscuit_token=BISCUIT, control_plane_public_key=CP_KEY.public_key_raw, expiration=7).SerializeToString()++ e = ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /register": register})).register(+ identity, "eyJ.fake.jwt", role="sam:role:custom"+ )+ assert e.biscuit == BISCUIT+ assert e.expiration == 7++ denied = lambda *a: (200, pb.EnrollResponse(error_message="role not bound").SerializeToString()) # noqa: E731+ with pytest.raises(EnrollmentRejectedError, match="role not bound"):+ ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /register": denied})).register(identity, "j")+++def test_refresh_presents_bearer_biscuit_and_signs_refresh_challenge():+ identity = Identity.generate()++ def refresh(parts, headers, body):+ assert headers["Authorization"] == "Bearer " + base64.b64encode(BISCUIT).decode()+ r = pb.TokenRefreshRequest.FromString(body)+ assert r.peer_id == identity.peer_id+ assert verify_ed25519(identity.public_key_raw, challenges.refresh_challenge(identity.peer_id, r.timestamp), r.challenge_signature)+ return 200, pb.TokenRefreshResponse(biscuit_token=b"fresher-biscuit", expires_at=99).SerializeToString()++ result = ControlPlaneClient("http://127.0.0.1:1", transport=fake_transport({"POST /refresh": refresh})).refresh(identity, BISCUIT)+ assert result.biscuit == b"fresher-biscuit"+ assert result.expiration == 99++ with pytest.raises(ControlPlaneError) as excinfo:+ ControlPlaneClient(+ "http://127.0.0.1:1", transport=fake_transport({"POST /refresh": lambda *a: (401, b"Biscuit already rotated")})+ ).refresh(identity, BISCUIT)+ assert excinfo.value.status == 401+++def test_verify_keys_response_accepts_only_a_set_vouched_for_by_a_trusted_key():+ retiring = Identity.generate()+ resp = signed_keys([CP_KEY, retiring])++ assert verify_keys_response(resp, [CP_KEY.public_key_raw]) == [CP_KEY.public_key_raw, retiring.public_key_raw]+ assert verify_keys_response(resp, [retiring.public_key_raw]) == [CP_KEY.public_key_raw, retiring.public_key_raw]++ with pytest.raises(ValueError, match="no trusted control plane key"):+ verify_keys_response(resp, [])+ with pytest.raises(ValueError, match="not signed by any trusted"):+ verify_keys_response(resp, [Identity.generate().public_key_raw])+ with pytest.raises(ValueError, match="freshness window"):+ verify_keys_response(resp, [CP_KEY.public_key_raw], now_ms=resp.timestamp + KEYS_RESPONSE_FRESHNESS_MS + 1000)++ forged = pb.KeysResponse(public_keys=[Identity.generate().public_key_raw, retiring.public_key_raw], timestamp=resp.timestamp, signatures=list(resp.signatures))+ with pytest.raises(ValueError, match="not signed by any trusted"):+ verify_keys_response(forged, [retiring.public_key_raw])++ unsigned = pb.KeysResponse(public_keys=list(resp.public_keys), timestamp=resp.timestamp)+ with pytest.raises(ValueError, match="carries 0 signatures for 2 keys"):+ verify_keys_response(unsigned, [CP_KEY.public_key_raw])+++def test_keys_fetches_and_verifies_against_the_enrollment_key():+ client = ControlPlaneClient(+ "http://127.0.0.1:1", transport=fake_transport({"GET /keys": lambda *a: (200, signed_keys([CP_KEY]).SerializeToString())})+ )+ assert client.keys([CP_KEY.public_key_raw]) == [CP_KEY.public_key_raw]+ with pytest.raises(ValueError, match="not signed by any trusted"):+ client.keys([Identity.generate().public_key_raw])diff --git a/sdk/python/tests/test_identity.py b/sdk/python/tests/test_identity.pynew file mode 100644index 00000000..78edba2b--- /dev/null+++ b/sdk/python/tests/test_identity.py@@ -0,0 +1,75 @@+# 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.++import json+from pathlib import Path++import pytest++from agent_mesh import base58+from agent_mesh.challenges import enroll_challenge+from agent_mesh.identity import Identity, libp2p_public_key, peer_id_from_public_key, verify_ed25519++VECTORS = json.loads((Path(__file__).resolve().parents[2] / "testdata" / "identity_vectors.json").read_text())["vectors"]++[email protected]("v", VECTORS, ids=[v["peer_id"] for v in VECTORS])+def test_identity_matches_go_libp2p(v):+ identity = Identity.from_seed(bytes.fromhex(v["seed"]))+ assert identity.public_key_raw.hex() == v["public_key"]+ assert identity.peer_id == v["peer_id"]+ assert identity.libp2p_public_key.hex() == v["libp2p_public_key"]+ assert identity.to_libp2p_private_key().hex() == v["libp2p_private_key"]+ assert peer_id_from_public_key(bytes.fromhex(v["public_key"])) == v["peer_id"]+ # ed25519 signatures are deterministic, so the Go signature is reproducible.+ _, _, peer, ts = v["challenge"].split(":")+ assert identity.sign(enroll_challenge(peer, int(ts))).hex() == v["signature"]+ assert verify_ed25519(identity.public_key_raw, v["challenge"].encode(), bytes.fromhex(v["signature"]))+++def test_libp2p_private_key_round_trips_and_rejects_mismatch():+ identity = Identity.generate()+ assert Identity.from_libp2p_private_key(identity.to_libp2p_private_key()).peer_id == identity.peer_id++ tampered = bytearray(identity.to_libp2p_private_key())+ tampered[-1] ^= 0xFF+ with pytest.raises(ValueError, match="public half does not match"):+ Identity.from_libp2p_private_key(bytes(tampered))+ with pytest.raises(ValueError, match="not a libp2p ed25519 private key"):+ Identity.from_libp2p_private_key(bytes(tampered)[1:])+++def test_generated_identities_are_distinct_and_self_verify():+ a, b = Identity.generate(), Identity.generate()+ assert a.peer_id != b.peer_id+ sig = a.sign(b"hello")+ assert a.verify(b"hello", sig)+ assert not b.verify(b"hello", sig)+ assert not verify_ed25519(b"\x00" * 31, b"hello", sig)+++def test_libp2p_public_key_refuses_wrong_size():+ with pytest.raises(ValueError, match="32 bytes"):+ libp2p_public_key(b"\x00" * 33)++[email protected]("data", [b"", b"\x00", b"\x00\x00\x01\x02", bytes.fromhex("00ff"), bytes.fromhex("deadbeef")])+def test_base58_round_trips(data):+ assert base58.decode(base58.encode(data)) == data+++def test_base58_known_vector_and_invalid_character():+ assert base58.encode(b"Hello World!") == "2NEpo7TZRRrLZSi2U"+ with pytest.raises(ValueError, match="invalid base58 character"):+ base58.decode("0OIl")diff --git a/sdk/python/tests/test_mesh.py b/sdk/python/tests/test_mesh.pynew file mode 100644index 00000000..3894d825--- /dev/null+++ b/sdk/python/tests/test_mesh.py@@ -0,0 +1,126 @@+# 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.++import json+import stat+import time+import urllib.parse++import pytest++from agent_mesh._proto import sam_pb2 as pb+from agent_mesh.credential import decode_auth_response+from agent_mesh.identity import Identity+from agent_mesh.mesh import AgentMesh++CP_KEY = Identity.generate()+++class FakeControlPlane:+ """Approves everything and hands out numbered biscuits."""++ def __init__(self, keys_ok=True):+ self.issued = 0+ self.keys_ok = keys_ok++ def _signed_keys(self):+ ts = int(time.time() * 1000)+ unsigned = pb.KeysResponse(public_keys=[CP_KEY.public_key_raw], timestamp=ts)+ return pb.KeysResponse(public_keys=[CP_KEY.public_key_raw], timestamp=ts, signatures=[CP_KEY.sign(unsigned.SerializeToString(deterministic=True))])++ def transport(self, method, url, headers, body):+ path = urllib.parse.urlsplit(url).path+ if (method, path) == ("POST", "/enroll"):+ self.issued += 1+ return 200, pb.BootstrapEnrollResponse(+ status=pb.ENROLLMENT_STATUS_APPROVED,+ biscuit_token=f"biscuit-{self.issued}".encode(),+ control_plane_public_key=CP_KEY.public_key_raw,+ router_addresses=["/dns4/router.example/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"],+ expiration=int(time.time()) + 3600,+ ).SerializeToString()+ if (method, path) == ("POST", "/refresh"):+ self.issued += 1+ return 200, pb.TokenRefreshResponse(biscuit_token=f"biscuit-{self.issued}".encode(), expires_at=int(time.time()) + 7200).SerializeToString()+ if (method, path) == ("GET", "/keys"):+ return (200, self._signed_keys().SerializeToString()) if self.keys_ok else (500, b"boom")+ return 404, f"no route for {method} {path}".encode()+++def test_enroll_persists_load_resumes_refresh_rotates(tmp_path):+ cp = FakeControlPlane()+ token_path = tmp_path / "bootstrap.token"+ token_path.write_text("sbt_secret\n")+ state = tmp_path / "state"++ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token_path=token_path, state_dir=state, transport=cp.transport)+ assert mesh.credential.biscuit == b"biscuit-1"+ assert mesh.credential.control_plane_keys == [CP_KEY.public_key_raw]+ assert len(mesh.credential.router_addresses) == 1+ assert mesh.credential.time_to_live_seconds() > 3500++ # Secrets on disk are owner-only.+ for name in ("identity.key", "credential.json"):+ assert stat.S_IMODE((state / name).stat().st_mode) == 0o600, name+ assert stat.S_IMODE(state.stat().st_mode) == 0o700++ resumed = AgentMesh.load(state, transport=cp.transport)+ assert resumed.peer_id == mesh.peer_id+ assert resumed.credential.biscuit == b"biscuit-1"+ assert resumed.control_plane.url == "http://127.0.0.1:1"++ resumed.refresh()+ assert resumed.credential.biscuit == b"biscuit-2"+ on_disk = json.loads((state / "credential.json").read_text())+ assert on_disk["biscuit"] == "YmlzY3VpdC0y" # base64("biscuit-2")++ # Re-enrolling from the same directory keeps the identity.+ again = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt_secret", state_dir=state, transport=cp.transport)+ assert again.peer_id == mesh.peer_id+++def test_enroll_without_state_dir_keeps_enrollment_key_when_keys_fails():+ cp = FakeControlPlane(keys_ok=False)+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt_secret", transport=cp.transport)+ assert mesh.credential.control_plane_keys == [CP_KEY.public_key_raw]+ mesh.save()+ mesh.refresh()+ assert mesh.credential.biscuit == b"biscuit-2"+++def test_enroll_refuses_ambiguous_credentials():+ cp = FakeControlPlane()+ with pytest.raises(ValueError, match="exactly one of"):+ AgentMesh.enroll("http://127.0.0.1:1", transport=cp.transport)+ with pytest.raises(ValueError, match="exactly one of"):+ AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="a", jwt="b", transport=cp.transport)+ assert cp.issued == 0+++def test_load_without_identity_says_enroll_first(tmp_path):+ with pytest.raises(FileNotFoundError, match="enroll first"):+ AgentMesh.load(tmp_path)+++def test_auth_frame_is_the_protobuf_with_this_members_biscuit():+ cp = FakeControlPlane()+ mesh = AgentMesh.enroll("http://127.0.0.1:1", bootstrap_token="sbt_secret", transport=cp.transport)+ frame = pb.AuthFrame.FromString(mesh.auth_frame("mcp://calculator", "agent:acme.example:bot"))+ assert frame.biscuit == b"biscuit-1"+ assert frame.target_service == "mcp://calculator"+ assert frame.agent == "agent:acme.example:bot"++ resp = decode_auth_response(pb.AuthResponse(success=False, error="denied").SerializeToString())+ assert resp.success is False+ assert resp.error == "denied"diff --git a/sdk/testdata/identity_vectors.json b/sdk/testdata/identity_vectors.jsonnew file mode 100644index 00000000..b127f4f1--- /dev/null+++ b/sdk/testdata/identity_vectors.json@@ -0,0 +1,23 @@+{+ "_comment": "ed25519 identity vectors produced with go-libp2p (crypto.MarshalPrivateKey, peer.IDFromPublicKey). sig is the ed25519 signature over the UTF-8 challenge; all values hex except peer_id (base58btc).",+ "vectors": [+ {+ "seed": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",+ "public_key": "03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8",+ "peer_id": "12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB",+ "libp2p_private_key": "08011240000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f03a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8",+ "libp2p_public_key": "0801122003a107bff3ce10be1d70dd18e74bc09967e4d6309ba50d5f1ddc8664125531b8",+ "challenge": "sam:enroll:12D3KooWA4Xop1JaT3MHxwYMkCepYsv4iPVopMXwCz5iHYdBfeSB:1700000000000",+ "signature": "575045472111763965a2fb46f642af2dc5665caf03138039fbb42bb62f8c2671de3717e5a83b6c50096ad9846b9139a19bc816375669549a9ddc23a8dc416c09"+ },+ {+ "seed": "42434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f6061",+ "public_key": "c5db2c53c2bcf3dd886f05e60ac9828ed244e61a4fdc09277d58bdf4af1ba29f",+ "peer_id": "12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp",+ "libp2p_private_key": "0801124042434445464748494a4b4c4d4e4f505152535455565758595a5b5c5d5e5f6061c5db2c53c2bcf3dd886f05e60ac9828ed244e61a4fdc09277d58bdf4af1ba29f",+ "libp2p_public_key": "08011220c5db2c53c2bcf3dd886f05e60ac9828ed244e61a4fdc09277d58bdf4af1ba29f",+ "challenge": "sam:enroll:12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp:1700000000000",+ "signature": "f529ba43012e38e023407ffa01f62ace64795d72c57dbaac81d7018b12577f3384f3b8ee570c7da580066f0358525fb040878180cd253a17dec9a7a8eaaaa200"+ }+ ]+}diff --git a/tests/integration/sdk_enroll_test.go b/tests/integration/sdk_enroll_test.gonew file mode 100644index 00000000..ae237846--- /dev/null+++ b/tests/integration/sdk_enroll_test.go@@ -0,0 +1,410 @@+// 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.++package integration_test++import (+ "bytes"+ "context"+ "crypto/ed25519"+ "encoding/base64"+ "encoding/hex"+ "encoding/json"+ "io"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/google/sam/api"+ "github.com/google/sam/internal/controlplane"+ "github.com/google/sam/internal/identity"+ "github.com/google/sam/internal/storage"+ "github.com/libp2p/go-libp2p/core/crypto"+ "github.com/libp2p/go-libp2p/core/peer"+ "google.golang.org/protobuf/proto"+)++// sdkConformanceReport is what sdk/js/src/conformance.ts and+// sdk/python/src/agent_mesh/conformance.py print after enrolling, reloading+// from disk and refreshing against the control plane this test runs.+type sdkConformanceReport struct {+ SDK string `json:"sdk"`+ PeerID string `json:"peer_id"`+ PublicKey string `json:"public_key"`+ Biscuit string `json:"biscuit"`+ Expiration int64 `json:"expiration"`+ ControlPlaneKeys []string `json:"control_plane_keys"`+ RouterAddresses []string `json:"router_addresses"`+ ReloadedPeerID string `json:"reloaded_peer_id"`+ RefreshedBiscuit string `json:"refreshed_biscuit"`+ RefreshedExpiration int64 `json:"refreshed_expiration"`+ AuthFrame string `json:"auth_frame"`+}++// sdkRunner is how to start one SDK's conformance runner, or why it cannot+// run here. The SDKs are not Go and are not built by `go test`, so a+// missing toolchain skips rather than fails; CI installs both.+type sdkRunner struct {+ name string+ cmd func(root string) (*exec.Cmd, string)+}++var sdkRunners = []sdkRunner{+ {+ name: "js",+ cmd: func(root string) (*exec.Cmd, string) {+ entry := filepath.Join(root, "sdk", "js", "dist", "conformance.js")+ if _, err := exec.LookPath("node"); err != nil {+ return nil, "node is not installed"+ }+ if _, err := os.Stat(entry); err != nil {+ return nil, "sdk/js is not built (cd sdk/js && npm ci && npm run build)"+ }+ return exec.Command("node", entry), ""+ },+ },+ {+ name: "python",+ cmd: func(root string) (*exec.Cmd, string) {+ python := filepath.Join(root, "sdk", "python", ".venv", "bin", "python")+ if _, err := os.Stat(python); err != nil {+ var lookErr error+ if python, lookErr = exec.LookPath("python3"); lookErr != nil {+ return nil, "python3 is not installed"+ }+ }+ if err := exec.Command(python, "-c", "import agent_mesh").Run(); err != nil {+ return nil, "agent_mesh is not importable (pip install -e sdk/python)"+ }+ return exec.Command(python, "-m", "agent_mesh.conformance"), ""+ },+ },+}++// TestNativeSDKs is the interoperability check for the native SDKs: each one+// enrolls a fresh identity over the mesh protocol (protobuf over HTTP,+// signed proof-of-possession challenges) with a real control plane in+// manual-approval mode, polls /enroll/status until this test approves it,+// reloads its state from disk, refreshes its biscuit and reports what it+// holds. The control plane's own verification of every request is the+// judge; this test then checks that what the SDK holds is what the control+// plane issued and bound to the peer ID the SDK derived.+func TestNativeSDKs(t *testing.T) {+ root := repoRoot(t)+ oidcURL, _ := startCustomMockOIDC(t)++ store, err := storage.NewSQLStore("sqlite", filepath.Join(t.TempDir(), "cp.db"))+ if err != nil {+ t.Fatalf("failed to create store: %v", err)+ }+ t.Cleanup(func() { _ = store.Close() })++ const adminToken = "test-admin-token"+ srv, err := controlplane.NewServer(controlplane.Options{+ ListenAddr: "127.0.0.1:0",+ AdminToken: adminToken,+ OIDCIssuer: oidcURL,+ AllowedAudiences: []string{"sam-mesh-audience"},+ AutoApproveEnrollment: false,+ }, store)+ if err != nil {+ t.Fatalf("failed to create control plane: %v", err)+ }+ if err := srv.Start(); err != nil {+ t.Fatalf("failed to start control plane: %v", err)+ }+ t.Cleanup(func() { _ = srv.Close() })+ baseURL := "http://" + srv.Addr()++ ctx := context.Background()+ _, cpPub, err := store.GetCurrentKey(ctx)+ if err != nil {+ t.Fatalf("failed to load control plane signing key: %v", err)+ }++ // A router lease is what puts router addresses in an approved enrollment.+ routerAddr := "/ip4/127.0.0.1/tcp/4001/p2p/12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp"+ if err := store.UpsertRouterLease(ctx, &storage.RouterLease{+ PeerID: "12D3KooWP8iKhDf3iCMo2H3butNVfdTUtYwYWYQ75jTGnynXPFMp",+ Addresses: []string{routerAddr},+ LastRenewal: time.Now(),+ ExpiresAt: time.Now().Add(time.Hour),+ }); err != nil {+ t.Fatalf("failed to register router lease: %v", err)+ }++ for _, runner := range sdkRunners {+ t.Run(runner.name, func(t *testing.T) {+ cmd, skip := runner.cmd(root)+ if skip != "" {+ t.Skipf("%s SDK: %s", runner.name, skip)+ }++ tokenPath := filepath.Join(t.TempDir(), "bootstrap.token")+ if err := os.WriteFile(tokenPath, []byte(mintBootstrapToken(t, baseURL, adminToken)+"\n"), 0o600); err != nil {+ t.Fatalf("failed to write bootstrap token: %v", err)+ }+ stateDir := filepath.Join(t.TempDir(), "state")++ var stdout, stderr bytes.Buffer+ cmd.Stdout = &stdout+ cmd.Stderr = &stderr+ cmd.Dir = root+ cmd.Env = append(os.Environ(),+ "SAM_CONTROL_PLANE_URL="+baseURL,+ "SAM_BOOTSTRAP_TOKEN_PATH="+tokenPath,+ "SAM_SDK_STATE_DIR="+stateDir,+ )+ if err := cmd.Start(); err != nil {+ t.Fatalf("failed to start %s runner: %v", runner.name, err)+ }+ done := make(chan error, 1)+ go func() { done <- cmd.Wait() }()++ // The runner is now polling /enroll/status with signed challenges.+ // Approve it the way an operator would.+ peerID := approvePendingEnrollment(t, baseURL, adminToken, done)++ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("%s runner failed: %v\nstdout:\n%s\nstderr:\n%s", runner.name, err, stdout.String(), stderr.String())+ }+ case <-time.After(8 * time.Second):+ _ = cmd.Process.Kill()+ t.Fatalf("%s runner did not finish after approval\nstdout:\n%s\nstderr:\n%s", runner.name, stdout.String(), stderr.String())+ }++ var report sdkConformanceReport+ if err := json.Unmarshal(stdout.Bytes(), &report); err != nil {+ t.Fatalf("%s runner printed no report: %v\nstdout:\n%s\nstderr:\n%s", runner.name, err, stdout.String(), stderr.String())+ }+ verifySDKReport(t, ctx, store, cpPub, peerID, routerAddr, &report)++ // The state directory holds the identity in the encoding sam-node+ // uses and nothing world-readable.+ keyBytes, err := os.ReadFile(filepath.Join(stateDir, "identity.key"))+ if err != nil {+ t.Fatalf("identity.key not written: %v", err)+ }+ priv, err := crypto.UnmarshalPrivateKey(keyBytes)+ if err != nil {+ t.Fatalf("identity.key is not a libp2p private key: %v", err)+ }+ if fromKey, _ := peer.IDFromPrivateKey(priv); fromKey != peerID {+ t.Fatalf("identity.key belongs to %s, report says %s", fromKey, peerID)+ }+ for _, name := range []string{"identity.key", "credential.json"} {+ info, err := os.Stat(filepath.Join(stateDir, name))+ if err != nil {+ t.Fatalf("%s not written: %v", name, err)+ }+ if mode := info.Mode().Perm(); mode != 0o600 {+ t.Errorf("%s has mode %o, want 0600", name, mode)+ }+ }+ })+ }+}++// verifySDKReport checks a runner's report against the control plane's+// records: the peer ID is the one the control plane bound, both biscuits+// verify under the control plane key for that peer with the node role, the+// refresh was persisted server-side, and the AuthFrame the SDK would open a+// stream with carries the refreshed biscuit.+func verifySDKReport(t *testing.T, ctx context.Context, store storage.Store, cpPub ed25519.PublicKey, peerID peer.ID, routerAddr string, report *sdkConformanceReport) {+ t.Helper()+ if report.PeerID != peerID.String() {+ t.Fatalf("report peer_id %s, control plane enrolled %s", report.PeerID, peerID)+ }+ if report.ReloadedPeerID != report.PeerID {+ t.Errorf("identity did not survive reload: %s vs %s", report.ReloadedPeerID, report.PeerID)+ }++ // The SDK's peer ID derivation, checked from the raw key with go-libp2p.+ rawPub, err := hex.DecodeString(report.PublicKey)+ if err != nil || len(rawPub) != ed25519.PublicKeySize {+ t.Fatalf("report public_key is not a raw ed25519 key: %q", report.PublicKey)+ }+ pub, err := crypto.UnmarshalEd25519PublicKey(rawPub)+ if err != nil {+ t.Fatalf("report public_key does not unmarshal: %v", err)+ }+ if derived, _ := peer.IDFromPublicKey(pub); derived != peerID {+ t.Errorf("peer ID %s does not derive from the reported public key (got %s)", peerID, derived)+ }++ node, err := store.GetNode(ctx, peerID.String())+ if err != nil {+ t.Fatalf("control plane has no node record for %s: %v", peerID, err)+ }+ if libp2pPub, _ := crypto.MarshalPublicKey(pub); !bytes.Equal(node.PublicKey, libp2pPub) {+ t.Errorf("control plane stored public key %x, SDK holds %x", node.PublicKey, libp2pPub)+ }+ if node.Role != api.RoleNode {+ t.Errorf("node enrolled with role %q, want %q", node.Role, api.RoleNode)+ }++ const biscuitTimeout = 5 * time.Second+ biscuit := decodeB64(t, "biscuit", report.Biscuit)+ refreshed := decodeB64(t, "refreshed_biscuit", report.RefreshedBiscuit)+ for name, b := range map[string][]byte{"biscuit": biscuit, "refreshed_biscuit": refreshed} {+ if _, err := identity.VerifyBiscuitAndGetExpiry(b, peerID, []ed25519.PublicKey{cpPub}, biscuitTimeout); err != nil {+ t.Errorf("%s does not verify for %s under the control plane key: %v", name, peerID, err)+ }+ if err := identity.VerifyBiscuitRole(b, cpPub, api.RoleNode, biscuitTimeout); err != nil {+ t.Errorf("%s lacks role %s: %v", name, api.RoleNode, err)+ }+ }+ if bytes.Equal(biscuit, refreshed) {+ t.Error("refresh returned the same biscuit")+ }+ // Only the last issued biscuit is redeemable, so the control plane must+ // hold the refreshed one, and that is what the SDK must present next.+ if !bytes.Equal(node.Biscuit, refreshed) {+ t.Error("control plane's current biscuit for the node is not the refreshed one the SDK holds")+ }+ if report.RefreshedExpiration <= time.Now().Unix() || report.Expiration <= time.Now().Unix() {+ t.Errorf("expirations are not in the future: %d, %d", report.Expiration, report.RefreshedExpiration)+ }++ if len(report.ControlPlaneKeys) == 0 || !containsHex(report.ControlPlaneKeys, cpPub) {+ t.Errorf("control_plane_keys %v does not include the signing key %x", report.ControlPlaneKeys, cpPub)+ }+ if len(report.RouterAddresses) != 1 || report.RouterAddresses[0] != routerAddr {+ t.Errorf("router_addresses %v, want [%s]", report.RouterAddresses, routerAddr)+ }++ var frame api.AuthFrame+ if err := proto.Unmarshal(decodeB64(t, "auth_frame", report.AuthFrame), &frame); err != nil {+ t.Fatalf("auth_frame is not an AuthFrame: %v", err)+ }+ if !bytes.Equal(frame.Biscuit, refreshed) {+ t.Error("auth_frame does not carry the refreshed biscuit")+ }+ if frame.TargetService != "mcp://echo" || frame.Agent != "agent:example.test:conformance" {+ t.Errorf("auth_frame target/agent = %q/%q", frame.TargetService, frame.Agent)+ }+}++func mintBootstrapToken(t *testing.T, baseURL, adminToken string) string {+ t.Helper()+ body, err := json.Marshal(api.BootstrapTokenRequest{+ Role: api.RoleNode,+ TTLHours: 1,+ MaxUsages: 1,+ Description: "native sdk conformance",+ })+ if err != nil {+ t.Fatalf("failed to encode bootstrap token request: %v", err)+ }+ req, err := http.NewRequest(http.MethodPost, baseURL+"/admin/bootstrap-tokens", bytes.NewReader(body))+ if err != nil {+ t.Fatalf("failed to build bootstrap token request: %v", err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+adminToken)+ resp, err := (&http.Client{Timeout: 5 * time.Second}).Do(req)+ if err != nil {+ t.Fatalf("failed to create bootstrap token: %v", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusCreated {+ msg, _ := io.ReadAll(resp.Body)+ t.Fatalf("unexpected status creating token: %s body %s", resp.Status, msg)+ }+ var token struct {+ Token string `json:"token"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&token); err != nil || token.Token == "" {+ t.Fatalf("failed to decode bootstrap token: %v", err)+ }+ return token.Token+}++// approvePendingEnrollment waits for the runner's enrollment request to+// appear, approves it and returns the peer ID the control plane bound. done+// reports a runner that gave up before that.+func approvePendingEnrollment(t *testing.T, baseURL, adminToken string, done <-chan error) peer.ID {+ t.Helper()+ client := &http.Client{Timeout: 5 * time.Second}+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ select {+ case err := <-done:+ t.Fatalf("runner exited before its enrollment was approved: %v", err)+ default:+ }+ req, _ := http.NewRequest(http.MethodGet, baseURL+"/admin/enrollments", nil)+ req.Header.Set("Authorization", "Bearer "+adminToken)+ resp, err := client.Do(req)+ if err != nil {+ time.Sleep(50 * time.Millisecond)+ continue+ }+ var pending []storage.EnrollmentRequest+ decodeErr := json.NewDecoder(resp.Body).Decode(&pending)+ _ = resp.Body.Close()+ if decodeErr != nil || resp.StatusCode != http.StatusOK {+ time.Sleep(50 * time.Millisecond)+ continue+ }+ for _, e := range pending {+ if e.Status != api.EnrollmentStatus_ENROLLMENT_STATUS_PENDING {+ continue+ }+ approve, _ := http.NewRequest(http.MethodPost, baseURL+"/admin/enrollments/"+e.ID+"/approve", nil)+ approve.Header.Set("Authorization", "Bearer "+adminToken)+ approveResp, err := client.Do(approve)+ if err != nil {+ t.Fatalf("failed to approve enrollment: %v", err)+ }+ msg, _ := io.ReadAll(approveResp.Body)+ _ = approveResp.Body.Close()+ if approveResp.StatusCode != http.StatusOK {+ t.Fatalf("failed to approve enrollment: %s body %s", approveResp.Status, msg)+ }+ pid, err := peer.Decode(e.PeerID)+ if err != nil {+ t.Fatalf("control plane recorded an undecodable peer ID %q: %v", e.PeerID, err)+ }+ return pid+ }+ time.Sleep(50 * time.Millisecond)+ }+ t.Fatal("runner's enrollment request never appeared")+ return ""+}++func decodeB64(t *testing.T, field, value string) []byte {+ t.Helper()+ b, err := base64.StdEncoding.DecodeString(value)+ if err != nil || len(b) == 0 {+ t.Fatalf("report %s is not base64 or is empty: %q", field, value)+ }+ return b+}++func containsHex(values []string, want []byte) bool {+ for _, v := range values {+ if strings.EqualFold(v, hex.EncodeToString(want)) {+ return true+ }+ }+ return false+}