diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 4bb3c5c..75cd17b 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,2 +1,2 @@ -# Repository administrator. Update through an administrator-reviewed pull request. -* @K-3-LT +# Existing repository administrators. Update through administrator review. +* @K-3-LT @aikevan diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml new file mode 100644 index 0000000..b7e387c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -0,0 +1,20 @@ +name: Bug report +description: Report a reproducible connector problem without credentials +body: + - type: textarea + id: problem + attributes: + label: What happened? + description: Include reproduction steps, expected behavior, client versions, protocol and model ID. Never include keys or private prompts. + validations: + required: true + - type: dropdown + id: evidence + attributes: + label: Backend used + options: + - Local fixture + - IteraCompute API + - Other API + validations: + required: true diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml new file mode 100644 index 0000000..291515e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -0,0 +1,10 @@ +name: Feature request +description: Suggest a provider, agent or workflow improvement +body: + - type: textarea + id: proposal + attributes: + label: Proposal + description: Explain the use case, relevant upstream links, and expected behavior. Do not include credentials. + validations: + required: true diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..2f41603 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,9 @@ +Describe the behavior change and why it is needed. + +Validation: + +- 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. diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..ff1e514 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,70 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + +permissions: + contents: read + +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, macos-latest, windows-latest] + python: ['3.11', '3.14'] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: ${{ matrix.python }} + - run: python -m pip install . + - run: python -m unittest discover -v + - run: itera-connect --version + + quality: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + 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 + + 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 + with: + python-version: '3.11' + - run: python -m pip install . + - run: itera-connect install-magpie + - name: Verify real Magpie translation and five native config adapters with fixture backend + run: | + export ITERACONNECT_TEST_MAGPIE_BIN="$ITERACONNECT_HOME/bin/magpie" + python -m unittest tests.test_magpie.MagpieTests -v + + checks: + if: always() + needs: [test, quality, magpie] + runs-on: ubuntu-latest + steps: + - name: Require every validation job + env: + TEST_RESULT: ${{ needs.test.result }} + QUALITY_RESULT: ${{ needs.quality.result }} + MAGPIE_RESULT: ${{ needs.magpie.result }} + run: | + test "$TEST_RESULT" = success + test "$QUALITY_RESULT" = success + test "$MAGPIE_RESULT" = success diff --git a/.gitignore b/.gitignore index 3f852c5..a82e44e 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,4 @@ dist/ .local/ reports/ .ruff_cache/ +agent-connect.local.toml diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..20ffa8f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,12 @@ +# Agent Connect development + +This repository is independent of IteraCompute/LLMProxy. Do not change production gateway, +website or platform services as part of connector development. + +- 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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..d8b9061 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,25 @@ +# Contributing + +Issues, Discussions and pull requests are welcome. Include a minimal reproduction, versions, +protocol and model ID. Redact keys, prompts and private paths before sharing logs. + +Develop in a branch and run the checks in [testing.md](docs/testing.md). New behavior should +include an appropriate contract test; fixture evidence and real service evidence must remain +separate. Change upstream pins deliberately, retain licenses and verify release digests. + +`main` is protected. Merging requires a repository administrator named in `.github/CODEOWNERS`, +at least one approval, approval of the latest reviewable push, resolution of review conversations +and the `checks` CI status. Stale reviews are dismissed. Administrators are subject to these rules. +Force pushes and deletion of `main` are disabled. CI runs untrusted contributions with read-only +repository access and no provider secrets. Automated merge is disabled. + +The repository administrators are `@K-3-LT` and `@aikevan`; both are proposed as CODEOWNERS in +the initial implementation PR. Additional administrators can be added to CODEOWNERS +through the same reviewed workflow; reviewers must have write access for GitHub to recognize +their code-owner approval. Authors cannot approve their own pull requests. Normal contributions need a separate +administrator/reviewer account; administrator identity does not count as independent self-review. + +Organization Actions is enabled for this repository, with read-only default workflow tokens and +no workflow review approval. See [governance setup](docs/governance.md) for the initial base-branch +ownership dependency and the current first-merge status. Initial setup exceptions require explicit +Owner approval, preserve required CI and must not become a permanent community-review bypass. diff --git a/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..c1a54f6 --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +include LICENSE THIRD_PARTY_NOTICES README.en.md CONTRIBUTING.md SECURITY.md requirements-dev.txt +include start.py Start.command Start.bat config.example.toml +recursive-include docs *.md +recursive-include docs/images *.jpg +recursive-include tests *.py diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000..4bfcb28 --- /dev/null +++ b/README.en.md @@ -0,0 +1,426 @@ +# Agent Connect + +**Choose an API → Choose a client → Connect.** + +[**中文**](README.md) | [**English**](README.en.md) + +A lightweight local connector for Claude Code, Codex, WorkBuddy, WorkBuddy AI, OpenClaw and Hermes. +IteraCompute is configured by default; you can save and switch to other compatible model APIs. +The UI, configuration editors and relay are independent implementations. No CC Switch or Magpie +application source is copied. The normal workflow requires **Python 3.11+** only: no pip install, +Node.js, CC Switch or Magpie installation is needed. + +![Agent Connect local workspace](docs/images/client.jpg) + +This README and the Chinese version contain the same complete workflow. The application UI +currently uses Chinese labels; the button reference below lets you follow this English guide. + +**Contents:** [Quick start](#quick-start) · [Key file](#fill-the-configuration-file) · [Other APIs](#connect-other-apis) · [Clients](#connect-each-client) · [Verification](#verify-the-connection) · [Restore](#switch-and-restore-settings) · [Troubleshooting](#troubleshooting) · [Contributing](#development-and-governance) + +## Quick start + +### 1. Prepare your environment + +- Install **Python 3.11 or newer** and make sure your terminal can run it. +- Install the client you want to connect. You can write configuration before installation, + but successful configuration is not evidence of a real inference response. +- Obtain an API key with access to your intended model. Verification can incur API usage. + +Check your Python version: + +```bash +# macOS / Linux +python3 --version +``` + +```powershell +# Windows PowerShell +py -3 --version +``` + +If Windows has no `py` launcher, use `python --version` and `python start.py`, provided that +`python` is version 3.11 or newer. + +### 2. Download and launch + +The initial implementation is on `feat/agent-connect` in [PR #1](https://github.com/IteraCompute/agent-connect/pull/1). +Before that PR reaches `main`, use these complete commands: + +```bash +git clone --branch feat/agent-connect https://github.com/IteraCompute/agent-connect.git +cd agent-connect +python3 start.py +``` + +On Windows, replace the last line with `py -3 start.py`. Without Git, download the +[branch ZIP](https://github.com/IteraCompute/agent-connect/archive/refs/heads/feat/agent-connect.zip), +extract it, and open the directory containing `start.py`. After the initial merge, you can also +clone the default `main` branch directly. + +| Platform | Recommended launch | Alternative | +| --- | --- | --- | +| Windows | `py -3 start.py` in the project directory | Double-click `Start.bat` | +| macOS | `python3 start.py` in the project directory | Double-click `Start.command`; use the terminal if execution is blocked | +| Linux | `python3 start.py` in the project directory | Your own terminal launcher | + +The launcher opens the local workspace and creates `agent-connect.local.toml` in the project +directory on first use. If the browser does not open, copy the **complete URL** printed in the +terminal, including the local management token after `#`. Opening only `http://127.0.0.1:18424/` +in a new browser session may not authorize management operations. + +### 3. Enter an API key and model + +1. Keep **IteraCompute** selected and enter your key in **API key**. +2. The default model is `openai/gpt-6-luna`, which passed the recorded acceptance checks. + Click **获取模型** (Fetch models) to choose another, or type its complete model ID. +3. Click **保存 API 设置** (Save API settings), or let connection, export or verification save + the form automatically. + +Fetching models requests the catalog only. It does not generate a response, save the draft or +replace the live relay credentials. Availability depends on your account and the current API; +see the dated [acceptance record](docs/acceptance.md). + +### 4. Select and connect a client + +1. Select a client card, such as **Claude Code**. +2. Check the API, model and protocol in the connection preview. Once it shows **协议匹配** + (Protocol matched), click **连接 Claude Code** (Connect Claude Code), or the equivalent + button for your selected client. +3. Agent Connect backs up the original file and writes that client's user configuration. + Fully quit and restart the client, then create a fresh session. +4. WorkBuddy / WorkBuddy AI also requires choosing the added `custom-local` model in the + task model menu; see [client instructions](#connect-each-client). + +Keep Agent Connect's launcher terminal running while using a connected client. Closing the +browser tab does not stop the service; press `Ctrl+C` in its terminal to stop it. Run the same +launch command next time to reload saved settings. Restarting Agent Connect alone, with the +same endpoint and model, does not require entering the key again. + +### UI button reference + +| Chinese label | Meaning | +| --- | --- | +| 添加 API / 取消添加 | Add API / Cancel adding | +| 获取模型 | Fetch models | +| 地址与协议 | URL and protocols | +| 保存 API 设置 | Save API settings | +| 重新读取 | Reload the private configuration file | +| 连接 + client name | Back up and configure the selected client | +| 测试 API | Test the selected client's API protocol | +| 客户端实测 | Run an isolated actual-client test | +| 导出配置 / 复制配置 | Export / Copy a manual configuration fragment | +| 恢复原配置 | Restore the configuration from before the first connection | +| 检查协议 | Open the protocol setting required by this client | + +## Fill the configuration file + +You can enter the key entirely through a file. Launch once, then edit the generated +`agent-connect.local.toml`: + +```toml +selected_provider = "iteracompute" +client = "claude" + +[providers.iteracompute] +name = "IteraCompute" +api_key = "" # Enter your key between the quotes +base_url = "https://api.iteracompute.com" +model = "openai/gpt-6-luna" +protocols = ["chat", "responses", "anthropic"] +``` + +This is a complete example. Normally only `api_key` needs changing. Save, then click +**重新读取** (Reload); if the service is not running, simply start it. You can also use the blank +[config.example.toml](config.example.toml), but do not overwrite a local file already containing a key. + +| Field | Purpose | +| --- | --- | +| `selected_provider` | API ID for this operation; must match a `[providers.]` table | +| `client` | `claude`, `codex`, `workbuddy`, `workbuddy-ai`, `openclaw` or `hermes` | +| `name` | Display name | +| `api_key` | This provider's credential; never returned to the page or written to client settings | +| `base_url` | API root or OpenAI-compatible `/v1` base | +| `model` | Complete model ID, including provider-supplied `/` characters | +| `protocols` | Native protocols the API actually serves; checking a box does not add server capabilities | + +The file is ignored by Git and uses owner-only read/write permissions on POSIX. On Windows, +keep it in your own user directory. Stored keys are not shown in the UI; leaving its key input +empty preserves the saved value. To remove a key, set `api_key = ""` in the file and reload. +The simple app uses this file exclusively, not other vendor credentials inherited from your shell. +Do not publish filled key files, management URLs or exported relay credentials in issues, PRs +or screenshots. + +If the UI says the local file changed, click **重新读取** before saving. The app stops the stale +save rather than overwrite a key you just entered outside the page. + +## Connect other APIs + +### Add through the workspace + +1. Click **添加 API** (Add API). +2. Enter a unique ID such as `my-api`. It must start with a lowercase letter and contain only + lowercase letters, digits and hyphens, with at most 48 characters. +3. Enter a display name and this API's key. Set its base URL under **地址与协议**. +4. Select the protocols the API **actually supports**. Fetch models or enter a model ID directly. +5. Choose a client and connect, or save the API for later selection in the provider menu. + +A new provider starts with an empty key and never inherits another provider's credential. +**取消添加** discards the new draft and restores the previous provider form. If the vendor does +not implement a model catalog, type the model ID it documents instead. + +### Choose the URL and protocols + +| API type | Example base | Protocol | Directly supported clients | +| --- | --- | --- | --- | +| OpenAI Chat compatible | `https://api.example.com/v1` | `chat` | WorkBuddy, WorkBuddy AI, OpenClaw, Hermes | +| OpenAI Responses compatible | `https://api.example.com/v1` | `responses` | Codex | +| Anthropic Messages compatible | `https://api.example.com` | `anthropic` | Claude Code | +| Multiple native protocols | Vendor's documented base | Only protocols it actually serves | Clients requiring those protocols | +| Local OpenAI-compatible server | `http://127.0.0.1:PORT/v1` | As supported by the server | Clients requiring those protocols | + +Enter a **base**, not a full inference route ending in `/chat/completions`, `/responses` or +`/v1/messages`. Public endpoints require HTTPS; loopback endpoints may use HTTP. A keyless local +server still needs a nonempty placeholder key such as `local` in Agent Connect. + +If protocols use different paths, append explicit endpoints after an existing provider table: + +```toml +[providers.my-api.endpoints] +chat = "https://api.example.com/openai/v1" +responses = "https://api.example.com/openai/v1" +anthropic = "https://api.example.com/anthropic" +``` + +This assumes `[providers.my-api]` already exists and advertises these protocols. See +[configuration](docs/configuration.md) for complete rules. + +The local relay preserves native protocols. It does not convert Chat to Responses or Messages. +A Chat-only service cannot directly serve Claude Code or Codex through the simple app; use the +[optional Magpie bridge](docs/advanced.md) when conversion is required. + +Configuration also accepts Gemini endpoints, but the six simple client cards use Chat, Responses +or Messages. See the [coverage matrix](docs/coverage.md) for Gemini-specific advanced access. + +## Connect each client + +These are the simple workspace's independent native adapters. No additional vendor key needs +to be entered in the client: it receives a local relay credential, and Agent Connect forwards requests. + +| Client | Required native protocol | Default user file edited | +| --- | --- | --- | +| Claude Code | Anthropic Messages | `~/.claude/settings.json` | +| Codex CLI | OpenAI Responses | `~/.codex/config.toml` | +| WorkBuddy | OpenAI Chat Completions | `~/.workbuddy/models.json` | +| WorkBuddy AI | OpenAI Chat Completions | `~/.workbuddy-ai/models.json` | +| OpenClaw | OpenAI Chat Completions | `~/.openclaw/openclaw.json` | +| Hermes | OpenAI Chat Completions | `~/.hermes/config.yaml` | + +`~` means the current user's home, typically `C:\Users\YOUR_NAME` on Windows. Client-specific +configuration environment variables change these paths; see [file locations](#file-locations-and-startup-options). + +### Claude Code + +Select **Claude Code**, connect, exit the old process and start a fresh `claude` session in a +new terminal. The adapter sets the Messages endpoint, model and local authentication while +preserving unrelated settings. Project settings, environment variables or enterprise policy +can still override user settings. Verify with the workspace's actual-client test or send the +fixed test message below in a new session. + +### Codex + +Select **Codex**, connect and restart `codex`. The adapter sets a Responses provider named +`iteraconnect` and your selected model. If an existing user file already contains an unrelated +provider with that name, the app reports an error and preserves the file. Rename that entry +before retrying or export and merge the fragment manually. Acceptance covers Codex CLI; +those results are not evidence for other desktop, IDE or cloud execution modes. + +### WorkBuddy / WorkBuddy AI + +Choose the card matching your installed edition, connect, restart the application and create +a new task. Select `custom-local:iteracompute/MODEL_ID` in the task model menu; replace +`iteracompute` with your API ID for other providers. The display name includes +`Agent Connect · MODEL_ID`. Existing models are preserved; the added model's `vendor` is `iteraconnect`. + +The workspace requests manual verification in the original application. Automated desktop +inference acceptance is not available; successful configuration alone is not a passing inference test. + +### OpenClaw + +Select **OpenClaw**, connect, restart its relevant processes using your normal launch method +and begin a fresh session. The adapter updates the provider and default model, extending an +existing model allowlist to include the connected model. It does not enable channel delivery. +The workspace test runs a local single turn with independent temporary settings and no daily sessions. + +### Hermes + +Select **Hermes**, connect, restart Hermes and create a new session. The adapter uses the +`custom:iteraconnect` provider with explicit Chat transport, preserving unrelated settings. +Automatic actual-client testing uses Hermes 0.23.1 JSONL output; older versions can be checked +manually in the original client. Complex YAML is rejected without rewriting the original; +use an exported fragment or the advanced adapter instead. + +## Verify the connection + +Testing is optional before connecting: you may test the API first. **Tests never run automatically +at startup.** + +| Operation | What it verifies | Usage and limits | +| --- | --- | --- | +| **获取模型** | Vendor model catalog | One catalog request; no generation or draft save | +| **测试 API** | Text, complete SSE and a tool-call/result round trip for the selected client's protocol | Up to 4 generation requests, each with a 256-token output budget | +| **客户端实测** | Installed Claude Code / Codex / OpenClaw / Hermes process and its actual reply | Uses API quota; temporary settings/directories; no daily logins or chats copied | +| WorkBuddy / WorkBuddy AI | Message and tool task inside the original application | Manual acceptance required and explicitly reported | + +Recommended sequence: + +1. Choose the API, model and client. Click **测试 API** and check that all three result cards pass. +2. For an installed client supporting automation, click **客户端实测**. +3. Connect, restart the original client and send this in a new session: + + ```text + Reply with exactly ITERACONNECT_OK. + ``` + +4. In a disposable test directory, ask the client to create and read a small file to verify + its actual tool workflow. + +The API tool test returns a fixed string; it never executes model-generated commands. A passing +native single turn does not establish the client's full tool loop, long sessions, vision, +permissions or error recovery. + +![Separate text, stream and tool-result cards](docs/images/test-passed.jpg) + +This result-card screenshot uses a **local simulated backend** to demonstrate the UI. Real +IteraCompute acceptance was recorded on 2026-11-16: the three native protocols and four actual +CLIs passed the listed checks with `openai/gpt-6-luna`. WorkBuddy desktop inference still awaits +manual acceptance. Earlier Auto 400/429 and a Haiku tool 502 are retained in the +[acceptance record](docs/acceptance.md), separately from simulated results. + +[GitHub CI](https://github.com/IteraCompute/agent-connect/actions/runs/44015209371) passed unit/fixture +tests on Ubuntu, macOS and Windows with Python 3.11/3.14, plus quality/build, Magpie and the required +aggregate check. Cross-platform CI does not replace real-client acceptance on each platform. + +### Read the status labels + +| Chinese status | Meaning | +| --- | --- | +| 有未保存更改 | API, model, protocol or client changed; connection, export and tests save automatically | +| 协议匹配 / 需要配置 | Checks declared protocol support only; a mismatch disables connection/tests and links to its setting | +| 已检测到安装 | A command or configuration directory exists; execution still needs verification | +| 已配置 · 可恢复 | An original-config backup exists, not an inference result for this model | +| API 测试通过 | All three protocol checks passed; expand the redacted report for details | +| 客户端实测通过 | The expected reply was confirmed in a real client's output | + +Changing the API, model or client clears old results. Client cards support Tab, arrow keys and +Home/End. Narrow screens use a stacked layout. + +## Switch and restore settings + +**Switch models or providers:** choose another API/model, keep the intended client selected, +connect again, then restart that client. Saving API settings alone does not edit client files. +Connecting one client does not automatically configure the others; connect each separately. + +A connected client keeps the provider and model last written for it. Changing a saved provider's +key or base URL affects the local relay. Do not remove providers still used by clients. Restore +before switching configuration managers to avoid competing changes. + +**Restore:** select the client, click **恢复原配置**, then restart it. The first connection records +the original content, which remains the backup across reconnections. If the file did not exist +before connecting, restoration removes the file created by Agent Connect. + +If another application edits the file after connection, automatic restoration stops to preserve +those later changes. Compare the backup under `native-backups` and merge manually; do not delete +the client's entire configuration directory. Standard JSON, Codex TOML and common indented +Hermes YAML/JSON are supported. JSON5 or complex structures are rejected with the original preserved. + +**Manual export:** click **导出配置**, expand the fragment and click **复制配置**. Merge it into the +appropriate file yourself. Export does not edit the client or mark it connected. Fragments +include a local relay credential and should remain on your machine. + +## File locations and startup options + +| File / endpoint | Default | Purpose | +| --- | --- | --- | +| Private API settings | `agent-connect.local.toml` in the project | Provider keys, models and last selection | +| State directory | `~/.config/iteraconnect` | Local relay key and backups | +| Original configuration backups | `native-backups` in the state directory | Original content and conflict checks for each client | +| Management workspace | `127.0.0.1:18424` | Per-launch token and Host/Origin checks | +| Inference relay | `127.0.0.1:18423` | Local API used by connected clients | + +`ITERACONNECT_HOME` overrides the state directory; otherwise it follows `XDG_CONFIG_HOME`. +Adapters honor `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `WORKBUDDY_CONFIG_DIR`, `WORKBUDDY_AI_CONFIG_DIR`, +`OPENCLAW_STATE_DIR` / `OPENCLAW_CONFIG_PATH`, and `HERMES_HOME`. + +```bash +# Change ports; on Windows replace python3 with py -3 +python3 start.py --port 18434 --relay-port 18433 + +# Do not open a browser; use the complete URL printed in the terminal +python3 start.py --no-browser + +# Show startup options +python3 start.py --help +``` + +Reconnect clients after changing the relay port. Run only one instance with the same ports. +To store private settings elsewhere, run these from the source directory: + +```bash +python3 -m pip install . +itera-connect app --settings /absolute/path/to/private.toml +``` + +`pip install .` installs this checkout; it does not imply a published PyPI release. The simple +app's TOML and advanced CLI's JSON are independent configurations. To update a checkout, run +`git pull --ff-only` in the project, then restart Agent Connect. Preserve the ignored local TOML. + +## Troubleshooting + +| Symptom | Check / action | +| --- | --- | +| Missing `python3` / `py`, or unsupported version | Install Python 3.11+ and reopen the terminal; on Windows check `python --version` | +| Missing `start.py` | Use the complete feature branch and enter the extracted/cloned directory; before release, `main` may contain bootstrap files only | +| Page unavailable / port occupied | Stop the old instance or change both ports; use the full terminal URL if the browser did not open | +| Management page is unauthorized | Use the URL from this launch; the management token changes after restarting the service | +| API 401 / 403 | Check key, account and model access; reload after editing the private file | +| 429 / 502 / timeout | Inspect redacted details; retry later or choose another authorized model; an explicit model is usually easier to diagnose than Auto | +| Model catalog fails | Check the base URL; the vendor may not expose a catalog, so type its documented model ID | +| Disabled connection / test buttons | Check the selected client's required protocol; do not declare support merely to enable a button | +| Configuration succeeded but old model remains | Quit old processes and start a new session; inspect project/environment/policy overrides and WorkBuddy's task model selection | +| Installed client reported missing | Check command visibility in the terminal launching Agent Connect and the actual config directory; connect first and test manually if needed | +| Cannot save after editing the file | Reload first to preserve external changes | +| Restore refused / JSON5 or YAML rejected | Original remains; compare backups and merge manually, or use the advanced adapter | +| Client cannot connect after closing workspace | Keep the launcher terminal running; restart Agent Connect if it was stopped | + +Raw vendor error bodies and arbitrary client logs are not returned directly, to avoid exposing +credentials or private context. The workspace serves this machine only. Remote sharing, +conversion and broader upstream settings are covered in the [advanced guide](docs/advanced.md). + +## Development and governance + +```bash +python3 -m venv .venv +source .venv/bin/activate +# Windows PowerShell: .venv\Scripts\Activate.ps1 +python -m pip install -e . -r requirements-dev.txt +python -m unittest discover -v +ruff check . +ruff format --check . +python -m build +``` + +Only the Python standard library is needed at runtime. Ruff and build above are development +dependencies. UI source is in `src/iteraconnect/web`, independent adapters in `native.py`, and +the relay in `gateway.py`. The [testing guide](docs/testing.md) distinguishes simulated vendor, +installed CLI and actual API evidence, including optional commands. + +MIT licensed. [Issues](https://github.com/IteraCompute/agent-connect/issues), +[Discussions](https://github.com/IteraCompute/agent-connect/discussions) and PRs are welcome. +Share versions, protocol, model ID and a redacted reproduction. Community contributions are +open; merges require administrator review. Main's review/CI policy, first CODEOWNERS setup +and repair status are recorded in [governance](docs/governance.md). + +For Magpie conversion, more clients, subscription logins, MCP, skills or CC Switch import, see +the [advanced entry points](docs/advanced.md) and [coverage matrix](docs/coverage.md). Optional +upstream versions, provenance and licenses are in [THIRD_PARTY_NOTICES](THIRD_PARTY_NOTICES) +and the lock file; those components follow their own credential/storage behavior. diff --git a/README.md b/README.md index 6f7ab38..ea627f3 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,347 @@ -# IteraCompute Agent Connect +# Agent Connect -Open-source provider and agent connectivity for IteraCompute, CC Switch and Magpie. +**选择 API → 选择客户端 → 点击连接。** -The initial implementation is developed through pull requests. Community issues and -pull requests are welcome; merging into `main` requires an administrator's review. +[**中文**](README.md) | [**English**](README.en.md) -Default API: `https://api.iteracompute.com/v1`. Custom providers remain supported. +一个在本机运行的轻量连接工具,让 Claude Code、Codex、WorkBuddy、WorkBuddy AI、OpenClaw 和 Hermes 使用你选择的模型 API。 +默认提供 IteraCompute,也可以保存和切换其他兼容服务。界面、配置管理和转发均为独立实现,没有复制 CC Switch 或 Magpie 的应用代码。 +正常使用只需要 **Python 3.11+**;无需 pip install、Node.js、CC Switch 或 Magpie。 + +![Agent Connect 本地工作台](docs/images/client.jpg) + +本 README 与英文版包含相同的完整使用流程。客户端界面目前使用中文;英文版附有按钮对照表。 + +**导航:** [快速开始](#快速开始) · [填写配置文件](#填写配置文件) · [其他-api](#接入其他-api) · [客户端操作](#连接不同的客户端) · [测试](#确认接入是否成功) · [恢复](#切换与恢复配置) · [常见问题](#常见问题) · [开源治理](#开发与开源治理) + +## 快速开始 + +### 1. 准备运行环境 + +- 安装 Python **3.11 或更新版本**,并确保终端能运行它。 +- 安装需要连接的客户端。未安装时也可先生成配置,但“连接成功”不代表已经完成真实推理。 +- 准备一个有目标模型访问权限的 API key。测试可能产生 API 用量。 + +检查 Python 版本: + +```bash +# macOS / Linux +python3 --version +``` + +```powershell +# Windows PowerShell +py -3 --version +``` + +Windows 没有 `py` 启动器时,可使用 `python --version` 和 `python start.py`,前提是该 Python 为 3.11+。 + +### 2. 下载并启动 + +首次发布的代码位于 [PR #1](https://github.com/IteraCompute/agent-connect/pull/1) 的 `feat/agent-connect` 分支。 +在它合并到 `main` 前,使用下面的完整命令: + +```bash +git clone --branch feat/agent-connect https://github.com/IteraCompute/agent-connect.git +cd agent-connect +python3 start.py +``` + +Windows 将最后一行换成 `py -3 start.py`。不使用 Git 时,可下载[该分支的 ZIP](https://github.com/IteraCompute/agent-connect/archive/refs/heads/feat/agent-connect.zip),解压后进入包含 `start.py` 的目录。 +首次发布合并后,也可直接克隆默认的 `main` 分支。 + +| 系统 | 推荐启动方式 | 可选启动方式 | +| --- | --- | --- | +| Windows | 在项目目录执行 `py -3 start.py` | 双击 `Start.bat` | +| macOS | 在项目目录执行 `python3 start.py` | 双击 `Start.command`;系统不允许执行时使用终端方式 | +| Linux | 在项目目录执行 `python3 start.py` | 使用你自己的终端启动器 | + +启动后会打开本地工作台。首次运行还会在项目目录生成 `agent-connect.local.toml`。 +如果浏览器没有打开,请复制终端打印的**完整地址**,包括 `#` 后的本地管理令牌;只打开 `http://127.0.0.1:18424/` 的新浏览器会话可能无法管理配置。 + +### 3. 填写 API 与模型 + +1. 保持默认的 **IteraCompute**,在 **API key** 输入框填写你的 key。 +2. 模型默认是验收时通过的 `openai/gpt-6-luna`。也可点击 **获取模型**,再在输入框选择或填写完整模型 ID。 +3. 可点击 **保存 API 设置**。连接、导出或测试时也会自动保存。 + +“获取模型”只请求目录,不进行生成、不保存草稿,也不会替换当前转发使用的密钥。 +模型是否可用,以你的账号权限和当前 API 返回为准;历史验收记录见[测试状态](docs/acceptance.md)。 + +### 4. 选择客户端并连接 + +1. 点击需要使用的客户端卡片,例如 **Claude Code**。 +2. 检查“本次连接”的 API、模型与协议。显示 **协议匹配** 后,点击 **连接 Claude Code** 等对应按钮。 +3. Agent Connect 会备份原配置,并写入这个客户端的用户配置。完全退出并重新启动对应客户端,再新建会话。 +4. WorkBuddy / WorkBuddy AI 还需要在任务的模型菜单中选择新增的 `custom-local` 模型,详见[客户端操作](#连接不同的客户端)。 + +使用客户端期间,请保持 Agent Connect 的启动终端运行。关闭浏览器标签页不会停止服务;在启动终端按 `Ctrl+C` 才会停止。 +下次执行同一个启动命令即可读取已保存的设置。仅重新启动 Agent Connect、地址和模型都没有变化时,无需重复填写 key。 + +## 填写配置文件 + +也可以完全通过文件填写 key。推荐先启动一次,再编辑已经生成的 `agent-connect.local.toml`: + +```toml +selected_provider = "iteracompute" +client = "claude" + +[providers.iteracompute] +name = "IteraCompute" +api_key = "" # 在引号内填写你的 key +base_url = "https://api.iteracompute.com" +model = "openai/gpt-6-luna" +protocols = ["chat", "responses", "anthropic"] +``` + +这是一份完整示例。通常只需要填写 `api_key`,其余值保留默认。 +保存文件后,在界面点击 **重新读取**;如果服务尚未启动,直接启动即可。 +也可使用空白模板 [config.example.toml](config.example.toml),但不要覆盖已经填写过 key 的本地文件。 + +| 字段 | 用途 | +| --- | --- | +| `selected_provider` | 本次使用的 API 标识,须与某个 `[providers.<标识>]` 一致 | +| `client` | `claude`、`codex`、`workbuddy`、`workbuddy-ai`、`openclaw` 或 `hermes` | +| `name` | 界面显示名称 | +| `api_key` | 此服务商的凭据;不会返回给网页或写入客户端配置 | +| `base_url` | API 根地址或 OpenAI 兼容的 `/v1` 地址 | +| `model` | 完整模型 ID;保留服务商提供的 `/` 等字符 | +| `protocols` | API 实际提供的原生协议,不能通过勾选增加服务端能力 | + +本地文件已被 Git 忽略,POSIX 系统使用仅当前用户可读写的权限;Windows 请将项目保存在自己的用户目录。 +界面不回显已保存的 key,输入框留空表示保留它;要删除 key,请在文件中设为 `api_key = ""` 后重新读取。 +简化客户端只读取此文件中的 key,不会使用终端里已有的其他供应商 key。 +请勿将填过 key 的文件、本地管理地址或导出的网关令牌公开到 Issue、PR 或截图中。 + +如果你编辑文件后网页提示“本地配置文件已被修改”,点击 **重新读取** 后再操作。程序会停止保存,避免旧页面覆盖刚填好的 key。 + +## 接入其他 API + +### 在工作台添加 + +1. 点击 **添加 API**。 +2. 输入唯一标识,例如 `my-api`。标识以小写字母开头,只含小写字母、数字和短横线,最多 48 个字符。 +3. 输入显示名称、此 API 的 key,并在 **地址与协议** 中填写 API 地址。 +4. 勾选该 API **实际支持**的协议,再点击 **获取模型**,或直接输入模型 ID。 +5. 选择客户端后点击连接,或先保存,以后从 API 服务商菜单切换。 + +新增服务商时 key 为空,不会沿用另一家的凭据。点击 **取消添加** 会丢弃新增草稿,回到原服务商设置。 +模型目录接口不存在时,可以直接填写供应商提供的模型 ID。 + +### 地址与协议如何填写 + +| API 类型 | 地址示例 | 勾选的协议 | 可直接接入的客户端 | +| --- | --- | --- | --- | +| OpenAI Chat 兼容 | `https://api.example.com/v1` | `chat` | WorkBuddy、WorkBuddy AI、OpenClaw、Hermes | +| OpenAI Responses 兼容 | `https://api.example.com/v1` | `responses` | Codex | +| Anthropic Messages 兼容 | `https://api.example.com` | `anthropic` | Claude Code | +| 同时提供多个原生协议 | 供应商的 API 基地址 | 只勾选实际提供的协议 | 对应协议的客户端 | +| 本地 OpenAI 兼容服务 | `http://127.0.0.1:你的端口/v1` | 按服务能力勾选 | 对应协议的客户端 | + +上表使用的是基地址,**不要**填写 `/chat/completions`、`/responses` 或 `/v1/messages` 等完整推理路径。 +公网地址使用 HTTPS;本机回环服务允许 HTTP。对于无需鉴权的本地服务,仍需填一个非空占位 key,例如 `local`。 + +不同协议位于不同路径时,可在本地 TOML 中设置 `endpoints`。例如在已有的服务商表后追加: + +```toml +[providers.my-api.endpoints] +chat = "https://api.example.com/openai/v1" +responses = "https://api.example.com/openai/v1" +anthropic = "https://api.example.com/anthropic" +``` + +前提是已经存在 `[providers.my-api]`,且它的 `protocols` 包含这些协议。完整规则见[配置说明](docs/configuration.md)。 + +本地转发保留原生协议,不会自动把 Chat 转换为 Responses 或 Messages。 +只有 Chat 的服务不能直接供 Claude Code 或 Codex 使用;需要转换时,参阅[可选 Magpie 高级入口](docs/advanced.md)。 +配置支持 Gemini 基地址,但当前六个简化版客户端卡片使用的是 Chat、Responses 或 Messages;Gemini 专用接入见[覆盖范围](docs/coverage.md)。 + +## 连接不同的客户端 + +以下是简化工作台的直接配置方式。无需额外向客户端填写供应商 key;客户端使用本地网关令牌,由 Agent Connect 转发请求。 + +| 客户端 | 所需原生协议 | 默认修改的用户配置 | +| --- | --- | --- | +| Claude Code | Anthropic Messages | `~/.claude/settings.json` | +| Codex CLI | OpenAI Responses | `~/.codex/config.toml` | +| WorkBuddy | OpenAI Chat Completions | `~/.workbuddy/models.json` | +| WorkBuddy AI | OpenAI Chat Completions | `~/.workbuddy-ai/models.json` | +| OpenClaw | OpenAI Chat Completions | `~/.openclaw/openclaw.json` | +| Hermes | OpenAI Chat Completions | `~/.hermes/config.yaml` | + +`~` 表示当前用户主目录,Windows 通常为 `C:\Users\你的用户名`。设置了客户端配置目录环境变量时,实际位置会随之变化,见[文件位置](#文件位置与启动选项)。 + +### Claude Code + +选择 **Claude Code** 并连接,然后退出旧进程,在新终端启动新的 `claude` 会话。 +适配器配置 Messages 地址、模型和本地鉴权,并保留不相关设置。项目配置、环境变量或企业策略仍可能覆盖用户配置。 +确认接入可先使用工作台的 **客户端实测**,或在新会话发送下方的固定测试消息。 + +### Codex + +选择 **Codex** 并连接,再重新启动 `codex`。适配器配置名为 `iteraconnect` 的 Responses 提供方及所选模型。 +如果用户文件中已经有来源不明的同名提供方,程序会报错并保留原文件;请改名后重试,或使用 **导出配置** 手动合并。 +这里只验证了 Codex CLI;不把 CLI 测试结果当作其他桌面、IDE 或云端运行方式的验收结果。 + +### WorkBuddy / WorkBuddy AI + +选择与安装版本对应的卡片,连接并重启应用,然后新建任务。 +在任务模型菜单选择 `custom-local:iteracompute/模型ID`;自定义服务商时将 `iteracompute` 替换为你的 API 标识。 +模型显示名称包含 `Agent Connect · 模型ID`。现有模型会保留,新增配置的 `vendor` 为 `iteraconnect`。 + +工作台会提示在原应用手动验证,因为当前没有自动执行桌面应用推理的测试。仅配置写入成功不算真实接入通过。 + +### OpenClaw + +选择 **OpenClaw** 并连接,再按原来的运行方式重启相关进程、开始新会话。 +适配器更新提供方和默认模型,并将接入模型加入已有的模型允许列表;不会替你开启消息渠道投递。 +工作台实测会使用独立临时配置运行本地单轮测试,不复用日常会话。 + +### Hermes + +选择 **Hermes** 并连接,再重新启动 Hermes、新建会话。 +适配器使用 `custom:iteraconnect` 提供方和明确的 Chat transport,保留其他无关设置。 +自动 **客户端实测** 基于 Hermes 0.23.1 的 JSONL 输出;旧版本可以在原客户端手动测试。 +复杂 YAML 会明确报错,原文件不会被重写;此时使用导出片段或高级适配器。 + +## 确认接入是否成功 + +连接不是测试的前置强制步骤;可以先测试 API,再连接客户端。**测试不会自动在启动时运行。** + +| 操作 | 验证内容 | 用量与边界 | +| --- | --- | --- | +| **获取模型** | 供应商模型目录 | 一次目录请求,不进行生成,不保存草稿 | +| **测试 API** | 所选客户端协议的文本、完整 SSE、工具调用与结果回传 | 最多 4 次生成请求,每次输出预算 256 token | +| **客户端实测** | 启动已安装的 Claude Code / Codex / OpenClaw / Hermes,检查实际回复 | 会产生 API 用量;临时配置、独立目录,不复制日常登录和聊天 | +| WorkBuddy / WorkBuddy AI | 原应用内发送消息与工具任务 | 需手动验收,工作台会明确提示 | + +推荐顺序: + +1. 选定 API、模型、客户端,点击 **测试 API**,检查三张结果卡是否全部通过。 +2. 对支持自动测试的已安装客户端,点击 **客户端实测**。 +3. 点击连接,重启原客户端,在新会话发送: + + ```text + Reply with exactly ITERACONNECT_OK. + ``` + +4. 在可丢弃的测试目录里,再让客户端创建并读取一个小文件,检查其真实工具工作流。 + +API 工具测试只回传固定字符串,不执行模型生成的命令。客户端单轮回复通过,不代表它的完整工具循环、长会话、图像、权限或异常恢复均已验收。 + +![文本、流式与工具调用的独立结果卡](docs/images/test-passed.jpg) + +此结果卡截图使用**本地模拟后端**展示界面。真实 IteraCompute 验收发生于 2026-11-16: +`openai/gpt-6-luna` 的三个原生协议及四个真实 CLI 通过了记录中的检查;WorkBuddy 桌面推理仍待手动验收。 +`Auto` 曾返回 400/429,另一次 Haiku 工具测试曾返回 502,这些失败均保留在[验收记录](docs/acceptance.md),不会被模拟测试结果覆盖。 + +[GitHub CI](https://github.com/IteraCompute/agent-connect/actions/runs/44015209371) 已通过 Ubuntu、macOS、Windows × Python 3.11 / 3.14 的单元与模拟后端测试,以及构建、Magpie 与必需检查。跨平台 CI 不替代真实客户端的各平台验收。 + +### 读懂界面状态 + +| 状态 | 含义 | +| --- | --- | +| 有未保存更改 | 修改了 API、模型、协议或客户端;连接、导出和测试会自动保存 | +| 协议匹配 / 需要配置 | 只检查声明的协议;缺少协议时连接与测试不可用,可点“检查协议”定位 | +| 已检测到安装 | 发现命令或配置目录,仍需实测确认能否执行 | +| 已配置 · 可恢复 | 存在原配置备份,不等于当前模型已通过推理测试 | +| API 测试通过 | 三项协议检查通过;报告默认收起,可展开查看脱敏详情 | +| 客户端实测通过 | 从真实客户端输出中确认了预期回复 | + +修改 API、模型或客户端后,旧测试结果会清除。客户端卡片支持 Tab、方向键、Home / End;窄屏会自动堆叠显示。 + +## 切换与恢复配置 + +**换模型或服务商:** 选择另一个 API / 模型,保持目标客户端卡片选中,再点击连接,随后重启客户端。 +只保存 API 设置不会改写客户端文件。切换一个客户端不会自动配置其他客户端;请逐个连接。 + +已连接的客户端仍使用它最近一次连接时写入的服务商和模型;修改同一服务商的 key / 地址会影响本地转发。 +不要删除仍被客户端使用的服务商配置。使用多个配置管理器前,先恢复原配置,避免相互覆盖。 + +**恢复:** 选中目标客户端,点击 **恢复原配置**,再重启客户端。 +第一次连接前会保存原始内容;重复连接仍保留这份原始备份。原文件原本不存在时,恢复会移除由本工具创建的文件。 + +如果客户端或其他工具在连接后改写了该文件,自动恢复会停止,避免覆盖后续修改。请对照 `native-backups` 中的备份手动合并;不要为了恢复而直接删除整个客户端配置目录。 +支持标准 JSON、Codex TOML 和 Hermes 常见缩进 YAML / JSON。JSON5 或复杂结构会报错并保留原文件。 + +**手动导出:** 点击 **导出配置**,展开片段并点击 **复制配置**,手动合并到对应文件。 +导出不会写入目标客户端,也不算“已连接”。片段含本地网关令牌,请仅在本机使用。 + +## 文件位置与启动选项 + +| 文件 / 端口 | 默认值 | 作用 | +| --- | --- | --- | +| 私密 API 设置 | 项目内 `agent-connect.local.toml` | 保存 API key、服务商、模型与上次选择 | +| 状态目录 | `~/.config/iteraconnect` | 本地网关 key、备份等 | +| 原配置备份 | 状态目录内 `native-backups` | 每个客户端的原始内容与冲突检测信息 | +| 本地工作台 | `127.0.0.1:18424` | 需本次启动管理令牌,检查 Host / Origin | +| 推理转发 | `127.0.0.1:18423` | 客户端连接的本地 API | + +`ITERACONNECT_HOME` 覆盖状态目录;否则状态目录遵循 `XDG_CONFIG_HOME`。 +客户端适配器遵循 `CLAUDE_CONFIG_DIR`、`CODEX_HOME`、`WORKBUDDY_CONFIG_DIR`、`WORKBUDDY_AI_CONFIG_DIR`、`OPENCLAW_STATE_DIR` / `OPENCLAW_CONFIG_PATH` 和 `HERMES_HOME`。 + +```bash +# 修改端口;Windows 将 python3 换成 py -3 +python3 start.py --port 18434 --relay-port 18433 + +# 不自动打开浏览器,使用终端显示的完整地址 +python3 start.py --no-browser + +# 查看可用启动选项 +python3 start.py --help +``` + +更换转发端口后,必须重新连接对应客户端。使用同一组端口时只启动一个实例。 +需要把私密配置保存在其他目录时,在源码目录执行: + +```bash +python3 -m pip install . +itera-connect app --settings /absolute/path/to/private.toml +``` + +这里的 `pip install .` 是从当前源码安装,不代表已发布到 PyPI。简化客户端 TOML 与高级入口 JSON 配置相互独立。 +更新源码可在项目目录执行 `git pull --ff-only`,然后重启 Agent Connect;已填写的本地 TOML 被 Git 忽略,更新时请保留它。 + +## 常见问题 + +| 现象 | 检查与处理 | +| --- | --- | +| `python3` / `py` 不存在,或提示版本过低 | 安装 Python 3.11+,重新打开终端;Windows 可检查 `python --version` | +| 找不到 `start.py` | 确认解压/克隆的是完整功能分支,并进入文件所在目录;发布前 `main` 可能只有初始化文件 | +| 页面打不开、地址占用 | 停止旧实例,或使用上面的两个端口参数;浏览器未打开时复制终端完整地址 | +| 本地页面提示未授权 | 使用本次启动打印的完整地址;重启服务后管理令牌会变化 | +| API 返回 401 / 403 | 核对 key、账号和模型权限;修改文件后点“重新读取” | +| 429 / 502 / 超时 | 查看脱敏详情,稍后重试或选择其他已授权模型;具体模型通常比 `Auto` 更容易排查 | +| 获取模型失败 | 核对 API 基地址;供应商可能没有目录接口,可直接输入模型 ID | +| 连接或测试按钮不可用 | 检查所选客户端需要的协议;不要只为启用按钮而勾选服务并不支持的协议 | +| 配置成功但客户端仍用旧模型 | 完全退出旧进程并新建会话,检查项目配置、环境变量、企业策略以及 WorkBuddy 的任务模型选择 | +| 提示未安装,但实际已安装 | 检查启动 Agent Connect 的终端能否找到客户端命令,以及实际配置目录;也可先连接后在原应用手测 | +| 修改文件后无法保存 | 先点“重新读取”,再操作,避免覆盖外部修改 | +| 恢复被拒绝 / JSON5 或 YAML 报错 | 原文件保留;对照备份手动合并,或使用高级适配器 | +| 关闭工作台后客户端报连接失败 | 保持启动终端运行;如果已停止,重新启动 Agent Connect | + +供应商原始错误正文和任意客户端日志不会直接返回,避免泄露凭据或私密上下文。 +当前工作台只服务本机;远程共享、协议转换和其他上游选项见[高级指南](docs/advanced.md)。 + +## 开发与开源治理 + +```bash +python3 -m venv .venv +source .venv/bin/activate +# Windows PowerShell:.venv\Scripts\Activate.ps1 +python -m pip install -e . -r requirements-dev.txt +python -m unittest discover -v +ruff check . +ruff format --check . +python -m build +``` + +运行时只有 Python 标准库;上面的 Ruff / build 是开发依赖。网页源码位于 `src/iteraconnect/web`,原生适配器位于 `native.py`,转发位于 `gateway.py`。 +[测试指南](docs/testing.md)说明模拟后端、真实 CLI、真实 API 验收的区别及可选命令。 + +MIT 开源,欢迎 [Issues](https://github.com/IteraCompute/agent-connect/issues)、[Discussions](https://github.com/IteraCompute/agent-connect/discussions) 和 PR。 +公开讨论请提供版本、协议、模型 ID 与脱敏复现步骤。社区可以提交建议与代码,合并由管理员审核。 +`main` 的审核、CI、首次 CODEOWNERS 设置与当前修复进度见[治理记录](docs/governance.md)。 + +需要 Magpie 协议转换、更多客户端、订阅登录、MCP、skills 或 CC Switch 导入时,使用[高级入口](docs/advanced.md)与[覆盖矩阵](docs/coverage.md)。 +可选上游组件的版本、来源和许可证见 [THIRD_PARTY_NOTICES](THIRD_PARTY_NOTICES) 与锁文件;它们遵循各自的存储和授权方式。 diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..d020592 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,25 @@ +# Security policy + +Report vulnerabilities privately using GitHub's **Report a vulnerability** feature on this +repository's Security page. Do not publish API keys or exploit details in public issues. + +Agent Connect is an authenticated, loopback-only desktop relay. Provider keys are environment +references in advanced mode, or an ignored owner-only local TOML file in the simple app. Runtime +profiles use environment references in both modes. Vendor keys are never placed in generated +agent configs, Magpie entries or command-line arguments. The UI never returns stored vendor keys. +Its per-launch control token is carried in the launch URL fragment, then session storage; API +operations require it plus matching Host/Origin. It serves only local packaged assets with a +restrictive CSP. Do not share the launch URL. Native configuration backups may contain your +previous client credentials; backups are private and must not be uploaded either. +Generated import links and native fragments may contain a local relay key: protect them as credentials. +The local key can make requests with the providers available to the relay; rotate it and resync +Magpie/reimport client configs if it is disclosed. Magpie's loopback gateway uses its own documented +local trust model, which should be considered on shared multi-user machines. + +Use Magpie's native authenticated/TLS sharing feature for remote clients. Do not expose the relay +port using a public bind or tunnel. A successful protocol conversion does not imply identical +behavior for provider beta features, cache semantics, reasoning or signatures. + +The pinned installer verifies published asset sizes and SHA-256 digests before executing anything. +It does not execute remote installer scripts. Keep upstream notices when redistributing binaries. +Supported release line: `0.1.x`. diff --git a/Start.bat b/Start.bat new file mode 100644 index 0000000..32cf8cd --- /dev/null +++ b/Start.bat @@ -0,0 +1,5 @@ +@echo off +cd /d "%~dp0" +where py >nul 2>nul +if errorlevel 1 (python start.py %*) else (py -3 start.py %*) +if errorlevel 1 pause diff --git a/Start.command b/Start.command new file mode 100755 index 0000000..01364d1 --- /dev/null +++ b/Start.command @@ -0,0 +1,3 @@ +#!/bin/sh +cd "$(dirname "$0")" || exit 1 +exec python3 start.py "$@" diff --git a/THIRD_PARTY_NOTICES b/THIRD_PARTY_NOTICES new file mode 100644 index 0000000..6824f66 --- /dev/null +++ b/THIRD_PARTY_NOTICES @@ -0,0 +1,51 @@ +Upstream software notices + +Agent Connect composes these independently maintained MIT projects. + + +cc-switch +MIT License + +Copyright (c) 2025 Jason Young + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +magpie +MIT License + +Copyright (c) 2026 yetone + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/config.example.toml b/config.example.toml new file mode 100644 index 0000000..c256650 --- /dev/null +++ b/config.example.toml @@ -0,0 +1,11 @@ +# 复制为 agent-connect.local.toml,或直接打开客户端填写。 +# 只需要把下面 api_key 的空引号填好;这个本地文件不会提交到 GitHub。 +selected_provider = "iteracompute" +client = "claude" + +[providers.iteracompute] +name = "IteraCompute" +api_key = "" +base_url = "https://api.iteracompute.com" +model = "openai/gpt-6-luna" +protocols = ["chat", "responses", "anthropic"] diff --git a/docs/acceptance.md b/docs/acceptance.md new file mode 100644 index 0000000..79271a6 --- /dev/null +++ b/docs/acceptance.md @@ -0,0 +1,101 @@ +# Acceptance record + +Date: **2026-11-16 (Asia/Shanghai)**. Candidate: **0.1.0**, independent simple local client. + +A dedicated key was supplied through ignored `agent-connect.local.toml`. Real requests went to +`https://api.iteracompute.com` through the local relay. No vendor key, prompts, raw responses, +account balance or arbitrary client logs are included here. Native runs used isolated temporary +homes, configurations generated by our independent adapters, and no existing user logins. +Daily client configuration was not changed by these acceptance runs. + +## Real IteraCompute API and clients + +| Check | Model | Result | Scope | +| --- | --- | --- | --- | +| Authenticated model catalog | — | Passed | 32 model IDs returned through the new UI | +| Chat Completions | `openai/gpt-6-luna` | Passed | Text, complete SSE, tool call + result round trip | +| Responses | `openai/gpt-6-luna` | Passed | Text, complete SSE, tool call + result round trip | +| Anthropic Messages | `openai/gpt-6-luna` | Passed | Text, complete SSE, tool call + result round trip | +| Claude Code 2.1.312 | `openai/gpt-6-luna` | Passed, 13.734 s | Actual CLI read generated user settings and returned exactly `ITERACONNECT_OK` | +| Codex CLI 0.156.1 | `openai/gpt-6-luna` | Passed, 10.847 s | Actual CLI read generated TOML and completed a turn with the expected assistant reply | +| OpenClaw 2026.10.2 | `openai/gpt-6-luna` | Passed, 18.916 s | Actual local agent read generated JSON; expected reply payload; channels disabled | +| Hermes 0.23.1 | `openai/gpt-6-luna` | Passed, 13.721 s | Official stable source in a separate test environment; generated provider config; successful terminal JSONL result | +| WorkBuddy / WorkBuddy AI | — | Application acceptance pending | Independent list/object JSON adapters, preservation and restoration verified; desktop apps are not installed in this Linux test environment | + +The simple app now selects the verified `openai/gpt-6-luna` model by default; users can select +another catalog model, including `Auto`. This is evidence for the listed model/key/date, not +a guarantee of every model's permissions, availability or feature semantics. + +Earlier attempts are retained as useful limitations: + +- `Auto` over Messages returned HTTP 400 for text and 429 for stream/tools; this did not pass. +- `anthropic/claude-haiku-5-5` passed text, streaming and actual Claude Code single-turn use + (9.128 s), but its tool-roundtrip attempt returned HTTP 502 after approximately 60 seconds. +- Switching to the explicit verified model passed all three native protocols and tool cases. + The project did not change IteraCompute's production routing or suppress these failures. + +Native one-turn success proves routing and an actual reply. It does **not** establish every +client's autonomous tool loop, long session, compaction, vision, sandbox behavior or error recovery. +The API tool round trip does not substitute for each native client's real filesystem tool loop. +WorkBuddy still needs an installed desktop app, restart, task-picker selection and disposable +workspace acceptance. CC Switch desktop import click-through remains a separate optional test. + +## Local automated evidence + +Rechecked on **2026-11-17**: the local suite passes **52 tests** with pinned Magpie and installed native CLI opt-ins enabled. +It covers the independent UI management API, private settings, no inherited-key fallback, +Host/Origin/control-token checks, fixture requests, exact native restoration, later-edit +conflicts, symlink preservation, WorkBuddy list/object formats, and stale Hermes route/key fields. +Draft model discovery additionally verifies that both success and failure preserve the private file, +active provider and live key, with temporary credentials removed afterward. + +The native-settings suite exercises actual installed Claude Code, Codex, OpenClaw and Hermes against +a local fixture backend. Hermes 0.23.1 was separately installed and passed the same independent +configuration/fixture path (7.631 s) before the real-provider run. Optional Magpie tests verify +its pinned engine translating a Chat-only source across all three protocols, sync idempotence +and its own five native adapter restore paths. No model key is required for fixture tests. + +Ruff check/format, JavaScript syntax and frontend formatting checks pass. The sdist/wheel build +includes the packaged HTML/CSS/JS assets, launchers and blank template; private key files are excluded. +Manual real-provider and installed-client acceptance was performed on Linux. Separately, the +[first enabled GitHub CI run](https://github.com/IteraCompute/agent-connect/actions/runs/44015209371) +passed on 2026-11-17: Ubuntu, macOS and Windows with Python 3.11/3.14, quality/build, pinned Magpie +fixture tests and the required aggregate `checks` job. These OS unit/fixture runs do not establish +real-provider or installed desktop-client acceptance on macOS/Windows. + +Hermes stable source: **v0.23.1**, commit +`3b421578588243f920886e6fe79a6faa87ea026e`. Its official `uv.lock` and dependency overrides were +used in a separate test environment. It is not bundled into Agent Connect or required by its runtime. +Pinned optional Magpie: **v0.1.4314**, Linux x64 SHA-256 +`b1d88d7afd5e211d8992273e906455c11ea84cac31e764d47af20ac4d0a25339`. + +```bash +ITERACONNECT_TEST_MAGPIE_BIN=/absolute/path/to/verified/magpie \ +ITERACONNECT_TEST_NATIVE=1 python -m unittest discover -v +``` + +Add the Hermes executable's directory to PATH to include it in the independent native-settings +suite. Plain test runs skip installed-program opt-ins. Reports under `reports/` remain private +and ignored by Git; the public record contains only safe result summaries. + +## UI regression (2026-11-17) + +The redesigned local workspace was exercised in the browser against a simulated vendor with +an isolated HOME and client directories. Desktop and 390 px layouts, keyboard client selection, +protocol mismatch, duplicate-provider validation, model discovery before saving a model, automatic +save/connect, result cards, native configuration restore, copyable export and stale-result clearing +passed. No daily client settings were changed. README screenshots of result cards are UI examples +from this simulated backend; the real-provider evidence above remains dated 2026-11-16. + +## Repository governance + +Public repository, Issues and Discussions enabled. Protected `main` requires administrator +CODEOWNER review, passing checks, stale-approval dismissal, latest-push approval and resolved +conversations; administrators are subject to the rules. The implementation PR is ready for independent review. + +On 2026-11-17, the organization Owner enabled Actions for this repository only; default workflow +permissions remain read-only and workflow PR approval is disabled. GitHub CI results are recorded +on the PR separately from the local evidence above. Initial base CODEOWNERS names only the PR +author, so its first-merge bootstrap needs an independently eligible reviewer or an explicitly +authorized one-time Owner exception. The proposed CODEOWNERS lists both existing administrators. +See [governance.md](governance.md) and the PR for the current state. diff --git a/docs/advanced.md b/docs/advanced.md new file mode 100644 index 0000000..d9e923f --- /dev/null +++ b/docs/advanced.md @@ -0,0 +1,95 @@ +# Advanced CLI, Magpie and CC Switch + +The default client is `python3 start.py`. It owns an original local UI, private TOML settings, +native configuration editors and loopback relay. None of those require upstream software. + +The advanced CLI keeps the composition interfaces for protocol conversion, subscription +providers, additional harnesses and upstream features. It uses a **separate configuration** from +the simple app: JSON provider profiles with environment key references. Switching an agent with +both managers simultaneously is unsupported. Stop one manager and restore its configuration first. + +## Optional Magpie bridge + +```bash +python -m pip install . +itera-connect init +itera-connect install-magpie +# Set ITERACOMPUTE_API_KEY securely in this terminal, then: +itera-connect up --web +``` + +This starts Magpie's own UI and the relay. It does not read `agent-connect.local.toml`. +Magpie is downloaded from its official release at a pinned version and verified by SHA-256. +Its independent process supplies cross-protocol conversion; its source is not copied into this package. + +In another terminal: + +```bash +itera-connect connect claude +itera-connect connect codex +itera-connect connect workbuddy +itera-connect connect openclaw +itera-connect connect hermes +itera-connect disconnect claude +itera-connect run codex --via magpie -- exec --skip-git-repo-check 'Reply only OK' +``` + +`connect`/`disconnect` in this advanced CLI intentionally use Magpie's native adapters. The simple +UI uses Agent Connect's independent editors. Magpie-backed WorkBuddy model IDs start with +`iteraconnect-iteracompute/`; simple-UI WorkBuddy model IDs start with `iteracompute/`. + +Add another API with protocol-specific bases: + +```bash +itera-connect provider add my-api --name 'My API' --key-env MY_API_KEY \ + --model my-model --chat https://example.com/v1 +itera-connect provider use my-api +# Set MY_API_KEY, restart up, then connect the chosen client. +``` + +Only declare protocols the API supports. When it only serves Chat, Magpie can translate for +Codex or Claude Code. `run --via gateway` uses native protocols; `--via direct` accesses the +provider without the local relay. Vendor keys stay in process environments and are not put in argv. + +All Magpie native options remain available through pass-through: + +```bash +itera-connect magpie -- presets +itera-connect magpie -- ls +itera-connect magpie -- tui +``` + +Suppliers added inside Magpie follow its own credential/storage rules and access their APIs +directly. Subscription sign-ins, plugins, routing, fallback, MCP and skills are upstream features; +availability is not a claim that every combination has been acceptance tested here. + +## Optional CC Switch import + +Install CC Switch from its [official release](https://github.com/farion1231/cc-switch/releases). +Generate a native import link and open it in the installed application: + +```bash +itera-connect cc-link claude +itera-connect cc-link codex --via magpie +itera-connect cc-link openclaw +itera-connect cc-link hermes +itera-connect cc-switch +``` + +Links contain a local gateway credential, not the vendor key. Imports are not switched on +automatically. Per-app protocol restrictions and the full capability matrix are documented in +[coverage.md](coverage.md). WorkBuddy provider deep links are not supported by this upstream +contract; use the independent simple-UI adapter or Magpie's adapter. + +## Advanced acceptance commands + +These commands use the advanced JSON/environment configuration and a running relay/bridge: + +```bash +itera-connect doctor +itera-connect probe --via gateway --out reports/gateway.json +itera-connect probe --via magpie --protocol chat --protocol responses --protocol anthropic +itera-connect smoke claude codex openclaw --via magpie --out reports/clients.json +``` + +See [testing.md](testing.md) for exact test scope and [configuration.md](configuration.md) for paths. diff --git a/docs/configuration.md b/docs/configuration.md new file mode 100644 index 0000000..0c240ed --- /dev/null +++ b/docs/configuration.md @@ -0,0 +1,147 @@ +# Configuration + +## Simple local app + +`python3 start.py` reads `agent-connect.local.toml` beside the launcher and creates it if absent. +Only `api_key` needs to be filled. The file is ignored by Git, atomically saved with mode 0600 +on POSIX, and never returned by the management API. On Windows use a private user directory/ACL. +An empty key input preserves an existing key; edit the file to clear it. Click Reload after file edits. +The app does not fall back to inherited vendor credentials. No inference runs automatically. + +```toml +selected_provider = "iteracompute" +client = "claude" + +[providers.iteracompute] +name = "IteraCompute" +api_key = "" +base_url = "https://api.iteracompute.com" +model = "openai/gpt-6-luna" +protocols = ["chat", "responses", "anthropic"] +``` + +Add providers in the UI or as more `[providers.]` tables. The simple app requires a nonempty +key before connection/testing; use a harmless placeholder such as `local` for keyless loopback +servers. Root bases derive `/v1` for Chat/Responses and `/v1beta` for Gemini; an existing `/v1` +suffix is preserved for OpenAI protocols and stripped for Messages. For nonstandard paths, +override any supported protocol explicitly: + +```toml +[providers.iteracompute.endpoints] +chat = "https://api.iteracompute.com/v1" +responses = "https://api.iteracompute.com/v1" +anthropic = "https://api.iteracompute.com" +``` + +The app runs its relay on 18423 and management panel on 18424, loopback only. Use +`python3 start.py --port 18434 --relay-port 18433` to change them. Reconnect native clients after +changing the relay port. Installed packages can use `itera-connect app --settings /path/private.toml`. +Private runtime provider keys use generated environment names; they are not persisted in config.json. + +The independent native adapters honor `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `WORKBUDDY_CONFIG_DIR`, +`WORKBUDDY_AI_CONFIG_DIR`, `OPENCLAW_STATE_DIR` / `OPENCLAW_CONFIG_PATH`, and `HERMES_HOME`. +Defaults are `~/.claude/settings.json`, `~/.codex/config.toml`, `~/.workbuddy/models.json`, +`~/.workbuddy-ai/models.json`, `~/.openclaw/openclaw.json` and `~/.hermes/config.yaml`. +Original contents and the installed content hash are journaled under `native-backups` in the +Agent Connect state directory. Restore only proceeds if the file still matches the known +applied/transaction state. Existing unrelated JSON fields and TOML/YAML settings are preserved. +Unsupported complex formats fail without rewriting the client file. Project settings and +process environment may override user settings; restart and test a fresh session. + +Codex's persistent adapter uses `experimental_bearer_token` for the **local relay token only**, +so terminals do not need a manual key export. Real provider keys remain exclusively in the relay. +Hermes uses a named custom provider and explicit Chat transport. OpenClaw's existing model +allowlist is extended to include the connected model. WorkBuddy keeps existing models and adds +the provider-prefixed model, then requires a task-picker selection after restart. + +## Advanced JSON/environment configuration + +`itera-connect init` creates `$ITERACONNECT_HOME/config.json`, or +`${XDG_CONFIG_HOME:-~/.config}/iteraconnect/config.json` by default. Files are replaced +atomically with owner-only permissions on POSIX. Windows users should restrict the containing +folder's ACL to their account. In this advanced mode, native app backups remain managed by +Magpie/CC Switch. This configuration is independent of the simple app's private TOML. + +```json +{ + "schema_version": 1, + "active_provider": "iteracompute", + "gateway": {"host": "127.0.0.1", "port": 18423, "timeout": 180}, + "providers": { + "iteracompute": { + "name": "IteraCompute", + "key_env": "ITERACOMPUTE_API_KEY", + "default_model": "Auto", + "endpoints": { + "chat": "https://api.iteracompute.com/v1", + "responses": "https://api.iteracompute.com/v1", + "anthropic": "https://api.iteracompute.com" + } + } + } +} +``` + +An absent file uses these defaults in memory. An invalid existing file fails closed. +Inline provider secrets are rejected. `--config /path/config.json` selects a different file; +`ITERACONNECT_HOME` still selects its local key and installed binary directory. +The gateway reads config and environment at startup: restart it after changes. + +| Endpoint key | Base convention | Native inference route | +| --- | --- | --- | +| `chat` | e.g. `https://relay.example/v1` | `/chat/completions` | +| `responses` | e.g. `https://relay.example/v1` | `/responses` | +| `anthropic` | e.g. `https://relay.example` | `/v1/messages`, `/v1/messages/count_tokens` | +| `gemini` | e.g. `https://relay.example/v1beta` | `/models/{model}:generateContent`, `:streamGenerateContent` | + +Keep custom path prefixes in the base. Credentials, query strings and fragments are refused +in configured base URLs. HTTPS is required except on loopback; `provider add --allow-http` +explicitly allows a trusted LAN server. Declare only protocols the provider serves natively. +Magpie performs translation when the native client speaks a different protocol. + +Provider IDs use lower-case letters, digits and hyphens. Model IDs can contain `/` and are +preserved. Root gateway requests may select `provider-id/model-id`. Explicit +`/p/provider-id/v1/...` routes accept the provider's exact model ID, avoiding namespace ambiguity. +`GET /v1/models` returns provider-prefixed IDs; per-provider catalogs preserve the original IDs. +Catalog failures are reported explicitly, without inventing a replacement catalog. + +All inference and catalog routes require the local `gateway.key`, or an explicit +`ITERACONNECT_GATEWAY_KEY` (24+ printable characters). `/health` returns only name/version. +Never share the local key or generated CC Switch links. The relay replaces client credentials +with the selected provider's environment key and does not forward cookies or arbitrary headers. +It never retries a POST, follows an upstream redirect, or writes request/response content to logs. +HTTP upstream error bodies are replaced by generic status messages. Successful SSE content is +relayed as received, including in-stream provider error events; probe reports do not record it. + +Requests are limited to 16 MiB JSON and 64 concurrent inference calls. The relay supports the +three agent protocols, Gemini content endpoints, Chat-style embeddings/rerank/image generation. +It does not implement arbitrary vendor administration APIs, WebSocket Responses, multipart +uploads or persisted Response retrieval. Magpie's own native-provider/plugin interfaces remain +available for APIs outside this relay's scope. HTTP proxy environment variables are not used +by the relay transport; configure a reachable provider endpoint or use Magpie's native proxy settings. + +## Magpie and CC Switch + +`sync` creates `iteraconnect-` entries in Magpie. These entries point to per-provider +relay URLs and hold only its local key. They expose exactly the provider's advertised native +protocols, letting Magpie translate correctly. Models are discovered on sync; run sync again +when the provider catalog changes. Existing unrelated Magpie providers are preserved. Changing +the relay port requires removing the old Agent Connect provider from Magpie before syncing, +so the collision guard cannot silently take over an existing endpoint. + +`ITERACONNECT_MAGPIE_BIN` selects an existing binary, otherwise the checksum-verified local +installation is preferred, followed by `PATH`. `ITERACONNECT_MAGPIE_URL` overrides the default +client gateway `http://127.0.0.1:3425`; when changing Magpie's port, use the corresponding +`MAGPIE_ADDR` too. Agent Connect's generated Magpie client keys assume a loopback gateway; +remote Magpie deployments need their native gateway-key configuration instead. + +The pinned installer writes only to the Agent Connect bin folder. It does not install a service +or replace a system Magpie. Pass-through commands disable Magpie usage telemetry with its +documented opt-out environment variables. Other upstream network behavior follows Magpie's settings. + +`export --out ` writes a private standalone fragment for manual merging. +It refuses to overwrite files. Claude and WorkBuddy fragments hold only the local relay key. +Codex/OpenClaw fragments reference `ITERACONNECT_GATEWAY_KEY`: export the contents of the local +`gateway.key` in the client process first, or use `run`/`connect` to supply it automatically. +Exports are optional; in advanced mode use Magpie's native adapter, which preserves comments, +unrelated settings, profile behavior, model metadata and restoration state. diff --git a/docs/coverage.md b/docs/coverage.md new file mode 100644 index 0000000..477bc1c --- /dev/null +++ b/docs/coverage.md @@ -0,0 +1,54 @@ +# Upstream and downstream coverage + +## Independent simple client + +`python3 start.py` uses original UI, settings, native adapters and the relay. It needs no upstream +binary. API switching, custom native endpoints, model discovery, connect/restore and API/client +tests are available in one local interface. Six client entries cover Claude Code, Codex, +WorkBuddy, WorkBuddy AI, OpenClaw and Hermes. Config adaptation is separate from actual app +inference verification; see acceptance.md. Protocol conversion, subscription login, upstream +plugins and additional clients remain in the optional advanced interfaces below. + +## Optional upstream composition + +Composition keeps upstream capabilities available through their own supported interfaces. +It does not claim every upstream feature has been retested against every IteraCompute model. +Source revisions and the Magpie release artifacts are pinned in +[`upstreams.lock.json`](../src/iteraconnect/upstreams.lock.json). + +| Layer | Available interface | Scope | +| --- | --- | --- | +| IteraCompute and custom APIs | `provider`, `models`, `serve`, `probe` | Selectable Chat, Responses, Messages and Gemini native bases; environment-only vendor keys | +| Magpie upstreams | `itera-connect magpie -- presets`, Magpie web/TUI | All presets, custom endpoints, local models, remote Magpie, supported sign-ins, subscription providers and community plugins | +| Magpie routing | Magpie web/TUI or CLI pass-through | Groups, fallback, account selection, quota/usage, native plugins, MCP, skills and supported agent settings | +| Magpie downstreams | `connect ` or full upstream CLI | Native adapters, including Claude Code, Codex, WorkBuddy/WorkBuddy AI, OpenClaw, Hermes, Gemini CLI, OpenCode, Pi, Goose, Copilot, Qwen, Kimi, dsh and the other registered agents | +| CC Switch upstreams | `cc-link`, CC Switch desktop | Import Agent Connect as a provider beside every upstream preset/custom provider and official account option | +| CC Switch downstreams | CC Switch desktop, native app settings | Claude Code/Desktop, Codex, Gemini, Grok Build, OpenCode, OpenClaw, Hermes, Pi, MiniMax Code, Kimi, dsh, Antigravity, Oh My Pi, Copilot, WorkBuddy | +| CC Switch extra features | CC Switch desktop | Its native MCP, prompt, skills, workspace, account and local routing features remain available | +| Additional API-compatible clients | local gateway URL/key or Magpie | Use a supported native protocol; no fixed list of clients in the relay | + +`connect` accepts arbitrary Magpie agent IDs rather than imposing a smaller allowlist. +Most model-selecting adapters accept the standard model command. Provider-only or other +special adapters should use the full native CLI (`magpie -- `). +WorkBuddy and WorkBuddy AI are handled explicitly as provider/picker adapters. + +CC Switch currently accepts provider deep links for `claude`, `codex`, `gemini`, `agy`, +`grokbuild`, `opencode`, `openclaw`, `hermes` and `pi`. Other desktop entries remain available +through the upstream UI; a missing deep-link adapter is reported explicitly. Unsupported +protocol/client combinations must be routed through Magpie or CC Switch's native routing. + +The default IteraCompute profile advertises Chat, Responses and Messages. It does not assume +that IteraCompute serves the native Gemini API. Gemini CLI can use IteraCompute through +Magpie's protocol conversion. Provider-specific beta features, signatures, reasoning budgets, +context limits and tool support still depend on the selected model/API. + +Verified source references: + +- [Magpie reference](https://github.com/yetone/magpie/blob/187d067241d891b0603358537f7ef8909a7599a7/docs/reference.md) +- [Magpie agent registry](https://github.com/yetone/magpie/blob/187d067241d891b0603358537f7ef8909a7599a7/internal/agent/agents.go) +- [Magpie integration contract](https://usemagpie.ai/docs/integrate) +- [CC Switch app capabilities](https://github.com/farion1231/cc-switch/blob/09acca04941a359096bb16ea4fa4073c5e2c46e5/src/config/appSpecs.ts) +- [CC Switch deep-link contract](https://github.com/farion1231/cc-switch/blob/09acca04941a359096bb16ea4fa4073c5e2c46e5/docs/user-manual/en/5-faq/5.3-deeplink.md) +- [Codex provider configuration](https://developers.openai.com/codex/config-reference/) +- [OpenClaw custom providers](https://docs.openclaw.ai/gateway/config-tools/custom-providers) +- [Hermes custom providers](https://hermes-agent.nousresearch.com/docs/integrations/providers) diff --git a/docs/governance.md b/docs/governance.md new file mode 100644 index 0000000..3efbd76 --- /dev/null +++ b/docs/governance.md @@ -0,0 +1,95 @@ +# Repository governance and first-merge setup + +[中文说明](#中文说明) · [English](#english) + +## 中文说明 + +### 已确认的权限与 Actions 修复 + +2026-11-17 核查:`K-3-LT` 既是 `agent-connect` 的仓库管理员,也是 IteraCompute 的组织 Owner。 +组织角色与工具令牌的权限范围是两回事:当前 GitHub CLI 的令牌包含 `repo`、`workflow` 和 `read:org`,但没有组织 Actions 管理 API 所需的 `admin:org`。 +此前组织 API 返回 403,仓库启用 API 返回“组织禁用”的 409;这些结果不表示账号不是管理员。 + +组织 Owner 登录 GitHub 网页后,已完成以下修复: + +- 组织 Actions 从 Disabled 改为 **Selected repositories**,仅选择 `agent-connect`。 +- 仓库 API 已确认 `enabled=true`,其余仓库没有因此获得 Actions 执行权限。 +- 工作流默认权限仍为 **read**,不允许 Actions 创建或批准 PR;现有 CI 不使用供应商密钥。 +- 未扩大本机 CLI 令牌的组织权限范围。更改由已登录 Owner 的网页会话完成。 + +页面:[组织 Actions 设置](https://github.com/organizations/IteraCompute/settings/actions)。 +权限范围说明见 [GitHub Actions permissions API](https://docs.github.com/en/rest/actions/permissions#get-github-actions-permissions-for-an-organization)。 + +### 为什么管理员也会被阻止合并 + +`main` 的保护规则明确包含 `enforce_admins=true`,所以管理员也要满足: + +1. 至少一名审核者批准、CODEOWNER 批准。 +2. 新推送使旧批准失效;最近一次可审核推送需要其他人批准。 +3. 当前基线上的必需 `checks` 状态成功,所有审核讨论解决。 +4. 禁止 force push、删除主分支,自动合并关闭。 + +首次初始化的 `main` 仅将 `K-3-LT` 列为 CODEOWNER,而 PR #1 的作者和推送者也是该账号。 +GitHub 按 **base 分支**识别 CODEOWNERS,并禁止作者自审;PR 中增加 `aikevan` 在进入 `main` 前不会解除这个初始死锁。 +当前实现已将两名既有管理员 `K-3-LT`、`aikevan` 都列入 CODEOWNERS,以支持后续独立管理员审核;没有授予其他人管理员权限。 + +正常初始化方式是由另一管理员作为作者和最近推送者发起初始化 PR,经当前 CODEOWNER 独立审核,并通过 CI。 +如果 Owner 选择对当前 PR 做一次初始化例外,必须先明确批准该例外;它应只针对命名管理员和这一次合并,保留必需 CI,并在合并后立即恢复审核限制。 +这不是允许社区贡献绕过审核的长期策略。 + +### 审核与审计 + +仓库公开,允许 fork 和社区 PR,Issues、Discussions 与私密漏洞报告已启用。 +社区可以提出建议和代码;合并仍由管理员审核。CLI 的管理员身份不会被当作另一位审核者,也不会伪造 CI 或自审批准。 + +```bash +python scripts/check_governance.py +``` + +审计检查仓库公开性、管理员角色、主分支保护、base CODEOWNERS 与 Actions 状态。 +首次 CODEOWNERS 尚未进入 `main` 时,该项会报告未完成;这与组织 Actions 已修复是不同的状态。 +合并后的当前状态和实际检查结果以 [PR #1](https://github.com/IteraCompute/agent-connect/pull/1) 与 GitHub 设置为准。 + +## English + +### Administrator identity and Actions repair + +On 2026-11-17, the authenticated `K-3-LT` account was confirmed to be both repository administrator +and IteraCompute organization Owner. The CLI token's authorization is separate from that role: +it has `repo`, `workflow` and `read:org`, but lacks the `admin:org` scope required by the organization +Actions policy API. The earlier organization 403 and repository 409 did not mean the account lacked +an administrator role. + +After the Owner signed into GitHub in the browser, organization Actions was changed from Disabled +to **Selected repositories**, with **agent-connect only** selected. The repository API confirms +`enabled=true`. Default workflow permissions remain **read**, and workflow PR approval remains +disabled. Other repositories were not enabled. No broader CLI token scope was granted. + +### First CODEOWNER bootstrap + +Protected `main` enforces rules for administrators too: one approving review, CODEOWNER approval, +stale-review dismissal, approval of the latest reviewable push by someone else, a passing `checks` +status against the current base, and resolved conversations. Force pushes and main deletion are +disabled, and automatic merge is off. + +Initial base `main` names only `K-3-LT` as CODEOWNER; that account also authored and pushed PR #1. +GitHub uses the base branch's CODEOWNERS and does not permit author self-approval. Adding `aikevan` +inside the PR alone cannot resolve that bootstrap dependency. The proposed CODEOWNERS lists both +existing administrators so future changes have an independently eligible administrator. No new +administrator has been granted access. + +A normal bootstrap can be authored and last pushed by another administrator, then independently +reviewed by the existing CODEOWNER with CI passing. An Owner-authorized initial-merge exception, +if explicitly approved, must be limited to a named administrator and that one merge, retain the +required CI, and restore review restrictions immediately afterward. It is not a permanent bypass +for community contributions. + +Run `python scripts/check_governance.py` after setup. Before the initial ownership change reaches +main, its base-ownership audit remains pending even though Actions has been repaired. The current +PR and repository settings are the authoritative live state. + +References: + +- [Actions policy API and token scopes](https://docs.github.com/en/rest/actions/permissions#get-github-actions-permissions-for-an-organization) +- [Code owners and base branches](https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners) +- [Protected branches and administrator enforcement](https://docs.github.com/en/repositories/configuring-branches-and-merges-in-your-repository/managing-protected-branches/about-protected-branches) diff --git a/docs/images/client.jpg b/docs/images/client.jpg new file mode 100644 index 0000000..cc58e3a Binary files /dev/null and b/docs/images/client.jpg differ diff --git a/docs/images/test-passed.jpg b/docs/images/test-passed.jpg new file mode 100644 index 0000000..a755ec5 Binary files /dev/null and b/docs/images/test-passed.jpg differ diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..f192f24 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,126 @@ +# Testing and acceptance + +Tests deliberately distinguish three kinds of evidence: + +1. **Contract tests with a simulated vendor**: requests, auth substitution, provider selection, + text, SSE completion, tool results, failures, truncation, private exports and configuration preservation. +2. **Actual installed programs with a simulated vendor**: pinned Magpie translation and native + adapter restoration, plus Claude Code, Codex, OpenClaw and Hermes single-turn runs in temporary homes. +3. **Actual provider/model/client tests**: require an explicitly supplied test key. Fixture success + is not evidence that the remote API, model permissions, budget, tool semantics or every client works. + +## Repeatable local and CI tests + +```bash +python -m pip install -e . -r requirements-dev.txt +python -m unittest discover -v +ruff check . +ruff format --check . +python -m build +``` + +For the actual Magpie engine, install the pinned binary, then set +`ITERACONNECT_TEST_MAGPIE_BIN` to its absolute path: + +```bash +itera-connect install-magpie +ITERACONNECT_TEST_MAGPIE_BIN=/absolute/path/to/magpie python -m unittest tests.test_magpie.MagpieTests -v +ITERACONNECT_TEST_NATIVE=1 python -m unittest tests.test_magpie.NativeClientTests -v +``` + +No model key is needed for these tests. The opt-in native suite uses existing executables, +temporary HOME/XDG/config directories, a synthetic key and a local fixture vendor. No existing +user credentials or installed skills are copied. OpenClaw channel delivery is never enabled. +Only clients actually installed are executed. An unavailable program is reported as unavailable. +Magpie tests verify connection and restoration of Claude Code, Codex, WorkBuddy, OpenClaw and Hermes +configs; WorkBuddy application execution is separate evidence; the independent native-settings suite can also run installed Hermes. + +## Test-key acceptance + +### Simple local client + +Use a dedicated developer key. Fill `api_key` in ignored `agent-connect.local.toml`, run +`python3 start.py`, then click Reload if you edited the file after launch. Select the provider, +model and client, and click Test API. This tests that client's native protocol. Click Native +client test to exercise an installed Claude Code, Codex, OpenClaw or Hermes in an isolated temporary +home using configuration generated by the **new independent adapter**, without copying user +settings/logins. WorkBuddy explicitly requests manual acceptance in the original app. Hermes 0.23.1 supports automatic JSONL acceptance; the isolated profile gateway is stopped afterward. + +`tests.test_app` covers private settings, no inherited-key fallback, redacted management APIs, +Host/Origin/control-token enforcement, local-fixture probes, independent configuration +preservation, reconnect, exact restoration and protection against later edits. The opt-in +`NativeSettingsClientTests` reads these new native configs with the installed actual clients. + +### Browser UI regression + +Use a temporary HOME/config directory and a local fixture vendor; do not connect the UI test +instance to daily client settings. The 2026-11-17 UI regression covered: + +- Desktop at the normal browser viewport, and a 390 px narrow viewport without horizontal overflow. +- Radio selection using arrow keys, protocol mismatch disabling connection and tests, and its settings link. +- Duplicate provider validation, cancellation, and custom model discovery with no model or saved draft. +- Automatic save/connect for a custom provider, independent text/SSE/tool result cards, and exact restore. +- Clearing stale results when selections change, and copyable manual export with no vendor key. + +`tests.test_app` additionally verifies that successful and failed draft catalog requests preserve +the private file, selected provider and live credentials, and remove temporary credential references. +Screenshot result cards in the README use the simulated vendor; they are not new real-provider evidence. +Frontend development checks (Node is only needed for development): + +```bash +node --check src/iteraconnect/web/app.js +npx --yes prettier@3.6.2 --check src/iteraconnect/web/index.html src/iteraconnect/web/app.css src/iteraconnect/web/app.js +``` + +### Advanced CLI + +The advanced CLI uses separate JSON profiles and environment variables, as described in +[advanced.md](advanced.md). No keys belong in issues, PRs, screenshots or committed files. Runtime +reports under `reports/` and `.env` files are ignored. The relay's process must receive the key; +setting it only in a second terminal cannot update a running relay's environment. + +Start `itera-connect up --web`, then use the exact authorized model ID from `models`: + +```bash +itera-connect models +itera-connect probe --model Auto --via gateway --out reports/gateway.json +itera-connect probe --model Auto --via magpie --protocol chat --protocol responses --protocol anthropic --out reports/magpie.json +itera-connect smoke claude codex openclaw --model Auto --via magpie --out reports/clients.json +``` + +Each full probe makes four requests per protocol: one text response, one SSE response, and two +requests for a tool call/result round trip. The default output budget is 256 tokens per request; +`--budget` adjusts it (32–8192). Reasoning models may need more. Default protocol selection tests +the three conversational protocols advertised by the provider. Pass all three `--protocol` +arguments explicitly to test conversion from a Chat-only source through Magpie. + +The probe never executes arbitrary model tools; its sole tool returns a fixed code. It checks +the tool name/arguments and preserves full assistant output, including Messages thinking and +signature blocks, in the follow-up request. SSE tests require output and a protocol terminal +event and reject errors, incomplete responses and truncated streams. + +`smoke` tests an installed client's actual process, using a temporary config/home and safe +single-turn prompt. It reports `passed`, `failed`, `not-installed` or `manual-required`. +Skipped/manual clients do not make the aggregate CLI command successful. It suppresses arbitrary +client output in saved reports, which can otherwise contain private context or credentials. + +## WorkBuddy, Hermes and CC Switch UI acceptance + +For WorkBuddy, connect from the simple UI, restart the app, start a new task, select +`custom-local:iteracompute/` and ask for the fixed reply. The advanced Magpie workflow +instead uses `iteraconnect-iteracompute/`. Then use a disposable workspace and ask +it to create/read a small text file to exercise its real tool loop. Record app version, model, +result and a redacted screenshot. Repeat with WorkBuddy AI if supporting the international build. + +For Hermes, install its CLI, connect from the simple UI, start a fresh session, select the connected +provider and ask for the reply and a disposable-file tool round trip. Disconnect and confirm its +previous provider returns. Automatic Hermes one-turn acceptance uses 0.23.1 stream-json output, disables all CLI toolsets, ignores injected rules and uses a temporary home. It stops the temporary profile gateway afterward. The independent plain-YAML editor and optional Magpie adapters are additionally checked as configuration tests; those alone are not proof of inference. + +For CC Switch, open each generated import link in the desktop app, confirm the endpoint and +protocol, import, switch to the provider, then execute the relevant native client. WorkBuddy +provider links are unsupported upstream and must use Magpie's adapter or the native CC Switch UI. +Do not report a generated link alone as a completed desktop integration test. + +For each real client, also verify a tool call/result loop, streaming, a permission or bad-key +failure, and disconnect/restore behavior. The automated single-turn native smoke is only the +first part of acceptance; the API tool round-trip is not a substitute for each client's tool loop. diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..f2f54d5 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,34 @@ +[build-system] +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[project] +name = "iteracompute-agent-connect" +version = "0.1.0" +description = "A simple local client to connect model APIs to coding harnesses and agents" +readme = "README.md" +requires-python = ">=3.11" +license = "MIT" +license-files = ["LICENSE", "THIRD_PARTY_NOTICES"] +authors = [{name = "IteraCompute"}] +dependencies = [] + +[project.scripts] +itera-connect = "iteraconnect.cli:main" + +[project.urls] +Homepage = "https://github.com/IteraCompute/agent-connect" +Issues = "https://github.com/IteraCompute/agent-connect/issues" + +[tool.setuptools.packages.find] +where = ["src"] + +[tool.setuptools.package-data] +iteraconnect = ["upstreams.lock.json", "upstream-notices.txt", "web/*.html", "web/*.css", "web/*.js"] + +[tool.ruff] +target-version = "py311" +line-length = 100 + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I"] diff --git a/requirements-dev.txt b/requirements-dev.txt new file mode 100644 index 0000000..5264a85 --- /dev/null +++ b/requirements-dev.txt @@ -0,0 +1,2 @@ +ruff==0.17.5 +build==1.6.1 diff --git a/scripts/check_governance.py b/scripts/check_governance.py new file mode 100644 index 0000000..312aec9 --- /dev/null +++ b/scripts/check_governance.py @@ -0,0 +1,51 @@ +"""Read-only audit of repository visibility and administrator review enforcement.""" + +import base64 +import json +import subprocess + + +def api(path): + result = subprocess.run(["gh", "api", path], capture_output=True, text=True, check=True) + return json.loads(result.stdout) + + +def main(): + repo = "IteraCompute/agent-connect" + metadata = api("repos/" + repo) + protection = api("repos/" + repo + "/branches/main/protection") + reviews = protection["required_pull_request_reviews"] + owners = base64.b64decode( + api("repos/" + repo + "/contents/.github/CODEOWNERS?ref=main")["content"] + ).decode() + checks = { + "public": metadata["visibility"] == "public", + "issues": metadata["has_issues"], + "discussions": metadata["has_discussions"], + "no_auto_merge": not metadata["allow_auto_merge"], + "admins_enforced": protection["enforce_admins"]["enabled"], + "code_owner_review": reviews["require_code_owner_reviews"], + "approval_required": reviews["required_approving_review_count"] >= 1, + "stale_reviews_dismissed": reviews["dismiss_stale_reviews"], + "latest_push_approved": reviews["require_last_push_approval"], + "ci_required": "checks" in protection["required_status_checks"]["contexts"], + "conversations_resolved": protection["required_conversation_resolution"]["enabled"], + "no_force_push": not protection["allow_force_pushes"]["enabled"], + "no_main_deletion": not protection["allow_deletions"]["enabled"], + "codeowner_is_admin": api("repos/" + repo + "/collaborators/K-3-LT/permission")[ + "permission" + ] + == "admin", + "independent_admin_is_admin": api("repos/" + repo + "/collaborators/aikevan/permission")[ + "permission" + ] + == "admin", + "base_codeowners_include_independent_admin": "@aikevan" in owners, + "actions_enabled": api("repos/" + repo + "/actions/permissions")["enabled"], + } + print(json.dumps(checks, indent=2)) + return 0 if all(checks.values()) else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/iteraconnect/__init__.py b/src/iteraconnect/__init__.py new file mode 100644 index 0000000..07db8d9 --- /dev/null +++ b/src/iteraconnect/__init__.py @@ -0,0 +1,3 @@ +"""IteraCompute Agent Connect.""" + +__version__ = "0.1.0" diff --git a/src/iteraconnect/__main__.py b/src/iteraconnect/__main__.py new file mode 100644 index 0000000..eb53e2f --- /dev/null +++ b/src/iteraconnect/__main__.py @@ -0,0 +1,3 @@ +from .cli import main + +raise SystemExit(main()) diff --git a/src/iteraconnect/app.py b/src/iteraconnect/app.py new file mode 100644 index 0000000..d41129d --- /dev/null +++ b/src/iteraconnect/app.py @@ -0,0 +1,263 @@ +"""One local control panel plus the inference relay; no third-party UI/runtime.""" + +from __future__ import annotations + +import copy +import hmac +import json +import os +import secrets +import shutil +import threading +import webbrowser +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from urllib.parse import urlsplit + +from .config import ConnectError, state_dir +from .diagnostics import probe +from .gateway import Gateway, provider_models +from .native import client_path, connect_native, disconnect_native, render_native +from .settings import ( + CLIENTS, + check_settings, + public_settings, + read_settings, + runtime_config, + write_settings, +) +from .smoke import smoke + + +class App(ThreadingHTTPServer): + daemon_threads = True + block_on_close = False + + def __init__(self, settings, port=18424, relay_port=18423): + self.settings_path = Path(settings).absolute() + self.data = read_settings(self.settings_path) + self.settings_bytes = self.settings_path.read_bytes() + self.config = runtime_config(self.data, relay_port or 18423) + self.token = secrets.token_urlsafe(32) + self.operation = threading.Lock() + self.relay = Gateway(self.config, address=("127.0.0.1", relay_port)) + self.config["gateway"]["port"] = self.relay.server_port + try: + super().__init__(("127.0.0.1", port), Handler) + except OSError: + self.relay.server_close() + raise + self.origin = "http://127.0.0.1:" + str(self.server_port) + + def activate(self, data, persist=False): + check_settings(data) + if persist and self.settings_path.read_bytes() != self.settings_bytes: + raise ConnectError( + "本地配置文件已被修改,请先点击「重新读取配置」,避免覆盖刚填的 key。" + ) + config = runtime_config(data, self.relay.server_port) + if persist: + write_settings(self.settings_path, data) + self.settings_bytes = self.settings_path.read_bytes() + self.data, self.config, self.relay.config = data, config, config + + def state(self): + return { + "settings": public_settings(self.data), + "settings_path": str(self.settings_path), + "relay_port": self.relay.server_port, + "clients": [ + { + "id": k, + "name": v[0], + "protocol": v[1], + "installed": bool(shutil.which(k)) or client_path(k).parent.exists(), + "config_path": str(client_path(k)), + "connected": (state_dir() / "native-backups" / (k + ".json")).exists(), + } + for k, v in CLIENTS.items() + ], + } + + def draft_models(self, body): + """Discover models without saving a draft or changing live relay credentials.""" + pid = body.get("provider") + if not isinstance(pid, str): + raise ConnectError("请选择有效的 API。") + old = self.data["providers"].get(pid, {}) + provider = {k: body.get(k, old.get(k)) for k in ("name", "base_url", "protocols")} + provider["model"] = body.get("model") or old.get("model") or "Auto" + provider["api_key"] = body.get("api_key") or old.get("api_key", "") + if "endpoints" in body or "endpoints" in old: + provider["endpoints"] = body.get("endpoints", old.get("endpoints")) + # Each request owns a distinct temporary env reference; the active provider + # can keep serving requests with its original key during discovery. + temporary = "catalog-" + secrets.token_hex(16) + data = { + "selected_provider": temporary, + "client": body.get("client", self.data["client"]), + "providers": {temporary: provider}, + } + check_settings(data) + if not provider["api_key"]: + raise ConnectError("请先填写此 API 的 key。") + key_env = "ITERACONNECT_APP_KEY_" + temporary.upper().replace("-", "_") + try: + config = runtime_config(data, self.relay.server_port) + return {"models": [m["id"] for m in provider_models(config["providers"][temporary])]} + finally: + os.environ.pop(key_env, None) + + def action(self, route, body): + if route == "/api/models" and body: + return self.draft_models(body) + if route == "/api/reload": + self.activate(read_settings(self.settings_path)) + return self.state() + if route == "/api/save": + data = copy.deepcopy(self.data) + pid, target = body.get("provider"), body.get("client") + if target not in CLIENTS or not isinstance(pid, str): + raise ConnectError("请选择有效的 API 和客户端。") + old = data["providers"].get(pid, {}) + p = {k: body.get(k, old.get(k)) for k in ("name", "base_url", "model", "protocols")} + p["api_key"] = body.get("api_key") or old.get("api_key", "") + if "endpoints" in body: + p["endpoints"] = body["endpoints"] + elif "endpoints" in old: + p["endpoints"] = old["endpoints"] + data["providers"][pid] = p + data["selected_provider"], data["client"] = pid, target + self.activate(data, persist=True) + return self.state() + pid, target = self.data["selected_provider"], self.data["client"] + p = self.data["providers"][pid] + if route == "/api/disconnect": + return disconnect_native(target) + if route == "/api/export": + fragment = render_native(target, "", self.config, pid, p["model"]) + # Export substitutes the local relay token, never a vendor key. + return {"fragment": fragment, "message": "手动合并到客户端配置;仅含本地网关令牌。"} + if not p["api_key"]: + raise ConnectError("请先填写并保存 API key,或修改本地配置后点击「重新读取」。") + if route == "/api/models": + return {"models": [m["id"] for m in provider_models(self.config["providers"][pid])]} + if route == "/api/connect": + return connect_native(target, self.config, pid, p["model"]) + if route == "/api/probe": + protocol = CLIENTS[target][1] + if protocol not in p["protocols"]: + raise ConnectError(f"此客户端需要 {protocol} 协议,当前 API 未配置。") + return probe(self.config, pid, protocols=[protocol], budget=256) + if route == "/api/smoke": + if target not in ("claude", "codex", "openclaw", "hermes"): + return { + "status": "manual-required", + "message": "此客户端需要在原应用中手动发送测试消息;配置成功不代表实测通过。", + } + return smoke(self.config, target, pid, timeout=90, native=True) + raise ConnectError("未知操作。") + + +class Handler(BaseHTTPRequestHandler): + server: App + server_version = "AgentConnect" + sys_version = "" + + def log_message(self, *_): + pass + + def setup(self): + super().setup() + self.connection.settimeout(15) + + def reply(self, status, raw, mime="application/json; charset=utf-8"): + if not isinstance(raw, bytes): + raw = json.dumps(raw, ensure_ascii=False).encode() + self.send_response(status) + self.send_header("Content-Type", mime) + self.send_header("Content-Length", str(len(raw))) + self.send_header("Cache-Control", "no-store") + self.send_header("X-Content-Type-Options", "nosniff") + self.send_header("Referrer-Policy", "no-referrer") + self.send_header( + "Content-Security-Policy", + "default-src 'self'; script-src 'self'; style-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'", + ) + self.end_headers() + try: + self.wfile.write(raw) + except OSError: + pass + + def authorized(self, api=True): + if self.headers.get("Host") != urlsplit(self.server.origin).netloc: + self.reply(403, {"error": "只允许本机访问。"}) + return False + origin = self.headers.get("Origin") + if origin and origin != self.server.origin: + self.reply(403, {"error": "不允许跨站请求。"}) + return False + if api and not hmac.compare_digest( + self.headers.get("X-Agent-Connect", "").encode(), self.server.token.encode() + ): + self.reply(401, {"error": "请使用启动器打开的完整地址。"}) + return False + return True + + def do_GET(self): + if not self.authorized(api=self.path.startswith("/api/")): + return + if self.path == "/api/state": + self.reply(200, self.server.state()) + return + files = { + "/": ("index.html", "text/html; charset=utf-8"), + "/app.js": ("app.js", "text/javascript; charset=utf-8"), + "/app.css": ("app.css", "text/css; charset=utf-8"), + } + if self.path in files: + name, mime = files[self.path] + self.reply(200, Path(__file__).with_name("web").joinpath(name).read_bytes(), mime) + else: + self.reply(404, {"error": "页面不存在。"}) + + def do_POST(self): + if not self.authorized(): + return + if not self.server.operation.acquire(blocking=False): + self.reply(409, {"error": "上一个操作仍在进行,请稍后重试。"}) + return + try: + size = int(self.headers.get("Content-Length", "0")) + if not 0 < size <= 32768 or self.headers.get("Content-Type") != "application/json": + raise ConnectError("请求必须是小于 32 KiB 的 JSON。") + body = json.loads(self.rfile.read(size)) + if not isinstance(body, dict): + raise ValueError + self.reply(200, self.server.action(self.path, body)) + except ConnectError as e: + self.reply(400, {"error": str(e)}) + except (ValueError, TypeError, KeyError, AttributeError, OSError): + self.reply( + 400, {"error": "操作未完成,请检查配置、文件权限及网络。详细内容不会返回密钥。"} + ) + finally: + self.server.operation.release() + + +def serve_app(settings, port=18424, relay_port=18423, open_browser=True): + with App(settings, port, relay_port) as app, app.relay: + worker = threading.Thread(target=app.relay.serve_forever, daemon=True) + worker.start() + url = app.origin + "/#" + app.token + print("Agent Connect 已启动:" + url, flush=True) + print("配置文件:" + str(app.settings_path), flush=True) + print("使用客户端期间请保持此窗口运行;Ctrl+C 退出。", flush=True) + if open_browser: + webbrowser.open(url) + try: + app.serve_forever() + finally: + app.relay.shutdown() + worker.join(timeout=3) diff --git a/src/iteraconnect/cli.py b/src/iteraconnect/cli.py new file mode 100644 index 0000000..a1792bd --- /dev/null +++ b/src/iteraconnect/cli.py @@ -0,0 +1,309 @@ +"""Public CLI. Defaults are useful without modifying any native agent config.""" + +from __future__ import annotations + +import argparse +import json +import shutil +import subprocess +import sys +import threading +from pathlib import Path + +from . import __version__ +from .config import ConnectError, api_key, gateway_key, gateway_url, load, private_write, save +from .diagnostics import probe +from .gateway import Gateway, provider_models +from .integrations import ( + cc_link, + connect, + install_magpie, + magpie, + magpie_bin, + sync_magpie, + write_export, +) +from .launch import launch +from .network import json_request +from .smoke import smoke + + +def parser(): + p = argparse.ArgumentParser( + prog="itera-connect", description="Agent Connect · 选择 API,连接客户端" + ) + p.add_argument("--version", action="version", version=__version__) + p.add_argument( + "--config", type=Path, help="Agent Connect config.json; credentials are env references" + ) + sub = p.add_subparsers(dest="command", required=True) + app = sub.add_parser("app", help="打开独立的本地客户端界面(不需要 Magpie 或 CC Switch)") + app.add_argument("--settings", type=Path, default=Path("agent-connect.local.toml")) + app.add_argument("--port", type=int, default=18424) + app.add_argument("--relay-port", type=int, default=18423) + app.add_argument("--no-browser", action="store_true") + sub.add_parser("init", help="Write the default IteraCompute profile if no config exists") + providers = sub.add_parser("provider", help="Choose IteraCompute or any other API provider") + actions = providers.add_subparsers(dest="action", required=True) + actions.add_parser("list") + use = actions.add_parser("use") + use.add_argument("id") + add = actions.add_parser("add") + add.add_argument("id") + add.add_argument("--name") + add.add_argument("--key-env", required=True) + add.add_argument("--model", required=True) + for kind in ("chat", "responses", "anthropic", "gemini"): + add.add_argument("--" + kind, help="Native protocol base URL") + add.add_argument( + "--allow-http", action="store_true", help="Allow HTTP for a trusted LAN endpoint" + ) + for command in ("serve", "up"): + server = sub.add_parser( + command, + help="Serve the loopback relay" + if command == "serve" + else "Start the relay and Magpie together; sync providers first", + ) + if command == "up": + server.add_argument( + "--web", action="store_true", help="Serve Magpie's management UI too" + ) + sub.add_parser("install-magpie", help="Download the pinned, SHA-256 verified Magpie CLI") + sub.add_parser("sync", help="Add/update these relay providers in Magpie; relay must be running") + models = sub.add_parser("models", help="Fetch the provider's current catalog") + models.add_argument("--provider") + con = sub.add_parser( + "connect", help="Use Magpie's native adapter to connect an installed agent" + ) + con.add_argument("target") + con.add_argument("--provider") + con.add_argument("--model") + dis = sub.add_parser("disconnect", help="Use Magpie to restore an agent's previous provider") + dis.add_argument("target") + link = sub.add_parser( + "cc-link", help="Create a CC Switch provider import with a local-only key" + ) + link.add_argument("target") + link.add_argument("--provider") + link.add_argument("--model") + link.add_argument( + "--api-format", choices=("openai_chat", "openai_responses", "anthropic", "gemini_native") + ) + link.add_argument("--via", choices=("gateway", "magpie"), default="gateway") + export = sub.add_parser("export", help="Write a private, standalone native config fragment") + export.add_argument( + "target", choices=("claude", "codex", "workbuddy", "workbuddy-ai", "openclaw", "hermes") + ) + export.add_argument("--provider") + export.add_argument("--model") + export.add_argument("--out", type=Path, required=True) + runner = sub.add_parser( + "run", help="Launch Claude Code or Codex with process-local API settings" + ) + runner.add_argument("target", choices=("claude", "codex")) + runner.add_argument("--provider") + runner.add_argument("--model") + runner.add_argument("--via", choices=("gateway", "magpie", "direct"), default="gateway") + for command in ("probe", "smoke"): + test = sub.add_parser( + command, + help="Test API contracts" + if command == "probe" + else "Test installed native clients in a temporary HOME", + ) + if command == "smoke": + test.add_argument( + "targets", nargs="*", default=["claude", "codex", "openclaw", "workbuddy", "hermes"] + ) + test.add_argument("--provider") + test.add_argument("--model") + test.add_argument("--via", choices=("gateway", "magpie", "direct"), default="gateway") + test.add_argument("--out", type=Path) + if command == "probe": + test.add_argument( + "--protocol", action="append", choices=("chat", "responses", "anthropic") + ) + test.add_argument("--budget", type=int, default=256) + test.add_argument("--no-tools", action="store_true") + else: + test.add_argument("--timeout", type=int, default=90) + sub.add_parser("doctor", help="Report missing keys, clients and gateway; never display keys") + for command in ("magpie", "cc-switch"): + sub.add_parser(command, help="Pass all following arguments to the upstream program") + return p + + +def main(argv=None): + argv = list(sys.argv[1:] if argv is None else argv) + trailing = [] + if "--" in argv: + index = argv.index("--") + argv, trailing = argv[:index], argv[index + 1 :] + p = parser() + args = p.parse_args(argv) + if trailing and args.command not in ("run", "magpie", "cc-switch"): + p.error("Arguments after -- are accepted only for run, magpie and cc-switch") + try: + return dispatch(args, trailing) + except (ConnectError, OSError) as e: + # OSError filenames may come from native tools: keep OS errors generic. + message = ( + str(e) if isinstance(e, ConnectError) else "Local file or process operation failed" + ) + print("itera-connect: " + message, file=sys.stderr) + return 1 + except KeyboardInterrupt: + return 130 + + +def output(value, path=None): + text = json.dumps(value, indent=2) + "\n" + if path: + private_write(path, text) + print(text, end="") + + +def dispatch(args, trailing): + if args.command == "app": + from .app import serve_app + + serve_app(args.settings, args.port, args.relay_port, not args.no_browser) + return 0 + config = load(args.config) + command = args.command + pid = getattr(args, "provider", None) or config["active_provider"] + if pid not in config["providers"]: + raise ConnectError("Unknown provider") + vendor_env_names = [p["key_env"] for p in config["providers"].values()] + if command == "init": + from .config import state_dir + + path = args.config or state_dir() / "config.json" + if path.exists(): + raise ConnectError("Configuration already exists; use provider commands to change it") + save(config, path) + gateway_key() + print( + "Created IteraCompute profile. Set ITERACOMPUTE_API_KEY, then run itera-connect up --web" + ) + elif command == "provider": + if args.action == "list": + output(config) + elif args.action == "use": + if args.id not in config["providers"]: + raise ConnectError("Unknown provider") + config["active_provider"] = args.id + save(config, args.config) + print("Default provider: " + args.id + ". Restart the relay to apply.") + else: + if args.id in config["providers"]: + raise ConnectError( + "Provider already exists; edit its environment-only config explicitly" + ) + config["providers"][args.id] = { + "name": args.name or args.id, + "key_env": args.key_env, + "default_model": args.model, + "allow_http": args.allow_http, + "endpoints": { + k: getattr(args, k).rstrip("/") + for k in ("chat", "responses", "anthropic", "gemini") + if getattr(args, k) + }, + } + save(config, args.config) + print("Added " + args.id + ". Restart the relay and run sync.") + elif command in ("serve", "up"): + with Gateway(config) as gateway: + print("Relay listening at " + gateway_url(config), flush=True) + if command == "serve": + gateway.serve_forever() + else: + worker = threading.Thread(target=gateway.serve_forever, daemon=True) + worker.start() + try: + sync_magpie(config) + print("Providers synced. Starting Magpie.", flush=True) + result = magpie( + ["serve", *(["--web"] if args.web else [])], + timeout=None, + vendor_env_names=vendor_env_names, + ) + return result.returncode + finally: + gateway.shutdown() + worker.join(timeout=3) + elif command == "install-magpie": + print("Verified Magpie: " + str(install_magpie())) + elif command == "sync": + output({"synced": sync_magpie(config)}) + elif command == "models": + output({"provider": pid, "data": provider_models(config["providers"][pid])}) + elif command == "connect": + connect(config, args.target, pid, args.model) + print("Connected " + args.target + ". Restart the client if it keeps its config in memory.") + elif command == "disconnect": + magpie([args.target, "default"], capture=True, vendor_env_names=vendor_env_names) + print("Disconnected " + args.target + ". Restart it if required.") + elif command == "cc-link": + print(cc_link(config, args.target, pid, args.model, args.api_format, args.via)) + elif command == "export": + write_export(config, args.target, pid, args.out, args.model) + print("Fragment written to " + str(args.out) + "; merge it into your client config.") + elif command == "run": + return launch(config, args.target, pid, args.model, args.via, trailing) + elif command == "probe": + if not 32 <= args.budget <= 8192: + raise ConnectError("Probe budget must be between 32 and 8192 tokens per request") + result = probe( + config, pid, args.model, args.via, args.protocol, args.budget, not args.no_tools + ) + output(result, args.out) + return 0 if result["passed"] else 1 + elif command == "smoke": + if not 10 <= args.timeout <= 600: + raise ConnectError("Smoke timeout must be between 10 and 600 seconds per client") + results = [smoke(config, t, pid, args.model, args.via, args.timeout) for t in args.targets] + output({"kind": "native-clients", "results": results}, args.out) + return 0 if results and all(r["status"] == "passed" for r in results) else 1 + elif command == "doctor": + clients = { + t: bool(shutil.which(t)) for t in ("claude", "codex", "openclaw", "hermes", "cc-switch") + } + try: + clients["magpie"] = bool(magpie_bin()) + except ConnectError: + clients["magpie"] = False + try: + relay = ( + json_request("GET", gateway_url(config) + "/health", timeout=2).get("name") + == "iteraconnect" + ) + except ConnectError: + relay = False + output( + { + "version": __version__, + "clients": clients, + "relay_running": relay, + "providers": { + k: { + "key_present": bool(api_key(v, required=False)), + "key_env": v["key_env"], + "protocols": list(v["endpoints"]), + } + for k, v in config["providers"].items() + }, + } + ) + elif command == "magpie": + return magpie(trailing, timeout=None, vendor_env_names=vendor_env_names).returncode + elif command == "cc-switch": + binary = shutil.which("cc-switch") + if not binary: + raise ConnectError( + "Install CC Switch from its official release, then use cc-link to import" + ) + return subprocess.run([binary, *trailing]).returncode + return 0 diff --git a/src/iteraconnect/config.py b/src/iteraconnect/config.py new file mode 100644 index 0000000..f122afa --- /dev/null +++ b/src/iteraconnect/config.py @@ -0,0 +1,174 @@ +"""Small, versioned configuration. Provider credentials are environment references.""" + +from __future__ import annotations + +import copy +import ipaddress +import json +import os +import re +import secrets +import tempfile +from pathlib import Path +from urllib.parse import urlsplit + +PROTOCOLS = ("chat", "responses", "anthropic", "gemini") +DEFAULT = { + "schema_version": 1, + "active_provider": "iteracompute", + "gateway": {"host": "127.0.0.1", "port": 18423, "timeout": 180}, + "providers": { + "iteracompute": { + "name": "IteraCompute", + "key_env": "ITERACOMPUTE_API_KEY", + "default_model": "Auto", + "endpoints": { + "chat": "https://api.iteracompute.com/v1", + "responses": "https://api.iteracompute.com/v1", + "anthropic": "https://api.iteracompute.com", + }, + } + }, +} + + +class ConnectError(Exception): + """An error safe to show to the user, without upstream data or credentials.""" + + +def state_dir() -> Path: + if p := os.environ.get("ITERACONNECT_HOME"): + return Path(p).expanduser().absolute() + return Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "iteraconnect" + + +def private_write(path: Path, content: str | bytes) -> None: + """Replace one file atomically; never create a world-readable intermediate file.""" + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + fd, tmp = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent) + try: + with os.fdopen(fd, "wb") as f: + f.write(content.encode() if isinstance(content, str) else content) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def validate_url(value: str, allow_http: bool = False) -> str: + try: + p = urlsplit(value) + _ = p.port + if p.scheme not in ("http", "https") or not p.hostname: + raise ValueError + if p.username or p.password or p.query or p.fragment: + raise ValueError + if any(c.isspace() or ord(c) < 32 for c in value): + raise ValueError + loopback = p.hostname == "localhost" + try: + loopback = loopback or ipaddress.ip_address(p.hostname).is_loopback + except ValueError: + pass + if p.scheme == "http" and not (loopback or allow_http): + raise ConnectError("HTTP requires --allow-http except on loopback addresses") + except ValueError: + raise ConnectError( + "Invalid endpoint: use an HTTP(S) URL without credentials or query" + ) from None + return value.rstrip("/") + + +def validate(data: dict) -> dict: + try: + if data["schema_version"] != 1 or not data["providers"]: + raise ValueError + gateway = data["gateway"] + # This gateway holds vendor credentials. Remote/LAN serving belongs to Magpie. + if gateway["host"] not in ("127.0.0.1", "localhost"): + raise ConnectError( + "Agent Connect binds to loopback; use Magpie's sharing for remote access" + ) + if type(gateway["port"]) is not int or not 1 <= gateway["port"] <= 65535: + raise ValueError + if not 1 <= gateway["timeout"] <= 600: + raise ValueError + if data["active_provider"] not in data["providers"]: + raise ValueError + for pid, p in data["providers"].items(): + if not re.fullmatch(r"[a-z][a-z0-9-]{0,47}", pid): + raise ValueError + if not isinstance(p["name"], str) or not p["name"]: + raise ValueError + if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", p["key_env"]): + raise ValueError + if not isinstance(p["default_model"], str) or not p["default_model"].strip(): + raise ValueError + if not p["endpoints"] or set(p["endpoints"]) - set(PROTOCOLS): + raise ValueError + if type(p.get("allow_http", False)) is not bool: + raise ValueError + for protocol, endpoint in p["endpoints"].items(): + p["endpoints"][protocol] = validate_url(endpoint, p.get("allow_http", False)) + # Never silently accept inline keys from hand-edited configs. + if set(p) - {"name", "key_env", "default_model", "endpoints", "allow_http"}: + raise ConnectError("Provider config accepts key_env, never inline credentials") + except (KeyError, TypeError, ValueError, AttributeError): + raise ConnectError( + "Invalid Agent Connect configuration; see docs/configuration.md" + ) from None + return data + + +def load(path: Path | None = None) -> dict: + path = path or state_dir() / "config.json" + if not path.exists(): + return copy.deepcopy(DEFAULT) + try: + return validate(json.loads(path.read_text())) + except (json.JSONDecodeError, UnicodeError): + raise ConnectError("Invalid configuration JSON") from None + + +def save(data: dict, path: Path | None = None) -> None: + private_write(path or state_dir() / "config.json", json.dumps(validate(data), indent=2) + "\n") + + +def gateway_key() -> str: + if value := os.environ.get("ITERACONNECT_GATEWAY_KEY"): + if len(value) < 24 or any(ord(c) < 33 or ord(c) > 126 for c in value): + raise ConnectError( + "ITERACONNECT_GATEWAY_KEY needs at least 24 printable ASCII characters" + ) + return value + path = state_dir() / "gateway.key" + path.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + try: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + except FileExistsError: + value = path.read_text().strip() + if len(value) < 24: + raise ConnectError( + "Invalid gateway.key; restore it or remove it to create a new local key" + ) + 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: + value = os.environ.get(provider["key_env"], "") + if required and not value: + raise ConnectError(f"Set {provider['key_env']} in the gateway process environment") + if any(ord(c) < 33 or ord(c) > 126 for c in value): + raise ConnectError(f"{provider['key_env']} must contain printable ASCII without whitespace") + return value + + +def gateway_url(config: dict, pid: str | None = None) -> str: + base = f"http://127.0.0.1:{config['gateway']['port']}" + return base + (f"/p/{pid}" if pid else "") diff --git a/src/iteraconnect/diagnostics.py b/src/iteraconnect/diagnostics.py new file mode 100644 index 0000000..6a0042a --- /dev/null +++ b/src/iteraconnect/diagnostics.py @@ -0,0 +1,269 @@ +"""Protocol contract probes, including complete SSE and a real tool-result round trip.""" + +from __future__ import annotations + +import json +import os +import time + +from .config import ConnectError, api_key, gateway_key, gateway_url +from .network import MAX_JSON, request + +PROMPT = "Reply with exactly ITERACONNECT_OK." +TOOL = { + "name": "echo_code", + "description": "Return the code unchanged.", + "parameters": { + "type": "object", + "properties": {"code": {"type": "string"}}, + "required": ["code"], + "additionalProperties": False, + }, +} + + +def endpoint(config, pid, protocol, via): + p = config["providers"][pid] + if via == "magpie": + root = os.environ.get("ITERACONNECT_MAGPIE_URL", "http://127.0.0.1:3425").rstrip("/") + base, key = root + ("/v1" if protocol != "anthropic" else ""), "magpie-iteraconnect-probe" + else: + if protocol not in p["endpoints"]: + raise ConnectError("Provider does not advertise this native protocol") + if via == "direct": + base, key = p["endpoints"][protocol], api_key(p) + else: + base = gateway_url(config, pid) + ("/v1" if protocol != "anthropic" else "") + key = gateway_key() + suffix = {"chat": "/chat/completions", "responses": "/responses", "anthropic": "/v1/messages"}[ + protocol + ] + return base + suffix, key + + +def send(url, key, protocol, payload, timeout): + headers = {"Content-Type": "application/json"} + if protocol == "anthropic": + headers.update({"x-api-key": key, "anthropic-version": "2023-06-01"}) + else: + headers["Authorization"] = "Bearer " + key + conn, response = request("POST", url, headers, json.dumps(payload).encode(), timeout) + try: + if not 200 <= response.status < 300: + raise ConnectError(f"Endpoint returned HTTP {response.status}") + raw = response.read(MAX_JSON + 1) + if len(raw) > MAX_JSON: + raise ConnectError("Probe response exceeds limit") + if payload.get("stream"): + return stream_check(protocol, raw) + try: + result = json.loads(raw) + except (ValueError, UnicodeError): + raise ConnectError("Invalid JSON response") from None + if not isinstance(result, dict) or result.get("error"): + raise ConnectError("API returned an error object") + return result + except (OSError, ValueError): + raise ConnectError("Probe connection ended before a complete response") from None + finally: + conn.close() + + +def stream_check(protocol, raw): + try: + frames = raw.decode().replace("\r\n", "\n").split("\n\n") + types, done, text = [], False, "" + for frame in frames: + values = [x[5:].lstrip() for x in frame.splitlines() if x.startswith("data:")] + if not values: + continue + data = "\n".join(values) + if data == "[DONE]": + done = True + continue + event = json.loads(data) + kind = event.get("type", "") + if event.get("error") or kind in ("error", "response.failed", "response.incomplete"): + raise ConnectError("SSE contains an error or incomplete response") + types.append(kind) + if protocol == "chat": + for choice in event.get("choices", []): + text += choice.get("delta", {}).get("content") or "" + elif protocol == "responses" and kind == "response.output_text.delta": + text += event.get("delta", "") + elif protocol == "anthropic" and kind == "content_block_delta": + text += event.get("delta", {}).get("text", "") + terminal = ( + done + if protocol == "chat" + else ( + "response.completed" in types + if protocol == "responses" + else "message_stop" in types + ) + ) + if not terminal or "ITERACONNECT_OK" not in text: + raise ConnectError("SSE is missing expected output or its terminal event") + if protocol == "responses" and (not types or types[0] != "response.created"): + raise ConnectError("Responses SSE must begin with response.created") + if protocol == "anthropic" and (not types or types[0] != "message_start"): + raise ConnectError("Messages SSE must begin with message_start") + return {"complete": True} + except (ValueError, UnicodeError, TypeError, AttributeError): + raise ConnectError("Malformed SSE response") from None + + +def payload(protocol, model, budget, stream=False): + p = {"model": model, "stream": stream} + if protocol == "responses": + p.update(input=PROMPT, max_output_tokens=budget, store=False) + else: + p.update(messages=[{"role": "user", "content": PROMPT}], max_tokens=budget) + return p + + +def check_text(protocol, response): + try: + if protocol == "chat": + text = response["choices"][0]["message"]["content"] + elif protocol == "responses": + if response.get("status") != "completed": + raise ConnectError("Responses object is not completed") + text = "".join( + c.get("text", "") for i in response["output"] for c in i.get("content", []) + ) + else: + text = "".join(c.get("text", "") for c in response["content"]) + if not isinstance(text, str) or "ITERACONNECT_OK" not in text: + raise ConnectError("Response does not contain expected text") + except (KeyError, IndexError, TypeError): + raise ConnectError("Response has an invalid protocol shape") from None + + +def tool_roundtrip(protocol, url, key, model, budget, timeout): + p = payload(protocol, model, budget) + prompt = "Call echo_code with code ITERACONNECT_OK, then repeat its result." + if protocol == "responses": + p["input"] = prompt + p["tools"] = [{"type": "function", **TOOL}] + p["tool_choice"] = {"type": "function", "name": TOOL["name"]} + elif protocol == "chat": + p["messages"] = [{"role": "user", "content": prompt}] + p["tools"] = [{"type": "function", "function": TOOL}] + p["tool_choice"] = {"type": "function", "function": {"name": TOOL["name"]}} + else: + p["messages"] = [{"role": "user", "content": prompt}] + p["tools"] = [ + { + "name": TOOL["name"], + "description": TOOL["description"], + "input_schema": TOOL["parameters"], + } + ] + p["tool_choice"] = {"type": "tool", "name": TOOL["name"]} + try: + first = send(url, key, protocol, p, timeout) + except ConnectError as e: + raise ConnectError("Tool call request failed: " + str(e)) from None + try: + if protocol == "chat": + message = first["choices"][0]["message"] + calls = message["tool_calls"] + call = calls[0] + name, arguments = call["function"]["name"], json.loads(call["function"]["arguments"]) + p["messages"] += [message] + [ + {"role": "tool", "tool_call_id": c["id"], "content": "ITERACONNECT_OK"} + for c in calls + ] + elif protocol == "responses": + calls = [c for c in first["output"] if c["type"] == "function_call"] + call = calls[0] + name, arguments = call["name"], json.loads(call["arguments"]) + p["input"] = [ + {"role": "user", "content": prompt}, + *first["output"], + *[ + { + "type": "function_call_output", + "call_id": c["call_id"], + "output": "ITERACONNECT_OK", + } + for c in calls + ], + ] + else: + calls = [c for c in first["content"] if c["type"] == "tool_use"] + call = calls[0] + name, arguments = call["name"], call["input"] + # Preserve thinking/signature blocks exactly as returned by the provider. + p["messages"] += [ + {"role": "assistant", "content": first["content"]}, + { + "role": "user", + "content": [ + { + "type": "tool_result", + "tool_use_id": c["id"], + "content": "ITERACONNECT_OK", + } + for c in calls + ], + }, + ] + if name != TOOL["name"] or arguments != {"code": "ITERACONNECT_OK"}: + raise ConnectError("Tool call name or arguments did not match the probe") + except (KeyError, IndexError, TypeError, ValueError): + raise ConnectError("Provider did not return a valid tool call") from None + p.pop("tool_choice", None) + try: + check_text(protocol, send(url, key, protocol, p, timeout)) + except ConnectError as e: + raise ConnectError("Tool result request failed: " + str(e)) from None + + +def probe(config, pid, model=None, via="gateway", protocols=None, budget=256, tools=True): + p = config["providers"][pid] + selected = model or p["default_model"] + if via == "magpie": + selected = "iteraconnect-" + pid + "/" + selected + protocols = protocols or [k for k in ("chat", "responses", "anthropic") if k in p["endpoints"]] + results = [] + for protocol in protocols: + for case in ["text", "stream", "tool-roundtrip"] if tools else ["text", "stream"]: + start = time.monotonic() + try: + url, key = endpoint(config, pid, protocol, via) + if case == "tool-roundtrip": + tool_roundtrip( + protocol, url, key, selected, budget, config["gateway"]["timeout"] + ) + else: + value = send( + url, + key, + protocol, + payload(protocol, selected, budget, case == "stream"), + config["gateway"]["timeout"], + ) + if case == "text": + check_text(protocol, value) + status, detail = "passed", "contract satisfied" + except ConnectError as e: + status, detail = "failed", str(e) + results.append( + { + "protocol": protocol, + "case": case, + "status": status, + "detail": detail, + "seconds": round(time.monotonic() - start, 3), + } + ) + return { + "kind": "api-contract", + "provider": pid, + "model": selected, + "via": via, + "passed": bool(results) and all(x["status"] == "passed" for x in results), + "results": results, + } diff --git a/src/iteraconnect/gateway.py b/src/iteraconnect/gateway.py new file mode 100644 index 0000000..2b328aa --- /dev/null +++ b/src/iteraconnect/gateway.py @@ -0,0 +1,275 @@ +"""Authenticated loopback relay. Protocol conversion is supplied by Magpie.""" + +from __future__ import annotations + +import hmac +import http.client +import json +import re +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qsl, unquote, urlsplit + +from . import __version__ +from .config import ConnectError, api_key, gateway_key +from .network import MAX_JSON, json_request, request + +# Explicit inference routes keep provider administration APIs unreachable. +ROUTES = { + "/v1/chat/completions": ("chat", "/chat/completions"), + "/v1/responses": ("responses", "/responses"), + "/v1/messages": ("anthropic", "/v1/messages"), + "/v1/messages/count_tokens": ("anthropic", "/v1/messages/count_tokens"), + "/v1/embeddings": ("chat", "/embeddings"), + "/v1/images/generations": ("chat", "/images/generations"), + "/v1/rerank": ("chat", "/rerank"), +} + + +def provider_models(provider: dict, timeout=20) -> list[dict]: + endpoints = provider["endpoints"] + if base := endpoints.get("chat") or endpoints.get("responses"): + url = base + "/models" + elif base := endpoints.get("anthropic"): + url = base + "/v1/models" + else: + # Gemini-only providers need Google's list shape; Magpie can still select a model by id. + return [{"id": provider["default_model"], "object": "model"}] + value = json_request("GET", url, api_key(provider, required=False), timeout=timeout) + if not isinstance(value, dict) or not isinstance(value.get("data"), list): + raise ConnectError("Provider returned an invalid model catalog") + rows = value["data"] + if any(not isinstance(x, dict) or not isinstance(x.get("id"), str) for x in rows): + raise ConnectError("Provider returned an invalid model catalog") + return rows + + +class Gateway(ThreadingHTTPServer): + daemon_threads = True + block_on_close = False + + def __init__(self, config: dict, key: str | None = None, address=None): + self.config = config + self.key = key or gateway_key() + self.slots = threading.BoundedSemaphore(64) + self.counters = {"requests": 0, "errors": 0} + self.counter_lock = threading.Lock() + g = config["gateway"] + super().__init__(address or (g["host"], g["port"]), Handler) + + def count(self, field): + with self.counter_lock: + self.counters[field] += 1 + + +class Handler(BaseHTTPRequestHandler): + server: Gateway + protocol_version = "HTTP/1.1" + server_version = "IteraConnect/" + __version__ + sys_version = "" + + def setup(self): + super().setup() + self.connection.settimeout(self.server.config["gateway"]["timeout"]) + + def log_message(self, *_): + # No request paths, prompts, headers, keys or upstream errors in logs. + pass + + def json(self, status: int, value: dict): + raw = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(raw))) + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.end_headers() + self.close_connection = True + try: + self.wfile.write(raw) + except OSError: + pass + + def fail(self, status, message): + self.server.count("errors") + self.json(status, {"type": "error", "error": {"type": "api_error", "message": message}}) + + def authenticated(self): + if self.headers.get("Origin"): + self.fail(403, "Browser origins are not accepted on the credential relay") + return False + bearer = self.headers.get("Authorization", "") + key = bearer[7:] if bearer.startswith("Bearer ") else "" + other = self.headers.get("x-api-key", "") or self.headers.get("x-goog-api-key", "") + if key and other and key != other: + self.fail(400, "Conflicting gateway credentials") + return False + if not hmac.compare_digest((key or other).encode(), self.server.key.encode()): + self.fail(401, "A valid local gateway key is required") + return False + return True + + def split_route(self): + parsed = urlsplit(self.path) + path = unquote(parsed.path) + if ( + parsed.fragment + or any(c in path for c in ("\\", "\x00", "\r", "\n", "?", "#", "%")) + or any(segment in (".", "..") for segment in path.split("/")) + ): + raise ConnectError("Invalid inference path") + self.inference_query = "" + if parsed.query: + # Native Anthropic SDKs append beta=true; Gemini's SSE transport uses alt=sse. + query = parse_qsl(parsed.query, keep_blank_values=True) + if query == [("beta", "true")] and path.endswith( + ("/v1/messages", "/v1/messages/count_tokens") + ): + self.inference_query = "?beta=true" + elif query == [("alt", "sse")] and ":streamGenerateContent" in path: + self.inference_query = "?alt=sse" + else: + raise ConnectError( + "Only native beta=true and alt=sse transport queries are accepted" + ) + if path.startswith("/p/"): + parts = path.split("/", 3) + if len(parts) != 4 or parts[2] not in self.server.config["providers"]: + raise ConnectError("Unknown provider route") + return parts[2], "/" + parts[3] + return None, path + + def do_GET(self): + if self.path == "/health": + self.json(200, {"name": "iteraconnect", "version": __version__}) + return + if not self.authenticated(): + return + try: + pid, path = self.split_route() + if path != "/v1/models": + self.fail(404, "Inference route not found") + return + rows, errors = [], [] + selected = [pid] if pid else list(self.server.config["providers"]) + for source in selected: + try: + for row in provider_models(self.server.config["providers"][source]): + rows.append({**row, "id": row["id"] if pid else source + "/" + row["id"]}) + except ConnectError as e: + errors.append({"provider": source, "message": str(e)}) + if not rows and errors: + self.fail(502, "Model catalog unavailable") + else: + self.json(200, {"object": "list", "data": rows, "errors": errors}) + except ConnectError as e: + self.fail(400, str(e)) + + def do_POST(self): + if not self.authenticated(): + return + if not self.server.slots.acquire(blocking=False): + self.fail(429, "Local gateway concurrency limit reached") + return + try: + self.relay() + except ConnectError as e: + self.fail(400, str(e)) + except (OSError, http.client.HTTPException): + # A closed stream remains closed: never replay a possibly executed tool request. + self.close_connection = True + finally: + self.server.slots.release() + + def relay(self): + pid, path = self.split_route() + route = ROUTES.get(path) + gemini = re.fullmatch( + r"/v1beta/models/([^:]+):(generateContent|streamGenerateContent)", path + ) + if not route and not gemini: + self.fail(404, "Inference route not found") + return + if self.headers.get("Transfer-Encoding"): + raise ConnectError("Use Content-Length for request bodies") + try: + length = int(self.headers.get("Content-Length", "-1")) + except ValueError: + raise ConnectError("Invalid Content-Length") from None + if not 0 < length <= MAX_JSON: + self.fail(413, "JSON body must be between 1 byte and 16 MiB") + return + if self.headers.get_content_type() != "application/json": + self.fail(415, "Use application/json") + return + raw = self.rfile.read(length) + if len(raw) != length: + raise ConnectError("Incomplete request body") + try: + body = json.loads(raw) + except (ValueError, UnicodeError): + raise ConnectError("Invalid JSON body") from None + if not isinstance(body, dict): + raise ConnectError("JSON body must be an object") + model = gemini[1] if gemini else body.get("model", "") + if not isinstance(model, str) or not model: + raise ConnectError("A model id is required") + providers = self.server.config["providers"] + prefix, sep, rest = model.partition("/") + if pid is None and sep and prefix in providers: + pid, model = prefix, rest + pid = pid or self.server.config["active_provider"] + provider = providers[pid] + protocol, suffix = ("gemini", f"/models/{model}:{gemini[2]}") if gemini else route + suffix += self.inference_query + if protocol not in provider["endpoints"]: + self.fail( + 501, "Provider has no native endpoint for this protocol; use the Magpie bridge" + ) + return + if not gemini: + body["model"] = model + key = api_key(provider) + headers = {"Content-Type": "application/json", "Accept": self.headers.get("Accept", "*/*")} + # Never forward local Authorization, cookies, Host, or an arbitrary user-supplied header. + if protocol == "anthropic": + headers["x-api-key"] = key + headers["anthropic-version"] = self.headers.get("anthropic-version", "2023-06-01") + if beta := self.headers.get("anthropic-beta"): + headers["anthropic-beta"] = beta + elif protocol == "gemini": + headers["x-goog-api-key"] = key + else: + headers["Authorization"] = "Bearer " + key + try: + conn, response = request( + "POST", + provider["endpoints"][protocol] + suffix, + headers, + json.dumps(body).encode(), + self.server.config["gateway"]["timeout"], + ) + except ConnectError: + self.fail(502, "Upstream connection failed or timed out") + return + self.server.count("requests") + try: + if not 200 <= response.status < 300: + # HTTP redirects are deliberately not followed with the vendor credential. + self.fail( + response.status if 400 <= response.status < 600 else 502, + f"Provider {pid} returned HTTP {response.status}", + ) + return + self.send_response(response.status) + self.send_header("Content-Type", response.getheader("Content-Type", "application/json")) + self.send_header("Cache-Control", "no-store") + self.send_header("Connection", "close") + self.send_header("X-Accel-Buffering", "no") + self.end_headers() + self.close_connection = True + while chunk := response.read1(65536): + self.wfile.write(chunk) + self.wfile.flush() + finally: + conn.close() diff --git a/src/iteraconnect/integrations.py b/src/iteraconnect/integrations.py new file mode 100644 index 0000000..4b06d9d --- /dev/null +++ b/src/iteraconnect/integrations.py @@ -0,0 +1,305 @@ +"""Composition adapters: keep Magpie's full CLI and CC Switch's native import contract.""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import shutil +import subprocess +import tempfile +import urllib.request +from pathlib import Path +from urllib.parse import urlencode + +from .config import ConnectError, gateway_key, gateway_url, private_write, state_dir +from .network import json_request + +CC_FORMATS = { + "claude": "anthropic", + "codex": "openai_responses", + "gemini": "gemini_native", + "agy": "gemini_native", + "grokbuild": "openai_responses", + "opencode": "openai_chat", + "openclaw": "openai_chat", + "hermes": "openai_chat", + "pi": "openai_chat", +} +FORMAT_PROTOCOL = { + "anthropic": "anthropic", + "openai_responses": "responses", + "openai_chat": "chat", + "gemini_native": "gemini", +} + + +def lock_data(): + return json.loads(Path(__file__).with_name("upstreams.lock.json").read_text()) + + +def magpie_bin() -> str: + if path := os.environ.get("ITERACONNECT_MAGPIE_BIN"): + if not Path(path).is_file(): + raise ConnectError("ITERACONNECT_MAGPIE_BIN is not a file") + return path + local = state_dir() / "bin" / ("magpie.exe" if os.name == "nt" else "magpie") + if local.is_file(): + return str(local) + if path := shutil.which("magpie"): + return path + raise ConnectError("Magpie is not installed; run: itera-connect install-magpie") + + +def install_magpie() -> Path: + system = {"Darwin": "darwin", "Linux": "linux", "Windows": "windows"}.get(platform.system()) + machine = {"x86_64": "amd64", "AMD64": "amd64", "aarch64": "arm64", "arm64": "arm64"}.get( + platform.machine() + ) + name = f"magpie-cli-{system}-{machine}" + (".exe" if system == "windows" else "") + info = lock_data()["magpie"]["assets"].get(name) + if not info: + raise ConnectError("No pinned Magpie binary for this platform; build the pinned source") + dest = state_dir() / "bin" / ("magpie.exe" if system == "windows" else "magpie") + if dest.exists() and hashlib.sha256(dest.read_bytes()).hexdigest() == info["sha256"]: + private_write( + dest.parent / "THIRD_PARTY_NOTICES", + Path(__file__).with_name("upstream-notices.txt").read_text(), + ) + return dest + dest.parent.mkdir(parents=True, exist_ok=True, mode=0o700) + fd, temporary = tempfile.mkstemp(dir=dest.parent, prefix=".magpie-") + try: + digest, length = hashlib.sha256(), 0 + with os.fdopen(fd, "wb") as output: + with urllib.request.urlopen(info["url"], timeout=30) as response: + while block := response.read(1024 * 1024): + length += len(block) + if length > info["size"]: + raise ConnectError("Magpie download exceeds pinned size") + digest.update(block) + output.write(block) + if length != info["size"] or digest.hexdigest() != info["sha256"]: + raise ConnectError("Magpie checksum mismatch; download was not installed") + os.chmod(temporary, 0o700) + os.replace(temporary, dest) + private_write( + dest.parent / "THIRD_PARTY_NOTICES", + Path(__file__).with_name("upstream-notices.txt").read_text(), + ) + except (OSError, ValueError): + raise ConnectError("Magpie download failed; retry install-magpie") from None + finally: + if os.path.exists(temporary): + os.unlink(temporary) + return dest + + +def magpie(args: list[str], capture=False, timeout=90, vendor_env_names=()): + env = {**os.environ, "DO_NOT_TRACK": "1", "MAGPIE_NO_STATS": "1"} + for name in vendor_env_names: + env.pop(name, None) + try: + result = subprocess.run( + [magpie_bin(), *args], env=env, capture_output=capture, text=True, timeout=timeout + ) + except subprocess.TimeoutExpired: + raise ConnectError("Magpie command timed out") from None + if result.returncode and capture: + # Magpie can include keys and upstream error bodies; do not copy these to logs. + raise ConnectError("Magpie command failed; inspect Magpie locally for details") + return result + + +def magpie_providers() -> dict: + folder = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "magpie" + path = folder / "providers.json" + if not path.exists(): + return {} + try: + data = json.loads(path.read_text()) + return {p["id"]: p for p in data["providers"]} + except (ValueError, KeyError, TypeError): + raise ConnectError( + "Cannot read Magpie providers.json; refusing to overwrite providers" + ) from None + + +def sync_magpie(config: dict) -> list[str]: + base = gateway_url(config) + hello = json_request("GET", base + "/health", timeout=3) + if hello.get("name") != "iteraconnect": + raise ConnectError("The local port is not an Agent Connect gateway") + existing = magpie_providers() + synced = [] + vendor_env_names = [p["key_env"] for p in config["providers"].values()] + for pid, source in config["providers"].items(): + mid = "iteraconnect-" + pid + root = gateway_url(config, pid) + if old := existing.get(mid): + old_urls = [old.get(k, "") for k in ("chat", "responses", "anthropic", "gemini")] + if not any(u.startswith(root + "/") or u == root for u in old_urls): + raise ConnectError(f"Magpie id {mid} is already used by another provider") + # The only key passed to Magpie is the local relay key. Vendor keys stay in the relay. + pairs = ["name=" + source["name"] + " · Agent Connect", "key=" + gateway_key()] + pairs += ["url=" + (root + "/v1" if "chat" in source["endpoints"] else "")] + pairs += ["responses=" + (root + "/v1" if "responses" in source["endpoints"] else "")] + pairs += ["anthropic=" + (root if "anthropic" in source["endpoints"] else "")] + pairs += ["gemini=" + (root + "/v1beta" if "gemini" in source["endpoints"] else "")] + # This is also an authenticated health check: a different local key must fail sync. + rows = json_request("GET", root + "/v1/models", gateway_key(), timeout=25)["data"] + ids = [r["id"] for r in rows] + if not ids: + raise ConnectError(f"No models discovered for {pid}") + if any("," in model for model in ids): + raise ConnectError("Magpie CLI cannot import a model id containing a comma") + pairs += ["models=" + ",".join(ids), "list=off"] + if old: + magpie( + ["provider", "set", mid, *pairs], capture=True, vendor_env_names=vendor_env_names + ) + else: + magpie( + ["provider", "add", source["name"] + " Agent Connect", "id=" + mid, *pairs], + capture=True, + vendor_env_names=vendor_env_names, + ) + synced.append(mid) + return synced + + +def connect(config: dict, target: str, pid: str, model: str | None = None): + vendor_env_names = [p["key_env"] for p in config["providers"].values()] + # WorkBuddy selects a model per task; its adapter connects a provider/picker, not a default model. + if target in ("workbuddy", "workbuddy-ai"): + magpie([target, "provider", "magpie"], capture=True, vendor_env_names=vendor_env_names) + else: + selected = model or config["providers"][pid]["default_model"] + magpie( + [target, "iteraconnect-" + pid + "/" + selected], + capture=True, + vendor_env_names=vendor_env_names, + ) + + +def cc_link(config: dict, target: str, pid: str, model=None, api_format=None, via="gateway") -> str: + if target not in CC_FORMATS: + raise ConnectError("This client has no CC Switch provider import; use: connect ") + fmt = api_format or CC_FORMATS[target] + protocol = FORMAT_PROTOCOL.get(fmt) + if not protocol: + raise ConnectError("Unsupported CC Switch API format") + if target in ("gemini", "agy") and protocol != "gemini": + raise ConnectError("This CC Switch client only supports gemini_native imports") + if target in ("codex", "grokbuild", "hermes") and protocol == "gemini": + raise ConnectError("This CC Switch client does not support gemini_native imports") + p = config["providers"][pid] + if via == "magpie": + # Magpie converts protocols here when a provider only serves Chat, Messages, etc. + root = os.environ.get("ITERACONNECT_MAGPIE_URL", "http://127.0.0.1:3425").rstrip("/") + key = "magpie-iteraconnect-" + target + selected = "iteraconnect-" + pid + "/" + (model or p["default_model"]) + else: + if protocol not in p["endpoints"]: + raise ConnectError("Provider lacks this native protocol; use --via magpie") + root, key, selected = gateway_url(config, pid), gateway_key(), model or p["default_model"] + suffix = ( + "/v1" + if protocol in ("chat", "responses") or (protocol == "anthropic" and target == "opencode") + else "" + ) + if protocol == "gemini" and target in ("opencode", "openclaw", "pi"): + suffix = "/v1beta" + return "ccswitch://v1/import?" + urlencode( + { + "resource": "provider", + "app": target, + "name": p["name"] + " · Agent Connect", + "endpoint": root + suffix, + "apiKey": key, + "apiFormat": fmt, + "model": selected, + "homepage": "https://github.com/IteraCompute/agent-connect", + "enabled": "false", + } + ) + + +def export_fragment(config: dict, target: str, pid: str, model=None) -> str: + """Standalone fragments for manual merging; never overwrite native config files.""" + root, key = gateway_url(config, pid), gateway_key() + p = config["providers"][pid] + selected = model or p["default_model"] + if target == "codex": + if "responses" not in p["endpoints"]: + raise ConnectError("Codex needs Responses; connect through Magpie for translation") + return ( + f'model = {json.dumps(selected)}\nmodel_provider = "iteraconnect"\n\n' + '[model_providers.iteraconnect]\nname = "IteraCompute Agent Connect"\n' + f'base_url = {json.dumps(root + "/v1")}\nenv_key = "ITERACONNECT_GATEWAY_KEY"\n' + 'wire_api = "responses"\nrequires_openai_auth = false\nsupports_websockets = false\n' + ) + if target == "claude": + if "anthropic" not in p["endpoints"]: + raise ConnectError("Claude Code needs Messages; connect through Magpie for translation") + value = { + "env": { + "ANTHROPIC_BASE_URL": root, + "ANTHROPIC_AUTH_TOKEN": key, + "ANTHROPIC_MODEL": selected, + } + } + elif target in ("workbuddy", "workbuddy-ai"): + if "chat" not in p["endpoints"]: + raise ConnectError("WorkBuddy needs Chat; connect through Magpie for translation") + value = [ + { + "id": selected, + "name": p["name"] + " / " + selected, + "vendor": "iteraconnect", + "apiKey": key, + "url": root + "/v1/chat/completions", + "supportsToolCall": True, + } + ] + elif target == "openclaw": + if "chat" not in p["endpoints"]: + raise ConnectError("This fragment uses Chat; use Magpie for another protocol") + value = { + "models": { + "mode": "merge", + "providers": { + "iteraconnect": { + "baseUrl": root + "/v1", + "apiKey": "${ITERACONNECT_GATEWAY_KEY}", + "api": "openai-completions", + "models": [{"id": selected, "name": selected}], + } + }, + }, + "agents": {"defaults": {"model": {"primary": "iteraconnect/" + selected}}}, + } + elif target == "hermes": + if "chat" not in p["endpoints"]: + raise ConnectError("This fragment uses Chat; use Magpie for another protocol") + # JSON is also valid YAML; Hermes can read this standalone config.yaml fragment. + value = { + "model": {"provider": "iteraconnect", "default": selected}, + "providers": { + "iteraconnect": { + "base_url": root + "/v1", + "api_key": key, + "api_mode": "chat_completions", + } + }, + } + else: + raise ConnectError("Use Magpie's native adapter for this client") + return json.dumps(value, indent=2) + "\n" + + +def write_export(config, target, pid, path, model=None): + if Path(path).exists(): + raise ConnectError("Export output already exists; choose a new file") + private_write(Path(path), export_fragment(config, target, pid, model)) diff --git a/src/iteraconnect/launch.py b/src/iteraconnect/launch.py new file mode 100644 index 0000000..191aefc --- /dev/null +++ b/src/iteraconnect/launch.py @@ -0,0 +1,69 @@ +"""Launch native harnesses with process-local settings, without editing user config.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess + +from .config import ConnectError, api_key, gateway_key, gateway_url + + +def launch_args(config: dict, target: str, pid: str, model=None, via="gateway", args=()): + p = config["providers"][pid] + selected = model or p["default_model"] + protocol = {"claude": "anthropic", "codex": "responses"}.get(target) + if not protocol: + raise ConnectError("run supports claude and codex; use connect for other agents") + env = os.environ.copy() + for provider in config["providers"].values(): + env.pop(provider["key_env"], None) + if via == "magpie": + root = env.get("ITERACONNECT_MAGPIE_URL", "http://127.0.0.1:3425").rstrip("/") + base = root + ("/v1" if protocol == "responses" else "") + key, selected = "magpie-" + target, "iteraconnect-" + pid + "/" + selected + else: + if protocol not in p["endpoints"]: + raise ConnectError("Provider lacks this protocol; use --via magpie") + if via == "direct": + base, key = p["endpoints"][protocol], api_key(p) + else: + base = gateway_url(config, pid) + ("/v1" if protocol == "responses" else "") + key = gateway_key() + if target == "claude": + for name in ( + "ANTHROPIC_API_KEY", + "CLAUDE_CODE_OAUTH_TOKEN", + "CLAUDE_CODE_USE_BEDROCK", + "CLAUDE_CODE_USE_VERTEX", + "CLAUDE_CODE_USE_FOUNDRY", + ): + env.pop(name, None) + env.update(ANTHROPIC_BASE_URL=base, ANTHROPIC_AUTH_TOKEN=key, ANTHROPIC_MODEL=selected) + command = [target, "--model", selected, *args] + else: + env["ITERACONNECT_SESSION_KEY"] = key + overrides = { + "model": selected, + "model_provider": "iteraconnect", + "model_providers.iteraconnect.name": "IteraCompute Agent Connect", + "model_providers.iteraconnect.base_url": base, + "model_providers.iteraconnect.env_key": "ITERACONNECT_SESSION_KEY", + "model_providers.iteraconnect.wire_api": "responses", + "model_providers.iteraconnect.requires_openai_auth": False, + "model_providers.iteraconnect.supports_websockets": False, + } + command = [target] + for name, value in overrides.items(): + command += ["-c", name + "=" + json.dumps(value)] + command += list(args) + # Vendor credentials never appear in argv or generated native config files. + return command, env + + +def launch(config, target, pid, model=None, via="gateway", args=()): + if not shutil.which(target): + raise ConnectError(f"{target} is not installed") + command, env = launch_args(config, target, pid, model, via, args) + return subprocess.run(command, env=env).returncode diff --git a/src/iteraconnect/native.py b/src/iteraconnect/native.py new file mode 100644 index 0000000..691ebc2 --- /dev/null +++ b/src/iteraconnect/native.py @@ -0,0 +1,347 @@ +"""Original, conservative native configuration editors with conflict-aware rollback.""" + +from __future__ import annotations + +import copy +import hashlib +import json +import os +import re +import tomllib +from pathlib import Path + +from .config import ConnectError, gateway_key, gateway_url, private_write, state_dir +from .settings import CLIENTS + + +def client_path(target, home=None): + home = home or Path.home() + folders = { + "claude": ("CLAUDE_CONFIG_DIR", ".claude", "settings.json"), + "codex": ("CODEX_HOME", ".codex", "config.toml"), + "workbuddy": ("WORKBUDDY_CONFIG_DIR", ".workbuddy", "models.json"), + "workbuddy-ai": ("WORKBUDDY_AI_CONFIG_DIR", ".workbuddy-ai", "models.json"), + "openclaw": ("OPENCLAW_STATE_DIR", ".openclaw", "openclaw.json"), + "hermes": ("HERMES_HOME", ".hermes", "config.yaml"), + } + if target not in folders: + raise ConnectError("未知客户端") + env, folder, filename = folders[target] + if target == "openclaw" and os.environ.get("OPENCLAW_CONFIG_PATH"): + return Path(os.environ["OPENCLAW_CONFIG_PATH"]).expanduser().absolute() + return (Path(os.environ[env]).expanduser() if env in os.environ else home / folder) / filename + + +def merge_dict(original, update): + for k, v in update.items(): + if isinstance(v, dict): + if k not in original: + original[k] = {} + if not isinstance(original[k], dict): + raise ConnectError("客户端配置结构不兼容;原文件未修改,请使用手动导出。") + merge_dict(original[k], v) + else: + original[k] = v + return original + + +def unique_object(pairs): + value = {} + for name, item in pairs: + if name in value: + raise ValueError("duplicate JSON field") + value[name] = item + return value + + +def edit_codex(text, root, key, model): + try: + before = tomllib.loads(text) + marker, end = "# BEGIN AGENT CONNECT\n", "# END AGENT CONNECT\n" + if marker in text: + start = text.index(marker) + stop = text.index(end, start) + len(end) + text = text[:start] + text[stop:] + elif "iteraconnect" in before.get("model_providers", {}): + raise ConnectError("Codex 已有同名 iteraconnect 配置,请先重命名或手动处理。") + # Edit only simple root assignments. Parsing and equality checks below guard complex TOML. + for name, value in (("model", model), ("model_provider", "iteraconnect")): + pattern = rf"(?m)^{name}\s*=.*$" + matches = list(re.finditer(pattern, text)) + if name in before: + if not matches or ("[" in text[: matches[0].start()]): + raise ConnectError("Codex 根配置使用复杂 TOML,请使用手动导出。") + text = ( + text[: matches[0].start()] + + name + + " = " + + json.dumps(value) + + text[matches[0].end() :] + ) + else: + text = name + " = " + json.dumps(value) + "\n" + text + text = text.rstrip() + "\n\n" + marker + "[model_providers.iteraconnect]\n" + values = { + "name": "Agent Connect", + "base_url": root + "/v1", + "experimental_bearer_token": key, + "wire_api": "responses", + "requires_openai_auth": False, + "supports_websockets": False, + } + text += "".join(k + " = " + json.dumps(v) + "\n" for k, v in values.items()) + end + after = tomllib.loads(text) + expected = copy.deepcopy(before) + expected["model"], expected["model_provider"] = model, "iteraconnect" + expected.setdefault("model_providers", {})["iteraconnect"] = values + if after != expected: + raise ValueError + return text + except (ValueError, KeyError, TypeError): + raise ConnectError("无法安全修改此 Codex TOML;原文件未修改,请使用手动导出。") from None + + +def yaml_put(text, path, value, remove=False): + """Edit a plain mapping path, preserving all other YAML verbatim; refuse ambiguous syntax.""" + if text and not text.endswith("\n"): + text += "\n" + lines = text.splitlines(keepends=True) + start, stop, indent = 0, len(lines), 0 + for pos, name in enumerate(path): + found = [] + for i in range(start, stop): + line = lines[i] + if "\t" in line[: len(line) - len(line.lstrip())]: + raise ConnectError("Hermes YAML 使用制表符,请使用手动导出。") + if re.match(rf"^ {{{indent}}}{re.escape(name)}\s*:", line): + found.append(i) + # Quoted keys, flow mappings and aliases at the edited level require a full YAML editor. + stripped = line.strip() + if ( + len(line) - len(line.lstrip()) == indent + and stripped + and not stripped.startswith("#") + ): + if stripped.startswith(("{", "[", "&", "*", "<<:", "'" + name, '"' + name)): + raise ConnectError("Hermes YAML 包含复杂映射,请使用手动导出。") + if len(found) > 1: + raise ConnectError("Hermes YAML 含重复配置项;原文件未修改。") + if not found: + if remove: + return text + i = stop + lines[i:i] = [" " * indent + name + ":\n"] + stop += 1 + else: + i = found[0] + finish = i + 1 + while finish < stop: + line = lines[finish] + if ( + line.strip() + and not line.lstrip().startswith("#") + and len(line) - len(line.lstrip()) <= indent + ): + break + finish += 1 + if pos == len(path) - 1: + # Replace a single known field; nested values are deliberately rejected. + if any( + line.strip() and not line.lstrip().startswith("#") for line in lines[i + 1 : finish] + ): + raise ConnectError("Hermes 目标字段不是标量,请使用手动导出。") + if remove: + del lines[i] + else: + lines[i] = " " * indent + name + ": " + json.dumps(value, ensure_ascii=False) + "\n" + else: + rhs = lines[i].split(":", 1)[1].strip() + if rhs and not rhs.startswith("#"): + raise ConnectError("Hermes YAML 目标段使用行内映射,请使用手动导出。") + start, stop, indent = i + 1, finish, indent + 2 + return "".join(lines) + + +def render_native(target, text, config, pid, model): + protocol = CLIENTS[target][1] + if protocol not in config["providers"][pid]["endpoints"]: + raise ConnectError( + f"当前 API 缺少 {protocol} 协议。请选择支持它的 API,或使用高级协议适配。" + ) + root, key = gateway_url(config, pid), gateway_key() + if target == "codex": + return edit_codex(text, root, key, model) + if target == "hermes": + # Stale explicit model routes and key commands can override a newly selected named provider. + removals = [ + ("model", key) + for key in ("base_url", "api", "api_key", "api_mode", "key_env", "api_key_env") + ] + removals += [ + ("providers", "iteraconnect", key) + for key in ("api", "url", "key_env", "key_cmd", "api_mode") + ] + if text.lstrip().startswith("{"): + try: + value = json.loads(text, object_pairs_hook=unique_object) + for path in removals: + parent = value + for part in path[:-1]: + parent = parent.get(part, {}) + parent.pop(path[-1], None) + merge_dict( + value, + { + "model": {"provider": "custom:iteraconnect", "default": model}, + "providers": { + "iteraconnect": { + "base_url": root + "/v1", + "api_key": key, + "transport": "chat_completions", + } + }, + }, + ) + return json.dumps(value, indent=2) + "\n" + except (ValueError, TypeError, AttributeError): + raise ConnectError("无法解析 Hermes JSON 配置;原文件未修改。") from None + if re.search(r"(?m)^(?:---|\.\.\.|%)", text): + raise ConnectError("Hermes YAML 包含文档指令,请使用手动导出。") + for path in removals: + text = yaml_put(text, path, None, remove=True) + for path, value in ( + (["model", "provider"], "custom:iteraconnect"), + (["model", "default"], model), + (["providers", "iteraconnect", "base_url"], root + "/v1"), + (["providers", "iteraconnect", "api_key"], key), + (["providers", "iteraconnect", "transport"], "chat_completions"), + ): + text = yaml_put(text, path, value) + return text + try: + value = ( + json.loads(text, object_pairs_hook=unique_object) + if text.strip() + else ([] if target.startswith("workbuddy") else {}) + ) + if target.startswith("workbuddy"): + models = value.get("models") if isinstance(value, dict) else value + if not isinstance(models, list) or any(not isinstance(x, dict) for x in models): + raise ValueError + models = [x for x in models if x.get("vendor") != "iteraconnect"] + models.append( + { + "id": pid + "/" + model, + "name": "Agent Connect · " + model, + "vendor": "iteraconnect", + "apiKey": key, + "url": gateway_url(config) + "/v1/chat/completions", + "supportsToolCall": True, + } + ) + if isinstance(value, dict): + value["models"] = models + else: + value = models + elif target == "claude": + # Explicitly neutralize competing API-key and cloud-provider settings at this scope. + merge_dict( + value, + { + "model": model, + "env": { + "ANTHROPIC_BASE_URL": root, + "ANTHROPIC_AUTH_TOKEN": key, + "ANTHROPIC_API_KEY": "", + "ANTHROPIC_MODEL": model, + "CLAUDE_CODE_USE_BEDROCK": "0", + "CLAUDE_CODE_USE_VERTEX": "0", + "CLAUDE_CODE_USE_FOUNDRY": "0", + }, + }, + ) + else: + merge_dict( + value, + { + "models": { + "mode": "merge", + "providers": { + "iteraconnect": { + "baseUrl": root + "/v1", + "apiKey": key, + "api": "openai-completions", + "models": [{"id": model, "name": model}], + } + }, + }, + "agents": {"defaults": {"model": {"primary": "iteraconnect/" + model}}}, + }, + ) + # An existing model allowlist also needs the newly selected model. + defaults = value["agents"]["defaults"] + if "models" in defaults: + if not isinstance(defaults["models"], dict): + raise ValueError + defaults["models"].setdefault("iteraconnect/" + model, {}) + return json.dumps(value, indent=2, ensure_ascii=False) + "\n" + except (ValueError, TypeError, AttributeError): + raise ConnectError("客户端配置不是兼容的 JSON;原文件未修改,请使用手动导出。") from None + + +def digest(content): + return hashlib.sha256(content).hexdigest() + + +def connect_native(target, config, pid, model, home=None, backups=None): + path = client_path(target, home).resolve() + backups = backups or state_dir() / "native-backups" + record = backups / (target + ".json") + old = path.read_bytes() if path.exists() else None + try: + text = (old or b"").decode("utf-8") + except UnicodeError: + raise ConnectError("客户端配置不是 UTF-8;原文件未修改。") from None + new = render_native(target, text, config, pid, model).encode() + if record.exists(): + saved = json.loads(record.read_text()) + if saved["path"] != str(path) or saved["applied_sha256"] != digest(old or b""): + raise ConnectError("客户端配置在连接后发生变化。请先手动核对备份,避免覆盖你的修改。") + else: + saved = {"path": str(path), "original": text if old is not None else None} + # Journal before mutation. If interrupted, rollback accepts the known before/after digest. + saved["previous_sha256"] = digest(old or b"") + saved["applied_sha256"] = digest(new) + private_write(record, json.dumps(saved)) + private_write(path, new) + return { + "path": str(path), + "message": "配置已连接。重启客户端后生效;使用期间保持 Agent Connect 运行。" + + ( + " 在 WorkBuddy 的模型选择器中选择 custom-local:" + pid + "/" + model + "。" + if target.startswith("workbuddy") + else "" + ), + } + + +def disconnect_native(target, home=None, backups=None): + path = client_path(target, home).resolve() + record = (backups or state_dir() / "native-backups") / (target + ".json") + if not record.exists(): + raise ConnectError("此客户端没有 Agent Connect 备份。") + saved = json.loads(record.read_text()) + current = path.read_bytes() if path.exists() else b"" + if saved["path"] != str(path) or digest(current) not in ( + saved["applied_sha256"], + saved["previous_sha256"], + ): + raise ConnectError( + "客户端配置已有后续修改;为保护你的设置,停止自动恢复。备份位于 native-backups。" + ) + if saved["original"] is None: + path.unlink(missing_ok=True) + else: + private_write(path, saved["original"]) + record.unlink() + return {"message": "已恢复连接前的配置,请重启客户端。"} diff --git a/src/iteraconnect/network.py b/src/iteraconnect/network.py new file mode 100644 index 0000000..a98844a --- /dev/null +++ b/src/iteraconnect/network.py @@ -0,0 +1,50 @@ +"""HTTP transport with no redirect or credential forwarding to a second host.""" + +from __future__ import annotations + +import http.client +import json +import ssl +from urllib.parse import urlsplit + +from .config import ConnectError + +MAX_JSON = 16 * 1024 * 1024 + + +def request(method: str, url: str, headers: dict, body: bytes | None = None, timeout=180): + p = urlsplit(url) + cls = http.client.HTTPSConnection if p.scheme == "https" else http.client.HTTPConnection + options = {"timeout": timeout} + if p.scheme == "https": + options["context"] = ssl.create_default_context() + conn = cls(p.hostname, p.port, **options) + path = p.path or "/" + if p.query: + path += "?" + p.query + try: + conn.request(method, path, body=body, headers=headers) + return conn, conn.getresponse() + except (OSError, http.client.HTTPException, ValueError): + conn.close() + raise ConnectError("Upstream connection failed or timed out") from None + + +def json_request(method: str, url: str, key: str = "", payload=None, timeout=180): + headers = {"Accept": "application/json", "Content-Type": "application/json"} + if key: + headers["Authorization"] = "Bearer " + key + body = json.dumps(payload).encode() if payload is not None else None + conn, response = request(method, url, headers, body, timeout) + try: + if not 200 <= response.status < 300: + raise ConnectError(f"Endpoint returned HTTP {response.status}") + raw = response.read(MAX_JSON + 1) + if len(raw) > MAX_JSON: + raise ConnectError("JSON response exceeds 16 MiB") + try: + return json.loads(raw) + except (ValueError, UnicodeError): + raise ConnectError("Endpoint returned invalid JSON") from None + finally: + conn.close() diff --git a/src/iteraconnect/settings.py b/src/iteraconnect/settings.py new file mode 100644 index 0000000..61621a0 --- /dev/null +++ b/src/iteraconnect/settings.py @@ -0,0 +1,135 @@ +"""Private, user-facing settings; convert credentials to runtime references only.""" + +from __future__ import annotations + +import copy +import json +import os +import re +import tomllib +from pathlib import Path + +from .config import DEFAULT, ConnectError, private_write, validate, validate_url + +CLIENTS = { + "claude": ("Claude Code", "anthropic"), + "codex": ("Codex", "responses"), + "workbuddy": ("WorkBuddy", "chat"), + "workbuddy-ai": ("WorkBuddy AI", "chat"), + "openclaw": ("OpenClaw", "chat"), + "hermes": ("Hermes", "chat"), +} +APP_DEFAULT = { + "selected_provider": "iteracompute", + "client": "claude", + "providers": { + "iteracompute": { + "name": "IteraCompute", + "api_key": "", + "base_url": "https://api.iteracompute.com", + "model": "openai/gpt-6-luna", + "protocols": ["chat", "responses", "anthropic"], + } + }, +} + + +def check_settings(data): + try: + if set(data) - {"selected_provider", "client", "providers"}: + raise ValueError + if data["client"] not in CLIENTS or data["selected_provider"] not in data["providers"]: + raise ValueError + for pid, p in data["providers"].items(): + if not re.fullmatch(r"[a-z][a-z0-9-]{0,47}", pid): + raise ValueError + if set(p) - {"name", "api_key", "base_url", "model", "protocols", "endpoints"}: + raise ValueError + for field in ("name", "model", "base_url"): + if not isinstance(p[field], str) or not p[field].strip(): + raise ValueError + if not isinstance(p["api_key"], str) or any( + ord(c) < 33 or ord(c) > 126 for c in p["api_key"] + ): + raise ValueError + validate_url(p["base_url"]) + if not isinstance(p["protocols"], list) or not p["protocols"]: + raise ValueError + if set(p["protocols"]) - {"chat", "responses", "anthropic", "gemini"}: + raise ValueError + for protocol, url in p.get("endpoints", {}).items(): + if protocol not in p["protocols"]: + raise ValueError + validate_url(url) + except (KeyError, TypeError, ValueError, AttributeError): + raise ConnectError( + "本地配置格式错误,请参照 config.example.toml;错误内容不会显示密钥。" + ) from None + return data + + +def write_settings(path: Path, data): + check_settings(data) + lines = [ + "# 本地私密配置,请勿分享或提交。只需填写 api_key,保存后在界面点「重新读取」。", + "selected_provider = " + json.dumps(data["selected_provider"]), + "client = " + json.dumps(data["client"]), + ] + for pid, p in data["providers"].items(): + lines += ["", f"[providers.{pid}]"] + for k in ("name", "api_key", "base_url", "model", "protocols"): + lines.append(k + " = " + json.dumps(p[k], ensure_ascii=False)) + if p.get("endpoints"): + lines.append(f"[providers.{pid}.endpoints]") + lines.extend(k + " = " + json.dumps(v) for k, v in p["endpoints"].items()) + private_write(path, "\n".join(lines) + "\n") + + +def read_settings(path: Path): + if not path.exists(): + write_settings(path, copy.deepcopy(APP_DEFAULT)) + try: + data = tomllib.loads(path.read_text(encoding="utf-8")) + if os.name != "nt": + path.chmod(0o600) + return check_settings(data) + except (tomllib.TOMLDecodeError, UnicodeError): + raise ConnectError("无法读取本地 TOML 配置,请检查引号;错误内容不会显示密钥。") from None + + +def runtime_config(data, port=18423): + """The app exclusively uses this private file, never an unrelated inherited vendor key.""" + config = copy.deepcopy(DEFAULT) + config["active_provider"] = data["selected_provider"] + config["gateway"]["port"] = port + config["providers"] = {} + for pid, p in data["providers"].items(): + name = "ITERACONNECT_APP_KEY_" + pid.upper().replace("-", "_") + os.environ[name] = p["api_key"] + base = p["base_url"].rstrip("/") + root = base[:-3] if base.endswith("/v1") else base + endpoints = {} + for protocol in p["protocols"]: + endpoints[protocol] = p.get("endpoints", {}).get(protocol) or ( + base + if protocol in ("chat", "responses") and base.endswith("/v1") + else root + "/v1" + if protocol in ("chat", "responses") + else root + "/v1beta" + if protocol == "gemini" + else root + ) + config["providers"][pid] = { + "name": p["name"], + "key_env": name, + "default_model": p["model"], + "endpoints": endpoints, + } + return validate(config) + + +def public_settings(data): + visible = copy.deepcopy(data) + for p in visible["providers"].values(): + p["has_key"] = bool(p.pop("api_key")) + return visible diff --git a/src/iteraconnect/smoke.py b/src/iteraconnect/smoke.py new file mode 100644 index 0000000..30a063f --- /dev/null +++ b/src/iteraconnect/smoke.py @@ -0,0 +1,275 @@ +"""Run installed clients in a temporary HOME, with no access to saved user logins.""" + +from __future__ import annotations + +import json +import os +import shutil +import subprocess +import tempfile +import time +from pathlib import Path + +from .config import gateway_key, gateway_url +from .diagnostics import PROMPT +from .launch import launch_args + + +def reply_received(target, stdout): + if target == "claude": + return stdout.strip() == "ITERACONNECT_OK" + if target == "hermes": + try: + events = [json.loads(line) for line in stdout.splitlines() if line.strip()] + return any( + isinstance(event, dict) + and event.get("type") == "result" + and event.get("exit_code") == 0 + and not event.get("error") + and event.get("text", "").strip() == "ITERACONNECT_OK" + for event in events + ) + except (ValueError, TypeError, AttributeError): + return False + if target == "codex": + events = [] + try: + events = [json.loads(line) for line in stdout.splitlines() if line.strip()] + except ValueError: + return False + messages = [e.get("item", {}) for e in events if e.get("type") == "item.completed"] + return any(e.get("type") == "turn.completed" for e in events) and any( + m.get("type") == "agent_message" and m.get("text", "").strip() == "ITERACONNECT_OK" + for m in messages + ) + # OpenClaw may print startup notices before its JSON result. Inspect actual reply payloads. + decoder = json.JSONDecoder() + for index, char in enumerate(stdout): + if char != "{": + continue + try: + data, _ = decoder.raw_decode(stdout[index:]) + if not isinstance(data, dict): + continue + data = data.get("result", data) + if isinstance(data, dict) and any( + p.get("text", "").strip() == "ITERACONNECT_OK" for p in data.get("payloads", []) + ): + return True + except (ValueError, TypeError, AttributeError): + continue + return False + + +def sandbox_env(home: Path) -> dict: + env = { + k: v + for k, v in os.environ.items() + if k in ("PATH", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT", "LANG", "LC_ALL", "TERM") + } + env.update( + { + "HOME": str(home), + "USERPROFILE": str(home), + "XDG_CONFIG_HOME": str(home / ".config"), + "XDG_CACHE_HOME": str(home / ".cache"), + "XDG_DATA_HOME": str(home / ".local/share"), + "XDG_STATE_HOME": str(home / ".local/state"), + "APPDATA": str(home / "AppData/Roaming"), + "LOCALAPPDATA": str(home / "AppData/Local"), + "CODEX_HOME": str(home / ".codex"), + "CLAUDE_CONFIG_DIR": str(home / ".claude"), + "HERMES_HOME": str(home / ".hermes"), + "OPENCLAW_STATE_DIR": str(home / ".openclaw"), + "OPENCLAW_CONFIG_PATH": str(home / ".openclaw/openclaw.json"), + "DO_NOT_TRACK": "1", + "DISABLE_TELEMETRY": "1", + "MAGPIE_NO_STATS": "1", + "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1", + "NO_PROXY": "127.0.0.1,localhost", + "CLAUDE_CODE_SIMPLE": "1", + "NO_COLOR": "1", + } + ) + return env + + +def smoke(config, target, pid, model=None, via="gateway", timeout=90, native=False): + if target not in ("claude", "codex", "openclaw", "hermes") or ( + target == "hermes" and via != "gateway" + ): + return { + "kind": "native-client", + "target": target, + "status": "manual-required", + "detail": "Use connect and the documented UI/CLI acceptance steps", + } + if not shutil.which(target): + return {"kind": "native-client", "target": target, "status": "not-installed"} + selected = model or config["providers"][pid]["default_model"] + start = time.monotonic() + with tempfile.TemporaryDirectory(prefix="iteraconnect-smoke-") as directory: + home = Path(directory) + env = sandbox_env(home) + for name in ("CODEX_HOME", "CLAUDE_CONFIG_DIR", "HERMES_HOME", "OPENCLAW_STATE_DIR"): + Path(env[name]).mkdir(parents=True, exist_ok=True) + if target in ("claude", "codex"): + args = ( + [ + "-p", + "--tools", + "", + "--strict-mcp-config", + "--mcp-config", + '{"mcpServers":{}}', + "--setting-sources", + "", + PROMPT, + ] + if target == "claude" + else ["exec", "--skip-git-repo-check", "--sandbox", "read-only", "--json", PROMPT] + ) + command, routed = launch_args(config, target, pid, model, via, args) + names = ( + "ANTHROPIC_BASE_URL", + "ANTHROPIC_AUTH_TOKEN", + "ANTHROPIC_MODEL", + "ITERACONNECT_SESSION_KEY", + ) + env.update({k: routed[k] for k in names if k in routed}) + if native: + from .native import render_native + + folder = Path(env["CLAUDE_CONFIG_DIR" if target == "claude" else "CODEX_HOME"]) + path = folder / ("settings.json" if target == "claude" else "config.toml") + path.write_text(render_native(target, "", config, pid, selected)) + if target == "claude": + args[args.index("--setting-sources") + 1] = "user" + command = [target, *args] + for name in names: + env.pop(name, None) + elif target == "hermes": + from .native import render_native + + seed = { + "platform_toolsets": {"cli": []}, + "agent": {"max_turns": 1}, + "memory": {"memory_enabled": False, "user_profile_enabled": False}, + } + path = Path(env["HERMES_HOME"]) / "config.yaml" + path.write_text(render_native(target, json.dumps(seed), config, pid, selected)) + command = [ + target, + "--ignore-rules", + "chat", + "--quiet", + "--format", + "stream-json", + "--max-turns", + "1", + "-q", + PROMPT, + ] + else: + root, key = gateway_url(config, pid), gateway_key() + api_base = root + "/v1" + if via == "magpie": + root = os.environ.get("ITERACONNECT_MAGPIE_URL", "http://127.0.0.1:3425") + key, selected = "magpie-openclaw", "iteraconnect-" + pid + "/" + selected + api_base = root.rstrip("/") + "/v1" + elif via == "direct": + from .config import api_key + + api_base = config["providers"][pid]["endpoints"]["chat"] + key = api_key(config["providers"][pid]) + data = { + "models": { + "mode": "merge", + "providers": { + "iteraconnect": { + "baseUrl": api_base, + "apiKey": key, + "api": "openai-completions", + "models": [ + { + "id": selected, + "name": selected, + "contextWindow": 32768, + "maxTokens": 256, + } + ], + } + }, + }, + "agents": { + "defaults": { + "workspace": str(home / "workspace"), + "model": {"primary": "iteraconnect/" + selected}, + } + }, + "tools": {"deny": ["*"]}, + } + path = Path(env["OPENCLAW_CONFIG_PATH"]) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(data)) + if native: + from .native import render_native + + path.write_text(render_native(target, path.read_text(), config, pid, selected)) + command = [ + target, + "agent", + "--local", + "--agent", + "main", + "--session-id", + "iteraconnect-smoke", + "--message", + PROMPT, + "--thinking", + "off", + "--timeout", + str(timeout), + "--json", + ] + try: + result = subprocess.run( + command, env=env, cwd=home, capture_output=True, text=True, timeout=timeout + ) + # Never publish arbitrary CLI output: it may contain URLs, credentials or private context. + valid = result.returncode == 0 and reply_received(target, result.stdout) + detail = ( + "expected reply received" + if valid + else f"client exited {result.returncode} or reply missing" + ) + return { + "kind": "native-client", + "target": target, + "via": via, + "status": "passed" if valid else "failed", + "detail": detail, + "seconds": round(time.monotonic() - start, 3), + } + except subprocess.TimeoutExpired: + return { + "kind": "native-client", + "target": target, + "via": via, + "status": "failed", + "detail": "client timed out", + "seconds": round(time.monotonic() - start, 3), + } + finally: + if target == "hermes": + # Hermes one-shot starts a profile gateway. Stop only this temporary profile's gateway. + try: + subprocess.run( + [target, "gateway", "stop"], + env=env, + cwd=home, + capture_output=True, + timeout=15, + ) + except (OSError, subprocess.TimeoutExpired): + pass diff --git a/src/iteraconnect/upstream-notices.txt b/src/iteraconnect/upstream-notices.txt new file mode 100644 index 0000000..6824f66 --- /dev/null +++ b/src/iteraconnect/upstream-notices.txt @@ -0,0 +1,51 @@ +Upstream software notices + +Agent Connect composes these independently maintained MIT projects. + + +cc-switch +MIT License + +Copyright (c) 2025 Jason Young + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + +magpie +MIT License + +Copyright (c) 2026 yetone + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/src/iteraconnect/upstreams.lock.json b/src/iteraconnect/upstreams.lock.json new file mode 100644 index 0000000..1ea5e18 --- /dev/null +++ b/src/iteraconnect/upstreams.lock.json @@ -0,0 +1,49 @@ +{ + "magpie": { + "repository": "https://github.com/yetone/magpie", + "commit": "187d067241d891b0603358537f7ef8909a7599a7", + "version": "v0.1.4314", + "assets": { + "magpie-cli-android-arm64": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-android-arm64", + "sha256": "7cb7b6c9c0bb477d27a6738a9dd60defcf91adffb49b50524c03459507edc4ca", + "size": 91423016 + }, + "magpie-cli-darwin-amd64": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-darwin-amd64", + "sha256": "6b10a255528a1d2d84fd5b83f48e2af919afeec07e47dee0b6f510ad81d4d420", + "size": 93645984 + }, + "magpie-cli-darwin-arm64": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-darwin-arm64", + "sha256": "74c373cf8498dced6e407168c8c5f859fe7a291deecadd474966b777eff56e32", + "size": 86917890 + }, + "magpie-cli-linux-amd64": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-linux-amd64", + "sha256": "b1d88d7afd5e211d8992273e906455c11ea84cac31e764d47af20ac4d0a25339", + "size": 92176546 + }, + "magpie-cli-linux-arm64": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-linux-arm64", + "sha256": "a31311b0540e09470cf2c3a75f794ee42eff6145fe3b4d6c56bc00b9a0dadbdd", + "size": 84803746 + }, + "magpie-cli-windows-amd64.exe": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-windows-amd64.exe", + "sha256": "c017233f9643339ff3d640d86f619765bf33a110d5ccffdf9b44e390cf1d826c", + "size": 93173248 + }, + "magpie-cli-windows-arm64.exe": { + "url": "https://github.com/yetone/magpie-releases/releases/download/v0.1.4314/magpie-cli-windows-arm64.exe", + "sha256": "bd9469f81111cea0dfdd41d6db7417f835e339271c6c9c07132f852835c24ac9", + "size": 85015040 + } + } + }, + "cc-switch": { + "repository": "https://github.com/farion1231/cc-switch", + "commit": "09acca04941a359096bb16ea4fa4073c5e2c46e5", + "license": "MIT" + } +} diff --git a/src/iteraconnect/web/app.css b/src/iteraconnect/web/app.css new file mode 100644 index 0000000..a261be0 --- /dev/null +++ b/src/iteraconnect/web/app.css @@ -0,0 +1,1430 @@ +:root { + font-family: Inter, "PingFang SC", "Microsoft YaHei", system-ui, sans-serif; + font-synthesis: none; + color: #192d28; + background: #f4f7f5; + --green: #1b684d; + --green-dark: #11523c; + --muted: #617267; + --border: #dfe7e2; + --surface: #fff; + --tint: #edf6f0; + --focus: #1b7959; +} +* { + box-sizing: border-box; +} +html { + scroll-padding-top: 24px; +} +body { + margin: 0; + min-width: 320px; +} +button, +input, +select { + font: inherit; +} +button { + cursor: pointer; +} +button:disabled { + cursor: wait; + opacity: 0.55; +} +button:disabled:not(.primary) { + cursor: not-allowed; +} +button:focus-visible, +a:focus-visible, +summary:focus-visible { + outline: 3px solid #71ae8b; + outline-offset: 4px; +} +input:focus, +select:focus { + outline: 0; + border-color: var(--focus); + box-shadow: 0 0 0 3px #e3f1e9; +} +a { + color: inherit; + text-decoration: none; +} +p, +h1, +h2 { + margin: 0; +} +.icon-defs { + position: absolute; + width: 0; + height: 0; + overflow: hidden; +} +.icon { + width: 18px; + height: 18px; + fill: none; + stroke: currentColor; + stroke-width: 1.7; + stroke-linecap: round; + stroke-linejoin: round; + flex-shrink: 0; + vertical-align: middle; +} +.topbar { + border-bottom: 1px solid var(--border); + background: #fff; +} +.topbar-inner { + max-width: 1328px; + margin: 0 auto; + min-height: 68px; + padding: 0 32px; + display: flex; + align-items: center; + gap: 64px; +} +.brand { + display: flex; + align-items: center; + gap: 12px; + font-size: 19px; + font-weight: 650; + letter-spacing: -0.6px; + white-space: nowrap; +} +.brand small { + display: block; + font-size: 10px; + font-weight: 500; + letter-spacing: 0.6px; + margin-top: 3px; + color: #718178; +} +.brand-mark { + display: flex; + align-items: center; + justify-content: center; + gap: 4px; + width: 38px; + height: 38px; + border-radius: 11px; + background: var(--green-dark); + color: #fff; + position: relative; + transform: rotate(-7deg); +} +.brand-mark span { + display: block; + width: 7px; + height: 19px; + border: 2px solid #e3f0dc; + border-radius: 5px; + transform: rotate(32deg); +} +.brand-mark span + span { + transform: rotate(-32deg); +} +.brand-mark i { + width: 5px; + height: 5px; + background: #bed99b; + border-radius: 50%; + position: absolute; + bottom: 6px; + right: 7px; +} +nav { + display: flex; + align-items: center; + align-self: stretch; + gap: 30px; +} +nav a { + display: flex; + align-items: center; + gap: 6px; + font-size: 12px; + color: var(--muted); + border-bottom: 2px solid transparent; +} +nav .icon { + width: 12px; + height: 12px; +} +nav .nav-current { + color: var(--green); + font-weight: 600; + border-bottom-color: var(--green); +} +nav a:hover { + color: var(--green); +} +.service-status { + display: inline-flex; + align-items: center; + gap: 7px; + margin-left: auto; + color: #5a7765; + font-size: 11px; + border: 1px solid #e0eadd; + background: #f6faf4; + padding: 7px 11px; + border-radius: 30px; + white-space: nowrap; +} +.status-dot { + width: 6px; + height: 6px; + border-radius: 50%; + background: #6a9a67; + display: inline-block; + flex-shrink: 0; +} +.service-status.unavailable { + color: #a64a35; + background: #fff1ea; + border-color: #efc8b8; +} +.service-status.unavailable .status-dot { + background: #a64a35; +} +main { + max-width: 1328px; + margin: 0 auto; + padding: 26px 32px; +} +.intro { + display: flex; + justify-content: space-between; + align-items: center; + gap: 28px; + margin-bottom: 24px; +} +.eyebrow { + display: flex; + align-items: center; + gap: 7px; + font-size: 9px; + font-weight: 650; + letter-spacing: 1.9px; + color: #66806e; +} +.eyebrow span { + width: 14px; + height: 3px; + border-radius: 4px; + background: #76a078; +} +h1 { + font-size: clamp(25px, 2.5vw, 34px); + letter-spacing: -1.2px; + font-weight: 600; + line-height: 1.4; + margin-top: 8px; +} +.intro p { + color: var(--muted); + font-size: 13px; + line-height: 1.8; + margin-top: 6px; +} +.local-note { + display: flex; + align-items: center; + gap: 11px; + color: #59745f; +} +.local-note > .icon { + width: 27px; + height: 27px; + stroke-width: 1.3; +} +.local-note strong { + display: block; + font-size: 12px; + font-weight: 550; +} +.local-note span { + display: block; + font-size: 10px; + margin-top: 6px; + color: #7b8d7e; +} +.workspace { + display: grid; + grid-template-columns: minmax(330px, 0.83fr) minmax(520px, 1.3fr); + align-items: start; + gap: 22px; +} +.panel { + background: #fff; + border: 1px solid var(--border); + border-radius: 15px; + box-shadow: 0 3px 10px #20372b03; + padding: 26px; +} +.section-heading { + display: flex; + align-items: center; + gap: 11px; + margin-bottom: 20px; +} +.step { + width: 29px; + height: 29px; + border-radius: 9px; + background: #eff5ec; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 10px; + font-weight: 650; + color: #557755; + flex-shrink: 0; +} +h2 { + font-size: 17px; + letter-spacing: -0.3px; + font-weight: 600; +} +.section-heading p { + font-size: 11px; + color: var(--muted); + margin-top: 6px; +} +.badge { + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 10px; + font-weight: 500; + padding: 4px 8px; + border: 1px solid transparent; + border-radius: 5px; + white-space: nowrap; + line-height: 1.3; +} +.section-heading > .badge { + margin-left: auto; +} +.badge.neutral { + color: #607064; + background: #f5f7f4; + border-color: #edf0e9; +} +.badge.good { + color: #397247; + background: #eef7ea; + border-color: #dcebd6; +} +.badge.changed { + color: #8c6c2e; + background: #fff8e7; + border-color: #f4e7c1; +} +label { + font-size: 12px; + font-weight: 550; + display: block; +} +.field-label { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin: 24px 0 10px; +} +.section-heading + .field-label { + margin-top: 0; +} +.text-button { + border: 0; + background: none; + color: var(--green); + font-size: 11px; + font-weight: 500; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 5px; + padding: 3px 0; + min-height: 25px; +} +.text-button:hover:not(:disabled) { + color: #103d29; + text-decoration: underline; + text-underline-offset: 4px; +} +.text-button .icon { + width: 13px; + height: 13px; +} +input:not([type="checkbox"]), +select { + width: 100%; + border: 1px solid #d6e1d8; + border-radius: 8px; + background: #fff; + padding: 12px 13px; + color: #203f2e; + min-height: 46px; + font-size: 13px; + transition: + border-color 0.15s, + box-shadow 0.15s; +} +select { + cursor: pointer; + appearance: auto; + padding-right: 12px; +} +input::placeholder { + color: #83928a; +} +input[aria-invalid="true"] { + border-color: #ba5a45; + box-shadow: 0 0 0 3px #fff1ea; +} +.field-note { + color: #5a805f; + font-size: 11px; + display: flex; + align-items: center; + gap: 5px; +} +.field-help { + margin-top: 8px; + font-size: 11px; + line-height: 1.7; + color: var(--muted); +} +.field-error { + font-size: 12px; + line-height: 1.7; + color: #a64a35; + margin-top: 7px; +} +.new-provider { + margin-top: 14px; + padding: 16px; + border: 1px solid #dce9e0; + border-radius: 10px; + background: #f7fbf8; +} +.new-provider-title { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + margin-bottom: 16px; +} +.new-provider-title strong { + font-size: 12px; +} +.new-provider-title .text-button { + font-size: 11px; + color: var(--muted); +} +.new-provider > label { + margin: 14px 0 8px; +} +details { + margin-top: 21px; + border-top: 1px solid #e8ede8; + padding-top: 16px; + font-size: 12px; +} +summary { + cursor: pointer; + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + list-style: none; + color: #455f4d; + min-height: 24px; +} +summary::-webkit-details-marker { + display: none; +} +summary > span { + display: inline-flex; + align-items: center; + gap: 5px; +} +summary > span + span { + font-size: 11px; + color: var(--muted); +} +summary .icon { + width: 14px; + height: 14px; + transition: transform 0.15s; +} +details[open] > summary > span > .icon { + transform: rotate(90deg); +} +.advanced-body { + padding-top: 18px; +} +.advanced-body > label { + margin-bottom: 8px; +} +fieldset { + border: 0; + padding: 0; + margin: 20px 0 0; + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px 8px; +} +legend { + font-size: 11px; + color: var(--muted); + padding: 0; + margin-bottom: 13px; +} +fieldset label { + display: flex; + gap: 7px; + align-items: center; + font-weight: 400; + font-size: 11px; + cursor: pointer; +} +input[type="checkbox"] { + accent-color: var(--green); + margin: 0; + width: 14px; + height: 14px; + cursor: pointer; +} +.save-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 15px; + margin-top: 23px; +} +.secondary { + display: inline-flex; + justify-content: center; + align-items: center; + gap: 7px; + padding: 10px 14px; + background: #fff; + border: 1px solid #d5e0d6; + border-radius: 8px; + color: #385e40; + min-height: 39px; + font-size: 12px; + font-weight: 550; + white-space: nowrap; + transition: + background 0.15s, + border-color 0.15s; +} +.secondary:not(:disabled):hover { + background: #f3f8f2; + border-color: #b6cbb7; +} +.secondary .icon { + width: 15px; + height: 15px; +} +.privacy { + font-size: 11px; + color: var(--muted); + line-height: 1.7; + margin-top: 14px; + display: flex; + align-items: flex-start; + gap: 6px; +} +.privacy .icon { + width: 13px; + height: 13px; + margin-top: 2px; + color: #6d9770; +} +.client-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 11px; +} +.client { + display: flex; + position: relative; + align-items: flex-start; + gap: 10px; + min-width: 0; + text-align: left; + padding: 12px; + background: #fff; + border: 1px solid #dfe6df; + border-radius: 11px; + min-height: 84px; + transition: + background 0.16s, + border-color 0.16s, + box-shadow 0.16s; +} +.client:not(:disabled):hover { + background: #f8fbf6; + border-color: #afc9b0; + box-shadow: 0 3px 10px #28643408; +} +.client.selected { + background: #f0f8ee; + border-color: #6e9b6c; + box-shadow: 0 0 0 1px #6e9b6c; +} +.client-icon { + width: 31px; + height: 34px; + border-radius: 9px; + flex-shrink: 0; + display: grid; + place-items: center; + background: #faf0e9; + color: #b77b4f; + font-size: 21px; + font-weight: 550; +} +.client[data-id="codex"] .client-icon { + background: #edf1ed; + color: #324c3b; +} +.client[data-id^="workbuddy"] .client-icon { + background: #edf4fc; + color: #567da7; + font-size: 16px; + font-weight: 700; +} +.client[data-id="openclaw"] .client-icon { + background: #fff0e9; + color: #c47d61; +} +.client[data-id="hermes"] .client-icon { + background: #f2edf9; + color: #9674ad; + font-size: 17px; +} +.client-labels { + min-width: 0; +} +.client-name { + font-size: 12px; + font-weight: 650; + display: block; + color: #334f37; + line-height: 1.4; + margin-top: 1px; + padding-right: 4px; +} +.client-type { + font-size: 10px; + display: block; + color: #596c5c; + line-height: 1.5; + margin-top: 3px; +} +.client-status { + display: flex; + align-items: center; + gap: 4px; + font-size: 10px; + line-height: 1.5; + color: #5d705b; + margin-top: 9px; +} +.client-status:before { + content: ""; + display: block; + width: 4px; + height: 4px; + border-radius: 50%; + background: #aab6a6; + flex-shrink: 0; +} +.client-status.detected:before { + background: #5a9662; +} +.client-check { + position: absolute; + right: 7px; + top: 7px; + border: 1px solid #dce4d9; + border-radius: 50%; + width: 13px; + height: 13px; + display: grid; + place-items: center; + background: #fff; +} +.client-check .icon { + display: none; + width: 9px; + height: 9px; + stroke-width: 2.3; +} +.client.selected .client-check { + background: #45814a; + border-color: #45814a; + color: white; +} +.client.selected .client-check .icon { + display: block; +} +.connection-preview { + background: #f7f9f4; + border: 1px solid #e8eee2; + border-radius: 11px; + margin-top: 16px; + padding: 14px 16px; +} +.preview-label { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + color: #728068; + font-size: 11px; +} +.connection-path { + display: flex; + align-items: center; + gap: 17px; + margin: 12px 0; +} +.path-source, +.path-target { + display: flex; + align-items: center; + gap: 9px; + min-width: 0; +} +.path-source { + flex: 1; +} +.path-source > span + span { + min-width: 0; +} +.provider-mark { + display: grid; + place-items: center; + width: 31px; + height: 32px; + border: 1px solid #dbe8d2; + border-radius: 8px; + flex-shrink: 0; + color: #4d8051; + background: #eef4e5; + font-weight: 650; + font-size: 13px; + letter-spacing: -1px; +} +.path-source strong, +.path-target strong { + display: block; + font-size: 12px; + font-weight: 600; + line-height: 1.5; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} +.path-source small { + display: block; + font-size: 11px; + color: #6e7d64; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + margin-top: 3px; +} +.path-arrow { + color: #91a180; + width: 22px; +} +.mini-client-icon { + font-size: 19px; + color: #6c805a; +} +.path-target { + max-width: 45%; +} +.protocol-line { + display: flex; + align-items: center; + gap: 9px; + border-top: 1px solid #e5ebdd; + padding-top: 12px; + color: #738069; + font-size: 10px; +} +.protocol-line strong { + font-size: 10px; + font-weight: 500; + color: #526849; +} +.match-state { + margin-left: auto; + color: #4c7b49; +} +.match-state.missing { + color: #a26626; +} +.match-state:before { + content: "·"; + margin-right: 4px; +} +.compatibility { + display: flex; + gap: 7px; + align-items: flex-start; + background: #fff6e6; + color: #96662d; + font-size: 11px; + line-height: 1.7; + border: 1px solid #efdfbe; + border-radius: 8px; + padding: 11px; + margin-top: 14px; +} +.compatibility > .icon { + width: 14px; + height: 14px; + margin-top: 3px; +} +.compatibility > span { + flex: 1; +} +.compatibility .text-button { + font-size: 11px; + color: #96662d; + align-self: center; +} +.primary { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 9px; + background: var(--green); + color: white; + border: 1px solid var(--green); + border-radius: 9px; + padding: 13px 18px; + font-size: 14px; + font-weight: 600; + min-height: 48px; + box-shadow: 0 3px 6px #1b684d12; + transition: + background 0.15s, + box-shadow 0.15s; +} +.primary:not(:disabled):hover { + background: var(--green-dark); + box-shadow: 0 5px 12px #1b684d20; +} +.primary:disabled { + opacity: 0.6; +} +.connect-button { + width: 100%; + margin-top: 16px; +} +.connect-button > .icon:last-child { + margin-left: auto; + width: 18px; +} +.connect-button > .icon:first-child { + margin-right: auto; + width: 18px; +} +.connect-help { + font-size: 11px; + line-height: 1.7; + color: var(--muted); + text-align: center; + margin-top: 10px; + min-height: 19px; +} +.client-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + border-top: 1px solid #e8ede5; + margin-top: 21px; + padding-top: 15px; + font-size: 11px; + color: #73806b; +} +.client-footer > span { + display: flex; + align-items: center; + gap: 5px; +} +.client-footer .icon { + width: 13px; + height: 13px; +} +.client-footer > div { + display: flex; + gap: 16px; +} +.client-footer .text-button { + font-size: 11px; +} +.test-panel { + margin-top: 22px; +} +.test-toolbar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 20px; +} +.test-toolbar .section-heading { + margin-bottom: 0; +} +.test-buttons { + display: flex; + gap: 10px; +} +.result-box { + display: flex; + align-items: flex-start; + gap: 11px; + margin-top: 21px; + padding: 16px; + background: #f6f8f3; + border: 1px solid #e3e9dc; + border-radius: 10px; + overflow-wrap: anywhere; +} +.result-symbol { + display: grid; + place-items: center; + width: 29px; + height: 29px; + border-radius: 8px; + background: #eaf0e3; + color: #74866a; + flex-shrink: 0; +} +.result-symbol > .icon { + width: 16px; + height: 16px; +} +.result-box strong { + display: block; + font-size: 12px; + color: #4b6244; + font-weight: 600; + line-height: 1.7; +} +.result-box p { + font-size: 12px; + line-height: 1.8; + color: #6b7d60; + margin-top: 2px; + white-space: pre-wrap; +} +.result-box.success { + border-color: #cfe3c7; + background: #f2f9ed; +} +.result-box.success .result-symbol { + background: #e2f0db; + color: #4e7e41; +} +.result-box.error, +#fatal { + border-color: #efd5c8; + background: #fff5ef; +} +.result-box.error strong, +.result-box.error p { + color: #9a5039; +} +.result-box.error .result-symbol { + background: #fae6da; + color: #a45b40; +} +.result-box.busy .result-symbol .icon { + animation: spin 1s linear infinite; +} +.result-cards { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; + margin-top: 12px; +} +.result-card { + display: flex; + align-items: center; + gap: 8px; + padding: 13px; + border: 1px solid #e0e9d9; + border-radius: 8px; + color: #647c53; + background: #fcfdf9; + min-width: 0; +} +.result-card > .icon { + width: 15px; + height: 15px; +} +.result-card strong { + display: block; + font-weight: 550; + font-size: 11px; +} +.result-card small { + font-size: 10px; + display: block; + color: #7a8970; + margin-top: 4px; +} +.result-card.failed { + color: #a15a3b; + border-color: #efd9cb; + background: #fff9f3; +} +.result-card.manual { + color: #9b7b4c; + background: #fcf9f0; + border-color: #e8ddc8; +} +#result-details { + margin-top: 16px; +} +#result-details summary { + justify-content: flex-start; + font-size: 11px; +} +.detail-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 13px; + min-height: 21px; + font-size: 10px; + color: var(--muted); +} +pre { + margin: 8px 0 0; + padding: 15px; + background: #f5f7f2; + border: 1px solid #e3e8db; + border-radius: 8px; + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; + max-height: 260px; + overflow: auto; + white-space: pre-wrap; + overflow-wrap: anywhere; + font-size: 11px; + line-height: 1.8; + color: #5e7251; +} +.cost { + display: flex; + gap: 7px; + align-items: flex-start; + color: #7b8873; + font-size: 10px; + line-height: 1.8; + margin-top: 16px; +} +.cost > .icon { + width: 13px; + height: 13px; + margin-top: 2px; +} +footer { + display: flex; + align-items: center; + gap: 20px; + flex-wrap: wrap; + color: #74826d; + font-size: 10px; + line-height: 1.8; + margin-top: 22px; +} +footer > span:first-child { + display: flex; + align-items: center; + gap: 6px; +} +footer a { + margin-left: auto; + display: flex; + gap: 5px; + align-items: center; + text-decoration: none; +} +footer a:hover { + color: var(--green); +} +footer .icon { + width: 12px; + height: 12px; +} +#settings-location { + overflow-wrap: anywhere; + max-width: 45%; +} +#fatal { + padding: 15px 18px; + border: 1px solid #efd5c8; + color: #99523c; + border-radius: 10px; + margin-bottom: 20px; + font-size: 13px; + line-height: 1.8; +} +[hidden] { + display: none !important; +} +@keyframes spin { + to { + transform: rotate(360deg); + } +} +@media (min-width: 1450px) { + .topbar-inner { + padding-left: 44px; + padding-right: 44px; + } + main { + padding-top: 46px; + } +} +@media (max-width: 1100px) { + .topbar-inner { + gap: 36px; + padding: 20px 26px; + } + main { + padding: 32px 26px 22px; + } + .workspace { + grid-template-columns: minmax(300px, 0.9fr) minmax(430px, 1.1fr); + gap: 18px; + } + .panel { + padding: 23px; + } + .client-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + } + .client { + min-height: 84px; + padding: 14px 12px; + } + .client-type { + display: none; + } + .client-status { + margin-top: 7px; + } + .intro { + margin-bottom: 26px; + } + .local-note { + display: none; + } + h1 { + font-size: 30px; + } + .client-footer > div { + gap: 11px; + } + .client-footer > span { + font-size: 10px; + } + .section-heading > .badge { + font-size: 9px; + padding: 4px 6px; + } + .section-heading p { + font-size: 11px; + } +} +@media (max-width: 820px) { + .workspace { + grid-template-columns: 1fr; + } + .topbar-inner { + gap: 26px; + } + .topbar nav { + gap: 20px; + } + .topbar nav .nav-current { + display: none; + } + .topbar nav a { + font-size: 12px; + } + .client-grid { + grid-template-columns: repeat(3, minmax(0, 1fr)); + } + .client { + min-height: 92px; + padding: 16px; + } + .client-type { + display: block; + } + .clients-panel .section-heading > .badge { + font-size: 10px; + } + .test-toolbar { + align-items: flex-start; + } + .test-buttons { + flex-direction: column; + gap: 8px; + } + .test-buttons .secondary { + padding: 9px 13px; + } + .test-panel .section-heading p { + font-size: 12px; + line-height: 1.7; + } + footer a { + margin-left: 0; + } + .provider-panel .section-heading > .badge { + font-size: 10px; + } + h1 { + font-size: 29px; + } +} +@media (max-width: 520px) { + .topbar-inner { + padding: 17px 18px; + gap: 12px; + } + .brand { + font-size: 15px; + gap: 9px; + } + .brand-mark { + width: 35px; + height: 35px; + border-radius: 10px; + } + .brand-mark span { + left: 8px; + top: 11px; + } + .brand-mark span + span { + left: 20px; + top: 7px; + } + .brand-mark i { + left: 8px; + top: 5px; + } + .brand small { + font-size: 9px; + } + .topbar nav { + display: none; + } + .service-status { + font-size: 10px; + padding: 7px 9px; + gap: 5px; + } + main { + padding: 27px 16px 20px; + } + .intro { + margin-bottom: 23px; + } + .eyebrow { + font-size: 9px; + letter-spacing: 1.2px; + } + h1 { + font-size: 25px; + letter-spacing: -0.9px; + margin: 13px 0 9px; + } + .intro p { + font-size: 12px; + line-height: 1.9; + } + .panel { + padding: 21px 18px; + border-radius: 14px; + } + .section-heading { + gap: 9px; + margin-bottom: 23px; + } + .section-heading p { + font-size: 11px; + } + h2 { + font-size: 15px; + } + .section-heading > .badge { + font-size: 9px; + padding: 4px 6px; + } + .workspace { + gap: 16px; + } + .client-grid { + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; + } + .client { + padding: 16px 11px; + gap: 9px; + min-height: 95px; + } + .client-icon { + width: 29px; + height: 32px; + } + .client-name { + font-size: 12px; + } + .connection-preview { + margin-top: 19px; + padding: 14px; + } + .connection-path { + gap: 10px; + } + .path-source strong, + .path-target strong { + font-size: 11px; + } + .path-source small { + font-size: 10px; + } + .path-target { + max-width: 42%; + } + .path-arrow { + width: 17px; + } + .provider-mark { + width: 28px; + height: 30px; + } + .mini-client-icon { + font-size: 17px; + } + .protocol-line { + font-size: 9px; + gap: 6px; + } + .protocol-line strong { + font-size: 9px; + } + .client-footer { + flex-wrap: wrap; + row-gap: 13px; + } + .client-footer > div { + margin-left: auto; + gap: 15px; + } + .client-footer > span { + font-size: 10px; + } + .test-panel { + margin-top: 16px; + } + .test-toolbar { + display: block; + } + .test-buttons { + margin-top: 18px; + flex-direction: row; + } + .test-buttons .secondary { + flex: 1; + padding: 10px; + min-height: 42px; + } + .result-box { + margin-top: 17px; + padding: 14px; + gap: 9px; + } + .result-box p { + font-size: 11px; + } + .result-cards { + grid-template-columns: 1fr; + } + .result-card { + padding: 12px; + } + .result-card > div { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + flex: 1; + } + .result-card small { + margin-top: 0; + } + .compatibility { + flex-wrap: wrap; + } + .compatibility > span { + min-width: 150px; + } + .compatibility .text-button { + margin-left: 21px; + } + .cost { + font-size: 10px; + } + footer { + font-size: 10px; + gap: 10px; + margin-top: 19px; + } + footer > span:first-child { + flex-basis: 100%; + } + #settings-location { + max-width: 70%; + } + footer a { + margin-left: auto; + } + .field-label { + margin-top: 23px; + } +} +@media (prefers-reduced-motion: reduce) { + html { + scroll-behavior: auto; + } + *, + *:before, + *:after { + animation: none !important; + transition: none !important; + } +} diff --git a/src/iteraconnect/web/app.js b/src/iteraconnect/web/app.js new file mode 100644 index 0000000..e65380c --- /dev/null +++ b/src/iteraconnect/web/app.js @@ -0,0 +1,598 @@ +"use strict"; +const $ = (id) => document.getElementById(id); +const clientIcons = { + claude: "✳", + codex: "⌘", + workbuddy: "W", + "workbuddy-ai": "W", + openclaw: "◈", + hermes: "H", +}; +const protocols = { + chat: "Chat Completions", + responses: "Responses", + anthropic: "Anthropic Messages", + gemini: "Gemini", +}; +const caseLabels = { + text: "文本回复", + stream: "流式输出", + "tool-roundtrip": "工具调用往返", +}; +const modelCatalogs = new Map(); +let token = sessionStorage.getItem("agent-connect-token") || ""; +if (/^#[A-Za-z0-9_-]{43}$/.test(location.hash)) { + token = location.hash.slice(1); + sessionStorage.setItem("agent-connect-token", token); + history.replaceState(null, "", "/"); +} +let state, + selectedClient, + resultSelection, + adding = false, + working = false; +function icon(name) { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.classList.add("icon"); + svg.setAttribute("aria-hidden", "true"); + const use = document.createElementNS(svg.namespaceURI, "use"); + use.setAttribute("href", "#i-" + name); + svg.append(use); + return svg; +} +function textElement(tag, className, text) { + const el = document.createElement(tag); + el.className = className; + el.textContent = text; + return el; +} +async function api(path, body) { + const options = { headers: { "X-Agent-Connect": token } }; + if (body !== undefined) { + options.method = "POST"; + options.headers["Content-Type"] = "application/json"; + options.body = JSON.stringify(body); + } + let response; + try { + response = await fetch("/api/" + path, options); + } catch { + throw new Error( + "无法连接本地服务。请确认启动窗口仍在运行,再重新打开页面。", + ); + } + const data = await response.json(); + if (!response.ok) throw new Error(data.error || "操作未完成,请重试。"); + return data; +} +function result(title, message, kind = "", data) { + resultSelection = undefined; + $("result").className = "result-box" + (kind ? " " + kind : ""); + $("result-title").textContent = title; + $("result-message").textContent = message; + $("result-symbol").replaceChildren( + icon(kind === "success" ? "check" : kind === "busy" ? "refresh" : "info"), + ); + $("result-cards").replaceChildren(); + $("result-cards").hidden = true; + $("result-details").hidden = !data; + $("result-details").open = false; + $("details-label").textContent = "查看测试详情"; + $("details-note").textContent = "仅显示脱敏结果"; + $("copy-export").hidden = true; + $("copy-export").replaceChildren( + icon("copy"), + document.createTextNode("复制配置"), + ); + $("result-json").textContent = data ? JSON.stringify(data, null, 2) : ""; +} +function updateAvailability() { + document.querySelectorAll("button,input,select").forEach((el) => { + el.disabled = working || !state; + }); + $("workspace").setAttribute("aria-busy", String(working)); + if (!state || working) return; + const client = state.clients.find((c) => c.id === selectedClient); + const matched = selectedProtocols().includes(client.protocol); + ["connect", "probe", "smoke", "export"].forEach((id) => { + $(id).disabled = !matched; + }); + $("disconnect").disabled = !client.connected; + $("provider").disabled = adding; + $("add-provider").disabled = adding; +} +async function busy(message, work) { + if (working) return; + working = true; + updateAvailability(); + result("正在处理", message, "busy"); + let focusId; + try { + await work(); + } catch (e) { + result("操作未完成", e.message, "error"); + focusId = e.focusId; + } finally { + working = false; + updateAvailability(); + if (focusId) $(focusId).focus(); + } +} +function clearErrors() { + ["provider-id", "api-key", "model", "base-url"].forEach((id) => { + $(id).removeAttribute("aria-invalid"); + $(id + "-error").hidden = true; + }); +} +function invalid(id, message) { + $(id).setAttribute("aria-invalid", "true"); + $(id + "-error").textContent = message; + $(id + "-error").hidden = false; + if (id === "base-url") $("advanced").open = true; + const error = new Error(message); + error.focusId = id; + throw error; +} +function selectedProtocols() { + return [...document.querySelectorAll("[name=protocol]:checked")].map( + (el) => el.value, + ); +} +function catalogKey() { + return ( + (adding ? $("provider-id").value.trim() : $("provider").value) + + "|" + + $("base-url").value.trim() + ); +} +function renderCatalog() { + $("model-list").replaceChildren(); + const models = modelCatalogs.get(catalogKey()) || []; + models.forEach((id) => { + const option = document.createElement("option"); + option.value = id; + $("model-list").append(option); + }); + $("model-help").textContent = models.length + ? `已获取 ${models.length} 个模型,点击输入框可选择,也可直接输入。` + : "可直接输入模型 ID,也可从 API 获取列表。"; +} +function loadProvider() { + const p = state.settings.providers[$("provider").value]; + if (!p) return; + adding = false; + clearErrors(); + $("new-fields").hidden = true; + $("provider-id").value = ""; + $("provider-name").value = ""; + $("api-key").value = ""; + $("api-key").placeholder = p.has_key + ? "已保存,留空保留原 key" + : "填写你的 API key"; + $("model").value = p.model; + $("base-url").value = p.base_url; + document.querySelectorAll("[name=protocol]").forEach((el) => { + el.checked = p.protocols.includes(el.value); + }); + renderCatalog(); + updatePath(); +} +function selectionSnapshot() { + return JSON.stringify([ + adding ? $("provider-id").value.trim() : $("provider").value, + selectedClient, + $("model").value.trim(), + $("base-url").value.trim(), + selectedProtocols(), + Boolean($("api-key").value.trim()), + ]); +} +function updatePath() { + if (!state) return; + if (resultSelection && resultSelection !== selectionSnapshot()) { + result("设置已更改", "请重新测试或导出当前 API、模型与客户端的配置。"); + } + const p = state.settings.providers[$("provider").value]; + const client = state.clients.find((c) => c.id === selectedClient); + const currentProtocols = selectedProtocols(); + const matched = currentProtocols.includes(client.protocol); + const keyEntered = Boolean($("api-key").value.trim()); + $("key-status").textContent = keyEntered + ? "待保存" + : !adding && p.has_key + ? "已保存在本机" + : "尚未填写"; + $("path-provider").textContent = adding + ? $("provider-name").value.trim() || "我的 API" + : p.name; + $("path-model").textContent = $("model").value.trim() || "请选择模型"; + $("path-client").textContent = client.name; + $("path-client-icon").textContent = clientIcons[client.id]; + $("connect-label").textContent = "连接 " + client.name; + $("required-protocol").textContent = protocols[client.protocol]; + $("protocol-match").textContent = matched ? "协议匹配" : "需要配置"; + $("protocol-match").classList.toggle("missing", !matched); + $("protocol-summary").textContent = `${currentProtocols.length} 种协议`; + $("compatibility").hidden = matched; + $("compatibility-text").textContent = + `此客户端需要 ${protocols[client.protocol]}。请确认 API 支持后,在地址与协议中勾选。`; + $("connection-status").textContent = client.connected + ? "已配置 · 可恢复" + : "尚未连接"; + $("connection-status").className = + "badge " + (client.connected ? "good" : "neutral"); + $("client-hint").textContent = client.id.startsWith("workbuddy") + ? "连接后重启 WorkBuddy,在任务中选择 custom-local 模型。" + : client.installed + ? "自动备份并写入配置,连接后重启客户端即可使用。" + : "尚未检测到安装。可以先连接配置,再安装客户端。"; + document.querySelectorAll(".client").forEach((el) => { + const selected = el.dataset.id === selectedClient; + el.classList.toggle("selected", selected); + el.setAttribute("aria-checked", String(selected)); + el.tabIndex = selected ? 0 : -1; + }); + const dirty = + adding || + keyEntered || + $("provider").value !== state.settings.selected_provider || + selectedClient !== state.settings.client || + $("model").value.trim() !== p.model || + $("base-url").value.trim() !== p.base_url || + [...currentProtocols].sort().join() !== [...p.protocols].sort().join(); + $("save-state").textContent = dirty ? "有未保存更改" : "已保存到本机"; + $("save-state").className = "badge " + (dirty ? "changed" : "neutral"); + updateAvailability(); +} +function render(next) { + const first = !state; + state = next; + selectedClient = next.settings.client; + $("provider").replaceChildren(); + Object.entries(next.settings.providers).forEach(([id, p]) => { + const option = document.createElement("option"); + option.value = id; + option.textContent = p.name; + $("provider").append(option); + }); + $("provider").value = next.settings.selected_provider; + $("clients").replaceChildren(); + next.clients.forEach((c) => { + const button = document.createElement("button"); + button.className = "client"; + button.dataset.id = c.id; + button.setAttribute("role", "radio"); + button.setAttribute("aria-label", c.name); + const labels = textElement("span", "client-labels", ""); + labels.append( + textElement("span", "client-name", c.name), + textElement( + "span", + "client-type", + c.id === "hermes" || c.id === "openclaw" ? "智能体" : "编码工具", + ), + textElement( + "span", + "client-status" + (c.connected || c.installed ? " detected" : ""), + c.connected + ? "已配置 · 可恢复" + : c.installed + ? "已检测到安装" + : "可配置 · 未检测到", + ), + ); + const mark = textElement("span", "client-check", ""); + mark.append(icon("check")); + const badge = textElement("span", "client-icon", clientIcons[c.id]); + badge.setAttribute("aria-hidden", "true"); + mark.setAttribute("aria-hidden", "true"); + button.append(badge, labels, mark); + button.onclick = () => { + selectedClient = c.id; + updatePath(); + }; + button.onkeydown = (event) => { + const keys = [ + "ArrowLeft", + "ArrowRight", + "ArrowUp", + "ArrowDown", + "Home", + "End", + ]; + if (!keys.includes(event.key)) return; + event.preventDefault(); + const index = next.clients.findIndex( + (item) => item.id === selectedClient, + ); + const at = + event.key === "Home" + ? 0 + : event.key === "End" + ? next.clients.length - 1 + : (index + + (["ArrowLeft", "ArrowUp"].includes(event.key) ? -1 : 1) + + next.clients.length) % + next.clients.length; + selectedClient = next.clients[at].id; + updatePath(); + $("clients").children[at].focus(); + }; + $("clients").append(button); + }); + $("settings-location").textContent = + "本地配置:" + next.settings_path.split(/[\\/]/).pop(); + $("settings-location").title = next.settings_path; + loadProvider(); + if (first && next.settings.providers[next.settings.selected_provider].has_key) + result("已读取本地配置", "选择客户端即可连接,也可以先测试 API。"); +} +function form({ catalog = false, requireKey = false } = {}) { + clearErrors(); + const id = adding ? $("provider-id").value.trim() : $("provider").value; + if (!/^[a-z][a-z0-9-]{0,47}$/.test(id)) + invalid( + "provider-id", + "标识需以小写字母开头,使用小写字母、数字或短横线,最多 48 个字符。", + ); + if (adding && Object.hasOwn(state.settings.providers, id)) + invalid("provider-id", "此标识已存在,请换一个标识。"); + const key = $("api-key").value.trim(); + if (requireKey && !key && (adding || !state.settings.providers[id].has_key)) + invalid("api-key", "请先填写此 API 的 key。"); + if (key && !/^[\x21-\x7e]+$/.test(key)) + invalid("api-key", "API key 不能包含空格或非英文字符,请检查复制内容。"); + const base = $("base-url").value.trim(); + let url; + try { + url = new URL(base); + } catch { + invalid( + "base-url", + "请输入完整 API 地址,例如 https://api.example.com/v1。", + ); + } + if ( + url.username || + url.password || + url.search || + url.hash || + (url.protocol !== "https:" && + !( + url.protocol === "http:" && + ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) + )) + ) + invalid( + "base-url", + "请使用 HTTPS 地址(本机接口可用 HTTP),不要包含账号、查询参数或片段。", + ); + const model = $("model").value.trim(); + if (!catalog && !model) + invalid("model", "请选择或输入模型 ID,也可先点击「获取模型」。"); + if (!selectedProtocols().length) { + $("advanced").open = true; + throw new Error("请至少选择一种 API 实际支持的协议。"); + } + return { + provider: id, + client: selectedClient, + name: adding + ? $("provider-name").value.trim() || id + : state.settings.providers[id].name, + api_key: key, + base_url: base, + model, + protocols: selectedProtocols(), + }; +} +async function save(options) { + render(await api("save", form(options))); +} +function showTest(data, type) { + const passed = type === "probe" ? data.passed : data.status === "passed"; + let message = data.message; + if (!message) + message = + type === "probe" + ? passed + ? "文本回复、完整流式输出和工具调用往返均成功。" + : "部分项目未通过。展开详情查看;遇到 429 可稍后重试,Auto 失败时可选择具体模型。" + : passed + ? "已从实际客户端回复中确认 ITERACONNECT_OK。" + : data.status === "not-installed" + ? "未检测到客户端,请先安装后重试。" + : "客户端实测未通过,请展开详情查看。"; + const manual = + data.status === "manual-required" || data.status === "not-installed"; + result( + passed + ? type === "probe" + ? "API 测试通过" + : "客户端实测通过" + : manual + ? data.status === "not-installed" + ? "尚未检测到客户端" + : "需要在客户端继续操作" + : "测试未全部通过", + message, + passed ? "success" : manual ? "" : "error", + data, + ); + const cases = + type === "probe" + ? data.results || [] + : [{ case: selectedClient, status: data.status, seconds: data.seconds }]; + cases.forEach((item) => { + const ok = item.status === "passed"; + const card = textElement( + "div", + "result-card" + (ok ? "" : manual ? " manual" : " failed"), + "", + ); + const labels = document.createElement("div"); + labels.append( + textElement( + "strong", + "", + type === "probe" + ? caseLabels[item.case] || item.case + : state.clients.find((c) => c.id === selectedClient).name, + ), + textElement( + "small", + "", + (ok + ? "通过" + : item.status === "not-installed" + ? "未检测到安装" + : manual + ? "待手动验证" + : "未通过") + + (typeof item.seconds === "number" + ? ` · ${item.seconds.toFixed(1)} 秒` + : ""), + ), + ); + card.append(icon(ok ? "check" : "info"), labels); + $("result-cards").append(card); + }); + $("result-cards").hidden = cases.length === 0; + resultSelection = selectionSnapshot(); +} +$("provider").onchange = loadProvider; +["provider-name", "model", "api-key", "base-url", "provider-id"].forEach( + (id) => { + $(id).oninput = () => { + clearErrors(); + if (["base-url", "provider-id"].includes(id)) renderCatalog(); + if (id === "api-key") { + modelCatalogs.delete(catalogKey()); + renderCatalog(); + } + updatePath(); + }; + }, +); +document.querySelectorAll("[name=protocol]").forEach((el) => { + el.onchange = updatePath; +}); +$("fix-protocol").onclick = () => { + $("advanced").open = true; + document + .querySelector( + `[name=protocol][value="${state.clients.find((c) => c.id === selectedClient).protocol}"]`, + ) + .focus(); +}; +$("add-provider").onclick = () => { + adding = true; + clearErrors(); + $("new-fields").hidden = false; + $("advanced").open = true; + ["api-key", "provider-id", "provider-name", "base-url", "model"].forEach( + (id) => { + $(id).value = ""; + }, + ); + $("api-key").placeholder = "填写新的 API key"; + document.querySelectorAll("[name=protocol]").forEach((el) => { + el.checked = el.value === "chat"; + }); + renderCatalog(); + updatePath(); + $("provider-id").focus(); +}; +$("cancel-provider").onclick = loadProvider; +$("save").onclick = () => + busy("正在保存本地设置…", async () => { + await save(); + result( + "设置已保存", + "API 设置已保存到本机。选择客户端即可连接。", + "success", + ); + }); +$("reload").onclick = () => + busy("正在重新读取配置文件…", async () => { + render(await api("reload", {})); + result("配置已更新", "已重新读取本地配置文件。", "success"); + }); +$("models").onclick = () => + busy("正在获取当前 API 的模型列表…", async () => { + const draft = form({ catalog: true, requireKey: true }); + const data = await api("models", draft); + modelCatalogs.set(catalogKey(), data.models); + renderCatalog(); + result( + data.models.length ? "模型列表已更新" : "API 未返回模型列表", + data.models.length + ? `已获取 ${data.models.length} 个模型。点击模型输入框选择,或直接输入模型 ID。当前设置尚未自动保存。` + : "仍可在模型输入框中直接填写 API 提供的模型 ID。", + data.models.length ? "success" : "", + ); + }); +$("connect").onclick = () => + busy("正在备份并连接客户端…", async () => { + await save({ requireKey: true }); + const data = await api("connect", {}); + render(await api("state")); + result("客户端已配置", data.message, "success"); + }); +$("disconnect").onclick = () => + busy("正在检查并恢复原配置…", async () => { + await save(); + const data = await api("disconnect", {}); + render(await api("state")); + result("已恢复原配置", data.message, "success"); + }); +$("export").onclick = () => + busy("正在生成配置片段…", async () => { + await save(); + const data = await api("export", {}); + result("配置片段已生成", data.message); + $("result-json").textContent = data.fragment; + $("details-label").textContent = "查看配置片段"; + $("details-note").textContent = "仅含本地网关令牌,请在本机使用"; + $("copy-export").hidden = false; + $("result-details").hidden = false; + $("result-details").open = true; + resultSelection = selectionSnapshot(); + }); +$("copy-export").onclick = async () => { + try { + await navigator.clipboard.writeText($("result-json").textContent); + $("copy-export").replaceChildren( + icon("check"), + document.createTextNode("已复制"), + ); + } catch { + $("details-note").textContent = + "浏览器未允许复制,请选中下方配置手动复制。"; + } +}; +["probe", "smoke"].forEach((type) => { + $(type).onclick = () => + busy( + type === "probe" + ? "正在测试文本、流式与工具调用,请稍候…" + : "正在启动隔离的客户端测试,最长约 90 秒…", + async () => { + await save({ requireKey: true }); + showTest(await api(type, {}), type); + }, + ); +}); +updateAvailability(); +api("state") + .then(render) + .catch((e) => { + $("fatal").hidden = false; + $("fatal").textContent = e.message; + $("service-status").classList.add("unavailable"); + $("service-status").replaceChildren( + textElement("span", "status-dot", ""), + document.createTextNode("本地服务未连接"), + ); + result("无法读取配置", e.message, "error"); + }); diff --git a/src/iteraconnect/web/index.html b/src/iteraconnect/web/index.html new file mode 100644 index 0000000..6f633a1 --- /dev/null +++ b/src/iteraconnect/web/index.html @@ -0,0 +1,373 @@ + + + + + + + Agent Connect · IteraCompute + + + + +
+ +
+
+
+
+
YOUR MODELS. YOUR TOOLS.
+

把模型,接入你的工作流。

+

选择 API 和客户端,让你熟悉的工具用上你需要的模型。

+
+
+ +
+ 你的密钥,留在本机本地运行 · 随时切换 · 可恢复配置 +
+
+
+ +
+
+
+ 01 +
+

配置你的 API

+

选择服务商与模型

+
+ 本地配置 +
+
+ +
+ + +
+ +
+ +

+ 密钥只保存到本机,留空可保留已保存的 key。 +

+ +
+ +
+ + +

+ 可直接输入模型 ID,也可从 API 获取列表。 +

+ +
+ + 地址与协议高级设置 + +
+ + +
+ API 实际支持的协议 + +
+

+ 只选择服务实际支持的协议。不同协议的独立路径可在本地配置文件中设置。 +

+
+
+
+ +
+

+ 连接或测试时会自动保存当前设置。 +

+
+
+
+ 02 +
+

选择你的客户端

+

编码工具或智能体,都可以接入

+
+ 6 个客户端 +
+
+
+
+ 本次连接尚未连接 +
+
+
+ IteraCompute选择模型 +
+ +
+ Claude Code +
+
+
+ 接入协议Anthropic Messages等待配置 +
+
+ + +

+ 自动备份原配置,连接后重启客户端即可使用。 +

+ +
+
+
+
+
+ 03 +
+

确认连接可用

+

先检查 API,再验证客户端的真实回复

+
+
+
+ +
+
+
+ +
+ 准备就绪 +

填写 API key,选择客户端,即可开始连接。

+
+
+ + +

+ 测试会使用当前 API + key,可能产生少量费用。API 测试最多 4 + 次请求;客户端实测可能发起多次请求。 +

+
+ +
+ + + diff --git a/start.py b/start.py new file mode 100644 index 0000000..1ec6ff0 --- /dev/null +++ b/start.py @@ -0,0 +1,15 @@ +#!/usr/bin/env python3 +"""Start the local client directly from a checkout. No pip install required.""" + +import sys +from pathlib import Path + +if sys.version_info < (3, 11): + raise SystemExit("Agent Connect requires Python 3.11 or newer.") + +ROOT = Path(__file__).resolve().parent +sys.path.insert(0, str(ROOT / "src")) + +from iteraconnect.cli import main # noqa: E402 + +raise SystemExit(main(["app", "--settings", str(ROOT / "agent-connect.local.toml"), *sys.argv[1:]])) diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/fixtures.py b/tests/fixtures.py new file mode 100644 index 0000000..434a097 --- /dev/null +++ b/tests/fixtures.py @@ -0,0 +1,338 @@ +"""Deterministic vendor fixture. Never contacts a real model service.""" + +import copy +import json +import os +import threading +from contextlib import contextmanager +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from unittest.mock import patch + +from iteraconnect.config import DEFAULT +from iteraconnect.gateway import Gateway + +LOCAL_KEY = "fixture-local-key-with-at-least-24-characters" +VENDOR_KEY = "fixture-vendor-credential" +MODEL = "fixture-model" +TEXT = "ITERACONNECT_OK" + + +def chat_object(tool=False): + message = {"role": "assistant", "content": TEXT} + if tool: + message = { + "role": "assistant", + "content": None, + "tool_calls": [ + { + "id": "call_fixture", + "type": "function", + "function": {"name": "echo_code", "arguments": json.dumps({"code": TEXT})}, + } + ], + } + return { + "id": "chatcmpl-fixture", + "object": "chat.completion", + "created": 1700000000, + "model": MODEL, + "choices": [ + {"index": 0, "message": message, "finish_reason": "tool_calls" if tool else "stop"} + ], + "usage": {"prompt_tokens": 12, "completion_tokens": 4, "total_tokens": 16}, + } + + +def response_object(tool=False, status="completed"): + item = { + "id": "msg_fixture", + "type": "message", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": TEXT, "annotations": []}], + } + if tool: + item = { + "id": "fc_fixture", + "type": "function_call", + "call_id": "call_fixture", + "name": "echo_code", + "arguments": json.dumps({"code": TEXT}), + "status": "completed", + } + return { + "id": "resp_fixture", + "object": "response", + "created_at": 1700000000, + "status": status, + "model": MODEL, + "output": [item], + "error": None, + "usage": { + "input_tokens": 12, + "output_tokens": 4, + "total_tokens": 16, + "input_tokens_details": {"cached_tokens": 0}, + "output_tokens_details": {"reasoning_tokens": 0}, + }, + } + + +def message_object(tool=False): + return { + "id": "msg_fixture", + "type": "message", + "role": "assistant", + "model": MODEL, + "content": ( + [ + { + "type": "tool_use", + "id": "call_fixture", + "name": "echo_code", + "input": {"code": TEXT}, + } + ] + if tool + else [{"type": "text", "text": TEXT}] + ), + "stop_reason": "tool_use" if tool else "end_turn", + "stop_sequence": None, + "usage": {"input_tokens": 12, "output_tokens": 4}, + } + + +def stream_frames(protocol): + if protocol == "chat": + common = { + "id": "chatcmpl-fixture", + "object": "chat.completion.chunk", + "created": 1700000000, + "model": MODEL, + } + return [ + { + **common, + "choices": [ + { + "index": 0, + "delta": {"role": "assistant", "content": ""}, + "finish_reason": None, + } + ], + }, + { + **common, + "choices": [{"index": 0, "delta": {"content": TEXT}, "finish_reason": None}], + }, + { + **common, + "choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}], + "usage": {"prompt_tokens": 12, "completion_tokens": 4, "total_tokens": 16}, + }, + "[DONE]", + ] + if protocol == "anthropic": + initial = message_object() + initial.update(content=[], stop_reason=None, usage={"input_tokens": 12, "output_tokens": 0}) + return [ + {"type": "message_start", "message": initial}, + { + "type": "content_block_start", + "index": 0, + "content_block": {"type": "text", "text": ""}, + }, + { + "type": "content_block_delta", + "index": 0, + "delta": {"type": "text_delta", "text": TEXT}, + }, + {"type": "content_block_stop", "index": 0}, + { + "type": "message_delta", + "delta": {"stop_reason": "end_turn", "stop_sequence": None}, + "usage": {"output_tokens": 4}, + }, + {"type": "message_stop"}, + ] + result = response_object() + initial = {**result, "output": [], "status": "in_progress", "usage": None} + item = result["output"][0] + part = item["content"][0] + frames = [ + {"type": "response.created", "response": initial}, + {"type": "response.in_progress", "response": initial}, + { + "type": "response.output_item.added", + "output_index": 0, + "item": {**item, "status": "in_progress", "content": []}, + }, + { + "type": "response.content_part.added", + "output_index": 0, + "item_id": item["id"], + "content_index": 0, + "part": {**part, "text": ""}, + }, + { + "type": "response.output_text.delta", + "output_index": 0, + "item_id": item["id"], + "content_index": 0, + "delta": TEXT, + }, + { + "type": "response.output_text.done", + "output_index": 0, + "item_id": item["id"], + "content_index": 0, + "text": TEXT, + }, + { + "type": "response.content_part.done", + "output_index": 0, + "item_id": item["id"], + "content_index": 0, + "part": part, + }, + {"type": "response.output_item.done", "output_index": 0, "item": item}, + {"type": "response.completed", "response": result}, + ] + return [{**event, "sequence_number": i} for i, event in enumerate(frames)] + + +class VendorHandler(BaseHTTPRequestHandler): + def log_message(self, *_): + pass + + def reply(self, status, value): + data = json.dumps(value).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + self.server.requests.append(("GET", self.path, dict(self.headers), None)) + self.reply( + 200, + {"object": "list", "data": [{"id": MODEL, "object": "model", "owned_by": "fixture"}]}, + ) + + def do_POST(self): + body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", "0")))) + choice = body.get("tool_choice") + tool = ( + isinstance(choice, dict) + and (choice.get("name") or choice.get("function", {}).get("name")) == "echo_code" + ) + self.server.requests.append(("POST", self.path, dict(self.headers), body)) + if self.server.status != 200: + self.reply( + self.server.status, {"error": {"message": VENDOR_KEY + " private upstream detail"}} + ) + return + route = self.path.split("?", 1)[0] + if route.endswith("count_tokens"): + self.reply(200, {"input_tokens": 12}) + return + protocol = ( + "chat" + if route.endswith("chat/completions") + else "responses" + if route.endswith("responses") + else "anthropic" + ) + if self.server.chat_only and protocol != "chat": + self.reply(404, {"error": "fixture only speaks Chat"}) + return + if body.get("stream"): + self.send_response(200) + self.send_header("Content-Type", "text/event-stream") + self.end_headers() + frames = stream_frames(protocol) + if protocol == "chat" and tool: + common = { + "id": "chatcmpl-fixture", + "object": "chat.completion.chunk", + "created": 1700000000, + "model": MODEL, + } + frames = [ + { + **common, + "choices": [ + { + "index": 0, + "delta": { + "role": "assistant", + "tool_calls": [ + { + "index": 0, + "id": "call_fixture", + "type": "function", + "function": { + "name": "echo_code", + "arguments": json.dumps({"code": TEXT}), + }, + } + ], + }, + "finish_reason": None, + } + ], + }, + { + **common, + "choices": [{"index": 0, "delta": {}, "finish_reason": "tool_calls"}], + "usage": {"prompt_tokens": 12, "completion_tokens": 4, "total_tokens": 16}, + }, + "[DONE]", + ] + if self.server.truncated: + frames = frames[:-1] + for frame in frames: + data = frame if isinstance(frame, str) else json.dumps(frame) + event = ( + ("event: " + frame["type"] + "\n") + if protocol != "chat" and isinstance(frame, dict) + else "" + ) + self.wfile.write((event + "data: " + data + "\n\n").encode()) + self.wfile.flush() + return + value = {"chat": chat_object, "responses": response_object, "anthropic": message_object}[ + protocol + ](tool) + self.reply(200, value) + + +@contextmanager +def stack(chat_only=False): + vendor = ThreadingHTTPServer(("127.0.0.1", 0), VendorHandler) + vendor.requests, vendor.status, vendor.truncated, vendor.chat_only = [], 200, False, chat_only + upstream = f"http://127.0.0.1:{vendor.server_port}" + config = copy.deepcopy(DEFAULT) + config["providers"]["iteracompute"].update(key_env="FIXTURE_VENDOR_KEY", default_model=MODEL) + config["providers"]["iteracompute"]["endpoints"] = {"chat": upstream + "/v1"} + if not chat_only: + config["providers"]["iteracompute"]["endpoints"].update( + responses=upstream + "/v1", anthropic=upstream + ) + gateway = Gateway(config, LOCAL_KEY, ("127.0.0.1", 0)) + config["gateway"]["port"] = gateway.server_port + threads = [threading.Thread(target=s.serve_forever, daemon=True) for s in (vendor, gateway)] + for thread in threads: + thread.start() + with patch.dict( + os.environ, {"FIXTURE_VENDOR_KEY": VENDOR_KEY, "ITERACONNECT_GATEWAY_KEY": LOCAL_KEY} + ): + try: + yield config, vendor, gateway + finally: + for s in (vendor, gateway): + s.shutdown() + s.server_close() + for t in threads: + t.join(timeout=2) diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..205f57b --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,380 @@ +"""Exercise the simple entry point with fixture credentials and a local vendor only.""" + +import copy +import http.client +import json +import os +import stat +import tempfile +import threading +import tomllib +import unittest +from pathlib import Path +from unittest.mock import patch + +from iteraconnect.app import App +from iteraconnect.config import DEFAULT, ConnectError +from iteraconnect.native import client_path, connect_native, disconnect_native, render_native +from iteraconnect.settings import ( + APP_DEFAULT, + public_settings, + read_settings, + runtime_config, + write_settings, +) +from iteraconnect.smoke import smoke + +from .fixtures import LOCAL_KEY, MODEL, VENDOR_KEY, stack + + +class PrivateSettingsTests(unittest.TestCase): + def test_editable_toml_roundtrip_private_and_redacted(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "settings.toml" + data = read_settings(path) + data["providers"]["iteracompute"]["api_key"] = VENDOR_KEY + write_settings(path, data) + self.assertEqual(read_settings(path), data) + self.assertNotIn(VENDOR_KEY, json.dumps(public_settings(data))) + self.assertTrue(public_settings(data)["providers"]["iteracompute"]["has_key"]) + if os.name != "nt": + self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) + + def test_explicit_file_key_does_not_fall_back_to_inherited_key(self): + with patch.dict(os.environ, {"ITERACOMPUTE_API_KEY": "unrelated-existing-key"}): + data = copy.deepcopy(APP_DEFAULT) + runtime = runtime_config(data) + self.assertEqual(os.environ[runtime["providers"]["iteracompute"]["key_env"]], "") + data["providers"]["iteracompute"]["api_key"] = VENDOR_KEY + runtime = runtime_config(data) + self.assertEqual( + os.environ[runtime["providers"]["iteracompute"]["key_env"]], VENDOR_KEY + ) + self.assertNotIn(VENDOR_KEY, json.dumps(runtime)) + + def test_nonstandard_protocol_paths_survive_roundtrip(self): + data = copy.deepcopy(APP_DEFAULT) + p = data["providers"]["iteracompute"] + p["base_url"] = "https://example.test/openai/v1" + p["endpoints"] = {"anthropic": "https://example.test/anthropic"} + with patch.dict(os.environ): + runtime = runtime_config(data) + self.assertEqual(runtime["providers"]["iteracompute"]["endpoints"]["chat"], p["base_url"]) + self.assertEqual( + runtime["providers"]["iteracompute"]["endpoints"]["anthropic"], + p["endpoints"]["anthropic"], + ) + + def test_malformed_file_never_discloses_input(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "settings.toml" + path.write_text('api_key = "' + VENDOR_KEY) + with self.assertRaises(ConnectError) as error: + read_settings(path) + self.assertNotIn(VENDOR_KEY, str(error.exception)) + + +class NativeEditorTests(unittest.TestCase): + def setUp(self): + self.env = patch.dict(os.environ, {"ITERACONNECT_GATEWAY_KEY": LOCAL_KEY}, clear=True) + self.env.start() + self.addCleanup(self.env.stop) + + def test_all_adapters_preserve_settings_reconnect_and_restore_exactly(self): + seeds = { + "claude": '{"theme":"dark","env":{"KEEP":"yes"}}\n', + "codex": '# a comment\nmodel = "old"\n[history]\npersistence = "none"\n', + "workbuddy": '[{"id":"mine","vendor":"mine","enabled":false}]\n', + "workbuddy-ai": '[{"id":"mine","vendor":"mine","enabled":false}]\n', + "openclaw": '{"messages":{"responsePrefix":"keep"},"agents":{"defaults":{"models":{"mine/old":{}}}}}\n', + "hermes": "# my config\nmodel:\n provider: openrouter\n default: old\nui:\n theme: dark", + } + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + for target, original in seeds.items(): + with self.subTest(target=target): + path = client_path(target, home) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(original) + connect_native(target, DEFAULT, "iteracompute", MODEL, home, home / "backups") + first = path.read_text() + self.assertNotIn(VENDOR_KEY, first) + self.assertIn(LOCAL_KEY, first) + connect_native( + target, DEFAULT, "iteracompute", MODEL + "-new", home, home / "backups" + ) + self.assertIn(MODEL + "-new", path.read_text()) + if target == "codex": + self.assertEqual(tomllib.loads(first)["history"]["persistence"], "none") + self.assertIn("# a comment", first) + if target == "hermes": + self.assertIn("ui:\n theme: dark", first) + self.assertIn("# my config", first) + if target.startswith("workbuddy"): + rows = json.loads(first) + self.assertFalse(rows[0]["enabled"]) + self.assertEqual(rows[1]["id"], "iteracompute/" + MODEL) + if target == "openclaw": + self.assertIn( + "iteraconnect/" + MODEL, + json.loads(first)["agents"]["defaults"]["models"], + ) + disconnect_native(target, home, home / "backups") + self.assertEqual(path.read_text(), original) + + def test_restoring_a_new_file_removes_it_and_later_edits_are_protected(self): + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + backups = home / "backups" + path = client_path("claude", home) + connect_native("claude", DEFAULT, "iteracompute", MODEL, home, backups) + disconnect_native("claude", home, backups) + self.assertFalse(path.exists()) + connect_native("claude", DEFAULT, "iteracompute", MODEL, home, backups) + path.write_text(path.read_text() + "\n") + with self.assertRaises(ConnectError): + disconnect_native("claude", home, backups) + with self.assertRaises(ConnectError): + connect_native("claude", DEFAULT, "iteracompute", MODEL, home, backups) + + def test_ambiguous_client_config_is_never_overwritten(self): + for target, text in ( + ("hermes", "model: {provider: old}\n"), + ("hermes", '"model":\n provider: old\n'), + ("openclaw", '{ // JSON5\n "key":true\n}'), + ("codex", '[model_providers.iteraconnect]\nname="another app"\n'), + ): + with self.subTest(target=target), self.assertRaises(ConnectError): + render_native(target, text, DEFAULT, "iteracompute", MODEL) + + def test_workbuddy_object_and_duplicate_json_fields(self): + text = ( + '{"models":[{"id":"mine","vendor":"mine"}],"availableModels":["mine"],"theme":"dark"}' + ) + data = json.loads(render_native("workbuddy", text, DEFAULT, "iteracompute", MODEL)) + self.assertEqual(data["availableModels"], ["mine"]) + self.assertEqual(data["theme"], "dark") + self.assertEqual(len(data["models"]), 2) + with self.assertRaises(ConnectError): + render_native( + "claude", '{"env":{},"env":{"KEEP":"yes"}}', DEFAULT, "iteracompute", MODEL + ) + + def test_hermes_stale_endpoint_and_key_command_cannot_override_selection(self): + values = ( + 'model:\n provider: custom\n base_url: "https://oldvendor.example/v1"\n api_key: old-key\n key_env: OLD_KEY\nproviders:\n iteraconnect:\n key_cmd: old-helper\n api: "https://oldvendor.example/v1"\nui:\n theme: dark\n', + json.dumps( + { + "model": { + "provider": "custom", + "base_url": "https://oldvendor.example/v1", + "api_key": "old-key", + "key_env": "OLD_KEY", + }, + "providers": { + "iteraconnect": { + "key_cmd": "old-helper", + "api": "https://oldvendor.example/v1", + } + }, + "ui": {"theme": "dark"}, + } + ), + ) + for value in values: + result = render_native("hermes", value, DEFAULT, "iteracompute", MODEL) + self.assertNotIn("oldvendor.example", result) + self.assertNotIn("old-key", result) + self.assertNotIn("old-helper", result) + self.assertIn("dark", result) + self.assertIn(LOCAL_KEY, result) + + @unittest.skipIf(os.name == "nt", "Windows symlink privilege varies") + def test_symlinked_client_config_is_kept_as_a_symlink(self): + with tempfile.TemporaryDirectory() as directory: + home = Path(directory) + original = '{"theme":"dark"}\n' + real = home / "dotfiles" / "claude.json" + real.parent.mkdir() + real.write_text(original) + path = client_path("claude", home) + path.parent.mkdir() + path.symlink_to(real) + connect_native("claude", DEFAULT, "iteracompute", MODEL, home, home / "backups") + self.assertTrue(path.is_symlink()) + self.assertIn(LOCAL_KEY, real.read_text()) + disconnect_native("claude", home, home / "backups") + self.assertEqual(real.read_text(), original) + + +class ControlPanelTests(unittest.TestCase): + def setUp(self): + self.folder = tempfile.TemporaryDirectory() + self.addCleanup(self.folder.cleanup) + self.env = patch.dict( + os.environ, + {"ITERACONNECT_HOME": self.folder.name, "ITERACONNECT_GATEWAY_KEY": LOCAL_KEY}, + ) + self.env.start() + self.addCleanup(self.env.stop) + self.app = App(Path(self.folder.name) / "settings.toml", port=0, relay_port=0) + self.addCleanup(self.app.server_close) + self.addCleanup(self.app.relay.server_close) + self.worker = threading.Thread(target=self.app.serve_forever, daemon=True) + self.worker.start() + self.addCleanup(self.app.shutdown) + + def call(self, path, body=None, headers=None, auth=True): + conn = http.client.HTTPConnection("127.0.0.1", self.app.server_port, timeout=10) + request_headers = {"Content-Type": "application/json"} + if auth: + request_headers["X-Agent-Connect"] = self.app.token + request_headers.update(headers or {}) + conn.request( + "POST" if body is not None else "GET", + path, + json.dumps(body) if body is not None else None, + request_headers, + ) + response = conn.getresponse() + raw = response.read() + status = response.status + conn.close() + return status, raw + + def test_api_auth_origin_host_and_static_assets(self): + self.assertEqual(self.call("/api/state", auth=False)[0], 401) + self.assertEqual( + self.call("/api/state", headers={"Origin": "https://evil.example"})[0], 403 + ) + self.assertEqual(self.call("/api/state", headers={"Host": "evil.example"})[0], 403) + for path in ("/", "/app.css", "/app.js"): + self.assertEqual(self.call(path, auth=False)[0], 200) + self.assertEqual(self.call("/../../settings.toml")[0], 404) + + def test_save_redacts_key_reload_and_empty_key_blocks_inference(self): + self.assertEqual(self.call("/api/probe", {})[0], 400) + body = {"provider": "iteracompute", "client": "codex", "api_key": VENDOR_KEY} + status, raw = self.call("/api/save", body) + self.assertEqual(status, 200) + self.assertNotIn(VENDOR_KEY.encode(), raw) + self.assertTrue(json.loads(raw)["settings"]["providers"]["iteracompute"]["has_key"]) + self.assertEqual(self.call("/api/save", {**body, "api_key": ""})[0], 200) + self.assertEqual( + read_settings(self.app.settings_path)["providers"]["iteracompute"]["api_key"], + VENDOR_KEY, + ) + self.assertNotIn(VENDOR_KEY.encode(), self.call("/api/reload", {})[1]) + + def test_simple_ui_protocol_probe_against_fixture_vendor(self): + # stack() supplies only a localhost vendor; no real API service is reachable in this test. + with stack() as (fixture_config, vendor, gateway): + provider = copy.deepcopy(APP_DEFAULT["providers"]["iteracompute"]) + provider.update( + api_key=VENDOR_KEY, + model=MODEL, + base_url=fixture_config["providers"]["iteracompute"]["endpoints"]["anthropic"], + ) + data = copy.deepcopy(APP_DEFAULT) + data["providers"]["iteracompute"] = provider + self.app.activate(data) + worker = threading.Thread(target=self.app.relay.serve_forever, daemon=True) + worker.start() + try: + status, raw = self.call("/api/probe", {}) + self.assertEqual(status, 200, raw) + self.assertTrue(json.loads(raw)["passed"], raw) + self.assertNotIn(VENDOR_KEY.encode(), raw) + finally: + self.app.relay.shutdown() + worker.join(timeout=3) + + def test_model_discovery_works_before_saving_a_custom_provider_or_model(self): + original = self.app.settings_path.read_bytes() + active = copy.deepcopy(self.app.config) + active_key_env = active["providers"]["iteracompute"]["key_env"] + original_key = os.environ[active_key_env] + before_env = dict(os.environ) + with stack() as (config, vendor, gateway): + status, raw = self.call( + "/api/models", + { + "provider": "my-api", + "name": "My API", + "client": "codex", + "base_url": config["providers"]["iteracompute"]["endpoints"]["chat"], + "protocols": ["chat", "responses"], + "api_key": VENDOR_KEY, + "model": "", + }, + ) + self.assertEqual(status, 200, raw) + self.assertIn(MODEL, json.loads(raw)["models"]) + self.assertNotIn(VENDOR_KEY.encode(), raw) + self.assertEqual(self.app.settings_path.read_bytes(), original) + self.assertEqual(self.app.config, active) + self.assertEqual(os.environ[active_key_env], original_key) + self.assertFalse(set(os.environ) - set(before_env)) + self.assertNotIn("my-api", self.app.data["providers"]) + + def test_failed_draft_discovery_cleans_up_and_preserves_the_saved_key(self): + self.app.data["providers"]["iteracompute"]["api_key"] = VENDOR_KEY + original = self.app.settings_path.read_bytes() + before_env = dict(os.environ) + with patch("iteraconnect.app.provider_models", side_effect=ConnectError("目录暂不可用")): + status, raw = self.call( + "/api/models", {"provider": "iteracompute", "api_key": "draft-only-key"} + ) + self.assertEqual(status, 400) + self.assertNotIn(b"draft-only-key", raw) + self.assertEqual(self.app.settings_path.read_bytes(), original) + self.assertEqual(self.app.data["providers"]["iteracompute"]["api_key"], VENDOR_KEY) + self.assertEqual(dict(os.environ), before_env) + + def test_external_key_file_edits_are_not_overwritten_by_stale_ui(self): + data = read_settings(self.app.settings_path) + data["providers"]["iteracompute"]["api_key"] = VENDOR_KEY + write_settings(self.app.settings_path, data) + status, raw = self.call("/api/save", {"provider": "iteracompute", "client": "claude"}) + self.assertEqual(status, 400) + self.assertNotIn(VENDOR_KEY.encode(), raw) + self.assertEqual(read_settings(self.app.settings_path), data) + self.assertEqual(self.call("/api/reload", {})[0], 200) + self.assertEqual( + self.call("/api/save", {"provider": "iteracompute", "client": "codex"})[0], 200 + ) + + def test_connect_and_restore_via_ui_api_without_touching_user_config(self): + path = Path(self.folder.name) / "client" / "settings.json" + path.parent.mkdir() + original = '{"theme":"dark"}\n' + path.write_text(original) + self.assertEqual( + self.call( + "/api/save", {"provider": "iteracompute", "client": "claude", "api_key": VENDOR_KEY} + )[0], + 200, + ) + with patch("iteraconnect.native.client_path", return_value=path): + status, raw = self.call("/api/connect", {}) + self.assertEqual(status, 200, raw) + self.assertIn(LOCAL_KEY, path.read_text()) + self.assertNotIn(VENDOR_KEY, path.read_text()) + self.assertEqual(self.call("/api/disconnect", {})[0], 200) + self.assertEqual(path.read_text(), original) + + +@unittest.skipUnless( + os.environ.get("ITERACONNECT_TEST_NATIVE") == "1", "opt-in installed CLI tests" +) +class NativeSettingsClientTests(unittest.TestCase): + def test_installed_clients_read_the_new_native_configuration(self): + import shutil + + with stack() as (config, vendor, gateway): + for target in ("claude", "codex", "openclaw", "hermes"): + if not shutil.which(target): + continue + with self.subTest(target=target): + result = smoke(config, target, "iteracompute", native=True) + self.assertEqual(result["status"], "passed", result) diff --git a/tests/test_core.py b/tests/test_core.py new file mode 100644 index 0000000..781f40c --- /dev/null +++ b/tests/test_core.py @@ -0,0 +1,182 @@ +import copy +import json +import os +import stat +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch +from urllib.parse import parse_qs, urlsplit + +from iteraconnect.cli import main +from iteraconnect.config import ( + DEFAULT, + ConnectError, + gateway_key, + load, + save, + validate, + validate_url, +) +from iteraconnect.integrations import cc_link, export_fragment, write_export +from iteraconnect.launch import launch_args + +from .fixtures import LOCAL_KEY, MODEL, VENDOR_KEY + + +class ConfigTests(unittest.TestCase): + def test_defaults_and_isolation(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "absent" + a = load(path) + a["providers"].clear() + self.assertIn("iteracompute", load(path)["providers"]) + self.assertEqual(load(path)["active_provider"], "iteracompute") + + def test_save_is_private_and_never_contains_key(self): + with ( + tempfile.TemporaryDirectory() as d, + patch.dict(os.environ, {"ITERACOMPUTE_API_KEY": VENDOR_KEY}), + ): + path = Path(d) / "config.json" + save(copy.deepcopy(DEFAULT), path) + self.assertNotIn(VENDOR_KEY, path.read_text()) + self.assertEqual(load(path), DEFAULT) + if os.name != "nt": + self.assertEqual(stat.S_IMODE(path.stat().st_mode), 0o600) + + def test_keys_are_created_once(self): + with tempfile.TemporaryDirectory() as d, patch.dict(os.environ, {"ITERACONNECT_HOME": d}): + with patch.dict(os.environ): + os.environ.pop("ITERACONNECT_GATEWAY_KEY", None) + self.assertEqual(gateway_key(), gateway_key()) + + def test_bad_url_rejected(self): + for url in ( + "ftp://host", + "https://user:secret@host", + "https://host?key=a", + "https://host/#x", + "https://a/\nb", + ): + with self.subTest(url=url), self.assertRaises(ConnectError): + validate_url(url) + + def test_lan_plain_http_requires_opt_in(self): + with self.assertRaises(ConnectError): + validate_url("http://192.168.1.1/v1") + self.assertEqual(validate_url("http://192.168.1.1/v1", True), "http://192.168.1.1/v1") + validate_url("http://127.0.0.1:1234/v1") + + def test_inline_credential_and_public_bind_rejected(self): + for mutate in ( + lambda d: d["providers"]["iteracompute"].update(api_key="bad"), + lambda d: d["gateway"].update(host="0.0.0.0"), + ): + value = copy.deepcopy(DEFAULT) + mutate(value) + with self.assertRaises(ConnectError): + validate(value) + + def test_malformed_config_error_is_safe(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "config.json" + path.write_text('{"secret":"' + VENDOR_KEY) + with self.assertRaises(ConnectError) as e: + load(path) + self.assertNotIn(VENDOR_KEY, str(e.exception)) + + +class IntegrationTests(unittest.TestCase): + def setUp(self): + self.env = patch.dict( + os.environ, {"ITERACONNECT_GATEWAY_KEY": LOCAL_KEY, "ITERACOMPUTE_API_KEY": VENDOR_KEY} + ) + self.env.start() + self.addCleanup(self.env.stop) + + def test_cc_link_is_per_app_and_has_no_vendor_key(self): + for target, fmt, suffix in ( + ("claude", "anthropic", ""), + ("codex", "openai_responses", "/v1"), + ("hermes", "openai_chat", "/v1"), + ("openclaw", "openai_chat", "/v1"), + ): + link = cc_link(DEFAULT, target, "iteracompute", MODEL) + q = parse_qs(urlsplit(link).query) + self.assertEqual(q["apiFormat"], [fmt]) + self.assertTrue(q["endpoint"][0].endswith("/p/iteracompute" + suffix)) + self.assertEqual(q["enabled"], ["false"]) + self.assertNotIn(VENDOR_KEY, link) + + def test_unsupported_cc_app_fails(self): + with self.assertRaises(ConnectError): + cc_link(DEFAULT, "workbuddy", "iteracompute") + + def test_chat_only_requires_magpie_for_codex(self): + config = copy.deepcopy(DEFAULT) + config["providers"]["iteracompute"]["endpoints"] = {"chat": "https://example.test/v1"} + with self.assertRaises(ConnectError): + cc_link(config, "codex", "iteracompute") + q = parse_qs(urlsplit(cc_link(config, "codex", "iteracompute", via="magpie")).query) + self.assertEqual(q["model"], ["iteraconnect-iteracompute/Auto"]) + + def test_native_exports_and_no_overwrite(self): + for target in ("claude", "codex", "workbuddy", "workbuddy-ai", "openclaw", "hermes"): + self.assertNotIn(VENDOR_KEY, export_fragment(DEFAULT, target, "iteracompute")) + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "fragment.json" + write_export(DEFAULT, "claude", "iteracompute", path) + with self.assertRaises(ConnectError): + write_export(DEFAULT, "claude", "iteracompute", path) + + def test_native_launch_keys_only_in_environment(self): + for target in ("claude", "codex"): + command, env = launch_args(DEFAULT, target, "iteracompute", via="direct") + self.assertNotIn(VENDOR_KEY, json.dumps(command)) + self.assertIn(VENDOR_KEY, env.values()) + if target == "codex": + self.assertIn('model_providers.iteraconnect.wire_api="responses"', command) + + def test_managed_harnesses_do_not_inherit_vendor_credentials(self): + for target in ("claude", "codex"): + _, env = launch_args(DEFAULT, target, "iteracompute", via="gateway") + self.assertNotIn("ITERACOMPUTE_API_KEY", env) + self.assertNotIn(VENDOR_KEY, env.values()) + + def test_cc_import_formats_follow_native_client_contracts(self): + for target, fmt in ( + ("gemini", "anthropic"), + ("agy", "openai_chat"), + ("hermes", "gemini_native"), + ): + with self.assertRaises(ConnectError): + cc_link(DEFAULT, target, "iteracompute", api_format=fmt, via="magpie") + link = cc_link(DEFAULT, "gemini", "iteracompute", via="magpie") + self.assertEqual(parse_qs(urlsplit(link).query)["endpoint"], ["http://127.0.0.1:3425"]) + link = cc_link(DEFAULT, "opencode", "iteracompute", api_format="anthropic") + self.assertTrue(parse_qs(urlsplit(link).query)["endpoint"][0].endswith("/v1")) + + def test_cli_custom_provider_preserves_default(self): + with tempfile.TemporaryDirectory() as d: + path = Path(d) / "config.json" + self.assertEqual( + main( + [ + "--config", + str(path), + "provider", + "add", + "other", + "--key-env", + "OTHER_KEY", + "--model", + MODEL, + "--chat", + "https://example.test/v1", + ] + ), + 0, + ) + self.assertIn("iteracompute", load(path)["providers"]) + self.assertEqual(load(path)["providers"]["other"]["key_env"], "OTHER_KEY") diff --git a/tests/test_gateway.py b/tests/test_gateway.py new file mode 100644 index 0000000..58eabee --- /dev/null +++ b/tests/test_gateway.py @@ -0,0 +1,154 @@ +import copy +import http.client +import json +import unittest + +from iteraconnect.config import ConnectError +from iteraconnect.diagnostics import probe, stream_check + +from .fixtures import LOCAL_KEY, MODEL, VENDOR_KEY, stack + + +def call(port, path, payload=None, key=LOCAL_KEY, extra=None): + conn = http.client.HTTPConnection("127.0.0.1", port, timeout=10) + headers = {"Authorization": "Bearer " + key, "Content-Type": "application/json"} + headers.update(extra or {}) + conn.request( + "POST" if payload is not None else "GET", + path, + json.dumps(payload) if payload is not None else None, + headers, + ) + response = conn.getresponse() + value = response.read() + conn.close() + return response.status, value + + +class GatewayTests(unittest.TestCase): + def test_all_native_contracts_and_tool_roundtrips(self): + with stack() as (config, vendor, _): + report = probe(config, "iteracompute", MODEL) + self.assertTrue(report["passed"], report) + self.assertEqual(len(report["results"]), 9) + for method, _, headers, body in vendor.requests: + self.assertNotIn(LOCAL_KEY, json.dumps(headers)) + if method == "POST": + self.assertEqual(body["model"], MODEL) + + def test_unauthenticated_and_browser_requests_never_reach_upstream(self): + with stack() as (_, vendor, gateway): + self.assertEqual(call(gateway.server_port, "/v1/models", key="wrong")[0], 401) + self.assertEqual( + call(gateway.server_port, "/v1/models", extra={"Origin": "https://evil.test"})[0], + 403, + ) + self.assertEqual(vendor.requests, []) + + def test_error_and_redirect_are_sanitized(self): + with stack() as (_, vendor, gateway): + for status in (401, 429, 500, 302, 307): + vendor.status = status + actual, body = call( + gateway.server_port, "/v1/responses", {"model": MODEL, "input": "hi"} + ) + self.assertEqual(actual, status if status >= 400 else 502) + self.assertNotIn(VENDOR_KEY.encode(), body) + self.assertNotIn(b"private upstream", body) + self.assertEqual(len(vendor.requests), 5) # no retry and no redirected POST + + def test_missing_model_bad_body_unknown_paths(self): + with stack() as (_, vendor, gateway): + for path, payload, status in ( + ("/v1/responses", {}, 400), + ("/v1/responses", [], 400), + ("/admin/keys", {"model": MODEL}, 404), + ("/v1/responses?key=bad", {"model": MODEL}, 400), + ("/p/missing/v1/responses", {"model": MODEL}, 400), + ): + self.assertEqual(call(gateway.server_port, path, payload)[0], status) + self.assertEqual(vendor.requests, []) + + def test_named_provider_routes_and_native_model_slashes(self): + with stack() as (config, vendor, gateway): + config["providers"]["other"] = copy.deepcopy(config["providers"]["iteracompute"]) + for path, model, expected in ( + ("/v1/responses", "other/namespace/model", "namespace/model"), + ("/p/other/v1/responses", "namespace/model", "namespace/model"), + ): + self.assertEqual( + call(gateway.server_port, path, {"model": model, "input": "hi"})[0], 200 + ) + self.assertEqual(vendor.requests[-1][3]["model"], expected) + + def test_unsupported_protocol_is_explicit(self): + with stack(chat_only=True) as (_, vendor, gateway): + status, _ = call(gateway.server_port, "/v1/messages", {"model": MODEL, "messages": []}) + self.assertEqual(status, 501) + self.assertEqual(vendor.requests, []) + + def test_native_transport_queries_and_gemini_model_paths(self): + with stack() as (config, vendor, gateway): + config["providers"]["iteracompute"]["endpoints"]["gemini"] = ( + f"http://127.0.0.1:{vendor.server_port}/v1beta" + ) + status, _ = call( + gateway.server_port, + "/p/iteracompute/v1/messages?beta=true", + {"model": MODEL, "messages": []}, + ) + self.assertEqual(status, 200) + self.assertEqual(vendor.requests[-1][1], "/v1/messages?beta=true") + status, _ = call( + gateway.server_port, + "/v1beta/models/iteracompute%2Fnamespace%2Fmodel:streamGenerateContent?alt=sse", + {"contents": []}, + ) + self.assertEqual(status, 200) + self.assertEqual( + vendor.requests[-1][1], + "/v1beta/models/namespace/model:streamGenerateContent?alt=sse", + ) + self.assertEqual(vendor.requests[-1][2]["x-goog-api-key"], VENDOR_KEY) + + def test_catalog_prefixes_and_preserves_per_provider_model_id(self): + with stack() as (_, _, gateway): + status, body = call(gateway.server_port, "/v1/models") + self.assertEqual(status, 200) + self.assertEqual(json.loads(body)["data"][0]["id"], "iteracompute/" + MODEL) + _, body = call(gateway.server_port, "/p/iteracompute/v1/models") + self.assertEqual(json.loads(body)["data"][0]["id"], MODEL) + + def test_sse_truncation_is_not_a_success(self): + with stack() as (config, vendor, _): + vendor.truncated = True + result = probe(config, "iteracompute", MODEL, tools=False) + streams = [r for r in result["results"] if r["case"] == "stream"] + self.assertTrue(all(r["status"] == "failed" for r in streams)) + + def test_stream_error_is_detected(self): + for raw in ( + b'data: {"type":"error","error":{"message":"failed"}}\n\n', + b"data: {broken}\n\n", + ): + with self.assertRaises(ConnectError): + stream_check("responses", raw) + + def test_arbitrary_headers_not_forwarded_and_beta_is_preserved(self): + with stack() as (_, vendor, gateway): + status, _ = call( + gateway.server_port, + "/v1/messages", + {"model": MODEL, "messages": []}, + extra={ + "Cookie": "secret-cookie", + "X-Secret": "private", + "anthropic-beta": "fixture-beta", + }, + ) + self.assertEqual(status, 200) + headers = {k.lower(): v for k, v in vendor.requests[-1][2].items()} + self.assertNotIn("cookie", headers) + self.assertNotIn("x-secret", headers) + self.assertEqual(headers["anthropic-beta"], "fixture-beta") + self.assertEqual(headers["x-api-key"], VENDOR_KEY) diff --git a/tests/test_installer.py b/tests/test_installer.py new file mode 100644 index 0000000..5ab05a5 --- /dev/null +++ b/tests/test_installer.py @@ -0,0 +1,54 @@ +import hashlib +import io +import os +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from iteraconnect.config import ConnectError +from iteraconnect.integrations import install_magpie + + +class InstallerTests(unittest.TestCase): + def attempt(self, home, received, expected=b"verified fixture executable"): + lock = { + "magpie": { + "assets": { + "magpie-cli-linux-amd64": { + "url": "https://example.test/fixture", + "size": len(expected), + "sha256": hashlib.sha256(expected).hexdigest(), + } + } + } + } + with ( + patch.dict(os.environ, {"ITERACONNECT_HOME": home}), + patch("iteraconnect.integrations.platform.system", return_value="Linux"), + patch("iteraconnect.integrations.platform.machine", return_value="x86_64"), + patch("iteraconnect.integrations.lock_data", return_value=lock), + patch( + "iteraconnect.integrations.urllib.request.urlopen", + return_value=io.BytesIO(received), + ), + ): + return install_magpie() + + def test_verified_bytes_are_installed_with_notices(self): + with tempfile.TemporaryDirectory() as home: + expected = b"verified fixture executable" + path = self.attempt(home, expected) + self.assertEqual(path.read_bytes(), expected) + self.assertIn("MIT License", (path.parent / "THIRD_PARTY_NOTICES").read_text()) + + def test_checksum_or_size_mismatch_preserves_existing_binary(self): + for received in (b"bad executable", b"x" * 100): + with self.subTest(received=received), tempfile.TemporaryDirectory() as home: + path = Path(home) / "bin/magpie" + path.parent.mkdir() + path.write_bytes(b"previous binary") + with self.assertRaises(ConnectError): + self.attempt(home, received) + self.assertEqual(path.read_bytes(), b"previous binary") + self.assertEqual(list(path.parent.glob(".magpie-*")), []) diff --git a/tests/test_magpie.py b/tests/test_magpie.py new file mode 100644 index 0000000..49789ae --- /dev/null +++ b/tests/test_magpie.py @@ -0,0 +1,160 @@ +"""Opt-in tests with the actual pinned Magpie executable, under an isolated HOME.""" + +import json +import os +import socket +import subprocess +import tempfile +import time +import unittest +from contextlib import ExitStack +from pathlib import Path +from unittest.mock import patch + +from iteraconnect.diagnostics import probe +from iteraconnect.integrations import connect, magpie, magpie_providers, sync_magpie +from iteraconnect.network import json_request +from iteraconnect.smoke import sandbox_env, smoke + +from .fixtures import LOCAL_KEY, MODEL, VENDOR_KEY, stack + + +@unittest.skipUnless( + os.environ.get("ITERACONNECT_TEST_MAGPIE_BIN"), + "set ITERACONNECT_TEST_MAGPIE_BIN for real Magpie tests", +) +class MagpieTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.resources = ExitStack() + cls.addClassCleanup(cls.resources.close) + binary = os.environ["ITERACONNECT_TEST_MAGPIE_BIN"] + cls.home = Path( + cls.resources.enter_context( + tempfile.TemporaryDirectory(prefix="iteraconnect-magpie-test-") + ) + ) + cls.config, cls.vendor, _ = cls.resources.enter_context(stack(chat_only=True)) + sock = socket.socket() + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + sock.close() + env = { + **sandbox_env(cls.home), + "ITERACONNECT_HOME": str(cls.home / "connector"), + "ITERACONNECT_GATEWAY_KEY": LOCAL_KEY, + "ITERACONNECT_MAGPIE_BIN": binary, + "FIXTURE_VENDOR_KEY": VENDOR_KEY, + "MAGPIE_ADDR": f"127.0.0.1:{port}", + "ITERACONNECT_MAGPIE_URL": f"http://127.0.0.1:{port}", + } + cls.resources.enter_context(patch.dict(os.environ, env, clear=True)) + # Seed native config files so detection and preservation are both exercised. + seeds = { + ".claude/settings.json": json.dumps( + {"model": "own-claude", "env": {"KEEP_ME": "yes"}, "theme": "dark"} + ), + ".codex/config.toml": '# keep comment\nmodel = "own-codex"\n[history]\npersistence = "none"\n', + ".workbuddy/models.json": json.dumps( + [{"id": "own-model", "name": "Mine", "vendor": "mine"}] + ), + ".openclaw/openclaw.json": json.dumps( + { + "agents": {"defaults": {"model": {"primary": "mine/old"}}}, + "messages": {"responsePrefix": "keep"}, + } + ), + ".hermes/config.yaml": "model:\n provider: openrouter\n default: own-hermes\nui:\n theme: dark\n", + } + for name, content in seeds.items(): + path = cls.home / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(content) + sync_magpie(cls.config) + cls.log = cls.resources.enter_context(open(cls.home / "magpie.log", "w+")) + cls.process = subprocess.Popen([binary, "serve"], env=env, stdout=cls.log, stderr=cls.log) + cls.resources.callback(cls.stop) + for _ in range(80): + try: + json_request( + "GET", env["ITERACONNECT_MAGPIE_URL"] + "/v1/models", "magpie-test", timeout=1 + ) + break + except Exception: + if cls.process.poll() is not None: + raise AssertionError("Magpie failed to start in sandbox") + time.sleep(0.1) + else: + raise AssertionError("Magpie did not become ready") + + @classmethod + def stop(cls): + cls.process.terminate() + try: + cls.process.wait(timeout=5) + except subprocess.TimeoutExpired: + cls.process.kill() + cls.process.wait() + + def test_chat_only_source_translates_all_three_protocols(self): + result = probe( + self.config, + "iteracompute", + MODEL, + via="magpie", + protocols=["chat", "responses", "anthropic"], + ) + self.assertTrue(result["passed"], result) + self.assertTrue( + all( + path.endswith("/chat/completions") + for method, path, _, _ in self.vendor.requests + if method == "POST" + ) + ) + + def test_sync_is_idempotent_and_vendor_key_never_reaches_magpie(self): + sync_magpie(self.config) + providers = magpie_providers() + self.assertEqual(list(providers), ["iteraconnect-iteracompute"]) + self.assertEqual(providers["iteraconnect-iteracompute"]["key"], LOCAL_KEY) + self.assertNotIn(VENDOR_KEY, json.dumps(providers)) + + def test_connect_disconnect_five_native_configs(self): + for target, filename, original in ( + ("claude", ".claude/settings.json", "own-claude"), + ("codex", ".codex/config.toml", "own-codex"), + ("workbuddy", ".workbuddy/models.json", "own-model"), + ("openclaw", ".openclaw/openclaw.json", "mine/old"), + ("hermes", ".hermes/config.yaml", "own-hermes"), + ): + with self.subTest(target=target): + connect(self.config, target, "iteracompute", MODEL) + text = (self.home / filename).read_text() + self.assertIn("magpie", text) + self.assertNotIn(VENDOR_KEY, text) + magpie([target, "default"], capture=True) + text = (self.home / filename).read_text() + self.assertIn(original, text) + if target == "claude": + self.assertIn("KEEP_ME", text) + if target == "codex": + self.assertIn("keep comment", text) + if target == "hermes": + self.assertIn("theme: dark", text) + + +@unittest.skipUnless( + os.environ.get("ITERACONNECT_TEST_NATIVE"), "opt-in actual installed native CLI tests" +) +class NativeClientTests(unittest.TestCase): + def test_installed_clients_against_fixture(self): + with stack() as (config, _, _): + results = [ + smoke(config, target, "iteracompute", MODEL, timeout=45) + for target in ("claude", "codex", "openclaw") + ] + self.assertTrue( + all(r["status"] in ("passed", "not-installed") for r in results), results + ) + print(json.dumps({"backend": "local-fixture", "native_clients": results})) diff --git a/tests/test_smoke.py b/tests/test_smoke.py new file mode 100644 index 0000000..122eb08 --- /dev/null +++ b/tests/test_smoke.py @@ -0,0 +1,61 @@ +import json +import unittest + +from iteraconnect.smoke import reply_received + + +class SmokeEvidenceTests(unittest.TestCase): + def test_echoed_prompt_or_error_is_not_client_success(self): + for target in ("claude", "codex", "openclaw", "hermes"): + self.assertFalse(reply_received(target, 'Asked: "Reply with exactly ITERACONNECT_OK".')) + self.assertFalse( + reply_received( + "openclaw", + json.dumps({"payloads": [{"text": "Failed"}], "debug": "ITERACONNECT_OK"}), + ) + ) + self.assertFalse( + reply_received( + "codex", + json.dumps( + { + "type": "item.completed", + "item": {"type": "agent_message", "text": "ITERACONNECT_OK"}, + } + ), + ) + ) + + def test_success_requires_actual_completed_reply(self): + self.assertTrue( + reply_received( + "hermes", json.dumps({"type": "result", "exit_code": 0, "text": "ITERACONNECT_OK"}) + ) + ) + self.assertFalse( + reply_received( + "hermes", json.dumps({"type": "result", "exit_code": 1, "text": "ITERACONNECT_OK"}) + ) + ) + self.assertFalse( + reply_received("hermes", json.dumps({"type": "text", "text": "ITERACONNECT_OK"})) + ) + self.assertTrue(reply_received("claude", "ITERACONNECT_OK\n")) + self.assertTrue( + reply_received("openclaw", json.dumps({"payloads": [{"text": "ITERACONNECT_OK"}]})) + ) + self.assertTrue( + reply_received( + "codex", + "\n".join( + json.dumps(e) + for e in [ + { + "type": "item.completed", + "item": {"type": "agent_message", "text": "ITERACONNECT_OK"}, + }, + {"type": "turn.completed", "usage": {}}, + ] + ), + ) + )