package codex import ( "context" "encoding/json" "errors" "log" "maps" "git.a-wan.net/alan/pipelines/internal/chattools" ) // withPipelinesTools returns params with the thread config override that // registers the Pipelines MCP server at url, leaving params unchanged. func withPipelinesTools(params map[string]any, url string) map[string]any { next := maps.Clone(params) next["config"] = chattools.CodexConfig(url) return next } // startThread calls thread/start registering the Pipelines tools for the new // thread. Its id is assigned by the App Server, so the endpoint is issued // pending and bound to the id the reply names. An App Server that refuses the // override still gets the thread, started without the tools (logged). func (c *Chat) startThread(ctx context.Context, params map[string]any) (json.RawMessage, error) { registry := chattools.Current() if registry == nil { return c.call(ctx, "thread/start", params) } url, bind, err := registry.PendingURL() if err != nil { log.Printf("codex chat: Pipelines tools not registered: %v", err) return c.call(ctx, "thread/start", params) } raw, err := c.call(ctx, "thread/start", withPipelinesTools(params, url)) var refused *rpcCallError if errors.As(err, &refused) { log.Printf("codex chat: thread/start refused the Pipelines tools (%s); starting without them", refused.Message) return c.call(ctx, "thread/start", params) } if err != nil { return raw, err } var reply struct { Thread struct { ID string `json:"id"` } `json:"thread"` } if json.Unmarshal(raw, &reply) == nil && reply.Thread.ID != "" { if err := bind(reply.Thread.ID); err != nil { log.Printf("codex chat %s: Pipelines tools endpoint not bound: %v", reply.Thread.ID, err) } } return raw, nil } // resumeThread calls thread/resume for id, registering the thread's own // Pipelines tools endpoint; a refusal of the override resumes without it. func (c *Chat) resumeThread(ctx context.Context, params map[string]any, id string) (json.RawMessage, error) { registry := chattools.Current() if registry == nil { return c.call(ctx, "thread/resume", params) } url, err := registry.SessionURL(id) if err != nil { log.Printf("codex chat %s: Pipelines tools not registered: %v", id, err) return c.call(ctx, "thread/resume", params) } raw, err := c.call(ctx, "thread/resume", withPipelinesTools(params, url)) var refused *rpcCallError if errors.As(err, &refused) && refused.Message != "thread not found: "+id { log.Printf("codex chat %s: thread/resume refused the Pipelines tools (%s); resuming without them", id, refused.Message) return c.call(ctx, "thread/resume", params) } return raw, err }