Broker chat from an operator's own OpenCode endpoint and adopt existing sessions

Add an opt-in way to broker chat from an operator-supplied OpenCode service
instead of the instance the server spawns for itself, and a way to adopt a
session that already exists on that endpoint so it appears in chat_sessions and
can be continued from the app.

- Endpoint selection: the `-opencode-endpoint` server flag (defaulting to
  `PIPELINES_OPENCODE_ENDPOINT`) opts in; precedence is explicit flag >
  explicit environment > the endpoint recorded on a previous run, with the
  spawned instance as the default. opencode.OpenEndpoint validates the
  reference once (http(s), host, no userinfo/query/fragment/path), detects the
  backend from its own /api/info (v2) or /global/health (v1) contract, and
  requires a streamable text/event-stream event path. It owns no process
  (Close is a no-op) and never calls startServe; every failure names the
  endpoint and disables chat rather than silently falling back. An
  authenticated endpoint takes an optional password only through the private
  file PIPELINES_OPENCODE_ENDPOINT_PASSWORD_FILE, with
  PIPELINES_OPENCODE_ENDPOINT_USERNAME overriding the detected default.
- Persistence: the validated choice is recorded in an additive single-row
  server_settings table so a restart with no flag/environment reuses it; an
  unreachable recorded endpoint disables chat with a clear message and no
  fallback.
- chat_adopt: a new protocol request (ChatAdoptRequest) with handleChatAdopt in
  internal/server/chat.go. It refuses a nil broker/registry/payload and a
  blank or foreign-shaped id before any endpoint call, reads the endpoint via
  the shared Chat.Session (which reuses Sessions/decodeChatSessions), records
  through the existing RecordOperatorSession with the endpoint's directory and
  title verbatim, and echoes the adopted session plus its registry row like
  chat_create. A missing id is refused naming the id and records nothing; an
  endpoint record with an empty directory is refused rather than substituting
  the server's working directory or home.
- CLI: `pipelines chat-adopt <session-id> [--json]` (usage, notes, help
  inventory, dispatch) with docs/cli.md updated under Chat sessions.
- Autostart preserves the endpoint variables (and the password-file reference,
  never an inline secret) via serviceEnvironmentKeys.

Checks before committing:
- Package location: the change is user-facing chat behaviour, so the packaged
  authoring skill reference internal/author/skill/references/operations.md is
  updated in the same change (Brokered OpenCode chat section) with a dated
  verification-evidence entry and the not-deployed state. No new reference file
  is added, so internal/author/install.go's managed inventory is unchanged.
- Packaged templates: this repository packages no template set for this
  behaviour and none references the chat endpoint, so no template needs
  updating.
- Verification: `go build ./...`, `go vet` on the touched packages, `gofmt -l`
  clean and `go test ./...` all pass. The unit tests cover the endpoint
  validation/precedence, the adopt happy path and refusals, the recorded
  endpoint round-trip, the protocol round-trip and the CLI dispatch. The live
  scratch-server check against the operator's real endpoint was not run in this
  change.

Nothing unrelated is staged; docs left stale (README and other shared documents)
are not edited here and are for a single folding writer.
This commit is contained in:
2026-10-17 20:14:11 +01:00
parent 50af9dbc62
commit 1f75e4797e
20 changed files with 1027 additions and 33 deletions
+17
View File
@@ -955,6 +955,23 @@ func (a App) Run(ctx context.Context, args []string) error {
}
_, err = fmt.Fprintf(a.Out, "Renamed run #%d to %s\n", r.RunDetail.ID, r.RunDetail.Label())
return err
case "chat-adopt":
id, err := one()
if err != nil {
return err
}
r, err := call(protocol.Message{Type: protocol.ChatAdopt, ChatAdopt: &protocol.ChatAdoptRequest{SessionID: id}})
if err != nil {
return err
}
if o.json {
return a.output(r)
}
if r.ChatSession == nil {
return fmt.Errorf("server did not return the adopted session")
}
_, err = fmt.Fprintf(a.Out, "Adopted %s · %s\n", r.ChatSession.ID, r.ChatSession.Directory)
return err
case "rpc":
path, err := one()
if err != nil {
+58
View File
@@ -0,0 +1,58 @@
package cli
import (
"bytes"
"context"
"encoding/json"
"strings"
"sync/atomic"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/wstest"
)
// TestCLIChatAdoptSendsOneRequest pins the CLI parity for chat_adopt: exactly one
// chat_adopt request carrying the id travels over the shared protocol client,
// --json prints the response, and the human line is concise.
func TestCLIChatAdoptSendsOneRequest(t *testing.T) {
var calls int32
var got protocol.Message
session := protocol.ChatSession{ID: "ses_abc", Title: "mine", Directory: "/work/mine", Tag: protocol.ChatSessionTagOperator}
endpoint := wstest.Server(t, func(request protocol.Message) protocol.Message {
atomic.AddInt32(&calls, 1)
got = request
return protocol.Message{Type: protocol.ChatAdopt, ChatSession: &session, ChatSessions: []protocol.ChatSession{session}}
})
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
var out, errOut bytes.Buffer
app := App{Out: &out, Err: &errOut, In: strings.NewReader("")}
if err := app.Run(ctx, []string{"--url", endpoint, "chat-adopt", "ses_abc", "--json"}); err != nil {
t.Fatal(err)
}
if n := atomic.LoadInt32(&calls); n != 1 {
t.Fatalf("chat-adopt sent %d requests, want exactly one", n)
}
if got.Type != protocol.ChatAdopt || got.ChatAdopt == nil || got.ChatAdopt.SessionID != "ses_abc" {
t.Fatalf("wire request = %+v, want chat_adopt with the id", got)
}
var decoded protocol.Message
if err := json.Unmarshal(out.Bytes(), &decoded); err != nil {
t.Fatalf("stdout is not parseable JSON: %v\n%s", err, out.String())
}
if decoded.ChatSession == nil || decoded.ChatSession.ID != "ses_abc" {
t.Fatalf("stdout lost the adopted session: %+v", decoded.ChatSession)
}
var humanOut, humanErr bytes.Buffer
human := App{Out: &humanOut, Err: &humanErr, In: strings.NewReader("")}
if err := human.Run(ctx, []string{"--url", endpoint, "chat-adopt", "ses_abc"}); err != nil {
t.Fatal(err)
}
if !strings.Contains(humanOut.String(), "ses_abc") || !strings.Contains(humanOut.String(), "/work/mine") {
t.Fatalf("human line = %q, want the id and the endpoint directory", humanOut.String())
}
}
+2
View File
@@ -25,6 +25,7 @@ var usage = map[string]string{
"retry": "retry <run-id> [--json [--wait [--wait-timeout DURATION]]]",
"title": "title <run-id> \"<title>\" [--json]",
"debug": "debug <run-id> [--json | --no-open]",
"chat-adopt": "chat-adopt <session-id> [--json]",
"connection": "connection [--json]",
"ping": "ping [--json]",
"version": "version [--json]",
@@ -52,6 +53,7 @@ var notes = map[string]string{
"decide": "Choose an option for a run waiting on a human stage. The run must be `waiting`; the option must be one of that stage's non-error edges. The stage is inferred from the run's current stage unless named. The choice and optional --feedback are recorded as the step's evidence (visible in inspect and the TUI) and the run resumes along the chosen edge. An unknown option is refused with the valid list; a repeated decision for an already-decided visit does not double-apply. Works across a server restart because the wait is persisted.",
"debug": "Open a fresh configured harness conversation to investigate a run using inspect/show/runs CLI queries. --harness opencode|pi|nvim chooses another configured harness or read-only nvim packet. Does not resume implementation or retry. --json returns the prompt without launching anything.",
"rpc": "Accepts a JSON protocol envelope; '-' reads stdin. Every TUI server operation is available here too. Mutating commands are not dry runs. The omni-search command is `search` (fields query, optional kind and limit) and answers with ranked `search_results`.",
"chat-adopt": "Adopt a session that already exists on the configured OpenCode endpoint so it appears in chat_sessions and can be continued. The id must be one the endpoint reports; its directory and title are taken from the endpoint's own record (never guessed), and a missing id records nothing. Adopting is always explicit and does not change the server's endpoint choice.",
"retention": "Local, explicit run-history retention; never automatic and never a side effect of another command. `report` is strictly read-only and prints what a policy would remove; `apply` removes it after approval (--yes for scripted use). Policy: --older-than DURATION selects runs created before now minus that rolling UTC duration (Go durations plus d/w; not a calendar boundary), --keep N keeps the newest N runs by run id and selects older ranks (--keep 0 keeps none). Both together are the conservative intersection; at least one is required. Protected and never removed: queued/running runs, runs waiting on a person (waiting run or step), runs with an active cleanup agent, and any run referenced by a retained run's retry provenance (transitively). A run that becomes protected before deletion aborts the whole apply. Artifacts at <root>/<run> are removed with their run and kept with protected/retained runs; the database is VACUUMed and its WAL checkpointed, with measured reclaimed bytes. Definitions and versions are immutable and never touched. --db must name an existing database (default: the standard data directory); --artifacts defaults to artifacts/ beside --db. Works without a running server.",
"search": "One read-only query over pipelines, versions, runs, steps, field text and artifacts. QUERY is free text, a bare status word (queued, running, succeeded, failed, canceled, interrupted) selecting those runs, or a lone date expression (today, yesterday, this week [Monday 00:00 local], or YYYY-MM-DD) selecting the runs created in that window. --type is the only narrowing mechanism and takes one kind: pipeline, version, run, step, field or artifact; an unknown kind is an error. Ranking: an exact name match (3) beats a name substring (2) beats a body-text match (1); equal tiers break by recency, then a stable kind/target tie-break, and every hit reports score, matched_field and recency so a client can re-rank. Bounds: the result cap defaults to 50 and clamps to 200 (0 = default); every kind scans at most 2000 rows and field-text scanning is additionally capped at 2000 steps / 1 MiB; Truncated plus scanned_steps, scanned_bytes and scan_bound_bytes report when a bound applied. Targets are stable: pipeline:<id>, pipeline:<id>:v<version>, run:<id>, run:<id>:<sequence>, run:<id>:<sequence>:<field>, or an artifact URL.",
}
+1
View File
@@ -31,6 +31,7 @@ EXECUTE
retry <run-id> Restart a failed run with its original input and directory
title <run-id> "<title>" Rename a run after the fact; input/steps unchanged
debug <run-id> Investigate a run with a configured harness or nvim
chat-adopt <session-id> Adopt an existing OpenCode session into chat_sessions
draft-delete <draft.md> Delete a selected retained draft and its metadata
connection Server and public phone connection (no secrets)
status Server/ntfy health, ports and server computer IPs