Skip to main content

swarph-mesh

PyPI Python Docs codecov License: MIT

Model-agnostic Python substrate for the swarph-mesh ecosystem. Pure library, no CLI.

Designed to fill the gap left by existing tools (aichat, mods, Simon Willison's llm, gemini-cli, claude-cli): none expose mesh-gateway participation, per-caller attribution, structured-output discipline, or the cooperative-protocol patterns the swarph encodes.

This is one of three repos in the v0.3.x architecture:

Repo Role
swarph-mesh This package — typed Protocol + adapters + SwarphCall + MeshClient
swarph-cli The swarph binary. Thin client over swarph-mesh
swarph-meshlm Simon Willison llm plugin. Same primitives wired into llm's plugin host

All three sit on top of swarph-shared which provides the cross-billing-path attribution + subprocess env scrubbing + JSON-mode harness + peer-name registry primitives.

Status

v0.6.1 — PRICING table catch-up + alias resolution. Patches v0.6.0's discovery substrate with corrected pricing for ~20 models surfaced by the AIMLAPI catalog diff:

  • Critical fix: gpt-5 was at (5.00, 20.00) speculative in v0.5.x; real direct OpenAI pricing is (1.25, 10.00) — anyone calling gpt-5 between v0.5.x and v0.6.1 had cost_usd over-attributed by ~4x.
  • New OpenAI entries: gpt-4.1 family (4.1 / 4.1-mini / 4.1-nano), gpt-5-mini, gpt-5-nano, gpt-5.2, gpt-5.2-pro.
  • New Anthropic entries: claude-opus-4-1 (premium $15/$75 tier), claude-sonnet-4-5, claude-sonnet-4, claude-haiku-3-5, claude-haiku-3 + dated-build aliases (claude-opus-4-5-20251101, etc.).
  • New xAI entries: grok-4-3, grok-4-20-*, grok-4-1-fast-*, grok-4-fast-* (current generation per xAI docs). grok-4 + grok-code-fast-1 retire 2026-05-15 per xAI; v0.6.1 documents this in _GROK_RETIREMENT_NOTICE.
  • New xAI / DeepSeek alias normalizers: _normalize_xai_id strips x-ai/ prefix + -beta + dated suffixes; _normalize_deepseek_id strips deepseek/ prefix + version suffixes. AIMLAPI's prefixed catalog IDs now resolve to PRICING entries instead of falling through to _default.
  • New Gemini entries: gemini-2.0-flash, gemini-2.0-flash-001.
  • _OPENAI_PRICING_VERIFIED_AT / _GROK_PRICING_VERIFIED_AT / _GEMINI_PRICING_VERIFIED_AT metadata added for future drift detection (drop DM #720 direction).

v0.6.0 — architectural promotion: model discovery substrate. Four primitives:

  • Catalog (AIMLAPI primary + per-provider fallback)
  • Gemini pricing (Cloud Billing Catalog API)
  • Anthropic pricing (manual table from claude.com/pricing with verified_at provenance)
  • OpenAI cost reconciliation (admin-key gated /v1/organization/costs)
  • LLMAdapter.list_models() Protocol method (breaking change → v0.6.0 major-version bump)

Public surface:

  • LLMAdapter Protocol (runtime-checkable) + ChatMessage + LLMResponse

  • SwarphCall — caller-convention-validated entry point with hooks + attribution

  • GeminiAdapter — wraps langgraph-genai-bridge (Flex tier, context caching)

  • DeepSeekAdapter (v0.3.0) — OpenAI-protocol-compatible client for V4-Flash / V4-Pro / V3 aliases; preserves reasoning content as [reasoning] preamble for portability

  • ClaudeAdapter (v0.4.0) — subprocess-based wrapper around claude -p for subscription billing path (no ANTHROPIC_API_KEY needed; reads ~/.claude/.credentials.json). Reuses swarph_shared.scrub_env_for_subprocess to keep billing-relevant env keys out of the subprocess. #244: cost_usd carries the CLI's own total_cost_usd with cost_basis="list" (list-price equivalent of subscription consumption; older CLIs without the field → 0.0 + "unknown"), and thinking_tokens + the cache read/creation TTL split are captured into the contract fields. A locally-computed metered-equivalent stays in raw_response["api_metered_cost_usd"] as a cross-check — raw_response itself is still stripped before the attribution row is written; what survives to the row is AttributionEvent.extra, which the default post-call hook now populates with {billing_path, max_price_usd, vendor_domicile} (the v0.1 dead-extra defect is closed).

  • OpenAIAdapter (v0.5.0) — native async via openai.AsyncOpenAI (no asyncio.to_thread threadpool ceiling). Pricing for gpt-4o / gpt-4o-mini / o1 / o3 / o3-mini / o4-mini / gpt-5. o-series reasoning_content preserved as [reasoning] preamble. OPENAI_API_KEY env fallback.

  • GrokAdapter (v0.5.0) — xAI's OpenAI-compatible API at https://api.x.ai/v1, also via AsyncOpenAI. Pricing for grok-4 / grok-3 / grok-3-mini. Dual env-var resolution: XAI_API_KEY (canonical) → GROK_API_KEY (alias). Same [reasoning] preamble shape as the rest of the adapter family.

  • AntigravityAdapter — Google subscription lane via the antigravity CLI, firejail-sandboxed. #244: runs agy -p --output-format json and captures thinking_tokens / cache_read_tokens from the envelope's usage block; agy reports no cost figure, so cost_usd=0.0 with cost_basis="unknown" — an honest unknown, not a measured free call (a consumer-side price table may upgrade the row to "calculated").

  • GeminiCLIAdapter — Gemini subscription lane via the local CLI (sibling of the metered GeminiAdapter).

  • GrokCLIAdapter (v0.7.9) — xAI subscription lane: firejail-sandboxed grok --prompt-file on a SuperGrok-Heavy OIDC session token. Stateless per call (--no-memory, --no-subagents); metered XAI_API_KEY is deliberately scrubbed so no pay-per-token fallback can fire.

  • VibeCLIAdapter (v0.8.0) — Mistral subscription lane: firejail-sandboxed vibe -p, prompt piped on stdin (never written to disk), no tools at all (--disabled-tools '*'), and an ephemeral VIBE_HOME so the worker is stateless by construction. Carries --max-price, a hard per-call dollar ceiling enforced by the CLI — the only lane with a call-site cost bound. Note the inversion from the grok lane: Mistral issues subscription API keys, so MISTRAL_API_KEY is the subscription path and must be allowlisted through the env scrub, not stripped. Reports vendor_domicile="FR" and processing_residency="unknown" as separate informational facts — neither is a routing-eligibility jurisdiction.

  • swarph_mesh.discovery (NEW v0.6.0) — three primitives:

    • Catalog backed by AIMLAPI's public /models endpoint (no auth, ~600+ entries) with per-provider /v1/models fallback when AIMLAPI is unreachable. list_models(provider=...), is_model_supported(model_id), get_model_info(model_id). 24h TTL cache.
    • Gemini pricing via Google's Cloud Billing Catalog API (service 241C-273D-49C8 = Vertex AI). fetch_gemini_pricing() and pricing_for_gemini_model(hint, direction, tier). Auth: GOOGLE_CLOUD_BILLING_API_KEY env (separate from GEMINI_API_KEY — Cloud Console project key with Billing API scope).
    • Anthropic pricing via static manual table mirrored from claude.com/pricing (Anthropic does not expose programmatic pricing). pricing_for_anthropic_model(id) returns full 5-tuple (base input + 5m cache + 1h cache + cache hit + output) per model. Honest about origin via verified_at field; update by re-pasting the docs table.
    • OpenAI/xAI/DeepSeek pricing stays in adapter-local PRICING dicts until programmatic sources surface.
  • LLMAdapter.list_models() (NEW v0.6.0) — Protocol-level method. Each adapter delegates to discovery.list_models(provider=self.name). Breaking change: external implementations of LLMAdapter from v0.5.x must implement this method to satisfy the runtime-checkable Protocol.

  • JSON-mode harness — retry-once with [USER]-turn feedback (per swarph-shared invariant)

  • Attribution: FileAttributionWriter default; set_default_writer() for production TSDB consumers

  • MeshClient (v0.2.0) — async wrapper around mesh-gateway HTTP API; replaces hand-rolled curl in inbox-drain scripts

Tests: 253+ passing (250 offline + live gates: 1 claude subscription + 1 antigravity subscription (#244 envelope gate) + 1 deepseek + 2 mesh + 1 gemini + 1 openai + 1 grok + 3 discovery against live AIMLAPI; live tests gated on env/creds or SWARPH_SKIP_NETWORK=1).

from swarph_mesh import SwarphCall, ChatMessage

# Phase 1 — LLM call with attribution
result = await SwarphCall(
    provider="gemini",
    caller="orchestrator.boss",
).chat(
    messages=[ChatMessage(role="user", content="hi")],
)
print(result.text, result.cost_usd, result.input_tokens)
from swarph_mesh import MeshClient
import os

# Phase 3 — mesh-gateway DM coordination
async with MeshClient(node="my-cell") as client:  # token from MESH_GATEWAY_TOKEN env
    peers = await client.list_peers()
    msgs = await client.fetch(unread_only=True)
    sent = await client.send(to="peer-cell", kind="fyi", content="hello")
    await client.mark_read(msgs[0].id)

MeshClient.send() enforces two structural invariants:

  1. Recipient name validation via swarph_shared.validate_node_name — closes the framing-contagion class (Vector A peer-onboarding chatter, Vector B human-prompt shorthand).
  2. Mesh-secrets out-of-band guard — best-effort regex sniff for credential-shaped content (PyPI tokens, Anthropic keys, GitHub tokens, JWTs, AWS keys). Hits raise MeshSecretLeakError BEFORE the POST. Operator escape hatch via skip_secret_check=True for legitimate prose mentioning credential shapes. Treat "mesh secrets out-of-band only" as non-negotiable; the guard catches obvious cases.

Phase rollout

Phase Scope
0 (v0.0.1) Typed substrate — Protocol + dataclasses + exceptions
1 (v0.1.0) Gemini adapter + SwarphCall surface + caller convention import + JSON-mode harness + attribution hook
3 (v0.2.0) MeshClient async wrapper + recipient validation + mesh-secrets guard
4 #2 (v0.3.0) DeepSeek adapter — OpenAI-protocol-compatible, V4-Flash default, V4-Pro premium, V3 aliases preserved, reasoning_content kept as [reasoning] preamble
4 #3 (v0.4.0) Claude subscription adapter — wraps claude -p via subprocess, reads ~/.claude/.credentials.json, billing-leak prevention via scrub_env_for_subprocess
4 #4 + #5 (v0.5.0 — this release) OpenAI + Grok adapters — both native-async via AsyncOpenAI from day one (per issue #7); xAI on base_url=https://api.x.ai/v1; Phase 4 ship-order complete
5.5 swarph onboard + swarph ratify (lives in swarph-cli, depends on this)
5.7 swarph daemon + REPL drain coroutine (lives in swarph-cli)
6 (already done) PyPI publish
7 swarph-meshlm plugin (separate repo, this dep)

Skunkworks (0.9.1)

swarph_mesh.skunkworks is a research pipeline any cell can run on subscription lanes: ideation, web research, an architect audit, then a human gate. Run it with the swarph skunkworks commands from swarph-cli (run, status, show, stop, decide). Ideation and the architect are jobs on the mesh queue; research spends the requesting cell's own Claude quota; nothing is metered. Runs are refused Monday to Friday 09:30-16:00 New York time (market holidays too: there is no holiday calendar), at most 10 jobs and 30 minutes per run, one live run per cell, three runs per cell per UTC day. Approval produces no code: a build still needs its own spec, plan and review. A killed process leaves the run in ERROR and nothing resumes it.

Install (dev)

git clone https://github.com/BrainSurfing-tech/swarph-mesh
cd swarph-mesh
python -m venv venv && source venv/bin/activate
pip install -e ".[dev]"
pytest

License

MIT. Pierre Samson + Claude Opus, 2026.

Metadata

Release files for swarph-mesh 0.9.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for swarph-mesh 0.9.1
File Size Uploaded Provenance Actions
swarph_mesh-0.9.1.tar.gz 199.5 kB With provenance Details for swarph_mesh-0.9.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for swarph-mesh 0.9.1
File Interpreter ABI Platform Actions
swarph_mesh-0.9.1-py3-none-any.whl Python 3 none any Details for swarph_mesh-0.9.1-py3-none-any.whl

Total release size: 337.8 kB

Release files / swarph_mesh-0.9.1.tar.gz

Download URL swarph_mesh-0.9.1.tar.gz
Size 199.5 kB
Tags Source
SHA-256 checksum
How to use checksums
2289c161cf7aba29c1d3ca94564eddca9ba1d46c2d0061fe81008478fae108ef
BLAKE2b-256 checksum
How to use checksums
a9b782473562d2ee3f8a9c18bdfe97491b6a3c0ed4eb4c64783b9d205c7db3e2
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Release files / swarph_mesh-0.9.1-py3-none-any.whl

Download URL swarph_mesh-0.9.1-py3-none-any.whl
Size 138.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
12f0ace1c3426eeca11b87659506980577000b2c358cff35f6f8c704fd73cbf6
BLAKE2b-256 checksum
How to use checksums
46945deb7309549c894041ec7439331250d511b8810c17e4cb52c9f2edab6c06
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

Security for swarph-mesh 0.9.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for swarph_mesh-0.9.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 4, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page