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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions .github/pull_request_template.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
Describe the behavior change and why it is needed.

Validation:
- Report the verification command and result. For user-facing changes, include the
operation you exercised and its observed outcome.
- Identify the evidence used (fixture, configuration adapter or actual provider/client).
Include relevant client/protocol/model versions and any skipped checks.
- For a release, identify the commit and CI artifact containing the tested wheel and sdist.

- Commands/results, with simulated and real-provider evidence distinguished.
- Client/protocol/model versions if relevant.
- Remaining limitations or required manual checks.

Do not include keys or unredacted private logs. An administrator code-owner review is required.
Keep keys and private logs out of the PR. An independent administrator reviews the change.
28 changes: 18 additions & 10 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ jobs:
python: ['3.11', '3.14']
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: ${{ matrix.python }}
- run: python -m pip install .
Expand All @@ -28,23 +28,31 @@ jobs:
quality:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.11'
- run: python -m pip install . -r requirements-dev.txt
- run: ruff check .
- run: ruff format --check .
- run: python -m build
- run: python -m pip install -e . -r requirements-dev.txt
- name: Verify source, installed wheel and native journal model
run: |
curl --fail --location --silent --show-error --retry 3 \
https://github.com/tlaplus/tlaplus/releases/download/v1.7.4/tla2tools.jar -o "$RUNNER_TEMP/tla2tools.jar"
python scripts/verify.py --tlc-jar "$RUNNER_TEMP/tla2tools.jar" --dist-dir dist
- name: Archive checked wheel and source distribution
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: agent-connect-${{ github.sha }}-${{ github.run_attempt }}
path: dist/
if-no-files-found: error

magpie:
runs-on: ubuntu-latest
env:
ITERACONNECT_HOME: ${{ github.workspace }}/.local/ci
DO_NOT_TRACK: '1'
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
with:
python-version: '3.11'
- run: python -m pip install .
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,5 @@ dist/
reports/
.ruff_cache/
agent-connect.local.toml
.mypy_cache/
.import_linter_cache/
19 changes: 10 additions & 9 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
# Agent Connect development

This repository is independent of IteraCompute/LLMProxy. Do not change production gateway,
website or platform services as part of connector development.
Scope is this connector repository. Production gateway, website and platform services
belong in their own repositories. Use a feature branch and submit a PR for independent
administrator review.

- Python source is in `src/iteraconnect`; the runtime uses the standard library only.
- Use `python -m unittest discover -v`, Ruff check/format and `python -m build`.
- Optional real Magpie/native fixture tests are documented in `docs/testing.md`.
- The simple app stores keys only in ignored private local TOML; runtime provider profiles use environment references. Never print keys, request bodies or arbitrary client logs.
- Distinguish fixture tests, config adapter checks and actual provider/client acceptance.
- Preserve upstream MIT notices and pinned source/release provenance.
- Work on a feature branch and open a PR. Do not merge or bypass administrator review.
Run `python scripts/verify.py` before review. [Testing and release](docs/testing.md)
covers setup, the installed-wheel checks, the recovery model and release artifacts.

- Keep credentials in ignored private local TOML or runtime environment references.
Never print keys, request bodies or arbitrary client logs.
- Preserve upstream MIT notices and pinned source and release provenance.
- Report fixture, configuration adapter and actual provider/client evidence separately.
2 changes: 2 additions & 0 deletions MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,5 @@ include start.py Start.command Start.bat config.example.toml
recursive-include docs *.md
recursive-include docs/images *.jpg
recursive-include tests *.py
include scripts/verify.py
recursive-include verification *.cfg *.tla
45 changes: 41 additions & 4 deletions docs/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,49 @@ Tests deliberately distinguish three kinds of evidence:

```bash
python -m pip install -e . -r requirements-dev.txt
python -m unittest discover -v
ruff check .
ruff format --check .
python -m build
python scripts/verify.py
```

Run these commands from an activated Python 3.11+ virtual environment. The verifier runs
Ruff, mypy across the runtime (including unannotated function bodies), and the import layers
declared in `pyproject.toml`. New runtime modules must fit a layer. The configuration boundary
requires typed function signatures. A test scans static imports for the standard-library-only
runtime contract, including imports inside functions.

The verifier then runs `python -m build`, installs the wheel built from the sdist into a fresh
environment, initializes a disposable CLI profile and reads it back. It runs unittest discovery
against that installation, including the loopback control panel, packaged web assets, fixture
provider probes and client config restoration. For a shorter edit cycle, run
`python -m unittest discover -v` against the editable installation.

### Native configuration recovery model

The TLA+ model covers one client file, an initial connection, reconnections, an interruption
between journaling and replacing the file, and a later external edit with a distinct digest.
TLC checks that the original image survives reconnection, a restore is enabled after an
interrupted write, and the adapter preserves that external edit. The model assumes serialized
operations and atomic single-file replacement. Concurrent external writers, interruptions
during disconnect, and filesystem durability are outside its scope. The Python regression in
`NativeEditorTests` injects a write failure into the real adapter and checks exact recovery for
both existing and absent files.

CI runs the model on every PR. To reproduce this locally, install Java 11+ and download
`tla2tools.jar` from the pinned release. Run
`python scripts/verify.py --tlc-jar /path/to/tla2tools.jar`. The verifier checks its SHA-256
before execution. [TLC release](https://github.com/tlaplus/tlaplus/releases/tag/v1.7.4) ·
[Model and properties](../verification/NativeJournal.tla)

### Release handoff

Each successful quality job archives the exact sdist and wheel it tested, under
`agent-connect-<commit SHA>-<run attempt>` in GitHub Actions. For release, use the artifact from the
successful **push to protected main** for the reviewed commit. Check the commit SHA and
aggregate `checks` result before using that artifact. The PR run is available for review.
A local rehearsal can retain both artifacts in a new directory with
`python scripts/verify.py --tlc-jar /path/to/tla2tools.jar --dist-dir dist/candidate`.

### Optional native and Magpie checks

For the actual Magpie engine, install the pinned binary, then set
`ITERACONNECT_TEST_MAGPIE_BIN` to its absolute path:

Expand Down
33 changes: 32 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,4 +31,35 @@ target-version = "py311"
line-length = 100

[tool.ruff.lint]
select = ["E4", "E7", "E9", "F", "I"]
select = ["B", "E4", "E7", "E9", "F", "I", "PGH003", "PGH004", "RUF100"]

[tool.mypy]
files = ["src/iteraconnect"]
python_version = "3.11"
check_untyped_defs = true
warn_unused_ignores = true
warn_redundant_casts = true

[[tool.mypy.overrides]]
module = "iteraconnect.config"
disallow_untyped_defs = true
disallow_any_generics = true
warn_return_any = true

[tool.importlinter]
root_package = "iteraconnect"

[[tool.importlinter.contracts]]
name = "Runtime dependencies point from entry points toward configuration"
type = "layers"
containers = ["iteraconnect"]
exhaustive = true
layers = [
"__main__",
"cli",
"app",
"smoke",
"diagnostics | gateway | integrations | launch | native",
"network | settings",
"config",
]
2 changes: 2 additions & 0 deletions requirements-dev.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
ruff==0.17.5
build==1.6.1
mypy==2.4.1
import-linter==2.16
89 changes: 89 additions & 0 deletions scripts/verify.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""Check the checkout and exercise the distributions built from it."""

import argparse
import hashlib
import json
import os
import shutil
import subprocess
import sys
import sysconfig
import tempfile
import venv
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
# tlaplus/tlaplus release v1.7.4, tla2tools.jar (TLC 2.19).
TLC_SHA256 = "936a262061c914694dfd669a543be24573c45d5aa0ff20a8b96b23d01e050e88"


def check_wheel(wheel: Path, work: Path) -> None:
environment = work / "env"
venv.EnvBuilder(with_pip=True).create(environment)
scripts = environment / ("Scripts" if os.name == "nt" else "bin")
python = scripts / ("python.exe" if os.name == "nt" else "python")
cli = scripts / ("itera-connect.exe" if os.name == "nt" else "itera-connect")
subprocess.run(
[python, "-I", "-m", "pip", "--isolated", "install", "--no-index", "--no-deps", wheel],
cwd=work,
check=True,
)
# Give the installed CLI and fixture suite a disposable home and state directory.
env = {k: os.environ[k] for k in ("PATH", "SystemRoot", "TEMP", "TMP") if k in os.environ}
env.update(HOME=str(work), USERPROFILE=str(work), ITERACONNECT_HOME=str(work / "state"))
subprocess.run([cli, "init"], cwd=work, env=env, check=True)
result = subprocess.run(
[cli, "provider", "list"], cwd=work, env=env, check=True, capture_output=True
)
if json.loads(result.stdout)["active_provider"] != "iteracompute":
raise SystemExit("Installed CLI failed to load the initialized profile")
subprocess.run(
[python, "-I", "-m", "unittest", "discover", "-v", "-s", ROOT / "tests", "-t", ROOT],
cwd=work,
env=env,
check=True,
)


def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dist-dir", type=Path, help="new directory for the verified artifacts")
parser.add_argument("--tlc-jar", type=Path, help="also check the native journal model with TLC")
args = parser.parse_args()
python = sys.executable
lint_imports = Path(sysconfig.get_path("scripts")) / (
"lint-imports.exe" if os.name == "nt" else "lint-imports"
)
for command in (
[python, "-m", "ruff", "check", "."],
[python, "-m", "ruff", "format", "--check", "."],
[python, "-m", "mypy"],
[lint_imports],
):
subprocess.run(command, cwd=ROOT, check=True)
with tempfile.TemporaryDirectory() as temporary:
work = Path(temporary)
if args.tlc_jar:
jar = args.tlc_jar.resolve()
with jar.open("rb") as file:
if hashlib.file_digest(file, "sha256").hexdigest() != TLC_SHA256:
raise SystemExit("Unexpected digest for the TLC release jar")
subprocess.run(
["java", "-cp", jar, "tlc2.TLC", "-metadir", work / "tlc", "NativeJournal"],
cwd=ROOT / "verification",
check=True,
)
dist = work / "dist"
subprocess.run([python, "-m", "build", "--outdir", dist], cwd=ROOT, check=True)
# The default build makes an sdist and builds its wheel from that sdist.
(wheel,) = dist.glob("*.whl")
(sdist,) = dist.glob("*.tar.gz")
check_wheel(wheel, work)
if args.dist_dir:
args.dist_dir.mkdir(parents=True, exist_ok=False)
for artifact in (sdist, wheel):
shutil.copy2(artifact, args.dist_dir)


if __name__ == "__main__":
main()
38 changes: 31 additions & 7 deletions src/iteraconnect/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,34 @@
import secrets
import tempfile
from pathlib import Path
from typing import NotRequired, TypedDict
from urllib.parse import urlsplit

PROTOCOLS = ("chat", "responses", "anthropic", "gemini")
DEFAULT = {


class ProviderConfig(TypedDict):
name: str
key_env: str
default_model: str
endpoints: dict[str, str]
allow_http: NotRequired[bool]


class GatewayConfig(TypedDict):
host: str
port: int
timeout: float


class RuntimeConfig(TypedDict):
schema_version: int
active_provider: str
gateway: GatewayConfig
providers: dict[str, ProviderConfig]


DEFAULT: RuntimeConfig = {
"schema_version": 1,
"active_provider": "iteracompute",
"gateway": {"host": "127.0.0.1", "port": 18423, "timeout": 180},
Expand Down Expand Up @@ -81,7 +105,7 @@ def validate_url(value: str, allow_http: bool = False) -> str:
return value.rstrip("/")


def validate(data: dict) -> dict:
def validate(data: RuntimeConfig) -> RuntimeConfig:
try:
if data["schema_version"] != 1 or not data["providers"]:
raise ValueError
Expand Down Expand Up @@ -122,7 +146,7 @@ def validate(data: dict) -> dict:
return data


def load(path: Path | None = None) -> dict:
def load(path: Path | None = None) -> RuntimeConfig:
path = path or state_dir() / "config.json"
if not path.exists():
return copy.deepcopy(DEFAULT)
Expand All @@ -132,7 +156,7 @@ def load(path: Path | None = None) -> dict:
raise ConnectError("Invalid configuration JSON") from None


def save(data: dict, path: Path | None = None) -> None:
def save(data: RuntimeConfig, path: Path | None = None) -> None:
private_write(path or state_dir() / "config.json", json.dumps(validate(data), indent=2) + "\n")


Expand All @@ -152,15 +176,15 @@ def gateway_key() -> str:
if len(value) < 24:
raise ConnectError(
"Invalid gateway.key; restore it or remove it to create a new local key"
)
) from None
return value
value = "ic-" + secrets.token_urlsafe(32)
with os.fdopen(fd, "w") as f:
f.write(value)
return value


def api_key(provider: dict, required: bool = True) -> str:
def api_key(provider: ProviderConfig, required: bool = True) -> str:
value = os.environ.get(provider["key_env"], "")
if required and not value:
raise ConnectError(f"Set {provider['key_env']} in the gateway process environment")
Expand All @@ -169,6 +193,6 @@ def api_key(provider: dict, required: bool = True) -> str:
return value


def gateway_url(config: dict, pid: str | None = None) -> str:
def gateway_url(config: RuntimeConfig, pid: str | None = None) -> str:
base = f"http://127.0.0.1:{config['gateway']['port']}"
return base + (f"/p/{pid}" if pid else "")
Loading
Loading