Keep OpenCode/Codex chat and stage sessions running across server restarts

A stopping server no longer interrupts harness sessions. Runs are canceled
with a shutdown cause, so stage clients leave admitted sessions running and
owned; start-up recovery re-adopts live OpenCode V2 stage sessions (wait,
read back the result, continue the graph), restarts unadmitted visits,
continues runs between stages, and falls back to interrupted with a reason
when the harness is gone. Chats with live work are recorded on shutdown and
reattached on start; turns that ended during the downtime are folded in
from history. The server-spawned V2 chat serve is now a detached owned
service. PIPELINES_SHUTDOWN_SESSIONS=stop restores the old behaviour.
This commit is contained in:
2026-11-04 16:17:08 +00:00
parent 9351cd7d74
commit aa8eddd686
26 changed files with 2318 additions and 99 deletions
+63 -19
View File
@@ -27,6 +27,23 @@ type AgentClient struct {
WorkStarted bool
}
// resumeConnection reopens the retained execution service a previous server
// process recorded for a session, refusing a different backend or directory.
func resumeConnection(reference, backend, directory string) (*opencode.Connection, error) {
if reference == "" {
return nil, fmt.Errorf("retained OpenCode session has no execution-service reference")
}
connection, err := opencode.FromReference(reference)
if err != nil {
return nil, err
}
if (backend != "" && connection.Backend != backend) || connection.Directory != directory {
connection.Close()
return nil, fmt.Errorf("retained OpenCode execution context mismatch")
}
return connection, nil
}
func (c OpenCodeClient) Interrupt(ctx context.Context, id string) error {
return c.interrupt(ctx, id, false)
}
@@ -80,7 +97,18 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
if c.Operations != nil {
c.Operations.Provider, c.Operations.Model = config.Provider, config.Model
}
if c.command == nil {
// A re-adopted session was admitted by a previous server process: attach
// to its retained service and wait for it; never create or prompt again.
resume := TakeResumeSession(ctx)
if resume != "" && c.command == nil {
connection, err := resumeConnection(c.Reference, c.Backend, c.Directory)
if err != nil {
return "", err
}
defer connection.Close()
c.connection = connection
c.Backend = connection.Backend
} else if c.command == nil {
connection, err := opencode.OpenStage(ctx, opencode.Executable(), c.Directory, c.Backend)
if err != nil {
// Connecting to the service failed before any session existed.
@@ -101,24 +129,31 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
if err != nil {
return "", err
}
data, err := c.call(ctx, "post", "/api/session", map[string]any{"title": "Pipeline audited agent stage", "agent": "build", "location": map[string]string{"directory": c.Directory}, "model": model, "permissions": rules})
if err != nil {
if variant := model["variant"]; variant != "" {
err = fmt.Errorf("OpenCode model selection for reasoning_effort=%s (variant %q) failed: %w", variant, variant, err)
if resume != "" {
if c.Backend != "v2" || !sessionIDPattern.MatchString(resume) {
return "", fmt.Errorf("retained OpenCode session %.128s cannot be re-adopted on backend %q", RedactEvidence(resume), c.Backend)
}
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
c.SessionID = resume
} else {
data, err := c.call(ctx, "post", "/api/session", map[string]any{"title": "Pipeline audited agent stage", "agent": "build", "location": map[string]string{"directory": c.Directory}, "model": model, "permissions": rules})
if err != nil {
if variant := model["variant"]; variant != "" {
err = fmt.Errorf("OpenCode model selection for reasoning_effort=%s (variant %q) failed: %w", variant, variant, err)
}
// No prompt or tool call was admitted: a request failure here is a
// reachable retry rather than a reason to end the run.
return "", harnessUnreachable(err)
}
var created struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if json.Unmarshal(data, &created) != nil || !sessionIDPattern.MatchString(created.Data.ID) {
return "", fmt.Errorf("invalid agent session")
}
c.SessionID = created.Data.ID
}
var created struct {
Data struct {
ID string `json:"id"`
} `json:"data"`
}
if json.Unmarshal(data, &created) != nil || !sessionIDPattern.MatchString(created.Data.ID) {
return "", fmt.Errorf("invalid agent session")
}
c.SessionID = created.Data.ID
if c.connection != nil && c.Backend == "v1" {
c.Reference, err = c.connection.Reference()
if err != nil {
@@ -134,6 +169,12 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
defer func() {
watch.stopWatch(ctx, &err)
defer watch.finish(ctx, &err)
if err != nil && Detached(ctx) {
// The server is restarting: leave the admitted session running and
// its ownership recorded, so the next process re-adopts it.
err = fmt.Errorf("%w: retained OpenCode session %s left running", ErrDetached, c.SessionID)
return
}
cleanup, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second)
defer cancel()
if err != nil {
@@ -181,8 +222,10 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
return "", err
}
c.WorkStarted = true
if _, err = c.call(ctx, "post", "/api/session/"+c.SessionID+"/prompt", generationBody("text", prompt, config, c.Backend)); err != nil {
return "", err
if resume == "" {
if _, err = c.call(ctx, "post", "/api/session/"+c.SessionID+"/prompt", generationBody("text", prompt, config, c.Backend)); err != nil {
return "", err
}
}
if c.Backend == "v1" {
// Native V1 prompts block until completion; keep the existing settlement
@@ -193,6 +236,7 @@ func (c *AgentClient) Generate(ctx context.Context, config ModelConfig, prompt s
} else if err = c.waitForSessionIdle(ctx, c.SessionID); err != nil {
return "", err
}
var data []byte
data, text, err = c.readFinalAgentResult(ctx, c.SessionID)
if len(data) > 0 {
c.Transcript = string(data)