| 1 | package control |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "log/slog" |
| 7 | "sync" |
| 8 | |
| 9 | "reasonix/internal/event" |
| 10 | "reasonix/internal/eventwire" |
| 11 | "reasonix/internal/evidence" |
| 12 | "reasonix/internal/extension" |
| 13 | "reasonix/internal/extension/dispatch" |
| 14 | "reasonix/internal/sessioninbox" |
| 15 | ) |
| 16 | |
| 17 | // Extension dispatch wiring (stage 6b1). Nil dispatcher is a no-op. |
| 18 | // SessionPayload carries only path + phase; the host owns file decisions. |
| 19 | |
| 20 | // extensionSessionEvent broadcasts one session.* point fire-and-forget. |
| 21 | func (c *Controller) extensionSessionEvent(point extension.InterceptorPoint, phase, path string) { |
| 22 | c.extensionSessionPayloadEvent(point, dispatch.SessionPayload{SessionPath: path, Phase: phase}) |
| 23 | } |
| 24 | |
| 25 | // loadExtensions returns the dispatcher under c.mu (safe vs ReplaceExtensions). |
| 26 | func (c *Controller) loadExtensions() *dispatch.Dispatcher { |
| 27 | if c == nil { |
| 28 | return nil |
| 29 | } |
| 30 | c.mu.Lock() |
| 31 | d := c.extensions |
| 32 | c.mu.Unlock() |
| 33 | return d |
| 34 | } |
| 35 | |
| 36 | // interceptInputReceive runs input.receive; blocked surfaces a notice. |
| 37 | func (c *Controller) interceptInputReceive(ctx context.Context, input string) (text string, blocked bool, err error) { |
| 38 | d := c.loadExtensions() |
| 39 | if d == nil { |
| 40 | return input, false, nil |
| 41 | } |
| 42 | payload := dispatch.InputPayload{Text: input} |
| 43 | result, err := d.Intercept(ctx, extension.PointInputReceive, &payload) |
| 44 | if err != nil { |
| 45 | return input, false, err |
| 46 | } |
| 47 | if result.Blocked { |
| 48 | c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "Turn blocked by an extension.", Detail: result.BlockReason}) |
| 49 | return input, true, nil |
| 50 | } |
| 51 | return payload.Text, false, nil |
| 52 | } |
| 53 | |
| 54 | // extensionSessionPayloadEvent broadcasts one session.* point with an |
| 55 | // already-settled (possibly owner-adjusted) payload. |
| 56 | func (c *Controller) extensionSessionPayloadEvent(point extension.InterceptorPoint, payload dispatch.SessionPayload) { |
| 57 | d := c.loadExtensions() |
| 58 | if d == nil { |
| 59 | return |
| 60 | } |
| 61 | d.Event(point, payload) |
| 62 | } |
| 63 | |
| 64 | // extensionSessionStrategy runs only the strategy half of a session.* point |
| 65 | // and returns the final payload for a later event broadcast. Callers that |
| 66 | // must separate the ruling from the observation (session.save rules on the |
| 67 | // impending write but observes the completed one) use this half directly. |
| 68 | func (c *Controller) extensionSessionStrategy(ctx context.Context, point extension.InterceptorPoint, phase, path string) (dispatch.SessionPayload, error) { |
| 69 | payload := dispatch.SessionPayload{SessionPath: path, Phase: phase} |
| 70 | d := c.loadExtensions() |
| 71 | if d == nil { |
| 72 | return payload, nil |
| 73 | } |
| 74 | if _, owned := d.Strategy(extension.SlotSessionPolicy); owned { |
| 75 | if err := d.RunStrategy(ctx, extension.SlotSessionPolicy, point, &payload); err != nil { |
| 76 | return payload, err |
| 77 | } |
| 78 | } |
| 79 | return payload, nil |
| 80 | } |
| 81 | |
| 82 | // extensionSessionPhase runs the session_policy strategy at one session.* |
| 83 | // point (load/save/rotate) when the slot has an owner, then broadcasts the |
| 84 | // event with the final (possibly owner-adjusted) payload. The strategy error |
| 85 | // is returned to the caller: at session.save and session.rotate it is fatal |
| 86 | // to the operation (the owner is required-class by definition); at |
| 87 | // session.load the caller degrades to a warning because Controller.Resume has |
| 88 | // no failure channel this stage. |
| 89 | func (c *Controller) extensionSessionPhase(ctx context.Context, point extension.InterceptorPoint, phase, path string) error { |
| 90 | if c.loadExtensions() == nil { |
| 91 | return nil |
| 92 | } |
| 93 | payload, err := c.extensionSessionStrategy(ctx, point, phase, path) |
| 94 | if err != nil { |
| 95 | return err |
| 96 | } |
| 97 | c.extensionSessionPayloadEvent(point, payload) |
| 98 | return nil |
| 99 | } |
| 100 | |
| 101 | // extensionWarn surfaces a required-class extension failure to the user and |
| 102 | // the log. It goes through the ordinary sink (the failure itself is a |
| 103 | // frontend event like any other). |
| 104 | func (c *Controller) extensionWarn(what string, err error) { |
| 105 | slog.Warn("controller: extension "+what, "err", err) |
| 106 | c.sink.Emit(event.Event{Kind: event.Notice, Level: event.LevelWarn, Text: "Extension " + what + ": " + err.Error()}) |
| 107 | } |
| 108 | |
| 109 | // frontendEventSink wraps the controller's sink when a dispatcher is |
| 110 | // installed: every event is observed at frontend.event (fire-and-forget) |
| 111 | // and, when the frontend_events slot has an owner, ruled on first — a |
| 112 | // replacement may rewrite Text/Detail but never the Kind. |
| 113 | type frontendEventSink struct { |
| 114 | inner event.Sink |
| 115 | d *dispatch.Dispatcher |
| 116 | |
| 117 | warnMu sync.Mutex |
| 118 | warned map[string]bool |
| 119 | } |
| 120 | |
| 121 | var _ event.OptionalSinkCapabilities = (*frontendEventSink)(nil) |
| 122 | |
| 123 | func newFrontendEventSink(inner event.Sink, d *dispatch.Dispatcher) *frontendEventSink { |
| 124 | return &frontendEventSink{inner: inner, d: d, warned: map[string]bool{}} |
| 125 | } |
| 126 | |
| 127 | func (s *frontendEventSink) setDispatcher(d *dispatch.Dispatcher) { |
| 128 | if s == nil || d == nil { |
| 129 | return |
| 130 | } |
| 131 | s.warnMu.Lock() |
| 132 | s.d = d |
| 133 | s.warnMu.Unlock() |
| 134 | } |
| 135 | |
| 136 | // Emit observes and rules on one controller event before forwarding it. The |
| 137 | // strategy runs synchronously (the frontend_events owner is required-class): |
| 138 | // an explicit block ruling suppresses the event, but an owner malfunction |
| 139 | // (timeout, crash, contract violation) emits the original event with a |
| 140 | // warning — dropping ApprovalRequest/TurnDone-class events would hang the |
| 141 | // frontend's state machine, so only an affirmative block ruling may. |
| 142 | func (s *frontendEventSink) Emit(ev event.Event) { |
| 143 | name, ok := eventwire.KindName(ev.Kind) |
| 144 | if !ok { |
| 145 | s.inner.Emit(ev) |
| 146 | return |
| 147 | } |
| 148 | s.warnMu.Lock() |
| 149 | d := s.d |
| 150 | s.warnMu.Unlock() |
| 151 | payload := dispatch.FrontendEventPayload{Kind: name, Text: ev.Text, Detail: ev.Detail} |
| 152 | if _, owned := d.Strategy(extension.SlotFrontendEvents); owned { |
| 153 | before := payload |
| 154 | if err := d.RunStrategy(context.Background(), extension.SlotFrontendEvents, extension.PointFrontendEvent, &payload); err != nil { |
| 155 | var blockErr *dispatch.BlockError |
| 156 | if errors.As(err, &blockErr) { |
| 157 | s.warnOnce("block|"+blockErr.Plugin, "extension frontend event suppressed: "+blockErr.Error()) |
| 158 | return |
| 159 | } |
| 160 | s.warnOnce("failure|"+extensionFailurePlugin(err), "extension frontend event strategy failed; emitting the original event: "+err.Error()) |
| 161 | payload = before |
| 162 | } else if payload.Kind != before.Kind { |
| 163 | s.warnOnce("kind", "extension frontend event strategy tried to change the event kind; emitting the original event") |
| 164 | payload = before |
| 165 | } |
| 166 | } |
| 167 | // Observers see exactly what the frontend is about to receive. |
| 168 | s.d.Event(extension.PointFrontendEvent, payload) |
| 169 | ev.Text, ev.Detail = payload.Text, payload.Detail |
| 170 | s.inner.Emit(ev) |
| 171 | } |
| 172 | |
| 173 | func (s *frontendEventSink) InboxChanged(snap sessioninbox.InboxSnapshot) { |
| 174 | if s == nil { |
| 175 | return |
| 176 | } |
| 177 | notifyInboxChanged(s.inner, snap) |
| 178 | } |
| 179 | |
| 180 | // warnOnce logs msg at most once per key for the life of the sink. Warnings |
| 181 | // stay on the log: routing them back through the sink would re-enter the |
| 182 | // strategy path they describe. |
| 183 | func (s *frontendEventSink) warnOnce(key, msg string) { |
| 184 | s.warnMu.Lock() |
| 185 | if s.warned[key] { |
| 186 | s.warnMu.Unlock() |
| 187 | return |
| 188 | } |
| 189 | s.warned[key] = true |
| 190 | s.warnMu.Unlock() |
| 191 | slog.Warn("controller: " + msg) |
| 192 | } |
| 193 | |
| 194 | // extensionFailurePlugin extracts the plugin ID from a dispatch error for |
| 195 | // warn-once keying. |
| 196 | func extensionFailurePlugin(err error) string { |
| 197 | var failureErr *dispatch.FailureError |
| 198 | if errors.As(err, &failureErr) { |
| 199 | return failureErr.Plugin |
| 200 | } |
| 201 | var violationErr *dispatch.ViolationError |
| 202 | if errors.As(err, &violationErr) { |
| 203 | return violationErr.Plugin |
| 204 | } |
| 205 | return "unknown" |
| 206 | } |
| 207 | |
| 208 | // The audit capabilities pass through untouched: extension rulings apply to |
| 209 | // user-facing events, never to the content-free telemetry channels — without |
| 210 | // these, enabling extensions severed every audit from the recorder. |
| 211 | |
| 212 | func (s *frontendEventSink) RecordReadinessAudit(a evidence.ReadinessAudit) { |
| 213 | event.RecordReadinessAudit(s.inner, a) |
| 214 | } |
| 215 | |
| 216 | func (s *frontendEventSink) RecordAnchorSafetyAudit(a event.AnchorSafetyAudit) { |
| 217 | event.RecordAnchorSafetyAudit(s.inner, a) |
| 218 | } |
| 219 | |
| 220 | func (s *frontendEventSink) RecordContractShadow(a event.ContractShadowAudit) { |
| 221 | event.RecordContractShadow(s.inner, a) |
| 222 | } |
| 223 | |
| 224 | func (s *frontendEventSink) RecordDelegationAudit(a evidence.DelegationAudit) { |
| 225 | event.RecordDelegationAudit(s.inner, a) |
| 226 | } |
| 227 | |
| 228 | func (s *frontendEventSink) RecordCompletionReport(a event.CompletionReportAudit) { |
| 229 | event.RecordCompletionReport(s.inner, a) |
| 230 | } |
| 231 | |
| 232 | func (s *frontendEventSink) RecordOutcomeProgress(sample evidence.OutcomeSample) { |
| 233 | event.RecordOutcomeProgress(s.inner, sample) |
| 234 | } |
| 235 | |
| 236 | func (s *frontendEventSink) RecordDelegationAdmission(a event.DelegationAdmissionAudit) { |
| 237 | event.RecordDelegationAdmission(s.inner, a) |
| 238 | } |
| 239 | |
| 240 | func (s *frontendEventSink) RecordMemoryRecall(a event.MemoryRecallAudit) { |
| 241 | event.RecordMemoryRecall(s.inner, a) |
| 242 | } |
| 243 | |
| 244 | func (s *frontendEventSink) RecordProtocolRecovery(a event.ProtocolRecoveryAudit) { |
| 245 | event.RecordProtocolRecovery(s.inner, a) |
| 246 | } |
| 247 | |
| 248 | func (s *frontendEventSink) RecordTurnCompletion() { |
| 249 | event.RecordTurnCompletion(s.inner) |
| 250 | } |
| 251 | |
| 252 | func (s *frontendEventSink) RecordWorkspaceMutation(m event.WorkspaceMutation) { |
| 253 | event.RecordWorkspaceMutation(s.inner, m) |
| 254 | } |
| 255 | |
| 256 | func (s *frontendEventSink) RecordRunBudget(sample event.RunBudgetSample) { |
| 257 | event.RecordRunBudget(s.inner, sample) |
| 258 | } |
| 259 | |
| 260 | func (s *frontendEventSink) RecordSubagentLifecycle(info event.SubagentLifecycleInfo) { |
| 261 | event.RecordSubagentLifecycle(s.inner, info) |
| 262 | } |
| 263 |