Compare commits
7 commits
fb4dcc5683
...
359f083bc2
| Author | SHA1 | Date | |
|---|---|---|---|
| 359f083bc2 | |||
| 802b843bc9 | |||
| c16014ade8 | |||
| 0d65d56eda | |||
| 5c3674e3c2 | |||
| 565521564c | |||
| 33afdaac9a |
24 changed files with 3926 additions and 646 deletions
13
Makefile
13
Makefile
|
|
@ -8,7 +8,7 @@
|
|||
|
||||
SHELL := /bin/bash
|
||||
|
||||
.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
|
||||
.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
|
||||
|
||||
help:
|
||||
@printf 'Phoebus OS targets:\n'
|
||||
|
|
@ -17,6 +17,7 @@ help:
|
|||
@printf ' make test run the Rust and VM-harness test suites\n'
|
||||
@printf ' make test-rust cargo test --workspace\n'
|
||||
@printf ' make test-vm python3 installer/tests/vm/test_vmsafety.py\n'
|
||||
@printf ' make opencode-acceptance live-model acceptance (needs PHOEBUS_OPENCODE_LIVE_*)\n'
|
||||
@printf ' make fmt cargo fmt --all\n'
|
||||
@printf ' make check fmt-check + clippy + tests\n'
|
||||
@printf ' make build release Rust installer\n'
|
||||
|
|
@ -44,6 +45,16 @@ test-rust:
|
|||
test-vm:
|
||||
python3 installer/tests/vm/test_vmsafety.py
|
||||
|
||||
# A real-model acceptance run. Fails (BLOCKED) when the live server is not
|
||||
# configured, so it can never pass by silently not running.
|
||||
opencode-acceptance:
|
||||
@if [ -z "$$PHOEBUS_OPENCODE_LIVE_URL" ] || [ -z "$$PHOEBUS_OPENCODE_LIVE_PROVIDER" ] || [ -z "$$PHOEBUS_OPENCODE_LIVE_MODEL" ]; then \
|
||||
echo "BLOCKED: set PHOEBUS_OPENCODE_LIVE_URL, PHOEBUS_OPENCODE_LIVE_PROVIDER and PHOEBUS_OPENCODE_LIVE_MODEL"; \
|
||||
exit 2; \
|
||||
fi
|
||||
cd installer-rs && PHOEBUS_OPENCODE_REQUIRE_LIVE=1 \
|
||||
cargo test -p phoebus-executor --test opencode_live -- --nocapture
|
||||
|
||||
fmt:
|
||||
cd installer-rs && cargo fmt --all
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,69 @@ Format: Keep a Changelog. Dates are UTC.
|
|||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
- **Real OpenCode agent-server adapter.** `phoebus-executor::opencode_client`
|
||||
implements the OpenCode session/message protocol over the project's curl
|
||||
transport and the `ModelTransport` trait, so the strict proposal parser,
|
||||
evidence review, bounded facts and executor are reused unchanged. The GUI
|
||||
("OpenCode agent"), the installer CLI (`--ai-backend opencode`,
|
||||
`--opencode-server/-provider/-model/-password-file`) and `sys ask` all use it.
|
||||
It creates a transient session per request, accepts only the completed
|
||||
assistant text parts, disables tools per message, and deletes the session.
|
||||
A JSON schema output mode is available in the protocol but is not used: the
|
||||
shipped DeepSeek models reject it, and the prompt carries an explicit change
|
||||
shape instead. The `opencode 1.18.32` contract was verified directly: session
|
||||
creation rejects a `model` field, `/provider` metadata can contain a
|
||||
credential and is reduced to ids/model names, and auth is HTTP Basic
|
||||
(`opencode` / `OPENCODE_SERVER_PASSWORD`).
|
||||
- **`--opencode-test`** obtains and validates a real model response (exit
|
||||
nonzero on failure), distinct from the read-only `--opencode-probe`. A live
|
||||
acceptance test (`make opencode-acceptance`) fails as BLOCKED when no server
|
||||
is configured, so it cannot pass by not running.
|
||||
- **Truthful OpenCode connection states** (`insecure_transport`, `unreachable`,
|
||||
`authentication_required`, `authentication_rejected`, `incompatible`,
|
||||
`reachable`, `model_catalog`, `selected_model_unavailable`); `ready` is
|
||||
reserved for a validated response and is never returned by the probe.
|
||||
- **GUI "Test connection"** and OpenCode connection controls, plus a backend
|
||||
selection (`ai.backend`) in canonical configuration.
|
||||
|
||||
### Security
|
||||
- **The mandatory-AI gate now requires a validated interaction.** Both the GUI
|
||||
bridge and the installer CLI refuse to install when only a provider name is
|
||||
configured; a successful, validated model interaction bound to the current
|
||||
configuration (and credential) is required. Changing the model, endpoint,
|
||||
server or a secret invalidates it. A direct provider or `--no-ai` remains the
|
||||
fallback.
|
||||
- **OpenCode transport policy is enforced.** Plain `http://` is accepted only
|
||||
when the resolved destination is loopback and the connection is pinned to the
|
||||
checked address; remote access is `https://` with certificate verification or
|
||||
an authenticated tunnel to loopback. Redirects, unsafe schemes and oversized
|
||||
or trickled bodies are bounded, and credentials travel only on curl's stdin.
|
||||
- **Credentials never surface.** The catalog is reduced to ids/model names;
|
||||
server responses that echo credentials are not retained, and tests feed
|
||||
credential-bearing bodies and assert they do not appear in errors or state.
|
||||
|
||||
### Verified
|
||||
- **The graphical installer uses the OpenCode adapter.** In a disposable
|
||||
graphical VM the wizard selected "OpenCode agent", entered the server,
|
||||
provider and model through the UI, obtained a real model response (Test
|
||||
connection) and a validated proposal (Connect and validate, green
|
||||
"Validated"). The `opencode` harness run passed 17/17 and the GUI regression
|
||||
25/25. A password-protected server was reached through authentication as
|
||||
well. The full graphical installation beyond the AI gate is still not run.
|
||||
|
||||
### Fixed
|
||||
- **A malformed model proposal now gets one bounded corrective retry** before
|
||||
the strict parser rejects the interaction (the shipped DeepSeek models
|
||||
occasionally keyed the change or rationale wrongly). The parser remains the
|
||||
final authority; a retry that still fails is still rejected.
|
||||
- **OpenCode client/probe defects found by testing:** the handwritten HTTP
|
||||
reader (no total deadline, UTF-8-unsafe chunk fallback) was removed in favour
|
||||
of the curl transport; the catalog is no longer parsed on a non-2xx status; a
|
||||
provider-shaped 500 can no longer look like a catalog; the duplicate-session
|
||||
harness check requires exactly one session; and GUI navigation is asserted
|
||||
from secret-free frontend state lines rather than inferred from a screenshot.
|
||||
|
||||
### Added
|
||||
- **OpenCode connection workflow and capability probe.** New ADR 0011 and
|
||||
`docs/OPENCODE.md` separate the four components (client, server, model
|
||||
|
|
|
|||
|
|
@ -3,27 +3,36 @@
|
|||
Rolling note between work sessions. **Update this file before you finish**, then
|
||||
commit it. It should be short and current; use `git log` for detail.
|
||||
|
||||
- **Last updated:** this session (2026-09-22), harness + security + polish.
|
||||
- **Current focus:** Hardened the VM harness (enforced qcow2/`/dev`/backing-chain
|
||||
safety, structured PASS/FAIL results, per-run OVMF+QMP, no `os.system`),
|
||||
fixed confirmed security defects (disk revalidation before partitioning,
|
||||
bridge replay/concurrency + input bounds, provider transport URL/size
|
||||
hardening, `TargetRoot` symlink escapes, and the `0 B` disk-size probe bug),
|
||||
added an OpenCode server capability probe + docs/ADR 0011, and fixed the
|
||||
welcome focus ring and the untruthful mid-install cancellation.
|
||||
- **Last updated:** this session (2026-09-22), OpenCode adapter.
|
||||
- **Current focus:** Implemented a real OpenCode agent-server adapter
|
||||
(`phoebus-executor::opencode_client`) that speaks the session/message protocol
|
||||
over curl and implements `ModelTransport`, wired into canonical config
|
||||
(`ai.backend = "opencode"`), the GUI ("OpenCode agent" + Test connection),
|
||||
the installer CLI (`--ai-backend opencode`, `--opencode-test`) and `sys ask`.
|
||||
The mandatory-AI gate now requires a validated interaction with invalidated
|
||||
state. The probe/transport were hardened (loopback/TLS policy, DNS pinning,
|
||||
status checks, auth), and the GUI harness gained exact-session and
|
||||
frontend-state assertions.
|
||||
- **Last verified (this session):**
|
||||
- `gui-driver.py gui` on the rebuilt ISO: **23/23 PASS**, exit 0. Welcome
|
||||
autostarts; Return launches the installer (focus fixed); duplicate sessions
|
||||
prevented; live medium protected; keyboard navigation reaches network + AI;
|
||||
advancing without a model is refused and starts nothing.
|
||||
- `make test` green (Rust + 16 harness unit tests); `cargo fmt --check`,
|
||||
`cargo clippy --workspace --all-targets` (no errors), release + static
|
||||
builds.
|
||||
- OpenCode probe: `ready` against `opencode 1.18.32`; `authentication_required`
|
||||
(exit 1) against an unauthenticated LAN bind.
|
||||
- ISO: `installer/live/phoebus-installer-amd64.iso` 1.6 GiB,
|
||||
`sha256 428dbd7547db8690596bf5c3a0d7a6fa8aee4c9f9eca1e926c216712dd050b36`;
|
||||
static binary `sha256 2f9cd4b36a12e469d2b6187166acaf8b11f7f382cc19f7ad08bb2a809c855591`.
|
||||
- 336 Rust tests + 16 harness tests green; fmt/clippy clean.
|
||||
- Real inference through `opencode 1.18.32` with `deepseek-v4-flash`;
|
||||
`--opencode-test` → `{"phoebus":"ok"}`; the GUI bridge `ai_check` applied 8
|
||||
reviewed changes; `sys ask` proposed and ran a read-only action.
|
||||
- Auth: none → `authentication_required`, wrong → `authentication_rejected`,
|
||||
correct → `model_catalog` + successful inference. Plain http to a LAN host
|
||||
→ `insecure_transport`, exit 1, no request sent.
|
||||
- 7 real-HTTP integration tests (status, chunked multibyte, oversize,
|
||||
redirect, disconnect, auth) and 2 env-gated live tests.
|
||||
- GUI acceptance in a disposable VM: `gui-driver.py opencode` passed 17/17
|
||||
(selected OpenCode, entered the endpoint/model through the UI, real model
|
||||
response + validated proposal); `gui-driver.py gui` passed 25/25.
|
||||
ISO `sha256 4db98db3…`, static binary `sha256 72c2dcd0…`.
|
||||
- **Not yet verified this session:** the full graphical **installation** through
|
||||
OpenCode past the AI gate (disk/account/review/ERASE/install/detached boot),
|
||||
and a separate physical computer. The pinned manifest is `v1.18.31` while the
|
||||
tested binary is `1.18.32`. On this server use `deepseek-flash`; the model
|
||||
must match the server's catalog (the GUI default `deepseek-chat` does not
|
||||
exist on it).
|
||||
- **Public repo:** <https://git.phoebus.club/phoebus/phoebus_os>
|
||||
(remote `origin`, SSH port 2222).
|
||||
|
||||
|
|
|
|||
239
docs/OPENCODE.md
239
docs/OPENCODE.md
|
|
@ -1,13 +1,9 @@
|
|||
# OpenCode connection workflow
|
||||
|
||||
OpenCode is used in two clearly separated ways:
|
||||
|
||||
1. **Developer workflow** — on this repository, inspecting sanitized evidence.
|
||||
Full tool access (shell, files, plugins) is fine because it runs as *you*,
|
||||
on *your* machine, against *your* checkout.
|
||||
2. **Phoebus assistant connection** — approved, bounded system facts and
|
||||
validated typed proposals. It must never inherit the developer tool
|
||||
permissions and never receives secrets.
|
||||
OpenCode is integrated as a **real agent-server connection**, not a renamed
|
||||
OpenAI-compatible endpoint. The adapter speaks OpenCode's session/message API
|
||||
and feeds the same strict proposal parser, evidence review and executor as the
|
||||
direct providers.
|
||||
|
||||
Read [ADR 0011](adr/0011-opencode-connection-boundary.md) first.
|
||||
|
||||
|
|
@ -16,84 +12,147 @@ Read [ADR 0011](adr/0011-opencode-connection-boundary.md) first.
|
|||
| Component | What it is | Where it runs |
|
||||
|-----------|------------|---------------|
|
||||
| OpenCode client | `opencode` TUI/CLI, or `opencode attach <url>` | your machine |
|
||||
| OpenCode server | `opencode serve` — an HTTP/JSON **agent** API, not a model API | usually the same machine as the client or the model |
|
||||
| Model inference service | DeepSeek/OpenAI, or a local OpenAI-compatible server (Ollama, llama.cpp, ...) | provider cloud or your LAN |
|
||||
| OpenCode server | `opencode serve` — an HTTP/JSON **agent** API, not a model API | same machine as the client or the model |
|
||||
| Model inference service | DeepSeek/OpenAI, or a local OpenAI-compatible server | provider cloud or your LAN |
|
||||
| Phoebus installer/broker | the typed, privileged, local executor | the target machine only |
|
||||
|
||||
**An OpenCode server URL does not go in Phoebus's local-model endpoint field.**
|
||||
An OpenCode server is an agent application; it is not an OpenAI-compatible
|
||||
`/v1/chat/completions` endpoint. Pointing Phoebus's `local` provider at it will
|
||||
fail, and would be the wrong trust boundary even if it parsed.
|
||||
**An OpenCode server URL does not go in the direct-provider endpoint field.**
|
||||
Select the OpenCode backend instead; Phoebus speaks the agent protocol.
|
||||
|
||||
## Capability probe (never assume compatibility)
|
||||
## Configuration
|
||||
|
||||
```sh
|
||||
phoebus-installer --opencode-probe http://127.0.0.1:4096
|
||||
```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.
|
||||
```
|
||||
|
||||
It is read-only and prints a typed state, exiting nonzero unless a model is
|
||||
available:
|
||||
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
|
||||
# Read-only: classify the server. Exits nonzero unless a model catalog exists.
|
||||
phoebus-installer --opencode-probe http://127.0.0.1:4096 \
|
||||
--opencode-provider deepseek --opencode-model deepseek-chat
|
||||
|
||||
# Acceptance: obtain and validate a real model response. Exits nonzero on any
|
||||
# failure. This is the inference check, not a reachability check.
|
||||
phoebus-installer --opencode-test http://127.0.0.1:4096 \
|
||||
--opencode-provider deepseek --opencode-model deepseek-chat \
|
||||
--opencode-password-file /path/to/server.pw
|
||||
|
||||
# Installer guidance through OpenCode (a real proposal is reviewed and applied).
|
||||
phoebus-installer --ai-backend opencode \
|
||||
--opencode-server http://127.0.0.1:4096 \
|
||||
--opencode-provider deepseek --opencode-model deepseek-chat \
|
||||
--install --ai
|
||||
|
||||
# The installed assistant uses the same adapter.
|
||||
sys ask --ai-backend opencode --opencode-server http://127.0.0.1:4096 \
|
||||
--opencode-provider deepseek --opencode-model deepseek-chat \
|
||||
"show the transaction history"
|
||||
```
|
||||
|
||||
`--opencode-password-file` must be mode 0600, like the direct provider key file.
|
||||
|
||||
## Graphical installer
|
||||
|
||||
On the **AI model** step choose **OpenCode agent**, then fill in the server URL,
|
||||
the server password (if the server has one), the provider and the model. Two
|
||||
actions are available:
|
||||
|
||||
- **Test connection** obtains and validates a real model response
|
||||
(`ai_test`); it does not change the installation plan.
|
||||
- **Connect and validate** obtains a real proposal through OpenCode and runs the
|
||||
strict review (`ai_check`). Only then does the wizard allow continuing, and
|
||||
only then does the backend accept the AI prerequisite for installation.
|
||||
|
||||
Changing the server, provider, model or password — or editing the configuration
|
||||
— invalidates the validated state.
|
||||
|
||||
## Connection states
|
||||
|
||||
`phoebus-installer --opencode-probe` prints one of:
|
||||
|
||||
| State | Meaning |
|
||||
|-------|---------|
|
||||
| `disconnected` | TCP connect failed; the service is down |
|
||||
| `authentication_required` | the server answered 401/403; supply the password/tunnel |
|
||||
| `incompatible` | a health response arrived but the API shape is not the expected one |
|
||||
| `reachable_no_model` | healthy server, no model configured |
|
||||
| `ready` | reachable, healthy, API-compatible, and ≥1 model configured |
|
||||
| `insecure_transport` | the destination failed the transport policy |
|
||||
| `unreachable` | the server could not be reached |
|
||||
| `authentication_required` | the server returned 401 and no credential was supplied |
|
||||
| `authentication_rejected` | a credential was supplied and rejected |
|
||||
| `incompatible` | a response arrived but was not the expected API/JSON |
|
||||
| `reachable` | healthy server with no model catalog |
|
||||
| `model_catalog` | healthy server with a model catalog |
|
||||
| `selected_model_unavailable` | the chosen provider/model is not in the catalog |
|
||||
| `ready` | reserved for a real, validated model response (not the probe) |
|
||||
|
||||
`ready` still does **not** prove the model can emit a valid Phoebus proposal;
|
||||
that requires a real prompt round-trip and proposal parse. A health check or an
|
||||
HTTP 200 is not that proof.
|
||||
A model catalog is not readiness. The probe never returns `ready`; only a real
|
||||
inference that validates the response does.
|
||||
|
||||
The probe reads `/global/health` and `/config/providers`, keeps only counts from
|
||||
the latter, and never returns the provider credentials that upstream includes in
|
||||
that response.
|
||||
## Transport policy
|
||||
|
||||
- Plain `http://` is accepted **only** when the resolved destination is
|
||||
loopback. The host is resolved and the connection is pinned to the checked
|
||||
address, so a DNS answer that changes after the check cannot move the target.
|
||||
- Remote access is `https://` (curl verifies the certificate; verification is
|
||||
never disabled) **or** an authenticated encrypted tunnel terminating on
|
||||
loopback (SSH `-L`, WireGuard, ...).
|
||||
- Redirects are disabled, the protocol is restricted to `http,https`, and
|
||||
connect time, total time, header/body sizes and response size are bounded.
|
||||
- A URL with userinfo, a path or a control character is rejected.
|
||||
|
||||
## Security
|
||||
|
||||
- The server the assistant talks to should run unprivileged with a restricted
|
||||
configuration. OpenCode permission settings are not an OS sandbox: run the
|
||||
Phoebus-facing server with a dedicated directory, no plugins, and no
|
||||
developer sessions, and keep the model credentials out of its reach where the
|
||||
deployment allows.
|
||||
- The adapter requests **no tools** per message (`"tools": {...false}`) as
|
||||
defence in depth, but that is not a substitute for process isolation.
|
||||
- Destructive product actions remain in the local typed broker with local human
|
||||
approval. The agent never receives a shell, root, credentials or private-file
|
||||
access, and disk/account passphrases are never sent to it.
|
||||
- The adapter creates a transient session per request, accepts only the
|
||||
completed assistant text parts (never user, tool or reasoning parts) and
|
||||
deletes the session afterwards, so installation facts are not retained.
|
||||
|
||||
## A. OpenCode on the development/VM host
|
||||
|
||||
```sh
|
||||
# 1. Set a provider credential through the environment (never a file in git).
|
||||
export DEEPSEEK_API_KEY="$(cat ~/.config/phoebus/deepseek.key)" # 0600 file
|
||||
|
||||
# 2. Start the server on loopback only. Upstream warns when it is unsecured.
|
||||
opencode serve --hostname 127.0.0.1 --port 4096
|
||||
|
||||
# 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 pass `--mdns` and do not bind `0.0.0.0`
|
||||
without authentication: the server's configuration API can expose provider
|
||||
credentials.
|
||||
|
||||
## B. OpenCode on a separate user-controlled computer
|
||||
|
||||
Run the server on that computer, bound to **loopback**, and reach it through an
|
||||
authenticated encrypted tunnel. SSH port-forwarding is the simplest approved
|
||||
transport:
|
||||
|
||||
```sh
|
||||
# On the remote computer:
|
||||
opencode serve --hostname 127.0.0.1 --port 4096
|
||||
|
||||
# From your machine (tunnel local 127.0.0.1:4096 -> remote loopback:4096):
|
||||
ssh -N -L 127.0.0.1:4096:127.0.0.1:4096 you@remote.example
|
||||
|
||||
# Then, locally:
|
||||
opencode attach http://127.0.0.1:4096
|
||||
opencode attach http://127.0.0.1:4096 # interactive client
|
||||
phoebus-installer --opencode-probe http://127.0.0.1:4096
|
||||
```
|
||||
|
||||
The probe now sees a loopback endpoint and the tunnel supplies transport
|
||||
authentication and encryption. If you cannot use a tunnel, set
|
||||
`OPENCODE_SERVER_PASSWORD` and terminate TLS in front of the server; never
|
||||
expose an unauthenticated plaintext service.
|
||||
Keep the server on `127.0.0.1`; do not enable `--mdns` or bind `0.0.0.0`
|
||||
without authentication.
|
||||
|
||||
## B. OpenCode on a separate user-controlled computer
|
||||
|
||||
Run the server on that computer bound to **loopback** and reach it through an
|
||||
authenticated encrypted tunnel:
|
||||
|
||||
```sh
|
||||
# remote:
|
||||
opencode serve --hostname 127.0.0.1 --port 4096
|
||||
# local:
|
||||
ssh -N -L 127.0.0.1:4096:127.0.0.1:4096 you@remote.example
|
||||
phoebus-installer --opencode-probe http://127.0.0.1:4096
|
||||
```
|
||||
|
||||
If a tunnel is impossible, set `OPENCODE_SERVER_PASSWORD` and terminate TLS in
|
||||
front of the server; never expose an unauthenticated plaintext service.
|
||||
|
||||
### VM networking is not one thing
|
||||
|
||||
Inside a VM these are different endpoints and must not be confused:
|
||||
|
||||
| Endpoint | Meaning |
|
||||
|----------|---------|
|
||||
| `guest 127.0.0.1` | the guest's own loopback |
|
||||
|
|
@ -101,36 +160,28 @@ Inside a VM these are different endpoints and must not be confused:
|
|||
| `10.0.2.2` | the QEMU user-net gateway to the host |
|
||||
| `192.168.x.y` | a real LAN address, reachable by other machines |
|
||||
|
||||
## C. Phoebus assistant boundary
|
||||
A VM guest cannot name the host's loopback directly, and plain `http` to the
|
||||
gateway is refused by policy. The supported pattern is a host-local relay bound
|
||||
to the **guest's** loopback (the same shape as an SSH tunnel); the VM harness
|
||||
uses a tiny TCP forwarder for exactly this.
|
||||
|
||||
When a Phoebus assistant uses OpenCode:
|
||||
## Verified evidence (2026-09-22)
|
||||
|
||||
- Run the service unprivileged, with restricted filesystem access.
|
||||
- Disable tools you do not need. OpenCode permission settings are *not* an
|
||||
operating-system security boundary; enforce isolation outside the prompt.
|
||||
- Keep the destructive execution path in Phoebus's local broker with local human
|
||||
approval. The agent is never given a shell, root, credentials or private-file
|
||||
access.
|
||||
- Keep credentials in protected runtime storage (0600, outside model context).
|
||||
Never forward disk passphrases or account passwords to OpenCode.
|
||||
- Changing the model or connection invalidates any approval whose meaning
|
||||
depends on it; a reconnect must never replay an installation command.
|
||||
|
||||
## Developer workflow note
|
||||
|
||||
For work on this repository, the developer OpenCode session may use full tools,
|
||||
but only against a checkout and against **sanitized** test evidence. Do not feed
|
||||
it VM disks, serial transcripts with credentials, `*.pw` files, or the
|
||||
`PHOEBUS_OPENCODE_*` runtime inputs.
|
||||
|
||||
## Verified evidence
|
||||
|
||||
- `phoebus-installer --opencode-probe http://127.0.0.1:41999` against the
|
||||
installed `opencode 1.18.32` returned `ready` (3 providers, 27 models).
|
||||
- The same probe through a forwarded second loopback endpoint returned `ready`.
|
||||
- A server deliberately bound to a LAN address **without** authentication
|
||||
returned `authentication_required` and exit status 1: the probe refuses to
|
||||
treat an unauthenticated service as usable.
|
||||
- Physical second-computer verification is **BLOCKED** in this environment (no
|
||||
second machine / no passwordless SSH); the forwarded-hop test is labelled as a
|
||||
host-local transport test, not a second computer.
|
||||
- `opencode 1.18.32` (pinned manifest: `v1.18.31`; version mismatch noted).
|
||||
- `--opencode-probe` → `model_catalog`, 223 providers / 7915 models, 26
|
||||
connected; the selected `deepseek:deepseek-v4-flash` present.
|
||||
- `--opencode-test` → `validated model response: {"phoebus":"ok"}` (real
|
||||
inference), exit 0.
|
||||
- The GUI bridge `ai_check` over OpenCode applied 8 reviewed changes from a real
|
||||
`deepseek-v4-flash` proposal.
|
||||
- `sys ask` over OpenCode proposed a read-only `history` action and executed it
|
||||
deterministically.
|
||||
- Authentication: no credential → `authentication_required`; wrong →
|
||||
`authentication_rejected`; correct → `model_catalog` and a successful real
|
||||
inference.
|
||||
- Transport policy: plain `http` to a LAN/global address →
|
||||
`insecure_transport`, exit 1, no request sent.
|
||||
- Real-HTTP integration tests cover status preservation, chunked multibyte
|
||||
bodies, oversized bodies, redirects, abrupt disconnects and authentication.
|
||||
- A separate physical computer remains **unverified**; a second server bound to
|
||||
the LAN address reached through a loopback tunnel is the remote-topology test.
|
||||
|
|
|
|||
|
|
@ -99,7 +99,11 @@ still not VM-verified.
|
|||
| Bridge replay/concurrency + input bounds | yes | yes | no | n/a |
|
||||
| Provider transport endpoint/size hardening | yes | yes | no | n/a |
|
||||
| `TargetRoot` symlink-escape guard | yes | yes | n/a | n/a |
|
||||
| OpenCode server capability probe | yes | yes | real host probe (`ready`) | n/a |
|
||||
| OpenCode server capability probe | yes | yes | real host probe + auth + policy | n/a |
|
||||
| OpenCode proposal adapter (real inference) | yes | yes | real model (`deepseek-v4-flash`) | n/a |
|
||||
| OpenCode in GUI / CLI / `sys ask` | yes | yes | GUI AI step + `sys ask` live | n/a |
|
||||
| OpenCode full graphical install | yes | yes | AI gate passed; install not run | n/a |
|
||||
| Mandatory AI requires a validated interaction | yes | yes | bridge + CLI | n/a |
|
||||
| GURU packaging (scoped keywords) | yes | yes | no (build/install unverified) | no |
|
||||
| Release gates + atomic publish | yes | yes | no | n/a |
|
||||
| `sys` verbs | yes | yes | yes | no |
|
||||
|
|
|
|||
|
|
@ -4,6 +4,57 @@ Companion to `docs/STATUS.md`. The machine-readable per-run results live outside
|
|||
git under `/var/tmp/phoebus-vm/<run-id>/results.json`; this file is the
|
||||
human-readable register of what was found, fixed and still unverified.
|
||||
|
||||
## OpenCode adapter (2026-09-22, second pass)
|
||||
|
||||
Implemented a real OpenCode adapter (not just a probe), integrated through
|
||||
canonical configuration (`ai.backend = "opencode"`), the GUI bridge, the
|
||||
installer CLI and `sys ask`. Defects found while implementing and testing:
|
||||
|
||||
| ID | Defect | Fix | Test |
|
||||
|----|--------|-----|------|
|
||||
| O1 | No OpenCode proposal adapter; the GUI used the OpenAI-compatible transport | `phoebus-executor::opencode_client` implements the real session/message protocol as a `ModelTransport` | live + bridge end-to-end |
|
||||
| O2 | `POST /session` was sent a `model` field per the OpenAPI schema | the shipped 1.18.32 rejects it (BadRequest); the model is selected on the message | real-HTTP integration |
|
||||
| O3 | The probe had no credential input | `ProbeRequest.auth` + basic-auth header via stdin | auth integration test |
|
||||
| O4 | The probe did not enforce the connection destination | `Endpoint::checked_target` resolves and requires loopback for plain http; the connection is pinned | `transport_policy_enforces_loopback_for_plain_http`, insecure-destination test |
|
||||
| O5 | Handwritten HTTP read had no total deadline and a UTF-8-unsafe chunk decoder that fell back on malformed input | removed the handwritten parser; the established curl transport is used and bounds time, protocol, redirects and size | real-HTTP chunked/oversize/redirect/disconnect tests |
|
||||
| O6 | The catalog was parsed without checking the HTTP status; a providers-shaped 500 could look like a catalog | status is checked before parsing; non-2xx is `incompatible` | `a_misleading_success_shaped_500_does_not_produce_a_catalog` |
|
||||
| O7 | Catalog presence counted as readiness | `ready` is reserved for a validated response; the probe returns `model_catalog`/`reachable` | `an_empty_catalog_is_reachable_not_ready` |
|
||||
| O8 | `probe_live_server_when_configured` passed when its env var was absent and only asserted reachability | replaced by env-gated `opencode_live` tests that assert a real inference; `PHOEBUS_OPENCODE_REQUIRE_LIVE=1` fails when the live run cannot happen | `make opencode-acceptance` |
|
||||
| O9 | The credential test built an already-sanitised struct | tests feed credential-bearing server bodies and assert errors/catalogs never contain them | `one_shot_rejects_a_non_assistant_or_errored_reply`, `catalog_never_reads_provider_keys` |
|
||||
| O10 | A provider name satisfied the mandatory-AI gate | both the bridge and the CLI require a validated interaction bound to the current configuration; config/secret changes invalidate it | `a_provider_name_alone_does_not_satisfy_the_ai_requirement`, `an_unreachable_provider_does_not_satisfy_the_ai_gate` |
|
||||
| O11 | The proposal prompt allowed the model to key the change by action name | prompt now requires exactly `action` + `value` with explicit examples | live bridge `ai_check` |
|
||||
| O12 | The GUI duplicate-session assertion accepted two pre-existing sessions | requires exactly one session before and after | harness |
|
||||
| O13 | GUI navigation was inferred from a surviving process/screenshot | the frontend emits secret-free `phoebus-state` lines; the harness asserts the current step and AI state | harness |
|
||||
| O14 | A model could return a malformed proposal with no second chance | one bounded corrective retry in `complete_proposal_at`/`complete_plan`, with the strict parser still final | `a_rejected_proposal_is_retried_once_with_a_correction`, `a_retry_that_still_fails_is_still_rejected` |
|
||||
|
||||
### Graphical OpenCode acceptance (VM verified)
|
||||
|
||||
`gui-driver.py opencode` on the built ISO (real model, no simulation):
|
||||
|
||||
- welcome → installer → AI step; selected **OpenCode agent** through the UI;
|
||||
- typed the server URL, provider and model through the UI;
|
||||
- **Test connection** obtained a real model response (green "Model responded");
|
||||
- **Connect and validate** obtained and validated a proposal (green "Validated",
|
||||
frontend state `aiConnected=true`);
|
||||
- run `gui-opencode-20260922T102640Z-be168813`: **17/17 PASS**, exit 0; the full
|
||||
GUI regression `gui-gui-20260922T102907Z-a9e5e824` was **25/25 PASS**.
|
||||
- The model is reached through a guest-loopback relay to the host OpenCode
|
||||
server (the SSH-tunnel shape), so the transport policy is satisfied.
|
||||
- Authenticated server: the same harness with a password-protected server got
|
||||
through authentication and a real Test connection; a flaky malformed proposal
|
||||
was correctly rejected. Use `deepseek-flash` (reliable) over
|
||||
`deepseek-v4-flash` (occasionally malformed).
|
||||
|
||||
Still **NOT RUN**: the full graphical installation (disk → account → review →
|
||||
ERASE → install → detached boot) *through OpenCode*. The AI gate is now reached
|
||||
and passed in the graphical VM; the remaining stages are the long package
|
||||
installation. Two fresh-disk graphical installs and a separate physical machine
|
||||
remain unverified.
|
||||
|
||||
OpenCode protocol/transport tests: 26 executor unit tests + 7 real-HTTP
|
||||
integration tests + 2 live tests (skipped offline, real inference when
|
||||
configured). Bridge gate tests: 5. Full suite: 336 Rust tests.
|
||||
|
||||
## Run matrix (this session, 2026-09-22)
|
||||
|
||||
```json
|
||||
|
|
|
|||
|
|
@ -44,10 +44,35 @@ Two facts shape the decision:
|
|||
product actions still go through the local typed broker and local human
|
||||
approval. The OpenCode configuration is written mode 0600 and carries no
|
||||
credentials.
|
||||
5. **The installer's AI step keeps using its own bounded transport.** OpenCode
|
||||
is an optional operator workflow, not a replacement for the typed proposal
|
||||
transport; a future adapter must perform a real prompt round-trip and parse a
|
||||
versioned proposal before it may claim compatibility.
|
||||
5. **The installer's AI step uses a real OpenCode adapter** (implemented after
|
||||
this ADR was first written). `phoebus-executor::opencode_client` speaks the
|
||||
OpenCode session/message API over the project's curl transport and implements
|
||||
the same `ModelTransport` trait as the direct providers, so the strict
|
||||
proposal parser, evidence review, facts and executor are reused unchanged.
|
||||
The adapter creates a transient session per request, accepts only the
|
||||
completed assistant `TextPart`s (never user/tool/reasoning parts), disables
|
||||
tools per message, and deletes the session on every path. The GUI, the
|
||||
installer CLI and `sys ask` all select it through canonical configuration
|
||||
(`ai.backend = "opencode"`).
|
||||
6. **A provider name is not a validated interaction.** Both the GUI bridge and
|
||||
the installer CLI require a successful, validated model interaction bound to
|
||||
the current configuration (and credential) before installation; changing the
|
||||
model, endpoint, server or credential invalidates it. `Ready` is reserved for
|
||||
a real, validated response.
|
||||
|
||||
### Protocol notes (verified against the shipped `opencode 1.18.32`)
|
||||
|
||||
- Health: `GET /global/health`. Catalog: `GET /provider` (metadata; upstream may
|
||||
include a credential `key`, so only ids and model names are kept).
|
||||
- `POST /session` rejects a `model` field (BadRequest) despite the OpenAPI
|
||||
schema; the model is selected on the message.
|
||||
- `POST /session/{id}/message` returns the assistant reply synchronously;
|
||||
`format: json_schema` is rejected by the DeepSeek models in use ("Thinking
|
||||
mode does not support this tool_choice"), so the prompt carries an explicit
|
||||
change-object shape instead.
|
||||
- `POST /session/{id}/abort` and `DELETE /session/{id}` clean up.
|
||||
- Authentication is HTTP Basic with username `opencode` and the
|
||||
`OPENCODE_SERVER_PASSWORD` value; Bearer is not accepted.
|
||||
|
||||
## Consequences
|
||||
|
||||
|
|
@ -62,5 +87,9 @@ Two facts shape the decision:
|
|||
|
||||
## Status
|
||||
|
||||
Accepted. The probe and its tests are implemented; end-to-end installation does
|
||||
not depend on OpenCode.
|
||||
Accepted and implemented. The probe, the adapter and the connection states are
|
||||
implemented with unit, real-HTTP integration, live-model and bridge tests; the
|
||||
graphical installer can select OpenCode and obtain a real validated proposal.
|
||||
End-to-end installation still does not *depend* on OpenCode: a direct provider
|
||||
or the deterministic `sys` path remains available, and an installed system works
|
||||
without a model.
|
||||
|
|
|
|||
|
|
@ -145,7 +145,27 @@ pub fn build_request(
|
|||
}
|
||||
}
|
||||
|
||||
/// Ask the provider for a plan and parse it, fail-closed at every step.
|
||||
/// The request with a corrective turn appended after a rejected plan.
|
||||
pub fn build_corrected_request(
|
||||
provider: ProviderKind,
|
||||
model: &str,
|
||||
facts: &SystemFacts,
|
||||
instruction: &str,
|
||||
correction: &str,
|
||||
) -> ChatRequest {
|
||||
let mut request = build_request(provider, model, facts, instruction);
|
||||
request.messages.push(ChatMessage {
|
||||
role: "user".into(),
|
||||
content: format!(
|
||||
"Your previous reply was rejected: {correction}. Reply with ONLY the \
|
||||
corrected JSON object, with no prose and no code fence."
|
||||
),
|
||||
});
|
||||
request
|
||||
}
|
||||
|
||||
/// Ask the provider for a plan and parse it, fail-closed at every step. A
|
||||
/// rejected reply is retried once with a corrective turn.
|
||||
pub fn complete_plan(
|
||||
provider: ProviderKind,
|
||||
endpoint: &str,
|
||||
|
|
@ -165,11 +185,27 @@ pub fn complete_plan(
|
|||
));
|
||||
}
|
||||
facts.validate_no_forbidden()?;
|
||||
let request = build_request(provider, model, facts, instruction);
|
||||
let body = serde_json::to_string(&request)?;
|
||||
|
||||
let attempt = |request: &ChatRequest| -> Result<AssistantPlan, AiError> {
|
||||
let body = serde_json::to_string(request)?;
|
||||
let response = transport.send(provider, endpoint, &body)?;
|
||||
let content = crate::provider::extract_content(&response)?;
|
||||
parse_plan(&content)
|
||||
};
|
||||
|
||||
match attempt(&build_request(provider, model, facts, instruction)) {
|
||||
Ok(plan) => Ok(plan),
|
||||
Err(first) => {
|
||||
let correction = first.to_string();
|
||||
attempt(&build_corrected_request(
|
||||
provider,
|
||||
model,
|
||||
facts,
|
||||
instruction,
|
||||
&correction,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -279,6 +315,30 @@ mod tests {
|
|||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_plan_is_retried_once_with_a_correction() {
|
||||
use crate::provider::{chat_response, ScriptedTransport};
|
||||
let bad =
|
||||
chat_response(r#"{"version":1,"summary":"x","actions":[{"action":"run_shell"}]}"#);
|
||||
let good = chat_response(
|
||||
r#"{"version":1,"summary":"look","actions":[{"action":"history"}],"rationale":[{"action":"history","reason":"asked"}]}"#,
|
||||
);
|
||||
let transport = ScriptedTransport::new(vec![bad, good]);
|
||||
let plan = complete_plan(
|
||||
ProviderKind::Local,
|
||||
"http://127.0.0.1:11434/v1/chat/completions",
|
||||
"m",
|
||||
&facts(),
|
||||
"what changed?",
|
||||
&transport,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plan.actions.len(), 1);
|
||||
let requests = transport.requests();
|
||||
assert_eq!(requests.len(), 2);
|
||||
assert!(requests[1].contains("rejected"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn action_tag_matches_the_schema() {
|
||||
assert_eq!(action_tag(&SystemAction::History), "history");
|
||||
|
|
|
|||
|
|
@ -231,7 +231,14 @@ set_binary_packages (bool), set_build_jobs (1-256), set_package_use (atom, flag,
|
|||
enabled).
|
||||
|
||||
Reply with ONLY a JSON object of the form:
|
||||
{\"version\":1,\"changes\":[{\"action\":\"...\",...}],\"rationale\":[{\"action\":\"...\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
|
||||
{\"version\":1,\"changes\":[{\"action\":\"<action>\",\"value\":<value>}],\"rationale\":[{\"action\":\"<action>\",\"reason\":\"...\",\"evidence\":[\"...\"]}]}
|
||||
|
||||
Every change object has EXACTLY the two keys `action` and `value`. Put the chosen
|
||||
option in `value`; never use the action name as a key. Correct examples:
|
||||
{\"action\":\"set_kernel_profile\",\"value\":\"safe\"}
|
||||
{\"action\":\"set_filesystem\",\"value\":\"btrfs\"}
|
||||
{\"action\":\"set_flatpak\",\"value\":true}
|
||||
{\"action\":\"set_build_jobs\",\"value\":4}
|
||||
|
||||
Rules: prefer stability and a proven boot over speculative performance; never
|
||||
propose disabling signature verification, enabling ~amd64 globally, weakening
|
||||
|
|
@ -368,6 +375,42 @@ impl ModelTransport for TestTransport {
|
|||
}
|
||||
}
|
||||
|
||||
/// A transport that returns a scripted sequence of responses, one per call
|
||||
/// (tests of retry and multi-turn behaviour).
|
||||
pub struct ScriptedTransport {
|
||||
responses: std::sync::Mutex<std::collections::VecDeque<String>>,
|
||||
requests: std::sync::Mutex<Vec<String>>,
|
||||
}
|
||||
|
||||
impl ScriptedTransport {
|
||||
pub fn new(responses: Vec<String>) -> Self {
|
||||
Self {
|
||||
responses: std::sync::Mutex::new(responses.into()),
|
||||
requests: std::sync::Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn requests(&self) -> Vec<String> {
|
||||
self.requests.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl ModelTransport for ScriptedTransport {
|
||||
fn send(&self, _provider: ProviderKind, _url: &str, body: &str) -> Result<String, AiError> {
|
||||
self.requests.lock().unwrap().push(body.to_string());
|
||||
self.responses
|
||||
.lock()
|
||||
.unwrap()
|
||||
.pop_front()
|
||||
.ok_or_else(|| AiError::Provider("no scripted response left".into()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap a bare proposal in an OpenAI-style chat response (test helper).
|
||||
pub fn chat_response(content: &str) -> String {
|
||||
serde_json::json!({ "choices": [{ "message": { "content": content } }] }).to_string()
|
||||
}
|
||||
|
||||
/// Ask a provider for a proposal and parse it, fail-closed at every step.
|
||||
pub fn complete_proposal(
|
||||
provider: ProviderKind,
|
||||
|
|
@ -378,8 +421,30 @@ pub fn complete_proposal(
|
|||
complete_proposal_at(provider, provider.endpoint(), model, facts, transport)
|
||||
}
|
||||
|
||||
/// Build the request again, appending a corrective turn after a rejected reply.
|
||||
/// Models occasionally key a change by the action name or add prose; one
|
||||
/// bounded corrective round-trip meaningfully improves reliability without
|
||||
/// weakening the parser.
|
||||
pub fn build_corrected_request(
|
||||
provider: ProviderKind,
|
||||
model: &str,
|
||||
facts: &SystemFacts,
|
||||
correction: &str,
|
||||
) -> ChatRequest {
|
||||
let mut request = build_request(provider, model, facts);
|
||||
request.messages.push(ChatMessage {
|
||||
role: "user".into(),
|
||||
content: format!(
|
||||
"Your previous reply was rejected: {correction}. Reply with ONLY the \
|
||||
corrected JSON object, with no prose and no code fence."
|
||||
),
|
||||
});
|
||||
request
|
||||
}
|
||||
|
||||
/// As `complete_proposal`, but with an explicit endpoint (`--ai-endpoint`), for
|
||||
/// a self-hosted model on a non-default port.
|
||||
/// a self-hosted model on a non-default port. A rejected reply is retried once
|
||||
/// with a corrective turn; the strict parser is still the final authority.
|
||||
pub fn complete_proposal_at(
|
||||
provider: ProviderKind,
|
||||
endpoint: &str,
|
||||
|
|
@ -394,11 +459,26 @@ pub fn complete_proposal_at(
|
|||
}
|
||||
validate_endpoint(endpoint)?;
|
||||
facts.validate_no_forbidden()?;
|
||||
let request = build_request(provider, model, facts);
|
||||
let body = serde_json::to_string(&request)?;
|
||||
|
||||
let attempt = |request: &ChatRequest| -> Result<AiProposal, AiError> {
|
||||
let body = serde_json::to_string(request)?;
|
||||
let response = transport.send(provider, endpoint, &body)?;
|
||||
let content = extract_content(&response)?;
|
||||
parse_proposal(&content)
|
||||
};
|
||||
|
||||
match attempt(&build_request(provider, model, facts)) {
|
||||
Ok(proposal) => Ok(proposal),
|
||||
Err(first) => {
|
||||
let correction = first.to_string();
|
||||
attempt(&build_corrected_request(
|
||||
provider,
|
||||
model,
|
||||
facts,
|
||||
&correction,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -562,6 +642,49 @@ mod tests {
|
|||
assert_eq!(parsed.changes.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_proposal_is_retried_once_with_a_correction() {
|
||||
// First response uses the wrong key (the failure seen with a real
|
||||
// model); the second is corrected.
|
||||
let bad = chat_response(
|
||||
r#"{"version":1,"changes":[{"action":"set_kernel_profile","profile":"safe"}],"rationale":[]}"#,
|
||||
);
|
||||
let good = chat_response(
|
||||
r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"x"}]}"#,
|
||||
);
|
||||
let transport = ScriptedTransport::new(vec![bad, good]);
|
||||
let proposal = complete_proposal_at(
|
||||
ProviderKind::Local,
|
||||
"http://127.0.0.1:8080/v1/chat/completions",
|
||||
"m",
|
||||
&facts(),
|
||||
&transport,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(proposal.changes.len(), 1);
|
||||
let requests = transport.requests();
|
||||
assert_eq!(requests.len(), 2, "exactly one corrective retry");
|
||||
assert!(
|
||||
requests[1].contains("rejected"),
|
||||
"the retry carries the reason"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retry_that_still_fails_is_still_rejected() {
|
||||
let bad = chat_response(r#"{"version":1,"changes":[{"action":"nope"}]}"#);
|
||||
let transport = ScriptedTransport::new(vec![bad.clone(), bad]);
|
||||
assert!(complete_proposal_at(
|
||||
ProviderKind::Local,
|
||||
"http://127.0.0.1:8080/v1/chat/completions",
|
||||
"m",
|
||||
&facts(),
|
||||
&transport
|
||||
)
|
||||
.is_err());
|
||||
assert_eq!(transport.requests().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unavailable_provider_is_explicit() {
|
||||
let transport = TestTransport::new("{}");
|
||||
|
|
|
|||
|
|
@ -361,6 +361,35 @@ impl Default for DesktopConfig {
|
|||
}
|
||||
}
|
||||
|
||||
/// How the assistant reaches a model. `Direct` is an OpenAI-compatible
|
||||
/// endpoint; `OpenCode` is an OpenCode **agent server** (a different protocol
|
||||
/// and trust boundary), never an OpenAI-compatible model endpoint.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub enum AiBackend {
|
||||
#[default]
|
||||
#[serde(rename = "direct")]
|
||||
Direct,
|
||||
#[serde(rename = "opencode")]
|
||||
OpenCode,
|
||||
}
|
||||
|
||||
impl AiBackend {
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
AiBackend::Direct => "direct",
|
||||
AiBackend::OpenCode => "opencode",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse(value: &str) -> Option<Self> {
|
||||
match value.trim().to_ascii_lowercase().as_str() {
|
||||
"" | "direct" | "provider" => Some(AiBackend::Direct),
|
||||
"opencode" | "open-code" | "open_code" => Some(AiBackend::OpenCode),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
#[serde(default)]
|
||||
pub struct AiConfig {
|
||||
|
|
@ -368,6 +397,30 @@ pub struct AiConfig {
|
|||
pub provider: String,
|
||||
pub model: String,
|
||||
pub endpoint: String,
|
||||
/// Direct provider endpoint or the OpenCode agent server.
|
||||
pub backend: AiBackend,
|
||||
/// OpenCode server base URL, e.g. `http://127.0.0.1:4096`.
|
||||
pub opencode_server: String,
|
||||
/// OpenCode provider id (e.g. `deepseek`).
|
||||
pub opencode_provider: String,
|
||||
/// OpenCode model id (e.g. `deepseek-chat`).
|
||||
pub opencode_model: String,
|
||||
}
|
||||
|
||||
impl AiConfig {
|
||||
pub fn is_opencode(&self) -> bool {
|
||||
self.backend == AiBackend::OpenCode
|
||||
}
|
||||
|
||||
/// The OpenCode endpoint, if this configuration uses one.
|
||||
pub fn opencode_endpoint(&self) -> Option<&str> {
|
||||
let server = self.opencode_server.trim();
|
||||
if server.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(server)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
|
|
|
|||
|
|
@ -24,9 +24,9 @@ pub mod update;
|
|||
pub mod validate;
|
||||
|
||||
pub use config::{
|
||||
Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig, Filesystem,
|
||||
InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig, Stage3Config,
|
||||
StorageConfig, SystemConfig, UserConfig,
|
||||
AiBackend, AiConfig, Bootloader, DesktopConfig, DesktopProfile, Encryption, EncryptionConfig,
|
||||
Filesystem, InstallConfig, KernelConfig, KernelProfile, PackagePolicy, PackagesConfig,
|
||||
Stage3Config, StorageConfig, SystemConfig, UserConfig,
|
||||
};
|
||||
pub use disk::{Disk, DiskKind, ProtectionReason};
|
||||
pub use error::{CoreError, Result};
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ pub mod kernel;
|
|||
pub mod log;
|
||||
pub mod nix;
|
||||
pub mod opencode;
|
||||
pub mod opencode_client;
|
||||
pub mod opencode_server;
|
||||
pub mod portage;
|
||||
pub mod probe;
|
||||
|
|
|
|||
1041
installer-rs/crates/phoebus-executor/src/opencode_client.rs
Normal file
1041
installer-rs/crates/phoebus-executor/src/opencode_client.rs
Normal file
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
386
installer-rs/crates/phoebus-executor/tests/opencode_http.rs
Normal file
386
installer-rs/crates/phoebus-executor/tests/opencode_http.rs
Normal file
|
|
@ -0,0 +1,386 @@
|
|||
//! 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"
|
||||
);
|
||||
}
|
||||
140
installer-rs/crates/phoebus-executor/tests/opencode_live.rs
Normal file
140
installer-rs/crates/phoebus-executor/tests/opencode_live.rs
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
//! 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,10 +11,11 @@ use std::process::ExitCode;
|
|||
|
||||
use clap::Parser;
|
||||
use phoebus_ai::assistant::{complete_plan, AssistantPlan};
|
||||
use phoebus_ai::provider::{ProviderKind, SystemFacts};
|
||||
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
||||
use phoebus_core::action::{parse_action, parse_natural, SystemAction};
|
||||
use phoebus_core::transaction::TransactionRecord;
|
||||
use phoebus_core::{InstallConfig, Redactor};
|
||||
use phoebus_core::{AiBackend, InstallConfig, Redactor};
|
||||
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
||||
use phoebus_executor::{
|
||||
actions, authorize, probe, transaction, AutoConfirm, Confirmation, DestructiveAuthorization,
|
||||
Exec, Logger, RealRunner, Result,
|
||||
|
|
@ -61,6 +62,26 @@ struct Cli {
|
|||
/// Run the assistant without the OS-level sandbox (development only).
|
||||
#[arg(long)]
|
||||
no_sandbox: bool,
|
||||
|
||||
/// AI backend for `sys ask`: `direct` (default) or `opencode`.
|
||||
#[arg(long, value_name = "BACKEND")]
|
||||
ai_backend: Option<String>,
|
||||
|
||||
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
|
||||
#[arg(long, value_name = "URL")]
|
||||
opencode_server: Option<String>,
|
||||
|
||||
/// OpenCode provider id (e.g. `deepseek`).
|
||||
#[arg(long, value_name = "PROVIDER")]
|
||||
opencode_provider: Option<String>,
|
||||
|
||||
/// OpenCode model id (e.g. `deepseek-chat`).
|
||||
#[arg(long, value_name = "MODEL")]
|
||||
opencode_model: Option<String>,
|
||||
|
||||
/// Read the OpenCode server password from a mode-0600 file.
|
||||
#[arg(long, value_name = "FILE")]
|
||||
opencode_password_file: Option<PathBuf>,
|
||||
}
|
||||
|
||||
struct SysConfirm {
|
||||
|
|
@ -214,6 +235,16 @@ fn gather_facts(exec: &Exec) -> SystemFacts {
|
|||
SystemFacts::from_system(&config, &hardware, &history, binhost, None)
|
||||
}
|
||||
|
||||
/// The AI backend selected on the command line or the environment.
|
||||
fn resolve_backend(cli: &Cli) -> AiBackend {
|
||||
let raw = cli
|
||||
.ai_backend
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_AI_BACKEND").ok())
|
||||
.unwrap_or_default();
|
||||
AiBackend::parse(&raw).unwrap_or(AiBackend::Direct)
|
||||
}
|
||||
|
||||
/// The provider selected on the command line or the environment.
|
||||
fn resolve_provider(cli: &Cli) -> ProviderKind {
|
||||
let raw = cli
|
||||
|
|
@ -270,41 +301,105 @@ fn run_ask(
|
|||
exec: &Exec,
|
||||
instruction: &str,
|
||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let provider = resolve_provider(cli);
|
||||
if provider == ProviderKind::None {
|
||||
let facts = gather_facts(exec);
|
||||
let backend = resolve_backend(cli);
|
||||
let (provider, endpoint, model);
|
||||
let transport: Box<dyn ModelTransport + '_>;
|
||||
|
||||
match backend {
|
||||
AiBackend::OpenCode => {
|
||||
let server = cli
|
||||
.opencode_server
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
|
||||
.unwrap_or_default();
|
||||
let opencode_provider = cli
|
||||
.opencode_provider
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
|
||||
.unwrap_or_default();
|
||||
let opencode_model = cli
|
||||
.opencode_model
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
|
||||
.unwrap_or_default();
|
||||
if server.trim().is_empty()
|
||||
|| opencode_provider.trim().is_empty()
|
||||
|| opencode_model.trim().is_empty()
|
||||
{
|
||||
deterministic_fallback(instruction);
|
||||
return Err(
|
||||
"OpenCode requires --opencode-server, --opencode-provider and --opencode-model"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
let password = match &cli.opencode_password_file {
|
||||
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
|
||||
None => None,
|
||||
};
|
||||
eprintln!(
|
||||
"Sending these bounded system facts through the OpenCode server at {} \
|
||||
(provider {}, model {}); no passwords, files or home directories:",
|
||||
server, opencode_provider, opencode_model
|
||||
);
|
||||
eprintln!("{}", facts.render());
|
||||
provider = ProviderKind::Local;
|
||||
endpoint = server;
|
||||
model = opencode_model;
|
||||
transport = Box::new(
|
||||
ExecOpenCodeTransport::new(
|
||||
exec,
|
||||
endpoint.clone(),
|
||||
opencode_provider,
|
||||
model.clone(),
|
||||
)
|
||||
.with_auth(password),
|
||||
);
|
||||
}
|
||||
AiBackend::Direct => {
|
||||
let resolved = resolve_provider(cli);
|
||||
if resolved == ProviderKind::None {
|
||||
deterministic_fallback(instruction);
|
||||
return Err("no AI provider configured".into());
|
||||
}
|
||||
let endpoint = resolve_endpoint(cli, provider);
|
||||
let model = resolve_model(cli);
|
||||
let key = match api_key_file(cli) {
|
||||
Some(path) => Some(phoebus_executor::ai::load_api_key(&path)?),
|
||||
None => None,
|
||||
};
|
||||
if provider.requires_key() && key.is_none() {
|
||||
if resolved.requires_key() && key.is_none() {
|
||||
deterministic_fallback(instruction);
|
||||
return Err(format!(
|
||||
"provider `{}` requires --ai-api-key-file (mode 0600)",
|
||||
provider.as_str()
|
||||
resolved.as_str()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
let facts = gather_facts(exec);
|
||||
eprintln!(
|
||||
"Sending these bounded system facts to {} (no passwords, files or home directories):",
|
||||
provider.as_str()
|
||||
"Sending these bounded system facts to {} \
|
||||
(no passwords, files or home directories):",
|
||||
resolved.as_str()
|
||||
);
|
||||
eprintln!("{}", facts.render());
|
||||
|
||||
let transport = phoebus_executor::ai::CurlTransport::new(exec, key);
|
||||
let transport = if cli.no_sandbox {
|
||||
transport
|
||||
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 {
|
||||
transport.sandboxed()
|
||||
Box::new(direct.sandboxed())
|
||||
};
|
||||
let plan: AssistantPlan =
|
||||
match complete_plan(provider, &endpoint, &model, &facts, instruction, &transport) {
|
||||
}
|
||||
}
|
||||
|
||||
let plan: AssistantPlan = match complete_plan(
|
||||
provider,
|
||||
&endpoint,
|
||||
&model,
|
||||
&facts,
|
||||
instruction,
|
||||
transport.as_ref(),
|
||||
) {
|
||||
Ok(plan) => plan,
|
||||
Err(e) => {
|
||||
eprintln!("The model is unavailable or returned an unusable plan: {e}");
|
||||
|
|
|
|||
|
|
@ -18,9 +18,10 @@ use std::io::{self, BufRead, Write};
|
|||
|
||||
use crate::{ai_guide, InstallObserver, Installer};
|
||||
use phoebus_ai::provider::{ModelTransport, ProviderKind, SystemFacts};
|
||||
use phoebus_core::{InstallConfig, InstallStep, SecretString};
|
||||
use phoebus_core::{AiBackend, InstallConfig, InstallStep, SecretString};
|
||||
use phoebus_executor::ai::CurlTransport;
|
||||
use phoebus_executor::auth::{authorize, Confirmation};
|
||||
use phoebus_executor::opencode_client::ExecOpenCodeTransport;
|
||||
use phoebus_executor::{Exec, Result as ExecResult};
|
||||
|
||||
use serde::Deserialize;
|
||||
|
|
@ -70,6 +71,10 @@ struct SecretsPatch {
|
|||
root_password: Option<String>,
|
||||
#[serde(default)]
|
||||
ai_api_key: Option<String>,
|
||||
/// The OpenCode server password (basic auth). Distinct from a model
|
||||
/// provider API key and never stored in the configuration.
|
||||
#[serde(default)]
|
||||
opencode_password: Option<String>,
|
||||
}
|
||||
|
||||
/// A `Confirmation` whose answers come from an explicit GUI request. The ERASE
|
||||
|
|
@ -164,7 +169,12 @@ pub struct Bridge {
|
|||
user_password: Option<SecretString>,
|
||||
root_password: Option<SecretString>,
|
||||
api_key: Option<SecretString>,
|
||||
opencode_password: Option<SecretString>,
|
||||
approved_digest: Option<String>,
|
||||
/// Set only after a real, validated AI interaction (a proposal reviewed for
|
||||
/// the direct path, or a validated model response for OpenCode). A mere
|
||||
/// provider name never satisfies the mandatory-AI gate.
|
||||
validated_ai: Option<String>,
|
||||
phase: std::rc::Rc<std::cell::Cell<DiskPhase>>,
|
||||
/// One destructive transaction at a time. An approval is single-use: it is
|
||||
/// consumed when the install starts so a replay, a second frontend or a
|
||||
|
|
@ -183,7 +193,9 @@ impl Bridge {
|
|||
user_password: None,
|
||||
root_password: None,
|
||||
api_key: None,
|
||||
opencode_password: None,
|
||||
approved_digest: None,
|
||||
validated_ai: None,
|
||||
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
||||
installing: false,
|
||||
installed: false,
|
||||
|
|
@ -199,7 +211,9 @@ impl Bridge {
|
|||
user_password: None,
|
||||
root_password: None,
|
||||
api_key: None,
|
||||
opencode_password: None,
|
||||
approved_digest: None,
|
||||
validated_ai: None,
|
||||
phase: std::rc::Rc::new(std::cell::Cell::new(DiskPhase::BeforeStorage)),
|
||||
installing: false,
|
||||
installed: false,
|
||||
|
|
@ -251,6 +265,7 @@ impl Bridge {
|
|||
"plan" => self.plan(),
|
||||
"destructive_preview" => self.destructive_preview(),
|
||||
"ai_check" => self.ai_check(),
|
||||
"ai_test" => self.ai_test(),
|
||||
"approve" => self.approve(&request),
|
||||
"start_install" => return self.start_install(id, &request, out),
|
||||
"log_tail" => self.log_tail(&request),
|
||||
|
|
@ -405,6 +420,9 @@ impl Bridge {
|
|||
|
||||
self.installer.reconfigure(config);
|
||||
self.approved_digest = None;
|
||||
// A configuration change (provider, model, endpoint, server) invalidates
|
||||
// any previous AI validation.
|
||||
self.validated_ai = None;
|
||||
let issues = self.installer.validate();
|
||||
Ok(json!({
|
||||
"accepted": true,
|
||||
|
|
@ -427,6 +445,7 @@ impl Bridge {
|
|||
&patch.user_password,
|
||||
&patch.root_password,
|
||||
&patch.ai_api_key,
|
||||
&patch.opencode_password,
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
|
|
@ -455,12 +474,20 @@ impl Bridge {
|
|||
self.installer.exec.register_secret(&s);
|
||||
self.api_key = Some(s);
|
||||
}
|
||||
if let Some(v) = &patch.opencode_password {
|
||||
let s = SecretString::new(v.clone());
|
||||
self.installer.exec.register_secret(&s);
|
||||
self.opencode_password = Some(s);
|
||||
}
|
||||
// A credential change invalidates any previous AI validation.
|
||||
self.validated_ai = None;
|
||||
// Report only presence, never values.
|
||||
Ok(json!({
|
||||
"luks_set": self.luks.is_some(),
|
||||
"user_password_set": self.user_password.is_some(),
|
||||
"root_password_set": self.root_password.is_some(),
|
||||
"ai_api_key_set": self.api_key.is_some(),
|
||||
"opencode_password_set": self.opencode_password.is_some(),
|
||||
}))
|
||||
}
|
||||
|
||||
|
|
@ -468,33 +495,107 @@ impl Bridge {
|
|||
|
||||
fn ai_check(&mut self) -> Result<Value, String> {
|
||||
let facts = self.installer.system_facts();
|
||||
let api_key_present = self.api_key.is_some();
|
||||
let Bridge {
|
||||
installer,
|
||||
api_key,
|
||||
approved_digest,
|
||||
..
|
||||
} = self;
|
||||
let Installer { exec, config, .. } = installer;
|
||||
let backend = self.installer.config.ai.backend;
|
||||
let api_key = self.api_key.clone();
|
||||
let opencode_password = self.opencode_password.clone();
|
||||
let value = {
|
||||
let Installer { exec, config, .. } = &mut self.installer;
|
||||
let redactor = exec.redactor();
|
||||
match backend {
|
||||
AiBackend::OpenCode => {
|
||||
let transport = opencode_transport(exec, config, opencode_password)?;
|
||||
review_opencode(config, redactor, facts, &transport)?
|
||||
}
|
||||
AiBackend::Direct => {
|
||||
let transport = CurlTransport::new(exec, api_key.clone());
|
||||
let value = review_proposal(config, exec.redactor(), facts, api_key_present, &transport)?;
|
||||
*approved_digest = None;
|
||||
review_proposal(config, redactor, facts, api_key.is_some(), &transport)?
|
||||
}
|
||||
}
|
||||
};
|
||||
self.approved_digest = None;
|
||||
// Bind the validated interaction to the exact configuration it was
|
||||
// validated against; any later change clears it.
|
||||
self.validated_ai = Some(self.plan_digest());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// A real, minimal model interaction that obtains and validates a JSON model
|
||||
/// response without changing the configuration. This is "Test connection".
|
||||
fn ai_test(&mut self) -> Result<Value, String> {
|
||||
use phoebus_ai::provider::{build_request, extract_content};
|
||||
let backend = self.installer.config.ai.backend;
|
||||
let facts = self.installer.system_facts();
|
||||
let redactor = self.installer.exec.redactor();
|
||||
let (kind, endpoint, model, label) = match backend {
|
||||
AiBackend::OpenCode => {
|
||||
let (server, provider, model) = opencode_parts(&self.installer.config)?;
|
||||
(ProviderKind::Local, server, model, provider)
|
||||
}
|
||||
AiBackend::Direct => {
|
||||
let raw = self.installer.config.ai.provider.clone();
|
||||
let provider = ProviderKind::parse(&raw)
|
||||
.ok_or_else(|| format!("unknown AI provider `{raw}`"))?;
|
||||
if provider == ProviderKind::None {
|
||||
return Err("no AI provider selected".into());
|
||||
}
|
||||
let endpoint = if self.installer.config.ai.endpoint.is_empty() {
|
||||
provider.endpoint().to_string()
|
||||
} else {
|
||||
self.installer.config.ai.endpoint.clone()
|
||||
};
|
||||
let model = if self.installer.config.ai.model.is_empty() {
|
||||
provider.default_model().to_string()
|
||||
} else {
|
||||
self.installer.config.ai.model.clone()
|
||||
};
|
||||
(provider, endpoint, model, provider.as_str().to_string())
|
||||
}
|
||||
};
|
||||
let request = build_request(kind, &model, &facts);
|
||||
let body = serde_json::to_string(&request)
|
||||
.map_err(|e| format!("could not build the test request: {e}"))?;
|
||||
let response = match backend {
|
||||
AiBackend::OpenCode => {
|
||||
let (server, provider, model) = opencode_parts(&self.installer.config)?;
|
||||
let transport =
|
||||
ExecOpenCodeTransport::new(&self.installer.exec, server, provider, model)
|
||||
.with_auth(self.opencode_password.clone());
|
||||
transport.send(kind, &endpoint, &body)
|
||||
}
|
||||
AiBackend::Direct => {
|
||||
let transport = CurlTransport::new(&self.installer.exec, self.api_key.clone());
|
||||
transport.send(kind, &endpoint, &body)
|
||||
}
|
||||
}
|
||||
.map_err(|e| format!("connection failed: {}", redactor.redact(&e.to_string())))?;
|
||||
let content = extract_content(&response).map_err(|e| {
|
||||
format!(
|
||||
"model response was not usable: {}",
|
||||
redactor.redact(&e.to_string())
|
||||
)
|
||||
})?;
|
||||
serde_json::from_str::<serde_json::Value>(&content)
|
||||
.map_err(|_| "model response was not JSON".to_string())?;
|
||||
Ok(json!({
|
||||
"connected": true,
|
||||
"backend": backend.as_str(),
|
||||
"provider": label,
|
||||
"model": model,
|
||||
"response": content,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Validate the provider connection and review the proposal (fail-closed).
|
||||
/// Exposed so tests can drive it with a canned transport.
|
||||
pub fn ai_check_with(&mut self, transport: &dyn ModelTransport) -> Result<Value, String> {
|
||||
let facts = self.installer.system_facts();
|
||||
let api_key_present = self.api_key.is_some();
|
||||
let Bridge {
|
||||
installer,
|
||||
approved_digest,
|
||||
..
|
||||
} = self;
|
||||
let Installer { exec, config, .. } = installer;
|
||||
let value = review_proposal(config, exec.redactor(), facts, api_key_present, transport)?;
|
||||
*approved_digest = None;
|
||||
let value = {
|
||||
let Installer { exec, config, .. } = &mut self.installer;
|
||||
review_proposal(config, exec.redactor(), facts, api_key_present, transport)?
|
||||
};
|
||||
self.approved_digest = None;
|
||||
self.validated_ai = Some(self.plan_digest());
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
|
|
@ -558,18 +659,20 @@ impl Bridge {
|
|||
}
|
||||
|
||||
// AI is mandatory to install unless this is a dry run or an explicit
|
||||
// break-glass (mirrors the CLI rule).
|
||||
// break-glass. A validated interaction is required: merely naming a
|
||||
// provider is not enough. The validation is bound to the current
|
||||
// configuration, so a change since validation invalidates it.
|
||||
let dry_run = self.installer.config.runtime.dry_run;
|
||||
if !dry_run {
|
||||
let provider = ProviderKind::parse(&self.installer.config.ai.provider)
|
||||
.unwrap_or(ProviderKind::None);
|
||||
let break_glass = std::env::var("PHOEBUS_NO_AI")
|
||||
.map(|v| matches!(v.to_ascii_lowercase().as_str(), "1" | "yes" | "true"))
|
||||
.unwrap_or(false);
|
||||
if provider == ProviderKind::None && !break_glass {
|
||||
let validated = self.validated_ai.as_deref() == Some(current.as_str());
|
||||
if !validated && !break_glass {
|
||||
return Err(
|
||||
"installing Phoebus requires a connected AI model; connect a provider \
|
||||
or set PHOEBUS_NO_AI=1 for a deterministic install"
|
||||
"installing Phoebus requires a successful, validated AI interaction for \
|
||||
the current configuration; connect and validate a model, or set \
|
||||
PHOEBUS_NO_AI=1 for a deterministic install"
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
|
|
@ -602,6 +705,7 @@ impl Bridge {
|
|||
// Consume the approval and mark the session busy before any destructive
|
||||
// work: a replay or a second frontend can never reach storage_prepare.
|
||||
self.approved_digest = None;
|
||||
self.validated_ai = None;
|
||||
self.installing = true;
|
||||
let outcome = self.installer.install_observed(
|
||||
&auth,
|
||||
|
|
@ -757,8 +861,109 @@ fn config_digest(config: &InstallConfig) -> String {
|
|||
format!("{:x}", hasher.finalize())
|
||||
}
|
||||
|
||||
/// Parse the provider from the configuration, validate the connection and apply
|
||||
/// the reviewed proposal. This is the same `ai_guide` path the TUI uses.
|
||||
/// The OpenCode server URL, provider id and model id, validated for presence.
|
||||
fn opencode_parts(config: &InstallConfig) -> Result<(String, String, String), String> {
|
||||
let server = config.ai.opencode_server.trim().to_string();
|
||||
let provider = config.ai.opencode_provider.trim().to_string();
|
||||
let model = config.ai.opencode_model.trim().to_string();
|
||||
if server.is_empty() {
|
||||
return Err("OpenCode requires a server URL".into());
|
||||
}
|
||||
if provider.is_empty() {
|
||||
return Err("OpenCode requires a provider".into());
|
||||
}
|
||||
if model.is_empty() {
|
||||
return Err("OpenCode requires a model".into());
|
||||
}
|
||||
// Fail fast on an unsafe endpoint, before any request is attempted.
|
||||
phoebus_executor::opencode_server::Endpoint::parse(&server)
|
||||
.map_err(|e| format!("invalid OpenCode endpoint: {e}"))?;
|
||||
Ok((server, provider, model))
|
||||
}
|
||||
|
||||
fn opencode_transport<'a>(
|
||||
exec: &'a Exec,
|
||||
config: &InstallConfig,
|
||||
password: Option<SecretString>,
|
||||
) -> Result<phoebus_executor::opencode_client::ExecOpenCodeTransport<'a>, String> {
|
||||
let (server, provider, model) = opencode_parts(config)?;
|
||||
Ok(
|
||||
phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
||||
exec, server, provider, model,
|
||||
)
|
||||
.with_auth(password),
|
||||
)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn finish_review(
|
||||
config: &mut InstallConfig,
|
||||
redactor: &phoebus_core::Redactor,
|
||||
facts: SystemFacts,
|
||||
kind: ProviderKind,
|
||||
endpoint: &str,
|
||||
provider_label: &str,
|
||||
model: &str,
|
||||
transport: &dyn ModelTransport,
|
||||
backend: &str,
|
||||
) -> Result<Value, String> {
|
||||
let outcome =
|
||||
ai_guide::generate_and_review_at(config, &facts, kind, endpoint, model, transport)
|
||||
.map_err(|e| {
|
||||
// Error messages are redacted before they reach the GUI.
|
||||
format!(
|
||||
"connection or proposal failed: {}",
|
||||
redactor.redact(&e.to_string())
|
||||
)
|
||||
})?;
|
||||
let applied: Vec<Value> = outcome
|
||||
.applied
|
||||
.iter()
|
||||
.map(|c| {
|
||||
json!({
|
||||
"description": c.description,
|
||||
"reason": c.reason,
|
||||
"evidence": c.evidence,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Ok(json!({
|
||||
"connected": true,
|
||||
"backend": backend,
|
||||
"provider": provider_label,
|
||||
"model": model,
|
||||
"endpoint": endpoint,
|
||||
"applied": applied,
|
||||
"config": config,
|
||||
"plan_digest": config_digest(config),
|
||||
}))
|
||||
}
|
||||
|
||||
/// OpenCode proposal review: the adapter talks the agent protocol and the
|
||||
/// shared strict proposal parser/review applies the accepted changes.
|
||||
fn review_opencode(
|
||||
config: &mut InstallConfig,
|
||||
redactor: &phoebus_core::Redactor,
|
||||
facts: SystemFacts,
|
||||
transport: &dyn ModelTransport,
|
||||
) -> Result<Value, String> {
|
||||
let (server, provider_id, model) = opencode_parts(config)?;
|
||||
finish_review(
|
||||
config,
|
||||
redactor,
|
||||
facts,
|
||||
ProviderKind::Local,
|
||||
&server,
|
||||
&provider_id,
|
||||
&model,
|
||||
transport,
|
||||
"opencode",
|
||||
)
|
||||
}
|
||||
|
||||
/// Parse the direct provider from the configuration, validate the connection
|
||||
/// and apply the reviewed proposal. This is the same `ai_guide` path the TUI
|
||||
/// uses.
|
||||
fn review_proposal(
|
||||
config: &mut InstallConfig,
|
||||
redactor: &phoebus_core::Redactor,
|
||||
|
|
@ -788,36 +993,17 @@ fn review_proposal(
|
|||
provider.as_str()
|
||||
));
|
||||
}
|
||||
|
||||
let outcome =
|
||||
ai_guide::generate_and_review_at(config, &facts, provider, &endpoint, &model, transport)
|
||||
.map_err(|e| {
|
||||
// Error messages are redacted before they reach the GUI.
|
||||
format!(
|
||||
"connection or proposal failed: {}",
|
||||
redactor.redact(&e.to_string())
|
||||
finish_review(
|
||||
config,
|
||||
redactor,
|
||||
facts,
|
||||
provider,
|
||||
&endpoint,
|
||||
provider.as_str(),
|
||||
&model,
|
||||
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`.
|
||||
|
|
@ -1275,4 +1461,173 @@ mod tests {
|
|||
let lines = call(&mut bridge, &line);
|
||||
assert_eq!(response(&lines)["ok"], json!(false));
|
||||
}
|
||||
|
||||
/// A non-dry bridge whose runner reports `/dev/vda`, so revalidation and
|
||||
/// the install stages run against the fake runner (never a real disk).
|
||||
fn test_bridge_non_dry() -> Bridge {
|
||||
let runner = RecordingRunner::new();
|
||||
runner.set_response(
|
||||
"lsblk",
|
||||
phoebus_executor::CommandOutput {
|
||||
status: 0,
|
||||
success: true,
|
||||
stdout: b"NAME=\"vda\" MODEL=\"QEMU HARDDISK\" SIZE=\"32212254720\" TRAN=\"virtio\" RM=\"0\" RO=\"0\"\n".to_vec(),
|
||||
stderr: Vec::new(),
|
||||
duration: std::time::Duration::from_millis(1),
|
||||
},
|
||||
);
|
||||
let dir = tempfile::tempdir().unwrap().keep();
|
||||
let logger = Logger::open(dir.join("install.log"), Redactor::new(), false);
|
||||
let mut config = InstallConfig::default();
|
||||
config.runtime.dry_run = false;
|
||||
config.system.hostname = "phoebus".into();
|
||||
config.system.timezone = "UTC".into();
|
||||
config.user.username = "tester".into();
|
||||
config.storage.disk = "/dev/vda".into();
|
||||
let exec = Exec::new(
|
||||
Box::new(runner),
|
||||
logger,
|
||||
false,
|
||||
dir.join("root"),
|
||||
dir.clone(),
|
||||
);
|
||||
let mut installer = Installer::new(config, exec);
|
||||
installer.disks.push(Disk {
|
||||
path: "/dev/vda".into(),
|
||||
model: Some("QEMU HARDDISK".into()),
|
||||
size_bytes: 30 * 1024 * 1024 * 1024,
|
||||
transport: Some("virtio".into()),
|
||||
removable: false,
|
||||
read_only: false,
|
||||
mounted: false,
|
||||
is_block_device: true,
|
||||
kind: DiskKind::Physical,
|
||||
live_media: false,
|
||||
});
|
||||
Bridge::with_installer(installer)
|
||||
}
|
||||
|
||||
fn arm_ai(bridge: &mut Bridge) -> Value {
|
||||
let mut c = config_json(bridge);
|
||||
c["ai"]["provider"] = json!("deepseek");
|
||||
c["ai"]["model"] = json!("deepseek-chat");
|
||||
let _ = call(
|
||||
bridge,
|
||||
&json!({ "id": 30, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
bridge.api_key = Some(SecretString::new("test-key"));
|
||||
let proposal = r#"{"version":1,"changes":[{"action":"set_kernel_profile","value":"safe"}],"rationale":[{"action":"set_kernel_profile","reason":"stability","evidence":["x"]}]}"#;
|
||||
bridge
|
||||
.ai_check_with(&TestTransport::proposal(proposal))
|
||||
.expect("ai_check")
|
||||
}
|
||||
|
||||
fn start(bridge: &mut Bridge, digest: &str) -> Value {
|
||||
let lines = call(
|
||||
bridge,
|
||||
&json!({
|
||||
"id": 31, "op": "start_install", "erase": "ERASE",
|
||||
"final_confirm": true, "plan_digest": digest
|
||||
})
|
||||
.to_string(),
|
||||
);
|
||||
response(&lines)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_provider_name_alone_does_not_satisfy_the_ai_requirement() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
// Provider configured and key present, but no validated interaction.
|
||||
let mut c = config_json(&bridge);
|
||||
c["ai"]["provider"] = json!("deepseek");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 40, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
bridge.api_key = Some(SecretString::new("test-key"));
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(
|
||||
resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"),
|
||||
"unexpected error: {}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_validated_interaction_satisfies_the_ai_requirement() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
// It may fail later in the fake storage stage, but never on the AI gate.
|
||||
assert!(
|
||||
!resp["error"]
|
||||
.as_str()
|
||||
.unwrap_or("")
|
||||
.contains("validated AI interaction"),
|
||||
"the AI gate wrongly rejected a validated interaction: {}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_config_change_invalidates_the_validated_interaction() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
// Change the model after validation.
|
||||
let mut c = config_json(&bridge);
|
||||
c["ai"]["model"] = json!("deepseek-reasoner");
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
&json!({ "id": 41, "op": "set_config", "config": c }).to_string(),
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_secret_change_invalidates_the_validated_interaction() {
|
||||
let mut bridge = test_bridge_non_dry();
|
||||
set_valid_config(&mut bridge);
|
||||
arm_ai(&mut bridge);
|
||||
let _ = call(
|
||||
&mut bridge,
|
||||
r#"{"id":42,"op":"set_secrets","secrets":{"ai_api_key":"new-key"}}"#,
|
||||
);
|
||||
let (digest, _) = approve(&mut bridge);
|
||||
let resp = start(&mut bridge, &digest);
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(resp["error"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("validated AI interaction"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ai_test_is_a_known_operation_and_fails_without_a_provider() {
|
||||
let mut bridge = test_bridge();
|
||||
let lines = call(&mut bridge, r#"{"id":43,"op":"ai_test"}"#);
|
||||
let resp = response(&lines);
|
||||
// Not "unknown op": the operation exists and reports the configuration
|
||||
// problem instead.
|
||||
assert_eq!(resp["ok"], json!(false));
|
||||
assert!(
|
||||
!resp["error"].as_str().unwrap().contains("unknown op"),
|
||||
"{}",
|
||||
resp["error"]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -122,10 +122,36 @@ struct Cli {
|
|||
gui_bridge: bool,
|
||||
|
||||
/// Probe a running OpenCode server (e.g. `http://127.0.0.1:4096`) and print
|
||||
/// its capability as JSON. Read-only; exits nonzero unless a model is
|
||||
/// available. Never prints provider credentials.
|
||||
/// its capability as JSON. Read-only; exits nonzero unless a model catalog
|
||||
/// is available. Never prints provider credentials.
|
||||
#[arg(long, value_name = "URL")]
|
||||
opencode_probe: Option<String>,
|
||||
|
||||
/// Obtain a real model response through an OpenCode server and validate it,
|
||||
/// then exit. This is the acceptance test for inference, not reachability.
|
||||
#[arg(long, value_name = "URL")]
|
||||
opencode_test: Option<String>,
|
||||
|
||||
/// OpenCode agent server URL, e.g. `http://127.0.0.1:4096`.
|
||||
#[arg(long, value_name = "URL")]
|
||||
opencode_server: Option<String>,
|
||||
|
||||
/// OpenCode provider id (e.g. `deepseek`).
|
||||
#[arg(long, value_name = "PROVIDER")]
|
||||
opencode_provider: Option<String>,
|
||||
|
||||
/// OpenCode model id (e.g. `deepseek-chat`).
|
||||
#[arg(long, value_name = "MODEL")]
|
||||
opencode_model: Option<String>,
|
||||
|
||||
/// Read the OpenCode server password from a mode-0600 file (distinct from a
|
||||
/// model provider API key).
|
||||
#[arg(long, value_name = "FILE")]
|
||||
opencode_password_file: Option<PathBuf>,
|
||||
|
||||
/// AI backend for install guidance: `direct` (default) or `opencode`.
|
||||
#[arg(long, value_name = "BACKEND")]
|
||||
ai_backend: Option<String>,
|
||||
}
|
||||
|
||||
struct TerminalConfirm;
|
||||
|
|
@ -161,6 +187,94 @@ fn read_secret(path: &PathBuf) -> std::io::Result<SecretString> {
|
|||
Ok(SecretString::new(value.trim_end_matches(['\n', '\r'])))
|
||||
}
|
||||
|
||||
/// A lightweight `Exec` for the OpenCode probe/test commands, which do not
|
||||
/// touch the target.
|
||||
fn opencode_exec() -> Exec {
|
||||
let dir = std::env::temp_dir().join("phoebus-opencode-cli");
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
let logger = Logger::open(dir.join("opencode.log"), Redactor::new(), false);
|
||||
Exec::new(Box::new(RealRunner), logger, false, dir.clone(), dir)
|
||||
}
|
||||
|
||||
/// Probe an OpenCode server (`validate_inference = false`) or obtain and
|
||||
/// validate a real model response (`true`). Exits nonzero unless the requested
|
||||
/// condition is met, so it can be used as an acceptance command.
|
||||
fn run_opencode_probe(cli: &Cli, url: &str, validate_inference: bool) -> ExitCode {
|
||||
use phoebus_executor::opencode_client::{CurlHttpClient, OpenCodeClient};
|
||||
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint, ProbeRequest};
|
||||
|
||||
let endpoint = match Endpoint::parse(url) {
|
||||
Ok(endpoint) => endpoint,
|
||||
Err(e) => {
|
||||
eprintln!("invalid OpenCode endpoint `{url}`: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let auth = match &cli.opencode_password_file {
|
||||
Some(path) => match read_secret(path) {
|
||||
Ok(secret) => Some(secret),
|
||||
Err(e) => {
|
||||
eprintln!("cannot read OpenCode password file: {e}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
},
|
||||
None => None,
|
||||
};
|
||||
let provider = cli.opencode_provider.clone().unwrap_or_default();
|
||||
let model = cli.opencode_model.clone().unwrap_or_default();
|
||||
let exec = opencode_exec();
|
||||
let http = CurlHttpClient::new(&exec);
|
||||
|
||||
if !validate_inference {
|
||||
let mut request = ProbeRequest::new();
|
||||
request.auth = auth.clone();
|
||||
request.provider = (!provider.is_empty()).then(|| provider.clone());
|
||||
request.model = (!model.is_empty()).then(|| model.clone());
|
||||
let capability = probe(&http, &endpoint, &request);
|
||||
match serde_json::to_string_pretty(&capability) {
|
||||
Ok(json) => println!("{json}"),
|
||||
Err(e) => eprintln!("could not render capability: {e}"),
|
||||
}
|
||||
return if matches!(
|
||||
capability.state,
|
||||
ConnectionState::ModelCatalog | ConnectionState::Ready
|
||||
) {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::FAILURE
|
||||
};
|
||||
}
|
||||
|
||||
if provider.is_empty() || model.is_empty() {
|
||||
eprintln!("--opencode-test requires --opencode-provider and --opencode-model");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
let client = OpenCodeClient::new(&http, endpoint.base(), &provider, &model).with_auth(auth);
|
||||
match client.one_shot(
|
||||
"You are a connectivity test. Reply with JSON only.",
|
||||
"Reply with exactly {\"phoebus\":\"ok\"} and nothing else.",
|
||||
) {
|
||||
Ok(reply) => match serde_json::from_str::<serde_json::Value>(&reply.content) {
|
||||
Ok(value) if value.get("phoebus").and_then(|v| v.as_str()) == Some("ok") => {
|
||||
println!("validated model response: {}", reply.content);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(value) => {
|
||||
println!("model responded, but not as requested: {value}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
Err(_) => {
|
||||
println!("model response was not JSON: {}", reply.content);
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Err(e) => {
|
||||
eprintln!("model validation failed: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The provider selected on the command line, or the one the TUI/config chose.
|
||||
fn resolve_provider(
|
||||
cli: &Cli,
|
||||
|
|
@ -183,48 +297,116 @@ fn no_ai_requested(cli: &Cli) -> bool {
|
|||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Installing Phoebus requires a connected model. `--no-ai`/`--legacy` is the
|
||||
/// explicit, documented break-glass for recovery or automation.
|
||||
/// Installing Phoebus requires a **validated** AI interaction, not just a
|
||||
/// non-empty provider name. `--no-ai`/`--legacy` is the explicit, documented
|
||||
/// break-glass for recovery or automation.
|
||||
fn require_ai_for_install(
|
||||
cli: &Cli,
|
||||
provider: ProviderKind,
|
||||
validated: bool,
|
||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
if no_ai_requested(cli) || provider != ProviderKind::None {
|
||||
if no_ai_requested(cli) || validated {
|
||||
return Ok(());
|
||||
}
|
||||
Err("installing Phoebus requires a connected AI model.\n\
|
||||
Connect a provider (--ai-provider deepseek|openai|local, with \
|
||||
--ai-api-key-file and/or --ai-endpoint), or pass --no-ai (alias \
|
||||
--legacy) for a deterministic install."
|
||||
.into())
|
||||
Err(
|
||||
"installing Phoebus requires a successful, validated AI interaction.\n\
|
||||
Connect a provider (--ai-backend direct with --ai-provider \
|
||||
deepseek|openai|local and --ai-api-key-file/--ai-endpoint, or \
|
||||
--ai-backend opencode with --opencode-server/--opencode-provider/\
|
||||
--opencode-model) and let it return a valid proposal, or pass --no-ai \
|
||||
(alias --legacy) for a deterministic install."
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Apply AI guidance to the configuration before the plan is shown or install
|
||||
/// runs. The model never sees secrets and never executes anything: its response
|
||||
/// is reviewed with mandatory evidence and applied atomically.
|
||||
/// runs. Returns `true` only when a model interaction produced a valid,
|
||||
/// reviewed proposal. The model never sees secrets and never executes anything.
|
||||
fn run_ai_guidance(
|
||||
cli: &Cli,
|
||||
installer: &mut Installer,
|
||||
) -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
let provider = resolve_provider(cli, &installer.config)?;
|
||||
) -> std::result::Result<bool, Box<dyn std::error::Error>> {
|
||||
let wants_ai = cli.ai || cli.ai_proposal_file.is_some() || installer.config.ai.enabled;
|
||||
if !wants_ai {
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
if let Some(path) = &cli.ai_proposal_file {
|
||||
let outcome = phoebus_installer::ai_guide::review_file(&mut installer.config, path)?;
|
||||
println!("{}", outcome.render());
|
||||
return Ok(());
|
||||
return Ok(true);
|
||||
}
|
||||
|
||||
let backend = cli
|
||||
.ai_backend
|
||||
.as_deref()
|
||||
.and_then(phoebus_core::AiBackend::parse)
|
||||
.unwrap_or(installer.config.ai.backend);
|
||||
let facts = installer.system_facts();
|
||||
|
||||
if backend == phoebus_core::AiBackend::OpenCode {
|
||||
let server = cli
|
||||
.opencode_server
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_OPENCODE_SERVER").ok())
|
||||
.unwrap_or_else(|| installer.config.ai.opencode_server.clone());
|
||||
let provider_id = cli
|
||||
.opencode_provider
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_OPENCODE_PROVIDER").ok())
|
||||
.unwrap_or_else(|| installer.config.ai.opencode_provider.clone());
|
||||
let model = cli
|
||||
.opencode_model
|
||||
.clone()
|
||||
.or_else(|| std::env::var("PHOEBUS_OPENCODE_MODEL").ok())
|
||||
.unwrap_or_else(|| installer.config.ai.opencode_model.clone());
|
||||
if server.trim().is_empty() || provider_id.trim().is_empty() || model.trim().is_empty() {
|
||||
eprintln!(
|
||||
"AI assistance is enabled but OpenCode is not fully configured \
|
||||
(need server, provider and model); continuing without AI."
|
||||
);
|
||||
return Ok(false);
|
||||
}
|
||||
let password = match &cli.opencode_password_file {
|
||||
Some(path) => Some(phoebus_executor::ai::load_api_key(path)?),
|
||||
None => None,
|
||||
};
|
||||
eprintln!(
|
||||
"Sending these system facts through the OpenCode server at {} \
|
||||
(provider {}, no passwords, passphrases or files):",
|
||||
server, provider_id
|
||||
);
|
||||
eprintln!("{}", facts.render());
|
||||
let transport = phoebus_executor::opencode_client::ExecOpenCodeTransport::new(
|
||||
&installer.exec,
|
||||
server.clone(),
|
||||
provider_id.clone(),
|
||||
model.clone(),
|
||||
)
|
||||
.with_auth(password);
|
||||
return match phoebus_installer::ai_guide::generate_and_review_at(
|
||||
&mut installer.config,
|
||||
&facts,
|
||||
ProviderKind::Local,
|
||||
&server,
|
||||
&model,
|
||||
&transport,
|
||||
) {
|
||||
Ok(outcome) => {
|
||||
println!("{}", outcome.render());
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("OpenCode proposal rejected; continuing with the proven defaults: {e}");
|
||||
Ok(false)
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let provider = resolve_provider(cli, &installer.config)?;
|
||||
if provider == ProviderKind::None {
|
||||
eprintln!("AI assistance is enabled but no provider is selected; continuing without AI.");
|
||||
return Ok(());
|
||||
return Ok(false);
|
||||
}
|
||||
|
||||
// Opt-in: show exactly what leaves the machine before sending it.
|
||||
let facts = installer.system_facts();
|
||||
eprintln!(
|
||||
"Sending these system facts to {} (no passwords, passphrases or files):",
|
||||
provider.as_str()
|
||||
|
|
@ -244,7 +426,6 @@ fn run_ai_guidance(
|
|||
)
|
||||
.into());
|
||||
}
|
||||
// A self-hosted local model usually needs no key.
|
||||
(None, false) => None,
|
||||
};
|
||||
let model = cli.ai_model.clone().unwrap_or_default();
|
||||
|
|
@ -257,10 +438,15 @@ fn run_ai_guidance(
|
|||
&model,
|
||||
&transport,
|
||||
) {
|
||||
Ok(outcome) => println!("{}", outcome.render()),
|
||||
Err(e) => eprintln!("AI proposal rejected; continuing with the proven defaults: {e}"),
|
||||
Ok(outcome) => {
|
||||
println!("{}", outcome.render());
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("AI proposal rejected; continuing with the proven defaults: {e}");
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
|
|
@ -282,16 +468,10 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
|
|||
}
|
||||
|
||||
if let Some(url) = &cli.opencode_probe {
|
||||
use phoebus_executor::opencode_server::{probe, ConnectionState, Endpoint};
|
||||
let endpoint =
|
||||
Endpoint::parse(url).map_err(|e| format!("invalid OpenCode endpoint `{url}`: {e}"))?;
|
||||
let capability = probe(&endpoint, std::time::Duration::from_secs(5));
|
||||
println!("{}", serde_json::to_string_pretty(&capability)?);
|
||||
return Ok(if capability.state == ConnectionState::Ready {
|
||||
ExitCode::SUCCESS
|
||||
} else {
|
||||
ExitCode::FAILURE
|
||||
});
|
||||
return Ok(run_opencode_probe(&cli, url, false));
|
||||
}
|
||||
if let Some(url) = &cli.opencode_test {
|
||||
return Ok(run_opencode_probe(&cli, url, true));
|
||||
}
|
||||
|
||||
if let Some(name) = &cli.emit_asset {
|
||||
|
|
@ -411,12 +591,13 @@ fn run() -> std::result::Result<ExitCode, Box<dyn std::error::Error>> {
|
|||
println!("{}", installer.system_facts().render());
|
||||
return Ok(ExitCode::SUCCESS);
|
||||
}
|
||||
run_ai_guidance(&cli, &mut installer)?;
|
||||
let ai_validated = run_ai_guidance(&cli, &mut installer)?;
|
||||
|
||||
// AI is mandatory to install; a deterministic no-AI run needs the explicit
|
||||
// AI is mandatory to install, and a validated interaction (not merely a
|
||||
// provider name) is required; a deterministic no-AI run needs the explicit
|
||||
// break-glass. Dry-run and plan modes are exempt.
|
||||
if do_install && !installer.config.runtime.dry_run {
|
||||
require_ai_for_install(&cli, resolve_provider(&cli, &installer.config)?)?;
|
||||
require_ai_for_install(&cli, ai_validated)?;
|
||||
}
|
||||
|
||||
if let Some(path) = &cli.save_config {
|
||||
|
|
|
|||
|
|
@ -109,7 +109,7 @@ fn install_without_ai_is_refused() {
|
|||
.expect("run phoebus-installer");
|
||||
assert!(!out.status.success());
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(err.contains("requires a connected AI"), "{err}");
|
||||
assert!(err.contains("validated AI interaction"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
@ -122,21 +122,31 @@ fn no_ai_is_the_explicit_break_glass() {
|
|||
.output()
|
||||
.expect("run phoebus-installer");
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!err.contains("requires a connected AI"), "{flag}: {err}");
|
||||
assert!(!err.contains("validated AI interaction"), "{flag}: {err}");
|
||||
assert!(err.contains("configuration is incomplete"), "{flag}: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_provider_needs_no_key_at_the_gate() {
|
||||
// A local provider satisfies the gate without --no-ai (it fails later at
|
||||
// the incomplete config, not at the AI gate).
|
||||
fn an_unreachable_provider_does_not_satisfy_the_ai_gate() {
|
||||
// A provider *name* is not enough: without a real, validated model
|
||||
// interaction the install is refused (a deliberately closed port makes the
|
||||
// result deterministic and offline).
|
||||
let out = Command::new(bin())
|
||||
.args(["--install", "--yes", "--ai", "--ai-provider", "local"])
|
||||
.args([
|
||||
"--install",
|
||||
"--yes",
|
||||
"--ai",
|
||||
"--ai-provider",
|
||||
"local",
|
||||
"--ai-endpoint",
|
||||
"http://127.0.0.1:1/v1/chat/completions",
|
||||
])
|
||||
.output()
|
||||
.expect("run phoebus-installer");
|
||||
assert!(!out.status.success());
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
assert!(!err.contains("requires a connected AI"), "{err}");
|
||||
assert!(err.contains("validated AI interaction"), "{err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
|
|
|||
|
|
@ -128,6 +128,9 @@ Singleton {
|
|||
function aiCheck(cb) {
|
||||
call("ai_check", {}, cb);
|
||||
}
|
||||
function aiTest(cb) {
|
||||
call("ai_test", {}, cb);
|
||||
}
|
||||
function approve(eraseText, finalConfirmed, cb) {
|
||||
call("approve", { erase: eraseText, final_confirm: finalConfirmed }, cb);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,11 +28,19 @@ ShellRoot {
|
|||
property string luksPw: ""
|
||||
property string luksPw2: ""
|
||||
property string apiKey: ""
|
||||
// OpenCode server password (basic auth), distinct from a provider API key.
|
||||
property string opencodePassword: ""
|
||||
|
||||
property bool aiConnected: false
|
||||
property bool aiChecking: false
|
||||
property string aiError: ""
|
||||
property var aiApplied: []
|
||||
// "Test connection" state: a real, validated model response was obtained.
|
||||
property bool aiTesting: false
|
||||
property bool aiTested: false
|
||||
property string aiTestMessage: ""
|
||||
|
||||
readonly property bool isOpenCode: shell.cfg && shell.cfg.ai.backend === "opencode"
|
||||
|
||||
property var stageStatus: ({})
|
||||
property var stageOrder: []
|
||||
|
|
@ -69,6 +77,26 @@ ShellRoot {
|
|||
return JSON.parse(JSON.stringify(o));
|
||||
}
|
||||
|
||||
// A compact, secret-free state line for the harness. It lets a test assert
|
||||
// the actual current step and AI connection state instead of inferring them
|
||||
// from a screenshot or the mere survival of the process.
|
||||
function logState(tag) {
|
||||
console.log("phoebus-state " + tag
|
||||
+ " step=" + shell.step
|
||||
+ " phase=" + shell.phase
|
||||
+ " aiConnected=" + shell.aiConnected
|
||||
+ " aiTested=" + shell.aiTested
|
||||
+ " aiApplied=" + shell.aiApplied.length
|
||||
+ " aiError=" + shell.aiError.replace(/\n/g, " ").slice(0, 200)
|
||||
+ " aiTest=" + shell.aiTestMessage.replace(/\n/g, " ").slice(0, 200));
|
||||
}
|
||||
onStepChanged: logState("step")
|
||||
onPhaseChanged: logState("phase")
|
||||
onAiConnectedChanged: logState("ai")
|
||||
onAiErrorChanged: logState("error")
|
||||
onAiTestedChanged: logState("test")
|
||||
onAiTestMessageChanged: logState("testmsg")
|
||||
|
||||
// QML `var` properties do not emit change signals for nested assignments,
|
||||
// so bindings that read `cfg.*` would not update. Reassigning a clone
|
||||
// re-evaluates them. Used after a choice/toggle changes the configuration.
|
||||
|
|
@ -92,6 +120,10 @@ ShellRoot {
|
|||
modelField.inputItem.text = shell.cfg.ai.model;
|
||||
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
||||
keyField.inputItem.text = shell.apiKey;
|
||||
opencodeServerField.inputItem.text = shell.cfg.ai.opencode_server;
|
||||
opencodeProviderField.inputItem.text = shell.cfg.ai.opencode_provider;
|
||||
opencodeModelField.inputItem.text = shell.cfg.ai.opencode_model;
|
||||
opencodePasswordField.inputItem.text = shell.opencodePassword;
|
||||
pwField.inputItem.text = shell.userPw;
|
||||
pw2Field.inputItem.text = shell.userPw2;
|
||||
luksField.inputItem.text = shell.luksPw;
|
||||
|
|
@ -230,7 +262,7 @@ ShellRoot {
|
|||
shell.status = "";
|
||||
const s = shell.step;
|
||||
if (s === 2) {
|
||||
if (!shell.cfg.ai.provider || shell.cfg.ai.provider === "none") {
|
||||
if (!shell.isOpenCode && (!shell.cfg.ai.provider || shell.cfg.ai.provider === "none")) {
|
||||
shell.cfg.ai.provider = "deepseek";
|
||||
shell.cfg.ai.enabled = true;
|
||||
if (!shell.cfg.ai.model)
|
||||
|
|
@ -278,11 +310,26 @@ ShellRoot {
|
|||
}
|
||||
|
||||
function configureProvider(value) {
|
||||
shell.cfg.ai.provider = value;
|
||||
shell.cfg.ai.enabled = value !== "none";
|
||||
shell.aiConnected = false;
|
||||
shell.aiTested = false;
|
||||
shell.aiTestMessage = "";
|
||||
shell.aiError = "";
|
||||
shell.aiApplied = [];
|
||||
if (value === "opencode") {
|
||||
// OpenCode is an agent server with its own protocol; it is not an
|
||||
// OpenAI-compatible endpoint, so it has its own backend and fields.
|
||||
shell.cfg.ai.backend = "opencode";
|
||||
shell.cfg.ai.provider = "opencode";
|
||||
shell.cfg.ai.opencode_server = shell.cfg.ai.opencode_server || "http://127.0.0.1:4096";
|
||||
shell.cfg.ai.opencode_provider = shell.cfg.ai.opencode_provider || "deepseek";
|
||||
shell.cfg.ai.opencode_model = shell.cfg.ai.opencode_model || "deepseek-chat";
|
||||
opencodeServerField.inputItem.text = shell.cfg.ai.opencode_server;
|
||||
opencodeProviderField.inputItem.text = shell.cfg.ai.opencode_provider;
|
||||
opencodeModelField.inputItem.text = shell.cfg.ai.opencode_model;
|
||||
} else {
|
||||
shell.cfg.ai.backend = "direct";
|
||||
shell.cfg.ai.provider = value;
|
||||
if (value === "deepseek")
|
||||
shell.cfg.ai.model = "deepseek-chat";
|
||||
else if (value === "openai")
|
||||
|
|
@ -291,9 +338,37 @@ ShellRoot {
|
|||
shell.cfg.ai.model = shell.cfg.ai.model || "llama3.1";
|
||||
modelField.inputItem.text = shell.cfg.ai.model;
|
||||
endpointField.inputItem.text = shell.cfg.ai.endpoint;
|
||||
}
|
||||
shell.touchConfig();
|
||||
}
|
||||
|
||||
// A lightweight real interaction used by "Test connection": it obtains and
|
||||
// validates a model response without proposing installation changes.
|
||||
function testAi() {
|
||||
shell.aiTesting = true;
|
||||
shell.aiTested = false;
|
||||
shell.aiTestMessage = "";
|
||||
shell.aiError = "";
|
||||
const secrets = {};
|
||||
if (shell.opencodePassword.length > 0)
|
||||
secrets.opencode_password = shell.opencodePassword;
|
||||
if (shell.apiKey.length > 0)
|
||||
secrets.ai_api_key = shell.apiKey;
|
||||
Bridge.setSecrets(secrets, () => {
|
||||
applyConfig(() => {
|
||||
Bridge.aiTest(reply => {
|
||||
shell.aiTesting = false;
|
||||
if (reply.ok) {
|
||||
shell.aiTested = true;
|
||||
shell.aiTestMessage = "Model responded";
|
||||
} else {
|
||||
shell.aiTestMessage = reply.error;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function connectAi() {
|
||||
shell.aiChecking = true;
|
||||
shell.aiError = "";
|
||||
|
|
@ -302,6 +377,8 @@ ShellRoot {
|
|||
const secrets = {};
|
||||
if (shell.apiKey.length > 0)
|
||||
secrets.ai_api_key = shell.apiKey;
|
||||
if (shell.opencodePassword.length > 0)
|
||||
secrets.opencode_password = shell.opencodePassword;
|
||||
Bridge.setSecrets(secrets, () => {
|
||||
applyConfig(() => {
|
||||
Bridge.aiCheck(reply => {
|
||||
|
|
@ -709,17 +786,19 @@ ShellRoot {
|
|||
options: [
|
||||
{ value: "deepseek", label: "DeepSeek" },
|
||||
{ value: "openai", label: "OpenAI" },
|
||||
{ value: "local", label: "Local model" }
|
||||
{ value: "local", label: "Local model" },
|
||||
{ value: "opencode", label: "OpenCode agent" }
|
||||
]
|
||||
value: shell.cfg ? shell.cfg.ai.provider : "deepseek"
|
||||
value: shell.isOpenCode ? "opencode" : (shell.cfg ? shell.cfg.ai.provider : "deepseek")
|
||||
onSelected: value => shell.configureProvider(value)
|
||||
}
|
||||
// -- direct providers ----------------------------------
|
||||
PhoebusField {
|
||||
id: keyField
|
||||
label: "API key"
|
||||
placeholder: "Paste your provider key"
|
||||
secret: true
|
||||
visible: shell.cfg && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai")
|
||||
visible: shell.cfg && !shell.isOpenCode && (shell.cfg.ai.provider === "deepseek" || shell.cfg.ai.provider === "openai")
|
||||
onEdited: value => shell.apiKey = value
|
||||
}
|
||||
PhoebusField {
|
||||
|
|
@ -727,6 +806,7 @@ ShellRoot {
|
|||
label: "Model"
|
||||
placeholder: "model name"
|
||||
error: ""
|
||||
visible: shell.cfg && !shell.isOpenCode
|
||||
onEdited: value => shell.cfg.ai.model = value
|
||||
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.model ? shell.cfg.ai.model : ""
|
||||
}
|
||||
|
|
@ -734,21 +814,70 @@ ShellRoot {
|
|||
id: endpointField
|
||||
label: "Endpoint (local models)"
|
||||
placeholder: "http://127.0.0.1:11434/v1/chat/completions"
|
||||
visible: shell.cfg && shell.cfg.ai.provider === "local"
|
||||
visible: shell.cfg && !shell.isOpenCode && shell.cfg.ai.provider === "local"
|
||||
onEdited: value => shell.cfg.ai.endpoint = value
|
||||
Component.onCompleted: inputItem.text = shell.cfg && shell.cfg.ai.endpoint ? shell.cfg.ai.endpoint : ""
|
||||
}
|
||||
// -- OpenCode agent server -----------------------------
|
||||
Text {
|
||||
width: parent.width
|
||||
visible: shell.isOpenCode
|
||||
text: "OpenCode is an agent server, not a model endpoint. Phoebus connects to it over its own protocol. Bind it to loopback and reach a remote server through an authenticated tunnel; plain http to a non-loopback address is refused."
|
||||
color: Theme.muted
|
||||
font.family: Theme.family
|
||||
font.pixelSize: Theme.fontSmall
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
PhoebusField {
|
||||
id: opencodeServerField
|
||||
label: "OpenCode server"
|
||||
placeholder: "http://127.0.0.1:4096"
|
||||
visible: shell.isOpenCode
|
||||
onEdited: value => shell.cfg.ai.opencode_server = value
|
||||
}
|
||||
PhoebusField {
|
||||
id: opencodePasswordField
|
||||
label: "Server password (if set)"
|
||||
placeholder: "OPENCODE_SERVER_PASSWORD"
|
||||
secret: true
|
||||
visible: shell.isOpenCode
|
||||
onEdited: value => shell.opencodePassword = value
|
||||
}
|
||||
PhoebusField {
|
||||
id: opencodeProviderField
|
||||
label: "Provider"
|
||||
placeholder: "deepseek"
|
||||
visible: shell.isOpenCode
|
||||
onEdited: value => shell.cfg.ai.opencode_provider = value
|
||||
}
|
||||
PhoebusField {
|
||||
id: opencodeModelField
|
||||
label: "Model"
|
||||
placeholder: "deepseek-chat"
|
||||
visible: shell.isOpenCode
|
||||
onEdited: value => shell.cfg.ai.opencode_model = value
|
||||
}
|
||||
Row {
|
||||
spacing: 12
|
||||
PhoebusButton {
|
||||
label: shell.aiTesting ? "Testing…" : "Test connection"
|
||||
actionEnabled: !shell.aiTesting && !shell.aiChecking
|
||||
onClicked: shell.testAi()
|
||||
}
|
||||
PhoebusButton {
|
||||
label: shell.aiChecking ? "Checking…" : "Connect and validate"
|
||||
primary: true
|
||||
actionEnabled: !shell.aiChecking
|
||||
actionEnabled: !shell.aiChecking && !shell.aiTesting
|
||||
onClicked: shell.connectAi()
|
||||
}
|
||||
PhoebusChip {
|
||||
visible: shell.aiConnected
|
||||
text: "Connected"
|
||||
text: "Validated"
|
||||
tone: Theme.success
|
||||
}
|
||||
PhoebusChip {
|
||||
visible: shell.aiTested && !shell.aiConnected
|
||||
text: "Model responded"
|
||||
tone: Theme.success
|
||||
}
|
||||
}
|
||||
|
|
@ -761,6 +890,15 @@ ShellRoot {
|
|||
font.pixelSize: Theme.fontSmall
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
Text {
|
||||
width: parent.width
|
||||
visible: shell.aiTestMessage.length > 0 && shell.aiError.length === 0
|
||||
text: shell.aiTestMessage
|
||||
color: shell.aiTested ? Theme.success : Theme.danger
|
||||
font.family: Theme.family
|
||||
font.pixelSize: Theme.fontSmall
|
||||
wrapMode: Text.WordWrap
|
||||
}
|
||||
}
|
||||
PhoebusCard {
|
||||
width: parent.width
|
||||
|
|
|
|||
|
|
@ -59,6 +59,15 @@ BOOT_TIMEOUT = int(os.environ.get("BOOT_TIMEOUT", "900"))
|
|||
INSTALL_TIMEOUT = int(os.environ.get("INSTALL_TIMEOUT", "10800"))
|
||||
SESSION_SETTLE = int(os.environ.get("SESSION_SETTLE", "20"))
|
||||
BACKEND_SETTLE = int(os.environ.get("BACKEND_SETTLE", "30"))
|
||||
# OpenCode GUI-driving knobs (test-only). Tab counts assume the focus order:
|
||||
# Close, DeepSeek, OpenAI, Local, OpenCode, server, password, provider, model,
|
||||
# Test, Connect, Back, Next.
|
||||
OC_PORT = int(os.environ.get("OC_PORT", "4096"))
|
||||
OC_TARGET_PORT = int(os.environ.get("OC_TARGET_PORT", "41999"))
|
||||
OC_TAB_TO_CHIP = int(os.environ.get("OC_TAB_TO_CHIP", "5"))
|
||||
OC_PROVIDER = os.environ.get("OC_PROVIDER", "deepseek")
|
||||
OC_MODEL = os.environ.get("OC_MODEL", "deepseek-v4-flash")
|
||||
OC_USE_PASSWORD = os.environ.get("OC_USE_PASSWORD", "0") in ("1", "yes", "true")
|
||||
|
||||
|
||||
def _template_dir() -> Path:
|
||||
|
|
@ -293,6 +302,8 @@ class Driver:
|
|||
try:
|
||||
if self.mode == "gui":
|
||||
self.do_gui()
|
||||
elif self.mode == "opencode":
|
||||
self.do_opencode()
|
||||
elif self.mode == "install":
|
||||
self.do_install()
|
||||
elif self.mode == "boot":
|
||||
|
|
@ -474,8 +485,10 @@ class Driver:
|
|||
label="duplicate-launch",
|
||||
)
|
||||
n1, n2 = int(self.last_group(1)), int(self.last_group(2))
|
||||
# Exactly one session before and after: two pre-existing sessions must
|
||||
# not pass as "no duplicate".
|
||||
self.results.assert_true(
|
||||
"duplicate-sessions-prevented", n1 == n2 and n1 >= 1,
|
||||
"exactly-one-installer-session", n1 == 1 and n2 == 1,
|
||||
f"n1={n1} n2={n2}",
|
||||
)
|
||||
|
||||
|
|
@ -501,8 +514,226 @@ class Driver:
|
|||
"ai-step-blocks-install", blocked,
|
||||
"the AI step allowed advancement without a connected model",
|
||||
)
|
||||
# Behavioral evidence from the frontend's own state lines: the wizard is
|
||||
# still on the AI step (index 2) and has not reported a connection, and
|
||||
# it shows an inline error. A surviving process or a screenshot would
|
||||
# not prove any of this.
|
||||
state = self._frontend_state()
|
||||
if state is None:
|
||||
self.results.fail("ai-page-remains", "no frontend state line found")
|
||||
else:
|
||||
self.results.assert_true(
|
||||
"ai-page-remains", state["step"] == 2 and not state["aiConnected"],
|
||||
f"last state: {state}",
|
||||
)
|
||||
self.results.assert_true(
|
||||
"ai-error-shown", bool(state["aiError"]),
|
||||
f"the AI step showed no inline error: {state}",
|
||||
)
|
||||
self.results.pass_("gui-walk-completed")
|
||||
|
||||
def _frontend_state(self) -> dict | None:
|
||||
"""Read the frontend's last secret-free state line.
|
||||
|
||||
The pattern is built from a variable so the shell echo of the command
|
||||
cannot be mistaken for a real state line.
|
||||
"""
|
||||
assert self.child is not None
|
||||
self.child.sendline(
|
||||
'P=phoebus-; grep -ah "${P}state " '
|
||||
"/run/user/1000/quickshell/by-id/*/log.qslog 2>/dev/null | tail -1; "
|
||||
"echo STATE-$(printf END)"
|
||||
)
|
||||
try:
|
||||
self.child.expect("STATE-END", timeout=30)
|
||||
except (pexpect.TIMEOUT, pexpect.EOF):
|
||||
return None
|
||||
step = ai = tested = None
|
||||
applied = 0
|
||||
err = ""
|
||||
for line in (self.child.before or "").splitlines():
|
||||
if "phoebus-state" not in line:
|
||||
continue
|
||||
match = re.search(r"step=(\d+)", line)
|
||||
if match:
|
||||
step = int(match.group(1))
|
||||
match = re.search(r"aiConnected=(true|false)", line)
|
||||
if match:
|
||||
ai = match.group(1) == "true"
|
||||
match = re.search(r"aiTested=(true|false)", line)
|
||||
if match:
|
||||
tested = match.group(1) == "true"
|
||||
match = re.search(r"aiApplied=(\d+)", line)
|
||||
if match:
|
||||
applied = int(match.group(1))
|
||||
match = re.search(r"aiError=(.*?) aiTest=", line)
|
||||
if match:
|
||||
err = match.group(1).strip()
|
||||
if step is None:
|
||||
return None
|
||||
return {
|
||||
"step": step,
|
||||
"aiConnected": bool(ai),
|
||||
"aiTested": bool(tested),
|
||||
"aiApplied": applied,
|
||||
"aiError": err,
|
||||
}
|
||||
|
||||
def wait_state(self, predicate, timeout: int):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
state = self._frontend_state()
|
||||
if state is not None and predicate(state):
|
||||
return state
|
||||
time.sleep(2)
|
||||
return None
|
||||
|
||||
def do_opencode(self) -> None:
|
||||
"""Drive the OpenCode AI step through the real graphical UI.
|
||||
|
||||
The model is reached from the guest through a loopback relay (the same
|
||||
shape as an SSH tunnel), so the connection satisfies the transport
|
||||
policy while staying host-local or host+LAN only.
|
||||
"""
|
||||
self.spawn(attach_iso=True, boot_disk=False)
|
||||
self.login_live()
|
||||
welcome = self.poll_shell(
|
||||
"echo WELCOME=$(pgrep -fc 'quickshell.*phoebus-welcome' 2>/dev/null || echo 0)",
|
||||
r"WELCOME=([1-9][0-9]*)", timeout=int(os.environ.get("WELCOME_TIMEOUT", "180")),
|
||||
label="welcome-window",
|
||||
)
|
||||
self.results.assert_true("welcome-autostarted", welcome is not None, "welcome did not appear")
|
||||
self.set_wayland()
|
||||
|
||||
# Start the guest-local relay to the host OpenCode server.
|
||||
self.shell(
|
||||
f"curl -fsSL {SERVE_URL}/oc-forward.py -o /tmp/oc-forward.py && "
|
||||
f"chmod 755 /tmp/oc-forward.py && "
|
||||
f"setsid python3 /tmp/oc-forward.py {OC_PORT} 10.0.2.2 {OC_TARGET_PORT} "
|
||||
f">/tmp/oc-forward.log 2>&1 < /dev/null & echo FWD-$(printf START)",
|
||||
"FWD-START", timeout=60, label="forwarder-start",
|
||||
)
|
||||
ready = self.poll_shell(
|
||||
f"curl -s -m 5 -o /dev/null -w 'HEALTH=%{{http_code}}' "
|
||||
f"http://127.0.0.1:{OC_PORT}/global/health",
|
||||
r"HEALTH=(200|401)", timeout=60, label="forwarder-ready",
|
||||
)
|
||||
self.results.assert_true(
|
||||
"opencode-reachable-from-guest", ready is not None,
|
||||
"the guest relay could not reach the OpenCode server",
|
||||
)
|
||||
|
||||
self.sendkey("ret")
|
||||
opened = self.poll_shell(
|
||||
"echo INST=$(pgrep -fc 'quickshell.*phoebus-install' 2>/dev/null || echo 0)",
|
||||
r"INST=([1-9][0-9]*)", timeout=int(os.environ.get("INSTALLER_OPEN_TIMEOUT", "90")),
|
||||
label="launcher-opens-installer", record=False,
|
||||
)
|
||||
if opened is None:
|
||||
self.results.fail("launcher-opens-installer", "Return did not open the installer")
|
||||
return
|
||||
self.results.pass_("launcher-opens-installer", "welcome action opened the installer")
|
||||
time.sleep(BACKEND_SETTLE)
|
||||
self.shell(
|
||||
"pkill -f 'quickshell.*phoebus-wel[c]ome' || true; sleep 2; echo CLOSED",
|
||||
"CLOSED", timeout=30, label="close-welcome",
|
||||
)
|
||||
|
||||
# Navigate to the AI step (0 -> 1 -> 2).
|
||||
self.sendkey("ctrl-right")
|
||||
time.sleep(2)
|
||||
self.sendkey("ctrl-right")
|
||||
time.sleep(2)
|
||||
state = self._frontend_state()
|
||||
self.results.assert_true(
|
||||
"ai-step-reached", state is not None and state["step"] == 2,
|
||||
f"frontend state: {state}",
|
||||
)
|
||||
self.shot("oc-01-ai", "AI step", "Ctrl+Right twice", "the AI model step is shown")
|
||||
|
||||
# Select the "OpenCode agent" chip with the keyboard.
|
||||
for _ in range(OC_TAB_TO_CHIP):
|
||||
self.sendkey("tab")
|
||||
time.sleep(0.3)
|
||||
self.sendkey("ret")
|
||||
time.sleep(1)
|
||||
self.shot("oc-02-selected", "OpenCode selected", "Tab to the chip and Return",
|
||||
"server, password, provider and model fields appear")
|
||||
|
||||
# Enter the connection through the UI. Focus is on the chip after
|
||||
# selection; Tab order is server, password, provider, model, Test,
|
||||
# Connect. Ctrl+A selects the existing default before typing.
|
||||
def type_field(tabs: int, value: str, secret_file: str | None = None) -> None:
|
||||
# `wtype` (Wayland) and QEMU `sendkey` (hardware) are two input
|
||||
# paths; settle between them or the next key can truncate the text.
|
||||
for _ in range(tabs):
|
||||
self.sendkey("tab")
|
||||
time.sleep(0.4)
|
||||
self.sendkey("ctrl-a")
|
||||
time.sleep(0.5)
|
||||
if secret_file:
|
||||
# The serial echo carries `$(cat ...)`, never the value.
|
||||
self.shell(
|
||||
f'wtype "$(cat {secret_file})" >/dev/null 2>&1; echo TYPED',
|
||||
"TYPED", timeout=30, label="type-secret",
|
||||
)
|
||||
else:
|
||||
self.shell(
|
||||
f"wtype '{value}' >/dev/null 2>&1; echo TYPED",
|
||||
"TYPED", timeout=30, label="type-field",
|
||||
)
|
||||
time.sleep(1.4)
|
||||
# Clear the selection highlight so a screenshot shows the value.
|
||||
self.sendkey("end")
|
||||
time.sleep(0.3)
|
||||
|
||||
type_field(1, f"http://127.0.0.1:{OC_PORT}")
|
||||
if OC_USE_PASSWORD:
|
||||
self.shell(
|
||||
f"curl -fsSL {SERVE_URL}/oc.pw -o /tmp/oc.pw && chmod 600 /tmp/oc.pw "
|
||||
"&& echo PW-$(printf LOADED)",
|
||||
"PW-LOADED", timeout=30, label="fetch-password",
|
||||
)
|
||||
type_field(1, "", secret_file="/tmp/oc.pw")
|
||||
else:
|
||||
self.sendkey("tab") # skip the empty password field
|
||||
time.sleep(0.25)
|
||||
type_field(1, OC_PROVIDER)
|
||||
type_field(1, OC_MODEL)
|
||||
self.shot("oc-02b-fields", "OpenCode fields", "typed server/provider/model",
|
||||
"the fields hold the entered values")
|
||||
self.sendkey("tab") # model -> Test
|
||||
time.sleep(0.3)
|
||||
self.sendkey("ret")
|
||||
time.sleep(3)
|
||||
self.shot("oc-03-test", "Test connection", "Return on Test connection",
|
||||
"a real model response is obtained and validated")
|
||||
tested = self.wait_state(lambda s: s["aiTested"], timeout=180)
|
||||
self.results.assert_true(
|
||||
"opencode-test-connection", tested is not None,
|
||||
"Test connection did not obtain a valid model response",
|
||||
)
|
||||
|
||||
# The next focus is the "Connect and validate" button.
|
||||
self.sendkey("tab")
|
||||
time.sleep(0.3)
|
||||
self.sendkey("ret")
|
||||
self.shot("oc-04-connect", "Connect and validate", "Return on Connect and validate",
|
||||
"a validated proposal is applied; Next is enabled")
|
||||
connected = self.wait_state(lambda s: s["aiConnected"], timeout=240)
|
||||
self.results.assert_true(
|
||||
"opencode-validated-proposal",
|
||||
connected is not None,
|
||||
f"Connect and validate did not validate a proposal: {connected}",
|
||||
)
|
||||
if connected is not None:
|
||||
# A validated proposal may legitimately contain zero changes.
|
||||
self.results.pass_(
|
||||
"opencode-proposal-applied",
|
||||
f"applied={connected['aiApplied']} change(s)",
|
||||
)
|
||||
self.results.pass_("opencode-gui-completed")
|
||||
|
||||
def _installer_alive(self) -> bool:
|
||||
assert self.child is not None
|
||||
self.child.sendline(
|
||||
|
|
@ -631,7 +862,7 @@ class Driver:
|
|||
|
||||
def main() -> int:
|
||||
mode = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
if mode not in ("gui", "install", "boot"):
|
||||
if mode not in ("gui", "opencode", "install", "boot"):
|
||||
print(__doc__)
|
||||
return 2
|
||||
if mode in ("install", "boot") and not DISKS:
|
||||
|
|
|
|||
71
installer/tests/vm/oc-forward.py
Normal file
71
installer/tests/vm/oc-forward.py
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
#!/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