Compare commits
No commits in common. "359f083bc2924b483fa632bcae44b6debab52a22" and "fb4dcc5683bc17cb713c1ddf0e396cf6046c157b" have entirely different histories.
359f083bc2
...
fb4dcc5683
24 changed files with 623 additions and 3903 deletions
13
Makefile
13
Makefile
|
|
@ -8,7 +8,7 @@
|
||||||
|
|
||||||
SHELL := /bin/bash
|
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:
|
help:
|
||||||
@printf 'Phoebus OS targets:\n'
|
@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 run the Rust and VM-harness test suites\n'
|
||||||
@printf ' make test-rust cargo test --workspace\n'
|
@printf ' make test-rust cargo test --workspace\n'
|
||||||
@printf ' make test-vm python3 installer/tests/vm/test_vmsafety.py\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 fmt cargo fmt --all\n'
|
||||||
@printf ' make check fmt-check + clippy + tests\n'
|
@printf ' make check fmt-check + clippy + tests\n'
|
||||||
@printf ' make build release Rust installer\n'
|
@printf ' make build release Rust installer\n'
|
||||||
|
|
@ -45,16 +44,6 @@ test-rust:
|
||||||
test-vm:
|
test-vm:
|
||||||
python3 installer/tests/vm/test_vmsafety.py
|
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:
|
fmt:
|
||||||
cd installer-rs && cargo fmt --all
|
cd installer-rs && cargo fmt --all
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -7,69 +7,6 @@ Format: Keep a Changelog. Dates are UTC.
|
||||||
|
|
||||||
## Unreleased
|
## 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
|
### Added
|
||||||
- **OpenCode connection workflow and capability probe.** New ADR 0011 and
|
- **OpenCode connection workflow and capability probe.** New ADR 0011 and
|
||||||
`docs/OPENCODE.md` separate the four components (client, server, model
|
`docs/OPENCODE.md` separate the four components (client, server, model
|
||||||
|
|
|
||||||
|
|
@ -3,36 +3,27 @@
|
||||||
Rolling note between work sessions. **Update this file before you finish**, then
|
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.
|
commit it. It should be short and current; use `git log` for detail.
|
||||||
|
|
||||||
- **Last updated:** this session (2026-09-22), OpenCode adapter.
|
- **Last updated:** this session (2026-09-22), harness + security + polish.
|
||||||
- **Current focus:** Implemented a real OpenCode agent-server adapter
|
- **Current focus:** Hardened the VM harness (enforced qcow2/`/dev`/backing-chain
|
||||||
(`phoebus-executor::opencode_client`) that speaks the session/message protocol
|
safety, structured PASS/FAIL results, per-run OVMF+QMP, no `os.system`),
|
||||||
over curl and implements `ModelTransport`, wired into canonical config
|
fixed confirmed security defects (disk revalidation before partitioning,
|
||||||
(`ai.backend = "opencode"`), the GUI ("OpenCode agent" + Test connection),
|
bridge replay/concurrency + input bounds, provider transport URL/size
|
||||||
the installer CLI (`--ai-backend opencode`, `--opencode-test`) and `sys ask`.
|
hardening, `TargetRoot` symlink escapes, and the `0 B` disk-size probe bug),
|
||||||
The mandatory-AI gate now requires a validated interaction with invalidated
|
added an OpenCode server capability probe + docs/ADR 0011, and fixed the
|
||||||
state. The probe/transport were hardened (loopback/TLS policy, DNS pinning,
|
welcome focus ring and the untruthful mid-install cancellation.
|
||||||
status checks, auth), and the GUI harness gained exact-session and
|
|
||||||
frontend-state assertions.
|
|
||||||
- **Last verified (this session):**
|
- **Last verified (this session):**
|
||||||
- 336 Rust tests + 16 harness tests green; fmt/clippy clean.
|
- `gui-driver.py gui` on the rebuilt ISO: **23/23 PASS**, exit 0. Welcome
|
||||||
- Real inference through `opencode 1.18.32` with `deepseek-v4-flash`;
|
autostarts; Return launches the installer (focus fixed); duplicate sessions
|
||||||
`--opencode-test` → `{"phoebus":"ok"}`; the GUI bridge `ai_check` applied 8
|
prevented; live medium protected; keyboard navigation reaches network + AI;
|
||||||
reviewed changes; `sys ask` proposed and ran a read-only action.
|
advancing without a model is refused and starts nothing.
|
||||||
- Auth: none → `authentication_required`, wrong → `authentication_rejected`,
|
- `make test` green (Rust + 16 harness unit tests); `cargo fmt --check`,
|
||||||
correct → `model_catalog` + successful inference. Plain http to a LAN host
|
`cargo clippy --workspace --all-targets` (no errors), release + static
|
||||||
→ `insecure_transport`, exit 1, no request sent.
|
builds.
|
||||||
- 7 real-HTTP integration tests (status, chunked multibyte, oversize,
|
- OpenCode probe: `ready` against `opencode 1.18.32`; `authentication_required`
|
||||||
redirect, disconnect, auth) and 2 env-gated live tests.
|
(exit 1) against an unauthenticated LAN bind.
|
||||||
- GUI acceptance in a disposable VM: `gui-driver.py opencode` passed 17/17
|
- ISO: `installer/live/phoebus-installer-amd64.iso` 1.6 GiB,
|
||||||
(selected OpenCode, entered the endpoint/model through the UI, real model
|
`sha256 428dbd7547db8690596bf5c3a0d7a6fa8aee4c9f9eca1e926c216712dd050b36`;
|
||||||
response + validated proposal); `gui-driver.py gui` passed 25/25.
|
static binary `sha256 2f9cd4b36a12e469d2b6187166acaf8b11f7f382cc19f7ad08bb2a809c855591`.
|
||||||
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).
|
|
||||||
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
|
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
|
||||||
(remote `origin`, SSH port 2222).
|
(remote `origin`, SSH port 2222).
|
||||||
|
|
||||||
|
|
|
||||||
219
docs/OPENCODE.md
219
docs/OPENCODE.md
|
|
@ -1,9 +1,13 @@
|
||||||
# OpenCode connection workflow
|
# OpenCode connection workflow
|
||||||
|
|
||||||
OpenCode is integrated as a **real agent-server connection**, not a renamed
|
OpenCode is used in two clearly separated ways:
|
||||||
OpenAI-compatible endpoint. The adapter speaks OpenCode's session/message API
|
|
||||||
and feeds the same strict proposal parser, evidence review and executor as the
|
1. **Developer workflow** — on this repository, inspecting sanitized evidence.
|
||||||
direct providers.
|
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.
|
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 |
|
| Component | What it is | Where it runs |
|
||||||
|-----------|------------|---------------|
|
|-----------|------------|---------------|
|
||||||
| OpenCode client | `opencode` TUI/CLI, or `opencode attach <url>` | your machine |
|
| 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 |
|
| 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 | provider cloud or your LAN |
|
| 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 |
|
| 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.**
|
**An OpenCode server URL does not go in Phoebus's local-model endpoint field.**
|
||||||
Select the OpenCode backend instead; Phoebus speaks the agent protocol.
|
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
|
## Capability probe (never assume compatibility)
|
||||||
|
|
||||||
```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
|
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# Read-only: classify the server. Exits nonzero unless a model catalog exists.
|
phoebus-installer --opencode-probe http://127.0.0.1:4096
|
||||||
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"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
`--opencode-password-file` must be mode 0600, like the direct provider key file.
|
It is read-only and prints a typed state, exiting nonzero unless a model is
|
||||||
|
available:
|
||||||
## 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:
|
|
||||||
|
|
||||||
| State | Meaning |
|
| State | Meaning |
|
||||||
|-------|---------|
|
|-------|---------|
|
||||||
| `insecure_transport` | the destination failed the transport policy |
|
| `disconnected` | TCP connect failed; the service is down |
|
||||||
| `unreachable` | the server could not be reached |
|
| `authentication_required` | the server answered 401/403; supply the password/tunnel |
|
||||||
| `authentication_required` | the server returned 401 and no credential was supplied |
|
| `incompatible` | a health response arrived but the API shape is not the expected one |
|
||||||
| `authentication_rejected` | a credential was supplied and rejected |
|
| `reachable_no_model` | healthy server, no model configured |
|
||||||
| `incompatible` | a response arrived but was not the expected API/JSON |
|
| `ready` | reachable, healthy, API-compatible, and ≥1 model configured |
|
||||||
| `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) |
|
|
||||||
|
|
||||||
A model catalog is not readiness. The probe never returns `ready`; only a real
|
`ready` still does **not** prove the model can emit a valid Phoebus proposal;
|
||||||
inference that validates the response does.
|
that requires a real prompt round-trip and proposal parse. A health check or an
|
||||||
|
HTTP 200 is not that proof.
|
||||||
|
|
||||||
## Transport policy
|
The probe reads `/global/health` and `/config/providers`, keeps only counts from
|
||||||
|
the latter, and never returns the provider credentials that upstream includes in
|
||||||
- Plain `http://` is accepted **only** when the resolved destination is
|
that response.
|
||||||
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.
|
|
||||||
|
|
||||||
## A. OpenCode on the development/VM host
|
## A. OpenCode on the development/VM host
|
||||||
|
|
||||||
```sh
|
```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
|
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 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`
|
Keep the server on `127.0.0.1`. Do not pass `--mdns` and do not bind `0.0.0.0`
|
||||||
without authentication.
|
without authentication: the server's configuration API can expose provider
|
||||||
|
credentials.
|
||||||
|
|
||||||
## B. OpenCode on a separate user-controlled computer
|
## B. OpenCode on a separate user-controlled computer
|
||||||
|
|
||||||
Run the server on that computer bound to **loopback** and reach it through an
|
Run the server on that computer, bound to **loopback**, and reach it through an
|
||||||
authenticated encrypted tunnel:
|
authenticated encrypted tunnel. SSH port-forwarding is the simplest approved
|
||||||
|
transport:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
# remote:
|
# On the remote computer:
|
||||||
opencode serve --hostname 127.0.0.1 --port 4096
|
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
|
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
|
phoebus-installer --opencode-probe http://127.0.0.1:4096
|
||||||
```
|
```
|
||||||
|
|
||||||
If a tunnel is impossible, set `OPENCODE_SERVER_PASSWORD` and terminate TLS in
|
The probe now sees a loopback endpoint and the tunnel supplies transport
|
||||||
front of the server; never expose an unauthenticated plaintext service.
|
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
|
### VM networking is not one thing
|
||||||
|
|
||||||
|
Inside a VM these are different endpoints and must not be confused:
|
||||||
|
|
||||||
| Endpoint | Meaning |
|
| Endpoint | Meaning |
|
||||||
|----------|---------|
|
|----------|---------|
|
||||||
| `guest 127.0.0.1` | the guest's own loopback |
|
| `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 |
|
| `10.0.2.2` | the QEMU user-net gateway to the host |
|
||||||
| `192.168.x.y` | a real LAN address, reachable by other machines |
|
| `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
|
## C. Phoebus assistant boundary
|
||||||
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.
|
|
||||||
|
|
||||||
## Verified evidence (2026-09-22)
|
When a Phoebus assistant uses OpenCode:
|
||||||
|
|
||||||
- `opencode 1.18.32` (pinned manifest: `v1.18.31`; version mismatch noted).
|
- Run the service unprivileged, with restricted filesystem access.
|
||||||
- `--opencode-probe` → `model_catalog`, 223 providers / 7915 models, 26
|
- Disable tools you do not need. OpenCode permission settings are *not* an
|
||||||
connected; the selected `deepseek:deepseek-v4-flash` present.
|
operating-system security boundary; enforce isolation outside the prompt.
|
||||||
- `--opencode-test` → `validated model response: {"phoebus":"ok"}` (real
|
- Keep the destructive execution path in Phoebus's local broker with local human
|
||||||
inference), exit 0.
|
approval. The agent is never given a shell, root, credentials or private-file
|
||||||
- The GUI bridge `ai_check` over OpenCode applied 8 reviewed changes from a real
|
access.
|
||||||
`deepseek-v4-flash` proposal.
|
- Keep credentials in protected runtime storage (0600, outside model context).
|
||||||
- `sys ask` over OpenCode proposed a read-only `history` action and executed it
|
Never forward disk passphrases or account passwords to OpenCode.
|
||||||
deterministically.
|
- Changing the model or connection invalidates any approval whose meaning
|
||||||
- Authentication: no credential → `authentication_required`; wrong →
|
depends on it; a reconnect must never replay an installation command.
|
||||||
`authentication_rejected`; correct → `model_catalog` and a successful real
|
|
||||||
inference.
|
## Developer workflow note
|
||||||
- Transport policy: plain `http` to a LAN/global address →
|
|
||||||
`insecure_transport`, exit 1, no request sent.
|
For work on this repository, the developer OpenCode session may use full tools,
|
||||||
- Real-HTTP integration tests cover status preservation, chunked multibyte
|
but only against a checkout and against **sanitized** test evidence. Do not feed
|
||||||
bodies, oversized bodies, redirects, abrupt disconnects and authentication.
|
it VM disks, serial transcripts with credentials, `*.pw` files, or the
|
||||||
- A separate physical computer remains **unverified**; a second server bound to
|
`PHOEBUS_OPENCODE_*` runtime inputs.
|
||||||
the LAN address reached through a loopback tunnel is the remote-topology test.
|
|
||||||
|
## 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.
|
||||||
|
|
|
||||||
|
|
@ -99,11 +99,7 @@ still not VM-verified.
|
||||||
| Bridge replay/concurrency + input bounds | yes | yes | no | n/a |
|
| Bridge replay/concurrency + input bounds | yes | yes | no | n/a |
|
||||||
| Provider transport endpoint/size hardening | 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 |
|
| `TargetRoot` symlink-escape guard | yes | yes | n/a | n/a |
|
||||||
| OpenCode server capability probe | yes | yes | real host probe + auth + policy | n/a |
|
| OpenCode server capability probe | yes | yes | real host probe (`ready`) | 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 |
|
|
||||||
| GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no |
|
| GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no |
|
||||||
| Release gates + atomic publish | yes | yes | no | n/a |
|
| Release gates + atomic publish | yes | yes | no | n/a |
|
||||||
| `sys` verbs | yes | yes | yes | no |
|
| `sys` verbs | yes | yes | yes | no |
|
||||||
|
|
|
||||||
|
|
@ -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
|
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.
|
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)
|
## Run matrix (this session, 2026-09-22)
|
||||||
|
|
||||||
```json
|
```json
|
||||||
|
|
|
||||||
|
|
@ -44,35 +44,10 @@ Two facts shape the decision:
|
||||||
product actions still go through the local typed broker and local human
|
product actions still go through the local typed broker and local human
|
||||||
approval. The OpenCode configuration is written mode 0600 and carries no
|
approval. The OpenCode configuration is written mode 0600 and carries no
|
||||||
credentials.
|
credentials.
|
||||||
5. **The installer's AI step uses a real OpenCode adapter** (implemented after
|
5. **The installer's AI step keeps using its own bounded transport.** OpenCode
|
||||||
this ADR was first written). `phoebus-executor::opencode_client` speaks the
|
is an optional operator workflow, not a replacement for the typed proposal
|
||||||
OpenCode session/message API over the project's curl transport and implements
|
transport; a future adapter must perform a real prompt round-trip and parse a
|
||||||
the same `ModelTransport` trait as the direct providers, so the strict
|
versioned proposal before it may claim compatibility.
|
||||||
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.
|
|
||||||
|
|
||||||
## Consequences
|
## Consequences
|
||||||
|
|
||||||
|
|
@ -87,9 +62,5 @@ Two facts shape the decision:
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Accepted and implemented. The probe, the adapter and the connection states are
|
Accepted. The probe and its tests are implemented; end-to-end installation does
|
||||||
implemented with unit, real-HTTP integration, live-model and bridge tests; the
|
not depend on OpenCode.
|
||||||
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.
|
|
||||||
|
|
|
||||||
|
|
@ -145,27 +145,7 @@ pub fn build_request(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The request with a corrective turn appended after a rejected plan.
|
/// Ask the provider for a plan and parse it, fail-closed at every step.
|
||||||
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.
|
|
||||||
pub fn complete_plan(
|
pub fn complete_plan(
|
||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
endpoint: &str,
|
endpoint: &str,
|
||||||
|
|
@ -185,27 +165,11 @@ pub fn complete_plan(
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
facts.validate_no_forbidden()?;
|
facts.validate_no_forbidden()?;
|
||||||
|
let request = build_request(provider, model, facts, instruction);
|
||||||
let attempt = |request: &ChatRequest| -> Result<AssistantPlan, AiError> {
|
let body = serde_json::to_string(&request)?;
|
||||||
let body = serde_json::to_string(request)?;
|
|
||||||
let response = transport.send(provider, endpoint, &body)?;
|
let response = transport.send(provider, endpoint, &body)?;
|
||||||
let content = crate::provider::extract_content(&response)?;
|
let content = crate::provider::extract_content(&response)?;
|
||||||
parse_plan(&content)
|
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)]
|
#[cfg(test)]
|
||||||
|
|
@ -315,30 +279,6 @@ mod tests {
|
||||||
.is_err());
|
.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]
|
#[test]
|
||||||
fn action_tag_matches_the_schema() {
|
fn action_tag_matches_the_schema() {
|
||||||
assert_eq!(action_tag(&SystemAction::History), "history");
|
assert_eq!(action_tag(&SystemAction::History), "history");
|
||||||
|
|
|
||||||
|
|
@ -231,14 +231,7 @@ set_binary_packages (bool), set_build_jobs (1-256), set_package_use (atom, flag,
|
||||||
enabled).
|
enabled).
|
||||||
|
|
||||||
Reply with ONLY a JSON object of the form:
|
Reply with ONLY a JSON object of the form:
|
||||||
{\"version\":1,\"changes\":[{\"action\":\"<action>\",\"value\":<value>}],\"rationale\":[{\"action\":\"<action>\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
|
{\"version\":1,\"changes\":[{\"action\":\"...\",...}],\"rationale\":[{\"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}
|
|
||||||
|
|
||||||
Rules: prefer stability and a proven boot over speculative performance; never
|
Rules: prefer stability and a proven boot over speculative performance; never
|
||||||
propose disabling signature verification, enabling ~amd64 globally, weakening
|
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.
|
/// Ask a provider for a proposal and parse it, fail-closed at every step.
|
||||||
pub fn complete_proposal(
|
pub fn complete_proposal(
|
||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
|
|
@ -421,30 +378,8 @@ pub fn complete_proposal(
|
||||||
complete_proposal_at(provider, provider.endpoint(), model, facts, transport)
|
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
|
/// 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
|
/// a self-hosted model on a non-default port.
|
||||||
/// with a corrective turn; the strict parser is still the final authority.
|
|
||||||
pub fn complete_proposal_at(
|
pub fn complete_proposal_at(
|
||||||
provider: ProviderKind,
|
provider: ProviderKind,
|
||||||
endpoint: &str,
|
endpoint: &str,
|
||||||
|
|
@ -459,26 +394,11 @@ pub fn complete_proposal_at(
|
||||||
}
|
}
|
||||||
validate_endpoint(endpoint)?;
|
validate_endpoint(endpoint)?;
|
||||||
facts.validate_no_forbidden()?;
|
facts.validate_no_forbidden()?;
|
||||||
|
let request = build_request(provider, model, facts);
|
||||||
let attempt = |request: &ChatRequest| -> Result<AiProposal, AiError> {
|
let body = serde_json::to_string(&request)?;
|
||||||
let body = serde_json::to_string(request)?;
|
|
||||||
let response = transport.send(provider, endpoint, &body)?;
|
let response = transport.send(provider, endpoint, &body)?;
|
||||||
let content = extract_content(&response)?;
|
let content = extract_content(&response)?;
|
||||||
parse_proposal(&content)
|
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)]
|
#[cfg(test)]
|
||||||
|
|
@ -642,49 +562,6 @@ mod tests {
|
||||||
assert_eq!(parsed.changes.len(), 1);
|
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]
|
#[test]
|
||||||
fn unavailable_provider_is_explicit() {
|
fn unavailable_provider_is_explicit() {
|
||||||
let transport = TestTransport::new("{}");
|
let transport = TestTransport::new("{}");
|
||||||
|
|
|
||||||
|
|
@ -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)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub struct AiConfig {
|
pub struct AiConfig {
|
||||||
|
|
@ -397,30 +368,6 @@ pub struct AiConfig {
|
||||||
pub provider: String,
|
pub provider: String,
|
||||||
pub model: String,
|
pub model: String,
|
||||||
pub endpoint: 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)]
|
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||||
|
|
|
||||||
|
|
@ -24,9 +24,9 @@ pub mod update;
|
||||||
pub mod validate;
|
pub mod validate;
|
||||||
|
|
||||||
pub use config::{
|
pub use config::{
|
||||||
AiBackend, AiConfig, Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig,
|
Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig, Filesystem,
|
||||||
Filesystem, InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig,
|
InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig, Stage3Config,
|
||||||
Stage3Config, StorageConfig, SystemConfig, UserConfig,
|
StorageConfig, SystemConfig, UserConfig,
|
||||||
};
|
};
|
||||||
pub use disk::{Disk, DiskKind, ProtectionReason};
|
pub use disk::{Disk, DiskKind, ProtectionReason};
|
||||||
pub use error::{CoreError, Result};
|
pub use error::{CoreError, Result};
|
||||||
|
|
|
||||||
|
|
@ -18,7 +18,6 @@ pub mod kernel;
|
||||||
pub mod log;
|
pub mod log;
|
||||||
pub mod nix;
|
pub mod nix;
|
||||||
pub mod opencode;
|
pub mod opencode;
|
||||||
pub mod opencode_client;
|
|
||||||
pub mod opencode_server;
|
pub mod opencode_server;
|
||||||
pub mod portage;
|
pub mod portage;
|
||||||
pub mod probe;
|
pub mod probe;
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -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
|
//! 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
|
//! endpoint. A successful TCP connect, a health check or an HTTP 200 is not
|
||||||
//! model is configured, that the selected model exists, or that it can produce
|
//! proof that a model is configured or that it can produce a valid Phoebus
|
||||||
//! a valid Phoebus proposal. The probe reports a typed state for each of those
|
//! proposal. This module makes those distinctions explicit so a caller can
|
||||||
//! distinctions, and only a real inference (`OpenCodeClient::one_shot`) can
|
//! report an honest connection state instead of assuming compatibility.
|
||||||
//! reach [`ConnectionState::Ready`].
|
|
||||||
//!
|
//!
|
||||||
//! The probe uses the shared [`HttpClient`] transport (curl through [`Exec`]),
|
//! It talks to the OpenCode HTTP API documented at <https://opencode.ai/docs/server/>
|
||||||
//! never a second handwritten HTTP parser, and it keeps only ids and model
|
//! using a deliberately tiny HTTP/1.1 client (no TLS, no redirects, no
|
||||||
//! names from the provider catalog: upstream's catalog can contain credentials,
|
//! credentials in the URL). Remote access is expected through an authenticated,
|
||||||
//! so raw bodies are never retained or surfaced.
|
//! encrypted tunnel to a loopback-bound server, never by exposing the server
|
||||||
|
//! directly.
|
||||||
//!
|
//!
|
||||||
//! ## Transport policy
|
//! The probe never returns provider credentials: upstream's `/config/providers`
|
||||||
//!
|
//! response includes them, so only counts are kept.
|
||||||
//! 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.
|
|
||||||
|
|
||||||
use std::net::{SocketAddr, ToSocketAddrs};
|
use std::io::{Read, Write};
|
||||||
|
use std::net::{SocketAddr, TcpStream, ToSocketAddrs};
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use phoebus_ai::AiError;
|
use serde::{Deserialize, Serialize};
|
||||||
use phoebus_core::SecretString;
|
|
||||||
|
|
||||||
use crate::opencode_client::{parse_catalog, Catalog, HttpClient, HttpRequest, HttpResponse};
|
/// A parsed `http://host:port` server endpoint.
|
||||||
|
|
||||||
/// 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.
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub struct Endpoint {
|
pub struct Endpoint {
|
||||||
pub scheme: Scheme,
|
|
||||||
pub host: String,
|
pub host: String,
|
||||||
pub port: u16,
|
pub port: u16,
|
||||||
}
|
}
|
||||||
|
|
@ -56,9 +31,7 @@ pub struct Endpoint {
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum EndpointError {
|
pub enum EndpointError {
|
||||||
Empty,
|
Empty,
|
||||||
UnsupportedScheme,
|
NotHttp,
|
||||||
UserInfo,
|
|
||||||
PathNotAllowed,
|
|
||||||
BadHost,
|
BadHost,
|
||||||
BadPort,
|
BadPort,
|
||||||
}
|
}
|
||||||
|
|
@ -67,9 +40,7 @@ impl std::fmt::Display for EndpointError {
|
||||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
let text = match self {
|
let text = match self {
|
||||||
EndpointError::Empty => "empty endpoint",
|
EndpointError::Empty => "empty endpoint",
|
||||||
EndpointError::UnsupportedScheme => "only http:// and https:// are accepted",
|
EndpointError::NotHttp => "only http:// endpoints are accepted",
|
||||||
EndpointError::UserInfo => "userinfo (@) is not allowed in the endpoint",
|
|
||||||
EndpointError::PathNotAllowed => "a path, query or fragment is not allowed",
|
|
||||||
EndpointError::BadHost => "the host is missing or contains an unsafe character",
|
EndpointError::BadHost => "the host is missing or contains an unsafe character",
|
||||||
EndpointError::BadPort => "the port is missing or invalid",
|
EndpointError::BadPort => "the port is missing or invalid",
|
||||||
};
|
};
|
||||||
|
|
@ -78,119 +49,61 @@ impl std::fmt::Display for EndpointError {
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Endpoint {
|
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> {
|
pub fn parse(value: &str) -> Result<Self, EndpointError> {
|
||||||
let text = value.trim();
|
let text = value.trim();
|
||||||
if text.is_empty() {
|
if text.is_empty() {
|
||||||
return Err(EndpointError::Empty);
|
return Err(EndpointError::Empty);
|
||||||
}
|
}
|
||||||
let (scheme, rest) = if let Some(rest) = text.strip_prefix("http://") {
|
let rest = text.strip_prefix("http://").ok_or(EndpointError::NotHttp)?;
|
||||||
(Scheme::Http, rest)
|
// Reject userinfo, paths and control characters.
|
||||||
} else if let Some(rest) = text.strip_prefix("https://") {
|
if rest.is_empty()
|
||||||
(Scheme::Https, rest)
|
|| rest.contains('/')
|
||||||
} else {
|
|| rest.contains('@')
|
||||||
return Err(EndpointError::UnsupportedScheme);
|
|| rest.contains('"')
|
||||||
};
|
|| rest.contains('\\')
|
||||||
if rest.is_empty() {
|
|| rest.chars().any(|c| c.is_whitespace() || c.is_control())
|
||||||
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 == '\\')
|
|
||||||
{
|
{
|
||||||
return Err(EndpointError::BadHost);
|
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)?;
|
let (host, port) = rest.rsplit_once(':').ok_or(EndpointError::BadPort)?;
|
||||||
(host.to_string(), port)
|
|
||||||
};
|
|
||||||
if host.is_empty() {
|
if host.is_empty() {
|
||||||
return Err(EndpointError::BadHost);
|
return Err(EndpointError::BadHost);
|
||||||
}
|
}
|
||||||
let port: u16 = port.parse().map_err(|_| EndpointError::BadPort)?;
|
let port: u16 = port.parse().map_err(|_| EndpointError::BadPort)?;
|
||||||
if port == 0 {
|
Ok(Endpoint {
|
||||||
return Err(EndpointError::BadPort);
|
host: host.to_string(),
|
||||||
}
|
port,
|
||||||
Ok(Endpoint { scheme, host, port })
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn base(&self) -> String {
|
pub fn base(&self) -> String {
|
||||||
if self.host.contains(':') {
|
format!("http://{}:{}", self.host, self.port)
|
||||||
format!("{}://[{}]:{}", self.scheme.as_str(), self.host, self.port)
|
|
||||||
} else {
|
|
||||||
format!("{}://{}:{}", self.scheme.as_str(), self.host, self.port)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolve the endpoint and enforce the transport policy.
|
fn socket_addrs(&self) -> std::io::Result<Vec<SocketAddr>> {
|
||||||
///
|
(self.host.as_str(), self.port)
|
||||||
/// 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)
|
|
||||||
.to_socket_addrs()
|
.to_socket_addrs()
|
||||||
.map_err(|e| AiError::Provider(format!("cannot resolve {}: {e}", self.host)))?
|
.map(|it| it.collect())
|
||||||
.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])
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The connection state a frontend should display. Only [`ConnectionState::Ready`]
|
/// The connection state a frontend should display. `Ready` means the server is
|
||||||
/// follows a real, validated model response for the current connection/model.
|
/// reachable, authenticated, API-compatible *and* has at least one model; it
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
/// 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")]
|
#[serde(rename_all = "snake_case")]
|
||||||
pub enum ConnectionState {
|
pub enum ConnectionState {
|
||||||
/// The destination did not satisfy the transport policy.
|
Disconnected,
|
||||||
InsecureTransport,
|
|
||||||
/// The server could not be reached.
|
|
||||||
Unreachable,
|
|
||||||
/// The server demanded authentication we did not supply.
|
|
||||||
AuthenticationRequired,
|
AuthenticationRequired,
|
||||||
/// The server rejected the authentication we supplied.
|
ReachableNoModel,
|
||||||
AuthenticationRejected,
|
|
||||||
/// A health response arrived but the API is not the expected shape.
|
|
||||||
Incompatible,
|
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,
|
Ready,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct Capability {
|
pub struct Capability {
|
||||||
pub state: ConnectionState,
|
pub state: ConnectionState,
|
||||||
pub tcp_reachable: bool,
|
pub tcp_reachable: bool,
|
||||||
|
|
@ -198,467 +111,380 @@ pub struct Capability {
|
||||||
pub server_version: Option<String>,
|
pub server_version: Option<String>,
|
||||||
pub provider_count: usize,
|
pub provider_count: usize,
|
||||||
pub model_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,
|
pub detail: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Capability {
|
impl Capability {
|
||||||
fn new(state: ConnectionState, detail: impl Into<String>) -> Self {
|
fn disconnected(detail: impl Into<String>) -> Self {
|
||||||
Self {
|
Self {
|
||||||
state,
|
state: ConnectionState::Disconnected,
|
||||||
tcp_reachable: false,
|
tcp_reachable: false,
|
||||||
healthy: false,
|
healthy: false,
|
||||||
server_version: None,
|
server_version: None,
|
||||||
provider_count: 0,
|
provider_count: 0,
|
||||||
model_count: 0,
|
model_count: 0,
|
||||||
connected_model_count: 0,
|
|
||||||
selected_provider: None,
|
|
||||||
selected_model: None,
|
|
||||||
selected_model_available: false,
|
|
||||||
detail: detail.into(),
|
detail: detail.into(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Inputs for a probe. `auth` is the server basic-auth password (distinct from
|
#[derive(Debug, Deserialize)]
|
||||||
/// any model provider credential).
|
struct Health {
|
||||||
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 {
|
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
healthy: bool,
|
healthy: bool,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
version: Option<String>,
|
version: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn http_base(endpoint: &Endpoint) -> String {
|
#[derive(Debug, Deserialize)]
|
||||||
endpoint.base()
|
struct Providers {
|
||||||
|
#[serde(default)]
|
||||||
|
providers: Vec<Provider>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn auth_required_state(auth_supplied: bool, status: u16) -> ConnectionState {
|
#[derive(Debug, Deserialize)]
|
||||||
match (auth_supplied, status) {
|
struct Provider {
|
||||||
(true, _) => ConnectionState::AuthenticationRejected,
|
#[serde(default)]
|
||||||
(false, 403) => ConnectionState::AuthenticationRejected,
|
models: std::collections::BTreeMap<String, serde_json::Value>,
|
||||||
_ => ConnectionState::AuthenticationRequired,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Probe the server and classify the connection without claiming model
|
/// Probe an OpenCode server and classify the connection.
|
||||||
/// readiness. The connection is pinned to the policy-checked address.
|
pub fn probe(endpoint: &Endpoint, timeout: Duration) -> Capability {
|
||||||
pub fn probe<H: HttpClient>(http: &H, endpoint: &Endpoint, request: &ProbeRequest) -> Capability {
|
let addrs = match endpoint.socket_addrs() {
|
||||||
let target = match endpoint.checked_target() {
|
Ok(addrs) if !addrs.is_empty() => addrs,
|
||||||
Ok(target) => target,
|
Ok(_) => return Capability::disconnected("host did not resolve"),
|
||||||
Err(error) => {
|
Err(e) => return Capability::disconnected(format!("resolve failed: {e}")),
|
||||||
return Capability::new(ConnectionState::InsecureTransport, error.to_string())
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
let resolve = Some((endpoint.host.clone(), endpoint.port, target.ip()));
|
// A failed TCP connect is the only way to be certain the service is down.
|
||||||
|
if TcpStream::connect_timeout(&addrs[0], timeout).is_err() {
|
||||||
// The `/provider` catalog can be several MiB on a server with many
|
return Capability::disconnected("connect failed");
|
||||||
// configured providers; health is tiny. Both are bounded.
|
}
|
||||||
const HEALTH_MAX_BODY: u64 = 64 * 1024;
|
// Each request uses its own short-lived connection (Connection: close),
|
||||||
const CATALOG_MAX_BODY: u64 = 16 * 1024 * 1024;
|
// which is what the health/config endpoints expect and keeps the client
|
||||||
let make = |path: &str, max_body: u64| -> HttpRequest {
|
// simple and redirect-free.
|
||||||
let mut req = HttpRequest::get(format!("{}{path}", http_base(endpoint)));
|
let timeout = timeout;
|
||||||
req.timeout = request.timeout;
|
let request = |path: &str| -> std::io::Result<(u16, String)> {
|
||||||
req.connect_timeout = request.timeout.min(Duration::from_secs(10));
|
let mut stream = TcpStream::connect_timeout(&addrs[0], timeout)?;
|
||||||
req.max_body = max_body;
|
let _ = stream.set_read_timeout(Some(timeout));
|
||||||
req.resolve = resolve.clone();
|
let _ = stream.set_write_timeout(Some(timeout));
|
||||||
req.auth = request.auth.clone();
|
get(&mut stream, &endpoint.host, path)
|
||||||
req
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Health is the API-compatibility signal.
|
// Health first: it is the API-compatibility signal.
|
||||||
let health = match http.request(&make("/global/health", HEALTH_MAX_BODY)) {
|
let (status, body) = match request("/global/health") {
|
||||||
Ok(response) => response,
|
Ok(pair) => pair,
|
||||||
Err(error) => {
|
Err(e) => {
|
||||||
return Capability::new(ConnectionState::Unreachable, error.to_string());
|
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 status == 401 || status == 403 {
|
||||||
if capability.state != ConnectionState::Reachable {
|
return Capability {
|
||||||
// Health did not produce a usable server; report that state now.
|
state: ConnectionState::AuthenticationRequired,
|
||||||
if matches!(
|
tcp_reachable: true,
|
||||||
capability.state,
|
healthy: false,
|
||||||
ConnectionState::AuthenticationRequired | ConnectionState::AuthenticationRejected
|
server_version: None,
|
||||||
) {
|
provider_count: 0,
|
||||||
capability.tcp_reachable = true;
|
model_count: 0,
|
||||||
}
|
detail: format!("server requires authentication (HTTP {status})"),
|
||||||
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 !catalog_response.is_success() {
|
}
|
||||||
capability.state = match catalog_response.status {
|
if status != 200 {
|
||||||
401 => auth_required_state(request.auth.is_some(), 401),
|
return Capability {
|
||||||
403 => ConnectionState::AuthenticationRejected,
|
state: ConnectionState::Incompatible,
|
||||||
_ => 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) {
|
let health: Health = match serde_json::from_str(&body) {
|
||||||
Ok(catalog) => catalog,
|
Ok(h) => h,
|
||||||
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,
|
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
return Capability::new(
|
return Capability {
|
||||||
ConnectionState::Incompatible,
|
state: ConnectionState::Incompatible,
|
||||||
"/global/health was not the expected JSON",
|
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 {
|
if !health.healthy {
|
||||||
return Capability::new(ConnectionState::Incompatible, "server reported unhealthy");
|
return Capability {
|
||||||
}
|
state: ConnectionState::Incompatible,
|
||||||
let mut capability = Capability::new(ConnectionState::Reachable, "healthy server");
|
tcp_reachable: true,
|
||||||
capability.healthy = true;
|
healthy: false,
|
||||||
capability.sign_healthy(health.version);
|
server_version: health.version,
|
||||||
capability
|
provider_count: 0,
|
||||||
}
|
model_count: 0,
|
||||||
|
detail: "server reported unhealthy".into(),
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if capability.selected_provider.is_some() && !capability.selected_model_available {
|
// Providers: authentication and model availability.
|
||||||
capability.state = ConnectionState::SelectedModelUnavailable;
|
let (pstatus, pbody) = request("/config/providers").unwrap_or((0, String::new()));
|
||||||
capability.detail = format!(
|
if pstatus == 401 || pstatus == 403 {
|
||||||
"provider/model {}:{} is not available in the catalog",
|
return Capability {
|
||||||
request.provider.as_deref().unwrap_or("?"),
|
state: ConnectionState::AuthenticationRequired,
|
||||||
request.model.as_deref().unwrap_or("?")
|
tcp_reachable: true,
|
||||||
);
|
healthy: true,
|
||||||
} else if capability.model_count > 0 {
|
server_version: health.version,
|
||||||
capability.state = ConnectionState::ModelCatalog;
|
provider_count: 0,
|
||||||
capability.detail = format!(
|
model_count: 0,
|
||||||
"{} provider(s), {} model(s), {} connected",
|
detail: format!("provider list requires authentication (HTTP {pstatus})"),
|
||||||
capability.provider_count, capability.model_count, capability.connected_model_count
|
};
|
||||||
);
|
}
|
||||||
|
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 {
|
} else {
|
||||||
capability.state = ConnectionState::Reachable;
|
ConnectionState::Ready
|
||||||
capability.detail = "server is healthy but no model is configured".into();
|
};
|
||||||
|
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)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
use std::sync::Mutex;
|
use std::io::Read as _;
|
||||||
|
use std::net::TcpListener;
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
struct FakeHttp {
|
fn spawn_server(routes: Vec<(&'static str, u16, &'static str)>) -> Endpoint {
|
||||||
responses: Mutex<Vec<HttpResponse>>,
|
use std::collections::HashMap;
|
||||||
requests: Mutex<Vec<HttpRequest>>,
|
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;
|
||||||
}
|
}
|
||||||
|
let request = String::from_utf8_lossy(&buf[..n]);
|
||||||
impl FakeHttp {
|
let want = request
|
||||||
fn new(responses: Vec<(u16, &str)>) -> Self {
|
.lines()
|
||||||
Self {
|
.next()
|
||||||
responses: Mutex::new(
|
.and_then(|l| l.split_whitespace().nth(1))
|
||||||
responses
|
.unwrap_or("");
|
||||||
.into_iter()
|
let (code, payload) = routes.get(want).copied().unwrap_or((404, "{}"));
|
||||||
.map(|(status, body)| HttpResponse {
|
let response = format!(
|
||||||
status,
|
"HTTP/1.1 {code} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{payload}",
|
||||||
body: body.to_string(),
|
payload.len()
|
||||||
})
|
);
|
||||||
.collect(),
|
let _ = stream.write_all(response.as_bytes());
|
||||||
),
|
|
||||||
requests: Mutex::new(Vec::new()),
|
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
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]
|
#[test]
|
||||||
fn parses_endpoints_and_rejects_unsafe_forms() {
|
fn parses_and_rejects_endpoints() {
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Endpoint::parse("http://127.0.0.1:4096").unwrap(),
|
Endpoint::parse("http://127.0.0.1:4096").unwrap(),
|
||||||
Endpoint {
|
Endpoint {
|
||||||
scheme: Scheme::Http,
|
|
||||||
host: "127.0.0.1".into(),
|
host: "127.0.0.1".into(),
|
||||||
port: 4096
|
port: 4096
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
let v6 = Endpoint::parse("https://[::1]:4096").unwrap();
|
|
||||||
assert_eq!(v6.host, "::1");
|
|
||||||
assert_eq!(v6.scheme, Scheme::Https);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Endpoint::parse("ftp://host:1"),
|
Endpoint::parse("https://127.0.0.1:4096"),
|
||||||
Err(EndpointError::UnsupportedScheme)
|
Err(EndpointError::NotHttp)
|
||||||
);
|
);
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
Endpoint::parse("http://user:pw@host:1"),
|
Endpoint::parse("http://user@host:1"),
|
||||||
Err(EndpointError::UserInfo)
|
Err(EndpointError::BadHost)
|
||||||
);
|
|
||||||
assert_eq!(
|
|
||||||
Endpoint::parse("http://host:1/v1/chat"),
|
|
||||||
Err(EndpointError::PathNotAllowed)
|
|
||||||
);
|
);
|
||||||
assert_eq!(Endpoint::parse("http://host"), Err(EndpointError::BadPort));
|
assert_eq!(Endpoint::parse("http://host"), Err(EndpointError::BadPort));
|
||||||
assert_eq!(
|
assert!(Endpoint::parse("http://host:1/../../etc").is_err());
|
||||||
Endpoint::parse("http://host:0"),
|
assert!(Endpoint::parse("").is_err());
|
||||||
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"));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn transport_policy_enforces_loopback_for_plain_http() {
|
fn probe_reports_ready_with_models() {
|
||||||
// An IP literal avoids DNS and works offline.
|
let endpoint = spawn_server(vec![
|
||||||
let public = Endpoint::parse("http://93.184.216.34:80").unwrap();
|
(
|
||||||
let err = public.checked_target().unwrap_err().to_string();
|
"/global/health",
|
||||||
assert!(err.contains("refusing plain http"), "{err}");
|
200,
|
||||||
// https is allowed (certificate verification happens in the transport).
|
r#"{"healthy":true,"version":"1.18.32"}"#,
|
||||||
let secure = Endpoint::parse("https://93.184.216.34:443").unwrap();
|
),
|
||||||
assert!(secure.checked_target().is_ok());
|
(
|
||||||
// loopback http is allowed and pinned.
|
"/config/providers",
|
||||||
let target = endpoint().checked_target().unwrap();
|
200,
|
||||||
assert!(target.ip().is_loopback());
|
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]
|
#[test]
|
||||||
fn probe_reports_a_model_catalog_without_leaking_keys() {
|
fn probe_reports_reachable_but_model_less() {
|
||||||
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
|
let endpoint = spawn_server(vec![
|
||||||
let capability = probe(&http, &endpoint(), &ProbeRequest::new());
|
(
|
||||||
assert_eq!(capability.state, ConnectionState::ModelCatalog);
|
"/global/health",
|
||||||
assert_eq!(capability.model_count, 1);
|
200,
|
||||||
assert_eq!(capability.connected_model_count, 1);
|
r#"{"healthy":true,"version":"1.18.32"}"#,
|
||||||
let debug = format!("{capability:?}");
|
),
|
||||||
assert!(
|
("/config/providers", 200, r#"{"providers":[]}"#),
|
||||||
!debug.contains("SECRET"),
|
]);
|
||||||
"capability leaked a key: {debug}"
|
let capability = probe(&endpoint, Duration::from_secs(2));
|
||||||
);
|
assert_eq!(capability.state, ConnectionState::ReachableNoModel);
|
||||||
// The catalog request carried no credentials.
|
|
||||||
assert!(http.requests.lock().unwrap()[0].auth.is_none());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn probe_reports_selected_model_unavailable() {
|
fn probe_reports_authentication_required() {
|
||||||
let http = FakeHttp::new(vec![(200, health()), (200, catalog())]);
|
let endpoint = spawn_server(vec![("/global/health", 401, r#"{"error":"unauthorized"}"#)]);
|
||||||
let mut request = ProbeRequest::new();
|
let capability = probe(&endpoint, Duration::from_secs(2));
|
||||||
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());
|
|
||||||
assert_eq!(capability.state, ConnectionState::AuthenticationRequired);
|
assert_eq!(capability.state, ConnectionState::AuthenticationRequired);
|
||||||
|
assert!(capability.tcp_reachable);
|
||||||
// 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());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn probe_reports_incompatible_and_unreachable() {
|
fn probe_reports_incompatible_api() {
|
||||||
let http = FakeHttp::new(vec![(404, "{}")]);
|
let endpoint = spawn_server(vec![("/global/health", 404, "{}")]);
|
||||||
assert_eq!(
|
let capability = probe(&endpoint, Duration::from_secs(2));
|
||||||
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());
|
|
||||||
assert_eq!(capability.state, ConnectionState::Incompatible);
|
assert_eq!(capability.state, ConnectionState::Incompatible);
|
||||||
assert_eq!(capability.model_count, 0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_empty_catalog_is_reachable_not_ready() {
|
fn probe_reports_disconnected_for_a_closed_port() {
|
||||||
let http = FakeHttp::new(vec![(200, health()), (200, r#"{"all":[],"connected":[]}"#)]);
|
let endpoint = Endpoint {
|
||||||
let capability = probe(&http, &endpoint(), &ProbeRequest::new());
|
host: "127.0.0.1".into(),
|
||||||
assert_eq!(capability.state, ConnectionState::Reachable);
|
port: 1,
|
||||||
assert_ne!(capability.state, ConnectionState::Ready);
|
};
|
||||||
|
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]
|
#[test]
|
||||||
fn capability_serialisation_has_no_credential_fields() {
|
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();
|
let json = serde_json::to_string(&capability).unwrap();
|
||||||
assert!(!json.to_lowercase().contains("key"));
|
assert!(!json.to_lowercase().contains("key"));
|
||||||
|
assert!(!json.contains("sk-"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -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:?}"
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
@ -11,11 +11,10 @@ use std::process::ExitCode;
|
||||||
|
|
||||||
use clap::Parser;
|
use clap::Parser;
|
||||||
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
|
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::action::{parse_action, parse_natural, SystemAction};
|
||||||
use phoebus_core::transaction::TransactionRecord;
|
use phoebus_core::transaction::TransactionRecord;
|
||||||
use phoebus_core::{AiBackend, InstallConfig, Redactor};
|
use phoebus_core::{InstallConfig, Redactor};
|
||||||
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
|
||||||
use phoebus_executor::{
|
use phoebus_executor::{
|
||||||
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization,
|
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization,
|
||||||
Exec, Logger, RealRunner, Result,
|
Exec, Logger, RealRunner, Result,
|
||||||
|
|
@ -62,26 +61,6 @@ struct Cli {
|
||||||
/// Run the assistant without the OS-level sandbox (development only).
|
/// Run the assistant without the OS-level sandbox (development only).
|
||||||
#[arg(long)]
|
#[arg(long)]
|
||||||
no_sandbox: bool,
|
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 {
|
struct SysConfirm {
|
||||||
|
|
@ -235,16 +214,6 @@ fn gather_facts(exec: &Exec) -> SystemFacts {
|
||||||
SystemFacts::from_system(&config, &hardware, &history, binhost, None)
|
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.
|
/// The provider selected on the command line or the environment.
|
||||||
fn resolve_provider(cli: &Cli) -> ProviderKind {
|
fn resolve_provider(cli: &Cli) -> ProviderKind {
|
||||||
let raw = cli
|
let raw = cli
|
||||||
|
|
@ -301,105 +270,41 @@ fn run_ask(
|
||||||
exec: &Exec,
|
exec: &Exec,
|
||||||
instruction: &str,
|
instruction: &str,
|
||||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
let facts = gather_facts(exec);
|
let provider = resolve_provider(cli);
|
||||||
let backend = resolve_backend(cli);
|
if provider == ProviderKind::None {
|
||||||
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 {
|
|
||||||
deterministic_fallback(instruction);
|
deterministic_fallback(instruction);
|
||||||
return Err("no AI provider configured".into());
|
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) {
|
let key = match api_key_file(cli) {
|
||||||
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
|
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
|
||||||
None => None,
|
None => None,
|
||||||
};
|
};
|
||||||
if resolved.requires_key() && key.is_none() {
|
if provider.requires_key() && key.is_none() {
|
||||||
deterministic_fallback(instruction);
|
deterministic_fallback(instruction);
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
"provider `{}` requires --ai-api-key-file (mode 0600)",
|
"provider `{}` requires --ai-api-key-file (mode 0600)",
|
||||||
resolved.as_str()
|
provider.as_str()
|
||||||
)
|
)
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let facts = gather_facts(exec);
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Sending these bounded system facts to {} \
|
"Sending these bounded system facts to {} (no passwords, files or home directories):",
|
||||||
(no passwords, files or home directories):",
|
provider.as_str()
|
||||||
resolved.as_str()
|
|
||||||
);
|
);
|
||||||
eprintln!("{}", facts.render());
|
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(
|
let transport = phoebus_executor::ai::CurlTransport::new(exec, key);
|
||||||
provider,
|
let transport = if cli.no_sandbox {
|
||||||
&endpoint,
|
transport
|
||||||
&model,
|
} else {
|
||||||
&facts,
|
transport.sandboxed()
|
||||||
instruction,
|
};
|
||||||
transport.as_ref(),
|
let plan: AssistantPlan =
|
||||||
) {
|
match complete_plan(provider, &endpoint, &model, &facts, instruction, &transport) {
|
||||||
Ok(plan) => plan,
|
Ok(plan) => plan,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("The model is unavailable or returned an unusable plan: {e}");
|
eprintln!("The model is unavailable or returned an unusable plan: {e}");
|
||||||
|
|
|
||||||
|
|
@ -18,10 +18,9 @@ use std::io::{self, BufRead, Write};
|
||||||
|
|
||||||
use crate::{ai_guide, InstallObserver, Installer};
|
use crate::{ai_guide, InstallObserver, Installer};
|
||||||
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
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::ai::CurlTransport;
|
||||||
use phoebus_executor::auth::{authorize, Confirmation};
|
use phoebus_executor::auth::{authorize, Confirmation};
|
||||||
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
|
||||||
use phoebus_executor::{Exec, Result as ExecResult};
|
use phoebus_executor::{Exec, Result as ExecResult};
|
||||||
|
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
|
|
@ -71,10 +70,6 @@ struct SecretsPatch {
|
||||||
root_password: Option<String>,
|
root_password: Option<String>,
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
ai_api_key: Option<String>,
|
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
|
/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE
|
||||||
|
|
@ -169,12 +164,7 @@ pub struct Bridge {
|
||||||
user_password: Option<SecretString>,
|
user_password: Option<SecretString>,
|
||||||
root_password: Option<SecretString>,
|
root_password: Option<SecretString>,
|
||||||
api_key: Option<SecretString>,
|
api_key: Option<SecretString>,
|
||||||
opencode_password: Option<SecretString>,
|
|
||||||
approved_digest: Option<String>,
|
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>>,
|
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
||||||
/// One destructive transaction at a time. An approval is single-use: it is
|
/// 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
|
/// consumed when the install starts so a replay, a second frontend or a
|
||||||
|
|
@ -193,9 +183,7 @@ impl Bridge {
|
||||||
user_password: None,
|
user_password: None,
|
||||||
root_password: None,
|
root_password: None,
|
||||||
api_key: None,
|
api_key: None,
|
||||||
opencode_password: None,
|
|
||||||
approved_digest: None,
|
approved_digest: None,
|
||||||
validated_ai: None,
|
|
||||||
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
||||||
installing: false,
|
installing: false,
|
||||||
installed: false,
|
installed: false,
|
||||||
|
|
@ -211,9 +199,7 @@ impl Bridge {
|
||||||
user_password: None,
|
user_password: None,
|
||||||
root_password: None,
|
root_password: None,
|
||||||
api_key: None,
|
api_key: None,
|
||||||
opencode_password: None,
|
|
||||||
approved_digest: None,
|
approved_digest: None,
|
||||||
validated_ai: None,
|
|
||||||
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
||||||
installing: false,
|
installing: false,
|
||||||
installed: false,
|
installed: false,
|
||||||
|
|
@ -265,7 +251,6 @@ impl Bridge {
|
||||||
"plan" => self.plan(),
|
"plan" => self.plan(),
|
||||||
"destructive_preview" => self.destructive_preview(),
|
"destructive_preview" => self.destructive_preview(),
|
||||||
"ai_check" => self.ai_check(),
|
"ai_check" => self.ai_check(),
|
||||||
"ai_test" => self.ai_test(),
|
|
||||||
"approve" => self.approve(&request),
|
"approve" => self.approve(&request),
|
||||||
"start_install" => return self.start_install(id, &request, out),
|
"start_install" => return self.start_install(id, &request, out),
|
||||||
"log_tail" => self.log_tail(&request),
|
"log_tail" => self.log_tail(&request),
|
||||||
|
|
@ -420,9 +405,6 @@ impl Bridge {
|
||||||
|
|
||||||
self.installer.reconfigure(config);
|
self.installer.reconfigure(config);
|
||||||
self.approved_digest = None;
|
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();
|
let issues = self.installer.validate();
|
||||||
Ok(json!({
|
Ok(json!({
|
||||||
"accepted": true,
|
"accepted": true,
|
||||||
|
|
@ -445,7 +427,6 @@ impl Bridge {
|
||||||
&patch.user_password,
|
&patch.user_password,
|
||||||
&patch.root_password,
|
&patch.root_password,
|
||||||
&patch.ai_api_key,
|
&patch.ai_api_key,
|
||||||
&patch.opencode_password,
|
|
||||||
]
|
]
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.flatten()
|
.flatten()
|
||||||
|
|
@ -474,20 +455,12 @@ impl Bridge {
|
||||||
self.installer.exec.register_secret(&s);
|
self.installer.exec.register_secret(&s);
|
||||||
self.api_key = Some(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.
|
// Report only presence, never values.
|
||||||
Ok(json!({
|
Ok(json!({
|
||||||
"luks_set": self.luks.is_some(),
|
"luks_set": self.luks.is_some(),
|
||||||
"user_password_set": self.user_password.is_some(),
|
"user_password_set": self.user_password.is_some(),
|
||||||
"root_password_set": self.root_password.is_some(),
|
"root_password_set": self.root_password.is_some(),
|
||||||
"ai_api_key_set": self.api_key.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> {
|
fn ai_check(&mut self) -> Result<Value, String> {
|
||||||
let facts = self.installer.system_facts();
|
let facts = self.installer.system_facts();
|
||||||
let backend = self.installer.config.ai.backend;
|
let api_key_present = self.api_key.is_some();
|
||||||
let api_key = self.api_key.clone();
|
let Bridge {
|
||||||
let opencode_password = self.opencode_password.clone();
|
installer,
|
||||||
let value = {
|
api_key,
|
||||||
let Installer { exec, config, .. } = &mut self.installer;
|
approved_digest,
|
||||||
let redactor = exec.redactor();
|
..
|
||||||
match backend {
|
} = self;
|
||||||
AiBackend::OpenCode => {
|
let Installer { exec, config, .. } = installer;
|
||||||
let transport = opencode_transport(exec, config, opencode_password)?;
|
|
||||||
review_opencode(config, redactor, facts, &transport)?
|
|
||||||
}
|
|
||||||
AiBackend::Direct => {
|
|
||||||
let transport = CurlTransport::new(exec, api_key.clone());
|
let transport = CurlTransport::new(exec, api_key.clone());
|
||||||
review_proposal(config, redactor, facts, api_key.is_some(), &transport)?
|
let value = review_proposal(config, exec.redactor(), facts, api_key_present, &transport)?;
|
||||||
}
|
*approved_digest = None;
|
||||||
}
|
|
||||||
};
|
|
||||||
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());
|
|
||||||
Ok(value)
|
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).
|
/// Validate the provider connection and review the proposal (fail-closed).
|
||||||
/// Exposed so tests can drive it with a canned transport.
|
/// Exposed so tests can drive it with a canned transport.
|
||||||
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
||||||
let facts = self.installer.system_facts();
|
let facts = self.installer.system_facts();
|
||||||
let api_key_present = self.api_key.is_some();
|
let api_key_present = self.api_key.is_some();
|
||||||
let value = {
|
let Bridge {
|
||||||
let Installer { exec, config, .. } = &mut self.installer;
|
installer,
|
||||||
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
|
approved_digest,
|
||||||
};
|
..
|
||||||
self.approved_digest = None;
|
} = self;
|
||||||
self.validated_ai = Some(self.plan_digest());
|
let Installer { exec, config, .. } = installer;
|
||||||
|
let value = review_proposal(config, exec.redactor(), facts, api_key_present, transport)?;
|
||||||
|
*approved_digest = None;
|
||||||
Ok(value)
|
Ok(value)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -659,20 +558,18 @@ impl Bridge {
|
||||||
}
|
}
|
||||||
|
|
||||||
// AI is mandatory to install unless this is a dry run or an explicit
|
// AI is mandatory to install unless this is a dry run or an explicit
|
||||||
// break-glass. A validated interaction is required: merely naming a
|
// break-glass (mirrors the CLI rule).
|
||||||
// provider is not enough. The validation is bound to the current
|
|
||||||
// configuration, so a change since validation invalidates it.
|
|
||||||
let dry_run = self.installer.config.runtime.dry_run;
|
let dry_run = self.installer.config.runtime.dry_run;
|
||||||
if !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")
|
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
||||||
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
||||||
.unwrap_or(false);
|
.unwrap_or(false);
|
||||||
let validated = self.validated_ai.as_deref() == Some(current.as_str());
|
if provider == ProviderKind::None && !break_glass {
|
||||||
if !validated && !break_glass {
|
|
||||||
return Err(
|
return Err(
|
||||||
"installing Phoebus requires a successful, validated AI interaction for \
|
"installing Phoebus requires a connected AI model; connect a provider \
|
||||||
the current configuration; connect and validate a model, or set \
|
or set PHOEBUS_NO_AI=1 for a deterministic install"
|
||||||
PHOEBUS_NO_AI=1 for a deterministic install"
|
|
||||||
.into(),
|
.into(),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
@ -705,7 +602,6 @@ impl Bridge {
|
||||||
// Consume the approval and mark the session busy before any destructive
|
// Consume the approval and mark the session busy before any destructive
|
||||||
// work: a replay or a second frontend can never reach storage_prepare.
|
// work: a replay or a second frontend can never reach storage_prepare.
|
||||||
self.approved_digest = None;
|
self.approved_digest = None;
|
||||||
self.validated_ai = None;
|
|
||||||
self.installing = true;
|
self.installing = true;
|
||||||
let outcome = self.installer.install_observed(
|
let outcome = self.installer.install_observed(
|
||||||
&auth,
|
&auth,
|
||||||
|
|
@ -861,109 +757,8 @@ fn config_digest(config: &InstallConfig) -> String {
|
||||||
format!("{:x}", hasher.finalize())
|
format!("{:x}", hasher.finalize())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The OpenCode server URL, provider id and model id, validated for presence.
|
/// Parse the provider from the configuration, validate the connection and apply
|
||||||
fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String), String> {
|
/// the reviewed proposal. This is the same `ai_guide` path the TUI uses.
|
||||||
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.
|
|
||||||
fn review_proposal(
|
fn review_proposal(
|
||||||
config: &mut InstallConfig,
|
config: &mut InstallConfig,
|
||||||
redactor: &phoebus_core::Redactor,
|
redactor: &phoebus_core::Redactor,
|
||||||
|
|
@ -993,17 +788,36 @@ fn review_proposal(
|
||||||
provider.as_str()
|
provider.as_str()
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
finish_review(
|
|
||||||
config,
|
let outcome =
|
||||||
redactor,
|
ai_guide::generate_and_review_at(config, &facts, provider, &endpoint, &model, transport)
|
||||||
facts,
|
.map_err(|e| {
|
||||||
provider,
|
// Error messages are redacted before they reach the GUI.
|
||||||
&endpoint,
|
format!(
|
||||||
provider.as_str(),
|
"connection or proposal failed: {}",
|
||||||
&model,
|
redactor.redact(&e.to_string())
|
||||||
transport,
|
|
||||||
"direct",
|
|
||||||
)
|
)
|
||||||
|
})?;
|
||||||
|
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`.
|
/// The stdio entry point used by `--gui-bridge`.
|
||||||
|
|
@ -1461,173 +1275,4 @@ mod tests {
|
||||||
let lines = call(&mut bridge, &line);
|
let lines = call(&mut bridge, &line);
|
||||||
assert_eq!(response(&lines)["ok"], json!(false));
|
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"]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -122,36 +122,10 @@ struct Cli {
|
||||||
gui_bridge: bool,
|
gui_bridge: bool,
|
||||||
|
|
||||||
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
|
/// 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
|
/// its capability as JSON. Read-only; exits nonzero unless a model is
|
||||||
/// is available. Never prints provider credentials.
|
/// available. Never prints provider credentials.
|
||||||
#[arg(long, value_name = "URL")]
|
#[arg(long, value_name = "URL")]
|
||||||
opencode_probe: Option<String>,
|
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;
|
struct TerminalConfirm;
|
||||||
|
|
@ -187,94 +161,6 @@ fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
|
||||||
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
|
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.
|
/// The provider selected on the command line, or the one the TUI/config chose.
|
||||||
fn resolve_provider(
|
fn resolve_provider(
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
|
|
@ -297,116 +183,48 @@ fn no_ai_requested(cli: &Cli) -> bool {
|
||||||
.unwrap_or(false)
|
.unwrap_or(false)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Installing Phoebus requires a **validated** AI interaction, not just a
|
/// Installing Phoebus requires a connected model. `--no-ai`/`--legacy` is the
|
||||||
/// non-empty provider name. `--no-ai`/`--legacy` is the explicit, documented
|
/// explicit, documented break-glass for recovery or automation.
|
||||||
/// break-glass for recovery or automation.
|
|
||||||
fn require_ai_for_install(
|
fn require_ai_for_install(
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
validated: bool,
|
provider: ProviderKind,
|
||||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||||
if no_ai_requested(cli) || validated {
|
if no_ai_requested(cli) || provider != ProviderKind::None {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
Err(
|
Err("installing Phoebus requires a connected AI model.\n\
|
||||||
"installing Phoebus requires a successful, validated AI interaction.\n\
|
Connect a provider (--ai-provider deepseek|openai|local, with \
|
||||||
Connect a provider (--ai-backend direct with --ai-provider \
|
--ai-api-key-file and/or --ai-endpoint), or pass --no-ai (alias \
|
||||||
deepseek|openai|local and --ai-api-key-file/--ai-endpoint, or \
|
--legacy) for a deterministic install."
|
||||||
--ai-backend opencode with --opencode-server/--opencode-provider/\
|
.into())
|
||||||
--opencode-model) and let it return a valid proposal, or pass --no-ai \
|
|
||||||
(alias --legacy) for a deterministic install."
|
|
||||||
.into(),
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Apply AI guidance to the configuration before the plan is shown or install
|
/// Apply AI guidance to the configuration before the plan is shown or install
|
||||||
/// runs. Returns `true` only when a model interaction produced a valid,
|
/// runs. The model never sees secrets and never executes anything: its response
|
||||||
/// reviewed proposal. The model never sees secrets and never executes anything.
|
/// is reviewed with mandatory evidence and applied atomically.
|
||||||
fn run_ai_guidance(
|
fn run_ai_guidance(
|
||||||
cli: &Cli,
|
cli: &Cli,
|
||||||
installer: &mut Installer,
|
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;
|
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
|
||||||
if !wants_ai {
|
if !wants_ai {
|
||||||
return Ok(false);
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(path) = &cli.ai_proposal_file {
|
if let Some(path) = &cli.ai_proposal_file {
|
||||||
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
|
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
|
||||||
println!("{}", outcome.render());
|
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 {
|
if provider == ProviderKind::None {
|
||||||
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
|
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!(
|
eprintln!(
|
||||||
"Sending these system facts to {} (no passwords, passphrases or files):",
|
"Sending these system facts to {} (no passwords, passphrases or files):",
|
||||||
provider.as_str()
|
provider.as_str()
|
||||||
|
|
@ -426,6 +244,7 @@ fn run_ai_guidance(
|
||||||
)
|
)
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
|
// A self-hosted local model usually needs no key.
|
||||||
(None, false) => None,
|
(None, false) => None,
|
||||||
};
|
};
|
||||||
let model = cli.ai_model.clone().unwrap_or_default();
|
let model = cli.ai_model.clone().unwrap_or_default();
|
||||||
|
|
@ -438,15 +257,10 @@ fn run_ai_guidance(
|
||||||
&model,
|
&model,
|
||||||
&transport,
|
&transport,
|
||||||
) {
|
) {
|
||||||
Ok(outcome) => {
|
Ok(outcome) => println!("{}", outcome.render()),
|
||||||
println!("{}", outcome.render());
|
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
|
||||||
Ok(true)
|
|
||||||
}
|
|
||||||
Err(e) => {
|
|
||||||
eprintln!("AI proposal rejected; continuing with the proven defaults: {e}");
|
|
||||||
Ok(false)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn main() -> ExitCode {
|
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 {
|
if let Some(url) = &cli.opencode_probe {
|
||||||
return Ok(run_opencode_probe(&cli, url, false));
|
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint};
|
||||||
}
|
let endpoint =
|
||||||
if let Some(url) = &cli.opencode_test {
|
Endpoint::parse(url).map_err(|e| format!("invalid OpenCode endpoint `{url}`: {e}"))?;
|
||||||
return Ok(run_opencode_probe(&cli, url, true));
|
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 {
|
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());
|
println!("{}", installer.system_facts().render());
|
||||||
return Ok(ExitCode::SUCCESS);
|
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
|
// AI is mandatory to install; a deterministic no-AI run needs the explicit
|
||||||
// provider name) is required; a deterministic no-AI run needs the explicit
|
|
||||||
// break-glass. Dry-run and plan modes are exempt.
|
// break-glass. Dry-run and plan modes are exempt.
|
||||||
if do_install && !installer.config.runtime.dry_run {
|
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 {
|
if let Some(path) = &cli.save_config {
|
||||||
|
|
|
||||||
|
|
@ -109,7 +109,7 @@ fn install_without_ai_is_refused() {
|
||||||
.expect("run phoebus-installer");
|
.expect("run phoebus-installer");
|
||||||
assert!(!out.status.success());
|
assert!(!out.status.success());
|
||||||
let err = String::from_utf8_lossy(&out.stderr);
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
assert!(err.contains("validated AI interaction"), "{err}");
|
assert!(err.contains("requires a connected AI"), "{err}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -122,31 +122,21 @@ fn no_ai_is_the_explicit_break_glass() {
|
||||||
.output()
|
.output()
|
||||||
.expect("run phoebus-installer");
|
.expect("run phoebus-installer");
|
||||||
let err = String::from_utf8_lossy(&out.stderr);
|
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}");
|
assert!(err.contains("configuration is incomplete"), "{flag}: {err}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_unreachable_provider_does_not_satisfy_the_ai_gate() {
|
fn local_provider_needs_no_key_at_the_gate() {
|
||||||
// A provider *name* is not enough: without a real, validated model
|
// A local provider satisfies the gate without --no-ai (it fails later at
|
||||||
// interaction the install is refused (a deliberately closed port makes the
|
// the incomplete config, not at the AI gate).
|
||||||
// result deterministic and offline).
|
|
||||||
let out = Command::new(bin())
|
let out = Command::new(bin())
|
||||||
.args([
|
.args(["--install", "--yes", "--ai", "--ai-provider", "local"])
|
||||||
"--install",
|
|
||||||
"--yes",
|
|
||||||
"--ai",
|
|
||||||
"--ai-provider",
|
|
||||||
"local",
|
|
||||||
"--ai-endpoint",
|
|
||||||
"http://127.0.0.1:1/v1/chat/completions",
|
|
||||||
])
|
|
||||||
.output()
|
.output()
|
||||||
.expect("run phoebus-installer");
|
.expect("run phoebus-installer");
|
||||||
assert!(!out.status.success());
|
|
||||||
let err = String::from_utf8_lossy(&out.stderr);
|
let err = String::from_utf8_lossy(&out.stderr);
|
||||||
assert!(err.contains("validated AI interaction"), "{err}");
|
assert!(!err.contains("requires a connected AI"), "{err}");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
|
|
@ -128,9 +128,6 @@ Singleton {
|
||||||
function aiCheck(cb) {
|
function aiCheck(cb) {
|
||||||
call("ai_check", {}, cb);
|
call("ai_check", {}, cb);
|
||||||
}
|
}
|
||||||
function aiTest(cb) {
|
|
||||||
call("ai_test", {}, cb);
|
|
||||||
}
|
|
||||||
function approve(eraseText, finalConfirmed, cb) {
|
function approve(eraseText, finalConfirmed, cb) {
|
||||||
call("approve", { erase: eraseText, final_confirm: finalConfirmed }, cb);
|
call("approve", { erase: eraseText, final_confirm: finalConfirmed }, cb);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -28,19 +28,11 @@ ShellRoot {
|
||||||
property string luksPw: ""
|
property string luksPw: ""
|
||||||
property string luksPw2: ""
|
property string luksPw2: ""
|
||||||
property string apiKey: ""
|
property string apiKey: ""
|
||||||
// OpenCode server password (basic auth), distinct from a provider API key.
|
|
||||||
property string opencodePassword: ""
|
|
||||||
|
|
||||||
property bool aiConnected: false
|
property bool aiConnected: false
|
||||||
property bool aiChecking: false
|
property bool aiChecking: false
|
||||||
property string aiError: ""
|
property string aiError: ""
|
||||||
property var aiApplied: []
|
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 stageStatus: ({})
|
||||||
property var stageOrder: []
|
property var stageOrder: []
|
||||||
|
|
@ -77,26 +69,6 @@ ShellRoot {
|
||||||
return JSON.parse(JSON.stringify(o));
|
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,
|
// QML `var` properties do not emit change signals for nested assignments,
|
||||||
// so bindings that read `cfg.*` would not update. Reassigning a clone
|
// so bindings that read `cfg.*` would not update. Reassigning a clone
|
||||||
// re-evaluates them. Used after a choice/toggle changes the configuration.
|
// re-evaluates them. Used after a choice/toggle changes the configuration.
|
||||||
|
|
@ -120,10 +92,6 @@ ShellRoot {
|
||||||
modelField.inputItem.text = shell.cfg.ai.model;
|
modelField.inputItem.text = shell.cfg.ai.model;
|
||||||
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
||||||
keyField.inputItem.text = shell.apiKey;
|
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;
|
pwField.inputItem.text = shell.userPw;
|
||||||
pw2Field.inputItem.text = shell.userPw2;
|
pw2Field.inputItem.text = shell.userPw2;
|
||||||
luksField.inputItem.text = shell.luksPw;
|
luksField.inputItem.text = shell.luksPw;
|
||||||
|
|
@ -262,7 +230,7 @@ ShellRoot {
|
||||||
shell.status = "";
|
shell.status = "";
|
||||||
const s = shell.step;
|
const s = shell.step;
|
||||||
if (s === 2) {
|
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.provider = "deepseek";
|
||||||
shell.cfg.ai.enabled = true;
|
shell.cfg.ai.enabled = true;
|
||||||
if (!shell.cfg.ai.model)
|
if (!shell.cfg.ai.model)
|
||||||
|
|
@ -310,26 +278,11 @@ ShellRoot {
|
||||||
}
|
}
|
||||||
|
|
||||||
function configureProvider(value) {
|
function configureProvider(value) {
|
||||||
|
shell.cfg.ai.provider = value;
|
||||||
shell.cfg.ai.enabled = value !== "none";
|
shell.cfg.ai.enabled = value !== "none";
|
||||||
shell.aiConnected = false;
|
shell.aiConnected = false;
|
||||||
shell.aiTested = false;
|
|
||||||
shell.aiTestMessage = "";
|
|
||||||
shell.aiError = "";
|
shell.aiError = "";
|
||||||
shell.aiApplied = [];
|
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")
|
if (value === "deepseek")
|
||||||
shell.cfg.ai.model = "deepseek-chat";
|
shell.cfg.ai.model = "deepseek-chat";
|
||||||
else if (value === "openai")
|
else if (value === "openai")
|
||||||
|
|
@ -338,37 +291,9 @@ ShellRoot {
|
||||||
shell.cfg.ai.model = shell.cfg.ai.model || "llama3.1";
|
shell.cfg.ai.model = shell.cfg.ai.model || "llama3.1";
|
||||||
modelField.inputItem.text = shell.cfg.ai.model;
|
modelField.inputItem.text = shell.cfg.ai.model;
|
||||||
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
||||||
}
|
|
||||||
shell.touchConfig();
|
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() {
|
function connectAi() {
|
||||||
shell.aiChecking = true;
|
shell.aiChecking = true;
|
||||||
shell.aiError = "";
|
shell.aiError = "";
|
||||||
|
|
@ -377,8 +302,6 @@ ShellRoot {
|
||||||
const secrets = {};
|
const secrets = {};
|
||||||
if (shell.apiKey.length > 0)
|
if (shell.apiKey.length > 0)
|
||||||
secrets.ai_api_key = shell.apiKey;
|
secrets.ai_api_key = shell.apiKey;
|
||||||
if (shell.opencodePassword.length > 0)
|
|
||||||
secrets.opencode_password = shell.opencodePassword;
|
|
||||||
Bridge.setSecrets(secrets, () => {
|
Bridge.setSecrets(secrets, () => {
|
||||||
applyConfig(() => {
|
applyConfig(() => {
|
||||||
Bridge.aiCheck(reply => {
|
Bridge.aiCheck(reply => {
|
||||||
|
|
@ -786,19 +709,17 @@ ShellRoot {
|
||||||
options: [
|
options: [
|
||||||
{ value: "deepseek", label: "DeepSeek" },
|
{ value: "deepseek", label: "DeepSeek" },
|
||||||
{ value: "openai", label: "OpenAI" },
|
{ value: "openai", label: "OpenAI" },
|
||||||
{ value: "local", label: "Local model" },
|
{ value: "local", label: "Local model" }
|
||||||
{ value: "opencode", label: "OpenCode agent" }
|
|
||||||
]
|
]
|
||||||
value: shell.isOpenCode ? "opencode" : (shell.cfg ? shell.cfg.ai.provider : "deepseek")
|
value: shell.cfg ? shell.cfg.ai.provider : "deepseek"
|
||||||
onSelected: value => shell.configureProvider(value)
|
onSelected: value => shell.configureProvider(value)
|
||||||
}
|
}
|
||||||
// -- direct providers ----------------------------------
|
|
||||||
PhoebusField {
|
PhoebusField {
|
||||||
id: keyField
|
id: keyField
|
||||||
label: "API key"
|
label: "API key"
|
||||||
placeholder: "Paste your provider key"
|
placeholder: "Paste your provider key"
|
||||||
secret: true
|
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
|
onEdited: value => shell.apiKey = value
|
||||||
}
|
}
|
||||||
PhoebusField {
|
PhoebusField {
|
||||||
|
|
@ -806,7 +727,6 @@ ShellRoot {
|
||||||
label: "Model"
|
label: "Model"
|
||||||
placeholder: "model name"
|
placeholder: "model name"
|
||||||
error: ""
|
error: ""
|
||||||
visible: shell.cfg && !shell.isOpenCode
|
|
||||||
onEdited: value => shell.cfg.ai.model = value
|
onEdited: value => shell.cfg.ai.model = value
|
||||||
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : ""
|
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : ""
|
||||||
}
|
}
|
||||||
|
|
@ -814,70 +734,21 @@ ShellRoot {
|
||||||
id: endpointField
|
id: endpointField
|
||||||
label: "Endpoint (local models)"
|
label: "Endpoint (local models)"
|
||||||
placeholder: "http://127.0.0.1:11434/v1/chat/completions"
|
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
|
onEdited: value => shell.cfg.ai.endpoint = value
|
||||||
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.endpoint ? shell.cfg.ai.endpoint : ""
|
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 {
|
Row {
|
||||||
spacing: 12
|
spacing: 12
|
||||||
PhoebusButton {
|
|
||||||
label: shell.aiTesting ? "Testing…" : "Test connection"
|
|
||||||
actionEnabled: !shell.aiTesting && !shell.aiChecking
|
|
||||||
onClicked: shell.testAi()
|
|
||||||
}
|
|
||||||
PhoebusButton {
|
PhoebusButton {
|
||||||
label: shell.aiChecking ? "Checking…" : "Connect and validate"
|
label: shell.aiChecking ? "Checking…" : "Connect and validate"
|
||||||
primary: true
|
primary: true
|
||||||
actionEnabled: !shell.aiChecking && !shell.aiTesting
|
actionEnabled: !shell.aiChecking
|
||||||
onClicked: shell.connectAi()
|
onClicked: shell.connectAi()
|
||||||
}
|
}
|
||||||
PhoebusChip {
|
PhoebusChip {
|
||||||
visible: shell.aiConnected
|
visible: shell.aiConnected
|
||||||
text: "Validated"
|
text: "Connected"
|
||||||
tone: Theme.success
|
|
||||||
}
|
|
||||||
PhoebusChip {
|
|
||||||
visible: shell.aiTested && !shell.aiConnected
|
|
||||||
text: "Model responded"
|
|
||||||
tone: Theme.success
|
tone: Theme.success
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -890,15 +761,6 @@ ShellRoot {
|
||||||
font.pixelSize: Theme.fontSmall
|
font.pixelSize: Theme.fontSmall
|
||||||
wrapMode: Text.WordWrap
|
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 {
|
PhoebusCard {
|
||||||
width: parent.width
|
width: parent.width
|
||||||
|
|
|
||||||
|
|
@ -59,15 +59,6 @@ BOOT_TIMEOUT = int(os.environ.get("BOOT_TIMEOUT", "900"))
|
||||||
INSTALL_TIMEOUT = int(os.environ.get("INSTALL_TIMEOUT", "10800"))
|
INSTALL_TIMEOUT = int(os.environ.get("INSTALL_TIMEOUT", "10800"))
|
||||||
SESSION_SETTLE = int(os.environ.get("SESSION_SETTLE", "20"))
|
SESSION_SETTLE = int(os.environ.get("SESSION_SETTLE", "20"))
|
||||||
BACKEND_SETTLE = int(os.environ.get("BACKEND_SETTLE", "30"))
|
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:
|
def _template_dir() -> Path:
|
||||||
|
|
@ -302,8 +293,6 @@ class Driver:
|
||||||
try:
|
try:
|
||||||
if self.mode == "gui":
|
if self.mode == "gui":
|
||||||
self.do_gui()
|
self.do_gui()
|
||||||
elif self.mode == "opencode":
|
|
||||||
self.do_opencode()
|
|
||||||
elif self.mode == "install":
|
elif self.mode == "install":
|
||||||
self.do_install()
|
self.do_install()
|
||||||
elif self.mode == "boot":
|
elif self.mode == "boot":
|
||||||
|
|
@ -485,10 +474,8 @@ class Driver:
|
||||||
label="duplicate-launch",
|
label="duplicate-launch",
|
||||||
)
|
)
|
||||||
n1, n2 = int(self.last_group(1)), int(self.last_group(2))
|
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(
|
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}",
|
f"n1={n1} n2={n2}",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -514,226 +501,8 @@ class Driver:
|
||||||
"ai-step-blocks-install", blocked,
|
"ai-step-blocks-install", blocked,
|
||||||
"the AI step allowed advancement without a connected model",
|
"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")
|
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:
|
def _installer_alive(self) -> bool:
|
||||||
assert self.child is not None
|
assert self.child is not None
|
||||||
self.child.sendline(
|
self.child.sendline(
|
||||||
|
|
@ -862,7 +631,7 @@ class Driver:
|
||||||
|
|
||||||
def main() -> int:
|
def main() -> int:
|
||||||
mode = sys.argv[1] if len(sys.argv) > 1 else ""
|
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__)
|
print(__doc__)
|
||||||
return 2
|
return 2
|
||||||
if mode in ("install", "boot") and not DISKS:
|
if mode in ("install", "boot") and not DISKS:
|
||||||
|
|
|
||||||
|
|
@ -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())
|
|
||||||
Loading…
Add table
Reference in a new issue