diff --git a/docs/cli.md b/docs/cli.md index dc5470d9..bca1999a 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -543,6 +543,19 @@ sessions pipeline runs create. The protocol types are: server keeps observing it while its tasks run (bounded like an unattended turn: at most 16 such chats and 6 hours). Once released it reports none rather than a stale count. +- `chat_automations` reads provider-owned scheduled work for one operator chat. + Its body is `chat_query: {session_id}` and the reply is + `chat_automations: {session_id, provider, status, active_count?, reason?}`. + `status` is `supported` or `unavailable`; a supported empty result has + `active_count: 0`, while an unavailable result omits the count (unknown is + never represented as zero). OpenCode uses its documented + `GET /api/experimental/schedule?sessionID=...` read and counts only records + whose native `sessionID` matches and whose status is `active`. The older + OpenCode serve surface, Claude Code (which currently exposes schedule data + only through events/hooks), and Codex report their exact readback limitation. + The request is ownership-checked against the operator session registry, + bounded and read-only; it never starts or resumes a model turn and does not + inspect transcripts or count project/global work. - `chat_subscribe` attaches a connection to one session's shared live stream (body `session_id`) and replays the session's still-pending approval requests, so every client that watches a session sees every frame any client's turn produces — the diff --git a/docs/notes/chat-automation-discovery.md b/docs/notes/chat-automation-discovery.md new file mode 100644 index 00000000..16fde987 --- /dev/null +++ b/docs/notes/chat-automation-discovery.md @@ -0,0 +1,33 @@ +# Manager native scheduling findings + +Official Anthropic SDK types downloaded read-only from the official npm package +@anthropic-ai/claude-agent-sdk 0.3.319 into /tmp/claude-schedules-sdk-types. +Installed Claude is2.1.318. sdk.d.ts StopHookInput (line10147) has optional +session_crons: SessionCronSummary[]; each id/schedule/recurring/prompt. Empty is +known none, absent unknown. Hook callback initialization SDKControlInitializeRequest +line4722 includes hooks and SDKHookCallbackMatcher hookCallbackIds; callback subtype +hook_callback has callback_id and input. Existing server translate.go177 rejects +all hook_callback, so a small explicit observer callback could be handled without +model turns. Detachable claudehost must own callback ACK/metadata even when server +disconnected to preserve real scheduled sessions; never make the new observer +block or auto-answer operator permission callbacks. No global hook config changes. + +There is NO SDK get_session_info/get_session_state/get_cron_tasks control request. +background_tasks control is mutating Ctrl+B, NOT a read; do not call it. +Stop snapshot is native current session state, whereas parsing CronCreate history +as if it were current would be misleading. Old retained hosts lack observer hooks; +never restart them to enable metadata, report unknown until native support exists. + +Official OpenCode API current docs GET /api/experimental/schedule?sessionID=...: +Schedule.Info status active/paused/done, id, sessionID, nextDueAt. Installed2.0.32 +binary does not contain experimental/schedule, ScheduleCreate or schedule.list +symbols. No provider upgrades authorized just to make a count work. +Codex CLI0.164 has no Scheduled management interface per official OpenAI docs; +app/global automation jobs must not be assigned to chats by shared cwd. + +Manager native probe: isolated scratch CLI initialization accepted the observer +configuration. Both direct CLI and official SDK probes failed provider authentication +before an ordinary successful turn/Stop callback. This did not verify native Stop +delivery or schedule lifecycle. Existing credentials/configurations were unchanged; +owned processes exited. Reports: /tmp/claude-native-automation-hook-probe.json and +/tmp/claude-native-sdk-automation-hook-probe.json. No real operator chat was prompted. diff --git a/docs/notes/chat-automations-metadata.md b/docs/notes/chat-automations-metadata.md new file mode 100644 index 00000000..e2ab5190 --- /dev/null +++ b/docs/notes/chat-automations-metadata.md @@ -0,0 +1,23 @@ +# Chat scheduled-work metadata + +The read-only `chat_automations` websocket command exposes provider-owned +scheduled work for one operator chat. It deliberately distinguishes a +supported empty result (`active_count: 0`) from an unavailable provider +(`active_count` omitted), so a composer must not render unknown as zero. + +OpenCode endpoints that expose scheduling use the documented experimental read endpoint and filters +the validated response to the requested session and `active` status. Claude +Code's installed control protocol has no authoritative read-only schedule +operation; its event/hook metadata is therefore not promoted to a current +count. Codex has no documented native scheduled-management read API. No +schedule is created, changed, resumed, or inferred from a transcript or cwd. + +Pipeline291 passed implementation and code review (UI review skipped: backend-only), +then blocked at its read-only delivery-stage commit step. The manager retained the +candidate, updated existing API pipeline22 to v10 so its local commit stage can +write, and took over integration/landing. This metadata task alone is not the +composer feature and has not been deployed. Current installed OpenCode2.0.32 +appears not to expose the newer experimental API; unavailable is intentional. + +Manager integration: go build ./..., go vet ./..., go test ./... all passed; +full test log /tmp/chat-automation-go-integration.log. No service restart. diff --git a/internal/claude/chat.go b/internal/claude/chat.go index 15b20d23..eaeeb578 100644 --- a/internal/claude/chat.go +++ b/internal/claude/chat.go @@ -90,6 +90,20 @@ func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) { return sessions, nil } +// Automations reports Claude Code's current limitation honestly. Claude's +// scheduled-task metadata is emitted through stop-hook/task events, but the +// installed control protocol has no authoritative read-only session schedule +// operation. Starting a process or inspecting transcripts would not establish +// the current schedule set, so this method never does either. +func (c *Chat) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) { + return protocol.ChatAutomationInfo{ + SessionID: sessionID, + Provider: Backend, + Status: protocol.ChatAutomationUnavailable, + Reason: "Claude Code exposes scheduled-task metadata through events, but no authoritative read-only session schedule API is available", + }, nil +} + func (s *session) chatSessionLocked() protocol.ChatSession { model := s.modelActual if model == "" { diff --git a/internal/opencode/chat.go b/internal/opencode/chat.go index 781880a6..c33c8dfb 100644 --- a/internal/opencode/chat.go +++ b/internal/opencode/chat.go @@ -400,6 +400,83 @@ func (c *Chat) Sessions(ctx context.Context) ([]protocol.ChatSession, error) { return decodeChatSessions(data) } +// Automations reads the documented OpenCode experimental schedule surface. The +// endpoint is session-scoped by query parameter; the decoder still requires an +// exact sessionID match before counting anything. The older serve backend has +// no schedule API, so it reports unavailable without making a guessed request. +func (c *Chat) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) { + info := protocol.ChatAutomationInfo{SessionID: sessionID, Provider: "opencode"} + if !ValidSessionID(sessionID) { + return info, fmt.Errorf("invalid OpenCode session id") + } + if c == nil || c.conn == nil || c.conn.Backend == "v1" { + info.Status = protocol.ChatAutomationUnavailable + info.Reason = "this OpenCode backend does not expose the experimental schedule read API" + return info, nil + } + readCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + data, err := c.call(readCtx, "get", "/api/experimental/schedule?sessionID="+url.QueryEscape(sessionID), nil) + if err != nil { + if strings.Contains(err.Error(), "HTTP 404") || strings.Contains(err.Error(), "HTTP 405") { + info.Status = protocol.ChatAutomationUnavailable + info.Reason = "this OpenCode endpoint does not expose the experimental schedule read API" + return info, nil + } + return info, err + } + entries, err := decodeScheduleInfos(data) + if err != nil { + return info, err + } + count := 0 + for _, entry := range entries { + if entry.SessionID == sessionID && entry.Status == "active" { + count++ + } + } + info.Status = protocol.ChatAutomationSupported + info.ActiveCount = &count + return info, nil +} + +type scheduleInfo struct { + SessionID string `json:"sessionID"` + Status string `json:"status"` +} + +// decodeScheduleInfos accepts the documented array and the API's common data +// envelope, but rejects null/malformed bodies so a bad response never becomes a +// false empty count. +func decodeScheduleInfos(data []byte) ([]scheduleInfo, error) { + var entries []scheduleInfo + if err := json.Unmarshal(data, &entries); err == nil && entries != nil { + if err := validateScheduleInfos(entries); err != nil { + return nil, err + } + return entries, nil + } + var envelope struct { + Data []scheduleInfo `json:"data"` + } + if err := json.Unmarshal(data, &envelope); err != nil || envelope.Data == nil { + return nil, fmt.Errorf("invalid OpenCode schedule response") + } + if err := validateScheduleInfos(envelope.Data); err != nil { + return nil, err + } + return envelope.Data, nil +} + +func validateScheduleInfos(entries []scheduleInfo) error { + for _, entry := range entries { + if entry.SessionID == "" || entry.Status == "" { + return fmt.Errorf("invalid OpenCode schedule response") + } + } + return nil +} + // Create creates one OpenCode session in the given directory, mirroring the // verified V2 shape POST /api/session {"title":...,"location":{"directory":...}}. // It deliberately sends no model or permission override here: the endpoint's own diff --git a/internal/opencode/chat_automations_test.go b/internal/opencode/chat_automations_test.go new file mode 100644 index 00000000..b5cedc7c --- /dev/null +++ b/internal/opencode/chat_automations_test.go @@ -0,0 +1,51 @@ +package opencode + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestDecodeScheduleInfos(t *testing.T) { + tests := []struct { + name string + raw string + want int + }{ + {name: "array", raw: `[{"sessionID":"ses_a","status":"active"},{"sessionID":"ses_b","status":"done"}]`, want: 2}, + {name: "data envelope", raw: `{"data":[{"sessionID":"ses_a","status":"active"}]}`, want: 1}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + got, err := decodeScheduleInfos([]byte(test.raw)) + if err != nil || len(got) != test.want { + t.Fatalf("decodeScheduleInfos = %#v, %v", got, err) + } + }) + } +} + +func TestDecodeScheduleInfosRejectsMalformedOrNull(t *testing.T) { + for _, raw := range []string{`{}`, `null`, `not-json`, `[{"status":"active"}]`} { + if _, err := decodeScheduleInfos([]byte(raw)); err == nil { + t.Fatalf("decodeScheduleInfos(%q) accepted malformed response", raw) + } + } +} + +func TestChatAutomationsReadsOnlyActiveSessionSchedules(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/experimental/schedule" || r.URL.Query().Get("sessionID") != "ses_a" { + t.Fatalf("schedule request = %s?%s", r.URL.Path, r.URL.RawQuery) + } + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"sessionID":"ses_a","status":"active"},{"sessionID":"ses_a","status":"paused"},{"sessionID":"ses_b","status":"active"}]}`)) + })) + defer server.Close() + + info, err := NewChat(&Connection{Backend: "v2", URL: server.URL}).Automations(context.Background(), "ses_a") + if err != nil || info.Status != "supported" || info.ActiveCount == nil || *info.ActiveCount != 1 { + t.Fatalf("Automations = %+v, %v", info, err) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index 797e36b6..d172b420 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -126,6 +126,10 @@ const ( // carries ChatAttachmentImageContent. Only regular image files inside the // server's private chat attachment store are served. ChatAttachmentImage = "chat_attachment_image" + // ChatAutomations reads provider-owned scheduled work for one operator chat. + // It is deliberately read-only; providers that cannot authoritatively expose + // this information return an unavailable status instead of an empty count. + ChatAutomations = "chat_automations" // ChatEvent and ChatPermission are the server-pushed frames; they are the // only types the server sends without a matching request. ChatEvent = "chat_event" @@ -141,6 +145,22 @@ const ( ChatPermission = "chat_permission" ) +const ( + ChatAutomationSupported = "supported" + ChatAutomationUnavailable = "unavailable" +) + +// ChatAutomationInfo is the bounded, per-session scheduled-work snapshot. A +// nil ActiveCount means the provider could not authoritatively report a count; +// zero is reserved for a supported provider with no active schedules. +type ChatAutomationInfo struct { + SessionID string `json:"session_id"` + Provider string `json:"provider"` + Status string `json:"status"` + ActiveCount *int `json:"active_count,omitempty"` + Reason string `json:"reason,omitempty"` +} + // Content part types carried by ChatPart.Type and ChatEvent.Kind. const ( ChatPartText = "text" diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 19a4b911..00e21d5f 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -270,6 +270,9 @@ type Message struct { // ChatAttachmentImage its reply. ChatAttachmentImageRequest *ChatAttachmentImageRequest `json:"chat_attachment_image_request,omitempty"` ChatAttachmentImage *ChatAttachmentImageContent `json:"chat_attachment_image,omitempty"` + // ChatAutomations is the provider-owned scheduled-work readback for one + // operator session. ActiveCount is omitted when the count is unknown. + ChatAutomations *ChatAutomationInfo `json:"chat_automations,omitempty"` // RunEvent is the server-pushed run state delta (see runevents.go) and // RunIDs the optional subscribe scope, so a client asks for the runs it // displays. Both are optional so older peers ignore them. diff --git a/internal/server/chat.go b/internal/server/chat.go index d6948f3e..dc3e0eb9 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -85,6 +85,13 @@ type chatShellOutputReader interface { ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) } +// chatAutomationReader is optional so every broker and test fake does not need +// to grow a scheduler-shaped interface. Implementations must read only +// provider-owned, session-scoped metadata and return unavailable explicitly. +type chatAutomationReader interface { + Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) +} + // chatShellReleaser is implemented by brokers that retain verified shell ids for // attributing exit events. The hub calls it only after the last observer leaves // a room; a later attach obtains a fresh authoritative snapshot. @@ -251,6 +258,9 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker case protocol.ChatAttachmentImage: handleChatAttachmentImage(request, broker, write) return true + case protocol.ChatAutomations: + handleChatAutomations(ctx, request, broker, registry, write) + return true } return false } diff --git a/internal/server/chat_automations.go b/internal/server/chat_automations.go new file mode 100644 index 00000000..0cf41478 --- /dev/null +++ b/internal/server/chat_automations.go @@ -0,0 +1,64 @@ +package server + +import ( + "context" + "fmt" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func validChatAutomationInfo(info protocol.ChatAutomationInfo, sessionID string) error { + if info.SessionID != "" && info.SessionID != sessionID { + return fmt.Errorf("provider returned automation metadata for another session") + } + if info.Status != protocol.ChatAutomationSupported && info.Status != protocol.ChatAutomationUnavailable { + return fmt.Errorf("provider returned an invalid automation status") + } + if info.ActiveCount != nil && *info.ActiveCount < 0 { + return fmt.Errorf("provider returned a negative automation count") + } + if info.Status == protocol.ChatAutomationUnavailable && info.ActiveCount != nil { + return fmt.Errorf("unavailable automation metadata must not include a count") + } + if info.Status == protocol.ChatAutomationSupported && info.ActiveCount == nil { + return fmt.Errorf("supported automation metadata is missing a count") + } + return nil +} + +func handleChatAutomations(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 + } + query := request.ChatQuery + if query == nil || !validChatSessionID(query.SessionID) { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a valid chat session id is required"}) + return + } + if err := operatorChatSession(ctx, registry, query.SessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) + return + } + reader, ok := broker.(chatAutomationReader) + if !ok { + _ = write(protocol.Message{Type: protocol.ChatAutomations, ID: request.ID, ChatAutomations: &protocol.ChatAutomationInfo{ + SessionID: query.SessionID, Status: protocol.ChatAutomationUnavailable, + Reason: "this chat provider has no authoritative scheduled-work read API", + }}) + return + } + info, err := reader.Automations(ctx, query.SessionID) + if err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: fmt.Sprintf("read chat automations: %v", err)}) + return + } + if info.SessionID == "" { + info.SessionID = query.SessionID + } + if err := validChatAutomationInfo(info, query.SessionID); err != nil { + _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "read chat automations: " + err.Error()}) + return + } + _ = write(protocol.Message{Type: protocol.ChatAutomations, ID: request.ID, ChatAutomations: &info}) +} diff --git a/internal/server/chat_automations_test.go b/internal/server/chat_automations_test.go new file mode 100644 index 00000000..478c7751 --- /dev/null +++ b/internal/server/chat_automations_test.go @@ -0,0 +1,90 @@ +package server + +import ( + "context" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +type automationChat struct { + *fakeChat + info protocol.ChatAutomationInfo + readCalled int +} + +func (c *automationChat) Automations(context.Context, string) (protocol.ChatAutomationInfo, error) { + c.readCalled++ + return c.info, nil +} + +func automationReply(t *testing.T, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message { + t.Helper() + var reply protocol.Message + handleChatAutomations(context.Background(), request, broker, registry, func(message protocol.Message) error { + reply = message + return nil + }) + return reply +} + +func TestChatAutomationsRequiresOwnedSession(t *testing.T) { + store := newOperatorStore(t) + if err := store.RecordOperatorSession(context.Background(), "ses_owned", t.TempDir(), "owned", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + broker := &automationChat{fakeChat: scriptedChat(), info: protocol.ChatAutomationInfo{Status: protocol.ChatAutomationSupported}} + reply := automationReply(t, protocol.Message{Type: protocol.ChatAutomations, ID: "a1", ChatQuery: &protocol.ChatQuery{SessionID: "ses_foreign"}}, broker, store) + if reply.Type != protocol.Error || reply.Error != "operator session is not available" { + t.Fatalf("foreign automation read = %+v", reply) + } + if broker.readCalled != 0 { + t.Fatal("provider read happened before ownership check") + } +} + +func TestChatAutomationsDistinguishesUnavailableFromEmpty(t *testing.T) { + store := newOperatorStore(t) + if err := store.RecordOperatorSession(context.Background(), "ses_empty", t.TempDir(), "empty", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + request := protocol.Message{Type: protocol.ChatAutomations, ID: "a2", ChatQuery: &protocol.ChatQuery{SessionID: "ses_empty"}} + unsupported := automationReply(t, request, scriptedChat(), store) + if unsupported.Type != protocol.ChatAutomations || unsupported.ChatAutomations == nil || unsupported.ChatAutomations.Status != protocol.ChatAutomationUnavailable || unsupported.ChatAutomations.ActiveCount != nil { + t.Fatalf("unsupported automation read = %+v", unsupported) + } + empty := 0 + broker := &automationChat{fakeChat: scriptedChat(), info: protocol.ChatAutomationInfo{SessionID: "ses_empty", Provider: "opencode", Status: protocol.ChatAutomationSupported, ActiveCount: &empty}} + supported := automationReply(t, request, broker, store) + if supported.Type != protocol.ChatAutomations || supported.ChatAutomations == nil || supported.ChatAutomations.Status != protocol.ChatAutomationSupported || supported.ChatAutomations.ActiveCount == nil || *supported.ChatAutomations.ActiveCount != 0 { + t.Fatalf("empty automation read = %+v", supported) + } +} + +func TestChatAutomationsRejectsMalformedSessionBounds(t *testing.T) { + broker := &automationChat{fakeChat: scriptedChat()} + for _, query := range []*protocol.ChatQuery{ + nil, + {SessionID: ""}, + {SessionID: "not-a-session"}, + {SessionID: "ses_" + string(make([]byte, 201))}, + } { + reply := automationReply(t, protocol.Message{Type: protocol.ChatAutomations, ID: "a3", ChatQuery: query}, broker, nil) + if reply.Type != protocol.Error { + t.Fatalf("malformed query %+v returned %+v", query, reply) + } + } +} + +func TestChatAutomationsRejectsMalformedProviderMetadata(t *testing.T) { + store := newOperatorStore(t) + if err := store.RecordOperatorSession(context.Background(), "ses_bad", t.TempDir(), "bad", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + count := -1 + broker := &automationChat{fakeChat: scriptedChat(), info: protocol.ChatAutomationInfo{SessionID: "ses_bad", Status: protocol.ChatAutomationSupported, ActiveCount: &count}} + reply := automationReply(t, protocol.Message{Type: protocol.ChatAutomations, ID: "a4", ChatQuery: &protocol.ChatQuery{SessionID: "ses_bad"}}, broker, store) + if reply.Type != protocol.Error { + t.Fatalf("malformed provider metadata = %+v", reply) + } +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 47143590..82548df6 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -332,6 +332,21 @@ func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBrok return adapter, nil } +// Automations routes the optional readback capability without adding it to the +// base broker contract. The session's registry-selected provider remains the +// ownership boundary; no provider-wide or cwd-wide schedule list is consulted. +func (m *chatManager) Automations(ctx context.Context, sessionID string) (protocol.ChatAutomationInfo, error) { + adapter, err := m.brokerFor(ctx, sessionID) + if err != nil { + return protocol.ChatAutomationInfo{SessionID: sessionID, Status: protocol.ChatAutomationUnavailable, Reason: err.Error()}, nil + } + reader, ok := adapter.(chatAutomationReader) + if !ok { + return protocol.ChatAutomationInfo{SessionID: sessionID, Provider: m.backendFor(ctx, sessionID), Status: protocol.ChatAutomationUnavailable, Reason: "this chat provider has no authoritative scheduled-work read API"}, nil + } + return reader.Automations(ctx, sessionID) +} + // chatTitleSetter is a harness that names its own sessions from the operator's // chat title (Claude Code passes it as --name on the next spawn). SetTitle // records the title in memory only and does no I/O.