Compare commits

..

No commits in common. "359f083bc2924b483fa632bcae44b6debab52a22" and "fb4dcc5683bc17cb713c1ddf0e396cf6046c157b" have entirely different histories.

24 changed files with 623 additions and 3903 deletions

View file

@ -8,7 +8,7 @@
SHELL := /bin/bash
.PHONY: help context doctor test test-rust test-vm opencode-acceptance fmt fmt-check clippy check build static vm hooks commit publish backup forgejo-init public private protect release clean
.PHONY: help context doctor test test-rust test-vm fmt fmt-check clippy check build static vm hooks commit publish backup forgejo-init public private protect release clean
help:
@printf 'Phoebus OS targets:\n'
@ -17,7 +17,6 @@ help:
@printf ' make test run the Rust and VM-harness test suites\n'
@printf ' make test-rust cargo test --workspace\n'
@printf ' make test-vm python3 installer/tests/vm/test_vmsafety.py\n'
@printf ' make opencode-acceptance live-model acceptance (needs PHOEBUS_OPENCODE_LIVE_*)\n'
@printf ' make fmt cargo fmt --all\n'
@printf ' make check fmt-check + clippy + tests\n'
@printf ' make build release Rust installer\n'
@ -45,16 +44,6 @@ test-rust:
test-vm:
python3 installer/tests/vm/test_vmsafety.py
# A real-model acceptance run. Fails (BLOCKED) when the live server is not
# configured, so it can never pass by silently not running.
opencode-acceptance:
@if [ -z "$$PHOEBUS_OPENCODE_LIVE_URL" ] || [ -z "$$PHOEBUS_OPENCODE_LIVE_PROVIDER" ] || [ -z "$$PHOEBUS_OPENCODE_LIVE_MODEL" ]; then \
echo "BLOCKED: set PHOEBUS_OPENCODE_LIVE_URL, PHOEBUS_OPENCODE_LIVE_PROVIDER and PHOEBUS_OPENCODE_LIVE_MODEL"; \
exit 2; \
fi
cd installer-rs && PHOEBUS_OPENCODE_REQUIRE_LIVE=1 \
cargo test -p phoebus-executor --test opencode_live -- --nocapture
fmt:
cd installer-rs && cargo fmt --all

View file

@ -7,69 +7,6 @@ Format: Keep a Changelog. Dates are UTC.
## Unreleased
### Added
- **Real OpenCode agent-server adapter.** `phoebus-executor::opencode_client`
implements the OpenCode session/message protocol over the project's curl
transport and the `ModelTransport` trait, so the strict proposal parser,
evidence review, bounded facts and executor are reused unchanged. The GUI
("OpenCode agent"), the installer CLI (`--ai-backend opencode`,
`--opencode-server/-provider/-model/-password-file`) and `sys ask` all use it.
It creates a transient session per request, accepts only the completed
assistant text parts, disables tools per message, and deletes the session.
A JSON schema output mode is available in the protocol but is not used: the
shipped DeepSeek models reject it, and the prompt carries an explicit change
shape instead. The `opencode 1.18.32` contract was verified directly: session
creation rejects a `model` field, `/provider` metadata can contain a
credential and is reduced to ids/model names, and auth is HTTP Basic
(`opencode` / `OPENCODE_SERVER_PASSWORD`).
- **`--opencode-test`** obtains and validates a real model response (exit
nonzero on failure), distinct from the read-only `--opencode-probe`. A live
acceptance test (`make opencode-acceptance`) fails as BLOCKED when no server
is configured, so it cannot pass by not running.
- **Truthful OpenCode connection states** (`insecure_transport`, `unreachable`,
`authentication_required`, `authentication_rejected`, `incompatible`,
`reachable`, `model_catalog`, `selected_model_unavailable`); `ready` is
reserved for a validated response and is never returned by the probe.
- **GUI "Test connection"** and OpenCode connection controls, plus a backend
selection (`ai.backend`) in canonical configuration.
### Security
- **The mandatory-AI gate now requires a validated interaction.** Both the GUI
bridge and the installer CLI refuse to install when only a provider name is
configured; a successful, validated model interaction bound to the current
configuration (and credential) is required. Changing the model, endpoint,
server or a secret invalidates it. A direct provider or `--no-ai` remains the
fallback.
- **OpenCode transport policy is enforced.** Plain `http://` is accepted only
when the resolved destination is loopback and the connection is pinned to the
checked address; remote access is `https://` with certificate verification or
an authenticated tunnel to loopback. Redirects, unsafe schemes and oversized
or trickled bodies are bounded, and credentials travel only on curl's stdin.
- **Credentials never surface.** The catalog is reduced to ids/model names;
server responses that echo credentials are not retained, and tests feed
credential-bearing bodies and assert they do not appear in errors or state.
### Verified
- **The graphical installer uses the OpenCode adapter.** In a disposable
graphical VM the wizard selected "OpenCode agent", entered the server,
provider and model through the UI, obtained a real model response (Test
connection) and a validated proposal (Connect and validate, green
"Validated"). The `opencode` harness run passed 17/17 and the GUI regression
25/25. A password-protected server was reached through authentication as
well. The full graphical installation beyond the AI gate is still not run.
### Fixed
- **A malformed model proposal now gets one bounded corrective retry** before
the strict parser rejects the interaction (the shipped DeepSeek models
occasionally keyed the change or rationale wrongly). The parser remains the
final authority; a retry that still fails is still rejected.
- **OpenCode client/probe defects found by testing:** the handwritten HTTP
reader (no total deadline, UTF-8-unsafe chunk fallback) was removed in favour
of the curl transport; the catalog is no longer parsed on a non-2xx status; a
provider-shaped 500 can no longer look like a catalog; the duplicate-session
harness check requires exactly one session; and GUI navigation is asserted
from secret-free frontend state lines rather than inferred from a screenshot.
### Added
- **OpenCode connection workflow and capability probe.** New ADR 0011 and
`docs/OPENCODE.md` separate the four components (client, server, model

View file

@ -3,36 +3,27 @@
Rolling note between work sessions. **Update this file before you finish**, then
commit it. It should be short and current; use `git log` for detail.
- **Last updated:** this session (2026-09-22), OpenCode adapter.
- **Current focus:** Implemented a real OpenCode agent-server adapter
(`phoebus-executor::opencode_client`) that speaks the session/message protocol
over curl and implements `ModelTransport`, wired into canonical config
(`ai.backend = "opencode"`), the GUI ("OpenCode agent" + Test connection),
the installer CLI (`--ai-backend opencode`, `--opencode-test`) and `sys ask`.
The mandatory-AI gate now requires a validated interaction with invalidated
state. The probe/transport were hardened (loopback/TLS policy, DNS pinning,
status checks, auth), and the GUI harness gained exact-session and
frontend-state assertions.
- **Last updated:** this session (2026-09-22), harness + security + polish.
- **Current focus:** Hardened the VM harness (enforced qcow2/`/dev`/backing-chain
safety, structured PASS/FAIL results, per-run OVMF+QMP, no `os.system`),
fixed confirmed security defects (disk revalidation before partitioning,
bridge replay/concurrency + input bounds, provider transport URL/size
hardening, `TargetRoot` symlink escapes, and the `0 B` disk-size probe bug),
added an OpenCode server capability probe + docs/ADR 0011, and fixed the
welcome focus ring and the untruthful mid-install cancellation.
- **Last verified (this session):**
- 336 Rust tests + 16 harness tests green; fmt/clippy clean.
- Real inference through `opencode 1.18.32` with `deepseek-v4-flash`;
`--opencode-test` → `{"phoebus":"ok"}`; the GUI bridge `ai_check` applied 8
reviewed changes; `sys ask` proposed and ran a read-only action.
- Auth: none → `authentication_required`, wrong → `authentication_rejected`,
correct → `model_catalog` + successful inference. Plain http to a LAN host
→ `insecure_transport`, exit 1, no request sent.
- 7 real-HTTP integration tests (status, chunked multibyte, oversize,
redirect, disconnect, auth) and 2 env-gated live tests.
- GUI acceptance in a disposable VM: `gui-driver.py opencode` passed 17/17
(selected OpenCode, entered the endpoint/model through the UI, real model
response + validated proposal); `gui-driver.py gui` passed 25/25.
ISO `sha256 4db98db3…`, static binary `sha256 72c2dcd0…`.
- **Not yet verified this session:** the full graphical **installation** through
OpenCode past the AI gate (disk/account/review/ERASE/install/detached boot),
and a separate physical computer. The pinned manifest is `v1.18.31` while the
tested binary is `1.18.32`. On this server use `deepseek-flash`; the model
must match the server's catalog (the GUI default `deepseek-chat` does not
exist on it).
- `gui-driver.py gui` on the rebuilt ISO: **23/23 PASS**, exit 0. Welcome
autostarts; Return launches the installer (focus fixed); duplicate sessions
prevented; live medium protected; keyboard navigation reaches network + AI;
advancing without a model is refused and starts nothing.
- `make test` green (Rust + 16 harness unit tests); `cargo fmt --check`,
`cargo clippy --workspace --all-targets` (no errors), release + static
builds.
- OpenCode probe: `ready` against `opencode 1.18.32`; `authentication_required`
(exit 1) against an unauthenticated LAN bind.
- ISO: `installer/live/phoebus-installer-amd64.iso` 1.6 GiB,
`sha256 428dbd7547db8690596bf5c3a0d7a6fa8aee4c9f9eca1e926c216712dd050b36`;
static binary `sha256 2f9cd4b36a12e469d2b6187166acaf8b11f7f382cc19f7ad08bb2a809c855591`.
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
(remote `origin`, SSH port 2222).

View file

@ -1,9 +1,13 @@
# OpenCode connection workflow
OpenCode is integrated as a **real agent-server connection**, not a renamed
OpenAI-compatible endpoint. The adapter speaks OpenCode's session/message API
and feeds the same strict proposal parser, evidence review and executor as the
direct providers.
OpenCode is used in two clearly separated ways:
1. **Developer workflow** — on this repository, inspecting sanitized evidence.
Full tool access (shell, files, plugins) is fine because it runs as *you*,
on *your* machine, against *your* checkout.
2. **Phoebus assistant connection** — approved, bounded system facts and
validated typed proposals. It must never inherit the developer tool
permissions and never receives secrets.
Read [ADR 0011](adr/0011-opencode-connection-boundary.md) first.
@ -12,147 +16,84 @@ Read [ADR 0011](adr/0011-opencode-connection-boundary.md) first.
| Component | What it is | Where it runs |
|-----------|------------|---------------|
| OpenCode client | `opencode` TUI/CLI, or `opencode attach <url>` | your machine |
| OpenCode server | `opencode serve` — an HTTP/JSON **agent** API, not a model API | same machine as the client or the model |
| Model inference service | DeepSeek/OpenAI, or a local OpenAI-compatible server | provider cloud or your LAN |
| OpenCode server | `opencode serve` — an HTTP/JSON **agent** API, not a model API | usually the same machine as the client or the model |
| Model inference service | DeepSeek/OpenAI, or a local OpenAI-compatible server (Ollama, llama.cpp, ...) | provider cloud or your LAN |
| Phoebus installer/broker | the typed, privileged, local executor | the target machine only |
**An OpenCode server URL does not go in the direct-provider endpoint field.**
Select the OpenCode backend instead; Phoebus speaks the agent protocol.
**An OpenCode server URL does not go in Phoebus's local-model endpoint field.**
An OpenCode server is an agent application; it is not an OpenAI-compatible
`/v1/chat/completions` endpoint. Pointing Phoebus's `local` provider at it will
fail, and would be the wrong trust boundary even if it parsed.
## Configuration
```toml
[ai]
enabled = true
backend = "opencode" # "direct" (default) or "opencode"
opencode_server = "http://127.0.0.1:4096"
opencode_provider = "deepseek"
opencode_model = "deepseek-chat"
# The server password is a secret: supply it at runtime, never here.
```
The server password is stored in protected runtime input (a 0600 file or the GUI
secret pipe) and is **separate** from a direct provider API key.
## Command line
## Capability probe (never assume compatibility)
```sh
# Read-only: classify the server. Exits nonzero unless a model catalog exists.
phoebus-installer --opencode-probe http://127.0.0.1:4096 \
--opencode-provider deepseek --opencode-model deepseek-chat
# Acceptance: obtain and validate a real model response. Exits nonzero on any
# failure. This is the inference check, not a reachability check.
phoebus-installer --opencode-test http://127.0.0.1:4096 \
--opencode-provider deepseek --opencode-model deepseek-chat \
--opencode-password-file /path/to/server.pw
# Installer guidance through OpenCode (a real proposal is reviewed and applied).
phoebus-installer --ai-backend opencode \
--opencode-server http://127.0.0.1:4096 \
--opencode-provider deepseek --opencode-model deepseek-chat \
--install --ai
# The installed assistant uses the same adapter.
sys ask --ai-backend opencode --opencode-server http://127.0.0.1:4096 \
--opencode-provider deepseek --opencode-model deepseek-chat \
"show the transaction history"
phoebus-installer --opencode-probe http://127.0.0.1:4096
```
`--opencode-password-file` must be mode 0600, like the direct provider key file.
## Graphical installer
On the **AI model** step choose **OpenCode agent**, then fill in the server URL,
the server password (if the server has one), the provider and the model. Two
actions are available:
- **Test connection** obtains and validates a real model response
(`ai_test`); it does not change the installation plan.
- **Connect and validate** obtains a real proposal through OpenCode and runs the
strict review (`ai_check`). Only then does the wizard allow continuing, and
only then does the backend accept the AI prerequisite for installation.
Changing the server, provider, model or password — or editing the configuration
— invalidates the validated state.
## Connection states
`phoebus-installer --opencode-probe` prints one of:
It is read-only and prints a typed state, exiting nonzero unless a model is
available:
| State | Meaning |
|-------|---------|
| `insecure_transport` | the destination failed the transport policy |
| `unreachable` | the server could not be reached |
| `authentication_required` | the server returned 401 and no credential was supplied |
| `authentication_rejected` | a credential was supplied and rejected |
| `incompatible` | a response arrived but was not the expected API/JSON |
| `reachable` | healthy server with no model catalog |
| `model_catalog` | healthy server with a model catalog |
| `selected_model_unavailable` | the chosen provider/model is not in the catalog |
| `ready` | reserved for a real, validated model response (not the probe) |
| `disconnected` | TCP connect failed; the service is down |
| `authentication_required` | the server answered 401/403; supply the password/tunnel |
| `incompatible` | a health response arrived but the API shape is not the expected one |
| `reachable_no_model` | healthy server, no model configured |
| `ready` | reachable, healthy, API-compatible, and ≥1 model configured |
A model catalog is not readiness. The probe never returns `ready`; only a real
inference that validates the response does.
`ready` still does **not** prove the model can emit a valid Phoebus proposal;
that requires a real prompt round-trip and proposal parse. A health check or an
HTTP 200 is not that proof.
## Transport policy
- Plain `http://` is accepted **only** when the resolved destination is
loopback. The host is resolved and the connection is pinned to the checked
address, so a DNS answer that changes after the check cannot move the target.
- Remote access is `https://` (curl verifies the certificate; verification is
never disabled) **or** an authenticated encrypted tunnel terminating on
loopback (SSH `-L`, WireGuard, ...).
- Redirects are disabled, the protocol is restricted to `http,https`, and
connect time, total time, header/body sizes and response size are bounded.
- A URL with userinfo, a path or a control character is rejected.
## Security
- The server the assistant talks to should run unprivileged with a restricted
configuration. OpenCode permission settings are not an OS sandbox: run the
Phoebus-facing server with a dedicated directory, no plugins, and no
developer sessions, and keep the model credentials out of its reach where the
deployment allows.
- The adapter requests **no tools** per message (`"tools": {...false}`) as
defence in depth, but that is not a substitute for process isolation.
- Destructive product actions remain in the local typed broker with local human
approval. The agent never receives a shell, root, credentials or private-file
access, and disk/account passphrases are never sent to it.
- The adapter creates a transient session per request, accepts only the
completed assistant text parts (never user, tool or reasoning parts) and
deletes the session afterwards, so installation facts are not retained.
The probe reads `/global/health` and `/config/providers`, keeps only counts from
the latter, and never returns the provider credentials that upstream includes in
that response.
## A. OpenCode on the development/VM host
```sh
# 1. Set a provider credential through the environment (never a file in git).
export DEEPSEEK_API_KEY="$(cat ~/.config/phoebus/deepseek.key)" # 0600 file
# 2. Start the server on loopback only. Upstream warns when it is unsecured.
opencode serve --hostname 127.0.0.1 --port 4096
opencode attach http://127.0.0.1:4096 # interactive client
phoebus-installer --opencode-probe http://127.0.0.1:4096
# 3. In another terminal, attach a client to it.
opencode attach http://127.0.0.1:4096
```
Keep the server on `127.0.0.1`; do not enable `--mdns` or bind `0.0.0.0`
without authentication.
Keep the server on `127.0.0.1`. Do not pass `--mdns` and do not bind `0.0.0.0`
without authentication: the server's configuration API can expose provider
credentials.
## B. OpenCode on a separate user-controlled computer
Run the server on that computer bound to **loopback** and reach it through an
authenticated encrypted tunnel:
Run the server on that computer, bound to **loopback**, and reach it through an
authenticated encrypted tunnel. SSH port-forwarding is the simplest approved
transport:
```sh
# remote:
# On the remote computer:
opencode serve --hostname 127.0.0.1 --port 4096
# local:
# From your machine (tunnel local 127.0.0.1:4096 -> remote loopback:4096):
ssh -N -L 127.0.0.1:4096:127.0.0.1:4096 you@remote.example
# Then, locally:
opencode attach http://127.0.0.1:4096
phoebus-installer --opencode-probe http://127.0.0.1:4096
```
If a tunnel is impossible, set `OPENCODE_SERVER_PASSWORD` and terminate TLS in
front of the server; never expose an unauthenticated plaintext service.
The probe now sees a loopback endpoint and the tunnel supplies transport
authentication and encryption. If you cannot use a tunnel, set
`OPENCODE_SERVER_PASSWORD` and terminate TLS in front of the server; never
expose an unauthenticated plaintext service.
### VM networking is not one thing
Inside a VM these are different endpoints and must not be confused:
| Endpoint | Meaning |
|----------|---------|
| `guest 127.0.0.1` | the guest's own loopback |
@ -160,28 +101,36 @@ front of the server; never expose an unauthenticated plaintext service.
| `10.0.2.2` | the QEMU user-net gateway to the host |
| `192.168.x.y` | a real LAN address, reachable by other machines |
A VM guest cannot name the host's loopback directly, and plain `http` to the
gateway is refused by policy. The supported pattern is a host-local relay bound
to the **guest's** loopback (the same shape as an SSH tunnel); the VM harness
uses a tiny TCP forwarder for exactly this.
## C. Phoebus assistant boundary
## Verified evidence (2026-09-22)
When a Phoebus assistant uses OpenCode:
- `opencode 1.18.32` (pinned manifest: `v1.18.31`; version mismatch noted).
- `--opencode-probe` → `model_catalog`, 223 providers / 7915 models, 26
connected; the selected `deepseek:deepseek-v4-flash` present.
- `--opencode-test` → `validated model response: {"phoebus":"ok"}` (real
inference), exit 0.
- The GUI bridge `ai_check` over OpenCode applied 8 reviewed changes from a real
`deepseek-v4-flash` proposal.
- `sys ask` over OpenCode proposed a read-only `history` action and executed it
deterministically.
- Authentication: no credential → `authentication_required`; wrong →
`authentication_rejected`; correct → `model_catalog` and a successful real
inference.
- Transport policy: plain `http` to a LAN/global address →
`insecure_transport`, exit 1, no request sent.
- Real-HTTP integration tests cover status preservation, chunked multibyte
bodies, oversized bodies, redirects, abrupt disconnects and authentication.
- A separate physical computer remains **unverified**; a second server bound to
the LAN address reached through a loopback tunnel is the remote-topology test.
- Run the service unprivileged, with restricted filesystem access.
- Disable tools you do not need. OpenCode permission settings are *not* an
operating-system security boundary; enforce isolation outside the prompt.
- Keep the destructive execution path in Phoebus's local broker with local human
approval. The agent is never given a shell, root, credentials or private-file
access.
- Keep credentials in protected runtime storage (0600, outside model context).
Never forward disk passphrases or account passwords to OpenCode.
- Changing the model or connection invalidates any approval whose meaning
depends on it; a reconnect must never replay an installation command.
## Developer workflow note
For work on this repository, the developer OpenCode session may use full tools,
but only against a checkout and against **sanitized** test evidence. Do not feed
it VM disks, serial transcripts with credentials, `*.pw` files, or the
`PHOEBUS_OPENCODE_*` runtime inputs.
## Verified evidence
- `phoebus-installer --opencode-probe http://127.0.0.1:41999` against the
installed `opencode 1.18.32` returned `ready` (3 providers, 27 models).
- The same probe through a forwarded second loopback endpoint returned `ready`.
- A server deliberately bound to a LAN address **without** authentication
returned `authentication_required` and exit status 1: the probe refuses to
treat an unauthenticated service as usable.
- Physical second-computer verification is **BLOCKED** in this environment (no
second machine / no passwordless SSH); the forwarded-hop test is labelled as a
host-local transport test, not a second computer.

View file

@ -99,11 +99,7 @@ still not VM-verified.
| Bridge replay/concurrency + input bounds | yes | yes | no | n/a |
| Provider transport endpoint/size hardening | yes | yes | no | n/a |
| `TargetRoot` symlink-escape guard | yes | yes | n/a | n/a |
| OpenCode server capability probe | yes | yes | real host probe + auth + policy | n/a |
| OpenCode proposal adapter (real inference) | yes | yes | real model (`deepseek-v4-flash`) | n/a |
| OpenCode in GUI / CLI / `sys ask` | yes | yes | GUI AI step + `sys ask` live | n/a |
| OpenCode full graphical install | yes | yes | AI gate passed; install not run | n/a |
| Mandatory AI requires a validated interaction | yes | yes | bridge + CLI | n/a |
| OpenCode server capability probe | yes | yes | real host probe (`ready`) | n/a |
| GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no |
| Release gates + atomic publish | yes | yes | no | n/a |
| `sys` verbs | yes | yes | yes | no |

View file

@ -4,57 +4,6 @@ Companion to `docs/STATUS.md`. The machine-readable per-run results live outside
git under `/var/tmp/phoebus-vm/<run-id>/results.json`; this file is the
human-readable register of what was found, fixed and still unverified.
## OpenCode adapter (2026-09-22, second pass)
Implemented a real OpenCode adapter (not just a probe), integrated through
canonical configuration (`ai.backend = "opencode"`), the GUI bridge, the
installer CLI and `sys ask`. Defects found while implementing and testing:
| ID | Defect | Fix | Test |
|----|--------|-----|------|
| O1 | No OpenCode proposal adapter; the GUI used the OpenAI-compatible transport | `phoebus-executor::opencode_client` implements the real session/message protocol as a `ModelTransport` | live + bridge end-to-end |
| O2 | `POST /session` was sent a `model` field per the OpenAPI schema | the shipped 1.18.32 rejects it (BadRequest); the model is selected on the message | real-HTTP integration |
| O3 | The probe had no credential input | `ProbeRequest.auth` + basic-auth header via stdin | auth integration test |
| O4 | The probe did not enforce the connection destination | `Endpoint::checked_target` resolves and requires loopback for plain http; the connection is pinned | `transport_policy_enforces_loopback_for_plain_http`, insecure-destination test |
| O5 | Handwritten HTTP read had no total deadline and a UTF-8-unsafe chunk decoder that fell back on malformed input | removed the handwritten parser; the established curl transport is used and bounds time, protocol, redirects and size | real-HTTP chunked/oversize/redirect/disconnect tests |
| O6 | The catalog was parsed without checking the HTTP status; a providers-shaped 500 could look like a catalog | status is checked before parsing; non-2xx is `incompatible` | `a_misleading_success_shaped_500_does_not_produce_a_catalog` |
| O7 | Catalog presence counted as readiness | `ready` is reserved for a validated response; the probe returns `model_catalog`/`reachable` | `an_empty_catalog_is_reachable_not_ready` |
| O8 | `probe_live_server_when_configured` passed when its env var was absent and only asserted reachability | replaced by env-gated `opencode_live` tests that assert a real inference; `PHOEBUS_OPENCODE_REQUIRE_LIVE=1` fails when the live run cannot happen | `make opencode-acceptance` |
| O9 | The credential test built an already-sanitised struct | tests feed credential-bearing server bodies and assert errors/catalogs never contain them | `one_shot_rejects_a_non_assistant_or_errored_reply`, `catalog_never_reads_provider_keys` |
| O10 | A provider name satisfied the mandatory-AI gate | both the bridge and the CLI require a validated interaction bound to the current configuration; config/secret changes invalidate it | `a_provider_name_alone_does_not_satisfy_the_ai_requirement`, `an_unreachable_provider_does_not_satisfy_the_ai_gate` |
| O11 | The proposal prompt allowed the model to key the change by action name | prompt now requires exactly `action` + `value` with explicit examples | live bridge `ai_check` |
| O12 | The GUI duplicate-session assertion accepted two pre-existing sessions | requires exactly one session before and after | harness |
| O13 | GUI navigation was inferred from a surviving process/screenshot | the frontend emits secret-free `phoebus-state` lines; the harness asserts the current step and AI state | harness |
| O14 | A model could return a malformed proposal with no second chance | one bounded corrective retry in `complete_proposal_at`/`complete_plan`, with the strict parser still final | `a_rejected_proposal_is_retried_once_with_a_correction`, `a_retry_that_still_fails_is_still_rejected` |
### Graphical OpenCode acceptance (VM verified)
`gui-driver.py opencode` on the built ISO (real model, no simulation):
- welcome → installer → AI step; selected **OpenCode agent** through the UI;
- typed the server URL, provider and model through the UI;
- **Test connection** obtained a real model response (green "Model responded");
- **Connect and validate** obtained and validated a proposal (green "Validated",
frontend state `aiConnected=true`);
- run `gui-opencode-20260922T102640Z-be168813`: **17/17 PASS**, exit 0; the full
GUI regression `gui-gui-20260922T102907Z-a9e5e824` was **25/25 PASS**.
- The model is reached through a guest-loopback relay to the host OpenCode
server (the SSH-tunnel shape), so the transport policy is satisfied.
- Authenticated server: the same harness with a password-protected server got
through authentication and a real Test connection; a flaky malformed proposal
was correctly rejected. Use `deepseek-flash` (reliable) over
`deepseek-v4-flash` (occasionally malformed).
Still **NOT RUN**: the full graphical installation (disk → account → review →
ERASE → install → detached boot) *through OpenCode*. The AI gate is now reached
and passed in the graphical VM; the remaining stages are the long package
installation. Two fresh-disk graphical installs and a separate physical machine
remain unverified.
OpenCode protocol/transport tests: 26 executor unit tests + 7 real-HTTP
integration tests + 2 live tests (skipped offline, real inference when
configured). Bridge gate tests: 5. Full suite: 336 Rust tests.
## Run matrix (this session, 2026-09-22)
```json

View file

@ -44,35 +44,10 @@ Two facts shape the decision:
product actions still go through the local typed broker and local human
approval. The OpenCode configuration is written mode 0600 and carries no
credentials.
5. **The installer's AI step uses a real OpenCode adapter** (implemented after
this ADR was first written). `phoebus-executor::opencode_client` speaks the
OpenCode session/message API over the project's curl transport and implements
the same `ModelTransport` trait as the direct providers, so the strict
proposal parser, evidence review, facts and executor are reused unchanged.
The adapter creates a transient session per request, accepts only the
completed assistant `TextPart`s (never user/tool/reasoning parts), disables
tools per message, and deletes the session on every path. The GUI, the
installer CLI and `sys ask` all select it through canonical configuration
(`ai.backend = "opencode"`).
6. **A provider name is not a validated interaction.** Both the GUI bridge and
the installer CLI require a successful, validated model interaction bound to
the current configuration (and credential) before installation; changing the
model, endpoint, server or credential invalidates it. `Ready` is reserved for
a real, validated response.
### Protocol notes (verified against the shipped `opencode 1.18.32`)
- Health: `GET /global/health`. Catalog: `GET /provider` (metadata; upstream may
include a credential `key`, so only ids and model names are kept).
- `POST /session` rejects a `model` field (BadRequest) despite the OpenAPI
schema; the model is selected on the message.
- `POST /session/{id}/message` returns the assistant reply synchronously;
`format: json_schema` is rejected by the DeepSeek models in use ("Thinking
mode does not support this tool_choice"), so the prompt carries an explicit
change-object shape instead.
- `POST /session/{id}/abort` and `DELETE /session/{id}` clean up.
- Authentication is HTTP Basic with username `opencode` and the
`OPENCODE_SERVER_PASSWORD` value; Bearer is not accepted.
5. **The installer's AI step keeps using its own bounded transport.** OpenCode
is an optional operator workflow, not a replacement for the typed proposal
transport; a future adapter must perform a real prompt round-trip and parse a
versioned proposal before it may claim compatibility.
## Consequences
@ -87,9 +62,5 @@ Two facts shape the decision:
## Status
Accepted and implemented. The probe, the adapter and the connection states are
implemented with unit, real-HTTP integration, live-model and bridge tests; the
graphical installer can select OpenCode and obtain a real validated proposal.
End-to-end installation still does not *depend* on OpenCode: a direct provider
or the deterministic `sys` path remains available, and an installed system works
without a model.
Accepted. The probe and its tests are implemented; end-to-end installation does
not depend on OpenCode.

View file

@ -145,27 +145,7 @@ pub fn build_request(
}
}
/// The request with a corrective turn appended after a rejected plan.
pub fn build_corrected_request(
provider: ProviderKind,
model: &str,
facts: &SystemFacts,
instruction: &str,
correction: &str,
) -> ChatRequest {
let mut request = build_request(provider, model, facts, instruction);
request.messages.push(ChatMessage {
role: "user".into(),
content: format!(
"Your previous reply was rejected: {correction}. Reply with ONLY the \
corrected JSON object, with no prose and no code fence."
),
});
request
}
/// Ask the provider for a plan and parse it, fail-closed at every step. A
/// rejected reply is retried once with a corrective turn.
/// Ask the provider for a plan and parse it, fail-closed at every step.
pub fn complete_plan(
provider: ProviderKind,
endpoint: &str,
@ -185,27 +165,11 @@ pub fn complete_plan(
));
}
facts.validate_no_forbidden()?;
let attempt = |request: &ChatRequest| -> Result<AssistantPlan, AiError> {
let body = serde_json::to_string(request)?;
let request = build_request(provider, model, facts, instruction);
let body = serde_json::to_string(&request)?;
let response = transport.send(provider, endpoint, &body)?;
let content = crate::provider::extract_content(&response)?;
parse_plan(&content)
};
match attempt(&build_request(provider, model, facts, instruction)) {
Ok(plan) => Ok(plan),
Err(first) => {
let correction = first.to_string();
attempt(&build_corrected_request(
provider,
model,
facts,
instruction,
&correction,
))
}
}
}
#[cfg(test)]
@ -315,30 +279,6 @@ mod tests {
.is_err());
}
#[test]
fn a_rejected_plan_is_retried_once_with_a_correction() {
use crate::provider::{chat_response, ScriptedTransport};
let bad =
chat_response(r#"{"version":1,"summary":"x","actions":[{"action":"run_shell"}]}"#);
let good = chat_response(
r#"{"version":1,"summary":"look","actions":[{"action":"history"}],"rationale":[{"action":"history","reason":"asked"}]}"#,
);
let transport = ScriptedTransport::new(vec![bad, good]);
let plan = complete_plan(
ProviderKind::Local,
"http://127.0.0.1:11434/v1/chat/completions",
"m",
&facts(),
"what changed?",
&transport,
)
.unwrap();
assert_eq!(plan.actions.len(), 1);
let requests = transport.requests();
assert_eq!(requests.len(), 2);
assert!(requests[1].contains("rejected"));
}
#[test]
fn action_tag_matches_the_schema() {
assert_eq!(action_tag(&SystemAction::History), "history");

View file

@ -231,14 +231,7 @@ set_binary_packages (bool), set_build_jobs (1-256), set_package_use (atom, flag,
enabled).
Reply with ONLY a JSON object of the form:
{\"version\":1,\"changes\":[{\"action\":\"<action>\",\"value\":<value>}],\"rationale\":[{\"action\":\"<action>\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
Every change object has EXACTLY the two keys `action` and `value`. Put the chosen
option in `value`; never use the action name as a key. Correct examples:
{\"action\":\"set_kernel_profile\",\"value\":\"safe\"}
{\"action\":\"set_filesystem\",\"value\":\"btrfs\"}
{\"action\":\"set_flatpak\",\"value\":true}
{\"action\":\"set_build_jobs\",\"value\":4}
{\"version\":1,\"changes\":[{\"action\":\"...\",...}],\"rationale\":[{\"action\":\"...\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
Rules: prefer stability and a proven boot over speculative performance; never
propose disabling signature verification, enabling ~amd64 globally, weakening
@ -375,42 +368,6 @@ impl ModelTransport for TestTransport {
}
}
/// A transport that returns a scripted sequence of responses, one per call
/// (tests of retry and multi-turn behaviour).
pub struct ScriptedTransport {
responses: std::sync::Mutex<std::collections::VecDeque<String>>,
requests: std::sync::Mutex<Vec<String>>,
}
impl ScriptedTransport {
pub fn new(responses: Vec<String>) -> Self {
Self {
responses: std::sync::Mutex::new(responses.into()),
requests: std::sync::Mutex::new(Vec::new()),
}
}
pub fn requests(&self) -> Vec<String> {
self.requests.lock().unwrap().clone()
}
}
impl ModelTransport for ScriptedTransport {
fn send(&self, _provider: ProviderKind, _url: &str, body: &str) -> Result<String, AiError> {
self.requests.lock().unwrap().push(body.to_string());
self.responses
.lock()
.unwrap()
.pop_front()
.ok_or_else(|| AiError::Provider("no scripted response left".into()))
}
}
/// Wrap a bare proposal in an OpenAI-style chat response (test helper).
pub fn chat_response(content: &str) -> String {
serde_json::json!({ "choices": [{ "message": { "content": content } }] }).to_string()
}
/// Ask a provider for a proposal and parse it, fail-closed at every step.
pub fn complete_proposal(
provider: ProviderKind,
@ -421,30 +378,8 @@ pub fn complete_proposal(
complete_proposal_at(provider, provider.endpoint(), model, facts, transport)
}
/// Build the request again, appending a corrective turn after a rejected reply.
/// Models occasionally key a change by the action name or add prose; one
/// bounded corrective round-trip meaningfully improves reliability without
/// weakening the parser.
pub fn build_corrected_request(
provider: ProviderKind,
model: &str,
facts: &SystemFacts,
correction: &str,
) -> ChatRequest {
let mut request = build_request(provider, model, facts);
request.messages.push(ChatMessage {
role: "user".into(),
content: format!(
"Your previous reply was rejected: {correction}. Reply with ONLY the \
corrected JSON object, with no prose and no code fence."
),
});
request
}
/// As `complete_proposal`, but with an explicit endpoint (`--ai-endpoint`), for
/// a self-hosted model on a non-default port. A rejected reply is retried once
/// with a corrective turn; the strict parser is still the final authority.
/// a self-hosted model on a non-default port.
pub fn complete_proposal_at(
provider: ProviderKind,
endpoint: &str,
@ -459,26 +394,11 @@ pub fn complete_proposal_at(
}
validate_endpoint(endpoint)?;
facts.validate_no_forbidden()?;
let attempt = |request: &ChatRequest| -> Result<AiProposal, AiError> {
let body = serde_json::to_string(request)?;
let request = build_request(provider, model, facts);
let body = serde_json::to_string(&request)?;
let response = transport.send(provider, endpoint, &body)?;
let content = extract_content(&response)?;
parse_proposal(&content)
};
match attempt(&build_request(provider, model, facts)) {
Ok(proposal) => Ok(proposal),
Err(first) => {
let correction = first.to_string();
attempt(&build_corrected_request(
provider,
model,
facts,
&correction,
))
}
}
}
#[cfg(test)]
@ -642,49 +562,6 @@ mod tests {
assert_eq!(parsed.changes.len(), 1);
}
#[test]
fn a_rejected_proposal_is_retried_once_with_a_correction() {
// First response uses the wrong key (the failure seen with a real
// model); the second is corrected.
let bad = chat_response(
r#"{"version":1,"changes":[{"action":"set_kernel_profile","profile":"safe"}],"rationale":[]}"#,
);
let good = chat_response(
r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"x"}]}"#,
);
let transport = ScriptedTransport::new(vec![bad, good]);
let proposal = complete_proposal_at(
ProviderKind::Local,
"http://127.0.0.1:8080/v1/chat/completions",
"m",
&facts(),
&transport,
)
.unwrap();
assert_eq!(proposal.changes.len(), 1);
let requests = transport.requests();
assert_eq!(requests.len(), 2, "exactly one corrective retry");
assert!(
requests[1].contains("rejected"),
"the retry carries the reason"
);
}
#[test]
fn a_retry_that_still_fails_is_still_rejected() {
let bad = chat_response(r#"{"version":1,"changes":[{"action":"nope"}]}"#);
let transport = ScriptedTransport::new(vec![bad.clone(), bad]);
assert!(complete_proposal_at(
ProviderKind::Local,
"http://127.0.0.1:8080/v1/chat/completions",
"m",
&facts(),
&transport
)
.is_err());
assert_eq!(transport.requests().len(), 2);
}
#[test]
fn unavailable_provider_is_explicit() {
let transport = TestTransport::new("{}");

View file

@ -361,35 +361,6 @@ impl Default for DesktopConfig {
}
}
/// How the assistant reaches a model. `Direct` is an OpenAI-compatible
/// endpoint; `OpenCode` is an OpenCode **agent server** (a different protocol
/// and trust boundary), never an OpenAI-compatible model endpoint.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum AiBackend {
#[default]
#[serde(rename = "direct")]
Direct,
#[serde(rename = "opencode")]
OpenCode,
}
impl AiBackend {
pub fn as_str(self) -> &'static str {
match self {
AiBackend::Direct => "direct",
AiBackend::OpenCode => "opencode",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value.trim().to_ascii_lowercase().as_str() {
"" | "direct" | "provider" => Some(AiBackend::Direct),
"opencode" | "open-code" | "open_code" => Some(AiBackend::OpenCode),
_ => None,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(default)]
pub struct AiConfig {
@ -397,30 +368,6 @@ pub struct AiConfig {
pub provider: String,
pub model: String,
pub endpoint: String,
/// Direct provider endpoint or the OpenCode agent server.
pub backend: AiBackend,
/// OpenCode server base URL, e.g. `http://127.0.0.1:4096`.
pub opencode_server: String,
/// OpenCode provider id (e.g. `deepseek`).
pub opencode_provider: String,
/// OpenCode model id (e.g. `deepseek-chat`).
pub opencode_model: String,
}
impl AiConfig {
pub fn is_opencode(&self) -> bool {
self.backend == AiBackend::OpenCode
}
/// The OpenCode endpoint, if this configuration uses one.
pub fn opencode_endpoint(&self) -> Option<&str> {
let server = self.opencode_server.trim();
if server.is_empty() {
None
} else {
Some(server)
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]

View file

@ -24,9 +24,9 @@ pub mod update;
pub mod validate;
pub use config::{
AiBackend, AiConfig, Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig,
Filesystem, InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig,
Stage3Config, StorageConfig, SystemConfig, UserConfig,
Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig, Filesystem,
InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig, Stage3Config,
StorageConfig, SystemConfig, UserConfig,
};
pub use disk::{Disk, DiskKind, ProtectionReason};
pub use error::{CoreError, Result};

View file

@ -18,7 +18,6 @@ pub mod kernel;
pub mod log;
pub mod nix;
pub mod opencode;
pub mod opencode_client;
pub mod opencode_server;
pub mod portage;
pub mod probe;

File diff suppressed because it is too large Load diff

View file

@ -1,54 +1,29 @@
//! OpenCode **server** types, transport policy and capability probe.
//! OpenCode **server** capability probe.
//!
//! OpenCode is an agent application, not an OpenAI-compatible inference
//! endpoint. A TCP connect, a health check or an HTTP 200 is not proof that a
//! model is configured, that the selected model exists, or that it can produce
//! a valid Phoebus proposal. The probe reports a typed state for each of those
//! distinctions, and only a real inference (`OpenCodeClient::one_shot`) can
//! reach [`ConnectionState::Ready`].
//! endpoint. A successful TCP connect, a health check or an HTTP 200 is not
//! proof that a model is configured or that it can produce a valid Phoebus
//! proposal. This module makes those distinctions explicit so a caller can
//! report an honest connection state instead of assuming compatibility.
//!
//! The probe uses the shared [`HttpClient`] transport (curl through [`Exec`]),
//! never a second handwritten HTTP parser, and it keeps only ids and model
//! names from the provider catalog: upstream's catalog can contain credentials,
//! so raw bodies are never retained or surfaced.
//! It talks to the OpenCode HTTP API documented at <https://opencode.ai/docs/server/>
//! using a deliberately tiny HTTP/1.1 client (no TLS, no redirects, no
//! credentials in the URL). Remote access is expected through an authenticated,
//! encrypted tunnel to a loopback-bound server, never by exposing the server
//! directly.
//!
//! ## Transport policy
//!
//! Plain `http://` is accepted only when the resolved destination is loopback;
//! remote access must be `https://` (certificate-verified by curl) or an
//! authenticated encrypted tunnel terminating on loopback. The policy resolves
//! the host and the connection is pinned to the checked address, so a DNS
//! answer that changes after the check cannot move the destination.
//! The probe never returns provider credentials: upstream's `/config/providers`
//! response includes them, so only counts are kept.
use std::net::{SocketAddr, ToSocketAddrs};
use std::io::{Read, Write};
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
use std::time::Duration;
use phoebus_ai::AiError;
use phoebus_core::SecretString;
use serde::{Deserialize, Serialize};
use crate::opencode_client::{parse_catalog, Catalog, HttpClient, HttpRequest, HttpResponse};
/// The URL scheme of an endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scheme {
Http,
Https,
}
impl Scheme {
pub fn as_str(self) -> &'static str {
match self {
Scheme::Http => "http",
Scheme::Https => "https",
}
}
}
/// A parsed `scheme://host:port` server endpoint. No path, query, fragment or
/// userinfo is accepted.
/// A parsed `http://host:port` server endpoint.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Endpoint {
pub scheme: Scheme,
pub host: String,
pub port: u16,
}
@ -56,9 +31,7 @@ pub struct Endpoint {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EndpointError {
Empty,
UnsupportedScheme,
UserInfo,
PathNotAllowed,
NotHttp,
BadHost,
BadPort,
}
@ -67,9 +40,7 @@ impl std::fmt::Display for EndpointError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let text = match self {
EndpointError::Empty => "empty endpoint",
EndpointError::UnsupportedScheme => "only http:// and https:// are accepted",
EndpointError::UserInfo => "userinfo (@) is not allowed in the endpoint",
EndpointError::PathNotAllowed => "a path, query or fragment is not allowed",
EndpointError::NotHttp => "only http:// endpoints are accepted",
EndpointError::BadHost => "the host is missing or contains an unsafe character",
EndpointError::BadPort => "the port is missing or invalid",
};
@ -78,119 +49,61 @@ impl std::fmt::Display for EndpointError {
}
impl Endpoint {
/// Parse `http://host:port`. Plain HTTP only: remote access is over an
/// authenticated tunnel, not a direct TLS-less LAN bind.
pub fn parse(value: &str) -> Result<Self, EndpointError> {
let text = value.trim();
if text.is_empty() {
return Err(EndpointError::Empty);
}
let (scheme, rest) = if let Some(rest) = text.strip_prefix("http://") {
(Scheme::Http, rest)
} else if let Some(rest) = text.strip_prefix("https://") {
(Scheme::Https, rest)
} else {
return Err(EndpointError::UnsupportedScheme);
};
if rest.is_empty() {
return Err(EndpointError::BadHost);
}
if rest.contains('@') {
return Err(EndpointError::UserInfo);
}
if rest.contains('/') || rest.contains('?') || rest.contains('#') {
return Err(EndpointError::PathNotAllowed);
}
if rest
.chars()
.any(|c| c.is_whitespace() || c.is_control() || c == '"' || c == '\\')
let rest = text.strip_prefix("http://").ok_or(EndpointError::NotHttp)?;
// Reject userinfo, paths and control characters.
if rest.is_empty()
|| rest.contains('/')
|| rest.contains('@')
|| rest.contains('"')
|| rest.contains('\\')
|| rest.chars().any(|c| c.is_whitespace() || c.is_control())
{
return Err(EndpointError::BadHost);
}
// IPv6 literals are bracketed: [::1]:4096
let (host, port) = if let Some(rest) = rest.strip_prefix('[') {
let end = rest.find(']').ok_or(EndpointError::BadHost)?;
let host = &rest[..end];
let after = &rest[end + 1..];
let port = after.strip_prefix(':').ok_or(EndpointError::BadPort)?;
(host.to_string(), port)
} else {
let (host, port) = rest.rsplit_once(':').ok_or(EndpointError::BadPort)?;
(host.to_string(), port)
};
if host.is_empty() {
return Err(EndpointError::BadHost);
}
let port: u16 = port.parse().map_err(|_| EndpointError::BadPort)?;
if port == 0 {
return Err(EndpointError::BadPort);
}
Ok(Endpoint { scheme, host, port })
Ok(Endpoint {
host: host.to_string(),
port,
})
}
pub fn base(&self) -> String {
if self.host.contains(':') {
format!("{}://[{}]:{}", self.scheme.as_str(), self.host, self.port)
} else {
format!("{}://{}:{}", self.scheme.as_str(), self.host, self.port)
}
format!("http://{}:{}", self.host, self.port)
}
/// Resolve the endpoint and enforce the transport policy.
///
/// Returns the address the connection must be pinned to. `http` requires
/// every resolved address to be loopback; `https` requires a valid
/// certificate (checked by curl, never disabled).
pub fn checked_target(&self) -> Result<SocketAddr, AiError> {
let addrs: Vec<SocketAddr> = (self.host.as_str(), self.port)
fn socket_addrs(&self) -> std::io::Result<Vec<SocketAddr>> {
(self.host.as_str(), self.port)
.to_socket_addrs()
.map_err(|e| AiError::Provider(format!("cannot resolve {}: {e}", self.host)))?
.collect();
if addrs.is_empty() {
return Err(AiError::Rejected(format!(
"{} did not resolve to any address",
self.host
)));
}
if self.scheme == Scheme::Http {
for addr in &addrs {
if !addr.ip().is_loopback() {
return Err(AiError::Rejected(format!(
"refusing plain http to {} ({}); use https or a loopback tunnel",
self.host,
addr.ip()
)));
}
}
}
Ok(addrs[0])
.map(|it| it.collect())
}
}
/// The connection state a frontend should display. Only [`ConnectionState::Ready`]
/// follows a real, validated model response for the current connection/model.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
/// The connection state a frontend should display. `Ready` means the server is
/// reachable, authenticated, API-compatible *and* has at least one model; it
/// still does not prove the model can emit a valid proposal (that needs a real
/// prompt round-trip).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConnectionState {
/// The destination did not satisfy the transport policy.
InsecureTransport,
/// The server could not be reached.
Unreachable,
/// The server demanded authentication we did not supply.
Disconnected,
AuthenticationRequired,
/// The server rejected the authentication we supplied.
AuthenticationRejected,
/// A health response arrived but the API is not the expected shape.
ReachableNoModel,
Incompatible,
/// Healthy server with no model catalog.
Reachable,
/// Healthy server with an available model catalog.
ModelCatalog,
/// The selected provider/model is not in the catalog.
SelectedModelUnavailable,
/// A real model response was obtained and validated for this connection.
Ready,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Capability {
pub state: ConnectionState,
pub tcp_reachable: bool,
@ -198,467 +111,380 @@ pub struct Capability {
pub server_version: Option<String>,
pub provider_count: usize,
pub model_count: usize,
pub connected_model_count: usize,
pub selected_provider: Option<String>,
pub selected_model: Option<String>,
pub selected_model_available: bool,
pub detail: String,
}
impl Capability {
fn new(state: ConnectionState, detail: impl Into<String>) -> Self {
fn disconnected(detail: impl Into<String>) -> Self {
Self {
state,
state: ConnectionState::Disconnected,
tcp_reachable: false,
healthy: false,
server_version: None,
provider_count: 0,
model_count: 0,
connected_model_count: 0,
selected_provider: None,
selected_model: None,
selected_model_available: false,
detail: detail.into(),
}
}
}
/// Inputs for a probe. `auth` is the server basic-auth password (distinct from
/// any model provider credential).
pub struct ProbeRequest {
pub auth: Option<SecretString>,
/// The provider the frontend intends to use, if any.
pub provider: Option<String>,
/// The model the frontend intends to use, if any.
pub model: Option<String>,
pub timeout: Duration,
}
impl ProbeRequest {
pub fn new() -> Self {
Self {
auth: None,
provider: None,
model: None,
timeout: Duration::from_secs(10),
}
}
}
impl Default for ProbeRequest {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, serde::Deserialize)]
struct HealthBody {
#[derive(Debug, Deserialize)]
struct Health {
#[serde(default)]
healthy: bool,
#[serde(default)]
version: Option<String>,
}
fn http_base(endpoint: &Endpoint) -> String {
endpoint.base()
#[derive(Debug, Deserialize)]
struct Providers {
#[serde(default)]
providers: Vec<Provider>,
}
fn auth_required_state(auth_supplied: bool, status: u16) -> ConnectionState {
match (auth_supplied, status) {
(true, _) => ConnectionState::AuthenticationRejected,
(false, 403) => ConnectionState::AuthenticationRejected,
_ => ConnectionState::AuthenticationRequired,
}
#[derive(Debug, Deserialize)]
struct Provider {
#[serde(default)]
models: std::collections::BTreeMap<String, serde_json::Value>,
}
/// Probe the server and classify the connection without claiming model
/// readiness. The connection is pinned to the policy-checked address.
pub fn probe<H: HttpClient>(http: &H, endpoint: &Endpoint, request: &ProbeRequest) -> Capability {
let target = match endpoint.checked_target() {
Ok(target) => target,
Err(error) => {
return Capability::new(ConnectionState::InsecureTransport, error.to_string())
}
/// Probe an OpenCode server and classify the connection.
pub fn probe(endpoint: &Endpoint, timeout: Duration) -> Capability {
let addrs = match endpoint.socket_addrs() {
Ok(addrs) if !addrs.is_empty() => addrs,
Ok(_) => return Capability::disconnected("host did not resolve"),
Err(e) => return Capability::disconnected(format!("resolve failed: {e}")),
};
let resolve = Some((endpoint.host.clone(), endpoint.port, target.ip()));
// The `/provider` catalog can be several MiB on a server with many
// configured providers; health is tiny. Both are bounded.
const HEALTH_MAX_BODY: u64 = 64 * 1024;
const CATALOG_MAX_BODY: u64 = 16 * 1024 * 1024;
let make = |path: &str, max_body: u64| -> HttpRequest {
let mut req = HttpRequest::get(format!("{}{path}", http_base(endpoint)));
req.timeout = request.timeout;
req.connect_timeout = request.timeout.min(Duration::from_secs(10));
req.max_body = max_body;
req.resolve = resolve.clone();
req.auth = request.auth.clone();
req
// A failed TCP connect is the only way to be certain the service is down.
if TcpStream::connect_timeout(&addrs[0], timeout).is_err() {
return Capability::disconnected("connect failed");
}
// Each request uses its own short-lived connection (Connection: close),
// which is what the health/config endpoints expect and keeps the client
// simple and redirect-free.
let timeout = timeout;
let request = |path: &str| -> std::io::Result<(u16, String)> {
let mut stream = TcpStream::connect_timeout(&addrs[0], timeout)?;
let _ = stream.set_read_timeout(Some(timeout));
let _ = stream.set_write_timeout(Some(timeout));
get(&mut stream, &endpoint.host, path)
};
// Health is the API-compatibility signal.
let health = match http.request(&make("/global/health", HEALTH_MAX_BODY)) {
Ok(response) => response,
Err(error) => {
return Capability::new(ConnectionState::Unreachable, error.to_string());
// Health first: it is the API-compatibility signal.
let (status, body) = match request("/global/health") {
Ok(pair) => pair,
Err(e) => {
return Capability {
state: ConnectionState::Incompatible,
tcp_reachable: true,
healthy: false,
server_version: None,
provider_count: 0,
model_count: 0,
detail: format!("health request failed: {e}"),
}
}
};
let mut capability = classify_health(health, request.auth.is_some());
if capability.state != ConnectionState::Reachable {
// Health did not produce a usable server; report that state now.
if matches!(
capability.state,
ConnectionState::AuthenticationRequired | ConnectionState::AuthenticationRejected
) {
capability.tcp_reachable = true;
}
return capability;
}
capability.tcp_reachable = true;
// Catalog: metadata only, credentials never retained.
let catalog_response = match http.request(&make("/provider", CATALOG_MAX_BODY)) {
Ok(response) => response,
Err(error) => {
capability.state = ConnectionState::Incompatible;
capability.detail = format!("provider catalog request failed: {error}");
return capability;
}
if status == 401 || status == 403 {
return Capability {
state: ConnectionState::AuthenticationRequired,
tcp_reachable: true,
healthy: false,
server_version: None,
provider_count: 0,
model_count: 0,
detail: format!("server requires authentication (HTTP {status})"),
};
if !catalog_response.is_success() {
capability.state = match catalog_response.status {
401 => auth_required_state(request.auth.is_some(), 401),
403 => ConnectionState::AuthenticationRejected,
_ => ConnectionState::Incompatible,
}
if status != 200 {
return Capability {
state: ConnectionState::Incompatible,
tcp_reachable: true,
healthy: false,
server_version: None,
provider_count: 0,
model_count: 0,
detail: format!("/global/health returned HTTP {status}"),
};
capability.detail = auth_detail(capability.state, catalog_response.status);
return capability;
}
let catalog: Catalog = match parse_catalog(&catalog_response.body) {
Ok(catalog) => catalog,
Err(error) => {
capability.state = ConnectionState::Incompatible;
capability.detail = format!("provider catalog was not usable: {error}");
return capability;
}
};
apply_catalog(&mut capability, &catalog, request);
capability
}
fn classify_health(response: HttpResponse, auth_supplied: bool) -> Capability {
if response.status == 401 || response.status == 403 {
let state = auth_required_state(auth_supplied, response.status);
return Capability::new(state, auth_detail(state, response.status));
}
if !response.is_success() {
return Capability::new(
ConnectionState::Incompatible,
format!("/global/health returned HTTP {}", response.status),
);
}
let health: HealthBody = match serde_json::from_str(&response.body) {
Ok(health) => health,
let health: Health = match serde_json::from_str(&body) {
Ok(h) => h,
Err(_) => {
return Capability::new(
ConnectionState::Incompatible,
"/global/health was not the expected JSON",
)
return Capability {
state: ConnectionState::Incompatible,
tcp_reachable: true,
healthy: false,
server_version: None,
provider_count: 0,
model_count: 0,
detail: "/global/health was not the expected JSON".into(),
}
}
};
if !health.healthy {
return Capability::new(ConnectionState::Incompatible, "server reported unhealthy");
}
let mut capability = Capability::new(ConnectionState::Reachable, "healthy server");
capability.healthy = true;
capability.sign_healthy(health.version);
capability
}
impl Capability {
fn sign_healthy(&mut self, version: Option<String>) {
self.server_version = version;
self.tcp_reachable = true;
}
}
fn auth_detail(state: ConnectionState, status: u16) -> String {
match state {
ConnectionState::AuthenticationRequired => {
format!("server requires authentication (HTTP {status})")
}
ConnectionState::AuthenticationRejected => {
format!("server rejected the supplied authentication (HTTP {status})")
}
_ => format!("HTTP {status}"),
}
}
fn apply_catalog(capability: &mut Capability, catalog: &Catalog, request: &ProbeRequest) {
capability.provider_count = catalog
.providers
.iter()
.filter(|p| !p.models.is_empty())
.count();
capability.model_count = catalog.model_count();
capability.connected_model_count = catalog.connected_model_count();
if let Some(provider) = &request.provider {
capability.selected_provider = Some(provider.clone());
if let Some(model) = &request.model {
capability.selected_model = Some(model.clone());
capability.selected_model_available = catalog.has_model(provider, model);
}
return Capability {
state: ConnectionState::Incompatible,
tcp_reachable: true,
healthy: false,
server_version: health.version,
provider_count: 0,
model_count: 0,
detail: "server reported unhealthy".into(),
};
}
if capability.selected_provider.is_some() && !capability.selected_model_available {
capability.state = ConnectionState::SelectedModelUnavailable;
capability.detail = format!(
"provider/model {}:{} is not available in the catalog",
request.provider.as_deref().unwrap_or("?"),
request.model.as_deref().unwrap_or("?")
);
} else if capability.model_count > 0 {
capability.state = ConnectionState::ModelCatalog;
capability.detail = format!(
"{} provider(s), {} model(s), {} connected",
capability.provider_count, capability.model_count, capability.connected_model_count
);
// Providers: authentication and model availability.
let (pstatus, pbody) = request("/config/providers").unwrap_or((0, String::new()));
if pstatus == 401 || pstatus == 403 {
return Capability {
state: ConnectionState::AuthenticationRequired,
tcp_reachable: true,
healthy: true,
server_version: health.version,
provider_count: 0,
model_count: 0,
detail: format!("provider list requires authentication (HTTP {pstatus})"),
};
}
let providers: Option<Providers> = serde_json::from_str(&pbody).ok();
let (provider_count, model_count) = match providers {
Some(p) => (
p.providers.iter().filter(|p| !p.models.is_empty()).count(),
p.providers.iter().map(|p| p.models.len()).sum(),
),
None => (0, 0),
};
let state = if model_count == 0 {
ConnectionState::ReachableNoModel
} else {
capability.state = ConnectionState::Reachable;
capability.detail = "server is healthy but no model is configured".into();
ConnectionState::Ready
};
Capability {
state,
tcp_reachable: true,
healthy: true,
server_version: health.version,
provider_count,
model_count,
detail: if model_count == 0 {
"server is healthy but no model is configured".into()
} else {
format!("{provider_count} provider(s), {model_count} model(s)")
},
}
}
/// Minimal HTTP/1.1 GET with connection close. Never follows redirects.
fn get(stream: &mut TcpStream, host: &str, path: &str) -> std::io::Result<(u16, String)> {
let request = format!(
"GET {path} HTTP/1.1\r\nHost: {host}\r\nAccept: application/json\r\nConnection: close\r\n\r\n"
);
stream.write_all(request.as_bytes())?;
stream.flush()?;
let mut raw = Vec::new();
stream.read_to_end(&mut raw)?;
let text = String::from_utf8_lossy(&raw).into_owned();
let Some(header_end) = text.find("\r\n\r\n") else {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"no HTTP header terminator",
));
};
let headers = &text[..header_end];
let body = &text[header_end + 4..];
let status = headers
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|code| code.parse::<u16>().ok())
.ok_or_else(|| std::io::Error::new(std::io::ErrorKind::InvalidData, "no status line"))?;
let chunked = headers
.to_ascii_lowercase()
.contains("transfer-encoding: chunked");
let body = if chunked {
decode_chunked(body).unwrap_or_else(|| body.to_string())
} else {
body.to_string()
};
Ok((status, body))
}
/// Decode an HTTP chunked body. Best-effort; returns `None` on malformed input.
fn decode_chunked(body: &str) -> Option<String> {
let mut out = String::new();
let mut rest = body;
loop {
let line_end = rest.find("\r\n")?;
let size_text = rest[..line_end].split(';').next()?.trim();
let size = usize::from_str_radix(size_text, 16).ok()?;
rest = &rest[line_end + 2..];
if size == 0 {
return Some(out);
}
if rest.len() < size {
return None;
}
out.push_str(&rest[..size]);
rest = &rest[size..];
rest = rest.strip_prefix("\r\n").unwrap_or(rest);
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
use std::io::Read as _;
use std::net::TcpListener;
use std::thread;
struct FakeHttp {
responses: Mutex<Vec<HttpResponse>>,
requests: Mutex<Vec<HttpRequest>>,
fn spawn_server(routes: Vec<(&'static str, u16, &'static str)>) -> Endpoint {
use std::collections::HashMap;
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let routes: HashMap<&'static str, (u16, &'static str)> =
routes.into_iter().map(|(p, s, b)| (p, (s, b))).collect();
thread::spawn(move || {
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let mut buf = [0u8; 2048];
let n = stream.read(&mut buf).unwrap_or(0);
if n == 0 {
// The reachability probe connects and closes without a
// request; ignore it.
continue;
}
impl FakeHttp {
fn new(responses: Vec<(u16, &str)>) -> Self {
Self {
responses: Mutex::new(
responses
.into_iter()
.map(|(status, body)| HttpResponse {
status,
body: body.to_string(),
})
.collect(),
),
requests: Mutex::new(Vec::new()),
let request = String::from_utf8_lossy(&buf[..n]);
let want = request
.lines()
.next()
.and_then(|l| l.split_whitespace().nth(1))
.unwrap_or("");
let (code, payload) = routes.get(want).copied().unwrap_or((404, "{}"));
let response = format!(
"HTTP/1.1 {code} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
payload.len()
);
let _ = stream.write_all(response.as_bytes());
}
});
Endpoint {
host: "127.0.0.1".into(),
port,
}
}
impl HttpClient for FakeHttp {
fn request(&self, request: &HttpRequest) -> Result<HttpResponse, AiError> {
self.requests.lock().unwrap().push(request.clone());
let mut responses = self.responses.lock().unwrap();
if responses.is_empty() {
return Err(AiError::Provider("connection refused".into()));
}
Ok(responses.remove(0))
}
}
fn health() -> &'static str {
r#"{"healthy":true,"version":"1.18.32"}"#
}
fn catalog() -> &'static str {
r#"{"all":[
{"id":"deepseek","name":"DeepSeek","key":"sk-SECRET","models":{"deepseek-chat":{}}},
{"id":"empty","name":"Empty","models":{}}],
"connected":["deepseek"],
"default":{"deepseek":"deepseek-chat"}}"#
}
fn endpoint() -> Endpoint {
Endpoint::parse("http://127.0.0.1:4096").unwrap()
}
#[test]
fn parses_endpoints_and_rejects_unsafe_forms() {
fn parses_and_rejects_endpoints() {
assert_eq!(
Endpoint::parse("http://127.0.0.1:4096").unwrap(),
Endpoint {
scheme: Scheme::Http,
host: "127.0.0.1".into(),
port: 4096
}
);
let v6 = Endpoint::parse("https://[::1]:4096").unwrap();
assert_eq!(v6.host, "::1");
assert_eq!(v6.scheme, Scheme::Https);
assert_eq!(
Endpoint::parse("ftp://host:1"),
Err(EndpointError::UnsupportedScheme)
Endpoint::parse("https://127.0.0.1:4096"),
Err(EndpointError::NotHttp)
);
assert_eq!(
Endpoint::parse("http://user:pw@host:1"),
Err(EndpointError::UserInfo)
);
assert_eq!(
Endpoint::parse("http://host:1/v1/chat"),
Err(EndpointError::PathNotAllowed)
Endpoint::parse("http://user@host:1"),
Err(EndpointError::BadHost)
);
assert_eq!(Endpoint::parse("http://host"), Err(EndpointError::BadPort));
assert_eq!(
Endpoint::parse("http://host:0"),
Err(EndpointError::BadPort)
);
assert_eq!(
Endpoint::parse("http://host:99999"),
Err(EndpointError::BadPort)
);
assert_eq!(
Endpoint::parse("http://ho st:1"),
Err(EndpointError::BadHost)
);
assert_eq!(
Endpoint::parse("http://host:1\nX: y"),
Err(EndpointError::BadHost)
);
assert!(EndpointError::Empty.to_string().contains("empty"));
assert!(Endpoint::parse("http://host:1/../../etc").is_err());
assert!(Endpoint::parse("").is_err());
}
#[test]
fn transport_policy_enforces_loopback_for_plain_http() {
// An IP literal avoids DNS and works offline.
let public = Endpoint::parse("http://93.184.216.34:80").unwrap();
let err = public.checked_target().unwrap_err().to_string();
assert!(err.contains("refusing plain http"), "{err}");
// https is allowed (certificate verification happens in the transport).
let secure = Endpoint::parse("https://93.184.216.34:443").unwrap();
assert!(secure.checked_target().is_ok());
// loopback http is allowed and pinned.
let target = endpoint().checked_target().unwrap();
assert!(target.ip().is_loopback());
fn probe_reports_ready_with_models() {
let endpoint = spawn_server(vec![
(
"/global/health",
200,
r#"{"healthy":true,"version":"1.18.32"}"#,
),
(
"/config/providers",
200,
r#"{"providers":[{"id":"deepseek","models":{"m1":{},"m2":{}}},{"id":"empty","models":{}}]}"#,
),
]);
let capability = probe(&endpoint, Duration::from_secs(2));
assert_eq!(capability.state, ConnectionState::Ready);
assert_eq!(capability.server_version.as_deref(), Some("1.18.32"));
assert_eq!(capability.provider_count, 1);
assert_eq!(capability.model_count, 2);
}
#[test]
fn probe_reports_a_model_catalog_without_leaking_keys() {
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
let capability = probe(&http, &endpoint(), &ProbeRequest::new());
assert_eq!(capability.state, ConnectionState::ModelCatalog);
assert_eq!(capability.model_count, 1);
assert_eq!(capability.connected_model_count, 1);
let debug = format!("{capability:?}");
assert!(
!debug.contains("SECRET"),
"capability leaked a key: {debug}"
);
// The catalog request carried no credentials.
assert!(http.requests.lock().unwrap()[0].auth.is_none());
fn probe_reports_reachable_but_model_less() {
let endpoint = spawn_server(vec![
(
"/global/health",
200,
r#"{"healthy":true,"version":"1.18.32"}"#,
),
("/config/providers", 200, r#"{"providers":[]}"#),
]);
let capability = probe(&endpoint, Duration::from_secs(2));
assert_eq!(capability.state, ConnectionState::ReachableNoModel);
}
#[test]
fn probe_reports_selected_model_unavailable() {
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
let mut request = ProbeRequest::new();
request.provider = Some("deepseek".into());
request.model = Some("does-not-exist".into());
let capability = probe(&http, &endpoint(), &request);
assert_eq!(capability.state, ConnectionState::SelectedModelUnavailable);
assert!(!capability.selected_model_available);
// The available model is accepted.
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
let mut request = ProbeRequest::new();
request.provider = Some("deepseek".into());
request.model = Some("deepseek-chat".into());
let capability = probe(&http, &endpoint(), &request);
assert_eq!(capability.state, ConnectionState::ModelCatalog);
assert!(capability.selected_model_available);
}
#[test]
fn probe_distinguishes_authentication_states() {
// No credential supplied → required.
let http = FakeHttp::new(vec![(401, r#"{"error":"unauthorized"}"#)]);
let capability = probe(&http, &endpoint(), &ProbeRequest::new());
fn probe_reports_authentication_required() {
let endpoint = spawn_server(vec![("/global/health", 401, r#"{"error":"unauthorized"}"#)]);
let capability = probe(&endpoint, Duration::from_secs(2));
assert_eq!(capability.state, ConnectionState::AuthenticationRequired);
// A credential was supplied and rejected.
let http = FakeHttp::new(vec![(401, "{}")]);
let mut request = ProbeRequest::new();
request.auth = Some(SecretString::new("wrong"));
let capability = probe(&http, &endpoint(), &request);
assert_eq!(capability.state, ConnectionState::AuthenticationRejected);
// Authentication accepted, then health+catalog.
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
let request = ProbeRequest {
auth: Some(SecretString::new("right")),
..ProbeRequest::new()
};
let capability = probe(&http, &endpoint(), &request);
assert_eq!(capability.state, ConnectionState::ModelCatalog);
// The credential is presented to the server but never returned.
assert!(http.requests.lock().unwrap()[0].auth.is_some());
assert!(capability.tcp_reachable);
}
#[test]
fn probe_reports_incompatible_and_unreachable() {
let http = FakeHttp::new(vec![(404, "{}")]);
assert_eq!(
probe(&http, &endpoint(), &ProbeRequest::new()).state,
ConnectionState::Incompatible
);
let http = FakeHttp::new(vec![(200, "<html>hi</html>")]);
assert_eq!(
probe(&http, &endpoint(), &ProbeRequest::new()).state,
ConnectionState::Incompatible
);
let http = FakeHttp::new(vec![]);
assert_eq!(
probe(&http, &endpoint(), &ProbeRequest::new()).state,
ConnectionState::Unreachable
);
}
#[test]
fn probe_rejects_an_insecure_destination_before_any_request() {
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
let public = Endpoint::parse("http://93.184.216.34:80").unwrap();
let capability = probe(&http, &public, &ProbeRequest::new());
assert_eq!(capability.state, ConnectionState::InsecureTransport);
assert!(
http.requests.lock().unwrap().is_empty(),
"no request may be sent"
);
}
#[test]
fn a_misleading_success_shaped_500_does_not_produce_a_catalog() {
// Health OK, but the catalog endpoint returns a providers-shaped body
// with a 500 status: it must not be parsed.
let shaped = r#"{"all":[{"id":"deepseek","models":{"m":{}}}],"connected":[]}"#;
let http = FakeHttp::new(vec![(200, health()), (500, shaped)]);
let capability = probe(&http, &endpoint(), &ProbeRequest::new());
fn probe_reports_incompatible_api() {
let endpoint = spawn_server(vec![("/global/health", 404, "{}")]);
let capability = probe(&endpoint, Duration::from_secs(2));
assert_eq!(capability.state, ConnectionState::Incompatible);
assert_eq!(capability.model_count, 0);
}
#[test]
fn an_empty_catalog_is_reachable_not_ready() {
let http = FakeHttp::new(vec![(200, health()), (200, r#"{"all":[],"connected":[]}"#)]);
let capability = probe(&http, &endpoint(), &ProbeRequest::new());
assert_eq!(capability.state, ConnectionState::Reachable);
assert_ne!(capability.state, ConnectionState::Ready);
fn probe_reports_disconnected_for_a_closed_port() {
let endpoint = Endpoint {
host: "127.0.0.1".into(),
port: 1,
};
let capability = probe(&endpoint, Duration::from_millis(300));
assert_eq!(capability.state, ConnectionState::Disconnected);
assert!(!capability.tcp_reachable);
}
/// Live check against a real `opencode serve`, enabled explicitly:
/// `PHOEBUS_OPENCODE_PROBE=http://127.0.0.1:4096 cargo test probe_live`.
#[test]
fn probe_live_server_when_configured() {
let Ok(url) = std::env::var("PHOEBUS_OPENCODE_PROBE") else {
return;
};
let endpoint = Endpoint::parse(&url).expect("valid probe endpoint");
let capability = probe(&endpoint, Duration::from_secs(3));
eprintln!("live opencode capability: {capability:?}");
assert!(
capability.tcp_reachable,
"server was not reachable: {capability:?}"
);
}
#[test]
fn capability_serialisation_has_no_credential_fields() {
let capability = Capability::new(ConnectionState::Ready, "1 provider(s)");
let capability = Capability {
state: ConnectionState::Ready,
tcp_reachable: true,
healthy: true,
server_version: Some("1.18.32".into()),
provider_count: 1,
model_count: 3,
detail: "1 provider(s), 3 model(s)".into(),
};
let json = serde_json::to_string(&capability).unwrap();
assert!(!json.to_lowercase().contains("key"));
assert!(!json.contains("sk-"));
}
}

View file

@ -1,386 +0,0 @@
//! Integration tests for the OpenCode HTTP client and protocol adapter over a
//! **real** local TCP server and the **real** curl transport.
//!
//! These exercise the parts the fake-client unit tests cannot: the curl config
//! encoding, HTTP status/marker parsing, de-chunking (including a multibyte
//! character split across chunks), body-size limits, redirect refusal, and the
//! request authentication. The server is a minimal hand-rolled HTTP/1.1
//! responder that terminates cleanly.
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;
use phoebus_core::{Redactor, SecretString};
use phoebus_executor::opencode_client::{CurlHttpClient, HttpClient, HttpRequest, OpenCodeClient};
use phoebus_executor::opencode_server::{probe, Endpoint, ProbeRequest};
use phoebus_executor::{Exec, Logger, RealRunner};
#[derive(Clone)]
struct Route {
method: String,
/// Exact path match, or a prefix if it ends with `*`, or any method when
/// `method` is `*`.
path: String,
status: u16,
body: Vec<u8>,
chunked: bool,
require_auth: Option<String>,
location: Option<String>,
close_without_response: bool,
}
impl Route {
fn get(path: &str, status: u16, body: &str) -> Self {
Self {
method: "GET".into(),
path: path.into(),
status,
body: body.as_bytes().to_vec(),
chunked: false,
require_auth: None,
location: None,
close_without_response: false,
}
}
fn method(method: &str, path: &str, status: u16, body: &str) -> Self {
let mut route = Self::get(path, status, body);
route.method = method.into();
route
}
fn matches(&self, method: &str, path: &str) -> bool {
if self.method != "*" && self.method != method {
return false;
}
if let Some(prefix) = self.path.strip_suffix('*') {
path.starts_with(prefix)
} else {
path == self.path
}
}
}
struct Server {
port: u16,
stop: Arc<AtomicBool>,
auth_seen: Arc<Mutex<Vec<String>>>,
}
impl Drop for Server {
fn drop(&mut self) {
self.stop.store(true, Ordering::SeqCst);
}
}
fn spawn_server(mut routes: Vec<Route>) -> Server {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
listener.set_nonblocking(true).unwrap();
let stop = Arc::new(AtomicBool::new(false));
let stop_thread = stop.clone();
let auth_seen = Arc::new(Mutex::new(Vec::new()));
let auth_thread = auth_seen.clone();
thread::spawn(move || {
while !stop_thread.load(Ordering::SeqCst) {
match listener.accept() {
Ok((mut stream, _)) => {
let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));
let _ = handle(&mut stream, &mut routes, &auth_thread);
}
Err(ref e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(5));
}
Err(_) => break,
}
}
});
Server {
port,
stop,
auth_seen,
}
}
fn handle(
stream: &mut TcpStream,
routes: &mut Vec<Route>,
auth_seen: &Arc<Mutex<Vec<String>>>,
) -> std::io::Result<()> {
let mut buf = [0u8; 16384];
let n = stream.read(&mut buf)?;
if n == 0 {
return Ok(());
}
let request = String::from_utf8_lossy(&buf[..n]).to_string();
let mut lines = request.lines();
let request_line = lines.next().unwrap_or("");
let mut parts = request_line.split_whitespace();
let method = parts.next().unwrap_or("").to_string();
let path = parts.next().unwrap_or("").to_string();
let auth = request
.lines()
.find_map(|l| {
l.strip_prefix("Authorization:")
.map(|v| v.trim().to_string())
})
.unwrap_or_default();
if !auth.is_empty() {
auth_seen.lock().unwrap().push(auth.clone());
}
// Routes are permanent: a test may issue the same request more than once
// (e.g. once unauthenticated, once authenticated).
let Some(route) = routes.iter().find(|r| r.matches(&method, &path)).cloned() else {
let body = b"{}";
write_response(stream, 404, &[], body, false, None)?;
return Ok(());
};
if route.close_without_response {
return Ok(()); // drop the stream without a response
}
if let Some(expected) = &route.require_auth {
if &auth != expected {
write_response(stream, 401, &[], b"{}", false, None)?;
return Ok(());
}
}
write_response(
stream,
route.status,
&[],
&route.body,
route.chunked,
route.location.as_deref(),
)
}
fn write_response(
stream: &mut TcpStream,
status: u16,
extra: &[(String, String)],
body: &[u8],
chunked: bool,
location: Option<&str>,
) -> std::io::Result<()> {
let mut head = format!("HTTP/1.1 {status} X\r\n");
if let Some(location) = location {
head.push_str(&format!("Location: {location}\r\n"));
}
for (k, v) in extra {
head.push_str(&format!("{k}: {v}\r\n"));
}
if chunked {
head.push_str("Transfer-Encoding: chunked\r\n");
} else {
head.push_str(&format!("Content-Length: {}\r\n", body.len()));
}
head.push_str("Connection: close\r\n\r\n");
stream.write_all(head.as_bytes())?;
if chunked {
// Split the body into small chunks; the first cut may fall inside a
// multibyte UTF-8 sequence.
for chunk in body.chunks(3) {
stream.write_all(format!("{:x}\r\n", chunk.len()).as_bytes())?;
stream.write_all(chunk)?;
stream.write_all(b"\r\n")?;
}
stream.write_all(b"0\r\n\r\n")?;
} else {
stream.write_all(body)?;
}
stream.flush()
}
fn test_exec() -> Exec {
let dir = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(dir.join("opencode.log"), Redactor::new(), false);
Exec::new(Box::new(RealRunner), logger, false, dir.clone(), dir)
}
fn base(port: u16) -> String {
format!("http://127.0.0.1:{port}")
}
#[test]
fn curl_transport_round_trips_and_preserves_status() {
let server = spawn_server(vec![
Route::get("/global/health", 200, r#"{"healthy":true}"#),
Route::get("/provider", 500, r#"{"all":[{"id":"x","models":{}}]}"#),
]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
let ok = http
.request(&HttpRequest::get(format!(
"{}/global/health",
base(server.port)
)))
.unwrap();
assert_eq!(ok.status, 200);
assert!(ok.body.contains("healthy"));
// A 500 with a providers-shaped body is a 500; the status is not discarded.
let failure = http
.request(&HttpRequest::get(format!("{}/provider", base(server.port))))
.unwrap();
assert_eq!(failure.status, 500);
}
#[test]
fn curl_transport_dechunks_a_multibyte_body_split_across_chunks() {
// "héllo wörld" in UTF-8; chunk boundaries at 3 bytes split the multibyte
// characters. curl must reassemble the bytes before we decode them.
let text = "héllo wörld";
let server = spawn_server(vec![Route {
chunked: true,
..Route::get("/chunked", 200, text)
}]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
let response = http
.request(&HttpRequest::get(format!("{}/chunked", base(server.port))))
.unwrap();
assert_eq!(response.status, 200);
assert_eq!(response.body, text);
}
#[test]
fn curl_transport_refuses_an_oversized_body() {
let big = "x".repeat(2 * 1024 * 1024);
let server = spawn_server(vec![Route::get("/big", 200, &big)]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
let mut request = HttpRequest::get(format!("{}/big", base(server.port)));
request.max_body = 4096;
assert!(
http.request(&request).is_err(),
"an oversized body must fail"
);
}
#[test]
fn curl_transport_does_not_follow_redirects() {
let mut redirect = Route::get("/redir", 302, "");
redirect.location = Some("/final".into());
let server = spawn_server(vec![redirect, Route::get("/final", 200, "landed")]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
let response = http
.request(&HttpRequest::get(format!("{}/redir", base(server.port))))
.unwrap();
assert_eq!(response.status, 302, "a redirect must not be followed");
assert!(!response.body.contains("landed"));
}
#[test]
fn curl_transport_reports_an_abrupt_disconnect() {
let server = spawn_server(vec![Route {
close_without_response: true,
..Route::get("/drop", 200, "")
}]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
assert!(http
.request(&HttpRequest::get(format!("{}/drop", base(server.port))))
.is_err());
}
#[test]
fn opencode_client_adapts_over_real_http() {
let server = spawn_server(vec![
Route::get(
"/global/health",
200,
r#"{"healthy":true,"version":"1.18.32"}"#,
),
Route::get(
"/provider",
200,
r#"{"all":[{"id":"deepseek","name":"DeepSeek","models":{"deepseek-chat":{}}}],
"connected":["deepseek"],"default":{"deepseek":"deepseek-chat"}}"#,
),
Route::method("POST", "/session", 200, r#"{"id":"ses_abc"}"#),
Route::method(
"POST",
"/session/ses_abc/message",
200,
r#"{"info":{"role":"assistant","time":{"created":1,"completed":2}},
"parts":[{"type":"text","text":"{\"version\":1}"}]}"#,
),
Route::method("DELETE", "/session/ses_abc", 200, "true"),
]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
let endpoint = Endpoint::parse(&base(server.port)).unwrap();
let mut request = ProbeRequest::new();
request.provider = Some("deepseek".into());
request.model = Some("deepseek-chat".into());
let capability = probe(&http, &endpoint, &request);
assert_eq!(
capability.state,
phoebus_executor::opencode_server::ConnectionState::ModelCatalog
);
assert!(capability.selected_model_available);
let client = OpenCodeClient::new(&http, base(server.port), "deepseek", "deepseek-chat");
let reply = client.one_shot("system", "user").unwrap();
assert_eq!(reply.content, "{\"version\":1}");
assert!(reply.completed);
}
#[test]
fn authentication_is_required_and_presented() {
// The endpoint demands basic auth; the matching header is recorded.
// base64("opencode:sekret").
let required = "Basic b3BlbmNvZGU6c2VrcmV0".to_string();
let mut route = Route::get(
"/provider",
200,
r#"{"all":[{"id":"x","models":{"m":{}}}],"connected":[]}"#,
);
route.require_auth = Some(required.clone());
let server = spawn_server(vec![
Route {
require_auth: Some(required),
..Route::get("/global/health", 200, r#"{"healthy":true}"#)
},
route,
]);
let exec = test_exec();
let http = CurlHttpClient::new(&exec);
let endpoint = Endpoint::parse(&base(server.port)).unwrap();
// Without a credential the probe reports "authentication required".
let mut request = ProbeRequest::new();
request.provider = Some("x".into());
request.model = Some("m".into());
let capability = probe(&http, &endpoint, &request);
assert_eq!(
capability.state,
phoebus_executor::opencode_server::ConnectionState::AuthenticationRequired
);
// With the credential it succeeds and the header was actually sent.
let mut request = ProbeRequest::new();
request.auth = Some(SecretString::new("sekret"));
let capability = probe(&http, &endpoint, &request);
assert_eq!(
capability.state,
phoebus_executor::opencode_server::ConnectionState::ModelCatalog,
"{capability:?}"
);
assert!(
server
.auth_seen
.lock()
.unwrap()
.iter()
.any(|h| h.starts_with("Basic ")),
"the Authorization header never reached the server"
);
}

View file

@ -1,140 +0,0 @@
//! Live OpenCode acceptance test.
//!
//! This is the only test that proves **real model inference** through OpenCode.
//! It is skipped unless the environment names a server, provider and model:
//!
//! ```sh
//! PHOEBUS_OPENCODE_LIVE_URL=http://127.0.0.1:4096 \
//! PHOEBUS_OPENCODE_LIVE_PROVIDER=deepseek \
//! PHOEBUS_OPENCODE_LIVE_MODEL=deepseek-chat \
//! cargo test -p phoebus-executor --test opencode_live -- --nocapture
//! ```
//!
//! When `PHOEBUS_OPENCODE_REQUIRE_LIVE=1` is set (as `make opencode-acceptance`
//! does), a missing configuration is a hard failure, so an acceptance command
//! cannot pass by silently not running.
use std::time::Duration;
use phoebus_core::SecretString;
use phoebus_executor::opencode_client::{CurlHttpClient, OpenCodeClient};
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint, ProbeRequest};
use phoebus_executor::{Exec, Logger, RealRunner};
struct Live {
url: String,
provider: String,
model: String,
password: Option<SecretString>,
}
fn live() -> Option<Live> {
let url = std::env::var("PHOEBUS_OPENCODE_LIVE_URL").unwrap_or_default();
let provider = std::env::var("PHOEBUS_OPENCODE_LIVE_PROVIDER").unwrap_or_default();
let model = std::env::var("PHOEBUS_OPENCODE_LIVE_MODEL").unwrap_or_default();
let required = std::env::var("PHOEBUS_OPENCODE_REQUIRE_LIVE")
.map(|v| matches!(v.as_str(), "1" | "yes" | "true"))
.unwrap_or(false);
if url.trim().is_empty() || provider.trim().is_empty() || model.trim().is_empty() {
if required {
panic!(
"BLOCKED: a live OpenCode acceptance run was required, but \
PHOEBUS_OPENCODE_LIVE_URL/PROVIDER/MODEL are not all set"
);
}
eprintln!(
"SKIPPED: set PHOEBUS_OPENCODE_LIVE_URL, PHOEBUS_OPENCODE_LIVE_PROVIDER and \
PHOEBUS_OPENCODE_LIVE_MODEL to run the live acceptance test"
);
return None;
}
let password = match std::env::var("PHOEBUS_OPENCODE_LIVE_PASSWORD_FILE") {
Ok(path) if !path.is_empty() => {
Some(phoebus_executor::ai::load_api_key(std::path::Path::new(&path)).unwrap())
}
_ => None,
};
Some(Live {
url,
provider,
model,
password,
})
}
fn exec() -> Exec {
let dir = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(
dir.join("opencode-live.log"),
phoebus_core::Redactor::new(),
false,
);
Exec::new(Box::new(RealRunner), logger, false, dir.clone(), dir)
}
#[test]
fn live_inference_through_opencode() {
let Some(live) = live() else { return };
let exec = exec();
let http = CurlHttpClient::new(&exec);
let endpoint = Endpoint::parse(&live.url).expect("a valid live endpoint");
// 1. The catalog must list the selected model.
let mut request = ProbeRequest::new();
request.provider = Some(live.provider.clone());
request.model = Some(live.model.clone());
request.auth = live.password.clone();
let capability = probe(&http, &endpoint, &request);
eprintln!("live capability: {capability:?}");
assert!(
matches!(
capability.state,
ConnectionState::ModelCatalog | ConnectionState::SelectedModelUnavailable
),
"the live server is not usable: {capability:?}"
);
assert!(
capability.selected_model_available,
"the selected model {}:{} is not in the catalog: {capability:?}",
live.provider, live.model
);
// 2. A real inference round-trip must return a valid JSON response.
let client = OpenCodeClient::new(&http, endpoint.base(), &live.provider, &live.model)
.with_auth(live.password.clone())
.with_timeout(Duration::from_secs(120));
let reply = client
.one_shot(
"You are a connectivity test. Reply with JSON only.",
"Reply with exactly {\"phoebus\":\"ok\"} and nothing else.",
)
.unwrap_or_else(|e| panic!("live inference failed: {e}"));
let value: serde_json::Value =
serde_json::from_str(&reply.content).expect("the live model returned non-JSON");
assert_eq!(
value.get("phoebus").and_then(|v| v.as_str()),
Some("ok"),
"the live model did not follow the instruction: {}",
reply.content
);
eprintln!("live inference OK: {}", reply.content);
}
#[test]
fn live_endpoint_is_reported_truthfully() {
let Some(live) = live() else { return };
let exec = exec();
let http = CurlHttpClient::new(&exec);
let endpoint = Endpoint::parse(&live.url).unwrap();
// A deliberate wrong model must be reported as unavailable, not accepted.
let mut request = ProbeRequest::new();
request.provider = Some(live.provider.clone());
request.model = Some("definitely-not-a-real-model-xyz".into());
request.auth = live.password.clone();
let capability = probe(&http, &endpoint, &request);
assert_eq!(
capability.state,
ConnectionState::SelectedModelUnavailable,
"an unknown model was not reported as unavailable: {capability:?}"
);
}

View file

@ -11,11 +11,10 @@ use std::process::ExitCode;
use clap::Parser;
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
use phoebus_ai::provider::{ProviderKind, SystemFacts};
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
use phoebus_core::transaction::TransactionRecord;
use phoebus_core::{AiBackend, InstallConfig, Redactor};
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
use phoebus_core::{InstallConfig, Redactor};
use phoebus_executor::{
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization,
Exec, Logger, RealRunner, Result,
@ -62,26 +61,6 @@ struct Cli {
/// Run the assistant without the OS-level sandbox (development only).
#[arg(long)]
no_sandbox: bool,
/// AI backend for `sys ask`: `direct` (default) or `opencode`.
#[arg(long, value_name = "BACKEND")]
ai_backend: Option<String>,
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
#[arg(long, value_name = "URL")]
opencode_server: Option<String>,
/// OpenCode provider id (e.g. `deepseek`).
#[arg(long, value_name = "PROVIDER")]
opencode_provider: Option<String>,
/// OpenCode model id (e.g. `deepseek-chat`).
#[arg(long, value_name = "MODEL")]
opencode_model: Option<String>,
/// Read the OpenCode server password from a mode-0600 file.
#[arg(long, value_name = "FILE")]
opencode_password_file: Option<PathBuf>,
}
struct SysConfirm {
@ -235,16 +214,6 @@ fn gather_facts(exec: &Exec) -> SystemFacts {
SystemFacts::from_system(&config, &hardware, &history, binhost, None)
}
/// The AI backend selected on the command line or the environment.
fn resolve_backend(cli: &Cli) -> AiBackend {
let raw = cli
.ai_backend
.clone()
.or_else(|| std::env::var("PHOEBUS_AI_BACKEND").ok())
.unwrap_or_default();
AiBackend::parse(&raw).unwrap_or(AiBackend::Direct)
}
/// The provider selected on the command line or the environment.
fn resolve_provider(cli: &Cli) -> ProviderKind {
let raw = cli
@ -301,105 +270,41 @@ fn run_ask(
exec: &Exec,
instruction: &str,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let facts = gather_facts(exec);
let backend = resolve_backend(cli);
let (provider, endpoint, model);
let transport: Box<dyn ModelTransport + '_>;
match backend {
AiBackend::OpenCode => {
let server = cli
.opencode_server
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
.unwrap_or_default();
let opencode_provider = cli
.opencode_provider
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
.unwrap_or_default();
let opencode_model = cli
.opencode_model
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
.unwrap_or_default();
if server.trim().is_empty()
|| opencode_provider.trim().is_empty()
|| opencode_model.trim().is_empty()
{
deterministic_fallback(instruction);
return Err(
"OpenCode requires --opencode-server, --opencode-provider and --opencode-model"
.into(),
);
}
let password = match &cli.opencode_password_file {
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
None => None,
};
eprintln!(
"Sending these bounded system facts through the OpenCode server at {} \
(provider {}, model {}); no passwords, files or home directories:",
server, opencode_provider, opencode_model
);
eprintln!("{}", facts.render());
provider = ProviderKind::Local;
endpoint = server;
model = opencode_model;
transport = Box::new(
ExecOpenCodeTransport::new(
exec,
endpoint.clone(),
opencode_provider,
model.clone(),
)
.with_auth(password),
);
}
AiBackend::Direct => {
let resolved = resolve_provider(cli);
if resolved == ProviderKind::None {
let provider = resolve_provider(cli);
if provider == ProviderKind::None {
deterministic_fallback(instruction);
return Err("no AI provider configured".into());
}
let endpoint = resolve_endpoint(cli, provider);
let model = resolve_model(cli);
let key = match api_key_file(cli) {
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
None => None,
};
if resolved.requires_key() && key.is_none() {
if provider.requires_key() && key.is_none() {
deterministic_fallback(instruction);
return Err(format!(
"provider `{}` requires --ai-api-key-file (mode 0600)",
resolved.as_str()
provider.as_str()
)
.into());
}
let facts = gather_facts(exec);
eprintln!(
"Sending these bounded system facts to {} \
(no passwords, files or home directories):",
resolved.as_str()
"Sending these bounded system facts to {} (no passwords, files or home directories):",
provider.as_str()
);
eprintln!("{}", facts.render());
provider = resolved;
endpoint = resolve_endpoint(cli, resolved);
model = resolve_model(cli);
let direct = phoebus_executor::ai::CurlTransport::new(exec, key);
transport = if cli.no_sandbox {
Box::new(direct)
} else {
Box::new(direct.sandboxed())
};
}
}
let plan: AssistantPlan = match complete_plan(
provider,
&endpoint,
&model,
&facts,
instruction,
transport.as_ref(),
) {
let transport = phoebus_executor::ai::CurlTransport::new(exec, key);
let transport = if cli.no_sandbox {
transport
} else {
transport.sandboxed()
};
let plan: AssistantPlan =
match complete_plan(provider, &endpoint, &model, &facts, instruction, &transport) {
Ok(plan) => plan,
Err(e) => {
eprintln!("The model is unavailable or returned an unusable plan: {e}");

View file

@ -18,10 +18,9 @@ use std::io::{self, BufRead, Write};
use crate::{ai_guide, InstallObserver, Installer};
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
use phoebus_core::{AiBackend, InstallConfig, InstallStep, SecretString};
use phoebus_core::{InstallConfig, InstallStep, SecretString};
use phoebus_executor::ai::CurlTransport;
use phoebus_executor::auth::{authorize, Confirmation};
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
use phoebus_executor::{Exec, Result as ExecResult};
use serde::Deserialize;
@ -71,10 +70,6 @@ struct SecretsPatch {
root_password: Option<String>,
#[serde(default)]
ai_api_key: Option<String>,
/// The OpenCode server password (basic auth). Distinct from a model
/// provider API key and never stored in the configuration.
#[serde(default)]
opencode_password: Option<String>,
}
/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE
@ -169,12 +164,7 @@ pub struct Bridge {
user_password: Option<SecretString>,
root_password: Option<SecretString>,
api_key: Option<SecretString>,
opencode_password: Option<SecretString>,
approved_digest: Option<String>,
/// Set only after a real, validated AI interaction (a proposal reviewed for
/// the direct path, or a validated model response for OpenCode). A mere
/// provider name never satisfies the mandatory-AI gate.
validated_ai: Option<String>,
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
/// One destructive transaction at a time. An approval is single-use: it is
/// consumed when the install starts so a replay, a second frontend or a
@ -193,9 +183,7 @@ impl Bridge {
user_password: None,
root_password: None,
api_key: None,
opencode_password: None,
approved_digest: None,
validated_ai: None,
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
installing: false,
installed: false,
@ -211,9 +199,7 @@ impl Bridge {
user_password: None,
root_password: None,
api_key: None,
opencode_password: None,
approved_digest: None,
validated_ai: None,
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
installing: false,
installed: false,
@ -265,7 +251,6 @@ impl Bridge {
"plan" => self.plan(),
"destructive_preview" => self.destructive_preview(),
"ai_check" => self.ai_check(),
"ai_test" => self.ai_test(),
"approve" => self.approve(&request),
"start_install" => return self.start_install(id, &request, out),
"log_tail" => self.log_tail(&request),
@ -420,9 +405,6 @@ impl Bridge {
self.installer.reconfigure(config);
self.approved_digest = None;
// A configuration change (provider, model, endpoint, server) invalidates
// any previous AI validation.
self.validated_ai = None;
let issues = self.installer.validate();
Ok(json!({
"accepted": true,
@ -445,7 +427,6 @@ impl Bridge {
&patch.user_password,
&patch.root_password,
&patch.ai_api_key,
&patch.opencode_password,
]
.into_iter()
.flatten()
@ -474,20 +455,12 @@ impl Bridge {
self.installer.exec.register_secret(&s);
self.api_key = Some(s);
}
if let Some(v) = &patch.opencode_password {
let s = SecretString::new(v.clone());
self.installer.exec.register_secret(&s);
self.opencode_password = Some(s);
}
// A credential change invalidates any previous AI validation.
self.validated_ai = None;
// Report only presence, never values.
Ok(json!({
"luks_set": self.luks.is_some(),
"user_password_set": self.user_password.is_some(),
"root_password_set": self.root_password.is_some(),
"ai_api_key_set": self.api_key.is_some(),
"opencode_password_set": self.opencode_password.is_some(),
}))
}
@ -495,107 +468,33 @@ impl Bridge {
fn ai_check(&mut self) -> Result<Value, String> {
let facts = self.installer.system_facts();
let backend = self.installer.config.ai.backend;
let api_key = self.api_key.clone();
let opencode_password = self.opencode_password.clone();
let value = {
let Installer { exec, config, .. } = &mut self.installer;
let redactor = exec.redactor();
match backend {
AiBackend::OpenCode => {
let transport = opencode_transport(exec, config, opencode_password)?;
review_opencode(config, redactor, facts, &transport)?
}
AiBackend::Direct => {
let api_key_present = self.api_key.is_some();
let Bridge {
installer,
api_key,
approved_digest,
..
} = self;
let Installer { exec, config, .. } = installer;
let transport = CurlTransport::new(exec, api_key.clone());
review_proposal(config, redactor, facts, api_key.is_some(), &transport)?
}
}
};
self.approved_digest = None;
// Bind the validated interaction to the exact configuration it was
// validated against; any later change clears it.
self.validated_ai = Some(self.plan_digest());
let value = review_proposal(config, exec.redactor(), facts, api_key_present, &transport)?;
*approved_digest = None;
Ok(value)
}
/// A real, minimal model interaction that obtains and validates a JSON model
/// response without changing the configuration. This is "Test connection".
fn ai_test(&mut self) -> Result<Value, String> {
use phoebus_ai::provider::{build_request, extract_content};
let backend = self.installer.config.ai.backend;
let facts = self.installer.system_facts();
let redactor = self.installer.exec.redactor();
let (kind, endpoint, model, label) = match backend {
AiBackend::OpenCode => {
let (server, provider, model) = opencode_parts(&self.installer.config)?;
(ProviderKind::Local, server, model, provider)
}
AiBackend::Direct => {
let raw = self.installer.config.ai.provider.clone();
let provider = ProviderKind::parse(&raw)
.ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
if provider == ProviderKind::None {
return Err("no AI provider selected".into());
}
let endpoint = if self.installer.config.ai.endpoint.is_empty() {
provider.endpoint().to_string()
} else {
self.installer.config.ai.endpoint.clone()
};
let model = if self.installer.config.ai.model.is_empty() {
provider.default_model().to_string()
} else {
self.installer.config.ai.model.clone()
};
(provider, endpoint, model, provider.as_str().to_string())
}
};
let request = build_request(kind, &model, &facts);
let body = serde_json::to_string(&request)
.map_err(|e| format!("could not build the test request: {e}"))?;
let response = match backend {
AiBackend::OpenCode => {
let (server, provider, model) = opencode_parts(&self.installer.config)?;
let transport =
ExecOpenCodeTransport::new(&self.installer.exec, server, provider, model)
.with_auth(self.opencode_password.clone());
transport.send(kind, &endpoint, &body)
}
AiBackend::Direct => {
let transport = CurlTransport::new(&self.installer.exec, self.api_key.clone());
transport.send(kind, &endpoint, &body)
}
}
.map_err(|e| format!("connection failed: {}", redactor.redact(&e.to_string())))?;
let content = extract_content(&response).map_err(|e| {
format!(
"model response was not usable: {}",
redactor.redact(&e.to_string())
)
})?;
serde_json::from_str::<serde_json::Value>(&content)
.map_err(|_| "model response was not JSON".to_string())?;
Ok(json!({
"connected": true,
"backend": backend.as_str(),
"provider": label,
"model": model,
"response": content,
}))
}
/// Validate the provider connection and review the proposal (fail-closed).
/// Exposed so tests can drive it with a canned transport.
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
let facts = self.installer.system_facts();
let api_key_present = self.api_key.is_some();
let value = {
let Installer { exec, config, .. } = &mut self.installer;
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
};
self.approved_digest = None;
self.validated_ai = Some(self.plan_digest());
let Bridge {
installer,
approved_digest,
..
} = self;
let Installer { exec, config, .. } = installer;
let value = review_proposal(config, exec.redactor(), facts, api_key_present, transport)?;
*approved_digest = None;
Ok(value)
}
@ -659,20 +558,18 @@ impl Bridge {
}
// AI is mandatory to install unless this is a dry run or an explicit
// break-glass. A validated interaction is required: merely naming a
// provider is not enough. The validation is bound to the current
// configuration, so a change since validation invalidates it.
// break-glass (mirrors the CLI rule).
let dry_run = self.installer.config.runtime.dry_run;
if !dry_run {
let provider = ProviderKind::parse(&self.installer.config.ai.provider)
.unwrap_or(ProviderKind::None);
let break_glass = std::env::var("PHOEBUS_NO_AI")
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
.unwrap_or(false);
let validated = self.validated_ai.as_deref() == Some(current.as_str());
if !validated && !break_glass {
if provider == ProviderKind::None && !break_glass {
return Err(
"installing Phoebus requires a successful, validated AI interaction for \
the current configuration; connect and validate a model, or set \
PHOEBUS_NO_AI=1 for a deterministic install"
"installing Phoebus requires a connected AI model; connect a provider \
or set PHOEBUS_NO_AI=1 for a deterministic install"
.into(),
);
}
@ -705,7 +602,6 @@ impl Bridge {
// Consume the approval and mark the session busy before any destructive
// work: a replay or a second frontend can never reach storage_prepare.
self.approved_digest = None;
self.validated_ai = None;
self.installing = true;
let outcome = self.installer.install_observed(
&auth,
@ -861,109 +757,8 @@ fn config_digest(config: &InstallConfig) -> String {
format!("{:x}", hasher.finalize())
}
/// The OpenCode server URL, provider id and model id, validated for presence.
fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String), String> {
let server = config.ai.opencode_server.trim().to_string();
let provider = config.ai.opencode_provider.trim().to_string();
let model = config.ai.opencode_model.trim().to_string();
if server.is_empty() {
return Err("OpenCode requires a server URL".into());
}
if provider.is_empty() {
return Err("OpenCode requires a provider".into());
}
if model.is_empty() {
return Err("OpenCode requires a model".into());
}
// Fail fast on an unsafe endpoint, before any request is attempted.
phoebus_executor::opencode_server::Endpoint::parse(&server)
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
Ok((server, provider, model))
}
fn opencode_transport<'a>(
exec: &'a Exec,
config: &InstallConfig,
password: Option<SecretString>,
) -> Result<phoebus_executor::opencode_client::ExecOpenCodeTransport<'a>, String> {
let (server, provider, model) = opencode_parts(config)?;
Ok(
phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
exec, server, provider, model,
)
.with_auth(password),
)
}
#[allow(clippy::too_many_arguments)]
fn finish_review(
config: &mut InstallConfig,
redactor: &phoebus_core::Redactor,
facts: SystemFacts,
kind: ProviderKind,
endpoint: &str,
provider_label: &str,
model: &str,
transport: &dyn ModelTransport,
backend: &str,
) -> Result<Value, String> {
let outcome =
ai_guide::generate_and_review_at(config, &facts, kind, endpoint, model, transport)
.map_err(|e| {
// Error messages are redacted before they reach the GUI.
format!(
"connection or proposal failed: {}",
redactor.redact(&e.to_string())
)
})?;
let applied: Vec<Value> = outcome
.applied
.iter()
.map(|c| {
json!({
"description": c.description,
"reason": c.reason,
"evidence": c.evidence,
})
})
.collect();
Ok(json!({
"connected": true,
"backend": backend,
"provider": provider_label,
"model": model,
"endpoint": endpoint,
"applied": applied,
"config": config,
"plan_digest": config_digest(config),
}))
}
/// OpenCode proposal review: the adapter talks the agent protocol and the
/// shared strict proposal parser/review applies the accepted changes.
fn review_opencode(
config: &mut InstallConfig,
redactor: &phoebus_core::Redactor,
facts: SystemFacts,
transport: &dyn ModelTransport,
) -> Result<Value, String> {
let (server, provider_id, model) = opencode_parts(config)?;
finish_review(
config,
redactor,
facts,
ProviderKind::Local,
&server,
&provider_id,
&model,
transport,
"opencode",
)
}
/// Parse the direct provider from the configuration, validate the connection
/// and apply the reviewed proposal. This is the same `ai_guide` path the TUI
/// uses.
/// Parse the provider from the configuration, validate the connection and apply
/// the reviewed proposal. This is the same `ai_guide` path the TUI uses.
fn review_proposal(
config: &mut InstallConfig,
redactor: &phoebus_core::Redactor,
@ -993,17 +788,36 @@ fn review_proposal(
provider.as_str()
));
}
finish_review(
config,
redactor,
facts,
provider,
&endpoint,
provider.as_str(),
&model,
transport,
"direct",
let outcome =
ai_guide::generate_and_review_at(config, &facts, provider, &endpoint, &model, transport)
.map_err(|e| {
// Error messages are redacted before they reach the GUI.
format!(
"connection or proposal failed: {}",
redactor.redact(&e.to_string())
)
})?;
let applied: Vec<Value> = outcome
.applied
.iter()
.map(|c| {
json!({
"description": c.description,
"reason": c.reason,
"evidence": c.evidence,
})
})
.collect();
Ok(json!({
"connected": true,
"provider": provider.as_str(),
"model": model,
"endpoint": endpoint,
"applied": applied,
"config": config,
"plan_digest": config_digest(config),
}))
}
/// The stdio entry point used by `--gui-bridge`.
@ -1461,173 +1275,4 @@ mod tests {
let lines = call(&mut bridge, &line);
assert_eq!(response(&lines)["ok"], json!(false));
}
/// A non-dry bridge whose runner reports `/dev/vda`, so revalidation and
/// the install stages run against the fake runner (never a real disk).
fn test_bridge_non_dry() -> Bridge {
let runner = RecordingRunner::new();
runner.set_response(
"lsblk",
phoebus_executor::CommandOutput {
status: 0,
success: true,
stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(),
stderr: Vec::new(),
duration: std::time::Duration::from_millis(1),
},
);
let dir = tempfile::tempdir().unwrap().keep();
let logger = Logger::open(dir.join("install.log"), Redactor::new(), false);
let mut config = InstallConfig::default();
config.runtime.dry_run = false;
config.system.hostname = "phoebus".into();
config.system.timezone = "UTC".into();
config.user.username = "tester".into();
config.storage.disk = "/dev/vda".into();
let exec = Exec::new(
Box::new(runner),
logger,
false,
dir.join("root"),
dir.clone(),
);
let mut installer = Installer::new(config, exec);
installer.disks.push(Disk {
path: "/dev/vda".into(),
model: Some("QEMU HARDDISK".into()),
size_bytes: 30 * 1024 * 1024 * 1024,
transport: Some("virtio".into()),
removable: false,
read_only: false,
mounted: false,
is_block_device: true,
kind: DiskKind::Physical,
live_media: false,
});
Bridge::with_installer(installer)
}
fn arm_ai(bridge: &mut Bridge) -> Value {
let mut c = config_json(bridge);
c["ai"]["provider"] = json!("deepseek");
c["ai"]["model"] = json!("deepseek-chat");
let _ = call(
bridge,
&json!({ "id": 30, "op": "set_config", "config": c }).to_string(),
);
bridge.api_key = Some(SecretString::new("test-key"));
let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["x"]}]}"#;
bridge
.ai_check_with(&TestTransport::proposal(proposal))
.expect("ai_check")
}
fn start(bridge: &mut Bridge, digest: &str) -> Value {
let lines = call(
bridge,
&json!({
"id": 31, "op": "start_install", "erase": "ERASE",
"final_confirm": true, "plan_digest": digest
})
.to_string(),
);
response(&lines)
}
#[test]
fn a_provider_name_alone_does_not_satisfy_the_ai_requirement() {
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
// Provider configured and key present, but no validated interaction.
let mut c = config_json(&bridge);
c["ai"]["provider"] = json!("deepseek");
let _ = call(
&mut bridge,
&json!({ "id": 40, "op": "set_config", "config": c }).to_string(),
);
bridge.api_key = Some(SecretString::new("test-key"));
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
assert_eq!(resp["ok"], json!(false));
assert!(
resp["error"]
.as_str()
.unwrap()
.contains("validated AI interaction"),
"unexpected error: {}",
resp["error"]
);
}
#[test]
fn a_validated_interaction_satisfies_the_ai_requirement() {
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
arm_ai(&mut bridge);
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
// It may fail later in the fake storage stage, but never on the AI gate.
assert!(
!resp["error"]
.as_str()
.unwrap_or("")
.contains("validated AI interaction"),
"the AI gate wrongly rejected a validated interaction: {}",
resp["error"]
);
}
#[test]
fn a_config_change_invalidates_the_validated_interaction() {
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
arm_ai(&mut bridge);
// Change the model after validation.
let mut c = config_json(&bridge);
c["ai"]["model"] = json!("deepseek-reasoner");
let _ = call(
&mut bridge,
&json!({ "id": 41, "op": "set_config", "config": c }).to_string(),
);
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
assert_eq!(resp["ok"], json!(false));
assert!(resp["error"]
.as_str()
.unwrap()
.contains("validated AI interaction"));
}
#[test]
fn a_secret_change_invalidates_the_validated_interaction() {
let mut bridge = test_bridge_non_dry();
set_valid_config(&mut bridge);
arm_ai(&mut bridge);
let _ = call(
&mut bridge,
r#"{"id":42,"op":"set_secrets","secrets":{"ai_api_key":"new-key"}}"#,
);
let (digest, _) = approve(&mut bridge);
let resp = start(&mut bridge, &digest);
assert_eq!(resp["ok"], json!(false));
assert!(resp["error"]
.as_str()
.unwrap()
.contains("validated AI interaction"));
}
#[test]
fn ai_test_is_a_known_operation_and_fails_without_a_provider() {
let mut bridge = test_bridge();
let lines = call(&mut bridge, r#"{"id":43,"op":"ai_test"}"#);
let resp = response(&lines);
// Not "unknown op": the operation exists and reports the configuration
// problem instead.
assert_eq!(resp["ok"], json!(false));
assert!(
!resp["error"].as_str().unwrap().contains("unknown op"),
"{}",
resp["error"]
);
}
}

View file

@ -122,36 +122,10 @@ struct Cli {
gui_bridge: bool,
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
/// its capability as JSON. Read-only; exits nonzero unless a model catalog
/// is available. Never prints provider credentials.
/// its capability as JSON. Read-only; exits nonzero unless a model is
/// available. Never prints provider credentials.
#[arg(long, value_name = "URL")]
opencode_probe: Option<String>,
/// Obtain a real model response through an OpenCode server and validate it,
/// then exit. This is the acceptance test for inference, not reachability.
#[arg(long, value_name = "URL")]
opencode_test: Option<String>,
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
#[arg(long, value_name = "URL")]
opencode_server: Option<String>,
/// OpenCode provider id (e.g. `deepseek`).
#[arg(long, value_name = "PROVIDER")]
opencode_provider: Option<String>,
/// OpenCode model id (e.g. `deepseek-chat`).
#[arg(long, value_name = "MODEL")]
opencode_model: Option<String>,
/// Read the OpenCode server password from a mode-0600 file (distinct from a
/// model provider API key).
#[arg(long, value_name = "FILE")]
opencode_password_file: Option<PathBuf>,
/// AI backend for install guidance: `direct` (default) or `opencode`.
#[arg(long, value_name = "BACKEND")]
ai_backend: Option<String>,
}
struct TerminalConfirm;
@ -187,94 +161,6 @@ fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
}
/// A lightweight `Exec` for the OpenCode probe/test commands, which do not
/// touch the target.
fn opencode_exec() -> Exec {
let dir = std::env::temp_dir().join("phoebus-opencode-cli");
let _ = std::fs::create_dir_all(&dir);
let logger = Logger::open(dir.join("opencode.log"), Redactor::new(), false);
Exec::new(Box::new(RealRunner), logger, false, dir.clone(), dir)
}
/// Probe an OpenCode server (`validate_inference = false`) or obtain and
/// validate a real model response (`true`). Exits nonzero unless the requested
/// condition is met, so it can be used as an acceptance command.
fn run_opencode_probe(cli: &Cli, url: &str, validate_inference: bool) -> ExitCode {
use phoebus_executor::opencode_client::{CurlHttpClient, OpenCodeClient};
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint, ProbeRequest};
let endpoint = match Endpoint::parse(url) {
Ok(endpoint) => endpoint,
Err(e) => {
eprintln!("invalid OpenCode endpoint `{url}`: {e}");
return ExitCode::FAILURE;
}
};
let auth = match &cli.opencode_password_file {
Some(path) => match read_secret(path) {
Ok(secret) => Some(secret),
Err(e) => {
eprintln!("cannot read OpenCode password file: {e}");
return ExitCode::FAILURE;
}
},
None => None,
};
let provider = cli.opencode_provider.clone().unwrap_or_default();
let model = cli.opencode_model.clone().unwrap_or_default();
let exec = opencode_exec();
let http = CurlHttpClient::new(&exec);
if !validate_inference {
let mut request = ProbeRequest::new();
request.auth = auth.clone();
request.provider = (!provider.is_empty()).then(|| provider.clone());
request.model = (!model.is_empty()).then(|| model.clone());
let capability = probe(&http, &endpoint, &request);
match serde_json::to_string_pretty(&capability) {
Ok(json) => println!("{json}"),
Err(e) => eprintln!("could not render capability: {e}"),
}
return if matches!(
capability.state,
ConnectionState::ModelCatalog | ConnectionState::Ready
) {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
};
}
if provider.is_empty() || model.is_empty() {
eprintln!("--opencode-test requires --opencode-provider and --opencode-model");
return ExitCode::FAILURE;
}
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model).with_auth(auth);
match client.one_shot(
"You are a connectivity test. Reply with JSON only.",
"Reply with exactly {\"phoebus\":\"ok\"} and nothing else.",
) {
Ok(reply) => match serde_json::from_str::<serde_json::Value>(&reply.content) {
Ok(value) if value.get("phoebus").and_then(|v| v.as_str()) == Some("ok") => {
println!("validated model response: {}", reply.content);
ExitCode::SUCCESS
}
Ok(value) => {
println!("model responded, but not as requested: {value}");
ExitCode::FAILURE
}
Err(_) => {
println!("model response was not JSON: {}", reply.content);
ExitCode::FAILURE
}
},
Err(e) => {
eprintln!("model validation failed: {e}");
ExitCode::FAILURE
}
}
}
/// The provider selected on the command line, or the one the TUI/config chose.
fn resolve_provider(
cli: &Cli,
@ -297,116 +183,48 @@ fn no_ai_requested(cli: &Cli) -> bool {
.unwrap_or(false)
}
/// Installing Phoebus requires a **validated** AI interaction, not just a
/// non-empty provider name. `--no-ai`/`--legacy` is the explicit, documented
/// break-glass for recovery or automation.
/// Installing Phoebus requires a connected model. `--no-ai`/`--legacy` is the
/// explicit, documented break-glass for recovery or automation.
fn require_ai_for_install(
cli: &Cli,
validated: bool,
provider: ProviderKind,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
if no_ai_requested(cli) || validated {
if no_ai_requested(cli) || provider != ProviderKind::None {
return Ok(());
}
Err(
"installing Phoebus requires a successful, validated AI interaction.\n\
Connect a provider (--ai-backend direct with --ai-provider \
deepseek|openai|local and --ai-api-key-file/--ai-endpoint, or \
--ai-backend opencode with --opencode-server/--opencode-provider/\
--opencode-model) and let it return a valid proposal, or pass --no-ai \
(alias --legacy) for a deterministic install."
.into(),
)
Err("installing Phoebus requires a connected AI model.\n\
Connect a provider (--ai-provider deepseek|openai|local, with \
--ai-api-key-file and/or --ai-endpoint), or pass --no-ai (alias \
--legacy) for a deterministic install."
.into())
}
/// Apply AI guidance to the configuration before the plan is shown or install
/// runs. Returns `true` only when a model interaction produced a valid,
/// reviewed proposal. The model never sees secrets and never executes anything.
/// runs. The model never sees secrets and never executes anything: its response
/// is reviewed with mandatory evidence and applied atomically.
fn run_ai_guidance(
cli: &Cli,
installer: &mut Installer,
) -> std::result::Result<bool, Box<dyn std::error::Error>> {
) -> std::result::Result<(), Box<dyn std::error::Error>> {
let provider = resolve_provider(cli, &installer.config)?;
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
if !wants_ai {
return Ok(false);
return Ok(());
}
if let Some(path) = &cli.ai_proposal_file {
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
println!("{}", outcome.render());
return Ok(true);
return Ok(());
}
let backend = cli
.ai_backend
.as_deref()
.and_then(phoebus_core::AiBackend::parse)
.unwrap_or(installer.config.ai.backend);
let facts = installer.system_facts();
if backend == phoebus_core::AiBackend::OpenCode {
let server = cli
.opencode_server
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
.unwrap_or_else(|| installer.config.ai.opencode_server.clone());
let provider_id = cli
.opencode_provider
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
.unwrap_or_else(|| installer.config.ai.opencode_provider.clone());
let model = cli
.opencode_model
.clone()
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
.unwrap_or_else(|| installer.config.ai.opencode_model.clone());
if server.trim().is_empty() || provider_id.trim().is_empty() || model.trim().is_empty() {
eprintln!(
"AI assistance is enabled but OpenCode is not fully configured \
(need server, provider and model); continuing without AI."
);
return Ok(false);
}
let password = match &cli.opencode_password_file {
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
None => None,
};
eprintln!(
"Sending these system facts through the OpenCode server at {} \
(provider {}, no passwords, passphrases or files):",
server, provider_id
);
eprintln!("{}", facts.render());
let transport = phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
&installer.exec,
server.clone(),
provider_id.clone(),
model.clone(),
)
.with_auth(password);
return match phoebus_installer::ai_guide::generate_and_review_at(
&mut installer.config,
&facts,
ProviderKind::Local,
&server,
&model,
&transport,
) {
Ok(outcome) => {
println!("{}", outcome.render());
Ok(true)
}
Err(e) => {
eprintln!("OpenCode proposal rejected; continuing with the proven defaults: {e}");
Ok(false)
}
};
}
let provider = resolve_provider(cli, &installer.config)?;
if provider == ProviderKind::None {
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
return Ok(false);
return Ok(());
}
// Opt-in: show exactly what leaves the machine before sending it.
let facts = installer.system_facts();
eprintln!(
"Sending these system facts to {} (no passwords, passphrases or files):",
provider.as_str()
@ -426,6 +244,7 @@ fn run_ai_guidance(
)
.into());
}
// A self-hosted local model usually needs no key.
(None, false) => None,
};
let model = cli.ai_model.clone().unwrap_or_default();
@ -438,15 +257,10 @@ fn run_ai_guidance(
&model,
&transport,
) {
Ok(outcome) => {
println!("{}", outcome.render());
Ok(true)
}
Err(e) => {
eprintln!("AI proposal rejected; continuing with the proven defaults: {e}");
Ok(false)
}
Ok(outcome) => println!("{}", outcome.render()),
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
}
Ok(())
}
fn main() -> ExitCode {
@ -468,10 +282,16 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
}
if let Some(url) = &cli.opencode_probe {
return Ok(run_opencode_probe(&cli, url, false));
}
if let Some(url) = &cli.opencode_test {
return Ok(run_opencode_probe(&cli, url, true));
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint};
let endpoint =
Endpoint::parse(url).map_err(|e| format!("invalid OpenCode endpoint `{url}`: {e}"))?;
let capability = probe(&endpoint, std::time::Duration::from_secs(5));
println!("{}", serde_json::to_string_pretty(&capability)?);
return Ok(if capability.state == ConnectionState::Ready {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
});
}
if let Some(name) = &cli.emit_asset {
@ -591,13 +411,12 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
println!("{}", installer.system_facts().render());
return Ok(ExitCode::SUCCESS);
}
let ai_validated = run_ai_guidance(&cli, &mut installer)?;
run_ai_guidance(&cli, &mut installer)?;
// AI is mandatory to install, and a validated interaction (not merely a
// provider name) is required; a deterministic no-AI run needs the explicit
// AI is mandatory to install; a deterministic no-AI run needs the explicit
// break-glass. Dry-run and plan modes are exempt.
if do_install && !installer.config.runtime.dry_run {
require_ai_for_install(&cli, ai_validated)?;
require_ai_for_install(&cli, resolve_provider(&cli, &installer.config)?)?;
}
if let Some(path) = &cli.save_config {

View file

@ -109,7 +109,7 @@ fn install_without_ai_is_refused() {
.expect("run phoebus-installer");
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("validated AI interaction"), "{err}");
assert!(err.contains("requires a connected AI"), "{err}");
}
#[test]
@ -122,31 +122,21 @@ fn no_ai_is_the_explicit_break_glass() {
.output()
.expect("run phoebus-installer");
let err = String::from_utf8_lossy(&out.stderr);
assert!(!err.contains("validated AI interaction"), "{flag}: {err}");
assert!(!err.contains("requires a connected AI"), "{flag}: {err}");
assert!(err.contains("configuration is incomplete"), "{flag}: {err}");
}
}
#[test]
fn an_unreachable_provider_does_not_satisfy_the_ai_gate() {
// A provider *name* is not enough: without a real, validated model
// interaction the install is refused (a deliberately closed port makes the
// result deterministic and offline).
fn local_provider_needs_no_key_at_the_gate() {
// A local provider satisfies the gate without --no-ai (it fails later at
// the incomplete config, not at the AI gate).
let out = Command::new(bin())
.args([
"--install",
"--yes",
"--ai",
"--ai-provider",
"local",
"--ai-endpoint",
"http://127.0.0.1:1/v1/chat/completions",
])
.args(["--install", "--yes", "--ai", "--ai-provider", "local"])
.output()
.expect("run phoebus-installer");
assert!(!out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains("validated AI interaction"), "{err}");
assert!(!err.contains("requires a connected AI"), "{err}");
}
#[test]

View file

@ -128,9 +128,6 @@ Singleton {
function aiCheck(cb) {
call("ai_check", {}, cb);
}
function aiTest(cb) {
call("ai_test", {}, cb);
}
function approve(eraseText, finalConfirmed, cb) {
call("approve", { erase: eraseText, final_confirm: finalConfirmed }, cb);
}

View file

@ -28,19 +28,11 @@ ShellRoot {
property string luksPw: ""
property string luksPw2: ""
property string apiKey: ""
// OpenCode server password (basic auth), distinct from a provider API key.
property string opencodePassword: ""
property bool aiConnected: false
property bool aiChecking: false
property string aiError: ""
property var aiApplied: []
// "Test connection" state: a real, validated model response was obtained.
property bool aiTesting: false
property bool aiTested: false
property string aiTestMessage: ""
readonly property bool isOpenCode: shell.cfg && shell.cfg.ai.backend === "opencode"
property var stageStatus: ({})
property var stageOrder: []
@ -77,26 +69,6 @@ ShellRoot {
return JSON.parse(JSON.stringify(o));
}
// A compact, secret-free state line for the harness. It lets a test assert
// the actual current step and AI connection state instead of inferring them
// from a screenshot or the mere survival of the process.
function logState(tag) {
console.log("phoebus-state " + tag
+ " step=" + shell.step
+ " phase=" + shell.phase
+ " aiConnected=" + shell.aiConnected
+ " aiTested=" + shell.aiTested
+ " aiApplied=" + shell.aiApplied.length
+ " aiError=" + shell.aiError.replace(/\n/g, " ").slice(0, 200)
+ " aiTest=" + shell.aiTestMessage.replace(/\n/g, " ").slice(0, 200));
}
onStepChanged: logState("step")
onPhaseChanged: logState("phase")
onAiConnectedChanged: logState("ai")
onAiErrorChanged: logState("error")
onAiTestedChanged: logState("test")
onAiTestMessageChanged: logState("testmsg")
// QML `var` properties do not emit change signals for nested assignments,
// so bindings that read `cfg.*` would not update. Reassigning a clone
// re-evaluates them. Used after a choice/toggle changes the configuration.
@ -120,10 +92,6 @@ ShellRoot {
modelField.inputItem.text = shell.cfg.ai.model;
endpointField.inputItem.text = shell.cfg.ai.endpoint;
keyField.inputItem.text = shell.apiKey;
opencodeServerField.inputItem.text = shell.cfg.ai.opencode_server;
opencodeProviderField.inputItem.text = shell.cfg.ai.opencode_provider;
opencodeModelField.inputItem.text = shell.cfg.ai.opencode_model;
opencodePasswordField.inputItem.text = shell.opencodePassword;
pwField.inputItem.text = shell.userPw;
pw2Field.inputItem.text = shell.userPw2;
luksField.inputItem.text = shell.luksPw;
@ -262,7 +230,7 @@ ShellRoot {
shell.status = "";
const s = shell.step;
if (s === 2) {
if (!shell.isOpenCode && (!shell.cfg.ai.provider || shell.cfg.ai.provider === "none")) {
if (!shell.cfg.ai.provider || shell.cfg.ai.provider === "none") {
shell.cfg.ai.provider = "deepseek";
shell.cfg.ai.enabled = true;
if (!shell.cfg.ai.model)
@ -310,26 +278,11 @@ ShellRoot {
}
function configureProvider(value) {
shell.cfg.ai.provider = value;
shell.cfg.ai.enabled = value !== "none";
shell.aiConnected = false;
shell.aiTested = false;
shell.aiTestMessage = "";
shell.aiError = "";
shell.aiApplied = [];
if (value === "opencode") {
// OpenCode is an agent server with its own protocol; it is not an
// OpenAI-compatible endpoint, so it has its own backend and fields.
shell.cfg.ai.backend = "opencode";
shell.cfg.ai.provider = "opencode";
shell.cfg.ai.opencode_server = shell.cfg.ai.opencode_server || "http://127.0.0.1:4096";
shell.cfg.ai.opencode_provider = shell.cfg.ai.opencode_provider || "deepseek";
shell.cfg.ai.opencode_model = shell.cfg.ai.opencode_model || "deepseek-chat";
opencodeServerField.inputItem.text = shell.cfg.ai.opencode_server;
opencodeProviderField.inputItem.text = shell.cfg.ai.opencode_provider;
opencodeModelField.inputItem.text = shell.cfg.ai.opencode_model;
} else {
shell.cfg.ai.backend = "direct";
shell.cfg.ai.provider = value;
if (value === "deepseek")
shell.cfg.ai.model = "deepseek-chat";
else if (value === "openai")
@ -338,37 +291,9 @@ ShellRoot {
shell.cfg.ai.model = shell.cfg.ai.model || "llama3.1";
modelField.inputItem.text = shell.cfg.ai.model;
endpointField.inputItem.text = shell.cfg.ai.endpoint;
}
shell.touchConfig();
}
// A lightweight real interaction used by "Test connection": it obtains and
// validates a model response without proposing installation changes.
function testAi() {
shell.aiTesting = true;
shell.aiTested = false;
shell.aiTestMessage = "";
shell.aiError = "";
const secrets = {};
if (shell.opencodePassword.length > 0)
secrets.opencode_password = shell.opencodePassword;
if (shell.apiKey.length > 0)
secrets.ai_api_key = shell.apiKey;
Bridge.setSecrets(secrets, () => {
applyConfig(() => {
Bridge.aiTest(reply => {
shell.aiTesting = false;
if (reply.ok) {
shell.aiTested = true;
shell.aiTestMessage = "Model responded";
} else {
shell.aiTestMessage = reply.error;
}
});
});
});
}
function connectAi() {
shell.aiChecking = true;
shell.aiError = "";
@ -377,8 +302,6 @@ ShellRoot {
const secrets = {};
if (shell.apiKey.length > 0)
secrets.ai_api_key = shell.apiKey;
if (shell.opencodePassword.length > 0)
secrets.opencode_password = shell.opencodePassword;
Bridge.setSecrets(secrets, () => {
applyConfig(() => {
Bridge.aiCheck(reply => {
@ -786,19 +709,17 @@ ShellRoot {
options: [
{ value: "deepseek", label: "DeepSeek" },
{ value: "openai", label: "OpenAI" },
{ value: "local", label: "Local model" },
{ value: "opencode", label: "OpenCode agent" }
{ value: "local", label: "Local model" }
]
value: shell.isOpenCode ? "opencode" : (shell.cfg ? shell.cfg.ai.provider : "deepseek")
value: shell.cfg ? shell.cfg.ai.provider : "deepseek"
onSelected: value => shell.configureProvider(value)
}
// -- direct providers ----------------------------------
PhoebusField {
id: keyField
label: "API key"
placeholder: "Paste your provider key"
secret: true
visible: shell.cfg && !shell.isOpenCode && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai")
visible: shell.cfg && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai")
onEdited: value => shell.apiKey = value
}
PhoebusField {
@ -806,7 +727,6 @@ ShellRoot {
label: "Model"
placeholder: "model name"
error: ""
visible: shell.cfg && !shell.isOpenCode
onEdited: value => shell.cfg.ai.model = value
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : ""
}
@ -814,70 +734,21 @@ ShellRoot {
id: endpointField
label: "Endpoint (local models)"
placeholder: "http://127.0.0.1:11434/v1/chat/completions"
visible: shell.cfg && !shell.isOpenCode && shell.cfg.ai.provider === "local"
visible: shell.cfg && shell.cfg.ai.provider === "local"
onEdited: value => shell.cfg.ai.endpoint = value
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.endpoint ? shell.cfg.ai.endpoint : ""
}
// -- OpenCode agent server -----------------------------
Text {
width: parent.width
visible: shell.isOpenCode
text: "OpenCode is an agent server, not a model endpoint. Phoebus connects to it over its own protocol. Bind it to loopback and reach a remote server through an authenticated tunnel; plain http to a non-loopback address is refused."
color: Theme.muted
font.family: Theme.family
font.pixelSize: Theme.fontSmall
wrapMode: Text.WordWrap
}
PhoebusField {
id: opencodeServerField
label: "OpenCode server"
placeholder: "http://127.0.0.1:4096"
visible: shell.isOpenCode
onEdited: value => shell.cfg.ai.opencode_server = value
}
PhoebusField {
id: opencodePasswordField
label: "Server password (if set)"
placeholder: "OPENCODE_SERVER_PASSWORD"
secret: true
visible: shell.isOpenCode
onEdited: value => shell.opencodePassword = value
}
PhoebusField {
id: opencodeProviderField
label: "Provider"
placeholder: "deepseek"
visible: shell.isOpenCode
onEdited: value => shell.cfg.ai.opencode_provider = value
}
PhoebusField {
id: opencodeModelField
label: "Model"
placeholder: "deepseek-chat"
visible: shell.isOpenCode
onEdited: value => shell.cfg.ai.opencode_model = value
}
Row {
spacing: 12
PhoebusButton {
label: shell.aiTesting ? "Testing…" : "Test connection"
actionEnabled: !shell.aiTesting && !shell.aiChecking
onClicked: shell.testAi()
}
PhoebusButton {
label: shell.aiChecking ? "Checking…" : "Connect and validate"
primary: true
actionEnabled: !shell.aiChecking && !shell.aiTesting
actionEnabled: !shell.aiChecking
onClicked: shell.connectAi()
}
PhoebusChip {
visible: shell.aiConnected
text: "Validated"
tone: Theme.success
}
PhoebusChip {
visible: shell.aiTested && !shell.aiConnected
text: "Model responded"
text: "Connected"
tone: Theme.success
}
}
@ -890,15 +761,6 @@ ShellRoot {
font.pixelSize: Theme.fontSmall
wrapMode: Text.WordWrap
}
Text {
width: parent.width
visible: shell.aiTestMessage.length > 0 && shell.aiError.length === 0
text: shell.aiTestMessage
color: shell.aiTested ? Theme.success : Theme.danger
font.family: Theme.family
font.pixelSize: Theme.fontSmall
wrapMode: Text.WordWrap
}
}
PhoebusCard {
width: parent.width

View file

@ -59,15 +59,6 @@ BOOT_TIMEOUT = int(os.environ.get("BOOT_TIMEOUT", "900"))
INSTALL_TIMEOUT = int(os.environ.get("INSTALL_TIMEOUT", "10800"))
SESSION_SETTLE = int(os.environ.get("SESSION_SETTLE", "20"))
BACKEND_SETTLE = int(os.environ.get("BACKEND_SETTLE", "30"))
# OpenCode GUI-driving knobs (test-only). Tab counts assume the focus order:
# Close, DeepSeek, OpenAI, Local, OpenCode, server, password, provider, model,
# Test, Connect, Back, Next.
OC_PORT = int(os.environ.get("OC_PORT", "4096"))
OC_TARGET_PORT = int(os.environ.get("OC_TARGET_PORT", "41999"))
OC_TAB_TO_CHIP = int(os.environ.get("OC_TAB_TO_CHIP", "5"))
OC_PROVIDER = os.environ.get("OC_PROVIDER", "deepseek")
OC_MODEL = os.environ.get("OC_MODEL", "deepseek-v4-flash")
OC_USE_PASSWORD = os.environ.get("OC_USE_PASSWORD", "0") in ("1", "yes", "true")
def _template_dir() -> Path:
@ -302,8 +293,6 @@ class Driver:
try:
if self.mode == "gui":
self.do_gui()
elif self.mode == "opencode":
self.do_opencode()
elif self.mode == "install":
self.do_install()
elif self.mode == "boot":
@ -485,10 +474,8 @@ class Driver:
label="duplicate-launch",
)
n1, n2 = int(self.last_group(1)), int(self.last_group(2))
# Exactly one session before and after: two pre-existing sessions must
# not pass as "no duplicate".
self.results.assert_true(
"exactly-one-installer-session", n1 == 1 and n2 == 1,
"duplicate-sessions-prevented", n1 == n2 and n1 >= 1,
f"n1={n1} n2={n2}",
)
@ -514,226 +501,8 @@ class Driver:
"ai-step-blocks-install", blocked,
"the AI step allowed advancement without a connected model",
)
# Behavioral evidence from the frontend's own state lines: the wizard is
# still on the AI step (index 2) and has not reported a connection, and
# it shows an inline error. A surviving process or a screenshot would
# not prove any of this.
state = self._frontend_state()
if state is None:
self.results.fail("ai-page-remains", "no frontend state line found")
else:
self.results.assert_true(
"ai-page-remains", state["step"] == 2 and not state["aiConnected"],
f"last state: {state}",
)
self.results.assert_true(
"ai-error-shown", bool(state["aiError"]),
f"the AI step showed no inline error: {state}",
)
self.results.pass_("gui-walk-completed")
def _frontend_state(self) -> dict | None:
"""Read the frontend's last secret-free state line.
The pattern is built from a variable so the shell echo of the command
cannot be mistaken for a real state line.
"""
assert self.child is not None
self.child.sendline(
'P=phoebus-; grep -ah "${P}state " '
"/run/user/1000/quickshell/by-id/*/log.qslog 2>/dev/null | tail -1; "
"echo STATE-$(printf END)"
)
try:
self.child.expect("STATE-END", timeout=30)
except (pexpect.TIMEOUT, pexpect.EOF):
return None
step = ai = tested = None
applied = 0
err = ""
for line in (self.child.before or "").splitlines():
if "phoebus-state" not in line:
continue
match = re.search(r"step=(\d+)", line)
if match:
step = int(match.group(1))
match = re.search(r"aiConnected=(true|false)", line)
if match:
ai = match.group(1) == "true"
match = re.search(r"aiTested=(true|false)", line)
if match:
tested = match.group(1) == "true"
match = re.search(r"aiApplied=(\d+)", line)
if match:
applied = int(match.group(1))
match = re.search(r"aiError=(.*?) aiTest=", line)
if match:
err = match.group(1).strip()
if step is None:
return None
return {
"step": step,
"aiConnected": bool(ai),
"aiTested": bool(tested),
"aiApplied": applied,
"aiError": err,
}
def wait_state(self, predicate, timeout: int):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
state = self._frontend_state()
if state is not None and predicate(state):
return state
time.sleep(2)
return None
def do_opencode(self) -> None:
"""Drive the OpenCode AI step through the real graphical UI.
The model is reached from the guest through a loopback relay (the same
shape as an SSH tunnel), so the connection satisfies the transport
policy while staying host-local or host+LAN only.
"""
self.spawn(attach_iso=True, boot_disk=False)
self.login_live()
welcome = self.poll_shell(
"echo WELCOME=$(pgrep -fc 'quickshell.*phoebus-welcome' 2>/dev/null || echo 0)",
r"WELCOME=([1-9][0-9]*)", timeout=int(os.environ.get("WELCOME_TIMEOUT", "180")),
label="welcome-window",
)
self.results.assert_true("welcome-autostarted", welcome is not None, "welcome did not appear")
self.set_wayland()
# Start the guest-local relay to the host OpenCode server.
self.shell(
f"curl -fsSL {SERVE_URL}/oc-forward.py -o /tmp/oc-forward.py && "
f"chmod 755 /tmp/oc-forward.py && "
f"setsid python3 /tmp/oc-forward.py {OC_PORT} 10.0.2.2 {OC_TARGET_PORT} "
f">/tmp/oc-forward.log 2>&1 < /dev/null & echo FWD-$(printf START)",
"FWD-START", timeout=60, label="forwarder-start",
)
ready = self.poll_shell(
f"curl -s -m 5 -o /dev/null -w 'HEALTH=%{{http_code}}' "
f"http://127.0.0.1:{OC_PORT}/global/health",
r"HEALTH=(200|401)", timeout=60, label="forwarder-ready",
)
self.results.assert_true(
"opencode-reachable-from-guest", ready is not None,
"the guest relay could not reach the OpenCode server",
)
self.sendkey("ret")
opened = self.poll_shell(
"echo INST=$(pgrep -fc 'quickshell.*phoebus-install' 2>/dev/null || echo 0)",
r"INST=([1-9][0-9]*)", timeout=int(os.environ.get("INSTALLER_OPEN_TIMEOUT", "90")),
label="launcher-opens-installer", record=False,
)
if opened is None:
self.results.fail("launcher-opens-installer", "Return did not open the installer")
return
self.results.pass_("launcher-opens-installer", "welcome action opened the installer")
time.sleep(BACKEND_SETTLE)
self.shell(
"pkill -f 'quickshell.*phoebus-wel[c]ome' || true; sleep 2; echo CLOSED",
"CLOSED", timeout=30, label="close-welcome",
)
# Navigate to the AI step (0 -> 1 -> 2).
self.sendkey("ctrl-right")
time.sleep(2)
self.sendkey("ctrl-right")
time.sleep(2)
state = self._frontend_state()
self.results.assert_true(
"ai-step-reached", state is not None and state["step"] == 2,
f"frontend state: {state}",
)
self.shot("oc-01-ai", "AI step", "Ctrl+Right twice", "the AI model step is shown")
# Select the "OpenCode agent" chip with the keyboard.
for _ in range(OC_TAB_TO_CHIP):
self.sendkey("tab")
time.sleep(0.3)
self.sendkey("ret")
time.sleep(1)
self.shot("oc-02-selected", "OpenCode selected", "Tab to the chip and Return",
"server, password, provider and model fields appear")
# Enter the connection through the UI. Focus is on the chip after
# selection; Tab order is server, password, provider, model, Test,
# Connect. Ctrl+A selects the existing default before typing.
def type_field(tabs: int, value: str, secret_file: str | None = None) -> None:
# `wtype` (Wayland) and QEMU `sendkey` (hardware) are two input
# paths; settle between them or the next key can truncate the text.
for _ in range(tabs):
self.sendkey("tab")
time.sleep(0.4)
self.sendkey("ctrl-a")
time.sleep(0.5)
if secret_file:
# The serial echo carries `$(cat ...)`, never the value.
self.shell(
f'wtype "$(cat {secret_file})" >/dev/null 2>&1; echo TYPED',
"TYPED", timeout=30, label="type-secret",
)
else:
self.shell(
f"wtype '{value}' >/dev/null 2>&1; echo TYPED",
"TYPED", timeout=30, label="type-field",
)
time.sleep(1.4)
# Clear the selection highlight so a screenshot shows the value.
self.sendkey("end")
time.sleep(0.3)
type_field(1, f"http://127.0.0.1:{OC_PORT}")
if OC_USE_PASSWORD:
self.shell(
f"curl -fsSL {SERVE_URL}/oc.pw -o /tmp/oc.pw && chmod 600 /tmp/oc.pw "
"&& echo PW-$(printf LOADED)",
"PW-LOADED", timeout=30, label="fetch-password",
)
type_field(1, "", secret_file="/tmp/oc.pw")
else:
self.sendkey("tab") # skip the empty password field
time.sleep(0.25)
type_field(1, OC_PROVIDER)
type_field(1, OC_MODEL)
self.shot("oc-02b-fields", "OpenCode fields", "typed server/provider/model",
"the fields hold the entered values")
self.sendkey("tab") # model -> Test
time.sleep(0.3)
self.sendkey("ret")
time.sleep(3)
self.shot("oc-03-test", "Test connection", "Return on Test connection",
"a real model response is obtained and validated")
tested = self.wait_state(lambda s: s["aiTested"], timeout=180)
self.results.assert_true(
"opencode-test-connection", tested is not None,
"Test connection did not obtain a valid model response",
)
# The next focus is the "Connect and validate" button.
self.sendkey("tab")
time.sleep(0.3)
self.sendkey("ret")
self.shot("oc-04-connect", "Connect and validate", "Return on Connect and validate",
"a validated proposal is applied; Next is enabled")
connected = self.wait_state(lambda s: s["aiConnected"], timeout=240)
self.results.assert_true(
"opencode-validated-proposal",
connected is not None,
f"Connect and validate did not validate a proposal: {connected}",
)
if connected is not None:
# A validated proposal may legitimately contain zero changes.
self.results.pass_(
"opencode-proposal-applied",
f"applied={connected['aiApplied']} change(s)",
)
self.results.pass_("opencode-gui-completed")
def _installer_alive(self) -> bool:
assert self.child is not None
self.child.sendline(
@ -862,7 +631,7 @@ class Driver:
def main() -> int:
mode = sys.argv[1] if len(sys.argv) > 1 else ""
if mode not in ("gui", "opencode", "install", "boot"):
if mode not in ("gui", "install", "boot"):
print(__doc__)
return 2
if mode in ("install", "boot") and not DISKS:

View file

@ -1,71 +0,0 @@
#!/usr/bin/env python3
"""Guest-local TCP forwarder for OpenCode VM testing.
The Phoebus transport policy allows plain `http://` only to a **loopback**
destination. A VM guest cannot name the host's loopback directly, and the QEMU
gateway address (`10.0.2.2`) is not loopback. This forwarder is the same shape
as an SSH tunnel: the GUI connects to the guest's own loopback, and the
forwarder relays to the host's OpenCode server over the QEMU host gateway. The
connection therefore never leaves the machine pair.
oc-forward.py [listen_port] [target_host] [target_port]
It is test infrastructure, not a product component.
"""
from __future__ import annotations
import socket
import sys
import threading
LISTEN_HOST = "127.0.0.1"
def pipe(src: socket.socket, dst: socket.socket) -> None:
try:
while True:
data = src.recv(65536)
if not data:
break
dst.sendall(data)
except OSError:
pass
finally:
for sock in (src, dst):
try:
sock.shutdown(socket.SHUT_RDWR)
except OSError:
pass
def handle(client: socket.socket, target: tuple[str, int]) -> None:
try:
upstream = socket.create_connection(target)
except OSError:
client.close()
return
threading.Thread(target=pipe, args=(client, upstream), daemon=True).start()
threading.Thread(target=pipe, args=(upstream, client), daemon=True).start()
def main() -> int:
listen_port = int(sys.argv[1]) if len(sys.argv) > 1 else 4096
target_host = sys.argv[2] if len(sys.argv) > 2 else "10.0.2.2"
target_port = int(sys.argv[3]) if len(sys.argv) > 3 else 41999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((LISTEN_HOST, listen_port))
server.listen(32)
print(f"oc-forward listening on {LISTEN_HOST}:{listen_port} -> {target_host}:{target_port}", flush=True)
while True:
try:
client, _ = server.accept()
except OSError:
break
threading.Thread(target=handle, args=(client, (target_host, target_port)), daemon=True).start()
return 0
if __name__ == "__main__":
sys.exit(main())