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:
@@ -33,6 +33,10 @@ type chatBroker interface {
|
||||
Sessions(ctx context.Context) ([]protocol.ChatSession, error)
|
||||
// Create creates one OpenCode session in the given directory and returns it.
|
||||
Create(ctx context.Context, title, directory string) (protocol.ChatSession, error)
|
||||
// Session returns the endpoint's own record of one existing session so an
|
||||
// adopted session carries the endpoint's directory and title; found is false
|
||||
// when the endpoint does not list sessionID.
|
||||
Session(ctx context.Context, sessionID string) (protocol.ChatSession, bool, error)
|
||||
// Permissions lists the session's pending OpenCode approval requests so the
|
||||
// handler can push chat_permission frames.
|
||||
Permissions(ctx context.Context, sessionID string) ([]protocol.ChatPermissionFrame, error)
|
||||
@@ -474,6 +478,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
|
||||
case protocol.ChatCreate:
|
||||
handleChatCreate(ctx, request, broker, registry, write)
|
||||
return true
|
||||
case protocol.ChatAdopt:
|
||||
handleChatAdopt(ctx, request, broker, registry, write)
|
||||
return true
|
||||
case protocol.ChatDirectories:
|
||||
handleChatDirectories(ctx, request, registry, write)
|
||||
return true
|
||||
@@ -591,6 +598,59 @@ func handleChatCreate(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(response)
|
||||
}
|
||||
|
||||
// handleChatAdopt records a session that already exists on the endpoint in the
|
||||
// operator registry, using the endpoint's own directory and title verbatim, so
|
||||
// it appears in chat_sessions and can be continued. It refuses a nil broker, a
|
||||
// nil registry, a nil payload and an invalid/blank id before any broker call; an
|
||||
// id the endpoint does not report is an error naming the id and records nothing;
|
||||
// an endpoint record with an empty directory is refused rather than substituting
|
||||
// the server's working directory or the operator home. The response echoes the
|
||||
// adopted session and its registry row like chat_create.
|
||||
func handleChatAdopt(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, write func(protocol.Message) error) {
|
||||
if broker == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat is not configured on this server"})
|
||||
return
|
||||
}
|
||||
if registry == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"})
|
||||
return
|
||||
}
|
||||
if request.ChatAdopt == nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a chat_adopt session id is required"})
|
||||
return
|
||||
}
|
||||
id := strings.TrimSpace(request.ChatAdopt.SessionID)
|
||||
if !opencode.ValidSessionID(id) {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid OpenCode session id is required"})
|
||||
return
|
||||
}
|
||||
session, found, err := broker.Session(ctx, id)
|
||||
if err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()})
|
||||
return
|
||||
}
|
||||
if !found {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " was not found on the OpenCode endpoint"})
|
||||
return
|
||||
}
|
||||
directory := strings.TrimSpace(session.Directory)
|
||||
if directory == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + id + " has no directory on the OpenCode endpoint"})
|
||||
return
|
||||
}
|
||||
if err := registry.RecordOperatorSession(ctx, session.ID, directory, session.Title, protocol.ChatSessionTagOperator); err != nil {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "session " + session.ID + " was found but could not be recorded: " + err.Error()})
|
||||
return
|
||||
}
|
||||
session.Directory = directory
|
||||
session.Tag = protocol.ChatSessionTagOperator
|
||||
response := protocol.Message{Type: protocol.ChatAdopt, ID: request.ID, ChatSession: &session}
|
||||
// The same registry row is echoed on the list field so a client can splice it
|
||||
// into chat_sessions without a re-list.
|
||||
response.ChatSessions = []protocol.ChatSession{session}
|
||||
_ = write(response)
|
||||
}
|
||||
|
||||
// handleChatDirectories answers chat_directories with the operator's home first,
|
||||
// then the directories of previous operator sessions most-recently-used first,
|
||||
// deduplicated against the home directory and capped at operatorDirectoryLimit.
|
||||
|
||||
@@ -71,6 +71,11 @@ type fakeChat struct {
|
||||
createDirectory string
|
||||
created protocol.ChatSession
|
||||
createErr error
|
||||
sessionByIDCalls int
|
||||
sessionByID string
|
||||
sessionRecord protocol.ChatSession
|
||||
sessionFound bool
|
||||
sessionByIDErr error
|
||||
}
|
||||
|
||||
func (f *fakeChat) Prompt(context.Context, string, string) error {
|
||||
@@ -214,6 +219,34 @@ func (f *fakeChat) createQuery() (int, string, string) {
|
||||
return f.createCalls, f.createTitle, f.createDirectory
|
||||
}
|
||||
|
||||
// Session returns the seeded endpoint record of one session (or "not found")
|
||||
// and counts each call, so the adopt handler can be asserted to read the
|
||||
// endpoint exactly once and never invent a directory.
|
||||
func (f *fakeChat) Session(_ context.Context, sessionID string) (protocol.ChatSession, bool, error) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.sessionByIDCalls++
|
||||
f.sessionByID = sessionID
|
||||
if f.sessionByIDErr != nil {
|
||||
return protocol.ChatSession{}, false, f.sessionByIDErr
|
||||
}
|
||||
if !f.sessionFound {
|
||||
return protocol.ChatSession{}, false, nil
|
||||
}
|
||||
session := f.sessionRecord
|
||||
if session.ID == "" {
|
||||
session.ID = sessionID
|
||||
}
|
||||
return session, true, nil
|
||||
}
|
||||
|
||||
// sessionByIDQuery reports the recorded chat_adopt read count and last id.
|
||||
func (f *fakeChat) sessionByIDQuery() (int, string) {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
return f.sessionByIDCalls, f.sessionByID
|
||||
}
|
||||
|
||||
// replyQuery reports the recorded chat_reply count and the last forwarded
|
||||
// request, so a test can assert the exact session/request/decision.
|
||||
func (f *fakeChat) replyQuery() (int, protocol.ChatReplyRequest) {
|
||||
@@ -1676,3 +1709,170 @@ func TestChatPermissionWriteFailureDoesNotDropRequest(t *testing.T) {
|
||||
t.Fatalf("push attempts = %d, want the request re-pushed after the failure", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatAdoptRecordsEndpointSession is the chat_adopt acceptance test: the
|
||||
// endpoint's own record supplies the directory and title, the handler records
|
||||
// the row with the operator tag, and the response echoes the session and its
|
||||
// registry row so the client can splice it into chat_sessions without a re-list.
|
||||
func TestChatAdoptRecordsEndpointSession(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newOperatorStore(t)
|
||||
broker := scriptedChat()
|
||||
broker.sessionFound = true
|
||||
broker.sessionRecord = protocol.ChatSession{ID: "ses_existing", Title: "my own work", Directory: "/work/existing"}
|
||||
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_existing"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.ChatAdopt || response.ID != "a1" || response.ChatSession == nil {
|
||||
t.Fatalf("chat_adopt response = %+v", response)
|
||||
}
|
||||
if response.ChatSession.ID != "ses_existing" || response.ChatSession.Directory != "/work/existing" || response.ChatSession.Tag != protocol.ChatSessionTagOperator {
|
||||
t.Fatalf("adopted session = %+v", response.ChatSession)
|
||||
}
|
||||
if len(response.ChatSessions) != 1 || response.ChatSessions[0].ID != "ses_existing" || response.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
|
||||
t.Fatalf("adopted session not echoed as a registry row: %+v", response.ChatSessions)
|
||||
}
|
||||
if calls, id := broker.sessionByIDQuery(); calls != 1 || id != "ses_existing" {
|
||||
t.Fatalf("broker.Session = %d/%q, want 1/ses_existing", calls, id)
|
||||
}
|
||||
recorded, err := store.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(recorded) != 1 || recorded[0].ID != "ses_existing" || recorded[0].Directory != "/work/existing" || recorded[0].Title != "my own work" || recorded[0].Tag != protocol.ChatSessionTagOperator {
|
||||
t.Fatalf("registry row = %+v", recorded)
|
||||
}
|
||||
// chat_sessions now lists the adopted session (the endpoint still reports it),
|
||||
// carrying the registry directory and operator tag.
|
||||
broker.mu.Lock()
|
||||
broker.sessions = []protocol.ChatSession{{ID: "ses_existing", Title: "endpoint title", Directory: "/endpoint/elsewhere"}}
|
||||
broker.mu.Unlock()
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatSessions, ID: "s1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var listed protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &listed); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if listed.Type != protocol.ChatSessions || len(listed.ChatSessions) != 1 || listed.ChatSessions[0].ID != "ses_existing" || listed.ChatSessions[0].Directory != "/work/existing" || listed.ChatSessions[0].Tag != protocol.ChatSessionTagOperator {
|
||||
t.Fatalf("chat_sessions did not list the adopted session with its registry directory: %+v", listed.ChatSessions)
|
||||
}
|
||||
// chat_prompt can continue the adopted session: TouchOperatorSession updates
|
||||
// the recorded row, so it moves to the front of the list.
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatPrompt, ID: "p1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_existing", Text: "continue"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ack protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ack.Type != protocol.ChatPrompt || ack.ID != "p1" {
|
||||
t.Fatalf("adopted session prompt ack = %+v", ack)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatAdoptMissingIDRecordsNothing pins that an id the endpoint does not
|
||||
// report is refused naming the id and leaves the registry unchanged.
|
||||
func TestChatAdoptMissingIDRecordsNothing(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newOperatorStore(t)
|
||||
// Seed one unrelated operator row so the "unchanged" claim compares the
|
||||
// stored rows before and after, not merely an empty registry.
|
||||
if err := store.RecordOperatorSession(ctx, "ses_other", "/work/other", "other", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := store.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broker := scriptedChat()
|
||||
broker.sessionFound = false
|
||||
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_missing"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.Error || !strings.Contains(response.Error, "ses_missing") {
|
||||
t.Fatalf("missing id not refused naming the id: %+v", response)
|
||||
}
|
||||
after, err := store.OperatorSessions(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(before) != 1 || len(after) != 1 || after[0].ID != before[0].ID {
|
||||
t.Fatalf("missing id changed the registry: before %+v after %+v", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatAdoptRefusesEmptyDirectory pins the no-guessing rule: an endpoint
|
||||
// record with an empty directory is refused and records nothing, never falling
|
||||
// back to the server's working directory or the operator home.
|
||||
func TestChatAdoptRefusesEmptyDirectory(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newOperatorStore(t)
|
||||
broker := scriptedChat()
|
||||
broker.sessionFound = true
|
||||
broker.sessionRecord = protocol.ChatSession{ID: "ses_nodir"}
|
||||
_, _, conn := dialChatOptions(t, Options{Chat: broker, OperatorRegistry: store})
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_nodir"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.Error || !strings.Contains(response.Error, "directory") {
|
||||
t.Fatalf("empty directory not refused: %+v", response)
|
||||
}
|
||||
if recorded, err := store.OperatorSessions(ctx); err != nil || len(recorded) != 0 {
|
||||
t.Fatalf("empty directory recorded a session: %+v %v", recorded, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatAdoptRejectsInvalidInputBeforeBroker pins that a nil payload, a blank
|
||||
// or foreign-shaped id, a nil registry and a nil broker are each refused before
|
||||
// any endpoint call.
|
||||
func TestChatAdoptRejectsInvalidInputBeforeBroker(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
cases := []struct {
|
||||
name string
|
||||
request protocol.Message
|
||||
options Options
|
||||
wantCall int
|
||||
}{
|
||||
{name: "nil payload", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1"}, options: Options{Chat: scriptedChat(), OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
||||
{name: "blank id", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: " "}}, options: Options{Chat: scriptedChat(), OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
||||
{name: "foreign id", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "not-a-session"}}, options: Options{Chat: scriptedChat(), OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
||||
{name: "nil broker", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_1"}}, options: Options{OperatorRegistry: newOperatorStore(t)}, wantCall: 0},
|
||||
{name: "nil registry", request: protocol.Message{Type: protocol.ChatAdopt, ID: "a1", ChatAdopt: &protocol.ChatAdoptRequest{SessionID: "ses_1"}}, options: Options{Chat: scriptedChat()}, wantCall: 0},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
broker, _ := tc.options.Chat.(*fakeChat)
|
||||
_, _, conn := dialChatOptions(t, tc.options)
|
||||
if err := wsjson.Write(ctx, conn, protocol.Message(tc.request)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response protocol.Message
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.Error {
|
||||
t.Fatalf("%s not refused: %+v", tc.name, response)
|
||||
}
|
||||
if broker != nil {
|
||||
if calls, _ := broker.sessionByIDQuery(); calls != tc.wantCall {
|
||||
t.Fatalf("%s reached the endpoint %d times, want %d", tc.name, calls, tc.wantCall)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user